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