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