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