function pretake_update()
{
    extract($_REQUEST);
    pglib_transaction("BEGIN");
    $page = page_number($offset);
    if (isset($new) && $new) {
        $sql = "DELETE FROM cubit.stock_take";
        db_exec($sql) or errDie("Unable to remove old stock take.");
    }
    $sql = "SELECT stkid FROM cubit.stock \n\t\t\tORDER BY stkcod ASC LIMIT {$limit} OFFSET {$offset}";
    $stock_rslt = db_exec($sql) or errDie("Unable to retrieve stock.");
    while (list($stkid) = pg_fetch_array($stock_rslt)) {
        $sql = "INSERT INTO cubit.stock_take (stkid, page)\n\t\t\t\tVALUES ('{$stkid}', '{$page}')";
        db_exec($sql) or errDie("Unable to add to stock take.");
    }
    $sql = "SELECT stkid FROM cubit.stock\n\t\t\tORDER BY stkcod ASC LIMIT {$limit} OFFSET {$offset}";
    db_exec($sql) or errDie("Unable to retrieve stock take.");
    $next_page = $page + 1;
    $next_offset = page_offset($next_page);
    if ($next_page <= total_pages()) {
        $button = "<input type='submit' value='Page {$next_page}' />";
    } else {
        $button = "\n\t\t<input type='button' value='Post Stock Take'\n\t\tonclick='javascript:move(\"stock_take_post.php\")' />";
    }
    pglib_transaction("COMMIT");
    $OUTPUT = "\n\t<script>\n\t\tprinter(\"" . SELF . "?key=pretake_print&offset={$offset}&limit={$limit}\");\n\t</script>\n\t<center>\n\t<h3>Pre Stock Take</h3>\n\t<form method='post' action='" . SELF . "'>\n\t<input type='hidden' name='key' value='pretake_update' />\n\t<input type='hidden' name='limit' value='{$limit}' />\n\t<input type='hidden' name='offset' value='{$next_offset}' />\n\t{$button}\n\t</form>\n\t</center>";
    return $OUTPUT;
}
function write()
{
    extract($_REQUEST);
    pglib_transaction("BEGIN");
    $sql = "DELETE FROM cubit.forecasts WHERE id='{$forecast_id}'";
    db_exec($sql) or errDie("Unable to remove forecasts.");
    $sql = "DELETE FROM cubit.forecast_items WHERE forecast_id='{$forecast_id}'";
    db_exec($sql) or errDie("Unable to remove forecast items.");
    pglib_transaction("COMMIT");
    $OUTPUT = "<h3>Remove Saved Sales Forecast</h3>\n\t<table " . TMPL_tblDflts . ">\n\t\t<tr>\n\t\t\t<th>Remove</th>\n\t\t</tr>\n\t\t<tr class='" . bg_class() . "'>\n\t\t\t<td><li>Saved sales forecast removed successfully.</li></td>\n\t\t</tr>\n\t</table>";
    return $OUTPUT;
}
예제 #3
0
function select()
{
    global $ePRDMON;
    pglib_transaction("BEGIN");
    $sql = "SELECT * FROM cubit.employees";
    mdbg($sql);
    $rslt = db_exec($sql);
    print "<xmp>";
    print "employees to process: " . pg_num_rows($rslt) . "\n";
    $empnum = 0;
    while ($emp = pg_fetch_assoc($rslt)) {
        print "processing employee number: " . ++$empnum . "\n";
        flush();
        ob_flush();
        $sql = "SELECT * FROM \"3\".empledger WHERE empid='{$emp['empnum']}'";
        mdbg($sql);
        $ybrslt = db_exec($sql);
        if (pg_num_rows($ybrslt) > 0) {
            $yb = pg_fetch_assoc($ybrslt);
            $p_dbal = $yb["dbalance"];
            $p_cbal = $yb["cbalance"];
        } else {
            $p_dbal = 0;
            $p_cbal = 0;
        }
        /* create the balance transactions */
        for ($i = 1; $i <= 12; ++$i) {
            $month = $ePRDMON[$i];
            $sql = "SELECT * FROM \"{$month}\".empledger \n\t\t\t\t\tWHERE empid='{$emp['empnum']}'\n\t\t\t\t\tORDER BY edate,id";
            $elrslt = db_exec($sql);
            if (pg_num_rows($elrslt) <= 0) {
                $sql = "INSERT INTO \"{$month}\".empledger (empid, contra, edate, ref, des,\n\t\t\t\t\t\t\tdebit, credit, dbalance, cbalance, sdate, div)\n\t\t\t\t\t\tVALUES('{$emp['empnum']}', '0', CURRENT_DATE, 0, 'Balance', '0', '0', \n\t\t\t\t\t\t\t'{$p_dbal}', '{$p_cbal}', CURRENT_DATE, 2)";
                db_exec($sql);
            } else {
                while ($row = pg_fetch_assoc($elrslt)) {
                    $p_dbal += $row["debit"];
                    $p_cbal += $row["credit"];
                    if ($p_dbal >= $p_cbal) {
                        $p_dbal = $p_dbal - $p_cbal;
                        $p_cbal = 0;
                    } else {
                        $p_cbal = $p_cbal - $p_dbal;
                        $p_dbal = 0;
                    }
                }
            }
        }
    }
    print "\nDone.";
    print "</xmp>";
    mdbg(false);
    pglib_transaction("COMMIT");
}
function complete()
{
    extract($_REQUEST);
    pglib_transaction("BEGIN");
    $datetime = date("Y-m-d G:i:s");
    $sql = "SELECT stkid, qty FROM cubit.stock_take";
    $stock_rslt = db_exec($sql) or errDie("Unable to retrieve stock.");
    while (list($stkid, $qty) = pg_fetch_array($stock_rslt)) {
        $sql = "INSERT INTO cubit.stock_take_report (timestamp, stkid, qty)\n\t\t\t\tVALUES ('{$datetime}', '{$stkid}', '{$qty}')";
        db_exec($sql) or errDie("Unable to add to report.");
    }
    $sql = "DELETE FROM cubit.stock_take";
    db_exec($sql) or errDie("Unable to remove from stock take.");
    pglib_transaction("COMMIT");
    $OUTPUT = "\n\t<h3>Stock Take</h3>\n\t<table " . TMPL_tblDflts . ">\n\t\t<tr><th>Complete</th></tr>\n\t\t<tr class='" . bg_class() . "'>\n\t\t\t<td><li>Stock Take has successfully been completed.</td></li>\n\t\t</tr>\n\t</table>";
    return $OUTPUT;
}
function posttake_update()
{
    extract($_REQUEST);
    pglib_transaction("BEGIN");
    foreach ($qty as $stkid => $value) {
        $sql = "SELECT stkid FROM cubit.stock_take WHERE stkid='{$stkid}'";
        $stktake_rslt = db_exec($sql) or errDie("Unable to retrieve stock take.");
        if (is_numeric($qty[$stkid])) {
            if (pg_num_rows($stktake_rslt)) {
                $sql = "UPDATE cubit.stock_take SET qty='{$qty[$stkid]}' WHERE stkid='{$stkid}'";
            }
        }
        db_exec($sql) or errDie("Unable to add to stock take.");
    }
    pglib_transaction("COMMIT");
    return posttake_display();
}
function invoice()
{
    extract($_REQUEST);
    pglib_transaction("BEGIN");
    $invnum = divlastid("inv");
    $sql = "INSERT INTO cubit.invoices(deptid, chrgvat, odate, printed, done, \n\t\t\t\tusername, prd, invnum, div, systime, pslip_sordid, cusnum, ordno)\n\t\t\tVALUES ('" . USER_DIV . "', 'inc', current_date, 'n', 'n',\n\t\t\t\t'" . USER_NAME . "', '" . PRD_DB . "', '{$invnum}', '" . USER_DIV . "',\n\t\t\t\tcurrent_date, '{$sordid}', '{$cusnum}', '{$sordid}')";
    $inv_rslt = db_exec($sql) or errDie("Unable to retrieve invoice.");
    $invid = lastinvid();
    $sql = "SELECT stock.stkid, stock.whid, qty, sorders_items.vatcode, amt, unitcost\n\t\t\tFROM cubit.sorders_items\n\t\t\t\tLEFT JOIN cubit.stock ON sorders_items.stkid=stock.stkid\n\t\t\tWHERE sordid='{$sordid}'";
    $stock_rslt = db_exec($sql) or errDie("Unable to retrieve stock.");
    while (list($stkid, $whid, $qty, $vatcode, $amt, $unitcost) = pg_fetch_array($stock_rslt)) {
        $sql = "INSERT INTO cubit.inv_items (invid, whid, stkid, qty, div,\n\t\t\t\t\tvatcode, amt, unitcost)\n\t\t\t\tVALUES ('{$invid}', '{$whid}', '{$stkid}', '{$qty}', '" . USER_DIV . "',\n\t\t\t\t\t'{$vatcode}', '{$amt}', '{$unitcost}')";
        db_exec($sql) or errDie("Unable to add inventory items.");
    }
    $OUTPUT = "\n\t<script>\n\t\tmove(\"../cust-credit-stockinv-no-neg.php?invid={$invid}&cont=true\");\n\t</script>";
    pglib_transaction("COMMIT");
    return $OUTPUT;
}
function save()
{
    extract($_REQUEST);
    pglib_transaction("BEGIN");
    if (isset($asset)) {
        foreach ($asset as $id) {
            $sql = "SELECT id FROM hire.basis_prices WHERE assetid='{$id}'";
            $bp_rslt = db_exec($sql) or errDie("Unable to retrieve basis.");
            if (pg_num_rows($bp_rslt)) {
                $bp_id = pg_fetch_result($bp_rslt, 0);
                $sql = "UPDATE hire.basis_prices SET per_hour='{$hour[$id]}',\r\n\t\t\t\t\t\t\tper_day='{$day[$id]}', per_week='{$week[$id]}'\r\n\t\t\t\t\t\t\tWHERE id='{$bp_id}'";
            } else {
                $sql = "INSERT INTO hire.basis_prices (assetid, per_hour,\r\n\t\t\t\t\t\t\tper_day, per_week)\r\n\t\t\t\t\t\t\tVALUES ('{$id}', '{$hour[$id]}', '{$day[$id]}',\r\n\t\t\t\t\t\t\t\t'{$week[$id]}')";
            }
            db_exec($sql) or errDie("Unable to update basis prices.");
        }
    }
    pglib_transaction("COMMIT");
    $msg = "<tr class='" . bg_class() . "'>\r\n\t\t<td colspan='6'><li>Successfully saved the default basis prices.</li>\r\n\t</tr>";
    return display($msg);
}
function save()
{
    extract($_REQUEST);
    print "<xmp>";
    print_r($_REQUEST);
    print "</xmp>";
    pglib_transaction("BEGIN");
    if (isset($blocked)) {
        foreach ($blocked as $stkid) {
            $sql = "UPDATE cubit.stock SET blocked='y' WHERE stkid='{$stkid}'";
            db_exec($sql) or errDie("Unable to update stock.");
        }
    }
    if (isset($count)) {
        foreach ($count as $stkid => $value) {
            $sql = "UPDATE cubit.stock SET units='{$value}' WHERE stkid='{$stkid}'";
            db_exec($sql) or errDie("Unable to update stock.");
        }
    }
    pglib_transaction("COMMIT");
    return display();
}
function save()
{
    extract($_REQUEST);
    pglib_transaction("BEGIN");
    foreach ($days as $asset_id => $days) {
        $sql = "UPDATE cubit.assets SET days='{$days}' WHERE id='{$asset_id}'";
        db_exec($sql) or errDie("Unable to update service days.");
        $secs = $days * 60 * 60 * 24;
        $svdate = date("Y-m-d", time() + $days);
        $sql = "SELECT * FROM cubit.asset_svdates\r\n\t\t\t\tWHERE asset_id='{$asset_id}'";
        $svdate_rslt = db_exec($sql) or errDie("Unable to retrieve days.");
        if (!pg_num_rows($svdate_rslt)) {
            $sql = "INSERT INTO cubit.asset_svdates (asset_id, svdate, des)\r\n\t\t\t\t\tVALUES ('{$asset_id}', '{$svdate}', '{$description[$asset_id]}')";
        } else {
            $sv_data = pg_fetch_array($svdate_rslt);
            $sql = "UPDATE cubit.asset_svdates SET svdate='{$svdate}',\r\n\t\t\t\t\t\tdescription='{$description[$asset_id]}'\r\n\t\t\t\t\tWHERE id='{$sv_data['id']}'";
        }
    }
    db_exec($sql) or errDie("Unable to update service history.");
    pglib_transaction("COMMIT");
    $message = "<li class='yay'>\r\n\t\t\t\t\tSuccessfully saved service days.\r\n\t\t\t\t</li>";
    return display($message);
}
function write()
{
    extract($_REQUEST);
    pglib_transaction("BEGIN");
    if (is_uploaded_file($_FILES["file"]["tmp_name"])) {
        $file = "";
        $fp = fopen($_FILES["file"]["tmp_name"], "rb");
        while (!feof($fp)) {
            // fread is binary safe
            $file .= fread($fp, 1024);
        }
        fclose($fp);
        # base 64 encoding
        $file = base64_encode($file);
        $sql = "DELETE FROM hire.unsigned_hirenotes WHERE id='{$uh_id}'";
        db_exec($sql) or errDie("Unable to remove from unsigned hirenotes.");
        $sql = "INSERT INTO hire.signed_hirenotes (invid, file_name, file_type, file)\r\n\t\t\t\tVALUES ('{$invid}', '" . $_FILES["file"]["name"] . "',\r\n\t\t\t\t\t'" . $_FILES["file"]["type"] . "', '{$file}')";
        db_exec($sql) or errDie("Unable to retrieve scanned signed hire notes.");
    }
    pglib_transaction("COMMIT");
    $OUTPUT = "\r\n\t<script>\r\n\t\tparent.document.reload();\r\n\t</script>\r\n\t<h3>Signed Hire Note</h3>\r\n\t<table " . TMPL_tblDflts . ">\r\n\t\t<tr>\r\n\t\t\t<th>Write</th>\r\n\t\t</tr>\r\n\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t<td><li>Successfully saved signed hire note</li></td>\r\n\t\t</tr>\r\n\t</table>";
    return $OUTPUT;
}
function write($_POST)
{
    # get vars
    foreach ($_POST as $key => $value) {
        ${$key} = $value;
    }
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($cusnum, "num", 1, 20, "Invalid Customer, Please select a customer.");
    $v->isOk($invid, "num", 1, 20, "Invalid Invoice Number.");
    $v->isOk($cordno, "num", 0, 20, "Invalid Customer Order Number.");
    $v->isOk($comm, "string", 0, 255, "Invalid Comments.");
    $v->isOk($ordno, "num", 0, 20, "Invalid 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($oday, "num", 1, 2, "Invalid Invoice Date day.");
    $v->isOk($omon, "num", 1, 2, "Invalid Invoice Date month.");
    $v->isOk($oyear, "num", 1, 5, "Invalid Invoice Date year.");
    $odate = $oyear . "-" . $omon . "-" . $oday;
    if (!checkdate($omon, $oday, $oyear)) {
        $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 quantities
    if (isset($qtys)) {
        foreach ($qtys as $keys => $qty) {
            $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>.");
            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"];
        }
        $_POST["done"] = "";
        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);
    # check if invoice has been printed
    if ($inv['printed'] == "y") {
        $error = "<li class=err> Error : Invoice number <b>{$invid}</b> has already been printed.";
        $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);
    }
    # 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;
    # 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
    db_connect();
    $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);
    }
    # 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 -- */
    $taxex = 0;
    if (isset($stkids)) {
        foreach ($stkids as $keys => $value) {
            if (isset($remprod)) {
                if (in_array($keys, $remprod)) {
                    # skip product (wonder if $keys still align)
                    $amt[$keys] = 0;
                    continue;
                } 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]);
                    # Check Tax Excempt
                    if ($stk['exvat'] == 'yes') {
                        $taxex += $amt[$keys];
                    }
                    # insert invoice items
                    $sql = "INSERT INTO inv_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);
                    # 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);
                }
            } 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]);
                $amt[$keys] = $qtys[$keys] * ($unitcost[$keys] - $disc[$keys]);
                if ($stk['exvat'] == 'yes') {
                    $taxex += $amt[$keys];
                }
                # insert invoice items
                $sql = "INSERT INTO inv_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);
                # 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='Done'>";
        }
    } else {
        $_POST["done"] = "";
    }
    /* --- Clac --- */
    # calculate subtot
    if (isset($amt)) {
        $SUBTOT = array_sum($amt);
    } else {
        $SUBTOT = 0.0;
    }
    # Calculate tradediscm
    if ($traddisc > 0) {
        $traddiscm = round($traddisc / 100 * $SUBTOT, 2);
    } else {
        $traddiscm = 0;
    }
    /* Trade discount fix */
    # Calculate tradediscm
    if ($traddisc > 0) {
        $traddiscmt = sprint($traddisc / 100 * $taxex);
    } else {
        $traddiscmt = 0.0;
    }
    $taxex -= $traddiscmt;
    /* Trade discount fix */
    # minus discount
    # $SUBTOT -= $disc; --> already minused
    # duplicate
    $SUBTOTAL = $SUBTOT;
    # minus trade discount
    $SUBTOTAL -= $traddiscm;
    # add del charge
    $SUBTOTAL += $delchrg;
    # If vat must be charged
    if ($chrgvat == "exc") {
        $VATP = TAX_VAT;
        $VAT = sprint($VATP / 100 * ($SUBTOTAL - $taxex));
    } elseif ($chrgvat == "inc") {
        $VATP = TAX_VAT;
        $VAT = sprint(($SUBTOTAL - $taxex) / ($VATP + 100) * $VATP);
    } else {
        $VATP = 0;
        $VAT = "0.00";
    }
    # total
    if ($chrgvat == "exc") {
        $TOTAL = sprint($SUBTOTAL + $VAT);
    } else {
        $TOTAL = sprint($SUBTOTAL);
        $SUBTOT = sprint($SUBTOT - $VAT);
    }
    /* --- End Clac --- */
    # insert invoice to DB
    $sql = "UPDATE invoices SET cusnum = '{$cusnum}', deptname = '{$dept['deptname']}', cusacc = '{$cust['accno']}', cusname = '{$cust['cusname']}', surname = '{$cust['surname']}', cusaddr = '{$cust['addr1']}', cusvatno = '{$cust['vatnum']}', cordno = '{$cordno}', ordno = '{$ordno}', chrgvat = '{$chrgvat}', terms = '{$terms}', salespn = '{$salespn}',\n\t\todate = '{$odate}', traddisc = '{$traddisc}', delchrg = '{$delchrg}', subtot = '{$SUBTOT}', vat = '{$VAT}', total = '{$TOTAL}', balance = '{$TOTAL}', comm = '{$comm}' WHERE 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);
    # commit updating
    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 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);
        # print the invoice
        header("Location:invoice-print.php?invid={$invid}");
    } elseif (isset($saveBtn)) {
        // Final Laytout
        $write = "\n\t\t<table border=0 cellpadding='" . TMPL_tblCellPadding . "' cellspacing='" . TMPL_tblCellSpacing . "'>\n\t\t\t<tr><th>New Invoice Saved</th></tr>\n\t\t\t<tr class='bg-even'><td>Invoice for customer <b>{$cust['cusname']} {$cust['surname']}</b> has been saved.</td></tr>\n\t\t</table>\n\t\t<p>\n\t\t<table border=0 cellpadding='" . TMPL_tblCellPadding . "' cellspacing='" . TMPL_tblCellSpacing . "'>\n\t\t\t<tr><th>Quick Links</th></tr>\n\t\t\t<tr class='bg-odd'><td><a href='invoice-view.php'>View Invoices</a></td></tr>\n\t\t\t<script>document.write(getQuicklinkSpecial());</script>\n\t\t</table>";
        return $write;
    } else {
        return details($_POST);
    }
    /* --- End button Listeners --- */
}
function write()
{
    extract($_REQUEST);
    require_lib("validate");
    $v = new validate();
    $v->isOk($invid, "num", 1, 20, "Invalid invoice number.");
    $sndate = "{$ninv_year}-{$ninv_month}-{$ninv_day}";
    if (!checkdate($ninv_month, $ninv_day, $ninv_year)) {
        $v->addError($sdate, "Invalid Date.");
    }
    pglib_transaction("BEGIN");
    // Get invoice info
    $sql = "SELECT * FROM cubit.nons_invoices WHERE invid='{$invid}' AND div='" . USER_DIV . "'";
    $inv_rslt = db_exec($sql) or errDie("Unable to get invoice information");
    if (pg_numrows($inv_rslt) < 1) {
        return "<i class='err'>Not Found</i>";
    }
    $inv = pg_fetch_array($inv_rslt);
    $TOTAL = $inv["subtot"] + $inv["vat"];
    $notenum = pglib_lastid("cubit.nons_inv_notes", "noteid");
    $notenum++;
    // Add to the non stock credit notes
    $sql = "\r\n\t\tINSERT INTO cubit.nons_inv_notes (\r\n\t\t\tinvid, invnum, cusname, cusaddr, cusvatno, chrgvat, \r\n\t\t\tdate, subtot, vat, total, username, prd, notenum, ctyp, \r\n\t\t\tremarks, div\r\n\t\t) VALUES (\r\n\t\t\t'{$inv['invid']}', '{$inv['invnum']}', '{$inv['cusname']}', '{$inv['cusaddr']}', '{$inv['cusvatno']}', '{$inv['chrgvat']}', \r\n\t\t\t'{$sndate}', '{$inv['subtot']}', '{$inv['vat']}', '{$TOTAL}', '" . USER_NAME . "', '" . PRD_DB . "', '{$notenum}', '{$inv['ctyp']}', \r\n\t\t\t'{$inv['remarks']}', '" . USER_DIV . "'\r\n\t\t)";
    db_exec($sql) or errDie("Unable to save credit note.");
    $noteid = pglib_lastid("cubit.nons_inv_notes", "noteid");
    $sql = "SELECT count(id) FROM cubit.nons_inv_items WHERE invid='{$invid}'";
    $count_rslt = db_exec($sql) or errDie("Unable to retrieve amount of items.");
    $item_count = pg_fetch_result($count_rslt, 0);
    $i = 0;
    $page = 0;
    foreach ($ids as $key => $id) {
        $sql = "SELECT * FROM cubit.nons_inv_items WHERE invid='{$invid}' AND id='{$id}'";
        $item_rslt = db_exec($sql) or errDie("Unable to retrieve item.");
        $item_data = pg_fetch_array($item_rslt);
        if ($item_data['vatex'] == 'y') {
            $ex = "#";
        } else {
            $ex = "&nbsp;&nbsp;";
        }
        // Time for a new page ??
        if ($i >= 25) {
            $page++;
            $i = 0;
        }
        $products[$page][] = "\r\n\t\t\t<tr valign='top'>\r\n\t\t\t\t<td style='border-right: 2px solid #000'>\r\n\t\t\t\t\t{$ex} {$item_data['description']}&nbsp;\r\n\t\t\t\t</td>\r\n\t\t\t\t<td style='border-right: 2px solid #000'>\r\n\t\t\t\t\t{$item_data['qty']}&nbsp;\r\n\t\t\t\t</td>\r\n\t\t\t\t<td style='border-right: 2px solid #000' align='right' nowrap>\r\n\t\t\t\t\t" . CUR . " {$item_data['unitcost']}&nbsp;\r\n\t\t\t\t</td>\r\n\t\t\t\t<td align='right' nowrap>" . CUR . " {$item_data['amt']}&nbsp;</td>\r\n\t\t\t</tr>";
        $i++;
        // Create credit note item
        $sql = "\r\n\t\t\tINSERT INTO cubit.nons_note_items (\r\n\t\t\t\tnoteid, qty, description, amt, unitcost, \r\n\t\t\t\tvatcode\r\n\t\t\t) VALUES (\r\n\t\t\t\t'{$noteid}', '{$qtys[$key]}', '{$item_data['description']}', '{$amts[$key]}', '{$item_data['unitcost']}', \r\n\t\t\t\t'{$item_data['vatex']}'\r\n\t\t\t)";
        db_exec($sql) or errDie("Unable to create credit note item.");
        $sql = "SELECT grpid FROM cubit.assets WHERE id='{$item_data['asset_id']}'";
        $group_rslt = db_exec($sql) or errDie("Unable to retrieve group.");
        $group_id = pg_fetch_result($group_rslt, 0);
        $discount = $inv["discount"] / $item_count;
        $amt = $item_data["amt"];
        // Update royalty report and detail report
        $sql = "\r\n\t\t\tINSERT INTO hire.revenue (\r\n\t\t\t\tgroup_id, asset_id, total, discount, credit\r\n\t\t\t) VALUES (\r\n\t\t\t\t'{$group_id}', '{$item_data['asset_id']}', '-{$amt}', '-{$discount}', '1'\r\n\t\t\t)";
        db_exec($sql) or errDie("Unable to update revenue.");
        $i++;
    }
    $blank_lines = 25;
    foreach ($products as $key => $val) {
        $bl = $blank_lines - count($products[$key]);
        for ($i = 0; $i <= $bl; $i++) {
            $products[$key][] = "\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'>&nbsp;</td>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'>&nbsp;</td>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'>&nbsp;</td>\r\n\t\t\t\t\t<td>&nbsp;</td>\r\n\t\t\t\t</tr>";
        }
    }
    // Retrieve customer debt account
    $sql = "\r\n\t\tSELECT debtacc FROM exten.departments \r\n\t\t\tLEFT JOIN cubit.customers ON departments.deptid=customers.deptid\r\n\t\tWHERE cusnum='{$inv['cusid']}'";
    $dept_rslt = db_exec($sql) or errDie("Unable to retrieve departments.");
    $debtacc = pg_fetch_result($dept_rslt, 0);
    $hireacc = $inv["accid"];
    $vatacc = gethook("accnum", "salesacc", "name", "VAT", "vat");
    $refnum = getrefnum();
    writetrans($hireacc, $debtacc, $sndate, $refnum, $inv["subtot"], "Non-Stock Invoice No. {$inv['invnum']} Credit Note No. {$noteid} Customer\r\n\t\t{$inv['cusname']}");
    if ($inv["vat"] != 0) {
        writetrans($vatacc, $debtacc, $sndate, $refnum, $inv["vat"], "Non-Stock Invoice No. {$inv['invnum']} Credit Note No. {$noteid} VAT.\r\n\t\tCustomer {$inv['cusname']}");
    }
    // Record on the statement
    $sql = "\r\n\t\tINSERT INTO cubit.stmnt (\r\n\t\t\tcusnum, invid, amount, date, type, \r\n\t\t\tdiv\r\n\t\t) VALUES (\r\n\t\t\t'{$inv['cusid']}', '{$noteid}', '-{$TOTAL}', '{$sndate}', 'Non-Stock Credit Note, for invoice {$inv['invnum']}', \r\n\t\t\t'" . USER_DIV . "'\r\n\t\t)";
    db_exec($sql) or errDie("Unable to insert to customer statement.");
    // Update the customer (Make the balance less)
    $sql = "UPDATE cubit.customers SET balance=(balance-'{$TOTAL}') WHERE cusnum='{$inv['cusid']}'";
    db_exec($sql) or errDie("Unable to update customer balance.");
    // Update the customer (Make the balance less)
    $sql = "UPDATE cubit.open_stmnt SET balance=(balance-'{$TOTAL}') WHERE cusnum='{$inv['cusid']}'";
    db_exec($sql) or errDie("Unable to update customer balance.");
    // Create ledger record
    custledger($inv["cusid"], $hireacc, $sndate, $noteid, "Non-Stock Credit Note {$noteid}", $TOTAL, "c");
    custCT($inv["total"], $inv["cusid"], $inv["odate"]);
    // Update non-stock invoice
    $sql = "UPDATE cubit.nons_invoices SET balance=(balance-'{$TOTAL}') WHERE invid='{$invid}'";
    db_exec($sql) or errDie("Unable to update non-stock invoice.");
    $sql = "\r\n\t\tINSERT INTO cubit.salesrec (\r\n\t\t\tedate, invid, invnum, debtacc, vat, total, typ, div\r\n\t\t) VALUES (\r\n\t\t\t'{$sndate}', '{$noteid}', '{$notenum}', '0', '{$inv['vat']}', '{$TOTAL}', 'nnon', '" . USER_DIV . "'\r\n\t\t)";
    db_exec($sql) or errDie("Unable to record in sales.");
    $sql = "\r\n\t\tINSERT INTO cubit.sj (\r\n\t\t\tcid, name, des, date, \r\n\t\t\texl, vat, inc, div\r\n\t\t) VALUES (\r\n\t\t\t'{$inv['cusid']}', '{$inv['cusname']}', 'Credit Note: {$noteid} Invoice {$inv['invnum']}', '{$sndate}', \r\n\t\t\t'-" . ($TOTAL - $inv["vat"]) . "', '{$inv['vat']}', '" . -sprint($TOTAL) . "', '" . USER_DIV . "'\r\n\t\t)";
    db_exec($sql) or errDie("Unable to record in sj.");
    $sql = "UPDATE cubit.nons_invoices SET accepted='note' WHERE invid='{$invid}'";
    db_exec($sql) or errDie("Unable to update invoice.");
    com_invoice($inv["salespn"], -($TOTAL - $inv["vat"]), 0, $inv["invnum"], $sndate);
    $cc = "\r\n\t\t<script>\r\n\t\t\tCostCenter('ct', 'Credit Note', '{$sndate}',\r\n\t\t\t'Non Stock Credit Note No.{$noteid}', '" . ($TOTAL - $inv["vat"]) . "', '');\r\n\t   </script>";
    // Reverse the amounts on the coastal reports -----------------------------
    $sql = "UPDATE hire.assets_hired SET value=0 WHERE invid='{$inv['hire_invid']}'";
    db_exec($sql) or errDie("Unable to update asset hired records.");
    // Vat
    $sql = "SELECT id FROM cubit.vatcodes WHERE code='01'";
    $vd_rslt = db_exec($sql) or errDie("Unable to retrieve vatcodes.");
    $vd_id = pg_fetch_result($vd_rslt, 0);
    vatr($vd_id, $sndate, "OUTPUT", "01", $refnum, "Non-Stock Sales, invoice No.{$inv['invnum']}", $TOTAL, $inv["vat"]);
    if (!isset($showvat)) {
        $showvat = TRUE;
    }
    if ($showvat == TRUE) {
        $vat14 = AT14;
    } else {
        $vat14 = "";
    }
    // Retrieve the company information
    db_conn("cubit");
    $sql = "SELECT * FROM compinfo";
    $comp_rslt = db_exec($sql) or errDie("Unable to retrieve company.");
    $comp_data = pg_fetch_array($comp_rslt);
    // Retrieve the banking information
    $sql = "SELECT * FROM bankacct WHERE bankid='2' AND div='" . USER_DIV . "'";
    $bank_rslt = db_exec($sql) or errDie("Unable to retrieve bank.");
    $bank_data = pg_fetch_array($bank_rslt);
    // Retrieve customer information
    $sql = "SELECT * FROM customers WHERE cusnum='{$inv['cusid']}'";
    $cust_rslt = db_exec($sql) or errDie("Unable to retrieve customer.");
    $cust_data = pg_fetch_array($cust_rslt);
    if ($inv['cusid'] == "0") {
        $cust_data['surname'] = $inv['cusname'];
        $cust_data['addr1'] = $inv['cusaddr'];
        $cust_data['paddr1'] = $inv['cusaddr'];
    }
    $table_borders = "\r\n\t\tborder-top: 2px solid #000000;\r\n\t\tborder-left: 2px solid #000000;\r\n\t\tborder-right: 2px solid #000000;\r\n\t\tborder-bottom: none;";
    $details = "";
    for ($i = 0; $i <= $page; $i++) {
        // new page?
        if ($i > 1) {
            $details .= "<br style='page-break-after:always;'>";
        }
        $products_out = "";
        foreach ($products[$i] as $string) {
            $products_out .= $string;
        }
        $details .= "\r\n\t\t\t<center>\r\n\t\t\t<table cellpadding='0' cellspacing='0' width='85%' style='{$table_borders}'>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td>\r\n\t\t\t\t\t\t<table border='0' cellpadding='2' cellspacing='2' width='100%'>\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t<td align='left' rowspan='2'><img src='../compinfo/getimg.php' width='230' height='47'></td>\r\n\t\t\t\t\t\t\t\t<td align='left' rowspan='2'><font size='5'><b>" . COMP_NAME . "</b></font></td>\r\n\t\t\t\t\t\t\t\t<td align='right'><font size='5'><b>Tax Credit Note</b></font></td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t</table>\r\n\t\t\t\t\t</td>\r\n\t\t\t\t</tr>\r\n\t\t\t</table>\r\n\r\n\t\t\t<table cellpadding='0' cellspacing='0' width='85%' style='{$table_borders}'>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td valign='top'>\r\n\t\t\t\t\t\t<table cellpadding='2' cellspacing='0' border='0' width='100%'>\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t<td style='border-right: 2px solid #000'>{$comp_data['addr1']}&nbsp;</td>\r\n\t\t\t\t\t\t\t\t<td style='border-right: 2px solid #000'>{$comp_data['paddr1']}&nbsp;</td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t<td style='border-right: 2px solid #000'>{$comp_data['addr2']}&nbsp;</td>\r\n\t\t\t\t\t\t\t\t<td style='border-right: 2px solid #000'>{$comp_data['paddr2']}&nbsp;</td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t<td style='border-right: 2px solid #000'>{$comp_data['addr3']}&nbsp;</td>\r\n\t\t\t\t\t\t\t\t<td style='border-right: 2px solid #000'>{$comp_data['paddr3']}&nbsp;</td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t<td style='border-right: 2px solid #000'>{$comp_data['addr4']}&nbsp;</td>\r\n\t\t\t\t\t\t\t\t<td style='border-right: 2px solid #000'>{$comp_data['postcode']}&nbsp;</td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t<td style='border-right: 2px solid #000'><b>REG:</b> {$comp_data['regnum']}</b>&nbsp;</td>\r\n\t\t\t\t\t\t\t\t<td style='border-right: 2px solid #000'><b>{$bank_data['bankname']}</b>&nbsp;</td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t<td style='border-right: 2px solid #000'><b>VAT REG:</b> {$comp_data['vatnum']}&nbsp;</td>\r\n\t\t\t\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Branch</b> {$bank_data['branchname']}&nbsp;</td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Tel:</b> {$comp_data['tel']}&nbsp;</td>\r\n\t\t\t\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Branch Code:</b> {$bank_data['branchcode']}&nbsp;</td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Fax:</b> {$comp_data['fax']}&nbsp;</td>\r\n\t\t\t\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Acc Num:</b> {$bank_data['accnum']}&nbsp;</td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t</table>\r\n\t\t\t\t\t</td>\r\n\t\t\t\t\t<td valign='top'>\r\n\t\t\t\t\t\t<table cellpadding='2' cellspacing='0' border='0' width='100%'>\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Date</b></td>\r\n\t\t\t\t\t\t\t\t<td><b>Page Number</b></td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t<td style='border-right: 2px solid #000'>{$inv['odate']}</td>\r\n\t\t\t\t\t\t\t\t<td>" . ($i + 1) . "</td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t<td style='border-bottom: 2px solid #000; border-right: 2px solid #000'>&nbsp</td>\r\n\t\t\t\t\t\t\t\t<td style='border-bottom: 2px solid #000'>&nbsp</td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t\t<tr><td>&nbsp</td></tr>\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t<td colspan='2'><b>Credit Note No:</b> {$noteid}</td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t<td colspan='2'><b>Invoice No:</b> {$inv['invnum']}</td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t<td colspan='2'><b>Proforma Inv No:</b> {$inv['docref']}</td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t</table>\r\n\t\t\t\t\t</td>\r\n\t\t\t\t</tr>\r\n\t\t\t</table>\r\n\r\n\t\t\t<table cellpadding='0' cellspacing='0' width='85%' style='{$table_borders}'>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td>\r\n\t\t\t\t\t\t<table cellpadding='2' cellspacing='0' border='0' width='100%'>\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t<td align='center'><font size='4'><b>Credit Note To:</b></font></td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t</table>\r\n\t\t\t\t\t</td>\r\n\t\t\t\t</tr>\r\n\t\t\t</table>\r\n\r\n\t\t\t<table cellpadding='0' cellspacing='0' width='85%' style='{$table_borders}'>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td>\r\n\t\t\t\t\t\t<table cellpadding='2' cellspacing='0' border='0' width='100%'>\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t<td width='33%' style='border-right: 2px solid #000'><b>{$cust_data['surname']}</b></td>\r\n\t\t\t\t\t\t\t\t<td width='33%' style='border-right: 2px solid #000'><b>Postal Address</b></td>\r\n\t\t\t\t\t\t\t\t<td width='33%'><b>Delivery Address</td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t<td style='border-right: 2px solid #000'>" . nl2br($cust_data["addr1"]) . "</td>\r\n\t\t\t\t\t\t\t\t<td style='border-right: 2px solid #000'>" . nl2br($cust_data["paddr1"]) . "</td>\r\n\t\t\t\t\t\t\t\t<td>&nbsp</td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t</table>\r\n\t\t\t\t\t</td>\r\n\t\t\t\t</tr>\r\n\t\t\t</table>\r\n\r\n\t\t\t<table cellpadding='0' cellspacing='0' width='85%' style='{$table_borders}'>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td>\r\n\t\t\t\t\t\t<table cellpadding='2' cellspacing='0' border='0' width='100%'>\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t<td width='33%' style='border-right: 2px solid #000'><b>Customer VAT No:</b> {$inv['cusvatno']}</td>\r\n\t\t\t\t\t\t\t\t<td width='33%'><b>Customer Order No:</b> {$inv['cordno']}</td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t</table>\r\n\t\t\t\t\t</td>\r\n\t\t\t\t</tr>\r\n\t\t\t</table>\r\n\r\n\t\t\t<table cellpadding='0' cellspacing='0' width='85%' style='{$table_borders}'>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td>\r\n\t\t\t\t\t\t<table cellpadding='2' cellspacing='0' border='0' width='100%'>\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t<td style='border-bottom: 2px solid #000; border-right: 2px solid #000'><b>Description</b></td>\r\n\t\t\t\t\t\t\t\t<td style='border-bottom: 2px solid #000; border-right: 2px solid #000'><b>Qty</b></td>\r\n\t\t\t\t\t\t\t\t<td style='border-bottom: 2px solid #000; border-right: 2px solid #000' align='right'><b>Unit Price</b></td>\r\n\t\t\t\t\t\t\t\t<td style='border-bottom: 2px solid #000;' align='right'><b>Amount</b></td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t\t{$products_out}\r\n\t\t\t\t\t\t</table>\r\n\t\t\t\t\t</td>\r\n\t\t\t\t</tr>\r\n\t\t\t</table>\r\n\r\n\t\t\t<table cellpadding='0' cellspacing='0' width='85%' style='{$table_borders}'>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td>\r\n\t\t\t\t\t\t<table cellpadding='2' cellspacing='0' border='0' width='100%'>\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t<td><i>VAT Exempt Indicator: #</i></td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t<td>{$remarks}</td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t</table>\r\n\t\t\t\t\t</td>\r\n\t\t\t\t</tr>\r\n\t\t\t</table>\r\n\r\n\t\t\t<table cellpadding='0' cellspacing='0' width='85%' style='border: 2px solid #000000'>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td>\r\n\t\t\t\t\t\t<table cellpadding='2' cellspacing='0' border='0' width='100%'>\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Terms:</b> {$inv['terms']} days</b></td>\r\n\t\t\t\t\t\t\t\t<td><b>Trade Discount:</b></td>\r\n\t\t\t\t\t\t\t\t<td nowrap><b>" . CUR . " {$inv['discount']}</b></td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t<td style='border-right: 2px solid #000'>&nbsp;</td>\r\n\t\t\t\t\t\t\t\t<td><b>Subtotal:</b></td>\r\n\t\t\t\t\t\t\t\t<td nowrap><b>" . CUR . " {$inv['subtot']}</b></td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Received in good order by:</b>_____________________</td>\r\n\t\t\t\t\t\t\t\t<td><b>VAT {$vat14}:</b></td>\r\n\t\t\t\t\t\t\t\t<td nowrap><b>" . CUR . " {$inv['vat']}</b></td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t<td style='border-right: 2px solid #000'>&nbsp;</td>\r\n\t\t\t\t\t\t\t\t<td><b>Total Incl VAT:</b></td>\r\n\t\t\t\t\t\t\t\t<td nowrap><b>" . CUR . " " . sprint($TOTAL) . "</b></td>\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Date:</b>_____________________</td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t</table>\r\n\t\t\t\t\t</td>\r\n\t\t\t\t</tr>\r\n\t\t\t</table>";
    }
    pglib_transaction("COMMIT");
    $OUTPUT = $details;
    require "../tmpl-print.php";
}
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;
}
예제 #14
0
function write_data($_POST)
{
    # get vars
    extract($_POST);
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($id, "num", 1, 9, "ID Field (hidden)");
    $v->isOk($surname, "string", 1, 100, "Last name");
    $v->isOk($name, "string", 0, 100, "First name");
    $v->isOk($account_id, "num", 0, 9, "Account ID (hidden)");
    $v->isOk($account_type, "string", 0, 100, "Account type (hidden)");
    $v->isOk($lead_source, "string", 0, 100, "Lead Source");
    $v->isOk($title, "string", 0, 100, "Title");
    $v->isOk($department, "string", 0, 100, "Department");
    $v->isOk($tell, "string", 0, 100, "Home Phone");
    $v->isOk($cell, "string", 0, 100, "Mobile Phone");
    $v->isOk($fax, "string", 0, 100, "Fax");
    $v->isOk($tell_office, "string", 0, 100, "Office Phone");
    $v->isOk($tell_other, "string", 0, 100, "Other Phone");
    $v->isOk($email, "string", 0, 100, "Email");
    $v->isOk($email_other, "string", 0, 100, "Other Email");
    $v->isOk($assistant, "string", 0, 100, "Assistant");
    $v->isOk($assistant_phone, "string", 0, 100, "Assistant Phone");
    $v->isOk($padd, "string", 0, 250, "Physical Address");
    $v->isOk($padd_city, "string", 0, 100, "Physical Address: City");
    $v->isOk($padd_state, "string", 0, 100, "Physical Address: State/Province");
    $v->isOk($padd_code, "string", 0, 100, "Physical Address: Postal Code");
    $v->isOk($padd_country, "string", 0, 100, "Physical Address: Country");
    $v->isOk($hadd, "string", 0, 250, "Postal Address");
    $v->isOk($hadd_city, "string", 0, 100, "Postal Address: City");
    $v->isOk($hadd_state, "string", 0, 100, "Postal Address: State/Province");
    $v->isOk($hadd_code, "string", 0, 100, "Postal Address: Postal Code");
    $v->isOk($hadd_country, "string", 0, 100, "Postal Address: Country");
    $v->isOk($description, "string", 0, 100, "Description");
    $v->isOk($website, "string", 0, 255, "Website");
    $v->isOk($religion, "string", 0, 100, "Religion");
    $v->isOk($race, "string", 0, 100, "Race");
    $v->isOk($gender, "string", 0, 6, "Gender");
    $v->isOk($Con, "string", 2, 3, "Invalid private.");
    $v->isOk($salespn, "num", 1, 9, "Sales person.");
    $v->isOk($team_id, "num", 1, 9, "Team");
    if (!empty($ncdate_day) || !empty($ncdate_month) || !empty($ncdate_year)) {
        $v->isOk($ncdate_day, "num", 1, 2, "Next contact date (Day)");
        $v->isOk($ncdate_month, "num", 1, 2, "Next contact date (Month)");
        $v->isOk($ncdate_year, "num", 4, 4, "Next contact date (Year)");
        $ncdate = ", ncdate = '{$ncdate_year}-{$ncdate_month}-{$ncdate_day}'";
    } else {
        $ncdate = "";
    }
    $birthdate = "{$bf_year}-{$bf_month}-{$bf_day}";
    if ($v->isOk($birthdate, "string", 1, 100, "Birthdate")) {
        if (!checkdate($bf_month, $bf_day, $bf_year)) {
            $v->addError("_OTHER", "Invalid birthdate. No such date exists.");
        }
    }
    $birthdate_description = date("d F Y", mktime(0, 0, 0, $bf_day, $bf_month, $bf_year));
    # display errors, if any
    if ($v->isError()) {
        $err = "The following field value errors occured:<br>";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            if ($e["value"] == "_OTHER") {
                $err .= "<li class='err'>{$e['msg']}</li>";
            } else {
                $err .= "<li class='err'>Invalid characters: {$e['msg']}</li>";
            }
        }
        return get_data($_POST, $err);
    }
    db_conn('crm');
    if (!pglib_transaction("BEGIN")) {
        return "<li class='err'>Unable to edit lead(TB)</li>";
    }
    $Sl = "SELECT * FROM leads WHERE id='{$id}'";
    $Ry = db_exec($Sl) or errDie("Unable to get lead details.");
    if (pg_num_rows($Ry) < 1) {
        return "Invalid lead.";
    }
    $cdata = pg_fetch_array($Ry);
    if ($account_type == "Customer") {
        db_conn("cubit");
        $sql = "SELECT surname FROM customers WHERE cusnum='{$account_id}'";
        $rslt = db_exec($sql) or errDie("Error reading account name (customers)");
        if (pg_num_rows($rslt) > 0) {
            $accountname = pg_fetch_result($rslt, 0, 0);
        } else {
            $account_id = 0;
            $accountname = "";
            $account_type = "";
        }
    } else {
        if ($account_type == "Supplier") {
            db_conn("cubit");
            $sql = "SELECT supname FROM suppliers WHERE supid='{$account_id}'";
            $rslt = db_exec($sql) or errDie("Error reading account name (suppliers)");
            if (pg_num_rows($rslt) > 0) {
                $accountname = pg_fetch_result($rslt, 0, 0);
            } else {
                $account_id = 0;
                $accountname = "";
                $account_type = "";
            }
        } else {
            $accountname = "";
        }
    }
    # write to db
    db_conn("crm");
    $Sql = "\r\n\t\tUPDATE leads \r\n\t\tSET surname='{$surname}', name='{$name}', accountname='{$accountname}', account_id='{$account_id}', \r\n\t\t\taccount_type='{$account_type}', lead_source='{$lead_source}', title='{$title}', department='{$department}', \r\n\t\t\tbirthdate='{$birthdate}', tell='{$tell}', cell='{$cell}', fax='{$fax}', tell_office='{$tell_office}', \r\n\t\t\ttell_other='{$tell_other}', email='{$email}', email_other='{$email_other}', assistant='{$assistant}', \r\n\t\t\tassistant_phone='{$assistant_phone}', padd='{$padd}', padd_city='{$padd_city}', padd_state='{$padd_state}', \r\n\t\t\tpadd_code='{$padd_code}', padd_country='{$padd_country}', hadd='{$hadd}', hadd_city='{$hadd_city}', \r\n\t\t\thadd_state='{$hadd_state}', hadd_code='{$hadd_code}', hadd_country='{$hadd_country}', description='{$description}', \r\n\t\t\twebsite='{$website}', religion='{$religion}', race='{$race}', gender='{$gender}', con='{$Con}', salespid='{$salespn}', \r\n\t\t\tteam_id='{$team_id}' {$ncdate}\r\n\t\tWHERE id='{$id}'";
    // Add entry to today
    if (!empty($ncdate_year) && !empty($ncdate_month) && !empty($ncdate_day)) {
        $contact_date = "{$ncdate_year}-{$ncdate_month}-{$ncdate_day}";
        addTodayEntry("Leads", $id, $contact_date, "Contact {$surname}");
    }
    $Rslt = db_exec($Sql) or errDie("Unable to access database.");
    $Data = pg_fetch_array($Rslt);
    db_conn("cubit");
    if ($cdata['supp_id'] != 0) {
        $Sl = "UPDATE suppliers SET supname='{$surname}',tel='{$tell}',fax='{$fax}',email='{$email}',supaddr='{$padd} \n {$hadd}' WHERE supid='{$cdata['supp_id']}'";
        $Ry = db_exec($Sl) or errDie("Unable to update supplier.");
    }
    if ($cdata['cust_id'] != 0) {
        $Sl = "UPDATE customers SET surname='{$surname}',tel='{$tell}',fax='{$fax}',email='{$email}',paddr1='{$padd}',addr1='{$hadd}' WHERE cusnum='{$cdata['cust_id']}'";
        $Ry = db_exec($Sl) or errDie("Unable to update customers.");
    }
    if (!pglib_transaction("COMMIT")) {
        return "<li class='err'>Unable to edit lead. (TC)</li>";
    }
    $write_data = "\r\n\t\t<table " . TMPL_tblDflts . " width='50%'>\r\n\t\t\t<tr>\r\n\t\t\t\t<th>Lead modified</th>\r\n\t\t\t</tr>\r\n\t\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t\t<td>{$surname} has been modified.</td>\r\n\t\t\t</tr>\r\n\t\t</table>\r\n\t\t<p>\r\n\t\t<table " . TMPL_tblDflts . ">\r\n\t\t\t<tr>\r\n\t\t\t\t<th>Quick Links</th>\r\n\t\t\t</tr>\r\n\t\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t\t<td><a href='leads_list.php'>List leads</a></td>\r\n\t\t\t</tr>\r\n\t\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t\t<td><a href='../main.php'>Main Menu</a></td>\r\n\t\t\t</tr>\r\n\t\t</table>";
    return $write_data;
}
function write($_POST)
{
    #get vars
    foreach ($_POST as $key => $value) {
        ${$key} = $value;
    }
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($sordid, "num", 1, 20, "Invalid Sales Order number.");
    # display errors, if any
    $err = "";
    if ($v->isError()) {
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $err .= "<li class=err>" . $e["msg"];
        }
        return $err;
    }
    # Get Sales Order info
    db_connect();
    $sql = "SELECT * FROM corders WHERE sordid = '{$sordid}' AND accepted != 'c' AND div = '" . USER_DIV . "'";
    $sordRslt = db_exec($sql) or errDie("Unable to get Sales Order information");
    if (pg_numrows($sordRslt) < 1) {
        return "<li class=err>Sales Order Not Found</li>";
    }
    $sord = pg_fetch_array($sordRslt);
    # Get selected customer info
    db_connect();
    $sql = "SELECT * FROM customers WHERE cusnum = '{$sord['cusnum']}' AND div = '" . USER_DIV . "'";
    $custRslt = db_exec($sql) or errDie("Unable to get customer information");
    if (pg_numrows($custRslt) < 1) {
        $sql = "SELECT * FROM cord_data WHERE sordid = '{$sordid}' 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);
    }
    /* - Start Copying - */
    pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
    # todays date (sql formatted)
    $date = date("Y-m-d");
    # get selected stock in this Sales Order
    db_connect();
    $sql = "SELECT * FROM corders_items  WHERE sordid = '{$sordid}' AND div = '" . USER_DIV . "'";
    $stkdRslt = db_exec($sql);
    while ($stkd = pg_fetch_array($stkdRslt)) {
        # update stock(alloc - qty)
        $sql = "UPDATE stock SET alloc = (alloc - '{$stkd['qty']}') WHERE stkid = '{$stkd['stkid']}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update stock to Cubit.", SELF);
    }
    # remove the Sales Order
    $sql = "DELETE FROM corders WHERE sordid = '{$sordid}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to remove Sales Order from Cubit.", SELF);
    #record (sordid, username, date)
    $sql = "INSERT INTO cancelled_cord(sordid, deptid, username, date, deptname, div) VALUES('{$sordid}', '{$sord['deptid']}', '" . USER_NAME . "', '{$date}','{$sord['deptname']}', '" . USER_DIV . "')";
    $rslt = db_exec($sql) or errDie("Unable to insert Sales Order record to Cubit.", SELF);
    /* - End Copying - */
    pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
    // Final Laytout
    $write = "\n\t<table border=0 cellpadding='" . TMPL_tblCellPadding . "' cellspacing='" . TMPL_tblCellSpacing . "'>\n\t\t<tr><th>Consignement Order Cancelled</th></tr>\n\t\t<tr class='bg-even'><td>Consignment Order for customer <b>{$cust['cusname']} {$cust['surname']}</b> has been cancelled.</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='corder-view.php'>View Consignment Orders</a></td></tr>\n\t\t<script>document.write(getQuicklinkSpecial());</script>\n\t</table>";
    return $write;
}
function accept($_POST)
{
    extract($_POST);
    # Validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($invid, "num", 1, 20, "Invalid Sales Order number.");
    # display errors, if any
    if ($v->isError()) {
        $err = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $err .= "<li class=err>" . $e["msg"];
        }
        $confirm .= "<p><input type=button onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $confirm;
    }
    # Get Sales Order info
    db_connect();
    $sql = "SELECT * FROM nons_invoices WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
    $invRslt = db_exec($sql) or errDie("Unable to get -sorder- information");
    if (pg_numrows($invRslt) < 1) {
        return "<i class=err>Not Found</i>";
    }
    $inv = pg_fetch_array($invRslt);
    db_connect();
    /* - Start Copying - */
    pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
    $sql = "INSERT INTO nons_invoices(cusname,cusaddr,cusvatno,chrgvat,sdate,odate,done,username,\n\t\t\t\tprd,invnum,div,remarks,cusid,age,typ,subtot,balance,vat,total,descrip,ctyp,\n\t\t\t\taccid,tval,docref,jobid,jobnum,labid,location,fcid,currency,xrate,fbalance,\n\t\t\t\tfsubtot)\n\tVALUES('{$inv['cusname']}','{$inv['cusaddr']}','{$inv['cusvatno']}','{$inv['chrgvat']}','{$inv['sdate']}',\n\t\t\t'{$inv['odate']}', '{$inv['done']}','{$inv['username']}','{$inv['prd']}','{$inv['invnum']}','{$inv['div']}',\n\t\t\t'{$inv['remarks']}','{$inv['cusid']}','{$inv['age']}','inv','{$inv['subtot']}','{$inv['balance']}',\n\t\t\t'{$inv['vat']}','{$inv['total']}','{$inv['descrip']}', '{$inv['ctyp']}','{$inv['accid']}','{$inv['tval']}',\n\t\t\t'{$inv['docref']}','{$inv['jobid']}','{$inv['jobnum']}','{$inv['labid']}','{$inv['location']}',\n\t\t\t'{$inv['fcid']}','{$inv['currency']}','{$inv['xrate']}','{$inv['fbalance']}', '{$inv['fsubtot']}')";
    $upRslt = db_exec($sql) or errDie("Unable to update -sorder- information");
    # get next ordnum
    $ninvid = lastinvid();
    # Get selected stock in this Sales Order
    db_connect();
    $sql = "SELECT * FROM nons_inv_items  WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
    $stkdRslt = db_exec($sql);
    while ($stkd = pg_fetch_array($stkdRslt)) {
        $stkd['cunitcost'] += 0;
        $sql = "INSERT INTO nons_inv_items(invid, qty, description, div, amt, unitcost, accid, rqty, vatex, cunitcost)\n\t\tVALUES('{$ninvid}', '{$stkd['qty']}', '{$stkd['description']}', '{$stkd['div']}', '{$stkd['amt']}', '{$stkd['unitcost']}', '{$stkd['accid']}', '{$stkd['rqty']}', '{$stkd['vatex']}', '{$stkd['cunitcost']}')";
        $upRslt = db_exec($sql) or errDie("Unable to update -sorder- information");
    }
    # Set to not serialised
    $sql = "UPDATE nons_invoices SET done = 'y' WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to update -sorder-s in Cubit.", SELF);
    /* - End Copying - */
    pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
    header("Location: nons-invoice-new.php?invid={$ninvid}&cont=1");
    exit;
    # Final Laytout
    $write = "\n\t<table border=0 cellpadding='" . TMPL_tblCellPadding . "' cellspacing='" . TMPL_tblCellSpacing . "'>\n\t\t<tr><th>Non-Stock Sales Orders accepted</th></tr>\n\t\t<tr class='bg-even'><td>Non-Stock Sales Orders for Customer <b>{$inv['cusname']}</b> has been accepted.</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='nons-sorder-view.php'>View Non-Stock Sales Orders</a></td></tr>\n\t\t<script>document.write(getQuicklinkSpecial());</script>\n\t</table>";
    return $write;
}
function invoiceHire()
{
    extract($_REQUEST);
    pglib_transaction("BEGIN");
    $sql = "SELECT * FROM hire.hire_invoices WHERE invid='{$invid}'";
    $hi_rslt = db_exec($sql) or errDie("Unable to retrieve invoice.");
    $hi_data = pg_fetch_array($hi_rslt);
    $sql = "SELECT * FROM cubit.customers WHERE cusnum='{$hi_data['cusnum']}'";
    $cust_rslt = db_exec($sql) or errDie("Unable to retrieve customer.");
    $cust_data = pg_fetch_array($cust_rslt);
    $sql = "SELECT * FROM core.accounts WHERE topacc='1050' AND accnum='000'";
    $acc_rslt = db_exec($sql) or errDie("Unable to retrieve account.");
    $acc_data = pg_fetch_array($acc_rslt);
    // 	$sql = "
    // 	INSERT INTO hire.hire_invoices (deptid, cusnum,
    // 		deptname, cusacc, cusname, surname, cusaddr, cusvatno, cordno,
    // 		ordno, chrgvat, terms, traddisc, salespn, odate, delchrg, subtot,
    // 		vat, total, balance, comm, printed, done, div, username, rounding,
    // 		delvat, vatnum, pcash, pcheque, pcc, pcredit, invnum)
    // 	VALUES('$hi_data[deptid]', '$hi_data[cusnum]',
    // 		'$hi_data[deptname]', '$hi_data[cusacc]', '$hi_data[cusname]',
    // 		'$hi_data[surname]', '$hi_data[cusaddr]', '$hi_data[cusvatno]',
    // 		'$hi_data[cordno]', '$hi_data[ordno]', '$hi_data[chrgvat]',
    // 		'$hi_data[terms]', '$hi_data[traddisc]', '$hi_data[salespn]',
    // 		'$hi_data[odate]', '$hi_data[delchrg]', '$hi_data[subtot]',
    // 		'$hi_data[vat]' , '$hi_data[total]', '$hi_data[balance]',
    // 		'$hi_data[comm]', 'y', 'y', '".USER_DIV."', '".USER_NAME."',
    // 		'$hi_data[rounding]', '$hi_data[delvat]', '$hi_data[vatnum]',
    // 		'$hi_data[pcash]', '$hi_data[pcheque]', '$hi_data[pcc]',
    // 		'$hi_data[pcredit]', '$hi_data[invnum]')";
    // 	db_exec($sql) or errDie("Unable to create new hire note.");
    // 	$in_invid = pglib_lastid("hire.hire_invoices", "invid");
    //
    // 	$in_invnum = $hi_data["invnum"];
    //
    // 	$sql = "UPDATE hire.hire_invoices SET invnum='$in_invnum'
    // 			WHERE invid='$in_invid'";
    // 	db_exec($sql) or errDie("Unable to update hire no.");
    $hire_invnum = "{$hi_data['invnum']}" . rev($hi_data["invid"]);
    # Insert invoice to DB
    $sql = "\r\n\t\tINSERT INTO cubit.nons_invoices (\r\n\t\t\tcusnum, cusname, cusaddr, chrgvat, sdate, odate, \r\n\t\t\tsubtot, balance, vat, total, done, username, prd, \r\n\t\t\tinvnum, typ, div, accid, discount, delivery, \r\n\t\t\thire_invid, hire_invnum\r\n\t\t) VALUES (\r\n\t\t\t'{$cust_data['cusnum']}', '{$cust_data['surname']}', '{$cust_data['paddr1']}', 'yes', CURRENT_DATE, CURRENT_DATE, \r\n\t\t\t'{$hi_data['subtot']}', '{$hi_data['total']}', '{$hi_data['vat']}', '{$hi_data['total']}', 'n', '" . USER_NAME . "', '" . PRD_DB . "', \r\n\t\t\t'{$hi_data['invnum']}',  'inv', '" . USER_DIV . "','{$acc_data['accid']}', '{$hi_data['discount']}', '{$hi_data['delivery']}', \r\n\t\t\t'{$hi_data['invid']}', '{$hire_invnum}'\r\n\t\t)";
    $rslt = db_exec($sql) or errDie("Unable to create template Non-Stock Invoice.", SELF);
    db_conn("hire");
    $nons_invid = lastinvid();
    db_conn("cubit");
    $sql = "SELECT * FROM hire.hire_invitems WHERE invid='{$invid}'";
    $hire_rslt = db_exec($sql) or errDie("Unable to retrieve hire items.");
    while ($hire_data = pg_fetch_array($hire_rslt)) {
        $sql = "SELECT des FROM cubit.assets WHERE id='{$hire_data['asset_id']}'";
        $des_rslt = db_exec($sql) or errDie("Unable to retrieve asset.");
        $itemdes = pg_fetch_result($des_rslt, 0);
        if ($hire_data["basis"] == "per_hour") {
            $des = getSerial($hire_data["asset_id"], 1) . " {$itemdes} hired for {$hire_data['hours']} hours.";
        } elseif ($hire_data["basis"] == "per_day") {
            $des = getSerial($hire_data["asset_id"], 1) . " {$itemdes} hired from {$hire_data['from_date']} to {$hire_data['to_date']}.";
        } else {
            $des = getSerial($hire_data["asset_id"], 1) . " {$itemdes} hired for {$hire_data['weeks']} weeks.";
        }
        $sql = "\r\n\t\t\tINSERT INTO hire.hire_nons_inv_items (\r\n\t\t\t\tinvid, qty, description, div, amt, unitcost, vatex, \r\n\t\t\t\taccid, item_id, asset_id\r\n\t\t\t) VALUES (\r\n\t\t\t\t'{$nons_invid}', '{$hire_data['qty']}', '{$des}', " . USER_DIV . ", '{$hire_data['amt']}', '{$hire_data['amt']}', '2', \r\n\t\t\t\t'{$acc_data['accid']}', '{$hire_data['id']}', '{$hire_data['asset_id']}'\r\n\t\t\t)";
        db_exec($sql) or errDie("Unable to add non stock items.");
        /*		$sql = "
        		INSERT INTO hire.hire_invitems (invid, qty, ss, div, amt, discp, disc,
        			unitcost, noted, serno, vatcode, description, account, from_date,
        			to_date, asset_id, basis, hours, stkid, collection, weeks, days)
        		VALUES ('$in_invid', '$hire_data[qty]', '$hire_data[ss]',
        			'$hire_data[div]', '$hire_data[amt]', '$hire_data[discp]',
        			'$hire_data[disc]', '$hire_data[unitcost]', '$hire_data[noted]',
        			'$hire_data[serno]', '$hire_data[vatcode]', '$hire_data[description]',
        			'$hire_data[account]', '$hire_data[from_date]', '$hire_data[to_date]',
        			'$hire_data[asset_id]', '$hire_data[basis]', '$hire_data[hours]',
        			'$hire_data[stkid]', '$hire_data[collection]', '$hire_data[weeks]',
        			'$hire_data[days]')";
        		db_exec($sql) or errDie("Unable to create new hire note items.");*/
    }
    pglib_transaction("COMMIT");
    header("Location: hire-nons-invoice-print.php?invid={$nons_invid}&key=cconfirm&ctyp=s&cusnum={$hi_data['cusnum']}&post=true&monthly=1");
    return $OUTPUT;
}
function write($_POST)
{
    # strip the vars
    foreach ($_POST as $key => $value) {
        ${$key} = $value;
    }
    # open temp file
    if ($file = file(dirname($tmpname) . "/" . $filename)) {
        # delete the temporary file
        unlink(dirname($tmpname) . "/" . $filename);
    } else {
        return "Unable to open file {$filename} on the temp Directory";
    }
    # number of accounts
    $numrec = 0;
    # connect to core
    core_connect();
    # start inserting
    pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
    foreach ($file as $key => $value) {
        # Explode the line into vars( in order )
        list($date[$key], $refnum[$key], $dtaccname[$key], $dtaccnum[$key], $ctaccname[$key], $ctaccnum[$key], $amount[$key], $details[$key], $author[$key]) = explode(";", $value);
        # Account numbers
        $dtaccno = explode("/", $dtaccnum[$key]);
        $ctaccno = explode("/", $ctaccnum[$key]);
        # get DT account ID
        $dtaccRs = get("core", "accid", "accounts", "topacc", "{$dtaccno['0']}' AND accnum = '{$dtaccno['1']}");
        if (pg_numrows($dtaccRs) < 1) {
            return "<li> Accounts number : {$ctaccno['0']}/{$ctaccno['1']} does not exist";
        }
        $dtacc = pg_fetch_array($dtaccRs);
        $dtaccid[$key] = $dtacc['accid'];
        # get CT account ID
        $ctaccRs = get("core", "accid", "accounts", "topacc", "{$ctaccno['0']}' AND accnum = '{$ctaccno['1']}");
        if (pg_numrows($ctaccRs) < 1) {
            return "<li> Accounts number : {$ctaccno['0']}/{$ctaccno['1']} does not exist";
        }
        $ctacc = pg_fetch_array($ctaccRs);
        $ctaccid[$key] = $ctacc['accid'];
        #  if(count($tran) < 2){
        #        return "<li>Invalid file format";
        # }
        # Wrtie to table
        # $tab .= "<tr><td>$date[$key]</td><td>$refnum[$key]</td><td>$dtaccname[$key]</td><td>$ctaccname[$key]</td><td>$amount[$key]</td><td>$details[$key]</td><td>$author[$key]</td></tr>";
        # Insert Into the batch table
        $sql = "INSERT INTO batch(date, debit, credit, refnum, amount, author, details) VALUES('{$date[$key]}', '{$dtaccid[$key]}', '{$ctaccid[$key]}', '{$refnum[$key]}', '{$amount[$key]}', '{$author[$key]}', '{$details[$key]}')";
        $transRslt = db_exec($sql) or errDie("Unable to insert Transaction  details to database", SELF);
        $numrec++;
    }
    # commit sql transaction
    pglib_transaction("COMMIT") or errDie("Unable to finish a database transaction.", SELF);
    $tab = "<center><table bgcolor=#ffffff width=50%>\r\n        <tr><th>Transactions Saved to system batch file</th></tr>\r\n        <tr><td class=datacell align=center><b>{$numrec}</b> Transections from the file : <b>{$filename}</b> have been succsessfuly added to the system batch.</b></td></tr>\r\n        </table>";
    return $tab;
}
function write($_POST)
{
    # Get vars
    extract($_POST);
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($cusnum, "num", 1, 50, "Invalid Customer number.");
    $v->isOk($accid, "num", 1, 50, "Invalid Contra Account.");
    $v->isOk($refnum, "num", 1, 10, "Invalid Reference number.");
    $v->isOk($amount, "float", 1, 20, "Invalid Amount.");
    $v->isOk($details, "string", 0, 255, "Invalid Details.");
    $v->isOk($author, "string", 1, 30, "Invalid Authorising person name.");
    $datea = explode("-", $date);
    if (count($datea) == 3) {
        if (!checkdate($datea[1], $datea[2], $datea[0])) {
            $v->isOk($date, "num", 1, 1, "Invalid date.");
        }
    } else {
        $v->isOk($date, "num", 1, 1, "Invalid date.");
    }
    # display errors, if any
    if ($v->isError()) {
        $write = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $write .= "<li class='err'>" . $e["msg"] . "</li>";
        }
        $write .= "<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $write;
    }
    # Accounts details
    $accRs = get("core", "*", "accounts", "accid", $accid);
    $acc = pg_fetch_array($accRs);
    # Select customer
    db_connect();
    $sql = "SELECT * FROM customers WHERE cusnum = '{$cusnum}' AND div = '" . USER_DIV . "'";
    $custRslt = db_exec($sql) or errDie("Unable to access databse.", SELF);
    if (pg_numrows($custRslt) < 1) {
        return "<li> Invalid Customer ID.</li>";
    } else {
        $cust = pg_fetch_array($custRslt);
    }
    # Get department
    db_conn("exten");
    $sql = "SELECT * FROM departments WHERE deptid = '{$cust['deptid']}' AND div = '" . USER_DIV . "'";
    $deptRslt = db_exec($sql);
    if (pg_numrows($deptRslt) < 1) {
        return "<i class='err'>Department Not Found</i>";
    } else {
        $dept = pg_fetch_array($deptRslt);
    }
    $famt = sprint($amount);
    $amount = sprint($amount * $rate);
    cus_xrate_update($cust['fcid'], $rate);
    xrate_update($cust['fcid'], $rate, "invoices", "invid");
    xrate_update($cust['fcid'], $rate, "custran", "id");
    # Probe tran type
    if ($entry == "CT") {
        # Write transaction  (debit contra account, credit debtors control)
        writetrans($accid, $dept['debtacc'], $date, $refnum, $amount, $details . " - Customer {$cust['cusname']} {$cust['surname']}");
        $tran = "\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>{$acc['topacc']}/{$acc['accnum']} - {$acc['accname']}</td>\n\t\t\t\t\t<td>{$cust['accno']} - {$cust['cusname']} {$cust['surname']}</td>\n\t\t\t\t</tr>";
        $samount = sprint($amount - $amount * 2);
        $sfamt = sprint($famt - $famt * 2);
        // recordCT($samount, $cust['cusnum']);
        frecordCT($famt, $amount, $cust['cusnum'], $cust['fcid'], $date);
        $type = 'c';
    } else {
        # Write transaction  (debit debtors control, credit contra account)
        writetrans($dept['debtacc'], $accid, $date, $refnum, $amount, $details . " - Customer {$cust['cusname']} {$cust['surname']}");
        $tran = "\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>{$cust['accno']} - {$cust['cusname']} {$cust['surname']}</td>\n\t\t\t\t\t<td>{$acc['topacc']}/{$acc['accnum']} - {$acc['accname']}</td>\n\t\t\t\t</tr>";
        $samount = $amount;
        $sfamt = $famt;
        // recordDT($samount, $cust['cusnum']);
        frecordDT($famt, $amount, $cust['cusnum'], $cust['fcid'], $date);
        $type = 'd';
    }
    db_connect();
    # Begin updates
    pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
    $sdate = date("Y-m-d");
    # record the payment on the statement
    $sql = "\n\t\t\tINSERT INTO stmnt \n\t\t\t\t(cusnum, invid, amount, date, type, st, div, allocation_date) \n\t\t\tVALUES \n\t\t\t\t('{$cust['cusnum']}', '0', '{$sfamt}', '{$date}', '{$details}', 'n', '" . USER_DIV . "', '{$date}')";
    $stmntRslt = db_exec($sql) or errDie("Unable to Insert statement record in Cubit.", SELF);
    # update the customer (make balance more)
    $sql = "UPDATE customers SET balance = (balance + '{$samount}'), fbalance = (fbalance + '{$sfamt}') WHERE cusnum = '{$cust['cusnum']}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to update customer in Cubit.", SELF);
    # Commit updates
    pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
    # Make ledge record
    custledger($cust['cusnum'], $accid, $date, $refnum, $details, $amount, $type);
    // Start layout
    $write = "\n\t\t\t<h3>Journal transaction has been recorded</h3>\n\t\t\t<table " . TMPL_tblDflts . " width='500'>\n\t\t\t\t<tr>\n\t\t\t\t\t<td width='50%'><h3>Debit</h3></td>\n\t\t\t\t\t<td width='50%'><h3>Credit</h3></td>\n\t\t\t\t</tr>\n\t\t\t\t{$tran}\n\t\t\t\t" . TBL_BR . "\n\t\t\t\t<tr colspan='2'>\n\t\t\t\t\t<td><h4>Amount</h4></td>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td colspan='2'><b>" . CUR . " {$famt}</b></td>\n\t\t\t\t</tr>\n\t\t\t</table>\n\t\t\t<P>\n\t\t\t<table " . TMPL_tblDflts . " width='25%'>\n\t\t\t\t<tr>\n\t\t\t\t\t<th>Quick Links</th>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td align='center'><a href='trans-new.php'>Journal Transactions</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td align='center'><a href='../customers-view.php'>View Customers</a></td>\n\t\t\t\t</tr>\n\t\t\t\t<script>document.write(getQuicklinkSpecial());</script>\n\t\t\t</table>";
    return $write;
}
function write($_POST)
{
    # get vars
    extract($_POST);
    // prevent from updating
    if (isset($cusnum) && customer_overdue($cusnum)) {
        return details($_POST);
    }
    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($bodydata)) {
        $bodydata = "";
    }
    if (!isset($counter)) {
        $counter = "";
    }
    $bodydata = str_replace("'", "", $bodydata);
    $bodydata = str_replace("  ", " ", $bodydata);
    $bodydata = str_replace("&nbsp;&nbsp;", " ", $bodydata);
    $bodydata = str_replace(" &nbsp;", " ", $bodydata);
    $bodydata = str_replace("&nbsp; ", " ", $bodydata);
    $des[$counter] = $bodydata;
    # validate input
    require_lib("validate");
    $v = new validate();
    if (empty($ninv_year)) {
        list($ninv_year, $ninv_month, $ninv_day) = date("Y-m-d");
    }
    $odate = mkdate($ninv_year, $ninv_month, $ninv_day);
    $v->isOk($odate, "date", 1, 1, "Invalid Date.");
    # used to generate errors
    $error = "asa@";
    // check the invoice details
    $v->isOK($cusname, "string", 1, 100, "Invalid customer name");
    $v->isOK($cusaddr, "string", 0, 400, "Invalid customer address");
    $v->isOK($cusvatno, "string", 0, 50, "Invalid customer vat number");
    $v->isOK($docref, "string", 0, 20, "Invalid Document Reference No.");
    $v->isOK($cordno, "string", 0, 20, "Invalid Customer Order Number.");
    if ($chrgvat != "yes" && $chrgvat != "no" && $chrgvat != "none") {
        $v->addError($chrgvat, "Invalid vat option");
    }
    # check quantities
    if (isset($qtys)) {
        foreach ($qtys as $keys => $qty) {
            $v->isOk($qty, "float", 1, 10, "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>.");
            //		$v->isOk ($des[$keys], "url", 1, 255, "Invalid Description.");
            if ($qty <= 0) {
                $v->isOk($qty, "num", 0, 0, "Error : Item Quantity can't be zero or less. Product number: <b>" . ($keys + 1) . "</b>");
            }
        }
    }
    # check amt
    if (isset($amt)) {
        foreach ($amt as $keys => $amount) {
            $v->isOk($amount, "float", 1, 16, "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>";
        }
        $_POST['done'] = "";
        return details($_POST, $err);
    }
    # Get purchase info
    db_connect();
    $sql = "SELECT * FROM nons_invoices WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
    $invRslt = db_exec($sql) or errDie("Unable to get purchase information");
    if (pg_numrows($invRslt) < 1) {
        return "<li>- Invoice Not Found</li>";
    }
    $inv = pg_fetch_array($invRslt);
    $inv['chrgvat'] = $chrgvat;
    # check if purchase has been printed
    if ($inv['done'] == "y") {
        $error = "<li class='err'> Error : Invoice number <b>{$invid}</b> has already been printed.";
        $error .= "<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $error;
    }
    $vatamount = 0;
    $showvat = TRUE;
    # insert purchase to DB
    db_conn("cubit");
    # begin updating
    pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
    /* -- Start remove old items -- */
    # remove old items
    $sql = "DELETE FROM nons_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 -- */
    $taxex = 0;
    if (isset($qtys)) {
        foreach ($qtys as $keys => $value) {
            if (isset($remprod)) {
                if (in_array($keys, $remprod)) {
                    # skip product (wonder if $keys still align)
                    $amt[$keys] = 0;
                    continue;
                } else {
                    # Calculate amount
                    $amt[$keys] = $qtys[$keys] * $unitcost[$keys];
                    if (!isset($vatcodes[$keys])) {
                        $vatcodes[$keys] = 0;
                    }
                    db_connect();
                    $Sl = "SELECT * FROM vatcodes WHERE id='{$vatcodes[$keys]}'";
                    $Ri = db_exec($Sl);
                    // 					if(pg_num_rows($Ri)<1) {
                    // 						return "Please select the vatcode for all your stock.";
                    // 					}
                    $vd = pg_fetch_array($Ri);
                    if ($vd['zero'] == "Yes") {
                        $excluding = "y";
                    } else {
                        $excluding = "";
                    }
                    if (TAX_VAT != $vd['vat_amount'] and $vd['vat_amount'] != "0.00") {
                        $showvat = FALSE;
                    }
                    $vr = vatcalc($amt[$keys], $inv['chrgvat'], $excluding, 0, $vd['vat_amount']);
                    $vrs = explode("|", $vr);
                    $ivat = $vrs[0];
                    $iamount = $vrs[1];
                    $vatamount += $ivat;
                    $vate = 'n';
                    if (isset($vatex) && in_array($keys, $vatex) || $vd['zero'] == "Yes") {
                        $taxex += $amt[$keys];
                        $vate = 'y';
                    }
                    $vate = $vatcodes[$keys];
                    # insert purchase items
                    $sql = "\n\t\t\t\t\t\tINSERT INTO nons_inv_items (\n\t\t\t\t\t\t\tinvid, qty, amt, unitcost, description, vatex, div\n\t\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t\t'{$invid}', '{$qtys[$keys]}', '{$amt[$keys]}', '{$unitcost[$keys]}', '{$des[$keys]}', '{$vate}', '" . USER_DIV . "'\n\t\t\t\t\t\t)";
                    $rslt = db_exec($sql) or errDie("Unable to insert invoice items to Cubit.", SELF);
                }
            } else {
                # Calculate amount
                $amt[$keys] = $qtys[$keys] * $unitcost[$keys];
                if (!isset($vatcodes[$keys])) {
                    $vatcodes[$keys] = 0;
                }
                $Sl = "SELECT * FROM vatcodes WHERE id='{$vatcodes[$keys]}'";
                $Ri = db_exec($Sl);
                // 				if(pg_num_rows($Ri) < 1) {
                // 					return "Please select the vatcode for all your stock.";
                // 				}
                $vd = pg_fetch_array($Ri);
                if ($vd['zero'] == "Yes") {
                    $excluding = "y";
                } else {
                    $excluding = "";
                }
                if (TAX_VAT != $vd['vat_amount'] and $vd['vat_amount'] != "0.00") {
                    $showvat = FALSE;
                }
                $vr = vatcalc($amt[$keys], $inv['chrgvat'], $excluding, 0, $vd['vat_amount']);
                $vrs = explode("|", $vr);
                $ivat = $vrs[0];
                $iamount = $vrs[1];
                $vatamount += $ivat;
                $vate = 'n';
                if (isset($vatex) && in_array($keys, $vatex) || $vd['zero'] == "Yes") {
                    $taxex += $amt[$keys];
                    $vate = 'y';
                }
                $vate = $vatcodes[$keys];
                db_connect();
                # insert purchase items
                $sql = "\n\t\t\t\t\tINSERT INTO nons_inv_items (\n\t\t\t\t\t\tinvid, qty, amt, unitcost, description, vatex, div\n\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t'{$invid}', '{$qtys[$keys]}', '{$amt[$keys]}', '{$unitcost[$keys]}', '{$des[$keys]}', '{$vate}', '" . USER_DIV . "'\n\t\t\t\t\t)";
                $rslt = db_exec($sql) or errDie("Unable to insert invoice items to Cubit.", SELF);
            }
            # everything is set place done button
            $_POST["done"] = " | <input name='doneBtn' type='submit' value='Done'>| <input name='print' type='submit' value='Process'>";
        }
    } else {
        $_POST["done"] = "";
    }
    $_POST['showvat'] = $showvat;
    /* --- ----------- Clac --------------------- */
    ##----------------------NEW----------------------
    $sub = 0.0;
    if (isset($amt)) {
        $sub = sprint(array_sum($amt));
    }
    $VATP = TAX_VAT;
    if ($chrgvat == "no") {
        $subtotal = sprint($sub);
        $subtotal = sprint($subtotal);
        // 		$VAT=sprint(($subtotal-$taxex)*$VATP/100);
        $VAT = $vatamount;
        $SUBTOT = $sub;
        $TOTAL = sprint($subtotal + $VAT);
    } elseif ($chrgvat == "yes") {
        $subtotal = sprint($sub);
        $subtotal = sprint($subtotal);
        // 		$VAT=sprint(($subtotal-$taxex)*$VATP/(100+$VATP));
        $VAT = $vatamount;
        $SUBTOT = sprint($sub);
        $TOTAL = sprint($subtotal);
    } else {
        $subtotal = sprint($sub);
        $traddiscmt = sprint($subtotal);
        $subtotal = sprint($subtotal);
        $VAT = sprint(0);
        $SUBTOT = $sub;
        $TOTAL = $subtotal;
    }
    /* --- ----------- Clac --------------------- */
    ##----------------------END----------------------
    /* --- Clac ---
    	# calculate subtot
    	if( isset($amt) ){
    		$SUBTOT = array_sum($amt);
    	}else{
    		$SUBTOT = 0.00;
    	}
    
    	$SUBTOT -= $taxex;
    
    	$VATP = TAX_VAT;
    	if($chrgvat == "no"){
    		$SUBTOT = $SUBTOT;
    	}elseif($chrgvat == "yes"){
    		$SUBTOT = sprint(($SUBTOT * 100)/(100 + $VATP));
    	}else{
    		$SUBTOT = ($SUBTOT);
    	}
    
    	if($chrgvat != "none"){
    		$VAT = sprint($SUBTOT * ($VATP/100));
    	}else{
    		$VAT = 0;
    	}
    
    	$TOTAL = sprint($SUBTOT + $VAT + $taxex);
    	$SUBTOT += $taxex;
    
    	/* --- End Clac --- */
    $salespn = remval($salespn);
    if (!isset($bankid)) {
        if (isset($cusnum) and strlen($cusnum) > 0) {
            #get bankid from customer info
            $get_cbank = "SELECT bankid FROM customers WHERE cusnum = '{$cusnum}' LIMIT 1";
            $run_cbank = db_exec($get_cbank) or errDie("Unable to get bank information for customer.");
            if (pg_numrows($run_cbank) > 0) {
                $bankid = pg_fetch_result($run_cbank, 0, 0);
            } else {
                $bankid = "2";
            }
        } else {
            $bankid = "2";
        }
    }
    # insert purchase to DB
    $sql = "\n\t\tUPDATE nons_invoices \n\t\tSET salespn='{$salespn}', cusname = '{$cusname}', cusaddr = '{$cusaddr}', \n\t\t\tcusvatno = '{$cusvatno}', cordno = '{$cordno}', docref = '{$docref}', \n\t\t\tchrgvat = '{$chrgvat}', odate = '{$odate}', terms = '{$terms}', \n\t\t\tsubtot = '{$SUBTOT}', vat = '{$VAT}', total = '{$TOTAL}', \n\t\t\tremarks = '{$remarks}', bankid = '{$bankid}' \n\t\tWHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
    # commit updating
    pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
    if (isset($print)) {
        $OUTPUT = "<script>printer('nons-invoice-print.php?invid={$invid}');move('nons-invoice-new.php');</script>";
        require "template.php";
    }
    if (!isset($doneBtn)) {
        return details($_POST);
    } else {
        //$rslt = db_exec($sql) or errDie("Unable to update invoices status in Cubit.$sql",SELF);
        # Final Laytout
        $write = "\n\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t<tr>\n\t\t\t\t\t<th>New Non-Stock Invoices</th>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>Non-Stock Invoices for Customer <b>{$cusname}</b> has been recorded.</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='nons-invoice-view.php'>View Non-Stock 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;
    }
}
function write()
{
    validate($_REQUEST);
    extract($_REQUEST);
    $where_qry = array();
    if ($pricelist) {
        $where_qry[] = "listid='{$pricelist}'";
    }
    if ($category) {
        $sql = "SELECT cat FROM cubit.stockcat WHERE catid='{$category}'";
        $category_rslt = db_exec($sql) or errDie("Unable to retrieve category.");
        $category_name = pg_fetch_result($category_rslt, 0);
        $where_qry[] = "catname='{$category_name}'";
    }
    if ($classification) {
        $sql = "SELECT classname FROM cubit.stockclass WHERE clasid='{$classification}'";
        $classification_rslt = db_exec($sql) or errDie("Unable to retrieve classification.");
        $classification_name = pg_fetch_result($classification_rslt, 0);
        $where_qry[] = "classname='{$classification_name}'";
    }
    $where = implode(" AND ", $where_qry);
    if (!empty($where)) {
        $where = "WHERE {$where}";
    }
    $percentage = $increase - $decrease;
    $sql = "\n\tSELECT listid, stkcod, stkdes, price AS old_price,\n\t\t(price + (price / 100 * '{$percentage}')) AS new_price\n\tFROM exten.splist_prices\n\t\tLEFT JOIN cubit.stock ON splist_prices.stkid=stock.stkid\n\t{$where}";
    $prices_rslt = db_exec($sql) or errDie("Unable to retrieve prices.");
    $i = 0;
    pglib_transaction("BEGIN");
    while ($prices_data = pg_fetch_array($prices_rslt)) {
        $sql = "\n\t\tUPDATE exten.splist_prices\n\t\tSET price='{$prices_data['new_price']}'\n\t\tWHERE listid='{$prices_data['listid']}'";
        db_exec($sql) or errDie("Unable to update price.");
        $i++;
    }
    pglib_transaction("COMMIT");
    $OUTPUT = "\n\t<center>\n\t<h3>Mass Adjust Prices</h3>\n\t<table " . TMPL_tblDflts . ">\n\t\t<tr>\n\t\t\t<th>Write</th>\n\t\t</tr>\n\t\t<tr class='" . bg_class() . "'>\n\t\t\t<td><li>Successfully adjusted <b>{$i}</b> prices.</li></td>\n\t\t</tr>\n\t</table>";
    return $OUTPUT;
}
예제 #22
0
function write($_POST)
{
    # get vars
    extract($_POST);
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($type, "string", 1, 255, "Invalid Transaction type switch.");
    $v->isOk($typename, "string", 1, 255, "Invalid Transaction type.");
    $edate = $v->chkrDate($edate, "Invalid date.");
    $v->isOk($amount, "float", 1, 13, "Invalid Amount.");
    $v->isOk($descrip, "string", 0, 255, "Invalid description.");
    if (isset($ccids)) {
        foreach ($ccids as $key => $value) {
            $v->isOk($ccperc[$key], "float", 1, 20, "Invalid Cost center percentage.");
        }
    } else {
        return enter($_POST, "<li class=err> There are no Cost centers found.");
    }
    # display errors, if any
    if ($v->isError()) {
        $confirmCust = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $confirmCust .= "<li class='err'>" . $e["msg"] . "</li>";
        }
        return enter($_POST, $confirm);
        $confirmCust .= "<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $confirmCust;
    }
    $type = strtolower($type);
    $edate = ext_rdate($edate);
    $edarr = explode("-", $edate);
    $prd = $edarr[1];
    ## start transaction
    pglib_transaction("BEGIN") or errDie("Unable to start transaction.");
    $ccenters = "";
    foreach ($ccids as $key => $value) {
        db_connect();
        $sql = "SELECT * FROM costcenters_links WHERE id = '{$ccids[$key]}'";
        $ccRslt = db_exec($sql) or errDie("Unable to retrieve Cost centers from database.");
        $cc = pg_fetch_array($ccRslt);
        $ccamts[$key] = sprint($amount * ($ccperc[$key] / 100));
        #we need to connect to the actual period db
        db_conn($prd);
        if ($type == "dtct") {
            $sql = "\n\t\t\t\t\tINSERT INTO cctran \n\t\t\t\t\t\t(ccid, trantype, typename, edate, description, amount, username, div, project) \n\t\t\t\t\tVALUES \n\t\t\t\t\t\t('{$ccids[$key]}', 'dt', '{$typename}', '{$edate}', '{$descrip}', '{$ccamts[$key]}', '" . USER_NAME . "', '" . USER_DIV . "', '{$ccidpro[$key]}')";
            $insRslt = db_exec($sql) or errDie("Unable to retrieve insert Cost center amounts into database.");
            $sql = "\n\t\t\t\t\tINSERT INTO cctran \n\t\t\t\t\t\t(ccid, trantype, typename, edate, description, amount, username, div, project) \n\t\t\t\t\tVALUES \n\t\t\t\t\t\t('{$ccids[$key]}', 'ct', '{$typename}', '{$edate}', '{$descrip}', '{$ccamts[$key]}', '" . USER_NAME . "', '" . USER_DIV . "', '{$ccidpro[$key]}')";
            $insRslt = db_exec($sql) or errDie("Unable to retrieve insert Cost center amounts into database.");
        } else {
            $sql = "\n\t\t\t\t\tINSERT INTO cctran \n\t\t\t\t\t\t(ccid, trantype, typename, edate, description, amount, username, div, project) \n\t\t\t\t\tVALUES \n\t\t\t\t\t\t('{$ccids[$key]}', '{$type}', '{$typename}', '{$edate}', '{$descrip}', '{$ccamts[$key]}', '" . USER_NAME . "', '" . USER_DIV . "', '{$ccidpro[$key]}')";
            $insRslt = db_exec($sql) or errDie("Unable to retrieve insert Cost center amounts into database.");
        }
    }
    db_connect();
    #now remove the temp entry
    $rem_sql = "DELETE FROM cc_popup_data WHERE id = '{$writeid}'";
    $run_rem = db_exec($rem_sql) or errDie("Unable to remove temporary cost center information.");
    pglib_transaction("COMMIT") or errDie("Unable to complete transaction.");
    // Layout
    $write = "\n\t\t<center>\n\t\t<table " . TMPL_tblDflts . " width='300'>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td align='center'><b>( i )</b> Amount has been allocated to Cost Centers. <b>( i )</b></td>\n\t\t\t</tr>\n\t\t</table>\n\t\t<p>\n\t\t<input type=button value=' [X] Close ' onClick='javascript:window.close();'>\n\t\t</center>";
    return $write;
}
예제 #23
0
function con_data($_POST)
{
    # get vars
    extract($_POST);
    if (isset($back)) {
        return view_data($_POST);
    }
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($id, "num", 0, 100, "Invalid number.");
    $v->isOk($depamt, "float", 0, 14, "Invalid Depreciation Amount.");
    $v->isOk($depmonths, "num", 0, 3, "Invalid auto depreciation period.");
    $v->isOk("{$depmonths}{$depamt}", "float", 1, 14, "Enter one of Depreciation amount or period.");
    if (!empty($depamt) && $netval < $depamt) {
        $v->isOk("###", "float", 1, 1, "Error : Depreciation amount must not be more than the Net Value.");
    } else {
        if (!empty($depmonths) && $depperc <= 0) {
            $v->addError("###", "Depriaction percentage has to be more than 0 if depreciating by period.");
        }
    }
    $v->isOk($date, "date", 1, 14, "Invalid account open date.");
    # display errors, if any
    if ($v->isError()) {
        $confirmCust = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $confirmCust .= "<li class=err>" . $e["msg"];
        }
        $confirmCust .= "<p><input type=button onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $confirmCust;
    }
    db_conn('cubit');
    $user = USER_NAME;
    $Sql = "SELECT * FROM assets WHERE (id='{$id}' AND div = '" . USER_DIV . "')";
    $Rslt = db_exec($Sql) or errDie("Unable to access database.");
    if (pg_numrows($Rslt) < 1) {
        return "Asset not Found";
    }
    $led = pg_fetch_array($Rslt);
    # Get group
    $sql = "SELECT * FROM assetgrp WHERE grpid = '{$led['grpid']}' AND div = '" . USER_DIV . "'";
    $grpRslt = db_exec($sql);
    $grp = pg_fetch_array($grpRslt);
    # get last ref number
    $refnum = getrefnum($date);
    if ($led["dep_acc"]) {
        $dep_acc = $led["dep_acc"];
    } else {
        // Maintain backwards compatibiltiy
        $sql = "\r\n\t\tSELECT accid FROM core.accounts\r\n\t\tWHERE topacc='2200' AND accnum='000'";
        $acc_rslt = db_exec($sql) or errDie("Unable to retrieve account.");
        $dep_acc = pg_fetch_result($acc_rslt, 0);
    }
    if ($led["accdep_acc"]) {
        $accdep_acc = $led["accdep_acc"];
    } else {
        // Maintain backwards compatibiltiy
        $accdep_acc = $grp["accdacc"];
    }
    pglib_transaction("BEGIN");
    # dt(depacc) ct(accdep)
    writetrans($dep_acc, $accdep_acc, $date, $refnum, $depamt, "{$led['des']} Depreciation");
    db_connect();
    $sql = "UPDATE assets SET accdep = (accdep + '{$depamt}') WHERE (id='{$id}' AND div = '" . USER_DIV . "')";
    $up = db_exec($sql) or errdie("Could not update assets table.");
    $snetval = $netval - $depamt;
    $sdate = date("Y-m-d");
    $sql = "INSERT INTO assetledger(assetid, asset, date, depamt, netval, div) \r\n\t\t\tVALUES ('{$id}', '{$led['des']}', '{$date}', '{$depamt}', '{$snetval}', '" . USER_DIV . "')";
    $rec = db_exec($sql) or errdie("Could not write to asset ledger.");
    $cc = "<script> CostCenter('ct', 'Asset Depreciation', '{$date}', '{$led['des']} Depreciation', '{$depamt}', ''); </script>";
    pglib_transaction("COMMIT");
    $write = "\r\n\t\t\t\t{$cc}\r\n\t\t\t\t<table " . TMPL_tblDflts . " width='50%'>\r\n\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t<th>Asset Depreciation</th>\r\n\t\t\t\t\t</tr>\r\n\t\t\t\t\t<tr class='datacell'>\r\n\t\t\t\t\t\t<td>Asset Depreciation has been recorded</td>\r\n\t\t\t\t\t</tr>\r\n\t\t\t\t</table>\r\n\t\t\t\t<p>\r\n\t\t\t\t<table border=0 cellpadding='2' cellspacing='1'>\r\n\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t<th>Quick Links</th>\r\n\t\t\t\t\t</tr>\r\n\t\t\t\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t\t\t\t<td><a href='asset-new.php'>New Asset</a></td>\r\n\t\t\t\t\t</tr>\r\n\t\t\t\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t\t\t\t<td><a href='asset-view.php'>View Assets</a></td>\r\n\t\t\t\t\t</tr>\r\n\t\t\t\t\t<script>document.write(getQuicklinkSpecial());</script>\r\n\t\t\t\t</table>";
    return $write;
}
예제 #24
0
function getMsgType($msg_type)
{
    $rslt = db_exec("SELECT type_id FROM mail_datatypes WHERE name = '{$msg_type}'");
    // does it exist? return it
    if (pg_num_rows($rslt) > 0) {
        return pg_fetch_result($rslt, 0, 0);
    }
    // it doesn't! create it and get the insert id
    if (!pglib_transaction("BEGIN")) {
        return 1;
    }
    if (!db_exec("\n\t\tINSERT INTO mail_datatypes (name,icon)\n\t\tVALUES('{$msg_type}', 'icon_blank.gif')")) {
        return;
    }
    $type_id = pglib_lastid("mail_datatypes", "type_id");
    if (!pglib_transaction("COMMIT")) {
        return 1;
    }
    return $type_id;
}
function write($_POST)
{
    # Get vars
    extract($_POST);
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($quoid, "num", 1, 20, "Invalid Quote number.");
    # display errors, if any
    $err = "";
    if ($v->isError()) {
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $err .= "<li class='err'>" . $e["msg"] . "</li>";
        }
        return $err;
    }
    # Get quote info
    db_connect();
    $sql = "SELECT * FROM pos_quotes WHERE quoid = '{$quoid}' AND div = '" . USER_DIV . "'";
    $quoRslt = db_exec($sql) or errDie("Unable to get quote information");
    if (pg_numrows($quoRslt) < 1) {
        return "<li class='err'>Quote Not Found</li>";
    }
    $quo = pg_fetch_array($quoRslt);
    /* - Start Copying - */
    pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
    db_connect();
    $Sl = "SELECT * FROM posround";
    $Ri = db_exec($Sl);
    $data = pg_fetch_array($Ri);
    $TOTAL = $quo['total'];
    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;
    }
    # Insert invoice to DB
    $sql = "INSERT INTO pinvoices(deptid, deptname, cusname, surname, cusaddr, ordno, chrgvat, terms, traddisc, salespn, odate, delchrg, subtot, vat, total, balance, comm, printed, done, prd, div,rounding,delvat)";
    $sql .= " VALUES('{$quo['deptid']}', '{$quo['deptname']}', '{$quo['cusname']}', '{$quo['surname']}', '{$quo['cusaddr']}', '{$quo['ordno']}', '{$quo['chrgvat']}', '{$quo['terms']}', '{$quo['traddisc']}', '{$quo['salespn']}', '{$quo['odate']}', '{$quo['delchrg']}', '{$quo['subtot']}', '{$quo['vat']}' , '{$quo['total']}', '{$quo['total']}', '{$quo['comm']}', 'n', 'y', '" . PRD_DB . "', '" . USER_DIV . "','{$rounding}', '{$quo['delvat']}')";
    $rslt = db_exec($sql) or errDie("Unable to insert invoice to Cubit.", SELF);
    # get next ordnum
    $invid = lastinvid();
    # get selected stock in this quote
    db_connect();
    $sql = "SELECT * FROM pos_quote_items  WHERE quoid = '{$quoid}' AND div = '" . USER_DIV . "'";
    $stkdRslt = db_exec($sql);
    while ($stkd = pg_fetch_array($stkdRslt)) {
        # insert invoice items
        $stkd['vatcode'] += 0;
        $stkd['account'] += 0;
        $sql = "INSERT INTO pinv_items(invid, whid, stkid, qty, unitcost, amt, disc, discp, div,vatcode,description,account) VALUES('{$invid}', '{$stkd['whid']}', '{$stkd['stkid']}', '{$stkd['qty']}', '{$stkd['unitcost']}', '{$stkd['amt']}', '{$stkd['disc']}', '{$stkd['discp']}', '" . USER_DIV . "','{$stkd['vatcode']}','{$stkd['description']}','{$stkd['account']}')";
        $rslt = db_exec($sql) or errDie("Unable to insert invoice items to Cubit.", SELF);
        # update stock(alloc + qty)
        $sql = "UPDATE stock SET alloc = (alloc + '{$stkd['qty']}') WHERE stkid = '{$stkd['stkid']}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update stock to Cubit.", SELF);
    }
    db_connect();
    # set to accepted
    $sql = "UPDATE pos_quotes SET accepted = 'y' WHERE quoid = '{$quoid}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to update quotes in Cubit.", SELF);
    /* Remove access data
    		$sql = "DELETE FROM pos_quotes WHERE quoid = '$quoid' AND div = '".USER_DIV."'";
    		$rslt = db_exec($sql) or errDie("Unable to update quotes in Cubit.",SELF);
    
    		$sql = "DELETE FROM pos_quote_items WHERE quoid = '$quoid' AND div = '".USER_DIV."'";
    		$rslt = db_exec($sql) or errDie("Unable to update quotes in Cubit.",SELF);
    		*/
    /* - End Copying - */
    pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
    #redirect to pos invoice screen ...
    header("Location: pos-invoice-new.php?invid={$invid}&cont=1");
    // Final Laytout
    $write = "\n\t\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t\t<tr>\n\t\t\t\t\t\t<th>Quote accepted</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>Quote for customer <b>{$quo['cusname']}</b> has been accepted</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='pos-quote-view.php'>View Pos Quotes</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 cancel()
{
    extract($_REQUEST);
    pglib_transaction("BEGIN");
    if (isset($rem) && is_array($rem)) {
        foreach ($rem as $invid) {
            db_conn("cubit");
            $sql = "DELETE FROM pinvoices WHERE invid='{$invid}'";
            $pinvRslt = db_exec($sql) or errDie("Unable to remove invoice from Cubit.");
            #get any allocated serial numbers and remove items ... AND re-allocate stock
            $get_sers = "SELECT ss,serno,stkid,qty FROM pinv_items WHERE invid = '{$invid}'";
            $run_sers = db_exec($get_sers) or errDie("Unable to get invoice items serial numbers");
            if (pg_numrows($run_sers) < 1) {
                #no items ?
            } else {
                while ($parr = pg_fetch_array($run_sers)) {
                    if (strlen($parr['ss']) > 0) {
                        $me = $parr['ss'];
                    } else {
                        $me = $parr['serno'];
                    }
                    #determine which table to connect to and update it
                    switch (substr($me, strlen($me) - 1, 1)) {
                        case "0":
                            $tab = "ss0";
                            break;
                        case "1":
                            $tab = "ss1";
                            break;
                        case "2":
                            $tab = "ss2";
                            break;
                        case "3":
                            $tab = "ss3";
                            break;
                        case "4":
                            $tab = "ss4";
                            break;
                        case "5":
                            $tab = "ss5";
                            break;
                        case "6":
                            $tab = "ss6";
                            break;
                        case "7":
                            $tab = "ss7";
                            break;
                        case "8":
                            $tab = "ss8";
                            break;
                        case "9":
                            $tab = "ss9";
                            break;
                        default:
                            return order($_POST, "The code you selected is invalid");
                    }
                    $upd = "UPDATE {$tab} SET active = 'yes' WHERE code = '{$parr['ss']}' OR code = '{$parr['serno']}'";
                    $run_upd = db_exec($upd) or errDie("Unable to update stock serial numbers");
                    #look 4 this stock item
                    $get_stock = "SELECT * FROM stock WHERE stkid = '{$parr['stkid']}' LIMIT 1";
                    $run_stock = db_exec($get_stock) or errDie("Unable to get stock information.");
                    if (pg_numrows($run_stock) < 1) {
                        #cant find stock item ???
                    } else {
                        $min_alloc = $parr['qty'] + 0;
                        $starr = pg_fetch_array($run_stock);
                        #all set ... re-allocate stock
                        $update_sql = "UPDATE stock SET alloc = alloc - '{$min_alloc}' WHERE stkid = '{$starr['stkid']}'";
                        $update_run = db_exec($update_sql) or errDie("Unable to update allocated stock information.");
                    }
                }
            }
            #now remove the items
            $rem_items = "DELETE FROM pinv_items WHERE invid = '{$invid}'";
            $run_rem = db_exec($rem_items) or errDie("Unable to remove invoice items");
        }
    }
    return printInv();
}
function printSord($_POST)
{
    extract($_POST);
    #nothing to remove ? set var anyway ...
    if (!isset($cancorderid)) {
        $cancorderid = array();
    }
    #get the entries to remove here ...
    foreach ($cancorderid as $each) {
        pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
        # Get Sales Order info
        db_connect();
        $sql = "SELECT * FROM corders WHERE sordid = '{$each}' AND accepted != 'c' AND div = '" . USER_DIV . "'";
        $sordRslt = db_exec($sql) or errDie("Unable to get Sales Order information");
        if (pg_numrows($sordRslt) < 1) {
            return "<li class='err'>Sales Order Not Found</li>";
        }
        $sord = pg_fetch_array($sordRslt);
        # todays date (sql formatted)
        $date = date("Y-m-d");
        # get selected stock in this Sales Order
        db_connect();
        $sql = "SELECT * FROM corders_items  WHERE sordid = '{$each}' AND div = '" . USER_DIV . "'";
        $stkdRslt = db_exec($sql);
        while ($stkd = pg_fetch_array($stkdRslt)) {
            # update stock(alloc - qty)
            $sql = "UPDATE stock SET alloc = (alloc - '{$stkd['qty']}') WHERE stkid = '{$stkd['stkid']}' AND div = '" . USER_DIV . "'";
            $rslt = db_exec($sql) or errDie("Unable to update stock to Cubit.", SELF);
        }
        # remove the Sales Order
        $sql = "DELETE FROM corders WHERE sordid = '{$each}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to remove Sales Order from Cubit.", SELF);
        #record (sordid, username, date)
        $sql = "INSERT INTO cancelled_cord(sordid, deptid, username, date, deptname, div) VALUES('{$each}', '{$sord['deptid']}', '" . USER_NAME . "', '{$date}','{$sord['deptname']}', '" . USER_DIV . "')";
        $rslt = db_exec($sql) or errDie("Unable to insert Sales Order record to Cubit.", SELF);
        /* - End Copying - */
        pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
    }
    #select all clicked gets set here ...
    if (isset($all)) {
        $ch = "checked";
    } else {
        $ch = "";
    }
    # Set up table to display in
    $printSord = "\n\t\t\t\t<h3>View Consignment Orders</h3>\n\t\t\t\t<form action='" . SELF . "' method='POST'>\n\t\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t\t<tr>\n\t\t\t\t\t\t<th>Department</th>\n\t\t\t\t\t\t<th>Sales Person</th>\n\t\t\t\t\t\t<th>Consignment Order No.</th>\n\t\t\t\t\t\t<th>Date</th>\n\t\t\t\t\t\t<th>Customer Name</th>\n\t\t\t\t\t\t<th>Order No</th>\n\t\t\t\t\t\t<th>Grand Total</th>\n\t\t\t\t\t\t<th colspan='5'>Options</th>\n\t\t\t\t\t\t<th>Remove</th>\n\t\t\t\t\t</tr>";
    # connect to database
    db_connect();
    # Query server
    $i = 0;
    $sql = "SELECT * FROM corders WHERE accepted != 'c' AND done = 'y' AND div = '" . USER_DIV . "' ORDER BY sordid DESC";
    $sordRslt = db_exec($sql) or errDie("Unable to retrieve Sales Orders from database.");
    if (pg_numrows($sordRslt) < 1) {
        return "\n\t\t\t\t\t<li class='err'>No previous Consignment Orders.</li>\n\t\t\t\t\t<p>\n\t\t\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t\t\t<tr><td><br></td></tr>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<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 align='center'><a href='corder-new.php'>New Consignment Order</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 align='center'><a href='main.php'>Main Menu</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t</table>";
    } else {
        while ($sord = pg_fetch_array($sordRslt)) {
            # format date
            $sord['odate'] = explode("-", $sord['odate']);
            $sord['odate'] = $sord['odate'][2] . "-" . $sord['odate'][1] . "-" . $sord['odate'][0];
            $printSord .= "\n\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t<td>{$sord['deptname']}</td>\n\t\t\t\t\t\t\t\t<td>{$sord['salespn']}</td>\n\t\t\t\t\t\t\t\t<td>{$sord['sordid']}</td>\n\t\t\t\t\t\t\t\t<td align='center'>{$sord['odate']}</td>\n\t\t\t\t\t\t\t\t<td>{$sord['cusname']} {$sord['surname']}</td>\n\t\t\t\t\t\t\t\t<td align='right'>{$sord['ordno']}</td>\n\t\t\t\t\t\t\t\t<td>" . CUR . " {$sord['total']}</td>\n\t\t\t\t\t\t\t\t<td><a href='corder-details.php?sordid={$sord['sordid']}'>Details</a></td>\n\t\t\t\t\t\t\t\t<td><a href='corder-new.php?sordid={$sord['sordid']}&cont=1'>Edit</a></td>\n\t\t\t\t\t\t\t\t<td><a href='corder-cancel.php?sordid={$sord['sordid']}'>Cancel</a></td>\n\t\t\t\t\t\t\t\t<td><a target='_blank' href='corder-print.php?sordid={$sord['sordid']}'>Print</a></td>\n\t\t\t\t\t\t\t\t<td><a href='corder-accept.php?sordid={$sord['sordid']}'>Invoice</a></td>\n\t\t\t\t\t\t\t\t<td><input type='checkbox' name='cancorderid[]' value='{$sord['sordid']}' {$ch}></td>\n\t\t\t\t\t\t\t</tr>";
            $i++;
        }
    }
    // Layout
    $printSord .= "\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<td colspan='9'></td>\n\t\t\t\t\t\t\t<td colspan='2'><input type='submit' name='all' value='Select All'></td>\n\t\t\t\t\t\t\t<td colspan='2'><input type='submit' value='Cancel Selected'></td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t</table>\n\t\t\t\t\t</form>\n\t\t\t\t\t<p>\n\t\t\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t\t\t<tr><td><br></td></tr>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<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 align='center'><a href='corder-new.php'>New Consignment Order</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 align='center'><a href='main.php'>Main Menu</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t</table>";
    return $printSord;
}
function write($_POST)
{
    # Get vars
    foreach ($_POST as $key => $value) {
        ${$key} = $value;
    }
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($quoid, "num", 1, 20, "Invalid Quote number.");
    $v->isOk($cusnum, "num", 1, 20, "Invalid Customer number.");
    $v->isOk($cordno, "string", 0, 20, "Invalid Customer order number.");
    # display errors, if any
    $err = "";
    if ($v->isError()) {
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $err .= "<li class=err>" . $e["msg"];
        }
        return $err;
    }
    # Get quote info
    db_connect();
    $sql = "SELECT * FROM pos_quotes WHERE quoid = '{$quoid}' AND div = '" . USER_DIV . "'";
    $quoRslt = db_exec($sql) or errDie("Unable to get quote information");
    if (pg_numrows($quoRslt) < 1) {
        return "<li class=err>Quote Not Found</li>";
    }
    $quo = pg_fetch_array($quoRslt);
    # Get Customer info
    db_connect();
    $sql = "SELECT * FROM customers WHERE cusnum = '{$cusnum}' AND div = '" . USER_DIV . "'";
    $cusRslt = db_exec($sql) or errDie("Unable to get customer information");
    if (pg_numrows($cusRslt) < 1) {
        return "<i class=err>Customer Not Found</i>";
    }
    $cus = pg_fetch_array($cusRslt);
    /* - Start Copying - */
    pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
    db_connect();
    # Insert invoice to DB
    $sql = "INSERT INTO pinvoices(deptid, cusnum, deptname, cusacc, cusname, surname, cusaddr, cusvatno, cordno, ordno, chrgvat, terms, traddisc, salespn, odate, delchrg, subtot, vat, total, balance, comm, printed, done, prd, div)";
    $sql .= " VALUES('{$quo['deptid']}', '{$cus['cusnum']}', '{$quo['deptname']}', '{$cus['accno']}', '{$cus['cusname']}', '{$cus['surname']}', '{$cus['addr1']}', '{$cus['vatnum']}', '{$cordno}', '{$quo['ordno']}', '{$quo['chrgvat']}', '{$quo['terms']}', '{$quo['traddisc']}', '{$quo['salespn']}', '{$quo['odate']}', '{$quo['delchrg']}', '{$quo['subtot']}', '{$quo['vat']}' , '{$quo['total']}', '{$quo['total']}', '{$quo['comm']}', 'n', 'y', '" . PRD_DB . "', '" . USER_DIV . "')";
    $rslt = db_exec($sql) or errDie("Unable to insert invoice to Cubit.", SELF);
    # get next ordnum
    $invid = lastinvid();
    # get selected stock in this quote
    db_connect();
    $sql = "SELECT * FROM pos_quote_items  WHERE quoid = '{$quoid}' AND div = '" . USER_DIV . "'";
    $stkdRslt = db_exec($sql);
    /*
    		while($stkd = pg_fetch_array($stkdRslt)){
    			# Insert one by one per quantity
    			if(ext_isSerial("stock", "stkid", $stkd['stkid'])){
    				$stkd['amt'] = sprint($stkd['amt']/$stkd['qty']);
    
    				for($i = 0; $i < $stkd['qty']; $i++){
    					# insert invoice items
    					$sql = "INSERT INTO inv_items(invid, whid, stkid, qty, unitcost, amt, disc, discp, div) VALUES('$invid', '$stkd[whid]', '$stkd[stkid]', '1', '$stkd[unitcost]', '$stkd[amt]', '$stkd[disc]', '$stkd[discp]', '".USER_DIV."')";
    					$rslt = db_exec($sql) or errDie("Unable to insert invoice items to Cubit.",SELF);
    				}
    			}else{
    				# insert invoice items
    				$sql = "INSERT INTO inv_items(invid, whid, stkid, qty, unitcost, amt, disc, discp, div) VALUES('$invid', '$stkd[whid]', '$stkd[stkid]', '$stkd[qty]', '$stkd[unitcost]', '$stkd[amt]', '$stkd[disc]', '$stkd[discp]', '".USER_DIV."')";
    				$rslt = db_exec($sql) or errDie("Unable to insert invoice items to Cubit.",SELF);
    			}
    
    			# update stock(alloc + qty)
    			$sql = "UPDATE stock SET alloc = (alloc + '$stkd[qty]') WHERE stkid = '$stkd[stkid]' AND div = '".USER_DIV."'";
    			$rslt = db_exec($sql) or errDie("Unable to update stock to Cubit.",SELF);
    		}
    
    
    		# Get selected stock in this quote
    		db_connect();
    
    		# Remove access data
    		$sql = "DELETE FROM pos_quotes WHERE quoid = '$quoid' AND div = '".USER_DIV."'";
    		$rslt = db_exec($sql) or errDie("Unable to update quotes in Cubit.",SELF);
    
    		$sql = "DELETE FROM pos_quote_items WHERE quoid = '$quoid' AND div = '".USER_DIV."'";
    		$rslt = db_exec($sql) or errDie("Unable to update quotes in Cubit.",SELF);
    
    /* - End Copying - */
    pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
    // Final Laytout
    $write = "\n\t<table border=0 cellpadding='" . TMPL_tblCellPadding . "' cellspacing='" . TMPL_tblCellSpacing . "'>\n\t\t<tr><th>Quote accepted</th></tr>\n\t\t<tr class='bg-even'><td>Quote for customer <b>{$cus['cusname']} {$cus['surname']}</b> has been accepted</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='pos-quote-view.php'>View Pos Quotes</a></td></tr>\n\t\t<script>document.write(getQuicklinkSpecial());</script>\n\t</table>";
    return $write;
}
예제 #29
0
function order($_POST, $errors = "")
{
    $Out = "";
    # get vars
    foreach ($_POST as $key => $value) {
        ${$key} = $value;
    }
    db_conn("cubit");
    $date = date("Y-m-d");
    pglib_transaction("begin");
    $cdate = date("D, d M Y");
    $datemade = date("Y-m-d");
    $timemade = date("H:i");
    $op = USER_NAME;
    if (!isset($con)) {
        $con = '';
    }
    if (!isset($name)) {
        $name = '';
    }
    if (!isset($notes)) {
        $notes = '';
    }
    if (!isset($comp)) {
        $comp = '';
    }
    $Pals = "";
    $Sl = "SELECT * FROM todos WHERE com='No' and op='{$op}' ORDER BY datemade DESC,timemade DESC";
    $Rs = db_exec($Sl) or errDie("Unable to view clients");
    $numrow = pg_numrows($Rs);
    if (pg_numrows($Rs) < 1) {
        $Trips = "";
    } else {
        $i = 0;
        while ($Tp = pg_fetch_array($Rs)) {
            $i++;
            $Tpdes = substr($Tp['timemade'], 0, 2) . ":" . substr($Tp['timemade'], 2, 2);
            $Pals .= "<tr class='" . bg_class() . "'><td>{$Tp['datemade']}</td><td>{$Tpdes}</td><td>{$Tp['des']}</td><td><input type=checkbox name=done[{$Tp['id']}] OnClick='javascript:document.form.submit();'></td></tr>";
        }
    }
    pglib_transaction("commit");
    $account_dets = "<form action='" . SELF . "' method=post name=form>\r\n\t<input type=hidden name=key value=account_info>\r\n\t<table border=0 cellpadding='" . TMPL_tblCellPadding . "' cellspacing='" . TMPL_tblCellSpacing . "'>\r\n\t<tr class='bg-even'><th colspan=3 align=left><h3>TO DO LIST ({$numrow})</h3></th></tr>\r\n\t <tr class='bg-even'><td width='20%'>CURRENT DATE</td><td>{$cdate}</td></tr>\r\n\t</table>\r\n\r\n\t<table border=0 cellpadding='" . TMPL_tblCellPadding . "' cellspacing='" . TMPL_tblCellSpacing . "'>\r\n\t <tr><th>DATE</th><th>TIME</th><th>DESCRIPTION</th><th>DONE</th></tr>\r\n\t <tr class='bg-odd'><td><input type=hidden name=datemade value='{$datemade}'>{$datemade}</td><td><input type=hidden name=timemade value='{$timemade}'>{$timemade}</td><td><input type=text size=20 name=des value=''></td><td> &nbsp; </td></tr>\r\n\r\n\t {$Pals}\r\n\r\n\t <tr><td valign=center><input type=submit value='Update >>>'></td></tr>\r\n\t</table>\r\n\t</form>\r\n\t<table cellpadding='" . TMPL_tblCellPadding . "' cellspacing='" . TMPL_tblCellSpacing . "' width=30%>\r\n\t <tr><td><br><br></tr>\r\n\t <tr><th>Quick Links</th></tr>\r\n\t <tr class='bg-odd'><td><a href='index_die.php'>Diary</td>\r\n\t <tr class='bg-odd'><td><a href='main.php'>Main Menu</td>\r\n\t </tr>\r\n\t</table>\r\n\r\n\t<script>\r\n\t\tsetOnload\r\n\t</script>";
    return $account_dets;
}
function write($_POST)
{
    # Get vars
    extract($_POST);
    if (!isset($cusnum)) {
        return details($_POST, "<li class='err'>Please select a customer.</li>");
    }
    # validate input
    require_lib("validate");
    $v = new validate();
    if (isset($cusnum)) {
        $v->isOk($cusnum, "num", 1, 20, "Invalid Customer, Please select a customer.");
    }
    $v->isOk($invid, "num", 1, 20, "Invalid Invoice Number.");
    if (isset($cordno)) {
        $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, 255, "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($rinv_day, "num", 1, 2, "Invalid Invoice Date day.");
    $v->isOk($rinv_month, "num", 1, 2, "Invalid Invoice Date month.");
    $v->isOk($rinv_year, "num", 1, 5, "Invalid Invoice Date year.");
    $odate = $rinv_year . "-" . $rinv_month . "-" . $rinv_day;
    if (!checkdate($rinv_month, $rinv_day, $rinv_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)) {
        if (!ext_isUnique(ext_remBlnk($sernos))) {
            $v->isOk($error, "num", 0, 0, "Error : Serial Numbers must be unique per line item.");
        }
    }
    # 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 <= 0) {
                $v->isOk($qty, "num", 0, 0, "Error : Item Quantity must be more than zero. 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 rec_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['chrgvat'] = $chrgvat;
    # 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 recinv_items  WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
    $stktRslt = db_exec($sql);
    # remove old items
    $sql = "DELETE FROM recinv_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) {
            if (isset($remprod) && in_array($keys, $remprod)) {
            } 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 recinv_items (\n\t\t\t\t\t\t\tinvid, whid, stkid, qty, unitcost, \n\t\t\t\t\t\t\tamt, disc, discp,  div, vatcode, \n\t\t\t\t\t\t\tdescription, account\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]}', \n\t\t\t\t\t\t\t'{$amt[$keys]}', '{$disc[$keys]}', '{$discp[$keys]}', '" . USER_DIV . "', '{$vatcodes[$keys]}', \n\t\t\t\t\t\t\t'{$descriptions[$keys]}', '{$accounts[$keys]}'\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";
                }
                $wtd = $whids[$keys];
                if (!isset($sernos[$keys])) {
                    $sernos[$keys] = "";
                }
                # insert invoice items
                $sql = "\n\t\t\t\t\t\tINSERT INTO recinv_items (\n\t\t\t\t\t\t\tinvid, whid, stkid, qty, unitcost, \n\t\t\t\t\t\t\tamt, disc, discp, serno, div, \n\t\t\t\t\t\t\tvatcode\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]}', \n\t\t\t\t\t\t\t'{$amt[$keys]}', '{$disc[$keys]}', '{$discp[$keys]}', '{$sernos[$keys]}', '" . USER_DIV . "', \n\t\t\t\t\t\t\t'{$vatcodes[$keys]}'\n\t\t\t\t\t\t)";
                $rslt = db_exec($sql) or errDie("Unable to insert invoice items to Cubit.", SELF);
            }
            # everything is set place done button
            $_POST["done"] = " | <input name='doneBtn' type='submit' value='Done'>";
        }
    } 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 = $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 = $vatamount;
        $SUBTOT = sprint($sub);
        $TOTAL = sprint($subtotal);
        $delexvat = sprint($delchrg);
        $traddiscmt = sprint($traddiscmt);
    } else {
        $subtotal = sprint($sub + $delchrg);
        $traddiscmt = sprint($subtotal * $traddisc / 100);
        $subtotal = sprint($subtotal - $traddiscmt);
        $VAT = sprint(0);
        $SUBTOT = $sub;
        $TOTAL = $subtotal;
        $delexvat = sprint($delchrg);
    }
    /* --- ----------- Clac --------------------- */
    ##----------------------END----------------------
    db_conn('cubit');
    $Sl = "SELECT * FROM costcenters";
    $Ri = db_exec($Sl);
    $i = 0;
    $Sl = "DELETE FROM invc WHERE inv='{$invid}'";
    $Rl = db_exec($Sl);
    while ($data = pg_fetch_array($Ri)) {
        if ($ct[$data['ccid']] > 0) {
            $Sl = "INSERT INTO invc (cid,inv,amount) VALUES ('{$data['ccid']}','{$invid}','" . $ct[$data['ccid']] . "')";
            $Rl = db_exec($Sl);
        }
        $i++;
    }
    /* --- ----------- Clac ---------------------
    
    		# 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;
    
    /* --- ----------- Clac --------------------- */
    # insert invoice to DB
    $sql = "\n\t\t\tUPDATE rec_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}' \n\t\t\tWHERE invid = '{$invid}'";
    $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
    # commit updating
    pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
    if (strlen($bar) > 0) {
        $Sl = "SELECT * FROM possets WHERE div = '" . USER_DIV . "'";
        $Rs = db_exec($Sl) or errDie("Unable to add supplier to the system.", SELF);
        if (pg_numrows($Rs) < 1) {
            return details($_POST, "<a href='pos-set.php'>Please set the point of sale setting by clicking here.</a>");
        }
        $Dets = pg_fetch_array($Rs);
        if ($Dets['opt'] == "No") {
            switch (substr($bar, strlen($bar) - 1, 1)) {
                case "0":
                    $tab = "ss0";
                    break;
                case "1":
                    $tab = "ss1";
                    break;
                case "2":
                    $tab = "ss2";
                    break;
                case "3":
                    $tab = "ss3";
                    break;
                case "4":
                    $tab = "ss4";
                    break;
                case "5":
                    $tab = "ss5";
                    break;
                case "6":
                    $tab = "ss6";
                    break;
                case "7":
                    $tab = "ss7";
                    break;
                case "8":
                    $tab = "ss8";
                    break;
                case "9":
                    $tab = "ss9";
                    break;
                default:
                    return details($_POST, "The code you selected is invalid");
            }
            db_conn('cubit');
            pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
            $stid = barext_dbget($tab, 'code', $bar, 'stock');
            if (!($stid > 0)) {
                return details($_POST, "The bar code you selected is not in the system or is not available.");
            }
            $Sl = "SELECT * FROM stock WHERE stkid = '{$stid}' AND div = '" . USER_DIV . "'";
            $Rs = db_exec($Sl);
            $s = pg_fetch_array($Rs);
            # put scanned-in product into invoice db
            $sql = "\n\t\t\t\tINSERT INTO recinv_items (\n\t\t\t\t\tinvid, whid, stkid, qty, unitcost, amt, disc, discp, ss, div\n\t\t\t\t) VALUES (\n\t\t\t\t\t'{$invid}', '{$s['whid']}', '{$stid}', '1','{$s['selamt']}', '{$s['selamt']}', '0', '0', '{$bar}', '" . USER_DIV . "'\n\t\t\t\t)";
            $rslt = db_exec($sql) or errDie("Unable to insert invoice items to Cubit.", SELF);
            # update stock(alloc + qty)
            $sql = "UPDATE stock SET alloc = (alloc + '1') WHERE stkid = '{$stid}' AND div = '" . USER_DIV . "'";
            $rslt = db_exec($sql) or errDie("Unable to update stock to Cubit.", SELF);
            $Sl = "UPDATE " . $tab . " SET active = 'no' WHERE code = '{$bar}' AND div = '" . USER_DIV . "'";
            $Rs = db_exec($Sl);
            pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
        } else {
            db_conn('cubit');
            pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
            $stid = ext_dbget('stock', 'bar', $bar, 'stkid');
            if (!($stid > 0)) {
                return details($_POST, "The bar code you selected is not in the system or is not available.");
            }
            $Sl = "SELECT * FROM stock WHERE stkid = '{$stid}' AND div = '" . USER_DIV . "'";
            $Rs = db_exec($Sl);
            $s = pg_fetch_array($Rs);
            # put scanned-in product into invoice db
            $sql = "\n\t\t\t\tINSERT INTO recinv_items (\n\t\t\t\t\tinvid, whid, stkid, qty, unitcost, amt, disc, discp,ss, div\n\t\t\t\t) VALUES (\n\t\t\t\t\t'{$invid}', '{$s['whid']}', '{$stid}', '1', '{$s['selamt']}', '{$s['selamt']}', '0', '0', '{$bar}',  '" . USER_DIV . "'\n\t\t\t\t)";
            $rslt = db_exec($sql) or errDie("Unable to insert invoice items to Cubit.", SELF);
            # update stock(alloc + qty)
            $sql = "UPDATE stock SET alloc = (alloc + '1') WHERE stkid = '{$stid}' AND div = '" . USER_DIV . "'";
            $rslt = db_exec($sql) or errDie("Unable to update stock to Cubit.", SELF);
            pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
        }
    }
    /* --- Start button Listeners --- */
    if (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>Recurring 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>Recurring Invoice for customer <b>{$cust['cusname']} {$cust['surname']}</b> has been saved.</td>\n\t\t\t\t</tr>\n\t\t\t</table>" . mkQuickLinks(ql("rec-invoice-view.php", "View Recurring Invoices"), ql("customers-new.php", "New Customer"));
        return $write;
    } else {
        if (isset($wtd)) {
            $_POST['wtd'] = $wtd;
        }
        if (strlen($ria) > 0) {
            $_POST['ria'] = $ria;
        }
        return details($_POST);
    }
    /* --- End button Listeners --- */
}