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