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