1<?php
2
3
4/*The credit selection screen uses the Cart class used for the making up orders
5some of the variable names refer to order - please think credit when you read order */
6
7include('includes/DefineCartClass.php');
8include('includes/DefineSerialItems.php');
9/* Session started in session.php for password checking and authorisation level check */
10include('includes/session.php');
11
12$Title = _('Create Credit Note');
13$ViewTopic= 'ARTransactions';
14$BookMark = 'CreateCreditNote';
15
16include('includes/header.php');
17include('includes/SQL_CommonFunctions.inc');
18include('includes/GetSalesTransGLCodes.inc');
19include('includes/GetPrice.inc');
20
21
22if (empty($_GET['identifier'])) {
23	/*unique session identifier to ensure that there is no conflict with other order entry sessions on the same machine  */
24	$identifier=date('U');
25} else {
26	$identifier=$_GET['identifier'];
27}
28
29if (isset($_POST['ProcessCredit']) AND !isset($_SESSION['CreditItems'.$identifier])){
30	prnMsg(_('This credit note has already been processed. Refreshing the page will not enter the credit note again') . '<br />' . _('Please use the navigation links provided rather than using the browser back button and then having to refresh'),'info');
31	echo '<br /><a href="' . $RootPath . '/index.php">' . _('Back to the menu') . '</a>';
32	include('includes/footer.php');
33  exit;
34}
35
36if (isset($_GET['NewCredit'])){
37/*New credit note entry - clear any existing credit note details from the Items object and initiate a newy*/
38	if (isset($_SESSION['CreditItems'.$identifier])){
39		unset ($_SESSION['CreditItems'.$identifier]->LineItems);
40		unset ($_SESSION['CreditItems'.$identifier]);
41	}
42}
43
44
45if (!isset($_SESSION['CreditItems'.$identifier])){
46	 /* It must be a new credit note being created $_SESSION['CreditItems'.$identifier] would be set up from a previous call*/
47
48	$_SESSION['CreditItems'.$identifier] = new cart;
49
50	$_SESSION['RequireCustomerSelection'] = 1;
51}
52
53if (isset($_POST['ChangeCustomer'])){
54	$_SESSION['RequireCustomerSelection']=1;
55}
56
57if (isset($_POST['Quick'])){
58	unset($_POST['PartSearch']);
59}
60
61if (isset($_POST['CancelCredit'])) {
62	unset($_SESSION['CreditItems'.$identifier]->LineItems);
63	unset($_SESSION['CreditItems'.$identifier]);
64	$_SESSION['CreditItems'.$identifier] = new cart;
65	$_SESSION['RequireCustomerSelection'] = 1;
66}
67
68
69if (isset($_POST['SearchCust']) AND $_SESSION['RequireCustomerSelection']==1){
70
71	if ($_POST['Keywords'] AND $_POST['CustCode']) {
72		  prnMsg( _('Customer name keywords have been used in preference to the customer code extract entered'), 'info' );
73	}
74	if ($_POST['Keywords']=='' AND $_POST['CustCode']=='') {
75		  prnMsg( _('At least one Customer Name keyword OR an extract of a Customer Code must be entered for the search'), 'info' );
76	} else {
77		if (mb_strlen($_POST['Keywords'])>0) {
78		  //insert wildcard characters in spaces
79			$SearchString = '%' . str_replace(' ', '%', $_POST['Keywords']) . '%';
80
81			   $SQL = "SELECT	debtorsmaster.name,
82								custbranch.debtorno,
83								custbranch.brname,
84								custbranch.contactname,
85								custbranch.phoneno,
86								custbranch.faxno,
87								custbranch.branchcode
88							FROM custbranch
89							INNER JOIN debtorsmaster
90							ON custbranch.debtorno=debtorsmaster.debtorno
91							WHERE custbranch.brname " . LIKE  . " '" . $SearchString . "'
92							AND custbranch.disabletrans='0'";
93
94		  } elseif (mb_strlen($_POST['CustCode'])>0){
95
96			   $SQL = "SELECT 	debtorsmaster.name,
97								custbranch.debtorno,
98								custbranch.brname,
99								custbranch.contactname,
100								custbranch.phoneno,
101								custbranch.faxno,
102								custbranch.branchcode
103							FROM custbranch
104							INNER JOIN debtorsmaster
105							ON custbranch.debtorno=debtorsmaster.debtorno
106							WHERE custbranch.debtorno " . LIKE  . "'%" . $_POST['CustCode'] . "%'
107							AND custbranch.disabletrans='0'";
108		  }
109
110		  $ErrMsg = _('Customer branch records requested cannot be retrieved because');
111		  $DbgMsg = _('SQL used to retrieve the customer details was');
112		  $result_CustSelect = DB_query($SQL,$ErrMsg,$DbgMsg);
113
114
115		  if (DB_num_rows($result_CustSelect)==1){
116			    $myrow=DB_fetch_array($result_CustSelect);
117			    $SelectedCustomer = trim($myrow['debtorno']);
118			    $SelectedBranch = trim($myrow['branchcode']);
119			    $_POST['JustSelectedACustomer'] = true;
120		  } elseif (DB_num_rows($result_CustSelect)==0){
121			    prnMsg(_('Sorry') . ' ... ' . _('there are no customer branch records contain the selected text') . ' - ' . _('please alter your search criteria and try again'),'info');
122		  }
123
124	 } /*one of keywords or custcode was more than a zero length string */
125} /*end of if search button for customers was hit*/
126
127
128if (isset($_POST['JustSelectedACustomer']) AND !isset($SelectedCustomer)){
129	/*Need to figure out the number of the form variable that the user clicked on */
130	for ($i=1; $i < count($_POST); $i++){ //loop through the returned customers
131		if(isset($_POST['SubmitCustomerSelection'.$i])){
132			break;
133		}
134	}
135	if ($i==count($_POST)){
136		prnMsg(_('Unable to identify the selected customer'),'error');
137	} else {
138		$SelectedCustomer = trim($_POST['SelectedCustomer'.$i]);
139		$SelectedBranch = trim($_POST['SelectedBranch'.$i]);
140	}
141}
142
143
144if (isset($SelectedCustomer) AND isset($_POST['JustSelectedACustomer'])) {
145
146/*will only be true if page called from customer selection form
147  Now retrieve customer information - name, salestype, currency, terms etc
148*/
149
150	$_SESSION['CreditItems'.$identifier]->DebtorNo = $SelectedCustomer;
151	$_SESSION['CreditItems'.$identifier]->Branch = $SelectedBranch;
152	$_SESSION['RequireCustomerSelection'] = 0;
153
154/*  default the branch information from the customer branches table CustBranch -particularly where the stock
155will be booked back into. */
156
157	 $sql = "SELECT debtorsmaster.name,
158					debtorsmaster.salestype,
159					debtorsmaster.currcode,
160					currencies.rate,
161					currencies.decimalplaces,
162					custbranch.brname,
163					custbranch.braddress1,
164					custbranch.braddress2,
165					custbranch.braddress3,
166					custbranch.braddress4,
167					custbranch.braddress5,
168					custbranch.braddress6,
169					custbranch.phoneno,
170					custbranch.email,
171					custbranch.salesman,
172					custbranch.defaultlocation,
173					custbranch.taxgroupid,
174					locations.taxprovinceid
175				FROM custbranch
176				INNER JOIN locations ON locations.loccode=custbranch.defaultlocation
177				INNER JOIN debtorsmaster ON custbranch.debtorno=debtorsmaster.debtorno
178				INNER JOIN currencies ON debtorsmaster.currcode=currencies.currabrev
179				WHERE custbranch.branchcode='" . $_SESSION['CreditItems'.$identifier]->Branch . "'
180				AND custbranch.debtorno = '" . $_SESSION['CreditItems'.$identifier]->DebtorNo . "'";
181
182	$ErrMsg = _('The customer branch record of the customer selected') . ': ' . $SelectedCustomer . ' ' . _('cannot be retrieved because');
183	$DbgMsg =  _('SQL used to retrieve the branch details was');
184	$result =DB_query($sql,$ErrMsg,$DbgMsg);
185
186	$myrow = DB_fetch_array($result);
187
188/* the sales type determines the price list to be used by default the customer of the user is
189defaulted from the entry of the userid and password.  */
190	$_SESSION['CreditItems'.$identifier]->CustomerName = $myrow['name'];
191	$_SESSION['CreditItems'.$identifier]->DefaultSalesType = $myrow['salestype'];
192	$_SESSION['CreditItems'.$identifier]->DefaultCurrency = $myrow['currcode'];
193	$_SESSION['CreditItems'.$identifier]->CurrDecimalPlaces = $myrow['decimalplaces'];
194	$_SESSION['CurrencyRate'] = $myrow['rate'];
195	$_SESSION['CreditItems'.$identifier]->DeliverTo = $myrow['brname'];
196	$_SESSION['CreditItems'.$identifier]->BrAdd1 = $myrow['braddress1'];
197	$_SESSION['CreditItems'.$identifier]->BrAdd2 = $myrow['braddress2'];
198	$_SESSION['CreditItems'.$identifier]->BrAdd3 = $myrow['braddress3'];
199	$_SESSION['CreditItems'.$identifier]->BrAdd4 = $myrow['braddress4'];
200	$_SESSION['CreditItems'.$identifier]->BrAdd5 = $myrow['braddress5'];
201	$_SESSION['CreditItems'.$identifier]->BrAdd6 = $myrow['braddress6'];
202	$_SESSION['CreditItems'.$identifier]->PhoneNo = $myrow['phoneno'];
203	$_SESSION['CreditItems'.$identifier]->Email = $myrow['email'];
204	$_SESSION['CreditItems'.$identifier]->SalesPerson = $myrow['salesman'];
205	$_SESSION['CreditItems'.$identifier]->Location = $myrow['defaultlocation'];
206	$_SESSION['CreditItems'.$identifier]->TaxGroup = $myrow['taxgroupid'];
207	$_SESSION['CreditItems'.$identifier]->DispatchTaxProvince = $myrow['taxprovinceid'];
208	$_SESSION['CreditItems'.$identifier]->GetFreightTaxes();
209}
210
211/* if the change customer button hit or the customer has not already been selected */
212if ($_SESSION['RequireCustomerSelection'] ==1
213	OR !isset($_SESSION['CreditItems'.$identifier]->DebtorNo)
214	OR $_SESSION['CreditItems'.$identifier]->DebtorNo=='' ) {
215
216	echo '<form action="' . htmlspecialchars($_SERVER['PHP_SELF'], ENT_QUOTES, 'UTF-8') . '?identifier=' . urlencode($identifier) . '" method="post">';
217    echo '<div>';
218	echo '<input type="hidden" name="FormID" value="' . $_SESSION['FormID'] . '" />';
219	echo '<p class="page_title_text"><img src="' . $RootPath . '/css/' . $Theme . '/images/magnifier.png" title="' .
220		_('Search') . '" alt="" />' . ' ' . _('Select Customer For Credit Note') . '</p>';
221
222	echo '<table cellpadding="3" class="selection">';
223	echo '<tr><th colspan="5"><h3> ' . _('Customer Selection')  . '</h3></th></tr>';
224	echo '<tr>
225			<td>' . _('Enter text in the customer name') . ':</td>
226			<td><input type="text" name="Keywords" size="20" maxlength="25" /></td>
227			<td><b>' . _('OR') . '</b></td>
228			<td>' . _('Enter text extract in the customer code') . ':</td>
229			<td><input type="text" name="CustCode" size="15" maxlength="18" /></td>
230		</tr>';
231	echo '</table>
232		<br />
233		<div class="centre">
234			<input type="submit" name="SearchCust" value="' . _('Search Now') . '" />
235		</div>';
236
237	if (isset($result_CustSelect)) {
238
239		echo '<br /><table cellpadding="2">';
240
241		$TableHeader = '<tr>
242						<th>' . _('Customer') . '</th>
243						<th>' . _('Branch') . '</th>
244						<th>' . _('Contact') . '</th>
245						<th>' . _('Phone') . '</th>
246						<th>' . _('Fax') . '</th>
247					</tr>';
248		echo $TableHeader;
249
250		$j = 1;
251		$LastCustomer='';
252		while ($myrow=DB_fetch_array($result_CustSelect)) {
253
254			if ($LastCustomer != $myrow['name']) {
255				echo '<td>' . $myrow['name'] . '</td>';
256			} else {
257				echo '<td></td>';
258			}
259			echo '<tr class="striped_row">
260				<td><input tabindex="'.($j+5).'" type="submit" name="SubmitCustomerSelection' . $j .'" value="' . htmlspecialchars($myrow['brname'], ENT_QUOTES,'UTF-8'). '" />
261				<input type="hidden" name="SelectedCustomer' . $j .'" value="'.$myrow['debtorno'].'" />
262				<input type="hidden" name="SelectedBranch' . $j .'" value="'. $myrow['branchcode'].'" /></td>
263				<td>' . $myrow['contactname'] . '</td>
264				<td>' . $myrow['phoneno'] . '</td>
265				<td>' . $myrow['faxno'] . '</td>
266				</tr>';
267			$LastCustomer=$myrow['name'];
268			$j++;
269		//end of page full new headings if
270		} //end of while loop
271		echo '</table><input type="hidden" name="JustSelectedACustomer" value="Yes" />';
272	}//end if results to show
273    echo '</div>
274          </form>';
275
276
277//end if RequireCustomerSelection
278} else {
279/* everything below here only do if a customer is selected
280   first add a header to show who we are making a credit note for */
281
282	echo '<p class="page_title_text"><img src="' . $RootPath . '/css/' . $Theme . '/images/magnifier.png" title="' .
283		_('Search') . '" alt="" />' . ' ' . $_SESSION['CreditItems'.$identifier]->CustomerName  . ' - ' . $_SESSION['CreditItems'.$identifier]->DeliverTo . '</p>';
284
285	if (isset($_POST['SalesPerson'])){
286		$_SESSION['CreditItems' . $identifier]->SalesPerson = $_POST['SalesPerson'];
287	}
288
289 /* do the search for parts that might be being looked up to add to the credit note */
290	 if (isset($_POST['Search'])){
291
292		  if ($_POST['Keywords']!='' AND $_POST['StockCode']!='') {
293			   prnMsg( _('Stock description keywords have been used in preference to the Stock code extract entered') . '.', 'info' );
294		  }
295
296		if ($_POST['Keywords']!='') {
297			//insert wildcard characters in spaces
298			$SearchString = '%' . str_replace(' ', '%', $_POST['Keywords']) . '%';
299
300			if ($_POST['StockCat']=='All'){
301				$SQL = "SELECT stockmaster.stockid,
302						stockmaster.description,
303						stockmaster.units
304					FROM stockmaster INNER JOIN stockcategory
305					ON stockmaster.categoryid=stockcategory.categoryid
306					WHERE (stockcategory.stocktype='F' OR stockcategory.stocktype='D')
307					AND stockmaster.description " . LIKE . " '" . $SearchString . "'
308					GROUP BY stockmaster.stockid,
309						stockmaster.description,
310						stockmaster.units
311					ORDER BY stockmaster.stockid";
312			} else {
313				$SQL = "SELECT stockmaster.stockid,
314						stockmaster.description,
315						stockmaster.units
316					FROM stockmaster INNER JOIN stockcategory
317					ON stockmaster.categoryid=stockcategory.categoryid
318					WHERE (stockcategory.stocktype='F' OR stockcategory.stocktype='D')
319					AND stockmaster.description " . LIKE . " '" . $SearchString . "'
320					AND stockmaster.categoryid='" . $_POST['StockCat'] . "'
321					GROUP BY stockmaster.stockid,
322						stockmaster.description,
323						stockmaster.units
324					ORDER BY stockmaster.stockid";
325			}
326
327		} elseif ($_POST['StockCode']!=''){
328			$SearchString = '%' . $_POST['StockCode'] . '%';
329			if ($_POST['StockCat']=='All'){
330				$SQL = "SELECT stockmaster.stockid,
331						stockmaster.description,
332						stockmaster.units
333					FROM stockmaster INNER JOIN stockcategory
334					ON stockmaster.categoryid=stockcategory.categoryid
335					WHERE (stockcategory.stocktype='F' OR stockcategory.stocktype='D')
336					AND  stockmaster.stockid " . LIKE . " '" . $SearchString . "'
337					GROUP BY stockmaster.stockid,
338						stockmaster.description,
339						stockmaster.units
340					ORDER BY stockmaster.stockid";
341			} else {
342				$SQL = "SELECT stockmaster.stockid,
343						stockmaster.description,
344						stockmaster.units
345						FROM stockmaster INNER JOIN stockcategory
346						ON stockmaster.categoryid=stockcategory.categoryid
347						WHERE (stockcategory.stocktype='F' OR stockcategory.stocktype='D')
348						AND stockmaster.stockid " . LIKE . " '" . $SearchString . "'
349						AND stockmaster.categoryid='" . $_POST['StockCat'] . "'
350						GROUP BY stockmaster.stockid,
351							stockmaster.description,
352							stockmaster.units
353						ORDER BY stockmaster.stockid";
354			}
355		} else {
356			if ($_POST['StockCat']=='All'){
357				$SQL = "SELECT stockmaster.stockid,
358						stockmaster.description,
359						stockmaster.units
360					FROM stockmaster INNER JOIN stockcategory
361					ON stockmaster.categoryid=stockcategory.categoryid
362					WHERE (stockcategory.stocktype='F' OR stockcategory.stocktype='D')
363					GROUP BY stockmaster.stockid,
364						stockmaster.description,
365						stockmaster.units
366					ORDER BY stockmaster.stockid";
367			} else {
368				$SQL = "SELECT stockmaster.stockid,
369						stockmaster.description,
370						stockmaster.units
371					FROM stockmaster INNER JOIN stockcategory
372					ON stockmaster.categoryid=stockcategory.categoryid
373					WHERE (stockcategory.stocktype='F' OR stockcategory.stocktype='D')
374					AND stockmaster.categoryid='" . $_POST['StockCat'] . "'
375					GROUP BY stockmaster.stockid,
376						stockmaster.description,
377						stockmaster.units
378					ORDER BY stockmaster.stockid";
379			  }
380		}
381
382		$ErrMsg = _('There is a problem selecting the part records to display because');
383		$SearchResult = DB_query($SQL,$ErrMsg);
384
385		if (DB_num_rows($SearchResult)==0){
386			   prnMsg(_('There are no products available that match the criteria specified'),'info');
387			   if ($debug==1){
388				    prnMsg(_('The SQL statement used was') . ':<br />' . $SQL,'info');
389			   }
390		}
391		if (DB_num_rows($SearchResult)==1){
392			   $myrow=DB_fetch_array($SearchResult);
393			   $_POST['NewItem'] = $myrow['stockid'];
394			   DB_data_seek($SearchResult,0);
395		}
396
397	 } //end of if search for parts to add to the credit note
398
399/*Always do the stuff below if not looking for a customerid
400  Set up the form for the credit note display and  entry*/
401
402	 echo '<form id="MainForm" action="' . htmlspecialchars($_SERVER['PHP_SELF'], ENT_QUOTES, 'UTF-8') . '?identifier=' . urlencode($identifier) . '" method="post">
403		<div>
404		<input type="hidden" name="FormID" value="' . $_SESSION['FormID'] . '" />';
405
406
407/*Process Quick Entry */
408
409	 if (isset($_POST['QuickEntry'])){
410/* get the item details from the database and hold them in the cart object make the quantity 1 by default then add it to the cart */
411	    $i=1;
412	     do {
413		   do {
414			  $QuickEntryCode = 'part_' . $i;
415			  $QuickEntryQty = 'qty_' . $i;
416			  $i++;
417		   } while (!is_numeric(filter_number_format($_POST[$QuickEntryQty]))
418					AND filter_number_format($_POST[$QuickEntryQty]) <=0
419					AND mb_strlen($_POST[$QuickEntryCode])!=0
420					AND $i<=$QuickEntires);
421
422		   $_POST['NewItem'] = trim($_POST[$QuickEntryCode]);
423		   $NewItemQty = filter_number_format($_POST[$QuickEntryQty]);
424
425		   if (mb_strlen($_POST['NewItem'])==0){
426			     break;	 /* break out of the loop if nothing in the quick entry fields*/
427		   }
428
429		   $AlreadyOnThisCredit =0;
430
431		   foreach ($_SESSION['CreditItems'.$identifier]->LineItems AS $OrderItem) {
432
433		   /* do a loop round the items on the credit note to see that the item
434		   is not already on this credit note */
435
436			    if ($_SESSION['SO_AllowSameItemMultipleTimes']==0 AND strcasecmp($OrderItem->StockID, $_POST['NewItem']) == 0) {
437				     $AlreadyOnThisCredit = 1;
438				     prnMsg($_POST['NewItem'] . ' ' . _('is already on this credit - the system will not allow the same item on the credit note more than once. However you can change the quantity credited of the existing line if necessary'),'warn');
439			    }
440		   } /* end of the foreach loop to look for preexisting items of the same code */
441
442		   if ($AlreadyOnThisCredit!=1){
443
444			    $sql = "SELECT stockmaster.description,
445								stockmaster.longdescription,
446					    		stockmaster.stockid,
447								stockmaster.units,
448								stockmaster.volume,
449								stockmaster.grossweight,
450								(materialcost+labourcost+overheadcost) AS standardcost,
451								stockmaster.mbflag,
452								stockmaster.decimalplaces,
453								stockmaster.controlled,
454								stockmaster.serialised,
455								stockmaster.discountcategory,
456								stockmaster.taxcatid
457							FROM stockmaster
458							WHERE  stockmaster.stockid = '". $_POST['NewItem'] . "'";
459
460				$ErrMsg =  _('There is a problem selecting the part because');
461				$result1 = DB_query($sql,$ErrMsg);
462
463		   		if ($myrow = DB_fetch_array($result1)){
464
465					$LineNumber = $_SESSION['CreditItems'.$identifier]->LineCounter;
466
467					if ($_SESSION['CreditItems'.$identifier]->add_to_cart ($myrow['stockid'],
468																			$NewItemQty,
469																			$myrow['description'],
470																			$myrow['longdescription'],
471																			GetPrice ($_POST['NewItem'],
472																			$_SESSION['CreditItems'.$identifier]->DebtorNo,
473																			$_SESSION['CreditItems'.$identifier]->Branch),
474																			0,
475																			$myrow['units'],
476																			$myrow['volume'],
477																			$myrow['grossweight'],
478																			0,
479																			$myrow['mbflag'],
480																			Date($_SESSION['DefaultDateFormat']),
481																			0,
482																			$myrow['discountcategory'],
483																			$myrow['controlled'],
484																			$myrow['serialised'],
485																			$myrow['decimalplaces'],
486																			'',
487																			'No',
488																			-1,
489																			$myrow['taxcatid'],
490																			'',
491																			'',
492																			'',
493																			$myrow['standardcost']) ==1){
494
495						$_SESSION['CreditItems'.$identifier]->GetTaxes($LineNumber);
496
497						if ($myrow['controlled']==1){
498							/*Qty must be built up from serial item entries */
499				   			$_SESSION['CreditItems'.$identifier]->LineItems[$LineNumber]->Quantity = 0;
500						}
501
502					}
503			   	} else {
504					prnMsg( $_POST['NewItem'] . ' ' . _('does not exist in the database and cannot therefore be added to the credit note'),'warn');
505			   	}
506		   	} /* end of if not already on the credit note */
507		} while ($i<=$_SESSION['QuickEntries']); /*loop to the next quick entry record */
508		unset($_POST['NewItem']);
509	} /* end of if quick entry */
510
511
512/* setup system defaults for looking up prices and the number of ordered items
513   if an item has been selected for adding to the basket add it to the session arrays */
514
515	 if ($_SESSION['CreditItems'.$identifier]->ItemsOrdered > 0 OR isset($_POST['NewItem'])){
516
517		if (isset($_GET['Delete'])){
518			$_SESSION['CreditItems'.$identifier]->remove_from_cart($_GET['Delete']);
519		}
520
521		if (isset($_POST['ChargeFreightCost'])){
522			$_SESSION['CreditItems'.$identifier]->FreightCost = filter_number_format($_POST['ChargeFreightCost']);
523		}
524
525		if (isset($_POST['Location'])
526			AND $_POST['Location'] != $_SESSION['CreditItems'.$identifier]->Location){
527
528			$_SESSION['CreditItems'.$identifier]->Location = $_POST['Location'];
529
530			$NewDispatchTaxProvResult = DB_query("SELECT taxprovinceid FROM locations WHERE loccode='" . $_POST['Location'] . "'");
531			$myrow = DB_fetch_array($NewDispatchTaxProvResult);
532
533			$_SESSION['CreditItems'.$identifier]->DispatchTaxProvince = $myrow['taxprovinceid'];
534
535			foreach ($_SESSION['CreditItems'.$identifier]->LineItems as $LineItem) {
536				$_SESSION['CreditItems'.$identifier]->GetTaxes($LineItem->LineNumber);
537			}
538		}
539
540		foreach ($_SESSION['CreditItems'.$identifier]->LineItems as $LineItem) {
541
542			if (isset($_POST['Quantity_' . $LineItem->LineNumber])){
543
544				$Quantity = filter_number_format($_POST['Quantity_' . $LineItem->LineNumber]);
545				$Narrative = $_POST['Narrative_' . $LineItem->LineNumber];
546
547				if (isset($_POST['Price_' . $LineItem->LineNumber])){
548					if (isset($_POST['Gross']) AND $_POST['Gross']==true){
549						$TaxTotalPercent =0;
550						foreach ($LineItem->Taxes AS $Tax) {
551							if ($Tax->TaxOnTax ==1){
552								$TaxTotalPercent += (1 + $TaxTotalPercent) * $Tax->TaxRate;
553							} else {
554								$TaxTotalPercent += $Tax->TaxRate;
555							}
556						}
557						$Price = round(filter_number_format($_POST['Price_' . $LineItem->LineNumber])/($TaxTotalPercent + 1),$_SESSION['CreditItems'.$identifier]->CurrDecimalPlaces);
558					} else {
559						$Price = filter_number_format($_POST['Price_' . $LineItem->LineNumber]);
560					}
561
562     				$DiscountPercentage = filter_number_format($_POST['Discount_' . $LineItem->LineNumber]);
563
564					foreach ($LineItem->Taxes as $TaxKey=>$TaxLine) {
565						if (is_numeric(filter_number_format($_POST[$LineItem->LineNumber  . $TaxLine->TaxCalculationOrder . '_TaxRate']))){
566							$_SESSION['CreditItems'.$identifier]->LineItems[$LineItem->LineNumber]->Taxes[$TaxKey]->TaxRate = filter_number_format($_POST[$LineItem->LineNumber  . $TaxKey . '_TaxRate'])/100;
567						}
568					}
569				}
570				if ($Quantity<0 OR $Price <0 OR $DiscountPercentage >100 OR $DiscountPercentage <0){
571					prnMsg(_('The item could not be updated because you are attempting to set the quantity credited to less than 0 or the price less than 0 or the discount more than 100% or less than 0%'),'warn');
572				} elseif (isset($_POST['Quantity_' . $LineItem->LineNumber])) {
573					$_SESSION['CreditItems'.$identifier]->update_cart_item($LineItem->LineNumber,
574																			$Quantity,
575																			$Price,
576																			$DiscountPercentage/100,
577																			$Narrative,
578																			'No',
579																			$LineItem->ItemDue,
580																			$LineItem->POLine,
581																			0,
582																			$identifier);
583				}
584			}
585
586		}
587
588		foreach ($_SESSION['CreditItems'.$identifier]->FreightTaxes as $FreightTaxKey=>$FreightTaxLine) {
589			if (is_numeric(filter_number_format($_POST['FreightTaxRate'  . $FreightTaxLine->TaxCalculationOrder]))){
590				$_SESSION['CreditItems'.$identifier]->FreightTaxes[$FreightTaxKey]->TaxRate = filter_number_format($_POST['FreightTaxRate'  . $FreightTaxKey])/100;
591			}
592		}
593
594		if (isset($_POST['NewItem'])){
595/* get the item details from the database and hold them in the cart object make the quantity 1 by default then add it to the cart */
596
597			   $AlreadyOnThisCredit =0;
598
599			   foreach ($_SESSION['CreditItems'.$identifier]->LineItems AS $OrderItem) {
600
601			   /* do a loop round the items on the credit note to see that the item
602			   is not already on this credit note */
603
604					if ($_SESSION['SO_AllowSameItemMultipleTimes']==0 AND strcasecmp($OrderItem->StockID, $_POST['NewItem']) == 0) {
605					     $AlreadyOnThisCredit = 1;
606					     prnMsg(_('The item selected is already on this credit the system will not allow the same item on the credit note more than once. However you can change the quantity credited of the existing line if necessary.'),'warn');
607				    }
608			   } /* end of the foreach loop to look for preexisting items of the same code */
609
610			   if ($AlreadyOnThisCredit!=1){
611
612				$sql = "SELECT stockmaster.description,
613								stockmaster.longdescription,
614								stockmaster.stockid,
615								stockmaster.units,
616								stockmaster.volume,
617								stockmaster.grossweight,
618								stockmaster.mbflag,
619								stockmaster.discountcategory,
620								stockmaster.controlled,
621								stockmaster.decimalplaces,
622								stockmaster.serialised,
623								(materialcost+labourcost+overheadcost) AS standardcost,
624								stockmaster.taxcatid
625							FROM stockmaster
626							WHERE stockmaster.stockid = '". $_POST['NewItem'] . "'";
627
628				$ErrMsg = _('The item details could not be retrieved because');
629				$DbgMsg = _('The SQL used to retrieve the item details but failed was');
630				$result1 = DB_query($sql,$ErrMsg,$DbgMsg);
631				$myrow = DB_fetch_array($result1);
632
633				$LineNumber = $_SESSION['CreditItems'.$identifier]->LineCounter;
634/*validate the data returned before adding to the items to credit */
635				if ($_SESSION['CreditItems'.$identifier]->add_to_cart ($myrow['stockid'],
636														1,
637														$myrow['description'],
638														$myrow['longdescription'],
639														GetPrice($_POST['NewItem'],
640														$_SESSION['CreditItems'.$identifier]->DebtorNo,
641														$_SESSION['CreditItems'.$identifier]->Branch),
642														0,
643														$myrow['units'],
644														$myrow['volume'],
645														$myrow['grossweight'],
646														0,
647														$myrow['mbflag'],
648														Date($_SESSION['DefaultDateFormat']),
649														0,
650														$myrow['discountcategory'],
651														$myrow['controlled'],
652														$myrow['serialised'],
653														$myrow['decimalplaces'],
654														'',
655														'No',
656														-1,
657														$myrow['taxcatid'],
658														'',
659														'',
660														'',
661														$myrow['standardcost']) ==1){
662
663					$_SESSION['CreditItems'.$identifier]->GetTaxes($LineNumber);
664
665					if ($myrow['controlled']==1){
666						/*Qty must be built up from serial item entries */
667						$_SESSION['CreditItems'.$identifier]->LineItems[$LineNumber]->Quantity = 0;
668					}
669				}
670			   } /* end of if not already on the credit note */
671		  } /* end of if its a new item */
672
673/* This is where the credit note as selected should be displayed  reflecting any deletions or insertions*/
674
675		  echo '<table cellpadding="2" class="selection">
676				<tr>
677					<th>' . _('Item Code') . '</th>
678					<th>' . _('Item Description') . '</th>
679					<th>' . _('Quantity') . '</th>
680					<th>' . _('Unit') . '</th>
681					<th>' . _('Price') . '</th>
682					<th>' . _('Gross') . '</th>
683					<th>' . _('Discount') . '</th>
684					<th>' . _('Total') . '<br />' . _('Excl Tax') . '</th>
685					<th>' . _('Tax Authority') . '</th>
686					<th>' . _('Tax') . '<br />' . _('Rate') . '</th>
687					<th>' . _('Tax') . '<br />' . _('Amount') . '</th>
688					<th>' . _('Total') . '<br />' . _('Incl Tax') . '</th>
689				</tr>';
690
691		  $_SESSION['CreditItems'.$identifier]->total = 0;
692		  $_SESSION['CreditItems'.$identifier]->totalVolume = 0;
693		  $_SESSION['CreditItems'.$identifier]->totalWeight = 0;
694
695		  $TaxTotal = 0;
696		  $TaxTotals = array();
697		  $TaxGLCodes = array();
698
699		  foreach ($_SESSION['CreditItems'.$identifier]->LineItems as $LineItem) {
700
701			   $LineTotal =  round($LineItem->Quantity * $LineItem->Price * (1 - $LineItem->DiscountPercent),$_SESSION['CreditItems'.$identifier]->CurrDecimalPlaces);
702			   $DisplayLineTotal = locale_number_format($LineTotal,$_SESSION['CreditItems'.$identifier]->CurrDecimalPlaces);
703
704			   echo '<tr class="striped_row">
705						<td>' . $LineItem->StockID . '</td>
706									<td title="'. $LineItem->LongDescription . '">' . $LineItem->ItemDescription . '</td>';
707
708			   if ($LineItem->Controlled==0){
709			   	echo '<td><input type="text" class="number" name="Quantity_' . $LineItem->LineNumber . '" maxlength="8" size="6" value="' . locale_number_format(round($LineItem->Quantity,$LineItem->DecimalPlaces),$LineItem->DecimalPlaces) . '" /></td>';
710			   } else {
711				echo '<td class="number"><a href="' . $RootPath . '/CreditItemsControlled.php?LineNo=' . $LineItem->LineNumber . '&identifier=' . $identifier . '">' . locale_number_format($LineItem->Quantity,$LineItem->DecimalPlaces) . '</a>
712                      <input type="hidden" name="Quantity_' . $LineItem->LineNumber . '" value="' . locale_number_format(round($LineItem->Quantity,$LineItem->DecimalPlaces),$LineItem->DecimalPlaces) . '" /></td>';
713			   }
714
715			echo '<td>' . $LineItem->Units . '</td>
716			<td><input type="text" class="number" name="Price_' . $LineItem->LineNumber . '" size="10" maxlength="12" value="' . locale_number_format($LineItem->Price,$_SESSION['CreditItems'.$identifier]->CurrDecimalPlaces) . '" /></td>
717			<td><input type="CheckBox" name="Gross" value="false" /></td>
718			<td><input type="text" class="number" name="Discount_' . $LineItem->LineNumber . '" size="3" maxlength="3" value="' . locale_number_format(($LineItem->DiscountPercent * 100),'Variable') . '" />%</td>
719			<td class="number">' . $DisplayLineTotal . '</td>';
720
721
722			/*Need to list the taxes applicable to this line */
723			echo '<td>';
724			foreach ($_SESSION['CreditItems'.$identifier]->LineItems[$LineItem->LineNumber]->Taxes AS $Tax) {
725				echo '<br />';
726				echo $Tax->TaxAuthDescription;
727			}
728			echo '</td>';
729			echo '<td>';
730
731			$i=0; // initialise the number of taxes iterated through
732			$TaxLineTotal =0; //initialise tax total for the line
733
734			foreach ($LineItem->Taxes AS $TaxKey=>$Tax) {
735
736				if ($i>0){
737					echo '<br />';
738				}
739				echo '<input type="text" class="number" name="' . $LineItem->LineNumber . $TaxKey . '_TaxRate" maxlength="4" size="4" value="' . locale_number_format($Tax->TaxRate*100,'Variable') . '" />';
740				$i++;
741				if ($Tax->TaxOnTax ==1){
742					$TaxTotals[$Tax->TaxAuthID] += ($Tax->TaxRate * ($LineTotal + $TaxLineTotal));
743					$TaxLineTotal += ($Tax->TaxRate * ($LineTotal + $TaxLineTotal));
744				} else {
745					$TaxTotals[$Tax->TaxAuthID] += ($Tax->TaxRate * $LineTotal);
746					$TaxLineTotal += ($Tax->TaxRate * $LineTotal);
747				}
748				$TaxGLCodes[$Tax->TaxAuthID] = $Tax->TaxGLCode;
749			}
750			echo '</td>';
751
752			$TaxTotal += $TaxLineTotal;
753
754			$DisplayTaxAmount = locale_number_format($TaxLineTotal ,$_SESSION['CreditItems'.$identifier]->CurrDecimalPlaces);
755			$DisplayGrossLineTotal = locale_number_format($LineTotal + $TaxLineTotal, $_SESSION['CreditItems'.$identifier]->CurrDecimalPlaces);
756
757			echo '<td class="number">' . $DisplayTaxAmount . '</td>
758				<td class="number">' . $DisplayGrossLineTotal . '</td>
759				<td><a href="' . htmlspecialchars($_SERVER['PHP_SELF'],ENT_QUOTES,'UTF-8') . '?identifier=' . $identifier . '&Delete=' . $LineItem->LineNumber . '" onclick="return confirm(\'' . _('Are you sure you wish to delete this line item from the credit note?') . '\');">' . _('Delete') . '</a></td>
760				</tr>';
761
762			echo '<tr class="striped_row">
763					<td colspan="11"><textarea  name="Narrative_' . $LineItem->LineNumber . '" cols="100%" rows="1">' . $LineItem->Narrative . '</textarea><br /></td>
764				</tr>';
765
766
767			$_SESSION['CreditItems'.$identifier]->total += $LineTotal;
768			$_SESSION['CreditItems'.$identifier]->totalVolume += ($LineItem->Quantity * $LineItem->Volume);
769			$_SESSION['CreditItems'.$identifier]->totalWeight += ($LineItem->Quantity * $LineItem->Weight);
770		}
771
772		if (!isset($_POST['ChargeFreightCost'])
773			AND !isset($_SESSION['CreditItems'.$identifier]->FreightCost)){
774			$_POST['ChargeFreightCost']=0;
775		}
776		echo '<tr>
777				<td colspan="5"></td>';
778
779		echo '<td colspan="2" class="number">' .  _('Credit Freight') . '</td>
780			<td><input type="text" class="number" size="6" maxlength="6" name="ChargeFreightCost" value="' . locale_number_format($_SESSION['CreditItems'.$identifier]->FreightCost,$_SESSION['CreditItems'.$identifier]->CurrDecimalPlaces) . '" /></td>';
781
782		$FreightTaxTotal =0; //initialise tax total
783
784		echo '<td>';
785
786		$i=0; // initialise the number of taxes iterated through
787		foreach ($_SESSION['CreditItems'.$identifier]->FreightTaxes as $FreightTaxLine) {
788			if ($i>0){
789				echo '<br />';
790			}
791			echo  $FreightTaxLine->TaxAuthDescription;
792			$i++;
793		}
794
795		echo '</td><td>';
796
797		$i=0;
798		foreach ($_SESSION['CreditItems'.$identifier]->FreightTaxes as $FreightTaxLine) {
799			if ($i>0){
800				echo '<br />';
801			}
802
803			echo  '<input type="text" class="number" name=FreightTaxRate' . $FreightTaxLine->TaxCalculationOrder . ' maxlength="4" size="4" value="' . locale_number_format(($FreightTaxLine->TaxRate * 100),'Variable') . '" />';
804
805			if ($FreightTaxLine->TaxOnTax ==1){
806				$TaxTotals[$FreightTaxLine->TaxAuthID] += ($FreightTaxLine->TaxRate * ($_SESSION['CreditItems'.$identifier]->FreightCost + $FreightTaxTotal));
807				$FreightTaxTotal += ($FreightTaxLine->TaxRate * ($_SESSION['CreditItems'.$identifier]->FreightCost + $FreightTaxTotal));
808			} else {
809				$TaxTotals[$FreightTaxLine->TaxAuthID] += ($FreightTaxLine->TaxRate * $_SESSION['CreditItems'.$identifier]->FreightCost);
810				$FreightTaxTotal += ($FreightTaxLine->TaxRate * $_SESSION['CreditItems'.$identifier]->FreightCost);
811			}
812			$i++;
813			$TaxGLCodes[$FreightTaxLine->TaxAuthID] = $FreightTaxLine->TaxGLCode;
814		}
815		echo '</td>';
816
817		echo '<td class="number">' . locale_number_format($FreightTaxTotal,$_SESSION['CreditItems'.$identifier]->CurrDecimalPlaces) . '</td>
818			<td class="number">' . locale_number_format($FreightTaxTotal+ $_SESSION['CreditItems'.$identifier]->FreightCost,$_SESSION['CreditItems'.$identifier]->CurrDecimalPlaces) . '</td>
819			</tr>';
820
821		$TaxTotal += $FreightTaxTotal;
822		$DisplayTotal = locale_number_format($_SESSION['CreditItems'.$identifier]->total + $_SESSION['CreditItems'.$identifier]->FreightCost,$_SESSION['CreditItems'.$identifier]->CurrDecimalPlaces);
823
824		echo '<tr>
825				<td colspan="7" class="number">' . _('Credit Totals') . '</td>
826				<td class="number"><b>' . $DisplayTotal . '</b></td>
827				<td colspan="2"></td>
828				<td class="number"><b>' . locale_number_format($TaxTotal,$_SESSION['CreditItems'.$identifier]->CurrDecimalPlaces) . '</td>
829				<td class="number"><b>' . locale_number_format($TaxTotal+($_SESSION['CreditItems'.$identifier]->total + $_SESSION['CreditItems'.$identifier]->FreightCost),$_SESSION['CreditItems'.$identifier]->CurrDecimalPlaces) . '</b></td>
830			</tr>
831			</table>';
832
833/*Now show options for the credit note */
834
835		echo '<br />
836				<table class="selection">
837				<tr>
838					<td>' . _('Credit Note Type') . ' :</td>
839					<td><select name="CreditType" onchange="ReloadForm(MainForm.Update)" >';
840
841		if (!isset($_POST['CreditType']) OR $_POST['CreditType']=='Return'){
842			   echo '<option selected="selected" value="Return">' . _('Goods returned to store') . '</option>
843					<option value="WriteOff">' . _('Goods written off') . '</option>
844					<option value="ReverseOverCharge">' . _('Reverse an Overcharge') . '</option>';
845		} elseif ($_POST['CreditType']=='WriteOff') {
846			   echo '<option selected="selected" value="WriteOff">' . _('Goods written off') . '</option>
847					<option value="Return">' . _('Goods returned to store') . '</option>
848					<option value="ReverseOverCharge">' . _('Reverse an Overcharge') . '</option>';
849		} elseif($_POST['CreditType']=='ReverseOverCharge'){
850		  	echo '<option selected="selected" value="ReverseOverCharge">' . _('Reverse Overcharge Only') . '</option>
851				<option value="Return">' . _('Goods Returned To Store') . '</option>
852				<option value="WriteOff">' . _('Good written off') . '</option>';
853		}
854
855		echo '</select></td></tr>';
856
857
858		if (!isset($_POST['CreditType']) OR $_POST['CreditType']=='Return'){
859
860/*if the credit note is a return of goods then need to know which location to receive them into */
861
862			echo '<tr>
863					<td>' . _('Goods Returned to Location') . ' :</td>
864					<td><select name="Location">';
865
866			$SQL="SELECT locations.loccode, locationname FROM locations INNER JOIN locationusers ON locationusers.loccode=locations.loccode AND locationusers.userid='" .  $_SESSION['UserID'] . "' AND locationusers.canupd=1";
867			$Result = DB_query($SQL);
868
869			if (!isset($_POST['Location'])){
870				$_POST['Location'] = $_SESSION['CreditItems'.$identifier]->Location;
871			}
872			while ($myrow = DB_fetch_array($Result)) {
873
874				if ($_POST['Location']==$myrow['loccode']){
875					echo '<option selected="selected" value="' . $myrow['loccode'] . '">' . $myrow['locationname'] . '</option>';
876				} else {
877					echo '<option value="' . $myrow['loccode'] . '">' . $myrow['locationname'] . '</option>';
878				}
879			}
880			echo '</select></td></tr>';
881
882		} elseif ($_POST['CreditType']=='WriteOff') { /* the goods are to be written off to somewhere */
883
884			echo '<tr><td>' . _('Write off the cost of the goods to') . '</td>
885					<td><select name=WriteOffGLCode>';
886
887			$SQL="SELECT accountcode,
888						accountname
889					FROM chartmaster INNER JOIN accountgroups
890					ON chartmaster.group_=accountgroups.groupname
891					WHERE accountgroups.pandl=1
892					ORDER BY accountcode";
893			$Result = DB_query($SQL);
894
895			while ($myrow = DB_fetch_array($Result)) {
896
897				if ($_POST['WriteOffGLCode']==$myrow['accountcode']){
898					echo '<option selected="selected" value="' . $myrow['accountcode'] . '">' . $myrow['accountcode'] . ' - ' . $myrow['accountname'] . '</option>';
899				} else {
900					echo '<option value="' . $myrow['accountcode'] . '">' . $myrow['accountcode'] . ' - ' . $myrow['accountname'] . '</option>';
901				}
902			}
903			   echo '</select></td></tr>';
904		  }
905		echo '<tr>
906				<td>' . _('Sales person'). ':</td>
907				<td><select name="SalesPerson">';
908		$SalesPeopleResult = DB_query("SELECT salesmancode, salesmanname FROM salesman WHERE current=1");
909		if (!isset($_POST['SalesPerson']) AND $_SESSION['SalesmanLogin']!=NULL ){
910			$_SESSION['CreditItems'.$identifier]->SalesPerson = $_SESSION['SalesmanLogin'];
911		}
912
913		while ($SalesPersonRow = DB_fetch_array($SalesPeopleResult)){
914			if ($SalesPersonRow['salesmancode']==$_SESSION['CreditItems'.$identifier]->SalesPerson){
915				echo '<option selected="selected" value="' . $SalesPersonRow['salesmancode'] . '">' . $SalesPersonRow['salesmanname'] . '</option>';
916			} else {
917				echo '<option value="' . $SalesPersonRow['salesmancode'] . '">' . $SalesPersonRow['salesmanname'] . '</option>';
918			}
919		}
920
921		echo '</select></td>
922			</tr>';
923		  if (!isset($_POST['CreditText'])) {
924			  $_POST['CreditText']='';
925		  }
926		  echo '<tr><td>' . _('Credit Note Text') . ' :</td>
927		  		<td><textarea name="CreditText" COLS="31" rows="5">' . $_POST['CreditText'] . '</textarea></td>
928			</tr>
929			</table><br />';
930
931		  $OKToProcess = true;
932		/*Check for the worst */
933		  if (isset($_POST['CreditType']) and $_POST['CreditType']=='WriteOff' AND !isset($_POST['WriteOffGLCode'])){
934			prnMsg (_('The GL code to write off the credit value to must be specified. Please select the appropriate GL code for the selection box'),'info');
935			$OKToProcess = false;
936		  }
937		  echo '<div class="centre">
938				<input type="submit" name="Update" value="' . _('Update') . '" />
939				<input type="submit" name="CancelCredit" value="' . _('Cancel') . '" onclick="return confirm(\'' . _('Are you sure you wish to cancel the whole of this credit note?') . '\');" />';
940		  if (!isset($_POST['ProcessCredit']) AND $OKToProcess == true){
941			echo '<input type="submit" name="ProcessCredit" value="' . _('Process Credit Note') . '" />
942					<br />';
943		  }
944		  echo '</div>';
945	 } # end of if lines
946
947
948/* Now show the stock item selection search stuff below */
949
950	 if (isset($_POST['PartSearch']) AND $_POST['PartSearch']!='' AND !isset($_POST['ProcessCredit'])){
951
952		 echo '<input type="hidden" name="PartSearch" value="' . _('Yes Please') . '" />';
953
954		 $SQL="SELECT categoryid,
955					categorydescription
956				FROM stockcategory
957				WHERE stocktype='F'
958				ORDER BY categorydescription";
959
960		 $result1 = DB_query($SQL);
961
962		 echo '<br />
963				<table class="selection">
964				<tr>
965					<td>' . _('Select a stock category') . ':&nbsp;<select name="StockCat">';
966
967		 echo '<option selected="selected" value="All">' . _('All') . '</option>';
968		 while ($myrow1 = DB_fetch_array($result1)) {
969			  if (isset($_POST['StockCat']) and $_POST['StockCat']==$myrow1['categoryid']){
970				   echo '<option selected="selected" value="' . $myrow1['categoryid'] . '">' . $myrow1['categorydescription'] . '</option>';
971			  } else {
972				   echo '<option value="' . $myrow1['categoryid'] . '">' . $myrow1['categorydescription'] . '</option>';
973			  }
974		 }
975
976		 echo '</select></td>';
977		 if (!isset($_POST['Keywords'])) {
978		 	$_POST['Keywords'] = '';
979		 }
980		 if (!isset($_POST['StockCode'])) {
981		 	$_POST['StockCode'] = '';
982		 }
983		 echo '<td>' . _('Enter text extracts in the description') . ':&nbsp;</td>';
984		 echo '<td><input type="text" name="Keywords" size="20" maxlength="25" value="' . $_POST['Keywords'] . '" /></td></tr>';
985		 echo '<tr><td></td>';
986		 echo '<td><b>' ._('OR') . '</b>&nbsp;&nbsp;' . _('Enter extract of the Stock Code') . ':&nbsp;</td>';
987		 echo '<td><input type="text" name="StockCode" size="15" maxlength="18" value="' . $_POST['StockCode'] . '" /></td>';
988		 echo '</tr>';
989		 echo '</table>
990				<br />
991				<div class="centre">';
992
993		 echo '<input type="submit" name="Search" value="' . _('Search Now') .'" />
994				<input type="submit" name="ChangeCustomer" value="' . _('Change Customer') . '" />
995				<input type="submit" name="Quick" value="' . _('Quick Entry') . '" />
996				</div>';
997
998		 if (isset($SearchResult)) {
999
1000			  echo '<table cellpadding="2" class="selection">';
1001			  $TableHeader = '<tr>
1002								<th>' . _('Code') . '</th>
1003					  			<th>' . _('Description') . '</th>
1004								<th>' . _('Units')  . '</th>
1005							</tr>';
1006			  echo $TableHeader;
1007
1008			  $j = 1;
1009
1010			  while ($myrow=DB_fetch_array($SearchResult)) {
1011
1012				$SupportedImgExt = array('png','jpg','jpeg');
1013				$imagefile = reset((glob($_SESSION['part_pics_dir'] . '/' . $myrow['stockid'] . '.{' . implode(",", $SupportedImgExt) . '}', GLOB_BRACE)));
1014				if (extension_loaded('gd') && function_exists('gd_info') && file_exists ($imagefile) ) {
1015						$ImageSource = '<img src="GetStockImage.php?automake=1&amp;textcolor=FFFFFF&amp;bgcolor=CCCCCC'.
1016							'&amp;StockID='.urlencode($myrow['stockid']).
1017							'&amp;text='.
1018							'&amp;width=64'.
1019							'&amp;height=64'.
1020							'" alt="" />';
1021					printf('<tr class="striped_row">
1022							<td><input type="submit" name="NewItem" value="%s" /></td>
1023							<td>%s</td>
1024							<td>%s</td>
1025							<td>' . $ImageSource . '</td>
1026							</tr>',
1027							$myrow['stockid'],
1028							$myrow['description'],
1029							$myrow['units'],
1030							$myrow['stockid']);
1031				} else { //don't try to show the image
1032					printf('<tr class="striped_row">
1033						<td><input type="submit" name="NewItem" value="%s" /></td>
1034						<td>%s</td>
1035						<td>%s</td>
1036						<td>' . _('No Image') . '</td>
1037						</tr>',
1038						$myrow['stockid'],
1039						$myrow['description'],
1040						$myrow['units']);
1041				}
1042	#end of page full new headings if
1043			  }
1044	#end of while loop
1045			  echo '</table>';
1046		 }#end if SearchResults to show
1047	} /*end if part searching required */ elseif(!isset($_POST['ProcessCredit'])) { /*quick entry form */
1048
1049/*FORM VARIABLES TO POST TO THE CREDIT NOTE 10 AT A TIME WITH PART CODE AND QUANTITY */
1050	     echo '<table class="selection">';
1051	     echo '<tr><th colspan="2"><h3>' . _('Quick Entry') . '</h3></th></tr>';
1052	     echo '<tr>
1053	           	<th>' . _('Part Code') . '</th>
1054	           	<th>' . _('Quantity') . '</th>
1055	           </tr>';
1056
1057	      for ($i=1;$i<=$_SESSION['QuickEntries'];$i++){
1058
1059	     	echo '<tr class="striped_row">
1060					<td><input type="text" name="part_' . $i . '" size="21" maxlength="20" /></td>
1061					<td><input type="text" class="number" name="qty_' . $i . '" size="6" maxlength="6" /></td>
1062				</tr>';
1063	     }
1064
1065	     echo '</table>
1066				<br />
1067				<div class="centre">
1068				<input type="submit" name="QuickEntry" value="' . _('Process Entries') . '" />
1069				<input type="submit" name="PartSearch" value="' . _('Search Parts') . '" />
1070				</div>';
1071
1072	}
1073
1074    echo '</div>
1075          </form>';
1076} //end of else not selecting a customer
1077
1078if (isset($_POST['ProcessCredit']) AND $OKToProcess==true){
1079
1080	/* SQL to process the postings for sales credit notes...
1081	First Get the area where the credit note is to from the branches table */
1082
1083	 $SQL = "SELECT area
1084		 	FROM custbranch
1085			WHERE custbranch.debtorno ='". $_SESSION['CreditItems'.$identifier]->DebtorNo . "'
1086			AND custbranch.branchcode = '" . $_SESSION['CreditItems'.$identifier]->Branch . "'";
1087	$ErrMsg =  _('CRITICAL ERROR') . '! ' . _('NOTE DOWN THIS ERROR AND SEEK ASSISTANCE') . ': ' . _('The area cannot be determined for this customer');
1088	$DbgMsg = _('The following SQL to insert the customer credit note was used');
1089	$Result = DB_query($SQL,$ErrMsg,$DbgMsg);
1090
1091	 if ($myrow = DB_fetch_row($Result)){
1092	     $Area = $myrow[0];
1093	 }
1094
1095	 DB_free_result($Result);
1096
1097	 if ($_SESSION['CompanyRecord']['gllink_stock']==1
1098	 	AND $_POST['CreditType']=='WriteOff'
1099		AND (!isset($_POST['WriteOffGLCode'])
1100		OR $_POST['WriteOffGLCode']=='')){
1101
1102		  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');
1103		  include('includes/footer.php');
1104		  exit;
1105	 }
1106
1107
1108/*Now Get the next credit note number - function in SQL_CommonFunctions*/
1109
1110	 $CreditNo = GetNextTransNo(11);
1111	 $SQLCreditDate = Date('Y-m-d');
1112	 $PeriodNo = GetPeriod(Date($_SESSION['DefaultDateFormat']));
1113
1114/*Start an SQL transaction */
1115	 DB_Txn_Begin();
1116
1117
1118/*Now insert the Credit Note into the DebtorTrans table allocations will have to be done seperately*/
1119
1120	 $SQL = "INSERT INTO debtortrans (transno,
1121							 		type,
1122									debtorno,
1123									branchcode,
1124									trandate,
1125									inputdate,
1126									prd,
1127									tpe,
1128									ovamount,
1129									ovgst,
1130									ovfreight,
1131									rate,
1132									invtext,
1133									salesperson)
1134								  VALUES ('". $CreditNo . "',
1135								  	'11',
1136									'" . $_SESSION['CreditItems' . $identifier]->DebtorNo . "',
1137									'" . $_SESSION['CreditItems' . $identifier]->Branch . "',
1138									'" . $SQLCreditDate . "',
1139									'" . date('Y-m-d H-i-s') . "',
1140									'" . $PeriodNo . "',
1141									'" . $_SESSION['CreditItems' . $identifier]->DefaultSalesType . "',
1142									'" . -($_SESSION['CreditItems'.$identifier]->total) . "',
1143									'" . -$TaxTotal . "',
1144								  	'" . -$_SESSION['CreditItems' . $identifier]->FreightCost . "',
1145									'" . $_SESSION['CurrencyRate'] . "',
1146									'" . $_POST['CreditText'] . "',
1147									'" . $_SESSION['CreditItems' . $identifier]->SalesPerson . "' )";
1148
1149	$ErrMsg = _('CRITICAL ERROR') . '! ' . _('NOTE DOWN THIS ERROR AND SEEK ASSISTANCE') . ': ' . _('The customer credit note transaction could not be added to the database because');
1150	$DbgMsg = _('The following SQL to insert the customer credit note was used');
1151	$Result = DB_query($SQL,$ErrMsg,$DbgMsg,true);
1152
1153
1154	$CreditTransID = DB_Last_Insert_ID('debtortrans','id');
1155
1156	/* Insert the tax totals for each tax authority where tax was charged on the invoice */
1157	foreach ($TaxTotals AS $TaxAuthID => $TaxAmount) {
1158
1159		$SQL = "INSERT INTO debtortranstaxes (debtortransid,
1160							taxauthid,
1161							taxamount)
1162				VALUES ('" . $CreditTransID . "',
1163						'" . $TaxAuthID . "',
1164						'" . -$TaxAmount/$_SESSION['CurrencyRate'] . "')";
1165
1166		$ErrMsg =_('CRITICAL ERROR') . '! ' . _('NOTE DOWN THIS ERROR AND SEEK ASSISTANCE') . ': ' . _('The debtor transaction taxes records could not be inserted because');
1167		$DbgMsg = _('The following SQL to insert the debtor transaction taxes record was used');
1168 		$Result = DB_query($SQL,$ErrMsg,$DbgMsg,true);
1169	}
1170
1171/* Insert stock movements for stock coming back in if the Credit is a return of goods */
1172
1173	 foreach ($_SESSION['CreditItems'.$identifier]->LineItems as $CreditLine) {
1174
1175		if ($CreditLine->Quantity > 0){
1176
1177			$LocalCurrencyPrice = ($CreditLine->Price / $_SESSION['CurrencyRate']);
1178
1179		    if ($CreditLine->MBflag=='M' oR $CreditLine->MBflag=='B'){
1180		   /*Need to get the current location quantity will need it later for the stock movement */
1181	 	    	$SQL="SELECT locstock.quantity
1182						FROM locstock
1183						WHERE locstock.stockid='" . $CreditLine->StockID . "'
1184						AND loccode= '" . $_SESSION['CreditItems'.$identifier]->Location . "'";
1185
1186		    	$Result = DB_query($SQL);
1187		    	if (DB_num_rows($Result)==1){
1188					$LocQtyRow = DB_fetch_row($Result);
1189					$QtyOnHandPrior = $LocQtyRow[0];
1190		    	} else {
1191				/*There must actually be some error this should never happen */
1192					$QtyOnHandPrior = 0;
1193		    	}
1194		    } else {
1195		    	$QtyOnHandPrior =0; //because its a dummy/assembly/kitset part
1196		    }
1197
1198		    if ($_POST['CreditType']=='ReverseOverCharge') {
1199		   /*Insert a stock movement coming back in to show the credit note  - flag the stockmovement not to show on stock movement enquiries - its is not a real stock movement only for invoice line - also no mods to location stock records*/
1200				$SQL = "INSERT INTO stockmoves (stockid,
1201												type,
1202												transno,
1203												loccode,
1204												trandate,
1205												userid,
1206												debtorno,
1207												branchcode,
1208												price,
1209												prd,
1210												reference,
1211												qty,
1212												discountpercent,
1213												standardcost,
1214												newqoh,
1215												hidemovt,
1216												narrative)
1217										VALUES ('" . $CreditLine->StockID . "',
1218												11,
1219												'" . $CreditNo . "',
1220												'" . $_SESSION['CreditItems'.$identifier]->Location . "',
1221												'" . $SQLCreditDate . "',
1222												'" . $_SESSION['UserID'] . "',
1223												'" . $_SESSION['CreditItems'.$identifier]->DebtorNo . "',
1224												'" . $_SESSION['CreditItems'.$identifier]->Branch . "',
1225												'" . $LocalCurrencyPrice . "',
1226												'" . $PeriodNo . "',
1227												'" . $_POST['CreditText'] . "',
1228												'" . $CreditLine->Quantity . "',
1229												'" . $CreditLine->DiscountPercent . "',
1230												'" . $CreditLine->StandardCost . "',
1231												'" . $QtyOnHandPrior  . "',
1232												1,
1233												'" . $CreditLine->Narrative . "')";
1234
1235				$ErrMsg =  _('CRITICAL ERROR') . '! ' . _('NOTE DOWN THIS ERROR AND SEEK ASSISTANCE') . ': ' . _('Stock movement records could not be inserted because');
1236				$DbgMsg = _('The following SQL to insert the stock movement records for the purpose of display on the credit note was used');
1237				$Result = DB_query($SQL,$ErrMsg,$DbgMsg,true);
1238
1239			} else { //its a return or a write off need to record goods coming in first
1240
1241		    	if ($CreditLine->MBflag=='M' OR $CreditLine->MBflag=='B'){
1242		    		$SQL = "INSERT INTO stockmoves (stockid,
1243												type,
1244												transno,
1245												loccode,
1246												trandate,
1247												userid,
1248												debtorno,
1249												branchcode,
1250												price,
1251												prd,
1252												qty,
1253												discountpercent,
1254												standardcost,
1255												reference,
1256												newqoh,
1257												narrative)
1258											VALUES (
1259												'" . $CreditLine->StockID . "',
1260												11,
1261												" . $CreditNo . ",
1262												'" . $_SESSION['CreditItems'.$identifier]->Location . "',
1263												'" . $SQLCreditDate . "',
1264												'" . $_SESSION['UserID'] . "',
1265												'" . $_SESSION['CreditItems'.$identifier]->DebtorNo . "',
1266												'" . $_SESSION['CreditItems'.$identifier]->Branch . "',
1267												'" . $LocalCurrencyPrice . "',
1268												'" . $PeriodNo . "',
1269												'" . $CreditLine->Quantity . "',
1270												'" . $CreditLine->DiscountPercent . "',
1271												'" . $CreditLine->StandardCost . "',
1272												'" . $_POST['CreditText'] . "',
1273												'" . ($QtyOnHandPrior + $CreditLine->Quantity) . "',
1274												'" . $CreditLine->Narrative . "'
1275											)";
1276
1277		    	} else { /*its an assembly/kitset or dummy so don't attempt to figure out new qoh */
1278					$SQL = "INSERT INTO stockmoves (stockid,
1279													type,
1280													transno,
1281													loccode,
1282													trandate,
1283													userid,
1284													debtorno,
1285													branchcode,
1286													price,
1287													prd,
1288													qty,
1289													discountpercent,
1290													standardcost,
1291													reference,
1292													narrative)
1293											VALUES ('" . $CreditLine->StockID . "',
1294													11,
1295													'" . $CreditNo . "',
1296													'" . $_SESSION['CreditItems'.$identifier]->Location . "',
1297													'" . $SQLCreditDate . "',
1298													'" . $_SESSION['UserID'] . "',
1299													'" . $_SESSION['CreditItems'.$identifier]->DebtorNo . "',
1300													'" . $_SESSION['CreditItems'.$identifier]->Branch . "',
1301													'" . $LocalCurrencyPrice . "',
1302													'" . $PeriodNo . "',
1303													'" . $CreditLine->Quantity . "',
1304													'" . $CreditLine->DiscountPercent . "',
1305													'" . $CreditLine->StandardCost . "',
1306													'" . $_POST['CreditText'] . "',
1307													'" . $CreditLine->Narrative . "' )";
1308		    	}
1309
1310				$ErrMsg = _('CRITICAL ERROR') . '! ' . _('NOTE DOWN THIS ERROR AND SEEK ASSISTANCE') . ': ' . _('Stock movement records could not be inserted because');
1311				$DbgMsg = _('The following SQL to insert the stock movement records was used');
1312				$Result = DB_query($SQL, $ErrMsg, $DbgMsg, true);
1313
1314				/*Get the stockmoveno from above - need to ref StockMoveTaxes and possibly SerialStockMoves */
1315				$StkMoveNo = DB_Last_Insert_ID('stockmoves','stkmoveno');
1316
1317				/*Insert the taxes that applied to this line */
1318				foreach ($CreditLine->Taxes as $Tax) {
1319
1320					$SQL = "INSERT INTO stockmovestaxes (stkmoveno,
1321										taxauthid,
1322										taxrate,
1323										taxcalculationorder,
1324										taxontax)
1325							VALUES ('" . $StkMoveNo . "',
1326								'" . $Tax->TaxAuthID . "',
1327								'" . $Tax->TaxRate . "',
1328								'" . $Tax->TaxCalculationOrder . "',
1329								'" . $Tax->TaxOnTax . "')";
1330
1331					$ErrMsg = _('CRITICAL ERROR') . '! ' . _('NOTE DOWN THIS ERROR AND SEEK ASSISTANCE') . ': ' . _('Taxes and rates applicable to this credit note line item could not be inserted because');
1332					$DbgMsg = _('The following SQL to insert the stock movement tax detail records was used');
1333					$Result = DB_query($SQL,$ErrMsg,$DbgMsg,true);
1334				}
1335
1336
1337				if (($CreditLine->MBflag=='M' OR $CreditLine->MBflag=='B') AND $CreditLine->Controlled==1){
1338					/*Need to do the serial stuff in here now */
1339
1340					foreach($CreditLine->SerialItems as $Item){
1341
1342						/*1st off check if StockSerialItems already exists */
1343						$SQL = "SELECT COUNT(*)
1344								FROM stockserialitems
1345								WHERE stockid='" . $CreditLine->StockID . "'
1346								AND loccode='" . $_SESSION['CreditItems'.$identifier]->Location . "'
1347								AND serialno='" . $Item->BundleRef . "'";
1348						$ErrMsg = _('CRITICAL ERROR') . '! ' . _('NOTE DOWN THIS ERROR AND SEEK ASSISTANCE') . ': ' . _('The existence of the serial stock item record could not be determined because');
1349						$DbgMsg = _('The following SQL to find out if the serial stock item record existed already was used');
1350						$Result = DB_query($SQL, $ErrMsg, $DbgMsg, true);
1351						$myrow = DB_fetch_row($Result);
1352
1353						if ($myrow[0]==0) {
1354						/*The StockSerialItem record didnt exist
1355						so insert a new record */
1356							$SQL = "INSERT INTO stockserialitems ( stockid,
1357																loccode,
1358																serialno,
1359																quantity)
1360																VALUES (
1361																'" . $CreditLine->StockID . "',
1362																'" . $_SESSION['CreditItems'.$identifier]->Location . "',
1363																'" . $Item->BundleRef . "',
1364																'" . $Item->BundleQty . "'
1365																)";
1366
1367							$ErrMsg = _('CRITICAL ERROR') . '! ' . _('NOTE DOWN THIS ERROR AND SEEK ASSISTANCE') . ': ' . _('The new serial stock item record could not be inserted because');
1368							$DbgMsg = _('The following SQL to insert the new serial stock item record was used') ;
1369							$Result = DB_query($SQL, $ErrMsg, $DbgMsg, true);
1370						} else { /*Update the existing StockSerialItems record */
1371							$SQL = "UPDATE stockserialitems SET quantity= quantity + " . $Item->BundleQty . "
1372									WHERE stockid='" . $CreditLine->StockID . "'
1373									AND loccode='" . $_SESSION['CreditItems'.$identifier]->Location . "'
1374									AND serialno='" . $Item->BundleRef . "'";
1375
1376							$ErrMsg = _('CRITICAL ERROR') . '! ' . _('NOTE DOWN THIS ERROR AND SEEK ASSISTANCE') . ': ' . _('The serial stock item record could not be updated because');
1377							$DbgMsg = _('The following SQL to update the serial stock item record was used');
1378							$Result = DB_query($SQL, $ErrMsg, $DbgMsg, true);
1379						}
1380						/* now insert the serial stock movement */
1381
1382						$SQL = "INSERT INTO stockserialmoves ( stockmoveno,
1383															stockid,
1384															serialno,
1385															moveqty)
1386														VALUES (
1387															'" . $StkMoveNo . "',
1388															'" . $CreditLine->StockID . "',
1389															'" . $Item->BundleRef . "',
1390															'" . $Item->BundleQty . "')";
1391						$ErrMsg = _('CRITICAL ERROR') . '! ' . _('NOTE DOWN THIS ERROR AND SEEK ASSISTANCE') . ': ' . _('The serial stock movement record could not be inserted because');
1392						$DbgMsg = _('The following SQL to insert the serial stock movement record was used');
1393						$Result = DB_query($SQL, $ErrMsg, $DbgMsg, true);
1394
1395					}/* foreach serial item in the serialitems array */
1396
1397				} /*end if the credit line is a controlled item */
1398
1399			    }/*End of its a return or a write off */
1400
1401			    if ($_POST['CreditType']=='Return'){
1402
1403				/* Update location stock records if not a dummy stock item */
1404
1405				if ($CreditLine->MBflag=='B' OR $CreditLine->MBflag=='M') {
1406
1407					$SQL = "UPDATE locstock
1408							SET locstock.quantity = locstock.quantity + " . $CreditLine->Quantity . "
1409							WHERE locstock.stockid = '" . $CreditLine->StockID . "'
1410							AND locstock.loccode = '" . $_SESSION['CreditItems'.$identifier]->Location . "'";
1411
1412					$ErrMsg = _('CRITICAL ERROR') . '! ' . _('NOTE DOWN THIS ERROR AND SEEK ASSISTANCE') . ': ' . _('Location stock record could not be updated because');
1413					$DbgMsg = _('The following SQL to update the location stock record was used');
1414					$Result = DB_query($SQL,$ErrMsg,$DbgMsg,true);
1415
1416				} else if ($CreditLine->MBflag=='A'){ /* its an assembly */
1417					/*Need to get the BOM for this part and make stock moves
1418					for the componentsand of course update the Location stock
1419					balances for all the components*/
1420
1421					$StandardCost =0; /*To start with then accumulate the cost of the comoponents
1422								for use in journals later on */
1423
1424					$SQL = "SELECT bom.component,
1425									bom.quantity,
1426									stockmaster.materialcost+stockmaster.labourcost+stockmaster.overheadcost AS standard
1427							FROM bom INNER JOIN stockmaster
1428							ON bom.component=stockmaster.stockid
1429							WHERE bom.parent='" . $CreditLine->StockID . "'
1430                            AND bom.effectiveafter <= '" . date('Y-m-d') . "'
1431                            AND bom.effectiveto > '" . date('Y-m-d') . "'";
1432
1433					$ErrMsg =  _('Could not retrieve assembly components from the database for') . ' ' . $CreditLine->StockID . ' ' . _('because');
1434				 	$DbgMsg = _('The SQL that failed was');
1435					$AssResult = DB_query($SQL,$ErrMsg,$DbgMsg,true);
1436
1437					while ($AssParts = DB_fetch_array($AssResult)){
1438
1439						$StandardCost += $AssParts['standard'] * $AssParts['quantity'];
1440
1441/*Need to get the current location quantity will need it later for the stock movement */
1442					   	$SQL="SELECT locstock.quantity
1443						   		FROM locstock
1444								WHERE locstock.stockid='" . $AssParts['component'] . "'
1445								AND locstock.loccode= '" . $_SESSION['CreditItems'.$identifier]->Location . "'";
1446
1447        					$Result = DB_query($SQL);
1448						if (DB_num_rows($Result)==1){
1449							$LocQtyRow = DB_fetch_row($Result);
1450							$QtyOnHandPrior = $LocQtyRow[0];
1451						} else {
1452						/*There must actually be some error this should never happen */
1453							$QtyOnHandPrior = 0;
1454						}
1455
1456						/*Add stock movements for the assembly component items */
1457						$SQL = "INSERT INTO stockmoves (stockid,
1458														type,
1459														transno,
1460														loccode,
1461														trandate,
1462														userid,
1463														debtorno,
1464														branchcode,
1465														prd,
1466														reference,
1467														qty,
1468														standardcost,
1469														show_on_inv_crds,
1470														newqoh)
1471												VALUES (
1472													'" . $AssParts['component'] . "',
1473													11,
1474													'" . $CreditNo . "',
1475													'" . $_SESSION['CreditItems'.$identifier]->Location . "',
1476													'" . $SQLCreditDate . "',
1477													'" . $_SESSION['UserID'] . "',
1478													'" . $_SESSION['CreditItems'.$identifier]->DebtorNo . "',
1479													'" . $_SESSION['CreditItems'.$identifier]->Branch . "',
1480													'" . $PeriodNo . "',
1481													'" . _('Assembly') .': ' . $CreditLine->StockID . "',
1482													'" . $AssParts['quantity'] * $CreditLine->Quantity . "',
1483													'" . $AssParts['standard'] . "',
1484													0,
1485													'" . ($QtyOnHandPrior + ($AssParts['quantity'] * $CreditLine->Quantity)) . "'
1486													)";
1487
1488					$ErrMsg = _('CRITICAL ERROR') . '! ' . _('NOTE DOWN THIS ERROR AND SEEK ASSISTANCE') . ': ' . _('Stock movement records for the assembly components of') . ' ' . $CreditLine->StockID . ' ' . _('could not be inserted because');
1489					$DbgMsg = _('The following SQL to insert the assembly components stock movement records was used');
1490				        $Result = DB_query($SQL,$ErrMsg,$DbgMsg,true);
1491
1492					  /*Update the stock quantities for the assembly components */
1493					 $SQL = "UPDATE locstock
1494					   		SET locstock.quantity = locstock.quantity + " . $AssParts['quantity'] * $CreditLine->Quantity . "
1495							WHERE locstock.stockid = '" . $AssParts['component'] . "'
1496							AND locstock.loccode = '" . $_SESSION['CreditItems'.$identifier]->Location . "'";
1497
1498					$ErrMsg =  _('CRITICAL ERROR') . '! ' . _('NOTE DOWN THIS ERROR AND SEEK ASSISTANCE') . ': ' . _('Location stock record could not be updated for an assembly component because');
1499  					$DbgMsg =  _('The following SQL to update the component location stock record was used');
1500					$Result = DB_query($SQL,$ErrMsg, $DbgMsg,true);
1501				    } /* end of assembly explosion and updates */
1502
1503
1504				    /*Update the cart with the recalculated standard cost
1505				    from the explosion of the assembly's components*/
1506				    $_SESSION['CreditItems'.$identifier]->LineItems[$CreditLine->LineNumber]->StandardCost = $StandardCost;
1507				    $CreditLine->StandardCost = $StandardCost;
1508				}
1509				    /*end of its a return of stock */
1510			   } elseif ($_POST['CreditType']=='WriteOff'){ /*its a stock write off */
1511
1512			   	    if ($CreditLine->MBflag=='B' OR $CreditLine->MBflag=='M'){
1513			   		/* Insert stock movements for the
1514					item being written off - with unit cost */
1515				    	$SQL = "INSERT INTO stockmoves ( stockid,
1516													type,
1517													transno,
1518													loccode,
1519													trandate,
1520													userid,
1521													debtorno,
1522													branchcode,
1523													price,
1524													prd,
1525													qty,
1526													discountpercent,
1527													standardcost,
1528													reference,
1529													show_on_inv_crds,
1530													newqoh,
1531													narrative)
1532												VALUES (
1533													'" . $CreditLine->StockID . "',
1534													11,
1535													'" . $CreditNo . "',
1536													'" . $_SESSION['CreditItems'.$identifier]->Location . "',
1537													'" . $SQLCreditDate . "',
1538													'" . $_SESSION['UserID'] . "',
1539													'" . $_SESSION['CreditItems'.$identifier]->DebtorNo . "',
1540													'" . $_SESSION['CreditItems'.$identifier]->Branch . "',
1541													'" . $LocalCurrencyPrice . "',
1542													'" . $PeriodNo . "',
1543													'" . -$CreditLine->Quantity . "',
1544													'" . $CreditLine->DiscountPercent . "',
1545													'" . $CreditLine->StandardCost . "',
1546													'" . $_POST['CreditText'] . "',
1547													0,
1548													'" . $QtyOnHandPrior . "',
1549													'" . $CreditLine->Narrative . "'
1550													)";
1551
1552				    } else { /* its an assembly, so dont figure out the new qoh */
1553
1554					$SQL = "INSERT INTO stockmoves (stockid,
1555													type,
1556													transno,
1557													loccode,
1558													trandate,
1559													userid,
1560													debtorno,
1561													branchcode,
1562													price,
1563													prd,
1564													qty,
1565													discountpercent,
1566													standardcost,
1567													reference,
1568													show_on_inv_crds)
1569												VALUES (
1570													'" . $CreditLine->StockID . "',
1571													11,
1572													'" . $CreditNo . "',
1573													'" . $_SESSION['CreditItems'.$identifier]->Location . "',
1574													'" . $SQLCreditDate . "',
1575													'" . $_SESSION['UserID'] . "',
1576													'" . $_SESSION['CreditItems'.$identifier]->DebtorNo . "',
1577													'" . $_SESSION['CreditItems'.$identifier]->Branch . "',
1578													'" . $LocalCurrencyPrice . "',
1579													'" . $PeriodNo . "',
1580													'" . -$CreditLine->Quantity . "',
1581													'" . $CreditLine->DiscountPercent . "',
1582													'" . $CreditLine->StandardCost . "',
1583													'" . $_POST['CreditText'] . "',
1584													0)";
1585
1586				}
1587
1588     			$ErrMsg = _('CRITICAL ERROR') . '! ' . _('NOTE DOWN THIS ERROR AND SEEK ASSISTANCE') . ': ' . _('Stock movement record to write the stock off could not be inserted because');
1589				$DbgMsg = _('The following SQL to insert the stock movement to write off the stock was used');
1590				$Result = DB_query($SQL, $ErrMsg, $DbgMsg, true);
1591
1592				if (($CreditLine->MBflag=='M' OR $CreditLine->MBflag=='B') AND $CreditLine->Controlled==1){
1593					/*Its a write off too still so need to process the serial items
1594					written off */
1595
1596					$StkMoveNo = DB_Last_Insert_ID('stockmoves','stkmoveno');
1597
1598					foreach($CreditLine->SerialItems as $Item){
1599					/*no need to check StockSerialItems record exists
1600					it would have been added by the return stock movement above */
1601						$SQL = "UPDATE stockserialitems SET quantity= quantity - " . $Item->BundleQty . "
1602								WHERE stockid='" . $CreditLine->StockID . "'
1603								AND loccode='" . $_SESSION['CreditItems'.$identifier]->Location . "'
1604								AND serialno='" . $Item->BundleRef . "'";
1605
1606						$ErrMsg = _('CRITICAL ERROR') . '! ' . _('NOTE DOWN THIS ERROR AND SEEK ASSISTANCE') . ': ' . _('The serial stock item record could not be updated for the write off because');
1607						$DbgMsg = _('The following SQL to update the serial stock item record was used');
1608						$Result = DB_query($SQL, $ErrMsg, $DbgMsg, true);
1609
1610						/* now insert the serial stock movement */
1611
1612						$SQL = "INSERT INTO stockserialmoves ( stockmoveno,
1613															stockid,
1614															serialno,
1615															moveqty)
1616														VALUES (
1617															'" . $StkMoveNo . "',
1618															'" . $CreditLine->StockID . "',
1619															'" . $Item->BundleRef . "',
1620															'" . -$Item->BundleQty . "'
1621															)";
1622						$ErrMsg = _('CRITICAL ERROR') . '! ' . _('NOTE DOWN THIS ERROR AND SEEK ASSISTANCE') . ': ' . _('The serial stock movement record for the write off could not be inserted because');
1623						$DbgMsg = _('The following SQL to insert the serial stock movement write off record was used');
1624						$Result = DB_query($SQL, $ErrMsg, $DbgMsg, true);
1625
1626					}/* foreach serial item in the serialitems array */
1627
1628				} /*end if the credit line is a controlled item */
1629
1630   			} /*end if its a stock write off */
1631
1632/*Insert Sales Analysis records use links to the customer master and branch tables to ensure that if
1633the salesman or area has changed a new record is inserted for the customer and salesman of the new
1634set up. Considered just getting the area and salesman from the branch table but these can alter and the
1635sales analysis needs to reflect the sales made before and after the changes*/
1636
1637			$SalesValue = 0;
1638			if ($_SESSION['CurrencyRate']>0){
1639				$SalesValue = $CreditLine->Price * $CreditLine->Quantity / $_SESSION['CurrencyRate'];
1640			}
1641
1642			   $SQL="SELECT	COUNT(*),
1643							salesanalysis.stkcategory,
1644							salesanalysis.area
1645						FROM salesanalysis,
1646							custbranch,
1647							stockmaster
1648						WHERE salesanalysis.stkcategory=stockmaster.categoryid
1649						AND salesanalysis.stockid=stockmaster.stockid
1650						AND salesanalysis.cust=custbranch.debtorno
1651						AND salesanalysis.custbranch=custbranch.branchcode
1652						AND salesanalysis.area=custbranch.area
1653						AND salesanalysis.salesperson='" . $_SESSION['CreditItems'.$identifier]->SalesPerson . "'
1654						AND salesanalysis.typeabbrev ='" . $_SESSION['CreditItems'.$identifier]->DefaultSalesType . "'
1655						AND salesanalysis.periodno='" . $PeriodNo . "'
1656						AND salesanalysis.cust = '" . $_SESSION['CreditItems'.$identifier]->DebtorNo . "'
1657						AND salesanalysis.custbranch = '" . $_SESSION['CreditItems'.$identifier]->Branch . "'
1658						AND salesanalysis.stockid = '" . $CreditLine->StockID . "'
1659						AND salesanalysis.budgetoractual=1
1660						GROUP BY salesanalysis.stkcategory,
1661							salesanalysis.area,
1662							salesanalysis.salesperson";
1663
1664			$ErrMsg = _('The count to check for existing Sales analysis records could not run because');
1665			$DbgMsg = _('SQL to count the no of sales analysis records');
1666			$Result = DB_query($SQL, $ErrMsg, $DbgMsg, true);
1667
1668			$myrow = DB_fetch_array($Result);
1669
1670			if ($myrow[0]>0){  /*Update the existing record that already exists */
1671
1672				if ($_POST['CreditType']=='ReverseOverCharge'){
1673
1674					/*No updates to qty or cost data */
1675
1676					$SQL = "UPDATE salesanalysis SET amt=amt-" . $SalesValue . ",
1677													disc=disc-" . $CreditLine->DiscountPercent * $SalesValue . "
1678							WHERE salesanalysis.area='" . $myrow['area'] . "'
1679							AND salesanalysis.salesperson='" . $_SESSION['CreditItems'.$identifier]->SalesPerson . "'
1680							AND salesanalysis.typeabbrev ='" . $_SESSION['CreditItems'.$identifier]->DefaultSalesType . "'
1681							AND salesanalysis.periodno = '" . $PeriodNo . "'
1682							AND salesanalysis.cust = '" . $_SESSION['CreditItems'.$identifier]->DebtorNo . "'
1683							AND salesanalysis.custbranch = '" . $_SESSION['CreditItems'.$identifier]->Branch . "'
1684							AND salesanalysis.stockid = '" . $CreditLine->StockID . "'
1685							AND salesanalysis.stkcategory ='" . $myrow['stkcategory'] . "'
1686							AND salesanalysis.budgetoractual=1";
1687
1688				} else {
1689
1690					$SQL = "UPDATE salesanalysis SET Amt=Amt-" . $SalesValue . ",
1691													Cost=Cost-" . $CreditLine->StandardCost * $CreditLine->Quantity . ",
1692													Qty=Qty-" . $CreditLine->Quantity . ",
1693													Disc=Disc-" . $CreditLine->DiscountPercent * $SalesValue . "
1694							WHERE salesanalysis.area='" . $myrow['area'] . "'
1695							AND salesanalysis.salesperson='" . $_SESSION['CreditItems'.$identifier]->SalesPerson . "'
1696							AND salesanalysis.typeabbrev ='" . $_SESSION['CreditItems'.$identifier]->DefaultSalesType . "'
1697							AND salesanalysis.periodno = '" . $PeriodNo . "'
1698							AND salesanalysis.cust = '" . $_SESSION['CreditItems'.$identifier]->DebtorNo . "'
1699							AND salesanalysis.custbranch = '" . $_SESSION['CreditItems'.$identifier]->Branch . "'
1700							AND salesanalysis.stockid = '" . $CreditLine->StockID . "'
1701							AND salesanalysis.stkcategory ='" . $myrow['stkcategory'] . "'
1702							AND salesanalysis.budgetoractual=1";
1703				}
1704
1705			   } else { /* insert a new sales analysis record */
1706
1707		   		if ($_POST['CreditType']=='ReverseOverCharge'){
1708
1709					$SQL = "INSERT salesanalysis (typeabbrev,
1710												periodno,
1711												amt,
1712												cust,
1713												custbranch,
1714												qty,
1715												disc,
1716												stockid,
1717												area,
1718												budgetoractual,
1719												salesperson,
1720												stkcategory)
1721										 SELECT '" . $_SESSION['CreditItems'.$identifier]->DefaultSalesType . "',
1722												'" . $PeriodNo . "',
1723												'" . -$SalesValue . "',
1724												'" . $_SESSION['CreditItems'.$identifier]->DebtorNo . "',
1725												'" . $_SESSION['CreditItems'.$identifier]->Branch . "',
1726												0,
1727												'" . -$CreditLine->DiscountPercent * $SalesValue . "',
1728												'" . $CreditLine->StockID . "',
1729												custbranch.area,
1730												1,
1731												'" . $_SESSION['CreditItems'.$identifier]->SalesPerson . "',
1732												stockmaster.categoryid
1733										FROM stockmaster, custbranch
1734										WHERE stockmaster.stockid = '" . $CreditLine->StockID . "'
1735										AND custbranch.debtorno = '" . $_SESSION['CreditItems'.$identifier]->DebtorNo . "'
1736										AND custbranch.branchcode='" . $_SESSION['CreditItems'.$identifier]->Branch . "'";
1737
1738				} else {
1739
1740				    $SQL = "INSERT salesanalysis ( typeabbrev,
1741												periodno,
1742												amt,
1743												cost,
1744												cust,
1745												custbranch,
1746												qty,
1747												disc,
1748												stockid,
1749												area,
1750												budgetoractual,
1751												salesperson,
1752												stkcategory)
1753										SELECT '" . $_SESSION['CreditItems'.$identifier]->DefaultSalesType . "',
1754												'" . $PeriodNo . "',
1755												'" . -$SalesValue . "',
1756												'" . -$CreditLine->StandardCost * $CreditLine->Quantity . "',
1757												'" . $_SESSION['CreditItems'.$identifier]->DebtorNo . "',
1758												'" . $_SESSION['CreditItems'.$identifier]->Branch . "',
1759												'" . -$CreditLine->Quantity . "',
1760												'" . -$CreditLine->DiscountPercent * $SalesValue . "',
1761												'" . $CreditLine->StockID . "',
1762												custbranch.area,
1763												1,
1764												'" . $_SESSION['CreditItems'.$identifier]->SalesPerson . "',
1765												stockmaster.categoryid
1766										FROM stockmaster,
1767												custbranch
1768										WHERE stockmaster.stockid = '" . $CreditLine->StockID . "'
1769										AND custbranch.debtorno = '" . $_SESSION['CreditItems'.$identifier]->DebtorNo . "'
1770										AND custbranch.branchcode='" . $_SESSION['CreditItems'.$identifier]->Branch . "'";
1771				}
1772			}
1773
1774			$ErrMsg = _('The sales analysis record for this credit note could not be added because');
1775			$DbgMsg = _('The following SQL to insert the sales analysis record was used');
1776			$Result = DB_query($SQL,$ErrMsg, $DbgMsg, true);
1777
1778
1779/* If GLLink_Stock then insert GLTrans to either debit stock or an expense
1780depending on the valuve of $_POST['CreditType'] and then credit the cost of sales
1781at standard cost*/
1782
1783			   if ($_SESSION['CompanyRecord']['gllink_stock']==1
1784			   	AND $CreditLine->StandardCost !=0
1785				AND $_POST['CreditType']!='ReverseOverCharge'){
1786
1787/*first reverse credit the cost of sales entry*/
1788				  $COGSAccount = GetCOGSGLAccount($Area,
1789				  					$CreditLine->StockID,
1790									$_SESSION['CreditItems'.$identifier]->DefaultSalesType);
1791
1792				  $SQL = "INSERT INTO gltrans (type,
1793											typeno,
1794											trandate,
1795											periodno,
1796											account,
1797											narrative,
1798											amount)
1799										VALUES (
1800											11,
1801											'" . $CreditNo . "',
1802											'" . $SQLCreditDate . "',
1803											'" . $PeriodNo . "',
1804											'" . $COGSAccount . "',
1805											'" . $_SESSION['CreditItems'.$identifier]->DebtorNo . " - " . $CreditLine->StockID . " x " . $CreditLine->Quantity . " @ " . $CreditLine->StandardCost . "',
1806											'" . ($CreditLine->StandardCost * -$CreditLine->Quantity) . "')";
1807
1808				$ErrMsg = _('CRITICAL ERROR') . '! ' . _('NOTE DOWN THIS ERROR AND SEEK ASSISTANCE') . ': ' . _('The cost of the stock credited GL posting could not be inserted because');
1809				$DbgMsg = _('The following SQL to insert the GLTrans record was used');
1810				$Result = DB_query($SQL, $ErrMsg, $DbgMsg, true);
1811
1812
1813				if ($_POST['CreditType']=='WriteOff'){
1814
1815/* The double entry required is to reverse the cost of sales entry as above
1816then debit the expense account the stock is to written off to */
1817
1818					$SQL = "INSERT INTO gltrans (type,
1819												typeno,
1820												trandate,
1821												periodno,
1822												account,
1823												narrative,
1824												amount)
1825								VALUES (11,
1826										'" . $CreditNo . "',
1827										'" . $SQLCreditDate . "',
1828										'" . $PeriodNo . "',
1829										'" . $_POST['WriteOffGLCode'] . "',
1830										'" . $_SESSION['CreditItems'.$identifier]->DebtorNo . " - " . $CreditLine->StockID . " x " . $CreditLine->Quantity . " @ " . $CreditLine->StandardCost . "',
1831										'" . ($CreditLine->StandardCost * $CreditLine->Quantity) . "'
1832										)";
1833
1834					$ErrMsg = _('CRITICAL ERROR') . '! ' . _('NOTE DOWN THIS ERROR AND SEEK ASSISTANCE') . ': ' . _('The cost of the stock credited GL posting could not be inserted because');
1835					$DbgMsg = _('The following SQL to insert the GLTrans record was used');
1836					$Result = DB_query($SQL, $ErrMsg, $DbgMsg, true);
1837				    } else {
1838
1839/*the goods are coming back into stock so debit the stock account*/
1840					$StockGLCode = GetStockGLCode($CreditLine->StockID);
1841					$SQL = "INSERT INTO gltrans (type,
1842												typeno,
1843												trandate,
1844												periodno,
1845												account,
1846												narrative,
1847												amount)
1848										VALUES (11,
1849											'" . $CreditNo . "',
1850											'" . $SQLCreditDate . "',
1851											'" . $PeriodNo . "',
1852											'" . $StockGLCode['stockact'] . "',
1853											'" . $_SESSION['CreditItems'.$identifier]->DebtorNo . " - " . $CreditLine->StockID . " x " . $CreditLine->Quantity . " @ " . $CreditLine->StandardCost . "',
1854											'" . ($CreditLine->StandardCost * $CreditLine->Quantity) . "'
1855											)";
1856
1857					$ErrMsg = _('CRITICAL ERROR') . '! ' . _('NOTE DOWN THIS ERROR AND SEEK ASSISTANCE') . ': ' . _('The stock side (or write off) of the cost of sales GL posting could not be inserted because');
1858					$DbgMsg = _('The following SQL to insert the GLTrans record was used');
1859					$Result = DB_query($SQL, $ErrMsg, $DbgMsg, true);
1860				    }
1861
1862				} /* end of if GL and stock integrated and standard cost !=0 */
1863
1864				if ($_SESSION['CompanyRecord']['gllink_debtors']==1 AND $CreditLine->Price !=0){
1865
1866//Post sales transaction to GL credit sales
1867				    $SalesGLAccounts = GetSalesGLAccount($Area,
1868				    						$CreditLine->StockID,
1869										$_SESSION['CreditItems'.$identifier]->DefaultSalesType);
1870
1871					$SQL = "INSERT INTO gltrans (type,
1872												typeno,
1873												trandate,
1874												periodno,
1875												account,
1876												narrative,
1877												amount)
1878										VALUES (11,
1879											'" . $CreditNo . "',
1880											'" . $SQLCreditDate . "',
1881											'" . $PeriodNo . "',
1882											'" . $SalesGLAccounts['salesglcode'] . "',
1883											'" . $_SESSION['CreditItems'.$identifier]->DebtorNo . " - " . $CreditLine->StockID . " x " . $CreditLine->Quantity . " @ " . $CreditLine->Price . "',
1884											'" . (($CreditLine->Price * $CreditLine->Quantity)/$_SESSION['CurrencyRate']) . "'
1885											)";
1886
1887					$ErrMsg = _('CRITICAL ERROR') . '! ' . _('NOTE DOWN THIS ERROR AND SEEK ASSISTANCE') . ': ' . _('The credit note GL posting could not be inserted because');
1888					$DbgMsg = _('The following SQL to insert the GLTrans record was used');
1889					$Result = DB_query($SQL, $ErrMsg, $DbgMsg, true);
1890
1891					if ($CreditLine->DiscountPercent !=0){
1892
1893						$SQL = "INSERT INTO gltrans (type,
1894													typeno,
1895													trandate,
1896													periodno,
1897													account,
1898													narrative,
1899													amount)
1900									VALUES (11,
1901										'" . $CreditNo . "',
1902										'" . $SQLCreditDate . "',
1903										'" . $PeriodNo . "',
1904										'" . $SalesGLAccounts['discountglcode'] . "',
1905										'" . $_SESSION['CreditItems'.$identifier]->DebtorNo . " - " . $CreditLine->StockID . " @ " . ($CreditLine->DiscountPercent * 100) . "%',
1906										'" . -(($CreditLine->Price * $CreditLine->Quantity * $CreditLine->DiscountPercent)/$_SESSION['CurrencyRate']) . "'
1907										)";
1908
1909
1910						$ErrMsg = _('CRITICAL ERROR') . '! ' . _('NOTE DOWN THIS ERROR AND SEEK ASSISTANCE') . ': ' . _('The credit note discount GL posting could not be inserted because');
1911						$DbgMsg = _('The following SQL to insert the GLTrans record was used');
1912						$Result = DB_query($SQL, $ErrMsg, $DbgMsg, true);
1913					}/* end of if discount not equal to 0 */
1914				} /*end of if sales integrated with debtors */
1915		  } /*Quantity credited is more than 0 */
1916	} /*end of CreditLine loop */
1917
1918
1919	if ($_SESSION['CompanyRecord']['gllink_debtors']==1){
1920
1921/*Post credit note transaction to GL credit debtors, debit freight re-charged and debit sales */
1922		if (($_SESSION['CreditItems'.$identifier]->total + $_SESSION['CreditItems'.$identifier]->FreightCost + $TaxTotal) !=0) {
1923			$SQL = "INSERT INTO gltrans (type,
1924										typeno,
1925										trandate,
1926										periodno,
1927										account,
1928										narrative,
1929										amount)
1930							VALUES (11,
1931								'" . $CreditNo . "',
1932								'" . $SQLCreditDate . "',
1933								'" . $PeriodNo . "',
1934								'" . $_SESSION['CompanyRecord']['debtorsact'] . "',
1935								'" . $_SESSION['CreditItems'.$identifier]->DebtorNo . "',
1936								'" . -(($_SESSION['CreditItems'.$identifier]->total + $_SESSION['CreditItems'.$identifier]->FreightCost + $TaxTotal)/$_SESSION['CurrencyRate']) . "')";
1937
1938			$ErrMsg = _('CRITICAL ERROR') . '! ' . _('NOTE DOWN THIS ERROR AND SEEK ASSISTANCE') . ': ' . _('The total debtor GL posting for the credit note could not be inserted because');
1939			$DbgMsg = _('The following SQL to insert the GLTrans record was used');
1940			$Result = DB_query($SQL, $ErrMsg, $DbgMsg, true);
1941		}
1942		if ($_SESSION['CreditItems'.$identifier]->FreightCost !=0) {
1943			$SQL = "INSERT INTO gltrans (type,
1944										typeno,
1945										trandate,
1946										periodno,
1947										account,
1948										narrative,
1949										amount)
1950							VALUES (11,
1951								'" . $CreditNo . "',
1952								'" . $SQLCreditDate . "',
1953								'" . $PeriodNo . "',
1954								'" . $_SESSION['CompanyRecord']['freightact'] . "',
1955								'" . $_SESSION['CreditItems'.$identifier]->DebtorNo . "',
1956								'" . ($_SESSION['CreditItems'.$identifier]->FreightCost/$_SESSION['CurrencyRate']) . "')";
1957
1958			$ErrMsg = _('CRITICAL ERROR') . '! ' . _('NOTE DOWN THIS ERROR AND SEEK ASSISTANCE') . ': ' . _('The freight GL posting for this credit note could not be inserted because');
1959			$DbgMsg = _('The following SQL to insert the GLTrans record was used');
1960			$Result = DB_query($SQL, $ErrMsg, $DbgMsg, true);
1961		}
1962		foreach ( $TaxTotals as $TaxAuthID => $TaxAmount){
1963			if ($TaxAmount !=0 ){
1964				$SQL = "INSERT INTO gltrans (type,
1965											typeno,
1966											trandate,
1967											periodno,
1968											account,
1969											narrative,
1970											amount )
1971										VALUES (11,
1972											'" . $CreditNo . "',
1973											'" . $SQLCreditDate . "',
1974											'" . $PeriodNo . "',
1975											'" . $TaxGLCodes[$TaxAuthID] . "',
1976											'" . $_SESSION['CreditItems'.$identifier]->DebtorNo . "',
1977											'" . ($TaxAmount/$_SESSION['CurrencyRate']) . "')";
1978
1979				$ErrMsg = _('CRITICAL ERROR') . '! ' . _('NOTE DOWN THIS ERROR AND SEEK ASSISTANCE') . ': ' . _('The tax GL posting could not be inserted because');
1980				$DbgMsg = _('The following SQL to insert the GLTrans record was used');
1981				$Result = DB_query($SQL,$ErrMsg,$DbgMsg,true);
1982			}
1983		}
1984
1985		EnsureGLEntriesBalance(11,$CreditNo);
1986
1987	} /*end of if Sales and GL integrated */
1988
1989	DB_Txn_Commit();
1990
1991	 unset($_SESSION['CreditItems'.$identifier]->LineItems);
1992	 unset($_SESSION['CreditItems'.$identifier]);
1993
1994	 echo _('Credit Note number') . ' ' . $CreditNo . ' ' . _('processed') . '<br />';
1995	 echo '<a target="_blank" href="' . $RootPath . '/PrintCustTrans.php?FromTransNo=' . $CreditNo . '&InvOrCredit=Credit">' . _('Show this Credit Note on screen') . '</a><br />';
1996	if ($_SESSION['InvoicePortraitFormat']==0){
1997	 	echo '<a href="' . $RootPath . '/PrintCustTrans.php?FromTransNo=' . $CreditNo . '&InvOrCredit=Credit&PrintPDF=True">' . _('Print this Credit Note') . '</a>';
1998	} else {
1999		echo '<a href="' . $RootPath . '/PrintCustTransPortrait.php?FromTransNo=' . $CreditNo . '&InvOrCredit=Credit&PrintPDF=True">' . _('Print this Credit Note') . '</a>';
2000	}
2001	 echo '<br /><a href="' . $RootPath . '/SelectCreditItems.php">' . _('Enter Another Credit Note') . '</a>';
2002
2003} /*end of process credit note */
2004
2005include('includes/footer.php');
2006?>
2007