コード例 #1
0
function write($_POST)
{
    #get vars
    extract($_POST);
    if (isset($cusnum) && customer_overdue($cusnum)) {
        return details($_POST, "<li class='err'>Customer is overdue, account blocked!</li>");
    }
    $pcredit += 0;
    $pcash += 0;
    $pcheque += 0;
    $pcc += 0;
    $deptid += 0;
    db_conn('cubit');
    if (isset($printsales)) {
        $Sl = "SELECT * FROM settings WHERE constant='PSALES'";
        $Ri = db_exec($Sl) or errDie("Unable to get settings.");
        if (pg_num_rows($Ri) < 1) {
            $Sl = "INSERT INTO settings (constant,value,div) VALUES ('PSALES','Yes','" . USER_DIV . "')";
            $Ri = db_exec($Sl);
        } else {
            $Sl = "UPDATE settings SET value='Yes' WHERE constant='PSALES' AND div='" . USER_DIV . "'";
            $Ri = db_exec($Sl);
        }
    } else {
        $Sl = "UPDATE settings SET value='No' WHERE constant='PSALES' AND div='" . USER_DIV . "'";
        $Ri = db_exec($Sl);
    }
    //$it+=0;
    # validate input
    require_lib("validate");
    $v = new validate();
    if (isset($client)) {
        $v->isOk($client, "string", 0, 20, "Invalid Customer.");
    } else {
        $client = "";
    }
    if (isset($vatnum)) {
        $v->isOk($vatnum, "string", 0, 30, "Invalid VAT Number.");
    } else {
        $vatnum = "";
    }
    $v->isOk($invid, "num", 1, 20, "Invalid Invoice Number.");
    $v->isOk($telno, "string", 0, 20, "Invalid Customer Telephone Number.");
    $v->isOk($cordno, "string", 0, 20, "Invalid Customer Order Number.");
    $v->isOk($comm, "string", 0, 255, "Invalid Comments.");
    $v->isOk($ordno, "string", 0, 20, "Invalid sales order number.");
    $v->isOk($chrgvat, "string", 1, 4, "Invalid charge vat option.");
    $v->isOk($salespn, "string", 1, 255, "Invalid sales person.");
    $v->isOk($pinv_day, "num", 1, 2, "Invalid Invoice Date day.");
    $v->isOk($pinv_month, "num", 1, 2, "Invalid Invoice Date month.");
    $v->isOk($pinv_year, "num", 1, 5, "Invalid Invoice Date year.");
    $odate = $pinv_year . "-" . $pinv_month . "-" . $pinv_day;
    if (!checkdate($pinv_month, $pinv_day, $pinv_year)) {
        $v->isOk($odate, "num", 1, 1, "Invalid Invoice Date.");
    }
    $v->isOk($traddisc, "float", 0, 20, "Invalid Trade Discount.");
    if ($traddisc > 100) {
        $v->isOk($traddisc, "float", 0, 0, "Error : Trade Discount cannot be more than 100 %.");
    }
    $v->isOk($delchrg, "float", 0, 20, "Invalid Delivery Charge.");
    $v->isOk($SUBTOT, "float", 0, 20, "Invalid Delivery Charge.");
    $odate = $pinv_year . "-" . $pinv_month . "-" . $pinv_day;
    if (!checkdate($pinv_month, $pinv_day, $pinv_year)) {
        $v->isOk($odate, "num", 1, 1, "Invalid Invoice Date.");
    }
    # used to generate errors
    $error = "asa@";
    # check if duplicate serial number selected, remove blanks
    if (isset($sernos)) {
        if (!ext_isUnique(ext_remBlnk($sernos))) {
            //$v->isOk ($error, "num", 0, 0, "Error : Serial Numbers must be unique per line item.");
        }
    }
    # check is serial no was selected
    if (isset($stkids)) {
        foreach ($stkids as $keys => $stkid) {
            if (is_numeric($stkid)) {
                $sql = "SELECT units, stkcod FROM cubit.stock WHERE stkid='{$stkid}'";
                $stock_rslt = db_exec($sql) or errDie("Unable to retrieve stock.");
                list($stock_units, $stock_code) = pg_fetch_array($stock_rslt);
                if ($qtys[$keys] > $stock_units) {
                    $v->addError(0, "Not enough stock available for {$stock_code}");
                }
            }
            # check if serial is selected
            if (ext_isSerial("stock", "stkid", $stkid) && !isset($sernos[$keys])) {
                $v->isOk($error, "num", 0, 0, "Error : Missing serial number for product number (2): <b>" . ($keys + 1) . "</b>");
            } elseif (ext_isSerial("stock", "stkid", $stkid) && strlen($sernos[$keys]) <= 0 && strlen($sernos_ss[$keys]) <= 0) {
                $v->isOk($error, "num", 0, 0, "Error : Missing serial number for product number (1): <b>" . ($keys + 1) . "</b>");
            }
        }
    }
    # check quantities
    if (isset($qtys)) {
        foreach ($qtys as $keys => $qty) {
            $discp[$keys] += 0;
            $disc[$keys] += 0;
            $v->isOk($qty, "num", 1, 10, "Invalid Quantity for product number : <b>" . ($keys + 1) . "</b>");
            $v->isOk($disc[$keys], "float", 0, 20, "Invalid Discount for product number : <b>" . ($keys + 1) . "</b>.");
            if ($disc[$keys] > $unitcost[$keys]) {
                $v->isOk($disc[$keys], "float", 0, 0, "Error : Discount for product number : <b>" . ($keys + 1) . "</b> is more than the unitcost.");
            }
            $v->isOk($discp[$keys], "float", 0, 20, "Invalid Discount Percentage 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 ($qty < 1) {
                $v->isOk($qty, "num", 0, 0, "Error : Item Quantity must be at least one. Product number : <b>" . ($keys + 1) . "</b>");
            }
        }
    }
    # check whids
    if (isset($whids)) {
        foreach ($whids as $keys => $whid) {
            $v->isOk($whid, "num", 1, 10, "Invalid Store number, please enter all details.");
        }
    }
    $cusnum += 0;
    # check stkids
    if (isset($stkids)) {
        foreach ($stkids as $keys => $stkid) {
            $v->isOk($stkid, "num", 1, 10, "Invalid Stock number, please enter all details.");
        }
    }
    # check amt
    if (isset($amt)) {
        foreach ($amt as $keys => $amount) {
            $v->isOk($amount, "float", 1, 20, "Invalid Amount, please enter all details.");
        }
    }
    $des = remval($des);
    # 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);
    }
    if (strlen($client) < 1) {
        $client = "Cash Sale";
    }
    if (strlen($vatnum) < 1) {
        $vatnum = "";
    }
    $_POST['client'] = $client;
    $_POST['vatnum'] = $vatnum;
    $_POST['telno'] = $telno;
    $_POST['cordno'] = $cordno;
    # Get invoice info
    db_connect();
    $sql = "SELECT * FROM pinvoices WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
    $invRslt = db_exec($sql) or errDie("Unable to get invoice information");
    if (pg_numrows($invRslt) < 1) {
        return "<li>- Invoice Not Found</li>";
    }
    $inv = pg_fetch_array($invRslt);
    $inv['traddisc'] = $traddisc;
    $inv['chrgvat'] = $chrgvat;
    # check if invoice has been printed
    if ($inv['printed'] == "y") {
        $error = "<li class='err'> Error : Invoice number <b>{$invid}</b> has already been printed.</li>";
        $error .= "<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $error;
    }
    # get department
    db_conn("exten");
    $sql = "SELECT * FROM departments WHERE deptid = '{$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);
    }
    # fix those nasty zeros
    $traddisc += 0;
    $delchrg += 0;
    $vatamount = 0;
    $showvat = TRUE;
    # insert invoice to DB
    db_connect();
    # begin updating
    pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
    /* -- Start remove old items -- */
    # get selected stock in this invoice
    $sql = "SELECT * FROM pinv_items  WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
    $stktRslt = db_exec($sql);
    while ($stkt = pg_fetch_array($stktRslt)) {
        # update stock(alloc + qty)
        $sql = "UPDATE stock SET alloc = (alloc - '{$stkt['qty']}')  WHERE stkid = '{$stkt['stkid']}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update stock to Cubit.", SELF);
        if (strlen($stkt['serno']) > 0) {
            ext_unresvSer($stkt['serno'], $stkt['stkid']);
        }
    }
    # remove old items
    $sql = "DELETE FROM pinv_items WHERE invid='{$invid}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to update invoice items in Cubit.", SELF);
    /* -- End remove old items -- */
    $taxex = 0;
    if (isset($qtys)) {
        foreach ($qtys as $keys => $value) {
            /* set the serial ss field for serials selected from list */
            if ($sernos_ss[$keys] == "*_*_*CUBIT_SERIAL_SELECT_BOX*_*_*") {
                $sernos_ss[$keys] = $sernos[$keys];
            }
            if (isset($remprod) && in_array($keys, $remprod)) {
                if ($sernos[$keys] == $sernos_ss[$keys] && $sernos_ss[$keys] != "") {
                    $chr = substr($sernos[$keys], strlen($sernos[$keys]) - 1, 1);
                    $tab = "ss{$chr}";
                    /* mark barcoded item as unavailable */
                    $sql = "UPDATE " . $tab . " SET active='yes' WHERE code = '{$sernos[$keys]}' AND div = '" . USER_DIV . "'";
                    db_exec($sql);
                }
            } else {
                if (isset($accounts[$keys]) && $accounts[$keys] != 0) {
                    $accounts[$keys] += 0;
                    # Get selamt from selected stock
                    db_conn('core');
                    $Sl = "SELECT * FROM accounts WHERE accid='{$accounts[$keys]}'";
                    $Ri = db_exec($Sl) or errDie("Unable to get account data.");
                    $ad = pg_fetch_array($Ri);
                    $amt[$keys] = $qtys[$keys] * $unitcost[$keys];
                    db_conn('cubit');
                    $Sl = "SELECT * FROM vatcodes WHERE id='{$vatcodes[$keys]}'";
                    $Ri = db_exec($Sl);
                    if (pg_num_rows($Ri) < 1) {
                        return details($_POST, "<li class='err'>Please select the vatcode for all your items.</li>");
                    }
                    $vd = pg_fetch_array($Ri);
                    if ($vd['zero'] == "Yes") {
                        $excluding = "y";
                    } else {
                        $excluding = "";
                    }
                    if (TAX_VAT != $vd['vat_amount'] and $vd['vat_amount'] != "0.00") {
                        $showvat = FALSE;
                    }
                    $vr = vatcalc($amt[$keys], $inv['chrgvat'], $excluding, $inv['traddisc'], $vd['vat_amount']);
                    $vrs = explode("|", $vr);
                    $ivat = $vrs[0];
                    $iamount = $vrs[1];
                    $vatamount += $ivat;
                    # Check Tax Excempt
                    if ($vd['zero'] == "Yes") {
                        $taxex += $amt[$keys];
                        $exvat = "y";
                    } else {
                        $exvat = "n";
                    }
                    //$newvat+=vatcalc($amt[$keys],$chrgvat,$exvat,$traddisc);
                    $vatcodes[$keys] += 0;
                    $accounts[$keys] += 0;
                    $descriptions[$keys] = remval($descriptions[$keys]);
                    $wtd = $whids[$keys];
                    # insert invoice items
                    $sql = "INSERT INTO pinv_items(invid, whid, stkid, qty, unitcost,\n\t\t\t\t\t\t\t\tamt, disc, discp, ss, serno, div,vatcode,description,\n\t\t\t\t\t\t\t\taccount)\n\t\t\t\t\t\t\tVALUES('{$invid}', '{$whids[$keys]}', '{$stkids[$keys]}',\n\t\t\t\t\t\t\t\t'{$qtys[$keys]}', '{$unitcost[$keys]}', '{$amt[$keys]}',\n\t\t\t\t\t\t\t\t'{$disc[$keys]}', '{$discp[$keys]}', '', '','" . USER_DIV . "',\n\t\t\t\t\t\t\t\t'{$vatcodes[$keys]}','{$descriptions[$keys]}',\n\t\t\t\t\t\t\t\t'{$accounts[$keys]}')";
                    $rslt = db_exec($sql) or errDie("Unable to insert invoice items to Cubit.", SELF);
                } else {
                    # 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);
                    # Calculate the Discount discount
                    if ($disc[$keys] < 1) {
                        if ($discp[$keys] > 0) {
                            $disc[$keys] = $discp[$keys] / 100 * $unitcost[$keys];
                        }
                    } else {
                        $discp[$keys] = $disc[$keys] * 100 / $unitcost[$keys];
                    }
                    # Calculate amount
                    $amt[$keys] = $qtys[$keys] * ($unitcost[$keys] - $disc[$keys]);
                    $Sl = "SELECT * FROM vatcodes WHERE id='{$vatcodes[$keys]}'";
                    $Ri = db_exec($Sl);
                    if (pg_num_rows($Ri) < 1) {
                        return details($_POST, "<li class=err>Please select the vatcode for all your items.</li>");
                    }
                    $vd = pg_fetch_array($Ri);
                    if ($vd['zero'] == "Yes") {
                        $excluding = "y";
                    } else {
                        $excluding = "";
                    }
                    if (TAX_VAT != $vd['vat_amount'] and $vd['vat_amount'] != "0.00") {
                        $showvat = FALSE;
                    }
                    $vr = vatcalc($amt[$keys], $inv['chrgvat'], $excluding, $inv['traddisc'], $vd['vat_amount']);
                    $vrs = explode("|", $vr);
                    $ivat = $vrs[0];
                    $iamount = $vrs[1];
                    $vatamount += $ivat;
                    # Check Tax Excempt
                    if ($stk['exvat'] == 'yes' || $vd['zero'] == "Yes") {
                        $taxex += $amt[$keys];
                        $exvat = "y";
                    } else {
                        $exvat = "n";
                    }
                    $wtd = $whids[$keys];
                    # insert invoice items
                    $sql = "INSERT INTO pinv_items(invid, whid, stkid, qty,\n\t\t\t\t\t\t\t\tunitcost, amt, disc, discp, ss, serno, div,vatcode)\n\t\t\t\t\t\t\tVALUES('{$invid}', '{$whids[$keys]}', '{$stkids[$keys]}',\n\t\t\t\t\t\t\t\t'{$qtys[$keys]}', '{$unitcost[$keys]}', '{$amt[$keys]}',\n\t\t\t\t\t\t\t\t'{$disc[$keys]}', '{$discp[$keys]}', '{$sernos_ss[$keys]}', '{$sernos[$keys]}',\n\t\t\t\t\t\t\t\t'" . USER_DIV . "','{$vatcodes[$keys]}')";
                    // $sql = "INSERT INTO pinv_items(invid, whid, stkid, qty, unitcost, amt, disc, discp, div) VALUES('$invid', '$whids[$keys]', '$stkids[$keys]', '$qtys[$keys]', '$unitcost[$keys]','$amt[$keys]', '$disc[$keys]', '$discp[$keys]', '".USER_DIV."')";
                    $rslt = db_exec($sql) or errDie("Unable to insert invoice items to Cubit.", SELF);
                    if (strlen($sernos[$keys]) > 0) {
                        ext_resvSer($sernos[$keys], $stk['stkid']);
                    }
                    # update stock(alloc + qty)
                    $sql = "UPDATE stock SET alloc = (alloc + '{$qtys[$keys]}') WHERE stkid = '{$stkids[$keys]}' AND div = '" . USER_DIV . "'";
                    $rslt = db_exec($sql) or errDie("Unable to update stock to Cubit.", SELF);
                }
            }
            # everything is set place done button
            $_POST["done"] = " | <input name='doneBtn' type='submit' value='Process'>";
        }
    } else {
        $_POST["done"] = "";
    }
    db_conn('cubit');
    $Sl = "SELECT * FROM vatcodes WHERE id='{$delvat}'";
    $Ri = db_exec($Sl);
    // 		/*if(pg_num_rows($Ri)>0) {
    // 			*/$taxex += $delchrg;
    // 		}
    $vd = pg_fetch_array($Ri);
    if ($vd['zero'] == "Yes") {
        $excluding = "y";
    } else {
        $excluding = "";
    }
    if (TAX_VAT != $vd['vat_amount'] and $vd['vat_amount'] != "0.00") {
        $showvat = FALSE;
    }
    $_POST['showvat'] = $showvat;
    $vr = vatcalc($delchrg, $inv['chrgvat'], $excluding, $inv['traddisc'], $vd['vat_amount']);
    $vrs = explode("|", $vr);
    $ivat = $vrs[0];
    $iamount = $vrs[1];
    $vatamount += $ivat;
    /* --- ----------- Clac --------------------- */
    ##----------------------NEW----------------------
    $sub = 0.0;
    if (isset($amt)) {
        $sub = sprint(array_sum($amt));
    }
    $VATP = TAX_VAT;
    if ($chrgvat == "exc") {
        $taxex = sprint($taxex - $taxex * $traddisc / 100);
        $subtotal = sprint($sub + $delchrg);
        $traddiscmt = sprint($subtotal * $traddisc / 100);
        $subtotal = sprint($subtotal - $traddiscmt);
        // 			$VAT=sprint(($subtotal-$taxex)*$VATP/100);
        $VAT = sprint($vatamount);
        $SUBTOT = $sub;
        $TOTAL = sprint($subtotal + $VAT);
        $delexvat = sprint($delchrg);
    } elseif ($chrgvat == "inc") {
        $ot = $taxex;
        $taxex = sprint($taxex - $taxex * $traddisc / 100);
        $subtotal = sprint($sub + $delchrg);
        $traddiscmt = sprint($subtotal * $traddisc / 100);
        $subtotal = sprint($subtotal - $traddiscmt);
        // 			$VAT=sprint(($subtotal-$taxex)*$VATP/(100+$VATP));
        $VAT = sprint($vatamount);
        $SUBTOT = sprint($sub);
        $TOTAL = sprint($subtotal);
        $delexvat = sprint($delchrg);
        $traddiscmt = sprint($traddiscmt);
    } else {
        $subtotal = sprint($sub + $delchrg);
        $traddiscmt = sprint($subtotal * $traddisc / 100);
        $subtotal = sprint($subtotal - $traddiscmt);
        $VAT = sprint(0);
        $SUBTOT = $sub;
        $TOTAL = $subtotal;
        $delexvat = sprint($delchrg);
    }
    $Sl = "SELECT * FROM posround";
    $Ri = db_exec($Sl);
    $data = pg_fetch_array($Ri);
    if ($data['setting'] == "5cent") {
        if (sprint(floor(sprint($TOTAL / 0.05))) != sprint($TOTAL / 0.05)) {
            $otot = $TOTAL;
            $nTOTAL = sprint(sprint(floor($TOTAL / 0.05)) * 0.05);
            $rounding = $otot - $nTOTAL;
        } else {
            $rounding = 0;
        }
    } else {
        $rounding = 0;
    }
    //print sprint(floor($TOTAL/0.05));
    #get accno if invoice is on credit
    if ($cusnum != "0") {
        $get_acc = "SELECT * FROM customers WHERE cusnum = '{$cusnum}' LIMIT 1";
        $run_acc = db_exec($get_acc) or errDie("Unable to get customer information");
        if (pg_numrows($run_acc) < 1) {
            $accno = "";
        } else {
            $arr = pg_fetch_array($run_acc);
            $cusacc = $arr['accno'];
        }
    } else {
        $cusacc = "";
    }
    //	die($cusnum);
    # insert invoice to DB
    $sql = "UPDATE pinvoices SET pcredit='{$pcredit}',cusnum='{$cusnum}',delvat='{$delvat}',rounding='{$rounding}',pcash='{$pcash}',pcheque='{$pcheque}',\n\t\tpcc='{$pcc}',deptid='{$deptid}',deptname = '{$dept['deptname']}', cusname = '{$client}', cordno = '{$cordno}', ordno = '{$ordno}',chrgvat = '{$chrgvat}',\n\t\tsalespn = '{$salespn}', odate = '{$odate}', traddisc = '{$traddisc}', delchrg = '{$delchrg}', subtot = '{$SUBTOT}', vat = '{$VAT}', total = '{$TOTAL}',\n\t\tbalance = '{$pcredit}', comm = '{$comm}', discount='{$traddiscmt}', delivery='{$delexvat}', vatnum='{$vatnum}', cusacc = '{$cusacc}', telno='{$telno}'\n\t\tWHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
    # remove old data
    $sql = "DELETE FROM pinv_data WHERE invid='{$invid}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to update invoice data in Cubit.", SELF);
    # put in new data
    $sql = "INSERT INTO pinv_data(invid, dept, customer, div) VALUES('{$invid}', '{$dept['deptname']}', '{$client}', '" . USER_DIV . "')";
    $rslt = db_exec($sql) or errDie("Unable to insert invoice data to Cubit.", SELF);
    # commit updatin
    if (strlen($bar) > 0) {
        /* check if there a stock item with global barcode matching input barcode */
        $sql = "SELECT * FROM stock WHERE bar='{$bar}' AND div = '" . USER_DIV . "'";
        $barRslt = db_exec($sql);
        if (pg_num_rows($barRslt) <= 0) {
            /* fetch last character of barcode */
            $chr = substr($bar, strlen($bar) - 1, 1);
            /* invalid barcode */
            if (!is_numeric($chr)) {
                return details($_POST, "The code you selected is invalid");
            }
            /* which barcode table to scan for stock id */
            $tab = "ss{$chr}";
            $stid = barext_dbget($tab, 'code', $bar, 'stock');
            $stab = "serial{$chr}";
            $sstid = serext_dbget($stab, 'serno', $bar, 'stkid');
            /* non-existing barcode, check for serial number */
            if ($stid <= 0) {
                if ($sstid <= 0) {
                    return details($_POST, "<li class='err'>The serial number/bar code you selected is not in the system or is not available.</li>");
                }
                if (serext_dbnum($stab, 'serno', $bar, 'stkid') > 1) {
                    return details($_POST, "<li class='err'>Duplicate serial numbers found, please scan barcode or select stock item.</li>");
                }
                /* mark barcoded item as unavailable */
                $sql = "UPDATE " . $stab . " SET rsvd='y' WHERE serno='{$bar}'";
                db_exec($sql);
                $serno_bar = "{$bar}";
                $stid = $sstid;
            } else {
                if ($sstid > 0) {
                    return details($_POST, "<li class='err'>A serial and barcode with same value, please scan other value or select product manually.</li>");
                }
                /* mark barcoded item as unavailable */
                $sql = "UPDATE " . $tab . " SET active='no' WHERE code='{$bar}' AND div='" . USER_DIV . "'";
                db_exec($sql);
                $serno_bar = "{$bar}";
            }
            /* fetch stock row for selected item */
            $sql = "SELECT * FROM stock WHERE stkid = '{$stid}' AND div = '" . USER_DIV . "'";
            $barRslt = db_exec($sql);
        } else {
            $serno_bar = "";
        }
        $s = pg_fetch_array($barRslt);
        /* allocate stock item */
        $sql = "UPDATE stock SET alloc = (alloc + '1') WHERE stkid = '{$s['stkid']}' AND div = '" . USER_DIV . "'";
        db_exec($sql) or errDie("Unable to update stock to Cubit.", SELF);
        $sql = "INSERT INTO pinv_items(invid, whid, stkid, qty, unitcost, amt,\n\t\t\t\t\tdisc, discp, ss, serno, div)\n\t\t\t\tVALUES('{$invid}', '{$s['whid']}', '{$s['stkid']}', '1','{$s['selamt']}',\n\t\t\t\t\t'{$s['selamt']}', '0', '0','{$bar}', '{$serno_bar}', '" . USER_DIV . "')";
        db_exec($sql) or errDie("Unable to insert invoice items to Cubit.", SELF);
    }
    pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
    /* --- Start button Listeners --- */
    if (isset($doneBtn)) {
        # check if stock was selected(yes = put done button)
        db_connect();
        $sql = "SELECT stkid FROM pinv_items WHERE invid = '{$inv['invid']}' AND div = '" . USER_DIV . "'";
        $crslt = db_exec($sql);
        if (pg_numrows($crslt) < 1) {
            $error = "<li class='err'> Error : Invoice number has no items.";
            return details($_POST, $error);
        }
        $TOTAL = sprint($TOTAL - $rounding);
        #check for credit limit
        if ($cusnum != "0") {
            #customer is selected ... get info
            $sql = "SELECT * FROM customers WHERE cusnum = '{$cusnum}' AND location != 'int' AND div = '" . USER_DIV . "'";
            $custRslt = db_exec($sql) or errDie("Unable to view customer");
            if (pg_numrows($custRslt) < 1) {
                $cust['balance'] = "0";
                $cust['creditlimit'] = "0";
            } else {
                $cust = pg_fetch_array($custRslt);
            }
            #customer is set check for response
            if ($pcredit + $cust['balance'] > $cust['credlimit']) {
                #limit reached ... check for block
                db_conn("cubit");
                $get_check = "SELECT value FROM set WHERE label = 'CUST_INV_WARN' LIMIT 1";
                $run_check = db_exec($get_check) or errDie("Unable to get credit limit response setting");
                if (pg_numrows($run_check) < 1) {
                    #no setting ? do nothing ....
                } else {
                    $sarr = pg_fetch_array($run_check);
                    if ($sarr['value'] == "block") {
                        #block account ...
                        return details($_POST, "<li class='err'>Warning : Customers Credit limit of <b>" . CUR . " " . sprint($cust["credlimit"]) . "</b> has been exceeded.</li>");
                    }
                }
                # Check permissions
                if (!perm("invoice-limit-override.php")) {
                    return details($_POST, "<li class='err'>Warning : Customers Credit limit of <b>" . CUR . " " . sprint($cust["credlimit"]) . "</b> has been exceeded.</li>");
                }
            }
        }
        if ($pcash + $pcheque + $pcc + $pcredit < $TOTAL) {
            return details($_POST, "<li class='err'>The total of all the payments is less than the invoice total</li>");
        }
        $change = sprint(sprint($pcash + $pcheque + $pcc + $pcredit) - sprint($TOTAL));
        $pcash = sprint($pcash - $change);
        if ($pcash < 0) {
            $pcash = 0;
        }
        if (sprint($pcash + $pcheque + $pcc + $pcredit) != sprint($TOTAL)) {
            return details($_POST, "<li class='err'>The total of all the payments is not equal to the invoice total.<br>\n\t\t\t(You can only overpay with cash)</li>");
        }
        # insert quote to DB
        $sql = "UPDATE pinvoices SET done = 'y' WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update invoice status in Cubit.", SELF);
        # print the invoice
        $OUTPUT = "\n\t\t\t\t\t<script>printer2('pos-invoice-print.php?invid={$invid}');</script>\n\t\t\t\t\t<input type='button' value='Create New POS Invoice' onClick=\"move('pos-invoice-new-no-neg.php');\">";
        require "template.php";
    } elseif (isset($saveBtn)) {
        // Final Laytout
        $write = "\n\t\t<table " . TMPL_tblDflts . ">\n\t\t\t<tr>\n\t\t\t\t<th>New Point of Sale Invoice Saved</th>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Invoice for <b>{$client}</b> has been saved.</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='pos-invoice-new-no-neg.php'>New Point of Sale Invoice</a></td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td><a href='pos-invoice-list.php'>View Point of Sale Invoices</a></td>\n\t\t\t</tr>\n\t\t\t<script>document.write(getQuicklinkSpecial());</script>\n\t\t</table>";
        return $write;
    } elseif (isset($cancel)) {
        // Final Laytout
        $write = "\n\t\t<table " . TMPL_tblDflts . ">\n\t\t\t<tr>\n\t\t\t\t<th>New Point of Sale Invoice Saved</th>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Invoice for <b>{$client}</b> has been saved.</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='pos-invoice-new-no-neg.php'>New Point of Sale Invoice</a></td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td><a href='pos-invoice-list.php'>View Point of Sale Invoices</a></td>\n\t\t\t</tr>\n\t\t\t<script>document.write(getQuicklinkSpecial());</script>\n\t\t</table>";
        return $write;
    } else {
        if (isset($wtd)) {
            $_POST['wtd'] = $wtd;
        }
        return details($_POST);
    }
    /* --- End button Listeners --- */
}
コード例 #2
0
function write($_POST)
{
    # Get vars
    extract($_POST);
    if (!isset($cusnum)) {
        return details($_POST, "<li class='err'>Please select customer/department first.</li>");
    }
    $delvat += 0;
    db_conn('cubit');
    if (isset($printsales)) {
        $Sl = "SELECT * FROM settings WHERE constant='SALES'";
        $Ri = db_exec($Sl) or errDie("Unable to get settings.");
        if (pg_num_rows($Ri) < 1) {
            $Sl = "INSERT INTO settings (constant,value,div) VALUES ('SALES','Yes','" . USER_DIV . "')";
            $Ri = db_exec($Sl);
        } else {
            $Sl = "UPDATE settings SET value='Yes' WHERE constant='SALES' AND div='" . USER_DIV . "'";
            $Ri = db_exec($Sl);
        }
    } else {
        $Sl = "UPDATE settings SET value='No' WHERE constant='SALES' AND div='" . USER_DIV . "'";
        $Ri = db_exec($Sl);
    }
    if (isset($printdel)) {
        $Sl = "SELECT * FROM settings WHERE constant='Delivery Note'";
        $Ri = db_exec($Sl) or errDie("Unable to get settings.");
        if (pg_num_rows($Ri) < 1) {
            $Sl = "INSERT INTO settings (constant,value,div) VALUES ('Delivery Note','Yes','" . USER_DIV . "')";
            $Ri = db_exec($Sl);
        } else {
            $Sl = "UPDATE settings SET value='Yes' WHERE constant='Delivery Note' AND div='" . USER_DIV . "'";
            $Ri = db_exec($Sl);
        }
    } else {
        $Sl = "UPDATE settings SET value='No' WHERE constant='Delivery Note' AND div='" . USER_DIV . "'";
        $Ri = db_exec($Sl);
    }
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($cusnum, "num", 1, 20, "Invalid Customer, Please select a customer.");
    $v->isOk($branch, "num", 1, 20, "Invalid Branch, Please select a branch.");
    $v->isOk($invid, "num", 1, 20, "Invalid Invoice Number.");
    $v->isOk($cordno, "string", 0, 20, "Invalid Customer Order Number.");
    if (!isset($ria)) {
        $ria = "";
    }
    $v->isOk($ria, "string", 0, 20, "Invalid stock code(fist letters).");
    $v->isOk($comm, "string", 0, 1024, "Invalid Comments.");
    $v->isOk($docref, "string", 0, 20, "Invalid Document Reference No.");
    $v->isOk($ordno, "string", 0, 20, "Invalid sales order number.");
    $v->isOk($chrgvat, "string", 1, 4, "Invalid charge vat option.");
    $v->isOk($terms, "num", 1, 20, "Invalid terms.");
    $v->isOk($salespn, "string", 1, 255, "Invalid sales person.");
    $v->isOk($inv_date_day, "num", 1, 2, "Invalid Invoice Date day.");
    $v->isOk($inv_date_month, "num", 1, 2, "Invalid Invoice Date month.");
    $v->isOk($inv_date_year, "num", 1, 5, "Invalid Invoice Date year.");
    $odate = $inv_date_year . "-" . $inv_date_month . "-" . $inv_date_day;
    if (!checkdate($inv_date_month, $inv_date_day, $inv_date_year)) {
        $v->isOk($odate, "num", 1, 1, "Invalid Invoice Date.");
    }
    $v->isOk($traddisc, "float", 0, 20, "Invalid Trade Discount.");
    if ($traddisc > 100) {
        $v->isOk($traddisc, "float", 0, 0, "Error : Trade Discount cannot be more than 100 %.");
    }
    $v->isOk($delchrg, "float", 0, 20, "Invalid Delivery Charge.");
    $v->isOk($SUBTOT, "float", 0, 20, "Invalid Delivery Charge.");
    # used to generate errors
    $error = "asa@";
    # check if duplicate serial number selected, remove blanks
    if (isset($sernos)) {
        $tmp_sernos = $sernos;
        // only check for uniqueness among items not selected for removal
        foreach ($sernos as $k => $serno_val) {
            if (isset($remprod) && in_array($k, $remprod)) {
                unset($tmp_sernos[$k]);
            }
        }
        if (!ext_isUnique(ext_remBlnk($tmp_sernos))) {
            $v->isOk($error, "num", 0, 0, "Error : Serial Numbers must be unique per line item.");
        }
    }
    # check is serai no was selected
    if (isset($stkids)) {
        foreach ($stkids as $keys => $stkid) {
            # check if serial is selected
            if (ext_isSerial("stock", "stkid", $stkid) && !isset($sernos[$keys])) {
                $v->isOk($error, "num", 0, 0, "Error : Missing serial number for product number : <b>" . ($keys + 1) . "</b>");
            } elseif (ext_isSerial("stock", "stkid", $stkid) && !(strlen($sernos[$keys]) > 0)) {
                $v->isOk($error, "num", 0, 0, "Error : Missing serial number for product number : <b>" . ($keys + 1) . "</b>");
            }
        }
    }
    if (!isset($qtys) && isset($qtemp)) {
        $qtys[] = $qtemp;
    } elseif (isset($qtys) && isset($qtemp)) {
        //array_unshift ($qtys,$qtemp);
        $qtys[] = $qtemp;
    }
    # check quantities
    if (isset($qtys)) {
        foreach ($qtys as $keys => $qty) {
            $discp[$keys] += 0;
            $disc[$keys] += 0;
            $v->isOk($qty, "float", 1, 15, "Invalid Quantity for product number : <b>" . ($keys + 1) . "</b>");
            $v->isOk($disc[$keys], "float", 0, 20, "Invalid Discount for product number : <b>" . ($keys + 1) . "</b>.");
            if ($disc[$keys] > $unitcost[$keys]) {
                $v->isOk($disc[$keys], "float", 0, 0, "Error : Discount for product number : <b>" . ($keys + 1) . "</b> is more than the unitcost.");
            }
            $v->isOk($discp[$keys], "float", 0, 20, "Invalid Discount Percentage for product number : <b>" . ($keys + 1) . "</b>.");
            if ($discp[$keys] > 100) {
                $v->isOk($discp[$keys], "float", 0, 0, "Error : Discount for product number : <b>" . ($keys + 1) . "</b> is more than 100 %.");
            }
            $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>");
            }
        }
    }
    # check whids
    if (isset($whids)) {
        foreach ($whids as $keys => $whid) {
            $v->isOk($whid, "num", 1, 10, "Invalid Store number, please enter all details.");
        }
    }
    # check stkids
    if (isset($stkids)) {
        foreach ($stkids as $keys => $stkid) {
            $v->isOk($stkid, "num", 1, 10, "Invalid Stock number, please enter all details.");
        }
    }
    # check amt
    if (isset($amt)) {
        foreach ($amt as $keys => $amount) {
            $v->isOk($amount, "float", 1, 20, "Invalid Amount, please enter all details.");
        }
    }
    # 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 invoice info
    db_connect();
    $sql = "SELECT * FROM invoices WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
    $invRslt = db_exec($sql) or errDie("Unable to get invoice information");
    if (pg_numrows($invRslt) < 1) {
        return "<li>- Invoice Not Found</li>";
    }
    $inv = pg_fetch_array($invRslt);
    $inv['traddisc'] = $traddisc;
    $inv['chrgvat'] = $chrgvat;
    if ($cusnum != $inv['cusnum'] or $branch != $inv['branch']) {
        $get_addr = "SELECT branch_descrip FROM customer_branches WHERE id = '{$branch}' AND div = '" . USER_DIV . "' LIMIT 1";
        $run_addr = db_exec($get_addr);
        if (pg_numrows($run_addr) < 1) {
            #no branch addres ? since we NEED to update the address, add the customer's here
            $get_cadd = "SELECT del_addr1 FROM customers WHERE cusnum = '{$cusnum}' LIMIT 1";
            $run_cadd = db_exec($get_cadd) or errDie("Unable to get customer delivery address");
            if (pg_numrows($run_cadd) < 1) {
                #no customer ??
                return details($_POST, "<li class='err'>Invalid customer selected.</li>");
            } else {
                $carr = pg_fetch_array($run_cadd);
                $update_addr = "UPDATE invoices SET del_addr  = '{$carr['del_addr1']}' WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
                $run_update = db_exec($update_addr) or errDie("Unable to update invoice information");
            }
        } else {
            $arr = pg_fetch_array($run_addr);
            $cust['addr1'] = $arr['branch_descrip'];
            if ($inv['del_addr'] != $arr['branch_descrip']) {
                $update_addr = "UPDATE invoices SET del_addr  = '{$arr['branch_descrip']}' WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
                $run_update = db_exec($update_addr) or errDie("Unable to update invoice information");
            }
        }
    }
    # check if invoice has been printed
    if ($inv['printed'] == "y") {
        $error = "<li class='err'> Error : Invoice number <b>{$invid}</b> has already been printed.</li>";
        $error .= "<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $error;
    }
    # Get selected customer info
    db_connect();
    $sql = "SELECT * FROM customers WHERE cusnum = '{$cusnum}' AND div = '" . USER_DIV . "'";
    $custRslt = db_exec($sql) or errDie("Unable to get customer information");
    if (pg_numrows($custRslt) < 1) {
        $sql = "SELECT * FROM inv_data WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
        $custRslt = db_exec($sql) or errDie("Unable to get customer information data");
        $cust = pg_fetch_array($custRslt);
        $cust['cusname'] = $cust['customer'];
        $cust['surname'] = "";
        $cust['addr1'] = "";
    } else {
        $cust = pg_fetch_array($custRslt);
        $inv['deptid'] = $cust['deptid'];
        # If customer was just selected, get the following
        if ($inv['cusnum'] == 0) {
            $traddisc = $cust['traddisc'];
            $terms = $cust['credterm'];
        }
    }
    # get department
    db_conn("exten");
    $sql = "SELECT * FROM departments WHERE deptid = '{$inv['deptid']}' AND div = '" . USER_DIV . "'";
    $deptRslt = db_exec($sql);
    if (pg_numrows($deptRslt) < 1) {
        $dept['deptname'] = "<i class='err'>Not Found</i>";
    } else {
        $dept = pg_fetch_array($deptRslt);
    }
    # fix those nasty zeros
    $traddisc += 0;
    $delchrg += 0;
    $vatamount = 0;
    $showvat = TRUE;
    # insert invoice to DB
    db_connect();
    # begin updating
    pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
    /* -- Start remove old items -- */
    # get selected stock in this invoice
    $sql = "SELECT * FROM inv_items  WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
    $stktRslt = db_exec($sql);
    while ($stkt = pg_fetch_array($stktRslt)) {
        # update stock(alloc + qty)
        $sql = "UPDATE stock SET alloc = (alloc - '{$stkt['qty']}')  WHERE stkid = '{$stkt['stkid']}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update stock to Cubit.", SELF);
        if (strlen($stkt['serno']) > 0) {
            ext_unresvSer($stkt['serno'], $stkt['stkid']);
        }
    }
    # remove old items
    $sql = "DELETE FROM inv_items WHERE invid='{$invid}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to update invoice items in Cubit.", SELF);
    /* -- End remove old items -- */
    $newvat = 0;
    $taxex = 0;
    if (isset($qtys)) {
        foreach ($qtys as $keys => $value) {
            /* set the serial ss field for serials selected from list */
            if ($sernos_ss[$keys] == "*_*_*CUBIT_SERIAL_SELECT_BOX*_*_*") {
                $sernos_ss[$keys] = $sernos[$keys];
            }
            if (isset($remprod) && in_array($keys, $remprod)) {
                $amt[$keys] = 0;
                if ($sernos[$keys] == $sernos_ss[$keys] && $sernos_ss[$keys] != "") {
                    $chr = substr($sernos[$keys], strlen($sernos[$keys]) - 1, 1);
                    $tab = "ss{$chr}";
                    /* mark barcoded item as unavailable */
                    $sql = "UPDATE " . $tab . " SET active='yes' WHERE code = '{$sernos[$keys]}' AND div = '" . USER_DIV . "'";
                    db_exec($sql);
                }
            } elseif (isset($accounts[$keys]) && $accounts[$keys] != 0) {
                $accounts[$keys] += 0;
                # Get selamt from selected stock
                db_conn('core');
                $Sl = "SELECT * FROM accounts WHERE accid='{$accounts[$keys]}'";
                $Ri = db_exec($Sl) or errDie("Unable to get account data.");
                $ad = pg_fetch_array($Ri);
                # Calculate amount
                $amt[$keys] = $qtys[$keys] * $unitcost[$keys];
                db_conn('cubit');
                $Sl = "SELECT * FROM vatcodes WHERE id='{$vatcodes[$keys]}'";
                $Ri = db_exec($Sl);
                if (pg_num_rows($Ri) < 1) {
                    return details($_POST, "<li class='err'>Please select the vatcode for all your items.</li>");
                }
                $vd = pg_fetch_array($Ri);
                if ($vd['zero'] == "Yes") {
                    $excluding = "y";
                } else {
                    $excluding = "";
                }
                if (TAX_VAT != $vd['vat_amount'] and $vd['vat_amount'] != "0.00") {
                    $showvat = FALSE;
                }
                $vr = vatcalc($amt[$keys], $inv['chrgvat'], $excluding, $inv['traddisc'], $vd['vat_amount']);
                $vrs = explode("|", $vr);
                $ivat = $vrs[0];
                $iamount = $vrs[1];
                $vatamount += $ivat;
                # Check Tax Excempt
                if ($vd['zero'] == "Yes") {
                    $taxex += $amt[$keys];
                    $exvat = "y";
                } else {
                    $exvat = "n";
                }
                //$newvat+=vatcalc($amt[$keys],$chrgvat,$exvat,$traddisc);
                $vatcodes[$keys] += 0;
                $accounts[$keys] += 0;
                $descriptions[$keys] = remval($descriptions[$keys]);
                $wtd = $whids[$keys];
                # insert invoice items
                $sql = "\n\t\t\t\t\t\tINSERT INTO inv_items (\n\t\t\t\t\t\t\tinvid, whid, stkid, qty, unitcost, amt, \n\t\t\t\t\t\t\tdisc, discp, serno, div, vatcode, description, \n\t\t\t\t\t\t\taccount, del\n\t\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t\t'{$invid}', '{$whids[$keys]}', '{$stkids[$keys]}', '{$qtys[$keys]}', '{$unitcost[$keys]}', '{$amt[$keys]}', \n\t\t\t\t\t\t\t'{$disc[$keys]}', '{$discp[$keys]}', '', '" . USER_DIV . "', '{$vatcodes[$keys]}', '{$descriptions[$keys]}', \n\t\t\t\t\t\t\t'{$accounts[$keys]}', '0'\n\t\t\t\t\t\t)";
                $rslt = db_exec($sql) or errDie("Unable to insert invoice items to Cubit.", SELF);
            } else {
                # 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);
                # Calculate the Discount discount
                if ($disc[$keys] < 1) {
                    if ($discp[$keys] > 0) {
                        $disc[$keys] = $discp[$keys] / 100 * $unitcost[$keys];
                    }
                } else {
                    $discp[$keys] = $disc[$keys] * 100 / $unitcost[$keys];
                }
                # Calculate amount
                $amt[$keys] = $qtys[$keys] * ($unitcost[$keys] - $disc[$keys]);
                $Sl = "SELECT * FROM vatcodes WHERE id='{$vatcodes[$keys]}'";
                $Ri = db_exec($Sl);
                if (pg_num_rows($Ri) < 1) {
                    return details($_POST, "<li class='err'>Please select the vatcode for all your items.</li>");
                }
                $vd = pg_fetch_array($Ri);
                if ($vd['zero'] == "Yes") {
                    $excluding = "y";
                } else {
                    $excluding = "";
                }
                if (TAX_VAT != $vd['vat_amount'] and $vd['vat_amount'] != "0.00") {
                    $showvat = FALSE;
                }
                $vr = vatcalc($amt[$keys], $inv['chrgvat'], $excluding, $inv['traddisc'], $vd['vat_amount']);
                $vrs = explode("|", $vr);
                $ivat = $vrs[0];
                $iamount = $vrs[1];
                $vatamount += $ivat;
                # Check Tax Excempt
                if ($stk['exvat'] == 'yes' || $vd['zero'] == "Yes") {
                    $taxex += $amt[$keys];
                    $exvat = "y";
                } else {
                    $exvat = "n";
                }
                //$newvat+=vatcalc($amt[$keys],$chrgvat,$exvat,$traddisc);
                $wtd = $whids[$keys];
                # insert invoice items
                $sql = "\n\t\t\t\t\t\tINSERT INTO inv_items (\n\t\t\t\t\t\t\tinvid, whid, stkid, qty, unitcost, amt, \n\t\t\t\t\t\t\tdisc, discp, ss, serno, div, \n\t\t\t\t\t\t\tvatcode, del\n\t\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t\t'{$invid}', '{$whids[$keys]}', '{$stkids[$keys]}', '{$qtys[$keys]}', '{$unitcost[$keys]}', '{$amt[$keys]}', \n\t\t\t\t\t\t\t'{$disc[$keys]}', '{$discp[$keys]}', '{$sernos_ss[$keys]}', '{$sernos[$keys]}', '" . USER_DIV . "', \n\t\t\t\t\t\t\t'{$vatcodes[$keys]}', '0'\n\t\t\t\t\t\t)";
                $rslt = db_exec($sql) or errDie("Unable to insert invoice items to Cubit.", SELF);
                if (strlen($sernos[$keys]) > 0) {
                    ext_resvSer($sernos[$keys], $stk['stkid']);
                }
                # update stock(alloc + qty)
                $sql = "UPDATE stock SET alloc = (alloc + '{$qtys[$keys]}') WHERE stkid = '{$stkids[$keys]}' AND div = '" . USER_DIV . "'";
                $rslt = db_exec($sql) or errDie("Unable to update stock to Cubit.", SELF);
            }
            # everything is set place done button
            $_POST["done"] = "\t| <input name='doneBtn' type='submit' value='Process'>";
            //if ($cust["email"] != "") {
            $_POST["done"] .= " | <input name='emailBtn' type='submit' value='Process and Email to Customer'>";
            //}
        }
    } else {
        $_POST["done"] = "";
    }
    //$newvat+=vatcalc($delchrg,$chrgvat,"no",$traddisc);
    db_conn('cubit');
    $Sl = "SELECT * FROM vatcodes WHERE id='{$delvat}'";
    $Ri = db_exec($Sl);
    $vd = pg_fetch_array($Ri);
    // 		if(pg_num_rows($Ri)>0) {
    // 			$taxex += $delchrg;
    // 		}
    if ($vd['zero'] == "Yes") {
        $excluding = "y";
    } else {
        $excluding = "";
    }
    if (TAX_VAT != $vd['vat_amount'] and $vd['vat_amount'] != "0.00") {
        $showvat = FALSE;
    }
    $_POST['showvat'] = $showvat;
    $vr = vatcalc($delchrg, $inv['chrgvat'], $excluding, $inv['traddisc'], $vd['vat_amount']);
    $vrs = explode("|", $vr);
    $ivat = $vrs[0];
    $iamount = $vrs[1];
    $vatamount += $ivat;
    /* --- ----------- Clac --------------------- */
    ##----------------------NEW----------------------
    $sub = 0.0;
    if (isset($amt)) {
        $sub = sprint(array_sum($amt));
    }
    $VATP = TAX_VAT;
    #get traddisc setting ...
    $traddisc_setting = getCSetting("SET_INV_TRADDISC");
    if ($chrgvat == "exc") {
        $taxex = sprint($taxex - $taxex * $traddisc / 100);
        $subtotal = sprint($sub + $delchrg);
        if ($traddisc_setting == "include") {
            $tradvar = $subtotal;
        } else {
            $tradvar = $sub;
        }
        $traddiscmt = sprint($tradvar * $traddisc / 100);
        $subtotal = sprint($subtotal - $traddiscmt);
        $VAT = $vatamount;
        $SUBTOT = $sub;
        $TOTAL = sprint($subtotal + $VAT);
        $delexvat = sprint($delchrg);
    } elseif ($chrgvat == "inc") {
        $ot = $taxex;
        $taxex = sprint($taxex - $taxex * $traddisc / 100);
        $subtotal = sprint($sub + $delchrg);
        if ($traddisc_setting == "include") {
            $tradvar = $subtotal;
        } else {
            $tradvar = $sub;
        }
        $traddiscmt = sprint($tradvar * $traddisc / 100);
        $subtotal = sprint($subtotal - $traddiscmt);
        $VAT = $vatamount;
        $SUBTOT = sprint($sub);
        $TOTAL = sprint($subtotal);
        $delexvat = sprint($delchrg);
        $traddiscmt = sprint($traddiscmt);
    } else {
        $subtotal = sprint($sub + $delchrg);
        if ($traddisc_setting == "include") {
            $tradvar = $subtotal;
        } else {
            $tradvar = $sub;
        }
        $traddiscmt = sprint($tradvar * $traddisc / 100);
        $subtotal = sprint($subtotal - $traddiscmt);
        $VAT = sprint(0);
        $SUBTOT = $sub;
        $TOTAL = $subtotal;
        $delexvat = sprint($delchrg);
    }
    /* --- ----------- Clac --------------------- */
    ##----------------------END----------------------
    /* --- ----------- Clac ---------------------
    ----------------------OLD----------------------
    		# calculate subtot
    		$SUBTOT = 0.00;
    		if(isset($amt))
    			$SUBTOT = array_sum($amt);
    
    		$SUBTOT -= $taxex;
    
    		# duplicate
    		$SUBTOTAL = $SUBTOT;
    
    		$VATP = TAX_VAT;
    		if($chrgvat == "exc"){
    			$SUBTOTAL = $SUBTOTAL;
    			$delexvat= ($delchrg);
    		}elseif($chrgvat == "inc"){
    			$SUBTOTAL = sprint(($SUBTOTAL * 100)/(100 + $VATP));
    			$delexvat = sprint(($delchrg * 100)/($VATP + 100));
    		}else{
    			$SUBTOTAL = ($SUBTOTAL);
    			$delexvat = ($delchrg);
    		}
    
    		$SUBTOT = $SUBTOTAL;
    		$EXVATTOT = $SUBTOT;
    		$EXVATTOT += $delexvat;
    
    		# Minus trade discount from taxex
    		if($traddisc > 0){
    			$traddiscmtt = (($traddisc/100) * $taxex);
    		}else{
    			$traddiscmtt = 0;
    		}
    		$taxext = ($taxex - $traddiscmtt);
    
    		if($traddisc > 0) {
    			$traddiscmt = ($EXVATTOT * ($traddisc/100));
    		}else{
    			$traddiscmt = 0;
    		}
    		$EXVATTOT -= $traddiscmt;
    		// $EXVATTOT -= $taxex;
    
    		$traddiscmt = sprint($traddiscmt  + $traddiscmtt);
    
    		if($chrgvat != "nov"){
    			$VAT = sprint($EXVATTOT * ($VATP/100));
    		}else{
    			$VAT = 0;
    		}
    
    		$TOTAL = sprint($EXVATTOT + $VAT + $taxext);
    		$SUBTOT += $taxex;
    */
    #override address
    if ($branch != 0) {
        $get_addr = "SELECT branch_descrip FROM customer_branches WHERE id = '{$branch}' AND div = '" . USER_DIV . "' LIMIT 1";
        $run_addr = db_exec($get_addr);
        if (pg_numrows($run_addr) < 1) {
            #address missing ... do nothing
        } else {
            $arr = pg_fetch_array($run_addr);
            $cust['addr1'] = $arr['branch_descrip'];
        }
    }
    // Delivery Date
    $deldate = "{$del_date_year}-{$del_date_month}-{$del_date_day}";
    /* --- ----------- Clac --------------------- */
    if (!isset($bankid)) {
        $bankid = cust_bank_id($cusnum);
    }
    # insert invoice to DB
    $sql = "\n\t\t\tUPDATE invoices \n\t\t\tSET delvat='{$delvat}', cusnum = '{$cusnum}', deptid = '{$dept['deptid']}', deptname = '{$dept['deptname']}', \n\t\t\t\tcusacc = '{$cust['accno']}', cusname = '{$cust['cusname']}', surname = '{$cust['surname']}', cusaddr = '{$cust['addr1']}', \n\t\t\t\tcusvatno = '{$cust['vatnum']}', cordno = '{$cordno}', ordno = '{$ordno}', docref = '{$docref}', \n\t\t\t\tchrgvat = '{$chrgvat}', terms = '{$terms}', salespn = '{$salespn}', odate = '{$odate}', traddisc = '{$traddisc}', \n\t\t\t\tdelchrg = '{$delchrg}', subtot = '{$SUBTOT}', vat = '{$VAT}', total = '{$TOTAL}', balance = '{$TOTAL}', \n\t\t\t\tcomm = '{$comm}', serd = 'y', discount='{$traddiscmt}', delivery='{$delexvat}', branch = '{$branch}', \n\t\t\t\tdeldate = '{$deldate}', bankid = '{$bankid}' \n\t\t\tWHERE invid = '{$invid}'";
    $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
    # remove old data
    $sql = "DELETE FROM inv_data WHERE invid='{$invid}'  AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to update invoice data in Cubit.", SELF);
    # pu in new data
    $sql = "INSERT INTO inv_data(invid, dept, customer, addr1, div) VALUES('{$invid}', '{$dept['deptname']}', '{$cust['cusname']} {$cust['surname']}', '{$cust['addr1']}', '" . USER_DIV . "')";
    $rslt = db_exec($sql) or errDie("Unable to insert invoice data to Cubit.", SELF);
    if (strlen($bar) > 0) {
        /* check if there a stock item with global barcode matching input barcode */
        $sql = "SELECT * FROM stock WHERE bar='{$bar}' AND div = '" . USER_DIV . "'";
        $barRslt = db_exec($sql);
        if (pg_num_rows($barRslt) <= 0) {
            /* fetch last character of barcode */
            $chr = substr($bar, strlen($bar) - 1, 1);
            /* invalid barcode */
            if (!is_numeric($chr)) {
                return details($_POST, "The code you selected is invalid");
            }
            /* which barcode table to scan for stock id */
            $tab = "ss{$chr}";
            $stid = barext_dbget($tab, 'code', $bar, 'stock');
            $stab = "serial{$chr}";
            $sstid = serext_dbget($stab, 'serno', $bar, 'stkid');
            /* non-existing barcode, check for serial number */
            if ($stid <= 0) {
                if ($sstid <= 0) {
                    return details($_POST, "<li class='err'>The serial number/bar code you selected is not in the system or is not available.</li>");
                }
                if (serext_dbnum($stab, 'serno', $bar, 'stkid') > 1) {
                    return details($_POST, "<li class='err'>Duplicate serial numbers found, please scan barcode or select stock item.</li>");
                }
                /* mark barcoded item as unavailable */
                $sql = "UPDATE " . $stab . " SET rsvd='y' WHERE serno='{$bar}'";
                db_exec($sql);
                $serno_bar = "{$bar}";
                $stid = $sstid;
            } else {
                if ($sstid > 0) {
                    return details($_POST, "<li class='err'>A serial and barcode with same value, please scan other value or select product manually.</li>");
                }
                /* mark barcoded item as unavailable */
                $sql = "UPDATE " . $tab . " SET active='no' WHERE code='{$bar}' AND div='" . USER_DIV . "'";
                db_exec($sql);
                $serno_bar = "{$bar}";
            }
            /* fetch stock row for selected item */
            $sql = "SELECT * FROM stock WHERE stkid = '{$stid}' AND div = '" . USER_DIV . "'";
            $barRslt = db_exec($sql);
        } else {
            $serno_bar = "";
        }
        $s = pg_fetch_array($barRslt);
        /* allocate stock item */
        $sql = "UPDATE stock SET alloc = (alloc + '1') WHERE stkid = '{$s['stkid']}' AND div = '" . USER_DIV . "'";
        db_exec($sql) or errDie("Unable to update stock to Cubit.", SELF);
        $sql = "\n\t\t\tINSERT INTO inv_items (\n\t\t\t\tinvid, whid, stkid, qty, unitcost, amt, disc, discp, ss, serno, \n\t\t\t\tdiv, vatcode\n\t\t\t) VALUES (\n\t\t\t\t'{$invid}', '{$s['whid']}', '{$s['stkid']}', '1','{$s['selamt']}', '{$s['selamt']}','0','0','{$bar}', '{$serno_bar}', \n\t\t\t\t'" . USER_DIV . "', (SELECT id FROM cubit.vatcodes LIMIT 1)\n\t\t\t)";
        db_exec($sql) or errDie("Unable to insert invoice items to Cubit.", SELF);
    }
    pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
    /* --- Start button Listeners --- */
    if (isset($doneBtn) || isset($emailBtn)) {
        # Check if stock was selected(yes = put done button)
        db_connect();
        $sql = "SELECT stkid FROM inv_items WHERE invid = '{$inv['invid']}' AND div = '" . USER_DIV . "'";
        $crslt = db_exec($sql);
        if (pg_numrows($crslt) < 1) {
            $error = "<li class='err'> Error : Invoice number has no items.";
            return details($_POST, $error);
        }
        # Insert quote to DB
        $sql = "UPDATE invoices SET done = 'y' WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update invoice status in Cubit.", SELF);
        $Sl = "SELECT * FROM settings WHERE constant='Delivery Note'";
        $Ri = db_exec($Sl) or errDie("Unable to get settings.");
        $data = pg_fetch_array($Ri);
        if (isset($emailBtn)) {
            $email = "email=true";
        } else {
            $email = "";
        }
        if ($data['value'] == "Yes") {
            //		move('cust-credit-stockinv.php');
            //move('cust-credit-stockinv-newsetting.php');
            $OUTPUT = "\n\t\t\t\t<script>\n\t\t\t\t\tnhprinter('invoice-delnote.php?invid={$invid}','Delivery Note');\n\t\t\t\t\tprinter('invoice-print.php?invid={$invid}&type=inv&salespn={$salespn}&{$email}');\n\t\t\t\t\tmove('settings/cust-credit-stockinv-newsetting.php');\n\t\t\t\t</script>";
        } else {
            //		move('cust-credit-stockinv.php');
            //move('cust-credit-stockinv-newsetting.php');
            $OUTPUT = "\n\t\t\t\t<script>\n\t\t\t\t\tprinter('invoice-print.php?invid={$invid}&type=inv&{$email}');\n\t\t\t\t\tmove('settings/cust-credit-stockinv-newsetting.php');\n\t\t\t\t</script>";
        }
        # Print the invoice
        require "template.php";
    } elseif (isset($saveBtn)) {
        // Final Laytout
        $write = "\n\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t<tr>\n\t\t\t\t\t<th>New Invoice Saved</th>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>Invoice for customer <b>{$cust['cusname']} {$cust['surname']}</b> has been saved. To view it go to 'View incomplete invoices'</td>\n\t\t\t\t</tr>\n\t\t\t</table>\n\t\t\t<p>\n\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t<tr>\n\t\t\t\t\t<th>Quick Links</th>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td><a href='invoice-view.php'>View Invoices</a></td>\n\t\t\t\t</tr>\n\t\t\t\t<script>document.write(getQuicklinkSpecial());</script>\n\t\t\t</table>";
        return $write;
    } else {
        if (isset($wtd)) {
            $_POST['wtd'] = $wtd;
        }
        if (strlen($ria) > 0) {
            $_POST['ria'] = $ria;
        }
        return details($_POST);
    }
    /* --- End button Listeners --- */
}