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