function enter()
{
    extract($_REQUEST);
    $fields = array();
    $fields["user_id"] = USER_ID;
    extract($fields, EXTR_SKIP);
    // Retrieve users
    $users_out = "";
    if (user_is_admin(USER_NAME)) {
        $sql = "\r\n\t\tSELECT DISTINCT user_id, username FROM cubit.hire_trans\r\n\t\t\tLEFT JOIN cubit.users ON hire_trans.user_id=users.userid\r\n\t\tWHERE done='t' AND processed='0'\r\n\t\tORDER BY username ASC";
        $user_rslt = db_exec($sql) or errDie("Unable to retrieve users.");
        $user_sel = "<select name='user_id'>";
        while ($user_data = pg_fetch_array($user_rslt)) {
            $sel = $user_id == $user_data["user_id"] ? "selected" : "";
            $user_sel .= "\r\n\t\t\t<option value='{$user_data['user_id']}' {$sel}>\r\n\t\t\t\t{$user_data['username']}\r\n\t\t\t</option>";
        }
        $user_sel .= "</select>";
        $users_out = "\r\n\t\t<form method='post' action='" . SELF . "'>\r\n\t\t<input type='hidden' name='key' value='enter' />\r\n\t\t<table " . TMPL_tblDflts . ">\r\n\t\t\t<tr>\r\n\t\t\t\t<th colspan='2'>User</th>\r\n\t\t\t</tr>\r\n\t\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t\t<td>{$user_sel}</td>\r\n\t\t\t\t<td><input type='submit' value='Select' /></td>\r\n\t\t\t</tr>\r\n\t\t</table>\r\n\t\t</form>";
    }
    // Get outstanding rentals count
    $sql = "\r\n\tSELECT count(id) FROM cubit.hire_trans\r\n\tWHERE user_id='{$user_id}' AND done='t' AND processed='0'";
    $trans_rslt = db_exec($sql) or errDie("Unable to retrieve transactions.");
    $trans_count = pg_fetch_result($trans_rslt, 0);
    $sql = "\r\n\tSELECT count(id) FROM cubit.hire_trans_returned\r\n\tWHERE processed='f'";
    $rtrans_rslt = db_exec($sql) or errDie("Unable to retrieve returns.");
    $trans_count += pg_fetch_result($rtrans_rslt, 0);
    $OUTPUT = "\r\n\t<center>\r\n\t<h3>Video POS Cashup</h3>\r\n\t{$users_out}\r\n\t<table " . TMPL_tblDflts . ">\r\n\t\t<tr>\r\n\t\t\t<th>Type</th>\r\n\t\t\t<th>Total Outstanding</th>\r\n\t\t</tr>\r\n\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t<td>Video Rentals</td>\r\n\t\t\t<td>{$trans_count}</td>\r\n\t\t</tr>\r\n\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t<td colspan='2' align='center'>\r\n\t\t\t\t<a href='" . SELF . "?key=run&user_id={$user_id}'\r\n\t\t\t\tstyle='font-size: 1.6em'>Run</a>\r\n\t\t\t</td>\r\n\t\t</tr>\r\n\t</table>";
    return $OUTPUT;
}
function enter()
{
    extract($_REQUEST);
    $fields = array();
    $fields["user_id"] = USER_ID;
    extract($fields, EXTR_SKIP);
    $users_out = "";
    if (user_is_admin(USER_NAME)) {
        $sql = "SELECT DISTINCT user_id FROM cubit.hire_trans";
        $user_rslt = db_exec($sql) or errDie("Unable to retrieve user ids.");
        $users_sel = "<select name='user_id'>";
        while ($user_data = pg_fetch_array($user_rslt)) {
            $sql = "\n\t\t\tSELECT username FROM cubit.users\n\t\t\tWHERE userid='{$user_data['user_id']}'";
            $username_rslt = db_exec($sql) or errDie("Unable to retrieve user.");
            $username = pg_fetch_result($username_rslt, 0);
            $sel = $user_data["user_id"] == $user_id ? "selected='t'" : "";
            $users_sel .= "\n\t\t\t<option value='{$user_data['user_id']}' {$sel}>\n\t\t\t\t{$username}\n\t\t\t</option";
        }
        $users_sel .= "</select>";
        $users_out = "\n\t\t<form method='post' action='" . SELF . "'>\n\t\t<input type='hidden' name='key' value='enter' />\n\t\t<table " . TMPL_tblDflts . ">\n\t\t\t<tr>\n\t\t\t\t<th colspan='2'>User</th>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>{$users_sel}</td>\n\t\t\t\t<td><input type='submit' value='Select' /></td>\n\t\t\t</tr>\n\t\t</table>\n\t\t</form>";
    }
    // Get outstanding rentals count
    $sql = "\n\tSELECT count(id) FROM cubit.hire_trans\n\tWHERE user_id='{$user_id}' AND done='y'";
    $rental_rslt = db_exec($sql) or errDie("Unable to retrieve outstanding rentals");
    $rental_count = pg_fetch_result($rental_rslt, 0);
    // Get outstanding invoices count
    $sql = "\n\tSELECT count(id) FROM cubit.hire_invoice_trans\n\tWHERE user_id='" . $user_id . "' AND done='t' AND hire_id > 0";
    $invoice_rslt = db_exec($sql) or errDie("Unable to retrieve outstanding invoices.");
    $invoice_count = pg_fetch_result($invoice_rslt, 0);
    $OUTPUT = "\n\t<center>\n\t<h3>Rental POS Cash Up</h3>\n\t{$users_out}\n\t<table " . TMPL_tblDflts . ">\n\t\t<tr>\n\t\t\t<th>Type</th>\n\t\t\t<th>Total Outstanding</th>\n<!--\n\t\t\t<th colspan='2'>Options</th>\n-->\n\t\t</tr>\n\t\t<tr class='" . bg_class() . "'>\n\t\t\t<td>Rentals</td>\n\t\t\t<td>{$rental_count}</td>\n<!--\n\t\t\t<td>\n\t\t\t\t<a href='" . SELF . "?key=run&type=rental&user_id={$user_id}'>\n\t\t\t\t\tRun\n\t\t\t\t</a>\n\t\t\t</td>\n\t\t\t<td>\n\t\t\t\t<a href='" . SELF . "?key=view_rental&type=rental&user_id={$user_id}'>\n\t\t\t\t\tView\n\t\t\t\t</a>\n\t\t\t</td>\n-->\n\t\t</tr>\n\t\t<tr class='" . bg_class() . "'>\n\t\t\t<td>Invoices</td>\n\t\t\t<td>{$invoice_count}</td>\n<!--\t\t\t\n\t\t\t<td>\n\t\t\t\t<a href='" . SELF . "?key=run&type=invoice&user_id={$user_id}'>\n\t\t\t\t\tRun\n\t\t\t\t</a>\n\t\t\t</td>\n\t\t\t<td>\n\t\t\t\t<a href='" . SELF . "?key=view&type=invoice&user_id={$user_id}'>\n\t\t\t\t\tView\n\t\t\t\t</a>\n\t\t\t</td>\n-->\n\t\t</tr>\n\t\t<tr class='" . bg_class() . "'>\n\t\t\t<td colspan='4' align='center'>\n\t\t\t\t<a href='" . SELF . "?key=run&user_id={$user_id}'\n\t\t\t\tstyle='font-size: 1.6em'>Run</a>\n\t\t\t</td>\n\t\t</tr>\n\t</table>\n\t</center>";
    return $OUTPUT;
}
function tweet_delete()
{
    include_once 'login.php';
    include_once 'sinaoauth.inc.php';
    $id = get_current_user_id();
    $args = func_get_args();
    $key = $args[2];
    if (!$key) {
        die('Invalid Argument!');
    }
    connect_db();
    $view = "SELECT tweets.* FROM tweets, (SELECT user_id, user_site_id, site_id FROM accountbindings) AS ac WHERE tweets.user_site_id = ac.user_site_id AND ac.user_id='{$id}' AND ac.site_id = tweets.site_id AND tweets.tweet_id='{$key}' AND tweets.deleted='0'";
    $list = mysql_query($view);
    $row = mysql_fetch_array($list);
    if ($row or user_is_admin()) {
        if ($row) {
            $c = new WeiboClient(SINA_AKEY, SINA_SKEY, $GLOBALS['user']['sinakey']['oauth_token'], $GLOBALS['user']['sinakey']['oauth_token_secret']);
            $msg = $c->destroy($row['tweet_site_id']);
        }
        $view = "UPDATE tweets SET deleted='1' WHERE tweet_id='{$key}'";
        $list = mysql_query($view) or die("Delete error!");
    } else {
        print $key;
        die(": Non-exist Error!");
    }
}
function display()
{
    extract($_REQUEST);
    if (user_is_admin(USER_ID)) {
        $user_id = $_REQUEST["user_id"];
    } else {
        $user_id = USER_ID;
    }
    // Retrieve user information
    $sql = "SELECT * FROM cubit.users WHERE userid='{$user_id}'";
    $user_rslt = db_exec($sql) or errDie("Unable to retrieve user.");
    $user_data = pg_fetch_array($user_rslt);
    define("SECONDS_IN_7_DAYS", 604800);
    $seven_days = date("Y-m-d", time() + SECONDS_IN_7_DAYS);
    // Retrieve orders for expired orders and orders that will expire within
    // 7 days
    $sql = "SELECT * FROM cubit.sorders\n\t\t\tWHERE ddate<'{$seven_days}' AND accepted='n' AND done='y'\n\t\t\t\tAND username='******'username']}'\n\t\t\tORDER BY ddate DESC";
    $sorder_rslt = db_exec($sql) or errDie("Unable to retrieve sales orders.");
    $sorder_out = "";
    while ($sorder_data = pg_fetch_array($sorder_rslt)) {
        $sorder_out .= "\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>{$sorder_data['ddate']}</td>\n\t\t\t\t<td>{$sorder_data['odate']}</td>\n\t\t\t\t<td>{$sorder_data['cusname']} {$sorder_data['surname']}</td>\n\t\t\t\t<td>{$sorder_data['ordno']}</td>\n\t\t\t\t<td>{$sorder_data['cusname']}</td>\n\t\t\t\t<td>" . CUR . "{$sorder_data['discount']}</td>\n\t\t\t\t<td>" . CUR . "{$sorder_data['total']}</td>\n\t\t\t</tr>";
    }
    if (empty($sorder_out)) {
        $sorder_out = "\n\t\t<tr class='" . bg_class() . "'>\n\t\t\t<td colspan='7'>No items found</td>\n\t\t</tr>";
    }
    $OUTPUT = "\n\t\t<center>\n\t\t<h3>Sales Orders Past Due/Delivery Date</h3>\n\t\t<table " . TMPL_tblDflts . ">\n\t\t\t<tr>\n\t\t\t\t<th>Due Date</th>\n\t\t\t\t<th>Sales Order Date</th>\n\t\t\t\t<th>Customer</th>\n\t\t\t\t<th>Sales Order No</th>\n\t\t\t\t<th>Customer Order No</th>\n\t\t\t\t<th>Discount</th>\n\t\t\t\t<th>Total</th>\n\t\t\t</tr>\n\t\t\t{$sorder_out}\n\t\t</table>\n\t\t</center>";
    return $OUTPUT;
}
function user_ensure_admin()
{
    user_ensure_authenticated();
    if (!user_is_admin()) {
        header("Location: " . BASE_URL . "?errormsg=" . urlencode("不要做坏事哟^o^"));
        die("Access denied");
    }
}
 function user_in_store_team($whid, $user_id)
 {
     if (user_is_admin($user_id)) {
         return true;
     }
     $sql = "SELECT team_id FROM exten.warehouses WHERE whid='{$whid}'";
     $wh_rslt = db_exec($sql) or errDie("Unable to retrieve stores.");
     $team_id = pg_fetch_result($wh_rslt, 0);
     return user_in_team($team_id, $user_id);
 }
Exemple #7
0
 public function __construct()
 {
     parent::__construct();
     $this->load->library(array('session', 'form_validation'));
     $this->load->helper('string');
     $this->load->database();
     $this->load->model('user_model');
     if (!logged_in() or !user_is_admin()) {
         redirect('user/login');
     }
 }
