kludge to clone customer packages you otherwise couldn't see, RT#4854
[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' => $agent_clone_extra_sql,
9               #'viewall_dir'           => 'browse',
10               'viewall_url'           => $p.'browse/part_pkg.cgi',
11               'html_init'             => include('/elements/init_overlib.html').
12                                          $javascript,
13               'html_bottom'           => $html_bottom,
14               'body_etc'              =>
15                 'onLoad="agent_changed(document.edit_topform.agentnum)"',
16
17               'begin_callback'        => $begin_callback,
18               'end_callback'          => $end_callback,
19               'new_hashref_callback'  => $new_hashref_callback,
20               'new_object_callback'   => $new_object_callback,
21               'new_callback'          => $new_callback,
22               'clone_callback'        => $clone_callback,
23               'edit_callback'         => $edit_callback,
24               'error_callback'        => $error_callback,
25               'field_callback'        => $field_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 $agent_clone_extra_sql = 
210   ' ( '. FS::part_pkg->curuser_pkgs_sql.
211   #kludge to clone custom customer packages you otherwise couldn't see
212   "   OR ( part_pkg.disabled = 'Y' AND part_pkg.comment LIKE '(CUSTOM)%' ) ".
213   ' ) ';
214
215 my $conf = new FS::Conf;
216 my $taxproducts = $conf->exists('enable_taxproducts');
217
218 #XXX
219 # - tr-part_pkg_freq: month_increments_only (from price plans)
220 # - test cloning
221 # - test errors cloning
222 # - test custom pricing
223 # - move the selectlayer divs away from lame layer_callback
224
225 #my ($query) = $cgi->keywords;
226 #
227 #my $part_pkg = '';
228
229 my @agent_type = ();
230 my %tax_override = ();
231
232 my %taxproductnums = map { ($_->classnum => 1) }
233                      qsearch('usage_class', { 'disabled' => '' });
234 my @taxproductnums = ( qw( setup recur ), sort (keys %taxproductnums) );
235
236 my %options = ();
237 my $recur_disabled = 1;
238
239 my $error_callback = sub {
240   my($cgi, $object, $fields, $opt ) = @_;
241
242   (@agent_type) = $cgi->param('agent_type');
243
244   $opt->{action} = 'Custom' if $cgi->param('pkgnum');
245
246   $recur_disabled = $cgi->param('freq') ? 0 : 1;
247
248   foreach ($cgi->param) {
249     /^usage_taxproductnum_(\d+)$/ && ($taxproductnums{$1} = 1);
250   }
251   $tax_override{''} = $cgi->param('tax_override');
252   $tax_override{$_} = $cgi->param('tax_override_$_')
253     foreach(grep { /^tax_override_(\w+)$/ } $cgi->param);
254
255   #some false laziness w/process
256   $cgi->param('plan') =~ /^(\w+)$/ or die 'unparsable plan';
257   my $plan = $1;
258   my $options = $cgi->param($plan."__OPTIONS");
259   my @options = split(',', $options);
260   %options =
261     map { my $optionname = $_;
262           my $param = $plan."__$optionname";
263           my $value = join(', ', $cgi->param($param));
264           ( $optionname => $value );
265         }
266         @options;
267
268   #$cgi->param($_, $options{$_}) foreach (qw( setup_fee recur_fee ));
269   $object->set($_ => scalar($cgi->param($_)) )
270     foreach (qw( setup_fee recur_fee ));
271
272 };
273
274 my $new_hashref_callback = sub { { 'plan' => 'flat' }; };
275
276 my $new_object_callback = sub {
277   my( $cgi, $hashref, $fields, $opt ) = @_;
278
279   my $part_pkg = FS::part_pkg->new( $hashref );
280   $part_pkg->set($_ => '0')
281     foreach (qw( setup_fee recur_fee ));
282
283   $part_pkg;
284
285 };
286
287 my $edit_callback = sub {
288   my( $cgi, $object, $fields, $opt ) = @_;
289
290   $recur_disabled = $object->freq ? 0 : 1;
291
292   (@agent_type) = map {$_->typenum} qsearch('type_pkgs',{'pkgpart'=>$1});
293
294   foreach ($object->options) {
295     /^usage_taxproductnum_(\d+)$/ && ($taxproductnums{$1} = 1);
296   }
297   foreach ($object->part_pkg_taxoverride) {
298     $taxproductnums{$_->usage_class} = 1
299       if $_->usage_class;
300   }
301
302   %options = $object->options;
303
304   $object->set($_ => $object->option($_))
305     foreach (qw( setup_fee recur_fee ));
306
307 };
308
309 my $new_callback = sub {
310   my( $cgi, $object, $fields ) = @_;
311
312   my $conf = new FS::Conf; 
313   if ( $conf->exists('agent_defaultpkg') ) {
314     #my @all_agent_types = map {$_->typenum} qsearch('agent_type',{});
315     @agent_type = map {$_->typenum} qsearch('agent_type',{});
316   }
317
318 };
319
320 my $clone_callback = sub {
321   my( $cgi, $object, $fields, $opt ) = @_;
322
323   if ( $cgi->param('pkgnum') ) {
324
325     my $cust_pkg = qsearchs('cust_pkg', { 'pkgnum' => $cgi->param('pkgnum') } );
326     $object->agentnum( $cust_pkg->cust_main->agentnum );
327
328     $opt->{action} = 'Custom';
329
330     #my $part_pkg = $clone_part_pkg->clone;
331     #this is all clone did anyway
332     $object->comment( '(CUSTOM) '. $object->comment )
333       unless $object->comment =~ /^\(CUSTOM\) /;
334
335     $object->disabled('Y');
336
337   }
338
339   %options = $object->options;
340
341   $object->set($_ => $options{$_})
342     foreach (qw( setup_fee recur_fee ));
343
344   $recur_disabled = $object->freq ? 0 : 1;
345 };
346
347 my $m2_error_callback_maker = sub {
348   my $link_type = shift; #yay closures
349   return sub {
350     my( $cgi, $object ) = @_;
351       map  {
352              new FS::part_pkg_link {
353                'link_type'   => $link_type,
354                'src_pkgpart' => $object->pkgpart,
355                'dst_pkgpart' => $_,
356              };
357            }
358       grep $_,
359       map  $cgi->param($_),
360       grep /^${link_type}_dst_pkgpart(\d+)$/, $cgi->param;
361   };
362 };
363
364 my $javascript = <<'END';
365   <SCRIPT TYPE="text/javascript">
366
367     function freq_changed(what) {
368       var freq = what.options[what.selectedIndex].value;
369
370       if ( freq == '0' ) {
371         what.form.recur_fee.disabled = true;
372         what.form.recur_fee.style.backgroundColor = '#dddddd';
373       } else {
374         what.form.recur_fee.disabled = false;
375         what.form.recur_fee.style.backgroundColor = '#ffffff';
376       }
377
378     }
379
380     function agent_changed(what) {
381
382       var agentnum = what.options[what.selectedIndex].value;
383
384       if ( agentnum == 0 ) {
385         what.form.agent_type.disabled = false;
386         //what.form.agent_type.style.backgroundColor = '#ffffff';
387         what.form.agent_type.style.visibility = '';
388       } else {
389         what.form.agent_type.disabled = true;
390         //what.form.agent_type.style.backgroundColor = '#dddddd';
391         what.form.agent_type.style.visibility = 'hidden';
392       }
393
394     }
395
396   </SCRIPT>
397 END
398
399 tie my %plans, 'Tie::IxHash', %{ FS::part_pkg::plan_info() };
400
401 tie my %plan_labels, 'Tie::IxHash',
402   map {  $_ => ( $plans{$_}->{'shortname'} || $plans{$_}->{'name'} ) }
403       keys %plans;
404
405 my $html_bottom = sub {
406   my( $object ) = @_;
407
408   #warn join("\n", map { "$_: $options{$_}" } keys %options ). "\n";
409
410   my $layer_callback = sub {
411   
412     my $layer = shift;
413     my $html = ntable("#cccccc",2);
414   
415     #$html .= '
416     #  <TR>
417     #    <TD ALIGN="right">Recurring fee frequency </TD>
418     #    <TD><SELECT NAME="freq">
419     #';
420     #
421     #my @freq = keys %freq;
422     #@freq = grep { /^\d+$/ } @freq
423   #XXX this bit#  #  if exists($plans{$layer}->{'freq'}) && $plans{$layer}->{'freq'} eq 'm';
424     #foreach my $freq ( @freq ) {
425     #  $html .= qq(<OPTION VALUE="$freq");
426     #  $html .= ' SELECTED' if $freq eq $part_pkg->freq;
427     #  $html .= ">$freq{$freq}";
428     #}
429     #$html .= '</SELECT></TD></TR>';
430   
431     my $href = $plans{$layer}->{'fields'};
432     my @fields = exists($plans{$layer}->{'fieldorder'})
433                    ? @{$plans{$layer}->{'fieldorder'}}
434                    : keys %{ $href };
435   
436     foreach my $field ( grep $_ !~ /^(setup|recur)_fee$/, @fields ) {
437   
438       $html .= '<TR><TD ALIGN="right">'. $href->{$field}{'name'}. '</TD><TD>';
439   
440       my $format = sub { shift };
441       $format = $href->{$field}{'format'} if exists($href->{$field}{'format'});
442
443       #XXX these should use elements/ fields... (or this whole thing should
444       #just use layer_fields instead of layer_callback)
445   
446       if ( ! exists($href->{$field}{'type'}) ) {
447   
448         $html .= qq!<INPUT TYPE="text" NAME="${layer}__$field" VALUE="!.
449                  ( exists($options{$field})
450                      ? &$format($options{$field})
451                      : $href->{$field}{'default'} ).
452                  qq!">!;
453   
454       } elsif ( $href->{$field}{'type'} eq 'checkbox' ) {
455   
456         $html .= qq!<INPUT TYPE="checkbox" NAME="${layer}__$field" VALUE=1 !.
457                  ( exists($options{$field}) && $options{$field}
458                    ? ' CHECKED'
459                    : ''
460                  ). '>';
461   
462       } elsif ( $href->{$field}{'type'} =~ /^select/ ) {
463   
464         $html .= '<SELECT';
465         $html .= ' MULTIPLE'
466           if $href->{$field}{'type'} eq 'select_multiple';
467         $html .= qq! NAME="${layer}__$field">!;
468   
469         if ( $href->{$field}{'select_table'} ) {
470           foreach my $record (
471             qsearch( $href->{$field}{'select_table'},
472                      $href->{$field}{'select_hash'}   )
473           ) {
474             my $value = $record->getfield($href->{$field}{'select_key'});
475             $html .= qq!<OPTION VALUE="$value"!.
476                      (  $options{$field} =~ /(^|, *)$value *(,|$)/ #?
477                           ? ' SELECTED'
478                           : ''
479                      ).
480                      '>'. $record->getfield($href->{$field}{'select_label'});
481           }
482         } elsif ( $href->{$field}{'select_options'} ) {
483           foreach my $key ( keys %{ $href->{$field}{'select_options'} } ) {
484             my $label = $href->{$field}{'select_options'}{$key};
485             $html .= qq!<OPTION VALUE="$key"!.
486                      ( $options{$field} =~ /(^|, *)$key *(,|$)/ #?
487                          ? ' SELECTED'
488                          : ''
489                      ).
490                      '>'. $label;
491           }
492   
493         } else {
494           $html .= '<font color="#ff0000">warning: '.
495                    "don't know how to retreive options for $field select field".
496                    '</font>';
497         }
498         $html .= '</SELECT>';
499   
500       } elsif ( $href->{$field}{'type'} eq 'radio' ) {
501   
502         my $radio =
503           qq!<INPUT TYPE="radio" NAME="${layer}__$field"!;
504   
505         foreach my $key ( keys %{ $href->{$field}{'options'} } ) {
506           my $label = $href->{$field}{'options'}{$key};
507           $html .= qq!$radio VALUE="$key"!.
508                    ( $options{$field} =~ /(^|, *)$key *(,|$)/ #?
509                        ? ' CHECKED'
510                        : ''
511                    ).
512                    "> $label<BR>";
513         }
514   
515       }
516   
517       $html .= '</TD></TR>';
518     }
519     $html .= '</TABLE>';
520   
521     $html .= qq(<INPUT TYPE="hidden" NAME="${layer}__OPTIONS" VALUE=").
522              join(',', keys %{ $href } ). '">';
523   
524     $html;
525   
526   };
527
528   my %selectlayers = (
529     field          => 'plan',
530     options        => [ keys %plan_labels ],
531     labels         => \%plan_labels,
532     curr_value     => $object->plan,
533     layer_callback => $layer_callback,
534   );
535
536   my $return =
537     include('/elements/selectlayers.html', %selectlayers, 'layers_only'=>1 ).
538     '<SCRIPT TYPE="text/javascript">'.
539       include('/elements/selectlayers.html', %selectlayers, 'js_only'=>1 );
540
541   $return .=
542     "taxproduct_selectchanged(document.getElementById('taxproduct_select'));\n"
543       if $taxproducts;
544
545   $return .= '</SCRIPT>';
546
547   $return;
548
549 };
550
551 my %usage_class = map { ($_->classnum => $_->classname) }
552                   qsearch('usage_class', {});
553 $usage_class{setup} = 'Setup';
554 $usage_class{recur} = 'Recurring';
555
556 my %taxproduct_fields = ();
557 my $end_callback = sub {
558   my( $cgi, $object, $fields, $opt ) = @_;
559
560   @taxproductnums = ( qw( setup recur ), sort (keys %taxproductnums) );
561
562   if ( $object->pkgpart ) {
563     foreach my $usage_class ( '', @taxproductnums ) {
564       $tax_override{$usage_class} =
565         join (",", map $_->taxclassnum,
566                        qsearch( 'part_pkg_taxoverride', {
567                                   'pkgpart'     => $object->pkgpart,
568                                   'usage_class' => $usage_class,
569                               })
570              );
571     }
572   }
573
574   %taxproduct_fields =
575     map { $_ => [ "taxproductnum_$_", 
576                   { type  => 'select-taxproduct',
577                     #label => "$usage_class{$_} tax product",
578                   },
579                   "tax_override_$_", 
580                   { type  => 'select-taxoverride' }
581                 ]
582         }
583         @taxproductnums;
584
585   $taxproduct_fields{'(default)'} =
586     [ 'taxproductnum', { type => 'select-taxproduct',
587                          #label => 'Default tax product',
588                        },
589       'tax_override',  { type => 'select-taxoverride' },
590     ];
591 };
592
593 my $taxproduct_values = sub {
594   my ($cgi, $object, $flags) = @_;
595   my $routine =
596     sub { my $layer = shift;
597           my @fields = @{$taxproduct_fields{$layer}};
598           my @values = ();
599           while( @fields ) {
600             my $field = shift @fields;
601             shift @fields;
602             $field =~ /^taxproductnum_\w+$/ &&
603               push @values, ( $field => $options{"usage_$field"} );
604             $field =~ /^tax_override_(\w+)$/ &&
605               push @values, ( $field => $tax_override{$1} );
606             $field =~ /^taxproductnum$/ &&
607               push @values, ( $field => $object->taxproductnum );
608             $field =~ /^tax_override$/ &&
609               push @values, ( $field => $tax_override{''} );
610           }
611           { (@values) };
612         };
613   
614   my @result = 
615     map { ( $_ => { &{$routine}($_) } ) } ( '(default)', @taxproductnums );
616   return({ @result });
617   
618 };
619
620 my $field_callback = sub {
621   my ($cgi, $object, $fieldref) = @_;
622
623   my $field = $fieldref->{field};
624   if ($field eq 'taxproductnums') {
625     $fieldref->{value} = join(',', @taxproductnums);
626   } elsif ($field eq 'taxproduct_select') {
627     $fieldref->{options} = [ '(default)', @taxproductnums ];
628     $fieldref->{labels}  = { ( '(default)' => '(default)' ),
629                              map {( $_ => ($usage_class{$_} || $_) )}
630                                @taxproductnums
631                            };
632     $fieldref->{layer_fields} = \%taxproduct_fields;
633     $fieldref->{layer_values_callback} = $taxproduct_values;
634   }
635 };
636
637 </%init>