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                             '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 my $edit_callback = sub {
413   my( $cgi, $object, $fields, $opt ) = @_;
414
415   $setup_show_zero_disabled = ($object->option('setup_fee') > 0) ? 1 : 0;
416
417   $recur_disabled = $object->freq ? 0 : 1;
418
419   $recur_show_zero_disabled =
420     $object->freq
421       ? $object->option('recur_fee') > 0 ? 1 : 0
422       : 1;
423
424   (@agent_type) =
425     map {$_->typenum} qsearch('type_pkgs', { 'pkgpart' => $object->pkgpart } );
426
427   my @report_option = ();
428   foreach ($object->options) {
429     /^usage_taxproductnum_(\d+)$/ && ($taxproductnums{$1} = 1);
430     /^report_option_(\d+)$/ && (push @report_option, $1);
431   }
432   foreach ($object->part_pkg_taxoverride) {
433     $taxproductnums{$_->usage_class} = 1
434       if $_->usage_class;
435   }
436
437   $cgi->param('report_option', join(',', @report_option));
438   foreach my $field ( @$fields ) {
439     next unless ( 
440       ref($field) eq 'HASH' &&
441       $field->{field} &&
442       $field->{field} eq 'report_option'
443     );
444     #$field->{curr_value} = join(',', @report_option);
445     $field->{value} = join(',', @report_option);
446   }
447
448   %options = $object->options;
449
450   $object->set($_ => $object->option($_, 1))
451     foreach (qw( setup_fee recur_fee disable_line_item_date_ranges ));
452
453   $pkgpart = $object->pkgpart;
454
455 };
456
457 my $new_callback = sub {
458   my( $cgi, $object, $fields ) = @_;
459
460   my $conf = new FS::Conf; 
461
462   if ( $conf->exists('agent_defaultpkg') ) {
463     #my @all_agent_types = map {$_->typenum} qsearch('agent_type',{});
464     @agent_type = map {$_->typenum} qsearch('agent_type',{});
465   }
466
467   $options{'suspend_bill'}=1 if $conf->exists('part_pkg-default_suspend_bill');
468
469 };
470
471 my $clone_callback = sub {
472   my( $cgi, $object, $fields, $opt ) = @_;
473
474   if ( $cgi->param('pkgnum') ) {
475
476     my $cust_pkg = qsearchs('cust_pkg', { 'pkgnum' => $cgi->param('pkgnum') } );
477     $object->agentnum( $cust_pkg->cust_main->agentnum );
478
479     $opt->{action} = 'Custom';
480
481     #my $part_pkg = $clone_part_pkg->clone;
482     #this is all clone does anyway
483     $object->custom('Y');
484
485     $object->disabled('Y');
486
487   } else { #not when cloning...
488
489     (@agent_type) =
490       map {$_->typenum} qsearch('type_pkgs',{ 'pkgpart' => $object->pkgpart } );
491
492   }
493
494   %options = $object->options;
495
496   $object->set($_ => $options{$_})
497     foreach (qw( setup_fee recur_fee disable_line_item_date_ranges ));
498
499   $recur_disabled = $object->freq ? 0 : 1;
500 };
501
502 my $discount_error_callback = sub {
503   my( $cgi, $object ) = @_;
504   map {
505         if ( /^discountnum(\d+)$/ &&
506              ( my $discountnum = $cgi->param("discountnum$1") ) )
507         {
508           new FS::part_pkg_discount {
509             'pkgpart'     => $object->pkgpart,
510             'discountnum' => $discountnum,
511           };
512         } else {
513           ();
514         }
515       }
516   $cgi->param;
517 };
518
519 my $m2_error_callback_maker = sub {
520   my $link_type = shift; #yay closures
521   return sub {
522     my( $cgi, $object ) = @_;
523     map {
524
525           if ( /^${link_type}_dst_pkgpart(\d+)$/ &&
526                ( my $dst = $cgi->param("${link_type}_dst_pkgpart$1") ) )
527           {
528
529             my $hidden = $cgi->param("${link_type}_dst_pkgpart__hidden$1")
530                          || '';
531             new FS::part_pkg_link {
532               'link_type'   => $link_type,
533               'src_pkgpart' => $object->pkgpart,
534               'dst_pkgpart' => $dst,
535               'hidden'      => $hidden,
536             };
537           } else {
538             ();
539           }
540         }
541     $cgi->param;
542   };
543 };
544
545 my $javascript = <<'END';
546   <SCRIPT TYPE="text/javascript">
547
548     function freq_changed(what) {
549       var freq = what.options[what.selectedIndex].value;
550
551       if ( freq == '0' ) {
552         what.form.recur_fee.disabled = true;
553         what.form.recur_fee.style.backgroundColor = '#dddddd';
554         what.form.recur_show_zero.disabled = true;
555         //what.form.recur_show_zero.style.backgroundColor= '#dddddd';
556       } else {
557         what.form.recur_fee.disabled = false;
558         what.form.recur_fee.style.backgroundColor = '#ffffff';
559         recur_changed( what.form.recur_fee );
560         //what.form.recur_show_zero.style.backgroundColor= '#ffffff';
561       }
562
563     }
564
565     function setup_changed(what) {
566       var setup = what.value;
567       if ( parseFloat(setup) == 0 ) {
568         what.form.setup_show_zero.disabled = false;
569       } else {
570         what.form.setup_show_zero.disabled = true;
571       }
572     }
573
574     function recur_changed(what) {
575       var recur = what.value;
576       if ( parseFloat(recur) == 0 ) {
577         what.form.recur_show_zero.disabled = false;
578       } else {
579         what.form.recur_show_zero.disabled = true;
580       }
581     }
582
583     function agent_changed(what) {
584
585       var agentnum;
586       if ( what.type == 'select-one' ) {
587         agentnum = what.options[what.selectedIndex].value;
588       } else {
589         agentnum = what.value;
590       }
591
592       if ( agentnum == 0 ) {
593         what.form.agent_type.disabled = false;
594         //what.form.agent_type.style.backgroundColor = '#ffffff';
595         what.form.agent_type.style.visibility = '';
596       } else {
597         what.form.agent_type.disabled = true;
598         //what.form.agent_type.style.backgroundColor = '#dddddd';
599         what.form.agent_type.style.visibility = 'hidden';
600       }
601
602     }
603
604     function aux_planchanged(what) { //?
605
606       alert('called!');
607       var plan = what.options[what.selectedIndex].value;
608       var table = document.getElementById('TableNumber7') // XXX NOT ROBUST
609
610       if ( plan == 'flat' || plan == 'prorate' || plan == 'subscription' ) {
611         //table.disabled = false;
612         table.style.visibility = '';
613       } else {
614         //table.disabled = true;
615         table.style.visibility = 'hidden';
616       }
617
618     }
619
620 END
621
622 my $warning =
623   'Changing the setup or recurring fee will create a new package definition. '.
624   'Continue?';
625               
626 if ( $conf->exists('part_pkg-lineage') ) {
627   $javascript .= "
628     function confirm_submit(f) {
629     
630       var fields = Array('setup_fee','recur_fee');
631       for(var i=0; i < fields.length; i++) {
632           if ( f[fields[i]].value != f[fields[i]].defaultValue ) {
633               return confirm('$warning');
634           }
635       }
636       return true;
637     }
638 ";
639 }
640
641 $javascript .= '</SCRIPT>';
642
643 tie my %plans, 'Tie::IxHash', %{ FS::part_pkg::plan_info() };
644
645 tie my %plan_labels, 'Tie::IxHash',
646   map {  $_ => ( $plans{$_}->{'shortname'} || $plans{$_}->{'name'} ) }
647       keys %plans;
648
649 my $html_bottom = sub {
650   my( $object ) = @_;
651
652   #warn join("\n", map { "$_: $options{$_}" } keys %options ). "\n";
653
654   my $layer_callback = sub {
655   
656     my $layer = shift;
657     my $html = ntable("#cccccc",2);
658   
659     #$html .= '
660     #  <TR>
661     #    <TD ALIGN="right">Recurring fee frequency </TD>
662     #    <TD><SELECT NAME="freq">
663     #';
664     #
665     #my @freq = keys %freq;
666     #@freq = grep { /^\d+$/ } @freq
667   #XXX this bit#  #  if exists($plans{$layer}->{'freq'}) && $plans{$layer}->{'freq'} eq 'm';
668     #foreach my $freq ( @freq ) {
669     #  $html .= qq(<OPTION VALUE="$freq");
670     #  $html .= ' SELECTED' if $freq eq $part_pkg->freq;
671     #  $html .= ">$freq{$freq}";
672     #}
673
674    #$html .= '</SELECT></TD></TR>';
675   
676     my $href = $plans{$layer}->{'fields'};
677     my @fields = exists($plans{$layer}->{'fieldorder'})
678                    ? @{$plans{$layer}->{'fieldorder'}}
679                    : keys %{ $href };
680   
681     foreach my $field ( grep $_ !~ /^(setup|recur)_fee$/, @fields ) {
682   
683        if(!exists($href->{$field})) {
684         # shouldn't happen
685         warn "nonexistent part_pkg option: '$field'\n";
686         next;
687       }
688
689       $html .= '<TR><TD ALIGN="right">'. $href->{$field}{'name'}. '</TD><TD>';
690   
691       my $format = sub { shift };
692       $format = $href->{$field}{'format'} if exists($href->{$field}{'format'});
693
694       #XXX these should use elements/ fields... (or this whole thing should
695       #just use layer_fields instead of layer_callback)
696   
697       if ( ! exists($href->{$field}{'type'}) ) {
698   
699         $html .= qq!<INPUT TYPE="text" NAME="${layer}__$field" VALUE="!.
700                  ( exists($options{$field})
701                      ? &$format($options{$field})
702                      : $href->{$field}{'default'} ).
703                  qq!">!;
704   
705       } elsif ( $href->{$field}{'type'} eq 'checkbox' ) {
706   
707         $html .= qq!<INPUT TYPE="checkbox" NAME="${layer}__$field" VALUE=1 !.
708                  ( exists($options{$field}) && $options{$field}
709                    ? ' CHECKED'
710                    : ''
711                  ). '>';
712   
713       } elsif ( $href->{$field}{'type'} =~ /^select/ ) {
714   
715         $html .= '<SELECT';
716         $html .= ' MULTIPLE'
717           if $href->{$field}{'type'} eq 'select_multiple';
718         $html .= qq! NAME="${layer}__$field">!;
719
720         $html .= '<OPTION VALUE="">'. $href->{$field}{'empty_label'}
721           if exists($href->{$field}{'disable_empty'})
722                && ! $href->{$field}{'disable_empty'};
723   
724         if ( $href->{$field}{'select_table'} ) {
725           foreach my $record (
726             qsearch( $href->{$field}{'select_table'},
727                      $href->{$field}{'select_hash'}   )
728           ) {
729             my $value = $record->getfield($href->{$field}{'select_key'});
730             $html .= qq!<OPTION VALUE="$value"!.
731                      (  $options{$field} =~ /(^|, *)$value *(,|$)/ #?
732                           ? ' SELECTED'
733                           : ''
734                      ).
735                      '>'. $record->getfield($href->{$field}{'select_label'});
736           }
737         } elsif ( $href->{$field}{'select_options'} ) {
738           foreach my $key ( keys %{ $href->{$field}{'select_options'} } ) {
739             my $label = $href->{$field}{'select_options'}{$key};
740             $html .= qq!<OPTION VALUE="$key"!.
741                      ( $options{$field} =~ /(^|, *)$key *(,|$)/ #?
742                          ? ' SELECTED'
743                          : ''
744                      ).
745                      '>'. $label;
746           }
747   
748         } else {
749           $html .= '<font color="#ff0000">warning: '.
750                    "don't know how to retreive options for $field select field".
751                    '</font>';
752         }
753         $html .= '</SELECT>';
754   
755       } elsif ( $href->{$field}{'type'} eq 'radio' ) {
756   
757         my $radio =
758           qq!<INPUT TYPE="radio" NAME="${layer}__$field"!;
759   
760         foreach my $key ( keys %{ $href->{$field}{'options'} } ) {
761           my $label = $href->{$field}{'options'}{$key};
762           $html .= qq!$radio VALUE="$key"!.
763                    ( $options{$field} =~ /(^|, *)$key *(,|$)/ #?
764                        ? ' CHECKED'
765                        : ''
766                    ).
767                    "> $label<BR>";
768         }
769   
770       }
771   
772       $html .= '</TD></TR>';
773     }
774     $html .= '</TABLE>';
775   
776     $html .= qq(<INPUT TYPE="hidden" NAME="${layer}__OPTIONS" VALUE=").
777              join(',', keys %{ $href } ). '">';
778   
779     $html;
780   
781   };
782
783   my %selectlayers = (
784     field          => 'plan',
785     options        => [ keys %plan_labels ],
786     labels         => \%plan_labels,
787     curr_value     => $object->plan,
788     layer_callback => $layer_callback,
789   );
790
791   my $return =
792     include('/elements/selectlayers.html', %selectlayers, 'layers_only'=>1 ).
793     '<SCRIPT TYPE="text/javascript">'.
794       include('/elements/selectlayers.html', %selectlayers, 'js_only'=>1 );
795
796   $return .=
797     "taxproduct_selectchanged(document.getElementById('taxproduct_select'));\n"
798       if $taxproducts;
799
800   $return .= '</SCRIPT>';
801
802   $return;
803
804 };
805
806 my %usage_class = map { ($_->classnum => $_->classname) }
807                   qsearch('usage_class', {});
808 $usage_class{setup} = 'Setup';
809 $usage_class{recur} = 'Recurring';
810
811 my %taxproduct_fields = ();
812 my $end_callback = sub {
813   my( $cgi, $object, $fields, $opt ) = @_;
814
815   @taxproductnums = ( qw( setup recur ), sort (keys %taxproductnums) );
816
817   if ( $object->pkgpart ) {
818     foreach my $usage_class ( '', @taxproductnums ) {
819       $tax_override{$usage_class} =
820         join (",", map $_->taxclassnum,
821                        qsearch( 'part_pkg_taxoverride', {
822                                   'pkgpart'     => $object->pkgpart,
823                                   'usage_class' => $usage_class,
824                               })
825              );
826     }
827   }
828
829   %taxproduct_fields =
830     map { $_ => [ "taxproductnum_$_", 
831                   { type  => 'select-taxproduct',
832                     #label => "$usage_class{$_} tax product",
833                   },
834                   "tax_override_$_", 
835                   { type  => 'select-taxoverride' }
836                 ]
837         }
838         @taxproductnums;
839
840   $taxproduct_fields{'(default)'} =
841     [ 'taxproductnum', { type => 'select-taxproduct',
842                          #label => 'Default tax product',
843                        },
844       'tax_override',  { type => 'select-taxoverride' },
845     ];
846 };
847
848 my $taxproduct_values = sub {
849   my ($cgi, $object, $flags) = @_;
850   my $routine =
851     sub { my $layer = shift;
852           my @fields = @{$taxproduct_fields{$layer}};
853           my @values = ();
854           while( @fields ) {
855             my $field = shift @fields;
856             shift @fields;
857             $field =~ /^taxproductnum_\w+$/ &&
858               push @values, ( $field => $options{"usage_$field"} );
859             $field =~ /^tax_override_(\w+)$/ &&
860               push @values, ( $field => $tax_override{$1} );
861             $field =~ /^taxproductnum$/ &&
862               push @values, ( $field => $object->taxproductnum );
863             $field =~ /^tax_override$/ &&
864               push @values, ( $field => $tax_override{''} );
865           }
866           { (@values) };
867         };
868   
869   my @result = 
870     map { ( $_ => { &{$routine}($_) } ) } ( '(default)', @taxproductnums );
871   return({ @result });
872   
873 };
874
875 my $field_callback = sub {
876   my ($cgi, $object, $fieldref) = @_;
877
878   my $field = $fieldref->{field};
879   if ($field eq 'taxproductnums') {
880     $fieldref->{value} = join(',', @taxproductnums);
881   } elsif ($field eq 'taxproduct_select') {
882     $fieldref->{options} = [ '(default)', @taxproductnums ];
883     $fieldref->{labels}  = { ( '(default)' => '(default)' ),
884                              map {( $_ => ($usage_class{$_} || $_) )}
885                                @taxproductnums
886                            };
887     $fieldref->{layer_fields} = \%taxproduct_fields;
888     $fieldref->{layer_values_callback} = $taxproduct_values;
889   }
890 };
891
892 my $discountnum_hashref = {
893                             'disabled' => '',
894                             'months' => { 'op' => '>', 'value' => 1 },
895                           };
896
897 </%init>