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