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