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