コード例 #1
0
function write($_POST)
{
    # processes
    db_connect();
    # Get vars
    extract($_POST);
    if (isset($back)) {
        return add($_POST);
    }
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($bankid, "num", 1, 30, "Invalid Bank Account.");
    $v->isOk($date, "date", 1, 10, "Invalid Date Entry.");
    $v->isOk($cusnum, "num", 1, 20, "Invalid Customer account.");
    $v->isOk($descript, "string", 0, 255, "Invalid Description.");
    $v->isOk($reference, "string", 0, 50, "Invalid Reference Name/Number.");
    $v->isOk($cheqnum, "num", 0, 30, "Invalid Cheque number.");
    $v->isOk($amount, "float", 1, 10, "Invalid amount.");
    # display errors, if any
    if ($v->isError()) {
        $confirm = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $confirm .= "<li class='err'>" . $e["msg"] . "</li>";
        }
        $confirm .= "<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $confirm;
    }
    # date format
    $date = explode("-", $date);
    $date = $date[2] . "-" . $date[1] . "-" . $date[0];
    # refnum
    $refnum = getrefnum();
    # cheq number
    $cheqnum = 0 + $cheqnum;
    # Get customer
    $custRslt = get("cubit", "*", "customers", "cusnum", $cusnum);
    $cust = pg_fetch_array($custRslt);
    # Get department
    db_conn("exten");
    $sql = "SELECT * FROM departments WHERE deptid = '{$cust['deptid']}' AND div = '" . USER_DIV . "'";
    $deptRslt = db_exec($sql);
    if (pg_numrows($deptRslt) < 1) {
        return "<i class='err'>Department Not Found</i>";
    } else {
        $dept = pg_fetch_array($deptRslt);
    }
    # Get hook account number
    core_connect();
    $sql = "SELECT * FROM bankacc WHERE accid = '{$bankid}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to retrieve bank account link from Cubit", SELF);
    # Check if link exists
    if (pg_numrows($rslt) < 1) {
        return "<li class='err'> ERROR : The bank account that you selected doesn't appear to have an account linked to it.</li>";
    }
    $banklnk = pg_fetch_array($rslt);
    # Begin updates
    pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
    # DT(customer control), CT(bank)
    writetrans($dept['debtacc'], $banklnk['accnum'], $date, $refnum, $amount, $descript);
    recordDT($amount, $cust['cusnum'], $date);
    # Record the payment record
    db_connect();
    $sql = "\n\t\t\tINSERT INTO cashbook (\n\t\t\t\tbankid, trantype, date, cusnum, name, descript, \n\t\t\t\tcheqnum, amount, vat, chrgvat, banked, accinv, reference, div\n\t\t\t) VALUES (\n\t\t\t\t'{$bankid}', 'withdrawal', '{$date}', '{$cusnum}', '({$cust['accno']}) {$cust['cusname']} {$cust['surname']}', '{$descript}', \n\t\t\t\t'{$cheqnum}', '{$amount}', '0', 'no', 'no', '{$dept['debtacc']}', '{$reference}', '" . USER_DIV . "'\n\t\t\t)";
    $Rslt = db_exec($sql) or errDie("Unable to add bank payment to database.", SELF);
    # record the payment on the statement
    $sql = "\n\t\t\tINSERT INTO stmnt (\n\t\t\t\tcusnum, invid, amount, date, type, st, div, allocation_date\n\t\t\t) VALUES (\n\t\t\t\t'{$cust['cusnum']}', '0', '{$amount}', '{$date}', '{$descript}', 'n', '" . USER_DIV . "', '{$date}'\n\t\t\t)";
    $stmntRslt = db_exec($sql) or errDie("Unable to Insert statement record in Cubit.", SELF);
    # record the payment on the statement
    $sql = "\n\t\t\tINSERT INTO open_stmnt (\n\t\t\t\tcusnum, invid, amount, date, type, st, div, balance\n\t\t\t) VALUES (\n\t\t\t\t'{$cust['cusnum']}', '0', '{$amount}', '{$date}', '{$descript}', 'n', '" . USER_DIV . "', '{$amount}'\n\t\t\t)";
    $stmntRslt = db_exec($sql) or errDie("Unable to Insert statement record in Cubit.", SELF);
    # update the customer (make balance more)
    $sql = "UPDATE customers SET balance = (balance + '{$amount}') WHERE cusnum = '{$cust['cusnum']}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to update customer in Cubit.", SELF);
    # Make ledge record
    custledger($cust['cusnum'], $banklnk['accnum'], $date, $refnum, $descript, $amount, "d");
    # Commit updates
    pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
    # Status report
    $write = "\n\t\t<table " . TMPL_tblDflts . " width='100%'>\n\t\t\t<tr>\n\t\t\t\t<th>Bank Payment</th>\n\t\t\t</tr>\n\t\t\t<tr class='datacell'>\n\t\t\t\t<td>Bank Payment added to cash book.</td>\n\t\t\t</tr>\n\t\t</table>";
    # Main table (layout with menu)
    $OUTPUT = "\n\t\t<center>\n\t\t<table width='90%'>\n\t\t\t<tr valign='top'>\n\t\t\t\t<td width='50%'>{$write}</td>\n\t\t\t\t<td align='center'>\n\t\t\t\t\t<table " . TMPL_tblDflts . " width='80%'>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<th>Quick Links</th>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr class='datacell'>\n\t\t\t\t\t\t\t<td align='center'><a target=_blank href='../core/acc-new2.php'>Add account (New Window)</a></td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td><a href='bank-pay-add.php'>Add Bank Payment</a></td></tr>\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td><a href='bank-recpt-add.php'>Add Bank Receipt</a></td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td><a href='cashbook-view.php'>View Cash Book</a></td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<script>document.write(getQuicklinkSpecial());</script>\n\t\t\t\t\t</table>\n\t\t\t\t</td>\n\t\t\t</tr>\n\t\t</table>";
    return $OUTPUT;
}
コード例 #2
0
function recvpayment_write()
{
    if (isset($_POST["btn_back"])) {
        return details($_POST);
    }
    extract($_POST);
    $v = new validate();
    $v->isOk($cusnum, "num", 1, 10, "Invalid customer id.");
    $v->isOk($bank_acc, "num", 1, 10, "Invalid cash account selected.");
    $v->isOk($pcc, "float", 1, 40, "Invalid credit card amount.");
    $v->isOk($pcash, "float", 1, 40, "Invalid cash amount.");
    $v->isOk($pcheque, "float", 1, 40, "Invalid cheque amount.");
    $v->isOk($amt, "float", 1, 40, "Invalid total received amount.");
    $v->isOk($out, "float", 1, 40, "Invalid unallocated amount.");
    $v->isOk($descript, "string", 1, 255, "Invalid description.");
    $v->isOk($date, "date", 1, 1, "Invalid invoice date.");
    if ($v->isError()) {
        return details($_POST, $v->genErrors());
    }
    $sdate = $date;
    $cus = qryCustomer($cusnum);
    $dept = qryDepartment($cus["deptid"], "debtacc");
    $refnum = getrefnum();
    pglib_transaction("BEGIN");
    /* do the calculations/recordings */
    # update the customer (make balance less)
    $sql = "UPDATE cubit.customers SET balance = (balance - '{$amt}'::numeric(13,2))\n\t\t\tWHERE cusnum = '{$cus['cusnum']}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
    if (isset($invids)) {
        foreach ($invids as $key => $value) {
            $ii = $invids[$key];
            /* OPTION 1: STOCK INVOICES */
            if (!isset($itype[$ii]) && !isset($ptype[$ii])) {
                $sql = "SELECT prd,invnum,odate FROM cubit.invoices\n\t\t\t\t\t\tWHERE invid ='{$invids[$key]}' AND div = '" . USER_DIV . "'";
                $invRslt = db_exec($sql) or errDie("Unable to retrieve invoice details from database.");
                if (pg_numrows($invRslt) < 1) {
                    return "<li class=err>Invalid Invoice Number.";
                }
                $inv = pg_fetch_array($invRslt);
                $inv['invnum'] += 0;
                // reduce invoice balance
                $sql = "UPDATE cubit.invoices\n\t\t\t\t\t\tSET balance = (balance - {$paidamt[$key]}::numeric(13,2))\n\t\t\t\t\t\tWHERE invid = '{$invids[$key]}' AND div = '" . USER_DIV . "'";
                $payRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
                $sql = "UPDATE cubit.open_stmnt\n\t\t\t\t\t\tSET balance = (balance - {$paidamt[$key]}::numeric(13,2))\n\t\t\t\t\t\tWHERE invid = '{$inv['invnum']}' AND div = '" . USER_DIV . "'";
                $payRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
                # record the payment on the statement
                $sql = "\n\t\t\t\t\tINSERT INTO cubit.stmnt \n\t\t\t\t\t\t(cusnum, invid, amount, date, type, div, allocation_date) \n\t\t\t\t\tVALUES \n\t\t\t\t\t\t('{$cus['cusnum']}','{$inv['invnum']}', '" . ($paidamt[$key] - $paidamt[$key] * 2) . "','{$sdate}', 'Payment for Invoice No. {$inv['invnum']}', '" . USER_DIV . "', '{$inv['odate']}')";
                $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
                custledger($cus['cusnum'], $bank_acc, $sdate, $inv['invnum'], "Payment for Invoice No. {$inv['invnum']}", $paidamt[$key], "c");
                $rinvids .= "|{$invids[$key]}";
                $amounts .= "|{$paidamt[$key]}";
                if ($inv['prd'] == "0") {
                    $inv['prd'] = PRD_DB;
                }
                $invprds .= "|{$inv['prd']}";
                $rages .= "|0";
                $invidsers .= " - {$inv['invnum']}";
                /* OPTION 1: NONS STOCK INVOICES */
            } else {
                if (!isset($ptype[$ii])) {
                    $sql = "SELECT prd,invnum,descrip,age,odate FROM cubit.nons_invoices\n\t\t\t\t\t\tWHERE invid ='{$invids[$key]}' AND div = '" . USER_DIV . "'";
                    $invRslt = db_exec($sql) or errDie("Unable to retrieve invoice details from database.");
                    if (pg_numrows($invRslt) < 1) {
                        return "<li class=err>Invalid Invoice Number.";
                    }
                    $inv = pg_fetch_array($invRslt);
                    $inv['invnum'] += 0;
                    # reduce the money that has been paid
                    $sql = "UPDATE cubit.nons_invoices\n\t\t\t\t\t\tSET balance = (balance - {$paidamt[$key]}::numeric(13,2))\n\t\t\t\t\t\tWHERE invid = '{$invids[$key]}' AND div = '" . USER_DIV . "'";
                    $payRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
                    $sql = "UPDATE cubit.open_stmnt\n\t\t\t\t\t\tSET balance = (balance - {$paidamt[$key]}::numeric(13,2))\n\t\t\t\t\t\tWHERE invid = '{$inv['invnum']}' AND div = '" . USER_DIV . "'";
                    $payRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
                    # record the payment on the statement
                    $sql = "\n\t\t\t\t\tINSERT INTO cubit.stmnt \n\t\t\t\t\t\t(cusnum, invid, amount, date, type, div, allocation_date) \n\t\t\t\t\tVALUES \n\t\t\t\t\t\t('{$cus['cusnum']}','{$inv['invnum']}', '" . ($paidamt[$key] - $paidamt[$key] * 2) . "','{$sdate}', 'Payment for Non Stock Invoice No. {$inv['invnum']} - {$inv['descrip']}', '" . USER_DIV . "', '{$inv['odate']}')";
                    $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
                    custledger($cus['cusnum'], $bank_acc, $sdate, $inv['invnum'], "Payment for Non Stock Invoice No. {$inv['invnum']} - {$inv['descrip']}", $paidamt[$key], "c");
                    recordCT($paidamt[$key], $cus['cusnum'], $inv['age'], $sdate);
                    $rinvids .= "|{$invids[$key]}";
                    $amounts .= "|{$paidamt[$key]}";
                    $invprds .= "|0";
                    $rages .= "|{$inv['age']}";
                    $invidsers .= " - {$inv['invnum']}";
                } else {
                    /* pos invoices */
                    $sql = "SELECT * FROM cubit.prd_pinvoices\n\t\t\t\t\t\tWHERE invid='{$invids[$key]}' AND div='" . USER_DIV . "'";
                    $invRslt = db_exec($sql) or errDie("Unable to retrieve invoice details from database.");
                    if (pg_numrows($invRslt) < 1) {
                        return "<li class='err'>Invalid Invoice Number.</li>";
                    }
                    $inv = pg_fetch_array($invRslt);
                    // reduce the invoice balance
                    $sql = "UPDATE \"{$inv['iprd']}\".pinvoices\n\t\t\t\t\t\tSET balance = (balance - {$paidamt[$key]}::numeric(13,2))\n\t\t\t\t\t\tWHERE invid = '{$invids[$key]}' AND div = '" . USER_DIV . "'";
                    $payRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
                    $sql = "UPDATE cubit.open_stmnt\n\t\t\t\t\t\tSET balance = (balance - {$paidamt[$key]}::numeric(13,2))\n\t\t\t\t\t\tWHERE invid = '{$inv['invnum']}' AND div = '" . USER_DIV . "'";
                    $payRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
                    # record the payment on the statement
                    $sql = "\n\t\t\t\t\tINSERT INTO cubit.stmnt\n\t\t\t\t\t\t(cusnum, invid, amount, date, type, div, allocation_date) \n\t\t\t\t\tVALUES \n\t\t\t\t\t\t('{$cus['cusnum']}','{$inv['invnum']}', '" . ($paidamt[$key] - $paidamt[$key] * 2) . "','{$sdate}', 'Payment for Non Stock Invoice No. {$inv['invnum']}', '" . USER_DIV . "', '{$inv['odate']}')";
                    $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
                    custledger($cus['cusnum'], $bank_acc, $sdate, $inv['invnum'], "Payment for Non Stock Invoice No. {$inv['invnum']}", $paidamt[$key], "c");
                    recordCT($paidamt[$key], $cus['cusnum'], 0, $sdate);
                    $rinvids .= "|{$invids[$key]}";
                    $amounts .= "|{$paidamt[$key]}";
                    $invprds .= "|{$inv['prd']}";
                    //$rages .= "|$inv[age]";
                    $invidsers .= " - {$inv['invnum']}";
                }
            }
        }
    }
    writetrans($bank_acc, $dept['debtacc'], $sdate, $refnum, $amt, "Payment for Invoices {$invidsers} from customer {$cus['cusname']} {$cus['surname']}");
    db_conn('cubit');
    if ($out > 0) {
        /* START OPEN ITEMS */
        $openstmnt = new dbSelect("open_stmnt", "cubit", grp(m("where", "balance>0 AND cusnum='{$cusnum}'"), m("order", "date")));
        $openstmnt->run();
        $open_out = $out;
        $i = 0;
        $ox = "";
        while ($od = $openstmnt->fetch_array()) {
            if ($open_out == 0) {
                continue;
            }
            $oid = $od['id'];
            if ($open_out >= $od['balance']) {
                $open_amount[$oid] = $od['balance'];
                $open_out = sprint($open_out - $od['balance']);
                $ox .= "<tr class='" . bg_class() . "'><td><input type=hidden size=20 name=open[{$oid}] value='{$oid}'>{$od['type']}</td>\n\t\t\t\t\t<td>" . CUR . " {$od['balance']}</td><td>{$od['date']}</td><td><input type=hidden name='open_amount[{$oid}]' value='{$open_amount[$oid]}'>\n\t\t\t\t\t" . CUR . " {$open_amount[$oid]}</td></tr>";
                $Sl = "UPDATE cubit.open_stmnt SET balance=balance-'{$open_amount[$oid]}' WHERE id='{$oid}'";
                $Ri = db_exec($Sl) or errDie("Unable to update statement.");
            } elseif ($open_out < $od['balance']) {
                $open_amount[$oid] = $open_out;
                $open_out = 0;
                $ox .= "<tr class='" . bg_class() . "'><td><input type=hidden size=20 name=open[{$oid}] value='{$od['id']}'>{$od['type']}</td>\n\t\t\t\t\t<td>" . CUR . " {$od['balance']}</td><td>{$od['date']}</td><td><input type=hidden name='open_amount[{$oid}]' value='{$open_amount[$oid]}'>\n\t\t\t\t\t" . CUR . " {$open_amount[$oid]}</td></tr>";
                $Sl = "UPDATE cubit.open_stmnt SET balance=balance-'{$open_amount[$oid]}' WHERE id='{$oid}'";
                $Ri = db_exec($Sl) or errDie("Unable to update statement.");
            }
            $i++;
        }
        if (open()) {
            $bout = $out;
            $out = $open_out;
            if ($out > 0) {
                $sql = "INSERT INTO cubit.open_stmnt(cusnum, invid, amount, balance, date, type, st, div) VALUES('{$cus['cusnum']}', '0', '-{$out}', '-{$out}', '{$sdate}', 'Payment Received', 'n', '" . USER_DIV . "')";
                $stmntRslt = db_exec($sql) or errDie("Unable to Insert statement record in Cubit.", SELF);
                //$confirm .="<tr class='bg-even'><td colspan=4><b>A general transaction will credit the client's account with ".CUR." $out </b></td></tr>";
            }
            $out = $bout;
        } else {
            //$confirm .="<tr class='bg-even'><td colspan=4><b>A general transaction will credit the client's account with ".CUR." $out </b></td></tr>";}
        }
    }
    if ($out > 0) {
        recordCT($out, $cus['cusnum'], 0, $sdate);
        $cols = grp(m("cusnum", $cus["cusnum"]), m("invid", 0), m("amount", -$out), m("date", $sdate), m("type", "Payment Received"), m("div", USER_DIV), m("allocation_date", $sdate));
        $dbobj = new dbUpdate("stmnt", "cubit", $cols);
        $dbobj->run(DB_INSERT);
        $dbobj->free();
        custledger($cus['cusnum'], $bank_acc, $sdate, "PAYMENT", "Payment received.", $out, "c");
    }
    $sql = "INSERT INTO cubit.payrec(date,by,multiinv,amount,method,prd,note)\n\t\t\tVALUES('{$sdate}','" . USER_NAME . "', '{$invidsers}', '{$pcash}','Cash','" . PRD_DB . "','0')";
    db_exec($sql) or errDie("Unable to insert data.");
    $sql = "INSERT INTO cubit.payrec(date,by,multiinv,amount,method,prd,note)\n\t\t\tVALUES('{$sdate}','" . USER_NAME . "', '{$invidsers}', '{$pcc}','Credit Card','" . PRD_DB . "','0')";
    db_exec($sql) or errDie("Unable to insert data.");
    $sql = "INSERT INTO cubit.payrec(date,by,multiinv,amount,method,prd,note)\n\t\t\tVALUES('{$sdate}','" . USER_NAME . "', '{$invidsers}', '{$pcheque}','Cheque','" . PRD_DB . "','0')";
    db_exec($sql) or errDie("Unable to insert data.");
    pglib_transaction("COMMIT");
    $_POST["pcc"] = $_POST["pcheque"] = $_POST["pcash"] = "0.00";
    return details($_POST, "<li class='err'>Payment received successfully</li>");
}
コード例 #3
0
function write()
{
    extract($_REQUEST);
    require_lib("validate");
    $v = new validate();
    $v->isOk($invid, "num", 1, 20, "Invalid invoice number.");
    $sndate = "{$ninv_year}-{$ninv_month}-{$ninv_day}";
    if (!checkdate($ninv_month, $ninv_day, $ninv_year)) {
        $v->addError($sdate, "Invalid Date.");
    }
    pglib_transaction("BEGIN");
    // Get invoice info
    $sql = "SELECT * FROM cubit.nons_invoices WHERE invid='{$invid}' AND div='" . USER_DIV . "'";
    $inv_rslt = db_exec($sql) or errDie("Unable to get invoice information");
    if (pg_numrows($inv_rslt) < 1) {
        return "<i class='err'>Not Found</i>";
    }
    $inv = pg_fetch_array($inv_rslt);
    $TOTAL = $inv["subtot"] + $inv["vat"];
    $notenum = pglib_lastid("cubit.nons_inv_notes", "noteid");
    $notenum++;
    // Add to the non stock credit notes
    $sql = "\r\n\t\tINSERT INTO cubit.nons_inv_notes (\r\n\t\t\tinvid, invnum, cusname, cusaddr, cusvatno, chrgvat, \r\n\t\t\tdate, subtot, vat, total, username, prd, notenum, ctyp, \r\n\t\t\tremarks, div\r\n\t\t) VALUES (\r\n\t\t\t'{$inv['invid']}', '{$inv['invnum']}', '{$inv['cusname']}', '{$inv['cusaddr']}', '{$inv['cusvatno']}', '{$inv['chrgvat']}', \r\n\t\t\t'{$sndate}', '{$inv['subtot']}', '{$inv['vat']}', '{$TOTAL}', '" . USER_NAME . "', '" . PRD_DB . "', '{$notenum}', '{$inv['ctyp']}', \r\n\t\t\t'{$inv['remarks']}', '" . USER_DIV . "'\r\n\t\t)";
    db_exec($sql) or errDie("Unable to save credit note.");
    $noteid = pglib_lastid("cubit.nons_inv_notes", "noteid");
    $sql = "SELECT count(id) FROM cubit.nons_inv_items WHERE invid='{$invid}'";
    $count_rslt = db_exec($sql) or errDie("Unable to retrieve amount of items.");
    $item_count = pg_fetch_result($count_rslt, 0);
    $i = 0;
    $page = 0;
    foreach ($ids as $key => $id) {
        $sql = "SELECT * FROM cubit.nons_inv_items WHERE invid='{$invid}' AND id='{$id}'";
        $item_rslt = db_exec($sql) or errDie("Unable to retrieve item.");
        $item_data = pg_fetch_array($item_rslt);
        if ($item_data['vatex'] == 'y') {
            $ex = "#";
        } else {
            $ex = "&nbsp;&nbsp;";
        }
        // Time for a new page ??
        if ($i >= 25) {
            $page++;
            $i = 0;
        }
        $products[$page][] = "\r\n\t\t\t<tr valign='top'>\r\n\t\t\t\t<td style='border-right: 2px solid #000'>\r\n\t\t\t\t\t{$ex} {$item_data['description']}&nbsp;\r\n\t\t\t\t</td>\r\n\t\t\t\t<td style='border-right: 2px solid #000'>\r\n\t\t\t\t\t{$item_data['qty']}&nbsp;\r\n\t\t\t\t</td>\r\n\t\t\t\t<td style='border-right: 2px solid #000' align='right' nowrap>\r\n\t\t\t\t\t" . CUR . " {$item_data['unitcost']}&nbsp;\r\n\t\t\t\t</td>\r\n\t\t\t\t<td align='right' nowrap>" . CUR . " {$item_data['amt']}&nbsp;</td>\r\n\t\t\t</tr>";
        $i++;
        // Create credit note item
        $sql = "\r\n\t\t\tINSERT INTO cubit.nons_note_items (\r\n\t\t\t\tnoteid, qty, description, amt, unitcost, \r\n\t\t\t\tvatcode\r\n\t\t\t) VALUES (\r\n\t\t\t\t'{$noteid}', '{$qtys[$key]}', '{$item_data['description']}', '{$amts[$key]}', '{$item_data['unitcost']}', \r\n\t\t\t\t'{$item_data['vatex']}'\r\n\t\t\t)";
        db_exec($sql) or errDie("Unable to create credit note item.");
        $sql = "SELECT grpid FROM cubit.assets WHERE id='{$item_data['asset_id']}'";
        $group_rslt = db_exec($sql) or errDie("Unable to retrieve group.");
        $group_id = pg_fetch_result($group_rslt, 0);
        $discount = $inv["discount"] / $item_count;
        $amt = $item_data["amt"];
        // Update royalty report and detail report
        $sql = "\r\n\t\t\tINSERT INTO hire.revenue (\r\n\t\t\t\tgroup_id, asset_id, total, discount, credit\r\n\t\t\t) VALUES (\r\n\t\t\t\t'{$group_id}', '{$item_data['asset_id']}', '-{$amt}', '-{$discount}', '1'\r\n\t\t\t)";
        db_exec($sql) or errDie("Unable to update revenue.");
        $i++;
    }
    $blank_lines = 25;
    foreach ($products as $key => $val) {
        $bl = $blank_lines - count($products[$key]);
        for ($i = 0; $i <= $bl; $i++) {
            $products[$key][] = "\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'>&nbsp;</td>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'>&nbsp;</td>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'>&nbsp;</td>\r\n\t\t\t\t\t<td>&nbsp;</td>\r\n\t\t\t\t</tr>";
        }
    }
    // Retrieve customer debt account
    $sql = "\r\n\t\tSELECT debtacc FROM exten.departments \r\n\t\t\tLEFT JOIN cubit.customers ON departments.deptid=customers.deptid\r\n\t\tWHERE cusnum='{$inv['cusid']}'";
    $dept_rslt = db_exec($sql) or errDie("Unable to retrieve departments.");
    $debtacc = pg_fetch_result($dept_rslt, 0);
    $hireacc = $inv["accid"];
    $vatacc = gethook("accnum", "salesacc", "name", "VAT", "vat");
    $refnum = getrefnum();
    writetrans($hireacc, $debtacc, $sndate, $refnum, $inv["subtot"], "Non-Stock Invoice No. {$inv['invnum']} Credit Note No. {$noteid} Customer\r\n\t\t{$inv['cusname']}");
    if ($inv["vat"] != 0) {
        writetrans($vatacc, $debtacc, $sndate, $refnum, $inv["vat"], "Non-Stock Invoice No. {$inv['invnum']} Credit Note No. {$noteid} VAT.\r\n\t\tCustomer {$inv['cusname']}");
    }
    // Record on the statement
    $sql = "\r\n\t\tINSERT INTO cubit.stmnt (\r\n\t\t\tcusnum, invid, amount, date, type, \r\n\t\t\tdiv\r\n\t\t) VALUES (\r\n\t\t\t'{$inv['cusid']}', '{$noteid}', '-{$TOTAL}', '{$sndate}', 'Non-Stock Credit Note, for invoice {$inv['invnum']}', \r\n\t\t\t'" . USER_DIV . "'\r\n\t\t)";
    db_exec($sql) or errDie("Unable to insert to customer statement.");
    // Update the customer (Make the balance less)
    $sql = "UPDATE cubit.customers SET balance=(balance-'{$TOTAL}') WHERE cusnum='{$inv['cusid']}'";
    db_exec($sql) or errDie("Unable to update customer balance.");
    // Update the customer (Make the balance less)
    $sql = "UPDATE cubit.open_stmnt SET balance=(balance-'{$TOTAL}') WHERE cusnum='{$inv['cusid']}'";
    db_exec($sql) or errDie("Unable to update customer balance.");
    // Create ledger record
    custledger($inv["cusid"], $hireacc, $sndate, $noteid, "Non-Stock Credit Note {$noteid}", $TOTAL, "c");
    custCT($inv["total"], $inv["cusid"], $inv["odate"]);
    // Update non-stock invoice
    $sql = "UPDATE cubit.nons_invoices SET balance=(balance-'{$TOTAL}') WHERE invid='{$invid}'";
    db_exec($sql) or errDie("Unable to update non-stock invoice.");
    $sql = "\r\n\t\tINSERT INTO cubit.salesrec (\r\n\t\t\tedate, invid, invnum, debtacc, vat, total, typ, div\r\n\t\t) VALUES (\r\n\t\t\t'{$sndate}', '{$noteid}', '{$notenum}', '0', '{$inv['vat']}', '{$TOTAL}', 'nnon', '" . USER_DIV . "'\r\n\t\t)";
    db_exec($sql) or errDie("Unable to record in sales.");
    $sql = "\r\n\t\tINSERT INTO cubit.sj (\r\n\t\t\tcid, name, des, date, \r\n\t\t\texl, vat, inc, div\r\n\t\t) VALUES (\r\n\t\t\t'{$inv['cusid']}', '{$inv['cusname']}', 'Credit Note: {$noteid} Invoice {$inv['invnum']}', '{$sndate}', \r\n\t\t\t'-" . ($TOTAL - $inv["vat"]) . "', '{$inv['vat']}', '" . -sprint($TOTAL) . "', '" . USER_DIV . "'\r\n\t\t)";
    db_exec($sql) or errDie("Unable to record in sj.");
    $sql = "UPDATE cubit.nons_invoices SET accepted='note' WHERE invid='{$invid}'";
    db_exec($sql) or errDie("Unable to update invoice.");
    com_invoice($inv["salespn"], -($TOTAL - $inv["vat"]), 0, $inv["invnum"], $sndate);
    $cc = "\r\n\t\t<script>\r\n\t\t\tCostCenter('ct', 'Credit Note', '{$sndate}',\r\n\t\t\t'Non Stock Credit Note No.{$noteid}', '" . ($TOTAL - $inv["vat"]) . "', '');\r\n\t   </script>";
    // Reverse the amounts on the coastal reports -----------------------------
    $sql = "UPDATE hire.assets_hired SET value=0 WHERE invid='{$inv['hire_invid']}'";
    db_exec($sql) or errDie("Unable to update asset hired records.");
    // Vat
    $sql = "SELECT id FROM cubit.vatcodes WHERE code='01'";
    $vd_rslt = db_exec($sql) or errDie("Unable to retrieve vatcodes.");
    $vd_id = pg_fetch_result($vd_rslt, 0);
    vatr($vd_id, $sndate, "OUTPUT", "01", $refnum, "Non-Stock Sales, invoice No.{$inv['invnum']}", $TOTAL, $inv["vat"]);
    if (!isset($showvat)) {
        $showvat = TRUE;
    }
    if ($showvat == TRUE) {
        $vat14 = AT14;
    } else {
        $vat14 = "";
    }
    // Retrieve the company information
    db_conn("cubit");
    $sql = "SELECT * FROM compinfo";
    $comp_rslt = db_exec($sql) or errDie("Unable to retrieve company.");
    $comp_data = pg_fetch_array($comp_rslt);
    // Retrieve the banking information
    $sql = "SELECT * FROM bankacct WHERE bankid='2' AND div='" . USER_DIV . "'";
    $bank_rslt = db_exec($sql) or errDie("Unable to retrieve bank.");
    $bank_data = pg_fetch_array($bank_rslt);
    // Retrieve customer information
    $sql = "SELECT * FROM customers WHERE cusnum='{$inv['cusid']}'";
    $cust_rslt = db_exec($sql) or errDie("Unable to retrieve customer.");
    $cust_data = pg_fetch_array($cust_rslt);
    if ($inv['cusid'] == "0") {
        $cust_data['surname'] = $inv['cusname'];
        $cust_data['addr1'] = $inv['cusaddr'];
        $cust_data['paddr1'] = $inv['cusaddr'];
    }
    $table_borders = "\r\n\t\tborder-top: 2px solid #000000;\r\n\t\tborder-left: 2px solid #000000;\r\n\t\tborder-right: 2px solid #000000;\r\n\t\tborder-bottom: none;";
    $details = "";
    for ($i = 0; $i <= $page; $i++) {
        // new page?
        if ($i > 1) {
            $details .= "<br style='page-break-after:always;'>";
        }
        $products_out = "";
        foreach ($products[$i] as $string) {
            $products_out .= $string;
        }
        $details .= "\r\n\t\t\t<center>\r\n\t\t\t<table cellpadding='0' cellspacing='0' width='85%' style='{$table_borders}'>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td>\r\n\t\t\t\t\t\t<table border='0' cellpadding='2' cellspacing='2' width='100%'>\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t<td align='left' rowspan='2'><img src='../compinfo/getimg.php' width='230' height='47'></td>\r\n\t\t\t\t\t\t\t\t<td align='left' rowspan='2'><font size='5'><b>" . COMP_NAME . "</b></font></td>\r\n\t\t\t\t\t\t\t\t<td align='right'><font size='5'><b>Tax Credit Note</b></font></td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t</table>\r\n\t\t\t\t\t</td>\r\n\t\t\t\t</tr>\r\n\t\t\t</table>\r\n\r\n\t\t\t<table cellpadding='0' cellspacing='0' width='85%' style='{$table_borders}'>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td valign='top'>\r\n\t\t\t\t\t\t<table cellpadding='2' cellspacing='0' border='0' width='100%'>\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t<td style='border-right: 2px solid #000'>{$comp_data['addr1']}&nbsp;</td>\r\n\t\t\t\t\t\t\t\t<td style='border-right: 2px solid #000'>{$comp_data['paddr1']}&nbsp;</td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t<td style='border-right: 2px solid #000'>{$comp_data['addr2']}&nbsp;</td>\r\n\t\t\t\t\t\t\t\t<td style='border-right: 2px solid #000'>{$comp_data['paddr2']}&nbsp;</td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t<td style='border-right: 2px solid #000'>{$comp_data['addr3']}&nbsp;</td>\r\n\t\t\t\t\t\t\t\t<td style='border-right: 2px solid #000'>{$comp_data['paddr3']}&nbsp;</td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t<td style='border-right: 2px solid #000'>{$comp_data['addr4']}&nbsp;</td>\r\n\t\t\t\t\t\t\t\t<td style='border-right: 2px solid #000'>{$comp_data['postcode']}&nbsp;</td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t<td style='border-right: 2px solid #000'><b>REG:</b> {$comp_data['regnum']}</b>&nbsp;</td>\r\n\t\t\t\t\t\t\t\t<td style='border-right: 2px solid #000'><b>{$bank_data['bankname']}</b>&nbsp;</td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t<td style='border-right: 2px solid #000'><b>VAT REG:</b> {$comp_data['vatnum']}&nbsp;</td>\r\n\t\t\t\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Branch</b> {$bank_data['branchname']}&nbsp;</td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Tel:</b> {$comp_data['tel']}&nbsp;</td>\r\n\t\t\t\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Branch Code:</b> {$bank_data['branchcode']}&nbsp;</td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Fax:</b> {$comp_data['fax']}&nbsp;</td>\r\n\t\t\t\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Acc Num:</b> {$bank_data['accnum']}&nbsp;</td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t</table>\r\n\t\t\t\t\t</td>\r\n\t\t\t\t\t<td valign='top'>\r\n\t\t\t\t\t\t<table cellpadding='2' cellspacing='0' border='0' width='100%'>\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Date</b></td>\r\n\t\t\t\t\t\t\t\t<td><b>Page Number</b></td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t<td style='border-right: 2px solid #000'>{$inv['odate']}</td>\r\n\t\t\t\t\t\t\t\t<td>" . ($i + 1) . "</td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t<td style='border-bottom: 2px solid #000; border-right: 2px solid #000'>&nbsp</td>\r\n\t\t\t\t\t\t\t\t<td style='border-bottom: 2px solid #000'>&nbsp</td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t\t<tr><td>&nbsp</td></tr>\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t<td colspan='2'><b>Credit Note No:</b> {$noteid}</td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t<td colspan='2'><b>Invoice No:</b> {$inv['invnum']}</td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t<td colspan='2'><b>Proforma Inv No:</b> {$inv['docref']}</td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t</table>\r\n\t\t\t\t\t</td>\r\n\t\t\t\t</tr>\r\n\t\t\t</table>\r\n\r\n\t\t\t<table cellpadding='0' cellspacing='0' width='85%' style='{$table_borders}'>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td>\r\n\t\t\t\t\t\t<table cellpadding='2' cellspacing='0' border='0' width='100%'>\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t<td align='center'><font size='4'><b>Credit Note To:</b></font></td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t</table>\r\n\t\t\t\t\t</td>\r\n\t\t\t\t</tr>\r\n\t\t\t</table>\r\n\r\n\t\t\t<table cellpadding='0' cellspacing='0' width='85%' style='{$table_borders}'>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td>\r\n\t\t\t\t\t\t<table cellpadding='2' cellspacing='0' border='0' width='100%'>\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t<td width='33%' style='border-right: 2px solid #000'><b>{$cust_data['surname']}</b></td>\r\n\t\t\t\t\t\t\t\t<td width='33%' style='border-right: 2px solid #000'><b>Postal Address</b></td>\r\n\t\t\t\t\t\t\t\t<td width='33%'><b>Delivery Address</td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t<td style='border-right: 2px solid #000'>" . nl2br($cust_data["addr1"]) . "</td>\r\n\t\t\t\t\t\t\t\t<td style='border-right: 2px solid #000'>" . nl2br($cust_data["paddr1"]) . "</td>\r\n\t\t\t\t\t\t\t\t<td>&nbsp</td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t</table>\r\n\t\t\t\t\t</td>\r\n\t\t\t\t</tr>\r\n\t\t\t</table>\r\n\r\n\t\t\t<table cellpadding='0' cellspacing='0' width='85%' style='{$table_borders}'>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td>\r\n\t\t\t\t\t\t<table cellpadding='2' cellspacing='0' border='0' width='100%'>\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t<td width='33%' style='border-right: 2px solid #000'><b>Customer VAT No:</b> {$inv['cusvatno']}</td>\r\n\t\t\t\t\t\t\t\t<td width='33%'><b>Customer Order No:</b> {$inv['cordno']}</td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t</table>\r\n\t\t\t\t\t</td>\r\n\t\t\t\t</tr>\r\n\t\t\t</table>\r\n\r\n\t\t\t<table cellpadding='0' cellspacing='0' width='85%' style='{$table_borders}'>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td>\r\n\t\t\t\t\t\t<table cellpadding='2' cellspacing='0' border='0' width='100%'>\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t<td style='border-bottom: 2px solid #000; border-right: 2px solid #000'><b>Description</b></td>\r\n\t\t\t\t\t\t\t\t<td style='border-bottom: 2px solid #000; border-right: 2px solid #000'><b>Qty</b></td>\r\n\t\t\t\t\t\t\t\t<td style='border-bottom: 2px solid #000; border-right: 2px solid #000' align='right'><b>Unit Price</b></td>\r\n\t\t\t\t\t\t\t\t<td style='border-bottom: 2px solid #000;' align='right'><b>Amount</b></td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t\t{$products_out}\r\n\t\t\t\t\t\t</table>\r\n\t\t\t\t\t</td>\r\n\t\t\t\t</tr>\r\n\t\t\t</table>\r\n\r\n\t\t\t<table cellpadding='0' cellspacing='0' width='85%' style='{$table_borders}'>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td>\r\n\t\t\t\t\t\t<table cellpadding='2' cellspacing='0' border='0' width='100%'>\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t<td><i>VAT Exempt Indicator: #</i></td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t<td>{$remarks}</td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t</table>\r\n\t\t\t\t\t</td>\r\n\t\t\t\t</tr>\r\n\t\t\t</table>\r\n\r\n\t\t\t<table cellpadding='0' cellspacing='0' width='85%' style='border: 2px solid #000000'>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td>\r\n\t\t\t\t\t\t<table cellpadding='2' cellspacing='0' border='0' width='100%'>\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Terms:</b> {$inv['terms']} days</b></td>\r\n\t\t\t\t\t\t\t\t<td><b>Trade Discount:</b></td>\r\n\t\t\t\t\t\t\t\t<td nowrap><b>" . CUR . " {$inv['discount']}</b></td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t<td style='border-right: 2px solid #000'>&nbsp;</td>\r\n\t\t\t\t\t\t\t\t<td><b>Subtotal:</b></td>\r\n\t\t\t\t\t\t\t\t<td nowrap><b>" . CUR . " {$inv['subtot']}</b></td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Received in good order by:</b>_____________________</td>\r\n\t\t\t\t\t\t\t\t<td><b>VAT {$vat14}:</b></td>\r\n\t\t\t\t\t\t\t\t<td nowrap><b>" . CUR . " {$inv['vat']}</b></td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t<td style='border-right: 2px solid #000'>&nbsp;</td>\r\n\t\t\t\t\t\t\t\t<td><b>Total Incl VAT:</b></td>\r\n\t\t\t\t\t\t\t\t<td nowrap><b>" . CUR . " " . sprint($TOTAL) . "</b></td>\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Date:</b>_____________________</td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t</table>\r\n\t\t\t\t\t</td>\r\n\t\t\t\t</tr>\r\n\t\t\t</table>";
    }
    pglib_transaction("COMMIT");
    $OUTPUT = $details;
    require "../tmpl-print.php";
}
コード例 #4
0
function write($_POST)
{
    # Get vars
    extract($_POST);
    if (!isset($proc_trans) or !is_array($proc_trans)) {
        return slctacc($_POST, "<li class='err'>Please Select Transaction(s) To Process</li>");
    }
    db_connect();
    # validate input
    require_lib("validate");
    $v = new validate();
    foreach ($proc_trans as $procid => $value) {
        $get_trans = "SELECT * FROM cust_trans_batch WHERE id = '{$procid}' LIMIT 1";
        $run_trans = db_exec($get_trans) or errDie("Unable to get transaction information.");
        if (pg_numrows($run_trans) < 1) {
            return slctacc($_POST, "<li class='err'>Transaction Not Found: (ID:{$procid})</li>");
        }
        $parr = pg_fetch_array($run_trans);
        $v->isOk($parr['cusnum'], "num", 1, 50, "Invalid Customer number.");
        $v->isOk($parr['contra_account'], "num", 1, 50, "Invalid Contra Account.");
        $v->isOk($parr['ref_num'], "num", 1, 10, "Invalid Reference number.");
        $v->isOk($parr['amount'], "float", 1, 20, "Invalid Amount.");
        $v->isOk($parr['description'], "string", 0, 255, "Invalid Details.");
        // 		$v->isOk ($author, "string", 1, 30, "Invalid Authorising person name.");
        $datea = explode("-", $parr['proc_date']);
        if (count($datea) == 3) {
            if (!checkdate($datea[1], $datea[2], $datea[0])) {
                $v->isOk($parr['proc_date'], "num", 1, 1, "Invalid date. (1)");
            }
        } else {
            $v->isOk($parr['proc_date'], "num", 1, 1, "Invalid date. (2)");
        }
        $v->isOk($parr['chrg_vat'], "string", 1, 10, "Invalid Charge VAT Option.");
        // 	$v->isOk ($vatinc, "string", 1, 10, "Invalid VAT Inclusive Exclusive Option.");
        $v->isOk($parr['vatcode'], "num", 1, 5, "Invalid Vat Code Option.");
    }
    # display errors, if any
    if ($v->isError()) {
        $write = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $write .= "<li class='err'>" . $e["msg"] . "</li>";
        }
        $write .= "<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $write;
    }
    foreach ($proc_trans as $procid => $value) {
        db_connect();
        $get_trans = "SELECT * FROM cust_trans_batch WHERE id = '{$procid}' LIMIT 1";
        $run_trans = db_exec($get_trans) or errDie("Unable to get transaction information.");
        if (pg_numrows($run_trans) < 1) {
            return slctacc($_POST, "<li class='err'>Transaction Not Found: (ID:{$procid})</li>");
        }
        $parr = pg_fetch_array($run_trans);
        $cusnum = $parr['cusnum'];
        $vatinc = $parr['chrg_vat'];
        if (isset($vatinc) and $vatinc != "0") {
            $chrgvat = "yes";
        } else {
            $chrgvat = "no";
        }
        // 		$chrgvat = $parr['chrg_vat'];
        $vatcode = $parr['vatcode'];
        $amount = $parr['amount'];
        $type = 1;
        $entry = $parr['entry_type'];
        $date = $parr['proc_date'];
        $datea = explode("-", $parr['proc_date']);
        $accid = $parr['contra_account'];
        $refnum = $parr['ref_num'];
        $details = $parr['description'];
        if (isset($chrgvat) and $chrgvat == "yes") {
            db_connect();
            #get selected vatcode
            $get_vatcode = "SELECT * FROM vatcodes WHERE id = '{$vatcode}' LIMIT 1";
            $run_vatcode = db_exec($get_vatcode) or errDie("Unable to get vat code information.");
            if (pg_numrows($run_vatcode) < 1) {
                #vatcode not found ....
                return "<li class='err'>Unable to get vat code information.</li>";
            }
            $vd = pg_fetch_array($run_vatcode);
            if ($vatinc == "inc") {
                #vat inc ...  recalc value
                $vatamt = sprint($amount * ($vd['vat_amount'] / (100 + $vd['vat_amount'])));
                $amount = sprint($amount - $vatamt);
            } else {
                #vat excl
                $amount = sprint($amount);
                $vatamt = sprint($amount / 100 * $vd['vat_amount']);
            }
        } else {
            #vat not set
            $amount = sprint($amount);
            $vatamt = sprint(0);
        }
        // 		$date = "$datea[2]-$datea[1]-$datea[0]";
        # Accounts details
        $accRs = get("core", "*", "accounts", "accid", $accid);
        $acc = pg_fetch_array($accRs);
        # Select customer
        db_connect();
        $sql = "SELECT * FROM customers WHERE cusnum = '{$cusnum}' AND div = '" . USER_DIV . "'";
        $custRslt = db_exec($sql) or errDie("Unable to access databse.", SELF);
        if (pg_numrows($custRslt) < 1) {
            return slctacc($_POST, "<li class='err'>Invalid customer ID, or customer has been blocked.</li>");
        } else {
            $cust = pg_fetch_array($custRslt);
        }
        # Get department
        db_conn("exten");
        $sql = "SELECT * FROM departments WHERE deptid = '{$cust['deptid']}' AND div = '" . USER_DIV . "'";
        $deptRslt = db_exec($sql);
        if (pg_numrows($deptRslt) < 1) {
            return slctacc($_POST, "<i class='err'>Department Not Found</i>");
        } else {
            $dept = pg_fetch_array($deptRslt);
        }
        #get vat acc ...
        $vatacc = gethook("accnum", "salesacc", "name", "VAT", "VAT");
        # Begin updates
        pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
        # Probe tran type
        if ($entry == "CT") {
            # Write transaction  (debit contra account, credit debtors control)
            writetrans($accid, $dept['debtacc'], $date, $refnum, $amount, $details . " - Customer {$cust['cusname']} {$cust['surname']}");
            $tran = "\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t      <td>{$acc['topacc']}/{$acc['accnum']} - {$acc['accname']}</td>\n\t\t\t\t      <td>{$cust['accno']} - {$cust['cusname']} {$cust['surname']}</td>\n\t\t\t      </tr>";
            $samount = $amount - $amount * 2;
            $svatamt = $vatamt - $vatamt * 2;
            recordCT($samount, $cust['cusnum'], $date);
            $type = 'c';
            if (isset($chrgvat) and $chrgvat == "yes") {
                writetrans($vatacc, $dept['debtacc'], $date, $refnum, $vatamt, "VAT for Transaction: {$refnum} for Customer : {$cust['cusname']} {$cust['surname']}");
                vatr($vd['id'], $date, "OUTPUT", $vd['code'], $refnum, "VAT for Transaction: {$refnum} for Customer : {$cust['cusname']} {$cust['surname']}", $samount + $svatamt, $svatamt);
            }
        } else {
            # Write transaction  (debit debtors control, credit contra account)
            writetrans($dept['debtacc'], $accid, $date, $refnum, $amount, $details . " - Customer {$cust['cusname']} {$cust['surname']}");
            $tran = "\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>{$cust['accno']} - {$cust['cusname']} {$cust['surname']}</td>\n\t\t\t\t\t<td>{$acc['topacc']}/{$acc['accnum']} - {$acc['accname']}</td>\n\t\t\t\t</tr>";
            $samount = $amount;
            $svatamt = $vatamt;
            recordDT($samount, $cust['cusnum'], $date);
            $type = 'd';
            if (isset($chrgvat) and $chrgvat == "yes") {
                writetrans($dept['debtacc'], $vatacc, $date, $refnum, $vatamt, "VAT for Transaction: {$refnum} for Customer : {$cust['cusname']} {$cust['surname']}");
                vatr($vd['id'], $date, "OUTPUT", $vd['code'], $refnum, "VAT for Transaction: {$refnum} for Customer : {$cust['cusname']} {$cust['surname']}", $amount + $vatamt, $vatamt);
            }
        }
        db_connect();
        $sdate = date("Y-m-d");
        # record the payment on the statement
        $sql = "\n\t\t\tINSERT INTO stmnt (\n\t\t\t\tcusnum, invid, amount, date, type, st, div, allocation_date\n\t\t\t) VALUES (\n\t\t\t\t'{$cust['cusnum']}', '0', '" . sprint($samount + $svatamt) . "', '{$date}', '{$details}', 'n', '" . USER_DIV . "', '{$date}'\n\t\t\t)";
        $stmntRslt = db_exec($sql) or errDie("Unable to Insert statement record in Cubit.", SELF);
        $sql = "\n\t\t\tINSERT INTO open_stmnt (\n\t\t\t\tcusnum, invid, amount, balance, date, type, st, div\n\t\t\t) VALUES (\n\t\t\t\t'{$cust['cusnum']}', '0', '" . sprint($samount + $svatamt) . "', '" . sprint($samount + $svatamt) . "', '{$date}', '{$details}', 'n', '" . USER_DIV . "'\n\t\t\t)";
        $stmntRslt = db_exec($sql) or errDie("Unable to Insert statement record in Cubit.", SELF);
        # update the customer (make balance more)
        $sql = "UPDATE customers SET balance = (balance + '{$samount}') WHERE cusnum = '{$cust['cusnum']}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update customer in Cubit.", SELF);
        # Make ledge record
        //	custledger($cust['cusnum'], $accid, $date, $refnum, $details, $amount, $type);
        custledger($cust['cusnum'], $accid, $date, $refnum, $details, sprint($amount + $vatamt), $type);
        db_connect();
        $rem_batch = "DELETE FROM cust_trans_batch WHERE id = '{$procid}'";
        $run_batch = db_exec($rem_batch) or errDie("Unable to remove customer batch transaction information.");
        # Commit updates
        pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
    }
    return slctacc($_POST, "<li class='yay'>Transaction(s) Have Been Processed.</li><br>");
}
コード例 #5
0
function write($_POST)
{
    # processes
    db_connect();
    # Get vars
    extract($_POST);
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($bankid, "num", 1, 30, "Invalid Bank Account.");
    $v->isOk($date, "date", 1, 10, "Invalid Date Entry.");
    $v->isOk($descript, "string", 0, 255, "Invalid Description.");
    $v->isOk($cheqnum, "num", 0, 30, "Invalid Cheque number.");
    $v->isOk($amount, "float", 1, 10, "Invalid amount.");
    $v->isOk($cusid, "num", 1, 20, "Invalid customer account.");
    # Display errors, if any
    if ($v->isError()) {
        $confirm = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $confirm .= "<li class='err'>" . $e["msg"] . "</li>";
        }
        $confirm .= "<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $confirm;
    }
    # date format
    $date = explode("-", $date);
    $date = $date[2] . "-" . $date[1] . "-" . $date[0];
    $cheqnum = 0 + $cheqnum;
    core_connect();
    $sql = "SELECT * FROM bankacc WHERE accid = '{$bankid}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to retrieve bank account link from Cubit", SELF);
    # Check if link exists
    if (pg_numrows($rslt) < 1) {
        return "<li class='err'> ERROR : The bank account that you selected doesn't appear to have an account linked to it.</li>";
    }
    $bank = pg_fetch_array($rslt);
    # get account name
    $supRslt = get("cubit", "*", "customers", "cusnum", $cusid);
    $cus = pg_fetch_array($supRslt);
    db_conn("exten");
    # get debtors control account
    $sql = "SELECT debtacc FROM departments WHERE deptid ='{$cus['deptid']}' AND div = '" . USER_DIV . "'";
    $deptRslt = db_exec($sql);
    $dept = pg_fetch_array($deptRslt);
    db_connect();
    $Sl = "\n\t\tINSERT INTO stmnt \n\t\t\t(cusnum, invid, amount, date, type, div, allocation_date) \n\t\tVALUES \n\t\t\t('{$cusid}','0','{$amount}', '{$date}','{$descript}','" . USER_DIV . "', '{$date}')";
    $Rs = db_exec($Sl) or errDie("Unable to insert statement record in Cubit.", SELF);
    $Sl = "INSERT INTO open_stmnt (cusnum, invid, amount, date, type, div,balance) VALUES ('{$cusid}','0','{$amount}', '{$date}','{$descript}','" . USER_DIV . "','{$amount}')";
    $Rs = db_exec($Sl) or errDie("Unable to insert statement record in Cubit.", SELF);
    $sql = "UPDATE customers SET balance = (balance + '{$amount}') WHERE cusnum = '{$cus['cusnum']}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
    custledger($cusid, $bank['accnum'], $date, '0', "Payment to Customer", $amount, "d");
    custDT($amount, $cus['cusnum']);
    # record the payment record
    db_connect();
    $sql = "INSERT INTO cashbook(bankid, trantype, date, name, descript, cheqnum, amount, banked, accinv, suprec, div) VALUES ('{$bankid}', 'withdrawal', '{$date}', '{$cus['cusname']} {$cus['surname']}', '{$descript}', '{$cheqnum}', '{$amount}', 'no', '{$dept['debtacc']}', '{$cusid}', '" . USER_DIV . "')";
    $Rslt = db_exec($sql) or errDie("Unable to add bank payment to database.", SELF);
    $refnum = getrefnum();
    writetrans($dept['debtacc'], $bank['accnum'], $date, $refnum, $amount, $descript);
    # status report
    $write = "\n\t\t\t\t<table " . TMPL_tblDflts . " width='100%'>\n\t\t\t\t\t<tr>\n\t\t\t\t\t\t<th>Bank Payment</th>\n\t\t\t\t\t</tr>\n\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t<td>Bank Payment to customer : {$cus['surname']} added to cash book.</td>\n\t\t\t\t\t</tr>\n\t\t\t\t</table>\n\t\t\t";
    # main table (layout with menu)
    $OUTPUT = "\n\t\t\t\t<center>\n\t\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t\t<tr valign='top'>\n\t\t\t\t\t\t<td width='50%'>{$write}</td>\n\t\t\t\t\t\t<td align='center'>\n\t\t\t\t\t\t\t<table " . TMPL_tblDflts . " width='80%'>\n\t\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t\t<th>Quick Links</th>\n\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t\t<td><a href='bank-pay-add.php'>Add Bank Payment</a></td>\n\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t\t<td><a href='bank-recpt-add.php'>Add Bank Receipt</a></td>\n\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t\t<td><a href='cashbook-view.php'>View Cash Book</a></td>\n\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t</table>\n\t\t\t\t\t\t</td>\n\t\t\t\t\t</tr>\n\t\t\t\t</table>\n\t\t\t";
    return $OUTPUT;
}
コード例 #6
0
function write($_GET)
{
    $showvat = TRUE;
    # get vars
    extract($_GET);
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($invid, "num", 1, 20, "Invalid Invoice number.");
    $sndate = $ninv_year . "-" . $ninv_month . "-" . $ninv_day;
    if (!checkdate($ninv_month, $ninv_day, $ninv_year)) {
        $v->addError($sdate, "Invalid Date.");
    }
    $td = $sndate;
    foreach ($ids as $key => $id) {
        $v->isOk($id, "num", 1, 20, "Invalid Item number.");
        $v->isOk($qtys[$key], "float", 1, 20, "Invalid Item quantity.");
        $v->isOk($amts[$key], "float", 1, 20, "Invalid Item amount.");
    }
    $v->isOk($subtot, "float", 1, 20, "Invalid sub-total amount.");
    $v->isOk($vat, "float", 1, 20, "Invalid vat amount.");
    $v->isOk($total, "float", 1, 20, "Invalid total amount.");
    # display errors, if any
    if ($v->isError()) {
        $err = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $err .= "<li class='err'>" . $e["msg"] . "</li>";
        }
        $confirm .= "<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $confirm;
    }
    db_connect();
    # Get invoice info
    $sql = "SELECT * FROM hire.hire_nons_invoices WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
    $invRslt = db_exec($sql) or errDie("Unable to get invoice information");
    if (pg_numrows($invRslt) < 1) {
        return "<i class='err'>Not Found</i>";
    }
    $inv = pg_fetch_array($invRslt);
    db_conn("hire");
    $noteid = pglib_lastid("hire_nons_inv_notes", "noteid");
    $noteid++;
    # Begin updates
    pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
    /* --- Start Products Display --- */
    $refnum = getrefnum();
    /*refnum*/
    $real_noteid = divlastid('note', USER_DIV);
    $vattot = 0;
    $amttot = 0;
    db_connect();
    # Products layout
    $products = array();
    $i = 0;
    $page = 0;
    foreach ($ids as $key => $id) {
        if ($i >= 25) {
            $page++;
            $i = 0;
        }
        $sql = "SELECT * FROM hire.hire_nons_inv_items  WHERE invid = '{$invid}' AND id = '{$id}' AND div = '" . USER_DIV . "'";
        $stkdRslt = db_exec($sql);
        $stkd = pg_fetch_array($stkdRslt);
        db_conn('cubit');
        $Sl = "SELECT * FROM vatcodes WHERE id='{$stkd['vatex']}'";
        $Ri = db_exec($Sl) or errDie("Unable to get data.");
        $vd = pg_fetch_array($Ri);
        if (TAX_VAT != $vd['vat_amount'] and $vd['vat_amount'] != "0.00") {
            $showvat = FALSE;
        }
        $temp = $stkd['vatex'];
        if ($vd['zero'] == "Yes") {
            $stkd['vatex'] = "y";
        }
        $t = $inv['chrgvat'];
        //	$VATP = TAX_VAT;
        $VATP = $vd['vat_amount'];
        $stkacc = $stkd['accid'];
        # keep records for transactions
        if (isset($totstkamt[$stkacc])) {
            if ($stkd['vatex'] == "y") {
                $totstkamt[$stkacc] += $amts[$key];
                $va = 0;
                $inv['chrgvat'] = "";
            } else {
                $totstkamt[$stkacc] += vats($amts[$key], $inv['chrgvat'], $vd['vat_amount']);
                $va = sprint($stkd['amt'] - vats($amts[$key], $inv['chrgvat'], $vd['vat_amount']));
                if ($inv['chrgvat'] == "no") {
                    $va = sprint($amts[$key] * $VATP / 100);
                }
            }
        } else {
            if ($stkd['vatex'] == "y") {
                $totstkamt[$stkacc] = $amts[$key];
                $va = 0;
                $inv['chrgvat'] = "";
            } else {
                $totstkamt[$stkacc] = vats($amts[$key], $inv['chrgvat'], $vd['vat_amount']);
                $va = sprint($amts[$key] - vats($amts[$key], $inv['chrgvat'], $vd['vat_amount']));
                if ($inv['chrgvat'] == "no") {
                    $va = sprint($amts[$key] * $VATP / 100);
                }
            }
        }
        #add this entry's vat to a total
        $vattot = $vattot + $va;
        vatr($vd['id'], $td, "OUTPUT", $vd['code'], $refnum, "Non-Stock invoice No. {$inv['invnum']} Credit note No.{$real_noteid} Customer {$inv['cusname']}.", -vats($amts[$key], $inv['chrgvat'], $vd['vat_amount']) - $va, -$va);
        $inv['chrgvat'] = $t;
        $sql = "UPDATE hire.hire_nons_inv_items SET rqty = (rqty + '{$qtys[$key]}') WHERE id = '{$stkd['id']}'";
        $sRslt = db_exec($sql);
        if ($stkd['vatex'] == 'y') {
            $ex = "#";
        } else {
            $ex = "&nbsp;&nbsp;";
        }
        $stkd['vatex'] = $temp;
        #add this entry's amt to a total
        $amttot = $amttot + $amts[$key];
        $sql = "INSERT INTO hire.hire_nons_note_items(noteid, qty, description, amt, unitcost, vatcode) VALUES('{$noteid}', '{$qtys[$key]}', '{$stkd['description']}', '{$amts[$key]}', '{$stkd['unitcost']}', '{$stkd['vatex']}')";
        $stkdRslt = db_exec($sql);
        #the credit note entry will get any remark entered here ? so we dont update the invoice entry ...
        //	db_conn("cubit");
        //	$sql = "UPDATE nons_invoices SET remarks='$remarks' WHERE invid='$invid'";
        //	$rslt = db_exec($sql) or errDie("Unable to save the comments to Cubit.");
        $products[$page][] = "\r\n\t\t\t\t\t\t<tr valign='top'>\r\n\t\t\t\t\t\t\t<td style='border-right: 2px solid #000'>{$ex} {$stkd['description']}&nbsp;</td>\r\n\t\t\t\t\t\t\t<td style='border-right: 2px solid #000'>{$qtys[$key]}&nbsp;</td>\r\n\t\t\t\t\t\t\t<td style='border-right: 2px solid #000' align='right' nowrap>" . CUR . " {$stkd['unitcost']}&nbsp;</td>\r\n\t\t\t\t\t\t\t<td align='right' nowrap>" . CUR . " {$amts[$key]}&nbsp;</td>\r\n\t\t\t\t\t\t</tr>";
        $i++;
    }
    $blank_lines = 25;
    foreach ($products as $key => $val) {
        $bl = $blank_lines - count($products[$key]);
        for ($i = 0; $i <= $bl; $i++) {
            $products[$key][] = "\r\n\t\t\t\t \t\t\t<tr>\r\n\t\t\t\t \t\t\t\t<td style='border-right: 2px solid #000'>&nbsp;</td>\r\n\t\t\t\t \t\t\t\t<td style='border-right: 2px solid #000'>&nbsp;</td>\r\n\t\t\t\t \t\t\t\t<td style='border-right: 2px solid #000'>&nbsp;</td>\r\n\t\t\t\t \t\t\t\t<td>&nbsp;</td>\r\n\t\t\t\t \t\t\t</tr>";
        }
    }
    /* --- Start Some calculations --- */
    # Subtotal
    $SUBTOT = sprint($subtot);
    $VAT = sprint($vat);
    $TOTAL = sprint($total);
    /* --- End Some calculations --- */
    /* - Start Hooks - */
    $vatacc = gethook("accnum", "salesacc", "name", "VAT", "vat");
    $varacc = gethook("accnum", "salesacc", "name", "sales_variance");
    /* - End Hooks - */
    # todays date
    $date = date("d-m-Y");
    $sdate = date("Y-m-d");
    // print $inv['ctyp']; exit;
    db_connect();
    $tot_post = 0;
    # bank  % cust
    if ($inv['ctyp'] == 's') {
        $sql = "SELECT * FROM customers WHERE cusnum = '{$inv['cusid']}' AND div = '" . USER_DIV . "'";
        $custRslt = db_exec($sql) or errDie("Unable to view customer");
        $cus = pg_fetch_array($custRslt);
        # Get department
        db_conn("exten");
        $sql = "SELECT * FROM departments WHERE deptid = '{$cus['deptid']}' AND div = '" . USER_DIV . "'";
        $deptRslt = db_exec($sql);
        if (pg_numrows($deptRslt) < 1) {
            $dept['deptname'] = "<li class=err>Department not Found.";
        } else {
            $dept = pg_fetch_array($deptRslt);
        }
        $tpp = 0;
        # record transaction  from data
        foreach ($totstkamt as $stkacc => $wamt) {
            $tot_post += $wamt;
            writetrans($stkacc, $dept['debtacc'], $td, $refnum, $wamt, "Non-Stock invoice No. {$inv['invnum']} Credit note No.{$real_noteid} Customer {$inv['cusname']}.");
        }
        if ($VAT != 0) {
            $tot_post += $VAT;
            writetrans($vatacc, $dept['debtacc'], $td, $refnum, $VAT, "Non-Stock invoice No. {$inv['invnum']} Credit note No.{$real_noteid} VAT. Customer {$inv['cusname']}.");
        }
        $tot_dif = sprint($tot_post - $TOTAL);
        if ($tot_dif > 0) {
            writetrans($dept['debtacc'], $varacc, $td, $refnum, $tot_dif, "Sales Variance on Credit note No.{$real_noteid}");
        } elseif ($tot_dif < 0) {
            $tot_dif = $tot_dif * -1;
            writetrans($varacc, $dept['debtacc'], $td, $refnum, $tot_dif, "Sales Variance on Credit note No.{$real_noteid}");
        }
    } elseif ($inv['ctyp'] == 'b') {
        $dept['debtacc'] = getbankaccid($inv['accid']);
        $amounts = "";
        $accids = "";
        $vats = "";
        $chrgvats = "";
        $gamt = 0;
        # record transaction  from data
        foreach ($totstkamt as $stkacc => $wamt) {
            # Cook vars
            $amounts .= "|{$wamt}";
            $accids .= "|{$stkacc}";
            $vats .= "|0";
            $chrgvats .= "|no";
            # Debit Customer and Credit stock
            $tot_post += $wamt;
            writetrans($stkacc, $dept['debtacc'], $td, $refnum, $wamt, "Non-Stock invoice No. {$inv['invnum']} Credit note No.{$real_noteid}.");
        }
        # Debit bank and credit the account involved
        if ($VAT != 0) {
            # Cook vars
            $amounts .= "|{$VAT}";
            $accids .= "|{$vatacc}";
            $vats .= "|0";
            $chrgvats .= "|no";
            $tot_post += $VAT;
            writetrans($vatacc, $dept['debtacc'], $td, $refnum, $VAT, "Non-Stock invoice No. {$inv['invnum']} Credit note No.{$real_noteid} VAT.");
        }
    } else {
        $cusacc = $inv['accid'];
        $sdate = date("Y-m-d");
        # record transaction  from data
        foreach ($totstkamt as $stkacc => $wamt) {
            # Debit Customer and Credit stock
            $tot_post += $wamt;
            writetrans($stkacc, $cusacc, $td, $refnum, $wamt, "Non-Stock invoice No. {$inv['invnum']} Credit note No.{$real_noteid}.");
            pettyrec($cusacc, $td, "dt", "Non-Stock invoice No. {$inv['invnum']} Credit note No.{$real_noteid}.", $wamt, "Account Sale Credit note");
        }
        # Debit bank and credit the account involved
        $tot_post += $VAT;
        writetrans($vatacc, $cusacc, $td, $refnum, $VAT, "Non-Stock invoice No. {$inv['invnum']} Credit note No.{$real_noteid} VAT.");
        pettyrec($cusacc, $td, "dt", "Non-Stock invoice No. {$inv['invnum']} Credit note No.{$real_noteid} VAT.", $VAT, "Account Sale Credit note VAT");
        $tot_dif = sprint($tot_post - $TOTAL);
        if ($tot_dif > 0) {
            writetrans($cusacc, $varacc, $td, $refnum, $tot_dif, "Sales Variance on Credit note No.{$real_noteid}");
        } elseif ($tot_dif < 0) {
            $tot_dif = $tot_dif * -1;
            writetrans($varacc, $cusacc, $td, $refnum, $tot_dif, "Sales Variance on Credit note No.{$real_noteid}");
        }
    }
    $sdate = date("Y-m-d");
    db_connect();
    if ($inv['ctyp'] == 's') {
        # Record the payment on the statement
        $sql = "\r\n\t\t\tINSERT INTO stmnt \r\n\t\t\t\t(cusnum, invid, amount, date, type, div, allocation_date) \r\n\t\t\tVALUES \r\n\t\t\t\t('{$inv['cusid']}', '{$real_noteid}', '-{$TOTAL}','{$td}', 'Non Stock Credit Note, for invoice {$inv['invnum']}', '" . USER_DIV . "', '{$inv['odate']}')";
        $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
        # Update the customer (make balance less)
        $sql = "UPDATE customers SET balance = (balance - '{$TOTAL}'::numeric(13,2)) WHERE cusnum = '{$inv['cusid']}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
        # Update the customer (make balance less)
        $sql = "UPDATE open_stmnt SET balance = (balance - '{$TOTAL}'::numeric(13,2)) WHERE invid = '{$inv['invnum']}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
        # Make ledge record
        custledger($inv['cusid'], $stkacc, $td, $real_noteid, "Non Stock Credit note {$real_noteid}", $TOTAL, "c");
        #record entry for age analysis ...
        #this function seems a little ... broken
        //custfCT($TOTAL, $inv['cusid'], $inv['age']);
        #lets rather use the system wide function and send it the invoice transaction date to do the entry for that age
        custCT($TOTAL, $inv['cusid'], $inv['odate']);
    } elseif ($inv['ctyp'] == 'cb') {
        $date = date("Y-m-d");
        # Record the Receipt record
        db_connect();
        $sql = "INSERT INTO cashbook(bankid, trantype, date, name, descript, cheqnum, amount, banked, accids, amounts,  chrgvats, vats, div,accinv) VALUES ('{$inv['jobid']}', 'withdrawal', '{$td}', '{$inv['cusname']}', 'Nons Stock Credit note for invoice {$inv['invnum']}', '0', '{$TOTAL}', 'no', '', '0', '{$inv['chrgvat']}', '0', '" . USER_DIV . "','{$stkacc}')";
        die($sql);
        $Rslt = db_exec($sql) or errDie("Unable to add bank Receipt to database.", SELF);
    }
    db_connect();
    $sql = "UPDATE hire.hire_nons_invoices SET balance = (balance - '{$TOTAL}'::numeric(13,2)) WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
    $upRslt = db_exec($sql) or errDie("Unable to update invoice information");
    # write note
    $sql = "INSERT INTO hire.hire_nons_inv_notes(invid, invnum, cusname, cusaddr, cusvatno, chrgvat, date, subtot, vat, total, username, prd, notenum, ctyp, remarks, div)";
    $sql .= " VALUES('{$inv['invid']}', '{$inv['invnum']}', '{$inv['cusname']}', '{$inv['cusaddr']}', '{$inv['cusvatno']}', '{$inv['chrgvat']}', '{$td}', {$SUBTOT}, {$VAT}, {$TOTAL}, '" . USER_NAME . "', '" . PRD_DB . "', '{$real_noteid}', '{$inv['ctyp']}', '{$remarks}', '" . USER_DIV . "')";
    $rslt = db_exec($sql) or errDie("Unable to create template Non-Stock Invoice.", SELF);
    # write note items
    foreach ($ids as $key => $id) {
        $sql = "SELECT * FROM hire.hire_nons_inv_items  WHERE invid = '{$invid}' AND id = '{$id}' AND div = '" . USER_DIV . "'";
        $stkdRslt = db_exec($sql);
        $nstk = pg_fetch_array($stkdRslt);
    }
    $sql = "INSERT INTO salesrec(edate, invid, invnum, debtacc, vat, total, typ, div)\r\n\tVALUES('{$td}', '{$noteid}', '{$real_noteid}', '0', '{$VAT}', '{$TOTAL}', 'nnon', '" . USER_DIV . "')";
    $recRslt = db_exec($sql);
    $Sl = "INSERT INTO sj(cid,name,des,date,exl,vat,inc,div) VALUES\r\n\t('{$inv['cusid']}','{$inv['cusname']}','Credit Note: {$real_noteid}, Invoice {$inv['invnum']}','{$td}','" . -sprint($TOTAL - $VAT) . "','-{$VAT}','" . -sprint($TOTAL) . "','" . USER_DIV . "')";
    $Ri = db_exec($Sl);
    com_invoice($inv['salespn'], -($TOTAL - $VAT), 0, $inv['invnum'], $td);
    # Commit updates
    pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
    $cc = "<script> CostCenter('ct', 'Credit Note', '{$td}', 'Non Stock Credit Note No.{$real_noteid}', '" . ($TOTAL - $VAT) . "', ''); </script>";
    if (!isset($showvat)) {
        $showvat = TRUE;
    }
    if ($showvat == TRUE) {
        $vat14 = AT14;
    } else {
        $vat14 = "";
    }
    // Retrieve the company information
    db_conn("cubit");
    $sql = "SELECT * FROM compinfo";
    $comp_rslt = db_exec($sql) or errDie("Unable to retrieve company information from Cubit.");
    $comp_data = pg_fetch_array($comp_rslt);
    // Retrieve the banking information
    db_conn("cubit");
    $sql = "SELECT * FROM bankacct WHERE bankid='2' AND div='" . USER_DIV . "'";
    $bank_rslt = db_exec($sql) or errDie("Unable to retrieve bank information from Cubit.");
    $bank_data = pg_fetch_array($bank_rslt);
    // Retrieve customer information
    db_conn("cubit");
    $sql = "SELECT * FROM customers WHERE cusnum='{$inv['cusid']}'";
    $cust_rslt = db_exec($sql) or errDie("Unable to retrieve customer information from Cubit.");
    $cust_data = pg_fetch_array($cust_rslt);
    if ($inv['cusid'] == "0") {
        $cust_data['surname'] = $inv['cusname'];
        $cust_data['addr1'] = $inv['cusaddr'];
        $cust_data['paddr1'] = $inv['cusaddr'];
    }
    $table_borders = "\r\n\t\tborder-top: 2px solid #000000;\r\n\t\tborder-left: 2px solid #000000;\r\n\t\tborder-right: 2px solid #000000;\r\n\t\tborder-bottom: none;\r\n\t";
    // 	$nolr_borders = "
    // 		border-top: 2px solid #000;
    // 		border-left: none;
    // 		border-right: none;
    // 		border-bottom: none;
    // 	";
    $details = "";
    for ($i = 0; $i <= $page; $i++) {
        // new page?
        if ($i > 1) {
            $details .= "<br style='page-break-after:always;'>";
        }
        $products_out = "";
        foreach ($products[$i] as $string) {
            $products_out .= $string;
        }
        $vattot = sprint($vattot);
        $amttot = sprint($amttot);
        $details .= "<center>\r\n\t\t<table cellpadding='0' cellspacing='0' width='85%' style='{$table_borders}'>\r\n\t\t\t<tr><td>\r\n\t\t\t<table border='0' cellpadding='2' cellspacing='2' width='100%'>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td align='left' rowspan='2'><img src='compinfo/getimg.php' width=230 height=47></td>\r\n\t\t\t\t\t<td align='left' rowspan='2'><font size='5'><b>" . COMP_NAME . "</b></font></td>\r\n\t\t\t\t\t<td align='right'><font size='5'><b>Tax Credit Note</b></font></td>\r\n\t\t\t\t</tr>\r\n\t\t\t</table>\r\n\t\t\t</td></tr>\r\n\t\t</table>\r\n\r\n\t\t<table cellpadding='0' cellspacing='0' width='85%' style='{$table_borders}'>\r\n\t\t\t<tr><td valign='top'>\r\n\t\t\t<table cellpadding='2' cellspacing='0' border='0' width='100%'>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'>{$comp_data['addr1']}&nbsp;</td>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'>{$comp_data['paddr1']}&nbsp;</td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'>{$comp_data['addr2']}&nbsp;</td>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'>{$comp_data['paddr2']}&nbsp;</td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'>{$comp_data['addr3']}&nbsp;</td>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'>{$comp_data['paddr3']}&nbsp;</td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'>{$comp_data['addr4']}&nbsp;</td>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'>{$comp_data['postcode']}&nbsp;</td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>REG:</b> {$comp_data['regnum']}</b>&nbsp;</td>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>{$bank_data['bankname']}</b>&nbsp;</td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>VAT REG:</b> {$comp_data['vatnum']}&nbsp;</td>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Branch</b> {$bank_data['branchname']}&nbsp;</td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Tel:</b> {$comp_data['tel']}&nbsp;</td>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Branch Code:</b> {$bank_data['branchcode']}&nbsp;</td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Fax:</b> {$comp_data['fax']}&nbsp;</td>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Acc Num:</b> {$bank_data['accnum']}&nbsp;</td>\r\n\t\t\t\t</tr>\r\n\t\t\t</table>\r\n\t\t\t</td><td valign='top'>\r\n\t\t\t<table cellpadding='2' cellspacing='0' border='0' width='100%'>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Date</b></td>\r\n\t\t\t\t\t<td><b>Page Number</b></td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'>{$inv['odate']}</td>\r\n\t\t\t\t\t<td>" . ($i + 1) . "</td>\r\n\t\t\t\t</tr>\r\n\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-bottom: 2px solid #000; border-right: 2px solid #000'>&nbsp</td>\r\n\t\t\t\t\t<td style='border-bottom: 2px solid #000'>&nbsp</td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr><td>&nbsp</td></tr>\r\n\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td colspan='2'><b>Credit Note No:</b> {$real_noteid}</td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td colspan='2'><b>Invoice No:</b> {$inv['invnum']}</td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td colspan='2'><b>Proforma Inv No:</b> {$inv['docref']}</td>\r\n\t\t\t\t</tr>\r\n\t\t\t</table>\r\n\t\t\t</td></tr>\r\n\t\t</table>\r\n\r\n\t\t<table cellpadding='0' cellspacing='0' width='85%' style='{$table_borders}'>\r\n\t\t\t<tr><td>\r\n\t\t\t<table cellpadding='2' cellspacing='0' border='0' width='100%'>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td align='center'><font size='4'><b>Credit Note To:</b></font></td>\r\n\t\t\t\t</tr>\r\n\t\t\t</table>\r\n\t\t\t</td></tr>\r\n\t\t</table>\r\n\r\n\t\t<table cellpadding='0' cellspacing='0' width='85%' style='{$table_borders}'>\r\n\t\t\t<tr><td>\r\n\t\t\t<table cellpadding='2' cellspacing='0' border='0' width='100%'>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td width='33%' style='border-right: 2px solid #000'><b>{$cust_data['surname']}</b></td>\r\n\t\t\t\t\t<td width='33%' style='border-right: 2px solid #000'><b>Postal Address</b></td>\r\n\t\t\t\t\t<td width='33%'><b>Delivery Address</td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'>" . nl2br($cust_data["addr1"]) . "</td>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'>" . nl2br($cust_data["paddr1"]) . "</td>\r\n\t\t\t\t\t<td>&nbsp</td>\r\n\t\t\t\t</tr>\r\n\t\t\t</table>\r\n\t\t\t</td></tr>\r\n\t\t</table>\r\n\r\n\t\t<table cellpadding='0' cellspacing='0' width='85%' style='{$table_borders}'>\r\n\t\t\t<tr><td>\r\n\t\t\t<table cellpadding='2' cellspacing='0' border='0' width='100%'>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td width='33%' style='border-right: 2px solid #000'><b>Customer VAT No:</b> {$inv['cusvatno']}</td>\r\n\t\t\t\t\t<td width='33%'><b>Customer Order No:</b> {$inv['cordno']}</td>\r\n\t\t\t\t</tr>\r\n\t\t\t</table>\r\n\t\t\t</td></tr>\r\n\t\t</table>\r\n\r\n\t\t<table cellpadding='0' cellspacing='0' width='85%' style='{$table_borders}'>\r\n\t\t\t<tr><td>\r\n\t\t\t<table cellpadding='2' cellspacing='0' border='0' width='100%'>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-bottom: 2px solid #000; border-right: 2px solid #000'><b>Description</b></td>\r\n\t\t\t\t\t<td style='border-bottom: 2px solid #000; border-right: 2px solid #000'><b>Qty</b></td>\r\n\t\t\t\t\t<td style='border-bottom: 2px solid #000; border-right: 2px solid #000' align='right'><b>Unit Price</b></td>\r\n\t\t\t\t\t<td style='border-bottom: 2px solid #000;' align='right'><b>Amount</b></td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t{$products_out}\r\n\t\t\t</table>\r\n\t\t\t</td></tr>\r\n\t\t</table>\r\n\r\n\t\t<table cellpadding='0' cellspacing='0' width='85%' style='{$table_borders}'>\r\n\t\t\t<tr><td>\r\n\t\t\t<table cellpadding='2' cellspacing='0' border='0' width='100%'>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td><i>VAT Exempt Indicator: #</i></td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td>{$remarks}</td>\r\n\t\t\t\t</tr>\r\n\t\t\t</table>\r\n\t\t</table>\r\n\r\n\t\t<table cellpadding='0' cellspacing='0' width='85%' style='border: 2px solid #000000'>\r\n\t\t\t<tr><td>\r\n\t\t\t<table cellpadding='2' cellspacing='0' border='0' width='100%'>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Terms:</b> {$inv['terms']} days</b></td>\r\n\t\t\t\t\t<td><b>Subtotal:</b></td>\r\n\t\t\t\t\t<td nowrap><b>" . CUR . " {$SUBTOT}</b></td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'>&nbsp;</td>\r\n\t\t\t\t\t<td><b>VAT {$vat14}:</b></td>\r\n\t\t\t\t\t<td nowrap><b>" . CUR . " {$VAT}</b></td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Received in good order by:</b>_____________________</td>\r\n\t\t\t\t\t<td><b>Total Incl VAT:</b></td>\r\n\t\t\t\t\t<td nowrap><b>" . CUR . " {$TOTAL}</b></td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'>&nbsp;</td>\r\n\t\t\t\t<tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Date:</b>_____________________</td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t</tr>\r\n\t\t\t</table>\r\n\t\t</table>\r\n\t\t";
    }
    #fix teh date
    $date_arr = explode("-", $date);
    $cdate = "{$date_arr['2']}-{$date_arr['1']}-{$date_arr['0']}";
    // Retrieve template settings from Cubit
    db_conn("cubit");
    $sql = "SELECT filename FROM template_settings WHERE template='invoices'";
    $tsRslt = db_exec($sql) or errDie("Unable to retrieve the template settings from Cubit.");
    $template = pg_fetch_result($tsRslt, 0);
    if ($template == "invoice-print.php") {
        $OUTPUT = "\r\n\t\t\t<script>\r\n\t\t\t\tCostCenter('ct', 'Credit Note', '{$cdate}', 'Non Stock Credit Note No.{$real_noteid}', '" . ($TOTAL - $VAT) . "', '');\r\n\t\t\t</script>\r\n\t\t\t{$details}";
        require "tmpl-print.php";
    } else {
        $OUTPUT = "\r\n\t\t\t<script>\r\n\t\t\t\tCostCenter('ct', 'Credit Note', '{$cdate}', 'Non Stock Credit Note No.{$real_noteid}', '" . ($TOTAL - $VAT) . "', '');\r\n\t\t\t\tmove(\"{$template}?noteid={$noteid}&type=nonsnote\");\r\n\t\t\t</script>";
        require "template.php";
    }
}
コード例 #7
0
function write($_POST)
{
    extract($_POST);
    if (isset($back)) {
        unset($_POST["back"]);
        return alloc($_POST);
    }
    require_lib("validate");
    $v = new validate();
    $v->isOk($all, "num", 1, 1, "Invalid allocation.");
    $v->isOk($bankid, "num", 1, 30, "Invalid Bank Account.");
    $v->isOk($date, "date", 1, 14, "Invalid Date.");
    $v->isOk($out, "float", 1, 40, "Invalid out amount.");
    $v->isOk($descript, "string", 0, 255, "Invalid Description.");
    $v->isOk($reference, "string", 0, 50, "Invalid Reference Name/Number.");
    $v->isOk($cheqnum, "num", 0, 30, "Invalid Cheque number.");
    $v->isOk($amt, "float", 1, 40, "Invalid amount.");
    $v->isOk($setamt, "float", 1, 40, "Invalid Settlement Amount.");
    $v->isOk($setvat, "string", 1, 10, "Invalid Settlement VAT Option.");
    $v->isOk($setvatcode, "string", 1, 40, "Invalid Settlement VAT code");
    $v->isOk($cusid, "num", 1, 40, "Invalid customer number.");
    $v->isOk($out1, "float", 0, 40, "Invalid paid amount(current).");
    $v->isOk($out2, "float", 0, 40, "Invalid paid amount(30).");
    $v->isOk($out3, "float", 0, 40, "Invalid paid amount(60).");
    $v->isOk($out4, "float", 0, 40, "Invalid paid amount(90).");
    $v->isOk($out5, "float", 0, 40, "Invalid paid amount(120).");
    $v->isOk($overpay, "float", 1, 20, "Invalid Overpay Amount.");
    if (isset($invids)) {
        foreach ($invids as $key => $value) {
            $v->isOk($invids[$key], "num", 1, 50, "Invalid Invoice No.");
            $v->isOk($paidamt[$key], "float", 1, 40, "Invalid amount to be paid.");
            $v->isOk($stock_setamt[$key], "float", 1, 40, "Invalid Settlement Discount Amount");
        }
    }
    if ($v->isError()) {
        $confirm = $v->genErrors();
        return $confirm . confirm($_POST);
    }
    /* get bank account id of cash on hand account IF this entry is cash */
    if (($bank_acc = getbankaccid($bankid)) === false or $bankid == "0") {
        //old function didnt check if cash is selected ... if(($bank_acc = getbankaccid($bankid)) === false) {
        $sql = "SELECT accid FROM core.accounts WHERE accname='Cash on Hand'";
        $rslt = db_exec($sql);
        if (pg_num_rows($rslt) < 1) {
            if ($bankid == 0) {
                return "There is no 'Cash on Hand' account, there was one, but\n\t\t\t\t\t**s not there now, you must have deleted it, if you want\n\t\t\t\t\tto use cash functionality please create a 'Cash on Hand' account.";
            } else {
                return "Invalid bank acc.";
            }
        }
        $bank_acc = pg_fetch_result($rslt, 0);
    }
    $cus = qryCustomer($cusid, "cusnum, deptid, cusname, surname");
    $dept = qryDepartment($cus["deptid"], "debtacc");
    $refnum = getrefnum();
    pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
    # date format
    $sdate = explode("-", $date);
    $_SESSION["global_day"] = $sdate[2];
    $_SESSION["global_month"] = $sdate[1];
    $_SESSION["global_year"] = $sdate[0];
    //	$sdate = $sdate[2]."-".$sdate[1]."-".$sdate[0];
    $sdate = "{$date_year}-{$date_month}-{$date_day}";
    $cheqnum = 0 + $cheqnum;
    $pay = "";
    $accdate = $sdate;
    //	$accdate = "$date_year-$date_month-$date_day";
    /* Paid invoices */
    $invidsers = "";
    $rinvids = "";
    $amounts = "";
    $invprds = "";
    $rages = "";
    $setamts = "";
    #get settlement accid
    $get_setacc = "SELECT accid FROM accounts WHERE accname = 'Debtors Settlement Discount'";
    $run_setacc = db_exec($get_setacc) or errDie("Unable to get settlement account information");
    $setaccid = pg_fetch_result($run_setacc, 0, 0);
    $vatacc = gethook("accnum", "salesacc", "name", "VAT", "VAT");
    $amt += $overpay;
    /* OPTION 3 : ALLOCATE TO EACH INVOICE (confirm) */
    if ($all == 2) {
        $sql = "UPDATE cubit.customers SET balance = (balance - '{$amt}'::numeric(16,2)) WHERE cusnum = '{$cus['cusnum']}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
        if (isset($invids)) {
            foreach ($invids as $key => $value) {
                $ii = $invids[$key];
                # some logic ...
                # because the customer account should be 0 when paid fully, we need
                # to also deduct the settlement amount ...
                $paidamt[$key] = $paidamt[$key] + $stock_setamt[$key];
                # with the amount added to the paid amount, we tract it using a new
                # seperate setamt db column
                if (!isset($itype[$key]) && !isset($ptype[$key])) {
                    $sql = "SELECT prd,invnum,odate FROM cubit.invoices WHERE invid ='{$invids[$key]}' AND div = '" . USER_DIV . "'";
                    $invRslt = db_exec($sql) or errDie("Unable to retrieve invoice details from database.");
                    if (pg_numrows($invRslt) < 1) {
                        return "<li class='err'>Invalid Invoice Number.</li>";
                    }
                    $inv = pg_fetch_array($invRslt);
                    // reduce invoice balance
                    $sql = "\n\t\t\t\t\t\tUPDATE cubit.invoices\n\t\t\t\t\t\tSET balance = (balance - {$paidamt[$key]}::numeric(16,2))\n\t\t\t\t\t\tWHERE invid = '{$invids[$key]}' AND div = '" . USER_DIV . "'";
                    $payRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
                    $sql = "\n\t\t\t\t\t\tUPDATE cubit.open_stmnt\n\t\t\t\t\t\tSET balance = (balance - {$paidamt[$key]}::numeric(16,2))\n\t\t\t\t\t\tWHERE invid = '{$inv['invnum']}' AND div = '" . USER_DIV . "'";
                    $payRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
                    # record the payment on the statement
                    $sql = "\n\t\t\t\t\t\tINSERT INTO cubit.stmnt (\n\t\t\t\t\t\t\tcusnum, invid, \n\t\t\t\t\t\t\tamount, date, type, div, allocation_date, docref, \n\t\t\t\t\t\t\tallocation_balance\n\t\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t\t'{$cus['cusnum']}', '{$inv['invnum']}', \n\t\t\t\t\t\t\t'" . ($paidamt[$key] - $stock_setamt[$key] - ($paidamt[$key] - $stock_setamt[$key]) * 2) . "', \n\t\t\t\t\t\t\t'{$sdate}', 'Payment for Invoice No. {$inv['invnum']}', '" . USER_DIV . "', '{$inv['odate']}', '{$reference}', \n\t\t\t\t\t\t\t'" . abs($paidamt[$key] - $stock_setamt[$key] - ($paidamt[$key] - $stock_setamt[$key]) * 2) . "'\n\t\t\t\t\t\t)";
                    $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
                    #record the settlement discount on the statement
                    if ($stock_setamt[$key] > 0) {
                        $sql = "\n\t\t\t\t\t\t\tINSERT INTO cubit.stmnt (\n\t\t\t\t\t\t\t\tcusnum, invid, amount, \n\t\t\t\t\t\t\t\tdate, type, \n\t\t\t\t\t\t\t\tdiv, allocation_date, docref, allocation_balance\n\t\t\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t\t\t'{$cus['cusnum']}', '{$inv['invnum']}', '" . ($stock_setamt[$key] - $stock_setamt[$key] * 2) . "', \n\t\t\t\t\t\t\t\t'{$sdate}', 'Settlement Discount for Invoice No.{$inv['invnum']} Ref. {$refnum}', \n\t\t\t\t\t\t\t\t'" . USER_DIV . "', '{$inv['odate']}', '{$reference}', '" . abs($stock_setamt[$key] - $stock_setamt[$key] * 2) . "'\n\t\t\t\t\t\t\t)";
                        $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
                    }
                    #deduct setamt for records ...
                    custledger($cus['cusnum'], $bank_acc, $sdate, $inv['invnum'], "Payment for Invoice No. {$inv['invnum']}", $paidamt[$key] - $stock_setamt[$key], "c");
                    db_connect();
                    $rinvids .= "|{$invids[$key]}";
                    $amounts .= "|{$paidamt[$key]}";
                    if ($inv['prd'] == "0") {
                        $inv['prd'] = PRD_DB;
                    }
                    $invprds .= "|{$inv['prd']}";
                    $rages .= "|0";
                    $invidsers .= " - {$inv['invnum']}";
                    $setamts .= "|{$stock_setamt[$key]}";
                } elseif (!isset($ptype[$key])) {
                    $sql = "\n\t\t\t\t\t\tSELECT prd,invnum,descrip,age,odate \n\t\t\t\t\t\tFROM cubit.nons_invoices \n\t\t\t\t\t\tWHERE invid ='{$invids[$key]}' AND div = '" . USER_DIV . "'";
                    $invRslt = db_exec($sql) or errDie("Unable to retrieve invoice details from database.");
                    if (pg_numrows($invRslt) < 1) {
                        return "<li class='err'>Invalid Invoice Number.</li>";
                    }
                    $inv = pg_fetch_array($invRslt);
                    // reduce the invoice balance
                    $sql = "\n\t\t\t\t\t\tUPDATE cubit.nons_invoices \n\t\t\t\t\t\tSET balance = (balance - {$paidamt[$key]}::numeric(16,2)) \n\t\t\t\t\t\tWHERE invid = '{$invids[$key]}' AND div = '" . USER_DIV . "'";
                    $payRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
                    $sql = "\n\t\t\t\t\t\tUPDATE cubit.open_stmnt \n\t\t\t\t\t\tSET balance = (balance - {$paidamt[$key]}::numeric(16,2)) \n\t\t\t\t\t\tWHERE invid = '{$inv['invnum']}' AND div = '" . USER_DIV . "'";
                    $payRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
                    if (!isset($inv['odate']) or strlen($inv['odate']) < 1) {
                        $inv['odate'] = $sdate;
                    }
                    // add payment to statement
                    $sql = "\n\t\t\t\t\t\tINSERT INTO cubit.stmnt (\n\t\t\t\t\t\t\tcusnum, invid, \n\t\t\t\t\t\t\tamount, \n\t\t\t\t\t\t\tdate, type, \n\t\t\t\t\t\t\tdiv, allocation_date, docref, allocation_balance\n\t\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t\t'{$cus['cusnum']}', '{$inv['invnum']}', \n\t\t\t\t\t\t\t'" . ($paidamt[$key] - $stock_setamt[$key] - ($paidamt[$key] - $stock_setamt[$key]) * 2) . "', \n\t\t\t\t\t\t\t'{$sdate}', 'Payment for Non Stock Invoice No. {$inv['invnum']} - {$inv['descrip']}', \n\t\t\t\t\t\t\t'" . USER_DIV . "', '{$inv['odate']}', '{$reference}', '" . abs($paidamt[$key] - $stock_setamt[$key] - ($paidamt[$key] - $stock_setamt[$key]) * 2) . "'\n\t\t\t\t\t\t)";
                    $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
                    #record the settlement discount on the statement
                    if ($stock_setamt[$key] > 0) {
                        $sql = "\n\t\t\t\t\t\t\tINSERT INTO cubit.stmnt (\n\t\t\t\t\t\t\t\tcusnum, invid, amount, \n\t\t\t\t\t\t\t\tdate, type, \n\t\t\t\t\t\t\t\tdiv, allocation_date, docref, allocation_balance\n\t\t\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t\t\t'{$cus['cusnum']}', '{$inv['invnum']}', '" . ($stock_setamt[$key] - $stock_setamt[$key] * 2) . "', \n\t\t\t\t\t\t\t\t'{$sdate}', 'Settlement Discount for Invoice No.{$inv['invnum']} Ref. {$refnum}', \n\t\t\t\t\t\t\t\t'" . USER_DIV . "', '{$inv['odate']}', '{$reference}', '" . abs($stock_setamt[$key] - $stock_setamt[$key] * 2) . "'\n\t\t\t\t\t\t\t)";
                        $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
                    }
                    custledger($cus['cusnum'], $bank_acc, $sdate, $inv['invnum'], "Payment for Non Stock Invoice No. {$inv['invnum']} - {$inv['descrip']}", $paidamt[$key], "c");
                    db_connect();
                    //recordCT($paidamt[$key], $cus['cusnum'],$inv['age'],$accdate);
                    $rinvids .= "|{$invids[$key]}";
                    $amounts .= "|{$paidamt[$key]}";
                    $invprds .= "|0";
                    $rages .= "|{$inv['age']}";
                    $invidsers .= " - {$inv['invnum']}";
                    $setamts .= "|{$stock_setamt[$key]}";
                } else {
                    /* pos invoices */
                    $sqls = array();
                    for ($i = 1; $i <= 12; ++$i) {
                        $sqls[] = "\n\t\t\t\t\t\t\tSELECT '{$i}' AS prd,invid,invnum,odate \n\t\t\t\t\t\t\tFROM \"{$i}\".pinvoices \n\t\t\t\t\t\t\tWHERE invid='{$invids[$key]}' AND div='" . USER_DIV . "'";
                    }
                    $sql = implode(" UNION ", $sqls);
                    $invRslt = db_exec($sql) or errDie("Unable to retrieve invoice details from database.");
                    if (pg_numrows($invRslt) < 1) {
                        return "<li class='err'>Invalid Invoice Number.</li>";
                    }
                    $inv = pg_fetch_array($invRslt);
                    // reduce the invoice balance
                    $sql = "\n\t\t\t\t\t\tUPDATE \"{$inv['prd']}\".pinvoices \n\t\t\t\t\t\tSET balance = (balance - {$paidamt[$key]}::numeric(16,2)) \n\t\t\t\t\t\tWHERE invid = '{$invids[$key]}' AND div = '" . USER_DIV . "'";
                    $payRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
                    $sql = "\n\t\t\t\t\t\tUPDATE cubit.open_stmnt \n\t\t\t\t\t\tSET balance = (balance - {$paidamt[$key]}::numeric(16,2)) \n\t\t\t\t\t\tWHERE invid = '{$inv['invnum']}' AND div = '" . USER_DIV . "'";
                    $payRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
                    // add payment to statement
                    $sql = "\n\t\t\t\t\t\tINSERT INTO cubit.stmnt (\n\t\t\t\t\t\t\tcusnum, invid, amount, date, \n\t\t\t\t\t\t\ttype, div, \n\t\t\t\t\t\t\tallocation_date, docref, allocation_balance\n\t\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t\t'{$cus['cusnum']}', '{$inv['invnum']}', '" . ($paidamt[$key] - $stock_setamt[$key]) * -1 . "', '{$sdate}', \n\t\t\t\t\t\t\t'Payment for POS Invoice No. {$inv['invnum']}', '" . USER_DIV . "', \n\t\t\t\t\t\t\t'{$inv['odate']}', '{$reference}', '" . abs(($paidamt[$key] - $stock_setamt[$key]) * -1) . "'\n\t\t\t\t\t\t)";
                    $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
                    #record the settlement discount on the statement
                    if ($stock_setamt[$key] > 0) {
                        $sql = "\n\t\t\t\t\t\t\tINSERT INTO cubit.stmnt (\n\t\t\t\t\t\t\t\tcusnum, invid, \n\t\t\t\t\t\t\t\tamount, date, \n\t\t\t\t\t\t\t\ttype, \n\t\t\t\t\t\t\t\tdiv, allocation_date, docref, allocation_balance\n\t\t\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t\t\t'{$cus['cusnum']}', '{$inv['invnum']}', \n\t\t\t\t\t\t\t\t'" . ($stock_setamt[$key] - $stock_setamt[$key] * 2) . "', '{$sdate}', \n\t\t\t\t\t\t\t\t'Settlement Discount for Invoice No.{$inv['invnum']} Ref. {$refnum}', \n\t\t\t\t\t\t\t\t'" . USER_DIV . "', '{$inv['odate']}', '{$reference}', '" . abs($stock_setamt[$key] - $stock_setamt[$key] * 2) . "'\n\t\t\t\t\t\t\t)";
                        $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
                    }
                    custledger($cus['cusnum'], $bank_acc, $sdate, $inv['invnum'], "Payment for POS Invoice No. {$inv['invnum']}", $paidamt[$key], "c");
                    //recordCT($paidamt[$key], $cus['cusnum'],"0",$accdate);
                    $rinvids .= "|{$invids[$key]}";
                    $amounts .= "|{$paidamt[$key]}";
                    $invprds .= "|{$inv['prd']}";
                    $rages .= "|0";
                    $invidsers .= " - {$inv['invnum']}";
                    $setamts .= "|{$stock_setamt[$key]}";
                }
            }
        }
        if (open()) {
            db_conn('cubit');
            $Sl = "SELECT * FROM cubit.open_stmnt WHERE balance>0 AND cusnum='{$cusid}' ORDER BY date";
            $Ri = db_exec($Sl) or errDie("Unable to get open items.");
            //$open_out=$out;
            $ox = "";
            $i = 0;
            while ($od = pg_fetch_array($Ri)) {
                $oid = $od['id'];
                if (!isset($open_amount[$oid]) || $open_amount[$oid] == 0) {
                    continue;
                }
                $ox .= "\n\t\t\t\t\t<input type='hidden' size='20' name='open[{$oid}]' value='{$oid}'>\n\t\t\t\t\t<input type='hidden' name='open_amount[{$oid}]' value='{$open_amount[$oid]}'>\n\t\t\t\t\t<tr bgcolor='" . bgcolor($i) . "'>\n\t\t\t\t\t\t<td>{$od['type']}</td>\n\t\t\t\t\t\t<td>" . CUR . " {$od['balance']}</td>\n\t\t\t\t\t\t<td>{$od['date']}</td>\n\t\t\t\t\t\t<td>" . CUR . " {$open_amount[$oid]}</td>\n\t\t\t\t\t</tr>";
                $sql = "\n\t\t\t\t\tUPDATE cubit.open_stmnt \n\t\t\t\t\tSET balance = (balance - {$open_amount[$oid]} ::numeric(16,2)) \n\t\t\t\t\tWHERE id = '{$oid}' AND div = '" . USER_DIV . "'";
                $payRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
                // record the payment on the statement
                $sql = "\n\t\t\t\t\tINSERT INTO cubit.stmnt (\n\t\t\t\t\t\tcusnum, invid, amount, date, \n\t\t\t\t\t\ttype, div, allocation_date, docref, allocation_balance\n\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t'{$cus['cusnum']}', '0', '" . -$open_amount[$oid] . "', '{$sdate}', \n\t\t\t\t\t\t'Payment received', '" . USER_DIV . "', '{$accdate}', '{$reference}', '" . abs($open_amount[$oid]) . "'\n\t\t\t\t\t)";
                $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
                custledger($cus['cusnum'], $bank_acc, $sdate, 0, "Payment received", $open_amount[$oid], "c");
                recordCT($open_amount[$oid], $cus['cusnum'], 0, $accdate);
            }
        }
        // record the payment record
        $cols = grp(m("bankid", $bankid), m("trantype", "deposit"), m("date", $sdate), m("name", "{$cus['cusname']} {$cus['surname']}"), m("descript", "Payment for Invoices {$invidsers} from customer {$cus['cusname']} {$cus['surname']}"), m("cheqnum", $cheqnum), m("amount", $amt), m("banked", "no"), m("accinv", $dept["debtacc"]), m("cusnum", $cus["cusnum"]), m("rinvids", $rinvids), m("amounts", $amounts), m("invprds", $invprds), m("rages", $rages), m("reference", $reference), m("div", USER_DIV));
        $dbobj = new dbUpdate("cashbook", "cubit", $cols);
        $dbobj->run(DB_INSERT);
        $dbobj->free();
        $cashbook_id = pglib_lastid("cashbook", "cashid");
        writetrans($bank_acc, $dept['debtacc'], $accdate, $refnum, $amt, "Payment for Invoices {$invidsers} from customer {$cus['cusname']} {$cus['surname']}");
    }
    /* start moving invoices */
    // move invoices that are fully paid
    $sql = "SELECT * FROM cubit.invoices WHERE balance='0' AND printed = 'y' AND done = 'y' AND div = '" . USER_DIV . "'";
    $invbRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
    while ($x = pg_fetch_array($invbRslt)) {
        if (($prd = $x['prd']) == "0") {
            $prd = PRD_DB;
        }
        // move invoice
        $cols = grp(m("invid", $x["invid"]), m("invnum", $x["invnum"]), m("deptid", $x["deptid"]), m("cusnum", $x["cusnum"]), m("deptname", $x["deptname"]), m("cusacc", $x["cusacc"]), m("cusname", $x["cusname"]), m("surname", $x["surname"]), m("cusaddr", $x["cusaddr"]), m("cusvatno", $x["cusvatno"]), m("cordno", $x["cordno"]), m("ordno", $x["ordno"]), m("chrgvat", $x["chrgvat"]), m("terms", $x["terms"]), m("traddisc", $x["traddisc"]), m("salespn", $x["salespn"]), m("odate", $x["odate"]), m("delchrg", $x["delchrg"]), m("subtot", $x["subtot"]), m("vat", $x["vat"]), m("total", $x["total"]), m("age", $x["age"]), m("comm", $x["comm"]), m("discount", $x["discount"]), m("delivery", $x["delivery"]), m("docref", $x["docref"]), m("prd", $x["prd"]), m("delvat", $x["delvat"]), m("balance", 0), m("printed", "y"), m("done", "y"), m("username", USER_NAME), m("div", USER_DIV));
        $dbobj = new dbUpdate("invoices", $prd, $cols);
        $dbobj->run(DB_INSERT);
        $dbobj->free();
        // record movement
        $cols = grp(m("invtype", "inv"), m("invnum", $x["invnum"]), m("prd", $x["prd"]), m("docref", $x["docref"]), m("div", USER_DIV));
        $dbobj->setTable("movinv", "cubit");
        $dbobj->setOpt($cols);
        $dbobj->run();
        $dbobj->free();
        // move invoice items
        $inv_items = new dbSelect("inv_items", "cubit", grp(m("where", wgrp(m("invid", $x["invid"]), m("div", USER_DIV)))));
        $inv_items->run();
        while ($xi = $inv_items->fetch_array()) {
            $xi['vatcode'] += 0;
            $xi['account'] += 0;
            $xi['del'] += 0;
            $cols = grp(m("invid", $x["invid"]), m("whid", $xi["whid"]), m("stkid", $xi["stkid"]), m("qty", $xi["qty"]), m("unitcost", $xi["unitcost"]), m("amt", $xi["amt"]), m("disc", $xi["disc"]), m("discp", $xi["discp"]), m("vatcode", $xi["vatcode"]), m("account", $xi["account"]), m("description", $xi["description"]), m("del", $xi["del"]), m("noted", $xi["noted"]), m("serno", $xi["serno"]), m("div", USER_DIV));
            $dbobj->setTable("inv_items", $prd);
            $dbobj->setOpt($cols);
            $dbobj->run();
            $dbobj->free();
        }
        /* remove invoice from cubit schema */
        $dbobj = new dbDelete("invoices", "cubit", wgrp(m("invid", $x["invid"]), m("div", USER_DIV)));
        $dbobj->run();
        $dbobj->setTable("inv_items", "cubit");
        $dbobj->run();
    }
    #do journal for the settlement discount here ... now ...
    if ($setamt > 0) {
        db_conn('core');
        #calculate the settlement vat ... and amt
        if (isset($setvat) and $setvat == 'inc') {
            db_connect();
            $get_vcode = "SELECT * FROM vatcodes WHERE id = '{$setvatcode}' LIMIT 1";
            $run_vcode = db_exec($get_vcode) or errDie("Unable to get vatcode informtion.");
            if (pg_numrows($run_vcode) < 1) {
                return "<li class='err'>Settlement Discount VAT Code Not Set.</li>";
            }
            $vd = pg_fetch_array($run_vcode);
            #vat inc ... recalculate the amts
            $setvatamt = sprint($setamt * ($vd['vat_amount'] / (100 + $vd['vat_amount'])));
            $setamt = sprint($setamt - $setvatamt);
            #process the vat amt ...
            writetrans($vatacc, $dept['debtacc'], $accdate, $refnum, $setvatamt, "VAT Received on Settlement Discount (Ref.{$refnum}) for Customer : {$cus['cusname']} {$cus['surname']}");
            vatr($vd['id'], $accdate, "OUTPUT", $vd['code'], $refnum, "VAT for Settlement Discount (Ref.{$refnum}) for Customer : {$cus['cusname']} {$cus['surname']}", ($setamt + $setvatamt) * -1, $setvatamt * -1);
        } else {
            #no vat for set amt ... do nothing
            $setvatamt = 0;
        }
        custledger($cus['cusnum'], $setaccid, $accdate, $refnum, "Settlement Discount (Ref.{$refnum})", $setamt + $setvatamt, "c");
        writetrans($setaccid, $dept['debtacc'], $accdate, $refnum, $setamt, "Settlement Discount (Ref.{$refnum}) For {$cus['cusname']} {$cus['surname']}");
        db_connect();
        #record this paid settlement discount for reporting ...
        $settl_sql = "\n\t\t\tINSERT INTO settlement_cus (\n\t\t\t\tcustomer, amt, setamt, setvatamt, setvat, setvatcode, tdate, sdate, refnum\n\t\t\t) VALUES (\n\t\t\t\t'{$cus['cusnum']}', '{$amt}', '{$setamt}', '{$setvatamt}', '{$setvat}', '{$setvatcode}', '{$accdate}', 'now', '{$refnum}'\n\t\t\t)";
        $run_settl = db_exec($settl_sql) or errDie("Unable to get debtor settlement information.");
    }
    //	$overpay = sprint ($amt - array_sum($paidamt));
    if (!isset($overpay) or $overpay < 0) {
        $overpay = 0.0;
    }
    if ($overpay > 0) {
        recordCT($overpay, $cus['cusnum'], 0, $accdate);
        $cols = grp(m("cusnum", $cus["cusnum"]), m("invid", 0), m("amount", -$overpay), m("date", $sdate), m("type", "Payment Received (Receipt " . pglib_lastid("cashbook", "cashid") . ")"), m("div", USER_DIV), m("allocation_date", $accdate), m("docref", $reference));
        $dbobj = new dbUpdate("stmnt", "cubit", $cols);
        $dbobj->run(DB_INSERT);
        $dbobj->free();
        custledger($cus['cusnum'], $bank_acc, $sdate, "PAYMENT", "Payment received.", $overpay, "c");
    }
    pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
    // status report
    //	$write = "
    //				<table ".TMPL_tblDflts." width='100%'>
    //					<tr>
    //						<th>Bank Receipt</th>
    //					</tr>
    //					<tr class='".bg_class()."'>
    //						<td>Bank Receipt added to cash book.</td>
    //					</tr>
    //				</table>
    //			";
    //
    //	$OUTPUT = "<center>
    //        <table width='90%'>
    //        <tr valign='top'>
    //        	<td width='50%'>$write</td>
    //	        <td align='center'>"
    //				.mkQuickLinks(
    //					ql("bank-pay-add.php", "Add Bank Payment"),
    //					ql("bank-recpt-add.php", "Add Bank Receipt"),
    //					ql("bank-recpt-inv.php", "Add Customer Payment"),
    //					ql("cashbook-view.php", "View Cash Book")
    //				)."
    //			</td>
    //		</tr>
    //		</table>";
    //	return $OUTPUT;
    if (isset($print_recpt) and $print_recpt == "yes") {
        $showreceipt = "printer ('bank/bank-recpt-inv-print.php?recid={$cashbook_id}');";
    } else {
        $showreceipt = "";
    }
    return "\n\t\t<script>\n\t\t\tmove ('../customers-view.php?offset=0&fval=&filter=surname&nozerobal=yes');\n\t\t\t{$showreceipt}\n\t\t</script>";
}
コード例 #8
0
function cwrite($_GET)
{
    # get vars
    extract($_GET);
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($invid, "num", 1, 20, "Invalid invoice number.");
    $v->isOk($cusnum, "num", 1, 20, "Invalid customer number.");
    if (isset($stkaccs)) {
        foreach ($stkaccs as $key => $accid) {
            $v->isOk($accid, "num", 1, 20, "Invalid Item Account number.");
        }
    } else {
        $v->isOk($invid, "num", 0, 0, "Invalid Item Account number.");
    }
    # display errors, if any
    if ($v->isError()) {
        $err = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $err .= "<li class='err'>" . $e["msg"] . "</li>";
        }
        $confirm .= "<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $confirm;
    }
    db_connect();
    # Get invoice info
    $sql = "SELECT * FROM nons_invoices WHERE invid = '{$invid}' AND div = '" . USER_DIV . "' and done='n'";
    $invRslt = db_exec($sql) or errDie("Unable to get invoice information");
    if (pg_numrows($invRslt) < 1) {
        return "<i class='err'>Not Found</i>";
    }
    $inv = pg_fetch_array($invRslt);
    # CHECK IF THIS DATE IS IN THE BLOCKED RANGE
    $blocked_date_from = getCSetting("BLOCKED_FROM");
    $blocked_date_to = getCSetting("BLOCKED_TO");
    if (strtotime($inv['odate']) >= strtotime($blocked_date_from) and strtotime($inv['odate']) <= strtotime($blocked_date_to) and !user_is_admin(USER_ID)) {
        return "<li class='err'>Period Range Is Blocked. Only an administrator can process entries within this period.</li>";
    }
    $td = $inv['sdate'];
    $currs = getSymbol($inv['fcid']);
    # Update xrate
    cus_xrate_update($inv['fcid'], $inv['xrate']);
    xrate_update($inv['fcid'], $inv['xrate'], "invoices", "invid");
    xrate_update($inv['fcid'], $inv['xrate'], "custran", "id");
    db_connect();
    # cust
    $sql = "SELECT * FROM customers WHERE cusnum = '{$cusnum}' AND div = '" . USER_DIV . "'";
    $custRslt = db_exec($sql) or errDie("Unable to view customer");
    $cus = pg_fetch_array($custRslt);
    $details = "\n\t<tr><td>{$cus['surname']}</td></tr>\n\t<tr><td>" . nl2br($cus['addr1']) . "</td></tr>\n\t<tr><td>{$cus['vatnum']}</td></tr>";
    $na = $cus['surname'];
    # Begin updates
    pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
    /* --- Start Products Display --- */
    # Products layout
    $products = "";
    $disc = 0;
    # get selected stock in this invoice
    db_connect();
    $sql = "SELECT * FROM nons_inv_items  WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
    $stkdRslt = db_exec($sql);
    $refnum = getrefnum();
    /*refnum*/
    /* - Start Hooks - */
    $vatacc = gethook("accnum", "salesacc", "name", "VAT", "non");
    /* - End Hooks - */
    $real_invid = divlastid('inv', USER_DIV);
    db_connect();
    # Put in product
    while ($stk = pg_fetch_array($stkdRslt)) {
        $stkacc = $stkaccs[$stk['id']];
        # keep records for transactions
        // 		if(isset($totstkamt[$stkacc])){
        // 			$totstkamt[$stkacc] += vats($stk['amt'], $inv['chrgvat']);
        // 		}else{
        // 			$totstkamt[$stkacc] = vats($stk['amt'], $inv['chrgvat']);
        // 		}
        $Sl = "SELECT * FROM vatcodes WHERE id='{$stk['vatex']}'";
        $Ri = db_exec($Sl) or errDie("Unable to get data.");
        $vd = pg_fetch_array($Ri);
        if ($vd['zero'] == "Yes") {
            $stk['vatex'] = "y";
        }
        //print $inv['chrgvat'];exit;
        $t = $inv['chrgvat'];
        $VATP = $vd['vat_amount'];
        # keep records for transactions
        if (isset($totstkamt[$stkacc])) {
            if ($stk['vatex'] == "y") {
                $totstkamt[$stkacc] += vats($stk['amt'], 'novat', $vd['vat_amount']);
                $va = 0;
                $inv['chrgvat'] = "";
            } else {
                $totstkamt[$stkacc] += vats($stk['amt'], $inv['chrgvat'], $vd['vat_amount']);
                $va = sprint($stk['amt'] - vats($stk['amt'], $inv['chrgvat'], $vd['vat_amount']));
                if ($inv['chrgvat'] == "no") {
                    $va = sprint($stk['amt'] * $VATP / 100);
                }
            }
        } else {
            if ($stk['vatex'] == "y") {
                $totstkamt[$stkacc] = $stk['amt'];
                $inv['chrgvat'] = "";
                $va = 0;
            } else {
                $totstkamt[$stkacc] = vats($stk['amt'], $inv['chrgvat'], $vd['vat_amount']);
                $va = sprint($stk['amt'] - vats($stk['amt'], $inv['chrgvat'], $vd['vat_amount']));
                if ($inv['chrgvat'] == "no") {
                    $va = sprint($stk['amt'] * $VATP / 100);
                }
            }
        }
        $f = vats($stk['amt'], $inv['chrgvat'], $vd['vat_amount']);
        $f = $f * $inv['xrate'];
        $va = $va * $inv['xrate'];
        vatr($vd['id'], $td, "OUTPUT", $vd['code'], $refnum, "Non-Stock Sales, invoice No.{$real_invid}", $f + $va, $va);
        $inv['chrgvat'] = $t;
        $sql = "UPDATE nons_inv_items SET accid = '{$stkacc}' WHERE id = '{$stk['id']}'";
        $sRslt = db_exec($sql);
        $products .= "<tr valign=top><td>{$stk['description']}</td><td>{$stk['qty']}</td><td>{$inv['currency']}  {$stk['unitcost']}</td><td>{$inv['currency']} {$stk['amt']}</td></tr>";
    }
    /* --- Start Some calculations --- */
    # Subtotal
    $SUBTOT = sprint($inv['subtot']);
    $VAT = sprint($inv['vat']);
    $TOTAL = sprint($inv['total']);
    $LVAT = sprint($VAT * $inv['xrate']);
    $LTOTAL = sprint($TOTAL * $inv['xrate']);
    /* --- End Some calculations --- */
    /* - Start Hooks - */
    $vatacc = gethook("accnum", "salesacc", "name", "VAT", "non");
    /* - End Hooks - */
    # todays date
    $date = date("d-m-Y");
    $sdate = date("Y-m-d");
    # Get department
    db_conn("exten");
    $sql = "SELECT * FROM departments WHERE deptid = '{$cus['deptid']}' AND div = '" . USER_DIV . "'";
    $deptRslt = db_exec($sql);
    if (pg_numrows($deptRslt) < 1) {
        $dept['deptname'] = "<li class=err>Department not Found.";
    } else {
        $dept = pg_fetch_array($deptRslt);
    }
    # record transaction  from data
    foreach ($totstkamt as $stkacc => $wamt) {
        # Debit Customer and Credit stock
        writetrans($dept['debtacc'], $stkacc, $td, $refnum, $wamt * $inv['xrate'], "Non-Stock Sales on invoice No.{$real_invid} customer {$cus['surname']}.");
    }
    # Debit bank and credit the account involved
    writetrans($dept['debtacc'], $vatacc, $td, $refnum, $LVAT, "Non-Stock Sales VAT received on invoice No.{$real_invid} customer {$cus['surname']}.");
    $sdate = date("Y-m-d");
    db_connect();
    $sql = "UPDATE nons_invoices SET cusid = '{$cusnum}', done = 'y', invnum = '{$real_invid}' WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
    $upRslt = db_exec($sql) or errDie("Unable to update invoice information");
    # Record the payment on the statement
    $sql = "\n\t\tINSERT INTO stmnt \n\t\t\t(cusnum, invid, docref, amount, date, type, div, allocation_date) \n\t\tVALUES \n\t\t\t('{$cusnum}', '{$real_invid}', '{$inv['docref']}', '{$TOTAL}','{$inv['sdate']}', 'Non-Stock Invoice', '" . USER_DIV . "', '{$inv['odate']}')";
    $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
    # Record the payment on the statement
    $sql = "INSERT INTO open_stmnt(cusnum, invid, docref, amount,  balance, date, type, div) VALUES('{$cusnum}', '{$real_invid}', '{$inv['docref']}', '{$TOTAL}', '{$TOTAL}','{$inv['sdate']}', 'Non-Stock Invoice', '" . USER_DIV . "')";
    $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
    # Update the customer (make balance more)
    $sql = "UPDATE customers SET balance = (balance + '{$LTOTAL}'::numeric(13,2)), fbalance = (fbalance + '{$TOTAL}'::numeric(13,2)) WHERE cusnum = '{$cusnum}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
    # Make ledge record
    custledger($cusnum, $dept['incacc'], $td, $real_invid, "Non Stock Invoice No. {$real_invid}", $LTOTAL, "d");
    frecordDT($TOTAL, $cusnum, $inv['xrate'], $inv['fcid'], $inv['sdate']);
    db_connect();
    $sql = "INSERT INTO salesrec(edate, invid, invnum, debtacc, vat, total, typ, div)\n\tVALUES('{$inv['sdate']}', '{$invid}', '{$real_invid}', '{$dept['debtacc']}', '{$LVAT}', '{$LTOTAL}', 'non', '" . USER_DIV . "')";
    $recRslt = db_exec($sql);
    db_conn('cubit');
    $Sl = "INSERT INTO sj(cid,name,des,date,exl,vat,inc,div) VALUES\n\t('{$cusnum}','{$na}','Non-stock International Invoice {$real_invid}','{$inv['sdate']}','" . sprint($LTOTAL - $LVAT) . "','{$LVAT}','" . sprint($LTOTAL) . "','" . USER_DIV . "')";
    $Ri = db_exec($Sl);
    # Commit updates
    pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
    # Get selected stock in this invoice
    $sql = "SELECT * FROM nons_inv_items  WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
    # $stkdRslt = db_exec($sql);
    /* -- Format the remarks boxlet -- */
    $inv["remarks"] = "<table border=1><tr><td>Remarks:<br>{$inv['remarks']}</td></tr></table>";
    $cc = "<script> CostCenter('dt', 'Sales', '{$td}', 'Non Stock Invoice No.{$real_invid}', '" . ($LTOTAL - $LVAT) . "', ''); </script>";
    if ($inv['chrgvat'] == "yes") {
        $inv['chrgvat'] = "Inclusive";
    } elseif ($inv['chrgvat'] == "no") {
        $inv['chrgvat'] = "Exclusive";
    } else {
        $inv['chrgvat'] = "No vat";
    }
    /* -- Final Layout -- */
    $details = "\n\t\t\t\t<center>\n\t\t\t\t{$cc}\n\t\t\t\t<h2>Tax Invoice</h2>\n\t\t\t\t<table cellpadding='0' cellspacing='4' border=0 width='750'>\n\t\t\t\t\t<tr>\n\t\t\t\t\t\t<td valign='top' width='30%'>\n\t\t\t\t\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t\t\t\t\t{$details}\n\t\t\t\t\t\t\t</table>\n\t\t\t\t\t\t</td>\n\t\t\t\t\t\t<td valign='top' width='30%'>\n\t\t\t\t\t\t\t" . COMP_NAME . "<br>\n\t\t\t\t\t\t\t" . COMP_ADDRESS . "<br>\n\t\t\t\t\t\t\t" . COMP_TEL . "<br>\n\t\t\t\t\t\t\t" . COMP_FAX . "<br>\n\t\t\t\t\t\t\tReg No. " . COMP_REGNO . "<br>\n\t\t\t\t\t\t\tVAT No. " . COMP_VATNO . "\n\t\t\t\t\t\t</td>\n\t\t\t\t\t\t<td width='20%'><img src='compinfo/getimg.php' width='230' height='47'></td>\n\t\t\t\t\t\t<td valign='bottom' align='right' width='20%'>\n\t\t\t\t\t\t\t<table cellpadding='2' cellspacing='0' border='1' bordercolor='#000000'>\n\t\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t\t<td><b>Invoice No.</b></td>\n\t\t\t\t\t\t\t\t\t<td valign='center'>{$real_invid}</td>\n\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t\t<td><b>Proforma Inv No.</b></td>\n\t\t\t\t\t\t\t\t\t<td valign='center'>{$inv['docref']}</td>\n\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t\t<td><b>Invoice Date</b></td>\n\t\t\t\t\t\t\t\t\t<td valign='center'>{$inv['sdate']}</td>\n\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t\t<td><b>VAT</b></td>\n\t\t\t\t\t\t\t\t\t<td valign='center'>{$inv['chrgvat']}</td>\n\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t</table>\n\t\t\t\t\t\t</td>\n\t\t\t\t\t</tr>\n\t\t\t\t\t" . TBL_BR . "\n\t\t\t\t\t<tr>\n\t\t\t\t\t\t<td colspan='4'>\n\t\t\t\t\t\t\t<table cellpadding='5' cellspacing='0' border='1' width='100%' bordercolor='#000000'>\n\t\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t\t<th width='65%'>DESCRIPTION</th>\n\t\t\t\t\t\t\t\t\t<th width='10%'>QTY</th>\n\t\t\t\t\t\t\t\t\t<th width='10%'>UNIT PRICE</th>\n\t\t\t\t\t\t\t\t\t<th width='10%'>AMOUNT</th>\n\t\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t{$products}\n\t\t\t\t\t\t\t</table>\n\t\t\t\t\t\t</td>\n\t\t\t\t\t</tr>\n\t\t\t\t\t<tr>\n\t\t\t\t\t\t<td>{$inv['remarks']}</td>\n\t\t\t\t\t\t<td>" . BNK_BANKDET . "</td>\n\t\t\t\t\t\t<td align='right' colspan='2'>\n\t\t\t\t\t\t\t<table cellpadding='5' cellspacing='0' border=1 width=50% bordercolor='#000000'>\n\t\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t\t<td><b>SUBTOTAL</b></td>\n\t\t\t\t\t\t\t\t\t<td align='right'>{$inv['currency']} {$SUBTOT}</td>\n\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t\t<td><b>VAT @ " . TAX_VAT . "%</b></td>\n\t\t\t\t\t\t\t\t\t<td align='right'>{$inv['currency']} {$VAT}</td>\n\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t\t<th><b>GRAND TOTAL<b></th>\n\t\t\t\t\t\t\t\t\t<td align='right'>{$inv['currency']} {$TOTAL}</td>\n\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t</table>\n\t\t\t\t\t\t</td>\n\t\t\t\t\t</tr>\n\t\t\t\t\t" . TBL_BR . "\n\t\t\t\t</table>\n\t\t\t\t</center>\n\t\t\t";
    $OUTPUT = $details;
    require "tmpl-print.php";
}
コード例 #9
0
function write_data($_POST)
{
    extract($_POST);
    if (isset($back)) {
        return enter_data2($_POST);
    }
    db_conn('core');
    $Sl = "SELECT accnum FROM salesacc WHERE name='VATIN'";
    $Ri = db_exec($Sl);
    if (pg_num_rows($Ri) > 0) {
        $vd = pg_fetch_array($Ri);
        $vatin = $vd['accnum'];
    } else {
        $vatin = 0;
    }
    $Sl = "SELECT accnum FROM salesacc WHERE name='VATOUT'";
    $Ri = db_exec($Sl);
    if (pg_num_rows($Ri) > 0) {
        $vd = pg_fetch_array($Ri);
        $vatout = $vd['accnum'];
    } else {
        $vatout = 0;
    }
    db_conn('cubit');
    $Sl = "SELECT * FROM vatcodes WHERE del='Yes'";
    $Ri = db_exec($Sl);
    if (pg_num_rows($Ri) < 1) {
        $Sl = "SELECT * FROM vatcodes WHERE zero='Yes'";
        $Ri = db_exec($Sl);
        if (pg_num_rows($Ri) < 1) {
            return "Please set up your vatcodes first.";
        }
    }
    $vcd = pg_fetch_array($Ri);
    db_conn('exten');
    $Sl = "SELECT debtacc FROM departments";
    $Ri = db_exec($Sl);
    $dd = pg_fetch_array($Ri);
    $cc = $dd['debtacc'];
    db_conn('core');
    $Sl = "SELECT * FROM accounts WHERE accname='Opening Balances / Suspense Account'";
    $Ri = db_exec($Sl) or errDie("Unable to get account.");
    if (pg_num_rows($Ri) < 1) {
        return "<li class='err'>There is no account called 'Opening Balances / Suspense Account'. <br>\n\t\tI Need that account.<br>\n\t\tPlease create it. <br><br>\n\t\tThank you.</li>";
    }
    $ad = pg_fetch_array($Ri);
    $bala = $ad['accid'];
    db_conn(PRD_DB);
    # get last ref number
    pglib_transaction("BEGIN");
    $refnum = getrefnum();
    /* check for main accounts whose sub accounts add up to same total,
    			then clear main account
    	   check for main accounts whose sub accounts dont add up, then unblock
    	   		main accounts
    	 */
    $sql = "SELECT * FROM cubit.import_data";
    $rslt = db_exec($sql) or errDie("Error validating data.");
    $acsub = $acmain = array();
    while ($fd = pg_fetch_array($rslt)) {
        $n = explode("/", $fd["des1"]);
        if (!isset($n[1]) || $n[1] == "000") {
            $n[1] = "000";
        }
        $a = array("num" => $fd["des1"], "name" => $fd["des2"], "dt" => $fd["des3"], "ct" => $fd["des4"]);
        if ($n[1] == "000") {
            $acmain["{$n['0']}"] = $a;
        } else {
            if (!isset($acsub[$n[0]])) {
                $acsub[$n[0]] = array();
            }
            $acsub[$n[0]][] = $a;
        }
    }
    /* match subs with mains */
    $unblock_main = false;
    foreach ($acmain as $k => $v) {
        $totdt = 0;
        $totct = 0;
        if (isset($acsub[$k])) {
            foreach ($acsub[$k] as $sk => $sv) {
                $totdt += $sv["dt"];
                $totct += $sv["ct"];
            }
            if ($totdt - $totct != $v["dt"] - $v["ct"]) {
                $unblock_main = true;
            } else {
                $sql = "UPDATE cubit.import_data SET des3='0', des4='0'\n\t\t\t\t\t\tWHERE des1='{$v['num']}' AND des2='{$v['name']}'";
                $rslt = db_exec($sql) or errDie("Error balancing main account with sub accounts: {$v['num']} - {$v['name']} with {$sv['num']} - {$sv['name']}.");
            }
        }
    }
    if ($unblock_main) {
        $sql = "UPDATE cubit.set SET value = 'nuse', descript = 'Dont block main accounts'\n\t\t\t\tWHERE label = 'BLOCK' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Error unblocking main accounts.");
    }
    /* continue importing (validated/fixed) data */
    db_conn('cubit');
    $Sl = "SELECT * FROM import_data";
    $Ri = db_exec($Sl);
    $i = 0;
    $tot_debit = 0;
    $tot_credit = 0;
    $date = mkdate(getYearOfFinMon($prd), $prd, 1);
    db_conn('core');
    while ($fd = pg_fetch_array($Ri)) {
        $fid = $fd['id'];
        $accs = explode('/', $fd['des1']);
        $topacc = $accs[0];
        $topacc = str_pad($topacc, 4, "0");
        if (isset($accs[1])) {
            $accnum = $accs[1];
        } else {
            $accnum = "000";
        }
        db_conn('core');
        if ($accounts[$fid] == 0) {
            $catss = explode(":", $cat[$fid]);
            if ($catss[0] == "other_income" || $catss[0] == "sales") {
                $catT = "I10";
                $type = "I";
            } elseif ($catss[0] == "expenses" || $catss[0] == "cost_of_sales") {
                $catT = "E10";
                $type = "E";
            } else {
                $catT = "B10";
                $type = "B";
            }
            $Sl = "\n\t\t\t\tINSERT INTO accounts (\n\t\t\t\t\ttopacc, accnum, catid, accname, vat, \n\t\t\t\t\tdiv, toptype, acctype\n\t\t\t\t) VALUES (\n\t\t\t\t\t'{$topacc}', '{$accnum}', '{$catT}', '{$fd['des2']}', 'f', \n\t\t\t\t\t'" . USER_DIV . "', '{$catss['0']}', '{$type}'\n\t\t\t\t)";
            $Rl = db_exec($Sl);
            $accname = $fd['des2'];
            $accid = pglib_lastid("accounts", "accid");
            // 			$query = "INSERT INTO trial_bal(accid, topacc, accnum, accname, div) VALUES('$accid', '$topacc', '$accnum', '$fd[des2]', '".USER_DIV."')";
            // 			$trialRslt = db_exec($query);
            global $MONPRD;
            insert_trialbal($accid, $topacc, $accnum, $accname, $type, 'f', USER_DIV);
            for ($i = 1; $i <= 12; $i++) {
                $periodname = getMonthName($i);
                $sql = "INSERT INTO " . YR_DB . ".{$periodname} (accid, topacc, accnum, accname,\n\t\t\t\t\t\t\tdebit, credit, div)\n\t\t\t\t\t\tSELECT accid, topacc, accnum, accname, debit, credit, div\n\t\t\t\t\t\tFROM core.trial_bal WHERE month='{$i}' AND accid='{$accid}'";
                db_exec($sql) or die($sql);
                $sql = "INSERT INTO \"{$i}\".openbal (accid, accname, debit, credit, div)\n\t\t\t\t\t\tSELECT accid, accname, debit, credit, div\n\t\t\t\t\t\tFROM core.trial_bal WHERE month='{$i}' AND accid='{$accid}'";
                db_exec($sql) or die($sql);
                $sql = "INSERT INTO \"{$i}\".ledger (acc, contra, edate, eref, descript,\n\t\t\t\t\t\t\tcredit, debit, div, caccname, ctopacc, caccnum, cbalance, dbalance)\n\t\t\t\t\t\tSELECT accid, accid, CURRENT_DATE, '0', 'Balance', '0', '0', div,\n\t\t\t\t\t\t\taccname, topacc, accnum, credit, debit\n\t\t\t\t\t\tFROM core.trial_bal WHERE month='{$i}' AND accid='{$accid}'";
                db_exec($sql) or die($sql);
            }
            $accounts[$fid] = $accid;
        } else {
            $Sl = "UPDATE accounts SET topacc='{$topacc}',accnum='{$accnum}',accname='{$fd['des2']}' WHERE accid='{$accounts[$fid]}'";
            $Rl = db_exec($Sl);
            $Sl = "UPDATE trial_bal SET topacc='{$topacc}',accnum='{$accnum}',accname='{$fd['des2']}' WHERE accid='{$accounts[$fid]}'";
            $Rl = db_exec($Sl);
        }
        $Sl = "SELECT accid,accname FROM accounts WHERE accid='{$accounts[$fid]}'";
        $Rx = db_exec($Sl);
        $ad = pg_fetch_array($Rx);
        $i++;
        $debit = $fd['des3'];
        $credit = $fd['des4'];
        if ($debit > 0) {
            writetrans($ad['accid'], $bala, $date, $refnum, sprint($debit), "Opening balance imported");
        }
        if ($credit > 0) {
            writetrans($bala, $ad['accid'], $date, $refnum, sprint($credit), "Opening balance imported");
        }
        $tot_debit += $fd['des3'];
        $tot_credit += $fd['des4'];
        if ($ad['accid'] == $vatin) {
            vatr($vcd['id'], $date, "INPUT", $vcd['code'], $refnum, "Opening balance VAT imported", sprint($credit - $debit), sprint($credit - $debit));
        }
        if ($ad['accid'] == $vatout) {
            vatr($vcd['id'], $date, "OUTPUT", $vcd['code'], $refnum, "Opening balance VAT imported", sprint($credit - $debit), sprint($credit - $debit));
        }
    }
    $tot_debit = sprint($tot_debit);
    $tot_credit = sprint($tot_credit);
    if ($cc_tot > 0) {
        $tot = array_sum($cbalance);
        if (sprint($cc_tot) != sprint($tot)) {
            return enter_data2($_POST) . "<li class='err'>The total amount for balances for customers you entered is: " . CUR . " {$tot}, the\n\t\t\ttotal for the control account is: " . sprint($cc_tot) . ". These need to be the same.</li>";
        }
        db_conn('cubit');
        $Sl = "SELECT cusnum,accno,surname FROM customers ORDER BY surname";
        $Ri = db_exec($Sl);
        if (pg_num_rows($Ri) < 1) {
            return "<li class='err'>If you want to import your customer control account you need to add customers first</li>";
        }
        $tot = 0;
        while ($cd = pg_fetch_array($Ri)) {
            $cid = $cd['cusnum'];
            $cbalance[$cid] = sprint($cbalance[$cid]);
            if ($cbalance[$cid] > 0) {
                db_conn('cubit');
                # Update the customer (make balance more)
                $sql = "UPDATE customers SET balance = (balance + '{$cbalance[$cid]}') WHERE cusnum = '{$cid}' AND div = '" . USER_DIV . "'";
                $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
                $sql = "\n\t\t\t\t\tINSERT INTO stmnt (\n\t\t\t\t\t\tcusnum, invid, amount, date, type, \n\t\t\t\t\t\tst, div\n\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t'{$cid}', '0', '{$cbalance[$cid]}', '{$date}', 'Opening Balance Imported', \n\t\t\t\t\t\t'n', '" . USER_DIV . "'\n\t\t\t\t\t)";
                $stmntRslt = db_exec($sql) or errDie("Unable to Insert statement record in Cubit.", SELF);
                $sql = "\n\t\t\t\t\tINSERT INTO open_stmnt (\n\t\t\t\t\t\tcusnum, invid, amount, balance, date, \n\t\t\t\t\t\ttype, st, div\n\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t'{$cid}', '0', '{$cbalance[$cid]}', '{$cbalance[$cid]}', '{$date}', \n\t\t\t\t\t\t'Opening Balance Imported', 'n', '" . USER_DIV . "'\n\t\t\t\t\t)";
                $stmntRslt = db_exec($sql) or errDie("Unable to Insert statement record in Cubit.", SELF);
                crecordDT($cbalance[$cid], $cid, $date);
                custledger($cid, $bala, $date, 0, "Opening Balance Imported", $cbalance[$cid], "d");
            } elseif ($cbalance[$cid] < 0) {
                db_conn('cubit');
                # Update the customer (make balance more)
                $sql = "UPDATE customers SET balance = (balance + '{$cbalance[$cid]}') WHERE cusnum = '{$cid}' AND div = '" . USER_DIV . "'";
                $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
                $sql = "\n\t\t\t\t\tINSERT INTO stmnt (\n\t\t\t\t\t\tcusnum, invid, amount, date, type, \n\t\t\t\t\t\tst, div\n\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t'{$cid}', '0', '{$cbalance[$cid]}', '{$date}', 'Opening Balance Imported', \n\t\t\t\t\t\t'n', '" . USER_DIV . "'\n\t\t\t\t\t)";
                $stmntRslt = db_exec($sql) or errDie("Unable to Insert statement record in Cubit.", SELF);
                $sql = "\n\t\t\t\t\tINSERT INTO open_stmnt (\n\t\t\t\t\t\tcusnum, invid, amount, balance, date, \n\t\t\t\t\t\ttype, st, div\n\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t'{$cid}', '0', '{$cbalance[$cid]}', '{$cbalance[$cid]}', '{$date}', \n\t\t\t\t\t\t'Opening Balance Imported', 'n', '" . USER_DIV . "'\n\t\t\t\t\t)";
                $stmntRslt = db_exec($sql) or errDie("Unable to Insert statement record in Cubit.", SELF);
                crecordCT(-$cbalance[$cid], $cid, $date);
                custledger($cid, $bala, $date, 0, "Opening Balance Imported", -$cbalance[$cid], "c");
            }
            $i++;
            $tot += $cbalance[$cid];
        }
    }
    if ($sc_tot > 0) {
        db_conn('cubit');
        $Sl = "SELECT supid,supno,supname FROM suppliers ORDER BY supname";
        $Ri = db_exec($Sl);
        if (pg_num_rows($Ri) < 1) {
            return "<li class='err'>If you want to import your supplier control account you need to add suppliers first</li>";
        }
        $tot = 0;
        while ($cd = pg_fetch_array($Ri)) {
            $sid = $cd['supid'];
            $sbalance[$sid] += 0;
            if ($sbalance[$sid] > 0) {
                db_conn('cubit');
                $sql = "UPDATE suppliers SET balance = (balance + '{$sbalance[$sid]}') WHERE supid = '{$sid}' AND div = '" . USER_DIV . "'";
                $rslt = db_exec($sql) or errDie("Unable to update supplier in Cubit.", SELF);
                $sql = "\n\t\t\t\t\tINSERT INTO sup_stmnt (\n\t\t\t\t\t\tsupid, edate, ref, cacc, descript, \n\t\t\t\t\t\tamount, div\n\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t'{$sid}', '{$date}', '0', '{$bala}', 'Opening balance imported', \n\t\t\t\t\t\t'{$sbalance[$sid]}', '" . USER_DIV . "'\n\t\t\t\t\t)";
                $stmntRslt = db_exec($sql) or errDie("Unable to Insert statement record in Cubit.", SELF);
                recordCT(-$sbalance[$sid], $sid, $date);
                suppledger($sid, $bala, $date, $refnum, "Opening balance imported", $sbalance[$sid], "c");
            } elseif ($sbalance[$sid] < 0) {
                db_conn('cubit');
                $sql = "UPDATE suppliers SET balance = (balance + '{$sbalance[$sid]}') WHERE supid = '{$sid}' AND div = '" . USER_DIV . "'";
                $rslt = db_exec($sql) or errDie("Unable to update supplier in Cubit.", SELF);
                $sql = "\n\t\t\t\t\tINSERT INTO sup_stmnt (\n\t\t\t\t\t\tsupid, edate, ref, cacc, descript, amount, div\n\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t'{$sid}', '{$date}', '0', '{$bala}', 'Opening balance imported', \n\t\t\t\t\t\t'{$sbalance[$sid]}', '" . USER_DIV . "'\n\t\t\t\t\t)";
                $stmntRslt = db_exec($sql) or errDie("Unable to Insert statement record in Cubit.", SELF);
                recordDT(-$sbalance[$sid], $sid, $date);
                suppledger($sid, $bala, $date, $refnum, "Opening balance imported", $sbalance[$sid], "d");
            }
            $i++;
            $tot += $sbalance[$sid];
        }
        if (sprint($sc_tot) != sprint($tot)) {
            return enter_data2($_POST) . "<li class='err'>The total amount for balances for suppliers you entered is: " . CUR . " {$tot}, the\n\t\t\ttotal for the control account is: " . sprint($sc_tot) . ". These need to be the same.</li>";
        }
    }
    if ($sal_tot > 0) {
        db_conn('cubit');
        $Sl = "SELECT empnum,enum,sname,fnames FROM employees ORDER BY sname,fnames";
        $Ri = db_exec($Sl);
        if (pg_num_rows($Ri) < 1) {
            return "<li class='err'>If you want to import your employee control account you need to add employees first</li>";
        }
        $tot = 0;
        while ($cd = pg_fetch_array($Ri)) {
            $eid = $cd['empnum'];
            if (!isset($ebalance[$eid])) {
                $ebalance[$eid] = "";
            }
            $ebalance[$eid] = sprint($ebalance[$eid]);
            db_conn('cubit');
            $Sl = "UPDATE employees SET balance=balance+'{$ebalance[$eid]}' WHERE empnum = '{$eid}' AND div = '" . USER_DIV . "'";
            $Rt = db_exec($Sl) or errDie("Unable to get employee details.");
            if ($ebalance[$eid] > 0) {
                empledger($eid, $bala, $date, $refnum, "Opening balance imported", $ebalance[$eid], "c");
            } else {
                empledger($eid, $bala, $date, $refnum, "Opening balance imported", abs($ebalance[$eid]), "d");
            }
            $i++;
            $tot += $ebalance[$eid];
        }
        if (sprint($sal_tot) != sprint($tot)) {
            return enter_data2($_POST) . "<li class='err'>The total amount for balances for employees you entered is: " . CUR . " {$tot}, the\n\t\t\ttotal for the control account is: " . sprint($sal_tot) . ". These need to be the same.</li>";
        }
    }
    if ($i_tot > 0) {
        db_conn('cubit');
        $Sl = "SELECT stkid,stkcod,stkdes FROM stock ORDER BY stkcod";
        $Ri = db_exec($Sl);
        if (pg_num_rows($Ri) < 1) {
            return "<li class='err'>If you want to import your inventory control account you need to add stock first</li>";
        }
        $tot = 0;
        while ($cd = pg_fetch_array($Ri)) {
            $iid = $cd['stkid'];
            if (!isset($ibalance[$iid])) {
                $ibalance[$iid] = "";
            }
            if ($ibalance[$iid] > 0) {
                $unitnum = $units[$iid];
                db_connect();
                $sql = "UPDATE stock SET csamt = (csamt + '{$ibalance[$iid]}'), units = (units + '{$unitnum}') WHERE stkid = '{$iid}' AND div = '" . USER_DIV . "'";
                $rslt = db_exec($sql) or errDie("Unable to insert stock to Cubit.", SELF);
                stockrec($cd['stkid'], $cd['stkcod'], $cd['stkdes'], 'dt', $date, $unitnum, $ibalance[$iid], "Inventory balance imported");
                db_connect();
                $cspric = sprint($ibalance[$iid] / $unitnum);
                //$cspric = sprint(0);
                $sql = "\n\t\t\t\t\tINSERT INTO stockrec (\n\t\t\t\t\t\tedate, stkid, stkcod, stkdes, trantype, qty, \n\t\t\t\t\t\tcsprice, csamt, details, div\n\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t'{$date}', '{$cd['stkid']}', '{$cd['stkcod']}', '{$cd['stkdes']}', 'inc', '{$unitnum}', \n\t\t\t\t\t\t'{$ibalance[$iid]}', '{$cspric}', 'Inventory balance imported', '" . USER_DIV . "'\n\t\t\t\t\t)";
                $recRslt = db_exec($sql);
                db_connect();
                $sql = "SELECT * FROM stock WHERE stkid = '{$iid}' AND div = '" . USER_DIV . "'";
                $stkRslt = db_exec($sql) or errDie("Unable to access databse.", SELF);
                if (pg_numrows($stkRslt) < 1) {
                    return "<li> Invalid Stock ID.</li>";
                } else {
                    $stk = pg_fetch_array($stkRslt);
                }
                if ($stk['units'] != 0) {
                    $sql = "UPDATE stock SET csprice = (csamt/units) WHERE stkid = '{$iid}' AND div = '" . USER_DIV . "'";
                    $rslt = db_exec($sql) or errDie("Unable to insert stock to Cubit.", SELF);
                } else {
                    $sql = "UPDATE stock SET csprice = '{$csprice}' WHERE stkid = '{$iid}' AND div = '" . USER_DIV . "'";
                    $rslt = db_exec($sql) or errDie("Unable to insert stock to Cubit.", SELF);
                }
            }
            $tot += $ibalance[$iid];
            $i++;
        }
        if (sprint($i_tot) != sprint($tot)) {
            return enter_data2($_POST) . "<li class='err'>The total amount for balances for inventory you entered is: " . CUR . " {$tot}, the\n\t\t\ttotal for the control account is: " . sprint($sal_tot) . ". These need to be the same.</li>";
        }
    }
    $out = "\n\t\t<table " . TMPL_tblDflts . " width='50%'>\n\t\t\t<tr>\n\t\t\t\t<th>Data Imported</th>\n\t\t\t</tr>\n\t\t\t<tr class='datacell'>\n\t\t\t\t<td>Trial balance, has been successfully imported.</td>\n\t\t\t</tr>\n\t\t</table>";
    pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
    block();
    return $out;
}
コード例 #10
0
function recvpayment_write()
{
    if (isset($_POST["btn_back"])) {
        return details($_POST);
    }
    extract($_POST);
    $bank_acc = qryAccountsName("Cash on Hand");
    $bank_acc = $bank_acc["accid"];
    $cred_acc = qryAccountsName("POS Credit Card Control");
    $cred_acc = $cred_acc["accid"];
    $v = new validate();
    $v->isOk($cusnum, "num", 1, 10, "Invalid customer id.");
    $v->isOk($bank_acc, "num", 1, 10, "Invalid cash account selected.");
    $v->isOk($pcc, "float", 1, 40, "Invalid credit card amount.");
    $v->isOk($pcash, "float", 1, 40, "Invalid cash amount.");
    $v->isOk($pcheque, "float", 1, 40, "Invalid cheque amount.");
    $v->isOk($amt, "float", 1, 40, "Invalid total received amount.");
    $v->isOk($date, "date", 1, 1, "Invalid invoice date.");
    if ($v->isError()) {
        return details($_POST, $v->genErrors());
    }
    $sdate = $date;
    $cus = qryCustomer($cusnum);
    $dept = qryDepartment($cus["deptid"], "debtacc");
    $refnum = getrefnum();
    pglib_transaction("BEGIN");
    /* do the calculations/recordings */
    # update the customer (make balance less)
    $sql = "UPDATE cubit.customers SET balance = (balance - '{$amt}'::numeric(13,2))\r\n\t\t\tWHERE cusnum = '{$cus['cusnum']}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
    $sql = "SELECT prd,invnum,descrip,age FROM cubit.nons_invoices\r\n\t\t\tWHERE invid ='{$invid}' AND div = '" . USER_DIV . "'";
    $invRslt = db_exec($sql) or errDie("Unable to retrieve invoice details from database.");
    if (pg_numrows($invRslt) < 1) {
        return "<li class=err>Invalid Invoice Number.";
    }
    $inv = pg_fetch_array($invRslt);
    $inv['invnum'] += 0;
    # reduce the money that has been paid
    if ($amt) {
        $sql = "UPDATE cubit.nons_invoices\r\n\t\t\t\tSET balance = (balance - {$amt}::numeric(13,2))\r\n\t\t\t\tWHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
        $payRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
        $sql = "UPDATE cubit.open_stmnt\r\n\t\t\t\tSET balance = (balance - {$amt}::numeric(13,2))\r\n\t\t\t\tWHERE invid = '{$inv['invnum']}' AND div = '" . USER_DIV . "'";
        $payRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
        # record the payment on the statement
        $sql = "INSERT INTO cubit.stmnt(cusnum, invid, amount, date, type, div)\r\n\t\t\t\tVALUES('{$cus['cusnum']}','{$inv['invnum']}',\r\n\t\t\t\t'" . ($amt - $amt * 2) . "','{$sdate}',\r\n\t\t\t\t'Payment for Hire Invoice No. {$inv['invnum']}',\r\n\t\t\t\t'" . USER_DIV . "')";
        $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
        $cash_amt = $pcash + $pcheque;
        $cred_amt = $pcc;
        custledger($cus['cusnum'], $bank_acc, $sdate, $inv['invnum'], "Payment for Hire Invoice No. {$inv['invnum']}", $cash_amt, "c");
        custledger($cus["cusnum"], $cred_acc, $sdate, $inv["invnum"], "Payment for Hire Invoice No. {$inv['invnum']}", $cred_amt, "c");
        custCT($amt, $cus["cusnum"], $sdate);
        //recordCT($amt, $cus['cusnum'],$inv['age'],$sdate);
    }
    if (!isset($invids[$key])) {
        $invids[$key] = 0;
    }
    if (!isset($rinvids)) {
        $rinvids = 0;
    }
    if (!isset($amounts)) {
        $amounts = 0;
    }
    if (!isset($invprds)) {
        $invprds = 0;
    }
    if (!isset($rages)) {
        $rages = 0;
    }
    if (!isset($invidsers)) {
        $invidsers = 0;
    }
    $rinvids .= "|{$invids[$key]}";
    $amounts .= "|{$amt}";
    $invprds .= "|0";
    $rages .= "|{$inv['age']}";
    $invidsers .= " - {$inv['invnum']}";
    $sql = "SELECT * FROM core.accounts WHERE topacc='6400' AND accnum='000'";
    $acc_rslt = db_exec($sql);
    $deptacc = pg_fetch_result($acc_rslt, 0);
    if ((double) $pcash) {
        writetrans($bank_acc, $deptacc, $sdate, $refnum, $pcash, "Payment for Invoice {$inv['invnum']} from customer {$cus['cusname']} {$cus['surname']}");
    }
    if ((double) $pcc) {
        $sql = "SELECT accid FROM core.accounts WHERE topacc='7300' AND accnum='000'";
        $acc_rslt = db_exec($sql);
        $accid = pg_fetch_result($acc_rslt, 0);
        writetrans($accid, $deptacc, $sdate, $refnum, $pcc, "Payment for Invoice {$invidsers} from customer {$cus['cusname']} {$cus['surname']}");
    }
    if ((double) $pcheque) {
        $sql = "SELECT accid FROM core.accounts WHERE topacc='7200' AND accnum='000'";
        $acc_rslt = db_exec($sql);
        $accid = pg_fetch_result($acc_rslt, 0);
        writetrans($accid, $deptacc, $sdate, $refnum, $pcheque, "Payment for Invoice {$invidsers} from customer {$cus['cusname']} {$cus['surname']}");
    }
    db_conn('cubit');
    pglib_transaction("COMMIT");
    $_POST["pcc"] = $_POST["pcheque"] = $_POST["pcash"] = "0.00";
    return cdetails($_POST, "<li class='err'>Payment received successfully</li>");
}
コード例 #11
0
function cwrite($_GET)
{
    $showvat = TRUE;
    extract($_GET);
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($invid, "num", 1, 20, "Invalid invoice number.");
    if (isset($ctyp) && $ctyp == 's') {
        $v->isOk($cusnum, "num", 1, 20, "Invalid customer number.");
    } elseif (isset($ctyp) && $ctyp == 'c') {
        $v->isOk($deptid, "num", 1, 20, "Invalid Department.");
    }
    if (isset($stkaccs)) {
        foreach ($stkaccs as $key => $accid) {
            $v->isOk($accid, "num", 1, 20, "Invalid Item Account number.");
        }
    } else {
        $v->isOk($invid, "num", 0, 0, "Invalid Item Account number.");
    }
    # display errors, if any
    if ($v->isError()) {
        $err = $v->genErrors();
        $err .= "<input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $err;
    }
    db_connect();
    # Get invoice info
    $sql = "SELECT * FROM nons_invoices WHERE invid = '{$invid}' AND div = '" . USER_DIV . "' and done='n'";
    $invRslt = db_exec($sql) or errDie("Unable to get invoice information");
    if (pg_numrows($invRslt) < 1) {
        return "<i class='err'>Not Found</i>";
    }
    $inv = pg_fetch_array($invRslt);
    $td = $inv['odate'];
    db_connect();
    # cust % bank
    if ($ctyp == 's') {
        $sql = "SELECT * FROM customers WHERE cusnum = '{$cusnum}' AND div = '" . USER_DIV . "'";
        $custRslt = db_exec($sql) or errDie("Unable to view customer");
        $cus = pg_fetch_array($custRslt);
        $details = "\r\n\t\t<tr><td>{$cus['surname']}</td></tr>\r\n\t\t<tr><td>" . nl2br($cus['addr1']) . "</td></tr>\r\n\t\t<tr><td>VAT No. {$cus['vatnum']}</td></tr>\r\n\t\t<tr><td>Customer Order Number: {$inv['cordno']}</td></tr>";
        $na = $cus['surname'];
    } elseif ($ctyp == 'c') {
        $cus['surname'] = $inv['cusname'];
        $cus['addr1'] = $inv['cusaddr'];
        $cus["del_addr1"] = "";
        $cus["paddr1"] = "";
        db_conn("exten");
        $sql = "SELECT * FROM departments WHERE deptid = '{$deptid}'";
        $deptRslt = db_exec($sql) or errDie("Unable to view customers");
        $dept = pg_fetch_array($deptRslt);
        $details = "\r\n\t\t<tr><td>{$inv['cusname']}</td></tr>\r\n\t\t<tr><td>" . nl2br($inv['cusaddr']) . "</td></tr>\r\n\t\t<tr><td>VAT No. {$inv['cusvatno']}</td></tr>\r\n\t\t<tr><td>Customer Order Number: {$inv['cordno']}</td></tr>";
        $na = $inv['cusname'];
    } else {
        $cus["del_addr1"] = "";
        $cus["paddr1"] = "";
        $cus['surname'] = $inv['cusname'];
        $cus['addr1'] = $inv['cusaddr'];
        $details = "\r\n\t\t<tr><td>{$inv['cusname']}</td></tr>\r\n\t\t<tr><td>" . nl2br($inv['cusaddr']) . "</td></tr>\r\n\t\t<tr><td>VAT No. {$inv['cusvatno']}</td></tr>\r\n\t\t<tr><td>Customer Order Number: {$inv['cordno']}</td></tr>";
        $na = $inv['cusname'];
    }
    # Begin updates
    $refnum = getrefnum();
    /* - Start Hooks - */
    $vatacc = gethook("accnum", "salesacc", "name", "VAT", "NO VAT");
    $varacc = gethook("accnum", "salesacc", "name", "sales_variance");
    /* - End Hooks - */
    //lock(2);
    $real_invid = divlastid('inv', USER_DIV);
    //unlock(2);
    pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
    /* --- Start Products Display --- */
    # Products layout
    $products = "";
    $disc = 0;
    # get selected stock in this invoice
    db_connect();
    $sql = "SELECT * FROM nons_inv_items  WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
    $stkdRslt = db_exec($sql);
    # Put in product
    $i = 0;
    $page = 0;
    while ($stk = pg_fetch_array($stkdRslt)) {
        if ($i >= 25) {
            $page++;
            $i = 0;
        }
        $stkacc = $stkaccs[$stk['id']];
        $Sl = "SELECT * FROM vatcodes WHERE id='{$stk['vatex']}'";
        $Ri = db_exec($Sl) or errDie("Unable to get data.");
        $vd = pg_fetch_array($Ri);
        if ($vd['zero'] == "Yes") {
            $stk['vatex'] = "y";
        }
        //print $inv['chrgvat'];exit;
        if (TAX_VAT != $vd['vat_amount'] and $vd['vat_amount'] != "0.00") {
            $showvat = FALSE;
        }
        $t = $inv['chrgvat'];
        $VATP = TAX_VAT;
        # keep records for transactions
        if (isset($totstkamt[$stkacc])) {
            if ($stk['vatex'] == "y") {
                $totstkamt[$stkacc] += vats($stk['amt'], 'novat', $vd['vat_amount']);
                $va = 0;
                $inv['chrgvat'] = "";
            } else {
                $totstkamt[$stkacc] += vats($stk['amt'], $inv['chrgvat'], $vd['vat_amount']);
                $va = sprint($stk['amt'] - vats($stk['amt'], $inv['chrgvat'], $vd['vat_amount']));
                if ($inv['chrgvat'] == "no") {
                    $va = sprint($stk['amt'] * $vd['vat_amount'] / 100);
                }
            }
        } else {
            if ($stk['vatex'] == "y") {
                $totstkamt[$stkacc] = $stk['amt'];
                $inv['chrgvat'] = "";
                $va = 0;
            } else {
                $totstkamt[$stkacc] = vats($stk['amt'], $inv['chrgvat'], $vd['vat_amount']);
                $va = sprint($stk['amt'] - vats($stk['amt'], $inv['chrgvat'], $vd['vat_amount']));
                if ($inv['chrgvat'] == "no") {
                    $va = sprint($stk['amt'] * $vd['vat_amount'] / 100);
                }
            }
        }
        vatr($vd['id'], $td, "OUTPUT", $vd['code'], $refnum, "Non-Stock Sales, invoice No.{$real_invid}", vats($stk['amt'], $inv['chrgvat'], $vd['vat_amount']) + $va, $va);
        if ($stk["asset_id"] > 0) {
            $asset_vat[$stk["id"]] = $va;
        }
        $inv['chrgvat'] = $t;
        // 		if(isset($totstkamt[$stkacc])){
        // 			$totstkamt[$stkacc] += vats($stk['amt'], $inv['chrgvat']);
        // 		}else{
        // 			$totstkamt[$stkacc] = vats($stk['amt'], $inv['chrgvat']);
        // 		}
        $sql = "UPDATE nons_inv_items SET accid = '{$stkacc}' WHERE id = '{$stk['id']}'";
        $sRslt = db_exec($sql);
        if ($stk['vatex'] == 'y') {
            $ex = "#";
        } else {
            $ex = "&nbsp;&nbsp;";
        }
        $products[$page][] = "\r\n\t\t\t<tr valign=top>\r\n\t\t\t\t<td style='border-right: 2px solid #000'>{$ex} {$stk['description']}&nbsp;</td>\r\n\t\t\t\t<td style='border-right: 2px solid #000'>{$stk['qty']}&nbsp;</td>\r\n\t\t\t\t<td align='right' style='border-right: 2px solid #000'>{$stk['unitcost']}&nbsp;</td>\r\n\t\t\t\t<td align='right'>" . CUR . " {$stk['amt']}&nbsp;</td>\r\n\t\t\t</tr>";
        $i++;
    }
    $blank_lines = 25;
    foreach ($products as $key => $val) {
        $bl = $blank_lines - count($products[$key]);
        for ($i = 0; $i <= $bl; $i++) {
            $products[$key][] = "\r\n\t \t\t\t<tr>\r\n\t \t\t\t\t<td style='border-right: 2px solid #000'>&nbsp;</td>\r\n\t \t\t\t\t<td style='border-right: 2px solid #000'>&nbsp;</td>\r\n\t \t\t\t\t<td style='border-right: 2px solid #000'>&nbsp;</td>\r\n\t \t\t\t\t<td>&nbsp;</td>\r\n\t \t\t\t</tr>";
        }
    }
    /* --- Start Some calculations --- */
    # Subtotal
    $SUBTOT = sprint($inv['subtot']);
    $VAT = sprint($inv['vat']);
    $TOTAL = sprint($inv['total']);
    /* --- End Some calculations --- */
    /* - Start Hooks - */
    $vatacc = gethook("accnum", "salesacc", "name", "VAT", "novat");
    /* - End Hooks - */
    # todays date
    $date = date("d-m-Y");
    $sdate = date("Y-m-d");
    if (isset($bankid)) {
        $bankid += 0;
        db_conn("cubit");
        $sql = "SELECT * FROM bankacct WHERE bankid = '{$inv['accid']}'";
        $deptRslt = db_exec($sql) or errDie("Unable to view customers");
        if (pg_numrows($deptRslt) < 1) {
            $error = "<li class='err'> Bank not Found.</li>";
            $confirm .= "{$error}<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
            return $confirm;
        } else {
            $deptd = pg_fetch_array($deptRslt);
        }
        db_conn('core');
        $Sl = "SELECT * FROM bankacc WHERE accid='{$bankid}'";
        $rd = db_exec($Sl) or errDie("Unable to get data.");
        $data = pg_fetch_array($rd);
        $BA = $data['accnum'];
    }
    $tot_post = 0;
    # bank  % cust
    if ($ctyp == 's') {
        # Get department
        db_conn("exten");
        $sql = "SELECT * FROM departments WHERE deptid = '{$cus['deptid']}' AND div = '" . USER_DIV . "'";
        $deptRslt = db_exec($sql);
        if (pg_numrows($deptRslt) < 1) {
            $dept['deptname'] = "<li class='err'>Department not Found.</li>";
        } else {
            $dept = pg_fetch_array($deptRslt);
        }
        $tpp = 0;
        # record transaction  from data
        foreach ($totstkamt as $stkacc => $wamt) {
            # Debit Customer and Credit stock
            $tot_post += $wamt;
            writetrans($dept['debtacc'], $stkacc, $td, $refnum, $wamt, "Non-Stock Sales on invoice No.{$real_invid} customer {$cus['surname']}.");
        }
        # Debit bank and credit the account involved
        if ($VAT != 0) {
            $tot_post += $VAT;
            writetrans($dept['debtacc'], $vatacc, $td, $refnum, $VAT, "Non-Stock Sales VAT received on invoice No.{$real_invid} customer {$cus['surname']}.");
        }
        $sdate = date("Y-m-d");
        $asset_dtacc = $dept["debtacc"];
    } else {
        if (!isset($accountc)) {
            $accountc = 0;
        }
        if (!isset($dept['pca'])) {
            $accountc += 0;
            $dept['pca'] = $accountc;
            $dept['debtacc'] = $accountc;
        }
        if (isset($bankid)) {
            $dept['pca'] = $BA;
        }
        $tpp = 0;
        # record transaction  from data
        foreach ($totstkamt as $stkacc => $wamt) {
            if (!isset($cust['surname'])) {
                $cust['surname'] = $inv['cusname'];
                $cust['addr1'] = $inv['cusaddr'];
            }
            # Debit Customer and Credit stock
            $tot_post += $wamt;
            writetrans($dept['pca'], $stkacc, $td, $refnum, $wamt, "Non-Stock Sales on invoice No.{$real_invid} customer {$cust['surname']}.");
        }
        if (isset($bankid)) {
            db_connect();
            $bankid += 0;
            $sql = "INSERT INTO cashbook(bankid, trantype, date, name, descript, cheqnum, amount, vat, chrgvat, banked, accinv, div) VALUES ('{$bankid}', 'deposit', '{$td}', '{$inv['cusname']}', 'Non-Stock Sales on invoice No.{$real_invid} customer {$inv['cusname']}', '0', '{$TOTAL}', '{$VAT}', '{$inv['chrgvat']}', 'no', '{$stkacc}', '" . USER_DIV . "')";
            $Rslt = db_exec($sql) or errDie("Unable to add bank payment to database.", SELF);
            $sql = "UPDATE nons_invoices SET jobid='{$bankid}' WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
            $upRslt = db_exec($sql) or errDie("Unable to update invoice information");
        }
        # Debit bank and credit the account involved
        if ($VAT != 0) {
            $tot_post += $VAT;
            writetrans($dept['pca'], $vatacc, $td, $refnum, $VAT, "Non-Stock Sales VAT received on invoice No.{$real_invid} customer {$cust['surname']}.");
        }
        $sdate = date("Y-m-d");
        $asset_dtacc = $dept["pca"];
    }
    $tot_post = sprint($tot_post);
    db_connect();
    if ($ctyp == 's') {
        $sql = "UPDATE nons_invoices SET balance = total, cusid = '{$cusnum}', ctyp = '{$ctyp}', cusname = '{$cus['surname']}', cusaddr = '{$cus['addr1']}', cusvatno = '{$cus['vatnum']}', done = 'y', invnum = '{$real_invid}' WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
        $upRslt = db_exec($sql) or errDie("Unable to update invoice information");
        # Record the payment on the statement
        $sql = "INSERT INTO stmnt(cusnum, invid, docref, amount, date, type, div) VALUES('{$cusnum}', '{$real_invid}', '{$inv['docref']}', '{$TOTAL}','{$inv['odate']}', 'Non-Stock Invoice', '" . USER_DIV . "')";
        $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
        # Record the payment on the statement
        $sql = "INSERT INTO open_stmnt(cusnum, invid, docref, amount, balance, date, type, div) VALUES('{$cusnum}', '{$real_invid}', '{$inv['docref']}', '{$TOTAL}', '{$TOTAL}','{$inv['sdate']}', 'Non-Stock Invoice', '" . USER_DIV . "')";
        $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
        # Update the customer (make balance more)
        $sql = "UPDATE customers SET balance = (balance + '{$TOTAL}'::numeric(13,2)) WHERE cusnum = '{$cusnum}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
        # Make ledge record
        custledger($cusnum, $stkacc, $td, $real_invid, "Non Stock Invoice No. {$real_invid}", $TOTAL, "d");
        custDT($TOTAL, $cusnum, $td);
        $tot_dif = sprint($tot_post - $TOTAL);
        if ($tot_dif > 0) {
            writetrans($varacc, $dept['debtacc'], $td, $refnum, $tot_dif, "Sales Variance on invoice {$real_invid}");
        } elseif ($tot_dif < 0) {
            $tot_dif = $tot_dif * -1;
            writetrans($dept['debtacc'], $varacc, $td, $refnum, $tot_dif, "Sales Variance on invoice {$real_invid}");
        }
    } else {
        $date = date("Y-m-d");
        $sql = "UPDATE nons_invoices SET balance=total, cusname = '{$cust['surname']}', accid = '{$dept['pca']}', ctyp = '{$ctyp}', cusaddr = '{$cust['addr1']}', done = 'y', invnum = '{$real_invid}' WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
        $upRslt = db_exec($sql) or errDie("Unable to update invoice information");
        $tot_dif = sprint($tot_post - $TOTAL);
        if ($tot_dif > 0) {
            writetrans($varacc, $dept['pca'], $td, $refnum, $tot_dif, "Sales Variance on invoice {$real_invid}");
        } elseif ($tot_dif < 0) {
            $tot_dif = $tot_dif * -1;
            writetrans($dept['pca'], $varacc, $td, $refnum, $tot_dif, "Sales Variance on invoice {$real_invid}");
        }
    }
    $sql = "SELECT * FROM cubit.nons_inv_items WHERE invid='{$invid}'";
    $nii_rslt = db_exec($sql) or errDie("Unable to retrieve items.");
    while ($nii_data = pg_fetch_array($nii_rslt)) {
        if ($nii_data["asset_id"] > 0) {
            $asset_vatamt = $asset_vat[$nii_data["id"]];
            if ($inv['chrgvat'] == "yes") {
                $asset_amt = sprint($nii_data["amt"] - $asset_vatamt);
            } else {
                if ($inv['chrgvat'] == "no") {
                    $asset_amt = $nii_data["amt"];
                }
            }
            asset_accounting($nii_data["asset_id"], $nii_data["qty"], $refnum, $asset_amt, $asset_vatamt, $inv["odate"], $invid, $asset_dtacc, $nii_data["accid"]);
        }
    }
    db_connect();
    $sql = "INSERT INTO salesrec(edate, invid, invnum, debtacc, vat, total, typ, div)\r\n\tVALUES('{$inv['odate']}', '{$invid}', '{$real_invid}', '{$dept['debtacc']}', '{$VAT}', '{$TOTAL}', 'non', '" . USER_DIV . "')";
    $recRslt = db_exec($sql);
    com_invoice($inv['salespn'], $TOTAL - $VAT, 0, $real_invid, $inv["odate"]);
    db_conn('cubit');
    if (!isset($cusnum)) {
        $cusnum = 0;
    }
    $Sl = "INSERT INTO sj(cid,name,des,date,exl,vat,inc,div) VALUES\r\n\t('{$cusnum}','{$na}','Non stock Invoice {$real_invid}','{$inv['sdate']}','" . sprint($TOTAL - $VAT) . "','{$VAT}','" . sprint($TOTAL) . "','" . USER_DIV . "')";
    $Ri = db_exec($Sl);
    # Commit updates
    pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
    # Get selected stock in this invoice
    $sql = "SELECT * FROM nons_inv_items  WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
    # $stkdRslt = db_exec($sql);
    $date = date("d-m-Y");
    $cc = "<script> CostCenter('dt', 'Sales', '{$inv['odate']}', 'Non Stock Invoice No.{$real_invid}', '" . ($TOTAL - $VAT) . "', ''); </script>";
    db_conn('cubit');
    $Sl = "SELECT * FROM settings WHERE constant='SALES'";
    $Ri = db_exec($Sl) or errDie("Unable to get settings.");
    $data = pg_fetch_array($Ri);
    if ($data['value'] == "Yes") {
        $sp = "<tr><td><b>Sales Person:</b> {$inv['salespn']}</td></tr>";
    } else {
        $sp = "";
    }
    if ($inv['chrgvat'] == "yes") {
        $inv['chrgvat'] = "Inclusive";
    } elseif ($inv['chrgvat'] == "no") {
        $inv['chrgvat'] = "Exclusive";
    } else {
        $inv['chrgvat'] = "No vat";
    }
    if ($inv["remarks"] == "") {
        db_conn("cubit");
        $sql = "SELECT value FROM settings WHERE constant='DEFAULT_COMMENTS'";
        $commRslt = db_exec($sql) or errDie("Unable to retrieve the default comments from Cubit.");
        $inv["remarks"] = pg_fetch_result($commRslt, 0);
    }
    if (!isset($showvat)) {
        $showvat = TRUE;
    }
    if ($showvat == TRUE) {
        $vat14 = AT14;
    } else {
        $vat14 = "";
    }
    // Retrieve the company information
    db_conn("cubit");
    $sql = "SELECT * FROM compinfo";
    $comp_rslt = db_exec($sql) or errDie("Unable to retrieve company information from Cubit.");
    $comp_data = pg_fetch_array($comp_rslt);
    // Retrieve the banking information
    db_conn("cubit");
    $sql = "SELECT * FROM bankacct WHERE bankid='2' AND div='" . USER_DIV . "'";
    $bank_rslt = db_exec($sql) or errDie("Unable to retrieve bank information from Cubit.");
    $bank_data = pg_fetch_array($bank_rslt);
    $table_borders = "\r\n\t\tborder-top: 2px solid #000000;\r\n\t\tborder-left: 2px solid #000000;\r\n\t\tborder-right: 2px solid #000000;\r\n\t\tborder-bottom: none;\r\n\t";
    // 	$nolr_borders = "
    // 		border-top: 2px solid #000;
    // 		border-left: none;
    // 		border-right: none;
    // 		border-bottom: none;
    // 	";
    $details = "";
    for ($i = 0; $i <= $page; $i++) {
        // new page?
        if ($i > 1) {
            $details .= "<br style='page-break-after:always;'>";
        }
        $products_out = "";
        foreach ($products[$i] as $string) {
            $products_out .= $string;
        }
        $details .= "<center>\r\n\t\t<table cellpadding='0' cellspacing='0' width='85%' style='{$table_borders}'>\r\n\t\t\t<tr><td>\r\n\t\t\t<table border='0' cellpadding='2' cellspacing='2' width='100%'>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td align='left' rowspan='2'><img src='compinfo/getimg.php' width=230 height=47></td>\r\n\t\t\t\t\t<td align='left' rowspan='2'><font size='5'><b>" . COMP_NAME . "</b></font></td>\r\n\t\t\t\t\t<td align='right'><font size='5'><b>Tax Invoice</b></font></td>\r\n\t\t\t\t</tr>\r\n\t\t\t</table>\r\n\t\t\t</td></tr>\r\n\t\t</table>\r\n\r\n\t\t<table cellpadding='0' cellspacing='0' width='85%' style='{$table_borders}'>\r\n\t\t\t<tr><td valign='top'>\r\n\t\t\t<table cellpadding='2' cellspacing='0' border='0' width='100%'>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'>{$comp_data['addr1']}&nbsp;</td>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'>{$comp_data['paddr1']}&nbsp;</td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'>{$comp_data['addr2']}&nbsp;</td>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'>{$comp_data['paddr2']}&nbsp;</td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'>{$comp_data['addr3']}&nbsp;</td>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'>{$comp_data['paddr3']}&nbsp;</td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'>{$comp_data['addr4']}&nbsp;</td>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'>{$comp_data['postcode']}&nbsp;</td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>REG:</b> {$comp_data['regnum']}</b>&nbsp;</td>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>{$bank_data['bankname']}</b>&nbsp;</td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>VAT REG:</b> {$comp_data['vatnum']}&nbsp;</td>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Branch</b> {$bank_data['branchname']}&nbsp;</td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Tel:</b> {$comp_data['tel']}&nbsp;</td>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Branch Code:</b> {$bank_data['branchcode']}&nbsp;</td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Fax:</b> {$comp_data['fax']}&nbsp;</td>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Acc Num:</b> {$bank_data['accnum']}&nbsp;</td>\r\n\t\t\t\t</tr>\r\n\t\t\t</table>\r\n\t\t\t</td><td valign='top'>\r\n\t\t\t<table cellpadding='2' cellspacing='0' border='0' width='100%'>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Date</b></td>\r\n\t\t\t\t\t<td><b>Page Number</b></td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'>{$inv['odate']}</td>\r\n\t\t\t\t\t<td>" . ($i + 1) . "</td>\r\n\t\t\t\t</tr>\r\n\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-bottom: 2px solid #000; border-right: 2px solid #000'>&nbsp</td>\r\n\t\t\t\t\t<td style='border-bottom: 2px solid #000'>&nbsp</td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr><td>&nbsp</td></tr>\r\n\t\t\t\t<tr><td>&nbsp</td></tr>\r\n\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td colspan='2'><b>Invoice No:</b> {$real_invid}</td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td colspan='2'><b>Proforma Inv No:</b> {$inv['docref']}</td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t{$sp}\r\n\t\t\t</table>\r\n\t\t\t</td></tr>\r\n\t\t</table>\r\n\r\n\t\t<table cellpadding='0' cellspacing='0' width='85%' style='{$table_borders}'>\r\n\t\t\t<tr><td>\r\n\t\t\t<table cellpadding='2' cellspacing='0' border='0' width='100%'>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td align='center'><font size='4'><b>Tax Invoice To:</b></font></td>\r\n\t\t\t\t</tr>\r\n\t\t\t</table>\r\n\t\t\t</td></tr>\r\n\t\t</table>\r\n\r\n\t\t<table cellpadding='0' cellspacing='0' width='85%' style='{$table_borders}'>\r\n\t\t\t<tr><td>\r\n\t\t\t<table cellpadding='2' cellspacing='0' border='0' width='100%'>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td width='33%' style='border-right: 2px solid #000'><b>{$cus['surname']}</b>&nbsp;</td>\r\n\t\t\t\t\t<td width='33%' style='border-right: 2px solid #000'><b>Postal Address</b></td>\r\n\t\t\t\t\t<td width='33%'><b>Delivery Address</td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'>" . nl2br($cus["addr1"]) . "&nbsp;</td>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'>" . nl2br($cus["paddr1"]) . "&nbsp;</td>\r\n\t\t\t\t\t<td>" . nl2br($cus["del_addr1"]) . "&nbsp;</td>\r\n\t\t\t\t</tr>\r\n\t\t\t</table>\r\n\t\t\t</td></tr>\r\n\t\t</table>\r\n\r\n\t\t<table cellpadding='0' cellspacing='0' width='85%' style='{$table_borders}'>\r\n\t\t\t<tr><td>\r\n\t\t\t<table cellpadding='2' cellspacing='0' border='0' width='100%'>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td width='33%' style='border-right: 2px solid #000'><b>Customer VAT No:</b> {$inv['cusvatno']}</td>\r\n\t\t\t\t\t<td width='33%'><b>Customer Order No:</b> {$inv['cordno']}</td>\r\n\t\t\t\t</tr>\r\n\t\t\t</table>\r\n\t\t\t</td></tr>\r\n\t\t</table>\r\n\r\n\t\t<table cellpadding='0' cellspacing='0' width='85%' style='{$table_borders}'>\r\n\t\t\t<tr><td>\r\n\t\t\t<table cellpadding='2' cellspacing='0' border='0' width='100%'>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-bottom: 2px solid #000; border-right: 2px solid #000'><b>Description</b></td>\r\n\t\t\t\t\t<td style='border-bottom: 2px solid #000; border-right: 2px solid #000'><b>Qty</b></td>\r\n\t\t\t\t\t<td style='border-bottom: 2px solid #000; border-right: 2px solid #000' align='right'><b>Unit Price</b></td>\r\n\t\t\t\t\t<td style='border-bottom: 2px solid #000;' align='right'><b>Amount</b></td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t{$products_out}\r\n\t\t\t</table>\r\n\t\t\t</td></tr>\r\n\t\t</table>\r\n\r\n\t\t<table cellpadding='0' cellspacing='0' width='85%' style='{$table_borders}'>\r\n\t\t\t<tr><td>\r\n\t\t\t<table cellpadding='2' cellspacing='0' border='0' width='100%'>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td><i>VAT Exempt Indicator: #</i></td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td>{$inv['remarks']}</td>\r\n\t\t\t\t</tr>\r\n\t\t\t</table>\r\n\t\t</table>\r\n\r\n\t\t<table cellpadding='0' cellspacing='0' width='85%' style='border: 2px solid #000000'>\r\n\t\t\t<tr><td>\r\n\t\t\t<table cellpadding='2' cellspacing='0' border='0' width='100%'>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Terms:</b> {$inv['terms']} days</b></td>\r\n\t\t\t\t\t<td><b>Subtotal:</b></td>\r\n\t\t\t\t\t<td><b>" . CUR . "{$inv['subtot']}</b></td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'>&nbsp;</td>\r\n\t\t\t\t\t<td><b>VAT {$vat14}:</b></td>\r\n\t\t\t\t\t<td><b>" . CUR . "{$inv['vat']}</b></td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Received in good order by:</b>_____________________</td>\r\n\t\t\t\t\t<td><b>Total Incl VAT:</b></td>\r\n\t\t\t\t\t<td><b>" . CUR . "{$inv['total']}</b></td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'>&nbsp;</td>\r\n\t\t\t\t<tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Date:</b>_____________________</td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t</tr>\r\n\t\t\t</table>\r\n\t\t</table>\r\n\t\t";
    }
    // Retrieve the template settings from Cubit
    db_conn("cubit");
    $sql = "SELECT filename FROM template_settings WHERE template='invoices'";
    $tsRslt = db_exec($sql) or errDie("Unable to retrieve template settings from Cubit.");
    $template = pg_fetch_result($tsRslt, 0);
    if ($template == "invoice-print.php") {
        $OUTPUT = "<script> CostCenter('dt', 'Sales', '{$inv['odate']}', 'Non Stock Invoice No.{$real_invid}', '" . ($TOTAL - $VAT) . "', '');</script>\r\n\t\t\t{$details}";
        require "tmpl-print.php";
    } else {
        $OUTPUT = "<script> CostCenter('dt', 'Sales', '{$inv['odate']}', 'Non Stock Invoice No.{$real_invid}', '" . ($TOTAL - $VAT) . "', '');\r\n\t\tmove (\"{$template}?invid={$inv['invid']}&type=nons\");\r\n\t\t</script>";
        require "template.php";
    }
}
コード例 #12
0
function do_trans($_POST)
{
    extract($_POST);
    global $complete;
    #use the perm file we saved in the previous function ...
    $filename_path = $filename_path . "1";
    #now parse it into $complete
    parseXML($filename_path);
    db_connect();
    //print "<pre>";
    //var_dump($complete);
    //print "</pre>";
    pglib_transaction("BEGIN") or errDie("Unable to start transaction.");
    if (isset($complete["DEBTOR"]) and is_array($complete["DEBTOR"])) {
        foreach ($complete["DEBTOR"] as $jobjs) {
            $parms = $jobjs->cols;
            $debtor = $complete["DEBTOR"][$parms["iid"]]->cols;
            if (!isset($debtadd[$parms["accno"]]) or strlen($debtadd[$parms["accno"]]) < 1) {
                continue;
            }
            #this debtor is checked for adding ... so add it
            $ins_sql = "\n\t\t\t\tINSERT INTO customers (\n\t\t\t\t\taccno,surname,title,init,category,class,paddr1,addr1,contname,bustel,tel,cellno,fax,email,saleterm,traddisc,setdisc,pricelist,chrgint,overdue,chrgvat,credterm,odate,credlimit,blocked,deptid,vatnum,div,url,ddiv,intrate,balance,day30,day60,day90,day120,classname,catname,deptname,fbalance,fcid,location,currency,lead_source,comments,del_addr1,sales_rep,bankname,branname,brancode,bankaccno,bankaccname,team_id,registration,bankacctype\n\t\t\t\t) VALUES (\n\t\t\t\t\t'{$parms['accno']}','{$parms['surname']}','{$parms['title']}','{$parms['init']}','{$parms['category']}','{$parms['class']}','{$parms['paddr1']}','{$parms['addr1']}','{$parms['contname']}','{$parms['bustel']}','{$parms['tel']}','{$parms['cellno']}','{$parms['fax']}','{$parms['email']}','{$parms['saleterm']}','{$parms['traddisc']}','{$parms['setdisc']}','{$parms['pricelist']}','{$parms['chrgint']}','{$parms['overdue']}','{$parms['chrgvat']}','{$parms['credterm']}','{$parms['odate']}','{$parms['credlimit']}','{$parms['blocked']}','{$parms['deptid']}','{$parms['vatnum']}','{$parms['div']}','{$parms['url']}','{$parms['ddiv']}','{$parms['intrate']}','{$parms['balance']}','{$parms['day30']}','{$parms['day60']}','{$parms['day90']}','{$parms['day120']}','{$parms['classname']}','{$parms['catname']}','{$parms['deptname']}','{$parms['fbalance']}','{$parms['fcid']}','{$parms['location']}','{$parms['currency']}','{$parms['lead_source']}','{$parms['comments']}','{$parms['del_addr1']}','{$parms['sales_rep']}','{$parms['bankname']}','{$parms['branname']}','{$parms['brancode']}','{$parms['bankaccno']}','{$parms['bankaccname']}','{$parms['team_id']}','{$parms['registration']}','{$parms['bankacctype']}'\n\t\t\t\t)";
            $run_ins = db_exec($ins_sql) or errDie("Unable to add debtor information.");
        }
    }
    if (isset($complete["CREDITOR"]) and is_array($complete["CREDITOR"])) {
        foreach ($complete["CREDITOR"] as $jobjs) {
            $parms = $jobjs->cols;
            $creditor = $complete["CREDITOR"][$parms["iid"]]->cols;
            if (!isset($suppadd[$parms["supno"]]) or strlen($suppadd[$parms["supno"]]) < 1) {
                continue;
            }
            #this creditor is checked for adding ... so add it
            $ins_sql = "\n\t\t\t\tINSERT INTO suppliers (\n\t\t\t\t\tsupno,supname,supaddr,contname,tel,fax,email,bankname,branname,brancode,bankaccno,deptid,vatnum,div,url,ddiv,balance,listid,fbalance,fcid,location,currency,lead_source,comments,branch,groupid,reference,bee_status,team_id,registration,bankaccname,bankacctype\n\t\t\t\t) VALUES (\n\t\t\t\t\t'{$parms['supno']}','{$parms['supname']}','{$parms['supaddr']}','{$parms['contname']}','{$parms['tel']}','{$parms['fax']}','{$parms['email']}','{$parms['bankname']}','{$parms['branname']}','{$parms['brancode']}','{$parms['bankaccno']}','{$parms['deptid']}','{$parms['vatnum']}','{$parms['div']}','{$parms['url']}','{$parms['ddiv']}','{$parms['balance']}','{$parms['listid']}','{$parms['fbalance']}','{$parms['fcid']}','{$parms['location']}','{$parms['currency']}','{$parms['lead_source']}','{$parms['comments']}','{$parms['branch']}','{$parms['groupid']}','{$parms['reference']}','{$parms['bee_status']}','{$parms['team_id']}','{$parms['registration']}','{$parms['bankaccname']}','{$parms['bankacctype']}'\n\t\t\t\t)";
            $run_ins = db_exec($ins_sql) or errDie("Unable to add supplier information.");
        }
    }
    $sdate = date("Y-m-d");
    if (isset($complete["JOURNAL"]) and is_array($complete["JOURNAL"])) {
        foreach ($complete["JOURNAL"] as $jobjs) {
            $parms = $jobjs->cols;
            $doid = $jobjs->id;
            #check if we should run this transaction
            if (!isset($replay[$doid]) or strlen($replay[$doid]) < 1) {
                continue;
            }
            if (!isset($parms["debitacc"])) {
                $parms["debitacc"] = "0";
            }
            db_connect();
            switch ($jobjs->type) {
                case "DEBTOR":
                    $debtor = $complete["DEBTOR"][$parms["iid"]]->cols;
                    if (!isset($parms['creditacc'])) {
                        $parms['creditacc'] = "0";
                    }
                    if ($parms['debitacc'] == '0' and $parms['creditacc'] == '0') {
                        #its not 1 of the custom saves ... so do generic ...
                        # record the payment on the statement
                        $sql = "\n\t\t\t\t\t\t\tINSERT INTO stmnt (\n\t\t\t\t\t\t\t\tcusnum, invid, amount, date, type, st, div, allocation_date\n\t\t\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t\t\t'{$parms['iid']}', '0', '{$parms['amount']}', '{$parms['date']}', '{$parms['details']}', 'n', '" . USER_DIV . "', '{$parms['date']}'\n\t\t\t\t\t\t\t)";
                        $stmntRslt = db_exec($sql) or errDie("Unable to Insert statement record in Cubit.", SELF);
                        $sql = "INSERT INTO open_stmnt(cusnum, invid, amount, balance, date, type, st, div) VALUES('{$parms['iid']}', '0', '{$parms['amount']}', '{$parms['amount']}', '{$parms['date']}', '{$parms['details']}', 'n', '" . USER_DIV . "')";
                        $stmntRslt = db_exec($sql) or errDie("Unable to Insert statement record in Cubit.", SELF);
                        # update the customer (make balance more)
                        $sql = "UPDATE customers SET balance = (balance + '{$parms['amount']}') WHERE cusnum = '{$parms['iid']}' AND div = '" . USER_DIV . "'";
                        $rslt = db_exec($sql) or errDie("Unable to update customer in Cubit.", SELF);
                    } else {
                        if ($parms['debitacc'] == '0') {
                            if ($parms['creditacc'] == '1') {
                                recordCT($parms['amount'], $parms['iid'], $parms['date']);
                            } else {
                                custledger($parms['iid'], $parms['creditacc'], $parms['date'], $parms['refno'], $parms['details'], $parms['amount'], 'c');
                            }
                        } elseif ($parms['creditacc'] == '0') {
                            if ($parms['debitacc'] == '1') {
                                recordDT($parms['amount'], $parms['iid'], $parms['date']);
                            } else {
                                custledger($parms['iid'], $parms['creditacc'], $parms['date'], $parms['refno'], $parms['details'], $parms['amount'], 'd');
                            }
                        }
                    }
                    break;
                case "CREDITOR":
                    $creditor = $complete["CREDITOR"][$parms["iid"]]->cols;
                    if ($parms['debitacc'] == '0') {
                        if ($parms['creditacc'] == '1') {
                            recordCT(-$parms['amount'], $parms['iid'], $parms['date']);
                        } else {
                            suppledger($parms['iid'], $parms['creditacc'], $parms['date'], $parms['refno'], $parms['details'], $parms['amount'], 'c');
                        }
                    } elseif ($parms['creditacc'] == '0') {
                        if ($parms['debitacc'] == '1') {
                            recordDT($parms['amount'], $parms['iid'], $parms['date']);
                        } else {
                            suppledger($parms['iid'], $parms['debitacc'], $parms['date'], $parms['refno'], $parms['details'], $parms['amount'], 'd');
                        }
                    } elseif ($parms['debitacc'] == "9999" or $parms['creditacc'] == "9999") {
                        # record the payment on the statement
                        $sql = "INSERT INTO sup_stmnt(supid, edate, ref, cacc, descript, amount, div) VALUES('{$parms['iid']}', '{$parms['date']}', '0', '{$parms['refno']}', '{$parms['details']}', '{$parms['amount']}', '" . USER_DIV . "')";
                        $stmntRslt = db_exec($sql) or errDie("Unable to Insert statement record in Cubit.", SELF);
                        # update the supplier (make balance more)
                        $sql = "UPDATE suppliers SET balance = (balance + '{$parms['amount']}') WHERE supid = '{$parms['iid']}' AND div = '" . USER_DIV . "'";
                        $rslt = db_exec($sql) or errDie("Unable to update supplier in Cubit.", SELF);
                    } else {
                        #do nothing ?
                        #its not 1 of the custom saves ... so do generic ...
                        //						db_connect();
                        //						$sql = "INSERT INTO sup_stmnt(supid, edate, ref, cacc, descript, amount, div) VALUES('$parms[iid]', '$parms[date]', '0', '$parms[vat]', '$parms[details]', '$parms[amount]', '".USER_DIV."')";
                        //						$stmntRslt = db_exec($sql) or errDie("Unable to Insert statement record in Cubit.",SELF);
                        //						# update the supplier (make balance more)
                        //						$sql = "UPDATE suppliers SET balance = (balance + '$parms[amount]') WHERE supid = '$parms[iid]' AND div = '".USER_DIV."'";
                        //						$rslt = db_exec($sql) or errDie("Unable to update supplier in Cubit.",SELF);
                    }
                    break;
                case "STOCK":
                    $stock = $complete["STOCK"][$parms["iid"]]->cols;
                    if ($parms['debitacc'] == "0" and $parms['creditacc'] == "0") {
                        $sql = "UPDATE stock SET csamt = (csamt - {$parms['amount']}), units = (units - '{$parms['refno']}') WHERE stkid = '{$parms['iid']}' AND div = '" . USER_DIV . "'";
                        $rslt = db_exec($sql) or errDie("Unable to insert stock to Cubit.", SELF);
                    } elseif ($parms['debitacc'] == "1" and $parms['creditacc'] == "1") {
                        $sql = "UPDATE stock\n\t\t\t\t\t\t\t\tSET units = (units + '{$parms['refno']}'),\n\t\t\t\t\t\t\t\t\tlcsprice = '{$parms['vat']}',\n\t\t\t\t\t\t\t\t\tcsamt = (csamt + {$parms['amount']}),\n\t\t\t\t\t\t\t\t\tcsprice = (\n\t\t\t\t\t\t\t\t\t\tSELECT\n\t\t\t\t\t\t\t\t\t\tCASE WHEN (units != -{$parms['refno']}) THEN (csamt+{$parms['amount']})/(units+{$parms['refno']})\n\t\t\t\t\t\t\t\t\t\t\tELSE 0\n\t\t\t\t\t\t\t\t\t\tEND\n\t\t\t\t\t\t\t\t\t\tFROM cubit.stock\n\t\t\t\t\t\t\t\t\t\tWHERE stkid='{$parms['iid']}' AND div='" . USER_DIV . "'\n\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\tWHERE stkid = '{$parms['iid']}' AND div = '" . USER_DIV . "'";
                        $rslt = db_exec($sql) or errDie("Unable to insert stock to Cubit.", SELF);
                    } else {
                        if ($parms['debitacc'] == "1" and $parms['creditacc'] == "0") {
                            #first get the stock information
                            $sql = "SELECT * FROM stock WHERE stkid = '{$parms['iid']}' AND div = '" . USER_DIV . "'";
                            $stkRslt = db_exec($sql) or errDie("Unable to access databse.", SELF);
                            if (pg_numrows($stkRslt) < 1) {
                                return "<li> Invalid Stock ID.</li>";
                            } else {
                                $stk = pg_fetch_array($stkRslt);
                            }
                            stockrec($stk['stkid'], $stk['stkcod'], $stk['stkdes'], 'dt', $parms['date'], $parms['refno'], $parms['amount'], $parms['details']);
                            $sql = "INSERT INTO stockrec (edate, stkid, stkcod, stkdes, trantype, qty, csprice, csamt, details, div)\n\t\t\t\t\t\t\t\t\t\t\t\tVALUES ('{$parms['date']}', '{$stk['stkid']}', '{$stk['stkcod']}', '{$stk['stkdes']}', 'inc', '{$parms['refno']}', '{$parms['amount']}', '{$parms['vat']}', '{$parms['details']}', '" . USER_DIV . "')";
                            $recRslt = db_exec($sql);
                        } elseif ($parms['debitacc'] == "0" and $parms['creditacc'] == "1") {
                            $sql = "SELECT * FROM stock WHERE stkid = '{$parms['iid']}' AND div = '" . USER_DIV . "'";
                            $stkRslt = db_exec($sql) or errDie("Unable to access databse.", SELF);
                            if (pg_numrows($stkRslt) < 1) {
                                return "<li> Invalid Stock ID.</li>";
                            } else {
                                $stk = pg_fetch_array($stkRslt);
                            }
                            stockrec($stk['stkid'], $stk['stkcod'], $stk['stkdes'], 'ct', $parms['date'], $parms['refno'], $parms['amount'], $parms['details']);
                            $parms[vat] += 0;
                            db_connect();
                            $sql = "INSERT INTO stockrec(edate, stkid, stkcod, stkdes, trantype, qty, csprice, csamt, details, div)\n\t\t\t\t\t\t\t\t\t\t\t\tVALUES('{$parms['date']}', '{$stk['stkid']}', '{$stk['stkcod']}', '{$stk['stkdes']}', 'dec', '-{$parms['refno']}', '{$parms['amount']}', '{$parms['vat']}', '{$parms['details']}', '" . USER_DIV . "')";
                            $recRslt = db_exec($sql);
                            # Units
                            if ($stk['units'] != 0) {
                                $sql = "UPDATE stock SET csprice = (csamt/units) WHERE stkid = '{$parms['iid']}' AND div = '" . USER_DIV . "'";
                                $rslt = db_exec($sql) or errDie("Unable to insert stock to Cubit.", SELF);
                            } else {
                                $sql = "UPDATE stock SET csprice = '{$parms['vat']}' WHERE stkid = '{$parms['iid']}' AND div = '" . USER_DIV . "'";
                                $rslt = db_exec($sql) or errDie("Unable to insert stock to Cubit.", SELF);
                            }
                        } else {
                            #nothing to do ...
                        }
                    }
                    break;
                case "JOURNAL":
                    #process the writetrans
                    if ($parms['debitacc'] == "0" and $parms['creditacc'] == "0") {
                        print "WROTE JOURNAL: VAT<br>";
                        #we are dealing with vatr .. proceed
                        #get the compressed vars
                        $arrs = explode("|", $parms['details']);
                        vatr($arrs[1], $parms['date'], $arrs[2], $arrs[3], $parms['refno'], $arrs[0], $parms['amount'], $parms['vat']);
                    } else {
                        print "WROTE JOURNAL: TRANSACTION<br>";
                        writetrans($parms['debitacc'], $parms['creditacc'], $parms['date'], $parms['refno'], $parms['amount'], $parms['details']);
                    }
                    break;
            }
        }
    }
    pglib_transaction("COMMIT") or errDie("Unable to commit transactions.");
    $display = "\n\t\t\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<th>Transactions Completed</th>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td>All Selected Replay Transactions Completed.</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t</table>\n\t\t\t\t";
    return $display;
}
コード例 #13
0
function details($_POST)
{
    extract($_POST);
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($invid, "num", 1, 20, "Invalid invoice number.");
    # display errors, if any
    if ($v->isError()) {
        $err = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $err .= "<li class='err'>{$e['msg']}</li>";
        }
        return $confirm;
    }
    db_connect();
    # Get invoice info
    $sql = "SELECT * FROM invoices WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
    $invRslt = db_exec($sql) or errDie("Unable to get invoice information");
    if (pg_numrows($invRslt) < 1) {
        return "<i class='err'>Not Found</i>";
    }
    $inv = pg_fetch_array($invRslt);
    $sql = "SELECT stkid FROM inv_items WHERE invid = '{$inv['invid']}' AND div = '" . USER_DIV . "'";
    $crslt = db_exec($sql);
    if (pg_numrows($crslt) < 1) {
        $error = "<li class='err'> Error : Invoice number <b>{$invid}</b> has no items.</li>";
        $error .= "<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $error;
    }
    # check if invoice has been printed
    if ($inv['printed'] == "y") {
        $error = "<li class='err'> Error : Invoice number <b>{$invid}</b> has already been printed.</li>";
        return $error;
    }
    # check if invoice has been serialised
    if ($inv['serd'] == "n") {
        $error = "<li class='err'> Error : You must select serial numbers for some Items on Invoice No. <b>T {$invid}</b> before you can print it.</li>";
        return $error;
    }
    #check if this transaction date is allowed
    // 	$curyr = getActiveFinYear();
    // 	if ($yr > $curyr || ($yr == $curyr && $mon > $PRDMON[12])) {
    // 		$v->addError("", "Cannot do transaction in future financial year. ".(DEBUG>0?"\"$details\"":""));
    // 	}
    db_conn('cubit');
    $showvat = TRUE;
    $blocked_date_from = getCSetting("BLOCKED_FROM");
    $blocked_date_to = getCSetting("BLOCKED_TO");
    if (strtotime($inv['odate']) >= strtotime($blocked_date_from) and strtotime($inv['odate']) <= strtotime($blocked_date_to) and !user_is_admin(USER_ID)) {
        return "<li class='err'>Period Range Is Blocked. Only an administrator can process entries within this period.</li>";
    }
    pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
    $invnum = divlastid('inv', USER_DIV);
    $Sl = "INSERT INTO ncsrec (oldnum, newnum, div) VALUES ('{$invid}', '{$invnum}', '" . USER_DIV . "')";
    $Rs = db_exec($Sl) or errDie("Unable to insert into db");
    # Get department
    db_conn("exten");
    $sql = "SELECT * FROM departments WHERE deptid = '{$inv['deptid']}' AND div = '" . USER_DIV . "'";
    $deptRslt = db_exec($sql);
    if (pg_numrows($deptRslt) < 1) {
        $dept['deptname'] = "<i class='err'>Not Found</i>";
    } else {
        $dept = pg_fetch_array($deptRslt);
    }
    /* --- Start Products Display --- */
    # Products layout
    $commision = 0;
    $products = array();
    $disc = 0;
    # get selected stock in this invoice
    db_connect();
    $sql = "SELECT * FROM inv_items WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
    $stkdRslt = db_exec($sql);
    $taxex = 0;
    $i = 0;
    $page = 0;
    $salesp = qrySalesPersonN($inv["salespn"]);
    while ($stkd = pg_fetch_array($stkdRslt)) {
        if ($i >= 25) {
            $page++;
            $i = 0;
        }
        $stkd['account'] += 0;
        if ($stkd['account'] == 0) {
            # get warehouse name
            db_conn("exten");
            $sql = "SELECT whname FROM warehouses WHERE whid = '{$stkd['whid']}' AND div = '" . USER_DIV . "'";
            $whRslt = db_exec($sql);
            $wh = pg_fetch_array($whRslt);
            # get selected stock in this warehouse
            db_connect();
            $sql = "SELECT * FROM stock WHERE stkid = '{$stkd['stkid']}' AND div = '" . USER_DIV . "'";
            $stkRslt = db_exec($sql);
            $stk = pg_fetch_array($stkRslt);
            $Sl = "SELECT * FROM vatcodes WHERE id='{$stkd['vatcode']}'";
            $Ri = db_exec($Sl);
            if (pg_num_rows($Ri) < 1) {
                return "Please select the vatcode for all your stock.";
            }
            $vd = pg_fetch_array($Ri);
            if (TAX_VAT != $vd['vat_amount'] and $vd['vat_amount'] != "0.00") {
                $showvat = FALSE;
            }
            $sp = "";
            # Check Tax Excempt
            if ($stk['exvat'] == 'yes' || $vd['zero'] == "Yes") {
                $taxex += $stkd['amt'];
                $ex = "#";
            } else {
                $ex = "";
            }
            # all must be excempted
            if ($inv['chrgvat'] == 'nov') {
                $ex = "#";
            }
            # Keep track of discounts
            $disc += $stkd['disc'] * $stkd['qty'];
            # Insert stock record
            $sdate = date("Y-m-d");
            $csprice = sprint($stk['csprice'] * $stkd['qty']);
            # Sales rep commission
            if ($salesp["com"] > 0) {
                $itemcommission = $salesp['com'];
            } else {
                $itemcommission = $stk["com"];
            }
            #if this item is not exvat (ie. $ex != #) then reduce by the vat amount
            if ((strlen($ex) != "#" or $vd['vat_amount'] > 0) and $inv['chrgvat'] == "inc") {
                $vat = sprint($stkd['amt'] * $vd['vat_amount'] / (100 + $vd['vat_amount']));
                $exvatamt = sprint($stkd['amt'] - $vat);
            } else {
                $exvatamt = sprint($stkd['amt']);
            }
            $commision = $commision + coms($inv['salespn'], sprint($exvatamt), $itemcommission);
            if (strlen($stkd['serno']) > 0) {
                $showser = "<br>" . trim($stkd['serno']);
            } else {
                $showser = "";
            }
            # Put in product
            $products[$page][] = "\n\t\t\t\t<tr valign='top'>\n\t\t\t\t\t<td style='border-right: 2px solid #000'>{$stk['stkcod']}&nbsp;</td>\n\t\t\t\t\t<td style='border-right: 2px solid #000'>{$ex} {$sp} {$stk['stkdes']}&nbsp; {$showser}</td>\n\t\t\t\t\t<td style='border-right: 2px solid #000'>{$stkd['qty']}&nbsp;</td>\n\t\t\t\t\t<td align='right' style='border-right: 2px solid #000'>{$stkd['unitcost']}&nbsp;</td>\n\t\t\t\t\t<td align='right' style='border-right: 2px solid #000'>{$stkd['disc']}&nbsp;</td>\n\t\t\t\t\t<td align='right' nowrap>" . CUR . " {$stkd['amt']}&nbsp;</td>\n\t\t\t\t</tr>";
            $i++;
        } else {
            db_conn('core');
            $Sl = "SELECT * FROM accounts WHERE accid='{$stkd['account']}'";
            $Ri = db_exec($Sl) or errDie("Unable to get account data.");
            $ad = pg_fetch_array($Ri);
            db_conn('cubit');
            $Sl = "SELECT * FROM vatcodes WHERE id='{$stkd['vatcode']}'";
            $Ri = db_exec($Sl);
            if (pg_num_rows($Ri) < 1) {
                return "Please select the vatcode for all your stock.";
            }
            $vd = pg_fetch_array($Ri);
            if (TAX_VAT != $vd['vat_amount'] and $vd['vat_amount'] != "0.00") {
                $showvat = FALSE;
            }
            $sp = "";
            # Check Tax Excempt
            if ($vd['zero'] == "Yes") {
                $taxex += $stkd['amt'];
                $ex = "#";
            } else {
                $ex = "";
            }
            # all must be excempted
            if ($inv['chrgvat'] == 'nov') {
                $ex = "#";
            }
            #if this item is not exvat (ie. $ex != #) then reduce by the vat amount
            if ((strlen($ex) != "#" or $vd['vat_amount'] > 0) and $inv['chrgvat'] == "inc") {
                $vat = sprint($stkd['amt'] * $vd['vat_amount'] / (100 + $vd['vat_amount']));
                $exvatamt = sprint($stkd['amt'] - $vat);
            } else {
                $exvatamt = sprint($stkd['amt']);
            }
            if ($salesp["com"] > 0) {
                $itemcommission = $salesp['com'];
            } else {
                $itemcommission = 0;
            }
            $commision = $commision + coms($inv['salespn'], sprint($exvatamt), $itemcommission);
            # Put in product
            $products[$page][] = "\n\t\t\t\t<tr valign='top'>\n\t\t\t\t\t<td style='border-right: 2px solid #000'>&nbsp;</td>\n\t\t\t\t\t<td style='border-right: 2px solid #000'>{$ex} {$sp} {$stkd['description']}&nbsp;</td>\n\t\t\t\t\t<td style='border-right: 2px solid #000'>{$stkd['qty']}&nbsp;</td>\n\t\t\t\t\t<td align='right' style='border-right: 2px solid #000'>{$stkd['unitcost']}&nbsp;</td>\n\t\t\t\t\t<td align='right' style='border-right: 2px solid #000'>{$stkd['disc']}&nbsp;</td>\n\t\t\t\t\t<td align='right' nowrap>" . CUR . " {$stkd['amt']}&nbsp;</td>\n\t\t\t\t</tr>";
            $i++;
        }
    }
    $blank_lines = 25;
    foreach ($products as $key => $val) {
        $bl = $blank_lines - count($products[$key]);
        for ($i = 0; $i <= $bl; $i++) {
            $products[$key][] = "\n\t \t\t\t<tr>\n\t \t\t\t\t<td style='border-right: 2px solid #000'>&nbsp;</td>\n\t \t\t\t\t<td style='border-right: 2px solid #000'>&nbsp;</td>\n\t \t\t\t\t<td style='border-right: 2px solid #000'>&nbsp;</td>\n\t \t\t\t\t<td style='border-right: 2px solid #000'>&nbsp;</td>\n\t \t\t\t\t<td style='border-right: 2px solid #000'>&nbsp;</td>\n\t \t\t\t\t<td>&nbsp;</td>\n\t \t\t\t</tr>";
        }
    }
    /* --- Start Some calculations --- */
    # Subtotal
    $SUBTOT = sprint($inv['subtot']);
    # Calculate tradediscm
    if (strlen($inv['traddisc']) > 0) {
        $traddiscm = sprint($inv['traddisc'] / 100 * $SUBTOT);
    } else {
        $traddiscm = "0.00";
    }
    # Calculate subtotal
    $VATP = TAX_VAT;
    $SUBTOTAL = sprint($inv['subtot']);
    $VAT = sprint($inv['vat']);
    $TOTAL = sprint($inv['total']);
    $inv['delchrg'] = sprint($inv['delchrg']);
    com_invoice($inv['salespn'], $TOTAL - $VAT, sprint($commision), $invnum, $inv["odate"], true);
    /* --- End Some calculations --- */
    /* - Start Hooks - */
    $vatacc = gethook("accnum", "salesacc", "name", "VAT", "VAT");
    /* - End Hooks - */
    # Todays date
    $date = date("d-m-Y");
    $sdate = date("Y-m-d");
    $refnum = getrefnum();
    /*refnum*/
    if ($inv['branch'] != 0) {
        db_conn("cubit");
        $get_addr = "SELECT * FROM customer_branches WHERE id = '{$inv['branch']}' LIMIT 1";
        $run_addr = db_exec($get_addr);
        if (pg_numrows($run_addr) < 1) {
            $address = "";
        } else {
            $barr = pg_fetch_array($run_addr);
            $address = " - {$barr['branch_name']}";
        }
    } else {
        $address = "";
    }
    /* --- Updates ---- */
    db_connect();
    $Sql = "UPDATE invoices SET printed = 'y', done = 'y', invnum='{$invnum}' WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
    $upRslt = db_exec($Sql) or errDie("Unable to update invoice information");
    //dont make consignment order from invoice if customer number is entered ...
    //		if (isset($inv['cordno']) AND strlen($inv['cordno']) > 0){
    //			$inv_type = "Consignment Order";
    //		}else {
    $inv_type = "Invoice";
    //		}
    # Record the payment on the statement
    $sql = "\n\t\t\tINSERT INTO stmnt (\n\t\t\t\tcusnum, invid, docref, amount, date, \n\t\t\t\ttype, branch, div, allocation_date, \n\t\t\t\tallocation_balance\n\t\t\t) VALUES (\n\t\t\t\t'{$inv['cusnum']}', '{$invnum}', '{$inv['docref']}', '{$inv['total']}', '{$inv['odate']}', \n\t\t\t\t'{$inv_type}', '{$address}', '" . USER_DIV . "', '{$inv['odate']}', \n\t\t\t\t'" . abs($inv['total']) . "'\n\t\t\t)";
    $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
    # Record the payment on the statement
    $sql = "\n\t\t\tINSERT INTO open_stmnt (\n\t\t\t\tcusnum, invid, docref, amount, balance, \n\t\t\t\tdate, type, div\n\t\t\t) VALUES (\n\t\t\t\t'{$inv['cusnum']}', '{$invnum}', '{$inv['docref']}', '{$inv['total']}','{$inv['total']}', \n\t\t\t\t'{$inv['odate']}', '{$inv_type}', '" . USER_DIV . "'\n\t\t\t)";
    $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
    # Save invoice discount
    $sql = "\n\t\t\tINSERT INTO inv_discs (\n\t\t\t\tcusnum, invid, traddisc, itemdisc, inv_date, delchrg, \n\t\t\t\tdiv, total\n\t\t\t) VALUES (\n\t\t\t\t'{$inv['cusnum']}', '{$invnum}', '{$traddiscm}', '{$disc}', '{$inv['odate']}', '{$inv['delchrg']}', \n\t\t\t\t'" . USER_DIV . "', ({$SUBTOT}+{$inv['delchrg']})\n\t\t\t)";
    $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
    # Update the customer (make balance more)
    $sql = "UPDATE customers SET balance = (balance + '{$inv['total']}') WHERE cusnum = '{$inv['cusnum']}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
    # Make ledge record
    custledger($inv['cusnum'], $dept['incacc'], $inv['odate'], $invnum, "Invoice No. {$invnum}", $inv['total'], "d");
    db_connect();
    # get selected stock in this invoice
    $sql = "SELECT * FROM inv_items  WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
    $stkdRslt = db_exec($sql);
    $tcosamt = 0;
    $sdate = date("Y-m-d");
    $nsp = 0;
    while ($stkd = pg_fetch_array($stkdRslt)) {
        $stkd['account'] += 0;
        if ($stkd['account'] == 0) {
            db_connect();
            # get selamt from selected stock
            $sql = "SELECT * FROM stock WHERE stkid = '{$stkd['stkid']}' AND div = '" . USER_DIV . "'";
            $stkRslt = db_exec($sql);
            $stk = pg_fetch_array($stkRslt);
            if ($stk['units'] - $stkd['qty'] < 0) {
                if ($stk['units'] <= 0) {
                    $cosamt = 0;
                    $cosamt2 = 0;
                } else {
                    $cosamt = round($stk['units'] * $stk['csprice'], 2);
                    $cosamt2 = round($stk['units'] * $stk['csprice'], 4);
                }
            } else {
                $cosamt = round($stkd['qty'] * $stk['csprice'], 2);
                $cosamt2 = round($stkd['qty'] * $stk['csprice'], 4);
            }
            # update stock(alloc - qty)
            $sql = "\n\t\t\t\t\tUPDATE stock \n\t\t\t\t\tSET csamt = (csamt - '{$cosamt}'),units = (units - '{$stkd['qty']}'), alloc=(alloc - '{$stkd['qty']}') \n\t\t\t\t\tWHERE stkid = '{$stkd['stkid']}' AND div = '" . USER_DIV . "'";
            $rslt = db_exec($sql) or errDie("Unable to update stock to Cubit.", SELF);
            if ($inv["pslip_sordid"] > 0) {
                $sql = "UPDATE stock SET alloc = (alloc - '{$stkd['qty']}') WHERE stkid='{$stkd['stkid']}'";
                //					db_exec($sql) or errDie("Unable to update allocation.");
            }
            ###################VAT CALCS#######################
            $Sl = "SELECT * FROM vatcodes WHERE id='{$stkd['vatcode']}'";
            $Ri = db_exec($Sl);
            if (pg_num_rows($Ri) < 1) {
                return "Please select the vatcode for all your stock.";
            }
            $vd = pg_fetch_array($Ri);
            if ($stk['exvat'] == 'yes' || $vd['zero'] == "Yes") {
                $excluding = "y";
            } else {
                $excluding = "";
            }
            $vr = vatcalc($stkd['amt'], $inv['chrgvat'], $excluding, $inv['traddisc'], $vd['vat_amount']);
            $vrs = explode("|", $vr);
            $ivat = $vrs[0];
            $iamount = $vrs[1];
            vatr($vd['id'], $inv['odate'], "OUTPUT", $vd['code'], $refnum, "VAT for Invoice No.{$invnum} for Customer : {$inv['cusname']} {$inv['surname']}", $iamount, $ivat);
            ####################################################
            $amtexvat = sprint($stkd['amt']);
            //	$uc=sprint($cosamt2/$stkd['qty']);
            $uc = round($cosamt2 / $stkd['qty'], 4);
            // '$cosamt',
            $csprice = sprint($stk['csprice'] * $stkd['qty']);
            db_connect();
            $sql = "\n\t\t\t\t\tINSERT INTO stockrec (\n\t\t\t\t\t\tedate, stkid, stkcod, stkdes, trantype, qty, \n\t\t\t\t\t\tcsprice, csamt, details, div\n\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t'{$inv['odate']}', '{$stkd['stkid']}', '{$stk['stkcod']}', '{$stk['stkdes']}', 'invoice', '{$stkd['qty']}', \n\t\t\t\t\t\t'{$amtexvat}', '{$csprice}', 'Stock sold - Invoice No. {$invnum}', '" . USER_DIV . "'\n\t\t\t\t\t)";
            $recRslt = db_exec($sql);
            if ($stk['csprice'] > 0) {
                $Sl = "INSERT INTO scr (inv, stkid, amount, invid) VALUES ('{$invnum}', '{$stkd['stkid']}', '{$uc}', '{$stkd['id']}')";
                $Rg = db_exec($Sl);
            }
            if ($stk['serd'] == 'yes') {
                ext_invSer($stkd['serno'], $stkd['stkid'], "{$inv['cusname']} {$inv['surname']}", $invnum, $inv['odate']);
            }
            # stkid, stkcod, stkdes, trantype, edate, qty, csamt, details
            $sdate = date("Y-m-d");
            stockrec($stk['stkid'], $stk['stkcod'], $stk['stkdes'], 'ct', $inv['odate'], $stkd['qty'], $cosamt, "Sold to Customer : {$inv['surname']} - Invoice No. {$invnum}");
            # get accounts
            db_conn("exten");
            $sql = "SELECT stkacc, cosacc FROM warehouses WHERE whid = '{$stkd['whid']}' AND div = '" . USER_DIV . "'";
            $whRslt = db_exec($sql);
            $wh = pg_fetch_array($whRslt);
            $stockacc = $wh['stkacc'];
            $cosacc = $wh['cosacc'];
            if ($cosamt < 0) {
                $cosamt = 0;
            }
            # dt(cos) ct(stock)
            writetrans($cosacc, $stockacc, $inv['odate'], $refnum, $cosamt, "Cost Of Sales for Invoice No.{$invnum} for Customer : {$inv['cusname']} {$inv['surname']}");
            $tcosamt += $cosamt;
            #record the entry for the stock report
            db_connect();
            $sql = "\n\t\t\t\t\tINSERT INTO salesrec (\n\t\t\t\t\t\tedate, invid, invnum, debtacc, vat, total, typ, div\n\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t'{$inv['odate']}', '{$invid}', '{$invnum}', '{$dept['debtacc']}', '{$ivat}', '{$iamount}', 'stk', '" . USER_DIV . "'\n\t\t\t\t\t)";
            $recRslt = db_exec($sql);
        } else {
            db_connect();
            ###################VAT CALCS#######################
            $Sl = "SELECT * FROM vatcodes WHERE id='{$stkd['vatcode']}'";
            $Ri = db_exec($Sl);
            if (pg_num_rows($Ri) < 1) {
                return "Please select the vatcode for all your stock.";
            }
            $vd = pg_fetch_array($Ri);
            if ($vd['zero'] == "Yes") {
                $excluding = "y";
            } else {
                $excluding = "";
            }
            $vr = vatcalc($stkd['amt'], $inv['chrgvat'], $excluding, $inv['traddisc'], $vd['vat_amount']);
            $vrs = explode("|", $vr);
            $ivat = $vrs[0];
            $iamount = $vrs[1];
            vatr($vd['id'], $inv['odate'], "OUTPUT", $vd['code'], $refnum, "VAT for Invoice No.{$invnum} for Customer : {$inv['cusname']} {$inv['surname']}", $iamount, $ivat);
            ####################################################
            $amtexvat = sprint($stkd['amt']);
            db_connect();
            $sdate = date("Y-m-d");
            $nsp += sprint($iamount - $ivat);
            writetrans($dept['debtacc'], $stkd['account'], $inv['odate'], $refnum, $iamount - $ivat, "Debtors Control for Invoice No.{$invnum} for Customer : {$inv['cusname']} {$inv['surname']}");
            db_connect();
            $sql = "\n\t\t\t\t\tINSERT INTO salesrec (\n\t\t\t\t\t\tedate, invid, invnum, debtacc, vat, total, typ, div\n\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t'{$inv['odate']}', '{$invid}', '{$invnum}', '{$dept['debtacc']}', '{$ivat}', '{$iamount}', 'non', '" . USER_DIV . "'\n\t\t\t\t\t)";
            $recRslt = db_exec($sql);
        }
    }
    ###################VAT CALCS#######################
    $inv['delvat'] += 0;
    db_conn('cubit');
    $Sl = "SELECT * FROM vatcodes WHERE id='{$inv['delvat']}'";
    $Ri = db_exec($Sl);
    if (pg_num_rows($Ri) < 1) {
        $Sl = "SELECT * FROM vatcodes";
        $Ri = db_exec($Sl);
    }
    $vd = pg_fetch_array($Ri);
    if (TAX_VAT != $vd['vat_amount'] and $vd['vat_amount'] != "0.00") {
        $showvat = FALSE;
    }
    if ($vd['zero'] == "Yes") {
        $excluding = "y";
    } else {
        $excluding = "";
    }
    $vr = vatcalc($inv['delchrg'], $inv['chrgvat'], $excluding, $inv['traddisc'], $vd['vat_amount']);
    $vrs = explode("|", $vr);
    $ivat = $vrs[0];
    $iamount = $vrs[1];
    vatr($vd['id'], $inv['odate'], "OUTPUT", $vd['code'], $refnum, "VAT for Invoice No.{$invnum} for Customer : {$inv['cusname']} {$inv['surname']}", sprint($iamount + $ivat), $ivat);
    ####################################################
    /* - Start Transactoins - */
    # dt(debtors) ct(income/sales)
    writetrans($dept['debtacc'], $dept['incacc'], $inv['odate'], $refnum, sprint($TOTAL - $VAT - $nsp), "Debtors Control for Invoice No.{$invnum} for Customer : {$inv['cusname']} {$inv['surname']}");
    # dt(debtors) ct(vat account)
    writetrans($dept['debtacc'], $vatacc, $inv['odate'], $refnum, $VAT, "VAT Received on Invoice No.{$invnum} for Customer : {$inv['cusname']} {$inv['surname']}");
    db_conn('cubit');
    $Sl = "\n\t\t\tINSERT INTO sj (\n\t\t\t\tcid, name, des, date, exl, \n\t\t\t\tvat, inc, div\n\t\t\t) VALUES (\n\t\t\t\t'{$inv['cusnum']}', '{$inv['surname']}', 'Invoice {$invnum}', '{$inv['odate']}', '" . sprint($TOTAL - $VAT) . "', \n\t\t\t\t'{$VAT}', '" . sprint($TOTAL) . "', '" . USER_DIV . "'\n\t\t\t)";
    $Ri = db_exec($Sl);
    //		db_connect();
    //		$sql = "INSERT INTO salesrec(edate, invid, invnum, debtacc, vat, total, typ, div)
    //		VALUES('$inv[odate]', '$invid', '$invnum', '$dept[debtacc]', '$VAT', '$TOTAL', 'stk', '".USER_DIV."')";
    //		$recRslt = db_exec($sql);
    //exit;
    # Commit updates
    pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
    /* - End Transactoins - */
    # vat explanation
    if ($inv['chrgvat'] == 'nov') {
        $expl = "VAT Exempt indicator";
    } else {
        $expl = "VAT Exempt indicator";
    }
    if (strlen($inv['comm']) > 0) {
        $inv['comm'] = "\n\t\t\t<table border='1' cellspacing='0' bordercolor='#000000'>\n\t\t\t\t<tr>\n\t\t\t\t\t<td>Remarks:</td>\n\t\t\t\t\t<td>" . nl2br($inv['comm']) . "</td>\n\t\t\t\t</tr>\n\t\t\t</table>";
    }
    $cc = "<script> sCostCenter('dt', 'Sales', '{$inv['odate']}', 'Invoice No.{$invnum} for Customer {$inv['cusname']} {$inv['surname']}', '" . ($TOTAL - $VAT) . "', 'Cost Of Sales for Invoice No.{$invnum}', '{$tcosamt}', ''); </script>";
    db_conn('cubit');
    $Sl = "SELECT * FROM settings WHERE constant='SALES'";
    $Ri = db_exec($Sl) or errDie("Unable to get settings.");
    $data = pg_fetch_array($Ri);
    if ($data['value'] == "Yes") {
        $sp = "\n\t\t\t<tr>\n\t\t\t\t<td><b>Sales Person:</b> {$inv['salespn']}</td>\n\t\t\t</tr>";
    } else {
        $sp = "";
    }
    if ($inv['chrgvat'] == "inc") {
        $inv['chrgvat'] = "Inclusive";
    } elseif ($inv['chrgvat'] == "exc") {
        $inv['chrgvat'] = "Exclusive";
    } else {
        $inv['chrgvat'] = "No vat";
    }
    if ($inv['branch'] == 0) {
        $branchname = "Head Office";
    } else {
        $get_bname = "SELECT * FROM customer_branches WHERE id = '{$inv['branch']}' LIMIT 1";
        $run_bname = db_exec($get_bname);
        if (pg_numrows($run_bname) < 1) {
            $branchname = "";
        } else {
            $arr = pg_fetch_array($run_bname);
            $branchname = $arr['branch_name'];
        }
    }
    if (!isset($showvat)) {
        $showvat = TRUE;
    }
    if ($showvat == TRUE) {
        $vat14 = AT14;
    } else {
        $vat14 = "";
    }
    if (strlen(COMP_TEL) > 0) {
        $showtel = "Tel: ";
    } else {
        $showtel = "";
    }
    if (strlen(COMP_FAX) > 0) {
        $showfax = "Fax: ";
    } else {
        $showfax = "";
    }
    // Retrieve the company information
    db_conn("cubit");
    $sql = "SELECT * FROM compinfo";
    $comp_rslt = db_exec($sql) or errDie("Unable to retrieve company information from Cubit.");
    $comp_data = pg_fetch_array($comp_rslt);
    // Retrieve the banking information
    $bank_data = qryBankAcct(getdSetting("BANK_DET"));
    // Retrieve customer information
    db_conn("cubit");
    $sql = "SELECT * FROM customers WHERE cusnum='{$inv['cusnum']}'";
    $cust_rslt = db_exec($sql) or errDie("Unable to retrieve customer information from Cubit.");
    $cust_data = pg_fetch_array($cust_rslt);
    $table_borders = "\n\t\tborder-top: 2px solid #000000;\n\t\tborder-left: 2px solid #000000;\n\t\tborder-right: 2px solid #000000;\n\t\tborder-bottom: none;";
    $details = "";
    for ($i = 0; $i <= $page; $i++) {
        // new page?
        if ($i > 1) {
            $details .= "<br style='page-break-after:always;'>";
        }
        $products_out = "";
        foreach ($products[$i] as $string) {
            $products_out .= $string;
        }
        $barcode = "<img src='manufact/" . pick_slip_barcode($inv["invid"], 1) . "' />";
        $details .= "\n\t\t<center>\n\t\t<table cellpadding='0' cellspacing='0' width='85%' style='{$table_borders}'>\n\t\t\t<tr><td>\n\t\t\t<table border='0' cellpadding='2' cellspacing='2' width='100%'>\n\t\t\t\t<tr>\n\t\t\t\t\t<td align='left'><img src='compinfo/getimg.php' width='230' height='47'>{$barcode}</td>\n\t\t\t\t\t<td align='left'><font size='5'><b>" . COMP_NAME . "</b></font></td>\n\t\t\t\t\t<td align='right'><font size='5'><b>Tax Invoice</b></font></td>\n\t\t\t\t</tr>\n\t\t\t</table>\n\t\t\t</td></tr>\n\t\t</table>\n\n\t\t<table cellpadding='0' cellspacing='0' width='85%' style='{$table_borders}'>\n\t\t\t<tr><td valign='top'>\n\t\t\t<table cellpadding='2' cellspacing='0' border='0' width='100%'>\n\t\t\t\t<tr>\n\t\t\t\t\t<td style='border-right: 2px solid #000'>{$comp_data['addr1']}&nbsp;</td>\n\t\t\t\t\t<td style='border-right: 2px solid #000'>{$comp_data['paddr1']}&nbsp;</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<td style='border-right: 2px solid #000'>{$comp_data['addr2']}&nbsp;</td>\n\t\t\t\t\t<td style='border-right: 2px solid #000'>{$comp_data['paddr2']}&nbsp;</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<td style='border-right: 2px solid #000'>{$comp_data['addr3']}&nbsp;</td>\n\t\t\t\t\t<td style='border-right: 2px solid #000'>{$comp_data['paddr3']}&nbsp;</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<td style='border-right: 2px solid #000'>{$comp_data['addr4']}&nbsp;</td>\n\t\t\t\t\t<td style='border-right: 2px solid #000'>{$comp_data['postcode']}&nbsp;</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>REG:</b> {$comp_data['regnum']}</b>&nbsp;</td>\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>{$bank_data['bankname']}</b>&nbsp;</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>VAT REG:</b> {$comp_data['vatnum']}&nbsp;</td>\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Branch</b> {$bank_data['branchname']}&nbsp;</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Tel:</b> {$comp_data['tel']}&nbsp;</td>\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Branch Code:</b> {$bank_data['branchcode']}&nbsp;</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Fax:</b> {$comp_data['fax']}&nbsp;</td>\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Acc Num:</b> {$bank_data['accnum']}&nbsp;</td>\n\t\t\t\t</tr>\n\t\t\t</table>\n\t\t\t</td><td valign='top'>\n\t\t\t<table cellpadding='2' cellspacing='0' border='0' width='100%'>\n\t\t\t\t<tr>\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Date</b></td>\n\t\t\t\t\t<td><b>Page Number</b></td>\n\t\t\t\t</tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<td style='border-right: 2px solid #000'>{$inv['odate']}</td>\n\t\t\t\t\t<td>" . ($i + 1) . "</td>\n\t\t\t\t</tr>\n\n\t\t\t\t<tr>\n\t\t\t\t\t<td style='border-bottom: 2px solid #000; border-right: 2px solid #000'>&nbsp</td>\n\t\t\t\t\t<td style='border-bottom: 2px solid #000'>&nbsp</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr><td>&nbsp</td></tr>\n\n\t\t\t\t<tr>\n\t\t\t\t\t<td colspan='2'><b>Invoice No:</b> {$invnum}</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<td colspan='2'><b>Proforma Inv No:</b> {$inv['docref']}</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<td colspan='2'><b>Sales Order No:</b> {$inv['ordno']}</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<td colspan='2'><b>Account No:</b> {$cust_data['accno']}</td>\n\t\t\t\t</tr>\n\t\t\t\t{$sp}\n\t\t\t</table>\n\t\t\t</td></tr>\n\t\t</table>\n\n\t\t<table cellpadding='0' cellspacing='0' width='85%' style='{$table_borders}'>\n\t\t\t<tr><td>\n\t\t\t<table cellpadding='2' cellspacing='0' border='0' width='100%'>\n\t\t\t\t<tr>\n\t\t\t\t\t<td align='center'><font size='4'><b>Tax Invoice To:</b></font></td>\n\t\t\t\t</tr>\n\t\t\t</table>\n\t\t\t</td></tr>\n\t\t</table>\n\n\t\t<table cellpadding='0' cellspacing='0' width='85%' style='{$table_borders}'>\n\t\t\t<tr><td>\n\t\t\t<table cellpadding='2' cellspacing='0' border='0' width='100%'>\n\t\t\t\t<tr>\n\t\t\t\t\t<td width='33%' style='border-right: 2px solid #000'><b>{$inv['surname']}</b></td>\n\t\t\t\t\t<td width='33%' style='border-right: 2px solid #000'><b>Postal Address</b></td>\n\t\t\t\t\t<td width='33%'><b>Delivery Address</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<td style='border-right: 2px solid #000'>" . nl2br($cust_data["addr1"]) . "</td>\n\t\t\t\t\t<td style='border-right: 2px solid #000'>" . nl2br($cust_data["paddr1"]) . "</td>\n\t\t\t\t\t<td>Branch: {$branchname}<br />" . nl2br($inv["del_addr"]) . "</td>\n\t\t\t\t</tr>\n\t\t\t</table>\n\t\t\t</td></tr>\n\t\t</table>\n\n\t\t<table cellpadding='0' cellspacing='0' width='85%' style='{$table_borders}'>\n\t\t\t<tr><td>\n\t\t\t<table cellpadding='2' cellspacing='0' border='0' width='100%'>\n\t\t\t\t<tr>\n\t\t\t\t\t<td width='33%' style='border-right: 2px solid #000'><b>Customer VAT No:</b> {$inv['cusvatno']}</td>\n\t\t\t\t\t<td width='33%' style='border-right: 2px solid #000'><b>Customer Order No:</b> {$inv['cordno']}</td>\n\t\t\t\t\t<td width='33%'><b>Delivery Date:</b> {$inv['deldate']}</td>\n\t\t\t\t</tr>\n\t\t\t</table>\n\t\t\t</td></tr>\n\t\t</table>\n\n\t\t<table cellpadding='0' cellspacing='0' width='85%' style='{$table_borders}'>\n\t\t\t<tr><td>\n\t\t\t<table cellpadding='2' cellspacing='0' border='0' width='100%'>\n\t\t\t\t<tr>\n\t\t\t\t\t<td style='border-bottom: 2px solid #000; border-right: 2px solid #000;'><b>Code</b></td>\n\t\t\t\t\t<td style='border-bottom: 2px solid #000; border-right: 2px solid #000;'><b>Description</b></td>\n\t\t\t\t\t<td style='border-bottom: 2px solid #000; border-right: 2px solid #000;'><b>Qty</b></td>\n\t\t\t\t\t<td style='border-bottom: 2px solid #000; border-right: 2px solid #000;' align='right'><b>Unit Price</b></td>\n\t\t\t\t\t<td style='border-bottom: 2px solid #000; border-right: 2px solid #000;' align='right'><b>Unit Discount</b></td>\n\t\t\t\t\t<td style='border-bottom: 2px solid #000' align='right'><b>Amount</b></td>\n\t\t\t\t</tr>\n\t\t\t\t{$products_out}\n\t\t\t</table>\n\t\t\t</td></tr>\n\t\t</table>\n\n\t\t<table cellpadding='0' cellspacing='0' width='85%' style='{$table_borders}'>\n\t\t\t<tr><td>\n\t\t\t<table cellpadding='2' cellspacing='0' border='0' width='100%'>\n\t\t\t\t<tr>\n\t\t\t\t\t<td><i>VAT Exempt Indicator: #</i></td>\n\t\t\t\t</tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<td>{$inv['comm']}</td>\n\t\t\t\t</tr>\n\t\t\t</table>\n\t\t</table>\n\n\t\t<table cellpadding='0' cellspacing='0' width='85%' style='border: 2px solid #000000'>\n\t\t\t<tr><td>\n\t\t\t<table cellpadding='2' cellspacing='0' border='0' width='100%'>\n\t\t\t\t<tr>\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Terms: {$inv['terms']} days</b></td>\n\t\t\t\t\t<td><b>Subtotal:</b></td>\n\t\t\t\t\t<td nowrap><b>" . CUR . " {$inv['subtot']}</b></td>\n\t\t\t\t</tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<td style='border-right: 2px solid #000'>&nbsp;</td>\n\t\t\t\t\t<td><b>Trade Discount:</b></td>\n\t\t\t\t\t<td nowrap><b>" . CUR . " {$inv['discount']}</b></td>\n\t\t\t\t</tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Received in good order by:</b>_____________________</td>\n\t\t\t\t\t<td><b>Delivery Charge</b></td>\n\t\t\t\t\t<td nowrap><b>" . CUR . " {$inv['delivery']}</b></td>\n\t\t\t\t</tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<td style='border-right: 2px solid #000'>&nbsp;</td>\n\t\t\t\t\t<td><b>VAT {$vat14}:</b></td>\n\t\t\t\t\t<td nowrap><b>" . CUR . " {$inv['vat']}</b></td>\n\t\t\t\t<tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Date:</b>_____________________</td>\n\t\t\t\t\t<td><b>Total Incl VAT:</b></td>\n\t\t\t\t\t<td nowrap><b>" . CUR . " {$inv['total']}</b></td>\n\t\t\t\t</tr>\n\t\t\t\t</tr>\n\t\t\t</table>\n\t\t</table>";
    }
    // Retrieve template settings from Cubit
    db_conn("cubit");
    $sql = "SELECT filename FROM template_settings WHERE template='invoices'";
    $tsRslt = db_exec($sql) or errDie("Unable to retrieve the template settings from Cubit.");
    $template = pg_fetch_result($tsRslt, 0);
    $OUTPUT = "\n\t\t<script>\n\t\t\tsCostCenter('dt', 'Sales', '{$inv['odate']}', 'Invoice No.{$invnum} for Customer {$inv['cusname']} {$inv['surname']}', '" . ($TOTAL - $VAT) . "', 'Cost Of Sales for Invoice No.{$invnum}', '{$tcosamt}', '');\n\t\t</script>";
    if (isset($email)) {
        $OUTPUT .= "\n\t\t\t<script>\n\t\t\t\tmove(\"invoices-email.php?evs={$inv['invid']}\");\n\t\t\t</script>";
        require "template.php";
    }
    if ($template == "invoice-print.php") {
        $OUTPUT .= $details;
        require "tmpl-print.php";
    } else {
        $OUTPUT .= "\n\t\t\t<script>\n\t\t\t\tmove(\"{$template}?invid={$inv['invid']}&type=inv\");\n\t\t\t</script>";
        require "template.php";
    }
}
コード例 #14
0
function write($_POST)
{
    # get vars
    foreach ($_POST as $key => $value) {
        ${$key} = $value;
    }
    if (isset($back)) {
        unset($_POST["back"]);
        return alloc($_POST);
    }
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($all, "num", 1, 1, "Invalid allocation.");
    $v->isOk($bankid, "num", 1, 30, "Invalid Bank Account.");
    $v->isOk($date, "date", 1, 14, "Invalid Date.");
    $v->isOk($out, "float", 1, 10, "Invalid out amount.");
    $v->isOk($descript, "string", 0, 255, "Invalid Description.");
    $v->isOk($cheqnum, "num", 0, 30, "Invalid Cheque number.");
    $v->isOk($amt, "float", 1, 10, "Invalid amount.");
    $v->isOk($cusid, "num", 1, 10, "Invalid customer number.");
    $v->isOk($out1, "float", 0, 10, "Invalid paid amount(currant).");
    $v->isOk($out2, "float", 0, 10, "Invalid paid amount(30).");
    $v->isOk($out3, "float", 0, 10, "Invalid paid amount(60).");
    $v->isOk($out4, "float", 0, 10, "Invalid paid amount(90).");
    $v->isOk($out5, "float", 0, 10, "Invalid paid amount(120).");
    if (isset($invids)) {
        foreach ($invids as $key => $value) {
            $v->isOk($invids[$key], "num", 1, 50, "Invalid Invoice No.");
            $v->isOk($paidamt[$key], "float", 1, 20, "Invalid amount to be paid.");
        }
    }
    # display errors, if any
    if ($v->isError()) {
        $confirm = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $confirm .= "<li class=err>" . $e["msg"];
        }
        $confirm .= "<p><input type=button onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $confirm;
    }
    pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
    # get hook account number
    core_connect();
    $sql = "SELECT * FROM bankacc WHERE accid = '{$bankid}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to retrieve bank account link from Cubit", SELF);
    # check if link exists
    if (pg_numrows($rslt) < 1) {
        return "<li class=err> ERROR : The bank account that you selected doesn't appear to have an account linked to it.";
    }
    $bank = pg_fetch_array($rslt);
    db_connect();
    # Customer name
    $sql = "SELECT cusnum,deptid,cusname,surname FROM customers WHERE cusnum = '{$cusid}' AND div = '" . USER_DIV . "'";
    $cusRslt = db_exec($sql);
    $cus = pg_fetch_array($cusRslt);
    db_conn("exten");
    # get debtors control account
    $sql = "SELECT debtacc FROM departments WHERE deptid ='{$cus['deptid']}' AND div = '" . USER_DIV . "'";
    $deptRslt = db_exec($sql);
    $dept = pg_fetch_array($deptRslt);
    # date format
    $sdate = explode("-", $date);
    $sdate = $sdate[2] . "-" . $sdate[1] . "-" . $sdate[0];
    $cheqnum = 0 + $cheqnum;
    $pay = "";
    $accdate = $sdate;
    # Paid invoices
    $invidsers = "";
    $rinvids = "";
    $amounts = "";
    $invprds = "";
    $rages = "";
    db_connect();
    if ($all == 0) {
        # Begin updates
        # pglib_transaction ("BEGIN") or errDie("Unable to start a database transaction.",SELF);
        # update the customer (make balance less)
        $sql = "UPDATE customers SET balance = (balance - '{$amt}'::numeric(13,2)) WHERE cusnum = '{$cus['cusnum']}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
        if (isset($invids)) {
            foreach ($invids as $key => $value) {
                $ii = $invids[$key];
                if (!isset($itype[$ii])) {
                    # Get debt invoice info
                    $sql = "SELECT prd,invnum FROM invoices WHERE invid ='{$invids[$key]}' AND div = '" . USER_DIV . "'";
                    $invRslt = db_exec($sql) or errDie("Unable to retrieve invoice details from database.");
                    if (pg_numrows($invRslt) < 1) {
                        return "<li class=err>Invalid Invoice Number.";
                    }
                    $inv = pg_fetch_array($invRslt);
                    # reduce the money that has been paid
                    $sql = "UPDATE invoices SET balance = (balance - {$paidamt[$key]}::numeric(13,2)) WHERE invid = '{$invids[$key]}' AND div = '" . USER_DIV . "'";
                    $payRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
                    $sql = "UPDATE  open_stmnt SET balance = (balance - {$paidamt[$key]}::numeric(13,2)) WHERE invid = '{$inv['invnum']}' AND div = '" . USER_DIV . "'";
                    $payRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
                    $inv['invnum'] += 0;
                    # record the payment on the statement
                    $sql = "INSERT INTO stmnt(cusnum, invid, amount, date, type, div) VALUES('{$cus['cusnum']}','{$inv['invnum']}','" . ($paidamt[$key] - $paidamt[$key] * 2) . "','{$sdate}', 'Payment for Invoice No. {$inv['invnum']}', '" . USER_DIV . "')";
                    $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
                    custledger($cus['cusnum'], $bank['accnum'], $sdate, $inv['invnum'], "Payment for Invoice No. {$inv['invnum']}", $paidamt[$key], "c");
                    db_connect();
                    $rinvids .= "|{$invids[$key]}";
                    $amounts .= "|{$paidamt[$key]}";
                    if ($inv['prd'] == 0) {
                        $inv['prd'] = PRD_DB;
                    }
                    $invprds .= "|{$inv['prd']}";
                    $rages .= "|0";
                    $invidsers .= " - {$inv['invnum']}";
                } else {
                    # Get debt invoice info
                    $sql = "SELECT prd,invnum,descrip,age FROM nons_invoices WHERE invid ='{$invids[$key]}' AND div = '" . USER_DIV . "'";
                    $invRslt = db_exec($sql) or errDie("Unable to retrieve invoice details from database.");
                    if (pg_numrows($invRslt) < 1) {
                        return "<li class=err>Invalid Invoice Number.";
                    }
                    $inv = pg_fetch_array($invRslt);
                    # reduce the money that has been paid
                    $sql = "UPDATE nons_invoices SET balance = (balance - {$paidamt[$key]}::numeric(13,2)) WHERE invid = '{$invids[$key]}' AND div = '" . USER_DIV . "'";
                    $payRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
                    $sql = "UPDATE  open_stmnt SET balance = (balance - {$paidamt[$key]}::numeric(13,2)) WHERE invid = '{$inv['invnum']}' AND div = '" . USER_DIV . "'";
                    $payRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
                    $inv['invnum'] += 0;
                    # record the payment on the statement
                    $sql = "INSERT INTO stmnt(cusnum, invid, amount, date, type, div) VALUES('{$cus['cusnum']}','{$inv['invnum']}','" . ($paidamt[$key] - $paidamt[$key] * 2) . "','{$sdate}', 'Payment for Non Stock Invoice No. {$inv['invnum']} - {$inv['descrip']}', '" . USER_DIV . "')";
                    $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
                    custledger($cus['cusnum'], $bank['accnum'], $sdate, $inv['invnum'], "Payment for Non Stock Invoice No. {$inv['invnum']} - {$inv['descrip']}", $paidamt[$key], "c");
                    db_connect();
                    recordCT($paidamt[$key], $cus['cusnum'], $inv['age'], $accdate);
                    $rinvids .= "|{$invids[$key]}";
                    $amounts .= "|{$paidamt[$key]}";
                    $invprds .= "|0";
                    $rages .= "|{$inv['age']}";
                    $invidsers .= " - {$inv['invnum']}";
                }
            }
        }
        # record the payment record
        $sql = "INSERT INTO cashbook(bankid, trantype, date, name, descript, cheqnum, amount, banked, accinv, cusnum, rinvids, amounts, invprds, rages, div) VALUES ('{$bankid}', 'deposit', '{$sdate}', '{$cus['cusname']} {$cus['surname']}', 'Payment for Invoices {$invidsers} from customer {$cus['cusname']} {$cus['surname']}', '{$cheqnum}', '{$amt}', 'no', '{$dept['debtacc']}', '{$cus['cusnum']}', '{$rinvids}', '{$amounts}', '{$invprds}', '{$rages}', '" . USER_DIV . "')";
        $Rslt = db_exec($sql) or errDie("Unable to add bank payment to database.", SELF);
        $refnum = getrefnum($accdate);
        db_conn('core');
        $Sl = "SELECT * FROM bankacc WHERE accid='{$bankid}'";
        $Rx = db_exec($Sl) or errDie("Uanble to get bank acc.");
        if (pg_numrows($Rx) < 1) {
            return "Invalid bank acc.";
        }
        $link = pg_fetch_array($Rx);
        writetrans($link['accnum'], $dept['debtacc'], $accdate, $refnum, $amt, "Payment for Invoices {$invidsers} from customer {$cus['cusname']} {$cus['surname']}");
        db_conn('cubit');
        if ($out > 0) {
            /* START OPEN ITEMS */
            $ox = "";
            db_conn('cubit');
            $Sl = "SELECT * FROM open_stmnt WHERE balance>0 AND cusnum='{$cusid}' ORDER BY date";
            $Ri = db_exec($Sl) or errDie("Unable to get open items.");
            $open_out = $out;
            $i = 0;
            while ($od = pg_fetch_array($Ri)) {
                if ($open_out == 0) {
                    continue;
                }
                $oid = $od['id'];
                if ($open_out >= $od['balance']) {
                    $open_amount[$oid] = $od['balance'];
                    $open_out = sprint($open_out - $od['balance']);
                    $ox .= "<tr class='" . bg_class() . "'><td><input type=hidden size=20 name=open[{$oid}] value='{$oid}'>{$od['type']}</td>\n\t\t\t\t\t\t<td>" . CUR . " {$od['balance']}</td><td>{$od['date']}</td><td><input type=hidden name='open_amount[{$oid}]' value='{$open_amount[$oid]}'>\n\t\t\t\t\t\t" . CUR . " {$open_amount[$oid]}</td></tr>";
                    $Sl = "UPDATE open_stmnt SET balance=balance-'{$open_amount[$oid]}' WHERE id='{$oid}'";
                    $Ri = db_exec($Sl) or errDie("Unable to update statement.");
                } elseif ($open_out < $od['balance']) {
                    $open_amount[$oid] = $open_out;
                    $open_out = 0;
                    $ox .= "<tr class='" . bg_class() . "'><td><input type=hidden size=20 name=open[{$oid}] value='{$od['id']}'>{$od['type']}</td>\n\t\t\t\t\t\t<td>" . CUR . " {$od['balance']}</td><td>{$od['date']}</td><td><input type=hidden name='open_amount[{$oid}]' value='{$open_amount[$oid]}'>\n\t\t\t\t\t\t" . CUR . " {$open_amount[$oid]}</td></tr>";
                    $Sl = "UPDATE open_stmnt SET balance=balance-'{$open_amount[$oid]}' WHERE id='{$oid}'";
                    $Ri = db_exec($Sl) or errDie("Unable to update statement.");
                }
                $i++;
            }
            if (open()) {
                // 					$confirm .= "<tr><td colspan=2><br></td></tr>
                // 					<tr><td colspan=2><h3>Outstanding Transactions</h3></td></tr>
                // 					<tr><th>Description</th><th>Outstanding Amount</th><th>Date</th><th>Amount</th></tr>";
                //$confirm.=$ox;
                $bout = $out;
                $out = $open_out;
                if ($out > 0) {
                    $sql = "INSERT INTO open_stmnt(cusnum, invid, amount, balance, date, type, st, div) VALUES('{$cus['cusnum']}', '0', '-{$out}', '-{$out}', '{$sdate}', 'Payment Received', 'n', '" . USER_DIV . "')";
                    $stmntRslt = db_exec($sql) or errDie("Unable to Insert statement record in Cubit.", SELF);
                    //$confirm .="<tr class='bg-even'><td colspan=4><b>A general transaction will credit the client's account with ".CUR." $out </b></td></tr>";
                }
                $out = $bout;
            } else {
                //$confirm .="<tr class='bg-even'><td colspan=4><b>A general transaction will credit the client's account with ".CUR." $out </b></td></tr>";}
            }
        }
        if ($out > 0) {
            recordCT($out, $cus['cusnum'], 0, $accdate);
            $Sl = "INSERT INTO stmnt(cusnum, invid, amount, date, type, div) VALUES('{$cus['cusnum']}','0','" . $out * -1 . "','{$sdate}', 'Payment Received.', '" . USER_DIV . "')";
            $Rs = db_exec($Sl) or errDie("Unable to insert statement record in Cubit.", SELF);
            custledger($cus['cusnum'], $bank['accnum'], $sdate, "PAYMENT", "Payment received.", $out, "c");
            db_connect();
        }
        # Commit updates
        # pglib_transaction ("COMMIT") or errDie("Unable to commit a database transaction.",SELF);
    }
    db_connect();
    if ($all == 1) {
        # Begin updates
        # pglib_transaction ("BEGIN") or errDie("Unable to start a database transaction.",SELF);
        # update the customer (make balance less)
        $sql = "UPDATE customers SET balance = (balance - '{$amt}'::numeric(13,2)) WHERE cusnum = '{$cus['cusnum']}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
        if (isset($invids)) {
            foreach ($invids as $key => $value) {
                $ii = $invids[$key];
                if (!isset($itype[$ii])) {
                    # Get debt invoice info
                    $sql = "SELECT prd,invnum FROM invoices WHERE invid ='{$invids[$key]}' AND div = '" . USER_DIV . "'";
                    $invRslt = db_exec($sql) or errDie("Unable to retrieve invoice details from database.");
                    if (pg_numrows($invRslt) < 1) {
                        return "<li class=err>Invalid Invoice Number.";
                    }
                    $inv = pg_fetch_array($invRslt);
                    # reduce the money that has been paid
                    $sql = "UPDATE invoices SET balance = (balance - {$paidamt[$key]}::numeric(13,2)) WHERE invid = '{$invids[$key]}' AND div = '" . USER_DIV . "'";
                    $payRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
                    $sql = "UPDATE  open_stmnt SET balance = (balance - {$paidamt[$key]}::numeric(13,2)) WHERE invid = '{$inv['invnum']}' AND div = '" . USER_DIV . "'";
                    $payRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
                    $inv['invnum'] += 0;
                    # record the payment on the statement
                    $sql = "INSERT INTO stmnt(cusnum, invid, amount, date, type, div) VALUES('{$cus['cusnum']}','{$inv['invnum']}','" . ($paidamt[$key] - $paidamt[$key] * 2) . "','{$sdate}', 'Payment for Invoice No. {$inv['invnum']}', '" . USER_DIV . "')";
                    $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
                    custledger($cus['cusnum'], $bank['accnum'], $sdate, $inv['invnum'], "Payment for Invoice No. {$inv['invnum']}", $paidamt[$key], "c");
                    db_connect();
                    $rinvids .= "|{$invids[$key]}";
                    $amounts .= "|{$paidamt[$key]}";
                    if ($inv['prd'] == 0) {
                        $inv['prd'] = PRD_DB;
                    }
                    $invprds .= "|{$inv['prd']}";
                    $rages .= "|0";
                    $invidsers .= " - {$inv['invnum']}";
                } else {
                    # Get debt invoice info
                    $sql = "SELECT prd,invnum,descrip,age FROM nons_invoices WHERE invid ='{$invids[$key]}' AND div = '" . USER_DIV . "'";
                    $invRslt = db_exec($sql) or errDie("Unable to retrieve invoice details from database.");
                    if (pg_numrows($invRslt) < 1) {
                        return "<li class=err>Invalid Invoice Number.";
                    }
                    $inv = pg_fetch_array($invRslt);
                    # reduce the money that has been paid
                    $sql = "UPDATE nons_invoices SET balance = (balance - {$paidamt[$key]}::numeric(13,2)) WHERE invid = '{$invids[$key]}' AND div = '" . USER_DIV . "'";
                    $payRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
                    $inv['invnum'] += 0;
                    # record the payment on the statement
                    $sql = "INSERT INTO stmnt(cusnum, invid, amount, date, type, div) VALUES('{$cus['cusnum']}','{$inv['invnum']}','" . ($paidamt[$key] - $paidamt[$key] * 2) . "','{$sdate}', 'Payment for Non Stock Invoice No. {$inv['invnum']} - {$inv['descrip']}', '" . USER_DIV . "')";
                    $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
                    $sql = "UPDATE  open_stmnt SET balance = (balance - {$paidamt[$key]}::numeric(13,2)) WHERE invid = '{$inv['invnum']}' AND div = '" . USER_DIV . "'";
                    $payRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
                    custledger($cus['cusnum'], $bank['accnum'], $sdate, $inv['invnum'], "Payment for Non Stock Invoice No. {$inv['invnum']} - {$inv['descrip']}", $paidamt[$key], "c");
                    db_connect();
                    recordCT($paidamt[$key], $cus['cusnum'], $inv['age'], $accdate);
                    $rinvids .= "|{$invids[$key]}";
                    $amounts .= "|{$paidamt[$key]}";
                    $invprds .= "|0";
                    $rages .= "|{$inv['age']}";
                    $invidsers .= " - {$inv['invnum']}";
                }
            }
        }
        # record the payment record
        $sql = "INSERT INTO cashbook(bankid, trantype, date, name, descript, cheqnum, amount, banked, accinv, cusnum, rinvids, amounts, invprds, rages, div) VALUES ('{$bankid}', 'deposit', '{$sdate}', '{$cus['cusname']} {$cus['surname']}', 'Payment for Invoices {$invidsers} from customer {$cus['cusname']} {$cus['surname']}', '{$cheqnum}', '{$amt}', 'no', '{$dept['debtacc']}', '{$cus['cusnum']}', '{$rinvids}', '{$amounts}', '{$invprds}', '{$rages}', '" . USER_DIV . "')";
        $Rslt = db_exec($sql) or errDie("Unable to add bank payment to database.", SELF);
        $refnum = getrefnum($accdate);
        db_conn('core');
        $Sl = "SELECT * FROM bankacc WHERE accid='{$bankid}'";
        $Rx = db_exec($Sl) or errDie("Uanble to get bank acc.");
        if (pg_numrows($Rx) < 1) {
            return "Invalid bank acc.";
        }
        $link = pg_fetch_array($Rx);
        writetrans($link['accnum'], $dept['debtacc'], $accdate, $refnum, $amt, "Payment for Invoices {$invidsers} from customer {$cus['cusname']} {$cus['surname']}");
        db_conn('cubit');
        if ($out1 + $out2 + $out3 + $out4 + $out5 > 0) {
            $Sl = "INSERT INTO stmnt(cusnum, invid, amount, date, type, div) VALUES('{$cus['cusnum']}','0','" . ($out1 + $out2 + $out3 + $out4 + $out5) * -1 . "','{$sdate}', 'Payment Received.', '" . USER_DIV . "')";
            $Rs = db_exec($Sl) or errDie("Unable to insert statement record in Cubit.", SELF);
            custledger($cus['cusnum'], $bank['accnum'], $sdate, "PAYMENT", "Payment received.", $out1 + $out2 + $out3 + $out4 + $out5, "c");
            db_connect();
        }
        if ($out1 > 0) {
            recordCT($out1, $cus['cusnum'], 0, $accdate);
        }
        if ($out2 > 0) {
            recordCT($out2, $cus['cusnum'], 1, $accdate);
        }
        if ($out3 > 0) {
            recordCT($out3, $cus['cusnum'], 2, $accdate);
        }
        if ($out4 > 0) {
            recordCT($out4, $cus['cusnum'], 3, $accdate);
        }
        if ($out5 > 0) {
            recordCT($out5, $cus['cusnum'], 4, $accdate);
        }
        # Commit updates
        # pglib_transaction ("COMMIT") or errDie("Unable to commit a database transaction.",SELF);
    }
    if ($all == 2) {
        # Begin updates
        //pglib_transaction ("BEGIN") or errDie("Unable to start a database transaction.",SELF);
        # update the customer (make balance less)
        $sql = "UPDATE customers SET balance = (balance - '{$amt}'::numeric(13,2)) WHERE cusnum = '{$cus['cusnum']}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
        # Debtors
        foreach ($invids as $key => $value) {
            $ii = $invids[$key];
            if (!isset($itype[$ii])) {
                # Get debt invoice info
                $sql = "SELECT prd,invnum FROM invoices WHERE invid ='{$invids[$key]}' AND div = '" . USER_DIV . "'";
                $invRslt = db_exec($sql) or errDie("Unable to retrieve invoice details from database.");
                if (pg_numrows($invRslt) < 1) {
                    return "<li class=err>Invalid Invoice Number.";
                }
                $inv = pg_fetch_array($invRslt);
                # reduce the money that has been paid
                $sql = "UPDATE invoices SET balance = (balance - {$paidamt[$key]}::numeric(13,2)) WHERE invid = '{$invids[$key]}' AND div = '" . USER_DIV . "'";
                $payRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
                $sql = "UPDATE  open_stmnt SET balance = (balance - {$paidamt[$key]}::numeric(13,2)) WHERE invid = '{$inv['invnum']}' AND div = '" . USER_DIV . "'";
                $payRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
                # record the payment on the statement
                $sql = "INSERT INTO stmnt(cusnum, invid, amount, date, type, div) VALUES('{$cus['cusnum']}','{$inv['invnum']}','" . ($paidamt[$key] - $paidamt[$key] * 2) . "','{$sdate}', 'Payment for Invoice No. {$inv['invnum']}', '" . USER_DIV . "')";
                $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
                custledger($cus['cusnum'], $bank['accnum'], $sdate, $inv['invnum'], "Payment for Invoice No. {$inv['invnum']}", $paidamt[$key], "c");
                db_connect();
                $rinvids .= "|{$invids[$key]}";
                $amounts .= "|{$paidamt[$key]}";
                if ($inv['prd'] == 0) {
                    $inv['prd'] = PRD_DB;
                }
                $invprds .= "|{$inv['prd']}";
                $rages .= "|0";
                $invidsers .= " - {$inv['invnum']}";
            } else {
                # Get debt invoice info
                $sql = "SELECT prd,invnum,descrip,age FROM nons_invoices WHERE invid ='{$invids[$key]}' AND div = '" . USER_DIV . "'";
                $invRslt = db_exec($sql) or errDie("Unable to retrieve invoice details from database.");
                if (pg_numrows($invRslt) < 1) {
                    return "<li class=err>Invalid Invoice Number.";
                }
                $inv = pg_fetch_array($invRslt);
                # reduce the money that has been paid
                $sql = "UPDATE nons_invoices SET balance = (balance - {$paidamt[$key]}::numeric(13,2)) WHERE invid = '{$invids[$key]}' AND div = '" . USER_DIV . "'";
                $payRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
                $sql = "UPDATE  open_stmnt SET balance = (balance - {$paidamt[$key]}::numeric(13,2)) WHERE invid = '{$inv['invnum']}' AND div = '" . USER_DIV . "'";
                $payRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
                # record the payment on the statement
                $sql = "INSERT INTO stmnt(cusnum, invid, amount, date, type, div) VALUES('{$cus['cusnum']}','{$inv['invnum']}','" . ($paidamt[$key] - $paidamt[$key] * 2) . "','{$sdate}', 'Payment for Non Stock Invoice No. {$inv['invnum']} - {$inv['descrip']}', '" . USER_DIV . "')";
                $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
                custledger($cus['cusnum'], $bank['accnum'], $sdate, $inv['invnum'], "Payment for Non Stock Invoice No. {$inv['invnum']} - {$inv['descrip']}", $paidamt[$key], "c");
                db_connect();
                recordCT($paidamt[$key], $cus['cusnum'], $inv['age'], $accdate);
                $rinvids .= "|{$invids[$key]}";
                $amounts .= "|{$paidamt[$key]}";
                $invprds .= "|0";
                $rages .= "|{$inv['age']}";
                $invidsers .= " - {$inv['invnum']}";
            }
        }
        if (open()) {
            db_conn('cubit');
            $Sl = "SELECT * FROM open_stmnt WHERE balance>0 AND cusnum='{$cusid}' ORDER BY date";
            $Ri = db_exec($Sl) or errDie("Unable to get open items.");
            //$open_out=$out;
            $ox = "";
            $i = 0;
            while ($od = pg_fetch_array($Ri)) {
                $oid = $od['id'];
                if ($open_amount[$oid] == 0) {
                    continue;
                }
                $ox .= "<tr class='" . bg_class() . "'><td><input type=hidden size=20 name=open[{$oid}] value='{$oid}'>{$od['type']}</td>\n\t\t\t\t\t<td>" . CUR . " {$od['balance']}</td><td>{$od['date']}</td><td><input type=hidden name='open_amount[{$oid}]' value='{$open_amount[$oid]}'>\n\t\t\t\t\t" . CUR . " {$open_amount[$oid]}</td></tr>";
                $i++;
                $sql = "UPDATE  open_stmnt SET balance = (balance - {$open_amount[$oid]} ::numeric(13,2)) WHERE id = '{$oid}' AND div = '" . USER_DIV . "'";
                $payRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
                # record the payment on the statement
                $sql = "INSERT INTO stmnt(cusnum, invid, amount, date, type, div) VALUES('{$cus['cusnum']}','0','" . -$open_amount[$oid] . "','{$sdate}', 'Payment received', '" . USER_DIV . "')";
                $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
                custledger($cus['cusnum'], $bank['accnum'], $sdate, 0, "Payment received", $open_amount[$oid], "c");
                db_connect();
                recordCT($open_amount[$oid], $cus['cusnum'], 0, $accdate);
            }
        }
        # record the payment record
        $sql = "INSERT INTO cashbook(bankid, trantype, date, name, descript, cheqnum, amount, banked, accinv, cusnum, rinvids, amounts, invprds, rages, div) VALUES ('{$bankid}', 'deposit', '{$sdate}', '{$cus['cusname']} {$cus['surname']}', 'Payment for Invoices {$invidsers} from customer {$cus['cusname']} {$cus['surname']}', '{$cheqnum}', '{$amt}', 'no', '{$dept['debtacc']}', '{$cus['cusnum']}', '{$rinvids}', '{$amounts}', '{$invprds}', '{$rages}', '" . USER_DIV . "')";
        $Rslt = db_exec($sql) or errDie("Unable to add bank payment to database.", SELF);
        $refnum = getrefnum($accdate);
        db_conn('core');
        $Sl = "SELECT * FROM bankacc WHERE accid='{$bankid}'";
        $Rx = db_exec($Sl) or errDie("Uanble to get bank acc.");
        if (pg_numrows($Rx) < 1) {
            return "Invalid bank acc.";
        }
        $link = pg_fetch_array($Rx);
        writetrans($link['accnum'], $dept['debtacc'], $accdate, $refnum, $amt, "Payment for Invoices {$invidsers} from customer {$cus['cusname']} {$cus['surname']}");
        # Commit updates
        //pglib_transaction ("COMMIT") or errDie("Unable to commit a database transaction.",SELF);
    }
    db_conn('cubit');
    /* start moving invoices */
    # move invoices that are fully paid
    $sql = "SELECT * FROM invoices WHERE balance = 0 AND printed = 'y' AND done = 'y' AND div = '" . USER_DIV . "'";
    $invbRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
    while ($invb = pg_fetch_array($invbRslt)) {
        if ($invb['prd'] == 0) {
            $invb['prd'] = PRD_DB;
        }
        db_conn($invb['prd']);
        # Insert invoice to period DB
        $sql = "INSERT INTO invoices(invid,invnum, deptid, cusnum, deptname, cusacc, cusname, surname, cusaddr, cusvatno, cordno, ordno, chrgvat, terms, traddisc, salespn, odate, delchrg, subtot, vat, total, balance, age, comm, discount, delivery, printed, done, username, docref, div,prd,delvat)";
        $sql .= " VALUES('{$invb['invid']}','{$invb['invnum']}', '{$invb['deptid']}', '{$invb['cusnum']}', '{$invb['deptname']}', '{$invb['cusacc']}', '{$invb['cusname']}', '{$invb['surname']}', '{$invb['cusaddr']}', '{$invb['cusvatno']}', '{$invb['cordno']}', '{$invb['ordno']}', '{$invb['chrgvat']}', '{$invb['terms']}', '{$invb['traddisc']}', '{$invb['salespn']}', '{$invb['odate']}', '{$invb['delchrg']}', '{$invb['subtot']}', '{$invb['vat']}' , '{$invb['total']}', '0', '{$invb['age']}', '{$invb['comm']}', '{$invb['discount']}', '{$invb['delivery']}', 'y', 'y', '" . USER_NAME . "', '{$invb['docref']}','" . USER_DIV . "','{$invb['prd']}','{$invb['delvat']}')";
        $rslt = db_exec($sql) or errDie("Unable to insert invoice to the period database.", SELF);
        db_connect();
        $sql = "INSERT INTO movinv(invtype, invnum, prd, docref, div) VALUES('inv', '{$invb['invnum']}', '{$invb['prd']}', '{$invb['docref']}', '" . USER_DIV . "')";
        $rslt = db_exec($sql) or errDie("Unable to insert invoice to the period database.", SELF);
        # get selected stock in this invoice
        db_connect();
        $sql = "SELECT * FROM inv_items WHERE invid = '{$invb['invid']}' AND div = '" . USER_DIV . "'";
        $stkdRslt = db_exec($sql);
        while ($stkd = pg_fetch_array($stkdRslt)) {
            db_conn($invb['prd']);
            $stkd['vatcode'] += 0;
            $stkd['account'] += 0;
            # insert invoice items
            $sql = "INSERT INTO inv_items(invid, whid, stkid, qty, unitcost, amt, disc, discp, div,vatcode,account,description) VALUES\n\t\t\t('{$invb['invid']}', '{$stkd['whid']}', '{$stkd['stkid']}', '{$stkd['qty']}', '{$stkd['unitcost']}', '{$stkd['amt']}', '{$stkd['disc']}', '{$stkd['discp']}', '" . USER_DIV . "','{$stkd['vatcode']}','{$stkd['account']}','{$stkd['description']}')";
            $rslt = db_exec($sql) or errDie("Unable to insert invoice items to Cubit.", SELF);
        }
        db_connect();
        # Remove those invoices from running DB
        $sql = "DELETE FROM invoices WHERE invid = '{$invb['invid']}' AND div = '" . USER_DIV . "'";
        $delRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
        # Remove those invoice items from running DB
        $sql = "DELETE FROM inv_items WHERE invid = '{$invb['invid']}' AND div = '" . USER_DIV . "'";
        $delRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
    }
    pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
    /* end moving invoices */
    # status report
    $write = "\n        <table border=0 cellpadding='" . TMPL_tblCellPadding . "' cellspacing='" . TMPL_tblCellSpacing . "' width='100%'>\n        <tr><th>Bank Receipt</th></tr>\n        <tr class=datacell><td>Bank Receipt added to cash book.</td></tr>\n        </table>";
    # main table (layout with menu)
    $OUTPUT = "<center>\n        <table width = 90%>\n        <tr valign=top><td width=50%>{$write}</td>\n        <td align=center>\n        <table border=0 cellpadding='" . TMPL_tblCellPadding . "' cellspacing='" . TMPL_tblCellSpacing . "' width=80%>\n        <tr><th>Quick Links</th></tr>\n        <tr class='bg-odd'><td><a href='bank-pay-add.php'>Add Bank Payment</a></td></tr>\n        <tr class='bg-odd'><td><a href='bank-recpt-add.php'>Add Bank Receipt</a></td></tr>\n        <tr class='bg-odd'><td><a href='bank-recpt-inv.php'>Add Customer Payment</a></td></tr>\n\t\t<tr class='bg-odd'><td><a href='cashbook-view.php'>View Cash Book</a></td></tr>\n\t\t<script>document.write(getQuicklinkSpecial());</script>\n\t\t<tr class='bg-odd'><td><a href='../main.php'>Main Menu</a></td></tr>\n        </table>\n        </td></tr></table>";
    return $OUTPUT;
}
コード例 #15
0
function details($_GET)
{
    $showvat = TRUE;
    # get vars
    extract($_GET);
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($invid, "num", 1, 20, "Invalid invoice number.");
    # display errors, if any
    if ($v->isError()) {
        $err = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $err .= "<li class='err'>" . $e["msg"] . "</li>";
        }
        $confirm .= "<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $confirm;
    }
    db_connect();
    # Get invoice info
    $sql = "SELECT * FROM invoices WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
    $invRslt = db_exec($sql) or errDie("Unable to get invoice information");
    if (pg_numrows($invRslt) < 1) {
        return "<i class='err'>Not Found</i>";
    }
    $inv = pg_fetch_array($invRslt);
    $td = $inv['odate'];
    # CHECK IF THIS DATE IS IN THE BLOCKED RANGE
    $blocked_date_from = getCSetting("BLOCKED_FROM");
    $blocked_date_to = getCSetting("BLOCKED_TO");
    if (strtotime($td) >= strtotime($blocked_date_from) and strtotime($td) <= strtotime($blocked_date_to) and !user_is_admin(USER_ID)) {
        return "<li class='err'>Period Range Is Blocked. Only an administrator can process entries within this period.</li>";
    }
    $sql = "SELECT stkid FROM inv_items WHERE invid = '{$inv['invid']}' AND div = '" . USER_DIV . "'";
    $crslt = db_exec($sql);
    if (pg_numrows($crslt) < 1) {
        $error = "<li class='err'> Error : Invoice number <b>{$invid}</b> has no items.</li>";
        $error .= "<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $error;
    }
    # check if invoice has been printed
    if ($inv['printed'] == "y") {
        $error = "<li class='err'> Error : Invoice number <b>{$invid}</b> has already been printed.</li>";
        $error .= "<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $error;
    }
    # check if invoice has been serialised
    if ($inv['serd'] == "n") {
        $error = "<li class='err'> Error : You must select serial numbers for some Items on Invoice No. <b>T {$invid}</b> before you can print it.</li>";
        $error .= "<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $error;
    }
    cus_xrate_update($inv['fcid'], $inv['xrate']);
    # Begin Updates
    pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
    $invnum = divlastid('inv', USER_DIV);
    $Sl = "INSERT INTO ncsrec (oldnum, newnum, div) VALUES ('{$invid}', '{$invnum}', '" . USER_DIV . "')";
    $Rs = db_exec($Sl) or errDie("Unable to insert into db");
    # Get department
    db_conn("exten");
    $sql = "SELECT * FROM departments WHERE deptid = '{$inv['deptid']}' AND div = '" . USER_DIV . "'";
    $deptRslt = db_exec($sql);
    if (pg_numrows($deptRslt) < 1) {
        $dept['deptname'] = "<i class='err'>Not Found</i>";
    } else {
        $dept = pg_fetch_array($deptRslt);
    }
    /* --- Start Products Display --- */
    # Products layout
    $commision = 0;
    $products = "";
    $disc = 0;
    # get selected stock in this invoice
    db_connect();
    $sql = "SELECT * FROM inv_items  WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
    $stkdRslt = db_exec($sql);
    $taxex = 0;
    while ($stkd = pg_fetch_array($stkdRslt)) {
        # get warehouse name
        db_conn("exten");
        $sql = "SELECT whname FROM warehouses WHERE whid = '{$stkd['whid']}' AND div = '" . USER_DIV . "'";
        $whRslt = db_exec($sql);
        $wh = pg_fetch_array($whRslt);
        # get selected stock in this warehouse
        db_connect();
        $sql = "SELECT * FROM stock WHERE stkid = '{$stkd['stkid']}' AND div = '" . USER_DIV . "'";
        $stkRslt = db_exec($sql);
        $stk = pg_fetch_array($stkRslt);
        $Sl = "SELECT * FROM vatcodes WHERE id='{$stkd['vatcode']}'";
        $Ri = db_exec($Sl);
        if (pg_num_rows($Ri) < 1) {
            return "Please select the vatcode for all your stock.";
        }
        $vd = pg_fetch_array($Ri);
        $sp = "";
        # Check Tax Excempt
        if ($stk['exvat'] == 'yes' || $vd['zero'] == "Yes") {
            $taxex += $stkd['amt'];
            $ex = "#";
        } else {
            $ex = "";
        }
        # all must be excempted
        if ($inv['chrgvat'] == 'nov') {
            $ex = "#";
        }
        # Keep track of discounts
        $disc += $stkd['disc'] * $stkd['qty'];
        # Insert stock record
        $sdate = date("Y-m-d");
        $csprice = sprint($stk['csprice'] * $stkd['qty']);
        # Get amount exluding vat if including and not exempted
        $VATP = TAX_VAT;
        $amtexvat = sprint($stkd['famt']);
        if ($inv['chrgvat'] == "inc" && $stk['exvat'] != 'yes') {
            $amtexvat = sprint($stkd['famt'] * 100 / (100 + $VATP));
        }
        db_connect();
        $sql = "\n\t\t\tINSERT INTO stockrec (\n\t\t\t\tedate, stkid, stkcod, stkdes, trantype, qty, csprice, csamt, \n\t\t\t\tdetails, div\n\t\t\t) VALUES (\n\t\t\t\t'{$td}', '{$stkd['stkid']}', '{$stk['stkcod']}', '{$stk['stkdes']}', 'invoice', '{$stkd['qty']}', '{$amtexvat}', '{$csprice}', \n\t\t\t\t'Stock sold - Invoice No. {$invnum}', '" . USER_DIV . "'\n\t\t\t)";
        $recRslt = db_exec($sql);
        # Sales rep commission
        $commision = $commision + coms($inv['salespn'], $stkd['amt'], $stk['com']);
        # Put in product
        $products .= "\n\t\t\t<tr valign='top'>\n\t\t\t\t<td>{$stk['stkcod']}</td>\n\t\t\t\t<td>{$ex} {$sp} {$stk['stkdes']}</td>\n\t\t\t\t<td>" . sprint3($stkd['qty']) . "</td>\n\t\t\t\t<td>{$inv['currency']} " . sprint($stkd['unitcost']) . "</td>\n\t\t\t\t<td>{$inv['currency']} {$stkd['disc']}</td>\n\t\t\t\t<td>{$inv['currency']} {$stkd['amt']}</td>\n\t\t\t</tr>";
    }
    /* --- Start Some calculations --- */
    # Subtotal
    $SUBTOT = sprint($inv['subtot']);
    # Calculate subtotal
    $VATP = TAX_VAT;
    $SUBTOTAL = sprint($inv['subtot']);
    $VAT = sprint($inv['vat']);
    $TOTAL = sprint($inv['total']);
    $inv['delchrg'] = sprint($inv['delchrg']);
    $FSUBTOT = sprint($inv['subtot'] * $inv['xrate']);
    $FVAT = sprint($inv['vat'] * $inv['xrate']);
    $FTOTAL = sprint($inv['total'] * $inv['xrate']);
    $fdelchrg = sprint($inv['delchrg'] * $inv['xrate']);
    $ftraddiscm = sprint($inv['discount'] * $inv['xrate']);
    com_invoice($inv['salespn'], $FTOTAL, $commision * $inv['xrate'], $invnum, $td);
    /* --- End Some calculations --- */
    /* - Start Hooks - */
    $vatacc = gethook("accnum", "salesacc", "name", "VAT", "int");
    /* - End Hooks - */
    # Todays date
    $date = date("d-m-Y");
    $sdate = date("Y-m-d");
    $refnum = getrefnum();
    /*$refnum*/
    /* --- Updates ---- */
    db_connect();
    $Sql = "UPDATE invoices SET printed ='y', done ='y', invnum='{$invnum}' WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
    $upRslt = db_exec($Sql) or errDie("Unable to update invoice information");
    # Record the payment on the statement
    $sql = "\n\t\tINSERT INTO stmnt (\n\t\t\tcusnum, invid, amount, date, type, div, allocation_date\n\t\t) VALUES (\n\t\t\t'{$inv['cusnum']}','{$invnum}', '{$TOTAL}', '{$inv['odate']}', 'Invoice', '" . USER_DIV . "', '{$inv['odate']}'\n\t\t)";
    $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
    # Record the payment on the statement
    $sql = "\n\t\tINSERT INTO open_stmnt (\n\t\t\tcusnum, invid, amount, balance, date, type, div\n\t\t) VALUES (\n\t\t\t'{$inv['cusnum']}', '{$invnum}', '{$TOTAL}', '{$TOTAL}', '{$inv['odate']}', 'Invoice', '" . USER_DIV . "'\n\t\t)";
    $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
    # Save invoice discount
    $sql = "\n\t\tINSERT INTO inv_discs (\n\t\t\tcusnum, invid, traddisc, itemdisc, inv_date, delchrg, div, \n\t\t\ttotal\n\t\t) VALUES (\n\t\t\t'{$inv['cusnum']}', '{$invnum}', '{$ftraddiscm}', '{$disc}', '{$inv['odate']}', '{$fdelchrg}', '" . USER_DIV . "', \n\t\t\t({$FSUBTOT}+{$fdelchrg})\n\t\t)";
    $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
    # Update the customer (make balance more)
    $sql = "UPDATE customers SET balance = (balance + '{$FTOTAL}'), fbalance = (fbalance + '{$TOTAL}') WHERE cusnum = '{$inv['cusnum']}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
    # Make ledge record
    custledger($inv['cusnum'], $dept['incacc'], $td, $invnum, "Invoice No. {$invnum}", $FTOTAL, "d");
    db_connect();
    # get selected stock in this invoice
    $sql = "SELECT * FROM inv_items  WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
    $stkdRslt = db_exec($sql);
    $tcosamt = 0;
    while ($stkd = pg_fetch_array($stkdRslt)) {
        db_connect();
        # get selamt from selected stock
        $sql = "SELECT * FROM stock WHERE stkid = '{$stkd['stkid']}' AND div = '" . USER_DIV . "'";
        $stkRslt = db_exec($sql);
        $stk = pg_fetch_array($stkRslt);
        # cost amount
        $cosamt = round($stkd['qty'] * $stk['csprice'], 2);
        # update stock(alloc - qty)
        $sql = "UPDATE stock SET csamt = (csamt - '{$cosamt}'),units = (units - '{$stkd['qty']}'),alloc = (alloc - '{$stkd['qty']}')  WHERE stkid = '{$stkd['stkid']}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update stock to Cubit.", SELF);
        ###################VAT CALCS#######################
        $Sl = "SELECT * FROM vatcodes WHERE id='{$stkd['vatcode']}'";
        $Ri = db_exec($Sl);
        if (pg_num_rows($Ri) < 1) {
            return "Please select the vatcode for all your stock.";
        }
        $vd = pg_fetch_array($Ri);
        if ($stk['exvat'] == 'yes' || $vd['zero'] == "Yes") {
            $excluding = "y";
        } else {
            $excluding = "";
        }
        if (TAX_VAT != $vd['vat_amount'] and $vd['vat_amount'] != "0.00") {
            $showvat = FALSE;
        }
        $vr = vatcalc($stkd['amt'], $inv['chrgvat'], $excluding, $inv['traddisc'], $vd['vat_amount']);
        $vrs = explode("|", $vr);
        $ivat = $vrs[0];
        $iamount = $vrs[1];
        $iamount = $iamount * $inv['xrate'];
        $ivat = $ivat * $inv['xrate'];
        vatr($vd['id'], $inv['odate'], "OUTPUT", $vd['code'], $refnum, "VAT for Invoice No.{$invnum} for Customer : {$inv['cusname']} {$inv['surname']}", $iamount, $ivat);
        ####################################################
        if ($stk['serd'] == 'yes') {
            ext_invSer($stkd['serno'], $stkd['stkid'], "{$inv['cusname']} {$inv['surname']}", $invnum);
        }
        # stkid, stkcod, stkdes, trantype, edate, qty, csamt, details
        $sdate = date("Y-m-d");
        stockrec($stk['stkid'], $stk['stkcod'], $stk['stkdes'], 'ct', $td, $stkd['qty'], $cosamt, "Sold to Customer : {$inv['surname']} - Invoice No. {$invnum}");
        # get accounts
        db_conn("exten");
        $sql = "SELECT stkacc,cosacc FROM warehouses WHERE whid = '{$stkd['whid']}' AND div = '" . USER_DIV . "'";
        $whRslt = db_exec($sql);
        $wh = pg_fetch_array($whRslt);
        $stockacc = $wh['stkacc'];
        $cosacc = $wh['cosacc'];
        # dt(cos) ct(stock)
        writetrans($cosacc, $stockacc, $td, $refnum, $cosamt, "Cost Of Sales for Invoice No.{$invnum} for Customer : {$inv['cusname']} {$inv['surname']}");
        $tcosamt += $cosamt;
    }
    ###################VAT CALCS#######################
    $inv['delvat'] += 0;
    db_conn('cubit');
    $Sl = "SELECT * FROM vatcodes WHERE id='{$inv['delvat']}'";
    $Ri = db_exec($Sl);
    if (pg_num_rows($Ri) < 1) {
        $Sl = "SELECT * FROM vatcodes";
        $Ri = db_exec($Sl);
    }
    $vd = pg_fetch_array($Ri);
    if ($vd['zero'] == "Yes") {
        $excluding = "y";
    } else {
        $excluding = "";
    }
    $vr = vatcalc($inv['delchrg'], $inv['chrgvat'], $excluding, $inv['traddisc'], $vd['vat_amount']);
    $vrs = explode("|", $vr);
    $ivat = $vrs[0];
    $iamount = $vrs[1];
    $iamount = $iamount * $inv['xrate'];
    $ivat = $ivat * $inv['xrate'];
    vatr($vd['id'], $inv['odate'], "OUTPUT", $vd['code'], $refnum, "VAT for Invoice No.{$invnum} for Customer : {$inv['cusname']} {$inv['surname']}", $iamount, $ivat);
    ####################################################
    /* - Start Transactoins - */
    # dt(debtors) ct(income/sales)
    writetrans($dept['debtacc'], $dept['incacc'], $td, $refnum, $FTOTAL - $FVAT, "Debtors Control for Invoice No.{$invnum} for Customer : {$inv['cusname']} {$inv['surname']}");
    # dt(debtors) ct(vat account)
    writetrans($dept['debtacc'], $vatacc, $td, $refnum, $FVAT, "VAT Received on Invoice No.{$invnum} for Customer : {$inv['cusname']} {$inv['surname']}");
    db_connect();
    $sql = "\n\t\tINSERT INTO salesrec (\n\t\t\tedate, invid, invnum, debtacc, vat, total, typ, div\n\t\t) VALUES (\n\t\t\t'{$inv['odate']}', '{$invid}', '{$invnum}', '{$dept['debtacc']}', '{$FVAT}', '{$FTOTAL}', 'stk', '" . USER_DIV . "'\n\t\t)";
    $recRslt = db_exec($sql);
    db_conn('cubit');
    $Sl = "\n\t\tINSERT INTO sj (\n\t\t\tcid, name, des, date, exl, vat, inc, div\n\t\t) VALUES (\n\t\t\t'{$inv['cusnum']}', '{$inv['surname']}', 'International Invoice {$invnum}', '{$inv['odate']}', '" . sprint($FTOTAL - $FVAT) . "', \n\t\t\t'{$FVAT}', '" . sprint($FTOTAL) . "', '" . USER_DIV . "'\n\t\t)";
    $Ri = db_exec($Sl);
    # Commit updates
    pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
    /* - End Transactoins - */
    # vat explanation
    if ($inv['chrgvat'] == 'nov') {
        $expl = "VAT Exempt indicator";
    } else {
        $expl = "0% VAT indicator";
        $expl = "VAT Exempt indicator";
    }
    # Avoid little box, <table border=1> <-- ehhhemm !!
    if (strlen($inv['comm']) > 0) {
        $inv['comm'] = "\n\t\t\t<table border='1' cellspacing='0' bordercolor='#000000'>\n\t\t\t\t<tr>\n\t\t\t\t\t<td>" . nl2br($inv['comm']) . "</td>\n\t\t\t\t</tr>\n\t\t\t</table>";
    }
    if ($inv['chrgvat'] == "inc") {
        $inv['chrgvat'] = "Inclusive";
    } elseif ($inv['chrgvat'] == "exc") {
        $inv['chrgvat'] = "Exclusive";
    } else {
        $inv['chrgvat'] = "No vat";
    }
    if (!isset($showvat)) {
        $showvat = TRUE;
    }
    if ($showvat == TRUE) {
        $vat14 = AT14;
    } else {
        $vat14 = "";
    }
    $cc = "<script> sCostCenter('dt', 'Sales', '{$inv['odate']}', 'Invoice No.{$invnum} for Customer {$inv['cusname']} {$inv['surname']}', '" . ($FTOTAL - $FVAT) . "', 'Cost Of Sales for Invoice No.{$invnum}', '{$tcosamt}', ''); </script>";
    /* -- Final Layout -- */
    $details = "\n\t\t<center>\n\t\t{$cc}\n\t\t<h2>Tax Invoice</h2>\n\t\t<table cellpadding='0' cellspacing='4' border='0' width='750'>\n\t\t\t<tr>\n\t\t\t\t<td valign='top' width='30%'>\n\t\t\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<td>{$inv['surname']}</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<td>" . nl2br($inv['cusaddr']) . "</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<td>(VAT No. {$inv['cusvatno']})</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t</table>\n\t\t\t\t</td>\n\t\t\t\t<td valign='top' width='30%'>\n\t\t\t\t\t" . COMP_NAME . "<br>\n\t\t\t\t\t" . COMP_ADDRESS . "<br>\n\t\t\t\t\t" . COMP_PADDR . "<br>\n\t\t\t\t\t" . COMP_TEL . "<br>\n\t\t\t\t\t" . COMP_FAX . "<br>\n\t\t\t\t\tReg No. " . COMP_REGNO . "<br>\n\t\t\t\t\tVAT No. " . COMP_VATNO . "<br>\n\t\t\t\t</td>\n\t\t\t\t<td width='20%'>\n\t\t\t\t\t<img src='compinfo/getimg.php' width='230' height='47'>\n\t\t\t\t</td>\n\t\t\t\t<td valign='bottom' align='right' width='20%'>\n\t\t\t\t\t<table cellpadding='2' cellspacing='0' border='1' bordercolor='#000000'>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<td><b>Invoice No.</b></td>\n\t\t\t\t\t\t\t<td valign='center'>{$invnum}</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<td><b>Proforma Inv No.</b></td>\n\t\t\t\t\t\t\t<td>{$inv['docref']}</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<td><b>Order No.</b></td>\n\t\t\t\t\t\t\t<td valign='center'>{$inv['ordno']}</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<td><b>Terms</b></td>\n\t\t\t\t\t\t\t<td valign='center'>{$inv['terms']} Days</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<td><b>Invoice Date</b></td>\n\t\t\t\t\t\t\t<td valign='center'>{$inv['odate']}</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<td><b>VAT</b></td>\n\t\t\t\t\t\t\t<td valign='center'>{$inv['chrgvat']}</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t</table>\n\t\t\t\t</td>\n\t\t\t</tr>\n\t\t\t<tr><td><br></td></tr>\n\t\t\t<tr>\n\t\t\t\t<td colspan='4'>\n\t\t\t\t\t<table cellpadding='5' cellspacing='0' border='1' width='100%' bordercolor='#000000'>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<td><b>ITEM NUMBER</b></td>\n\t\t\t\t\t\t\t<td width='45%'><b>DESCRIPTION</b></td>\n\t\t\t\t\t\t\t<td><b>QTY</b></td>\n\t\t\t\t\t\t\t<td><b>UNIT PRICE</b></td>\n\t\t\t\t\t\t\t<td><b>DISCOUNT</b></td>\n\t\t\t\t\t\t\t<td><b>AMOUNT</b></td>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t{$products}\n\t\t\t\t\t</table>\n\t\t\t\t</td>\n\t\t\t</tr>\n\t\t\t<tr>\n\t\t\t\t<td>{$inv['comm']}</td>\n\t\t\t\t<td>" . BNK_BANKDET . "</td>\n\t\t\t\t<td align='right' colspan='2'>\n\t\t\t\t\t<table cellpadding='5' cellspacing='0' border='1' width='50%' bordercolor='#000000'>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<td><b>SUBTOTAL</b></td>\n\t\t\t\t\t\t\t<td align='right'>{$inv['currency']} {$SUBTOT}</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<td><b>Trade Discount</b></td>\n\t\t\t\t\t\t\t<td align='right'>{$inv['currency']} {$inv['discount']}</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<td><b>Delivery Charge</b></td>\n\t\t\t\t\t\t\t<td align='right'>{$inv['currency']} {$inv['delivery']}</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<td><b>VAT {$vat14}</b></td>\n\t\t\t\t\t\t\t<td align='right'>{$inv['currency']} {$VAT}</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<td><b>GRAND TOTAL<b></td>\n\t\t\t\t\t\t\t<td align='right'>{$inv['currency']} {$TOTAL}</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t</table>\n\t\t\t\t</td>\n\t\t\t</tr>\n\t\t\t<tr><td><br></td></tr>\n\t\t\t<tr>\n\t\t\t\t<td>\n\t\t\t\t\t<table cellpadding='2' cellspacing='0' border='1'>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<td colspan='2'>{$expl} = #</td>\n\t\t\t\t\t\t</tr>\n\t\t\t        </table>\n\t\t\t\t</td>\n\t\t\t\t<td><br></td>\n\t\t\t</tr>\n\t\t</table>\n\t\t</center>";
    $OUTPUT = $details;
    require "tmpl-print.php";
}
コード例 #16
0
function write($_GET)
{
    # get vars
    extract($_GET);
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($invid, "num", 1, 20, "Invalid Invoice number.");
    $sndate = mkdate($s_year, $s_month, $s_day);
    if (!checkdate($s_month, $s_day, $s_year)) {
        $v->addError($sdate, "Invalid Date.");
    }
    foreach ($ids as $key => $id) {
        $v->isOk($id, "num", 1, 20, "Invalid Item number.");
        //		if (!is_int($qtys[$key])) {
        if (!ctype_digit($qtys[$key])) {
            $v->addError(0, "Invalid Item Quantity.");
        }
        $v->isOk($amts[$key], "float", 1, 20, "Invalid Item amount.");
    }
    $v->isOk($subtot, "float", 1, 20, "Invalid sub-total amount.");
    $v->isOk($vat, "float", 1, 20, "Invalid vat amount.");
    $v->isOk($total, "float", 1, 20, "Invalid total amount.");
    # display errors, if any
    if ($v->isError()) {
        $err = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $err .= "<li class='err'>" . $e["msg"] . "</li>";
        }
        $err .= "<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $err;
    }
    db_connect();
    # Get invoice info
    $sql = "SELECT * FROM nons_invoices WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
    $invRslt = db_exec($sql) or errDie("Unable to get invoice information");
    if (pg_numrows($invRslt) < 1) {
        return "<i class='err'>Not Found</i>";
    }
    $inv = pg_fetch_array($invRslt);
    # Update xrate
    cus_xrate_update($inv['fcid'], $inv['xrate']);
    xrate_update($inv['fcid'], $inv['xrate'], "invoices", "invid");
    xrate_update($inv['fcid'], $inv['xrate'], "custran", "id");
    db_connect();
    # Begin updates
    pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
    $refnum = getrefnum();
    /*refnum*/
    $real_noteid = divlastid('note', USER_DIV);
    db_connect();
    /* --- Start Products Display --- */
    $td = $sndate;
    # Products layout
    $products = "";
    foreach ($ids as $key => $id) {
        $sql = "SELECT * FROM nons_inv_items  WHERE invid = '{$invid}' AND id = '{$id}' AND div = '" . USER_DIV . "'";
        $stkdRslt = db_exec($sql);
        $stkd = pg_fetch_array($stkdRslt);
        $stkacc = $stkd['accid'];
        # keep records for transactions
        // 		if(isset($totstkamt[$stkacc])){
        // 			$totstkamt[$stkacc] += vats($amts[$key], $inv['chrgvat']);
        // 		}else{
        // 			$totstkamt[$stkacc] = vats($amts[$key], $inv['chrgvat']);
        // 		}
        $Sl = "SELECT * FROM vatcodes WHERE id='{$stkd['vatex']}'";
        $Ri = db_exec($Sl) or errDie("Unable to get data.");
        $vd = pg_fetch_array($Ri);
        if ($vd['zero'] == "Yes") {
            $stkd['vatex'] = "y";
        }
        $t = $inv['chrgvat'];
        $VATP = TAX_VAT;
        $stkacc = $stkd['accid'];
        # keep records for transactions
        if (isset($totstkamt[$stkacc])) {
            if ($stkd['vatex'] == "y") {
                $totstkamt[$stkacc] += $amts[$key];
                $va = 0;
                $inv['chrgvat'] = "";
            } else {
                $totstkamt[$stkacc] += vats($amts[$key], $inv['chrgvat']);
                $va = sprint($stkd['amt'] - vats($amts[$key], $inv['chrgvat']));
                if ($inv['chrgvat'] == "no") {
                    $va = sprint($amts[$key] * $VATP / 100);
                }
            }
        } else {
            if ($stkd['vatex'] == "y") {
                $totstkamt[$stkacc] = $amts[$key];
                $va = 0;
                $inv['chrgvat'] = "";
            } else {
                $totstkamt[$stkacc] = vats($amts[$key], $inv['chrgvat']);
                $va = sprint($amts[$key] - vats($amts[$key], $inv['chrgvat']));
                if ($inv['chrgvat'] == "no") {
                    $va = sprint($amts[$key] * $VATP / 100);
                }
            }
        }
        $f = -vats($amts[$key], $inv['chrgvat']);
        $f = $f * $inv['xrate'];
        $va = $va * $inv['xrate'];
        vatr($vd['id'], $td, "OUTPUT", $vd['code'], $refnum, "Non-Stock invoice No. {$inv['invnum']} Credit note No.{$real_noteid} Customer {$inv['cusname']}.", $f - $va, -$va);
        $inv['chrgvat'] = $t;
        $sql = "UPDATE nons_inv_items SET rqty = (rqty + '{$qtys[$key]}') WHERE id = '{$stkd['id']}'";
        $sRslt = db_exec($sql);
        $products .= "\n\t\t\t\t\t\t<tr valign='top'>\n\t\t\t\t\t\t\t<td>{$stkd['description']}</td>\n\t\t\t\t\t\t\t<td>{$qtys[$key]}</td>\n\t\t\t\t\t\t\t<td>{$inv['currency']} {$stkd['unitcost']}</td>\n\t\t\t\t\t\t\t<td>{$inv['currency']} {$amts[$key]}</td>\n\t\t\t\t\t\t</tr>";
    }
    /* --- Start Some calculations --- */
    # Subtotal
    $SUBTOT = sprint($subtot);
    $VAT = sprint($vat);
    $TOTAL = sprint($total);
    $LVAT = sprint($VAT * $inv['xrate']);
    $LTOTAL = sprint($TOTAL * $inv['xrate']);
    /* --- End Some calculations --- */
    /* - Start Hooks - */
    $vatacc = gethook("accnum", "salesacc", "name", "VAT", "VAT");
    /* - End Hooks - */
    # todays date
    db_connect();
    $sql = "SELECT * FROM customers WHERE cusnum = '{$inv['cusid']}' AND div = '" . USER_DIV . "'";
    $custRslt = db_exec($sql) or errDie("Unable to view customer");
    if (pg_numrows($custRslt) < 1) {
        return "<li class='err'>Error : Customer not Found.</li>";
    }
    $cus = pg_fetch_array($custRslt);
    $na = $cus['surname'];
    # Get department
    db_conn("exten");
    $sql = "SELECT * FROM departments WHERE deptid = '{$cus['deptid']}' AND div = '" . USER_DIV . "'";
    $deptRslt = db_exec($sql);
    if (pg_numrows($deptRslt) < 1) {
        return "<li class='err'>Department not Found.</li>";
    } else {
        $dept = pg_fetch_array($deptRslt);
    }
    $wtot = array_sum($totstkamt) + $va;
    $lwtot = sprint($wtot * $inv['xrate']);
    $lva = sprint($va * $inv["xrate"]);
    $tpp = 0;
    # record transaction  from data
    foreach ($totstkamt as $stkacc => $wamt) {
        writetrans($stkacc, $dept['debtacc'], $sndate, $refnum, $lwtot, "Non-Stock invoice No. {$inv['invnum']} Credit note No.{$real_noteid} Customer {$inv['cusname']}.");
    }
    if ($lva != 0) {
        writetrans($vatacc, $dept['debtacc'], $sndate, $refnum, $lva, "Non-Stock invoice No. {$inv['invnum']} Credit note No.{$real_noteid} Vat. Customer {$inv['cusname']}.");
    }
    db_connect();
    # Record the payment on the statement
    $sql = "\n\t\tINSERT INTO stmnt \n\t\t\t(cusnum, invid, amount, date, type, div, allocation_date) \n\t\tVALUES \n\t\t\t('{$inv['cusid']}', '{$real_noteid}', '-{$wtot}','{$sndate}', 'Non Stock Credit Note, for invoice {$inv['invnum']}', '" . USER_DIV . "', '{$sndate}')";
    $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
    # Update the customer (make balance less)
    $sql = "UPDATE customers \n\t\t\tSET balance = (balance - '{$lwtot}'::numeric(13,2)), \n\t\t\t\tfbalance = (fbalance - '{$wtot}'::numeric(13,2)) WHERE cusnum = '{$inv['cusid']}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
    # Make ledge record
    custledger($inv['cusid'], $dept['incacc'], $sndate, $real_noteid, "Non Stock Credit note {$real_noteid}", $lwtot, "c");
    frecordCT($wtot, $inv['cusid'], $inv['xrate'], $inv['fcid'], $sndate);
    // custCT($TOTAL, $inv['cusid']);
    db_connect();
    $sql = "UPDATE nons_invoices \n\t\t\tSET balance = (balance - '{$lwtot}'::numeric(13,2)), \n\t\t\t\tfbalance = (fbalance - '{$wtot}'::numeric(13,2)) WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
    $upRslt = db_exec($sql) or errDie("Unable to update invoice information");
    # write note
    $sql = "INSERT INTO nons_inv_notes(invid, invnum, cusname, cusaddr, cusvatno, chrgvat, location, currency, date, subtot, vat, total, username, prd, notenum, ctyp, div)";
    $sql .= " VALUES('{$inv['invid']}', '{$inv['invnum']}', '{$inv['cusname']}', '{$inv['cusaddr']}', '{$inv['cusvatno']}', '{$inv['chrgvat']}', 'int', '{$inv['currency']}', '{$sndate}', '" . sprint($wtot - $va) . "', {$va}, {$wtot}, '" . USER_NAME . "', '" . PRD_DB . "', '{$real_noteid}', '{$inv['ctyp']}', '" . USER_DIV . "')";
    $rslt = db_exec($sql) or errDie("Unable to create template Non-Stock Invoice.", SELF);
    $noteid = pglib_lastid("nons_inv_notes", "noteid");
    # write note items
    foreach ($ids as $key => $id) {
        $sql = "SELECT * FROM nons_inv_items  WHERE invid = '{$invid}' AND id = '{$id}' AND div = '" . USER_DIV . "'";
        $stkdRslt = db_exec($sql);
        $nstk = pg_fetch_array($stkdRslt);
        $sql = "INSERT INTO nons_note_items(noteid, qty, description, amt, unitcost) \n\t\t\t\tVALUES('{$noteid}', '{$qtys[$key]}', '{$nstk['description']}', '{$amts[$key]}', \n\t\t\t\t\t'{$nstk['unitcost']}')";
        $stkdRslt = db_exec($sql);
    }
    $sql = "INSERT INTO salesrec(edate, invid, invnum, debtacc, vat, total, typ, div)\n\tVALUES('{$sndate}', '{$noteid}', '{$real_noteid}', '0', '{$lva}', '{$lwtot}', 'nnon', '" . USER_DIV . "')";
    $recRslt = db_exec($sql);
    db_conn('cubit');
    $Sl = "INSERT INTO sj(cid,name,des,date,exl,vat,inc,div) VALUES\n\t('{$inv['cusid']}','{$na}','Credit note: {$real_noteid}, Non-stock International Invoice {$inv['invnum']} ','{$sndate}','" . -sprint($lwtot - $lva) . "','-{$lva}','" . -sprint($lwtot) . "','" . USER_DIV . "')";
    $Ri = db_exec($Sl);
    # Commit updates
    pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
    /* -- Format the remarks boxlet -- */
    $inv["remarks"] = "<table border=1><tr><td>Remarks:<br>{$inv['remarks']}</td></tr></table>";
    $cc = "<script> CostCenter('ct', 'Credit Note', '{$sndate}', 'Non Stock Credit Note No.{$real_noteid}', '" . ($LTOTAL - $LVAT) . "', ''); </script>";
    /* -- Final Layout -- */
    $details = "\n\t\t\t\t\t{$cc}\n\t\t\t\t\t<center>\n\t\t\t\t\t<h2>Credit Note</h2>\n\t\t\t\t\t<table cellpadding='0' cellspacing='4' border='0' width='750'>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<td valign='top' width='30%'>\n\t\t\t\t\t\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t\t\t<td>{$inv['cusname']}</td>\n\t\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t\t\t<td>" . nl2br($inv['cusaddr']) . "</td>\n\t\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t\t\t<td>(Vat No. {$inv['cusvatno']})</td>\n\t\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t</table>\n\t\t\t\t\t\t\t</td>\n\t\t\t\t\t\t\t<td valign='top' width='30%'>\n\t\t\t\t\t\t\t\t" . COMP_NAME . "<br>\n\t\t\t\t\t\t\t\t" . COMP_ADDRESS . "<br>\n\t\t\t\t\t\t\t\t" . COMP_TEL . "<br>\n\t\t\t\t\t\t\t\t" . COMP_FAX . "<br>\n\t\t\t\t\t\t\t\tReg No. " . COMP_REGNO . "<br>\n\t\t\t\t\t\t\t\tVat No. " . COMP_VATNO . "\n\t\t\t\t\t\t\t</td>\n\t\t\t\t\t\t\t<td width='20%'><img src='compinfo/getimg.php' width=230 height=47></td>\n\t\t\t\t\t\t\t<td valign='bottom' align='right' width='20%'>\n\t\t\t\t\t\t\t\t<table cellpadding='2' cellspacing='0' border=1 bordercolor='#000000'>\n\t\t\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t\t\t<td><b>Credit Note No.</b></td>\n\t\t\t\t\t\t\t\t\t\t<td valign='center'>{$real_noteid}</td>\n\t\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t\t\t<td><b>Invoice No.</b></td>\n\t\t\t\t\t\t\t\t\t\t<td valign='center'>{$inv['invnum']}</td>\n\t\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t\t\t<td><b>Date</b></td>\n\t\t\t\t\t\t\t\t\t\t<td valign='center'>{$sndate}</td>\n\t\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t</table>\n\t\t\t\t\t\t\t</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr><td><br></td></tr>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<td colspan='4'>\n\t\t\t\t\t\t\t\t<table cellpadding='5' cellspacing='0' border=1 width=100% bordercolor='#000000'>\n\t\t\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t\t\t<th width='65%'>DESCRIPTION</th>\n\t\t\t\t\t\t\t\t\t\t<th width='10%'>QTY</th>\n\t\t\t\t\t\t\t\t\t\t<th width='10%'>UNIT PRICE</th>\n\t\t\t\t\t\t\t\t\t\t<th width='10%'>AMOUNT</th>\n\t\t\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t\t{$products}\n\t\t\t\t\t\t\t\t</table>\n\t\t\t\t\t\t\t</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<td>{$inv['remarks']}</td>\n\t\t\t\t\t\t\t<td align='right' colspan='3'>\n\t\t\t\t\t\t\t\t<table cellpadding='5' cellspacing='0' border=1 width=50% bordercolor='#000000'>\n\t\t\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t\t\t<td><b>SUBTOTAL</b></td>\n\t\t\t\t\t\t\t\t\t\t<td align='right'>{$inv['currency']} {$SUBTOT}</td>\n\t\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t\t\t<td><b>VAT @ " . TAX_VAT . "%</b></td>\n\t\t\t\t\t\t\t\t\t\t<td align='right'>{$inv['currency']} {$VAT}</td>\n\t\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t\t\t<th><b>GRAND TOTAL<b></th>\n\t\t\t\t\t\t\t\t\t\t<td align='right'>{$inv['currency']} {$TOTAL}</td>\n\t\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t</table>\n\t\t\t\t\t\t\t</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr><td><br></td></tr>\n\t\t\t\t\t</table>\n\t\t\t\t\t</center>";
    $OUTPUT = $details;
    require "tmpl-print.php";
}
コード例 #17
0
function write($_POST)
{
    # get vars
    extract($_POST);
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($all, "num", 1, 1, "Invalid allocation.");
    $v->isOk($bankid, "num", 1, 30, "Invalid Bank Account.");
    $v->isOk($date, "date", 1, 14, "Invalid Date.");
    $v->isOk($out, "float", 1, 10, "Invalid out amount.");
    $v->isOk($descript, "string", 0, 255, "Invalid Description.");
    $v->isOk($cheqnum, "num", 0, 30, "Invalid Cheque number.");
    $v->isOk($amt, "float", 1, 10, "Invalid amount.");
    $v->isOk($cusid, "num", 1, 10, "Invalid customer number.");
    $v->isOk($out1, "float", 0, 10, "Invalid paid amount(currant).");
    $v->isOk($out2, "float", 0, 10, "Invalid paid amount(30).");
    $v->isOk($out3, "float", 0, 10, "Invalid paid amount(60).");
    $v->isOk($out4, "float", 0, 10, "Invalid paid amount(90).");
    $v->isOk($out5, "float", 0, 10, "Invalid paid amount(120).");
    if (isset($invids)) {
        foreach ($invids as $key => $value) {
            $v->isOk($invids[$key], "num", 1, 50, "Invalid Invoice No.");
            $v->isOk($paidamt[$key], "float", 1, 20, "Invalid amount to be paid.");
        }
    }
    # display errors, if any
    if ($v->isError()) {
        $confirm = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $confirm .= "<li class=err>" . $e["msg"];
        }
        $confirm .= "<p><input type=button onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $confirm;
    }
    # get hook account number
    core_connect();
    $sql = "SELECT * FROM bankacc WHERE accid = '{$bankid}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to retrieve bank account link from Cubit", SELF);
    # check if link exists
    if (pg_numrows($rslt) < 1) {
        $Sl = "SELECT * FROM accounts WHERE accname='Cash on Hand'";
        $Rg = db_exec($Sl);
        if (pg_num_rows($Rg) < 1) {
            if ($bankid == 0) {
                return "There is no 'Cash on Hand' account, there was one, but its not there now, you must have deleted it, if you want to use cash functionality please create a 'Cash on Hand' account.";
            } else {
                return "Invalid bank acc.";
            }
        }
        $add = pg_fetch_array($Rg);
        $bank['accnum'] = $add['accid'];
    } else {
        $bank = pg_fetch_array($rslt);
    }
    db_connect();
    # Customer name
    $sql = "SELECT * FROM customers WHERE cusnum = '{$cusid}' AND div = '" . USER_DIV . "'";
    $cusRslt = db_exec($sql);
    $cus = pg_fetch_array($cusRslt);
    db_conn("exten");
    # get debtors control account
    $sql = "SELECT debtacc FROM departments WHERE deptid ='{$cus['deptid']}' AND div = '" . USER_DIV . "'";
    $deptRslt = db_exec($sql);
    $dept = pg_fetch_array($deptRslt);
    # Update xrate
    cus_xrate_update($cus['fcid'], $rate);
    xrate_update($cus['fcid'], $rate, "invoices", "invid");
    xrate_update($cus['fcid'], $rate, "custran", "id");
    bank_xrate_update($cus['fcid'], $rate);
    $lamt = sprint($amt * $rate);
    # date format
    $sdate = explode("-", $date);
    $sdate = $sdate[2] . "-" . $sdate[1] . "-" . $sdate[0];
    $cheqnum = 0 + $cheqnum;
    $pay = "";
    $accdate = date("Y-m-d");
    # Paid invoices
    $invidsers = "";
    $rinvids = "";
    $famounts = "";
    $amounts = "";
    $invprds = "";
    $rages = "";
    db_connect();
    if ($all == 0) {
        # Begin updates
        # pglib_transaction ("BEGIN") or errDie("Unable to start a database transaction.",SELF);
        if (isset($invids)) {
            foreach ($invids as $key => $value) {
                $ii = $invids[$key];
                $lpaidamt[$key] = sprint($paidamt[$key] * $rate);
                if (!isset($itype[$ii])) {
                    # Get debt invoice info
                    $sql = "SELECT prd,invnum,odate FROM invoices WHERE invid ='{$invids[$key]}' AND div = '" . USER_DIV . "'";
                    $invRslt = db_exec($sql) or errDie("Unable to retrieve invoice details from database.");
                    if (pg_numrows($invRslt) < 1) {
                        return "<li class='err'>Invalid Invoice Number.</li>";
                    }
                    $inv = pg_fetch_array($invRslt);
                    # reduce the money that has been paid
                    $sql = "UPDATE invoices SET balance = (balance - {$lpaidamt[$key]}::numeric(13,2)),fbalance = (fbalance - {$paidamt[$key]}::numeric(13,2)) WHERE invid = '{$invids[$key]}' AND div = '" . USER_DIV . "'";
                    $payRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
                    $inv['invnum'] += 0;
                    # record the payment on the statement
                    $sql = "\n\t\t\t\t\t\t\tINSERT INTO stmnt \n\t\t\t\t\t\t\t\t(cusnum, invid, amount, date, type, div, allocation_date) \n\t\t\t\t\t\t\tVALUES \n\t\t\t\t\t\t\t\t('{$cus['cusnum']}','{$inv['invnum']}','" . ($paidamt[$key] - $paidamt[$key] * 2) . "','{$sdate}', 'Payment for Invoice No. {$inv['invnum']}', '" . USER_DIV . "', '{$inv['odate']}')";
                    $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
                    custledger($cus['cusnum'], $bank['accnum'], $sdate, $inv['invnum'], "Payment for Invoice No. {$inv['invnum']}", $lpaidamt[$key], "c");
                    db_connect();
                    $rinvids .= "|{$invids[$key]}";
                    $famounts .= "|{$paidamt[$key]}";
                    $amounts .= "|{$lpaidamt[$key]}";
                    $invprds .= "|{$inv['prd']}";
                    $rages .= "|0";
                    $invidsers .= " - {$inv['invnum']}";
                } else {
                    # Get debt invoice info
                    $sql = "SELECT prd,invnum,descrip,age,odate FROM nons_invoices WHERE invid ='{$invids[$key]}' AND div = '" . USER_DIV . "'";
                    $invRslt = db_exec($sql) or errDie("Unable to retrieve invoice details from database.");
                    if (pg_numrows($invRslt) < 1) {
                        return "<li class='err'>Invalid Invoice Number.</li>";
                    }
                    $inv = pg_fetch_array($invRslt);
                    # reduce the money that has been paid
                    $sql = "UPDATE nons_invoices SET balance = (balance - {$lpaidamt[$key]}::numeric(13,2)), fbalance = (fbalance - {$paidamt[$key]}::numeric(13,2)) WHERE invid = '{$invids[$key]}' AND div = '" . USER_DIV . "'";
                    $payRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
                    $inv['invnum'] += 0;
                    # record the payment on the statement
                    $sql = "\n\t\t\t\t\t\t\tINSERT INTO stmnt \n\t\t\t\t\t\t\t\t(cusnum, invid, amount, date, type, div, allocation_date) \n\t\t\t\t\t\t\tVALUES \n\t\t\t\t\t\t\t\t('{$cus['cusnum']}','{$inv['invnum']}','" . ($paidamt[$key] - $paidamt[$key] * 2) . "','{$sdate}', 'Payment for Non Stock Invoice No. {$inv['invnum']} - {$inv['descrip']}', '" . USER_DIV . "', '{$inv['odate']}')";
                    $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
                    custledger($cus['cusnum'], $bank['accnum'], $sdate, $inv['invnum'], "Payment for Non Stock Invoice No. {$inv['invnum']} - {$inv['descrip']}", $lpaidamt[$key], "c");
                    db_connect();
                    frecordCT($paidamt[$key], $cus['cusnum'], $rate, $cus['fcid']);
                    $rinvids .= "|{$invids[$key]}";
                    $famounts .= "|{$paidamt[$key]}";
                    $amounts .= "|{$lpaidamt[$key]}";
                    $invprds .= "|0";
                    $rages .= "|{$inv['age']}";
                    $invidsers .= " - {$inv['invnum']}";
                }
            }
        }
        # update the customer (make fbalance less)
        $sql = "UPDATE customers SET balance = (balance - '{$lamt}'::numeric(13,2)), fbalance = (fbalance - '{$amt}'::numeric(13,2)) WHERE cusnum = '{$cus['cusnum']}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
        # record the payment record
        // $sql = "INSERT INTO cashbook(bankid, trantype, date, name, descript, cheqnum, amount, banked, accinv, cusnum, rinvids, amounts, invprds, rages, div) VALUES ('$bankid', 'deposit', '$sdate', '$cus[cusname] $cus[surname]', 'Payment for Invoices $invidsers from customer $cus[cusname] $cus[surname]', '$cheqnum', '$lamt', 'no', '$dept[debtacc]', '$cus[cusnum]', '$rinvids', '$amounts', '$invprds', '$rages', '".USER_DIV."')";
        // 2 $sql = "INSERT INTO cashbook(bankid, trantype, date, name, descript, cheqnum, amount, famount, banked, accinv, cusnum, rinvids, amounts, invprds, rages, div) VALUES ('$bankid', 'deposit', '$sdate', '$cus[cusname] $cus[surname]', 'Payment for Invoices $invidsers from customer $cus[cusname] $cus[surname]', '$cheqnum', '$lamt', '$amt', 'no', '$dept[debtacc]', '$cus[cusnum]', '$rinvids', '$amounts', '$invprds', '$rages', '".USER_DIV."')";
        $sql = "INSERT INTO cashbook(bankid, trantype, date, name, descript, cheqnum, amount, famount, banked, accinv, cusnum, rinvids, amounts, famounts, invprds, rages, fcid, currency, location, div) VALUES ('{$bankid}', 'deposit', '{$sdate}', '{$cus['cusname']} {$cus['surname']}', 'Payment for Invoices {$invidsers} from customer {$cus['cusname']} {$cus['surname']}', '{$cheqnum}', '{$lamt}', '{$amt}', 'no', '{$dept['debtacc']}', '{$cus['cusnum']}', '{$rinvids}', '{$amounts}', '{$famounts}', '{$invprds}', '{$rages}', '{$cus['fcid']}', '{$cus['currency']}', '{$cus['location']}', '" . USER_DIV . "')";
        $Rslt = db_exec($sql) or errDie("Unable to add bank payment to database.", SELF);
        # Update the bankacct table (make fbalance less) [used for cashbook fc value]
        $sql = "UPDATE bankacct SET balance = (balance + '{$lamt}'::numeric(13,2)), fbalance = (fbalance + '{$amt}'::numeric(13,2)) WHERE bankid = '{$bankid}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
        $refnum = getrefnum($sdate);
        db_conn('core');
        $Sl = "SELECT * FROM bankacc WHERE accid='{$bankid}' AND accid!=0";
        $Rx = db_exec($Sl) or errDie("Uanble to get bank acc.");
        if (pg_numrows($Rx) < 1) {
            $Sl = "SELECT * FROM accounts WHERE accname='Cash on Hand'";
            $Rg = db_exec($Sl);
            if (pg_num_rows($Rg) < 1) {
                if ($bankid == 0) {
                    return "There is no 'Cash on Hand' account, there was one, but its not there now, if you want to use cash functionality please create a 'Cash on Hand' account.";
                } else {
                    return "Invalid bank acc.";
                }
            }
            $add = pg_fetch_array($Rg);
            $link['accnum'] = $add['accid'];
        } else {
            $link = pg_fetch_array($Rx);
        }
        writetrans($link['accnum'], $dept['debtacc'], $sdate, $refnum, $lamt, "Payment for Invoices {$invidsers} from customer {$cus['cusname']} {$cus['surname']}");
        db_conn('cubit');
        if ($out > 0) {
            frecordCT($out, $cus['cusnum'], $rate, $cus['fcid']);
            $Sl = "\n\t\t\t\tINSERT INTO stmnt \n\t\t\t\t\t(cusnum, invid, amount, date, type, div, allocation_date) \n\t\t\t\tVALUES \n\t\t\t\t\t('{$cus['cusnum']}','0','" . $out * -1 . "','{$sdate}', 'Payment Received.', '" . USER_DIV . "', '{$sdate}')";
            $Rs = db_exec($Sl) or errDie("Unable to insert statement record in Cubit.", SELF);
            custledger($cus['cusnum'], $bank['accnum'], $sdate, "PAYMENT", "Payment received.", $out * $rate, "c");
            db_connect();
        }
        # Commit updates
        # pglib_transaction ("COMMIT") or errDie("Unable to commit a database transaction.",SELF);
    }
    if ($all == 1) {
        # Begin updates
        # pglib_transaction ("BEGIN") or errDie("Unable to start a database transaction.",SELF);
        if (isset($invids)) {
            foreach ($invids as $key => $value) {
                $ii = $invids[$key];
                $lpaidamt[$key] = sprint($paidamt[$key] * $rate);
                if (!isset($itype[$ii])) {
                    # Get debt invoice info
                    $sql = "SELECT prd,invnum,odate FROM invoices WHERE invid ='{$invids[$key]}' AND div = '" . USER_DIV . "'";
                    $invRslt = db_exec($sql) or errDie("Unable to retrieve invoice details from database.");
                    if (pg_numrows($invRslt) < 1) {
                        return "<li class=err>Invalid Invoice Number.";
                    }
                    $inv = pg_fetch_array($invRslt);
                    # reduce the money that has been paid
                    $sql = "UPDATE invoices SET balance = (balance - '{$lpaidamt[$key]}'::numeric(13,2)), fbalance = (fbalance - {$paidamt[$key]}::numeric(13,2)) WHERE invid = '{$invids[$key]}' AND div = '" . USER_DIV . "'";
                    $payRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
                    $inv['invnum'] += 0;
                    # record the payment on the statement
                    $sql = "\n\t\t\t\t\t\t\tINSERT INTO stmnt \n\t\t\t\t\t\t\t\t(cusnum, invid, amount, date, type, div, allocation_date) \n\t\t\t\t\t\t\tVALUES \n\t\t\t\t\t\t\t\t('{$cus['cusnum']}','{$inv['invnum']}','" . ($paidamt[$key] - $paidamt[$key] * 2) . "','{$sdate}', 'Payment for Invoice No. {$inv['invnum']}', '" . USER_DIV . "', '{$inv['odate']}')";
                    $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
                    custledger($cus['cusnum'], $bank['accnum'], $sdate, $inv['invnum'], "Payment for Invoice No. {$inv['invnum']}", $lpaidamt[$key], "c");
                    db_connect();
                    $rinvids .= "|{$invids[$key]}";
                    $famounts .= "|{$paidamt[$key]}";
                    $amounts .= "|{$lpaidamt[$key]}";
                    $invprds .= "|{$inv['prd']}";
                    $rages .= "|0";
                    $invidsers .= " - {$inv['invnum']}";
                } else {
                    # Get debt invoice info
                    $sql = "SELECT prd,invnum,descrip,age,odate FROM nons_invoices WHERE invid ='{$invids[$key]}' AND div = '" . USER_DIV . "'";
                    $invRslt = db_exec($sql) or errDie("Unable to retrieve invoice details from database.");
                    if (pg_numrows($invRslt) < 1) {
                        return "<li class=err>Invalid Invoice Number.";
                    }
                    $inv = pg_fetch_array($invRslt);
                    # reduce the money that has been paid
                    $sql = "UPDATE nons_invoices SET balance = (balance - '{$lpaidamt[$key]}'::numeric(13,2)), fbalance = (fbalance - {$paidamt[$key]}::numeric(13,2)) WHERE invid = '{$invids[$key]}' AND div = '" . USER_DIV . "'";
                    $payRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
                    $inv['invnum'] += 0;
                    # record the payment on the statement
                    $sql = "\n\t\t\t\t\t\t\tINSERT INTO stmnt \n\t\t\t\t\t\t\t\t(cusnum, invid, amount, date, type, div, allocation_date) \n\t\t\t\t\t\t\tVALUES \n\t\t\t\t\t\t\t\t('{$cus['cusnum']}','{$inv['invnum']}','" . ($paidamt[$key] - $paidamt[$key] * 2) . "','{$sdate}', 'Payment for Non Stock Invoice No. {$inv['invnum']} - {$inv['descrip']}', '" . USER_DIV . "', '{$inv['odate']}')";
                    $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
                    custledger($cus['cusnum'], $bank['accnum'], $sdate, $inv['invnum'], "Payment for Non Stock Invoice No. {$inv['invnum']} - {$inv['descrip']}", $lpaidamt[$key], "c");
                    db_connect();
                    frecordCT($paidamt[$key], $cus['cusnum'], $rate, $cus['fcid']);
                    $rinvids .= "|{$invids[$key]}";
                    $famounts .= "|{$paidamt[$key]}";
                    $amounts .= "|{$lpaidamt[$key]}";
                    $invprds .= "|0";
                    $rages .= "|{$inv['age']}";
                    $invidsers .= " - {$inv['invnum']}";
                }
            }
        }
        # update the customer (make fbalance less)
        $sql = "UPDATE customers SET balance = (balance - '{$lamt}'::numeric(13,2)), fbalance = (fbalance - '{$amt}'::numeric(13,2)) WHERE cusnum = '{$cus['cusnum']}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
        # record the payment record
        // $sql = "INSERT INTO cashbook(bankid, trantype, date, name, descript, cheqnum, amount, banked, accinv, cusnum, rinvids, amounts, invprds, rages, div) VALUES ('$bankid', 'deposit', '$sdate', '$cus[cusname] $cus[surname]', 'Payment for Invoices $invidsers from customer $cus[cusname] $cus[surname]', '$cheqnum', '$lamt', 'no', '$dept[debtacc]', '$cus[cusnum]', '$rinvids', '$amounts', '$invprds', '$rages', '".USER_DIV."')";
        // 2 $sql = "INSERT INTO cashbook(bankid, trantype, date, name, descript, cheqnum, amount, famount, banked, accinv, cusnum, rinvids, amounts, invprds, rages, div) VALUES ('$bankid', 'deposit', '$sdate', '$cus[cusname] $cus[surname]', 'Payment for Invoices $invidsers from customer $cus[cusname] $cus[surname]', '$cheqnum', '$lamt', '$amt', 'no', '$dept[debtacc]', '$cus[cusnum]', '$rinvids', '$amounts', '$invprds', '$rages', '".USER_DIV."')";
        $sql = "INSERT INTO cashbook(bankid, trantype, date, name, descript, cheqnum, amount, famount, banked, accinv, cusnum, rinvids, amounts, famounts, invprds, rages, fcid, currency, location, div) VALUES ('{$bankid}', 'deposit', '{$sdate}', '{$cus['cusname']} {$cus['surname']}', 'Payment for Invoices {$invidsers} from customer {$cus['cusname']} {$cus['surname']}', '{$cheqnum}', '{$lamt}', '{$amt}', 'no', '{$dept['debtacc']}', '{$cus['cusnum']}', '{$rinvids}', '{$amounts}', '{$famounts}', '{$invprds}', '{$rages}', '{$cus['fcid']}', '{$cus['currency']}', '{$cus['location']}', '" . USER_DIV . "')";
        $Rslt = db_exec($sql) or errDie("Unable to add bank payment to database.", SELF);
        # Update the bankacct table (make fbalance less) [used for cashbook fc value]
        $sql = "UPDATE bankacct SET balance = (balance + '{$lamt}'::numeric(13,2)), fbalance = (fbalance + '{$amt}'::numeric(13,2)) WHERE bankid = '{$bankid}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
        $refnum = getrefnum($sdate);
        db_conn('core');
        $Sl = "SELECT * FROM bankacc WHERE accid='{$bankid}' AND accid!=0";
        $Rx = db_exec($Sl) or errDie("Uanble to get bank acc.");
        if (pg_numrows($Rx) < 1) {
            $Sl = "SELECT * FROM accounts WHERE accname='Cash on Hand'";
            $Rg = db_exec($Sl);
            if (pg_num_rows($Rg) < 1) {
                if ($bankid == 0) {
                    return "There is no 'Cash on Hand' account, there was one, but its not there now, if you want to use cash functionality please create a 'Cash on Hand' account.";
                } else {
                    return "Invalid bank acc.";
                }
            }
            $add = pg_fetch_array($Rg);
            $link['accnum'] = $add['accid'];
        } else {
            $link = pg_fetch_array($Rx);
        }
        writetrans($link['accnum'], $dept['debtacc'], $sdate, $refnum, $lamt, "Payment for Invoices {$invidsers} from customer {$cus['cusname']} {$cus['surname']}");
        db_conn('cubit');
        if ($out1 + $out2 + $out3 + $out4 + $out5 > 0) {
            $Sl = "\n\t\t\t\t\tINSERT INTO stmnt \n\t\t\t\t\t\t(cusnum, invid, amount, date, type, div, allocation_date) \n\t\t\t\t\tVALUES \n\t\t\t\t\t\t('{$cus['cusnum']}','0','" . ($out1 + $out2 + $out3 + $out4 + $out5) * -1 . "','{$sdate}', 'Payment Received.', '" . USER_DIV . "', '{$sdate}')";
            $Rs = db_exec($Sl) or errDie("Unable to insert statement record in Cubit.", SELF);
            custledger($cus['cusnum'], $bank['accnum'], $sdate, "PAYMENT", "Payment received.", ($out1 + $out2 + $out3 + $out4 + $out5) * $rate, "c");
            db_connect();
        }
        if ($out1 > 0) {
            frecordCT($out1, $cus['cusnum'], $rate, $cus['fcid']);
        }
        if ($out2 > 0) {
            frecordCT($out2, $cus['cusnum'], $rate, $cus['fcid']);
        }
        if ($out3 > 0) {
            frecordCT($out3, $cus['cusnum'], $rate, $cus['fcid']);
        }
        if ($out4 > 0) {
            frecordCT($out4, $cus['cusnum'], $rate, $cus['fcid']);
        }
        if ($out5 > 0) {
            frecordCT($out5, $cus['cusnum'], $rate, $cus['fcid']);
        }
        # Commit updates
        # pglib_transaction ("COMMIT") or errDie("Unable to commit a database transaction.",SELF);
    }
    if ($all == 2) {
        # Begin updates
        //pglib_transaction ("BEGIN") or errDie("Unable to start a database transaction.",SELF);
        # Debtors
        foreach ($invids as $key => $value) {
            $ii = $invids[$key];
            $lpaidamt[$key] = sprint($paidamt[$key] * $rate);
            if (!isset($itype[$ii])) {
                # Get debt invoice info
                $sql = "SELECT prd,invnum,odate FROM invoices WHERE invid ='{$invids[$key]}' AND div = '" . USER_DIV . "'";
                $invRslt = db_exec($sql) or errDie("Unable to retrieve invoice details from database.");
                if (pg_numrows($invRslt) < 1) {
                    return "<li class=err>Invalid Invoice Number.";
                }
                $inv = pg_fetch_array($invRslt);
                # reduce the money that has been paid
                $sql = "UPDATE invoices SET balance = (balance - '{$lpaidamt[$key]}'::numeric(13,2)), fbalance = (fbalance - {$paidamt[$key]}::numeric(13,2)) WHERE invid = '{$invids[$key]}' AND div = '" . USER_DIV . "'";
                $payRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
                # record the payment on the statement
                $sql = "\n\t\t\t\t\t\tINSERT INTO stmnt \n\t\t\t\t\t\t\t(cusnum, invid, amount, date, type, div, allocation_date) \n\t\t\t\t\t\tVALUES \n\t\t\t\t\t\t\t('{$cus['cusnum']}','{$inv['invnum']}','" . ($paidamt[$key] - $paidamt[$key] * 2) . "','{$sdate}', 'Payment for Invoice No. {$inv['invnum']}', '" . USER_DIV . "', '{$inv['odate']}')";
                $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
                custledger($cus['cusnum'], $bank['accnum'], $sdate, $inv['invnum'], "Payment for Invoice No. {$inv['invnum']}", $lpaidamt[$key], "c");
                db_connect();
                $rinvids .= "|{$invids[$key]}";
                $famounts .= "|{$paidamt[$key]}";
                $amounts .= "|{$lpaidamt[$key]}";
                $invprds .= "|{$inv['prd']}";
                $rages .= "|0";
                $invidsers .= " - {$inv['invnum']}";
            } else {
                # Get debt invoice info
                $sql = "SELECT prd,invnum,descrip,age,odate FROM nons_invoices WHERE invid ='{$invids[$key]}' AND div = '" . USER_DIV . "'";
                $invRslt = db_exec($sql) or errDie("Unable to retrieve invoice details from database.");
                if (pg_numrows($invRslt) < 1) {
                    return "<li class=err>Invalid Invoice Number.";
                }
                $inv = pg_fetch_array($invRslt);
                # reduce the money that has been paid
                $sql = "UPDATE nons_invoices SET balance = (balance - '{$lpaidamt[$key]}'::numeric(13,2)), fbalance = (fbalance - {$paidamt[$key]}::numeric(13,2)) WHERE invid = '{$invids[$key]}' AND div = '" . USER_DIV . "'";
                $payRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
                # record the payment on the statement
                $sql = "\n\t\t\t\t\t\tINSERT INTO stmnt \n\t\t\t\t\t\t\t(cusnum, invid, amount, date, type, div, allocation_date) \n\t\t\t\t\t\tVALUES \n\t\t\t\t\t\t\t('{$cus['cusnum']}','{$inv['invnum']}','" . ($paidamt[$key] - $paidamt[$key] * 2) . "','{$sdate}', 'Payment for Non Stock Invoice No. {$inv['invnum']} - {$inv['descrip']}', '" . USER_DIV . "', '{$inv['odate']}')";
                $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
                custledger($cus['cusnum'], $bank['accnum'], $sdate, $inv['invnum'], "Payment for Non Stock Invoice No. {$inv['invnum']} - {$inv['descrip']}", $lpaidamt[$key], "c");
                db_connect();
                frecordCT($paidamt[$key], $cus['cusnum'], $rate, $cus['fcid']);
                $rinvids .= "|{$invids[$key]}";
                $famounts .= "|{$paidamt[$key]}";
                $amounts .= "|{$lpaidamt[$key]}";
                $invprds .= "|0";
                $rages .= "|{$inv['age']}";
                $invidsers .= " - {$inv['invnum']}";
            }
        }
        # update the customer (make fbalance less)
        $sql = "UPDATE customers SET balance = (balance - '{$lamt}'::numeric(13,2)), fbalance = (fbalance - '{$amt}'::numeric(13,2)) WHERE cusnum = '{$cus['cusnum']}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
        # record the payment record
        //2 $sql = "INSERT INTO cashbook(bankid, trantype, date, name, descript, cheqnum, amount, famount, banked, accinv, cusnum, rinvids, amounts, famounts, invprds, rages, div) VALUES ('$bankid', 'deposit', '$sdate', '$cus[cusname] $cus[surname]', 'Payment for Invoices $invidsers from customer $cus[cusname] $cus[surname]', '$cheqnum', '$lamt', '$amt', 'no', '$dept[debtacc]', '$cus[cusnum]', '$rinvids', '$amounts', '$famounts', '$invprds', '$rages', '".USER_DIV."')";
        $sql = "INSERT INTO cashbook(bankid, trantype, date, name, descript, cheqnum, amount, famount, banked, accinv, cusnum, rinvids, amounts, famounts, invprds, rages, fcid, currency, location, div) VALUES ('{$bankid}', 'deposit', '{$sdate}', '{$cus['cusname']} {$cus['surname']}', 'Payment for Invoices {$invidsers} from customer {$cus['cusname']} {$cus['surname']}', '{$cheqnum}', '{$lamt}', '{$amt}', 'no', '{$dept['debtacc']}', '{$cus['cusnum']}', '{$rinvids}', '{$amounts}', '{$famounts}', '{$invprds}', '{$rages}', '{$cus['fcid']}', '{$cus['currency']}', '{$cus['location']}', '" . USER_DIV . "')";
        $Rslt = db_exec($sql) or errDie("Unable to add bank payment to database.", SELF);
        # Update the bankacct table (make fbalance less) [used for cashbook fc value]
        $sql = "UPDATE bankacct SET balance = (balance + '{$lamt}'::numeric(13,2)), fbalance = (fbalance + '{$amt}'::numeric(13,2)) WHERE bankid = '{$bankid}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
        $refnum = getrefnum($accdate);
        db_conn('core');
        $Sl = "SELECT * FROM bankacc WHERE accid='{$bankid}'";
        $Rx = db_exec($Sl) or errDie("Uanble to get bank acc.");
        $Sl = "SELECT * FROM bankacc WHERE accid='{$bankid}' AND accid!=0";
        $Rx = db_exec($Sl) or errDie("Uanble to get bank acc.");
        if (pg_numrows($Rx) < 1) {
            $Sl = "SELECT * FROM accounts WHERE accname='Cash on Hand'";
            $Rg = db_exec($Sl);
            if (pg_num_rows($Rg) < 1) {
                if ($bankid == 0) {
                    return "There is no 'Cash on Hand' account, there was one, but its not there now, if you want to use cash functionality please create a 'Cash on Hand' account.";
                } else {
                    return "Invalid bank acc.";
                }
            }
            $add = pg_fetch_array($Rg);
            $link['accnum'] = $add['accid'];
        } else {
            $link = pg_fetch_array($Rx);
        }
        writetrans($link['accnum'], $dept['debtacc'], $sdate, $refnum, $lamt, "Payment for Invoices {$invidsers} from customer {$cus['cusname']} {$cus['surname']}");
        # Commit updates
        //pglib_transaction ("COMMIT") or errDie("Unable to commit a database transaction.",SELF);
    }
    db_conn('cubit');
    /* start moving invoices */
    # move invoices that are fully paid
    $sql = "SELECT * FROM invoices WHERE fbalance = 0 AND balance = 0 AND printed = 'y' AND done = 'y' AND div = '" . USER_DIV . "'";
    $invbRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
    while ($invb = pg_fetch_array($invbRslt)) {
        if ($invb['prd'] == 0) {
            $invb['prd'] = PRD_DB;
        }
        db_conn($invb['prd']);
        # Insert invoice to period DB
        $sql = "INSERT INTO invoices(invid, invnum, deptid, cusnum, deptname, cusacc, cusname, surname, cusaddr, cusvatno, cordno, ordno, chrgvat, fcid, currency, xrate, terms, traddisc, salespn, odate, delchrg, subtot, vat, total, fbalance, location, age, comm, discount, delivery, printed, done, div)";
        $sql .= " VALUES('{$invb['invid']}','{$invb['invnum']}', '{$invb['deptid']}', '{$invb['cusnum']}', '{$invb['deptname']}', '{$invb['cusacc']}', '{$invb['cusname']}', '{$invb['surname']}', '{$invb['cusaddr']}', '{$invb['cusvatno']}', '{$invb['cordno']}', '{$invb['ordno']}', '{$invb['chrgvat']}', '{$invb['fcid']}', '{$invb['currency']}', '{$invb['xrate']}', '{$invb['terms']}', '{$invb['traddisc']}', '{$invb['salespn']}', '{$invb['odate']}', '{$invb['delchrg']}', '{$invb['subtot']}', '{$invb['vat']}' , '{$invb['total']}', '0', '{$invb['location']}', '{$invb['age']}', '{$invb['comm']}', '{$invb['discount']}', '{$invb['delivery']}', 'y', 'y', '" . USER_DIV . "')";
        $rslt = db_exec($sql) or errDie("Unable to insert invoice to the period database.", SELF);
        # get selected stock in this invoice
        db_connect();
        $sql = "SELECT * FROM inv_items WHERE invid = '{$invb['invid']}' AND div = '" . USER_DIV . "'";
        $stkdRslt = db_exec($sql);
        while ($stkd = pg_fetch_array($stkdRslt)) {
            db_conn($invb['prd']);
            # insert invoice items
            $sql = "INSERT INTO inv_items(invid, whid, stkid, qty, unitcost, amt, disc, discp, div) VALUES('{$invb['invid']}', '{$stkd['whid']}', '{$stkd['stkid']}', '{$stkd['qty']}', '{$stkd['unitcost']}', '{$stkd['amt']}', '{$stkd['disc']}', '{$stkd['discp']}', '" . USER_DIV . "')";
            $rslt = db_exec($sql) or errDie("Unable to insert invoice items to Cubit.", SELF);
        }
        db_connect();
        # Remove those invoices from running DB
        $sql = "DELETE FROM invoices WHERE invid = '{$invb['invid']}' AND div = '" . USER_DIV . "'";
        $delRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
        # Remove those invoice items from running DB
        $sql = "DELETE FROM inv_items WHERE invid = '{$invb['invid']}' AND div = '" . USER_DIV . "'";
        $delRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
    }
    /* end moving invoices */
    # status report
    $write = "\n\t\t\t<table " . TMPL_tblDflts . " width='100%'>\n\t\t\t\t<tr><th>Bank Receipt</th></tr>\n\t\t\t\t<tr class='datacell'><td>Bank Receipt added to cash book.</td></tr>\n\t\t\t</table>";
    # main table (layout with menu)
    $OUTPUT = "\n\t\t\t<center>\n\t\t\t<table width='90%'>\n\t\t\t\t<tr valign='top'>\n\t\t\t\t\t<td width=50%>{$write}</td>\n\t\t\t\t\t<td align='center'>\n\t\t\t\t\t\t<table " . TMPL_tblDflts . " width='80%'>\n\t\t\t\t\t\t\t<tr><th>Quick Links</th></tr>\n\t\t\t\t\t\t\t<tr class='" . bg_class() . "'><td><a href='bank-pay-add.php'>Add Bank Payment</a></td></tr>\n\t\t\t\t\t\t\t<tr class='" . bg_class() . "'><td><a href='bank-recpt-add.php'>Add Bank Receipt</a></td></tr>\n\t\t\t\t\t\t\t<tr class='" . bg_class() . "'><td><a href='bank-recpt-inv.php'>Add Customer Payment</a></td></tr>\n\t\t\t\t\t\t\t<tr class='" . bg_class() . "'><td><a href='cashbook-view.php'>View Cash Book</a></td></tr>\n\t\t\t\t\t\t\t<script>document.write(getQuicklinkSpecial());</script>\n\t\t\t\t\t\t</table>\n\t\t\t\t\t</td>\n\t\t\t\t</tr>\n\t\t\t</table>";
    return $OUTPUT;
}
コード例 #18
0
function cp2($id, $amount, $description, $contra, $refnum, $date, $cheque = 0, $bankid)
{
    $cheque += 0;
    $sdate = date("Y-m-d");
    $accdate = $date;
    if ($accdate == 0) {
        $accdate = date("Y-m-d");
    }
    $cus = qryCustomer($id, "cusnum, deptid, cusname, surname");
    $dept = qryDepartment($cus["deptid"], "debtacc");
    // 	db_connect();
    //
    // 	$Sl = "SELECT cusnum,deptid,cusname,surname FROM customers WHERE cusnum = '$id' AND div = '".USER_DIV."'";
    // 	$Ri = db_exec($Sl) or errDie("Unable to get data.");
    // 	$cus = pg_fetch_array($Ri);
    db_conn('core');
    $Sl = "SELECT * FROM bankacc WHERE accid='{$bankid}'";
    $Rx = db_exec($Sl) or errDie("Uanble to get bank acc.");
    if (pg_numrows($Rx) < 1) {
        return "Invalid bank acc.";
    }
    $link = pg_fetch_array($Rx);
    #######################################################################################################
    ########################################### COMPILE ###################################################
    #######################################################################################################
    $out = $amount;
    $invs_arr = array();
    // Connect to database
    db_connect();
    #####################[ GET OUTSTANDING INVOICES ]######################
    $sql = "\n\t\tSELECT invnum, invid, balance, terms, odate \n\t\tFROM invoices \n\t\tWHERE cusnum = '{$id}' AND printed = 'y' AND balance>0 AND div = '" . USER_DIV . "' ORDER BY odate ASC";
    $prnInvRslt = db_exec($sql);
    while (($inv = pg_fetch_array($prnInvRslt)) && $out > 0) {
        $invs_arr[] = array("s", $inv['odate'], "{$inv['invid']}", "{$inv['balance']}");
    }
    #####################[ GET OUTSTANDING NON STOCK INVOICES ]######################
    $sql = "\n\t\tSELECT invnum, invid, balance, odate \n\t\tFROM nons_invoices \n\t\tWHERE cusid='{$id}' AND done='y' AND balance>0 AND div='" . USER_DIV . "' ORDER BY odate ASC";
    $prnInvRslt = db_exec($sql);
    while (($inv = pg_fetch_array($prnInvRslt)) && $out > 0) {
        $invs_arr[] = array("n", $inv['odate'], "{$inv['invid']}", "{$inv['balance']}");
    }
    $out = sprint($out);
    #####################[ GET OUTSTANDING POS INVOICES ]######################
    $sqls = array();
    for ($i = 1; $i <= 12; ++$i) {
        $sqls[] = "\n\t\t\tSELECT invnum, invid, balance, odate \n\t\t\tFROM \"{$i}\".pinvoices \n\t\t\tWHERE cusnum='{$id}' AND done='y' AND balance > 0 AND div='" . USER_DIV . "'";
    }
    $sql = implode(" UNION ", $sqls);
    $prnInvRslt = db_exec($sql);
    while ($inv = pg_fetch_array($prnInvRslt)) {
        $invs_arr[] = array("p", $inv['odate'], "{$inv['invid']}", "{$inv['balance']}");
    }
    #compile results into an array we can sort by date
    $search_arr = array();
    foreach ($invs_arr as $key => $array) {
        $search_arr[$key] = $array[1];
    }
    #sort array by date
    asort($search_arr);
    #add sorted invoices to payment listing
    foreach ($search_arr as $key => $date) {
        $arr = $invs_arr[$key];
        if ($arr[0] == "s") {
            db_connect();
            $get_sql = "\n\t\t\t\tSELECT invnum, invid, balance, terms, odate \n\t\t\t\tFROM invoices \n\t\t\t\tWHERE cusnum = '{$id}' AND printed = 'y' AND balance>0 AND div = '" . USER_DIV . "' AND invid = '{$arr['2']}'  LIMIT 1";
            $run_sql = db_exec($get_sql) or errDie("Unable to get stock invoice information.");
            if (pg_numrows($run_sql) > 0) {
                $inv = pg_fetch_array($run_sql);
                $invid = $inv['invid'];
                $val = allocamt($out, $inv["balance"]);
                if ($val == 0.0) {
                    continue;
                }
                $inv['invnum'] += 0;
                // reduce invoice balance
                $sql = "\n\t\t\t\t\tUPDATE cubit.invoices \n\t\t\t\t\tSET balance = (balance - {$val}::numeric(13,2)) \n\t\t\t\t\tWHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
                $payRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
                $sql = "\n\t\t\t\t\tUPDATE cubit.open_stmnt \n\t\t\t\t\tSET balance = (balance - {$val}::numeric(13,2)) \n\t\t\t\t\tWHERE invid = '{$inv['invnum']}' AND div = '" . USER_DIV . "'";
                $payRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
                # record the payment on the statement
                $sql = "\n\t\t\t\t\tINSERT INTO cubit.stmnt (\n\t\t\t\t\t\tcusnum, invid, amount, date, \n\t\t\t\t\t\ttype, div, allocation_date\n\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t'{$id}','{$inv['invnum']}', '" . ($val - $val * 2) . "', '{$accdate}', \n\t\t\t\t\t\t'Payment for Invoice No. {$inv['invnum']}', '" . USER_DIV . "', '{$inv['odate']}'\n\t\t\t\t\t)";
                $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
                custledger($cus['cusnum'], $link['accnum'], $accdate, $inv['invnum'], "Payment for Invoice No. {$inv['invnum']}", $val, "c");
                $rinvids .= "|{$invids[$key]}";
                $amounts .= "|{$paidamt[$key]}";
                if ($inv['prd'] == "0") {
                    $inv['prd'] = PRD_DB;
                }
                $invprds .= "|{$inv['prd']}";
                $rages .= "|0";
                $invidsers .= " - {$inv['invnum']}";
            }
        } elseif ($arr[0] == "n") {
            db_connect();
            $get_sql = "\n\t\t\t\tSELECT invnum, invid, balance, odate \n\t\t\t\tFROM nons_invoices \n\t\t\t\tWHERE cusid='{$id}' AND done='y' AND balance>0 AND div='" . USER_DIV . "' AND invid = '{$arr['2']}' LIMIT 1";
            $run_sql = db_exec($get_sql) or errDie("Unable to get non stock information.");
            if (pg_numrows($run_sql) > 0) {
                $inv = pg_fetch_array($run_sql);
                $invid = $inv['invid'];
                $val = allocamt($out, $inv["balance"]);
                if ($val == 0.0) {
                    continue;
                }
                $inv['invnum'] += 0;
                # reduce the money that has been paid
                $sql = "\n\t\t\t\t\tUPDATE cubit.nons_invoices \n\t\t\t\t\tSET balance = (balance - {$val}::numeric(13,2)) \n\t\t\t\t\tWHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
                $payRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
                $sql = "\n\t\t\t\t\tUPDATE cubit.open_stmnt \n\t\t\t\t\tSET balance = (balance - {$val}::numeric(13,2)) \n\t\t\t\t\tWHERE invid = '{$inv['invnum']}' AND div = '" . USER_DIV . "'";
                $payRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
                # record the payment on the statement
                $sql = "\n\t\t\t\t\tINSERT INTO cubit.stmnt (\n\t\t\t\t\t\tcusnum, invid, amount, date, \n\t\t\t\t\t\ttype, \n\t\t\t\t\t\tdiv, allocation_date\n\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t'{$id}', '{$inv['invnum']}', '" . ($val - $val * 2) . "', '{$accdate}', \n\t\t\t\t\t\t'Payment for Non Stock Invoice No. {$inv['invnum']} - {$inv['descrip']}', \n\t\t\t\t\t\t'" . USER_DIV . "', '{$inv['odate']}'\n\t\t\t\t\t)";
                $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
                custledger($cus['cusnum'], $link['accnum'], $accdate, $inv['invnum'], "Payment for Non Stock Invoice No. {$inv['invnum']} - {$inv['descrip']}", $val, "c");
                $rinvids .= "|{$invids[$key]}";
                $amounts .= "|{$paidamt[$key]}";
                $invprds .= "|0";
                $rages .= "|{$inv['age']}";
                $invidsers .= " - {$inv['invnum']}";
            }
        } else {
            db_connect();
            $sqls = array();
            for ($i = 1; $i <= 12; ++$i) {
                $sqls[] = "\n\t\t\t\t\tSELECT invnum, invid, balance, odate, '{$i}' AS prd  \n\t\t\t\t\tFROM \"{$i}\".pinvoices \n\t\t\t\t\tWHERE cusnum='{$id}' AND done='y' AND balance > 0 AND div='" . USER_DIV . "' AND invid = '{$arr['2']}'";
            }
            $get_sql = implode(" UNION ", $sqls);
            $run_sql = db_exec($get_sql) or errDie("Unable to get pos invoice information.");
            if (pg_numrows($run_sql) > 0) {
                $inv = pg_fetch_array($run_sql);
                $invid = $inv['invid'];
                $val = allocamt($out, $inv["balance"]);
                if ($val == 0.0) {
                    continue;
                }
                // reduce the invoice balance
                $sql = "\n\t\t\t\t\tUPDATE \"{$inv['prd']}\".pinvoices \n\t\t\t\t\tSET balance = (balance - {$val}::numeric(13,2)) \n\t\t\t\t\tWHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
                $payRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
                $sql = "\n\t\t\t\t\tUPDATE cubit.open_stmnt \n\t\t\t\t\tSET balance = (balance - {$val}::numeric(13,2)) \n\t\t\t\t\tWHERE invid = '{$inv['invnum']}' AND div = '" . USER_DIV . "'";
                $payRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
                # record the payment on the statement
                $sql = "\n\t\t\t\t\tINSERT INTO cubit.stmnt (\n\t\t\t\t\t\tcusnum, invid, amount, date, \n\t\t\t\t\t\ttype, div, allocation_date\n\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t'{$cus['cusnum']}', '{$inv['invnum']}', '" . ($val - $val * 2) . "', '{$accdate}', \n\t\t\t\t\t\t'Payment for Non Stock Invoice No. {$inv['invnum']}', '" . USER_DIV . "', '{$inv['odate']}'\n\t\t\t\t\t)";
                $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
                custledger($cus['cusnum'], $link['accnum'], $accdate, $inv['invnum'], "Payment for Non Stock Invoice No. {$inv['invnum']}", $val, "c");
                $rinvids .= "|{$invids[$key]}";
                $amounts .= "|{$paidamt[$key]}";
                $invprds .= "|{$inv['prd']}";
                $rages .= "|0";
                $invidsers .= " - {$inv['invnum']}";
            }
        }
    }
    #if there is any amount unallocated, it goes to general transaction
    $confirm .= "\n\t\t<tr class='" . bg_class() . "'>\n\t\t\t<td colspan='6'><b>A general transaction will credit the client's account with " . CUR . " {$out} </b></td>\n\t\t</tr>";
    vsprint($out);
    $confirm .= "<input type='hidden' name='out' value='{$out}'>";
    ###############################################################################################################################
    ###############################################################################################################################
    ###############################################################################################################################
    #######################################################################################################
    ########################################### PROCESS ###################################################
    #######################################################################################################
    # update the customer (make balance less)
    $sql = "\n\t\tUPDATE cubit.customers \n\t\tSET balance = (balance - '{$amount}'::numeric(13,2)) \n\t\tWHERE cusnum = '{$id}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
    $cols = grp(m("bankid", $bankid), m("trantype", "deposit"), m("date", $accdate), m("name", "{$cus['cusname']} {$cus['surname']}"), m("descript", "Payment for Invoices {$invidsers} from customer {$cus['cusname']} {$cus['surname']}"), m("cheqnum", $cheque), m("amount", $amount), m("banked", "no"), m("accinv", $dept["debtacc"]), m("cusnum", $cus["cusnum"]), m("rinvids", $rinvids), m("amounts", $amounts), m("invprds", $invprds), m("rages", $rages), m("reference", $reference), m("div", USER_DIV));
    $dbobj = new dbUpdate("cashbook", "cubit", $cols);
    $dbobj->run(DB_INSERT);
    $dbobj->free();
    writetrans($link['accnum'], $dept['debtacc'], $accdate, $refnum, $amount, "Payment for Invoices {$invidsers} from customer {$cus['cusname']} {$cus['surname']}");
    db_conn('cubit');
    if ($out > 0) {
        /* START OPEN ITEMS */
        $openstmnt = new dbSelect("open_stmnt", "cubit", grp(m("where", "balance>0 AND cusnum='{$id}'"), m("order", "date")));
        $openstmnt->run();
        $open_out = $out;
        $i = 0;
        $ox = "";
        while ($od = $openstmnt->fetch_array()) {
            if ($open_out == 0) {
                continue;
            }
            $oid = $od['id'];
            if ($open_out >= $od['balance']) {
                $open_amount[$oid] = $od['balance'];
                $open_out = sprint($open_out - $od['balance']);
                $ox .= "\n\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t<td><input type='hidden' size='20' name='open[{$oid}]' value='{$oid}'>{$od['type']}</td>\n\t\t\t\t\t\t<td>" . CUR . " {$od['balance']}</td>\n\t\t\t\t\t\t<td>{$od['date']}</td>\n\t\t\t\t\t\t<td><input type='hidden' name='open_amount[{$oid}]' value='{$open_amount[$oid]}'>" . CUR . " {$open_amount[$oid]}</td>\n\t\t\t\t\t</tr>";
                $Sl = "UPDATE cubit.open_stmnt SET balance=balance-'{$open_amount[$oid]}' WHERE id='{$oid}'";
                $Ri = db_exec($Sl) or errDie("Unable to update statement.");
            } elseif ($open_out < $od['balance']) {
                $open_amount[$oid] = $open_out;
                $open_out = 0;
                $ox .= "\n\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t<td><input type='hidden' size='20' name='open[{$oid}]' value='{$od['id']}'>{$od['type']}</td>\n\t\t\t\t\t\t<td>" . CUR . " {$od['balance']}</td>\n\t\t\t\t\t\t<td>{$od['date']}</td>\n\t\t\t\t\t\t<td><input type='hidden' name='open_amount[{$oid}]' value='{$open_amount[$oid]}'>" . CUR . " {$open_amount[$oid]}</td>\n\t\t\t\t\t</tr>";
                $Sl = "UPDATE cubit.open_stmnt SET balance=balance-'{$open_amount[$oid]}' WHERE id='{$oid}'";
                $Ri = db_exec($Sl) or errDie("Unable to update statement.");
            }
            $i++;
        }
        if (open()) {
            $bout = $out;
            $out = $open_out;
            if ($out > 0) {
                $sql = "\n\t\t\t\t\tINSERT INTO cubit.open_stmnt (\n\t\t\t\t\t\tcusnum, invid, amount, balance, date, type, st, div\n\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t'{$cus['cusnum']}', '0', '-{$out}', '-{$out}', '{$accdate}', 'Payment Received', 'n', '" . USER_DIV . "'\n\t\t\t\t\t)";
                $stmntRslt = db_exec($sql) or errDie("Unable to Insert statement record in Cubit.", SELF);
            }
            $out = $bout;
        }
        if ($out > 0) {
            recordCT($out, $cus['cusnum'], $accdate, 0);
            $cols = grp(m("cusnum", $cus["cusnum"]), m("invid", 0), m("amount", -$out), m("date", $accdate), m("type", "Payment Received"), m("div", USER_DIV), m("allocation_date", $accdate));
            $dbobj = new dbUpdate("stmnt", "cubit", $cols);
            $dbobj->run(DB_INSERT);
            $dbobj->free();
            custledger($cus['cusnum'], $link['accnum'], $accdate, "PAYMENT", "Payment received.", $out, "c");
        }
    }
    /* start moving invoices */
    // move invoices that are fully paid
    $sql = "SELECT * FROM cubit.invoices WHERE balance=0 AND printed = 'y' AND done = 'y' AND div = '" . USER_DIV . "'";
    $invbRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
    while ($x = pg_fetch_array($invbRslt)) {
        if (($prd = $x['prd']) == "0") {
            $prd = PRD_DB;
        }
        // move invoice
        $cols = grp(m("invid", $x["invid"]), m("invnum", $x["invnum"]), m("deptid", $x["deptid"]), m("cusnum", $x["cusnum"]), m("deptname", $x["deptname"]), m("cusacc", $x["cusacc"]), m("cusname", $x["cusname"]), m("surname", $x["surname"]), m("cusaddr", $x["cusaddr"]), m("cusvatno", $x["cusvatno"]), m("cordno", $x["cordno"]), m("ordno", $x["ordno"]), m("chrgvat", $x["chrgvat"]), m("terms", $x["terms"]), m("traddisc", $x["traddisc"]), m("salespn", $x["salespn"]), m("odate", $x["odate"]), m("delchrg", $x["delchrg"]), m("subtot", $x["subtot"]), m("vat", $x["vat"]), m("total", $x["total"]), m("age", $x["age"]), m("comm", $x["comm"]), m("discount", $x["discount"]), m("delivery", $x["delivery"]), m("docref", $x["docref"]), m("prd", $x["prd"]), m("delvat", $x["delvat"]), m("balance", 0), m("printed", "y"), m("done", "y"), m("username", USER_NAME), m("div", USER_DIV));
        $dbobj = new dbUpdate("invoices", $prd, $cols);
        $dbobj->run(DB_INSERT);
        $dbobj->free();
        // record movement
        $cols = grp(m("invtype", "inv"), m("invnum", $x["invnum"]), m("prd", $x["prd"]), m("docref", $x["docref"]), m("div", USER_DIV));
        $dbobj->setTable("movinv", "cubit");
        $dbobj->setOpt($cols);
        $dbobj->run();
        $dbobj->free();
        // move invoice items
        $inv_items = new dbSelect("inv_items", "cubit", grp(m("where", wgrp(m("invid", $x["invid"]), m("div", USER_DIV)))));
        $inv_items->run();
        while ($xi = $inv_items->fetch_array()) {
            $xi['vatcode'] += 0;
            $xi['account'] += 0;
            $xi['del'] += 0;
            $cols = grp(m("invid", $x["invid"]), m("whid", $xi["whid"]), m("stkid", $xi["stkid"]), m("qty", $xi["qty"]), m("unitcost", $xi["unitcost"]), m("amt", $xi["amt"]), m("disc", $xi["disc"]), m("discp", $xi["discp"]), m("vatcode", $xi["vatcode"]), m("account", $xi["account"]), m("description", $xi["description"]), m("del", $xi["del"]), m("noted", $xi["noted"]), m("serno", $xi["serno"]), m("div", USER_DIV));
            $dbobj->setTable("inv_items", $prd);
            $dbobj->setOpt($cols);
            $dbobj->run();
            $dbobj->free();
        }
        /* remove invoice from cubit schema */
        $dbobj = new dbDelete("invoices", "cubit", wgrp(m("invid", $x["invid"]), m("div", USER_DIV)));
        $dbobj->run();
        $dbobj->setTable("inv_items", "cubit");
        $dbobj->run();
    }
}
コード例 #19
0
function write($_POST)
{
    extract($_POST);
    if (isset($back)) {
        unset($_POST["back"]);
        return alloc($_POST);
    }
    # CHECK IF THIS DATE IS IN THE BLOCKED RANGE
    $blocked_date_from = getCSetting("BLOCKED_FROM");
    $blocked_date_to = getCSetting("BLOCKED_TO");
    require_lib("validate");
    $v = new validate();
    $v->isOk($all, "num", 1, 1, "Invalid allocation.");
    $v->isOk($rec_amount, "num", 1, 5, "Invalid amount of entries.");
    for ($t = 0; $t < $rec_amount; $t++) {
        if (!isset($descript[$t]) or !isset($reference[$t]) or !isset($setamt[$t]) or empty($descript[$t]) or empty($reference[$t]) or empty($setamt[$t])) {
            continue;
        }
        $v->isOk($bankid[$t], "num", 1, 30, "Invalid Bank Account.");
        $v->isOk($date[$t], "date", 1, 14, "Invalid Date.");
        $v->isOk($out[$t], "float", 1, 40, "Invalid out amount.");
        $v->isOk($descript[$t], "string", 0, 255, "Invalid Description.");
        $v->isOk($reference[$t], "string", 0, 50, "Invalid Reference Name/Number.");
        $v->isOk($cheqnum[$t], "num", 0, 30, "Invalid Cheque number.");
        $v->isOk($amt[$t], "float", 1, 40, "Invalid amount.");
        $v->isOk($setamt[$t], "float", 1, 40, "Invalid Settlement amount.");
        $v->isOk($setvat[$t], "string", 1, 10, "Invalid Settlement VAT Option.");
        $v->isOk($setvatcode[$t], "string", 1, 40, "Invalid Settlement VAT code");
        $v->isOk($cusid[$t], "num", 1, 40, "Invalid customer number.");
        $v->isOk($out1[$t], "float", 0, 40, "Invalid paid amount(currant).");
        $v->isOk($out2[$t], "float", 0, 40, "Invalid paid amount(30).");
        $v->isOk($out3[$t], "float", 0, 40, "Invalid paid amount(60).");
        $v->isOk($out4[$t], "float", 0, 40, "Invalid paid amount(90).");
        $v->isOk($out5[$t], "float", 0, 40, "Invalid paid amount(120).");
        if (isset($invids[$t])) {
            foreach ($invids[$t] as $key => $value) {
                $v->isOk($invids[$t][$key], "num", 1, 50, "Invalid Invoice No.");
                $v->isOk($paidamt[$t][$key], "float", 1, 40, "Invalid amount to be paid.");
            }
        }
        if (strtotime($date[$t]) >= strtotime($blocked_date_from) and strtotime($date[$t]) <= strtotime($blocked_date_to) and !user_is_admin(USER_ID)) {
            return "<li class='err'>Period Range Is Blocked. Only an administrator can process entries within this period.</li>";
        }
    }
    if ($v->isError()) {
        $confirm = $v->genErrors();
        return $confirm . confirm($_POST);
    }
    for ($t = 0; $t < $rec_amount; $t++) {
        if (!isset($descript[$t]) or !isset($reference[$t]) or !isset($setamt[$t]) or empty($descript[$t]) or empty($reference[$t]) or empty($setamt[$t])) {
            continue;
        }
        /* get bank account id */
        if (($bank_acc[$t] = getbankaccid($bankid[$t])) === false) {
            $sql = "SELECT accid FROM core.accounts WHERE accname='Cash on Hand'";
            $rslt = db_exec($sql);
            if (pg_num_rows($rslt) < 1) {
                if ($bankid[$t] == 0) {
                    return "There is no 'Cash on Hand' account, there was one, but\n\t\t\t\t\t\t**s not there now, you mudst have deleted it, if you want\n\t\t\t\t\t\tto use cash functionality please create a 'Cash on Hand' account.";
                } else {
                    return "Invalid bank acc.";
                }
            }
            $bank_acc[$t] = pg_fetch_result($rslt, 0);
        }
        $cus = qryCustomer($cusid[$t], "cusnum, deptid, cusname, surname");
        $dept = qryDepartment($cus["deptid"], "debtacc");
        $refnum = getrefnum();
        pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
        # date format
        $sdate[$t] = explode("-", $date[$t]);
        $sdate[$t] = $sdate[$t][2] . "-" . $sdate[$t][1] . "-" . $sdate[$t][0];
        $cheqnum[$t] = 0 + $cheqnum[$t];
        $pay = "";
        $accdate[$t] = $sdate[$t];
        /* Paid invoices */
        $invidsers = "";
        $rinvids = "";
        $amounts = "";
        $invprds = "";
        $rages = "";
        /* OPTION 1 : AUTO ALLOCATE (write) */
        if ($all == 0) {
            # update the customer (make balance less)
            $sql = "UPDATE cubit.customers SET balance = (balance - '{$amt[$t]}'::numeric(13,2))\n\t\t\t\t\tWHERE cusnum = '{$cus['cusnum']}' AND div = '" . USER_DIV . "'";
            $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
            if (isset($invids[$t])) {
                foreach ($invids[$t] as $key => $value) {
                    $ii = $invids[$t][$key];
                    $pp = $paidamt[$t][$key];
                    /* OPTION 1: STOCK INVOICES */
                    if (!isset($itype[$t][$ii]) && !isset($ptype[$t][$ii])) {
                        $sql = "SELECT prd,invnum,odate FROM cubit.invoices\n\t\t\t\t\t\t\t\tWHERE invid ='{$ii}' AND div = '" . USER_DIV . "'";
                        $invRslt = db_exec($sql) or errDie("Unable to retrieve invoice details from database.");
                        if (pg_numrows($invRslt) < 1) {
                            return "<li class='err'>Invalid Invoice Number.</li>";
                        }
                        $inv = pg_fetch_array($invRslt);
                        $inv['invnum'] += 0;
                        // reduce invoice balance
                        $sql = "UPDATE cubit.invoices \n\t\t\t\t\t\t\t\tSET balance = (balance - {$pp}::numeric(13,2))\n\t\t\t\t\t\t\t\tWHERE invid = '{$ii}' AND div = '" . USER_DIV . "'";
                        $payRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
                        $sql = "UPDATE cubit.open_stmnt \n\t\t\t\t\t\t\t\tSET balance = (balance - {$pp}::numeric(13,2))\n\t\t\t\t\t\t\t\tWHERE invid = '{$inv['invnum']}' AND div = '" . USER_DIV . "'";
                        $payRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
                        # record the payment on the statement
                        $sql = "\n\t\t\t\t\t\t\tINSERT INTO cubit.stmnt (\n\t\t\t\t\t\t\t\tcusnum, invid, amount, date, \n\t\t\t\t\t\t\t\ttype, div, allocation_date\n\t\t\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t\t\t'{$cus['cusnum']}', '{$inv['invnum']}', '" . ($pp - $pp * 2) . "', '{$sdate[$t]}', \n\t\t\t\t\t\t\t\t'Payment for Invoice No. {$inv['invnum']}', '" . USER_DIV . "', '{$inv['odate']}'\n\t\t\t\t\t\t\t)";
                        $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
                        custledger($cus['cusnum'], $bank_acc[$t], $sdate[$t], $inv['invnum'], "Payment for Invoice No. {$inv['invnum']}", $paidamt[$t][$key], "c");
                        $rinvids .= "|{$invids[$t]}[{$key}]";
                        $amounts .= "|{$pp}";
                        if ($inv['prd'] == "0") {
                            $inv['prd'] = PRD_DB;
                        }
                        $invprds .= "|{$inv['prd']}";
                        $rages .= "|0";
                        $invidsers .= " - {$inv['invnum']}";
                        /* OPTION 1: NONS STOCK INVOICES */
                    } else {
                        if (!isset($ptype[$t][$ii])) {
                            $sql = "SELECT prd,invnum,descrip,age,odate FROM cubit.nons_invoices\n\t\t\t\t\t\t\t\tWHERE invid ='{$ii}' AND div = '" . USER_DIV . "'";
                            $invRslt = db_exec($sql) or errDie("Unable to retrieve invoice details from database.");
                            if (pg_numrows($invRslt) < 1) {
                                return "<li class='err'>Invalid Invoice Number.</li>";
                            }
                            $inv = pg_fetch_array($invRslt);
                            $inv['invnum'] += 0;
                            # reduce the money that has been paid
                            $sql = "UPDATE cubit.nons_invoices\n\t\t\t\t\t\t\t\tSET balance = (balance - {$pp}::numeric(13,2))\n\t\t\t\t\t\t\t\tWHERE invid = '{$ii}' AND div = '" . USER_DIV . "'";
                            $payRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
                            $sql = "UPDATE cubit.open_stmnt\n\t\t\t\t\t\t\t\tSET balance = (balance - {$pp}::numeric(13,2))\n\t\t\t\t\t\t\t\tWHERE invid = '{$inv['invnum']}' AND div = '" . USER_DIV . "'";
                            $payRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
                            # record the payment on the statement
                            $sql = "\n\t\t\t\t\t\t\tINSERT INTO cubit.stmnt (\n\t\t\t\t\t\t\t\tcusnum, invid, amount, date, \n\t\t\t\t\t\t\t\ttype, div, allocation_date\n\t\t\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t\t\t'{$cus['cusnum']}', '{$inv['invnum']}', '" . ($pp - $pp * 2) . "', '{$sdate[$t]}', \n\t\t\t\t\t\t\t\t'Payment for Non Stock Invoice No. {$inv['invnum']} - {$inv['descrip']}', '" . USER_DIV . "', '{$inv['odate']}'\n\t\t\t\t\t\t\t)";
                            $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
                            custledger($cus['cusnum'], $bank_acc[$t], $sdate[$t], $inv['invnum'], "Payment for Non Stock Invoice No. {$inv['invnum']} - {$inv['descrip']}", $paidamt[$t][$key], "c");
                            recordCT($pp, $cus['cusnum'], $inv['age'], $accdate[$t]);
                            $rinvids .= "|{$ii}";
                            $amounts .= "|{$pp}";
                            $invprds .= "|0";
                            $rages .= "|{$inv['age']}";
                            $invidsers .= " - {$inv['invnum']}";
                        } else {
                            /* pos invoices */
                            $sqls = array();
                            for ($i = 1; $i <= 12; ++$i) {
                                $sqls[] = "SELECT '{$i}' AS prd,invid,invnum,odate FROM \"{$i}\".pinvoices \n\t\t\t\t\t\t\t\t\tWHERE invid='{$ii}' AND div='" . USER_DIV . "'";
                            }
                            $sql = implode(" UNION ", $sqls);
                            $invRslt = db_exec($sql) or errDie("Unable to retrieve invoice details from database.");
                            if (pg_numrows($invRslt) < 1) {
                                return "<li class='err'>Invalid Invoice Number.</li>";
                            }
                            $inv = pg_fetch_array($invRslt);
                            // reduce the invoice balance
                            $sql = "UPDATE \"{$inv['prd']}\".pinvoices \n\t\t\t\t\t\t\t\tSET balance = (balance - {$pp}::numeric(13,2)) \n\t\t\t\t\t\t\t\tWHERE invid = '{$ii}' AND div = '" . USER_DIV . "'";
                            $payRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
                            $sql = "UPDATE cubit.open_stmnt \n\t\t\t\t\t\t\t\tSET balance = (balance - {$pp}::numeric(13,2)) \n\t\t\t\t\t\t\t\tWHERE invid = '{$inv['invnum']}' AND div = '" . USER_DIV . "'";
                            $payRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
                            # record the payment on the statement
                            $sql = "\n\t\t\t\t\t\t\tINSERT INTO cubit.stmnt (\n\t\t\t\t\t\t\t\tcusnum, invid, amount, date, type, div, allocation_date\n\t\t\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t\t\t'{$cus['cusnum']}','{$inv['invnum']}', '" . ($pp - $pp * 2) . "','{$sdate[$t]}', 'Payment for Non Stock Invoice No. {$inv['invnum']}', '" . USER_DIV . "', '{$inv['odate']}'\n\t\t\t\t\t\t\t)";
                            $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
                            custledger($cus['cusnum'], $bank_acc[$t], $sdate[$t], $inv['invnum'], "Payment for Non Stock Invoice No. {$inv['invnum']}", $paidamt[$t][$key], "c");
                            recordCT($paidamt[$t][$key], $cus['cusnum'], 0, $accdate[$t]);
                            $rinvids .= "|{$invids[$t]}[{$key}]";
                            $amounts .= "|{$paidamt[$t]}[{$key}]";
                            $invprds .= "|{$inv['prd']}";
                            //$rages .= "|$inv[age]";
                            $invidsers .= " - {$inv['invnum']}";
                        }
                    }
                }
            }
            $cols = grp(m("bankid", $bankid[$t]), m("trantype", "deposit"), m("date", $sdate[$t]), m("name", "{$cus['cusname']} {$cus['surname']}"), m("descript", "Payment for Invoices {$invidsers} from customer {$cus['cusname']} {$cus['surname']}"), m("cheqnum", $cheqnum[$t]), m("amount", $amt[$t]), m("banked", "no"), m("accinv", $dept["debtacc"]), m("cusnum", $cus["cusnum"]), m("rinvids", $rinvids), m("amounts", $amounts), m("invprds", $invprds), m("rages", $rages), m("reference", $reference[$t]), m("div", USER_DIV));
            $dbobj = new dbUpdate("cashbook", "cubit", $cols);
            $dbobj->run(DB_INSERT);
            $dbobj->free();
            /*
            $sql = "INSERT INTO cashbook(bankid, trantype, date, name, descript,
            			cheqnum, amount, banked, accinv, cusnum, rinvids, amounts,
            			invprds, rages, reference, div)
            		VALUES ('$bankid', 'deposit', '$sdate', '$cus[cusname] $cus[surname]',
            			'',
            			'$cheqnum', '$amt', 'no', '$dept[debtacc]', '$cus[cusnum]',
            			'$rinvids', '$amounts', '$invprds', '$rages', '$reference',
            			'".USER_DIV."')";
            $Rslt = db_exec ($sql) or errDie ("Unable to add bank payment to database.",SELF);
            */
            $refnum = getrefnum($accdate[$t]);
            writetrans($bank_acc[$t], $dept['debtacc'], $accdate[$t], $refnum, $amt[$t], "Payment for Invoices {$invidsers} from customer {$cus['cusname']} {$cus['surname']}");
            db_conn('cubit');
            if ($out > 0) {
                /* START OPEN ITEMS */
                $openstmnt = new dbSelect("open_stmnt", "cubit", grp(m("where", "balance>0 AND cusnum='{$cusid[$t]}'"), m("order", "date")));
                $openstmnt->run();
                $open_out[$t] = $out[$t];
                $i = 0;
                $ox = "";
                while ($od = $openstmnt->fetch_array()) {
                    if ($open_out[$t] == 0) {
                        continue;
                    }
                    $oid = $od['id'];
                    if ($open_out[$t] >= $od['balance']) {
                        $open_amount[$t][$oid] = $od['balance'];
                        $open_out[$t] = sprint($open_out[$t] - $od['balance']);
                        $ox .= "\n\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t<td><input type='hidden' size='20' name='open[{$t}][{$oid}]' value='{$oid}'>{$od['type']}</td>\n\t\t\t\t\t\t\t\t<td>" . CUR . " {$od['balance']}</td>\n\t\t\t\t\t\t\t\t<td>{$od['date']}</td>\n\t\t\t\t\t\t\t\t<td><input type='hidden' name='open_amount[{$t}][{$oid}]' value='{$open_amount[$t]}[{$oid}]'>" . CUR . " {$open_amount[$t]}[{$oid}]</td>\n\t\t\t\t\t\t\t</tr>";
                        $Sl = "UPDATE cubit.open_stmnt SET balance=balance-'" . $open_amount[$t][$oid] . "' WHERE id='{$oid}'";
                        $Ri = db_exec($Sl) or errDie("Unable to update statement.");
                    } elseif ($open_out < $od['balance']) {
                        $open_amount[$t][$oid] = $open_out[$t];
                        $open_out = 0;
                        $ox .= "\n\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t<td><input type='hidden' size='20' name='open[{$t}][{$oid}]' value='{$od['id']}'>{$od['type']}</td>\n\t\t\t\t\t\t\t\t<td>" . CUR . " {$od['balance']}</td>\n\t\t\t\t\t\t\t\t<td>{$od['date']}</td>\n\t\t\t\t\t\t\t\t<td><input type='hidden' name='open_amount[{$t}][{$oid}]' value='{$open_amount[$t]}[{$oid}]'>" . CUR . " {$open_amount[$t]}[{$oid}]</td>\n\t\t\t\t\t\t\t</tr>";
                        $Sl = "UPDATE cubit.open_stmnt SET balance=balance-'" . $open_amount[$t][$oid] . "' WHERE id='{$oid}'";
                        $Ri = db_exec($Sl) or errDie("Unable to update statement.");
                    }
                    $i++;
                }
                if (open()) {
                    $bout[$t] = $out[$t];
                    $out[$t] = $open_out[$t];
                    if ($out > 0) {
                        $sql = "\n\t\t\t\t\t\t\tINSERT INTO cubit.open_stmnt (\n\t\t\t\t\t\t\t\tcusnum, invid, amount, balance, date, \n\t\t\t\t\t\t\t\ttype, st, div\n\t\t\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t\t\t'{$cus['cusnum']}', '0', '-{$out[$t]}', '-{$out[$t]}', '{$sdate[$t]}', \n\t\t\t\t\t\t\t\t'Payment Received', 'n', '" . USER_DIV . "'\n\t\t\t\t\t\t\t)";
                        $stmntRslt = db_exec($sql) or errDie("Unable to Insert statement record in Cubit.", SELF);
                        //$confirm .="<tr class='bg-even'><td colspan=4><b>A general transaction will credit the client's account with ".CUR." $out </b></td></tr>";
                    }
                    $out[$t] = $bout[$t];
                } else {
                    //$confirm .="<tr class='bg-even'><td colspan=4><b>A general transaction will credit the client's account with ".CUR." $out </b></td></tr>";}
                }
            }
            if ($out[$t] > 0) {
                recordCT($out[$t], $cus['cusnum'], 0, $accdate[$t]);
                $cols = grp(m("cusnum", $cus["cusnum"]), m("invid", 0), m("amount", -$out[$t]), m("date", $sdate[$t]), m("type", "Payment Received"), m("div", USER_DIV), m("allocation_date", $accdate[$t]));
                $dbobj = new dbUpdate("stmnt", "cubit", $cols);
                $dbobj->run(DB_INSERT);
                $dbobj->free();
                custledger($cus['cusnum'], $bank_acc[$t], $sdate[$t], "PAYMENT", "Payment received.", $out[$t], "c");
            }
        }
        /* start moving invoices */
        // move invoices that are fully paid
        $sql = "SELECT * FROM cubit.invoices WHERE balance=0 AND printed = 'y' AND done = 'y' AND div = '" . USER_DIV . "'";
        $invbRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
        while ($x = pg_fetch_array($invbRslt)) {
            if (($prd = $x['prd']) == "0") {
                $prd = PRD_DB;
            }
            // move invoice
            $cols = grp(m("invid", $x["invid"]), m("invnum", $x["invnum"]), m("deptid", $x["deptid"]), m("cusnum", $x["cusnum"]), m("deptname", $x["deptname"]), m("cusacc", $x["cusacc"]), m("cusname", $x["cusname"]), m("surname", $x["surname"]), m("cusaddr", $x["cusaddr"]), m("cusvatno", $x["cusvatno"]), m("cordno", $x["cordno"]), m("ordno", $x["ordno"]), m("chrgvat", $x["chrgvat"]), m("terms", $x["terms"]), m("traddisc", $x["traddisc"]), m("salespn", $x["salespn"]), m("odate", $x["odate"]), m("delchrg", $x["delchrg"]), m("subtot", $x["subtot"]), m("vat", $x["vat"]), m("total", $x["total"]), m("age", $x["age"]), m("comm", $x["comm"]), m("discount", $x["discount"]), m("delivery", $x["delivery"]), m("docref", $x["docref"]), m("prd", $x["prd"]), m("delvat", $x["delvat"]), m("balance", 0), m("printed", "y"), m("done", "y"), m("username", USER_NAME), m("div", USER_DIV));
            $dbobj = new dbUpdate("invoices", $prd, $cols);
            $dbobj->run(DB_INSERT);
            $dbobj->free();
            // record movement
            $cols = grp(m("invtype", "inv"), m("invnum", $x["invnum"]), m("prd", $x["prd"]), m("docref", $x["docref"]), m("div", USER_DIV));
            $dbobj->setTable("movinv", "cubit");
            $dbobj->setOpt($cols);
            $dbobj->run();
            $dbobj->free();
            // move invoice items
            $inv_items = new dbSelect("inv_items", "cubit", grp(m("where", wgrp(m("invid", $x["invid"]), m("div", USER_DIV)))));
            $inv_items->run();
            while ($xi = $inv_items->fetch_array()) {
                $xi['vatcode'] += 0;
                $xi['account'] += 0;
                $xi['del'] += 0;
                $cols = grp(m("invid", $x["invid"]), m("whid", $xi["whid"]), m("stkid", $xi["stkid"]), m("qty", $xi["qty"]), m("unitcost", $xi["unitcost"]), m("amt", $xi["amt"]), m("disc", $xi["disc"]), m("discp", $xi["discp"]), m("vatcode", $xi["vatcode"]), m("account", $xi["account"]), m("description", $xi["description"]), m("del", $xi["del"]), m("noted", $xi["noted"]), m("serno", $xi["serno"]), m("div", USER_DIV));
                $dbobj->setTable("inv_items", $prd);
                $dbobj->setOpt($cols);
                $dbobj->run();
                $dbobj->free();
            }
            /* remove invoice from cubit schema */
            $dbobj = new dbDelete("invoices", "cubit", wgrp(m("invid", $x["invid"]), m("div", USER_DIV)));
            $dbobj->run();
            $dbobj->setTable("inv_items", "cubit");
            $dbobj->run();
        }
        /* start moving invoices */
        // move invoices that are fully paid
        $sql = "SELECT * FROM cubit.invoices WHERE balance=0 AND printed = 'y' AND done = 'y' AND div = '" . USER_DIV . "'";
        $invbRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
        while ($x = pg_fetch_array($invbRslt)) {
            if (($prd = $x['prd']) == "0") {
                $prd = PRD_DB;
            }
            // move invoice
            $cols = grp(m("invid", $x["invid"]), m("invnum", $x["invnum"]), m("deptid", $x["deptid"]), m("cusnum", $x["cusnum"]), m("deptname", $x["deptname"]), m("cusacc", $x["cusacc"]), m("cusname", $x["cusname"]), m("surname", $x["surname"]), m("cusaddr", $x["cusaddr"]), m("cusvatno", $x["cusvatno"]), m("cordno", $x["cordno"]), m("ordno", $x["ordno"]), m("chrgvat", $x["chrgvat"]), m("terms", $x["terms"]), m("traddisc", $x["traddisc"]), m("salespn", $x["salespn"]), m("odate", $x["odate"]), m("delchrg", $x["delchrg"]), m("subtot", $x["subtot"]), m("vat", $x["vat"]), m("total", $x["total"]), m("age", $x["age"]), m("comm", $x["comm"]), m("discount", $x["discount"]), m("delivery", $x["delivery"]), m("docref", $x["docref"]), m("prd", $x["prd"]), m("delvat", $x["delvat"]), m("balance", 0), m("printed", "y"), m("done", "y"), m("username", USER_NAME), m("div", USER_DIV));
            $dbobj = new dbUpdate("invoices", $prd, $cols);
            $dbobj->run(DB_INSERT);
            $dbobj->free();
            // record movement
            $cols = grp(m("invtype", "inv"), m("invnum", $x["invnum"]), m("prd", $x["prd"]), m("docref", $x["docref"]), m("div", USER_DIV));
            $dbobj->setTable("movinv", "cubit");
            $dbobj->setOpt($cols);
            $dbobj->run();
            $dbobj->free();
            // move invoice items
            $inv_items = new dbSelect("inv_items", "cubit", grp(m("where", wgrp(m("invid", $x["invid"]), m("div", USER_DIV)))));
            $inv_items->run();
            while ($xi = $inv_items->fetch_array()) {
                $xi['vatcode'] += 0;
                $xi['account'] += 0;
                $xi['del'] += 0;
                $cols = grp(m("invid", $x["invid"]), m("whid", $xi["whid"]), m("stkid", $xi["stkid"]), m("qty", $xi["qty"]), m("unitcost", $xi["unitcost"]), m("amt", $xi["amt"]), m("disc", $xi["disc"]), m("discp", $xi["discp"]), m("vatcode", $xi["vatcode"]), m("account", $xi["account"]), m("description", $xi["description"]), m("del", $xi["del"]), m("noted", $xi["noted"]), m("serno", $xi["serno"]), m("div", USER_DIV));
                $dbobj->setTable("inv_items", $prd);
                $dbobj->setOpt($cols);
                $dbobj->run();
                $dbobj->free();
            }
            /* remove invoice from cubit schema */
            $dbobj = new dbDelete("invoices", "cubit", wgrp(m("invid", $x["invid"]), m("div", USER_DIV)));
            $dbobj->run();
            $dbobj->setTable("inv_items", "cubit");
            $dbobj->run();
        }
        #do journal for the settlement discount here ... now ...
        if ($setamt[$t] > 0) {
            db_conn('core');
            #get settlement accid
            $get_setacc = "SELECT accid FROM accounts WHERE accname = 'Debtors Settlement Discount'";
            $run_setacc = db_exec($get_setacc) or errDie("Unable to get settlement account information");
            $setaccid = pg_fetch_result($run_setacc, 0, 0);
            #calculate the settlement vat ... and amt
            if (isset($setvat[$t]) and $setvat[$t] == 'inc') {
                db_connect();
                $get_vcode = "SELECT * FROM vatcodes WHERE id = '{$setvatcode[$t]}' LIMIT 1";
                $run_vcode = db_exec($get_vcode) or errDie("Unable to get vatcode informtion.");
                if (pg_numrows($run_vcode) < 1) {
                    return "<li class='err'>Settlement Discount VAT Code Not Set.</li>";
                }
                $vd = pg_fetch_array($run_vcode);
                #vat inc ... recalculate the amts
                $setvatamt = sprint($setamt[$t] * ($vd['vat_amount'] / (100 + $vd['vat_amount'])));
                $setamt[$t] = sprint($setamt[$t] - $setvatamt);
                $vatacc = gethook("accnum", "salesacc", "name", "VAT", "VAT");
                $svattot = sprint($setamt[$t] + $setvatamt - ($setamt[$t] + $setvatamt) * 2);
                $svatamt = sprint($setvatamt - $setvatamt * 2);
                #process the vat amt ...
                writetrans($vatacc, $dept['debtacc'], $accdate[$t], $refnum, $setvatamt, "VAT Received on Settlement Discount for Customer : {$cus['cusname']} {$cus['surname']}");
                vatr($vd['id'], $accdate[$t], "OUTPUT", $vd['code'], $refnum, "VAT for Settlement Discount for Customer : {$cus['cusname']} {$cus['surname']}", $svattot, $svatamt);
            } else {
                #no vat for set amt ... do nothing
                $setvatamt = 0;
                $svattot = 0;
                $svatamt = 0;
            }
            writetrans($setaccid, $dept['debtacc'], $accdate[$t], $refnum, sprint($setamt[$t]), "Settlement Discount For {$cus['cusname']} {$cus['surname']}");
            custledger($cus['cusnum'], $bank_acc[$t], $sdate[$t], "{$refnum}", "Payment Settlement Discount Received.", sprint($setamt[$t] + $setvatamt), "c");
            $sql = "\n\t\t\t\tINSERT INTO cubit.stmnt (\n\t\t\t\t\tcusnum, invid, amount, date, \n\t\t\t\t\ttype, div, allocation_date\n\t\t\t\t) VALUES (\n\t\t\t\t\t'{$cus['cusnum']}', '0', '" . $svattot . "', '{$sdate[$t]}', \n\t\t\t\t\t'Settlement Discount for Payment. Ref {$refnum}', '" . USER_DIV . "', '{$accdate[$t]}'\n\t\t\t\t)";
            $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
            db_connect();
            #record this paid settlement discount for reporting ...
            $settl_sql = "\n\t\t\t\tINSERT INTO settlement_cus (\n\t\t\t\t\tcustomer, amt, setamt, setvatamt, setvat, \n\t\t\t\t\tsetvatcode, tdate, sdate, refnum\n\t\t\t\t) VALUES (\n\t\t\t\t\t'{$cus['cusnum']}', '{$amt[$t]}', '{$setamt[$t]}', '{$setvatamt}', '{$setvat[$t]}', \n\t\t\t\t\t'{$setvatcode[$t]}', '{$accdate[$t]}', 'now', '{$refnum[$t]}'\n\t\t\t\t)";
            $run_settl = db_exec($settl_sql) or errDie("Unable to get debtor settlement information.");
        }
        pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
    }
    // status report
    $write = "\n\t\t<table " . TMPL_tblDflts . " width='100%'>\n\t\t\t<tr>\n\t\t\t\t<th>Bank Receipt</th>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Bank Receipt added to cash book.</td>\n\t\t\t</tr>\n\t\t</table>";
    $OUTPUT = "\n\t\t<center>\n\t\t<table width='90%'>\n\t\t\t<tr valign='top'>\n\t\t\t\t<td width='50%'>{$write}</td>\n\t\t\t\t<td align='center'>" . mkQuickLinks(ql("bank-pay-add.php", "Add Bank Payment"), ql("bank-recpt-add.php", "Add Bank Receipt"), ql("bank-recpt-inv.php", "Add Customer Payment"), ql("cashbook-view.php", "View Cash Book")) . "\n\t\t\t\t</td>\n\t\t\t</tr>\n\t\t</table>";
    return $OUTPUT;
}
コード例 #20
0
function write($_POST)
{
    # processes
    db_connect();
    # Get vars
    extract($_POST);
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($cashacc, "num", 1, 30, "Invalid Petty Cash Account.");
    $v->isOk($date, "date", 1, 10, "Invalid Date Entry.");
    $v->isOk($descript, "string", 0, 255, "Invalid Description.");
    $v->isOk($amount, "float", 1, 10, "Invalid amount.");
    $v->isOk($cusid, "num", 1, 20, "Invalid customer account.");
    # Display errors, if any
    if ($v->isError()) {
        $confirm = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $confirm .= "<li class='err'>" . $e["msg"] . "</li>";
        }
        $confirm .= "<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $confirm;
    }
    # date format
    $date = explode("-", $date);
    $date = $date[2] . "-" . $date[1] . "-" . $date[0];
    # Get account name
    $cusRslt = get("cubit", "*", "customers", "cusnum", $cusid);
    $cus = pg_fetch_array($cusRslt);
    db_conn("exten");
    # get debtors control account
    $sql = "SELECT debtacc FROM departments WHERE deptid ='{$cus['deptid']}' AND div = '" . USER_DIV . "'";
    $deptRslt = db_exec($sql);
    $dept = pg_fetch_array($deptRslt);
    pglib_transaction("BEGIN");
    custledger($cusid, $cashacc, $date, '0', "Customer Payment", $amount, "d");
    db_connect();
    $Sl = "\n\t\tINSERT INTO stmnt (\n\t\t\tcusnum, invid, amount, date, type, div, allocation_date\n\t\t) VALUES (\n\t\t\t'{$cusid}', '0', '{$amount}', '{$date}', 'Cash Payment', '" . USER_DIV . "', '{$date}'\n\t\t)";
    $Rs = db_exec($Sl) or errDie("Unable to insert statement record in Cubit.", SELF);
    $sql = "UPDATE customers SET balance = (balance + '{$amount}') WHERE cusnum = '{$cus['cusnum']}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
    custDT($amount, $cus['cusnum']);
    # Record tranfer for patty cash report
    $sql = "\n\t\tINSERT INTO pettyrec (\n\t\t\tdate, type, det, amount, name, div\n\t\t) VALUES (\n\t\t\t'{$date}', 'Req', '{$descript}', '-{$amount}', 'Paid to customer: {$cus['cusname']} {$cus['surname']}', '" . USER_DIV . "'\n\t\t)";
    $Rslt = db_exec($sql) or errDie("Unable to add bank payment to database.", SELF);
    $refnum = getrefnum();
    writetrans($dept['debtacc'], $cashacc, $date, $refnum, $amount, $descript);
    pglib_transaction("COMMIT");
    # status report
    $write = "\n\t\t<table " . TMPL_tblDflts . " width='100%'>\n\t\t\t<tr>\n\t\t\t\t<th>Petty Cash Payment</th>\n\t\t\t</tr>\n\t\t\t<tr class='datacell'>\n\t\t\t\t<td>Petty Cash Payment to customer : {$cus['surname']} added to petty cash book.</td>\n\t\t\t</tr>\n\t\t</table>";
    # main table (layout with menu)
    $OUTPUT = "\n\t\t<center>\n\t\t<table width='90%'>\n\t\t\t<tr valign='top'>\n\t\t\t\t<td width='50%'>{$write}</td>\n\t\t\t\t<td align='center'>\n\t\t\t\t\t<table " . TMPL_tblDflts . " width='80%'>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<th>Quick Links</th>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td><a href='bank-pay-add.php'>Add Petty Cash Payment</a></td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td><a href='bank-recpt-add.php'>Add Petty Cash Receipt</a></td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td><a href='cashbook-view.php'>View Cash Book</a></td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t</table>\n\t\t\t\t</td>\n\t\t\t</tr>\n\t\t</table>";
    return $OUTPUT;
}
コード例 #21
0
function write($_POST)
{
    extract($_POST);
    if (isset($back)) {
        unset($_POST["back"]);
        return alloc($_POST);
    }
    require_lib("validate");
    $v = new validate();
    $v->isOk($all, "num", 1, 1, "Invalid allocation.");
    $v->isOk($bankid, "num", 1, 30, "Invalid Bank Account.");
    $v->isOk($date, "date", 1, 14, "Invalid Date.");
    $v->isOk($out, "float", 1, 40, "Invalid out amount.");
    $v->isOk($descript, "string", 0, 255, "Invalid Description.");
    $v->isOk($reference, "string", 0, 50, "Invalid Reference Name/Number.");
    $v->isOk($cheqnum, "num", 0, 30, "Invalid Cheque number.");
    $v->isOk($amt, "float", 1, 40, "Invalid amount.");
    $v->isOk($cusid, "num", 1, 40, "Invalid customer number.");
    $v->isOk($out1, "float", 0, 40, "Invalid paid amount(currant).");
    $v->isOk($out2, "float", 0, 40, "Invalid paid amount(30).");
    $v->isOk($out3, "float", 0, 40, "Invalid paid amount(60).");
    $v->isOk($out4, "float", 0, 40, "Invalid paid amount(90).");
    $v->isOk($out5, "float", 0, 40, "Invalid paid amount(120).");
    if (isset($invids)) {
        foreach ($invids as $key => $value) {
            $v->isOk($invids[$key], "num", 1, 50, "Invalid Invoice No.");
            $v->isOk($paidamt[$key], "float", 1, 40, "Invalid amount to be paid.");
        }
    }
    if ($v->isError()) {
        $confirm = $v->genErrors();
        return $confirm . confirm($_POST);
    }
    /* get bank account id of cash on hand account IF this entry is cash */
    if (($bank_acc = getbankaccid($bankid)) === false or $bankid == "0") {
        //old function didnt check if cash is selected ... if(($bank_acc = getbankaccid($bankid)) === false) {
        $sql = "SELECT accid FROM core.accounts WHERE accname='Cash on Hand'";
        $rslt = db_exec($sql);
        if (pg_num_rows($rslt) < 1) {
            if ($bankid == 0) {
                return "There is no 'Cash on Hand' account, there was one, but\n\t\t\t\t\t\t**s not there now, you must have deleted it, if you want\n\t\t\t\t\t\tto use cash functionality please create a 'Cash on Hand' account.";
            } else {
                return "Invalid bank acc.";
            }
        }
        $bank_acc = pg_fetch_result($rslt, 0);
    }
    $cus = qryCustomer($cusid, "cusnum, deptid, cusname, surname");
    $dept = qryDepartment($cus["deptid"], "debtacc");
    $refnum = getrefnum();
    pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
    # date format
    $sdate = explode("-", $date);
    $sdate = $sdate[2] . "-" . $sdate[1] . "-" . $sdate[0];
    $cheqnum = 0 + $cheqnum;
    $pay = "";
    $accdate = $sdate;
    /* Paid invoices */
    $invidsers = "";
    $rinvids = "";
    $amounts = "";
    $invprds = "";
    $rages = "";
    /* OPTION 1 : AUTO ALLOCATE (write) */
    if ($all == 0) {
        # update the customer (make balance less)
        $sql = "UPDATE cubit.customers SET balance = (balance - '{$amt}'::numeric(13,2))\n\t\t\t\tWHERE cusnum = '{$cus['cusnum']}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
        $reverse_allocation_dates = "";
        $reverse_allocation_amounts = "";
        if (isset($invids)) {
            foreach ($invids as $key => $value) {
                $ii = $invids[$key];
                /* OPTION 1: STOCK INVOICES */
                if (!isset($itype[$ii]) && !isset($ptype[$ii])) {
                    $sql = "\n\t\t\t\t\t\tSELECT prd,invnum,odate \n\t\t\t\t\t\tFROM cubit.invoices\n\t\t\t\t\t\tWHERE invid ='{$invids[$key]}' AND div = '" . USER_DIV . "'";
                    $invRslt = db_exec($sql) or errDie("Unable to retrieve invoice details from database.");
                    if (pg_numrows($invRslt) < 1) {
                        return "<li class='err'>Invalid Invoice Number.</li>";
                    }
                    $inv = pg_fetch_array($invRslt);
                    $inv['invnum'] += 0;
                    // reduce invoice balance
                    $sql = "UPDATE cubit.invoices\n\t\t\t\t\t\t\tSET balance = (balance - {$paidamt[$key]}::numeric(13,2))\n\t\t\t\t\t\t\tWHERE invid = '{$invids[$key]}' AND div = '" . USER_DIV . "'";
                    $payRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
                    $sql = "UPDATE cubit.open_stmnt\n\t\t\t\t\t\t\tSET balance = (balance - {$paidamt[$key]}::numeric(13,2))\n\t\t\t\t\t\t\tWHERE invid = '{$inv['invnum']}' AND div = '" . USER_DIV . "'";
                    $payRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
                    # record the payment on the statement
                    $sql = "\n\t\t\t\t\t\tINSERT INTO cubit.stmnt (\n\t\t\t\t\t\t\tcusnum, invid, \n\t\t\t\t\t\t\tamount, date, \n\t\t\t\t\t\t\ttype, div, allocation_date\n\t\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t\t'{$cus['cusnum']}','{$inv['invnum']}', \n\t\t\t\t\t\t\t'" . ($paidamt[$key] - $paidamt[$key] * 2) . "', '{$sdate}', \n\t\t\t\t\t\t\t'Payment for Invoice No. {$inv['invnum']}', '" . USER_DIV . "', '{$inv['odate']}'\n\t\t\t\t\t\t)";
                    if (!(isset($bulk_pay) and strlen($bulk_pay) > 0)) {
                        $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
                    } else {
                        $reverse_allocation_dates .= "{$inv['odate']}|";
                        $reverse_allocation_amounts .= sprint($paidamt[$key] - $paidamt[$key] * 2) . "|";
                    }
                    custledger($cus['cusnum'], $bank_acc, $sdate, $inv['invnum'], "Payment for Invoice No. {$inv['invnum']}", $paidamt[$key], "c");
                    $rinvids .= "|{$invids[$key]}";
                    $amounts .= "|{$paidamt[$key]}";
                    if ($inv['prd'] == "0") {
                        $inv['prd'] = PRD_DB;
                    }
                    $invprds .= "|{$inv['prd']}";
                    $rages .= "|0";
                    $invidsers .= " - {$inv['invnum']}";
                    /* OPTION 1: NONS STOCK INVOICES */
                } else {
                    if (!isset($ptype[$ii])) {
                        $sql = "\n\t\t\t\t\t\tSELECT prd,invnum,descrip,age,odate \n\t\t\t\t\t\tFROM cubit.nons_invoices \n\t\t\t\t\t\tWHERE invid ='{$invids[$key]}' AND div = '" . USER_DIV . "'";
                        $invRslt = db_exec($sql) or errDie("Unable to retrieve invoice details from database.");
                        if (pg_numrows($invRslt) < 1) {
                            return "<li class='err'>Invalid Invoice Number.";
                        }
                        $inv = pg_fetch_array($invRslt);
                        $inv['invnum'] += 0;
                        # reduce the money that has been paid
                        $sql = "UPDATE cubit.nons_invoices\n\t\t\t\t\t\t\tSET balance = (balance - {$paidamt[$key]}::numeric(13,2))\n\t\t\t\t\t\t\tWHERE invid = '{$invids[$key]}' AND div = '" . USER_DIV . "'";
                        $payRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
                        $sql = "UPDATE cubit.open_stmnt\n\t\t\t\t\t\t\tSET balance = (balance - {$paidamt[$key]}::numeric(13,2))\n\t\t\t\t\t\t\tWHERE invid = '{$inv['invnum']}' AND div = '" . USER_DIV . "'";
                        $payRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
                        # record the payment on the statement
                        $sql = "\n\t\t\t\t\t\tINSERT INTO cubit.stmnt (\n\t\t\t\t\t\t\tcusnum, invid, \n\t\t\t\t\t\t\tamount, date, \n\t\t\t\t\t\t\ttype, \n\t\t\t\t\t\t\tdiv, allocation_date\n\t\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t\t'{$cus['cusnum']}', '{$inv['invnum']}', \n\t\t\t\t\t\t\t'" . ($paidamt[$key] - $paidamt[$key] * 2) . "', '{$sdate}', \n\t\t\t\t\t\t\t'Payment for Non Stock Invoice No. {$inv['invnum']} - {$inv['descrip']}', \n\t\t\t\t\t\t\t'" . USER_DIV . "', '{$inv['odate']}'\n\t\t\t\t\t\t)";
                        if (!(isset($bulk_pay) and strlen($bulk_pay) > 0)) {
                            $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
                        } else {
                            $reverse_allocation_dates .= "{$inv['odate']}|";
                            $reverse_allocation_amounts .= sprint($paidamt[$key] - $paidamt[$key] * 2) . "|";
                        }
                        custledger($cus['cusnum'], $bank_acc, $sdate, $inv['invnum'], "Payment for Non Stock Invoice No. {$inv['invnum']} - {$inv['descrip']}", $paidamt[$key], "c");
                        //recordCT($paidamt[$key], $cus['cusnum'],$inv['age'],$accdate);
                        $rinvids .= "|{$invids[$key]}";
                        $amounts .= "|{$paidamt[$key]}";
                        $invprds .= "|0";
                        $rages .= "|{$inv['age']}";
                        $invidsers .= " - {$inv['invnum']}";
                    } else {
                        /* pos invoices */
                        $sqls = array();
                        for ($i = 1; $i <= 12; ++$i) {
                            $sqls[] = "\n\t\t\t\t\t\t\tSELECT '{$i}' AS prd,invid,invnum,odate \n\t\t\t\t\t\t\tFROM \"{$i}\".pinvoices \n\t\t\t\t\t\t\tWHERE invid='{$invids[$key]}' AND div='" . USER_DIV . "'";
                        }
                        $sql = implode(" UNION ", $sqls);
                        $invRslt = db_exec($sql) or errDie("Unable to retrieve invoice details from database.");
                        if (pg_numrows($invRslt) < 1) {
                            return "<li class='err'>Invalid Invoice Number.";
                        }
                        $inv = pg_fetch_array($invRslt);
                        // reduce the invoice balance
                        $sql = "UPDATE \"{$inv['prd']}\".pinvoices\n\t\t\t\t\t\t\tSET balance = (balance - {$paidamt[$key]}::numeric(13,2))\n\t\t\t\t\t\t\tWHERE invid = '{$invids[$key]}' AND div = '" . USER_DIV . "'";
                        $payRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
                        $sql = "UPDATE cubit.open_stmnt\n\t\t\t\t\t\t\tSET balance = (balance - {$paidamt[$key]}::numeric(13,2))\n\t\t\t\t\t\t\tWHERE invid = '{$inv['invnum']}' AND div = '" . USER_DIV . "'";
                        $payRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
                        # record the payment on the statement
                        $sql = "\n\t\t\t\t\t\tINSERT INTO cubit.stmnt (\n\t\t\t\t\t\t\tcusnum, invid, \n\t\t\t\t\t\t\tamount, date, \n\t\t\t\t\t\t\ttype, div, \n\t\t\t\t\t\t\tallocation_date\n\t\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t\t'{$cus['cusnum']}', '{$inv['invnum']}', \n\t\t\t\t\t\t\t'" . ($paidamt[$key] - $paidamt[$key] * 2) . "', '{$sdate}', \n\t\t\t\t\t\t\t'Payment for Non Stock Invoice No. {$inv['invnum']}', '" . USER_DIV . "', \n\t\t\t\t\t\t\t'{$inv['odate']}'\n\t\t\t\t\t\t)";
                        if (!(isset($bulk_pay) and strlen($bulk_pay) > 0)) {
                            $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
                        } else {
                            $reverse_allocation_dates .= "{$inv['odate']}|";
                            $reverse_allocation_amounts .= sprint($paidamt[$key] - $paidamt[$key] * 2) . "|";
                        }
                        custledger($cus['cusnum'], $bank_acc, $sdate, $inv['invnum'], "Payment for Non Stock Invoice No. {$inv['invnum']}", $paidamt[$key], "c");
                        //recordCT($paidamt[$key], $cus['cusnum'],0,$accdate);
                        $rinvids .= "|{$invids[$key]}";
                        $amounts .= "|{$paidamt[$key]}";
                        $invprds .= "|{$inv['prd']}";
                        $rages .= "|0";
                        $invidsers .= " - {$inv['invnum']}";
                    }
                }
            }
            #record the total for the statement if bulk is selected
            if (isset($bulk_pay) and strlen($bulk_pay) > 0) {
                $arrtotal = sprint(array_sum($paidamt));
                $sql = "\n\t\t\t\t\t\tINSERT INTO cubit.stmnt (\n\t\t\t\t\t\t\tcusnum, invid, \n\t\t\t\t\t\t\tamount, date, \n\t\t\t\t\t\t\ttype, div, \n\t\t\t\t\t\t\tallocation_date, reverse_allocation_dates, reverse_allocation_amounts\n\t\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t\t'{$cus['cusnum']}', '{$inv['invnum']}', \n\t\t\t\t\t\t\t'" . ($arrtotal - $arrtotal * 2) . "', '{$sdate}', \n\t\t\t\t\t\t\t'Payment Received (Ref:{$reference})', '" . USER_DIV . "', \n\t\t\t\t\t\t\t'1500-01-01', '{$reverse_allocation_dates}', '{$reverse_allocation_amounts}'\n\t\t\t\t\t\t)";
                $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
            }
        }
        $cols = grp(m("bankid", $bankid), m("trantype", "deposit"), m("date", $sdate), m("name", "{$cus['cusname']} {$cus['surname']}"), m("descript", "Payment for Invoices {$invidsers} from customer {$cus['cusname']} {$cus['surname']}"), m("cheqnum", $cheqnum), m("amount", $amt), m("banked", "no"), m("accinv", $dept["debtacc"]), m("cusnum", $cus["cusnum"]), m("rinvids", $rinvids), m("amounts", $amounts), m("invprds", $invprds), m("rages", $rages), m("reference", $reference), m("div", USER_DIV));
        $dbobj = new dbUpdate("cashbook", "cubit", $cols);
        $dbobj->run(DB_INSERT);
        $dbobj->free();
        /*
        $sql = "INSERT INTO cashbook(bankid, trantype, date, name, descript,
        			cheqnum, amount, banked, accinv, cusnum, rinvids, amounts,
        			invprds, rages, reference, div)
        		VALUES ('$bankid', 'deposit', '$sdate', '$cus[cusname] $cus[surname]',
        			'',
        			'$cheqnum', '$amt', 'no', '$dept[debtacc]', '$cus[cusnum]',
        			'$rinvids', '$amounts', '$invprds', '$rages', '$reference',
        			'".USER_DIV."')";
        $Rslt = db_exec ($sql) or errDie ("Unable to add bank payment to database.",SELF);
        */
        writetrans($bank_acc, $dept['debtacc'], $accdate, $refnum, $amt, "Payment for Invoices {$invidsers} from customer {$cus['cusname']} {$cus['surname']}");
        db_conn('cubit');
        if ($out > 0) {
            /* START OPEN ITEMS */
            $openstmnt = new dbSelect("open_stmnt", "cubit", grp(m("where", "balance>0 AND cusnum='{$cusid}'"), m("order", "date")));
            $openstmnt->run();
            $open_out = $out;
            $i = 0;
            $ox = "";
            while ($od = $openstmnt->fetch_array()) {
                if ($open_out == 0) {
                    continue;
                }
                $oid = $od['id'];
                if ($open_out >= $od['balance']) {
                    $open_amount[$oid] = $od['balance'];
                    $open_out = sprint($open_out - $od['balance']);
                    $ox .= "\n\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t<td><input type='hidden' size='20' name='open[{$oid}]' value='{$oid}'>{$od['type']}</td>\n\t\t\t\t\t\t\t\t<td>" . CUR . " {$od['balance']}</td>\n\t\t\t\t\t\t\t\t<td>{$od['date']}</td>\n\t\t\t\t\t\t\t\t<td><input type='hidden' name='open_amount[{$oid}]' value='{$open_amount[$oid]}'>" . CUR . " {$open_amount[$oid]}</td>\n\t\t\t\t\t\t\t</tr>";
                    $Sl = "UPDATE cubit.open_stmnt SET balance=balance-'{$open_amount[$oid]}' WHERE id='{$oid}'";
                    $Ri = db_exec($Sl) or errDie("Unable to update statement.");
                } elseif ($open_out < $od['balance']) {
                    $open_amount[$oid] = $open_out;
                    $open_out = 0;
                    $ox .= "\n\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t<td><input type='hidden' size='20' name='open[{$oid}]' value='{$od['id']}'>{$od['type']}</td>\n\t\t\t\t\t\t\t\t<td>" . CUR . " {$od['balance']}</td>\n\t\t\t\t\t\t\t\t<td>{$od['date']}</td>\n\t\t\t\t\t\t\t\t<td><input type='hidden' name='open_amount[{$oid}]' value='{$open_amount[$oid]}'>" . CUR . " {$open_amount[$oid]}</td>\n\t\t\t\t\t\t\t</tr>";
                    $Sl = "UPDATE cubit.open_stmnt SET balance=balance-'{$open_amount[$oid]}' WHERE id='{$oid}'";
                    $Ri = db_exec($Sl) or errDie("Unable to update statement.");
                }
                $i++;
            }
            if (open()) {
                $bout = $out;
                $out = $open_out;
                if ($out > 0) {
                    $sql = "INSERT INTO cubit.open_stmnt(cusnum, invid, amount, balance, date, type, st, div) VALUES('{$cus['cusnum']}', '0', '-{$out}', '-{$out}', '{$sdate}', 'Payment Received', 'n', '" . USER_DIV . "')";
                    $stmntRslt = db_exec($sql) or errDie("Unable to Insert statement record in Cubit.", SELF);
                    //$confirm .="<tr class='bg-even'><td colspan=4><b>A general transaction will credit the client's account with ".CUR." $out </b></td></tr>";
                }
                $out = $bout;
            } else {
                //$confirm .="<tr class='bg-even'><td colspan=4><b>A general transaction will credit the client's account with ".CUR." $out </b></td></tr>";}
            }
        }
        if ($out > 0) {
            recordCT($out, $cus['cusnum'], 0, $accdate);
            $cols = grp(m("cusnum", $cus["cusnum"]), m("invid", 0), m("amount", -$out), m("date", $sdate), m("type", "Payment Received"), m("div", USER_DIV), m("allocation_date", $accdate));
            $dbobj = new dbUpdate("stmnt", "cubit", $cols);
            $dbobj->run(DB_INSERT);
            $dbobj->free();
            custledger($cus['cusnum'], $bank_acc, $sdate, "PAYMENT", "Payment received.", $out, "c");
        }
    }
    /* start moving invoices */
    // move invoices that are fully paid
    $sql = "SELECT * FROM cubit.invoices WHERE balance=0 AND printed = 'y' AND done = 'y' AND div = '" . USER_DIV . "'";
    $invbRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
    while ($x = pg_fetch_array($invbRslt)) {
        if (($prd = $x['prd']) == "0") {
            $prd = PRD_DB;
        }
        // move invoice
        $cols = grp(m("invid", $x["invid"]), m("invnum", $x["invnum"]), m("deptid", $x["deptid"]), m("cusnum", $x["cusnum"]), m("deptname", $x["deptname"]), m("cusacc", $x["cusacc"]), m("cusname", $x["cusname"]), m("surname", $x["surname"]), m("cusaddr", $x["cusaddr"]), m("cusvatno", $x["cusvatno"]), m("cordno", $x["cordno"]), m("ordno", $x["ordno"]), m("chrgvat", $x["chrgvat"]), m("terms", $x["terms"]), m("traddisc", $x["traddisc"]), m("salespn", $x["salespn"]), m("odate", $x["odate"]), m("delchrg", $x["delchrg"]), m("subtot", $x["subtot"]), m("vat", $x["vat"]), m("total", $x["total"]), m("age", $x["age"]), m("comm", $x["comm"]), m("discount", $x["discount"]), m("delivery", $x["delivery"]), m("docref", $x["docref"]), m("prd", $x["prd"]), m("delvat", $x["delvat"]), m("balance", 0), m("printed", "y"), m("done", "y"), m("username", USER_NAME), m("div", USER_DIV));
        $dbobj = new dbUpdate("invoices", $prd, $cols);
        $dbobj->run(DB_INSERT);
        $dbobj->free();
        // record movement
        $cols = grp(m("invtype", "inv"), m("invnum", $x["invnum"]), m("prd", $x["prd"]), m("docref", $x["docref"]), m("div", USER_DIV));
        $dbobj->setTable("movinv", "cubit");
        $dbobj->setOpt($cols);
        $dbobj->run();
        $dbobj->free();
        // move invoice items
        $inv_items = new dbSelect("inv_items", "cubit", grp(m("where", wgrp(m("invid", $x["invid"]), m("div", USER_DIV)))));
        $inv_items->run();
        while ($xi = $inv_items->fetch_array()) {
            $xi['vatcode'] += 0;
            $xi['account'] += 0;
            $xi['del'] += 0;
            $cols = grp(m("invid", $x["invid"]), m("whid", $xi["whid"]), m("stkid", $xi["stkid"]), m("qty", $xi["qty"]), m("unitcost", $xi["unitcost"]), m("amt", $xi["amt"]), m("disc", $xi["disc"]), m("discp", $xi["discp"]), m("vatcode", $xi["vatcode"]), m("account", $xi["account"]), m("description", $xi["description"]), m("del", $xi["del"]), m("noted", $xi["noted"]), m("serno", $xi["serno"]), m("div", USER_DIV));
            $dbobj->setTable("inv_items", $prd);
            $dbobj->setOpt($cols);
            $dbobj->run();
            $dbobj->free();
        }
        /* remove invoice from cubit schema */
        $dbobj = new dbDelete("invoices", "cubit", wgrp(m("invid", $x["invid"]), m("div", USER_DIV)));
        $dbobj->run();
        $dbobj->setTable("inv_items", "cubit");
        $dbobj->run();
    }
    pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
    $cashbook_id = pglib_lastid("cashbook", "cashid");
    if (isset($print_recpt) and $print_recpt == "yes") {
        $showreceipt = "<script>printer ('bank/bank-recpt-inv-print.php?recid={$cashbook_id}');</script>";
    } else {
        $showreceipt = "";
    }
    // status report
    $write = "\n\t\t{$showreceipt}\n\t\t<table " . TMPL_tblDflts . " width='100%'>\n\t\t\t<tr>\n\t\t\t\t<th>Bank Receipt</th>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Bank Receipt added to cash book.</td>\n\t\t\t</tr>\n\t\t</table>";
    $OUTPUT = "\n\t\t<center>\n\t\t<table width='90%'>\n\t\t\t<tr valign='top'>\n\t\t\t\t<td width='50%'>{$write}</td>\n\t\t\t\t<td align='center'>" . mkQuickLinks(ql("bank-pay-add.php", "Add Bank Payment"), ql("bank-recpt-add.php", "Add Bank Receipt"), ql("bank-recpt-inv.php", "Add Customer Payment"), ql("cashbook-view.php", "View Cash Book")) . "\n\t\t\t\t</td>\n\t\t\t</tr>\n\t\t</table>";
    return $OUTPUT;
}
コード例 #22
0
function write($_POST)
{
    # Get vars
    extract($_POST);
    if (isset($back)) {
        unset($_POST["back"]);
        return slctacc($_POST);
    }
    if (isset($cback)) {
        return custconfirm($_POST);
    }
    # validate input
    require_lib("validate");
    $v = new validate();
    foreach ($amount as $key => $value) {
        if ($value > 0) {
            continue;
        }
        $v->isOk($ctaccid[$key], "num", 1, 50, "Invalid Account to be Credited.[{$key}]");
        $v->isOk($dtaccid[$key], "num", 1, 50, "Invalid Account to be Debited.[{$key}]");
        $v->isOk($refnum[$key], "num", 1, 10, "Invalid Reference number.[{$key}]");
        $v->isOk($amount[$key], "float", 1, 20, "Invalid Amount.[{$key}]");
        $v->isOk($descript[$key], "string", 0, 255, "Invalid Details.[{$key}]");
        $datea = explode("-", $date[$key]);
        if (count($datea) == 3) {
            if (!checkdate($datea[1], $datea[0], $datea[2])) {
                $v->isOk("dadasdas", "num", 1, 1, "Invalid date.");
            }
        } else {
            $v->isOk("asdasd", "num", 1, 1, "Invalid date.");
        }
        $date[$key] = $datea[2] . "-" . $datea[1] . "-" . $datea[0];
    }
    # display errors, if any
    if ($v->isError()) {
        $write = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $write .= "<li class='err'>" . $e["msg"] . "</li>";
        }
        $write .= "<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $write;
    }
    foreach ($amount as $key => $value) {
        if ($value <= 0) {
            continue;
        }
        // Accounts details
        $dtaccRs = get("core", "accname, topacc, accnum", "accounts", "accid", $dtaccid[$key]);
        $dtacc[$key] = pg_fetch_array($dtaccRs);
        $ctaccRs = get("core", "accname, topacc, accnum", "accounts", "accid", $ctaccid[$key]);
        $ctacc[$key] = pg_fetch_array($ctaccRs);
        $td = $date[$key];
        if (isDebtors($dtaccid[$key])) {
            # Select customer
            db_connect();
            $sql = "SELECT * FROM customers WHERE cusnum = '{$dcusnum[$key]}' AND div = '" . USER_DIV . "'";
            $custRslt = db_exec($sql) or errDie("Unable to access databse.", SELF);
            if (pg_numrows($custRslt) < 1) {
                return "<li> Invalid Customer ID.</li>";
            } else {
                $cust = pg_fetch_array($custRslt);
            }
            # Get department
            db_conn("exten");
            $sql = "SELECT * FROM departments WHERE deptid = '{$cust['deptid']}' AND div = '" . USER_DIV . "'";
            $deptRslt = db_exec($sql);
            if (pg_numrows($deptRslt) < 1) {
                return "<i class='err'>Department Not Found</i>";
            } else {
                $dept = pg_fetch_array($deptRslt);
            }
            db_connect();
            # Begin updates
            pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
            $sdate = date("Y-m-d");
            # record the payment on the statement
            $sql = "\n\t\t\t\t\tINSERT INTO stmnt (\n\t\t\t\t\t\tcusnum, invid, amount, date, type, st, div, allocation_date\n\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t'{$cust['cusnum']}', '0', '{$amount[$key]}', '{$td}', '{$descript[$key]}', 'n', '" . USER_DIV . "', '{$td}'\n\t\t\t\t\t)";
            $stmntRslt = db_exec($sql) or errDie("Unable to Insert statement record in Cubit.", SELF);
            $sql = "\n\t\t\t\t\tINSERT INTO open_stmnt (\n\t\t\t\t\t\tcusnum, invid, amount, balance, date, \n\t\t\t\t\t\ttype, st, div\n\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t'{$cust['cusnum']}', '0', '{$amount[$key]}', '{$amount[$key]}', '{$td}', \n\t\t\t\t\t\t'{$descript[$key]}', 'n', '" . USER_DIV . "'\n\t\t\t\t\t)";
            $stmntRslt = db_exec($sql) or errDie("Unable to Insert statement record in Cubit.", SELF);
            # update the customer (make balance more)
            $sql = "UPDATE customers SET balance = (balance + '{$amount[$key]}') WHERE cusnum = '{$cust['cusnum']}' AND div = '" . USER_DIV . "'";
            $rslt = db_exec($sql) or errDie("Unable to update customer in Cubit.", SELF);
            # Commit updates
            pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
            # Make ledge record
            custledger($cust['cusnum'], $ctaccid[$key], $td, $refnum[$key], $descript[$key], $amount[$key], "d");
            custDT($amount[$key], $cust['cusnum'], $td);
            $dtaccid[$key] = $dept['debtacc'];
            $descript[$key] = $descript[$key] . " - Customer {$cust['surname']}";
        } elseif (isCreditors($dtaccid[$key])) {
            # Select supplier
            db_connect();
            $sql = "SELECT * FROM suppliers WHERE supid = '{$dsupid[$key]}' AND div = '" . USER_DIV . "'";
            $suppRslt = db_exec($sql) or errDie("Unable to access databse.", SELF);
            if (pg_numrows($suppRslt) < 1) {
                return "<li> Invalid Supplier ID.</li>";
            } else {
                $supp = pg_fetch_array($suppRslt);
            }
            # Get department
            db_conn("exten");
            $sql = "SELECT * FROM departments WHERE deptid = '{$supp['deptid']}' AND div = '" . USER_DIV . "'";
            $deptRslt = db_exec($sql);
            if (pg_numrows($deptRslt) < 1) {
                return "<i class='err'>Department Not Found</i>";
            } else {
                $dept = pg_fetch_array($deptRslt);
            }
            db_connect();
            # Begin updates
            pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
            $edate = date("Y-m-d");
            # record the payment on the statement
            $sql = "\n\t\t\t\t\tINSERT INTO sup_stmnt (\n\t\t\t\t\t\tsupid, edate, ref, cacc, descript, amount, div\n\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t'{$supp['supid']}', '{$td}', '0', '{$ctaccid[$key]}', '{$descript[$key]}', '-{$amount[$key]}', '" . USER_DIV . "'\n\t\t\t\t\t)";
            $stmntRslt = db_exec($sql) or errDie("Unable to Insert statement record in Cubit.", SELF);
            # update the supplier (make balance more)
            $sql = "UPDATE suppliers SET balance = (balance - '{$amount[$key]}') WHERE supid = '{$supp['supid']}' AND div = '" . USER_DIV . "'";
            $rslt = db_exec($sql) or errDie("Unable to update supplier in Cubit.", SELF);
            # Commit updates
            pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
            # Ledger Records
            suppledger($supp['supid'], $ctaccid[$key], $td, $refnum[$key], $descript[$key], $amount[$key], 'd');
            suppDT($amount[$key], $supp['supid'], $td);
            $dtaccid[$key] = $dept['credacc'];
            $descript[$key] = $descript[$key] . " - Supplier {$supp['supname']}";
        } elseif (isStock($dtaccid[$key])) {
            # Select Stock
            db_connect();
            $sql = "SELECT * FROM stock WHERE stkid = '{$dstkids[$key]}' AND div = '" . USER_DIV . "'";
            $stkRslt = db_exec($sql) or errDie("Unable to access databse.", SELF);
            if (pg_numrows($stkRslt) < 1) {
                return "<li> Invalid Stock ID.</li>";
            } else {
                $stk = pg_fetch_array($stkRslt);
            }
            # Get warehouse name
            db_conn("exten");
            $sql = "SELECT * FROM warehouses WHERE whid = '{$stk['whid']}' AND div = '" . USER_DIV . "'";
            $whRslt = db_exec($sql);
            $wh = pg_fetch_array($whRslt);
            # Update Stock
            db_connect();
            $sql = "UPDATE stock SET csamt = (csamt + '{$amount[$key]}') WHERE stkid = '{$stk['stkid']}' AND div = '" . USER_DIV . "'";
            $rslt = db_exec($sql) or errDie("Unable to insert stock to Cubit.", SELF);
            $sdate = date("Y-m-d");
            # stkid, stkcod, stkdes, trantype, edate, qty, csamt, details
            stockrec($stk['stkid'], $stk['stkcod'], $stk['stkdes'], 'dt', $td, 0, $amount[$key], "Stock Debit Transaction");
            db_connect();
            $dtaccid[$key] = $wh['stkacc'];
        }
        if (isDebtors($ctaccid[$key])) {
            # Select customer
            db_connect();
            $sql = "SELECT * FROM customers WHERE cusnum = '{$ccusnum[$key]}' AND div = '" . USER_DIV . "'";
            $custRslt = db_exec($sql) or errDie("Unable to access databse.", SELF);
            if (pg_numrows($custRslt) < 1) {
                return "<li> Invalid Customer ID.</li>";
            } else {
                $cust = pg_fetch_array($custRslt);
            }
            # Get department
            db_conn("exten");
            $sql = "SELECT * FROM departments WHERE deptid = '{$cust['deptid']}' AND div = '" . USER_DIV . "'";
            $deptRslt = db_exec($sql);
            if (pg_numrows($deptRslt) < 1) {
                return "<i class='err'>Department Not Found</i>";
            } else {
                $dept = pg_fetch_array($deptRslt);
            }
            db_connect();
            # Begin updates
            pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
            $sdate = date("Y-m-d");
            # record the payment on the statement
            $sql = "\n\t\t\t\t\tINSERT INTO stmnt (\n\t\t\t\t\t\tcusnum, invid, amount, date, type, st, div, allocation_date\n\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t'{$cust['cusnum']}', '0', '-{$amount[$key]}', '{$td}', '{$descript[$key]}', 'n', '" . USER_DIV . "', '{$td}'\n\t\t\t\t\t)";
            $stmntRslt = db_exec($sql) or errDie("Unable to Insert statement record in Cubit.", SELF);
            $sql = "\n\t\t\t\t\tINSERT INTO open_stmnt (\n\t\t\t\t\t\tcusnum, invid, amount, balance, date, \n\t\t\t\t\t\ttype, st, div\n\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t'{$cust['cusnum']}', '0', '-{$amount[$key]}', '-{$amount[$key]}', '{$td}', \n\t\t\t\t\t\t'{$descript[$key]}', 'n', '" . USER_DIV . "'\n\t\t\t\t\t)";
            $stmntRslt = db_exec($sql) or errDie("Unable to Insert statement record in Cubit.", SELF);
            # update the customer (make balance more)
            $sql = "UPDATE customers SET balance = (balance - '{$amount[$key]}') WHERE cusnum = '{$cust['cusnum']}' AND div = '" . USER_DIV . "'";
            $rslt = db_exec($sql) or errDie("Unable to update customer in Cubit.", SELF);
            # Commit updates
            pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
            # Make ledge record
            custledger($cust['cusnum'], $dtaccid[$key], $sdate, $refnum[$key], $descript[$key], $amount[$key], "c");
            custCT($amount[$key], $cust['cusnum'], $td);
            $ctaccid[$key] = $dept['debtacc'];
            $descript[$key] = $descript[$key] . " - Customer {$cust['surname']}";
        } elseif (isCreditors($ctaccid[$key])) {
            # Select supplier
            db_connect();
            $sql = "SELECT * FROM suppliers WHERE supid = '{$csupid[$key]}' AND div = '" . USER_DIV . "'";
            $suppRslt = db_exec($sql) or errDie("Unable to access databse.", SELF);
            if (pg_numrows($suppRslt) < 1) {
                return "<li> Invalid Supplier ID.</li>";
            } else {
                $supp = pg_fetch_array($suppRslt);
            }
            # Get department
            db_conn("exten");
            $sql = "SELECT * FROM departments WHERE deptid = '{$supp['deptid']}' AND div = '" . USER_DIV . "'";
            $deptRslt = db_exec($sql);
            if (pg_numrows($deptRslt) < 1) {
                return "<i class='err'>Department Not Found</i>";
            } else {
                $dept = pg_fetch_array($deptRslt);
            }
            db_connect();
            # Begin updates
            pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
            $edate = date("Y-m-d");
            # record the payment on the statement
            $sql = "\n\t\t\t\t\tINSERT INTO sup_stmnt (\n\t\t\t\t\t\tsupid, edate, ref, cacc, descript, amount, div\n\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t'{$supp['supid']}', '{$td}', '0', '{$dtaccid[$key]}', '{$descript[$key]}', '{$amount[$key]}', '" . USER_DIV . "'\n\t\t\t\t\t)";
            $stmntRslt = db_exec($sql) or errDie("Unable to Insert statement record in Cubit.", SELF);
            # update the supplier (make balance more)
            $sql = "UPDATE suppliers SET balance = (balance + '{$amount[$key]}') WHERE supid = '{$supp['supid']}' AND div = '" . USER_DIV . "'";
            $rslt = db_exec($sql) or errDie("Unable to update supplier in Cubit.", SELF);
            # Commit updates
            pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
            # Ledger Records
            suppledger($supp['supid'], $dtaccid[$key], $edate, $refnum[$key], $descript[$key], $amount[$key], 'c');
            suppCT($amount[$key], $supp['supid'], $td);
            $ctaccid[$key] = $dept['credacc'];
            $descript[$key] = $descript[$key] . " - Supplier {$supp['supname']}";
        } elseif (isStock($ctaccid[$key])) {
            # Select Stock
            db_connect();
            $sql = "SELECT * FROM stock WHERE stkid = '{$cstkids[$key]}' AND div = '" . USER_DIV . "'";
            $stkRslt = db_exec($sql) or errDie("Unable to access databse.", SELF);
            if (pg_numrows($stkRslt) < 1) {
                return "<li> Invalid Stock ID.</li>";
            } else {
                $stk = pg_fetch_array($stkRslt);
            }
            # Get warehouse name
            db_conn("exten");
            $sql = "SELECT * FROM warehouses WHERE whid = '{$stk['whid']}' AND div = '" . USER_DIV . "'";
            $whRslt = db_exec($sql);
            $wh = pg_fetch_array($whRslt);
            # Update Stock
            db_connect();
            $sql = "UPDATE stock SET csamt = (csamt + '{$amount[$key]}') WHERE stkid = '{$stk['stkid']}' AND div = '" . USER_DIV . "'";
            $rslt = db_exec($sql) or errDie("Unable to insert stock to Cubit.", SELF);
            $sdate = date("Y-m-d");
            # stkid, stkcod, stkdes, trantype, edate, qty, csamt, details
            stockrec($stk['stkid'], $stk['stkcod'], $stk['stkdes'], 'ct', $td, 0, $amount[$key], "Stock Credit Transaction");
            db_connect();
            $ctaccid[$key] = $wh['stkacc'];
        }
        # write transaction
        writetrans($dtaccid[$key], $ctaccid[$key], $date[$key], $refnum[$key], $amount[$key], $descript[$key]);
    }
    // Layout
    $write = "\n\t\t<center>\n\t\t<h3>Journal transactions have been recorded</h3>\n\t\t<table " . TMPL_tblDflts . ">\n\t\t\t<tr>\n\t\t\t\t<th>Date</th>\n\t\t\t\t<th>Ref num</th>\n\t\t\t\t<th>Debit</th>\n\t\t\t\t<th>Credit</th>\n\t\t\t\t<th>Amount</th>\n\t\t\t\t<th>Description</th>\n\t\t\t</tr>";
    foreach ($amount as $key => $value) {
        if ($value <= 0) {
            continue;
        }
        if (isDebtors($dtaccid[$key])) {
            $dcusRs = get("cubit", "*", "customers", "cusnum", $dcusnum[$key]);
            $dcus = pg_fetch_array($dcusRs);
            $dt = "<td valign='center'>{$dcus['accno']} - {$dcus['cusname']} {$dcus['surname']}</td>";
        } elseif (isCreditors($dtaccid[$key])) {
            $dsupRs = get("cubit", "*", "suppliers", "supid", $dsupid[$key]);
            $dsup = pg_fetch_array($dsupRs);
            $dt = "<td valign='center'>{$dsup['supno']} - {$dsup['supname']}</td>";
        } elseif (isStock($dtaccid[$key])) {
            $dstkRs = get("cubit", "*", "stock", "stkid", $dstkids[$key]);
            $dstk = pg_fetch_array($dstkRs);
            $dt = "<td valign='center'>{$dstk['stkcod']} - {$dstk['stkdes']}</td>";
        } else {
            $dt = "<td valign='center'>" . $dtacc[$key]['accname'] . "</td>";
        }
        if (isDebtors($ctaccid[$key])) {
            $ccusRs = get("cubit", "*", "customers", "cusnum", $ccusnum[$key]);
            $ccus = pg_fetch_array($ccusRs);
            $ct = "<td valign='center'>{$ccus['accno']} - {$ccus['cusname']} {$ccus['surname']}</td>";
        } elseif (isCreditors($ctaccid[$key])) {
            $csupRs = get("cubit", "*", "suppliers", "supid", $csupid[$key]);
            $csup = pg_fetch_array($csupRs);
            $ct = "<td valign='center'>{$csup['supno']} - {$csup['supname']}</td>";
        } elseif (isStock($ctaccid[$key])) {
            $cstkRs = get("cubit", "*", "stock", "stkid", $cstkids[$key]);
            $cstk = pg_fetch_array($cstkRs);
            $ct = "<td valign='center'>{$cstk['stkcod']} - {$cstk['stkdes']}</td>";
        } else {
            $ct = "<td valign='center'>" . $ctacc[$key]['accname'] . "</td>";
        }
        $write .= "\n\t\t\t\t<tr bgcolor=" . bgcolorg() . ">\n\t\t\t\t\t<td>{$date[$key]}</td>\n\t\t\t\t\t<td>{$refnum[$key]}</td>\n\t\t\t\t\t{$dt}\n\t\t\t\t\t{$ct}\n\t\t\t\t\t<td>" . CUR . " {$amount[$key]}</td>\n\t\t\t\t\t<td>{$descript[$key]}</td>\n\t\t\t\t</tr>";
    }
    $write .= "\n\t\t</table>\n\t\t<p>\n\t\t<table " . TMPL_tblDflts . " width='25%'>\n\t\t\t<tr>\n\t\t\t\t<th>Quick Links</th>\n\t\t\t</tr>\n\t\t\t<tr class='datacell'>\n\t\t\t\t<td align='center'><a href='../reporting/index-reports.php'>Financials</a></td>\n\t\t\t</tr>\n\t\t\t<tr class='datacell'>\n\t\t\t\t<td align='center'><a href='multi-trans.php'>Journal Transactions</td>\n\t\t\t</tr>\n\t\t\t<script>document.write(getQuicklinkSpecial());</script>\n\t\t</table>";
    return $write;
}
コード例 #23
0
function bank($_POST)
{
    # Get vars
    extract($_POST);
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($cashid, "num", 1, 4, "Invalid Reference number.");
    # display errors, if any
    if ($v->isError()) {
        $confirm = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $confirm .= "<li class='err'>" . $e["msg"] . "</li>";
        }
        $confirm .= "<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $confirm;
    }
    # Get cash book record
    Db_Connect();
    $sql = "SELECT * FROM cashbook WHERE cashid = '{$cashid}' AND div = '" . USER_DIV . "'";
    $accntRslt = db_exec($sql) or errDie("ERROR: Unable to retrieve cashbook entry details from database11.", SELF);
    if (pg_numrows($accntRslt) < 1) {
        $OUTPUT = "<li clss='err'>The entry with reference number, <b>{$cashid}</b> was not found in Cubit.</li>";
        return $OUTPUT;
    }
    $accnt = pg_fetch_array($accntRslt);
    # get hook account number
    core_connect();
    $sql = "SELECT * FROM bankacc WHERE accid = '{$accnt['bankid']}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to retrieve bank account link from Cubit", SELF);
    # check if link exists
    if (pg_numrows($rslt) < 1) {
        return "<li class='err'> ERROR : The bank account that you selected doesn't appear to have an account linked to it.</li>";
    }
    $bank = pg_fetch_array($rslt);
    # Date
    $sdate = date("Y-m-d");
    # If tis customer payment
    if ($accnt['cusnum'] > 0) {
        db_connect();
        # Get invoice Ids and Amounts
        $invids = explode("|", $accnt['rinvids']);
        $amounts = explode("|", $accnt['amounts']);
        $invprds = explode("|", $accnt['invprds']);
        $rages = explode("|", $accnt['rages']);
        # Return the amount that was surppose to be paid to invoices
        foreach ($invids as $key => $invid) {
            db_connect();
            # Skip all nulls and check existance
            if ($invids[$key] > 0 && ext_ex("invoices", "invid", $invids[$key]) && $invprds[$key] != 0) {
                db_connect();
                $sql = "UPDATE invoices SET balance = (balance + '{$amounts[$key]}'::numeric(13,2)) WHERE invid = '{$invids[$key]}' AND div = '" . USER_DIV . "'";
                $payRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
            } elseif ($invids[$key] > 0 && ext_ex("nons_invoices", "invid", $invids[$key]) && $invprds[$key] == 0) {
                db_connect();
                $sql = "UPDATE nons_invoices SET balance = (balance + '{$amounts[$key]}'::numeric(13,2)) WHERE invid = '{$invids[$key]}' AND div = '" . USER_DIV . "'";
                $payRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
                custDTA($amounts[$key], $accnt['cusnum'], $rages[$key]);
            } elseif ($invids[$key] > 0) {
                db_conn($invprds[$key]);
                # check if invoice exitsts on prd
                if (ext_ex("invoices", "invid", $invids[$key])) {
                    # if found, Move the invoice back
                    if (moveback($invids[$key], $invprds[$key], $amounts[$key])) {
                    }
                }
            }
        }
        # Begin updates
        pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
        db_connect();
        # Update the customer (make balance more)
        $sql = "UPDATE customers SET balance = (balance + '{$accnt['amount']}'::numeric(13,2)) WHERE cusnum = '{$accnt['cusnum']}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit1.", SELF);
        # Record the transaction on the statement
        $sql = "\n\t\t\t\tINSERT INTO stmnt \n\t\t\t\t\t(cusnum, invid, amount, date, type, div, allocation_date) \n\t\t\t\tVALUES('{$accnt['cusnum']}', '0', '{$accnt['amount']}','{$sdate}', 'Cheque/Payment for Invoices Cancelled.', '" . USER_DIV . "', '{$accnt['date']}')";
        $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
        # Delete cashbook ID
        $sql = "DELETE FROM cashbook WHERE cashid='{$cashid}' AND div = '" . USER_DIV . "'";
        $Rslt = db_exec($sql) or errDie("Unable to cancel cheque.", SELF);
        if ($accnt['lcashid'] > 0) {
            // Connect to database
            db_Connect();
            $sql = "SELECT * FROM cashbook WHERE cashid = '{$accnt['lcashid']}' AND div = '" . USER_DIV . "'";
            $laccntRslt = db_exec($sql) or errDie("ERROR: Unable to retrieve cashbook entry details from database.2", SELF);
            $laccnt = pg_fetch_array($laccntRslt);
            $sql = "UPDATE bankacct SET fbalance = (fbalance + '{$laccnt['famount']}'::numeric(13,2)), balance = (balance + '{$laccnt['amount']}'::numeric(13,2)) WHERE bankid = '{$laccnt['bankid']}'";
            $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit2.", SELF);
            # Delete cashbook ID
            $sql = "DELETE FROM cashbook WHERE cashid = '{$accnt['lcashid']}' AND div = '" . USER_DIV . "'";
            $Rslt = db_exec($sql) or errDie("Unable to cancel cheque.", SELF);
        }
        # Commit updates
        pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
        # Make ledge record
        custledger($accnt['cusnum'], $bank['accnum'], $sdate, "cancel", "Payment for Invoices Cancelled.", $accnt['amount'], "d");
        $descript = $accnt['descript'] . " Cancelled";
        $refnum = getrefnum();
        $date = date("Y-m-d");
        # debit customer account, credit bank account (customer takes money back)
        writetrans($accnt['accinv'], $bank['accnum'], $date, $refnum, $accnt['amount'], $descript);
    } elseif ($accnt['supid'] > 0) {
        db_connect();
        # Begin updates
        pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
        $ids = explode("|", $accnt['ids']);
        $purids = explode("|", $accnt['purids']);
        $pamounts = explode("|", $accnt['pamounts']);
        $pdates = explode("|", $accnt['pdates']);
        if (count($ids) > 0) {
            foreach ($ids as $key => $vale) {
                if ($ids[$key] > 0) {
                    rerecord($ids[$key], $accnt['supid'], $purids[$key], $pamounts[$key], $pdates[$key]);
                }
            }
        }
        # if the amount was overpaid
        if (array_sum($pamounts) < $accnt['amount']) {
            # get and record amount that was overpaid to balance the equation
            $rem = $accnt['amount'] - array_sum($pamounts);
            rerecord('0', $accnt['supid'], '0', $rem, $accnt['date']);
        }
        # Update the supplier (make balance more)
        $sql = "UPDATE suppliers SET balance = (balance + '{$accnt['amount']}'::numeric(13,2)) WHERE supid = '{$accnt['supid']}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit3.", SELF);
        # Record the payment on the statement
        $sql = "INSERT INTO sup_stmnt(supid, edate, cacc, ref, descript, amount, div) VALUES('{$accnt['supid']}', '{$sdate}', '{$bank['accnum']}', '{$accnt['cheqnum']}', 'Cheque/Payment to Supplier Cancelled.', '{$accnt['amount']}', '" . USER_DIV . "')";
        $stmntRslt = db_exec($sql) or errDie("Unable to Insert statement record in Cubit.", SELF);
        # Delete cashbook ID
        $sql = "DELETE FROM cashbook WHERE cashid='{$cashid}' AND div = '" . USER_DIV . "'";
        $Rslt = db_exec($sql) or errDie("Unable to cancel cheque.", SELF);
        if ($accnt['lcashid'] > 0) {
            // Connect to database
            db_Connect();
            $sql = "SELECT * FROM cashbook WHERE cashid = '{$accnt['lcashid']}' AND div = '" . USER_DIV . "'";
            $laccntRslt = db_exec($sql) or errDie("ERROR: Unable to retrieve cashbook entry details from database3.", SELF);
            $laccnt = pg_fetch_array($laccntRslt);
            $sql = "UPDATE bankacct SET fbalance = (fbalance + '{$laccnt['famount']}'::numeric(13,2)), balance = (balance + '{$laccnt['amount']}'::numeric(13,2)) WHERE bankid = '{$laccnt['bankid']}'";
            $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.4", SELF);
            # Delete cashbook ID
            $sql = "DELETE FROM cashbook WHERE cashid = '{$accnt['lcashid']}' AND div = '" . USER_DIV . "'";
            $Rslt = db_exec($sql) or errDie("Unable to cancel cheque.", SELF);
        }
        # Commit updates
        pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
        suppledger($accnt['supid'], $bank['accnum'], $sdate, $accnt['cheqnum'], "Payment to Supplier Cancelled", $accnt['amount'], "c");
        db_connect();
        $descript = $accnt['descript'] . " Cancelled";
        $refnum = getrefnum();
        $date = date("Y-m-d");
        # debit bank, credit supplier account
        writetrans($bank['accnum'], $accnt['accinv'], $date, $refnum, $accnt['amount'], $descript);
    } elseif ($accnt['suprec'] > 0) {
        db_connect();
        $Sl = "INSERT INTO sup_stmnt(supid, amount, edate, descript,ref,cacc, div) VALUES('{$accnt['suprec']}','-{$accnt['amount']}','{$accnt['date']}', 'Receipt Returned','{$accnt['cheqnum']}','0', '" . USER_DIV . "')";
        $Rs = db_exec($Sl) or errDie("Unable to insert statement record in Cubit.", SELF);
        # Update the supplier (make balance less)
        $sql = "UPDATE suppliers SET balance = (balance - '{$accnt['amount']}'::numeric(13,2)) WHERE supid = '{$accnt['suprec']}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.5", SELF);
        suppDT($accnt['amount'], $accnt['suprec']);
        db_connect();
        # Delete cashbook ID
        $sql = "DELETE FROM cashbook WHERE cashid='{$cashid}' AND div = '" . USER_DIV . "'";
        $Rslt = db_exec($sql) or errDie("Unable to cancel cheque.", SELF);
        if ($accnt['lcashid'] > 0) {
            # Delete cashbook ID
            $sql = "DELETE FROM cashbook WHERE cashid = '{$accnt['lcashid']}' AND div = '" . USER_DIV . "'";
            $Rslt = db_exec($sql) or errDie("Unable to cancel cheque.", SELF);
        }
        $descript = $accnt['descript'] . " Cancelled";
        $refnum = getrefnum();
        $date = date("Y-m-d");
        # debit bank, credit supplier account
        writetrans($bank['accnum'], $accnt['accinv'], $date, $refnum, $accnt['amount'], $descript);
    } elseif (strlen($accnt['accids']) > 0) {
        /* -- Start Hooks -- */
        $vatacc = gethook("accnum", "salesacc", "name", "VAT");
        /* -- End Hooks -- */
        multican($accnt, $bank, $vatacc);
    } else {
        $amount = $accnt['amount'];
        $vat = $accnt['vat'];
        $chrgvat = $accnt['chrgvat'];
        $amount -= $vat;
        /* -- Start Hooks -- */
        $vatacc = gethook("accnum", "salesacc", "name", "VAT");
        /* -- End Hooks -- */
        db_connect();
        # Delete cashbook ID
        $sql = "DELETE FROM cashbook WHERE cashid = '{$cashid}' AND div = '" . USER_DIV . "'";
        $Rslt = db_exec($sql) or errDie("Unable to cancel cheque.", SELF);
        if ($accnt['trantype'] == "deposit") {
            $sql = "UPDATE bankacct SET fbalance = (fbalance - '{$accnt['famount']}'::numeric(13,2)), balance = (balance - '{$accnt['amount']}'::numeric(13,2)) WHERE bankid = '{$accnt['bankid']}'";
            $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.5", SELF);
        } else {
            $sql = "UPDATE bankacct SET fbalance = (fbalance + '{$accnt['famount']}'::numeric(13,2)), balance = (balance + '{$accnt['amount']}'::numeric(13,2)) WHERE bankid = '{$accnt['bankid']}'";
            $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.6", SELF);
        }
        /* ---- the Others ---- */
        if ($accnt['lcashid'] > 0) {
            //Connect to database
            db_Connect();
            $sql = "SELECT * FROM cashbook WHERE cashid = '{$accnt['lcashid']}' AND div = '" . USER_DIV . "'";
            $laccntRslt = db_exec($sql) or errDie("ERROR: Unable to retrieve cashbook entry details from database.4", SELF);
            $laccnt = pg_fetch_array($laccntRslt);
            if ($laccnt['trantype'] == "deposit") {
                $sql = "UPDATE bankacct SET fbalance = (fbalance - '{$laccnt['famount']}'::numeric(13,2)), balance = (balance - '{$laccnt['amount']}'::numeric(13,2)) WHERE bankid = '{$laccnt['bankid']}'";
                $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.7", SELF);
            } else {
                $sql = "UPDATE bankacct SET fbalance = (fbalance + '{$laccnt['famount']}'::numeric(13,2)), balance = (balance + '{$laccnt['amount']}'::numeric(13,2)) WHERE bankid = '{$laccnt['bankid']}'";
                $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.8", SELF);
            }
            # Delete cashbook ID
            $sql = "DELETE FROM cashbook WHERE cashid = '{$accnt['lcashid']}' AND div = '" . USER_DIV . "'";
            $Rslt = db_exec($sql) or errDie("Unable to cancel cheque.", SELF);
            /* ---- End the Others ---- */
        }
        $descript = $accnt['descript'] . " Cancelled";
        $refnum = getrefnum();
        $date = date("Y-m-d");
        if ($accnt['trantype'] == "deposit") {
            # DT(account involved), CT(bank)
            writetrans($accnt['accinv'], $bank['accnum'], $date, $refnum, $amount, $descript);
            if ($vat != 0) {
                # DT(Vat), CT(Bank)
                writetrans($vatacc, $bank['accnum'], $date, $refnum, $vat, $descript);
            }
            $cc_trantype = cc_TranTypeAcc($accnt['accinv'], $bank['accnum']);
        } else {
            # DT(bank), CT(account invoilved)
            writetrans($bank['accnum'], $accnt['accinv'], $date, $refnum, $amount, $descript);
            if ($vat != 0) {
                # DT(Vat), CT(Bank)
                writetrans($bank['accnum'], $vatacc, $date, $refnum, $vat, $descript);
            }
            $cc_trantype = cc_TranTypeAcc($bank['accnum'], $accnt['accinv']);
        }
    }
    if (isset($cc_trantype) && $cc_trantype != false) {
        $cc = "<script> CostCenter('{$cc_trantype}', 'Cancelled Bank Transaction', '{$date}', '{$descript}', '" . ($accnt['amount'] - $accnt['vat']) . "', '../'); </script>";
    } else {
        $cc = "";
    }
    # Status report
    $bank = "\n\t\t\t\t{$cc}\n\t\t\t\t<table " . TMPL_tblDflts . " width='100%'>\n\t\t\t\t\t<tr>\n\t\t\t\t\t\t<th>Cash Book</th>\n\t\t\t\t\t</tr>\n\t\t\t\t\t<tr class='datacell'>\n\t\t\t\t\t\t<td>Cash Book Entry was successfully canceled .</td>\n\t\t\t\t\t</tr>\n\t\t\t\t</table>";
    # Main table (layout with menu)
    $OUTPUT = "\n\t\t\t\t<center>\n\t\t\t\t<table width='90%'>\n\t\t\t\t\t<tr valign='top'>\n\t\t\t\t\t\t<td width='60%'>{$bank}</td>\n\t\t\t\t\t\t<td align='center'>\n\t\t\t\t\t\t\t<table " . TMPL_tblDflts . " width='80%'>\n\t\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t\t<th>Quick Navigation</th>\n\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t<tr class='datacell'>\n\t\t\t\t\t\t\t\t\t<td align='center'><a href='cashbook-view.php'>View Cash Book</td>\n\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t<tr class='datacell'>\n\t\t\t\t\t\t\t\t\t<td align='center'><a href='../reporting/not-banked.php'>View Outstanding Cash Book Entries</td>\n\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t<tr class='datacell'>\n\t\t\t\t\t\t\t\t\t<td align='center'><a href='bank-pay-add.php'>Add bank Payment</td>\n\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t<tr class='datacell'>\n\t\t\t\t\t\t\t\t\t<td align='center'><a href='bank-recpt-add.php'>Add Bank Receipt</td>\n\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t</table>\n\t\t\t\t\t\t</td>\n\t\t\t\t\t</tr>\n\t\t\t\t</table>";
    return $OUTPUT;
}
コード例 #24
0
function write($_POST)
{
    # get vars
    extract($_POST);
    $rounding += 0;
    $pcredit += 0;
    $vatamount = 0;
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($invid, "num", 1, 20, "Invalid invoice number.");
    $v->isOk($prd, "num", 1, 20, "Invalid period number.");
    $v->isOk($comm, "string", 0, 255, "Invalid Comments.");
    $v->isOk($terms, "num", 1, 20, "Invalid terms.");
    $v->isOk($odate, "date", 1, 14, "Invalid Invoice note date.");
    $v->isOk($traddisc, "float", 0, 20, "Invalid Trade Discount.");
    $v->isOk($delchrg, "float", 0, 20, "Invalid Delivery Charge.");
    $v->isOk($SUBTOT, "float", 0, 20, "Invalid Delivery Charge.");
    # Used to generate errors
    $error = "asa@";
    # Check quantities
    if (isset($qtys)) {
        foreach ($qtys as $keys => $qty) {
            $v->isOk($qty, "float", 1, 15, "Invalid Returned Quantity.");
            $v->isOk($disc[$keys], "float", 0, 20, "Invalid Discount.");
            $v->isOk($discp[$keys], "float", 0, 20, "Invalid Discount Percentage.");
        }
    } else {
        $v->isOk($error, "num", 0, 1, "Invalid Returned Quantity.");
    }
    # Check stkids[]
    if (isset($stkids)) {
        foreach ($stkids as $keys => $stkid) {
            $v->isOk($stkid, "num", 1, 10, "Invalid Stock number, please enter all details.{$stkid}");
        }
    } else {
        $v->isOk($error, "num", 0, 1, "Invalid Stock number, please enter all details.");
    }
    # Check amt[]
    if (isset($amt)) {
        foreach ($amt as $keys => $amount) {
            $v->isOk($amount, "float", 1, 20, "Invalid Amount, please enter all details.");
        }
    } else {
        $v->isOk($error, "num", 0, 1, "Invalid Amount, please enter all details.");
    }
    # display errors, if any
    $err = "";
    if ($v->isError()) {
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $err .= "<li class='err'>" . $e["msg"] . "</li>";
        }
        return error($_POST, $err);
    }
    pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
    /* -------------------------------- */
    # Get invoice info
    db_conn($prd);
    $sql = "SELECT * FROM pinvoices WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
    $invRslt = db_exec($sql) or errDie("Unable to get invoice information");
    if (pg_numrows($invRslt) < 1) {
        return "<i class='err'>Not Found</i>";
    }
    $inv = pg_fetch_array($invRslt);
    if ($rounding > 0) {
        db_conn('core');
        $Sl = "SELECT * FROM salesacc WHERE name='rounding'";
        $Ri = db_exec($Sl);
        if (pg_num_rows($Ri) < 1) {
            return "Please set the rounding account, under sales settings.";
        }
        $ad = pg_fetch_array($Ri);
        $rac = $ad['accnum'];
    }
    $notenum = divlastid('note', USER_DIV);
    /* --- Start Products Display --- */
    # Products layout
    $products = "";
    $taxex = 0;
    foreach ($qtys as $keys => $value) {
        db_connect();
        # get selamt from selected stock
        $sql = "SELECT * FROM stock WHERE stkid = '{$stkids[$keys]}' AND div = '" . USER_DIV . "'";
        $stkRslt = db_exec($sql);
        $stk = pg_fetch_array($stkRslt);
        # get selected stock in this invoice
        db_conn($prd);
        $sql = "SELECT * FROM pinv_items  WHERE id = '{$sids[$keys]}' AND invid ='{$invid}' AND div = '" . USER_DIV . "'";
        $stkdRslt = db_exec($sql);
        $stkd = pg_fetch_array($stkdRslt);
        #check serial number
        if (strlen($stkd['ss']) > 0) {
            $me = $stkd['ss'];
        } else {
            $me = $stkd['serno'];
        }
        #determine which table to connect to
        switch (substr($me, strlen($me) - 1, 1)) {
            case "0":
                $tab = "ss0";
                break;
            case "1":
                $tab = "ss1";
                break;
            case "2":
                $tab = "ss2";
                break;
            case "3":
                $tab = "ss3";
                break;
            case "4":
                $tab = "ss4";
                break;
            case "5":
                $tab = "ss5";
                break;
            case "6":
                $tab = "ss6";
                break;
            case "7":
                $tab = "ss7";
                break;
            case "8":
                $tab = "ss8";
                break;
            case "9":
                $tab = "ss9";
                break;
            default:
                $tab = "ss0";
        }
        db_connect();
        $upd = "UPDATE {$tab} SET active = 'yes' WHERE code = '{$stkd['ss']}' OR code = '{$stkd['serno']}'";
        $run_upd = db_exec($upd) or errDie("Unable to update stock serial numbers");
        # get warehouse name
        db_conn("exten");
        $sql = "SELECT whname FROM warehouses WHERE whid = '{$stkd['whid']}' AND div = '" . USER_DIV . "'";
        $whRslt = db_exec($sql);
        $wh = pg_fetch_array($whRslt);
        # Calculate the Discount discount
        if ($disc[$keys] < 1) {
            if ($discp[$keys] > 0) {
                $disc[$keys] = $discp[$keys] / 100 * $stkd['unitcost'];
            }
        } else {
            $discp[$keys] = $disc[$keys] * 100 / $stkd['unitcost'];
        }
        # Calculate amount
        $amt[$keys] = $qtys[$keys] * ($stkd['unitcost'] - $disc[$keys]);
        db_connect();
        $Sl = "SELECT * FROM vatcodes WHERE id='{$stkd['vatcode']}'";
        $Ri = db_exec($Sl);
        if (pg_num_rows($Ri) < 1) {
            return "Please select the vatcode for all your stock.";
        }
        $vd = pg_fetch_array($Ri);
        if ($vd['zero'] == "Yes") {
            $excluding = "y";
        } else {
            $excluding = "";
        }
        $vr = vatcalc($amt[$keys], $inv['chrgvat'], $excluding, $inv['traddisc'], $vd['vat_amount']);
        $vrs = explode("|", $vr);
        $ivat = $vrs[0];
        $iamount = $vrs[1];
        $vatamount += $ivat;
        # Check Tax Excempt
        if ($stk['exvat'] == 'yes' || $vd['zero'] == "Yes") {
            $taxex += $amt[$keys];
        }
        if ($stkd['account'] != 0) {
            # put in product
            $products .= "\n\t\t\t<input type='hidden' name='vatcode[]' value='{$stkd['vatcode']}' />\n\t\t\t<tr>\n\t\t\t\t<td colspan='2'><input type='hidden' name='stkids[]' value='{$stk['stkid']}'>{$stkd['description']}</td>\n\t\t\t\t<td><input type='hidden' size='5' name='qtys[]' value='{$qtys[$keys]}'>{$qtys[$keys]}</td>\n\t\t\t\t<td nowrap>" . CUR . " {$stkd['unitcost']}</td>\n\t\t\t\t<td nowrap><input type='hidden' name='amt[]' value='{$amt[$keys]}'>" . CUR . " {$amt[$keys]}</td>\n\t\t\t</tr>";
        } else {
            # put in product
            $products .= "\n\t\t\t<input type='hidden' name='vatcode[]' value='{$stkd['vatcode']}' />\n\t\t\t<tr>\n\t\t\t\t<td><input type='hidden' name='stkids[]' value='{$stk['stkid']}'>{$stk['stkcod']}</td>\n\t\t\t\t<td>{$stk['stkdes']}</td>\n\t\t\t\t<td><input type='hidden' size='5' name='qtys[]' value='{$qtys[$keys]}'>{$qtys[$keys]}</td>\n\t\t\t\t<td nowrap>" . CUR . " {$stkd['unitcost']}</td>\n\t\t\t\t<td nowrap><input type='hidden' name='amt[]' value='{$amt[$keys]}'>" . CUR . " {$amt[$keys]}</td>\n\t\t\t</tr>";
        }
    }
    # get department
    db_conn("exten");
    $sql = "SELECT * FROM departments WHERE deptid = '{$inv['deptid']}' AND div = '" . USER_DIV . "'";
    $deptRslt = db_exec($sql);
    if (pg_numrows($deptRslt) < 1) {
        $dept['deptname'] = "<i class='err'>Not Found</i>";
    } else {
        $dept = pg_fetch_array($deptRslt);
    }
    /* calculate delivery charge vat */
    db_conn('cubit');
    $Sl = "SELECT * FROM vatcodes WHERE id='{$inv['delvat']}'";
    $Ri = db_exec($Sl);
    $vd = pg_fetch_array($Ri);
    $vr = vatcalc($delchrg, $inv['chrgvat'], $vd['zero'] == "Yes" ? "y" : "", $inv['traddisc'], $vd['vat_amount']);
    $vrs = explode("|", $vr);
    $ivat = $vrs[0];
    $vatamount += $ivat;
    /* --- ----------- Clac ---------------------
    
    	# calculate subtot
    	$SUBTOT = 0.00;
    	if(isset($amt))
    	$SUBTOT = array_sum($amt);
    
    	$SUBTOT -= $taxex;
    
    	# duplicate
    	$SUBTOTAL = $SUBTOT;
    
    	$VATP = TAX_VAT;
    	if($inv['chrgvat'] == "exc"){
    	$SUBTOTAL = $SUBTOTAL;
    	$delexvat= ($delchrg);
    	}elseif($inv['chrgvat'] == "inc"){
    	$SUBTOTAL = sprint(($SUBTOTAL * 100)/(100 + $VATP));
    	$delexvat = sprint(($delchrg * 100)/($VATP + 100));
    	}else{
    	$SUBTOTAL = ($SUBTOTAL);
    	$delexvat = ($delchrg);
    	}
    
    	$SUBTOT = $SUBTOTAL;
    	$EXVATTOT = $SUBTOT;
    	$EXVATTOT += $delexvat;
    
    	# Minus trade discount from taxex
    	if($traddisc > 0){
    	$traddiscmtt = (($traddisc/100) * $taxex);
    	}else{
    	$traddiscmtt = 0;
    	}
    	$taxext = ($taxex - $traddiscmtt);
    
    	if($traddisc > 0) {
    	$traddiscmt = ($EXVATTOT * ($traddisc/100));
    	}else{
    	$traddiscmt = 0;
    	}
    	$EXVATTOT -= $traddiscmt;
    	// $EXVATTOT -= $taxex;
    
    	$traddiscmt = sprint($traddiscmt  + $traddiscmtt);
    	$traddiscm = $traddiscmt;
    
    	if($inv['chrgvat'] != "nov"){
    	$VAT = sprint($EXVATTOT * ($VATP/100));
    	}else{
    	$VAT = 0;
    	}
    
    	$TOTAL = sprint($EXVATTOT + $VAT + $taxext);
    	$SUBTOT += $taxex;
    
    	/* --- ----------- Clac --------------------- */
    /* --- ----------- Clac --------------------- */
    ##----------------------NEW----------------------
    $chrgvat = $inv['chrgvat'];
    $sub = 0.0;
    if (isset($amt)) {
        $sub = sprint(array_sum($amt));
    }
    $VATP = TAX_VAT;
    if ($chrgvat == "exc") {
        $taxex = sprint($taxex - $taxex * $traddisc / 100);
        $subtotal = sprint($sub + $delchrg);
        $traddiscmt = sprint($subtotal * $traddisc / 100);
        $subtotal = sprint($subtotal - $traddiscmt);
        //$VAT=sprint(($subtotal-$taxex)*$VATP/100);
        $VAT = sprint($vatamount);
        $SUBTOT = $sub;
        $TOTAL = sprint($subtotal + $VAT);
        $delexvat = sprint($delchrg);
    } elseif ($chrgvat == "inc") {
        $ot = $taxex;
        $taxex = sprint($taxex - $taxex * $traddisc / 100);
        $subtotal = sprint($sub + $delchrg);
        $traddiscmt = sprint($subtotal * $traddisc / 100);
        $subtotal = sprint($subtotal - $traddiscmt);
        //$VAT=sprint(($subtotal-$taxex)*$VATP/(100+$VATP));
        $VAT = sprint($vatamount);
        $SUBTOT = sprint($sub);
        $TOTAL = sprint($subtotal);
        $delexvat = sprint($delchrg);
        $traddiscmt = sprint($traddiscmt);
    } else {
        $subtotal = sprint($sub + $delchrg);
        $traddiscmt = sprint($subtotal * $traddisc / 100);
        $subtotal = sprint($subtotal - $traddiscmt);
        $VAT = sprint(0);
        $SUBTOT = $sub;
        $TOTAL = $subtotal;
        $delexvat = sprint($delchrg);
    }
    /* --- ----------- Clac --------------------- */
    ##----------------------END----------------------
    # Get invoice info
    db_conn($prd);
    $sql = "SELECT * FROM pinvoices WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
    $invRslt = db_exec($sql) or errDie("Unable to get invoice information");
    if (pg_numrows($invRslt) < 1) {
        return "<li class='err'>Invoice Not Found</li>";
    }
    $inv = pg_fetch_array($invRslt);
    if ($inv['balance'] >= $TOTAL) {
        $invpay = $TOTAL;
        $examt = 0;
    } else {
        $invpay = $inv['balance'];
        $examt = $TOTAL - $invpay;
    }
    /* - Start Hooks - */
    $vatacc = gethook("accnum", "salesacc", "name", "VAT", "VAT");
    /* - End Hooks - */
    # todays date
    $date = date("d-m-Y");
    $sdate = date("Y-m-d");
    $refnum = getrefnum();
    /*refnum*/
    # insert invoice to period DB
    if ($inv['cusnum'] != "0") {
        #then get the actual customer
        db_connect();
        $get_cus = "SELECT * FROM customers WHERE cusnum = '{$inv['cusnum']}' LIMIT 1";
        $run_cus = db_exec($get_cus) or errDie("Unable to get customer information");
        if (pg_numrows($run_cus) < 1) {
            #do nothing
        } else {
            $carr = pg_fetch_array($run_cus);
            $inv['cusname'] = "{$carr['cusname']}";
            $inv['surname'] = "{$carr['surname']}";
        }
    }
    db_conn($prd);
    # Format date
    $odate = explode("-", $odate);
    $rodate = $odate[2] . "-" . $odate[1] . "-" . $odate[0];
    $td = $rodate;
    # Insert invoice credit note to DB
    $sql = "INSERT INTO inv_notes(deptid, notenum, invnum, invid, cusnum, cordno, ordno,\n\t\t\t\tchrgvat, terms, traddisc, salespn, odate, delchrg, subtot, vat, total, comm,\n\t\t\t\tusername, div, surname, cusaddr, cusvatno, telno, deptname, prd)";
    $sql .= " VALUES('{$inv['deptid']}', '{$notenum}', '{$inv['invnum']}', '{$inv['invid']}',\n\t\t\t\t'{$inv['cusnum']}', '{$inv['cordno']}', '{$inv['ordno']}', '{$inv['chrgvat']}',\n\t\t\t\t'{$terms}', '{$traddiscmt}', '{$inv['salespn']}', '{$rodate}', '{$delexvat}',\n\t\t\t\t'{$SUBTOT}', '{$VAT}' , '{$TOTAL}', '{$comm}', '" . USER_NAME . "', '" . USER_DIV . "',\n\t\t\t\t'{$inv['cusname']} {$inv['surname']}', '{$inv['cusaddr']}', '{$inv['cusvatno']}', '{$inv['telno']}',\n\t\t\t\t'{$inv['deptname']}', {$inv['prd']})";
    $rslt = db_exec($sql) or errDie("Unable to insert invoice to Cubit.", SELF);
    $invnum = $inv['invnum'];
    # Get next ordnum
    $noteid = pglib_lastid("inv_notes", "noteid");
    db_conn($prd);
    # Begin updating
    $nbal = $inv['nbal'] + $TOTAL;
    # Update the invoice (make balance less)
    $sql = "UPDATE pinvoices SET nbal = '{$nbal}', rdelchrg = (rdelchrg + '{$delchrg}'), balance = balance - '{$invpay}' WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
    $av = $VAT;
    $at = $TOTAL - $VAT;
    /*
    	$inv['pcash']=$pcash;
    	$inv['pcheque']=$pcheque;
    	$inv['pcc']=$pcc;
    	$inv['pcredit']=$pcredit;*/
    $sd = date("Y-m-d");
    db_conn('cubit');
    $Sl = "SELECT * FROM payrec WHERE inv='{$invnum}'";
    $Ri = db_exec($Sl);
    $data = pg_fetch_array($Ri);
    $user = $data['by'];
    $ro = $rounding;
    $ro += 0;
    $nsp = 0;
    # Commit updating
    $inv['pcash'] = $pcash;
    $inv['pcheque'] = $pcheque;
    $inv['pcc'] = $pcc;
    $inv['pcredit'] = $pcredit;
    $pcreditback = $pcredit;
    # Make ledge record
    //custledger($inv['cusnum'], $dept['incacc'], $td, $notenum, "Credit Note No. $notenum for invoice No. $inv[invnum]", $TOTAL, "c");
    $commision = 0;
    if ($examt > 0) {
        # Make record for age analisys
        //custCTP($examt, $inv['cusnum'],$td);
    }
    $discs = 0;
    $salesp = qrySalesPersonN($inv["salespn"]);
    foreach ($qtys as $keys => $value) {
        db_connect();
        # get selamt from selected stock
        $sql = "SELECT * FROM stock WHERE stkid = '{$stkids[$keys]}' AND div = '" . USER_DIV . "'";
        $stkRslt = db_exec($sql);
        $stk = pg_fetch_array($stkRslt);
        # get selected stock in this invoice
        db_conn($prd);
        $sql = "SELECT * FROM pinv_items  WHERE id = '{$sids[$keys]}' AND invid ='{$invid}' AND div = '" . USER_DIV . "'";
        //print $sql;
        $stkdRslt = db_exec($sql);
        $stkd = pg_fetch_array($stkdRslt);
        $stkd['account'] += 0;
        if ($stkd['account'] == 0) {
            # Keep track of discounts
            $discs += $stkd['disc'] * $stkd['qty'];
            db_connect();
            $Sl = "SELECT * FROM scr WHERE inv='{$inv['invnum']}' AND stkid='{$stkd['stkid']}'";
            $Ri = db_exec($Sl);
            if (pg_num_rows($Ri) > 0) {
                $cd = pg_fetch_array($Ri);
                $stk['csprice'] = $cd['amount'];
            } else {
                $stk["csprice"] = 0;
            }
            # cost amount
            if ($stk['csprice'] == "0.00") {
                $cosamt = round($qtys[$keys] * $stk['lcsprice'], 2);
            } else {
                $cosamt = round($qtys[$keys] * $stk['csprice'], 2);
            }
            db_connect();
            # Update stock(onhand + qty)
            $sql = "UPDATE stock SET csamt = (csamt + '{$cosamt}'), units = (units + '{$qtys[$keys]}') WHERE stkid = '{$stkids[$keys]}' AND div = '" . USER_DIV . "'";
            $rslt = db_exec($sql) or errDie("Unable to update stock to Cubit.", SELF);
            # fix stock cost amount
            $Sl = "UPDATE stock set csprice=csamt/units WHERE stkid = '{$stkids[$keys]}' AND units>0";
            $Ri = db_exec($Sl) or errDie("Unable to update stock cost price in Cubit.", SELF);
            if ($stk['serd'] == 'yes') {
                ext_InSer($stkd['serno'], $stkd['stkid'], "{$inv['cusname']} {$inv['surname']}", $notenum, 'note', $td);
            }
            # negetive values to minus profit
            $nqty = $qtys[$keys] * 1;
            $namt = $amt[$keys] * -1;
            $ncsprice = $cosamt * -1;
            $noted = $stkd['noted'] + $qtys[$keys];
            # stkid, stkcod, stkdes, trantype, edate, qty, csamt, details
            stockrec($stkd['stkid'], $stk['stkcod'], $stk['stkdes'], 'dt', $td, $nqty, $cosamt, "Credit note for Customer : {$inv['surname']} - Credit note No. {$notenum}");
            db_connect();
            # Get amount exluding vat if including and not exempted
            $VATP = TAX_VAT;
            $amtexvat = $amt[$keys];
            ###################VAT CALCS#######################
            $Sl = "SELECT * FROM cubit.vatcodes WHERE id='{$stk['vatcode']}'";
            $Ri = db_exec($Sl);
            if (pg_num_rows($Ri) < 1) {
                return "Please select the vatcode for all your stock.";
            }
            $vd = pg_fetch_array($Ri);
            if ($stk['exvat'] == 'yes' || $vd['zero'] == "Yes") {
                $excluding = "y";
            } else {
                $excluding = "";
            }
            $vr = vatcalc($amt[$keys], $inv['chrgvat'], $excluding, $inv['traddisc'], $vd["vat_amount"]);
            $vrs = explode("|", $vr);
            $ivat = $vrs[0];
            $iamount = $vrs[1];
            vatr($vd['id'], $td, "OUTPUT", $vd['code'], $refnum, "VAT for Credit note: {$notenum} Customer : {$inv['surname']}", -$iamount, -$ivat);
            ####################################################
            $sql = "INSERT INTO stockrec(edate, stkid, stkcod, stkdes, trantype, qty, csprice, csamt, details, div)\n\t\t\t\tVALUES('{$td}', '{$stk['stkid']}', '{$stk['stkcod']}', '{$stk['stkdes']}', 'note', '{$qtys[$keys]}', '{$amtexvat}', '{$cosamt}', 'Credit note for Customer : {$inv['surname']} - Credit note No. {$notenum}', '" . USER_DIV . "')";
            $recRslt = db_exec($sql);
            if ($salesp["com"] > 0) {
                $itemcommission = $salesp['com'];
            } else {
                $itemcommission = $stk["com"];
            }
            $commision = $commision + coms($inv['salespn'], $amt[$keys], $itemcommission);
            # Get selected stock in this invoice
            db_conn($prd);
            $sql = "UPDATE pinv_items SET noted = '{$noted}' WHERE id = '{$sids[$keys]}' AND invid ='{$invid}' AND div = '" . USER_DIV . "'";
            $stkdsRslt = db_exec($sql);
            # get accounts
            db_conn("exten");
            $sql = "SELECT stkacc,cosacc FROM warehouses WHERE whid = '{$stkd['whid']}' AND div = '" . USER_DIV . "'";
            $whRslt = db_exec($sql);
            $wh = pg_fetch_array($whRslt);
            $stockacc = $wh['stkacc'];
            $cosacc = $wh['cosacc'];
            # dt(stock) ct(cos)
            writetrans($stockacc, $cosacc, $td, $refnum, $cosamt, "Cost Of Sales for Credit note No. {$notenum}.");
            db_conn($prd);
            # insert invoice items
            $sql = "INSERT INTO inv_note_items(noteid, whid, stkid, qty, amt, div, vatcode) \n\t\t\t\t\tVALUES('{$noteid}', '{$stkd['whid']}', '{$stkids[$keys]}', '{$qtys[$keys]}', \n\t\t\t\t\t\t'{$amt[$keys]}', '" . USER_DIV . "', '{$vatcode[$keys]}')";
            $rslt = db_exec($sql) or errDie("Unable to insert invoice items to Cubit.", SELF);
            db_connect();
            $date = date("Y-m-d");
            $sql = "INSERT INTO salesrec(edate, invid, invnum, debtacc, vat, total, typ, div)\n\t\t\tVALUES('{$rodate}', '{$noteid}', '{$notenum}', '{$dept['debtacc']}', '{$ivat}', '{$iamount}', 'nstk', '" . USER_DIV . "')";
            $recRslt = db_exec($sql);
        } else {
            db_connect();
            ###################VAT CALCS#######################
            $noted = $stkd['noted'] + $qtys[$keys];
            db_conn($prd);
            $sql = "UPDATE pinv_items SET noted = '{$noted}' WHERE id = '{$sids[$keys]}' AND invid ='{$invid}' AND div = '" . USER_DIV . "'";
            $stkdsRslt = db_exec($sql);
            db_conn($prd);
            # insert invoice items
            $sql = "INSERT INTO inv_note_items(noteid, whid, stkid, qty, amt, div,description, vatcode) \n\t\t\t\t\tVALUES('{$noteid}', '{$stkd['vatcode']}', '{$stkids[$keys]}', '{$qtys[$keys]}', '{$amt[$keys]}', '" . USER_DIV . "', '{$stkd['description']}', '{$vatcode[$keys]}')";
            $rslt = db_exec($sql) or errDie("Unable to insert invoice items to Cubit.", SELF);
            db_connect();
            $Sl = "SELECT * FROM vatcodes WHERE id='{$stkd['vatcode']}'";
            $Ri = db_exec($Sl);
            if (pg_num_rows($Ri) < 1) {
                return "Please select the vatcode for all your stock.";
            }
            $vd = pg_fetch_array($Ri);
            if ($vd['zero'] == "Yes") {
                $excluding = "y";
            } else {
                $excluding = "";
            }
            $vr = vatcalc($amt[$keys], $inv['chrgvat'], $excluding, $inv['traddisc'], $vd["vat_amount"]);
            $vrs = explode("|", $vr);
            $ivat = $vrs[0];
            $iamount = $vrs[1];
            $av -= $ivat;
            $at -= $iamount;
            vatr($vd['id'], $inv['odate'], "OUTPUT", $vd['code'], $refnum, "VAT for Credit note No. {$notenum} for Customer : {$inv['cusname']} {$inv['surname']}", -$iamount, -$ivat);
            ####################################################
            $amtexvat = sprint($stkd['amt']);
            db_connect();
            $sdate = date("Y-m-d");
            $nsp += sprint($iamount - $ivat);
            if ($salesp["com"] > 0) {
                $itemcommission = $salesp['com'];
            } else {
                $itemcommission = 0;
            }
            $commision = $commision + coms($inv['salespn'], $amt[$keys], $itemcommission);
            // 				//writetrans($cosacc, $stockacc,$inv['odate'] , $refnum, $cosamt, "Cost Of Sales for Invoice No.$invnum for Customer : $inv[cusname] $inv[surname]");
            // 				writetrans($dept['debtacc'], $stkd['account'],$inv['odate'], $refnum, ($iamount-$ivat), "Debtors Control for Invoice No.$invnum for Customer : $inv[cusname] $inv[surname]");
            db_connect();
            $date = date("Y-m-d");
            $sql = "INSERT INTO salesrec(edate, invid, invnum, debtacc, vat, total, typ, div)\n\t\t\tVALUES('{$rodate}', '{$noteid}', '{$notenum}', '{$dept['debtacc']}', '{$ivat}', '{$iamount}', 'nnon', '" . USER_DIV . "')";
            $recRslt = db_exec($sql);
            if ($inv['pcash'] > 0) {
                $min = $ro;
                $inv['pcash'] += $ro;
                $ro = 0;
                //$amount=$inv['pcash'];
                if ($inv['pcash'] >= $ivat) {
                    writetrans($vatacc, $dept['pca'], $td, $refnum, $ivat, "VAT Returned for Credit note No. {$notenum}");
                    $inv['pcash'] = sprint($inv['pcash'] - $ivat);
                    $ivat = 0;
                    if ($inv['pcash'] > 0) {
                        if ($inv['pcash'] >= $iamount) {
                            writetrans($stkd['account'], $dept['pca'], $td, $refnum, $iamount, "Sales for Credit note No. {$notenum}");
                            $inv['pcash'] = sprint($inv['pcash'] - $iamount);
                            $iamount = 0;
                        } elseif ($inv['pcash'] < $iamount) {
                            writetrans($stkd['account'], $dept['pca'], $td, $refnum, $inv['pcash'], "Sales for Credit note No. {$notenum}");
                            $iamount = sprint($iamount - $inv['pcash']);
                            $inv['pcash'] = 0;
                        }
                    }
                } else {
                    writetrans($vatacc, $dept['pca'], $td, $refnum, $inv['pcash'], "VAT Returned for Credit note No. {$notenum}");
                    $ivat = sprint($ivat - $inv['pcash']);
                    $inv['pcash'] = 0;
                }
                // 					db_conn('cubit');
                //
                // 					$inv['pcash']-=$min;
                //
                // 					$Sl="INSERT INTO payrec(date,by,inv,amount,method,prd,note) VALUES ('$sd','".USER_NAME."','$invnum','$inv[pcash]','Cash','".PRD_DB."','0')";
                // 					$Ri=db_exec($Sl) or errDie("Unable to insert data.");
            }
            if ($inv['pcheque'] > 0) {
                $min = $ro;
                $inv['pcheque'] += $ro;
                $ro = 0;
                //$amount=$inv['pcash'];
                if ($inv['pcheque'] >= $ivat) {
                    writetrans($vatacc, $dept['pca'], $td, $refnum, $ivat, "VAT Returned for Credit note No. {$notenum}");
                    $inv['pcheque'] = sprint($inv['pcheque'] - $ivat);
                    $ivat = 0;
                    if ($inv['pcheque'] > 0) {
                        if ($inv['pcheque'] >= $iamount) {
                            writetrans($stkd['account'], $dept['pca'], $td, $refnum, $iamount, "Sales for Credit note No. {$notenum}");
                            $inv['pcheque'] = sprint($inv['pcheque'] - $iamount);
                            $iamount = 0;
                        } elseif ($inv['pcheque'] < $iamount) {
                            writetrans($stkd['account'], $dept['pca'], $td, $refnum, $inv['pcheque'], "Sales for Credit note No. {$notenum}");
                            $iamount = sprint($iamount - $inv['pcheque']);
                            $inv['pcheque'] = 0;
                        }
                    }
                } else {
                    writetrans($vatacc, $dept['pca'], $td, $refnum, $inv['pcheque'], "VAT Returned for Credit note No. {$notenum}");
                    $ivat = sprint($ivat - $inv['pcheque']);
                    $inv['pcheque'] = 0;
                }
                db_conn('cubit');
                $inv['pcash'] -= $min;
                $Sl = "INSERT INTO payrec(date,by,inv,amount,method,prd,note) VALUES ('{$sd}','" . USER_NAME . "','{$invnum}','-{$inv['pcash']}','Cash','" . PRD_DB . "','{$noteid}')";
                $Ri = db_exec($Sl) or errDie("Unable to insert data.");
            }
            if ($inv['pcc'] > 0) {
                db_conn('core');
                $Sl = "SELECT * FROM salacc WHERE name='cc'";
                $Ri = db_exec($Sl);
                if (pg_num_rows($Ri) < 1) {
                    return "Please set a link for the POS credit card control account";
                }
                $cd = pg_fetch_array($Ri);
                $cc = $cd['accnum'];
                $min = $ro;
                $inv['pcc'] += $ro;
                $ro = 0;
                //$amount=$inv['pcash'];
                if ($inv['pcc'] >= $ivat) {
                    writetrans($vatacc, $cc, $td, $refnum, $ivat, "VAT Returned for Credit note No. {$notenum}");
                    $inv['pcc'] = sprint($inv['pcc'] - $ivat);
                    $ivat = 0;
                    if ($inv['pcc'] > 0) {
                        if ($inv['pcc'] >= $iamount) {
                            writetrans($stkd['account'], $cc, $td, $refnum, $iamount, "Sales for Credit note No. {$notenum}");
                            $inv['pcc'] = sprint($inv['pcc'] - $iamount);
                            $iamount = 0;
                        } elseif ($inv['pcc'] < $iamount) {
                            writetrans($stkd['account'], $cc, $td, $refnum, $inv['pcc'], "Sales for Credit note No. {$notenum}");
                            $iamount = sprint($iamount - $inv['pcc']);
                            $inv['pcc'] = 0;
                        }
                    }
                } else {
                    writetrans($vatacc, $cc, $td, $refnum, $inv['pcc'], "VAT Returned for Credit note No. {$notenum}");
                    $ivat = sprint($ivat - $inv['pcc']);
                    $inv['pcc'] = 0;
                }
                db_conn('cubit');
                $inv['pcash'] -= $min;
                $Sl = "INSERT INTO payrec(date,by,inv,amount,method,prd,note) VALUES ('{$sd}','" . USER_NAME . "','{$invnum}','-{$inv['pcash']}','Cash','" . PRD_DB . "','{$noteid}')";
                $Ri = db_exec($Sl) or errDie("Unable to insert data.");
            }
            if ($inv['pcredit'] > 0) {
                db_conn('core');
                $min = $ro;
                $inv['pcredit'] += $ro;
                $ro = 0;
                //$amount=$inv['pcash'];
                if ($inv['pcredit'] >= $ivat) {
                    writetrans($vatacc, $dept['debtacc'], $td, $refnum, $ivat, "VAT Returned for Credit note No. {$notenum}");
                    $inv['pcredit'] = sprint($inv['pcredit'] - $ivat);
                    $ivat = 0;
                    if ($inv['pcredit'] > 0) {
                        if ($inv['pcredit'] >= $iamount) {
                            writetrans($stkd['account'], $dept['debtacc'], $td, $refnum, $iamount, "Sales for Credit note No. {$notenum}");
                            $inv['pcredit'] = sprint($inv['pcredit'] - $iamount);
                            $iamount = 0;
                        } elseif ($inv['pcredit'] < $iamount) {
                            writetrans($stkd['account'], $dept['debtacc'], $td, $refnum, $inv['pcredit'], "Sales for Credit note No. {$notenum}");
                            $iamount = sprint($iamount - $inv['pcredit']);
                            $inv['pcredit'] = 0;
                        }
                    }
                } else {
                    writetrans($vatacc, $dept['debtacc'], $td, $refnum, $inv['pcredit'], "VAT Returned for Credit note No. {$notenum}");
                    $ivat = sprint($ivat - $inv['pcredit']);
                    $inv['pcredit'] = 0;
                }
                db_conn('cubit');
                $inv['pcash'] -= $min;
                $Sl = "INSERT INTO payrec(date,by,inv,amount,method,prd,note) VALUES ('{$sd}','" . USER_NAME . "','{$invnum}','-{$inv['pcash']}','Cash','" . PRD_DB . "','{$noteid}')";
                $Ri = db_exec($Sl) or errDie("Unable to insert data.");
            }
        }
    }
    db_connect();
    # save invoice discount
    $sql = "INSERT INTO inv_discs(cusnum, invid, traddisc, itemdisc, inv_date, delchrg, div) VALUES('{$inv['cusnum']}', '{$invid}', '0', '-{$discs}', '{$inv['odate']}', '0', '" . USER_DIV . "')";
    $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
    /* - Start Transactoins - */
    ###################VAT CALCS#######################
    db_conn('cubit');
    $Sl = "SELECT * FROM vatcodes WHERE del='Yes'";
    $Ri = db_exec($Sl);
    if (pg_num_rows($Ri) < 1) {
        $Sl = "SELECT * FROM vatcodes";
        $Ri = db_exec($Sl);
    }
    $vd = pg_fetch_array($Ri);
    $excluding = "";
    $vr = vatcalc($delexvat, $inv['chrgvat'], $excluding, $inv['traddisc'], $vd["vat_amount"]);
    $vrs = explode("|", $vr);
    $ivat = $vrs[0];
    $iamount = $vrs[1];
    vatr($vd['id'], $td, "OUTPUT", $vd['code'], $refnum, "VAT for Credit note No. {$notenum}, Customer : {$inv['cusname']} {$inv['surname']}", -$iamount, -$ivat);
    ####################################################
    /*
    # dt(income) ct(debtors)
    writetrans($dept['pia'], $dept['pca'], $td, $refnum, ($TOTAL-$VAT), "Debtors Control for Credit note No. $notenum for Customer : $inv[cusname] $inv[surname]");
    
    # dt(vat) ct(debtors)
    writetrans($vatacc, $dept['pca'], $td, $refnum, $VAT, "VAT Return for Credit note No. $notenum for Customer : $inv[cusname] $inv[surname]");
    */
    //	db_connect();
    //	$date = date("Y-m-d");
    //	$sql = "INSERT INTO salesrec(edate, invid, invnum, debtacc, vat, total, typ, div)
    //	VALUES('$rodate', '$noteid', '$notenum', '$dept[debtacc]', '$VAT', '$TOTAL', 'nstk', '".USER_DIV."')";
    //	$recRslt = db_exec($sql);
    $Sl = "INSERT INTO sj(cid,name,des,date,exl,vat,inc,div) VALUES\n\t('{$inv['cusnum']}','{$inv['surname']}','Credit Note:{$notenum}, POS Invoice {$inv['invnum']}','{$rodate}','" . -sprint($TOTAL - $VAT) . "','-{$VAT}','" . -sprint($TOTAL) . "','" . USER_DIV . "')";
    $Ri = db_exec($Sl);
    // 	$av=$VAT;
    // 	$at=$TOTAL-$VAT;
    //
    // 	$inv['pcash']=$pcash;
    // 	$inv['pcheque']=$pcheque;
    // 	$inv['pcc']=$pcc;
    // 	$inv['pcredit']=$pcredit;
    //
    // 	$sd=date("Y-m-d");
    //
    // 	db_conn('cubit');
    // 	$Sl="SELECT * FROM payrec WHERE inv='$invnum'";
    // 	$Ri=db_exec($Sl);
    //
    // 	$data=pg_fetch_array($Ri);
    //
    // 	$user=$data['by'];
    //
    // 	$ro=$rounding;
    // 	$ro+=0;
    if ($inv['pcash'] > 0) {
        $min = $ro;
        $inv['pcash'] += $ro;
        $ro = 0;
        $amount = $inv['pcash'];
        if ($amount >= $av) {
            writetrans($vatacc, $dept['pca'], $td, $refnum, $av, "VAT Returned for POS Credit note: {$notenum}.");
            $amount = sprint($amount - $av);
            $av = 0;
            if ($amount > 0) {
                writetrans($dept['pia'], $dept['pca'], $td, $refnum, $amount, "Sales for POS Credit note: {$notenum}.");
                $at = $at - $amount;
            }
        } else {
            writetrans($vatacc, $dept['pca'], $td, $refnum, $amount, "VAT Returned for POS Credit note: {$notenum}.");
            $av = $av - $amount;
            $amount = 0;
        }
        db_conn('cubit');
        $inv['pcash'] -= $min;
        $Sl = "INSERT INTO payrec(date,by,inv,amount,method,prd,note) VALUES ('{$td}','{$user}','{$invnum}','-{$inv['pcash']}','Cash','" . PRD_DB . "','{$noteid}')";
        $Ri = db_exec($Sl) or errDie("Unable to insert data.");
    }
    if ($inv['pcheque'] > 0) {
        $min = $ro;
        $inv['pcheque'] += $ro;
        $ro = 0;
        $amount = $inv['pcheque'];
        if ($amount >= $av) {
            writetrans($vatacc, $dept['pca'], $td, $refnum, $av, "VAT Returned for POS Credit note: {$notenum}.");
            $amount = sprint($amount - $av);
            $av = 0;
            if ($amount > 0) {
                writetrans($dept['pia'], $dept['pca'], $td, $refnum, $amount, "Sales for POS Credit note: {$notenum}.");
                $at = $at - $amount;
            }
        } else {
            writetrans($vatacc, $dept['pca'], $td, $refnum, $amount, "VAT Returned for POS Credit note: {$notenum}.");
            $av = $av - $amount;
            $amount = 0;
        }
        db_conn('cubit');
        $inv['pcheque'] -= $min;
        $Sl = "INSERT INTO payrec(date,by,inv,amount,method,prd,note) VALUES ('{$td}','{$user}','{$invnum}','-{$inv['pcheque']}','Cheque','" . PRD_DB . "','{$noteid}')";
        $Ri = db_exec($Sl) or errDie("Unable to insert data.");
    }
    if ($inv['pcc'] > 0) {
        db_conn('core');
        $Sl = "SELECT * FROM salacc WHERE name='cc'";
        $Ri = db_exec($Sl);
        if (pg_num_rows($Ri) < 1) {
            return "Please set a link for the POS credit card control account";
        }
        $cd = pg_fetch_array($Ri);
        $cc = $cd['accnum'];
        $min = $ro;
        $inv['pcc'] += $ro;
        $ro = 0;
        $amount = $inv['pcc'];
        if ($amount >= $av) {
            writetrans($vatacc, $cc, $td, $refnum, $av, "VAT Returned for POS Credit note: {$notenum}.");
            $amount = sprint($amount - $av);
            $av = 0;
            if ($amount > 0) {
                writetrans($dept['pia'], $cc, $td, $refnum, $amount, "Sales for POS Credit note: {$notenum}.");
                $at = $at - $amount;
            }
        } else {
            writetrans($vatacc, $cc, $td, $refnum, $amount, "VAT Returned for POS Credit note: {$notenum}.");
            $av = $av - $amount;
            $amount = 0;
        }
        db_conn('cubit');
        $inv['pcc'] -= $min;
        $Sl = "INSERT INTO payrec(date,by,inv,amount,method,prd,note) VALUES ('{$td}','" . USER_NAME . "','{$invnum}','-{$inv['pcc']}','Credit Card','" . PRD_DB . "','{$noteid}')";
        $Ri = db_exec($Sl) or errDie("Unable to insert data.");
    }
    if ($inv['pcredit'] > 0) {
        db_conn('core');
        $cc = $dept['debtacc'];
        $min = $ro;
        $inv['pcredit'] += $ro;
        $ro = 0;
        $amount = $inv['pcredit'];
        if ($amount >= $av) {
            writetrans($vatacc, $cc, $td, $refnum, $av, "VAT Returned for POS Credit note: {$notenum}.");
            $amount = sprint($amount - $av);
            $av = 0;
            if ($amount > 0) {
                writetrans($dept['pia'], $cc, $td, $refnum, $amount, "Sales for POS Credit note: {$notenum}.");
                $at = $at - $amount;
            }
        } else {
            writetrans($vatacc, $cc, $td, $refnum, $amount, "VAT Returned for POS Credit note: {$notenum}.");
            $av = $av - $amount;
            $amount = 0;
        }
        db_conn('cubit');
        $inv['pcc'] -= $min;
        $Sl = "INSERT INTO payrec(date,by,inv,amount,method,prd,note) VALUES ('{$td}','" . USER_NAME . "','{$invnum}','-{$inv['pcredit']}','Credit','" . PRD_DB . "','{$noteid}')";
        $Ri = db_exec($Sl) or errDie("Unable to insert data.");
    }
    if ($inv['rounding'] > 0) {
        if ($inv['pcash'] > 0) {
            writetrans($dept['pca'], $rac, $td, $refnum, $inv['rounding'], "Rounding  on Credit note: {$notenum}.");
        } elseif ($inv['pcheque'] > 0) {
            writetrans($dept['pca'], $rac, $td, $refnum, $inv['rounding'], "Rounding on Credit note: {$notenum}.");
        } elseif ($inv['pcc'] > 0) {
            writetrans($cc, $rac, $td, $refnum, $inv['rounding'], "Rounding on Credit note: {$notenum}.");
        } elseif ($inv['pcredit'] > 0) {
            writetrans($dept['debtacc'], $rac, $td, $refnum, $inv['rounding'], "Rounding on Credit note: {$notenum}.");
        }
    }
    com_invoice($inv['salespn'], -($TOTAL - $VAT), -$commision, $invnum, $td);
    db_conn('cubit');
    $Sl = "INSERT INTO pr(userid,username,amount,pdate,inv,cust,t) VALUES ('" . USER_ID . "','" . USER_NAME . "','-{$TOTAL}','{$td}','{$invnum}','{$inv['cusname']}','{$inv['terms']}')";
    $Ry = db_exec($Sl) or errDie("Unable to insert pos record.");
    if ($rounding > 0) {
        $Sl = "INSERT INTO pcnc (note,amount) VALUES ('{$notenum}','{$rounding}')";
        $Ri = db_exec($Sl);
    }
    $inv['pcredit'] = $pcreditback;
    if ($inv['cusnum'] > 0 && $inv['pcredit'] > 0) {
        $nt = $inv['pcredit'];
        # Record the payment on the statement
        $sql = "\n\t\t\tINSERT INTO stmnt \n\t\t\t\t(cusnum, invid, docref, amount, date, type, div, allocation_date) \n\t\t\tVALUES \n\t\t\t\t('{$inv['cusnum']}', '{$invnum}', '0', '-{$nt}', '{$inv['odate']}', 'Credit Note {$notenum}', '" . USER_DIV . "', '{$inv['odate']}')";
        $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
        # Update the customer (make balance more)
        $sql = "UPDATE customers SET balance = (balance - '{$nt}') WHERE cusnum = '{$inv['cusnum']}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
        # Update the invoice (make balance less)
        $sql = "UPDATE open_stmnt SET balance = balance-'{$pcreditback}' WHERE invid = '{$inv['invnum']}'";
        $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
        custledger($inv['cusnum'], $dept['incacc'], $inv['odate'], $invnum, "Credit note {$notenum}", $nt, "c");
        //print $nt;exit;
        recordCT($nt, $inv['cusnum'], $inv['odate']);
    }
    pglib_transaction("COMMIT");
    //die("<br /><br />NOTE: TRANSACTION ROLLBACK!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
    /* - End Transactoins - */
    /* -- Final Layout -- */
    $details = "\n\t\t\t\t\t<center>\n\t\t\t\t\t<h2>Credit Note</h2>\n\t\t\t\t\t<table cellpadding='0' cellspacing='4' border=0 width='750'>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<td valign='top' width='30%'>\n\t\t\t\t\t\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t\t\t<td>{$inv['surname']}</td>\n\t\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t</table>\n\t\t\t\t\t\t\t</td>\n\t\t\t\t\t\t\t<td valign='top' width='25%'>\n\t\t\t\t\t\t\t\t" . COMP_NAME . "<br>\n\t\t\t\t\t\t\t\t" . COMP_ADDRESS . "<br>\n\t\t\t\t\t\t\t\t" . COMP_TEL . "<br>\n\t\t\t\t\t\t\t\t" . COMP_FAX . "<br>\n\t\t\t\t\t\t\t</td>\n\t\t\t\t\t\t\t<td width='20%'>\n\t\t\t\t\t\t\t\t<img src='compinfo/getimg.php' width='230' height='47'>\n\t\t\t\t\t\t\t</td>\n\t\t\t\t\t\t\t<td valign='bottom' align='right' width='25%'>\n\t\t\t\t\t\t\t\t<table cellpadding='2' cellspacing='0' border='1' bordercolor='#000000'>\n\t\t\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t\t\t<td><b>Credit Note No.</b></td>\n\t\t\t\t\t\t\t\t\t\t<td valign='center'>{$notenum}</td>\n\t\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t\t\t<td><b>Invoice No.</b></td>\n\t\t\t\t\t\t\t\t\t\t<td valign='center'>{$inv['invnum']}</td>\n\t\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t\t\t<td><b>Order No.</b></td>\n\t\t\t\t\t\t\t\t\t\t<td valign='center'>{$inv['ordno']}</td>\n\t\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t\t\t<td><b>Terms</b></td>\n\t\t\t\t\t\t\t\t\t\t<td valign='center'>{$terms} Days</td>\n\t\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t\t\t<td><b>Credit note Date</b></td>\n\t\t\t\t\t\t\t\t\t\t<td valign='center'>{$rodate}</td>\n\t\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t</table>\n\t\t\t\t\t\t\t</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr><td><br></td></tr>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<td colspan='4'>\n\t\t\t\t\t\t\t\t<table cellpadding='5' cellspacing='0' border='1' width='100%' bordercolor='#000000'>\n\t\t\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t\t\t<th>ITEM NUMBER</th>\n\t\t\t\t\t\t\t\t\t\t<th width='45%'>DESCRIPTION</th>\n\t\t\t\t\t\t\t\t\t\t<th>QTY RETURNED</th>\n\t\t\t\t\t\t\t\t\t\t<th>UNIT PRICE</th>\n\t\t\t\t\t\t\t\t\t\t<th>AMOUNT</th>\n\t\t\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t\t{$products}\n\t\t\t\t\t\t\t\t</table>\n\t\t\t\t\t\t\t</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<td>\n\t\t\t\t\t\t\t\t<table border='1' cellspacing='0' bordercolor='#000000'>\n\t\t\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t\t\t<td>" . nl2br($comm) . "</td>\n\t\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t</table>\n\t\t\t\t\t\t\t</td>\n\t\t\t\t\t\t\t<td align='right' colspan='3'>\n\t\t\t\t\t\t\t\t<table cellpadding='5' cellspacing='0' border='1' width='50%' bordercolor='#000000'>\n\t\t\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t\t\t<td><b>SUBTOTAL</b></td>\n\t\t\t\t\t\t\t\t\t\t<td align='right'>" . CUR . " {$SUBTOT}</td>\n\t\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t\t\t<td><b>Trade Discount</b></td>\n\t\t\t\t\t\t\t\t\t\t<td align='right'>" . CUR . " {$traddiscmt}</td>\n\t\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t\t\t<td><b>Delivery Charge</b></td>\n\t\t\t\t\t\t\t\t\t\t<td align='right'>" . CUR . " {$delexvat}</td>\n\t\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t\t\t<td><b>VAT @ {$VATP}%</b></td>\n\t\t\t\t\t\t\t\t\t\t<td align='right'>" . CUR . " {$VAT}</td>\n\t\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t\t\t<th><b>GRAND TOTAL<b></th>\n\t\t\t\t\t\t\t\t\t\t<td align='right'>" . CUR . " {$TOTAL}</td>\n\t\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t</table>\n\t\t\t\t\t\t\t</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr><td><br></td></tr>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<td>\n\t\t\t\t\t\t\t\t<table " . TMPL_tblDflts . " border='1'>\n\t\t\t\t\t\t        \t<tr>\n\t\t\t\t\t\t        \t\t<th>VAT No.</th>\n\t\t\t\t\t\t        \t\t<td align='center'>" . COMP_VATNO . "</td>\n\t\t\t\t\t\t        \t</tr>\n\t\t\t\t\t\t        </table>\n\t\t\t\t\t\t\t</td>\n\t\t\t\t\t\t\t<td><br></td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t</table>\n\t\t\t\t\t</center>";
    $OUTPUT = "<script>printer2('pos-note-slip.php?noteid={$noteid}&prd={$prd}&cccc=true');move('main.php');</script>";
    require "template.php";
}
コード例 #25
0
function write($_POST)
{
    # Set max execution time to 12 hours
    ini_set("max_execution_time", 43200);
    # Get vars
    foreach ($_POST as $key => $value) {
        ${$key} = $value;
    }
    # validate input
    require_lib("validate");
    $v = new validate();
    foreach ($invids as $key => $invid) {
        $v->isOk($invid, "num", 1, 20, "Invalid recuring invoice number.");
    }
    $VATP = TAX_VAT;
    # display errors, if any
    $err = "";
    if ($v->isError()) {
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $err .= "<li class=err>" . $e["msg"];
        }
        return $err;
    }
    pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
    $i = 0;
    foreach ($invids as $key => $invid) {
        db_connect();
        $sql = "SELECT * FROM nons_invoices WHERE invid = '{$invid}' AND div = '" . USER_DIV . "' and done='n'";
        $invRslt = db_exec($sql) or errDie("Unable to get invoice information");
        if (pg_numrows($invRslt) < 1) {
            return "<i class=err>Not Found</i>";
        }
        $inv = pg_fetch_array($invRslt);
        $ctyp = $inv['ctyp'];
        //$td=$inv['sdate'];
        $td = $inv['odate'];
        //$cus['surname']=$inv['cusname'];
        if ($ctyp == 's') {
            $cusnum = $inv['tval'];
            $sql = "SELECT * FROM customers WHERE cusnum = '{$cusnum}' AND div = '" . USER_DIV . "'";
            $custRslt = db_exec($sql) or errDie("Unable to view customer");
            $cus = pg_fetch_array($custRslt);
            $na = $cus['surname'];
        } elseif ($ctyp == 'c') {
            $deptid = $inv['tval'];
            db_conn("exten");
            $sql = "SELECT * FROM departments WHERE deptid = '{$deptid}'";
            $deptRslt = db_exec($sql) or errDie("Unable to view customers");
            $dept = pg_fetch_array($deptRslt);
            $na = $inv['cusname'];
        }
        db_connect();
        $sql = "SELECT * FROM nons_inv_items  WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
        $stkdRslt = db_exec($sql) or errDie("Unable to get data.");
        unset($totstkamt);
        $refnum = getrefnum();
        /*refnum*/
        /* - Start Hooks - */
        $vatacc = gethook("accnum", "salesacc", "name", "VAT", "NO VAT");
        $varacc = gethook("accnum", "salesacc", "name", "sales_variance");
        /* - End Hooks - */
        db_conn("cubit");
        $real_invid = divlastid('inv', USER_DIV);
        db_conn("cubit");
        # Put in product
        $totstkamt = array();
        while ($stk = pg_fetch_array($stkdRslt)) {
            $Sl = "SELECT * FROM vatcodes WHERE id='{$stk['vatex']}'";
            $Ri = db_exec($Sl) or errDie("Unable to get data.");
            $vd = pg_fetch_array($Ri);
            if ($vd['zero'] == "Yes") {
                $stk['vatex'] = "y";
            }
            $t = $inv['chrgvat'];
            $stkacc = $stk['accid'];
            if (isset($totstkamt[$stkacc])) {
                if ($stk['vatex'] == "y") {
                    $totstkamt[$stkacc] += vats($stk['amt'], 'novat', $vd['vat_amount']);
                    $va = 0;
                    $inv['chrgvat'] = "";
                } else {
                    $totstkamt[$stkacc] += vats($stk['amt'], $inv['chrgvat'], $vd['vat_amount']);
                    $va = sprint($stk['amt'] - vats($stk['amt'], $inv['chrgvat'], $vd['vat_amount']));
                    if ($inv['chrgvat'] == "no") {
                        $va = sprint($stk['amt'] * $vd['vat_amount'] / 100);
                    }
                }
            } else {
                if ($stk['vatex'] == "y") {
                    $totstkamt[$stkacc] = vats($stk['amt'], 'novat', $vd['vat_amount']);
                    $inv['chrgvat'] = "";
                    $va = 0;
                } else {
                    $totstkamt[$stkacc] = vats($stk['amt'], $inv['chrgvat'], $vd['vat_amount']);
                    $va = sprint($stk['amt'] - vats($stk['amt'], $inv['chrgvat'], $vd['vat_amount']));
                    if ($inv['chrgvat'] == "no") {
                        $va = sprint($stk['amt'] * $vd['vat_amount'] / 100);
                    }
                }
            }
            vatr($vd['id'], $td, "OUTPUT", $vd['code'], $refnum, "Non-Stock Sales, invoice No.{$real_invid}", vats($stk['amt'], $inv['chrgvat'], $vd['vat_amount']) + $va, $va);
            //print vats($stk['amt'],$inv['chrgvat'], $vd['vat_amount']);
            $inv['chrgvat'] = $t;
            //$sql = "UPDATE nons_inv_items SET accid = '$stk[account]' WHERE id = '$stk[id]'";
            //$sRslt = db_exec($sql);
        }
        /* --- Start Some calculations --- */
        # Subtotal
        $SUBTOT = sprint($inv['subtot']);
        $VAT = sprint($inv['vat']);
        $TOTAL = sprint($inv['total']);
        /* --- End Some calculations --- */
        /* - Start Hooks - */
        //$vatacc = gethook("accnum", "salesacc", "name", "VAT");
        /* - End Hooks - */
        # todays date
        $date = date("d-m-Y");
        $sdate = date("Y-m-d");
        db_conn("cubit");
        if (isset($bankid)) {
            $bankid += 0;
            db_conn("cubit");
            $sql = "SELECT * FROM bankacct WHERE bankid = '{$inv['accid']}'";
            $deptRslt = db_exec($sql) or errDie("Unable to view customers");
            if (pg_numrows($deptRslt) < 1) {
                $error = "<li class=err> Bank not Found.";
                $confirm .= "{$error}<p><input type=button onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
                return $confirm;
            } else {
                $deptd = pg_fetch_array($deptRslt);
            }
            db_conn('core');
            $Sl = "SELECT * FROM bankacc WHERE accid='{$bankid}'";
            $rd = db_exec($Sl) or errDie("Unable to get data.");
            $data = pg_fetch_array($rd);
            $BA = $data['accnum'];
        }
        $tot_post = 0;
        # bank  % cust
        if ($ctyp == 's') {
            # Get department
            db_conn("exten");
            $sql = "SELECT * FROM departments WHERE deptid = '{$cus['deptid']}' AND div = '" . USER_DIV . "'";
            $deptRslt = db_exec($sql);
            if (pg_numrows($deptRslt) < 1) {
                $dept['deptname'] = "<li class=err>Department not Found.";
            } else {
                $dept = pg_fetch_array($deptRslt);
            }
            $tpp = 0;
            //$sql = "SELECT * FROM nons_inv_items  WHERE invid = '$invid' AND div = '".USER_DIV."'";
            //$stkdRslt = db_exec($sql);
            // 			# Put in product
            // 			while($stk = pg_fetch_array($stkdRslt)){
            // 				$wamt=$stk['amt'];
            //
            // 				$tot_post+=$wamt;
            // 				writetrans($dept['debtacc'], $stk['account'], $td, $refnum, $wamt, "Non-Stock Sales on invoice No.$real_invid customer $cus[surname].");
            // 			}
            # record transaction  from data
            foreach ($totstkamt as $stkacc => $wamt) {
                # Debit Customer and Credit stock
                $tot_post += $wamt;
                writetrans($dept['debtacc'], $stkacc, $td, $refnum, $wamt, "Non-Stock Sales on invoice No.{$real_invid} customer {$inv['cusname']}.");
            }
            # Debit bank and credit the account involved
            if ($VAT != 0) {
                $tot_post += $VAT;
                writetrans($dept['debtacc'], $vatacc, $td, $refnum, $VAT, "Non-Stock Sales VAT received on invoice No.{$real_invid} customer {$inv['cusname']}.");
            }
            $sdate = date("Y-m-d");
        } else {
            if (!isset($accountc)) {
                $accountc = 0;
            }
            if (!isset($dept['pca'])) {
                $accountc += 0;
                $dept['pca'] = $accountc;
                $dept['debtacc'] = $accountc;
            }
            if (isset($bankid)) {
                $dept['pca'] = $BA;
            }
            if ($ctyp == "ac") {
                $dept['pca'] = $inv['tval'];
            }
            $tpp = 0;
            # record transaction  from data
            foreach ($totstkamt as $stkacc => $wamt) {
                if (!isset($cust['surname'])) {
                    $cust['surname'] = $inv['cusname'];
                    $cust['addr1'] = $inv['cusaddr'];
                }
                # Debit Customer and Credit stock
                $tot_post += $wamt;
                writetrans($dept['pca'], $stkacc, $td, $refnum, $wamt, "Non-Stock Sales on invoice No.{$real_invid} customer {$inv['cusname']}.");
            }
            if (isset($bankid)) {
                db_connect();
                $bankid += 0;
                $sql = "INSERT INTO cashbook(bankid, trantype, date, name, descript, cheqnum, amount, vat, chrgvat, banked, accinv, div) VALUES ('{$bankid}', 'deposit', '{$td}', '{$inv['cusname']}', 'Non-Stock Sales on invoice No.{$real_invid} customer {$inv['cusname']}', '0', '{$TOTAL}', '{$VAT}', '{$inv['chrgvat']}', 'no', '{$stkacc}', '" . USER_DIV . "')";
                $Rslt = db_exec($sql) or errDie("Unable to add bank payment to database.", SELF);
                $sql = "UPDATE nons_invoices SET jobid='{$bankid}' WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
                $upRslt = db_exec($sql) or errDie("Unable to update invoice information");
            }
            # Debit bank and credit the account involved
            if ($VAT != 0) {
                $tot_post += $VAT;
                writetrans($dept['pca'], $vatacc, $td, $refnum, $VAT, "Non-Stock Sales VAT received on invoice No.{$real_invid} customer {$inv['cusname']}.");
            }
            $sdate = date("Y-m-d");
        }
        $tot_post = sprint($tot_post);
        db_connect();
        if ($ctyp == 's') {
            $sql = "UPDATE nons_invoices SET balance = total, cusid = '{$cusnum}', ctyp = '{$ctyp}', cusaddr = '{$cus['addr1']}', cusvatno = '{$cus['vatnum']}', done = 'y', invnum = '{$real_invid}' WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
            $upRslt = db_exec($sql) or errDie("Unable to update invoice information");
            # Record the payment on the statement
            $sql = "\n\t\t\t\tINSERT INTO stmnt \n\t\t\t\t\t(cusnum, invid, docref, amount, date, type, div, allocation_date) \n\t\t\t\tVALUES \n\t\t\t\t\t('{$cusnum}', '{$real_invid}', '{$inv['docref']}', '{$TOTAL}','{$inv['odate']}', 'Non-Stock Invoice', '" . USER_DIV . "', '{$inv['odate']}')";
            $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
            # Record the payment on the statement
            $sql = "INSERT INTO open_stmnt(cusnum, invid, docref, amount, balance, date, type, div) VALUES('{$cusnum}', '{$real_invid}', '{$inv['docref']}', '{$TOTAL}', '{$TOTAL}','{$inv['sdate']}', 'Non-Stock Invoice', '" . USER_DIV . "')";
            $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
            # Update the customer (make balance more)
            $sql = "UPDATE customers SET balance = (balance + '{$TOTAL}'::numeric(13,2)) WHERE cusnum = '{$cusnum}' AND div = '" . USER_DIV . "'";
            $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
            # Make ledge record
            custledger($cusnum, $stkacc, $td, $real_invid, "Non Stock Invoice No. {$real_invid}", $TOTAL, "d");
            custDT($TOTAL, $cusnum, $td, $invid, "nons");
            //print $tot_post;exit;
            $tot_dif = sprint($tot_post - $TOTAL);
            if ($tot_dif > 0) {
                writetrans($varacc, $dept['debtacc'], $td, $refnum, $tot_dif, "Sales Variance on invoice {$real_invid}");
            } elseif ($tot_dif < 0) {
                $tot_dif = $tot_dif * -1;
                writetrans($dept['debtacc'], $varacc, $td, $refnum, $tot_dif, "Sales Variance on invoice {$real_invid}");
            }
        } else {
            $date = date("Y-m-d");
            $sql = "UPDATE nons_invoices SET balance=total, accid = '{$dept['pca']}', ctyp = '{$ctyp}', done = 'y', invnum = '{$real_invid}' WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
            $upRslt = db_exec($sql) or errDie("Unable to update invoice information");
            $tot_dif = sprint($tot_post - $TOTAL);
            if ($tot_dif > 0) {
                writetrans($varacc, $dept['pca'], $td, $refnum, $tot_dif, "Sales Variance on invoice {$real_invid}");
            } elseif ($tot_dif < 0) {
                $tot_dif = $tot_dif * -1;
                writetrans($dept['pca'], $varacc, $td, $refnum, $tot_dif, "Sales Variance on invoice {$real_invid}");
            }
            if ($ctyp == "c") {
                $cusnum = "0";
            } elseif ($ctyp == "ac") {
                $cusnum = "0";
                $na = "";
            }
        }
        db_connect();
        $sql = "INSERT INTO salesrec(edate, invid, invnum, debtacc, vat, total, typ, div)\n\t\tVALUES('{$inv['sdate']}', '{$invid}', '{$real_invid}', '{$dept['debtacc']}', '{$VAT}', '{$TOTAL}', 'non', '" . USER_DIV . "')";
        $recRslt = db_exec($sql);
        db_conn('cubit');
        $Sl = "INSERT INTO sj(cid,name,des,date,exl,vat,inc,div) VALUES\n\t\t('{$cusnum}','{$na}','Non-stock Invoice {$real_invid}','{$inv['sdate']}','" . sprint($TOTAL - $VAT) . "','{$VAT}','" . sprint($TOTAL) . "','" . USER_DIV . "')";
        $Ri = db_exec($Sl);
        $ecost = sprint($TOTAL - $VAT);
        db_conn('cubit');
        $inv['jobid'] += 0;
        $Sl = "SELECT * FROM ninvc WHERE inv='{$inv['jobid']}'";
        $Ri = db_exec($Sl);
        if (CC_USE == "use") {
            if (pg_num_rows($Ri) > 0) {
                while ($data = pg_fetch_array($Ri)) {
                    db_conn('cubit');
                    $sql = "SELECT * FROM costcenters WHERE ccid = '{$data['cid']}'";
                    $ccRslt = db_exec($sql) or errDie("Unable to retrieve Cost centers from database.");
                    $cc = pg_fetch_array($ccRslt);
                    $amount = sprint($ecost * $data['amount'] / 100);
                    db_conn(PRD_DB);
                    $sql = "INSERT INTO cctran(ccid, trantype, typename, edate, description, amount, username, div)\n\t\t\t\t\tVALUES('{$cc['ccid']}', 'dt', 'Invoice', '{$inv['sdate']}', 'Invoice No.{$real_invid}', '{$amount}', '" . USER_NAME . "', '" . USER_DIV . "')";
                    $insRslt = db_exec($sql) or errDie("Unable to retrieve insert Cost center amounts into database.");
                }
            }
        }
        $i++;
    }
    pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
    // Retrieve template settings
    db_conn("cubit");
    $sql = "SELECT filename FROM template_settings WHERE template='invoices' AND div='" . USER_DIV . "'";
    $tsRslt = db_exec($sql) or errDie("Unable to retrieve template settings from Cubit.");
    $template = pg_fetch_result($tsRslt, 0);
    if ($template == "invoice-print.php") {
        pdf($_POST);
    } else {
        templatePdf($_POST);
    }
    // Final Laytout
    $write = "\n\t<table border=0 cellpadding='" . TMPL_tblCellPadding . "' cellspacing='" . TMPL_tblCellSpacing . "'>\n\t\t<tr><th>{$i} Invoices Proccesed</th></tr>\n\t\t<tr class='bg-even'><td>Invoices have been successfully printed.</td></tr>\n\t</table>\n\t<p>\n\t<table border=0 cellpadding='" . TMPL_tblCellPadding . "' cellspacing='" . TMPL_tblCellSpacing . "'>\n\t<tr><th>Quick Links</th></tr>\n\t<tr class='bg-odd'><td><a href='invoice-view.php'>View Invoices</a></td></tr>\n\t<script>document.write(getQuicklinkSpecial());</script>\n\t</table>";
    return $write;
}
コード例 #26
0
function calcPerc($type)
{
    core_connect();
    $intacc = gethook("accnum", "salesacc", "name", "SalesInt");
    db_connect();
    # Get all client that must be charged interest
    $sql = "SELECT surname, cusnum, balance, fbalance, deptid, intrate, location, fcid FROM customers WHERE chrgint = 'yes' AND (balance > 0 OR fbalance > 0) AND div = '" . USER_DIV . "'";
    $rs = db_exec($sql) or errDie("Unable to get clients from Cubit.");
    if (pg_numrows($rs) < 1) {
        # Return if they are not charging any interest
        return;
    }
    #go through matching customers ...
    while ($clnt = pg_fetch_array($rs)) {
        if ($clnt['location'] != 'int') {
            #local customer ...
            #figure out the percentage ... based on setting ...
            if ($type == 'brac') {
                # Get from bracket
                $sql = "SELECT percentage as perc FROM intbracs WHERE min <= '{$clnt['balance']}' AND max >= '{$clnt['balance']}'";
                $bRs = db_exec($sql);
                if (pg_numrows($bRs) > 0) {
                    $brac = pg_fetch_array($bRs);
                    $perc = $brac['perc'];
                } else {
                    $perc = 0;
                }
            } elseif ($type[0] == 'r') {
                $perc = $clnt['intrate'];
            } else {
                $perc = $type;
            }
            //calculate the amount to charge interest on ...
            $overdue = getOverdue($clnt['cusnum']);
            # Get Perc of overdue
            $pamt = sprint($perc / 12 / 100 * $overdue);
            $totamt = $pamt + $clnt['balance'];
            $ret[$clnt['cusnum']] = $totamt;
            # Get department
            db_conn("exten");
            $sql = "SELECT * FROM departments WHERE deptid = '{$clnt['deptid']}' AND div = '" . USER_DIV . "'";
            $deptRslt = db_exec($sql);
            if (pg_numrows($deptRslt) < 1) {
                return "<i class='err'>Department Not Found</i>";
            } else {
                $dept = pg_fetch_array($deptRslt);
            }
            if ($pamt > 0) {
                $sdate = date("Y-m-d");
                $invnum = intInvoice($clnt['cusnum'], $pamt, $intacc);
                db_connect();
                # Record the payment on the statement
                $sql = "\n\t\t\t\t\tINSERT INTO stmnt (\n\t\t\t\t\t\tcusnum, invid, amount, date, \n\t\t\t\t\t\ttype, div, allocation_date\n\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t'{$clnt['cusnum']}', '{$invnum}', '{$pamt}', '{$sdate}', \n\t\t\t\t\t\t'Interest on Outstanding balance', '" . USER_DIV . "', '{$sdate}'\n\t\t\t\t\t)";
                $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
                $sql = "\n\t\t\t\t\tINSERT INTO open_stmnt (\n\t\t\t\t\t\tcusnum, invid, amount, balance, date, \n\t\t\t\t\t\ttype, div\n\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t'{$clnt['cusnum']}', '{$invnum}', '{$pamt}', '{$pamt}','{$sdate}', \n\t\t\t\t\t\t'Interest on Outstanding balance', '" . USER_DIV . "'\n\t\t\t\t\t)";
                $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
                # Update the customer (make balance more)
                $sql = "UPDATE customers SET balance = (balance + '{$pamt}'::numeric(13,2)) WHERE cusnum = '{$clnt['cusnum']}' AND div = '" . USER_DIV . "'";
                $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
                # Make ledge record
                custledger($clnt['cusnum'], $intacc, $sdate, 0, "Interest on Outstanding balance", $pamt, "d");
                # Write transaction  (debit debtors control, credit contra account)
                $refnum = getrefnum();
                writetrans($dept['debtacc'], $intacc, date("d-m-Y"), $refnum, $pamt, "Interest Received from customer : {$clnt['surname']}.");
                recordDT($pamt, $clnt['cusnum']);
            }
        } else {
            if ($type == 'brac') {
                # Get from bracket
                $sql = "SELECT percentage as perc FROM intbracs WHERE min <= '{$clnt['balance']}' AND max >= '{$clnt['balance']}'";
                $bRs = db_exec($sql);
                if (pg_numrows($bRs) > 0) {
                    $brac = pg_fetch_array($bRs);
                    $perc = $brac['perc'];
                } else {
                    $perc = 0;
                }
            } elseif ($type[0] == 'r') {
                $perc = $clnt['intrate'];
            } else {
                $perc = $type;
            }
            //		$overdue = getfOverdue($clnt['cusnum']);
            $overdue = getOverdue($clnt['cusnum']);
            $rate = sprint($clnt['balance'] / $clnt['fbalance']);
            # Get Perc of overdue
            $pamt = sprint($perc / 12 / 100 * $overdue);
            $totamt = $pamt + $clnt['fbalance'];
            $ret[$clnt['cusnum']] = $totamt;
            if ($rate == 0) {
                $rate = 1;
            }
            $ltotamt = sprint($totamt * $rate);
            $lpamt = sprint($ltotamt - $clnt['balance']);
            # Get department
            db_conn("exten");
            $sql = "SELECT * FROM departments WHERE deptid = '{$clnt['deptid']}' AND div = '" . USER_DIV . "'";
            $deptRslt = db_exec($sql);
            if (pg_numrows($deptRslt) < 1) {
                return "<i class='err'>Department Not Found</i>";
            } else {
                $dept = pg_fetch_array($deptRslt);
            }
            if ($pamt > 0) {
                $sdate = date("Y-m-d");
                $invnum = fintInvoice($clnt['cusnum'], $pamt, $rate);
                db_connect();
                # Record the payment on the statement
                $sql = "\n\t\t\t\t\tINSERT INTO stmnt (\n\t\t\t\t\t\tcusnum, invid, amount, date, \n\t\t\t\t\t\ttype, div, allocation_date\n\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t'{$clnt['cusnum']}', '{$invnum}', '{$pamt}','{$sdate}', \n\t\t\t\t\t\t'Interest on Outstanding balance', '" . USER_DIV . "', '{$sdate}'\n\t\t\t\t\t)";
                $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
                # Update the customer (make balance more)
                $sql = "UPDATE customers SET fbalance = (fbalance + '{$pamt}'::numeric(13,2)), balance = '{$ltotamt}'::numeric(13,2) WHERE cusnum = '{$clnt['cusnum']}' AND div = '" . USER_DIV . "'";
                $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
                # Make ledge record
                custledger($clnt['cusnum'], $intacc, $sdate, 0, "Interest on Outstanding balance", $lpamt, "d");
                # Write transaction  (debit debtors control, credit contra account)
                $refnum = getrefnum();
                writetrans($dept['debtacc'], $intacc, date("d-m-Y"), $refnum, $lpamt, "Interest Received from customer : {$clnt['surname']}.");
                frecordDT($pamt, $lpamt, $clnt['cusnum'], $clnt['fcid']);
            }
        }
    }
    return $ret;
}
コード例 #27
0
function cash_receipt()
{
    extract($_REQUEST);
    $sql = "SELECT * FROM hire.hire_invoices WHERE invid='{$invid}'";
    $inv_rslt = db_exec($sql) or errDie("Unable to retrieve note.");
    $inv = pg_fetch_array($inv_rslt);
    // Retrieve customer account
    $sql = "SELECT accid FROM core.accounts WHERE topacc='6400' AND accnum='000'";
    $acc_rslt = db_exec($sql) or errDie("Unable to retrieve account.");
    $cust_acc = pg_fetch_result($acc_rslt, 0);
    // Retrieve cash on hand
    $sql = "SELECT accid FROM core.accounts WHERE topacc='7200' AND accnum='000'";
    $acc_rslt = db_exec($sql) or errDie("Unable to retrieve account.");
    $coh_acc = pg_fetch_result($acc_rslt, 0);
    $sql = "SELECT * FROM cubit.customers WHERE cusnum='{$inv['cusnum']}'";
    $cust_rslt = db_exec($sql) or errDie("Unable to retrieve customer.");
    $cust_data = pg_fetch_array($cust_rslt);
    // Retrieve company details
    $sql = "SELECT * FROM cubit.compinfo WHERE compname='" . COMP_NAME . "'";
    $comp_rslt = db_exec($sql) or errDie("Unable to retrieve company details.");
    $comp_data = pg_fetch_array($comp_rslt);
    // Start transactions -----------------------------------------------------
    pglib_transaction("BEGIN");
    $sql = "INSERT INTO hire.cash (invid, cash)\r\n\t\t\tVALUES ('{$invid}', '{$inv['deposit_amt']}')";
    db_exec($sql) or errDie("Unable to add cash to hire.");
    $refnum = getrefnum();
    writetrans($coh_acc, $cust_acc, $inv["odate"], $refnum, $inv["deposit_amt"], "Cash Receipt for " . CUR . "{$inv['deposit_amt']} from {$cust_data['cusname']} " . "{$cust_data['surname']} for Deposit on Hire Note H" . getHirenum($inv["invid"], 1));
    // Make ledger record
    custledger($inv["cusnum"], $cust_acc, $inv["odate"], $inv["invid"], "Cash Receipt for " . CUR . "{$inv['deposit_amt']} from {$cust_data['cusname']} " . "{$cust_data['surname']} for Deposit on Hire Note H" . getHirenum($inv["invid"], 1), $inv["deposit_amt"], "c");
    custCT($inv["deposit_amt"], $inv["cusnum"], $inv["odate"]);
    // Turn the amount around to a negative
    $stmnt_amt = $inv["deposit_amt"] - $inv["deposit_amt"] * 2;
    // Record the payment on the statement
    $sql = "INSERT INTO cubit.stmnt(cusnum, invid, docref, amount, date, type,\r\n\t\t\t\tdiv)\r\n\t\t\tVALUES('{$inv['cusnum']}', '{$inv['invid']}', '{$inv['invnum']}',\r\n\t\t\t\t'{$stmnt_amt}', '{$inv['odate']}',\r\n\t\t\t\t'Cash Receipt for " . CUR . "{$inv['deposit_amt']} from {$cust_data['cusname']} " . "{$cust_data['surname']} for Deposit on Hire Note H" . getHirenum($inv["invid"], 1) . "',\r\n\t\t\t\t'" . USER_DIV . "')";
    $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record");
    // Record the payment on the statement
    $sql = "INSERT INTO cubit.open_stmnt(cusnum, invid, docref, amount, balance,\r\n\t\t\t\tdate, type, div)\r\n\t\t\tVALUES ('{$inv['cusnum']}', '{$inv['invid']}', '{$inv['invnum']}',\r\n\t\t\t\t'{$stmnt_amt}', '{$stmnt_amt}', '{$inv['odate']}',\r\n\t\t\t\t'Cash Receipt for " . CUR . "{$inv['deposit_amt']} from {$cust_data['cusname']} " . "{$cust_data['surname']} for Deposit on Hire Note H" . getHirenum($inv["invid"], 1) . "',\r\n\t\t\t\t'" . USER_DIV . "')";
    $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record.");
    $sql = "UPDATE cubit.customers SET balance=balance-'{$inv['deposit_amt']}'\r\n\t\t\tWHERE cusnum='{$inv['cusnum']}'";
    db_exec($sql) or errDie("Unable to update customer balance.");
    pglib_transaction("COMMIT");
    // End transactions -------------------------------------------------------
    $OUTPUT = "<table " . TMPL_tblDflts . " style='border: 1px solid #000'>\r\n\t\t<tr>\r\n\t\t\t<td align='center'>\r\n\t\t\t\t<b>CASH RECEIPT</b>\r\n\t\t\t</td>\r\n\t\t</tr>\r\n\t\t<tr>\r\n\t\t\t<td align='center'><b>{$comp_data['compname']}</b></td>\r\n\t\t</tr>\r\n\t\t<tr>\r\n\t\t\t<td align='center'>{$comp_data['addr1']}</td>\r\n\t\t</tr>\r\n\t\t<tr>\r\n\t\t\t<td align='center'>{$comp_data['addr2']}</td>\r\n\t\t</tr>\r\n\t\t<tr>\r\n\t\t\t<td align='center'>{$comp_data['addr3']}</td>\r\n\t\t</tr>\r\n\t\t<tr>\r\n\t\t\t<td align='center'>{$comp_data['addr4']}</td>\r\n\t\t</tr>\r\n\t\t<tr>\r\n\t\t\t<td align='center'>Tel: {$comp_data['tel']}</td>\r\n\t\t</tr>\r\n\t\t<tr>\r\n\t\t\t<td style='border-top: 1px solid #000'>Hire No: H" . getHirenum($inv["invid"], 1) . "</td>\r\n\t\t</tr>\r\n\t\t<tr>\r\n\t\t\t<td>Order No.{$inv['ordno']}</td>\r\n\t\t</tr>\r\n\t\t<tr>\r\n\t\t\t<td>Hire Date. {$inv['odate']}</td>\r\n\t\t</tr>\r\n\t\t<tr>\r\n\t\t\t<td style='border-top: 1px solid #000'\r\n\t\t\t\t>Cash Amount Received<br /> From {$cust_data['cusname']} {$cust_data['surname']}: " . CUR . "{$inv['deposit_amt']}</td>\r\n\t\t</tr>\r\n\t\t<tr>\r\n\t\t\t<td>&nbsp;</td>\r\n\t\t</tr>\r\n\t\t<tr>\r\n\t\t\t<td>By: {$inv['username']}</td>\r\n\t\t</tr>\r\n\t\t<tr>\r\n\t\t\t<td><br /><br /></td>\r\n\t\t</tr>\r\n\t</table>";
    require "../tmpl-print.php";
}
コード例 #28
0
function bank($_POST)
{
    # Get vars
    extract($_POST);
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($cashid, "num", 1, 20, "Invalid Reference number.");
    $v->isOk("{$date_day}{$date_month}{$date_year}", "num", 6, 8, "Invalid date selected.");
    if (!checkdate($date_month, $date_day, $date_year)) {
        $v->addError("", "Invalid date selected. No such date possible.");
    }
    # display errors, if any
    if ($v->isError()) {
        $confirm = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $confirm .= "<li class='err'>" . $e["msg"] . "</li>";
        }
        $confirm .= "<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $confirm;
    }
    $seldate = "{$date_year}-{$date_month}-{$date_day}";
    $salconacc = gethook("accnum", "salacc", "name", "salaries control");
    # Get cash book record
    Db_Connect();
    $sql = "SELECT * FROM cashbook WHERE cashid = '{$cashid}' AND div = '" . USER_DIV . "'";
    $accntRslt = db_exec($sql) or errDie("ERROR: Unable to retrieve cashbook entry details from database11.", SELF);
    if (pg_numrows($accntRslt) < 1) {
        $OUTPUT = "<li clss='err'>The entry with reference number, <b>{$cashid}</b> was not found in Cubit.</li>";
        return $OUTPUT;
    }
    $accnt = pg_fetch_array($accntRslt);
    # get hook account number
    core_connect();
    $sql = "SELECT * FROM bankacc WHERE accid = '{$accnt['bankid']}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to retrieve bank account link from Cubit", SELF);
    # check if link exists
    if (pg_numrows($rslt) < 1) {
        return "<li class='err'> ERROR : The bank account that you selected doesn't appear to have an account linked to it.</li>";
    }
    $bank = pg_fetch_array($rslt);
    # Date
    $sdate = date("Y-m-d");
    pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
    # If tis customer payment
    if (($accnt['cusnum'] > 0 || $accnt["multicusnum"] != "") && strlen($accnt['rinvids']) > 0) {
        db_connect();
        # Get invoice Ids and Amounts
        $invids = explode("|", $accnt['rinvids']);
        $amounts = explode("|", $accnt['amounts']);
        $invprds = explode("|", $accnt['invprds']);
        $rages = explode("|", $accnt['rages']);
        if ($accnt["multicusnum"] != "") {
            $cusnums = explode(",", $accnt["multicusnum"]);
            $cusamts = explode(",", $accnt["multicusamt"]);
        } else {
            $cusnums = array($accnt["cusnum"]);
            $cusamts = array($accnt["amount"]);
        }
        $oa = 0;
        # Return the amount that was surppose to be paid to invoices
        foreach ($invids as $key => $invid) {
            if ($invids[$key] <= 0) {
                continue;
            }
            db_connect();
            if (ext_ex("invoices", "invid", $invids[$key]) && $invprds[$key] != 0) {
                db_connect();
                $sql = "\n\t\t\t\t\tUPDATE invoices \n\t\t\t\t\tSET balance = (balance + '{$amounts[$key]}'::numeric(13,2)) \n\t\t\t\t\tWHERE invid = '{$invids[$key]}' AND div = '" . USER_DIV . "'";
                $payRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
                if (open()) {
                    $sql = "SELECT invnum FROM invoices WHERE invid = '{$invids[$key]}' AND div = '" . USER_DIV . "'";
                    $payRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
                    $idata = pg_fetch_array($payRslt);
                    $sql = "\n\t\t\t\t\t\tUPDATE open_stmnt \n\t\t\t\t\t\tSET balance = (balance + '{$amounts[$key]}'::numeric(13,2)) \n\t\t\t\t\t\tWHERE invid = '{$idata['invnum']}' AND div = '" . USER_DIV . "'";
                    $payRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
                    $oa = $oa - $amounts[$key];
                }
            } else {
                if (ext_ex("nons_invoices", "invid", $invids[$key]) && $invprds[$key] == 0) {
                    db_connect();
                    $sql = "\n\t\t\t\t\tUPDATE nons_invoices \n\t\t\t\t\tSET balance = (balance + '{$amounts[$key]}'::numeric(13,2)) \n\t\t\t\t\tWHERE invid = '{$invids[$key]}' AND div = '" . USER_DIV . "'";
                    db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
                    /*$Sll="SELECT sdate FROM nons_invoices WHERE invid = '$invids[$key]' AND div = '".USER_DIV."'";
                    		$Rii=db_exec($Sll) or errDie("Unable to get invoice data.");
                    		$dii=pg_fetch_array($Rii);*/
                    $cnsql = "SELECT cusid FROM cubit.nons_invoices WHERE invid='{$invids[$key]}'";
                    $cnrslt = db_exec($cnsql) or errDie("Error reading customer info from nonstock invoice.");
                    $invcusid = pg_fetch_result($cnrslt, 0, 0);
                    custDTA($amounts[$key], $invcusid, $rages[$key], $seldate);
                } else {
                    if ($invprds[$key] != 0 && ext_ex("pinvoices", "invid", $invids[$key], $invprds[$key])) {
                        $sql = "\n\t\t\t\t\tUPDATE \"{$invprds[$key]}\".pinvoices \n\t\t\t\t\tSET balance = (balance + '{$amounts[$key]}'::numeric(13,2)) \n\t\t\t\t\tWHERE invid = '{$invids[$key]}' AND div = '" . USER_DIV . "'";
                        db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
                        $sql = "SELECT cusnum, balance FROM \"{$invprds[$key]}\".pinvoices WHERE invid='{$invids[$key]}'";
                        $rslt = db_exec($sql) or errDie("Error reading customer info from nonstock invoice.");
                        $invcusid = pg_fetch_result($rslt, 0, 0);
                        custDTA($amounts[$key], $invcusid, $rages[$key], $seldate);
                    } else {
                        if ($invprds[$key] > 0) {
                            if (open()) {
                                db_conn($invprds[$key]);
                                $sql = "SELECT invnum FROM  invoices WHERE invid = '{$invids[$key]}' AND div = '" . USER_DIV . "'";
                                $payRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
                                $idata = pg_fetch_array($payRslt);
                                db_conn('cubit');
                                $sql = "\n\t\t\t\t\t\tUPDATE open_stmnt \n\t\t\t\t\t\tSET balance = (balance + '{$amounts[$key]}'::numeric(13,2)) \n\t\t\t\t\t\tWHERE invid = '{$idata['invnum']}' AND div = '" . USER_DIV . "'";
                                $payRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
                                $oa = $oa - $amounts[$key];
                            }
                            db_conn($invprds[$key]);
                            # check if invoice exitsts on prd
                            if (ext_ex("invoices", "invid", $invids[$key])) {
                                # if found, Move the invoice back
                                if (moveback($invids[$key], $invprds[$key], $amounts[$key])) {
                                }
                            }
                        }
                    }
                }
            }
        }
        foreach ($cusnums as $cuskey => $cusnum) {
            $accnt["cusnum"] = $cusnum;
            $cusamt = $cusamts[$cuskey];
            db_connect();
            # Update the customer (make balance more)
            $sql = "UPDATE customers SET balance = (balance + '{$cusamt}'::numeric(13,2)) \n\t\t\t\t\tWHERE cusnum = '{$accnt['cusnum']}' AND div = '" . USER_DIV . "'";
            $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit1.", SELF);
            # Record the transaction on the statement
            $sql = "\n\t\t\t\tINSERT INTO stmnt (\n\t\t\t\t\tcusnum, invid, amount, date, type, \n\t\t\t\t\tdiv, allocation_date\n\t\t\t\t) VALUES (\n\t\t\t\t\t'{$accnt['cusnum']}', '0', '{$cusamt}', '{$seldate}', 'Cheque/Payment for Invoices Returned.', \n\t\t\t\t\t'" . USER_DIV . "', '{$accnt['date']}'\n\t\t\t\t)";
            $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
            if (sprint($accnt['amount'] + $oa) > 0) {
                # Record the transaction on the statement
                $sql = "\n\t\t\t\t\tINSERT INTO open_stmnt (\n\t\t\t\t\t\tcusnum, invid, amount, date, \n\t\t\t\t\t\ttype, div, balance\n\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t'{$accnt['cusnum']}', '0', '" . sprint($accnt['amount'] + $oa) . "', '{$seldate}', \n\t\t\t\t\t\t'Cheque/Payment for Invoices Returned.', '" . USER_DIV . "', '{$cusamt}'\n\t\t\t\t\t)";
                $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
            }
        }
        # Delete cashbook ID
        $sql = "UPDATE cashbook SET opt = 'n' WHERE cashid='{$cashid}' AND div = '" . USER_DIV . "'";
        $Rslt = db_exec($sql) or errDie("Unable to cancel cheque.", SELF);
        copyEntry($cashid);
        if ($accnt['lcashid'] > 0) {
            // Connect to database
            db_Connect();
            $sql = "SELECT * FROM cashbook WHERE cashid = '{$accnt['lcashid']}' AND div = '" . USER_DIV . "'";
            $laccntRslt = db_exec($sql) or errDie("ERROR: Unable to retrieve cashbook entry details from database.2", SELF);
            $laccnt = pg_fetch_array($laccntRslt);
            $sql = "\n\t\t\t\tUPDATE bankacct \n\t\t\t\tSET fbalance = (fbalance + '{$laccnt['famount']}'::numeric(13,2)), balance = (balance + '{$laccnt['amount']}'::numeric(13,2)) \n\t\t\t\tWHERE bankid = '{$laccnt['bankid']}'";
            $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit2.", SELF);
            # Delete cashbook ID
            $sql = "DELETE FROM cashbook WHERE cashid = '{$accnt['lcashid']}' AND div = '" . USER_DIV . "'";
            $Rslt = db_exec($sql) or errDie("Unable to cancel cheque.", SELF);
        }
        # Make ledge record
        //		custledger($accnt['cusnum'], $bank['accnum'], $accnt['date'], "cancel", "Payment Returned.", $accnt['amount'], "d");
        foreach ($cusnums as $cuskey => $cusnum) {
            $cusamt = $cusamts[$cuskey];
            custledger($cusnum, $bank['accnum'], $seldate, "cancel", "Payment Returned.", $cusamt, "d");
        }
        $descript = $accnt['descript'] . " Returned, Unpaid";
        $refnum = getrefnum();
        $date = date("Y-m-d");
        # debit customer account, credit bank account (customer takes money back)
        //		writetrans($accnt['accinv'], $bank['accnum'], $accnt['date'], $refnum, $accnt['amount'], $descript);
        writetrans($accnt['accinv'], $bank['accnum'], $seldate, $refnum, $accnt['amount'], $descript);
        $vatacc = gethook("accnum", "salesacc", "name", "VAT");
        if ($accnt['vat'] != 0) {
            # DT(VAT), CT(Bank)
            writetrans($vatacc, $bank['accnum'], $accnt['date'], $accnt['reference'], $vat, $accnt['descript']);
        }
    } else {
        if (($accnt['cusnum'] > 0 || $accnt["multicusnum"] != "") && $accnt['trantype'] != "withdrawal") {
            $refnum = getrefnum();
            $date = date("Y-m-d");
            //		recordDT($accnt['amount'], $accnt['cusnum']);
            recordCT($accnt['amount'], $accnt['cusnum']);
            if ($accnt["multicusnum"] != "") {
                $cusnums = explode(",", $accnt["multicusnum"]);
                $cusamts = explode(",", $accnt["multicusamt"]);
            } else {
                $cusnums = array($accnt["cusnum"]);
                $cusamts = array($accnt["amount"]);
            }
            db_connect();
            foreach ($cusnums as $cuskey => $cusnum) {
                $accnt["cusnum"] = $cusnum;
                $cusamt = $cusamts[$cuskey];
                # receipt from customer returned
                $sql = "\n\t\t\t\t\tINSERT INTO stmnt \n\t\t\t\t\t\t(cusnum, invid, amount, date, type, st, div, allocation_date) \n\t\t\t\t\tVALUES \n\t\t\t\t\t\t('{$accnt['cusnum']}', '0', '{$cusamt}', '{$seldate}', 'Cheque/Payment returned', 'n', '" . USER_DIV . "', '{$accnt['date']}')";
                $stmntRslt = db_exec($sql) or errDie("Unable to Insert statement record in Cubit.", SELF);
                $sql = "INSERT INTO open_stmnt(cusnum, invid, amount, date, type, st, div,balance) VALUES('{$accnt['cusnum']}', '0', '{$cusamt}', '{$seldate}', '{$accnt['descript']}, Cheque/Payment returned', 'n', '" . USER_DIV . "','{$cusamt}')";
                $stmntRslt = db_exec($sql) or errDie("Unable to Insert statement record in Cubit.", SELF);
                # update the customer (make balance more)
                $sql = "UPDATE customers SET balance = (balance + '{$cusamt}') WHERE cusnum = '{$accnt['cusnum']}' AND div = '" . USER_DIV . "'";
                $rslt = db_exec($sql) or errDie("Unable to update customer in Cubit.", SELF);
            }
            copyEntry($cashid);
            foreach ($cusnums as $cuskey => $cusnum) {
                $cusamt = $cusamts[$cuskey];
                # Make ledge record
                //		custledger($accnt['cusnum'], $bank['accnum'], $accnt['date'], $refnum, "Cheque/Payment returned.", $accnt['amount'], "c");
                custledger($cusnum, $bank['accnum'], $seldate, $refnum, "Cheque/Payment returned.", $cusamt, "d");
            }
            db_conn('cubit');
            $sql = "UPDATE cashbook SET opt = 'n' WHERE cashid='{$cashid}' AND div = '" . USER_DIV . "'";
            $Rslt = db_exec($sql) or errDie("Unable to cancel cheque.", SELF);
            //		writetrans ($accnt['accinv'],$bank['accnum'], $accnt['date'], $refnum, $accnt['amount'], "Cheque/Payment returned.$accnt[descript]");
            writetrans($accnt['accinv'], $bank['accnum'], $seldate, $refnum, $accnt['amount'], "Cheque/Payment returned.{$accnt['descript']}");
            $vatacc = gethook("accnum", "salesacc", "name", "VAT");
            if ($accnt['vat'] != 0) {
                # DT(VAT), CT(Bank)
                writetrans($vatacc, $bank['accnum'], $accnt['date'], $accnt['reference'], $vat, $accnt['descript']);
            }
        } elseif ($accnt['cusnum'] > 0) {
            $refnum = getrefnum();
            $date = date("Y-m-d");
            recordCT($accnt['amount'], $accnt['cusnum']);
            db_connect();
            # receipt from customer returned
            $sql = "\n\t\t\t\tINSERT INTO stmnt \n\t\t\t\t\t(cusnum, invid, amount, date, type, st, div, allocation_date) \n\t\t\t\tVALUES \n\t\t\t\t\t('{$accnt['cusnum']}', '0', '-{$accnt['amount']}', '{$seldate}', 'Cheque/Payment returned', 'n', '" . USER_DIV . "', '{$accnt['date']}')";
            $stmntRslt = db_exec($sql) or errDie("Unable to Insert statement record in Cubit.", SELF);
            $sql = "INSERT INTO open_stmnt(cusnum, invid, amount, date, type, st, div,balance) VALUES('{$accnt['cusnum']}', '0', '-{$accnt['amount']}', '{$seldate}', '{$accnt['descript']}, Cheque/Payment returned', 'n', '" . USER_DIV . "','-{$accnt['amount']}')";
            $stmntRslt = db_exec($sql) or errDie("Unable to Insert statement record in Cubit.", SELF);
            # update the customer (make balance more)
            $sql = "UPDATE customers SET balance = (balance - '{$accnt['amount']}') WHERE cusnum = '{$accnt['cusnum']}' AND div = '" . USER_DIV . "'";
            $rslt = db_exec($sql) or errDie("Unable to update customer in Cubit.", SELF);
            copyEntry($cashid);
            # Make ledge record
            custledger($accnt['cusnum'], $bank['accnum'], $accnt['date'], $refnum, "Cheque/Payment returned.", $accnt['amount'], "c");
            db_conn('cubit');
            $sql = "UPDATE cashbook SET opt = 'n' WHERE cashid='{$cashid}' AND div = '" . USER_DIV . "'";
            $Rslt = db_exec($sql) or errDie("Unable to cancel cheque.", SELF);
            //		writetrans ($bank['accnum'],$accnt['accinv'], $date, $refnum, $accnt['amount'], "Cheque/Payment returned.$accnt[descript]");
            writetrans($bank['accnum'], $accnt['accinv'], $accnt['date'], $refnum, $accnt['amount'], "Cheque/Payment returned.{$accnt['descript']}");
            $vatacc = gethook("accnum", "salesacc", "name", "VAT");
            if ($accnt['vat'] != 0) {
                # DT(VAT), CT(Bank)
                writetrans($vatacc, $bank['accnum'], $accnt['date'], $accnt['reference'], $vat, $accnt['descript']);
            }
        } elseif ($accnt['supid'] > 0) {
            db_connect();
            $ids = explode("|", $accnt['ids']);
            $purids = explode("|", $accnt['purids']);
            $pamounts = explode("|", $accnt['pamounts']);
            $pdates = explode("|", $accnt['pdates']);
            if (count($ids) > 0) {
                foreach ($ids as $key => $vale) {
                    if ($ids[$key] > 0) {
                        rerecord($ids[$key], $accnt['supid'], $purids[$key], $pamounts[$key], $pdates[$key]);
                    }
                }
            }
            # if the amount was overpaid
            if (array_sum($pamounts) < $accnt['amount']) {
                # get and record amount that was overpaid to balance the equation
                $rem = $accnt['amount'] - array_sum($pamounts);
                rerecord('0', $accnt['supid'], '0', $rem, $accnt['date']);
            }
            # Update the supplier (make balance more)
            $sql = "UPDATE suppliers SET balance = (balance + '{$accnt['amount']}'::numeric(13,2)) WHERE supid = '{$accnt['supid']}' AND div = '" . USER_DIV . "'";
            $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit3.", SELF);
            # Record the payment on the statement
            $sql = "INSERT INTO sup_stmnt(supid, edate, cacc, ref, descript, amount, div) VALUES('{$accnt['supid']}', '{$seldate}', '{$bank['accnum']}', '{$accnt['cheqnum']}', 'Cheque/Payment to Supplier Returned.', '{$accnt['amount']}', '" . USER_DIV . "')";
            $stmntRslt = db_exec($sql) or errDie("Unable to Insert statement record in Cubit.", SELF);
            # Delete cashbook ID
            $sql = "UPDATE cashbook SET opt = 'n' WHERE cashid = '{$cashid}' AND div = '" . USER_DIV . "'";
            $Rslt = db_exec($sql) or errDie("Unable to cancel cheque.", SELF);
            copyEntry($cashid);
            if ($accnt['lcashid'] > 0) {
                // Connect to database
                db_Connect();
                $sql = "SELECT * FROM cashbook WHERE cashid = '{$accnt['lcashid']}' AND div = '" . USER_DIV . "'";
                $laccntRslt = db_exec($sql) or errDie("ERROR: Unable to retrieve cashbook entry details from database3.", SELF);
                $laccnt = pg_fetch_array($laccntRslt);
                $sql = "UPDATE bankacct SET fbalance = (fbalance + '{$laccnt['famount']}'::numeric(13,2)), balance = (balance + '{$laccnt['amount']}'::numeric(13,2)) WHERE bankid = '{$laccnt['bankid']}'";
                $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.4", SELF);
                # Delete cashbook ID
                $sql = "DELETE FROM cashbook WHERE cashid = '{$accnt['lcashid']}' AND div = '" . USER_DIV . "'";
                $Rslt = db_exec($sql) or errDie("Unable to cancel cheque.", SELF);
            }
            suppledger($accnt['supid'], $bank['accnum'], $accnt['date'], $accnt['cheqnum'], "Payment to Supplier Returned", $accnt['amount'], "c");
            db_connect();
            $descript = $accnt['descript'] . " Returned, Unpaid";
            $refnum = getrefnum();
            $date = date("Y-m-d");
            # debit bank, credit supplier account
            writetrans($bank['accnum'], $accnt['accinv'], $accnt['date'], $refnum, $accnt['amount'], $descript);
            $vatacc = gethook("accnum", "salesacc", "name", "VAT");
            if ($accnt['vat'] != 0) {
                # DT(VAT), CT(Bank)
                writetrans($vatacc, $bank['accnum'], $accnt['date'], $accnt['reference'], $vat, $accnt['descript']);
            }
        } elseif ($accnt['suprec'] > 0) {
            db_connect();
            $Sl = "INSERT INTO sup_stmnt(supid, amount, edate, descript,ref,cacc, div) VALUES('{$accnt['suprec']}','-{$accnt['amount']}','{$accnt['date']}', 'Receipt Returned','{$accnt['cheqnum']}','0', '" . USER_DIV . "')";
            $Rs = db_exec($Sl) or errDie("Unable to insert statement record in Cubit.", SELF);
            # Update the supplier (make balance less)
            $sql = "UPDATE suppliers SET balance = (balance - '{$accnt['amount']}'::numeric(13,2)) WHERE supid = '{$accnt['suprec']}' AND div = '" . USER_DIV . "'";
            $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.5", SELF);
            suppDT($accnt['amount'], $accnt['suprec']);
            suppledger($accnt['suprec'], $bank['accnum'], $accnt['date'], $accnt['cheqnum'], "Receipt from Supplier Returned", $accnt['amount'], "d");
            db_connect();
            # Delete cashbook ID
            $sql = "UPDATE cashbook SET opt = 'n' WHERE cashid='{$cashid}' AND div = '" . USER_DIV . "'";
            $Rslt = db_exec($sql) or errDie("Unable to cancel cheque.", SELF);
            copyEntry($cashid);
            if ($accnt['lcashid'] > 0) {
                # Delete cashbook ID
                $sql = "DELETE FROM cashbook WHERE cashid = '{$accnt['lcashid']}' AND div = '" . USER_DIV . "'";
                $Rslt = db_exec($sql) or errDie("Unable to cancel cheque.", SELF);
            }
            $descript = $accnt['descript'] . " Returned, Unpaid";
            $refnum = getrefnum();
            $date = date("Y-m-d");
            # debit bank, credit supplier account
            writetrans($accnt['accinv'], $bank['accnum'], $accnt['date'], $refnum, $accnt['amount'], $descript);
            $vatacc = gethook("accnum", "salesacc", "name", "VAT");
            if ($accnt['vat'] != 0) {
                # DT(VAT), CT(Bank)
                writetrans($vatacc, $bank['accnum'], $accnt['date'], $accnt['reference'], $vat, $accnt['descript']);
            }
        } else {
            if ($accnt["empnum"] != "0" && strlen($accnt["empnum"]) > 0 && $accnt['trantype'] == "withdrawal") {
                $refnum = getrefnum();
                $date = date("Y-m-d");
                $sql = "UPDATE cubit.employees SET balance = balance + '{$accnt['amount']}' \n\t\t\t\tWHERE empnum='{$accnt['empnum']}' AND div = '" . USER_DIV . "'";
                db_exec($sql) or errDie("Unable to get employee details.");
                $sql = "SELECT fnames,sname FROM cubit.employees WHERE empnum='{$accnt['empnum']}'";
                $rslt = db_exec($sql);
                $empinfo = pg_fetch_array($rslt);
                $empname = "{$empinfo['fnames']} {$empinfo['sname']}";
                copyEntry($cashid);
                empledger($accnt["empnum"], $bank['accnum'], $accnt["date"], $refnum, "Cheque/Payment Returned", $accnt['amount'], "c");
                db_conn('cubit');
                $sql = "UPDATE cashbook SET opt = 'n' WHERE cashid='{$cashid}' AND div = '" . USER_DIV . "'";
                $Rslt = db_exec($sql) or errDie("Unable to cancel cheque.", SELF);
                writetrans($bank['accnum'], $accnt['accinv'], $accnt['date'], $refnum, $accnt['amount'], "Cheque/Payment returned for {$empname}");
            } elseif (strlen($accnt['accids']) > 0) {
                /* -- Start Hooks -- */
                $vatacc = gethook("accnum", "salesacc", "name", "VAT");
                /* -- End Hooks -- */
                multican($accnt, $bank, $vatacc, $accnt['vatcode']);
            } else {
                $amount = $accnt['amount'];
                $vat = $accnt['vat'];
                $chrgvat = $accnt['chrgvat'];
                $amount -= $vat;
                /* -- Start Hooks -- */
                $vatacc = gethook("accnum", "salesacc", "name", "VAT");
                /* -- End Hooks -- */
                db_connect();
                # Delete cashbook ID
                $sql = "UPDATE cashbook SET opt = 'n' WHERE cashid='{$cashid}' AND div = '" . USER_DIV . "'";
                $Rslt = db_exec($sql) or errDie("Unable to cancel cheque.", SELF);
                copyEntry($cashid);
                if ($accnt['trantype'] == "deposit") {
                    $sql = "UPDATE bankacct SET fbalance = (fbalance - '{$accnt['famount']}'::numeric(13,2)), balance = (balance - '{$accnt['amount']}'::numeric(13,2)) WHERE bankid = '{$accnt['bankid']}'";
                    $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.5", SELF);
                } else {
                    $sql = "UPDATE bankacct SET fbalance = (fbalance + '{$accnt['famount']}'::numeric(13,2)), balance = (balance + '{$accnt['amount']}'::numeric(13,2)) WHERE bankid = '{$accnt['bankid']}'";
                    $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.6", SELF);
                }
                /* ---- the Others ---- */
                if ($accnt['lcashid'] > 0) {
                    //Connect to database
                    db_Connect();
                    $sql = "SELECT * FROM cashbook WHERE cashid = '{$accnt['lcashid']}' AND div = '" . USER_DIV . "'";
                    $laccntRslt = db_exec($sql) or errDie("ERROR: Unable to retrieve cashbook entry details from database.4", SELF);
                    $laccnt = pg_fetch_array($laccntRslt);
                    if ($laccnt['trantype'] == "deposit") {
                        $sql = "UPDATE bankacct SET fbalance = (fbalance - '{$laccnt['famount']}'::numeric(13,2)), balance = (balance - '{$laccnt['amount']}'::numeric(13,2)) WHERE bankid = '{$laccnt['bankid']}'";
                        $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.7", SELF);
                    } else {
                        $sql = "UPDATE bankacct SET fbalance = (fbalance + '{$laccnt['famount']}'::numeric(13,2)), balance = (balance + '{$laccnt['amount']}'::numeric(13,2)) WHERE bankid = '{$laccnt['bankid']}'";
                        $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.8", SELF);
                    }
                    # Delete cashbook ID
                    $sql = "DELETE FROM cashbook WHERE cashid = '{$accnt['lcashid']}' AND div = '" . USER_DIV . "'";
                    $Rslt = db_exec($sql) or errDie("Unable to cancel cheque.", SELF);
                    /* ---- End the Others ---- */
                }
                $descript = $accnt['descript'] . " Returned, Unpaid";
                $refnum = getrefnum();
                $date = date("Y-m-d");
                if ($accnt['trantype'] == "deposit") {
                    $vatacc = gethook("accnum", "salesacc", "name", "VAT", "a");
                    # DT(account involved), CT(bank)
                    //			writetrans($accnt['accinv'], $bank['accnum'], $accnt['date'], $refnum, $amount, $descript);
                    writetrans($accnt['accinv'], $bank['accnum'], $seldate, $refnum, $amount, $descript);
                    if ($vat != 0) {
                        # DT(Vat), CT(Bank)
                        db_conn('cubit');
                        $Sl = "SELECT * FROM vatcodes WHERE id='{$accnt['vatcode']}'";
                        $Ri = db_exec($Sl);
                        $vd = pg_fetch_array($Ri);
                        //				vatr($vd['id'],$date,"OUTPUT",$vd['code'],$refnum,$descript,-($amount+$vat),-$vat);
                        vatr($vd['id'], $seldate, "OUTPUT", $vd['code'], $refnum, $descript, -($amount + $vat), -$vat);
                        //				writetrans($vatacc, $bank['accnum'], $accnt['date'], $refnum, $vat, $descript);
                        writetrans($vatacc, $bank['accnum'], $seldate, $refnum, $vat, $descript);
                    }
                    $cc_trantype = cc_TranTypeAcc($accnt['accinv'], $bank['accnum']);
                } else {
                    # DT(bank), CT(account invoilved)
                    //			writetrans($bank['accnum'], $accnt['accinv'], $accnt['date'], $refnum, $amount, $descript);
                    writetrans($bank['accnum'], $accnt['accinv'], $seldate, $refnum, $amount, $descript);
                    if ($vat != 0) {
                        # DT(Vat), CT(Bank)
                        db_conn('cubit');
                        $Sl = "SELECT * FROM vatcodes WHERE id='{$accnt['vatcode']}'";
                        $Ri = db_exec($Sl);
                        $vd = pg_fetch_array($Ri);
                        //				vatr($vd['id'],$date,"INPUT",$vd['code'],$refnum,$descript,($amount+$vat),$vat);
                        vatr($vd['id'], $seldate, "INPUT", $vd['code'], $refnum, $descript, $amount + $vat, $vat);
                        //				writetrans($bank['accnum'], $vatacc, $accnt['date'], $refnum, $vat, $descript);
                        writetrans($bank['accnum'], $vatacc, $seldate, $refnum, $vat, $descript);
                    }
                    $cc_trantype = cc_TranTypeAcc($bank['accnum'], $accnt['accinv']);
                }
                /* stock purchase/sale */
                if (!empty($accnt["stkinfo"])) {
                    list($si_stkid, $si_unitnum, $si_cost, $si_vat) = explode("|", $accnt["stkinfo"]);
                    db_connect();
                    $sql = "SELECT * FROM stock WHERE stkid = '{$si_stkid}' AND div = '" . USER_DIV . "'";
                    $stkRslt = db_exec($sql) or errDie("Unable to access databse.", SELF);
                    $stk = pg_fetch_array($stkRslt);
                    if ($accnt['trantype'] == "deposit") {
                        db_connect();
                        $sql = "UPDATE stock SET csamt = (csamt + '{$si_cost}'), \n\t\t\t\t\t\t\tunits = (units + '{$si_unitnum}') \n\t\t\t\t\t\tWHERE stkid = '{$si_stkid}' AND div = '" . USER_DIV . "'";
                        $rslt = db_exec($sql) or errDie("Unable to insert stock to Cubit.", SELF);
                        stockrec($stk['stkid'], $stk['stkcod'], $stk['stkdes'], 'dt', $seldate, $si_unitnum, $si_cost, "Returned receipt for: {$accnt['descript']}");
                        db_connect();
                        $cspric = sprint($si_cost / $si_unitnum);
                        $sql = "INSERT INTO stockrec(edate, stkid, stkcod, stkdes, trantype, qty, csprice, csamt, details, div)\n\t\t\t\t\t\tVALUES('{$seldate}', '{$stk['stkid']}', '{$stk['stkcod']}', '{$stk['stkdes']}', 'inc', '{$si_unitnum}', '{$si_cost}', '{$cspric}', 'Returned receipt for: {$accnt['descript']}', '" . USER_DIV . "')";
                        $recRslt = db_exec($sql);
                        db_connect();
                        $sql = "SELECT * FROM stock WHERE stkid = '{$si_stkid}' AND div = '" . USER_DIV . "'";
                        $stkRslt = db_exec($sql) or errDie("Unable to access databse.", SELF);
                        $stk = pg_fetch_array($stkRslt);
                        if ($stk['units'] != 0) {
                            $sql = "UPDATE stock SET csprice = (csamt/units) WHERE stkid = '{$si_stkid}' AND div = '" . USER_DIV . "'";
                            $rslt = db_exec($sql) or errDie("Unable to insert stock to Cubit.", SELF);
                        } else {
                            $csprice = sprint($si_cost / $si_unitnum);
                            $sql = "UPDATE stock SET csprice = '{$csprice}' WHERE stkid = '{$si_stkid}' AND div = '" . USER_DIV . "'";
                            $rslt = db_exec($sql) or errDie("Unable to insert stock to Cubit.", SELF);
                        }
                    } else {
                        db_connect();
                        $sql = "UPDATE stock SET csamt = (csamt - {$si_cost}), \n\t\t\t\t\t\t\tunits = (units - '{$si_unitnum}') \n\t\t\t\t\t\tWHERE stkid = '{$si_stkid}' AND div = '" . USER_DIV . "'";
                        $rslt = db_exec($sql) or errDie("Unable to insert stock to Cubit.", SELF);
                        stockrec($stk['stkid'], $stk['stkcod'], $stk['stkdes'], 'ct', $seldate, $si_unitnum, $si_cost, "Returned payment for: {$accnt['descript']}");
                        db_connect();
                        $cspric = sprint($si_cost / $si_unitnum);
                        $sql = "INSERT INTO stockrec(edate, stkid, stkcod, stkdes, trantype, qty, csprice, csamt, details, div)\n\t\t\t\t\t\tVALUES('{$seldate}', '{$stk['stkid']}', '{$stk['stkcod']}', '{$stk['stkdes']}', 'dec', '-{$si_unitnum}', '{$si_cost}', '{$cspric}', 'Returned payment for: {$accnt['descript']}', '" . USER_DIV . "')";
                        $recRslt = db_exec($sql);
                        db_connect();
                        $sql = "SELECT * FROM stock WHERE stkid = '{$si_stkid}' AND div = '" . USER_DIV . "'";
                        $stkRslt = db_exec($sql) or errDie("Unable to access databse.", SELF);
                        $stk = pg_fetch_array($stkRslt);
                        if ($stk['units'] != 0) {
                            $sql = "UPDATE stock SET csprice = (csamt/units) WHERE stkid = '{$si_stkid}' AND div = '" . USER_DIV . "'";
                            $rslt = db_exec($sql) or errDie("Unable to insert stock to Cubit.", SELF);
                        } else {
                            $csprice = sprint($si_cost / $si_unitnum);
                            $sql = "UPDATE stock SET csprice = '{$csprice}' WHERE stkid = '{$si_stkid}' AND div = '" . USER_DIV . "'";
                            $rslt = db_exec($sql) or errDie("Unable to insert stock to Cubit.", SELF);
                        }
                    }
                }
            }
        }
    }
    if (isset($cc_trantype) && $cc_trantype != false) {
        $cc = "<script> CostCenter('{$cc_trantype}', 'Returned, Unpaid Bank Transaction', '{$seldate}', '{$descript}', '" . ($accnt['amount'] - $accnt['vat']) . "', '../'); </script>";
    } else {
        $cc = "";
    }
    pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
    # Status report
    $bank = "\n\t\t\t{$cc}\n\t\t\t<table " . TMPL_tblDflts . " width='100%'>\n\t\t\t\t<tr>\n\t\t\t\t\t<th>Cash Book</th>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='datacell'>\n\t\t\t\t\t<td>Cash Book Entry was successfully canceled .</td>\n\t\t\t\t</tr>\n\t\t\t</table>";
    # Main table (layout with menu)
    $OUTPUT = "\n\t\t\t<center>\n\t\t\t<table width='90%'>\n\t\t\t\t<tr valign='top'>\n\t\t\t\t\t<td width='60%'>{$bank}</td>\n\t\t\t\t\t<td align='center'>\n\t\t\t\t\t\t<table " . TMPL_tblDflts . " width='80%'>\n\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t<th>Quick Links</th>\n\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t<td align='center'><a href='cashbook-view.php'>View Cash Book</td>\n\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t<td align='center'><a href='../reporting/not-banked.php'>View Outstanding Cash Book Entries</td>\n\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t<td align='center'><a href='bank-pay-add.php'>Add Bank Payment</td>\n\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t<td align='center'><a href='bank-recpt-add.php'>Add Bank Receipt</td>\n\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t<script>document.write(getQuicklinkSpecial());</script>\n\t\t\t\t\t\t</table>\n\t\t\t\t\t</td>\n\t\t\t\t</tr>\n\t\t\t</table>";
    return $OUTPUT;
}
コード例 #29
0
function write($_POST)
{
    # Get vars
    extract($_POST);
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($cusnum, "num", 1, 50, "Invalid Customer number.");
    $v->isOk($accid, "num", 1, 50, "Invalid Contra Account.");
    $v->isOk($refnum, "num", 1, 10, "Invalid Reference number.");
    $v->isOk($amount, "float", 1, 20, "Invalid Amount.");
    $v->isOk($details, "string", 0, 255, "Invalid Details.");
    $v->isOk($author, "string", 1, 30, "Invalid Authorising person name.");
    $datea = explode("-", $date);
    if (count($datea) == 3) {
        if (!checkdate($datea[1], $datea[2], $datea[0])) {
            $v->isOk($date, "num", 1, 1, "Invalid date.");
        }
    } else {
        $v->isOk($date, "num", 1, 1, "Invalid date.");
    }
    # display errors, if any
    if ($v->isError()) {
        $write = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $write .= "<li class='err'>" . $e["msg"] . "</li>";
        }
        $write .= "<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $write;
    }
    # Accounts details
    $accRs = get("core", "*", "accounts", "accid", $accid);
    $acc = pg_fetch_array($accRs);
    # Select customer
    db_connect();
    $sql = "SELECT * FROM customers WHERE cusnum = '{$cusnum}' AND div = '" . USER_DIV . "'";
    $custRslt = db_exec($sql) or errDie("Unable to access databse.", SELF);
    if (pg_numrows($custRslt) < 1) {
        return "<li> Invalid Customer ID.</li>";
    } else {
        $cust = pg_fetch_array($custRslt);
    }
    # Get department
    db_conn("exten");
    $sql = "SELECT * FROM departments WHERE deptid = '{$cust['deptid']}' AND div = '" . USER_DIV . "'";
    $deptRslt = db_exec($sql);
    if (pg_numrows($deptRslt) < 1) {
        return "<i class='err'>Department Not Found</i>";
    } else {
        $dept = pg_fetch_array($deptRslt);
    }
    $famt = sprint($amount);
    $amount = sprint($amount * $rate);
    cus_xrate_update($cust['fcid'], $rate);
    xrate_update($cust['fcid'], $rate, "invoices", "invid");
    xrate_update($cust['fcid'], $rate, "custran", "id");
    # Probe tran type
    if ($entry == "CT") {
        # Write transaction  (debit contra account, credit debtors control)
        writetrans($accid, $dept['debtacc'], $date, $refnum, $amount, $details . " - Customer {$cust['cusname']} {$cust['surname']}");
        $tran = "\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>{$acc['topacc']}/{$acc['accnum']} - {$acc['accname']}</td>\n\t\t\t\t\t<td>{$cust['accno']} - {$cust['cusname']} {$cust['surname']}</td>\n\t\t\t\t</tr>";
        $samount = sprint($amount - $amount * 2);
        $sfamt = sprint($famt - $famt * 2);
        // recordCT($samount, $cust['cusnum']);
        frecordCT($famt, $amount, $cust['cusnum'], $cust['fcid'], $date);
        $type = 'c';
    } else {
        # Write transaction  (debit debtors control, credit contra account)
        writetrans($dept['debtacc'], $accid, $date, $refnum, $amount, $details . " - Customer {$cust['cusname']} {$cust['surname']}");
        $tran = "\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>{$cust['accno']} - {$cust['cusname']} {$cust['surname']}</td>\n\t\t\t\t\t<td>{$acc['topacc']}/{$acc['accnum']} - {$acc['accname']}</td>\n\t\t\t\t</tr>";
        $samount = $amount;
        $sfamt = $famt;
        // recordDT($samount, $cust['cusnum']);
        frecordDT($famt, $amount, $cust['cusnum'], $cust['fcid'], $date);
        $type = 'd';
    }
    db_connect();
    # Begin updates
    pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
    $sdate = date("Y-m-d");
    # record the payment on the statement
    $sql = "\n\t\t\tINSERT INTO stmnt \n\t\t\t\t(cusnum, invid, amount, date, type, st, div, allocation_date) \n\t\t\tVALUES \n\t\t\t\t('{$cust['cusnum']}', '0', '{$sfamt}', '{$date}', '{$details}', 'n', '" . USER_DIV . "', '{$date}')";
    $stmntRslt = db_exec($sql) or errDie("Unable to Insert statement record in Cubit.", SELF);
    # update the customer (make balance more)
    $sql = "UPDATE customers SET balance = (balance + '{$samount}'), fbalance = (fbalance + '{$sfamt}') WHERE cusnum = '{$cust['cusnum']}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to update customer in Cubit.", SELF);
    # Commit updates
    pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
    # Make ledge record
    custledger($cust['cusnum'], $accid, $date, $refnum, $details, $amount, $type);
    // Start layout
    $write = "\n\t\t\t<h3>Journal transaction has been recorded</h3>\n\t\t\t<table " . TMPL_tblDflts . " width='500'>\n\t\t\t\t<tr>\n\t\t\t\t\t<td width='50%'><h3>Debit</h3></td>\n\t\t\t\t\t<td width='50%'><h3>Credit</h3></td>\n\t\t\t\t</tr>\n\t\t\t\t{$tran}\n\t\t\t\t" . TBL_BR . "\n\t\t\t\t<tr colspan='2'>\n\t\t\t\t\t<td><h4>Amount</h4></td>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td colspan='2'><b>" . CUR . " {$famt}</b></td>\n\t\t\t\t</tr>\n\t\t\t</table>\n\t\t\t<P>\n\t\t\t<table " . TMPL_tblDflts . " width='25%'>\n\t\t\t\t<tr>\n\t\t\t\t\t<th>Quick Links</th>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td align='center'><a href='trans-new.php'>Journal Transactions</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td align='center'><a href='../customers-view.php'>View Customers</a></td>\n\t\t\t\t</tr>\n\t\t\t\t<script>document.write(getQuicklinkSpecial());</script>\n\t\t\t</table>";
    return $write;
}
コード例 #30
0
function cash_receipt()
{
    extract($_REQUEST);
    $sql = "SELECT * FROM hire.hire_invoices WHERE invid='{$invid}'";
    $inv_rslt = db_exec($sql) or errDie("Unable to retrieve note.");
    $inv = pg_fetch_array($inv_rslt);
    // Retrieve customer account
    $sql = "SELECT accid FROM core.accounts WHERE topacc='6400' AND accnum='000'";
    $acc_rslt = db_exec($sql) or errDie("Unable to retrieve account.");
    $cust_acc = pg_fetch_array($acc_rslt);
    // Retrieve cash on hand
    $sql = "SELECT accid FROM core.accounts WHERE topacc='7200' AND accnum='000'";
    $acc_rslt = db_exec($sql) or errDie("Unable to retrieve account.");
    $coh_acc = pg_fetch_array($acc_rslt);
    $sql = "SELECT * FROM cubit.customers WHERE cusnum='{$inv['cusnum']}'";
    $cust_rslt = db_exec($sql) or errDie("Unable to retrieve customer.");
    $cust_data = pg_fetch_array($cust_rslt);
    $details = "Cash Receipt for " . CUR . "{$inv['deposit_amt']} from " . ($details .= "{$cust_data['cusname']} {$cust_data['surname']}");
    custledger($cust_data["cusnum"], $coh_acc, $inv["odate"], $details, $inv["deposit_amt"], "d");
    custDT($inv["deposit_amt"], $cust_data["cusnum"], $inv["odate"]);
    $sql = "UPDATE cubit.customers SET balance=balance-'{$inv['deposit_amt']}'\r\n\t\t\tWHERE cusnum='{$cust_data['cusnum']}'";
    db_exec($sql) or errDie("Unable to update customer balance.");
    // Retrieve company details
    $sql = "SELECT * FROM cubit.compinfo WHERE compname='" . COMP_NAME . "'";
    $comp_rslt = db_exec($sql) or errDie("Unable to retrieve company details.");
    $comp_data = pg_fetch_array($comp_rslt);
    $OUTPUT = "<table " . TMPL_tblDflts . " style='border: 1px solid #000'>\r\n\t\t<tr>\r\n\t\t\t<td align='center'>\r\n\t\t\t\t<b>CASH RECEIPT</b>\r\n\t\t\t</td>\r\n\t\t</tr>\r\n\t\t<tr>\r\n\t\t\t<td align='center'><b>{$comp_data['compname']}</b></td>\r\n\t\t</tr>\r\n\t\t<tr>\r\n\t\t\t<td align='center'>{$comp_data['addr1']}</td>\r\n\t\t</tr>\r\n\t\t<tr>\r\n\t\t\t<td align='center'>{$comp_data['addr2']}</td>\r\n\t\t</tr>\r\n\t\t<tr>\r\n\t\t\t<td align='center'>{$comp_data['addr3']}</td>\r\n\t\t</tr>\r\n\t\t<tr>\r\n\t\t\t<td align='center'>{$comp_data['addr4']}</td>\r\n\t\t</tr>\r\n\t\t<tr>\r\n\t\t\t<td align='center'>Tel: {$comp_data['tel']}</td>\r\n\t\t</tr>\r\n\t\t<tr>\r\n\t\t\t<td style='border-top: 1px solid #000'>Hire No: H{$inv['invid']}" . rev($inv["invid"]) . "</td>\r\n\t\t</tr>\r\n\t\t<tr>\r\n\t\t\t<td>Order No.{$inv['ordno']}</td>\r\n\t\t</tr>\r\n\t\t<tr>\r\n\t\t\t<td>Hire Date. {$inv['odate']}</td>\r\n\t\t</tr>\r\n\t\t<tr>\r\n\t\t\t<td style='border-top: 1px solid #000'\r\n\t\t\t\t>Cash Amount Received<br /> From {$cust_data['cusname']} {$cust_data['surname']}: " . CUR . "{$inv['deposit_amt']}</td>\r\n\t\t</tr>\r\n\t\t<tr>\r\n\t\t\t<td>&nbsp;</td>\r\n\t\t</tr>\r\n\t\t<tr>\r\n\t\t\t<td>By: {$inv['username']}</td>\r\n\t\t</tr>\r\n\t\t<tr>\r\n\t\t\t<td><br /><br /></td>\r\n\t\t</tr>\r\n\t</table>";
    require "../tmpl-print.php";
}