#!/usr/local/qddb/bin/qtclsh

lappend auto_path $qddb_library/hx

source /var/lib/ISPutil/bin/init.tcl

set dir /var/lib/www/staffcgi/qddb/payments
set mypath /staff/cgi-bin/qddb/payments/submit
set webmaster webmaster@knotwork.com
set hostname www.knotwork.com
set dbname $dir/Payments
set title "Payments Submission Form"
set opening "Welcome to the Payments submission form"
set message \
"This form is for posting Payments accepted by you on behalf of the
system. It adjusts the Balance both of the user who made the Payment
and of the representative who received the Payment (and is thus
accountable for the Amount of the Payment).<P>
Please fill in all fields (especially the Amount field!)
and submit when ready.
"
set signature "The Knotwork Team"
set body "<body bgcolor=#F0F0F0 text=#222222 link=#1B3E62 vlink=#962835 \
alink=#EE0000>"




#------- end variable definitions --------


if {[info exists env(REMOTE_USER)]} {
  set REMOTE_USER $env(REMOTE_USER)
} else {
	puts "Content-type: text/html

<html>
<head><title>Submission error (Payments)</title></head>
$body
<h2>Unknown remote user</h2>
You have to be logged-in to the server for this to work,
otherwise I have no idea who it is that wants to post a Payment!
</h2><br>
</body>
</html>
"	
exit 0
}



proc NoUser {} {
	global body
	puts "Content-type: text/html

<html>
<head><title>Submission error (Payments)</title></head>
$body
<h2>You must enter the username in the payment report field before submission!
</h2><br>
</body>
</html>
"	
exit 0
}


proc NoAmount {} {
	global body
	puts "Content-type: text/html

<html>
<head><title>Submission error (Payments)</title></head>
$body
<h2>You must enter a postive Amount before submission!
</h2><br>
</body>
</html>
"	
exit 0
}


proc NoMethod {} {
	global body
	puts "Content-type: text/html

<html>
<head><title>Submission error (Payments)</title></head>
$body
<h2>You must enter a Method Of Payment before submission!
</h2><br>
</body>
</html>
"	
exit 0
}


proc BadName {} {
	global body
	puts "Content-type: text/html

<html>
<head><title>Submission error (Payments)</title></head>
$body
<h2>You must enter a valid username in the username field before submission!
</h2><br>
</body>
</html>
"
exit 0
}


proc BadUSER {} {
	global body
	puts "Content-type: text/html

<html>
<head><title>Submission error (Payments)</title></head>
$body
<h2>Invalid Sales Representative!</h2>
Only recognised Sales Representatives may accept Payments on behalf
of the system.
</h2><br>
</body>
</html>
"
exit 0
}


proc NoOneself {} {
	global body
	puts "Content-type: text/html

<html>
<head><title>Submission error (Payments)</title></head>
$body
<h2>You cannot enter your own Payments!</h2>

This form is for posting Payments accepted by you on behalf of the
system. It adjusts the Balance both of the user who made the Payment
and of the representative who received the Payment (and is thus
accountable for the Amount of the Payment).
<P>
You are already responsible for your own Balance, so there is no
need to post a Payment to tell the system that you are the representative
responsible for the Balance of your own account.
</h2><br>
</body>
</html>
"
exit 0
}


proc EntryProc {schema} {
  Hx:DefinedEntryForm $schema {
    {Name.Username 14 text 40} 
    {Amount 14 text 20} {MethodOfPayment 0 label 0} {MethodOfPayment 2 radio 0 0 Cash} {MethodOfPayment 2 radio 0 0 Cheque} {MethodOfPayment 2 radio 0 0 Credit}
    {Comments 14 textarea 60 5}
  }
}


