function edit()
{
    extract($_GET);
    if (isset($id)) {
        $subinfo = new dbSelect("subsistence", "cubit", array("where" => wgrp(m("id", "{$id}"))));
        $subinfo->run();
        if ($subinfo->num_rows() > 0) {
            extract($subinfo->fetch_array(), EXTR_SKIP);
        }
    }
    $fields = array("name" => "", "in_republic" => "yes", "meals" => "yes", "accid" => false);
    foreach ($fields as $fname => $val) {
        if (!isset(${$fname})) {
            ${$fname} = $val;
        }
    }
    /* no accid is set, use salaries and wages */
    if ($accid === false) {
        $swacc = qryAccountsName("Salaries and Wages", "accid");
        $accid = $swacc["accid"];
    }
    $bg = 0;
    $OUT = "\n\t<h3>Define Subsistence Allowance</h3>\n\t<li class='err'>The selection on this window will create a Subsistence Allowance\n\twith the specified properties. To assign this subsistence to an employee you\n\twill need to edit the employee, and on the 'Calculate Salary' window\n\tfill out the employee specific information involving the Subsistence Allowance.</li>\n\t<form method='get' action='" . SELF . "'>\n\t<input type='hidden' name='key' value='write'>\n\t" . (isset($id) ? "<input type='hidden' name='id' value='{$id}'" : "") . "\n\t<table " . TMPL_tblDflts . ">\n\t<tr>\n\t\t<th colspan='2'>Details</th>\n\t</tr>\n\t<tr class='" . bg_class() . "'>\n\t\t<td>Name:</td>\n\t\t<td><input type='text' name='name' value='{$name}'></td>\n\t</tr>\n\t<tr class='" . bg_class() . "'>\n\t\t<td>In Republic (ZA):</td>\n\t\t<td>\n\t\t\t<select name='in_republic'>\n\t\t\t\t<option value='yes' " . ($in_republic != "no" ? "selected" : "") . ">Yes</option>\n\t\t\t\t<option value='no' " . ($in_republic == "no" ? "selected" : "") . ">No</option>\n\t\t\t</select>\n\t\t</td>\n\t</tr>\n\t<tr class='" . bg_class() . "'>\n\t\t<td>Employee pays for own Meals:</td>\n\t\t<td>\n\t\t\t<select name='meals'>\n\t\t\t\t<option value='yes' " . ($meals != "no" ? "selected" : "") . ">Yes</option>\n\t\t\t\t<option value='no' " . ($meals == "no" ? "selected" : "") . ">No</option>\n\t\t\t</select>\n\t\t</td>\n\t</tr>\n\t<tr class='" . bg_class() . "'>\n\t\t<td>Account:</td>\n\t\t<td>" . finAccList("accid", false, $accid) . "</td>\n\t\t<td class='err'>Select an account where the expense must be debited to.</td>\n\t</tr>\n\t<tr>\n\t\t<td colspan='2' align='right'><input type='submit' value='Next'></td>\n\t</tr>\n\t</table>\n\t</form>\n\t<table " . TMPL_tblDflts . ">\n\t<tr>\n\t\t<td>\n\t\t\t<u><b>Subsistence allowance</b></u>\n\t\t\t<p>\n\t\t\tThe income tax provides that there shall not be included in the\n\t\t\ttaxable income of any person, any amount paid or granted by a\n\t\t\tprincipal as a reimbursement of, or as an advance for, the\n\t\t\texpenditure incurred or to be incurred by the employee - where\n\t\t\tthat employee must produce proof to that employer that such\n\t\t\texpenditure was wholly incurred and must account to that employer\n\t\t\tfor that expenditure.\n\t\t\t</p><p>\n\t\t\tFor the purpose of the above provision an employee shall be deemed\n\t\t\tto have actually incurred expenditure:\n\t\t\t<li>Where the employee proves to the Commissioner the amount of\n\t\t\tthe expenses incurred by him in respect of accommodation, meals or\n\t\t\tother incidental costs, the amount so actually incurred but\n\t\t\tlimited to the amount of the allowance or advance paid or granted\n\t\t\tto meet those expenses; or</li>\n\t\t\t<li>For each day or part of a day in the period during which that\n\t\t\temployee is absent from his or her usual place of residence, an\n\t\t\tamount in respect of meals and other incidental costs, or\n\t\t\tincidental costs only, determined by the Minister for the relevant\n\t\t\tyear of assessment by way of notice in The Gazette but limited to\n\t\t\tthe amount of the allowance paid or granted to meet those\n\t\t\texpenses.\n\t\t\t</p><p>\n\t\t\tAccording to the regulations published in The Gazette the\n\t\t\tfollowing amounts will be deemted to have been expended by an\n\t\t\temployee to whom an allowance or advance has been granted or paid:\n\t\t\t<li>Where the accommodation to which that allowance or advance\n\t\t\trelate is the Republic and that allowance or the advance is paid\n\t\t\tor granted to defray Incidental costs only, an amount equal to R93\n\t\t\tper day; or<br />\n\t\t\tThe cost of meals and incidental costs, an amount equal to R303\n\t\t\tper day; or</li>\n\t\t\t<li>Where the accommodation to which that allowance or advance\n\t\t\trelates is outside the Republic and that the allowance or advance\n\t\t\tis paid or granted to defray the cost of meals and incidental\n\t\t\tcosts, an amount equal to U.S. \$215 per day.</li>\n\t\t</td>\n\t</tr>\n\t</table>";
    return $OUT;
}
function acc_total($accname)
{
    $accid = qryAccountsName($accname);
    $accid = $accid["accid"];
    list($left_op, $right_op) = acc_calc($accid);
    $sql = "SELECT (sum({$left_op}) - sum({$right_op})) AS total\n\t\t\tFROM core.trial_bal\n\t\t\tWHERE accid='{$accid}' AND month='" . date("m") . "'";
    $total_rslt = db_exec($sql) or errDie("Unable to retrieve account total.");
    $total = (double) pg_fetch_result($total_rslt, 0);
    return $total;
}
$sql = "INSERT INTO cubit.ratio_account_types (rtype, rname)\n\t\tVALUES ('working_capital', 'Working Capital')";
db_exec($sql) or errDie("Unable to create ratio type");
$type_id = pglib_lastid("cubit.ratio_account_types", "id");
$accid = qryAccountsName("Share Capital / Members Contribution");
$accid = $accid["accid"];
$sql = "INSERT INTO cubit.ratio_account_owners (type_id, accid)\n\t\tVALUES ('{$type_id}', '{$accid}')";
db_exec($sql) or errDie("Unable to add ratio account.");
// Setup Long Term Liabilities ------------------------------------------------
$sql = "INSERT INTO cubit.ratio_account_types (rtype, rname)\n\t\tVALUES ('long_term_liabilities', 'Long Term Liabilities')";
db_exec($sql) or errDie("Unable to create ratio type");
$type_id = pglib_lastid("cubit.ratio_account_types", "id");
$accid = qryAccountsName("Shareholder / Director / Members Loan Account");
$accid = $accid["accid"];
$sql = "INSERT INTO cubit.ratio_account_owners (type_id, accid)\n\t\tVALUES ('{$type_id}', '{$accid}')";
db_exec($sql) or errDie("Unable to add ratio account.");
// Setup Owners Equity --------------------------------------------------------
$sql = "INSERT INTO cubit.ratio_account_types (rtype, rname)\n\t\tVALUES ('owners_equity', 'Owners Equity')";
db_exec($sql) or errDie("Unable to create ratio type");
$type_id = pglib_lastid("cubit.ratio_account_types", "id");
$accid = qryAccountsName("Share Capital / Members Contribution");
$accid = $accid["accid"];
$sql = "INSERT INTO cubit.ratio_account_owners (type_id, accid)\n\t\tVALUES ('{$type_id}', '{$accid}')";
db_exec($sql) or errDie("Unable to add ratio account.");
// Setup Interest Expense -----------------------------------------------------
$sql = "INSERT INTO cubit.ratio_account_types (rtype, rname)\n\t\tVALUES ('interest_expense', 'Interest Expense')";
db_exec($sql) or errDie("Unable to create ratio type");
$type_id = pglib_lastid("cubit.ratio_account_types", "id");
$accid = qryAccountsName("Interest Paid");
$accid = $accid["accid"];
$sql = "INSERT INTO cubit.ratio_account_owners (type_id, accid)\n\t\tVALUES ('{$type_id}', '{$accid}')";
db_exec($sql) or errDie("Unable to add ratio account.");
function recvpayment()
{
    extract($_POST);
    $v = new validate();
    $v->isOk($cusnum, "num", 1, 10, "Invalid customer id.");
    $v->isOk($invid, "num", 1, 10, "Invalid invoice id.");
    $v->isOk($pcc, "float", 1, 40, "Invalid credit card amount.");
    $v->isOk($pcash, "float", 1, 40, "Invalid cash amount.");
    $v->isOk($pcheque, "float", 1, 40, "Invalid cheque amount.");
    $date = mkdate($pinv_year, $pinv_month, $pinv_day);
    $v->isOk($date, "date", 1, 1, "Invalid invoice date.");
    if ($v->isError()) {
        return details($_POST, $v->genErrors());
    }
    $amt = sprint($pcc + $pcash + $pcheque);
    $cus = qryCustomer($cusnum);
    $bank_acc = qryAccountsName("Cash on Hand");
    $OUT = "\n\t<table " . TMPL_tblDflts . ">\n\t<tr>\n\t\t<th colspan='2'>Payment Details</th>\n\t</tr>\n\t<tr class='" . bg_class() . "'>\n\t\t<td>Account</td>\n\t\t<td>{$bank_acc['topacc']}/{$bank_acc['accnum']} {$bank_acc['accname']}</td>\n\t</tr>\n\t<tr class='" . bg_class() . "'>\n\t\t<td>Date</td>\n\t\t<td valign='center'>{$date}</td>\n\t</tr>\n\t<tr class='" . bg_class() . "'>\n\t\t<td>Received from</td>\n\t\t<td valign='center'>{$cus['cusname']} {$cus['surname']}</td>\n\t</tr>\n\t<tr class='" . bg_class() . "'>\n\t\t<td>Description</td>\n\t\t<td valign='center'>POS Payment Received</td>\n\t</tr>\n\t<tr class='" . bg_class() . "'>\n\t\t<td>Amount</td>\n\t\t<td valign='center'>" . CUR . " {$amt}</td>\n\t</tr>\n\t</table>\n\n\t<form method='post' action='" . SELF . "'>\n\t<input type='hidden' name='key' value='recvpayment_write' />\n\t<input type='hidden' name='bank_acc' value='{$bank_acc['accid']}' />\n\t<input type='hidden' name='invid' value='{$invid}' />\n\t<input type='hidden' name='pcc' value='{$pcc}' />\n\t<input type='hidden' name='pcash' value='{$pcash}' />\n\t<input type='hidden' name='pcheque' value='{$pcheque}' />\n\t<input type='hidden' name='amt' value='{$amt}' />\n\t<input type='hidden' name='date' value='{$date}' />\n\t<input type='hidden' name='cusnum' value='{$cusnum}' />\n\t<input type='hidden' name='descript' value='POS Payment Received' />\n\n\t<input type='hidden' name='stkerr' value='{$stkerr}' />\n\t<input type='hidden' name='prev_cusnum' value='{$prev_cusnum}' />\n\t<input type='hidden' name='deptid' value='{$deptid}' />\n\t<input type='hidden' name='telno' value='{$telno}' />\n\t<input type='hidden' name='cordno' value='{$cordno}' />\n\t<input type='hidden' name='bar' value='{$bar}' />\n\t<input type='hidden' name='des' value='{$des}' />\n\t<input type='hidden' name='sel_frm' value='{$sel_frm}' />\n\t<input type='hidden' name='ordno' value='{$ordno}' />\n\t<input type='hidden' name='pinv_day' value='{$pinv_day}' />\n\t<input type='hidden' name='pinv_month' value='{$pinv_month}' />\n\t<input type='hidden' name='pinv_year' value='{$pinv_year}' />\n\t<input type='hidden' name='chrgvat' value='{$chrgvat}' />\n\t<input type='hidden' name='salespn' value='{$salespn}' />\n\t<input type='hidden' name='traddisc' value='{$traddisc}' />\n\t<input type='hidden' name='delchrg' value='{$delchrg}' />\n\t<input type='hidden' name='delvat' value='{$delvat}' />\n\t<input type='hidden' name='user' value='{$user}' />\n\t<input type='hidden' name='SUBTOT' value='{$subtot}' />\n\t<input type='hidden' name='comm' value='{$comm}' />\n\n\t<table " . TMPL_tblDflts . ">";
    // Connect to database
    db_connect();
    $sql = "SELECT invnum,invid,balance,terms,odate FROM invoices\n\t\t\tWHERE cusnum = '{$cusnum}' AND printed = 'y' AND balance>0\n\t\t\t\tAND div = '" . USER_DIV . "'\n\t\t\tORDER BY odate ASC";
    $prnInvRslt = db_exec($sql);
    $i = 0;
    while (($inv = pg_fetch_array($prnInvRslt)) && $amt > 0) {
        if ($i == 0) {
            $OUT .= "\n\t\t\t<tr>\n\t\t\t\t<td colspan='2'>&nbsp;</td>\n\t\t\t</tr>\n\t\t\t<tr>\n\t\t\t\t<td colspan='2'><h3>Outstanding Invoices</h3></td>\n\t\t\t</tr>\n\t\t\t<tr>\n\t\t\t\t<th>Invoice</th>\n\t\t\t\t<th>Outstanding Amount</th>\n\t\t\t\t<th>Terms</th>\n\t\t\t\t<th>Date</th>\n\t\t\t\t<th>Amount</th>\n\t\t\t</tr>";
        }
        $invid = $inv['invid'];
        $val = allocamt($amt, $inv["balance"]);
        $OUT .= "\n\t\t<input type='hidden' name='paidamt[{$invid}]' size=10 value='{$val}'>\n\t\t<input type='hidden' size=20 name=invids[{$invid}] value='{$inv['invid']}'>\n\t\t<tr bgcolor='" . bgcolor($i) . "'>\n\t\t\t<td>{$inv['invnum']}</td>\n\t\t\t<td>" . CUR . " {$inv['balance']}</td>\n\t\t\t<td>{$inv['terms']} days</td>\n\t\t\t<td>{$inv['odate']}</td>\n\t\t\t<td>" . CUR . " {$val}</td>\n\t\t</tr>";
    }
    $sql = "SELECT invnum,invid,balance,sdate as odate FROM nons_invoices\n\t\t\tWHERE cusid='{$cusnum}' AND done='y' AND balance>0\n\t\t\t\tAND div='" . USER_DIV . "'\n\t\t\tORDER BY odate ASC";
    $prnInvRslt = db_exec($sql);
    while (($inv = pg_fetch_array($prnInvRslt)) && $amt > 0) {
        if ($i == 0) {
            $OUT .= "\n\t\t\t<tr>\n\t\t\t\t<td colspan='2'>&nbsp;</td>\n\t\t\t</tr>\n\t\t\t<tr>\n\t\t\t\t<td colspan='2'><h3>Outstanding Non-Stock Invoices</h3></td>\n\t\t\t</tr>\n\t\t\t<tr>\n\t\t\t\t<th>Invoice</th>\n\t\t\t\t<th>Outstanding Amount</th>\n\t\t\t\t<th></th>\n\t\t\t\t<th>Date</th>\n\t\t\t\t<th>Amount</th>\n\t\t\t</tr>";
        }
        $invid = $inv['invid'];
        $val = allocamt($amt, $inv["balance"]);
        $OUT .= "\n\t\t\t\t<input type='hidden' name='paidamt[{$invid}]' value='{$val}'>\n\t\t\t\t<input type='hidden' name='itype[{$invid}]' value='Yes'>\n\t\t\t\t<tr bgcolor='" . bgcolor($i) . "'>\n\t\t\t\t\t<td><input type='hidden' size='20' name='invids[{$invid}]' value='{$inv['invid']}'>{$inv['invnum']}</td>\n\t\t\t\t\t<td>" . CUR . " {$inv['balance']}</td>\n\t\t\t\t\t<td></td>\n\t\t\t\t\t<td>{$inv['odate']}</td>\n\t\t\t\t\t<td>" . CUR . " {$val}</td>\n\t\t\t\t</tr>";
    }
    $amt = sprint($amt);
    /* pos invoices */
    $sqls = array();
    for ($i = 1; $i <= 12; ++$i) {
        $sqls[] = "SELECT invnum,invid,balance,odate FROM \"{$i}\".pinvoices\n\t\t\t\t\tWHERE cusnum='{$cusnum}' AND done='y' AND balance>0\n\t\t\t\t\t\tAND div='" . USER_DIV . "'";
    }
    $sql = implode(" UNION ", $sqls);
    $prnInvRslt = db_exec($sql);
    if (pg_numrows($prnInvRslt) > 0) {
        $OUT .= "\n\t\t<tr>\n\t\t\t<td colspan='2'><br></td>\n\t\t</tr>\n\t\t<tr>\n\t\t\t<td colspan='2'><h3>Outstanding POS Invoices</h3></td>\n\t\t</tr>\n\t\t<tr>\n\t\t\t<th>Invoice</th>\n\t\t\t<th>Outstanding Amount</th>\n\t\t\t<th></th>\n\t\t\t<th>Date</th>\n\t\t\t<th>Amount</th>\n\t\t</tr>";
        $i = 0;
        while ($inv = pg_fetch_array($prnInvRslt)) {
            $invid = $inv['invid'];
            $val = allocamt($amt, $inv["balance"]);
            $OUT .= "\n\t\t\t<input type='hidden' size='20' name='invids[{$invid}]' value='{$inv['invid']}'>\n\t\t\t<input type='hidden' name='paidamt[{$invid}]' size=10 value='{$val}'>\n\t\t\t<input type='hidden' name='ptype[{$invid}]' value='YnYn'>\n\t\t\t<tr bgcolor='" . bgcolor($i) . "'>\n\t\t\t\t<td>{$inv['invnum']}</td>\n\t\t\t\t<td>" . CUR . " {$inv['balance']}</td>\n\t\t\t\t<td></td>\n\t\t\t\t<td>{$inv['odate']}</td>\n\t\t\t\t<td>" . CUR . " {$val}</td>\n\t\t\t</tr>";
        }
    }
    if ($amt > 0) {
        /* START OPEN ITEMS */
        $ox = "";
        $sql = "SELECT * FROM cubit.open_stmnt WHERE balance>0 AND cusnum='{$cusnum}'\n\t\t\t\t\tAND type!='Invoice' AND type!='Non-Stock Invoice'\n\t\t\t\t\tAND type!='Interest on Outstanding balance'\n\t\t\t\tORDER BY date";
        $rslt = db_exec($sql) or errDie("Unable to get open items.");
        $open_out = $amt;
        $i = 0;
        while ($od = pg_fetch_array($rslt)) {
            if ($open_out == 0) {
                continue;
            }
            $oid = $od['id'];
            if ($open_out >= $od['balance']) {
                $open_amount[$oid] = $od['balance'];
                $open_out = sprint($open_out - $od['balance']);
                $ox .= "\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td><input type='hidden' size='20' name='open[{$oid}]' value='{$oid}'>{$od['type']}</td>\n\t\t\t\t\t<td>" . CUR . " {$od['balance']}</td>\n\t\t\t\t\t<td>{$od['date']}</td>\n\t\t\t\t\t<td><input type='hidden' name='open_amount[{$oid}]' value='{$open_amount[$oid]}'>" . CUR . " {$open_amount[$oid]}</td>\n\t\t\t\t</tr>";
            } elseif ($open_out < $od['balance']) {
                $open_amount[$oid] = $open_out;
                $open_out = 0;
                $ox .= "\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td><input type='hidden' size='20' name='open[{$oid}]' value='{$od['id']}'>{$od['type']}</td>\n\t\t\t\t\t<td>" . CUR . " {$od['balance']}</td>\n\t\t\t\t\t<td>{$od['date']}</td>\n\t\t\t\t\t<td><input type='hidden' name='open_amount[{$oid}]' value='{$open_amount[$oid]}'>" . CUR . " {$open_amount[$oid]}</td>\n\t\t\t\t</tr>";
            }
            $i++;
        }
        if (open()) {
            $OUT .= "\n\t\t\t" . TBL_BR . "\n\t\t\t<input type='hidden' name='bout' value='{$amt}'>\n\t\t\t<tr>\n\t\t\t\t<td colspan='2'><h3>Outstanding Transactions</h3></td>\n\t\t\t</tr>\n\t\t\t<tr>\n\t\t\t\t<th>Description</th>\n\t\t\t\t<th>Outstanding Amount</th>\n\t\t\t\t<th>Date</th>\n\t\t\t\t<th>Amount</th>\n\t\t\t</tr>";
            $OUT .= $ox;
            $bout = $amt;
            $amt = $open_out;
            if ($amt > 0) {
                $OUT .= "\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td colspan='4'><b>A general transaction will credit the client's account with " . CUR . " {$amt}</b></td>\n\t\t\t\t</tr>";
            }
            //$amt=$bout;
        } else {
            $OUT .= "\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td colspan='4'><b>A general transaction will credit the client's account with " . CUR . " {$amt} </b></td>\n\t\t\t</tr>";
        }
    }
    $OUT .= "\n\t<input type='hidden' name='out' value='{$amt}' />\n\t<tr>\n\t\t<td colspan='5' align='right'>\n\t\t\t<input type='submit' name='btn_back' value='&laquo; Correction' />\n\t\t\t<input type='submit' value='Record Payment' />\n\t\t</td>\n\t</table>";
    return $OUT;
}
function decrease_stock($stkid, $qty)
{
    $sysdate = date("Y-m-d");
    $sql = "\n\t\tSELECT stkcod, stkdes, csprice FROM cubit.stock\n\t\t\tWHERE stkid='{$stkid}'";
    $stock_rslt = db_exec($sql) or errDie("Unable to retrieve stock.");
    list($stkcod, $stkdes, $csprice) = pg_fetch_array($stock_rslt);
    $price = $csprice * $qty;
    $sql = "\n\t\tUPDATE cubit.stock SET units=(units-'{$qty}'), csamt=(csamt-'{$price}')\n\t\t\tWHERE stkid='{$stkid}'";
    db_exec($sql) or errDie("Unable to decrease stock.");
    $inventory_acc = qryAccountsName("Inventory");
    $inventory_acc = $inventory_acc["accid"];
    // Stock take suspense
    $inventory_suspense_acc = qryAccountsName("Stock Take Suspense Account");
    $inventory_suspense_acc = $inventory_suspense_acc["accid"];
    $refnum = getRefnum();
    stockrec($stkid, $stkcod, $stkdes, "ct", $sysdate, $qty, $price, "Stock Take Adjustment");
    writetrans($inventory_suspense_acc, $inventory_acc, $sysdate, $refnum, $price, "Stock Take Adjustment for ({$stkcod}) {$stkdes} - {$qty} Units");
    return;
}
Ejemplo n.º 6
0
function update($_POST)
{
    extract($_POST);
    // Validate
    require_lib("validate");
    $v = new validate();
    if (isset($accid) && isset($category)) {
        $v->isOk($accid, "num", 1, 9, "Invalid account selection.");
        $v->isOk($category, "string", 1, 6, "Invalid category selection.");
    }
    if ($v->isError()) {
        $confirm = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $confirm .= "<li class='err'>{$e['msg']}</li>";
        }
        return slct($confirm);
    }
    $key = strtolower($key);
    if ($key == "add" || $key == "select account") {
        // Make sure the account has not been added already
        db_conn("cubit");
        $sql = "SELECT * FROM saved_cf_accounts WHERE accid='{$accid}'";
        $cfacc_rslt = db_exec($sql) or errDie("Unable to retrieve account from the account list.");
        if (!pg_num_rows($cfacc_rslt)) {
            db_conn("cubit");
            $sql = "INSERT INTO saved_cf_accounts (accid, category) VALUES ('{$accid}', '{$category}')";
            $cfacc_rslt = db_exec($sql) or errDie("Unable to save account to the accounts list.");
        }
    }
    if ($key == "remove selected") {
        if (!isset($rem)) {
            $rem = array();
        }
        foreach ($rem as $id) {
            db_conn("cubit");
            $sql = "DELETE FROM saved_cf_accounts WHERE accid='{$id}'";
            $cfacc_rslt = db_exec($sql) or errDie("Unable to remove selected account from the accounts list.");
        }
    }
    if ($key == "default") {
        list($accid) = qryAccountsName("Depreciation", "accid");
        db_conn("cubit");
        $cols = grp(m("accid", $accid), m("category", "nciis"));
        $qry = new dbUpdate("saved_cf_accounts", "cubit", $cols);
        $qry->run(DB_INSERT);
        // add balance sheet items to list
        $qry = new dbQuery(DB_SQL, "INSERT INTO cubit.saved_cf_accounts (accid, category)\n\t\t\tSELECT accid, 'ciaal' FROM core.accounts WHERE catid='B10'");
        $qry->run();
        /*
        // Inventory
        db_conn("core");
        $sql = "SELECT accid FROM accounts WHERE accname='Inventory'";
        $rslt = db_exec($sql) or errDie("Unable to retrieve the inventory account.");
        $accid = pg_fetch_result($rslt, 0);
        
        db_conn("cubit");
        $sql = "INSERT INTO saved_cf_accounts (accid, category) VALUES ('$accid', 'ciaal')";
        $rslt = db_exec($sql) or errDie("Unable to add the inventory account.");
        
        // Accounts Receivable
        db_conn("core");
        $sql = "SELECT accid FROM accounts WHERE accname='Customer Control Account'";
        $rslt = db_exec($sql) or errDie("Unable to retrieve the accounts receivable account.");
        $accid = pg_fetch_result($rslt, 0);
        
        db_conn("cubit");
        $sql = "INSERT INTO saved_cf_accounts (accid, category) VALUES ('$accid', 'ciaal')";
        $rslt = db_exec($sql) or errDie("Unable to add the accounts receivable account.");
        */
    }
    return slct();
}
function recvpayment_write()
{
    if (isset($_POST["btn_back"])) {
        return details($_POST);
    }
    extract($_POST);
    $bank_acc = qryAccountsName("Cash on Hand");
    $bank_acc = $bank_acc["accid"];
    $cred_acc = qryAccountsName("POS Credit Card Control");
    $cred_acc = $cred_acc["accid"];
    $v = new validate();
    $v->isOk($cusnum, "num", 1, 10, "Invalid customer id.");
    $v->isOk($bank_acc, "num", 1, 10, "Invalid cash account selected.");
    $v->isOk($pcc, "float", 1, 40, "Invalid credit card amount.");
    $v->isOk($pcash, "float", 1, 40, "Invalid cash amount.");
    $v->isOk($pcheque, "float", 1, 40, "Invalid cheque amount.");
    $v->isOk($amt, "float", 1, 40, "Invalid total received amount.");
    $v->isOk($date, "date", 1, 1, "Invalid invoice date.");
    if ($v->isError()) {
        return details($_POST, $v->genErrors());
    }
    $sdate = $date;
    $cus = qryCustomer($cusnum);
    $dept = qryDepartment($cus["deptid"], "debtacc");
    $refnum = getrefnum();
    pglib_transaction("BEGIN");
    /* do the calculations/recordings */
    # update the customer (make balance less)
    $sql = "UPDATE cubit.customers SET balance = (balance - '{$amt}'::numeric(13,2))\r\n\t\t\tWHERE cusnum = '{$cus['cusnum']}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
    $sql = "SELECT prd,invnum,descrip,age FROM cubit.nons_invoices\r\n\t\t\tWHERE invid ='{$invid}' AND div = '" . USER_DIV . "'";
    $invRslt = db_exec($sql) or errDie("Unable to retrieve invoice details from database.");
    if (pg_numrows($invRslt) < 1) {
        return "<li class=err>Invalid Invoice Number.";
    }
    $inv = pg_fetch_array($invRslt);
    $inv['invnum'] += 0;
    # reduce the money that has been paid
    if ($amt) {
        $sql = "UPDATE cubit.nons_invoices\r\n\t\t\t\tSET balance = (balance - {$amt}::numeric(13,2))\r\n\t\t\t\tWHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
        $payRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
        $sql = "UPDATE cubit.open_stmnt\r\n\t\t\t\tSET balance = (balance - {$amt}::numeric(13,2))\r\n\t\t\t\tWHERE invid = '{$inv['invnum']}' AND div = '" . USER_DIV . "'";
        $payRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
        # record the payment on the statement
        $sql = "INSERT INTO cubit.stmnt(cusnum, invid, amount, date, type, div)\r\n\t\t\t\tVALUES('{$cus['cusnum']}','{$inv['invnum']}',\r\n\t\t\t\t'" . ($amt - $amt * 2) . "','{$sdate}',\r\n\t\t\t\t'Payment for Hire Invoice No. {$inv['invnum']}',\r\n\t\t\t\t'" . USER_DIV . "')";
        $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
        $cash_amt = $pcash + $pcheque;
        $cred_amt = $pcc;
        custledger($cus['cusnum'], $bank_acc, $sdate, $inv['invnum'], "Payment for Hire Invoice No. {$inv['invnum']}", $cash_amt, "c");
        custledger($cus["cusnum"], $cred_acc, $sdate, $inv["invnum"], "Payment for Hire Invoice No. {$inv['invnum']}", $cred_amt, "c");
        custCT($amt, $cus["cusnum"], $sdate);
        //recordCT($amt, $cus['cusnum'],$inv['age'],$sdate);
    }
    if (!isset($invids[$key])) {
        $invids[$key] = 0;
    }
    if (!isset($rinvids)) {
        $rinvids = 0;
    }
    if (!isset($amounts)) {
        $amounts = 0;
    }
    if (!isset($invprds)) {
        $invprds = 0;
    }
    if (!isset($rages)) {
        $rages = 0;
    }
    if (!isset($invidsers)) {
        $invidsers = 0;
    }
    $rinvids .= "|{$invids[$key]}";
    $amounts .= "|{$amt}";
    $invprds .= "|0";
    $rages .= "|{$inv['age']}";
    $invidsers .= " - {$inv['invnum']}";
    $sql = "SELECT * FROM core.accounts WHERE topacc='6400' AND accnum='000'";
    $acc_rslt = db_exec($sql);
    $deptacc = pg_fetch_result($acc_rslt, 0);
    if ((double) $pcash) {
        writetrans($bank_acc, $deptacc, $sdate, $refnum, $pcash, "Payment for Invoice {$inv['invnum']} from customer {$cus['cusname']} {$cus['surname']}");
    }
    if ((double) $pcc) {
        $sql = "SELECT accid FROM core.accounts WHERE topacc='7300' AND accnum='000'";
        $acc_rslt = db_exec($sql);
        $accid = pg_fetch_result($acc_rslt, 0);
        writetrans($accid, $deptacc, $sdate, $refnum, $pcc, "Payment for Invoice {$invidsers} from customer {$cus['cusname']} {$cus['surname']}");
    }
    if ((double) $pcheque) {
        $sql = "SELECT accid FROM core.accounts WHERE topacc='7200' AND accnum='000'";
        $acc_rslt = db_exec($sql);
        $accid = pg_fetch_result($acc_rslt, 0);
        writetrans($accid, $deptacc, $sdate, $refnum, $pcheque, "Payment for Invoice {$invidsers} from customer {$cus['cusname']} {$cus['surname']}");
    }
    db_conn('cubit');
    pglib_transaction("COMMIT");
    $_POST["pcc"] = $_POST["pcheque"] = $_POST["pcash"] = "0.00";
    return cdetails($_POST, "<li class='err'>Payment received successfully</li>");
}
function allocateStockToJob($jobcard_id, $stock_id, $units = 1)
{
    $refnum = getRefnum();
    $sysdate = date("Y-m-d");
    $stock_wh = getStore($stock_id);
    $production_wh = getProductionStore();
    $sql = "SELECT * FROM cubit.stock WHERE stkid='{$stock_id}'";
    $stock_rslt = db_exec($sql) or errDie("Unable to retrieve stock.");
    $stock_data = pg_fetch_array($stock_rslt);
    // Do we have this stock in the production store already
    $sql = "SELECT stkid FROM cubit.stock WHERE stkcod='{$stock_data['stkcod']}' AND whid='{$production_wh}'";
    $production_rslt = db_exec($sql) or errDie("Unable to retrieve production stock.");
    $production_id = pg_fetch_result($production_rslt, 0);
    if (!pg_num_rows($production_rslt)) {
        $sql = "\n\t\t\tINSERT INTO cubit.stock (\n\t\t\t\tstkcod, stkdes, prdcls, csamt, units, \n\t\t\t\tbuom, suom, rate, \n\t\t\t\tminlvl, whid, shelf, row, \n\t\t\t\ttype, catname, classname, \n\t\t\t\tcom, csprice, serd, \n\t\t\t\tlcsprice, vatcode, supplier1, \n\t\t\t\tsupplier2, supplier3, rfidfreq, \n\t\t\t\trfidrate, size, post_production, \n\t\t\t\ttreatment, div\n\t\t\t) VALUES (\n\t\t\t\t'{$stock_data['stkcod']}', '{$stock_data['stkdes']}', '{$stock_data['prdcls']}', '0', '0', \n\t\t\t\t'{$stock_data['buom']}', '{$stock_data['suom']}', '{$stock_data['rate']}', \n\t\t\t\t'{$stock_data['minlvl']}', '{$production_wh}', '{$stock_data['shelf']}', '{$stock_data['row']}', \n\t\t\t\t'{$stock_data['type']}', '{$stock_data['catname']}', '{$stock_data['classname']}', \n\t\t\t\t'{$stock_data['com']}', '{$stock_data['csprice']}', '{$stock_data['serd']}', \n\t\t\t\t'{$stock_data['lcsprice']}', '{$stock_data['vatcode']}', '{$stock_data['supplier1']}', \n\t\t\t\t'{$stock_data['supplier2']}', '{$stock_data['supplier3']}', '{$stock_data['rfidfreq']}', \n\t\t\t\t'{$stock_data['rfidrate']}', '{$stock_data['size']}', '{$stock_data['post_production']}', \n\t\t\t\t'{$stock_data['treatment']}', '" . USER_DIV . "'\n\t\t\t)";
        db_exec($sql) or errDie("Unable to create in stock store.");
        $production_id = pglib_lastid("cubit.stock", "stkid");
        for ($i = 1; $i <= 12; $i++) {
            $sql = "\n\t\t\t\tINSERT INTO \"{$i}\".stkledger (\n\t\t\t\t\tstkid, stkcod, stkdes, trantype, \n\t\t\t\t\tedate, qty, csamt, balance, bqty, details, div, yrdb\n\t\t\t\t) VALUES (\n\t\t\t\t\t'{$production_id}', '{$stock_data['stkcod']}', '{$stock_data['stkdes']}', 'bal', \n\t\t\t\t\t'{$sysdate}', '0', '0', '0', '0','Balance', '" . USER_DIV . "','" . YR_DB . "'\n\t\t\t\t)";
            db_exec($sql) or errDie("Unable to create ledger entries.");
        }
    }
    $details = "Stock allocated to job {$jobcard_id}";
    reduceStock($stock_id, $units, $details);
    increaseStock($production_id, $units, $details);
    $production_acc = qryAccountsName("Inventory in Production");
    $production_acc = $production_acc["accid"];
    $inventory_acc = qryAccountsName("Inventory");
    $inventory_acc = $inventory_acc["accid"];
    $amount = getStockCostPrice($stock_id) * $units;
    writetrans($production_acc, $inventory_acc, $sysdate, $refnum, $amount, $details);
    return;
}
function write($HTTP_VARS)
{
    extract($HTTP_VARS);
    if (isset($back)) {
        return enter($HTTP_VARS);
    }
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($id, "num", 1, 20, "Invalid employee number.");
    $v->isOk($bankid, "num", 1, 20, "Invalid bank number.");
    $v->isOk($paidamount, "float", 1, 10, "Invalid amount.");
    if (isset($account)) {
        $v->isOk($account, "num", 1, 100, "Invalid account.");
    }
    $ydate = mkdate($date_year, $date_month, $date_day);
    $v->isOk($ydate, "date", 1, 1, "Invalid payment date selected.");
    # display errors, if any
    if ($v->isError()) {
        $confirmCust = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $confirmCust .= "<li class='err'>" . $e["msg"] . "</li>";
        }
        $confirmCust .= "<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $confirmCust;
    }
    //$date=date("d-m-Y");
    $salconacc = gethook("accnum", "salacc", "name", "salaries control");
    $cash_account = gethook("accnum", "salacc", "name", "cash");
    pglib_transaction("BEGIN");
    $refnum = getrefnum($ydate);
    $paidamount = sprint($paidamount);
    db_conn('cubit');
    $Sl = "SELECT * FROM employees WHERE empnum='{$id}'";
    $Ri = db_exec($Sl) or errDie("Unable to get data.");
    if (pg_num_rows($Ri) < 1) {
        return "Invalid employee.";
    }
    $edata = pg_fetch_array($Ri);
    /* if we came from the cashbook, always use bank payment */
    if ($bankpay && $bankpay == "t") {
        $edata["paytype"] = "Cheque";
    } else {
        $bankpay = "f";
    }
    db_conn('cubit');
    $Sl = "UPDATE employees SET balance=balance-'{$paidamount}' WHERE empnum = '{$id}' AND div = '" . USER_DIV . "'";
    $Ri = db_exec($Sl) or errDie("Unable to get employee details.");
    // 	if($edata['paytype']=="Cash") {
    //
    // 		writetrans($salconacc, $cash_account, $date, $refnum, $paidamount, "Salary Payment(Cash) for employee,  $edata[fnames] $edata[sname].");
    //
    // 		empledger($id, $cash_account, $ydate, $refnum,"Payment(Cash)" ,  $paidamount, "d");
    //
    // 	}
    if ($edata['paytype'] == "Ledger Account") {
        writetrans($salconacc, $account, $ydate, $refnum, $paidamount, "Salary Payment(Ledger Account) for employee,  {$edata['fnames']} {$edata['sname']}.");
        empledger($id, $account, $ydate, $refnum, "Payment(Ledger Account)", $paidamount, "d");
    } else {
        core_connect();
        if ($edata["paytype"] == "Cash") {
            $bank = qryAccountsName("Cash on Hand", "accid");
            $bankacc = $bank["accid"];
        } else {
            $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.";
            }
            $bank = pg_fetch_array($Rslt);
            $bankacc = $bank["accnum"];
            banktrans($bankid, "withdrawal", $ydate, "{$edata['fnames']} {$edata['sname']}", "Salary Payment for employee,  {$edata['fnames']} {$edata['sname']}", 0, $paidamount, $salconacc, $edata['empnum']);
        }
        writetrans($salconacc, $bankacc, $ydate, $refnum, $paidamount, "Salary Payment for employee,  {$edata['fnames']} {$edata['sname']}.");
        empledger($id, $bankacc, $ydate, $refnum, "Payment(Bank)", $paidamount, "d");
    }
    pglib_transaction("COMMIT");
    $out = "\n\t\t<table " . TMPL_tblDflts . ">\n\t\t\t<tr>\n\t\t\t\t<th>Payment Processed</th>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Employee payment has been processed.</td>\n\t\t\t</tr>\n\t\t</table>";
    return $out;
}
function write()
{
    extract($_REQUEST);
    require_lib("validate");
    $v = new validate();
    $v->isOk($cusnum, "num", 1, 20, "Invalid customer selection.");
    $v->isOk($amount, "float", 1, 20, "Invalid amount.");
    // Retrieve cash on hand and customer accounts
    list($coh_acc) = array_values(qryAccountsName("Cash on Hand"));
    list($cus_acc) = array_values(qryAccountsName("Customer Control Account"));
    // Retrieve cash on hand account balance
    $sql = "\n\tSELECT (debit - credit) AS balance FROM core.trial_bal\n\tWHERE period='" . PRD_DB . "' AND accid='{$coh_acc}'";
    $bal_rslt = db_exec($sql) or errDie("Unable to retrieve cash on hand balance.");
    $coh_bal = pg_fetch_result($bal_rslt, 0);
    // See if we have enough money available in cash on hand
    if ($coh_bal < $amount) {
        $v->addError(0, "Not enough cash available in cash on hand account.");
    }
    // Make sure the refund amount is not more than the deposit
    if (is_numeric($cash_id)) {
        $sql = "SELECT cash FROM hire.cash WHERE id='{$cash_id}'";
        $deposit_rslt = db_exec($sql) or errDie("Unable to retrieve deposit.");
        $deposit_amount = pg_fetch_result($deposit_rslt, 0);
        if ($deposit_amount < $amount) {
            $v->addError(0, "Refund amount cannot be more than the deposit amount.");
        }
    }
    if ($v->isError()) {
        return enter($v->genErrors());
    }
    $refnum = getrefnum();
    $date = date("Y-m-d");
    pglib_transaction("BEGIN");
    $sql = "\n\tUPDATE cubit.customers SET balance=(balance + '{$amount}')\n\tWHERE cusnum='{$cusnum}'";
    db_exec($sql) or errDie("Unable to update customer balance.");
    // Do the reversal
    writetrans($cus_acc, $coh_acc, $date, $refnum, $amount, "Customer Refund for Hire No H{$invnum}");
    // Retrieve bank account
    $sql = "SELECT bankid FROM cubit.customers WHERE cusnum='{$cusnum}'";
    $bank_rslt = db_exec($sql) or errDie("Unable to retrieve customers.");
    $bankid = pg_fetch_result($bank_rslt, 0);
    if (!$bankid) {
        $sql = "SELECT bankid FROM cubit.bankacct";
        $bank_rslt = db_exec($sql) or errDie("Unable to retrieve bank");
        $bankid = pg_fetch_result($bank_rslt, 0);
    }
    custledger($cusnum, $coh_acc, $date, $invnum, "Customer Refund for Hire No H{$invnum}", $amount, "d");
    $sql = "\n\tINSERT INTO cubit.stmnt (cusnum, invid, docref, amount, date, type, div)\n\tVALUES ('{$cusnum}', '{$invid}', '{$invnum}', '{$amount}', '{$date}',\n\t\t'Customer Refund for Hire No H{$invnum}', '" . USER_DIV . "')";
    db_exec($sql) or errDie("Unable to add to statement.");
    $sql = "SELECT cash FROM hire.cash WHERE id='{$cash_id}'";
    $cash_rslt = db_exec($sql) or errDie("Unable to retrieve cash.");
    $cash_amount = pg_fetch_result($cash_rslt, 0);
    if ($cash_amount - $amount == 0) {
        $sql = "DELETE FROM hire.cash WHERE id='{$cash_id}'";
        db_exec($sql) or errDie("Unable to remove deposit.");
    } else {
        $sql = "UPDATE hire.cash SET cash=(cash-'{$amount}') WHERE id='{$cash_id}'";
        db_exec($sql) or errDie("Unable to update deposit.");
    }
    pglib_transaction("COMMIT");
    $OUTPUT = "\n\t<h3>Customer Refund</h3>\n\t<table " . TMPL_tblDflts . ">\n\t\t<tr>\n\t\t\t<th>Write</th>\n\t\t</tr>\n\t\t<tr class='" . bg_class() . "'>\n\t\t\t<td><li>Successfully refunded customer.</li></td>\n\t\t</tr>\n\t</table>";
    return $OUTPUT;
}