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