FCC form 477 reporting #4912
[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               'labels' => { 
28                             'pkgpart'          => 'Package Definition',
29                             'pkg'              => 'Package (customer-visible)',
30                             'comment'          => 'Comment (customer-hidden)',
31                             'classnum'         => 'Package class',
32                             'promo_code'       => 'Promotional code',
33                             'freq'             => 'Recurring fee frequency',
34                             'setuptax'         => 'Setup fee tax exempt',
35                             'recurtax'         => 'Recurring fee tax exempt',
36                             'taxclass'         => 'Tax class',
37                             'taxproduct_select'=> 'Tax products',
38                             'plan'             => 'Price plan',
39                             'disabled'         => 'Disable new orders',
40                             'setup_cost'       => 'Setup cost',
41                             'recur_cost'       => 'Recur cost',
42                             'pay_weight'       => 'Payment weight',
43                             'credit_weight'    => 'Credit weight',
44                             'agentnum'         => 'Agent',
45                             'setup_fee'        => 'Setup fee',
46                             'recur_fee'        => 'Recurring fee',
47                             'bill_dst_pkgpart' => 'Include line item(s) from package',
48                             'svc_dst_pkgpart'  => 'Include services of package',
49                             'report_option'    => 'Report classes',
50                           },
51
52               'fields' => [
53                             { field=>'clone',  type=>'hidden',
54                               curr_value_callback =>
55                                 sub { shift->param('clone') },
56                             },
57                             { field=>'pkgnum', type=>'hidden',
58                               curr_value_callback =>
59                                 sub { shift->param('pkgnum') },
60                             },
61
62                             { field=>'custom',  type=>'hidden' },
63
64                             { type => 'columnstart' },
65                             
66                               { field     => 'pkg',
67                                 type      => 'text',
68                                 size      => 40, #32
69                                 maxlength => 50,
70                               },
71                               {field=>'comment',  type=>'text', size=>40 }, #32
72                               { field         => 'agentnum',
73                                 type          => 'select-agent',
74                                 disable_empty => ! $acl_edit_global,
75                                 empty_label   => '(global)',
76                                 onchange      => 'agent_changed',
77                               },
78                               {field=>'classnum', type=>'select-pkg_class' },
79                               {field=>'disabled', type=>$disabled_type, value=>'Y'},
80
81                               { type  => 'tablebreak-tr-title',
82                                 value => 'Pricing', #better name?
83                               },
84                               { field => 'plan',
85                                 type  => 'selectlayers-select',
86                                 options => [ keys %plan_labels ],
87                                 labels  => \%plan_labels,
88                               },
89                               { field => 'setup_fee',
90                                 type  => 'money',
91                               },
92                               { field    => 'freq',
93                                 type     => 'part_pkg_freq',
94                                 onchange => 'freq_changed',
95                               },
96                               { field    => 'recur_fee',
97                                 type     => 'money',
98                                 disabled => sub { $recur_disabled },
99                               },
100                                 
101                               #price plan
102                               #setup fee
103                               #recurring frequency
104                               #recurring fee (auto-disable)
105
106                             { type => 'columnnext' },
107
108                               {type=>'justtitle', value=>'Taxation' },
109                               {field=>'setuptax', type=>'checkbox', value=>'Y'},
110                               {field=>'recurtax', type=>'checkbox', value=>'Y'},
111                               {field=>'taxclass', type=>'select-taxclass' },
112                               { field => 'taxproductnums',
113                                 type  => 'hidden',
114                                 value => join(',', @taxproductnums),
115                               },
116                               { field => 'taxproduct_select',
117                                 type  => 'selectlayers',
118                                 options => [ '(default)', @taxproductnums ],
119                                 curr_value => '(default)',
120                                 labels  => { ( '(default)' => '(default)' ),
121                                              map {($_=>$usage_class{$_})}
122                                              @taxproductnums
123                                            },
124                                 layer_fields => \%taxproduct_fields,
125                                 layer_values_callback => $taxproduct_values,
126                                 layers_only  =>   !$taxproducts,
127                                 cell_style   => ( !$taxproducts
128                                                   ? 'display:none'
129                                                   : ''
130                                                 ),
131                               },
132
133                               { type  => 'tablebreak-tr-title',
134                                 value => 'Promotions', #better name?
135                               },
136                               { field=>'promo_code', type=>'text', size=>15 },
137
138                               { type  => 'tablebreak-tr-title',
139                                 value => 'Cost tracking', #better name?
140                               },
141                               { field=>'setup_cost', type=>'money', },
142                               { field=>'recur_cost', type=>'money', },
143
144                             { type => 'columnnext' },
145
146                               { field    => 'agent_type',
147                                 type     => 'select-agent_types',
148                                 disabled => ! $acl_edit_global,
149                                 curr_value_callback => sub {
150                                   my($cgi, $object, $field) = @_;
151                                   #in the other callbacks..?  hmm.
152                                   \@agent_type;
153                                 },
154                               },
155
156                               { type  => 'tablebreak-tr-title',
157                                 value => 'Line-item revenue recogition', #better name?
158                               },
159                               { field=>'pay_weight',    type=>'text', size=>6 },
160                               { field=>'credit_weight', type=>'text', size=>6 },
161
162
163                             { type => 'columnend' },
164
165                             { 'type'  => $census ? 'tablebreak-tr-title'
166                                                  : 'hidden',
167                               'value' => 'Optional report classes',
168                               'field' => 'census_title',
169                             },
170                             { 'field'    => 'report_option',
171                               'type'     => $census ? 'select-table' : 'hidden',
172                               'table'    => 'part_pkg_report_option',
173                               'name_col' => 'name',
174                               'multiple' => 1,
175                             },
176
177
178                             { 'type'  => 'tablebreak-tr-title',
179                               'value' => 'Pricing add-ons',
180                             },
181                             { 'field'      => 'bill_dst_pkgpart',
182                               'type'       => 'select-part_pkg',
183                               'm2_label'   => 'Include line item(s) from package',
184                               'm2m_method' => 'bill_part_pkg_link',
185                               'm2m_dstcol' => 'dst_pkgpart',
186                               'm2_error_callback' =>
187                                 &{$m2_error_callback_maker}('bill'),
188                             },
189
190                             { type  => 'tablebreak-tr-title',
191                               value => 'Services',
192                             },
193                             { type => 'pkg_svc', },
194
195                             { 'field'      => 'svc_dst_pkgpart',
196                               'label'      => 'Also include services from package: ',
197                               'type'       => 'select-part_pkg',
198                               'm2_label'   => 'Include services of package: ',
199                               'm2m_method' => 'svc_part_pkg_link',
200                               'm2m_dstcol' => 'dst_pkgpart',
201                               'm2_error_callback' =>
202                                 &{$m2_error_callback_maker}('svc'),
203                             },
204
205                             { type  => 'tablebreak-tr-title',
206                               value => 'Price plan options',
207                             },
208
209                           ],
210
211            )
212 %>
213 <%init>
214
215 my $curuser = $FS::CurrentUser::CurrentUser;
216
217 my $edit_global = 'Edit global package definitions';
218 my $acl_edit        = $curuser->access_right('Edit package definitions');
219 my $acl_edit_global = $curuser->access_right($edit_global);
220
221 my $acl_edit_either = $acl_edit || $acl_edit_global;
222
223 my $begin_callback = sub {
224   my( $cgi, $fields, $opt ) = @_;
225   die "access denied"
226     unless $acl_edit_either
227         || ( $cgi->param('pkgnum')
228              && $curuser->access_right('Customize customer package')
229            );
230 };
231
232 my $disabled_type = $acl_edit_either ? 'checkbox' : 'hidden';
233
234 my $agent_clone_extra_sql = 
235   ' ( '. FS::part_pkg->curuser_pkgs_sql.
236   "   OR ( part_pkg.custom = 'Y' ) ".
237   ' ) ';
238
239 my $conf = new FS::Conf;
240 my $taxproducts = $conf->exists('enable_taxproducts');
241 my $census = scalar( qsearch( 'part_pkg_report_option', {} ) );
242
243 #XXX
244 # - tr-part_pkg_freq: month_increments_only (from price plans)
245 # - test cloning
246 # - test errors cloning
247 # - test custom pricing
248 # - move the selectlayer divs away from lame layer_callback
249
250 #my ($query) = $cgi->keywords;
251 #
252 #my $part_pkg = '';
253
254 my @agent_type = ();
255 my %tax_override = ();
256
257 my %taxproductnums = map { ($_->classnum => 1) }
258                      qsearch('usage_class', { 'disabled' => '' });
259 my @taxproductnums = ( qw( setup recur ), sort (keys %taxproductnums) );
260
261 my %options = ();
262 my $recur_disabled = 1;
263
264 my $error_callback = sub {
265   my($cgi, $object, $fields, $opt ) = @_;
266
267   (@agent_type) = $cgi->param('agent_type');
268
269   $opt->{action} = 'Custom' if $cgi->param('pkgnum');
270
271   $recur_disabled = $cgi->param('freq') ? 0 : 1;
272
273   foreach ($cgi->param) {
274     /^usage_taxproductnum_(\d+)$/ && ($taxproductnums{$1} = 1);
275   }
276   $tax_override{''} = $cgi->param('tax_override');
277   $tax_override{$_} = $cgi->param('tax_override_$_')
278     foreach(grep { /^tax_override_(\w+)$/ } $cgi->param);
279
280   #some false laziness w/process
281   $cgi->param('plan') =~ /^(\w+)$/ or die 'unparsable plan';
282   my $plan = $1;
283   my $options = $cgi->param($plan."__OPTIONS");
284   my @options = split(',', $options);
285   %options =
286     map { my $optionname = $_;
287           my $param = $plan."__$optionname";
288           my $value = join(', ', $cgi->param($param));
289           ( $optionname => $value );
290         }
291         @options;
292
293   #$cgi->param($_, $options{$_}) foreach (qw( setup_fee recur_fee ));
294   $object->set($_ => scalar($cgi->param($_)) )
295     foreach (qw( setup_fee recur_fee ));
296
297 };
298
299 my $new_hashref_callback = sub { { 'plan' => 'flat' }; };
300
301 my $new_object_callback = sub {
302   my( $cgi, $hashref, $fields, $opt ) = @_;
303
304   my $part_pkg = FS::part_pkg->new( $hashref );
305   $part_pkg->set($_ => '0')
306     foreach (qw( setup_fee recur_fee ));
307
308   $part_pkg;
309
310 };
311
312 my $edit_callback = sub {
313   my( $cgi, $object, $fields, $opt ) = @_;
314
315   $recur_disabled = $object->freq ? 0 : 1;
316
317   (@agent_type) = map {$_->typenum} qsearch('type_pkgs',{'pkgpart'=>$1});
318
319   my @report_option = ();
320   foreach ($object->options) {
321     /^usage_taxproductnum_(\d+)$/ && ($taxproductnums{$1} = 1);
322     /^report_option_(\d+)$/ && (push @report_option, $1);
323   }
324   foreach ($object->part_pkg_taxoverride) {
325     $taxproductnums{$_->usage_class} = 1
326       if $_->usage_class;
327   }
328
329   $cgi->param('report_option', join(',', @report_option));
330   foreach my $field ( @$fields ) {
331     next unless ( 
332       ref($field) eq 'HASH' &&
333       $field->{field} &&
334       $field->{field} eq 'report_option'
335     );
336     #$field->{curr_value} = join(',', @report_option);
337     $field->{value} = join(',', @report_option);
338   }
339
340   %options = $object->options;
341
342   $object->set($_ => $object->option($_))
343     foreach (qw( setup_fee recur_fee ));
344
345 };
346
347 my $new_callback = sub {
348   my( $cgi, $object, $fields ) = @_;
349
350   my $conf = new FS::Conf; 
351   if ( $conf->exists('agent_defaultpkg') ) {
352     #my @all_agent_types = map {$_->typenum} qsearch('agent_type',{});
353     @agent_type = map {$_->typenum} qsearch('agent_type',{});
354   }
355
356 };
357
358 my $clone_callback = sub {
359   my( $cgi, $object, $fields, $opt ) = @_;
360
361   if ( $cgi->param('pkgnum') ) {
362
363     my $cust_pkg = qsearchs('cust_pkg', { 'pkgnum' => $cgi->param('pkgnum') } );
364     $object->agentnum( $cust_pkg->cust_main->agentnum );
365
366     $opt->{action} = 'Custom';
367
368     #my $part_pkg = $clone_part_pkg->clone;
369     #this is all clone does anyway
370     $object->custom('Y');
371
372     $object->disabled('Y');
373
374   }
375
376   %options = $object->options;
377
378   $object->set($_ => $options{$_})
379     foreach (qw( setup_fee recur_fee ));
380
381   $recur_disabled = $object->freq ? 0 : 1;
382 };
383
384 my $m2_error_callback_maker = sub {
385   my $link_type = shift; #yay closures
386   return sub {
387     my( $cgi, $object ) = @_;
388       map  {
389              new FS::part_pkg_link {
390                'link_type'   => $link_type,
391                'src_pkgpart' => $object->pkgpart,
392                'dst_pkgpart' => $_,
393              };
394            }
395       grep $_,
396       map  $cgi->param($_),
397       grep /^${link_type}_dst_pkgpart(\d+)$/, $cgi->param;
398   };
399 };
400
401 my $javascript = <<'END';
402   <SCRIPT TYPE="text/javascript">
403
404     function freq_changed(what) {
405       var freq = what.options[what.selectedIndex].value;
406
407       if ( freq == '0' ) {
408         what.form.recur_fee.disabled = true;
409         what.form.recur_fee.style.backgroundColor = '#dddddd';
410       } else {
411         what.form.recur_fee.disabled = false;
412         what.form.recur_fee.style.backgroundColor = '#ffffff';
413       }
414
415     }
416
417     function agent_changed(what) {
418
419       var agentnum = what.options[what.selectedIndex].value;
420
421       if ( agentnum == 0 ) {
422         what.form.agent_type.disabled = false;
423         //what.form.agent_type.style.backgroundColor = '#ffffff';
424         what.form.agent_type.style.visibility = '';
425       } else {
426         what.form.agent_type.disabled = true;
427         //what.form.agent_type.style.backgroundColor = '#dddddd';
428         what.form.agent_type.style.visibility = 'hidden';
429       }
430
431     }
432
433   </SCRIPT>
434 END
435
436 tie my %plans, 'Tie::IxHash', %{ FS::part_pkg::plan_info() };
437
438 tie my %plan_labels, 'Tie::IxHash',
439   map {  $_ => ( $plans{$_}->{'shortname'} || $plans{$_}->{'name'} ) }
440       keys %plans;
441
442 my $html_bottom = sub {
443   my( $object ) = @_;
444
445   #warn join("\n", map { "$_: $options{$_}" } keys %options ). "\n";
446
447   my $layer_callback = sub {
448   
449     my $layer = shift;
450     my $html = ntable("#cccccc",2);
451   
452     #$html .= '
453     #  <TR>
454     #    <TD ALIGN="right">Recurring fee frequency </TD>
455     #    <TD><SELECT NAME="freq">
456     #';
457     #
458     #my @freq = keys %freq;
459     #@freq = grep { /^\d+$/ } @freq
460   #XXX this bit#  #  if exists($plans{$layer}->{'freq'}) && $plans{$layer}->{'freq'} eq 'm';
461     #foreach my $freq ( @freq ) {
462     #  $html .= qq(<OPTION VALUE="$freq");
463     #  $html .= ' SELECTED' if $freq eq $part_pkg->freq;
464     #  $html .= ">$freq{$freq}";
465     #}
466     #$html .= '</SELECT></TD></TR>';
467   
468     my $href = $plans{$layer}->{'fields'};
469     my @fields = exists($plans{$layer}->{'fieldorder'})
470                    ? @{$plans{$layer}->{'fieldorder'}}
471                    : keys %{ $href };
472   
473     foreach my $field ( grep $_ !~ /^(setup|recur)_fee$/, @fields ) {
474   
475       $html .= '<TR><TD ALIGN="right">'. $href->{$field}{'name'}. '</TD><TD>';
476   
477       my $format = sub { shift };
478       $format = $href->{$field}{'format'} if exists($href->{$field}{'format'});
479
480       #XXX these should use elements/ fields... (or this whole thing should
481       #just use layer_fields instead of layer_callback)
482   
483       if ( ! exists($href->{$field}{'type'}) ) {
484   
485         $html .= qq!<INPUT TYPE="text" NAME="${layer}__$field" VALUE="!.
486                  ( exists($options{$field})
487                      ? &$format($options{$field})
488                      : $href->{$field}{'default'} ).
489                  qq!">!;
490   
491       } elsif ( $href->{$field}{'type'} eq 'checkbox' ) {
492   
493         $html .= qq!<INPUT TYPE="checkbox" NAME="${layer}__$field" VALUE=1 !.
494                  ( exists($options{$field}) && $options{$field}
495                    ? ' CHECKED'
496                    : ''
497                  ). '>';
498   
499       } elsif ( $href->{$field}{'type'} =~ /^select/ ) {
500   
501         $html .= '<SELECT';
502         $html .= ' MULTIPLE'
503           if $href->{$field}{'type'} eq 'select_multiple';
504         $html .= qq! NAME="${layer}__$field">!;
505   
506         if ( $href->{$field}{'select_table'} ) {
507           foreach my $record (
508             qsearch( $href->{$field}{'select_table'},
509                      $href->{$field}{'select_hash'}   )
510           ) {
511             my $value = $record->getfield($href->{$field}{'select_key'});
512             $html .= qq!<OPTION VALUE="$value"!.
513                      (  $options{$field} =~ /(^|, *)$value *(,|$)/ #?
514                           ? ' SELECTED'
515                           : ''
516                      ).
517                      '>'. $record->getfield($href->{$field}{'select_label'});
518           }
519         } elsif ( $href->{$field}{'select_options'} ) {
520           foreach my $key ( keys %{ $href->{$field}{'select_options'} } ) {
521             my $label = $href->{$field}{'select_options'}{$key};
522             $html .= qq!<OPTION VALUE="$key"!.
523                      ( $options{$field} =~ /(^|, *)$key *(,|$)/ #?
524                          ? ' SELECTED'
525                          : ''
526                      ).
527                      '>'. $label;
528           }
529   
530         } else {
531           $html .= '<font color="#ff0000">warning: '.
532                    "don't know how to retreive options for $field select field".
533                    '</font>';
534         }
535         $html .= '</SELECT>';
536   
537       } elsif ( $href->{$field}{'type'} eq 'radio' ) {
538   
539         my $radio =
540           qq!<INPUT TYPE="radio" NAME="${layer}__$field"!;
541   
542         foreach my $key ( keys %{ $href->{$field}{'options'} } ) {
543           my $label = $href->{$field}{'options'}{$key};
544           $html .= qq!$radio VALUE="$key"!.
545                    ( $options{$field} =~ /(^|, *)$key *(,|$)/ #?
546                        ? ' CHECKED'
547                        : ''
548                    ).
549                    "> $label<BR>";
550         }
551   
552       }
553   
554       $html .= '</TD></TR>';
555     }
556     $html .= '</TABLE>';
557   
558     $html .= qq(<INPUT TYPE="hidden" NAME="${layer}__OPTIONS" VALUE=").
559              join(',', keys %{ $href } ). '">';
560   
561     $html;
562   
563   };
564
565   my %selectlayers = (
566     field          => 'plan',
567     options        => [ keys %plan_labels ],
568     labels         => \%plan_labels,
569     curr_value     => $object->plan,
570     layer_callback => $layer_callback,
571   );
572
573   my $return =
574     include('/elements/selectlayers.html', %selectlayers, 'layers_only'=>1 ).
575     '<SCRIPT TYPE="text/javascript">'.
576       include('/elements/selectlayers.html', %selectlayers, 'js_only'=>1 );
577
578   $return .=
579     "taxproduct_selectchanged(document.getElementById('taxproduct_select'));\n"
580       if $taxproducts;
581
582   $return .= '</SCRIPT>';
583
584   $return;
585
586 };
587
588 my %usage_class = map { ($_->classnum => $_->classname) }
589                   qsearch('usage_class', {});
590 $usage_class{setup} = 'Setup';
591 $usage_class{recur} = 'Recurring';
592
593 my %taxproduct_fields = ();
594 my $end_callback = sub {
595   my( $cgi, $object, $fields, $opt ) = @_;
596
597   @taxproductnums = ( qw( setup recur ), sort (keys %taxproductnums) );
598
599   if ( $object->pkgpart ) {
600     foreach my $usage_class ( '', @taxproductnums ) {
601       $tax_override{$usage_class} =
602         join (",", map $_->taxclassnum,
603                        qsearch( 'part_pkg_taxoverride', {
604                                   'pkgpart'     => $object->pkgpart,
605                                   'usage_class' => $usage_class,
606                               })
607              );
608     }
609   }
610
611   %taxproduct_fields =
612     map { $_ => [ "taxproductnum_$_", 
613                   { type  => 'select-taxproduct',
614                     #label => "$usage_class{$_} tax product",
615                   },
616                   "tax_override_$_", 
617                   { type  => 'select-taxoverride' }
618                 ]
619         }
620         @taxproductnums;
621
622   $taxproduct_fields{'(default)'} =
623     [ 'taxproductnum', { type => 'select-taxproduct',
624                          #label => 'Default tax product',
625                        },
626       'tax_override',  { type => 'select-taxoverride' },
627     ];
628 };
629
630 my $taxproduct_values = sub {
631   my ($cgi, $object, $flags) = @_;
632   my $routine =
633     sub { my $layer = shift;
634           my @fields = @{$taxproduct_fields{$layer}};
635           my @values = ();
636           while( @fields ) {
637             my $field = shift @fields;
638             shift @fields;
639             $field =~ /^taxproductnum_\w+$/ &&
640               push @values, ( $field => $options{"usage_$field"} );
641             $field =~ /^tax_override_(\w+)$/ &&
642               push @values, ( $field => $tax_override{$1} );
643             $field =~ /^taxproductnum$/ &&
644               push @values, ( $field => $object->taxproductnum );
645             $field =~ /^tax_override$/ &&
646               push @values, ( $field => $tax_override{''} );
647           }
648           { (@values) };
649         };
650   
651   my @result = 
652     map { ( $_ => { &{$routine}($_) } ) } ( '(default)', @taxproductnums );
653   return({ @result });
654   
655 };
656
657 my $field_callback = sub {
658   my ($cgi, $object, $fieldref) = @_;
659
660   my $field = $fieldref->{field};
661   if ($field eq 'taxproductnums') {
662     $fieldref->{value} = join(',', @taxproductnums);
663   } elsif ($field eq 'taxproduct_select') {
664     $fieldref->{options} = [ '(default)', @taxproductnums ];
665     $fieldref->{labels}  = { ( '(default)' => '(default)' ),
666                              map {( $_ => ($usage_class{$_} || $_) )}
667                                @taxproductnums
668                            };
669     $fieldref->{layer_fields} = \%taxproduct_fields;
670     $fieldref->{layer_values_callback} = $taxproduct_values;
671   }
672 };
673
674 </%init>