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