}
 }
 $SQL = "SELECT salestype\n\t\t\t\tFROM debtorsmaster\n\t\t\t\tWHERE debtorno='" . $_POST['PatientNo'] . "'";
 $Result = DB_query($SQL, $db);
 $myrow = DB_fetch_array($Result);
 $SalesGLAccounts = GetSalesGLAccount('AN', $BaseStockID, $myrow['salestype'], $db);
 $SQL = "INSERT INTO gltrans (\ttype,\n\t\t\t\t\t\t\t\t\ttypeno,\n\t\t\t\t\t\t\t\t\ttrandate,\n\t\t\t\t\t\t\t\t\tperiodno,\n\t\t\t\t\t\t\t\t\taccount,\n\t\t\t\t\t\t\t\t\tdefaulttag,\n\t\t\t\t\t\t\t\t\tnarrative,\n\t\t\t\t\t\t\t\t\tamount)\n\t\t\t\t\t\t\tVALUES ( 10,\n\t\t\t\t\t\t\t\t\t'" . $InvoiceNo . "',\n\t\t\t\t\t\t\t\t\t'" . FormatDateForSQL($_POST['AdmissionDate']) . "',\n\t\t\t\t\t\t\t\t\t'" . $PeriodNo . "',\n\t\t\t\t\t\t\t\t\t'" . $SalesGLAccounts['salesglcode'] . "',\n\t\t\t\t\t\t\t\t\t'" . $_SESSION['DefaultTag'] . "',\n\t\t\t\t\t\t\t\t\t'" . _('Invoice for radiology test of Patient number') . ' ' . $_POST['PatientNo'] . "',\n\t\t\t\t\t\t\t\t\t'" . -$_SESSION['Items']['Value'] . "')";
 $ErrMsg = _('CRITICAL ERROR') . '! ' . _('NOTE DOWN THIS ERROR AND SEEK ASSISTANCE') . ': ' . _('The cost of sales GL posting could not be inserted because');
 $DbgMsg = _('The following SQL to insert the GLTrans record was used');
 $Result = DB_query($SQL, $db, $ErrMsg, $DbgMsg, true);
 $SQL = "INSERT INTO gltrans (\ttype,\n\t\t\t\t\t\t\t\t\ttypeno,\n\t\t\t\t\t\t\t\t\ttrandate,\n\t\t\t\t\t\t\t\t\tperiodno,\n\t\t\t\t\t\t\t\t\taccount,\n\t\t\t\t\t\t\t\t\tdefaulttag,\n\t\t\t\t\t\t\t\t\tnarrative,\n\t\t\t\t\t\t\t\t\tamount )\n\t\t\t\t\t\t\t\tVALUES ( 10,\n\t\t\t\t\t\t\t\t\t'" . $InvoiceNo . "',\n\t\t\t\t\t\t\t\t\t'" . FormatDateForSQL($_POST['AdmissionDate']) . "',\n\t\t\t\t\t\t\t\t\t'" . $PeriodNo . "',\n\t\t\t\t\t\t\t\t\t'" . $_SESSION['CompanyRecord']['debtorsact'] . "',\n\t\t\t\t\t\t\t\t\t'" . $_SESSION['DefaultTag'] . "',\n\t\t\t\t\t\t\t\t\t'" . _('Invoice for radiology test of Patient number') . ' ' . $_POST['PatientNo'] . "',\n\t\t\t\t\t\t\t\t\t'" . $_SESSION['Items']['Value'] . "')";
 $ErrMsg = _('CRITICAL ERROR') . '! ' . _('NOTE DOWN THIS ERROR AND SEEK ASSISTANCE') . ': ' . _('The stock side of the cost of sales GL posting could not be inserted because');
 $DbgMsg = _('The following SQL to insert the GLTrans record was used');
 $Result = DB_query($SQL, $db, $ErrMsg, $DbgMsg, true);
 if (isset($_POST['SubmitCash'])) {
     $ReceiptNumber = GetNextTransNo(12, $db);
     $SQL = "INSERT INTO gltrans (type,\n\t\t\t\t\t\t\t\t\t\ttypeno,\n\t\t\t\t\t\t\t\t\t\ttrandate,\n\t\t\t\t\t\t\t\t\t\tperiodno,\n\t\t\t\t\t\t\t\t\t\taccount,\n\t\t\t\t\t\t\t\t\t\tdefaulttag,\n\t\t\t\t\t\t\t\t\t\tnarrative,\n\t\t\t\t\t\t\t\t\t\tamount)\n\t\t\t\t\t\t\t\t\tVALUES (12,\n\t\t\t\t\t\t\t\t\t\t'" . $ReceiptNumber . "',\n\t\t\t\t\t\t\t\t\t\t'" . FormatDateForSQL($_POST['AdmissionDate']) . "',\n\t\t\t\t\t\t\t\t\t\t'" . $PeriodNo . "',\n\t\t\t\t\t\t\t\t\t\t'" . $_POST['BankAccount'] . "',\n\t\t\t\t\t\t\t\t\t\t'" . $_SESSION['DefaultTag'] . "',\n\t\t\t\t\t\t\t\t\t\t'" . _('Payment of radiology test for Patient number') . ' ' . $_POST['PatientNo'] . "',\n\t\t\t\t\t\t\t\t\t\t'" . $_SESSION['Items']['Value'] . "')";
     $DbgMsg = _('The SQL that failed to insert the GL transaction for the bank account debit was');
     $ErrMsg = _('Cannot insert a GL transaction for the bank account debit');
     $result = DB_query($SQL, $db, $ErrMsg, $DbgMsg, true);
     /* Now Credit Debtors account with receipt */
     $SQL = "INSERT INTO gltrans ( type,\n\t\t\t\t\t\t\t\t\t\ttypeno,\n\t\t\t\t\t\t\t\t\t\ttrandate,\n\t\t\t\t\t\t\t\t\t\tperiodno,\n\t\t\t\t\t\t\t\t\t\taccount,\n\t\t\t\t\t\t\t\t\t\tdefaulttag,\n\t\t\t\t\t\t\t\t\t\tnarrative,\n\t\t\t\t\t\t\t\t\t\tamount)\n\t\t\t\t\t\t\t\t\tVALUES (12,\n\t\t\t\t\t\t\t\t\t\t'" . $ReceiptNumber . "',\n\t\t\t\t\t\t\t\t\t\t'" . FormatDateForSQL($_POST['AdmissionDate']) . "',\n\t\t\t\t\t\t\t\t\t\t'" . $PeriodNo . "',\n\t\t\t\t\t\t\t\t\t\t'" . $_SESSION['CompanyRecord']['debtorsact'] . "',\n\t\t\t\t\t\t\t\t\t\t'" . $_SESSION['DefaultTag'] . "',\n\t\t\t\t\t\t\t\t\t\t'" . _('Payment of radiology test for Patient number') . ' ' . $_POST['PatientNo'] . "',\n\t\t\t\t\t\t\t\t\t\t'" . -$_SESSION['Items']['Value'] . "'\n\t\t\t\t\t\t\t\t\t)";
     $DbgMsg = _('The SQL that failed to insert the GL transaction for the debtors account credit was');
     $ErrMsg = _('Cannot insert a GL transaction for the debtors account credit');
     $result = DB_query($SQL, $db, $ErrMsg, $DbgMsg, true);
     $SQL = "INSERT INTO banktrans (type,\n\t\t\t\t\t\t\t\t\ttransno,\n\t\t\t\t\t\t\t\t\tbankact,\n\t\t\t\t\t\t\t\t\tref,\n\t\t\t\t\t\t\t\t\texrate,\n\t\t\t\t\t\t\t\t\tfunctionalexrate,\n\t\t\t\t\t\t\t\t\ttransdate,\n\t\t\t\t\t\t\t\t\tbanktranstype,\n\t\t\t\t\t\t\t\t\tamount,\n\t\t\t\t\t\t\t\t\tcurrcode,\n\t\t\t\t\t\t\t\t\tuserid)\n\t\t\t\t\t\t\t\tVALUES (12,\n\t\t\t\t\t\t\t\t\t'" . $ReceiptNumber . "',\n\t\t\t\t\t\t\t\t\t'" . $_POST['BankAccount'] . "',\n\t\t\t\t\t\t\t\t\t'" . _('Radiology test for Patient') . ' ' . $_POST['PatientNo'] . "',\n\t\t\t\t\t\t\t\t\t'1',\n\t\t\t\t\t\t\t\t\t'1',\n\t\t\t\t\t\t\t\t\t'" . FormatDateForSQL($_POST['AdmissionDate']) . "',\n\t\t\t\t\t\t\t\t\t'2',\n\t\t\t\t\t\t\t\t\t'" . $_SESSION['Items']['Value'] . "',\n\t\t\t\t\t\t\t\t\t'" . $_SESSION['CompanyRecord']['currencydefault'] . "',\n\t\t\t\t\t\t\t\t\t'" . $_SESSION['UserID'] . "'\n\t\t\t\t\t\t\t\t)";
     $DbgMsg = _('The SQL that failed to insert the bank account transaction was');
     $ErrMsg = _('Cannot insert a bank transaction');
     $result = DB_query($SQL, $db, $ErrMsg, $DbgMsg, true);
     $SQL = "INSERT INTO debtortrans (transno,\n\t\t\t\t\t\t\t\t\t\t\ttype,\n\t\t\t\t\t\t\t\t\t\t\tdebtorno,\n\t\t\t\t\t\t\t\t\t\t\ttrandate,\n\t\t\t\t\t\t\t\t\t\t\tinputdate,\n\t\t\t\t\t\t\t\t\t\t\tprd,\n\t\t\t\t\t\t\t\t\t\t\treference,\n\t\t\t\t\t\t\t\t\t\t\trate,\n\t\t\t\t\t\t\t\t\t\t\tovamount,\n\t\t\t\t\t\t\t\t\t\t\talloc,\n\t\t\t\t\t\t\t\t\t\t\tinvtext)\n\t\t\t\t\t\t\t\t\t\tVALUES ('" . $ReceiptNumber . "',\n\t\t\t\t\t\t\t\t\t\t\t12,\n\t\t\t\t\t\t\t\t\t\t\t'" . $_POST['PatientNo'] . "',\n\t\t\t\t\t\t\t\t\t\t\t'" . FormatDateForSQL($_POST['AdmissionDate']) . "',\n\t\t\t\t\t\t\t\t\t\t\t'" . FormatDateForSQL($_POST['AdmissionDate']) . "',\n\t\t\t\t\t\t\t\t\t\t\t'" . $PeriodNo . "',\n\t\t\t\t\t\t\t\t\t\t\t'" . $InvoiceNo . "',\n\t\t\t\t\t\t\t\t\t\t\t'1',\n\t\t\t\t\t\t\t\t\t\t\t'" . -$_SESSION['Items']['Value'] . "',\n\t\t\t\t\t\t\t\t\t\t\t'" . -filter_currency_input($_POST['Received']) . "',\n\t\t\t\t\t\t\t\t\t\t\t'" . _('Payment of radiology test for Patient number') . ' ' . $_POST['PatientNo'] . "'\n\t\t\t\t\t\t\t\t\t\t)";
     prnMsg(_('The transaction has been successfully posted'), 'success');
echo '<tr><td colspan="3"></td><td><hr/></td><td colspan="2"></td><td colspan="3"><hr></td></tr>';
echo '<tr><td colspan="2" align="right">' . _('Totals') . '</td>
	<td></td>
	<td>' . number_format($TotalReqdCost, 2) . '</td>
	<td></td><td></td>
	<td>' . number_format($TotalIssuedCost, 2) . '</td>
	<td align="right">' . number_format($TotalUsageVar, 2) . '</td>
	<td align="right">' . number_format($TotalCostVar, 2) . '</td></tr>';
echo '<tr><td colspan="3"></td><td><hr/></td><td colspan="2"></td><td colspan="3"><hr></td></tr>';
#echo '<tr><td colspan="7"></td><td colspan="2"><hr></td></tr>';
if (isset($_POST['Close'])) {
    DB_data_seek($WOItemsResult, 0);
    $NoItemsOnWO = DB_num_rows($WOItemsResult);
    $TotalVariance = $TotalUsageVar + $TotalCostVar;
    $PeriodNo = GetPeriod(Date($_SESSION['DefaultDateFormat']), $db);
    $WOCloseNo = GetNextTransNo(29, $db);
    $TransResult = DB_Txn_Begin($db);
    while ($WORow = DB_fetch_array($WOItemsResult)) {
        if ($TotalStdValueRecd == 0) {
            $ShareProportion = 1 / $NoItemsOnWO;
        } else {
            $ShareProportion = $WORow['stdcost'] * $WORow['qtyrecd'] / $TotalStdValueRecd;
        }
        if ($_SESSION['WeightedAverageCosting'] == 1) {
            //we need to post the variances to stock and update the weighted average cost
            /*  need to get the current total quantity on hand
            			if the quantity on hand is less than the quantity received on the work order
            			then some of the variance needs to be written off to P & L and only the proportion
            			of the variance relating to the stock still on hand should be posted to the stock value
            			*/
            $TotOnHandResult = DB_query("SELECT SUM(quantity)\n\t\t\t\t\t\t\tFROM locstock\n\t\t\t\t\t\t\tWHERE stockid='" . $WORow['stockid'] . "'", $db);
Exemple #3
0
 function Save()
 {
     global $db;
     if ($this->OrderNumber == 0) {
         $this->OrderNumber = GetNextTransNo(40, $db);
         $sql = "INSERT INTO workorders (wo,\n\t\t\t\t\t\t\t\t\t\t\tloccode,\n\t\t\t\t\t\t\t\t\t\t\trequiredby,\n\t\t\t\t\t\t\t\t\t\t\tstartdate,\n\t\t\t\t\t\t\t\t\t\t\tcostissued)\n\t\t\t\t\t\t\t\t\t\tVALUES (\n\t\t\t\t\t\t\t\t\t\t\t'" . $this->OrderNumber . "',\n\t\t\t\t\t\t\t\t\t\t\t'" . $this->LocationCode . "',\n\t\t\t\t\t\t\t\t\t\t\t'" . FormatDateForSQL($this->RequiredBy) . "',\n\t\t\t\t\t\t\t\t\t\t\t'" . FormatDateForSQL($this->StartDate) . "',\n\t\t\t\t\t\t\t\t\t\t\t'" . $this->CostIssued . "'\n\t\t\t\t\t\t\t\t\t\t)";
     } else {
         $sql = "UPDATE workorders SET   loccode='" . $this->LocationCode . "',\n\t\t\t\t\t\t\t\t\t\t\trequiredby='" . FormatDateForSQL($this->RequiredBy) . "',\n\t\t\t\t\t\t\t\t\t\t\tstartdate='" . FormatDateForSQL($this->StartDate) . "',\n\t\t\t\t\t\t\t\t\t\t\tcostissued='" . $this->CostIssued . "'\n\t\t\t\t\t\t\t\t\t\tWHERE wo='" . $this->OrderNumber . "'";
     }
     $UpdateWOResult = DB_query($sql, $db);
     foreach ($this->Items as $i => $Item) {
         $Item->Save($this->OrderNumber);
     }
 }
Exemple #4
0
 function save($db)
 {
     /* Does record exist for this tender
      */
     if ($this->TenderId == '') {
         $this->TenderId = GetNextTransNo(37, $db);
         $HeaderSQL = "INSERT INTO tenders (tenderid,\n\t\t\t\t\t\t\t\t\t\t\tlocation,\n\t\t\t\t\t\t\t\t\t\t\taddress1,\n\t\t\t\t\t\t\t\t\t\t\taddress2,\n\t\t\t\t\t\t\t\t\t\t\taddress3,\n\t\t\t\t\t\t\t\t\t\t\taddress4,\n\t\t\t\t\t\t\t\t\t\t\taddress5,\n\t\t\t\t\t\t\t\t\t\t\taddress6,\n\t\t\t\t\t\t\t\t\t\t\ttelephone,\n\t\t\t\t\t\t\t\t\t\t\trequiredbydate)\n\t\t\t\t\t\t\t\tVALUES ('" . $this->TenderId . "',\n\t\t\t\t\t\t\t\t\t\t'" . $this->Location . "',\n\t\t\t\t\t\t\t\t\t\t'" . $this->DelAdd1 . "',\n\t\t\t\t\t\t\t\t\t\t'" . $this->DelAdd2 . "',\n\t\t\t\t\t\t\t\t\t\t'" . $this->DelAdd3 . "',\n\t\t\t\t\t\t\t\t\t\t'" . $this->DelAdd4 . "',\n\t\t\t\t\t\t\t\t\t\t'" . $this->DelAdd5 . "',\n\t\t\t\t\t\t\t\t\t\t'" . $this->DelAdd6 . "',\n\t\t\t\t\t\t\t\t\t\t'" . $this->Telephone . "',\n\t\t\t\t\t\t\t\t\t\t'" . FormatDateForSQL($this->RequiredByDate) . "')";
         foreach ($this->Suppliers as $Supplier) {
             $SuppliersSQL[] = "INSERT INTO tendersuppliers (tenderid,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tsupplierid,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\temail)\n\t\t\t\t\t\t\t\tVALUES ('" . $this->TenderId . "',\n\t\t\t\t\t\t\t\t\t\t'" . $Supplier->SupplierCode . "',\n\t\t\t\t\t\t\t\t\t\t'" . $Supplier->EmailAddress . "')";
         }
         foreach ($this->LineItems as $LineItem) {
             $ItemsSQL[] = "INSERT INTO tenderitems (tenderid,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tstockid,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tquantity,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tunits)\n\t\t\t\t\t\t\t\t\t\t\tVALUES ('" . $this->TenderId . "',\n\t\t\t\t\t\t\t\t\t\t\t\t\t'" . $LineItem->StockID . "',\n\t\t\t\t\t\t\t\t\t\t\t\t\t'" . $LineItem->Quantity . "',\n\t\t\t\t\t\t\t\t\t\t\t\t\t'" . $LineItem->Units . "')";
         }
     } else {
         $HeaderSQL = "UPDATE tenders SET location='" . $this->Location . "',\n\t\t\t\t\t\t\t\t\t\t\taddress1='" . $this->DelAdd1 . "',\n\t\t\t\t\t\t\t\t\t\t\taddress2='" . $this->DelAdd2 . "',\n\t\t\t\t\t\t\t\t\t\t\taddress3='" . $this->DelAdd3 . "',\n\t\t\t\t\t\t\t\t\t\t\taddress4='" . $this->DelAdd4 . "',\n\t\t\t\t\t\t\t\t\t\t\taddress5='" . $this->DelAdd5 . "',\n\t\t\t\t\t\t\t\t\t\t\taddress6='" . $this->DelAdd6 . "',\n\t\t\t\t\t\t\t\t\t\t\ttelephone='" . $this->Telephone . "',\n\t\t\t\t\t\t\t\t\t\t\trequiredbydate='" . FormatDateForSQL($this->RequiredByDate) . "'\n\t\t\t\t\t\tWHERE tenderid = '" . $this->TenderId . "'";
         foreach ($this->Suppliers as $Supplier) {
             $sql = "DELETE FROM tendersuppliers\n\t\t\t\t\tWHERE  tenderid='" . $this->TenderId . "'";
             $result = DB_query($sql, $db);
             $SuppliersSQL[] = "INSERT INTO tendersuppliers (\n\t\t\t\t\t\t\t\t\ttenderid,\n\t\t\t\t\t\t\t\t\tsupplierid,\n\t\t\t\t\t\t\t\t\temail)\n\t\t\t\t\t\t\t\tVALUES ('" . $this->TenderId . "',\n\t\t\t\t\t\t\t\t\t\t'" . $Supplier->SupplierCode . "',\n\t\t\t\t\t\t\t\t\t\t'" . $Supplier->EmailAddress . "')";
         }
         foreach ($this->LineItems as $LineItem) {
             $sql = "DELETE FROM tenderitems\n\t\t\t\t\t\tWHERE  tenderid='" . $this->TenderId . "'";
             $result = DB_query($sql, $db);
             $ItemsSQL[] = "INSERT INTO tenderitems (tenderid,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tstockid,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tquantity,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tunits)\n\t\t\t\t\t\t\t\tVALUES ('" . $this->TenderId . "',\n\t\t\t\t\t\t\t\t\t\t'" . $LineItem->StockID . "',\n\t\t\t\t\t\t\t\t\t\t'" . $LineItem->Quantity . "',\n\t\t\t\t\t\t\t\t\t\t'" . $LineItem->Units . "')";
         }
     }
     DB_Txn_Begin($db);
     $result = DB_query($HeaderSQL, $db, '', '', True);
     foreach ($SuppliersSQL as $sql) {
         $result = DB_query($sql, $db, '', '', True);
     }
     foreach ($ItemsSQL as $sql) {
         $result = DB_query($sql, $db, '', '', True);
     }
     DB_Txn_Commit($db);
 }
Exemple #5
0
 $PageNumber = 1;
 $line_height = 19;
 $Xpos = $Left_Margin + 1;
 //template
 if ($_POST['template'] == 'simple') {
     $template = 'simple';
 } elseif ($_POST['template'] == 'standard') {
     $template = 'standard';
 } elseif ($_POST['template'] == 'full') {
     $template = 'full';
 } else {
     $template = 'fullprices';
 }
 // Create Transfer Number
 if (!isset($Trf_ID) and $_POST['ReportType'] == 'Batch') {
     $Trf_ID = GetNextTransNo(16, $db);
 }
 // from location
 $ErrMsg = _('Could not retrieve location name from the database');
 $sqlfrom = "SELECT locationname FROM `locations` WHERE loccode='" . $_POST['FromLocation'] . "'";
 $result = DB_query($sqlfrom, $db, $ErrMsg);
 $Row = DB_fetch_row($result);
 $FromLocation = $Row['0'];
 // to location
 $sqlto = "SELECT locationname,\n\t\t\t\t\tcashsalecustomer,\n\t\t\t\t\tcashsalebranch\n\t\t\t\tFROM `locations`\n\t\t\t\tWHERE loccode='" . $_POST['ToLocation'] . "'";
 $resultto = DB_query($sqlto, $db, $ErrMsg);
 $RowTo = DB_fetch_row($resultto);
 $ToLocation = $RowTo['0'];
 $ToCustomer = $RowTo['1'];
 $ToBranch = $RowTo['2'];
 if ($template == 'fullprices') {
    }
}
if (isset($_POST['Submit'])) {
    DB_Txn_Begin($db);
    $InputError = 0;
    if ($_SESSION['Request']->Department == '') {
        prnMsg(_('You must select a Department for the request'), 'error');
        $InputError = 1;
    }
    if ($_SESSION['Request']->Location == '') {
        prnMsg(_('You must select a Location to request the items from'), 'error');
        $InputError = 1;
    }
    if ($InputError == 0) {
        if ($_SESSION['Request']->NewRequest == 0) {
            $_SESSION['Request']->ID = GetNextTransNo(38, $db);
            $HeaderSQL = "INSERT INTO stockrequest (dispatchid,\n\t\t\t\t\t\t\t\t\t\t\t\t\tloccode,\n\t\t\t\t\t\t\t\t\t\t\t\t\tuserid,\n\t\t\t\t\t\t\t\t\t\t\t\t\tdepartmentid,\n\t\t\t\t\t\t\t\t\t\t\t\t\tdespatchdate,\n\t\t\t\t\t\t\t\t\t\t\t\t\tnarrative)\n\t\t\t\t\t\t\t\t\t\t\t\tVALUES(\n\t\t\t\t\t\t\t\t\t\t\t\t\t'" . $_SESSION['Request']->ID . "',\n\t\t\t\t\t\t\t\t\t\t\t\t\t'" . $_SESSION['Request']->Location . "',\n\t\t\t\t\t\t\t\t\t\t\t\t\t'" . $_SESSION['UserID'] . "',\n\t\t\t\t\t\t\t\t\t\t\t\t\t'" . $_SESSION['Request']->Department . "',\n\t\t\t\t\t\t\t\t\t\t\t\t\t'" . FormatDateForSQL($_SESSION['Request']->DispatchDate) . "',\n\t\t\t\t\t\t\t\t\t\t\t\t\t'" . $_SESSION['Request']->Narrative . "')";
        } else {
            $HeaderSQL = "UPDATE stockrequest SET loccode='" . $_SESSION['Request']->Location . "',\n\t\t\t\t\t\t\t\t\t\t\t\t\tuserid='" . $_SESSION['UserID'] . "',\n\t\t\t\t\t\t\t\t\t\t\t\t\tdepartmentid='" . $_SESSION['Request']->Department . "',\n\t\t\t\t\t\t\t\t\t\t\t\t\tdespatchdate='" . FormatDateForSQL($_SESSION['Request']->DispatchDate) . "',\n\t\t\t\t\t\t\t\t\t\t\t\t\tnarrative='" . $_SESSION['Request']->Narrative . "'\n\t\t\t\t\t\t\t\t\t\t\t\tWHERE dispatchid='" . $_SESSION['Request']->ID . "'";
        }
        $ErrMsg = _('CRITICAL ERROR') . '! ' . _('NOTE DOWN THIS ERROR AND SEEK ASSISTANCE') . ': ' . _('The request header record could not be inserted because');
        $DbgMsg = _('The following SQL to insert the request header record was used');
        $Result = DB_query($HeaderSQL, $db, $ErrMsg, $DbgMsg, true);
        foreach ($_SESSION['Request']->LineItems as $LineItems) {
            $sql = "SELECT COUNT(stockid) as total FROM stockrequestitems\n\t\t\t\t\t\t\t\t\tWHERE dispatchid='" . $_SESSION['Request']->ID . "'\n\t\t\t\t\t\t\t\t\t\tAND dispatchitemsid='" . $LineItems->LineNumber . "'";
            $result = DB_query($sql, $db);
            $myrow = DB_fetch_array($result);
            if ($myrow['total'] == 0) {
                $LineSQL = "INSERT INTO stockrequestitems (dispatchitemsid,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tdispatchid,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tstockid,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tquantity,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tdecimalplaces,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tuom)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tVALUES(\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t'" . $LineItems->LineNumber . "',\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t'" . $_SESSION['Request']->ID . "',\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t'" . $LineItems->StockID . "',\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t'" . $LineItems->Quantity . "',\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t'" . $LineItems->DecimalPlaces . "',\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t'" . $LineItems->UOM . "')";
            } else {
                $LineSQL = "UPDATE stockrequestitems SET stockid='" . $LineItems->StockID . "',\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tquantity='" . $LineItems->Quantity . "',\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tdecimalplaces='" . $LineItems->DecimalPlaces . "',\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tuom='" . $LineItems->UOM . "'\n\t\t\t\t\t\t\t\t\t\t\t\t\tWHERE dispatchid='" . $_SESSION['Request']->ID . "'\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tAND dispatchitemsid='" . $LineItems->LineNumber . "'";
    }
    if ($InputError == 1) {
        foreach ($msg as $message) {
            prnMsg($message, 'info');
        }
    } else {
        $SalesAreaSQL = "SELECT areacode FROM areas";
        $SalesAreaResult = DB_query($SalesAreaSQL, $db);
        $SalesAreaRow = DB_fetch_array($SalesAreaResult);
        $SalesManSQL = "SELECT salesmancode FROM salesman";
        $SalesManResult = DB_query($SalesManSQL, $db);
        $SalesManRow = DB_fetch_array($SalesManResult);
        if ($_SESSION['AutoDebtorNo'] > 0) {
            /* system assigned, sequential, numeric */
            if ($_SESSION['AutoDebtorNo'] == 1) {
                $_POST['FileNumber'] = GetNextTransNo(500, $db);
            }
        }
        $sql = "INSERT INTO debtorsmaster (debtorno,\n\t\t\t\t\t\t\t\t\t\tname,\n\t\t\t\t\t\t\t\t\t\taddress1,\n\t\t\t\t\t\t\t\t\t\taddress2,\n\t\t\t\t\t\t\t\t\t\taddress3,\n\t\t\t\t\t\t\t\t\t\taddress4,\n\t\t\t\t\t\t\t\t\t\taddress5,\n\t\t\t\t\t\t\t\t\t\taddress6,\n\t\t\t\t\t\t\t\t\t\tcurrcode,\n\t\t\t\t\t\t\t\t\t\tsalestype,\n\t\t\t\t\t\t\t\t\t\tclientsince,\n\t\t\t\t\t\t\t\t\t\tholdreason,\n\t\t\t\t\t\t\t\t\t\tpaymentterms)\n\t\t\t\t\t\t\t\t\tVALUES (\n\t\t\t\t\t\t\t\t\t\t'" . $_POST['FileNumber'] . "',\n\t\t\t\t\t\t\t\t\t\t'" . $_POST['Name'] . "',\n\t\t\t\t\t\t\t\t\t\t'" . $_POST['Address1'] . "',\n\t\t\t\t\t\t\t\t\t\t'" . $_POST['Address2'] . "',\n\t\t\t\t\t\t\t\t\t\t'" . $_POST['Address3'] . "',\n\t\t\t\t\t\t\t\t\t\t'" . $_POST['Address4'] . "',\n\t\t\t\t\t\t\t\t\t\t'" . $_POST['Address5'] . "',\n\t\t\t\t\t\t\t\t\t\t'" . $_POST['Address6'] . "',\n\t\t\t\t\t\t\t\t\t\t'" . $_SESSION['CompanyRecord']['currencydefault'] . "',\n\t\t\t\t\t\t\t\t\t\t'" . $_POST['SalesType'] . "',\n\t\t\t\t\t\t\t\t\t\t'" . FormatDateForSQL($_POST['DateOfBirth']) . "',\n\t\t\t\t\t\t\t\t\t\t'" . $_POST['Sex'] . "',\n\t\t\t\t\t\t\t\t\t\t'20'\n\t\t\t\t\t\t\t\t\t)";
        $result = DB_query($sql, $db);
        $sql = "INSERT INTO custbranch (branchcode,\n\t\t\t\t\t\t\t\t\t\tdebtorno,\n\t\t\t\t\t\t\t\t\t\tbrname,\n\t\t\t\t\t\t\t\t\t\tarea,\n\t\t\t\t\t\t\t\t\t\tsalesman,\n\t\t\t\t\t\t\t\t\t\tphoneno,\n\t\t\t\t\t\t\t\t\t\tdefaultlocation,\n\t\t\t\t\t\t\t\t\t\ttaxgroupid)\n\t\t\t\t\t\t\t\t\tVALUES (\n\t\t\t\t\t\t\t\t\t\t'CASH',\n\t\t\t\t\t\t\t\t\t\t'" . $_POST['FileNumber'] . "',\n\t\t\t\t\t\t\t\t\t\t'CASH',\n\t\t\t\t\t\t\t\t\t\t'" . $SalesAreaRow['areacode'] . "',\n\t\t\t\t\t\t\t\t\t\t'" . $SalesManRow['salesmancode'] . "',\n\t\t\t\t\t\t\t\t\t\t'" . $_POST['Telephone'] . "',\n\t\t\t\t\t\t\t\t\t\t'" . $_SESSION['DefaultFactoryLocation'] . "',\n\t\t\t\t\t\t\t\t\t\t'1'\n\t\t\t\t\t\t\t\t\t)";
        $result = DB_query($sql, $db);
        if ($_POST['Insurance'] != '') {
            $sql = "INSERT INTO custbranch (branchcode,\n\t\t\t\t\t\t\t\t\t\t\tdebtorno,\n\t\t\t\t\t\t\t\t\t\t\tbrname,\n\t\t\t\t\t\t\t\t\t\t\tarea,\n\t\t\t\t\t\t\t\t\t\t\tsalesman,\n\t\t\t\t\t\t\t\t\t\t\tphoneno,\n\t\t\t\t\t\t\t\t\t\t\tdefaultlocation,\n\t\t\t\t\t\t\t\t\t\t\ttaxgroupid)\n\t\t\t\t\t\t\t\t\t\tVALUES (\n\t\t\t\t\t\t\t\t\t\t\t'" . $_POST['Insurance'] . "',\n\t\t\t\t\t\t\t\t\t\t\t'" . $_POST['FileNumber'] . "',\n\t\t\t\t\t\t\t\t\t\t\t'" . $_POST['Insurance'] . "',\n\t\t\t\t\t\t\t\t\t\t\t'" . $SalesAreaRow['areacode'] . "',\n\t\t\t\t\t\t\t\t\t\t\t'" . $SalesManRow['salesmancode'] . "',\n\t\t\t\t\t\t\t\t\t\t\t'" . $_POST['Telephone'] . "',\n\t\t\t\t\t\t\t\t\t\t\t'" . $_SESSION['DefaultFactoryLocation'] . "',\n\t\t\t\t\t\t\t\t\t\t\t'1'\n\t\t\t\t\t\t\t\t\t\t)";
            $result = DB_query($sql, $db);
        }
        prnMsg(_('The patient') . ' ' . $_POST['FileNumber'] . ' ' . _('has been successfully registered'), 'success');
    }
}
echo '<form action="' . $_SERVER['PHP_SELF'] . '" method=post>';
echo '<input type="hidden" name="FormID" value="' . $_SESSION['FormID'] . '" />';
     echo '<P>';
     prnMsg(_('The quantity entered must be numeric'), 'error');
     $InputError = true;
 } elseif ($_SESSION['Transfer']->TransferItem[0]->Quantity <= 0) {
     echo '<P>';
     prnMsg(_('The quantity entered must be a positive number greater than zero'), 'error');
     $InputError = true;
 }
 if ($_SESSION['Transfer']->StockLocationFrom == $_SESSION['Transfer']->StockLocationTo) {
     echo '<P>';
     prnMsg(_('The locations to transfer from and to must be different'), 'error');
     $InputError = true;
 }
 if ($InputError == False) {
     /*All inputs must be sensible so make the stock movement records and update the locations stocks */
     $TransferNumber = GetNextTransNo(16, $db);
     $PeriodNo = GetPeriod(Date($_SESSION['DefaultDateFormat']), $db);
     $SQLTransferDate = FormatDateForSQL(Date($_SESSION['DefaultDateFormat']));
     $Result = DB_Txn_Begin($db);
     // Need to get the current location quantity will need it later for the stock movement
     $SQL = "SELECT locstock.quantity\n\t\t\tFROM locstock\n\t\t\tWHERE locstock.stockid='" . $_SESSION['Transfer']->TransferItem[0]->StockID . "'\n\t\t\tAND loccode= '" . $_SESSION['Transfer']->StockLocationFrom . "'";
     $ErrMsg = _('Could not retrieve the QOH at the sending location because');
     $DbgMsg = _('The SQL that failed was');
     $Result = DB_query($SQL, $db, $ErrMsg, $DbgMsg, true);
     if (DB_num_rows($Result) == 1) {
         $LocQtyRow = DB_fetch_row($Result);
         $QtyOnHandPrior = $LocQtyRow[0];
     } else {
         // There must actually be some error this should never happen
         $QtyOnHandPrior = 0;
     }
             					 exrate    (1 EUR =  (0.85 x 0.90)/0.52 USD)
             					 					(ExRate x FunctionalExRate) / USD Functional ExRate
             					 functionalexrate =     (1NZD = EUR 0.52)
             
             				*/
             $ReceiptTransNo = GetNextTransNo(2, $db);
             $SQL = "INSERT INTO banktrans (transno,\n\t\t\t\t\t\t\t\t\t\t\t\t\ttype,\n\t\t\t\t\t\t\t\t\t\t\t\t\tbankact,\n\t\t\t\t\t\t\t\t\t\t\t\t\tref,\n\t\t\t\t\t\t\t\t\t\t\t\t\texrate,\n\t\t\t\t\t\t\t\t\t\t\t\t\tfunctionalexrate,\n\t\t\t\t\t\t\t\t\t\t\t\t\ttransdate,\n\t\t\t\t\t\t\t\t\t\t\t\t\tbanktranstype,\n\t\t\t\t\t\t\t\t\t\t\t\t\tamount,\n\t\t\t\t\t\t\t\t\t\t\t\t\tcurrcode)\n\t\t\t\t\t\tVALUES ('" . $ReceiptTransNo . "',\n\t\t\t\t\t\t\t2,\n\t\t\t\t\t\t\t'" . $PaymentItem->GLCode . "',\n\t\t\t\t\t\t\t'" . _('Act Transfer From ') . $_SESSION['PaymentDetail' . $identifier]->Account . ' - ' . $PaymentItem->Narrative . "',\n\t\t\t\t\t\t\t'" . $_SESSION['PaymentDetail' . $identifier]->ExRate * $_SESSION['PaymentDetail' . $identifier]->FunctionalExRate / $TrfToBankExRate . "',\n\t\t\t\t\t\t\t'" . $TrfToBankExRate . "',\n\t\t\t\t\t\t\t'" . FormatDateForSQL($_SESSION['PaymentDetail' . $identifier]->DatePaid) . "',\n\t\t\t\t\t\t\t'" . $_SESSION['PaymentDetail' . $identifier]->Paymenttype . "',\n\t\t\t\t\t\t\t'" . $PaymentItem->Amount . "',\n\t\t\t\t\t\t\t'" . $_SESSION['PaymentDetail' . $identifier]->Currency . "'\n\t\t\t\t\t\t)";
             $ErrMsg = _('Cannot insert a bank transaction because');
             $DbgMsg = _('Cannot insert a bank transaction with the SQL');
             $result = DB_query($SQL, $db, $ErrMsg, $DbgMsg, true);
         }
     }
 } else {
     /*Its a supplier payment type 22 */
     $CreditorTotal = ($_SESSION['PaymentDetail' . $identifier]->Discount + $_SESSION['PaymentDetail' . $identifier]->Amount) / $_SESSION['PaymentDetail' . $identifier]->ExRate / $_SESSION['PaymentDetail' . $identifier]->FunctionalExRate;
     $TransNo = GetNextTransNo(22, $db);
     $TransType = 22;
     /* Create a SuppTrans entry for the supplier payment */
     $SQL = "INSERT INTO supptrans (transno,\n\t\t\t\t\t\t\t\t\t\t\ttype,\n\t\t\t\t\t\t\t\t\t\t\tsupplierno,\n\t\t\t\t\t\t\t\t\t\t\ttrandate,\n\t\t\t\t\t\t\t\t\t\t\tinputdate,\n\t\t\t\t\t\t\t\t\t\t\tsuppreference,\n\t\t\t\t\t\t\t\t\t\t\trate,\n\t\t\t\t\t\t\t\t\t\t\tovamount,\n\t\t\t\t\t\t\t\t\t\t\ttranstext) ";
     $SQL = $SQL . "valueS ('" . $TransNo . "',\n\t\t\t\t\t22,\n\t\t\t\t\t'" . $_SESSION['PaymentDetail' . $identifier]->SupplierID . "',\n\t\t\t\t\t'" . FormatDateForSQL($_SESSION['PaymentDetail' . $identifier]->DatePaid) . "',\n\t\t\t\t\t'" . date('Y-m-d H-i-s') . "',\n\t\t\t\t\t'" . $_SESSION['PaymentDetail' . $identifier]->Paymenttype . "',\n\t\t\t\t\t'" . $_SESSION['PaymentDetail' . $identifier]->FunctionalExRate / $_SESSION['PaymentDetail' . $identifier]->ExRate . "',\n\t\t\t\t\t'" . (-$_SESSION['PaymentDetail' . $identifier]->Amount - $_SESSION['PaymentDetail' . $identifier]->Discount) . "',\n\t\t\t\t\t'" . $_SESSION['PaymentDetail' . $identifier]->Narrative . "'\n\t\t\t\t)";
     $ErrMsg = _('Cannot insert a payment transaction against the supplier because');
     $DbgMsg = _('Cannot insert a payment transaction against the supplier using the SQL');
     $result = DB_query($SQL, $db, $ErrMsg, $DbgMsg, true);
     /*Update the supplier master with the date and amount of the last payment made */
     $SQL = "UPDATE suppliers\n\t\t\t\t\tSET\tlastpaiddate = '" . FormatDateForSQL($_SESSION['PaymentDetail' . $identifier]->DatePaid) . "',\n\t\t\t\t\t\tlastpaid='" . $_SESSION['PaymentDetail' . $identifier]->Amount . "'\n\t\t\t\t\tWHERE suppliers.supplierid='" . $_SESSION['PaymentDetail' . $identifier]->SupplierID . "'";
     $ErrMsg = _('Cannot update the supplier record for the date of the last payment made because');
     $DbgMsg = _('Cannot update the supplier record for the date of the last payment made using the SQL');
     $result = DB_query($SQL, $db, $ErrMsg, $DbgMsg, true);
     $_SESSION['PaymentDetail' . $identifier]->Narrative = $_SESSION['PaymentDetail' . $identifier]->SupplierID . '-' . $_SESSION['PaymentDetail' . $identifier]->Narrative;
     if ($_SESSION['CompanyRecord']['gllink_creditors'] == 1) {
         /* then do the supplier control GLTrans */
 }
 /* end of the costing specific updates */
 if ($_SESSION['CompanyRecord']['gllink_stock'] == 1) {
     /*we always need to reverse entries relating to the GRN suspense during delivery and entry of shipment charges */
     $sql = "INSERT INTO gltrans (type,\n\t\t\t\t\t\t\ttypeno,\n\t\t\t\t\t\t\ttrandate,\n\t\t\t\t\t\t\tperiodno,\n\t\t\t\t\t\t\taccount,\n\t\t\t\t\t\t\tnarrative,\n\t\t\t\t\t\t\tamount)\n\t\t\t\tVALUES (31,\n\t\t\t\t\t" . $_GET['SelectedShipment'] . ",\n\t\t\t\t\t'" . Date('Y-m-d') . "',\n\t\t\t\t\t" . $PeriodNo . ",\n\t\t\t\t\t" . $_SESSION['CompanyRecord']['grnact'] . ",\n\t\t\t\t\t'" . $myrow['itemcode'] . ' ' . _('shipt cost') . ' ' . number_format($ItemShipmentCost, 2) . ' x ' . _('Qty invoiced') . ' ' . $myrow['totqtyinvoiced'] . "',\n                                        " . $Variance * $myrow['totqtyinvoiced'] . ")";
     $ErrMsg = _('CRITICAL ERROR') . '! ' . _('NOTE DOWN THIS ERROR AND SEEK ASSISTANCE') . ': ' . _('The credit GL entry for the shipment variance posting for') . ' ' . $myrow['itemcode'] . ' ' . _('could not be inserted because');
     $result = DB_query($sql, $db, $ErrMsg, '', TRUE);
 }
 if ($_POST['UpdateCost'] == 'Yes') {
     /*Only ever a standard costing option
       Weighted average costing implies cost updates taking place automatically */
     $QOHResult = DB_query("SELECT SUM(quantity) FROM locstock WHERE stockid ='" . $myrow['itemcode'] . "'", $db);
     $QOHRow = DB_fetch_row($QOHResult);
     $QOH = $QOHRow[0];
     if ($_SESSION['CompanyRecord']['gllink_stock'] == 1) {
         $CostUpdateNo = GetNextTransNo(35, $db);
         $PeriodNo = GetPeriod(Date("d/m/Y"), $db);
         $ValueOfChange = $QOH * ($ItemShipmentCost - $StdCostUnit);
         $SQL = "INSERT INTO gltrans (type,\n\t\t\t\t\t\t\t\ttypeno,\n\t\t\t\t\t\t\t\ttrandate,\n\t\t\t\t\t\t\t\tperiodno,\n\t\t\t\t\t\t\t\taccount,\n\t\t\t\t\t\t\t\tnarrative,\n\t\t\t\t\t\t\t\tamount)\n\t\t\t\t\t\tVALUES (35,\n\t\t\t\t\t\t\t" . $CostUpdateNo . ",\n\t\t\t\t\t\t\t'" . Date('Y-m-d') . "',\n\t\t\t\t\t\t\t" . $PeriodNo . ",\n\t\t\t\t\t\t\t" . $StockGLCodes['adjglact'] . ",\n\t\t\t\t\t\t\t'" . _('Shipment of') . ' ' . $myrow['itemcode'] . " " . _('cost was') . ' ' . $StdCostUnit . ' ' . _('changed to') . ' ' . number_format($ItemShipmentCost, 2) . ' x ' . _('QOH of') . ' ' . $QOH . "', " . -$ValueOfChange . ")";
         $ErrMsg = _('CRITICAL ERROR') . '! ' . _('NOTE DOWN THIS ERROR AND SEEK ASSISTANCE') . ': ' . _('The GL credit for the shipment stock cost adjustment posting could not be inserted because') . ' ' . DB_error_msg($db);
         $Result = DB_query($SQL, $db, $ErrMsg, '', TRUE);
         $SQL = "INSERT INTO gltrans (type,\n\t\t\t\t\t\t\t\ttypeno,\n\t\t\t\t\t\t\t\ttrandate,\n\t\t\t\t\t\t\t\tperiodno,\n\t\t\t\t\t\t\t\taccount,\n\t\t\t\t\t\t\t\tnarrative,\n\t\t\t\t\t\t\t\tamount)\n\t\t\t\t\t\tVALUES (35,\n\t\t\t\t\t\t\t" . $CostUpdateNo . ",\n\t\t\t\t\t\t\t'" . Date('Y-m-d') . "',\n\t\t\t\t\t\t\t" . $PeriodNo . ",\n\t\t\t\t\t\t\t" . $StockGLCodes['stockact'] . ",\n\t\t\t\t\t\t\t'" . _('Shipment of') . ' ' . $myrow['itemcode'] . ' ' . _('cost was') . ' ' . $StdCostUnit . ' ' . _('changed to') . ' ' . number_format($ItemShipmentCost, 2) . ' x ' . _('QOH of') . ' ' . $QOH . "',\n                                                        " . $ValueOfChange . ")";
         $ErrMsg = _('CRITICAL ERROR') . '! ' . _('NOTE DOWN THIS ERROR AND SEEK ASSISTANCE') . ': ' . _('The GL debit for stock cost adjustment posting could not be inserted because') . ' ' . DB_error_msg($db);
         $Result = DB_query($SQL, $db, $ErrMsg, '', TRUE);
     }
     /*end of GL entries for a standard cost update */
     /* Only the material cost is important for imported items */
     $sql = "UPDATE stockmaster SET materialcost=" . $ItemShipmentCost . ",\n\t\t\t\t\t\t\t\tlabourcost=0,\n\t\t\t\t\t\t\t\toverheadcost=0,\n\t\t\t\t\t\t\t\tlastcost=" . $StdCostUnit . "\n\t\t\t\t\t\tWHERE stockid='" . $myrow['itemcode'] . "'";
     $ErrMsg = _('CRITICAL ERROR') . '! ' . _('NOTE DOWN THIS ERROR AND SEEK ASSISTANCE') . ': ' . _('The shipment cost details for the stock item could not be updated because') . ': ' . DB_error_msg($db);
     $result = DB_query($sql, $db, $ErrMsg, '', TRUE);
 }
     $DemandDate = $DemRow[2];
 }
 if ($StockQOH < 0) {
     $StockQOH = 0;
 }
 if ($StockQOH + $StockQOWO - $StockDemand < 0) {
     $DemandQuantity = $StockDemand - ($StockQOH + $StockQOWO);
     if ($StockEOQ > 0) {
         if ($StockEOQ > $DemandQuantity) {
             $DemandQuantity = $StockEOQ;
         } else {
             $EOQMultiple = Round($DemandQuantity / $StockEOQ + 0.49, 0);
             $DemandQuantity = $StockEOQ * $EOQMultiple;
         }
     }
     $WO = GetNextTransNo(30, $db);
     // echo $WO. "= WO<BR>";
     $InsWOResult = DB_query("INSERT INTO workorders (wo,\n                                                     loccode,\n                                                     requiredby,\n                                                     startdate)\n                                     VALUES (" . $WO . ",\n                                            '" . $_SESSION['UserStockLocation'] . "',\n                                            '" . $DemandDate . "',\n                                            '" . Date('Y-m-d') . "')", $db);
     $sql = "INSERT INTO woitems (wo,\n\t                             stockid,\n\t                             qtyreqd,\n\t                             stdcost)\n\t         VALUES ( " . $WO . ",\n                         '" . $StockId . "',\n                         " . $DemandQuantity . ",\n                          0)";
     $result = DB_query($sql, $db, $ErrMsg);
     $sql2 = "INSERT INTO worequirements (wo,\n                                            parentstockid,\n                                            stockid,\n                                            qtypu,\n                                            stdcost,\n                                            autoissue)\n      \t                 SELECT " . $WO . ",\n        \t                           bom.parent,\n                                       bom.component,\n                                       bom.quantity,\n                                       (materialcost+labourcost+overheadcost)*bom.quantity,\n                                       autoissue\n                         FROM bom INNER JOIN stockmaster\n                         ON bom.component=stockmaster.stockid\n                         WHERE parent='" . $StockId . "'\n                         AND loccode ='" . $_POST['StockLocation'] . "'";
     $result = DB_query($sql2, $db, $ErrMsg);
     echo '<tr><TD>' . $StockId . '</TD>';
     echo '<td>' . $WO . '</td>';
     echo '<TD>' . $StockDescription . '</td>';
     echo '<td class="label">' . $DemandQuantity . '</td>';
     $PictureToDisplay = '/srv/www/htdocs/batavg/webERP2/companies/' . $_SESSION['DatabaseName'] . '/part_pics/' . $StockId . '.jpg';
     if (file_exists($PictureToDisplay)) {
         echo '<td class="label">OK</td>';
     } else {
         echo '<td class="label">Need Picture</td>';
             $DbgMsg = _('The SQL that was used to create the stock cost journal and failed was');
             $result = DB_query($SQL, $ErrMsg, $DbgMsg, true);
             $SQL = "INSERT INTO gltrans (type,\n\t\t\t\t\t\t\t\t\t\t\t\ttypeno,\n\t\t\t\t\t\t\t\t\t\t\t\ttrandate,\n\t\t\t\t\t\t\t\t\t\t\t\tperiodno,\n\t\t\t\t\t\t\t\t\t\t\t\taccount,\n\t\t\t\t\t\t\t\t\t\t\t\tnarrative,\n\t\t\t\t\t\t\t\t\t\t\t\tamount)\n\t\t\t\t\t\t\t\t\t\tVALUES ( 0,\n\t\t\t\t\t\t\t\t\t\t\t\t'" . $JournalNo . "',\n\t\t\t\t\t\t\t\t\t\t\t\t'" . Date('Y-m-d') . "',\n\t\t\t\t\t\t\t\t\t\t\t\t'" . GetPeriod(Date($_SESSION['DefaultDateFormat']), $db, true) . "',\n\t\t\t\t\t\t\t\t\t\t\t\t'" . $OldStockAccount . "',\n\t\t\t\t\t\t\t\t\t\t\t\t'" . $StockID . ' ' . _('Change stock category') . "',\n\t\t\t\t\t\t\t\t\t\t\t\t'" . -$UnitCost * $StockQtyRow[0] . "')";
             $result = DB_query($SQL, $ErrMsg, $DbgMsg, true);
         }
         /* end if the stock category changed and forced a change in stock cost account */
         if ($OldWIPAccount != $NewWIPAct and $_SESSION['CompanyRecord']['gllink_stock'] == 1) {
             /*Then we need to make a journal to transfer the cost  of WIP to the new WIP account */
             /*First get the total cost of WIP for this category */
             $WOCostsResult = DB_query("SELECT workorders.costissued,\n\t\t\t\t\t\t\t\t\t\t\t\t\tSUM(woitems.qtyreqd * woitems.stdcost) AS costrecd\n\t\t\t\t\t\t\t\t\t\t\t\tFROM woitems INNER JOIN workorders\n\t\t\t\t\t\t\t\t\t\t\t\tON woitems.wo = workorders.wo\n\t\t\t\t\t\t\t\t\t\t\t\tINNER JOIN stockmaster\n\t\t\t\t\t\t\t\t\t\t\t\tON woitems.stockid=stockmaster.stockid\n\t\t\t\t\t\t\t\t\t\t\t\tWHERE stockmaster.stockid='" . $StockID . "'\n\t\t\t\t\t\t\t\t\t\t\t\tAND workorders.closed=0\n\t\t\t\t\t\t\t\t\t\t\t\tGROUP BY workorders.costissued", _('Error retrieving value of finished goods received and cost issued against work orders for this item'));
             $WIPValue = 0;
             while ($WIPRow = DB_fetch_array($WOCostsResult)) {
                 $WIPValue += $WIPRow['costissued'] - $WIPRow['costrecd'];
             }
             if ($WIPValue != 0) {
                 $JournalNo = GetNextTransNo(0, $db);
                 //enter as a journal
                 $SQL = "INSERT INTO gltrans (type,\n\t\t\t\t\t\t\t\t\t\t\t\t\ttypeno,\n\t\t\t\t\t\t\t\t\t\t\t\t\ttrandate,\n\t\t\t\t\t\t\t\t\t\t\t\t\tperiodno,\n\t\t\t\t\t\t\t\t\t\t\t\t\taccount,\n\t\t\t\t\t\t\t\t\t\t\t\t\tnarrative,\n\t\t\t\t\t\t\t\t\t\t\t\t\tamount)\n\t\t\t\t\t\t\t\t\t\t\tVALUES ( 0,\n\t\t\t\t\t\t\t\t\t\t\t\t\t'" . $JournalNo . "',\n\t\t\t\t\t\t\t\t\t\t\t\t\t'" . Date('Y-m-d') . "',\n\t\t\t\t\t\t\t\t\t\t\t\t\t'" . GetPeriod(Date($_SESSION['DefaultDateFormat']), $db, true) . "',\n\t\t\t\t\t\t\t\t\t\t\t\t\t'" . $NewWIPAct . "',\n\t\t\t\t\t\t\t\t\t\t\t\t\t'" . $StockID . ' ' . _('Change stock category') . "',\n\t\t\t\t\t\t\t\t\t\t\t\t\t'" . $WIPValue . "')";
                 $ErrMsg = _('The WIP cost journal could not be inserted because');
                 $DbgMsg = _('The SQL that was used to create the WIP cost journal and failed was');
                 $result = DB_query($SQL, $ErrMsg, $DbgMsg, true);
                 $SQL = "INSERT INTO gltrans (type,\n\t\t\t\t\t\t\t\t\t\t\t\t\ttypeno,\n\t\t\t\t\t\t\t\t\t\t\t\t\ttrandate,\n\t\t\t\t\t\t\t\t\t\t\t\t\tperiodno,\n\t\t\t\t\t\t\t\t\t\t\t\t\taccount,\n\t\t\t\t\t\t\t\t\t\t\t\t\tnarrative,\n\t\t\t\t\t\t\t\t\t\t\t\t\tamount)\n\t\t\t\t\t\t\t\t\t\t\tVALUES ( 0,\n\t\t\t\t\t\t\t\t\t\t\t\t\t'" . $JournalNo . "',\n\t\t\t\t\t\t\t\t\t\t\t\t\t'" . Date('Y-m-d') . "',\n\t\t\t\t\t\t\t\t\t\t\t\t\t'" . GetPeriod(Date($_SESSION['DefaultDateFormat']), $db, true) . "',\n\t\t\t\t\t\t\t\t\t\t\t\t\t'" . $OldWIPAccount . "',\n\t\t\t\t\t\t\t\t\t\t\t\t\t'" . $StockID . ' ' . _('Change stock category') . "',\n\t\t\t\t\t\t\t\t\t\t\t\t\t'" . -$WIPValue . "')";
                 $result = DB_query($SQL, $ErrMsg, $DbgMsg, true);
             }
         }
         /* end if the stock category changed and forced a change in WIP account */
         DB_Txn_Commit();
         prnMsg(_('Stock Item') . ' ' . $StockID . ' ' . _('has been updated'), 'success');
         echo '<br />';
     }
 } else {
    $_POST['BankStatementBalance'] = filter_number_format($_POST['BankStatementBalance']);
}
if (isset($_POST['PostExchangeDifference']) and is_numeric(filter_number_format($_POST['DoExchangeDifference']))) {
    if (!is_numeric($_POST['BankStatementBalance'])) {
        prnMsg(_('The entry in the bank statement balance is not numeric. The balance on the bank statement should be entered. The exchange difference has not been calculated and no general ledger journal has been created'), 'warn');
        echo '<br />' . $_POST['BankStatementBalance'];
    } else {
        /* Now need to get the currency of the account and the current table ex rate */
        $SQL = "SELECT rate,\n\t\t\t\t\t\tbankaccountname,\n\t\t\t\t\t\tdecimalplaces AS currdecimalplaces\n\t\t\t\tFROM bankaccounts\n\t\t\t\tINNER JOIN currencies\n\t\t\t\t\tON bankaccounts.currcode=currencies.currabrev\n\t\t\t\tWHERE bankaccounts.accountcode = '" . $_POST['BankAccount'] . "'";
        $ErrMsg = _('Could not retrieve the exchange rate for the selected bank account');
        $CurrencyResult = DB_query($SQL, $db);
        $CurrencyRow = DB_fetch_array($CurrencyResult);
        $CalculatedBalance = filter_number_format($_POST['DoExchangeDifference']);
        $ExchangeDifference = ($CalculatedBalance - filter_number_format($_POST['BankStatementBalance'])) / $CurrencyRow['rate'];
        include 'includes/SQL_CommonFunctions.inc';
        $ExDiffTransNo = GetNextTransNo(36, $db);
        /*Post the exchange difference to the last day of the month prior to current date*/
        $PostingDate = Date($_SESSION['DefaultDateFormat'], mktime(0, 0, 0, Date('m'), 0, Date('Y')));
        $PeriodNo = GetPeriod($PostingDate, $db);
        $Result = DB_Txn_Begin($db);
        //yet to code the journal
        $SQL = "INSERT INTO gltrans (type,\n\t\t\t\t\t\t\t\t\ttypeno,\n\t\t\t\t\t\t\t\t\ttrandate,\n\t\t\t\t\t\t\t\t\tperiodno,\n\t\t\t\t\t\t\t\t\taccount,\n\t\t\t\t\t\t\t\t\tnarrative,\n\t\t\t\t\t\t\t\t\tamount)\n\t\t\t\t\t\t\t\t  VALUES (36,\n\t\t\t\t\t\t\t\t\t'" . $ExDiffTransNo . "',\n\t\t\t\t\t\t\t\t\t'" . FormatDateForSQL($PostingDate) . "',\n\t\t\t\t\t\t\t\t\t'" . $PeriodNo . "',\n\t\t\t\t\t\t\t\t\t'" . $_SESSION['CompanyRecord']['exchangediffact'] . "',\n\t\t\t\t\t\t\t\t\t'" . $CurrencyRow['bankaccountname'] . ' ' . _('reconciliation on') . " " . Date($_SESSION['DefaultDateFormat']) . "','" . $ExchangeDifference . "')";
        $ErrMsg = _('Cannot insert a GL entry for the exchange difference because');
        $DbgMsg = _('The SQL that failed to insert the exchange difference GL entry was');
        $Result = DB_query($SQL, $db, $ErrMsg, $DbgMsg, true);
        $SQL = "INSERT INTO gltrans (type,\n\t\t\t\t\t\t\t\t\ttypeno,\n\t\t\t\t\t\t\t\t\ttrandate,\n\t\t\t\t\t\t\t\t\tperiodno,\n\t\t\t\t\t\t\t\t\taccount,\n\t\t\t\t\t\t\t\t\tnarrative,\n\t\t\t\t\t\t\t\t\tamount)\n\t\t\t\t\t\t\t\t  VALUES (36,\n\t\t\t\t\t\t\t\t\t'" . $ExDiffTransNo . "',\n\t\t\t\t\t\t\t\t\t'" . FormatDateForSQL($PostingDate) . "',\n\t\t\t\t\t\t\t\t\t'" . $PeriodNo . "',\n\t\t\t\t\t\t\t\t\t'" . $_POST['BankAccount'] . "',\n\t\t\t\t\t\t\t\t\t'" . $CurrencyRow['bankaccountname'] . ' ' . _('reconciliation on') . ' ' . Date($_SESSION['DefaultDateFormat']) . "',\n\t\t\t\t\t\t\t\t\t'" . -$ExchangeDifference . "')";
        $Result = DB_query($SQL, $db, $ErrMsg, $DbgMsg, true);
        $Result = DB_Txn_Commit($db);
        prnMsg(_('Exchange difference of') . ' ' . locale_number_format($ExchangeDifference, $_SESSION['CompanyRecord']['decimalplaces']) . ' ' . _('has been posted'), 'success');
    }
    //end if the bank statement balance was numeric
         $AccountTo = $myrowAccExp['glaccount'];
         $TagTo = $myrowAccExp['tag'];
     }
     //get typeno
     $typeno = GetNextTransNo($type, $db);
     //build narrative
     $Narrative = _('PettyCash') . ' - ' . $myrow['tabcode'] . ' - ' . $myrow['codeexpense'] . ' - ' . DB_escape_string($myrow['notes']) . ' - ' . $myrow['receipt'];
     //insert to gltrans
     DB_Txn_Begin($db);
     $sqlFrom = "INSERT INTO `gltrans` (`counterindex`,\n\t\t\t\t\t\t\t\t\t\t\t`type`,\n\t\t\t\t\t\t\t\t\t\t\t`typeno`,\n\t\t\t\t\t\t\t\t\t\t\t`chequeno`,\n\t\t\t\t\t\t\t\t\t\t\t`trandate`,\n\t\t\t\t\t\t\t\t\t\t\t`periodno`,\n\t\t\t\t\t\t\t\t\t\t\t`account`,\n\t\t\t\t\t\t\t\t\t\t\t`narrative`,\n\t\t\t\t\t\t\t\t\t\t\t`amount`,\n\t\t\t\t\t\t\t\t\t\t\t`posted`,\n\t\t\t\t\t\t\t\t\t\t\t`jobref`,\n\t\t\t\t\t\t\t\t\t\t\t`tag`)\n\t\t\t\t\t\t\t\t\tVALUES (NULL,\n\t\t\t\t\t\t\t\t\t\t\t'" . $type . "',\n\t\t\t\t\t\t\t\t\t\t\t'" . $typeno . "',\n\t\t\t\t\t\t\t\t\t\t\t0,\n\t\t\t\t\t\t\t\t\t\t\t'" . $myrow['date'] . "',\n\t\t\t\t\t\t\t\t\t\t\t'" . $PeriodNo . "',\n\t\t\t\t\t\t\t\t\t\t\t'" . $AccountFrom . "',\n\t\t\t\t\t\t\t\t\t\t\t'" . $Narrative . "',\n\t\t\t\t\t\t\t\t\t\t\t'" . -$Amount . "',\n\t\t\t\t\t\t\t\t\t\t\t0,\n\t\t\t\t\t\t\t\t\t\t\t'',\n\t\t\t\t\t\t\t\t\t\t\t'" . $TagTo . "')";
     $ResultFrom = DB_Query($sqlFrom, $db, '', '', true);
     $sqlTo = "INSERT INTO `gltrans` (`counterindex`,\n\t\t\t\t\t\t\t\t\t\t`type`,\n\t\t\t\t\t\t\t\t\t\t`typeno`,\n\t\t\t\t\t\t\t\t\t\t`chequeno`,\n\t\t\t\t\t\t\t\t\t\t`trandate`,\n\t\t\t\t\t\t\t\t\t\t`periodno`,\n\t\t\t\t\t\t\t\t\t\t`account`,\n\t\t\t\t\t\t\t\t\t\t`narrative`,\n\t\t\t\t\t\t\t\t\t\t`amount`,\n\t\t\t\t\t\t\t\t\t\t`posted`,\n\t\t\t\t\t\t\t\t\t\t`jobref`,\n\t\t\t\t\t\t\t\t\t\t`tag`)\n\t\t\t\t\t\t\t\tVALUES (NULL,\n\t\t\t\t\t\t\t\t\t\t'" . $type . "',\n\t\t\t\t\t\t\t\t\t\t'" . $typeno . "',\n\t\t\t\t\t\t\t\t\t\t0,\n\t\t\t\t\t\t\t\t\t\t'" . $myrow['date'] . "',\n\t\t\t\t\t\t\t\t\t\t'" . $PeriodNo . "',\n\t\t\t\t\t\t\t\t\t\t'" . $AccountTo . "',\n\t\t\t\t\t\t\t\t\t\t'" . $Narrative . "',\n\t\t\t\t\t\t\t\t\t\t'" . $Amount . "',\n\t\t\t\t\t\t\t\t\t\t0,\n\t\t\t\t\t\t\t\t\t\t'',\n\t\t\t\t\t\t\t\t\t\t'" . $TagTo . "')";
     $ResultTo = DB_Query($sqlTo, $db, '', '', true);
     if ($myrow['codeexpense'] == 'ASSIGNCASH') {
         // if it's a cash assignation we need to updated banktrans table as well.
         $ReceiptTransNo = GetNextTransNo(2, $db);
         $SQLBank = "INSERT INTO banktrans (transno,\n\t\t\t\t\t\t\t\t\t\t\t\ttype,\n\t\t\t\t\t\t\t\t\t\t\t\tbankact,\n\t\t\t\t\t\t\t\t\t\t\t\tref,\n\t\t\t\t\t\t\t\t\t\t\t\texrate,\n\t\t\t\t\t\t\t\t\t\t\t\tfunctionalexrate,\n\t\t\t\t\t\t\t\t\t\t\t\ttransdate,\n\t\t\t\t\t\t\t\t\t\t\t\tbanktranstype,\n\t\t\t\t\t\t\t\t\t\t\t\tamount,\n\t\t\t\t\t\t\t\t\t\t\t\tcurrcode)\n\t\t\t\t\t\t\t\t\t\tVALUES ('" . $ReceiptTransNo . "',\n\t\t\t\t\t\t\t\t\t\t\t1,\n\t\t\t\t\t\t\t\t\t\t\t'" . $AccountFrom . "',\n\t\t\t\t\t\t\t\t\t\t\t'" . $Narrative . "',\n\t\t\t\t\t\t\t\t\t\t\t1,\n\t\t\t\t\t\t\t\t\t\t\t'" . $myrow['rate'] . "',\n\t\t\t\t\t\t\t\t\t\t\t'" . $myrow['date'] . "',\n\t\t\t\t\t\t\t\t\t\t\t'Cash',\n\t\t\t\t\t\t\t\t\t\t\t'" . -$myrow['amount'] . "',\n\t\t\t\t\t\t\t\t\t\t\t'" . $myrow['currency'] . "'\n\t\t\t\t\t\t\t\t\t\t)";
         $ErrMsg = _('Cannot insert a bank transaction because');
         $DbgMsg = _('Cannot insert a bank transaction with the SQL');
         $resultBank = DB_query($SQLBank, $db, $ErrMsg, $DbgMsg, true);
     }
     $sql = "UPDATE pcashdetails\n\t\t\t\t\tSET authorized = '" . Date('Y-m-d') . "',\n\t\t\t\t\tposted = 1\n\t\t\t\t\tWHERE counterindex = '" . $myrow['counterindex'] . "'";
     $resultupdate = DB_query($sql, $db, '', '', true);
     DB_Txn_Commit($db);
 }
 if ($k == 1) {
     echo '<tr class="EvenTableRows">';
     $k = 0;
 } else {
     echo '<tr class="OddTableRows">';
     $k = 1;
     if ($_SESSION['Items']->LineItems[$myrow['orderlineno']]->Quantity != $myrow['quantity'] or $_SESSION['Items']->LineItems[$myrow['orderlineno']]->QtyInv != $myrow['qtyinvoiced']) {
         echo '<br>' . _('Orig order for') . ' ' . $myrow['orderlineno'] . ' ' . _('has a quantity of') . ' ' . $myrow['quantity'] . ' ' . _('and an invoiced qty of') . ' ' . $myrow['qtyinvoiced'] . ' ' . _('the session shows quantity of') . ' ' . $_SESSION['Items']->LineItems[$myrow['orderlineno']]->Quantity . ' ' . _('and quantity invoice of') . ' ' . $_SESSION['Items']->LineItems[$myrow['orderlineno']]->QtyInv;
         prnMsg(_('This order has been changed or invoiced since this delivery was started to be confirmed') . ' ' . _('Processing halted.') . ' ' . _('To enter and confirm this dispatch, it must be re-selected and re-read again to update the changes made by the other user'), 'error');
         echo '<br>';
         echo '<div class="centre"><a href="' . $rootpath . '/SelectSalesOrder.php?' . SID . '">' . _('Select a sales order for confirming deliveries and invoicing') . '</a></div>';
         unset($_SESSION['Items']->LineItems);
         unset($_SESSION['Items']);
         unset($_SESSION['ProcessingOrder']);
         include 'includes/footer.inc';
         exit;
     }
 }
 /*loop through all line items of the order to ensure none have been invoiced since started looking at this order*/
 DB_free_result($Result);
 /*Now Get the next invoice number - function in SQL_CommonFunctions*/
 $InvoiceNo = GetNextTransNo(10, $db);
 $PeriodNo = GetPeriod($DefaultDispatchDate, $db);
 /*Start an SQL transaction */
 DB_Txn_Begin($db);
 if ($DefaultShipVia != $_SESSION['Items']->ShipVia) {
     $SQL = "UPDATE custbranch SET defaultshipvia ='" . $_SESSION['Items']->ShipVia . "' WHERE debtorno='" . $_SESSION['Items']->DebtorNo . "' AND branchcode='" . $_SESSION['Items']->Branch . "'";
     $ErrMsg = _('Could not update the default shipping carrier for this branch because');
     $DbgMsg = _('The SQL used to update the branch default carrier was');
     $result = DB_query($SQL, $db, $ErrMsg, $DbgMsg, true);
 }
 $DefaultDispatchDate = FormatDateForSQL($DefaultDispatchDate);
 /*Update order header for invoice charged on */
 $SQL = "UPDATE salesorders SET comments = CONCAT(comments,' Inv ','" . $InvoiceNo . "') WHERE orderno= " . $_SESSION['ProcessingOrder'];
 $ErrMsg = _('CRITICAL ERROR') . ' ' . _('NOTE DOWN THIS ERROR AND SEEK ASSISTANCE') . ': ' . _('The sales order header could not be updated with the invoice number');
 $DbgMsg = _('The following SQL to update the sales order was used');
 $Result = DB_query($SQL, $db, $ErrMsg, $DbgMsg, true);
 $Location = $_POST[$RequestID . 'Location' . $LineID];
 $Department = $_POST[$RequestID . 'Department' . $LineID];
 $Tag = $_POST[$RequestID . 'Tag' . $LineID];
 $RequestedQuantity = filter_number_format($_POST[$RequestID . 'RequestedQuantity' . $LineID]);
 if (isset($_POST[$RequestID . 'Completed' . $LineID])) {
     $Completed = True;
 } else {
     $Completed = False;
 }
 $sql = "SELECT materialcost, labourcost, overheadcost, decimalplaces FROM stockmaster WHERE stockid='" . $StockID . "'";
 $result = DB_query($sql, $db);
 $myrow = DB_fetch_array($result);
 $StandardCost = $myrow['materialcost'] + $myrow['labourcost'] + $myrow['overheadcost'];
 $DecimalPlaces = $myrow['decimalplaces'];
 $Narrative = _('Issue') . ' ' . $Quantity . ' ' . _('of') . ' ' . $StockID . ' ' . _('to department') . ' ' . $Department . ' ' . _('from') . ' ' . $Location;
 $AdjustmentNumber = GetNextTransNo(17, $db);
 $PeriodNo = GetPeriod(Date($_SESSION['DefaultDateFormat']), $db);
 $SQLAdjustmentDate = FormatDateForSQL(Date($_SESSION['DefaultDateFormat']));
 $Result = DB_Txn_Begin($db);
 // Need to get the current location quantity will need it later for the stock movement
 $SQL = "SELECT locstock.quantity\n\t\t\t\t\tFROM locstock\n\t\t\t\t\tWHERE locstock.stockid='" . $StockID . "'\n\t\t\t\t\t\tAND loccode= '" . $Location . "'";
 $Result = DB_query($SQL, $db);
 if (DB_num_rows($Result) == 1) {
     $LocQtyRow = DB_fetch_row($Result);
     $QtyOnHandPrior = $LocQtyRow[0];
 } else {
     // There must actually be some error this should never happen
     $QtyOnHandPrior = 0;
 }
 if ($_SESSION['ProhibitNegativeStock'] == 0 or $_SESSION['ProhibitNegativeStock'] == 1 and $QtyOnHandPrior >= $Quantity) {
     $SQL = "INSERT INTO stockmoves (\n\t\t\t\t\t\t\t\t\tstockid,\n\t\t\t\t\t\t\t\t\ttype,\n\t\t\t\t\t\t\t\t\ttransno,\n\t\t\t\t\t\t\t\t\tloccode,\n\t\t\t\t\t\t\t\t\ttrandate,\n\t\t\t\t\t\t\t\t\tprd,\n\t\t\t\t\t\t\t\t\treference,\n\t\t\t\t\t\t\t\t\tqty,\n\t\t\t\t\t\t\t\t\tnewqoh)\n\t\t\t\t\t\t\t\tVALUES (\n\t\t\t\t\t\t\t\t\t'" . $StockID . "',\n\t\t\t\t\t\t\t\t\t17,\n\t\t\t\t\t\t\t\t\t'" . $AdjustmentNumber . "',\n\t\t\t\t\t\t\t\t\t'" . $Location . "',\n\t\t\t\t\t\t\t\t\t'" . $SQLAdjustmentDate . "',\n\t\t\t\t\t\t\t\t\t'" . $PeriodNo . "',\n\t\t\t\t\t\t\t\t\t'" . $Narrative . "',\n\t\t\t\t\t\t\t\t\t'" . -$Quantity . "',\n\t\t\t\t\t\t\t\t\t'" . ($QtyOnHandPrior - $Quantity) . "'\n\t\t\t\t\t\t\t\t)";
    //depn calc has been run previously
    $AllowUserEnteredProcessDate = false;
    $_POST['ProcessDate'] = LastDayOfMonth(DateAdd(ConvertSQLDate($LastDepnRun[0]), 'd', 28));
}
/* Get list of assets for journal */
$sql = "SELECT fixedassets.assetid,\n\t\t\tfixedassets.description,\n\t\t\tfixedassets.depntype,\n\t\t\tfixedassets.depnrate,\n\t\t\tfixedassets.datepurchased,\n\t\t\tfixedassetcategories.accumdepnact,\n\t\t\tfixedassetcategories.depnact,\n\t\t\tfixedassetcategories.categorydescription,\n\t\t\tSUM(CASE WHEN fixedassettrans.fixedassettranstype='cost' THEN fixedassettrans.amount ELSE 0 END) AS costtotal,\n\t\t\tSUM(CASE WHEN fixedassettrans.fixedassettranstype='depn' THEN fixedassettrans.amount ELSE 0 END) AS depnbfwd\n\t\tFROM fixedassets\n\t\tINNER JOIN fixedassetcategories\n\t\t\tON fixedassets.assetcategoryid=fixedassetcategories.categoryid\n\t\tINNER JOIN fixedassettrans\n\t\t\tON fixedassets.assetid=fixedassettrans.assetid\n\t\tWHERE fixedassettrans.transdate<='" . FormatDateForSQL($_POST['ProcessDate']) . "'\n\t\tGROUP BY fixedassets.assetid,\n\t\t\tfixedassets.description,\n\t\t\tfixedassets.depntype,\n\t\t\tfixedassets.depnrate,\n\t\t\tfixedassets.datepurchased,\n\t\t\tfixedassetcategories.accumdepnact,\n\t\t\tfixedassetcategories.depnact,\n\t\t\tfixedassetcategories.categorydescription\n\t\tORDER BY assetcategoryid, assetid";
$AssetsResult = DB_query($sql, $db);
$InputError = false;
//always hope for the best
if (Date1GreaterThanDate2($_POST['ProcessDate'], Date($_SESSION['DefaultDateFormat']))) {
    prnMsg(_('No depreciation will be committed as the processing date is beyond the current date. The depreciation run can only be run for periods prior to today'), 'warn');
    $InputError = true;
}
if (isset($_POST['CommitDepreciation']) and $InputError == false) {
    $result = DB_Txn_Begin($db);
    $TransNo = GetNextTransNo(44, $db);
    $PeriodNo = GetPeriod($_POST['ProcessDate'], $db);
}
echo '<br /><table>';
$Heading = '<tr>
				<th>' . _('Asset ID') . '</th>
				<th>' . _('Description') . '</th>
				<th>' . _('Date Purchased') . '</th>
				<th>' . _('Cost') . '</th>
				<th>' . _('Accum Depn') . '</th>
				<th>' . _('B/fwd Book Value') . '</th>
				<th>' . _('Depn Type') . '</th>
				<th>' . _('Depn Rate') . '</th>
				<th>' . _('New Depn') . '</th>
			</tr>';
