#!/usr/bin/perl -Tw
#
# $Id: cust_main.cgi,v 1.12 1999-02-07 09:59:40 ivan Exp $
#
# Usage: cust_main.cgi custnum
#        http://server.name/path/cust_main.cgi?custnum
#
# Note: Should be run setuid freeside as user nobody.
#
# the payment history section could use some work, see below
# 
# ivan@voicenet.com 96-nov-29 -> 96-dec-11
#
# added navigation bar (go to main menu ;)
# ivan@voicenet.com 97-jan-30
#
# changes to the way credits/payments are applied (the links are here).
# ivan@voicenet.com 97-apr-21
#
# added debugging code to diagnose CPU sucking problem.
# ivan@voicenet.com 97-may-19
#
# CPU sucking problem was in comment code?  fixed?
# ivan@voicenet.com 97-may-22
#
# rewrote for new API
# ivan@voicenet.com 97-jul-22
#
# Changes to allow page to work at a relative position in server
# Changed 'day' to 'daytime' because Pg6.3 reserves the day word
#       bmccane@maxbaud.net     98-apr-3
#
# lose background, FS::CGI ivan@sisd.com 98-sep-2
#
# $Log: cust_main.cgi,v $
# Revision 1.12  1999-02-07 09:59:40  ivan
# more mod_perl fixes, and bugfixes Peter Wemm sent via email
#
# Revision 1.11  1999/01/25 12:26:04  ivan
# yet more mod_perl stuff
#
# Revision 1.10  1999/01/19 05:14:19  ivan
# for mod_perl: no more top-level my() variables; use vars instead
# also the last s/create/new/;
#
# Revision 1.9  1999/01/18 09:41:43  ivan
# all $cgi->header calls now include ( '-expires' => 'now' ) for mod_perl
# (good idea anyway)
#
# Revision 1.8  1999/01/18 09:22:35  ivan
# changes to track email addresses for email invoicing
#
# Revision 1.7  1998/12/30 23:03:34  ivan
# bugfixes; fields isn't exported by derived classes
#
# Revision 1.6  1998/12/23 02:42:33  ivan
# remove double '/' in link urls
#
# Revision 1.5  1998/12/23 02:36:28  ivan
# use FS::cust_refund; to eliminate warning
#
# Revision 1.4  1998/12/17 09:57:21  ivan
# s/CGI::(Base|Request)/CGI.pm/;
#
# Revision 1.3  1998/11/15 13:14:20  ivan
# first pass as per-customer custom pricing
#
# Revision 1.2  1998/11/13 11:28:08  ivan
# s/CGI-modules/CGI.pm/;, relative URL's with popurl
#
use strict;
use vars qw ( $cgi $query $custnum $cust_main $hashref $agent $referral 
              @packages $package @history @bills $bill @credits $credit
              $balance $item @agents @referrals @invoicing_list $n1 ); 
use CGI;
use CGI::Carp qw(fatalsToBrowser);
use Date::Format;
use FS::UID qw(cgisuidsetup);
use FS::Record qw(qsearchs qsearch);
use FS::CGI qw(header menubar popurl table itable ntable);
use FS::cust_credit;
use FS::cust_pay;
use FS::cust_bill;
use FS::part_pkg;
use FS::cust_pkg;
use FS::part_referral;
use FS::agent;
use FS::cust_main;
use FS::cust_refund;
$cgi = new CGI;
&cgisuidsetup($cgi);
print $cgi->header( '-expires' => 'now' ), header("Customer View", menubar(
  'Main Menu' => popurl(2)
));
die "No customer specified (bad URL)!" unless $cgi->keywords;
($query) = $cgi->keywords; # needs parens with my, ->keywords returns array
$query =~ /^(\d+)$/;
$custnum = $1;
$cust_main = qsearchs('cust_main',{'custnum'=>$custnum});
die "Customer not found!" unless $cust_main;
$hashref = $cust_main->hashref;
print itable(), '
| ';
print qq!Edit this customer!,
      ntable("#c0c0c0"), " | 
| ", ntable("#c0c0c0",2),
      ' | 
| Customer number | ',
      $custnum, ' | 