function write($_POST)
{
    extract($_POST);
    if (isset($back)) {
        unset($_POST["back"]);
        return enter($_POST);
    }
    # CHECK IF THIS DATE IS IN THE BLOCKED RANGE
    $blocked_date_from = getCSetting("BLOCKED_FROM");
    $blocked_date_to = getCSetting("BLOCKED_TO");
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($bankid, "num", 1, 20, "Invalid Bank ID.");
    foreach ($amount as $key => $value) {
        # check all vars
        $v->isOk($to[$key], "string", 1, 255, "Invalid receipient/depositor.");
        $v->isOk($trantype[$key], "string", 1, 20, "Invalid transaction type.");
        $v->isOk($descript[$key], "string", 0, 255, "Invalid description.");
        $v->isOk($ref[$key], "string", 0, 255, "Invalid reference <b>[{$key}]</b>.");
        $v->isOk($cheqnum[$key], "num", 0, 20, "Invalid cheque number <b>[{$key}]</b>.");
        $v->isOk($amount[$key], "float", 1, 8, "Invalid amount <b>[{$key}]</b>.");
        $v->isOk($accinv[$key], "num", 1, 20, "Invalid account involved <b>[{$key}]</b>.");
        $v->isOk($date[$key], "date", 1, 15, "Invalid date <b>[{$key}]</b>.");
        if (strtotime($date[$key]) >= strtotime($blocked_date_from) and strtotime($date[$key]) <= 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>";
        }
    }
    # 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='&laquo; Correct submission'>";
        return $confirm;
    }
    # Processes
    db_connect();
    # Begin Transaction
    pglib_transaction("BEGIN");
    # Some info
    $bankacc = getbankaccid($bankid);
    $vatacc = gethook("accnum", "salesacc", "name", "VAT");
    foreach ($amount as $key => $amt) {
        $totamt = $amount[$key];
        if ($chrgvat[$key] == "exc") {
            $totamt += $vat[$key];
        } elseif ($chrgvat[$key] == "inc") {
            $amount[$key] -= $vat[$key];
        } else {
            $vat[$key] = "No VAT";
        }
        if ($cheqnum[$key] == '') {
            $cheqnum[$key] = 0;
        }
        if (!isset($batch)) {
            $refnum = getrefnum();
            if (strtolower($trantype[$key]) == 'deposit') {
                $vatacc = gethook("accnum", "salesacc", "name", "VAT", "1");
                writetrans($bankacc, $accinv[$key], $date[$key], $refnum, $amount[$key], $descript[$key]);
                if ($vat[$key] != 0) {
                    # DT(Bank), CT(VAT)
                    $vat[$key] += 0;
                    writetrans($bankacc, $vatacc, $date[$key], $refnum, $vat[$key], $descript[$key] . " VAT");
                    db_conn('cubit');
                    $Sl = "SELECT * FROM vatcodes WHERE id='{$vatcode[$key]}'";
                    $Rt = db_exec($Sl) or errDie("Unable to get data.");
                    $vd = pg_fetch_array($Rt);
                    vatr($vatcode[$key], $date[$key], "OUTPUT", $vd['code'], $refnum, $descript[$key] . " VAT", $totamt, $vat[$key]);
                }
            } else {
                $vatacc = gethook("accnum", "salesacc", "name", "VAT");
                writetrans($accinv[$key], $bankacc, $date[$key], $refnum, $amount[$key], $descript[$key]);
                if ($vat[$key] != 0) {
                    # DT(Bank), CT(VAT)
                    $vat[$key] += 0;
                    writetrans($vatacc, $bankacc, $date[$key], $refnum, $vat[$key], $descript[$key] . " VAT");
                    db_conn('cubit');
                    $Sl = "SELECT * FROM vatcodes WHERE id='{$vatcode[$key]}'";
                    $Rt = db_exec($Sl) or errDie("Unable to get data.");
                    $vd = pg_fetch_array($Rt);
                    vatr($vatcode[$key], $date[$key], "INPUT", $vd['code'], $refnum, $descript[$key] . " VAT", -$totamt, -$vat[$key]);
                }
            }
            $vat[$key] += 0;
            db_connect();
            $sql = "\n\t\t\t\tINSERT INTO cashbook (\n\t\t\t\t\tbankid, trantype, date, name, descript, cheqnum, \n\t\t\t\t\tamount, banked, accinv, div,chrgvat,vat,reference\n\t\t\t\t) VALUES (\n\t\t\t\t\t'{$bankid}', lower('{$trantype[$key]}'), '{$date[$key]}', '{$to[$key]}', '{$descript[$key]}', '{$cheqnum[$key]}', \n\t\t\t\t\t'{$totamt}', 'no', '{$accinv[$key]}', '" . USER_DIV . "','{$chrgvat[$key]}', '{$vat[$key]}','{$ref[$key]}'\n\t\t\t\t)";
            $Rslt = db_exec($sql) or errDie("Unable to add bank payment to database.", SELF);
        } else {
            db_connect();
            $vat[$key] += 0;
            $sql = "\n\t\t\t\tINSERT INTO batch_cashbook (\n\t\t\t\t\tbankid, trantype, date, name, descript, cheqnum, \n\t\t\t\t\tamount, banked, accinv, div, chrgvat, vat, vatcode, \n\t\t\t\t\treference\n\t\t\t\t) VALUES (\n\t\t\t\t\t'{$bankid}', lower('{$trantype[$key]}'), '{$date[$key]}', '{$to[$key]}', '{$descript[$key]}', '{$cheqnum[$key]}', \n\t\t\t\t\t'{$totamt}', 'no', '{$accinv[$key]}', '" . USER_DIV . "','{$chrgvat[$key]}','{$vat[$key]}','{$vatcode[$key]}', \n\t\t\t\t\t'{$ref[$key]}'\n\t\t\t\t)";
            $Rslt = db_exec($sql) or errDie("Unable to add bank payment to database.", SELF);
        }
    }
    # Get bank details
    $bankAccRslt = get("cubit", "*", "bankacct", "bankid", $bankid);
    $bankacc = pg_fetch_array($bankAccRslt);
    pglib_transaction("COMMIT");
    if (!isset($batch)) {
        $write = "\n\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t<tr>\n\t\t\t\t\t<th>Statement Recorded</th>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='datacell'>\n\t\t\t\t\t<td>New Statement Details for account, <b>{$bankacc['accname']} ({$bankacc['accnum']})</b><br>held at <b>{$bankacc['bankname']}</b>, was successfully added to Cubit.</td>\n\t\t\t\t</tr>\n\t\t\t</table>";
    } else {
        $write = "\n\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t<tr>\n\t\t\t\t\t<th>Batch entries recorded</th>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='datacell'>\n\t\t\t\t\t<td>New batch items for account, <b>{$bankacc['accname']} ({$bankacc['accnum']})</b><br>held at <b>{$bankacc['bankname']}</b>, was successfully added to Cubit.</td>\n\t\t\t\t</tr>\n\t\t\t</table>";
    }
    # Main table (layout with menu)
    $OUTPUT = "\n\t\t<center>\n\t\t<table width='90%'>\n\t\t\t<tr valign='top'>\n\t\t\t\t<td width='50%'>{$write}</td>\n\t\t\t\t<td align='center'>" . mkQuickLinks(ql("bank-pay-add.php", "Add Bank Payment"), ql("bank-recpt-add.php", "Add Bank Receipt"), ql("cashbook-view.php", "View Cash Book"), ql("batch-cashbook-view.php", "View Batch Cashbook")) . "\n\t\t\t\t</td>\n\t\t\t</tr>\n\t\t</table>";
    return $OUTPUT;
}
function printSord()
{
    extract($_REQUEST);
    if (isset($key)) {
        $key = strtolower($key);
        switch ($key) {
            case "export to spreadsheet":
            case "print":
            case "save":
                $pure = true;
                break;
            case "view":
            default:
                $pure = false;
        }
    } else {
        $pure = false;
    }
    if (!isset($from_year)) {
        explodeDate(false, $from_year, $from_month, $from_day);
        explodeDate(false, $to_year, $to_month, $to_day);
    }
    $printSord = "";
    if (!$pure) {
        $printSord .= "\n\t\t<form method='post' action='" . SELF . "'>\n\t    <table " . TMPL_tblDflts . ">\n\t    <tr>\n\t    \t<th colspan='2'>View Options</th>\n\t    </tr>\n\t    <tr class='" . bg_class() . "'>\n\t    \t<td>Begin Date:</td>\n\t    \t<td>" . mkDateSelect("from", $from_year, $from_month, $from_day) . "</td>\n\t\t</tr>\n\t\t<tr class='" . bg_class() . "'>\n\t    \t<td>End Date:</td>\n\t    \t<td>" . mkDateSelect("to", $to_year, $to_month, $to_day) . "</td>\n\t    </tr>\n\t    <tr>\n\t    \t<td colspan='2' align='right'><input type='submit' value='Filter' /></td>\n\t    </tr>\n\t    </table>";
    }
    if (!isset($key)) {
        $printSord .= "</form>";
        return $printSord;
    }
    $printSord .= "\n\t<table " . TMPL_tblDflts . ">\n\t<tr>\n\t\t<th>Department</th>\n\t\t<th>Sales Person</th>\n\t\t<th>Sales Order No.</th>\n\t\t<th>Sales Order Date</th>\n\t\t<th>Customer Name</th>\n\t\t<th>Order No</th>\n\t\t" . ($pure ? "" : "<th colspan=6>Options</th>") . "\n\t</tr>";
    $i = 0;
    $sql = "SELECT * FROM cubit.sorders\n    \t\tWHERE accepted = 'n' AND done = 'y' AND div = '" . USER_DIV . "' AND\n    \t\t\todate BETWEEN '{$from_year}-{$from_month}-{$from_day}' AND \n    \t\t\t\t'{$to_year}-{$to_month}-{$to_day}' AND slip_done='n'\n    \t\tORDER BY sordid DESC";
    $sordRslt = db_exec($sql) or errDie("Unable to retrieve Sales Orders.");
    if (pg_numrows($sordRslt) < 1) {
        $printSord .= "\n\t\t<tr bgcolor='" . bgcolorc(0) . "'>\n\t\t\t<td colspan='13'>No Sales Orders matching criteria.</td>\n\t\t</tr>";
    } else {
        while ($sord = pg_fetch_array($sordRslt)) {
            # alternate bgcolor
            $bgColor = bgcolor($i);
            # format date
            $sord['odate'] = explode("-", $sord['odate']);
            $sord['odate'] = $sord['odate'][2] . "-" . $sord['odate'][1] . "-" . $sord['odate'][0];
            $det = "sorder-details.php";
            $cancel = "sorder-cancel.php";
            $accept = "sorder-accept.php";
            $print = "sorder-print.php";
            $edit = "sorder-new.php";
            if ($sord['location'] == 'int') {
                $det = "intsorder-details.php";
                $cancel = "intsorder-cancel.php";
                $accept = "intsorder-accept.php";
                $print = "intsorder-print.php";
                $edit = "intsorder-new.php";
            }
            $sp4 = "&nbsp;&nbsp;&nbsp;&nbsp;";
            $bcurr = CUR;
            if ($sord['location'] == 'int') {
                $bcurr = $sord['currency'];
            }
            if ($sord["username"] == USER_NAME || user_is_admin(USER_NAME)) {
                $done = "\n\t\t\t\t<a href='picking_slip_done.php?sordid={$sord['sordid']}'>\n\t\t\t\t\tCancel\n\t\t\t\t</a>";
            } else {
                $done = "";
            }
            $printSord .= "<tr class='" . bg_class() . "'>\n\t\t\t\t<td>{$sord['deptname']}</td>\n\t\t\t\t<td>{$sord['salespn']}</td>\n\t\t\t\t<td>{$sord['sordid']}</td>\n\t\t\t\t<td align=center>{$sord['odate']}</td>\n\t\t\t\t<td>{$sord['cusname']} {$sord['surname']}</td>\n\t\t\t\t<td align=right>{$sord['ordno']}</td>\n\t\t\t\t<td>\n\t\t\t\t\t<a href='javascript:printer(\"picking_slips/picking_slip_print.php?sordid={$sord['sordid']}\")'>\n\t\t\t\t\t\tPrint Picking Slip\n\t\t\t\t\t</a>\n\t\t\t\t</td>\n\t\t\t\t<td>\n\t\t\t\t\t<a href='" . SELF . "?key=invoice&sordid={$sord['sordid']}'>\n\t\t\t\t\t\tInvoice\n\t\t\t\t\t</a>\n\t\t\t\t</td>\n\t\t\t\t<td>\n\t\t\t\t\t<a href='" . SELF . "?key=pos_invoice&sordid={$sord['sordid']}'>\n\t\t\t\t\t\tPOS Invoice\n\t\t\t\t\t</a>\n\t\t\t\t</td>\n\t\t\t\t<td>{$done}</td>";
        }
    }
    if (!$pure) {
        $printSord .= "\n\t\t</table>\n\t\t</form>";
    } else {
        $printSord .= "\n\t\t</table>";
        $OUTPUT = clean_html($printSord);
        switch ($key) {
            case "export to spreadsheet":
                require_lib("xls");
                StreamXLS("sorders", $OUTPUT);
                break;
            case "print":
                $OUTPUT = "<h3>Sales Orders</h3>{$OUTPUT}";
                require "tmpl-print.php";
                break;
            case "save":
                $pure = true;
                break;
        }
    }
    return $printSord;
}
function write($_GET)
{
    # get vars
    extract($_GET);
    # validate input
    require_lib("validate");
    $v = new validate();
    $prd += 0;
    $v->isOk($purid, "num", 1, 20, "Invalid Invoice number.");
    $sndate = $p_year . "-" . $p_month . "-" . $p_day;
    if (!checkdate($p_month, $p_day, $p_year)) {
        $v->addError($sdate, "Invalid Date.");
    }
    $td = $sndate;
    foreach ($ids as $key => $id) {
        $v->isOk($id, "num", 1, 20, "Invalid Item number.");
        $v->isOk($qtys[$key], "num", 1, 20, "Invalid Item quantity.");
        //$v->isOk ($amts[$key], "float", 1, 20, "Invalid Item amount.");
    }
    //$v->isOk ($subtot, "float", 1, 20, "Invalid sub-total amount.");
    //$v->isOk ($vat, "float", 1, 20, "Invalid vat amount.");
    //$v->isOk ($total, "float", 1, 20, "Invalid total amount.");
    # display errors, if any
    if ($v->isError()) {
        $err = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $err .= "<li class='err'>" . $e["msg"] . "</li>";
        }
        $confirm .= "<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $confirm;
    }
    # CHECK IF THIS DATE IS IN THE BLOCKED RANGE
    $blocked_date_from = getCSetting("BLOCKED_FROM");
    $blocked_date_to = getCSetting("BLOCKED_TO");
    if (strtotime($sndate) >= strtotime($blocked_date_from) and strtotime($sndate) <= 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>";
    }
    $cvacc = gethook("accnum", "pchsacc", "name", "Cost Variance");
    db_conn($prd);
    # Get invoice info
    $sql = "SELECT * FROM nons_purchases WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
    $invRslt = db_exec($sql) or errDie("Unable to get invoice information");
    if (pg_numrows($invRslt) < 1) {
        return "<i class='err'>Not Found{$sql}</i>";
    }
    $inv = pg_fetch_array($invRslt);
    db_conn("cubit");
    $sql = "SELECT * FROM nons_purchasesn";
    $purRslt = db_exec($sql) or errDie("Unable to get Non-Stock Order information");
    if (pg_numrows($purRslt) < 1) {
        $noteid = 2;
    } else {
        $noteid = pglib_lastid("nons_purchasesn", "id");
        $noteid++;
    }
    $refnum = getrefnum();
    db_conn("cubit");
    if ($inv['spurnum'] > 0) {
        if ($inv['ctyp'] == "sup") {
            $inv['ctyp'] = 's';
            $inv['supid'] = $inv['typeid'];
        } elseif ($inv['ctyp'] == "led") {
            $inv['ctyp'] = 'c';
            $inv['deptid'] = $inv['typeid'];
        } else {
            $inv['ctyp'] = 'p';
        }
    }
    # Begin updates
    pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
    if ($inv['ctyp'] == 's') {
        $sql = "SELECT * FROM suppliers WHERE supid = '{$inv['supid']}' AND div = '" . USER_DIV . "'";
        $custRslt = db_exec($sql) or errDie("Unable to view customer");
        $cus = pg_fetch_array($custRslt);
        # Get department
        db_conn("exten");
        $sql = "SELECT * FROM departments WHERE deptid = '{$cus['deptid']}' AND div = '" . USER_DIV . "'";
        $deptRslt = db_exec($sql) or errDie("Unable to get details.");
        if (pg_numrows($deptRslt) < 1) {
            $dept['deptname'] = "<li class=err>Department not Found.";
        } else {
            $dept = pg_fetch_array($deptRslt);
        }
    } elseif ($inv['ctyp'] == 'c') {
        # Get department
        db_conn("exten");
        $sql = "SELECT * FROM departments WHERE deptid = '{$inv['deptid']}' AND div = '" . USER_DIV . "'";
        $deptRslt = db_exec($sql) or errDie("Unable to get details.");
        if (pg_numrows($deptRslt) < 1) {
            $dept['deptname'] = "<li class=err>Department not Found.";
        } else {
            $dept = pg_fetch_array($deptRslt);
        }
        $dept['credacc'] = $dept['pca'];
    } elseif ($inv['ctyp'] == 'cb') {
        $bankid = $inv['supid'];
        $bankid += 0;
        db_conn("cubit");
        $sql = "SELECT * FROM bankacct WHERE bankid = '{$bankid}'";
        $deptRslt = db_exec($sql) or errDie("Unable to view customers");
        if (pg_numrows($deptRslt) < 1) {
            $error = "<li class=err> Bank not Found.";
            $confirm .= "{$error}<p><input type=button onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
            return $confirm;
        } else {
            $deptd = pg_fetch_array($deptRslt);
        }
        db_conn('core');
        $Sl = "SELECT * FROM bankacc WHERE accid='{$bankid}'";
        $rd = db_exec($Sl) or errDie("Unable to get data.");
        $data = pg_fetch_array($rd);
        $BA = $data['accnum'];
        $dept['credacc'] = $BA;
    } elseif ($inv['ctyp'] == 'p') {
        core_connect();
        # Get Petty cash account
        $cashacc = gethook("accnum", "bankacc", "name", "Petty Cash");
        # Get account name for thy lame User's Sake
        $accRslt = get("core", "*", "accounts", "accid", $cashacc);
        if (pg_numrows($accRslt) < 1) {
            return "<li class='err'> Petty Cash Account not found.</li>";
        }
        $acc = pg_fetch_array($accRslt);
        $dept['credacc'] = $cashacc;
        //$supacc = "$acc[topacc]/$acc[accnum] - $acc[accname]";
        //$hide = "<input type=hidden name=supacc value='$cashacc'><input type=hidden name=ctyp value='$ctyp'>";
    }
    db_conn($prd);
    /* --- Start Products Display --- */
    $tot_post = 0;
    # Products layout
    $products = "";
    $resub = 0;
    $revat = 0;
    foreach ($ids as $key => $id) {
        db_conn($prd);
        $sql = "SELECT * FROM nons_pur_items  WHERE purid = '{$purid}' AND id = '{$id}' AND div = '" . USER_DIV . "'";
        $stkdRslt = db_exec($sql);
        $stkd = pg_fetch_array($stkdRslt);
        $stkacc = $stkd['accid'];
        # keep records for transactions
        $sql = "UPDATE nons_pur_items SET rqty = (rqty + '{$qtys[$key]}') WHERE id = '{$stkd['id']}'";
        $sRslt = db_exec($sql);
        # Calculate cost amount bought
        $amt[$key] = $qtys[$key] * $unitcost[$key];
        /* delivery charge */
        # Calculate percentage from subtotal
        $perc[$key] = $amt[$key] / $SUBTOTAL * 100;
        # Get percentage from shipping charges
        $shipc[$key] = $perc[$key] / 100 * $shipchrg;
        # add delivery charges
        $amt[$key] += $shipc[$key];
        /* end delivery charge */
        # the subtotal + delivery charges
        $resub += $amt[$key];
        # calculate vat
        $svat[$key] = svat($amt[$key], $stkd['amt'], $stkd['svat']);
        db_conn('cubit');
        $Sl = "SELECT * FROM vatcodes WHERE id='{$stkd['vatcode']}'";
        $Ri = db_exec($Sl) or errDie("Unable to get data.");
        $vd = pg_fetch_array($Ri);
        vatr($vd['id'], $td, "INPUT", $vd['code'], $refnum, "VAT for Non-Stock purchase No. {$inv['purnum']} returned", $amt[$key], $svat[$key]);
        # received vat
        $revat += $svat[$key];
        # make amount vat free
        // 		if($inv['vatinc'] == "yes"){
        // 			$amt[$key] = ($amt[$key] - $svat[$key]);
        // 		}
        $amts[$key] = $stkd['unitcost'] * $qtys[$key];
        $nv = sprint($stkd['svat'] / $stkd['qty'] * $qtys[$key]);
        if ($inv['vatinc'] != "no") {
            $aev = $amts[$key] - $nv;
        } else {
            $aev = $amts[$key];
        }
        $stkd['accid'] += 0;
        db_conn('cubit');
        $sql = "\n\t\t\tINSERT INTO nons_pur_itemsn (\n\t\t\t\tnoteid, qty, description, amt, unitcost, svat, div, \n\t\t\t\tcod, des, ddate, accid\n\t\t\t) VALUES (\n\t\t\t\t'{$noteid}', '{$qtys[$key]}', '{$stkd['des']}', '{$amts[$key]}', '{$stkd['unitcost']}', '{$stkd['svat']}', '" . USER_DIV . "', \n\t\t\t\t'{$stkd['cod']}', '{$stkd['des']}', '{$stkd['ddate']}', '{$stkd['accid']}'\n\t\t\t)";
        $stkdRslt = db_exec($sql) or errDie("Unable to insert note items.");
        if ($inv['ctyp'] == 'ac') {
            $dept['credacc'] = $inv['mpurid'];
        }
        //$sql = "INSERT INTO nons_pur_itemsn(noteid, cod, des, qty, unitcost, amt, svat, ddate, accid, div) VALUES('$nid', '$stktc[cod]', '$stktc[des]', '$qtys[$key]', '$stktc[unitcost]', '$stktc[amt]', '$stktc[svat]', '$stktc[ddate]', '$stktc[accid]', '".USER_DIV."')";
        if ($inv['spurprd'] == 0) {
            $tot_post += $aev;
            writetrans($dept['credacc'], $stkacc, $td, $refnum, $aev, "Non-Stock purchase No. {$inv['purnum']} returned, Supplier {$inv['supplier']}.");
        }
    }
    $supacc = $dept['credacc'];
    $tot_post = 0;
    $pur = $inv;
    if ($inv['spurprd'] > 0) {
        $retot = $TOTAL;
        $vatamt = $VAT;
        db_conn($pur['spurprd']);
        # Get purchase info
        $sql = "SELECT * FROM purchases WHERE purnum = '{$pur['spurnum']}' AND div = '" . USER_DIV . "'";
        $spurRslt = db_exec($sql) or errDie("Unable to get purchase information");
        if (pg_numrows($spurRslt) < 1) {
            return "<li> - purchase Not Found</li>";
        }
        $spur = pg_fetch_array($spurRslt);
        db_conn($pur['spurprd']);
        # Get selected stock
        $sql = "SELECT * FROM pur_items WHERE purid = '{$spur['purid']}' AND div = '" . USER_DIV . "'";
        $sstkdRslt = db_exec($sql);
        while ($sstk = pg_fetch_array($sstkdRslt)) {
            if ($spur['vatinc'] == "yes") {
                $csamt = sprint(($sstk['amt'] - $sstk['svat']) / $spur['subtot'] * ($retot - $vatamt));
            } else {
                $csamt = sprint($sstk['amt'] / $spur['subtot'] * ($retot - $vatamt));
            }
            db_connect();
            # get selected stock
            $sql = "SELECT * FROM stock WHERE stkid = '{$sstk['stkid']}' AND div = '" . USER_DIV . "'";
            $stktRslt = db_exec($sql);
            $stkt = pg_fetch_array($stktRslt);
            /* Code insert */
            # get warehouse name
            db_conn("exten");
            $sql = "SELECT * FROM warehouses WHERE whid = '{$stkt['whid']}' AND div = '" . USER_DIV . "'";
            $whRslt = db_exec($sql);
            $wh = pg_fetch_array($whRslt);
            $tot_post += $csamt;
            writetrans($supacc, $wh['stkacc'], date("d-m-Y"), $refnum, $csamt, "Non-Stock Purchase No. {$pur['purnum']} Returned.");
            /* End code insert */
            db_connect();
            if ($stkt['units'] != 0) {
                $sql = "\n\t\t\t\t\tUPDATE stock \n\t\t\t\t\tSET csamt = (csamt - '{$csamt}'), csprice = (csamt/units) \n\t\t\t\t\tWHERE stkid = '{$sstk['stkid']}' AND div = '" . USER_DIV . "'";
                $rslt = db_exec($sql) or errDie("Unable to update stock to Cubit.", SELF);
            } else {
                $sql = "UPDATE stock SET csamt = (csamt - '{$csamt}') WHERE stkid = '{$sstk['stkid']}' AND div = '" . USER_DIV . "'";
                $rslt = db_exec($sql) or errDie("Unable to update stock to Cubit.", SELF);
            }
            $sdate = $pur['pdate'];
            stockrec($stkt['stkid'], $stkt['stkcod'], $stkt['stkdes'], 'ct', $sdate, 0, $csamt, "Cost decreased with Non Stock Purchase No. {$pur['purnum']}, returned");
            # Just wanted to fix the xxx.xxxxxxe-x value
            # get selected stock
            db_connect();
            $sql = "SELECT * FROM stock WHERE stkid = '{$sstk['stkid']}' AND div = '" . USER_DIV . "'";
            $stktRslt = db_exec($sql);
            $stkt = pg_fetch_array($stktRslt);
            # $csprice = round(($stk['csamt']/$stk['units']), 2);
            if ($stkt['units'] > 0) {
                $csprice = round($stkt['csamt'] / $stkt['units'], 2);
            } else {
                $csprice = round($stkt['csprice'], 2);
            }
            # update stock(csprice = (csamt/units))
            $sql = "UPDATE stock SET csprice = '{$csprice}' WHERE stkid = '{$sstk['stkid']}' AND div = '" . USER_DIV . "'";
            $rslt = db_exec($sql) or errDie("Unable to update stock to Cubit.", SELF);
        }
    }
    /* --- Start Some calculations --- */
    # Subtotal
    //$SUBTOT = sprint($subtot);
    //	$VAT = sprint($vat);
    //$TOTAL = sprint($total);
    /* --- End Some calculations --- */
    /* - Start Hooks - */
    $vatacc = gethook("accnum", "salesacc", "name", "VAT");
    $varacc = gethook("accnum", "salesacc", "name", "sales_variance");
    /* - End Hooks - */
    # todays date
    $date = date("d-m-Y");
    $sdate = date("Y-m-d");
    // print $inv['ctyp']; exit;
    //$real_noteid = divlastid('note', USER_DIV);
    db_conn('cubit');
    # bank  % cust
    if ($inv['ctyp'] == 's') {
        $sql = "SELECT * FROM suppliers WHERE supid = '{$inv['supid']}' AND div = '" . USER_DIV . "'";
        $custRslt = db_exec($sql) or errDie("Unable to view customer");
        $cus = pg_fetch_array($custRslt);
        # Get department
        db_conn("exten");
        $sql = "SELECT * FROM departments WHERE deptid = '{$cus['deptid']}' AND div = '" . USER_DIV . "'";
        $deptRslt = db_exec($sql) or errDie("Unable to get details.");
        if (pg_numrows($deptRslt) < 1) {
            $dept['deptname'] = "<li class=err>Department not Found.";
        } else {
            $dept = pg_fetch_array($deptRslt);
        }
        $tpp = 0;
        # record transaction  from data
        //foreach($totstkamt as $stkacc => $wamt){
        //}
        //$tot_dif=sprint($tot_post-$TOTAL);
    } elseif ($inv['ctyp'] == 'b') {
        $dept['debtacc'] = getbankaccid($inv['accid']);
        $amounts = "";
        $accids = "";
        $vats = "";
        $chrgvats = "";
        $gamt = 0;
        # record transaction  from data
        foreach ($totstkamt as $stkacc => $wamt) {
            # Cook vars
            $amounts .= "|{$wamt}";
            $accids .= "|{$stkacc}";
            $vats .= "|0";
            $chrgvats .= "|no";
            # Debit Customer and Credit stock
            //$tot_post+=$wamt;
            //writetrans($stkacc, $dept['debtacc'], date("d-m-Y"), $refnum, $wamt, "Non-Stock purchase No. $inv[invnum] Credit note No.$real_noteid.");
        }
        # Debit bank and credit the account involved
    } else {
        //$cusacc = $inv['accid'];
        $sdate = date("Y-m-d");
        # record transaction  from data
        //foreach($totstkamt as $stkacc => $wamt){
        # Debit Customer and Credit stock
        //			$tot_post+=$wamt;
        //writetrans($stkacc, $cusacc,  date("d-m-Y"), $refnum, $wamt, "Non-Stock Purchase No. $inv[invnum] Credit note No.$real_noteid.");
        //pettyrec($cusacc, $sdate, "dt", "Non-Stock Purchase No. $inv[invnum] Credit note No.$real_noteid.", $wamt, "Account Sale Credit note");
        //}
        # Debit bank and credit the account involved
        //$tot_post+=$VAT;
        //writetrans($vatacc, $cusacc, date("d-m-Y"), $refnum, $VAT, "Non-Stock Purchase No. $inv[invnum] Credit note No.$real_noteid VAT.");
        //pettyrec($cusacc, $sdate, "dt", "Non-Stock Purchase No. $inv[invnum] Credit note No.$real_noteid VAT.", $VAT, "Account Sale Credit note VAT");
    }
    if ($VAT != 0) {
        $tot_post += $VAT;
        writetrans($dept['credacc'], $vatacc, $td, $refnum, $VAT, "Non-Stock purchase No. {$inv['purnum']} Returned. Supplier {$inv['supplier']}.");
    }
    $sdate = date("Y-m-d");
    if ($inv['spurprd'] > 0) {
        $stkacc = $wh['stkacc'];
        $diff = sprint($TOTAL - $tot_post);
        if ($diff > 0) {
            writetrans($dept['credacc'], $cvacc, $td, $refnum, $diff, "Cost Variance for Non stock Purchase No. {$pur['purnum']} Returned");
        } elseif ($diff < 0) {
            writetrans($cvacc, $dept['credacc'], $td, $refnum, -$diff, "Cost Variance for Non stock Purchase No. {$pur['purnum']} Returned");
        }
    }
    /*
    	if($tot_dif>0) {
    		writetrans($stkacc, $varacc, date("d-m-Y"), $refnum, $tot_dif, "Purchase Variance on invoice $real_invid");
    	} elseif($tot_post<0) {
    		writetrans($varacc, $stkacc, date("d-m-Y"), $refnum, $tot_dif, "Purchase Variance on invoice $real_invid");
    	}*/
    $reff = $refnum;
    db_connect();
    if ($inv['ctyp'] == 's') {
        # Record the payment on the statement
        $sql = "\n\t\t\tINSERT INTO sup_stmnt (\n\t\t\t\tsupid, ref, amount, edate, descript, div, cacc\n\t\t\t) VALUES (\n\t\t\t\t'{$inv['supid']}', '{$reff}', '-{$TOTAL}', '{$td}', 'Non Stock purchase {$inv['purnum']} returned', '" . USER_DIV . "', '{$stkacc}'\n\t\t\t)";
        $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
        # Update the customer (make balance less)
        $sql = "UPDATE suppliers SET balance = (balance - '{$TOTAL}'::numeric(13,2)) WHERE supid = '{$inv['supid']}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
        # Make ledge record
        suppledger($inv['supid'], $stkacc, $td, $reff, "Non Stock purchase {$inv['purnum']} returned", $TOTAL, "d");
        $mt = $TOTAL * -1;
        db_connect();
        $sql = "INSERT INTO suppurch (supid, purid, pdate, balance, div) VALUES ('{$inv['supid']}', '{$inv['purnum']}', '{$td}', '{$mt}', '" . USER_DIV . "')";
        $purcRslt = db_exec($sql) or errDie("Unable to update int Orders information in Cubit.{$sql}", SELF);
        //custfCT($TOTAL, $inv['cusid'], $sndate);
    } elseif ($inv['ctyp'] == 'cb') {
        $date = date("Y-m-d");
        # Record the Receipt record
        db_connect();
        $sql = "\n\t\t\tINSERT INTO cashbook (\n\t\t\t\tbankid, trantype, date, name, descript, cheqnum, amount, \n\t\t\t\tbanked, accids, amounts,  chrgvats, vats, div, accinv\n\t\t\t) VALUES (\n\t\t\t\t'{$inv['supid']}', 'deposit', '{$td}', '{$inv['supplier']}', 'Nons Stock purchase {$inv['purnum']} returned', '0', '{$TOTAL}', \n\t\t\t\t'no', '', '{$TOTAL}', '{$inv['vatinc']}', '{$VAT}', '" . USER_DIV . "','{$stkacc}'\n\t\t\t)";
        $Rslt = db_exec($sql) or errDie("Unable to add bank Receipt to database.", SELF);
    }
    db_connect();
    $sql = "UPDATE \"{$prd}\".nons_purchases SET balance = (balance - '{$TOTAL}'::numeric(13,2)) WHERE purid = '{$inv['purid']}' AND div = '" . USER_DIV . "'";
    $upRslt = db_exec($sql) or errDie("Unable to update invoice information");
    $sql = "UPDATE cubit.suppurch SET balance=(balance - '{$TOTAL}'::numeric(13,2)) WHERE purid='{$inv['purid']}'";
    $rslt = db_exec($sql) or errDie("Unable to update invoice balance.");
    # write note
    $sql = "\n\t\tINSERT INTO cubit.nons_purchasesn (\n\t\t\tpurid, purnum, supplier, supaddr, vatinc, pdate, subtot, vat, total, \n\t\t\tprd, notenum, ctyp, remarks, div\n\t\t) VALUES (\n\t\t\t'{$inv['purid']}', '{$inv['purnum']}', '{$inv['supplier']}', '{$inv['supaddr']}', '{$inv['vatinc']}', '{$td}', '{$SUBTOTAL}', '{$VAT}', '{$TOTAL}', \n\t\t\t'" . PRD_DB . "', '{$noteid}', '{$inv['ctyp']}', '{$remarks}', '" . USER_DIV . "'\n\t\t)";
    $rslt = db_exec($sql) or errDie("Unable to create template Non-Stock Invoice.{$sql}", SELF);
    $nid = pglib_lastid("nons_purchasesn", "id");
    $nid++;
    # write note items
    foreach ($ids as $key => $id) {
        db_conn($prd);
        $sql = "SELECT * FROM nons_pur_items  WHERE purid = '{$purid}' AND id = '{$id}' AND div = '" . USER_DIV . "'";
        $stkdRslt = db_exec($sql) or errDie("Unable to get data.{$sql}");
        $stktc = pg_fetch_array($stkdRslt);
        db_conn("cubit");
        $sql = "\n\t\t\tINSERT INTO nons_pur_itemsn (\n\t\t\t\tnoteid, cod, des, qty, unitcost, amt, svat, \n\t\t\t\tddate, accid, div\n\t\t\t) VALUES (\n\t\t\t\t'{$nid}', '{$stktc['cod']}', '{$stktc['des']}', '{$qtys[$key]}', '{$stktc['unitcost']}', '{$stktc['amt']}', '{$stktc['svat']}', \n\t\t\t\t'{$stktc['ddate']}', '{$stktc['accid']}', '" . USER_DIV . "'\n\t\t\t)";
        //$rslt = db_exec($sql) or errDie("Unable to insert Order items to Cubit.",SELF);
    }
    # Commit updates
    pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
    /* -- Format the remarks boxlet -- */
    $inv["remarks"] = "<table border=1><tr><td>Remarks:<br>{$inv['remarks']}</td><ble>";
    $cc = "<script> CostCenter('dt', 'Credit Note', '{$inv['pdate']}', 'Non Stock Credit Note No.{$noteid}', '" . ($TOTAL - $VAT) . "', ''); </script>";
    /* -- Final Layout -- */
    $details = "\n\t\t{$cc}\n\t\t<table " . TMPL_tblDflts . ">\n\t\t\t<tr>\n\t\t\t\t<th>Purchase Return</th>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Purchase return 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-view.php'>View purchases</a></td>\n\t\t\t</tr>\n\t\t\t<script>document.write(getQuicklinkSpecial());</script>\n\t\t</table>";
    return $details;
}
function input_check()
{
    $numargs = func_num_args();
    $arg_list = func_get_args();
    if (!validate_request_checksum()) {
        perihelion_die("Refresh Error", "You can only submit this form once.");
    }
    if (!isset($_REQUEST['cmd'])) {
        perihelion_die("", "No command requested.");
        return "";
    }
    // Command is needed. If not present... whooops.
    $cmd = decrypt_get_vars($_REQUEST['cmd']);
    // Browse through all numargs, check the command, if it is ours, decrypt all vars EXCEPT
    // the ne_* vars
    $i = 0;
    for (;;) {
        $tmp_cmd = $arg_list[$i];
        $i++;
        if ($tmp_cmd != $cmd) {
            while ($arg_list[$i] != "0") {
                $i++;
            }
        } else {
            while ($arg_list[$i] != "0") {
                $tmp_var = $arg_list[$i];
                $GLOBALS[$tmp_var] = "";
                // Error if we can't find a mandatory var
                if (substr($tmp_var, 0, 1) == "!") {
                    $tmp_var = substr($tmp_var, 1, 255);
                    if (!isset($_REQUEST[$tmp_var])) {
                        perihelion_die("Internal Error", "Mandatory var not found: " . $tmp_var);
                    }
                }
                if (isset($_REQUEST[$tmp_var])) {
                    // Check if we need decrypting or not
                    if (substr($tmp_var, 0, 3) == "ne_") {
                        $GLOBALS[$tmp_var] = $_REQUEST[$tmp_var];
                    } else {
                        $GLOBALS[$tmp_var] = decrypt_get_vars($_REQUEST[$tmp_var]);
                    }
                }
                $i++;
            }
            return $tmp_cmd;
        }
        $i++;
        if ($i >= $numargs) {
            break;
        }
    }
    // No command found :(
    if (user_is_admin(user_ourself())) {
        $str = "Illegal or no command requested.<br>Command issued: '{$cmd}'";
    } else {
        $str = "Illegal or no command requested.";
    }
    perihelion_die("Internal Error", $str);
}
function confirm($_POST)
{
    # Get vars
    extract($_POST);
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($cashacc, "num", 1, 30, "Invalid Petty Cash Account.");
    $v->isOk($date_day, "num", 1, 2, "Invalid Date day.");
    $v->isOk($date_month, "num", 1, 2, "Invalid Date month.");
    $v->isOk($date_year, "num", 1, 4, "Invalid Date Year.");
    if (strlen($date_year) != 4) {
        $v->isOk($bankname, "num", 1, 1, "Invalid Date year.");
    }
    if ($amount > $max) {
        $v->isOk("##", "num", 1, 1, "ERROR : amount is more than available petty cash funds.");
    }
    $v->isOk($descript, "string", 0, 255, "Invalid Description.");
    $v->isOk($amount, "float", 1, 10, "Invalid amount.");
    $v->isOk($supid, "num", 1, 20, "Invalid Supplier account.");
    $date = $date_day . "-" . $date_month . "-" . $date_year;
    if (!checkdate($date_month, $date_day, $date_year)) {
        $v->isOk($date, "num", 1, 1, "Invalid date.");
    }
    # 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='&laquo; Correct submission'>";
        return $confirm;
    }
    # CHECK IF THIS DATE IS IN THE BLOCKED RANGE
    $blocked_date_from = getCSetting("BLOCKED_FROM");
    $blocked_date_to = getCSetting("BLOCKED_TO");
    if (strtotime($date) >= strtotime($blocked_date_from) and strtotime($date) <= 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>";
    }
    # Get account name
    $supRslt = get("cubit", "*", "suppliers", "supid", $supid);
    $sup = pg_fetch_array($supRslt);
    # Get account name for thy lame User's Sake
    $accRslt = get("core", "*", "accounts", "accid", $cashacc);
    if (pg_numrows($accRslt) < 1) {
        return "<li class='err'> Petty Cash Account not found.</li>";
    }
    $acc = pg_fetch_array($accRslt);
    # Check available funds
    core_connect();
    $sql = "SELECT (debit - credit) as bal FROM trial_bal WHERE month='" . PRD_DB . "' AND accid = '{$cashacc}' AND div = '" . USER_DIV . "'";
    $accbRslt = db_exec($sql);
    if (pg_numrows($accbRslt) < 1) {
        return "<li class='err'> Petty Cash Account not found.</li>";
    }
    $accb = pg_fetch_array($accbRslt);
    $accb['bal'] = sprint($accb['bal']);
    $confirm = "\n\t\t<center>\n\t\t<h3>New Petty Cash Payment</h3>\n\t\t<h4>Confirm entry (Please check the details)</h4>\n\t\t<table " . TMPL_tblDflts . " width=60%>\n\t\t<form action='" . SELF . "' method='POST'>\n\t\t\t<input type='hidden' name='key' value='write'>\n\t\t\t<input type='hidden' name='cashacc' value='{$cashacc}'>\n\t\t\t<input type='hidden' name='date' value='{$date}'>\n\t\t\t<input type='hidden' name='descript' value='{$descript}'>\n\t\t\t<input type='hidden' name='amount' value='{$amount}'>\n\t\t\t<input type='hidden' name='supid' value='{$supid}'>\n\t\t\t<tr>\n\t\t\t\t<th>Field</th>\n\t\t\t\t<th>Value</th>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Petty Cash Account</td>\n\t\t\t\t<td>{$acc['topacc']}/{$acc['accnum']} {$acc['accname']}</td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Available Funds</td>\n\t\t\t\t<td>" . CUR . " {$accb['bal']}</td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Date</td>\n\t\t\t\t<td valign='center'>{$date}</td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Paid from</td>\n\t\t\t\t<td valign='center'>{$sup['supno']} - {$sup['supname']}</td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Description</td>\n\t\t\t\t<td valign='center'>{$descript}</td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Amount</td>\n\t\t\t\t<td valign='center'>" . CUR . " {$amount}</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<td align='right'><input type='button' value='&laquo Back' onClick='javascript:history.back()'></td>\n\t\t\t\t<td align='right'><input type='submit' value='Confirm &raquo'></td>\n\t\t\t</tr>\n\t\t</form>\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<script>document.write(getQuicklinkSpecial());</script>\n\t\t</table>";
    return $confirm;
}
function confirm($_POST)
{
    # Get vars
    extract($_POST);
    # validate input
    require_lib("validate");
    $v = new validate();
    $date = $date_year . "-" . $date_month . "-" . $date_day;
    if (!checkdate($date_month, $date_day, $date_year)) {
        $v->isOk($date, "num", 1, 1, "Invalid date.");
    }
    $v->isOk($account, "num", 1, 50, "Invalid Account to be used as contra.[{$key}]");
    $v->isOk($refnum, "num", 1, 10, "Invalid Reference number.");
    # CHECK IF THIS DATE IS IN THE BLOCKED RANGE
    $blocked_date_from = getCSetting("BLOCKED_FROM");
    $blocked_date_to = getCSetting("BLOCKED_TO");
    if (strtotime($date) >= strtotime($blocked_date_from) and strtotime($date) <= 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>";
    }
    foreach ($accid as $key => $value) {
        $dtamount[$key] += 0;
        $ctamount[$key] += 0;
        if ($dtamount[$key] > 0 || $ctamount[$key] > 0) {
            $v->isOk($accid[$key], "num", 1, 50, "Invalid Account to be Debited.[{$key}]");
            $v->isOk($dtamount[$key], "float", 1, 20, "Invalid Debit Amount.[{$key}]");
            $v->isOk($ctamount[$key], "float", 1, 20, "Invalid Credit Amount.[{$key}]");
            $v->isOk($descript[$key], "string", 0, 255, "Invalid Details.[{$key}]");
        }
    }
    # 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='&laquo; Correct submission'>";
        return $confirm;
    }
    # get contra account
    $accRs = get("core", "*", "accounts", "accid", $account);
    if (pg_numrows($accRs) < 1) {
        return "<li> Accounts to be debited does not exist.</li>";
    }
    $account_info = pg_fetch_array($accRs);
    # accnums
    foreach ($accid as $key => $value) {
        if ($dtamount[$key] > 0 || $ctamount[$key] > 0) {
            # get account to be debited
            $accRss = get("core", "*", "accounts", "accid", $accid[$key]);
            if (pg_numrows($accRs) < 1) {
                return "<li> Accounts to be debited does not exist.</li>";
            }
            $accs[$key] = pg_fetch_array($accRss);
        }
    }
    $confirm = "\n\t\t<center>\n\t\t<h3>Add Multiple Journal transactions to batch</h3>\n\t\t<h4>Confirm entry</h4>\n\t\t<form action='" . SELF . "' method='POST'>\n\t\t\t<input type='hidden' name='date_year' value='{$date_year}'>\n\t\t\t<input type='hidden' name='date_month' value='{$date_month}'>\n\t\t\t<input type='hidden' name='date_day' value='{$date_day}'>\n\t\t\t<input type='hidden' name='refnum' value='{$refnum}'>\n\t\t\t<input type='hidden' name='account' value='{$account}'>\n\t\t\t<input type='hidden' name='total' value='{$total}'>\n\t\t\t<input type='hidden' name='key' value='write'>\n\t\t<table " . TMPL_tblDflts . " width='590'>\n\t\t\t<tr>\n\t\t\t\t<th>Transaction Date</th>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>{$date_year}-{$date_month}-{$date_day}</td>\n\t\t\t</tr>\n\t\t\t<tr>\n\t\t\t\t<th>Select Contra Account</th>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>{$account_info['accname']}</td>\n\t\t\t</tr>\n\t\t\t<tr>\n\t\t\t\t<th>Reference Number</th>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>{$refnum}</td>\n\t\t\t</tr>\n\t\t\t" . TBL_BR . "\n\t\t</table>\n\t\t<table " . TMPL_tblDflts . " width='590'>\n\t\t\t<tr>\n\t\t\t\t<th>Account</th>\n\t\t\t\t<th>Description</th>\n\t\t\t\t<th>Debit</th>\n\t\t\t\t<th>Credit</th>\n\t\t\t</tr>";
    $trans = "";
    foreach ($accid as $key => $value) {
        if ($dtamount[$key] > 0 || $ctamount[$key] > 0) {
            $accRss = get("core", "*", "accounts", "accid", $accid[$key]);
            if (pg_numrows($accRs) < 1) {
                return "<li> Accounts to be debited does not exist.</li>";
            }
            $acc_each[$key] = pg_fetch_array($accRss);
            $trans .= "\n\t\t\t\t<input type='hidden' name='accid[]' value='{$accid[$key]}'>\n\t\t\t\t<input type='hidden' name='descript[]' value ='{$descript[$key]}'>\n\t\t\t\t<input type='hidden' name='dtamount[]' value='{$dtamount[$key]}'>\n\t\t\t\t<input type='hidden' name='ctamount[]' value='{$ctamount[$key]}'>\n\t\t\t\t<tr bgcolor=" . bgcolorg() . ">\n\t\t\t\t\t<td valign='center'>" . $acc_each[$key]['accname'] . "</td>\n\t\t\t\t\t<td>{$descript[$key]}</td>\n\t\t\t\t\t<td nowrap>" . CUR . " " . sprint($dtamount[$key]) . "</td>\n\t\t\t\t\t<td nowrap>" . CUR . " " . sprint($ctamount[$key]) . "</td>\n\t\t\t\t</tr>";
        }
    }
    if (strlen($trans) < 5) {
        return slctacc($_POST, "<li class='err'>Please enter full transaction details</li><br>");
    }
    $confirm .= "\n\t\t\t{$trans}\n\t\t\t<tr><td><br></td></tr>\n\t\t\t<tr>\n\t\t\t\t<td align='right'><input type='submit' name='back' value='&laquo; Correction'></td>\n\t\t\t\t<td align='right' colspan='3'><input type='submit' value='Write &raquo'></td>\n\t\t\t</tr>\n\t\t</form>\n\t\t</table>\n\t\t<table border='0' cellpadding='2' cellspacing='1' width=15%>\n\t\t\t<tr><td><br></td></tr>\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='datacell'>\n\t\t\t\t<td align='center'><a href='../reporting/index-reports.php'>Financials</a></td>\n\t\t\t</tr>\n\t\t\t<tr class='datacell'>\n\t\t\t\t<td align='center'><a href='batch-view.php'>View batch file</td>\n\t\t\t</tr>\n\t\t\t<tr class='datacell'>\n\t\t\t\t<td align='center'><a href='trans-new.php'>Journal Transaction</td>\n\t\t\t</tr>\n\t\t\t<script>document.write(getQuicklinkSpecial());</script>\n\t\t</table>";
    return $confirm;
}
function write($_POST)
{
    extract($_POST);
    if (isset($back)) {
        unset($_POST["back"]);
        return alloc($_POST);
    }
    # CHECK IF THIS DATE IS IN THE BLOCKED RANGE
    $blocked_date_from = getCSetting("BLOCKED_FROM");
    $blocked_date_to = getCSetting("BLOCKED_TO");
    require_lib("validate");
    $v = new validate();
    $v->isOk($all, "num", 1, 1, "Invalid allocation.");
    $v->isOk($rec_amount, "num", 1, 5, "Invalid amount of entries.");
    for ($t = 0; $t < $rec_amount; $t++) {
        if (!isset($descript[$t]) or !isset($reference[$t]) or !isset($setamt[$t]) or empty($descript[$t]) or empty($reference[$t]) or empty($setamt[$t])) {
            continue;
        }
        $v->isOk($bankid[$t], "num", 1, 30, "Invalid Bank Account.");
        $v->isOk($date[$t], "date", 1, 14, "Invalid Date.");
        $v->isOk($out[$t], "float", 1, 40, "Invalid out amount.");
        $v->isOk($descript[$t], "string", 0, 255, "Invalid Description.");
        $v->isOk($reference[$t], "string", 0, 50, "Invalid Reference Name/Number.");
        $v->isOk($cheqnum[$t], "num", 0, 30, "Invalid Cheque number.");
        $v->isOk($amt[$t], "float", 1, 40, "Invalid amount.");
        $v->isOk($setamt[$t], "float", 1, 40, "Invalid Settlement amount.");
        $v->isOk($setvat[$t], "string", 1, 10, "Invalid Settlement VAT Option.");
        $v->isOk($setvatcode[$t], "string", 1, 40, "Invalid Settlement VAT code");
        $v->isOk($cusid[$t], "num", 1, 40, "Invalid customer number.");
        $v->isOk($out1[$t], "float", 0, 40, "Invalid paid amount(currant).");
        $v->isOk($out2[$t], "float", 0, 40, "Invalid paid amount(30).");
        $v->isOk($out3[$t], "float", 0, 40, "Invalid paid amount(60).");
        $v->isOk($out4[$t], "float", 0, 40, "Invalid paid amount(90).");
        $v->isOk($out5[$t], "float", 0, 40, "Invalid paid amount(120).");
        if (isset($invids[$t])) {
            foreach ($invids[$t] as $key => $value) {
                $v->isOk($invids[$t][$key], "num", 1, 50, "Invalid Invoice No.");
                $v->isOk($paidamt[$t][$key], "float", 1, 40, "Invalid amount to be paid.");
            }
        }
        if (strtotime($date[$t]) >= strtotime($blocked_date_from) and strtotime($date[$t]) <= 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>";
        }
    }
    if ($v->isError()) {
        $confirm = $v->genErrors();
        return $confirm . confirm($_POST);
    }
    for ($t = 0; $t < $rec_amount; $t++) {
        if (!isset($descript[$t]) or !isset($reference[$t]) or !isset($setamt[$t]) or empty($descript[$t]) or empty($reference[$t]) or empty($setamt[$t])) {
            continue;
        }
        /* get bank account id */
        if (($bank_acc[$t] = getbankaccid($bankid[$t])) === false) {
            $sql = "SELECT accid FROM core.accounts WHERE accname='Cash on Hand'";
            $rslt = db_exec($sql);
            if (pg_num_rows($rslt) < 1) {
                if ($bankid[$t] == 0) {
                    return "There is no 'Cash on Hand' account, there was one, but\n\t\t\t\t\t\t**s not there now, you mudst have deleted it, if you want\n\t\t\t\t\t\tto use cash functionality please create a 'Cash on Hand' account.";
                } else {
                    return "Invalid bank acc.";
                }
            }
            $bank_acc[$t] = pg_fetch_result($rslt, 0);
        }
        $cus = qryCustomer($cusid[$t], "cusnum, deptid, cusname, surname");
        $dept = qryDepartment($cus["deptid"], "debtacc");
        $refnum = getrefnum();
        pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
        # date format
        $sdate[$t] = explode("-", $date[$t]);
        $sdate[$t] = $sdate[$t][2] . "-" . $sdate[$t][1] . "-" . $sdate[$t][0];
        $cheqnum[$t] = 0 + $cheqnum[$t];
        $pay = "";
        $accdate[$t] = $sdate[$t];
        /* Paid invoices */
        $invidsers = "";
        $rinvids = "";
        $amounts = "";
        $invprds = "";
        $rages = "";
        /* OPTION 1 : AUTO ALLOCATE (write) */
        if ($all == 0) {
            # update the customer (make balance less)
            $sql = "UPDATE cubit.customers SET balance = (balance - '{$amt[$t]}'::numeric(13,2))\n\t\t\t\t\tWHERE cusnum = '{$cus['cusnum']}' AND div = '" . USER_DIV . "'";
            $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
            if (isset($invids[$t])) {
                foreach ($invids[$t] as $key => $value) {
                    $ii = $invids[$t][$key];
                    $pp = $paidamt[$t][$key];
                    /* OPTION 1: STOCK INVOICES */
                    if (!isset($itype[$t][$ii]) && !isset($ptype[$t][$ii])) {
                        $sql = "SELECT prd,invnum,odate FROM cubit.invoices\n\t\t\t\t\t\t\t\tWHERE invid ='{$ii}' 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.</li>";
                        }
                        $inv = pg_fetch_array($invRslt);
                        $inv['invnum'] += 0;
                        // reduce invoice balance
                        $sql = "UPDATE cubit.invoices \n\t\t\t\t\t\t\t\tSET balance = (balance - {$pp}::numeric(13,2))\n\t\t\t\t\t\t\t\tWHERE invid = '{$ii}' AND div = '" . USER_DIV . "'";
                        $payRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
                        $sql = "UPDATE cubit.open_stmnt \n\t\t\t\t\t\t\t\tSET balance = (balance - {$pp}::numeric(13,2))\n\t\t\t\t\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 = "\n\t\t\t\t\t\t\tINSERT INTO cubit.stmnt (\n\t\t\t\t\t\t\t\tcusnum, invid, amount, date, \n\t\t\t\t\t\t\t\ttype, div, allocation_date\n\t\t\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t\t\t'{$cus['cusnum']}', '{$inv['invnum']}', '" . ($pp - $pp * 2) . "', '{$sdate[$t]}', \n\t\t\t\t\t\t\t\t'Payment for Invoice No. {$inv['invnum']}', '" . USER_DIV . "', '{$inv['odate']}'\n\t\t\t\t\t\t\t)";
                        $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
                        custledger($cus['cusnum'], $bank_acc[$t], $sdate[$t], $inv['invnum'], "Payment for Invoice No. {$inv['invnum']}", $paidamt[$t][$key], "c");
                        $rinvids .= "|{$invids[$t]}[{$key}]";
                        $amounts .= "|{$pp}";
                        if ($inv['prd'] == "0") {
                            $inv['prd'] = PRD_DB;
                        }
                        $invprds .= "|{$inv['prd']}";
                        $rages .= "|0";
                        $invidsers .= " - {$inv['invnum']}";
                        /* OPTION 1: NONS STOCK INVOICES */
                    } else {
                        if (!isset($ptype[$t][$ii])) {
                            $sql = "SELECT prd,invnum,descrip,age,odate FROM cubit.nons_invoices\n\t\t\t\t\t\t\t\tWHERE invid ='{$ii}' 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.</li>";
                            }
                            $inv = pg_fetch_array($invRslt);
                            $inv['invnum'] += 0;
                            # reduce the money that has been paid
                            $sql = "UPDATE cubit.nons_invoices\n\t\t\t\t\t\t\t\tSET balance = (balance - {$pp}::numeric(13,2))\n\t\t\t\t\t\t\t\tWHERE invid = '{$ii}' AND div = '" . USER_DIV . "'";
                            $payRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
                            $sql = "UPDATE cubit.open_stmnt\n\t\t\t\t\t\t\t\tSET balance = (balance - {$pp}::numeric(13,2))\n\t\t\t\t\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 = "\n\t\t\t\t\t\t\tINSERT INTO cubit.stmnt (\n\t\t\t\t\t\t\t\tcusnum, invid, amount, date, \n\t\t\t\t\t\t\t\ttype, div, allocation_date\n\t\t\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t\t\t'{$cus['cusnum']}', '{$inv['invnum']}', '" . ($pp - $pp * 2) . "', '{$sdate[$t]}', \n\t\t\t\t\t\t\t\t'Payment for Non Stock Invoice No. {$inv['invnum']} - {$inv['descrip']}', '" . USER_DIV . "', '{$inv['odate']}'\n\t\t\t\t\t\t\t)";
                            $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
                            custledger($cus['cusnum'], $bank_acc[$t], $sdate[$t], $inv['invnum'], "Payment for Non Stock Invoice No. {$inv['invnum']} - {$inv['descrip']}", $paidamt[$t][$key], "c");
                            recordCT($pp, $cus['cusnum'], $inv['age'], $accdate[$t]);
                            $rinvids .= "|{$ii}";
                            $amounts .= "|{$pp}";
                            $invprds .= "|0";
                            $rages .= "|{$inv['age']}";
                            $invidsers .= " - {$inv['invnum']}";
                        } else {
                            /* pos invoices */
                            $sqls = array();
                            for ($i = 1; $i <= 12; ++$i) {
                                $sqls[] = "SELECT '{$i}' AS prd,invid,invnum,odate FROM \"{$i}\".pinvoices \n\t\t\t\t\t\t\t\t\tWHERE invid='{$ii}' AND div='" . USER_DIV . "'";
                            }
                            $sql = implode(" UNION ", $sqls);
                            $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.</li>";
                            }
                            $inv = pg_fetch_array($invRslt);
                            // reduce the invoice balance
                            $sql = "UPDATE \"{$inv['prd']}\".pinvoices \n\t\t\t\t\t\t\t\tSET balance = (balance - {$pp}::numeric(13,2)) \n\t\t\t\t\t\t\t\tWHERE invid = '{$ii}' AND div = '" . USER_DIV . "'";
                            $payRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
                            $sql = "UPDATE cubit.open_stmnt \n\t\t\t\t\t\t\t\tSET balance = (balance - {$pp}::numeric(13,2)) \n\t\t\t\t\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 = "\n\t\t\t\t\t\t\tINSERT INTO cubit.stmnt (\n\t\t\t\t\t\t\t\tcusnum, invid, amount, date, type, div, allocation_date\n\t\t\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t\t\t'{$cus['cusnum']}','{$inv['invnum']}', '" . ($pp - $pp * 2) . "','{$sdate[$t]}', 'Payment for Non Stock Invoice No. {$inv['invnum']}', '" . USER_DIV . "', '{$inv['odate']}'\n\t\t\t\t\t\t\t)";
                            $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
                            custledger($cus['cusnum'], $bank_acc[$t], $sdate[$t], $inv['invnum'], "Payment for Non Stock Invoice No. {$inv['invnum']}", $paidamt[$t][$key], "c");
                            recordCT($paidamt[$t][$key], $cus['cusnum'], 0, $accdate[$t]);
                            $rinvids .= "|{$invids[$t]}[{$key}]";
                            $amounts .= "|{$paidamt[$t]}[{$key}]";
                            $invprds .= "|{$inv['prd']}";
                            //$rages .= "|$inv[age]";
                            $invidsers .= " - {$inv['invnum']}";
                        }
                    }
                }
            }
            $cols = grp(m("bankid", $bankid[$t]), m("trantype", "deposit"), m("date", $sdate[$t]), m("name", "{$cus['cusname']} {$cus['surname']}"), m("descript", "Payment for Invoices {$invidsers} from customer {$cus['cusname']} {$cus['surname']}"), m("cheqnum", $cheqnum[$t]), m("amount", $amt[$t]), m("banked", "no"), m("accinv", $dept["debtacc"]), m("cusnum", $cus["cusnum"]), m("rinvids", $rinvids), m("amounts", $amounts), m("invprds", $invprds), m("rages", $rages), m("reference", $reference[$t]), m("div", USER_DIV));
            $dbobj = new dbUpdate("cashbook", "cubit", $cols);
            $dbobj->run(DB_INSERT);
            $dbobj->free();
            /*
            $sql = "INSERT INTO cashbook(bankid, trantype, date, name, descript,
            			cheqnum, amount, banked, accinv, cusnum, rinvids, amounts,
            			invprds, rages, reference, div)
            		VALUES ('$bankid', 'deposit', '$sdate', '$cus[cusname] $cus[surname]',
            			'',
            			'$cheqnum', '$amt', 'no', '$dept[debtacc]', '$cus[cusnum]',
            			'$rinvids', '$amounts', '$invprds', '$rages', '$reference',
            			'".USER_DIV."')";
            $Rslt = db_exec ($sql) or errDie ("Unable to add bank payment to database.",SELF);
            */
            $refnum = getrefnum($accdate[$t]);
            writetrans($bank_acc[$t], $dept['debtacc'], $accdate[$t], $refnum, $amt[$t], "Payment for Invoices {$invidsers} from customer {$cus['cusname']} {$cus['surname']}");
            db_conn('cubit');
            if ($out > 0) {
                /* START OPEN ITEMS */
                $openstmnt = new dbSelect("open_stmnt", "cubit", grp(m("where", "balance>0 AND cusnum='{$cusid[$t]}'"), m("order", "date")));
                $openstmnt->run();
                $open_out[$t] = $out[$t];
                $i = 0;
                $ox = "";
                while ($od = $openstmnt->fetch_array()) {
                    if ($open_out[$t] == 0) {
                        continue;
                    }
                    $oid = $od['id'];
                    if ($open_out[$t] >= $od['balance']) {
                        $open_amount[$t][$oid] = $od['balance'];
                        $open_out[$t] = sprint($open_out[$t] - $od['balance']);
                        $ox .= "\n\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t<td><input type='hidden' size='20' name='open[{$t}][{$oid}]' value='{$oid}'>{$od['type']}</td>\n\t\t\t\t\t\t\t\t<td>" . CUR . " {$od['balance']}</td>\n\t\t\t\t\t\t\t\t<td>{$od['date']}</td>\n\t\t\t\t\t\t\t\t<td><input type='hidden' name='open_amount[{$t}][{$oid}]' value='{$open_amount[$t]}[{$oid}]'>" . CUR . " {$open_amount[$t]}[{$oid}]</td>\n\t\t\t\t\t\t\t</tr>";
                        $Sl = "UPDATE cubit.open_stmnt SET balance=balance-'" . $open_amount[$t][$oid] . "' WHERE id='{$oid}'";
                        $Ri = db_exec($Sl) or errDie("Unable to update statement.");
                    } elseif ($open_out < $od['balance']) {
                        $open_amount[$t][$oid] = $open_out[$t];
                        $open_out = 0;
                        $ox .= "\n\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t<td><input type='hidden' size='20' name='open[{$t}][{$oid}]' value='{$od['id']}'>{$od['type']}</td>\n\t\t\t\t\t\t\t\t<td>" . CUR . " {$od['balance']}</td>\n\t\t\t\t\t\t\t\t<td>{$od['date']}</td>\n\t\t\t\t\t\t\t\t<td><input type='hidden' name='open_amount[{$t}][{$oid}]' value='{$open_amount[$t]}[{$oid}]'>" . CUR . " {$open_amount[$t]}[{$oid}]</td>\n\t\t\t\t\t\t\t</tr>";
                        $Sl = "UPDATE cubit.open_stmnt SET balance=balance-'" . $open_amount[$t][$oid] . "' WHERE id='{$oid}'";
                        $Ri = db_exec($Sl) or errDie("Unable to update statement.");
                    }
                    $i++;
                }
                if (open()) {
                    $bout[$t] = $out[$t];
                    $out[$t] = $open_out[$t];
                    if ($out > 0) {
                        $sql = "\n\t\t\t\t\t\t\tINSERT INTO cubit.open_stmnt (\n\t\t\t\t\t\t\t\tcusnum, invid, amount, balance, date, \n\t\t\t\t\t\t\t\ttype, st, div\n\t\t\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t\t\t'{$cus['cusnum']}', '0', '-{$out[$t]}', '-{$out[$t]}', '{$sdate[$t]}', \n\t\t\t\t\t\t\t\t'Payment Received', 'n', '" . USER_DIV . "'\n\t\t\t\t\t\t\t)";
                        $stmntRslt = db_exec($sql) or errDie("Unable to Insert statement record in Cubit.", SELF);
                        //$confirm .="<tr class='bg-even'><td colspan=4><b>A general transaction will credit the client's account with ".CUR." $out </b></td></tr>";
                    }
                    $out[$t] = $bout[$t];
                } else {
                    //$confirm .="<tr class='bg-even'><td colspan=4><b>A general transaction will credit the client's account with ".CUR." $out </b></td></tr>";}
                }
            }
            if ($out[$t] > 0) {
                recordCT($out[$t], $cus['cusnum'], 0, $accdate[$t]);
                $cols = grp(m("cusnum", $cus["cusnum"]), m("invid", 0), m("amount", -$out[$t]), m("date", $sdate[$t]), m("type", "Payment Received"), m("div", USER_DIV), m("allocation_date", $accdate[$t]));
                $dbobj = new dbUpdate("stmnt", "cubit", $cols);
                $dbobj->run(DB_INSERT);
                $dbobj->free();
                custledger($cus['cusnum'], $bank_acc[$t], $sdate[$t], "PAYMENT", "Payment received.", $out[$t], "c");
            }
        }
        /* start moving invoices */
        // move invoices that are fully paid
        $sql = "SELECT * FROM cubit.invoices WHERE balance=0 AND printed = 'y' AND done = 'y' AND div = '" . USER_DIV . "'";
        $invbRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
        while ($x = pg_fetch_array($invbRslt)) {
            if (($prd = $x['prd']) == "0") {
                $prd = PRD_DB;
            }
            // move invoice
            $cols = grp(m("invid", $x["invid"]), m("invnum", $x["invnum"]), m("deptid", $x["deptid"]), m("cusnum", $x["cusnum"]), m("deptname", $x["deptname"]), m("cusacc", $x["cusacc"]), m("cusname", $x["cusname"]), m("surname", $x["surname"]), m("cusaddr", $x["cusaddr"]), m("cusvatno", $x["cusvatno"]), m("cordno", $x["cordno"]), m("ordno", $x["ordno"]), m("chrgvat", $x["chrgvat"]), m("terms", $x["terms"]), m("traddisc", $x["traddisc"]), m("salespn", $x["salespn"]), m("odate", $x["odate"]), m("delchrg", $x["delchrg"]), m("subtot", $x["subtot"]), m("vat", $x["vat"]), m("total", $x["total"]), m("age", $x["age"]), m("comm", $x["comm"]), m("discount", $x["discount"]), m("delivery", $x["delivery"]), m("docref", $x["docref"]), m("prd", $x["prd"]), m("delvat", $x["delvat"]), m("balance", 0), m("printed", "y"), m("done", "y"), m("username", USER_NAME), m("div", USER_DIV));
            $dbobj = new dbUpdate("invoices", $prd, $cols);
            $dbobj->run(DB_INSERT);
            $dbobj->free();
            // record movement
            $cols = grp(m("invtype", "inv"), m("invnum", $x["invnum"]), m("prd", $x["prd"]), m("docref", $x["docref"]), m("div", USER_DIV));
            $dbobj->setTable("movinv", "cubit");
            $dbobj->setOpt($cols);
            $dbobj->run();
            $dbobj->free();
            // move invoice items
            $inv_items = new dbSelect("inv_items", "cubit", grp(m("where", wgrp(m("invid", $x["invid"]), m("div", USER_DIV)))));
            $inv_items->run();
            while ($xi = $inv_items->fetch_array()) {
                $xi['vatcode'] += 0;
                $xi['account'] += 0;
                $xi['del'] += 0;
                $cols = grp(m("invid", $x["invid"]), m("whid", $xi["whid"]), m("stkid", $xi["stkid"]), m("qty", $xi["qty"]), m("unitcost", $xi["unitcost"]), m("amt", $xi["amt"]), m("disc", $xi["disc"]), m("discp", $xi["discp"]), m("vatcode", $xi["vatcode"]), m("account", $xi["account"]), m("description", $xi["description"]), m("del", $xi["del"]), m("noted", $xi["noted"]), m("serno", $xi["serno"]), m("div", USER_DIV));
                $dbobj->setTable("inv_items", $prd);
                $dbobj->setOpt($cols);
                $dbobj->run();
                $dbobj->free();
            }
            /* remove invoice from cubit schema */
            $dbobj = new dbDelete("invoices", "cubit", wgrp(m("invid", $x["invid"]), m("div", USER_DIV)));
            $dbobj->run();
            $dbobj->setTable("inv_items", "cubit");
            $dbobj->run();
        }
        /* start moving invoices */
        // move invoices that are fully paid
        $sql = "SELECT * FROM cubit.invoices WHERE balance=0 AND printed = 'y' AND done = 'y' AND div = '" . USER_DIV . "'";
        $invbRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
        while ($x = pg_fetch_array($invbRslt)) {
            if (($prd = $x['prd']) == "0") {
                $prd = PRD_DB;
            }
            // move invoice
            $cols = grp(m("invid", $x["invid"]), m("invnum", $x["invnum"]), m("deptid", $x["deptid"]), m("cusnum", $x["cusnum"]), m("deptname", $x["deptname"]), m("cusacc", $x["cusacc"]), m("cusname", $x["cusname"]), m("surname", $x["surname"]), m("cusaddr", $x["cusaddr"]), m("cusvatno", $x["cusvatno"]), m("cordno", $x["cordno"]), m("ordno", $x["ordno"]), m("chrgvat", $x["chrgvat"]), m("terms", $x["terms"]), m("traddisc", $x["traddisc"]), m("salespn", $x["salespn"]), m("odate", $x["odate"]), m("delchrg", $x["delchrg"]), m("subtot", $x["subtot"]), m("vat", $x["vat"]), m("total", $x["total"]), m("age", $x["age"]), m("comm", $x["comm"]), m("discount", $x["discount"]), m("delivery", $x["delivery"]), m("docref", $x["docref"]), m("prd", $x["prd"]), m("delvat", $x["delvat"]), m("balance", 0), m("printed", "y"), m("done", "y"), m("username", USER_NAME), m("div", USER_DIV));
            $dbobj = new dbUpdate("invoices", $prd, $cols);
            $dbobj->run(DB_INSERT);
            $dbobj->free();
            // record movement
            $cols = grp(m("invtype", "inv"), m("invnum", $x["invnum"]), m("prd", $x["prd"]), m("docref", $x["docref"]), m("div", USER_DIV));
            $dbobj->setTable("movinv", "cubit");
            $dbobj->setOpt($cols);
            $dbobj->run();
            $dbobj->free();
            // move invoice items
            $inv_items = new dbSelect("inv_items", "cubit", grp(m("where", wgrp(m("invid", $x["invid"]), m("div", USER_DIV)))));
            $inv_items->run();
            while ($xi = $inv_items->fetch_array()) {
                $xi['vatcode'] += 0;
                $xi['account'] += 0;
                $xi['del'] += 0;
                $cols = grp(m("invid", $x["invid"]), m("whid", $xi["whid"]), m("stkid", $xi["stkid"]), m("qty", $xi["qty"]), m("unitcost", $xi["unitcost"]), m("amt", $xi["amt"]), m("disc", $xi["disc"]), m("discp", $xi["discp"]), m("vatcode", $xi["vatcode"]), m("account", $xi["account"]), m("description", $xi["description"]), m("del", $xi["del"]), m("noted", $xi["noted"]), m("serno", $xi["serno"]), m("div", USER_DIV));
                $dbobj->setTable("inv_items", $prd);
                $dbobj->setOpt($cols);
                $dbobj->run();
                $dbobj->free();
            }
            /* remove invoice from cubit schema */
            $dbobj = new dbDelete("invoices", "cubit", wgrp(m("invid", $x["invid"]), m("div", USER_DIV)));
            $dbobj->run();
            $dbobj->setTable("inv_items", "cubit");
            $dbobj->run();
        }
        #do journal for the settlement discount here ... now ...
        if ($setamt[$t] > 0) {
            db_conn('core');
            #get settlement accid
            $get_setacc = "SELECT accid FROM accounts WHERE accname = 'Debtors Settlement Discount'";
            $run_setacc = db_exec($get_setacc) or errDie("Unable to get settlement account information");
            $setaccid = pg_fetch_result($run_setacc, 0, 0);
            #calculate the settlement vat ... and amt
            if (isset($setvat[$t]) and $setvat[$t] == 'inc') {
                db_connect();
                $get_vcode = "SELECT * FROM vatcodes WHERE id = '{$setvatcode[$t]}' LIMIT 1";
                $run_vcode = db_exec($get_vcode) or errDie("Unable to get vatcode informtion.");
                if (pg_numrows($run_vcode) < 1) {
                    return "<li class='err'>Settlement Discount VAT Code Not Set.</li>";
                }
                $vd = pg_fetch_array($run_vcode);
                #vat inc ... recalculate the amts
                $setvatamt = sprint($setamt[$t] * ($vd['vat_amount'] / (100 + $vd['vat_amount'])));
                $setamt[$t] = sprint($setamt[$t] - $setvatamt);
                $vatacc = gethook("accnum", "salesacc", "name", "VAT", "VAT");
                $svattot = sprint($setamt[$t] + $setvatamt - ($setamt[$t] + $setvatamt) * 2);
                $svatamt = sprint($setvatamt - $setvatamt * 2);
                #process the vat amt ...
                writetrans($vatacc, $dept['debtacc'], $accdate[$t], $refnum, $setvatamt, "VAT Received on Settlement Discount for Customer : {$cus['cusname']} {$cus['surname']}");
                vatr($vd['id'], $accdate[$t], "OUTPUT", $vd['code'], $refnum, "VAT for Settlement Discount for Customer : {$cus['cusname']} {$cus['surname']}", $svattot, $svatamt);
            } else {
                #no vat for set amt ... do nothing
                $setvatamt = 0;
                $svattot = 0;
                $svatamt = 0;
            }
            writetrans($setaccid, $dept['debtacc'], $accdate[$t], $refnum, sprint($setamt[$t]), "Settlement Discount For {$cus['cusname']} {$cus['surname']}");
            custledger($cus['cusnum'], $bank_acc[$t], $sdate[$t], "{$refnum}", "Payment Settlement Discount Received.", sprint($setamt[$t] + $setvatamt), "c");
            $sql = "\n\t\t\t\tINSERT INTO cubit.stmnt (\n\t\t\t\t\tcusnum, invid, amount, date, \n\t\t\t\t\ttype, div, allocation_date\n\t\t\t\t) VALUES (\n\t\t\t\t\t'{$cus['cusnum']}', '0', '" . $svattot . "', '{$sdate[$t]}', \n\t\t\t\t\t'Settlement Discount for Payment. Ref {$refnum}', '" . USER_DIV . "', '{$accdate[$t]}'\n\t\t\t\t)";
            $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
            db_connect();
            #record this paid settlement discount for reporting ...
            $settl_sql = "\n\t\t\t\tINSERT INTO settlement_cus (\n\t\t\t\t\tcustomer, amt, setamt, setvatamt, setvat, \n\t\t\t\t\tsetvatcode, tdate, sdate, refnum\n\t\t\t\t) VALUES (\n\t\t\t\t\t'{$cus['cusnum']}', '{$amt[$t]}', '{$setamt[$t]}', '{$setvatamt}', '{$setvat[$t]}', \n\t\t\t\t\t'{$setvatcode[$t]}', '{$accdate[$t]}', 'now', '{$refnum[$t]}'\n\t\t\t\t)";
            $run_settl = db_exec($settl_sql) or errDie("Unable to get debtor settlement information.");
        }
        pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
    }
    // status report
    $write = "\n\t\t<table " . TMPL_tblDflts . " width='100%'>\n\t\t\t<tr>\n\t\t\t\t<th>Bank Receipt</th>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Bank Receipt added to cash book.</td>\n\t\t\t</tr>\n\t\t</table>";
    $OUTPUT = "\n\t\t<center>\n\t\t<table width='90%'>\n\t\t\t<tr valign='top'>\n\t\t\t\t<td width='50%'>{$write}</td>\n\t\t\t\t<td align='center'>" . mkQuickLinks(ql("bank-pay-add.php", "Add Bank Payment"), ql("bank-recpt-add.php", "Add Bank Receipt"), ql("bank-recpt-inv.php", "Add Customer Payment"), ql("cashbook-view.php", "View Cash Book")) . "\n\t\t\t\t</td>\n\t\t\t</tr>\n\t\t</table>";
    return $OUTPUT;
}
function confirm($_POST)
{
    extract($_POST);
    if (isset($back)) {
        return method($cusid);
    }
    //	$date = "$date_day-$date_month-$date_year";
    $amt = sprint(array_sum($paidamt));
    $setamt = sprint(array_sum($stock_setamt));
    if (!isset($print_recpt)) {
        $print_recpt = "";
    }
    if (!isset($descript) or strlen($descript) < 1) {
        $descript = $reference;
    }
    if (!isset($out1)) {
        $out1 = '';
    }
    if (!isset($out2)) {
        $out2 = '';
    }
    if (!isset($out3)) {
        $out3 = '';
    }
    if (!isset($out4)) {
        $out4 = '';
    }
    if (!isset($out5)) {
        $out5 = '';
    }
    $date = "{$date_year}-{$date_month}-{$date_day}";
    require_lib("validate");
    $v = new validate();
    $v->isOk($all, "num", 1, 1, "Invalid allocation.");
    $v->isOk($bankid, "num", 1, 30, "Invalid Bank Account.");
    $v->isOk($date, "date", 1, 14, "Invalid Date.");
    $v->isOk($descript, "string", 1, 255, "Invalid Description.");
    $v->isOk($reference, "string", 1, 50, "Invalid Reference Name/Number.");
    $v->isOk($cheqnum, "num", 0, 30, "Invalid Cheque number.");
    $v->isOk($amt, "float", 1, 40, "Invalid amount.");
    $v->isOk($setamt, "float", 1, 40, "Invalid Settlement Amount.");
    $v->isOk($setvat, "string", 1, 10, "Invalid Settlement VAT Option.");
    $v->isOk($setvatcode, "string", 1, 40, "Invalid Settlement VAT code");
    //	$v->isOk($out, "float", 1, 40, "Invalid out amount.");
    $v->isOk($out1, "float", 0, 40, "Invalid paid amount(currant).");
    $v->isOk($out2, "float", 0, 40, "Invalid paid amount(30).");
    $v->isOk($out3, "float", 0, 40, "Invalid paid amount(60).");
    $v->isOk($out4, "float", 0, 40, "Invalid paid amount(90).");
    $v->isOk($out5, "float", 0, 40, "Invalid paid amount(120).");
    $v->isOk($cusid, "num", 1, 10, "Invalid customer number.");
    $v->isOk($overpay, "float", 1, 40, "Invalid Unallocated Amount.");
    $v->isOk($print_recpt, "string", 0, 10, "Invalid Print Receipt Setting.");
    if ($amt + $overpay <= 0) {
        $v->addError(0, "Invalid Amount Allocated To Receipt.");
    }
    if (isset($invids)) {
        foreach ($invids as $key => $value) {
            if ($paidamt[$key] < 0.01) {
                continue;
            }
            if (!isset($stock_setamt[$key]) or strlen($stock_setamt[$key]) < 1) {
                $stock_setamt[$key] = 0;
            }
            $v->isOk($invids[$key], "num", 1, 50, "Invalid Invoice No. [{$key}]");
            $v->isOk($paidamt[$key], "float", 1, 40, "Invalid amount to be paid. [{$key}]");
            $v->isOk($stock_setamt[$key], "float", 1, 40, "Invalid Settlement Discount Amount");
        }
    }
    if ($v->isError()) {
        $confirm = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $confirm .= "<li class='err'>" . $e["msg"] . "</li>";
        }
        $_POST['OUT1'] = $out1 + 0;
        $_POST['OUT2'] = $out2 + 0;
        $_POST['OUT3'] = $out3 + 0;
        $_POST['OUT4'] = $out4 + 0;
        $_POST['OUT5'] = $out5 + 0;
        return $confirm . alloc($_POST);
    }
    $blocked_date_from = getCSetting("BLOCKED_FROM");
    $blocked_date_to = getCSetting("BLOCKED_TO");
    if (strtotime($date) >= strtotime($blocked_date_from) and strtotime($date) <= 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>";
    }
    $out += 0;
    $OUT1 = $out1 + 0;
    $OUT2 = $out2 + 0;
    $OUT3 = $out3 + 0;
    $OUT4 = $out4 + 0;
    $OUT5 = $out5 + 0;
    $tot = 0;
    if (isset($invids)) {
        foreach ($invids as $key => $value) {
            if ($paidamt[$key] < 0.01) {
                continue;
            }
            $tot += $paidamt[$key];
        }
    }
    if (isset($open_amount)) {
        $tot += array_sum($open_amount);
    }
    $tot = sprint($tot);
    $amt = sprint($amt);
    $out = sprint($out);
    if (sprint($tot + $out + $out1 + $out2 + $out3 + $out4 + $out5 - $amt) > sprint(0)) {
        $_POST['OUT1'] = $OUT1;
        $_POST['OUT2'] = $OUT2;
        $_POST['OUT3'] = $OUT3;
        $_POST['OUT4'] = $OUT4;
        $_POST['OUT5'] = $OUT5;
        return "<li class='err'>The total amount for invoices is greater than the amount received.\n\t\t\tPlease check the details.</li>" . alloc($_POST);
    }
    if (sprint($setamt) > 0) {
        if (array_sum($stock_setamt) != $setamt) {
            return "<li class='err'>The total settlement amount for invoices is not equal to the amount received.\n\t\t\tPlease check the details.</li>" . alloc($_POST);
        }
    }
    if (isset($bout)) {
        $out = $bout;
    }
    if (!isset($overpay)) {
        $overpay = 0;
    }
    $overpay = sprint($overpay);
    #generate a receipt number
    $receiptnumber = divlastid("receipt");
    $confirm = "\n\t\t<h3>New Bank Receipt</h3>\n\t\t<h4>Confirm entry (Please check the details)</h4>\n\t\t<form action='" . SELF . "' method='POST'>\n\t\t\t<input type='hidden' name='key' value='write'>\n\t\t\t<input type='hidden' name='bankid' value='{$bankid}'>\n\t\t\t<input type='hidden' name='date' value='{$date}'>\n\t\t\t<input type='hidden' name='cusid' value='{$cusid}'>\n\t\t\t<input type='hidden' name='descript' value='{$descript}'>\n\t\t\t<input type='hidden' name='reference' value='{$reference}'>\n\t\t\t<input type='hidden' name='cheqnum' value='{$cheqnum}'>\n\t\t\t<input type='hidden' name='all' value='{$all}'>\n\t\t\t<input type='hidden' name='out' value='{$out}'>\n\t\t\t<input type='hidden' name='date_day' value='{$date_day}'>\n\t\t\t<input type='hidden' name='date_month' value='{$date_month}'>\n\t\t\t<input type='hidden' name='date_year' value='{$date_year}'>\n\t\t\t<input type='hidden' name='overpay' value='{$overpay}'>\n\t\t\t<input type='hidden' name='OUT1' value='{$OUT1}'>\n\t\t\t<input type='hidden' name='OUT2' value='{$OUT2}'>\n\t\t\t<input type='hidden' name='OUT3' value='{$OUT3}'>\n\t\t\t<input type='hidden' name='OUT4' value='{$OUT4}'>\n\t\t\t<input type='hidden' name='OUT5' value='{$OUT5}'>\n\t\t\t<input type='hidden' name='amt' value='{$amt}'>\n\t\t\t<input type='hidden' name='setamt' value='{$setamt}'>\n\t\t\t<input type='hidden' name='setvat' value='{$setvat}'>\n\t\t\t<input type='hidden' name='setvatcode' value='{$setvatcode}'>\n\t\t\t<input type='hidden' name='print_recpt' value='{$print_recpt}'>\n\t\t<table " . TMPL_tblDflts . ">";
    /* bank account name */
    if ($bankid == "0" or ($bank = qryBankAcct($bankid, "accname, bankname")) === false) {
        $bank['accname'] = "Cash";
        $bank['bankname'] = "";
    }
    /* customer name */
    $cus = qryCustomer($cusid, "accno, cusname, surname");
    if ($setvat == "inc") {
        $showsetvat = "VAT Inclusive";
    } else {
        $showsetvat = "No VAT";
    }
    //	$overpay = sprint ($amt - array_sum($paidamt));
    $overpay = sprint($overpay);
    if ($overpay < 0) {
        $overpay = 0.0;
    }
    if ($print_recpt == "yes") {
        $show_print_recpt = "Yes";
    } else {
        $show_print_recpt = "No";
    }
    $confirm .= "\n\t\t<tr>\n\t\t\t<th>Field</th>\n\t\t\t<th>Value</th>\n\t\t</tr>\n\t\t<tr class='" . bg_class() . "'>\n\t\t\t<td>Account</td>\n\t\t\t<td>{$bank['accname']} - {$bank['bankname']}</td>\n\t\t</tr>\n\t\t<tr class='" . bg_class() . "'>\n\t\t\t<td>Payment Date</td>\n\t\t\t<td valign='center'>{$date}</td>\n\t\t</tr>\n\t\t<tr class='" . bg_class() . "'>\n\t\t\t<td>Received from</td>\n\t\t\t<td valign='center'>{$cus['accno']} - {$cus['cusname']} {$cus['surname']}</td>\n\t\t</tr>\n\t\t<tr class='" . bg_class() . "'>\n\t\t\t<td>Description</td>\n\t\t\t<td valign='center'>{$descript}</td>\n\t\t</tr>\n\t\t<tr class='" . bg_class() . "'>\n\t\t\t<td>Reference</td>\n\t\t\t<td valign='center'>{$reference}</td>\n\t\t</tr>\n\t\t<tr class='" . bg_class() . "'>\n\t\t\t<td>Cheque Number</td>\n\t\t\t<td valign='center'>{$cheqnum}</td>\n\t\t</tr>\n\t\t<tr class='" . bg_class() . "'>\n\t\t\t<td>Amount</td>\n\t\t\t<td valign='center'>" . CUR . " {$amt}</td>\n\t\t</tr>\n\t\t<tr class='" . bg_class() . "'>\n\t\t\t<td>Settlement Discount</td>\n\t\t\t<td valign='center'>" . CUR . " {$setamt} {$showsetvat}</td>\n\t\t</tr>\n\t\t" . TBL_BR . "\n\t\t<tr class='" . bg_class() . "'>\n\t\t\t<td>Print Receipt</td>\n\t\t\t<td>{$show_print_recpt}</td>\n\t\t</tr>\n\t\t" . TBL_BR . "\n\t\t<tr class='" . bg_class() . "'>\n\t\t\t<td colspan='5'><b>A general transaction will credit the client's account with " . CUR . " {$overpay} </b></td>\n\t\t</tr>";
    if (sprint($setamt) > 0) {
        $doset = TRUE;
    } else {
        $doset = FALSE;
    }
    /* OPTION 3 : ALLOCATE TO EACH INVOICE (confirm) */
    if ($all == 2) {
        if ($doset) {
            $showsethead = "<th>Settlement</th>";
        } else {
            $showsethead = "";
        }
        // Layout
        $confirm .= "\n\t\t\t" . TBL_BR . "\n\t\t\t<tr>\n\t\t\t\t<td colspan='2'><h3>Invoices</h3></td>\n\t\t\t</tr>\n\t\t\t<tr>\n\t\t\t\t<th>Invoice Number</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\t{$showsethead}\n\t\t\t</tr>";
        $i = 0;
        foreach ($invids as $key => $value) {
            if ($paidamt[$key] < 0.01) {
                continue;
            }
            $paidamt[$key] = sprint($paidamt[$key]);
            $ii = $invids[$key];
            if (!isset($itype[$key]) && !isset($ptype[$key])) {
                /* STOCK INVOICE ! */
                db_connect();
                $sql = "SELECT invnum,invid,balance,terms,odate FROM invoices\n\t\t\t\t\t\tWHERE invid = '{$invids[$key]}' AND div = '" . USER_DIV . "'";
                $invRslt = db_exec($sql) or errDie("Unable to access database.");
                if (pg_numrows($invRslt) < 1) {
                    return "<li class='err'> -S- Invalid ord number {$invids[$key]}.</li>";
                }
                $inv = pg_fetch_array($invRslt);
                $invid = $inv['invid'];
                #handle warnings ...
                if ($paidamt[$invid] + $stock_setamt[$invid] < sprint($inv['balance'])) {
                    $warning = "<td><li class='err'>Paying Less Than Total Amount.</li></td>";
                } elseif ($paidamt[$invid] + $stock_setamt[$invid] > sprint($inv['balance'])) {
                    $warning = "<td><li class='err'>Paying More Than Total Amount Outstanding.</li></td>";
                } else {
                    $warning = "";
                }
                if ($doset) {
                    if (!isset($stock_setamt[$invid])) {
                        $stock_setamt[$invid] = "";
                    }
                    $showset = "<td>" . CUR . " " . sprint($stock_setamt[$invid]) . "</td>";
                } else {
                    $showset = "<td></td>";
                }
                $confirm .= "\n\t\t\t\t\t<input type='hidden' name='paidamt[{$key}]' size='7' value='{$paidamt[$invid]}'>\n\t\t\t\t\t<input type='hidden' name='stock_setamt[{$key}]' value='{$stock_setamt[$invid]}'>\n\t\t\t\t\t<input type='hidden' size='20' name='invids[{$key}]' value='{$inv['invid']}'>\n\t\t\t\t\t<tr bgcolor='" . bgcolor($i) . "'>\n\t\t\t\t\t\t<td>{$inv['invnum']}</td>\n\t\t\t\t\t\t<td>" . CUR . " {$inv['balance']}</td>\n\t\t\t\t\t\t<td>{$inv['terms']} days</td>\n\t\t\t\t\t\t<td>{$inv['odate']}</td>\n\t\t\t\t\t\t<td>" . CUR . " {$paidamt[$key]}</td>\n\t\t\t\t\t\t{$showset}\n\t\t\t\t\t\t{$warning}\n\t\t\t\t\t</tr>";
            } else {
                if (!isset($ptype[$key])) {
                    /* NON STOCK INVOICE ! */
                    db_connect();
                    $sql = "SELECT invnum,invid,balance,sdate as odate FROM nons_invoices\n\t\t\t\t\t\tWHERE invid = '{$invids[$key]}' AND div = '" . USER_DIV . "'";
                    $invRslt = db_exec($sql) or errDie("Unable to access database.");
                    if (pg_numrows($invRslt) < 1) {
                        return "<li class='err'> -N- Invalid ord number {$invids[$key]}.</li>";
                    }
                    $inv = pg_fetch_array($invRslt);
                    $invid = "i" . $inv['invid'];
                    #handle warnings ...
                    if ($paidamt[$invid] + $stock_setamt[$invid] < sprint($inv['balance'])) {
                        $warning = "<td><li class='err'>Paying Less Than Total Amount.</li></td>";
                    } elseif ($paidamt[$invid] + $stock_setamt[$invid] > sprint($inv['balance'])) {
                        $warning = "<td><li class='err'>Paying More Than Total Amount Outstanding.</li></td>";
                    } else {
                        $warning = "";
                    }
                    if ($doset) {
                        if (!isset($stock_setamt[$invid])) {
                            $stock_setamt[$invid] = "";
                        }
                        $showset = "<td>" . CUR . " " . sprint($stock_setamt[$invid]) . "</td>";
                    } else {
                        $showset = "<td></td>";
                    }
                    $confirm .= "\n\t\t\t\t\t<input type='hidden' size='20' name='invids[{$key}]' value='{$inv['invid']}'>\n\t\t\t\t\t<input type='hidden' name='paidamt[{$key}]' size='7' value='" . $paidamt[$key] . "'>\n\t\t\t\t\t<input type='hidden' name='stock_setamt[{$key}]' value='{$stock_setamt[$key]}'>\n\t\t\t\t\t<input type='hidden' name='itype[{$key}]' value='PcP'>\n\t\t\t\t\t<tr bgcolor='" . bgcolor($i) . "'>\n\t\t\t\t\t\t<td>{$inv['invnum']}</td>\n\t\t\t\t\t\t<td>" . CUR . " {$inv['balance']}</td>\n\t\t\t\t\t\t<td></td>\n\t\t\t\t\t\t<td>{$inv['odate']}</td>\n\t\t\t\t\t\t<td>" . CUR . " " . $paidamt[$key] . "</td>\n\t\t\t\t\t\t{$showset}\n\t\t\t\t\t\t{$warning}\n\t\t\t\t\t</tr>";
                } else {
                    /* POS INVOICE ! */
                    $sqls = array();
                    for ($i = 1; $i <= 12; ++$i) {
                        $sqls[] = "SELECT invnum,invid,balance,odate FROM \"{$i}\".pinvoices WHERE invid = '{$invids[$key]}' AND div = '" . USER_DIV . "'";
                    }
                    $sql = implode(" UNION ", $sqls);
                    // (1jun07) only checks the current prd ??????
                    //				db_conn(PRD_DB);
                    //				$sql = "SELECT invnum,invid,balance,odate FROM pinvoices
                    //						WHERE invid = '$invids[$key]' AND div = '".USER_DIV."'";
                    $invRslt = db_exec($sql) or errDie("Unable to access database.");
                    if (pg_numrows($invRslt) < 1) {
                        return "<li class='err'> -P- Invalid ord number {$invids[$key]}.</li>";
                    }
                    $inv = pg_fetch_array($invRslt);
                    $invid = "p" . $inv['invid'];
                    #handle warnings ...
                    if ($paidamt[$invid] + $stock_setamt[$invid] < sprint($inv['balance'])) {
                        $warning = "<td><li class='err'>Paying Less Than Total Amount.</li></td>";
                    } elseif ($paidamt[$invid] + $stock_setamt[$invid] > sprint($inv['balance'])) {
                        $warning = "<td><li class='err'>Paying More Than Total Amount Outstanding.</li></td>";
                    } else {
                        $warning = "";
                    }
                    if ($doset) {
                        if (!isset($stock_setamt[$invid])) {
                            $stock_setamt[$invid] = "";
                        }
                        $showset = "<td>" . CUR . " " . sprint($stock_setamt[$invid]) . "</td>";
                    } else {
                        $showset = "<td></td>";
                    }
                    $confirm .= "\n\t\t\t\t\t<input type='hidden' size='20' name='invids[{$key}]' value='{$inv['invid']}'>\n\t\t\t\t\t<input type='hidden' name='paidamt[{$key}]' size='7' value='" . $paidamt[$key] . "'>\n\t\t\t\t\t<input type='hidden' name='stock_setamt[{$key}]' value='{$stock_setamt[$key]}'>\n\t\t\t\t\t<input type='hidden' name='ptype[{$key}]' value='PcP'>\n\t\t\t\t\t<tr bgcolor='" . bgcolor($i) . "'>\n\t\t\t\t\t\t<td>{$inv['invnum']}</td>\n\t\t\t\t\t\t<td>" . CUR . " {$inv['balance']}</td>\n\t\t\t\t\t\t<td></td>\n\t\t\t\t\t\t<td>{$inv['odate']}</td>\n\t\t\t\t\t\t<td>" . CUR . " " . $paidamt[$key] . "</td>\n\t\t\t\t\t\t{$showset}\n\t\t\t\t\t\t{$warning}\n\t\t\t\t\t</tr>";
                }
            }
        }
        if (open()) {
            db_conn('cubit');
            $Sl = "SELECT * FROM open_stmnt WHERE balance>0 AND cusnum='{$cusid}' ORDER BY date";
            $Ri = db_exec($Sl) or errDie("Unable to get open items.");
            //$open_out=$out;
            $ox = "";
            $i = 0;
            while ($od = pg_fetch_array($Ri)) {
                $oid = $od['id'];
                if (!isset($open_amount[$oid]) || $open_amount[$oid] == 0) {
                    continue;
                }
                $ox .= "\n\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\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\t<td>" . CUR . " {$od['balance']}</td>\n\t\t\t\t\t\t<td>{$od['date']}</td>\n\t\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\t</tr>";
                $i++;
            }
            $confirm .= "\n\t\t\t\t<tr><td colspan='2'><br></td></tr>\n\t\t\t\t<tr><td colspan='2'>\n\t\t\t\t\t<h3>Outstanding Transactions</h3></td>\n\t\t\t\t</tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<th>Description</th>\n\t\t\t\t\t<th>Outstanding Amount</th>\n\t\t\t\t\t<th>Date</th>\n\t\t\t\t\t<th>Amount</th>\n\t\t\t\t</tr>\n\t\t\t\t{$ox}";
        }
    }
    vsprint($out);
    vsprint($out1);
    vsprint($out2);
    vsprint($out3);
    vsprint($out4);
    vsprint($out5);
    /*
    	<tr>
    		<td colspan='5' align='right'><input type='submit' name='batch' value='Add To Batch'></td>
    	</tr>
    */
    $confirm .= "\n\t\t<input type='hidden' name='out1' value='{$out1}'>\n\t\t<input type='hidden' name='out2' value='{$out2}'>\n\t\t<input type='hidden' name='out3' value='{$out3}'>\n\t\t<input type='hidden' name='out4' value='{$out4}'>\n\t\t<input type='hidden' name='out5' value='{$out5}'>\n\t\t" . TBL_BR . "\n\t\t<tr>\n\t\t\t<td><input type='submit' name='back' value='&laquo; Correction'></td>\n\t\t\t<td align='right' colspan='4'><input type='submit' value='Write &raquo'></td>\n\t\t</tr>\n\t\t</table>\n\t\t</form>" . mkQuickLinks(ql("../core/trans-new.php", "Journal Transactions"), ql("../customers-view.php", "View Customers"));
    return $confirm;
}
Exemple #16
0
        foreach ($messageList as $message) {
            $dialogBox->error($message);
        }
    }
}
// if apply changes
/**
 * PREPARE DISPLAY
 */
