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