function write($_POST)
{
    # Get vars
    extract($_POST);
    if (isset($back)) {
        return details($_POST);
    }
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($cusnum, "num", 1, 50, "Invalid Customer number.");
    $v->isOk($accid, "num", 1, 50, "Invalid Contra Account.");
    $v->isOk($refnum, "num", 1, 10, "Invalid Reference number.");
    $v->isOk($amount, "float", 1, 20, "Invalid Amount.");
    $v->isOk($details, "string", 0, 255, "Invalid Details.");
    $v->isOk($author, "string", 1, 30, "Invalid Authorising person name.");
    $v->isOk($vatinc, "string", 1, 6, "Invalid Transaction VAT Option.");
    $datea = explode("-", $date);
    if (count($datea) == 3) {
        if (!checkdate($datea[1], $datea[0], $datea[2])) {
            $v->isOk($date, "num", 1, 1, "Invalid date.");
        }
    } else {
        $v->isOk($date, "num", 1, 1, "Invalid date.");
    }
    # display errors, if any
    if ($v->isError()) {
        $write = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $write .= "<li class='err'>" . $e["msg"] . "</li>";
        }
        $write .= "<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $write;
    }
    if (isset($stock_prof) and is_array($stock_prof) and sprint(array_sum($stock_prof)) != $difference) {
        return details($_POST, "<li class='err'>Please ensure differences matches total difference.</li>");
    }
    //print "<pre>";
    //var_dump ($_POST);
    //print "</pre>";
    $date = "{$datea['2']}-{$datea['1']}-{$datea['0']}";
    # Accounts details
    $accRs = get("core", "*", "accounts", "accid", $accid);
    $acc = pg_fetch_array($accRs);
    # Select customer
    db_connect();
    $sql = "SELECT * FROM customers WHERE cusnum = '{$cusnum}' AND div = '" . USER_DIV . "'";
    $custRslt = db_exec($sql) or errDie("Unable to access databse.", SELF);
    if (pg_numrows($custRslt) < 1) {
        return "<li class='err'>Invalid customer ID, or customer has been blocked.</li>";
    } else {
        $cust = pg_fetch_array($custRslt);
    }
    # Get department
    db_conn("exten");
    $sql = "SELECT * FROM departments WHERE deptid = '{$cust['deptid']}' AND div = '" . USER_DIV . "'";
    $deptRslt = db_exec($sql);
    if (pg_numrows($deptRslt) < 1) {
        return "<i class='err'>Customer Department Not Found</i>";
    } else {
        $dept = pg_fetch_array($deptRslt);
    }
    # Begin updates
    pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
    # Probe tran type
    if ($entry == "CT") {
        $refnum = getrefnum();
        #update stock ...
        $stock_total = 0;
        if (isset($stock_items) and is_array($stock_items)) {
            $used_stock = TRUE;
            foreach ($stock_items as $stkid => $unitnum) {
                db_connect();
                $sql = "SELECT * FROM stock WHERE stkid = '{$stkid}' AND div = '" . USER_DIV . "'";
                $stkRslt = db_exec($sql) or errDie("Unable to access databse.", SELF);
                if (pg_numrows($stkRslt) < 1) {
                    return "<li> Invalid Stock ID.</li>";
                } else {
                    $stk = pg_fetch_array($stkRslt);
                }
                if ($stk['units'] < 0) {
                    $min_stock = abs($stk['units']);
                    if ($unitnum < $min_stock) {
                        $min_stock = $unitnum;
                    }
                } else {
                    $min_stock = 0;
                }
                # Get warehouse name
                db_conn("exten");
                $sql = "SELECT * FROM warehouses WHERE whid = '{$stk['whid']}' AND div = '" . USER_DIV . "'";
                $whRslt = db_exec($sql);
                $wh = pg_fetch_array($whRslt);
                # calculate actual cost amount
                //				$temp = $cost;
                //				$cost = sprint($cost * $unitnum);
                #temp = unitprice
                $temp = sprint($stock_cost[$stkid]);
                #cost = total price
                $cost = sprint($stock_cost[$stkid] * $unitnum);
                $cost_amt = sprint($cost);
                $stock_total = $stock_total + $cost_amt;
                $stock_cost[$stkid] = $cost_amt / $unitnum;
                #temp = unitprice
                $temp = sprint($stock_cost[$stkid]);
                #cost = total price
                $cost = sprint($stock_cost[$stkid] * $unitnum);
                $tipo = "Increase";
                if ($tipo == 'Increase') {
                    /* do the journals for stock sold before purchase 
                    			this will only be done by a purchase */
                    if ($min_stock > 0) {
                        db_conn("exten");
                        $sql = "SELECT stkacc,cosacc FROM warehouses WHERE whid = '{$stk['whid']}' AND div = '" . USER_DIV . "'";
                        $whRslt = db_exec($sql);
                        $wh = pg_fetch_array($whRslt);
                        $stockacc = $wh['stkacc'];
                        $cosacc = $wh['cosacc'];
                    }
                    # Update Stock
                    db_connect();
                    $sql = "UPDATE stock\n\t\t\t\t\t\t\tSET units = (units + '{$unitnum}'),\n\t\t\t\t\t\t\t\tlcsprice = '{$temp}',\n\t\t\t\t\t\t\t\tcsamt = (csamt + {$cost}),\n\t\t\t\t\t\t\t\tcsprice = (\n\t\t\t\t\t\t\t\t\tSELECT\n\t\t\t\t\t\t\t\t\t\tCASE WHEN (units != -{$unitnum}) THEN (csamt+{$cost})/(units+{$unitnum})\n\t\t\t\t\t\t\t\t\t\tELSE 0\n\t\t\t\t\t\t\t\t\t\tEND\n\t\t\t\t\t\t\t\t\tFROM cubit.stock\n\t\t\t\t\t\t\t\t\tWHERE stkid = '{$stkid}' AND div = '" . USER_DIV . "'\n\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\tWHERE stkid = '{$stkid}' AND div = '" . USER_DIV . "'";
                    $rslt = db_exec($sql) or errDie("Unable to insert stock to Cubit.", SELF);
                    $sdate = $date;
                    # stkid, stkcod, stkdes, trantype, edate, qty, csamt, details
                    stockrec($stk['stkid'], $stk['stkcod'], $stk['stkdes'], 'dt', $sdate, $unitnum, $cost, $details);
                    db_connect();
                    if ($unitnum == 0) {
                        $csprice = 0;
                    } else {
                        $csprice = sprint($cost / $unitnum);
                    }
                    $sql = "INSERT INTO stockrec(edate, stkid, stkcod, stkdes, trantype, qty, csprice, csamt, details, div)\n\t\t\t\t\t\t\tVALUES('{$sdate}', '{$stk['stkid']}', '{$stk['stkcod']}', '{$stk['stkdes']}', 'note', '{$unitnum}', '" . sprint($cost + $stock_prof[$stkid]) . "', '{$csprice}', '{$details}', '" . USER_DIV . "')";
                    $recRslt = db_exec($sql);
                    db_connect();
                    $sql = "SELECT * FROM stock WHERE stkid = '{$stkid}' AND div = '" . USER_DIV . "'";
                    $stkRslt = db_exec($sql) or errDie("Unable to access databse.", SELF);
                    if (pg_numrows($stkRslt) < 1) {
                        return "<li> Invalid Stock ID.</li>";
                    } else {
                        $stk = pg_fetch_array($stkRslt);
                    }
                    # balance transaction
                    # Debit STock account and Credit Contra Account
                    #ct was $dept['debtacc']
                    writetrans($wh['stkacc'], $wh['cosacc'], $date, $refnum, $cost, "Cost Of Sales for: {$details} for Customer: {$cust['surname']}");
                    $cc_trantype = cc_TranTypeAcc($wh['stkacc'], $dept['debtacc']);
                }
            }
        } else {
            $used_stock = FALSE;
        }
        #we'll handle the discrincy seperately
        if ($stock_total != 0) {
            $amount_dif = sprint($amount - $stock_total);
            //			$amount = sprint ($stock_total);
        } else {
            $amount_dif = 0;
            //			$amount = sprint ($amount);
        }
        #do vat trans ...
        if (isset($vatinc) and $vatinc != "novat") {
            #process vat
            db_connect();
            $Sl = "SELECT * FROM vatcodes WHERE id='{$vatcode}'";
            $Ri = db_exec($Sl);
            $vd = pg_fetch_array($Ri);
            $VATP = $vd['vat_amount'];
            #calculate amounts
            if ($vatinc == 'yes') {
                $vatamt = sprint($amount / ($VATP + 100) * $VATP);
                $amt = sprint($amount - $vatamt);
                $totamt = sprint($amount);
            } else {
                $vatamt = sprint($VATP / 100 * $amount);
                $amt = sprint($amount);
                $totamt = sprint($amount + $vatamt);
            }
            $datea = explode("-", $date);
            $cdate = $date;
            # Check VAt Deductable account
            if ($vatdedacc == 'dt') {
                vatr($vd['id'], $cdate, "INPUT", $vd['code'], $refnum, "{$details} VAT", -$totamt, -$vatamt);
                writetrans($vataccid, $dept['debtacc'], $date, $refnum, $vatamt, "VAT Return for: {$details}");
            } elseif ($vatdedacc == 'ct') {
                vatr($vd['id'], $cdate, "OUTPUT", $vd['code'], $refnum, "{$details}.  VAT", $totamt, $vatamt);
                writetrans($accid, $vataccid, $date, $refnum, $vatamt, "VAT Return for: {$details}");
            }
            if ($used_stock) {
                $accid = $dept['incacc'];
                $details = "Debtors Control for: {$details}";
            }
            writetrans($accid, $dept['debtacc'], $date, $refnum, $amt, $details . " - Customer {$cust['cusname']} {$cust['surname']}");
        } else {
            $totamt = sprint($amount);
            $amt = sprint($amount);
            $getacc_arr = getAccn("2190", "000");
            $getgacc = $getacc_arr['accid'];
            if ($used_stock) {
                $accid = $dept['incacc'];
                $details = "Debtors Control for: {$details}";
            }
            # Write transaction  (debit contra account, credit debtors control)
            writetrans($accid, $dept['debtacc'], $date, $refnum, $totamt, $details . " - Customer {$cust['cusname']} {$cust['surname']}");
        }
        $tran = "\n\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t<td>{$acc['topacc']}/{$acc['accnum']} - {$acc['accname']}</td>\n\t\t\t\t\t\t<td>{$cust['accno']} - {$cust['cusname']} {$cust['surname']}</td>\n\t\t\t\t\t</tr>";
        $samount = $amount - $amount * 2;
        recordCT($samount, $cust['cusnum'], $date);
        $type = 'c';
    }
    db_connect();
    $stotamt = $totamt - $totamt * 2;
    $sdate = date("Y-m-d");
    # record the payment on the statement
    $sql = "\n\t\t\tINSERT INTO stmnt \n\t\t\t\t(cusnum, invid, amount, date, type, st, div, allocation_date) \n\t\t\tVALUES \n\t\t\t\t('{$cust['cusnum']}', '0', '{$stotamt}', '{$date}', '{$details}', 'n', '" . USER_DIV . "', '{$date}')";
    $stmntRslt = db_exec($sql) or errDie("Unable to Insert statement record in Cubit.", SELF);
    $sql = "INSERT INTO open_stmnt(cusnum, invid, amount, balance, date, type, st, div) VALUES('{$cust['cusnum']}', '0', '{$samount}', '{$samount}', '{$date}', '{$details}', 'n', '" . USER_DIV . "')";
    $stmntRslt = db_exec($sql) or errDie("Unable to Insert statement record in Cubit.", SELF);
    # update the customer (make balance more)
    $sql = "UPDATE customers SET balance = (balance + '{$samount}') WHERE cusnum = '{$cust['cusnum']}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to update customer in Cubit.", SELF);
    # Make ledge record
    custledger($cust['cusnum'], $accid, $date, $refnum, $details, $totamt, $type);
    db_connect();
    $get_credid = "SELECT last_value FROM seq WHERE type = 'cred_note' LIMIT 1";
    $run_credid = db_exec($get_credid) or errDie("Unable to get credit note number.");
    $crednote_num = pg_fetch_result($run_credid, 0, 0);
    if (!isset($vataccid)) {
        $vataccid = 0;
    }
    if (!isset($vatamt)) {
        $vatamt = 0;
    }
    if (!isset($vatdedacc)) {
        $vatdedacc = 0;
    }
    if (!isset($vatcode)) {
        $vatcode = 0;
    }
    #record this credit note for records ...
    $ins_sql = "\n\t\t\t\t\t\tINSERT INTO credit_notes \n\t\t\t\t\t\t\t(cusnum,creditnote_num,tdate,sdate,refnum,contra,charge_vat,vatinc,vatacc,vatamt,vatacc_type,vatcode,used_stock,amount,totamt) \n\t\t\t\t\t\tVALUES \n\t\t\t\t\t\t\t('{$cusnum}','{$crednote_num}','{$date}','now','{$refnum}','{$accid}','{$vatinc}','{$vatinc}','{$vataccid}','{$vatamt}','{$vatdedacc}','{$vatcode}','{$used_stock}','{$amt}','{$totamt}')\n\t\t\t\t\t";
    $run_ins = db_exec($ins_sql) or errDie("Unable to record credit note information.");
    $cred_id = pglib_lastid("credit_notes", "id");
    if ($used_stock) {
        foreach ($stock_items as $stkid => $unitnum) {
            $ins_creditnote_sql = "\n\t\t\t\t\t\t\t\t\t\tINSERT INTO credit_notes_stock\n\t\t\t\t\t\t\t\t\t\t\t(creditnote_id,stkid,stkunits,stkcosts) \n\t\t\t\t\t\t\t\t\t\tVALUES \n\t\t\t\t\t\t\t\t\t\t\t('{$cred_id}','{$stkid}','{$unitnum}','" . sprint(($unitnum * $stock_cost[$stkid] + $stock_prof[$stkid]) / $unitnum) . "')";
            $run_creditnote_sql = db_exec($ins_creditnote_sql) or errDie("Unable to record credit note returned stock item information.");
        }
    }
    #update seq
    $upd_seq = "UPDATE seq SET last_value = last_value + 1 WHERE type = 'cred_note'";
    $run_seq = db_exec($upd_seq) or errDie("Unable to update credit note number.");
    # Commit updates
    pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
    if (isset($gds_note) and strlen($gds_note) > 0) {
        $show_gds_note = "\n\t\t\t\t\t<script>\n\t\t\t\t\t\twindow.open(\"" . SELF . "?key=recv_print&genid={$cred_id}\");\n\t\t\t\t\t</script>\n\t\t\t\t\t\t";
    } else {
        $show_gds_note = "";
    }
    // Start layout
    $write = "\n    \t\t\t<script>\n    \t\t\t\twindow.open('credit-note-print.php?id={$cred_id}');\n    \t\t\t</script>\n    \t\t\t{$show_gds_note}\n    \t\t\t<h3>Credit Note Has Been Recorded</h3>\n\t\t        <table " . TMPL_tblDflts . " width='500'>\n\t\t        \t<tr>\n\t\t        \t\t<td width='50%'><h3>Debit</h3></td>\n\t\t        \t\t<td width='50%'><h3>Credit</h3></td>\n\t\t        \t</tr>\n\t\t        \t{$tran}\n\t\t        \t<tr><td><br></td></tr>\n\t\t        \t<tr colspan='2'>\n\t\t        \t\t<td><h4>Amount</h4></td>\n\t\t        \t</tr>\n\t\t        \t<tr class='" . bg_class() . "'>\n\t\t        \t\t<td colspan='2'><b>" . CUR . " {$amount}</b></td>\n\t\t        \t</tr>\n\t\t        \t" . TBL_BR . "\n\t\t        </table>";
    return $write;
}
Пример #2
0
 function sup_xrate_update($fcid, $nrate)
 {
     $placc = getAccn('999', '999');
     $date = date("d-m-Y");
     $refnum = getrefnum();
     db_conn("exten");
     $sql = "SELECT deptid,credacc FROM departments";
     $drslt = db_exec($sql) or errDie("Unable to retrieve balances from Cubit", SELF);
     while ($dept = pg_fetch_array($drslt)) {
         db_connect();
         $sql = "SELECT supid, balance, fbalance, (balance/fbalance) as crate FROM suppliers WHERE fbalance <> 0 AND fcid = '{$fcid}' AND deptid = '{$dept['deptid']}'";
         $rslt = db_exec($sql) or errDie("Unable to retrieve balances from Cubit", SELF);
         while ($rec = pg_fetch_array($rslt)) {
             $nbal = sprint($rec['fbalance'] * $nrate);
             db_connect();
             $sql = "UPDATE suppliers SET balance = '{$nbal}' WHERE supid = '{$rec['supid']}'";
             $uRs = db_exec($sql) or errDie("Unable to retrieve update exchange rate : {$tab}", SELF);
             if ($nbal > $rec['balance']) {
                 $diff = sprint($nbal - $rec['balance']);
                 // Journal entry (? accounts)
                 writetrans($dept['credacc'], $placc['accid'], $date, $refnum, $diff, "Exchange rate loss.");
             } else {
                 $diff = sprint($rec['balance'] - $nbal);
                 // Journal entry (? accounts)
                 writetrans($placc['accid'], $dept['credacc'], $date, $refnum, $diff, "Exchange rate profit.");
             }
         }
     }
 }