// Prepend in reverse order !!!
if (isset($_REQUEST['cfrom']) && $_REQUEST['cfrom'] == 'ulist') {
    ClaroBreadCrumbs::getInstance()->prepend(get_lang('User list'), get_path('rootAdminWeb') . 'adminusers.php');
}
ClaroBreadCrumbs::getInstance()->prepend(get_lang('Administration'), get_path('rootAdminWeb'));
$htmlHeadXtra[] = "<script>\n            function confirmation (name)\n            {\n                if (confirm(\"" . clean_str_for_javascript(get_lang('Are you sure to delete')) . " \"+ name + \"? \"))\n                    {return true;}\n                else\n                    {return false;}\n            }\n            </script>";
$user_data['is_admin'] = user_is_admin($userId);
$cmd_menu[] = '<a class="claroCmd" href="../auth/courses.php' . '?cmd=rqReg' . '&amp;uidToEdit=' . $userId . '&amp;fromAdmin=settings' . '&amp;category=" >' . '<img src="' . get_icon_url('enroll') . '" />' . get_lang('Enrol to a new course') . '</a>';
$cmd_menu[] = '<a class="claroCmd" href="../auth/lostPassword.php' . '?Femail=' . urlencode($user_data['email']) . '&amp;searchPassword=1" >' . '<img src="' . get_icon_url('mail_close') . '" />' . get_lang('Send account information to user by email') . '</a>';
$cmd_menu[] = '<a class="claroCmd" href="adminuserdeleted.php' . '?uidToEdit=' . $userId . '&amp;cmd=rqDelete" ' . ' id="delete" >' . '<img src="' . get_icon_url('deluser') . '" /> ' . get_lang('Delete user') . '</a>';
$cmd_menu[] = '<a class="claroCmd" href="../messaging/sendmessage.php' . '?cmd=rqMessageToUser' . '&amp;userId=' . $userId . '">' . get_lang('Send a message to the user') . '</a>';
if (isset($_REQUEST['cfrom']) && $_REQUEST['cfrom'] == 'ulist') {
    $cmd_menu[] = '<a class="claroCmd" href="adminusers.php" >' . get_lang('Back to user list') . '</a>';
}
/**
 * DISPLAY
 */
