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