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