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