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