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