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