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