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