function confirm_list($_POST)
{
    extract($_POST);
    if (!isset($ids) or !is_array($ids) or count($ids) < 1) {
        return get_list($_POST);
    }
    //print "<pre>";
    //var_dump ($_POST);
    //print "</pre>";
    foreach ($ids as $id) {
        db_conn('contract');
        $get_info = "SELECT * from supp_creditor_run_cheques WHERE id = '{$id}' LIMIT 1";
        $run_info = db_exec($get_info) or errDie("Unable to get sub contractor information.");
        if (pg_numrows($run_info) < 1) {
            return "Could not get cheque information.";
        }
        $suparr = pg_fetch_array($run_info);
        $bankid = $suparr['bankid'];
        $supid = $suparr['supid'];
        $date = $suparr['proc_date'];
        $cheqnum = $suparr['cheq_num'];
        //$date = "$date_year-$date_month-$date_day";
        $amt = $suparr['amount'];
        $upd_sql = "UPDATE supp_creditor_run_cheques SET handed_over = 'yes' WHERE id = '{$id}'";
        $run_upd = db_exec($upd_sql) or errDie("Unable to update cheque run information.");
        #now we need to process these cheques
        # get hook account number
        core_connect();
        $sql = "SELECT * FROM bankacc WHERE accid = '{$bankid}' AND div = '" . USER_DIV . "' AND accid!=0";
        $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();
        # Supplier name
        $sql = "SELECT supid,supno,supname,deptid FROM suppliers WHERE supid = '{$supid}' AND div = '" . USER_DIV . "'";
        $supRslt = db_exec($sql);
        $sup = pg_fetch_array($supRslt);
        db_conn("exten");
        # get debtors control account
        $sql = "SELECT credacc FROM departments WHERE deptid ='{$sup['deptid']}' AND div = '" . USER_DIV . "'";
        $deptRslt = db_exec($sql);
        $dept = pg_fetch_array($deptRslt);
        # date format
        $sdate = $date;
        $cheqnum = 0 + $cheqnum;
        $pay = "";
        $accdate = $sdate;
        # Paid invoices
        $invidsers = "";
        $rinvids = "";
        $amounts = "";
        $invprds = "";
        $out = "";
        $reference = "";
        db_conn("cubit");
        pglib_transaction("BEGIN");
        $all = 0;
        if ($all == 0) {
            $ids2 = "";
            $purids = "";
            $pamounts = "";
            $pdates = "";
            if (isset($invids)) {
                foreach ($invids as $key => $value) {
                    #debt invoice info
                    $sql = "SELECT id,pdate FROM suppurch WHERE purid ='{$invids[$key]}' AND div = '" . USER_DIV . "' ORDER BY balance LIMIT 1";
                    $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.";
                    }
                    $pur = pg_fetch_array($invRslt);
                    # reduce the money that has been paid
                    $sql = "UPDATE suppurch SET balance = (balance - '{$paidamt[$key]}'::numeric(13,2)) WHERE purid = '{$invids[$key]}' AND div = '" . USER_DIV . "' AND id='{$pur['id']}'";
                    $payRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
                    $ids2 .= "|{$pur['id']}";
                    $purids .= "|{$invids[$key]}";
                    $pamounts .= "|{$paidamt[$key]}";
                    $pdates .= "|{$pur['pdate']}";
                }
            }
            $samount = $amt - $amt * 2;
            if ($out > 0) {
                recordDT($out, $sup['supid'], $sdate);
            }
            $Sl = "INSERT INTO sup_stmnt(supid, amount, edate, descript,ref,cacc, div) VALUES('{$sup['supid']}','{$samount}','{$sdate}', 'Payment','{$cheqnum}','{$bank['accnum']}', '" . USER_DIV . "')";
            $Rs = db_exec($Sl) or errDie("Unable to insert statement record in Cubit.", SELF);
            db_connect();
            # Update the supplier (make balance less)
            $sql = "UPDATE suppliers SET balance = (balance - '{$amt}'::numeric(13,2)) WHERE supid = '{$sup['supid']}'";
            $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
            suppledger($sup['supid'], $bank['accnum'], $sdate, $cheqnum, "Payment for purchases", $amt, "d");
            db_connect();
            # Record the payment record
            $sql = "INSERT INTO cashbook(bankid, trantype, date, name, descript, cheqnum, amount, banked, accinv, supid, ids, purids, pamounts, pdates, reference, div) VALUES ('{$bankid}', 'withdrawal', '{$sdate}', '{$sup['supno']} - {$sup['supname']}', 'Supplier Payment to {$sup['supname']}', '{$cheqnum}', '{$amt}', 'no', '{$dept['credacc']}', '{$sup['supid']}', '{$ids2}', '{$purids}', '{$pamounts}', '{$pdates}', '{$reference}', '" . 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);
            $link['accnum'] = $bank['accnum'];
            writetrans($dept['credacc'], $link['accnum'], $accdate, $refnum, $amt, "Supplier Payment to {$sup['supname']}");
            db_conn('cubit');
        }
        $Sl = "DELETE FROM suppurch WHERE balance=0::numeric(13,2)";
        $Rx = db_exec($Sl);
        #add the supplier purchase entry ?
        $purch_sql = "\n\t\t\t\t\t\tINSERT INTO suppurch \n\t\t\t\t\t\t\t(supid,purid,intpurid,pdate,div,npurid,balance,fcid,fbalance) \n\t\t\t\t\t\tVALUES \n\t\t\t\t\t\t\t('{$sup['supid']}','0','0','{$date}','" . USER_DIV . "','0','-{$amt}','0','0.00')";
        $run_purch = db_exec($purch_sql) or errDie("Unable to update supplier purchase information.");
        db_conn('contract');
        $upd_sql = "UPDATE supp_creditor_run_cheques SET remarks = '{$remark[$id]}' WHERE id = '{$id}'";
        $run_upd = db_exec($upd_sql) or errDie("Unable to update contract remittance.");
        #also update the run listing
        $upd2_sql = "UPDATE credit_runs SET remarks = '{$remark[$id]}' WHERE entry_id = '{$id}'";
        $run_upd2 = db_exec($upd2_sql) or errDie("Unable to update creditor run information.");
        pglib_transaction("COMMIT");
    }
    ##PTH/CUBIT
    //	db_conn ("contract");
    //	#process the remarks
    //	foreach ($conid AS $each => $own){
    //		$upd_sql = "UPDATE contract_recs SET remarks = '$remark[$each]' WHERE conid = '$own' AND remit = '$remit[$each]'";
    //		$run_upd = db_exec($upd_sql) or errDie("Unable to update contract remittance.");
    //	}
    return get_list($_POST, "<li class='err'>Cheques Have been recorded.</li>");
}
function write($_POST)
{
    # Get vars
    extract($_POST);
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($purid, "num", 1, 20, "Invalid Order number.");
    $v->isOk($refno, "string", 0, 255, "Invalid Delivery Reference No.");
    $v->isOk($remarks, "string", 0, 255, "Invalid Remarks.");
    $v->isOk($supinv, "string", 0, 255, "Invalid supp inv.");
    # used to generate errors
    $error = "asa@";
    # display errors, if any
    $err = "";
    if ($v->isError()) {
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $err .= "<li class='err'>" . $e["msg"] . "</li>";
        }
        return details($_POST, $err);
    }
    # Get purchase info
    db_connect();
    $sql = "SELECT * FROM purchases WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
    $purRslt = db_exec($sql) or errDie("Unable to get purchase information");
    if (pg_numrows($purRslt) < 1) {
        return "<li>- Purchase Not Found</li>";
    }
    $pur = pg_fetch_array($purRslt);
    # CHECK IF THIS DATE IS IN THE BLOCKED RANGE
    $blocked_date_from = getCSetting("BLOCKED_FROM");
    $blocked_date_to = getCSetting("BLOCKED_TO");
    if (strtotime($pur['pdate']) >= strtotime($blocked_date_from) and strtotime($pur['pdate']) <= 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 = $pur['pdate'];
    $td = "{$p_year}-{$p_month}-{$p_day}";
    # check if purchase has been received
    if ($pur['invcd'] == "y") {
        $error = "<li class='err'> Error : Purchase number <b>{$pur['purnum']}</b> has already been invoiced.</li>";
        $error .= "<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $error;
    }
    # Get selected supplier info
    db_connect();
    $sql = "SELECT * FROM suppliers WHERE supid = '{$pur['supid']}' AND div = '" . USER_DIV . "'";
    $supRslt = db_exec($sql) or errDie("Unable to get customer information");
    if (pg_numrows($supRslt) < 1) {
        // code here
    } else {
        $sup = pg_fetch_array($supRslt);
    }
    # Get department info
    db_conn("exten");
    $sql = "SELECT * FROM departments WHERE deptid = '{$pur['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);
    }
    # Get warehouse name
    db_conn("exten");
    $sql = "SELECT * FROM warehouses WHERE div = '" . USER_DIV . "'";
    $whRslt = db_exec($sql);
    $wh = pg_fetch_array($whRslt);
    pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
    $refnum = getrefnum();
    # get selected stock in this purchase
    db_connect();
    $sql = "SELECT * FROM pur_items  WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
    $stktRslt = db_exec($sql);
    while ($stkd = pg_fetch_array($stktRslt)) {
        $iq = $qty[$stkd['id']];
        $iq += 0;
        $Sl = "SELECT * FROM vatcodes WHERE id='{$stkd['vatcode']}'";
        $Ri = db_exec($Sl) or errDie("Unable to get data.");
        $vd = pg_fetch_array($Ri);
        if ($pur['vatinc'] == "yes") {
            $iamount = $stkd['amt'];
        } else {
            $iamount = sprint($stkd['amt'] + $stkd['svat']);
        }
        //$pur['pdate'] -> $td
        vatr($vd['id'], $td, "INPUT", $vd['code'], $refnum, "VAT for Purchase No. {$pur['purnum']}", -$iamount, -$stkd['svat']);
        $Sl = "UPDATE pur_items SET iqty=iqty-'{$iq}' WHERE id='{$stkd['id']}'";
        $Ri = db_exec($Sl) or errDie("Unable to update invoice qty.");
    }
    ###################VAT CALCS#######################
    $pur['delvat'] += 0;
    db_conn('cubit');
    $Sl = "SELECT * FROM vatcodes WHERE id='{$pur['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($pur['shipchrg'], $pur['vatinc'], $excluding, 0, $vd['vat_amount']);
    $vrs = explode("|", $vr);
    $ivat_tmp = $vrs[0];
    $iamount_tmp = $vrs[1];
    vatr($vd['id'], $td, "INPUT", $vd['code'], $refnum, "VAT Paid for Purchase No. {$pur['purnum']} from Supplier : {$pur['supname']}.", sprint(-$iamount_tmp), -$ivat_tmp);
    ####################################################
    /* - Start Hooks - */
    $vatacc = gethook("accnum", "salesacc", "name", "VAT");
    $cvacc = gethook("accnum", "pchsacc", "name", "Cost Variance");
    /* - End Hooks - */
    # Record the payment on the statement
    db_connect();
    $sdate = date("Y-m-d");
    $DAte = date("Y-m-d");
    # update the supplier (make balance more)
    $sql = "UPDATE suppliers SET balance = (balance + '{$TOTAL}') WHERE supid = '{$pur['supid']}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
    //$pur['pdate'] -> $td
    $sql = "\n\t\t\tINSERT INTO sup_stmnt (\n\t\t\t\tsupid, edate, cacc, amount, descript, \n\t\t\t\tref, ex, div\n\t\t\t) VALUES (\n\t\t\t\t'{$pur['supid']}', '{$td}', '{$wh['conacc']}', '{$TOTAL}', 'Stock Received - Purchase {$pur['purnum']} Inv:{$supinv}', \n\t\t\t\t'{$refnum}', '{$pur['purnum']}', '" . USER_DIV . "'\n\t\t\t)";
    $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
    # Debit Stock Control and Credit Creditors control
    writetrans($wh['conacc'], $dept['credacc'], $td, $refnum, sprint($SUBTOT + $del), "Invoice Received for Purchase No. {$pur['purnum']} from Supplier : {$pur['supname']}.");
    # Transfer vat
    writetrans($vatacc, $dept['credacc'], $td, $refnum, $VAT, "VAT Paid for Purchase No. {$pur['purnum']} from Supplier : {$pur['supname']}.");
    # Ledger Records
    suppledger($pur['supid'], $wh['conacc'], $td, $pur['purid'], "Purchase No. {$pur['purnum']} received.", $TOTAL, 'c');
    /* End Transactions */
    /* Make transaction record  for age analysis */
    db_connect();
    # update the supplier age analysis (make balance less)
    if (ext_ex2("suppurch", "purid", $pur['purnum'], "supid", $pur['supid'])) {
        # Found? Make amount less
        $sql = "\n\t\t\t\t\tUPDATE suppurch \n\t\t\t\t\tSET balance = (balance + '{$TOTAL}') \n\t\t\t\t\tWHERE supid = '{$pur['supid']}' AND purid = '{$pur['purnum']}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
    } else {
        //$pur['pdate'] -> $td
        /* Make transaction record for age analysis */
        $sql = "\n\t\t\t\t\tINSERT INTO suppurch (\n\t\t\t\t\t\tsupid, purid, pdate, balance, div\n\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t'{$pur['supid']}', '{$pur['purnum']}', '{$td}', '{$TOTAL}', '" . USER_DIV . "'\n\t\t\t\t\t)";
        $purcRslt = db_exec($sql) or errDie("Unable to update Order information in Cubit.", SELF);
    }
    /* Make transaction record  for age analysis */
    # commit updating
    $sql = "UPDATE purchases SET iamount = iamount+'{$TOTAL}',ivat=ivat+'{$VAT}' WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to update Order status in Cubit.", SELF);
    $sql = "SELECT * FROM purchases WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
    $purRslt = db_exec($sql) or errDie("Unable to get purchase information");
    $p = pg_fetch_array($purRslt);
    //pglib_transaction ("COMMIT") or errDie("Unable to commit a database transaction.",SELF);
    $sql = "SELECT SUM(iqty) FROM pur_items  WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
    $stktRslt = db_exec($sql);
    $data = pg_fetch_array($stktRslt);
    $left = $data['sum'];
    if ($left == 0) {
        /* Start moving if purchase */
        if ($pur['received'] == "y") {
            if (strlen($pur['appdate']) < 8) {
                $pur['appdate'] = date("Y-m-d");
            }
            # copy purchase
            db_conn($pur['prd']);
            //$pur['pdate'] -> $td
            $sql = "\n\t\t\t\tINSERT INTO purchases (\n\t\t\t\t\tpurid, deptid, supid, supname, supaddr, supno, terms, \n\t\t\t\t\tpdate, ddate, shipchrg, subtot, total, balance, vatinc, vat, \n\t\t\t\t\tshipping, remarks, refno, received, done, div, purnum, supinv, \n\t\t\t\t\tordernum, appname, appdate, delvat\n\t\t\t\t) VALUES (\n\t\t\t\t\t'{$purid}', '{$pur['deptid']}', '{$pur['supid']}',  '{$pur['supname']}', '{$pur['supaddr']}', '{$pur['supno']}', '{$pur['terms']}', \n\t\t\t\t\t'{$td}', '{$pur['ddate']}', '{$pur['shipchrg']}', '{$pur['subtot']}', '{$pur['total']}', '0', '{$pur['vatinc']}', '{$pur['vat']}', \n\t\t\t\t\t'{$pur['shipping']}', '{$remarks}', '{$pur['refno']}', 'y', 'y', '" . USER_DIV . "', '{$pur['purnum']}', '{$supinv}', \n\t\t\t\t\t'{$pur['ordernum']}', '{$pur['appname']}', '{$pur['appdate']}', '{$pur['delvat']}'\n\t\t\t\t)";
            $rslt = db_exec($sql) or errDie("Unable to insert Order to Cubit.", SELF);
            /*-- Cost varience -- */
            //$nsubtot = sprint($pur['total'] - $pur['vat']);
            $nsubtot = sprint($p['iamount'] - $p['ivat']);
            if ($p['rsubtot'] > $nsubtot) {
                $diff = sprint($p['rsubtot'] - $nsubtot);
                # Debit Stock Control and Credit Creditors control
                writetrans($wh['conacc'], $cvacc, $td, $refnum, $diff, "Cost Variance for Stock Received on Purchase No. {$pur['purnum']} from Supplier : {$sup['supname']}.");
            } elseif ($nsubtot > $p['rsubtot']) {
                $diff = sprint($nsubtot - $pur['rsubtot']);
                # Debit Stock Control and Credit Creditors control
                writetrans($cvacc, $wh['conacc'], $td, $refnum, $diff, "Cost Variance for Stock Received on Purchase No. {$pur['purnum']} from Supplier : {$sup['supname']}.");
            }
            /*-- End Cost varience -- */
            db_connect();
            # Get selected stock
            $sql = "SELECT * FROM pur_items WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
            $stktcRslt = db_exec($sql);
            while ($stktc = pg_fetch_array($stktcRslt)) {
                db_conn($pur['prd']);
                $sql = "\n\t\t\t\t\tINSERT INTO pur_items (\n\t\t\t\t\t\tpurid, whid, stkid, qty, rqty, unitcost, \n\t\t\t\t\t\tamt, svat, ddate, div, vatcode, \n\t\t\t\t\t\taccount, description, udiscount\n\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t'{$purid}', '{$stktc['whid']}', '{$stktc['stkid']}', '{$stktc['qty']}', '{$stktc['rqty']}', '{$stktc['unitcost']}', \n\t\t\t\t\t\t'{$stktc['amt']}', '{$stktc['svat']}', '{$stktc['ddate']}', '" . USER_DIV . "', '{$stktc['vatcode']}', \n\t\t\t\t\t\t'{$stktc['account']}', '{$stktc['description']}', '{$stktc['udiscount']}'\n\t\t\t\t\t)";
                $rslt = db_exec($sql) or errDie("Unable to insert Order items to Cubit.", SELF);
            }
            # begin updating
            //pglib_transaction ("BEGIN") or errDie("Unable to start a database transaction.",SELF);
            db_connect();
            # Remove the purchase from running DB
            $sql = "DELETE FROM purchases WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
            $delRslt = db_exec($sql) or errDie("Unable to update int purchases information in Cubit.", SELF);
            # Record where purchase is
            $sql = "INSERT INTO movpurch (purtype, purnum, prd, div) VALUES ('loc', '{$pur['purnum']}', '{$pur['prd']}', '" . USER_DIV . "')";
            $movRslt = db_exec($sql) or errDie("Unable to update int purchases information in Cubit.", SELF);
            # Remove those purchase items from running DB
            $sql = "DELETE FROM pur_items WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
            $delRslt = db_exec($sql) or errDie("Unable to update int purchases information in Cubit.", SELF);
            /* End moving purchase received */
            # commit updating
            //pglib_transaction ("COMMIT") or errDie("Unable to commit a database transaction.",SELF);
        } else {
            # insert Order to DB
            $sql = "UPDATE purchases SET invcd = 'y', supinv='{$supinv}', remarks = '{$remarks}' WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
            $rslt = db_exec($sql) or errDie("Unable to update Order status in Cubit.", SELF);
        }
    }
    pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
    // Final Layout
    $write = "\n\t\t<table " . TMPL_tblDflts . ">\n\t\t\t<tr>\n\t\t\t\t<th>Purchase Invoiced</th>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Purchase Invoice from Supplier <b>{$pur['supname']}</b> has been recorded.</td>\n\t\t\t</tr>\n\t\t</table>\n\t\t<p>\n\t\t<table " . TMPL_tblDflts . ">\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='" . bg_class() . "'>\n\t\t\t\t<td><a href='purchase-view.php'>View purchases</a></td>\n\t\t\t</tr>\n\t\t\t<script>document.write(getQuicklinkSpecial());</script>\n\t\t</table>";
    return $write;
}
function write($_POST)
{
    #get vars
    extract($_POST);
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($purid, "num", 1, 20, "Invalid Order number.");
    $v->isOk($refno, "string", 0, 255, "Invalid Delivery Reference No.");
    $ddate = $dyear . "-" . $dmon . "-" . $dday;
    if (!checkdate($dmon, $dday, $dyear)) {
        $v->isOk($ddate, "num", 1, 1, "Invalid Date.");
    }
    # used to generate errors
    $error = "asa@";
    # check quantities
    if (isset($qtys)) {
        foreach ($qtys as $keys => $qty) {
            $v->isOk($qtys[$keys], "num", 1, 10, "Invalid Quantity for product number : <b>" . ($keys + 1) . "</b>");
            $v->isOk($unitamts[$keys], "float", 1, 20, "Invalid Unit Price for product number : <b>" . ($keys + 1) . "</b>.");
            $v->isOk($stkacc[$keys], "num", 1, 10, "Invalid Item Account number : <b>" . ($keys + 1) . "</b>");
        }
    } else {
        $v->isOk("#", "num", 0, 0, "Error : no products selected.");
    }
    $prd += 0;
    # display errors, if any
    $err = "";
    if ($v->isError()) {
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $err .= "<li class='err'>" . $e["msg"] . "</li>";
        }
        return details($_POST, $err);
    }
    # Get Order info
    db_conn($prd);
    $sql = "SELECT * FROM nons_purch_int WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
    $purRslt = db_exec($sql) or errDie("Unable to get Order information");
    if (pg_numrows($purRslt) < 1) {
        return "<li>- Order Not Found</li>";
    }
    $pur = pg_fetch_array($purRslt);
    # Get selected supplier info
    db_connect();
    $sql = "SELECT * FROM suppliers WHERE supid = '{$pur['supid']}' AND div = '" . USER_DIV . "'";
    $supRslt = db_exec($sql) or errDie("Unable to get supplier");
    if (pg_numrows($supRslt) < 1) {
        $error = "<li class='err'> Supplier not Found.</li>";
        $confirm .= "{$error}<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $confirm;
    } else {
        $sup = pg_fetch_array($supRslt);
        $pur['supplier'] = $sup['supname'];
        $pur['supaddr'] = $sup['supaddr'];
        # Get department info
        db_conn("exten");
        $sql = "SELECT * FROM departments WHERE deptid = '{$sup['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);
        }
        $supacc = $dept['credacc'];
    }
    # Insert Order to DB
    db_connect();
    # begin updating
    pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
    db_connect();
    # Update all supplies xchange rate first
    xrate_update($pur['fcid'], $pur['xrate'], "suppurch", "id");
    sup_xrate_update($pur['fcid'], $pur['xrate']);
    db_connect();
    $retax = 0;
    if (isset($qtys)) {
        foreach ($qtys as $keys => $value) {
            # Get selected stock line
            db_conn($prd);
            $sql = "SELECT * FROM nons_purint_items WHERE id = '{$ids[$keys]}' AND purid = '{$purid}' AND div = '" . USER_DIV . "'";
            $stkdRslt = db_exec($sql);
            $stkd = pg_fetch_array($stkdRslt);
            # the unitcost + delivery charges * qty
            $famt[$keys] = sprint($unitamts[$keys] * $qtys[$keys]);
            # calculate tax
            $ftaxes[$keys] = svat($famt[$keys], $pur['subtot'], $pur['tax']);
            $amt[$keys] = sprint($unitamts[$keys] * $pur['xrate'] * $qtys[$keys]);
            # calculate tax
            $retax += sprint($ftaxes[$keys] * $pur['xrate']);
            # Update Order items
            $sql = "UPDATE nons_purint_items SET rqty = (rqty + '{$qtys[$keys]}'), accid = '{$stkacc[$keys]}' WHERE id = '{$ids[$keys]}' AND purid='{$purid}' AND div = '" . USER_DIV . "'";
            $rslt = db_exec($sql) or errDie("Unable to insert Order items to Cubit.", SELF);
            # keep records for transactions
            if (isset($totstkamt[$stkacc[$keys]])) {
                $totstkamt[$stkacc[$keys]] += $amt[$keys];
            } else {
                $totstkamt[$stkacc[$keys]] = $amt[$keys];
            }
        }
    }
    /* Transactions */
    /* - Start Hooks - */
    $vatacc = gethook("accnum", "salesacc", "name", "VAT");
    $refnum = getrefnum();
    $sdate = $pur["pdate"];
    //$ddate;
    /* - End Hooks - */
    # record transaction  from data
    foreach ($totstkamt as $stkacc => $wamt) {
        # Debit Stock and Credit Suppliers control
        writetrans($supacc, $stkacc, date("d-m-Y"), $refnum, $wamt, "Non-Stock Purchase No. {$pur['purnum']} Returned to Supplier {$sup['supname']}.");
    }
    db_connect();
    $Sl = "SELECT * FROM vatcodes WHERE id='{$pur['cusid']}'";
    $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 ($retax > 0) {
        writetrans($supacc, $vatacc, date("d-m-Y"), $refnum, $retax, "Returned, Non-Stock Purchase Vat paid on Non-Stock Order No. {$pur['purnum']}.");
    }
    $retot = sprint(array_sum($amt) + $retax);
    vatr($vd['id'], $pur['pdate'], "INPUT", $vd['code'], $refnum, "Returned, Non-Stock Purchase Vat paid on Non-Stock Order No. {$pur['purnum']}.", $retot, $retax);
    $fretot = sprint(array_sum($famt) + array_sum($ftaxes));
    suppledger($sup['supid'], $stkacc, $sdate, $pur['purid'], "Returned, Non-Stock Purchase No. {$pur['purnum']} received.", $retot, 'd');
    db_connect();
    # update the supplier (make balance more)
    $sql = "UPDATE suppliers SET balance = (balance - '{$retot}'), fbalance = (fbalance - '{$fretot}') WHERE supid = '{$sup['supid']}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
    $sql = "INSERT INTO sup_stmnt(supid, edate, cacc, amount, descript,ref,ex,div) VALUES('{$sup['supid']}','{$sdate}', '{$dept['credacc']}', '-{$fretot}','Returned, Non Stock Purchase No. {$pur['purnum']} Received', '{$refnum}', '{$pur['purnum']}','" . USER_DIV . "')";
    $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
    db_connect();
    # make transaction record for age analysis
    $sql = "INSERT INTO suppurch(supid, purid, pdate, fcid, balance, fbalance, div) VALUES('{$sup['supid']}', '{$pur['purnum']}', '{$sdate}', '{$pur['fcid']}', '-{$retot}', '-{$fretot}', '" . USER_DIV . "')";
    $purcRslt = db_exec($sql) or errDie("Unable to update int Orders information in Cubit.", SELF);
    # Commit updating
    pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
    db_conn($prd);
    # check if there are any outstanding items
    $sql = "SELECT * FROM nons_purint_items WHERE purid = '{$purid}' AND (qty - rqty) > '0' AND div = '" . USER_DIV . "'";
    $stkdRslt = db_exec($sql);
    # if none the set to received
    if (pg_numrows($stkdRslt) < 1) {
        # update surch_int(received = 'y')
        $sql = "UPDATE nons_purch_int SET received = 'y' WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
        //$rslt = db_exec($sql) or errDie("Unable to update international Orders in Cubit.",SELF);
    }
    # Update Order on the DB
    $sql = "UPDATE nons_purch_int SET refno = '{$refno}' WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
    //$rslt = db_exec($sql) or errDie("Unable to update Order in Cubit.",SELF);
    /* End Transactions */
    /* Start moving if Order received */
    db_conn($prd);
    # begin updating
    pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
    $sql = "SELECT * FROM nons_purch_int WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
    $purRslt = db_exec($sql) or errDie("Unable to get Order information");
    if (pg_numrows($purRslt) < 1) {
        return "<li>- Order Not Found</li>";
    }
    $pur = pg_fetch_array($purRslt);
    $rdate = date("Y-m-d");
    # copy Order
    db_conn($prd);
    $sql = "INSERT INTO rnons_purch_int(purid, deptid, supid, supplier, supaddr, terms, pdate, ddate, shipchrg, xrate, fcid, curr, currency, shipping, subtot, total, balance, tax, remarks, refno, received, done, div, purnum, rdate)";
    $sql .= " VALUES('{$purid}', '{$pur['deptid']}', '{$pur['supid']}', '{$pur['supplier']}',  '{$pur['supaddr']}', '{$pur['terms']}', '{$pur['pdate']}', '{$pur['ddate']}', '{$pur['shipchrg']}', '{$pur['xrate']}', '{$pur['fcid']}', '{$pur['curr']}', '{$pur['currency']}', '{$pur['shipping']}', '{$pur['subtot']}', '{$pur['total']}', '0', '{$pur['tax']}', '{$pur['remarks']}', '{$pur['refno']}', 'y', 'y', '" . USER_DIV . "', '{$pur['purnum']}', '{$rdate}')";
    $rslt = db_exec($sql) or errDie("Unable to insert Non-Stock Order to Cubit.", SELF);
    db_connect();
    db_conn($prd);
    # get selected stock
    $sql = "SELECT * FROM nons_purint_items WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
    $stktcRslt = db_exec($sql);
    while ($stktc = pg_fetch_array($stktcRslt)) {
        # Insert Order items
        db_conn($prd);
        $sql = "INSERT INTO rnons_purint_items(purid, cod, des, qty, unitcost, cunitcost, duty, dutyp, amt, accid, div) VALUES('{$purid}', '{$stktc['cod']}', '{$stktc['des']}', '{$stktc['qty']}', '{$stktc['unitcost']}', '{$stktc['cunitcost']}', '{$stktc['duty']}', '{$stktc['dutyp']}', '{$stktc['amt']}', '{$stktc['accid']}', '" . USER_DIV . "')";
        $rslt = db_exec($sql) or errDie("Unable to insert Order items to Cubit.", SELF);
    }
    db_connect();
    # Remove the Order from running DB
    $sql = "DELETE FROM nons_purch_int WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
    //$delRslt = db_exec($sql) or errDie("Unable to update int Orders information in Cubit.",SELF);
    # Remove those Order items from running DB
    $sql = "DELETE FROM nons_purint_items WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
    //$delRslt = db_exec($sql) or errDie("Unable to update int Orders information in Cubit.",SELF);
    # Commit updating
    pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
    /* End moving Order received */
    $cc = "<script> CostCenter('dt', 'Returned, International Non-Stock Purchase', '{$pur['pdate']}', 'Returned, Non Stock Purchase No.{$pur['purnum']}', '" . sprint($retot - $retax) . "', ''); </script>";
    // Final Layout
    $write = "{$cc}\n\t<table " . TMPL_tblDflts . ">\n\t\t<tr>\n\t\t\t<th>International Non-Stock Order received</th>\n\t\t</tr>\n\t\t<tr class='" . bg_class() . "'>\n\t\t\t<td>International Non-Stock Order receipt has been recorded.</td>\n\t\t</tr>\n\t</table>\n\t<p>\n\t<table " . TMPL_tblDflts . ">\n\t\t<tr>\n\t\t\t<th>Quick Links</th>\n\t\t</tr>\n\t\t<tr class='" . bg_class() . "'>\n\t\t\t<td><a href='nons-purch-int-view.php'>View International Orders</a></td>\n\t\t</tr>\n\t\t<script>document.write(getQuicklinkSpecial());</script>\n\t</table>";
    return $write;
}
Ejemplo n.º 4
0
function write($_POST)
{
    # Get vars
    extract($_POST);
    if (isset($back)) {
        unset($_POST["back"]);
        return details($_POST);
    }
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($supid, "num", 1, 50, "Invalid Supplier 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[0], $datea[2])) {
            $v->isOk($date, "num", 1, 1, "Invalid date.");
        }
    } else {
        $v->isOk($date, "num", 1, 1, "Invalid date.");
    }
    $v->isOk($chrgvat, "string", 1, 10, "Invalid Charge VAT Option.");
    $v->isOk($vatinc, "string", 1, 10, "Invalid VAT Inclusive Exclusive Option.");
    $v->isOk($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;
    }
    # CHECK IF THIS DATE IS IN THE BLOCKED RANGE
    $blocked_date_from = getCSetting("BLOCKED_FROM");
    $blocked_date_to = getCSetting("BLOCKED_TO");
    if (strtotime($date) >= strtotime($blocked_date_from) and strtotime($date) <= 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 (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 supplier
    db_connect();
    $sql = "SELECT * FROM suppliers WHERE supid = '{$supid}' AND div = '" . USER_DIV . "'";
    $suppRslt = db_exec($sql) or errDie("Unable to access databse.", SELF);
    if (pg_numrows($suppRslt) < 1) {
        return "<li class='err'>Invalid supplier ID, or supplier has been blocked</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);
    }
    $supp['supname'] = remval($supp['supname']);
    #get vat acc ...
    //	$vatacc = gethook("accnum", "salesacc", "name", "VAT","VAT");
    $vatacc = gethook("accnum", "salesacc", "name", "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['credacc'], $date, $refnum, $amount, $details . " - Supplier {$supp['supname']}");
        $tran = "\n\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>{$supp['supno']} - {$supp['supname']}</td>\n\t\t\t</tr>";
        $samount = $amount - $amount * 2;
        $svatamount = $vatamt - $vatamt * 2;
        recordCT(-$amount, $supp['supid'], $date);
        $type = 'c';
        if (isset($chrgvat) and $chrgvat == "yes") {
            writetrans($vatacc, $dept['credacc'], $date, $refnum, $vatamt, "VAT for Transaction: {$refnum} for Supplier : {$supp['supname']}");
            vatr($vd['id'], $date, "INPUT", $vd['code'], $refnum, "VAT for Transaction: {$refnum} for Supplier : {$supp['supname']}", $samount + $svatamount, $svatamount);
        }
        $balamt = sprint($amount + $vatamt);
    } else {
        # Write transaction  (debit debtors control, credit contra account)
        writetrans($dept['credacc'], $accid, $date, $refnum, $amount, $details . " - Supplier {$supp['supname']}");
        $tran = "\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>{$supp['supno']} - {$supp['supname']}</td>\n\t\t\t\t<td>{$acc['topacc']}/{$acc['accnum']} - {$acc['accname']}</td>\n\t\t\t</tr>";
        $samount = $amount;
        $svatamount = $vatamt;
        recordDT($amount, $supp['supid'], $date);
        $type = 'd';
        if (isset($chrgvat) and $chrgvat == "yes") {
            //			writetrans($vatacc, $dept['credacc'], $date, $refnum, $vatamt, "VAT for Transaction: $refnum for Supplier : $supp[supname]");
            writetrans($dept['credacc'], $vatacc, $date, $refnum, $vatamt, "VAT for Transaction: {$refnum} for Supplier : {$supp['supname']}");
            vatr($vd['id'], $date, "INPUT", $vd['code'], $refnum, "VAT for Transaction: {$refnum} for Supplier : {$supp['supname']}", $samount + $svatamount, $svatamount);
        }
        $balamt = sprint($amount - $amount * 2 + ($vatamt - $vatamt * 2));
    }
    db_connect();
    $edate = date("Y-m-d");
    # record the payment on the statement
    $sql = "\n\t\tINSERT INTO sup_stmnt (\n\t\t\tsupid, edate, ref, cacc, descript, amount, div\n\t\t) VALUES (\n\t\t\t'{$supp['supid']}', '{$date}', '0', '{$accid}', '{$details}', '" . sprint($balamt) . "', '" . USER_DIV . "'\n\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 + '{$balamt}') WHERE supid = '{$supp['supid']}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to update supplier in Cubit.", SELF);
    # Ledger Records
    suppledger($supp['supid'], $accid, $date, $refnum, $details, sprint($amount + $vatamt), $type);
    # Commit updates
    pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
    // Start layout
    $write = "\n\t\t<h3>Supplier Journal transaction has been recorded</h3>\n\t\t<table " . TMPL_tblDflts . ">\n\t\t\t<tr>\n\t\t\t\t<td width='50%'><h3>Debit</h3></td>\n\t\t\t\t<td width='50%'><h3>Credit</h3></td>\n\t\t\t</tr>\n\t\t\t{$tran}\n\t\t\t" . TBL_BR . "\n\t\t\t<tr colspan='2'>\n\t\t\t\t<td><h4>Amount</h4></td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td colspan='2'><b>" . CUR . " {$amount}</b></td>\n\t\t\t</tr>\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='" . bg_class() . "'>\n\t\t\t\t<td align='center'><a href='trans-new.php'>Journal Transactions</td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td align='center'><a href='../supp-view.php'>View Suppliers</a></td>\n\t\t\t</tr>\n\t\t\t<script>document.write(getQuicklinkSpecial());</script>\n\t\t</table>";
    return $write;
}
function bwrite($_POST)
{
    extract($_POST);
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($purid, "num", 1, 20, "Invalid Order number.");
    $v->isOk($prd, "num", 1, 20, "Invalid period Database number.");
    $v->isOk($remarks, "string", 0, 255, "Invalid Remarks.");
    $v->isOk($refno, "string", 0, 255, "Invalid Delivery Reference No.");
    $v->isOk($shipchrg, "float", 0, 20, "Invalid Delivery Charges.");
    $pdate = $p_year . "-" . $p_month . "-" . $p_day;
    if (!checkdate($p_month, $p_day, $p_year)) {
        $v->isOk($date, "num", 1, 1, "Invalid Date.");
    }
    # used to generate errors
    $error = "asa@";
    # check quantities
    if (isset($qtys)) {
        foreach ($qtys as $keys => $qty) {
            $v->isOk($qty, "num", 1, 10, "Invalid Quantity for product number : <b>" . ($keys + 1) . "</b>");
            if ($qty > $qts[$keys]) {
                $v->isOk($qty, "num", 0, 0, "Error : Quantity for product number : <b>" . ($keys + 1) . "</b> is more that Qty Orderd");
            }
            $v->isOk($unitcost[$keys], "float", 1, 20, "Invalid Unit Price for product number : <b>" . ($keys + 1) . "</b>.");
            if ($qty < 1) {
                $v->isOk($qty, "num", 0, 0, "Error : Item Quantity must be at least one. Product number : <b>" . ($keys + 1) . "</b>");
            }
        }
    }
    # display errors, if any
    $err = "";
    if ($v->isError()) {
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $err .= "<li class='err'>" . $e["msg"] . "</li>";
        }
        return details($_POST, $err);
    }
    # Get Order info
    db_conn($prd);
    $sql = "SELECT * FROM nons_purchases WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
    $purRslt = db_exec($sql) or errDie("Unable to get Order information");
    if (pg_numrows($purRslt) < 1) {
        return "<li>- Order Not Found</li>";
    }
    $pur = pg_fetch_array($purRslt);
    # Get selected supplier info
    db_connect();
    if ($pur['ctyp'] == 's') {
        $supid = $pur['typeid'];
        $sql = "SELECT * FROM suppliers WHERE supid = '{$supid}' AND div = '" . USER_DIV . "'";
        $supRslt = db_exec($sql) or errDie("Unable to get supplier");
        if (pg_numrows($supRslt) < 1) {
            $error = "<li class='err'> Supplier not Found.</li>";
            $confirm .= "{$error}<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
            return $confirm;
        } else {
            $sup = pg_fetch_array($supRslt);
            $pur['supplier'] = $sup['supname'];
            $pur['supaddr'] = $sup['supaddr'];
            # Get department info
            db_conn("exten");
            $sql = "SELECT * FROM departments WHERE deptid = '{$sup['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);
            }
            $supacc = $dept['credacc'];
        }
    } elseif ($pur['ctyp'] == 'c') {
        $deptid = $pur['typeid'];
        db_conn("exten");
        $sql = "SELECT * FROM departments WHERE deptid = '{$deptid}'";
        $deptRslt = db_exec($sql) or errDie("Unable to view customers");
        if (pg_numrows($deptRslt) < 1) {
            $error = "<li class='err'> Department not Found.</li>";
            $confirm .= "{$error}<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
            return $confirm;
        } else {
            $dept = pg_fetch_array($deptRslt);
            $supacc = $dept['pca'];
        }
    }
    # Insert Order to DB
    db_connect();
    # begin updating
    pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
    if (isset($qtys)) {
        # amount of stock in
        $totstkamt = array();
        $resub = 0;
        # Get subtotal
        foreach ($qtys as $keys => $value) {
            # Skip zeros
            if ($qtys[$keys] < 1) {
                continue;
            }
            $amt[$keys] = $qtys[$keys] * $unitcost[$keys];
        }
        $SUBTOTAL = array_sum($amt);
        $revat = 0;
        foreach ($qtys as $keys => $value) {
            # Get selected stock line
            $sql = "SELECT * FROM nons_pur_items WHERE id = '{$ids[$keys]}' AND purid = '{$purid}' AND div = '" . USER_DIV . "'";
            $stkdRslt = db_exec($sql);
            $stkd = pg_fetch_array($stkdRslt);
            # Calculate cost amount bought
            $amt[$keys] = $qtys[$keys] * $unitcost[$keys];
            /* delivery charge */
            # Calculate percentage from subtotal
            $perc[$keys] = $amt[$keys] / $SUBTOTAL * 100;
            # Get percentage from shipping charges
            $shipc[$keys] = $perc[$keys] / 100 * $shipchrg;
            # add delivery charges
            $amt[$keys] += $shipc[$keys];
            /* end delivery charge */
            # the subtotal + delivery charges
            $resub += $amt[$keys];
            # calculate vat
            $svat[$keys] = svat($amt[$keys], $stkd['amt'], $stkd['svat']);
            # received vat
            $revat += $svat[$keys];
            # make amount vat free
            if ($pur['vatinc'] == "yes") {
                $amt[$keys] = $amt[$keys] - $svat[$keys];
            }
            # Update Order items
            $sql = "\n\t\t\t\t\tUPDATE nons_pur_items \n\t\t\t\t\tSET rqty = (rqty + '{$qtys[$keys]}'), accid = '{$stkacc[$keys]}' \n\t\t\t\t\tWHERE id = '{$ids[$keys]}' AND purid='{$purid}' AND div = '" . USER_DIV . "'";
            $rslt = db_exec($sql) or errDie("Unable to insert Order items to Cubit.", SELF);
            # keep records for transactions
            if (isset($totstkamt[$stkacc[$keys]])) {
                $totstkamt[$stkacc[$keys]] += $amt[$keys];
            } else {
                $totstkamt[$stkacc[$keys]] = $amt[$keys];
            }
            # check if there are any outstanding items
            $sql = "SELECT * FROM nons_pur_items WHERE purid = '{$purid}' AND (qty - rqty) > '0' AND div = '" . USER_DIV . "'";
            $stkdRslt = db_exec($sql);
            # if none the set to received
            if (pg_numrows($stkdRslt) < 1) {
                # update surch_int(received = 'y')
                $sql = "\n\t\t\t\t\t\tUPDATE nons_purchases \n\t\t\t\t\t\tSET received = 'y', supplier = '{$pur['supplier']}', supaddr = '{$pur['supaddr']}' \n\t\t\t\t\t\tWHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
                $rslt = db_exec($sql) or errDie("Unable to update international Orders in Cubit.", SELF);
            }
        }
    }
    # Update Order on the DB
    if ($pur['part'] == 'y') {
        # Update Order on the DB
        $sql = "\n\t\t\t\tUPDATE nons_purchases \n\t\t\t\tSET ctyp = '{$ctyp}', typeid = '{$typeid}', refno = '{$refno}', remarks = '{$remarks}' \n\t\t\t\tWHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update Order in Cubit.", SELF);
    } else {
        # Update Order on the DB
        $sql = "\n\t\t\t\tUPDATE nons_purchases \n\t\t\t\tSET ctyp = '{$ctyp}', typeid = '{$typeid}', refno = '{$refno}', remarks = '{$remarks}' \n\t\t\t\tWHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update Order in Cubit.", SELF);
    }
    /* Transactions */
    $refnum = getrefnum(date("d-m-Y"));
    /* - Start Hooks - */
    $vatacc = gethook("accnum", "salesacc", "name", "VAT");
    /* - End Hooks - */
    $detadd = "";
    if (isset($supid)) {
        $detadd = " from Supplier {$sup['supname']}";
    }
    $sdate = $pur['pdate'];
    $tpp = 0;
    $ccamt = 0;
    # record transaction  from data
    foreach ($totstkamt as $stkacc => $wamt) {
        # Debit Stock and Credit Suppliers control
        writetrans($stkacc, $supacc, date("d-m-Y"), $refnum, $wamt, "Non-Stock Purchase No. {$pur['purnum']} Received {$detadd}.");
        pettyrec($supacc, $sdate, "ct", "Non-Stock Purchase No. {$pur['purnum']} Received {$detadd}.", $wamt, "Cash Order");
    }
    # vat
    $vatamt = $revat;
    # Add vat if not included
    if ($pur['vatinc'] == 'no') {
        $retot = $resub + $vatamt;
    } elseif ($pur['vatinc'] == "novat") {
        $retot = $resub;
        $vatamt = 0;
    } else {
        $retot = $resub;
    }
    if (isset($supid)) {
        # Ledger Records
        $DAte = $pur['pdate'];
        suppledger($sup['supid'], $stkacc, $DAte, $pur['purid'], "Non-Stock Purchase No. {$pur['purnum']} received.", $retot, 'c');
    }
    if ($vatamt != 0) {
        # Debit bank and credit the account involved
        writetrans($vatacc, $supacc, date("d-m-Y"), $refnum, $vatamt, "Non-Stock Purchase VAT paid on Non-Stock Order No. {$pur['purnum']} {$detadd}.");
        pettyrec($supacc, $sdate, "ct", "Non-Stock Purchase No. {$pur['purnum']} Received {$detadd}.", $vatamt, "Cash Order VAT");
        # Record the payment on the statement
        db_connect();
        $sdate = $pur['pdate'];
    }
    if (isset($supid)) {
        $DAte = $pur['pdate'];
        db_connect();
        # update the supplier (make balance more)
        $sql = "UPDATE suppliers SET balance = (balance + '{$retot}') WHERE supid = '{$sup['supid']}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
        $sql = "\n\t\t\t\tINSERT INTO sup_stmnt (\n\t\t\t\t\tsupid, edate, cacc, amount, descript, ref, ex, div\n\t\t\t\t) VALUES (\n\t\t\t\t\t'{$sup['supid']}','{$DAte}', '{$dept['credacc']}', '{$retot}', 'Non Stock Purchase No. {$pur['purnum']} Received', '{$refnum}', '{$pur['purnum']}', '" . USER_DIV . "'\n\t\t\t\t)";
        $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
        db_connect();
        # update the supplier age analysis (make balance less)
        /* Make transaction record for age analysis */
        $sql = "\n\t\t\t\tINSERT INTO suppurch (\n\t\t\t\t\tsupid, purid, pdate, balance, div\n\t\t\t\t) VALUES (\n\t\t\t\t\t'{$sup['supid']}', '{$pur['purnum']}', '{$DAte}', '{$retot}', '" . USER_DIV . "'\n\t\t\t\t)";
        $purcRslt = db_exec($sql) or errDie("Unable to update int Orders information in Cubit.", SELF);
    }
    # commit updating
    pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
    /* End Transactions */
    /* Start moving if Order received */
    # Get Order info
    db_connect();
    $sql = "SELECT * FROM nons_purchases WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
    $purRslt = db_exec($sql) or errDie("Unable to get Order information");
    if (pg_numrows($purRslt) < 1) {
        return "<li>- Order Not Found</li>";
    }
    $pur = pg_fetch_array($purRslt);
    if ($pur['received'] == "y") {
        # copy Order
        db_conn($pur['prd']);
        $sql = "\n\t\t\t\tINSERT INTO nons_purchases (\n\t\t\t\t\tpurid, deptid, supplier, supaddr, terms, pdate, ddate, \n\t\t\t\t\tshipchrg, shipping, subtot, total, balance, vatinc, vat, \n\t\t\t\t\tremarks, refno, received, done, ctyp, typeid, div, purnum\n\t\t\t\t) VALUES (\n\t\t\t\t\t'{$purid}', '{$pur['deptid']}', '{$pur['supplier']}',  '{$pur['supaddr']}', '{$pur['terms']}', '{$pur['pdate']}', '{$pur['ddate']}', \n\t\t\t\t\t'{$pur['shipchrg']}', '{$pur['shipping']}', '{$pur['subtot']}', '{$pur['total']}', '0', '{$pur['vatinc']}', '{$pur['vat']}', \n\t\t\t\t\t'{$pur['remarks']}', '{$pur['refno']}', 'y', 'y', '{$pur['ctyp']}', '{$pur['typeid']}', '" . USER_DIV . "', '{$pur['purnum']}'\n\t\t\t\t)";
        $rslt = db_exec($sql) or errDie("Unable to insert Non-Stock Order to Cubit.", SELF);
        db_connect();
        # Get selected stock
        $sql = "SELECT * FROM nons_pur_items WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
        $stktcRslt = db_exec($sql);
        while ($stktc = pg_fetch_array($stktcRslt)) {
            # Insert Order items
            db_conn($pur['prd']);
            $sql = "\n\t\t\t\t\tINSERT INTO nons_pur_items (\n\t\t\t\t\t\tpurid, cod, des, qty, unitcost, amt, \n\t\t\t\t\t\tsvat, ddate, accid, div\n\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t'{$purid}', '{$stktc['cod']}', '{$stktc['des']}', '{$stktc['qty']}', '{$stktc['unitcost']}', '{$stktc['amt']}', \n\t\t\t\t\t\t'{$stktc['svat']}', '{$stktc['ddate']}', '{$stktc['accid']}', '" . USER_DIV . "'\n\t\t\t\t\t)";
            $rslt = db_exec($sql) or errDie("Unable to insert Order items to Cubit.", SELF);
        }
        db_connect();
        # Remove the Order from running DB
        $sql = "DELETE FROM nons_purchases WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
        $delRslt = db_exec($sql) or errDie("Unable to update int Orders information in Cubit.", SELF);
        # Remove those Order items from running DB
        $sql = "DELETE FROM nons_pur_items WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
        $delRslt = db_exec($sql) or errDie("Unable to update int Orders information in Cubit.", SELF);
    }
    /* End moving Order received */
    $cc = "<script> CostCenter('ct', 'Non-Stock Purchase', '{$pur['pdate']}', 'Non Stock Purchase No.{$pur['purnum']}', '" . ($retot - $vatamt) . "', ''); </script>";
    // Final Layout
    $write = "\n\t\t{$cc}\n\t\t<table " . TMPL_tblDflts . ">\n\t\t\t<tr>\n\t\t\t\t<th>Non-Stock Order received</th>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Non-Stock Order receipt has been recorded.</td>\n\t\t\t</tr>\n\t\t</table>\n\t\t<p>\n\t\t<table " . TMPL_tblDflts . ">\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='" . bg_class() . "'>\n\t\t\t\t<td><a href='nons-purchase-view.php'>View Orders</a></td>\n\t\t\t</tr>\n\t\t\t<script>document.write(getQuicklinkSpecial());</script>\n\t\t</table>";
    return $write;
}
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($rate, "float", 1, 10, "Invalid exchange rate.");
    $v->isOk($supid, "num", 1, 10, "Invalid supplier number.");
    $v->isOk($out1, "float", 0, 10, "Invalid paid amount(current).");
    $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"] . "</li>";
        }
        $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) {
        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);
    db_connect();
    # Supplier name
    $sql = "SELECT * FROM suppliers WHERE supid = '{$supid}' AND div = '" . USER_DIV . "'";
    $supRslt = db_exec($sql);
    $sup = pg_fetch_array($supRslt);
    db_conn("exten");
    # get debtors control account
    $sql = "SELECT credacc FROM departments WHERE deptid ='{$sup['deptid']}' AND div = '" . USER_DIV . "'";
    $deptRslt = db_exec($sql);
    $dept = pg_fetch_array($deptRslt);
    # Update xrate
    xrate_update($sup['fcid'], $rate, "suppurch", "id");
    sup_xrate_update($sup['fcid'], $rate);
    bank_xrate_update($sup['fcid'], $rate);
    $lamt = sprint($amt * $rate);
    # date format
    $sdate = explode("-", $date);
    $sdate = $sdate[2] . "-" . $sdate[1] . "-" . $sdate[0];
    $cheqnum = 0 + $cheqnum;
    $pay = "";
    $accdate = $sdate;
    # Paid invoices
    $invidsers = "";
    $rinvids = "";
    $amounts = "";
    $invprds = "";
    db_connect();
    if ($all == 0) {
        $ids = "";
        $purids = "";
        $fpamounts = "";
        $pamounts = "";
        $pdates = "";
        # Begin updates
        # pglib_transaction ("BEGIN") or errDie("Unable to start a database transaction.",SELF);
        if (isset($invids)) {
            foreach ($invids as $key => $value) {
                $lpaidamt[$key] = sprint($paidamt[$key] * $rate);
                #debt invoice info
                $sql = "SELECT id,pdate FROM suppurch WHERE purid ='{$invids[$key]}' AND div = '" . USER_DIV . "' ORDER BY fbalance LIMIT 1";
                $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>";
                }
                $pur = pg_fetch_array($invRslt);
                # reduce the money that has been paid
                $sql = "UPDATE suppurch SET balance = (balance - '{$lpaidamt[$key]}'::numeric(13,2)), fbalance = (fbalance - '{$paidamt[$key]}'::numeric(13,2)) WHERE purid = '{$invids[$key]}' AND div = '" . USER_DIV . "' AND id='{$pur['id']}'";
                $payRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
                $ids .= "|{$pur['id']}";
                $purids .= "|{$invids[$key]}";
                $fpamounts .= "|{$paidamt[$key]}";
                $pamounts .= "|{$lpaidamt[$key]}";
                $pdates .= "|{$pur['pdate']}";
            }
        }
        $samount = $amt - $amt * 2;
        if ($out > 0) {
            recordDT($out, $sup['supid']);
        }
        $Sl = "INSERT INTO sup_stmnt(supid, amount, edate, descript,ref,cacc, div) VALUES('{$sup['supid']}','{$samount}','{$sdate}', 'Payment','{$cheqnum}','{$bank['accnum']}', '" . USER_DIV . "')";
        $Rs = db_exec($Sl) or errDie("Unable to insert statement record in Cubit.", SELF);
        suppledger($sup['supid'], $bank['accnum'], $sdate, $cheqnum, "Payment for purchases", $lamt, "d");
        db_connect();
        # Update the supplier (make fbalance less)
        $sql = "UPDATE suppliers SET balance = (balance - '{$lamt}'::numeric(13,2)), fbalance = (fbalance - '{$amt}'::numeric(13,2)) WHERE supid = '{$sup['supid']}'";
        $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, supid, ids, purids, pamounts, pdates, div) VALUES ('$bankid', 'withdrawal', '$sdate', '$sup[supno] - $sup[supname]', 'Supplier Payment to $sup[supname]', '$cheqnum', '$lamt', 'no', '$dept[credacc]', '$sup[supid]', '$ids', '$purids', '$pamounts', '$pdates', '".USER_DIV."')";
        //2 $sql = "INSERT INTO cashbook(bankid, trantype, date, name, descript, cheqnum, amount, famount, banked, accinv, supid, ids, purids, pamounts, pdates, div) VALUES ('$bankid', 'withdrawal', '$sdate', '$sup[supno] - $sup[supname]', 'Supplier Payment to $sup[supname]', '$cheqnum', '$lamt', '$amt', 'no', '$dept[credacc]', '$sup[supid]', '$ids', '$purids', '$pamounts', '$pdates', '".USER_DIV."')";
        $sql = "INSERT INTO cashbook(bankid, trantype, date, name, descript, cheqnum, amount, famount, banked, accinv, supid, ids, purids, pamounts, fpamounts, pdates, fcid, currency, location, div) VALUES ('{$bankid}', 'withdrawal', '{$sdate}', '{$sup['supno']} - {$sup['supname']}', 'Supplier Payment to {$sup['supname']}', '{$cheqnum}', '{$lamt}', '{$amt}', 'no', '{$dept['credacc']}', '{$sup['supid']}', '{$ids}', '{$purids}', '{$pamounts}', '{$fpamounts}', '{$pdates}', '{$sup['fcid']}', '{$sup['currency']}', '{$sup['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.");
        if (pg_numrows($Rx) < 1) {
            return "Invalid bank acc.";
        }
        $link = pg_fetch_array($Rx);
        writetrans($dept['credacc'], $link['accnum'], $accdate, $refnum, $lamt, "Supplier Payment to {$sup['supname']}");
        db_conn('cubit');
        # Commit updates
        # pglib_transaction ("COMMIT") or errDie("Unable to commit a database transaction.",SELF);
    }
    if ($all == 1) {
        $ids = "";
        $purids = "";
        $fpamounts = "";
        $pamounts = "";
        $pdates = "";
        # Begin updates
        //pglib_transaction ("BEGIN") or errDie("Unable to start a database transaction.",SELF);
        if (isset($invids)) {
            foreach ($invids as $key => $value) {
                $lpaidamt[$key] = sprint($paidamt[$key] * $rate);
                # Get debt invoice info
                $sql = "SELECT id,pdate FROM suppurch WHERE purid ='{$invids[$key]}' AND div = '" . USER_DIV . "' ORDER BY fbalance LIMIT 1";
                $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>";
                }
                $pur = pg_fetch_array($invRslt);
                # reduce the money that has been paid
                $sql = "UPDATE suppurch SET balance = (balance - '{$lpaidamt[$key]}'::numeric(13,2)), fbalance = (fbalance - {$paidamt[$key]}::numeric(13,2)) WHERE purid = '{$invids[$key]}' AND div = '" . USER_DIV . "' AND id='{$pur['id']}'";
                $payRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
                $ids .= "|{$pur['id']}";
                $purids .= "|{$invids[$key]}";
                $fpamounts .= "|{$paidamt[$key]}";
                $pamounts .= "|{$lpaidamt[$key]}";
                $pdates .= "|{$pur['pdate']}";
            }
        }
        $samount = $amt - $amt * 2;
        if ($out1 > 0) {
            recordDT($out1, $sup['supid']);
        }
        if ($out2 > 0) {
            recordDT($out2, $sup['supid']);
        }
        if ($out3 > 0) {
            recordDT($out3, $sup['supid']);
        }
        if ($out4 > 0) {
            recordDT($out4, $sup['supid']);
        }
        if ($out5 > 0) {
            recordDT($out5, $sup['supid']);
        }
        $Sl = "INSERT INTO sup_stmnt(supid, amount, edate, descript,ref,cacc, div) VALUES('{$sup['supid']}','{$samount}','{$sdate}', 'Payment','{$cheqnum}','{$bank['accnum']}', '" . USER_DIV . "')";
        $Rs = db_exec($Sl) or errDie("Unable to insert statement record in Cubit.", SELF);
        # Update the supplier (make fbalance less)
        $sql = "UPDATE suppliers SET balance = (balance - '{$lamt}'::numeric(13,2)), fbalance = (fbalance - '{$amt}'::numeric(13,2)) WHERE supid = '{$sup['supid']}' 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, supid, ids, purids, pamounts, pdates, div) VALUES ('$bankid', 'withdrawal', '$sdate', '$sup[supno] - $sup[supname]', 'Supplier Payment to $sup[supname]', '$cheqnum', '$lamt', 'no', '$dept[credacc]', '$sup[supid]', '$ids', '$purids', '$pamounts', '$pdates', '".USER_DIV."')";
        //2 $sql = "INSERT INTO cashbook(bankid, trantype, date, name, descript, cheqnum, amount, famount, banked, accinv, supid, ids, purids, pamounts, pdates, div) VALUES ('$bankid', 'withdrawal', '$sdate', '$sup[supno] - $sup[supname]', 'Supplier Payment to $sup[supname]', '$cheqnum', '$lamt', '$amt', 'no', '$dept[credacc]', '$sup[supid]', '$ids', '$purids', '$pamounts', '$pdates', '".USER_DIV."')";
        $sql = "INSERT INTO cashbook(bankid, trantype, date, name, descript, cheqnum, amount, famount, banked, accinv, supid, ids, purids, pamounts, fpamounts, pdates, fcid, currency, location, div) VALUES ('{$bankid}', 'withdrawal', '{$sdate}', '{$sup['supno']} - {$sup['supname']}', 'Supplier Payment to {$sup['supname']}', '{$cheqnum}', '{$lamt}', '{$amt}', 'no', '{$dept['credacc']}', '{$sup['supid']}', '{$ids}', '{$purids}', '{$pamounts}', '{$fpamounts}', '{$pdates}', '{$sup['fcid']}', '{$sup['currency']}', '{$sup['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.");
        if (pg_numrows($Rx) < 1) {
            return "Invalid bank acc.";
        }
        $link = pg_fetch_array($Rx);
        writetrans($dept['credacc'], $link['accnum'], $accdate, $refnum, $lamt, "Supplier Payment to {$sup['supname']}");
        db_conn('cubit');
        # Commit updates
        //pglib_transaction ("COMMIT") or errDie("Unable to commit a database transaction.",SELF);
        suppledger($sup['supid'], $bank['accnum'], $sdate, $cheqnum, "Payment to Supplier", $lamt, "d");
        db_connect();
    }
    if ($all == 2) {
        $ids = "";
        $purids = "";
        $fpamounts = "";
        $pamounts = "";
        $pdates = "";
        # Begin updates
        #pglib_transaction ("BEGIN") or errDie("Unable to start a database transaction.",SELF);
        if (isset($invids)) {
            foreach ($invids as $key => $value) {
                $lpaidamt[$key] = sprint($paidamt[$key] * $rate);
                # Get debt invoice info
                $sql = "SELECT id,pdate FROM suppurch WHERE purid ='{$invids[$key]}' AND div = '" . USER_DIV . "' ORDER BY fbalance LIMIT 1";
                $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.";
                }
                $pur = pg_fetch_array($invRslt);
                # reduce the money that has been paid
                $sql = "UPDATE suppurch SET balance = (balance - '{$lpaidamt[$key]}'::numeric(13,2)), fbalance = (fbalance - '{$paidamt[$key]}'::numeric(13,2)) WHERE purid = '{$invids[$key]}' AND div = '" . USER_DIV . "' AND id='{$pur['id']}'";
                $payRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
                $samount = $paidamt[$key] - $paidamt[$key] * 2;
                $Sl = "INSERT INTO sup_stmnt(supid, amount, edate, descript,ref,cacc,div) VALUES('{$sup['supid']}','{$samount}','{$sdate}', 'Payment - Purchase: {$invids[$key]}','{$cheqnum}','{$bank['accnum']}', '" . USER_DIV . "')";
                $Rs = db_exec($Sl) or errDie("Unable to insert statement record in Cubit.", SELF);
                suppledger($sup['supid'], $bank['accnum'], $sdate, $invids[$key], "Payment for Purchase No. {$invids[$key]}", $paidamt[$key], "d");
                db_connect();
                # record the payment on the statement
                $ids .= "|{$pur['id']}";
                $purids .= "|{$invids[$key]}";
                $fpamounts .= "|{$paidamt[$key]}";
                $pamounts .= "|{$lpaidamt[$key]}";
                $pdates .= "|{$pur['pdate']}";
            }
        }
        $samount = $amt - $amt * 2;
        # Update the supplier (make fbalance less)
        $sql = "UPDATE suppliers SET balance = (balance - '{$lamt}'::numeric(13,2)), fbalance = (fbalance - '{$amt}'::numeric(13,2)) WHERE supid = '{$sup['supid']}' 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, famount, banked, accinv, supid, ids, purids, pamounts, fpamounts, pdates, fcid, currency, location, div) VALUES ('{$bankid}', 'withdrawal', '{$sdate}', '{$sup['supno']} - {$sup['supname']}', 'Supplier Payment to {$sup['supname']}', '{$cheqnum}', '{$lamt}', '{$amt}', 'no', '{$dept['credacc']}', '{$sup['supid']}', '{$ids}', '{$purids}', '{$pamounts}', '{$fpamounts}', '{$pdates}', '{$sup['fcid']}', '{$sup['currency']}', '{$sup['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.");
        if (pg_numrows($Rx) < 1) {
            return "Invalid bank acc.";
        }
        $link = pg_fetch_array($Rx);
        writetrans($dept['credacc'], $link['accnum'], $accdate, $refnum, $lamt, "Supplier Payment to {$sup['supname']}");
        db_conn('cubit');
        # Commit updates
        #pglib_transaction ("COMMIT") or errDie("Unable to commit a database transaction.",SELF);
    }
    db_conn('cubit');
    $Sl = "DELETE FROM suppurch WHERE fbalance = 0::numeric(13,2) AND balance = 0::numeric(13,2)";
    $Rx = db_exec($Sl);
    # status report
    $write = "\n\t<table " . TMPL_tblDflts . " width='100%'>\n\t\t<tr>\n\t\t\t<th>International Bank Payment</th>\n\t\t</tr>\n\t\t<tr class='" . bg_class() . "'>\n\t\t\t<td>International Bank Payment added to cash book.</td>\n\t\t</tr>\n\t</table>";
    # main table (layout with menu)
    $OUTPUT = "<center>\n\t<table width='90%'>\n\t\t<tr valign='top'>\n\t\t\t<td width='50%'>{$write}</td>\n\t\t\t<td align='center'>\n\t\t\t\t<table " . TMPL_tblDflts . " width='80%'>\n\t\t\t\t\t<tr>\n\t\t\t\t\t\t<th>Quick Links</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><a href='bank-pay-supp.php'>Add supplier payment</a></td>\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><a href='bank-pay-add.php'>Add Bank Payment</a></td>\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><a href='bank-recpt-add.php'>Add Bank Receipt</a></td>\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><a href='cashbook-view.php'>View Cash Book</a></td>\n\t\t\t\t\t</tr>\n\t\t\t\t</table>\n\t\t\t</td>\n\t\t</tr>\n\t</table>";
    return $OUTPUT;
}
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;
}
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($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.");
    $v->isOk($supid, "num", 1, 20, "Invalid Supplier 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;
    }
    # CHECK IF THIS DATE IS IN THE BLOCKED RANGE
    $blocked_date_from = getCSetting("BLOCKED_FROM");
    $blocked_date_to = getCSetting("BLOCKED_TO");
    if (strtotime($date) >= strtotime($blocked_date_from) and strtotime($date) <= 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>";
    }
    # Date format
    $date = explode("-", $date);
    $date = $date[2] . "-" . $date[1] . "-" . $date[0];
    $cheqnum = 0 + $cheqnum;
    # Get bank account name
    db_connect();
    $sql = "SELECT accname,bankname FROM bankacct WHERE bankid = '{$bankid}' AND div = '" . USER_DIV . "'";
    $bankRslt = db_exec($sql);
    $bank = pg_fetch_array($bankRslt);
    # Get account name
    $supRslt = get("cubit", "*", "suppliers", "supid", $supid);
    $sup = pg_fetch_array($supRslt);
    $bankaccid = getbankaccid($bankid);
    db_conn("exten");
    # Get debtors control account
    $sql = "SELECT credacc FROM departments WHERE deptid ='{$sup['deptid']}' AND div = '" . USER_DIV . "'";
    $deptRslt = db_exec($sql);
    $dept = pg_fetch_array($deptRslt);
    pglib_transaction("BEGIN");
    db_connect();
    $Sl = "INSERT INTO sup_stmnt(supid, amount, edate, descript,ref,cacc, div) VALUES('{$supid}','{$amount}','{$date}', '{$descript}','{$cheqnum}','{$bankaccid}', '" . 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 + '{$amount}') WHERE supid = '{$supid}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
    suppCT($amount, $supid, $date);
    # record the payment record
    db_connect();
    $sql = "INSERT INTO cashbook(bankid, trantype, date, name, descript, cheqnum, amount, banked, accinv, suprec, reference, div) VALUES ('{$bankid}', 'deposit', '{$date}', '{$sup['supno']} - {$sup['supname']}', '{$descript}', '{$cheqnum}', '{$amount}', 'no', '{$dept['credacc']}', '{$supid}', '{$reference}', '" . USER_DIV . "')";
    $Rslt = db_exec($sql) or errDie("Unable to add bank payment to database.", SELF);
    $refnum = getrefnum();
    # DT(account involved), CT(bank)
    writetrans($bankaccid, $dept['credacc'], $date, $refnum, $amount, $descript);
    suppledger($supid, $bankaccid, $date, 0, $descript, $amount, 'c');
    pglib_transaction("COMMIT");
    # 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 Receipt</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>Bank Receipt from supplier : {$sup['supname']} added to cash book.</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='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>";
    return $OUTPUT;
}
function write($_POST)
{
    # get vars
    extract($_POST);
    if (isset($back)) {
        unset($_POST["back"]);
        return alloc($_POST);
    }
    $all = $all_val;
    $OUT1 = $out1_val;
    $OUT2 = $out2_val;
    $OUT3 = $out3_val;
    $OUT4 = $out4_val;
    $OUT5 = $out5_val;
    # 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($reference, "string", 0, 50, "Invalid Reference Name/Number.");
    $v->isOk($cheqnum, "num", 0, 30, "Invalid Cheque number.");
    $v->isOk($amt, "float", 1, 10, "Invalid amount.");
    $v->isOk($overpay, "float", 1, 15, "Invalid unallocated payment amount.");
    $v->isOk($setamt, "float", 1, 40, "Invalid Settlement Discount Amount.");
    $v->isOk($setvat, "string", 1, 10, "Invalid Settlement VAT Option.");
    $v->isOk($setvatcode, "string", 1, 40, "Invalid Settlement VAT code");
    $v->isOk($supid, "num", 1, 10, "Invalid supplier number.");
    $v->isOk($out1, "float", 0, 10, "Invalid paid amount(current).");
    $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"] . "</li>";
        }
        $confirm .= "<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        die("{$confirm}");
    }
    # get hook account number
    core_connect();
    $sql = "SELECT * FROM bankacc WHERE accid = '{$bankid}' AND div = '" . USER_DIV . "' AND accid!=0";
    $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();
    # Supplier name
    $sql = "SELECT supid,supno,supname,deptid FROM suppliers WHERE supid = '{$supid}' AND div = '" . USER_DIV . "'";
    $supRslt = db_exec($sql);
    $sup = pg_fetch_array($supRslt);
    db_conn("exten");
    # get debtors control account
    $sql = "SELECT credacc FROM departments WHERE deptid ='{$sup['deptid']}' AND div = '" . USER_DIV . "'";
    $deptRslt = db_exec($sql);
    $dept = pg_fetch_array($deptRslt);
    # date format
    $sdate = $date;
    $cheqnum = 0 + $cheqnum;
    $pay = "";
    $accdate = $sdate;
    # Paid invoices
    $invidsers = "";
    $rinvids = "";
    $amounts = "";
    $invprds = "";
    if ($overpay < 0) {
        $overpay = 0.0;
    }
    $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);
    $link['accnum'] = $bank['accnum'];
    pglib_transaction("BEGIN");
    db_conn("cubit");
    #record this payment for the print script ...
    $save_sql = "\n\t\tINSERT INTO supp_payment_print (\n\t\t\tsupid, account, pay_date, sdate, refno, \n\t\t\tcheqno, total_amt, set_amt, overpay_amt, descript\n\t\t) VALUES (\n\t\t\t'{$supid}', '{$bankid}', '{$accdate}', 'now', '{$reference}', \n\t\t\t'{$cheqnum}', '{$amt}', '{$setamt}', '{$overpay}', '{$descript}'\n\t\t)";
    $run_save = db_exec($save_sql) or errDie("Unable to record information.");
    $supp_pay_id = pglib_lastid("supp_payment_print", "id");
    if ($all == 2) {
        $ids = "";
        $purids = "";
        $pamounts = "";
        $pdates = "";
        db_conn('cubit');
        # Update the supplier (make balance less)
        $sql = "UPDATE suppliers SET balance = (balance - '{$amt}'::numeric(13,2)) WHERE supid = '{$sup['supid']}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
        # Begin updates
        if (isset($invids)) {
            db_connect();
            foreach ($invids as $key => $value) {
                # Get debt invoice info
                $sql = "SELECT id,pdate FROM suppurch WHERE purid ='{$invids[$key]}' AND div = '" . USER_DIV . "' ORDER BY balance LIMIT 1";
                $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>";
                }
                $pur = pg_fetch_array($invRslt);
                # reduce the money that has been paid
                $sql = "UPDATE suppurch SET balance = (balance - '{$paidamt[$key]}'::numeric(13,2)) WHERE purid = '{$invids[$key]}' AND div = '" . USER_DIV . "' AND id='{$pur['id']}'";
                $payRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
                $samount = $paidamt[$key] - $paidamt[$key] * 2;
                $Sl = "\n\t\t\t\t\t\tINSERT INTO sup_stmnt (\n\t\t\t\t\t\t\tsupid, amount, edate, \n\t\t\t\t\t\t\tdescript, ref, cacc, \n\t\t\t\t\t\t\tdiv\n\t\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t\t'{$sup['supid']}', '{$samount}', '{$sdate}', \n\t\t\t\t\t\t\t'Payment - Purchase: {$invids[$key]}', '{$cheqnum}', '{$bank['accnum']}', \n\t\t\t\t\t\t\t'" . USER_DIV . "'\n\t\t\t\t\t\t)";
                $Rs = db_exec($Sl) or errDie("Unable to insert statement record in Cubit.", SELF);
                #record the settlement discount on the statement
                #we record the total settlement below with a negative (correct?) amount ...
                #why do this here ??? -> so we have individual amount on statement ...
                #rather use this ... but with negative amount ... (fixed)
                if ($stock_setamt[$key] > 0) {
                    db_conn('core');
                    #get settlement accid
                    $get_setacc = "SELECT accid FROM accounts WHERE accname = 'Creditors Settlement Discount'";
                    $run_setacc = db_exec($get_setacc) or errDie("Unable to get settlement account information");
                    $setaccid = pg_fetch_result($run_setacc, 0, 0);
                    db_connect();
                    $sql = "\n\t\t\t\t\t\t\tINSERT INTO sup_stmnt (\n\t\t\t\t\t\t\t\tsupid, amount, edate, \n\t\t\t\t\t\t\t\tdescript, \n\t\t\t\t\t\t\t\tref, cacc, div\n\t\t\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t\t\t'{$sup['supid']}', '" . sprint($stock_setamt[$key] - 2 * $stock_setamt[$key]) . "', '{$sdate}', \n\t\t\t\t\t\t\t\t'Settlement Discount for Invoice (Ref. {$reference}): {$invids[$key]}', \n\t\t\t\t\t\t\t\t'{$cheqnum}','{$setaccid}', '" . USER_DIV . "'\n\t\t\t\t\t\t\t)";
                    $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
                    # reduce the money (settlement) that has been paid
                    $sql = "UPDATE suppurch SET balance = (balance - '{$stock_setamt[$key]}'::numeric(13,2)) WHERE purid = '{$invids[$key]}' AND div = '" . USER_DIV . "' AND id='{$pur['id']}'";
                    $payRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
                    #record settlement discount in supp ledger
                    suppledger($sup['supid'], $setaccid, $sdate, $invids[$key], "Settlement Discount On Payment for Purchase No. {$invids[$key]}", $stock_setamt[$key], "d");
                }
                db_connect();
                # Update the supplier (make balance less)
                $sql = "UPDATE suppliers SET balance = (balance - '{$stock_setamt[$key]}'::numeric(13,2)) WHERE supid = '{$sup['supid']}' AND div = '" . USER_DIV . "'";
                $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
                #record purchase in supp ledger
                suppledger($sup['supid'], $bank['accnum'], $sdate, $invids[$key], "Payment for Purchase No. {$invids[$key]}", $paidamt[$key], "d");
                db_connect();
                # record the payment on the statement
                $ids .= "|{$pur['id']}";
                $purids .= "|{$invids[$key]}";
                $pamounts .= "|{$paidamt[$key]}";
                $pdates .= "|{$pur['pdate']}";
                #record this for printing ...
                $save_sql2 = "\n\t\t\t\t\t\t\tINSERT INTO supp_payment_print_items (\n\t\t\t\t\t\t\t\tpayment_id, supid, purchase, tdate, sdate, \n\t\t\t\t\t\t\t\tpaid_amt, sett_amt\n\t\t\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t\t\t'{$supp_pay_id}', '{$supid}', '{$invids[$key]}', '{$date}', 'now', \n\t\t\t\t\t\t\t\t'{$paidamt[$key]}','{$stock_setamt[$key]}'\n\t\t\t\t\t\t\t)";
                $run_save2 = db_exec($save_sql2) or errDie("Unable to record item information.");
            }
        }
        $samount = $amt - $amt * 2;
        #handle overpay ...
        if ($overpay > 0) {
            $sql = "\n\t\t\t\tINSERT INTO sup_stmnt (\n\t\t\t\t\tsupid, amount, edate, \n\t\t\t\t\tdescript, \n\t\t\t\t\tref, cacc, div\n\t\t\t\t) VALUES (\n\t\t\t\t\t'{$sup['supid']}', '-{$overpay}', '{$sdate}', \n\t\t\t\t\t'Payment  (Ref. {$reference})', \n\t\t\t\t\t'{$cheqnum}','{$bank['accnum']}', '" . USER_DIV . "'\n\t\t\t\t)";
            $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
            $sql = "UPDATE suppliers SET balance = (balance - '{$overpay}'::numeric(13,2)) WHERE supid = '{$sup['supid']}' AND div = '" . USER_DIV . "'";
            $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
            #record general transaction in supp ledger
            suppledger($sup['supid'], $bank['accnum'], $sdate, "General Transaction", "Unallocated Payment for Supplier", $overpay, "d");
            db_connect();
            $sql = "\n\t\t\t\tINSERT INTO suppurch (\n\t\t\t\t\tsupid, purid, pdate, balance, div\n\t\t\t\t) VALUES (\n\t\t\t\t\t'{$sup['supid']}', '0', '{$date}', '-{$overpay}', '" . USER_DIV . "'\n\t\t\t\t)";
            $purcRslt = db_exec($sql) or errDie("Unable to update int purchases information in Cubit.", SELF);
        }
        db_conn('cubit');
        # Record the payment record
        $sql = "\n\t\t\tINSERT INTO cashbook (\n\t\t\t\tbankid, trantype, date, name, \n\t\t\t\tdescript, cheqnum, amount, banked, accinv, \n\t\t\t\tsupid, ids, purids, pamounts, pdates, reference, \n\t\t\t\tdiv\n\t\t\t) VALUES (\n\t\t\t\t'{$bankid}', 'withdrawal', '{$sdate}', '{$sup['supno']} - {$sup['supname']}', \n\t\t\t\t'Supplier Payment to {$sup['supname']}', '{$cheqnum}', '" . sprint($amt + $overpay) . "', 'no', '{$dept['credacc']}', \n\t\t\t\t'{$sup['supid']}', '{$ids}', '{$purids}', '{$pamounts}', '{$pdates}', '{$reference}', \n\t\t\t\t'" . USER_DIV . "'\n\t\t\t)";
        $Rslt = db_exec($sql) or errDie("Unable to add bank payment to database.", SELF);
        writetrans($dept['credacc'], $link['accnum'], $accdate, $refnum, sprint($amt + $overpay), "Supplier Payment to {$sup['supname']}");
        db_conn('cubit');
    }
    #do journal for the settlement discount here ... now ...
    if ($setamt > 0) {
        db_conn('core');
        #get settlement accid
        $get_setacc = "SELECT accid FROM accounts WHERE accname = 'Creditors 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) 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);
            $vatacc = gethook("accnum", "salesacc", "name", "VAT", "VAT");
            #process the vat amt ...
            writetrans($dept['credacc'], $vatacc, $accdate, $refnum, $setvatamt, "VAT Received on Settlement Discount for Supplier : {$sup['supname']}");
            vatr($vd['id'], $accdate, "INPUT", $vd['code'], $refnum, "VAT for Settlement Discount for Supplier : {$sup['supname']}", $setamt + $setvatamt, $setvatamt);
        } else {
            #no vat for set amt ... do nothing
            $setvatamt = 0;
        }
        writetrans($dept['credacc'], $setaccid, $accdate, $refnum, $setamt, "Settlement Discount For {$sup['supname']}");
        db_connect();
        $Sl = "\n\t\t\t\tINSERT INTO sup_stmnt (\n\t\t\t\t\tsupid, amount, edate, \n\t\t\t\t\tdescript, ref, cacc, div\n\t\t\t\t) VALUES (\n\t\t\t\t\t'{$sup['supid']}', '" . sprint($setamt - $setamt * 2) . "', '{$sdate}', \n\t\t\t\t\t'Settlement Discount','{$cheqnum}','{$bank['accnum']}', '" . USER_DIV . "'\n\t\t\t\t)";
        //		$Rs = db_exec($Sl) or errDie("Unable to insert statement record in Cubit.",SELF);
        #record this paid settlement discount for reporting ...
        $settl_sql = "\n\t\t\t\t\tINSERT INTO settlement_sup (\n\t\t\t\t\t\tsupplier, amt, setamt, setvatamt, setvat, \n\t\t\t\t\t\tsetvatcode, tdate, sdate, refnum\n\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t'{$sup['supid']}', '{$amt}', '{$setamt}', '{$setvatamt}', '{$setvat}', \n\t\t\t\t\t\t'{$setvatcode}', '{$accdate}','now','{$refnum}'\n\t\t\t\t\t)";
        $run_settl = db_exec($settl_sql) or errDie("Unable to get debtor settlement information.");
    }
    db_conn('cubit');
    $Sl = "DELETE FROM suppurch WHERE balance=0::numeric(13,2)";
    $Rx = db_exec($Sl);
    #check if date setting is in db ...
    $checkdate = getCSetting("SUPP_PAY_DATE");
    if (!isset($checkdate) or strlen($checkdate) < 1) {
        #no date ... insert
        $ins_sql = "\n\t\t\t\t\tINSERT INTO settings (\n\t\t\t\t\t\tconstant, label, value, type, \n\t\t\t\t\t\tdatatype, minlen, maxlen, div, readonly\n\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t'SUPP_PAY_DATE', 'Last Supplier Payment Date Used', '{$date}', 'general', \n\t\t\t\t\t\t'string', '10', '10', '0', 'n'\n\t\t\t\t\t);\n\t\t\t\t\t";
        $run_ins = db_exec($ins_sql) or errDie("Unable to record supplier payment date information.");
    } else {
        $upd_sql = "UPDATE settings SET value = '{$date}' WHERE constant = 'SUPP_PAY_DATE'";
        $run_upd = db_exec($upd_sql) or errDie("Unable to update supplier payment date setting.");
    }
    pglib_transaction("COMMIT");
}
function write($_POST)
{
    # Get vars
    extract($_POST);
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($purid, "num", 1, 20, "Invalid purchase number.");
    $v->isOk($remarks, "string", 0, 255, "Invalid Remarks.");
    $v->isOk($refno, "string", 0, 255, "Invalid Delivery Reference No.");
    $v->isOk($prd, "num", 1, 20, "Invalid period Database number.");
    $pdate = $p_year . "-" . $p_month . "-" . $p_day;
    if (!checkdate($p_month, $p_day, $p_year)) {
        $v->isOk($date, "num", 1, 1, "Invalid Date.");
    }
    $v->isOk($subtot, "float", 1, 20, "Invalid Subtotal.");
    foreach ($rvat as $rvat_k => $rvat_v) {
        $v->isOk($rvat_v, "float", 0, 40, "Invalid vat ({$rvat_v}).");
    }
    $v->isOk($total, "float", 1, 20, "Invalid total.");
    # Used to generate errors
    $error = "asa@";
    # display errors, if any
    $err = "";
    if ($v->isError()) {
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $err .= "<li class='err'>" . $e["msg"] . "</li>";
        }
        return details($_POST, $err);
    }
    # Get purchase info
    db_conn($prd);
    $sql = "SELECT * FROM purchases WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
    $purRslt = db_exec($sql) or errDie("Unable to get purchase information");
    if (pg_numrows($purRslt) < 1) {
        return "<li>- purchase Not Found</li>";
    }
    $pur = pg_fetch_array($purRslt);
    # check if purchase has been received
    if ($pur['received'] == "n") {
        $error = "<li class='err'> Error : purchase number <b>{$pur['purnum']}</b> has not been received.";
        $error .= "<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $error;
    }
    # Get selected supplier info
    db_connect();
    $sql = "SELECT * FROM suppliers WHERE supid = '{$pur['supid']}' AND div = '" . USER_DIV . "'";
    $supRslt = db_exec($sql) or errDie("Unable to get customer information");
    $sup = pg_fetch_array($supRslt);
    # Get department info
    db_conn("exten");
    $sql = "SELECT * FROM departments WHERE deptid = '{$pur['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);
    }
    # Insert purchase to DB
    db_connect();
    $d = date("Y-m-d");
    # Begin updating
    pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
    db_conn('cubit');
    $Sl = "INSERT INTO dnotes (purid,date,sub,vat,tot) VALUES ('{$purid}','{$d}','{$subtot}','{$vat}','{$total}')";
    $Ri = db_exec($Sl) or errDie("Unable insert data.");
    # Get warehouse name
    db_conn("exten");
    $sql = "SELECT * FROM warehouses WHERE div = '" . USER_DIV . "'";
    $whRslt = db_exec($sql);
    $wh = pg_fetch_array($whRslt);
    # Update purchase on the DB
    db_conn($prd);
    $sql = "UPDATE purchases SET noted = 'y', rsubtot = 0, remarks = '{$remarks}' WHERE purid = '{$purid}'";
    $rslt = db_exec($sql) or errDie("Unable to update purchase in Cubit.", SELF);
    /* - Start Hooks - */
    $refnum = getrefnum();
    $vatacc = gethook("accnum", "salesacc", "name", "VAT");
    $cvacc = gethook("accnum", "pchsacc", "name", "Cost Variance");
    /* - End Hooks - */
    $retot = sprint($subtot + $vat);
    $sdate = $pdate;
    //date("Y-m-d");
    # Debit Supplier control, credit inv control
    //	writetrans($dept['credacc'], $vatacc, date("d-m-Y"), $refnum, $vat, "Credit Note for VAT return on Purchase No. $pur[purnum] from Supplier : $sup[supname].");
    //	writetrans($dept['credacc'], $wh['conacc'], date("d-m-Y"), $refnum, $subtot, "Credit Note for Stock return on Purchase No. $pur[purnum] from Supplier : $sup[supname].");
    writetrans($dept['credacc'], $vatacc, $pur['pdate'], $refnum, $vat, "Credit Note for VAT return on Purchase No. {$pur['purnum']} from Supplier : {$sup['supname']}.");
    writetrans($dept['credacc'], $wh['conacc'], $pur['pdate'], $refnum, $subtot, "Credit Note for Stock return on Purchase No. {$pur['purnum']} from Supplier : {$sup['supname']}.");
    db_conn('cubit');
    $Sl = "SELECT * FROM vatcodes ORDER BY code";
    $Ri = db_exec($Sl);
    $f = 0;
    while ($vd = pg_fetch_array($Ri)) {
        $vid = $vd['id'];
        if ($rvat[$vid] < 0.01) {
            continue;
        }
        if ($f == 0) {
            $AM = sprint($subtot + $vat);
        } else {
            $AM = 0;
        }
        //$vd.="<tr><td><input type=hidden name='rvat[$vid]' value='$rvat[$vid]'></td></tr>";
        vatr($vd['id'], date("Y-m-d"), "INPUT", $vd['code'], $refnum, "Return VAT for Purchase No. {$pur['purnum']}", $AM, $rvat[$vid]);
        $f++;
    }
    db_connect();
    # Update the supplier (make balance less)
    $sql = "UPDATE suppliers SET balance = (balance - '{$retot}') WHERE supid = '{$pur['supid']}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
    # Update the supplier age analysis (make balance less)
    if (ext_ex2("suppurch", "purid", $pur['purnum'], "supid", $pur['supid'])) {
        # Found? Make amount less
        $sql = "\n\t\t\t\tUPDATE suppurch \n\t\t\t\tSET balance = (balance - '{$retot}') \n\t\t\t\tWHERE supid = '{$pur['supid']}' AND purid = '{$pur['purnum']}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
    } else {
        # Make transaction record for age analysis
        $sql = "\n\t\t\t\tINSERT INTO suppurch (\n\t\t\t\t\tsupid, purid, pdate, balance, div\n\t\t\t\t) VALUES (\n\t\t\t\t\t'{$pur['supid']}', '{$pur['purnum']}', '{$pdate}', '-{$retot}', '" . USER_DIV . "'\n\t\t\t\t)";
        $purcRslt = db_exec($sql) or errDie("Unable to update int purchases information in Cubit.", SELF);
    }
    # Remove all empty entries
    $sql = "DELETE FROM suppurch WHERE balance = 0::numeric(13,2) AND fbalance = 0::numeric(13,2) AND div = '" . USER_DIV . "'";
    $rs = db_exec($sql);
    $sql = "\n\t\t\tINSERT INTO sup_stmnt (\n\t\t\t\tsupid, edate, cacc, amount, descript, ref, ex, div\n\t\t\t) VALUES (\n\t\t\t\t'{$pur['supid']}', '{$pdate}', '{$dept['credacc']}', '-{$retot}', 'Stock Returned', '{$refnum}', '{$pur['purnum']}', '" . USER_DIV . "'\n\t\t\t)";
    $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
    # Ledger Records
    suppledger($pur['supid'], $wh['conacc'], $sdate, $pur['purid'], "Stock Purchase No. {$pur['purnum']} returned.", $retot, 'd');
    /*-- Cost varience -- */
    if ($pur['rsubtot'] > $subtot) {
        $diff = sprint($pur['rsubtot'] - $subtot);
        # Debit Stock Control and Credit Creditors control
        writetrans($cvacc, $wh['conacc'], $sdate, $refnum, $diff, "Cost Variance for Stock Return on Purchase No. {$pur['purnum']} from Supplier : {$sup['supname']}.");
    } elseif ($subtot > $pur['rsubtot']) {
        $diff = sprint($subtot - $pur['rsubtot']);
        # Debit Stock Control and Credit Creditors control
        writetrans($wh['conacc'], $cvacc, $sdate, $refnum, $diff, "Cost Variance for Stock Return on Purchase No. {$pur['purnum']} from Supplier : {$sup['supname']}.");
    }
    /*-- End Cost varience -- */
    /* End Transactions */
    db_conn($prd);
    $sql = "UPDATE pur_items SET ctqty = '0' WHERE purid = '{$purid}' AND ctqty > 0 AND div = '" . USER_DIV . "'";
    $stkdRslt = db_exec($sql);
    # Commit updating
    pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
    // Final Layout
    $write = "\n\t\t<table " . TMPL_tblDflts . ">\n\t\t\t<tr>\n\t\t\t\t<th>Stock Return Credit Note</th>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Stock Return Credit note from Supplier <b>{$sup['supname']}</b> has been recorded.</td>\n\t\t\t</tr>\n\t\t</table>\n\t\t<p>\n\t\t<table " . TMPL_tblDflts . ">\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='" . bg_class() . "'>\n\t\t\t\t<td><a href='purchase-view.php'>View purchases</a></td>\n\t\t\t</tr>\n\t\t\t<script>document.write(getQuicklinkSpecial());</script>\n\t\t</table>";
    return $write;
}
function process_entries($_POST)
{
    extract($_POST);
    # CHECK IF THIS DATE IS IN THE BLOCKED RANGE
    $blocked_date_from = getCSetting("BLOCKED_FROM");
    $blocked_date_to = getCSetting("BLOCKED_TO");
    db_connect();
    pglib_transaction("BEGIN") or errDie("Unable to start transaction.");
    $vatacc = gethook("accnum", "salesacc", "name", "VAT");
    $vatinc = "yes";
    #remove any selected entries
    foreach ($ids as $keys => $value) {
        if (isset($remids[$keys]) and $remids[$keys] == $value) {
            db_connect();
            #now remove this entry
            $rem_sql = "DELETE FROM purch_batch_entries WHERE id = '{$ids[$keys]}'";
            $run_rem = db_exec($rem_sql) or errDie("Unable to remove processed batch entry.");
            continue;
        }
    }
    db_connect();
    #first we get the suppliers involved
    $get_sup = "SELECT distinct(supplier) FROM purch_batch_entries";
    $run_sup = db_exec($get_sup) or errDie("Unable to get supplier information.");
    if (pg_numrows($run_sup) < 1) {
        return get_items($_POST, "<li class='err'>Please Add At Least One Item.</li>");
    } else {
        while ($sarr0 = pg_fetch_array($run_sup)) {
            #get this supplier's name
            $get_supp = "SELECT supname,supaddr FROM suppliers WHERE supid = '{$sarr0['supplier']}' LIMIT 1";
            $run_supp = db_exec($get_supp) or errDie("Unable to get supplier information.");
            if (pg_numrows($run_supp) < 1) {
                $supname = "";
                $supaddr = "";
            } else {
                $sarr = pg_fetch_array($run_supp);
                $supname = $sarr['supname'];
                $supaddr = $sarr['supaddr'];
            }
            #get distinct invs
            $get_inv = "SELECT distinct (supinv) FROM purch_batch_entries WHERE supplier = '{$sarr0['supplier']}'";
            $run_inv = db_exec($get_inv) or errDie("Unable to get batch entries.");
            if (pg_numrows($run_inv) < 1) {
                return get_items($_POST, "<li class='err'>Please Add At Least One Item.</li>");
            } else {
                while ($earr = pg_fetch_array($run_inv)) {
                    #get the info + each entry = new line item
                    $get_items = "SELECT * FROM purch_batch_entries WHERE supplier = '{$sarr0['supplier']}' AND supinv = '{$earr['supinv']}'";
                    $run_items = db_exec($get_items) or errDie("Unable to get purchase information.");
                    if (pg_numrows($run_items) < 1) {
                        return get_items($_POST, "<li class='err'>Please Add At Least One Item.</li>");
                    } else {
                        $total = 0;
                        while ($arr1 = pg_fetch_array($run_items)) {
                            if (strtotime($arr1['pdate']) >= strtotime($blocked_date_from) and strtotime($arr1['pdate']) <= 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>";
                            }
                            #calculate the total
                            $total = $total + $arr1['qty'] * $arr1['price'];
                            $pdate = $arr1['pdate'];
                            $ddate = $arr1['pdate'];
                        }
                    }
                    #get the info + each entry = new line item
                    $get_items = "SELECT * FROM purch_batch_entries WHERE supplier = '{$sarr0['supplier']}' AND supinv = '{$earr['supinv']}'";
                    $run_items = db_exec($get_items) or errDie("Unable to get purchase information.");
                    if (pg_numrows($run_items) < 1) {
                        return get_items($_POST, "<li class='err'>Please Add At Least One Item.</li>");
                    } else {
                        #################[ write the non stock purchase ]################
                        $remarks = "";
                        $supaddr = "";
                        $terms = "0";
                        $total = 0;
                        $subtot = 0;
                        //		$pdate = "$dates_year[$keys]-$dates_month[$keys]-$dates_day[$keys]";
                        //		$ddate = $arr['sdate'];
                        $shipchrg = "0.00";
                        $purnum = divlastid("pur", USER_DIV);
                        $typeid = 0;
                        if (!isset($ctyp)) {
                            $ctyp = "s";
                        }
                        //old ...
                        //'$sarr0[supplier]','2','$supname','$supaddr','$terms',
                        # Insert Order to DB
                        $sql = "\n\t\t\t\t\t\t\t\tINSERT INTO nons_purchases (\n\t\t\t\t\t\t\t\t\tsupid, deptid, supplier, supaddr, terms, pdate, ddate, \n\t\t\t\t\t\t\t\t\tshipchrg, subtot, total, balance, vatinc, vat, remarks, received, done, \n\t\t\t\t\t\t\t\t\tprd, div, purnum, ctyp, typeid\n\t\t\t\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t\t\t\t'{$sarr0['supplier']}', '2', '{$supname}', '{$supaddr}', '{$terms}', '{$pdate}', '{$ddate}', \n\t\t\t\t\t\t\t\t\t'{$shipchrg}', '{$subtot}', '{$total}', '{$total}', 'yes', '0', '{$remarks}', 'n', 'n', \n\t\t\t\t\t\t\t\t\t'" . PRD_DB . "', '" . USER_DIV . "', '{$purnum}', '{$ctyp}', '{$typeid}'\n\t\t\t\t\t\t\t\t)";
                        $rslt = db_exec($sql) or errDie("Unable to insert Non-Stock Order to Cubit.", SELF);
                        #################################################################
                        $refnum = getrefnum();
                        $resub = 0;
                        $totstkamt = array();
                        $revat = 0;
                        #######[ NOW WRITE THE ITEMS ]########
                        while ($arr1 = pg_fetch_array($run_items)) {
                            if (!in_array("{$arr1['id']}", $ids)) {
                            }
                            $darr = explode("-", $arr1['pdate']);
                            $suppliers[$keys] = $arr1['supplier'];
                            $accounts[$keys] = $arr1['account'];
                            $dates_year[$keys] = $darr[0];
                            $dates_month[$keys] = $darr[1];
                            $dates_day[$keys] = $darr[2];
                            $vatcodes[$keys] = $arr1['vatcode'];
                            $supinvs[$keys] = $arr1['supinv'];
                            $descriptions[$keys] = $arr1['description'];
                            $qtys[$keys] = $arr1['qty'];
                            $prices[$keys] = $arr1['price'];
                            # Get next ordnum
                            $purid = lastpurid();
                            $novat[$keys] = "1";
                            # Calculate amount
                            $amt[$keys] = $qtys[$keys] * $prices[$keys];
                            $tv = $vatinc;
                            db_conn('cubit');
                            $Sl = "SELECT * FROM vatcodes WHERE id='{$vatcodes[$keys]}'";
                            $Ri = db_exec($Sl);
                            if (pg_num_rows($Ri) < 1) {
                                return get_items($_POST, "<li class='err'>Please select the vatcode for all your items.</li>");
                            }
                            $vd = pg_fetch_array($Ri);
                            $VATP = $vd['vat_amount'];
                            if (TAX_VAT != $vd['vat_amount'] and $vd['vat_amount'] != "0.00") {
                                $showvat = FALSE;
                            }
                            # Check Tax Excempt
                            if ($vd['zero'] == "Yes") {
                                $vat[$keys] = 0;
                                $vatinc = "novat";
                            }
                            if (isset($novat[$keys]) || strlen($vat[$keys]) < 1) {
                                # If vat is not included
                                if ($vatinc == "no") {
                                    $vat[$keys] = sprint($VATP / 100 * $amt[$keys]);
                                } elseif ($vatinc == "yes") {
                                    $vat[$keys] = sprint($amt[$keys] / (100 + $VATP) * $VATP);
                                } else {
                                    $vat[$keys] = 0;
                                }
                            }
                            if ($vatinc == "novat") {
                                $vat[$keys] = 0;
                            }
                            if ($vatinc != "novat") {
                                # If vat is not included
                                if ($vatinc == "no") {
                                    $vat[$keys] = sprintf("%01.2f", $VATP / 100 * $amt[$keys]);
                                } else {
                                    $vat[$keys] = sprintf("%01.2f", $amt[$keys] / ($VATP + 100) * $VATP);
                                }
                            }
                            $vatinc = $tv;
                            # insert Order items
                            $sql = "\n\t\t\t\t\t\t\t\t\tINSERT INTO nons_pur_items (\n\t\t\t\t\t\t\t\t\t\tpurid, cod, des, \n\t\t\t\t\t\t\t\t\t\tqty, unitcost, amt, \n\t\t\t\t\t\t\t\t\t\tsvat, ddate, div, vatcode\n\t\t\t\t\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t\t\t\t\t'{$purid}', '{$supinvs[$keys]}', '{$descriptions[$keys]}', \n\t\t\t\t\t\t\t\t\t\t'{$qtys[$keys]}', '{$prices[$keys]}', '{$amt[$keys]}', \n\t\t\t\t\t\t\t\t\t\t'{$vat[$keys]}', '{$ddate}', '" . USER_DIV . "','{$vatcodes[$keys]}'\n\t\t\t\t\t\t\t\t\t)";
                            $rslt = db_exec($sql) or errDie("Unable to insert Order items to Cubit.", SELF);
                            //FP
                            $itemid = pglib_lastid("nons_pur_items", "id");
                            $SUBTOT = "";
                            $TOTAL = "";
                            # calculate subtot
                            if (isset($amt[$keys])) {
                                $SUBTOT = $amt[$keys];
                            } else {
                                $SUBTOT = 0.0;
                            }
                            # If there vatable items
                            if (isset($vat[$keys])) {
                                $VAT = $vat[$keys];
                            } else {
                                $VAT = 0;
                            }
                            # Total
                            $TOTAL = $SUBTOT;
                            # If vat is not included
                            if ($vatinc == "no") {
                                $TOTAL = $TOTAL + $VAT;
                            } else {
                                $TOTAL = $TOTAL;
                                $SUBTOT -= $VAT;
                            }
                            # insert Order to DB
                            $sql = "\n\t\t\t\t\t\t\t\t\tUPDATE nons_purchases \n\t\t\t\t\t\t\t\t\tSET terms = '{$terms}', \n\t\t\t\t\t\t\t\t\t\tsubtot = subtot + '{$SUBTOT}', total = total + '{$TOTAL}',\n\t\t\t\t\t\t\t\t\t\tbalance = balance + '{$TOTAL}', vatinc = 'yes', vat = vat + '{$VAT}',\n\t\t\t\t\t\t\t\t\t\tsupinv='{$supinvs[$keys]}'\n\t\t\t\t\t\t\t\t\tWHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
                            $rslt = db_exec($sql) or errDie("Unable to update Order in Cubit.", SELF);
                            #####################[ BEGIN PROCESSING ]#######################
                            db_connect();
                            $td = $pdate;
                            # amount of stock in
                            $amt[$keys] = $qtys[$keys] * $prices[$keys];
                            $SUBTOTAL = $amt[$keys];
                            # Get selected stock line
                            $sql = "SELECT * FROM nons_pur_items WHERE purid = '{$purid}' AND id = '{$itemid}' AND div = '" . USER_DIV . "'";
                            $stkdRslt = db_exec($sql);
                            $stkd = pg_fetch_array($stkdRslt);
                            # Calculate cost amount bought
                            $amt[$keys] = $qtys[$keys] * $prices[$keys];
                            /* delivery charge */
                            # Calculate percentage from subtotal
                            $perc[$keys] = $amt[$keys] / $SUBTOTAL * 100;
                            /* end delivery charge */
                            # the subtotal + delivery charges
                            $resub += $amt[$keys];
                            # calculate vat
                            $svat[$keys] = svat($amt[$keys], $stkd['amt'], $stkd['svat']);
                            db_conn('cubit');
                            $Sl = "SELECT * FROM vatcodes WHERE id='{$stkd['vatcode']}'";
                            $Ri = db_exec($Sl) or errDie("Unable to get data.");
                            $vd = pg_fetch_array($Ri);
                            vatr($vd['id'], $pdate, "INPUT", $vd['code'], $refnum, "VAT for Non-Stock Purchase No. {$purnum}", -$amt[$keys], -$svat[$keys]);
                            # received vat
                            $revat += $svat[$keys];
                            # make amount vat free
                            $amt[$keys] = $amt[$keys] - $svat[$keys];
                            # keep records for transactions
                            if (isset($totstkamt[$accounts[$keys]])) {
                                $totstkamt[$accounts[$keys]] += $amt[$keys];
                            } else {
                                $totstkamt[$accounts[$keys]] = $amt[$keys];
                            }
                            # check if there are any outstanding items
                            $sql = "SELECT * FROM nons_pur_items WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
                            // the old method check for this .. we receive everything NOW so we dont need this AND (qty - rqty) > '0' AND div = '".USER_DIV."'";
                            $stkdRslt = db_exec($sql);
                            # if none the set to received
                            if (pg_numrows($stkdRslt) < 1) {
                                //NO items were found ... problem somewhere
                            } else {
                                # update surch_int(received = 'y')
                                $sql = "UPDATE nons_purchases SET received = 'y' WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
                                $rslt = db_exec($sql) or errDie("Unable to update international Orders in Cubit.", SELF);
                                //	while ($uniarr1 = pg_fetch_array($stkdRslt)){
                                # Update Order items
                                $sql = "UPDATE nons_pur_items SET rqty = (rqty + '{$qtys[$keys]}'), accid = '{$accounts[$keys]}' WHERE purid='{$purid}' AND div = '" . USER_DIV . "' AND id = '{$itemid}'";
                                $rslt = db_exec($sql) or errDie("Unable to insert Order items to Cubit.", SELF);
                                //	}
                            }
                            # Update Order on the DB
                            $sql = "UPDATE nons_purchases SET  typeid = '2', refno = '', remarks = '{$remarks}' WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
                            $rslt = db_exec($sql) or errDie("Unable to update Order in Cubit.", SELF);
                            /* - Start Hooks - */
                            $vatacc = gethook("accnum", "salesacc", "name", "VAT");
                            if (isset($suppliers[$keys])) {
                                $typeid = $suppliers[$keys];
                                db_connect();
                                $sql = "SELECT * FROM suppliers WHERE supid = '{$suppliers[$keys]}' AND div = '" . USER_DIV . "'";
                                $supRslt = db_exec($sql) or errDie("Unable to get supplier");
                                if (pg_numrows($supRslt) < 1) {
                                    $error = "<li class='err'> Supplier not Found.</li>";
                                    $confirm .= "{$error}<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
                                    return $confirm;
                                } else {
                                    $sup = pg_fetch_array($supRslt);
                                    $pur['supplier'] = $sup['supname'];
                                    $pur['supaddr'] = $sup['supaddr'];
                                    # Get department info
                                    db_conn("exten");
                                    $sql = "SELECT * FROM departments WHERE deptid = '{$sup['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);
                                    }
                                    $supacc = $dept['credacc'];
                                }
                            }
                            /* - End Hooks - */
                            ### DATA SET 2 WAS HERE
                            #####################################################################################
                            //pglib_transaction("COMMIT") or errDie("Unable to complete transaction.");
                            #received so now move
                            //pglib_transaction("BEGIN") or errDie("Unable to start transaction.");
                            ## move stuff went here
                            #####################################################################################
                            db_connect();
                            //			$sql = "SELECT * FROM bankacct WHERE btype != 'int' AND div = '".USER_DIV."' LIMIT 1";
                            //			$banks = db_exec($sql);
                            //			if(pg_numrows($banks) < 1){
                            //				return "<li class='err'> There are no accounts held at the selected Bank.
                            //				<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct Selection'>";
                            //			}
                            //			$barr = pg_fetch_array($banks);
                            //			$bankid = $barr['bankid'];
                            //			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.";
                            //			}
                            //			$banklnk = pg_fetch_array($rslt);
                            //			$cc_trantype = cc_TranTypeAcc($arr1['account'], $banklnk['accnum']);
                            //
                            //			if(($arr1['project_id'] == 0) OR (strlen($arr1['project_code']) < 1) OR (strlen($arr1['center_code']) < 1) OR (strlen($arr1['center_perc']) < 1)){
                            //				$cc = "
                            //						<script>
                            //							CostCenter('$cc_trantype', 'Non Stock Purchase', '$arr1[pdate]', '$arr1[description]', '$arr1[price]', '');
                            //						</script>
                            //						";
                            //			}else {
                            //				$cc = "";
                            //			}
                            //								$get_data = "SELECT * FROM purch_batch_entries WHERE id = '$ids[$keys]' LIMIT 1";
                            $get_data = "SELECT * FROM purch_batch_entries WHERE id = '{$arr1['id']}' LIMIT 1";
                            $run_data = db_exec($get_data) or errDie("Unable to get cost ledger information.");
                            if (pg_numrows($run_data) < 1) {
                                return "\n\t\t\t\t\t\t\t\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t\t\t\t\t<td><li class='err'>Unable to get batch entry information.</li></td>\n\t\t\t\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t\t\t</table>\n\t\t\t\t\t\t\t\t\t\t<br>" . mkQuickLinks(ql("nons-purch-batch-add.php", "Batch Creditors Non-Stock Invoices Add"), ql("purchase-new.php", "Add Purchase"), ql("purchase-view.php", "View Purchases"), ql("nons-purchase-new.php", "Add Non-Stock Purchase"), ql("nons-purchase-view.php", "View Non-Stock Purchases"));
                            }
                            $data_arr = pg_fetch_array($run_data);
                            $csetting = getsetting("CC_USE");
                            if ($csetting == "use") {
                                # we want to store all the relevant information in a neat and orderly manner ...
                                $get_info = "SELECT * FROM purch_batch_entries_costcenters WHERE batch_entry = '{$arr1['id']}'";
                                //$ids[$keys]'";
                                $run_info = db_exec($get_info) or errDie("Unable to get batch entry cost ledger information.");
                                if (pg_numrows($run_info) < 1) {
                                    #no cost entries ????
                                } else {
                                    $ccenters = "";
                                    while ($arr = pg_fetch_array($run_info)) {
                                        $amt_vat = $arr1['price'] / (100 + $vd['vat_amount']) * $vd['vat_amount'];
                                        $amount = $arr1['qty'] * ($arr1['price'] - $amt_vat);
                                        db_connect();
                                        #get project id
                                        $get_pro = "SELECT * FROM projects WHERE code = '{$arr['project']}' LIMIT 1";
                                        $run_pro = db_exec($get_pro) or errDie("Unable to get project information.");
                                        if (pg_numrows($run_pro) < 1) {
                                            $project = 0;
                                        } else {
                                            $pro_arr = pg_fetch_array($run_pro);
                                            $project = $pro_arr['id'];
                                        }
                                        #get costcenter id
                                        $get_cst = "SELECT * FROM costcenters WHERE centercode = '{$arr['costcenter']}' LIMIT 1";
                                        $run_cst = db_exec($get_cst) or errDie("Unable to get cost center information.");
                                        if (pg_numrows($run_cst) < 1) {
                                            $costcenterlink = 0;
                                        } else {
                                            $cst_arr = pg_fetch_array($run_cst);
                                            $costcenterlink = $cst_arr['ccid'];
                                        }
                                        #get costcenter/project link id
                                        $get_link = "SELECT * FROM costcenters_links WHERE ccid = '{$costcenterlink}' AND project1 = '{$project}' LIMIT 1";
                                        $run_link = db_exec($get_link) or errDie("Unable to get cost center link information.");
                                        if (pg_numrows($run_link) < 1) {
                                            return "<li class='err'>Unable to get cost ledger link information.</li>";
                                        }
                                        $cc = pg_fetch_array($run_link);
                                        $edate = ext_rdate($data_arr['pdate']);
                                        $edarr = explode("-", $edate);
                                        $prd = $edarr[1];
                                        $ccamts = sprint($amount * ($arr['costperc'] / 100));
                                        #we need to connect to the actual period db
                                        db_conn($prd);
                                        $sql = "\n\t\t\t\t\t\t\t\t\t\t\t\tINSERT INTO cctran (\n\t\t\t\t\t\t\t\t\t\t\t\t\tccid, trantype, typename, edate, description, \n\t\t\t\t\t\t\t\t\t\t\t\t\tamount, username, div, project\n\t\t\t\t\t\t\t\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t\t\t\t\t\t\t\t'{$cc['ccid']}', 'ct', 'Non Stock Purchase', '{$data_arr['pdate']}', '{$data_arr['description']}', \n\t\t\t\t\t\t\t\t\t\t\t\t\t'{$ccamts}', '" . USER_NAME . "', '" . USER_DIV . "', '{$project}'\n\t\t\t\t\t\t\t\t\t\t\t\t)";
                                        $insRslt = db_exec($sql) or errDie("Unable to retrieve insert Cost center amounts into database.");
                                    }
                                }
                            }
                            db_connect();
                            #now remove this entry
                            $rem_sql = "DELETE FROM purch_batch_entries WHERE id = '{$arr1['id']}'";
                            $run_rem = db_exec($rem_sql) or errDie("Unable to remove processed batch entry.");
                            #remove cost center
                            $rem_sql2 = "DELETE FROM purch_batch_entries_costcenters WHERE batch_entry = '{$arr1['id']}'";
                            $run_rem2 = db_exec($rem_sql2) or errDie("Unable to remove cost center information.");
                        }
                        # Get Order info
                        db_connect();
                        $sql = "SELECT * FROM nons_purchases WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
                        $purRslt = db_exec($sql) or errDie("Unable to get Order information");
                        if (pg_numrows($purRslt) < 1) {
                            return "<li>- Order Not Found</li>";
                        }
                        $pur = pg_fetch_array($purRslt);
                        $sid = $pur['supid'];
                        $purnum = $pur['purnum'];
                        if ($pur['received'] == "y") {
                            if (isset($bankid)) {
                                $sid = $bankid;
                                $sid += 0;
                            }
                            ### DATA SET 2 ...
                            $detadd = "";
                            if (isset($sid)) {
                                $detadd = " from Supplier {$pur['supplier']}";
                            }
                            $sdate = $pdate;
                            $tpp = 0;
                            $ccamt = 0;
                            # record transaction  from data
                            if (isset($BA)) {
                                $supacc = $BA;
                            }
                            foreach ($totstkamt as $stkacc => $wamt) {
                                writetrans($stkacc, $supacc, $td, $refnum, $wamt, "Non-Stock Purchase No. {$purnum} Received {$detadd}.");
                                pettyrec($supacc, $sdate, "ct", "Non-Stock Purchase No. {$purnum} Received {$detadd}.", $wamt, "Cash Order");
                            }
                            # vat
                            $vatamt = $revat;
                            # Add vat if not included
                            $retot = $resub;
                            if (isset($sid)) {
                                db_connect();
                                # update the supplier (make balance more)
                                $sql = "UPDATE suppliers SET balance = (balance + '{$retot}') WHERE supid = '{$pur['supid']}' AND div = '" . USER_DIV . "'";
                                $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
                            }
                            if (isset($sid)) {
                                # Ledger Records
                                $DAte = $pur['pdate'];
                                suppledger($sup['supid'], $stkacc, $DAte, $purid, "Non-Stock Purchase No. {$purnum} received.", $retot, 'c');
                            }
                            if ($vatamt != 0) {
                                # Debit bank and credit the account involved
                                writetrans($vatacc, $supacc, $td, $refnum, $vatamt, "Non-Stock Purchase VAT paid on Non-Stock Order No. {$purnum} {$detadd}.");
                                pettyrec($supacc, $sdate, "ct", "Non-Stock Purchase No. {$purnum} Received {$detadd}.", $vatamt, "Cash Order VAT");
                                # Record the payment on the statement
                                db_connect();
                                $sdate = $pdate;
                            }
                            //								if(isset($bankid)) {
                            //									db_connect();
                            //									$sql = "INSERT INTO cashbook(bankid, trantype, date, name, descript, cheqnum, amount, vat, chrgvat, banked, accinv, div) VALUES ('$bankid', 'withdrawal', '$sdate', '$pur[supplier]', 'Non-Stock Purchase No. $pur[purnum] received', '0', '$retot', '$vatamt', '$pur[vatinc]', 'no', '$stkacc', '".USER_DIV."')";
                            //									$Rslt = db_exec ($sql) or errDie ("Unable to add bank payment to database.",SELF);
                            //								}
                            if (isset($sid)) {
                                db_connect();
                                $DAte = $pdate;
                                $sql = "\n\t\t\t\t\t\t\t\t\t\tINSERT INTO sup_stmnt (\n\t\t\t\t\t\t\t\t\t\t\tsupid, edate, cacc, amount, \n\t\t\t\t\t\t\t\t\t\t\tdescript, ref, ex, div\n\t\t\t\t\t\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t\t\t\t\t\t'{$pur['supid']}', '{$pur['pdate']}', '{$stkacc}', '{$retot}', \n\t\t\t\t\t\t\t\t\t\t\t'Non Stock Purchase No. {$purnum} Received', '{$refnum}', '{$purnum}', '" . USER_DIV . "'\n\t\t\t\t\t\t\t\t\t\t)";
                                $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
                                db_connect();
                                # update the supplier age analysis (make balance less)
                                /* Make transaction record for age analysis */
                                $sql = "\n\t\t\t\t\t\t\t\t\t\tINSERT INTO suppurch (\n\t\t\t\t\t\t\t\t\t\t\tsupid, purid, pdate, balance, div\n\t\t\t\t\t\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t\t\t\t\t\t'{$pur['supid']}', '{$purnum}', '{$pur['pdate']}', '{$retot}', '" . USER_DIV . "'\n\t\t\t\t\t\t\t\t\t\t)";
                                $purcRslt = db_exec($sql) or errDie("Unable to update int Orders information in Cubit.", SELF);
                            }
                            ###
                            # copy Order
                            db_conn(PRD_DB);
                            $sql = "\n\t\t\t\t\t\t\t\t\tINSERT INTO nons_purchases (\n\t\t\t\t\t\t\t\t\t\tpurid, deptid, supplier, supaddr, terms, \n\t\t\t\t\t\t\t\t\t\tpdate, ddate, shipchrg, shipping, subtot, \n\t\t\t\t\t\t\t\t\t\ttotal, balance, vatinc, vat, remarks, \n\t\t\t\t\t\t\t\t\t\trefno, received, done, ctyp, typeid, \n\t\t\t\t\t\t\t\t\t\tdiv, purnum, supid, mpurid, is_asset, supinv\n\t\t\t\t\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t\t\t\t\t'{$purid}', '{$pur['deptid']}', '{$pur['supplier']}',  '{$pur['supaddr']}', '{$pur['terms']}', \n\t\t\t\t\t\t\t\t\t\t'{$pur['pdate']}', '{$pur['ddate']}', '{$pur['shipchrg']}', '{$pur['shipping']}', '{$pur['subtot']}', \n\t\t\t\t\t\t\t\t\t\t'{$pur['total']}', '0', '{$pur['vatinc']}', '{$pur['vat']}', '{$pur['remarks']}', \n\t\t\t\t\t\t\t\t\t\t'{$pur['refno']}', 'y', 'y', '{$pur['ctyp']}', '{$pur['typeid']}', \n\t\t\t\t\t\t\t\t\t\t'" . USER_DIV . "', '{$pur['purnum']}','{$sid}', '{$supacc}', '{$pur['is_asset']}', '{$pur['supinv']}'\n\t\t\t\t\t\t\t\t\t)";
                            $rslt = db_exec($sql) or errDie("Unable to insert Non-Stock Order to Cubit.", SELF);
                            db_connect();
                            # Get selected stock
                            $sql = "SELECT * FROM nons_pur_items WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
                            $stktcRslt = db_exec($sql);
                            while ($stktc = pg_fetch_array($stktcRslt)) {
                                # Insert Order items
                                db_conn($pur['prd']);
                                $sql = "\n\t\t\t\t\t\t\t\t\t\tINSERT INTO nons_pur_items (\n\t\t\t\t\t\t\t\t\t\t\tpurid, cod, des, qty, unitcost, \n\t\t\t\t\t\t\t\t\t\t\tamt, svat, ddate, accid, \n\t\t\t\t\t\t\t\t\t\t\tdiv, vatcode\n\t\t\t\t\t\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t\t\t\t\t\t'{$purid}', '{$stktc['cod']}', '{$stktc['des']}', '{$stktc['qty']}', '{$stktc['unitcost']}', \n\t\t\t\t\t\t\t\t\t\t\t'{$stktc['amt']}', '{$stktc['svat']}', '{$stktc['ddate']}', '{$stktc['accid']}', \n\t\t\t\t\t\t\t\t\t\t\t'" . USER_DIV . "', '{$stktc['vatcode']}'\n\t\t\t\t\t\t\t\t\t\t)";
                                $rslt = db_exec($sql) or errDie("Unable to insert Order items to Cubit.", SELF);
                            }
                            db_connect();
                            # Remove the Order from running DB
                            $sql = "DELETE FROM nons_purchases WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
                            $delRslt = db_exec($sql) or errDie("Unable to update int Orders information in Cubit.", SELF);
                            # Remove those Order items from running DB
                            $sql = "DELETE FROM nons_pur_items WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
                            $delRslt = db_exec($sql) or errDie("Unable to update int Orders information in Cubit.", SELF);
                        }
                    }
                }
            }
        }
    }
    pglib_transaction("COMMIT") or errDie("Unable to complete transaction.");
    return "\n\t\t<table " . TMPL_tblDflts . ">\n\t\t\t<tr>\n\t\t\t\t<th>Processing Completed</th>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>All Selected Transactions Completed</td>\n\t\t\t</tr>\n\t\t</table>\n\t\t<br>\n\t\t" . mkQuickLinks(ql("nons-purch-batch-add.php", "Batch Creditors Non-Stock Invoices Add"), ql("purchase-new.php", "Add Purchase"), ql("purchase-view.php", "View Purchases"), ql("nons-purchase-new.php", "Add Non-Stock Purchase"), ql("nons-purchase-view.php", "View Non-Stock Purchases"));
}
function write($_POST)
{
    # Get vars
    extract($_POST);
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($purid, "num", 1, 20, "Invalid purchase number.");
    $v->isOk($remarks, "string", 0, 255, "Invalid Remarks.");
    $v->isOk($prd, "num", 1, 20, "Invalid period Database number.");
    // $v->isOk ($refno, "string", 0, 255, "Invalid Delivery Reference No.");
    $pdate = $p_year . "-" . $p_month . "-" . $p_day;
    if (!checkdate($p_month, $p_day, $p_year)) {
        $v->isOk($date, "num", 1, 1, "Invalid Date.");
    }
    $v->isOk($subtot, "float", 1, 20, "Invalid Subtotal.");
    $v->isOk($tax, "float", 0, 20, "Invalid Tax.");
    $v->isOk($total, "float", 1, 20, "Invalid total.");
    # display errors, if any
    $err = "";
    if ($v->isError()) {
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $err .= "<li class='err'>" . $e["msg"] . "</li>";
        }
        return details($_POST, $err);
    }
    # Get purchase info
    db_conn($prd);
    $sql = "SELECT * FROM purch_int WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
    $purRslt = db_exec($sql) or errDie("Unable to get purchase information");
    if (pg_numrows($purRslt) < 1) {
        return "<li>- purchase Not Found</li>";
    }
    $pur = pg_fetch_array($purRslt);
    # Get selected supplier info
    db_connect();
    $sql = "SELECT * FROM suppliers WHERE supid = '{$pur['supid']}' AND div = '" . USER_DIV . "'";
    $supRslt = db_exec($sql) or errDie("Unable to get customer information");
    $sup = pg_fetch_array($supRslt);
    # Get department info
    db_conn("exten");
    $sql = "SELECT * FROM departments WHERE deptid = '{$pur['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);
    }
    # Insert purchase to DB
    db_connect();
    # Begin updating
    pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
    # Get warehouse name
    db_conn("exten");
    $sql = "SELECT * FROM warehouses WHERE div = '" . USER_DIV . "'";
    $whRslt = db_exec($sql);
    $wh = pg_fetch_array($whRslt);
    # Update purchase on the DB
    db_conn($prd);
    $sql = "UPDATE purch_int SET noted = 'y', rsubtot = 0, rtax = 0, remarks = '{$remarks}' WHERE purid = '{$purid}'";
    $rslt = db_exec($sql) or errDie("Unable to update purchase in Cubit.", SELF);
    /* - Start Hooks - */
    $refnum = getrefnum();
    $vatacc = gethook("accnum", "salesacc", "name", "VAT");
    $cvacc = gethook("accnum", "pchsacc", "name", "Cost Variance");
    /* - End Hooks - */
    $retot = sprint($subtot + $tax);
    $sdate = date("Y-m-d");
    $lsubtot = sprint($subtot * $pur['xrate']);
    $ltax = sprint($tax * $pur['xrate']);
    $lretot = sprint($retot * $pur['xrate']);
    # Debit Supplier control, credit inv control
    //date("d-m-Y")
    writetrans($dept['credacc'], $vatacc, $pdate, $refnum, $ltax, "Credit Note for Vat return on Purchase No. {$pur['purnum']} from Supplier : {$sup['supname']}.");
    writetrans($dept['credacc'], $wh['conacc'], $pdate, $refnum, $lsubtot, "Credit Note for Stock return on Purchase No. {$pur['purnum']} from Supplier : {$sup['supname']}.");
    db_connect();
    # update the supplier (make balance less)
    $sql = "UPDATE suppliers SET fbalance = (fbalance - '{$retot}'), balance = (balance - '{$lretot}') WHERE supid = '{$pur['supid']}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
    # update the supplier age analysis (make balance less)
    if (ext_ex2("suppurch", "purid", $pur['purnum'], "supid", $pur['supid'])) {
        # Found? Make amount less
        $sql = "UPDATE suppurch SET fbalance = (fbalance - '{$retot}'), balance = (balance - '{$lretot}') WHERE supid = '{$pur['supid']}' AND purid = '{$pur['purnum']}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
    } else {
        /* Make transaction record for age analysis */
        $sql = "INSERT INTO suppurch(supid, purid, pdate, balance, fbalance, div) VALUES('{$pur['supid']}', '{$pur['purnum']}', '{$sdate}', '-{$lretot}', '-{$retot}', '" . USER_DIV . "')";
        $purcRslt = db_exec($sql) or errDie("Unable to update int purchases information in Cubit.", SELF);
    }
    $Date = date("Y-m-d");
    $sql = "INSERT INTO sup_stmnt(supid, edate, cacc, amount, descript, ref, ex, div) VALUES('{$pur['supid']}','{$Date}', '{$dept['credacc']}', '-{$retot}', 'Stock Returned', '{$refnum}', '{$pur['purnum']}', '" . USER_DIV . "')";
    $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
    # Ledger Records
    suppledger($pur['supid'], $wh['stkacc'], $Date, $pur['purid'], "Stock Purchase No. {$pur['purnum']} returned.", $lretot, 'd');
    /*-- Cost varience -- */
    //date("d-m-Y")
    if ($pur['rsubtot'] > $subtot) {
        $diff = sprint($pur['rsubtot'] - $subtot);
        # Debit Stock Control and Credit Creditors control
        writetrans($cvacc, $wh['conacc'], $pdate, $refnum, $diff, "Cost Variance for Stock Return on Purchase No. {$pur['purnum']} from Supplier : {$sup['supname']}.");
    } elseif ($subtot > $pur['rsubtot']) {
        $diff = sprint($subtot - $pur['rsubtot']);
        # Debit Stock Control and Credit Creditors control
        writetrans($wh['conacc'], $cvacc, $pdate, $refnum, $diff, "Cost Variance for Stock Return on Purchase No. {$pur['purnum']} from Supplier : {$sup['supname']}.");
    }
    /*-- End Cost varience -- */
    /* End Transactions */
    # commit updating
    pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
    // Final Layout
    $write = "\n\t\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t\t<tr>\n\t\t\t\t\t\t<th>Stock Return</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>Stock Return to Supplier <b>{$sup['supname']}</b> has been recorded.</td>\n\t\t\t\t\t</tr>\n\t\t\t\t</table>\n\t\t\t\t<p>\n\t\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t\t<tr>\n\t\t\t\t\t\t<th>Quick Links</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><a href='purchase-view.php'>View purchases</a></td>\n\t\t\t\t\t</tr>\n\t\t\t\t\t<script>document.write(getQuicklinkSpecial());</script>\n\t\t\t\t</table>";
    return $write;
}
Ejemplo n.º 13
0
function write()
{
    # Get vars
    extract($_REQUEST);
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($purid, "num", 1, 20, "Invalid Order number.");
    $v->isOk($remarks, "string", 0, 255, "Invalid Remarks.");
    $v->isOk($refno, "string", 0, 255, "Invalid Delivery Reference No.");
    $v->isOk($shipchrg, "float", 0, 20, "Invalid Delivery Charges.");
    # used to generate errors
    $error = "asa@";
    # check quantities
    if (isset($recvd)) {
        foreach ($recvd as $sk => $keys) {
            $v->isOk($qtys[$keys], "float", 1, 15, "Invalid Quantity for product number : <b>" . ($keys + 1) . "</b>");
            $v->isOk($unitcost[$keys], "float", 1, 20, "Invalid Unit Price for product number : <b>" . ($keys + 1) . "</b>.");
            if ($qtys[$keys] <= 0) {
                $v->isOk("#", "num", 0, 0, "Error : Item Quantity must be more than zero. Product number : <b>" . ($keys + 1) . "</b>");
            }
            if ($qtys[$keys] > $qts[$keys]) {
                $v->isOk("#", "num", 0, 0, "Error : Item Quantity returned is more than the bought quantity : <b>" . ($keys + 1) . "</b>");
            }
            $v->isOk($stkids[$keys], "num", 1, 10, "Invalid Stock number, please enter all details.");
            # Validate ddate[]
            $v->isOk($d_day[$keys], "num", 1, 2, "Invalid Delivery Date day.");
            $v->isOk($d_month[$keys], "num", 1, 2, "Invalid Delivery Date month.");
            $v->isOk($d_year[$keys], "num", 1, 5, "Invalid Delivery Date year.");
            $ddate[$keys] = $d_year[$keys] . "-" . $d_month[$keys] . "-" . $d_day[$keys];
            if (!checkdate($d_month[$keys], $d_day[$keys], $d_year[$keys])) {
                $v->isOk($ddate[$keys], "num", 1, 1, "Invalid Delivery Date.");
            }
        }
        if (isset($sers)) {
            foreach ($sers as $stkid => $sernos) {
                if (!ext_isUnique(ext_remBlnk($sernos))) {
                    $v->isOk("error", "num", 1, 1, "Error : Serial numbers must be unique per Stock Item.");
                } else {
                    foreach ($recvd as $sk => $keys) {
                        if (isset($sernos[$keys]) && $v->isOk($sernos[$keys], "string", 1, 20, "Error : Invalid Serial number.")) {
                            if (ext_findSer($sernos[$keys]) != false) {
                                $v->isOk("#", "string", 1, 20, "Error : Serial number already exists.");
                            }
                        }
                    }
                }
            }
        }
    } else {
        $v->isOk("#", "num", 0, 0, "Error : Items Not Selected.");
    }
    # display errors, if any
    $err = "";
    if ($v->isError()) {
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $err .= "<li class='err'>" . $e["msg"] . "</li>";
        }
        return details($_POST, $err);
    }
    # Get purchase info
    db_connect();
    $sql = "SELECT * FROM purchases WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
    $purRslt = db_exec($sql) or errDie("Unable to get purchase information");
    if (pg_numrows($purRslt) < 1) {
        return "<li> - Order Not Found</li>";
    }
    $pur = pg_fetch_array($purRslt);
    $td = $pur['pdate'];
    # check if purchase has been received
    if ($pur['received'] == "y") {
        $error = "<li class='err'> Error : Order number <b>{$purid}</b> has already been received.</li>";
        $error .= "<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $error;
    }
    # Get selected supplier info
    db_connect();
    $sql = "SELECT * FROM suppliers WHERE supid = '{$pur['supid']}' AND div = '" . USER_DIV . "'";
    $supRslt = db_exec($sql) or errDie("Unable to get customer information");
    if (pg_numrows($supRslt) < 1) {
        // code here
    } else {
        $sup = pg_fetch_array($supRslt);
    }
    # Get department info
    db_conn("exten");
    $sql = "SELECT * FROM departments WHERE deptid = '{$pur['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);
    }
    db_conn('cubit');
    $Sl = "SELECT * FROM vatcodes WHERE id='{$pur['delvat']}'";
    $Ri = db_exec($Sl);
    if (pg_num_rows($Ri) < 1) {
        $Sl = "SELECT * FROM vatcodes";
        $Ri = db_exec($Sl);
    }
    $vd = pg_fetch_array($Ri);
    $VATP = $vd['vat_amount'];
    if ($vd['zero'] != "Yes") {
        # If vat is not included (shipchrg)
        if ($pur['vatinc'] == "no") {
            $scvat = sprint($VATP / 100 * $shipchrg);
            $shipexvat = $shipchrg;
        } elseif ($pur['vatinc'] == "yes") {
            $scvat = sprint($shipchrg / ($VATP + 100) * $VATP);
            $shipexvat = $shipchrg - $scvat;
        } else {
            $scvat = 0;
            $shipexvat = $shipchrg;
        }
    } else {
        $scvat = 0;
        $shipexvat = $shipchrg;
    }
    db_conn("exten");
    $sql = "SELECT * FROM warehouses WHERE div = '" . USER_DIV . "'";
    $whRslt = db_exec($sql);
    $wh = pg_fetch_array($whRslt);
    # Begin updating
    pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
    db_conn(PRD_DB);
    # get last ref number
    $refnum = getrefnum();
    db_connect();
    # amount of stock in
    $totstkamt = array();
    $resub = 0;
    $vatacc = gethook("accnum", "salesacc", "name", "VAT");
    $cvacc = gethook("accnum", "pchsacc", "name", "Cost Variance");
    $flag = TRUE;
    $checkid = 0;
    $nonstot = 0;
    foreach ($recvd as $sk => $keys) {
        if ($checkid == $ids[$keys]) {
            $flag = FALSE;
        } else {
            $flag = TRUE;
        }
        $checkid = $ids[$keys];
        # Skip zeros
        if ($qtys[$keys] <= 0) {
            continue;
        }
        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);
        if ($stk['units'] < 0) {
            $min_stock = abs($stk['units']);
            if ($qtys[$keys] < $min_stock) {
                $min_stock = $qtys[$keys];
            }
        } else {
            $min_stock = 0;
        }
        # Get selected stock line
        $sql = "SELECT * FROM pur_items WHERE id = '{$ids[$keys]}' AND purid = '{$purid}' AND div = '" . USER_DIV . "'";
        $stkdRslt = db_exec($sql);
        $stkd = pg_fetch_array($stkdRslt);
        if ($pur['vatinc'] == "yes") {
            $unitcost[$keys] = sprint(($stkd['amt'] - $stkd['svat']) / $stkd['qty']);
        } else {
            $unitcost[$keys] = sprint($stkd['amt'] / $stkd['qty']);
        }
        //$perc[$keys] = sprint((($unitcost[$keys]*$qtys[$keys])/$pur['subtot']) * 100);
        $perc[$keys] = sprint($unitcost[$keys] / $pur['subtot'] * 100);
        $ffs = $perc[$keys] * $qtys[$keys];
        # Get percentage from shipping charges excluding vat
        $shipc[$keys] = sprint($perc[$keys] / 100 * $shipexvat);
        //print "cost: percent:$ffs ship: part1".($unitcost[$keys]*$qtys[$keys])."part2".($shipc[$keys]*$qtys[$keys])."<br>";
        # add delivery charges = amt + del chrg excluding vat
        $unitcost[$keys] += $shipc[$keys];
        if ($stkd['udiscount'] > 0) {
            $discps = round($stkd['udiscount'] / 100 * $unitcost[$keys], 2);
        } else {
            $discps = 0;
        }
        $amt[$keys] = sprint($qtys[$keys] * $unitcost[$keys]);
        #serialized items are broken into multiples .... we only want to process the first ... so FLAG is used
        if (isset($invoice)) {
            $iq = $qtys[$keys];
            $iq += 0;
            $Sl = "SELECT * FROM vatcodes WHERE id='{$stkd['vatcode']}'";
            $Ri = db_exec($Sl) or errDie("Unable to get data.");
            $vd = pg_fetch_array($Ri);
            if ($pur['vatinc'] == "yes") {
                $iamount = $stkd['amt'];
            } else {
                $iamount = sprint($stkd['amt'] + $stkd['svat']);
            }
            if ($flag) {
                vatr($vd['id'], $pur['pdate'], "INPUT", $vd['code'], $refnum, "VAT for Purchase No. {$pur['purnum']}", -$iamount, -$stkd['svat']);
            }
            $Sl = "UPDATE pur_items SET iqty=iqty-'{$iq}' WHERE id='{$stkd['id']}'";
            $Ri = db_exec($Sl) or errDie("Unable to update invoice qty.");
        }
        $resub += $amt[$keys];
        # Update purchase items
        $sql = "\n\t\t\tUPDATE pur_items \n\t\t\tSET rqty = (rqty + '{$qtys[$keys]}'), ddate = '{$ddate[$keys]}' \n\t\t\tWHERE id = '{$ids[$keys]}' AND purid='{$purid}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to insert Order items to Cubit.", SELF);
        $cc = "";
        if ($stkd['account'] > 0) {
            if ($pur['vatinc'] == "yes") {
                #calculate the vat of this amount as we dont store it !!
                $vatcod = $stkd['vatcode'] + 0;
                $get_v = "SELECT vat_amount FROM vatcodes WHERE id = '{$vatcod}' LIMIT 1";
                $run_v = db_exec($get_v) or errDie("Unable to get vatcode information.");
                $varr = pg_fetch_array($run_v);
                $clearvat = $varr['vat_amount'] + 0;
                $remvat = sprint($stkd['amt'] / ($clearvat + 100) * $clearvat);
                $nonstot = $nonstot + $stkd['amt'] - $remvat;
            } else {
                $nonstot = $nonstot + $stkd['amt'];
            }
            $stk['whid'] = $stkd['account'];
            $sql = "SELECT * FROM bankacct WHERE btype != 'int' AND div = '" . USER_DIV . "' LIMIT 1";
            $banks = db_exec($sql);
            if (pg_numrows($banks) < 1) {
                return "<li class='err'> There are no accounts held at the selected Bank.\n\t\t\t\t<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct Selection'>";
            }
            $barr = pg_fetch_array($banks);
            $bankid = $barr['bankid'];
            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.";
            }
            $banklnk = pg_fetch_array($rslt);
            $cc_trantype = cc_TranTypeAcc($stkd['account'], $banklnk['accnum']);
        } else {
            # Update stock(ordered + qty, units + qty, csamt + (csamt + amt))
            $sql = "\n\t\t\t\tUPDATE stock \n\t\t\t\tSET ordered = (ordered - '{$qtys[$keys]}'), units = (units + '{$qtys[$keys]}' +'{$min_stock}'), csamt = (csamt + '{$amt[$keys]}') \n\t\t\t\tWHERE stkid = '{$stkids[$keys]}' AND div = '" . USER_DIV . "'";
            $rslt = db_exec($sql) or errDie("Unable to update stock to Cubit.", SELF);
            if (isset($sers[$stkids[$keys]][$keys])) {
                ext_InSer($sers[$stkids[$keys]][$keys], $stkids[$keys], $pur['supname'], $pur['purnum'], "pur", $td);
                $serial = $sers[$stkids[$keys]][$keys];
                db_connect();
                $sql = "\n\t\t\t\t\tINSERT INTO pserec (\n\t\t\t\t\t\tpurid, purnum, stkid, serno, div\n\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t'{$purid}', '{$pur['purnum']}', '{$stkids[$keys]}', '{$serial}', '" . USER_DIV . "'\n\t\t\t\t\t)";
                $rslt = db_exec($sql) or errDie("Unable to update stock serials in Cubit.", SELF);
            }
            # Get selected stock
            $sql = "SELECT * FROM stock WHERE stkid = '{$stkids[$keys]}' AND div = '" . USER_DIV . "'";
            $stkRslt = db_exec($sql);
            $stk = pg_fetch_array($stkRslt);
            # stkid, stkcod, stkdes, trantype, edate, qty, csamt, details
            //$sdate = date("Y-m-d");
            stockrec($stk['stkid'], $stk['stkcod'], $stk['stkdes'], 'dt', $td, $qtys[$keys], $amt[$keys], "Stock Received from Supplier : {$sup['supname']} - Order No. {$pur['purnum']}");
            db_connect();
            $cspric = sprint($amt[$keys] / $qtys[$keys]);
            $sql = "\n\t\t\t\tINSERT INTO stockrec (\n\t\t\t\t\tedate, stkid, stkcod, stkdes, trantype, qty, csprice, \n\t\t\t\t\tcsamt, details, div\n\t\t\t\t) VALUES (\n\t\t\t\t\t'{$td}', '{$stk['stkid']}', '{$stk['stkcod']}', '{$stk['stkdes']}', 'purchase', '{$qtys[$keys]}', '{$amt[$keys]}', \n\t\t\t\t\t'{$cspric}', 'Stock Received from Supplier : {$sup['supname']} - Order No. {$pur['purnum']}', '" . USER_DIV . "'\n\t\t\t\t)";
            $recRslt = db_exec($sql);
            # Just wanted to fix the xxx.xxxxxxe-x value
            if ($stk['units'] > 0) {
                $csprice = round($stk['csamt'] / $stk['units'], 2);
            } else {
                $csprice = round($stk['csprice'], 2);
            }
            # update stock(csprice = (csamt/units))
            $sql = "\n\t\t\t\tUPDATE stock \n\t\t\t\tSET csprice = '{$csprice}', lcsprice = '{$cspric}' \n\t\t\t\tWHERE stkid = '{$stkids[$keys]}' AND div = '" . USER_DIV . "'";
            $rslt = db_exec($sql) or errDie("Unable to update stock to Cubit.", SELF);
        }
        # Keep records for transactions
        if (isset($totstkamt[$stk['whid']])) {
            $totstkamt[$stk['whid']] += $amt[$keys];
        } else {
            $totstkamt[$stk['whid']] = $amt[$keys];
        }
        db_connect();
        # check if there are any outstanding items
        $sql = "SELECT * FROM pur_items WHERE purid = '{$purid}' AND (qty - rqty) > '0' AND div = '" . USER_DIV . "'";
        $stkdRslt = db_exec($sql);
        # if none the set to received
        if (pg_numrows($stkdRslt) < 1) {
            # update surch_int(received = 'y')
            $sql = "UPDATE purchases SET received = 'y' WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
            $rslt = db_exec($sql) or errDie("Unable to update Orders in Cubit.", SELF);
        }
        if ($min_stock > 0) {
            $cost = sprint($unitcost[$keys] * $min_stock);
            db_conn("exten");
            $sql = "SELECT stkacc,cosacc FROM warehouses WHERE whid = '{$stk['whid']}' AND div = '" . USER_DIV . "'";
            $whRslt = db_exec($sql);
            $wh = pg_fetch_array($whRslt);
            $stockacc = $wh['stkacc'];
            $cosacc = $wh['cosacc'];
            db_connect();
            $Sl = "UPDATE stock SET csamt = (csamt - '{$cost}'),units=(units-'{$min_stock}') WHERE stkid='{$stkids[$keys]}'";
            $Ri = db_exec($Sl);
            writetrans($cosacc, $stockacc, $td, $refnum, $cost, "Cost Of Sales for stock sold before purchase {$pur['purnum']}");
            stockrec($stk['stkid'], $stk['stkcod'], $stk['stkdes'], 'ct', $td, 0, $cost, "Cost Of Sales for stock sold before purchase {$pur['purnum']}");
            db_connect();
            $Sl = "\n\t\t\t\tINSERT INTO pcost (\n\t\t\t\t\tpurnum, cost, qty, rqty, stkid\n\t\t\t\t) VALUES (\n\t\t\t\t\t'{$pur['purnum']}', '{$unitcost[$keys]}', '{$min_stock}', '0', '{$stk['stkid']}'\n\t\t\t\t)";
            $Ri = db_exec($Sl);
        }
    }
    //	$darr = explode ("-",$date);
    //	$cdate = "$darr[2]-$darr[1]-$darr[0]";
    #if non stock total is set, process the cost center
    if ($nonstot != "0") {
        $nonstot = sprint($nonstot);
        if ($cc_trantype != false) {
            $date = date("Y-m-d");
            $cc .= "\n\t\t\t\t<script>\n\t\t\t\t\tCostCenter('{$cc_trantype}', 'Non Stock Purchase', '{$date}', '{$stkd['description']}', {$nonstot}, '');\n\t\t\t\t</script>";
        } else {
            $cc .= "";
        }
    }
    if (isset($invoice)) {
        ###################VAT CALCS#######################
        $pur['delvat'] += 0;
        db_conn('cubit');
        $Sl = "SELECT * FROM vatcodes WHERE id='{$pur['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($shipchrg, $pur['vatinc'], $excluding, 0, $vd['vat_amount']);
        $vrs = explode("|", $vr);
        $ivat_tmp = $vrs[0];
        $iamount_tmp = $vrs[1];
        vatr($vd['id'], $td, "INPUT", $vd['code'], $refnum, "VAT Paid for Purchase No. {$pur['purnum']} from Supplier : {$pur['supname']}.", sprint(-$iamount_tmp), -$scvat);
        ####################################################
        db_conn("exten");
        $sql = "SELECT * FROM warehouses WHERE div = '" . USER_DIV . "'";
        $whRslt = db_exec($sql);
        $wh = pg_fetch_array($whRslt);
        db_connect();
        # update the supplier (make balance more)
        $sql = "UPDATE suppliers SET balance = (balance + '{$itotal}') WHERE supid = '{$pur['supid']}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
        $sql = "\n\t\t\tINSERT INTO sup_stmnt (\n\t\t\t\tsupid, edate, cacc, amount, descript, ref, ex, div\n\t\t\t) VALUES (\n\t\t\t\t'{$pur['supid']}', '{$pur['pdate']}', '{$wh['conacc']}', '{$itotal}', \n\t\t\t\t'Stock Received - Purchase {$pur['purnum']} Inv:{$pur['supinv']}', '{$refnum}', '{$pur['purnum']}', '" . USER_DIV . "'\n\t\t\t)";
        $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
        # Debit Stock Control and Credit Creditors control
        writetrans($wh['conacc'], $dept['credacc'], $td, $refnum, $isubtot, "Invoice Received for Purchase No. {$pur['purnum']} from Supplier : {$pur['supname']}.");
        # Transfer vat
        writetrans($vatacc, $dept['credacc'], $td, $refnum, $ivat, "VAT Paid for Purchase No. {$pur['purnum']} from Supplier : {$pur['supname']}.");
        # Ledger Records
        suppledger($pur['supid'], $wh['conacc'], $td, $pur['purid'], "Purchase No. {$pur['purnum']} received.", $itotal, 'c');
        db_connect();
        /* End Transactions */
        /* Make transaction record  for age analysis */
        db_connect();
        # update the supplier age analysis (make balance less)
        if (ext_ex2("suppurch", "purid", $pur['purnum'], "supid", $pur['supid'])) {
            # Found? Make amount less
            $sql = "UPDATE suppurch SET balance = (balance + '{$itotal}') WHERE supid = '{$pur['supid']}' AND purid = '{$pur['purnum']}' AND div = '" . USER_DIV . "'";
            $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
        } else {
            /* Make transaction record for age analysis */
            $sql = "\n\t\t\t\t\tINSERT INTO suppurch (\n\t\t\t\t\t\tsupid, purid, pdate, balance, div\n\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t'{$pur['supid']}', '{$pur['purnum']}', '{$pur['pdate']}', '{$itotal}', '" . USER_DIV . "'\n\t\t\t\t\t)";
            $purcRslt = db_exec($sql) or errDie("Unable to update Order information in Cubit.", SELF);
        }
        /* Make transaction record  for age analysis */
        # commit updating
        $sql = "UPDATE purchases SET iamount = iamount+'{$itotal}',ivat=ivat+'{$ivat}' WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update Order status in Cubit.", SELF);
        $sql = "SELECT SUM(iqty) FROM pur_items  WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
        $stktRslt = db_exec($sql);
        $data = pg_fetch_array($stktRslt);
        $left = $data['sum'];
        if ($left == 0) {
            /* Start moving if purchase */
            if ($pur['received'] == "y") {
                if (strlen($pur['appdate']) < 8) {
                    $pur['appdate'] = date("Y-m-d");
                }
                # copy purchase
                db_conn($pur['prd']);
                $sql = "\n\t\t\t\t\tINSERT INTO purchases (\n\t\t\t\t\t\tpurid, deptid, supid, supname, supaddr, supno, \n\t\t\t\t\t\tterms, pdate, ddate, shipchrg, subtot, total, \n\t\t\t\t\t\tbalance, vatinc, vat, shipping, remarks, refno, received, done, \n\t\t\t\t\t\tdiv, purnum, supinv, ordernum, appname, appdate\n\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t'{$purid}', '{$pur['deptid']}', '{$pur['supid']}',  '{$pur['supname']}', '{$pur['supaddr']}', '{$pur['supno']}', \n\t\t\t\t\t\t'{$pur['terms']}', '{$pur['pdate']}', '{$pur['ddate']}', '{$pur['shipchrg']}', '{$pur['subtot']}', '{$pur['total']}', \n\t\t\t\t\t\t'0', '{$pur['vatinc']}', '{$pur['vat']}', '{$pur['shipping']}', '{$remarks}', '{$pur['refno']}', 'y', 'y', \n\t\t\t\t\t\t'" . USER_DIV . "', '{$pur['purnum']}', '{$supinv}', '{$pur['ordernum']}', '{$pur['appname']}', '{$pur['appdate']}'\n\t\t\t\t\t)";
                $rslt = db_exec($sql) or errDie("Unable to insert Order to Cubit.", SELF);
                /*-- Cost varience -- */
                //$nsubtot = sprint($pur['total'] - $pur['vat']);
                $nsubtot = sprint($p['iamount'] - $p['ivat']);
                if ($p['rsubtot'] > $nsubtot) {
                    $diff = sprint($p['rsubtot'] - $nsubtot);
                    # Debit Stock Control and Credit Creditors control
                    writetrans($wh['conacc'], $cvacc, $td, $refnum, $diff, "Cost Variance for Stock Received on Purchase No. {$pur['purnum']} from Supplier : {$sup['supname']}.");
                } elseif ($nsubtot > $p['rsubtot']) {
                    $diff = sprint($nsubtot - $pur['rsubtot']);
                    # Debit Stock Control and Credit Creditors control
                    writetrans($cvacc, $wh['conacc'], $td, $refnum, $diff, "Cost Variance for Stock Received on Purchase No. {$pur['purnum']} from Supplier : {$sup['supname']}.");
                }
                /*-- End Cost varience -- */
                db_connect();
                # Get selected stock
                $sql = "SELECT * FROM pur_items WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
                $stktcRslt = db_exec($sql);
                while ($stktc = pg_fetch_array($stktcRslt)) {
                    # Insert purchase items
                    db_conn($pur['prd']);
                    $sql = "\n\t\t\t\t\t\tINSERT INTO pur_items (\n\t\t\t\t\t\t\tpurid, whid, stkid, qty, rqty, unitcost, \n\t\t\t\t\t\t\tamt, svat, ddate, div\n\t\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t\t'{$purid}', '{$stktc['whid']}', '{$stktc['stkid']}', '{$stktc['qty']}', '{$stktc['rqty']}', '{$stktc['unitcost']}', \n\t\t\t\t\t\t\t'{$stktc['amt']}', '{$stktc['svat']}', '{$stktc['ddate']}', '" . USER_DIV . "'\n\t\t\t\t\t\t)";
                    $rslt = db_exec($sql) or errDie("Unable to insert Order items to Cubit.", SELF);
                }
                # begin updating
                //pglib_transaction ("BEGIN") or errDie("Unable to start a database transaction.",SELF);
                db_connect();
                # Remove the purchase from running DB
                $sql = "DELETE FROM purchases WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
                $delRslt = db_exec($sql) or errDie("Unable to update int purchases information in Cubit.", SELF);
                # Record where purchase is
                $sql = "INSERT INTO movpurch(purtype, purnum, prd, div) VALUES('loc', '{$pur['purnum']}', '{$pur['prd']}', '" . USER_DIV . "')";
                $movRslt = db_exec($sql) or errDie("Unable to update int purchases information in Cubit.", SELF);
                # Remove those purchase items from running DB
                $sql = "DELETE FROM pur_items WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
                $delRslt = db_exec($sql) or errDie("Unable to update int purchases information in Cubit.", SELF);
                /* End moving purchase received */
                # commit updating
                //pglib_transaction ("COMMIT") or errDie("Unable to commit a database transaction.",SELF);
            } else {
                # insert Order to DB
                $sql = "UPDATE purchases SET invcd = 'y',supinv='{$pur['supinv']}' WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
                $rslt = db_exec($sql) or errDie("Unable to update Order status in Cubit.", SELF);
            }
        }
    }
    if (strlen($refno) > 0) {
        if (strlen($pur['refno']) > 0) {
            $refno = "{$pur['refno']}-{$refno}";
        } else {
            $refno = $refno;
        }
    } else {
        $refno = $pur['refno'];
    }
    db_connect();
    # Update purchase on the DB
    if ($pur['part'] == 'y') {
        $sql = "\n\t\t\tUPDATE purchases \n\t\t\tSET rsubtot = (rsubtot + '{$resub}'), refno = '{$refno}', remarks = '{$remarks}', edit = 1 \n\t\t\tWHERE purid = '{$purid}'";
    } else {
        $sql = "\n\t\t\tUPDATE purchases \n\t\t\tSET part = 'y', rsubtot = (rsubtot + '{$resub}'), refno = '{$refno}', remarks = '{$remarks}', edit = 1 \n\t\t\tWHERE purid = '{$purid}'";
    }
    $rslt = db_exec($sql) or errDie("Unable to update Order in Cubit.", SELF);
    /* Transactions */
    db_conn(PRD_DB);
    # get last ref number
    //$refnum = getrefnum();
    /* - Start Hooks - */
    /* - End Hooks - */
    # Record transaction  from data
    foreach ($totstkamt as $whid => $wamt) {
        # get whouse info
        db_conn("exten");
        $sql = "SELECT stkacc,conacc FROM warehouses WHERE whid = '{$whid}' AND div = '" . USER_DIV . "'";
        $whRslt = db_exec($sql);
        if (pg_num_rows($whRslt) < 1) {
            $sql = "SELECT stkacc,conacc FROM warehouses";
            $whRslt = db_exec($sql);
            $wh = pg_fetch_array($whRslt);
            $wh['stkacc'] = $whid;
        } else {
            $wh = pg_fetch_array($whRslt);
        }
        # Debit Stock and Credit Stock control
        writetrans($wh['stkacc'], $wh['conacc'], $td, $refnum, $wamt, "Stock Received for Purchase No. {$pur['purnum']} from Supplier : {$sup['supname']}.");
    }
    # commit updating
    /*** pglib_transaction ("COMMIT") or errDie("Unable to commit a database transaction.",SELF);
    
    	/* Start moving if Order received and invoiced */
    # Get purchase info
    db_connect();
    $sql = "SELECT * FROM purchases WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
    $purRslt = db_exec($sql) or errDie("Unable to get Order information");
    if (pg_numrows($purRslt) < 1) {
        return "<li> - Order Not Found</li>";
    }
    $pur = pg_fetch_array($purRslt);
    if ($pur['received'] == "y" && $pur['invcd'] == 'y') {
        if (strlen($pur['appdate']) < 8) {
            $pur['appdate'] = date("Y-m-d");
        }
        # copy purchase
        db_conn(PRD_DB);
        $sql = "\n\t\t\t\tINSERT INTO purchases (\n\t\t\t\t\tpurid, deptid, supid, supname, supaddr, supno, \n\t\t\t\t\tterms, pdate, ddate, shipchrg, subtot, total, balance, \n\t\t\t\t\tvatinc, vat, shipping, remarks, refno, received, done, div, \n\t\t\t\t\tpurnum, supinv, ordernum, appname, appdate, delvat\n\t\t\t\t) VALUES (\n\t\t\t\t\t'{$purid}', '{$pur['deptid']}', '{$pur['supid']}',  '{$pur['supname']}', '{$pur['supaddr']}', '{$pur['supno']}', \n\t\t\t\t\t'{$pur['terms']}', '{$pur['pdate']}', '{$pur['ddate']}', '{$pur['shipchrg']}', '{$pur['subtot']}', '{$pur['total']}', '0', \n\t\t\t\t\t'{$pur['vatinc']}', '{$pur['vat']}', '{$pur['shipping']}', '{$pur['remarks']}', '{$pur['refno']}', 'y', 'y', '" . USER_DIV . "', \n\t\t\t\t\t'{$pur['purnum']}', '{$pur['supinv']}', '{$pur['ordernum']}', '{$pur['appname']}', '{$pur['appdate']}', '{$pur['delvat']}'\n\t\t\t\t)";
        $rslt = db_exec($sql) or errDie("Unable to insert Order to Cubit.", SELF);
        /*-- Cost varience -- */
        $nsubtot = sprint($pur['total'] - $pur['vat']);
        if ($pur['rsubtot'] > $nsubtot) {
            $diff = sprint($pur['rsubtot'] - $nsubtot);
            # Debit Stock Control and Credit Creditors control
            writetrans($wh['conacc'], $cvacc, $td, $refnum, $diff, "Cost Variance for Stock Received on Purchase No. {$pur['purnum']} from Supplier : {$sup['supname']}.");
        } elseif ($nsubtot > $pur['rsubtot']) {
            $diff = sprint($nsubtot - $pur['rsubtot']);
            # Debit Stock Control and Credit Creditors control
            writetrans($cvacc, $wh['conacc'], $td, $refnum, $diff, "Cost Variance for Stock Received on Purchase No. {$pur['purnum']} from Supplier : {$sup['supname']}.");
        }
        /*-- End Cost varience -- */
        db_connect();
        # Get selected stock
        $sql = "SELECT * FROM pur_items WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
        $stktcRslt = db_exec($sql);
        while ($stktc = pg_fetch_array($stktcRslt)) {
            # Insert purchase items
            db_conn(PRD_DB);
            $sql = "\n\t\t\t\t\tINSERT INTO pur_items (\n\t\t\t\t\t\tpurid, whid, stkid, qty, rqty, unitcost, \n\t\t\t\t\t\tamt, svat, ddate, div, vatcode, \n\t\t\t\t\t\taccount, description, udiscount\n\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t'{$purid}', '{$stktc['whid']}', '{$stktc['stkid']}', '{$stktc['qty']}', '{$stktc['rqty']}', '{$stktc['unitcost']}', \n\t\t\t\t\t\t'{$stktc['amt']}', '{$stktc['svat']}', '{$stktc['ddate']}', '" . USER_DIV . "','{$stktc['vatcode']}', \n\t\t\t\t\t\t'{$stktc['account']}', '{$stktc['description']}', '{$stktc['udiscount']}'\n\t\t\t\t\t)";
            $rslt = db_exec($sql) or errDie("Unable to insert Order items to Cubit.", SELF);
        }
        db_connect();
        # Remove the purchase from running DB
        $sql = "DELETE FROM purchases WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
        $delRslt = db_exec($sql) or errDie("Unable to update int Orders information in Cubit.", SELF);
        # Record where purchase is
        $sql = "INSERT INTO movpurch(purtype, purnum, prd, div) VALUES('loc', '{$pur['purnum']}', '{$pur['prd']}', '" . USER_DIV . "')";
        $movRslt = db_exec($sql) or errDie("Unable to update int Orders information in Cubit.", SELF);
        # Remove those purchase items from running DB
        $sql = "DELETE FROM pur_items WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
        $delRslt = db_exec($sql) or errDie("Unable to update int Orders information in Cubit.", SELF);
    }
    pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
    /* End moving purchase received */
    if (isset($gds_note) and strlen($gds_note) > 0) {
        $cc .= "\n\t\t\t<script>\n\t\t\t\tprinter(\"" . SELF . "?key=recv_print&purid={$purid}\");\n\t\t\t</script>";
    }
    // Final Layout
    $write = "\n\t\t{$cc}\n\t\t<table " . TMPL_tblDflts . ">\n\t\t\t<tr>\n\t\t\t\t<th>Order received</th>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Order receipt from Supplier <b>{$sup['supname']}</b> has been recorded.</td>\n\t\t\t</tr>\n\t\t</table>\n\t\t<p>\n\t\t<table " . TMPL_tblDflts . ">\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='" . bg_class() . "'>\n\t\t\t\t<td><a href='purchase-new.php'>New Purchase</a></td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td><a href='purchase-view.php'>View Orders</a></td>\n\t\t\t</tr>\n\t\t\t<script>document.write(getQuicklinkSpecial());</script>\n\t\t</table>";
    return $write;
}
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($supid, "num", 1, 20, "Invalid Supplier 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
    $supRslt = get("cubit", "*", "suppliers", "supid", $supid);
    $sup = pg_fetch_array($supRslt);
    db_conn("exten");
    # Get debtors control account
    $sql = "SELECT credacc FROM departments WHERE deptid ='{$sup['deptid']}' AND div = '" . USER_DIV . "'";
    $deptRslt = db_exec($sql);
    $dept = pg_fetch_array($deptRslt);
    pglib_transaction("BEGIN");
    db_connect();
    $Sl = "\n\t\tINSERT INTO sup_stmnt (\n\t\t\tsupid, amount, edate, descript, ref, cacc, div\n\t\t) VALUES (\n\t\t\t'{$supid}', '-{$amount}', '{$date}', 'Cash Payment', '0', '{$cashacc}', '" . USER_DIV . "'\n\t\t)";
    $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 - '{$amount}'::numeric(13,2)) WHERE supid = '{$supid}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
    suppledger($supid, $cashacc, $date, 0, "Cash Payment", $amount, "d");
    suppDT($amount, $supid);
    # 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 supplier: {$sup['supname']}', '" . USER_DIV . "'\n\t\t)";
    $Rslt = db_exec($sql) or errDie("Unable to add bank payment to database.", SELF);
    $refnum = getrefnum();
    writetrans($dept['credacc'], $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 supplier : {$sup['supname']} 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;
}
function write($_POST)
{
    # Get vars
    extract($_POST);
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($purid, "num", 1, 20, "Invalid purchase number.");
    $v->isOk($remarks, "string", 0, 255, "Invalid Remarks.");
    $v->isOk($refno, "string", 0, 255, "Invalid Delivery Reference No.");
    $v->isOk($subtot, "float", 1, 20, "Invalid Sub Total.");
    $v->isOk($shipping, "float", 1, 20, "Invalid Delivery Charges.");
    $v->isOk($vat, "float", 1, 20, "Invalid VAT");
    $v->isOk($total, "float", 1, 20, "Invalid Total");
    # used to generate errors
    $error = "asa@";
    # display errors, if any
    $err = "";
    if ($v->isError()) {
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $err .= "<li class='err'>" . $e["msg"] . "</li>";
        }
        return details($_POST, $err);
    }
    # Get purchase info
    db_connect();
    $sql = "SELECT * FROM purchases WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
    $purRslt = db_exec($sql) or errDie("Unable to get purchase information");
    if (pg_numrows($purRslt) < 1) {
        return "<li>- purchase Not Found</li>";
    }
    $pur = pg_fetch_array($purRslt);
    # check if purchase has been received
    if ($pur['received'] == "y") {
        $error = "<li class='err'> Error : purchase number <b>{$purid}</b> has already been received.</li>";
        $error .= "<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $error;
    }
    # Get selected supplier info
    db_connect();
    $sql = "SELECT * FROM suppliers WHERE supid = '{$pur['supid']}' AND div = '" . USER_DIV . "'";
    $supRslt = db_exec($sql) or errDie("Unable to get customer information");
    if (pg_numrows($supRslt) < 1) {
        // code here
    } else {
        $sup = pg_fetch_array($supRslt);
    }
    # Get department info
    db_conn("exten");
    $sql = "SELECT * FROM departments WHERE deptid = '{$pur['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);
    }
    $sdate = date("Y-m-d");
    $date = $pur["pdate"];
    $refnum = getrefnum();
    # Get warehouse name
    db_conn("exten");
    $sql = "SELECT * FROM warehouses WHERE div = '" . USER_DIV . "'";
    $whRslt = db_exec($sql);
    $wh = pg_fetch_array($whRslt);
    $subtot = sprint($subtot);
    $shipping = sprint($shipping);
    $vat = sprint($vat);
    $total = sprint($total);
    pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
    # get selected stock in this purchase
    db_connect();
    $sql = "SELECT * FROM pur_items  WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
    $stktRslt = db_exec($sql);
    while ($stkt = pg_fetch_array($stktRslt)) {
        $cqty = $stkt['qty'] - $stkt['rqty'];
        # update stock(ordered - qty)
        $sql = "UPDATE stock SET ordered = (ordered - '{$cqty}')  WHERE stkid = '{$stkt['stkid']}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update stock to Cubit.", SELF);
    }
    /* - Start Hooks - */
    $vatacc = gethook("accnum", "salesacc", "name", "VAT");
    $cvacc = gethook("accnum", "pchsacc", "name", "Cost Variance");
    /* - End Hooks - */
    # Record the payment on the statement
    db_connect();
    db_connect();
    # update the supplier (make balance more)
    $sql = "UPDATE suppliers SET balance = (balance + '{$total}') WHERE supid = '{$pur['supid']}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
    $sql = "\n\t\t\tINSERT INTO sup_stmnt (\n\t\t\t\tsupid, edate, cacc, amount, descript, ref, ex, div\n\t\t\t) VALUES (\n\t\t\t\t'{$pur['supid']}', '{$date}', '{$dept['credacc']}', '{$total}', 'Stock Received - Purchase {$pur['purnum']}', '{$refnum}','{$pur['purnum']}','" . USER_DIV . "'\n\t\t\t)";
    $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
    # Debit Stock Control and Credit Creditors control
    writetrans($wh['conacc'], $dept['credacc'], $date, $refnum, $total - $vat, "Invoice Received for Purchase No. {$pur['purnum']} from Supplier : {$pur['supname']}.");
    # Transfer vat
    writetrans($vatacc, $dept['credacc'], $date, $refnum, $vat, "Vat Paid for Purchase No. {$pur['purnum']} from Supplier : {$pur['supname']}.");
    # Ledger Records
    suppledger($pur['supid'], $wh['conacc'], $date, $pur['purid'], "Purchase No. {$pur['purnum']} received.", $total, 'c');
    db_connect();
    /* End Transactions */
    /* Make transaction record  for age analysis */
    db_connect();
    # update the supplier age analysis (make balance less)
    if (ext_ex2("suppurch", "purid", $pur['purnum'], "supid", $pur['supid'])) {
        # Found? Make amount less
        $sql = "UPDATE suppurch SET balance = (balance + '{$total}') WHERE supid = '{$pur['supid']}' AND purid = '{$pur['purnum']}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
    } else {
        /* Make transaction record for age analysis */
        $sql = "INSERT INTO suppurch(supid, purid, pdate, balance, div) VALUES('{$pur['supid']}', '{$pur['purnum']}', '{$date}', '{$total}', '" . USER_DIV . "')";
        $purcRslt = db_exec($sql) or errDie("Unable to update Order information in Cubit.", SELF);
    }
    /* Make transaction record  for age analysis */
    # commit updating
    pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
    /* Start moving if purchase */
    # copy purchase
    db_conn($pur['prd']);
    $sql = "\n\t\tINSERT INTO purchases (\n\t\t\tpurid, deptid, supid, supname, supaddr, supno, terms, pdate, ddate, shipchrg, subtot, total, balance, vatinc, vat, shipping, remarks, refno, received, done, div, purnum, supinv\n\t\t) VALUES (\n\t\t\t'{$purid}', '{$pur['deptid']}', '{$pur['supid']}', '{$pur['supname']}', '{$pur['supaddr']}', '{$pur['supno']}', '{$pur['terms']}', '{$pur['pdate']}', '{$pur['ddate']}', '{$pur['shipchrg']}', '{$subtot}', '{$total}', '0', '{$pur['vatinc']}', '{$vat}', '{$shipping}', '{$remarks}', '{$refno}', 'y', 'y', '" . USER_DIV . "', '{$pur['purnum']}','{$pur['supinv']}'\n\t\t)";
    $rslt = db_exec($sql) or errDie("Unable to insert Purchase to Cubit.", SELF);
    /*-- Cost varience -- */
    $nsubtot = $total - $vat;
    if ($pur['rsubtot'] > $nsubtot) {
        $diff = $pur['rsubtot'] - $nsubtot;
        # Debit Stock Control and Credit Creditors control
        writetrans($wh['conacc'], $cvacc, $date, $refnum, $diff, "Cost Variance for Stock Received on Purchase No. {$pur['purnum']} from Supplier : {$sup['supname']}.");
    } elseif ($nsubtot > $pur['rsubtot']) {
        $diff = $nsubtot - $pur['rsubtot'];
        # Debit Stock Control and Credit Creditors control
        writetrans($cvacc, $wh['conacc'], $date, $refnum, $diff, "Cost Variance for Stock Received on Purchase No. {$pur['purnum']} from Supplier : {$sup['supname']}.");
    }
    /*-- End Cost varience -- */
    db_connect();
    # Get selected stock
    $sql = "SELECT * FROM pur_items WHERE purid = '{$purid}' AND (rqty) > 0 AND div = '" . USER_DIV . "'";
    $stktcRslt = db_exec($sql);
    while ($stktc = pg_fetch_array($stktcRslt)) {
        $stktc['amt'] = $stktc['unitcost'] * $stktc['rqty'];
        # Insert purchase items
        db_conn($pur['prd']);
        $sql = "\n\t\t\tINSERT INTO pur_items (\n\t\t\t\tpurid, whid, stkid, qty, rqty, unitcost, amt, ddate, div, vatcode\n\t\t\t) VALUES (\n\t\t\t\t'{$purid}', '{$stktc['whid']}', '{$stktc['stkid']}', '{$stktc['rqty']}', '{$stktc['rqty']}', '{$stktc['unitcost']}', '{$stktc['amt']}', '{$stktc['ddate']}', '" . USER_DIV . "', '{$stktc['vatcode']}'\n\t\t\t)";
        $rslt = db_exec($sql) or errDie("Unable to insert purchase items to Cubit.", SELF);
    }
    # begin updating
    pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
    db_connect();
    # Remove the purchase from running DB
    $sql = "DELETE FROM purchases WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
    $delRslt = db_exec($sql) or errDie("Unable to update int purchases information in Cubit.", SELF);
    # Record where purchase is
    $sql = "INSERT INTO movpurch(purtype, purnum, prd, div) VALUES('loc', '{$pur['purnum']}', '{$pur['prd']}', '" . USER_DIV . "')";
    $movRslt = db_exec($sql) or errDie("Unable to update int purchases information in Cubit.", SELF);
    # Remove those purchase items from running DB
    $sql = "DELETE FROM pur_items WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
    $delRslt = db_exec($sql) or errDie("Unable to update int purchases information in Cubit.", SELF);
    /* End moving purchase received */
    # commit updating
    pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
    // Final Layout
    $write = "\n\t\t<table " . TMPL_tblDflts . ">\n\t\t\t<tr>\n\t\t\t\t<th>Purchase Completed</th>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Purchase receipt from Supplier <b>{$pur['supname']}</b> has been completed.</td>\n\t\t\t</tr>\n\t\t</table>\n\t\t<p>\n\t\t<table " . TMPL_tblDflts . ">\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='" . bg_class() . "'>\n\t\t\t\t<td><a href='purchase-view.php'>View purchases</a></td>\n\t\t\t</tr>\n\t\t\t<script>document.write(getQuicklinkSpecial());</script>\n\t\t</table>";
    return $write;
}
function write($_POST)
{
    #get vars
    extract($_POST);
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($purid, "num", 1, 20, "Invalid Order number.");
    $v->isOk($refno, "string", 0, 255, "Invalid Delivery Reference number.");
    $v->isOk($remarks, "string", 0, 255, "Invalid Remarks.");
    # used to generate errors
    $error = "asa@";
    # display errors, if any
    $err = "";
    if ($v->isError()) {
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $err .= "<li class='err'>" . $e["msg"] . "</li>";
        }
        return details($_POST, $err);
    }
    # Get Order info
    db_connect();
    $sql = "SELECT * FROM purch_int WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
    $purRslt = db_exec($sql) or errDie("Unable to get Order information");
    if (pg_numrows($purRslt) < 1) {
        return "<li>- Order Not Found</li>";
    }
    $pur = pg_fetch_array($purRslt);
    # CHECK IF THIS DATE IS IN THE BLOCKED RANGE
    $blocked_date_from = getCSetting("BLOCKED_FROM");
    $blocked_date_to = getCSetting("BLOCKED_TO");
    if (strtotime($pur['pdate']) >= strtotime($blocked_date_from) and strtotime($pur['pdate']) <= 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>";
    }
    # check if Order has been received
    if ($pur['invcd'] == "y") {
        $error = "<li class='err'> Error : purchase number <b>{$pur['purnum']}</b> has already been invoiced.</li>";
        $error .= "<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $error;
    }
    # Get selected supplier info
    db_connect();
    $sql = "SELECT * FROM suppliers WHERE supid = '{$pur['supid']}' AND div = '" . USER_DIV . "'";
    $supRslt = db_exec($sql) or errDie("Unable to get customer information");
    if (pg_numrows($supRslt) < 1) {
        // code here
    } else {
        $sup = pg_fetch_array($supRslt);
    }
    # get department
    db_conn("exten");
    $sql = "SELECT * FROM departments WHERE deptid = '{$pur['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);
    }
    # Get warehouse name
    db_conn("exten");
    $sql = "SELECT * FROM warehouses WHERE div = '" . USER_DIV . "'";
    $whRslt = db_exec($sql);
    $wh = pg_fetch_array($whRslt);
    # insert Order to DB
    db_connect();
    # begin updating
    pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
    /* --- Transactions --- */
    db_conn(PRD_DB);
    $refnum = getrefnum();
    /* - Start Hooks - */
    $vatacc = gethook("accnum", "salesacc", "name", "VAT");
    $cvacc = gethook("accnum", "pchsacc", "name", "Cost Variance");
    /* - End Hooks - */
    # Record the payment on the statement
    db_connect();
    $sdate = date("Y-m-d");
    $taxamt = $pur['tax'] * -1;
    $ltotal = sprint($pur['total'] * $pur['xrate']);
    $ltax = sprint($pur['tax'] * $pur['xrate']);
    db_connect();
    # update all supplies xchange rate first
    xrate_update($pur['fcid'], $pur['xrate'], "suppurch", "id");
    sup_xrate_update($pur['fcid'], $pur['xrate']);
    db_connect();
    # Update the supplier (make balance more)
    $sql = "UPDATE suppliers SET balance = (balance + '{$ltotal}'), fbalance = (fbalance + '{$pur['total']}') WHERE supid = '{$pur['supid']}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
    $DAte = date("Y-m-d");
    $sql = "INSERT INTO sup_stmnt(supid, edate, cacc, amount, descript, ref, ex, div) VALUES('{$pur['supid']}','{$pur['pdate']}', '{$dept['credacc']}','{$pur['total']}','International - Stock Received', '{$refnum}','{$pur['purnum']}', '" . USER_DIV . "')";
    $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
    $Sl = "SELECT * FROM vatcodes WHERE id='{$pur['jobnum']}'";
    $Ri = db_exec($Sl);
    if (pg_num_rows($Ri) < 1) {
        return "Please select the vatcode for all your stock.";
    }
    $vd = pg_fetch_array($Ri);
    vatr($vd['id'], $pur['pdate'], "INPUT", $vd['code'], $refnum, "VAT for Purchase No. {$pur['purnum']}", -($ltotal + $ltax), -$ltax);
    # Debit Stock Control and Credit Creditors control
    writetrans($wh['conacc'], $dept['credacc'], $pur['pdate'], $refnum, $ltotal - $ltax, "Invoice Received for Purchase No. {$pur['purnum']} from Supplier : {$sup['supname']}.");
    # Debit bank and credit the account involved
    writetrans($vatacc, $dept['credacc'], $pur['pdate'], $refnum, $ltax, "Tax Paid on International Orders No. {$pur['purnum']} from Supplier {$sup['supname']}.");
    # Ledger Records
    suppledger($pur['supid'], $wh['stkacc'], $pur['pdate'], $pur['purid'], "International Order No. {$pur['purnum']} received.", $ltotal, 'c');
    db_connect();
    /* --- End Transactions --- */
    /* Make transaction record  for age analysis */
    $sql = "INSERT INTO suppurch(supid, purid, pdate, balance, fcid, fbalance, div) VALUES('{$pur['supid']}', '{$pur['purnum']}', '{$pur['pdate']}', '{$ltotal}', '{$pur['fcid']}', '{$pur['total']}', '" . USER_DIV . "')";
    $purcRslt = db_exec($sql) or errDie("Unable to update int Orders information in Cubit.", SELF);
    /* Make transaction record  for age analysis */
    # commit updating
    pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
    /* Start moving if Order received and invoiced */
    # Get Order info
    db_connect();
    $sql = "SELECT * FROM purch_int WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
    $purRslt = db_exec($sql) or errDie("Unable to get Order information");
    if (pg_numrows($purRslt) < 1) {
        return "<li>- Order Not Found</li>";
    }
    $pur = pg_fetch_array($purRslt);
    if ($pur['received'] == "y") {
        # Copy Order
        db_conn($pur['prd']);
        $sql = "INSERT INTO purch_int(purid, deptid, supid, supaddr, terms, pdate, ddate, xrate, fcid, curr, tax, shipchrg, fshipchrg, duty, subtot, total, balance, fbalance, remarks, refno, received, done, div, purnum)";
        $sql .= " VALUES('{$purid}', '{$pur['deptid']}', '{$pur['supid']}',  '{$pur['supaddr']}', '{$pur['terms']}', '{$pur['pdate']}', '{$pur['ddate']}', '{$pur['xrate']}', '{$pur['fcid']}', '{$pur['curr']}', '{$pur['tax']}', '{$pur['shipchrg']}', '{$pur['fshipchrg']}', '{$pur['duty']}', '{$pur['subtot']}', '{$pur['total']}', '0', '{$pur['fbalance']}', '{$pur['remarks']}', '{$pur['refno']}', 'y', 'y', '" . USER_DIV . "', '{$pur['purnum']}')";
        $rslt = db_exec($sql) or errDie("Unable to insert Order to Cubit.", SELF);
        /*-- Cost varience -- */
        $nsubtot = sprint($pur['total'] - $pur['tax']);
        $nsubtot = sprint($nsubtot * $pur['xrate']);
        if ($pur['rlsubtot'] > $nsubtot) {
            $diff = sprint($pur['rlsubtot'] - $nsubtot);
            # Debit Stock Control and Credit Creditors control
            writetrans($wh['conacc'], $cvacc, $pur['pdate'], $refnum, $diff, "Cost Variance for Stock Received on Purchase No. {$pur['purnum']} from Supplier : {$sup['supname']}.");
        } elseif ($nsubtot > $pur['rlsubtot']) {
            $diff = sprint($nsubtot - $pur['rlsubtot']);
            # Debit Stock Control and Credit Creditors control
            writetrans($cvacc, $wh['conacc'], $pur['pdate'], $refnum, $diff, "Cost Variance for Stock Received on Purchase No. {$pur['purnum']} from Supplier : {$sup['supname']}.");
        }
        /*-- End Cost varience -- */
        db_connect();
        # Get selected stock
        $sql = "SELECT * FROM purint_items WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
        $stktcRslt = db_exec($sql);
        while ($stktc = pg_fetch_array($stktcRslt)) {
            # Insert Order items
            db_conn($pur['prd']);
            $sql = "INSERT INTO purint_items(purid, whid, stkid, qty, unitcost, cunitcost, duty, dutyp, amt, ddate, recved, div) VALUES('{$purid}', '{$stktc['whid']}', '{$stktc['stkid']}', '{$stktc['qty']}', '{$stktc['unitcost']}', '{$stktc['cunitcost']}', '{$stktc['duty']}', '{$stktc['dutyp']}', '{$stktc['amt']}', '{$stktc['ddate']}', 'y', '" . USER_DIV . "')";
            $rslt = db_exec($sql) or errDie("Unable to insert Order items to Cubit.", SELF);
        }
        db_connect();
        # Remove the Order from running DB
        $sql = "DELETE FROM purch_int WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
        $delRslt = db_exec($sql) or errDie("Unable to update int Orders information in Cubit.", SELF);
        # Record where Order is
        $sql = "INSERT INTO movpurch(purtype, purnum, prd, div) VALUES('int', '{$pur['purnum']}', '{$pur['prd']}', '" . USER_DIV . "')";
        $movRslt = db_exec($sql) or errDie("Unable to update int Orders information in Cubit.", SELF);
        # Remove those Order items from running DB
        $sql = "DELETE FROM purint_items WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
        $delRslt = db_exec($sql) or errDie("Unable to update int Orders information in Cubit.", SELF);
    } else {
        # Insert Order to DB
        $sql = "UPDATE purch_int SET invcd = 'y' WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update Order status in Cubit.", SELF);
    }
    /* End moving Order received */
    // Final Layout
    $write = "\n\t\t<table " . TMPL_tblDflts . ">\n\t\t\t<tr>\n\t\t\t\t<th>International Purchase Invoiced</th>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Purchase Invoice from Supplier <b>{$sup['supname']}</b> has been recorded.</td>\n\t\t\t</tr>\n\t\t</table>\n\t\t<p>\n\t\t<table " . TMPL_tblDflts . ">\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='" . bg_class() . "'>\n\t\t\t\t<td><a href='purch-int-view.php'>View International Orders</a></td>\n\t\t\t</tr>\n\t\t\t<script>document.write(getQuicklinkSpecial());</script>\n\t\t</table>";
    return $write;
}
Ejemplo n.º 17
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;
}
function write($_POST)
{
    # Get vars
    foreach ($_POST as $key => $value) {
        ${$key} = $value;
    }
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($purid, "num", 1, 20, "Invalid Order number.");
    $v->isOk($refno, "string", 0, 255, "Invalid Delivery Reference No.");
    $v->isOk($remarks, "string", 0, 255, "Invalid Remarks.");
    $v->isOk($supinv, "string", 0, 255, "Invalid supp inv.");
    # used to generate errors
    $error = "asa@";
    # display errors, if any
    $err = "";
    if ($v->isError()) {
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $err .= "<li class=err>" . $e["msg"];
        }
        return details($_POST, $err);
    }
    pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
    # Get purchase info
    db_connect();
    $sql = "SELECT * FROM purchases WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
    $purRslt = db_exec($sql) or errDie("Unable to get purchase information");
    if (pg_numrows($purRslt) < 1) {
        return "<li>- purchase Not Found</li>";
    }
    $pur = pg_fetch_array($purRslt);
    $td = $pur['pdate'];
    # check if purchase has been received
    if ($pur['invcd'] == "y") {
        $error = "<li class=err> Error : purchase number <b>{$pur['purnum']}</b> has already been invoiced.";
        $error .= "<p><input type=button onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $error;
    }
    # Get selected supplier info
    db_connect();
    $sql = "SELECT * FROM suppliers WHERE supid = '{$pur['supid']}' AND div = '" . USER_DIV . "'";
    $supRslt = db_exec($sql) or errDie("Unable to get customer information");
    if (pg_numrows($supRslt) < 1) {
        // code here
    } else {
        $sup = pg_fetch_array($supRslt);
    }
    # Get department info
    db_conn("exten");
    $sql = "SELECT * FROM departments WHERE deptid = '{$pur['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);
    }
    # Get warehouse name
    db_conn("exten");
    $sql = "SELECT * FROM warehouses WHERE div = '" . USER_DIV . "'";
    $whRslt = db_exec($sql);
    $wh = pg_fetch_array($whRslt);
    //pglib_transaction ("BEGIN") or errDie("Unable to start a database transaction.",SELF);
    # get selected stock in this purchase
    db_connect();
    $sql = "SELECT * FROM pur_items  WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
    $Ri = db_exec($sql);
    $refnum = getrefnum();
    while ($id = pg_fetch_array($Ri)) {
        db_connect();
        # get selamt from selected stock
        $sql = "SELECT * FROM stock WHERE stkid = '{$id['stkid']}' AND div = '" . USER_DIV . "'";
        $stkRslt = db_exec($sql);
        $stk = pg_fetch_array($stkRslt);
        $Sl = "SELECT * FROM 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 ($id['svat'] == 0) {
            $exvat = "y";
        } else {
            $exvat = "";
        }
        $vr = pvatcalc($id['amt'], $pur['vatinc'], $exvat);
        $vrs = explode("|", $vr);
        $ivat = $vrs[0];
        $iamount = $vrs[1];
        vatr($vd['id'], $pur['pdate'], "INPUT", $vd['code'], $refnum, "Purchase {$pur['purnum']} Supplier : {$pur['supname']}.", $iamount, $ivat);
    }
    /* - Start Hooks - */
    $vatacc = gethook("accnum", "salesacc", "name", "VAT");
    $cvacc = gethook("accnum", "pchsacc", "name", "Cost Variance");
    /* - End Hooks - */
    # Record the payment on the statement
    db_connect();
    $sdate = date("Y-m-d");
    $DAte = date("Y-m-d");
    db_connect();
    # update the supplier (make balance more)
    $sql = "UPDATE suppliers SET balance = (balance + '{$pur['total']}') WHERE supid = '{$pur['supid']}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
    $sql = "INSERT INTO sup_stmnt(supid, edate, cacc, amount, descript,ref,ex,div) VALUES('{$pur['supid']}','{$pur['pdate']}', '{$dept['credacc']}', '{$pur['total']}', 'Stock Received - Purchase {$pur['purnum']}', '{$refnum}','{$pur['purnum']}','" . USER_DIV . "')";
    $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
    # Debit Stock Control and Credit Creditors control
    writetrans($wh['conacc'], $dept['credacc'], $td, $refnum, $pur['total'] - $pur['vat'], "Invoice Received for Purchase No. {$pur['purnum']} from Supplier : {$pur['supname']}.");
    # Transfer vat
    writetrans($vatacc, $dept['credacc'], $td, $refnum, $pur['vat'], "Vat Paid for Purchase No. {$pur['purnum']} from Supplier : {$pur['supname']}.");
    # Ledger Records
    suppledger($pur['supid'], $wh['conacc'], $td, $pur['purid'], "Purchase No. {$pur['purnum']} received.", $pur['total'], 'c');
    db_connect();
    /* End Transactions */
    /* Make transaction record  for age analysis */
    db_connect();
    # update the supplier age analysis (make balance less)
    if (ext_ex2("suppurch", "purid", $pur['purnum'], "supid", $pur['supid'])) {
        # Found? Make amount less
        $sql = "UPDATE suppurch SET balance = (balance + '{$pur['total']}') WHERE supid = '{$pur['supid']}' AND purid = '{$pur['purnum']}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
    } else {
        /* Make transaction record for age analysis */
        $sql = "INSERT INTO suppurch(supid, purid, pdate, balance, div) VALUES('{$pur['supid']}', '{$pur['purnum']}', '{$pur['pdate']}', '{$pur['total']}', '" . USER_DIV . "')";
        $purcRslt = db_exec($sql) or errDie("Unable to update Order information in Cubit.", SELF);
    }
    /* Make transaction record  for age analysis */
    # commit updating
    //1 ("COMMIT") or errDie("Unable to commit a database transaction.",SELF);
    /* Start moving if purchase */
    if ($pur['received'] == "y") {
        if (strlen($pur['appdate']) < 8) {
            $pur['appdate'] = date("Y-m-d");
        }
        # copy purchase
        db_conn(PRD_DB);
        $sql = "INSERT INTO purchases(purid, deptid, supid, supname, supaddr, supno, terms, pdate, ddate, shipchrg, subtot, total, balance, vatinc, vat, shipping, remarks, refno, received, done, div, purnum, supinv,ordernum,appname,appdate)";
        $sql .= " VALUES('{$purid}', '{$pur['deptid']}', '{$pur['supid']}',  '{$pur['supname']}', '{$pur['supaddr']}', '{$pur['supno']}', '{$pur['terms']}', '{$pur['pdate']}', '{$pur['ddate']}', '{$pur['shipchrg']}', '{$pur['subtot']}', '{$pur['total']}', '0', '{$pur['vatinc']}', '{$pur['vat']}', '{$pur['shipping']}', '{$pur['remarks']}', '{$pur['refno']}', 'y', 'y', '" . USER_DIV . "', '{$pur['purnum']}','{$supinv}','{$pur['ordernum']}','{$pur['appname']}','{$pur['appdate']}')";
        $rslt = db_exec($sql) or errDie("Unable to insert Order to Cubit.", SELF);
        /*-- Cost varience -- */
        $nsubtot = sprint($pur['total'] - $pur['vat']);
        if ($pur['rsubtot'] > $nsubtot) {
            $diff = sprint($pur['rsubtot'] - $nsubtot);
            # Debit Stock Control and Credit Creditors control
            writetrans($wh['conacc'], $cvacc, $td, $refnum, $diff, "Cost Variance for Stock Received on Purchase No. {$pur['purnum']} from Supplier : {$sup['supname']}.");
        } elseif ($nsubtot > $pur['rsubtot']) {
            $diff = sprint($nsubtot - $pur['rsubtot']);
            # Debit Stock Control and Credit Creditors control
            writetrans($cvacc, $wh['conacc'], $td, $refnum, $diff, "Cost Variance for Stock Received on Purchase No. {$pur['purnum']} from Supplier : {$sup['supname']}.");
        }
        /*-- End Cost varience -- */
        db_connect();
        # Get selected stock
        $sql = "SELECT * FROM pur_items WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
        $stktcRslt = db_exec($sql);
        while ($stktc = pg_fetch_array($stktcRslt)) {
            # Insert purchase items
            db_conn(PRD_DB);
            $sql = "INSERT INTO pur_items(purid, whid, stkid, qty, rqty, unitcost, amt, svat, ddate, div) VALUES('{$purid}', '{$stktc['whid']}', '{$stktc['stkid']}', '{$stktc['qty']}', '{$stktc['rqty']}', '{$stktc['unitcost']}', '{$stktc['amt']}', '{$stktc['svat']}', '{$stktc['ddate']}', '" . USER_DIV . "')";
            $rslt = db_exec($sql) or errDie("Unable to insert Order items to Cubit.", SELF);
        }
        # begin updating
        db_connect();
        # Remove the purchase from running DB
        $sql = "DELETE FROM purchases WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
        $delRslt = db_exec($sql) or errDie("Unable to update int purchases information in Cubit.", SELF);
        # Record where purchase is
        $sql = "INSERT INTO movpurch(purtype, purnum, prd, div) VALUES('loc', '{$pur['purnum']}', '{$pur['prd']}', '" . USER_DIV . "')";
        $movRslt = db_exec($sql) or errDie("Unable to update int purchases information in Cubit.", SELF);
        # Remove those purchase items from running DB
        $sql = "DELETE FROM pur_items WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
        $delRslt = db_exec($sql) or errDie("Unable to update int purchases information in Cubit.", SELF);
        /* End moving purchase received */
        # commit updating
    } else {
        # insert Order to DB
        $sql = "UPDATE purchases SET invcd = 'y',supinv='{$supinv}' WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update Order status in Cubit.", SELF);
    }
    pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
    // Final Layout
    $write = "\n\t<table border=0 cellpadding='" . TMPL_tblCellPadding . "' cellspacing='" . TMPL_tblCellSpacing . "'>\n\t\t<tr><th>Purchase Invoiced</th></tr>\n\t\t<tr class='bg-even'><td>Purchase Invoice from Supplier <b>{$pur['supname']}</b> has been recorded.</td></tr>\n\t</table>\n\t<p>\n\t<table border=0 cellpadding='" . TMPL_tblCellPadding . "' cellspacing='" . TMPL_tblCellSpacing . "'>\n\t\t<tr><th>Quick Links</th></tr>\n\t\t<tr class='bg-odd'><td><a href='purchase-view.php'>View purchases</a></td></tr>\n\t\t<script>document.write(getQuicklinkSpecial());</script>\n\t</table>";
    return $write;
}
function sp($id, $amount, $description, $contra, $refnum, $date, $cheque, $bankid)
{
    $id += 0;
    $amount += 0;
    $cheque += 0;
    db_connect();
    $Sl = "SELECT supid,supno,supname,deptid FROM suppliers WHERE supid = '{$id}' AND div = '" . USER_DIV . "'";
    $Ri = db_exec($Sl) or errDie("Unable to get supplier data.");
    $sup = pg_fetch_array($Ri);
    core_connect();
    $Sl = "SELECT * FROM bankacc WHERE accid = '{$bankid}' AND div = '" . USER_DIV . "'";
    $Ri = db_exec($Sl) or errDie("Unable to retrieve bank account link from Cubit", SELF);
    if (pg_numrows($Ri) < 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($Ri);
    db_conn("exten");
    $Sl = "SELECT credacc FROM departments WHERE deptid ='{$sup['deptid']}' AND div = '" . USER_DIV . "'";
    $Ri = db_exec($Sl) or errDie("Unable to get department data.");
    $dept = pg_fetch_array($Ri);
    $out = $amount;
    $confirm = "";
    $ids = "";
    $purids = "";
    $pamounts = "";
    $pdates = "";
    db_connect();
    $Sl = "SELECT id,purid AS invid,intpurid AS invid2,balance,pdate FROM suppurch WHERE supid='{$id}' AND balance > 0 AND div='" . USER_DIV . "' ORDER BY pdate ASC";
    $Ri = db_exec($Sl) or errDie("unable to get invoices.");
    $i = 0;
    while ($inv = pg_fetch_array($Ri) and $out > 0) {
        if ($inv['invid2'] > 0) {
            $inv['invid'] = $inv['invid2'];
        }
        $invid = $inv['invid'];
        if ($out >= $inv['balance']) {
            $val = $inv['balance'];
            $out = $out - $inv['balance'];
        } else {
            $val = $out;
            $out = 0;
        }
        $Sl = "UPDATE suppurch SET balance = (balance - '{$val}'::numeric(13,2)) WHERE id='{$inv['id']}'";
        $Rl = db_exec($Sl) or errDie("Unable to update Invoice information in Cubit.", SELF);
        $ids .= "|{$inv['id']}";
        $purids .= "|{$invid}";
        $pamounts .= "|{$val}";
        $pdates .= "|{$inv['pdate']}";
    }
    $samount = $amount - $amount * 2;
    if ($out > 0) {
        recordDT($out, $sup['supid'], $date);
    }
    $Sl = "INSERT INTO sup_stmnt (supid, amount, edate, descript,ref,cacc, div) VALUES ('{$sup['supid']}','{$samount}','{$date}', 'Payment','{$cheque}','{$bank['accnum']}', '" . USER_DIV . "')";
    $Rs = db_exec($Sl) or errDie("Unable to insert statement record in Cubit.", SELF);
    db_connect();
    $Sl = "UPDATE suppliers SET balance = (balance - '{$amount}'::numeric(13,2)) WHERE supid = '{$sup['supid']}'";
    $Ri = db_exec($Sl) or errDie("Unable to update invoice in Cubit.", SELF);
    suppledger($sup['supid'], $bank['accnum'], $date, $cheque, "Payment for purchases", $amount, "d");
    db_conn('cubit');
    $Sl = "\n\t\tINSERT INTO cashbook (\n\t\t\tbankid, trantype, date, name, descript, \n\t\t\tcheqnum, amount, banked, accinv, supid, ids, \n\t\t\tpurids, pamounts, pdates, div\n\t\t) VALUES (\n\t\t\t'{$bankid}', 'withdrawal', '{$date}', '{$sup['supno']} - {$sup['supname']}', 'Supplier Payment to {$sup['supname']}', \n\t\t\t'{$cheque}', '{$amount}', 'no', '{$dept['credacc']}', '{$sup['supid']}', '{$ids}', \n\t\t\t'{$purids}', '{$pamounts}', '{$pdates}', '" . USER_DIV . "'\n\t\t)";
    $Ri = db_exec($Sl) or errDie("Unable to add bank payment to database.", SELF);
    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($dept['credacc'], $bank['accnum'], $date, $refnum, $amount, "Supplier Payment to {$sup['supname']}");
}
Ejemplo n.º 20
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;
}
Ejemplo n.º 21
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;
}
function write($_POST)
{
    # Get vars
    foreach ($_POST as $key => $value) {
        ${$key} = $value;
    }
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($supid, "num", 1, 50, "Invalid Supplier 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"];
        }
        $write .= "<p><input type=button onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $write;
    }
    $td = $date;
    # Accounts details
    $accRs = get("core", "*", "accounts", "accid", $accid);
    $acc = pg_fetch_array($accRs);
    # Select supplier
    db_connect();
    $sql = "SELECT * FROM suppliers WHERE supid = '{$supid}' 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.";
    } 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);
    }
    $famt = sprint($amount);
    $amount = sprint($amount * $rate);
    # update all supplies xchange rate first
    xrate_update($supp['fcid'], $rate, "suppurch", "id");
    sup_xrate_update($supp['fcid'], $rate);
    $supp['supname'] = remval($supp['supname']);
    # Probe tran type
    if ($entry == "CT") {
        # Write transaction  (debit contra account, credit debtors control)
        writetrans($accid, $dept['credacc'], $td, $refnum, $amount, $details . " - Supplier {$supp['supname']}");
        $tran = "<tr class='bg-odd'><td>{$acc['topacc']}/{$acc['accnum']} - {$acc['accname']}</td><td>{$supp['supno']} - {$supp['supname']}</td></tr>";
        $samount = $amount;
        $sfamt = $famt;
        // recordCT(-$amount, $supp['supid']);
        frecordCT($famt, $amount, $supp['supid'], $supp['fcid'], $td);
        $type = 'c';
    } else {
        # Write transaction  (debit debtors control, credit contra account)
        writetrans($dept['credacc'], $accid, $td, $refnum, $amount, $details . " - Supplier {$supp['supname']}");
        $tran = "<tr class='bg-odd'><td>{$supp['supno']} - {$supp['supname']}</td><td>{$acc['topacc']}/{$acc['accnum']} - {$acc['accname']}</td></tr>";
        $samount = sprint($amount - $amount * 2);
        $sfamt = sprint($famt - $famt * 2);
        // recordDT($amount, $supp['supid']);
        frecordDT($famt, $amount, $supp['supid'], $supp['fcid'], $td);
        $type = 'd';
    }
    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 = "INSERT INTO sup_stmnt(supid, edate, ref, cacc, descript, amount, div) VALUES('{$supp['supid']}', '{$td}', '0', '{$accid}', '{$details}', '{$sfamt}', '" . 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 + '{$samount}'),fbalance = (fbalance + '{$sfamt}') 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'], $accid, $td, $refnum, $details, $amount, $type);
    db_connect();
    // Start layout
    $write = "<h3>Journal transaction has been recorded</h3>\n\t<table border=0 cellpadding='" . TMPL_tblCellPadding . "' cellspacing='" . TMPL_tblCellSpacing . "'>\n\t\t<tr><td width=50%><h3>Debit</h3></td><td width=50%><h3>Credit</h3></td></tr>\n\t\t{$tran}\n\t\t<tr><td><br></td></tr>\n\t\t<tr colspan=2><td><h4>Amount</h4></td></tr>\n\t\t<tr class='bg-even'><td colspan=2><b>" . CUR . " {$famt}</b></td></tr>\n\t</table>\n\t<P>\n\t<table border=0 cellpadding='" . TMPL_tblCellPadding . "' cellspacing='" . TMPL_tblCellSpacing . "' width=25%>\n\t\t<tr><th>Quick Links</th></tr>\n\t\t<tr class=datacell><td align=center><a href='trans-new.php'>Journal Transactions</td></tr>\n\t\t<tr class='bg-odd'><td align=center><a href='../supp-view.php'>View Suppliers</a></td></tr>\n\t\t<script>document.write(getQuicklinkSpecial());</script>\n\t</table>";
    return $write;
}
Ejemplo n.º 23
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;
}
function write($_POST)
{
    # get vars
    extract($_POST);
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($purid, "num", 1, 20, "Invalid purchase number.");
    if (!isset($supid) && !isset($deptid)) {
        $v->isOk($supacc, "num", 1, 10, "Invalid Supplier Account number.");
    }
    $v->isOk($remarks, "string", 0, 255, "Invalid Remarks.");
    $v->isOk($refno, "string", 0, 255, "Invalid Delivery Reference No.");
    $v->isOk($shipchrg, "float", 0, 20, "Invalid Delivery Charges.");
    $pdate = $p_year . "-" . $p_month . "-" . $p_day;
    if (!checkdate($p_month, $p_day, $p_year)) {
        $v->isOk($date, "num", 1, 1, "Invalid Date.");
    }
    # used to generate errors
    $error = "asa@";
    # check quantities
    if (isset($qtys)) {
        foreach ($qtys as $keys => $qty) {
            $v->isOk($qty, "num", 1, 10, "Invalid Quantity for product number : <b>" . ($keys + 1) . "</b>");
            if ($qty > $qts[$keys]) {
                $v->isOk($qty, "num", 0, 0, "Error : Quantity for product number : <b>" . ($keys + 1) . "</b> is more that Qty Purchased");
            }
            $v->isOk($unitcost[$keys], "float", 1, 20, "Invalid Unit Price for product number : <b>" . ($keys + 1) . "</b>.");
            if ($qty < 1) {
                $v->isOk($qty, "num", 0, 0, "Error : Item Quantity must be at least one. Product number : <b>" . ($keys + 1) . "</b>");
            }
        }
    }
    # display errors, if any
    $err = "";
    if ($v->isError()) {
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $err .= "<li class='err'>" . $e["msg"] . "</li>";
        }
        return details($_POST, $err);
    }
    # Get purchase info
    db_connect();
    $sql = "SELECT * FROM nons_purchases WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
    $purRslt = db_exec($sql) or errDie("Unable to get purchase information");
    if (pg_numrows($purRslt) < 1) {
        return "<li>- purchase Not Found</li>";
    }
    $pur = pg_fetch_array($purRslt);
    # CHECK IF THIS DATE IS IN THE BLOCKED RANGE
    $blocked_date_from = getCSetting("BLOCKED_FROM");
    $blocked_date_to = getCSetting("BLOCKED_TO");
    if (strtotime($pur['pdate']) >= strtotime($blocked_date_from) and strtotime($pur['pdate']) <= 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>";
    }
    $pur['pdate'] = $p_year . "-" . $p_month . "-" . $p_day;
    # Get selected supplier info
    db_connect();
    if (isset($supid)) {
        $sql = "SELECT * FROM suppliers WHERE supid = '{$supid}' AND div = '" . USER_DIV . "'";
        $supRslt = db_exec($sql) or errDie("Unable to get supplier");
        if (pg_numrows($supRslt) < 1) {
            $error = "<li class='err'> Supplier not Found.</li>";
            $confirm .= "{$error}<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
            return $confirm;
        } else {
            $sup = pg_fetch_array($supRslt);
            $pur['supplier'] = $sup['supname'];
            $pur['supaddr'] = $sup['supaddr'];
            # Get department info
            db_conn("exten");
            $sql = "SELECT * FROM departments WHERE deptid = '{$sup['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);
            }
            $supacc = $dept['credacc'];
        }
    } elseif (isset($deptid)) {
        db_conn("exten");
        $sql = "SELECT * FROM departments WHERE deptid = '{$deptid}'";
        $deptRslt = db_exec($sql) or errDie("Unable to view customers");
        if (pg_numrows($deptRslt) < 1) {
            $error = "<li class='err'> Department not Found.";
            $confirm .= "{$error}<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
            return $confirm;
        } else {
            $dept = pg_fetch_array($deptRslt);
            $supacc = $dept['pca'];
        }
    }
    # check if purchase has been received
    if ($pur['received'] == "y") {
        $error = "<li class='err'> Error : purchase number <b>{$purid}</b> has already been received.</li>";
        $error .= "<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $error;
    }
    $vatacc = gethook("accnum", "salesacc", "name", "VAT");
    $cvacc = gethook("accnum", "pchsacc", "name", "Cost Variance");
    # Insert purchase to DB
    db_connect();
    # begin updating
    pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
    $refnum = getrefnum();
    /*refnum*/
    db_connect();
    if (isset($qtys)) {
        # amount of stock in
        $totstkamt = array();
        $resub = 0;
        # Get subtotal
        foreach ($qtys as $keys => $value) {
            # Skip zeros
            if ($qtys[$keys] < 1) {
                continue;
            }
            $amt[$keys] = $qtys[$keys] * $unitcost[$keys];
        }
        $SUBTOTAL = array_sum($amt);
        $revat = 0;
        foreach ($qtys as $keys => $value) {
            # Get selected stock line
            $sql = "SELECT * FROM nons_pur_items WHERE cod = '{$cod[$keys]}' AND purid = '{$purid}' AND div = '" . USER_DIV . "'";
            $stkdRslt = db_exec($sql);
            $stkd = pg_fetch_array($stkdRslt);
            # Calculate cost amount bought
            $amt[$keys] = $qtys[$keys] * $unitcost[$keys];
            /* delivery charge */
            # Calculate percentage from subtotal
            $perc[$keys] = $amt[$keys] / $SUBTOTAL * 100;
            # Get percentage from shipping charges
            $shipc[$keys] = $perc[$keys] / 100 * $shipchrg;
            # add delivery charges
            $amt[$keys] += $shipc[$keys];
            /* end delivery charge */
            # the subtotal + delivery charges
            $resub += $amt[$keys];
            # calculate vat
            $svat[$keys] = svat($amt[$keys], $stkd['amt'], $stkd['svat']);
            db_conn('cubit');
            $Sl = "SELECT * FROM vatcodes WHERE id='{$stkd['vatcode']}'";
            $Ri = db_exec($Sl) or errDie("Unable to get data.");
            $vd = pg_fetch_array($Ri);
            vatr($vd['id'], $pur['pdate'], "INPUT", $vd['code'], $refnum, "Vat for Non-Stock Purchase No. {$pur['purnum']}", -$amt[$keys], -$svat[$keys]);
            # received vat
            $revat += $svat[$keys];
            # make amount vat free
            if ($pur['vatinc'] == "yes") {
                $amt[$keys] = $amt[$keys] - $svat[$keys];
            }
            # Update Order items
            $sql = "UPDATE nons_pur_items SET rqty = (rqty + '{$qtys[$keys]}') WHERE cod = '{$cod[$keys]}' AND purid='{$purid}' AND div = '" . USER_DIV . "'";
            $rslt = db_exec($sql) or errDie("Unable to insert Order items to Cubit.", SELF);
            /* ?: refer to :Code Insert:
            			# keep records for transactions
            			if(isset($totstkamt[$stkacc[$keys]])){
            				$totstkamt[$stkacc[$keys]] += $amt[$keys];
            			}else{
            				$totstkamt[$stkacc[$keys]] = $amt[$keys];
            			}
            			*/
            # check if there are any outstanding items
            $sql = "SELECT * FROM nons_pur_items WHERE purid = '{$purid}' AND (qty - rqty) > '0' AND div = '" . USER_DIV . "'";
            $stkdRslt = db_exec($sql);
            # if none the set to received
            if (pg_numrows($stkdRslt) < 1) {
                # update surch_int(received = 'y')
                $sql = "UPDATE nons_purchases SET received = 'y', supplier = '{$pur['supplier']}', supaddr = '{$pur['supaddr']}' WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
                $rslt = db_exec($sql) or errDie("Unable to update international Orders in Cubit.", SELF);
            }
        }
    }
    # Update purchase on the DB
    if ($pur['part'] == 'y') {
        # Update purchase on the DB
        $sql = "UPDATE nons_purchases SET shipchrg = (shipchrg + '{$shipchrg}'), refno = '{$refno}', remarks = '{$remarks}' WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update purchase in Cubit.", SELF);
    } else {
        # Update purchase on the DB
        $sql = "UPDATE nons_purchases SET shipchrg = '{$shipchrg}', refno = '{$refno}', remarks = '{$remarks}' WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update purchase in Cubit.", SELF);
    }
    /* Transactions */
    /* - Start Hooks - */
    /* - End Hooks - */
    $detadd = "";
    if (isset($supid)) {
        $detadd = " from Supplier {$sup['supname']}";
    }
    $sdate = $pur['pdate'];
    /* ?:refer to :Code Insert:
    		# record transaction  from data
    		foreach($totstkamt as $stkacc => $wamt){
    			# Debit Stock and Credit Suppliers control
    			writetrans($stkacc, $supacc, date("d-m-Y"), $refnum, $wamt, "Non-Stock Purchase No. $pur[purnum] Received $detadd.");
    			pettyrec($supacc, $sdate, "ct", "Non-Stock Purchase No. $pur[purnum] Received $detadd.", $wamt, "Cash Purchase");
    		}*/
    # Calc Vat amount on (subtot + delchrg)
    $vatamt = $revat;
    # Add vat if not included
    if ($pur['vatinc'] == 'no') {
        $retot = $resub + $vatamt;
    } elseif ($pur['vatinc'] == "novat") {
        $retot = $resub;
        $vatamt = 0;
    } else {
        $retot = $resub;
    }
    # get warehouse name
    db_conn("exten");
    $sql = "SELECT * FROM warehouses WHERE div = '" . USER_DIV . "'";
    $whRslt = db_exec($sql);
    $wh = pg_fetch_array($whRslt);
    $tot_post = 0;
    if ($vatamt != 0) {
        $tot_post += $vatamt;
        # Debit bank and credit the account involved
        writetrans($vatacc, $supacc, $pdate, $refnum, $vatamt, "Non-Stock Purchase Vat paid on Non-Stock Purchase No. {$pur['purnum']} {$detadd}.");
        pettyrec($supacc, $sdate, "ct", "Non-Stock Purchase No. {$pur['purnum']} Received {$detadd}.", $vatamt, "Cash Purchase Vat");
        # Record the payment on the statement
        db_connect();
        $sdate = $pur['pdate'];
    }
    if (isset($supid)) {
        $DAte = $pur['pdate'];
        db_connect();
        # update the supplier (make balance more)
        $sql = "UPDATE suppliers SET balance = (balance + '{$retot}') WHERE supid = '{$sup['supid']}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
        $sql = "INSERT INTO sup_stmnt(supid, edate, cacc, amount, descript,ref,ex,div) VALUES('{$sup['supid']}','{$DAte}', '{$dept['credacc']}', '{$retot}','Non-Stock Purchase No. {$pur['purnum']} Received', '{$refnum}', '{$pur['purnum']}','" . USER_DIV . "')";
        $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
        suppledger($sup['supid'], $wh['stkacc'], $DAte, $pur['purid'], "Non-Stock Purchase No. {$pur['purnum']} received.", $retot, 'c');
        db_connect();
        # update the supplier age analysis (make balance less)
        /* Make transaction record for age analysis */
        $sql = "INSERT INTO suppurch(supid, purid, pdate, balance, div) VALUES('{$sup['supid']}', '{$pur['purnum']}', '{$DAte}', '{$retot}', '" . USER_DIV . "')";
        $purcRslt = db_exec($sql) or errDie("Unable to update int purchases information in Cubit.", SELF);
    }
    /* End Transactions */
    # commit updating
    // pglib_transaction ("COMMIT") or errDie("Unable to commit a database transaction.",SELF);
    /* Update items found in ther linked purchase */
    # Get purchase info
    db_connect();
    $sql = "SELECT * FROM nons_purchases WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
    $purRslt = db_exec($sql) or errDie("Unable to get purchase information");
    if (pg_numrows($purRslt) < 1) {
        return "<li>- purchase Not Found</li>";
    }
    $pur = pg_fetch_array($purRslt);
    db_conn($pur['spurprd']);
    $stab = $pur['spurtype'] == "int" ? "purch_int" : "purchases";
    $itab = $pur['spurtype'] == "int" ? "purint_items" : "pur_items";
    # Get purchase info
    $sql = "SELECT * FROM {$stab} WHERE purnum = '{$pur['spurnum']}' AND div = '" . USER_DIV . "'";
    $spurRslt = db_exec($sql) or errDie("Unable to get purchase information");
    if (pg_numrows($spurRslt) < 1) {
        return "<li> - purchase Not Found</li>";
    }
    $spur = pg_fetch_array($spurRslt);
    $purs = explode(",", $pur['purs']);
    $TSUB = 0;
    foreach ($purs as $purID) {
        $purID += 0;
        db_connect();
        $sql = "SELECT * FROM purchases WHERE purnum = '{$purID}' AND div = '" . USER_DIV . "'";
        $srchRslt = db_exec($sql) or errDie("Unable to retrieve purchases from database.");
        if (pg_numrows($srchRslt) > 0) {
            $p = pg_fetch_array($srchRslt);
            $TSUB += $p['subtot'];
            $Sl = "SELECT sum(unitcost) -sum(svat) as non FROM pur_items WHERE purid='{$p['purid']}' AND stkid=0";
            $Ri = db_exec($Sl) or errDie("Unable to get data.");
            $pi = pg_fetch_array($Ri);
            $pi = $pi['non'];
        }
        $sql = "SELECT * FROM movpurch WHERE purnum = '{$purID}' AND div = '" . USER_DIV . "'";
        $srchRslt = db_exec($sql) or errDie("Unable to retrieve purchases from database.");
        if (pg_numrows($srchRslt) > 0) {
            $res = pg_fetch_array($srchRslt);
            db_conn($res['prd']);
            $sql = "SELECT * FROM purchases WHERE purnum = '{$purID}' AND div = '" . USER_DIV . "'";
            $srchRslt = db_exec($sql) or errDie("Unable to retrieve purchases from database.");
            if (pg_numrows($srchRslt) > 0) {
                $p = pg_fetch_array($srchRslt);
                $TSUB += $p['subtot'];
                $Sl = "SELECT sum(unitcost)-sum(svat) as non FROM pur_items WHERE purid='{$p['purid']}' AND stkid=0";
                $Ri = db_exec($Sl) or errDie("Unable to get data.");
                $pi = pg_fetch_array($Ri);
                $pi = $pi['non'];
            } else {
                db_conn($res['prd']);
                $sql = "SELECT * FROM purch_int WHERE purnum = '{$purID}' AND div = '" . USER_DIV . "'";
                $srchRslt = db_exec($sql) or errDie("Unable to retrieve purchases from database.");
                if (pg_numrows($srchRslt) > 0) {
                    $p = pg_fetch_array($srchRslt);
                    $TSUB += $p['subtot'];
                    // 					$Sl="SELECT sum(unitcost)-sum(svat) as non FROM purint_items WHERE purid='$p[purid]' AND stkid=0";
                    //
                    // 					$Ri=db_exec($Sl) or errDie("Unable to get data.");
                    // 					$pi=pg_fetch_array($Ri);
                    // 					$pi=$pi['non'];
                    $pi = 0;
                }
            }
        }
        if (!isset($pi)) {
            $pi = 0;
        }
        $TSUB -= $pi;
    }
    $purs = explode(",", $pur['purs']);
    foreach ($purs as $purID) {
        $itab = "pur_items";
        $purID += 0;
        //print $purID;
        db_connect();
        $sql = "SELECT * FROM purchases WHERE purnum = '{$purID}' AND div = '" . USER_DIV . "'";
        $srchRslt = db_exec($sql) or errDie("Unable to retrieve purchases from database.");
        if (pg_numrows($srchRslt) > 0) {
            $pur['spurprd'] = "cubit";
        }
        $sql = "SELECT * FROM movpurch WHERE purnum = '{$purID}' AND div = '" . USER_DIV . "'";
        $srchRslt = db_exec($sql) or errDie("Unable to retrieve purchases from database.");
        if (pg_numrows($srchRslt) > 0) {
            $res = pg_fetch_array($srchRslt);
            db_conn($res['prd']);
            $pur['spurprd'] = $res['prd'];
        }
        db_conn($pur['spurprd']);
        $test = $pur['spurprd'];
        $test += 0;
        if ($test != 0) {
            $s = "SELECT * FROM purchases WHERE purnum = '{$purID}' AND div = '" . USER_DIV . "'";
            $q = db_exec($s) or errDie("Unable to retrieve purchases from database.");
            if (pg_num_rows($q) > 0) {
                $p = pg_fetch_array($q);
                $purID = $p['purid'];
            } else {
                $s = "SELECT * FROM purch_int WHERE purnum = '{$purID}' AND div = '" . USER_DIV . "'";
                $q = db_exec($s) or errDie("Unable to retrieve purchases from database.");
                if (pg_num_rows($q) > 0) {
                    $p = pg_fetch_array($q);
                    $purID = $p['purid'];
                    $itab = "purint_items";
                }
            }
        }
        # Get selected stock
        $sql = "SELECT * FROM {$itab} WHERE purid = '{$purID}' AND div = '" . USER_DIV . "' AND stkid!=0";
        $sstkdRslt = db_exec($sql);
        while ($sstk = pg_fetch_array($sstkdRslt)) {
            if ($pur['spurtype'] == "int") {
                $csamt = sprint($sstk['amt'] / $TSUB * ($retot - $vatamt));
            } else {
                if ($spur['vatinc'] == "yes") {
                    $csamt = sprint(($sstk['amt'] - $sstk['svat']) / $TSUB * ($retot - $vatamt));
                } else {
                    $csamt = sprint($sstk['amt'] / $TSUB * ($retot - $vatamt));
                }
            }
            db_connect();
            # get selected stock
            $sql = "SELECT * FROM stock WHERE stkid = '{$sstk['stkid']}' AND div = '" . USER_DIV . "'";
            $stktRslt = db_exec($sql);
            $stkt = pg_fetch_array($stktRslt);
            /* Code insert */
            # get warehouse name
            db_conn("exten");
            $sql = "SELECT * FROM warehouses WHERE whid = '{$stkt['whid']}' AND div = '" . USER_DIV . "'";
            $whRslt = db_exec($sql);
            $wh = pg_fetch_array($whRslt);
            $tot_post += $csamt;
            writetrans($wh['stkacc'], $supacc, $pdate, $refnum, $csamt, "Non-Stock Purchase No. {$pur['purnum']} Received {$detadd}.");
            /* End code insert */
            db_connect();
            if ($stkt['units'] != 0) {
                $sql = "UPDATE stock SET csamt = (csamt + '{$csamt}'), csprice = (csamt/units) WHERE stkid = '{$sstk['stkid']}' AND div = '" . USER_DIV . "'";
                $rslt = db_exec($sql) or errDie("Unable to update stock to Cubit.", SELF);
            } else {
                $sql = "UPDATE stock SET csamt = (csamt + '{$csamt}') WHERE stkid = '{$sstk['stkid']}' AND div = '" . USER_DIV . "'";
                $rslt = db_exec($sql) or errDie("Unable to update stock to Cubit.", SELF);
            }
            $sdate = $pur['pdate'];
            stockrec($stkt['stkid'], $stkt['stkcod'], $stkt['stkdes'], 'dt', $sdate, 0, $csamt, "Cost Increased with Non Stock Purchase No. {$pur['purnum']}");
            # get selected stock
            db_connect();
            $sql = "SELECT * FROM stock WHERE stkid = '{$sstk['stkid']}' AND div = '" . USER_DIV . "'";
            $stktRslt = db_exec($sql);
            $stkt = pg_fetch_array($stktRslt);
            # $csprice = round(($stk['csamt']/$stk['units']), 2);
            if ($stkt['units'] > 0) {
                $csprice = round($stkt['csamt'] / $stkt['units'], 2);
            } else {
                $csprice = round($stkt['csprice'], 2);
            }
            # update stock(csprice = (csamt/units))
            $sql = "UPDATE stock SET csprice = '{$csprice}' WHERE stkid = '{$sstk['stkid']}' AND div = '" . USER_DIV . "'";
            $rslt = db_exec($sql) or errDie("Unable to update stock to Cubit.", SELF);
        }
    }
    //exit;
    /*
    		db_conn($pur['spurprd']);
    		# Get selected stock
    		$sql = "SELECT * FROM $itab WHERE purid = '$spur[purid]' AND div = '".USER_DIV."' AND stkid!=0";
    		$sstkdRslt = db_exec($sql);
    		while($sstk = pg_fetch_array($sstkdRslt)){
    			if($pur['spurtype'] == "int"){
    				$csamt = sprint(($sstk['amt']/$TSUB) * ($retot - $vatamt));
    			}else{
    				if($spur['vatinc'] == "yes"){
    					$csamt = sprint((($sstk['amt'] - $sstk['svat'])/$TSUB) * ($retot - $vatamt));
    				}else{
    					$csamt = sprint((($sstk['amt'])/$TSUB) * ($retot - $vatamt));
    				}
    			}
    
    			db_connect();
    			# get selected stock
    			$sql = "SELECT * FROM stock WHERE stkid = '$sstk[stkid]' AND div = '".USER_DIV."'";
    			$stktRslt = db_exec($sql);
    			$stkt = pg_fetch_array($stktRslt);
    
    			/* Code insert
    				# get warehouse name
    				db_conn("exten");
    				$sql = "SELECT * FROM warehouses WHERE whid = '$stkt[whid]' AND div = '".USER_DIV."'";
    				$whRslt = db_exec($sql);
    				$wh = pg_fetch_array($whRslt);
    
    				$tot_post+=$csamt;
    
    				writetrans($wh['stkacc'], $supacc, date("d-m-Y"), $refnum, $csamt, "Non-Stock Purchase No. $pur[purnum] Received $detadd.");
    			/* End code insert
    
    			db_connect();
    			if($stkt['units'] <> 0){
    				$sql = "UPDATE stock SET csamt = (csamt + '$csamt'), csprice = (csamt/units) WHERE stkid = '$sstk[stkid]' AND div = '".USER_DIV."'";
    				$rslt = db_exec($sql) or errDie("Unable to update stock to Cubit.",SELF);
    			}else{
    				$sql = "UPDATE stock SET csamt = (csamt + '$csamt') WHERE stkid = '$sstk[stkid]' AND div = '".USER_DIV."'";
    				$rslt = db_exec($sql) or errDie("Unable to update stock to Cubit.",SELF);
    			}
    			$sdate = $pur['pdate'];
    			stockrec($stkt['stkid'], $stkt['stkcod'], $stkt['stkdes'], 'dt', $sdate, 0, $csamt, "Cost Increased with Non Stock Purchase No. $pur[purnum]");
    
    			# get selected stock
    			db_connect();
    			$sql = "SELECT * FROM stock WHERE stkid = '$sstk[stkid]' AND div = '".USER_DIV."'";
    			$stktRslt = db_exec($sql);
    			$stkt = pg_fetch_array($stktRslt);
    
    			# $csprice = round(($stk['csamt']/$stk['units']), 2);
    			if($stkt['units'] > 0){
    				$csprice = round(($stkt['csamt']/$stkt['units']), 2);
    			}else{
    				$csprice = round($stkt['csprice'], 2);
    			}
    
    			# update stock(csprice = (csamt/units))
    			$sql = "UPDATE stock SET csprice = '$csprice' WHERE stkid = '$sstk[stkid]' AND div = '".USER_DIV."'";
    			$rslt = db_exec($sql) or errDie("Unable to update stock to Cubit.",SELF);
    		}
    */
    $diff = sprint($retot - $tot_post);
    if ($diff > 0) {
        writetrans($cvacc, $supacc, $sdate, $refnum, $diff, "Cost Variance for Non stock Purchase No. {$pur['purnum']}");
    } elseif ($diff < 0) {
        writetrans($supacc, $cvacc, $sdate, $refnum, -$diff, "Cost Variance for Non stock Purchase No. {$pur['purnum']}");
    }
    /* End Update items found in ther linked purchase */
    /* Start moving if purchase received */
    # Get purchase info
    db_connect();
    $sql = "SELECT * FROM nons_purchases WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
    $purRslt = db_exec($sql) or errDie("Unable to get purchase information");
    if (pg_numrows($purRslt) < 1) {
        return "<li>- purchase Not Found</li>";
    }
    $pur = pg_fetch_array($purRslt);
    if ($pur['received'] == "y") {
        if (isset($supid)) {
            $ctyp = "sup";
            $typeid = $supid;
        } elseif (isset($deptid)) {
            $ctyp = "led";
            $typeid = $deptid;
        } else {
            $ctyp = "ot";
            $typeid = 0;
        }
        # copy purchase
        db_conn($pur['prd']);
        $pur['spurprd'] += 0;
        $pur['spurnum'] += 0;
        $sql = "INSERT INTO nons_purchases(purid, deptid, supplier, supaddr, terms, pdate, ddate, shipchrg, subtot, total, balance, vatinc, vat, remarks, refno, received, done, div, purnum,ctyp,typeid,spurprd,spurnum)";
        $sql .= " VALUES('{$purid}', '{$pur['deptid']}', '{$pur['supplier']}',  '{$pur['supaddr']}', '{$pur['terms']}', '{$pur['pdate']}', '{$pur['ddate']}', '{$pur['shipchrg']}', '{$pur['subtot']}', '{$pur['total']}', '0', '{$pur['vatinc']}', '{$pur['vat']}', '{$pur['remarks']}', '{$pur['refno']}', 'y', 'y', '" . USER_DIV . "', '{$pur['purnum']}','{$ctyp}','{$typeid}','{$pur['spurprd']}','{$pur['spurnum']}')";
        $rslt = db_exec($sql) or errDie("Unable to insert Non-Stock Purchase to Cubit.", SELF);
        db_connect();
        # Get selected stock
        $sql = "SELECT * FROM nons_pur_items WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
        $stktcRslt = db_exec($sql);
        while ($stktc = pg_fetch_array($stktcRslt)) {
            # Insert purchase items
            db_conn($pur['prd']);
            $sql = "INSERT INTO nons_pur_items(purid, cod, des, qty, unitcost, amt, ddate, div,svat) VALUES('{$purid}', '{$stktc['cod']}', '{$stktc['des']}', '{$stktc['qty']}', '{$stktc['unitcost']}', '{$stktc['amt']}', '{$stktc['ddate']}', '" . USER_DIV . "','{$stktc['svat']}')";
            $rslt = db_exec($sql) or errDie("Unable to insert purchase items to Cubit.", SELF);
        }
        db_connect();
        # Remove the purchase from running DB
        $sql = "DELETE FROM nons_purchases WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
        $delRslt = db_exec($sql) or errDie("Unable to update int purchases information in Cubit.", SELF);
        # Remove those purchase items from running DB
        $sql = "DELETE FROM nons_pur_items WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
        $delRslt = db_exec($sql) or errDie("Unable to update int purchases information in Cubit.", SELF);
    }
    pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
    /* End moving purchase received */
    $cc = "<script> CostCenter('ct', 'Non-Stock Purchase', '{$pdate}', 'Non Stock Purchase No.{$pur['purnum']}', '" . ($retot - $vatamt) . "', ''); </script>";
    // Final Layout
    $write = "\n\t\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t\t<tr>\n\t\t\t\t\t\t<th>Non-Stock Purchase received</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>Non-Stock Purchase receipt has been recorded.</td>\n\t\t\t\t\t</tr>\n\t\t\t\t</table>\n\t\t\t\t<p>\n\t\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t\t<tr>\n\t\t\t\t\t\t<th>Quick Links</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><a href='nons-purchase-view.php'>View purchases</a></td>\n\t\t\t\t\t</tr>\n\t\t\t\t\t<script>document.write(getQuicklinkSpecial());</script>\n\t\t\t\t</table>";
    return $write;
}
function write($_POST)
{
    # get vars
    extract($_POST);
    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($reference, "string", 0, 50, "Invalid Reference Name/Number.");
    $v->isOk($cheqnum, "num", 0, 30, "Invalid Cheque number.");
    $v->isOk($amt, "float", 1, 10, "Invalid amount.");
    $v->isOk($supid, "num", 1, 10, "Invalid supplier number.");
    $v->isOk($out1, "float", 0, 10, "Invalid paid amount(current).");
    $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"] . "</li>";
        }
        $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 . "' AND accid!=0";
    $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();
    # Supplier name
    $sql = "SELECT supid,supno,supname,deptid FROM suppliers WHERE supid = '{$supid}' AND div = '" . USER_DIV . "'";
    $supRslt = db_exec($sql);
    $sup = pg_fetch_array($supRslt);
    db_conn("exten");
    # get debtors control account
    $sql = "SELECT credacc FROM departments WHERE deptid ='{$sup['deptid']}' AND div = '" . USER_DIV . "'";
    $deptRslt = db_exec($sql);
    $dept = pg_fetch_array($deptRslt);
    # date format
    $sdate = $date;
    $cheqnum = 0 + $cheqnum;
    $pay = "";
    $accdate = $sdate;
    # Paid invoices
    $invidsers = "";
    $rinvids = "";
    $amounts = "";
    $invprds = "";
    db_conn("cubit");
    pglib_transaction("BEGIN");
    if ($all == 0) {
        $ids = "";
        $purids = "";
        $pamounts = "";
        $pdates = "";
        if (isset($invids)) {
            foreach ($invids as $key => $value) {
                #debt invoice info
                $sql = "SELECT id,pdate FROM suppurch WHERE purid ='{$invids[$key]}' AND div = '" . USER_DIV . "' ORDER BY balance LIMIT 1";
                $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>";
                }
                $pur = pg_fetch_array($invRslt);
                # reduce the money that has been paid
                $sql = "UPDATE suppurch SET balance = (balance - '{$paidamt[$key]}'::numeric(13,2)) WHERE purid = '{$invids[$key]}' AND div = '" . USER_DIV . "' AND id='{$pur['id']}'";
                $payRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
                $ids .= "|{$pur['id']}";
                $purids .= "|{$invids[$key]}";
                $pamounts .= "|{$paidamt[$key]}";
                $pdates .= "|{$pur['pdate']}";
            }
        }
        $samount = $amt - $amt * 2;
        if ($out > 0) {
            recordDT($out, $sup['supid'], $sdate);
        }
        $Sl = "INSERT INTO sup_stmnt(supid, amount, edate, descript,ref,cacc, div) VALUES('{$sup['supid']}','{$samount}','{$sdate}', 'Payment','{$cheqnum}','{$bank['accnum']}', '" . USER_DIV . "')";
        $Rs = db_exec($Sl) or errDie("Unable to insert statement record in Cubit.", SELF);
        db_connect();
        # Update the supplier (make balance less)
        $sql = "UPDATE suppliers SET balance = (balance - '{$amt}'::numeric(13,2)) WHERE supid = '{$sup['supid']}'";
        $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
        suppledger($sup['supid'], $bank['accnum'], $sdate, $cheqnum, "Payment for purchases", $amt, "d");
        db_connect();
        # Record the payment record
        $sql = "INSERT INTO cashbook(bankid, trantype, date, name, descript, cheqnum, amount, banked, accinv, supid, ids, purids, pamounts, pdates, reference, div) VALUES ('{$bankid}', 'withdrawal', '{$sdate}', '{$sup['supno']} - {$sup['supname']}', 'Supplier Payment to {$sup['supname']}', '{$cheqnum}', '{$amt}', 'no', '{$dept['credacc']}', '{$sup['supid']}', '{$ids}', '{$purids}', '{$pamounts}', '{$pdates}', '{$reference}', '" . 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);
        $link['accnum'] = $bank['accnum'];
        writetrans($dept['credacc'], $link['accnum'], $accdate, $refnum, $amt, "Supplier Payment to {$sup['supname']}");
        db_conn('cubit');
    }
    if ($all == 1) {
        $ids = "";
        $purids = "";
        $pamounts = "";
        $pdates = "";
        if (isset($invids)) {
            foreach ($invids as $key => $value) {
                # Get debt invoice info
                $sql = "SELECT id,pdate FROM suppurch WHERE purid ='{$invids[$key]}' AND div = '" . USER_DIV . "' ORDER BY balance LIMIT 1";
                $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>";
                }
                $pur = pg_fetch_array($invRslt);
                # reduce the money that has been paid
                $sql = "UPDATE suppurch SET balance = (balance - {$paidamt[$key]}::numeric(13,2)) WHERE purid = '{$invids[$key]}' AND div = '" . USER_DIV . "' AND id='{$pur['id']}'";
                $payRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
                $ids .= "|{$pur['id']}";
                $purids .= "|{$invids[$key]}";
                $pamounts .= "|{$paidamt[$key]}";
                $pdates .= "|{$pur['pdate']}";
            }
        }
        $samount = $amt - $amt * 2;
        if ($out1 > 0) {
            recordDT($out1, $sup['supid'], $sdate);
        }
        if ($out2 > 0) {
            recordDT($out2, $sup['supid'], $sdate, "1");
        }
        if ($out3 > 0) {
            recordDT($out3, $sup['supid'], $sdate, "2");
        }
        if ($out4 > 0) {
            recordDT($out4, $sup['supid'], $sdate, "3");
        }
        if ($out5 > 0) {
            recordDT($out5, $sup['supid'], $sdate, "4");
        }
        $Sl = "INSERT INTO sup_stmnt(supid, amount, edate, descript,ref,cacc, div) VALUES('{$sup['supid']}','{$samount}','{$sdate}', 'Payment','{$cheqnum}','{$bank['accnum']}', '" . 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 - '{$amt}'::numeric(13,2)) WHERE supid = '{$sup['supid']}' 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, supid, ids, purids, pamounts, pdates, reference, div) VALUES ('{$bankid}', 'withdrawal', '{$sdate}', '{$sup['supno']} - {$sup['supname']}', 'Supplier Payment to {$sup['supname']}', '{$cheqnum}', '{$amt}', 'no', '{$dept['credacc']}', '{$sup['supid']}', '{$ids}', '{$purids}', '{$pamounts}', '{$pdates}', '{$reference}', '" . 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);
        $link['accnum'] = $bank['accnum'];
        writetrans($dept['credacc'], $link['accnum'], $accdate, $refnum, $amt, "Supplier Payment to {$sup['supname']}");
        db_conn('cubit');
        suppledger($sup['supid'], $bank['accnum'], $sdate, $cheqnum, "Payment to Supplier", $amt, "d");
        db_connect();
    }
    if ($all == 2) {
        $ids = "";
        $purids = "";
        $pamounts = "";
        $pdates = "";
        db_conn('cubit');
        # Update the supplier (make balance less)
        $sql = "UPDATE suppliers SET balance = (balance - '{$amt}'::numeric(13,2)) WHERE supid = '{$sup['supid']}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
        # Begin updates
        if (isset($invids)) {
            foreach ($invids as $key => $value) {
                # Get debt invoice info
                $sql = "SELECT id,pdate FROM suppurch WHERE purid ='{$invids[$key]}' AND div = '" . USER_DIV . "' ORDER BY balance LIMIT 1";
                $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>";
                }
                $pur = pg_fetch_array($invRslt);
                # reduce the money that has been paid
                $sql = "UPDATE suppurch SET balance = (balance - '{$paidamt[$key]}'::numeric(13,2)) WHERE purid = '{$invids[$key]}' AND div = '" . USER_DIV . "' AND id='{$pur['id']}'";
                $payRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
                $samount = $paidamt[$key] - $paidamt[$key] * 2;
                $Sl = "INSERT INTO sup_stmnt(supid, amount, edate, descript,ref,cacc,div) VALUES('{$sup['supid']}','{$samount}','{$sdate}', 'Payment - Purchase: {$invids[$key]}','{$cheqnum}','{$bank['accnum']}', '" . USER_DIV . "')";
                $Rs = db_exec($Sl) or errDie("Unable to insert statement record in Cubit.", SELF);
                suppledger($sup['supid'], $bank['accnum'], $sdate, $invids[$key], "Payment for Purchase No. {$invids[$key]}", $paidamt[$key], "d");
                db_connect();
                # record the payment on the statement
                $ids .= "|{$pur['id']}";
                $purids .= "|{$invids[$key]}";
                $pamounts .= "|{$paidamt[$key]}";
                $pdates .= "|{$pur['pdate']}";
            }
        }
        $samount = $amt - $amt * 2;
        db_conn('cubit');
        # Record the payment record
        $sql = "INSERT INTO cashbook(bankid, trantype, date, name, descript, cheqnum, amount, banked, accinv, supid, ids, purids, pamounts, pdates, reference, div) VALUES ('{$bankid}', 'withdrawal', '{$sdate}', '{$sup['supno']} - {$sup['supname']}', 'Supplier Payment to {$sup['supname']}', '{$cheqnum}', '{$amt}', 'no', '{$dept['credacc']}', '{$sup['supid']}', '{$ids}', '{$purids}', '{$pamounts}', '{$pdates}', '{$reference}', '" . 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);
        $link['accnum'] = $bank['accnum'];
        writetrans($dept['credacc'], $link['accnum'], $accdate, $refnum, $amt, "Supplier Payment to {$sup['supname']}");
        db_conn('cubit');
    }
    db_conn('cubit');
    $Sl = "DELETE FROM suppurch WHERE balance=0::numeric(13,2)";
    $Rx = db_exec($Sl);
    pglib_transaction("COMMIT");
    # status report
    $write = "\n\t\t\t<table " . TMPL_tblDflts . " width='100%'>\n\t\t\t\t<tr>\n\t\t\t\t\t<th>Bank Payment</th>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='datacell'><td>Bank Payment added to cash book.</td></tr>\n\t\t\t</table>";
    # main table (layout with menu)
    $OUTPUT = "<center>\n\t<table width='90%'>\n\t\t<tr valign='top'>\n\t\t\t<td width='50%'>{$write}</td>\n\t\t\t<td align='center'>\n\t\t\t\t<table " . TMPL_tblDflts . " width='80%'>\n\t\t\t\t\t<tr>\n\t\t\t\t\t\t<th>Quick Links</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><a href='bank-pay-supp.php'>Add supplier payment</a></td>\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><a href='bank-pay-add.php'>Add Bank Payment</a></td>\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><a href='bank-recpt-add.php'>Add Bank Receipt</a></td>\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><a href='cashbook-view.php'>View Cash Book</a></td>\n\t\t\t\t\t</tr>\n\t\t\t\t</table>\n\t\t\t</td>\n\t\t</tr>\n\t</table>";
    return $OUTPUT;
}