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