+/**
+* Check account history to find transaction which would exceed authorized overdraft for given account.
+* Returns null or transaction in conflict. Running balance is checked on daily basis only, to enable ID change after edition.
+* $delta_amount - tested change in bank balance at $date.
+**/
+function check_bank_account_history($delta_amount, $bank_account, $date=null, $user=null)
+{
+ if ($delta_amount >= 0 && isset($date))
+ return null; // amount increese is always safe
+
+ $balance = $date ? get_bank_account_limit($bank_account, $date, $user) : 0;
+
+ if (!isset($balance) && isset($date))
+ return null; // unlimited account
+
+ if (floatcmp($balance, -$delta_amount) < 0)
+ return array('amount' => $balance + $delta_amount, 'trans_date'=> date2sql($date));
+
+ $balance += $delta_amount;
+
+ $sql = "SELECT sum(amount) as amount, trans_date FROM ".TB_PREF."bank_trans WHERE bank_act=".db_escape($bank_account);
+ if ($date)
+ {
+ $date = date2sql($date);
+ $sql .= " AND trans_date > '$date'";
+ }
+ $sql .= " GROUP BY trans_date ORDER BY trans_date ASC";
+
+ $history = db_query($sql, "cannot retrieve cash account history");
+
+ while ($trans = db_fetch($history)) {
+ $balance += $trans['amount'];
+ if ($balance < 0)
+ {
+ $trans['amount'] = $balance;
+ return $trans;
+ }
+ }
+
+ return null;
+}
+
+/**
+* Check bank transfer, deposit or customer deposit before voiding.
+**/
+function check_void_bank_trans($type, $type_no)
+{
+ $moves = get_bank_trans($type, $type_no);
+ while ($trans = db_fetch($moves)) {
+ if ($trans['amount'] > 0) { // skip transfer input part
+ return check_bank_account_history(-$trans['amount'], $trans['bank_act'], sql2date($trans['trans_date'])) == null;
+ }
+ }
+ return true;
+}