function write($_POST) { extract($_POST); $deptid += 0; db_conn('cubit'); if (isset($printsales)) { $Sl = "SELECT * FROM settings WHERE constant='PSALES'"; $Ri = db_exec($Sl) or errDie("Unable to get settings."); if (pg_num_rows($Ri) < 1) { $Sl = "INSERT INTO settings (constant,value,div) VALUES ('PSALES','Yes','" . USER_DIV . "')"; $Ri = db_exec($Sl); } else { $Sl = "UPDATE settings SET value='Yes' WHERE constant='PSALES' AND div='" . USER_DIV . "'"; $Ri = db_exec($Sl); } } else { $Sl = "UPDATE settings SET value='No' WHERE constant='PSALES' AND div='" . USER_DIV . "'"; $Ri = db_exec($Sl); } //$it+=0; # validate input require_lib("validate"); $v = new validate(); if (isset($client)) { $v->isOk($client, "string", 0, 20, "Invalid Customer."); } else { $client = ""; } if (isset($vatnum)) { $v->isOk($vatnum, "string", 0, 30, "Invalid VAT Number."); } else { $vatnum = ""; } if (isset($branch_addr)) { $v->isOk($branch_addr, "num", 1, 20, "Invalid site address."); } else { $branch_addr = 0; } $v->isOk($invid, "num", 1, 20, "Invalid Invoice Number."); $v->isOk($telno, "string", 0, 20, "Invalid Customer Telephone Number."); $v->isOk($cordno, "string", 0, 20, "Invalid Customer Order Number."); //$v->isOk ($comm, "string", 0, 255, "Invalid Comments."); $v->isOk($ordno, "string", 0, 20, "Invalid sales order number."); // $v->isOk ($chrgvat, "string", 1, 4, "Invalid charge vat option."); $v->isOk($salespid, "string", 1, 255, "Invalid sales person."); $v->isOk($pinv_day, "num", 1, 2, "Invalid Invoice Date day."); $v->isOk($pinv_month, "num", 1, 2, "Invalid Invoice Date month."); $v->isOk($pinv_year, "num", 1, 5, "Invalid Invoice Date year."); $odate = $pinv_year . "-" . $pinv_month . "-" . $pinv_day; if (!checkdate($pinv_month, $pinv_day, $pinv_year)) { $v->isOk($odate, "num", 1, 1, "Invalid Invoice Date."); } $v->isOk($traddisc, "float", 0, 20, "Invalid Trade Discount."); if ($traddisc > 100) { $v->isOk($traddisc, "float", 0, 0, "Error : Trade Discount cannot be more than 100 %."); } $v->isOk($delchrg, "float", 0, 20, "Invalid Delivery Charge."); $v->isOk($subtot, "float", 0, 20, "Invalid subtotal."); $odate = $pinv_year . "-" . $pinv_month . "-" . $pinv_day; if (!checkdate($pinv_month, $pinv_day, $pinv_year)) { $v->isOk($odate, "num", 1, 1, "Invalid Invoice Date."); } $v->isOk($collection, "string", 0, 40, "Invalid collection method."); # used to generate errors $error = "asa@"; # check if duplicate serial number selected, remove blanks if (isset($sernos)) { if (!ext_isUnique(ext_remBlnk($sernos))) { $v->isOk($error, "num", 0, 0, "Error : Serial Numbers must be unique per line item."); } } # check is serial no was selected if (isset($stkids)) { foreach ($stkids as $keys => $stkid) { # 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>"); } } } # check quantities if (isset($qtys)) { foreach ($qtys as $keys => $qty) { $discp[$keys] += 0; $disc[$keys] += 0; $v->isOk($qty, "num", 1, 10, "Invalid Quantity for product number : <b>" . ($keys + 1) . "</b>"); if ($qty < 1) { $v->isOk($qty, "num", 0, 0, "Error : Item Quantity must be at least one. Product number : <b>" . ($keys + 1) . "</b>"); } } } # check whids if (isset($whids)) { foreach ($whids as $keys => $whid) { $v->isOk($whid, "num", 1, 10, "Invalid Store number, please enter all details."); } } $cusnum += 0; # check stkids if (isset($stkids)) { foreach ($stkids as $keys => $stkid) { $v->isOk($stkid, "num", 1, 10, "Invalid Stock number, please enter all details."); } } # check amt if (isset($amt)) { foreach ($amt as $keys => $amount) { $v->isOk($amount, "float", 1, 20, "Invalid Amount, please enter all details."); } } if (isset($des)) { $des = remval($des); } if (isset($asset_id) && is_numeric($asset_id)) { foreach ($asset_id as $value) { $sql = "SELECT id, des FROM cubit.assets WHERE id='{$asset_id}'"; $asset_rslt = db_exec($sql) or errDie("Unable to retrieve asset."); $asset_data = pg_fetch_array($asset_rslt); if (isHired($asset_id)) { $v->addError(0, "Asset " . getSerial($asset_id) . " {$asset_data['des']} has already been hired out."); } } } # 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); } if (strlen($vatnum) < 1) { $vatnum = ""; } $_POST['client'] = $client; $_POST['vatnum'] = $vatnum; $_POST['telno'] = $telno; $_POST['cordno'] = $cordno; # Get invoice info db_connect(); $sql = "SELECT * FROM hire.hire_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[1]</li>"; // } $inv = pg_fetch_array($invRslt); $inv['traddisc'] = $traddisc; $inv['chrgvat'] = 0; # 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='« Correct submission'>"; // return $error; // } # get department db_conn("exten"); $sql = "SELECT * FROM departments WHERE deptid = '{$deptid}' AND div = '" . USER_DIV . "'"; $deptRslt = db_exec($sql); if (pg_numrows($deptRslt) < 1) { $dept['deptname'] = "<i class='err'>Not Found[3]</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(); if (isset($upBtn) || isset($hirenewBtn)) { $update_ret = update($_POST); } else { $update_ret = false; } # begin updating pglib_transaction("BEGIN"); /* -- Start remove old items -- */ # get selected stock in this invoice $sql = "SELECT * FROM hire.hire_invitems WHERE invid = '{$invid}'"; $stktRslt = db_exec($sql); $subtot = 0; 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']); $subtot += $stkt["amt"]; } # remove old items /* --- ----------- Clac --------------------- */ ##----------------------NEW---------------------- $VATP = TAX_VAT; $subtotal = sprint($subtot + $delchrg); $traddiscmt = sprint($subtotal * $traddisc / 100); $subtotal = sprint($subtotal - $traddiscmt); $VAT = $subtotal / 100 * 14; $SUBTOT = $subtotal; $TOTAL = $subtotal + $VAT; $delexvat = sprint($delchrg); $Sl = "SELECT * FROM posround"; $Ri = db_exec($Sl); $data = pg_fetch_array($Ri); if ($data['setting'] == "5cent") { if (sprint(floor(sprint($TOTAL / 0.05))) != sprint($TOTAL / 0.05)) { $otot = $TOTAL; $nTOTAL = sprint(sprint(floor($TOTAL / 0.05)) * 0.05); $rounding = $otot - $nTOTAL; } else { $rounding = 0; } } else { $rounding = 0; } //print sprint(floor($TOTAL/0.05)); #get accno if invoice is on credit if ($cusnum != "0") { $get_acc = "SELECT * FROM customers WHERE cusnum = '{$cusnum}' LIMIT 1"; $run_acc = db_exec($get_acc) or errDie("Unable to get customer information"); if (pg_numrows($run_acc) < 1) { $accno = ""; } else { $arr = pg_fetch_array($run_acc); $cusacc = $arr['accno']; $cusname = "{$arr['cusname']} {$arr['surname']}"; } } else { $cusacc = ""; $cusname = ""; } # insert invoice to DB $sql = "\r\n\t\t\tUPDATE hire.hire_invoices \r\n\t\t\tSET cusnum='{$cusnum}', cusname='{$cusname}', rounding='{$rounding}', deptid='{$deptid}', deptname='{$dept['deptname']}', \r\n\t\t\t\tcordno='{$cordno}', ordno='{$ordno}', salespn='{$salespid}', odate='{$odate}', traddisc='{$traddisc}', \r\n\t\t\t\tdelchrg='{$delchrg}', subtot='{$SUBTOT}', vat='{$VAT}',balance='{$TOTAL}', total='{$TOTAL}', discount='{$traddiscmt}', \r\n\t\t\t\tdelivery='{$delexvat}', vatnum='{$vatnum}', cusacc='{$cusacc}', telno='{$telno}', deposit_type='{$deposit_type}', \r\n\t\t\t\tdeposit_amt='{$deposit_amt}', collection='{$collection}', custom_txt='{$custom_txt}', branch_addr='{$branch_addr}' \r\n\t\t\tWHERE invid='{$invid}' AND div = '" . USER_DIV . "'"; $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF); # remove old data $sql = "DELETE FROM pinv_data WHERE invid='{$invid}' AND div = '" . USER_DIV . "'"; $rslt = db_exec($sql) or errDie("Unable to update invoice data in Cubit.", SELF); # put in new data $sql = "INSERT INTO pinv_data(invid, dept, customer, div) VALUES('{$invid}', '{$dept['deptname']}', '{$client}', '" . USER_DIV . "')"; $rslt = db_exec($sql) or errDie("Unable to insert invoice data to Cubit.", SELF); # commit updating pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF); return details($_POST, $update_ret); 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, "Please go set the point of sale settings under the stock settings"); } $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, "<li class='err'><b>ERROR</b>: The bar code you selected is not in the system or is not available.</li>"); } $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 = "\r\n\t\t\t\tINSERT INTO hire.hire_invitems (\r\n\t\t\t\t\tinvid, whid, stkid, qty, amt, disc, discp, ss, serno, \r\n\t\t\t\t\tdiv\r\n\t\t\t\t) VALUES (\r\n\t\t\t\t\t'{$invid}', '{$s['whid']}', '{$stid}', '1', '{$s['selamt']}', '{$s['selamt']}', '0', '0', '{$bar}', '{$bar}', \r\n\t\t\t\t\t'" . USER_DIV . "'\r\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); $stid = ext_dbget('stock', 'bar', $bar, 'stkid'); if (!($stid > 0)) { return details($_POST, "<li class='err'><b>ERROR</b>: The bar code you selected is not in the system or is not available.</li>"); } $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 = "INSERT INTO hire.hire_invitems(invid, whid, stkid, qty, amt, disc, discp,ss, div) VALUES('{$invid}', '{$s['whid']}', '{$stid}', '1', '{$s['selamt']}','0','0','{$bar}', '" . 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 + '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($doneBtn)) { # check if stock was selected(yes = put done button) db_connect(); $sql = "SELECT stkid FROM hire.hire_invitems 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.</li>"; return details($_POST, $error); } $TOTAL = sprint($TOTAL - $rounding); if ($pcash + $pcheque + $pcc + $pcredit < $TOTAL) { return details($_POST, "<li class='err'>The total of all the payments is less than the invoice total</li>"); } $change = sprint(sprint($pcash + $pcheque + $pcc + $pcredit) - sprint($TOTAL)); $pcash = sprint($pcash - $change); if ($pcash < 0) { $pcash = 0; } if (sprint($pcash + $pcheque + $pcc + $pcredit) != sprint($TOTAL)) { return details($_POST, "<li class='err'>The total of all the payments is not equal to the invoice total.<br>\r\n\t\t\t(You can only overpay with cash)</li>"); } // make plant available $sql = "UPDATE hire.hire_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 $OUTPUT = "<script>printer('pos-invoice-print.php?invid={$invid}');move('pos-invoice-new.php');</script>"; require "template.php"; } elseif (isset($cancel)) { // Final Laytout $write = "\r\n\t\t\t<table border='0' cellpadding='" . TMPL_tblCellPadding . "' cellspacing='" . TMPL_tblCellSpacing . "'>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<th>New Point of Sale Invoice Saved</th>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t\t\t<td>Invoice for <b>{$client}</b> has been saved.</td>\r\n\t\t\t\t</tr>\r\n\t\t\t</table>\r\n\t\t\t<p>\r\n\t\t\t<table border=0 cellpadding='" . TMPL_tblCellPadding . "' cellspacing='" . TMPL_tblCellSpacing . "'>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<th>Quick Links</th>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t\t\t<td><a href='pos-invoice-new.php'>New Point of Sale Invoice</a></td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t\t\t<td><a href='pos-invoice-list.php'>View Point of Sale Invoices</a></td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<script>document.write(getQuicklinkSpecial());</script>\r\n\t\t\t</table>"; return $write; } else { if (isset($wtd)) { $_POST['wtd'] = $wtd; } return details($_POST); } }
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, "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, "num", 0, 20, "Invalid Document Reference No."); $v->isOk($ordno, "num", 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($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 if duplicate serial number selected, remove blanks if (isset($sernos)) { if (!ext_isUnique(ext_remBlnk($sernos))) { $v->isOk($error, "num", 0, 0, "Error : Serial Numbers must be unique per line item."); } } # check is 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>"); } } } # check quantities if (isset($qtys)) { foreach ($qtys as $keys => $qty) { $discp[$keys] += 0; $disc[$keys] += 0; $v->isOk($qty, "num", 1, 10, "Invalid Quantity for product number : <b>" . ($keys + 1) . "</b>"); $v->isOk($disc[$keys], "float", 0, 20, "Invalid Discount for product number : <b>" . ($keys + 1) . "</b>."); if ($disc[$keys] > $unitcost[$keys]) { $v->isOk($disc[$keys], "float", 0, 0, "Error : Discount for product number : <b>" . ($keys + 1) . "</b> is more than the unitcost."); } $v->isOk($discp[$keys], "float", 0, 20, "Invalid Discount Percentage for product number : <b>" . ($keys + 1) . "</b>."); 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"]; } 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='« 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); # 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; # 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 -- */ $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 { # 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]); # Check Tax Excempt if ($stk['exvat'] == 'yes') { $taxex += $amt[$keys]; } $wtd = $whids[$keys]; # insert invoice items $sql = "INSERT INTO inv_items(invid, whid, stkid, qty, unitcost, amt, disc, discp, serno, div) VALUES('{$invid}', '{$whids[$keys]}', '{$stkids[$keys]}', '{$qtys[$keys]}', '{$unitcost[$keys]}', '{$amt[$keys]}', '{$disc[$keys]}', '{$discp[$keys]}', '{$sernos[$keys]}','" . USER_DIV . "')"; $rslt = db_exec($sql) or errDie("Unable to insert invoice items to Cubit.", SELF); if (strlen($stkt['serno']) > 0) { ext_resvSer($stkt['serno'], $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); } } 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]; } $wtd = $whids[$keys]; # insert invoice items $sql = "INSERT INTO inv_items(invid, whid, stkid, qty, unitcost, amt, disc, discp, serno, div) VALUES('{$invid}', '{$whids[$keys]}', '{$stkids[$keys]}', '{$qtys[$keys]}', '{$unitcost[$keys]}', '{$amt[$keys]}', '{$disc[$keys]}', '{$discp[$keys]}', '{$sernos[$keys]}','" . USER_DIV . "')"; $rslt = db_exec($sql) or errDie("Unable to insert invoice items to Cubit.", SELF); if (strlen($sernos[$keys]) > 0) { ext_resvSer($sernos[$keys], $stk['stkid']); } # update stock(alloc + qty) $sql = "UPDATE stock SET alloc = (alloc + '{$qtys[$keys]}') WHERE stkid = '{$stkids[$keys]}' AND div = '" . USER_DIV . "'"; $rslt = db_exec($sql) or errDie("Unable to update stock to Cubit.", SELF); } # everything is set place done button $_POST["done"] = " | <input name=doneBtn type=submit value='Print'>"; } } else { $_POST["done"] = ""; } /* --- ----------- Clac --------------------- */ # calculate subtot $SUBTOT = 0.0; 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; } $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 + $taxex); $SUBTOT += $taxex; /* --- ----------- 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}', docref = '{$docref}',\n\t\tchrgvat = '{$chrgvat}', terms = '{$terms}', salespn = '{$salespn}', odate = '{$odate}', traddisc = '{$traddisc}', delchrg = '{$delchrg}', subtot = '{$SUBTOT}', vat = '{$VAT}', total = '{$TOTAL}', balance = '{$TOTAL}', comm = '{$comm}', serd = 'y', discount='{$traddiscmt}', delivery='{$delexvat}' 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); 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, "Please go set the point of sale settings under the stock settings"); } $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 = "INSERT INTO inv_items(invid, whid, stkid, qty, unitcost, amt, disc, discp,ss, div) VALUES('{$invid}', '{$s['whid']}', '{$stid}', '1','{$s['selamt']}','{$s['selamt']}','0','0','{$bar}', '" . 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 + '1') WHERE stkid = '{$stid}' AND div = '" . USER_DIV . "'"; $rslt = db_exec($sql) or errDie("Unable to update stock to Cubit.", SELF); $Sl = "DELETE FROM " . $tab . " 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 = "INSERT INTO inv_items(invid, whid, stkid, qty, unitcost, amt, disc, discp,ss, div) VALUES('{$invid}', '{$s['whid']}', '{$stid}', '1','{$s['selamt']}','{$s['selamt']}','0','0','{$bar}', '" . 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 + '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($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 $OUTPUT = "<script>printer('invoice-print.php?invid={$invid}');move('main.php');</script>"; require "template.php"; } 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\t<tr class='bg-odd'><td><a href='main.php'>Main Menu</a></td></tr>\n\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 --- */ }
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 --- */ }
function write($_POST) { # Get vars extract($_POST); # 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, "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, "num", 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($o_day, "num", 1, 2, "Invalid Invoice Date day."); $v->isOk($o_month, "num", 1, 2, "Invalid Invoice Date month."); $v->isOk($o_year, "num", 1, 5, "Invalid Invoice Date year."); $odate = $o_year . "-" . $o_month . "-" . $o_day; if (!checkdate($o_month, $o_day, $o_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 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>"); } } } # 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 %."); } $unitcost[$keys] += 0; $cunitcost[$keys] += 0; $v->isOk($unitcost[$keys], "float", 1, 20, "Invalid Unit Price for product number : <b>" . ($keys + 1) . "</b>."); $v->isOk($cunitcost[$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; # 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='« Correct submission'>"; return $error; } db_connect(); 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); } # 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'] = ""; # currency $currs = getSymbol($inv['fcid']); } else { $cust = pg_fetch_array($custRslt); # If customer was just selected/changed, get the following if ($inv['cusnum'] != $cusnum) { $traddisc = $cust['traddisc']; $terms = $cust['credterm']; $xrate = getRate($cust['fcid']); } # currency $currs = getSymbol($cust['fcid']); } # 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 $xrate += 0; if ($xrate == 0) { $xrate = 1; } $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 -- */ $taxex = 0; if (isset($qtys)) { foreach ($qtys as $keys => $value) { if (isset($remprod) && in_array($keys, $remprod)) { // 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); // // $t=$cunitcost[$keys]; // // # Calculate the unitcost // if($cunitcost[$keys] > 0 && $unitcost[$keys] == 0){ // $unitcost[$keys] = ($cunitcost[$keys] * $xrate); // }else{ // $cunitcost[$keys] = ($unitcost[$keys]/$xrate); // } // // # Calculate the Discount discount // if($disc[$keys] < 1){ // if($discp[$keys] > 0){ // $disc[$keys] = (($discp[$keys]/100) * $t); // } // }else{ // $discp[$keys] = (($disc[$keys] * 100) / $t); // } // // # Calculate amount // $funitcost[$keys] = $unitcost[$keys]; // $famt[$keys] = ($qtys[$keys] * ($funitcost[$keys])); // // # Calculate amount // // $amt[$keys] = ($qtys[$keys] * ($unitcost[$keys] - $disc[$keys])); // $unitcost[$keys] = sprint($funitcost[$keys]/$xrate); // $amt[$keys] = sprint($famt[$keys]/$xrate-($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); // // # Check Tax Excempt // if($stk['exvat'] == 'yes'||$vd['zero']=="Yes"){ // $taxex += $amt[$keys]; // } // // # insert invoice items // $sql = "INSERT INTO inv_items(invid, whid, stkid, qty, unitcost, funitcost, amt, famt, disc, discp, serno, div,vatcode,del) VALUES('$invid', '$whids[$keys]', '$stkids[$keys]', '$qtys[$keys]', '$unitcost[$keys]', '$funitcost[$keys]', '$amt[$keys]', '$famt[$keys]', '$disc[$keys]', '$discp[$keys]', '$sernos[$keys]', '".USER_DIV."','$vatcodes[$keys]','0')"; // $rslt = db_exec($sql) or errDie("Unable to insert invoice items to Cubit.",SELF); // // if(strlen($stkt['serno']) > 0) // ext_resvSer($stkt['serno'], $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); // } } 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 unitcost if($cunitcost[$keys] > 0 && $unitcost[$keys] == 0){ $unitcost[$keys] = ($cunitcost[$keys] * $xrate); }else{ $cunitcost[$keys] = ($unitcost[$keys]/$xrate); }*/ $t = $cunitcost[$keys]; # Calculate the unitcost if ($unitcost[$keys] > 0 && $cunitcost[$keys] == 0) { $cunitcost[$keys] = $unitcost[$keys] / $xrate; } else { $unitcost[$keys] = $cunitcost[$keys] * $xrate; } # Calculate the Discount discount if ($disc[$keys] < 1) { if ($discp[$keys] > 0) { $disc[$keys] = $discp[$keys] / 100 * $t; } } else { $discp[$keys] = $disc[$keys] * 100 / $t; } if ($xrate < 1) { $xrate = 1; } //$disc[$keys]=$disc[$keys]*$xrate; # Calculate amount $funitcost[$keys] = $unitcost[$keys]; $famt[$keys] = $qtys[$keys] * $funitcost[$keys]; //$famt[$keys] = ($qtys[$keys] * ($funitcost[$keys] - $disc[$keys])); # Calculate amount // $amt[$keys] = ($qtys[$keys] * ($unitcost[$keys] - $disc[$keys])); $unitcost[$keys] = sprint($funitcost[$keys] / $xrate); $amt[$keys] = sprint($famt[$keys] / $xrate - $disc[$keys]); //$amt[$keys] = sprint($famt[$keys]/$xrate); $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]; } # 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, \n\t\t\t\t\t\t\tfunitcost, amt, famt, disc, \n\t\t\t\t\t\t\tdiscp, serno, div, vatcode, 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]}', \n\t\t\t\t\t\t\t'{$funitcost[$keys]}', '{$amt[$keys]}', '{$famt[$keys]}', '{$disc[$keys]}', '{$discp[$keys]}', \n\t\t\t\t\t\t\t'{$sernos[$keys]}', '" . USER_DIV . "', '{$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"] = " | <input name='doneBtn' type='submit' value='Process'>"; } } else { $_POST["done"] = ""; } 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; 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---------------------- /* --- ----------- 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 --------------------- */ $FTOTAL = sprint($TOTAL * $xrate); /* --- ----------- Clac --------------------- */ # insert invoice to DB $sql = "\n\t\t\tUPDATE invoices \n\t\t\tSET delvat='{$delvat}', cusnum = '{$cusnum}', deptname = '{$dept['deptname']}', cusacc = '{$cust['accno']}', \n\t\t\t\tcusname = '{$cust['cusname']}', surname = '{$cust['surname']}', cusaddr = '{$cust['addr1']}', \n\t\t\t\tcusvatno = '{$cust['vatnum']}', cordno = '{$cordno}', ordno = '{$ordno}', chrgvat = '{$chrgvat}', docref = '{$docref}', \n\t\t\t\tterms = '{$terms}', salespn = '{$salespn}', fcid = '{$cust['fcid']}', currency = '{$currs['symbol']}', xrate = '{$xrate}', \n\t\t\t\todate = '{$odate}', traddisc = '{$traddisc}', delchrg = '{$delchrg}', subtot = '{$SUBTOT}', vat = '{$VAT}', \n\t\t\t\ttotal = '{$TOTAL}', balance = '{$FTOTAL}', fbalance = '{$TOTAL}', comm = '{$comm}', location = '{$cust['location']}', \n\t\t\t\tserd = 'y', discount='{$traddiscmt}', delivery='{$delexvat}' \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); # 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 inv_items (\n\t\t\t\t\tinvid, whid, stkid, qty, unitcost, amt, disc, discp,ss, div, del\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 . "', '0'\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 inv_items (\n\t\t\t\t\tinvid, whid, stkid, qty, unitcost, amt, disc, discp,ss, div, del\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 . "', '0'\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($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.</li>"; 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 ($data['value'] == "Yes") { # Print the invoice $OUTPUT = "<script>nhprinter('invoice-delnote.php?invid={$invid}','Delivery Note');printer('intinvoice-print.php?invid={$invid}');move('main.php');</script>"; } else { # Print the invoice $OUTPUT = "<script>printer('intinvoice-print.php?invid={$invid}');move('main.php');</script>"; } 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 International 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>International Invoice for customer <b>{$cust['cusname']} {$cust['surname']}</b> has been saved.</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); } }
function write($_POST) { #get vars extract($_POST); if (isset($cusnum) && customer_overdue($cusnum)) { return details($_POST, "<li class='err'>Customer is overdue, account blocked!</li>"); } $pcredit += 0; $pcash += 0; $pcheque += 0; $pcc += 0; $deptid += 0; db_conn('cubit'); if (isset($printsales)) { $Sl = "SELECT * FROM settings WHERE constant='PSALES'"; $Ri = db_exec($Sl) or errDie("Unable to get settings."); if (pg_num_rows($Ri) < 1) { $Sl = "INSERT INTO settings (constant,value,div) VALUES ('PSALES','Yes','" . USER_DIV . "')"; $Ri = db_exec($Sl); } else { $Sl = "UPDATE settings SET value='Yes' WHERE constant='PSALES' AND div='" . USER_DIV . "'"; $Ri = db_exec($Sl); } } else { $Sl = "UPDATE settings SET value='No' WHERE constant='PSALES' AND div='" . USER_DIV . "'"; $Ri = db_exec($Sl); } //$it+=0; # validate input require_lib("validate"); $v = new validate(); if (isset($client)) { $v->isOk($client, "string", 0, 20, "Invalid Customer."); } else { $client = ""; } if (isset($vatnum)) { $v->isOk($vatnum, "string", 0, 30, "Invalid VAT Number."); } else { $vatnum = ""; } $v->isOk($invid, "num", 1, 20, "Invalid Invoice Number."); $v->isOk($telno, "string", 0, 20, "Invalid Customer Telephone Number."); $v->isOk($cordno, "string", 0, 20, "Invalid Customer Order Number."); $v->isOk($comm, "string", 0, 255, "Invalid Comments."); $v->isOk($ordno, "string", 0, 20, "Invalid sales order number."); $v->isOk($chrgvat, "string", 1, 4, "Invalid charge vat option."); $v->isOk($salespn, "string", 1, 255, "Invalid sales person."); $v->isOk($pinv_day, "num", 1, 2, "Invalid Invoice Date day."); $v->isOk($pinv_month, "num", 1, 2, "Invalid Invoice Date month."); $v->isOk($pinv_year, "num", 1, 5, "Invalid Invoice Date year."); $odate = $pinv_year . "-" . $pinv_month . "-" . $pinv_day; if (!checkdate($pinv_month, $pinv_day, $pinv_year)) { $v->isOk($odate, "num", 1, 1, "Invalid Invoice Date."); } $v->isOk($traddisc, "float", 0, 20, "Invalid Trade Discount."); if ($traddisc > 100) { $v->isOk($traddisc, "float", 0, 0, "Error : Trade Discount cannot be more than 100 %."); } $v->isOk($delchrg, "float", 0, 20, "Invalid Delivery Charge."); $v->isOk($SUBTOT, "float", 0, 20, "Invalid Delivery Charge."); $odate = $pinv_year . "-" . $pinv_month . "-" . $pinv_day; if (!checkdate($pinv_month, $pinv_day, $pinv_year)) { $v->isOk($odate, "num", 1, 1, "Invalid Invoice Date."); } # used to generate errors $error = "asa@"; # check if duplicate serial number selected, remove blanks if (isset($sernos)) { if (!ext_isUnique(ext_remBlnk($sernos))) { //$v->isOk ($error, "num", 0, 0, "Error : Serial Numbers must be unique per line item."); } } # check is serial no was selected if (isset($stkids)) { foreach ($stkids as $keys => $stkid) { if (is_numeric($stkid)) { $sql = "SELECT units, stkcod FROM cubit.stock WHERE stkid='{$stkid}'"; $stock_rslt = db_exec($sql) or errDie("Unable to retrieve stock."); list($stock_units, $stock_code) = pg_fetch_array($stock_rslt); if ($qtys[$keys] > $stock_units) { $v->addError(0, "Not enough stock available for {$stock_code}"); } } # check if serial is selected if (ext_isSerial("stock", "stkid", $stkid) && !isset($sernos[$keys])) { $v->isOk($error, "num", 0, 0, "Error : Missing serial number for product number (2): <b>" . ($keys + 1) . "</b>"); } elseif (ext_isSerial("stock", "stkid", $stkid) && strlen($sernos[$keys]) <= 0 && strlen($sernos_ss[$keys]) <= 0) { $v->isOk($error, "num", 0, 0, "Error : Missing serial number for product number (1): <b>" . ($keys + 1) . "</b>"); } } } # check quantities if (isset($qtys)) { foreach ($qtys as $keys => $qty) { $discp[$keys] += 0; $disc[$keys] += 0; $v->isOk($qty, "num", 1, 10, "Invalid Quantity for product number : <b>" . ($keys + 1) . "</b>"); $v->isOk($disc[$keys], "float", 0, 20, "Invalid Discount for product number : <b>" . ($keys + 1) . "</b>."); if ($disc[$keys] > $unitcost[$keys]) { $v->isOk($disc[$keys], "float", 0, 0, "Error : Discount for product number : <b>" . ($keys + 1) . "</b> is more than the unitcost."); } $v->isOk($discp[$keys], "float", 0, 20, "Invalid Discount Percentage for product number : <b>" . ($keys + 1) . "</b>."); $v->isOk($unitcost[$keys], "float", 1, 20, "Invalid Unit Price for product number : <b>" . ($keys + 1) . "</b>."); if ($qty < 1) { $v->isOk($qty, "num", 0, 0, "Error : Item Quantity must be at least one. Product number : <b>" . ($keys + 1) . "</b>"); } } } # check whids if (isset($whids)) { foreach ($whids as $keys => $whid) { $v->isOk($whid, "num", 1, 10, "Invalid Store number, please enter all details."); } } $cusnum += 0; # check stkids if (isset($stkids)) { foreach ($stkids as $keys => $stkid) { $v->isOk($stkid, "num", 1, 10, "Invalid Stock number, please enter all details."); } } # check amt if (isset($amt)) { foreach ($amt as $keys => $amount) { $v->isOk($amount, "float", 1, 20, "Invalid Amount, please enter all details."); } } $des = remval($des); # display errors, if any $err = ""; if ($v->isError()) { $errors = $v->getErrors(); foreach ($errors as $e) { $err .= "<li class=err>" . $e["msg"]; } return details($_POST, $err); } if (strlen($client) < 1) { $client = "Cash Sale"; } if (strlen($vatnum) < 1) { $vatnum = ""; } $_POST['client'] = $client; $_POST['vatnum'] = $vatnum; $_POST['telno'] = $telno; $_POST['cordno'] = $cordno; # Get invoice info db_connect(); $sql = "SELECT * FROM pinvoices WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'"; $invRslt = db_exec($sql) or errDie("Unable to get invoice information"); if (pg_numrows($invRslt) < 1) { return "<li>- Invoice Not Found</li>"; } $inv = pg_fetch_array($invRslt); $inv['traddisc'] = $traddisc; $inv['chrgvat'] = $chrgvat; # check if invoice has been printed if ($inv['printed'] == "y") { $error = "<li class='err'> Error : Invoice number <b>{$invid}</b> has already been printed.</li>"; $error .= "<p><input type='button' onClick='JavaScript:history.back();' value='« Correct submission'>"; return $error; } # get department db_conn("exten"); $sql = "SELECT * FROM departments WHERE deptid = '{$deptid}' AND div = '" . USER_DIV . "'"; $deptRslt = db_exec($sql); if (pg_numrows($deptRslt) < 1) { $dept['deptname'] = "<i class='err'>Not Found</i>"; } else { $dept = pg_fetch_array($deptRslt); } # fix those nasty zeros $traddisc += 0; $delchrg += 0; $vatamount = 0; $showvat = TRUE; # insert invoice to DB db_connect(); # begin updating pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF); /* -- Start remove old items -- */ # get selected stock in this invoice $sql = "SELECT * FROM pinv_items WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'"; $stktRslt = db_exec($sql); while ($stkt = pg_fetch_array($stktRslt)) { # update stock(alloc + qty) $sql = "UPDATE stock SET alloc = (alloc - '{$stkt['qty']}') WHERE stkid = '{$stkt['stkid']}' AND div = '" . USER_DIV . "'"; $rslt = db_exec($sql) or errDie("Unable to update stock to Cubit.", SELF); if (strlen($stkt['serno']) > 0) { ext_unresvSer($stkt['serno'], $stkt['stkid']); } } # remove old items $sql = "DELETE FROM pinv_items WHERE invid='{$invid}' AND div = '" . USER_DIV . "'"; $rslt = db_exec($sql) or errDie("Unable to update invoice items in Cubit.", SELF); /* -- End remove old items -- */ $taxex = 0; if (isset($qtys)) { foreach ($qtys as $keys => $value) { /* set the serial ss field for serials selected from list */ if ($sernos_ss[$keys] == "*_*_*CUBIT_SERIAL_SELECT_BOX*_*_*") { $sernos_ss[$keys] = $sernos[$keys]; } if (isset($remprod) && in_array($keys, $remprod)) { if ($sernos[$keys] == $sernos_ss[$keys] && $sernos_ss[$keys] != "") { $chr = substr($sernos[$keys], strlen($sernos[$keys]) - 1, 1); $tab = "ss{$chr}"; /* mark barcoded item as unavailable */ $sql = "UPDATE " . $tab . " SET active='yes' WHERE code = '{$sernos[$keys]}' AND div = '" . USER_DIV . "'"; db_exec($sql); } } else { if (isset($accounts[$keys]) && $accounts[$keys] != 0) { $accounts[$keys] += 0; # Get selamt from selected stock db_conn('core'); $Sl = "SELECT * FROM accounts WHERE accid='{$accounts[$keys]}'"; $Ri = db_exec($Sl) or errDie("Unable to get account data."); $ad = pg_fetch_array($Ri); $amt[$keys] = $qtys[$keys] * $unitcost[$keys]; db_conn('cubit'); $Sl = "SELECT * FROM vatcodes WHERE id='{$vatcodes[$keys]}'"; $Ri = db_exec($Sl); if (pg_num_rows($Ri) < 1) { return details($_POST, "<li class='err'>Please select the vatcode for all your items.</li>"); } $vd = pg_fetch_array($Ri); if ($vd['zero'] == "Yes") { $excluding = "y"; } else { $excluding = ""; } if (TAX_VAT != $vd['vat_amount'] and $vd['vat_amount'] != "0.00") { $showvat = FALSE; } $vr = vatcalc($amt[$keys], $inv['chrgvat'], $excluding, $inv['traddisc'], $vd['vat_amount']); $vrs = explode("|", $vr); $ivat = $vrs[0]; $iamount = $vrs[1]; $vatamount += $ivat; # Check Tax Excempt if ($vd['zero'] == "Yes") { $taxex += $amt[$keys]; $exvat = "y"; } else { $exvat = "n"; } //$newvat+=vatcalc($amt[$keys],$chrgvat,$exvat,$traddisc); $vatcodes[$keys] += 0; $accounts[$keys] += 0; $descriptions[$keys] = remval($descriptions[$keys]); $wtd = $whids[$keys]; # insert invoice items $sql = "INSERT INTO pinv_items(invid, whid, stkid, qty, unitcost,\n\t\t\t\t\t\t\t\tamt, disc, discp, ss, serno, div,vatcode,description,\n\t\t\t\t\t\t\t\taccount)\n\t\t\t\t\t\t\tVALUES('{$invid}', '{$whids[$keys]}', '{$stkids[$keys]}',\n\t\t\t\t\t\t\t\t'{$qtys[$keys]}', '{$unitcost[$keys]}', '{$amt[$keys]}',\n\t\t\t\t\t\t\t\t'{$disc[$keys]}', '{$discp[$keys]}', '', '','" . USER_DIV . "',\n\t\t\t\t\t\t\t\t'{$vatcodes[$keys]}','{$descriptions[$keys]}',\n\t\t\t\t\t\t\t\t'{$accounts[$keys]}')"; $rslt = db_exec($sql) or errDie("Unable to insert invoice items to Cubit.", SELF); } else { # get selamt from selected stock $sql = "SELECT * FROM stock WHERE stkid = '{$stkids[$keys]}' AND div = '" . USER_DIV . "'"; $stkRslt = db_exec($sql); $stk = pg_fetch_array($stkRslt); # Calculate the Discount discount if ($disc[$keys] < 1) { if ($discp[$keys] > 0) { $disc[$keys] = $discp[$keys] / 100 * $unitcost[$keys]; } } else { $discp[$keys] = $disc[$keys] * 100 / $unitcost[$keys]; } # Calculate amount $amt[$keys] = $qtys[$keys] * ($unitcost[$keys] - $disc[$keys]); $Sl = "SELECT * FROM vatcodes WHERE id='{$vatcodes[$keys]}'"; $Ri = db_exec($Sl); if (pg_num_rows($Ri) < 1) { return details($_POST, "<li class=err>Please select the vatcode for all your items.</li>"); } $vd = pg_fetch_array($Ri); if ($vd['zero'] == "Yes") { $excluding = "y"; } else { $excluding = ""; } if (TAX_VAT != $vd['vat_amount'] and $vd['vat_amount'] != "0.00") { $showvat = FALSE; } $vr = vatcalc($amt[$keys], $inv['chrgvat'], $excluding, $inv['traddisc'], $vd['vat_amount']); $vrs = explode("|", $vr); $ivat = $vrs[0]; $iamount = $vrs[1]; $vatamount += $ivat; # Check Tax Excempt if ($stk['exvat'] == 'yes' || $vd['zero'] == "Yes") { $taxex += $amt[$keys]; $exvat = "y"; } else { $exvat = "n"; } $wtd = $whids[$keys]; # insert invoice items $sql = "INSERT INTO pinv_items(invid, whid, stkid, qty,\n\t\t\t\t\t\t\t\tunitcost, amt, disc, discp, ss, serno, div,vatcode)\n\t\t\t\t\t\t\tVALUES('{$invid}', '{$whids[$keys]}', '{$stkids[$keys]}',\n\t\t\t\t\t\t\t\t'{$qtys[$keys]}', '{$unitcost[$keys]}', '{$amt[$keys]}',\n\t\t\t\t\t\t\t\t'{$disc[$keys]}', '{$discp[$keys]}', '{$sernos_ss[$keys]}', '{$sernos[$keys]}',\n\t\t\t\t\t\t\t\t'" . USER_DIV . "','{$vatcodes[$keys]}')"; // $sql = "INSERT INTO pinv_items(invid, whid, stkid, qty, unitcost, amt, disc, discp, div) VALUES('$invid', '$whids[$keys]', '$stkids[$keys]', '$qtys[$keys]', '$unitcost[$keys]','$amt[$keys]', '$disc[$keys]', '$discp[$keys]', '".USER_DIV."')"; $rslt = db_exec($sql) or errDie("Unable to insert invoice items to Cubit.", SELF); if (strlen($sernos[$keys]) > 0) { ext_resvSer($sernos[$keys], $stk['stkid']); } # update stock(alloc + qty) $sql = "UPDATE stock SET alloc = (alloc + '{$qtys[$keys]}') WHERE stkid = '{$stkids[$keys]}' AND div = '" . USER_DIV . "'"; $rslt = db_exec($sql) or errDie("Unable to update stock to Cubit.", SELF); } } # everything is set place done button $_POST["done"] = " | <input name='doneBtn' type='submit' value='Process'>"; } } else { $_POST["done"] = ""; } db_conn('cubit'); $Sl = "SELECT * FROM vatcodes WHERE id='{$delvat}'"; $Ri = db_exec($Sl); // /*if(pg_num_rows($Ri)>0) { // */$taxex += $delchrg; // } $vd = pg_fetch_array($Ri); if ($vd['zero'] == "Yes") { $excluding = "y"; } else { $excluding = ""; } if (TAX_VAT != $vd['vat_amount'] and $vd['vat_amount'] != "0.00") { $showvat = FALSE; } $_POST['showvat'] = $showvat; $vr = vatcalc($delchrg, $inv['chrgvat'], $excluding, $inv['traddisc'], $vd['vat_amount']); $vrs = explode("|", $vr); $ivat = $vrs[0]; $iamount = $vrs[1]; $vatamount += $ivat; /* --- ----------- Clac --------------------- */ ##----------------------NEW---------------------- $sub = 0.0; if (isset($amt)) { $sub = sprint(array_sum($amt)); } $VATP = TAX_VAT; if ($chrgvat == "exc") { $taxex = sprint($taxex - $taxex * $traddisc / 100); $subtotal = sprint($sub + $delchrg); $traddiscmt = sprint($subtotal * $traddisc / 100); $subtotal = sprint($subtotal - $traddiscmt); // $VAT=sprint(($subtotal-$taxex)*$VATP/100); $VAT = sprint($vatamount); $SUBTOT = $sub; $TOTAL = sprint($subtotal + $VAT); $delexvat = sprint($delchrg); } elseif ($chrgvat == "inc") { $ot = $taxex; $taxex = sprint($taxex - $taxex * $traddisc / 100); $subtotal = sprint($sub + $delchrg); $traddiscmt = sprint($subtotal * $traddisc / 100); $subtotal = sprint($subtotal - $traddiscmt); // $VAT=sprint(($subtotal-$taxex)*$VATP/(100+$VATP)); $VAT = sprint($vatamount); $SUBTOT = sprint($sub); $TOTAL = sprint($subtotal); $delexvat = sprint($delchrg); $traddiscmt = sprint($traddiscmt); } else { $subtotal = sprint($sub + $delchrg); $traddiscmt = sprint($subtotal * $traddisc / 100); $subtotal = sprint($subtotal - $traddiscmt); $VAT = sprint(0); $SUBTOT = $sub; $TOTAL = $subtotal; $delexvat = sprint($delchrg); } $Sl = "SELECT * FROM posround"; $Ri = db_exec($Sl); $data = pg_fetch_array($Ri); if ($data['setting'] == "5cent") { if (sprint(floor(sprint($TOTAL / 0.05))) != sprint($TOTAL / 0.05)) { $otot = $TOTAL; $nTOTAL = sprint(sprint(floor($TOTAL / 0.05)) * 0.05); $rounding = $otot - $nTOTAL; } else { $rounding = 0; } } else { $rounding = 0; } //print sprint(floor($TOTAL/0.05)); #get accno if invoice is on credit if ($cusnum != "0") { $get_acc = "SELECT * FROM customers WHERE cusnum = '{$cusnum}' LIMIT 1"; $run_acc = db_exec($get_acc) or errDie("Unable to get customer information"); if (pg_numrows($run_acc) < 1) { $accno = ""; } else { $arr = pg_fetch_array($run_acc); $cusacc = $arr['accno']; } } else { $cusacc = ""; } // die($cusnum); # insert invoice to DB $sql = "UPDATE pinvoices SET pcredit='{$pcredit}',cusnum='{$cusnum}',delvat='{$delvat}',rounding='{$rounding}',pcash='{$pcash}',pcheque='{$pcheque}',\n\t\tpcc='{$pcc}',deptid='{$deptid}',deptname = '{$dept['deptname']}', cusname = '{$client}', cordno = '{$cordno}', ordno = '{$ordno}',chrgvat = '{$chrgvat}',\n\t\tsalespn = '{$salespn}', odate = '{$odate}', traddisc = '{$traddisc}', delchrg = '{$delchrg}', subtot = '{$SUBTOT}', vat = '{$VAT}', total = '{$TOTAL}',\n\t\tbalance = '{$pcredit}', comm = '{$comm}', discount='{$traddiscmt}', delivery='{$delexvat}', vatnum='{$vatnum}', cusacc = '{$cusacc}', telno='{$telno}'\n\t\tWHERE invid = '{$invid}' AND div = '" . USER_DIV . "'"; $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF); # remove old data $sql = "DELETE FROM pinv_data WHERE invid='{$invid}' AND div = '" . USER_DIV . "'"; $rslt = db_exec($sql) or errDie("Unable to update invoice data in Cubit.", SELF); # put in new data $sql = "INSERT INTO pinv_data(invid, dept, customer, div) VALUES('{$invid}', '{$dept['deptname']}', '{$client}', '" . USER_DIV . "')"; $rslt = db_exec($sql) or errDie("Unable to insert invoice data to Cubit.", SELF); # commit updatin if (strlen($bar) > 0) { /* check if there a stock item with global barcode matching input barcode */ $sql = "SELECT * FROM stock WHERE bar='{$bar}' AND div = '" . USER_DIV . "'"; $barRslt = db_exec($sql); if (pg_num_rows($barRslt) <= 0) { /* fetch last character of barcode */ $chr = substr($bar, strlen($bar) - 1, 1); /* invalid barcode */ if (!is_numeric($chr)) { return details($_POST, "The code you selected is invalid"); } /* which barcode table to scan for stock id */ $tab = "ss{$chr}"; $stid = barext_dbget($tab, 'code', $bar, 'stock'); $stab = "serial{$chr}"; $sstid = serext_dbget($stab, 'serno', $bar, 'stkid'); /* non-existing barcode, check for serial number */ if ($stid <= 0) { if ($sstid <= 0) { return details($_POST, "<li class='err'>The serial number/bar code you selected is not in the system or is not available.</li>"); } if (serext_dbnum($stab, 'serno', $bar, 'stkid') > 1) { return details($_POST, "<li class='err'>Duplicate serial numbers found, please scan barcode or select stock item.</li>"); } /* mark barcoded item as unavailable */ $sql = "UPDATE " . $stab . " SET rsvd='y' WHERE serno='{$bar}'"; db_exec($sql); $serno_bar = "{$bar}"; $stid = $sstid; } else { if ($sstid > 0) { return details($_POST, "<li class='err'>A serial and barcode with same value, please scan other value or select product manually.</li>"); } /* mark barcoded item as unavailable */ $sql = "UPDATE " . $tab . " SET active='no' WHERE code='{$bar}' AND div='" . USER_DIV . "'"; db_exec($sql); $serno_bar = "{$bar}"; } /* fetch stock row for selected item */ $sql = "SELECT * FROM stock WHERE stkid = '{$stid}' AND div = '" . USER_DIV . "'"; $barRslt = db_exec($sql); } else { $serno_bar = ""; } $s = pg_fetch_array($barRslt); /* allocate stock item */ $sql = "UPDATE stock SET alloc = (alloc + '1') WHERE stkid = '{$s['stkid']}' AND div = '" . USER_DIV . "'"; db_exec($sql) or errDie("Unable to update stock to Cubit.", SELF); $sql = "INSERT INTO pinv_items(invid, whid, stkid, qty, unitcost, amt,\n\t\t\t\t\tdisc, discp, ss, serno, div)\n\t\t\t\tVALUES('{$invid}', '{$s['whid']}', '{$s['stkid']}', '1','{$s['selamt']}',\n\t\t\t\t\t'{$s['selamt']}', '0', '0','{$bar}', '{$serno_bar}', '" . USER_DIV . "')"; db_exec($sql) or errDie("Unable to insert invoice items to Cubit.", SELF); } pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF); /* --- Start button Listeners --- */ if (isset($doneBtn)) { # check if stock was selected(yes = put done button) db_connect(); $sql = "SELECT stkid FROM pinv_items WHERE invid = '{$inv['invid']}' AND div = '" . USER_DIV . "'"; $crslt = db_exec($sql); if (pg_numrows($crslt) < 1) { $error = "<li class='err'> Error : Invoice number has no items."; return details($_POST, $error); } $TOTAL = sprint($TOTAL - $rounding); #check for credit limit if ($cusnum != "0") { #customer is selected ... get info $sql = "SELECT * FROM customers WHERE cusnum = '{$cusnum}' AND location != 'int' AND div = '" . USER_DIV . "'"; $custRslt = db_exec($sql) or errDie("Unable to view customer"); if (pg_numrows($custRslt) < 1) { $cust['balance'] = "0"; $cust['creditlimit'] = "0"; } else { $cust = pg_fetch_array($custRslt); } #customer is set check for response if ($pcredit + $cust['balance'] > $cust['credlimit']) { #limit reached ... check for block db_conn("cubit"); $get_check = "SELECT value FROM set WHERE label = 'CUST_INV_WARN' LIMIT 1"; $run_check = db_exec($get_check) or errDie("Unable to get credit limit response setting"); if (pg_numrows($run_check) < 1) { #no setting ? do nothing .... } else { $sarr = pg_fetch_array($run_check); if ($sarr['value'] == "block") { #block account ... return details($_POST, "<li class='err'>Warning : Customers Credit limit of <b>" . CUR . " " . sprint($cust["credlimit"]) . "</b> has been exceeded.</li>"); } } # Check permissions if (!perm("invoice-limit-override.php")) { return details($_POST, "<li class='err'>Warning : Customers Credit limit of <b>" . CUR . " " . sprint($cust["credlimit"]) . "</b> has been exceeded.</li>"); } } } if ($pcash + $pcheque + $pcc + $pcredit < $TOTAL) { return details($_POST, "<li class='err'>The total of all the payments is less than the invoice total</li>"); } $change = sprint(sprint($pcash + $pcheque + $pcc + $pcredit) - sprint($TOTAL)); $pcash = sprint($pcash - $change); if ($pcash < 0) { $pcash = 0; } if (sprint($pcash + $pcheque + $pcc + $pcredit) != sprint($TOTAL)) { return details($_POST, "<li class='err'>The total of all the payments is not equal to the invoice total.<br>\n\t\t\t(You can only overpay with cash)</li>"); } # insert quote to DB $sql = "UPDATE pinvoices SET done = 'y' WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'"; $rslt = db_exec($sql) or errDie("Unable to update invoice status in Cubit.", SELF); # print the invoice $OUTPUT = "\n\t\t\t\t\t<script>printer2('pos-invoice-print.php?invid={$invid}');</script>\n\t\t\t\t\t<input type='button' value='Create New POS Invoice' onClick=\"move('pos-invoice-new-no-neg.php');\">"; require "template.php"; } elseif (isset($saveBtn)) { // Final Laytout $write = "\n\t\t<table " . TMPL_tblDflts . ">\n\t\t\t<tr>\n\t\t\t\t<th>New Point of Sale Invoice Saved</th>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Invoice for <b>{$client}</b> has been saved.</td>\n\t\t\t</tr>\n\t\t</table>\n\t\t<p>\n\t\t<table " . TMPL_tblDflts . ">\n\t\t\t<tr>\n\t\t\t\t<th>Quick Links</th>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td><a href='pos-invoice-new-no-neg.php'>New Point of Sale Invoice</a></td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td><a href='pos-invoice-list.php'>View Point of Sale Invoices</a></td>\n\t\t\t</tr>\n\t\t\t<script>document.write(getQuicklinkSpecial());</script>\n\t\t</table>"; return $write; } elseif (isset($cancel)) { // Final Laytout $write = "\n\t\t<table " . TMPL_tblDflts . ">\n\t\t\t<tr>\n\t\t\t\t<th>New Point of Sale Invoice Saved</th>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Invoice for <b>{$client}</b> has been saved.</td>\n\t\t\t</tr>\n\t\t</table>\n\t\t<p>\n\t\t<table " . TMPL_tblDflts . ">\n\t\t\t<tr>\n\t\t\t\t<th>Quick Links</th>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td><a href='pos-invoice-new-no-neg.php'>New Point of Sale Invoice</a></td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td><a href='pos-invoice-list.php'>View Point of Sale Invoices</a></td>\n\t\t\t</tr>\n\t\t\t<script>document.write(getQuicklinkSpecial());</script>\n\t\t</table>"; return $write; } else { if (isset($wtd)) { $_POST['wtd'] = $wtd; } return details($_POST); } /* --- End button Listeners --- */ }
function write($_POST) { # Get vars extract($_POST); if (isset($back)) { return edit($_POST); } # validate input require_lib("validate"); $v = new validate(); $v->isOk($stkid, "num", 1, 50, "Invalid stock id."); $v->isOk($whid, "num", 1, 50, "Invalid stock id."); $v->isOk($unitnum, "num", 1, 50, "Invalid number of units."); $v->isOk($cost, "float", 1, 50, "Invalid cost amount per unit."); $v->isOk($cacc, "num", 1, 50, "Invalid contra account."); $v->isOk($tipo, "string", 1, 50, "Invalid type."); $v->isOk($det, "string", 0, 255, "Invalid Details."); $v->isOk($date, "string", 4, 14, "Invalid date."); # check if duplicate serial number selected, remove blanks if (isset($sernos)) { if (!ext_isUnique(ext_remBlnk($sernos))) { $v->isOk("##", "num", 0, 0, "Error : Serial Numbers must be unique per line item."); } } # Display errors, if any if ($v->isError()) { $confirm = ""; $errors = $v->getErrors(); foreach ($errors as $e) { $confirm .= "<li class='err'>" . $e["msg"] . "</li>"; } $confirm .= "<p><input type='button' onClick='JavaScript:history.back();' value='« Correct submission'>"; return $confirm; } # Select Stock db_connect(); $sql = "SELECT * FROM stock WHERE stkid = '{$stkid}' AND div = '" . USER_DIV . "'"; $stkRslt = db_exec($sql) or errDie("Unable to access databse.", SELF); if (pg_numrows($stkRslt) < 1) { return "<li> Invalid Stock ID.</li>"; } else { $stk = pg_fetch_array($stkRslt); } if ($stk['units'] < 0) { $min_stock = abs($stk['units']); if ($unitnum < $min_stock) { $min_stock = $unitnum; } } else { $min_stock = 0; } # Get warehouse name db_conn("exten"); $sql = "SELECT * FROM warehouses WHERE whid = '{$whid}' AND div = '" . USER_DIV . "'"; $whRslt = db_exec($sql); $wh = pg_fetch_array($whRslt); $refnum = getrefnum(); # calculate actual cost amount $temp = $cost; $cost = sprint($cost * $unitnum); if ($tipo == 'Increase') { # Update Stock db_connect(); $sql = "UPDATE stock\n\t\t\t\tSET units = (units + '{$unitnum}'),\n\t\t\t\t\tlcsprice = '{$temp}',\n\t\t\t\t\tcsamt = (csamt + {$cost}),\n\t\t\t\t\tcsprice = (\n\t\t\t\t\t\tSELECT\n\t\t\t\t\t\t\tCASE WHEN (units != -{$unitnum}) THEN (csamt+{$cost})/(units+{$unitnum})\n\t\t\t\t\t\t\tELSE 0\n\t\t\t\t\t\t\tEND\n\t\t\t\t\t\tFROM cubit.stock\n\t\t\t\t\t\tWHERE stkid='{$stkid}' AND div='" . USER_DIV . "'\n\t\t\t\t\t)\n\t\t\t\tWHERE stkid = '{$stkid}' AND div = '" . USER_DIV . "'"; // $rslt = db_exec($sql) or errDie("Unable to insert stock to Cubit.",SELF); $sdate = $date; recordtrans('stock', '1', '1', $sdate, $unitnum, $cost, $temp, '', $stkid); db_connect(); if ($unitnum == 0) { $csprice = 0; } else { $csprice = sprint($cost / $unitnum); } recordtrans('stock', '1', '0', $sdate, $unitnum, $cost, $csprice, $det, $stk['stkid']); # stkid, stkcod, stkdes, trantype, edate, qty, csamt, details //stockrec($stk['stkid'], $stk['stkcod'], $stk['stkdes'], 'dt', $sdate, $unitnum, $cost, $det); $sql = "INSERT INTO stockrec (edate, stkid, stkcod, stkdes, trantype, qty, csprice, csamt, details, div)\n\t\t\t\tVALUES('{$sdate}', '{$stk['stkid']}', '{$stk['stkcod']}', '{$stk['stkdes']}', 'inc', '{$unitnum}', '{$cost}', '{$csprice}', '{$det}', '" . USER_DIV . "')"; // $recRslt = db_exec($sql); db_connect(); $sql = "SELECT * FROM stock WHERE stkid = '{$stkid}' AND div = '" . USER_DIV . "'"; $stkRslt = db_exec($sql) or errDie("Unable to access databse.", SELF); if (pg_numrows($stkRslt) < 1) { return "<li> Invalid Stock ID."; } else { $stk = pg_fetch_array($stkRslt); } # balance transaction # Debit STock account and Credit Contra Account recordtrans('journal', $wh['stkacc'], $cacc, $date, $refnum, $cost, '0', $det); //writetrans($wh['stkacc'], $cacc, $date, $refnum, $cost, $det); $cc_trantype = cc_TranTypeAcc($wh['stkacc'], $cacc); } else { if ($tipo == 'Decrease') { # Update Stock db_connect(); $sql = "UPDATE stock SET csamt = (csamt - {$cost}), units = (units - '{$unitnum}') WHERE stkid = '{$stkid}' AND div = '" . USER_DIV . "'"; // $rslt = db_exec($sql) or errDie("Unable to insert stock to Cubit.",SELF); //$sdate = date("Y-m-d"); $sdate = $date; recordtrans('stock', '0', '0', $sdate, $unitnum, $cost, '0', $det, $stkid); recordtrans('stock', '0', '1', $sdate, $unitnum, $cost, $csprice, $det, $stk['stkid']); # stkid, stkcod, stkdes, trantype, edate, qty, csamt, details //stockrec($stk['stkid'], $stk['stkcod'], $stk['stkdes'], 'ct', $sdate, $unitnum, $cost, $det); db_connect(); if ($unitnum == 0) { $csprice = 0; } else { $csprice = sprint($cost / $unitnum); } $sql = "INSERT INTO stockrec(edate, stkid, stkcod, stkdes, trantype, qty, csprice, csamt, details, div)\n\t\t\t\tVALUES('{$sdate}', '{$stk['stkid']}', '{$stk['stkcod']}', '{$stk['stkdes']}', 'dec', '-{$unitnum}', '{$cost}', '{$csprice}', '{$det}', '" . USER_DIV . "')"; //$recRslt = db_exec($sql); db_connect(); $sql = "SELECT * FROM stock WHERE stkid = '{$stkid}' AND div = '" . USER_DIV . "'"; $stkRslt = db_exec($sql) or errDie("Unable to access databse.", SELF); if (pg_numrows($stkRslt) < 1) { return "<li> Invalid Stock ID.</li>"; } else { $stk = pg_fetch_array($stkRslt); } # Units if ($stk['units'] != 0) { $sql = "UPDATE stock SET csprice = (csamt/units) WHERE stkid = '{$stkid}' AND div = '" . USER_DIV . "'"; // $rslt = db_exec($sql) or errDie("Unable to insert stock to Cubit.",SELF); } else { $sql = "UPDATE stock SET csprice = '{$csprice}' WHERE stkid = '{$stkid}' AND div = '" . USER_DIV . "'"; // $rslt = db_exec($sql) or errDie("Unable to insert stock to Cubit.",SELF); } if (isset($sernos)) { foreach ($sernos as $skey => $serno) { ext_OutSer($serno, $stkid, $det, $refnum, "tran"); } } recordtrans('journal', $cacc, $wh['stkacc'], $date, $refnum, $cost, '0', $det); # Debit Contra Account and Credit Stock account //writetrans($cacc, $wh['stkacc'], $date, $refnum, $cost, $det); $cc_trantype = cc_TranTypeAcc($cacc, $wh['stkacc']); } } if ($cc_trantype != false) { $cc = "<script> CostCenter('{$cc_trantype}', 'Stock Transaction', '{$date}', '{$det}', '{$cost}', ''); </script>"; } else { $cc = ""; } $write = "\n\t\t\t{$cc}\n\t\t\t<table " . TMPL_tblDflts . " width='50%'>\n\t\t\t\t<tr>\n\t\t\t\t\t<th>Stock Balance Transaction</th>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='datacell'>\n\t\t\t\t\t<td>Stock Balance Transaction for stock, {$stk['stkdes']} ({$stk['stkcod']}) has been successfully recorded.</td>\n\t\t\t\t</tr>\n\t\t\t</table>" . mkQuickLinks(ql("stock-add.php", "Add Stock"), ql("stock-view.php", "View Stock")); return $write; }
function confirm($_POST) { # get vars extract($_POST); # validate input require_lib("validate"); $v = new validate(); $v->isOk($stkid, "num", 1, 50, "Invalid stock id."); if (!ext_isUnique(ext_remBlnk($sers))) { $v->isOk("error", "num", 1, 1, "Error : Serial numbers must be unique."); } foreach ($sers as $key => $serno) { if (strlen($serno) > 0) { $v->isOk($serno, "string", 1, 20, "Error : Invalid Serial number."); if (preg_match("/[-\\/\\'\"]/", $serno)) { $v->addError(0, "Error: Serial number cannot contain any of the following characters - / \\ ' \""); } } } # display errors, if any if ($v->isError()) { $confirm = ""; $errors = $v->getErrors(); foreach ($errors as $e) { $confirm .= "<li class='err'>{$e['msg']}</li>"; } return $confirm .= "<p><input type='button' onClick='JavaScript:history.back();' value='« Correct submission'>"; } db_connect(); $sql = "SELECT stkid, stkcod, stkdes, units FROM stock WHERE stkid = '{$stkid}' AND div = '" . USER_DIV . "'"; $stkRslt = db_exec($sql) or errDie("Unable to retrieve stocks from database."); $stk = pg_fetch_array($stkRslt); // Layout $confirm = "\r\n\t\t<h3>Confirm Serial Numbers</h3>\r\n\t\t<form action='" . SELF . "' method='POST'>\r\n\t\t<table " . TMPL_tblDflts . ">\r\n\t\t\t<input type='hidden' name='key' value='write'>\r\n\t\t\t<input type='hidden' name='stkid' value='{$stkid}'>\r\n\t\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t\t<td>Stock</td>\r\n\t\t\t\t<td align='center'>{$stk['stkcod']} {$stk['stkdes']}</td>\r\n\t\t\t</tr>\r\n\t\t\t<tr><td><br></td></tr>\r\n\t\t\t<tr>\r\n\t\t\t\t<td align='right'><input type='button' value='Back' onclick='javascript:history.back();'></td>\r\n\t\t\t\t<td valign='left'><input type='submit' value='Write »'></td>\r\n\t\t\t</tr>\r\n\t\t\t<tr>\r\n\t\t\t\t<th colspan='2'>Serial Numbers</th>\r\n\t\t\t</tr>"; foreach ($sers as $key => $serno) { if (strlen($serno) < 1) { continue; } $confirm .= "\r\n\t\t\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t\t\t<td align='center' colspan='2'><input type='hidden' name='sers[]' size='20' value='{$serno}'>{$serno}</td>\r\n\t\t\t\t</tr>"; } $confirm .= "\r\n\t\t\t\t<tr><td><br></td></tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td align='right'><input type='button' value='Back' onclick='javascript:history.back();'></td>\r\n\t\t\t\t\t<td valign='left'><input type='submit' value='Write »'></td>\r\n\t\t\t\t</tr>\r\n\t\t\t</table>\r\n\t\t\t</form>\r\n\t\t\t<p>\r\n\t\t\t<table border=0 cellpadding='2' cellspacing='1'>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<th>Quick Links</th>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t\t\t<td><a href='pricelist-view.php'>View Price Lists</a></td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t\t\t<td><a href='main.php'>Main Menu</a></td>\r\n\t\t\t\t</tr>\r\n\t\t\t</table>"; return $confirm; }
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='« 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 --- */ }
function write($_POST) { #get vars extract($_POST); # validate input require_lib("validate"); $v = new validate(); $v->isOk($purid, "num", 1, 20, "Invalid Order number."); $v->isOk($refno, "string", 0, 255, "Invalid Delivery Reference number."); $v->isOk($remarks, "string", 0, 255, "Invalid Remarks."); $ddate = $d_year . "-" . $d_month . "-" . $d_day; if (!checkdate($d_month, $d_day, $d_year)) { $v->isOk($ddate, "num", 1, 1, "Invalid Date."); } # used to generate errors $error = "asa@"; # check quantities if (isset($recvd)) { foreach ($recvd as $sk => $keys) { $v->isOk($qtys[$keys], "float", 1, 15, "Invalid Quantity for product number : <b>" . ($keys + 1) . "</b>"); $v->isOk($unitcost[$keys], "float", 0, 20, "Invalid Unit Price for product number : <b>" . ($keys + 1) . "</b>."); $v->isOk($cunitcost[$keys], "float", 0, 20, "Invalid Foreign currency Unit Price for product number : <b>" . ($keys + 1) . "</b>."); $v->isOk($duty[$keys], "float", 0, 20, "Invalid Duty Charges for product number : <b>" . ($keys + 1) . "</b>."); $v->isOk($dutyp[$keys], "float", 0, 20, "Invalid Duty Charges Percentage for product number : <b>" . ($keys + 1) . "</b>."); if ($qtys[$keys] < 1) { $v->isOk($qtys[$keys], "num", 0, 0, "Error : Item Quantity must be at least one. Product number : <b>" . ($keys + 1) . "</b>"); } if ($qtys[$keys] > $qts[$keys]) { $v->isOk($qtys[$keys], "num", 0, 0, "Error : Item Quantity returned is more than the bought quantity : <b>" . ($keys + 1) . "</b>"); } $v->isOk($stkids[$keys], "num", 1, 10, "Invalid Stock number, please enter all details."); # Nasty Zeros $unitcost[$keys] += 0; $cunitcost[$keys] += 0; $duty[$keys] += 0; $dutyp[$keys] += 0; } if (isset($sers)) { foreach ($sers as $stkid => $sernos) { if (!ext_isUnique(ext_remBlnk($sernos))) { $v->isOk("error", "num", 1, 1, "Error : Serial numbers must be unique per Stock Item."); } else { foreach ($recvd as $sk => $keys) { if (isset($sernos[$keys]) && $v->isOk($sernos[$keys], "string", 1, 20, "Error : Invalid Serial number.")) { if (ext_findSer($sernos[$keys]) != false) { $v->isOk("#", "string", 1, 20, "Error : Serial number already exists."); } } } } } } } else { $v->isOk("#", "num", 0, 0, "Error : Items Not Selected."); } # display errors, if any $err = ""; if ($v->isError()) { $errors = $v->getErrors(); foreach ($errors as $e) { $err .= "<li class='err'>" . $e["msg"] . "</li>"; } $_POST['done'] = ""; return details($_POST, $err); } //print $td; exit; # Get Order info db_connect(); $sql = "SELECT * FROM purch_int WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'"; $purRslt = db_exec($sql) or errDie("Unable to get Order information"); if (pg_numrows($purRslt) < 1) { return "<li>- Order Not Found</li>"; } $pur = pg_fetch_array($purRslt); $TD = $pur["pdate"]; # CHECK IF THIS DATE IS IN THE BLOCKED RANGE $blocked_date_from = getCSetting("BLOCKED_FROM"); $blocked_date_to = getCSetting("BLOCKED_TO"); if (strtotime($TD) >= strtotime($blocked_date_from) and strtotime($TD) <= strtotime($blocked_date_to) and !user_is_admin(USER_ID)) { return "<li class='err'>Period Range Is Blocked. Only an administrator can process entries within this period.</li>"; } # check if Order has been received if ($pur['received'] == "y") { $error = "<li class='err'> Error : Order number <b>{$purid}</b> has already been received.</li>"; $error .= "<p><input type='button' onClick='JavaScript:history.back();' value='« Correct submission'>"; return $error; } # Get selected supplier info db_connect(); $sql = "SELECT * FROM suppliers WHERE supid = '{$pur['supid']}' AND div = '" . USER_DIV . "'"; $supRslt = db_exec($sql) or errDie("Unable to get customer information"); $sup = pg_fetch_array($supRslt); # get department db_conn("exten"); $sql = "SELECT * FROM departments WHERE deptid = '{$pur['deptid']}' AND div = '" . USER_DIV . "'"; $deptRslt = db_exec($sql); if (pg_numrows($deptRslt) < 1) { $dept['deptname'] = "<i class='err'>Not Found</i>"; } else { $dept = pg_fetch_array($deptRslt); } # Insert Order to DB db_connect(); # begin updating pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF); db_conn(PRD_DB); # get last ref number $refnum = getrefnum(); db_connect(); # amount of stock in $totstkamt = array(); $resub = 0; foreach ($recvd as $sk => $keys) { if ($qtys[$keys] < 1) { continue; } /* -- Calculations -- */ # Calculate cost amount bought $amt[$keys] = $qtys[$keys] * $unitcost[$keys]; $amt[$keys] += $duty[$keys] * $pur['xrate']; # Calculate percentage from subtotal $perc[$keys] = $amt[$keys] / ($pur['subtot'] * $pur['xrate']) * 100; # Get percentage from shipping charges $shipchrg[$keys] = $perc[$keys] / 100 * ($pur['shipchrg'] * $pur['xrate']); # add shipping charges to amt $amt[$keys] = round($amt[$keys] + $shipchrg[$keys], 2); $resub += $amt[$keys]; /* -- End Calculations --*/ # Get selamt from selected stock $sql = "SELECT * FROM stock WHERE stkid = '{$stkids[$keys]}' AND div = '" . USER_DIV . "'"; $stkRslt = db_exec($sql); $stk = pg_fetch_array($stkRslt); if ($stk['units'] < 0) { $min_stock = abs($stk['units']); if ($qtys[$keys] < $min_stock) { $min_stock = $qtys[$keys]; } } else { $min_stock = 0; } # Update Order items $sql = "UPDATE purint_items SET rqty = (rqty + '{$qtys[$keys]}') WHERE stkid = '{$stkids[$keys]}' AND purid='{$purid}' AND div = '" . USER_DIV . "'"; $rslt = db_exec($sql) or errDie("Unable to insert Order items to Cubit.", SELF); # update stock(ordered + qty, units + qty, csamt + (csamt + amt)) $sql = "UPDATE stock SET ordered = (ordered - '{$qtys[$keys]}'), units = (units + '{$qtys[$keys]}' +'{$min_stock}'), csamt = (csamt + '{$amt[$keys]}') WHERE stkid = '{$stkids[$keys]}' AND div = '" . USER_DIV . "'"; $rslt = db_exec($sql) or errDie("Unable to update stock to Cubit.", SELF); if (isset($sers[$stkids[$keys]][$keys])) { ext_InSer($sers[$stkids[$keys]][$keys], $stkids[$keys], $sup['supname'], $pur['purnum'], "pur", $TD); $serial = $sers[$stkids[$keys]][$keys]; db_connect(); $sql = "INSERT INTO pserec(purid, purnum, stkid, serno, div)\n\t\t\t\tVALUES('{$purid}', '{$pur['purnum']}', '{$stkids[$keys]}', '{$serial}', '" . USER_DIV . "')"; $rslt = db_exec($sql) or errDie("Unable to update stock serials in Cubit.", SELF); } # get selected stock $sql = "SELECT * FROM stock WHERE stkid = '{$stkids[$keys]}' AND div = '" . USER_DIV . "'"; $stkRslt = db_exec($sql); $stk = pg_fetch_array($stkRslt); # stkid, stkcod, stkdes, trantype, edate, qty, csamt, details $sdate = date("Y-m-d"); stockrec($stk['stkid'], $stk['stkcod'], $stk['stkdes'], 'dt', $TD, $qtys[$keys], $amt[$keys], "Stock Received from Supplier : {$sup['supname']} - Order No. {$pur['purnum']}"); db_connect(); $cspric = sprint($amt[$keys] / $qtys[$keys]); $sql = "INSERT INTO stockrec(edate, stkid, stkcod, stkdes, trantype, qty, csprice, csamt, details, div)\n\t\t\tVALUES('{$TD}', '{$stk['stkid']}', '{$stk['stkcod']}', '{$stk['stkdes']}', 'purchase', '{$qtys[$keys]}', '{$amt[$keys]}', '{$cspric}', 'Stock Received from Supplier : {$sup['supname']} - Order No. {$pur['purnum']}', '" . USER_DIV . "')"; $recRslt = db_exec($sql); # keep records for transactions if (isset($totstkamt[$stk['whid']])) { $totstkamt[$stk['whid']] += $amt[$keys]; } else { $totstkamt[$stk['whid']] = $amt[$keys]; } # Just wanted to fix the xxx.xxxxxxe-x value # $csprice = round(($stk['csamt']/$stk['units']), 2); if ($stk['units'] > 0) { $csprice = round($stk['csamt'] / $stk['units'], 2); } else { $csprice = round($stk['csprice'], 2); } # update stock(csprice = (csamt/units)) $sql = "UPDATE stock SET csprice = '{$csprice}', lcsprice = '{$cspric}' WHERE stkid = '{$stkids[$keys]}' AND div = '" . USER_DIV . "'"; $rslt = db_exec($sql) or errDie("Unable to update stock to Cubit.", SELF); # check if there are any outstanding items $sql = "SELECT * FROM purint_items WHERE purid = '{$purid}' AND (qty - rqty) > '0' AND div = '" . USER_DIV . "'"; $stkdRslt = db_exec($sql); # if none the set to received if (pg_numrows($stkdRslt) < 1) { # update surch_int(received = 'y') $sql = "UPDATE purch_int SET received = 'y' WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'"; $rslt = db_exec($sql) or errDie("Unable to update international Orders in Cubit.", SELF); } } if ($min_stock > 0) { $cost = sprint($unitcost[$keys] * $min_stock); $td = "{$d_year}-{$d_month}-{$d_day}"; db_conn("exten"); $sql = "SELECT stkacc,cosacc FROM warehouses WHERE whid = '{$stk['whid']}' AND div = '" . USER_DIV . "'"; $whRslt = db_exec($sql); $wh = pg_fetch_array($whRslt); $stockacc = $wh['stkacc']; $cosacc = $wh['cosacc']; db_connect(); $Sl = "UPDATE stock SET csamt = (csamt - '{$cost}'),units=(units-'{$min_stock}') WHERE stkid='{$stkids[$keys]}'"; $Ri = db_exec($Sl); writetrans($cosacc, $stockacc, $TD, $refnum, $cost, "Cost Of Sales for stock sold before international purchase {$pur['purnum']}"); stockrec($stk['stkid'], $stk['stkcod'], $stk['stkdes'], 'ct', $td, 0, $cost, "Cost Of Sales for stock sold before international purchase {$pur['purnum']}"); db_connect(); $Sl = "INSERT INTO pcost(purnum,cost,qty,rqty,stkid) VALUES ('{$pur['purnum']}','{$unitcost[$keys]}','{$min_stock}','0','{$stk['stkid']}')"; $Ri = db_exec($Sl); } if (strlen($refno) > 0) { if (strlen($pur['refno']) > 0) { $refno = "{$pur['refno']}-{$refno}"; } else { $refno = $refno; } } else { $refno = $pur['refno']; } # Update Order on the DB $fresub = sprint($resub / $pur['xrate']); $sql = "UPDATE purch_int SET rsubtot = (rsubtot + '{$fresub}'), rlsubtot = (rlsubtot + '{$resub}'), refno = '{$refno}', remarks = '{$remarks}', ddate = '{$ddate}' WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'"; $rslt = db_exec($sql) or errDie("Unable to update Order in Cubit.", SELF); /* --- Transactions --- */ db_conn(PRD_DB); $refnum = getrefnum(); /* - Start Hooks - */ $vatacc = gethook("accnum", "salesacc", "name", "VAT"); $cvacc = gethook("accnum", "pchsacc", "name", "Cost Variance"); /* - End Hooks - */ # record transaction from data foreach ($totstkamt as $whid => $wamt) { # Get whouse info db_conn("exten"); $sql = "SELECT stkacc,conacc FROM warehouses WHERE whid = '{$whid}' AND div = '" . USER_DIV . "'"; $whRslt = db_exec($sql); $wh = pg_fetch_array($whRslt); # Debit Stock and Credit Suppliers control writetrans($wh['stkacc'], $wh['conacc'], $TD, $refnum, $wamt, "International Stock Order No. {$pur['purnum']} Received from Supplier {$sup['supname']}."); } # commit updating pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF); /* Start moving if Order received and invoiced */ # Get Order info db_connect(); $sql = "SELECT * FROM purch_int WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'"; $purRslt = db_exec($sql) or errDie("Unable to get Order information"); if (pg_numrows($purRslt) < 1) { return "<li>- Order Not Found</li>"; } $pur = pg_fetch_array($purRslt); if ($pur['received'] == "y" && $pur['invcd'] == 'y') { # Copy Order db_conn($pur['prd']); $sql = "INSERT INTO purch_int(purid, deptid, supid, supaddr, terms, pdate, ddate, xrate, fcid, curr, tax, shipchrg, fshipchrg, duty, subtot, total, balance, fbalance, remarks, refno, received, done, div, purnum)"; $sql .= " VALUES('{$purid}', '{$pur['deptid']}', '{$pur['supid']}', '{$pur['supaddr']}', '{$pur['terms']}', '{$pur['pdate']}', '{$pur['ddate']}', '{$pur['xrate']}', '{$pur['fcid']}', '{$pur['curr']}', '{$pur['tax']}', '{$pur['shipchrg']}', '{$pur['fshipchrg']}', '{$pur['duty']}', '{$pur['subtot']}', '{$pur['total']}', '0', '{$pur['fbalance']}', '{$pur['remarks']}', '{$pur['refno']}', 'y', 'y', '" . USER_DIV . "', '{$pur['purnum']}')"; $rslt = db_exec($sql) or errDie("Unable to insert Order to Cubit.", SELF); /*-- Cost varience -- */ $nsubtot = sprint($pur['total'] - $pur['tax']); $nsubtot = sprint($nsubtot * $pur['xrate']); if ($pur['rlsubtot'] > $nsubtot) { $diff = sprint($pur['rlsubtot'] - $nsubtot); # Debit Stock Control and Credit Creditors control writetrans($wh['conacc'], $cvacc, $TD, $refnum, $diff, "Cost Variance for Stock Received on Purchase No. {$pur['purnum']} from Supplier : {$sup['supname']}."); } elseif ($nsubtot > $pur['rlsubtot']) { $diff = sprint($nsubtot - $pur['rlsubtot']); # Debit Stock Control and Credit Creditors control writetrans($cvacc, $wh['conacc'], $TD, $refnum, $diff, "Cost Variance for Stock Received on Purchase No. {$pur['purnum']} from Supplier : {$sup['supname']}."); } /*-- End Cost varience -- */ db_connect(); # Get selected stock $sql = "SELECT * FROM purint_items WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'"; $stktcRslt = db_exec($sql); while ($stktc = pg_fetch_array($stktcRslt)) { # Insert Order items db_conn($pur['prd']); $sql = "INSERT INTO purint_items(purid, whid, stkid, qty, unitcost, cunitcost, duty, dutyp, amt, ddate, recved, div) VALUES('{$purid}', '{$stktc['whid']}', '{$stktc['stkid']}', '{$stktc['qty']}', '{$stktc['unitcost']}', '{$stktc['cunitcost']}', '{$stktc['duty']}', '{$stktc['dutyp']}', '{$stktc['amt']}', '{$stktc['ddate']}', 'y', '" . USER_DIV . "')"; $rslt = db_exec($sql) or errDie("Unable to insert Order items to Cubit.", SELF); } db_connect(); # Remove the Order from running DB $sql = "DELETE FROM purch_int WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'"; $delRslt = db_exec($sql) or errDie("Unable to update int Orders information in Cubit.", SELF); # Record where Order is $sql = "INSERT INTO movpurch(purtype, purnum, prd, div) VALUES('int', '{$pur['purnum']}', '{$pur['prd']}', '" . USER_DIV . "')"; $movRslt = db_exec($sql) or errDie("Unable to update int Orders information in Cubit.", SELF); # Remove those Order items from running DB $sql = "DELETE FROM purint_items WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'"; $delRslt = db_exec($sql) or errDie("Unable to update int Orders information in Cubit.", SELF); } /* End moving Order received */ // Final Layout $write = "\n\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t<tr>\n\t\t\t\t\t<th>International Order received</th>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>Order receipt from Supplier <b>{$sup['supname']}</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='purch-int-view.php'>View International Orders</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 stock vars extract($_POST); # validate input require_lib("validate"); $v = new validate(); $v->isOk($stkid, "num", 1, 50, "Invalid stock number."); $v->isOk($sdiv, "num", 1, 50, "Invalid branch number."); $v->isOk($whid, "num", 1, 50, "Invalid warehouse number."); $v->isOk($tunits, "num", 1, 50, "Invalid number of units."); # check if duplicate serial number selected, remove blanks if (isset($sernos)) { if (!ext_isUnique(ext_remBlnk($sernos))) { $v->isOk("##", "num", 0, 0, "Error : Serial Numbers must be unique per line item."); } } # display errors, if any if ($v->isError()) { $confirm = ""; $errors = $v->getErrors(); foreach ($errors as $e) { $confirm .= "<li class='err'>-" . $e["msg"] . "</li>"; } return $confirm; } # Select Stock db_connect(); $sql = "SELECT * FROM stock WHERE stkid = '{$stkid}' AND div = '" . USER_DIV . "'"; $stkRslt = db_exec($sql) or errDie("Unable to access databse.", SELF); if (pg_numrows($stkRslt) < 1) { return "<li> Invalid Stock ID.</li>"; } else { $stk = pg_fetch_array($stkRslt); } db_conn("exten"); # get warehouse $sql = "SELECT * FROM warehouses WHERE whid = '{$stk['whid']}' AND div = '" . USER_DIV . "'"; $whRslt = db_exec($sql); $wh = pg_fetch_array($whRslt); # get warehouse $sql = "SELECT * FROM warehouses WHERE whid = '{$whid}' AND div = '{$sdiv}'"; $swhRslt = db_exec($sql); $swh = pg_fetch_array($swhRslt); /* Start Stock transfering */ db_connect(); $csamt = $tunits * $stk['csprice']; # Reduce on the other hand $sql = "UPDATE stock SET units = (units - '{$tunits}'), csamt = (csamt - '{$csamt}') WHERE stkid = '{$stkid}' AND div = '" . USER_DIV . "'"; $rslt = db_exec($sql) or errDie("Unable to update stock in Cubit.", SELF); # Insert ithe stock into transit $sql = "INSERT INTO transit (trandate, stkid, sdiv, swhid, tunits, cstamt, div) VALUES (now(), '{$stkid}', '{$sdiv}', '{$whid}', '{$tunits}', '{$csamt}', '" . USER_DIV . "')"; $rslt = db_exec($sql) or errDie("Unable to insert stock into transit.", SELF); $tid = pglib_lastid("transit", "id"); if (isset($sernos)) { foreach ($sernos as $skey => $serno) { # Insert the stock serial into transit serials $sql = "INSERT INTO transerial (tid, stkid, serno) VALUES ('{$tid}', '{$stkid}', '{$serno}')"; $rslt = db_exec($sql) or errDie("Unable to insert stock into transit.", SELF); ext_invSer($serno, $stkid); } } # todays date $date = date("d-m-Y"); $refnum = getrefnum($date); # dt(conacc) ct(stkacc) # writetrans($wh['conacc'], $wh['stkacc'], $date, $refnum, $csamt, "Stock Transfer", USER_DIV); /* End Stock transfering */ db_connect(); # Original Branch $sql = "SELECT * FROM branches WHERE div = '{$stk['div']}'"; $branRslt = db_exec($sql) or errDie("Unable to access databse.", SELF); if (pg_numrows($branRslt) < 1) { return "<li> Invalid Branch ID.</li>"; } else { $bran = pg_fetch_array($branRslt); } # Selected Branch $sql = "SELECT * FROM branches WHERE div = '{$sdiv}'"; $sbranRslt = db_exec($sql) or errDie("Unable to access databse.", SELF); if (pg_numrows($sbranRslt) < 1) { return "<li> Invalid Branch ID.</li>"; } else { $sbran = pg_fetch_array($sbranRslt); } # Select Stock db_connect(); $sql = "SELECT * FROM stock WHERE stkid = '{$stkid}' AND div = '" . USER_DIV . "'"; $stkRslt = db_exec($sql) or errDie("Unable to access databse.", SELF); if (pg_numrows($stkRslt) < 1) { return "<li> Invalid Stock ID."; } else { $stk = pg_fetch_array($stkRslt); } # Available stock units $avstk = $stk['units'] - $stk['alloc']; # Return $write = "\n\t\t<h3>Stock has been taken to transit</h3>\n\t\t<table " . TMPL_tblDflts . " width='350'>\n\t\t\t<tr>\n\t\t\t\t<th width='40%'>Field</th>\n\t\t\t\t<th width='60%'>Value</th>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Branch</td>\n\t\t\t\t<td>{$bran['branname']}</td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Warehouse</td>\n\t\t\t\t<td>{$wh['whname']}</td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Category</td>\n\t\t\t\t<td>{$stk['catname']}</td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Stock code</td>\n\t\t\t\t<td>{$stk['stkcod']}</td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Stock description</td>\n\t\t\t\t<td>" . nl2br($stk['stkdes']) . "</pre></td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>On Hand</td>\n\t\t\t\t<td>{$stk['units']}</td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Allocated</td>\n\t\t\t\t<td>{$stk['alloc']}</td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Available</td>\n\t\t\t\t<td>{$avstk}</td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>On Order</td>\n\t\t\t\t<td>{$stk['ordered']}</td>\n\t\t\t</tr>\n\t\t\t<tr><td><br></td></tr>\n\t\t\t<tr>\n\t\t\t\t<th colspan='2'>Transfered to</th>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>To Branch</td>\n\t\t\t\t<td>{$sbran['branname']}</td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>To Store </td>\n\t\t\t\t<td>{$swh['whname']}</td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Number of units transfered</td>\n\t\t\t\t<td>{$tunits}</td>\n\t\t\t</tr>\n\t\t</table>\n\t\t<p>\n\t\t<table " . TMPL_tblDflts . " width='15%'>\n\t\t\t<tr>\n\t\t\t\t<th>Quick Links</th>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td><a href='stock-transit-view.php'>View Stock in transit</a></td>\n\t\t\t</tr>\n\t\t\t<script>document.write(getQuicklinkSpecial());</script>\n\t\t</table>"; return $write; }
function write($_POST) { # Get vars extract($_POST); # validate input require_lib("validate"); $v = new validate(); $v->isOk($purid, "num", 1, 20, "Invalid Order number."); $v->isOk($remarks, "string", 0, 255, "Invalid Remarks."); $v->isOk($refno, "string", 0, 255, "Invalid Delivery Reference No."); $v->isOk($shipchrg, "float", 0, 20, "Invalid Delivery Charges."); # used to generate errors $error = "asa@"; # check quantities if (isset($recvd)) { foreach ($recvd as $sk => $keys) { $v->isOk($qtys[$keys], "num", 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>."); if ($qtys[$keys] < 1) { $v->isOk("#", "num", 0, 0, "Error : Item Quantity must be at least one. Product number : <b>" . ($keys + 1) . "</b>"); } if ($qtys[$keys] > $qts[$keys]) { $v->isOk("#", "num", 0, 0, "Error : Item Quantity returned is more than the bought quantity : <b>" . ($keys + 1) . "</b>"); } $v->isOk($stkids[$keys], "num", 1, 10, "Invalid Stock number, please enter all details."); # Validate ddate[] $v->isOk($d_day[$keys], "num", 1, 2, "Invalid Delivery Date day."); $v->isOk($d_month[$keys], "num", 1, 2, "Invalid Delivery Date month."); $v->isOk($d_year[$keys], "num", 1, 5, "Invalid Delivery Date year."); $ddate[$keys] = $d_year[$keys] . "-" . $d_month[$keys] . "-" . $d_day[$keys]; if (!checkdate($d_month[$keys], $d_day[$keys], $d_year[$keys])) { $v->isOk($ddate[$keys], "num", 1, 1, "Invalid Delivery Date."); } } if (isset($sers)) { foreach ($sers as $stkid => $sernos) { if (!ext_isUnique(ext_remBlnk($sernos))) { $v->isOk("error", "num", 1, 1, "Error : Serial numbers must be unique per Stock Item."); } else { foreach ($recvd as $sk => $keys) { if (isset($sernos[$keys]) && $v->isOk($sernos[$keys], "string", 1, 20, "Error : Invalid Serial number.")) { if (ext_findSer($sernos[$keys]) != false) { $v->isOk("#", "string", 1, 20, "Error : Serial number already exists."); } } } } } } } else { $v->isOk("#", "num", 0, 0, "Error : Items Not Selected."); } /* 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 ($unitcost[$keys], "float", 1, 20, "Invalid Unit Price for product number : <b>".($keys+1)."</b>."); if($qty > $qts[$keys]){ $v->isOk ($qty, "num", 0, 0, "Error : Item Quantity returned is more than the bought quantity : <b>".($keys+1)."</b>"); } } } # check stkids if(isset($stkids)){ foreach($stkids as $keys => $stkid){ $v->isOk ($stkid, "num", 1, 10, "Invalid Stock number, 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 purchase info db_connect(); $sql = "SELECT * FROM purchases WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'"; $purRslt = db_exec($sql) or errDie("Unable to get Order information"); if (pg_numrows($purRslt) < 1) { return "<li> - Order Not Found</li>"; } $pur = pg_fetch_array($purRslt); # check if purchase has been received if ($pur['received'] == "y") { $error = "<li class='err'> Error : Order number <b>{$purid}</b> has already been received.</li>"; $error .= "<p><input type='button' onClick='JavaScript:history.back();' value='« Correct submission'>"; return $error; } # Get department info db_conn("exten"); $sql = "SELECT deptname FROM departments WHERE deptid = '{$pur['deptid']}' AND div = '" . USER_DIV . "'"; $deptRslt = db_exec($sql); if (pg_numrows($deptRslt) < 1) { $dept['deptname'] = "<i class='err'>Not Found</i>"; } else { $dept = pg_fetch_array($deptRslt); } core_connect(); # Get Petty cash account $cashacc = gethook("accnum", "bankacc", "name", "Petty Cash"); # Insert purchase to DB db_connect(); # Begin updating pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF); # amount of stock in $totstkamt = array(); $resub = 0; $taxex = 0; $revat = 0; # Get subtotal foreach ($recvd as $sk => $keys) { # Skip zeros if ($qtys[$keys] < 1) { continue; } $amt[$keys] = $qtys[$keys] * $unitcost[$keys]; } $SUBTOTAL = array_sum($amt); foreach ($recvd as $sk => $keys) { # Skip zeros if ($qtys[$keys] < 1) { continue; } # get selamt from selected stock $sql = "SELECT * FROM stock WHERE stkid = '{$stkids[$keys]}' AND div = '" . USER_DIV . "'"; $stkRslt = db_exec($sql); $stk = pg_fetch_array($stkRslt); # Get selected stock line $sql = "SELECT * FROM pur_items WHERE id = '{$ids[$keys]}' AND purid = '{$purid}' AND div = '" . USER_DIV . "'"; $stkdRslt = db_exec($sql); $stkd = pg_fetch_array($stkdRslt); # 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]; # Check Tax Excempt if ($stk['exvat'] == 'yes') { # how much is not vatable? $taxex += $amt[$keys]; } else { # Line vat $svat[$keys] = svat($amt[$keys], $stkd['amt'], $stkd['svat']); # received vat $revat += $svat[$keys]; # make amount vat free if ($pur['vatinc'] == "yes") { $amt[$keys] = $amt[$keys] - $svat[$keys]; } } # Update purchase items $sql = "UPDATE pur_items SET rqty = (rqty + '{$qtys[$keys]}'), ddate = '{$ddate[$keys]}' WHERE id = '{$ids[$keys]}' AND purid='{$purid}' AND div = '" . USER_DIV . "'"; $rslt = db_exec($sql) or errDie("Unable to insert Order items to Cubit.", SELF); # Update stock(ordered + qty, units + qty, csamt + (csamt + amt)) $sql = "UPDATE stock SET ordered = (ordered - '{$qtys[$keys]}'), units = (units + '{$qtys[$keys]}'), csamt = (csamt + '{$amt[$keys]}') WHERE stkid = '{$stkids[$keys]}' AND div = '" . USER_DIV . "'"; $rslt = db_exec($sql) or errDie("Unable to update stock to Cubit.", SELF); if (isset($sers[$stkids[$keys]][$keys])) { ext_InSer($sers[$stkids[$keys]][$keys], $stkids[$keys], $pur['supname'], $pur['purnum'], "pur", $pur['pdate']); $serial = $sers[$stkids[$keys]][$keys]; db_connect(); $sql = "INSERT INTO pserec(purid, purnum, stkid, serno, div)\n\t\t\t\tVALUES('{$purid}', '{$pur['purnum']}', '{$stkids[$keys]}', '{$serial}', '" . USER_DIV . "')"; $rslt = db_exec($sql) or errDie("Unable to update stock serials in Cubit.", SELF); } # Keep records for transactions if (isset($totstkamt[$stk['whid']])) { $totstkamt[$stk['whid']] += $amt[$keys]; } else { $totstkamt[$stk['whid']] = $amt[$keys]; } # Get selected stock $sql = "SELECT * FROM stock WHERE stkid = '{$stkids[$keys]}' AND div = '" . USER_DIV . "'"; $stkRslt = db_exec($sql); $stk = pg_fetch_array($stkRslt); # stkid, stkcod, stkdes, trantype, edate, qty, csamt, details $sdate = date("Y-m-d"); stockrec($stk['stkid'], $stk['stkcod'], $stk['stkdes'], 'dt', $sdate, $qtys[$keys], $amt[$keys], "Stock Received from Supplier : {$pur['supname']} - Order No. {$pur['purnum']}"); db_connect(); $cspric = sprint($amt[$keys] / $qtys[$keys]); $sql = "INSERT INTO stockrec(edate, stkid, stkcod, stkdes, trantype, qty, csprice, csamt, details, div)\n\t\t\tVALUES('{$sdate}', '{$stk['stkid']}', '{$stk['stkcod']}', '{$stk['stkdes']}', 'purchase', '{$qtys[$keys]}', '{$amt[$keys]}', '{$cspric}', 'Stock Received from Supplier : {$pur['supname']} - Order No. {$pur['purnum']}', '" . USER_DIV . "')"; $recRslt = db_exec($sql); # Just wanted to fix the xxx.xxxxxxe-x value if ($stk['units'] > 0) { $csprice = round($stk['csamt'] / $stk['units'], 2); } else { $csprice = round($stk['csprice'], 2); } # update stock(csprice = (csamt/units)) $sql = "UPDATE stock SET csprice = '{$csprice}', lcsprice = '{$cspric}' WHERE stkid = '{$stkids[$keys]}' AND div = '" . USER_DIV . "'"; $rslt = db_exec($sql) or errDie("Unable to update stock to Cubit.", SELF); # check if there are any outstanding items $sql = "SELECT * FROM pur_items WHERE purid = '{$purid}' AND (qty - rqty) > '0' AND div = '" . USER_DIV . "'"; $stkdRslt = db_exec($sql); # if none the set to received if (pg_numrows($stkdRslt) < 1) { # update surch_int(received = 'y') $sql = "UPDATE purchases SET received = 'y' WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'"; $rslt = db_exec($sql) or errDie("Unable to update Orders in Cubit.", SELF); } } if (strlen($refno) > 0) { if (strlen($pur['refno']) > 0) { $refno = "{$pur['refno']}-{$refno}"; } else { $refno = $refno; } } else { $refno = $pur['refno']; } # Update purchase on the DB if ($pur['part'] == 'y') { $sql = "UPDATE purchases SET shipchrg = (shipchrg + '{$shipchrg}'), refno = '{$refno}', remarks = '{$remarks}', edit = 1 WHERE purid = '{$purid}'"; } else { $sql = "UPDATE purchases SET shipchrg = '{$shipchrg}', part = 'y', refno = '{$refno}', remarks = '{$remarks}', edit = 1 WHERE purid = '{$purid}'"; } $rslt = db_exec($sql) or errDie("Unable to update Order in Cubit.", SELF); /* Transactions */ $refnum = getrefnum(date("d-m-Y")); /* - Start Hooks - */ $vatacc = gethook("accnum", "salesacc", "name", "VAT"); /* - End Hooks - */ $tpp = 0; # Record transaction from data foreach ($totstkamt as $whid => $wamt) { # Get whouse info db_conn("exten"); $sql = "SELECT stkacc FROM warehouses WHERE whid = '{$whid}' AND div = '" . USER_DIV . "'"; $whRslt = db_exec($sql); $wh = pg_fetch_array($whRslt); # Debit Stock and Petty Cash acc writetrans($wh['stkacc'], $cashacc, date("d-m-Y"), $refnum, $wamt, "Stock Received for Purchase No. {$pur['purid']} from Supplier : {$pur['supname']}."); } # Calc Vat amount on (subtot + delchrg) # $vatamt = vat(($resub - $taxex), $pur['vatinc']); $vatamt = $revat; # Add vat if not included if ($pur['vatinc'] == 'no') { $retot = $resub + $vatamt; } else { $retot = $resub; } # Transfer vat writetrans($vatacc, $cashacc, date("d-m-Y"), $refnum, $vatamt, "Vat Paid for Purchase No. {$pur['purid']} from Supplier : {$pur['supname']}."); db_connect(); # Record tranfer for patty cash report $sdate = date("Y-m-d"); $sql = "INSERT INTO pettyrec(date, type, det, amount, name, div) VALUES ('{$sdate}', 'Req', 'Cash Payment for Stock Received on Purchase No. {$pur['purid']} from Supplier : {$pur['supname']}.', '-{$retot}', 'Petty Cash Purchase', '" . USER_DIV . "')"; $Rslt = db_exec($sql) or errDie("Unable to add bank payment to database.", SELF); /* Start moving if purchase received */ # Get purchase info db_connect(); $sql = "SELECT * FROM purchases WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'"; $purRslt = db_exec($sql) or errDie("Unable to get Order information"); if (pg_numrows($purRslt) < 1) { return "<li> - Order Not Found</li>"; } $pur = pg_fetch_array($purRslt); if ($pur['received'] == "y") { # copy purchase db_conn($pur['prd']); $sql = "INSERT INTO purchases(purid, deptid, supid, supname, supaddr, supno, terms, pdate, ddate, shipchrg, subtot, total, balance, vatinc, vat, remarks, refno, received, done, div, purnum)"; $sql .= " VALUES('{$purid}', '{$pur['deptid']}', '{$pur['supid']}', '{$pur['supname']}', '{$pur['supaddr']}', '{$pur['supno']}', '{$pur['terms']}', '{$pur['pdate']}', '{$pur['ddate']}', '{$pur['shipchrg']}', '{$pur['subtot']}', '{$pur['total']}', '0', '{$pur['vatinc']}', '{$pur['vat']}', '{$pur['remarks']}', '{$pur['refno']}', 'y', 'y', '" . USER_DIV . "', '{$pur['purnum']}')"; $rslt = db_exec($sql) or errDie("Unable to insert Order to Cubit.", SELF); db_connect(); # Get selected stock $sql = "SELECT * FROM pur_items WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'"; $stktcRslt = db_exec($sql); while ($stktc = pg_fetch_array($stktcRslt)) { # Insert purchase items db_conn($pur['prd']); $sql = "INSERT INTO pur_items(purid, whid, stkid, qty, rqty, unitcost, amt, ddate, div) VALUES('{$purid}', '{$stktc['whid']}', '{$stktc['stkid']}', '{$stktc['qty']}', '{$stktc['rqty']}', '{$stktc['unitcost']}', '{$stktc['amt']}', '{$stktc['ddate']}', '" . USER_DIV . "')"; $rslt = db_exec($sql) or errDie("Unable to insert Order items to Cubit.", SELF); } db_connect(); # Remove the purchase from running DB $sql = "DELETE FROM purchases WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'"; $delRslt = db_exec($sql) or errDie("Unable to update int Order information in Cubit.", SELF); # Record where purchase is $sql = "INSERT INTO movpurch(purtype, purnum, prd, div) VALUES('loc', '{$pur['purnum']}', '{$pur['prd']}', '" . USER_DIV . "')"; $movRslt = db_exec($sql) or errDie("Unable to update int Order information in Cubit.", SELF); # Remove those purchase items from running DB $sql = "DELETE FROM pur_items WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'"; $delRslt = db_exec($sql) or errDie("Unable to update Order information in Cubit.", SELF); } # commit updating pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF); /* End moving purchase received */ // Final Layout $write = "\n\t<table " . TMPL_tblDflts . ">\n\t\t<tr>\n\t\t\t<th>Order received</th>\n\t\t</tr>\n\t\t<tr class='" . bg_class() . "'>\n\t\t\t<td>Order receipt from Supplier <b>{$pur['supname']}</b> has been recorded.</td>\n\t\t</tr>\n\t</table>\n\t<p>\n\t<table " . TMPL_tblDflts . ">\n\t\t<tr>\n\t\t\t<th>Quick Links</th>\n\t\t</tr>\n\t\t<tr class='" . bg_class() . "'>\n\t\t\t<td><a href='purchase-view.php'>View Orders</a></td>\n\t\t</tr>\n\t\t<script>document.write(getQuicklinkSpecial());</script>\n\t</table>"; return $write; }
function confirm($_POST) { # get vars foreach ($_POST as $key => $value) { ${$key} = $value; } # validate input require_lib("validate"); $v = new validate(); $v->isOk($purid, "num", 1, 50, "Invalid purchase id."); foreach ($sers as $stkid => $sernos) { if (!ext_isUniquedb(ext_remBlnk($sernos))) { $v->isOk("error", "num", 1, 1, "Error : Serial numbers must be unique per Stock Item."); } foreach ($sernos as $key => $serno) { if (strlen($serno) > 0) { $v->isOk($serno, "string", 1, 20, "Error : Invalid Serial number."); } } } # display errors, if any if ($v->isError()) { $confirm = ""; $errors = $v->getErrors(); foreach ($errors as $e) { $confirm .= "<li class=err>-" . $e["msg"] . "<br>"; } return $confirm .= "<p><input type=button onClick='JavaScript:history.back();' value='« Correct submission'>"; } print "Success !!!"; exit; db_connect(); $sql = "SELECT stkid, stkcod, stkdes, units FROM stock WHERE stkid = '{$stkid}' AND div = '" . USER_DIV . "'"; $stkRslt = db_exec($sql) or errDie("Unable to retrieve stocks from database."); $stk = pg_fetch_array($stkRslt); // Layout $confirm = "<h3>Confirm Serial Numbers</h3>\r\n\t<form action='" . SELF . "' method=post>\r\n\t<table cellpadding='" . TMPL_tblCellPadding . "' cellspacing='" . TMPL_tblCellSpacing . "'>\r\n\t\t<input type=hidden name=key value=write>\r\n\t\t<input type=hidden name=stkid value='{$stkid}'>\r\n\t\t<tr class='bg-even'><td>Stock</td><td align=center>{$stk['stkcod']} {$stk['stkdes']}</td></tr>\r\n\t\t<tr><td><br></td></tr>\r\n\t\t<tr><td align=right><input type=button value='Back' onclick='javascript:history.back();'></td><td valign=left><input type=submit value='Write »'></td></tr>\r\n\t\t<tr><th colspan=2>Serial Numbers</th></tr>"; foreach ($sers as $key => $serno) { if (strlen($serno) < 1) { continue; } $confirm .= "<tr class='" . bg_class() . "'><td align=center colspan=2><input type=hidden name=sers[] size=20 value='{$serno}'>{$serno}</td></tr>"; } $confirm .= "\r\n\t\t<tr><td><br></td></tr>\r\n\t\t<tr><td align=right><input type=button value='Back' onclick='javascript:history.back();'></td><td valign=left><input type=submit value='Write »'></td></tr>\r\n\t</table></form>\r\n\t<p>\r\n\t<table border=0 cellpadding='2' cellspacing='1'>\r\n\t\t<tr><th>Quick Links</th></tr>\r\n\t\t<tr class='bg-odd'><td><a href='pricelist-view.php'>View Price Lists</a></td></tr>\r\n\t\t<tr class='bg-odd'><td><a href='main.php'>Main Menu</a></td></tr>\r\n\t</table>"; return $confirm; }
function write($_POST) { # get stock vars extract($_POST); # validate input require_lib("validate"); $v = new validate(); $v->isOk($stkid, "num", 1, 50, "Invalid stock number."); $v->isOk($sstkid, "num", 1, 50, "Invalid stock number."); $v->isOk($whid, "num", 1, 50, "Invalid warehouse number."); $v->isOk($tunits, "float", 1, 15, "Invalid number of units."); $date = mkdate($d_year, $d_month, $d_day); $v->isOk($date, "date", 1, 1, "Invalid transfer date."); if ($stkid == $sstkid) { $v->isOk($shelf, "string", 0, 10, "Invalid Shelf number."); $v->isOk($row, "string", 0, 10, "Invalid Row number."); $v->isOk($minlvl, "num", 0, 10, "Invalid minimum stock level."); $v->isOk($maxlvl, "num", 0, 10, "Invalid maximum stock level."); $v->isOk($selamt, "float", 0, 10, "Invalid selling amount."); } # 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."); } } # display errors, if any if ($v->isError()) { $confirm = ""; $errors = $v->getErrors(); foreach ($errors as $e) { $confirm .= "<li class='err'>-" . $e["msg"] . "</li>"; } return $confirm; } # Select Stock db_connect(); $sql = "SELECT * FROM stock WHERE stkid = '{$stkid}' AND div = '" . USER_DIV . "'"; $stkRslt = db_exec($sql) or errDie("Unable to get stock information.", SELF); if (pg_numrows($stkRslt) < 1) { return "<li> Invalid Stock ID.</li>"; } else { $stk = pg_fetch_array($stkRslt); } if ($stkid == $sstkid) { $sstk = $stk; $head = "New Stock"; $data = "\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Location</td>\n\t\t\t\t<td>Shelf : <input type='hidden' name='shelf' value='{$shelf}'>{$shelf} - Row : <input type='hidden' name='row' value='{$row}'>{$row}</td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Level</td>\n\t\t\t\t<td>Minimum : <input type='hidden' name='minlvl' value='{$minlvl}'>{$minlvl} - Maximum : <input type='hidden' name='maxlvl' value='{$maxlvl}'>{$maxlvl}</td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Selling price per unit</td>\n\t\t\t\t<td>" . CUR . " <input type='hidden' name='selamt' value='{$stk['selamt']}'>{$stk['selamt']}</td>\n\t\t\t</tr>"; } else { $sql = "SELECT * FROM stock WHERE stkid = '{$sstkid}' AND div = '" . USER_DIV . "'"; $sstkRslt = db_exec($sql) or errDie("Unable to access databse.", SELF); if (pg_numrows($sstkRslt) < 1) { return "<li> Invalid Stock ID.</li>"; } else { $sstk = pg_fetch_array($sstkRslt); } $head = ""; $data = ""; } db_conn("exten"); # get warehouse $sql = "SELECT whid, whname, stkacc FROM warehouses WHERE whid = '{$stk['whid']}' AND div = '" . USER_DIV . "'"; $whRslt = db_exec($sql); $wh = pg_fetch_array($whRslt); # get warehouse $sql = "SELECT whid, whname, stkacc FROM warehouses WHERE whid = '{$whid}' AND div = '" . USER_DIV . "'"; $swhRslt = db_exec($sql); $swh = pg_fetch_array($swhRslt); /* Start Stock transfering */ pglib_transaction("BEGIN") or errDie("Could Not Start Transaction."); db_connect(); $csamt = $tunits * $stk['csprice']; $sdate = $date; if ($stkid == $sstkid) { # Create new stock item on the other hand $sql = "\n\t\t\tINSERT INTO stock (\n\t\t\t\tstkcod, serno, stkdes, prdcls, classname, csamt, \n\t\t\t\tunits, buom, suom, rate, shelf, row, minlvl, maxlvl, \n\t\t\t\tcsprice, selamt, catid, catname, whid, blocked, type, alloc, \n\t\t\t\tcom, serd, div, vatcode\n\t\t\t) VALUES (\n\t\t\t\t'{$sstk['stkcod']}', '{$sstk['serno']}', '{$sstk['stkdes']}', '{$sstk['prdcls']}', '{$sstk['classname']}', '{$csamt}', \n\t\t\t\t'{$tunits}', '{$sstk['buom']}', '{$sstk['suom']}', '{$sstk['rate']}', '{$shelf}', '{$row}', '{$minlvl}', '{$maxlvl}', \n\t\t\t\t'{$sstk['csprice']}', '{$sstk['selamt']}', '{$sstk['catid']}', '{$sstk['catname']}', '{$whid}', 'n', '{$sstk['type']}', '0', \n\t\t\t\t'0', '{$sstk['serd']}', '" . USER_DIV . "', '{$sstk['vatcode']}'\n\t\t\t)"; $rslt = db_exec($sql) or errDie("Unable to insert stock to Cubit.", SELF); $sstkid = pglib_lastid("stock", "stkid"); db_conn(date("n")); $sql = "\n\t\t\tINSERT INTO stkledger (\n\t\t\t\tstkid, stkcod, stkdes, trantype, edate, qty, csamt, \n\t\t\t\tbalance, bqty, details, div, yrdb\n\t\t\t) VALUES (\n\t\t\t\t'{$sstkid}', '{$sstk['stkcod']}', '{$sstk['stkdes']}', 'bal', '{$date}', '0', '0', \n\t\t\t\t'0', '0', 'Balance', '" . USER_DIV . "', '" . YR_DB . "'\n\t\t\t)"; $Ro = db_exec($sql); # stkid, stkcod, stkdes, trantype, edate, qty, csamt, details stockrec($sstkid, $sstk['stkcod'], $sstk['stkdes'], 'dt', $sdate, $tunits, $csamt, "Stock Transferred from Store : {$wh['whname']}", FALSE); db_connect(); # Reduce on the other hand $sql = "UPDATE stock SET units = (units - '{$tunits}'), csamt = (csamt - '{$csamt}') WHERE stkid = '{$stkid}' AND div = '" . USER_DIV . "'"; $rslt = db_exec($sql) or errDie("Unable to update stock in Cubit.", SELF); // db_conn('audit'); // for ($i = 1; $i <= 12; ++$i) { // db_conn($i); // $sql = "INSERT INTO stkledger(stkid,stkcod,stkdes,trantype,edate,qty,csamt,balance, // bqty,details,div,yrdb) // VALUES ('$data[stkid]','$data[stkcod]','$data[stkdes]','bal','$date', // '$data[units]','$data[csamt]','$data[csamt]','$data[units]', // 'Balance','".USER_DIV."','".YR_DB."')"; // $Ro=db_exec($sql); // doesnt make sense ??? // $sql = " // INSERT INTO stkledger ( // stkid, stkcod, stkdes, trantype, edate, qty, csamt, // balance, bqty, details, div, yrdb // ) VALUES ( // '$sstk[stkid]', '$sstk[stkcod]', '$sstk[stkdes]', 'bal', '$date', '$sstk[units]', '$sstk[csamt]', // '$sstk[csamt]', '$sstk[units]', 'Balance', '".USER_DIV."', '".YR_DB."' // )"; // } # stkid, stkcod, stkdes, trantype, edate, qty, csamt, details stockrec($stk['stkid'], $stk['stkcod'], $stk['stkdes'], 'ct', $sdate, $tunits, $csamt, "Stock Transferred to Store : {$swh['whname']}"); // db_connect(); } else { db_connect(); # Move units and csamt $sql = "UPDATE stock SET units = (units + '{$tunits}'), csamt = (csamt + '{$csamt}') WHERE stkid = '{$sstkid}' AND div = '" . USER_DIV . "'"; $rslt = db_exec($sql) or errDie("Unable to update stock in Cubit.", SELF); $sdate = date("Y-m-d"); # stkid, stkcod, stkdes, trantype, edate, qty, csamt, details stockrec($sstk['stkid'], $sstk['stkcod'], $sstk['stkdes'], 'dt', $sdate, $tunits, $csamt, "Stock Transferred from Store : {$wh['whname']}", FALSE); db_connect(); # Reduce on the other hand $sql = "UPDATE stock SET units = (units - '{$tunits}'), csamt = (csamt - '{$csamt}') WHERE stkid = '{$stkid}' AND div = '" . USER_DIV . "'"; $rslt = db_exec($sql) or errDie("Unable to update stock in Cubit.", SELF); # stkid, stkcod, stkdes, trantype, edate, qty, csamt, details stockrec($stk['stkid'], $stk['stkcod'], $stk['stkdes'], 'ct', $sdate, $tunits, $csamt, "Stock Transferred to Store : {$swh['whname']}"); } # todays date $refnum = getrefnum($date); db_connect(); $ins_sql = "\n\t\tINSERT INTO stock_transfer (\n\t\t\tstkid, whid_from, whid_to, units, reference, remark, location_shelf, location_row, level_min, level_max, transfer_date\n\t\t) VALUES (\n\t\t\t'{$stkid}', '{$wh['whid']}', '{$swh['whid']}', '{$tunits}', '{$refnum}', '{$remark}', '{$shelf}', '{$row}', '{$minlvl}', '{$maxlvl}', '{$date}'\n\t\t)"; $run_ins = db_exec($ins_sql) or errDie("Unable to record stock transfer information."); $serials = ""; # Move serial number,using functions if (isset($sernos)) { $serials = "\n\t\t\t<tr>\n\t\t\t\t<th colspan='2'>Units Serial Numbers</th>\n\t\t\t</tr>"; foreach ($sernos as $skey => $serno) { ext_invSer($serno, $stkid); ext_unInvSer($serno, $sstkid); $serials .= "\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td colspan='2' align='center'>{$serno}</td>\n\t\t\t\t</tr>"; } } # dt(cos) ct(stock) writetrans($swh['stkacc'], $wh['stkacc'], $date, $refnum, $csamt, "Stock Transfer"); /* End Stock transfering */ pglib_transaction("COMMIT") or errDie("Unable To Commit Transaction."); # Select Stock db_connect(); $sql = "SELECT * FROM stock WHERE stkid = '{$stkid}' AND div = '" . USER_DIV . "'"; $stkRslt = db_exec($sql) or errDie("Unable to access databse.", SELF); if (pg_numrows($stkRslt) < 1) { return "<li> Invalid Stock ID.</li>"; } else { $stk = pg_fetch_array($stkRslt); } # available stock units $avstk = $stk['units'] - $stk['alloc']; # return $write = "\n\t\t<h3> Stock has been Transfered </h3>\n\t\t<table " . TMPL_tblDflts . " width='350'>\n\t\t\t<tr>\n\t\t\t\t<th width='40%'>Field</th>\n\t\t\t\t<th width='60%'>Value</th>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Warehouse</td>\n\t\t\t\t<td>{$wh['whname']}</td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Category</td>\n\t\t\t\t<td>{$stk['catname']}</td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Stock code</td>\n\t\t\t\t<td>{$stk['stkcod']}</td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Stock description</td>\n\t\t\t\t<td>" . nl2br($stk['stkdes']) . "</pre></td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>On Hand</td>\n\t\t\t\t<td>" . sprint3($stk['units']) . "</td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Allocated</td>\n\t\t\t\t<td>" . sprint3($stk['alloc']) . "</td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Available</td>\n\t\t\t\t<td>" . sprint3($avstk) . "</td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>On Order</td>\n\t\t\t\t<td>" . sprint3($stk['ordered']) . "</td>\n\t\t\t</tr>\n\t\t\t<tr><td><br></td></tr>\n\t\t\t{$serials}\n\t\t\t<tr><td><br></td></tr>\n\t\t\t<tr>\n\t\t\t\t<th colspan='2'>Transfered to {$head}</th>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>To Store </td>\n\t\t\t\t<td>{$swh['whname']}</td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Stock code</td>\n\t\t\t\t<td>{$sstk['stkcod']}</td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Stock description</td>\n\t\t\t\t<td>" . nl2br($sstk['stkdes']) . "</td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Number of units transfered</td>\n\t\t\t\t<td>" . sprint3($tunits) . "</td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Remark</td>\n\t\t\t\t<td>{$remark}</td>\n\t\t\t</tr>\n\t\t\t{$data}\n\t\t</table>\n\t\t<p>\n\t\t<table " . TMPL_tblDflts . " width='15%'>\n\t\t\t<tr>\n\t\t\t\t<th>Quick Links</th>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td><a href='stock-transfer.php'>New Stock Transfer</a></td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td><a href='main.php'>Main Menu</a></td>\n\t\t\t</tr>\n\t\t</table>"; return $write; }
function write() { # Get vars extract($_REQUEST); # validate input require_lib("validate"); $v = new validate(); $v->isOk($purid, "num", 1, 20, "Invalid Order number."); $v->isOk($remarks, "string", 0, 255, "Invalid Remarks."); $v->isOk($refno, "string", 0, 255, "Invalid Delivery Reference No."); $v->isOk($shipchrg, "float", 0, 20, "Invalid Delivery Charges."); # used to generate errors $error = "asa@"; # check quantities if (isset($recvd)) { foreach ($recvd as $sk => $keys) { $v->isOk($qtys[$keys], "float", 1, 15, "Invalid Quantity for product number : <b>" . ($keys + 1) . "</b>"); $v->isOk($unitcost[$keys], "float", 1, 20, "Invalid Unit Price for product number : <b>" . ($keys + 1) . "</b>."); if ($qtys[$keys] <= 0) { $v->isOk("#", "num", 0, 0, "Error : Item Quantity must be more than zero. Product number : <b>" . ($keys + 1) . "</b>"); } if ($qtys[$keys] > $qts[$keys]) { $v->isOk("#", "num", 0, 0, "Error : Item Quantity returned is more than the bought quantity : <b>" . ($keys + 1) . "</b>"); } $v->isOk($stkids[$keys], "num", 1, 10, "Invalid Stock number, please enter all details."); # Validate ddate[] $v->isOk($d_day[$keys], "num", 1, 2, "Invalid Delivery Date day."); $v->isOk($d_month[$keys], "num", 1, 2, "Invalid Delivery Date month."); $v->isOk($d_year[$keys], "num", 1, 5, "Invalid Delivery Date year."); $ddate[$keys] = $d_year[$keys] . "-" . $d_month[$keys] . "-" . $d_day[$keys]; if (!checkdate($d_month[$keys], $d_day[$keys], $d_year[$keys])) { $v->isOk($ddate[$keys], "num", 1, 1, "Invalid Delivery Date."); } } if (isset($sers)) { foreach ($sers as $stkid => $sernos) { if (!ext_isUnique(ext_remBlnk($sernos))) { $v->isOk("error", "num", 1, 1, "Error : Serial numbers must be unique per Stock Item."); } else { foreach ($recvd as $sk => $keys) { if (isset($sernos[$keys]) && $v->isOk($sernos[$keys], "string", 1, 20, "Error : Invalid Serial number.")) { if (ext_findSer($sernos[$keys]) != false) { $v->isOk("#", "string", 1, 20, "Error : Serial number already exists."); } } } } } } } else { $v->isOk("#", "num", 0, 0, "Error : Items Not Selected."); } # display errors, if any $err = ""; if ($v->isError()) { $errors = $v->getErrors(); foreach ($errors as $e) { $err .= "<li class='err'>" . $e["msg"] . "</li>"; } return details($_POST, $err); } # Get purchase info db_connect(); $sql = "SELECT * FROM purchases WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'"; $purRslt = db_exec($sql) or errDie("Unable to get purchase information"); if (pg_numrows($purRslt) < 1) { return "<li> - Order Not Found</li>"; } $pur = pg_fetch_array($purRslt); $td = $pur['pdate']; # check if purchase has been received if ($pur['received'] == "y") { $error = "<li class='err'> Error : Order number <b>{$purid}</b> has already been received.</li>"; $error .= "<p><input type='button' onClick='JavaScript:history.back();' value='« Correct submission'>"; return $error; } # Get selected supplier info db_connect(); $sql = "SELECT * FROM suppliers WHERE supid = '{$pur['supid']}' AND div = '" . USER_DIV . "'"; $supRslt = db_exec($sql) or errDie("Unable to get customer information"); if (pg_numrows($supRslt) < 1) { // code here } else { $sup = pg_fetch_array($supRslt); } # Get department info db_conn("exten"); $sql = "SELECT * FROM departments WHERE deptid = '{$pur['deptid']}' AND div = '" . USER_DIV . "'"; $deptRslt = db_exec($sql); if (pg_numrows($deptRslt) < 1) { $dept['deptname'] = "<i class='err'> - Not Found</i>"; } else { $dept = pg_fetch_array($deptRslt); } db_conn('cubit'); $Sl = "SELECT * FROM vatcodes WHERE id='{$pur['delvat']}'"; $Ri = db_exec($Sl); if (pg_num_rows($Ri) < 1) { $Sl = "SELECT * FROM vatcodes"; $Ri = db_exec($Sl); } $vd = pg_fetch_array($Ri); $VATP = $vd['vat_amount']; if ($vd['zero'] != "Yes") { # If vat is not included (shipchrg) if ($pur['vatinc'] == "no") { $scvat = sprint($VATP / 100 * $shipchrg); $shipexvat = $shipchrg; } elseif ($pur['vatinc'] == "yes") { $scvat = sprint($shipchrg / ($VATP + 100) * $VATP); $shipexvat = $shipchrg - $scvat; } else { $scvat = 0; $shipexvat = $shipchrg; } } else { $scvat = 0; $shipexvat = $shipchrg; } db_conn("exten"); $sql = "SELECT * FROM warehouses WHERE div = '" . USER_DIV . "'"; $whRslt = db_exec($sql); $wh = pg_fetch_array($whRslt); # Begin updating pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF); db_conn(PRD_DB); # get last ref number $refnum = getrefnum(); db_connect(); # amount of stock in $totstkamt = array(); $resub = 0; $vatacc = gethook("accnum", "salesacc", "name", "VAT"); $cvacc = gethook("accnum", "pchsacc", "name", "Cost Variance"); $flag = TRUE; $checkid = 0; $nonstot = 0; foreach ($recvd as $sk => $keys) { if ($checkid == $ids[$keys]) { $flag = FALSE; } else { $flag = TRUE; } $checkid = $ids[$keys]; # Skip zeros if ($qtys[$keys] <= 0) { continue; } db_connect(); # Get selamt from selected stock $sql = "SELECT * FROM stock WHERE stkid = '{$stkids[$keys]}' AND div = '" . USER_DIV . "'"; $stkRslt = db_exec($sql); $stk = pg_fetch_array($stkRslt); if ($stk['units'] < 0) { $min_stock = abs($stk['units']); if ($qtys[$keys] < $min_stock) { $min_stock = $qtys[$keys]; } } else { $min_stock = 0; } # Get selected stock line $sql = "SELECT * FROM pur_items WHERE id = '{$ids[$keys]}' AND purid = '{$purid}' AND div = '" . USER_DIV . "'"; $stkdRslt = db_exec($sql); $stkd = pg_fetch_array($stkdRslt); if ($pur['vatinc'] == "yes") { $unitcost[$keys] = sprint(($stkd['amt'] - $stkd['svat']) / $stkd['qty']); } else { $unitcost[$keys] = sprint($stkd['amt'] / $stkd['qty']); } //$perc[$keys] = sprint((($unitcost[$keys]*$qtys[$keys])/$pur['subtot']) * 100); $perc[$keys] = sprint($unitcost[$keys] / $pur['subtot'] * 100); $ffs = $perc[$keys] * $qtys[$keys]; # Get percentage from shipping charges excluding vat $shipc[$keys] = sprint($perc[$keys] / 100 * $shipexvat); //print "cost: percent:$ffs ship: part1".($unitcost[$keys]*$qtys[$keys])."part2".($shipc[$keys]*$qtys[$keys])."<br>"; # add delivery charges = amt + del chrg excluding vat $unitcost[$keys] += $shipc[$keys]; if ($stkd['udiscount'] > 0) { $discps = round($stkd['udiscount'] / 100 * $unitcost[$keys], 2); } else { $discps = 0; } $amt[$keys] = sprint($qtys[$keys] * $unitcost[$keys]); #serialized items are broken into multiples .... we only want to process the first ... so FLAG is used if (isset($invoice)) { $iq = $qtys[$keys]; $iq += 0; $Sl = "SELECT * FROM vatcodes WHERE id='{$stkd['vatcode']}'"; $Ri = db_exec($Sl) or errDie("Unable to get data."); $vd = pg_fetch_array($Ri); if ($pur['vatinc'] == "yes") { $iamount = $stkd['amt']; } else { $iamount = sprint($stkd['amt'] + $stkd['svat']); } if ($flag) { vatr($vd['id'], $pur['pdate'], "INPUT", $vd['code'], $refnum, "VAT for Purchase No. {$pur['purnum']}", -$iamount, -$stkd['svat']); } $Sl = "UPDATE pur_items SET iqty=iqty-'{$iq}' WHERE id='{$stkd['id']}'"; $Ri = db_exec($Sl) or errDie("Unable to update invoice qty."); } $resub += $amt[$keys]; # Update purchase items $sql = "\n\t\t\tUPDATE pur_items \n\t\t\tSET rqty = (rqty + '{$qtys[$keys]}'), ddate = '{$ddate[$keys]}' \n\t\t\tWHERE id = '{$ids[$keys]}' AND purid='{$purid}' AND div = '" . USER_DIV . "'"; $rslt = db_exec($sql) or errDie("Unable to insert Order items to Cubit.", SELF); $cc = ""; if ($stkd['account'] > 0) { if ($pur['vatinc'] == "yes") { #calculate the vat of this amount as we dont store it !! $vatcod = $stkd['vatcode'] + 0; $get_v = "SELECT vat_amount FROM vatcodes WHERE id = '{$vatcod}' LIMIT 1"; $run_v = db_exec($get_v) or errDie("Unable to get vatcode information."); $varr = pg_fetch_array($run_v); $clearvat = $varr['vat_amount'] + 0; $remvat = sprint($stkd['amt'] / ($clearvat + 100) * $clearvat); $nonstot = $nonstot + $stkd['amt'] - $remvat; } else { $nonstot = $nonstot + $stkd['amt']; } $stk['whid'] = $stkd['account']; $sql = "SELECT * FROM bankacct WHERE btype != 'int' AND div = '" . USER_DIV . "' LIMIT 1"; $banks = db_exec($sql); if (pg_numrows($banks) < 1) { return "<li class='err'> There are no accounts held at the selected Bank.\n\t\t\t\t<p><input type='button' onClick='JavaScript:history.back();' value='« Correct Selection'>"; } $barr = pg_fetch_array($banks); $bankid = $barr['bankid']; core_connect(); $sql = "SELECT * FROM bankacc WHERE accid = '{$bankid}' AND div = '" . USER_DIV . "'"; $rslt = db_exec($sql) or errDie("Unable to retrieve bank account link from Cubit", SELF); # Check if link exists if (pg_numrows($rslt) < 1) { return "<li class='err'> ERROR : The bank account that you selected doesn't appear to have an account linked to it."; } $banklnk = pg_fetch_array($rslt); $cc_trantype = cc_TranTypeAcc($stkd['account'], $banklnk['accnum']); } else { # Update stock(ordered + qty, units + qty, csamt + (csamt + amt)) $sql = "\n\t\t\t\tUPDATE stock \n\t\t\t\tSET ordered = (ordered - '{$qtys[$keys]}'), units = (units + '{$qtys[$keys]}' +'{$min_stock}'), csamt = (csamt + '{$amt[$keys]}') \n\t\t\t\tWHERE stkid = '{$stkids[$keys]}' AND div = '" . USER_DIV . "'"; $rslt = db_exec($sql) or errDie("Unable to update stock to Cubit.", SELF); if (isset($sers[$stkids[$keys]][$keys])) { ext_InSer($sers[$stkids[$keys]][$keys], $stkids[$keys], $pur['supname'], $pur['purnum'], "pur", $td); $serial = $sers[$stkids[$keys]][$keys]; db_connect(); $sql = "\n\t\t\t\t\tINSERT INTO pserec (\n\t\t\t\t\t\tpurid, purnum, stkid, serno, div\n\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t'{$purid}', '{$pur['purnum']}', '{$stkids[$keys]}', '{$serial}', '" . USER_DIV . "'\n\t\t\t\t\t)"; $rslt = db_exec($sql) or errDie("Unable to update stock serials in Cubit.", SELF); } # Get selected stock $sql = "SELECT * FROM stock WHERE stkid = '{$stkids[$keys]}' AND div = '" . USER_DIV . "'"; $stkRslt = db_exec($sql); $stk = pg_fetch_array($stkRslt); # stkid, stkcod, stkdes, trantype, edate, qty, csamt, details //$sdate = date("Y-m-d"); stockrec($stk['stkid'], $stk['stkcod'], $stk['stkdes'], 'dt', $td, $qtys[$keys], $amt[$keys], "Stock Received from Supplier : {$sup['supname']} - Order No. {$pur['purnum']}"); db_connect(); $cspric = sprint($amt[$keys] / $qtys[$keys]); $sql = "\n\t\t\t\tINSERT INTO stockrec (\n\t\t\t\t\tedate, stkid, stkcod, stkdes, trantype, qty, csprice, \n\t\t\t\t\tcsamt, details, div\n\t\t\t\t) VALUES (\n\t\t\t\t\t'{$td}', '{$stk['stkid']}', '{$stk['stkcod']}', '{$stk['stkdes']}', 'purchase', '{$qtys[$keys]}', '{$amt[$keys]}', \n\t\t\t\t\t'{$cspric}', 'Stock Received from Supplier : {$sup['supname']} - Order No. {$pur['purnum']}', '" . USER_DIV . "'\n\t\t\t\t)"; $recRslt = db_exec($sql); # Just wanted to fix the xxx.xxxxxxe-x value if ($stk['units'] > 0) { $csprice = round($stk['csamt'] / $stk['units'], 2); } else { $csprice = round($stk['csprice'], 2); } # update stock(csprice = (csamt/units)) $sql = "\n\t\t\t\tUPDATE stock \n\t\t\t\tSET csprice = '{$csprice}', lcsprice = '{$cspric}' \n\t\t\t\tWHERE stkid = '{$stkids[$keys]}' AND div = '" . USER_DIV . "'"; $rslt = db_exec($sql) or errDie("Unable to update stock to Cubit.", SELF); } # Keep records for transactions if (isset($totstkamt[$stk['whid']])) { $totstkamt[$stk['whid']] += $amt[$keys]; } else { $totstkamt[$stk['whid']] = $amt[$keys]; } db_connect(); # check if there are any outstanding items $sql = "SELECT * FROM pur_items WHERE purid = '{$purid}' AND (qty - rqty) > '0' AND div = '" . USER_DIV . "'"; $stkdRslt = db_exec($sql); # if none the set to received if (pg_numrows($stkdRslt) < 1) { # update surch_int(received = 'y') $sql = "UPDATE purchases SET received = 'y' WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'"; $rslt = db_exec($sql) or errDie("Unable to update Orders in Cubit.", SELF); } if ($min_stock > 0) { $cost = sprint($unitcost[$keys] * $min_stock); db_conn("exten"); $sql = "SELECT stkacc,cosacc FROM warehouses WHERE whid = '{$stk['whid']}' AND div = '" . USER_DIV . "'"; $whRslt = db_exec($sql); $wh = pg_fetch_array($whRslt); $stockacc = $wh['stkacc']; $cosacc = $wh['cosacc']; db_connect(); $Sl = "UPDATE stock SET csamt = (csamt - '{$cost}'),units=(units-'{$min_stock}') WHERE stkid='{$stkids[$keys]}'"; $Ri = db_exec($Sl); writetrans($cosacc, $stockacc, $td, $refnum, $cost, "Cost Of Sales for stock sold before purchase {$pur['purnum']}"); stockrec($stk['stkid'], $stk['stkcod'], $stk['stkdes'], 'ct', $td, 0, $cost, "Cost Of Sales for stock sold before purchase {$pur['purnum']}"); db_connect(); $Sl = "\n\t\t\t\tINSERT INTO pcost (\n\t\t\t\t\tpurnum, cost, qty, rqty, stkid\n\t\t\t\t) VALUES (\n\t\t\t\t\t'{$pur['purnum']}', '{$unitcost[$keys]}', '{$min_stock}', '0', '{$stk['stkid']}'\n\t\t\t\t)"; $Ri = db_exec($Sl); } } // $darr = explode ("-",$date); // $cdate = "$darr[2]-$darr[1]-$darr[0]"; #if non stock total is set, process the cost center if ($nonstot != "0") { $nonstot = sprint($nonstot); if ($cc_trantype != false) { $date = date("Y-m-d"); $cc .= "\n\t\t\t\t<script>\n\t\t\t\t\tCostCenter('{$cc_trantype}', 'Non Stock Purchase', '{$date}', '{$stkd['description']}', {$nonstot}, '');\n\t\t\t\t</script>"; } else { $cc .= ""; } } if (isset($invoice)) { ###################VAT CALCS####################### $pur['delvat'] += 0; db_conn('cubit'); $Sl = "SELECT * FROM vatcodes WHERE id='{$pur['delvat']}'"; $Ri = db_exec($Sl); if (pg_num_rows($Ri) < 1) { $Sl = "SELECT * FROM vatcodes"; $Ri = db_exec($Sl); } $vd = pg_fetch_array($Ri); if ($vd['zero'] == "Yes") { $excluding = "y"; } else { $excluding = ""; } $vr = vatcalc($shipchrg, $pur['vatinc'], $excluding, 0, $vd['vat_amount']); $vrs = explode("|", $vr); $ivat_tmp = $vrs[0]; $iamount_tmp = $vrs[1]; vatr($vd['id'], $td, "INPUT", $vd['code'], $refnum, "VAT Paid for Purchase No. {$pur['purnum']} from Supplier : {$pur['supname']}.", sprint(-$iamount_tmp), -$scvat); #################################################### db_conn("exten"); $sql = "SELECT * FROM warehouses WHERE div = '" . USER_DIV . "'"; $whRslt = db_exec($sql); $wh = pg_fetch_array($whRslt); db_connect(); # update the supplier (make balance more) $sql = "UPDATE suppliers SET balance = (balance + '{$itotal}') WHERE supid = '{$pur['supid']}' AND div = '" . USER_DIV . "'"; $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF); $sql = "\n\t\t\tINSERT INTO sup_stmnt (\n\t\t\t\tsupid, edate, cacc, amount, descript, ref, ex, div\n\t\t\t) VALUES (\n\t\t\t\t'{$pur['supid']}', '{$pur['pdate']}', '{$wh['conacc']}', '{$itotal}', \n\t\t\t\t'Stock Received - Purchase {$pur['purnum']} Inv:{$pur['supinv']}', '{$refnum}', '{$pur['purnum']}', '" . USER_DIV . "'\n\t\t\t)"; $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF); # Debit Stock Control and Credit Creditors control writetrans($wh['conacc'], $dept['credacc'], $td, $refnum, $isubtot, "Invoice Received for Purchase No. {$pur['purnum']} from Supplier : {$pur['supname']}."); # Transfer vat writetrans($vatacc, $dept['credacc'], $td, $refnum, $ivat, "VAT Paid for Purchase No. {$pur['purnum']} from Supplier : {$pur['supname']}."); # Ledger Records suppledger($pur['supid'], $wh['conacc'], $td, $pur['purid'], "Purchase No. {$pur['purnum']} received.", $itotal, 'c'); db_connect(); /* End Transactions */ /* Make transaction record for age analysis */ db_connect(); # update the supplier age analysis (make balance less) if (ext_ex2("suppurch", "purid", $pur['purnum'], "supid", $pur['supid'])) { # Found? Make amount less $sql = "UPDATE suppurch SET balance = (balance + '{$itotal}') WHERE supid = '{$pur['supid']}' AND purid = '{$pur['purnum']}' AND div = '" . USER_DIV . "'"; $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF); } else { /* Make transaction record for age analysis */ $sql = "\n\t\t\t\t\tINSERT INTO suppurch (\n\t\t\t\t\t\tsupid, purid, pdate, balance, div\n\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t'{$pur['supid']}', '{$pur['purnum']}', '{$pur['pdate']}', '{$itotal}', '" . USER_DIV . "'\n\t\t\t\t\t)"; $purcRslt = db_exec($sql) or errDie("Unable to update Order information in Cubit.", SELF); } /* Make transaction record for age analysis */ # commit updating $sql = "UPDATE purchases SET iamount = iamount+'{$itotal}',ivat=ivat+'{$ivat}' WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'"; $rslt = db_exec($sql) or errDie("Unable to update Order status in Cubit.", SELF); $sql = "SELECT SUM(iqty) FROM pur_items WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'"; $stktRslt = db_exec($sql); $data = pg_fetch_array($stktRslt); $left = $data['sum']; if ($left == 0) { /* Start moving if purchase */ if ($pur['received'] == "y") { if (strlen($pur['appdate']) < 8) { $pur['appdate'] = date("Y-m-d"); } # copy purchase db_conn($pur['prd']); $sql = "\n\t\t\t\t\tINSERT INTO purchases (\n\t\t\t\t\t\tpurid, deptid, supid, supname, supaddr, supno, \n\t\t\t\t\t\tterms, pdate, ddate, shipchrg, subtot, total, \n\t\t\t\t\t\tbalance, vatinc, vat, shipping, remarks, refno, received, done, \n\t\t\t\t\t\tdiv, purnum, supinv, ordernum, appname, appdate\n\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t'{$purid}', '{$pur['deptid']}', '{$pur['supid']}', '{$pur['supname']}', '{$pur['supaddr']}', '{$pur['supno']}', \n\t\t\t\t\t\t'{$pur['terms']}', '{$pur['pdate']}', '{$pur['ddate']}', '{$pur['shipchrg']}', '{$pur['subtot']}', '{$pur['total']}', \n\t\t\t\t\t\t'0', '{$pur['vatinc']}', '{$pur['vat']}', '{$pur['shipping']}', '{$remarks}', '{$pur['refno']}', 'y', 'y', \n\t\t\t\t\t\t'" . USER_DIV . "', '{$pur['purnum']}', '{$supinv}', '{$pur['ordernum']}', '{$pur['appname']}', '{$pur['appdate']}'\n\t\t\t\t\t)"; $rslt = db_exec($sql) or errDie("Unable to insert Order to Cubit.", SELF); /*-- Cost varience -- */ //$nsubtot = sprint($pur['total'] - $pur['vat']); $nsubtot = sprint($p['iamount'] - $p['ivat']); if ($p['rsubtot'] > $nsubtot) { $diff = sprint($p['rsubtot'] - $nsubtot); # Debit Stock Control and Credit Creditors control writetrans($wh['conacc'], $cvacc, $td, $refnum, $diff, "Cost Variance for Stock Received on Purchase No. {$pur['purnum']} from Supplier : {$sup['supname']}."); } elseif ($nsubtot > $p['rsubtot']) { $diff = sprint($nsubtot - $pur['rsubtot']); # Debit Stock Control and Credit Creditors control writetrans($cvacc, $wh['conacc'], $td, $refnum, $diff, "Cost Variance for Stock Received on Purchase No. {$pur['purnum']} from Supplier : {$sup['supname']}."); } /*-- End Cost varience -- */ db_connect(); # Get selected stock $sql = "SELECT * FROM pur_items WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'"; $stktcRslt = db_exec($sql); while ($stktc = pg_fetch_array($stktcRslt)) { # Insert purchase items db_conn($pur['prd']); $sql = "\n\t\t\t\t\t\tINSERT INTO pur_items (\n\t\t\t\t\t\t\tpurid, whid, stkid, qty, rqty, unitcost, \n\t\t\t\t\t\t\tamt, svat, ddate, div\n\t\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t\t'{$purid}', '{$stktc['whid']}', '{$stktc['stkid']}', '{$stktc['qty']}', '{$stktc['rqty']}', '{$stktc['unitcost']}', \n\t\t\t\t\t\t\t'{$stktc['amt']}', '{$stktc['svat']}', '{$stktc['ddate']}', '" . USER_DIV . "'\n\t\t\t\t\t\t)"; $rslt = db_exec($sql) or errDie("Unable to insert Order items to Cubit.", SELF); } # begin updating //pglib_transaction ("BEGIN") or errDie("Unable to start a database transaction.",SELF); db_connect(); # Remove the purchase from running DB $sql = "DELETE FROM purchases WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'"; $delRslt = db_exec($sql) or errDie("Unable to update int purchases information in Cubit.", SELF); # Record where purchase is $sql = "INSERT INTO movpurch(purtype, purnum, prd, div) VALUES('loc', '{$pur['purnum']}', '{$pur['prd']}', '" . USER_DIV . "')"; $movRslt = db_exec($sql) or errDie("Unable to update int purchases information in Cubit.", SELF); # Remove those purchase items from running DB $sql = "DELETE FROM pur_items WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'"; $delRslt = db_exec($sql) or errDie("Unable to update int purchases information in Cubit.", SELF); /* End moving purchase received */ # commit updating //pglib_transaction ("COMMIT") or errDie("Unable to commit a database transaction.",SELF); } else { # insert Order to DB $sql = "UPDATE purchases SET invcd = 'y',supinv='{$pur['supinv']}' WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'"; $rslt = db_exec($sql) or errDie("Unable to update Order status in Cubit.", SELF); } } } if (strlen($refno) > 0) { if (strlen($pur['refno']) > 0) { $refno = "{$pur['refno']}-{$refno}"; } else { $refno = $refno; } } else { $refno = $pur['refno']; } db_connect(); # Update purchase on the DB if ($pur['part'] == 'y') { $sql = "\n\t\t\tUPDATE purchases \n\t\t\tSET rsubtot = (rsubtot + '{$resub}'), refno = '{$refno}', remarks = '{$remarks}', edit = 1 \n\t\t\tWHERE purid = '{$purid}'"; } else { $sql = "\n\t\t\tUPDATE purchases \n\t\t\tSET part = 'y', rsubtot = (rsubtot + '{$resub}'), refno = '{$refno}', remarks = '{$remarks}', edit = 1 \n\t\t\tWHERE purid = '{$purid}'"; } $rslt = db_exec($sql) or errDie("Unable to update Order in Cubit.", SELF); /* Transactions */ db_conn(PRD_DB); # get last ref number //$refnum = getrefnum(); /* - Start Hooks - */ /* - End Hooks - */ # Record transaction from data foreach ($totstkamt as $whid => $wamt) { # get whouse info db_conn("exten"); $sql = "SELECT stkacc,conacc FROM warehouses WHERE whid = '{$whid}' AND div = '" . USER_DIV . "'"; $whRslt = db_exec($sql); if (pg_num_rows($whRslt) < 1) { $sql = "SELECT stkacc,conacc FROM warehouses"; $whRslt = db_exec($sql); $wh = pg_fetch_array($whRslt); $wh['stkacc'] = $whid; } else { $wh = pg_fetch_array($whRslt); } # Debit Stock and Credit Stock control writetrans($wh['stkacc'], $wh['conacc'], $td, $refnum, $wamt, "Stock Received for Purchase No. {$pur['purnum']} from Supplier : {$sup['supname']}."); } # commit updating /*** pglib_transaction ("COMMIT") or errDie("Unable to commit a database transaction.",SELF); /* Start moving if Order received and invoiced */ # Get purchase info db_connect(); $sql = "SELECT * FROM purchases WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'"; $purRslt = db_exec($sql) or errDie("Unable to get Order information"); if (pg_numrows($purRslt) < 1) { return "<li> - Order Not Found</li>"; } $pur = pg_fetch_array($purRslt); if ($pur['received'] == "y" && $pur['invcd'] == 'y') { if (strlen($pur['appdate']) < 8) { $pur['appdate'] = date("Y-m-d"); } # copy purchase db_conn(PRD_DB); $sql = "\n\t\t\t\tINSERT INTO purchases (\n\t\t\t\t\tpurid, deptid, supid, supname, supaddr, supno, \n\t\t\t\t\tterms, pdate, ddate, shipchrg, subtot, total, balance, \n\t\t\t\t\tvatinc, vat, shipping, remarks, refno, received, done, div, \n\t\t\t\t\tpurnum, supinv, ordernum, appname, appdate, delvat\n\t\t\t\t) VALUES (\n\t\t\t\t\t'{$purid}', '{$pur['deptid']}', '{$pur['supid']}', '{$pur['supname']}', '{$pur['supaddr']}', '{$pur['supno']}', \n\t\t\t\t\t'{$pur['terms']}', '{$pur['pdate']}', '{$pur['ddate']}', '{$pur['shipchrg']}', '{$pur['subtot']}', '{$pur['total']}', '0', \n\t\t\t\t\t'{$pur['vatinc']}', '{$pur['vat']}', '{$pur['shipping']}', '{$pur['remarks']}', '{$pur['refno']}', 'y', 'y', '" . USER_DIV . "', \n\t\t\t\t\t'{$pur['purnum']}', '{$pur['supinv']}', '{$pur['ordernum']}', '{$pur['appname']}', '{$pur['appdate']}', '{$pur['delvat']}'\n\t\t\t\t)"; $rslt = db_exec($sql) or errDie("Unable to insert Order to Cubit.", SELF); /*-- Cost varience -- */ $nsubtot = sprint($pur['total'] - $pur['vat']); if ($pur['rsubtot'] > $nsubtot) { $diff = sprint($pur['rsubtot'] - $nsubtot); # Debit Stock Control and Credit Creditors control writetrans($wh['conacc'], $cvacc, $td, $refnum, $diff, "Cost Variance for Stock Received on Purchase No. {$pur['purnum']} from Supplier : {$sup['supname']}."); } elseif ($nsubtot > $pur['rsubtot']) { $diff = sprint($nsubtot - $pur['rsubtot']); # Debit Stock Control and Credit Creditors control writetrans($cvacc, $wh['conacc'], $td, $refnum, $diff, "Cost Variance for Stock Received on Purchase No. {$pur['purnum']} from Supplier : {$sup['supname']}."); } /*-- End Cost varience -- */ db_connect(); # Get selected stock $sql = "SELECT * FROM pur_items WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'"; $stktcRslt = db_exec($sql); while ($stktc = pg_fetch_array($stktcRslt)) { # Insert purchase items db_conn(PRD_DB); $sql = "\n\t\t\t\t\tINSERT INTO pur_items (\n\t\t\t\t\t\tpurid, whid, stkid, qty, rqty, unitcost, \n\t\t\t\t\t\tamt, svat, ddate, div, vatcode, \n\t\t\t\t\t\taccount, description, udiscount\n\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t'{$purid}', '{$stktc['whid']}', '{$stktc['stkid']}', '{$stktc['qty']}', '{$stktc['rqty']}', '{$stktc['unitcost']}', \n\t\t\t\t\t\t'{$stktc['amt']}', '{$stktc['svat']}', '{$stktc['ddate']}', '" . USER_DIV . "','{$stktc['vatcode']}', \n\t\t\t\t\t\t'{$stktc['account']}', '{$stktc['description']}', '{$stktc['udiscount']}'\n\t\t\t\t\t)"; $rslt = db_exec($sql) or errDie("Unable to insert Order items to Cubit.", SELF); } db_connect(); # Remove the purchase from running DB $sql = "DELETE FROM purchases WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'"; $delRslt = db_exec($sql) or errDie("Unable to update int Orders information in Cubit.", SELF); # Record where purchase is $sql = "INSERT INTO movpurch(purtype, purnum, prd, div) VALUES('loc', '{$pur['purnum']}', '{$pur['prd']}', '" . USER_DIV . "')"; $movRslt = db_exec($sql) or errDie("Unable to update int Orders information in Cubit.", SELF); # Remove those purchase items from running DB $sql = "DELETE FROM pur_items WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'"; $delRslt = db_exec($sql) or errDie("Unable to update int Orders information in Cubit.", SELF); } pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF); /* End moving purchase received */ if (isset($gds_note) and strlen($gds_note) > 0) { $cc .= "\n\t\t\t<script>\n\t\t\t\tprinter(\"" . SELF . "?key=recv_print&purid={$purid}\");\n\t\t\t</script>"; } // Final Layout $write = "\n\t\t{$cc}\n\t\t<table " . TMPL_tblDflts . ">\n\t\t\t<tr>\n\t\t\t\t<th>Order received</th>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Order receipt from Supplier <b>{$sup['supname']}</b> has been recorded.</td>\n\t\t\t</tr>\n\t\t</table>\n\t\t<p>\n\t\t<table " . TMPL_tblDflts . ">\n\t\t\t<tr>\n\t\t\t\t<th>Quick Links</th>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td><a href='purchase-new.php'>New Purchase</a></td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td><a href='purchase-view.php'>View Orders</a></td>\n\t\t\t</tr>\n\t\t\t<script>document.write(getQuicklinkSpecial());</script>\n\t\t</table>"; return $write; }