コード例 #1
0
function write($_POST)
{
    # Get vars
    extract($_POST);
    if (!isset($cusnum)) {
        return details($_POST, "<li class='err'>Please select customer/department first.</li>");
    }
    $delvat += 0;
    db_conn('cubit');
    if (isset($printsales)) {
        $Sl = "SELECT * FROM settings WHERE constant='SALES'";
        $Ri = db_exec($Sl) or errDie("Unable to get settings.");
        if (pg_num_rows($Ri) < 1) {
            $Sl = "INSERT INTO settings (constant,value,div) VALUES ('SALES','Yes','" . USER_DIV . "')";
            $Ri = db_exec($Sl);
        } else {
            $Sl = "UPDATE settings SET value='Yes' WHERE constant='SALES' AND div='" . USER_DIV . "'";
            $Ri = db_exec($Sl);
        }
    } else {
        $Sl = "UPDATE settings SET value='No' WHERE constant='SALES' AND div='" . USER_DIV . "'";
        $Ri = db_exec($Sl);
    }
    if (isset($printdel)) {
        $Sl = "SELECT * FROM settings WHERE constant='Delivery Note'";
        $Ri = db_exec($Sl) or errDie("Unable to get settings.");
        if (pg_num_rows($Ri) < 1) {
            $Sl = "INSERT INTO settings (constant,value,div) VALUES ('Delivery Note','Yes','" . USER_DIV . "')";
            $Ri = db_exec($Sl);
        } else {
            $Sl = "UPDATE settings SET value='Yes' WHERE constant='Delivery Note' AND div='" . USER_DIV . "'";
            $Ri = db_exec($Sl);
        }
    } else {
        $Sl = "UPDATE settings SET value='No' WHERE constant='Delivery Note' AND div='" . USER_DIV . "'";
        $Ri = db_exec($Sl);
    }
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($cusnum, "num", 1, 20, "Invalid Customer, Please select a customer.");
    $v->isOk($branch, "num", 1, 20, "Invalid Branch, Please select a branch.");
    $v->isOk($invid, "num", 1, 20, "Invalid Invoice Number.");
    $v->isOk($cordno, "string", 0, 20, "Invalid Customer Order Number.");
    if (!isset($ria)) {
        $ria = "";
    }
    $v->isOk($ria, "string", 0, 20, "Invalid stock code(fist letters).");
    $v->isOk($comm, "string", 0, 1024, "Invalid Comments.");
    $v->isOk($docref, "string", 0, 20, "Invalid Document Reference No.");
    $v->isOk($ordno, "string", 0, 20, "Invalid sales order number.");
    $v->isOk($chrgvat, "string", 1, 4, "Invalid charge vat option.");
    $v->isOk($terms, "num", 1, 20, "Invalid terms.");
    $v->isOk($salespn, "string", 1, 255, "Invalid sales person.");
    $v->isOk($inv_date_day, "num", 1, 2, "Invalid Invoice Date day.");
    $v->isOk($inv_date_month, "num", 1, 2, "Invalid Invoice Date month.");
    $v->isOk($inv_date_year, "num", 1, 5, "Invalid Invoice Date year.");
    $odate = $inv_date_year . "-" . $inv_date_month . "-" . $inv_date_day;
    if (!checkdate($inv_date_month, $inv_date_day, $inv_date_year)) {
        $v->isOk($odate, "num", 1, 1, "Invalid Invoice Date.");
    }
    $v->isOk($traddisc, "float", 0, 20, "Invalid Trade Discount.");
    if ($traddisc > 100) {
        $v->isOk($traddisc, "float", 0, 0, "Error : Trade Discount cannot be more than 100 %.");
    }
    $v->isOk($delchrg, "float", 0, 20, "Invalid Delivery Charge.");
    $v->isOk($SUBTOT, "float", 0, 20, "Invalid Delivery Charge.");
    # used to generate errors
    $error = "asa@";
    # check if duplicate serial number selected, remove blanks
    if (isset($sernos)) {
        $tmp_sernos = $sernos;
        // only check for uniqueness among items not selected for removal
        foreach ($sernos as $k => $serno_val) {
            if (isset($remprod) && in_array($k, $remprod)) {
                unset($tmp_sernos[$k]);
            }
        }
        if (!ext_isUnique(ext_remBlnk($tmp_sernos))) {
            $v->isOk($error, "num", 0, 0, "Error : Serial Numbers must be unique per line item.");
        }
    }
    # check is serai no was selected
    if (isset($stkids)) {
        foreach ($stkids as $keys => $stkid) {
            # check if serial is selected
            if (ext_isSerial("stock", "stkid", $stkid) && !isset($sernos[$keys])) {
                $v->isOk($error, "num", 0, 0, "Error : Missing serial number for product number : <b>" . ($keys + 1) . "</b>");
            } elseif (ext_isSerial("stock", "stkid", $stkid) && !(strlen($sernos[$keys]) > 0)) {
                $v->isOk($error, "num", 0, 0, "Error : Missing serial number for product number : <b>" . ($keys + 1) . "</b>");
            }
        }
    }
    if (!isset($qtys) && isset($qtemp)) {
        $qtys[] = $qtemp;
    } elseif (isset($qtys) && isset($qtemp)) {
        //array_unshift ($qtys,$qtemp);
        $qtys[] = $qtemp;
    }
    # check quantities
    if (isset($qtys)) {
        foreach ($qtys as $keys => $qty) {
            $discp[$keys] += 0;
            $disc[$keys] += 0;
            $v->isOk($qty, "float", 1, 15, "Invalid Quantity for product number : <b>" . ($keys + 1) . "</b>");
            $v->isOk($disc[$keys], "float", 0, 20, "Invalid Discount for product number : <b>" . ($keys + 1) . "</b>.");
            if ($disc[$keys] > $unitcost[$keys]) {
                $v->isOk($disc[$keys], "float", 0, 0, "Error : Discount for product number : <b>" . ($keys + 1) . "</b> is more than the unitcost.");
            }
            $v->isOk($discp[$keys], "float", 0, 20, "Invalid Discount Percentage for product number : <b>" . ($keys + 1) . "</b>.");
            if ($discp[$keys] > 100) {
                $v->isOk($discp[$keys], "float", 0, 0, "Error : Discount for product number : <b>" . ($keys + 1) . "</b> is more than 100 %.");
            }
            $v->isOk($unitcost[$keys], "float", 1, 20, "Invalid Unit Price for product number : <b>" . ($keys + 1) . "</b>.");
            if ($qty < 1) {
                $v->isOk($qty, "num", 0, 0, "Error : Item Quantity must be at least one. Product number : <b>" . ($keys + 1) . "</b>");
            }
        }
    }
    # check whids
    if (isset($whids)) {
        foreach ($whids as $keys => $whid) {
            $v->isOk($whid, "num", 1, 10, "Invalid Store number, please enter all details.");
        }
    }
    # check stkids
    if (isset($stkids)) {
        foreach ($stkids as $keys => $stkid) {
            $v->isOk($stkid, "num", 1, 10, "Invalid Stock number, please enter all details.");
        }
    }
    # check amt
    if (isset($amt)) {
        foreach ($amt as $keys => $amount) {
            $v->isOk($amount, "float", 1, 20, "Invalid Amount, please enter all details.");
        }
    }
    # display errors, if any
    $err = "";
    if ($v->isError()) {
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $err .= "<li class='err'>" . $e["msg"] . "</li>";
        }
        return details($_POST, $err);
    }
    # Get invoice info
    db_connect();
    $sql = "SELECT * FROM invoices WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
    $invRslt = db_exec($sql) or errDie("Unable to get invoice information");
    if (pg_numrows($invRslt) < 1) {
        return "<li>- Invoice Not Found</li>";
    }
    $inv = pg_fetch_array($invRslt);
    $inv['traddisc'] = $traddisc;
    $inv['chrgvat'] = $chrgvat;
    if ($cusnum != $inv['cusnum'] or $branch != $inv['branch']) {
        $get_addr = "SELECT branch_descrip FROM customer_branches WHERE id = '{$branch}' AND div = '" . USER_DIV . "' LIMIT 1";
        $run_addr = db_exec($get_addr);
        if (pg_numrows($run_addr) < 1) {
            #no branch addres ? since we NEED to update the address, add the customer's here
            $get_cadd = "SELECT del_addr1 FROM customers WHERE cusnum = '{$cusnum}' LIMIT 1";
            $run_cadd = db_exec($get_cadd) or errDie("Unable to get customer delivery address");
            if (pg_numrows($run_cadd) < 1) {
                #no customer ??
                return details($_POST, "<li class='err'>Invalid customer selected.</li>");
            } else {
                $carr = pg_fetch_array($run_cadd);
                $update_addr = "UPDATE invoices SET del_addr  = '{$carr['del_addr1']}' WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
                $run_update = db_exec($update_addr) or errDie("Unable to update invoice information");
            }
        } else {
            $arr = pg_fetch_array($run_addr);
            $cust['addr1'] = $arr['branch_descrip'];
            if ($inv['del_addr'] != $arr['branch_descrip']) {
                $update_addr = "UPDATE invoices SET del_addr  = '{$arr['branch_descrip']}' WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
                $run_update = db_exec($update_addr) or errDie("Unable to update invoice information");
            }
        }
    }
    # check if invoice has been printed
    if ($inv['printed'] == "y") {
        $error = "<li class='err'> Error : Invoice number <b>{$invid}</b> has already been printed.</li>";
        $error .= "<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $error;
    }
    # Get selected customer info
    db_connect();
    $sql = "SELECT * FROM customers WHERE cusnum = '{$cusnum}' AND div = '" . USER_DIV . "'";
    $custRslt = db_exec($sql) or errDie("Unable to get customer information");
    if (pg_numrows($custRslt) < 1) {
        $sql = "SELECT * FROM inv_data WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
        $custRslt = db_exec($sql) or errDie("Unable to get customer information data");
        $cust = pg_fetch_array($custRslt);
        $cust['cusname'] = $cust['customer'];
        $cust['surname'] = "";
        $cust['addr1'] = "";
    } else {
        $cust = pg_fetch_array($custRslt);
        $inv['deptid'] = $cust['deptid'];
        # If customer was just selected, get the following
        if ($inv['cusnum'] == 0) {
            $traddisc = $cust['traddisc'];
            $terms = $cust['credterm'];
        }
    }
    # get department
    db_conn("exten");
    $sql = "SELECT * FROM departments WHERE deptid = '{$inv['deptid']}' AND div = '" . USER_DIV . "'";
    $deptRslt = db_exec($sql);
    if (pg_numrows($deptRslt) < 1) {
        $dept['deptname'] = "<i class='err'>Not Found</i>";
    } else {
        $dept = pg_fetch_array($deptRslt);
    }
    # fix those nasty zeros
    $traddisc += 0;
    $delchrg += 0;
    $vatamount = 0;
    $showvat = TRUE;
    # insert invoice to DB
    db_connect();
    # begin updating
    pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
    /* -- Start remove old items -- */
    # get selected stock in this invoice
    $sql = "SELECT * FROM inv_items  WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
    $stktRslt = db_exec($sql);
    while ($stkt = pg_fetch_array($stktRslt)) {
        # update stock(alloc + qty)
        $sql = "UPDATE stock SET alloc = (alloc - '{$stkt['qty']}')  WHERE stkid = '{$stkt['stkid']}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update stock to Cubit.", SELF);
        if (strlen($stkt['serno']) > 0) {
            ext_unresvSer($stkt['serno'], $stkt['stkid']);
        }
    }
    # remove old items
    $sql = "DELETE FROM inv_items WHERE invid='{$invid}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to update invoice items in Cubit.", SELF);
    /* -- End remove old items -- */
    $newvat = 0;
    $taxex = 0;
    if (isset($qtys)) {
        foreach ($qtys as $keys => $value) {
            /* set the serial ss field for serials selected from list */
            if ($sernos_ss[$keys] == "*_*_*CUBIT_SERIAL_SELECT_BOX*_*_*") {
                $sernos_ss[$keys] = $sernos[$keys];
            }
            if (isset($remprod) && in_array($keys, $remprod)) {
                $amt[$keys] = 0;
                if ($sernos[$keys] == $sernos_ss[$keys] && $sernos_ss[$keys] != "") {
                    $chr = substr($sernos[$keys], strlen($sernos[$keys]) - 1, 1);
                    $tab = "ss{$chr}";
                    /* mark barcoded item as unavailable */
                    $sql = "UPDATE " . $tab . " SET active='yes' WHERE code = '{$sernos[$keys]}' AND div = '" . USER_DIV . "'";
                    db_exec($sql);
                }
            } elseif (isset($accounts[$keys]) && $accounts[$keys] != 0) {
                $accounts[$keys] += 0;
                # Get selamt from selected stock
                db_conn('core');
                $Sl = "SELECT * FROM accounts WHERE accid='{$accounts[$keys]}'";
                $Ri = db_exec($Sl) or errDie("Unable to get account data.");
                $ad = pg_fetch_array($Ri);
                # Calculate amount
                $amt[$keys] = $qtys[$keys] * $unitcost[$keys];
                db_conn('cubit');
                $Sl = "SELECT * FROM vatcodes WHERE id='{$vatcodes[$keys]}'";
                $Ri = db_exec($Sl);
                if (pg_num_rows($Ri) < 1) {
                    return details($_POST, "<li class='err'>Please select the vatcode for all your items.</li>");
                }
                $vd = pg_fetch_array($Ri);
                if ($vd['zero'] == "Yes") {
                    $excluding = "y";
                } else {
                    $excluding = "";
                }
                if (TAX_VAT != $vd['vat_amount'] and $vd['vat_amount'] != "0.00") {
                    $showvat = FALSE;
                }
                $vr = vatcalc($amt[$keys], $inv['chrgvat'], $excluding, $inv['traddisc'], $vd['vat_amount']);
                $vrs = explode("|", $vr);
                $ivat = $vrs[0];
                $iamount = $vrs[1];
                $vatamount += $ivat;
                # Check Tax Excempt
                if ($vd['zero'] == "Yes") {
                    $taxex += $amt[$keys];
                    $exvat = "y";
                } else {
                    $exvat = "n";
                }
                //$newvat+=vatcalc($amt[$keys],$chrgvat,$exvat,$traddisc);
                $vatcodes[$keys] += 0;
                $accounts[$keys] += 0;
                $descriptions[$keys] = remval($descriptions[$keys]);
                $wtd = $whids[$keys];
                # insert invoice items
                $sql = "\n\t\t\t\t\t\tINSERT INTO inv_items (\n\t\t\t\t\t\t\tinvid, whid, stkid, qty, unitcost, amt, \n\t\t\t\t\t\t\tdisc, discp, serno, div, vatcode, description, \n\t\t\t\t\t\t\taccount, del\n\t\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t\t'{$invid}', '{$whids[$keys]}', '{$stkids[$keys]}', '{$qtys[$keys]}', '{$unitcost[$keys]}', '{$amt[$keys]}', \n\t\t\t\t\t\t\t'{$disc[$keys]}', '{$discp[$keys]}', '', '" . USER_DIV . "', '{$vatcodes[$keys]}', '{$descriptions[$keys]}', \n\t\t\t\t\t\t\t'{$accounts[$keys]}', '0'\n\t\t\t\t\t\t)";
                $rslt = db_exec($sql) or errDie("Unable to insert invoice items to Cubit.", SELF);
            } else {
                # Get selamt from selected stock
                $sql = "SELECT * FROM stock WHERE stkid = '{$stkids[$keys]}' AND div = '" . USER_DIV . "'";
                $stkRslt = db_exec($sql);
                $stk = pg_fetch_array($stkRslt);
                # Calculate the Discount discount
                if ($disc[$keys] < 1) {
                    if ($discp[$keys] > 0) {
                        $disc[$keys] = $discp[$keys] / 100 * $unitcost[$keys];
                    }
                } else {
                    $discp[$keys] = $disc[$keys] * 100 / $unitcost[$keys];
                }
                # Calculate amount
                $amt[$keys] = $qtys[$keys] * ($unitcost[$keys] - $disc[$keys]);
                $Sl = "SELECT * FROM vatcodes WHERE id='{$vatcodes[$keys]}'";
                $Ri = db_exec($Sl);
                if (pg_num_rows($Ri) < 1) {
                    return details($_POST, "<li class='err'>Please select the vatcode for all your items.</li>");
                }
                $vd = pg_fetch_array($Ri);
                if ($vd['zero'] == "Yes") {
                    $excluding = "y";
                } else {
                    $excluding = "";
                }
                if (TAX_VAT != $vd['vat_amount'] and $vd['vat_amount'] != "0.00") {
                    $showvat = FALSE;
                }
                $vr = vatcalc($amt[$keys], $inv['chrgvat'], $excluding, $inv['traddisc'], $vd['vat_amount']);
                $vrs = explode("|", $vr);
                $ivat = $vrs[0];
                $iamount = $vrs[1];
                $vatamount += $ivat;
                # Check Tax Excempt
                if ($stk['exvat'] == 'yes' || $vd['zero'] == "Yes") {
                    $taxex += $amt[$keys];
                    $exvat = "y";
                } else {
                    $exvat = "n";
                }
                //$newvat+=vatcalc($amt[$keys],$chrgvat,$exvat,$traddisc);
                $wtd = $whids[$keys];
                # insert invoice items
                $sql = "\n\t\t\t\t\t\tINSERT INTO inv_items (\n\t\t\t\t\t\t\tinvid, whid, stkid, qty, unitcost, amt, \n\t\t\t\t\t\t\tdisc, discp, ss, serno, div, \n\t\t\t\t\t\t\tvatcode, del\n\t\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t\t'{$invid}', '{$whids[$keys]}', '{$stkids[$keys]}', '{$qtys[$keys]}', '{$unitcost[$keys]}', '{$amt[$keys]}', \n\t\t\t\t\t\t\t'{$disc[$keys]}', '{$discp[$keys]}', '{$sernos_ss[$keys]}', '{$sernos[$keys]}', '" . USER_DIV . "', \n\t\t\t\t\t\t\t'{$vatcodes[$keys]}', '0'\n\t\t\t\t\t\t)";
                $rslt = db_exec($sql) or errDie("Unable to insert invoice items to Cubit.", SELF);
                if (strlen($sernos[$keys]) > 0) {
                    ext_resvSer($sernos[$keys], $stk['stkid']);
                }
                # update stock(alloc + qty)
                $sql = "UPDATE stock SET alloc = (alloc + '{$qtys[$keys]}') WHERE stkid = '{$stkids[$keys]}' AND div = '" . USER_DIV . "'";
                $rslt = db_exec($sql) or errDie("Unable to update stock to Cubit.", SELF);
            }
            # everything is set place done button
            $_POST["done"] = "\t| <input name='doneBtn' type='submit' value='Process'>";
            //if ($cust["email"] != "") {
            $_POST["done"] .= " | <input name='emailBtn' type='submit' value='Process and Email to Customer'>";
            //}
        }
    } else {
        $_POST["done"] = "";
    }
    //$newvat+=vatcalc($delchrg,$chrgvat,"no",$traddisc);
    db_conn('cubit');
    $Sl = "SELECT * FROM vatcodes WHERE id='{$delvat}'";
    $Ri = db_exec($Sl);
    $vd = pg_fetch_array($Ri);
    // 		if(pg_num_rows($Ri)>0) {
    // 			$taxex += $delchrg;
    // 		}
    if ($vd['zero'] == "Yes") {
        $excluding = "y";
    } else {
        $excluding = "";
    }
    if (TAX_VAT != $vd['vat_amount'] and $vd['vat_amount'] != "0.00") {
        $showvat = FALSE;
    }
    $_POST['showvat'] = $showvat;
    $vr = vatcalc($delchrg, $inv['chrgvat'], $excluding, $inv['traddisc'], $vd['vat_amount']);
    $vrs = explode("|", $vr);
    $ivat = $vrs[0];
    $iamount = $vrs[1];
    $vatamount += $ivat;
    /* --- ----------- Clac --------------------- */
    ##----------------------NEW----------------------
    $sub = 0.0;
    if (isset($amt)) {
        $sub = sprint(array_sum($amt));
    }
    $VATP = TAX_VAT;
    #get traddisc setting ...
    $traddisc_setting = getCSetting("SET_INV_TRADDISC");
    if ($chrgvat == "exc") {
        $taxex = sprint($taxex - $taxex * $traddisc / 100);
        $subtotal = sprint($sub + $delchrg);
        if ($traddisc_setting == "include") {
            $tradvar = $subtotal;
        } else {
            $tradvar = $sub;
        }
        $traddiscmt = sprint($tradvar * $traddisc / 100);
        $subtotal = sprint($subtotal - $traddiscmt);
        $VAT = $vatamount;
        $SUBTOT = $sub;
        $TOTAL = sprint($subtotal + $VAT);
        $delexvat = sprint($delchrg);
    } elseif ($chrgvat == "inc") {
        $ot = $taxex;
        $taxex = sprint($taxex - $taxex * $traddisc / 100);
        $subtotal = sprint($sub + $delchrg);
        if ($traddisc_setting == "include") {
            $tradvar = $subtotal;
        } else {
            $tradvar = $sub;
        }
        $traddiscmt = sprint($tradvar * $traddisc / 100);
        $subtotal = sprint($subtotal - $traddiscmt);
        $VAT = $vatamount;
        $SUBTOT = sprint($sub);
        $TOTAL = sprint($subtotal);
        $delexvat = sprint($delchrg);
        $traddiscmt = sprint($traddiscmt);
    } else {
        $subtotal = sprint($sub + $delchrg);
        if ($traddisc_setting == "include") {
            $tradvar = $subtotal;
        } else {
            $tradvar = $sub;
        }
        $traddiscmt = sprint($tradvar * $traddisc / 100);
        $subtotal = sprint($subtotal - $traddiscmt);
        $VAT = sprint(0);
        $SUBTOT = $sub;
        $TOTAL = $subtotal;
        $delexvat = sprint($delchrg);
    }
    /* --- ----------- Clac --------------------- */
    ##----------------------END----------------------
    /* --- ----------- Clac ---------------------
    ----------------------OLD----------------------
    		# calculate subtot
    		$SUBTOT = 0.00;
    		if(isset($amt))
    			$SUBTOT = array_sum($amt);
    
    		$SUBTOT -= $taxex;
    
    		# duplicate
    		$SUBTOTAL = $SUBTOT;
    
    		$VATP = TAX_VAT;
    		if($chrgvat == "exc"){
    			$SUBTOTAL = $SUBTOTAL;
    			$delexvat= ($delchrg);
    		}elseif($chrgvat == "inc"){
    			$SUBTOTAL = sprint(($SUBTOTAL * 100)/(100 + $VATP));
    			$delexvat = sprint(($delchrg * 100)/($VATP + 100));
    		}else{
    			$SUBTOTAL = ($SUBTOTAL);
    			$delexvat = ($delchrg);
    		}
    
    		$SUBTOT = $SUBTOTAL;
    		$EXVATTOT = $SUBTOT;
    		$EXVATTOT += $delexvat;
    
    		# Minus trade discount from taxex
    		if($traddisc > 0){
    			$traddiscmtt = (($traddisc/100) * $taxex);
    		}else{
    			$traddiscmtt = 0;
    		}
    		$taxext = ($taxex - $traddiscmtt);
    
    		if($traddisc > 0) {
    			$traddiscmt = ($EXVATTOT * ($traddisc/100));
    		}else{
    			$traddiscmt = 0;
    		}
    		$EXVATTOT -= $traddiscmt;
    		// $EXVATTOT -= $taxex;
    
    		$traddiscmt = sprint($traddiscmt  + $traddiscmtt);
    
    		if($chrgvat != "nov"){
    			$VAT = sprint($EXVATTOT * ($VATP/100));
    		}else{
    			$VAT = 0;
    		}
    
    		$TOTAL = sprint($EXVATTOT + $VAT + $taxext);
    		$SUBTOT += $taxex;
    */
    #override address
    if ($branch != 0) {
        $get_addr = "SELECT branch_descrip FROM customer_branches WHERE id = '{$branch}' AND div = '" . USER_DIV . "' LIMIT 1";
        $run_addr = db_exec($get_addr);
        if (pg_numrows($run_addr) < 1) {
            #address missing ... do nothing
        } else {
            $arr = pg_fetch_array($run_addr);
            $cust['addr1'] = $arr['branch_descrip'];
        }
    }
    // Delivery Date
    $deldate = "{$del_date_year}-{$del_date_month}-{$del_date_day}";
    /* --- ----------- Clac --------------------- */
    if (!isset($bankid)) {
        $bankid = cust_bank_id($cusnum);
    }
    # insert invoice to DB
    $sql = "\n\t\t\tUPDATE invoices \n\t\t\tSET delvat='{$delvat}', cusnum = '{$cusnum}', deptid = '{$dept['deptid']}', deptname = '{$dept['deptname']}', \n\t\t\t\tcusacc = '{$cust['accno']}', cusname = '{$cust['cusname']}', surname = '{$cust['surname']}', cusaddr = '{$cust['addr1']}', \n\t\t\t\tcusvatno = '{$cust['vatnum']}', cordno = '{$cordno}', ordno = '{$ordno}', docref = '{$docref}', \n\t\t\t\tchrgvat = '{$chrgvat}', terms = '{$terms}', salespn = '{$salespn}', odate = '{$odate}', traddisc = '{$traddisc}', \n\t\t\t\tdelchrg = '{$delchrg}', subtot = '{$SUBTOT}', vat = '{$VAT}', total = '{$TOTAL}', balance = '{$TOTAL}', \n\t\t\t\tcomm = '{$comm}', serd = 'y', discount='{$traddiscmt}', delivery='{$delexvat}', branch = '{$branch}', \n\t\t\t\tdeldate = '{$deldate}', bankid = '{$bankid}' \n\t\t\tWHERE invid = '{$invid}'";
    $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
    # remove old data
    $sql = "DELETE FROM inv_data WHERE invid='{$invid}'  AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to update invoice data in Cubit.", SELF);
    # pu in new data
    $sql = "INSERT INTO inv_data(invid, dept, customer, addr1, div) VALUES('{$invid}', '{$dept['deptname']}', '{$cust['cusname']} {$cust['surname']}', '{$cust['addr1']}', '" . USER_DIV . "')";
    $rslt = db_exec($sql) or errDie("Unable to insert invoice data to Cubit.", SELF);
    if (strlen($bar) > 0) {
        /* check if there a stock item with global barcode matching input barcode */
        $sql = "SELECT * FROM stock WHERE bar='{$bar}' AND div = '" . USER_DIV . "'";
        $barRslt = db_exec($sql);
        if (pg_num_rows($barRslt) <= 0) {
            /* fetch last character of barcode */
            $chr = substr($bar, strlen($bar) - 1, 1);
            /* invalid barcode */
            if (!is_numeric($chr)) {
                return details($_POST, "The code you selected is invalid");
            }
            /* which barcode table to scan for stock id */
            $tab = "ss{$chr}";
            $stid = barext_dbget($tab, 'code', $bar, 'stock');
            $stab = "serial{$chr}";
            $sstid = serext_dbget($stab, 'serno', $bar, 'stkid');
            /* non-existing barcode, check for serial number */
            if ($stid <= 0) {
                if ($sstid <= 0) {
                    return details($_POST, "<li class='err'>The serial number/bar code you selected is not in the system or is not available.</li>");
                }
                if (serext_dbnum($stab, 'serno', $bar, 'stkid') > 1) {
                    return details($_POST, "<li class='err'>Duplicate serial numbers found, please scan barcode or select stock item.</li>");
                }
                /* mark barcoded item as unavailable */
                $sql = "UPDATE " . $stab . " SET rsvd='y' WHERE serno='{$bar}'";
                db_exec($sql);
                $serno_bar = "{$bar}";
                $stid = $sstid;
            } else {
                if ($sstid > 0) {
                    return details($_POST, "<li class='err'>A serial and barcode with same value, please scan other value or select product manually.</li>");
                }
                /* mark barcoded item as unavailable */
                $sql = "UPDATE " . $tab . " SET active='no' WHERE code='{$bar}' AND div='" . USER_DIV . "'";
                db_exec($sql);
                $serno_bar = "{$bar}";
            }
            /* fetch stock row for selected item */
            $sql = "SELECT * FROM stock WHERE stkid = '{$stid}' AND div = '" . USER_DIV . "'";
            $barRslt = db_exec($sql);
        } else {
            $serno_bar = "";
        }
        $s = pg_fetch_array($barRslt);
        /* allocate stock item */
        $sql = "UPDATE stock SET alloc = (alloc + '1') WHERE stkid = '{$s['stkid']}' AND div = '" . USER_DIV . "'";
        db_exec($sql) or errDie("Unable to update stock to Cubit.", SELF);
        $sql = "\n\t\t\tINSERT INTO inv_items (\n\t\t\t\tinvid, whid, stkid, qty, unitcost, amt, disc, discp, ss, serno, \n\t\t\t\tdiv, vatcode\n\t\t\t) VALUES (\n\t\t\t\t'{$invid}', '{$s['whid']}', '{$s['stkid']}', '1','{$s['selamt']}', '{$s['selamt']}','0','0','{$bar}', '{$serno_bar}', \n\t\t\t\t'" . USER_DIV . "', (SELECT id FROM cubit.vatcodes LIMIT 1)\n\t\t\t)";
        db_exec($sql) or errDie("Unable to insert invoice items to Cubit.", SELF);
    }
    pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
    /* --- Start button Listeners --- */
    if (isset($doneBtn) || isset($emailBtn)) {
        # Check if stock was selected(yes = put done button)
        db_connect();
        $sql = "SELECT stkid FROM inv_items WHERE invid = '{$inv['invid']}' AND div = '" . USER_DIV . "'";
        $crslt = db_exec($sql);
        if (pg_numrows($crslt) < 1) {
            $error = "<li class='err'> Error : Invoice number has no items.";
            return details($_POST, $error);
        }
        # Insert quote to DB
        $sql = "UPDATE invoices SET done = 'y' WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update invoice status in Cubit.", SELF);
        $Sl = "SELECT * FROM settings WHERE constant='Delivery Note'";
        $Ri = db_exec($Sl) or errDie("Unable to get settings.");
        $data = pg_fetch_array($Ri);
        if (isset($emailBtn)) {
            $email = "email=true";
        } else {
            $email = "";
        }
        if ($data['value'] == "Yes") {
            //		move('cust-credit-stockinv.php');
            //move('cust-credit-stockinv-newsetting.php');
            $OUTPUT = "\n\t\t\t\t<script>\n\t\t\t\t\tnhprinter('invoice-delnote.php?invid={$invid}','Delivery Note');\n\t\t\t\t\tprinter('invoice-print.php?invid={$invid}&type=inv&salespn={$salespn}&{$email}');\n\t\t\t\t\tmove('settings/cust-credit-stockinv-newsetting.php');\n\t\t\t\t</script>";
        } else {
            //		move('cust-credit-stockinv.php');
            //move('cust-credit-stockinv-newsetting.php');
            $OUTPUT = "\n\t\t\t\t<script>\n\t\t\t\t\tprinter('invoice-print.php?invid={$invid}&type=inv&{$email}');\n\t\t\t\t\tmove('settings/cust-credit-stockinv-newsetting.php');\n\t\t\t\t</script>";
        }
        # Print the invoice
        require "template.php";
    } elseif (isset($saveBtn)) {
        // Final Laytout
        $write = "\n\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t<tr>\n\t\t\t\t\t<th>New Invoice Saved</th>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>Invoice for customer <b>{$cust['cusname']} {$cust['surname']}</b> has been saved. To view it go to 'View incomplete invoices'</td>\n\t\t\t\t</tr>\n\t\t\t</table>\n\t\t\t<p>\n\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t<tr>\n\t\t\t\t\t<th>Quick Links</th>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td><a href='invoice-view.php'>View Invoices</a></td>\n\t\t\t\t</tr>\n\t\t\t\t<script>document.write(getQuicklinkSpecial());</script>\n\t\t\t</table>";
        return $write;
    } else {
        if (isset($wtd)) {
            $_POST['wtd'] = $wtd;
        }
        if (strlen($ria) > 0) {
            $_POST['ria'] = $ria;
        }
        return details($_POST);
    }
    /* --- End button Listeners --- */
}
コード例 #2
0
function templatePdf($_POST)
{
    extract($_POST);
    global $set_mainFont;
    $pdf =& new Cezpdf();
    $pdf->selectFont($set_mainFont);
    // Validate
    require_lib("validate");
    $v = new Validate();
    foreach ($invids as $invid) {
        $v->isOk($invid, "num", 1, 20, "Invalid invoice number.");
    }
    // Any errors?
    if ($v->isError()) {
        $err = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $err .= "<li class=error>{$e['msg']}</li>";
        }
        $OUTPUT = $confirm;
        require "template.php";
    }
    $ai = 0;
    foreach ($invids as $invid) {
        if ($ai) {
            $pdf->ezNewPage();
        }
        ++$ai;
        // Invoice info
        db_conn("cubit");
        $sql = "SELECT * FROM nons_invoices WHERE invid='{$invid}' AND DIV='" . USER_DIV . "'";
        $invRslt = db_exec($sql) or errDie("Unable to retrieve invoice info.");
        if (pg_num_rows($invRslt) == 0) {
            return "<li class=err>Not found</li>";
        }
        $inv = pg_fetch_array($invRslt);
        // Only needs to be blank, we're manually adding text
        $heading = array(array(""));
        // Company info ----------------------------------------------------------
        db_conn("cubit");
        $sql = "SELECT * FROM compinfo WHERE div='" . USER_DIV . "'";
        $ciRslt = db_exec($sql) or errDie("Unable to retrieve company info from Cubit.");
        $comp = pg_fetch_array($ciRslt);
        $bnkData = qryBankAcct(cust_bank_id($inv["cusid"]));
        $compinfo = array();
        $compinfo[] = array($comp["addr1"], "{$comp['paddr1']}");
        $compinfo[] = array($comp["addr2"], "{$comp['paddr2']}");
        $compinfo[] = array($comp["addr3"], "{$comp['paddr3']}");
        $compinfo[] = array($comp["addr4"], "{$comp['postcode']}");
        $compinfo[] = array("<b>REG: </b>{$comp['regnum']}", "<b>{$bnkData['bankname']}</b>");
        $compinfo[] = array("<b>VAT REG: </b>{$comp['vatnum']}", "<b>Branch: </b>{$bnkData['branchname']}");
        $compinfo[] = array("<b>Tel:</b> {$comp['tel']}", "<b>Branch Code: </b>{$bnkData['branchcode']}");
        $compinfo[] = array("<b>Fax:</b> {$comp['fax']}", "<b>Acc Num: </b>{$bnkData['accnum']}");
        // Date ------------------------------------------------------------------
        $date = array(array("<b>Date</b>"), array($inv['odate']));
        // Document info ---------------------------------------------------------
        db_conn('cubit');
        $Sl = "SELECT * FROM settings WHERE constant='SALES'";
        $Ri = db_exec($Sl) or errDie("Unable to get settings.");
        $data = pg_fetch_array($Ri);
        if ($data['value'] == "Yes") {
            $sp = "<b>Sales Person: </b>{$inv['salespn']}";
        } else {
            $sp = "";
        }
        $docinfo = array(array("<b>Invoice No:</b> {$inv['invnum']}"), array("<b>Proforma Inv No:</b> {$inv['docref']}"), array("{$sp}"));
        // Customer info ---------------------------------------------------------
        if ($inv["cusid"] != 0) {
            db_conn("cubit");
            $sql = "SELECT * FROM customers WHERE cusnum='{$inv['cusid']}'";
            $cusRslt = db_exec($sql) or errDie("Unable to retrieve customer information from Cubit.");
            $cusData = pg_fetch_array($cusRslt);
        } else {
            $cusData["surname"] = $inv["cusname"];
            $cusData["addr1"] = $inv["cusaddr"];
            $cusData["paddr1"] = "";
            $cusData["accno"] = "";
        }
        $cusinfo = array(array("<b>{$cusData['surname']}</b>"));
        $cusaddr = explode("\n", $cusData['paddr1']);
        foreach ($cusaddr as $v) {
            $cusinfo[] = array(pdf_lstr($v, 40));
        }
        $cusinfo[] = array("<b>Account no: </b>{$cusData['accno']}");
        $cusdaddr = array(array("<b>Physical Address:</b>"));
        $cusaddr = explode("\n", $cusData['addr1']);
        foreach ($cusaddr as $v) {
            $cusdaddr[] = array(pdf_lstr($v, 40));
        }
        // Registration numbers --------------------------------------------------
        $regnos = array(array("<b>VAT No:</b>", "<b>Order No:</b>"), array("{$inv['cusvatno']}", "{$inv['cordno']}"));
        // Items display ---------------------------------------------------------
        $items = array();
        db_conn("cubit");
        $sql = "SELECT * FROM nons_inv_items WHERE invid='{$invid}' AND DIV='" . USER_DIV . "'";
        $stkdRslt = db_exec($sql);
        while ($stkd = pg_fetch_array($stkdRslt)) {
            // Check Tax Excempt
            db_conn("cubit");
            $sql = "SELECT zero FROM vatcodes WHERE id='{$stkd['vatex']}'";
            $zRslt = db_exec($sql) or errDie("Unable to retrieve vat code from Cubit.");
            $vatex = pg_fetch_result($zRslt, 0);
            if ($vatex == "Yes") {
                $ex = "#";
            } else {
                $ex = "";
            }
            $items[] = array("Description" => pdf_lstr($ex . $stkd['description'], 65), "Qty" => $stkd['qty'], "Unit Price" => CUR . $stkd['unitcost'], "Amount" => CUR . $stkd['amt']);
        }
        // Comment ---------------------------------------------------------------
        db_conn("cubit");
        $sql = "SELECT value FROM settings WHERE constant='DEFAULT_COMMENTS'";
        $commentRslt = db_exec($sql) or errDie("Unable to retrieve the default comment from Cubit.");
        $default_comment = pg_fetch_result($commentRslt, 0);
        $comment = array(array("<i>VAT Exempt Indicator: #</i>"), array(base64_decode($default_comment)));
        // Box to sign in --------------------------------------------------------
        $sign = array(array("<i>Thank you for your support</i>"), array(''), array("<b>Received in good order by:</b> ____________________"), array(''), array("                                      <b>Date:</b> ____________________"));
        // Totals ----------------------------------------------------------------
        $totals = array(array("1" => "<b>Subtotal:</b> ", "2" => CUR . "{$inv['subtot']}"), array("1" => "<b>VAT @ " . TAX_VAT . "%:</b> ", "2" => CUR . "{$inv['vat']}"), array("1" => "<b>Total Incl VAT:</b> ", "2" => CUR . "{$inv['total']}"));
        $totCols = array("1" => array("width" => 90), "2" => array("justification" => "right"));
        $ic = 0;
        while (++$ic * 20 < count($items)) {
        }
        // Draw the pages, determine by the amount of items how many pages
        // if items > 20 start a new page
        $items_print = array();
        for ($i = 0; $i < $ic; $i++) {
            if ($i) {
                $pdf->ezNewPage();
            }
            // Page number -------------------------------------------------------
            $pagenr = array(array("<b>Page number</b>"), array($i + 1));
            // Heading
            $heading_pos = drawTable(&$pdf, $heading, 0, 0, 520, 5);
            drawText(&$pdf, "<b>{$comp['compname']}</b>", 18, 0, $heading_pos['y'] / 2 + 6);
            drawText(&$pdf, "<b>Tax Invoice</b>", 18, $heading_pos['x'] - 120, $heading_pos['y'] / 2 + 9);
            $compinfo_pos = drawTable(&$pdf, $compinfo, 0, $heading_pos['y'], 320, 8);
            $date_pos = drawTable(&$pdf, $date, $compinfo_pos['x'], $heading_pos['y'], 100, 4);
            $pagenr_pos = drawTable(&$pdf, $pagenr, $date_pos['x'], $heading_pos['y'], 100, 4);
            $docinfo_pos = drawTable(&$pdf, $docinfo, $compinfo_pos['x'], $date_pos['y'], 200, 4);
            $cusinfo_pos = drawTable(&$pdf, $cusinfo, 0, $compinfo_pos['y'], 320, 10);
            $cusdaddr_pos = drawTable(&$pdf, $cusdaddr, $cusinfo_pos['x'], $compinfo_pos['y'], 200, 10);
            $regnos_pos = drawTable(&$pdf, $regnos, 0, $cusinfo_pos['y'], 520, 2);
            $items_start = $i * 20;
            if ($items_start >= count($items) - 20) {
                $items_end = count($items) - 1;
            } else {
                $items_end = ($i + 1) * 20;
            }
            $items_print = array();
            for ($j = $items_start; $j <= $items_end; $j++) {
                $items_print[$j] = $items[$j];
            }
            // Adjust the column widths
            $cols = array("Description" => array("width" => 310), "Qty" => array("width" => 50), "Unit Price" => array("width" => 80, "justification" => "right"), "Amount" => array("width" => 80, "justification" => "right"));
            $items_pos = drawTable(&$pdf, $items_print, 0, $regnos_pos['y'] + 2, 520, 20, $cols, 1);
            $comment_pos = drawTable(&$pdf, $comment, 0, $items_pos['y'], 520, 2);
            $sign_pos = drawTable(&$pdf, $sign, 0, $comment_pos['y'], 320, 5);
            $totals_pos = drawTable(&$pdf, $totals, $sign_pos['x'], $comment_pos['y'], 200, 5, $totCols);
        }
    }
    $pdf->ezStream();
}
コード例 #3
0
function run()
{
    extract($_REQUEST);
    pglib_transaction("BEGIN");
    // Retrieve outstanding rentals
    $sql = "\n\tSELECT id, user_id, username, order_num, subtotal, vat, total, discount,\n\t\tdelivery, customers.cusnum, surname, addr1, addr2, addr3, accno,\n\t\tvatnum, tel, discount_perc, timestamp, deposit\n\tFROM cubit.hire_trans\n\t\tLEFT JOIN cubit.customers ON hire_trans.cusnum=customers.cusnum\n\t\tLEFT JOIN cubit.users ON hire_trans.user_id=users.userid\n\tWHERE user_id='{$user_id}' AND done='y'";
    $rental_rslt = db_exec($sql) or errDie("Unable to retrieve rentals.");
    $hire_nums = array();
    while ($rental_data = pg_fetch_array($rental_rslt)) {
        $deptid = 2;
        $time = strtotime($rental_data["timestamp"]);
        $sql = "SELECT deptname FROM exten.departments WHERE deptid='{$deptid}'";
        $deptname_rslt = db_exec($sql) or errDie("Unable to retrieve department.");
        $deptname = pg_fetch_result($deptname_rslt, 0);
        // Create hire note
        $sql = "\n\t\tINSERT INTO hire.hire_invoices (deptid, cusnum, cordno, ordno,\n\t\t\tchrgvat, terms, salespn, odate, printed, comm, done, username,\n\t\t\tdeptname, cusacc, cusname, surname, cusaddr, cusordno, cusvatno,\n\t\t\tprd, invnum, div, prints, disc, discp, delchrg, subtot, traddisc,\n\t\t\tbalance, vat, total, discount, delivery, nbal, rdelchrg, serd,\n\t\t\tpcash, pcheque, pcc, rounding, pchange, delvat, pcredit, vatnum,\n\t\t\ttelno, systime, deposit_type, deposit_amt, custom_txt, collection,\n\t\t\tbranch_addr, timestamp, hire_invid, revision)\n\t\tVALUES ('{$deptid}', '{$rental_data['cusnum']}', '', '', 'inc', '0', '2',\n\t\t\t'" . date("Y-m-d", $time) . "', 'y', '', 'y', '{$rental_data['username']}',\n\t\t\t'{$deptname}', '{$rental_data['accno']}', '', '{$rental_data['surname']}',\n\t\t\t'{$rental_data['addr1']}', '{$rental_data['order_num']}',\n\t\t\t'{$rental_data['vatnum']}', '" . PRD_DB . "', '{$rental_data['id']}',\n\t\t\t'" . USER_DIV . "', '0', '{$rental_data['discount']}',\n\t\t\t'{$rental_data['discount_perc']}', '{$rental_data['delivery']}',\n\t\t\t'{$rental_data['subtotal']}', '{$rental_data['discount']}', '0.00',\n\t\t\t'{$rental_data['vat']}', '{$rental_data['total']}',\n\t\t\t'{$rental_data['discount']}', '{$rental_data['delivery']}', '0.00', '0.00',\n\t\t\t'', '100', '100', '100', '100', '100', '0', '0.00',\n\t\t\t'{$rental_data['vatnum']}', '{$rental_data['tel']}',\n\t\t\t'{$rental_data['timestamp']}', 'CSH', '{$rental_data['deposit']}', '',\n\t\t\t'Client Collect', '0', current_timestamp, '0', '0')";
        db_exec($sql) or errDie("Unable to create hire note.");
        $invid = pglib_lastid("hire.hire_invoices", "invid");
        $hire_nums[$rental_data["id"]] = $invid;
        // Do deposit transaction if required
        if ($rental_data["deposit"] > 0) {
            $cash_on_hand = qryAccountsNum("7200", "000");
            $cash_on_hand = $cash_on_hand["accid"];
            $cust_control = qryAccountsNum("6400", "000");
            $cust_control = $cust_control["accid"];
            $refnum = getRefnum();
            writetrans($cash_on_hand, $cust_control, date("Y-m-d", $time), $refnum, $rental_data["deposit"], "Cash Receipt for " . CUR . "{$rental_data['deposit']} from " . "{$rental_data['surname']} for Deposit on Hire Note {$rental_data['id']}");
            $sql = "\n\t\t\tINSERT INTO hire.cash (invid, cash)\n\t\t\tVALUES ('{$invid}', '{$rental_data['deposit']}')";
            db_exec($sql) or errDie("Unable to add cash to hire.");
            // Make ledger record
            custledger($rental_data["cusnum"], $cust_control, date("Y-m-d", $time), $invid, "Cash Receipt for " . CUR . "{$rental_data['deposit']} from " . "{$rental_data['surname']} for Deposit on Hire Note {$rental_data['id']}", $rental_data["deposit"], "c");
            custCT($rental_data["deposit"], $rental_data["cusnum"], date("Y-m-d", $time));
            // Turn the amount around to a negative
            $stmnt_amt = $rental_data["deposit"] - $rental_data["deposit"] * 2;
            // Record the payment on the statement
            $sql = "\n\t\t\tINSERT INTO cubit.stmnt(cusnum, invid, docref, amount, date, type,\n\t\t\t\tdiv)\n\t\t\tVALUES('{$rental_data['cusnum']}', '{$invid}', '{$rental_data['id']}',\n\t\t\t\t'{$stmnt_amt}', '" . date("Y-m-d", $time) . "',\n\t\t\t\t'Cash Receipt for " . CUR . "{$rental_data['deposit']} from " . "{$rental_data['surname']} for Deposit on Hire Note {$rental_data['id']}',\n\t\t\t\t'" . USER_DIV . "')";
            $stmntRslt = db_exec($sql) or errDie("Unable to add deposit to statement");
            // Update customer balance
            $sql = "\n\t\t\tUPDATE cubit.customers SET balance=balance-'{$rental_data['deposit']}'\n\t\t\tWHERE cusnum='{$rental_data['cusnum']}'";
            db_exec($sql) or errDie("Unable to update customer balance.");
            $sql = "\n\t\t\tUPDATE hire.hire_invoices SET deposit_amt='0'\n\t\t\tWHERE invid='{$invid}'";
            db_exec($sql) or errDie("Unable to retrieve hire invoices.");
        }
        // Retrieve items on this invoice
        $sql = "\n\t\tSELECT asset_id, basis, from_date, to_date, half_day, qty,\n\t\t\tweekends, total_days, total\n\t\tFROM cubit.hire_trans_items\n\t\tWHERE hire_id='{$rental_data['id']}'";
        $item_rslt = db_exec($sql) or errDie("Unable to retrieve items.");
        while ($item_data = pg_fetch_array($item_rslt)) {
            $unitcost = $item_data["total"] / $item_data["qty"];
            // Decide which basis to use
            $hours = 0;
            $weeks = 0;
            $days = 0;
            $months = 0;
            $total_days = 0;
            switch ($item_data["basis"]) {
                case "per_hour":
                    $hours = $item_data["total_days"];
                    break;
                case "per_day":
                    $days = $item_data["total_days"];
                    $total_days = $item_data["total_days"];
                    break;
                case "per_week":
                    $week = $item_data["total_days"];
                    break;
                case "per_month":
                    $months = $item_data["total_days"];
                    break;
            }
            // Convert booleans into something we can use
            $half_day = $item_data["half_day"] == "t" ? 1 : 0;
            $weekends = $item_data["weekends"] == "t" ? 1 : 0;
            $sql = "\n\t\t\tINSERT INTO hire.hire_invitems (invid, qty, amt, unitcost,\n\t\t\t\tfrom_date, to_date, asset_id, basis, hours, weeks, days,\n\t\t\t\tmonths, half_day, weekends, total_days)\n\t\t\tVALUES ('{$invid}', '{$item_data['qty']}', '{$item_data['total']}',\n\t\t\t\t'{$unitcost}', '{$item_data['from_date']}', '{$item_data['to_date']}',\n\t\t\t\t'{$item_data['asset_id']}', '{$item_data['basis']}', '{$hours}',\n\t\t\t\t'{$weeks}', '{$days}', '{$months}', '{$half_day}', '{$weekends}',\n\t\t\t\t'{$total_days}')";
            db_exec($sql) or errDie("Unable to create rental items.");
            $item_id = pglib_lastid("hire.hire_invitems", "id");
            $sql = "\n\t\t\tINSERT INTO hire.assets_hired (invid, asset_id, qty, hired_time,\n\t\t\t\tcust_id, item_id, invnum, value, basis, discount, weekends)\n\t\t\tVALUES ('{$invid}', '{$item_data['asset_id']}', '{$item_data['qty']}',\n\t\t\t\t'{$rental_data['timestamp']}', '{$rental_data['cusnum']}', '{$item_id}',\n\t\t\t\t'{$rental_data['id']}', '{$item_data['total']}', '{$item_data['basis']}',\n\t\t\t\t'0.00', '{$weekends}')";
            db_exec($sql) or errDie("Unable to add to assets hired.");
        }
    }
    // Run invoices ----------------------------------------------------------
    $sql = "\n\tSELECT id, hire_id, customers.cusnum, order_num, discount_perc, discount,\n\t\tsubtotal, total, vat, timestamp, user_id, surname, addr1, vatnum,\n\t\tusername, delivery\n\tFROM cubit.hire_invoice_trans\n\t\tLEFT JOIN cubit.customers ON hire_invoice_trans.cusnum=customers.cusnum\n\t\tLEFT JOIN cubit.users ON hire_invoice_trans.user_id=users.userid\n\tWHERE done='y' AND user_id='{$user_id}' AND hire_id > 0";
    $inv_rslt = db_exec($sql) or errDie("Unable to retrieve invoices.");
    while ($inv_data = pg_fetch_array($inv_rslt)) {
        $hire_sales = qryAccountsNum("1050", "000");
        $cust_control = qryAccountsNum("6400", "000");
        $cash_on_hand = qryAccountsNum("7200", "000");
        $hire_sales = $hire_sales["accid"];
        $cust_control = $cust_control["accid"];
        $cash_on_hand = $cash_on_hand["accid"];
        $time = strtotime($inv_data["timestamp"]);
        $sql = "\n\t\tINSERT INTO cubit.nons_invoices (cusname, cusaddr, cusvatno,\n\t\t\tchrgvat, sdate, done, username, prd, invnum, div, remarks, cusid,\n\t\t\tage, typ, subtot, balance, vat, total, descrip, ctyp, accid,\n\t\t\tfbalance, fsubtot, cordno, terms, odate, systime, bankid,\n\t\t\tcusordno, ncdate, cusnum, discount, delivery, hire_invid,\n\t\t\tcash, cheque, credit)\n\t\tVALUES ('{$inv_data['surname']}', '{$inv_data['addr1']}', '{$inv_data['vatnum']}',\n\t\t\t'yes', '" . date("Y-m-d", $time) . "', 'y', '{$inv_data['username']}',\n\t\t\t'" . PRD_DB . "', '{$inv_data['id']}', '" . USER_DIV . "', '',\n\t\t\t'{$inv_data['cusnum']}', '0', 'inv', '{$inv_data['subtotal']}',\n\t\t\t'{$inv_data['total']}', '{$inv_data['vat']}', '{$inv_data['total']}', '', 's',\n\t\t\t'{$hire_sales}', '0.00', '0.00', '{$inv_data['order_num']}', '0',\n\t\t\t'" . date("Y-m-d", $time) . "', current_timestamp,\n\t\t\t'" . cust_bank_id($inv_data["cusnum"]) . "', '{$inv_data['order_num']}',\n\t\t\t'" . date("Y-m-d", $time) . "', '{$inv_data['cusnum']}',\n\t\t\t'{$inv_data['discount']}', '{$inv_data['delivery']}',\n\t\t\t'" . $hire_nums[$inv_data["hire_id"]] . "', '{$inv_data['total']}', '0', '0')";
        db_exec($sql) or errDie("Unable to create non stock invoice.");
        $invid = lastinvid();
        $sql = "\n\t\tSELECT hire_invoice_items_trans.id, asset_id, basis, from_date,\n\t\t\tto_date, half_day, qty, weekends, total_days, total,\n\t\t\tserial, des, grpid\n\t\tFROM cubit.hire_invoice_items_trans\n\t\t\tLEFT JOIN cubit.assets\n\t\t\t\tON hire_invoice_items_trans.asset_id=assets.id\n\t\tWHERE trans_id='{$inv_data['id']}'";
        $item_rslt = db_exec($sql) or errDie("Unable to retrieve items.");
        while ($item_data = pg_fetch_array($item_rslt)) {
            $unitcost = $item_data["total"] / $item_data["qty"];
            $item_id = 0;
            $sql = "\n\t\t\tSELECT {$item_data['basis']} FROM hire.basis_prices\n\t\t\tWHERE assetid='{$item_data['asset_id']}'";
            $rate_rslt = db_exec($sql) or errDie("Unable to retrieve rate.");
            $rate = pg_fetch_result($rate_rslt, 0);
            $rate = empty($rate) ? 0.0 : $rate;
            $sql = "\n\t\t\tSELECT serial, des FROM cubit.assets\n\t\t\tWHERE id='{$item_data['asset_id']}'";
            $asset_rslt = db_exec($sql) or errDie("Unable to retrieve assets.");
            $asset_data = pg_fetch_array($asset_rslt);
            $sql = "\n\t\t\tINSERT INTO hire.hire_nons_inv_items (invid, qty, description, div,\n\t\t\t\tamt, unitcost, accid, vatex, cunitcost, asset_id, item_id,\n\t\t\t\thired_days, rate)\n\t\t\tVALUES ('{$invid}', '{$item_data['qty']}', '({$asset_data['serial']}) " . "{$asset_data['des']} hired from {$item_data['from_date']} to " . "{$item_data['to_date']}.', '" . USER_DIV . "', '{$item_data['total']}',\n\t\t\t\t'{$unitcost}', '{$hire_sales}', '2', '{$unitcost}',\n\t\t\t\t'{$item_data['asset_id']}', '{$item_id}', '{$item_data['total_days']}',\n\t\t\t\t'{$rate}')";
            db_exec($sql) or errDie("Unable to create invoice item.");
            // Add up revenue
            $sql = "\n\t\t\tINSERT INTO hire.revenue (group_id, asset_id, total, discount,\n\t\t\t\thire_invnum, inv_invnum, cusname)\n\t\t\tVALUES ('{$item_data['grpid']}', '{$item_data['asset_id']}',\n\t\t\t\t'{$item_data['total']}', '0', '0',\n\t\t\t\t'0', '{$inv_data['surname']}')";
            db_exec($sql) or errDie("Unable to update revenue");
            $sql = "\n\t\t\tUPDATE hire.assets_hired SET return_time=CURRENT_TIMESTAMP\n\t\t\t\tWHERE item_id='{$item_data['id']}'";
            db_exec($sql) or errDie("Unable to update hired assets.");
            $sql = "\n\t\t\tSELECT serial2 FROM cubit.assets\n\t\t\tWHERE id='{$item_data['asset_id']}'";
            $asset_rslt = db_exec($sql) or errDie("Unable to retrieve asset");
            $asset_data = pg_fetch_array($asset_rslt);
            if (!isSerialized($item_data["asset_id"])) {
                $new_qty = $asset_data["serial2"] + $item_data["qty"];
                $sql = "\n\t\t\t\tUPDATE cubit.assets SET serial2=(serial2::numeric + '{$item_data['qty']}')\n\t\t\t\tWHERE id='{$item_data['asset_id']}'";
                db_exec($sql) or errDie("Unable to update asset qty.");
            }
        }
        $refnum = getRefnum();
        writetrans($cust_control, $hire_sales, date("Y-m-d", $time), $refnum, $inv_data["total"], "Non Stock Sales on invoice No. {$inv_data['id']} " . "customer {$inv_data['surname']}");
        // Sales record
        $sql = "\n\t\tINSERT INTO cubit.salesrec(edate, invid, invnum, debtacc, vat, total,\n\t\t\ttyp, div)\n\t\tVALUES('" . date("Y-m-d", $time) . "', '{$invid}', '{$inv_data['id']}',\n\t\t\t'{$cust_control}', '{$inv_data['vat']}', '{$inv_data['total']}', 'non',\n\t\t\t'" . USER_DIV . "')";
        db_exec($sql) or errDie("Unable to create sales record.");
        // Vat record
        vatr(2, date("Y-m-d", $time), "OUTPUT", '01', $refnum, "Non-Stock Sales, invoice No.{$inv_data['id']}", $inv_data["total"], $inv_data["vat"]);
        // Add to statement
        $sql = "\n\t\tINSERT INTO cubit.stmnt (cusnum, invid, docref, amount, date, type, div)\n\t\tVALUES ('{$inv_data['cusnum']}', '{$invid}', '{$inv_data['order_num']}',\n\t\t\t'{$inv_data['total']}', '" . date("Y-m-d", $time) . "',\n\t\t\t'Hire Invoice {$inv_data['id']}', '" . USER_DIV . "')";
        db_exec($sql) or errDie("Unable to add to statement.");
        // Update customer balance
        $sql = "\n\t\tUPDATE customers SET balance = (balance + '{$inv_data['total']}')\n\t\tWHERE cusnum='{$inv_data['cusnum']}' AND div='" . USER_DIV . "'";
        db_exec($sql) or errDie("Unable to update customer balance.");
        custledger($inv_data["cusnum"], $hire_sales, date("Y-m-d", $time), $invid, "Hire Invoice No. {$inv_data['id']}", $inv_data["total"], "d");
        custDT($inv_data["total"], $inv_data["cusnum"], date("Y-m-d", $time));
    }
    // Clear outstanding tables
    $sql = "DELETE FROM cubit.hire_trans";
    db_exec($sql) or errDie("Unable to remove outstanding (1)");
    $sql = "DELETE FROM cubit.hire_trans_items";
    db_exec($sql) or errDie("Unable to remove outstanding (2)");
    $sql = "DELETE FROM cubit.hire_invoice_trans";
    db_exec($sql) or errDie("Unable to remove outstanding (3)");
    $sql = "DELETE FROM cubit.hire_invoice_items_trans";
    db_exec($sql) or errDie("Unable to remove outstanding (4)");
    pglib_transaction("COMMIT");
    return enter();
}