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