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