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