$out = '';
// Display tool title
$out .= claro_html_tool_title($nameTools) . $dialogBox->render() . '<p>' . claro_html_menu_horizontal($cmd_menu) . '</p>' . user_html_form_admin_user_profile($user_data);
if (!is_null($dgExtra)) {
    $out .= $dgExtra->render();
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.");
    # used to generate errors
    $error = "asa@";
    # 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 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);
    # CHECK IF THIS DATE IS IN THE BLOCKED RANGE
    $blocked_date_from = getCSetting("BLOCKED_FROM");
    $blocked_date_to = getCSetting("BLOCKED_TO");
    if (strtotime($pur['pdate']) >= strtotime($blocked_date_from) and strtotime($pur['pdate']) <= strtotime($blocked_date_to) and !user_is_admin(USER_ID)) {
        return "<li class='err'>Period Range Is Blocked. Only an administrator can process entries within this period.</li>";
    }
    # check if Order has been received
    if ($pur['invcd'] == "y") {
        $error = "<li class='err'> Error : purchase number <b>{$pur['purnum']}</b> has already been invoiced.</li>";
        $error .= "<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; 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
    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);
    }
    # Get warehouse name
    db_conn("exten");
    $sql = "SELECT * FROM warehouses WHERE div = '" . USER_DIV . "'";
    $whRslt = db_exec($sql);
    $wh = pg_fetch_array($whRslt);
    # insert Order to DB
    db_connect();
    # begin updating
    pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", 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 the payment on the statement
    db_connect();
    $sdate = date("Y-m-d");
    $taxamt = $pur['tax'] * -1;
    $ltotal = sprint($pur['total'] * $pur['xrate']);
    $ltax = sprint($pur['tax'] * $pur['xrate']);
    db_connect();
    # update all supplies xchange rate first
    xrate_update($pur['fcid'], $pur['xrate'], "suppurch", "id");
    sup_xrate_update($pur['fcid'], $pur['xrate']);
    db_connect();
    # Update the supplier (make balance more)
    $sql = "UPDATE suppliers SET balance = (balance + '{$ltotal}'), fbalance = (fbalance + '{$pur['total']}') WHERE supid = '{$pur['supid']}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
    $DAte = date("Y-m-d");
    $sql = "INSERT INTO sup_stmnt(supid, edate, cacc, amount, descript, ref, ex, div) VALUES('{$pur['supid']}','{$pur['pdate']}', '{$dept['credacc']}','{$pur['total']}','International - Stock Received', '{$refnum}','{$pur['purnum']}', '" . USER_DIV . "')";
    $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
    $Sl = "SELECT * FROM vatcodes WHERE id='{$pur['jobnum']}'";
    $Ri = db_exec($Sl);
    if (pg_num_rows($Ri) < 1) {
        return "Please select the vatcode for all your stock.";
    }
    $vd = pg_fetch_array($Ri);
    vatr($vd['id'], $pur['pdate'], "INPUT", $vd['code'], $refnum, "VAT for Purchase No. {$pur['purnum']}", -($ltotal + $ltax), -$ltax);
    # Debit Stock Control and Credit Creditors control
    writetrans($wh['conacc'], $dept['credacc'], $pur['pdate'], $refnum, $ltotal - $ltax, "Invoice Received for Purchase No. {$pur['purnum']} from Supplier : {$sup['supname']}.");
    # Debit bank and credit the account involved
    writetrans($vatacc, $dept['credacc'], $pur['pdate'], $refnum, $ltax, "Tax Paid on International Orders No. {$pur['purnum']} from Supplier {$sup['supname']}.");
    # Ledger Records
    suppledger($pur['supid'], $wh['stkacc'], $pur['pdate'], $pur['purid'], "International Order No. {$pur['purnum']} received.", $ltotal, 'c');
    db_connect();
    /* --- End Transactions --- */
    /* Make transaction record  for age analysis */
    $sql = "INSERT INTO suppurch(supid, purid, pdate, balance, fcid, fbalance, div) VALUES('{$pur['supid']}', '{$pur['purnum']}', '{$pur['pdate']}', '{$ltotal}', '{$pur['fcid']}', '{$pur['total']}', '" . USER_DIV . "')";
    $purcRslt = db_exec($sql) or errDie("Unable to update int Orders information in Cubit.", SELF);
    /* Make transaction record  for age analysis */
    # 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") {
        # 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, $pur['pdate'], $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'], $pur['pdate'], $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);
    } else {
        # Insert Order to DB
        $sql = "UPDATE purch_int SET invcd = 'y' WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update Order status in Cubit.", SELF);
    }
    /* End moving Order received */
    // Final Layout
    $write = "\n\t\t<table " . TMPL_tblDflts . ">\n\t\t\t<tr>\n\t\t\t\t<th>International Purchase Invoiced</th>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Purchase Invoice 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='purch-int-view.php'>View International Orders</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($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='&laquo; 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 writeLoan($_POST)
{
    # get vars
    extract($_POST);
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($empnum, "num", 1, 20, "Invalid employee number.");
    $v->isOk($loanid, "num", 1, 20, "Invalid loan ID.");
    $v->isOk($loanamt, "float", 1, 10, "Invalid loan amount.");
    $v->isOk($loanint, "float", 1, 5, "Invalid loan interest.");
    $v->isOk($loanperiod, "num", 1, 3, "Invalid payback period.");
    $v->isOk($loaninstall, "float", 1, 10, "Invalid monthly installment.");
    $v->isOk($fringebenefit, "float", 1, 10, "Invalid fringe benefit amount.");
    $v->isOk($accid, "num", 1, 9, "Invalid bank account selected.");
    $v->isOk($account, "num", 1, 9, "Invalid contra account selected.");
    $v->isOk($loan_account, "num", 1, 9, "Invalid loan account selected.");
    $v->isOk($loan_type, "num", 1, 9, "Invalid loan type selected.");
    $ldate = mkdate($lyear, $lmonth, $lday);
    $v->isOk($ldate, "date", 1, 1, "Invalid loan date.");
    $archdate = mkdate($arch_year, $arch_month, $arch_day);
    $v->isOk($archdate, "date", 1, 1, "Invalid approval/denial date.");
    if (!checkdate($lmonth, $lday, $lyear)) {
        $v->addError("", "Invalid date.");
    }
    if ($account > 0 && isb($account) || isb($loan_account)) {
        $v->addError("", "Main accounts blocked. Please select sub accounts.");
    }
    # display errors, if any
    if ($v->isError()) {
        $confirmCust = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $confirmCust .= "<li class='err'>" . $e["msg"] . "</li>";
        }
        return enterLoan($confirmCust);
    }
    # CHECK IF THIS DATE IS IN THE BLOCKED RANGE
    $blocked_date_from = getCSetting("BLOCKED_FROM");
    $blocked_date_to = getCSetting("BLOCKED_TO");
    if (strtotime($ldate) >= strtotime($blocked_date_from) and strtotime($ldate) <= 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 THIS DATE IS IN THE BLOCKED RANGE
    $blocked_date_from = getCSetting("BLOCKED_FROM");
    $blocked_date_to = getCSetting("BLOCKED_TO");
    if (strtotime($archdate) >= strtotime($blocked_date_from) and strtotime($archdate) <= 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>";
    }
    # get employee details
    db_connect();
    $sql = "SELECT * FROM employees WHERE empnum='{$empnum}' AND div = '" . USER_DIV . "'";
    $empRslt = db_exec($sql) or errDie("Unable to select employees from database.");
    if (pg_numrows($empRslt) < 1) {
        return "Invalid employee ID.";
    }
    $myEmp = pg_fetch_array($empRslt);
    if (!isset($deny)) {
        # check for previous loan
        $sql = "SELECT empnum FROM employees WHERE empnum='{$empnum}' AND div = '" . USER_DIV . "' AND gotloan='t'::bool";
        $chkRslt = db_exec($sql) or errDie("Unable to check existing loans for employee.");
        if (pg_numrows($chkRslt) > 0) {
            return "<li class='err'>Loan already exists for employee number: {$empnum}.</li>";
        }
    }
    $date = date("Y-m-d");
    pglib_transaction("BEGIN");
    $totamount = sprint($loanperiod * $loaninstall);
    $loanint_amt = $totamount - $loanamt;
    $sql = "\n\t\tINSERT INTO emp_loanarchive (\n\t\t\tempnum, loanamt, loaninstall, loanint, loanperiod, loandate, archdate, loan_type, \n\t\t\tdiv, status\n\t\t) VALUES (\n\t\t\t'{$empnum}', '{$totamount}', '{$loaninstall}', '{$loanint}', '{$loanperiod}', '{$ldate}', '{$archdate}', '{$loan_type}', \n\t\t\t'" . USER_DIV . "', '" . (isset($deny) ? "D" : "A") . "'\n\t\t)";
    $rslt = db_exec($sql) or errDie("Unable to pre archive loan.");
    $loanaid = pglib_lastid('emp_loanarchive', 'id');
    $rem_sql = "DELETE FROM loan_requests WHERE id = '{$loanid}'";
    $run_rem = db_exec($rem_sql) or errDie("Unable to get loan requests information.");
    if (!isset($deny)) {
        $refnum = getrefnum();
        if ($accid > 0) {
            $bankacc = getbankaccid($accid);
        }
        if ($account > 0) {
            $bankacc = $account;
        }
        writetrans($loan_account, $bankacc, $archdate, $refnum, $loanamt, "Loan granted to employee {$myEmp['fnames']} {$myEmp['sname']}.");
        if ($accid > 0) {
            banktrans($accid, "withdrawal", $archdate, "{$myEmp['fnames']} {$myEmp['sname']}", "Loan granted to employee {$myEmp['fnames']} {$myEmp['sname']}.", 0, $loanamt, $loan_account);
        }
        # write to db
        $sql = "\n\t\t\tUPDATE cubit.employees \n\t\t\tSET loanamt = '{$totamount}', loanint = '{$loanint}', loanint_amt = '{$loanint_amt}', loanint_unpaid = '{$loanint_amt}', \n\t\t\t\tloanperiod = '{$loanperiod}', loaninstall = '{$loaninstall}', gotloan = 't'::bool, loanpayslip = '{$loanamt}', \n\t\t\t\tloanfringe = '{$fringebenefit}', loandate = '{$archdate}', expacc_loan = '{$loan_account}', \n\t\t\t\tloanamt_tot = '{$totamount}', loanid = '{$loanaid}' \n\t\t\tWHERE empnum = '{$empnum}' AND div = '" . USER_DIV . "'";
        $loanRslt = db_exec($sql) or errDie("Unable to add loan to system.", SELF);
        if (pg_cmdtuples($loanRslt) < 1) {
            return "Unable to add loan to system.";
        }
    }
    pglib_transaction("COMMIT");
    $OUT = "<table " . TMPL_tblDflts . ">";
    if (isset($deny)) {
        $OUT .= "\n\t\t\t<tr>\n\t\t\t\t<th>Loan Denied And Request Archived.</th>\n\t\t\t</tr>";
    } else {
        $OUT .= "\n\t\t\t<tr>\n\t\t\t\t<th>Loan Granted And Added To System</th>\n\t\t\t</tr>";
    }
    $OUT .= "\n\t\t<tr class='datacell'>\n\t\t\t<td>Loan information successfully updated.</td>\n\t\t</tr>\n\t\t" . TBL_BR;
    if (!isset($deny)) {
        $OUT .= "\n\t\t\t<tr>\n\t\t\t\t<td><input type='button' onclick=\"document.location='../reporting/loan_approval.php?id={$loanaid}'\" value='Generate Approval Report'></td>\n\t\t\t</tr>";
    }
    $OUT .= "\n\t\t</table><br>" . mkQuickLinks(ql("loan_apply.php", "Add Loan Application"), ql("loan_apply_view.php", "View Loan Applications"), ql("../admin-employee-add.php", "Add Employee"), ql("../admin-employee-view.php", "View Employees"));
    return $OUT;
}
Exemple #20
0
        echo date('H:i', $v->date_posted);
        ?>
