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