proc Post_Payment {Username Amount} {
  global carr gv_pmtamt username firstname lastname id
  #
  # Update customer. Key on Username for now (later, make this better)
  # If Username not found, user will have first to create the customer
  # using the client screen.
  #
  if {[catch "qddb_schema open Clients" c_s] != 0} {
    puts "Cannot open Clients Schema"; exit 1
  }
  set c_k [qddb_search $c_s \
	-prunebyattr Company.Contact.Username word $Username]
  set c_k1 [qddb_keylist get $c_k]
  set c_t [isUniqueTuple $c_k1 $c_s]
  if { $c_t == "" } {
    puts "Customer not found, or duplicate customer."
    qddb_keylist delete all
    qddb_tuple delete all
    qddb_schema close $c_s
    return
  }
  while {[qddb_tuple lock $c_t] == 0} {
    puts "Waiting for Customer screen to be closed...."
    exec sleep 2
  }	    
  set c_v [qddb_view define $c_t {
    { Company.Contact.Username   carr(Company.Contact.Username) }
    { Company.Contact.First   carr(Company.Contact.First) }
    { Company.Contact.Last   carr(Company.Contact.Last) }
    { Company.Contact.ID   carr(Company.Contact.ID) }
    { CurrentBalance             carr(CurrentBalance) }
    { Recent                     carr(Recent) }
    { Balance30                  carr(Balance30) }
    { Balance60                  carr(Balance60) }
    { Balance90                  carr(Balance90) }
    { Transaction.Date           carr(Transaction.Date) }
    { Transaction.Clock          carr(Transaction.Clock) }
    { Transaction.TType          carr(Transaction.TType) }
    { Transaction.InvoiceNumber  carr(Transaction.InvoiceNumber) }
    { Transaction.Amount         carr(Transaction.Amount) }
    { Transaction.RunningBalance carr(Transaction.RunningBalance) }
  }]
  qddb_instance switch $c_v Transaction \
	[qddb_instance new $c_v Transaction]
  set carr(Transaction.Date) [qddb_util formatdate "%m/%d/%y" today]
  set carr(Transaction.Clock) [qddb_util formatdate "%X" now]
  set carr(Transaction.TType) "Payment"
  set carr(Transaction.InvoiceNumber) ""
  set carr(Transaction.Amount) $Amount
  set carr(Transaction.RunningBalance) \
	[expr $carr(CurrentBalance) - $Amount]
  set carr(CurrentBalance) $carr(Transaction.RunningBalance)
  set username $carr(Company.Contact.Username)
  set firstname $carr(Company.Contact.First)
  set lastname $carr(Company.Contact.Last)
  set id $carr(Company.Contact.ID)
  set gv_pmtamt $Amount
  if { $gv_pmtamt > 0 } {
    #
    # Since, there was a payment, first subtract from 90,60,30
    # in that order
    #
    set remainder $gv_pmtamt
    if { $carr(Balance90) > 0 } {
	if {$carr(Balance90) >= $gv_pmtamt} {
	    set carr(Balance90) [expr $carr(Balance90) - $gv_pmtamt]
	    set remainder 0
	} else {
	    set remainder [expr $gv_pmtamt - $carr(Balance90)]
	    set carr(Balance90) 0
	}
    }
    if { $remainder != 0 && $carr(Balance60) > 0 } {
	if {$carr(Balance60) >= $remainder} {
	    set carr(Balance60) [expr $carr(Balance60) - $remainder]
	    set remainder 0
	} else {
	    set remainder [expr $remainder - $carr(Balance60)]
	    set carr(Balance60) 0
	}
    }
    if { $remainder != 0 && $carr(Balance30) > 0 } {
	if {$carr(Balance30) >= $remainder} {
	    set carr(Balance30) [expr $carr(Balance30) - $remainder]
	    set remainder 0
	} else {
	    set remainder [expr $remainder - $carr(Balance30)]
	    set carr(Balance30) 0
	}
    }
    if { $remainder != 0 } {
	if {$carr(Recent) >= $remainder} {
	    set carr(Recent) [expr $carr(Recent) - $remainder]
	    set remainder 0
	} else {
	    set carr(Recent) "-[expr $remainder - $carr(Recent)]"
	}
    }
  }
  qddb_tuple write $c_t
  qddb_tuple delete $c_t
  qddb_schema close $c_s
}


