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