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