proc Post_Fee {Username Amount} {
  global carr gv_pmtamt
  #
  # Update customer. Key on Username for now (later, make this better)
  # If Username not found, user will have first to create the customer
  # using the client screen.
  #
  if {[catch "qddb_schema open Clients" c_s] != 0} {
    puts "Cannot open Clients Schema"; exit 1
  }
  set c_k [qddb_search $c_s \
	-prunebyattr Company.Contact.Username word $Username]
  set c_k1 [qddb_keylist get $c_k]
  set c_t [isUniqueTuple $c_k1 $c_s]
  if { $c_t == "" } {
    puts "Customer not found, or duplicate customer."
    qddb_keylist delete all
    qddb_tuple delete all
    qddb_schema close $c_s
    return
  }
  while {[qddb_tuple lock $c_t] == 0} {
    puts "Waiting for Customer screen to be closed...."
    exec sleep 2
  }	    
  set c_v [qddb_view define $c_t {
    { Company.Contact.Username   carr(Company.Contact.Username) }
    { CurrentBalance             carr(CurrentBalance) }
    { Recent                     carr(Recent) }
    { Balance30                  carr(Balance30) }
    { Balance60                  carr(Balance60) }
    { Balance90                  carr(Balance90) }
    { Transaction.Date           carr(Transaction.Date) }
    { Transaction.Clock          carr(Transaction.Clock) }
    { Transaction.TType          carr(Transaction.TType) }
    { Transaction.InvoiceNumber  carr(Transaction.InvoiceNumber) }
    { Transaction.Amount         carr(Transaction.Amount) }
    { Transaction.RunningBalance carr(Transaction.RunningBalance) }
  }]
  qddb_instance switch $c_v Transaction \
	[qddb_instance new $c_v Transaction]
  set carr(Transaction.Date) [qddb_util formatdate "%m/%d/%y" today]
  set carr(Transaction.Clock) [qddb_util formatdate "%X" now]
  set carr(Transaction.TType) "PaymentAccepted"
  set carr(Transaction.InvoiceNumber) "0"
  set carr(Transaction.Amount) $Amount
  set carr(Transaction.RunningBalance) \
	[expr $carr(CurrentBalance) + $Amount]
  set carr(CurrentBalance) $carr(Transaction.RunningBalance)
  qddb_tuple write $c_t
  qddb_tuple delete $c_t
  qddb_schema close $c_s
}

proc CheckProc {tuple} {
	global env errorCode firstname lastname username id
	set v [qddb_view define $tuple {}]
	qddb_instance setval $v DateOfPayment now
	qddb_instance setval $v Clock [qddb_util formatdate "%X" now]
	set user [string trim [qddb_instance getval $v Name.Username]]
	if {[string length $user] == 0} {
		NoUser
	}
	if {![info exists env(REMOTE_USER)]} {
		BadUSER
	}
	if {$user == $env(REMOTE_USER)} {
		NoOneself
	}
	qddb_instance setval $v AcceptedBy $env(REMOTE_USER)
	set cost [qddb_instance getval $v Amount]
	if {[expr 0 + $cost] <= 0.00} {
		NoAmount
	}
	if {[string trim [qddb_instance getval $v MethodOfPayment]]==""} {
		NoMethod
	}
	catch {exec $ID -Gn $env(REMOTE_USER)} result
	if {$errorCode != "NONE"} {
       	        BadUSER
       	}
	catch {exec $ID -Gn $user} result
	if {$errorCode != "NONE"} {
                BadName
        }
	Post_Payment $user $cost
	if {$username != $user} {
		BadName
	}
	qddb_instance setval $v Name.First $firstname
	qddb_instance setval $v Name.Last $lastname
	qddb_instance setval $v Name.ID $id
	Post_Fee $env(REMOTE_USER) $cost
}

Hx:GenericSubmissionForm $dbname $webmaster $hostname $mypath $dir \
	$title $opening $message $signature {
	EntryProc
	CheckProc
}

exit 0

