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