+function is_cust_invoice_credited($trans_no)
+{
+ return db_num_rows(get_sales_child_lines(ST_SALESINVOICE, $trans_no));
+}
+
+function get_cust_prepayment_invoice_factor($trans_no)
+{
+ $sql = "SELECT IF(dt.prep_amount>0, dt.prep_amount/so.total ,0)
+ FROM ".TB_PREF."debtor_trans dt
+ LEFT JOIN ".TB_PREF."sales_orders so ON so.trans_type=".ST_SALESORDER." AND so.order_no=dt.order_
+ WHERE dt.type=".ST_SALESINVOICE." AND trans_no=".db_escape($trans_no);
+ $row = db_fetch(db_query($sql, 'cannot retrieve prepaid invoice factor'));
+ return $row[0];
+}
+
+/*
+ Return yet not invoiced amount of prepayment invoice (or 0 if normal invoice)
+*/
+function prepaid_invoice_remainder($order)
+{
+ $sql = "SELECT so.total - IFNULL(SUM(inv.prep_amount),0) FROM "
+ .TB_PREF."sales_orders so,
+ ".TB_PREF."debtor_trans inv,
+ ".TB_PREF."payment_terms pt
+ WHERE so.order_no=".db_escape($order)
+ ." AND so.trans_type=".ST_SALESORDER
+ ." AND inv.type=".ST_SALESINVOICE
+ ." AND inv.order_=so.order_no"
+ ." AND so.payment_terms=pt.terms_indicator"
+ ." AND inv.payment_terms=pt.terms_indicator"
+ ." AND pt.days_before_due = -1";
+
+ $result = db_fetch(db_query($sql, "cannot find final invoice value"));
+ return $result[0] ? $result[0] : 0;
+}
+
+
+/*
+ Find oldest delivery date for sales invoice
+*/
+function get_oldest_delivery_date($invoice_no)
+{
+ $sql = "SELECT MIN(trans.tran_date)
+ FROM
+ ".TB_PREF."debtor_trans_details del
+ LEFT JOIN ".TB_PREF."debtor_trans_details inv
+ ON inv.src_id=del.id
+ LEFT JOIN ".TB_PREF."debtor_trans trans
+ ON trans.type=".ST_CUSTDELIVERY." AND trans.trans_no = del.debtor_trans_no
+ WHERE
+ inv.debtor_trans_type=".ST_SALESINVOICE
+ ." AND inv.debtor_trans_no=".db_escape($invoice_no);
+ $res = db_query($sql, 'cannot find oldest delivery date');
+ $date = db_fetch($res);
+ return $date[0];
+}
+
+/*
+ Find oldest payment date for sales invoice
+*/
+function get_oldest_payment_date($invoice_no)
+{
+ $sql = "SELECT MIN(payment.tran_date)
+ FROM
+ ".TB_PREF."cust_allocations alloc,
+ ".TB_PREF."debtor_trans payment
+ WHERE
+ alloc.trans_type_to=".ST_SALESINVOICE." AND alloc.trans_no_to=".db_escape($invoice_no)
+ ." AND alloc.trans_type_from=payment.type AND alloc.trans_no_from=payment.trans_no";
+ $res = db_query($sql, 'cannot find oldest delivery date');
+ $date = db_fetch($res);
+ return $date[0];
+}