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