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