disable agent types, RT#31446
[freeside.git] / httemplate / browse / part_pkg.cgi
1 <% include( 'elements/browse.html',
2                  'title'                 => 'Package Definitions',
3                  'menubar'               => \@menubar,
4                  'html_init'             => $html_init,
5                  'html_form'             => $html_form,
6                  'html_posttotal'        => $html_posttotal,
7                  'name'                  => 'package definitions',
8                  'disableable'           => 1,
9                  'disabled_statuspos'    => 4,
10                  'agent_virt'            => 1,
11                  'agent_null_right'      => [ $edit, $edit_global ],
12                  'agent_null_right_link' => $edit_global,
13                  'agent_pos'             => 7, #5?
14                  'query'                 => { 'select'    => $select,
15                                               'table'     => 'part_pkg',
16                                               'hashref'   => \%hash,
17                                               'extra_sql' => $extra_sql,
18                                               'order_by'  => "ORDER BY $orderby"
19                                             },
20                  'count_query'           => $count_query,
21                  'header'                => \@header,
22                  'fields'                => \@fields,
23                  'links'                 => \@links,
24                  'align'                 => $align,
25                  'link_field'            => 'pkgpart',
26                  'html_init'             => $html_init,
27                  'html_foot'             => $html_foot,
28              )
29 %>
30 <%init>
31
32 my $curuser = $FS::CurrentUser::CurrentUser;
33
34 my $edit        = 'Edit package definitions';
35 my $edit_global = 'Edit global package definitions';
36 my $acl_edit        = $curuser->access_right($edit);
37 my $acl_edit_global = $curuser->access_right($edit_global);
38 my $acl_config      = $curuser->access_right('Configuration'); #to edit services
39                                                                #and agent types
40                                                                #and bulk change
41 my $acl_edit_bulk   = $curuser->access_right('Bulk edit package definitions');
42
43 die "access denied"
44   unless $acl_edit || $acl_edit_global;
45
46 my $conf = new FS::Conf;
47 my $taxclasses = $conf->exists('enable_taxclasses');
48 my $money_char = $conf->config('money_char') || '$';
49
50 my $select = '*';
51 my $orderby = 'pkgpart';
52 my %hash = ();
53 my $extra_count = '';
54 my $family_pkgpart;
55
56 if ( $cgi->param('active') ) {
57   $orderby = 'num_active DESC';
58 }
59
60 my @where = ();
61
62 #if ( $cgi->param('activeONLY') ) {
63 #  push @where, ' WHERE num_active > 0 '; #XXX doesn't affect count...
64 #}
65
66 if ( $cgi->param('recurring') ) {
67   $hash{'freq'} = { op=>'!=', value=>'0' };
68   $extra_count = " freq != '0' ";
69 }
70
71 my $classnum = '';
72 if ( $cgi->param('classnum') =~ /^(\d+)$/ ) {
73   $classnum = $1;
74   push @where, $classnum ? "classnum =  $classnum"
75                          : "classnum IS NULL";
76 }
77 $cgi->delete('classnum');
78
79 if ( $cgi->param('missing_recur_fee') ) {
80   push @where, "NOT EXISTS ( SELECT 1 FROM part_pkg_option
81                                WHERE optionname = 'recur_fee'
82                                  AND part_pkg_option.pkgpart = part_pkg.pkgpart
83                                  AND CAST( optionvalue AS NUMERIC ) > 0
84                            )";
85 }
86
87 if ( $cgi->param('family') =~ /^(\d+)$/ ) {
88   $family_pkgpart = $1;
89   push @where, "family_pkgpart = $1";
90   # Hiding disabled or one-time charges and limiting by classnum aren't 
91   # very useful in this mode, so all links should still refer back to the 
92   # non-family-limited display.
93   $cgi->param('showdisabled', 1);
94   $cgi->delete('family');
95 }
96
97 push @where, FS::part_pkg->curuser_pkgs_sql
98   unless $acl_edit_global;
99
100 my $extra_sql = scalar(@where)
101                 ? ( scalar(keys %hash) ? ' AND ' : ' WHERE ' ).
102                   join( 'AND ', @where)
103                 : '';
104
105 my $agentnums_sql = $curuser->agentnums_sql( 'table'=>'cust_main' );
106 my $count_cust_pkg = "
107   SELECT COUNT(*) FROM cust_pkg LEFT JOIN cust_main USING ( custnum )
108     WHERE cust_pkg.pkgpart = part_pkg.pkgpart
109       AND $agentnums_sql
110 ";
111 my $count_cust_pkg_cancel = "
112   SELECT COUNT(*) FROM cust_pkg LEFT JOIN cust_main USING ( custnum )
113     LEFT JOIN cust_pkg AS cust_pkg_next
114       ON (cust_pkg.pkgnum = cust_pkg_next.change_pkgnum)
115     WHERE cust_pkg.pkgpart = part_pkg.pkgpart
116       AND $agentnums_sql
117       AND cust_pkg.cancel IS NOT NULL AND cust_pkg.cancel != 0
118 ";
119
120 $select = "
121
122   *,
123
124   ( $count_cust_pkg
125       AND ( setup IS NULL OR setup = 0 )
126       AND ( cancel IS NULL OR cancel = 0 )
127       AND ( susp IS NULL OR susp = 0 )
128   ) AS num_not_yet_billed,
129
130   ( $count_cust_pkg
131       AND setup IS NOT NULL AND setup != 0
132       AND ( cancel IS NULL OR cancel = 0 )
133       AND ( susp IS NULL OR susp = 0 )
134   ) AS num_active,
135
136   ( $count_cust_pkg
137       AND ( cancel IS NULL OR cancel = 0 )
138       AND susp IS NOT NULL AND susp != 0
139       AND setup IS NOT NULL AND setup != 0
140   ) AS num_suspended,
141
142   ( $count_cust_pkg
143       AND ( cancel IS NULL OR cancel = 0 )
144       AND susp IS NOT NULL AND susp != 0
145       AND ( setup IS NULL OR setup = 0 )
146   ) AS num_on_hold,
147
148   ( $count_cust_pkg_cancel
149       AND (cust_pkg_next.pkgnum IS NULL
150            OR cust_pkg_next.pkgpart != cust_pkg.pkgpart)
151   ) AS num_cancelled
152
153 ";
154 # About the num_cancelled expression: packages that were changed, but 
155 # kept the same pkgpart, are considered "moved", not "canceled" (because
156 # this is the part_pkg UI).  We could show the count of those but it's 
157 # probably not interesting.
158
159 my $html_init = qq!
160     One or more service definitions are grouped together into a package 
161     definition and given pricing information.  Customers purchase packages
162     rather than purchase services directly.<BR><BR>
163     <FORM METHOD="GET" ACTION="${p}edit/part_pkg.cgi">
164     <A HREF="${p}edit/part_pkg.cgi"><I>Add a new package definition</I></A>
165     or
166     !.include('/elements/select-part_pkg.html', 'element_name' => 'clone' ). qq!
167     <INPUT TYPE="submit" VALUE="Clone existing package">
168     </FORM>
169     <BR><BR>
170   !;
171
172 $cgi->param('dummy', 1);
173
174 my $filter_change =
175   qq(\n<SCRIPT TYPE="text/javascript">\n).
176   "function filter_change() {".
177   "  window.location = '". $cgi->self_url.
178        ";classnum=' + document.getElementById('classnum').options[document.getElementById('classnum').selectedIndex].value".
179   "}".
180   "\n</SCRIPT>\n";
181
182 #restore this so pagination works
183 $cgi->param('classnum', $classnum) if length($classnum);
184
185 #should hide this if there aren't any classes
186 my $html_posttotal =
187   "$filter_change\n<BR>( show class: ".
188   include('/elements/select-pkg_class.html',
189             #'curr_value'    => $classnum,
190             'value'         => $classnum, #insist on 0 :/
191             'onchange'      => 'filter_change()',
192             'pre_options'   => [ '-1' => 'all',
193                                  '0'  => '(none)', ],
194             'disable_empty' => 1,
195          ).
196   ' )';
197
198 my $recur_toggle = $cgi->param('recurring') ? 'show' : 'hide';
199 $cgi->param('recurring', $cgi->param('recurring') ^ 1 );
200
201 $html_posttotal .=
202   '( <A HREF="'. $cgi->self_url.'">'. "$recur_toggle one-time charges</A> )";
203
204 $cgi->param('recurring', $cgi->param('recurring') ^ 1 ); #put it back
205
206 # ------
207
208 my $link = [ $p.'edit/part_pkg.cgi?', 'pkgpart' ];
209
210 my @header = ( '#', 'Package', 'Comment', 'Custom' );
211 my @fields = ( 'pkgpart', 'pkg', 'comment',
212                sub{ '<B><FONT COLOR="#0000CC">'.$_[0]->custom.'</FONT></B>' }
213              );
214 my $align = 'rllc';
215 my @links = ( $link, $link, '', '' );
216
217 unless ( 0 ) { #already showing only one class or something?
218   push @header, 'Class';
219   push @fields, sub { shift->classname || '(none)'; };
220   $align .= 'l';
221 }
222
223 if ( $conf->exists('pkg-addon_classnum') ) {
224   push @header, "Add'l order class";
225   push @fields, sub { shift->addon_classname || '(none)'; };
226   $align .= 'l';
227 }
228
229 tie my %plans, 'Tie::IxHash', %{ FS::part_pkg::plan_info() };
230
231 tie my %plan_labels, 'Tie::IxHash',
232   map {  $_ => ( $plans{$_}->{'shortname'} || $plans{$_}->{'name'} ) }
233       keys %plans;
234
235 push @header, 'Pricing';
236 $align .= 'r'; #?
237 push @fields, sub {
238   my $part_pkg = shift;
239   (my $plan = $plan_labels{$part_pkg->plan} ) =~ s/ /&nbsp;/g;
240   my $is_recur = ( $part_pkg->freq ne '0' );
241   my @discounts = sort { $a->months <=> $b->months }
242                   map { $_->discount  }
243                   $part_pkg->part_pkg_discount;
244
245   [
246     ( !$family_pkgpart &&
247       $part_pkg->pkgpart == $part_pkg->family_pkgpart ? () : [
248       {
249         'align'=> 'center',
250         'colspan' => 2,
251         'size' => '-1',
252         'data' => '<b>Show all versions</b>',
253         'link' => $p.'browse/part_pkg.cgi?family='.$part_pkg->family_pkgpart,
254       }
255     ] ),
256     [
257       { data =>$plan,
258         align=>'center',
259         colspan=>2,
260       },
261     ],
262     [
263       { data =>$money_char.
264                sprintf('%.2f ', $part_pkg->option('setup_fee') ),
265         align=>'right'
266       },
267       { data => ( ( $is_recur ? ' &nbsp; setup' : ' &nbsp; one-time' ).
268                   ( $part_pkg->option('recur_fee') == 0
269                       && $part_pkg->setup_show_zero
270                     ? ' (printed on invoices)'
271                     : ''
272                   )
273                 ),
274         align=>'left',
275       },
276     ],
277     [
278       { data=>(
279           $is_recur
280             ? $money_char. sprintf('%.2f', $part_pkg->option('recur_fee'))
281             : $part_pkg->freq_pretty
282         ),
283         align=> ( $is_recur ? 'right' : 'center' ),
284         colspan=> ( $is_recur ? 1 : 2 ),
285       },
286       ( $is_recur
287         ?  { data => ( $is_recur
288                ? ' &nbsp; '. $part_pkg->freq_pretty.
289                  ( $part_pkg->option('recur_fee') == 0
290                      && $part_pkg->recur_show_zero
291                    ? ' (printed on invoices)'
292                    : ''
293                  )
294                : '' ),
295              align=>'left',
296            }
297         : ()
298       ),
299     ],
300     (
301       map { my $amount = $_->amount / ($_->target_info->{multiplier} || 1);
302             my $label = $_->target_info->{label};
303             [
304               { data    => "Plus&nbsp;$money_char". $_->price. '&nbsp;'.
305                            ( $_->action eq 'increment' ? 'per' : 'for' ).
306                            "&nbsp;$amount&nbsp;$label",
307                 align   => 'center', #left?
308                 colspan => 2,
309               },
310             ];
311           }
312         $part_pkg->part_pkg_usageprice
313     ),
314     ( map { my $dst_pkg = $_->dst_pkg;
315             [
316               { data => 'Supplemental: &nbsp;'.
317                         '<A HREF="#'. $dst_pkg->pkgpart . '">' .
318                         $dst_pkg->pkg . '</A>',
319                 align=> 'center',
320                 colspan => 2,
321               }
322             ]
323           }
324       $part_pkg->supp_part_pkg_link
325     ),
326     ( map { 
327             my $dst_pkg = $_->dst_pkg;
328             [ 
329               { data => 'Add-on:&nbsp;'.$dst_pkg->pkg_comment,
330                 align=>'center', #?
331                 colspan=>2,
332               }
333             ]
334           }
335       $part_pkg->bill_part_pkg_link
336     ),
337     ( scalar(@discounts)
338         ?  [ 
339               { data => '<b>Discounts</b>',
340                 align=>'center', #?
341                 colspan=>2,
342               }
343             ]
344         : ()  
345     ),
346     ( scalar(@discounts)
347         ? map { 
348             [ 
349               { data  => $_->months. ':',
350                 align => 'right',
351               },
352               { data => $_->amount ? '$'. $_->amount : $_->percent. '%'
353               }
354             ]
355           }
356           @discounts
357         : ()
358     ),
359   ];
360
361 #  $plan_labels{$part_pkg->plan}.'<BR>'.
362 #    $money_char.sprintf('%.2f setup<BR>', $part_pkg->option('setup_fee') ).
363 #    ( $part_pkg->freq ne '0'
364 #      ? $money_char.sprintf('%.2f ', $part_pkg->option('recur_fee') )
365 #      : ''
366 #    ).
367 #    $part_pkg->freq_pretty; #.'<BR>'
368 };
369
370 push @header, 'Cost&nbsp;tracking';
371 $align .= 'r'; #?
372 push @fields, sub {
373   my $part_pkg = shift;
374   #(my $plan = $plan_labels{$part_pkg->plan} ) =~ s/ /&nbsp;/g;
375   my $is_recur = ( $part_pkg->freq ne '0' );
376
377   [
378     [
379       { data => '&nbsp;', # $plan,
380         align=>'center',
381         colspan=>2,
382       },
383     ],
384     [
385       { data =>$money_char.
386                sprintf('%.2f ', $part_pkg->setup_cost ),
387         align=>'right'
388       },
389       { data => ( $is_recur ? '&nbsp;setup' : '&nbsp;one-time' ),
390         align=>'left',
391       },
392     ],
393     [
394       { data=>(
395           $is_recur
396             ? $money_char. sprintf('%.2f', $part_pkg->recur_cost)
397             : '(no&nbsp;recurring)' #$part_pkg->freq_pretty
398         ),
399         align=> ( $is_recur ? 'right' : 'center' ),
400         colspan=> ( $is_recur ? 1 : 2 ),
401       },
402       ( $is_recur
403         ?  { data => ( $is_recur
404                          ? '&nbsp;'. $part_pkg->freq_pretty
405                          : ''
406                      ),
407              align=>'left',
408            }
409         : ()
410       ),
411     ],
412   ];
413 };
414
415 ###
416 # Agent goes here if displayed
417 ###
418
419 #agent type
420 if ( $acl_edit_global ) {
421   #really we just want a count, but this is fine unless someone has tons
422   my @all_agent_types = map {$_->typenum}
423                           qsearch('agent_type', { 'disabled'=>'' });
424   if ( scalar(@all_agent_types) > 1 ) {
425     push @header, 'Agent types';
426     my $typelink = $p. 'edit/agent_type.cgi?';
427     push @fields, sub { my $part_pkg = shift;
428                         [
429                           map { my $agent_type = $_->agent_type;
430                                 [ 
431                                   { 'data'  => $agent_type->atype, #escape?
432                                     'align' => 'left',
433                                     'link'  => ( $acl_config
434                                                    ? $typelink.
435                                                      $agent_type->typenum
436                                                    : ''
437                                                ),
438                                   },
439                                 ];
440                               }
441                               $part_pkg->type_pkgs
442                         ];
443                       };
444     $align .= 'l';
445   }
446 }
447
448 #if ( $cgi->param('active') ) {
449   push @header, 'Customer<BR>packages';
450   my %col = (
451     'on hold'         => '7E0079', #purple!
452     'not yet billed'  => '009999', #teal? cyan?
453     'active'          => '00CC00',
454     'suspended'       => 'FF9900',
455     'cancelled'       => 'FF0000',
456     #'one-time charge' => '000000',
457     'charge'          => '000000',
458   );
459   my $cust_pkg_link = $p. 'search/cust_pkg.cgi?pkgpart=';
460   push @fields, sub { my $part_pkg = shift;
461                         [
462                         map( {
463                               my $magic = $_;
464                               my $label = $_;
465                               if ( $magic eq 'active' && $part_pkg->freq == 0 ) {
466                                 $magic = 'inactive';
467                                 #$label = 'one-time charge';
468                                 $label = 'charge';
469                               }
470                               $label= 'not yet billed' if $magic eq 'not_yet_billed';
471                               $label= 'on hold' if $magic eq 'on_hold';
472                           
473                               [
474                                 {
475                                  'data'  => '<B><FONT COLOR="#'. $col{$label}. '">'.
476                                             $part_pkg->get("num_$_").
477                                             '</FONT></B>',
478                                  'align' => 'right',
479                                 },
480                                 {
481                                  'data'  => $label.
482                                               ( $part_pkg->get("num_$_") != 1
483                                                 && $label =~ /charge$/
484                                                   ? 's'
485                                                   : ''
486                                               ),
487                                  'align' => 'left',
488                                  'link'  => ( $part_pkg->get("num_$_")
489                                                 ? $cust_pkg_link.
490                                                   $part_pkg->pkgpart.
491                                                   ";magic=$magic"
492                                                 : ''
493                                             ),
494                                 },
495                               ],
496                             } (qw( on_hold not_yet_billed active suspended cancelled ))
497                           ),
498                       ($acl_config ? 
499                         [ {}, 
500                           { 'data'  => '<FONT SIZE="-1">[ '.
501                               include('/elements/popup_link.html',
502                                 'label'       => 'change',
503                                 'action'      => "${p}edit/bulk-cust_pkg.html?".
504                                                  'pkgpart='.$part_pkg->pkgpart,
505                                 'actionlabel' => 'Change Packages',
506                                 'width'       => 569,
507                                 'height'      => 210,
508                               ).' ]</FONT>',
509                             'align' => 'left',
510                           } 
511                         ] : () ),
512                       ]; 
513   };
514   $align .= 'r';
515 #}
516
517 if ( $taxclasses ) {
518   push @header, 'Taxclass';
519   push @fields, sub { shift->taxclass() || '&nbsp;'; };
520   $align .= 'l';
521 }
522
523 # make a table of report class optionnames =>  the actual 
524 my %report_optionname_name = map { 'report_option_'.$_->num, $_->name }
525   qsearch('part_pkg_report_option', { disabled => '' });
526
527 push @header, 'Plan options',
528               'Services';
529               #'Service', 'Quan', 'Primary';
530
531 push @fields, 
532               sub {
533                     my $part_pkg = shift;
534                     if ( $part_pkg->plan ) {
535
536                       my %options = $part_pkg->options;
537                       # gather any options that are really report options,
538                       # convert them to their user-friendly names,
539                       # and sort them (I think?)
540                       my @report_options =
541                         sort { $a cmp $b }
542                         map { $report_optionname_name{$_} }
543                         grep { $options{$_}
544                                and exists($report_optionname_name{$_}) }
545                         keys %options;
546
547                       my @rows = (
548                         map { 
549                               [
550                                 { 'data'  => "$_: ",
551                                   'align' => 'right',
552                                 },
553                                 { 'data'  => $part_pkg->format($_,$options{$_}),
554                                   'align' => 'left',
555                                 },
556                               ];
557                             }
558                         grep { $options{$_} =~ /\S/ } 
559                         grep { $_ !~ /^(setup|recur)_fee$/ 
560                                and $_ !~ /^report_option_\d+$/ }
561                         keys %options
562                       );
563                       if ( @report_options ) {
564                         push @rows,
565                           [ { 'data'  => 'Report classes',
566                               'align' => 'center',
567                               'style' => 'font-weight: bold',
568                               'colspan' => 2
569                             } ];
570                         foreach (@report_options) {
571                           push @rows, [
572                             { 'data'  => $_,
573                               'align' => 'center',
574                               'colspan' => 2
575                             }
576                           ];
577                         } # foreach @report_options
578                       } # if @report_options
579
580                       return \@rows;
581
582                     } else { # should never happen...
583
584                       [ map { [
585                                 { 'data'  => uc($_),
586                                   'align' => 'right',
587                                 },
588                                 {
589                                   'data'  => $part_pkg->$_(),
590                                   'align' => 'left',
591                                 },
592                               ];
593                             }
594                         (qw(setup recur))
595                       ];
596
597                     }
598
599                   },
600
601               sub {
602                     my $part_pkg = shift;
603                     my @part_pkg_usage = sort { $a->priority <=> $b->priority }
604                                          $part_pkg->part_pkg_usage;
605
606                     [ 
607                       (map {
608                              my $pkg_svc = $_;
609                              my $part_svc = $pkg_svc->part_svc;
610                              my $svc = $part_svc->svc;
611                              if ( $pkg_svc->primary_svc =~ /^Y/i ) {
612                                $svc = "<B>$svc (PRIMARY)</B>";
613                              }
614                              $svc =~ s/ +/&nbsp;/g;
615
616                              [
617                                {
618                                  'data'  => '<B>'. $pkg_svc->quantity. '</B>',
619                                  'align' => 'right'
620                                },
621                                {
622                                  'data'  => $svc,
623                                  'align' => 'left',
624                                  'link'  => ( $acl_config
625                                                 ? $p. 'edit/part_svc.cgi?'.
626                                                   $part_svc->svcpart
627                                                 : ''
628                                             ),
629                                },
630                              ];
631                            }
632                       sort {     $b->primary_svc =~ /^Y/i
633                              <=> $a->primary_svc =~ /^Y/i
634                            }
635                            $part_pkg->pkg_svc('disable_linked'=>1)
636                       ),
637                       ( map { 
638                               my $dst_pkg = $_->dst_pkg;
639                               [
640                                 { data => 'Add-on:&nbsp;'.$dst_pkg->pkg_comment,
641                                   align=>'center', #?
642                                   colspan=>2,
643                                 }
644                               ]
645                             }
646                         $part_pkg->svc_part_pkg_link
647                       ),
648                       ( scalar(@part_pkg_usage) ? 
649                           [ { data  => 'Usage minutes',
650                               align => 'center',
651                               colspan    => 2,
652                               data_style => 'b',
653                               link  => $p.'browse/part_pkg_usage.html#pkgpart'.
654                                        $part_pkg->pkgpart 
655                             } ]
656                           : ()
657                       ),
658                       ( map {
659                               [ { data  => $_->minutes,
660                                   align => 'right'
661                                 },
662                                 { data  => $_->description,
663                                   align => 'left'
664                                 },
665                               ]
666                             } @part_pkg_usage
667                       ),
668                     ];
669
670                   };
671
672 $align .= 'lrl'; #rr';
673
674 # --------
675
676 my $count_extra_sql = $extra_sql;
677 $count_extra_sql =~ s/^\s*AND /WHERE /i;
678 $extra_count = ( $count_extra_sql ? ' AND ' : ' WHERE ' ). $extra_count
679   if $extra_count;
680 my $count_query = "SELECT COUNT(*) FROM part_pkg $count_extra_sql $extra_count";
681
682 my $html_form = '';
683 my $html_foot = '';
684 if ( $acl_edit_bulk ) {
685   # insert a checkbox column
686   push @header, '';
687   push @fields, sub {
688     '<INPUT TYPE="checkbox" NAME="pkgpart" VALUE=' . $_[0]->pkgpart .'>';
689   };
690   push @links, '';
691   $align .= 'c';
692   $html_form = qq!<FORM ACTION="${p}edit/bulk-part_pkg.html" METHOD="POST">!;
693   $html_foot = include('/search/elements/checkbox-foot.html',
694       submit  => 'edit report classes', # for now it's only report classes
695   ) . '</FORM>';
696 }
697
698 my @menubar;
699 # show this if there are any voip_cdr packages defined
700 if ( FS::part_pkg->count("plan = 'voip_cdr'") ) {
701   push @menubar, 'Per-package usage minutes' => $p.'browse/part_pkg_usage.html';
702 }
703 </%init>