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