fix recurring fee edit on clone/customize, RT#72958
[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      => 'input-locale-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 $error_callback = sub {
438   my($cgi, $object, $fields, $opt ) = @_;
439
440   (@agent_type) = $cgi->param('agent_type');
441
442   $opt->{action} = 'Custom' if $cgi->param('pkgnum');
443
444   $setup_show_zero_disabled = ($cgi->param('setup_fee') > 0) ? 1 : 0;
445
446   $recur_disabled = $cgi->param('freq') ? 0 : 1;
447   $recur_show_zero_disabled =
448     $cgi->param('freq')
449       ? $cgi->param('recur_fee') > 0 ? 1 : 0
450       : 1;
451
452   foreach ($cgi->param) {
453     /^usage_taxproductnum_(\d+)$/ && ($taxproductnums{$1} = 1);
454   }
455   $tax_override{''} = $cgi->param('tax_override');
456   $tax_override{$_} = $cgi->param('tax_override_$_')
457     foreach(grep { /^tax_override_(\w+)$/ } $cgi->param);
458
459   #some false laziness w/process
460   $cgi->param('plan') =~ /^(\w+)$/ or die 'unparsable plan';
461   my $plan = $1;
462   my $options = $cgi->param($plan."__OPTIONS");
463   my @options = split(',', $options);
464   %options =
465     map { my $optionname = $_;
466           my $param = $plan."__$optionname";
467           my $value = join(', ', $cgi->param($param));
468           ( $optionname => $value );
469         }
470         @options;
471
472   $object->set($_ => scalar($cgi->param($_)) )
473     foreach (qw( setup_fee recur_fee disable_line_item_date_ranges ));
474
475   $pkgpart = $object->pkgpart;
476
477 };
478
479 my $new_hashref_callback = sub { { 'plan' => 'flat' }; };
480
481 my $new_object_callback = sub {
482   my( $cgi, $hashref, $fields, $opt ) = @_;
483
484   my $part_pkg = FS::part_pkg->new( $hashref );
485   $part_pkg->set($_ => '0')
486     foreach (qw( setup_fee recur_fee disable_line_item_date_ranges ));
487
488   $part_pkg;
489
490 };
491
492 sub set_report_option {
493   my($cgi, $object, $fields ) = @_; #, $opt
494
495   my @report_option = ();
496   foreach ($object->options) {
497     /^usage_taxproductnum_(\d+)$/ && ($taxproductnums{$1} = 1);
498     /^report_option_(\d+)$/ && (push @report_option, $1);
499   }
500   foreach ($object->part_pkg_taxoverride) {
501     $taxproductnums{$_->usage_class} = 1
502       if $_->usage_class;
503   }
504
505   $cgi->param('report_option', join(',', @report_option));
506   foreach my $field ( @$fields ) {
507     next unless ( 
508       ref($field) eq 'HASH' &&
509       $field->{field} &&
510       $field->{field} eq 'report_option'
511     );
512     #$field->{curr_value} = join(',', @report_option);
513     $field->{value} = join(',', @report_option);
514   }
515
516 }
517
518 my $edit_callback = sub {
519   my( $cgi, $object, $fields, $opt ) = @_;
520
521   $setup_show_zero_disabled = ($object->option('setup_fee') > 0) ? 1 : 0;
522
523   $recur_disabled = $object->freq ? 0 : 1;
524
525   $recur_show_zero_disabled =
526     $object->freq
527       ? $object->option('recur_fee') > 0 ? 1 : 0
528       : 1;
529
530   (@agent_type) =
531     map {$_->typenum} qsearch('type_pkgs', { 'pkgpart' => $object->pkgpart } );
532
533   set_report_option( $cgi, $object, $fields);
534
535   %options = $object->options;
536
537   $object->set($_ => $object->option($_, 1))
538     foreach (qw( setup_fee recur_fee disable_line_item_date_ranges ));
539
540   $pkgpart = $object->pkgpart;
541
542 };
543
544 my $new_callback = sub {
545   my( $cgi, $object, $fields ) = @_;
546
547   my $conf = new FS::Conf; 
548
549   if ( $conf->exists('agent_defaultpkg') ) {
550     @agent_type = map {$_->typenum} qsearch('agent_type', { 'disabled'=>'' });
551   }
552
553   $options{'suspend_bill'}=1 if $conf->exists('part_pkg-default_suspend_bill');
554
555 };
556
557 my $clone_callback = sub {
558   my( $cgi, $object, $fields, $opt ) = @_;
559
560   if ( $cgi->param('pkgnum') ) {
561
562     my $cust_pkg = qsearchs('cust_pkg', { 'pkgnum' => scalar($cgi->param('pkgnum')) } );
563     $object->agentnum( $cust_pkg->cust_main->agentnum );
564
565     $opt->{action} = 'Custom';
566
567     #my $part_pkg = $clone_part_pkg->clone;
568     #this is all clone does anyway
569     $object->custom('Y');
570
571     $object->disabled('Y');
572
573   } else { #when explicitly cloning, not customizing
574
575     (@agent_type) =
576       map {$_->typenum} qsearch('type_pkgs',{ 'pkgpart' => $object->pkgpart } );
577
578   }
579
580   set_report_option( $cgi, $object, $fields);
581
582   %options = $object->options;
583
584   $object->set($_ => $options{$_})
585     foreach (qw( setup_fee recur_fee disable_line_item_date_ranges ));
586
587   $recur_disabled = $object->freq ? 0 : 1;
588
589   $recur_show_zero_disabled =
590     $object->freq
591       ? $object->option('recur_fee') > 0 ? 1 : 0
592       : 1;
593
594 };
595
596 my $discount_error_callback = sub {
597   my( $cgi, $object ) = @_;
598   map {
599         if ( /^discountnum(\d+)$/ &&
600              ( my $discountnum = $cgi->param("discountnum$1") ) )
601         {
602           new FS::part_pkg_discount {
603             'pkgpart'     => $object->pkgpart,
604             'discountnum' => $discountnum,
605           };
606         } else {
607           ();
608         }
609       }
610   $cgi->param;
611 };
612
613 my $m2_error_callback_maker = sub {
614   my $link_type = shift; #yay closures
615   return sub {
616     my( $cgi, $object ) = @_;
617     map {
618
619           if ( /^${link_type}_dst_pkgpart(\d+)$/ &&
620                ( my $dst = $cgi->param("${link_type}_dst_pkgpart$1") ) )
621           {
622
623             my $hidden = $cgi->param("${link_type}_dst_pkgpart__hidden$1")
624                          || '';
625             new FS::part_pkg_link {
626               'link_type'   => $link_type,
627               'src_pkgpart' => $object->pkgpart,
628               'dst_pkgpart' => $dst,
629               'hidden'      => $hidden,
630             };
631           } else {
632             ();
633           }
634         }
635     $cgi->param;
636   };
637 };
638
639 my $javascript = <<'END';
640   <SCRIPT TYPE="text/javascript">
641
642     function freq_changed(what) {
643       var freq = what.options[what.selectedIndex].value;
644
645       if ( freq == '0' ) {
646         what.form.recur_fee.disabled = true;
647         what.form.recur_fee.style.backgroundColor = '#dddddd';
648         what.form.recur_show_zero.disabled = true;
649         //what.form.recur_show_zero.style.backgroundColor= '#dddddd';
650       } else {
651         what.form.recur_fee.disabled = false;
652         what.form.recur_fee.style.backgroundColor = '#ffffff';
653         recur_changed( what.form.recur_fee );
654         //what.form.recur_show_zero.style.backgroundColor= '#ffffff';
655       }
656
657     }
658
659     function setup_changed(what) {
660       var setup = what.value;
661       if ( parseFloat(setup) == 0 ) {
662         what.form.setup_show_zero.disabled = false;
663       } else {
664         what.form.setup_show_zero.disabled = true;
665       }
666     }
667
668     function recur_changed(what) {
669       var recur = what.value;
670       if ( parseFloat(recur) == 0 ) {
671         what.form.recur_show_zero.disabled = false;
672       } else {
673         what.form.recur_show_zero.disabled = true;
674       }
675     }
676
677     function agent_changed(what) {
678
679       var agentnum;
680       if ( what.type == 'select-one' ) {
681         agentnum = what.options[what.selectedIndex].value;
682       } else {
683         agentnum = what.value;
684       }
685
686       if ( agentnum == 0 ) {
687         what.form.agent_type.disabled = false;
688         //what.form.agent_type.style.backgroundColor = '#ffffff';
689         what.form.agent_type.style.visibility = '';
690       } else {
691         what.form.agent_type.disabled = true;
692         //what.form.agent_type.style.backgroundColor = '#dddddd';
693         what.form.agent_type.style.visibility = 'hidden';
694       }
695
696     }
697
698     function aux_planchanged(what) { //?
699
700       var plan = what.options[what.selectedIndex].value;
701       var table = document.getElementById('TableNumber6') // XXX NOT ROBUST
702
703       if ( plan == 'flat' || plan == 'prorate' || plan == 'subscription' ) {
704         //table.disabled = false;
705         table.style.visibility = '';
706       } else {
707         //table.disabled = true;
708         table.style.visibility = 'hidden';
709       }
710
711     }
712
713     // some magic to make "supplemental packages" less obvious
714     var supp_pkg_rows = [];
715     function show_supp_pkgs_click() {
716       supp_pkg_rows[0].style.display = '';
717       this.onclick = '';
718       this.style.backgroundColor = '';
719       this.style.border = '';
720       this.style.padding = '';
721     }
722
723     function hide_supp_pkgs() {
724       var all_selects = document.getElementsByTagName('select');
725       for (var i=0; i < all_selects.length; i++) {
726         if ( all_selects[i].id.match(/^supp_dst_pkgpart/) ) {
727           supp_pkg_rows.push( all_selects[i].parentNode.parentNode );
728         }
729       }
730       if ( supp_pkg_rows.length == 1 ) {
731         // there are none configured, so hide the row to create a new one
732         supp_pkg_rows[0].style.display = 'none';
733         var button = document.getElementById('show_supp_pkgs');
734         button.onclick = show_supp_pkgs_click;
735         button.style.backgroundColor = '#cccccc';
736         button.style.border = '1px solid #7e0079';
737         button.style.padding = '1px';
738       }
739     }
740
741     function finish_edit_fcc(id) {
742       cClick();
743       show_fcc_options(id); // refresh the display
744     }
745
746 END
747
748 my $warning =
749   'Changing the setup or recurring fee will create a new package definition. '.
750   'Continue?';
751
752 $javascript .= "function confirm_submit(f) {";
753 if ( $conf->exists('part_pkg-lineage') ) {
754   $javascript .= "
755
756     var fields = Array('setup_fee','recur_fee');
757     for(var i=0; i < fields.length; i++) {
758         if ( f[fields[i]].value != f[fields[i]].defaultValue ) {
759             return confirm('$warning');
760         }
761     }
762 ";
763 }
764 $javascript .= "
765   return true;
766 }
767 </SCRIPT>";
768
769 tie my %plans, 'Tie::IxHash', %{ FS::part_pkg::plan_info() };
770
771 tie my %plan_labels, 'Tie::IxHash',
772   map {  $_ => ( $plans{$_}->{'shortname'} || $plans{$_}->{'name'} ) }
773       keys %plans;
774
775 my $html_bottom = sub {
776   my( $object ) = @_;
777
778   #warn join("\n", map { "$_: $options{$_}" } keys %options ). "\n";
779
780   my $layer_callback = sub {
781   
782     my $layer = shift;
783     my $html = ntable("#cccccc",2);
784   
785     #$html .= '
786     #  <TR>
787     #    <TD ALIGN="right">Recurring fee frequency </TD>
788     #    <TD><SELECT NAME="freq">
789     #';
790     #
791     #my @freq = keys %freq;
792     #@freq = grep { /^\d+$/ } @freq
793   #XXX this bit#  #  if exists($plans{$layer}->{'freq'}) && $plans{$layer}->{'freq'} eq 'm';
794     #foreach my $freq ( @freq ) {
795     #  $html .= qq(<OPTION VALUE="$freq");
796     #  $html .= ' SELECTED' if $freq eq $part_pkg->freq;
797     #  $html .= ">$freq{$freq}";
798     #}
799
800    #$html .= '</SELECT></TD></TR>';
801   
802     my $href = $plans{$layer}->{'fields'};
803     my @fields;
804     if ( $plans{$layer}->{'fieldorder'} ) {
805       @fields = @{ $plans{$layer}->{'fieldorder'} };
806     } else {
807       warn "FS::part_pkg::$layer has no fieldorder.\n";
808       @fields = keys %$href;
809     }
810     
811     # hash of dependencies for each of the Pricing Plan fields.
812     # make sure NOT to use double-quotes inside the 'msg' value.
813     my $dependencies = {
814         'unused_credit_suspend' => {
815             'msg'       => q|You must set the 'suspend_credit_type' option in Configuration->Settings to gain access to this option.|,
816             'are_met'   => sub{
817                 my $conf = new FS::conf;
818                 my @conf_info = qsearch('conf', { 'name' => 'suspend_credit_type' } );
819                 return 1 if (exists($conf_info[0]) && $conf_info[0]->{Hash}{value});
820                 return 0;
821             }
822         },
823         'unused_credit_cancel' => {
824             'msg'       => q|You must set the 'cancel_credit_type' option in Configuration->Settings to gain access to this option.|,
825             'are_met'   => sub{
826                 my $conf = new FS::conf;
827                 my @conf_info = qsearch('conf', { 'name' => 'cancel_credit_type' } );
828                 return 1 if (exists($conf_info[0]) && $conf_info[0]->{Hash}{value});
829                 return 0;
830             }
831         }
832     };
833
834     foreach my $field ( grep $_ !~ /^(setup|recur)_fee$/, @fields ) {
835   
836       if(!exists($href->{$field})) {
837         # shouldn't happen
838         warn "nonexistent part_pkg option: '$field'\n";
839         next;
840       }
841       if ( exists($href->{$field}->{display_if}) ) {
842         my %args = ( 'plan' => $layer ); # anything else?
843         my $display = &{ $href->{$field}->{display_if} }(%args);
844         next if !$display;
845       }
846
847       $html .= '<TR><TD ALIGN="right">'. $href->{$field}{'name'}. '</TD><TD>
848       ';
849   
850       my $format = sub { shift };
851       $format = $href->{$field}{'format'} if exists($href->{$field}{'format'});
852
853       #XXX these should use elements/ fields... (or this whole thing should
854       #just use layer_fields instead of layer_callback)
855   
856       if (exists($dependencies->{$field}) && !$dependencies->{$field}{'are_met'}()) {
857           $html .= q!<span title="!.$dependencies->{$field}{'msg'}.q!">N/A</span>!;
858           
859       } elsif ( ! exists($href->{$field}{'type'}) ) {
860   
861         $html .= qq!<INPUT TYPE="text" NAME="${layer}__$field" VALUE="!.
862                  ( exists($options{$field})
863                      ? &$format($options{$field})
864                      : $href->{$field}{'default'} ).
865                  qq!">!;
866   
867       } elsif ( $href->{$field}{'type'} eq 'checkbox' ) {
868   
869         $html .= qq!<INPUT TYPE="checkbox" NAME="${layer}__$field" VALUE=1 !.
870                  ( exists($options{$field}) && $options{$field}
871                    ? ' CHECKED'
872                    : ''
873                  ). '>';
874
875       } elsif ( $href->{$field}{'type'} =~ /^select-rt-/ ) {
876
877         $html .= include('/elements/'.$href->{$field}{'type'}.'.html',
878                            'name'       => $layer.'__'.$field,
879                            'curr_value' => $options{$field},
880                            map { $_ => $href->{$field}{$_} }
881                              grep { $_ !~ /^(name|type|parse)$/ }
882                                keys %{ $href->{$field} }
883                         );
884
885       } elsif ( $href->{$field}{'type'} eq 'select-rate' ) {
886
887         $html .= include('/elements/select-rate.html',
888                            'field'      => $layer.'__'.$field,
889                            'curr_value' => $options{$field},
890                            map { $_ => $href->{$field}{$_} }
891                              grep { $_ !~ /^(name|type)$/ }
892                                keys %{ $href->{$field} }
893                         );
894
895       } elsif ( $href->{$field}{'type'} =~ /^select/ ) {
896   
897         $html .= '<SELECT';
898         $html .= ' MULTIPLE'
899           if $href->{$field}{'type'} eq 'select_multiple';
900         $html .= qq! NAME="${layer}__$field">!;
901
902         $html .= '<OPTION VALUE="">'. $href->{$field}{'empty_label'}
903           if exists($href->{$field}{'disable_empty'})
904                && ! $href->{$field}{'disable_empty'};
905   
906         if ( $href->{$field}{'select_table'} ) {
907           foreach my $record (
908             qsearch( $href->{$field}{'select_table'},
909                      $href->{$field}{'select_hash'}   )
910           ) {
911             my $value = $record->getfield($href->{$field}{'select_key'});
912             $html .= qq!<OPTION VALUE="$value"!.
913                      (  $options{$field} =~ /(^|, *)$value *(,|$)/ #?
914                           ? ' SELECTED'
915                           : ''
916                      ).
917                      '>'. $record->getfield($href->{$field}{'select_label'});
918           }
919         } elsif ( $href->{$field}{'select_options'} ) {
920           foreach my $key ( keys %{ $href->{$field}{'select_options'} } ) {
921             my $label = $href->{$field}{'select_options'}{$key};
922             $html .= qq!<OPTION VALUE="$key"!.
923                      ( $options{$field} =~ /(^|, *)$key *(,|$)/ #?
924                          ? ' SELECTED'
925                          : ''
926                      ).
927                      '>'. $label;
928           }
929   
930         } else {
931           $html .= '<font color="#ff0000">warning: '.
932                    "don't know how to retreive options for $field select field".
933                    '</font>';
934         }
935         $html .= '</SELECT>';
936   
937       } elsif ( $href->{$field}{'type'} eq 'radio' ) {
938   
939         my $radio =
940           qq!<INPUT TYPE="radio" NAME="${layer}__$field"!;
941   
942         foreach my $key ( keys %{ $href->{$field}{'options'} } ) {
943           my $label = $href->{$field}{'options'}{$key};
944           $html .= qq!$radio VALUE="$key"!.
945                    ( $options{$field} =~ /(^|, *)$key *(,|$)/ #?
946                        ? ' CHECKED'
947                        : ''
948                    ).
949                    "> $label<BR>";
950         }
951   
952       }
953   
954       $html .= '</TD></TR>';
955     }
956     $html .= '</TABLE>';
957  
958     $html .= include('/elements/hidden.html',
959                 field => $layer.'__OPTIONS',
960                 value => join(',', @fields)
961              );
962   
963     $html;
964   
965   };
966
967   my %selectlayers = (
968     field          => 'plan',
969     options        => [ keys %plan_labels ],
970     labels         => \%plan_labels,
971     curr_value     => $object->plan,
972     layer_callback => $layer_callback,
973     onchange       => 'aux_planchanged(what);',
974   );
975
976   my $return =
977     include('/elements/selectlayers.html', %selectlayers, 'layers_only'=>1 ).
978     '<SCRIPT TYPE="text/javascript">'.
979       include('/elements/selectlayers.html', %selectlayers, 'js_only'=>1 );
980
981   $return .=
982     "taxproduct_selectchanged(document.getElementById('taxproduct_select'));\n"
983       if $taxproducts;
984
985   $return .= '</SCRIPT>';
986
987   $return;
988
989 };
990
991 my %usage_class = map { ($_->classnum => $_->classname) }
992                   qsearch('usage_class', {});
993 $usage_class{setup} = 'Setup';
994 $usage_class{recur} = 'Recurring';
995
996 my %taxproduct_fields = ();
997 my $end_callback = sub {
998   my( $cgi, $object, $fields, $opt ) = @_;
999
1000   @taxproductnums = ( qw( setup recur ), sort (keys %taxproductnums) );
1001
1002   if ( $object->pkgpart ) {
1003     foreach my $usage_class ( '', @taxproductnums ) {
1004       $tax_override{$usage_class} =
1005         join (",", map $_->taxclassnum,
1006                        qsearch( 'part_pkg_taxoverride', {
1007                                   'pkgpart'     => $object->pkgpart,
1008                                   'usage_class' => $usage_class,
1009                               })
1010              );
1011     }
1012   }
1013
1014   %taxproduct_fields =
1015     map { $_ => [ "taxproductnum_$_", 
1016                   { type  => 'select-taxproduct',
1017                     #label => "$usage_class{$_} tax product",
1018                   },
1019                   "tax_override_$_", 
1020                   { type  => 'select-taxoverride' }
1021                 ]
1022         }
1023         @taxproductnums;
1024
1025   $taxproduct_fields{'(default)'} =
1026     [ 'taxproductnum', { type => 'select-taxproduct',
1027                          #label => 'Default tax product',
1028                        },
1029       'tax_override',  { type => 'select-taxoverride' },
1030     ];
1031 };
1032
1033 my $taxproduct_values = sub {
1034   my ($cgi, $object, $flags) = @_;
1035   my $routine =
1036     sub { my $layer = shift;
1037           my @fields = @{$taxproduct_fields{$layer}};
1038           my @values = ();
1039           while( @fields ) {
1040             my $field = shift @fields;
1041             shift @fields;
1042             $field =~ /^taxproductnum_\w+$/ &&
1043               push @values, ( $field => $options{"usage_$field"} );
1044             $field =~ /^tax_override_(\w+)$/ &&
1045               push @values, ( $field => $tax_override{$1} );
1046             $field =~ /^taxproductnum$/ &&
1047               push @values, ( $field => $object->taxproductnum );
1048             $field =~ /^tax_override$/ &&
1049               push @values, ( $field => $tax_override{''} );
1050           }
1051           { (@values) };
1052         };
1053   
1054   my @result = 
1055     map { ( $_ => { &{$routine}($_) } ) } ( '(default)', @taxproductnums );
1056   return({ @result });
1057   
1058 };
1059
1060 my $field_callback = sub {
1061   my ($cgi, $object, $fieldref) = @_;
1062
1063   my $field = $fieldref->{field};
1064   if ($field eq 'taxproductnums') {
1065     $fieldref->{value} = join(',', @taxproductnums);
1066   } elsif ($field eq 'taxproduct_select') {
1067     $fieldref->{options} = [ '(default)', @taxproductnums ];
1068     $fieldref->{labels}  = { ( '(default)' => '(default)' ),
1069                              map {( $_ => ($usage_class{$_} || $_) )}
1070                                @taxproductnums
1071                            };
1072     $fieldref->{layer_fields} = \%taxproduct_fields;
1073     $fieldref->{layer_values_callback} = $taxproduct_values;
1074   }
1075 };
1076
1077 my $discountnum_hashref = {
1078                             'disabled' => '',
1079                             'months' => { 'op' => '>', 'value' => 1 },
1080                           };
1081
1082 </%init>