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