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