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