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