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