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