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