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