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