2802ddc33052bf456dc1850f1387ff8d259aba9c
[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     @agent_type = map {$_->typenum} qsearch('agent_type', { 'disabled'=>'' });
611   }
612
613   $options{'suspend_bill'}=1 if $conf->exists('part_pkg-default_suspend_bill');
614
615   &$splice_locale_fields($fields, '', '');
616
617 };
618
619 my $clone_callback = sub {
620   my( $cgi, $object, $fields, $opt ) = @_;
621
622   if ( $cgi->param('pkgnum') ) {
623
624     my $cust_pkg = qsearchs('cust_pkg', { 'pkgnum' => $cgi->param('pkgnum') } );
625     $object->agentnum( $cust_pkg->cust_main->agentnum );
626
627     $opt->{action} = 'Custom';
628
629     #my $part_pkg = $clone_part_pkg->clone;
630     #this is all clone does anyway
631     $object->custom('Y');
632
633     $object->disabled('Y');
634
635   } else { #when explicitly cloning, not customizing
636
637     (@agent_type) =
638       map {$_->typenum} qsearch('type_pkgs',{ 'pkgpart' => $object->pkgpart } );
639
640   }
641
642   set_report_option( $cgi, $object, $fields);
643
644   %options = $object->options;
645
646   $object->set($_ => $options{$_})
647     foreach (qw( setup_fee recur_fee disable_line_item_date_ranges ));
648
649   $recur_disabled = $object->freq ? 0 : 1;
650
651   &$splice_locale_fields(
652     $fields,
653     '',
654     sub {
655       my $locale = shift;
656       my $part_pkg_msgcat = $object->part_pkg_msgcat($locale);
657       $part_pkg_msgcat ? $part_pkg_msgcat->pkg : '';
658     }
659   );
660 };
661
662 my $discount_error_callback = sub {
663   my( $cgi, $object ) = @_;
664   map {
665         if ( /^discountnum(\d+)$/ &&
666              ( my $discountnum = $cgi->param("discountnum$1") ) )
667         {
668           new FS::part_pkg_discount {
669             'pkgpart'     => $object->pkgpart,
670             'discountnum' => $discountnum,
671           };
672         } else {
673           ();
674         }
675       }
676   $cgi->param;
677 };
678
679 my $m2_error_callback_maker = sub {
680   my $link_type = shift; #yay closures
681   return sub {
682     my( $cgi, $object ) = @_;
683     map {
684
685           if ( /^${link_type}_dst_pkgpart(\d+)$/ &&
686                ( my $dst = $cgi->param("${link_type}_dst_pkgpart$1") ) )
687           {
688
689             my $hidden = $cgi->param("${link_type}_dst_pkgpart__hidden$1")
690                          || '';
691             new FS::part_pkg_link {
692               'link_type'   => $link_type,
693               'src_pkgpart' => $object->pkgpart,
694               'dst_pkgpart' => $dst,
695               'hidden'      => $hidden,
696             };
697           } else {
698             ();
699           }
700         }
701     $cgi->param;
702   };
703 };
704
705 my $javascript = <<'END';
706   <SCRIPT TYPE="text/javascript">
707
708     function freq_changed(what) {
709       var freq = what.options[what.selectedIndex].value;
710
711       if ( freq == '0' ) {
712         what.form.recur_fee.disabled = true;
713         what.form.recur_fee.style.backgroundColor = '#dddddd';
714         what.form.recur_show_zero.disabled = true;
715         //what.form.recur_show_zero.style.backgroundColor= '#dddddd';
716       } else {
717         what.form.recur_fee.disabled = false;
718         what.form.recur_fee.style.backgroundColor = '#ffffff';
719         recur_changed( what.form.recur_fee );
720         //what.form.recur_show_zero.style.backgroundColor= '#ffffff';
721       }
722
723     }
724
725     function setup_changed(what) {
726       var setup = what.value;
727       if ( parseFloat(setup) == 0 ) {
728         what.form.setup_show_zero.disabled = false;
729       } else {
730         what.form.setup_show_zero.disabled = true;
731       }
732     }
733
734     function recur_changed(what) {
735       var recur = what.value;
736       if ( parseFloat(recur) == 0 ) {
737         what.form.recur_show_zero.disabled = false;
738       } else {
739         what.form.recur_show_zero.disabled = true;
740       }
741     }
742
743     function agent_changed(what) {
744
745       var agentnum;
746       if ( what.type == 'select-one' ) {
747         agentnum = what.options[what.selectedIndex].value;
748       } else {
749         agentnum = what.value;
750       }
751
752       if ( agentnum == 0 ) {
753         what.form.agent_type.disabled = false;
754         //what.form.agent_type.style.backgroundColor = '#ffffff';
755         what.form.agent_type.style.visibility = '';
756       } else {
757         what.form.agent_type.disabled = true;
758         //what.form.agent_type.style.backgroundColor = '#dddddd';
759         what.form.agent_type.style.visibility = 'hidden';
760       }
761
762     }
763
764     function aux_planchanged(what) { //?
765
766       var plan = what.options[what.selectedIndex].value;
767       var table = document.getElementById('TableNumber6') // XXX NOT ROBUST
768
769       if ( plan == 'flat' || plan == 'prorate' || plan == 'subscription' ) {
770         //table.disabled = false;
771         table.style.visibility = '';
772       } else {
773         //table.disabled = true;
774         table.style.visibility = 'hidden';
775       }
776
777     }
778
779     // some magic to make "supplemental packages" less obvious
780     var supp_pkg_rows = [];
781     function show_supp_pkgs_click() {
782       supp_pkg_rows[0].style.display = '';
783       this.onclick = '';
784       this.style.backgroundColor = '';
785       this.style.border = '';
786       this.style.padding = '';
787     }
788
789     function hide_supp_pkgs() {
790       var all_selects = document.getElementsByTagName('select');
791       for (var i=0; i < all_selects.length; i++) {
792         if ( all_selects[i].id.match(/^supp_dst_pkgpart/) ) {
793           supp_pkg_rows.push( all_selects[i].parentNode.parentNode );
794         }
795       }
796       if ( supp_pkg_rows.length == 1 ) {
797         // there are none configured, so hide the row to create a new one
798         supp_pkg_rows[0].style.display = 'none';
799         var button = document.getElementById('show_supp_pkgs');
800         button.onclick = show_supp_pkgs_click;
801         button.style.backgroundColor = '#cccccc';
802         button.style.border = '1px solid #7e0079';
803         button.style.padding = '1px';
804       }
805     }
806
807     function finish_edit_fcc(id) {
808       cClick();
809       show_fcc_options(id); // refresh the display
810     }
811
812 END
813
814 my $warning =
815   'Changing the setup or recurring fee will create a new package definition. '.
816   'Continue?';
817
818 $javascript .= "function confirm_submit(f) {";
819 if ( $conf->exists('part_pkg-lineage') ) {
820   $javascript .= "
821
822     var fields = Array('setup_fee','recur_fee');
823     for(var i=0; i < fields.length; i++) {
824         if ( f[fields[i]].value != f[fields[i]].defaultValue ) {
825             return confirm('$warning');
826         }
827     }
828 ";
829 }
830 $javascript .= "
831   return true;
832 }
833 </SCRIPT>";
834
835 tie my %plans, 'Tie::IxHash', %{ FS::part_pkg::plan_info() };
836
837 tie my %plan_labels, 'Tie::IxHash',
838   map {  $_ => ( $plans{$_}->{'shortname'} || $plans{$_}->{'name'} ) }
839       keys %plans;
840
841 my $html_bottom = sub {
842   my( $object ) = @_;
843
844   #warn join("\n", map { "$_: $options{$_}" } keys %options ). "\n";
845
846   my $layer_callback = sub {
847   
848     my $layer = shift;
849     my $html = ntable("#cccccc",2);
850   
851     #$html .= '
852     #  <TR>
853     #    <TD ALIGN="right">Recurring fee frequency </TD>
854     #    <TD><SELECT NAME="freq">
855     #';
856     #
857     #my @freq = keys %freq;
858     #@freq = grep { /^\d+$/ } @freq
859   #XXX this bit#  #  if exists($plans{$layer}->{'freq'}) && $plans{$layer}->{'freq'} eq 'm';
860     #foreach my $freq ( @freq ) {
861     #  $html .= qq(<OPTION VALUE="$freq");
862     #  $html .= ' SELECTED' if $freq eq $part_pkg->freq;
863     #  $html .= ">$freq{$freq}";
864     #}
865
866    #$html .= '</SELECT></TD></TR>';
867   
868     my $href = $plans{$layer}->{'fields'};
869     my @fields;
870     if ( $plans{$layer}->{'fieldorder'} ) {
871       @fields = @{ $plans{$layer}->{'fieldorder'} };
872     } else {
873       warn "FS::part_pkg::$layer has no fieldorder.\n";
874       @fields = keys %$href;
875     }
876     
877     # hash of dependencies for each of the Pricing Plan fields.
878     # make sure NOT to use double-quotes inside the 'msg' value.
879     my $dependencies = {
880         'unused_credit_suspend' => {
881             'msg'       => q|You must set the 'suspend_credit_type' option in Configuration->Settings to gain access to this option.|,
882             'are_met'   => sub{
883                 my $conf = new FS::conf;
884                 my @conf_info = qsearch('conf', { 'name' => 'suspend_credit_type' } );
885                 return 1 if (exists($conf_info[0]) && $conf_info[0]->{Hash}{value});
886                 return 0;
887             }
888         },
889         'unused_credit_cancel' => {
890             'msg'       => q|You must set the 'cancel_credit_type' option in Configuration->Settings to gain access to this option.|,
891             'are_met'   => sub{
892                 my $conf = new FS::conf;
893                 my @conf_info = qsearch('conf', { 'name' => 'cancel_credit_type' } );
894                 return 1 if (exists($conf_info[0]) && $conf_info[0]->{Hash}{value});
895                 return 0;
896             }
897         }
898     };
899
900     foreach my $field ( grep $_ !~ /^(setup|recur)_fee$/, @fields ) {
901   
902       if(!exists($href->{$field})) {
903         # shouldn't happen
904         warn "nonexistent part_pkg option: '$field'\n";
905         next;
906       }
907       if ( exists($href->{$field}->{display_if}) ) {
908         my %args = ( 'plan' => $layer ); # anything else?
909         my $display = &{ $href->{$field}->{display_if} }(%args);
910         next if !$display;
911       }
912
913       $html .= '<TR><TD ALIGN="right">'. $href->{$field}{'name'}. '</TD><TD>
914       ';
915   
916       my $format = sub { shift };
917       $format = $href->{$field}{'format'} if exists($href->{$field}{'format'});
918
919       #XXX these should use elements/ fields... (or this whole thing should
920       #just use layer_fields instead of layer_callback)
921   
922       if (exists($dependencies->{$field}) && !$dependencies->{$field}{'are_met'}()) {
923           $html .= q!<span title="!.$dependencies->{$field}{'msg'}.q!">N/A</span>!;
924           
925       } elsif ( ! exists($href->{$field}{'type'}) ) {
926   
927         $html .= qq!<INPUT TYPE="text" NAME="${layer}__$field" VALUE="!.
928                  ( exists($options{$field})
929                      ? &$format($options{$field})
930                      : $href->{$field}{'default'} ).
931                  qq!">!;
932   
933       } elsif ( $href->{$field}{'type'} eq 'checkbox' ) {
934   
935         $html .= qq!<INPUT TYPE="checkbox" NAME="${layer}__$field" VALUE=1 !.
936                  ( exists($options{$field}) && $options{$field}
937                    ? ' CHECKED'
938                    : ''
939                  ). '>';
940
941       } elsif ( $href->{$field}{'type'} eq 'select-rate' ) {
942
943         $html .= include('/elements/select-rate.html',
944                            'field'      => $layer.'__'.$field,
945                            'curr_value' => $options{$field},
946                            map { $_ => $href->{$field}{$_} }
947                              grep { $_ !~ /^(name|type)$/ }
948                                keys %{ $href->{$field} }
949                         );
950
951       } elsif ( $href->{$field}{'type'} =~ /^select/ ) {
952   
953         $html .= '<SELECT';
954         $html .= ' MULTIPLE'
955           if $href->{$field}{'type'} eq 'select_multiple';
956         $html .= qq! NAME="${layer}__$field">!;
957
958         $html .= '<OPTION VALUE="">'. $href->{$field}{'empty_label'}
959           if exists($href->{$field}{'disable_empty'})
960                && ! $href->{$field}{'disable_empty'};
961   
962         if ( $href->{$field}{'select_table'} ) {
963           foreach my $record (
964             qsearch( $href->{$field}{'select_table'},
965                      $href->{$field}{'select_hash'}   )
966           ) {
967             my $value = $record->getfield($href->{$field}{'select_key'});
968             $html .= qq!<OPTION VALUE="$value"!.
969                      (  $options{$field} =~ /(^|, *)$value *(,|$)/ #?
970                           ? ' SELECTED'
971                           : ''
972                      ).
973                      '>'. $record->getfield($href->{$field}{'select_label'});
974           }
975         } elsif ( $href->{$field}{'select_options'} ) {
976           foreach my $key ( keys %{ $href->{$field}{'select_options'} } ) {
977             my $label = $href->{$field}{'select_options'}{$key};
978             $html .= qq!<OPTION VALUE="$key"!.
979                      ( $options{$field} =~ /(^|, *)$key *(,|$)/ #?
980                          ? ' SELECTED'
981                          : ''
982                      ).
983                      '>'. $label;
984           }
985   
986         } else {
987           $html .= '<font color="#ff0000">warning: '.
988                    "don't know how to retreive options for $field select field".
989                    '</font>';
990         }
991         $html .= '</SELECT>';
992   
993       } elsif ( $href->{$field}{'type'} eq 'radio' ) {
994   
995         my $radio =
996           qq!<INPUT TYPE="radio" NAME="${layer}__$field"!;
997   
998         foreach my $key ( keys %{ $href->{$field}{'options'} } ) {
999           my $label = $href->{$field}{'options'}{$key};
1000           $html .= qq!$radio VALUE="$key"!.
1001                    ( $options{$field} =~ /(^|, *)$key *(,|$)/ #?
1002                        ? ' CHECKED'
1003                        : ''
1004                    ).
1005                    "> $label<BR>";
1006         }
1007   
1008       }
1009   
1010       $html .= '</TD></TR>';
1011     }
1012     $html .= '</TABLE>';
1013  
1014     $html .= include('/elements/hidden.html',
1015                 field => $layer.'__OPTIONS',
1016                 value => join(',', @fields)
1017              );
1018   
1019     $html;
1020   
1021   };
1022
1023   my %selectlayers = (
1024     field          => 'plan',
1025     options        => [ keys %plan_labels ],
1026     labels         => \%plan_labels,
1027     curr_value     => $object->plan,
1028     layer_callback => $layer_callback,
1029     onchange       => 'aux_planchanged(what);',
1030   );
1031
1032   my $return =
1033     include('/elements/selectlayers.html', %selectlayers, 'layers_only'=>1 ).
1034     '<SCRIPT TYPE="text/javascript">'.
1035       include('/elements/selectlayers.html', %selectlayers, 'js_only'=>1 );
1036
1037   $return .=
1038     "taxproduct_selectchanged(document.getElementById('taxproduct_select'));\n"
1039       if $taxproducts;
1040
1041   $return .= '</SCRIPT>';
1042
1043   $return;
1044
1045 };
1046
1047 my %usage_class = map { ($_->classnum => $_->classname) }
1048                   qsearch('usage_class', {});
1049 $usage_class{setup} = 'Setup';
1050 $usage_class{recur} = 'Recurring';
1051
1052 my %taxproduct_fields = ();
1053 my $end_callback = sub {
1054   my( $cgi, $object, $fields, $opt ) = @_;
1055
1056   @taxproductnums = ( qw( setup recur ), sort (keys %taxproductnums) );
1057
1058   if ( $object->pkgpart ) {
1059     foreach my $usage_class ( '', @taxproductnums ) {
1060       $tax_override{$usage_class} =
1061         join (",", map $_->taxclassnum,
1062                        qsearch( 'part_pkg_taxoverride', {
1063                                   'pkgpart'     => $object->pkgpart,
1064                                   'usage_class' => $usage_class,
1065                               })
1066              );
1067     }
1068   }
1069
1070   %taxproduct_fields =
1071     map { $_ => [ "taxproductnum_$_", 
1072                   { type  => 'select-taxproduct',
1073                     #label => "$usage_class{$_} tax product",
1074                   },
1075                   "tax_override_$_", 
1076                   { type  => 'select-taxoverride' }
1077                 ]
1078         }
1079         @taxproductnums;
1080
1081   $taxproduct_fields{'(default)'} =
1082     [ 'taxproductnum', { type => 'select-taxproduct',
1083                          #label => 'Default tax product',
1084                        },
1085       'tax_override',  { type => 'select-taxoverride' },
1086     ];
1087 };
1088
1089 my $taxproduct_values = sub {
1090   my ($cgi, $object, $flags) = @_;
1091   my $routine =
1092     sub { my $layer = shift;
1093           my @fields = @{$taxproduct_fields{$layer}};
1094           my @values = ();
1095           while( @fields ) {
1096             my $field = shift @fields;
1097             shift @fields;
1098             $field =~ /^taxproductnum_\w+$/ &&
1099               push @values, ( $field => $options{"usage_$field"} );
1100             $field =~ /^tax_override_(\w+)$/ &&
1101               push @values, ( $field => $tax_override{$1} );
1102             $field =~ /^taxproductnum$/ &&
1103               push @values, ( $field => $object->taxproductnum );
1104             $field =~ /^tax_override$/ &&
1105               push @values, ( $field => $tax_override{''} );
1106           }
1107           { (@values) };
1108         };
1109   
1110   my @result = 
1111     map { ( $_ => { &{$routine}($_) } ) } ( '(default)', @taxproductnums );
1112   return({ @result });
1113   
1114 };
1115
1116 my $field_callback = sub {
1117   my ($cgi, $object, $fieldref) = @_;
1118
1119   my $field = $fieldref->{field};
1120   if ($field eq 'taxproductnums') {
1121     $fieldref->{value} = join(',', @taxproductnums);
1122   } elsif ($field eq 'taxproduct_select') {
1123     $fieldref->{options} = [ '(default)', @taxproductnums ];
1124     $fieldref->{labels}  = { ( '(default)' => '(default)' ),
1125                              map {( $_ => ($usage_class{$_} || $_) )}
1126                                @taxproductnums
1127                            };
1128     $fieldref->{layer_fields} = \%taxproduct_fields;
1129     $fieldref->{layer_values_callback} = $taxproduct_values;
1130   }
1131 };
1132
1133 my $discountnum_hashref = {
1134                             'disabled' => '',
1135                             'months' => { 'op' => '>', 'value' => 1 },
1136                           };
1137
1138 </%init>