</strong> (<?php 
        echo $v->full_name;
        ?>
)
	</p>

	<div class="desc">
		<?php 
        echo auto_p(auto_link($v->content));
        ?>
	</div>

	<?php 
        if (user_is_admin() || user_is_admin_event($eid)) {
            ?>
	<a href="/event/blog/edit/<?php 
            echo $eid;
            ?>
/<?php 
            echo $v->ID;
            ?>
" class="btn-small">Edit Entry</a>
	<?php 
        }
        ?>
</div>
<?php 
    }
}
Exemple #21
0
 /**
  * Check the return of user_is_admin for a valid admin user
  */
 public function testCheckUserIsAdmin()
 {
     $result = $this->ci->db->get_where('user', array('admin' => 1), 1)->result();
     $this->ci->session->set_userdata((array) $result[0]);
     $this->assertTrue(user_is_admin());
 }
function write($_POST)
{
    # get vars
    extract($_POST);
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($purid, "num", 1, 20, "Invalid purchase number.");
    if (!isset($supid) && !isset($deptid)) {
        $v->isOk($supacc, "num", 1, 10, "Invalid Supplier Account number.");
    }
    $v->isOk($remarks, "string", 0, 255, "Invalid Remarks.");
    $v->isOk($refno, "string", 0, 255, "Invalid Delivery Reference No.");
    $v->isOk($shipchrg, "float", 0, 20, "Invalid Delivery Charges.");
    $pdate = $p_year . "-" . $p_month . "-" . $p_day;
    if (!checkdate($p_month, $p_day, $p_year)) {
        $v->isOk($date, "num", 1, 1, "Invalid Date.");
    }
    # used to generate errors
    $error = "asa@";
    # check quantities
    if (isset($qtys)) {
        foreach ($qtys as $keys => $qty) {
            $v->isOk($qty, "num", 1, 10, "Invalid Quantity for product number : <b>" . ($keys + 1) . "</b>");
            if ($qty > $qts[$keys]) {
                $v->isOk($qty, "num", 0, 0, "Error : Quantity for product number : <b>" . ($keys + 1) . "</b> is more that Qty Purchased");
            }
            $v->isOk($unitcost[$keys], "float", 1, 20, "Invalid Unit Price for product number : <b>" . ($keys + 1) . "</b>.");
            if ($qty < 1) {
                $v->isOk($qty, "num", 0, 0, "Error : Item Quantity must be at least one. Product number : <b>" . ($keys + 1) . "</b>");
            }
        }
    }
    # display errors, if any
    $err = "";
    if ($v->isError()) {
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $err .= "<li class='err'>" . $e["msg"] . "</li>";
        }
        return details($_POST, $err);
    }
    # Get purchase info
    db_connect();
    $sql = "SELECT * FROM nons_purchases WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
    $purRslt = db_exec($sql) or errDie("Unable to get purchase information");
    if (pg_numrows($purRslt) < 1) {
        return "<li>- purchase Not Found</li>";
    }
    $pur = pg_fetch_array($purRslt);
    # CHECK IF THIS DATE IS IN THE BLOCKED RANGE
    $blocked_date_from = getCSetting("BLOCKED_FROM");
    $blocked_date_to = getCSetting("BLOCKED_TO");
    if (strtotime($pur['pdate']) >= strtotime($blocked_date_from) and strtotime($pur['pdate']) <= strtotime($blocked_date_to) and !user_is_admin(USER_ID)) {
        return "<li class='err'>Period Range Is Blocked. Only an administrator can process entries within this period.</li>";
    }
    $pur['pdate'] = $p_year . "-" . $p_month . "-" . $p_day;
    # Get selected supplier info
    db_connect();
    if (isset($supid)) {
        $sql = "SELECT * FROM suppliers WHERE supid = '{$supid}' AND div = '" . USER_DIV . "'";
        $supRslt = db_exec($sql) or errDie("Unable to get supplier");
        if (pg_numrows($supRslt) < 1) {
            $error = "<li class='err'> Supplier not Found.</li>";
            $confirm .= "{$error}<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
            return $confirm;
        } else {
            $sup = pg_fetch_array($supRslt);
            $pur['supplier'] = $sup['supname'];
            $pur['supaddr'] = $sup['supaddr'];
            # Get department info
            db_conn("exten");
            $sql = "SELECT * FROM departments WHERE deptid = '{$sup['deptid']}' AND div = '" . USER_DIV . "'";
            $deptRslt = db_exec($sql);
            if (pg_numrows($deptRslt) < 1) {
                return "<i class='err'>Department Not Found</i>";
            } else {
                $dept = pg_fetch_array($deptRslt);
            }
            $supacc = $dept['credacc'];
        }
    } elseif (isset($deptid)) {
        db_conn("exten");
        $sql = "SELECT * FROM departments WHERE deptid = '{$deptid}'";
        $deptRslt = db_exec($sql) or errDie("Unable to view customers");
        if (pg_numrows($deptRslt) < 1) {
            $error = "<li class='err'> Department not Found.";
            $confirm .= "{$error}<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
            return $confirm;
        } else {
            $dept = pg_fetch_array($deptRslt);
            $supacc = $dept['pca'];
        }
    }
    # check if purchase has been received
    if ($pur['received'] == "y") {
        $error = "<li class='err'> Error : purchase number <b>{$purid}</b> has already been received.</li>";
        $error .= "<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $error;
    }
    $vatacc = gethook("accnum", "salesacc", "name", "VAT");
    $cvacc = gethook("accnum", "pchsacc", "name", "Cost Variance");
    # Insert purchase to DB
    db_connect();
    # begin updating
    pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
    $refnum = getrefnum();
    /*refnum*/
    db_connect();
    if (isset($qtys)) {
        # amount of stock in
        $totstkamt = array();
        $resub = 0;
        # Get subtotal
        foreach ($qtys as $keys => $value) {
            # Skip zeros
            if ($qtys[$keys] < 1) {
                continue;
            }
            $amt[$keys] = $qtys[$keys] * $unitcost[$keys];
        }
        $SUBTOTAL = array_sum($amt);
        $revat = 0;
        foreach ($qtys as $keys => $value) {
            # Get selected stock line
            $sql = "SELECT * FROM nons_pur_items WHERE cod = '{$cod[$keys]}' AND purid = '{$purid}' AND div = '" . USER_DIV . "'";
            $stkdRslt = db_exec($sql);
            $stkd = pg_fetch_array($stkdRslt);
            # Calculate cost amount bought
            $amt[$keys] = $qtys[$keys] * $unitcost[$keys];
            /* delivery charge */
            # Calculate percentage from subtotal
            $perc[$keys] = $amt[$keys] / $SUBTOTAL * 100;
            # Get percentage from shipping charges
            $shipc[$keys] = $perc[$keys] / 100 * $shipchrg;
            # add delivery charges
            $amt[$keys] += $shipc[$keys];
            /* end delivery charge */
            # the subtotal + delivery charges
            $resub += $amt[$keys];
            # calculate vat
            $svat[$keys] = svat($amt[$keys], $stkd['amt'], $stkd['svat']);
            db_conn('cubit');
            $Sl = "SELECT * FROM vatcodes WHERE id='{$stkd['vatcode']}'";
            $Ri = db_exec($Sl) or errDie("Unable to get data.");
            $vd = pg_fetch_array($Ri);
            vatr($vd['id'], $pur['pdate'], "INPUT", $vd['code'], $refnum, "Vat for Non-Stock Purchase No. {$pur['purnum']}", -$amt[$keys], -$svat[$keys]);
            # received vat
            $revat += $svat[$keys];
            # make amount vat free
            if ($pur['vatinc'] == "yes") {
                $amt[$keys] = $amt[$keys] - $svat[$keys];
            }
            # Update Order items
            $sql = "UPDATE nons_pur_items SET rqty = (rqty + '{$qtys[$keys]}') WHERE cod = '{$cod[$keys]}' AND purid='{$purid}' AND div = '" . USER_DIV . "'";
            $rslt = db_exec($sql) or errDie("Unable to insert Order items to Cubit.", SELF);
            /* ?: refer to :Code Insert:
            			# keep records for transactions
            			if(isset($totstkamt[$stkacc[$keys]])){
            				$totstkamt[$stkacc[$keys]] += $amt[$keys];
            			}else{
            				$totstkamt[$stkacc[$keys]] = $amt[$keys];
            			}
            			*/
            # check if there are any outstanding items
            $sql = "SELECT * FROM nons_pur_items WHERE purid = '{$purid}' AND (qty - rqty) > '0' AND div = '" . USER_DIV . "'";
            $stkdRslt = db_exec($sql);
            # if none the set to received
            if (pg_numrows($stkdRslt) < 1) {
                # update surch_int(received = 'y')
                $sql = "UPDATE nons_purchases SET received = 'y', supplier = '{$pur['supplier']}', supaddr = '{$pur['supaddr']}' WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
                $rslt = db_exec($sql) or errDie("Unable to update international Orders in Cubit.", SELF);
            }
        }
    }
    # Update purchase on the DB
    if ($pur['part'] == 'y') {
        # Update purchase on the DB
        $sql = "UPDATE nons_purchases SET shipchrg = (shipchrg + '{$shipchrg}'), refno = '{$refno}', remarks = '{$remarks}' WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update purchase in Cubit.", SELF);
    } else {
        # Update purchase on the DB
        $sql = "UPDATE nons_purchases SET shipchrg = '{$shipchrg}', refno = '{$refno}', remarks = '{$remarks}' WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update purchase in Cubit.", SELF);
    }
    /* Transactions */
    /* - Start Hooks - */
    /* - End Hooks - */
    $detadd = "";
    if (isset($supid)) {
        $detadd = " from Supplier {$sup['supname']}";
    }
    $sdate = $pur['pdate'];
    /* ?:refer to :Code Insert:
    		# record transaction  from data
    		foreach($totstkamt as $stkacc => $wamt){
    			# Debit Stock and Credit Suppliers control
    			writetrans($stkacc, $supacc, date("d-m-Y"), $refnum, $wamt, "Non-Stock Purchase No. $pur[purnum] Received $detadd.");
    			pettyrec($supacc, $sdate, "ct", "Non-Stock Purchase No. $pur[purnum] Received $detadd.", $wamt, "Cash Purchase");
    		}*/
    # Calc Vat amount on (subtot + delchrg)
    $vatamt = $revat;
    # Add vat if not included
    if ($pur['vatinc'] == 'no') {
        $retot = $resub + $vatamt;
    } elseif ($pur['vatinc'] == "novat") {
        $retot = $resub;
        $vatamt = 0;
    } else {
        $retot = $resub;
    }
    # get warehouse name
    db_conn("exten");
    $sql = "SELECT * FROM warehouses WHERE div = '" . USER_DIV . "'";
    $whRslt = db_exec($sql);
    $wh = pg_fetch_array($whRslt);
    $tot_post = 0;
    if ($vatamt != 0) {
        $tot_post += $vatamt;
        # Debit bank and credit the account involved
        writetrans($vatacc, $supacc, $pdate, $refnum, $vatamt, "Non-Stock Purchase Vat paid on Non-Stock Purchase No. {$pur['purnum']} {$detadd}.");
        pettyrec($supacc, $sdate, "ct", "Non-Stock Purchase No. {$pur['purnum']} Received {$detadd}.", $vatamt, "Cash Purchase Vat");
        # Record the payment on the statement
        db_connect();
        $sdate = $pur['pdate'];
    }
    if (isset($supid)) {
        $DAte = $pur['pdate'];
        db_connect();
        # update the supplier (make balance more)
        $sql = "UPDATE suppliers SET balance = (balance + '{$retot}') WHERE supid = '{$sup['supid']}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
        $sql = "INSERT INTO sup_stmnt(supid, edate, cacc, amount, descript,ref,ex,div) VALUES('{$sup['supid']}','{$DAte}', '{$dept['credacc']}', '{$retot}','Non-Stock Purchase No. {$pur['purnum']} Received', '{$refnum}', '{$pur['purnum']}','" . USER_DIV . "')";
        $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
        suppledger($sup['supid'], $wh['stkacc'], $DAte, $pur['purid'], "Non-Stock Purchase No. {$pur['purnum']} received.", $retot, 'c');
        db_connect();
        # update the supplier age analysis (make balance less)
        /* Make transaction record for age analysis */
        $sql = "INSERT INTO suppurch(supid, purid, pdate, balance, div) VALUES('{$sup['supid']}', '{$pur['purnum']}', '{$DAte}', '{$retot}', '" . USER_DIV . "')";
        $purcRslt = db_exec($sql) or errDie("Unable to update int purchases information in Cubit.", SELF);
    }
    /* End Transactions */
    # commit updating
    // pglib_transaction ("COMMIT") or errDie("Unable to commit a database transaction.",SELF);
    /* Update items found in ther linked purchase */
    # Get purchase info
    db_connect();
    $sql = "SELECT * FROM nons_purchases WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
    $purRslt = db_exec($sql) or errDie("Unable to get purchase information");
    if (pg_numrows($purRslt) < 1) {
        return "<li>- purchase Not Found</li>";
    }
    $pur = pg_fetch_array($purRslt);
    db_conn($pur['spurprd']);
    $stab = $pur['spurtype'] == "int" ? "purch_int" : "purchases";
    $itab = $pur['spurtype'] == "int" ? "purint_items" : "pur_items";
    # Get purchase info
    $sql = "SELECT * FROM {$stab} WHERE purnum = '{$pur['spurnum']}' AND div = '" . USER_DIV . "'";
    $spurRslt = db_exec($sql) or errDie("Unable to get purchase information");
    if (pg_numrows($spurRslt) < 1) {
        return "<li> - purchase Not Found</li>";
    }
    $spur = pg_fetch_array($spurRslt);
    $purs = explode(",", $pur['purs']);
    $TSUB = 0;
    foreach ($purs as $purID) {
        $purID += 0;
        db_connect();
        $sql = "SELECT * FROM purchases WHERE purnum = '{$purID}' AND div = '" . USER_DIV . "'";
        $srchRslt = db_exec($sql) or errDie("Unable to retrieve purchases from database.");
        if (pg_numrows($srchRslt) > 0) {
            $p = pg_fetch_array($srchRslt);
            $TSUB += $p['subtot'];
            $Sl = "SELECT sum(unitcost) -sum(svat) as non FROM pur_items WHERE purid='{$p['purid']}' AND stkid=0";
            $Ri = db_exec($Sl) or errDie("Unable to get data.");
            $pi = pg_fetch_array($Ri);
            $pi = $pi['non'];
        }
        $sql = "SELECT * FROM movpurch WHERE purnum = '{$purID}' AND div = '" . USER_DIV . "'";
        $srchRslt = db_exec($sql) or errDie("Unable to retrieve purchases from database.");
        if (pg_numrows($srchRslt) > 0) {
            $res = pg_fetch_array($srchRslt);
            db_conn($res['prd']);
            $sql = "SELECT * FROM purchases WHERE purnum = '{$purID}' AND div = '" . USER_DIV . "'";
            $srchRslt = db_exec($sql) or errDie("Unable to retrieve purchases from database.");
            if (pg_numrows($srchRslt) > 0) {
                $p = pg_fetch_array($srchRslt);
                $TSUB += $p['subtot'];
                $Sl = "SELECT sum(unitcost)-sum(svat) as non FROM pur_items WHERE purid='{$p['purid']}' AND stkid=0";
                $Ri = db_exec($Sl) or errDie("Unable to get data.");
                $pi = pg_fetch_array($Ri);
                $pi = $pi['non'];
            } else {
                db_conn($res['prd']);
                $sql = "SELECT * FROM purch_int WHERE purnum = '{$purID}' AND div = '" . USER_DIV . "'";
                $srchRslt = db_exec($sql) or errDie("Unable to retrieve purchases from database.");
                if (pg_numrows($srchRslt) > 0) {
                    $p = pg_fetch_array($srchRslt);
                    $TSUB += $p['subtot'];
                    // 					$Sl="SELECT sum(unitcost)-sum(svat) as non FROM purint_items WHERE purid='$p[purid]' AND stkid=0";
                    //
                    // 					$Ri=db_exec($Sl) or errDie("Unable to get data.");
                    // 					$pi=pg_fetch_array($Ri);
                    // 					$pi=$pi['non'];
                    $pi = 0;
                }
            }
        }
        if (!isset($pi)) {
            $pi = 0;
        }
        $TSUB -= $pi;
    }
    $purs = explode(",", $pur['purs']);
    foreach ($purs as $purID) {
        $itab = "pur_items";
        $purID += 0;
        //print $purID;
        db_connect();
        $sql = "SELECT * FROM purchases WHERE purnum = '{$purID}' AND div = '" . USER_DIV . "'";
        $srchRslt = db_exec($sql) or errDie("Unable to retrieve purchases from database.");
        if (pg_numrows($srchRslt) > 0) {
            $pur['spurprd'] = "cubit";
        }
        $sql = "SELECT * FROM movpurch WHERE purnum = '{$purID}' AND div = '" . USER_DIV . "'";
        $srchRslt = db_exec($sql) or errDie("Unable to retrieve purchases from database.");
        if (pg_numrows($srchRslt) > 0) {
            $res = pg_fetch_array($srchRslt);
            db_conn($res['prd']);
            $pur['spurprd'] = $res['prd'];
        }
        db_conn($pur['spurprd']);
        $test = $pur['spurprd'];
        $test += 0;
        if ($test != 0) {
            $s = "SELECT * FROM purchases WHERE purnum = '{$purID}' AND div = '" . USER_DIV . "'";
            $q = db_exec($s) or errDie("Unable to retrieve purchases from database.");
            if (pg_num_rows($q) > 0) {
                $p = pg_fetch_array($q);
                $purID = $p['purid'];
            } else {
                $s = "SELECT * FROM purch_int WHERE purnum = '{$purID}' AND div = '" . USER_DIV . "'";
                $q = db_exec($s) or errDie("Unable to retrieve purchases from database.");
                if (pg_num_rows($q) > 0) {
                    $p = pg_fetch_array($q);
                    $purID = $p['purid'];
                    $itab = "purint_items";
                }
            }
        }
        # Get selected stock
        $sql = "SELECT * FROM {$itab} WHERE purid = '{$purID}' AND div = '" . USER_DIV . "' AND stkid!=0";
        $sstkdRslt = db_exec($sql);
        while ($sstk = pg_fetch_array($sstkdRslt)) {
            if ($pur['spurtype'] == "int") {
                $csamt = sprint($sstk['amt'] / $TSUB * ($retot - $vatamt));
            } else {
                if ($spur['vatinc'] == "yes") {
                    $csamt = sprint(($sstk['amt'] - $sstk['svat']) / $TSUB * ($retot - $vatamt));
                } else {
                    $csamt = sprint($sstk['amt'] / $TSUB * ($retot - $vatamt));
                }
            }
            db_connect();
            # get selected stock
            $sql = "SELECT * FROM stock WHERE stkid = '{$sstk['stkid']}' AND div = '" . USER_DIV . "'";
            $stktRslt = db_exec($sql);
            $stkt = pg_fetch_array($stktRslt);
            /* Code insert */
            # get warehouse name
            db_conn("exten");
            $sql = "SELECT * FROM warehouses WHERE whid = '{$stkt['whid']}' AND div = '" . USER_DIV . "'";
            $whRslt = db_exec($sql);
            $wh = pg_fetch_array($whRslt);
            $tot_post += $csamt;
            writetrans($wh['stkacc'], $supacc, $pdate, $refnum, $csamt, "Non-Stock Purchase No. {$pur['purnum']} Received {$detadd}.");
            /* End code insert */
            db_connect();
            if ($stkt['units'] != 0) {
                $sql = "UPDATE stock SET csamt = (csamt + '{$csamt}'), csprice = (csamt/units) WHERE stkid = '{$sstk['stkid']}' AND div = '" . USER_DIV . "'";
                $rslt = db_exec($sql) or errDie("Unable to update stock to Cubit.", SELF);
            } else {
                $sql = "UPDATE stock SET csamt = (csamt + '{$csamt}') WHERE stkid = '{$sstk['stkid']}' AND div = '" . USER_DIV . "'";
                $rslt = db_exec($sql) or errDie("Unable to update stock to Cubit.", SELF);
            }
            $sdate = $pur['pdate'];
            stockrec($stkt['stkid'], $stkt['stkcod'], $stkt['stkdes'], 'dt', $sdate, 0, $csamt, "Cost Increased with Non Stock Purchase No. {$pur['purnum']}");
            # get selected stock
            db_connect();
            $sql = "SELECT * FROM stock WHERE stkid = '{$sstk['stkid']}' AND div = '" . USER_DIV . "'";
            $stktRslt = db_exec($sql);
            $stkt = pg_fetch_array($stktRslt);
            # $csprice = round(($stk['csamt']/$stk['units']), 2);
            if ($stkt['units'] > 0) {
                $csprice = round($stkt['csamt'] / $stkt['units'], 2);
            } else {
                $csprice = round($stkt['csprice'], 2);
            }
            # update stock(csprice = (csamt/units))
            $sql = "UPDATE stock SET csprice = '{$csprice}' WHERE stkid = '{$sstk['stkid']}' AND div = '" . USER_DIV . "'";
            $rslt = db_exec($sql) or errDie("Unable to update stock to Cubit.", SELF);
        }
    }
    //exit;
    /*
    		db_conn($pur['spurprd']);
    		# Get selected stock
    		$sql = "SELECT * FROM $itab WHERE purid = '$spur[purid]' AND div = '".USER_DIV."' AND stkid!=0";
    		$sstkdRslt = db_exec($sql);
    		while($sstk = pg_fetch_array($sstkdRslt)){
    			if($pur['spurtype'] == "int"){
    				$csamt = sprint(($sstk['amt']/$TSUB) * ($retot - $vatamt));
    			}else{
    				if($spur['vatinc'] == "yes"){
    					$csamt = sprint((($sstk['amt'] - $sstk['svat'])/$TSUB) * ($retot - $vatamt));
    				}else{
    					$csamt = sprint((($sstk['amt'])/$TSUB) * ($retot - $vatamt));
    				}
    			}
    
    			db_connect();
    			# get selected stock
    			$sql = "SELECT * FROM stock WHERE stkid = '$sstk[stkid]' AND div = '".USER_DIV."'";
    			$stktRslt = db_exec($sql);
    			$stkt = pg_fetch_array($stktRslt);
    
    			/* Code insert
    				# get warehouse name
    				db_conn("exten");
    				$sql = "SELECT * FROM warehouses WHERE whid = '$stkt[whid]' AND div = '".USER_DIV."'";
    				$whRslt = db_exec($sql);
    				$wh = pg_fetch_array($whRslt);
    
    				$tot_post+=$csamt;
    
    				writetrans($wh['stkacc'], $supacc, date("d-m-Y"), $refnum, $csamt, "Non-Stock Purchase No. $pur[purnum] Received $detadd.");
    			/* End code insert
    
    			db_connect();
    			if($stkt['units'] <> 0){
    				$sql = "UPDATE stock SET csamt = (csamt + '$csamt'), csprice = (csamt/units) WHERE stkid = '$sstk[stkid]' AND div = '".USER_DIV."'";
    				$rslt = db_exec($sql) or errDie("Unable to update stock to Cubit.",SELF);
    			}else{
    				$sql = "UPDATE stock SET csamt = (csamt + '$csamt') WHERE stkid = '$sstk[stkid]' AND div = '".USER_DIV."'";
    				$rslt = db_exec($sql) or errDie("Unable to update stock to Cubit.",SELF);
    			}
    			$sdate = $pur['pdate'];
    			stockrec($stkt['stkid'], $stkt['stkcod'], $stkt['stkdes'], 'dt', $sdate, 0, $csamt, "Cost Increased with Non Stock Purchase No. $pur[purnum]");
    
    			# get selected stock
    			db_connect();
    			$sql = "SELECT * FROM stock WHERE stkid = '$sstk[stkid]' AND div = '".USER_DIV."'";
    			$stktRslt = db_exec($sql);
    			$stkt = pg_fetch_array($stktRslt);
    
    			# $csprice = round(($stk['csamt']/$stk['units']), 2);
    			if($stkt['units'] > 0){
    				$csprice = round(($stkt['csamt']/$stkt['units']), 2);
    			}else{
    				$csprice = round($stkt['csprice'], 2);
    			}
    
    			# update stock(csprice = (csamt/units))
    			$sql = "UPDATE stock SET csprice = '$csprice' WHERE stkid = '$sstk[stkid]' AND div = '".USER_DIV."'";
    			$rslt = db_exec($sql) or errDie("Unable to update stock to Cubit.",SELF);
    		}
    */
    $diff = sprint($retot - $tot_post);
    if ($diff > 0) {
        writetrans($cvacc, $supacc, $sdate, $refnum, $diff, "Cost Variance for Non stock Purchase No. {$pur['purnum']}");
    } elseif ($diff < 0) {
        writetrans($supacc, $cvacc, $sdate, $refnum, -$diff, "Cost Variance for Non stock Purchase No. {$pur['purnum']}");
    }
    /* End Update items found in ther linked purchase */
    /* Start moving if purchase received */
    # Get purchase info
    db_connect();
    $sql = "SELECT * FROM nons_purchases WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
    $purRslt = db_exec($sql) or errDie("Unable to get purchase information");
    if (pg_numrows($purRslt) < 1) {
        return "<li>- purchase Not Found</li>";
    }
    $pur = pg_fetch_array($purRslt);
    if ($pur['received'] == "y") {
        if (isset($supid)) {
            $ctyp = "sup";
            $typeid = $supid;
        } elseif (isset($deptid)) {
            $ctyp = "led";
            $typeid = $deptid;
        } else {
            $ctyp = "ot";
            $typeid = 0;
        }
        # copy purchase
        db_conn($pur['prd']);
        $pur['spurprd'] += 0;
        $pur['spurnum'] += 0;
        $sql = "INSERT INTO nons_purchases(purid, deptid, supplier, supaddr, terms, pdate, ddate, shipchrg, subtot, total, balance, vatinc, vat, remarks, refno, received, done, div, purnum,ctyp,typeid,spurprd,spurnum)";
        $sql .= " VALUES('{$purid}', '{$pur['deptid']}', '{$pur['supplier']}',  '{$pur['supaddr']}', '{$pur['terms']}', '{$pur['pdate']}', '{$pur['ddate']}', '{$pur['shipchrg']}', '{$pur['subtot']}', '{$pur['total']}', '0', '{$pur['vatinc']}', '{$pur['vat']}', '{$pur['remarks']}', '{$pur['refno']}', 'y', 'y', '" . USER_DIV . "', '{$pur['purnum']}','{$ctyp}','{$typeid}','{$pur['spurprd']}','{$pur['spurnum']}')";
        $rslt = db_exec($sql) or errDie("Unable to insert Non-Stock Purchase to Cubit.", SELF);
        db_connect();
        # Get selected stock
        $sql = "SELECT * FROM nons_pur_items WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
        $stktcRslt = db_exec($sql);
        while ($stktc = pg_fetch_array($stktcRslt)) {
            # Insert purchase items
            db_conn($pur['prd']);
            $sql = "INSERT INTO nons_pur_items(purid, cod, des, qty, unitcost, amt, ddate, div,svat) VALUES('{$purid}', '{$stktc['cod']}', '{$stktc['des']}', '{$stktc['qty']}', '{$stktc['unitcost']}', '{$stktc['amt']}', '{$stktc['ddate']}', '" . USER_DIV . "','{$stktc['svat']}')";
            $rslt = db_exec($sql) or errDie("Unable to insert purchase items to Cubit.", SELF);
        }
        db_connect();
        # Remove the purchase from running DB
        $sql = "DELETE FROM nons_purchases WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
        $delRslt = db_exec($sql) or errDie("Unable to update int purchases information in Cubit.", SELF);
        # Remove those purchase items from running DB
        $sql = "DELETE FROM nons_pur_items WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
        $delRslt = db_exec($sql) or errDie("Unable to update int purchases information in Cubit.", SELF);
    }
    pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
    /* End moving purchase received */
    $cc = "<script> CostCenter('ct', 'Non-Stock Purchase', '{$pdate}', 'Non Stock Purchase No.{$pur['purnum']}', '" . ($retot - $vatamt) . "', ''); </script>";
    // Final Layout
    $write = "\n\t\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t\t<tr>\n\t\t\t\t\t\t<th>Non-Stock Purchase received</th>\n\t\t\t\t\t</tr>\n\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t<td>Non-Stock Purchase receipt has been recorded.</td>\n\t\t\t\t\t</tr>\n\t\t\t\t</table>\n\t\t\t\t<p>\n\t\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t\t<tr>\n\t\t\t\t\t\t<th>Quick Links</th>\n\t\t\t\t\t</tr>\n\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t<td><a href='nons-purchase-view.php'>View purchases</a></td>\n\t\t\t\t\t</tr>\n\t\t\t\t\t<script>document.write(getQuicklinkSpecial());</script>\n\t\t\t\t</table>";
    return $write;
}
Exemple #23
0
function include_all($x)
{
    extract($x);
    #add a few extra variables that will be usefull in the output;
    #x = array('elements'=>, 'element_info'=>, 'user_id'=>, 'db'=>)
    #Example: $data = include_all(compact('elements', 'element_info', 'user_id', 'db'));
    #when there is no resource_class_id, find it from the project where instance was created. WILL ASSUME THAT RESOURCE_CLASS_ID FILLED OUT IS A REQUIREMENT FOR ALL S3DB THAT SHARE RULES
    if ($_REQUEST['project_id'] == '') {
        $project_id = $element_info['project_id'];
    } else {
        $project_id = $_REQUEST['project_id'];
    }
    if (!$model) {
        $model = 'nsy';
    }
    if ($letter == '') {
        $letter = strtoupper(substr($elements, 0, 1));
    }
    if (is_array($GLOBALS['s3map'][$GLOBALS['plurals'][$GLOBALS['s3codes'][$letter]]])) {
        foreach ($GLOBALS['s3map'][$GLOBALS['plurals'][$GLOBALS['s3codes'][$letter]]] as $replace => $with) {
            $element_info[$replace] = $element_info[$with];
        }
    }
    #if element is a class, return the class id
    if ($letter == 'D') {
        $element_info['acl'] = $user_id == '1' ? '222' : (user_is_admin($user_id, $db) ? '212' : (user_is_public($user_id, $db) ? '210' : '211'));
        $element_info['created_by'] = $user_id;
        $element_info['description'] = $GLOBALS['s3db_info']['server']['site_intro'];
        $element_info['name'] = $GLOBALS['s3db_info']['server']['site_title'];
        if ($element_info['deployment_id'] == $GLOBALS['s3db_info']['deployment']['Did']) {
            $element_info['self'] = 1;
        }
    }
    if ($letter == 'G') {
        #echo '<pre>';print_r($x);exit;
        $e = 'groups';
        #$element_info['group_id'] = $element_info['account_id'];
        #$element_info['groupname'] = $element_info['account_uname'];
        #$element_info['acl'] = groupAcl($element_info, $user_id, $db);
        $uid_info = uid($element_info['account_id']);
        $element_info['deployment_id'] = ereg_replace('^D', '', $uid_info['Did']);
        $strictuid = 1;
        $strictsharedwith = 1;
        $uid = 'G' . $element_info['group_id'];
        $shared_with = 'U' . $user_id;
        #$element_info['acl'] = permissionOnResource(compact('user_id', 'shared_with', 'db', 'uid','key','strictsharedwith','strictuid'));
        $element_info['acl'] = groupAcl($element_info, $user_id, $db, $timer);
        if ($timer) {
            $timer->setMarker('Included resource information for ' . $letter);
        }
        #echo '<pre>';print_r($element_info);exit;
    }
    if ($letter == 'U') {
        if ($element_info['account_addr_id'] != '') {
            $sql = "select * from s3db_addr where addr_id = '" . $element_info['account_addr_id'] . "'";
            $fields = array('addr1', 'addr2', 'city', 'state', 'postal_code', 'country');
            $db->query($sql);
            while ($db->next_record()) {
                for ($i = 0; $i < count($fields); $i++) {
                    $element_info[$fields[$i]] = $db->f($fields[$i]);
                }
            }
            $element_info = array_delete($element_info, 'account_addr_id');
        }
        $element_info['user_id'] = $element_info['account_id'];
        $element_info['username'] = $element_info['account_uname'];
        $element_info['login'] = $element_info['account_lid'];
        $element_info['address'] = $element_info['addr1'];
        $uid_info = uid($element_info['account_id']);
        $element_info['deployment_id'] = ereg_replace('^D', '', $uid_info['Did']);
        if ($user_id != '1' && $element_info['created_by'] != $user_id && $element_info['account_id'] != $user_id) {
            #if user is not seing himself and user is not admin and user was not the creator of element, then hide address, email, phone, etc.
            $keys2Remove = array('account_email' => '', 'account_phone' => '', 'addr1' => '', 'addr2' => '', 'city' => '', 'state' => '', 'postal_code' => '', 'country' => '');
            if (is_array($element_info)) {
                $element_info = array_diff_key($element_info, $keys2Remove);
            }
        }
        if ($user_id != '1' && $element_info['created_by'] != $user_id && $user_id != $element_info['account_id']) {
            if (is_array($element_info)) {
                $element_info = array_diff_key($element_info, array('account_type' => '', 'account_status' => ''));
            }
        } else {
            //if this user has been created with a filter, what is that filter
            $permission_info = array('uid' => 'U' . $element_info['created_by'], 'shared_with' => 'U' . $element_info['account_id']);
            $hp = has_permission($permission_info, $db);
            if ($hp) {
                $element_info['filter'] = $hp;
            }
        }
        if (is_array($element_info)) {
            $element_info = array_diff_key($element_info, array('account_pwd' => ''));
        }
        $user_id_who_asks = $user_id;
        $uid = 'U' . $element_info['user_id'];
        $shared_with = $user_id_who_asks;
        $strictuid = 1;
        $strictsharedwith = 1;
        $onPermissions = compact('user_id', 'shared_with', 'db', 'uid', 'key', 'strictsharedwith', 'strictuid');
        if ($element_info['acl'] == '') {
            $element_info['acl'] = userAcl(compact('key', 'element_info', 'user_id_who_asks', 'db'));
        }
    }
    if ($letter == 'P') {
        $element_info['name'] = $element_info['project_name'];
        $element_info['description'] = $element_info['project_description'];
        $id = 'P' . $element_info['project_id'];
        $uid = 'P' . $element_info['project_id'];
    }
    if ($letter == 'C') {
        $element_info['class_id'] = $element_info['resource_id'];
        $element_info['collection_id'] = $element_info['class_id'];
        $element_info['name'] = $element_info['entity'];
        $element_info['description'] = $element_info['notes'];
        #project_id to search for rule_id will be the same from the class
        $uid = 'C' . $element_info['resource_id'];
    }
    #if element is a rule, return the class_id of the subject. If the object is a class, return the object_id... to discuss with jonas
    if ($letter == 'R') {
        $uid = 'R' . $element_info['rule_id'];
    }
    #if this is an instance, return the class_id => ASSUMING THAT EVERY S3DB THAT HAS SHARED RULES HAS RESOURCECLASSID IN INSTANCE.
    if ($letter == 'I') {
        if ($element_info['resource_class_id'] != '') {
            $element_info['class_id'] = $element_info['resource_class_id'];
        }
        $element_info['instance_id'] = $element_info['resource_id'];
        $element_info['item_id'] = $element_info['instance_id'];
        $element_info['collection_id'] = $element_info['class_id'];
        $instance_id = $element_info['instance_id'];
        $uid = 'I' . $element_info['instance_id'];
    }
    if ($letter == 'S') {
        $uid = 'S' . $element_info['statement_id'];
        $info[$id] = $element_info;
        $statement_id = $element_info['statement_id'];
        $element_info['instance_id'] = $element_info['resource_id'];
        $element_info['item_id'] = $element_info['instance_id'];
        $element_info['instance_notes'] = $info['I' . $element_info['instance_id']]['notes'];
        if ($info['R' . $element_info['rule_id']] == '') {
            $info['R' . $element_info['rule_id']] = s3info('rule', $element_info['rule_id'], $db);
        }
        $element_info['object_notes'] = notes($element_info['value'], $db);
        $element_info['project_folder'] = $element_info['value'];
        $element_info = include_fileLinks($element_info, $db);
        $element_info['subject'] = $info['R' . $element_info['rule_id']]['subject'];
        $element_info['verb'] = $info['R' . $element_info['rule_id']]['verb'];
        $element_info['object'] = $info['R' . $element_info['rule_id']]['object'];
        $element_info['subject_id'] = $info['R' . $element_info['rule_id']]['subject_id'];
        $element_info['verb_id'] = $info['R' . $element_info['rule_id']]['verb_id'];
        $element_info['object_id'] = $info['R' . $element_info['rule_id']]['object_id'];
    }
    $strictuid = 1;
    $strictsharedwith = 1;
    $shared_with = 'U' . $user_id;
    $toFindInfo = $element_info;
    $onPermissions = compact('user_id', 'shared_with', 'db', 'uid', 'key', 'strictsharedwith', 'strictuid', 'timer', 'toFindInfo');
    if ($element_info['acl'] == '') {
        $element_info['acl'] = permission4Resource($onPermissions);
    }
    $element_info['permission_level'] = $element_info['acl'];
    if (!$element_info['effective_permission']) {
        $element_info['effective_permission'] = $element_info['acl'];
    }
    if (!$element_info['assigned_permission']) {
        $pp = array('uid' => $uid, 'shared_with' => $shared_with);
        $tmp = has_permission($pp, $db);
        if ($tmp) {
            $element_info['assigned_permission'] = $tmp;
        } else {
            $element_info['assigned_permission'] = '---';
        }
    }
    #Define if ser can view or not view data. View is the first number in the 3d code.
    $permission2user = permissionModelComp($element_info['permission_level']);
    ##According to the model, change the values of assigned_permission from prevous versions
    $element_info['assigned_permission'] = str_replace(array('0', '1', '2'), str_split($model), $element_info['assigned_permission']);
    $isOwner = $element_info['created_by'] == $user_id;
    $element_info['view'] = allowed($permission2user, 0, $isOwner, $state = 3, $model);
    $element_info['change'] = allowed($permission2user, 1, $isOwner, $state = 3, $model);
    $element_info['propagate'] = allowed($permission2user, 2, $isOwner, $state = 3, $model);
    #create the element "delete", in case it is eventually created...For now it is the same as change
    $element_info['delete'] = $element_info['change'];
    $element_info['delete_data'] = $element_info['add_data'];
    $element_info['add_data'] = $element_info['propagate'];
    return $element_info;
}
Exemple #24
0
function user_load_variables($login, $prefix)
{
    global $PUBLIC_ACCESS_FULLNAME, $NONUSER_PREFIX, $cached_user_var;
    global $app_host, $app_login, $app_pass, $app_db, $app_user_table;
    global $c, $db_host, $db_login, $db_password, $db_database, $app_same_db;
    if (!empty($cached_user_var[$login][$prefix])) {
        return $cached_user_var[$login][$prefix];
    }
    $cached_user_var = array();
    if ($NONUSER_PREFIX && substr($login, 0, strlen($NONUSER_PREFIX)) == $NONUSER_PREFIX) {
        nonuser_load_variables($login, $prefix);
        return true;
    }
    if ($login == '__public__') {
        $GLOBALS[$prefix . 'login'] = $login;
        $GLOBALS[$prefix . 'firstname'] = '';
        $GLOBALS[$prefix . 'lastname'] = '';
        $GLOBALS[$prefix . 'is_admin'] = 'N';
        $GLOBALS[$prefix . 'email'] = '';
        $GLOBALS[$prefix . 'fullname'] = $PUBLIC_ACCESS_FULLNAME;
        $GLOBALS[$prefix . 'password'] = '';
        return true;
    }
    // if application is in a separate db, we have to connect to it
    if ($app_same_db != '1') {
        $c = dbi_connect($app_host, $app_login, $app_pass, $app_db);
    }
    $sql = "SELECT id, name, username, email FROM {$app_user_table} WHERE username = '******'";
    $res = dbi_query($sql);
    if ($res) {
        if ($row = dbi_fetch_row($res)) {
            $flname = explode(' ', $row[1]);
            $fname = isset($flname[1]) ? $flname[0] : $row[1];
            $lname = isset($flname[1]) ? $flname[1] : '';
            $GLOBALS[$prefix . 'login'] = $login;
            $GLOBALS[$prefix . 'firstname'] = $fname;
            $GLOBALS[$prefix . 'lastname'] = $lname;
            $GLOBALS[$prefix . 'is_admin'] = user_is_admin($row[0], get_admins());
            $GLOBALS[$prefix . 'email'] = $row[3];
            $GLOBALS[$prefix . 'fullname'] = $row[1];
        }
        dbi_free_result($res);
    } else {
        $error = db_error();
        return false;
    }
    // if application is in a separate db, we have to connect back to the webcal db
    if ($app_same_db != '1') {
        $c = dbi_connect($db_host, $db_login, $db_password, $db_database);
    }
    //save these results
    $cached_user_var[$login][$prefix] = true;
    return true;
}
function update($_POST)
{
    extract($_POST);
    $collect_ar = array();
    if (!empty($client_collect)) {
        $collect_ar[] = "Client Collect";
    }
    if (!empty($collect)) {
        $collect_ar[] = "Collect";
    }
    if (!empty($deliver)) {
        $collect_ar[] = "Deliver";
    }
    $collection = implode(", ", $collect_ar);
    // 	if ((in_array("Collect", $collect_ar) && in_array("Client Collect", $collect_ar))
    // 		|| (count($collect_ar) == 3)) {
    // 		return "<li class='err'>Invalid collection options selected.</li>";
    // 	}
    if (count($collect_ar) > 1 && in_array("Client Collect", $collect_ar)) {
        return "<li class='err'>Invalid collection options selected.</li>";
    }
    $temp_assets = explode(",", $temp_assets);
    pglib_transaction("BEGIN");
    if (isset($nhalf_day) && $nhalf_day == "checked") {
        $nhalf_day = 1;
    } else {
        $nhalf_day = 0;
    }
    if (isset($nweekends) && $nweekends == "checked") {
        $nweekends = 1;
    } else {
        $nweekends = 0;
    }
    $sql = "UPDATE hire.hire_invoices SET comm='{$comm}' WHERE invid='{$invid}'";
    $comm_rslt = db_exec($sql) or errDie("Unable to retrieve invoice.");
    foreach ($temp_assets as $key => $value) {
        $sql = "SELECT * FROM cubit.assets WHERE id='{$key}'";
        $asset_rslt = db_exec($sql) or errDie("Unable to retrieve asset.");
        $asset_data = pg_fetch_array($asset_rslt);
    }
    if (isset($amount)) {
        foreach ($amount as $key => $value) {
            // 			if (empty($monthly)) {
            // 				$amount[$key] = "";
            // 			}
            if (!user_is_admin(USER_ID)) {
                $amount[$key] = "";
            }
            if (!isset($half_day[$key]) || empty($half_day[$key])) {
                $half_day[$key] = 0;
            }
            if (!isset($weekends[$key]) || empty($weekends[$key])) {
                $weekends[$key] = 0;
            } else {
                $weekends[$key] = 1;
            }
            if (empty($amount[$key]) && $amount != "0") {
                if ($basis[$key] == "per_day") {
                    $hifrm = "{$mfrm_year[$key]}-{$mfrm_month[$key]}-{$mfrm_day[$key]}";
                    $hito = "{$mto_year[$key]}-{$mto_month[$key]}-{$mto_day[$key]}";
                    $hours = "0";
                    /* calculate amount */
                    $ftime = getDTEpoch("{$hifrm} 0:00:00");
                    $ttime = getDTEpoch("{$hito} 0:00:00");
                    $days = 0;
                    $weeks = 0;
                    while ($ftime <= $ttime) {
                        if (date("w", $ftime) == 0 && isset($weekends[$key]) && $weekends[$key]) {
                            $days += 0.6;
                        } else {
                            ++$days;
                        }
                        $ftime += 24 * 60 * 60;
                    }
                    if (is_numeric($rain_days[$key])) {
                        $days -= $rain_days[$key];
                    }
                    $timeunits = $days;
                } else {
                    if ($basis[$key] == "per_hour") {
                        $hifrm = $hito = mkdate($pinv_year, $pinv_month, $pinv_day);
                        $timeunits = $hours;
                        $weeks = 0;
                        if (empty($hours) || !is_numeric($hours)) {
                            return "\r\n\t\t\t\t\t\t\t<li class='err'>\r\n\t\t\t\t\t\t\t\t<b>ERROR</b>: Invalid amount of hours.\r\n\t\t\t\t\t\t\t</li>";
                        }
                    } else {
                        if ($nbasis == "per_week") {
                            $nhifrm = $nhito = mkdate($pinv_year, $pinv_month, $pinv_day);
                            $timeunits = $weeks;
                            $hours = 0;
                            if (empty($weeks) || !is_numeric($weeks)) {
                                return "\r\n\t\t\t\t\t\t\t<li class='err'>\r\n\t\t\t\t\t\t\t\t<b>ERROR</b>: Invalid amount of weeks.\r\n\t\t\t\t\t\t\t</li>";
                            }
                        }
                    }
                }
                if ($half_day[$key]) {
                    $amount[$key] = $qty[$key] * $timeunits * (basisPrice($cusnum, $asset_id[$key], $basis[$key]) * $qty[$key]) - basisPrice($cusnum, $asset_id[$key], $basis[$key]) * $qty[$key] + basisPrice($cusnum, $asset_id[$key], $basis[$key]) * $qty[$key] / 2;
                } else {
                    $amount[$key] = $qty[$key] * $timeunits * basisPrice($cusnum, $asset_id[$key], $basis[$key]);
                }
            }
            if ($amount[$key] == 0) {
                $amount[$key] = 0;
                $blank_amount = 1;
            } else {
                $blank_amount = 0;
            }
            $sql = "UPDATE hire.hire_invitems SET amt='{$amount[$key]}',\r\n\t\t\t\t\t\thalf_day='{$half_day[$key]}', weekends='{$weekends[$key]}'\r\n\t\t\t\t\tWHERE id='{$key}'";
            db_exec($sql) or errDie("Unable to update item amount.");
            $sql = "UPDATE hire.reprint_invitems SET amt='{$amount[$key]}',\r\n\t\t\t\t\t\thalf_day='{$half_day[$key]}', weekends='{$weekends[$key]}'\r\n\t\t\t\t\tWHERE item_id='{$key}'";
            db_exec($sql) or errDie("Unable to update return item amount.");
            if ($blank_amount) {
                $amount[$key] = "";
            }
            //$hifrm = "$hifrm_year[$key]-$hifrm_month[$key]-$hifrm_day[$key]";
            //$hito = "$hito_year[$key]-$hito_month[$key]-$hito_day[$key]";
            if (!isset($remove[$key])) {
                $sql = "SELECT basis FROM hire.hire_invitems WHERE id='{$key}'";
                $item_rslt = db_exec($sql) or errDie("Unable to retrieve basis.");
                $mbasis = pg_fetch_result($item_rslt, 0);
                /* determine time units */
                if ($mbasis == "per_day") {
                    $mfrm = mkdate($mfrm_year[$key], $mfrm_month[$key], $mfrm_day[$key]);
                    $mto = mkdate($mto_year[$key], $mto_month[$key], $mto_day[$key]);
                    /* calculate amount */
                    $ftime = mktime(0, 0, 0, $mfrm_month[$key], $mfrm_day[$key], $mfrm_year[$key]);
                    $ttime = mktime(0, 0, 0, $mto_month[$key], $mto_day[$key], $mto_year[$key]);
                    $days = 0;
                    if (empty($weeks)) {
                        $weeks = 0;
                    }
                    if (empty($hours)) {
                        $hours = 0;
                    }
                    while ($ftime <= $ttime) {
                        if (date("w", $ftime) == 0 && isset($weekends[$key]) && $weekends[$key]) {
                            $days += 0.6;
                        } else {
                            ++$days;
                        }
                        $ftime += 24 * 60 * 60;
                    }
                    $timeunits = $days;
                    $sql = "UPDATE hire.hire_invitems\r\n\t\t\t\t\t\t\tSET from_date='{$mfrm}', to_date='{$mto}'\r\n\t\t\t\t\t\t\tWHERE id='{$key}'";
                    db_exec($sql) or errDie("Unable to update items.");
                    $sql = "UPDATE hire.reprint_invitems\r\n\t\t\t\t\t\t\tSET from_date='{$mfrm}', to_date='{$mto}'\r\n\t\t\t\t\t\t\tWHERE item_id='{$key}'";
                    db_exec($sql) or errDie("Unable to update reprint items.");
                }
            } else {
                // Delete the old items
                $sql = "DELETE FROM hire.hire_invitems WHERE id='{$key}'";
                db_exec($sql) or errDie("Unable to remove old items.");
                $sql = "DELETE FROM hire.reprint_invitems WHERE item_id='{$key}'";
                db_exec($sql) or errDie("Unable to remove old reprint items.");
                //.Remove if the item has been hired as well
                $sql = "DELETE FROM hire.assets_hired WHERE item_id='{$key}'";
                db_exec($sql) or errDie("Unable to remove items from hired log.");
            }
        }
    }
    $sql = "SELECT * FROM hire.hire_invoices WHERE invid='{$invid}'";
    $hi_rslt = db_exec($sql) or errDie("Unable to retrieve invoice.");
    $invb = pg_fetch_array($hi_rslt);
    // Insert new items
    if ($nasset_id != "0" || $nbasis != "0") {
        if ($nasset_id == "0") {
            return "<li class='err'><b>ERROR</b>: No asset selected.</li>";
        }
        /* get asset id */
        list($serialqty, $nasset_id) = explode(":", $nasset_id);
        /* disabled items don't get passed through */
        if ($serialqty == "s" || !isset($nqty)) {
            $nqty = "1";
        } else {
            $sql = "SELECT serial2 FROM cubit.assets WHERE id='{$nasset_id}'";
            $dqty_rslt = db_exec($sql) or errDie("Unable to retrieve assets.");
            $dqty = pg_fetch_result($dqty_rslt, 0);
            if ($dqty - $nqty < 0) {
                return "<li class='err'><b>ERROR</b>: Invalid quantity. Only &nbsp; <b>{$dqty}</b> &nbsp; available.</li>";
            }
        }
        if (empty($nqty) || !is_numeric($nqty)) {
            return "<li class='err'><b>ERROR</b>: Invalid quantity</li>";
        }
        /* determine time units */
        if ($nbasis == "per_day") {
            $nhifrm = mkdate($nhifrm_year, $nhifrm_month, $nhifrm_day);
            $nhito = mkdate($nhito_year, $nhito_month, $nhito_day);
            $hours = "0";
            /* calculate amount */
            $ftime = mktime(0, 0, 0, $nhifrm_month, $nhifrm_day, $nhifrm_year);
            $ttime = mktime(0, 0, 0, $nhito_month, $nhito_day, $nhito_year);
            $days = 0;
            $weeks = 0;
            while ($ftime <= $ttime) {
                if (date("w", $ftime) == 0 && isset($nweekends) && $nweekends) {
                    $days += 0.6;
                } else {
                    ++$days;
                }
                $ftime += 24 * 60 * 60;
            }
            $timeunits = $days;
        } else {
            if ($nbasis == "per_hour") {
                $nhifrm = $nhito = mkdate($pinv_year, $pinv_month, $pinv_day);
                $timeunits = $hours;
                $weeks = 0;
                if (empty($hours) || !is_numeric($hours)) {
                    return "<li class='err'><b>ERROR</b>: Invalid amount of hours.</li>";
                }
            } else {
                if ($nbasis == "per_week") {
                    $nhifrm = $nhito = mkdate($pinv_year, $pinv_month, $pinv_day);
                    $timeunits = $weeks;
                    $hours = 0;
                    if (empty($weeks) || !is_numeric($weeks)) {
                        return "<li class='err'><b>ERROR</b>: Invalid amount of weeks.</li>";
                    }
                } else {
                    return "<li class='err'><b>ERROR</b>: No basis selected.</li>";
                }
            }
        }
        /* calculate amount according to hire settings, quantity and time units */
        if ($nhalf_day) {
            $camt = $nqty * $timeunits * basisPrice($cusnum, $nasset_id, $nbasis) - basisPrice($cusnum, $nasset_id, $nbasis) + basisPrice($cusnum, $nasset_id, $nbasis) / 2;
        } else {
            $camt = $nqty * $timeunits * basisPrice($cusnum, $nasset_id, $nbasis);
        }
        /* insert item */
        $sql = "SELECT asset_id FROM hire.hire_invitems WHERE invid='{$invid}' AND asset_id='{$nasset_id}'";
        $asset_rslt = db_exec($sql) or errDie("Unable to retrieve assets.");
        // No duplicate assets
        if (!pg_num_rows($asset_rslt)) {
            if (isHired($nasset_id)) {
                return "\r\n\t\t\t\t<li class='err'>\r\n\t\t\t\t\t<b>ERROR</b>: Asset has already hired out.\r\n\t\t\t\t</li>";
            }
            $sql = "\r\n\t\t\t\tINSERT INTO hire.hire_invitems (\r\n\t\t\t\t\tinvid, asset_id, qty, amt, from_date, to_date, basis, hours, weeks, \r\n\t\t\t\t\tcollection, half_day, weekends\r\n\t\t\t\t) VALUES (\r\n\t\t\t\t\t'{$invid}', '{$nasset_id}', '{$nqty}', '{$camt}', '{$nhifrm}', '{$nhito}', '{$nbasis}', '{$hours}', '{$weeks}', \r\n\t\t\t\t\t'{$collection}', '{$nhalf_day}', '{$nweekends}'\r\n\t\t\t\t)";
            db_exec($sql) or errDie("Unable to create new invoice item.");
            $item_id = pglib_lastid("hire.hire_invitems", "id");
            $sql = "\r\n\t\t\t\tINSERT INTO hire.reprint_invitems (\r\n\t\t\t\t\tinvid, asset_id, qty, amt, from_date, to_date, basis, hours, weeks, \r\n\t\t\t\t\tcollection, half_day, weekends, item_id\r\n\t\t\t\t) VALUES (\r\n\t\t\t\t\t'{$invid}', '{$nasset_id}', '{$nqty}', '{$camt}', '{$nhifrm}', '{$nhito}', '{$nbasis}', '{$hours}', '{$weeks}', \r\n\t\t\t\t\t'{$collection}', '{$nhalf_day}', '{$nweekends}', '{$item_id}'\r\n\t\t\t\t)";
            db_exec($sql) or errDie("Unable to create reprint invoice item.");
        }
    }
    if ($monthly == "true") {
        $sql = "DELETE FROM hire.monthly_invitems WHERE invid='{$invid}'";
        db_exec($sql) or errDie("Unable to remove monthly items.");
    } else {
        $sql = "SELECT * FROM hire.hire_invitems WHERE invid='{$invid}'";
        $mii_rslt = db_exec($sql) or errDie("Unable to retrieve inv items.");
        $sql = "DELETE FROM hire.monthly_invitems WHERE invid='{$invid}'";
        db_exec($sql) or errDie("Unable to remove monthly items.");
        while ($item = pg_fetch_array($mii_rslt)) {
            $sql = "\r\n\t\t\t\tINSERT INTO hire.monthly_invitems (\r\n\t\t\t\t\tinvid, asset_id, qty, amt, from_date, to_date, \r\n\t\t\t\t\tbasis, hours, weeks, collection, half_day, \r\n\t\t\t\t\tweekends, item_id\r\n\t\t\t\t) VALUES (\r\n\t\t\t\t\t'{$item['invid']}', '{$item['asset_id']}', '{$item['qty']}', '{$item['amt']}', '{$item['from_date']}', '{$item['to_date']}', \r\n\t\t\t\t\t'{$item['basis']}', '{$item['hours']}', '{$item['weeks']}', '{$item['collection']}', '{$item['half_day']}', \r\n\t\t\t\t\t'{$item['weekends']}', '{$item['id']}'\r\n\t\t\t\t)";
            db_exec($sql) or errDie("Unable to create monthly items.");
        }
    }
    $sql = "SELECT * FROM hire.reprint_invoices WHERE invid='{$invid}'";
    $ri_rslt = db_exec($sql) or errDie("Unable to retrieve reprints.");
    // Create a new entry, or update
    if (pg_num_rows($ri_rslt)) {
        $sql = "\r\n\t\t\tUPDATE hire.reprint_invoices \r\n\t\t\tSET deptid='{$invb['deptid']}', cusnum='{$invb['cusnum']}', deptname='{$invb['deptname']}', cusacc='{$invb['cusacc']}', \r\n\t\t\t\tcusname='{$invb['cusname']}', surname='{$invb['surname']}', cusaddr='{$invb['cusaddr']}', cusvatno='{$invb['cusvatno']}', \r\n\t\t\t\tcordno='{$invb['cordno']}', ordno='{$invb['ordno']}', chrgvat='{$invb['chrgvat']}', terms='{$invb['terms']}', \r\n\t\t\t\ttraddisc='{$invb['traddisc']}', salespn='{$invb['salespn']}', odate='{$invb['odate']}', delchrg='{$invb['delchrg']}', \r\n\t\t\t\tsubtot='{$invb['subtot']}', vat='{$invb['vat']}', total='{$invb['total']}', balance='{$invb['balance']}', \r\n\t\t\t\tcomm='{$invb['comm']}', printed='{$invb['printed']}', done='{$invb['done']}', div='{$invb['div']}', \r\n\t\t\t\tusername='******'username']}', rounding='{$invb['rounding']}', delvat='{$invb['delvat']}', vatnum='{$invb['vatnum']}', \r\n\t\t\t\tpcash='{$invb['pcash']}', pcheque='{$invb['pcheque']}', pcc='{$invb['pcc']}', pcredit='{$invb['pcredit']}' \r\n\t\t\tWHERE invid='{$invid}'";
        db_exec($sql) or errDie("Unable to update reprint.");
    } else {
        $sql = "\r\n\t\t\tINSERT INTO hire.reprint_invoices(\r\n\t\t\t\tinvid, invnum, deptid, cusnum, deptname, cusacc, \r\n\t\t\t\tcusname, surname, cusaddr, cusvatno, cordno, ordno, \r\n\t\t\t\tchrgvat, terms, traddisc, salespn, odate, delchrg, \r\n\t\t\t\tsubtot, vat, total, balance, comm, printed, done, div, \r\n\t\t\t\tusername, rounding, delvat, vatnum, pcash, pcheque, \r\n\t\t\t\tpcc, pcredit\r\n\t\t\t) VALUES (\r\n\t\t\t\t'{$invid}', '{$invb['invnum']}', '{$invb['deptid']}', '{$invb['cusnum']}', '{$invb['deptname']}', '{$invb['cusacc']}', \r\n\t\t\t\t'{$invb['cusname']}', '{$invb['surname']}', '{$invb['cusaddr']}', '{$invb['cusvatno']}', '{$invb['cordno']}', '{$invb['ordno']}', \r\n\t\t\t\t'{$invb['chrgvat']}', '{$invb['terms']}', '{$invb['traddisc']}', '{$invb['salespn']}', '{$invb['odate']}', '{$invb['delchrg']}', \r\n\t\t\t\t'{$invb['subtot']}', '{$invb['vat']}' , '{$invb['total']}', '{$invb['balance']}', '{$invb['comm']}', 'y', 'y', '" . USER_DIV . "', \r\n\t\t\t\t'" . USER_NAME . "', '{$invb['rounding']}', '{$invb['delvat']}', '{$invb['vatnum']}', '{$invb['pcash']}', '{$invb['pcheque']}', \r\n\t\t\t\t'{$invb['pcc']}', '{$invb['pcredit']}'\r\n\t\t\t)";
        db_exec($sql) or errDie("Unable to add reprint.");
    }
    $sql = "SELECT * FROM hire.monthly_invoices\r\n\t\t\tWHERE invid='{$invid}' OR invnum='{$invb['invnum']}'";
    $mi_rslt = db_exec($sql) or errDie("Unable to retrieve monthly.");
    // Should we create a new entry
    if (pg_num_rows($mi_rslt)) {
        $sql = "\r\n\t\t\tUPDATE hire.monthly_invoices \r\n\t\t\tSET deptid='{$invb['deptid']}', cusnum='{$invb['cusnum']}', deptname='{$invb['deptname']}', cusacc='{$invb['cusacc']}', \r\n\t\t\t\tcusname='{$invb['cusname']}', surname='{$invb['surname']}', cusaddr='{$invb['cusaddr']}', cusvatno='{$invb['cusvatno']}', \r\n\t\t\t\tcordno='{$invb['cordno']}', ordno='{$invb['ordno']}', chrgvat='{$invb['chrgvat']}', terms='{$invb['terms']}', \r\n\t\t\t\ttraddisc='{$invb['traddisc']}', salespn='{$invb['salespn']}', odate='{$invb['odate']}', delchrg='{$invb['delchrg']}', \r\n\t\t\t\tsubtot='{$invb['subtot']}', vat='{$invb['vat']}', total='{$invb['total']}', balance='{$invb['balance']}', \r\n\t\t\t\tcomm='{$invb['comm']}', printed='{$invb['printed']}', done='{$invb['done']}', div='{$invb['div']}', \r\n\t\t\t\tusername='******'username']}', rounding='{$invb['rounding']}', delvat='{$invb['delvat']}', vatnum='{$invb['vatnum']}', \r\n\t\t\t\tpcash='{$invb['pcash']}', pcheque='{$invb['pcheque']}', pcc='{$invb['pcc']}', pcredit='{$invb['pcredit']}', \r\n\t\t\t\thire_invid='{$invid}' \r\n\t\t\tWHERE invid='{$invb['invid']}'";
    } elseif (empty($monthly)) {
        $sql = "\r\n\t\t\t\tINSERT INTO hire.monthly_invoices (\r\n\t\t\t\t\tinvid, invnum, deptid, cusnum, deptname, cusacc, \r\n\t\t\t\t\tcusname, surname, cusaddr, cusvatno, cordno, \r\n\t\t\t\t\tordno, chrgvat, terms, traddisc, salespn, odate, \r\n\t\t\t\t\tdelchrg, subtot, vat, total, balance, comm, \r\n\t\t\t\t\tprinted, done, div, username, rounding, delvat, vatnum, \r\n\t\t\t\t\tpcash, pcheque, pcc, pcredit, invoiced_month, hire_invid\r\n\t\t\t\t) VALUES (\r\n\t\t\t\t\t'{$invid}', '{$invb['invnum']}', '{$invb['deptid']}', '{$invb['cusnum']}', '{$invb['deptname']}', '{$invb['cusacc']}', \r\n\t\t\t\t\t'{$invb['cusname']}', '{$invb['surname']}', '{$invb['cusaddr']}', '{$invb['cusvatno']}', '{$invb['cordno']}', \r\n\t\t\t\t\t'{$invb['ordno']}', '{$invb['chrgvat']}', '{$invb['terms']}', '{$invb['traddisc']}', '{$invb['salespn']}', '{$invb['odate']}', \r\n\t\t\t\t\t'{$invb['delchrg']}', '{$invb['subtot']}', '{$invb['vat']}' , '{$invb['total']}', '{$invb['balance']}', '{$invb['comm']}', \r\n\t\t\t\t\t'y', 'y', '" . USER_DIV . "', '" . USER_NAME . "', '{$invb['rounding']}', '{$invb['delvat']}', '{$invb['vatnum']}', \r\n\t\t\t\t\t'{$invb['pcash']}', '{$invb['pcheque']}', '{$invb['pcc']}', '{$invb['pcredit']}', '" . date("m") . "', '{$invid}'\r\n\t\t\t\t)";
    }
    db_exec($sql) or errDie("Unable to store monthly invoice.");
    pglib_transaction("COMMIT");
    if (isset($upBtn)) {
        if ($upBtn == "Return") {
            return returnHire();
        } elseif ($upBtn == "Invoice") {
            return invoiceHire();
        }
    }
    return false;
}
function write($_POST)
{
    # Processes
    db_connect();
    # Get vars
    extract($_POST);
    if (isset($back)) {
        return add($_POST);
    }
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($bankid, "num", 1, 30, "Invalid Bank Account.");
    $v->isOk($date, "date", 1, 10, "Invalid Date Entry.");
    $v->isOk($descript, "string", 0, 255, "Invalid Description.");
    $v->isOk($reference, "string", 0, 50, "Invalid Reference Name/Number.");
    $v->isOk($cheqnum, "num", 0, 30, "Invalid Cheque number.");
    $v->isOk($amount, "float", 1, 10, "Invalid amount.");
    $v->isOk($supid, "num", 1, 20, "Invalid Supplier account.");
    # 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='&laquo; Correct submission'>";
        return $confirm;
    }
    # CHECK IF THIS DATE IS IN THE BLOCKED RANGE
    $blocked_date_from = getCSetting("BLOCKED_FROM");
    $blocked_date_to = getCSetting("BLOCKED_TO");
    if (strtotime($date) >= strtotime($blocked_date_from) and strtotime($date) <= 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>";
    }
    # Date format
    $date = explode("-", $date);
    $date = $date[2] . "-" . $date[1] . "-" . $date[0];
    $cheqnum = 0 + $cheqnum;
    # Get bank account name
    db_connect();
    $sql = "SELECT accname,bankname FROM bankacct WHERE bankid = '{$bankid}' AND div = '" . USER_DIV . "'";
    $bankRslt = db_exec($sql);
    $bank = pg_fetch_array($bankRslt);
    # Get account name
    $supRslt = get("cubit", "*", "suppliers", "supid", $supid);
    $sup = pg_fetch_array($supRslt);
    $bankaccid = getbankaccid($bankid);
    db_conn("exten");
    # Get debtors control account
    $sql = "SELECT credacc FROM departments WHERE deptid ='{$sup['deptid']}' AND div = '" . USER_DIV . "'";
    $deptRslt = db_exec($sql);
    $dept = pg_fetch_array($deptRslt);
    pglib_transaction("BEGIN");
    db_connect();
    $Sl = "INSERT INTO sup_stmnt(supid, amount, edate, descript,ref,cacc, div) VALUES('{$supid}','{$amount}','{$date}', '{$descript}','{$cheqnum}','{$bankaccid}', '" . USER_DIV . "')";
    $Rs = db_exec($Sl) or errDie("Unable to insert statement record in Cubit.", SELF);
    # Update the supplier (make balance less)
    $sql = "UPDATE suppliers SET balance = (balance + '{$amount}') WHERE supid = '{$supid}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
    suppCT($amount, $supid, $date);
    # record the payment record
    db_connect();
    $sql = "INSERT INTO cashbook(bankid, trantype, date, name, descript, cheqnum, amount, banked, accinv, suprec, reference, div) VALUES ('{$bankid}', 'deposit', '{$date}', '{$sup['supno']} - {$sup['supname']}', '{$descript}', '{$cheqnum}', '{$amount}', 'no', '{$dept['credacc']}', '{$supid}', '{$reference}', '" . USER_DIV . "')";
    $Rslt = db_exec($sql) or errDie("Unable to add bank payment to database.", SELF);
    $refnum = getrefnum();
    # DT(account involved), CT(bank)
    writetrans($bankaccid, $dept['credacc'], $date, $refnum, $amount, $descript);
    suppledger($supid, $bankaccid, $date, 0, $descript, $amount, 'c');
    pglib_transaction("COMMIT");
    # Status report
    $write = "\n\t\t\t\t<table " . TMPL_tblDflts . " width='100%'>\n\t\t\t\t\t<tr>\n\t\t\t\t\t\t<th>Bank Receipt</th>\n\t\t\t\t\t</tr>\n\t\t\t\t\t<tr class='datacell'>\n\t\t\t\t\t\t<td>Bank Receipt from supplier : {$sup['supname']} added to cash book.</td>\n\t\t\t\t\t</tr>\n\t\t\t\t</table>";
    # main table (layout with menu)
    $OUTPUT = "\n\t\t\t\t<center>\n\t\t\t\t<table width='90%'>\n\t\t\t\t\t<tr valign='top'>\n\t\t\t\t\t\t<td width='50%'>{$write}</td>\n\t\t\t\t\t\t<td align='center'>\n\t\t\t\t\t\t\t<table " . TMPL_tblDflts . " width='80%'>\n\t\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t\t<th>Quick Links</th>\n\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t\t<td><a href='bank-pay-add.php'>Add Bank Payment</a></td>\n\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t\t<td><a href='bank-recpt-add.php'>Add Bank Receipt</a></td>\n\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t\t<td><a href='cashbook-view.php'>View Cash Book</a></td>\n\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t</table>\n\t\t\t\t\t\t</td>\n\t\t\t\t\t</tr>\n\t\t\t\t</table>";
    return $OUTPUT;
}
Exemple #27
0
$claro_loginSucceeded = false;
$currentUser = false;
if ($logout && !empty($_SESSION['_uid'])) {
    // logout from CAS server
    if (get_conf('claro_CasEnabled', false) && get_conf('claro_CasGlobalLogout')) {
        require get_path('rootSys') . '/claroline/auth/extauth/cas/casProcess.inc.php';
    }
    // needed to notify that a user has just loggued out
    $logout_uid = $_SESSION['_uid'];
}
if (!empty($_SESSION['_uid']) && !($login || $logout)) {
    if (isset($_REQUEST['switchToUser'])) {
        if (!empty($_SESSION['_user']['isPlatformAdmin'])) {
            if ((bool) $_SESSION['_user']['isPlatformAdmin'] === true) {
                $targetId = $_REQUEST['switchToUser'];
                if (user_is_admin($targetId)) {
                    exit('ERROR !! You cannot access another administrator account !');
                }
                try {
                    $currentUser = Claro_CurrentUser::getInstance($targetId, true);
                    $currentUser->saveToSession();
                } catch (Exception $ex) {
                    exit('ERROR !! Undefined user id: the requested user doesn\'t exist' . 'at line ' . __LINE__);
                }
                $_SESSION['_uid'] = $targetId;
                $_SESSION['isVirtualUser'] = true;
                $_SESSION['is_platformAdmin'] = $_SESSION['_user']['isPlatformAdmin'];
                $_SESSION['is_allowedCreateCourse'] = $_SESSION['_user']['isCourseCreator'];
            }
        }
    }
function display()
{
    extract($_REQUEST);
    $fields = array();
    $fields["frm_year"] = date("Y");
    $fields["frm_month"] = date("m");
    $fields["frm_day"] = "01";
    $fields["to_year"] = date("Y");
    $fields["to_month"] = date("m");
    $fields["to_day"] = date("d");
    extract($fields, EXTR_SKIP);
    if (user_is_admin(USER_ID)) {
        $user_id = $_REQUEST["user_id"];
    } else {
        $user_id = USER_ID;
    }
    // Retrieve user information
    $sql = "SELECT * FROM cubit.users WHERE userid='{$user_id}'";
    $user_rslt = db_exec($sql) or errDie("Unable to retrieve user.");
    $user_data = pg_fetch_array($user_rslt);
    // Keep track of the totals
    $totals = array();
    $totals["customers"] = 0;
    $totals["discount"] = 0;
    $totals["total"] = 0;
    $totals["ocustomers"] = 0;
    $totals["odiscount"] = 0;
    $totals["ototal"] = 0;
    $totals["bcustomers"] = 0;
    $totals["bdiscount"] = 0;
    $totals["btotal"] = 0;
    $frm_date = "{$frm_year}-{$frm_month}-{$frm_day}";
    $to_date = "{$to_year}-{$to_month}-{$to_day}";
    // Retrieve the invoices
    $sql = "SELECT * FROM cubit.sorders\n\t\t\tWHERE username='******'username']}' AND done='y' AND accepted='y'\n\t\t\t\tAND odate BETWEEN '{$frm_date}' AND '{$to_date}'";
    $inv_rslt = db_exec($sql) or errDie("Unable to retrieve invoices.");
    $inv_out = "";
    while ($inv_data = pg_fetch_array($inv_rslt)) {
        $inv_out .= "\n\t\t<tr class='" . bg_class() . "'>\n\t\t\t<td>{$inv_data['odate']}</td>\n\t\t\t<td>{$inv_data['cusname']} {$inv_data['surname']}</td>\n\t\t\t<td align='center'>{$inv_data['sordid']}</td>\n\t\t\t<td align='center'>{$inv_data['ordno']}</td>\n\t\t\t<td align='center'>{$inv_data['cordno']}</td>\n\t\t\t<td align='right'>" . CUR . "{$inv_data['discount']}</td>\n\t\t\t<td align='right'>" . CUR . "{$inv_data['total']}</td>\n\t\t</tr>";
        // Add to the totals
        $totals["customers"]++;
        $totals["discount"] += $inv_data["discount"];
        $totals["total"] += $inv_data["total"];
    }
    $totals["bcustomers"] += $totals["customers"];
    $totals["bdiscount"] += $totals["discount"];
    $totals["btotal"] += $totals["total"];
    $invtot_out = "\n\t<tr class='" . bg_class() . "'>\n\t\t<td colspan='5'>&nbsp;</td>\n\t\t<td align='right'><b>" . CUR . sprint($totals["discount"]) . "</b></td>\n\t\t<td align='right'><b>" . CUR . sprint($totals["total"]) . "</b></td>\n\t</tr>";
    // Outstanding invoices
    $sql = "SELECT * FROM cubit.sorders\n\t\t\tWHERE username='******'username']}' AND done='y' AND accepted='n'\n\t\t\t\t\tAND odate BETWEEN '{$frm_date}' AND '{$to_date}'";
    $out_rslt = db_exec($sql) or errDie("Unable to retrieve outstanding invoices.");
    $out_out = "";
    while ($out_data = pg_fetch_array($out_rslt)) {
        $out_out .= "\n\t\t<tr class='" . bg_class() . "'>\n\t\t\t<td>{$out_data['odate']}</td>\n\t\t\t<td>{$out_data['cusname']} {$out_data['surname']}</td>\n\t\t\t<td align='center'>{$out_data['sordid']}</td>\n\t\t\t<td align='center'>{$out_data['ordno']}</td>\n\t\t\t<td align='center'>{$out_data['cordno']}</td>\n\t\t\t<td align='right'>" . CUR . "{$out_data['discount']}</td>\n\t\t\t<td align='right'>" . CUR . "{$out_data['total']}</td>\n\t\t</tr>";
        $totals["ocustomers"]++;
        $totals["odiscount"] += $out_data["discount"];
        $totals["ototal"] += $out_data["total"];
    }
    $totals["bcustomers"] += $totals["ocustomers"];
    $totals["bdiscount"] += $totals["odiscount"];
    $totals["btotal"] += $totals["ototal"];
    $outtot_out = "\n\t<tr class='" . bg_class() . "'>\n\t\t<td colspan='5'>&nbsp;</td>\n\t\t<td align='right'><b>" . CUR . sprint($totals["odiscount"]) . "</b></td>\n\t\t<td align='right'><b>" . CUR . sprint($totals["ototal"]) . "</b></td>\n\t</tr>";
    $bigtot_out = "\n\t<tr>\n\t\t<th colspan='7'>Grand Totals</th>\n\t</tr>\n\t<tr class='" . bg_class() . "'>\n\t\t<td colspan='5'>&nbsp;</td>\n\t\t<td align='right'><b>" . CUR . sprint($totals["bdiscount"]) . "</b></td>\n\t\t<td align='right'><b>" . CUR . sprint($totals["btotal"]) . "</b></td>\n\t</tr>";
    $OUTPUT = "<center>\n\t<h3>View Invoiced Sales Orders</h3>\n\t<form method='post' action='" . SELF . "'>\n\t<input type='hidden' name='key' value='display' />\n\t<input type='hidden' name='user_id' value='{$user_id}' />\n\t<table " . TMPL_tblDflts . ">\n\t\t<tr>\n\t\t\t<th colspan='4'>Date Range</th>\n\t\t</tr>\n\t\t<tr class='" . bg_class() . "'>\n\t\t\t<td>" . mkDateSelect("frm", $frm_year, $frm_month, $frm_day) . "</td>\n\t\t\t<td><b> To </b></td>\n\t\t\t<td>" . mkDateSelect("to", $to_year, $to_month, $to_day) . "</td>\n\t\t\t<td><input type='submit' value='Select' /></td>\n\t\t</tr>\n\t</table>\n\t<p></p>\n\t<table " . TMPL_tblDflts . ">\n\t\t<tr>\n\t\t\t<th colspan='7'>Invoiced</th>\n\t\t</tr>\n\t\t<tr>\n\t\t\t<th>Date</th>\n\t\t\t<th>Customer</th>\n\t\t\t<th>Sales Order No</th>\n\t\t\t<th>Order No</th>\n\t\t\t<th>Customer Order No</th>\n\t\t\t<th>Discount</th>\n\t\t\t<th>Total</th>\n\t\t</tr>\n\t\t{$inv_out}\n\t\t{$invtot_out}\n\t\t<tr>\n\t\t\t<th colspan='7'>Outstanding</th>\n\t\t</tr>\n\t\t\t<tr>\n\t\t\t\t<th>Date</th>\n\t\t\t\t<th>Customer</th>\n\t\t\t\t<th>Sales Order No</th>\n\t\t\t\t<th>Order No</th>\n\t\t\t\t<th>Customer Order No</th>\n\t\t\t\t<th>Discount</th>\n\t\t\t\t<th>Total</th>\n\t\t\t</tr>\n\t\t{$out_out}\n\t\t{$outtot_out}\n\t\t" . TBL_BR . "\n\t\t{$bigtot_out}\n\t</table>\n\t</form>\n\t</center>";
    return $OUTPUT;
}
Exemple #29
0
<div class="menu">
	<ul>
		<li><a href="/user/main">Dashboard</a>
		<li><a href="/user/manage">Manage Account</a>
	<?php 
if (user_is_admin()) {
    ?>
		<li class="active"><a href="/user/admin">User Admin</a>
		<li><a href="/event/pending">Pending Events</a>
	<?php 
}
?>
	</ul>
	<div class="clear"></div>
</div>

<?php 
echo form_open('user/admin');
echo form_input('user_search', $this->validation->user_search);
echo form_submit('sub', 'Search');
//echo form_button('clear','Clear','onClick="document.location.href=\'/user/admin\';"');
echo form_close();
?>

<b>Pages:</b>
<?php 
for ($i = 1; $i <= $page_ct; $i++) {
    $style = $i == $page ? 'style="font-weight:bold"' : '';
    echo '<a ' . $style . ' href="/user/admin/' . $i . '">' . $i . '</a> ';
}
?>
function alloc($_POST, $err = "")
{
    extract($_POST);
    if (isset($back)) {
        if (isset($e)) {
            header("Location: cashbook-entry.php");
            exit;
        }
        return sel_cus($_POST);
    }
    if (isset($print_recpt) and strlen($print_recpt) > 0) {
        $send_print = "<input type='hidden' name='print_recpt' value='{$print_recpt}'>";
    } else {
        $send_print = "";
    }
    if (isset($bulk_pay) and strlen($bulk_pay) > 0) {
        $send_bulk = "<input type='hidden' name='bulk_pay' value='yes'>";
    } else {
        $send_bulk = "";
    }
    $all = 0;
    $date_arr = explode("-", $tdate);
    $date_year = $date_arr[0];
    $date_month = $date_arr[1];
    $date_day = $date_arr[2];
    require_lib("validate");
    $v = new validate();
    $v->isOk($bankid, "num", 1, 30, "Select Bank Account.");
    $v->isOk($date_day, "num", 1, 2, "Invalid Date day.");
    $v->isOk($all, "num", 1, 1, "Invalid allocation.");
    $v->isOk($date_month, "num", 1, 2, "Invalid Date month.");
    $v->isOk($date_year, "num", 1, 4, "Invalid Date Year.");
    $v->isOk($descript, "string", 0, 255, "Invalid Description.");
    $v->isOk($reference, "string", 0, 50, "Invalid Reference Name/Number.");
    $v->isOk($cheqnum, "num", 0, 30, "Invalid Cheque number.");
    $v->isOk($amt, "float", 1, 40, "Invalid amount.");
    $v->isOk($cusid, "num", 1, 10, "Invalid customer number.");
    if (strlen($date_year) != 4) {
        $v->isOk($bankname, "num", 1, 1, "Invalid Date year.");
    }
    if ($amt < 0.01) {
        $v->addError($amt, "Amount too small.");
    }
    $date = $date_day . "-" . $date_month . "-" . $date_year;
    if (!checkdate($date_month, $date_day, $date_year)) {
        $v->isOk($date, "num", 1, 1, "Invalid date.");
    }
    if ($v->isError()) {
        $confirm = $v->genErrors();
        $confirm .= "<br>" . "<input type='button' onClick='history.back();' value='&laquo Correction'>";
        return $confirm;
        //.alloc($_POST);
    }
    # CHECK IF THIS DATE IS IN THE BLOCKED RANGE
    $blocked_date_from = getCSetting("BLOCKED_FROM");
    $blocked_date_to = getCSetting("BLOCKED_TO");
    if (strtotime($date) >= strtotime($blocked_date_from) and strtotime($date) <= 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>";
    }
    // bank account name
    if ($bankid == "0" or ($bank = qryBankAcct($bankid, "accname, bankname")) === false) {
        $bank['accname'] = "Cash";
        $bank['bankname'] = "";
    }
    // customer name
    $cus = qryCustomer($cusid, "cusname, surname");
    if ($print_recpt == "yes") {
        $show_print_recpt = "Yes";
    } else {
        $show_print_recpt = "No";
    }
    $confirm = "\n\t\t<h3>New Bank Receipt</h3>\n\t\t{$err}\n\t\t<form action='" . SELF . "' method='POST'>\n\t\t\t<input type='hidden' name='key' value='confirm'>\n\t\t\t<input type='hidden' name='accnum' value=''>\n\t\t\t<input type='hidden' name='bankid' value='{$bankid}'>\n\t\t\t<input type='hidden' name='date' value='{$date}'>\n\t\t\t<input type='hidden' name='all' value='{$all}'>\n\t\t\t<input type='hidden' name='cusid' value='{$cusid}'>\n\t\t\t<input type='hidden' name='date_day' value='{$date_day}'>\n\t\t\t<input type='hidden' name='date_month' value='{$date_month}'>\n\t\t\t<input type='hidden' name='date_year' value='{$date_year}'>\n\t\t\t<input type='hidden' name='descript' value='{$descript}'>\n\t\t\t<input type='hidden' name='reference' value='{$reference}'>\n\t\t\t<input type='hidden' name='cheqnum' value='{$cheqnum}'>\n\t\t\t<input type='hidden' name='amt' value='{$amt}'>\n\t\t\t{$send_bulk}\n\t\t\t{$send_print}\n\t\t<table " . TMPL_tblDflts . ">\n\t\t\t<tr>\n\t\t\t\t<th>Field</th>\n\t\t\t\t<th>Value</th>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Account</td>\n\t\t\t\t<td>{$bank['accname']} - {$bank['bankname']}</td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Date</td>\n\t\t\t\t<td valign='center'>{$date}</td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Received from</td>\n\t\t\t\t<td valign='center'>{$cus['cusname']} {$cus['surname']}</td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Description</td>\n\t\t\t\t<td valign='center'>" . nl2br($descript) . "</td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Reference</td>\n\t\t\t\t<td valign='center'>{$reference}</td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Cheque Number</td>\n\t\t\t\t<td valign='center'>{$cheqnum}</td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Amount</td>\n\t\t\t\t<td valign='center'>" . CUR . " {$amt}</td>\n\t\t\t</tr>\n\t\t\t" . TBL_BR . "\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Print Receipt</td>\n\t\t\t\t<td>{$show_print_recpt}</td>\n\t\t\t</tr>";
    /* OPTION 1 : AUTO ALLOCATE (allocate) */
    #we need a new why of allocating this ... stock,nonstock,pos order is counter productive
    #so, we get them all into an array, and sort that ...
    if ($all == 0) {
        $out = $amt;
        $invs_arr = array();
        // Connect to database
        db_connect();
        #####################[ GET OUTSTANDING INVOICES ]######################
        $sql = "SELECT invnum, invid, balance, terms, odate FROM invoices WHERE cusnum = '{$cusid}' AND printed = 'y' AND balance>0 AND div = '" . USER_DIV . "' ORDER BY odate ASC";
        $prnInvRslt = db_exec($sql);
        while (($inv = pg_fetch_array($prnInvRslt)) && $out > 0) {
            $invs_arr[] = array("s", $inv['odate'], "{$inv['invid']}", "{$inv['balance']}");
        }
        #####################[ GET OUTSTANDING NON STOCK INVOICES ]######################
        $sql = "SELECT invnum, invid, balance, odate FROM nons_invoices WHERE cusid='{$cusid}' AND done='y' AND balance>0 AND div='" . USER_DIV . "' ORDER BY odate ASC";
        $prnInvRslt = db_exec($sql);
        while (($inv = pg_fetch_array($prnInvRslt)) && $out > 0) {
            $invs_arr[] = array("n", $inv['odate'], "{$inv['invid']}", "{$inv['balance']}");
        }
        $out = sprint($out);
        #####################[ GET OUTSTANDING POS INVOICES ]######################
        $sqls = array();
        for ($i = 1; $i <= 12; ++$i) {
            $sqls[] = "\n\t\t\t\tSELECT invnum, invid, balance, odate \n\t\t\t\tFROM \"{$i}\".pinvoices \n\t\t\t\tWHERE cusnum='{$cusid}' AND done='y' AND balance > 0 AND div='" . USER_DIV . "'";
        }
        $sql = implode(" UNION ", $sqls);
        $prnInvRslt = db_exec($sql);
        while ($inv = pg_fetch_array($prnInvRslt)) {
            $invs_arr[] = array("p", $inv['odate'], "{$inv['invid']}", "{$inv['balance']}");
        }
        if (isset($invs_arr) and is_array($invs_arr)) {
            $confirm .= "\n\t\t\t\t<tr><td><br></td></tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<th>Type</th>\n\t\t\t\t\t<th>Invoice</th>\n\t\t\t\t\t<th>Outstanding Amount</th>\n\t\t\t\t\t<th></th>\n\t\t\t\t\t<th>Date</th>\n\t\t\t\t\t<th>Amount</th>\n\t\t\t\t</tr>";
        }
        #compile results into an array we can sort by date
        $search_arr = array();
        foreach ($invs_arr as $key => $array) {
            $search_arr[$key] = $array[1];
        }
        #sort array by date
        asort($search_arr);
        #add sorted invoices to payment listing
        foreach ($search_arr as $key => $date) {
            $arr = $invs_arr[$key];
            if ($arr[0] == "s") {
                $get_sql = "SELECT invnum, invid, balance, terms, odate FROM invoices WHERE cusnum = '{$cusid}' AND printed = 'y' AND balance>0 AND div = '" . USER_DIV . "' AND invid = '{$arr['2']}'  LIMIT 1";
                $run_sql = db_exec($get_sql) or errDie("Unable to get stock invoice information.");
                if (pg_numrows($run_sql) > 0) {
                    $inv = pg_fetch_array($run_sql);
                    $invid = $inv['invid'];
                    $val = allocamt($out, $inv["balance"]);
                    $confirm .= "\n\t\t\t\t\t\t<input type='hidden' name='paidamt[{$invid}]' size='10' value='{$val}'>\n\t\t\t\t\t\t<input type='hidden' size='20' name='invids[{$invid}]' value='{$inv['invid']}'>\n\t\t\t\t\t\t<tr bgcolor='" . bgcolor($i) . "'>\n\t\t\t\t\t\t\t<td>Stock Invoice</td>\n\t\t\t\t\t\t\t<td>{$inv['invnum']}</td>\n\t\t\t\t\t\t\t<td>" . CUR . " {$inv['balance']}</td>\n\t\t\t\t\t\t\t<td>{$inv['terms']} days</td>\n\t\t\t\t\t\t\t<td>{$inv['odate']}</td>\n\t\t\t\t\t\t\t<td>" . CUR . " {$val}</td>\n\t\t\t\t\t\t</tr>";
                }
            } elseif ($arr[0] == "n") {
                //sdate as
                $get_sql = "SELECT invnum, invid, balance, odate FROM nons_invoices WHERE cusid='{$cusid}' AND done='y' AND balance>0 AND div='" . USER_DIV . "' AND invid = '{$arr['2']}' LIMIT 1";
                $run_sql = db_exec($get_sql) or errDie("Unable to get non stock information.");
                if (pg_numrows($run_sql) > 0) {
                    $inv = pg_fetch_array($run_sql);
                    $invid = $inv['invid'];
                    $val = allocamt($out, $inv["balance"]);
                    $confirm .= "\n\t\t\t\t\t\t<input type='hidden' name='paidamt[{$invid}]' value='{$val}'>\n\t\t\t\t\t\t<input type='hidden' name='itype[{$invid}]' value='Yes'>\n\t\t\t\t\t\t<tr bgcolor='" . bgcolor($i) . "'>\n\t\t\t\t\t\t\t<td>Non Stock Invoice</td>\n\t\t\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\t\t<td>" . CUR . " {$inv['balance']}</td>\n\t\t\t\t\t\t\t<td></td>\n\t\t\t\t\t\t\t<td>{$inv['odate']}</td>\n\t\t\t\t\t\t\t<td>" . CUR . " {$val}</td>\n\t\t\t\t\t\t</tr>";
                }
            } else {
                $sqls = array();
                for ($i = 1; $i <= 12; ++$i) {
                    $sqls[] = "\n\t\t\t\t\t\tSELECT invnum, invid, balance, odate \n\t\t\t\t\t\tFROM \"{$i}\".pinvoices \n\t\t\t\t\t\tWHERE cusnum='{$cusid}' AND done='y' AND balance > 0 AND div='" . USER_DIV . "' AND invid = '{$arr['2']}'";
                }
                $get_sql = implode(" UNION ", $sqls);
                $run_sql = db_exec($get_sql) or errDie("Unable to get pos invoice information.");
                if (pg_numrows($run_sql) > 0) {
                    $inv = pg_fetch_array($run_sql);
                    $invid = $inv['invid'];
                    $val = allocamt($out, $inv["balance"]);
                    $confirm .= "\n\t\t\t\t\t\t<input type='hidden' size='20' name='invids[{$invid}]' value='{$inv['invid']}'>\n\t\t\t\t\t\t<input type='hidden' name='paidamt[{$invid}]' size='10' value='{$val}'>\n\t\t\t\t\t\t<input type='hidden' name='ptype[{$invid}]' value='YnYn'>\n\t\t\t\t\t\t<tr bgcolor='" . bgcolor($i) . "'>\n\t\t\t\t\t\t\t<td>POS Invoice</td>\n\t\t\t\t\t\t\t<td>{$inv['invnum']}</td>\n\t\t\t\t\t\t\t<td>" . CUR . " {$inv['balance']}</td>\n\t\t\t\t\t\t\t<td></td>\n\t\t\t\t\t\t\t<td>{$inv['odate']}</td>\n\t\t\t\t\t\t\t<td>" . CUR . " {$val}</td>\n\t\t\t\t\t\t</tr>";
                }
            }
        }
        #if there is any amount unallocated, it goes to general transaction
        $confirm .= "\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td colspan='6'><b>A general transaction will credit the client's account with " . CUR . " {$out} </b></td>\n\t\t\t</tr>";
    }
    vsprint($out);
    $confirm .= "\n\t\t\t<input type='hidden' name='out' value='{$out}'>\n\t\t\t<tr>\n\t\t\t\t<td><input type='submit' name='back' value='&laquo; Correction'></td>\n\t\t\t\t<td align='right'><input type='submit' value='Confirm &raquo'></td>\n\t\t\t</tr>\n\t\t</table>\n\t\t</form>" . mkQuickLinks(ql("../core/trans-new.php", "Journal Transactions"), ql("../customers-view.php", "View Customers"));
    return $confirm;
}