move a2billing tariff and prepaid options to package def, #24572, #24574
[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                          hide_supp_pkgs()"',
17
18               'begin_callback'        => $begin_callback,
19               'end_callback'          => $end_callback,
20               'new_hashref_callback'  => $new_hashref_callback,
21               'new_object_callback'   => $new_object_callback,
22               'new_callback'          => $new_callback,
23               'clone_callback'        => $clone_callback,
24               'edit_callback'         => $edit_callback,
25               'error_callback'        => $error_callback,
26               'field_callback'        => $field_callback,
27
28               'onsubmit'              => 'confirm_submit',
29
30               'labels' => { 
31                             'pkgpart'          => 'Package Definition',
32                             'pkg'              => 'Package',
33                             %locale_field_labels,
34                             'comment'          => 'Comment (customer-hidden)',
35                             'classnum'         => 'Package class',
36                             'addon_classnum'   => 'Restrict additional orders to package class',
37                             'promo_code'       => 'Promotional code',
38                             'freq'             => 'Recurring fee frequency',
39                             'setuptax'         => 'Setup fee tax exempt',
40                             'recurtax'         => 'Recurring fee tax exempt',
41                             'taxclass'         => 'Tax class',
42                             'taxproduct_select'=> 'Tax products',
43                             'plan'             => 'Price plan',
44                             'disabled'         => 'Disable new orders',
45                             'disable_line_item_date_ranges' => 'Disable line item date ranges',
46                             'setup_cost'       => 'Setup cost',
47                             'recur_cost'       => 'Recur cost',
48                             'pay_weight'       => 'Payment weight',
49                             'credit_weight'    => 'Credit weight',
50                             'agentnum'         => 'Agent',
51                             'setup_fee'        => 'Setup fee',
52                             'setup_show_zero'  => 'Show zero setup',
53                             'recur_fee'        => 'Recurring fee',
54                             'recur_show_zero'  => 'Show zero recurring',
55                             'discountnum'      => 'Offer discounts for longer terms',
56                             'bill_dst_pkgpart' => 'Include line item(s) from package',
57                             'svc_dst_pkgpart'  => 'Include services of package',
58                             'supp_dst_pkgpart' => 'When ordering package, also order',
59                             'report_option'    => 'Report classes',
60                             'fcc_ds0s'         => 'Voice-grade equivalents',
61                             'fcc_voip_class'   => 'Category',
62                             'delay_start'      => 'Default delay (days)',
63                           },
64
65               'fields' => [
66                             { field=>'clone',  type=>'hidden',
67                               curr_value_callback =>
68                                 sub { shift->param('clone') },
69                             },
70                             { field=>'pkgnum', type=>'hidden',
71                               curr_value_callback =>
72                                 sub { shift->param('pkgnum') },
73                             },
74
75                             { field=>'custom',  type=>'hidden' },
76                             { field=>'family_pkgpart', type=>'hidden' },
77                             { field=>'successor', type=>'hidden' },
78
79                             { type => 'columnstart' },
80                             
81                               { field     => 'pkg',
82                                 type      => 'text',
83                                 size      => 40, #32
84                                 maxlength => 50,
85                               },
86                               #@locale_fields,
87                               {field=>'comment',  type=>'text', size=>40 }, #32
88                               { field         => 'agentnum',
89                                 type          => 'select-agent',
90                                 disable_empty => ! $acl_edit_global,
91                                 empty_label   => '(global)',
92                                 onchange      => 'agent_changed',
93                               },
94                               {field=>'classnum', type=>'select-pkg_class' },
95                               ( $conf->exists('pkg-addon_classnum')
96                                   ? ( { field=>'addon_classnum',
97                                         type =>'select-pkg_class',
98                                       }
99                                     )
100                                    : ()
101                               ),
102                               {field=>'disabled', type=>$disabled_type, value=>'Y'},
103                               {field=>'disable_line_item_date_ranges', type=>$disabled_type, value=>'Y'},
104
105                               { type     => 'tablebreak-tr-title',
106                                 value    => 'Pricing', #better name?
107                               },
108                               { field    => 'plan',
109                                 type     => 'selectlayers-select',
110                                 options  => [ keys %plan_labels ],
111                                 labels   => \%plan_labels,
112                                 onchange => 'aux_planchanged(what);',
113                               },
114                               { field    => 'setup_fee',
115                                 type     => 'money',
116                                 onchange => 'setup_changed',
117                               },
118                               { field    => 'setup_show_zero',
119                                 type     => 'checkbox',
120                                 value    => 'Y',
121                                 disabled => sub { $setup_show_zero_disabled },
122                               },
123                               { field    => 'freq',
124                                 type     => 'part_pkg_freq',
125                                 onchange => 'freq_changed',
126                               },
127                               { field    => 'recur_fee',
128                                 type     => 'money',
129                                 disabled => sub { $recur_disabled },
130                                 onchange => 'recur_changed',
131                               },
132
133                               { field    => 'recur_show_zero',
134                                 type     => 'checkbox',
135                                 value    => 'Y',
136                                 disabled => sub { $recur_show_zero_disabled },
137                               },
138
139                               #price plan
140                               #setup fee
141                               #recurring frequency
142                               #recurring fee (auto-disable)
143
144                             { type => 'columnnext' },
145
146                               {type=>'justtitle', value=>'Taxation' },
147                               {field=>'setuptax', type=>'checkbox', value=>'Y'},
148                               {field=>'recurtax', type=>'checkbox', value=>'Y'},
149                               {field=>'taxclass', type=>'select-taxclass' },
150                               { field => 'taxproductnums',
151                                 type  => 'hidden',
152                                 value => join(',', @taxproductnums),
153                               },
154                               { field => 'taxproduct_select',
155                                 type  => 'selectlayers',
156                                 options => [ '(default)', @taxproductnums ],
157                                 curr_value => '(default)',
158                                 labels  => { ( '(default)' => '(default)' ),
159                                              map {($_=>$usage_class{$_})}
160                                              @taxproductnums
161                                            },
162                                 layer_fields => \%taxproduct_fields,
163                                 layer_values_callback => $taxproduct_values,
164                                 layers_only  =>   !$taxproducts,
165                                 cell_style   => ( !$taxproducts
166                                                   ? 'display:none'
167                                                   : ''
168                                                 ),
169                               },
170
171                               { type  => 'tablebreak-tr-title',
172                                 value => 'Promotions', #better name?
173                               },
174                               { field=>'promo_code', type=>'text', size=>15 },
175
176                               { type  => 'tablebreak-tr-title',
177                                 value => 'Cost tracking', #better name?
178                               },
179                               { field=>'setup_cost', type=>'money', },
180                               { field=>'recur_cost', type=>'money', },
181
182                               ( $conf->exists('part_pkg-delay_start')
183                                 ? ( { type  => 'tablebreak-tr-title',
184                                       value => 'Delayed start',
185                                     },
186                                     { field => 'delay_start',
187                                       type => 'text', size => 6 },
188                                   )
189                                 : ()
190                               ),
191
192                             { type => 'columnnext' },
193
194                               { field    => 'agent_type',
195                                 type     => 'select-agent_types',
196                                 disabled => ! $acl_edit_global,
197                                 curr_value_callback => sub {
198                                   my($cgi, $object, $field) = @_;
199                                   #in the other callbacks..?  hmm.
200                                   \@agent_type;
201                                 },
202                               },
203
204                               { type  => 'tablebreak-tr-title',
205                                 value => 'Line-item revenue recogition', #better name?
206                               },
207                               { field=>'pay_weight',    type=>'text', size=>6 },
208                               { field=>'credit_weight', type=>'text', size=>6 },
209
210                               ( $conf->exists('cust_pkg-show_fcc_voice_grade_equivalent')
211                                 ? ( 
212                                     { type  => 'tablebreak-tr-title',
213                                       value => 'FCC Form 477 information',
214                                     },
215                                     { field=>'fcc_voip_class',
216                                       type=>'select-voip_class',
217                                     },
218                                     { field=>'fcc_ds0s', type=>'text', size=>6 },
219                                   )
220                                  : ()
221                               ),
222
223                             { type => 'columnend' },
224
225                             { 'type'  => $report_option ? 'tablebreak-tr-title'
226                                                         : 'hidden',
227                               'value' => 'Optional report classes',
228                               'field' => 'census_title',
229                             },
230                             { 'field'    => 'report_option',
231                               'type'     => $report_option ? 'select-table'
232                                                            : 'hidden',
233                               'table'    => 'part_pkg_report_option',
234                               'name_col' => 'name',
235                               'hashref'  => { 'disabled' => '' },
236                               'multiple' => 1,
237                             },
238
239                             { 'type'    => 'tablebreak-tr-title',
240                               'value'   => 'Term discounts',
241                             },
242                             { 'field'      => 'discountnum',
243                               'type'       => 'select-table',
244                               'table'      => 'discount',
245                               'name_col'   => 'name',
246                               'hashref'    => { %$discountnum_hashref },
247                               #'extra_sql'  => 'AND (months IS NOT NULL OR months != 0)',
248                               'empty_label'=> 'Select discount',
249                               'm2_label'   => 'Offer discounts for longer terms',
250                               'm2m_method' => 'part_pkg_discount',
251                               'm2m_dstcol' => 'discountnum',
252                               'm2_error_callback' => $discount_error_callback,
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'   => 'Supplemental packages',
300                               'colspan' => '4',
301                               'include_opt_callback' => sub {
302                                  'id' => 'show_supp_pkgs',
303                               },
304                             },
305                             { 'field'       => 'supp_dst_pkgpart',
306                               'type'        => 'select-part_pkg',
307                               'm2_label'    => 'When ordering package, also order',
308                               'm2m_method'  => 'supp_part_pkg_link',
309                               'm2m_dstcol'  => 'dst_pkgpart',
310                               'm2_error_callback' =>
311                                 &{$m2_error_callback_maker}('supp'),
312                             },
313
314                             { type  => 'tablebreak-tr-title',
315                               value => 'Price plan options',
316                             },
317
318                           ],
319
320            )
321 %>
322 <%init>
323
324 my $curuser = $FS::CurrentUser::CurrentUser;
325
326 my $edit_global = 'Edit global package definitions';
327 my $acl_edit        = $curuser->access_right('Edit package definitions');
328 my $acl_edit_global = $curuser->access_right($edit_global);
329
330 my $acl_edit_either = $acl_edit || $acl_edit_global;
331
332 my $begin_callback = sub {
333   my( $cgi, $fields, $opt ) = @_;
334   die "access denied"
335     unless $acl_edit_either
336         || ( $cgi->param('pkgnum')
337              && $curuser->access_right('Customize customer package')
338            );
339 };
340
341 my $disabled_type = $acl_edit_either ? 'checkbox' : 'hidden';
342
343 #arg.  access rights for cloning are Hard.
344 # on the one hand we don't really want cloning (customizing a package) to fail 
345 #  for want of finding the source package in normal usage
346 # on the other hand, we don't want people using the clone link to be able to
347 #  see 
348 my $agent_clone_extra_sql = 
349   ' ( '. FS::part_pkg->curuser_pkgs_sql.
350   "   OR ( part_pkg.custom = 'Y' ) ".
351   ' ) ';
352
353 my $conf = new FS::Conf;
354 my $taxproducts = $conf->exists('enable_taxproducts');
355
356 my @locales = grep { ! /^en_/i } $conf->config('available-locales'); #should filter from the default locale lang instead of en_
357 my %locale_labels =  map {
358   ( $_ => 'Package -- '. FS::Locales->description($_) )
359 } @locales;
360 @locales = 
361   sort { $locale_labels{$a} cmp $locale_labels{$b} }
362     @locales;
363
364 my $n = 0;
365 my %locale_field_labels = (
366   map {
367         ( 'pkgpartmsgnum'. $n++. '_pkg' => $locale_labels{$_} );
368       }
369     @locales
370 );
371
372 my $sth = dbh->prepare("SELECT COUNT(*) FROM part_pkg_report_option".
373                        "  WHERE disabled IS NULL OR disabled = ''  ")
374   or die dbh->errstr;
375 $sth->execute or die $sth->errstr;
376 my $report_option = $sth->fetchrow_arrayref->[0];
377
378 #XXX
379 # - tr-part_pkg_freq: month_increments_only (from price plans)
380 # - test cloning
381 # - test errors cloning
382 # - test custom pricing
383 # - move the selectlayer divs away from lame layer_callback
384
385 #my ($query) = $cgi->keywords;
386 #
387 #my $part_pkg = '';
388
389 my @agent_type = ();
390 my %tax_override = ();
391
392 my %taxproductnums = map { ($_->classnum => 1) }
393                      qsearch('usage_class', { 'disabled' => '' });
394 my @taxproductnums = ( qw( setup recur ), sort (keys %taxproductnums) );
395
396 my %options = ();
397 my $recur_disabled = 1;
398 my $setup_show_zero_disabled = 0;
399 my $recur_show_zero_disabled = 1;
400
401 my $pkgpart = '';
402
403 my $splice_locale_fields = sub {
404   my( $fields, $pkey_value_callback, $pkg_value_callback ) = @_;
405
406   my $n = 0;
407   my @locale_fields = (
408     map { 
409           my $pkey_value= $pkey_value_callback ? &$pkey_value_callback($_) : '';
410           my $pkg_value = $pkg_value_callback
411                             ? $pkg_value_callback eq 'cgiparam'
412                                 ? $cgi->param('pkgpartmsgnum'. $n. '_pkg')
413                                 : &$pkg_value_callback($_)
414                             : '';
415           (
416             { field     => 'pkgpartmsgnum'. $n,
417               type      => 'hidden',
418               value     => $pkey_value,
419             },
420             { field     => 'pkgpartmsgnum'. $n. '_locale',
421               type      => 'hidden',
422               value     => $_,
423             },
424             { field     => 'pkgpartmsgnum'. $n++. '_pkg',
425               type      => 'text',
426               size      => 40,
427               #maxlength => 50,
428               value     => $pkg_value,
429             },
430           );
431   
432         }
433       @locales
434   );
435   splice(@$fields, 7, 0, @locale_fields); #XXX 7 is arbitrary above
436
437 };
438
439 my $error_callback = sub {
440   my($cgi, $object, $fields, $opt ) = @_;
441
442   (@agent_type) = $cgi->param('agent_type');
443
444   $opt->{action} = 'Custom' if $cgi->param('pkgnum');
445
446   $setup_show_zero_disabled = ($cgi->param('setup_fee') > 0) ? 1 : 0;
447
448   $recur_disabled = $cgi->param('freq') ? 0 : 1;
449   $recur_show_zero_disabled =
450     $cgi->param('freq')
451       ? $cgi->param('recur_fee') > 0 ? 1 : 0
452       : 1;
453
454   foreach ($cgi->param) {
455     /^usage_taxproductnum_(\d+)$/ && ($taxproductnums{$1} = 1);
456   }
457   $tax_override{''} = $cgi->param('tax_override');
458   $tax_override{$_} = $cgi->param('tax_override_$_')
459     foreach(grep { /^tax_override_(\w+)$/ } $cgi->param);
460
461   #some false laziness w/process
462   $cgi->param('plan') =~ /^(\w+)$/ or die 'unparsable plan';
463   my $plan = $1;
464   my $options = $cgi->param($plan."__OPTIONS");
465   my @options = split(',', $options);
466   %options =
467     map { my $optionname = $_;
468           my $param = $plan."__$optionname";
469           my $value = join(', ', $cgi->param($param));
470           ( $optionname => $value );
471         }
472         @options;
473
474   $object->set($_ => scalar($cgi->param($_)) )
475     foreach (qw( setup_fee recur_fee disable_line_item_date_ranges ));
476
477   $pkgpart = $object->pkgpart;
478
479   &$splice_locale_fields(
480     $fields,
481     sub {
482           my $locale = shift;
483           my $part_pkg_msgcat = $object->part_pkg_msgcat($locale);
484           $part_pkg_msgcat ? $part_pkg_msgcat->pkgpartmsgnum : '';
485         },
486     'cgiparam'
487   );
488
489 };
490
491 my $new_hashref_callback = sub { { 'plan' => 'flat' }; };
492
493 my $new_object_callback = sub {
494   my( $cgi, $hashref, $fields, $opt ) = @_;
495
496   my $part_pkg = FS::part_pkg->new( $hashref );
497   $part_pkg->set($_ => '0')
498     foreach (qw( setup_fee recur_fee disable_line_item_date_ranges ));
499
500   $part_pkg;
501
502 };
503
504 sub set_report_option {
505   my($cgi, $object, $fields ) = @_; #, $opt
506
507   my @report_option = ();
508   foreach ($object->options) {
509     /^usage_taxproductnum_(\d+)$/ && ($taxproductnums{$1} = 1);
510     /^report_option_(\d+)$/ && (push @report_option, $1);
511   }
512   foreach ($object->part_pkg_taxoverride) {
513     $taxproductnums{$_->usage_class} = 1
514       if $_->usage_class;
515   }
516
517   $cgi->param('report_option', join(',', @report_option));
518   foreach my $field ( @$fields ) {
519     next unless ( 
520       ref($field) eq 'HASH' &&
521       $field->{field} &&
522       $field->{field} eq 'report_option'
523     );
524     #$field->{curr_value} = join(',', @report_option);
525     $field->{value} = join(',', @report_option);
526   }
527
528 }
529
530 my $edit_callback = sub {
531   my( $cgi, $object, $fields, $opt ) = @_;
532
533   $setup_show_zero_disabled = ($object->option('setup_fee') > 0) ? 1 : 0;
534
535   $recur_disabled = $object->freq ? 0 : 1;
536
537   $recur_show_zero_disabled =
538     $object->freq
539       ? $object->option('recur_fee') > 0 ? 1 : 0
540       : 1;
541
542   (@agent_type) =
543     map {$_->typenum} qsearch('type_pkgs', { 'pkgpart' => $object->pkgpart } );
544
545   set_report_option( $cgi, $object, $fields);
546
547   %options = $object->options;
548
549   $object->set($_ => $object->option($_, 1))
550     foreach (qw( setup_fee recur_fee disable_line_item_date_ranges ));
551
552   $pkgpart = $object->pkgpart;
553
554   &$splice_locale_fields(
555     $fields,
556     sub {
557           my $locale = shift;
558           my $part_pkg_msgcat = $object->part_pkg_msgcat($locale);
559           $part_pkg_msgcat ? $part_pkg_msgcat->pkgpartmsgnum : '';
560         },
561     sub {
562           my $locale = shift;
563           my $part_pkg_msgcat = $object->part_pkg_msgcat($locale);
564           $part_pkg_msgcat ? $part_pkg_msgcat->pkg : '';
565         }
566   );
567
568 };
569
570 my $new_callback = sub {
571   my( $cgi, $object, $fields ) = @_;
572
573   my $conf = new FS::Conf; 
574
575   if ( $conf->exists('agent_defaultpkg') ) {
576     #my @all_agent_types = map {$_->typenum} qsearch('agent_type',{});
577     @agent_type = map {$_->typenum} qsearch('agent_type',{});
578   }
579
580   $options{'suspend_bill'}=1 if $conf->exists('part_pkg-default_suspend_bill');
581
582   &$splice_locale_fields($fields, '', '');
583
584 };
585
586 my $clone_callback = sub {
587   my( $cgi, $object, $fields, $opt ) = @_;
588
589   if ( $cgi->param('pkgnum') ) {
590
591     my $cust_pkg = qsearchs('cust_pkg', { 'pkgnum' => $cgi->param('pkgnum') } );
592     $object->agentnum( $cust_pkg->cust_main->agentnum );
593
594     $opt->{action} = 'Custom';
595
596     #my $part_pkg = $clone_part_pkg->clone;
597     #this is all clone does anyway
598     $object->custom('Y');
599
600     $object->disabled('Y');
601
602   } else { #when explicitly cloning, not customizing
603
604     (@agent_type) =
605       map {$_->typenum} qsearch('type_pkgs',{ 'pkgpart' => $object->pkgpart } );
606
607   }
608
609   set_report_option( $cgi, $object, $fields);
610
611   %options = $object->options;
612
613   $object->set($_ => $options{$_})
614     foreach (qw( setup_fee recur_fee disable_line_item_date_ranges ));
615
616   $recur_disabled = $object->freq ? 0 : 1;
617
618   &$splice_locale_fields(
619     $fields,
620     '',
621     sub {
622       my $locale = shift;
623       my $part_pkg_msgcat = $object->part_pkg_msgcat($locale);
624       $part_pkg_msgcat ? $part_pkg_msgcat->pkg : '';
625     }
626   );
627 };
628
629 my $discount_error_callback = sub {
630   my( $cgi, $object ) = @_;
631   map {
632         if ( /^discountnum(\d+)$/ &&
633              ( my $discountnum = $cgi->param("discountnum$1") ) )
634         {
635           new FS::part_pkg_discount {
636             'pkgpart'     => $object->pkgpart,
637             'discountnum' => $discountnum,
638           };
639         } else {
640           ();
641         }
642       }
643   $cgi->param;
644 };
645
646 my $m2_error_callback_maker = sub {
647   my $link_type = shift; #yay closures
648   return sub {
649     my( $cgi, $object ) = @_;
650     map {
651
652           if ( /^${link_type}_dst_pkgpart(\d+)$/ &&
653                ( my $dst = $cgi->param("${link_type}_dst_pkgpart$1") ) )
654           {
655
656             my $hidden = $cgi->param("${link_type}_dst_pkgpart__hidden$1")
657                          || '';
658             new FS::part_pkg_link {
659               'link_type'   => $link_type,
660               'src_pkgpart' => $object->pkgpart,
661               'dst_pkgpart' => $dst,
662               'hidden'      => $hidden,
663             };
664           } else {
665             ();
666           }
667         }
668     $cgi->param;
669   };
670 };
671
672 my $javascript = <<'END';
673   <SCRIPT TYPE="text/javascript">
674
675     function freq_changed(what) {
676       var freq = what.options[what.selectedIndex].value;
677
678       if ( freq == '0' ) {
679         what.form.recur_fee.disabled = true;
680         what.form.recur_fee.style.backgroundColor = '#dddddd';
681         what.form.recur_show_zero.disabled = true;
682         //what.form.recur_show_zero.style.backgroundColor= '#dddddd';
683       } else {
684         what.form.recur_fee.disabled = false;
685         what.form.recur_fee.style.backgroundColor = '#ffffff';
686         recur_changed( what.form.recur_fee );
687         //what.form.recur_show_zero.style.backgroundColor= '#ffffff';
688       }
689
690     }
691
692     function setup_changed(what) {
693       var setup = what.value;
694       if ( parseFloat(setup) == 0 ) {
695         what.form.setup_show_zero.disabled = false;
696       } else {
697         what.form.setup_show_zero.disabled = true;
698       }
699     }
700
701     function recur_changed(what) {
702       var recur = what.value;
703       if ( parseFloat(recur) == 0 ) {
704         what.form.recur_show_zero.disabled = false;
705       } else {
706         what.form.recur_show_zero.disabled = true;
707       }
708     }
709
710     function agent_changed(what) {
711
712       var agentnum;
713       if ( what.type == 'select-one' ) {
714         agentnum = what.options[what.selectedIndex].value;
715       } else {
716         agentnum = what.value;
717       }
718
719       if ( agentnum == 0 ) {
720         what.form.agent_type.disabled = false;
721         //what.form.agent_type.style.backgroundColor = '#ffffff';
722         what.form.agent_type.style.visibility = '';
723       } else {
724         what.form.agent_type.disabled = true;
725         //what.form.agent_type.style.backgroundColor = '#dddddd';
726         what.form.agent_type.style.visibility = 'hidden';
727       }
728
729     }
730
731     function aux_planchanged(what) { //?
732
733       var plan = what.options[what.selectedIndex].value;
734       var table = document.getElementById('TableNumber6') // XXX NOT ROBUST
735
736       if ( plan == 'flat' || plan == 'prorate' || plan == 'subscription' ) {
737         //table.disabled = false;
738         table.style.visibility = '';
739       } else {
740         //table.disabled = true;
741         table.style.visibility = 'hidden';
742       }
743
744     }
745
746     // some magic to make "supplemental packages" less obvious
747     var supp_pkg_rows = [];
748     function show_supp_pkgs_click() {
749       supp_pkg_rows[0].style.display = '';
750       this.onclick = '';
751       this.style.backgroundColor = '';
752       this.style.border = '';
753       this.style.padding = '';
754     }
755
756     function hide_supp_pkgs() {
757       var all_selects = document.getElementsByTagName('select');
758       for (var i=0; i < all_selects.length; i++) {
759         if ( all_selects[i].id.match(/^supp_dst_pkgpart/) ) {
760           supp_pkg_rows.push( all_selects[i].parentNode.parentNode );
761         }
762       }
763       if ( supp_pkg_rows.length == 1 ) {
764         // there are none configured, so hide the row to create a new one
765         supp_pkg_rows[0].style.display = 'none';
766         var button = document.getElementById('show_supp_pkgs');
767         button.onclick = show_supp_pkgs_click;
768         button.style.backgroundColor = '#cccccc';
769         button.style.border = '1px solid #7e0079';
770         button.style.padding = '1px';
771       }
772     }
773
774 END
775
776 my $warning =
777   'Changing the setup or recurring fee will create a new package definition. '.
778   'Continue?';
779
780 $javascript .= "function confirm_submit(f) {";
781 if ( $conf->exists('part_pkg-lineage') ) {
782   $javascript .= "
783
784     var fields = Array('setup_fee','recur_fee');
785     for(var i=0; i < fields.length; i++) {
786         if ( f[fields[i]].value != f[fields[i]].defaultValue ) {
787             return confirm('$warning');
788         }
789     }
790 ";
791 }
792 $javascript .= "
793   return true;
794 }
795 </SCRIPT>";
796
797 tie my %plans, 'Tie::IxHash', %{ FS::part_pkg::plan_info() };
798
799 tie my %plan_labels, 'Tie::IxHash',
800   map {  $_ => ( $plans{$_}->{'shortname'} || $plans{$_}->{'name'} ) }
801       keys %plans;
802
803 my $html_bottom = sub {
804   my( $object ) = @_;
805
806   #warn join("\n", map { "$_: $options{$_}" } keys %options ). "\n";
807
808   my $layer_callback = sub {
809   
810     my $layer = shift;
811     my $html = ntable("#cccccc",2);
812   
813     #$html .= '
814     #  <TR>
815     #    <TD ALIGN="right">Recurring fee frequency </TD>
816     #    <TD><SELECT NAME="freq">
817     #';
818     #
819     #my @freq = keys %freq;
820     #@freq = grep { /^\d+$/ } @freq
821   #XXX this bit#  #  if exists($plans{$layer}->{'freq'}) && $plans{$layer}->{'freq'} eq 'm';
822     #foreach my $freq ( @freq ) {
823     #  $html .= qq(<OPTION VALUE="$freq");
824     #  $html .= ' SELECTED' if $freq eq $part_pkg->freq;
825     #  $html .= ">$freq{$freq}";
826     #}
827
828    #$html .= '</SELECT></TD></TR>';
829   
830     my $href = $plans{$layer}->{'fields'};
831     my @fields = exists($plans{$layer}->{'fieldorder'})
832                    ? @{$plans{$layer}->{'fieldorder'}}
833                    : keys %{ $href };
834   
835     foreach my $field ( grep $_ !~ /^(setup|recur)_fee$/, @fields ) {
836   
837       if(!exists($href->{$field})) {
838         # shouldn't happen
839         warn "nonexistent part_pkg option: '$field'\n";
840         next;
841       }
842       if ( exists($href->{$field}->{display_if}) ) {
843         my %args = ( 'plan' => $layer ); # anything else?
844         my $display = &{ $href->{$field}->{display_if} }(%args);
845         next if !$display;
846       }
847
848       $html .= '<TR><TD ALIGN="right">'. $href->{$field}{'name'}. '</TD><TD>';
849   
850       my $format = sub { shift };
851       $format = $href->{$field}{'format'} if exists($href->{$field}{'format'});
852
853       #XXX these should use elements/ fields... (or this whole thing should
854       #just use layer_fields instead of layer_callback)
855   
856       if ( ! exists($href->{$field}{'type'}) ) {
857   
858         $html .= qq!<INPUT TYPE="text" NAME="${layer}__$field" VALUE="!.
859                  ( exists($options{$field})
860                      ? &$format($options{$field})
861                      : $href->{$field}{'default'} ).
862                  qq!">!;
863   
864       } elsif ( $href->{$field}{'type'} eq 'checkbox' ) {
865   
866         $html .= qq!<INPUT TYPE="checkbox" NAME="${layer}__$field" VALUE=1 !.
867                  ( exists($options{$field}) && $options{$field}
868                    ? ' CHECKED'
869                    : ''
870                  ). '>';
871   
872       } elsif ( $href->{$field}{'type'} =~ /^select/ ) {
873   
874         $html .= '<SELECT';
875         $html .= ' MULTIPLE'
876           if $href->{$field}{'type'} eq 'select_multiple';
877         $html .= qq! NAME="${layer}__$field">!;
878
879         $html .= '<OPTION VALUE="">'. $href->{$field}{'empty_label'}
880           if exists($href->{$field}{'disable_empty'})
881                && ! $href->{$field}{'disable_empty'};
882   
883         if ( $href->{$field}{'select_table'} ) {
884           foreach my $record (
885             qsearch( $href->{$field}{'select_table'},
886                      $href->{$field}{'select_hash'}   )
887           ) {
888             my $value = $record->getfield($href->{$field}{'select_key'});
889             $html .= qq!<OPTION VALUE="$value"!.
890                      (  $options{$field} =~ /(^|, *)$value *(,|$)/ #?
891                           ? ' SELECTED'
892                           : ''
893                      ).
894                      '>'. $record->getfield($href->{$field}{'select_label'});
895           }
896         } elsif ( $href->{$field}{'select_options'} ) {
897           foreach my $key ( keys %{ $href->{$field}{'select_options'} } ) {
898             my $label = $href->{$field}{'select_options'}{$key};
899             $html .= qq!<OPTION VALUE="$key"!.
900                      ( $options{$field} =~ /(^|, *)$key *(,|$)/ #?
901                          ? ' SELECTED'
902                          : ''
903                      ).
904                      '>'. $label;
905           }
906   
907         } else {
908           $html .= '<font color="#ff0000">warning: '.
909                    "don't know how to retreive options for $field select field".
910                    '</font>';
911         }
912         $html .= '</SELECT>';
913   
914       } elsif ( $href->{$field}{'type'} eq 'radio' ) {
915   
916         my $radio =
917           qq!<INPUT TYPE="radio" NAME="${layer}__$field"!;
918   
919         foreach my $key ( keys %{ $href->{$field}{'options'} } ) {
920           my $label = $href->{$field}{'options'}{$key};
921           $html .= qq!$radio VALUE="$key"!.
922                    ( $options{$field} =~ /(^|, *)$key *(,|$)/ #?
923                        ? ' CHECKED'
924                        : ''
925                    ).
926                    "> $label<BR>";
927         }
928   
929       }
930   
931       $html .= '</TD></TR>';
932     }
933     $html .= '</TABLE>';
934   
935     $html .= qq(<INPUT TYPE="hidden" NAME="${layer}__OPTIONS" VALUE=").
936              join(',', keys %{ $href } ). '">';
937   
938     $html;
939   
940   };
941
942   my %selectlayers = (
943     field          => 'plan',
944     options        => [ keys %plan_labels ],
945     labels         => \%plan_labels,
946     curr_value     => $object->plan,
947     layer_callback => $layer_callback,
948     onchange       => 'aux_planchanged(what);',
949   );
950
951   my $return =
952     include('/elements/selectlayers.html', %selectlayers, 'layers_only'=>1 ).
953     '<SCRIPT TYPE="text/javascript">'.
954       include('/elements/selectlayers.html', %selectlayers, 'js_only'=>1 );
955
956   $return .=
957     "taxproduct_selectchanged(document.getElementById('taxproduct_select'));\n"
958       if $taxproducts;
959
960   $return .= '</SCRIPT>';
961
962   $return;
963
964 };
965
966 my %usage_class = map { ($_->classnum => $_->classname) }
967                   qsearch('usage_class', {});
968 $usage_class{setup} = 'Setup';
969 $usage_class{recur} = 'Recurring';
970
971 my %taxproduct_fields = ();
972 my $end_callback = sub {
973   my( $cgi, $object, $fields, $opt ) = @_;
974
975   @taxproductnums = ( qw( setup recur ), sort (keys %taxproductnums) );
976
977   if ( $object->pkgpart ) {
978     foreach my $usage_class ( '', @taxproductnums ) {
979       $tax_override{$usage_class} =
980         join (",", map $_->taxclassnum,
981                        qsearch( 'part_pkg_taxoverride', {
982                                   'pkgpart'     => $object->pkgpart,
983                                   'usage_class' => $usage_class,
984                               })
985              );
986     }
987   }
988
989   %taxproduct_fields =
990     map { $_ => [ "taxproductnum_$_", 
991                   { type  => 'select-taxproduct',
992                     #label => "$usage_class{$_} tax product",
993                   },
994                   "tax_override_$_", 
995                   { type  => 'select-taxoverride' }
996                 ]
997         }
998         @taxproductnums;
999
1000   $taxproduct_fields{'(default)'} =
1001     [ 'taxproductnum', { type => 'select-taxproduct',
1002                          #label => 'Default tax product',
1003                        },
1004       'tax_override',  { type => 'select-taxoverride' },
1005     ];
1006 };
1007
1008 my $taxproduct_values = sub {
1009   my ($cgi, $object, $flags) = @_;
1010   my $routine =
1011     sub { my $layer = shift;
1012           my @fields = @{$taxproduct_fields{$layer}};
1013           my @values = ();
1014           while( @fields ) {
1015             my $field = shift @fields;
1016             shift @fields;
1017             $field =~ /^taxproductnum_\w+$/ &&
1018               push @values, ( $field => $options{"usage_$field"} );
1019             $field =~ /^tax_override_(\w+)$/ &&
1020               push @values, ( $field => $tax_override{$1} );
1021             $field =~ /^taxproductnum$/ &&
1022               push @values, ( $field => $object->taxproductnum );
1023             $field =~ /^tax_override$/ &&
1024               push @values, ( $field => $tax_override{''} );
1025           }
1026           { (@values) };
1027         };
1028   
1029   my @result = 
1030     map { ( $_ => { &{$routine}($_) } ) } ( '(default)', @taxproductnums );
1031   return({ @result });
1032   
1033 };
1034
1035 my $field_callback = sub {
1036   my ($cgi, $object, $fieldref) = @_;
1037
1038   my $field = $fieldref->{field};
1039   if ($field eq 'taxproductnums') {
1040     $fieldref->{value} = join(',', @taxproductnums);
1041   } elsif ($field eq 'taxproduct_select') {
1042     $fieldref->{options} = [ '(default)', @taxproductnums ];
1043     $fieldref->{labels}  = { ( '(default)' => '(default)' ),
1044                              map {( $_ => ($usage_class{$_} || $_) )}
1045                                @taxproductnums
1046                            };
1047     $fieldref->{layer_fields} = \%taxproduct_fields;
1048     $fieldref->{layer_values_callback} = $taxproduct_values;
1049   }
1050 };
1051
1052 my $discountnum_hashref = {
1053                             'disabled' => '',
1054                             'months' => { 'op' => '>', 'value' => 1 },
1055                           };
1056
1057 </%init>