예제 #1
0
function check_messages()
{
    $qry = new dbSelect("req", "cubit", grp(m("cols", "1"), m("where", "recipient='" . USER_NAME . "' AND alerted IS NULL")));
    $qry->run();
    if ($qry->num_rows() == 0) {
        return "NO MESSAGES";
    } else {
        $cols = grp(m("alerted", "1"));
        $upd = new dbUpdate("req", "cubit", $cols, "recipient='" . USER_NAME . "'");
        $upd->run(DB_UPDATE);
        $qry->setOpt(grp(m("where", "recipient='" . USER_NAME . "' AND viewed='0'")));
        $qry->run();
        return "MSGS: " . $qry->num_rows();
    }
}
function write()
{
    extract($_REQUEST);
    if ($page_option == "Edit") {
        $sql = "UPDATE cubit.diary_locations SET location='{$location}'\n\t\tWHERE id='{$id}'";
    } else {
        $sql = "INSERT INTO cubit.diary_locations (location) VALUES ('{$location}')";
    }
    db_exec($sql) or errDie("Unable to save location.");
    if (frmupdate_passon()) {
        $newlist = new dbSelect("diary_locations", "cubit");
        $newlist->run();
        $a = array();
        if ($newlist->num_rows() > 0) {
            while ($row = $newlist->fetch_array()) {
                $a[$row["id"]] = "{$row['location']}";
            }
        }
        $js = frmupdate_exec(array($a), true);
    } else {
        $js = "";
    }
    $OUTPUT = "{$js}\n\t<h3>{$page_option} Location</h3>\n\t<table cellpadding='2' cellspacing='0' class='shtable'>\n\t\t<tr>\n\t\t\t<th>Write</th>\n\t\t</tr>\n\t\t<tr class='" . bg_class() . "'>\n\t\t\t<td>Successfully saved location.</td>\n\t\t</tr>\n\t</table>";
    return $OUTPUT;
}
function bal($id)
{
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($id, "num", 1, 20, "Invalid Cash Flow Statement number.");
    # display errors, if any
    if ($v->isError()) {
        $theseErrors = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $theseErrors .= "<li class=err>" . $e["msg"];
        }
        $theseErrors .= "<p><input type=button onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $theseErrors;
    }
    # connect to core DB
    core_connect();
    # get the Trial Balance
    $cf = new dbSelect("save_cashflow", "core", grp(m("cols", "output, date_trunc('day', gentime) as gentime"), m("where", "id='{$id}'")));
    $cf->run();
    if ($cf->num_rows() < 1) {
        return "<center><li> Invalid Cash Flow Statement Number.</li></center>";
    }
    $stmnt = $cf->fetch_array();
    $OUTPUT = base64_decode($stmnt['output']);
    if (isset($_GET["xls"])) {
        $cftime = preg_replace("/ 00:00.*/", "", $stmnt["gentime"]);
        require_lib("xls");
        Stream("cashflow-{$cftime}", $OUTPUT);
    } else {
        require "../tmpl-print.php";
    }
}
function edit()
{
    extract($_GET);
    if (isset($id)) {
        $subinfo = new dbSelect("subsistence", "cubit", array("where" => wgrp(m("id", "{$id}"))));
        $subinfo->run();
        if ($subinfo->num_rows() > 0) {
            extract($subinfo->fetch_array(), EXTR_SKIP);
        }
    }
    $fields = array("name" => "", "in_republic" => "yes", "meals" => "yes", "accid" => false);
    foreach ($fields as $fname => $val) {
        if (!isset(${$fname})) {
            ${$fname} = $val;
        }
    }
    /* no accid is set, use salaries and wages */
    if ($accid === false) {
        $swacc = qryAccountsName("Salaries and Wages", "accid");
        $accid = $swacc["accid"];
    }
    $bg = 0;
    $OUT = "\n\t<h3>Define Subsistence Allowance</h3>\n\t<li class='err'>The selection on this window will create a Subsistence Allowance\n\twith the specified properties. To assign this subsistence to an employee you\n\twill need to edit the employee, and on the 'Calculate Salary' window\n\tfill out the employee specific information involving the Subsistence Allowance.</li>\n\t<form method='get' action='" . SELF . "'>\n\t<input type='hidden' name='key' value='write'>\n\t" . (isset($id) ? "<input type='hidden' name='id' value='{$id}'" : "") . "\n\t<table " . TMPL_tblDflts . ">\n\t<tr>\n\t\t<th colspan='2'>Details</th>\n\t</tr>\n\t<tr class='" . bg_class() . "'>\n\t\t<td>Name:</td>\n\t\t<td><input type='text' name='name' value='{$name}'></td>\n\t</tr>\n\t<tr class='" . bg_class() . "'>\n\t\t<td>In Republic (ZA):</td>\n\t\t<td>\n\t\t\t<select name='in_republic'>\n\t\t\t\t<option value='yes' " . ($in_republic != "no" ? "selected" : "") . ">Yes</option>\n\t\t\t\t<option value='no' " . ($in_republic == "no" ? "selected" : "") . ">No</option>\n\t\t\t</select>\n\t\t</td>\n\t</tr>\n\t<tr class='" . bg_class() . "'>\n\t\t<td>Employee pays for own Meals:</td>\n\t\t<td>\n\t\t\t<select name='meals'>\n\t\t\t\t<option value='yes' " . ($meals != "no" ? "selected" : "") . ">Yes</option>\n\t\t\t\t<option value='no' " . ($meals == "no" ? "selected" : "") . ">No</option>\n\t\t\t</select>\n\t\t</td>\n\t</tr>\n\t<tr class='" . bg_class() . "'>\n\t\t<td>Account:</td>\n\t\t<td>" . finAccList("accid", false, $accid) . "</td>\n\t\t<td class='err'>Select an account where the expense must be debited to.</td>\n\t</tr>\n\t<tr>\n\t\t<td colspan='2' align='right'><input type='submit' value='Next'></td>\n\t</tr>\n\t</table>\n\t</form>\n\t<table " . TMPL_tblDflts . ">\n\t<tr>\n\t\t<td>\n\t\t\t<u><b>Subsistence allowance</b></u>\n\t\t\t<p>\n\t\t\tThe income tax provides that there shall not be included in the\n\t\t\ttaxable income of any person, any amount paid or granted by a\n\t\t\tprincipal as a reimbursement of, or as an advance for, the\n\t\t\texpenditure incurred or to be incurred by the employee - where\n\t\t\tthat employee must produce proof to that employer that such\n\t\t\texpenditure was wholly incurred and must account to that employer\n\t\t\tfor that expenditure.\n\t\t\t</p><p>\n\t\t\tFor the purpose of the above provision an employee shall be deemed\n\t\t\tto have actually incurred expenditure:\n\t\t\t<li>Where the employee proves to the Commissioner the amount of\n\t\t\tthe expenses incurred by him in respect of accommodation, meals or\n\t\t\tother incidental costs, the amount so actually incurred but\n\t\t\tlimited to the amount of the allowance or advance paid or granted\n\t\t\tto meet those expenses; or</li>\n\t\t\t<li>For each day or part of a day in the period during which that\n\t\t\temployee is absent from his or her usual place of residence, an\n\t\t\tamount in respect of meals and other incidental costs, or\n\t\t\tincidental costs only, determined by the Minister for the relevant\n\t\t\tyear of assessment by way of notice in The Gazette but limited to\n\t\t\tthe amount of the allowance paid or granted to meet those\n\t\t\texpenses.\n\t\t\t</p><p>\n\t\t\tAccording to the regulations published in The Gazette the\n\t\t\tfollowing amounts will be deemted to have been expended by an\n\t\t\temployee to whom an allowance or advance has been granted or paid:\n\t\t\t<li>Where the accommodation to which that allowance or advance\n\t\t\trelate is the Republic and that allowance or the advance is paid\n\t\t\tor granted to defray Incidental costs only, an amount equal to R93\n\t\t\tper day; or<br />\n\t\t\tThe cost of meals and incidental costs, an amount equal to R303\n\t\t\tper day; or</li>\n\t\t\t<li>Where the accommodation to which that allowance or advance\n\t\t\trelates is outside the Republic and that the allowance or advance\n\t\t\tis paid or granted to defray the cost of meals and incidental\n\t\t\tcosts, an amount equal to U.S. \$215 per day.</li>\n\t\t</td>\n\t</tr>\n\t</table>";
    return $OUT;
}
/**
 * locates a supplier by name, if not found creates and returns id
 *
 * @param string $name company name
 * @return int
 */
function locateSupplier($name)
{
    $qry = new dbSelect("suppliers", "cubit", grp(m("cols", "supid"), m("where", "lower(supname)=lower('{$name}')")));
    $qry->run();
    if ($qry->num_rows() > 0) {
        $id = $qry->fetch_result();
    } else {
        // insert into new supps
        $id = -1;
    }
    $qry->free();
    return $id;
}
function entersal(&$frm)
{
    /* @var $frm cForm */
    if ($frm->validate("entersal")) {
        return select_emp($frm);
    }
    $frm->setkey("writesal");
    extract($_POST);
    $empi = qryEmployee($empnum);
    $qry = new dbSelect("salpaid", "cubit", grp(m("cols", "month, week"), m("where", "empnum='{$empnum}' AND cyear='" . EMP_YEAR . "'"), m("order", "month, week"), m("group", "month, week")));
    //print $qry->sql;
    $qry->run();
    /* in case we did a correction, we run clean_fields to remove the 
    		previous employee's fields */
    $frm->clean_fields("headers");
    $frm->clean_fields("hrs", true);
    $frm->clean_fields("sal", true);
    $frm->setcell(1, 2);
    $frm->add_layout("\n\t\t<tr>\n\t\t\t<th>Month</th>\n\t\t\t" . ($empi["payprd"] == "m" ? "" : "<th>Week/Day</th>") . "\n\t\t\t<th>Basic Salary Rate<br />for Month</th>\n\t\t\t" . ($empi["saltyp"] != "h" ? "" : "<th>Hours Worked</th>") . "\n\t\t</tr>", false, "headers");
    while ($row = $qry->fetch_array()) {
        $sqry = new dbSelect("salpaid", "cubit", grp(m("where", "empnum='{$empnum}' AND cyear='" . EMP_YEAR . "'\n\t\t\t\t\t\tAND month='{$row['month']}' AND week='{$row['week']}'"), m("order", "true_ids DESC"), m("limit", "1")));
        $sqry->run();
        if ($sqry->num_rows() > 0) {
            $si = $sqry->fetch_array();
            /* hours field option */
            if ($empi["saltyp"] == "h") {
                $hrsopt = "<td>%fldonly</td>";
            } else {
                $hrsopt = "";
            }
            /* show week number */
            if ($empi["payprd"] == "m") {
                $weekdisp = "";
            } else {
                $weekdisp = "<td>{$row['week']}</td>";
            }
            $lay = "\n\t\t\t<tr %bg>\n\t\t\t\t<td>{$row['month']}</td>\n\t\t\t\t{$weekdisp}\n\t\t\t\t<td>%fldonly</td>\n\t\t\t\t{$hrsopt}\n\t\t\t</tr>";
            $frm->add_layout($lay);
            $frm->add_text("", "sal[{$si['id']}]", $si["salrate"], "float", "1:40", array("size" => "7"));
            if ($empi["saltyp"] == "h") {
                $frm->add_text("", "hrs[{$si['id']}]", $si["hours"], "float", "1:40", array("size" => "5"));
            }
        }
    }
    return $frm->getfrm_input();
}
예제 #7
0
 /**
  * returns general email settings, and if done does an r2sListSet and goes to email settings page
  * 
  * @return array
  */
 function qryEmailSettings()
 {
     $qry = new dbSelect("esettings", "cubit");
     $qry->run();
     $invalid = false;
     if ($qry->num_rows() <= 0) {
         $invalid = true;
     } else {
         $d = $qry->fetch_array();
         $qry->free();
         if ($d["smtp_host"] == "" || $d["fromname"] == "") {
             $invalid = true;
         }
     }
     if ($invalid) {
         r2sListSet("emailsettings");
         header("Location: email-settings.php");
         exit;
     }
     return $d;
 }