echo $Heading;
     prnMsg(_('The credit note as entered cannot be processed because the date entered is not in the format') . ' ' . $_SESSION['DefaultDateFormat'], 'error');
 } elseif (DateDiff(Date($_SESSION['DefaultDateFormat']), $_SESSION['SuppTrans']->TranDate, 'd') < 0) {
     $InputError = True;
     prnMsg(_('The credit note as entered cannot be processed because the date is after today') . '. ' . _('Purchase credit notes are expected to have a date prior to or today'), 'error');
 } elseif ($_SESSION['SuppTrans']->ExRate <= 0) {
     $InputError = True;
     prnMsg(_('The credit note as entered cannot be processed because the exchange rate for the credit note has been entered as a negative or zero number') . '. ' . _('The exchange rate is expected to show how many of the suppliers currency there are in 1 of the local currency'), 'warn');
 } elseif ($_SESSION['SuppTrans']->OvAmount < round($TotalShiptValue + $TotalGLValue + $TotalAssetValue + $TotalGRNValue, $_SESSION['SuppTrans']->CurrDecimalPlaces)) {
     prnMsg(_('The credit note total as entered is less than the sum of the shipment charges') . ', ' . _('the general ledger entries (if any) and the charges for goods received') . '. ' . _('There must be a mistake somewhere') . ', ' . _('the credit note as entered will not be processed'), 'error');
     $InputError = True;
 } else {
     /* SQL to process the postings for purchase credit note */
     /*Start an SQL transaction */
     DB_Txn_Begin($db);
     /*Get the next transaction number for internal purposes and the period to post GL transactions in based on the credit note date*/
     $CreditNoteNo = GetNextTransNo(21, $db);
     $PeriodNo = GetPeriod($_SESSION['SuppTrans']->TranDate, $db);
     $SQLCreditNoteDate = FormatDateForSQL($_SESSION['SuppTrans']->TranDate);
     if ($_SESSION['SuppTrans']->GLLink_Creditors == 1) {
         /*Loop through the GL Entries and create a debit posting for each of the accounts entered */
         $LocalTotal = 0;
         /*the postings here are a little tricky, the logic goes like this:
         
         			> if its a shipment entry then the cost must go against the GRN suspense account defined in the company record
         
         			> if its a general ledger amount it goes straight to the account specified
         
         			> if its a GRN amount credited then there are two possibilities:
         
         			1 The PO line is on a shipment.
         			The whole charge goes to the GRN suspense account pending the closure of the
Exemple #19
0
function InsertSalesOrderHeader($OrderHeader, $user, $password)
{
    $Errors = array();
    $db = db($user, $password);
    if (gettype($db) == 'integer') {
        $Errors[0] = NoAuthorisation;
        return $Errors;
    }
    foreach ($OrderHeader as $key => $value) {
        $OrderHeader[$key] = DB_escape_string($value);
    }
    $Errors = VerifyDebtorExists($OrderHeader['debtorno'], sizeof($Errors), $Errors, $db);
    $Errors = VerifyBranchNoExists($OrderHeader['debtorno'], $OrderHeader['branchcode'], sizeof($Errors), $Errors, $db);
    if (isset($OrderHeader['customerref'])) {
        $Errors = VerifyCustomerRef($OrderHeader['customerref'], sizeof($Errors), $Errors);
    }
    if (isset($OrderHeader['buyername'])) {
        $Errors = VerifyBuyerName($OrderHeader['buyername'], sizeof($Errors), $Errors);
    }
    if (isset($OrderHeader['comments'])) {
        $Errors = VerifyComments($OrderHeader['comments'], sizeof($Errors), $Errors);
    }
    if (isset($OrderHeader['orddate'])) {
        $Errors = VerifyOrderDate($OrderHeader['orddate'], sizeof($Errors), $Errors, $db);
    }
    if (isset($OrderHeader['ordertype'])) {
        $Errors = VerifyOrderType($OrderHeader['ordertype'], sizeof($Errors), $Errors, $db);
    }
    if (isset($OrderHeader['shipvia'])) {
        $Errors = VerifyShipVia($OrderHeader['shipvia'], sizeof($Errors), $Errors, $db);
    }
    if (isset($OrderHeader['deladd1'])) {
        $Errors = VerifyAddressLine($OrderHeader['deladd1'], 40, sizeof($Errors), $Errors);
    }
    if (isset($OrderHeader['deladd2'])) {
        $Errors = VerifyAddressLine($OrderHeader['deladd2'], 40, sizeof($Errors), $Errors);
    }
    if (isset($OrderHeader['deladd3'])) {
        $Errors = VerifyAddressLine($OrderHeader['deladd3'], 40, sizeof($Errors), $Errors);
    }
    if (isset($OrderHeader['deladd4'])) {
        $Errors = VerifyAddressLine($OrderHeader['deladd4'], 40, sizeof($Errors), $Errors);
    }
    if (isset($OrderHeader['deladd5'])) {
        $Errors = VerifyAddressLine($OrderHeader['deladd5'], 20, sizeof($Errors), $Errors);
    }
    if (isset($OrderHeader['deladd6'])) {
        $Errors = VerifyAddressLine($OrderHeader['deladd6'], 15, sizeof($Errors), $Errors);
    }
    if (isset($OrderHeader['contactphone'])) {
        $Errors = VerifyPhoneNumber($OrderHeader['contactphone'], sizeof($Errors), $Errors);
    }
    if (isset($OrderHeader['contactemail'])) {
        $Errors = VerifyEmailAddress($OrderHeader['contactemail'], sizeof($Errors), $Errors);
    }
    if (isset($OrderHeader['deliverto'])) {
        $Errors = VerifyDeliverTo($OrderHeader['deliverto'], sizeof($Errors), $Errors);
    }
    if (isset($OrderHeader['deliverblind'])) {
        $Errors = VerifyDeliverBlind($OrderHeader['deliverblind'], sizeof($Errors), $Errors);
    }
    if (isset($OrderHeader['freightcost'])) {
        $Errors = VerifyFreightCost($OrderHeader['freightcost'], sizeof($Errors), $Errors);
    }
    if (isset($OrderHeader['fromstkloc'])) {
        $Errors = VerifyFromStockLocation($OrderHeader['fromstkloc'], sizeof($Errors), $Errors, $db);
    }
    if (isset($OrderHeader['deliverydate'])) {
        $Errors = VerifyDeliveryDate($OrderHeader['deliverydate'], sizeof($Errors), $Errors, $db);
    }
    if (isset($OrderHeader['quotation'])) {
        $Errors = VerifyQuotation($OrderHeader['quotation'], sizeof($Errors), $Errors);
    }
    $FieldNames = '';
    $FieldValues = '';
    global $SOH_DateFields;
    $OrderHeader['orderno'] = GetNextTransNo(30, $db);
    foreach ($OrderHeader as $key => $value) {
        $FieldNames .= $key . ', ';
        if (in_array($key, $SOH_DateFields)) {
            $value = FormatDateforSQL($value);
        }
        // Fix dates
        $FieldValues .= '"' . $value . '", ';
    }
    $sql = 'INSERT INTO salesorders (' . substr($FieldNames, 0, -2) . ') ' . 'VALUES (' . substr($FieldValues, 0, -2) . ') ';
    if (sizeof($Errors) == 0) {
        $result = api_DB_Query($sql, $db);
        if (DB_error_no($db) != 0) {
            $Errors[0] = DatabaseUpdateFailed;
        } else {
            $Errors[0] = 0;
            $Errors[1] = $OrderHeader['orderno'];
        }
    }
    return $Errors;
}
 $QuantityPurchOrders = $PurchOrdersRow[0];
 $SQL = "SELECT SUM(woitems.qtyreqd - woitems.qtyrecd) as qtyonorder\r\n\t\t\t\t\tFROM woitems INNER JOIN workorders\r\n\t\t\t\t\tON woitems.wo=workorders.wo\r\n\t\t\t\t\tWHERE woitems.stockid = '" . $StockItem->StockID . "'\r\n\t\t\t\t\tAND woitems.qtyreqd > woitems.qtyrecd\r\n\t\t\t\t\tAND workorders.closed = 0";
 $WorkOrdersResult = DB_query($SQL, $db);
 $WorkOrdersRow = DB_fetch_row($WorkOrdersResult);
 $QuantityWorkOrders = $WorkOrdersRow[0];
 //Now we have the data - do we need to make any more?
 $ShortfallQuantity = $QOH - $QuantityDemand - $QuantityAssemblyDemand + $QuantityPurchOrders + $QuantityWorkOrders;
 if ($ShortfallQuantity < 0) {
     //then we need to make a work order
     //How many should the work order be for??
     if ($ShortfallQuantity + $StockItem->EOQ < 0) {
         $WOQuantity = -$ShortfallQuantity;
     } else {
         $WOQuantity = $StockItem->EOQ;
     }
     $WONo = GetNextTransNo(40, $db);
     $ErrMsg = _('Unable to insert a new work order for the sales order item');
     $InsWOResult = DB_query("INSERT INTO workorders (wo,\r\n\t\t\t\t\t\t\t\t\t\t\t\t loccode,\r\n\t\t\t\t\t\t\t\t\t\t\t\t requiredby,\r\n\t\t\t\t\t\t\t\t\t\t\t\t startdate)\r\n\t\t\t\t\t\t\t\t VALUES (" . $WONo . ",\r\n\t\t\t\t\t\t\t\t\t\t'" . $_SESSION['DefaultFactoryLocation'] . "',\r\n\t\t\t\t\t\t\t\t\t\t'" . Date('Y-m-d') . "',\r\n\t\t\t\t\t\t\t\t\t\t'" . Date('Y-m-d') . "')", $db, $ErrMsg, $DbgMsg, true);
     //Need to get the latest BOM to roll up cost
     $CostResult = DB_query("SELECT SUM((materialcost+labourcost+overheadcost)*bom.quantity) AS cost\r\n\t\t\t\t\t\t\t\t\t\t\t\t\tFROM stockmaster INNER JOIN bom\r\n\t\t\t\t\t\t\t\t\t\t\t\t\tON stockmaster.stockid=bom.component\r\n\t\t\t\t\t\t\t\t\t\t\t\t\tWHERE bom.parent='" . $StockItem->StockID . "'\r\n\t\t\t\t\t\t\t\t\t\t\t\t\tAND bom.loccode='" . $_SESSION['DefaultFactoryLocation'] . "'", $db);
     $CostRow = DB_fetch_row($CostResult);
     if (is_null($CostRow[0]) or $CostRow[0] == 0) {
         $Cost = 0;
         prnMsg(_('In automatically creating a work order for') . ' ' . $StockItem->StockID . ' ' . _('an item on this sales order, the cost of this item as accumulated from the sum of the component costs is nil. This could be because there is no bill of material set up ... you may wish to double check this'), 'warn');
     } else {
         $Cost = $CostRow[0];
     }
     // insert parent item info
     $sql = "INSERT INTO woitems (wo,\r\n\t\t\t\t\t\t\t\t\t\t\t stockid,\r\n\t\t\t\t\t\t\t\t\t\t\t qtyreqd,\r\n\t\t\t\t\t\t\t\t\t\t\t stdcost)\r\n\t\t\t\t\t\t\t\t VALUES ( " . $WONo . ",\r\n\t\t\t\t\t\t\t\t\t\t '" . $StockItem->StockID . "',\r\n\t\t\t\t\t\t\t\t\t\t " . $WOQuantity . ",\r\n\t\t\t\t\t\t\t\t\t\t  " . $Cost . ")";
     $ErrMsg = _('The work order item could not be added');
     $result = DB_query($sql, $db, $ErrMsg, $DbgMsg, true);
        }
    }
}
if (isset($_POST['Submit'])) {
    DB_Txn_Begin($db);
    $InputError = 0;
    if ($_SESSION['Request']->Department == '') {
        prnMsg(_('You must select a Department for the request'), 'error');
        $InputError = 1;
    }
    if ($_SESSION['Request']->Location == '') {
        prnMsg(_('You must select a Location to request the items from'), 'error');
        $InputError = 1;
    }
    if ($InputError == 0) {
        $RequestNo = GetNextTransNo(38, $db);
        $HeaderSQL = "INSERT INTO stockrequest (dispatchid,\r\n\t\t\t\t\t\t\t\t\t\t\tloccode,\r\n\t\t\t\t\t\t\t\t\t\t\tdepartmentid,\r\n\t\t\t\t\t\t\t\t\t\t\tdespatchdate,\r\n\t\t\t\t\t\t\t\t\t\t\tnarrative)\r\n\t\t\t\t\t\t\t\t\t\tVALUES(\r\n\t\t\t\t\t\t\t\t\t\t\t'" . $RequestNo . "',\r\n\t\t\t\t\t\t\t\t\t\t\t'" . $_SESSION['Request']->Location . "',\r\n\t\t\t\t\t\t\t\t\t\t\t'" . $_SESSION['Request']->Department . "',\r\n\t\t\t\t\t\t\t\t\t\t\t'" . FormatDateForSQL($_SESSION['Request']->DispatchDate) . "',\r\n\t\t\t\t\t\t\t\t\t\t\t'" . $_SESSION['Request']->Narrative . "')";
        $ErrMsg = _('CRITICAL ERROR') . '! ' . _('NOTE DOWN THIS ERROR AND SEEK ASSISTANCE') . ': ' . _('The request header record could not be inserted because');
        $DbgMsg = _('The following SQL to insert the request header record was used');
        $Result = DB_query($HeaderSQL, $db, $ErrMsg, $DbgMsg, true);
        foreach ($_SESSION['Request']->LineItems as $LineItems) {
            $LineSQL = "INSERT INTO stockrequestitems (dispatchitemsid,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\tdispatchid,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\tstockid,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\tquantity,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\tdecimalplaces,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\tuom)\r\n\t\t\t\t\t\t\t\t\t\t\t\tVALUES(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t'" . $LineItems->LineNumber . "',\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t'" . $RequestNo . "',\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t'" . $LineItems->StockID . "',\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t'" . $LineItems->Quantity . "',\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t'" . $LineItems->DecimalPlaces . "',\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t'" . $LineItems->UOM . "')";
            $ErrMsg = _('CRITICAL ERROR') . '! ' . _('NOTE DOWN THIS ERROR AND SEEK ASSISTANCE') . ': ' . _('The request line record could not be inserted because');
            $DbgMsg = _('The following SQL to insert the request header record was used');
            $Result = DB_query($LineSQL, $db, $ErrMsg, $DbgMsg, true);
        }
        $EmailSQL = "SELECT email\r\n\t\t\t\t\tFROM www_users, departments\r\n\t\t\t\t\tWHERE departments.authoriser = www_users.userid\r\n\t\t\t\t\t\tAND departments.departmentid = '" . $_SESSION['Request']->Department . "'";
        $EmailResult = DB_query($EmailSQL, $db);
        if ($myEmail = DB_fetch_array($EmailResult)) {
            $ConfirmationText = _('An internal stock request has been created and is waiting for your authoritation');
            $EmailSubject = _('Internal Stock Request needs your authoritation');
Exemple #22
0
         }
         prnMsg(_('You do not have permission to authorise this purchase order') . '.<br />' . _('This order is for') . ' ' . $_SESSION['PO' . $identifier]->CurrCode . ' ' . $_SESSION['PO' . $identifier]->Order_Value() . '. ' . $AuthMessage . _('If you think this is a mistake please contact the systems administrator') . '<br />' . _('The order will be created with a status of pending and will require authorisation'), 'warn');
         $_SESSION['PO' . $identifier]->AllowPrintPO = 0;
         $StatusComment = date($_SESSION['DefaultDateFormat']) . ' - ' . _('Order Created by') . $UserDetails . '<br />' . $_SESSION['PO' . $identifier]->StatusComments . '<br />';
         $_SESSION['PO' . $identifier]->Status = 'Pending';
     }
 } else {
     //auto authorise is set to off
     $_SESSION['PO' . $identifier]->AllowPrintPO = 0;
     $StatusComment = date($_SESSION['DefaultDateFormat']) . ' - ' . _('Order Created by') . $UserDetails . ' - ' . $_SESSION['PO' . $identifier]->StatusComments . '<br />';
     $_SESSION['PO' . $identifier]->Status = 'Pending';
 }
 if ($_SESSION['ExistingOrder'] == 0) {
     /*its a new order to be inserted */
     /*Get the order number */
     $_SESSION['PO' . $identifier]->OrderNo = GetNextTransNo(18, $db);
     /*Insert to purchase order header record */
     $sql = "INSERT INTO purchorders ( orderno,\n\t\t\t\t\t\t\t\t\t\t\tsupplierno,\n\t\t\t\t\t\t\t\t\t\t\tcomments,\n\t\t\t\t\t\t\t\t\t\t\torddate,\n\t\t\t\t\t\t\t\t\t\t\trate,\n\t\t\t\t\t\t\t\t\t\t\tinitiator,\n\t\t\t\t\t\t\t\t\t\t\trequisitionno,\n\t\t\t\t\t\t\t\t\t\t\tintostocklocation,\n\t\t\t\t\t\t\t\t\t\t\tdeladd1,\n\t\t\t\t\t\t\t\t\t\t\tdeladd2,\n\t\t\t\t\t\t\t\t\t\t\tdeladd3,\n\t\t\t\t\t\t\t\t\t\t\tdeladd4,\n\t\t\t\t\t\t\t\t\t\t\tdeladd5,\n\t\t\t\t\t\t\t\t\t\t\tdeladd6,\n\t\t\t\t\t\t\t\t\t\t\ttel,\n\t\t\t\t\t\t\t\t\t\t\tsuppdeladdress1,\n\t\t\t\t\t\t\t\t\t\t\tsuppdeladdress2,\n\t\t\t\t\t\t\t\t\t\t\tsuppdeladdress3,\n\t\t\t\t\t\t\t\t\t\t\tsuppdeladdress4,\n\t\t\t\t\t\t\t\t\t\t\tsuppdeladdress5,\n\t\t\t\t\t\t\t\t\t\t\tsuppdeladdress6,\n\t\t\t\t\t\t\t\t\t\t\tsuppliercontact,\n\t\t\t\t\t\t\t\t\t\t\tsupptel,\n\t\t\t\t\t\t\t\t\t\t\tcontact,\n\t\t\t\t\t\t\t\t\t\t\tversion,\n\t\t\t\t\t\t\t\t\t\t\trevised,\n\t\t\t\t\t\t\t\t\t\t\tdeliveryby,\n\t\t\t\t\t\t\t\t\t\t\tstatus,\n\t\t\t\t\t\t\t\t\t\t\tstat_comment,\n\t\t\t\t\t\t\t\t\t\t\tdeliverydate,\n\t\t\t\t\t\t\t\t\t\t\tpaymentterms,\n\t\t\t\t\t\t\t\t\t\t\tallowprint)\n\t\t\t\t\t\t\tVALUES(\t'" . $_SESSION['PO' . $identifier]->OrderNo . "',\n\t\t\t\t\t\t\t\t\t'" . $_SESSION['PO' . $identifier]->SupplierID . "',\n\t\t\t\t\t\t\t\t\t'" . $_SESSION['PO' . $identifier]->Comments . "',\n\t\t\t\t\t\t\t\t\t'" . Date('Y-m-d') . "',\n\t\t\t\t\t\t\t\t\t'" . $_SESSION['PO' . $identifier]->ExRate . "',\n\t\t\t\t\t\t\t\t\t'" . $_SESSION['PO' . $identifier]->Initiator . "',\n\t\t\t\t\t\t\t\t\t'" . $_SESSION['PO' . $identifier]->RequisitionNo . "',\n\t\t\t\t\t\t\t\t\t'" . $_SESSION['PO' . $identifier]->Location . "',\n\t\t\t\t\t\t\t\t\t'" . $_SESSION['PO' . $identifier]->DelAdd1 . "',\n\t\t\t\t\t\t\t\t\t'" . $_SESSION['PO' . $identifier]->DelAdd2 . "',\n\t\t\t\t\t\t\t\t\t'" . $_SESSION['PO' . $identifier]->DelAdd3 . "',\n\t\t\t\t\t\t\t\t\t'" . $_SESSION['PO' . $identifier]->DelAdd4 . "',\n\t\t\t\t\t\t\t\t\t'" . $_SESSION['PO' . $identifier]->DelAdd5 . "',\n\t\t\t\t\t\t\t\t\t'" . $_SESSION['PO' . $identifier]->DelAdd6 . "',\n\t\t\t\t\t\t\t\t\t'" . $_SESSION['PO' . $identifier]->Tel . "',\n\t\t\t\t\t\t\t\t\t'" . $_SESSION['PO' . $identifier]->SuppDelAdd1 . "',\n\t\t\t\t\t\t\t\t\t'" . $_SESSION['PO' . $identifier]->SuppDelAdd2 . "',\n\t\t\t\t\t\t\t\t\t'" . $_SESSION['PO' . $identifier]->SuppDelAdd3 . "',\n\t\t\t\t\t\t\t\t\t'" . $_SESSION['PO' . $identifier]->SuppDelAdd4 . "',\n\t\t\t\t\t\t\t\t\t'" . $_SESSION['PO' . $identifier]->SuppDelAdd5 . "',\n\t\t\t\t\t\t\t\t\t'" . $_SESSION['PO' . $identifier]->SuppDelAdd6 . "',\n\t\t\t\t\t\t\t\t\t'" . $_SESSION['PO' . $identifier]->SupplierContact . "',\n\t\t\t\t\t\t\t\t\t'" . $_SESSION['PO' . $identifier]->SuppTel . "',\n\t\t\t\t\t\t\t\t\t'" . $_SESSION['PO' . $identifier]->Contact . "',\n\t\t\t\t\t\t\t\t\t'" . $_SESSION['PO' . $identifier]->Version . "',\n\t\t\t\t\t\t\t\t\t'" . Date('Y-m-d') . "',\n\t\t\t\t\t\t\t\t\t'" . $_SESSION['PO' . $identifier]->DeliveryBy . "',\n\t\t\t\t\t\t\t\t\t'" . $_SESSION['PO' . $identifier]->Status . "',\n\t\t\t\t\t\t\t\t\t'" . htmlspecialchars($StatusComment, ENT_QUOTES, 'UTF-8') . "',\n\t\t\t\t\t\t\t\t\t'" . FormatDateForSQL($_SESSION['PO' . $identifier]->DeliveryDate) . "',\n\t\t\t\t\t\t\t\t\t'" . $_SESSION['PO' . $identifier]->PaymentTerms . "',\n\t\t\t\t\t\t\t\t\t'" . $_SESSION['PO' . $identifier]->AllowPrintPO . "' )";
     $ErrMsg = _('The purchase order header record could not be inserted into the database because');
     $DbgMsg = _('The SQL statement used to insert the purchase order header record and failed was');
     $result = DB_query($sql, $db, $ErrMsg, $DbgMsg, true);
     /*Insert the purchase order detail records */
     foreach ($_SESSION['PO' . $identifier]->LineItems as $POLine) {
         if ($POLine->Deleted == False) {
             $sql = "INSERT INTO purchorderdetails (orderno,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\titemcode,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tdeliverydate,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\titemdescription,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tglcode,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tunitprice,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tquantityord,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tshiptref,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tjobref,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tsuppliersunit,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tsuppliers_partno,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tassetid,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tconversionfactor )\n\t\t\t\t\t\t\t\t\tVALUES ('" . $_SESSION['PO' . $identifier]->OrderNo . "',\n\t\t\t\t\t\t\t\t\t\t\t'" . $POLine->StockID . "',\n\t\t\t\t\t\t\t\t\t\t\t'" . FormatDateForSQL($POLine->ReqDelDate) . "',\n\t\t\t\t\t\t\t\t\t\t\t'" . DB_escape_string($POLine->ItemDescription) . "',\n\t\t\t\t\t\t\t\t\t\t\t'" . $POLine->GLCode . "',\n\t\t\t\t\t\t\t\t\t\t\t'" . $POLine->Price . "',\n\t\t\t\t\t\t\t\t\t\t\t'" . $POLine->Quantity . "',\n\t\t\t\t\t\t\t\t\t\t\t'" . $POLine->ShiptRef . "',\n\t\t\t\t\t\t\t\t\t\t\t'" . $POLine->JobRef . "',\n\t\t\t\t\t\t\t\t\t\t\t'" . $POLine->SuppliersUnit . "',\n\t\t\t\t\t\t\t\t\t\t\t'" . $POLine->Suppliers_PartNo . "',\n\t\t\t\t\t\t\t\t\t\t\t'" . $POLine->AssetID . "',\n\t\t\t\t\t\t\t\t\t\t\t'" . $POLine->ConversionFactor . "')";
             $ErrMsg = _('One of the purchase order detail records could not be inserted into the database because');
             $DbgMsg = _('The SQL statement used to insert the purchase order detail record and failed was');
             $result = DB_query($sql, $db, $ErrMsg, $DbgMsg, true);
         }
     }
     /* end of the loop round the detail line items on the order */
 	First Get the area where the credit note is to from the branches table */
 $SQL = "SELECT area\n\t\t \tFROM custbranch\n\t\t\tWHERE custbranch.debtorno ='" . $_SESSION['CreditItems' . $identifier]->DebtorNo . "'\n\t\t\tAND custbranch.branchcode = '" . $_SESSION['CreditItems' . $identifier]->Branch . "'";
 $ErrMsg = _('CRITICAL ERROR') . '! ' . _('NOTE DOWN THIS ERROR AND SEEK ASSISTANCE') . ': ' . _('The area cannot be determined for this customer');
 $DbgMsg = _('The following SQL to insert the customer credit note was used');
 $Result = DB_query($SQL, $ErrMsg, $DbgMsg);
 if ($myrow = DB_fetch_row($Result)) {
     $Area = $myrow[0];
 }
 DB_free_result($Result);
 if ($_SESSION['CompanyRecord']['gllink_stock'] == 1 and $_POST['CreditType'] == 'WriteOff' and (!isset($_POST['WriteOffGLCode']) or $_POST['WriteOffGLCode'] == '')) {
     prnMsg(_('For credit notes created to write off the stock a general ledger account is required to be selected. Please select an account to write the cost of the stock off to then click on Process again'), 'error');
     include 'includes/footer.inc';
     exit;
 }
 /*Now Get the next credit note number - function in SQL_CommonFunctions*/
 $CreditNo = GetNextTransNo(11, $db);
 $SQLCreditDate = Date('Y-m-d');
 $PeriodNo = GetPeriod(Date($_SESSION['DefaultDateFormat']), $db);
 /*Start an SQL transaction */
 DB_Txn_Begin();
 /*Now insert the Credit Note into the DebtorTrans table allocations will have to be done seperately*/
 $SQL = "INSERT INTO debtortrans (transno,\n\t\t\t\t\t\t\t \t\ttype,\n\t\t\t\t\t\t\t\t\tdebtorno,\n\t\t\t\t\t\t\t\t\tbranchcode,\n\t\t\t\t\t\t\t\t\ttrandate,\n\t\t\t\t\t\t\t\t\tinputdate,\n\t\t\t\t\t\t\t\t\tprd,\n\t\t\t\t\t\t\t\t\ttpe,\n\t\t\t\t\t\t\t\t\tovamount,\n\t\t\t\t\t\t\t\t\tovgst,\n\t\t\t\t\t\t\t\t\tovfreight,\n\t\t\t\t\t\t\t\t\trate,\n\t\t\t\t\t\t\t\t\tinvtext,\n\t\t\t\t\t\t\t\t\tsalesperson)\n\t\t\t\t\t\t\t\t  VALUES ('" . $CreditNo . "',\n\t\t\t\t\t\t\t\t  \t'11',\n\t\t\t\t\t\t\t\t\t'" . $_SESSION['CreditItems' . $identifier]->DebtorNo . "',\n\t\t\t\t\t\t\t\t\t'" . $_SESSION['CreditItems' . $identifier]->Branch . "',\n\t\t\t\t\t\t\t\t\t'" . $SQLCreditDate . "',\n\t\t\t\t\t\t\t\t\t'" . date('Y-m-d H-i-s') . "',\n\t\t\t\t\t\t\t\t\t'" . $PeriodNo . "',\n\t\t\t\t\t\t\t\t\t'" . $_SESSION['CreditItems' . $identifier]->DefaultSalesType . "',\n\t\t\t\t\t\t\t\t\t'" . -$_SESSION['CreditItems' . $identifier]->total . "',\n\t\t\t\t\t\t\t\t\t'" . -$TaxTotal . "',\n\t\t\t\t\t\t\t\t  \t'" . -$_SESSION['CreditItems' . $identifier]->FreightCost . "',\n\t\t\t\t\t\t\t\t\t'" . $_SESSION['CurrencyRate'] . "',\n\t\t\t\t\t\t\t\t\t'" . $_POST['CreditText'] . "',\n\t\t\t\t\t\t\t\t\t'" . $_SESSION['CreditItems' . $identifier]->SalesPerson . "' )";
 $ErrMsg = _('CRITICAL ERROR') . '! ' . _('NOTE DOWN THIS ERROR AND SEEK ASSISTANCE') . ': ' . _('The customer credit note transaction could not be added to the database because');
 $DbgMsg = _('The following SQL to insert the customer credit note was used');
 $Result = DB_query($SQL, $ErrMsg, $DbgMsg, true);
 $CreditTransID = DB_Last_Insert_ID($db, 'debtortrans', 'id');
 /* Insert the tax totals for each tax authority where tax was charged on the invoice */
 foreach ($TaxTotals as $TaxAuthID => $TaxAmount) {
     $SQL = "INSERT INTO debtortranstaxes (debtortransid,\n\t\t\t\t\t\t\ttaxauthid,\n\t\t\t\t\t\t\ttaxamount)\n\t\t\t\tVALUES ('" . $CreditTransID . "',\n\t\t\t\t\t\t'" . $TaxAuthID . "',\n\t\t\t\t\t\t'" . -$TaxAmount / $_SESSION['CurrencyRate'] . "')";
     $ErrMsg = _('CRITICAL ERROR') . '! ' . _('NOTE DOWN THIS ERROR AND SEEK ASSISTANCE') . ': ' . _('The debtor transaction taxes records could not be inserted because');
     $DbgMsg = _('The following SQL to insert the debtor transaction taxes record was used');
function CreateCreditNote($Header, $LineDetails, $User, $Password)
{
    /* Create a customer credit note in KwaMoja.
     * Needs an associative array for the $Header
     * and an array of assocative arrays for the $LineDetails
     * $Header contains an associative array in the format:
     * Header['debtorno'] - the customer code
     * Header['branchcode']  - the branch code
     * Header['trandate'] - the date of the credit note
     * Header['tpe'] - the sales type
     * Header['fromstkloc'] - the inventory location where the stock is put back into
     * Header['customerref'] - the customer's reference
     * Header['shipvia'] - the shipper required by KwaMoja
     *
     * and $LineDetails contains an array of associative arrays of the format:
     *
     * $LineDetails[0]['stockid']
     * $LineDetails[0]['price']
     * $LineDetails[0]['qty'] - expected to be a negative quantity (a negative sale)
     * $LineDetails[0]['discountpercent']
     */
    $Errors = array();
    $db = db($User, $Password);
    if (gettype($db) == 'integer') {
        $Errors[0] = NoAuthorisation;
        return $Errors;
    }
    $Errors = VerifyDebtorExists($Header['debtorno'], sizeof($Errors), $Errors, $db);
    $Errors = VerifyBranchNoExists($Header['debtorno'], $Header['branchcode'], sizeof($Errors), $Errors, $db);
    /*Does not deal with serialised/lot track items - for use by POS */
    /*Get Company Defaults */
    $ReadCoyResult = api_DB_query("SELECT debtorsact,\n\t\t\t\t\t\t\t\t\t\t\t\tfreightact,\n\t\t\t\t\t\t\t\t\t\t\t\tgllink_debtors,\n\t\t\t\t\t\t\t\t\t\t\t\tgllink_stock\n\t\t\t\t\t\t\t\t\t\tFROM companies\n\t\t\t\t\t\t\t\t\t\tWHERE coycode=1", $db);
    $CompanyRecord = DB_fetch_array($ReadCoyResult);
    if (DB_error_no($db) != 0) {
        $Errors[] = NoCompanyRecord;
    }
    $HeaderSQL = "SELECT custbranch.area,\n\t\t\t\t\t\t\t custbranch.taxgroupid,\n\t\t\t\t\t\t\t debtorsmaster.currcode,\n\t\t\t\t\t\t\t rate,\n\t\t\t\t\t\t\t salesman\n\t\t\t\t\t\t\tFROM debtorsmaster\n\t\t\t\t\t\t\tINNER JOIN custbranch\n\t\t\t\t\t\t\tON debtorsmaster.debtorno = custbranch.debtorno\n\t\t\t\t\t\t\tINNER JOIN currencies\n\t\t\t\t\t\t\tON debtorsmaster.currcode=currencies.currabrev\n\t\t\t\t\t\t\tWHERE custbranch.debtorno = '" . $Header['debtorno'] . "'\n\t\t\t\t\t\t\tAND custbranch.branchcode='" . $Header['branchcode'] . "'";
    $HeaderResult = api_DB_query($HeaderSQL, $db);
    if (DB_error_no($db) != 0) {
        $Errors[] = NoReadCustomerBranch;
    }
    $CN_Header = DB_fetch_array($HeaderResult);
    $TaxProvResult = api_DB_query("SELECT taxprovinceid FROM locations WHERE loccode='" . $Header['fromstkloc'] . "'", $db);
    if (DB_error_no($db) != 0) {
        $Errors[] = NoTaxProvince;
    }
    $myrow = DB_fetch_row($TaxProvResult);
    $DispTaxProvinceID = $myrow[0];
    /*Start an SQL transaction */
    $result = DB_Txn_Begin($db);
    /*Now Get the next credit note number - function in SQL_CommonFunctions*/
    $CreditNoteNo = GetNextTransNo(11, $db);
    $PeriodNo = GetCurrentPeriod($db);
    $TotalFXNetCredit = 0;
    $TotalFXTax = 0;
    $TaxTotals = array();
    $LineCounter = 0;
    foreach ($LineDetails as $CN_Line) {
        $LineSQL = "SELECT taxcatid,\n\t\t\t\t\t\t\t\tmbflag,\n\t\t\t\t\t\t\t\tmaterialcost+labourcost+overheadcost AS standardcost\n\t\t\t\t\t\tFROM stockmaster\n\t\t\t\t\t\tWHERE stockid ='" . $CN_Line['stockid'] . "'";
        $LineResult = api_DB_query($LineSQL, $db);
        if (DB_error_no($db) != 0 or DB_num_rows($LineResult) == 0) {
            $Errors[] = NoReadItem;
            return $Errors;
        }
        $LineRow = DB_fetch_array($LineResult);
        $StandardCost = $LineRow['standardcost'];
        $LocalCurrencyPrice = $CN_Line['price'] * (1 - floatval($CN_Line['discountpercent'])) / $CN_Header['rate'];
        $LineNetAmount = $CN_Line['price'] * $CN_Line['qty'] * (1 - floatval($CN_Line['discountpercent']));
        /*Gets the Taxes and rates applicable to this line from the TaxGroup of the branch and TaxCategory of the item
        		and the taxprovince of the dispatch location */
        $SQL = "SELECT taxgrouptaxes.calculationorder,\n\t\t\t\t\t\t\ttaxauthorities.description,\n\t\t\t\t\t\t\ttaxgrouptaxes.taxauthid,\n\t\t\t\t\t\t\ttaxauthorities.taxglcode,\n\t\t\t\t\t\t\ttaxgrouptaxes.taxontax,\n\t\t\t\t\t\t\ttaxauthrates.taxrate\n\t\t\t\t\tFROM taxauthrates INNER JOIN taxgrouptaxes ON\n\t\t\t\t\t\ttaxauthrates.taxauthority=taxgrouptaxes.taxauthid\n\t\t\t\t\t\tINNER JOIN taxauthorities ON\n\t\t\t\t\t\ttaxauthrates.taxauthority=taxauthorities.taxid\n\t\t\t\t\tWHERE taxgrouptaxes.taxgroupid='" . $CN_Header['taxgroupid'] . "'\n\t\t\t\t\tAND taxauthrates.dispatchtaxprovince='" . $DispTaxProvinceID . "'\n\t\t\t\t\tAND taxauthrates.taxcatid = '" . $LineRow['taxcatid'] . "'\n\t\t\t\t\tORDER BY taxgrouptaxes.calculationorder";
        $GetTaxRatesResult = api_DB_query($SQL, $db);
        if (DB_error_no($db) != 0) {
            $Errors[] = TaxRatesFailed;
        }
        $LineTaxAmount = 0;
        while ($myrow = DB_fetch_array($GetTaxRatesResult)) {
            if (!isset($TaxTotals[$myrow['taxauthid']]['FXAmount'])) {
                $TaxTotals[$myrow['taxauthid']]['FXAmount'] = 0;
            }
            $TaxAuthID = $myrow['taxauthid'];
            $TaxTotals[$myrow['taxauthid']]['GLCode'] = $myrow['taxglcode'];
            $TaxTotals[$myrow['taxauthid']]['TaxRate'] = $myrow['taxrate'];
            $TaxTotals[$myrow['taxauthid']]['TaxAuthDescription'] = $myrow['description'];
            if ($myrow['taxontax'] == 1) {
                $TaxAuthAmount = ($LineNetAmount + $LineTaxAmount) * $myrow['taxrate'];
            } else {
                $TaxAuthAmount = $LineNetAmount * $myrow['taxrate'];
            }
            $TaxTotals[$myrow['taxauthid']]['FXAmount'] += $TaxAuthAmount;
            /*Make an array of the taxes and amounts including GLcodes for later posting - need debtortransid
            		so can only post once the debtor trans is posted - can only post debtor trans when all tax is calculated */
            $LineTaxes[$LineCounter][$myrow['calculationorder']] = array('TaxCalculationOrder' => $myrow['calculationorder'], 'TaxAuthID' => $myrow['taxauthid'], 'TaxAuthDescription' => $myrow['description'], 'TaxRate' => $myrow['taxrate'], 'TaxOnTax' => $myrow['taxontax'], 'TaxAuthAmount' => $TaxAuthAmount);
            $LineTaxAmount += $TaxAuthAmount;
        }
        //end loop around Taxes
        $TotalFXNetCredit += $LineNetAmount;
        $TotalFXTax += $LineTaxAmount;
        if ($LineRow['mbflag'] == 'B' or $LineRow['mbflag'] == 'M') {
            $Assembly = False;
            /* Need to get the current location quantity
            			will need it later for the stock movement */
            $SQL = "SELECT locstock.quantity\n\t\t\t\t\t\tFROM locstock\n\t\t\t\t\t\tWHERE locstock.stockid='" . $CN_Line['stockid'] . "'\n\t\t\t\t\t\tAND loccode= '" . $Header['fromstkloc'] . "'";
            $Result = api_DB_query($SQL, $db);
            if (DB_num_rows($Result) == 1) {
                $LocQtyRow = DB_fetch_row($Result);
                $QtyOnHandPrior = $LocQtyRow[0];
            } else {
                /* There must be some error this should never happen */
                $QtyOnHandPrior = 0;
            }
            $SQL = "UPDATE locstock\n\t\t\t\t\t\tSET quantity = locstock.quantity - " . $CN_Line['qty'] . "\n\t\t\t\t\t\tWHERE locstock.stockid = '" . $CN_Line['stockid'] . "'\n\t\t\t\t\t\tAND loccode = '" . $Header['fromstkloc'] . "'";
            $Result = api_DB_query($SQL, $db, '', '', true);
            $SQL = "INSERT INTO stockmoves (stockid,\n\t\t\t\t\t\t\t\t\t\t\t\ttype,\n\t\t\t\t\t\t\t\t\t\t\t\ttransno,\n\t\t\t\t\t\t\t\t\t\t\t\tloccode,\n\t\t\t\t\t\t\t\t\t\t\t\ttrandate,\n\t\t\t\t\t\t\t\t\t\t\t\tdebtorno,\n\t\t\t\t\t\t\t\t\t\t\t\tbranchcode,\n\t\t\t\t\t\t\t\t\t\t\t\tprice,\n\t\t\t\t\t\t\t\t\t\t\t\tprd,\n\t\t\t\t\t\t\t\t\t\t\t\treference,\n\t\t\t\t\t\t\t\t\t\t\t\tqty,\n\t\t\t\t\t\t\t\t\t\t\t\tdiscountpercent,\n\t\t\t\t\t\t\t\t\t\t\t\tstandardcost,\n\t\t\t\t\t\t\t\t\t\t\t\tnewqoh)\n\t\t\t\t\t\tVALUES ('" . $CN_Line['stockid'] . "',\n\t\t\t\t\t\t\t\t'11',\n\t\t\t\t\t\t\t\t'" . $CreditNoteNo . "',\n\t\t\t\t\t\t\t\t'" . $Header['fromstkloc'] . "',\n\t\t\t\t\t\t\t\t'" . $Header['trandate'] . "',\n\t\t\t\t\t\t\t\t'" . $Header['debtorno'] . "',\n\t\t\t\t\t\t\t\t'" . $Header['branchcode'] . "',\n\t\t\t\t\t\t\t\t'" . $LocalCurrencyPrice . "',\n\t\t\t\t\t\t\t\t'" . $PeriodNo . "',\n\t\t\t\t\t\t\t\t'" . $Header['customerref'] . "',\n\t\t\t\t\t\t\t\t'" . -$CN_Line['qty'] . "',\n\t\t\t\t\t\t\t\t'" . $CN_Line['discountpercent'] . "',\n\t\t\t\t\t\t\t\t'" . $StandardCost . "',\n\t\t\t\t\t\t\t\t'" . ($QtyOnHandPrior - $CN_Line['qty']) . "' )";
            $Result = api_DB_query($SQL, $db, '', '', true);
        } else {
            if ($LineRow['mbflag'] == 'A') {
                /* its an assembly */
                /*Need to get the BOM for this part and make
                		stock moves for the components then update the Location stock balances */
                $Assembly = True;
                $StandardCost = 0;
                /*To start with - accumulate the cost of the comoponents for use in journals later on */
                $SQL = "SELECT bom.component,\n\t\t\t\t\t\t\t\tbom.quantity,\n\t\t\t\t\t\t\t\tstockmaster.materialcost+stockmaster.labourcost+stockmaster.overheadcost AS standard\n\t\t\t\t\t\t\tFROM bom INNER JOIN stockmaster\n\t\t\t\t\t\t\tON bom.component=stockmaster.stockid\n\t\t\t\t\t\t\tWHERE bom.parent='" . $CN_Line['stockid'] . "'\n\t\t\t\t\t\t\tAND bom.effectiveto >= '" . Date('Y-m-d') . "'\n\t\t\t\t\t\t\tAND bom.effectiveafter < '" . Date('Y-m-d') . "'";
                $AssResult = api_DB_query($SQL, $db);
                while ($AssParts = DB_fetch_array($AssResult, $db)) {
                    $StandardCost += $AssParts['standard'] * $AssParts['quantity'];
                    /* Need to get the current location quantity
                    			will need it later for the stock movement */
                    $SQL = "SELECT locstock.quantity\n\t\t\t\t\t\t\tFROM locstock\n\t\t\t\t\t\t\tWHERE locstock.stockid='" . $AssParts['component'] . "'\n\t\t\t\t\t\t\tAND loccode= '" . $Header['fromstkloc'] . "'";
                    $Result = api_DB_query($SQL, $db);
                    if (DB_num_rows($Result) == 1) {
                        $LocQtyRow = DB_fetch_row($Result);
                        $QtyOnHandPrior = $LocQtyRow[0];
                    } else {
                        /*There must be some error this should never happen */
                        $QtyOnHandPrior = 0;
                    }
                    if (empty($AssParts['standard'])) {
                        $AssParts['standard'] = 0;
                    }
                    $SQL = "INSERT INTO stockmoves (stockid,\n\t\t\t\t\t\t\t\t\t\t\t\t\ttype,\n\t\t\t\t\t\t\t\t\t\t\t\t\ttransno,\n\t\t\t\t\t\t\t\t\t\t\t\t\tloccode,\n\t\t\t\t\t\t\t\t\t\t\t\t\ttrandate,\n\t\t\t\t\t\t\t\t\t\t\t\t\tdebtorno,\n\t\t\t\t\t\t\t\t\t\t\t\t\tbranchcode,\n\t\t\t\t\t\t\t\t\t\t\t\t\tprd,\n\t\t\t\t\t\t\t\t\t\t\t\t\treference,\n\t\t\t\t\t\t\t\t\t\t\t\t\tqty,\n\t\t\t\t\t\t\t\t\t\t\t\t\tstandardcost,\n\t\t\t\t\t\t\t\t\t\t\t\t\tshow_on_inv_crds,\n\t\t\t\t\t\t\t\t\t\t\t\t\tnewqoh)\n\t\t\t\t\t\t\t\t\t\tVALUES ('" . $AssParts['component'] . "',\n\t\t\t\t\t\t\t\t\t\t\t\t 11,\n\t\t\t\t\t\t\t\t\t\t\t\t '" . $CreditNoteNo . "',\n\t\t\t\t\t\t\t\t\t\t\t\t '" . $Header['fromstkloc'] . "',\n\t\t\t\t\t\t\t\t\t\t\t\t '" . $Header['trandate'] . "',\n\t\t\t\t\t\t\t\t\t\t\t\t '" . $Header['debtorno'] . "',\n\t\t\t\t\t\t\t\t\t\t\t\t '" . $Header['branchcode'] . "',\n\t\t\t\t\t\t\t\t\t\t\t\t '" . $PeriodNo . "',\n\t\t\t\t\t\t\t\t\t\t\t\t '" . _('Assembly') . ': ' . $CN_Line['stockid'] . ' ' . $Header['customerref'] . "',\n\t\t\t\t\t\t\t\t\t\t\t\t '" . -$AssParts['quantity'] * $CN_Line['qty'] . "',\n\t\t\t\t\t\t\t\t\t\t\t\t '" . $AssParts['standard'] . "',\n\t\t\t\t\t\t\t\t\t\t\t\t 0,\n\t\t\t\t\t\t\t\t\t\t\t\t '" . ($QtyOnHandPrior - $AssParts['quantity'] * $CN_Line['qty']) . "'\t)";
                    $Result = DB_query($SQL, $db, '', '', true);
                    $SQL = "UPDATE locstock\n\t\t\t\t\t\t\tSET quantity = locstock.quantity - " . $AssParts['quantity'] * $CN_Line['qty'] . "\n\t\t\t\t\t\t\tWHERE locstock.stockid = '" . $AssParts['component'] . "'\n\t\t\t\t\t\t\tAND loccode = '" . $Header['fromlocstk'] . "'";
                    $Result = DB_query($SQL, $db, '', '', true);
                }
                /* end of assembly explosion and updates */
            }
        }
        /* end of its an assembly */
        if ($LineRow['mbflag'] == 'A' or $LineRow['mbflag'] == 'D') {
            /*it's a Dummy/Service item or an Assembly item - still need stock movement record
             * but quantites on hand are always nil */
            $SQL = "INSERT INTO stockmoves (stockid,\n\t\t\t\t\t\t\t\t\t\t\t\ttype,\n\t\t\t\t\t\t\t\t\t\t\t\ttransno,\n\t\t\t\t\t\t\t\t\t\t\t\tloccode,\n\t\t\t\t\t\t\t\t\t\t\t\ttrandate,\n\t\t\t\t\t\t\t\t\t\t\t\tdebtorno,\n\t\t\t\t\t\t\t\t\t\t\t\tbranchcode,\n\t\t\t\t\t\t\t\t\t\t\t\tprice,\n\t\t\t\t\t\t\t\t\t\t\t\tprd,\n\t\t\t\t\t\t\t\t\t\t\t\treference,\n\t\t\t\t\t\t\t\t\t\t\t\tqty,\n\t\t\t\t\t\t\t\t\t\t\t\tdiscountpercent,\n\t\t\t\t\t\t\t\t\t\t\t\tstandardcost,\n\t\t\t\t\t\t\t\t\t\t\t\tnewqoh)\n\t\t\t\t\t\tVALUES ('" . $CN_Line['stockid'] . "',\n\t\t\t\t\t\t\t\t'11',\n\t\t\t\t\t\t\t\t'" . $CreditNoteNo . "',\n\t\t\t\t\t\t\t\t'" . $Header['fromstkloc'] . "',\n\t\t\t\t\t\t\t\t'" . $Header['trandate'] . "',\n\t\t\t\t\t\t\t\t'" . $Header['debtorno'] . "',\n\t\t\t\t\t\t\t\t'" . $Header['branchcode'] . "',\n\t\t\t\t\t\t\t\t'" . $LocalCurrencyPrice . "',\n\t\t\t\t\t\t\t\t'" . $PeriodNo . "',\n\t\t\t\t\t\t\t\t'" . $Header['customerref'] . "',\n\t\t\t\t\t\t\t\t'" . -$CN_Line['qty'] . "',\n\t\t\t\t\t\t\t\t'" . $CN_Line['discountpercent'] . "',\n\t\t\t\t\t\t\t\t'" . $StandardCost . "',\n\t\t\t\t\t\t\t\t'0' )";
            $Result = api_DB_query($SQL, $db, '', '', true);
        }
        /*Get the ID of the StockMove... */
        $StkMoveNo = DB_Last_Insert_ID($db, 'stockmoves', 'stkmoveno');
        /*Insert the taxes that applied to this line */
        foreach ($LineTaxes[$LineCounter] as $Tax) {
            $SQL = "INSERT INTO stockmovestaxes (stkmoveno,\n\t\t\t\t\t\t\t\t\ttaxauthid,\n\t\t\t\t\t\t\t\t\ttaxrate,\n\t\t\t\t\t\t\t\t\ttaxcalculationorder,\n\t\t\t\t\t\t\t\t\ttaxontax)\n\t\t\t\t\t\tVALUES ('" . $StkMoveNo . "',\n\t\t\t\t\t\t\t'" . $Tax['TaxAuthID'] . "',\n\t\t\t\t\t\t\t'" . $Tax['TaxRate'] . "',\n\t\t\t\t\t\t\t'" . $Tax['TaxCalculationOrder'] . "',\n\t\t\t\t\t\t\t'" . $Tax['TaxOnTax'] . "')";
            $Result = DB_query($SQL, $db, '', '', true);
        }
        /*Insert Sales Analysis records */
        $SQL = "SELECT COUNT(*),\n\t\t\t\t\t\tsalesanalysis.stkcategory,\n\t\t\t\t\t\tsalesanalysis.area,\n\t\t\t\t\t\tsalesanalysis.salesperson,\n\t\t\t\t\t\tsalesanalysis.periodno,\n\t\t\t\t\t\tsalesanalysis.typeabbrev,\n\t\t\t\t\t\tsalesanalysis.cust,\n\t\t\t\t\t\tsalesanalysis.custbranch,\n\t\t\t\t\t\tsalesanalysis.stockid\n\t\t\t\t\tFROM salesanalysis,\n\t\t\t\t\t\tcustbranch,\n\t\t\t\t\t\tstockmaster\n\t\t\t\t\tWHERE salesanalysis.stkcategory=stockmaster.categoryid\n\t\t\t\t\tAND salesanalysis.stockid=stockmaster.stockid\n\t\t\t\t\tAND salesanalysis.cust=custbranch.debtorno\n\t\t\t\t\tAND salesanalysis.custbranch=custbranch.branchcode\n\t\t\t\t\tAND salesanalysis.area=custbranch.area\n\t\t\t\t\tAND salesanalysis.salesperson=custbranch.salesman\n\t\t\t\t\tAND salesanalysis.typeabbrev ='" . $Header['tpe'] . "'\n\t\t\t\t\tAND salesanalysis.periodno='" . $PeriodNo . "'\n\t\t\t\t\tAND salesanalysis.cust " . LIKE . "  '" . $Header['debtorno'] . "'\n\t\t\t\t\tAND salesanalysis.custbranch  " . LIKE . " '" . $Header['branchcode'] . "'\n\t\t\t\t\tAND salesanalysis.stockid  " . LIKE . " '" . $CN_Line['stockid'] . "'\n\t\t\t\t\tAND salesanalysis.budgetoractual='1'\n\t\t\t\t\tGROUP BY salesanalysis.stockid,\n\t\t\t\t\t\tsalesanalysis.stkcategory,\n\t\t\t\t\t\tsalesanalysis.cust,\n\t\t\t\t\t\tsalesanalysis.custbranch,\n\t\t\t\t\t\tsalesanalysis.area,\n\t\t\t\t\t\tsalesanalysis.periodno,\n\t\t\t\t\t\tsalesanalysis.typeabbrev,\n\t\t\t\t\t\tsalesanalysis.salesperson";
        $Result = api_DB_query($SQL, $db, '', '', true);
        $myrow = DB_fetch_row($Result);
        if ($myrow[0] > 0) {
            /*Update the existing record that already exists */
            $SQL = "UPDATE salesanalysis\n\t\t\t\t\t\tSET amt=amt+" . $CN_Line['price'] * $CN_Line['qty'] / $CN_Header['rate'] . ",\n\t\t\t\t\t\tqty=qty +" . $CN_Line['qty'] . ",\n\t\t\t\t\t\tdisc=disc+" . $CN_Line['discountpercent'] * $CN_Line['price'] * $CN_Line['qty'] / $CN_Header['rate'] . "\n\t\t\t\t\t\tWHERE salesanalysis.area='" . $myrow[2] . "'\n\t\t\t\t\t\tAND salesanalysis.salesperson='" . $myrow[3] . "'\n\t\t\t\t\t\tAND typeabbrev ='" . $Header['tpe'] . "'\n\t\t\t\t\t\tAND periodno = '" . $PeriodNo . "'\n\t\t\t\t\t\tAND cust  " . LIKE . " '" . $Header['debtorno'] . "'\n\t\t\t\t\t\tAND custbranch  " . LIKE . "  '" . $Header['branchcode'] . "'\n\t\t\t\t\t\tAND stockid  " . LIKE . " '" . $CN_Line['stockid'] . "'\n\t\t\t\t\t\tAND salesanalysis.stkcategory ='" . $myrow[1] . "'\n\t\t\t\t\t\tAND budgetoractual='1'";
        } else {
            /* insert a new sales analysis record */
            $SQL = "INSERT INTO salesanalysis (\ttypeabbrev,\n\t\t\t\t\t\t\t\t\t\t\t\t\tperiodno,\n\t\t\t\t\t\t\t\t\t\t\t\t\tamt,\n\t\t\t\t\t\t\t\t\t\t\t\t\tcost,\n\t\t\t\t\t\t\t\t\t\t\t\t\tcust,\n\t\t\t\t\t\t\t\t\t\t\t\t\tcustbranch,\n\t\t\t\t\t\t\t\t\t\t\t\t\tqty,\n\t\t\t\t\t\t\t\t\t\t\t\t\tdisc,\n\t\t\t\t\t\t\t\t\t\t\t\t\tstockid,\n\t\t\t\t\t\t\t\t\t\t\t\t\tarea,\n\t\t\t\t\t\t\t\t\t\t\t\t\tbudgetoractual,\n\t\t\t\t\t\t\t\t\t\t\t\t\tsalesperson,\n\t\t\t\t\t\t\t\t\t\t\t\t\tstkcategory )\n\t\t\t\t\t\t\t\tSELECT '" . $Header['tpe'] . "',\n\t\t\t\t\t\t\t\t\t'" . $PeriodNo . "',\n\t\t\t\t\t\t\t\t\t'" . $CN_Line['price'] * $CN_Line['qty'] / $CN_Header['rate'] . "',\n\t\t\t\t\t\t\t\t\t0,\n\t\t\t\t\t\t\t\t\t'" . $Header['debtorno'] . "',\n\t\t\t\t\t\t\t\t\t'" . $Header['branchcode'] . "',\n\t\t\t\t\t\t\t\t\t'" . $CN_Line['qty'] . "',\n\t\t\t\t\t\t\t\t\t'" . $CN_Line['discountpercent'] * $CN_Line['price'] * $CN_Line['qty'] / $CN_Header['rate'] . "',\n\t\t\t\t\t\t\t\t\t'" . $CN_Line['stockid'] . "',\n\t\t\t\t\t\t\t\t\tcustbranch.area,\n\t\t\t\t\t\t\t\t\t1,\n\t\t\t\t\t\t\t\t\tcustbranch.salesman,\n\t\t\t\t\t\t\t\t\tstockmaster.categoryid\n\t\t\t\t\t\t\t\tFROM stockmaster, custbranch\n\t\t\t\t\t\t\t\tWHERE stockmaster.stockid = '" . $CN_Line['stockid'] . "'\n\t\t\t\t\t\t\t\tAND custbranch.debtorno = '" . $Header['debtorno'] . "'\n\t\t\t\t\t\t\t\tAND custbranch.branchcode='" . $Header['branchcode'] . "'";
        }
        $Result = api_DB_query($SQL, $db, '', '', true);
        if ($CompanyRecord['gllink_stock'] == 1 and $StandardCost != 0) {
            /*first the cost of sales entry - GL accounts are retrieved using the function GetCOGSGLAccount from includes/GetSalesTransGLCodes.inc  */
            $SQL = "INSERT INTO gltrans (type,\n\t\t\t\t\t\t\t\t\t\t\ttypeno,\n\t\t\t\t\t\t\t\t\t\t\ttrandate,\n\t\t\t\t\t\t\t\t\t\t\tperiodno,\n\t\t\t\t\t\t\t\t\t\t\taccount,\n\t\t\t\t\t\t\t\t\t\t\tnarrative,\n\t\t\t\t\t\t\t\t\t\t\tamount)\n\t\t\t\t\t\t\t\t\tVALUES (11,\n\t\t\t\t\t\t\t\t\t\t'" . $CreditNoteNo . "',\n\t\t\t\t\t\t\t\t\t\t'" . $Header['trandate'] . "',\n\t\t\t\t\t\t\t\t\t\t'" . $PeriodNo . "',\n\t\t\t\t\t\t\t\t\t\t'" . GetCOGSGLAccount($CN_Header['area'], $CN_Line['stockid'], $Header['tpe'], $db) . "',\n\t\t\t\t\t\t\t\t\t\t'" . $Header['debtorno'] . " - " . $CN_Line['stockid'] . " x " . $CN_Line['qty'] . " @ " . $StandardCost . "',\n\t\t\t\t\t\t\t\t\t\t'" . $StandardCost * $CN_Line['qty'] . "')";
            $Result = api_DB_query($SQL, $db, '', '', true);
            /*now the stock entry - this is set to the cost act in the case of a fixed asset disposal */
            $StockGLCode = GetStockGLCode($CN_Line['stockid'], $db);
            $SQL = "INSERT INTO gltrans (type,\n\t\t\t\t\t\t\t\t\t\t\ttypeno,\n\t\t\t\t\t\t\t\t\t\t\ttrandate,\n\t\t\t\t\t\t\t\t\t\t\tperiodno,\n\t\t\t\t\t\t\t\t\t\t\taccount,\n\t\t\t\t\t\t\t\t\t\t\tnarrative,\n\t\t\t\t\t\t\t\t\t\t\tamount)\n\t\t\t\t\t\t\t\t\tVALUES (11,\n\t\t\t\t\t\t\t\t\t\t'" . $CreditNoteNo . "',\n\t\t\t\t\t\t\t\t\t\t'" . $Header['trandate'] . "',\n\t\t\t\t\t\t\t\t\t\t'" . $PeriodNo . "',\n\t\t\t\t\t\t\t\t\t\t'" . $StockGLCode['stockact'] . "',\n\t\t\t\t\t\t\t\t\t\t'" . $Header['debtorno'] . " - " . $CN_Line['stockid'] . " x " . $CN_Line['qty'] . " @ " . $StandardCost . "',\n\t\t\t\t\t\t\t\t\t\t'" . -$StandardCost * $CN_Line['qty'] . "')";
            $Result = api_DB_query($SQL, $db, '', '', true);
        }
        /* end of if GL and stock integrated and standard cost !=0  and not an asset */
        if ($CompanyRecord['gllink_debtors'] == 1 and $CN_Line['price'] != 0) {
            //Post sales transaction to GL credit sales
            $SalesGLAccounts = GetSalesGLAccount($CN_Header['area'], $CN_Line['stockid'], $Header['tpe'], $db);
            $SQL = "INSERT INTO gltrans (type,\n\t\t\t\t\t\t\t\t\t\t\ttypeno,\n\t\t\t\t\t\t\t\t\t\t\ttrandate,\n\t\t\t\t\t\t\t\t\t\t\tperiodno,\n\t\t\t\t\t\t\t\t\t\t\taccount,\n\t\t\t\t\t\t\t\t\t\t\tnarrative,\n\t\t\t\t\t\t\t\t\t\t\tamount )\n\t\t\t\t\tVALUES ('11',\n\t\t\t\t\t\t'" . $CreditNoteNo . "',\n\t\t\t\t\t\t'" . $Header['trandate'] . "',\n\t\t\t\t\t\t'" . $PeriodNo . "',\n\t\t\t\t\t\t'" . $SalesGLAccounts['salesglcode'] . "',\n\t\t\t\t\t\t'" . $Header['debtorno'] . " - " . $CN_Line['stockid'] . " x " . $CN_Line['qty'] . " @ " . $CN_Line['price'] . "',\n\t\t\t\t\t\t'" . -$CN_Line['price'] * $CN_Line['qty'] / $CN_Header['rate'] . "'\n\t\t\t\t\t)";
            $Result = api_DB_query($SQL, $db, '', '', true);
            if ($CN_Line['discountpercent'] != 0) {
                $SQL = "INSERT INTO gltrans (type,\n\t\t\t\t\t\t\t\t\t\t\t\ttypeno,\n\t\t\t\t\t\t\t\t\t\t\t\ttrandate,\n\t\t\t\t\t\t\t\t\t\t\t\tperiodno,\n\t\t\t\t\t\t\t\t\t\t\t\taccount,\n\t\t\t\t\t\t\t\t\t\t\t\tnarrative,\n\t\t\t\t\t\t\t\t\t\t\t\tamount)\n\t\t\t\t\t\t\tVALUES (11,\n\t\t\t\t\t\t\t\t'" . $CreditNoteNo . "',\n\t\t\t\t\t\t\t\t'" . $Header['trandate'] . "',\n\t\t\t\t\t\t\t\t'" . $PeriodNo . "',\n\t\t\t\t\t\t\t\t'" . $SalesGLAccounts['discountglcode'] . "',\n\t\t\t\t\t\t\t\t'" . $Header['debtorno'] . " - " . $CN_Line['stockid'] . " @ " . $CN_Line['discountpercent'] * 100 . "%',\n\t\t\t\t\t\t\t\t'" . $CN_Line['price'] * $CN_Line['qty'] * $CN_Line['discountpercent'] / $CN_Header['rate'] . "')";
                $Result = DB_query($SQL, $db, '', '', true);
            }
            /*end of if discount !=0 */
        }
        /*end of if sales integrated with gl */
        $LineCounter++;
        //needed for the array of taxes by line
    }
    /*end of OrderLine loop */
    $TotalCreditLocalCurr = ($TotalFXNetCredit + $TotalFXTax) / $CN_Header['rate'];
    if ($CompanyRecord['gllink_debtors'] == 1) {
        /*Now post the tax to the GL at local currency equivalent */
        if ($CompanyRecord['gllink_debtors'] == 1 and $TaxAuthAmount != 0) {
            /*Loop through the tax authorities array to post each total to the taxauth glcode */
            foreach ($TaxTotals as $Tax) {
                $SQL = "INSERT INTO gltrans (type,\n\t\t\t\t\t\t\t\t\t\t\t\ttypeno,\n\t\t\t\t\t\t\t\t\t\t\t\ttrandate,\n\t\t\t\t\t\t\t\t\t\t\t\tperiodno,\n\t\t\t\t\t\t\t\t\t\t\t\taccount,\n\t\t\t\t\t\t\t\t\t\t\t\tnarrative,\n\t\t\t\t\t\t\t\t\t\t\t\tamount )\n\t\t\t\t\t\t\t\t\t\t\tVALUES (11,\n\t\t\t\t\t\t\t\t\t\t\t'" . $CreditNoteNo . "',\n\t\t\t\t\t\t\t\t\t\t\t'" . $Header['trandate'] . "',\n\t\t\t\t\t\t\t\t\t\t\t'" . $PeriodNo . "',\n\t\t\t\t\t\t\t\t\t\t\t'" . $Tax['GLCode'] . "',\n\t\t\t\t\t\t\t\t\t\t\t'" . $Header['debtorno'] . "-" . $Tax['TaxAuthDescription'] . "',\n\t\t\t\t\t\t\t\t\t\t\t'" . -$Tax['FXAmount'] / $CN_Header['rate'] . "' )";
                $Result = api_DB_query($SQL, $db, '', '', true);
            }
        }
        /*Post debtors transaction to GL credit debtors, and debit sales */
        if ($TotalCreditLocalCurr != 0) {
            $SQL = "INSERT INTO gltrans (type,\n\t\t\t\t\t\t\t\t\t\t\ttypeno,\n\t\t\t\t\t\t\t\t\t\t\ttrandate,\n\t\t\t\t\t\t\t\t\t\t\tperiodno,\n\t\t\t\t\t\t\t\t\t\t\taccount,\n\t\t\t\t\t\t\t\t\t\t\tnarrative,\n\t\t\t\t\t\t\t\t\t\t\tamount)\n\t\t\t\t\t\t\t\t\tVALUES ('11',\n\t\t\t\t\t\t\t\t\t\t'" . $CreditNoteNo . "',\n\t\t\t\t\t\t\t\t\t\t'" . $Header['trandate'] . "',\n\t\t\t\t\t\t\t\t\t\t'" . $PeriodNo . "',\n\t\t\t\t\t\t\t\t\t\t'" . $CompanyRecord['debtorsact'] . "',\n\t\t\t\t\t\t\t\t\t\t'" . $Header['debtorno'] . "',\n\t\t\t\t\t\t\t\t\t\t'" . $TotalCreditLocalCurr . "')";
            $Result = api_DB_query($SQL, $db, '', '', true);
        }
        EnsureGLEntriesBalance(11, $CreditNoteNo, $db);
    }
    /*end of if Sales and GL integrated */
    /*Now insert the DebtorTrans */
    $SQL = "INSERT INTO debtortrans (transno,\n\t\t\t\t\t\t\t\t\t\ttype,\n\t\t\t\t\t\t\t\t\t\tdebtorno,\n\t\t\t\t\t\t\t\t\t\tbranchcode,\n\t\t\t\t\t\t\t\t\t\ttrandate,\n\t\t\t\t\t\t\t\t\t\tinputdate,\n\t\t\t\t\t\t\t\t\t\tprd,\n\t\t\t\t\t\t\t\t\t\treference,\n\t\t\t\t\t\t\t\t\t\ttpe,\n\t\t\t\t\t\t\t\t\t\tovamount,\n\t\t\t\t\t\t\t\t\t\tovgst,\n\t\t\t\t\t\t\t\t\t\trate,\n\t\t\t\t\t\t\t\t\t\tshipvia)\n\t\t\t\t\t\t\t\t\tVALUES (\n\t\t\t\t\t\t\t\t\t\t'" . $CreditNoteNo . "',\n\t\t\t\t\t\t\t\t\t\t11,\n\t\t\t\t\t\t\t\t\t\t'" . $Header['debtorno'] . "',\n\t\t\t\t\t\t\t\t\t\t'" . $Header['branchcode'] . "',\n\t\t\t\t\t\t\t\t\t\t'" . $Header['trandate'] . "',\n\t\t\t\t\t\t\t\t\t\t'" . date('Y-m-d H-i-s') . "',\n\t\t\t\t\t\t\t\t\t\t'" . $PeriodNo . "',\n\t\t\t\t\t\t\t\t\t\t'" . $Header['customerref'] . "',\n\t\t\t\t\t\t\t\t\t\t'" . $Header['tpe'] . "',\n\t\t\t\t\t\t\t\t\t\t'" . $TotalFXNetCredit . "',\n\t\t\t\t\t\t\t\t\t\t'" . $TotalFXTax . "',\n\t\t\t\t\t\t\t\t\t\t'" . $CN_Header['rate'] . "',\n\t\t\t\t\t\t\t\t\t\t'" . $Header['shipvia'] . "')";
    $Result = api_DB_query($SQL, $db, '', '', true);
    $DebtorTransID = DB_Last_Insert_ID($db, 'debtortrans', 'id');
    /*for each Tax - need to insert into debtortranstaxes */
    foreach ($TaxTotals as $TaxAuthID => $Tax) {
        $SQL = "INSERT INTO debtortranstaxes (debtortransid,\n\t\t\t\t\t\t\t\t\t\t\t\ttaxauthid,\n\t\t\t\t\t\t\t\t\t\t\t\ttaxamount)\n\t\t\t\t\t\t\t\tVALUES ('" . $DebtorTransID . "',\n\t\t\t\t\t\t\t\t\t\t'" . $TaxAuthID . "',\n\t\t\t\t\t\t\t\t\t\t'" . $Tax['FXAmount'] / $CN_Header['rate'] . "')";
        $Result = api_DB_query($SQL, $db, '', '', true);
    }
    #Now figure out if there was an invoice in the same POS transaction to allocate against?
    $SQL = "SELECT id,\n\t\t\t\t\tovamount+ovgst AS total,\n\t\t\t\t\talloc\n\t\t\t\tFROM debtortrans\n\t\t\t\tWHERE customerref='" . $Header['customerref'] . "'\n\t\t\t\tAND type=10\n\t\t\t\tAND settled=0";
    $Result = api_DB_query($SQL, $db, '', '', true);
    $TotalCreditFX = $TotalFXNetCredit + $TotalFXTax;
    #Should be negative number
    $Allocated = 0;
    if (DB_num_rows($Result) > 0) {
        while ($InvoiceRow = DB_fetch_array($Result) and $Allocated > $TotalCreditFX) {
            if ($InvoiceRow['total'] - $InvoiceRow['alloc'] + $TotalCreditFX - $Allocated > 0) {
                /*Then we can allocate all of the (remaining) credit against this invoice */
                $AllocateAmount = $InvoiceRow['total'] - $InvoiceRow['alloc'] + $TotalCreditFX - $Allocated;
            } elseif ($InvoiceRow['total'] - $InvoiceRow['alloc'] - $Allocated > 0) {
                $AllocateAmount = $InvoiceRow['total'] - $InvoiceRow['alloc'] - $Allocated;
            } else {
                $AllocateAmount = 0;
            }
            if ($AllocateAmount > 0) {
                $SQL = "INSERT INTO\tcustallocns (datealloc,\n\t\t\t\t\t\t\t\t\t\t\t\t\t amt,\n\t\t\t\t\t\t\t\t\t\t\t\t\t transid_allocfrom,\n\t\t\t\t\t\t\t\t\t\t\t\t\t transid_allocto)\n\t\t\t\t\t\t\tVALUES ('" . date('Y-m-d') . "',\n\t\t\t\t\t\t\t\t\t'" . $AllocateAmount . "',\n\t\t\t\t\t\t\t\t\t'" . $DebtorTransID . "',\n\t\t\t\t\t\t\t\t\t'" . $InvoiceRow['id'] . "')";
                $InsertAllocResult = api_DB_query($SQL, $db, '', '', true);
            }
            if (abs($InvoiceRow['total'] - $InvoiceRow['alloc'] - $AllocateAmount) < 0.005) {
                $Settled = 1;
            } else {
                $Settled = 0;
            }
            $SQL = "UPDATE debtortrans SET alloc = alloc + " . $AllocateAmount . ",\n\t\t\t\t\t\t\t\t\t\t\t\tsettled = '" . $Settled . "'\n\t\t\t\t\t\tWHERE id = '" . $InvoiceRow['id'] . "'";
            $UpdateAllocResult = api_DB_query($SQL, $db, '', '', true);
            $Allocated -= $AllocateAmount;
        }
        if (abs($TotalCreditFX - $Allocated) < 0.005) {
            $Settled = 1;
        } else {
            $Settled = 0;
        }
        $SQL = "UPDATE debtortrans SET alloc = alloc + " . $Allocated . ",\n\t\t\t\t\t\t\t\t\t\t\t\tsettled = '" . $Settled . "'\n\t\t\t\t\tWHERE id = '" . $DebtorTransID . "'";
        $UpdateAllocResult = api_DB_query($SQL, $db, '', '', true);
    }
    if (sizeof($Errors) == 0) {
        $Result = DB_Txn_Commit($db);
        $Errors[0] = 0;
        $Errors[1] = $CreditNoteNo;
    } else {
        $Result = DB_Txn_Rollback($db);
    }
    return $Errors;
}
Exemple #25
0
     prnMsg(_('The asset location code entered must be exist in the asset locations table'), 'error');
     echo '<br />' . _('Row:') . $Row . ' - ' . _('Invalid asset location code:') . ' ' . $AssetLocationCode;
 }
 if (!Is_Date($DatePurchased)) {
     $InputError = true;
     prnMsg(_('The date purchased must be entered in the format:') . ' ' . $_SESSION['DefaultDateFormat'], 'error');
     echo '<br />' . _('Row:') . $Row . ' - ' . _('Invalid date format:') . ' ' . $DatePurchased;
 }
 if ($DepnType == 'DV') {
     $DepnType = 1;
 } else {
     $DepnType = 0;
 }
 if ($InputError == false) {
     //no errors
     $TransNo = GetNextTransNo(49, $db);
     $PeriodNo = GetPeriod(ConvertSQLDate($_POST['DateToEnter']), $db);
     //attempt to insert the stock item
     $sql = "INSERT INTO fixedassets (description,\n\t\t\t\t\t\t\t\t\t\t\tlongdescription,\n\t\t\t\t\t\t\t\t\t\t\tassetcategoryid,\n\t\t\t\t\t\t\t\t\t\t\tserialno,\n\t\t\t\t\t\t\t\t\t\t\tbarcode,\n\t\t\t\t\t\t\t\t\t\t\tassetlocation,\n\t\t\t\t\t\t\t\t\t\t\tcost,\n\t\t\t\t\t\t\t\t\t\t\taccumdepn,\n\t\t\t\t\t\t\t\t\t\t\tdepntype,\n\t\t\t\t\t\t\t\t\t\t\tdepnrate,\n\t\t\t\t\t\t\t\t\t\t\tdatepurchased)\n\t\t\t\t\t\t\tVALUES ('" . $Description . "',\n\t\t\t\t\t\t\t\t\t'" . $LongDescription . "',\n\t\t\t\t\t\t\t\t\t'" . $AssetCategoryID . "',\n\t\t\t\t\t\t\t\t\t'" . $SerialNo . "',\n\t\t\t\t\t\t\t\t\t'" . $BarCode . "',\n\t\t\t\t\t\t\t\t\t'" . $AssetLocationCode . "',\n\t\t\t\t\t\t\t\t\t'" . $Cost . "',\n\t\t\t\t\t\t\t\t\t'" . $AccumDepn . "',\n\t\t\t\t\t\t\t\t\t'" . $DepnType . "',\n\t\t\t\t\t\t\t\t\t'" . $DepnRate . "',\n\t\t\t\t\t\t\t\t\t'" . FormatDateForSQL($DatePurchased) . "')";
     $ErrMsg = _('The asset could not be added because');
     $DbgMsg = _('The SQL that was used to add the asset and failed was');
     $result = DB_query($sql, $db, $ErrMsg, $DbgMsg);
     if (DB_error_no($db) == 0) {
         //the insert of the new code worked so bang in the fixedassettrans records too
         $AssetID = DB_Last_Insert_ID($db, 'fixedassets', 'assetid');
         $sql = "INSERT INTO fixedassettrans ( assetid,\n\t\t\t\t\t\t\t\t\t\t\t\ttranstype,\n\t\t\t\t\t\t\t\t\t\t\t\ttransno,\n\t\t\t\t\t\t\t\t\t\t\t\ttransdate,\n\t\t\t\t\t\t\t\t\t\t\t\tperiodno,\n\t\t\t\t\t\t\t\t\t\t\t\tinputdate,\n\t\t\t\t\t\t\t\t\t\t\t\tfixedassettranstype,\n\t\t\t\t\t\t\t\t\t\t\t\tamount)\n\t\t\t\t\t\t\t\t\tVALUES ( '" . $AssetID . "',\n\t\t\t\t\t\t\t\t\t\t\t'49',\n\t\t\t\t\t\t\t\t\t\t\t'" . $TransNo . "',\n\t\t\t\t\t\t\t\t\t\t\t'" . $_POST['DateToEnter'] . "',\n\t\t\t\t\t\t\t\t\t\t\t'" . $PeriodNo . "',\n\t\t\t\t\t\t\t\t\t\t\t'" . Date('Y-m-d') . "',\n\t\t\t\t\t\t\t\t\t\t\t'cost',\n\t\t\t\t\t\t\t\t\t\t\t'" . $Cost . "')";
         $ErrMsg = _('The transaction for the cost of the asset could not be added because');
         $DbgMsg = _('The SQL that was used to add the fixedasset trans record that failed was');
         $InsResult = DB_query($sql, $db, $ErrMsg, $DbgMsg);
         $sql = "INSERT INTO fixedassettrans ( assetid,\n\t\t\t\t\t\t\t\t\t\t\t\t\ttranstype,\n\t\t\t\t\t\t\t\t\t\t\t\t\ttransno,\n\t\t\t\t\t\t\t\t\t\t\t\t\ttransdate,\n\t\t\t\t\t\t\t\t\t\t\t\t\tperiodno,\n\t\t\t\t\t\t\t\t\t\t\t\t\tinputdate,\n\t\t\t\t\t\t\t\t\t\t\t\t\tfixedassettranstype,\n\t\t\t\t\t\t\t\t\t\t\t\t\tamount)\n\t\t\t\t\t\t\t\t\tVALUES ( '" . $AssetID . "',\n\t\t\t\t\t\t\t\t\t\t\t'49',\n\t\t\t\t\t\t\t\t\t\t\t'" . $TransNo . "',\n\t\t\t\t\t\t\t\t\t\t\t'" . $_POST['DateToEnter'] . "',\n\t\t\t\t\t\t\t\t\t\t\t'" . $PeriodNo . "',\n\t\t\t\t\t\t\t\t\t\t\t'" . Date('Y-m-d') . "',\n\t\t\t\t\t\t\t\t\t\t\t'depn',\n\t\t\t\t\t\t\t\t\t\t\t'" . $AccumDepn . "')";
         $ErrMsg = _('The transaction for the cost of the asset could not be added because');
                 break;
             case 3:
                 $Defers[] = $OfferID;
                 break;
         }
     }
 }
 if (sizeOf($Accepts) > 0) {
     $MailText = _('This email has been automatically generated by the webERP installation at') . ' ' . $_SESSION['CompanyRecord']['coyname'] . "\n";
     $MailText .= _('The following offers you made have been accepted') . "\n";
     $MailText .= _('An official order will be sent to you in due course') . "\n\n";
     $sql = "SELECT rate FROM currencies where currabrev='" . $CurrCode . "'";
     $result = DB_query($sql);
     $myrow = DB_fetch_array($result);
     $Rate = $myrow['rate'];
     $OrderNo = GetNextTransNo(18, $db);
     $sql = "INSERT INTO purchorders (\n\t\t\t\t\torderno,\n\t\t\t\t\tsupplierno,\n\t\t\t\t\torddate,\n\t\t\t\t\trate,\n\t\t\t\t\tinitiator,\n\t\t\t\t\tintostocklocation,\n\t\t\t\t\tdeliverydate,\n\t\t\t\t\tstatus,\n\t\t\t\t\tstat_comment,\n\t\t\t\t\tpaymentterms)\n\t\t\t\tVALUES (\n\t\t\t\t\t'" . $OrderNo . "',\n\t\t\t\t\t'" . $_POST['supplierid'] . "',\n\t\t\t\t\t'" . date('Y-m-d') . "',\n\t\t\t\t\t'" . $Rate . "',\n\t\t\t\t\t'" . $_SESSION['UserID'] . "',\n\t\t\t\t\t'" . $_SESSION['DefaultFactoryLocation'] . "',\n\t\t\t\t\t'" . date('Y-m-d') . "',\n\t\t\t\t\t'" . _('Pending') . "',\n\t\t\t\t\t'" . _('Automatically generated from tendering system') . "',\n\t\t\t\t\t'" . $PaymentTerms . "')";
     DB_query($sql);
     foreach ($Accepts as $AcceptID) {
         $sql = "SELECT offers.quantity,\n\t\t\t\t\t\t\toffers.price,\n\t\t\t\t\t\t\toffers.uom,\n\t\t\t\t\t\t\tstockmaster.description,\n\t\t\t\t\t\t\tstockmaster.stockid\n\t\t\t\t\t\tFROM offers\n\t\t\t\t\t\tLEFT JOIN stockmaster\n\t\t\t\t\t\t\tON offers.stockid=stockmaster.stockid\n\t\t\t\t\t\tWHERE offerid='" . $AcceptID . "'";
         $result = DB_query($sql);
         $myrow = DB_fetch_array($result);
         $MailText .= $myrow['description'] . "\t" . _('Quantity') . ' ' . $myrow['quantity'] . "\t" . _('Price') . ' ' . locale_number_format($myrow['price']) . "\n";
         $sql = "INSERT INTO purchorderdetails (orderno,\n\t\t\t\t\t\t\t\t\t\t\t\titemcode,\n\t\t\t\t\t\t\t\t\t\t\t\tdeliverydate,\n\t\t\t\t\t\t\t\t\t\t\t\titemdescription,\n\t\t\t\t\t\t\t\t\t\t\t\tunitprice,\n\t\t\t\t\t\t\t\t\t\t\t\tactprice,\n\t\t\t\t\t\t\t\t\t\t\t\tquantityord,\n\t\t\t\t\t\t\t\t\t\t\t\tsuppliersunit)\n\t\t\t\t\t\t\t\t\tVALUES ('" . $OrderNo . "',\n\t\t\t\t\t\t\t\t\t\t\t'" . $myrow['stockid'] . "',\n\t\t\t\t\t\t\t\t\t\t\t'" . date('Y-m-d') . "',\n\t\t\t\t\t\t\t\t\t\t\t'" . DB_escape_string($myrow['description']) . "',\n\t\t\t\t\t\t\t\t\t\t\t'" . $myrow['price'] . "',\n\t\t\t\t\t\t\t\t\t\t\t'" . $myrow['price'] . "',\n\t\t\t\t\t\t\t\t\t\t\t'" . $myrow['quantity'] . "',\n\t\t\t\t\t\t\t\t\t\t\t'" . $myrow['uom'] . "')";
         $result = DB_query($sql);
         $sql = "DELETE FROM offers WHERE offerid='" . $AcceptID . "'";
         $result = DB_query($sql);
     }
     $mail = new htmlMimeMail();
     $mail->setSubject(_('Your offer to') . ' ' . $_SESSION['CompanyRecord']['coyname'] . ' ' . _('has been accepted'));
     $mail->setText($MailText);
 if (DB_num_rows($result) > 0) {
     $CancelDelete = 1;
     /*cannot delete assets with transactions */
     prnMsg(_('The asset has transactions associated with it. The asset can only be deleted when the fixed asset transactions are purged, otherwise the integrity of fixed asset reports may be compromised'), 'error');
 }
 $result = DB_query("SELECT * FROM purchorderdetails WHERE assetid='" . $AssetID . "'");
 if (DB_num_rows($result) > 0) {
     $CancelDelete = 1;
     /*cannot delete assets where there is a purchase order set up for it */
     prnMsg(_('There is a purchase order set up for this asset. The purchase order line must be deleted first'), 'error');
 }
 if ($CancelDelete == 0) {
     $result = DB_Txn_Begin();
     /*Need to remove cost and accumulate depreciation from cost and accumdepn accounts */
     $PeriodNo = GetPeriod(Date($_SESSION['DefaultDateFormat']), $db);
     $TransNo = GetNextTransNo(43, $db);
     /* transaction type is asset deletion - (and remove cost/acc5umdepn from GL) */
     if ($AssetRow['cost'] > 0) {
         //credit cost for the asset deleted
         $SQL = "INSERT INTO gltrans (type,\n\t\t\t\t\t\t\t\t\t\ttypeno,\n\t\t\t\t\t\t\t\t\t\ttrandate,\n\t\t\t\t\t\t\t\t\t\tperiodno,\n\t\t\t\t\t\t\t\t\t\taccount,\n\t\t\t\t\t\t\t\t\t\tnarrative,\n\t\t\t\t\t\t\t\t\t\tamount)\n\t\t\t\t\t\tVALUES ('43',\n\t\t\t\t\t\t\t'" . $TransNo . "',\n\t\t\t\t\t\t\t'" . Date('Y-m-d') . "',\n\t\t\t\t\t\t\t'" . $PeriodNo . "',\n\t\t\t\t\t\t\t'" . $AssetRow['costact'] . "',\n\t\t\t\t\t\t\t'" . _('Delete asset') . ' ' . $AssetID . "',\n\t\t\t\t\t\t\t'" . -$AssetRow['cost'] . "'\n\t\t\t\t\t\t\t)";
         $ErrMsg = _('Cannot insert a GL entry for the deletion of the asset because');
         $DbgMsg = _('The SQL that failed to insert the cost GL Trans record was');
         $result = DB_query($SQL, $ErrMsg, $DbgMsg, true);
         //debit accumdepn for the depreciation removed on deletion of this asset
         $SQL = "INSERT INTO gltrans (type,\n\t\t\t\t\t\t\t\t\t\ttypeno,\n\t\t\t\t\t\t\t\t\t\ttrandate,\n\t\t\t\t\t\t\t\t\t\tperiodno,\n\t\t\t\t\t\t\t\t\t\taccount,\n\t\t\t\t\t\t\t\t\t\tnarrative,\n\t\t\t\t\t\t\t\t\t\tamount)\n\t\t\t\t\t\tVALUES ('43',\n\t\t\t\t\t\t\t'" . $TransNo . "',\n\t\t\t\t\t\t\t'" . Date('Y-m-d') . "',\n\t\t\t\t\t\t\t'" . $PeriodNo . "',\n\t\t\t\t\t\t\t'" . $AssetRow['accumdepnact'] . "',\n\t\t\t\t\t\t\t'" . _('Delete asset') . ' ' . $AssetID . "',\n\t\t\t\t\t\t\t'" . $Asset['accumdepn'] . "'\n\t\t\t\t\t\t\t)";
         $ErrMsg = _('Cannot insert a GL entry for the reversal of accumulated depreciation on deletion of the asset because');
         $DbgMsg = _('The SQL that failed to insert the cost GL Trans record was');
         $result = DB_query($SQL, $ErrMsg, $DbgMsg, true);
     }
     //end if cost > 0
     $sql = "DELETE FROM fixedassets WHERE assetid='" . $AssetID . "'";
     exit;
 }
 unset($Allocs);
 $Allocs = array();
 $AllocCounter = 0;
 while ($DetailTrans = DB_fetch_array($TransResult)) {
     if ($DetailTrans['supplierid'] != $SupplierID) {
         /*Need to head up for a new suppliers details */
         if ($SupplierID != '') {
             /*only print the footer if this is not the first pass */
             include 'includes/PDFPaymentRun_PymtFooter.php';
         }
         $SupplierID = $DetailTrans['supplierid'];
         $SupplierName = $DetailTrans['suppname'];
         if (isset($_POST['PrintPDFAndProcess'])) {
             $SuppPaymentNo = GetNextTransNo(22, $db);
         }
         $AccumBalance = 0;
         $AccumDiffOnExch = 0;
         $LeftOvers = $pdf->addTextWrap($Left_Margin, $YPos, 450 - $Left_Margin, $FontSize, $DetailTrans['supplierid'] . ' - ' . $DetailTrans['suppname'] . ' - ' . $DetailTrans['terms'], 'left');
         $YPos -= $line_height;
     }
     $DislayTranDate = ConvertSQLDate($DetailTrans['trandate']);
     $LeftOvers = $pdf->addTextWrap($Left_Margin + 15, $YPos, 340 - $Left_Margin, $FontSize, $DislayTranDate . ' - ' . $DetailTrans['typename'] . ' - ' . $DetailTrans['suppreference'], 'left');
     /*Positive is a favourable */
     $DiffOnExch = $DetailTrans['balance'] / $DetailTrans['rate'] - $DetailTrans['balance'] / filter_number_format($_POST['ExRate']);
     $AccumBalance += $DetailTrans['balance'];
     $AccumDiffOnExch += $DiffOnExch;
     if (isset($_POST['PrintPDFAndProcess'])) {
         /*Record the Allocations for later insertion once we have the ID of the payment SuppTrans */
         $Allocs[$AllocCounter] = new Allocation($DetailTrans['id'], $DetailTrans['balance']);
     $sql = $sql . $_SESSION['SPL' . $identifier]->PurchOrderNo . "',\n\t\t\t\t\t'" . $PartCode . "',\n\t\t\t\t\t'" . $OrderDate . "',\n\t\t\t\t\t'" . $SPLLine->ItemDescription . "',\n\t\t\t\t\t'" . $GLCode . "',\n\t\t\t\t\t'" . $SPLLine->Cost . "',\n\t\t\t\t\t'" . $SPLLine->Quantity . "')";
     $ErrMsg = _('One of the purchase order detail records could not be inserted into the database because');
     $DbgMsg = _('The SQL statement used to insert the purchase order detail record and failed was');
     $result = DB_query($sql, $db, $ErrMsg, $DbgMsg, true);
 }
 /* end of the loop round the detail line items on the order */
 echo '<br /><br />' . _('Purchase Order') . ' ' . $_SESSION['SPL' . $identifier]->PurchOrderNo . ' ' . _('on') . ' ' . $_SESSION['SPL' . $identifier]->SupplierName . ' ' . _('has been created');
 echo '<br /><a href="' . $rootpath . '/PO_PDFPurchOrder.php?OrderNo=' . $_SESSION['SPL' . $identifier]->PurchOrderNo . '">' . _('Print Purchase Order') . '</a>';
 /*Now insert the sales order too */
 /*First get the customer delivery information */
 $sql = "SELECT salestype,\n\t\t\t\t\tbrname,\n\t\t\t\t\tbraddress1,\n\t\t\t\t\tbraddress2,\n\t\t\t\t\tbraddress3,\n\t\t\t\t\tbraddress4,\n\t\t\t\t\tbraddress5,\n\t\t\t\t\tbraddress6,\n\t\t\t\t\tdefaultshipvia,\n\t\t\t\t\temail,\n\t\t\t\t\tphoneno\n\t\t\t\tFROM custbranch INNER JOIN debtorsmaster\n\t\t\t\t\tON custbranch.debtorno=debtorsmaster.debtorno\n\t\t\t\tWHERE custbranch.debtorno='" . $_SESSION['SPL' . $identifier]->CustomerID . "'\n\t\t\t\tAND custbranch.branchcode = '" . $_SESSION['SPL' . $identifier]->BranchCode . "'";
 $ErrMsg = _('The delivery and sales type for the customer could not be retrieved for this special order') . ' ' . $SPLLine->LineNo . ' ' . _('because');
 $DbgMsg = _('The SQL statement used to get the delivery details and that failed was');
 $result = DB_query($sql, $db, $ErrMsg, $DbgMsg, true);
 $BranchDetails = DB_fetch_array($result);
 $SalesOrderNo = GetNextTransNo(30, $db);
 $HeaderSQL = "INSERT INTO salesorders (orderno,\n\t\t\t\t\t\t\t\t\t\t\tdebtorno,\n\t\t\t\t\t\t\t\t\t\t\tbranchcode,\n\t\t\t\t\t\t\t\t\t\t\tcustomerref,\n\t\t\t\t\t\t\t\t\t\t\torddate,\n\t\t\t\t\t\t\t\t\t\t\tordertype,\n\t\t\t\t\t\t\t\t\t\t\tshipvia,\n\t\t\t\t\t\t\t\t\t\t\tdeliverto,\n\t\t\t\t\t\t\t\t\t\t\tdeladd1,\n\t\t\t\t\t\t\t\t\t\t\tdeladd2,\n\t\t\t\t\t\t\t\t\t\t\tdeladd3,\n\t\t\t\t\t\t\t\t\t\t\tdeladd4,\n\t\t\t\t\t\t\t\t\t\t\tdeladd5,\n\t\t\t\t\t\t\t\t\t\t\tdeladd6,\n\t\t\t\t\t\t\t\t\t\t\tcontactphone,\n\t\t\t\t\t\t\t\t\t\t\tcontactemail,\n\t\t\t\t\t\t\t\t\t\t\tfromstkloc,\n\t\t\t\t\t\t\t\t\t\t\tdeliverydate)\n\t\t\t\t\tVALUES ('" . $SalesOrderNo . "',\n\t\t\t\t\t\t\t'" . $_SESSION['SPL' . $identifier]->CustomerID . "',\n\t\t\t\t\t\t\t'" . $_SESSION['SPL' . $identifier]->BranchCode . "',\n\t\t\t\t\t\t\t'" . $_SESSION['SPL' . $identifier]->CustRef . "',\n\t\t\t\t\t\t\t'" . Date('Y-m-d') . "',\n\t\t\t\t\t\t\t'" . $BranchDetails['salestype'] . "',\n\t\t\t\t\t\t\t'" . $BranchDetails['defaultshipvia'] . "',\n\t\t\t\t\t\t\t'" . $BranchDetails['brname'] . "',\n\t\t\t\t\t\t\t'" . $BranchDetails['braddress1'] . "',\n\t\t\t\t\t\t\t'" . $BranchDetails['braddress2'] . "',\n\t\t\t\t\t\t\t'" . $BranchDetails['braddress3'] . "',\n\t\t\t\t\t\t\t'" . $BranchDetails['braddress4'] . "',\n\t\t\t\t\t\t\t'" . $BranchDetails['braddress5'] . "',\n\t\t\t\t\t\t\t'" . $BranchDetails['braddress6'] . "',\n\t\t\t\t\t\t\t'" . $BranchDetails['phoneno'] . "',\n\t\t\t\t\t\t\t'" . $BranchDetails['email'] . "',\n\t\t\t\t\t\t\t'" . $_SESSION['SPL' . $identifier]->StkLocation . "',\n\t\t\t\t\t\t\t'" . $OrderDate . "')";
 $ErrMsg = _('The sales order cannot be added because');
 $InsertQryResult = DB_query($HeaderSQL, $db, $ErrMsg, $DbgMsg);
 $StartOf_LineItemsSQL = "INSERT INTO salesorderdetails (orderno,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tstkcode,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tunitprice,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tquantity,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\torderlineno)\n\t\t\t\t\t\tVALUES ('" . $SalesOrderNo . "'";
 $ErrMsg = _('There was a problem inserting a line into the sales order because');
 foreach ($_SESSION['SPL' . $identifier]->LineItems as $StockItem) {
     $LineItemsSQL = $StartOf_LineItemsSQL . ",\n\t\t\t\t\t\t\t'" . $StockItem->PartCode . "',\n\t\t\t\t\t\t\t'" . $StockItem->Price . "',\n\t\t\t\t\t\t\t'" . $StockItem->Quantity . "',\n\t\t\t\t\t\t\t'" . $StockItem->LineNo . "')";
     $Ins_LineItemResult = DB_query($LineItemsSQL, $db, $ErrMsg);
 }
 /* inserted line items into sales order details */
 unset($_SESSION['SPL' . $identifier]);
 prnMsg(_('Sales Order Number') . ' ' . $SalesOrderNo . ' ' . _('has been entered') . '. <br />' . _('Orders created on a cash sales account may need the delivery details for the order to be modified') . '. <br /><br />' . _('A freight charge may also be applicable'), 'success');
 if (count($_SESSION['AllowedPageSecurityTokens']) > 1) {
     /* Only allow print of packing slip for internal staff - customer logon's cannot go here */
     echo '<p><a href="' . $rootpath . '/PrintCustOrder.php?TransNo=' . $SalesOrderNo . '">' . _('Print packing slip') . ' (' . _('Preprinted stationery') . ')</a></p>';
 //end of auto-issue loop for all components set to auto-issue
 /* Need to get the current location quantity will need it later for the stock movement */
 $SQL = "SELECT locstock.quantity\n\t\t\t\tFROM locstock\n\t\t\t\tWHERE locstock.stockid='" . $_POST['StockID'] . "'\n\t\t\t\tAND loccode= '" . $_POST['IntoLocation'] . "'";
 $Result = DB_query($SQL, $db);
 if (DB_num_rows($Result) == 1) {
     $LocQtyRow = DB_fetch_array($Result);
     $QtyOnHandPrior = $LocQtyRow['quantity'];
 } else {
     /*There must actually be some error this should never happen */
     $QtyOnHandPrior = 0;
 }
 $SQL = "UPDATE locstock\n\t\t\t\tSET quantity = locstock.quantity + " . $QuantityReceived . "\n\t\t\t\tWHERE locstock.stockid = '" . $_POST['StockID'] . "'\n\t\t\t\tAND loccode = '" . $_POST['IntoLocation'] . "'";
 $ErrMsg = _('CRITICAL ERROR') . '! ' . _('NOTE DOWN THIS ERROR AND SEEK ASSISTANCE') . ': ' . _('The location stock record could not be updated because');
 $DbgMsg = _('The following SQL to update the location stock record was used');
 $Result = DB_query($SQL, $db, $ErrMsg, $DbgMsg, true);
 $WOReceiptNo = GetNextTransNo(26, $db);
 /*Insert stock movements - with unit cost */
 $SQL = "INSERT INTO stockmoves (stockid,\n\t\t\t\t\t\t\t\t\t\ttype,\n\t\t\t\t\t\t\t\t\t\ttransno,\n\t\t\t\t\t\t\t\t\t\tloccode,\n\t\t\t\t\t\t\t\t\t\ttrandate,\n\t\t\t\t\t\t\t\t\t\tprice,\n\t\t\t\t\t\t\t\t\t\tprd,\n\t\t\t\t\t\t\t\t\t\treference,\n\t\t\t\t\t\t\t\t\t\tqty,\n\t\t\t\t\t\t\t\t\t\tstandardcost,\n\t\t\t\t\t\t\t\t\t\tnewqoh)\n\t\t\t\t\tVALUES ('" . $_POST['StockID'] . "',\n\t\t\t\t\t\t\t26,\n\t\t\t\t\t\t\t'" . $WOReceiptNo . "',\n\t\t\t\t\t\t\t'" . $_POST['IntoLocation'] . "',\n\t\t\t\t\t\t\t'" . Date('Y-m-d') . "',\n\t\t\t\t\t\t\t'" . $WORow['stdcost'] . "',\n\t\t\t\t\t\t\t'" . $PeriodNo . "',\n\t\t\t\t\t\t\t'" . $_POST['WO'] . "',\n\t\t\t\t\t\t\t'" . $QuantityReceived . "',\n\t\t\t\t\t\t\t'" . $WORow['stdcost'] . "',\n\t\t\t\t\t\t\t'" . ($QtyOnHandPrior + $QuantityReceived) . "')";
 $ErrMsg = _('CRITICAL ERROR') . '! ' . _('NOTE DOWN THIS ERROR AND SEEK ASSISTANCE') . ': ' . _('stock movement records could not be inserted when processing the work order receipt because');
 $DbgMsg = _('The following SQL to insert the stock movement records was used');
 $Result = DB_query($SQL, $db, $ErrMsg, $DbgMsg, true);
 /*Get the ID of the StockMove... */
 $StkMoveNo = DB_Last_Insert_ID($db, 'stockmoves', 'stkmoveno');
 /* Do the Controlled Item INSERTS HERE */
 if ($WORow['controlled'] == 1) {
     //the form is different for serialised items and just batch/lot controlled items
     if ($WORow['serialised'] == 1) {
         //serialised items form has a possible 60 fields for entry of serial numbers - 12 rows x 5 per row
         for ($i = 0; $i < $_POST['CountOfInputs']; $i++) {
             /*  We need to add the StockSerialItem record and
             				The StockSerialMoves as well */