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