- $sql = "SELECT SUM(IF(".TB_PREF."debtor_trans.type = ".ST_SALESINVOICE.", (".TB_PREF."debtor_trans.ov_amount + ".TB_PREF."debtor_trans.ov_gst +
- ".TB_PREF."debtor_trans.ov_freight + ".TB_PREF."debtor_trans.ov_discount)";
- if ($convert)
- $sql .= " * rate";
- $sql .= ", 0)) AS charges,
- SUM(IF(".TB_PREF."debtor_trans.type <> ".ST_SALESINVOICE.", (".TB_PREF."debtor_trans.ov_amount + ".TB_PREF."debtor_trans.ov_gst +
- ".TB_PREF."debtor_trans.ov_freight + ".TB_PREF."debtor_trans.ov_discount)";
- if ($convert)
- $sql .= " * rate";
- $sql .= " * -1, 0)) AS credits,
- SUM(".TB_PREF."debtor_trans.alloc";
- if ($convert)
- $sql .= " * rate";
- $sql .= ") AS Allocated,
- SUM(IF(".TB_PREF."debtor_trans.type = ".ST_SALESINVOICE.", (".TB_PREF."debtor_trans.ov_amount + ".TB_PREF."debtor_trans.ov_gst +
- ".TB_PREF."debtor_trans.ov_freight + ".TB_PREF."debtor_trans.ov_discount - ".TB_PREF."debtor_trans.alloc)";
- if ($convert)
- $sql .= " * rate";
- $sql .= ",
- ((".TB_PREF."debtor_trans.ov_amount + ".TB_PREF."debtor_trans.ov_gst + ".TB_PREF."debtor_trans.ov_freight +
- ".TB_PREF."debtor_trans.ov_discount) * -1 + ".TB_PREF."debtor_trans.alloc)";
- if ($convert)
- $sql .= " * rate";
- $sql .= ")) AS OutStanding
- FROM ".TB_PREF."debtor_trans
- WHERE ".TB_PREF."debtor_trans.tran_date < '$to'
- AND ".TB_PREF."debtor_trans.debtor_no = '$debtorno'
- AND ".TB_PREF."debtor_trans.type <> ".ST_CUSTDELIVERY." GROUP BY debtor_no";
+ $sql .= "SUM(IF(t.type = ".ST_SALESINVOICE." OR (t.type IN (".ST_JOURNAL." , ".ST_BANKPAYMENT.") AND t.ov_amount>0), 1, -1) *
+ (IF(t.prep_amount, t.prep_amount, abs(t.ov_amount + t.ov_gst + t.ov_freight + t.ov_freight_tax + t.ov_discount)) - abs(t.alloc))) AS OutStanding
+ FROM ".TB_PREF."debtor_trans t
+ WHERE t.debtor_no = ".db_escape($debtorno)
+ ." AND t.type <> ".ST_CUSTDELIVERY;
+ if ($to)
+ $sql .= " AND t.tran_date < '$to'";
+ $sql .= " GROUP BY debtor_no";