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