Changes up to 2.3.7 merged into unstable branch.
[fa-stable.git] / gl / includes / db / gl_db_bank_trans.inc
index a0aab62eac8a9e39ce21279d072f39361acfe4f9..f11a56987358dead57b1803f65fb1fa8ff4bea71 100644 (file)
@@ -87,11 +87,13 @@ function get_bank_trans_for_bank_account($bank_account, $from, $to)
 {
        $from = date2sql($from);
        $to = date2sql($to);
-       $sql = "SELECT ".TB_PREF."bank_trans.* FROM ".TB_PREF."bank_trans
-               WHERE ".TB_PREF."bank_trans.bank_act = ".db_escape($bank_account) . "
+       $sql = "SELECT t.* FROM "
+               .TB_PREF."bank_trans t LEFT JOIN ".TB_PREF."voided v ON t.type=v.type AND t.trans_no=v.id
+               WHERE t.bank_act = ".db_escape($bank_account) . "
+               AND ISNULL(v.date_)
                AND trans_date >= '$from'
                AND trans_date <= '$to'
-               ORDER BY trans_date,".TB_PREF."bank_trans.id";
+               ORDER BY trans_date, t.id";
 
        return db_query($sql,"The transactions for '" . $bank_account . "' could not be retrieved");
 }
@@ -126,6 +128,7 @@ function get_gl_trans_value($account, $type, $trans_no)
 
 function void_bank_trans($type, $type_no, $nested=false)
 {
+
        if (!$nested)
                begin_transaction();
 
@@ -150,4 +153,49 @@ function void_bank_trans($type, $type_no, $nested=false)
                commit_transaction();
 }
 
-?>
\ No newline at end of file
+/**
+*      Check account history to find transaction which would exceed authorized overdraft for given account.
+*      Returns null or transaction in conflict.
+*      $delta_amount - tested change in bank balance at $date.
+**/
+function check_bank_account_history($delta_amount, $bank_account, $date, $user=null)
+{
+       if ($delta_amount >= 0)
+                return null;   // amount increese is always safe
+
+       $balance = get_bank_account_limit($bank_account, $date, $user);
+
+       if (!isset($balance))
+               return null;    // unlimited account
+
+       $date = date2sql($date);
+       $balance+= $delta_amount;
+
+       $sql = "SELECT * FROM ".TB_PREF."bank_trans WHERE bank_act=".db_escape($bank_account)." AND trans_date > '$date' ORDER BY trans_date ASC, id ASC";
+
+       $history = db_query($sql, "cannot retrieve cash account history");
+
+       while ($trans = db_fetch($history)) {
+               $balance += $trans['amount'];
+               if ($balance < 0)
+                       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;
+}
+
+?>