prepayment discounts rt#5318
[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
17               'begin_callback'        => $begin_callback,
18               'end_callback'          => $end_callback,
19               'new_hashref_callback'  => $new_hashref_callback,
20               'new_object_callback'   => $new_object_callback,
21               'new_callback'          => $new_callback,
22               'clone_callback'        => $clone_callback,
23               'edit_callback'         => $edit_callback,
24               'error_callback'        => $error_callback,
25               'field_callback'        => $field_callback,
26
27               'labels' => { 
28                             'pkgpart'          => 'Package Definition',
29                             'pkg'              => 'Package (customer-visible)',
30                             'comment'          => 'Comment (customer-hidden)',
31                             'classnum'         => 'Package class',
32                             'addon_classnum'   => 'Restrict additional orders to package class',
33                             'promo_code'       => 'Promotional code',
34                             'freq'             => 'Recurring fee frequency',
35                             'setuptax'         => 'Setup fee tax exempt',
36                             'recurtax'         => 'Recurring fee tax exempt',
37                             'taxclass'         => 'Tax class',
38                             'taxproduct_select'=> 'Tax products',
39                             'plan'             => 'Price plan',
40                             'disabled'         => 'Disable new orders',
41                             'setup_cost'       => 'Setup cost',
42                             'recur_cost'       => 'Recur cost',
43                             'pay_weight'       => 'Payment weight',
44                             'credit_weight'    => 'Credit weight',
45                             'agentnum'         => 'Agent',
46                             'setup_fee'        => 'Setup fee',
47                             'recur_fee'        => 'Recurring fee',
48                             'discountnum'      => 'Offer discounts for longer terms',
49                             'bill_dst_pkgpart' => 'Include line item(s) from package',
50                             'svc_dst_pkgpart'  => 'Include services of package',
51                             'report_option'    => 'Report classes',
52                             'fcc_ds0s'         => 'Voice-grade eqivalents',
53                           },
54
55               'fields' => [
56                             { field=>'clone',  type=>'hidden',
57                               curr_value_callback =>
58                                 sub { shift->param('clone') },
59                             },
60                             { field=>'pkgnum', type=>'hidden',
61                               curr_value_callback =>
62                                 sub { shift->param('pkgnum') },
63                             },
64
65                             { field=>'custom',  type=>'hidden' },
66
67                             { type => 'columnstart' },
68                             
69                               { field     => 'pkg',
70                                 type      => 'text',
71                                 size      => 40, #32
72                                 maxlength => 50,
73                               },
74                               {field=>'comment',  type=>'text', size=>40 }, #32
75                               { field         => 'agentnum',
76                                 type          => 'select-agent',
77                                 disable_empty => ! $acl_edit_global,
78                                 empty_label   => '(global)',
79                                 onchange      => 'agent_changed',
80                               },
81                               {field=>'classnum', type=>'select-pkg_class' },
82                               ( $conf->exists('pkg-addon_classnum')
83                                   ? ( { field=>'addon_classnum',
84                                         type =>'select-pkg_class',
85                                       }
86                                     )
87                                    : ()
88                               ),
89                               {field=>'disabled', type=>$disabled_type, value=>'Y'},
90
91                               { type  => 'tablebreak-tr-title',
92                                 value => 'Pricing', #better name?
93                               },
94                               { field => 'plan',
95                                 type  => 'selectlayers-select',
96                                 options => [ keys %plan_labels ],
97                                 labels  => \%plan_labels,
98                                 onchange => 'aux_planchanged(what);',
99                               },
100                               { field => 'setup_fee',
101                                 type  => 'money',
102                               },
103                               { field    => 'freq',
104                                 type     => 'part_pkg_freq',
105                                 onchange => 'freq_changed',
106                               },
107                               { field    => 'recur_fee',
108                                 type     => 'money',
109                                 disabled => sub { $recur_disabled },
110                               },
111                                 
112                               #price plan
113                               #setup fee
114                               #recurring frequency
115                               #recurring fee (auto-disable)
116
117                             { type => 'columnnext' },
118
119                               {type=>'justtitle', value=>'Taxation' },
120                               {field=>'setuptax', type=>'checkbox', value=>'Y'},
121                               {field=>'recurtax', type=>'checkbox', value=>'Y'},
122                               {field=>'taxclass', type=>'select-taxclass' },
123                               { field => 'taxproductnums',
124                                 type  => 'hidden',
125                                 value => join(',', @taxproductnums),
126                               },
127                               { field => 'taxproduct_select',
128                                 type  => 'selectlayers',
129                                 options => [ '(default)', @taxproductnums ],
130                                 curr_value => '(default)',
131                                 labels  => { ( '(default)' => '(default)' ),
132                                              map {($_=>$usage_class{$_})}
133                                              @taxproductnums
134                                            },
135                                 layer_fields => \%taxproduct_fields,
136                                 layer_values_callback => $taxproduct_values,
137                                 layers_only  =>   !$taxproducts,
138                                 cell_style   => ( !$taxproducts
139                                                   ? 'display:none'
140                                                   : ''
141                                                 ),
142                               },
143
144                               { type  => 'tablebreak-tr-title',
145                                 value => 'Promotions', #better name?
146                               },
147                               { field=>'promo_code', type=>'text', size=>15 },
148
149                               { type  => 'tablebreak-tr-title',
150                                 value => 'Cost tracking', #better name?
151                               },
152                               { field=>'setup_cost', type=>'money', },
153                               { field=>'recur_cost', type=>'money', },
154
155                             { type => 'columnnext' },
156
157                               { field    => 'agent_type',
158                                 type     => 'select-agent_types',
159                                 disabled => ! $acl_edit_global,
160                                 curr_value_callback => sub {
161                                   my($cgi, $object, $field) = @_;
162                                   #in the other callbacks..?  hmm.
163                                   \@agent_type;
164                                 },
165                               },
166
167                               { type  => 'tablebreak-tr-title',
168                                 value => 'Line-item revenue recogition', #better name?
169                               },
170                               { field=>'pay_weight',    type=>'text', size=>6 },
171                               { field=>'credit_weight', type=>'text', size=>6 },
172
173                               ( $conf->exists('cust_pkg-show_fcc_voice_grade_equivalent')
174                                 ? ( 
175                                     { type  => 'tablebreak-tr-title',
176                                       value => 'FCC Form 477 information',
177                                     },
178                                     { field=>'fcc_ds0s', type=>'text', size=>6 },
179                                   )
180                                  : ()
181                               ),
182
183
184                             { type => 'columnend' },
185
186                             { 'type'  => $report_option ? 'tablebreak-tr-title'
187                                                         : 'hidden',
188                               'value' => 'Optional report classes',
189                               'field' => 'census_title',
190                             },
191                             { 'field'    => 'report_option',
192                               'type'     => $report_option ? 'select-table'
193                                                            : 'hidden',
194                               'table'    => 'part_pkg_report_option',
195                               'name_col' => 'name',
196                               'hashref'  => { 'disabled' => '' },
197                               'multiple' => 1,
198                             },
199
200                             { 'type'    => 'tablebreak-tr-title',
201                               'value'   => 'Term discounts',
202                             },
203                             { 'field'      => 'discountnum',
204                               'type'       => 'select-table',
205                               'table'      => 'discount',
206                               'name_col'   => 'name',
207                               'hashref'    => { %$discountnum_hashref },
208                               #'extra_sql'  => 'AND (months IS NOT NULL OR months != 0)',
209                               'empty_label'=> 'Select discount',
210                               'm2_label'   => 'Offer discounts for longer terms',
211                               'm2m_method' => 'part_pkg_discount',
212                               'm2m_dstcol' => 'discountnum',
213                               'm2_error_callback' => $discount_error_callback,
214                             },
215
216                             { 'type'    => 'tablebreak-tr-title',
217                               'value'   => 'Pricing add-ons',
218                               'colspan' => 4,
219                             },
220                             { 'field'      => 'bill_dst_pkgpart',
221                               'type'       => 'select-part_pkg',
222                               'm2_label'   => 'Include line item(s) from package',
223                               'm2m_method' => 'bill_part_pkg_link',
224                               'm2m_dstcol' => 'dst_pkgpart',
225                               'm2_error_callback' =>
226                                 &{$m2_error_callback_maker}('bill'),
227                               'm2_fields' => [ { 'field' => 'hidden',
228                                                  'type'  => 'checkbox',
229                                                  'value' => 'Y',
230                                                  'curr_value' => '',
231                                                  'label' => 'Bundle',
232                                                },
233                                              ],
234                             },
235
236                             { type  => 'tablebreak-tr-title',
237                               value => 'Services',
238                             },
239                             { type => 'pkg_svc', },
240
241                             { 'field'      => 'svc_dst_pkgpart',
242                               'label'      => 'Also include services from package: ',
243                               'type'       => 'select-part_pkg',
244                               'm2_label'   => 'Include services of package: ',
245                               'm2m_method' => 'svc_part_pkg_link',
246                               'm2m_dstcol' => 'dst_pkgpart',
247                               'm2_error_callback' =>
248                                 &{$m2_error_callback_maker}('svc'),
249                             },
250
251                             { type  => 'tablebreak-tr-title',
252                               value => 'Price plan options',
253                             },
254
255                           ],
256
257            )
258 %>
259 <%init>
260
261 my $curuser = $FS::CurrentUser::CurrentUser;
262
263 my $edit_global = 'Edit global package definitions';
264 my $acl_edit        = $curuser->access_right('Edit package definitions');
265 my $acl_edit_global = $curuser->access_right($edit_global);
266
267 my $acl_edit_either = $acl_edit || $acl_edit_global;
268
269 my $begin_callback = sub {
270   my( $cgi, $fields, $opt ) = @_;
271   die "access denied"
272     unless $acl_edit_either
273         || ( $cgi->param('pkgnum')
274              && $curuser->access_right('Customize customer package')
275            );
276 };
277
278 my $disabled_type = $acl_edit_either ? 'checkbox' : 'hidden';
279
280 #arg.  access rights for cloning are Hard.
281 # on the one hand we don't really want cloning (customizing a package) to fail 
282 #  for want of finding the source package in normal usage
283 # on the other hand, we don't want people using the clone link to be able to
284 #  see 
285 my $agent_clone_extra_sql = 
286   ' ( '. FS::part_pkg->curuser_pkgs_sql.
287   "   OR ( part_pkg.custom = 'Y' ) ".
288   ' ) ';
289
290 my $conf = new FS::Conf;
291 my $taxproducts = $conf->exists('enable_taxproducts');
292
293 my $sth = dbh->prepare("SELECT COUNT(*) FROM part_pkg_report_option".
294                        "  WHERE disabled IS NULL OR disabled = ''  ")
295   or die dbh->errstr;
296 $sth->execute or die $sth->errstr;
297 my $report_option = $sth->fetchrow_arrayref->[0];
298
299 #XXX
300 # - tr-part_pkg_freq: month_increments_only (from price plans)
301 # - test cloning
302 # - test errors cloning
303 # - test custom pricing
304 # - move the selectlayer divs away from lame layer_callback
305
306 #my ($query) = $cgi->keywords;
307 #
308 #my $part_pkg = '';
309
310 my @agent_type = ();
311 my %tax_override = ();
312
313 my %taxproductnums = map { ($_->classnum => 1) }
314                      qsearch('usage_class', { 'disabled' => '' });
315 my @taxproductnums = ( qw( setup recur ), sort (keys %taxproductnums) );
316
317 my %options = ();
318 my $recur_disabled = 1;
319
320 my $error_callback = sub {
321   my($cgi, $object, $fields, $opt ) = @_;
322
323   (@agent_type) = $cgi->param('agent_type');
324
325   $opt->{action} = 'Custom' if $cgi->param('pkgnum');
326
327   $recur_disabled = $cgi->param('freq') ? 0 : 1;
328
329   foreach ($cgi->param) {
330     /^usage_taxproductnum_(\d+)$/ && ($taxproductnums{$1} = 1);
331   }
332   $tax_override{''} = $cgi->param('tax_override');
333   $tax_override{$_} = $cgi->param('tax_override_$_')
334     foreach(grep { /^tax_override_(\w+)$/ } $cgi->param);
335
336   #some false laziness w/process
337   $cgi->param('plan') =~ /^(\w+)$/ or die 'unparsable plan';
338   my $plan = $1;
339   my $options = $cgi->param($plan."__OPTIONS");
340   my @options = split(',', $options);
341   %options =
342     map { my $optionname = $_;
343           my $param = $plan."__$optionname";
344           my $value = join(', ', $cgi->param($param));
345           ( $optionname => $value );
346         }
347         @options;
348
349   #$cgi->param($_, $options{$_}) foreach (qw( setup_fee recur_fee ));
350   $object->set($_ => scalar($cgi->param($_)) )
351     foreach (qw( setup_fee recur_fee ));
352
353 };
354
355 my $new_hashref_callback = sub { { 'plan' => 'flat' }; };
356
357 my $new_object_callback = sub {
358   my( $cgi, $hashref, $fields, $opt ) = @_;
359
360   my $part_pkg = FS::part_pkg->new( $hashref );
361   $part_pkg->set($_ => '0')
362     foreach (qw( setup_fee recur_fee ));
363
364   $part_pkg;
365
366 };
367
368 my $edit_callback = sub {
369   my( $cgi, $object, $fields, $opt ) = @_;
370
371   $recur_disabled = $object->freq ? 0 : 1;
372
373   (@agent_type) =
374     map {$_->typenum} qsearch('type_pkgs', { 'pkgpart' => $object->pkgpart } );
375
376   my @report_option = ();
377   foreach ($object->options) {
378     /^usage_taxproductnum_(\d+)$/ && ($taxproductnums{$1} = 1);
379     /^report_option_(\d+)$/ && (push @report_option, $1);
380   }
381   foreach ($object->part_pkg_taxoverride) {
382     $taxproductnums{$_->usage_class} = 1
383       if $_->usage_class;
384   }
385
386   $cgi->param('report_option', join(',', @report_option));
387   foreach my $field ( @$fields ) {
388     next unless ( 
389       ref($field) eq 'HASH' &&
390       $field->{field} &&
391       $field->{field} eq 'report_option'
392     );
393     #$field->{curr_value} = join(',', @report_option);
394     $field->{value} = join(',', @report_option);
395   }
396
397   %options = $object->options;
398
399   $object->set($_ => $object->option($_))
400     foreach (qw( setup_fee recur_fee ));
401
402 };
403
404 my $new_callback = sub {
405   my( $cgi, $object, $fields ) = @_;
406
407   my $conf = new FS::Conf; 
408   if ( $conf->exists('agent_defaultpkg') ) {
409     #my @all_agent_types = map {$_->typenum} qsearch('agent_type',{});
410     @agent_type = map {$_->typenum} qsearch('agent_type',{});
411   }
412
413 };
414
415 my $clone_callback = sub {
416   my( $cgi, $object, $fields, $opt ) = @_;
417
418   if ( $cgi->param('pkgnum') ) {
419
420     my $cust_pkg = qsearchs('cust_pkg', { 'pkgnum' => $cgi->param('pkgnum') } );
421     $object->agentnum( $cust_pkg->cust_main->agentnum );
422
423     $opt->{action} = 'Custom';
424
425     #my $part_pkg = $clone_part_pkg->clone;
426     #this is all clone does anyway
427     $object->custom('Y');
428
429     $object->disabled('Y');
430
431   } else { #not when cloning...
432
433     (@agent_type) =
434       map {$_->typenum} qsearch('type_pkgs',{ 'pkgpart' => $object->pkgpart } );
435
436   }
437
438   %options = $object->options;
439
440   $object->set($_ => $options{$_})
441     foreach (qw( setup_fee recur_fee ));
442
443   $recur_disabled = $object->freq ? 0 : 1;
444 };
445
446 my $discount_error_callback = sub {
447   my( $cgi, $object ) = @_;
448   map {
449         if ( /^discountnum(\d+)$/ &&
450              ( my $discountnum = $cgi->param("discountnum$1") ) )
451         {
452           new FS::part_pkg_discount {
453             'pkgpart'     => $object->pkgpart,
454             'discountnum' => $discountnum,
455           };
456         } else {
457           ();
458         }
459       }
460   $cgi->param;
461 };
462
463 my $m2_error_callback_maker = sub {
464   my $link_type = shift; #yay closures
465   return sub {
466     my( $cgi, $object ) = @_;
467     map {
468
469           if ( /^${link_type}_dst_pkgpart(\d+)$/ &&
470                ( my $dst = $cgi->param("${link_type}_dst_pkgpart$1") ) )
471           {
472
473             my $hidden = $cgi->param("${link_type}_dst_pkgpart__hidden$1")
474                          || '';
475             new FS::part_pkg_link {
476               'link_type'   => $link_type,
477               'src_pkgpart' => $object->pkgpart,
478               'dst_pkgpart' => $dst,
479               'hidden'      => $hidden,
480             };
481           } else {
482             ();
483           }
484         }
485     $cgi->param;
486   };
487 };
488
489 my $javascript = <<'END';
490   <SCRIPT TYPE="text/javascript">
491
492     function freq_changed(what) {
493       var freq = what.options[what.selectedIndex].value;
494
495       if ( freq == '0' ) {
496         what.form.recur_fee.disabled = true;
497         what.form.recur_fee.style.backgroundColor = '#dddddd';
498       } else {
499         what.form.recur_fee.disabled = false;
500         what.form.recur_fee.style.backgroundColor = '#ffffff';
501       }
502
503     }
504
505     function agent_changed(what) {
506
507       var agentnum = what.options[what.selectedIndex].value;
508
509       if ( agentnum == 0 ) {
510         what.form.agent_type.disabled = false;
511         //what.form.agent_type.style.backgroundColor = '#ffffff';
512         what.form.agent_type.style.visibility = '';
513       } else {
514         what.form.agent_type.disabled = true;
515         //what.form.agent_type.style.backgroundColor = '#dddddd';
516         what.form.agent_type.style.visibility = 'hidden';
517       }
518
519     }
520
521     function aux_planchanged(what) {
522
523       alert('called!');
524       var plan = what.options[what.selectedIndex].value;
525       var table = document.getElementById('TableNumber7') // XXX NOT ROBUST
526
527       if ( plan == 'flat' || plan == 'prorate' || plan == 'subscription' ) {
528         //table.disabled = false;
529         table.style.visibility = '';
530       } else {
531         //table.disabled = true;
532         table.style.visibility = 'hidden';
533       }
534
535     }
536
537   </SCRIPT>
538 END
539
540 tie my %plans, 'Tie::IxHash', %{ FS::part_pkg::plan_info() };
541
542 tie my %plan_labels, 'Tie::IxHash',
543   map {  $_ => ( $plans{$_}->{'shortname'} || $plans{$_}->{'name'} ) }
544       keys %plans;
545
546 my $html_bottom = sub {
547   my( $object ) = @_;
548
549   #warn join("\n", map { "$_: $options{$_}" } keys %options ). "\n";
550
551   my $layer_callback = sub {
552   
553     my $layer = shift;
554     my $html = ntable("#cccccc",2);
555   
556     #$html .= '
557     #  <TR>
558     #    <TD ALIGN="right">Recurring fee frequency </TD>
559     #    <TD><SELECT NAME="freq">
560     #';
561     #
562     #my @freq = keys %freq;
563     #@freq = grep { /^\d+$/ } @freq
564   #XXX this bit#  #  if exists($plans{$layer}->{'freq'}) && $plans{$layer}->{'freq'} eq 'm';
565     #foreach my $freq ( @freq ) {
566     #  $html .= qq(<OPTION VALUE="$freq");
567     #  $html .= ' SELECTED' if $freq eq $part_pkg->freq;
568     #  $html .= ">$freq{$freq}";
569     #}
570
571    #$html .= '</SELECT></TD></TR>';
572   
573     my $href = $plans{$layer}->{'fields'};
574     my @fields = exists($plans{$layer}->{'fieldorder'})
575                    ? @{$plans{$layer}->{'fieldorder'}}
576                    : keys %{ $href };
577   
578     foreach my $field ( grep $_ !~ /^(setup|recur)_fee$/, @fields ) {
579   
580        if(!exists($href->{$field})) {
581         # shouldn't happen
582         warn "nonexistent part_pkg option: '$field'\n";
583         next;
584       }
585
586       $html .= '<TR><TD ALIGN="right">'. $href->{$field}{'name'}. '</TD><TD>';
587   
588       my $format = sub { shift };
589       $format = $href->{$field}{'format'} if exists($href->{$field}{'format'});
590
591       #XXX these should use elements/ fields... (or this whole thing should
592       #just use layer_fields instead of layer_callback)
593   
594       if ( ! exists($href->{$field}{'type'}) ) {
595   
596         $html .= qq!<INPUT TYPE="text" NAME="${layer}__$field" VALUE="!.
597                  ( exists($options{$field})
598                      ? &$format($options{$field})
599                      : $href->{$field}{'default'} ).
600                  qq!">!;
601   
602       } elsif ( $href->{$field}{'type'} eq 'checkbox' ) {
603   
604         $html .= qq!<INPUT TYPE="checkbox" NAME="${layer}__$field" VALUE=1 !.
605                  ( exists($options{$field}) && $options{$field}
606                    ? ' CHECKED'
607                    : ''
608                  ). '>';
609   
610       } elsif ( $href->{$field}{'type'} =~ /^select/ ) {
611   
612         $html .= '<SELECT';
613         $html .= ' MULTIPLE'
614           if $href->{$field}{'type'} eq 'select_multiple';
615         $html .= qq! NAME="${layer}__$field">!;
616
617         $html .= '<OPTION VALUE="">'. $href->{$field}{'empty_label'}
618           if exists($href->{$field}{'disable_empty'})
619                && ! $href->{$field}{'disable_empty'};
620   
621         if ( $href->{$field}{'select_table'} ) {
622           foreach my $record (
623             qsearch( $href->{$field}{'select_table'},
624                      $href->{$field}{'select_hash'}   )
625           ) {
626             my $value = $record->getfield($href->{$field}{'select_key'});
627             $html .= qq!<OPTION VALUE="$value"!.
628                      (  $options{$field} =~ /(^|, *)$value *(,|$)/ #?
629                           ? ' SELECTED'
630                           : ''
631                      ).
632                      '>'. $record->getfield($href->{$field}{'select_label'});
633           }
634         } elsif ( $href->{$field}{'select_options'} ) {
635           foreach my $key ( keys %{ $href->{$field}{'select_options'} } ) {
636             my $label = $href->{$field}{'select_options'}{$key};
637             $html .= qq!<OPTION VALUE="$key"!.
638                      ( $options{$field} =~ /(^|, *)$key *(,|$)/ #?
639                          ? ' SELECTED'
640                          : ''
641                      ).
642                      '>'. $label;
643           }
644   
645         } else {
646           $html .= '<font color="#ff0000">warning: '.
647                    "don't know how to retreive options for $field select field".
648                    '</font>';
649         }
650         $html .= '</SELECT>';
651   
652       } elsif ( $href->{$field}{'type'} eq 'radio' ) {
653   
654         my $radio =
655           qq!<INPUT TYPE="radio" NAME="${layer}__$field"!;
656   
657         foreach my $key ( keys %{ $href->{$field}{'options'} } ) {
658           my $label = $href->{$field}{'options'}{$key};
659           $html .= qq!$radio VALUE="$key"!.
660                    ( $options{$field} =~ /(^|, *)$key *(,|$)/ #?
661                        ? ' CHECKED'
662                        : ''
663                    ).
664                    "> $label<BR>";
665         }
666   
667       }
668   
669       $html .= '</TD></TR>';
670     }
671     $html .= '</TABLE>';
672   
673     $html .= qq(<INPUT TYPE="hidden" NAME="${layer}__OPTIONS" VALUE=").
674              join(',', keys %{ $href } ). '">';
675   
676     $html;
677   
678   };
679
680   my %selectlayers = (
681     field          => 'plan',
682     options        => [ keys %plan_labels ],
683     labels         => \%plan_labels,
684     curr_value     => $object->plan,
685     layer_callback => $layer_callback,
686   );
687
688   my $return =
689     include('/elements/selectlayers.html', %selectlayers, 'layers_only'=>1 ).
690     '<SCRIPT TYPE="text/javascript">'.
691       include('/elements/selectlayers.html', %selectlayers, 'js_only'=>1 );
692
693   $return .=
694     "taxproduct_selectchanged(document.getElementById('taxproduct_select'));\n"
695       if $taxproducts;
696
697   $return .= '</SCRIPT>';
698
699   $return;
700
701 };
702
703 my %usage_class = map { ($_->classnum => $_->classname) }
704                   qsearch('usage_class', {});
705 $usage_class{setup} = 'Setup';
706 $usage_class{recur} = 'Recurring';
707
708 my %taxproduct_fields = ();
709 my $end_callback = sub {
710   my( $cgi, $object, $fields, $opt ) = @_;
711
712   @taxproductnums = ( qw( setup recur ), sort (keys %taxproductnums) );
713
714   if ( $object->pkgpart ) {
715     foreach my $usage_class ( '', @taxproductnums ) {
716       $tax_override{$usage_class} =
717         join (",", map $_->taxclassnum,
718                        qsearch( 'part_pkg_taxoverride', {
719                                   'pkgpart'     => $object->pkgpart,
720                                   'usage_class' => $usage_class,
721                               })
722              );
723     }
724   }
725
726   %taxproduct_fields =
727     map { $_ => [ "taxproductnum_$_", 
728                   { type  => 'select-taxproduct',
729                     #label => "$usage_class{$_} tax product",
730                   },
731                   "tax_override_$_", 
732                   { type  => 'select-taxoverride' }
733                 ]
734         }
735         @taxproductnums;
736
737   $taxproduct_fields{'(default)'} =
738     [ 'taxproductnum', { type => 'select-taxproduct',
739                          #label => 'Default tax product',
740                        },
741       'tax_override',  { type => 'select-taxoverride' },
742     ];
743 };
744
745 my $taxproduct_values = sub {
746   my ($cgi, $object, $flags) = @_;
747   my $routine =
748     sub { my $layer = shift;
749           my @fields = @{$taxproduct_fields{$layer}};
750           my @values = ();
751           while( @fields ) {
752             my $field = shift @fields;
753             shift @fields;
754             $field =~ /^taxproductnum_\w+$/ &&
755               push @values, ( $field => $options{"usage_$field"} );
756             $field =~ /^tax_override_(\w+)$/ &&
757               push @values, ( $field => $tax_override{$1} );
758             $field =~ /^taxproductnum$/ &&
759               push @values, ( $field => $object->taxproductnum );
760             $field =~ /^tax_override$/ &&
761               push @values, ( $field => $tax_override{''} );
762           }
763           { (@values) };
764         };
765   
766   my @result = 
767     map { ( $_ => { &{$routine}($_) } ) } ( '(default)', @taxproductnums );
768   return({ @result });
769   
770 };
771
772 my $field_callback = sub {
773   my ($cgi, $object, $fieldref) = @_;
774
775   my $field = $fieldref->{field};
776   if ($field eq 'taxproductnums') {
777     $fieldref->{value} = join(',', @taxproductnums);
778   } elsif ($field eq 'taxproduct_select') {
779     $fieldref->{options} = [ '(default)', @taxproductnums ];
780     $fieldref->{labels}  = { ( '(default)' => '(default)' ),
781                              map {( $_ => ($usage_class{$_} || $_) )}
782                                @taxproductnums
783                            };
784     $fieldref->{layer_fields} = \%taxproduct_fields;
785     $fieldref->{layer_values_callback} = $taxproduct_values;
786   }
787 };
788
789 my $discountnum_hashref = {
790                             'disabled' => '',
791                             'months' => { 'op' => '>', 'value' => 1 },
792                           };
793
794 </%init>