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