64a75252e3228638b24c8630bb7943a0eb5e44ac
[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   $recur_disabled = $object->freq ? 0 : 1;
682   $recur_show_zero_disabled =
683     $object->freq
684       ? $object->option('recur_fee') > 0 ? 1 : 0
685       : 1;
686
687   foreach my $currency ( $conf->config('currencies') ) {
688     my %part_pkg_currency = $object->part_pkg_currency_options($currency);
689     $object->set( $_.'_'.$currency, $part_pkg_currency{$_} )
690       foreach keys %part_pkg_currency;
691   }
692
693 };
694
695 my $discount_error_callback = sub {
696   my( $cgi, $object ) = @_;
697   map {
698         if ( /^discountnum(\d+)$/ &&
699              ( my $discountnum = $cgi->param("discountnum$1") ) )
700         {
701           new FS::part_pkg_discount {
702             'pkgpart'     => $object->pkgpart,
703             'discountnum' => $discountnum,
704           };
705         } else {
706           ();
707         }
708       }
709   $cgi->param;
710 };
711
712 my $usageprice_error_callback = sub {
713   my( $cgi, $object ) = @_;
714   map {
715         if ( /^usagepricepart(\d+)_price$/
716                && $cgi->param("usagepricepart$1_price") )
717         {
718           new FS::part_pkg_usageprice {
719             'usagepricepart' => scalar($cgi->param("usagepricepart$1")),
720             'pkgpart'        => $object->pkgpart,
721             'price'          => scalar($cgi->param("usagepricepart$1_price")),
722             #'currency
723             'action'         => scalar($cgi->param("usagepricepart$1_action")),
724             'target'         => scalar($cgi->param("usagepricepart$1_target")),
725             'amount'         => scalar($cgi->param("usagepricepart$1_amount")),
726           };
727         } else {
728           ();
729         }
730       }
731   $cgi->param;
732 };
733
734 my $m2_error_callback_maker = sub {
735   my $link_type = shift; #yay closures
736   return sub {
737     my( $cgi, $object ) = @_;
738     map {
739
740           if ( /^${link_type}_dst_pkgpart(\d+)$/ &&
741                ( my $dst = $cgi->param("${link_type}_dst_pkgpart$1") ) )
742           {
743
744             my $hidden = $cgi->param("${link_type}_dst_pkgpart__hidden$1")
745                          || '';
746             new FS::part_pkg_link {
747               'link_type'   => $link_type,
748               'src_pkgpart' => $object->pkgpart,
749               'dst_pkgpart' => $dst,
750               'hidden'      => $hidden,
751             };
752           } else {
753             ();
754           }
755         }
756     $cgi->param;
757   };
758 };
759
760 my $javascript = <<'END';
761   <SCRIPT TYPE="text/javascript">
762
763     function freq_changed(what) {
764       var freq = what.options[what.selectedIndex].value;
765
766       if ( freq == '0' ) {
767         what.form.recur_fee.disabled = true;
768         what.form.recur_fee.style.backgroundColor = '#dddddd';
769         what.form.recur_show_zero.disabled = true;
770         //what.form.recur_show_zero.style.backgroundColor= '#dddddd';
771       } else {
772         what.form.recur_fee.disabled = false;
773         what.form.recur_fee.style.backgroundColor = '#ffffff';
774         recur_changed( what.form.recur_fee );
775         //what.form.recur_show_zero.style.backgroundColor= '#ffffff';
776       }
777
778     }
779
780     function setup_changed(what) {
781       var setup = what.value;
782       if ( parseFloat(setup) == 0 ) {
783         what.form.setup_show_zero.disabled = false;
784       } else {
785         what.form.setup_show_zero.disabled = true;
786       }
787     }
788
789     function recur_changed(what) {
790       var recur = what.value;
791       if ( parseFloat(recur) == 0 ) {
792         what.form.recur_show_zero.disabled = false;
793       } else {
794         what.form.recur_show_zero.disabled = true;
795       }
796     }
797
798     function agent_changed(what) {
799
800       var agentnum;
801       if ( what.type == 'select-one' ) {
802         agentnum = what.options[what.selectedIndex].value;
803       } else {
804         agentnum = what.value;
805       }
806
807       if ( agentnum == 0 ) {
808         what.form.agent_type.disabled = false;
809         //what.form.agent_type.style.backgroundColor = '#ffffff';
810         what.form.agent_type.style.visibility = '';
811       } else {
812         what.form.agent_type.disabled = true;
813         //what.form.agent_type.style.backgroundColor = '#dddddd';
814         what.form.agent_type.style.visibility = 'hidden';
815       }
816
817     }
818
819     function aux_planchanged(what) { //?
820
821       var plan = what.options[what.selectedIndex].value;
822
823       var term_table = document.getElementById('TableNumber8') // XXX NOT ROBUST
824       if ( plan == 'flat' || plan == 'prorate' || plan == 'subscription' ) {
825         //term_table.disabled = false;
826         //term_table.style.visibility = '';
827         term_table.style.display = '';
828       } else {
829         //term_table.disabled = true;
830         //term_table.style.visibility = 'hidden';
831         term_table.style.display = 'none';
832       }
833
834       var currency_regex = /^(setup|recur)_fee_[A-Z]{3}$/;
835
836       var form = what.form
837       for ( var i=0; i < form.length; i++ ) {
838         if ( currency_regex.test(form[i].name) ) {
839           if ( plan == 'currency_fixed' ) {
840             form[i].disabled = false;
841           } else {
842             form[i].disabled = true;
843           }
844         }
845       }
846
847     }
848
849     // some magic to make "supplemental packages" less obvious
850     var supp_pkg_rows = [];
851     function show_supp_pkgs_click() {
852       supp_pkg_rows[0].style.display = '';
853       this.onclick = '';
854       this.style.backgroundColor = '';
855       this.style.border = '';
856       this.style.padding = '';
857     }
858
859     function hide_supp_pkgs() {
860       var all_selects = document.getElementsByTagName('select');
861       for (var i=0; i < all_selects.length; i++) {
862         if ( all_selects[i].id.match(/^supp_dst_pkgpart/) ) {
863           supp_pkg_rows.push( all_selects[i].parentNode.parentNode );
864         }
865       }
866       if ( supp_pkg_rows.length == 1 ) {
867         // there are none configured, so hide the row to create a new one
868         supp_pkg_rows[0].style.display = 'none';
869         var button = document.getElementById('show_supp_pkgs');
870         button.onclick = show_supp_pkgs_click;
871         button.style.backgroundColor = '#cccccc';
872         button.style.border = '1px solid #7e0079';
873         button.style.padding = '1px';
874       }
875     }
876
877     function finish_edit_fcc(id) {
878       cClick();
879       show_fcc_options(id); // refresh the display
880     }
881
882 END
883
884 my $warning =
885   'Changing the setup or recurring fee will create a new package definition. '.
886   'Continue?';
887
888 $javascript .= "function confirm_submit(f) {";
889 if ( $conf->exists('part_pkg-lineage') ) {
890   $javascript .= "
891
892     var fields = Array('setup_fee','recur_fee');
893     for(var i=0; i < fields.length; i++) {
894         if ( f[fields[i]].value != f[fields[i]].defaultValue ) {
895             return confirm('$warning');
896         }
897     }
898 ";
899 }
900 $javascript .= "
901   return true;
902 }
903 </SCRIPT>";
904
905 tie my %plans, 'Tie::IxHash', %{ FS::part_pkg::plan_info() };
906
907 tie my %plan_labels, 'Tie::IxHash',
908   map {  $_ => ( $plans{$_}->{'shortname'} || $plans{$_}->{'name'} ) }
909       keys %plans;
910
911 my $html_bottom = sub {
912   my( $object ) = @_;
913
914   #warn join("\n", map { "$_: $options{$_}" } keys %options ). "\n";
915
916   my $layer_callback = sub {
917   
918     my $layer = shift;
919     my $html = ntable("#cccccc",2);
920   
921     #$html .= '
922     #  <TR>
923     #    <TD ALIGN="right">Recurring fee frequency </TD>
924     #    <TD><SELECT NAME="freq">
925     #';
926     #
927     #my @freq = keys %freq;
928     #@freq = grep { /^\d+$/ } @freq
929   #XXX this bit#  #  if exists($plans{$layer}->{'freq'}) && $plans{$layer}->{'freq'} eq 'm';
930     #foreach my $freq ( @freq ) {
931     #  $html .= qq(<OPTION VALUE="$freq");
932     #  $html .= ' SELECTED' if $freq eq $part_pkg->freq;
933     #  $html .= ">$freq{$freq}";
934     #}
935
936    #$html .= '</SELECT></TD></TR>';
937   
938     my $href = $plans{$layer}->{'fields'};
939     my @fields;
940     if ( $plans{$layer}->{'fieldorder'} ) {
941       @fields = @{ $plans{$layer}->{'fieldorder'} };
942     } else {
943       warn "FS::part_pkg::$layer has no fieldorder.\n";
944       @fields = keys %$href;
945     }
946     
947     # hash of dependencies for each of the Pricing Plan fields.
948     # make sure NOT to use double-quotes inside the 'msg' value.
949     my $dependencies = {
950         'unused_credit_suspend' => {
951             'msg'       => q|You must set the 'suspend_credit_type' option in Configuration->Settings to gain access to this option.|,
952             'are_met'   => sub{
953                 my $conf = new FS::conf;
954                 my @conf_info = qsearch('conf', { 'name' => 'suspend_credit_type' } );
955                 return 1 if (exists($conf_info[0]) && $conf_info[0]->{Hash}{value});
956                 return 0;
957             }
958         },
959         'unused_credit_cancel' => {
960             'msg'       => q|You must set the 'cancel_credit_type' option in Configuration->Settings to gain access to this option.|,
961             'are_met'   => sub{
962                 my $conf = new FS::conf;
963                 my @conf_info = qsearch('conf', { 'name' => 'cancel_credit_type' } );
964                 return 1 if (exists($conf_info[0]) && $conf_info[0]->{Hash}{value});
965                 return 0;
966             }
967         }
968     };
969
970     foreach my $field ( grep $_ !~ /^(setup|recur)_fee$/, @fields ) {
971   
972       if(!exists($href->{$field})) {
973         # shouldn't happen
974         warn "nonexistent part_pkg option: '$field'\n";
975         next;
976       }
977       if ( exists($href->{$field}->{display_if}) ) {
978         my %args = ( 'plan' => $layer ); # anything else?
979         my $display = &{ $href->{$field}->{display_if} }(%args);
980         next if !$display;
981       }
982
983       $html .= '<TR><TD ALIGN="right">'. $href->{$field}{'name'}. '</TD><TD>
984       ';
985   
986       my $format = sub { shift };
987       $format = $href->{$field}{'format'} if exists($href->{$field}{'format'});
988
989       #XXX these should use elements/ fields... (or this whole thing should
990       #just use layer_fields instead of layer_callback)
991   
992       if (exists($dependencies->{$field}) && !$dependencies->{$field}{'are_met'}()) {
993           $html .= q!<span title="!.$dependencies->{$field}{'msg'}.q!">N/A</span>!;
994           
995       } elsif ( ! exists($href->{$field}{'type'}) ) {
996   
997         $html .= qq!<INPUT TYPE="text" NAME="${layer}__$field" VALUE="!.
998                  ( exists($options{$field})
999                      ? &$format($options{$field})
1000                      : $href->{$field}{'default'} ).
1001                  qq!">!;
1002   
1003       } elsif ( $href->{$field}{'type'} eq 'checkbox' ) {
1004   
1005         $html .= qq!<INPUT TYPE="checkbox" NAME="${layer}__$field" VALUE=1 !.
1006                  ( exists($options{$field}) && $options{$field}
1007                    ? ' CHECKED'
1008                    : ''
1009                  ). '>';
1010
1011       } elsif ( $href->{$field}{'type'} =~ /^select-rt-/ ) {
1012
1013         $html .= include('/elements/'.$href->{$field}{'type'}.'.html',
1014                            'name'       => $layer.'__'.$field,
1015                            'curr_value' => $options{$field},
1016                            map { $_ => $href->{$field}{$_} }
1017                              grep { $_ !~ /^(name|type|parse)$/ }
1018                                keys %{ $href->{$field} }
1019                         );
1020
1021       } elsif ( $href->{$field}{'type'} eq 'select-rate' ) {
1022
1023         $html .= include('/elements/select-rate.html',
1024                            'field'      => $layer.'__'.$field,
1025                            'curr_value' => $options{$field},
1026                            map { $_ => $href->{$field}{$_} }
1027                              grep { $_ !~ /^(name|type)$/ }
1028                                keys %{ $href->{$field} }
1029                         );
1030
1031       } elsif ( $href->{$field}{'type'} =~ /^select/ ) {
1032   
1033         $html .= '<SELECT';
1034         $html .= ' MULTIPLE'
1035           if $href->{$field}{'type'} eq 'select_multiple';
1036         $html .= qq! NAME="${layer}__$field">!;
1037
1038         $html .= '<OPTION VALUE="">'. $href->{$field}{'empty_label'}
1039           if exists($href->{$field}{'disable_empty'})
1040                && ! $href->{$field}{'disable_empty'};
1041   
1042         if ( $href->{$field}{'select_table'} ) {
1043           foreach my $record (
1044             qsearch( $href->{$field}{'select_table'},
1045                      $href->{$field}{'select_hash'}   )
1046           ) {
1047             my $value = $record->getfield($href->{$field}{'select_key'});
1048             $html .= qq!<OPTION VALUE="$value"!.
1049                      (  $options{$field} =~ /(^|, *)$value *(,|$)/ #?
1050                           ? ' SELECTED'
1051                           : ''
1052                      ).
1053                      '>'. $record->getfield($href->{$field}{'select_label'});
1054           }
1055         } elsif ( $href->{$field}{'select_options'} ) {
1056           foreach my $key ( keys %{ $href->{$field}{'select_options'} } ) {
1057             my $label = $href->{$field}{'select_options'}{$key};
1058             $html .= qq!<OPTION VALUE="$key"!.
1059                      ( $options{$field} =~ /(^|, *)$key *(,|$)/ #?
1060                          ? ' SELECTED'
1061                          : ''
1062                      ).
1063                      '>'. $label;
1064           }
1065   
1066         } else {
1067           $html .= '<font color="#ff0000">warning: '.
1068                    "don't know how to retreive options for $field select field".
1069                    '</font>';
1070         }
1071         $html .= '</SELECT>';
1072   
1073       } elsif ( $href->{$field}{'type'} eq 'radio' ) {
1074   
1075         my $radio =
1076           qq!<INPUT TYPE="radio" NAME="${layer}__$field"!;
1077   
1078         foreach my $key ( keys %{ $href->{$field}{'options'} } ) {
1079           my $label = $href->{$field}{'options'}{$key};
1080           $html .= qq!$radio VALUE="$key"!.
1081                    ( $options{$field} =~ /(^|, *)$key *(,|$)/ #?
1082                        ? ' CHECKED'
1083                        : ''
1084                    ).
1085                    "> $label<BR>";
1086         }
1087   
1088       }
1089   
1090       $html .= '</TD></TR>';
1091     }
1092     $html .= '</TABLE>';
1093  
1094     $html .= include('/elements/hidden.html',
1095                 field => $layer.'__OPTIONS',
1096                 value => join(',', @fields)
1097              );
1098   
1099     $html;
1100   
1101   };
1102
1103   my %selectlayers = (
1104     field          => 'plan',
1105     options        => [ keys %plan_labels ],
1106     labels         => \%plan_labels,
1107     curr_value     => $object->plan,
1108     layer_callback => $layer_callback,
1109     onchange       => 'aux_planchanged(what);',
1110   );
1111
1112   my $return =
1113     include('/elements/selectlayers.html', %selectlayers, 'layers_only'=>1 ).
1114     '<SCRIPT TYPE="text/javascript">'.
1115       include('/elements/selectlayers.html', %selectlayers, 'js_only'=>1 );
1116
1117 #  $return .=
1118 #    "taxproduct_selectchanged(document.getElementById('taxproduct_select'));\n"
1119 #      if $taxproducts;
1120
1121   $return .= '</SCRIPT>';
1122
1123   $return;
1124
1125 };
1126
1127 my %usage_class = map { ($_->classnum => $_->classname) }
1128                   qsearch('usage_class', {});
1129 $usage_class{setup} = 'Setup';
1130 $usage_class{recur} = 'Recurring';
1131
1132 my %taxproduct_fields = ();
1133 my $end_callback = sub {
1134   my( $cgi, $object, $fields, $opt ) = @_;
1135
1136   @taxproductnums = ( qw( setup recur ), sort (keys %taxproductnums) );
1137
1138   if ( $object->pkgpart ) {
1139     foreach my $usage_class ( '', @taxproductnums ) {
1140       $tax_override{$usage_class} =
1141         join (",", map $_->taxclassnum,
1142                        qsearch( 'part_pkg_taxoverride', {
1143                                   'pkgpart'     => $object->pkgpart,
1144                                   'usage_class' => $usage_class,
1145                               })
1146              );
1147     }
1148   }
1149
1150   %taxproduct_fields =
1151     map { $_ => [ "taxproductnum_$_", 
1152                   { type  => 'select-taxproduct',
1153                     #label => "$usage_class{$_} tax product",
1154                   },
1155                   "tax_override_$_", 
1156                   { type  => 'select-taxoverride' }
1157                 ]
1158         }
1159         @taxproductnums;
1160
1161   $taxproduct_fields{'(default)'} =
1162     [ 'taxproductnum', { type => 'select-taxproduct',
1163                          #label => 'Default tax product',
1164                        },
1165       'tax_override',  { type => 'select-taxoverride' },
1166     ];
1167 };
1168
1169 my $taxproduct_values = sub {
1170   my ($cgi, $object, $flags) = @_;
1171   my $routine =
1172     sub { my $layer = shift;
1173           my @fields = @{$taxproduct_fields{$layer}};
1174           my @values = ();
1175           while( @fields ) {
1176             my $field = shift @fields;
1177             shift @fields;
1178             $field =~ /^taxproductnum_\w+$/ &&
1179               push @values, ( $field => $options{"usage_$field"} );
1180             $field =~ /^tax_override_(\w+)$/ &&
1181               push @values, ( $field => $tax_override{$1} );
1182             $field =~ /^taxproductnum$/ &&
1183               push @values, ( $field => $object->taxproductnum );
1184             $field =~ /^tax_override$/ &&
1185               push @values, ( $field => $tax_override{''} );
1186           }
1187           { (@values) };
1188         };
1189   
1190   my @result = 
1191     map { ( $_ => { &{$routine}($_) } ) } ( '(default)', @taxproductnums );
1192   return({ @result });
1193   
1194 };
1195
1196 my $field_callback = sub {
1197   my ($cgi, $object, $fieldref) = @_;
1198
1199   my $field = $fieldref->{field};
1200   if ($field eq 'taxproductnums') {
1201     $fieldref->{value} = join(',', @taxproductnums);
1202   } elsif ($field eq 'taxproduct_select') {
1203     $fieldref->{options} = [ '(default)', @taxproductnums ];
1204     $fieldref->{labels}  = { ( '(default)' => '(default)' ),
1205                              map {( $_ => ($usage_class{$_} || $_) )}
1206                                @taxproductnums
1207                            };
1208     $fieldref->{layer_fields} = \%taxproduct_fields;
1209     $fieldref->{layer_values_callback} = $taxproduct_values;
1210   } elsif ($field eq 'taxproductnum') { # part_pkg-taxproduct, new style
1211     if ( !$taxproducts ) {
1212       # then make the widget go away
1213       $fieldref->{type} = 'hidden';
1214     }
1215   }
1216 };
1217
1218 my $discountnum_hashref = {
1219                             'disabled' => '',
1220                             'months' => { 'op' => '>', 'value' => 1 },
1221                           };
1222
1223 </%init>