function export()
{
    $oc = array();
    /* add (if any) last closed year */
    $qry = new dbSelect("year", "core", grp(m("cols", "yrdb"), m("where", "closed='y'"), m("order", "yrname DESC"), m("limit", "1")));
    $qry->run();
    if ($qry->num_rows() > 0) {
        $qry->fetch_array();
        add_tbdata($oc, $qry->d["yrdb"], 1);
    }
    /* add current year */
    add_tbdata($oc, "core");
    /* generate output information */
    $headings = "<td rowspan='1'></td>";
    $subhead = "";
    $accinfo = array();
    /* go through each period */
    foreach ($oc as $name => $data) {
        $headings .= "<td colspan='1'>{$name}</td>";
        //$subhead .= "<th>Debit</th><th>Credit</th>";
        /* go through each account for current period */
        foreach ($data as $accname => $accdata) {
            if (!isset($accinfo[$accname])) {
                $accinfo[$accname] = "<td>{$accname}</td>";
            }
            $accinfo[$accname] .= "<td align='right'>" . fsmoney($accdata["debit"] - $accdata["credit"]) . "</td>";
        }
    }
    /* build output information */
    $OUT = "<table>";
    $OUT .= "<tr>{$headings}</tr>\n";
    //$OUT .= "<tr>$subhead</tr>\n";
    $OUT .= "<tr>" . implode("</tr>\n<tr>", $accinfo) . "</tr>";
    $OUT .= "</table>";
    /* stream information */
    $months = count($oc);
    // number of months of data we gathered
    StreamXLS("GeneralLedger{$months}", $OUT);
    return $OUT;
}
function view()
{
    // Connect to database
    core_Connect();
    // Query server
    $cf = new dbSelect("save_cashflow", "core", grp(m("where", "div='" . USER_DIV . "'")));
    $cf->run();
    if ($cf->num_rows() < 1) {
        $OUTPUT = "<li> There are no saved Cash Flow Statements.";
    } else {
        // Set up table to display in
        $OUTPUT = "\n\t\t<h3>View Saved Cash Flow Statements</h3>\n\t\t<table border=0 cellpadding='" . TMPL_tblCellPadding . "' cellspacing='" . TMPL_tblCellSpacing . "' width=300>\n\t\t<tr>\n\t\t\t<th>Statement No.</th>\n\t\t\t<th>Generated</th>\n\t\t\t<th colspan=2>Options</th>\n\t\t</tr>";
        // display all statements
        while ($stmnt = $cf->fetch_array()) {
            $OUTPUT .= "\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>{$stmnt['id']}({$stmnt['des']})</td>\n\t\t\t\t<td>{$stmnt['gentime']}</td>\n\t\t\t\t<td><a target='_blank' href='cash-flow-print.php?id={$stmnt['id']}'>Print</a></td>\n\t\t\t\t<td><a href='cash-flow-print.php?id={$stmnt['id']}&xls=t'>Spreadsheet</a></td>\n\t\t\t</tr>";
        }
        $OUTPUT .= "</table>";
    }
    $OUTPUT .= "\n\t<p>\n\t<table border=0 cellpadding='" . TMPL_tblCellPadding . "' cellspacing='" . TMPL_tblCellSpacing . "'>\n\t<tr><th>Quick Links</th></tr>\n\t<tr class=datacell><td><a href='index-reports.php'>Financials</a></td></tr>\n\t<tr class=datacell><td><a href='index-reports-stmnt.php'>Current Year Financial Statements</a></td></tr>\n\t<tr class='bg-odd'><td><a href='../main.php'>Main Menu</a></td></tr>\n\t</table>";
    // call template to display the info and die
    return $OUTPUT;
}
function write()
{
    extract($_REQUEST);
    if ($page_option == "Edit") {
        $sql = "UPDATE cubit.todo_main SET title='{$title}', team_id='{$team_id}'\n\t\tWHERE id='{$id}' AND user_id='" . USER_ID . "'";
    } else {
        $sql = "INSERT INTO cubit.todo_main (title, user_id, team_id)\n\t\tVALUES ('{$title}', '" . USER_ID . "', '{$team_id}')";
    }
    db_exec($sql) or errDie("Unable to save main todo.");
    if (frmupdate_passon()) {
        $newlist = new dbSelect("todo_main", "cubit");
        $newlist->run();
        // are we an admin?
        $sql = "SELECT admin FROM cubit.users WHERE userid='" . USER_ID . "'";
        $admin_rslt = db_exec($sql) or errDie("Unable to check for admin.");
        $admin = pg_fetch_result($admin_rslt, 0);
        $a = array();
        if ($newlist->num_rows() > 0) {
            $a[0] = "[None]";
            while ($row = $newlist->fetch_array()) {
                if (in_team(USER_ID, $row["team_id"])) {
                    $sql = "SELECT * FROM cubit.todo_main WHERE id='{$row['id']}'";
                    $tm_rslt = db_exec($sql) or errDie("Unable to retrieve todo.");
                    $count = pg_num_rows($tm_rslt);
                    $a[$row["id"]] = "{$row['title']} ({$count})";
                } else {
                    continue;
                }
            }
        }
        $js = frmupdate_exec(array($a), true);
    } else {
        $js = "";
    }
    $OUTPUT = "{$js}\n\t<h3>{$page_option} Main Todo</h3>\n\t<table cellpadding='2' cellspacing='0' class='shtable'>\n\t\t<tr>\n\t\t\t<th>Write</th>\n\t\t</tr>\n\t\t<tr class='odd'><td>Successfully saved the main todo.</td></tr>\n\t</table>";
    return $OUTPUT;
}
예제 #11
0
function errSend()
{
    /* check for valid email settings */
    $settings = new dbSelect("esettings", "cubit");
    $settings->run();
    if ($settings->num_rows() <= 0) {
        r2sListSet("emailsettings");
        header("Location: email-settings.php");
        exit;
    }
    $settings->fetch_array();
    $server = $settings->d["smtp_host"];
    $from = $settings->d["fromname"];
    $reply = $settings->d["reply"];
    /* build the email */
    $data = errData($_GET["id"]);
    $msg = new clsMailMsg();
    $msg->newMessage($from, $reply, "Error Report: {$data['errtime']}", "Error report file attached.");
    $msg->addAttachment("application/octet-stream", "error{$_GET['id']}-{$data['errtime']}.cer", $data["errdata"]);
    $md = $msg->getNewMessage();
    /* send the email */
    /**
     * ok, so lets stop catching errors because if the email sending fails
     * we are just going to go back to "an error has occured"
     */
    disableErrorNet();
    $smtp = new clsSMTPMail();
    $smtp->sendMessages($server, 25, false, false, false, ERRORNET_EMAIL, $md["from"], $md["subject"], $md["body"], $md["headers"]);
    $OUTPUT = "<h3>Error Report</h3>";
    if ($smtp->bool_success !== true) {
        $OUTPUT .= "Error sending report. Please save report and email it\n\t\t\tto <a class='nav' href='mailto: " . ERRORNET_EMAIL . "'>" . ERRORNET_EMAIL . "</a><br />\n\t\t\t<br />\n\t\t\t<input type='button' value='Save Error Report'\n\t\t\t\tonClick='document.location.href=\"" . relpath("geterror.php") . "?id={$_GET['id']}\";' />";
    } else {
        $OUTPUT .= "Successfully sent report. Thank You.";
    }
    return $OUTPUT;
}
function printCust()
{
    global $_SESSION;
    extract($_REQUEST);
    if (!isset($action)) {
        $action = "listcust";
    }
    $sqlfilter = "";
    $printCust_begin = "<h2>View Customers</h2>";
    $ajaxCust = "";
    $ajaxCust .= "\n\t<form action='statements-email.php' method='get'>\n\t<input type='hidden' name='key' value='confirm' />";
    if (!isset($offset) && isset($_SESSION["offset"])) {
        $offset = $_SESSION["offset"];
    } else {
        if (!isset($offset)) {
            $offset = 0;
        }
    }
    $_SESSION["offset"] = $offset;
    # connect to database
    db_connect();
    # counting the number of possible entries
    $sql = "SELECT * FROM customers\n    \t\tWHERE (div = '" . USER_DIV . "' OR  ddiv = '" . USER_DIV . "') {$sqlfilter}\n    \t\tORDER BY surname ASC";
    $rslt = db_exec($sql) or errDie("Error counting matching customers.");
    $custcount = pg_num_rows($rslt);
    # Query server
    $tot = 0;
    $totoverd = 0;
    $i = 0;
    $ajaxCust .= "\n\t<table " . TMPL_tblDflts . ">\n\n\t<tr>\n\t\t<th>Acc no.</th>\n\t\t<th>Company/Name</th>\n\t\t<th>Tel</th>\n\t\t<th>Category</th>\n\t\t<th>Class</th>\n\t\t<th colspan='2'>Balance</th>\n\t\t<th>Overdue</th>\n\t</tr>";
    /* query object for cashbook */
    $cashbook = new dbSelect("cashbook", "cubit");
    $custRslt = new dbSelect("customers", "cubit", grp(m("where", "(div ='" . USER_DIV . "' or ddiv='" . USER_DIV . "') {$sqlfilter}"), m("order", "surname ASC"), m("offset", $offset), m("limit", 100)));
    $custRslt->run();
    if ($custRslt->num_rows() < 1) {
        $ajaxCust .= "\n\t\t<tr class='" . bg_class() . "'>\n\t\t\t<td colspan='20'><li>There are no Customers matching the criteria entered.</li></td>\n\t\t</tr>";
    } else {
        while ($cust = $custRslt->fetch_array()) {
            if (!user_in_team($cust["team_id"], USER_ID)) {
                continue;
            }
            # Check type of age analisys
            if (div_isset("DEBT_AGE", "mon")) {
                $overd = ageage($cust['cusnum'], $cust['overdue'] / 30 - 1, $cust['location']);
            } else {
                $overd = age($cust['cusnum'], $cust['overdue'] - 1, $cust['location']);
            }
            if ($overd < 0) {
                $overd = 0;
            }
            if ($overd > $cust['balance']) {
                $overd = $cust['balance'];
            }
            if ($cust["location"] == "int") {
                $cur = qryCurrency($cust["fcid"], "rate");
                $rate = $cur["rate"];
                if ($rate != 0) {
                    $totoverd += $overd * $rate;
                } else {
                    $totoverd += $overd;
                }
            } else {
                $totoverd += $overd;
            }
            /* check if customer may be removed */
            $cashbook->setOpt(grp(m("where", "cusnum='{$cust['cusnum']}' AND banked='no' AND div='" . USER_DIV . "'")));
            $cashbook->run();
            if (strlen(trim($cust['bustel'])) < 1) {
                $cust['bustel'] = $cust['tel'];
            }
            $cust['balance'] = sprint($cust['balance']);
            if ($cust["location"] == "int") {
                if ($rate != 0.0) {
                    $tot = $tot + $cust['fbalance'] * $rate;
                } else {
                    $tot = $tot + $cust['balance'];
                }
            } else {
                $tot = $tot + $cust['balance'];
            }
            # Locations drop down
            $locs = array("loc" => "Local", "int" => "International", "" => "");
            $loc = $locs[$cust['location']];
            $fbal = "--";
            $ocurr = CUR;
            # alternate bgcolor
            $bgColor = bgcolor($i);
            $ajaxCust .= "<tr class='" . bg_class() . "'>";
            if ($action == "contact_acc") {
                $updatelink = "javascript: updateAccountInfo(\"{$cust['cusnum']}\", \"{$cust['accno']}\");";
                $ajaxCust .= "\n\t\t\t\t\t<td><a href='{$updatelink}'>{$cust['accno']}</a></td>\n\t\t\t\t\t<td><a href='{$updatelink}'>{$cust['surname']}</a></td>";
            } else {
                if ($action == "select") {
                    $ajaxCust .= "\n\t\t\t\t\t<td><a href='" . SELF . "?key=select&cusnum={$cust['cusnum']}&" . frmupdate_passon(true) . "'>{$cust['accno']}</a></td>\n\t\t\t\t\t<td><a href='" . SELF . "?key=select&cusnum={$cust['cusnum']}&" . frmupdate_passon(true) . "'>{$cust['surname']}</a></td>";
                } else {
                    $ajaxCust .= "\n\t\t\t\t\t<td>{$cust['accno']}</td>\n\t\t\t\t\t<td>{$cust['surname']}</td>";
                }
            }
            $ajaxCust .= "\n\t\t\t\t\t<td>{$cust['bustel']}</td>\n\t\t\t\t\t<td>{$cust['catname']}</td>\n\t\t\t\t\t<td>{$cust['classname']}</td>\n\t\t\t\t\t<td align='right' nowrap>{$ocurr} {$cust['balance']}</td>\n\t\t\t\t\t<td align='center' nowrap>{$fbal}</td>\n\t\t\t\t\t<td align='right' nowrap>{$ocurr} {$overd}</td>";
            $ajaxCust .= "</tr>";
        }
        $bgColor = bgcolor($i);
        $tot = sprint($tot);
        $totoverd = sprint($totoverd);
        $i--;
        $ajaxCust .= "\n\t\t<tr class='" . bg_class() . "'>\n\t\t\t<td colspan='5'>Total Amount Outstanding, from {$i} " . ($i > 1 ? "clients" : "client") . "</td>\n\t\t\t<td align='right' nowrap>" . CUR . " {$tot}</td>\n\t\t\t<td></td>\n\t\t\t<td align='right' nowrap>" . CUR . " {$totoverd}</td>\n\t\t</tr>";
    }
    $ajaxCust .= "\n\t\t" . TBL_BR . "\n\t\t</table>\n\t\t</form>";
    $printCust_end = "\n\t</div>";
    if (AJAX) {
        return $ajaxCust;
    } else {
        return "{$printCust_begin}{$ajaxCust}{$printCust_end}";
    }
}
예제 #13
0
function checknum()
{
    extract($_REQUEST);
    require_lib("validate");
    $v = new Validate();
    $v->isOk($topacc, "num", 4, 4, "Invalid Main Part.");
    $v->isOk($accnum, "num", 3, 3, "Invalid Sub Part.");
    /* is account number valid */
    if ($v->isError()) {
        $e = $v->getErrors();
        if (count($e) == 2) {
            $err = "Invalid account number.";
        } else {
            $err = $e[0]["msg"];
        }
    } else {
        /* does account number exist */
        $qry = new dbSelect("accounts", "core", grp(m("cols", "accname"), m("where", "topacc='{$topacc}' AND accnum='{$accnum}'"), m("limit", "1")));
        $qry->run();
        if (!isset($rslt)) {
            $rslt = array();
        }
        if ($qry->num_rows($rslt) > 0) {
            $accname = $qry->fetch_result();
            $err = "Account number in use: {$accname}.";
        } else {
            if ($accnum != "000") {
                $qry->setOpt(grp(m("where", "topacc='{$topacc}'")));
                $qry->run();
                if ($qry->num_rows() <= 0) {
                    $err = "Main Account doesn't exist.";
                }
            }
        }
    }
    if (!isset($err)) {
        $err = "<strong>Account number valid.</strong>";
    } else {
        $err = "<li class='err'>{$err}</li>";
    }
    return $err;
}
function import($frm)
{
    /* @var $frm cForm */
    if ($frm->validate("import")) {
        return view($frm);
    }
    /* get field indexes */
    $stkcod = false;
    $price = false;
    foreach ($_REQUEST["fld"] as $fi => $ft) {
        if ($ft != "ignore") {
            ${$ft} = $fi;
        }
    }
    /* import file if all field types specified */
    if ($stkcod === false || $price === false) {
        $frm->setmsg("<li class='err'>Not all field types satisfied</li>");
    } else {
        $qry = new dbSelect("spricelist", "exten", grp(m("cols", "listid"), m("where", "suppid='{$_REQUEST['supid']}'")));
        $qry->run();
        if ($qry->num_rows() <= 0) {
            $suppinfo = qrySupplier($_REQUEST["supid"]);
            $cols = grp(m("suppid", $_REQUEST["supid"]), m("listname", $suppinfo["supname"]), m("div", USER_DIV));
            $upd = new dbUpdate("spricelist", "exten", $cols);
            $upd->run(DB_INSERT);
            $listid = $upd->lastid("listid");
        } else {
            $listid = $qry->fetch_result();
        }
        $upd = new dbDelete("splist_prices", "exten", "listid='{$listid}'");
        $upd->run();
        $upd = new dbUpdate("splist_prices", "exten");
        $invalid_fields = array();
        $nosuch_fields = array();
        $file = ucfs::file("supplist");
        foreach ($file as $rd) {
            $ri = explode(",", $rd);
            $ri[$stkcod] = trim($ri[$stkcod]);
            $ri[$price] = trim($ri[$price]);
            if (cForm::validateValue($ri[$stkcod], "string", 1, 250) || cForm::validateValue($ri[$price], "float", 1, 40)) {
                $invalid_fields[] = $ri[$stkcod];
                continue;
            }
            $stkid = suppStkid($_REQUEST["supid"], $ri[$stkcod]);
            if ($stkid === false) {
                $stkinfo = array("stkid" => "0", "catid" => "0", "prdcls" => "0");
            } else {
                $stkinfo = qryStock($stkid, "stkid, catid, prdcls");
            }
            if (!isset($_REQUEST["vatinc"])) {
                $ri[$price] += $ri[$price] * TAX_VAT / 100;
            }
            $cols = grp(m("listid", $listid), m("stkid", $stkinfo["stkid"]), m("catid", $stkinfo["catid"]), m("clasid", $stkinfo["prdcls"]), m("price", $ri[$price]), m("div", USER_DIV), m("supstkcod", $ri[$stkcod]));
            $upd->setCols($cols);
            $upd->run();
        }
        if (count($invalid_fields) > 0) {
            $msg = "<br />The following items weren't imported because they contain\n\t\t\t\tinvalid values for either the stock code or the price:<br />";
            foreach ($invalid_fields as $v) {
                $msg .= "&nbsp;&nbsp;&nbsp;&nbsp;- {$v}<br />";
            }
        } else {
            $msg = "";
        }
        $frm->setmsg("<li class='err'>Successfully imported new pricelist.{$msg}</li>");
    }
    return view($frm);
}
function deny(&$frm)
{
    /* @var $frm cForm */
    if (($e = $frm->validateValue($_GET["id"], "num", 1, 10)) !== false) {
        return view($frm, "<li class='err'>Error reading key: {$e}.</li>");
    }
    $qry = new dbSelect("keys", "trh", grp(m("cols", "*, (key).*"), m("where", "id='{$_GET['id']}'")));
    $qry->run();
    if ($qry->num_rows() <= 0) {
        return view($frm, "<li class='err'>Invalid key selected.</li>");
    }
    $ki = $qry->fetch_array();
    if ($ki["custid"] == "-1") {
        $fromwho = "cust";
    } else {
        if ($ki["suppid"] == "-1") {
            $fromwho = "supp";
        } else {
            return view($frm, "<li class='err'>Key already approved.</li>");
        }
    }
    if (send_trhmsg($fromwho, "-1", $ki["email"], "rspkey", str_pad("denied", 32, 'A', STR_PAD_RIGHT))) {
        $upd = new dbDelete("keys", "trh", "id='{$_GET['id']}'");
        $upd->run();
        return view($frm, "<li class='err'>Successfully denied request.</li>");
    } else {
        /* set the id back to -1, because there was an error */
        $cols = grp(m("{$fromwho}id", "-1"));
        $upd = new dbUpdate("keys", "trh", $cols, "id='{$_POST['id']}'");
        $upd->run(DB_UPDATE);
        return view($frm, "<li class='err'>Error denying request.</li>");
    }
}
function printCust()
{
    global $_SESSION;
    extract($_REQUEST);
    if (!isset($action)) {
        $action = "listcust";
    }
    /* session var prefix */
    $SPRE = "custview_";
    /* max number of customers in list */
    if (isset($viewall_cust)) {
        $offset = 0;
        define("ACT_SHOW_LIMIT", 2147483647);
    } else {
        define("ACT_SHOW_LIMIT", SHOW_LIMIT);
    }
    if (!isset($fval) && isset($_SESSION["{$SPRE}fval"])) {
        $fval = $_SESSION["{$SPRE}fval"];
    }
    if (!isset($filter) && isset($_SESSION["{$SPRE}filter"])) {
        $filter = $_SESSION["{$SPRE}filter"];
    }
    if (!isset($all) && isset($_SESSION["{$SPRE}all"]) && !isset($filter) && !isset($fval)) {
        $all = $_SESSION["{$SPRE}all"];
    }
    if (isset($filter) && isset($fval) && !isset($all)) {
        if (strlen($filter) > 0) {
            if ($filter == "all") {
                $sqlfilter = " AND (lower(accno) LIKE lower('%{$fval}%') OR lower(surname) LIKE lower('%{$fval}%') OR lower(paddr1) LIKE lower('%{$fval}%') OR lower(addr1) LIKE lower('%{$fval}%') OR lower(del_addr1) LIKE lower('%{$fval}%') OR lower(bustel) LIKE lower('%{$fval}%') OR lower(email) LIKE lower('%{$fval}%') OR lower(vatnum) LIKE lower('%{$fval}%') OR lower(contname) LIKE lower('%{$fval}%') OR lower(tel) LIKE lower('%{$fval}%') OR lower(cellno) LIKE lower('%{$fval}%') OR lower(fax) LIKE lower('%{$fval}%') OR lower(url) LIKE lower('%{$fval}%') OR lower(comments) LIKE lower('%{$fval}%') OR lower(bankname) LIKE lower('%{$fval}%') OR lower(branname) LIKE lower('%{$fval}%') OR lower(brancode) LIKE lower('%{$fval}%') OR lower(bankaccno) LIKE lower('%{$fval}%') OR lower(bankaccname) LIKE lower('%{$fval}%') OR lower(bankacctype) LIKE lower('%{$fval}%'))";
            } else {
                $sqlfilter = " AND lower({$filter}) LIKE lower('%{$fval}%')";
            }
        } else {
            $sqlfilter = "";
        }
        if (isset($_SESSION["{$SPRE}all"])) {
            unset($_SESSION["{$SPRE}all"]);
        }
        $_SESSION["{$SPRE}fval"] = $fval;
        $_SESSION["{$SPRE}filter"] = $filter;
    } else {
        if (isset($_SESSION["{$SPRE}fval"])) {
            unset($_SESSION["{$SPRE}fval"]);
        }
        if (isset($_SESSION["{$SPRE}filter"])) {
            unset($_SESSION["{$SPRE}filter"]);
        }
        $filter = "";
        $fval = "";
        $_SESSION["{$SPRE}all"] = "true";
        $sqlfilter = "";
    }
    $filterarr = array("all" => "Detailed", "surname" => "Company/Name", "init" => "Initials", "accno" => "Account Number", "deptname" => "Department", "category" => "Category", "class" => "Classification");
    $filtersel = extlib_cpsel("filter", $filterarr, $filter, "onChange='applyFilter();'");
    if (isset($export)) {
        $pure = true;
    } else {
        $pure = false;
    }
    if (!$pure) {
        # Set up table to display in
        $printCust_begin = "\n\t    <h3>" . (isset($findcust) ? "Find" : "Current") . " Customers</h3>\n\t\t<table " . TMPL_tblDflts . ">\n\t\t<input type='hidden' name='action' value='{$action}' />\n\t\t<tr>\n\t\t\t<th>.: Filter :.</th>\n\t\t\t<th colspan='2'>.: Search :.</th>\n\t\t</tr>\n\t\t<tr class='" . bg_class() . "'>\n\t\t\t<td>{$filtersel}</td>\n\t\t\t<td><input type='text' size='20' id='fval' value='{$fval}'></td>\n\t\t\t<td align='center'><input type='button' value='Search' onClick='applyFilter();' /></td>\n\t\t</tr>\n\t\t<tr class='" . bg_class() . "'>\n\t\t\t<td align='center'><input type='button' name='all' value='View All' onClick='viewAll();' /></td>\n\t\t</tr>\n\t\t</table>\n\t\t<script>\n\t\t\t/* CRM CODE */\n\t\t\tfunction updateAccountInfo(id, name) {\n\t\t\t\twindow.opener.document.frm_con.accountname.value=name;\n\t\t\t\twindow.opener.document.frm_con.account_id.value=id;\n\t\t\t\twindow.opener.document.frm_con.account_type.value='Customer';\n\t\t\t\twindow.close();\n\t\t\t}\n\n\t\t\t/* AJAX filter code */\n\t\t\tfunction viewAll() {\n\t\t\t\tajaxRequest('" . SELF . "', 'cust_list', AJAX_SET, 'all=t');\n\t\t\t}\n\n\t\t\tfunction applyFilter() {\n\t\t\t\tfilter = getObject('filter').value;\n\t\t\t\tfval = getObject('fval').value;\n\n\t\t\t\tajaxRequest('" . SELF . "', 'cust_list', AJAX_SET, 'filter=' + filter + '&fval=' + fval);\n\t\t\t}\n\n\t\t\tfunction updateOffset(noffset, viewall) {\n\t\t\t\tif (viewall && !noffset) {\n\t\t\t\t\tajaxRequest('" . SELF . "', 'cust_list', AJAX_SET, 'viewall_cust=t');\n\t\t\t\t} else {\n\t\t\t\t\tajaxRequest('" . SELF . "', 'cust_list', AJAX_SET, 'offset=' + noffset);\n\t\t\t\t}\n\t\t\t}\n\t\t</script>\n\t\t<p>\n\t\t<div id='cust_list'>";
    } else {
        $printCust_begin = "";
    }
    /* FIND CUSTOMER START */
    if (!isset($findcust)) {
        $ajaxCust = "";
        if (!$pure) {
            $ajaxCust .= "\n\t\t<form action='statements-email.php' method='get'>\n\t\t<input type='hidden' name='key' value='confirm' />";
        }
        if (!isset($offset) && isset($_SESSION["{$SPRE}offset"])) {
            $offset = $_SESSION["{$SPRE}offset"];
        } else {
            if (!isset($offset)) {
                $offset = 0;
            }
        }
        $_SESSION["{$SPRE}offset"] = $offset;
        # connect to database
        db_connect();
        # counting the number of possible entries
        $sql = "SELECT * FROM customers\n    \t\tWHERE (div = '" . USER_DIV . "' OR  ddiv = '" . USER_DIV . "') {$sqlfilter}\n    \t\tORDER BY surname ASC";
        $rslt = db_exec($sql) or errDie("Error counting matching customers.");
        $custcount = pg_num_rows($rslt);
        # Query server
        $tot = 0;
        $totoverd = 0;
        $i = 0;
        if (!isset($ajaxCust)) {
            $ajaxCust = "";
        }
        /* view offsets */
        if ($offset > 0) {
            $poffset = $offset >= ACT_SHOW_LIMIT ? $offset - ACT_SHOW_LIMIT : 0;
            $os_prev = "<a class='nav' href='javascript: updateOffset(\"{$poffset}\");'>Previous</a>";
        } else {
            $os_prev = "&nbsp;";
        }
        if ($offset + ACT_SHOW_LIMIT > $custcount) {
            $os_next = "&nbsp;";
        } else {
            $noffset = $offset + ACT_SHOW_LIMIT;
            $os_next = "<a class='nav' href='javascript: updateOffset(\"{$noffset}\");'>Next</a>";
        }
        if ($os_next != "&nbsp;" || $os_prev != "&nbsp;") {
            $os_viewall = "| <a class='nav' href='javascript: updateOffset(false, true);'>View All</a>";
        } else {
            $os_viewall = "";
        }
        $ajaxCust .= "\n\t<table " . TMPL_tblDflts . ">\n\t<tr>\n\t\t<td colspan='20'>\n\t\t<table width='100%' border='0'>\n\t\t<tr>\n\t\t\t<td align='right' width='50%'>{$os_prev}</td>\n\t\t\t<td align='left' width='50%'>{$os_next} {$os_viewall}</td>\n\t\t</tr>\n\t\t</table>\n\t\t</td>\n\t</tr>\n\t<tr>\n\t\t<th>Acc no.</th>\n\t\t<th>Company/Name</th>\n\t\t<th>Tel</th>\n\t\t<th>Category</th>\n\t\t<th>Class</th>\n\t\t<th colspan='2'>Balance</th>\n\t\t<th>Overdue</th>\n\t\t" . ($pure ? "" : "<th colspan='11'>Options</th>") . "\n\t</tr>";
        /* query object for cashbook */
        $cashbook = new dbSelect("cashbook", "cubit");
        $custRslt = new dbSelect("customers", "cubit", grp(m("where", "(div ='" . USER_DIV . "' or ddiv='" . USER_DIV . "') {$sqlfilter}"), m("order", "surname ASC"), m("offset", $offset), m("limit", ACT_SHOW_LIMIT)));
        $custRslt->run();
        if ($custRslt->num_rows() < 1) {
            $ajaxCust .= "\n\t\t<tr class='" . bg_class() . "'>\n\t\t\t<td colspan='20'><li>There are no Customers matching the criteria entered.</li></td>\n\t\t</tr>";
        } else {
            while ($cust = $custRslt->fetch_array()) {
                if (!user_in_team($cust["team_id"], USER_ID)) {
                    continue;
                }
                # Check type of age analisys
                if (div_isset("DEBT_AGE", "mon")) {
                    $overd = ageage($cust['cusnum'], $cust['overdue'] / 30 - 1, $cust['location']);
                } else {
                    $overd = age($cust['cusnum'], $cust['overdue'] - 1, $cust['location']);
                }
                if ($overd < 0) {
                    $overd = 0;
                }
                if ($overd > $cust['balance']) {
                    $overd = $cust['balance'];
                }
                if ($cust["location"] == "int") {
                    $cur = qryCurrency($cust["fcid"], "rate");
                    $rate = $cur["rate"];
                    if ($rate != 0) {
                        $totoverd += $overd * $rate;
                    } else {
                        $totoverd += $overd;
                    }
                } else {
                    $totoverd += $overd;
                }
                if (!$pure) {
                    /* check if customer may be removed */
                    $cashbook->setOpt(grp(m("where", "cusnum='{$cust['cusnum']}' AND banked='no' AND div='" . USER_DIV . "'")));
                    $cashbook->run();
                    if ($cashbook->num_rows() <= 0 && $cust['balance'] == 0) {
                        $rm = "<td><a href='cust-rem.php?cusnum={$cust['cusnum']}'>Remove</a></td>";
                    } else {
                        $rm = "<td></td>";
                    }
                }
                if (strlen(trim($cust['bustel'])) < 1) {
                    $cust['bustel'] = $cust['tel'];
                }
                $cust['balance'] = sprint($cust['balance']);
                if ($cust["location"] == "int") {
                    if ($rate != 0.0) {
                        $tot = $tot + $cust['fbalance'] * $rate;
                    } else {
                        $tot = $tot + $cust['balance'];
                    }
                } else {
                    $tot = $tot + $cust['balance'];
                }
                /* determine which template to use when printing customer invoices */
                if (templateScript("invoices") != "pdf/cust-pdf-print-invoices.php") {
                    $template = "pdf/pdf-tax-invoice.php?type=cusprintinvoices";
                } else {
                    $template = "pdf/pdf-tax-invoice.php?type=cusprintinvoices";
                }
                $inv = "";
                $inv = "\n\t\t\t<td>\n\t\t\t\t<a href='{$template}&cusnum={$cust['cusnum']}' target='_blank'>Print Invoices</a>\n\t\t\t</td>";
                # Locations drop down
                $locs = array("loc" => "Local", "int" => "International", "" => "");
                $loc = $locs[$cust['location']];
                $fbal = "--";
                $ocurr = CUR;
                $trans = "\n\t\t\t<td>\n\t\t\t\t<a href='core/cust-trans.php?cusnum={$cust['cusnum']}'>Transaction</a>\n\t\t\t</td>";
                if ($cust['location'] == 'int') {
                    $fbal = "{$cust['currency']} {$cust['fbalance']}";
                    $ocurr = CUR;
                    $trans = "\n\t\t\t\t<td>\n\t\t\t\t\t<a href='core/intcust-trans.php?cusnum={$cust['cusnum']}'>Transaction</a>\n\t\t\t\t</td>";
                    $receipt = "<a href='bank/bank-recpt-inv-int.php?cusid={$cust['cusnum']}&amp;cash=yes'>Add Receipt</a>";
                } else {
                    $receipt = "<a href='bank/bank-recpt-inv.php?cusnum={$cust['cusnum']}&amp;cash=yes'>Add Receipt</a>";
                }
                # alternate bgcolor
                $bgColor = bgcolor($i);
                $ajaxCust .= "<tr class='" . bg_class() . "'>";
                if ($action == "contact_acc") {
                    $updatelink = "javascript: updateAccountInfo(\"{$cust['cusnum']}\", \"{$cust['accno']}\");";
                    $ajaxCust .= "\n\t\t\t\t\t<td><a href='{$updatelink}'>{$cust['accno']}</a></td>\n\t\t\t\t\t<td><a href='{$updatelink}'>{$cust['surname']}</a></td>";
                } else {
                    if ($action == "select") {
                        $ajaxCust .= "\n\t\t\t\t\t<td><a href='" . SELF . "?key=select&cusnum={$cust['cusnum']}&" . frmupdate_passon(true) . "'>{$cust['accno']}</a></td>\n\t\t\t\t\t<td><a href='" . SELF . "?key=select&cusnum={$cust['cusnum']}&" . frmupdate_passon(true) . "'>{$cust['surname']}</a></td>";
                    } else {
                        $ajaxCust .= "\n\t\t\t\t\t<td>{$cust['accno']}</td>\n\t\t\t\t\t<td>{$cust['surname']}</td>";
                    }
                }
                $ajaxCust .= "\n\t\t\t\t\t<td>{$cust['bustel']}</td>\n\t\t\t\t\t<td>{$cust['catname']}</td>\n\t\t\t\t\t<td>{$cust['classname']}</td>\n\t\t\t\t\t<td align='right' nowrap>{$ocurr} {$cust['balance']}</td>\n\t\t\t\t\t<td align='center' nowrap>{$fbal}</td>\n\t\t\t\t\t<td align='right' nowrap>{$ocurr} {$overd}</td>";
                if (!$pure) {
                    if ($action == "listcust") {
                        $ajaxCust .= "\n\t\t\t\t\t\t<td>{$receipt}</td>\n\t\t\t\t\t\t<td><a href='delnote-report.php?cusnum={$cust['cusnum']}'>Outstanding Stock</a></td>\n\t\t\t\t\t\t<td><a href='cust-det.php?cusnum={$cust['cusnum']}'>Details</a></td>\n\t\t\t\t\t\t<td><a href='customers-new.php?cusnum={$cust['cusnum']}'>Edit</a></td>\n\t\t\t\t\t\t<td><a href='#' onClick='openPrintWin(\"cust-stmnt.php?cusnum={$cust['cusnum']}\");'>Statement</a></td>\n\t\t\t\t\t\t{$trans} {$inv}";
                        if ($cust['blocked'] == 'yes') {
                            $ajaxCust .= "<td><a href='cust-unblock.php?cusnum={$cust['cusnum']}'>Unblock</a></td>";
                        } else {
                            $ajaxCust .= "<td><a href='cust-block.php?cusnum={$cust['cusnum']}'>Block</a></td>";
                        }
                        $ajaxCust .= "<td><a href='transheks/pricelist_send.php?cusnum={$cust['cusnum']}'>Send Pricelist</a></td>";
                        $ajaxCust .= "{$rm} <td><a href='conper-add.php?type=cust&amp;id={$cust['cusnum']}'>Add Contact</a></td>\n\t\t\t\t\t<td><input type='checkbox' name='cids[]' value='{$cust['cusnum']}' /></td>";
                    } else {
                        $ajaxCust .= "\n\t\t\t\t\t\t<td align=center>\n\t\t\t\t\t\t\t<a href='javascript: popupSized(\"cust-det.php?cusnum={$cust['cusnum']}\", \"custdetails\", 550, 400, \"\");'>Details</a>\n\t\t\t\t\t\t</td>";
                    }
                }
                $ajaxCust .= "</tr>";
            }
            $bgColor = bgcolor($i);
            $tot = sprint($tot);
            $totoverd = sprint($totoverd);
            $i--;
            $ajaxCust .= "\n\t\t<tr class='" . bg_class() . "'>\n\t\t\t<td colspan='5'>Total Amount Outstanding, from {$i} " . ($i > 1 ? "clients" : "client") . "</td>\n\t\t\t<td align='right' nowrap>" . CUR . " {$tot}</td>\n\t\t\t<td></td>\n\t\t\t<td align='right' nowrap>" . CUR . " {$totoverd}</td>\n\t\t\t" . ($pure ? "" : "<td colspan='11' align='right'><input type='submit' value='Email Statements' /></td>") . "\n\t\t</tr>";
            if (!$pure) {
                $ajaxCust .= "\n\t\t\t<tr>\n\t\t\t\t<td colspan='20'>\n\t\t\t\t<table width='100%' border='0'>\n\t\t\t\t<tr>\n\t\t\t\t\t<td align='right' width='50%'>{$os_prev}</td>\n\t\t\t\t\t<td align='left' width='50%'>{$os_next} {$os_viewall}</td>\n\t\t\t\t</tr>\n\t\t\t\t</table>\n\t\t\t\t</td>\n\t\t\t</tr>";
            }
        }
        if ($pure) {
            $ajaxCust .= "</table>";
        } else {
            $ajaxCust .= "\n\t\t" . TBL_BR . "\n\t\t</table>\n\t\t</form>\n\t\t<form action='" . SELF . "' method='post'>\n\t\t<table>\n\t\t\t<input type='hidden' name='export' value='yes' />\n\t\t\t<input type='hidden' name='filter' value='{$filter}' />\n\t\t\t<input type='hidden' name='fval' value='{$fval}' />\n\t\t\t<tr>\n\t\t\t\t<td colspan='3'><input type='submit' value='Export to Spreadsheet' /></td>\n\t\t\t</tr>\n\t\t</table>\n\t\t</form>";
        }
        /* FIND CUSTOMER END */
    } else {
        $ajaxCust = "";
    }
    $printCust_end = "\n\t</div>";
    if (!$pure) {
        $printCust_end .= mkQuickLinks(ql("customers-new.php", "Add New Customer"));
    }
    if (AJAX) {
        return $ajaxCust;
    } else {
        return "{$printCust_begin}{$ajaxCust}{$printCust_end}";
    }
}
function write($_POST)
{
    # get vars
    foreach ($_POST as $key => $value) {
        ${$key} = $value;
    }
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($catcod, "string", 0, 50, "Invalid category code.");
    $v->isOk($cat, "string", 1, 255, "Invalid stock category name.");
    $v->isOk($descript, "string", 0, 100, "Invalid stock category descripting.");
    # Display errors, if any
    if ($v->isError()) {
        $confirm = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $confirm .= "<li class=err>{$e['msg']}</li>";
        }
        $confirm .= "</li><p><input type=button onClick='JavaScript:history.back();' value='&laquo; Correct submission'>\n\t\t\t\t<P>\n\t\t\t\t<table border=0 cellpadding='" . TMPL_tblCellPadding . "' cellspacing='" . TMPL_tblCellSpacing . "' width=100>\n\t\t\t\t<tr><th>Quick Links</th></tr>\n\t\t\t\t\t<tr class='bg-even'><td><a href='stockcat-view.php'>View Stock Category</a></td></tr>\n\t\t\t\t\t<script>document.write(getQuicklinkSpecial());</script>\n\t\t\t\t</form>\n\t\t\t\t</table>";
        return $confirm;
    }
    # check stock code
    db_connect();
    $sql = "SELECT catcod FROM stockcat WHERE lower(catcod) = lower('{$catcod}') AND div = '" . USER_DIV . "'";
    $cRslt = db_exec($sql);
    if (pg_numrows($cRslt) > 0) {
        $error = "<li class=err> A Category with code : <b>{$catcod}</b> already exists.</li>";
        $error .= "<p><input type=button onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        //return $error;
    }
    // insert into stock
    db_connect();
    $sql = "INSERT INTO stockcat(catcod, cat, descript, div) VALUES('{$catcod}', '{$cat}', '{$descript}', '" . USER_DIV . "')";
    $rslt = db_exec($sql) or errDie("Unable to insert stock category to Cubit.", SELF);
    if (frmupdate_passon()) {
        $newlst = new dbSelect("stockcat", "cubit", grp(m("cols", "catid, catcod, cat"), m("where", "div='" . USER_DIV . "'"), m("order", "cat ASC")));
        $newlst->run();
        $a = array();
        if ($newlst->num_rows() > 0) {
            while ($row = $newlst->fetch_array()) {
                $a[$row["catid"]] = "({$row['catcod']}) {$row['cat']}";
            }
        }
        $js = frmupdate_exec(array($a), true);
    } else {
        $js = "";
    }
    $write = "\n\t{$js}\n\t<table border=0 cellpadding='" . TMPL_tblCellPadding . "' cellspacing='" . TMPL_tblCellSpacing . "' width='50%'>\n\t\t<tr><th>New Stock Category added to database</th></tr>\n\t\t<tr class=datacell><td>New Stock Category, {$cat} ({$catcod}) has been successfully added to Cubit.</td></tr>\n\t</table>\n\t<p>\n\t<table border=0 cellpadding='2' cellspacing='1'>\n\t\t<tr><th>Quick Links</th></tr>\n\t\t<tr class='bg-even'><td><a href='stockcat-view.php'>View Stock Category</a></td></tr>\n\t\t<script>document.write(getQuicklinkSpecial());</script>\n\t</table>";
    return $write;
}
function process($_POST, $err = "")
{
    global $PRDMON;
    extract($_POST);
    # validate input
    require_lib("validate");
    $v = new validate();
    $proc_date = mkdate($proc_year, $proc_month, $proc_day);
    $v->isOk($empnum, "num", 1, 20, "Invalid employee number.");
    $v->isOk($MON, "num", 1, 2, "Invalid month.");
    $v->isOk($proc_date, "date", 1, 1, "Invalid date selected.");
    $salyr = getYearOfEmpMon($MON);
    $curyr = getActiveFinYear();
    if ($salyr > $curyr || $salyr == $curyr && $MON > $PRDMON[12]) {
        $v->addError("", "Cannot do transaction in future financial year. You need\n\t\t\tto close your year first before you can continue.");
    }
    # display errors, if any
    if ($v->isError()) {
        return slctEmployee($v->genErrors());
        return $confirmCust;
    }
    # CHECK IF THIS DATE IS IN THE BLOCKED RANGE
    $blocked_date_from = getCSetting("BLOCKED_FROM");
    $blocked_date_to = getCSetting("BLOCKED_TO");
    if (strtotime($proc_date) >= strtotime($blocked_date_from) and strtotime($proc_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>";
    }
    // first check if all the selected employees with EFT pay types have banking information
    // and their id numbers are valid
    $emp_err = array();
    $emp_nam = array();
    /* previously selected to remove this employee from process */
    if (isset($rememp[$empnum])) {
        unset($emps[$empnum]);
        continue;
    }
    db_connect();
    $sql = "\n\t\t\tSELECT fnames, sname, paytype, bankname, bankaccno, idnum, flag, hiredate, payprd \n\t\t\tFROM employees \n\t\t\tWHERE div='" . USER_DIV . "' AND empnum='{$empnum}'";
    $rslt = db_exec($sql) or errDie("error checking employee payment types.");
    $e_info = pg_fetch_array($rslt);
    /* if the employee's pay period doesn't match the selected button, don't
    			include employee in checklist */
    if (isset($d) && $e_info["payprd"] != "d") {
        continue;
    } else {
        if (isset($w) && $e_info["payprd"] != "w") {
            continue;
        } else {
            if (isset($b) && $e_info["payprd"] != "f") {
                continue;
            } else {
                if (isset($m) && $e_info["payprd"] != "m") {
                    continue;
                }
            }
        }
    }
    $empnum += 0;
    $emp_err[$empnum] = 0;
    $emp_nam[$empnum] = "{$e_info['fnames']} {$e_info['sname']}";
    if ($e_info["paytype"] == "EFT" && (empty($e_info["bankname"]) || empty($e_info["bankaccno"]))) {
        $emp_err[$empnum] |= 0x1;
    }
    if (!empty($e_info["idnum"])) {
        $bd_year = substr($e_info["idnum"], 0, 2);
        $bd_month = substr($e_info["idnum"], 2, 2);
        $bd_day = substr($e_info["idnum"], 4, 2);
        if (!checkdate($bd_month, $bd_day, $bd_year)) {
            $emp_err[$empnum] |= 0x2;
        }
    }
    if ($e_info["flag"] == "2.5EMP") {
        $emp_err[$empnum] |= 0x4;
        $special_error = 0x1;
    }
    if ($e_info["flag"] == "272PREVEMP") {
        $emp_err[$empnum] |= 0x4;
        $special_error = 0x2;
    }
    /* check hiredate after process date */
    explodeDate($e_info["hiredate"], $hd_year, $hd_month, $hd_day);
    $MONempyear = getYearOfEmpMon($MON);
    if ($hd_year > $MONempyear || $hd_year == $MONempyear && $hd_month > $MON) {
        $emp_err[$empnum] |= 0x8;
    }
    // list the employee information problems
    if (array_sum($emp_err) > 0) {
        $out = "<h3>Process Salaries</h3>\n\t\t\t<form method='POST' action='" . SELF . "'>";
        foreach ($_POST as $key => $value) {
            if (is_array($value)) {
                foreach ($value as $akey => $avalue) {
                    $out .= "<input type='hidden' name='{$key}" . "[{$akey}]' value='{$avalue}'>";
                }
            } else {
                $out .= "<input type='hidden' name='{$key}' value='{$value}'>";
            }
        }
        if (isset($special_error)) {
            switch ($special_error) {
                case 0x1:
                    $out .= "\n\t\t\t\t\t<li class='err'><strong>NOTICE:</strong> Due to changes in employee functionality from Cubit 2.5 to Cubit 2.6 <br>\n\t\t\t\t\t\tyou need to edit your employees' salary/deduction/allowance information</li>\n\t\t\t\t\t\t<br />";
                    break;
                case 0x2:
                    $out .= "\n\t\t\t\t\t<li class='err'><strong>NOTICE:</strong> Due to the changes from Cubit 2.71 to Cubit 2.72 you should first update your employee's\n\t\t\t\t\t\tprevious employment information in the employee edit form.</li>\n\t\t\t\t\t\t<br />";
                    break;
            }
        }
        $out .= "\n\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t<tr>\n\t\t\t\t\t<td colspan='3' class='err'>There are problems with the employee.<br />\n\t\t\t\t\t\tPlease edit the information first.<br /><br />\n\t\t\t\t\t\tClick the 'Done' button when ready to proceed.</td>\n\t\t\t\t</tr>";
        $out .= "\n\t\t\t<tr>\n\t\t\t\t<th>Name</th>\n\t\t\t\t<th>Message</th>\n\t\t\t</tr>";
        $i = 0;
        foreach ($emp_err as $e_empnum => $err_val) {
            $out .= "\n\t\t\t\t<tr bgcolor='" . bgcolor($i) . "'>\n\t\t\t\t\t<h1></h1>\n\t\t\t\t\t<th>{$emp_nam[$e_empnum]}</td>";
            if ($err_val & 0x4) {
                $specerr_msg = "(See above notice for this employee)";
            } else {
                $specerr_msg = "";
            }
            if ($err_val & 0x1 && $err_val & 0x2) {
                $out .= "<td class='err'>Banking info and ID number {$specerr_msg}</td>";
            } else {
                if ($err_val & 0x1) {
                    $out .= "<td class='err'>Banking info {$specerr_msg}</td>";
                } else {
                    if ($err_val & 0x2) {
                        $out .= "<td class='err'>ID number {$specerr_msg}</td>";
                    } else {
                        if ($err_val & 0x8) {
                            $out .= "<td class='err'>Employee was not employed in the period requested {$specerr_msg}</td>";
                        } else {
                            $out .= "<td>Employee Info Correct {$specerr_msg}</td>";
                        }
                    }
                }
            }
            if ($err_val && !($err_val == 0x8)) {
                $out .= "<td class='err'><a target='_blank' href='../admin-employee-edit.php?empnum={$e_empnum}'>Edit Employee</a></td>";
            }
            $out .= "\n\t\t\t</tr>";
        }
        $out .= "\n\t\t\t\t<tr>\n\t\t\t\t\t<td colspan='3' align='right'><input type='submit' value='Done' /></td>\n\t\t\t\t</tr>\n\t\t\t</table>\n\t\t\t</form>";
        return $out;
    }
    # Get employee details
    db_conn('cubit');
    $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 ($myEmp["flag"] == "2.5EMP") {
        $OUTPUT = "\n\t\t\t<h3>Process Employee Salary</h3>\n\t\t\t<li class='err'>\n\t\t\t\tDue to the changes from Cubit 2.5 to Cubit 2.6.1 you should first update your employee's\n\t\t\t\tsalary/deduction/allowance information in the employee edit form.\n\t\t\t\tClick <a href='../admin-employee-edit.php?empnum={$empnum}'>here</a> to do so.\n\t\t\t</li>";
        return $OUTPUT;
    }
    if (!empty($idnum)) {
        $bd_year = substr($myEmp["idnum"], 0, 2);
        $bd_month = substr($myEmp["idnum"], 2, 2);
        $bd_day = substr($myEmp["idnum"], 4, 2);
        if (!checkdate($bd_month, $bd_day, $bd_year)) {
            $OUTPUT = "\n\t\t\t<h3>Process Employee Salary</h3>\n\t\t\t<li class='err'>\n\t\t\t\tSelected employee does not have a valid id number and therefore his age cannot be\n\t\t\t\tcalculated.<br>\n\t\t\t\tPlease update this information in the employee <a href='../admin-employee-edit.php?empnum={$empnum}'>edit</a> form.\n\t\t\t</li>";
            return $OUTPUT;
        }
    }
    /* check for flag notices */
    if ($myEmp["flag"] == "272PREVEMP") {
        $OUTPUT = "\n\t\t<h3>Process Employee Salary</h3>\n\t\t<li class='err'>\n\t\t\tDue to the changes from Cubit 2.71 to Cubit 2.72 you should first update your employee's\n\t\t\tprevious employment information in the employee edit form.\n\t\t\tClick <a href='../admin-employee-edit.php?empnum={$empnum}'>here</a> to do so.\n\t\t</li>";
    }
    /* check if hiredate after process date */
    explodeDate($myEmp["hiredate"], $hd_year, $hd_month, $hd_day);
    if ($hd_year > getYearOfEmpMon($MON) || $hd_year == getYearOfEmpMon($MON) && $hd_month > $MON) {
        return slctEmployee("<li class='err'>Employee was not employed in the period\n\t\t\trequested.</li>");
    }
    if ($myEmp["paytype"] == "EFT" && (empty($myEmp["bankname"]) || empty($myEmp["bankaccno"]))) {
        return "Employee banking information not entered.<br>\n\t\t\tClick <a href='../admin-employee-edit.php?empnum={$empnum}'>here</a> employee banking information.";
    }
    $grossal = $myEmp["basic_sal"] + $myEmp["commission"] + $myEmp["bonus"];
    $yy = date("Y");
    $mm = $MON;
    $mm += 0;
    if ($myEmp['payprd'] == "m") {
        $Sl = "SELECT * FROM salpaid WHERE empnum='{$empnum}' AND month='{$mm}' AND cyear='" . EMP_YEAR . "'";
        $Ri = db_exec($Sl);
        $paid = pg_num_rows($Ri);
        $Sl = "SELECT * FROM salr WHERE empnum='{$empnum}' AND month='{$mm}' AND cyear='" . EMP_YEAR . "'";
        $Ri = db_exec($Sl);
        $upaid = pg_num_rows($Ri);
        $upaid += 0;
        $paid -= $upaid;
    }
    if (isset($paid) && $paid > 0) {
        return slctEmployee("<li class='err'>You have already processed a salary for that period.</li>");
    }
    /* calculate basic salary divisors and multipliers
     * used for calculating deductions/allowances/etc. when the
     * salary type and payment period differs in length
     */
    switch ($myEmp["saltyp"]) {
        case "h":
            $divisor = 1;
            switch ($myEmp["payprd"]) {
                case "d":
                    $multiplier = $myEmp["hpweek"] / 5;
                    break;
                case "w":
                    $multiplier = $myEmp["hpweek"];
                    break;
                case "f":
                    $multiplier = $myEmp["hpweek"] * 2;
                    break;
                case "m":
                    $multiplier = $myEmp["hpweek"] * 52 / 12;
                    break;
            }
            break;
        case "m":
            $divisor = 1;
            switch ($myEmp["payprd"]) {
                case "d":
                    $multiplier = 12 / (5 * 52);
                    break;
                case "w":
                    $multiplier = 12 / 52;
                    break;
                case "f":
                    $multiplier = 12 / 26;
                    break;
                case "m":
                    $multiplier = 1;
                    break;
            }
            break;
        case "w":
            $divisor = 52 / 12;
            switch ($myEmp["payprd"]) {
                case "d":
                    $multiplier = 1 / 5;
                    break;
                case "w":
                    $multiplier = 1;
                    break;
                case "f":
                    $multiplier = 2;
                    break;
                case "m":
                    $multiplier = 52 / 12;
                    break;
            }
            break;
        case "f":
            $divisor = 26 / 12;
            switch ($myEmp["payprd"]) {
                case "d":
                    $multiplier = 1 / 10;
                    break;
                case "w":
                    $multiplier = 1 / 2;
                    break;
                case "f":
                    $multiplier = 1;
                    break;
                case "m":
                    $multiplier = 26 / 12;
                    break;
            }
            break;
    }
    # fringe benefits
    $fringes = "";
    $i = 0;
    $sql = "SELECT * FROM fringebens WHERE div = '" . USER_DIV . "' ORDER BY fringeben";
    $rslt = db_exec($sql) or errDie("Unable to select allowances from database.");
    if (pg_num_rows($rslt) < 1) {
        $fringes = "<tr><td class='" . bg_class() . "' colspan='2' align='center'>None found in database.</td></tr>\n";
    } else {
        while ($myFringe = pg_fetch_array($rslt)) {
            # check if employee has allowance
            $sql = "SELECT * FROM empfringe WHERE fringeid='{$myFringe['id']}' AND empnum='{$myEmp['empnum']}' AND div = '" . USER_DIV . "'";
            $empRslt = db_exec($sql) or errDie("Unable to retrieve fringe benefit info from database.");
            if (pg_numrows($empRslt) > 0) {
                $empFringe = pg_fetch_array($empRslt);
                if (substr($empFringe["type"], 0, 4) == "Perc") {
                    $empFringe["amount"] = sprint($myEmp["basic_sal"] * ($empFringe["amount"] / 100) / $divisor);
                } else {
                    $empFringe['amount'] = sprint($empFringe['amount'] / $divisor);
                }
                $grossal += $empFringe["amount"];
                $tmp_fringeaccs = $empFringe["accid"];
                $tmp_fringebens = $empFringe["amount"];
            } else {
                $tmp_fringeaccs = "0";
                $tmp_fringebens = "0.00";
            }
            $fringes .= "\n\t\t\t<input type='hidden' name='fringeid[]' value='{$myFringe['id']}'>\n\t\t\t<input type='hidden' name='fringename[]' value='{$myFringe['fringeben']}'>\n\t\t\t<input type='hidden' name='fringeaccs[]' value='{$tmp_fringeaccs}'>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>{$myFringe['fringeben']}</td>\n\t\t\t\t<td align='center'>" . CUR . "<input type='text' size='10' name='fringebens[]' value='{$tmp_fringebens}'></td>\n\t\t\t</tr>";
            $i++;
        }
    }
    # get allowances
    $allowances = "";
    $i = 0;
    $sql = "SELECT * FROM allowances WHERE div = '" . USER_DIV . "' ORDER BY allowance";
    $allowRslt = db_exec($sql) or errDie("Unable to select allowances from database.");
    if (pg_numrows($allowRslt) < 1) {
        $allowances = "<tr><td class='" . bg_class() . "' colspan='2' align='center'>None found in database.</td></tr>\n";
    } else {
        while ($myAllow = pg_fetch_array($allowRslt)) {
            # check if employee has allowance
            $sql = "SELECT * FROM empallow WHERE allowid='{$myAllow['id']}' AND empnum='{$myEmp['empnum']}' AND div = '" . USER_DIV . "'";
            $empAllowRslt = db_exec($sql) or errDie("Unable to select allowance info from database.");
            if (pg_numrows($empAllowRslt) > 0) {
                $myEmpAllow = pg_fetch_array($empAllowRslt);
                if (substr($myEmpAllow["type"], 0, 4) == "Perc") {
                    $myEmpAllow["amount"] = sprint($myEmp["basic_sal"] * ($myEmpAllow["amount"] / 100) / $divisor);
                } else {
                    $myEmpAllow['amount'] = sprint($myEmpAllow['amount'] / $divisor);
                }
                $grossal += $myEmpAllow["amount"];
                $tmp_allowaccs = $myEmpAllow["accid"];
                $tmp_allowances = $myEmpAllow["amount"];
            } else {
                $tmp_allowaccs = $myAllow["accid"];
                $tmp_allowances = "0.00";
            }
            $allowances .= "\n\t\t\t<input type='hidden' size='10' name='allowid[]' value='{$myAllow['id']}'>\n\t\t\t<input type='hidden' size='30' name='allowname[]' value='{$myAllow['allowance']}'>\n\t\t\t<input type='hidden' size='10' name='allowtax[]' value='{$myAllow['add']}'>\n\t\t\t<input type='hidden' name='allowaccs[]' value='{$tmp_allowaccs}'>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>{$myAllow['allowance']}</td>\n\t\t\t\t<td align='center'>" . CUR . " <input type='text' size='10' name='allowances[]' value='{$tmp_allowances}'></td>\n\t\t\t</tr>";
            $i++;
        }
    }
    $subsistence = "";
    $subslst = new dbSelect("subsistence", "cubit", array("where" => "div='" . USER_DIV . "'", "order" => "name"));
    $subslst->run();
    $subs_int = false;
    if ($subslst->num_rows() > 0) {
        $i = 0;
        $subsistence .= "\n\t\t<tr><td colspan='10'>\n\t\t<table " . TMPL_tblDflts . ">\n\t\t<tr>\n\t\t\t<th>Name</th>\n\t\t\t<th>Amount</th>\n\t\t\t<th>Days</th>\n\t\t\t<th></th>\n\t\t</tr>";
        $empsubs = new dbSelect("emp_subsistence", "cubit");
        while ($subs = $subslst->fetch_array()) {
            $sid = $subs["id"];
            $empsubs->setOpt(array("where" => wgrp(m("empnum", $empnum), m("subid", $sid))));
            $empsubs->run();
            if ($empsubs->num_rows() <= 0) {
                $si["amount"] = "0.00";
                $si["days"] = "0";
                $si["accid"] = $subs["accid"];
            } else {
                $si = $empsubs->fetch_array();
            }
            if ($subs["in_republic"] != "yes") {
                $subs_int = true;
            }
            $subsistence .= "\n\t\t\t<input type='hidden' name='subsname[{$sid}]' value='{$subs['name']}'>\n\t\t\t<input type='hidden' name='subsacc[{$sid}]' value='{$si['accid']}'>\n\t\t\t<input type='hidden' name='subsrep[{$sid}]' value='{$subs['in_republic']}'>\n\t\t\t<input type='hidden' name='subsmeal[{$sid}]' value='{$subs['meals']}'>\n\t\t\t<tr bgcolor='" . bgcolor($i) . "'>\n\t\t\t\t<td>{$subs['name']}</td>\n\t\t\t\t<td>" . CUR . " <input type='text' name='subsamt[{$sid}]' value='{$si['amount']}'></td>\n\t\t\t\t<td><input type='text' name='subsdays[{$sid}]' value='{$si['days']}'></td>\n\t\t\t</tr>";
        }
        if ($subs_int) {
            $subsistence .= "\n\t\t\t\t<input type='hidden' name='subs_exch' value='1'>\n\t\t\t\t<tr>\n\t\t\t\t\t<td colspan='3'><li class='err'>Please calculate the rand amount prior to completing the amount above.</li></td>\n\t\t\t\t</tr>";
            // 			<tr bgcolor='".bgcolor($i)."'>
            // 				<td colspan='2'>Exchange (ZAR-USD):</td>
            // 				<td><input type='text' name='subs_exch' value='".xrate_get("USD")."'></td>
            // 			</tr>";
        }
        $subsistence .= "\n\t\t\t</table>\n\t\t\t</td></tr>";
    }
    # Deductions
    $deductions = "";
    $i = 0;
    $sql = "SELECT * FROM salded WHERE div = '" . USER_DIV . "' ORDER BY deduction";
    $deductRslt = db_exec($sql) or errDie("Unable to select deductions from database.");
    if (pg_numrows($deductRslt) < 1) {
        $deductions = "<tr><td class='" . bg_class() . "' colspan='2' align='center'>None found in database.</td></tr>\n";
    } else {
        while ($myDeduct = pg_fetch_array($deductRslt)) {
            # check if employee has deduction
            $sql = "SELECT * FROM empdeduct WHERE dedid='{$myDeduct['id']}' AND empnum='{$myEmp['empnum']}' AND div = '" . USER_DIV . "'";
            $empDeductRslt = db_exec($sql) or errDie("Unable to select Deduction info from database.");
            if (pg_numrows($empDeductRslt) > 0) {
                $myEmpDeduct = pg_fetch_array($empDeductRslt);
                if ($myEmpDeduct["grosdeduct"] == "y") {
                    $deductions_msg = "(Deducted from Gross Salary)";
                    $sal_calcfrom = $grossal;
                } else {
                    $deductions_msg = "";
                    $sal_calcfrom = $myEmp['basic_sal'];
                }
                if ($myEmpDeduct['type'] == "Amount") {
                    $myEmpDeduct['amount'] = sprint($myEmpDeduct['amount'] / $divisor);
                } else {
                    $myEmpDeduct['amount'] = sprint($sal_calcfrom * $myEmpDeduct['amount'] / 100 / $divisor);
                }
                // calculate employer contribution to deduction
                if ($myEmpDeduct["employer_type"] == "Amount") {
                    $myEmpDeduct["employer_amount"] = sprint($myEmpDeduct["employer_amount"] / $divisor);
                } else {
                    $myEmpDeduct["employer_amount"] = sprint($myEmpDeduct["amount"] * $myEmpDeduct["employer_amount"] / 100 / $divisor);
                }
                $tmp_deductions = $myEmpDeduct["amount"];
                $tmp_dedaccs = $myEmpDeduct["accid"];
                $tmp_emp_ded = $myEmpDeduct["employer_amount"];
                $tmp_grosdeduct = $myEmpDeduct["grosdeduct"];
            } else {
                $tmp_deductions = "0.00";
                $tmp_emp_ded = "0.00";
                $tmp_dedaccs = $myDeduct["accid"] != 0 ? $myDeduct["accid"] : $myDeduct["expaccid"];
                $tmp_grosdeduct = "n";
                $deductions_msg = "";
            }
            # check if we should be using deductions
            if ($myEmp['emp_usescales'] == "1" and $myDeduct['type'] == "Percentage") {
                # check if this deduction has scales
                $get_scales = "SELECT * FROM salded_scales WHERE saldedid = '{$myDeduct['id']}' LIMIT 1";
                $run_scales = db_exec($get_scales) or errDie("Unable to get deduction scale information.");
                if (pg_numrows($run_scales) > 0) {
                    # scales exist
                    $get_perc = "\n\t\t\t\t\t\tSELECT * FROM salded_scales \n\t\t\t\t\t\tWHERE scale_from <= '{$myEmp['basic_sal']}' AND scale_to >= '{$myEmp['basic_sal']}' AND saldedid = '{$myDeduct['id']}' \n\t\t\t\t\t\tLIMIT 1";
                    $run_perc = db_exec($get_perc) or errDie("Unable to get deduction scale information.");
                    if (pg_numrows($run_perc) > 0) {
                        # found a matching scale for this scaled duduction for a customer using scales ....
                        $scale_arr = pg_fetch_array($run_perc);
                        $tmp_deductions = sprint($myEmp['basic_sal'] / 100 * $scale_arr['scale_amount']);
                    }
                }
            }
            $deductions .= "\n\t\t\t\t<input type='hidden' size='10' name='employer_deductions[]' value='{$tmp_emp_ded}'>\n\t\t\t\t<input type='hidden' size='10' name='deducttax[]' value='{$myDeduct['add']}'>\n\t\t\t\t<input type='hidden' name='grosdeduct[]' value='{$tmp_grosdeduct}'>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>{$myDeduct['deduction']} {$deductions_msg}</td>\n\t\t\t\t\t<td align='center'>\n\t\t\t\t\t\t" . CUR . "<input type='hidden' size='10' name='deductid[]' value='{$myDeduct['id']}'>\n\t\t\t\t\t\t<input type='hidden' size='30' name='deductname[]' value='{$myDeduct['deduction']}'>\n\t\t\t\t\t\t<input type='text' size='10' name='deductions[]' value='{$tmp_deductions}'>\n\t\t\t\t\t\t<input type='hidden' name='dedaccs[]' value='{$tmp_dedaccs}'>\n\t\t\t\t\t</td>\n\t\t\t\t</tr>";
            $i++;
        }
    }
    $deductions .= "";
    $salarr = array("m" => "Per Month", "w" => "Per Week", "f" => "Fortnightly", "h" => "Per Hour");
    $salnarr = array("d" => "Day(s)", "h" => "Hour(s)");
    $saltype = $salarr[$myEmp['saltyp']];
    db_conn('cubit');
    $Sl = "SELECT * FROM bankacct WHERE btype != 'int' AND div = '" . USER_DIV . "' ORDER BY accname ASC";
    $Ry = db_exec($Sl) or errDie("Unable to get bank account.");
    if (pg_numrows($Ry) < 1) {
        return "<li class='err'> There are no bank accounts found in Cubit.\n\t\t<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct Selection'>";
    }
    $banks = "<select name='accid'>";
    while ($acc = pg_fetch_array($Ry)) {
        $banks .= "<option value='{$acc['bankid']}'>{$acc['accname']} ({$acc['acctype']})</option>";
    }
    $banks .= "</select>";
    $myEmp['loaninstall'] += 0;
    if ($myEmp['paytype'] == "Cash") {
        $paydetails = "\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td colspan='2'>Employee paid cash</td>\n\t\t\t</tr>\n\t\t\t<input type='hidden' name='accid' value='0'>";
    } elseif ($myEmp['paytype'] == "Ledger Account") {
        db_conn('core');
        $Sl = "SELECT accid,accname FROM accounts ORDER BY accname";
        $Ri = db_exec($Sl);
        $accounts = "<select name='account'>\n\t\t\t<option value='#'>Select Account</option>";
        while ($ad = pg_fetch_array($Ri)) {
            if (isset($account) && $account == $ad['accid']) {
                $sel = "selected";
            } else {
                $sel = "";
            }
            $accounts .= "<option value='{$ad['accid']}'>{$ad['accname']}</option>";
        }
        $accounts .= "</select>";
        $paydetails = "\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Ledger Account for payment</td>\n\t\t\t\t<td>{$accounts}</td>\n\t\t\t</tr>\n\t\t\t<input type='hidden' name='accid' value='0'>";
    } else {
        $paydetails = "\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Bank Account</td>\n\t\t\t\t<td valign='center'>{$banks}</td>\n\t\t\t</tr>";
    }
    $h1 = "";
    $h2 = "";
    $db = array("comp_pension" => $myEmp["comp_pension"], "emp_pension" => $myEmp["emp_pension"], "comp_provident" => $myEmp["comp_provident"], "emp_provident" => $myEmp["emp_provident"], "comp_uif" => $myEmp["comp_uif"], "emp_uif" => $myEmp["emp_uif"], "comp_other" => $myEmp["comp_other"], "emp_other" => $myEmp["emp_other"]);
    if (isset($basic_sal)) {
        $myEmp['basic_sal'] = $basic_sal;
        $myEmp['all_travel'] = $all_travel;
        $myEmp['bonus'] = $bonus;
        $myEmp['commission'] = $commission;
        $myEmp['abonus'] = $abonus;
        $myEmp['loaninstall'] = $loaninstall;
        $myEmp['comp_pension'] = $comp_pension;
        $myEmp['emp_pension'] = $emp_pension;
        $myEmp["comp_provident"] = $comp_provident;
        $myEmp["emp_provident"] = $emp_provident;
        //$myEmp["comp_uif"] = $comp_uif;
        //$myEmp["emp_uif"] = $emp_uif;
        $myEmp["comp_other"] = $comp_other;
        $myEmp["emp_other"] = $emp_other;
        $myEmp['comp_medical'] = $comp_medical;
        $myEmp['emp_medical'] = $emp_medical;
        $myEmp['comp_ret'] = $comp_ret;
        $myEmp['emp_ret'] = $emp_ret;
        $h1 = $novert;
        $h2 = $hovert;
    } else {
        if ($myEmp["payprd"] == "w" || $myEmp["payprd"] == "f") {
            $tmpmon = date("j");
            $daycount = date("t");
            $dayweek = date("D");
            if (strtolower($dayweek) == $myEmp["payprd_day"] && $day + 7 > $daycount) {
                $process_comp_deductions = true;
            } else {
                $process_comp_deductions = false;
            }
        } else {
            $process_comp_deductions = true;
        }
        $effective_basicsal = $myEmp["basic_sal"] * $multiplier;
        /* we only changing basic sal for non hourly employees,
        			because for hourly employees we change the hours ($mutli)  */
        if ($myEmp["saltyp"] != "h") {
            $myEmp["basic_sal"] *= $multiplier;
        }
        if ($myEmp["loaninstall"] > $myEmp["loanamt"]) {
            $myEmp["loaninstall"] = $myEmp["loanamt"];
        }
        $myEmp["emp_pension"] = sprint($effective_basicsal * ($myEmp["emp_pension"] / 100));
        $myEmp["comp_pension"] = sprint($effective_basicsal * ($myEmp["comp_pension"] / 100));
        $myEmp["emp_provident"] = sprint($effective_basicsal * ($myEmp["emp_provident"] / 100));
        $myEmp["comp_provident"] = sprint($effective_basicsal * ($myEmp["comp_provident"] / 100));
        $myEmp["emp_medical"] = sprint($myEmp["emp_medical"] / $divisor);
        $myEmp["comp_medical"] = sprint($myEmp["comp_medical"] / $divisor);
        $myEmp["emp_ret"] = sprint($myEmp["emp_ret"] / $divisor);
        $myEmp["comp_ret"] = sprint($myEmp["comp_ret"] / $divisor);
        $myEmp["loaninstall"] = sprint($myEmp["loaninstall"] / $divisor);
        $myEmp["all_travel"] = sprint($myEmp["all_travel"] / $divisor);
        if (isset($myEmp["loandate"]) and strlen($myEmp["loandate"]) > 0) {
            explodeDate($myEmp["loandate"], $loana_year, $loana_month, $loana_day);
            if ($loana_year > $salyr || $loana_year == $salyr && $loana_month > $MON) {
                $myEmp["loanint"] = 0;
                $myEmp["loaninstall"] = 0;
            }
        }
    }
    if (!isset($multi)) {
        $multi = $myEmp["saltyp"] == "h" ? $multiplier : 1;
    }
    $multi = round($multi);
    if ($myEmp['saltyp'] == 'd' || $myEmp['saltyp'] == 'h') {
        $salntype = $salnarr[$myEmp['saltyp']];
        $multi_show = "x <input type='text' size='3' name='multi' value='{$multi}'> {$salntype}";
    } else {
        $multi_show = "<input type='hidden' name='multi' value='{$multi}'>";
        $saltype = "";
    }
    /*	db_conn('cubit');
    	$sql = "SELECT value FROM settings WHERE constant='UIF_MAX'";
    	$percrslt = db_exec($sql);
    	$perc = pg_fetch_array($percrslt);
    	$uifmax = $perc['value'];
    
    	if ( $myEmp["emp_uif"] > $uifmax ) {
    		$myEmp["emp_uif"] = $uifmax;
    	}
    	if ( $myEmp["comp_uif"] > $uifmax ) {
    		$myEmp["comp_uif"] = $uifmax;
    	}
    */
    $Sl = "SELECT * FROM cubit.rbs ORDER BY name";
    $Ri = db_exec($Sl) or errDie("Unable to get data.");
    $i = 0;
    $rt = "";
    if (pg_num_rows($Ri) > 0) {
        while ($td = pg_fetch_array($Ri)) {
            if (!isset($rbsa[$td['id']])) {
                $rbsa[$td['id']] = "";
            }
            $rt .= "\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td><input type='hidden' name='rbs[{$td['id']}]' value='{$td['id']}'>{$td['name']}</td>\n\t\t\t\t\t<td>" . CUR . " <input type='text' size='10' name='rbsa[{$td['id']}]' value='" . $rbsa[$td['id']] . "' class=right></td>\n\t\t\t\t</tr>";
            $i++;
        }
    } else {
        $rt .= "<tr class='" . bg_class() . "'><td colspan='2' align='center'>There are no reimbursements</td></tr>";
    }
    if ($myEmp['payprd'] == "w") {
        $weekends = "";
        $weeks = "\n\t\t<select name='week'>";
        $stdate = mktime(0, 0, 0, $MON, 1, DATE_YEAR);
        $endate = mktime(0, 0, 0, $MON, DATE_DAYS, DATE_YEAR);
        $i = 1;
        while ($stdate <= $endate) {
            if (date("w", $stdate) == 5) {
                $weekends .= "<input type='hidden' name='weekends[{$i}]' value='" . date("j", $stdate) . "' />";
                if (isset($week) && $week == $i) {
                    $sel = "selected";
                } else {
                    $sel = "";
                }
                $weeks .= "<option {$sel} value='{$i}'>Week {$i} (" . date("j M", $stdate) . ")</option>";
                ++$i;
            }
            /* next day */
            $stdate += 24 * 60 * 60;
        }
        /*<option value='1'>Week 1</option>
        		<option value='2'>Week 2</option>
        		<option value='3'>Week 3</option>
        		<option value='4'>Week 4</option>
        		<option value='5'>Week 5</option>*/
        $weeks .= "\n\t\t</select>";
        $row = "{$weekends}<tr class='" . bg_class() . "'><td>Period</td><td>{$weeks}</td></tr>";
    } elseif ($myEmp['payprd'] == "f") {
        $weekends = "";
        $weeks = "\n\t\t<select name='week'>";
        $i = 1;
        /* find first friday of tax year */
        $stdate = mktime(0, 0, 0, 3, 1, getYearOfEmpMon(3));
        while (date("w", $stdate) != 5) {
            $stdate = mktime(0, 0, 0, 3, ++$i, getYearOfEmpMon(3));
        }
        // hack: go one week back so the +14 increases are easier
        $stdate -= 7 * 24 * 3600;
        /* end on the last day of the selected month */
        $endate = mktime(0, 0, 0, $MON + 1, 0, getYearOfEmpMon($MON));
        /* count weeks from start of tax year */
        $i = 1;
        $c = 0;
        while ($stdate <= $endate) {
            if (date("m", $stdate) == $MON && date("Y", $stdate) == getYearOfEmpMon($MON)) {
                $c += 2;
                $cd = $c - 1 . "-{$c}";
                $weekends .= "<input type='hidden' name='weekends[{$i}]' value='" . date("j", $stdate) . "' />";
                if (isset($week) && $week == $i) {
                    $sel = "selected";
                } else {
                    $sel = "";
                }
                $weeks .= "<option {$sel} value='{$i}'>Week {$cd} (" . date("j M", $stdate) . ")</option>";
                ++$i;
            }
            /* next day */
            $stdate += 24 * 60 * 60 * 14;
        }
        /*<option value='1'>Week 1</option>
        		<option value='2'>Week 2</option>
        		<option value='3'>Week 3</option>
        		<option value='4'>Week 4</option>
        		<option value='5'>Week 5</option>*/
        $weeks .= "\n\t\t</select>";
        $row = "{$weekends}<tr class='" . bg_class() . "'><td>Period</td><td>{$weeks}</td></tr>";
    } else {
        if ($myEmp["payprd"] == "d") {
            $x = date("t", mktime(0, 0, 0, $MON, 1, getYearOfFinMon($MON)));
            $MONstr = getMonthNameS($MON);
            if (!isset($pday)) {
                $pday = $proc_day;
            }
            $days = "<select name='pday'>";
            for ($i = 1; $i <= $x; ++$i) {
                if ($i == $pday) {
                    $sel = "selected='t'";
                } else {
                    $sel = "";
                }
                $days .= "<option {$sel} value='{$i}'>{$i} {$MONstr}</option>";
            }
            $days .= "</select>";
            $row = "\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Day for Payment</td>\n\t\t\t\t<td>{$days}</td>\n\t\t\t</tr>";
        } else {
            $weeks = "";
            $row = "<input type='hidden' name='week' value='0'>";
        }
    }
    if (!isset($abonus) && $myEmp["sal_bonus_month"] == $MON) {
        $abonus = $myEmp["sal_bonus"];
    } else {
        if (!isset($abonus)) {
            $abonus = 0;
        }
    }
    if ($myEmp["payprd"] == "m" || $myEmp["payprd"] == "h") {
        // count the amount of weekdays in this month
        $workdays = 0;
        for ($i = 1; $i <= date("t", mktime(0, 0, 0, $MON, 1, date("Y"))); ++$i) {
            $wd = date("w", mktime(0, 0, 0, $MON, $i, date("Y")));
            if ($wd != 0 && $wd != 6) {
                ++$workdays;
            }
        }
        // hours per day calculation
        $hpd = $myEmp["hpweek"] / 5;
        if (!isset($wh_total)) {
            $wh_total = $workdays * $hpd;
        }
        if (!isset($wh_actual)) {
            $wh_actual = $wh_total;
        }
    }
    if ($myEmp["payprd"] == "w") {
        if (!isset($wh_total)) {
            $wh_total = $myEmp["hpweek"];
        }
        if (!isset($wh_actual)) {
            $wh_actual = $wh_total;
        }
    }
    if ($myEmp["payprd"] == "f") {
        if (!isset($wh_total)) {
            $wh_total = $myEmp["hpweek"] * 2;
        }
        if (!isset($wh_actual)) {
            $wh_actual = $wh_total;
        }
    }
    $js_workhours = "\n\t<script>\n\t\tsf = document.getElementById('salfrm');\n\n\t\tf_sal\t\t= sf.elements['basic_sal'];\n\t\tf_whtot\t\t= sf.elements['wh_total'];\n\t\tf_whact\t\t= sf.elements['wh_actual'];\n\t\tf_cpension\t= sf.elements['comp_pension'];\n\t\tf_epension \t= sf.elements['emp_pension'];\n\t\tf_cprov\t\t= sf.elements['comp_provident'];\n\t\tf_eprov\t\t= sf.elements['emp_provident'];\n\t\t//f_cuif\t= sf.elements['comp_uif'];\n\t\t//f_euif\t= sf.elements['emp_uif'];\n\t\tf_cother\t= sf.elements['comp_other'];\n\t\tf_eother\t= sf.elements['emp_other'];\n\n\t\tdb_cpension\t= " . $db["comp_pension"] . ";\n\t\tdb_epension\t= " . $db["emp_pension"] . ";\n\t\tdb_cprov\t= " . $db["comp_provident"] . ";\n\t\tdb_eprov\t= " . $db["emp_provident"] . ";\n\t\t//db_cuif\t= " . $db["comp_uif"] . ";\n\t\t//db_euif\t= " . $db["emp_uif"] . ";\n\t\tdb_cother\t= " . $db["comp_other"] . ";\n\t\tdb_eother\t= " . $db["emp_other"] . ";\n\n\t\tval_sal \t\t= -1;\n\n\t\t// changing the workhours\n\t\tfunction workhours() {\n\t\t\tif ( val_sal < 0 ) val_sal = parseFloat(f_sal.value);\n\n\t\t\tval_whtot\t= parseFloat(f_whtot.value);\n\t\t\tval_whact\t= parseFloat(f_whact.value);\n\n\t\t\tif ( val_whtot >= val_whact ) {\n\t\t\t\tp = val_whact / val_whtot;\n\n\t\t\t\t// calculate the new basic salary\n\t\t\t\tx = val_sal * p;\n\t\t\t\tx = x.toFixed(2);\n\t\t\t\tf_sal.value = x;\n\n\t\t\t\t// calculate the new values\n\t\t\t\tval_cpension \t= x * db_cpension / 100;\n\t\t\t\tval_epension \t= x * db_epension / 100;\n\t\t\t\tval_cprov\t\t= x * db_cprov / 100;\n\t\t\t\tval_eprov\t\t= x * db_eprov / 100;\n\t\t\t\t//val_cuif\t\t= x * db_cuif / 100;\n\t\t\t\t//val_euif\t\t= x * db_euif / 100;\n\t\t\t\tval_cother\t\t= x * db_cother / 100;\n\t\t\t\tval_eother\t\t= x * db_eother / 100;\n\n\t\t\t\tval_cpension \t= val_cpension.toFixed(2);\n\t\t\t\tval_epension \t= val_epension.toFixed(2);\n\t\t\t\tval_cprov \t\t= val_cprov.toFixed(2);\n\t\t\t\tval_eprov\t\t= val_eprov.toFixed(2);\n\t\t\t\t//val_cuif\t\t= val_cuif.toFixed(2);\n\t\t\t\t//val_euif\t\t= val_euif.toFixed(2);\n\t\t\t\tval_cother\t\t= val_cother.toFixed(2);\n\t\t\t\tval_eother\t\t= val_eother.toFixed(2);\n\n\t\t\t\tf_cpension.value\t= val_cpension;\n\t\t\t\tf_epension.value \t= val_epension;\n\t\t\t\tf_cprov.value \t\t= val_cprov;\n\t\t\t\tf_eprov.value\t\t= val_eprov;\n\t\t\t\t//f_cuif.value\t\t= val_cuif;\n\t\t\t\t//f_euif.value\t\t= val_euif;\n\t\t\t\tf_cother.value\t\t= val_cother;\n\t\t\t\tf_eother.value\t\t= val_eother;\n\t\t\t}\n\t\t}\n\n\t\tfunction changedfield() {\n\t\t\tval_whtot\t= parseFloat(f_whtot.value);\n\t\t\tval_whact\t= parseFloat(f_whact.value);\n\n\t\t\tp = val_whtot / val_whact;\n\n\t\t\tval_sal = parseFloat(f_sal.value) * p;\n\t\t\tval_sal = val_sal.toFixed(2);\n\t\t}\n\t</script>";
    vsprint($myEmp["basic_sal"]);
    /* payprd message */
    $dispmsg = getCSetting("EMP_SALMSG");
    if (strpos($dispmsg, $myEmp["payprd"]) === false) {
        $payprd_msg_ch = "";
    } else {
        $payprd_msg_ch = "checked='t'";
    }
    $payprd_msg = get_payprdmsg($myEmp["payprd"]);
    /* print payslip on/off */
    $printslip = getCSetting("EMP_PRINTSLIP");
    $process = "\n\t<script>\n\t\tfunction update_salmsg(obj) {\n\t\t\tajaxRequest('payprdmsg.php', 'payprd_msg', AJAX_SET,\n\t\t\t\t'payprd={$myEmp['payprd']}&newval=' + obj.checked);\n\t\t}\n\t</script>\n\t<h3>Process Salary for {$myEmp['sname']}, {$myEmp['fnames']}</h3>\n\t<li class='err'>NOTE that Cubit is configured to compute employees' tax\n\t\tduring the employees' tax year that<br />\n\t\tstarts in March and ends in February,\n\t\tirrespective of the employer's financial year end.</li>\n\t<br />\n\t<form action='" . SELF . "' method='POST' id='salfrm'>\n\t\t<input type='hidden' name='key' value='confirm' />\n\t\t<input type='hidden' name='empnum' value='{$empnum}' />\n\t\t<input type='hidden' name='MON' value='{$MON}' />\n\t\t<input type='hidden' name='proc_day' value='{$proc_day}' />\n\t\t<input type='hidden' name='proc_month' value='{$proc_month}' />\n\t\t<input type='hidden' name='proc_year' value='{$proc_year}' />\n\t\t<input type='hidden' name='day' value='{$proc_day}' />\n\t\t<input type='hidden' name='mon' value='{$proc_month}' />\n\t\t<input type='hidden' name='year' value='{$proc_year}' />\n\t\t<input type='hidden' name='saltyp' value='{$myEmp['saltyp']}' />\n\t\t<input type='hidden' name='loanint' value='{$myEmp['loanint']}' />\n\t\t<input type='hidden' name='process_comp_deductions' value='{$process_comp_deductions}' />\n\t\t<input type='hidden' name='divisor' value='{$divisor}' />\n\t<table " . TMPL_tblDflts . " width='500'>\n\t\t<tr>\n\t\t\t<td id='payprd_msg'>{$payprd_msg}</td>\n\t\t</tr>\n\t\t<tr>\n\t\t\t<th align='right'>Salary Help Message: <input type='checkbox' onclick='update_salmsg(this);' name='payprd_dispmsg' {$payprd_msg_ch} /></th>\n\t\t</tr>\n\t</table>\n\t<table " . TMPL_tblDflts . ">\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'><input type='submit' value='Confirm &raquo;'></td>\n\t\t</tr>\n\t\t<tr>\n\t\t\t<td colspan='2'>{$err}</td>\n\t\t</tr>\n\t\t<tr>\n\t\t\t<th colspan='2'>Salary Details for the Pay Period</th>\n\t\t</tr>\n\t\t<tr class='" . bg_class() . "'>\n\t\t\t<td nowrap='t'>Print Salary Advice</td>\n\t\t\t<td>\n\t\t\t<select name='printslip'>\n\t\t\t\t<option value='y' " . ($printslip != "n" ? "selected='t'" : "") . ">Yes</option>\n\t\t\t\t<option value='n' " . ($printslip == "n" ? "selected='t'" : "") . ">No</option>\n\t\t\t</select>\n\t\t\t</td>\n\t\t</tr>\n\t\t<tr class='" . bg_class() . "'>\n\t\t\t<td nowrap>Basic salary</td>\n\t\t\t<td nowrap>" . CUR . " <input type='text' size='10' name='basic_sal' value='{$myEmp['basic_sal']}' class=right onChange='changedfield();'> {$saltype} {$multi_show}</td>\n\t\t</tr>";
    if ($myEmp["payprd"] == "d") {
        $process .= "\n\t\t\t<input type='hidden' name='wh_total' value='1'>\n\t\t\t<input type='hidden' name='wh_actual' value='1'>";
    } else {
        $process .= "\n\t\t<tr class='" . bg_class() . "'>\n\t\t\t<td>Total Work Hours:</td>\n\t\t\t<td><input type='text' size='10' name='wh_total' value='{$wh_total}' class='right' onChange='workhours();'></td>\n\t\t</tr>\n\t\t<tr class='" . bg_class() . "'>\n\t\t\t<td>Actual Hours Worked:</td>\n\t\t\t<td><input type='text' size='10' name='wh_actual' value='{$wh_actual}' class='right' onChange='workhours();'></td>\n\t\t</tr>";
    }
    if (!isset($annual)) {
        $annual = "";
    }
    $process .= "\n\t\t<tr class='" . bg_class() . "'>\n\t\t\t<td>Normal Overtime</td>\n\t\t\t<td nowrap><input type='text' size='5' name='novert' value='{$h1}' class='right'> Hrs</td>\n\t\t</tr>\n\t\t<tr class='" . bg_class() . "'>\n\t\t\t<td>Public Holiday Overtime</td>\n\t\t\t<td nowrap><input type='text' size='5' name='hovert' value='{$h2}' class='right'> Hrs</td>\n\t\t</tr>\n\t\t<tr class='" . bg_class() . "'>\n\t\t\t<!--<td>Special Bonus/Additional Salary</td>-->\n\t\t\t<td>Annual Bonus</td>\n\t\t\t<td>" . CUR . " <input type='text' size='10' name='abonus' value='{$abonus}' class='right'></td>\n\t\t\t<!--<td rowspan='2' class='err'>An amount entered here (Special Bonus/Additional\n\t\t\t\tSalary) will be treated as a recurring bonus/payment per pay period for PAYE\n\t\t\t\tpurposes, the amount will not be treated as an annual payment. If the\n\t\t\t\tamount paid as a bonus is a once off/annual payment please use the\n\t\t\t\tBonus(Annual Payments) option. In other cases PAYE has to be manually\n\t\t\t\tadjusted <u>per directive</u> from SARS when processing salary.\n\t\t\t</td>-->\n\t\t</tr>\n\t\t<input type='hidden' name='annual' value='0' />\n\t\t<!--<tr class='" . bg_class() . "'>\n\t\t\t<td>Bonus(Annual/Once Off Payments)</td>\n\t\t\t<td nowrap>" . CUR . " <input type='text' size='10' name='annual' value='{$annual}' class='right'></td>\n\t\t</tr>-->\n\t\t<tr class='" . bg_class() . "'>\n\t\t\t<td>Commission</td>\n\t\t\t<td nowrap>" . CUR . " <input type='text' size='10' name='commission' value='{$myEmp['commission']}' class='right'></td>\n\t\t</tr>\n\t\t<tr class='" . bg_class() . "'>\n\t\t\t<td>Low or interest-free loan installment</td>\n\t\t\t<td nowrap>" . CUR . " <input type='text' size='10' name='loaninstall' value='{$myEmp['loaninstall']}' class='right'></td>\n\t\t\t<td class='err'>In the event that the employee repays more than the installment -\n\t\t\t\tenter that amount, plus interest that is remitted, here.\n\t\t\t</td>\n\t\t</tr>\n\t\t<tr class='" . bg_class() . "'>\n\t\t\t<td>Travel Allowance</td>\n\t\t\t<td nowrap>" . CUR . " <input type='text' size='10' name='all_travel' value='{$myEmp['all_travel']}' class='right'></td>\n\t\t</tr>\n\t\t<tr class='" . bg_class() . "'>\n\t\t\t<td nowrap>Pension: Company Contribution</td>\n\t\t\t<td nowrap>" . CUR . " <input type='text' size='10' name='comp_pension' value='{$myEmp['comp_pension']}' class='right'></td>\n\t\t</tr>\n\t\t<tr class='" . bg_class() . "'>\n\t\t\t<td nowrap>Pension: Employee Deduction</td>\n\t\t\t<td nowrap>" . CUR . " <input type='text' size='10' name='emp_pension' value='{$myEmp['emp_pension']}' class='right'></td>\n\t\t</tr>\n\t\t<tr class='" . bg_class() . "'>\n\t\t\t<td nowrap>Provident: Company Contribution</td>\n\t\t\t<td nowrap>" . CUR . " <input type='text' size='10' name='comp_provident' value='{$myEmp['comp_provident']}' class='right'></td>\n\t\t</tr>\n\t\t<tr class='" . bg_class() . "'>\n\t\t\t<td nowrap>Provident: Employee Deduction</td>\n\t\t\t<td nowrap>" . CUR . " <input type='text' size='10' name='emp_provident' value='{$myEmp['emp_provident']}' class='right'></td>\n\t\t</tr>\n\t\t<!--\n\t\t<tr class='" . bg_class() . "'>\n\t\t\t<td nowrap>UIF: Company Contribution</td>\n\t\t\t<td nowrap>" . CUR . " <input type='text' size='10' name='comp_uif' value='{$myEmp['comp_uif']}' class='right'></td>\n\t\t</tr>\n\t\t<tr class='" . bg_class() . "'>\n\t\t\t<td nowrap>UIF: Employee Deduction</td>\n\t\t\t<td nowrap>" . CUR . " <input type='text' size='10' name='emp_uif' value='{$myEmp['emp_uif']}' class='right'></td>\n\t\t</tr>\n\t\t//-->\n\t\t<tr class='" . bg_class() . "'>\n\t\t\t<td nowrap>Retirement Annuity: Company Contribution</td>\n\t\t\t<td nowrap>" . CUR . " <input type='text' size='10' name='comp_ret' value='{$myEmp['comp_ret']}' class='right'></td>\n\t\t</tr>\n\t\t<tr class='" . bg_class() . "'>\n\t\t\t<td nowrap>Retirement Annuity: Employee Deduction</td>\n\t\t\t<td nowrap>" . CUR . " <input type='text' size='10' name='emp_ret' value='{$myEmp['emp_ret']}' class='right'></td>\n\t\t</tr>\n\t\t<tr class='" . bg_class() . "'>\n\t\t\t<td nowrap>Medical Contribution: Company</td>\n\t\t\t<td nowrap>" . CUR . " <input type='text' size='10' name='comp_medical' value='{$myEmp['comp_medical']}' class='right'></td>\n\t\t</tr>\n\t\t<tr class='" . bg_class() . "'>\n\t\t\t<td nowrap>Medical Contribution: Employee</td>\n\t\t\t<td nowrap>" . CUR . " <input type='text' size='10' name='emp_medical' value='{$myEmp['emp_medical']}' class='right'></td>\n\t\t</tr>\n\t\t<input type=hidden name='comp_other' value='0'>\n\t\t<input type=hidden name='emp_other' value='0'>\n\t\t<!--\n\t\t<tr class='" . bg_class() . "'>\n\t\t\t<td>Other: Company Contribution</td>\n\t\t\t<td>" . CUR . " <input type='text' size='10' name='comp_other' value='{$myEmp['comp_other']}' class='right'></td>\n\t\t</tr>\n\t\t<tr class='" . bg_class() . "'>\n\t\t\t<td>Other: Employee Deduction</td>\n\t\t\t<td>" . CUR . " <input type='text' size='10' name='emp_other' value='{$myEmp['emp_other']}' class='right'></td>\n\t\t</tr>\n\t\t//-->\n\t\t{$paydetails}\n\t\t<tr class='" . bg_class() . "'>\n\t\t\t<td>Override PAYE <input type='checkbox' name='mpaye'></td>\n\t\t\t<td>" . CUR . " <input type='text' size='10' name='mpaye_amount'></td>\n\t\t</tr>\n\t\t{$row}\n\t\t<tr><th colspan='2'>Fringe Benefits</th></tr>\n\t\t{$fringes}\n\t\t<tr><th colspan='2'>Allowances</th></tr>\n\t\t{$allowances}\n\t\t<tr><th colspan='2'>Subsistence Allowances</th></tr>\n\t\t{$subsistence}\n\t\t<tr><th colspan='2'>Deductions</th></tr>\n\t\t{$deductions}\n\t\t{$rt}\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'><input type='submit' value='Confirm &raquo;'></td>\n\t\t</tr>\n\t\t</form>\n\t\t{$js_workhours}\n\t\t</table>";
    return $process;
}
function send_mails()
{
    /* check for valid settings */
    $settings = new dbSelect("esettings", "cubit");
    $settings->run();
    if ($settings->num_rows() <= 0) {
        r2sListSet("emailsettings");
        header("Location: email-settings.php");
        exit;
    }
    /* send them */
    extract($_POST);
    require_lib("mail.smtp");
    $send = new clsSMTPMail();
    $settings->fetch_array();
    $server = $settings->d["smtp_host"];
    $from = $settings->d["fromname"];
    $reply = $settings->d["reply"];
    $content = chunk_split($emailsavepage_content);
    $boundary = md5($content) . "=:" . strlen($content);
    $headers = array();
    $headers[] = "From: {$from}";
    $headers[] = "Reply-To: {$reply}";
    $headers[] = "Content-Type: multipart/mixed; boundary=\"{$boundary}\"";
    $headers[] = "MIME-Version: 1.0";
    if (!isset($emailsavepage_mime)) {
        $attachmime = "text/html";
        $ext = ".html";
    } else {
        $attachmime = $emailsavepage_mime;
        if ($attachmime == "text/plain") {
            $ext = ".txt";
        } else {
            $ext = "";
        }
    }
    if ($emailsavepage_name == "") {
        $filename = "attachment{$ext}";
    } else {
        $filename = preg_replace("/.php\$/", "", $emailsavepage_name) . $ext;
    }
    // company image
    $get_img = "SELECT img, imgtype FROM compinfo LIMIT 1";
    $run_img = db_exec($get_img) or errDie("Unable to get company image information.");
    if (pg_numrows($run_img) > 0) {
        $carr = pg_fetch_array($run_img);
        // hack to limit a header line to 64 chars
        $temp = $carr['img'];
        $carr['img'] = "";
        $cnt = 0;
        for ($x = 0; $x <= strlen($temp); $x++) {
            $cnt++;
            $carr['img'] .= substr($temp, $x, 1);
            if ($cnt == 64) {
                $carr['img'] .= "\n";
                $cnt = 0;
            }
        }
        if (strlen($carr['img']) > 10) {
            if ($carr['imgtype'] == "image/jpeg") {
                $imgfilename = "logo.jpg";
            } elseif ($carr['imgtype'] == "image/png") {
                $imgfilename = "logo.png";
            } elseif ($carr['imgtype'] == "image/gif") {
                $imgfilename = "logo.gif";
            }
            $imagemsg = "Content-Type: {$carr['imgtype']}; charset=UTF-8\r\n" . "Content-Transfer-Encoding: base64\r\n" . "Content-Disposition: attachment; filename=\"{$imgfilename}\"" . "\r\n\r\n" . "{$carr['img']}\n";
            $content = base64_encode(str_replace("compinfo/getimg.php", "{$imgfilename}", base64_decode($content)));
        }
    }
    // hack to limit a header line to 64 chars
    $temp = $content;
    $content = "";
    $cnt = 0;
    for ($x = 0; $x <= strlen($temp); $x++) {
        $cnt++;
        $content .= substr($temp, $x, 1);
        if ($cnt == 64) {
            $content .= "\n";
            $cnt = 0;
        }
    }
    // the actual page
    $pagecontent = "Content-Type: {$attachmime}; charset=UTF-8\r\n" . "Content-Transfer-Encoding: base64\r\n" . "Content-Disposition: attachment; filename=\"{$filename}\"" . "\r\n\r\n" . "{$content}";
    $msg = "--{$boundary}\n" . "Content-Type: text/plain; charset=UTF-8\r\n\nDocument Attached\n\n" . "--{$boundary}\n" . "{$pagecontent}\n\n" . "--{$boundary}\n";
    if (isset($imagemsg) and strlen($imagemsg) > 0) {
        $msg .= "{$imagemsg}\n" . "--{$boundary}--\n";
    }
    $OUT = "\n\t<table " . TMPL_tblDflts . ">\n\t\t<tr>\n\t\t\t<th>Customer</th>\n\t\t\t<th>Email Status</th>\n\t\t</tr>";
    foreach ($emailcust as $cusnum => $email) {
        $custheaders = implode("\r\n", $headers);
        $custheaders .= "\r\nTo: \"{$surnames[$cusnum]}\" <{$email}>";
        $ret = $send->sendMessages($server, 25, "", "", "", $email, $from, $emailsavepage_subject, $msg, $custheaders);
        $redir = "";
        if ($cusnum == "custom_address") {
            $redir = "\n\t\t\t\t<td valign='center'>\n\t\t\t\t\t<form action='customers-new.php' method='POST'>\n\t\t\t\t\t\t<input type='hidden' name='surname' value='{$surnames[$cusnum]}'>\n\t\t\t\t\t\t<input type='hidden' name='email' value='{$email}'>\n\t\t\t\t\t\t<input type='submit' value='Add As Customer'>\n\t\t\t\t\t</form>\n\t\t\t\t</td>";
        }
        $OUT .= "\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>{$surnames[$cusnum]}</td>\n\t\t\t\t<td>{$ret}</td>\n\t\t\t\t{$redir}\n\t\t\t</tr>";
    }
    $OUT .= "</table><br>" . mkQuickLinks();
    return $OUT;
}
/**
 * checks whether supplier is transheks configured
 *
 * @param int $suppid
 * @return bool
 */
function trhSupplierEnabled($suppid)
{
    $qry = new dbSelect("config", "trh", grp(m("where", "value!='' AND (name='SMTP_SERVER' OR name='POP3_SERVER')")));
    $qry->run();
    $ret = $qry->num_rows() > 0;
    $qry->free();
    return $ret;
}
function write($_POST)
{
    # get vars
    extract($_POST);
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($classcode, "string", 1, 255, "Invalid Classification code.");
    $v->isOk($classname, "string", 1, 255, "Invalid Classification name.");
    # display errors, if any
    if ($v->isError()) {
        $confirmCust = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $confirmCust .= "<li class='err'>" . $e["msg"] . "</li>";
        }
        $confirmCust .= "<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $confirmCust;
    }
    # check stock code
    db_connect();
    $sql = "SELECT classcode FROM stockclass WHERE lower(classcode) = lower('{$classcode}') AND div = '" . USER_DIV . "'";
    $cRslt = db_exec($sql);
    if (pg_numrows($cRslt) > 0) {
        $error = "<li class='err'> A Classification with code : <b>{$classcode}</b> already exists.</li>";
        $error .= "<p><input type=button onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $error;
    }
    # connect to db
    db_connect();
    # write to db
    $sql = "INSERT INTO stockclass(classcode, classname, div) VALUES ('{$classcode}', '{$classname}', '" . USER_DIV . "')";
    $catRslt = db_exec($sql) or errDie("Unable to add class to system.", SELF);
    if (pg_cmdtuples($catRslt) < 1) {
        return "<li class='err'>Unable to add classname to database.</li>";
    }
    if (frmupdate_passon()) {
        $newlst = new dbSelect("stockclass", "cubit", grp(m("cols", "clasid, classname"), m("where", "div='" . USER_DIV . "'"), m("order", "classname ASC")));
        $newlst->run();
        $a = array();
        if ($newlst->num_rows() > 0) {
            while ($row = $newlst->fetch_array()) {
                $a[$row["clasid"]] = $row["classname"];
            }
        }
        $js = frmupdate_exec(array($a), true);
    } else {
        $js = "";
    }
    $write = "\n\t\t\t\t{$js}\n\t\t\t\t<table " . TMPL_tblDflts . " width='50%'>\n\t\t\t\t\t<tr>\n\t\t\t\t\t\t<th>Classification added to system</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>New Classification <b>{$classname}</b>, has been successfully added to the system.</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 border=0 cellpadding='2' cellspacing='1'>\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='stockclass-view.php'>View Classifications</a></td>\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='main.php'>Main Menu</a></td>\n\t\t\t\t\t</tr>\n\t\t\t\t</table>";
    return $write;
}
function deny()
{
    extract($_REQUEST);
    /* order info */
    $qry = new dbSelect("recvpurch", "trh", grp(m("where", wgrp(m("id", $id)))));
    $qry->run();
    if ($qry->num_rows() <= 0) {
        invalid_use("<li class='err'>Invalid Sales Order Id (TRHAPP).</li>");
    }
    $soi = $qry->fetch_array();
    /* set approve status */
    $cols = grp(m("approved", "d"));
    $upd = new dbUpdate("recvpurch", "trh", $cols, "id='{$id}'");
    $upd->run(DB_UPDATE);
    /* get customer trh config */
    $keyinfo = trhKeyCust($soi["custid"]);
    $email = $keyinfo["email"];
    /* send trh response message */
    $purinfo = array("purid" => $soi["purid"], "status" => "d");
    $ret = send_trhmsg("cust", $soi["custid"], $email, "rsppur", $purinfo);
    $OUT = listorders("<li class='err'>Successfully denied sales order.</li>");
    return $OUT;
}
예제 #23
0
function confirm_data($_POST)
{
    extract($_POST);
    if (isset($back)) {
        return enter_data($_POST);
    }
    /* do account number changes */
    if (isset($topacc) && is_array($topacc)) {
        $qry = new dbSql();
        foreach ($topacc as $fid => $v) {
            if (isset($accnum[$fid])) {
                $sql = "UPDATE cubit.import_data\n\t\t\t\t\t\tSET des1='{$topacc[$fid]}/{$accnum[$fid]}'\n\t\t\t\t\t\tWHERE id='{$fid}'";
                $qry->setSql($sql);
                $qry->run();
            }
        }
    }
    $qry = new dbSelect("import_data", "cubit");
    $qry->run();
    $check_num = new dbSelect("accounts", "core");
    $check_dup = new dbSelect("import_data", "cubit");
    while ($fd = $qry->fetch_array()) {
        $fid = $fd['id'];
        $accnum_parts = explode("/", $fd["des1"]);
        if (isset($topacc[$fid]) && isset($accnum[$fid])) {
            $check_num->setOpt(grp(m("where", wgrp(m("topacc", $accnum_parts[0]), m("accnum", $accnum_parts[1])))));
            $check_num->run();
            $check_dup->setOpt(grp(m("where", "des1='{$fd['des1']}' AND id!='{$fd['id']}'")));
            $check_dup->run();
            if ($check_num->num_rows() > 0 || $check_dup->num_rows() > 0) {
                return enter_data2($_POST);
            }
        }
    }
    global $_SESSION;
    $out = "\n\t\t<h3>Trial Balance Import</h3>\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='login' value='1' />\n\t\t\t<input type='hidden' name='div' value='{$_SESSION['USER_DIV']}' />\n\t\t\t<input type='hidden' name='login_user' value='{$_SESSION['USER_NAME']}' />\n\t\t\t<input type='hidden' name='login_pass' value='{$_SESSION['USER_PASS']}' />\n\t\t\t<input type='hidden' name='code' value='{$_SESSION['code']}' />\n\t\t\t<input type='hidden' name='comp' value='{$_SESSION['comp']}' />\n\t\t\t<input type='hidden' name='noroute' value='1' />\n\t\t\t<input type='hidden' name='prd' value='{$prd}' />\n\t\t<table " . TMPL_tblDflts . ">\n\t\t\t<tr>\n\t\t\t\t<th colspan='2'>Importing into " . getMonthName($prd) . " " . getYearOfFinMon($prd) . "</th>\n\t\t\t</tr>\n\t\t\t" . TBL_BR . "\n\t\t\t<tr>\n\t\t\t\t<th>Acc No</th>\n\t\t\t\t<th>Account Name</th>\n\t\t\t\t<th>Debit</th>\n\t\t\t\t<th>Credit</th>\n\t\t\t\t<th>Select Account to link to</th>\n\t\t\t</tr>";
    db_conn('cubit');
    $sql = "SELECT * FROM import_data ORDER BY des1";
    $rslt = db_exec($sql);
    $i = 0;
    $tot_debit = 0;
    $tot_credit = 0;
    db_conn('core');
    while ($fd = pg_fetch_array($rslt)) {
        $fid = $fd['id'];
        if ($accounts[$fid] == 0) {
            $catss = explode(":", $cat[$fid]);
            if ($catss[0] == "0") {
                return enter_data2($_POST) . "<li class=err>You need to select a category for the new account</li>";
            }
            $add = "<input type='hidden' name='cat[{$fid}]' value='{$cat[$fid]}'>\n\t\t\t(New Account) {$catss['1']}</td>";
        } else {
            $Sl = "SELECT accid,accname FROM accounts WHERE accid='{$accounts[$fid]}'";
            $Rx = db_exec($Sl);
            $ad = pg_fetch_array($Rx);
            $add = "{$ad['accname']}</td>";
        }
        $out .= "\n\t\t\t<input type='hidden' name='accounts[{$fid}]' value='{$accounts[$fid]}' />\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>{$fd['des1']}</td>\n\t\t\t\t<td>{$fd['des2']}</td>\n\t\t\t\t<td>{$fd['des3']}</td>\n\t\t\t\t<td>{$fd['des4']}</td>\n\t\t\t\t<td>{$add}</td>\n\t\t\t</tr>";
        $i++;
        $tot_debit += $fd['des3'];
        $tot_credit += $fd['des4'];
    }
    $tot_debit = sprint($tot_debit);
    $tot_credit = sprint($tot_credit);
    $out .= "\n\t\t<tr class='" . bg_class() . "'>\n\t\t\t<td colspan='2'>Total</td>\n\t\t\t<td align='right'>{$tot_debit}</td>\n\t\t\t<td align='right'>{$tot_credit}</td>\n\t\t</tr>";
    if ($cc_tot > 0) {
        db_conn('cubit');
        $Sl = "SELECT cusnum,accno,surname FROM customers ORDER BY surname";
        $Ri = db_exec($Sl);
        if (pg_num_rows($Ri) < 1) {
            return "<li class='err'>If you want to import your customer control account you need to add customers first</li>";
        }
        $out .= "\n\t\t\t<tr><td><br></td></tr>\n\t\t\t<tr>\n\t\t\t\t<td colspan='10'>\n\t\t\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<th>Acc No</th>\n\t\t\t\t\t\t\t<th>Customer</th>\n\t\t\t\t\t\t\t<th>Balance</th>\n\t\t\t\t\t\t</tr>";
        $tot = 0;
        while ($cd = pg_fetch_array($Ri)) {
            $cid = $cd['cusnum'];
            $cbalance[$cid] = sprint($cbalance[$cid]);
            $out .= "\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>{$cd['accno']}</td>\n\t\t\t\t<td>{$cd['surname']}</td>\n\t\t\t\t<td align='right'><input type='hidden' size='12' name='cbalance[{$cid}]' value='{$cbalance[$cid]}' />{$cbalance[$cid]}</td>\n\t\t\t</tr>";
            $tot += $cbalance[$cid];
        }
        $out .= "\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td colspan='2'><b>Total</b></td>\n\t\t\t\t\t<td align='right'><b>" . CUR . " {$cc_tot}</b></td>\n\t\t\t\t</tr>\n\t\t\t</td>\n\t\t</tr>";
        $out .= TBL_BR;
        if (sprint($cc_tot) != sprint($tot)) {
            return enter_data2($_POST) . "<li class='err'>The total amount for balances for customers you entered is: " . CUR . " {$tot}, the\n\t\t\ttotal for the control account is: " . sprint($cc_tot) . ". These need to be the same.</li>";
        }
    }
    if ($sc_tot > 0) {
        db_conn('cubit');
        $Sl = "SELECT supid,supno,supname FROM suppliers ORDER BY supname";
        $Ri = db_exec($Sl);
        if (pg_num_rows($Ri) < 1) {
            return "<li class='err'>If you want to import your supplier control account you need to add suppliers first</li>";
        }
        $out .= "\n\t\t\t<tr><td><br></td></tr>\n\t\t\t<tr>\n\t\t\t\t<td colspan='10'>\n\t\t\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<th>Supplier No</th>\n\t\t\t\t\t\t\t<th>Supplier</th>\n\t\t\t\t\t\t\t<th>Balance</th>\n\t\t\t\t\t\t</tr>";
        $tot = 0;
        while ($cd = pg_fetch_array($Ri)) {
            $sid = $cd['supid'];
            $sbalance[$sid] = sprint($sbalance[$sid]);
            $out .= "\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>{$cd['supno']}</td>\n\t\t\t\t\t<td>{$cd['supname']}</td>\n\t\t\t\t\t<td align='right'><input type='hidden' size='12' name='sbalance[{$sid}]' value='{$sbalance[$sid]}'>" . CUR . " {$sbalance[$sid]}</td>\n\t\t\t\t</tr>";
            $i++;
            $tot += $sbalance[$sid];
        }
        $out .= "\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td colspan='2'><b>Total</b></td>\n\t\t\t\t\t<td align='right'><b>" . CUR . " {$sc_tot}</b></td>\n\t\t\t\t</tr>\n\t\t\t</td>\n\t\t</tr>";
        $out .= TBL_BR;
        if (sprint($sc_tot) != sprint($tot)) {
            return enter_data2($_POST) . "<li class='err'>The total amount for balances for suppliers you entered is: " . CUR . " {$tot}, the\n\t\t\ttotal for the control account is: " . sprint($sc_tot) . ". These need to be the same.</li>";
        }
    }
    if ($sal_tot > 0) {
        db_conn('cubit');
        $Sl = "SELECT empnum,enum,sname,fnames FROM employees ORDER BY sname,fnames";
        $Ri = db_exec($Sl);
        if (pg_num_rows($Ri) < 1) {
            return "<li class='err'>If you want to import your employee control account you need to add employees first</li>";
        }
        $out .= "\n\t\t\t<tr>\n\t\t\t\t<td colspan='4'><li class='err'>Please enter the employee balances to link up with 'Employees Control Account'</li></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 colspan='10'>\n\t\t\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<th>Employee Number</th>\n\t\t\t\t\t\t\t<th>Employee</th>\n\t\t\t\t\t\t\t<th>Balance</th>\n\t\t\t\t\t\t</tr>";
        $tot = 0;
        while ($cd = pg_fetch_array($Ri)) {
            $eid = $cd['empnum'];
            if (!isset($ebalance[$eid])) {
                $ebalance[$eid] = "";
            }
            $ebalance[$eid] = sprint($ebalance[$eid]);
            $out .= "\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>{$cd['enum']}</td>\n\t\t\t\t\t<td>{$cd['sname']}, {$cd['fnames']}</td>\n\t\t\t\t\t<td align=right><input type='hidden' size='12' name='ebalance[{$eid}]' value='{$ebalance[$eid]}'>" . CUR . " {$ebalance[$eid]}</td>\n\t\t\t\t</tr>";
            $i++;
            $tot += $ebalance[$eid];
        }
        $out .= "\n\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t<td colspan='2'><b>Total</b></td>\n\t\t\t\t\t\t<td align='right'><b>" . CUR . " {$sal_tot}</b></td>\n\t\t\t\t\t</tr>\n\t\t\t\t</td>\n\t\t\t</tr>";
        $out .= "<tr><td><br></td></tr>";
        if (sprint($sal_tot) != sprint($tot)) {
            return enter_data2($_POST) . "<li class=err>The total amount for balances for employees you entered is: " . CUR . " {$tot}, the\n\t\t\ttotal for the control account is: " . sprint($sal_tot) . ". These need to be the same.</li>";
        }
    }
    if ($i_tot > 0) {
        db_conn('cubit');
        $Sl = "SELECT stkid,stkcod,stkdes FROM stock ORDER BY stkcod";
        $Ri = db_exec($Sl);
        if (pg_num_rows($Ri) < 1) {
            return "<li class='err'>If you want to import your inventory control account you need to add stock first</li>";
        }
        $out .= "\n\t\t\t<tr><td><br></td></tr>\n\t\t\t<tr>\n\t\t\t\t<td colspan='10'>\n\t\t\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<th>Stock Code</th>\n\t\t\t\t\t\t\t<th>Description</th>\n\t\t\t\t\t\t\t<th>Balance</th>\n\t\t\t\t\t\t\t<th>Units</th>\n\t\t\t\t\t\t</tr>";
        $tot = 0;
        while ($cd = pg_fetch_array($Ri)) {
            $iid = $cd['stkid'];
            if (!isset($ibalance[$iid])) {
                $ibalance[$iid] = "";
            }
            $tot += $ibalance[$iid];
            $units[$iid] += 0;
            if (sprint($ibalance[$iid]) > 0 && $units[$iid] <= 0) {
                return enter_data2($_POST) . "<li class='err'>You specified {$units[$iid]} units for {$cd['stkcod']}, but " . CUR . " {$ibalance[$iid]}.\n\t\t\t\tIf you want to enter an amount you need to give the qty.</li>";
            }
            $out .= "\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>{$cd['stkcod']}</td>\n\t\t\t\t\t<td>{$cd['stkdes']}</td>\n\t\t\t\t\t<td><input type='hidden' size='12' name='ibalance[{$iid}]' value='{$ibalance[$iid]}'>{$ibalance[$iid]}</td>\n\t\t\t\t\t<td><input type='hidden' name='units[{$iid}]' value='{$units[$iid]}'>{$units[$iid]}</td>\n\t\t\t\t</tr>";
            $i++;
        }
        $out .= "\n\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t<td colspan='2'><b>Total</b></td>\n\t\t\t\t\t\t<td align='right'><b>" . CUR . " {$i_tot}</b></td>\n\t\t\t\t\t\t<td></td>\n\t\t\t\t\t</tr>\n\t\t\t\t</td>\n\t\t\t</tr>";
        $out .= "<tr><td><br></td></tr>";
        if (sprint($i_tot) != sprint($tot)) {
            return enter_data2($_POST) . "<li class='err'>The total amount for balances for inventory you entered is: " . CUR . " {$tot}, the\n\t\t\ttotal for the control account is: " . sprint($i_tot) . ". These need to be the same.</li>";
        }
    }
    $out .= "\n\t\t\t<tr>\n\t\t\t\t<td colspan='2'><input type='submit' name='back' value='&laquo; Correction'></td>\n\t\t\t\t<td colspan='1' align='right'><input type='submit' value='Write &raquo;'></td>\n\t\t\t</tr>\n\t\t\t<input type='hidden' name='cc_tot' value='{$cc_tot}'>\n\t\t\t<input type='hidden' name='sal_tot' value='{$sal_tot}'>\n\t\t\t<input type='hidden' name='sc_tot' value='{$sc_tot}'>\n\t\t\t<input type='hidden' name='i_tot' value='{$i_tot}'>\n\t\t</form>\n\t\t</table>";
    return $out;
}
예제 #24
0
function send()
{
    if (!isset($_REQUEST["id"])) {
        invalid_use();
    }
    /* fetch purchase information */
    $purchase = new dbSelect("purchases", "cubit", grp(m("where", "purid='{$_REQUEST['id']}'")));
    $purchase->run();
    if ($purchase->num_rows() <= 0) {
        invalid_use("Invalid purchase.");
    }
    $purdata = $purchase->fetch_array();
    /* fetch the transheks email address of this supplier */
    $qry = new dbSelect("keys", "trh", grp(m("cols", "email, (key).send_key AS send_key"), m("where", "suppid='{$purdata['supid']}'")));
    $qry->run();
    if ($qry->num_rows() <= 0) {
        invalid_use("This supplier isn't configured for Transheks transactioning.");
    }
    $keyinfo = trhKeySupp($purdata["supid"]);
    $email = $keyinfo["email"];
    $send_key = $keyinfo["send_key"];
    if (empty($send_key)) {
        invalid_use("This supplier hasn't confirmed the Transactioning request sent.");
    }
    /* fetch purchase item information */
    $puritems = array();
    $purchase->setTable("pur_items", "cubit");
    $purchase->run();
    if ($purchase->num_rows() <= 0) {
        invalid_use("Invalid purchase, purchase has no items.");
    }
    while ($row = $purchase->fetch_array()) {
        $puritems[] = $row;
    }
    /* build xml data */
    $XML = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
    $attrs = array();
    foreach ($purdata as $k => $v) {
        $attrs[] = "{$k}=\"{$v}\"";
    }
    $XML .= "<purdata " . implode(" ", $attrs) . ">\n";
    foreach ($puritems as $puritem_data) {
        $attrs = array();
        foreach ($puritem_data as $k => $v) {
            $attrs[] = "{$k}=\"{$v}\"";
        }
        $XML .= "\t<puritem " . implode(" ", $attrs) . " />\n";
    }
    $XML .= "</purdata>\n";
    $OUT = "<h3>Send Supplier Order</h3>";
    if (($ret = send_trhmsg("supp", $purdata["supid"], $email, "reqpur", $XML)) !== true) {
        if ($ret === false) {
            $OUT .= "<li class='err'>There was an unknown error sending order to supplier.</li>";
        } else {
            $OUT .= "<li class='err'>Error sending order to supplier: {$ret}.</li>";
        }
    } else {
        $OUT .= "Successfully sent order to supplier.";
    }
    return $OUT;
}
function write($_POST)
{
    # Set mas execution time to 12 hours
    ini_set("max_execution_time", 43200);
    extract($_POST);
    # validate input
    require_lib("validate");
    $v = new validate();
    foreach ($invids as $key => $invid) {
        $v->isOk($invid, "num", 1, 20, "Invalid recuring invoice number.");
        $odate[$key] = mkdate($o_year[$key], $o_month[$key], $o_day[$key]);
        $v->isOk($odate[$key], "date", 1, 1, "Invalid Invoice Date for invoice: {$invid}.");
    }
    # display errors, if any
    $err = "";
    if ($v->isError()) {
        $err = $v->genErrors();
        return $err;
    }
    pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
    $i = 0;
    $recinv = new dbSelect("rnons_invoices", "cubit");
    $recinv_i = new dbSelect("rnons_inv_items", "cubit");
    $newinv = new dbUpdate("nons_invoices", "cubit");
    $newinv_i = new dbUpdate("nons_inv_items", "cubit");
    foreach ($invids as $key => $invid) {
        /* fetch recurring invoice info */
        $recinv->setOpt(grp(m("where", "invid='{$invid}' AND div='" . USER_DIV . "'")));
        $recinv->run();
        if ($recinv->num_rows() <= 0) {
            continue;
        }
        $inv = $recinv->fetch_array();
        /* create new invoice from recurring invoice */
        $cols = grp(m("accepted", " "), m("sdate", raw("CURRENT_DATE")), m("typ", "inv"), m("cusid", $inv["cusid"]), m("cusname", $inv["cusname"]), m("cusaddr", $inv["cusaddr"]), m("cusvatno", $inv["cusvatno"]), m("cordno", $inv["cordno"]), m("chrgvat", $inv["chrgvat"]), m("terms", $inv["terms"]), m("odate", $odate[$key]), m("subtot", $inv["subtot"]), m("vat", $inv["vat"]), m("total", $inv["total"]), m("balance", $inv["total"]), m("done", "n"), m("prd", PRD_DB), m("div", USER_DIV), m("ctyp", $inv["ctyp"]), m("tval", $inv["tval"]), m("jobid", $invid), m("remarks", $inv["remarks"]));
        $newinv->setOpt($cols);
        $newinv->run(DB_INSERT);
        /* fetch last invoice id */
        $invid = lastinvid();
        /* fetch recurring invoice items */
        $recinv_i->setOpt(grp(m("where", "invid='{$inv['invid']}' AND div='" . USER_DIV . "'")));
        $recinv_i->run();
        /* add items to new non stock invoice */
        while ($stkd = $recinv_i->fetch_array()) {
            $cols = grp(m("invid", $invid), m("qty", $stkd["qty"]), m("unitcost", $stkd["unitcost"]), m("amt", $stkd["amt"]), m("accid", $stkd["account"]), m("description", $stkd["description"]), m("vatex", $stkd["vatex"]), m("div", USER_DIV));
            $newinv_i->setOpt($cols);
            $newinv_i->run(DB_INSERT);
        }
    }
    pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
    $OUT = "\n\t\t<table " . TMPL_tblDflts . ">\n\t\t\t<tr>\n\t\t\t\t<th>Recurring Non-stock Invoices Processed</th>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>New non-stock Invoices have been created from Recurring Invoices</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='rec-invoice-view.php'>View Recurring Invoices</a></td>\n\t\t\t</tr>\n\t\t\t<script>document.write(getQuicklinkSpecial());</script>\n\t\t</table>";
    return $OUT;
}
function enter($_POST, $err = "")
{
    extract($_POST);
    global $PRDMON, $MONPRD;
    $salyr = getYearOfEmpMon($month);
    $curyr = getActiveFinYear();
    if ($salyr > $curyr || $salyr == $curyr && $month > $PRDMON[12]) {
        header("Location: ../admin-employee-view.php?err=Cannot do transaction in future financial year. You need to close your year first before you can continue.&" . array2get($_POST));
        exit;
    }
    if (!isset($emps) || !is_array($emps)) {
        header("Location: ../admin-employee-view.php?err=Please select at least one employee.");
        exit;
    }
    // first check if all the selected employees with EFT pay types have banking information
    // and their id numbers are valid
    $emp_err = array();
    $emp_nam = array();
    foreach ($emps as $e_empnum => $e_val) {
        /* previously selected to remove this employee from process */
        if (isset($rememp[$e_empnum])) {
            unset($emps[$e_empnum]);
            continue;
        }
        $sql = "\n\t\t\tSELECT fnames, sname, paytype, bankname, bankaccno, idnum, flag, hiredate, payprd \n\t\t\tFROM employees \n\t\t\tWHERE div='" . USER_DIV . "' AND empnum='{$e_empnum}'";
        $rslt = db_exec($sql) or errDie("error checking employee payment types.");
        $e_info = pg_fetch_array($rslt);
        /* if the employee's pay period doesn't match the selected button, don't
        			include employee in checklist */
        if (isset($d) && $e_info["payprd"] != "d") {
            continue;
        } else {
            if (isset($w) && $e_info["payprd"] != "w") {
                continue;
            } else {
                if (isset($b) && $e_info["payprd"] != "f") {
                    continue;
                } else {
                    if (isset($m) && $e_info["payprd"] != "m") {
                        continue;
                    }
                }
            }
        }
        $e_empnum += 0;
        $emp_err[$e_empnum] = 0;
        $emp_nam[$e_empnum] = "{$e_info['fnames']} {$e_info['sname']}";
        if ($e_info["paytype"] == "EFT" && (empty($e_info["bankname"]) || empty($e_info["bankaccno"]))) {
            $emp_err[$e_empnum] |= 0x1;
        }
        if (!empty($e_info["idnum"])) {
            $bd_year = substr($e_info["idnum"], 0, 2);
            $bd_month = substr($e_info["idnum"], 2, 2);
            $bd_day = substr($e_info["idnum"], 4, 2);
            if (!checkdate($bd_month, $bd_day, $bd_year)) {
                $emp_err[$e_empnum] |= 0x2;
            }
        }
        if ($e_info["flag"] == "2.5EMP") {
            $emp_err[$e_empnum] |= 0x4;
            $special_error = 0x1;
        }
        if ($e_info["flag"] == "272PREVEMP") {
            $emp_err[$e_empnum] |= 0x4;
            $special_error = 0x2;
        }
        /* check hiredate after process date */
        explodeDate($e_info["hiredate"], $hd_year, $hd_month, $hd_day);
        $MONempyear = getYearOfEmpMon($month);
        if ($hd_year > $MONempyear || $hd_year == $MONempyear && $hd_month > $month) {
            $emp_err[$e_empnum] |= 0x8;
        }
    }
    // list the employee information problems
    if (array_sum($emp_err) > 0) {
        $out = "\n\t\t\t<h3>Batch Salaries</h3>\n\t\t\t\t<form method='POST' action='" . SELF . "'>";
        foreach ($_POST as $key => $value) {
            if (is_array($value)) {
                foreach ($value as $akey => $avalue) {
                    $out .= "<input type='hidden' name='{$key}" . "[{$akey}]' value='{$avalue}'>";
                }
            } else {
                $out .= "<input type='hidden' name='{$key}' value='{$value}'>";
            }
        }
        if (isset($special_error)) {
            switch ($special_error) {
                case 0x1:
                    $out .= "\n\t\t\t\t\t<li class='err'><strong>NOTICE:</strong> Due to changes in employee functionality from Cubit 2.5 to Cubit 2.6 <br>\n\t\t\t\t\t\tyou need to edit your employees' salary/deduction/allowance information</li>\n\t\t\t\t\t\t<br />";
                    break;
                case 0x2:
                    $out .= "\n\t\t\t\t\t<li class='err'><strong>NOTICE:</strong> Due to the changes from Cubit 2.71 to Cubit 2.72 you should first update your employee's\n\t\t\t\t\t\tprevious employment information in the employee edit form.</li>\n\t\t\t\t\t\t<br />";
                    break;
            }
        }
        $out .= "\n\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t<tr>\n\t\t\t\t\t<td colspan='3' class='err'>There are problems with the following employees.<br />\n\t\t\t\t\t\tEdit their information or to remove an employee from the process select\n\t\t\t\t\t\tthe checkbox next to employee's name.<br /><br />\n\t\t\t\t\t\tClick the 'Done' button when ready to proceed.</td>\n\t\t\t\t</tr>";
        $out .= "\n\t\t\t<tr>\n\t\t\t\t<td>&nbsp;</td>\n\t\t\t\t<th>Name</th>\n\t\t\t\t<th>Message</th>\n\t\t\t</tr>";
        $i = 0;
        foreach ($emp_err as $e_empnum => $err_val) {
            $out .= "\n\t\t\t\t<tr bgcolor='" . bgcolor($i) . "'>\n\t\t\t\t\t<td><input type='checkbox' name='rememp[{$e_empnum}]' /></td>\n\t\t\t\t\t<th>{$emp_nam[$e_empnum]}</td>";
            if ($err_val & 0x4) {
                $specerr_msg = "(See above notice for this employee)";
            } else {
                $specerr_msg = "";
            }
            if ($err_val & 0x1 && $err_val & 0x2) {
                $out .= "<td class='err'>Banking info and ID number {$specerr_msg}</td>";
            } else {
                if ($err_val & 0x1) {
                    $out .= "<td class='err'>Banking info {$specerr_msg}</td>";
                } else {
                    if ($err_val & 0x2) {
                        $out .= "<td class='err'>ID number {$specerr_msg}</td>";
                    } else {
                        if ($err_val & 0x8) {
                            $out .= "<td class='err'>Employee was not employed in the period\n\t\t\t\t\trequested {$specerr_msg}</td>";
                        } else {
                            $out .= "<td>Employee Info Correct {$specerr_msg}</td>";
                        }
                    }
                }
            }
            if ($err_val && !($err_val == 0x8)) {
                $out .= "<td class='err'><a target='_blank' href='../admin-employee-edit.php?empnum={$e_empnum}'>Edit Employee</a></td>";
            }
            $out .= "</tr>";
        }
        $out .= "\n\t\t\t\t<tr>\n\t\t\t\t\t<td colspan='3' align='right'><input type='submit' value='Done' /></td>\n\t\t\t\t</tr>\n\t\t\t</table>\n\t\t\t</form>";
        return $out;
    }
    if (!isset($date_day)) {
        $date_day = date("d");
        $date_month = date("m");
        $date_year = date("Y");
    }
    if (!isset($date_month)) {
        $date_month = date("m");
    }
    /* make week/day selections */
    if (isset($w)) {
        $weekends = "";
        $weeks = "<select name='week'>";
        $stdate = mktime(0, 0, 0, $month, 1, DATE_YEAR);
        $endate = mktime(0, 0, 0, $month, DATE_DAYS, DATE_YEAR);
        $i = 1;
        while ($stdate <= $endate) {
            if (date("w", $stdate) == 5) {
                $weekends .= "<input type='hidden' name='weekends[{$i}]' value='" . date("j", $stdate) . "' />";
                if (isset($week) && $week == $i) {
                    $sel = "selected";
                } else {
                    $sel = "";
                }
                $weeks .= "<option {$sel} value='{$i}'>Week {$i} (" . date("j M", $stdate) . ")</option>";
                ++$i;
            }
            /* next day */
            $stdate += 24 * 60 * 60;
        }
        /*<option value='1'>Week 1</option>
        		<option value='2'>Week 2</option>
        		<option value='3'>Week 3</option>
        		<option value='4'>Week 4</option>
        		<option value='5'>Week 5</option>*/
        $weeks .= "</select>";
        $weeks = "\n\t\t\t<th>Week</th>\n\t\t\t<td>{$weekends}{$weeks}</td>\n\t\t\t<td class='err'>Period salaries are processed for</td>";
    } else {
        if (isset($b)) {
            $weekends = "";
            $weeks = "<select name='week'>";
            $i = 1;
            /* find first friday of tax year */
            $stdate = mktime(0, 0, 0, 3, 1, getYearOfEmpMon(3));
            while (date("w", $stdate) != 5) {
                $stdate = mktime(0, 0, 0, 3, ++$i, getYearOfEmpMon(3));
            }
            // hack: go one week back so the +14 increases are easier
            $stdate -= 7 * 24 * 3600;
            /* end on the last day of the selected month */
            $endate = mktime(0, 0, 0, $month + 1, 0, getYearOfEmpMon($month));
            /* count weeks from start of tax year */
            $i = 1;
            $c = 0;
            while ($stdate <= $endate) {
                if (date("m", $stdate) == $month && date("Y", $stdate) == getYearOfEmpMon($month)) {
                    $c += 2;
                    $cd = $c - 1 . "-{$c}";
                    $weekends .= "<input type='hidden' name='weekends[{$i}]' value='" . date("j", $stdate) . "' />";
                    if (isset($week) && $week == $i) {
                        $sel = "selected";
                    } else {
                        $sel = "";
                    }
                    $weeks .= "<option {$sel} value='{$i}'>Week {$cd} (" . date("j M", $stdate) . ")</option>";
                    ++$i;
                }
                /* next day */
                $stdate += 24 * 60 * 60 * 14;
            }
            /*<option value='1'>Week 1</option>
            		<option value='2'>Week 2</option>
            		<option value='3'>Week 3</option>
            		<option value='4'>Week 4</option>
            		<option value='5'>Week 5</option>*/
            $weeks .= "\n\t\t</select>";
            $weeks = "\n\t\t\t<th>Week</th>\n\t\t\t<td>{$weekends}{$weeks}</td>\n\t\t\t<td class='err'>Period salaries are processed for</td>";
        } else {
            if (isset($d)) {
                $x = date("t", mktime(0, 0, 0, $month, 1, getYearOfFinMon($month)));
                $MONstr = getMonthNameS($month);
                if (!isset($proc_day)) {
                    $proc_day = 0;
                }
                if (!isset($pday)) {
                    $pday = $proc_day;
                }
                $days = "<select name='pday'>";
                for ($i = 1; $i <= $x; ++$i) {
                    if ($i == $pday) {
                        $sel = "selected='t'";
                    } else {
                        $sel = "";
                    }
                    $days .= "<option {$sel} value='{$i}'>{$i} {$MONstr}</option>";
                }
                $days .= "</select>";
                $weeks = "\n\t\t\t<th>Day for Payment</th>\n\t\t\t<td>{$days}</td>\n\t\t\t<td class='err'>Period salaries are processed for</td>";
            } else {
                $weeks = "<input type='hidden' name='week' value='0'>";
            }
        }
    }
    /* payprd message */
    if (isset($d)) {
        $cpayprd = "d";
    } else {
        if (isset($w)) {
            $cpayprd = "w";
        } else {
            if (isset($b)) {
                $cpayprd = "f";
            } else {
                if (isset($m)) {
                    $cpayprd = "m";
                } else {
                    invalid_use("Invalid payment type selected.");
                }
            }
        }
    }
    $dispmsg = getCSetting("EMP_SALMSG");
    if (strpos($dispmsg, $cpayprd) === false) {
        $payprd_msg_ch = "";
    } else {
        $payprd_msg_ch = "checked='t'";
    }
    $payprd_msg = get_payprdmsg($cpayprd);
    /* print payslip on/off */
    $printslip = getCSetting("EMP_PRINTSLIP");
    $out = "\n\t\t<script>\n\t\t\tfunction update_salmsg(obj) {\n\t\t\t\tajaxRequest('payprdmsg.php', 'payprd_msg', AJAX_SET,'payprd={$cpayprd}&newval=' + obj.checked);\n\t\t\t}\n\t\t</script>\n\t\t<form action='" . SELF . "' method='POST' id='salfrm'>\n\t\t\t<input type='hidden' name='key' value='confirm' />\n\t\t\t<input type='hidden' name='month' value='{$month}' />\n\t\t<table " . TMPL_tblDflts . ">\n\t\t\t<tr>\n\t\t\t\t<td colspan='9'>\n\t\t\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<td><h3>Processing Batch Salaries</h3></td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<td>\n\t\t\t\t\t\t\t\t<li class='err'>NOTE that Cubit is configured to compute employees' tax\n\t\t\t\t\t\t\t\t\tduring the employees' tax year that<br />\n\t\t\t\t\t\t\t\t\tstarts in March and ends in February,\n\t\t\t\t\t\t\t\t\tirrespective of the employer's financial year end.</li>\n\t\t\t\t\t\t\t</td>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<td id='payprd_msg' colspan='2'>{$payprd_msg}</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<th align='right'>Salary Help Message: <input type='checkbox' onclick='update_salmsg(this);' name='payprd_dispmsg' {$payprd_msg_ch} /></th>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t</table>\n\t\t\t\t</td>\n\t\t\t</tr>\n\t\t\t<tr>\n\t\t\t\t<td colspan='6' valign='top' rowspan='2'>\n\t\t\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t{$weeks}\n\t\t\t\t\t</tr>\n\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t<th>Processing Date:</th>\n\t\t\t\t\t\t<td nowrap>" . mkDateSelect("date", $date_year, $date_month, $date_day) . "</td>\n\t\t\t\t\t\t<td colspan='2' class='err'>Date used by Cubit for the ledgers.</td>\n\t\t\t\t\t</tr>\n\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t<th nowrap='t'>Print Salary Advice</th\n\t\t\t\t\t\t<td>\n\t\t\t\t\t\t<select name='printslip'>\n\t\t\t\t\t\t\t<option value='y' " . ($printslip != "n" ? "selected='t'" : "") . ">Yes</option>\n\t\t\t\t\t\t\t<option value='n' " . ($printslip == "n" ? "selected='t'" : "") . ">No</option>\n\t\t\t\t\t\t</select>\n\t\t\t\t\t\t</td>\n\t\t\t\t\t</tr>\n\t\t\t\t\t\n\t\t\t\t\t</table>\n\t\t\t\t</td>\n\t\t\t\t<td colspan='3' align='right' nowrap='t'>\n\t\t\t\t\t<input type='submit' name='btn_back' value='&laquo; Correction'>\n\t\t\t\t\t<input type='submit' value='Confirm &raquo;'>\n\t\t\t\t</td>\n\t\t\t\t<td colspan='10' align='right' nowrap='t'>\n\t\t\t\t\t<input type='submit' name='btn_back' value='&laquo; Correction'>\n\t\t\t\t\t<input type='submit' value='Confirm &raquo;'>\n\t\t\t\t</td>\n\t\t\t</tr>\n\t\t\t<tr>\n\t\t\t\t<!--<td align='center' colspan='3' class='err'>An amount entered here (Special Bonus/Additional\n\t\t\t\t\tSalary) will be treated as a recurring bonus/payment per pay period for PAYE\n\t\t\t\t\tpurposes, the amount will not be treated as an annual payment. If the\n\t\t\t\t\tamount paid as a bonus is a once off/annual payment please use the\n\t\t\t\t\tBonus(Annual Payments) option. In other cases PAYE has to be manually\n\t\t\t\t\tadjusted <u>per directive</u> from SARS when processing salary.</td>-->\n\t\t\t\t<td colspan='3'>&nbsp;</td>\n\t\t\t\t<td colspan='3' class='err'><strong>LOAN NOTE:</strong><br />In the event that the employee repays more than the installment -\n\t\t\t\t\tenter that amount, plus interest that is remitted, in the \"Loan Repayment\" field below.\n\t\t\t\t</td>\n\t\t\t</tr>\n\t\t\t<tr>\n\t\t\t\t<td colspan='10'>{$err}</td>\n\t\t\t</tr>\n\t\t\t<tr>\n\t\t\t\t<th>Nr.</th>\n\t\t\t\t<th>Name</th>\n\t\t\t\t<th>Remuneration</th>";
    if (!isset($d)) {
        $out .= "\n\t\t\t<th>Total Work Hours</th>\n\t\t\t<th>Actual Hours Worked</th>";
    }
    $out .= "\n\t\t\t<th>Normal Overtime</th>\n\t\t\t<th>Public Holiday Overtime</th>\n\t\t\t<th>Annual Bonus</th>\n\t\t\t<!--\n\t\t\t<th>Special Bonus/Additional Salary</th>\n\t\t\t<th>Annual/Once Off Bonus</th>\n\t\t\t-->\n\t\t\t<th>Commission</th>\n\t\t\t<th>Travel Allowance</th>\n\t\t\t<th>Loan Repayment</th>\n\t\t\t<th>Pension: Company Contribution</th>\n\t\t\t<th>Pension: Employee Deduction</th>\n\t\t\t<th>Provident: Company Contribution</th>\n\t\t\t<th>Provident: Employee Deduction</th>\n\t\t\t<!--\n\t\t\t<th>UIF: Company Contribution</th>\n\t\t\t<th>UIF: Employee Deduction</th>\n\t\t\t//-->\n\t\t\t<th>Retirement Annuity: Company Contribution</th>\n\t\t\t<th>Retirement Annuity: Employee Deduction</th>\n\t\t\t<th>Medical Contribution: Company</th>\n\t\t\t<th>Medical Contribution: Employee</th>\n\t\t\t<!--\n\t\t\t<th>Other: Company Contribution</th>\n\t\t\t<th>Other: Employee Deduction</th>\n\t\t\t//-->\n\t\t\t<th>Method of Payment</th>\n\t \t\t<th>Override PAYE</th>\n\t \t\t<th>Fringe Ben.</th>\n\t \t\t<th>Allowances</th>\n\t \t\t<th>Subsistence</th>\n\t \t\t<th>Deductions</th>\n\t \t\t<th>Reimbursements</th>\n\t\t</tr>";
    db_conn('cubit');
    $i = 0;
    $Sl = "SELECT * FROM employees WHERE div='" . USER_DIV . "' ORDER BY sname,fnames";
    $Ri = db_exec($Sl) or errDie("Unable to get data.");
    $jsbonus_clear = array();
    $uif_calc = array();
    $jsbonus = array(1 => array(), 2 => array(), 3 => array(), 4 => array(), 5 => array(), 6 => array(), 7 => array(), 8 => array(), 9 => array(), 10 => array(), 11 => array(), 12 => array());
    $js_workhours_fields = "";
    $subs_int = false;
    // whether there are internation subsistence allowances
    $counter = 0;
    while ($data = pg_fetch_array($Ri)) {
        if ($counter == 8) {
            #show headings...
            $out .= "\n\t\t\t\t<tr>\n\t\t\t\t\t<th>Nr.</th>\n\t\t\t\t\t<th>Name</th>\n\t\t\t\t\t<th>Remuneration</th>";
            if (!isset($d)) {
                $out .= "\n\t\t\t\t\t<th>Total Work Hours</th>\n\t\t\t\t\t<th>Actual Hours Worked</th>";
            }
            $out .= "\n\t\t\t\t\t<th>Normal Overtime</th>\n\t\t\t\t\t<th>Public Holiday Overtime</th>\n\t\t\t\t\t<th>Annual Bonus</th>\n\t\t\t\t\t<!--\n\t\t\t\t\t<th>Special Bonus/Additional Salary</th>\n\t\t\t\t\t<th>Annual/Once Off Bonus</th>\n\t\t\t\t\t-->\n\t\t\t\t\t<th>Commission</th>\n\t\t\t\t\t<th>Travel Allowance</th>\n\t\t\t\t\t<th>Loan Repayment</th>\n\t\t\t\t\t<th>Pension: Company Contribution</th>\n\t\t\t\t\t<th>Pension: Employee Deduction</th>\n\t\t\t\t\t<th>Provident: Company Contribution</th>\n\t\t\t\t\t<th>Provident: Employee Deduction</th>\n\t\t\t\t\t<!--\n\t\t\t\t\t<th>UIF: Company Contribution</th>\n\t\t\t\t\t<th>UIF: Employee Deduction</th>\n\t\t\t\t\t//-->\n\t\t\t\t\t<th>Retirement Annuity: Company Contribution</th>\n\t\t\t\t\t<th>Retirement Annuity: Employee Deduction</th>\n\t\t\t\t\t<th>Medical Contribution: Company</th>\n\t\t\t\t\t<th>Medical Contribution: Employee</th>\n\t\t\t\t\t<!--\n\t\t\t\t\t<th>Other: Company Contribution</th>\n\t\t\t\t\t<th>Other: Employee Deduction</th>\n\t\t\t\t\t//-->\n\t\t\t\t\t<th>Method of Payment</th>\n\t\t\t \t\t<th>Override PAYE</th>\n\t\t\t \t\t<th>Fringe Ben.</th>\n\t\t\t \t\t<th>Allowances</th>\n\t\t\t \t\t<th>Subsistence</th>\n\t\t\t \t\t<th>Deductions</th>\n\t\t\t \t\t<th>Reimbursements</th>\n\t\t\t\t</tr>";
            $counter = 0;
        }
        $counter++;
        if (!isset($emps[$data['empnum']])) {
            continue;
        }
        $bgcolor = bgcolorc($i);
        $send = "";
        $grossal = $data["basic_sal"] + $data["commission"] + $data["all_travel"] / 2 + $data["bonus"];
        if (isset($d)) {
            $send = "<input type='hidden' name='d' value=''>";
            if ($data['payprd'] != "d") {
                continue;
            }
        } elseif (isset($w)) {
            $send = "<input type='hidden' name='w' value=''>";
            if ($data['payprd'] != "w") {
                continue;
            }
        } elseif (isset($m)) {
            $send = "<input type='hidden' name='m' value=''>";
            if ($data['payprd'] != "m") {
                continue;
            }
        } elseif (isset($b)) {
            $send = "<input type='hidden' name='b' value=''>";
            if ($data['payprd'] != "f") {
                continue;
            }
        } else {
            continue;
        }
        /* set employee id */
        $id = $data['empnum'];
        /* calculate basic salary divisors and multipliers
         * used for calculating deductions/allowances/etc. when the
         * salary type and payment period differs in length
         */
        switch ($data["saltyp"]) {
            case "h":
                $divisor = 1;
                switch ($data["payprd"]) {
                    case "d":
                        $multiplier = $data["hpweek"] / 5;
                        break;
                    case "w":
                        $multiplier = $data["hpweek"];
                        break;
                    case "f":
                        $multiplier = $data["hpweek"] * 2;
                        break;
                    case "m":
                        $multiplier = $data["hpweek"] * 52 / 12;
                        break;
                }
                break;
            case "m":
                $divisor = 1;
                switch ($data["payprd"]) {
                    case "d":
                        $multiplier = 12 / (5 * 52);
                        break;
                    case "w":
                        $multiplier = 12 / 52;
                        break;
                    case "f":
                        $multiplier = 12 / 26;
                        break;
                    case "m":
                        $multiplier = 1;
                        break;
                }
                break;
            case "w":
                $divisor = 52 / 12;
                switch ($data["payprd"]) {
                    case "d":
                        $multiplier = 1 / 5;
                        break;
                    case "w":
                        $multiplier = 1;
                        break;
                    case "f":
                        $multiplier = 2;
                        break;
                    case "m":
                        $multiplier = 52 / 12;
                        break;
                }
                break;
            case "f":
                $divisor = 26 / 12;
                switch ($data["payprd"]) {
                    case "d":
                        $multiplier = 1 / 10;
                        break;
                    case "w":
                        $multiplier = 1 / 2;
                        break;
                    case "f":
                        $multiplier = 1;
                        break;
                    case "m":
                        $multiplier = 26 / 12;
                        break;
                }
                break;
        }
        $bon_month = round($data["sal_bonus_month"]);
        $jsbonus_clear[] = "document.getElementById('salfrm').elements['bonus[{$id}]'].value='0.00';";
        $jsbonus[$bon_month][] = "document.getElementById('salfrm').elements['bonus[{$id}]'].value = '{$data['sal_bonus']}';";
        /*		$uif_calc[] = "
        			tmp_calc = parseFloat(document.getElementById('salfrm').elements['basic_sal[$id]'].value)
        				+ parseFloat(document.getElementById('salfrm').elements['annual[$id]'].value)
        				+ parseFloat(document.getElementById('salfrm').elements['all_travel[$id]'].value);
        			tmp_calc_emp = tmp_calc * $data[emp_uif] / 100;
        			tmp_calc_comp = tmp_calc * $data[comp_uif] / 100;
        			tmp_calc_emp = tmp_calc_emp.toFixed(2);
        			tmp_calc_comp = tmp_calc_comp.toFixed(2);
        			document.getElementById('salfrm').elements['emp_uif[$id]'].value = tmp_calc_emp;
        			document.getElementById('salfrm').elements['comp_uif[$id]'].value = tmp_calc_comp;";*/
        $db = array("comp_pension" => $data["comp_pension"], "emp_pension" => $data["emp_pension"], "comp_provident" => $data["comp_provident"], "emp_provident" => $data["emp_provident"], "comp_uif" => $data["comp_uif"], "emp_uif" => $data["emp_uif"], "comp_other" => $data["comp_other"], "emp_other" => $data["emp_other"]);
        if (isset($basic_sal[$id])) {
            $data['basic_sal'] = $basic_sal[$id];
            $data['bonus'] = $bonus[$id];
            $data['commission'] = $commission[$id];
            $date['abonus'] = $abonus[$id];
            $data['all_travel'] = $all_travel[$id];
            $data['loaninstall'] = $loaninstall[$id];
            $data['comp_pension'] = $comp_pension[$id];
            $data['emp_pension'] = $emp_pension[$id];
            $data['comp_provident'] = $comp_provident[$id];
            $data['emp_provident'] = $emp_provident[$id];
            //$data['comp_uif']=$comp_uif[$id];
            //$data['emp_uif']=$emp_uif[$id];
            $data['comp_ret'] = $comp_ret[$id];
            $data['emp_ret'] = $emp_ret[$id];
            $data['comp_medical'] = $comp_medical[$id];
            $data['emp_medical'] = $emp_medical[$id];
            $data['comp_other'] = $comp_other[$id];
            $data['emp_other'] = $emp_other[$id];
        } else {
            if ($data["sal_bonus_month"] == $month) {
                $annual[$id] = sprint($data["sal_bonus"]);
            } else {
                $annual[$id] = "0.00";
            }
            $novert[$id] = "";
            $hovert[$id] = "";
            $mpaye_amount[$id] = "";
            if ($data["payprd"] == "w" || $data["payprd"] == "f") {
                $tmpmon = date("j");
                $daycount = date("t");
                $dayweek = date("D");
                if (strtolower($dayweek) == $data["payprd_day"] && $date_day + 7 > $daycount) {
                    $process_comp_deductions = true;
                } else {
                    $process_comp_deductions = false;
                }
            } else {
                $process_comp_deductions = true;
            }
            //$data["emp_uif"] = sprint(($data["basic_sal"] + $data["all_travel"]) * ($data["emp_uif"]/100));
            $effective_basicsal = $data["basic_sal"] * $multiplier;
            /* we only changing basic sal for non hourly employees,
            			because for hourly employees we change the hours ($mutli)  */
            if ($data["saltyp"] != "h") {
                $data["basic_sal"] *= $multiplier;
            }
            if ($data["loaninstall"] > $data["loanamt"]) {
                $data["loaninstall"] = $data["loanamt"];
            }
            $data["comp_pension"] = sprint($effective_basicsal * ($data["comp_pension"] / 100));
            $data["comp_provident"] = sprint($effective_basicsal * ($data["comp_provident"] / 100));
            $data["emp_pension"] = sprint($effective_basicsal * ($data["emp_pension"] / 100));
            $data["emp_provident"] = sprint($effective_basicsal * ($data["emp_provident"] / 100));
            $data["emp_medical"] = sprint($data["emp_medical"] / $divisor);
            $data["comp_medical"] = sprint($data["comp_medical"] / $divisor);
            $data["emp_ret"] = sprint($data["emp_ret"] / $divisor);
            $data["comp_ret"] = sprint($data["comp_ret"] / $divisor);
            $data["loaninstall"] = sprint($data["loaninstall"] / $divisor);
            $data["all_travel"] = sprint($data["all_travel"] / $divisor);
            explodeDate($data["loandate"], $loana_year, $loana_month, $loana_day);
            if ($loana_year > $salyr || $loana_year == $salyr && $loana_month > $month) {
                $data["loanint"] = 0;
                $data["loaninstall"] = 0;
            }
        }
        if ($data['paytype'] == "Cash") {
            $paydetails = "Cash\n\t\t\t<input type='hidden' name='accid[{$id}]' value='0'>";
        } elseif ($data['paytype'] == "Ledger Account") {
            db_conn('core');
            $Sl = "SELECT accid,accname FROM accounts ORDER BY accname";
            $Rl = db_exec($Sl);
            $accounts = "<select name='account[{$id}]'>";
            while ($ad = pg_fetch_array($Rl)) {
                if (isset($account[$id]) && $account[$id] == $ad['accid']) {
                    $sel = "selected";
                } else {
                    $sel = "";
                }
                $accounts .= "<option value='{$ad['accid']}' {$sel}>{$ad['accname']}</option>";
            }
            $accounts .= "</select>";
            $paydetails = "{$accounts}\n\t\t\t\t<input type='hidden' name='accid[{$id}]' value='0'>";
        } else {
            db_conn('cubit');
            $Sl = "SELECT * FROM bankacct WHERE btype != 'int' AND div = '" . USER_DIV . "' ORDER BY accname ASC";
            $Ry = db_exec($Sl) or errDie("Unable to get bank account.");
            if (pg_numrows($Ry) < 1) {
                return "<li class='err'> There are no bank accounts found in Cubit.\n\t\t\t\t<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct Selection'>";
            }
            $banks = "<select name='accid[{$id}]'>";
            while ($acc = pg_fetch_array($Ry)) {
                $banks .= "<option value='{$acc['bankid']}'>{$acc['accname']} ({$acc['acctype']})</option>";
            }
            $banks .= "</select>";
            $paydetails = "{$banks}";
        }
        # fringe benefits
        $i = 0;
        db_conn("cubit");
        $sql = "SELECT * FROM fringebens WHERE div = '" . USER_DIV . "' ORDER BY fringeben";
        $rslt = db_exec($sql) or errDie("Unable to select fringe benefits from database.");
        if (pg_num_rows($rslt) < 1) {
            $fringes = "<table " . TMPL_tblDflts . ">";
            $fringes .= "<tr><td class='" . bg_class() . "' colspan='2' align='center'>None found in database.</td></tr>";
            $fringes .= "</table>";
        } else {
            $fringes = "<table " . TMPL_tblDflts . ">";
            while ($myFringe = pg_fetch_array($rslt)) {
                # check if employee has allowance
                $sql = "SELECT * FROM empfringe WHERE fringeid='{$myFringe['id']}' AND empnum='{$data['empnum']}' AND div = '" . USER_DIV . "'";
                $empRslt = db_exec($sql) or errDie("Unable to retrieve fringe benefit info from database.");
                if (pg_numrows($empRslt) > 0) {
                    $empFringe = pg_fetch_array($empRslt);
                    if (substr($empFringe["type"], 0, 4) == "Perc") {
                        $empFringe["amount"] = sprint($data["basic_sal"] * ($empFringe["amount"] / 100) / $divisor);
                    } else {
                        $empFringe['amount'] = sprint($empFringe['amount'] / $divisor);
                    }
                    $grossal += $empFringe["amount"];
                    $tmp_fringeaccs = $empFringe["accid"];
                    $tmp_fringebens = $empFringe["amount"];
                } else {
                    $tmp_fringeaccs = "0";
                    $tmp_fringebens = "0.00";
                }
                $fringes .= "\n\t\t\t\t\t<input type='hidden' name='fringeaccs[{$id}][]' value='{$tmp_fringeaccs}'>\n\t\t\t\t\t<input type='hidden' name='fringeid[{$id}][]' value='{$myFringe['id']}'>\n\t\t\t\t\t<input type='hidden' name='fringename[{$id}][]' value='{$myFringe['fringeben']}'>\n\t\t\t\t\t<tr>\n\t\t\t\t\t\t<td>{$myFringe['fringeben']}</td>\n\t\t\t\t\t\t<td>" . CUR . "</td>\n\t\t\t\t\t\t<td><input type='text' size='10' name='fringebens[{$id}][]' value='{$tmp_fringebens}'></td>\n\t\t\t\t\t</tr>";
                $i++;
            }
            $fringes .= "</table>";
        }
        # get allowances
        $i = 0;
        db_conn('cubit');
        $sql = "SELECT * FROM allowances WHERE div = '" . USER_DIV . "' ORDER BY allowance";
        $allowRslt = db_exec($sql) or errDie("Unable to select allowances from database.");
        if (pg_numrows($allowRslt) < 1) {
            $allowances = "<table " . TMPL_tblDflts . ">";
            $allowances .= "<tr><td>None</td></tr>";
            $allowances .= "</table>";
        } else {
            $allowances = "<table " . TMPL_tblDflts . ">";
            while ($myAllow = pg_fetch_array($allowRslt)) {
                # check if employee has allowance
                $sql = "SELECT * FROM empallow WHERE allowid='{$myAllow['id']}' AND empnum='{$data['empnum']}' AND div = '" . USER_DIV . "'";
                $empAllowRslt = db_exec($sql) or errDie("Unable to select allowance info from database.");
                if (pg_numrows($empAllowRslt) > 0) {
                    $dataAllow = pg_fetch_array($empAllowRslt);
                    $dataAllow['amount'] = sprint($dataAllow['amount'] / $divisor);
                    $grossal += $dataAllow["amount"];
                    $tmp_allowaccs = $dataAllow["accid"];
                    $tmp_allowances = $dataAllow["amount"];
                } else {
                    $tmp_allowaccs = $myAllow["accid"];
                    $tmp_allowances = "0.00";
                }
                $allowances .= "\n\t\t\t\t\t<input type='hidden' name='allowid[{$id}][]' value='{$myAllow['id']}'>\n\t\t\t\t\t<input type='hidden' name='allowname[{$id}][]' value='{$myAllow['allowance']}'>\n\t\t\t\t\t<input type='hidden' name='allowtax[{$id}][]' value='{$myAllow['add']}'>\n\t\t\t\t\t<input type='hidden' name='allowaccs[{$id}][]' value='{$tmp_allowaccs}'>\n\t\t\t\t\t<tr><td>{$myAllow['allowance']}</td>\n\t\t\t\t\t\t<td>" . CUR . "</td>\n\t\t\t\t\t\t<td><input type='text' size='10' name='allowances[{$id}][]' value='{$tmp_allowances}'></td>\n\t\t\t\t\t</tr>";
                $i++;
            }
            $allowances .= "</table>";
        }
        $subsistence = "";
        $subslst = new dbSelect("subsistence", "cubit", array("where" => "div='" . USER_DIV . "'", "order" => "name"));
        $subslst->run();
        if ($subslst->num_rows() > 0) {
            $i = 0;
            $subsistence .= "\n\t\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t\t<tr>\n\t\t\t\t\t\t<th>Name</th>\n\t\t\t\t\t\t<th>Amount</th>\n\t\t\t\t\t\t<th>Days</th>\n\t\t\t\t\t</tr>";
            $empsubs = new dbSelect("emp_subsistence", "cubit");
            while ($subs = $subslst->fetch_array()) {
                $sid = $subs["id"];
                $empsubs->setOpt(array("where" => "empnum='{$data['empnum']}' AND subid='{$sid}'"));
                $empsubs->run();
                if ($empsubs->num_rows() <= 0) {
                    $si["amount"] = "0.00";
                    $si["days"] = "0";
                    $si["accid"] = $subs["accid"];
                } else {
                    $si = $empsubs->fetch_array();
                }
                if ($subs["in_republic"] != "yes") {
                    $subs_int = true;
                }
                $subsistence .= "\n\t\t\t\t\t<input type='hidden' name='subsname[{$id}][{$sid}]' value='{$subs['name']}'>\n\t\t\t\t\t<input type='hidden' name='subsacc[{$id}][{$sid}]' value='{$si['accid']}'>\n\t\t\t\t\t<input type='hidden' name='subsrep[{$id}][{$sid}]' value='{$subs['in_republic']}'>\n\t\t\t\t\t<input type='hidden' name='subsmeal[{$id}][{$sid}]' value='{$subs['meals']}'>\n\t\t\t\t\t<tr bgcolor='" . bgcolor($i) . "'>\n\t\t\t\t\t\t<td>{$subs['name']}</td>\n\t\t\t\t\t\t<td nowrap>" . CUR . " <input type='text' size='5' name='subsamt[{$id}][{$sid}]' value='{$si['amount']}'></td>\n\t\t\t\t\t\t<td><input type='text' size='2' name='subsdays[{$id}][{$sid}]' value='{$si['days']}'></td>\n\t\t\t\t\t</tr>";
            }
            $subsistence .= "\n\t\t\t\t</table>";
        }
        # Deductions
        $i = 0;
        db_conn('cubit');
        $sql = "SELECT * FROM salded WHERE div = '" . USER_DIV . "' ORDER BY deduction";
        $deductRslt = db_exec($sql) or errDie("Unable to select deductions from database.");
        if (pg_numrows($deductRslt) < 1) {
            $deductions = "<table " . TMPL_tblDflts . ">";
            $deductions .= "<tr><td>None</td></tr>";
            $deductions .= "</table>";
        } else {
            $deductions = "<table " . TMPL_tblDflts . ">";
            while ($myDeduct = pg_fetch_array($deductRslt)) {
                # check if employee has deduction
                $sql = "SELECT * FROM empdeduct WHERE dedid='{$myDeduct['id']}' AND empnum='{$data['empnum']}' AND div = '" . USER_DIV . "'";
                $empDeductRslt = db_exec($sql) or errDie("Unable to select Deduction info from database.");
                if (pg_numrows($empDeductRslt) > 0) {
                    $dataDeduct = pg_fetch_array($empDeductRslt);
                    if ($dataDeduct["grosdeduct"] == "y") {
                        $deductions_msg = "(Before PAYE)";
                        $sal_calcfrom = $grossal;
                    } else {
                        $deductions_msg = "";
                        $sal_calcfrom = $data["basic_sal"];
                    }
                    if ($dataDeduct['type'] == "Amount") {
                        $dataDeduct['amount'] = sprint($dataDeduct['amount'] / $divisor);
                    } else {
                        $dataDeduct['amount'] = sprint($sal_calcfrom * $dataDeduct['amount'] / 100 / $divisor);
                    }
                    // calculate employer contribution to deduction
                    if ($dataDeduct["employer_type"] == "Amount") {
                        $dataDeduct["employer_amount"] = sprint($dataDeduct["employer_amount"] / $divisor);
                    } else {
                        $dataDeduct["employer_amount"] = sprint($dataDeduct["amount"] * $dataDeduct["employer_amount"] / 100 / $divisor);
                    }
                    $tmp_deductions = $dataDeduct["amount"];
                    $tmp_dedaccs = $dataDeduct["accid"];
                    $tmp_emp_ded = $dataDeduct["employer_amount"];
                } else {
                    $tmp_deductions = "0.00";
                    $tmp_emp_ded = "0.00";
                    $tmp_dedaccs = $myDeduct["accid"] != 0 ? $myDeduct["accid"] : $myDeduct["expaccid"];
                    $deductions_msg = "";
                }
                # check if we should be using deductions
                if ($data['emp_usescales'] == "1" and $myDeduct['type'] == "Percentage") {
                    # check if this deduction has scales
                    $get_scales = "SELECT * FROM salded_scales WHERE saldedid = '{$myDeduct['id']}' LIMIT 1";
                    $run_scales = db_exec($get_scales) or errDie("Unable to get deduction scale information.");
                    if (pg_numrows($run_scales) > 0) {
                        # scales exist
                        $get_perc = "\n\t\t\t\t\t\t\tSELECT * FROM salded_scales \n\t\t\t\t\t\t\tWHERE scale_from <= '{$data['basic_sal']}' AND scale_to >= '{$data['basic_sal']}' AND saldedid = '{$myDeduct['id']}' \n\t\t\t\t\t\t\tLIMIT 1";
                        $run_perc = db_exec($get_perc) or errDie("Unable to get deduction scale information.");
                        if (pg_numrows($run_perc) > 0) {
                            # found a matching scale for this scaled duduction for a customer using scales ....
                            $scale_arr = pg_fetch_array($run_perc);
                            $tmp_deductions = sprint($data['basic_sal'] / 100 * $scale_arr['scale_amount']);
                        }
                    }
                }
                $deductions .= "\n\t\t\t\t\t<input type='hidden' size='10' name='deductid[{$id}][]' value='{$myDeduct['id']}'>\n\t\t\t\t\t<input type='hidden' size='30' name='deductname[{$id}][]' value='{$myDeduct['deduction']}'>\n\t\t\t\t\t<input type='hidden' size='10' name='deducttax[{$id}][]' value='{$myDeduct['add']}'>\n\t\t\t\t\t<input type='hidden' name='dedaccs[{$id}][]' value='{$tmp_dedaccs}'>\n\t\t\t\t\t<tr>\n\t\t\t\t\t\t<td>{$myDeduct['deduction']} {$deductions_msg}</td>\n\t\t\t\t\t\t<td>" . CUR . "</td>\n\t\t\t\t\t\t<td><input type='text' size='10' name='deductions[{$id}][]' value='{$tmp_deductions}'></td>\n\t\t\t\t\t\t<td>" . CUR . "</td>\n\t\t\t\t\t\t<td><input type='hidden' size='10' name='employer_deductions[{$id}][]' value='{$tmp_emp_ded}'></td>\n\t\t\t\t\t</tr>";
                $i++;
            }
            $deductions .= "</table>";
        }
        $rt = "";
        db_conn('cubit');
        $Sl = "SELECT * FROM rbs ORDER BY name";
        $Rl = db_exec($Sl) or errDie("Unable to get data.");
        $i = 0;
        if (pg_num_rows($Rl) > 0) {
            $rt = "<table " . TMPL_tblDflts . ">";
            while ($td = pg_fetch_array($Rl)) {
                if (!isset($rbsa[$id][$td['id']])) {
                    $rbsa[$id][$td['id']] = "";
                }
                $rt .= "\n\t\t\t\t\t<tr>\n\t\t\t\t\t\t<td><input type='hidden' name='rbs[{$id}][{$td['id']}]' value='{$td['id']}'>{$td['name']}</td>\n\t\t\t\t\t\t<td>" . CUR . "</td>\n\t\t\t\t\t\t<td><input type='text' size='10' name='rbsa[{$id}][{$td['id']}]' value='" . $rbsa[$id][$td['id']] . "' class='right'></td>\n\t\t\t\t\t</tr>";
                $i++;
            }
            $rt .= "</table>";
        } else {
            $rt .= "None";
        }
        $salarr = array("m" => "Per Month", "w" => "Per Week", "f" => "Fortnightly", "h" => "Per Hour");
        $salnarr = array("d" => "Day(s)", "h" => "Hour(s)");
        $saltype = $salarr[$data['saltyp']];
        if (!isset($multi[$id])) {
            $multi[$id] = $data["saltyp"] == "h" ? $multiplier : 1;
        }
        $multi[$id] = round($multi[$id]);
        if ($data['saltyp'] == 'd' || $data['saltyp'] == 'h') {
            $salntype = $salnarr[$data['saltyp']];
            $multi_show = "x <input type='text' size='3' name='multi[{$id}]' value='{$multi[$id]}'> {$salntype}";
        } else {
            $multi_show = "<input type='hidden' name='multi[{$id}]' value='{$multi[$id]}'>";
            $saltype = "";
        }
        if (isset($mpaye[$id])) {
            $ch = "checked=yes";
        } else {
            $ch = "";
        }
        if ($data["payprd"] == "m" || $data["payprd"] == "d") {
            // count the amount of weekdays in this month
            $workdays = 0;
            for ($i = 1; $i <= date("t", mktime(0, 0, 0, $month, 1, date("Y"))); ++$i) {
                $wd = date("w", mktime(0, 0, 0, $month, $i, date("Y")));
                if ($wd != 0 && $wd != 6) {
                    ++$workdays;
                }
            }
            // hours per day calculation
            $hpd = $data["hpweek"] / 5;
            if (!isset($wh_total[$id])) {
                $wh_total[$id] = $workdays * $hpd;
            }
            if (!isset($wh_actual[$id])) {
                $wh_actual[$id] = $wh_total[$id];
            }
        }
        if ($data["payprd"] == "w") {
            if (!isset($wh_total[$id])) {
                $wh_total[$id] = $data["hpweek"];
            }
            if (!isset($wh_actual[$id])) {
                $wh_actual[$id] = $wh_total[$id];
            }
        }
        if ($data["payprd"] == "f") {
            if (!isset($wh_total[$id])) {
                $wh_total[$id] = $data["hpweek"] * 2;
            }
            if (!isset($wh_actual[$id])) {
                $wh_actual[$id] = $wh_total[$id];
            }
        }
        $js_workhours_fields .= "\n\t\t\t<script>\n\t\t\t\tf_sal[{$id}]\t\t= sf.elements['basic_sal[{$id}]'];\n\t\t\t\tf_salbonus[{$id}] = sf.elements['sal_bonus[{$id}]'];\n\t\t\t\tf_whtot[{$id}]\t= sf.elements['wh_total[{$id}]'];\n\t\t\t\tf_whact[{$id}]\t= sf.elements['wh_actual[{$id}]'];\n\t\t\t\tf_cpension[{$id}]\t= sf.elements['comp_pension[{$id}]'];\n\t\t\t\tf_epension[{$id}] = sf.elements['emp_pension[{$id}]'];\n\t\t\t\tf_cprov[{$id}]\t= sf.elements['comp_provident[{$id}]'];\n\t\t\t\tf_eprov[{$id}]\t= sf.elements['emp_provident[{$id}]'];\n\t\t\t\t//f_cuif[{$id}]\t\t= sf.elements['comp_uif[{$id}]'];\n\t\t\t\t//f_euif[{$id}]\t\t= sf.elements['emp_uif[{$id}]'];\n\t\t\t\tf_cother[{$id}]\t= sf.elements['comp_other[{$id}]'];\n\t\t\t\tf_eother[{$id}]\t= sf.elements['emp_other[{$id}]'];\n\n\t\t\t\tdb_cpension[{$id}]\t= " . $db["comp_pension"] . ";\n\t\t\t\tdb_epension[{$id}]\t= " . $db["emp_pension"] . ";\n\t\t\t\tdb_cprov[{$id}]\t\t= " . $db["comp_provident"] . ";\n\t\t\t\tdb_eprov[{$id}]\t\t= " . $db["emp_provident"] . ";\n\t\t\t\t//db_cuif[{$id}]\t\t= " . $db["comp_uif"] . ";\n\t\t\t\t//db_euif[{$id}]\t\t= " . $db["emp_uif"] . ";\n\t\t\t\tdb_cother[{$id}]\t= " . $db["comp_other"] . ";\n\t\t\t\tdb_eother[{$id}]\t= " . $db["emp_other"] . ";\n\n\t\t\t\tval_sal[{$id}] = -1;\n\t\t\t</script>";
        vsprint($data["basic_sal"]);
        $out .= "\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<input type='hidden' name='emps[{$id}]' value='{$id}'>\n\t\t\t\t<input type='hidden' name='saltyp[{$id}]' value='{$data['saltyp']}'>\n\t\t\t\t<input type='hidden' name='process_comp_deductions[{$id}]' value='{$process_comp_deductions}'>\n\t\t\t\t<input type='hidden' name='divisor[{$id}]' value='{$divisor}'>\n\t\t\t\t<td nowrap>{$data['enum']}</td>\n\t\t\t\t<td>{$data['sname']}, {$data['fnames']}</td>\n\t\t\t\t<td nowrap><input type='text' size='8' name='basic_sal[{$id}]' value='{$data['basic_sal']}' class='right' onChange='changedfield({$id});'>{$saltype} {$multi_show}</td>";
        if (isset($d)) {
            $out .= "\n\t\t\t\t<input type='hidden' name='wh_total' value='1'>\n\t\t\t\t<input type='hidden' name='wh_actual' value='1'>";
        } else {
            $out .= "\n\t\t\t\t<td nowrap><input type='text' size='10' name='wh_total[{$id}]' value='{$wh_total[$id]}' class='right' onChange='workhours({$id});'></td>\n\t\t\t\t<td nowrap><input type='text' size='10' name='wh_actual[{$id}]' value='{$wh_actual[$id]}' class='right' onChange='workhours({$id});'></td>";
        }
        if (!isset($abonus[$id])) {
            $abonus = 0;
        }
        $out .= "\n\t\t\t\t<td nowrap><input type='text' size='5' name='novert[{$id}]' value='{$novert[$id]}' class='right'> Hrs</td>\n\t\t\t\t<td nowrap><input type='text' size='5' name='hovert[{$id}]' value='{$hovert[$id]}' class='right'> Hrs</td>\n\t\t\t\t<td nowrap><input type='hidden' size='8' name='bonus[{$id}]' value='0' class='right'><input type='text' size='8' name='abonus[{$id}]' value='{$abonus[$id]}' class='right'></td>\n\t\t\t\t<input type='hidden' name='annual[{$id}]' value='0' />\n\t\t\t\t<!--<td nowrap><input type='text' size='8' name='annual[{$id}]' value='{$annual[$id]}' class='right'></td>-->\n\t\t\t\t<td nowrap><input type='text' size='8' name='commission[{$id}]' value='{$data['commission']}' class='right'></td>\n\t\t\t\t<td nowrap>R<input type='text' size='8' name='all_travel[{$id}]' value='{$data['all_travel']}' class='right'></td>\n\t\t\t\t<td nowrap>R<input type='text' size='8' name='loaninstall[{$id}]' value='{$data['loaninstall']}' class='right'></td>\n\t\t\t\t<td nowrap>R<input type='text' size='8' name='comp_pension[{$id}]' value='{$data['comp_pension']}' class='right'></td>\n\t\t\t\t<td nowrap>R<input type='text' size='8' name='emp_pension[{$id}]' value='{$data['emp_pension']}' class='right'></td>\n\t\t\t\t<td nowrap>R<input type='text' size='8' name='comp_provident[{$id}]' value='{$data['comp_provident']}' class='right'></td>\n\t\t\t\t<td nowrap>R<input type='text' size='8' name='emp_provident[{$id}]' value='{$data['emp_provident']}' class='right'></td>\n\t\t\t\t<!--\n\t\t\t\t<td nowrap>R<input type='text' size='8' name='comp_uif[{$id}]' value='{$data['comp_uif']}' class='right'></td>\n\t\t\t\t<td nowrap>R<input type='text' size='8' name='emp_uif[{$id}]' value='{$data['emp_uif']}' class='right'></td>\n\t\t\t\t//-->\n\t\t\t\t<td nowrap>R<input type='text' size='8' name='comp_ret[{$id}]' value='{$data['comp_ret']}' class='right'></td>\n\t\t\t\t<td nowrap>R<input type='text' size='8' name='emp_ret[{$id}]' value='{$data['emp_ret']}' class='right'></td>\n\t\t\t\t<td nowrap>R<input type='text' size='8' name='comp_medical[{$id}]' value='{$data['comp_medical']}' class='right'></td>\n\t\t\t\t<td nowrap>R<input type='text' size='8' name='emp_medical[{$id}]' value='{$data['emp_medical']}' class='right'></td>\n\t\t\t\t<input type=hidden name='comp_other[{$id}]' value='0'>\n\t\t\t\t<input type=hidden name='emp_other[{$id}]' value='0'>\n\t\t\t\t<!--\n\t\t\t\t<td nowrap>R<input type='text' size='8' name='comp_other[{$id}]' value='{$data['comp_other']}' class='right'></td>\n\t\t\t\t<td nowrap>R<input type='text' size='8' name='emp_other[{$id}]' value='{$data['emp_other']}' class='right'></td>\n\t\t\t\t//-->\n\t\t\t\t<td>{$paydetails}</td>\n\t\t\t\t<td>\n\t\t\t\t\t<table>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<td><input type='checkbox' name='mpaye[{$id}]' {$ch}></td>\n\t\t\t\t\t\t\t<td><input type='text' size='8' name='mpaye_amount[{$id}]' value='{$mpaye_amount[$id]}'></td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t</table>\n\t\t\t\t</td>\n\t\t\t\t<td>{$fringes}</td>\n\t\t\t\t<td>{$allowances}</td>\n\t\t\t\t<td>{$subsistence}<!--%%EXCHANGE%%--></td>\n\t\t\t\t<td>{$deductions}</td>\n\t\t\t\t<td>{$rt}</td>\n\t\t\t</tr>";
    }
    if (!isset($id)) {
        header("Location: ../admin-employee-view.php?err=Please select at least one employee.");
        exit;
    }
    // replace the exchange rate place holder with the exchange rate form field
    if ($subs_int) {
        $exch = "\n\t\t\t<input type='hidden' name='subs_exch' value='1'>\n\t\t\t<li class='err'>Please calculate the rand amount prior to completing the amount above.</li>";
        // 			<tr class='".bg_class()."'>
        // 				<th class='".bg_class()."'>Exchange (ZAR-USD):</th>
        // 				<td><input type='text' name='subs_exch' value='".xrate_get("USD")."'></td>
        // 			</tr>";
        $out = str_replace("<!--%%EXCHANGE%%-->", $exch, $out);
    }
    $out .= "\n\t\t\t<tr><td><br></td></tr>\n\t\t\t{$send}\n\t\t\t<tr>\n\t\t\t\t<td colspan='9' align='right' nowrap='t'>\n\t\t\t\t\t<input type='submit' name='btn_back' value='&laquo; Correction'>\n\t\t\t\t\t<input type='submit' value='Confirm &raquo;'>\n\t\t\t\t</td>\n\t\t\t\t<td colspan='10' align='right' nowrap='t'>\n\t\t\t\t\t<input type='submit' name='btn_back' value='&laquo; Correction'>\n\t\t\t\t\t<input type='submit' value='Confirm &raquo;'>\n\t\t\t\t</td>\n\t\t\t</tr>\n\t\t</table>\n\t\t</form>\n\t\t<script>\n\t\t\tfunction monthchange(mondd) {\n\t\t\t\t" . implode("\n", $jsbonus_clear) . "\n\t\t\t\tswitch ( mondd.value ) {\n\t\t\t\tcase '1':\n\t\t\t\t\t" . implode("\n", $jsbonus[1]) . "\n\t\t\t\t\tbreak;\n\t\t\t\tcase '2':\n\t\t\t\t\t" . implode("\n", $jsbonus[2]) . "\n\t\t\t\t\tbreak;\n\t\t\t\tcase '3':\n\t\t\t\t\t" . implode("\n", $jsbonus[3]) . "\n\t\t\t\t\tbreak;\n\t\t\t\tcase '4':\n\t\t\t\t\t" . implode("\n", $jsbonus[4]) . "\n\t\t\t\t\tbreak;\n\t\t\t\tcase '5':\n\t\t\t\t\t" . implode("\n", $jsbonus[5]) . "\n\t\t\t\t\tbreak;\n\t\t\t\tcase '6':\n\t\t\t\t\t" . implode("\n", $jsbonus[6]) . "\n\t\t\t\t\tbreak;\n\t\t\t\tcase '7':\n\t\t\t\t\t" . implode("\n", $jsbonus[7]) . "\n\t\t\t\t\tbreak;\n\t\t\t\tcase '8':\n\t\t\t\t\t" . implode("\n", $jsbonus[8]) . "\n\t\t\t\t\tbreak;\n\t\t\t\tcase '9':\n\t\t\t\t\t" . implode("\n", $jsbonus[9]) . "\n\t\t\t\t\tbreak;\n\t\t\t\tcase '10':\n\t\t\t\t\t" . implode("\n", $jsbonus[10]) . "\n\t\t\t\t\tbreak;\n\t\t\t\tcase '11':\n\t\t\t\t\t" . implode("\n", $jsbonus[11]) . "\n\t\t\t\t\tbreak;\n\t\t\t\tcase '12':\n\t\t\t\t\t" . implode("\n", $jsbonus[12]) . "\n\t\t\t\t\tbreak;\n\t\t\t\t}";
    //".implode("\n", $uif_calc)."
    $out .= "\n\t\t\t}\n\t\t</script>\n\t\t<script>\n\t\t\tsf = document.getElementById('salfrm');\n\t\t\tf_sal = new Array();\n\t\t\tf_salbonus = new Array();\n\t\t\tf_whtot = new Array();\n\t\t\tf_whact = new Array();\n\t\t\tf_cpension = new Array();\n\t\t\tf_epension = new Array();\n\t\t\tf_cprov = new Array();\n\t\t\tf_eprov = new Array();\n\t\t\t//f_cuif = new Array();\n\t\t\t//f_euif = new Array();\n\t\t\tf_cother = new Array();\n\t\t\tf_eother = new Array();\n\n\t\t\tdb_cpension = new Array();\n\t\t\tdb_epension = new Array();\n\t\t\tdb_cprov = new Array();\n\t\t\tdb_eprov = new Array();\n\t\t\t//db_cuif = new Array();\n\t\t\t//db_euif = new Array();\n\t\t\tdb_cother = new Array();\n\t\t\tdb_eother = new Array();\n\n\t\t\tval_sal = new Array();\n\t\t</script>\n \t\t{$js_workhours_fields}\n\t\t<script>\n\t\t\t// changing the workhours\n\t\t\tfunction workhours(id) {\n\t\t\t\tif ( val_sal[id] < 0 ) val_sal[id] = parseFloat(f_sal[id].value);\n\n\t\t\t\tval_whtot\t= parseFloat(f_whtot[id].value);\n\t\t\t\tval_whact\t= parseFloat(f_whact[id].value);\n\n\t\t\t\tif ( val_whtot >= val_whact ) {\n\t\t\t\t\tp = val_whact / val_whtot;\n\n\t\t\t\t\t// calculate the new basic salary\n\t\t\t\t\tx = val_sal[id] * p;\n\t\t\t\t\tx = x.toFixed(2);\n\t\t\t\t\tf_sal[id].value = x;\n\n\t\t\t\t\t// calculate the new values\n\t\t\t\t\tval_cpension \t= x * db_cpension[id] / 100;\n\t\t\t\t\tval_epension \t= x * db_epension[id] / 100;\n\t\t\t\t\tval_cprov\t\t= x * db_cprov[id] / 100;\n\t\t\t\t\tval_eprov\t\t= x * db_eprov[id] / 100;\n\t\t\t\t\t//val_cuif\t\t= x * db_cuif[id] / 100;\n\t\t\t\t\t//val_euif\t\t= x * db_euif[id] / 100;\n\t\t\t\t\tval_cother\t\t= x * db_cother[id] / 100;\n\t\t\t\t\tval_eother\t\t= x * db_eother[id] / 100;\n\n\t\t\t\t\tval_cpension \t= val_cpension.toFixed(2);\n\t\t\t\t\tval_epension \t= val_epension.toFixed(2);\n\t\t\t\t\tval_cprov \t\t= val_cprov.toFixed(2);\n\t\t\t\t\tval_eprov\t\t= val_eprov.toFixed(2);\n\t\t\t\t\t//val_cuif\t\t= val_cuif.toFixed(2);\n\t\t\t\t\t//val_euif\t\t= val_euif.toFixed(2);\n\t\t\t\t\tval_cother\t\t= val_cother.toFixed(2);\n\t\t\t\t\tval_eother\t\t= val_eother.toFixed(2);\n\n\t\t\t\t\tf_cpension[id].value\t= val_cpension;\n\t\t\t\t\tf_epension[id].value \t= val_epension;\n\t\t\t\t\tf_cprov[id].value \t\t= val_cprov;\n\t\t\t\t\tf_eprov[id].value\t\t= val_eprov;\n\t\t\t\t\t//f_cuif[id].value\t\t= val_cuif;\n\t\t\t\t\t//f_euif[id].value\t\t= val_euif;\n\t\t\t\t\tf_cother[id].value\t\t= val_cother;\n\t\t\t\t\tf_eother[id].value\t\t= val_eother;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfunction changedfield(id) {\n\t\t\t\tval_whtot\t= parseFloat(f_whtot[id].value);\n\t\t\t\tval_whact\t= parseFloat(f_whact[id].value);\n\n\t\t\t\tp = val_whtot / val_whact;\n\n\t\t\t\tval_sal[id] = parseFloat(f_sal[id].value) * p;\n\t\t\t\tval_sal[id] = val_sal[id].toFixed(2);\n\t\t\t}\n\n\t\t\tmonthchange(document.getElementById('salfrm').elements['month']);\n\t\t</script>";
    return $out;
}
function write()
{
    extract($_POST);
    if (isset($back)) {
        return enter();
    }
    if ($err = validate($_POST)) {
        return enter($err);
    }
    /* check account number */
    if (!isset($cusnum)) {
        $qry = new dbSelect("customers", "cubit", grp(m("where", "accno='{$accno}' AND div='" . USER_DIV . "'")));
        $qry->run();
        if ($qry->num_rows() > 0) {
            return enter("<li class='err'>A Customer/Client with this account number already exists.</li>");
        }
    }
    $data = qryCategory($category);
    $catname = $data["category"];
    $data = qryClass($class);
    $classname = $data["classname"];
    $data = qryPricelist($pricelist);
    $plist = $data["listname"];
    $curr = getSymbol($fcid);
    $currency = $curr["symbol"];
    /* fix numerics */
    $traddisc += 0;
    $setdisc += 0;
    $pricelist += 0;
    $overdue += 0;
    $credterm += 0;
    $credlimit += 0;
    pglib_transaction("BEGIN");
    /* insert into database / update */
    $cols = grp(m("deptid", $deptid), m("accno", $accno), m("surname", $surname), m("title", $title), m("init", $init), m("location", $location), m("fcid", $fcid), m("currency", $currency), m("category", $category), m("class", $class), m("addr1", $addr1), m("paddr1", $paddr1), m("del_addr1", $del_addr1), m("vatnum", $vatnum), m("contname", $contname), m("bustel", $bustel), m("tel", $tel), m("cellno", $cellno), m("fax", $fax), m("email", $email), m("url", $url), m("traddisc", $traddisc), m("setdisc", $setdisc), m("pricelist", $pricelist), m("chrgint", $chrgint), m("overdue", $overdue), m("intrate", $intrate), m("chrgvat", "yes"), m("credterm", $credterm), m("odate", $odate), m("credlimit", $credlimit), m("blocked", "no"), m("deptname", $deptname), m("classname", $classname), m("catname", $catname), m("lead_source", $lead_source), m("comments", $comments), m("sales_rep", $sales_rep), m("div", USER_DIV), m("bankname", $bankname), m("branname", $branname), m("brancode", $brancode), m("bankaccname", $bankaccname), m("bankaccno", $bankaccno), m("bankacctype", $bankacctype), m("team_id", $team_id), m("registration", $registration));
    $where = wgrp(m("cusnum", isset($cusnum) ? $cusnum : 0));
    $qryi = new dbUpdate("customers", "cubit", $cols, $where);
    $qryi->run(DB_REPLACE);
    /* get id */
    if (!isset($cusnum)) {
        $cusnum = pglib_lastid("customers", "cusnum");
        $newcust = true;
        // used later to check if we should create the ledgers
    }
    /* add to/update contact list */
    $cols = grp(m("surname", $surname), m("title", $title), m("ref", "Customer"), m("tell", $tel), m("tell_office", $bustel), m("cell", $cellno), m("fax", $fax), m("email", $email), m("hadd", $addr1), m("padd", $paddr1), m("del_addr", $del_addr1), m("date", $odate), m("cust_id", $cusnum), m("con", "No"), m("lead_source", $lead_source), m("description", $comments), m("account_type", "Customer"), m("accountname", $surname), m("account_id", $cusnum), m("by", USER_NAME), m("div", USER_DIV));
    $where = wgrp(m("cust_id", $cusnum));
    $qryi->setTable("cons", "cubit");
    $qryi->setOpt($cols, $where);
    $qryi->run(DB_REPLACE);
    if (PRD_STATE == "py") {
        $audit_db = YR_NAME . "_audit";
        $actyear = PYR_NAME;
    } else {
        $audit_db = "audit";
        $actyear = YR_NAME;
    }
    if (isset($newcust)) {
        /* create customer ledgers */
        for ($i = 1; $i <= 12; ++$i) {
            /* period customer ledger */
            $cols = grp(m("cusnum", $cusnum), m("contra", 0), m("edate", $odate), m("sdate", raw("CURRENT_DATE")), m("eref", 0), m("descript", "Balance"), m("credit", 0), m("debit", 0), m("cbalance", 0), m("dbalance", 0), m("div", USER_DIV));
            $qryi->setTable("custledger", "{$i}");
            $qryi->setOpt($cols);
            $qryi->run(DB_INSERT);
            /* audit customer ledger */
            $cols = grp(m("cusnum", $cusnum), m("contra", 0), m("edate", $odate), m("sdate", raw("CURRENT_DATE")), m("eref", 0), m("descript", "Balance"), m("credit", 0), m("debit", 0), m("cbalance", 0), m("dbalance", 0), m("div", USER_DIV), m("actyear", $actyear));
            $qryi->setTable(getMonthName($i) . "_custledger", $audit_db);
            $qryi->setOpt($cols);
            $qryi->run(DB_INSERT);
        }
        if (isset($crm)) {
            header("Location: crm/tokens-new.php?value={$surname}");
            exit;
        }
        if ($re != "not") {
            $qryi->setTable("invoices", "cubit");
            $cols = grp(m("cusnum", $cusnum));
            $where = wgrp(m("invid", $re));
            $qryi->setOpt($cols, $where);
            $qryi->run(DB_UPDATE);
            header("Location: cust-credit-stockinv.php?invid={$re}&cont=1&letters=");
            exit;
        }
    }
    pglib_transaction("COMMIT") or errDie("Unable to add customer to database. (TC)");
    // Update documents
    $sql = "SELECT * FROM crm.ctmp_docs WHERE session='{$_REQUEST['CUBIT_SESSION']}'";
    $ctdoc_rslt = db_exec($sql) or errDie("Unable to retrieve docs.");
    while ($ctdoc_data = pg_fetch_array($ctdoc_rslt)) {
        $sql = "INSERT INTO crm.customer_docs (cusnum, file, type, filename, size)\n\t\tVALUES ('{$cusnum}', '{$ctdoc_data['file']}', '{$ctdoc_data['type']}',\n\t\t\t\t'{$ctdoc_data['filename']}', '{$ctdoc_data['size']}')";
        db_exec($sql) or errDie("Unable to save files to customer.");
        $sql = "DELETE FROM crm.ctmp_docs WHERE id='{$ctdoc_data['id']}'";
        db_exec($sql) or errDie("Unable to remove tmp file.");
    }
    $sql = "SELECT * FROM cubit.cons WHERE cust_id='{$cusnum}'";
    $con_rslt = db_exec($sql) or errDie("Unable to retrieve contact.");
    $con_data = pg_fetch_array($con_rslt);
    if (pg_num_rows($con_rslt)) {
        $con_out = "\n\t\t<a href='javascript:popupOpen(\"groupware/conper-add.php?type=conn&id={$con_data['id']}\")'>\n\t\t\tAdd Sub Contact\n\t\t</a>";
    } else {
        $con_out = "";
    }
    onthespot_declare();
    $OUT = "\n\t<table " . TMPL_tblDflts . ">\n\t<tr>\n\t\t<th>Customer add/update successful.</th>\n\t</tr>\n\t<tr class='datacell'>\n\t\t<td>\n\t\t\tNew Customer <b>{$surname}</b>,\n\t\t\thas been successfully added to the system.\n\t\t\t{$con_out}</td>\n\t</tr>\n\t</table>";
    $OUT .= onthespot_out(mkQuickLinks(ql("customers-new.php", "Add Customers"), ql("customers-view.php", "View Customers")));
    return $OUT;
}
예제 #28
0
function write()
{
    if (PRD_STATE == 'py') {
        return "<center><li class='err'>Please update your transaction year before closing financial year: Click <a href='../set-period-use.php'>here</a> to do so.</li></center>";
    }
    // Check if last database has not been reached
    if (YR_DB == "yr10") {
        $OUTPUT = "<center>Warning : The System has reached its Last year of operation, Please contact the support team to reset.";
        require "template.php";
    }
    $i = substr(YR_DB, 2) + 1;
    $nextyr = "yr" . $i;
    $sdate = DATE_STD;
    pglib_transaction("BEGIN");
    global $PRDMON;
    $stmnt = financialStatements::trialbal(array("heading_3" => "Trial Balance: Year End", "month_to" => $PRDMON[12]), true);
    save_statement($stmnt, "trial_bal");
    $stmnt = financialStatements::incomestmnt(array("customized" => true, "this_year_year_to_date" => true, "heading_3" => "Income Statement: Year End", "budget" => true, "this_year_budget" => true, "month_to" => $PRDMON[12]), true);
    save_statement($stmnt, "income_stmnt");
    $stmnt = financialStatements::balsheet(array("customized" => true, "this_year_year_to_date" => true, "heading_3" => "Balance Sheet: Year End", "month_to" => $PRDMON[12]), true);
    save_statement($stmnt, "bal_sheet");
    # Copy balance sheet table
    core_connect();
    $sql = "SELECT * FROM bal_sheet";
    $balSheet = db_exec($sql) or errDie("Could not copy Balances to year DB", SELF);
    while ($bal = pg_fetch_array($balSheet)) {
        db_conn(YR_DB);
        $sql = "INSERT INTO bal_sheet (type, ref, value, div) VALUES ('{$bal['type']}', '{$bal['ref']}', '{$bal['value']}', '{$bal['div']}')";
        $inRslt = db_exec($sql) or print $sql;
    }
    core_connect();
    $sql = "SELECT * FROM core.trial_bal WHERE period='12'";
    $trialBal = db_exec($sql) or errDie("Could not copy Balances to year DB", SELF);
    while ($bal = pg_fetch_array($trialBal)) {
        $sql = "\n\t\t\tINSERT INTO " . YR_DB . ".year_balance (\n\t\t\t\taccid, topacc, accnum, accname, debit, credit, div\n\t\t\t) VALUES (\n\t\t\t\t'{$bal['accid']}', '{$bal['topacc']}', '{$bal['accnum']}', '{$bal['accname']}', '{$bal['debit']}', '{$bal['credit']}', '{$bal['div']}'\n\t\t\t)";
        $inRslt = db_exec($sql) or errDie("Failed to store year balance.");
    }
    //$sql = "CREATE TABLE \"".YR_DB."\".stkledger AS SELECT * FROM core.stkledger";
    //$rslt = db_exec_safe($sql);
    // make a copy from the trial balance
    $sql = "DROP TABLE \"" . YR_DB . "\".trial_bal";
    //$rslt = db_exec_safe($sql);
    $sql = "CREATE TABLE \"" . YR_DB . "\".trial_bal AS SELECT * FROM core.trial_bal";
    $rslt = db_exec_safe($sql);
    // recreate the trial balance actual view
    $sql = "\n\t\tCREATE OR REPLACE VIEW \"" . YR_DB . "\".trial_bal_actual AS\n\t\tSELECT tb.accid, tb.topacc, tb.accnum, tb.accname, tb.vat, tb.div, tb.acctype, \n\t\t\tCASE\n\t\t\t\tWHEN tb.period = 1 THEN tb.debit\n\t\t\t\tELSE tb.debit - atb.debit\n\t\t\tEND AS debit,\n\t\t\tCASE\n\t\t\t\tWHEN tb.period = 1 THEN tb.credit\n\t\t\t\tELSE tb.credit - atb.credit\n\t\t\tEND AS credit, tb.month, tb.period\n\t\tFROM \"" . YR_DB . "\".trial_bal tb LEFT JOIN \"" . YR_DB . "\".trial_bal atb\n\t\t\tON tb.period = (atb.period::int + 1) AND tb.accid = atb.accid;";
    db_exec_safe($sql);
    /* fetch customer balances */
    $custs = qryCustomer(false, "cusnum");
    $custdebit = array();
    $custcredit = array();
    while ($cd = $custs->fetch_array()) {
        $qry = new dbSelect("custledger", $PRDMON['12'], grp(m("cols", "cbalance, dbalance"), m("where", "cusnum='{$cd['cusnum']}'"), m("order", "id DESC"), m("limit", 1)));
        $qry->run();
        if ($qry->num_rows() <= 0) {
            $custcredit[$cd["cusnum"]] = 0;
            $custdebit[$cd["cusnum"]] = 0;
        } else {
            $qry->fetch_array();
            $custcredit[$cd["cusnum"]] = $qry->d["cbalance"];
            $custdebit[$cd["cusnum"]] = $qry->d["dbalance"];
        }
    }
    /* fetch supplier balances */
    $supps = qrySupplier(false, "supid");
    $suppdebit = array();
    $suppcredit = array();
    while ($sd = $supps->fetch_array()) {
        $qry = new dbSelect("suppledger", $PRDMON['12'], grp(m("cols", "cbalance, dbalance"), m("where", "supid='{$sd['supid']}'"), m("order", "id DESC"), m("limit", 1)));
        $qry->run();
        if ($qry->num_rows() <= 0) {
            $suppcredit[$sd["supid"]] = 0;
            $suppdebit[$sd["supid"]] = 0;
        } else {
            $qry->fetch_array();
            $suppcredit[$sd["supid"]] = $qry->d["cbalance"];
            $suppdebit[$sd["supid"]] = $qry->d["dbalance"];
        }
    }
    /* copy the inventory ledger */
    for ($i = 1; $i <= 12; ++$i) {
        $mname = strtolower(getMonthName($i));
        $sql = "CREATE TABLE audit.{$mname}_stkledger \n\t\t\t\tAS \n\t\t\t\tSELECT * FROM \"{$i}\".stkledger";
        db_exec($sql) or errDie("Error copying inventory ledger (P{$i}).");
    }
    // Empty All Period Databases
    for ($i = 1; $i <= 14; $i++) {
        db_conn($i);
        $sql = "TRUNCATE TABLE transect;";
        $sql .= "TRUNCATE TABLE ledger;";
        $sql .= "TRUNCATE TABLE custledger;";
        $sql .= "TRUNCATE TABLE suppledger;";
        $sql .= "TRUNCATE TABLE empledger;";
        db_exec($sql) or errDie("Unable to empty Period databases", SELF);
    }
    $qryi = new dbUpdate();
    recreateAudit();
    /* FP AUDIT FIX 
    		for ($p = 1; $p <= 12; ++$p) {
    			$monnum = $PRDMON[$i];
    			$monname = strtolower(getMonthName($i));
    		}
    	*/
    /* create the customer ledger balance entries */
    $custs = qryCustomer(false, "cusnum");
    while ($cd = $custs->fetch_array()) {
        for ($i = 1; $i <= 12; ++$i) {
            $cols = grp(m("cusnum", $cd["cusnum"]), m("contra", 0), m("edate", $sdate), m("sdate", raw("CURRENT_DATE")), m("eref", 0), m("descript", "Balance"), m("credit", 0), m("debit", 0), m("cbalance", $custcredit[$cd["cusnum"]]), m("dbalance", $custdebit[$cd["cusnum"]]), m("div", USER_DIV));
            $qryi->setTable("custledger", "{$i}");
            $qryi->setOpt($cols);
            $qryi->run(DB_INSERT);
            /* audit customer ledger */
            $cols = grp(m("cusnum", $cd["cusnum"]), m("contra", 0), m("edate", $sdate), m("sdate", raw("CURRENT_DATE")), m("eref", 0), m("descript", "Balance"), m("credit", 0), m("debit", 0), m("cbalance", $custcredit[$cd["cusnum"]]), m("dbalance", $custdebit[$cd["cusnum"]]), m("div", USER_DIV), m("actyear", YR_NAME));
            $qryi->setTable(getMonthName($i) . "_custledger", "audit");
            $qryi->setOpt($cols);
            $qryi->run(DB_INSERT);
        }
    }
    /* create the supplier ledger balance entries */
    $supps = qrySupplier(false, "supid");
    while ($sd = $supps->fetch_array()) {
        for ($i = 1; $i <= 12; ++$i) {
            $qryi->setTable("suppledger", "{$i}");
            $cols = grp(m("supid", $sd["supid"]), m("contra", "0"), m("edate", $sdate), m("sdate", raw("CURRENT_DATE")), m("eref", "0"), m("descript", "Balance"), m("credit", "0"), m("debit", "0"), m("div", USER_DIV), m("cbalance", $suppcredit[$sd["supid"]]), m("dbalance", $suppdebit[$sd["supid"]]));
            $qryi->setCols($cols);
            $qryi->run(DB_INSERT);
        }
    }
    /* create the stock ledger entries */
    $stock = qryStock(false, "stkid, stkcod, stkdes, units, csamt");
    while ($stk = $stock->fetch_array()) {
        for ($i = 1; $i <= 12; ++$i) {
            $qryi->setTable("stkledger", "{$i}");
            $cols = grp(m("stkid", $stk["stkid"]), m("stkcod", $stk["stkcod"]), m("stkdes", $stk["stkdes"]), m("trantype", "bal"), m("edate", $sdate), m("qty", $stk["units"]), m("csamt", $stk["csamt"]), m("balance", $stk["csamt"]), m("bqty", $stk["units"]), m("details", "Balance"), m("div", USER_DIV), m("yrdb", $nextyr));
            $qryi->setCols($cols);
            $qryi->run(DB_INSERT);
        }
    }
    /* do the retained income entries for all branches */
    $sql = "SELECT div FROM cubit.branches";
    $branRs = db_exec($sql) or errDie("Could not access branches table.");
    while ($bran = pg_fetch_array($branRs)) {
        fintran($bran['div']);
    }
    /* create the ledger account balance entries */
    for ($i = 1; $i <= 12; ++$i) {
        $periodname = getMonthName($i);
        $sql = "\n\t\t\tINSERT INTO " . YR_DB . ".{$periodname} (\n\t\t\t\taccid, topacc, accnum, accname, debit, credit, div\n\t\t\t) SELECT accid, topacc, accnum, accname, debit, credit, div\n\t\t\t\tFROM core.trial_bal WHERE month='1'";
        db_exec($sql) or errDie("Error creating ledger balances (1)");
        $sql = "\n\t\t\tINSERT INTO \"{$i}\".openbal (\n\t\t\t\taccid, accname, debit, credit, div\n\t\t\t) SELECT accid, accname, debit, credit, div\n\t\t\t\tFROM core.trial_bal WHERE month='1'";
        db_exec($sql) or errDie("Error creating ledger balances (2)");
        $sql = "\n\t\t\tINSERT INTO \"{$i}\".ledger (\n\t\t\t\tacc, contra, edate, eref, descript, credit, debit, div, caccname, ctopacc, caccnum, cbalance, dbalance\n\t\t\t) SELECT accid, accid, CURRENT_DATE, '0', 'Balance', '0', '0', div, accname, topacc, accnum, credit, debit\n\t\t\t\tFROM core.trial_bal WHERE month='1'";
        db_exec($sql) or errDie("Error creating ledger balances (3)");
    }
    /* close and select new year */
    selectNextYear($nextyr);
    /* mark year as closed */
    $sql = "UPDATE core.year SET closed = 'y' WHERE yrdb = '" . YR_DB . "'";
    $rslt = db_exec($sql) or errDie("Could not Set Next Year Database and Name", SELF);
    pglib_transaction("COMMIT");
    // Display
    $write = "<center><h3> Current Year has been closed </h3>\n\t<b>( i ) The next Year has been activated ( i )</b></center>" . mkQuickLinks();
    return $write;
}
function add()
{
    extract($_REQUEST);
    $qry = new dbSelect("batch_cashbook", "cubit", grp(m("where", wgrp(m("cashid", "{$id}")))));
    $qry->run();
    if ($qry->num_rows() <= 0) {
        invalid_use("Invalid batch cashbook entry.");
    }
    $bcb = $qry->fetch_array();
    if ($bcb["chrgvat"] == "exc") {
        $bcb["amount"] -= $bcb["vat"];
    }
    extract($bcb, EXTR_SKIP);
    core_connect();
    $accs = qryAccounts();
    if ($accs->num_rows() <= 0) {
        $glacc = "There are no Income accounts in Cubit.";
    }
    $glacc = "<select name='accinv'>";
    while ($acc = $accs->fetch_array()) {
        if (isDisabled($acc['accid'])) {
            continue;
        }
        if ($accinv == $acc['accid']) {
            $sel = "selected";
        } else {
            $sel = "";
        }
        $glacc .= "<option value='{$acc['accid']}' {$sel}>{$acc['accname']}</option>";
    }
    $glacc .= "</select>";
    $OUT = "\n\t\t\t\t<h3>Edit Bank Receipt</h3>\n\t\t\t\t<table " . TMPL_tblDflts . " width='100%'>\n\t\t\t\t<form action='" . SELF . "' method='POST' name='form'>\n\t\t\t\t\t<input type='hidden' name='key' value='confirm'>\n\t\t\t\t\t<input type='hidden' name='id' value='{$id}'>\n\t\t\t\t\t<input type='hidden' name='vat' value='{$bcb['vat']}' />\n\t\t\t\t\t<input type='hidden' name='orig_vatcode' value='{$bcb['vatcode']}' />\n\t\t\t\t\t<input type='hidden' name='orig_chrgvat' value='{$bcb['chrgvat']}' />\n\t\t\t\t\t<input type='hidden' name='orig_amount' value='{$bcb['amount']}' />\n\t\t\t\t\t<tr>\n\t\t\t\t\t\t<th>Field</th>\n\t\t\t\t\t\t<th>Value</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>Bank Account</td>\n\t\t\t\t\t\t<td valign='center'>\n\t\t\t\t\t\t\t<select name='bankid'>";
    db_connect();
    $qry->setTable("bankacct", "cubit");
    $qry->setOpt(grp(m("where", "btype!='int' AND div='" . USER_DIV . "'")));
    $qry->run();
    if ($qry->num_rows() <= 0) {
        return "<li class='err'> There are no accounts held at the selected Bank.\n\t\t\t<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct Selection'>";
    }
    while ($acc = $qry->fetch_array()) {
        if (isset($bankid) && $bankid == $acc['bankid']) {
            $sel = "selected";
        } else {
            $sel = "";
        }
        $OUT .= "<option value='{$acc['bankid']}' {$sel}>{$acc['accname']} - {$acc['bankname']} ({$acc['acctype']})</option>";
    }
    if (!isset($name)) {
        $name = "";
        $descript = "";
        $cheqnum = "";
        $amount = "";
        $chrgvat = "";
    }
    db_conn('cubit');
    $Sl = "SELECT * FROM vatcodes ORDER BY code";
    $Ri = db_exec($Sl) or errDie("Unable to get vat codes");
    $Vatcodes = "\n\t\t\t<select name='vatcode'>\n\t\t\t\t<option value='0'>Select</option>";
    $vacs = qryVatcode();
    $Vatcodes = db_mksel($vacs, "vatcode", $vatcode, "#id", "#code", "0:Select");
    list($o_year, $o_month, $o_day) = explode('-', $date);
    $sel1 = "";
    $sel2 = "";
    $sel3 = "";
    if ($chrgvat == "inc") {
        $sel1 = "checked=yes";
    } else {
        if ($chrgvat == "exc") {
            $sel2 = "checked=yes";
        } else {
            if ($chrgvat == "nov") {
                $sel3 = "checked=yes";
            } else {
                $sel1 = "checked=yes";
            }
        }
    }
    $OUT .= "\n\t\t</select>\n\t\t</td>\n\t</tr>\n\t<tr class='" . bg_class() . "'>\n\t\t<td>Date</td>\n\t\t<td>\n\t\t\t" . mkDateSelect("o", $o_year, $o_month, $o_day) . "\n\t\t</td>\n\t</tr>\n\t<tr class='" . bg_class() . "'>\n\t\t<td>Received from</td>\n\t\t<td valign='center'><input size='20' name='name' value='{$name}'></td>\n\t</tr>\n\t<tr class='" . bg_class() . "'>\n\t\t<td>Description</td>\n\t\t<td valign='center'><textarea col='18' rows='3' name='descript'>{$descript}</textarea></td>\n\t</tr>\n\t<tr class='" . bg_class() . "'>\n\t\t<td>Reference</td>\n\t\t<td valign='center'><input size='20' name='reference' value='{$reference}'></td>\n\t</tr>\n\t<tr class='" . bg_class() . "'>\n\t\t<td>Cheque Number</td>\n\t\t<td valign='center'><input size='20' name='cheqnum' value='{$cheqnum}'></td>\n\t</tr>\n\t<tr class='" . bg_class() . "'>\n\t\t<td>Amount</td>\n\t\t<td valign='center'>" . CUR . " <input type='text' size='10' name='amount' value='" . sprint($amount) . "'></td>\n\t</tr>\n\t<tr class='" . bg_class() . "'>\n\t\t<td>VAT </td>\n\t\t<td>\n\t\t\t<input type='radio' name='chrgvat' value='inc' {$sel1}>Inclusive &nbsp;&nbsp;\n\t\t\t<input type='radio' name='chrgvat' value='exc' {$sel2}>Exclusive &nbsp;&nbsp;\n\t\t\t<input type='radio' name='chrgvat' value='nov' {$sel3}>No VAT\n\t\t</td>\n\t</tr>\n\t<tr class='" . bg_class() . "'>\n\t\t<td>VAT Code</td>\n\t\t<td>{$Vatcodes}</td>\n\t</tr>\n\t<tr class='" . bg_class() . "'>\n\t\t<td valign='top'>Select Contra Account</td>\n\t\t<td>{$glacc}</td>\n\t</tr>\n\t<tr>\n\t\t<td>&nbsp;</td>\n\t\t<td valign='center' align='right'><input type='submit' value='Confirm &raquo;'></td>\n\t</tr>\n\t</table>";
    # main table (layout with menu)
    $OUT .= mkQuickLinks();
    return $OUT;
}
예제 #30
0
function printSupp()
{
    extract($_REQUEST);
    define("LIMIT", 100);
    $fields = array();
    $fields["action"] = "listsupp";
    $fields["filter"] = "supname";
    $fields["search"] = "[_BLANK_]";
    $fields["offset"] = 0;
    extract($fields, EXTR_SKIP);
    if (!isset($supp_grp)) {
        $supp_grp = "";
    }
    // Should results be displayed on first load results are only
    // displayed if results are less than the limit defined
    if ($search == "[_BLANK_]") {
        $sql = "SELECT count(supid) FROM cubit.suppliers";
        $count_rslt = db_exec($sql) or errDie("Unable to retrieve supplier count.");
        $count = pg_fetch_result($count_rslt, 0);
        if ($count < LIMIT) {
            $search = "";
        }
    }
    if (isset($filter) && !isset($all)) {
        $sqlfilter = " AND {$filter} ILIKE '%{$search}%'";
    } else {
        $filter = "";
        $search = "";
        $sqlfilter = "";
    }
    if ($search == "[_BLANK_]") {
        $search = "";
    }
    $filterarr = array("supname" => "Supplier Name", "supno" => "Account Number", "groupname" => "Supplier Groups");
    $filtersel = extlib_cpsel("filter", $filterarr, $filter);
    $supp_grps = "\n\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t<td colspan='2'>\n\t\t\t\t\t\t\t<select name='supp_grp'>\n\t\t\t\t\t\t\t\t<option value='all'>View All</option>\n\t\t\t\t";
    $get_grps = "SELECT * FROM supp_groups WHERE id != '0' ORDER BY groupname";
    $run_grps = db_exec($get_grps) or errDie("Unable to get supplier group information.");
    if (pg_numrows($run_grps) > 0) {
        while ($grp_arr = pg_fetch_array($run_grps)) {
            if ($grp_arr['id'] == $supp_grp) {
                $supp_grps .= "<option value='{$grp_arr['id']}' selected>{$grp_arr['groupname']}</option>";
            } else {
                $supp_grps .= "<option value='{$grp_arr['id']}'>{$grp_arr['groupname']}</option>";
            }
        }
    }
    $supp_grps .= "\n\t\t\t\t\t\t\t</select> \n\t\t\t\t\t\t\t<input type='submit' value='View'>\n\t\t\t\t\t\t</td>\n\t\t\t\t\t</tr>\n\t\t\t\t\t";
    if (!isset($sortfilter)) {
        $sortfilter = "supname";
    }
    $sel1 = "";
    $sel2 = "";
    if ($sortfilter == "supname ASC") {
        $sel1 = "selected";
    } else {
        $sel2 = "selected";
    }
    $sort_drop = "\n\t\t\t\t\t<select name='sortfilter'>\n\t\t\t\t\t\t<option value='supname ASC' {$sel1}>Alphabetically</option>\n\t\t\t\t\t\t<option value='balance DESC' {$sel2}>Balance</option>\n\t\t\t\t\t</select>\n\t\t\t\t";
    # Set up table to display in
    $printSupp = "\n\t<h3>Current Suppliers</h3>\n\t<table " . TMPL_tblDflts . ">\n\t<form action='" . SELF . "' method='GET'>\n\t<input type='hidden' name='action' value='{$action}'>\n\t<tr>\n\t\t<th>.: Filter :.</th>\n\t\t<th>.: Value :.</th>\n\t</tr>\n\t<tr class='" . bg_class() . "'>\n\t\t<td>{$filtersel}</td>\n\t\t<td><input type='text' size='20' name='search' value='{$search}'></td>\n\t</tr>\n\t<tr class='" . bg_class() . "'>\n\t\t<td align='center'><input type='submit' name='all' value='View All'></td>\n\t\t<td align='center'><input type='submit' value='Apply Filter'></td>\n\t</tr>\n\t<tr><td><br></td></tr>\n\t<tr>\n\t\t<th colspan='2'>Select View Type</th>\n\t</tr>\n\t{$supp_grps}\n\t" . TBL_BR . "\n\t<tr>\n\t\t<th colspan='2'>Sort By</th>\n\t</tr>\n\t<tr class='" . bg_class() . "'>\n\t\t<td colspan='2'>{$sort_drop} <input type='submit' value='Sort'></td>\n\t</tr>\n\t</form>\n\t</table>\n\t<script>\n\t\t/* CRM CODE */\n\t\tfunction updateAccountInfo(id, name) {\n\t\t\twindow.opener.document.frm_con.accountname.value=name;\n\t\t\twindow.opener.document.frm_con.account_id.value=id;\n\t\t\twindow.opener.document.frm_con.account_type.value='Supplier';\n\t\t\twindow.close();\n\t\t}\n\t</script>\n\t<p></p>\n\t<table " . TMPL_tblDflts . ">\n\t   <tr>\n\t    \t<th>Department</th>\n\t    \t<th>Supp No.</th>\n\t    \t<th>Supplier Name</th>\n\t    \t<th>Branch</th>\n\t    \t<th>Contact Name</th>\n\t    \t<th>Tel No.</th>\n\t    \t<th>Fax No.</th>\n\t    \t<th colspan='2'>Balance</th>\n\t    \t<th colspan='10'>Options</th>\n\t</tr>";
    $i = 0;
    $tot = 0;
    $sql = "\n\tSELECT deptid, balance, supid, location, supno, branch, contname, tel,\n\t\tfax, blocked, supname, groupname \n\tFROM cubit.suppliers\n\t\tLEFT JOIN cubit.supp_groups\n\t\t\tON suppliers.groupid=supp_groups.id\n\tWHERE (div = '" . USER_DIV . "' OR ddiv = '" . USER_DIV . "') {$sqlfilter}\n\tORDER BY {$sortfilter}\n\tOFFSET {$offset} LIMIT " . LIMIT;
    $suppRslt = db_exec($sql) or errDie("Unable to retrieve Suppliers from database.");
    $sql = "\n\tSELECT count(supid) FROM cubit.suppliers\n\tWHERE (div = '" . USER_DIV . "' OR ddiv = '" . USER_DIV . "') {$sqlfilter}";
    $count_rslt = db_exec($sql) or errDie("Unable to retrieve count.");
    $count = pg_fetch_result($count_rslt, 0);
    $grps_arr = array();
    $get_grps_owners = "SELECT * FROM supp_grpowners";
    $run_grps_owners = db_exec($get_grps_owners) or errDie("Unable to get group information.");
    if (pg_numrows($run_grps_owners) > 0) {
        while ($garr = pg_fetch_array($run_grps_owners)) {
            $grps_arr[$garr['supid']] = $garr['grpid'];
        }
    }
    if (pg_numrows($suppRslt) < 1) {
        $printSupp .= "\n\t\t<tr class='" . bg_class() . "'>\n\t\t\t<td colspan='20'>\n\t\t\t\t<li>Please enter the first few characters of\n\t\t\t\tthe supplier's name in the search box, to\n\t\t\t\tview the suppliers.</li>\n\t\t\t</td>\n\t\t</tr>";
    } else {
        while ($supp = pg_fetch_array($suppRslt)) {
            #check if this supplier is in the selected group
            if (isset($supp_grp) and strlen($supp_grp) > 0 and $supp_grp != 'all') {
                if (!isset($grps_arr[$supp['supid']])) {
                    $grps_arr[$supp['supid']] = 0;
                }
                if ($grps_arr[$supp['supid']] != $supp_grp) {
                    continue;
                }
            }
            # get department
            $sql = "\n\t\t\tSELECT * FROM exten.departments\n\t\t\tWHERE deptid = '{$supp['deptid']}' AND div = '" . USER_DIV . "'";
            $deptRslt = db_exec($sql);
            if (pg_numrows($deptRslt) < 1) {
                $deptname = "<li class='err'>Department not Found.</li>";
            } else {
                $dept = pg_fetch_array($deptRslt);
                $deptname = $dept['deptname'];
            }
            $supp['balance'] = sprint($supp['balance']);
            # Check if record can be removed
            $sql = "\n\t\t\tSELECT * FROM cubit.cashbook\n\t\t\tWHERE banked = 'no' AND supid = '{$supp['supid']}' AND\n\t\t\t\tdiv = '" . USER_DIV . "'";
            $rs = db_exec($sql) or errDie("Unable to get cashbook entries.", SELF);
            if (pg_numrows($rs) < 1 && $supp['balance'] == 0) {
                $rm = "<a href='supp-rem.php?supid={$supp['supid']}'>Remove</a>";
            } else {
                $rm = "";
            }
            #if($supp['balance']==0) {$rm="<a href='supp-rem.php?supid=$supp[supid]'>Remove</a>";} else {$rm="";}
            // check if supplier can be added to contact list
            $addcontact = "<td><a href='conper-add.php?type=supp&id={$supp['supid']}'>Add Contact</a></td>";
            $tot = $tot + $supp['balance'];
            # Locations drop down
            $locs = array("loc" => "Local", "int" => "International", "" => "");
            $loc = $locs[$supp['location']];
            $sp4 = "&nbsp;&nbsp;&nbsp;&nbsp;";
            $fbal = "{$sp4}--{$sp4}";
            $trans = "<a href='core/supp-trans.php?supid={$supp['supid']}'>Transaction</a>";
            if ($supp['location'] == 'int') {
                $fbal = "{$sp4} {$supp['currency']} {$supp['fbalance']}";
                $trans = "<a href='core/intsupp-trans.php?supid={$supp['supid']}'>Transaction</a>";
                $pay = "<td><a href='bank/bank-pay-supp-int.php?supid={$supp['supid']}&cash=yes'>Add Payment</a></td>";
            } else {
                $pay = "<td><a href='bank/bank-pay-supp.php?supid={$supp['supid']}&cash=yes'>Add Payment</a></td>";
            }
            # Alternate bgcolor
            $bgColor = bgcolor($i);
            $printSupp .= "<tr class='" . bg_class() . "'><td>{$deptname}</td>";
            if ($action == "contact_acc") {
                $updatelink = "javascript: updateAccountInfo(\"{$supp['supid']}\", \"{$supp['supno']}\");";
                $printSupp .= "\t<td><a href='{$updatelink}'>{$supp['supno']}</a></td>\n\t\t\t\t\t\t<td align=center><a href='{$updatelink}'>{$supp['supname']}</a></td>";
            } else {
                $printSupp .= "<td>{$supp['supno']}</td><td align=center>{$supp['supname']}</td>";
                $printSupp .= "<td align=center>{$supp['branch']}</td>";
            }
            $printSupp .= "\n\t\t\t<td>{$supp['contname']}</td>\n\t\t\t<td>{$supp['tel']}</td>\n\t\t\t<td>{$supp['fax']}</td>\n\t\t\t<td align='right' nowrap>{$sp4} " . CUR . " {$supp['balance']}</td>\n\t\t\t<td align='right' nowrap>{$fbal}</td>{$pay}";
            if ($action == "listsupp") {
                // Retrieve the template settings
                db_conn("cubit");
                $sql = "SELECT filename FROM template_settings WHERE div='" . USER_DIV . "' AND template='statements'";
                $tsRslt = db_exec($sql) or errDie("Unable to retrieve template settings from Cubit.");
                $template = pg_fetch_result($tsRslt, 0);
                $printSupp .= "\n\t\t\t\t<td><a href='supp-det.php?supid={$supp['supid']}'>Details</a></td>\n\t\t\t\t<td><a href='#' onclick='openPrintWin(\"supp-stmnt.php?supid={$supp['supid']}\")'>Statement</a></td>\n\t\t\t\t<td>{$trans}</td>\n\t\t\t\t<td><a href='supp-edit.php?supid={$supp['supid']}'>Edit</a></td>\n\t\t\t\t<td><a href='supp-pricelist.php?supid={$supp['supid']}'>Pricelist</a></td>";
                if ($supp['blocked'] == 'yes') {
                    $printSupp .= "<td><a href='supp-unblock.php?supid={$supp['supid']}'>Unblock</a></td>";
                } else {
                    $printSupp .= "<td><a href='supp-block.php?supid={$supp['supid']}'>Block</a></td>";
                }
                /* MODULE BEG: trh */
                $trhqry = new dbSelect("keys", "trh", grp(m("cols", "email"), m("where", "suppid='{$supp['supid']}'")));
                $trhqry->run();
                if ($trhqry->num_rows() == 0) {
                    $printSupp .= "<td><a href='transheks/comm_init.php?suppid={$supp['supid']}'>Configure for Transheks</a></td>";
                } else {
                    //$trh_email = $trhqry->fetch_result();
                    //$printSupp .= "<td><a href='transheks/comm_init.php?suppid=$supp[supid]&email=$trh_email'>Reconfigure for Transheks</a></td>";
                }
                /* MODULE END: trh */
                $printSupp .= "<td>{$rm}</td>{$addcontact}</tr>";
            } else {
                $printSupp .= "<td><a href='javascript: popupSized(\"supp-det.php?supid={$supp['supid']}\", \"suppdetails\", 500, 300, \"\");'>Details</a></td>";
            }
        }
        $tot = sprint($tot);
        $printSupp .= "\n\t\t<tr class='" . bg_class() . "'>\n\t\t\t<td colspan=7>Total Amount Owed, to {$i} " . ($i > 1 ? "suppliers" : "supplier") . " </td>\n\t\t\t<td align=right>" . CUR . " {$tot}</td>\n\t\t\t<td colspan='12'>&nbsp;</td>\n\t\t</tr>";
    }
    $next_offset = $offset + LIMIT;
    $prev_offset = $offset - LIMIT;
    $get_vars = "filter={$filter}&search={$search}";
    $prev_ancor = $prev_offset >= 0 ? "<a href='" . SELF . "?offset={$prev_offset}&{$get_vars}'>&laquo; Previous</a>" : "";
    $next_ancor = $next_offset < $count ? "<a href='" . SELF . "?offset={$next_offset}&{$get_vars}'>Next &raquo;</a>" : "";
    $printSupp .= "\n\t<tr class='" . bg_class() . "'>\n\t<td colspan='20' align='center'>\n\t\t\t{$prev_ancor}\n\t\t\t{$next_ancor}\n\t\t</td>\n\t</tr>";
    $printSupp .= "\n\t\t</form>\n\t\t<form action='" . SELF . "' method='POST'>\n\t\t<input type='hidden' name='export' value='yes'>\n\t\t<input type='hidden' name='filter' value='{$filter}'>\n\t\t<input type='hidden' name='search' value='{$search}'>\n\t\t<tr><td><br></td></tr>\n\t\t<tr>\n\t\t\t<td colspan='3'><input type='submit' value='Export to Spreadsheet'></td>\n\t\t</tr>\n\t\t</form>\n\t</table>";
    if ($action == "listsupp") {
        $printSupp .= "\n\t\t<p></p>\n\t\t<table " . TMPL_tblDflts . " 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\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td><a href='supp-new.php'>Add Supplier</a></td>\n\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td><a href='main.php'>Main Menu</a></td>\n\t\t\t</tr>\n\t\t</table>";
    }
    return $printSupp;
}