',
;
@agents = qsearch( 'agent', {} );
unless ( scalar(@agents) == 1 ) {
  $agent = qsearchs('agent',{
    'agentnum' => $cust_main->agentnum
  } );
  print '| Agent | ',
        $agent->agentnum, ": ", $agent->agent, ' | 
';
}
@referrals = qsearch( 'part_referral', {} );
unless ( scalar(@referrals) == 1 ) {
  my $referral = qsearchs('part_referral', {
    'refnum' => $cust_main->refnum
  } );
  print '| Referral | ',
        $referral->refnum, ": ", $referral->referral, ' | 
';
}
print '| Order taker | ',
  $cust_main->otaker, ' | 
';
print '';
print '';
print "Contact information", ntable("#c0c0c0"), " | | ",
      ntable("#c0c0c0",2),
  ' | 
| Contact name ',
    '(last, first)
 | ',
    $cust_main->last, ', ', $cust_main->first,
    ' | SS# | ',
    $cust_main->ss || ' ', ' | 
',
  '| Company | ',
    $cust_main->company,
    ' | 
',
  '| Address | ',
    $cust_main->address1,
    ' | 
',
;
print '|  | ',
      $cust_main->address2, ' | 
'
  if $cust_main->address2;
print '| City | ',
        $cust_main->city,
        ' | State | ',
        $cust_main->state,
        ' | Zip | ',
        $cust_main->zip, ' | 
',
      '| Country | ',
        $cust_main->country,
        ' | 
',
;
print '| Day Phone | ',
        $cust_main->daytime || ' ', ' | 
',
      '| Night Phone | ',
        $cust_main->night || ' ', ' | 
',
      '| Fax | ',
        $cust_main->fax || ' ', ' | 
',
      '', ""
;
print '| ';
@invoicing_list = $cust_main->invoicing_list;
print "Billing information (",
      qq!!, "Bill now)",
      ntable("#c0c0c0"), " | 
| ", ntable("#c0c0c0",2),
      ' | 
| Tax exempt | ',
      $cust_main->tax ? 'yes' : 'no',
      ' | 
',
      '| Postal invoices | ',
      ( grep { $_ eq 'POST' } @invoicing_list ) ? 'yes' : 'no',
      ' | 
',
      '| Email invoices | ',
      join(', ', grep { $_ ne 'POST' } @invoicing_list ) || 'no',
      ' | 
',
      '| Billing type | ',
;
if ( $cust_main->payby eq 'CARD' ) {
  print 'Credit card | 
',
        '| Card number | ',
        $cust_main->payinfo, ' | 
',
        '| Expiration | ',
        $cust_main->paydate, ' | 
',
        '| Name on card | ',
        $cust_main->payname, ' | 
'
  ;
} elsif ( $cust_main->payby eq 'BILL' ) {
  print 'Billing';
  print '| P.O. | ',
        $cust_main->payinfo, ' | 
',
    if $cust_main->payinfo;
  print '| Expiration | ',
        $cust_main->paydate, ' | 
',
        '| Attention | ',
        $cust_main->payname, ' | 
',
  ;
} elsif ( $cust_main->payby eq 'COMP' ) {
  print 'Complimentary',
        '| Authorized by | ',
        $cust_main->payinfo, ' | 
',
        '| Expiration | ',
        $cust_main->paydate, ' | 
',
  ;
}
print "";
print qq!
Packages !,
#      qq!
Click on package number to view/edit package.!,
      qq!( Order and cancel packages )!,
;
#display packages
#formatting
print qq!!, table, "\n",
      qq!| Package | !,
      qq!Dates | Services | 
|---|
\n!,
      qq!| Setup | !,
      qq!Next bill!,
      qq! | Susp. | Expire!,
      qq!!,
      qq! | Cancel!,
      qq! | 
