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