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