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