apply some heuristics to transfer ordering: primaries first, then sorted by quantity
[freeside.git] / httemplate / view / cust_main.cgi
1 <!-- mason kludge -->
2 <%
3
4 my $conf = new FS::Conf;
5
6 my %uiview = ();
7 my %uiadd = ();
8 foreach my $part_svc ( qsearch('part_svc',{}) ) {
9   $uiview{$part_svc->svcpart} = popurl(2). "view/". $part_svc->svcdb . ".cgi";
10   $uiadd{$part_svc->svcpart}= popurl(2). "edit/". $part_svc->svcdb . ".cgi";
11 }
12
13 print header("Customer View", menubar(
14   'Main Menu' => popurl(2)
15 ));
16
17 %>
18
19 <STYLE TYPE="text/css">
20 .package TH { font-size: medium }
21 .package TR { font-size: smaller }
22 .package .provision { font-weight: bold }
23 </STYLE>
24
25 <%
26
27 die "No customer specified (bad URL)!" unless $cgi->keywords;
28 my($query) = $cgi->keywords; # needs parens with my, ->keywords returns array
29 $query =~ /^(\d+)$/;
30 my $custnum = $1;
31 my $cust_main = qsearchs('cust_main',{'custnum'=>$custnum});
32 die "Customer not found!" unless $cust_main;
33
34 print qq!<A HREF="${p}edit/cust_main.cgi?$custnum">Edit this customer</A>!;
35
36 %>
37
38 <SCRIPT>
39 function cancel_areyousure(href) {
40     if (confirm("Perminantly delete all services and cancel this customer?") == true)
41         window.location.href = href;
42 }
43 </SCRIPT>
44
45 <%
46
47 print qq! | <A HREF="javascript:cancel_areyousure('${p}misc/cust_main-cancel.cgi?$custnum')">!.
48       'Cancel this customer</A>'
49   if $cust_main->ncancelled_pkgs;
50
51 print qq! | <A HREF="${p}misc/delete-customer.cgi?$custnum">!.
52       'Delete this customer</A>'
53   if $conf->exists('deletecustomers');
54
55 unless ( $conf->exists('disable_customer_referrals') ) {
56   print qq! | <A HREF="!, popurl(2),
57         qq!edit/cust_main.cgi?referral_custnum=$custnum">!,
58         qq!Refer a new customer</A>!;
59
60   print qq! | <A HREF="!, popurl(2),
61         qq!search/cust_main.cgi?referral_custnum=$custnum">!,
62         qq!View this customer's referrals</A>!;
63 }
64
65 print '<BR><BR>';
66
67 my $signupurl = $conf->config('signupurl');
68 if ( $signupurl ) {
69 print "This customer's signup URL: ".
70       "<a href=\"$signupurl?ref=$custnum\">$signupurl?ref=$custnum</a><BR><BR>";
71 }
72
73 print '<A NAME="cust_main"></A>';
74
75 print &itable(), '<TR>';
76
77 print '<TD VALIGN="top">';
78
79   print "Billing address", &ntable("#cccccc"), "<TR><TD>",
80         &ntable("#cccccc",2),
81     '<TR><TD ALIGN="right">Contact&nbsp;name</TD>',
82       '<TD COLSPAN=3 BGCOLOR="#ffffff">',
83       $cust_main->last, ', ', $cust_main->first,
84       '</TD>';
85 print '<TD ALIGN="right">SS#</TD><TD BGCOLOR="#ffffff">',
86       $cust_main->ss || '&nbsp', '</TD>'
87   if $conf->exists('show_ss');
88
89 print '</TR>',
90     '<TR><TD ALIGN="right">Company</TD><TD COLSPAN=5 BGCOLOR="#ffffff">',
91       $cust_main->company,
92       '</TD></TR>',
93     '<TR><TD ALIGN="right">Address</TD><TD COLSPAN=5 BGCOLOR="#ffffff">',
94       $cust_main->address1,
95       '</TD></TR>',
96   ;
97   print '<TR><TD ALIGN="right">&nbsp;</TD><TD COLSPAN=5 BGCOLOR="#ffffff">',
98         $cust_main->address2, '</TD></TR>'
99     if $cust_main->address2;
100   print '<TR><TD ALIGN="right">City</TD><TD BGCOLOR="#ffffff">',
101           $cust_main->city,
102           '</TD><TD ALIGN="right">State</TD><TD BGCOLOR="#ffffff">',
103           $cust_main->state,
104           '</TD><TD ALIGN="right">Zip</TD><TD BGCOLOR="#ffffff">',
105           $cust_main->zip, '</TD></TR>',
106         '<TR><TD ALIGN="right">Country</TD><TD BGCOLOR="#ffffff">',
107           $cust_main->country,
108           '</TD></TR>',
109   ;
110   my $daytime_label = FS::Msgcat::_gettext('daytime') || 'Day&nbsp;Phone';
111   my $night_label = FS::Msgcat::_gettext('night') || 'Night&nbsp;Phone';
112   print '<TR><TD ALIGN="right">'. $daytime_label.
113           '</TD><TD COLSPAN=5 BGCOLOR="#ffffff">',
114           $cust_main->daytime || '&nbsp', '</TD></TR>',
115         '<TR><TD ALIGN="right">'. $night_label. 
116           '</TD><TD COLSPAN=5 BGCOLOR="#ffffff">',
117           $cust_main->night || '&nbsp', '</TD></TR>',
118         '<TR><TD ALIGN="right">Fax</TD><TD COLSPAN=5 BGCOLOR="#ffffff">',
119           $cust_main->fax || '&nbsp', '</TD></TR>',
120         '</TABLE>', "</TD></TR></TABLE>"
121   ;
122
123   if ( defined $cust_main->dbdef_table->column('ship_last') ) {
124
125     my $pre = $cust_main->ship_last ? 'ship_' : '';
126
127     print "<BR>Service address", &ntable("#cccccc"), "<TR><TD>",
128           &ntable("#cccccc",2),
129       '<TR><TD ALIGN="right">Contact name</TD>',
130         '<TD COLSPAN=5 BGCOLOR="#ffffff">',
131         $cust_main->get("${pre}last"), ', ', $cust_main->get("${pre}first"),
132         '</TD></TR>',
133       '<TR><TD ALIGN="right">Company</TD><TD COLSPAN=5 BGCOLOR="#ffffff">',
134         $cust_main->get("${pre}company"),
135         '</TD></TR>',
136       '<TR><TD ALIGN="right">Address</TD><TD COLSPAN=5 BGCOLOR="#ffffff">',
137         $cust_main->get("${pre}address1"),
138         '</TD></TR>',
139     ;
140     print '<TR><TD ALIGN="right">&nbsp;</TD><TD COLSPAN=5 BGCOLOR="#ffffff">',
141           $cust_main->get("${pre}address2"), '</TD></TR>'
142       if $cust_main->get("${pre}address2");
143     print '<TR><TD ALIGN="right">City</TD><TD BGCOLOR="#ffffff">',
144             $cust_main->get("${pre}city"),
145             '</TD><TD ALIGN="right">State</TD><TD BGCOLOR="#ffffff">',
146             $cust_main->get("${pre}state"),
147             '</TD><TD ALIGN="right">Zip</TD><TD BGCOLOR="#ffffff">',
148             $cust_main->get("${pre}zip"), '</TD></TR>',
149           '<TR><TD ALIGN="right">Country</TD><TD BGCOLOR="#ffffff">',
150             $cust_main->get("${pre}country"),
151             '</TD></TR>',
152     ;
153     print '<TR><TD ALIGN="right">'. $daytime_label. '</TD>',
154           '<TD COLSPAN=5 BGCOLOR="#ffffff">',
155             $cust_main->get("${pre}daytime") || '&nbsp', '</TD></TR>',
156           '<TR><TD ALIGN="right">'. $night_label. '</TD>'.
157           '<TD COLSPAN=5 BGCOLOR="#ffffff">',
158             $cust_main->get("${pre}night") || '&nbsp', '</TD></TR>',
159           '<TR><TD ALIGN="right">Fax</TD><TD COLSPAN=5 BGCOLOR="#ffffff">',
160             $cust_main->get("${pre}fax") || '&nbsp', '</TD></TR>',
161           '</TABLE>', "</TD></TR></TABLE>"
162     ;
163
164   }
165
166 print '</TD>';
167
168 print '<TD VALIGN="top">';
169
170   print &ntable("#cccccc"), "<TR><TD>", &ntable("#cccccc",2),
171         '<TR><TD ALIGN="right">Customer&nbsp;number</TD><TD BGCOLOR="#ffffff">',
172         $custnum, '</TD></TR>',
173   ;
174
175   my @agents = qsearch( 'agent', {} );
176   my $agent;
177   unless ( scalar(@agents) == 1 ) {
178     $agent = qsearchs('agent',{ 'agentnum' => $cust_main->agentnum } );
179     print '<TR><TD ALIGN="right">Agent</TD><TD BGCOLOR="#ffffff">',
180         $agent->agentnum, ": ", $agent->agent, '</TD></TR>';
181   } else {
182     $agent = $agents[0];
183   }
184   my @referrals = qsearch( 'part_referral', {} );
185   unless ( scalar(@referrals) == 1 ) {
186     my $referral = qsearchs('part_referral', {
187       'refnum' => $cust_main->refnum
188     } );
189     print '<TR><TD ALIGN="right">Advertising&nbsp;source</TD><TD BGCOLOR="#ffffff">',
190           $referral->refnum, ": ", $referral->referral, '</TD></TR>';
191   }
192   print '<TR><TD ALIGN="right">Order taker</TD><TD BGCOLOR="#ffffff">',
193     $cust_main->otaker, '</TD></TR>';
194
195   print '<TR><TD ALIGN="right">Referring&nbsp;Customer</TD><TD BGCOLOR="#ffffff">';
196   my $referring_cust_main = '';
197   if ( $cust_main->referral_custnum
198        && ( $referring_cust_main =
199             qsearchs('cust_main', { custnum => $cust_main->referral_custnum } )
200           )
201      ) {
202     print '<A HREF="'. popurl(1). 'cust_main.cgi?'.
203           $cust_main->referral_custnum. '">'.
204           $cust_main->referral_custnum. ': '.
205           ( $referring_cust_main->company
206               ? $referring_cust_main->company. ' ('.
207                   $referring_cust_main->last. ', '. $referring_cust_main->first.
208                   ')'
209               : $referring_cust_main->last. ', '. $referring_cust_main->first
210           ).
211           '</A>';
212   }
213   print '</TD></TR>';
214
215   print '</TABLE></TD></TR></TABLE>';
216
217 print '<BR>';
218
219 if ( $conf->config('payby-default') ne 'HIDE' ) {
220
221   my @invoicing_list = $cust_main->invoicing_list;
222   print "Billing information (",
223        qq!<A HREF="!, popurl(2), qq!misc/bill.cgi?$custnum">!, "Bill now</A>)",
224         &ntable("#cccccc"), "<TR><TD>", &ntable("#cccccc",2),
225         '<TR><TD ALIGN="right">Tax&nbsp;exempt</TD><TD BGCOLOR="#ffffff">',
226         $cust_main->tax ? 'yes' : 'no',
227         '</TD></TR>',
228         '<TR><TD ALIGN="right">Postal&nbsp;invoices</TD><TD BGCOLOR="#ffffff">',
229         ( grep { $_ eq 'POST' } @invoicing_list ) ? 'yes' : 'no',
230         '</TD></TR>',
231         '<TR><TD ALIGN="right">Email&nbsp;invoices</TD><TD BGCOLOR="#ffffff">',
232         join(', ', grep { $_ ne 'POST' } @invoicing_list ) || 'no',
233         '</TD></TR>',
234         '<TR><TD ALIGN="right">Billing&nbsp;type</TD><TD BGCOLOR="#ffffff">',
235   ;
236
237   if ( $cust_main->payby eq 'CARD' || $cust_main->payby eq 'DCRD' ) {
238     my $payinfo = $cust_main->payinfo;
239     $payinfo = 'x'x(length($payinfo)-4). substr($payinfo,(length($payinfo)-4));
240     print 'Credit&nbsp;card&nbsp;',
241           ( $cust_main->payby eq 'CARD' ? '(automatic)' : '(on-demand)' ),
242           '</TD></TR>',
243           '<TR><TD ALIGN="right">Card number</TD><TD BGCOLOR="#ffffff">',
244           $payinfo, '</TD></TR>',
245           '<TR><TD ALIGN="right">Expiration</TD><TD BGCOLOR="#ffffff">',
246           $cust_main->paydate, '</TD></TR>',
247           '<TR><TD ALIGN="right">Name on card</TD><TD BGCOLOR="#ffffff">',
248           $cust_main->payname, '</TD></TR>'
249     ;
250   } elsif ( $cust_main->payby eq 'CHEK' || $cust_main->payby eq 'DCHK') {
251     my( $account, $aba ) = split('@', $cust_main->payinfo );
252     print 'Electronic&nbsp;check&nbsp;',
253           ( $cust_main->payby eq 'CHEK' ? '(automatic)' : '(on-demand)' ),
254           '</TD></TR>',
255           '<TR><TD ALIGN="right">Account number</TD><TD BGCOLOR="#ffffff">',
256           $account, '</TD></TR>',
257           '<TR><TD ALIGN="right">ABA/Routing code</TD><TD BGCOLOR="#ffffff">',
258           $aba, '</TD></TR>',
259           '<TR><TD ALIGN="right">Bank name</TD><TD BGCOLOR="#ffffff">',
260           $cust_main->payname, '</TD></TR>'
261     ;
262   } elsif ( $cust_main->payby eq 'LECB' ) {
263     $cust_main->payinfo =~ /^(\d{3})(\d{3})(\d{4})$/;
264     my $payinfo = "$1-$2-$3";
265     print 'Phone&nbsp;bill&nbsp;billing</TD></TR>',
266           '<TR><TD ALIGN="right">Phone number</TD><TD BGCOLOR="#ffffff">',
267           $payinfo, '</TD></TR>',
268     ;
269   } elsif ( $cust_main->payby eq 'BILL' ) {
270     print 'Billing</TD></TR>';
271     print '<TR><TD ALIGN="right">P.O. </TD><TD BGCOLOR="#ffffff">',
272           $cust_main->payinfo, '</TD></TR>',
273       if $cust_main->payinfo;
274     print '<TR><TD ALIGN="right">Expiration</TD><TD BGCOLOR="#ffffff">',
275           $cust_main->paydate, '</TD></TR>',
276           '<TR><TD ALIGN="right">Attention</TD><TD BGCOLOR="#ffffff">',
277           $cust_main->payname, '</TD></TR>',
278     ;
279   } elsif ( $cust_main->payby eq 'COMP' ) {
280     print 'Complimentary</TD></TR>',
281           '<TR><TD ALIGN="right">Authorized&nbsp;by</TD><TD BGCOLOR="#ffffff">',
282           $cust_main->payinfo, '</TD></TR>',
283           '<TR><TD ALIGN="right">Expiration</TD><TD BGCOLOR="#ffffff">',
284           $cust_main->paydate, '</TD></TR>',
285     ;
286   }
287
288   print "</TABLE></TD></TR></TABLE>";
289
290 }
291
292 print '</TD></TR></TABLE>';
293
294 if ( defined $cust_main->dbdef_table->column('comments')
295      && $cust_main->comments =~ /[^\s\n\r]/ )
296 {
297   print "<BR>Comments". &ntable("#cccccc"). "<TR><TD>".
298         &ntable("#cccccc",2).
299         '<TR><TD BGCOLOR="#ffffff"><PRE>'.
300         encode_entities($cust_main->comments).
301         '</PRE></TD></TR></TABLE></TABLE>';
302 }
303
304 print '</TD></TR></TABLE>';
305
306 print '<BR>'.
307   '<FORM ACTION="'.popurl(2).'edit/process/quick-cust_pkg.cgi" METHOD="POST">'.
308   qq!<INPUT TYPE="hidden" NAME="custnum" VALUE="$custnum">!.
309   '<SELECT NAME="pkgpart"><OPTION> ';
310
311 foreach my $part_pkg (
312   qsearch( 'part_pkg', { 'disabled' => '' }, '',
313            ' AND 0 < ( SELECT COUNT(*) FROM type_pkgs '.
314            '             WHERE typenum = '. $agent->typenum.
315            '             AND type_pkgs.pkgpart = part_pkg.pkgpart )'
316          )
317 ) {
318   print '<OPTION VALUE="'. $part_pkg->pkgpart. '">'. $part_pkg->pkg. ' - '.
319         $part_pkg->comment;
320 }
321
322 print '</SELECT><INPUT TYPE="submit" VALUE="Order Package"></FORM><BR>';
323
324 if ( $conf->config('payby-default') ne 'HIDE' ) {
325
326   print
327     qq!<FORM ACTION="${p}edit/process/quick-charge.cgi" METHOD="POST">!.
328     qq!<INPUT TYPE="hidden" NAME="custnum" VALUE="$custnum">!.
329     qq!Description:<INPUT TYPE="text" NAME="pkg">!.
330     qq!&nbsp;Amount:<INPUT TYPE="text" NAME="amount" SIZE=6>!.
331     qq!&nbsp;!;
332   
333   #false laziness w/ edit/part_pkg.cgi
334   if ( $conf->exists('enable_taxclasses') ) {
335     print '<SELECT NAME="taxclass">';
336     my $sth = dbh->prepare('SELECT DISTINCT taxclass FROM cust_main_county')
337       or die dbh->errstr;
338     $sth->execute or die $sth->errstr;
339     foreach my $taxclass ( map $_->[0], @{$sth->fetchall_arrayref} ) {
340       print qq!<OPTION VALUE="$taxclass"!;
341       #print ' SELECTED' if $taxclass eq $hashref->{taxclass};
342       print qq!>$taxclass</OPTION>!;
343     }
344     print '</SELECT>';
345   } else {
346     print '<INPUT TYPE="hidden" NAME="taxclass" VALUE="">';
347   }
348   
349   print qq!<INPUT TYPE="submit" VALUE="One-time charge"></FORM><BR>!;
350
351 }
352
353 %>
354
355 <SCRIPT>
356 function cust_pkg_areyousure(href) {
357     if (confirm("Permanently delete included services and cancel this package?") == true)
358         window.location.href = href;
359 }
360 function svc_areyousure(href) {
361     if (confirm("Permanently unprovision and delete this service?") == true)
362         window.location.href = href;
363 }
364 </SCRIPT>
365
366 <%
367
368 print qq!<A NAME="cust_pkg">Packages</A> !,
369       qq!( <A HREF="!, popurl(2), qq!edit/cust_pkg.cgi?$custnum">Order and cancel packages</A> (preserves services) )!,
370 ;
371
372 #begin display packages
373
374 #get package info
375
376 my $packages = get_packages($cust_main, $conf);
377
378 if ( @$packages ) {
379 %>
380 <TABLE CLASS="package" BORDER=1 CELLSPACING=0 CELLPADDING=2 BORDERCOLOR="#999999">
381 <TR>
382   <TH>Package</TH>
383   <TH>Status</TH>
384   <TH COLSPAN=2>Services</TH>
385 </TR>
386 <%
387 foreach my $pkg (sort pkgsort_pkgnum_cancel @$packages) {
388   my $rowspan = 0;
389
390   if ($pkg->{cancel}) {
391     $rowspan = 0;
392   } else {
393     foreach my $svcpart (@{$pkg->{svcparts}}) {
394       $rowspan += $svcpart->{count};
395       $rowspan++ if ($svcpart->{count} < $svcpart->{quantity});
396     }
397   } 
398
399 %>
400 <!--pkgnum: <%=$pkg->{pkgnum}%>-->
401 <TR>
402   <TD ROWSPAN=<%=$rowspan%>>
403     <A NAME="cust_pkg<%=$pkg->{pkgnum}%>"><%=$pkg->{pkgnum}%></A>:
404     <%=$pkg->{pkg}%> - <%=$pkg->{comment}%><BR>
405 <% unless ($pkg->{cancel}) { %>
406     (&nbsp;<%=pkg_change_link($pkg)%>&nbsp;)
407     (&nbsp;<%=pkg_dates_link($pkg)%>&nbsp;|&nbsp;<%=pkg_customize_link($pkg,$custnum)%>&nbsp;)
408 <% } %>
409   </TD>
410 <%
411   #foreach (qw(setup last_bill next_bill susp expire cancel)) {
412   #  print qq!  <TD ROWSPAN=$rowspan>! . pkg_datestr($pkg,$_,$conf) . qq!</TD>\n!;
413   #}
414   print "<TD ROWSPAN=$rowspan>". &itable('');
415
416   sub freq {
417
418     #false laziness w/edit/part_pkg.cgi
419     my %freq = ( #move this
420       '1d' => 'daily',
421       '1w' => 'weekly',
422       '2w' => 'biweekly (every 2 weeks)',
423       '1'  => 'monthly',
424       '2'  => 'bimonthly (every 2 months)',
425       '3'  => 'quarterly (every 3 months)',
426       '6'  => 'semiannually (every 6 months)',
427       '12' => 'annually',
428       '24' => 'biannually (every 2 years)',
429     );
430
431     my $freq = shift;
432     exists $freq{$freq} ? $freq{$freq} : "every&nbsp;$freq&nbsp;months";
433   }
434
435   #eomove
436
437   if ( $pkg->{cancel} ) { #status: cancelled
438
439     print '<TR><TD><FONT COLOR="#ff0000"><B>Cancelled&nbsp;</B></FONT></TD>'.
440           '<TD>'. pkg_datestr($pkg,'cancel',$conf). '</TD></TR>';
441     unless ( $pkg->{setup} ) {
442       print '<TR><TD COLSPAN=2>Never billed</TD></TR>';
443     } else {
444       print "<TR><TD>Setup&nbsp;</TD><TD>".
445             pkg_datestr($pkg, 'setup',$conf). '</TD></TR>';
446       print "<TR><TD>Last&nbsp;bill&nbsp;</TD><TD>".
447             pkg_datestr($pkg, 'last_bill',$conf). '</TD></TR>'
448         if $pkg->{'last_bill'};
449       print "<TR><TD>Suspended&nbsp;</TD><TD>".
450             pkg_datestr($pkg, 'susp',$conf). '</TD></TR>'
451         if $pkg->{'susp'};
452     }
453
454   } else {
455
456     if ( $pkg->{susp} ) { #status: suspended
457       print '<TR><TD><FONT COLOR="#FF9900"><B>Suspended</B>&nbsp;</FONT></TD>'.
458             '<TD>'. pkg_datestr($pkg,'susp',$conf). '</TD></TR>';
459       unless ( $pkg->{setup} ) {
460         print '<TR><TD COLSPAN=2>Never billed</TD></TR>';
461       } else {
462         print "<TR><TD>Setup&nbsp;</TD><TD>". 
463               pkg_datestr($pkg, 'setup',$conf). '</TD></TR>';
464       }
465       print "<TR><TD>Last&nbsp;bill&nbsp;</TD><TD>".
466             pkg_datestr($pkg, 'last_bill',$conf). '</TD></TR>'
467         if $pkg->{'last_bill'};
468       # next bill ??
469       print "<TR><TD>Expires&nbsp;</TD><TD>".
470             pkg_datestr($pkg, 'expire',$conf). '</TD></TR>'
471         if $pkg->{'expire'};
472       print '<TR><TD COLSPAN=2>(&nbsp;'. pkg_unsuspend_link($pkg).
473             '&nbsp;|&nbsp;'. pkg_cancel_link($pkg). '&nbsp;)</TD></TR>';
474
475     } else { #status: active
476
477       unless ( $pkg->{setup} ) { #not setup
478
479         print '<TR><TD COLSPAN=2>Not&nbsp;yet&nbsp;billed&nbsp;(';
480         unless ( $pkg->{freq} ) {
481           print 'one-time&nbsp;charge)</TD></TR>';
482           print '<TR><TD COLSPAN=2>(&nbsp;'. pkg_cancel_link($pkg).
483                 '&nbsp;)</TD</TR>';
484         } else {
485           print 'billed&nbsp;'. freq($pkg->{freq}). ')</TD></TR>';
486         }
487
488       } else { #setup
489
490         unless ( $pkg->{freq} ) {
491           print "<TR><TD COLSPAN=2>One-time&nbsp;charge</TD></TR>".
492                 '<TR><TD>Billed&nbsp;</TD><TD>'.
493                 pkg_datestr($pkg,'setup',$conf). '</TD></TR>';
494         } else {
495           print '<TR><TD COLSPAN=2><FONT COLOR="#00CC00"><B>Active</B></FONT>'.
496                 ',&nbsp;billed&nbsp;'. freq($pkg->{freq}). '</TD></TR>'.
497                 '<TR><TD>Setup&nbsp;</TD><TD>'.
498                 pkg_datestr($pkg, 'setup',$conf). '</TD></TR>';
499         }
500
501       }
502
503       print "<TR><TD>Last&nbsp;bill&nbsp;</TD><TD>".
504             pkg_datestr($pkg, 'last_bill',$conf). '</TD></TR>'
505         if $pkg->{'last_bill'};
506       print "<TR><TD>Next&nbsp;bill&nbsp;</TD><TD>".
507             pkg_datestr($pkg, 'next_bill',$conf). '</TD></TR>'
508         if $pkg->{'next_bill'};
509       print "<TR><TD>Expires&nbsp;</TD><TD>".
510             pkg_datestr($pkg, 'expire',$conf). '</TD></TR>'
511         if $pkg->{'expire'};
512       if ( $pkg->{freq} ) {
513         print '<TR><TD COLSPAN=2>(&nbsp;'. pkg_suspend_link($pkg).
514               '&nbsp;|&nbsp;'. pkg_cancel_link($pkg). '&nbsp;)</TD></TR>';
515       }
516
517     }
518
519   }
520
521   print "</TABLE></TD>\n";
522
523   if ($rowspan == 0) { print qq!</TR>\n!; next; }
524
525   my $cnt = 0;
526   foreach my $svcpart (sort {$a->{svcpart} <=> $b->{svcpart}} @{$pkg->{svcparts}}) {
527     foreach my $service (@{$svcpart->{services}}) {
528       print '<TR>' if ($cnt > 0);
529 %>
530   <TD><%=svc_link($svcpart,$service)%></TD>
531   <TD><%=svc_label_link($svcpart,$service)%><BR>(&nbsp;<%=svc_unprovision_link($service)%>&nbsp;)</TD>
532 </TR>
533 <%
534       $cnt++;
535     }
536     if ($svcpart->{count} < $svcpart->{quantity}) {
537       print qq!<TR>\n! if ($cnt > 0);
538       print qq!  <TD COLSPAN=2>!.svc_provision_link($pkg, $svcpart, $conf).qq!</TD>\n</TR>\n!;
539     }
540   }
541 }
542 print '</TABLE>';
543 }
544
545 #end display packages
546 %>
547
548 <SCRIPT>
549 function cust_pay_areyousure(href) {
550     if (confirm("Are you sure you want to delete this payment?")
551  == true)
552         window.location.href = href;
553 }
554 function cust_pay_unapply_areyousure(href) {
555     if (confirm("Are you sure you want to unapply this payment?")
556  == true)
557         window.location.href = href;
558 }
559 function cust_credit_unapply_areyousure(href) {
560     if (confirm("Are you sure you want to unapply this credit?")
561  == true)
562         window.location.href = href;
563 }
564 function cust_credit_areyousure(href) {
565     if (confirm("Are you sure you want to delete this credit?")
566  == true)
567         window.location.href = href;
568 }
569 </SCRIPT>
570
571 <% if ( $conf->config('payby-default') ne 'HIDE' ) { %>
572   
573   <BR><BR><A NAME="history"><FONT SIZE="+2">Payment History</FONT></A><BR>
574   <A HREF="<%= $p %>edit/cust_pay.cgi?custnum=<%= $custnum %>">Post cash/check payment</A>
575   | <A HREF="<%= $p %>misc/payment.cgi?payby=CARD;custnum=<%= $custnum %>">Process credit card payment</A>
576   | <A HREF="<%= $p %>misc/payment.cgi?payby=CHEK;custnum=<%= $custnum %>">Process electronic check (ACH) payment</A>
577   <BR><A HREF="<%= $p %>edit/cust_credit.cgi?<%= $custnum %>">Post credit</A>
578   <BR>
579
580   <%
581   #get payment history
582   my @history = ();
583
584   #invoices
585   foreach my $cust_bill ($cust_main->cust_bill) {
586     my $pre = ( $cust_bill->owed > 0 )
587                 ? '<B><FONT SIZE="+1" COLOR="#FF0000">Open '
588                 : '';
589     my $post = ( $cust_bill->owed > 0 ) ? '</FONT></B>' : '';
590     my $invnum = $cust_bill->invnum;
591     push @history, {
592       'date'   => $cust_bill->_date,
593       'desc'   => qq!<A HREF="${p}view/cust_bill.cgi?$invnum">!. $pre.
594                   "Invoice #$invnum (Balance \$". $cust_bill->owed. ')'.
595                   $post. '</A>',
596       'charge' => $cust_bill->charged,
597     };
598   }
599
600   #payments (some false laziness w/credits)
601   foreach my $cust_pay ($cust_main->cust_pay) {
602
603     my $payby = $cust_pay->payby;
604     my $payinfo = $cust_pay->payinfo;
605     my @cust_bill_pay = $cust_pay->cust_bill_pay;
606
607     $payinfo = 'x'x(length($payinfo)-4). substr($payinfo,(length($payinfo)-4))
608       if $payby eq 'CARD';
609     my $target = "$payby$payinfo";
610     $payby =~ s/^BILL$/Check #/ if $payinfo;
611     $payby =~ s/^BILL$//;
612     $payby =~ s/^(CARD|COMP)$/$1 /;
613     my $info = $payby ? " ($payby$payinfo)" : '';
614
615     my( $pre, $post, $desc, $apply, $ext ) = ( '', '', '', '', '' );
616     if ( scalar(@cust_bill_pay) == 0 ) {
617       #completely unapplied
618       $pre = '<B><FONT COLOR="#FF0000">Unapplied ';
619       $post = '</FONT></B>';
620       $apply = qq! (<A HREF="${p}edit/cust_bill_pay.cgi?!.
621                $cust_pay->paynum. '">apply</A>)';
622     } elsif ( scalar(@cust_bill_pay) == 1 && $cust_pay->unapplied == 0 ) {
623       #applied to one invoice
624       $desc = ' applied to Invoice #'. $cust_bill_pay[0]->invnum;
625     } else {
626       #complicated
627       $desc = '<BR>';
628       foreach my $cust_bill_pay (@cust_bill_pay) {
629         $desc .= '&nbsp;&nbsp;'.
630                  '$'. $cust_bill_pay->amount.
631                  ' applied to Invoice #'. $cust_bill_pay->invnum.
632                  '<BR>';
633                  #' on '. time2str("%D", $cust_bill_pay->_date).
634
635       }
636       if ( $cust_pay->unapplied > 0 ) {
637         $desc .= '&nbsp;&nbsp;'.
638                  '<B><FONT COLOR="#FF0000">$'.
639                  $cust_pay->unapplied. ' unapplied</FONT></B>'.
640                  qq! (<A HREF="${p}edit/cust_bill_pay.cgi?!.
641                  $cust_pay->paynum. '">apply</A>)'.
642                  '<BR>';
643       }
644     }
645
646     my $delete = '';
647     if ( $cust_pay->closed !~ /^Y/i && $conf->exists('deletepayments') ) {
648       $delete = qq! (<A HREF="javascript:cust_pay_areyousure('!.
649                 qq!${p}misc/delete-cust_pay.cgi?!. $cust_pay->paynum.
650                 qq!')">delete</A>)!;
651     }
652
653     my $unapply = '';
654     if (    $cust_pay->closed !~ /^Y/i
655          && $conf->exists('unapplypayments')
656          && scalar(@cust_bill_pay)           ) {
657       $unapply = qq! (<A HREF="javascript:cust_pay_unapply_areyousure('!.
658                  qq!${p}misc/unapply-cust_pay.cgi?!. $cust_pay->paynum.
659                  qq!')">unapply</A>)!;
660     }
661
662     push @history, {
663       'date'    => $cust_pay->_date,
664       'desc'    => $pre. "Payment$post$info$desc".
665                    "$apply$delete$unapply",
666       'payment' => $cust_pay->paid,
667       'target'  => $target,
668     };
669   }
670
671   #credits (some false laziness w/payments)
672   foreach my $cust_credit ($cust_main->cust_credit) {
673
674     my @cust_credit_bill = $cust_credit->cust_credit_bill;
675     my @cust_credit_refund = $cust_credit->cust_credit_refund;
676
677     my( $pre, $post, $desc, $apply, $ext ) = ( '', '', '', '', '' );
678     if (    scalar(@cust_credit_bill)   == 0
679          && scalar(@cust_credit_refund) == 0 ) {
680       #completely unapplied
681       $pre = '<B><FONT COLOR="#FF0000">Unapplied ';
682       $post = '</FONT></B>';
683       $apply = qq! (<A HREF="${p}edit/cust_credit_bill.cgi?!.
684                $cust_credit->crednum. '">apply</A>)';
685     } elsif (    scalar(@cust_credit_bill)   == 1
686               && scalar(@cust_credit_refund) == 0
687               && $cust_credit->credited == 0      ) {
688       #applied to one invoice
689       $desc = ' applied to Invoice #'. $cust_credit_bill[0]->invnum;
690     } elsif (    scalar(@cust_credit_bill)   == 0
691               && scalar(@cust_credit_refund) == 1
692               && $cust_credit->credited == 0      ) {
693       #applied to one refund
694       $desc = ' refunded on '.  time2str("%D", $cust_credit_refund[0]->_date);
695     } else {
696       #complicated
697       $desc = '<BR>';
698       foreach my $app ( sort { $a->_date <=> $b->_date }
699                              ( @cust_credit_bill, @cust_credit_refund ) ) {
700         if ( $app->isa('FS::cust_credit_bill') ) {
701           $desc .= '&nbsp;&nbsp;'.
702                    '$'. $app->amount.
703                    ' applied to Invoice #'. $app->invnum.
704                    '<BR>';
705                    #' on '. time2str("%D", $app->_date).
706         } elsif ( $app->isa('FS::cust_credit_refund') ) {
707           $desc .= '&nbsp;&nbsp;'.
708                    '$'. $app->amount.
709                    ' refunded on'. time2str("%D", $app->_date).
710                    '<BR>';
711         } else {
712           die "$app is not a FS::cust_credit_bill or a FS::cust_credit_refund";
713         }
714       }
715       if ( $cust_credit->credited > 0 ) {
716         $desc .= '&nbsp;&nbsp;<B><FONT COLOR="#FF0000">$'.
717                  $cust_credit->credited. ' unapplied</FONT></B>'.
718                  qq! (<A HREF="${p}edit/cust_credit_bill.cgi?!.
719                  $cust_credit->crednum. '">apply</A>)'.
720                  '<BR>';
721       }
722     }
723 #
724     my $delete = '';
725     if ( $cust_credit->closed !~ /^Y/i && $conf->exists('deletecredits') ) {
726       $delete = qq! (<A HREF="javascript:cust_credit_areyousure('!.
727                 qq!${p}misc/delete-cust_credit.cgi?!. $cust_credit->crednum.
728                 qq!')">delete</A>)!;
729     }
730     
731     my $unapply = '';
732     if (    $cust_credit->closed !~ /^Y/i
733          && $conf->exists('unapplycredits')
734          && scalar(@cust_credit_bill)       ) {
735       $unapply = qq! (<A HREF="javascript:cust_credit_unapply_areyousure('!.
736                  qq!${p}misc/unapply-cust_credit.cgi?!. $cust_credit->crednum.
737                  qq!')">unapply</A>)!;
738     }
739     
740     push @history, {
741       'date'   => $cust_credit->_date,
742       'desc'   => $pre. "Credit$post by ". $cust_credit->otaker.
743                   ' ('. $cust_credit->reason. ')'.
744                   "$desc$apply$delete$unapply",
745       'credit' => $cust_credit->amount,
746     };
747
748   }
749
750   #refunds
751   foreach my $cust_refund ($cust_main->cust_refund) {
752
753     my $payby = $cust_refund->payby;
754     my $payinfo = $cust_refund->payinfo;
755
756     $payinfo = 'x'x(length($payinfo)-4). substr($payinfo,(length($payinfo)-4))
757       if $payby eq 'CARD';
758     $payby =~ s/^BILL$/Check #/ if $payinfo;
759     $payby =~ s/^(CARD|COMP)$/$1 /;
760
761     push @history, {
762       'date'   => $cust_refund->_date,
763       'desc'   => "Refund ($payby$payinfo) by ". $cust_refund->otaker,
764       'refund' => $cust_refund->refund,
765     };
766   
767   }
768   
769   %>
770   
771   <%= table() %>
772   <TR>
773     <TH>Date</TH>
774     <TH>Description</TH>
775     <TH><FONT SIZE=-1>Charge</FONT></TH>
776     <TH><FONT SIZE=-1>Payment</FONT></TH>
777     <TH><FONT SIZE=-1>In-house<BR>Credit</FONT></TH>
778     <TH><FONT SIZE=-1>Refund</FONT></TH>
779     <TH><FONT SIZE=-1>Balance</FONT></TH>
780   </TR>
781
782   <%
783   #display payment history
784
785   my %target;
786   my $balance = 0;
787   foreach my $item ( sort { $a->{'date'} <=> $b->{'date'} } @history ) {
788
789     my $charge  = exists($item->{'charge'})
790                     ? sprintf('$%.2f', $item->{'charge'})
791                     : '';
792     my $payment = exists($item->{'payment'})
793                     ? sprintf('-&nbsp;$%.2f', $item->{'payment'})
794                     : '';
795     my $credit  = exists($item->{'credit'})
796                     ? sprintf('-&nbsp;$%.2f', $item->{'credit'})
797                     : '';
798     my $refund  = exists($item->{'refund'})
799                     ? sprintf('$%.2f', $item->{'refund'})
800                     : '';
801
802     my $target = exists($item->{'target'}) ? $item->{'target'} : '';
803
804     $balance += $item->{'charge'}  if exists $item->{'charge'};
805     $balance -= $item->{'payment'} if exists $item->{'payment'};
806     $balance -= $item->{'credit'}  if exists $item->{'credit'};
807     $balance += $item->{'refund'}  if exists $item->{'refund'};
808     $balance = sprintf("%.2f", $balance);
809     $balance =~ s/^\-0\.00$/0.00/; #yay ieee fp
810     ( my $showbalance = '$'. $balance ) =~ s/^\$\-/-&nbsp;\$/;
811
812   %>
813   
814     <TR>
815       <TD>
816         <% unless ( !$target || $target{$target}++ ) { %>
817           <A NAME="<%= $target %>">
818         <% } %>
819         <%= time2str("%D",$item->{'date'}) %>
820         <% if ( $target && $target{$target} == 1 ) { %>
821           </A>
822         <% } %>
823         </FONT>
824       </TD>
825       <TD><%= $item->{'desc'} %></TD>
826       <TD ALIGN="right"><%= $charge  %></TD>
827       <TD ALIGN="right"><%= $payment %></TD>
828       <TD ALIGN="right"><%= $credit  %></TD>
829       <TD ALIGN="right"><%= $refund  %></TD>
830       <TD ALIGN="right"><%= $showbalance %></TD>
831     </TR>
832
833   <% } %>
834   
835   </TABLE>
836
837 <% } %>
838
839 </BODY></HTML>
840
841 <%
842 #subroutines
843
844 sub get_packages {
845   my $cust_main = shift or return undef;
846   my $conf = shift;
847   
848   my @packages = ();
849   
850   foreach my $cust_pkg (
851     $conf->exists('hidecancelledpackages')
852       ? $cust_main->ncancelled_pkgs
853       : $cust_main->all_pkgs
854   ) { 
855   
856     my $part_pkg = $cust_pkg->part_pkg;
857   
858     my %pkg = ();
859     $pkg{pkgnum} = $cust_pkg->pkgnum;
860     $pkg{pkg} = $part_pkg->pkg;
861     $pkg{pkgpart} = $part_pkg->pkgpart;
862     $pkg{comment} = $part_pkg->getfield('comment');
863     $pkg{freq} = $part_pkg->freq;
864     $pkg{setup} = $cust_pkg->getfield('setup');
865     $pkg{last_bill} = $cust_pkg->getfield('last_bill');
866     $pkg{next_bill} = $cust_pkg->getfield('bill');
867     $pkg{susp} = $cust_pkg->getfield('susp');
868     $pkg{expire} = $cust_pkg->getfield('expire');
869     $pkg{cancel} = $cust_pkg->getfield('cancel');
870   
871     my %svcparts = ();
872
873     foreach my $pkg_svc (
874       qsearch('pkg_svc', { 'pkgpart' => $part_pkg->pkgpart })
875     ) {
876   
877       next if ($pkg_svc->quantity == 0);
878   
879       my $part_svc = qsearchs('part_svc', { 'svcpart' => $pkg_svc->svcpart });
880   
881       my $svcpart = {};
882       $svcpart->{svcpart} = $part_svc->svcpart;
883       $svcpart->{svc} = $part_svc->svc;
884       $svcpart->{svcdb} = $part_svc->svcdb;
885       $svcpart->{quantity} = $pkg_svc->quantity;
886       $svcpart->{count} = 0;
887   
888       $svcpart->{services} = [];
889
890       $svcparts{$svcpart->{svcpart}} = $svcpart;
891
892     }
893
894     foreach my $cust_svc ( $cust_pkg->cust_svc ) {
895       #warn "svcnum ". $cust_svc->svcnum. " / svcpart ". $cust_svc->svcpart. "\n";
896       my $svc = {
897         'svcnum' => $cust_svc->svcnum,
898         'label'  => ($cust_svc->label)[1],
899       };
900
901       #false laziness with above, to catch extraneous services.  whole
902       #damn thing should be OO...
903       my $svcpart = ( $svcparts{$cust_svc->svcpart} ||= {
904         'svcpart'  => $cust_svc->svcpart,
905         'svc'      => $cust_svc->part_svc->svc,
906         'svcdb'    => $cust_svc->part_svc->svcdb,
907         'quantity' => 0,
908         'count'    => 0,
909         'services' => [],
910       } );
911
912       push @{$svcpart->{services}}, $svc;
913
914       $svcpart->{count}++;
915
916     }
917
918     $pkg{svcparts} = [ values %svcparts ];
919
920     push @packages, \%pkg;
921   
922   }
923   
924   return \@packages;
925
926 }
927
928 sub svc_link {
929
930   my ($svcpart, $svc) = (shift,shift) or return '';
931   return qq!<A HREF="${p}view/$svcpart->{svcdb}.cgi?$svc->{svcnum}">$svcpart->{svc}</A>!;
932
933 }
934
935 sub svc_label_link {
936
937   my ($svcpart, $svc) = (shift,shift) or return '';
938   return qq!<A HREF="${p}view/$svcpart->{svcdb}.cgi?$svc->{svcnum}">$svc->{label}</A>!;
939
940 }
941
942 sub svc_provision_link {
943   my ($pkg, $svcpart, $conf) = @_;
944   ( my $svc_nbsp = $svcpart->{svc} ) =~ s/\s+/&nbsp;/g;
945   my $pkgnum_svcpart = "pkgnum$pkg->{pkgnum}-svcpart$svcpart->{svcpart}";
946   my $num_left = $svcpart->{quantity} - $svcpart->{count};
947
948   my $link = qq!<A CLASS="provision" HREF="${p}edit/$svcpart->{svcdb}.cgi?!.
949              qq!$pkgnum_svcpart">!.
950              "Provision&nbsp;$svc_nbsp&nbsp;($num_left)</A>";
951   if ( $conf->exists('legacy_link') ) {
952     $link .= '<BR>'.
953              qq!<A CLASS="provision" HREF="${p}misc/link.cgi?!.
954              qq!$pkgnum_svcpart">!.
955             "Link&nbsp;to&nbsp;legacy&nbsp;$svc_nbsp&nbsp;($num_left)</A>";
956   }
957   $link;
958 }
959
960 sub svc_unprovision_link {
961   my $svc = shift or return '';
962   return qq!<A HREF="javascript:svc_areyousure('${p}misc/unprovision.cgi?$svc->{svcnum}')">Unprovision</A>!;
963 }
964
965 # This should be generalized to use config options to determine order.
966 sub pkgsort_pkgnum_cancel {
967   if ($a->{cancel} and $b->{cancel}) {
968     return ($a->{pkgnum} <=> $b->{pkgnum});
969   } elsif ($a->{cancel} or $b->{cancel}) {
970     return (-1) if ($b->{cancel});
971     return (1) if ($a->{cancel});
972     return (0);
973   } else {
974     return($a->{pkgnum} <=> $b->{pkgnum});
975   }
976 }
977
978 sub pkg_datestr {
979   my($pkg, $field, $conf) = @_ or return '';
980   return '&nbsp;' unless $pkg->{$field};
981   my $format = $conf->exists('pkg_showtimes')
982                ? '<B>%D</B>&nbsp;<FONT SIZE=-3>%l:%M:%S%P&nbsp;%z</FONT>'
983                : '<B>%b&nbsp;%o,&nbsp;%Y</B>';
984   ( my $strip = time2str($format, $pkg->{$field}) ) =~ s/ (\d)/$1/g;
985   $strip;
986 }
987
988 sub pkg_change_link {
989   my $pkg = shift or return '';
990   return qq!<a href="${p}misc/change_pkg.cgi?$pkg->{pkgnum}">Change&nbsp;package</a>!;
991 }
992
993 sub pkg_suspend_link {
994   my $pkg = shift or return '';
995   return qq!<a href="${p}misc/susp_pkg.cgi?$pkg->{pkgnum}">Suspend</a>!;
996 }
997
998 sub pkg_unsuspend_link {
999   my $pkg = shift or return '';
1000   return qq!<a href="${p}misc/unsusp_pkg.cgi?$pkg->{pkgnum}">Unsuspend</a>!;
1001 }
1002
1003 sub pkg_cancel_link {
1004   my $pkg = shift or return '';
1005   qq!<A HREF="javascript:cust_pkg_areyousure('${p}misc/cancel_pkg.cgi?$pkg->{pkgnum}')">Cancel now</A> | !.
1006   qq!<A HREF="${p}misc/expire_pkg.cgi?$pkg->{pkgnum}">Cancel later</A>!;
1007 }
1008
1009 sub pkg_dates_link {
1010   my $pkg = shift or return '';
1011   return qq!<A HREF="${p}edit/REAL_cust_pkg.cgi?$pkg->{pkgnum}">Edit&nbsp;dates</A>!;
1012 }
1013
1014 sub pkg_customize_link {
1015   my $pkg = shift or return '';
1016   my $custnum = shift;
1017   return qq!<A HREF="${p}edit/part_pkg.cgi?keywords=$custnum;clone=$pkg->{pkgpart};pkgnum=$pkg->{pkgnum}">Customize</A>!;
1018 }
1019
1020 %>
1021