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