improve performance of package add/edit (don't pull up pricing info in add-on/supplem...
[freeside.git] / httemplate / edit / part_pkg.cgi
1 <% include( 'elements/edit.html',
2               'post_url'              => popurl(1).'process/part_pkg.cgi',
3               'name'                  => "Package definition",
4               'table'                 => 'part_pkg',
5
6               'agent_virt'            => 1,
7               'agent_null_right'      => $edit_global,
8               'agent_clone_extra_sql' => $agent_clone_extra_sql,
9               #'viewall_dir'           => 'browse',
10               'viewall_url'           => $p.'browse/part_pkg.cgi',
11               'html_init'             => include('/elements/init_overlib.html').
12                                          $javascript,
13               'html_bottom'           => $html_bottom,
14               'body_etc'              =>
15                 'onLoad="agent_changed(document.edit_topform.agentnum);
16                          hide_supp_pkgs()"',
17
18               'begin_callback'        => $begin_callback,
19               'end_callback'          => $end_callback,
20               'new_hashref_callback'  => $new_hashref_callback,
21               'new_object_callback'   => $new_object_callback,
22               'new_callback'          => $new_callback,
23               'clone_callback'        => $clone_callback,
24               'edit_callback'         => $edit_callback,
25               'error_callback'        => $error_callback,
26               'field_callback'        => $field_callback,
27
28               'onsubmit'              => 'confirm_submit',
29
30               'labels' => { 
31                             'pkgpart'          => 'Package Definition',
32                             'pkg'              => 'Package',
33                             %locale_field_labels,
34                             'comment'          => 'Comment (customer-hidden)',
35                             'classnum'         => 'Package class',
36                             'addon_classnum'   => 'Restrict additional orders to package class',
37                             'promo_code'       => 'Promotional code',
38                             'freq'             => 'Recurring fee frequency',
39                             'setuptax'         => 'Setup fee tax exempt',
40                             'recurtax'         => 'Recurring fee tax exempt',
41                             'taxclass'         => 'Tax class',
42                             'taxproduct_select'=> 'Tax products',
43                             'plan'             => 'Price plan',
44                             'disabled'         => 'Disable new orders',
45                             'disable_line_item_date_ranges' => 'Disable line item date ranges',
46                             'setup_cost'       => 'Setup cost',
47                             'recur_cost'       => 'Recur cost',
48                             'pay_weight'       => 'Payment weight',
49                             'credit_weight'    => 'Credit weight',
50                             'agent_pkgpartid'  => 'External ID',
51                             'agentnum'         => 'Agent',
52                             'setup_fee'        => 'Setup fee',
53                             'setup_show_zero'  => 'Show zero setup',
54                             'recur_fee'        => 'Recurring fee',
55                             'recur_show_zero'  => 'Show zero recurring',
56                             'discountnum'      => 'Offer discounts for longer terms',
57                             'bill_dst_pkgpart' => 'Include line item(s) from package',
58                             'svc_dst_pkgpart'  => 'Include services of package',
59                             'supp_dst_pkgpart' => 'When ordering package, also order',
60                             'report_option'    => 'Report classes',
61                             'fcc_ds0s'         => 'Voice-grade equivalents',
62                             'fcc_voip_class'   => 'Category',
63                             'delay_start'      => 'Default delay (days)',
64                           },
65
66               'fields' => [
67                             { field=>'clone',  type=>'hidden',
68                               curr_value_callback =>
69                                 sub { shift->param('clone') },
70                             },
71                             { field=>'pkgnum', type=>'hidden',
72                               curr_value_callback =>
73                                 sub { shift->param('pkgnum') },
74                             },
75
76                             { field=>'custom',  type=>'hidden' },
77                             { field=>'family_pkgpart', type=>'hidden' },
78                             { field=>'successor', type=>'hidden' },
79
80                             { type => 'columnstart' },
81                             
82                               { field     => 'pkg',
83                                 type      => 'text',
84                                 size      => 40, #32
85                                 maxlength => 50,
86                               },
87                               #@locale_fields,
88                               {field=>'comment',  type=>'text', size=>40 }, #32
89                               { field         => 'agentnum',
90                                 type          => 'select-agent',
91                                 disable_empty => ! $acl_edit_global,
92                                 empty_label   => '(global)',
93                                 onchange      => 'agent_changed',
94                               },
95                               {field=>'classnum', type=>'select-pkg_class' },
96                               ( $conf->exists('pkg-addon_classnum')
97                                   ? ( { field=>'addon_classnum',
98                                         type =>'select-pkg_class',
99                                       }
100                                     )
101                                    : ()
102                               ),
103                               {field=>'disabled', type=>$disabled_type, value=>'Y'},
104                               {field=>'disable_line_item_date_ranges', type=>$disabled_type, value=>'Y'},
105
106                               { type     => 'tablebreak-tr-title',
107                                 value    => 'Pricing', #better name?
108                               },
109                               { field    => 'plan',
110                                 type     => 'selectlayers-select',
111                                 options  => [ keys %plan_labels ],
112                                 labels   => \%plan_labels,
113                                 onchange => 'aux_planchanged(what);',
114                               },
115                               { field    => 'setup_fee',
116                                 type     => 'money',
117                                 onchange => 'setup_changed',
118                               },
119                               { field    => 'setup_show_zero',
120                                 type     => 'checkbox',
121                                 value    => 'Y',
122                                 disabled => sub { $setup_show_zero_disabled },
123                               },
124                               { field    => 'freq',
125                                 type     => 'part_pkg_freq',
126                                 onchange => 'freq_changed',
127                               },
128                               { field    => 'recur_fee',
129                                 type     => 'money',
130                                 disabled => sub { $recur_disabled },
131                                 onchange => 'recur_changed',
132                               },
133
134                               { field    => 'recur_show_zero',
135                                 type     => 'checkbox',
136                                 value    => 'Y',
137                                 disabled => sub { $recur_show_zero_disabled },
138                               },
139
140                               #price plan
141                               #setup fee
142                               #recurring frequency
143                               #recurring fee (auto-disable)
144
145                             { type => 'columnnext' },
146
147                               {type=>'justtitle', value=>'Taxation' },
148                               {field=>'setuptax', type=>'checkbox', value=>'Y'},
149                               {field=>'recurtax', type=>'checkbox', value=>'Y'},
150                               {field=>'taxclass', type=>'select-taxclass' },
151                               { field => 'taxproductnums',
152                                 type  => 'hidden',
153                                 value => join(',', @taxproductnums),
154                               },
155                               { field => 'taxproduct_select',
156                                 type  => 'selectlayers',
157                                 options => [ '(default)', @taxproductnums ],
158                                 curr_value => '(default)',
159                                 labels  => { ( '(default)' => '(default)' ),
160                                              map {($_=>$usage_class{$_})}
161                                              @taxproductnums
162                                            },
163                                 layer_fields => \%taxproduct_fields,
164                                 layer_values_callback => $taxproduct_values,
165                                 layers_only  =>   !$taxproducts,
166                                 cell_style   => ( !$taxproducts
167                                                   ? 'display:none'
168                                                   : ''
169                                                 ),
170                               },
171
172                               { type  => 'tablebreak-tr-title',
173                                 value => 'Promotions', #better name?
174                               },
175                               { field=>'promo_code', type=>'text', size=>15 },
176
177                               { type  => 'tablebreak-tr-title',
178                                 value => 'Cost tracking', #better name?
179                               },
180
181                               ( $curuser->access_right('Edit package definition costs')
182                                 ? ( { field=>'setup_cost', type=>'money', },
183                                     { field=>'recur_cost', type=>'money', },
184                                   )
185                                 : ( { field=>'setup_cost', type=>'fixed', },
186                                     { field=>'recur_cost', type=>'fixed', },
187                                   )
188                               ),
189
190                               ( $conf->exists('part_pkg-delay_start')
191                                 ? ( { type  => 'tablebreak-tr-title',
192                                       value => 'Delayed start',
193                                     },
194                                     { field => 'delay_start',
195                                       type => 'text', size => 6 },
196                                   )
197                                 : ()
198                               ),
199
200                             { type => 'columnnext' },
201
202                               { field    => 'agent_type',
203                                 type     => 'select-agent_types',
204                                 disabled => ! $acl_edit_global,
205                                 curr_value_callback => sub {
206                                   my($cgi, $object, $field) = @_;
207                                   #in the other callbacks..?  hmm.
208                                   \@agent_type;
209                                 },
210                               },
211
212                       { type  => 'tablebreak-tr-title',
213                         value => 'External Links', #better name?
214                       },
215                       { field=>'agent_pkgpartid', type=>'text', size=>21 },
216
217                       { type  => 'tablebreak-tr-title',
218                         value => 'Line-item revenue recogition', #better name?
219                       },
220                       { field=>'pay_weight',    type=>'text', size=>6 },
221                       { field=>'credit_weight', type=>'text', size=>6 },
222                       
223                         ( $conf->exists('cust_pkg-show_fcc_voice_grade_equivalent')
224                                 ? ( 
225                                     { type  => 'tablebreak-tr-title',
226                                       value => 'FCC Form 477 information',
227                                     },
228                                     { field=>'fcc_voip_class',
229                                       type=>'select-voip_class',
230                                     },
231                                     { field=>'fcc_ds0s', type=>'text', size=>6 },
232                                   )
233                                  : ()
234                               ),
235
236                             { type => 'columnend' },
237
238                             { 'type'  => $report_option ? 'tablebreak-tr-title'
239                                                         : 'hidden',
240                               'value' => 'Optional report classes',
241                               'field' => 'census_title',
242                             },
243                             { 'field'    => 'report_option',
244                               'type'     => $report_option ? 'select-table'
245                                                            : 'hidden',
246                               'table'    => 'part_pkg_report_option',
247                               'name_col' => 'name',
248                               'hashref'  => { 'disabled' => '' },
249                               'multiple' => 1,
250                             },
251
252                             { 'type'    => 'tablebreak-tr-title',
253                               'value'   => 'Term discounts',
254                             },
255                             { 'field'      => 'discountnum',
256                               'type'       => 'select-table',
257                               'table'      => 'discount',
258                               'name_col'   => 'name',
259                               'hashref'    => { %$discountnum_hashref },
260                               #'extra_sql'  => 'AND (months IS NOT NULL OR months != 0)',
261                               'empty_label'=> 'Select discount',
262                               'm2_label'   => 'Offer discounts for longer terms',
263                               'm2m_method' => 'part_pkg_discount',
264                               'm2m_dstcol' => 'discountnum',
265                               'm2_error_callback' => $discount_error_callback,
266                             },
267
268                             { 'type'    => 'tablebreak-tr-title',
269                               'value'   => 'Pricing add-ons',
270                               'colspan' => 4,
271                             },
272                             { 'field'      => 'bill_dst_pkgpart',
273                               'type'       => 'select-part_pkg',
274                               'extra_sql'  => sub { $pkgpart
275                                                      ? "AND pkgpart != $pkgpart"
276                                                      : ''
277                                                   },
278 +                             'label_callback' => sub { shift->pkg_comment_only },
279                               'm2_label'   => 'Include line item(s) from package',
280                               'm2m_method' => 'bill_part_pkg_link',
281                               'm2m_dstcol' => 'dst_pkgpart',
282                               'm2_error_callback' =>
283                                 &{$m2_error_callback_maker}('bill'),
284                               'm2_fields' => [ { 'field' => 'hidden',
285                                                  'type'  => 'checkbox',
286                                                  'value' => 'Y',
287                                                  'curr_value' => '',
288                                                  'label' => 'Bundle',
289                                                },
290                                              ],
291                             },
292
293                             { type  => 'tablebreak-tr-title',
294                               value => 'Services',
295                             },
296                             { type => 'pkg_svc', },
297
298                             { 'field'      => 'svc_dst_pkgpart',
299                               'label'      => 'Also include services from package: ',
300                               'type'       => 'select-part_pkg',
301                               'extra_sql'  => sub { $pkgpart
302                                                      ? "AND pkgpart != $pkgpart"
303                                                      : ''
304                                                   },
305 +                             'label_callback' => sub { shift->pkg_comment_only },
306                               'm2_label'   => 'Include services of package: ',
307                               'm2m_method' => 'svc_part_pkg_link',
308                               'm2m_dstcol' => 'dst_pkgpart',
309                               'm2_error_callback' =>
310                                 &{$m2_error_callback_maker}('svc'),
311                             },
312
313                             { 'type'    => 'tablebreak-tr-title',
314                               'value'   => 'Supplemental packages',
315                               'colspan' => '4',
316                               'include_opt_callback' => sub {
317                                  'id' => 'show_supp_pkgs',
318                               },
319                             },
320                             { 'field'       => 'supp_dst_pkgpart',
321                               'type'        => 'select-part_pkg',
322 +                             'label_callback' => sub { shift->pkg_comment_only },
323                               'm2_label'    => 'When ordering package, also order',
324                               'm2m_method'  => 'supp_part_pkg_link',
325                               'm2m_dstcol'  => 'dst_pkgpart',
326                               'm2_error_callback' =>
327                                 &{$m2_error_callback_maker}('supp'),
328                             },
329
330                             { type  => 'tablebreak-tr-title',
331                               value => 'Price plan options',
332                             },
333
334                           ],
335
336            )
337 %>
338 <%init>
339
340 my $curuser = $FS::CurrentUser::CurrentUser;
341
342 my $edit_global = 'Edit global package definitions';
343 my $acl_edit        = $curuser->access_right('Edit package definitions');
344 my $acl_edit_global = $curuser->access_right($edit_global);
345
346 my $acl_edit_either = $acl_edit || $acl_edit_global;
347
348 my $begin_callback = sub {
349   my( $cgi, $fields, $opt ) = @_;
350   die "access denied"
351     unless $acl_edit_either
352         || ( $cgi->param('pkgnum')
353              && $curuser->access_right('Customize customer package')
354            );
355 };
356
357 my $disabled_type = $acl_edit_either ? 'checkbox' : 'hidden';
358
359 #arg.  access rights for cloning are Hard.
360 # on the one hand we don't really want cloning (customizing a package) to fail 
361 #  for want of finding the source package in normal usage
362 # on the other hand, we don't want people using the clone link to be able to
363 #  see 
364 my $agent_clone_extra_sql = 
365   ' ( '. FS::part_pkg->curuser_pkgs_sql.
366   "   OR ( part_pkg.custom = 'Y' ) ".
367   ' ) ';
368
369 my $conf = new FS::Conf;
370 my $taxproducts = $conf->exists('enable_taxproducts');
371
372 my @locales = grep { ! /^en_/i } $conf->config('available-locales'); #should filter from the default locale lang instead of en_
373 my %locale_labels =  map {
374   ( $_ => 'Package -- '. FS::Locales->description($_) )
375 } @locales;
376 @locales = 
377   sort { $locale_labels{$a} cmp $locale_labels{$b} }
378     @locales;
379
380 my $n = 0;
381 my %locale_field_labels = (
382   map {
383         ( 'pkgpartmsgnum'. $n++. '_pkg' => $locale_labels{$_} );
384       }
385     @locales
386 );
387
388 my $sth = dbh->prepare("SELECT COUNT(*) FROM part_pkg_report_option".
389                        "  WHERE disabled IS NULL OR disabled = ''  ")
390   or die dbh->errstr;
391 $sth->execute or die $sth->errstr;
392 my $report_option = $sth->fetchrow_arrayref->[0];
393
394 #XXX
395 # - tr-part_pkg_freq: month_increments_only (from price plans)
396 # - test cloning
397 # - test errors cloning
398 # - test custom pricing
399 # - move the selectlayer divs away from lame layer_callback
400
401 #my ($query) = $cgi->keywords;
402 #
403 #my $part_pkg = '';
404
405 my @agent_type = ();
406 my %tax_override = ();
407
408 my %taxproductnums = map { ($_->classnum => 1) }
409                      qsearch('usage_class', { 'disabled' => '' });
410 my @taxproductnums = ( qw( setup recur ), sort (keys %taxproductnums) );
411
412 my %options = ();
413 my $recur_disabled = 1;
414 my $setup_show_zero_disabled = 0;
415 my $recur_show_zero_disabled = 1;
416
417 my $pkgpart = '';
418
419 my $splice_locale_fields = sub {
420   my( $fields, $pkey_value_callback, $pkg_value_callback ) = @_;
421
422   my $n = 0;
423   my @locale_fields = (
424     map { 
425           my $pkey_value= $pkey_value_callback ? &$pkey_value_callback($_) : '';
426           my $pkg_value = $pkg_value_callback
427                             ? $pkg_value_callback eq 'cgiparam'
428                                 ? $cgi->param('pkgpartmsgnum'. $n. '_pkg')
429                                 : &$pkg_value_callback($_)
430                             : '';
431           (
432             { field     => 'pkgpartmsgnum'. $n,
433               type      => 'hidden',
434               value     => $pkey_value,
435             },
436             { field     => 'pkgpartmsgnum'. $n. '_locale',
437               type      => 'hidden',
438               value     => $_,
439             },
440             { field     => 'pkgpartmsgnum'. $n++. '_pkg',
441               type      => 'text',
442               size      => 40,
443               #maxlength => 50,
444               value     => $pkg_value,
445             },
446           );
447   
448         }
449       @locales
450   );
451   splice(@$fields, 7, 0, @locale_fields); #XXX 7 is arbitrary above
452
453 };
454
455 my $error_callback = sub {
456   my($cgi, $object, $fields, $opt ) = @_;
457
458   (@agent_type) = $cgi->param('agent_type');
459
460   $opt->{action} = 'Custom' if $cgi->param('pkgnum');
461
462   $setup_show_zero_disabled = ($cgi->param('setup_fee') > 0) ? 1 : 0;
463
464   $recur_disabled = $cgi->param('freq') ? 0 : 1;
465   $recur_show_zero_disabled =
466     $cgi->param('freq')
467       ? $cgi->param('recur_fee') > 0 ? 1 : 0
468       : 1;
469
470   foreach ($cgi->param) {
471     /^usage_taxproductnum_(\d+)$/ && ($taxproductnums{$1} = 1);
472   }
473   $tax_override{''} = $cgi->param('tax_override');
474   $tax_override{$_} = $cgi->param('tax_override_$_')
475     foreach(grep { /^tax_override_(\w+)$/ } $cgi->param);
476
477   #some false laziness w/process
478   $cgi->param('plan') =~ /^(\w+)$/ or die 'unparsable plan';
479   my $plan = $1;
480   my $options = $cgi->param($plan."__OPTIONS");
481   my @options = split(',', $options);
482   %options =
483     map { my $optionname = $_;
484           my $param = $plan."__$optionname";
485           my $value = join(', ', $cgi->param($param));
486           ( $optionname => $value );
487         }
488         @options;
489
490   $object->set($_ => scalar($cgi->param($_)) )
491     foreach (qw( setup_fee recur_fee disable_line_item_date_ranges ));
492
493   $pkgpart = $object->pkgpart;
494
495   &$splice_locale_fields(
496     $fields,
497     sub {
498           my $locale = shift;
499           my $part_pkg_msgcat = $object->part_pkg_msgcat($locale);
500           $part_pkg_msgcat ? $part_pkg_msgcat->pkgpartmsgnum : '';
501         },
502     'cgiparam'
503   );
504
505 };
506
507 my $new_hashref_callback = sub { { 'plan' => 'flat' }; };
508
509 my $new_object_callback = sub {
510   my( $cgi, $hashref, $fields, $opt ) = @_;
511
512   my $part_pkg = FS::part_pkg->new( $hashref );
513   $part_pkg->set($_ => '0')
514     foreach (qw( setup_fee recur_fee disable_line_item_date_ranges ));
515
516   $part_pkg;
517
518 };
519
520 sub set_report_option {
521   my($cgi, $object, $fields ) = @_; #, $opt
522
523   my @report_option = ();
524   foreach ($object->options) {
525     /^usage_taxproductnum_(\d+)$/ && ($taxproductnums{$1} = 1);
526     /^report_option_(\d+)$/ && (push @report_option, $1);
527   }
528   foreach ($object->part_pkg_taxoverride) {
529     $taxproductnums{$_->usage_class} = 1
530       if $_->usage_class;
531   }
532
533   $cgi->param('report_option', join(',', @report_option));
534   foreach my $field ( @$fields ) {
535     next unless ( 
536       ref($field) eq 'HASH' &&
537       $field->{field} &&
538       $field->{field} eq 'report_option'
539     );
540     #$field->{curr_value} = join(',', @report_option);
541     $field->{value} = join(',', @report_option);
542   }
543
544 }
545
546 my $edit_callback = sub {
547   my( $cgi, $object, $fields, $opt ) = @_;
548
549   $setup_show_zero_disabled = ($object->option('setup_fee') > 0) ? 1 : 0;
550
551   $recur_disabled = $object->freq ? 0 : 1;
552
553   $recur_show_zero_disabled =
554     $object->freq
555       ? $object->option('recur_fee') > 0 ? 1 : 0
556       : 1;
557
558   (@agent_type) =
559     map {$_->typenum} qsearch('type_pkgs', { 'pkgpart' => $object->pkgpart } );
560
561   set_report_option( $cgi, $object, $fields);
562
563   %options = $object->options;
564
565   $object->set($_ => $object->option($_, 1))
566     foreach (qw( setup_fee recur_fee disable_line_item_date_ranges ));
567
568   $pkgpart = $object->pkgpart;
569
570   &$splice_locale_fields(
571     $fields,
572     sub {
573           my $locale = shift;
574           my $part_pkg_msgcat = $object->part_pkg_msgcat($locale);
575           $part_pkg_msgcat ? $part_pkg_msgcat->pkgpartmsgnum : '';
576         },
577     sub {
578           my $locale = shift;
579           my $part_pkg_msgcat = $object->part_pkg_msgcat($locale);
580           $part_pkg_msgcat ? $part_pkg_msgcat->pkg : '';
581         }
582   );
583
584 };
585
586 my $new_callback = sub {
587   my( $cgi, $object, $fields ) = @_;
588
589   my $conf = new FS::Conf; 
590
591   if ( $conf->exists('agent_defaultpkg') ) {
592     #my @all_agent_types = map {$_->typenum} qsearch('agent_type',{});
593     @agent_type = map {$_->typenum} qsearch('agent_type',{});
594   }
595
596   $options{'suspend_bill'}=1 if $conf->exists('part_pkg-default_suspend_bill');
597
598   &$splice_locale_fields($fields, '', '');
599
600 };
601
602 my $clone_callback = sub {
603   my( $cgi, $object, $fields, $opt ) = @_;
604
605   if ( $cgi->param('pkgnum') ) {
606
607     my $cust_pkg = qsearchs('cust_pkg', { 'pkgnum' => $cgi->param('pkgnum') } );
608     $object->agentnum( $cust_pkg->cust_main->agentnum );
609
610     $opt->{action} = 'Custom';
611
612     #my $part_pkg = $clone_part_pkg->clone;
613     #this is all clone does anyway
614     $object->custom('Y');
615
616     $object->disabled('Y');
617
618   } else { #when explicitly cloning, not customizing
619
620     (@agent_type) =
621       map {$_->typenum} qsearch('type_pkgs',{ 'pkgpart' => $object->pkgpart } );
622
623   }
624
625   set_report_option( $cgi, $object, $fields);
626
627   %options = $object->options;
628
629   $object->set($_ => $options{$_})
630     foreach (qw( setup_fee recur_fee disable_line_item_date_ranges ));
631
632   $recur_disabled = $object->freq ? 0 : 1;
633
634   &$splice_locale_fields(
635     $fields,
636     '',
637     sub {
638       my $locale = shift;
639       my $part_pkg_msgcat = $object->part_pkg_msgcat($locale);
640       $part_pkg_msgcat ? $part_pkg_msgcat->pkg : '';
641     }
642   );
643 };
644
645 my $discount_error_callback = sub {
646   my( $cgi, $object ) = @_;
647   map {
648         if ( /^discountnum(\d+)$/ &&
649              ( my $discountnum = $cgi->param("discountnum$1") ) )
650         {
651           new FS::part_pkg_discount {
652             'pkgpart'     => $object->pkgpart,
653             'discountnum' => $discountnum,
654           };
655         } else {
656           ();
657         }
658       }
659   $cgi->param;
660 };
661
662 my $m2_error_callback_maker = sub {
663   my $link_type = shift; #yay closures
664   return sub {
665     my( $cgi, $object ) = @_;
666     map {
667
668           if ( /^${link_type}_dst_pkgpart(\d+)$/ &&
669                ( my $dst = $cgi->param("${link_type}_dst_pkgpart$1") ) )
670           {
671
672             my $hidden = $cgi->param("${link_type}_dst_pkgpart__hidden$1")
673                          || '';
674             new FS::part_pkg_link {
675               'link_type'   => $link_type,
676               'src_pkgpart' => $object->pkgpart,
677               'dst_pkgpart' => $dst,
678               'hidden'      => $hidden,
679             };
680           } else {
681             ();
682           }
683         }
684     $cgi->param;
685   };
686 };
687
688 my $javascript = <<'END';
689   <SCRIPT TYPE="text/javascript">
690
691     function freq_changed(what) {
692       var freq = what.options[what.selectedIndex].value;
693
694       if ( freq == '0' ) {
695         what.form.recur_fee.disabled = true;
696         what.form.recur_fee.style.backgroundColor = '#dddddd';
697         what.form.recur_show_zero.disabled = true;
698         //what.form.recur_show_zero.style.backgroundColor= '#dddddd';
699       } else {
700         what.form.recur_fee.disabled = false;
701         what.form.recur_fee.style.backgroundColor = '#ffffff';
702         recur_changed( what.form.recur_fee );
703         //what.form.recur_show_zero.style.backgroundColor= '#ffffff';
704       }
705
706     }
707
708     function setup_changed(what) {
709       var setup = what.value;
710       if ( parseFloat(setup) == 0 ) {
711         what.form.setup_show_zero.disabled = false;
712       } else {
713         what.form.setup_show_zero.disabled = true;
714       }
715     }
716
717     function recur_changed(what) {
718       var recur = what.value;
719       if ( parseFloat(recur) == 0 ) {
720         what.form.recur_show_zero.disabled = false;
721       } else {
722         what.form.recur_show_zero.disabled = true;
723       }
724     }
725
726     function agent_changed(what) {
727
728       var agentnum;
729       if ( what.type == 'select-one' ) {
730         agentnum = what.options[what.selectedIndex].value;
731       } else {
732         agentnum = what.value;
733       }
734
735       if ( agentnum == 0 ) {
736         what.form.agent_type.disabled = false;
737         //what.form.agent_type.style.backgroundColor = '#ffffff';
738         what.form.agent_type.style.visibility = '';
739       } else {
740         what.form.agent_type.disabled = true;
741         //what.form.agent_type.style.backgroundColor = '#dddddd';
742         what.form.agent_type.style.visibility = 'hidden';
743       }
744
745     }
746
747     function aux_planchanged(what) { //?
748
749       var plan = what.options[what.selectedIndex].value;
750       var table = document.getElementById('TableNumber6') // XXX NOT ROBUST
751
752       if ( plan == 'flat' || plan == 'prorate' || plan == 'subscription' ) {
753         //table.disabled = false;
754         table.style.visibility = '';
755       } else {
756         //table.disabled = true;
757         table.style.visibility = 'hidden';
758       }
759
760     }
761
762     // some magic to make "supplemental packages" less obvious
763     var supp_pkg_rows = [];
764     function show_supp_pkgs_click() {
765       supp_pkg_rows[0].style.display = '';
766       this.onclick = '';
767       this.style.backgroundColor = '';
768       this.style.border = '';
769       this.style.padding = '';
770     }
771
772     function hide_supp_pkgs() {
773       var all_selects = document.getElementsByTagName('select');
774       for (var i=0; i < all_selects.length; i++) {
775         if ( all_selects[i].id.match(/^supp_dst_pkgpart/) ) {
776           supp_pkg_rows.push( all_selects[i].parentNode.parentNode );
777         }
778       }
779       if ( supp_pkg_rows.length == 1 ) {
780         // there are none configured, so hide the row to create a new one
781         supp_pkg_rows[0].style.display = 'none';
782         var button = document.getElementById('show_supp_pkgs');
783         button.onclick = show_supp_pkgs_click;
784         button.style.backgroundColor = '#cccccc';
785         button.style.border = '1px solid #7e0079';
786         button.style.padding = '1px';
787       }
788     }
789
790 END
791
792 my $warning =
793   'Changing the setup or recurring fee will create a new package definition. '.
794   'Continue?';
795
796 $javascript .= "function confirm_submit(f) {";
797 if ( $conf->exists('part_pkg-lineage') ) {
798   $javascript .= "
799
800     var fields = Array('setup_fee','recur_fee');
801     for(var i=0; i < fields.length; i++) {
802         if ( f[fields[i]].value != f[fields[i]].defaultValue ) {
803             return confirm('$warning');
804         }
805     }
806 ";
807 }
808 $javascript .= "
809   return true;
810 }
811 </SCRIPT>";
812
813 tie my %plans, 'Tie::IxHash', %{ FS::part_pkg::plan_info() };
814
815 tie my %plan_labels, 'Tie::IxHash',
816   map {  $_ => ( $plans{$_}->{'shortname'} || $plans{$_}->{'name'} ) }
817       keys %plans;
818
819 my $html_bottom = sub {
820   my( $object ) = @_;
821
822   #warn join("\n", map { "$_: $options{$_}" } keys %options ). "\n";
823
824   my $layer_callback = sub {
825   
826     my $layer = shift;
827     my $html = ntable("#cccccc",2);
828   
829     #$html .= '
830     #  <TR>
831     #    <TD ALIGN="right">Recurring fee frequency </TD>
832     #    <TD><SELECT NAME="freq">
833     #';
834     #
835     #my @freq = keys %freq;
836     #@freq = grep { /^\d+$/ } @freq
837   #XXX this bit#  #  if exists($plans{$layer}->{'freq'}) && $plans{$layer}->{'freq'} eq 'm';
838     #foreach my $freq ( @freq ) {
839     #  $html .= qq(<OPTION VALUE="$freq");
840     #  $html .= ' SELECTED' if $freq eq $part_pkg->freq;
841     #  $html .= ">$freq{$freq}";
842     #}
843
844    #$html .= '</SELECT></TD></TR>';
845   
846     my $href = $plans{$layer}->{'fields'};
847     my @fields = exists($plans{$layer}->{'fieldorder'})
848                    ? @{$plans{$layer}->{'fieldorder'}}
849                    : keys %{ $href };
850   
851     foreach my $field ( grep $_ !~ /^(setup|recur)_fee$/, @fields ) {
852   
853       if(!exists($href->{$field})) {
854         # shouldn't happen
855         warn "nonexistent part_pkg option: '$field'\n";
856         next;
857       }
858       if ( exists($href->{$field}->{display_if}) ) {
859         my %args = ( 'plan' => $layer ); # anything else?
860         my $display = &{ $href->{$field}->{display_if} }(%args);
861         next if !$display;
862       }
863
864       $html .= '<TR><TD ALIGN="right">'. $href->{$field}{'name'}. '</TD><TD>';
865   
866       my $format = sub { shift };
867       $format = $href->{$field}{'format'} if exists($href->{$field}{'format'});
868
869       #XXX these should use elements/ fields... (or this whole thing should
870       #just use layer_fields instead of layer_callback)
871   
872       if ( ! exists($href->{$field}{'type'}) ) {
873   
874         $html .= qq!<INPUT TYPE="text" NAME="${layer}__$field" VALUE="!.
875                  ( exists($options{$field})
876                      ? &$format($options{$field})
877                      : $href->{$field}{'default'} ).
878                  qq!">!;
879   
880       } elsif ( $href->{$field}{'type'} eq 'checkbox' ) {
881   
882         $html .= qq!<INPUT TYPE="checkbox" NAME="${layer}__$field" VALUE=1 !.
883                  ( exists($options{$field}) && $options{$field}
884                    ? ' CHECKED'
885                    : ''
886                  ). '>';
887   
888       } elsif ( $href->{$field}{'type'} =~ /^select/ ) {
889   
890         $html .= '<SELECT';
891         $html .= ' MULTIPLE'
892           if $href->{$field}{'type'} eq 'select_multiple';
893         $html .= qq! NAME="${layer}__$field">!;
894
895         $html .= '<OPTION VALUE="">'. $href->{$field}{'empty_label'}
896           if exists($href->{$field}{'disable_empty'})
897                && ! $href->{$field}{'disable_empty'};
898   
899         if ( $href->{$field}{'select_table'} ) {
900           foreach my $record (
901             qsearch( $href->{$field}{'select_table'},
902                      $href->{$field}{'select_hash'}   )
903           ) {
904             my $value = $record->getfield($href->{$field}{'select_key'});
905             $html .= qq!<OPTION VALUE="$value"!.
906                      (  $options{$field} =~ /(^|, *)$value *(,|$)/ #?
907                           ? ' SELECTED'
908                           : ''
909                      ).
910                      '>'. $record->getfield($href->{$field}{'select_label'});
911           }
912         } elsif ( $href->{$field}{'select_options'} ) {
913           foreach my $key ( keys %{ $href->{$field}{'select_options'} } ) {
914             my $label = $href->{$field}{'select_options'}{$key};
915             $html .= qq!<OPTION VALUE="$key"!.
916                      ( $options{$field} =~ /(^|, *)$key *(,|$)/ #?
917                          ? ' SELECTED'
918                          : ''
919                      ).
920                      '>'. $label;
921           }
922   
923         } else {
924           $html .= '<font color="#ff0000">warning: '.
925                    "don't know how to retreive options for $field select field".
926                    '</font>';
927         }
928         $html .= '</SELECT>';
929   
930       } elsif ( $href->{$field}{'type'} eq 'radio' ) {
931   
932         my $radio =
933           qq!<INPUT TYPE="radio" NAME="${layer}__$field"!;
934   
935         foreach my $key ( keys %{ $href->{$field}{'options'} } ) {
936           my $label = $href->{$field}{'options'}{$key};
937           $html .= qq!$radio VALUE="$key"!.
938                    ( $options{$field} =~ /(^|, *)$key *(,|$)/ #?
939                        ? ' CHECKED'
940                        : ''
941                    ).
942                    "> $label<BR>";
943         }
944   
945       }
946   
947       $html .= '</TD></TR>';
948     }
949     $html .= '</TABLE>';
950   
951     $html .= qq(<INPUT TYPE="hidden" NAME="${layer}__OPTIONS" VALUE=").
952              join(',', keys %{ $href } ). '">';
953   
954     $html;
955   
956   };
957
958   my %selectlayers = (
959     field          => 'plan',
960     options        => [ keys %plan_labels ],
961     labels         => \%plan_labels,
962     curr_value     => $object->plan,
963     layer_callback => $layer_callback,
964     onchange       => 'aux_planchanged(what);',
965   );
966
967   my $return =
968     include('/elements/selectlayers.html', %selectlayers, 'layers_only'=>1 ).
969     '<SCRIPT TYPE="text/javascript">'.
970       include('/elements/selectlayers.html', %selectlayers, 'js_only'=>1 );
971
972   $return .=
973     "taxproduct_selectchanged(document.getElementById('taxproduct_select'));\n"
974       if $taxproducts;
975
976   $return .= '</SCRIPT>';
977
978   $return;
979
980 };
981
982 my %usage_class = map { ($_->classnum => $_->classname) }
983                   qsearch('usage_class', {});
984 $usage_class{setup} = 'Setup';
985 $usage_class{recur} = 'Recurring';
986
987 my %taxproduct_fields = ();
988 my $end_callback = sub {
989   my( $cgi, $object, $fields, $opt ) = @_;
990
991   @taxproductnums = ( qw( setup recur ), sort (keys %taxproductnums) );
992
993   if ( $object->pkgpart ) {
994     foreach my $usage_class ( '', @taxproductnums ) {
995       $tax_override{$usage_class} =
996         join (",", map $_->taxclassnum,
997                        qsearch( 'part_pkg_taxoverride', {
998                                   'pkgpart'     => $object->pkgpart,
999                                   'usage_class' => $usage_class,
1000                               })
1001              );
1002     }
1003   }
1004
1005   %taxproduct_fields =
1006     map { $_ => [ "taxproductnum_$_", 
1007                   { type  => 'select-taxproduct',
1008                     #label => "$usage_class{$_} tax product",
1009                   },
1010                   "tax_override_$_", 
1011                   { type  => 'select-taxoverride' }
1012                 ]
1013         }
1014         @taxproductnums;
1015
1016   $taxproduct_fields{'(default)'} =
1017     [ 'taxproductnum', { type => 'select-taxproduct',
1018                          #label => 'Default tax product',
1019                        },
1020       'tax_override',  { type => 'select-taxoverride' },
1021     ];
1022 };
1023
1024 my $taxproduct_values = sub {
1025   my ($cgi, $object, $flags) = @_;
1026   my $routine =
1027     sub { my $layer = shift;
1028           my @fields = @{$taxproduct_fields{$layer}};
1029           my @values = ();
1030           while( @fields ) {
1031             my $field = shift @fields;
1032             shift @fields;
1033             $field =~ /^taxproductnum_\w+$/ &&
1034               push @values, ( $field => $options{"usage_$field"} );
1035             $field =~ /^tax_override_(\w+)$/ &&
1036               push @values, ( $field => $tax_override{$1} );
1037             $field =~ /^taxproductnum$/ &&
1038               push @values, ( $field => $object->taxproductnum );
1039             $field =~ /^tax_override$/ &&
1040               push @values, ( $field => $tax_override{''} );
1041           }
1042           { (@values) };
1043         };
1044   
1045   my @result = 
1046     map { ( $_ => { &{$routine}($_) } ) } ( '(default)', @taxproductnums );
1047   return({ @result });
1048   
1049 };
1050
1051 my $field_callback = sub {
1052   my ($cgi, $object, $fieldref) = @_;
1053
1054   my $field = $fieldref->{field};
1055   if ($field eq 'taxproductnums') {
1056     $fieldref->{value} = join(',', @taxproductnums);
1057   } elsif ($field eq 'taxproduct_select') {
1058     $fieldref->{options} = [ '(default)', @taxproductnums ];
1059     $fieldref->{labels}  = { ( '(default)' => '(default)' ),
1060                              map {( $_ => ($usage_class{$_} || $_) )}
1061                                @taxproductnums
1062                            };
1063     $fieldref->{layer_fields} = \%taxproduct_fields;
1064     $fieldref->{layer_values_callback} = $taxproduct_values;
1065   }
1066 };
1067
1068 my $discountnum_hashref = {
1069                             'disabled' => '',
1070                             'months' => { 'op' => '>', 'value' => 1 },
1071                           };
1072
1073 </%init>