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