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