1<?php
2/* Entry of both customer receipts against accounts receivable and also general ledger or nominal receipts */
3
4include('includes/DefineReceiptClass.php');
5include('includes/session.php');
6
7
8$Title = _('Receipt Entry');
9
10if ($_GET['Type']=='GL') {
11	$ViewTopic= 'GeneralLedger';
12	$BookMark = 'GLReceipts';
13} else {
14	$ViewTopic= 'ARTransactions';
15	$BookMark = 'CustomerReceipts';
16}
17
18include('includes/header.php');
19include('includes/SQL_CommonFunctions.inc');
20if (empty($_GET['identifier'])) {
21	$identifier = date('U');
22} else {
23	$identifier = $_GET['identifier'];
24}
25
26
27$msg='';
28
29if (isset($_GET['NewReceipt'])){
30	unset($_SESSION['ReceiptBatch' . $identifier]->Items);
31	unset($_SESSION['ReceiptBatch' . $identifier]);
32	unset($_SESSION['CustomerRecord' . $identifier]);
33}
34
35if (isset($_POST['Cancel'])) {
36	$Cancel=1;
37}
38
39if (isset($_GET['Type']) AND $_GET['Type']=='GL') {
40	$_POST['GLEntry']=1;
41}
42
43if ((isset($_POST['BatchInput'])
44	AND $_POST['BankAccount']=='')
45	OR (isset($_POST['Process'])
46	AND $_POST['BankAccount']=='')) {
47
48	echo '<br />';
49	prnMsg(_('A bank account must be selected for this receipt'), 'warn');
50	$BankAccountEmpty=true;
51} else if(isset($_GET['NewReceipt'])) {
52	$BankAccountEmpty=true;
53} else {
54	$BankAccountEmpty=false;
55}
56
57$Errors = array();
58
59if (!isset($_GET['Delete']) AND isset($_SESSION['ReceiptBatch' . $identifier])){
60	//always process a header update unless deleting an item
61
62	include('includes/GetPaymentMethods.php');
63
64	$_SESSION['ReceiptBatch' . $identifier]->Account = $_POST['BankAccount'];
65	/*Get the bank account currency and set that too */
66
67	$SQL = "SELECT bankaccountname,
68					currcode,
69					decimalplaces
70			FROM bankaccounts
71			INNER JOIN currencies
72			ON bankaccounts.currcode=currencies.currabrev
73			WHERE accountcode='" . $_POST['BankAccount']."'";
74
75	$ErrMsg =_('The bank account name cannot be retrieved because');
76	$result= DB_query($SQL,$ErrMsg);
77
78	if (DB_num_rows($result)==1){
79		$myrow = DB_fetch_array($result);
80		$_SESSION['ReceiptBatch' . $identifier]->BankAccountName = $myrow['bankaccountname'];
81		$_SESSION['ReceiptBatch' . $identifier]->AccountCurrency=$myrow['currcode'];
82		$_SESSION['ReceiptBatch' . $identifier]->CurrDecimalPlaces=$myrow['decimalplaces'];
83		unset($result);
84	} elseif (DB_num_rows($result)==0 AND !$BankAccountEmpty){
85		prnMsg( _('The bank account number') . ' ' . $_POST['BankAccount'] . ' ' . _('is not set up as a bank account'),'error');
86		include ('includes/footer.php');
87		exit;
88	}
89
90	if (!Is_Date($_POST['DateBanked'])){
91		$_POST['DateBanked'] = Date($_SESSION['DefaultDateFormat']);
92	}
93	$_SESSION['ReceiptBatch' . $identifier]->DateBanked = $_POST['DateBanked'];
94	if (isset($_POST['ExRate']) AND $_POST['ExRate']!=''){
95		if (is_numeric(filter_number_format($_POST['ExRate']))){
96			$_SESSION['ReceiptBatch' . $identifier]->ExRate = filter_number_format($_POST['ExRate']);
97		} else {
98			prnMsg(_('The exchange rate entered should be numeric'),'warn');
99		}
100	}
101	if (isset($_POST['FunctionalExRate']) AND $_POST['FunctionalExRate']!=''){
102		if (is_numeric(filter_number_format($_POST['FunctionalExRate']))){
103			$_SESSION['ReceiptBatch' . $identifier]->FunctionalExRate=filter_number_format($_POST['FunctionalExRate']); //ex rate between receipt currency and account currency
104		} else {
105			prnMsg(_('The functional exchange rate entered should be numeric'),'warn');
106		}
107	}
108	if (!isset($_POST['ReceiptType'])) {
109		$_POST['ReceiptType'] = '';
110	}
111	$_SESSION['ReceiptBatch' . $identifier]->ReceiptType = $_POST['ReceiptType'];
112
113	if (!isset($_POST['Currency'])){
114		$_POST['Currency']=$_SESSION['CompanyRecord']['currencydefault'];
115	}
116
117	if ($_SESSION['ReceiptBatch' . $identifier]->Currency!=$_POST['Currency']){
118
119		$_SESSION['ReceiptBatch' . $identifier]->Currency=$_POST['Currency']; //receipt currency
120		/*Now customer receipts entered using the previous currency need to be ditched
121		and a warning message displayed if there were some customer receipted entered */
122		if (count($_SESSION['ReceiptBatch' . $identifier]->Items)>0){
123			unset($_SESSION['ReceiptBatch' . $identifier]->Items);
124			prnMsg(_('Changing the currency of the receipt means that existing entries need to be re-done - only customers trading in the selected currency can be selected'),'warn');
125		}
126
127	}
128
129	if ($_SESSION['ReceiptBatch' . $identifier]->AccountCurrency==$_SESSION['CompanyRecord']['currencydefault']){
130		$_SESSION['ReceiptBatch' . $identifier]->FunctionalExRate = 1;
131		$SuggestedFunctionalExRate =1;
132	} elseif (!$BankAccountEmpty) {
133		/*To illustrate the rates required
134			Take an example functional currency NZD receipt in USD from an AUD bank account
135			1 NZD = 0.80 USD
136			1 NZD = 0.90 AUD
137			The FunctionalExRate = 0.90 - the rate between the functional currency and the bank account currency
138			The receipt ex rate is the rate at which one can sell the received currency and purchase the bank account currency
139			or 0.8/0.9 = 0.88889
140		*/
141
142		/*Get suggested FunctionalExRate between the bank account currency and the home (functional) currency */
143		$result = DB_query("SELECT rate, decimalplaces FROM currencies WHERE currabrev='" . $_SESSION['ReceiptBatch' . $identifier]->AccountCurrency . "'");
144		$myrow = DB_fetch_array($result);
145		$SuggestedFunctionalExRate = $myrow['rate'];
146		$_SESSION['ReceiptBatch' . $identifier]->CurrDecimalPlaces = $myrow['decimalplaces'];
147
148	} //end else account currency != functional currency
149
150	if ($_POST['Currency']==$_SESSION['ReceiptBatch' . $identifier]->AccountCurrency){
151		$_SESSION['ReceiptBatch' . $identifier]->ExRate = 1; //ex rate between receipt currency and account currency
152		$SuggestedExRate=1;
153	} elseif(isset($_POST['Currency'])) {
154		/*Get the exchange rate between the functional currency and the receipt currency*/
155		$result = DB_query("SELECT rate FROM currencies WHERE currabrev='" . $_SESSION['ReceiptBatch' . $identifier]->Currency . "'");
156		$myrow = DB_fetch_array($result);
157		$TableExRate = $myrow['rate']; //this is the rate of exchange between the functional currency and the receipt currency
158		/*Calculate cross rate to suggest appropriate exchange rate between receipt currency and account currency */
159		$SuggestedExRate = $TableExRate/$SuggestedFunctionalExRate;
160	}
161
162	$_SESSION['ReceiptBatch' . $identifier]->BankTransRef = $_POST['BankTransRef'];
163	$_SESSION['ReceiptBatch' . $identifier]->Narrative = $_POST['BatchNarrative'];
164
165} elseif (isset($_GET['Delete'])) {
166	/* User hit delete the receipt entry from the batch */
167	$_SESSION['ReceiptBatch' . $identifier]->remove_receipt_item($_GET['Delete']);
168} else { //it must be a new receipt batch
169	$_SESSION['ReceiptBatch' . $identifier] = new Receipt_Batch;
170}
171
172
173if (isset($_POST['Process'])){ //user hit submit a new entry to the receipt batch
174
175	if (!isset($_POST['GLCode'])) {
176		$_POST['GLCode']='';
177	}
178	if (!isset($_POST['tag'])) {
179		$_POST['tag']='';
180	}
181	if (!isset($_POST['CustomerID'])) {
182		$_POST['CustomerID']='';
183	}
184	if (!isset($_POST['CustomerName'])) {
185		$_POST['CustomerName']='';
186	}
187	if ($_POST['Discount']==0 AND $ReceiptTypes[$_SESSION['ReceiptBatch' . $identifier]->ReceiptType]['percentdiscount']>0){
188		if (isset($_GET['Type']) AND $_GET['Type'] == 'Customer') {
189			$_POST['Discount'] = $_POST['Amount']*$ReceiptTypes[$_SESSION['ReceiptBatch' . $identifier]->ReceiptType]['percentdiscount'];
190		}
191	}
192
193	if ($_POST['GLCode'] == '' AND $_GET['Type']=='GL') {
194		prnMsg( _('No General Ledger code has been chosen') . ' - ' . _('so this GL analysis item could not be added'),'warn');
195
196	} else {
197		$AllowThisPosting = true;
198 		if ($_SESSION['ProhibitJournalsToControlAccounts'] == 1) {
199 			if ($_SESSION['CompanyRecord']['gllink_debtors'] == '1' AND $_POST['GLCode'] == $_SESSION['CompanyRecord']['debtorsact']) {
200 				prnMsg(_('Payments involving the debtors control account cannot be entered. The general ledger debtors ledger (AR) integration is enabled so control accounts are automatically maintained. This setting can be disabled in System Configuration'), 'warn');
201 				$AllowThisPosting = false;
202 			}
203 			if ($_SESSION['CompanyRecord']['gllink_creditors'] == '1' AND
204				($_POST['GLCode'] == $_SESSION['CompanyRecord']['creditorsact'] OR $_POST['GLCode'] == $_SESSION['CompanyRecord']['grnact'])) {
205 				prnMsg(_('Payments involving the creditors control account or the GRN suspense account cannot be entered. The general ledger creditors ledger (AP) integration is enabled so control accounts are automatically maintained. This setting can be disabled in System Configuration'), 'warn');
206 				$AllowThisPosting = false;
207 			}
208 			if ($_POST['GLCode'] == $_SESSION['CompanyRecord']['retainedearnings']) {
209 				prnMsg(_('Payments involving the retained earnings control account cannot be entered. This account is automtically maintained.'), 'warn');
210 				$AllowThisPosting = false;
211 			}
212 		}
213 		if ($AllowThisPosting) {
214 			$_SESSION['ReceiptBatch' . $identifier]->add_to_batch(filter_number_format($_POST['Amount']),
215													$_POST['CustomerID'],
216													filter_number_format($_POST['Discount']),
217													$_POST['Narrative'],
218													$_POST['GLCode'],
219													$_POST['PayeeBankDetail'],
220													$_POST['CustomerName'],
221													$_POST['tag']);
222			/*Make sure the same receipt is not double processed by a page refresh */
223			$Cancel = 1;
224		}
225	}
226}
227
228if (isset($Cancel)){
229	unset($_SESSION['CustomerRecord' . $identifier]);
230	unset($_POST['CustomerID']);
231	unset($_POST['CustomerName']);
232	unset($_POST['Amount']);
233	unset($_POST['Discount']);
234	unset($_POST['Narrative']);
235	unset($_POST['PayeeBankDetail']);
236}
237
238
239if (isset($_POST['CommitBatch'])){
240
241 /* once all receipts items entered, process all the data in the
242  session cookie into the DB creating a single banktrans for the whole amount
243  of all receipts in the batch and DebtorTrans records for each receipt item
244  all DebtorTrans will refer to a single banktrans. A GL entry is created for
245  each GL receipt entry and one for the debtors entry and one for the bank
246  account debit
247
248  NB allocations against debtor receipts are a separate exercice
249
250  first off run through the array of receipt items $_SESSION['ReceiptBatch']->Items and
251  if GL integrated then create GL Entries for the GL Receipt items
252  and add up the non-GL ones for posting to debtors later,
253  also add the total discount total receipts*/
254
255	$PeriodNo = GetPeriod($_SESSION['ReceiptBatch' . $identifier]->DateBanked);
256
257	if ($_SESSION['CompanyRecord']==0){
258		prnMsg(_('The company has not yet been set up properly') . ' - ' . _('this information is needed to process the batch') . '. ' . _('Processing has been cancelled'),'error');
259		include('includes/footer.php');
260		exit;
261	}
262
263	/*Make an array of the defined bank accounts */
264	$SQL = "SELECT accountcode FROM bankaccounts";
265	$result = DB_query($SQL);
266	$BankAccounts = array();
267	$i=0;
268	while ($Act = DB_fetch_row($result)){
269		$BankAccounts[$i]= $Act[0];
270		$i++;
271	}
272
273	/*Start a transaction to do the whole lot inside */
274	$result = DB_Txn_Begin();
275	$_SESSION['ReceiptBatch' . $identifier]->BatchNo = GetNextTransNo(12);
276
277
278	$BatchReceiptsTotal = 0; //in functional currency
279	$BatchDiscount = 0; //in functional currency
280	$BatchDebtorTotal = 0; //in functional currency
281	$CustomerReceiptCounter=1; //Count lines of customer receipts in this batch
282
283	echo '<br />
284		<p class="page_title_text"><img alt="" src="', $RootPath, '/css/', $Theme,
285			'/images/money_add.png" title="',// Icon image.
286			_('Summary of Receipt Batch'), '" /> ',// Icon title.
287			_('Summary of Receipt Batch'), '</p>',// Page title.
288		'<br />
289		<table class="selection">
290		<thead>
291			<tr>
292				<th>', _('Batch Number'), '</th>
293				<th>', _('Date Banked'), '</th>
294				<th>', _('Customer Name'), '</th>
295				<th class="text">', _('GL Code'), '</th>
296				<th class="number">', _('Amount of Receipt'), '</th>';
297	if(isset($ReceiptItem) AND $ReceiptItem->GLCode =='') {
298		echo '<th class="noprint">&nbsp;</th>';
299	}
300	echo '</tr>
301		</thead><tbody>';
302
303	foreach ($_SESSION['ReceiptBatch' . $identifier]->Items as $ReceiptItem) {
304
305		$SQL = "SELECT accountname FROM chartmaster WHERE accountcode='" . $ReceiptItem->GLCode . "'";
306		$Result=DB_query($SQL);
307		$myrow=DB_fetch_array($Result);
308
309		echo '<tr class="striped_row">
310			<td>' . $_SESSION['ReceiptBatch' . $identifier]->BatchNo . '</td>
311			<td>' . $_SESSION['ReceiptBatch' . $identifier]->DateBanked . '</td>
312			<td>' . $ReceiptItem->CustomerName . '</td>
313			<td class="text">' . $ReceiptItem->GLCode . ' - ' . $myrow['accountname'] . '</td>
314			<td class="number">' . locale_number_format($ReceiptItem->Amount/$_SESSION['ReceiptBatch' . $identifier]->ExRate/$_SESSION['ReceiptBatch' . $identifier]->FunctionalExRate,$_SESSION['ReceiptBatch' . $identifier]->CurrDecimalPlaces)  . '</td>';
315
316		if ($ReceiptItem->GLCode ==''){
317			echo '<td class="noprint"><a target="_blank" href="', $RootPath, '/PDFReceipt.php?BatchNumber=', $_SESSION['ReceiptBatch' . $identifier]->BatchNo, '&ReceiptNumber=', $CustomerReceiptCounter, '">', _('Print a Customer Receipt'), '</a></td></tr>';
318			$CustomerReceiptCounter += 1;
319		}
320
321		if ($ReceiptItem->GLCode !=''){ //so its a GL receipt
322			if ($_SESSION['CompanyRecord']['gllink_debtors']==1){ /* then enter a GLTrans record */
323				 $SQL = "INSERT INTO gltrans (type,
324								 			typeno,
325											trandate,
326											periodno,
327											account,
328											narrative,
329											amount,
330											tag)
331					VALUES (
332						12,
333						'" . $_SESSION['ReceiptBatch' . $identifier]->BatchNo . "',
334						'" . FormatDateForSQL($_SESSION['ReceiptBatch' . $identifier]->DateBanked) . "',
335						'" . $PeriodNo . "',
336						'" . $ReceiptItem->GLCode . "',
337						'" . $ReceiptItem->Narrative . "',
338						'" . -($ReceiptItem->Amount/$_SESSION['ReceiptBatch' . $identifier]->ExRate/$_SESSION['ReceiptBatch' . $identifier]->FunctionalExRate) . "',
339						'" . $ReceiptItem->tag . "'" . "
340					)";
341				$ErrMsg = _('Cannot insert a GL entry for the receipt because');
342				$DbgMsg = _('The SQL that failed to insert the receipt GL entry was');
343				$result = DB_query($SQL,$ErrMsg,$DbgMsg,true);
344			}
345
346			/*check to see if this is a GL posting to another bank account (or the same one)
347			if it is then a matching payment needs to be created for this account too */
348
349			if (in_array($ReceiptItem->GLCode, $BankAccounts)) {
350
351			/*Need to deal with the case where the payment from one bank account could be to a bank account in another currency */
352
353				/*Get the currency and rate of the bank account transferring to*/
354				$SQL = "SELECT currcode, rate
355							FROM bankaccounts INNER JOIN currencies
356							ON bankaccounts.currcode = currencies.currabrev
357							WHERE accountcode='" . $ReceiptItem->GLCode."'";
358				$TrfFromAccountResult = DB_query($SQL);
359				$TrfFromBankRow = DB_fetch_array($TrfFromAccountResult) ;
360				$TrfFromBankCurrCode = $TrfFromBankRow['currcode'];
361				$TrfFromBankExRate = $TrfFromBankRow['rate'];
362
363				if ($_SESSION['ReceiptBatch' . $identifier]->AccountCurrency == $TrfFromBankCurrCode){
364					/*Make sure to use the same rate if the transfer is between two bank accounts in the same currency */
365					$TrfFromBankExRate = $_SESSION['ReceiptBatch' . $identifier]->FunctionalExRate;
366				}
367
368				/*Consider an example - had to be currencies I am familar with sorry so I could figure it out!!
369					 functional currency NZD
370					 bank account in AUD - 1 NZD = 0.90 AUD (FunctionalExRate)
371					 receiving USD - 1 AUD = 0.85 USD  (ExRate)
372					 from a bank account in EUR - 1 NZD = 0.52 EUR
373
374					 oh yeah - now we are getting tricky!
375					 Lets say we received USD 100 to the AUD bank account from the EUR bank account
376
377					 To get the ExRate for the bank account we are transferring money from
378					 we need to use the cross rate between the NZD-AUD/NZD-EUR
379					 and apply this to the
380
381					 the receipt record will read
382					 exrate = 0.85 (1 AUD = USD 0.85)
383					 amount = 100 (USD)
384					 functionalexrate = 0.90 (1 NZD = AUD 0.90)
385
386					 the payment record will read
387
388					 amount 100 (USD)
389					 exrate    (1 EUR =  (0.85 x 0.90)/0.52 USD  ~ 1.47
390					  					(ExRate x FunctionalExRate) / USD Functional ExRate
391					 Check this is 1 EUR = 1.47 USD
392					 functionalexrate =  (1NZD = EUR 0.52)
393
394				*/
395
396				$PaymentTransNo = GetNextTransNo( 1 );
397				$SQL="INSERT INTO banktrans (transno,
398											type,
399											bankact,
400											ref,
401											exrate,
402											functionalexrate,
403											transdate,
404											banktranstype,
405											amount,
406											currcode)
407						VALUES (
408							'" . $PaymentTransNo . "',
409							1,
410							'" . $ReceiptItem->GLCode . "',
411							'" . _('Act Transfer') ." - " . $ReceiptItem->Narrative . "',
412							'" . (($_SESSION['ReceiptBatch' . $identifier]->ExRate * $_SESSION['ReceiptBatch' . $identifier]->FunctionalExRate)/$TrfFromBankExRate). "',
413							'" . $TrfFromBankExRate . "',
414							'" . FormatDateForSQL($_SESSION['ReceiptBatch' . $identifier]->DateBanked) . "',
415							'" . $ReceiptTypes[$_SESSION['ReceiptBatch' . $identifier]->ReceiptType]['paymentname'] . "',
416							'" . -$ReceiptItem->Amount . "',
417							'" . $_SESSION['ReceiptBatch' . $identifier]->Currency . "'
418						)";
419
420				$DbgMsg = _('The SQL that failed to insert the bank transaction was');
421				$ErrMsg = _('Cannot insert a bank transaction using the SQL');
422				$result = DB_query($SQL,$ErrMsg,$DbgMsg,true);
423			} //end if an item is a transfer between bank accounts
424
425		} else { //its not a GL item - its a customer receipt then
426			/*Accumulate the total debtors credit including discount */
427			$BatchDebtorTotal += (($ReceiptItem->Discount + $ReceiptItem->Amount)/$_SESSION['ReceiptBatch' . $identifier]->ExRate/$_SESSION['ReceiptBatch' . $identifier]->FunctionalExRate);
428			/*Create a DebtorTrans entry for each customer deposit */
429
430			/*The rate of exchange required here is the rate between the functional (home) currency and the customer receipt currency
431			 * We have the exchange rate between the bank account and the functional home currency  $_SESSION['ReceiptBatch']->ExRate
432			 * and the exchange rate betwen the currency being paid and the bank account */
433
434			$SQL = "INSERT INTO debtortrans (transno,
435											type,
436											debtorno,
437											branchcode,
438											order_,
439											trandate,
440											inputdate,
441											prd,
442											reference,
443											tpe,
444											rate,
445											ovamount,
446											ovdiscount,
447											invtext,
448											salesperson)
449					VALUES (
450						'" . $_SESSION['ReceiptBatch' . $identifier]->BatchNo . "',
451						12,
452						'" . $ReceiptItem->Customer . "',
453						'',
454						'" . $ReceiptItem->ID . "',
455						'" . FormatDateForSQL($_SESSION['ReceiptBatch' . $identifier]->DateBanked) . "',
456						'" . date('Y-m-d H-i-s') . "',
457						'" . $PeriodNo . "',
458						'" . $ReceiptTypes[$_SESSION['ReceiptBatch' . $identifier]->ReceiptType]['paymentname']  . ' ' . $ReceiptItem->PayeeBankDetail . "',
459						'',
460						'" . ($_SESSION['ReceiptBatch' . $identifier]->FunctionalExRate*$_SESSION['ReceiptBatch' . $identifier]->ExRate) . "',
461						'" . -$ReceiptItem->Amount . "',
462						'" . -$ReceiptItem->Discount . "',
463						'" . $ReceiptItem->Narrative. "',
464						'" . $_SESSION['SalesmanLogin']. "'
465					)";
466			$DbgMsg = _('The SQL that failed to insert the customer receipt transaction was');
467			$ErrMsg = _('Cannot insert a receipt transaction against the customer because') ;
468			$result = DB_query($SQL,$ErrMsg,$DbgMsg,true);
469
470			$SQL = "UPDATE debtorsmaster
471						SET lastpaiddate = '" . FormatDateForSQL($_SESSION['ReceiptBatch' . $identifier]->DateBanked) . "',
472						lastpaid='" . $ReceiptItem->Amount ."'
473					WHERE debtorsmaster.debtorno='" . $ReceiptItem->Customer . "'";
474
475			$DbgMsg = _('The SQL that failed to update the date of the last payment received was');
476			$ErrMsg = _('Cannot update the customer record for the date of the last payment received because');
477			$result = DB_query($SQL,$ErrMsg,$DbgMsg,true);
478
479		} //end of if its a customer receipt
480		$BatchDiscount += ($ReceiptItem->Discount/$_SESSION['ReceiptBatch' . $identifier]->ExRate/$_SESSION['ReceiptBatch' . $identifier]->FunctionalExRate);
481		$BatchReceiptsTotal += ($ReceiptItem->Amount/$_SESSION['ReceiptBatch' . $identifier]->ExRate/$_SESSION['ReceiptBatch' . $identifier]->FunctionalExRate);
482
483	} /*end foreach $ReceiptItem */
484	echo '</tbody></table>';
485
486	/*now enter the BankTrans entry */
487
488	$SQL="INSERT INTO banktrans (type,
489								transno,
490								bankact,
491								ref,
492								exrate,
493								functionalexrate,
494								transdate,
495								banktranstype,
496								amount,
497								currcode)
498		VALUES (
499			12,
500			'" . $_SESSION['ReceiptBatch' . $identifier]->BatchNo . "',
501			'" . $_SESSION['ReceiptBatch' . $identifier]->Account . "',
502			'" . $_SESSION['ReceiptBatch' . $identifier]->BankTransRef . "',
503			'" . $_SESSION['ReceiptBatch' . $identifier]->ExRate . "',
504			'" . $_SESSION['ReceiptBatch' . $identifier]->FunctionalExRate . "',
505			'" . FormatDateForSQL($_SESSION['ReceiptBatch' . $identifier]->DateBanked) . "',
506			'" . $ReceiptTypes[$_SESSION['ReceiptBatch' . $identifier]->ReceiptType]['paymentname'] . "',
507			'" . ($BatchReceiptsTotal * $_SESSION['ReceiptBatch' . $identifier]->FunctionalExRate * $_SESSION['ReceiptBatch' . $identifier]->ExRate) . "',
508			'" . $_SESSION['ReceiptBatch' . $identifier]->Currency . "'
509		)";
510	$DbgMsg = _('The SQL that failed to insert the bank account transaction was');
511	$ErrMsg = _('Cannot insert a bank transaction');
512	$result = DB_query($SQL,$ErrMsg,$DbgMsg,true);
513
514
515	if ($_SESSION['CompanyRecord']['gllink_debtors']==1){ /* then enter GLTrans records for discount, bank and debtors */
516
517		if ($BatchReceiptsTotal!=0){
518			/* Bank account entry first */
519			$SQL="INSERT INTO gltrans (type,
520										typeno,
521										trandate,
522										periodno,
523										account,
524										narrative,
525										amount)
526				VALUES (
527					12,
528					'" . $_SESSION['ReceiptBatch' . $identifier]->BatchNo . "',
529					'" . FormatDateForSQL($_SESSION['ReceiptBatch' . $identifier]->DateBanked) . "',
530					'" . $PeriodNo . "',
531					'" . $_SESSION['ReceiptBatch' . $identifier]->Account . "',
532					'" . $_SESSION['ReceiptBatch' . $identifier]->Narrative . "',
533					'" . $BatchReceiptsTotal . "'
534				)";
535			$DbgMsg = _('The SQL that failed to insert the GL transaction fro the bank account debit was');
536			$ErrMsg = _('Cannot insert a GL transaction for the bank account debit');
537			$result = DB_query($SQL,$ErrMsg,$DbgMsg,true);
538
539
540		}
541		if ($BatchDebtorTotal!=0){
542			/* Now Credit Debtors account with receipts + discounts */
543			$SQL="INSERT INTO gltrans ( type,
544										typeno,
545										trandate,
546										periodno,
547										account,
548										narrative,
549										amount)
550						VALUES (
551							12,
552							'" . $_SESSION['ReceiptBatch' . $identifier]->BatchNo . "',
553							'" . FormatDateForSQL($_SESSION['ReceiptBatch' . $identifier]->DateBanked) . "',
554							'" . $PeriodNo . "',
555							'". $_SESSION['CompanyRecord']['debtorsact'] . "',
556							'" . $_SESSION['ReceiptBatch' . $identifier]->Narrative . "',
557							'" . -$BatchDebtorTotal . "'
558							)";
559			$DbgMsg = _('The SQL that failed to insert the GL transaction for the debtors account credit was');
560			$ErrMsg = _('Cannot insert a GL transaction for the debtors account credit');
561			$result = DB_query($SQL,$ErrMsg,$DbgMsg,true);
562
563		} //end if there are some customer deposits in this batch
564
565		if ($BatchDiscount!=0){
566			/* Now Debit Discount account with discounts allowed*/
567			$SQL="INSERT INTO gltrans ( type,
568										typeno,
569										trandate,
570										periodno,
571										account,
572										narrative,
573										amount)
574						VALUES (
575								12,
576								'" . $_SESSION['ReceiptBatch' . $identifier]->BatchNo . "',
577								'" . FormatDateForSQL($_SESSION['ReceiptBatch' . $identifier]->DateBanked) . "',
578								'" . $PeriodNo . "',
579								'" . $_SESSION['CompanyRecord']['pytdiscountact'] . "',
580								'" . $_SESSION['ReceiptBatch' . $identifier]->Narrative . "',
581								'" . $BatchDiscount . "'
582							)";
583			$DbgMsg = _('The SQL that failed to insert the GL transaction for the payment discount debit was');
584			$ErrMsg = _('Cannot insert a GL transaction for the payment discount debit');
585			$result = DB_query($SQL,$ErrMsg,$DbgMsg,true);
586		} //end if there is some discount
587
588	} //end if there is GL work to be done - ie config is to link to GL
589	EnsureGLEntriesBalance(12,$_SESSION['ReceiptBatch' . $identifier]->BatchNo);
590
591	$ErrMsg = _('Cannot commit the changes');
592	$DbgMsg = _('The SQL that failed was');
593	$result = DB_Txn_Commit();
594	echo '<br />';
595	prnMsg( _('Receipt batch') . ' ' . $_SESSION['ReceiptBatch' . $identifier]->BatchNo . ' ' . _('has been successfully entered into the database'),'success');
596
597	echo '<div class="centre noprint">',
598		'<p class="page_title_text"><img src="'.$RootPath.'/css/'.$Theme.'/images/printer.png" title="' . _('Print') . '" alt="" />' . ' ' . '<a href="' . $RootPath . '/PDFBankingSummary.php?BatchNo=' . $_SESSION['ReceiptBatch' . $identifier]->BatchNo . '">' . _('Print PDF Batch Summary') . '</a></p>';
599	echo '<p class="page_title_text"><img src="'.$RootPath.'/css/'.$Theme.'/images/allocation.png" title="' . _('Allocate') . '" alt="" />' . ' ' . '<a href="' . $RootPath . '/CustomerAllocations.php">' . _('Allocate Receipts') . '</a></p>';
600	echo '<p class="page_title_text"><img alt="" src="', $RootPath, '/css/', $Theme, '/images/transactions.png" title="', _('Enter Receipts'), '" /> ', '<a href="', $RootPath, '/CustomerReceipt.php?NewReceipt=Yes&Type=', urlencode($_GET['Type']), '">', _('Enter Receipts'), '</a></p>',
601		'</div>';
602
603	unset($_SESSION['ReceiptBatch' . $identifier]);
604	include('includes/footer.php');
605	exit;
606
607} /* End of commit batch */
608
609if (isset($_POST['Search'])){
610/*Will only be true if clicked to search for a customer code */
611
612	if ($_POST['Keywords'] AND $_POST['CustCode']) {
613		$msg=_('Customer name keywords have been used in preference to the customer code extract entered');
614	}
615	if ($_POST['Keywords']==''
616		AND $_POST['CustCode']==''
617		AND $_POST['CustInvNo']=='') {
618			$SQL = "SELECT debtorsmaster.debtorno,
619						debtorsmaster.name
620					FROM debtorsmaster
621					WHERE debtorsmaster.currcode= '" . $_SESSION['ReceiptBatch' . $identifier]->Currency . "'";
622	} else {
623		if (mb_strlen($_POST['Keywords'])>0) {
624			//insert wildcard characters in spaces
625			$SearchString = '%' . str_replace(' ', '%', $_POST['Keywords']) . '%';
626
627			$SQL = "SELECT debtorsmaster.debtorno,
628						debtorsmaster.name
629					FROM debtorsmaster
630					WHERE debtorsmaster.name " . LIKE . " '". $SearchString . "'
631					AND debtorsmaster.currcode= '" . $_SESSION['ReceiptBatch' . $identifier]->Currency . "'";
632
633		} elseif (mb_strlen($_POST['CustCode'])>0){
634			$SQL = "SELECT debtorsmaster.debtorno,
635						debtorsmaster.name
636					FROM debtorsmaster
637					WHERE debtorsmaster.debtorno " . LIKE . " '%" . $_POST['CustCode'] . "%'
638					AND debtorsmaster.currcode= '" . $_SESSION['ReceiptBatch' . $identifier]->Currency . "'";
639		} elseif (mb_strlen($_POST['CustInvNo'])>0){
640			$SQL = "SELECT debtortrans.debtorno,
641						debtorsmaster.name
642					FROM debtorsmaster LEFT JOIN debtortrans
643					ON debtorsmaster.debtorno=debtortrans.debtorno
644					WHERE debtortrans.transno " . LIKE . " '%" . $_POST['CustInvNo'] . "%'
645					AND debtorsmaster.currcode= '" . $_SESSION['ReceiptBatch' . $identifier]->Currency . "'";
646		}
647	}
648		if ($_SESSION['SalesmanLogin'] != '') {
649			$SQL .= " AND EXISTS (
650						SELECT *
651						FROM 	custbranch
652						WHERE 	custbranch.debtorno = debtorsmaster.debtorno
653							AND custbranch.salesman='" . $_SESSION['SalesmanLogin'] . "')";
654		}
655
656		$CustomerSearchResult = DB_query($SQL,'','',false,false);
657		if (DB_error_no() !=0) {
658			prnMsg(_('The searched customer records requested cannot be retrieved because') . ' - ' . DB_error_msg(),'error');
659			if ($debug==1){
660				prnMsg(_('SQL used to retrieve the customer details was') . '<br />' . $sql,'error');
661			}
662		} elseif (DB_num_rows($CustomerSearchResult)==1){
663			$myrow=DB_fetch_array($CustomerSearchResult);
664			$Select = $myrow['debtorno'];
665			unset($CustomerSearchResult);
666		} elseif (DB_num_rows($CustomerSearchResult)==0){
667			prnMsg( _('No customer records contain the selected text') . ' - ' . _('please alter your search criteria and try again'),'info');
668		}
669
670	 //one of keywords or custcode was more than a zero length string
671} //end of if search
672
673if (isset($_POST['Select'])){
674	$Select = $_POST['Select'];
675}
676
677if (isset($Select)) {
678/*will only be true if a customer has just been selected by clicking on the customer or only one
679customer record returned by the search - this record is then auto selected */
680
681	$_POST['CustomerID']=$Select;
682	/*need to get currency sales type - payment discount percent and GL code
683	as well as payment terms and credit status and hold the lot as session variables
684	the receipt held entirely as session variables until the button clicked to process*/
685
686
687	if (isset($_SESSION['CustomerRecord' . $identifier])){
688	   unset($_SESSION['CustomerRecord' . $identifier]);
689	}
690
691	$SQL = "SELECT debtorsmaster.name,
692				debtorsmaster.pymtdiscount,
693				debtorsmaster.currcode,
694				currencies.currency,
695				currencies.rate,
696				currencies.decimalplaces AS currdecimalplaces,
697				paymentterms.terms,
698				debtorsmaster.creditlimit,
699				holdreasons.dissallowinvoices,
700				holdreasons.reasondescription,
701				SUM(debtortrans.ovamount + debtortrans.ovgst + debtortrans.ovfreight + debtortrans.ovdiscount - debtortrans.alloc) AS balance,
702				SUM(CASE WHEN paymentterms.daysbeforedue > 0  THEN
703					CASE WHEN (TO_DAYS(Now()) - TO_DAYS(debtortrans.trandate)) >= paymentterms.daysbeforedue  THEN debtortrans.ovamount + debtortrans.ovgst + debtortrans.ovfreight + debtortrans.ovdiscount - debtortrans.alloc ELSE 0 END
704				ELSE
705					CASE WHEN TO_DAYS(Now()) - TO_DAYS(ADDDATE(last_day(debtortrans.trandate), paymentterms.dayinfollowingmonth)) >= 0 THEN debtortrans.ovamount + debtortrans.ovgst + debtortrans.ovfreight + debtortrans.ovdiscount - debtortrans.alloc ELSE 0 END
706				END) AS due,
707				SUM(CASE WHEN paymentterms.daysbeforedue > 0 THEN
708					CASE WHEN TO_DAYS(Now()) - TO_DAYS(debtortrans.trandate) > paymentterms.daysbeforedue	AND TO_DAYS(Now()) - TO_DAYS(debtortrans.trandate) >= (paymentterms.daysbeforedue + " . $_SESSION['PastDueDays1'] . ") THEN debtortrans.ovamount + debtortrans.ovgst + debtortrans.ovfreight - debtortrans.ovdiscount - debtortrans.alloc ELSE 0 END
709				ELSE
710					CASE WHEN TO_DAYS(Now()) - TO_DAYS(ADDDATE(last_day(debtortrans.trandate), paymentterms.dayinfollowingmonth)) >= " . $_SESSION['PastDueDays1'] . " THEN debtortrans.ovamount + debtortrans.ovgst + debtortrans.ovfreight + debtortrans.ovdiscount - debtortrans.alloc ELSE 0 END
711				END) AS overdue1,
712				SUM(CASE WHEN paymentterms.daysbeforedue > 0 THEN
713					CASE WHEN TO_DAYS(Now()) - TO_DAYS(debtortrans.trandate) > paymentterms.daysbeforedue AND TO_DAYS(Now()) - TO_DAYS(debtortrans.trandate) >= (paymentterms.daysbeforedue + " . $_SESSION['PastDueDays2'] . ") THEN debtortrans.ovamount + debtortrans.ovgst + debtortrans.ovfreight + debtortrans.ovdiscount - debtortrans.alloc ELSE 0 END
714				ELSE
715					CASE WHEN TO_DAYS(Now()) - TO_DAYS(ADDDATE(last_day(debtortrans.trandate), paymentterms.dayinfollowingmonth)) >= " . $_SESSION['PastDueDays2'] . " THEN debtortrans.ovamount + debtortrans.ovgst + debtortrans.ovfreight + debtortrans.ovdiscount - debtortrans.alloc ELSE 0 END
716				END) AS overdue2
717			FROM debtorsmaster INNER JOIN paymentterms
718			ON debtorsmaster.paymentterms = paymentterms.termsindicator
719			INNER JOIN holdreasons
720			ON debtorsmaster.holdreason = holdreasons.reasoncode
721			INNER JOIN currencies
722			ON debtorsmaster.currcode = currencies.currabrev
723			INNER JOIN debtortrans
724			ON debtorsmaster.debtorno = debtortrans.debtorno
725			WHERE debtorsmaster.debtorno = '" . $_POST['CustomerID'] . "'";
726	if ($_SESSION['SalesmanLogin'] != '') {
727		$SQL .= " AND debtortrans.salesperson='" . $_SESSION['SalesmanLogin'] . "'";
728	}
729	$SQL .= " GROUP BY debtorsmaster.name,
730				debtorsmaster.pymtdiscount,
731				debtorsmaster.currcode,
732				currencies.currency,
733				currencies.rate,
734				currencies.decimalplaces,
735				paymentterms.terms,
736				debtorsmaster.creditlimit,
737				paymentterms.daysbeforedue,
738				paymentterms.dayinfollowingmonth,
739				debtorsmaster.creditlimit,
740				holdreasons.dissallowinvoices,
741				holdreasons.reasondescription";
742
743
744	$ErrMsg = _('The customer details could not be retrieved because');
745	$DbgMsg = _('The SQL that failed was');
746	$CustomerResult = DB_query($SQL,$ErrMsg, $DbgMsg);
747
748	if (DB_num_rows($CustomerResult)==0){
749
750		/*Because there is no balance - so just retrieve the header information about the customer - the choice is do one query to get the balance and transactions for those customers who have a balance and two queries for those who don't have a balance OR always do two queries - I opted for the former */
751
752		$NIL_BALANCE = True;
753
754		$SQL = "SELECT debtorsmaster.name,
755						debtorsmaster.pymtdiscount,
756						currencies.currency,
757						currencies.rate,
758						currencies.decimalplaces AS currdecimalplaces,
759						paymentterms.terms,
760						debtorsmaster.creditlimit,
761						debtorsmaster.currcode,
762						holdreasons.dissallowinvoices,
763						holdreasons.reasondescription
764					FROM debtorsmaster INNER JOIN paymentterms
765					ON debtorsmaster.paymentterms = paymentterms.termsindicator
766					INNER JOIN holdreasons
767					ON debtorsmaster.holdreason = holdreasons.reasoncode
768					INNER JOIN currencies
769					ON debtorsmaster.currcode = currencies.currabrev
770					WHERE debtorsmaster.debtorno = '" . $_POST['CustomerID'] . "'";
771
772		$ErrMsg = _('The customer details could not be retrieved because');
773		$DbgMsg = _('The SQL that failed was');
774		$CustomerResult = DB_query($SQL,$ErrMsg, $DbgMsg);
775
776	} else {
777		$NIL_BALANCE = False;
778	}
779
780	$_SESSION['CustomerRecord' . $identifier] = DB_fetch_array($CustomerResult);
781
782	if ($NIL_BALANCE==True){
783		$_SESSION['CustomerRecord' . $identifier]['balance']=0;
784		$_SESSION['CustomerRecord' . $identifier]['due']=0;
785		$_SESSION['CustomerRecord' . $identifier]['overdue1']=0;
786		$_SESSION['CustomerRecord' . $identifier]['overdue2']=0;
787	}
788} /*end of if customer has just been selected  all info required read into $_SESSION['CustomerRecord']*/
789
790/*set up the form whatever */
791
792
793echo '<form action="' . htmlspecialchars($_SERVER['PHP_SELF'],ENT_QUOTES,'UTF-8') . '?Type=' . urlencode($_GET['Type']) . '&amp;identifier=' . urlencode($identifier) . '" method="post" id="form1">';
794echo '<div>';
795echo '<input type="hidden" name="FormID" value="' . $_SESSION['FormID'] . '" />';
796
797/*show the batch header details and the entries in the batch so far */
798
799$SQL = "SELECT bankaccountname,
800				bankaccounts.accountcode,
801				bankaccounts.currcode
802		FROM bankaccounts
803		INNER JOIN chartmaster
804			ON bankaccounts.accountcode=chartmaster.accountcode
805		INNER JOIN bankaccountusers
806			ON bankaccounts.accountcode=bankaccountusers.accountcode
807		WHERE bankaccountusers.userid = '" . $_SESSION['UserID'] ."'
808		ORDER BY bankaccountname";
809
810$ErrMsg = _('The bank accounts could not be retrieved because');
811$DbgMsg = _('The SQL used to retrieve the bank accounts was');
812$AccountsResults = DB_query($SQL,$ErrMsg,$DbgMsg);
813
814if (isset($_POST['GLEntry'])) {
815	echo '<p class="page_title_text"><img src="'.$RootPath.'/css/'.$Theme.'/images/transactions.png" title="' . _('Bank Account Receipts Entry') . '" alt="" />' . ' ' . _('Bank Account Receipts Entry') . '</p>';
816} else {
817	echo '<p class="page_title_text"><img src="'.$RootPath.'/css/'.$Theme.'/images/transactions.png" title="' . _('Enter Receipt') . '" alt="" />' . ' ' . _('Enter Customer Receipt') . '</p>';
818	echo '<div class="page_help_text">' . _('To enter a payment TO a customer (ie. to pay out a credit note), enter a negative payment amount.') . '</div>';
819}
820echo '<br />
821	<table class="selection">
822	<tr>
823		<td>' . _('Bank Account') . ':</td>
824		 <td><select tabindex="1" autofocus="autofocus" name="BankAccount" onchange="ReloadForm(form1.BatchInput)">';
825
826if (DB_num_rows($AccountsResults)==0){
827	echo '</select></td>
828		</tr>
829		</table>
830		<p />';
831	prnMsg(_('Bank Accounts have not yet been defined') . '. ' . _('You must first') . ' ' . '<a href="' . $RootPath . '/BankAccounts.php">' . _('define the bank accounts') . '</a>' . _('and general ledger accounts to be affected'),'info');
832	include('includes/footer.php');
833	 exit;
834} else {
835	echo '<option value=""></option>';
836	while ($myrow=DB_fetch_array($AccountsResults)){
837		/*list the bank account names */
838		if ($_SESSION['ReceiptBatch' . $identifier]->Account==$myrow['accountcode']){
839			echo '<option selected="selected" value="' . $myrow['accountcode'] . '">' . $myrow['bankaccountname'] . ' - ' . $myrow['currcode'] . '</option>';
840		} else {
841			echo '<option value="' . $myrow['accountcode'] . '">' . $myrow['bankaccountname']. ' - ' . $myrow['currcode'] . '</option>';
842		}
843	}
844	echo '</select></td>
845		</tr>';
846}
847
848if (!Is_Date($_SESSION['ReceiptBatch' . $identifier]->DateBanked)){
849	$_SESSION['ReceiptBatch' . $identifier]->DateBanked = Date($_SESSION['DefaultDateFormat']);
850}
851
852echo '<tr>
853		<td>' . _('Date Banked') . ':</td>
854		<td><input tabindex="2" type="text" required="required" class="date" name="DateBanked" maxlength="10" size="11" onchange="isDate(this, this.value, '."'".$_SESSION['DefaultDateFormat']."'".')" value="' . $_SESSION['ReceiptBatch' . $identifier]->DateBanked . '" /></td>
855	</tr>
856	<tr>
857		<td>' . _('Currency') . ':</td>
858		<td><select tabindex="3" name="Currency" onchange="ReloadForm(form1.BatchInput)">';
859
860if (!isset($_SESSION['ReceiptBatch' . $identifier]->Currency)){
861  $_SESSION['ReceiptBatch' . $identifier]->Currency=$_SESSION['CompanyRecord']['currencydefault'];
862}
863
864$SQL = "SELECT currency, currabrev, rate FROM currencies";
865$result=DB_query($SQL);
866if (DB_num_rows($result)==0){
867	echo '</select></td></tr>';
868	prnMsg(_('No currencies are defined yet') . '. ' . _('Receipts cannot be entered until a currency is defined'),'warn');
869
870} else {
871	include('includes/CurrenciesArray.php'); // To get the currency name from the currency code.
872	while ($myrow=DB_fetch_array($result)){
873		if ($_SESSION['ReceiptBatch' . $identifier]->Currency==$myrow['currabrev']){
874			echo '<option selected="selected" value="' . $myrow['currabrev'] . '">' . $CurrencyName[$myrow['currabrev']] . '</option>';
875		} else {
876			echo '<option value="' . $myrow['currabrev'] . '">' . $CurrencyName[$myrow['currabrev']] . '</option>';
877		}
878	}
879	echo '</select></td>
880		</tr>';
881}
882
883
884if (!isset($_SESSION['ReceiptBatch' . $identifier]->ExRate)){
885	$_SESSION['ReceiptBatch' . $identifier]->ExRate=1;
886}
887
888if (!isset($_SESSION['ReceiptBatch' . $identifier]->FunctionalExRate)){
889	$_SESSION['ReceiptBatch' . $identifier]->FunctionalExRate=1;
890}
891if ($_SESSION['ReceiptBatch' . $identifier]->AccountCurrency != $_SESSION['ReceiptBatch' . $identifier]->Currency AND isset($_SESSION['ReceiptBatch' . $identifier]->AccountCurrency)) {
892	if($_SESSION['ReceiptBatch' . $identifier]->ExRate==1 AND isset($SuggestedExRate)) {
893		$_SESSION['ReceiptBatch' . $identifier]->ExRate = $SuggestedExRate;
894	} elseif($_POST['Currency'] != $_POST['PreviousCurrency'] AND isset($SuggestedExRate)) {//the user has changed the currency, then we should revise suggested rate
895		$_SESSION['ReceiptBatch' . $identifier]->ExRate = $SuggestedExRate;
896	}
897
898	if(isset($SuggestedExRate)) {
899		$SuggestedExRateText = '<b>' . _('Suggested rate:') . ' 1 ' . $_SESSION['ReceiptBatch' . $identifier]->AccountCurrency . ' = ' . locale_number_format($SuggestedExRate,8) . ' ' . $_SESSION['ReceiptBatch']->Currency . '</b>';
900	} else {
901		$SuggestedExRateText = '<b>1 ' . $_SESSION['ReceiptBatch' . $identifier]->AccountCurrency . ' = ? ' . $_SESSION['ReceiptBatch' . $identifier]->Currency . '</b>';
902	}
903	echo '<tr>
904			<td>', _('Receipt Exchange Rate'), ':</td>
905			<td><input class="number" maxlength="12" name="ExRate" required="required" size="14" tabindex="4" type="text" value="', locale_number_format($_SESSION['ReceiptBatch' . $identifier]->ExRate,8), '" /> ', $SuggestedExRateText, ' <i>', _('The exchange rate between the currency of the bank account currency and the currency of the receipt'), '.</i></td>
906		</tr>';
907}
908
909if($_SESSION['ReceiptBatch' . $identifier]->AccountCurrency != $_SESSION['CompanyRecord']['currencydefault'] AND isset($_SESSION['ReceiptBatch' . $identifier]->AccountCurrency)) {
910
911	if($_SESSION['ReceiptBatch' . $identifier]->FunctionalExRate==1 AND isset($SuggestedFunctionalExRate)) {
912		$_SESSION['ReceiptBatch' . $identifier]->FunctionalExRate = $SuggestedFunctionalExRate;
913	}
914	if(isset($SuggestedFunctionalExRate)) {
915		$SuggestedFunctionalExRateText = '<b>' . _('Suggested rate:') . ' 1 ' . $_SESSION['CompanyRecord']['currencydefault'] . ' = ' . locale_number_format($SuggestedFunctionalExRate,8) . ' ' . $_SESSION['ReceiptBatch' . $identifier]->AccountCurrency . '</b>';
916	} else {
917		$SuggestedFunctionalExRateText = '<b>1 ' . $_SESSION['CompanyRecord']['currencydefault'] . ' = ? ' . $_SESSION['ReceiptBatch']->AccountCurrency . '</b>';
918	}
919	echo '<tr>
920			<td>', _('Functional Exchange Rate'), ':</td>
921			<td><input class="number" maxlength="12" name="FunctionalExRate" pattern="[0-9\.,]*" required="required" size="14" tabindex="5" type="text" value="', $_SESSION['ReceiptBatch' . $identifier]->FunctionalExRate, '" /> ', $SuggestedFunctionalExRateText, ' <i>', _('The exchange rate between the currency of the business (the functional currency) and the currency of the bank account'),  '.</i></td>
922		</tr>';
923}
924
925echo '<tr>
926		<td>' . _('Receipt Type') . ':</td>
927		<td><select name="ReceiptType" tabindex="6" onchange="ReloadForm(form1.BatchInput)">';
928
929/* The array ReceiptTypes is defined from the setup tab of the main menu under
930payment methods - the array is populated from the include file GetPaymentMethods.php */
931
932foreach ($ReceiptTypes as $RcptType) {
933	if (isset($_POST['ReceiptType']) AND $_POST['ReceiptType']==$RcptType['paymentid']){
934		echo '<option selected="selected" value="' . $RcptType['paymentid'] . '">' . $RcptType['paymentname']  . '</option>';
935	} else {
936		echo '<option value="' . $RcptType['paymentid'] . '">' . $RcptType['paymentname']  . '</option>';
937	}
938}
939echo '</select></td>
940	</tr>';
941
942/* Receipt (Bank Account) info to be inserted on banktrans.ref, varchar(50). */
943if (!isset($_SESSION['ReceiptBatch' . $identifier]->BankTransRef)) {
944	$_SESSION['ReceiptBatch' . $identifier]->BankTransRef='';
945}
946echo '<tr>
947		<td>', _('Reference'), ':</td>
948		<td><input maxlength="50" name="BankTransRef" size="52" tabindex="7" type="text" value="', $_SESSION['ReceiptBatch' . $identifier]->BankTransRef,'" /> <i>', _('Reference on Bank Transactions Inquiry'), '.</i></td>
949	</tr>';
950
951/* Receipt (Bank Account) info to be inserted on gltrans.narrative, varchar(200). */
952if (!isset($_SESSION['ReceiptBatch' . $identifier]->Narrative)) {
953	$_SESSION['ReceiptBatch' . $identifier]->Narrative='';
954}
955if (!isset($_POST['Currency'])){
956	$_POST['Currency'] = $_SESSION['CompanyRecord']['currencydefault'];
957}
958echo '<tr>
959		<td>', _('Narrative'), ':</td>
960		<td><input maxlength="200" name="BatchNarrative" size="52" tabindex="8" type="text" value="', $_SESSION['ReceiptBatch' . $identifier]->Narrative, '" /> <i>', _('Narrative on General Ledger Account Inquiry'), '.</i></td>
961	</tr>
962	<input name="PreviousCurrency" type="hidden" value="', $_POST['Currency'], '" />
963	<tr>
964		<td colspan="3">
965		<div class="centre">
966			<input name="BatchInput" tabindex="9" type="submit" value="', _('Accept'), '" />
967		</div>
968		</td>
969	</tr>
970	</table>
971	<br />';
972
973if (isset($_SESSION['ReceiptBatch' . $identifier])){
974	/* Now show the entries made so far */
975	if (!$BankAccountEmpty) {
976		if (!isset($ReceiptTypes[$_SESSION['ReceiptBatch' . $identifier]->ReceiptType]['paymentname'])) {
977			$PaymentTypeString = '';
978		} else {
979			$PaymentTypeString = $ReceiptTypes[$_SESSION['ReceiptBatch' . $identifier]->ReceiptType]['paymentname'];
980
981		}
982		echo '<p class="page_title_text"><img src="'.$RootPath.'/css/'.$Theme.'/images/transactions.png" title="' . _('Banked') . '" alt="" />
983             ' . ' ' . $PaymentTypeString . ' - ' . _('Banked into the') . " " .
984				$_SESSION['ReceiptBatch' . $identifier]->BankAccountName . ' ' . _('on') . ' ' . $_SESSION['ReceiptBatch' . $identifier]->DateBanked . '</p>';
985	}
986
987	echo '<table width="90%" class="selection">
988		<tr>
989			<th>' . _('Amount') . ' ' . _('Received') . '</th>
990			<th>' . _('Discount') . '</th>
991			<th>' . _('Customer') . '</th>
992			<th>' . _('GL Code') . '</th>
993			<th>' . _('Narrative') . '</th>
994			<th>' . _('Tag') . '</th>
995		</tr>';
996
997	$BatchTotal = 0;
998
999	foreach ($_SESSION['ReceiptBatch' . $identifier]->Items as $ReceiptItem) {
1000
1001		$SQL = "SELECT accountname FROM chartmaster WHERE accountcode='" . $ReceiptItem->GLCode . "'";
1002		$Result=DB_query($SQL);
1003		$myrow=DB_fetch_array($Result);
1004
1005		echo '<tr>
1006				<td class="number">' . locale_number_format($ReceiptItem->Amount,$_SESSION['ReceiptBatch' . $identifier]->CurrDecimalPlaces) . '</td>
1007				<td class="number">' . locale_number_format($ReceiptItem->Discount,$_SESSION['ReceiptBatch' . $identifier]->CurrDecimalPlaces) . '</td>
1008				<td>' . stripslashes($ReceiptItem->CustomerName) . '</td>
1009				<td>' . $ReceiptItem->GLCode.' - '.$myrow['accountname'] . '</td>
1010				<td>' .  stripslashes($ReceiptItem->Narrative) . '</td>
1011				<td>' .  $ReceiptItem->TagName . '</td>
1012				<td><a href="' . htmlspecialchars($_SERVER['PHP_SELF'],ENT_QUOTES,'UTF-8') . '?Delete='     . urlencode($ReceiptItem->ID)
1013                                                                                           . '&Type='       . urlencode($_GET['Type'])
1014                                                                                           . '&identifier=' . urlencode($identifier) . '">'
1015                                                                                           . _('Delete') . '</a></td>
1016			</tr>';
1017		$BatchTotal= $BatchTotal + $ReceiptItem->Amount;
1018	}
1019
1020	echo '<tr>
1021			<td class="number"><b>' . locale_number_format($BatchTotal,$_SESSION['ReceiptBatch' . $identifier]->CurrDecimalPlaces) . '</b></td>
1022		</tr>
1023		</table>';
1024}
1025
1026/*this next block of ifs deals with what information to display for input into the form
1027the info depends on where the user is up to ie the first stage is to select a bank
1028account, currency being banked and a batch number - or start a new batch by leaving the batch no blank
1029and a date for the banking. The second stage is to select a customer or GL account.
1030Finally enter the amount */
1031
1032
1033/*if a customer has been selected (and a receipt batch is underway)
1034then set out the customers account summary */
1035
1036
1037if (isset($_SESSION['CustomerRecord' . $identifier])
1038		AND $_SESSION['CustomerRecord' . $identifier]['currcode'] != $_SESSION['ReceiptBatch' . $identifier]->Currency){
1039	prnMsg(_('The selected customer does not trade in the currency of the receipt being entered - either the currency of the receipt needs to be changed or a different customer selected'),'warn');
1040	unset($_SESSION['CustomerRecord' . $identifier]);
1041}
1042
1043
1044if (isset($_SESSION['CustomerRecord' . $identifier])
1045		AND isset($_POST['CustomerID'])
1046		AND $_POST['CustomerID']!=''
1047		AND isset($_SESSION['ReceiptBatch' . $identifier])){
1048/*a customer is selected  */
1049
1050	echo '<p class="page_title_text"><img src="'.$RootPath.'/css/'.$Theme.'/images/customer.png" title="' . _('Customer') . '" alt="" />' . ' ' . $_SESSION['CustomerRecord' . $identifier]['name'] . ' - (' . _('All amounts stated in') . ' ' . $_SESSION['CustomerRecord' . $identifier]['currency'] . ')' . _('Terms') . ': ' . $_SESSION['CustomerRecord' . $identifier]['terms'] . '<br/>' . _('Credit Limit') . ': ' . locale_number_format($_SESSION['CustomerRecord'.$identifier]['creditlimit'],0) . '  ' . _('Credit Status') . ': ' . $_SESSION['CustomerRecord'.$identifier]['reasondescription'];
1051
1052	if ($_SESSION['CustomerRecord' . $identifier]['dissallowinvoices']!=0){
1053	   echo '<br />
1054			<font color="red" size="4"><b>' . _('ACCOUNT ON HOLD') . '</font></b>
1055			<br/>';
1056	}
1057
1058	echo '<table width="90%" class="selection">
1059			<tr>
1060				<th width="20%">' . _('Total Balance') . '</th>
1061				<th width="20%">' . _('Current') . '</th>
1062				<th width="20%">' . _('Now Due') . '</th>
1063				<th width="20%">' . $_SESSION['PastDueDays1'] . '-' . $_SESSION['PastDueDays2'] . ' ' . _('Days Overdue') . '</th>
1064				<th width="20%">' . _('Over') . ' ' . $_SESSION['PastDueDays2'] . ' ' . _('Days Overdue') . '</th>
1065				<th width="20%">' . _('Customer Transaction Inquiry') . '</th>
1066			</tr>';
1067
1068	echo '<tr>
1069		<td class="number">' . locale_number_format($_SESSION['CustomerRecord' . $identifier]['balance'],$_SESSION['CustomerRecord' . $identifier]['currdecimalplaces']) . '</td>
1070		<td class="number">' . locale_number_format(($_SESSION['CustomerRecord' . $identifier]['balance'] - $_SESSION['CustomerRecord' . $identifier]['due']),$_SESSION['CustomerRecord' . $identifier]['currdecimalplaces']) . '</td>
1071		<td class="number">' . locale_number_format(($_SESSION['CustomerRecord' . $identifier]['due']-$_SESSION['CustomerRecord' . $identifier]['overdue1']),$_SESSION['CustomerRecord' . $identifier]['currdecimalplaces']) . '</td>
1072		<td class="number">' . locale_number_format(($_SESSION['CustomerRecord' . $identifier]['overdue1']-$_SESSION['CustomerRecord' . $identifier]['overdue2']) ,$_SESSION['CustomerRecord' . $identifier]['currdecimalplaces']) . '</td>
1073		<td class="number">' . locale_number_format($_SESSION['CustomerRecord' . $identifier]['overdue2'],$_SESSION['CustomerRecord' . $identifier]['currdecimalplaces']) . '</td>
1074		<td><a href="CustomerInquiry.php?CustomerID=' . $_POST['CustomerID'] . '&Status=0" target="_blank">' . _('Inquiry') . '</td>
1075		</tr>
1076		</table>
1077		<br />';
1078
1079	echo '<table class="selection">';
1080
1081	if ($_SESSION['CustomerRecord' . $identifier]['pymtdiscount'] > $ReceiptTypes[$_SESSION['ReceiptBatch' . $identifier]->ReceiptType]['percentdiscount']) {
1082		$DisplayDiscountPercent = locale_number_format($_SESSION['CustomerRecord' . $identifier]['pymtdiscount']*100,2) . '%';
1083	} else {
1084		$DisplayDiscountPercent = locale_number_format($ReceiptTypes[$_SESSION['ReceiptBatch' . $identifier]->ReceiptType]['percentdiscount']*100,2) . '%';
1085	}
1086
1087	echo '<input type="hidden" name="CustomerID" value="' . $_POST['CustomerID'] . '" />';
1088	echo '<input type="hidden" name="CustomerName" value="' . $_SESSION['CustomerRecord' . $identifier]['name'] . '" />';
1089
1090}
1091
1092if (isset($_POST['GLEntry']) AND isset($_SESSION['ReceiptBatch' . $identifier])){
1093	/* Set up a heading for the transaction entry for a GL Receipt */
1094	echo '<br />
1095		<table class="selection">
1096			<tr>
1097				<th colspan="2">' . _('General Ledger Receipt Entry') . '</th>
1098			</tr>';
1099
1100	//Select the tag
1101	echo '<tr>
1102			<td>' . _('Select Tag') . ':</td>
1103			<td><select name="tag">';
1104
1105	$SQL = "SELECT tagref,
1106					tagdescription
1107					FROM tags
1108					ORDER BY tagref";
1109
1110	$result=DB_query($SQL);
1111	echo '<option value="0"></option>';
1112	while ($myrow=DB_fetch_array($result)){
1113		if (isset($_POST['tag']) AND $_POST['tag']==$myrow['tagref']){
1114			echo '<option selected="selected" value="' . $myrow['tagref'] . '">' . $myrow['tagref'].' - ' .$myrow['tagdescription'] . '</option>';
1115		} else {
1116			echo '<option value="' . $myrow['tagref'] . '">' . $myrow['tagref'].' - ' .$myrow['tagdescription'] . '</option>';
1117		}
1118	}
1119	echo '</select></td>
1120		</tr>';
1121// End select tag
1122
1123	/*now set up a GLCode field to select from avaialble GL accounts */
1124	echo '<tr>
1125			<td>' . _('GL Account') . ':</td>
1126			<td><select tabindex="8" name="GLCode">';
1127
1128	$SQL = "SELECT chartmaster.accountcode,
1129					chartmaster.accountname
1130			FROM chartmaster
1131				INNER JOIN glaccountusers ON glaccountusers.accountcode=chartmaster.accountcode AND glaccountusers.userid='" .  $_SESSION['UserID'] . "' AND glaccountusers.canupd=1
1132			ORDER BY chartmaster.accountcode";
1133	$result=DB_query($SQL);
1134	if (DB_num_rows($result)==0){
1135		echo '</select>' . _('No General ledger accounts have been set up yet') . ' - ' . _('receipts cannot be entered against GL accounts until the GL accounts are set up') . '</td>
1136			</tr>';
1137	} else {
1138		echo '<option value=""></option>';
1139		while ($myrow=DB_fetch_array($result)){
1140			if ($_POST['GLCode']==$myrow['accountcode']){
1141				echo '<option selected="selected" value="' . $myrow['accountcode'] . '">' . $myrow['accountcode'] . ' - ' . $myrow['accountname'] . '</option>';
1142			} else {
1143			echo '<option value="' . $myrow['accountcode'] . '">' . $myrow['accountcode'] . ' - ' . $myrow['accountname'] . '</option>';
1144			}
1145		}
1146		echo '</select></td>
1147			</tr>';
1148	}
1149}
1150
1151
1152
1153
1154
1155/*if either a customer is selected or its a GL Entry then set out
1156the fields for entry of receipt amt, disc, payee details, narrative */
1157
1158if (((isset($_SESSION['CustomerRecord' . $identifier])
1159		AND isset($_POST['CustomerID'])
1160		AND $_POST['CustomerID']!='')
1161			OR isset($_POST['GLEntry']))
1162		AND isset($_SESSION['ReceiptBatch' . $identifier])){
1163
1164	if (!isset($_POST['Amount'])) {
1165		$_POST['Amount']=0;
1166	}
1167	if (!isset($_POST['Discount'])) {
1168		$_POST['Discount']=0;
1169	}
1170	if (!isset($_POST['PayeeBankDetail'])) {
1171		$_POST['PayeeBankDetail']='';
1172	}
1173	if (!isset($_POST['Narrative'])) {
1174		$_POST['Narrative']='';
1175	}
1176	echo '<tr>
1177			<td>' . _('Amount of Receipt') . ':</td>
1178			<td><input tabindex="9" type="text" name="Amount" required="required" maxlength="12" size="13" class="number" value="' . $_POST['Amount'] . '" /></td>
1179		</tr>';
1180
1181	if (!isset($_POST['GLEntry'])){
1182		echo '<tr>
1183				<td>' . _('Amount of Discount') . ':</td>
1184				<td><input tabindex="10" type="text" name="Discount" maxlength="12" size="13" class="number" value="' . $_POST['Discount'] . '" /> ' . _('agreed prompt payment discount is') . ' ' . $DisplayDiscountPercent . '</td>
1185			</tr>';
1186	} else {
1187		echo '<input tabindex="11" type="hidden" name="Discount" value="0" />';
1188	}
1189
1190	echo '<tr>
1191			<td>' . _('Payee Bank Details') . ':</td>
1192			<td><input tabindex="12" type="text" name="PayeeBankDetail" maxlength="22" size="20" value="' . $_POST['PayeeBankDetail'] . '" /></td>
1193		</tr>
1194		<tr>
1195			<td>' . _('Narrative') . ':</td>
1196			<td><textarea name="Narrative"  cols="40" rows="1"></textarea></td>
1197		</tr>
1198		</table>
1199		<br />
1200		<div class="centre">
1201			<input tabindex="14" type="submit" name="Process" value="' . _('Accept') . '" />
1202			<input tabindex="15" type="submit" name="Cancel" value="' . _('Cancel') . '" />
1203		</div>';
1204
1205} elseif (isset($_SESSION['ReceiptBatch' . $identifier])
1206			AND !isset($_POST['GLEntry'])){
1207
1208	/*Show the form to select a customer */
1209	echo '<br />';
1210
1211	echo '<p class="page_title_text">
1212			<img src="'.$RootPath.'/css/'.$Theme.'/images/customer.png" title="' . _('Customer') . '" alt="" />' . ' ' . _('Select a Customer') . '</p>
1213		<table class="selection">
1214		<tr>
1215			<td>' . _('Text in the Customer') . ' ' . '<b>' . _('name') . '</b>:</td>
1216			<td><input tabindex="9" type="text" name="Keywords" size="15" maxlength="25" /></td>
1217			<td><b>' . _('OR') . '</b></td>
1218			<td>' . _('Text extract in the Customer') . ' ' . '<b>' . _('code') . '</b>:</td>
1219			<td><input tabindex="10" type="text" name="CustCode" data-type="no-illegal-chars" title="' . _('Enter an extract of the customer code to search for. Customer codes can contain any alpha-numeric character or underscore') . '" size="10" maxlength="18" /></td>
1220			<td><b>' . _('OR') . '</b></td>
1221			<td>' . _('Customer invoice number') . ':</td>
1222			<td><input tabindex="11" type="text" name="CustInvNo" class="integer" size="8" maxlength="8" /></td>
1223		</tr>
1224		</table>
1225		<div class="centre">
1226			<br />
1227			<input tabindex="11" type="submit" name="Search" value="' . _('Search Now') . '" />
1228			<br/>
1229			<br/>
1230			<input tabindex="12" type="submit" name="GLEntry" value="' . _('Enter A GL Receipt') . '" />
1231			<br />
1232		</div>';
1233
1234	if (isset($CustomerSearchResult)) {
1235
1236		echo '<table class="selection">';
1237		$TableHeader = '<tr>
1238							<th>' . _('Code') . '</th>
1239							<th>' . _('Customer Name') . '</th>
1240						</tr>';
1241		echo $TableHeader;
1242		$j = 1;
1243
1244		while ($myrow=DB_fetch_array($CustomerSearchResult)) {
1245
1246			printf('<tr class="striped_row">
1247					<td><input tabindex="'. strval(12+$j).'" type="submit" name="Select" value="%s" /></td>
1248					<td>%s</td>
1249					</tr>',
1250					$myrow['debtorno'],
1251					$myrow['name']);
1252
1253			$j++;
1254			If ($j == 11){
1255				$j=1;
1256				echo $TableHeader;
1257
1258			}
1259	//end of page full new headings if
1260		}
1261	//end of while loop
1262
1263		echo '</table>';
1264
1265	}	//end if results to show
1266
1267}
1268if (isset($_SESSION['ReceiptBatch' . $identifier]->Items) AND count($_SESSION['ReceiptBatch' . $identifier]->Items) > 0){
1269	echo '<div class="centre">
1270			<br/>
1271			<input tabindex="13" type="submit" name="CommitBatch" value="' . _('Accept and Process Batch') . '" />
1272		</div>';
1273}
1274echo '</div>';
1275echo '</form>';
1276include('includes/footer.php');
1277?>
1278