|---|
\n!;
#get package info
@packages = $cust_main->all_pkgs;
#@packages = $cust_main->ncancelled_pkgs;
$n1 = '';
foreach $package (@packages) {
  my $pkgnum = $package->pkgnum;
  my $pkg = $package->part_pkg->pkg;
  my $comment = $package->part_pkg->comment;
  my $pkgview = popurl(2). "view/cust_pkg.cgi?$pkgnum";
  my @cust_svc = qsearch( 'cust_svc', { 'pkgnum' => $pkgnum } );
  my $rowspan = scalar(@cust_svc) || 1;
  my $button_cgi = new CGI;
  $button_cgi->param('clone', $package->part_pkg->pkgpart);
  $button_cgi->param('pkgnum', $package->pkgnum);
  my $button_url = popurl(2). "edit/part_pkg.cgi?". $button_cgi->query_string;
  #print $n1, qq!| $pkgnum!,
  print $n1, qq! | $pkgnum!,
        qq! | !,
        #qq!$pkg - $comment!,
        qq!$pkg - $comment!,
        qq! ( Edit | Customize pricing )!,
  ;
  for ( qw( setup bill susp expire cancel ) ) {
    print " | ", ( $package->getfield($_)
            ? time2str("%D", $package->getfield($_) )
            :  ' '
          ), '',
    ;
  }
  my $n2 = '';
  foreach my $cust_svc ( @cust_svc ) {
     my($label, $value, $svcdb) = $cust_svc->label;
     my($svcnum) = $cust_svc->svcnum;
     my($sview) = popurl(2). "/view";
     print $n2,qq! | $label!,
           qq! | $value!;
     $n2=" | 
";
  }
  $n1="
";
}  
print "
";
#formatting
print "";
#formatting
print qq!
Payment History!,
      qq!!,
      qq! ( Click on invoice to view invoice/enter payment. | !,
      qq!!,
      qq!Post credit / refund )!;
#get payment history
#
# major problem: this whole thing is way too sloppy.
# minor problem: the description lines need better formatting.
@history = (); #needed for mod_perl :)
@bills = qsearch('cust_bill',{'custnum'=>$custnum});
foreach $bill (@bills) {
  my($bref)=$bill->hashref;
  push @history,
    $bref->{_date} . qq!\tInvoice #! . $bref->{invnum} .
    qq! (Balance \$! . $bref->{owed} . qq!)\t! .
    $bref->{charged} . qq!\t\t\t!;
  my(@payments)=qsearch('cust_pay',{'invnum'=> $bref->{invnum} } );
  my($payment);
  foreach $payment (@payments) {
    my($date,$invnum,$payby,$payinfo,$paid)=($payment->getfield('_date'),
                                             $payment->getfield('invnum'),
                                             $payment->getfield('payby'),
                                             $payment->getfield('payinfo'),
                                             $payment->getfield('paid'),
                      );
    push @history,
      "$date\tPayment, Invoice #$invnum ($payby $payinfo)\t\t$paid\t\t";
  }
}
@credits = qsearch('cust_credit',{'custnum'=>$custnum});
foreach $credit (@credits) {
  my($cref)=$credit->hashref;
  push @history,
    $cref->{_date} . "\tCredit #" . $cref->{crednum} . ", (Balance \$" .
    $cref->{credited} . ") by " . $cref->{otaker} . " - " .
    $cref->{reason} . "\t\t\t" . $cref->{amount} . "\t";
  my(@refunds)=qsearch('cust_refund',{'crednum'=> $cref->{crednum} } );
  my($refund);
  foreach $refund (@refunds) {
    my($rref)=$refund->hashref;
    push @history,
      $rref->{_date} . "\tRefund, Credit #" . $rref->{crednum} . " (" .
      $rref->{payby} . " " . $rref->{payinfo} . ") by " .
      $rref->{otaker} . " - ". $rref->{reason} . "\t\t\t\t" .
      $rref->{refund};
  }
}
        #formatting
        print table(), <
  Date | Description | Charge | Payment | In-house Credit
 | Refund | BalanceEND
#display payment history
$balance = 0;
foreach $item (sort keyfield_numerically @history) {
  my($date,$desc,$charge,$payment,$credit,$refund)=split(/\t/,$item);
  $charge ||= 0;
  $payment ||= 0;
  $credit ||= 0;
  $refund ||= 0;
  $balance += $charge - $payment;
  $balance -= $credit - $refund;
  print " | | ",time2str("%D",$date),"",
	" | $desc",
	" | ",
        ( $charge ? "\$".sprintf("%.2f",$charge) : '' ),
        "",
	" | ",
        ( $payment ? "- \$".sprintf("%.2f",$payment) : '' ),
        "",
	" | ",
        ( $credit ? "- \$".sprintf("%.2f",$credit) : '' ),
        "",
	" | ",
        ( $refund ? "\$".sprintf("%.2f",$refund) : '' ),
        "",
	" | \$" . sprintf("%.2f",$balance),
        "",
        "\n";
}
#formatting
print "";
#end
#formatting
print < |