prepayment discounts rt#5318
[freeside.git] / httemplate / browse / part_pkg.cgi
1 <% include( 'elements/browse.html',
2                  'title'                 => 'Package Definitions',
3                  'html_init'             => $html_init,
4                  'html_posttotal'        => $html_posttotal,
5                  'name'                  => 'package definitions',
6                  'disableable'           => 1,
7                  'disabled_statuspos'    => 4,
8                  'agent_virt'            => 1,
9                  'agent_null_right'      => [ $edit, $edit_global ],
10                  'agent_null_right_link' => $edit_global,
11                  'agent_pos'             => 6,
12                  'query'                 => { 'select'    => $select,
13                                               'table'     => 'part_pkg',
14                                               'hashref'   => \%hash,
15                                               'extra_sql' => $extra_sql,
16                                               'order_by'  => "ORDER BY $orderby"
17                                             },
18                  'count_query'           => $count_query,
19                  'header'                => \@header,
20                  'fields'                => \@fields,
21                  'links'                 => \@links,
22                  'align'                 => $align,
23              )
24 %>
25 <%init>
26
27 my $curuser = $FS::CurrentUser::CurrentUser;
28
29 my $edit        = 'Edit package definitions';
30 my $edit_global = 'Edit global package definitions';
31 my $acl_edit        = $curuser->access_right($edit);
32 my $acl_edit_global = $curuser->access_right($edit_global);
33 my $acl_config      = $curuser->access_right('Configuration'); #to edit services
34                                                                #and agent types
35
36 die "access denied"
37   unless $acl_edit || $acl_edit_global;
38
39 my $conf = new FS::Conf;
40 my $taxclasses = $conf->exists('enable_taxclasses');
41 my $money_char = $conf->config('money_char') || '$';
42
43 my $select = '*';
44 my $orderby = 'pkgpart';
45 my %hash = ();
46 my $extra_count = '';
47
48 if ( $cgi->param('active') ) {
49   $orderby = 'num_active DESC';
50 }
51
52 my @where = ();
53
54 #if ( $cgi->param('activeONLY') ) {
55 #  push @where, ' WHERE num_active > 0 '; #XXX doesn't affect count...
56 #}
57
58 if ( $cgi->param('recurring') ) {
59   $hash{'freq'} = { op=>'!=', value=>'0' };
60   $extra_count = " freq != '0' ";
61 }
62
63 my $classnum = '';
64 if ( $cgi->param('classnum') =~ /^(\d+)$/ ) {
65   $classnum = $1;
66   push @where, $classnum ? "classnum =  $classnum"
67                          : "classnum IS NULL";
68 }
69 $cgi->delete('classnum');
70
71 if ( $cgi->param('missing_recur_fee') ) {
72   push @where, "0 = ( SELECT COUNT(*) FROM part_pkg_option
73                         WHERE optionname = 'recur_fee'
74                           AND part_pkg_option.pkgpart = part_pkg.pkgpart
75                           AND CAST ( optionvalue AS NUMERIC ) > 0
76                     )";
77 }
78
79 push @where, FS::part_pkg->curuser_pkgs_sql
80   unless $acl_edit_global;
81
82 my $extra_sql = scalar(@where)
83                 ? ( scalar(keys %hash) ? ' AND ' : ' WHERE ' ).
84                   join( 'AND ', @where)
85                 : '';
86
87 my $agentnums_sql = $curuser->agentnums_sql( 'table'=>'cust_main' );
88 my $count_cust_pkg = "
89   SELECT COUNT(*) FROM cust_pkg LEFT JOIN cust_main USING ( custnum )
90     WHERE cust_pkg.pkgpart = part_pkg.pkgpart
91       AND $agentnums_sql
92 ";
93
94 $select = "
95
96   *,
97
98   ( $count_cust_pkg
99       AND ( cancel IS NULL OR cancel = 0 )
100       AND ( susp IS NULL OR susp = 0 )
101   ) AS num_active,
102
103   ( $count_cust_pkg
104       AND ( cancel IS NULL OR cancel = 0 )
105       AND susp IS NOT NULL AND susp != 0
106   ) AS num_suspended,
107
108   ( $count_cust_pkg
109       AND cancel IS NOT NULL AND cancel != 0
110   ) AS num_cancelled
111
112 ";
113
114 my $html_init;
115 #unless ( $cgi->param('active') ) {
116   $html_init = qq!
117     One or more service definitions are grouped together into a package 
118     definition and given pricing information.  Customers purchase packages
119     rather than purchase services directly.<BR><BR>
120     <FORM METHOD="POST" ACTION="${p}edit/part_pkg.cgi">
121     <A HREF="${p}edit/part_pkg.cgi"><I>Add a new package definition</I></A>
122     or
123     !.include('/elements/select-part_pkg.html', 'element_name' => 'clone' ). qq!
124     <INPUT TYPE="submit" VALUE="Clone existing package">
125     </FORM>
126     <BR><BR>
127   !;
128 #}
129
130 $cgi->param('dummy', 1);
131
132 my $filter_change =
133   qq(\n<SCRIPT TYPE="text/javascript">\n).
134   "function filter_change() {".
135   "  window.location = '". $cgi->self_url.
136        ";classnum=' + document.getElementById('classnum').options[document.getElementById('classnum').selectedIndex].value".
137   "}".
138   "\n</SCRIPT>\n";
139
140 #restore this so pagination works
141 $cgi->param('classnum', $classnum) if length($classnum);
142
143 my $html_posttotal =
144   "$filter_change\n<BR>( show class: ".
145   include('/elements/select-pkg_class.html',
146             #'curr_value'    => $classnum,
147             'value'         => $classnum, #insist on 0 :/
148             'onchange'      => 'filter_change()',
149             'pre_options'   => [ '-1' => 'all',
150                                  '0'  => '(none)', ],
151             'disable_empty' => 1,
152          ).
153   ' )';
154
155 my $recur_toggle = $cgi->param('recurring') ? 'show' : 'hide';
156 $cgi->param('recurring', $cgi->param('recurring') ^ 1 );
157
158 $html_posttotal .=
159   '( <A HREF="'. $cgi->self_url.'">'. "$recur_toggle one-time charges</A> )";
160
161 $cgi->param('recurring', $cgi->param('recurring') ^ 1 ); #put it back
162
163 # ------
164
165 my $link = [ $p.'edit/part_pkg.cgi?', 'pkgpart' ];
166
167 my @header = ( '#', 'Package', 'Comment', 'Custom' );
168 my @fields = ( 'pkgpart', 'pkg', 'comment',
169                sub{ '<B><FONT COLOR="#0000CC">'.$_[0]->custom.'</FONT></B>' }
170              );
171 my $align = 'rllc';
172 my @links = ( $link, $link, '', '' );
173
174 unless ( 0 ) { #already showing only one class or something?
175   push @header, 'Class';
176   push @fields, sub { shift->classname || '(none)'; };
177   $align .= 'l';
178 }
179
180 if ( $conf->exists('pkg-addon_classnum') ) {
181   push @header, "Add'l order class";
182   push @fields, sub { shift->addon_classname || '(none)'; };
183   $align .= 'l';
184 }
185
186 tie my %plans, 'Tie::IxHash', %{ FS::part_pkg::plan_info() };
187
188 tie my %plan_labels, 'Tie::IxHash',
189   map {  $_ => ( $plans{$_}->{'shortname'} || $plans{$_}->{'name'} ) }
190       keys %plans;
191
192 push @header, 'Pricing';
193 $align .= 'r'; #?
194 push @fields, sub {
195   my $part_pkg = shift;
196   (my $plan = $plan_labels{$part_pkg->plan} ) =~ s/ /&nbsp;/g;
197   my $is_recur = ( $part_pkg->freq ne '0' );
198   my @discounts = sort { $a->months <=> $b->months }
199                   map { $_->discount  }
200                   $part_pkg->part_pkg_discount;
201
202   [
203     [
204       { data =>$plan,
205         align=>'center',
206         colspan=>2,
207       },
208     ],
209     [
210       { data =>$money_char.
211                sprintf('%.2f', $part_pkg->option('setup_fee') ),
212         align=>'right'
213       },
214       { data => ( $is_recur ? ' setup' : ' one-time' ),
215         align=>'left',
216       },
217     ],
218     [
219       { data=>( $is_recur
220                   ? $money_char.sprintf('%.2f ', $part_pkg->option('recur_fee') )
221                   : $part_pkg->freq_pretty
222               ),
223         align=> ( $is_recur ? 'right' : 'center' ),
224         colspan=> ( $is_recur ? 1 : 2 ),
225       },
226       ( $is_recur
227         ?  { data => ( $is_recur ? $part_pkg->freq_pretty : '' ),
228              align=>'left',
229            }
230         : ()
231       ),
232     ],
233     ( map { 
234             my $dst_pkg = $_->dst_pkg;
235             [ 
236               { data => 'Add-on:&nbsp;'.$dst_pkg->pkg_comment,
237                 align=>'center', #?
238                 colspan=>2,
239               }
240             ]
241           }
242       $part_pkg->bill_part_pkg_link
243     ),
244     ( scalar(@discounts)
245         ?  [ 
246               { data => '<b>Discounts</b>',
247                 align=>'center', #?
248                 colspan=>2,
249               }
250             ]
251         : ()  
252     ),
253     ( scalar(@discounts)
254         ? map { 
255             [ 
256               { data  => $_->months. ':',
257                 align => 'right',
258               },
259               { data => $_->amount ? '$'. $_->amount : $_->percent. '%'
260               }
261             ]
262           }
263           @discounts
264         : ()
265     ),
266   ];
267
268 #  $plan_labels{$part_pkg->plan}.'<BR>'.
269 #    $money_char.sprintf('%.2f setup<BR>', $part_pkg->option('setup_fee') ).
270 #    ( $part_pkg->freq ne '0'
271 #      ? $money_char.sprintf('%.2f ', $part_pkg->option('recur_fee') )
272 #      : ''
273 #    ).
274 #    $part_pkg->freq_pretty; #.'<BR>'
275 };
276
277 ###
278 # Agent goes here if displayed
279 ###
280
281 #agent type
282 if ( $acl_edit_global ) {
283   #really we just want a count, but this is fine unless someone has tons
284   my @all_agent_types = map {$_->typenum} qsearch('agent_type',{});
285   if ( scalar(@all_agent_types) > 1 ) {
286     push @header, 'Agent types';
287     my $typelink = $p. 'edit/agent_type.cgi?';
288     push @fields, sub { my $part_pkg = shift;
289                         [
290                           map { my $agent_type = $_->agent_type;
291                                 [ 
292                                   { 'data'  => $agent_type->atype, #escape?
293                                     'align' => 'left',
294                                     'link'  => ( $acl_config
295                                                    ? $typelink.
296                                                      $agent_type->typenum
297                                                    : ''
298                                                ),
299                                   },
300                                 ];
301                               }
302                               $part_pkg->type_pkgs
303                         ];
304                       };
305     $align .= 'l';
306   }
307 }
308
309 #if ( $cgi->param('active') ) {
310   push @header, 'Customer<BR>packages';
311   my %col = (
312     'active'          => '00CC00',
313     'suspended'       => 'FF9900',
314     'cancelled'       => 'FF0000',
315     #'one-time charge' => '000000',
316     'charge'          => '000000',
317   );
318   my $cust_pkg_link = $p. 'search/cust_pkg.cgi?pkgpart=';
319   push @fields, sub { my $part_pkg = shift;
320                       [
321                         map {
322                               my $magic = $_;
323                               my $label = $_;
324                               if ( $magic eq 'active' && $part_pkg->freq == 0 ) {
325                                 $magic = 'inactive';
326                                 #$label = 'one-time charge',
327                                 $label = 'charge',
328                               }
329                           
330                               [
331                                 {
332                                  'data'  => '<B><FONT COLOR="#'. $col{$label}. '">'.
333                                             $part_pkg->get("num_$_").
334                                             '</FONT></B>',
335                                  'align' => 'right',
336                                 },
337                                 {
338                                  'data'  => $label.
339                                               ( $part_pkg->get("num_$_") != 1
340                                                 && $label =~ /charge$/
341                                                   ? 's'
342                                                   : ''
343                                               ),
344                                  'align' => 'left',
345                                  'link'  => ( $part_pkg->get("num_$_")
346                                                 ? $cust_pkg_link.
347                                                   $part_pkg->pkgpart.
348                                                   ";magic=$magic"
349                                                 : ''
350                                             ),
351                                 },
352                               ],
353                             } (qw( active suspended cancelled ))
354                       ]; };
355   $align .= 'r';
356 #}
357
358 if ( $taxclasses ) {
359   push @header, 'Taxclass';
360   push @fields, sub { shift->taxclass() || '&nbsp;'; };
361   $align .= 'l';
362 }
363
364 push @header, 'Plan options',
365               'Services';
366               #'Service', 'Quan', 'Primary';
367
368 push @fields, 
369               sub {
370                     my $part_pkg = shift;
371                     if ( $part_pkg->plan ) {
372
373                       my %options = $part_pkg->options;
374
375                       [ map { 
376                               [
377                                 { 'data'  => $_,
378                                   'align' => 'right',
379                                 },
380                                 { 'data'  => $part_pkg->format($_,$options{$_}),
381                                   'align' => 'left',
382                                 },
383                               ];
384                             }
385                         grep { $options{$_} =~ /\S/ } 
386                         grep { $_ !~ /^(setup|recur)_fee$/ }
387                         keys %options
388                       ];
389
390                     } else {
391
392                       [ map { [
393                                 { 'data'  => uc($_),
394                                   'align' => 'right',
395                                 },
396                                 {
397                                   'data'  => $part_pkg->$_(),
398                                   'align' => 'left',
399                                 },
400                               ];
401                             }
402                         (qw(setup recur))
403                       ];
404
405                     }
406
407                   },
408
409               sub {
410                     my $part_pkg = shift;
411
412                     [ 
413                       (map {
414                              my $pkg_svc = $_;
415                              my $part_svc = $pkg_svc->part_svc;
416                              my $svc = $part_svc->svc;
417                              if ( $pkg_svc->primary_svc =~ /^Y/i ) {
418                                $svc = "<B>$svc (PRIMARY)</B>";
419                              }
420                              $svc =~ s/ +/&nbsp;/g;
421
422                              [
423                                {
424                                  'data'  => '<B>'. $pkg_svc->quantity. '</B>',
425                                  'align' => 'right'
426                                },
427                                {
428                                  'data'  => $svc,
429                                  'align' => 'left',
430                                  'link'  => ( $acl_config
431                                                 ? $p. 'edit/part_svc.cgi?'.
432                                                   $part_svc->svcpart
433                                                 : ''
434                                             ),
435                                },
436                              ];
437                            }
438                       sort {     $b->primary_svc =~ /^Y/i
439                              <=> $a->primary_svc =~ /^Y/i
440                            }
441                            $part_pkg->pkg_svc('disable_linked'=>1)
442                       ),
443                       ( map { 
444                               my $dst_pkg = $_->dst_pkg;
445                               [
446                                 { data => 'Add-on:&nbsp;'.$dst_pkg->pkg_comment,
447                                   align=>'center', #?
448                                   colspan=>2,
449                                 }
450                               ]
451                             }
452                         $part_pkg->svc_part_pkg_link
453                       )
454                     ];
455
456                   };
457
458 $align .= 'lrl'; #rr';
459
460 # --------
461
462 my $count_extra_sql = $extra_sql;
463 $count_extra_sql =~ s/^\s*AND /WHERE /i;
464 $extra_count = ( $count_extra_sql ? ' AND ' : ' WHERE ' ). $extra_count
465   if $extra_count;
466 my $count_query = "SELECT COUNT(*) FROM part_pkg $count_extra_sql $extra_count";
467
468 </%init>