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