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