fix package def report totals to break down not yet billed vs. active package counts...
[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 ( setup IS NULL OR setup = 0 )
100       AND ( cancel IS NULL OR cancel = 0 )
101       AND ( susp IS NULL OR susp = 0 )
102   ) AS num_not_yet_billed,
103
104   ( $count_cust_pkg
105       AND setup IS NOT NULL AND setup != 0
106       AND ( cancel IS NULL OR cancel = 0 )
107       AND ( susp IS NULL OR susp = 0 )
108   ) AS num_active,
109
110   ( $count_cust_pkg
111       AND ( cancel IS NULL OR cancel = 0 )
112       AND susp IS NOT NULL AND susp != 0
113   ) AS num_suspended,
114
115   ( $count_cust_pkg
116       AND cancel IS NOT NULL AND cancel != 0
117   ) AS num_cancelled
118
119 ";
120
121 my $html_init;
122 #unless ( $cgi->param('active') ) {
123   $html_init = qq!
124     One or more service definitions are grouped together into a package 
125     definition and given pricing information.  Customers purchase packages
126     rather than purchase services directly.<BR><BR>
127     <FORM METHOD="POST" ACTION="${p}edit/part_pkg.cgi">
128     <A HREF="${p}edit/part_pkg.cgi"><I>Add a new package definition</I></A>
129     or
130     !.include('/elements/select-part_pkg.html', 'element_name' => 'clone' ). qq!
131     <INPUT TYPE="submit" VALUE="Clone existing package">
132     </FORM>
133     <BR><BR>
134   !;
135 #}
136
137 $cgi->param('dummy', 1);
138
139 my $filter_change =
140   qq(\n<SCRIPT TYPE="text/javascript">\n).
141   "function filter_change() {".
142   "  window.location = '". $cgi->self_url.
143        ";classnum=' + document.getElementById('classnum').options[document.getElementById('classnum').selectedIndex].value".
144   "}".
145   "\n</SCRIPT>\n";
146
147 #restore this so pagination works
148 $cgi->param('classnum', $classnum) if length($classnum);
149
150 my $html_posttotal =
151   "$filter_change\n<BR>( show class: ".
152   include('/elements/select-pkg_class.html',
153             #'curr_value'    => $classnum,
154             'value'         => $classnum, #insist on 0 :/
155             'onchange'      => 'filter_change()',
156             'pre_options'   => [ '-1' => 'all',
157                                  '0'  => '(none)', ],
158             'disable_empty' => 1,
159          ).
160   ' )';
161
162 my $recur_toggle = $cgi->param('recurring') ? 'show' : 'hide';
163 $cgi->param('recurring', $cgi->param('recurring') ^ 1 );
164
165 $html_posttotal .=
166   '( <A HREF="'. $cgi->self_url.'">'. "$recur_toggle one-time charges</A> )";
167
168 $cgi->param('recurring', $cgi->param('recurring') ^ 1 ); #put it back
169
170 # ------
171
172 my $link = [ $p.'edit/part_pkg.cgi?', 'pkgpart' ];
173
174 my @header = ( '#', 'Package', 'Comment', 'Custom' );
175 my @fields = ( 'pkgpart', 'pkg', 'comment',
176                sub{ '<B><FONT COLOR="#0000CC">'.$_[0]->custom.'</FONT></B>' }
177              );
178 my $align = 'rllc';
179 my @links = ( $link, $link, '', '' );
180
181 unless ( 0 ) { #already showing only one class or something?
182   push @header, 'Class';
183   push @fields, sub { shift->classname || '(none)'; };
184   $align .= 'l';
185 }
186
187 if ( $conf->exists('pkg-addon_classnum') ) {
188   push @header, "Add'l order class";
189   push @fields, sub { shift->addon_classname || '(none)'; };
190   $align .= 'l';
191 }
192
193 tie my %plans, 'Tie::IxHash', %{ FS::part_pkg::plan_info() };
194
195 tie my %plan_labels, 'Tie::IxHash',
196   map {  $_ => ( $plans{$_}->{'shortname'} || $plans{$_}->{'name'} ) }
197       keys %plans;
198
199 push @header, 'Pricing';
200 $align .= 'r'; #?
201 push @fields, sub {
202   my $part_pkg = shift;
203   (my $plan = $plan_labels{$part_pkg->plan} ) =~ s/ /&nbsp;/g;
204   my $is_recur = ( $part_pkg->freq ne '0' );
205   my @discounts = sort { $a->months <=> $b->months }
206                   map { $_->discount  }
207                   $part_pkg->part_pkg_discount;
208
209   [
210     [
211       { data =>$plan,
212         align=>'center',
213         colspan=>2,
214       },
215     ],
216     [
217       { data =>$money_char.
218                sprintf('%.2f', $part_pkg->option('setup_fee') ),
219         align=>'right'
220       },
221       { data => ( $is_recur ? ' setup' : ' one-time' ),
222         align=>'left',
223       },
224     ],
225     [
226       { data=>( $is_recur
227                   ? $money_char.sprintf('%.2f ', $part_pkg->option('recur_fee') )
228                   : $part_pkg->freq_pretty
229               ),
230         align=> ( $is_recur ? 'right' : 'center' ),
231         colspan=> ( $is_recur ? 1 : 2 ),
232       },
233       ( $is_recur
234         ?  { data => ( $is_recur ? $part_pkg->freq_pretty : '' ),
235              align=>'left',
236            }
237         : ()
238       ),
239     ],
240     ( map { 
241             my $dst_pkg = $_->dst_pkg;
242             [ 
243               { data => 'Add-on:&nbsp;'.$dst_pkg->pkg_comment,
244                 align=>'center', #?
245                 colspan=>2,
246               }
247             ]
248           }
249       $part_pkg->bill_part_pkg_link
250     ),
251     ( scalar(@discounts)
252         ?  [ 
253               { data => '<b>Discounts</b>',
254                 align=>'center', #?
255                 colspan=>2,
256               }
257             ]
258         : ()  
259     ),
260     ( scalar(@discounts)
261         ? map { 
262             [ 
263               { data  => $_->months. ':',
264                 align => 'right',
265               },
266               { data => $_->amount ? '$'. $_->amount : $_->percent. '%'
267               }
268             ]
269           }
270           @discounts
271         : ()
272     ),
273   ];
274
275 #  $plan_labels{$part_pkg->plan}.'<BR>'.
276 #    $money_char.sprintf('%.2f setup<BR>', $part_pkg->option('setup_fee') ).
277 #    ( $part_pkg->freq ne '0'
278 #      ? $money_char.sprintf('%.2f ', $part_pkg->option('recur_fee') )
279 #      : ''
280 #    ).
281 #    $part_pkg->freq_pretty; #.'<BR>'
282 };
283
284 ###
285 # Agent goes here if displayed
286 ###
287
288 #agent type
289 if ( $acl_edit_global ) {
290   #really we just want a count, but this is fine unless someone has tons
291   my @all_agent_types = map {$_->typenum} qsearch('agent_type',{});
292   if ( scalar(@all_agent_types) > 1 ) {
293     push @header, 'Agent types';
294     my $typelink = $p. 'edit/agent_type.cgi?';
295     push @fields, sub { my $part_pkg = shift;
296                         [
297                           map { my $agent_type = $_->agent_type;
298                                 [ 
299                                   { 'data'  => $agent_type->atype, #escape?
300                                     'align' => 'left',
301                                     'link'  => ( $acl_config
302                                                    ? $typelink.
303                                                      $agent_type->typenum
304                                                    : ''
305                                                ),
306                                   },
307                                 ];
308                               }
309                               $part_pkg->type_pkgs
310                         ];
311                       };
312     $align .= 'l';
313   }
314 }
315
316 #if ( $cgi->param('active') ) {
317   push @header, 'Customer<BR>packages';
318   my %col = (
319     'not yet billed'  => '009999', #teal? cyan?
320     'active'          => '00CC00',
321     'suspended'       => 'FF9900',
322     'cancelled'       => 'FF0000',
323     #'one-time charge' => '000000',
324     'charge'          => '000000',
325   );
326   my $cust_pkg_link = $p. 'search/cust_pkg.cgi?pkgpart=';
327   push @fields, sub { my $part_pkg = shift;
328                       [
329                         map {
330                               my $magic = $_;
331                               my $label = $_;
332                               if ( $magic eq 'active' && $part_pkg->freq == 0 ) {
333                                 $magic = 'inactive';
334                                 #$label = 'one-time charge',
335                                 $label = 'charge',
336                               }
337                               $label= 'not yet billed' if $magic eq 'not_yet_billed';
338                           
339                               [
340                                 {
341                                  'data'  => '<B><FONT COLOR="#'. $col{$label}. '">'.
342                                             $part_pkg->get("num_$_").
343                                             '</FONT></B>',
344                                  'align' => 'right',
345                                 },
346                                 {
347                                  'data'  => $label.
348                                               ( $part_pkg->get("num_$_") != 1
349                                                 && $label =~ /charge$/
350                                                   ? 's'
351                                                   : ''
352                                               ),
353                                  'align' => 'left',
354                                  'link'  => ( $part_pkg->get("num_$_")
355                                                 ? $cust_pkg_link.
356                                                   $part_pkg->pkgpart.
357                                                   ";magic=$magic"
358                                                 : ''
359                                             ),
360                                 },
361                               ],
362                             } (qw( not_yet_billed active suspended cancelled ))
363                       ]; };
364   $align .= 'r';
365 #}
366
367 if ( $taxclasses ) {
368   push @header, 'Taxclass';
369   push @fields, sub { shift->taxclass() || '&nbsp;'; };
370   $align .= 'l';
371 }
372
373 push @header, 'Plan options',
374               'Services';
375               #'Service', 'Quan', 'Primary';
376
377 push @fields, 
378               sub {
379                     my $part_pkg = shift;
380                     if ( $part_pkg->plan ) {
381
382                       my %options = $part_pkg->options;
383
384                       [ map { 
385                               [
386                                 { 'data'  => $_,
387                                   'align' => 'right',
388                                 },
389                                 { 'data'  => $part_pkg->format($_,$options{$_}),
390                                   'align' => 'left',
391                                 },
392                               ];
393                             }
394                         grep { $options{$_} =~ /\S/ } 
395                         grep { $_ !~ /^(setup|recur)_fee$/ }
396                         keys %options
397                       ];
398
399                     } else {
400
401                       [ map { [
402                                 { 'data'  => uc($_),
403                                   'align' => 'right',
404                                 },
405                                 {
406                                   'data'  => $part_pkg->$_(),
407                                   'align' => 'left',
408                                 },
409                               ];
410                             }
411                         (qw(setup recur))
412                       ];
413
414                     }
415
416                   },
417
418               sub {
419                     my $part_pkg = shift;
420
421                     [ 
422                       (map {
423                              my $pkg_svc = $_;
424                              my $part_svc = $pkg_svc->part_svc;
425                              my $svc = $part_svc->svc;
426                              if ( $pkg_svc->primary_svc =~ /^Y/i ) {
427                                $svc = "<B>$svc (PRIMARY)</B>";
428                              }
429                              $svc =~ s/ +/&nbsp;/g;
430
431                              [
432                                {
433                                  'data'  => '<B>'. $pkg_svc->quantity. '</B>',
434                                  'align' => 'right'
435                                },
436                                {
437                                  'data'  => $svc,
438                                  'align' => 'left',
439                                  'link'  => ( $acl_config
440                                                 ? $p. 'edit/part_svc.cgi?'.
441                                                   $part_svc->svcpart
442                                                 : ''
443                                             ),
444                                },
445                              ];
446                            }
447                       sort {     $b->primary_svc =~ /^Y/i
448                              <=> $a->primary_svc =~ /^Y/i
449                            }
450                            $part_pkg->pkg_svc('disable_linked'=>1)
451                       ),
452                       ( map { 
453                               my $dst_pkg = $_->dst_pkg;
454                               [
455                                 { data => 'Add-on:&nbsp;'.$dst_pkg->pkg_comment,
456                                   align=>'center', #?
457                                   colspan=>2,
458                                 }
459                               ]
460                             }
461                         $part_pkg->svc_part_pkg_link
462                       )
463                     ];
464
465                   };
466
467 $align .= 'lrl'; #rr';
468
469 # --------
470
471 my $count_extra_sql = $extra_sql;
472 $count_extra_sql =~ s/^\s*AND /WHERE /i;
473 $extra_count = ( $count_extra_sql ? ' AND ' : ' WHERE ' ). $extra_count
474   if $extra_count;
475 my $count_query = "SELECT COUNT(*) FROM part_pkg $count_extra_sql $extra_count";
476
477 </%init>