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