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