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