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