1<?php
2// PO_Items.php
3// Entry of a purchase order items - allows entry of items with lookup of currency cost from Purchasing Data previously entered also allows entry of nominal items against a general ledger code if the AP is integrated to the GL.
4
5
6include('includes/DefinePOClass.php');
7include('includes/SQL_CommonFunctions.inc');
8
9/* Session started in header.php for password checking
10 * and authorisation level check
11 */
12include('includes/session.php');
13
14$Title = _('Purchase Order Items');
15
16$identifier=$_GET['identifier'];
17
18/* If a purchase order header doesn't exist, then go to
19 * PO_Header.php to create one
20 */
21
22if (!isset($_SESSION['PO'.$identifier])){
23	header('Location:' . $RootPath . '/PO_Header.php');
24	exit;
25}
26
27/* webERP manual links before header.php */
28$ViewTopic= 'PurchaseOrdering';
29$BookMark = 'PurchaseOrdering';
30include('includes/header.php');
31
32if (!isset($_POST['Commit'])) {
33	echo '<a href="'.$RootPath.'/PO_Header.php?identifier=' . $identifier. '">' ._('Back To Purchase Order Header') . '</a><br />';
34}
35
36if (isset($_POST['UpdateLines']) OR isset($_POST['Commit'])) {
37	foreach ($_SESSION['PO'.$identifier]->LineItems as $POLine) {
38		if ($POLine->Deleted == false) {
39			if (!is_numeric(filter_number_format($_POST['ConversionFactor'.$POLine->LineNo]))){
40				prnMsg(_('The conversion factor is expected to be numeric - the figure which converts from our units to the supplier units. e.g. if the supplier units is a tonne and our unit is a kilogram then the conversion factor that converts our unit to the suppliers unit is 1000'),'error');
41				$_SESSION['PO'.$identifier]->LineItems[$POLine->LineNo]->ConversionFactor = 1;
42			} else { //a valid number for the conversion factor is entered
43				$_SESSION['PO'.$identifier]->LineItems[$POLine->LineNo]->ConversionFactor = filter_number_format($_POST['ConversionFactor'.$POLine->LineNo]);
44			}
45			if (!is_numeric(filter_number_format($_POST['SuppQty'.$POLine->LineNo]))){
46				prnMsg(_('The quantity in the supplier units is expected to be numeric. Please re-enter as a number'),'error');
47			} else { //ok to update the PO object variables
48				$_SESSION['PO'.$identifier]->LineItems[$POLine->LineNo]->Quantity = round(filter_number_format($_POST['SuppQty'.$POLine->LineNo])*$_SESSION['PO'.$identifier]->LineItems[$POLine->LineNo]->ConversionFactor,$_SESSION['PO'.$identifier]->LineItems[$POLine->LineNo]->DecimalPlaces);
49			}
50			if (!is_numeric(filter_number_format($_POST['SuppPrice'.$POLine->LineNo]))){
51				prnMsg(_('The supplier price is expected to be numeric. Please re-enter as a number'),'error');
52			} else { //ok to update the PO object variables
53				$_SESSION['PO'.$identifier]->LineItems[$POLine->LineNo]->Price = filter_number_format($_POST['SuppPrice'.$POLine->LineNo])/$_SESSION['PO'.$identifier]->LineItems[$POLine->LineNo]->ConversionFactor;
54			}
55			$_SESSION['PO'.$identifier]->LineItems[$POLine->LineNo]->ReqDelDate = $_POST['ReqDelDate'.$POLine->LineNo];
56            $_SESSION['PO'.$identifier]->LineItems[$POLine->LineNo]->ItemDescription = $_POST['ItemDescription'.$POLine->LineNo];
57		}
58	}
59}
60
61if (isset($_POST['Commit'])){ /*User wishes to commit the order to the database */
62
63/*First do some validation
64 *Is the delivery information all entered
65 */
66	$InputError=0; /*Start off assuming the best */
67	if ($_SESSION['PO'.$identifier]->DelAdd1=='' or mb_strlen($_SESSION['PO'.$identifier]->DelAdd1)<3){
68		prnMsg( _('The purchase order cannot be committed to the database because there is no delivery street address specified'),'error');
69		$InputError=1;
70	} elseif ($_SESSION['PO'.$identifier]->Location=='' or ! isset($_SESSION['PO'.$identifier]->Location)){
71		prnMsg( _('The purchase order can not be committed to the database because there is no location specified to book any stock items into'),'error');
72		$InputError=1;
73	} elseif ($_SESSION['PO'.$identifier]->LinesOnOrder <=0){
74		prnMsg( _('The purchase order can not be committed to the database because there are no lines entered on this order'),'error');
75		$InputError=1;
76	}
77
78/*If all clear then proceed to update the database
79 */
80	if ($InputError!=1){
81
82		$result = DB_Txn_Begin();
83
84		/*figure out what status to set the order to */
85		if (IsEmailAddress($_SESSION['UserEmail'])){
86			$UserDetails  = ' <a href="mailto:' . $_SESSION['UserEmail'] . '">' . $_SESSION['UsersRealName']. '</a>';
87		} else {
88			$UserDetails  = ' ' . $_SESSION['UsersRealName'] . ' ';
89		}
90		if ($_SESSION['AutoAuthorisePO']==1) {
91			//if the user has authority to authorise the PO then it will automatically be authorised
92			$AuthSQL ="SELECT authlevel
93						FROM purchorderauth
94						WHERE userid='".$_SESSION['UserID']."'
95						AND currabrev='".$_SESSION['PO'.$identifier]->CurrCode."'";
96
97			$AuthResult=DB_query($AuthSQL);
98			$AuthRow=DB_fetch_array($AuthResult);
99
100			if (DB_num_rows($AuthResult) > 0 AND $AuthRow['authlevel'] > $_SESSION['PO'.$identifier]->Order_Value()) { //user has authority to authrorise as well as create the order
101				$StatusComment=date($_SESSION['DefaultDateFormat']).' - ' . _('Order Created and Authorised by') . $UserDetails . '<br />' .  $_SESSION['PO'.$identifier]->StatusComments . '<br />';
102				$_SESSION['PO'.$identifier]->AllowPrintPO=1;
103				$_SESSION['PO'.$identifier]->Status = 'Authorised';
104			} else { // no authority to authorise this order
105				if (DB_num_rows($AuthResult) ==0){
106					$AuthMessage = _('Your authority to approve purchase orders in') . ' ' . $_SESSION['PO'.$identifier]->CurrCode . ' ' . _('has not yet been set up') . '<br />';
107				} else {
108					$AuthMessage = _('You can only authorise up to').' '.$_SESSION['PO'.$identifier]->CurrCode.' '.$AuthRow['authlevel'] .'.<br />';
109				}
110
111				prnMsg( _('You do not have permission to authorise this purchase order').'.<br />' .  _('This order is for').' '.
112					$_SESSION['PO'.$identifier]->CurrCode . ' '. $_SESSION['PO'.$identifier]->Order_Value() .'. '.
113					$AuthMessage .
114					_('If you think this is a mistake please contact the systems administrator') . '<br />' .
115					_('The order will be created with a status of pending and will require authorisation'), 'warn');
116
117				$_SESSION['PO'.$identifier]->AllowPrintPO=0;
118				$StatusComment=date($_SESSION['DefaultDateFormat']).' - ' . _('Order Created by') . $UserDetails . '<br />' . $_SESSION['PO'.$identifier]->StatusComments . '<br />';
119				$_SESSION['PO'.$identifier]->Status = 'Pending';
120			}
121		} else { //auto authorise is set to off
122			$_SESSION['PO'.$identifier]->AllowPrintPO=0;
123			$StatusComment=date($_SESSION['DefaultDateFormat']).' - ' . _('Order Created by') . $UserDetails . ' - '.$_SESSION['PO'.$identifier]->StatusComments . '<br />';
124			$_SESSION['PO'.$identifier]->Status = 'Pending';
125		}
126
127		if ($_SESSION['ExistingOrder']==0){ /*its a new order to be inserted */
128
129			/*Get the order number */
130			$_SESSION['PO'.$identifier]->OrderNo =  GetNextTransNo(18);
131
132			/*Insert to purchase order header record */
133			$sql = "INSERT INTO purchorders ( orderno,
134											supplierno,
135											comments,
136											orddate,
137											rate,
138											initiator,
139											requisitionno,
140											intostocklocation,
141											deladd1,
142											deladd2,
143											deladd3,
144											deladd4,
145											deladd5,
146											deladd6,
147											tel,
148											suppdeladdress1,
149											suppdeladdress2,
150											suppdeladdress3,
151											suppdeladdress4,
152											suppdeladdress5,
153											suppdeladdress6,
154											suppliercontact,
155											supptel,
156											contact,
157											version,
158											revised,
159											deliveryby,
160											status,
161											stat_comment,
162											deliverydate,
163											paymentterms,
164											allowprint)
165							VALUES(	'" . $_SESSION['PO'.$identifier]->OrderNo . "',
166									'" . $_SESSION['PO'.$identifier]->SupplierID . "',
167									'" . $_SESSION['PO'.$identifier]->Comments . "',
168									'" . Date('Y-m-d') . "',
169									'" . $_SESSION['PO'.$identifier]->ExRate . "',
170									'" . $_SESSION['PO'.$identifier]->Initiator . "',
171									'" . $_SESSION['PO'.$identifier]->RequisitionNo . "',
172									'" . $_SESSION['PO'.$identifier]->Location . "',
173									'" . $_SESSION['PO'.$identifier]->DelAdd1 . "',
174									'" . $_SESSION['PO'.$identifier]->DelAdd2 . "',
175									'" . $_SESSION['PO'.$identifier]->DelAdd3 . "',
176									'" . $_SESSION['PO'.$identifier]->DelAdd4 . "',
177									'" . $_SESSION['PO'.$identifier]->DelAdd5 . "',
178									'" . $_SESSION['PO'.$identifier]->DelAdd6 . "',
179									'" . $_SESSION['PO'.$identifier]->Tel . "',
180									'" . $_SESSION['PO'.$identifier]->SuppDelAdd1 . "',
181									'" . $_SESSION['PO'.$identifier]->SuppDelAdd2 . "',
182									'" . $_SESSION['PO'.$identifier]->SuppDelAdd3 . "',
183									'" . $_SESSION['PO'.$identifier]->SuppDelAdd4 . "',
184									'" . $_SESSION['PO'.$identifier]->SuppDelAdd5 . "',
185									'" . $_SESSION['PO'.$identifier]->SuppDelAdd6 . "',
186									'" . $_SESSION['PO'.$identifier]->SupplierContact . "',
187									'" . $_SESSION['PO'.$identifier]->SuppTel. "',
188									'" . $_SESSION['PO'.$identifier]->Contact . "',
189									'" . $_SESSION['PO'.$identifier]->Version . "',
190									'" . Date('Y-m-d') . "',
191									'" . $_SESSION['PO'.$identifier]->DeliveryBy . "',
192									'" . $_SESSION['PO'.$identifier]->Status . "',
193									'" . htmlspecialchars($StatusComment,ENT_QUOTES,'UTF-8') . "',
194									'" . FormatDateForSQL($_SESSION['PO'.$identifier]->DeliveryDate) . "',
195									'" . $_SESSION['PO'.$identifier]->PaymentTerms. "',
196									'" . $_SESSION['PO'.$identifier]->AllowPrintPO . "' )";
197
198			$ErrMsg =  _('The purchase order header record could not be inserted into the database because');
199			$DbgMsg = _('The SQL statement used to insert the purchase order header record and failed was');
200			$result = DB_query($sql,$ErrMsg,$DbgMsg,true);
201
202		     /*Insert the purchase order detail records */
203			foreach ($_SESSION['PO'.$identifier]->LineItems as $POLine) {
204				if ($POLine->Deleted==False) {
205					$sql = "INSERT INTO purchorderdetails (orderno,
206														itemcode,
207														deliverydate,
208														itemdescription,
209														glcode,
210														unitprice,
211														quantityord,
212														shiptref,
213														jobref,
214														suppliersunit,
215														suppliers_partno,
216														assetid,
217														conversionfactor )
218									VALUES ('" . $_SESSION['PO'.$identifier]->OrderNo . "',
219											'" . $POLine->StockID . "',
220											'" . FormatDateForSQL($POLine->ReqDelDate) . "',
221											'" . DB_escape_string($POLine->ItemDescription) . "',
222											'" . $POLine->GLCode . "',
223											'" . $POLine->Price . "',
224											'" . $POLine->Quantity . "',
225											'" . $POLine->ShiptRef . "',
226											'" . $POLine->JobRef . "',
227											'" . $POLine->SuppliersUnit . "',
228											'" . $POLine->Suppliers_PartNo . "',
229											'" . $POLine->AssetID . "',
230											'" . $POLine->ConversionFactor . "')";
231					$ErrMsg =_('One of the purchase order detail records could not be inserted into the database because');
232					$DbgMsg =_('The SQL statement used to insert the purchase order detail record and failed was');
233
234					$result =DB_query($sql,$ErrMsg,$DbgMsg,true);
235				}
236			} /* end of the loop round the detail line items on the order */
237			echo '<p />';
238			prnMsg(_('Purchase Order') . ' ' . $_SESSION['PO'.$identifier]->OrderNo . ' ' . _('on') . ' ' . $_SESSION['PO'.$identifier]->SupplierName . ' ' . _('has been created'),'success');
239                        if ($_SESSION['PO'.$identifier]->AllowPrintPO==1
240				AND ($_SESSION['PO'.$identifier]->Status=='Authorised'
241				OR $_SESSION['PO'.$identifier]->Status=='Printed')){
242
243			      echo '<br /><div class="centre"><a target="_blank" href="'.$RootPath.'/PO_PDFPurchOrder.php?OrderNo=' . $_SESSION['PO'.$identifier]->OrderNo . '">' . _('Print Purchase Order') . '</a></div>';
244			}
245
246		} else { /*its an existing order need to update the old order info */
247			/*Check to see if there are any incomplete lines on the order */
248			$Completed = true; //assume it is completed i.e. all lines are flagged as completed
249			foreach ($_SESSION['PO'.$identifier]->LineItems as $POLine) {
250				if ($POLine->Completed==0){
251					$Completed = false;
252					break;
253				}
254			}
255			if ($Completed){
256				$_SESSION['PO'.$identifier]->Status = 'Completed';
257				$_SESSION['PO'.$identifier]->StatusComments = date($_SESSION['DefaultDateFormat']).' - ' . _('Order completed by') . $UserDetails  . '<br />' . $_SESSION['PO'.$identifier]->StatusComments;
258			} else {
259				$_SESSION['PO'.$identifier]->StatusComments = date($_SESSION['DefaultDateFormat']).' - ' . _('Order modified by') . $UserDetails  . '<br />' . $_SESSION['PO'.$identifier]->StatusComments;
260			}
261		     /*Update the purchase order header with any changes */
262
263			$sql = "UPDATE purchorders SET supplierno = '" . $_SESSION['PO'.$identifier]->SupplierID . "' ,
264										comments='" . $_SESSION['PO'.$identifier]->Comments . "',
265										rate='" . $_SESSION['PO'.$identifier]->ExRate . "',
266										initiator='" . $_SESSION['PO'.$identifier]->Initiator . "',
267										requisitionno= '" . $_SESSION['PO'.$identifier]->RequisitionNo . "',
268										version= '" .  $_SESSION['PO'.$identifier]->Version . "',
269										deliveryby='" . $_SESSION['PO'.$identifier]->DeliveryBy . "',
270										deliverydate='" . FormatDateForSQL($_SESSION['PO'.$identifier]->DeliveryDate) . "',
271										revised= '" . Date('Y-m-d') . "',
272										intostocklocation='" . $_SESSION['PO'.$identifier]->Location . "',
273										deladd1='" . $_SESSION['PO'.$identifier]->DelAdd1 . "',
274										deladd2='" . $_SESSION['PO'.$identifier]->DelAdd2 . "',
275										deladd3='" . $_SESSION['PO'.$identifier]->DelAdd3 . "',
276										deladd4='" . $_SESSION['PO'.$identifier]->DelAdd4 . "',
277										deladd5='" . $_SESSION['PO'.$identifier]->DelAdd5 . "',
278										deladd6='" . $_SESSION['PO'.$identifier]->DelAdd6 . "',
279										tel='" . $_SESSION['PO'.$identifier]->Tel . "',
280										suppdeladdress1='" . $_SESSION['PO'.$identifier]->SuppDelAdd1 . "',
281										suppdeladdress2='" . $_SESSION['PO'.$identifier]->SuppDelAdd2 . "',
282										suppdeladdress3='" . $_SESSION['PO'.$identifier]->SuppDelAdd3 . "',
283										suppdeladdress4='" . $_SESSION['PO'.$identifier]->SuppDelAdd4 . "',
284										suppdeladdress5='" . $_SESSION['PO'.$identifier]->SuppDelAdd5 . "',
285										suppdeladdress6='" . $_SESSION['PO'.$identifier]->SuppDelAdd6 . "',
286										suppliercontact='" . $_SESSION['PO'.$identifier]->SupplierContact . "',
287										supptel='" . $_SESSION['PO'.$identifier]->SuppTel . "',
288										contact='" . $_SESSION['PO'.$identifier]->Contact . "',
289										paymentterms='" . $_SESSION['PO'.$identifier]->PaymentTerms . "',
290										allowprint='" . $_SESSION['PO'.$identifier]->AllowPrintPO . "',
291										status = '" . $_SESSION['PO'.$identifier]->Status . "',
292										stat_comment = '" . htmlspecialchars($_SESSION['PO'.$identifier]->StatusComments,ENT_QUOTES,'UTF-8') . "'
293										WHERE orderno = '" . $_SESSION['PO'.$identifier]->OrderNo ."'";
294
295			$ErrMsg =  _('The purchase order could not be updated because');
296			$DbgMsg = _('The SQL statement used to update the purchase order header record, that failed was');
297			$result = DB_query($sql,$ErrMsg,$DbgMsg,true);
298
299			/*Now Update the purchase order detail records */
300			foreach ($_SESSION['PO'.$identifier]->LineItems as $POLine) {
301
302				if ($POLine->Deleted==true) {
303					if ($POLine->PODetailRec!='') {
304						$sql="DELETE FROM purchorderdetails WHERE podetailitem='" . $POLine->PODetailRec . "'";
305						$ErrMsg =  _('The purchase order detail line could not be deleted because');
306						$DbgMsg = _('The SQL statement used to delete the purchase order detail record, that failed was');
307						$result = DB_query($sql,$ErrMsg,$DbgMsg,true);
308					}
309				} else if ($POLine->PODetailRec=='') {
310						/*When the purchase order line is an existing record the auto-increment
311						 * field PODetailRec is given to the session for that POLine
312						 * So it will only be a new POLine if PODetailRec is empty
313						*/
314					$sql = "INSERT INTO purchorderdetails ( orderno,
315														itemcode,
316														deliverydate,
317														itemdescription,
318														glcode,
319														unitprice,
320														quantityord,
321														shiptref,
322														jobref,
323														suppliersunit,
324														suppliers_partno,
325														assetid,
326														conversionfactor)
327													VALUES (
328														'" . $_SESSION['PO'.$identifier]->OrderNo . "',
329														'" . $POLine->StockID . "',
330														'" . FormatDateForSQL($POLine->ReqDelDate) . "',
331														'" . DB_escape_string($POLine->ItemDescription) . "',
332														'" . $POLine->GLCode . "',
333														'" . $POLine->Price . "',
334														'" . $POLine->Quantity . "',
335														'" . $POLine->ShiptRef . "',
336														'" . $POLine->JobRef . "',
337														'" . $POLine->SuppliersUnit . "',
338														'" . $POLine->Suppliers_PartNo . "',
339														'" . $POLine->AssetID . "',
340														'" . $POLine->ConversionFactor . "')";
341
342				} else {
343					if ($POLine->Quantity==$POLine->QtyReceived){
344						$sql = "UPDATE purchorderdetails SET itemcode='" . $POLine->StockID . "',
345															deliverydate ='" . FormatDateForSQL($POLine->ReqDelDate) . "',
346															itemdescription='" . DB_escape_string($POLine->ItemDescription) . "',
347															glcode='" . $POLine->GLCode . "',
348															unitprice='" . $POLine->Price . "',
349															quantityord='" . $POLine->Quantity . "',
350															shiptref='" . $POLine->ShiptRef . "',
351															jobref='" . $POLine->JobRef . "',
352															suppliersunit='" . $POLine->SuppliersUnit . "',
353															suppliers_partno='" . DB_escape_string($POLine->Suppliers_PartNo) . "',
354															completed=1,
355															assetid='" . $POLine->AssetID . "',
356															conversionfactor = '" . $POLine->ConversionFactor . "'
357								WHERE podetailitem='" . $POLine->PODetailRec . "'";
358					} else {
359						$sql = "UPDATE purchorderdetails SET itemcode='" . $POLine->StockID . "',
360															deliverydate ='" . FormatDateForSQL($POLine->ReqDelDate) . "',
361															itemdescription='" . DB_escape_string($POLine->ItemDescription) . "',
362															glcode='" . $POLine->GLCode . "',
363															unitprice='" . $POLine->Price . "',
364															quantityord='" . $POLine->Quantity . "',
365															shiptref='" . $POLine->ShiptRef . "',
366															jobref='" . $POLine->JobRef . "',
367															suppliersunit='" . $POLine->SuppliersUnit . "',
368															suppliers_partno='" . $POLine->Suppliers_PartNo . "',
369															assetid='" . $POLine->AssetID . "',
370															conversionfactor = '" . $POLine->ConversionFactor . "'
371								WHERE podetailitem='" . $POLine->PODetailRec . "'";
372					}
373				}
374
375				$ErrMsg = _('One of the purchase order detail records could not be updated because');
376				$DbgMsg = _('The SQL statement used to update the purchase order detail record that failed was');
377				$result =DB_query($sql,$ErrMsg,$DbgMsg,true);
378
379			} /* end of the loop round the detail line items on the order */
380			echo '<br /><br />';
381			prnMsg(_('Purchase Order') . ' ' . $_SESSION['PO'.$identifier]->OrderNo . ' ' . _('has been updated'),'success');
382			if ($_SESSION['PO'.$identifier]->AllowPrintPO==1
383					AND ($_SESSION['PO'.$identifier]->Status=='Authorised'
384					OR $_SESSION['PO'.$identifier]->Status=='Printed')){
385
386				echo '<br /><div class="centre"><a target="_blank" href="'.$RootPath.'/PO_PDFPurchOrder.php?OrderNo=' . $_SESSION['PO'.$identifier]->OrderNo . '">' . _('Print Purchase Order') . '</a></div>';
387			}
388
389		} /*end of if its a new order or an existing one */
390
391
392		$Result = DB_Txn_Commit();
393		/* Only show the link to auto receive the order if the user has permission to receive goods and permission to authorise and has authorised the order */
394		if ($_SESSION['PO'.$identifier]->Status == 'Authorised'
395                   AND in_array($_SESSION['PageSecurityArray']['GoodsReceived.php'], $_SESSION['AllowedPageSecurityTokens'])){
396
397                	echo '<a href="SupplierInvoice.php?SupplierID=' . $_SESSION['PO'.$identifier]->SupplierID . '&amp;ReceivePO=' . $_SESSION['PO'.$identifier]->OrderNo . '&amp;DeliveryDate=' . $_SESSION['PO'.$identifier]->DeliveryDate . '">' . _('Receive and Enter Purchase Invoice') . '</a>';
398		}
399
400		unset($_SESSION['PO'.$identifier]); /*Clear the PO data to allow a newy to be input*/
401		include('includes/footer.php');
402		exit;
403	} /*end if there were no input errors trapped */
404} /* end of the code to do transfer the PO object to the database  - user hit the place PO*/
405
406
407/* Always do the stuff below if not looking for a supplierid */
408
409if(isset($_GET['Delete'])){
410	if($_SESSION['PO'.$identifier]->Some_Already_Received($_GET['Delete'])==0){
411		$_SESSION['PO'.$identifier]->remove_from_order($_GET['Delete']);
412		include ('includes/PO_UnsetFormVbls.php');
413	} else {
414		prnMsg( _('This item cannot be deleted because some of it has already been received'),'warn');
415	}
416}
417
418if(isset($_GET['Complete'])){
419	$_SESSION['PO'.$identifier]->LineItems[$_GET['Complete']]->Completed=1;
420}
421
422if (isset($_POST['EnterLine'])){ /*Inputs from the form directly without selecting a stock item from the search */
423
424	$AllowUpdate = true; /*always assume the best */
425	if (!is_numeric(filter_number_format($_POST['Qty']))){
426		$AllowUpdate = false;
427		prnMsg( _('Cannot Enter this order line') . '<br />' . _('The quantity of the order item must be numeric'),'error');
428	}
429	if (filter_number_format($_POST['Qty'])<0){
430		$AllowUpdate = false;
431		prnMsg( _('Cannot Enter this order line') . '<br />' . _('The quantity of the ordered item entered must be a positive amount'),'error');
432	}
433	if (!is_numeric(filter_number_format($_POST['Price']))){
434		$AllowUpdate = false;
435		prnMsg( _('Cannot Enter this order line') . '<br />' . _('The price entered must be numeric'),'error');
436	}
437	if (!Is_Date($_POST['ReqDelDate'])){
438		$AllowUpdate = False;
439		prnMsg( _('Cannot Enter this order line') . '</b><br />' . _('The date entered must be in the format') . ' ' . $_SESSION['DefaultDateFormat'], 'error');
440	}
441
442 /*It's not a stock item
443  * need to check GL Code is valid if GLLink is active
444  * [icedlava] GL Code is required for non stock item variance in price vs purchase order when supplier invoice generated even if stock not linked to GL, but AP is else
445  * there will be an sql error  in SupplierInvoice.php without a valid GL Code
446	*/
447	if ($_SESSION['PO'.$identifier]->GLLink==1 OR $_SESSION['CompanyRecord']['gllink_creditors']==1){
448
449		$sql = "SELECT accountname
450				FROM chartmaster
451				WHERE accountcode ='" . $_POST['GLCode'] . "'";
452		$ErrMsg =  _('The account details for') . ' ' . $_POST['GLCode'] . ' ' . _('could not be retrieved because');
453		$DbgMsg =  _('The SQL used to retrieve the details of the account, but failed was');
454		$GLValidResult = DB_query($sql,$ErrMsg,$DbgMsg,false,false);
455		if (DB_error_no() !=0) {
456			$AllowUpdate = false;
457			prnMsg( _('The validation process for the GL Code entered could not be executed because') . ' ' . DB_error_msg(), 'error');
458			if ($debug==1){
459				prnMsg (_('The SQL used to validate the code entered was') . ' ' . $sql,'error');
460			}
461			include('includes/footer.php');
462			exit;
463		}
464		if (DB_num_rows($GLValidResult) == 0) { /*The GLCode entered does not exist */
465			$AllowUpdate = false;
466			prnMsg( _('Cannot enter this order line') . ':<br />' . _('The general ledger code') . ' - ' . $_POST['GLCode'] . ' ' . _('is not a general ledger code that is defined in the chart of accounts') . ' . ' . _('Please use a code that is already defined') . '. ' . _('See the Chart list from the link below'),'error');
467		} else {
468			$myrow = DB_fetch_row($GLValidResult);
469			$GLAccountName = $myrow[0];
470		}
471	} /* dont bother checking the GL Code if there is no GL code to check ie not linked to GL */
472	 else {
473		$_POST['GLCode']=0;
474	}
475	if ($_POST['AssetID'] !='Not an Asset'){
476		$ValidAssetResult = DB_query("SELECT assetid,
477											description,
478											costact
479										FROM fixedassets
480										INNER JOIN fixedassetcategories
481										ON fixedassets.assetcategoryid=fixedassetcategories.categoryid
482										WHERE assetid='" . $_POST['AssetID'] . "'");
483		if (DB_num_rows($ValidAssetResult)==0){ // then the asset id entered doesn't exist
484			$AllowUpdate = false;
485			prnMsg(_('An asset code was entered but it does not yet exist. Only pre-existing asset ids can be entered when ordering a fixed asset'),'error');
486		} else {
487			$AssetRow = DB_fetch_array($ValidAssetResult);
488			$_POST['GLCode'] = $AssetRow['costact'];
489			if ($_POST['ItemDescription']==''){
490				$_POST['ItemDescription'] = $AssetRow['description'];
491			}
492		}
493	} /*end if an AssetID is entered */
494	  else {
495		  $_POST['AssetID'] = 0; // cannot commit a string to an integer field so make it 0 if AssetID = 'Not an Asset'
496	}
497	if (mb_strlen($_POST['ItemDescription'])<=3){
498		$AllowUpdate = false;
499		prnMsg(_('Cannot enter this order line') . ':<br />' . _('The description of the item being purchased is required where a non-stock item is being ordered'),'warn');
500	}
501
502	if ($AllowUpdate == true){
503	//adding the non-stock item
504
505		$_SESSION['PO'.$identifier]->add_to_order($_SESSION['PO'.$identifier]->LinesOnOrder+1,
506												'',
507												0, /*Serialised */
508												0, /*Controlled */
509												filter_number_format($_POST['Qty']),
510												$_POST['ItemDescription'],
511												filter_number_format($_POST['Price']),
512												$_POST['SuppliersUnit'],
513												$_POST['GLCode'],
514												$_POST['ReqDelDate'],
515												'',
516												0,
517												'',
518												0,
519												0,
520												$GLAccountName,
521												2,
522												$_POST['SuppliersUnit'],
523												1,
524												1,
525												'',
526												$_POST['AssetID']);
527	   include ('includes/PO_UnsetFormVbls.php');
528	}
529}
530 /*end if Enter line button was hit - adding non stock items */
531
532//Add variables $_SESSION['PO_ItemsResubmitForm' . $identifier] and $_POST['PO_ItemsResubmitFormValue'] to prevent from page refreshing effect
533
534$_SESSION['PO_ItemsResubmitForm' . $identifier] = (empty($_SESSION['PO_ItemsResubmitForm' . $identifier]))? '1' : $_SESSION['PO_ItemsResubmitForm' . $identifier];
535if (isset($_POST['NewItem'])
536	AND !empty($_POST['PO_ItemsResubmitFormValue'])
537	AND $_SESSION['PO_ItemsResubmitForm' . $identifier] == $_POST['PO_ItemsResubmitFormValue']){ //only submit values can be processed
538
539	/* NewItem is set from the part selection list as the part code selected
540	* take the form entries and enter the data from the form into the PurchOrder class variable
541	* A series of form variables of the format "NewQty" with the ItemCode concatenated are created on the search for adding new
542	* items for each of these form variables need to parse out the item code and look up the details to add them to the purchase
543	* order  $_POST is of course the global array of all posted form variables
544	*/
545
546	foreach ($_POST as $FormVariableName => $Quantity) {
547		/*The form entity name is of the format NewQtyX where X is the index number that identifies the stock item code held in the hidden StockIDX form variable
548		 * */
549		if (mb_substr($FormVariableName, 0, 6)=='NewQty' AND filter_number_format($Quantity)!=0) { //if the form variable represents a Qty to add to the order
550
551			$ItemCode = $_POST['StockID' . mb_substr($FormVariableName, 6)];
552			$AlreadyOnThisOrder = 0;
553
554			if ($_SESSION['PO_AllowSameItemMultipleTimes'] ==false){
555				if (count($_SESSION['PO'.$identifier]->LineItems)!=0){
556
557					foreach ($_SESSION['PO'.$identifier]->LineItems AS $OrderItem) {
558
559					/* do a loop round the items on the order to see that the item is not already on this order */
560						if (($OrderItem->StockID == $ItemCode) AND ($OrderItem->Deleted==false)) {
561							$AlreadyOnThisOrder = 1;
562							prnMsg( _('The item') . ' ' . $ItemCode . ' ' . _('is already on this order') . '. ' . _('The system will not allow the same item on the order more than once') . '. ' . _('However you can change the quantity ordered of the existing line if necessary'),'error');
563						}
564					} /* end of the foreach loop to look for preexisting items of the same code */
565				}
566			}
567			if ($AlreadyOnThisOrder!=1 AND filter_number_format($Quantity) > 0){
568				$sql = "SELECT description,
569							longdescription,
570							stockid,
571							units,
572							decimalplaces,
573							stockact,
574							accountname
575						FROM stockmaster INNER JOIN stockcategory
576						ON stockcategory.categoryid = stockmaster.categoryid
577						INNER JOIN chartmaster
578						ON chartmaster.accountcode = stockcategory.stockact
579						WHERE  stockmaster.stockid = '". $ItemCode . "'";
580
581				$ErrMsg = _('The item details for') . ' ' . $ItemCode . ' ' . _('could not be retrieved because');
582				$DbgMsg = _('The SQL used to retrieve the item details but failed was');
583				$ItemResult = DB_query($sql,$ErrMsg,$DbgMsg);
584				if (DB_num_rows($ItemResult)==1){
585					$ItemRow = DB_fetch_array($ItemResult);
586
587					$sql = "SELECT price,
588								conversionfactor,
589								supplierdescription,
590								suppliersuom,
591								suppliers_partno,
592								leadtime,
593								MAX(purchdata.effectivefrom) AS latesteffectivefrom
594							FROM purchdata
595							WHERE purchdata.supplierno = '" . $_SESSION['PO'.$identifier]->SupplierID . "'
596							AND purchdata.effectivefrom <='" . Date('Y-m-d') . "'
597							AND purchdata.stockid = '". $ItemCode . "'
598							GROUP BY purchdata.price,
599									purchdata.conversionfactor,
600									purchdata.supplierdescription,
601									purchdata.suppliersuom,
602									purchdata.suppliers_partno,
603									purchdata.leadtime
604							ORDER BY latesteffectivefrom DESC";
605
606					$ErrMsg = _('The purchasing data for') . ' ' . $ItemCode . ' ' . _('could not be retrieved because');
607					$DbgMsg = _('The SQL used to retrieve the purchasing data but failed was');
608					$PurchDataResult = DB_query($sql,$ErrMsg,$DbgMsg);
609					if (DB_num_rows($PurchDataResult)>0){ //the purchasing data is set up
610						$PurchRow = DB_fetch_array($PurchDataResult);
611
612						/* Now to get the applicable discounts */
613						$sql = "SELECT discountpercent,
614										discountamount
615								FROM supplierdiscounts
616								WHERE supplierno= '" . $_SESSION['PO'.$identifier]->SupplierID . "'
617								AND effectivefrom <='" . Date('Y-m-d') . "'
618								AND effectiveto >='" . Date('Y-m-d') . "'
619								AND stockid = '". $ItemCode . "'";
620
621						$ItemDiscountPercent = 0;
622						$ItemDiscountAmount = 0;
623						$ErrMsg = _('Could not retrieve the supplier discounts applicable to the item');
624						$DbgMsg = _('The SQL used to retrive the supplier discounts that failed was');
625						$DiscountResult = DB_query($sql,$ErrMsg,$DbgMsg);
626						while ($DiscountRow = DB_fetch_array($DiscountResult)) {
627							$ItemDiscountPercent += $DiscountRow['discountpercent'];
628							$ItemDiscountAmount += $DiscountRow['discountamount'];
629						}
630						if ($ItemDiscountPercent != 0) {
631							prnMsg(_('Taken accumulated supplier percentage discounts of') .  ' ' . locale_number_format($ItemDiscountPercent*100,2) . '%','info');
632						}
633						if ($ItemDiscountAmount != 0 ){
634							prnMsg(_('Taken accumulated round sum supplier discount of') .  ' ' . $_SESSION['PO'.$identifier]->CurrCode . ' ' . locale_number_format($ItemDiscountAmount,$_SESSION['PO'.$identifier]->CurrDecimalPlaces) . ' (' . _('per supplier unit') . ')','info');
635						}
636						$PurchPrice = ($PurchRow['price']*(1-$ItemDiscountPercent) - $ItemDiscountAmount)/$PurchRow['conversionfactor'];
637						$ConversionFactor = $PurchRow['conversionfactor'];
638						if (mb_strlen($PurchRow['supplierdescription'])>2){
639							$SupplierDescription = $PurchRow['supplierdescription'];
640						} else {
641							$SupplierDescription = $ItemRow['description'];
642						}
643						$SuppliersUnitOfMeasure = $PurchRow['suppliersuom'];
644						$SuppliersPartNo = $PurchRow['suppliers_partno'];
645						$LeadTime = $PurchRow['leadtime'];
646						/* Work out the delivery date based on today + lead time
647					 * if > header DeliveryDate then set DeliveryDate to today + leadtime
648				        */
649						$DeliveryDate = DateAdd(Date($_SESSION['DefaultDateFormat']),'d',$LeadTime);
650						if (Date1GreaterThanDate2($_SESSION['PO'.$identifier]->DeliveryDate,$DeliveryDate)){
651							$DeliveryDate = $_SESSION['PO'.$identifier]->DeliveryDate;
652						}
653					} else { // no purchasing data setup
654						$PurchPrice = 0;
655						$ConversionFactor = 1;
656						$SupplierDescription = 	$ItemRow['description'];
657						$SuppliersUnitOfMeasure = $ItemRow['units'];
658						$SuppliersPartNo = '';
659						$LeadTime=1;
660						$DeliveryDate = $_SESSION['PO'.$identifier]->DeliveryDate;
661					}
662
663					$_SESSION['PO'.$identifier]->add_to_order ($_SESSION['PO'.$identifier]->LinesOnOrder+1,
664															$ItemCode,
665															0, /*Serialised */
666															0, /*Controlled */
667															filter_number_format($Quantity)*$ConversionFactor, /* Qty */
668															$SupplierDescription,
669															$PurchPrice,
670															$ItemRow['units'],
671															$ItemRow['stockact'],
672															$DeliveryDate,
673															0,
674															0,
675															0,
676															0,
677															0,
678															$ItemRow['accountname'],
679															$ItemRow['decimalplaces'],
680															$SuppliersUnitOfMeasure,
681															$ConversionFactor,
682															$LeadTime,
683															$SuppliersPartNo);
684				} else { //no rows returned by the SQL to get the item
685					prnMsg (_('The item code') . ' ' . $ItemCode . ' ' . _('does not exist in the database and therefore cannot be added to the order'),'error');
686					if ($debug==1){
687						echo '<br />' . $sql;
688					}
689					include('includes/footer.php');
690					exit;
691				}
692			} /* end of if not already on the order */
693		} /* end if the $_POST has NewQty in the variable name */
694	} /* end loop around the $_POST array */
695	$_SESSION['PO_ItemsResubmitForm' . $identifier]++; //change the $_SESSION VALUE
696} /* end of if its a new item */
697
698if (isset($_POST['UploadFile'])) {
699	if (isset($_FILES['CSVFile']) && $_FILES['CSVFile']['name']) {
700		//check file info
701		$FileName = $_FILES['CSVFile']['name'];
702		$TempName = $_FILES['CSVFile']['tmp_name'];
703		$FileSize = $_FILES['CSVFile']['size'];
704		//get file handle
705		$FileHandle = fopen($TempName, 'r');
706		$Row = 0;
707		$InsertNum = 0;
708
709		while (($FileRow = fgetcsv($FileHandle, 10000, ",")) !== False) {
710			++$Row;
711			if (filter_number_format($FileRow[1])!=0) { //if the form variable represents a Qty to add to the order
712
713				$ItemCode = $FileRow[0];
714				$Quantity = $FileRow[1];
715				$AlreadyOnThisOrder = 0;
716
717				if ($_SESSION['PO_AllowSameItemMultipleTimes'] ==false){
718					if (count($_SESSION['PO'.$identifier]->LineItems)!=0){
719
720						foreach ($_SESSION['PO'.$identifier]->LineItems AS $OrderItem) {
721
722						/* do a loop round the items on the order to see that the item is not already on this order */
723							if (($OrderItem->StockID == $ItemCode) AND ($OrderItem->Deleted==false)) {
724								$AlreadyOnThisOrder = 1;
725								prnMsg( _('The item') . ' ' . $ItemCode . ' ' . _('is already on this order') . '. ' . _('The system will not allow the same item on the order more than once') . '. ' . _('However you can change the quantity ordered of the existing line if necessary'),'error');
726							}
727						} /* end of the foreach loop to look for preexisting items of the same code */
728					}
729				}
730				if ($AlreadyOnThisOrder!=1 AND filter_number_format($Quantity) > 0){
731					$sql = "SELECT description,
732								longdescription,
733								stockid,
734								units,
735								decimalplaces,
736								stockact,
737								accountname
738							FROM stockmaster INNER JOIN stockcategory
739							ON stockcategory.categoryid = stockmaster.categoryid
740							INNER JOIN chartmaster
741							ON chartmaster.accountcode = stockcategory.stockact
742							WHERE  stockmaster.stockid = '". $ItemCode . "'";
743
744					$ErrMsg = _('The item details for') . ' ' . $ItemCode . ' ' . _('could not be retrieved because');
745					$DbgMsg = _('The SQL used to retrieve the item details but failed was');
746					$ItemResult = DB_query($sql,$ErrMsg,$DbgMsg);
747					if (DB_num_rows($ItemResult)==1){
748						$ItemRow = DB_fetch_array($ItemResult);
749
750						$sql = "SELECT price,
751									conversionfactor,
752									supplierdescription,
753									suppliersuom,
754									suppliers_partno,
755									leadtime,
756									MAX(purchdata.effectivefrom) AS latesteffectivefrom
757								FROM purchdata
758								WHERE purchdata.supplierno = '" . $_SESSION['PO'.$identifier]->SupplierID . "'
759								AND purchdata.effectivefrom <='" . Date('Y-m-d') . "'
760								AND purchdata.stockid = '". $ItemCode . "'
761								GROUP BY purchdata.price,
762										purchdata.conversionfactor,
763										purchdata.supplierdescription,
764										purchdata.suppliersuom,
765										purchdata.suppliers_partno,
766										purchdata.leadtime
767								ORDER BY latesteffectivefrom DESC";
768
769						$ErrMsg = _('The purchasing data for') . ' ' . $ItemCode . ' ' . _('could not be retrieved because');
770						$DbgMsg = _('The SQL used to retrieve the purchasing data but failed was');
771						$PurchDataResult = DB_query($sql,$ErrMsg,$DbgMsg);
772						if (DB_num_rows($PurchDataResult)>0){ //the purchasing data is set up
773							$PurchRow = DB_fetch_array($PurchDataResult);
774
775							/* Now to get the applicable discounts */
776							$sql = "SELECT discountpercent,
777											discountamount
778									FROM supplierdiscounts
779									WHERE supplierno= '" . $_SESSION['PO'.$identifier]->SupplierID . "'
780									AND effectivefrom <='" . Date('Y-m-d') . "'
781									AND effectiveto >='" . Date('Y-m-d') . "'
782									AND stockid = '". $ItemCode . "'";
783
784							$ItemDiscountPercent = 0;
785							$ItemDiscountAmount = 0;
786							$ErrMsg = _('Could not retrieve the supplier discounts applicable to the item');
787							$DbgMsg = _('The SQL used to retrive the supplier discounts that failed was');
788							$DiscountResult = DB_query($sql,$ErrMsg,$DbgMsg);
789							while ($DiscountRow = DB_fetch_array($DiscountResult)) {
790								$ItemDiscountPercent += $DiscountRow['discountpercent'];
791								$ItemDiscountAmount += $DiscountRow['discountamount'];
792							}
793							if ($ItemDiscountPercent != 0) {
794								prnMsg(_('Taken accumulated supplier percentage discounts of') .  ' ' . locale_number_format($ItemDiscountPercent*100,2) . '%','info');
795							}
796							if ($ItemDiscountAmount != 0 ){
797								prnMsg(_('Taken accumulated round sum supplier discount of') .  ' ' . $_SESSION['PO'.$identifier]->CurrCode . ' ' . locale_number_format($ItemDiscountAmount,$_SESSION['PO'.$identifier]->CurrDecimalPlaces) . ' (' . _('per supplier unit') . ')','info');
798							}
799							$PurchPrice = ($PurchRow['price']*(1-$ItemDiscountPercent) - $ItemDiscountAmount)/$PurchRow['conversionfactor'];
800							$ConversionFactor = $PurchRow['conversionfactor'];
801							if (mb_strlen($PurchRow['supplierdescription'])>2){
802								$SupplierDescription = $PurchRow['supplierdescription'];
803							} else {
804								$SupplierDescription = $ItemRow['description'];
805							}
806							$SuppliersUnitOfMeasure = $PurchRow['suppliersuom'];
807							$SuppliersPartNo = $PurchRow['suppliers_partno'];
808							$LeadTime = $PurchRow['leadtime'];
809							/* Work out the delivery date based on today + lead time
810						 * if > header DeliveryDate then set DeliveryDate to today + leadtime
811							*/
812							$DeliveryDate = DateAdd(Date($_SESSION['DefaultDateFormat']),'d',$LeadTime);
813							if (Date1GreaterThanDate2($_SESSION['PO'.$identifier]->DeliveryDate,$DeliveryDate)){
814								$DeliveryDate = $_SESSION['PO'.$identifier]->DeliveryDate;
815							}
816						} else { // no purchasing data setup
817							$PurchPrice = 0;
818							$ConversionFactor = 1;
819							$SupplierDescription = 	$ItemRow['description'];
820							$SuppliersUnitOfMeasure = $ItemRow['units'];
821							$SuppliersPartNo = '';
822							$LeadTime=1;
823							$DeliveryDate = $_SESSION['PO'.$identifier]->DeliveryDate;
824						}
825
826						$_SESSION['PO'.$identifier]->add_to_order ($_SESSION['PO'.$identifier]->LinesOnOrder+1,
827																$ItemCode,
828																0, /*Serialised */
829																0, /*Controlled */
830																filter_number_format($Quantity)*$ConversionFactor, /* Qty */
831																$SupplierDescription,
832																$PurchPrice,
833																$ItemRow['units'],
834																$ItemRow['stockact'],
835																$DeliveryDate,
836																0,
837																0,
838																0,
839																0,
840																0,
841																$ItemRow['accountname'],
842																$ItemRow['decimalplaces'],
843																$SuppliersUnitOfMeasure,
844																$ConversionFactor,
845																$LeadTime,
846																$SuppliersPartNo);
847						++$InsertNum;
848					} else { //no rows returned by the SQL to get the item
849						prnMsg (_('The item code') . ' ' . $ItemCode . ' ' . _('does not exist in the database and therefore cannot be added to the order'),'error');
850						if ($debug==1){
851							echo '<br />' . $sql;
852						}
853					}
854				} /* end of if not already on the order */
855			} /* end if the $_POST has NewQty in the variable name */
856		}
857	}
858	$_SESSION['PO_ItemsResubmitForm' . $identifier]++; //change the $_SESSION VALUE
859	prnMsg($InsertNum . ' ' . _('of') . ' ' . $Row . ' ' . _('rows have been added to the order'), 'info');
860} /* end of if its items uploaded from csv */
861
862
863/* This is where the order as selected should be displayed  reflecting any deletions or insertions*/
864
865echo '<form id="form1" action="' . htmlspecialchars($_SERVER['PHP_SELF'], ENT_QUOTES, 'UTF-8') . '?identifier=' . urlencode($identifier) . '" method="post" enctype="multipart/form-data">';
866echo '<div>';
867echo '<input type="hidden" name="FormID" value="' . $_SESSION['FormID'] . '" />';
868
869/*need to set up entry for item description where not a stock item and GL Codes */
870
871if (count($_SESSION['PO'.$identifier]->LineItems)>0 and !isset($_GET['Edit'])){
872	echo '<p class="page_title_text"><img src="'.$RootPath.'/css/'.$Theme.'/images/supplier.png" title="' .
873		_('Purchase Order') . '" alt="" />  '.$_SESSION['PO'.$identifier]->SupplierName;
874
875	if (isset($_SESSION['PO'.$identifier]->OrderNo)) {
876		echo  ' ' . _('Purchase Order') .' '. $_SESSION['PO'.$identifier]->OrderNo ;
877	}
878	echo '<br /><b>', _('Order Summary'), '</b></p>';
879	echo '<table cellpadding="2" class="selection">
880		<thead>
881			<tr>
882			<th class="ascending">' . _('Item Code') . '</th>
883			<th class="ascending">' . _('Description') . '</th>
884			<th class="ascending">' . _('Quantity Our Units') . '</th>
885			<th>' . _('Our Unit')  . '</th>
886			<th class="ascending">' . _('Price Our Units') .' (' . $_SESSION['PO'.$identifier]->CurrCode .  ')</th>
887			<th>' . _('Unit Conversion Factor') . '</th>
888			<th class="ascending">' . _('Order Quantity') . '<br />' . _('Supplier Units') . '</th>
889			<th>' .  _('Supplier Unit') . '</th>
890			<th class="ascending">' . _('Order Price') . '<br />' . _('Supp Units') . ' ('.$_SESSION['PO'.$identifier]->CurrCode.  ')</th>
891			<th class="ascending">' . _('Sub-Total') .' ('.$_SESSION['PO'.$identifier]->CurrCode.  ')</th>
892			<th class="ascending">' . _('Deliver By')  . '</th>
893			</tr>
894		</thead>
895		<tbody>';
896
897	$_SESSION['PO'.$identifier]->Total = 0;
898
899	foreach ($_SESSION['PO'.$identifier]->LineItems as $POLine) {
900
901		if ($POLine->Deleted==False) {
902			$LineTotal = $POLine->Quantity * $POLine->Price;
903			$DisplayLineTotal = locale_number_format($LineTotal,$_SESSION['PO'.$identifier]->CurrDecimalPlaces);
904			// Note if the price is greater than 1 use 2 decimal place, if the price is a fraction of 1, use 4 decimal places
905			// This should help display where item-price is a fraction
906			if ($POLine->Price > 1) {
907				$DisplayPrice = locale_number_format($POLine->Price,$_SESSION['PO'.$identifier]->CurrDecimalPlaces);
908				$SuppPrice = locale_number_format(round(($POLine->Price *$POLine->ConversionFactor),$_SESSION['PO'.$identifier]->CurrDecimalPlaces),$_SESSION['PO'.$identifier]->CurrDecimalPlaces);
909			} else {
910				$DisplayPrice = locale_number_format($POLine->Price,($_SESSION['PO'.$identifier]->CurrDecimalPlaces + 2));
911				$SuppPrice = locale_number_format(round(($POLine->Price *$POLine->ConversionFactor),($_SESSION['PO'.$identifier]->CurrDecimalPlaces+2)),($_SESSION['PO'.$identifier]->CurrDecimalPlaces+2));
912			}
913
914			echo '<tr class="striped_row">
915				<td>' . $POLine->StockID  . '</td>
916                <td><input type="text" name="ItemDescription' . $POLine->LineNo.'" size="30" value="' . stripslashes($POLine->ItemDescription) . '" /></td>
917				<td class="number">' . locale_number_format($POLine->Quantity,$POLine->DecimalPlaces) . '</td>
918				<td>' . $POLine->Units . '</td>
919				<td class="number">' . $DisplayPrice . '</td>
920				<td><input type="text" class="number" name="ConversionFactor' . $POLine->LineNo .'" size="8" value="' . locale_number_format($POLine->ConversionFactor,'Variable') . '" /></td>
921				<td><input type="text" class="number" name="SuppQty' . $POLine->LineNo .'" size="10" value="' . locale_number_format(round($POLine->Quantity/$POLine->ConversionFactor,$POLine->DecimalPlaces),$POLine->DecimalPlaces) . '" /></td>
922				<td>' . $POLine->SuppliersUnit . '</td>
923				<td><input type="text" class="number" name="SuppPrice' . $POLine->LineNo . '" size="10" value="' . $SuppPrice .'" /></td>
924				<td class="number">' . $DisplayLineTotal . '</td>
925				<td><input type="text" class="date" name="ReqDelDate' . $POLine->LineNo.'" size="10" value="' .$POLine->ReqDelDate .'" /></td>';
926			if ($POLine->QtyReceived !=0 AND $POLine->Completed!=1){
927				echo '<td><a href="' . htmlspecialchars($_SERVER['PHP_SELF'],ENT_QUOTES,'UTF-8') . '?identifier='.$identifier .'&amp;Complete=' . $POLine->LineNo . '">' . _('Complete') . '</a></td>';
928			} elseif ($POLine->QtyReceived ==0) {
929				echo '<td><a href="' . htmlspecialchars($_SERVER['PHP_SELF'],ENT_QUOTES,'UTF-8') . '?identifier='.$identifier .'&amp;Delete=' . $POLine->LineNo . '">' . _('Delete'). '</a></td>';
930			}
931			echo '</tr>';
932			$_SESSION['PO'.$identifier]->Total += $LineTotal;
933		}
934	}
935
936	$DisplayTotal = locale_number_format($_SESSION['PO'.$identifier]->Total,$_SESSION['PO'.$identifier]->CurrDecimalPlaces);
937	echo '</tbody>
938		<tfoot>
939			<tr>',
940/*				'<td colspan="9" class="number">' . _('TOTAL') . _(' excluding Tax') . '</td>',*/
941				'<td class="number" colspan="9">', _('Total Excluding Tax'), '</td>',
942				'<td class="number"><b>', $DisplayTotal, '</b></td>
943			</tr>
944		</tfoot>
945		</table>
946		<br />
947			<div class="centre">
948			<input type="submit" name="UpdateLines" value="' . _('Update Order Lines') . '" />
949			&nbsp;<input type="submit" name="Commit" value="' . _('Process Order') . '" />
950			</div>';
951
952} /*Only display the order line items if there are any !! */
953
954
955if (isset($_POST['NonStockOrder'])) {
956
957	echo '<br /><table class="selection"><tr>
958				<td>' . _('Item Description') . '</td>';
959	echo '<td><input type="text" name="ItemDescription" size="40" /></td></tr>';
960	echo '<tr>
961			<td>' . _('General Ledger Code') . '</td>
962			<td><select name="GLCode">';
963	$sql="SELECT accountcode,
964				  accountname
965				FROM chartmaster
966				ORDER BY accountcode ASC";
967
968	$result=DB_query($sql);
969	while ($myrow=DB_fetch_array($result)) {
970		echo '<option value="'.$myrow['accountcode'].'">' . $myrow['accountcode'].' - '.$myrow['accountname'] . '</option>';
971	}
972	echo '</select></td></tr>';
973	echo '<tr>
974			<td>' . _('OR Asset ID'). '</td>
975			<td><select name="AssetID">';
976	$AssetsResult = DB_query("SELECT assetid,
977									description,
978									datepurchased
979								FROM fixedassets
980								ORDER BY assetid DESC");
981	echo '<option selected="selected" value="Not an Asset">' . _('Not an Asset') . '</option>';
982	while ($AssetRow = DB_fetch_array($AssetsResult)){
983		if ($AssetRow['datepurchased']=='0000-00-00'){
984			$DatePurchased = _('Not yet purchased');
985		} else {
986			$DatePurchased = ConvertSQLDate($AssetRow['datepurchased']);
987		}
988		echo '<option value="' . $AssetRow['assetid'] . '">'  . $AssetRow['assetid'] . ' - '.  $DatePurchased . ' - ' . $AssetRow['description'] . '</option>';
989	}
990
991	echo'</select><a href="FixedAssetItems.php" target=_blank>' .  _('New Fixed Asset') . '</a></td></tr>
992		<tr>
993			<td>' . _('Quantity to purchase') . '</td>
994			<td><input type="text" class="number" name="Qty" size="10" value="1" /></td>
995		</tr>
996		<tr>
997			<td>' . _('Price per item') . '</td>
998			<td><input type="text" class="number" name="Price" size="10" /></td>
999		</tr>
1000		<tr>
1001			<td>' . _('Unit') . '</td>
1002			<td><input type="text" name="SuppliersUnit" size="10" value="' . _('each') . '" /></td>
1003		</tr>
1004		<tr>
1005			<td>' . _('Delivery Date') . '</td>
1006			<td><input type="text" class="date" name="ReqDelDate" size="11" value="'.$_SESSION['PO'.$identifier]->DeliveryDate .'" /></td>
1007		</tr>
1008		</table>
1009		<div class="centre">
1010			<input type="submit" name="EnterLine" value="' . _('Enter Item') . '" />
1011		</div>';
1012}
1013
1014/* Now show the stock item selection search stuff below */
1015if (isset($_POST['Search']) OR isset($_POST['Prev']) OR isset($_POST['Next'])){  /*ie seach for stock items */
1016
1017	if ($_POST['Keywords'] AND $_POST['StockCode']) {
1018		prnMsg( _('Stock description keywords have been used in preference to the Stock code extract entered'), 'info' );
1019	}
1020	if ($_POST['Keywords']) {
1021		//insert wildcard characters in spaces
1022		$SearchString = '%' . str_replace(' ', '%', $_POST['Keywords']) . '%';
1023
1024		if ($_POST['StockCat']=='All'){
1025			if ($_POST['SupplierItemsOnly']=='on'){
1026				$sql = "SELECT stockmaster.stockid,
1027								stockmaster.description,
1028								stockmaster.units
1029						FROM stockmaster INNER JOIN stockcategory
1030						ON stockmaster.categoryid=stockcategory.categoryid
1031						INNER JOIN purchdata
1032						ON stockmaster.stockid=purchdata.stockid
1033						WHERE (stockmaster.mbflag<>'D' OR stockcategory.stocktype='L')
1034						AND stockmaster.mbflag<>'K'
1035						AND stockmaster.mbflag<>'A'
1036						AND stockmaster.mbflag<>'G'
1037						AND stockmaster.discontinued<>1
1038						AND purchdata.supplierno='" . $_SESSION['PO'.$identifier]->SupplierID . "'
1039						AND stockmaster.description " . LIKE . " '" . $SearchString ."'
1040						GROUP BY stockmaster.stockid
1041						ORDER BY stockmaster.stockid ";
1042			} else { // not just supplier purchdata items
1043				$sql = "SELECT stockmaster.stockid,
1044							stockmaster.description,
1045							stockmaster.units
1046					FROM stockmaster INNER JOIN stockcategory
1047					ON stockmaster.categoryid=stockcategory.categoryid
1048					WHERE (stockmaster.mbflag<>'D' OR stockcategory.stocktype='L')
1049					AND stockmaster.mbflag<>'K'
1050					AND stockmaster.mbflag<>'A'
1051					AND stockmaster.mbflag<>'G'
1052					AND stockmaster.discontinued<>1
1053					AND stockmaster.description " . LIKE . " '" . $SearchString ."'
1054					ORDER BY stockmaster.stockid ";
1055			}
1056		} else { //for a specific stock category
1057			if ($_POST['SupplierItemsOnly']=='on'){
1058				$sql = "SELECT stockmaster.stockid,
1059								stockmaster.description,
1060								stockmaster.units
1061						FROM stockmaster INNER JOIN stockcategory
1062						ON stockmaster.categoryid=stockcategory.categoryid
1063						INNER JOIN purchdata
1064						ON stockmaster.stockid=purchdata.stockid
1065						WHERE (stockmaster.mbflag<>'D' OR stockcategory.stocktype='L')
1066						AND stockmaster.mbflag<>'A'
1067						AND stockmaster.mbflag<>'K'
1068						AND stockmaster.mbflag<>'G'
1069						AND purchdata.supplierno='" . $_SESSION['PO'.$identifier]->SupplierID . "'
1070						AND stockmaster.discontinued<>1
1071						AND stockmaster.description " . LIKE . " '". $SearchString ."'
1072						AND stockmaster.categoryid='" . $_POST['StockCat'] . "'
1073						GROUP BY stockmaster.stockid
1074						ORDER BY stockmaster.stockid ";
1075			} else {
1076				$sql = "SELECT stockmaster.stockid,
1077								stockmaster.description,
1078								stockmaster.units
1079						FROM stockmaster INNER JOIN stockcategory
1080						ON stockmaster.categoryid=stockcategory.categoryid
1081						WHERE (stockmaster.mbflag<>'D' OR stockcategory.stocktype='L')
1082						AND stockmaster.mbflag<>'A'
1083						AND stockmaster.mbflag<>'K'
1084						AND stockmaster.mbflag<>'G'
1085						AND stockmaster.discontinued<>1
1086						AND stockmaster.description " . LIKE . " '". $SearchString ."'
1087						AND stockmaster.categoryid='" . $_POST['StockCat'] . "'
1088						ORDER BY stockmaster.stockid ";
1089			}
1090		}
1091
1092	} elseif ($_POST['StockCode']){
1093
1094		$_POST['StockCode'] = '%' . $_POST['StockCode'] . '%';
1095
1096		if ($_POST['StockCat']=='All'){
1097			if ($_POST['SupplierItemsOnly']=='on'){
1098				$sql = "SELECT stockmaster.stockid,
1099								stockmaster.description,
1100								stockmaster.units
1101						FROM stockmaster INNER JOIN stockcategory
1102						ON stockmaster.categoryid=stockcategory.categoryid
1103						INNER JOIN purchdata
1104						ON stockmaster.stockid=purchdata.stockid
1105						WHERE (stockmaster.mbflag<>'D' OR stockcategory.stocktype='L')
1106						AND stockmaster.mbflag<>'K'
1107						AND stockmaster.mbflag<>'A'
1108						AND stockmaster.mbflag<>'G'
1109						AND purchdata.supplierno='" . $_SESSION['PO'.$identifier]->SupplierID . "'
1110						AND stockmaster.discontinued<>1
1111						AND stockmaster.stockid " . LIKE . " '" . $_POST['StockCode'] . "'
1112						GROUP BY stockmaster.stockid
1113						ORDER BY stockmaster.stockid ";
1114			} else {
1115				$sql = "SELECT stockmaster.stockid,
1116							stockmaster.description,
1117							stockmaster.units
1118					FROM stockmaster INNER JOIN stockcategory
1119					ON stockmaster.categoryid=stockcategory.categoryid
1120					WHERE (stockmaster.mbflag<>'D' OR stockcategory.stocktype='L')
1121					AND stockmaster.mbflag<>'A'
1122					AND stockmaster.mbflag<>'K'
1123					AND stockmaster.mbflag<>'G'
1124					AND stockmaster.discontinued<>1
1125					AND stockmaster.stockid " . LIKE . " '" . $_POST['StockCode'] . "'
1126					ORDER BY stockmaster.stockid ";
1127			}
1128		} else { //for a specific stock category and LIKE stock code
1129			if ($_POST['SupplierItemsOnly']=='on'){
1130				$sql = "SELECT stockmaster.stockid,
1131								stockmaster.description,
1132								stockmaster.units
1133						FROM stockmaster INNER JOIN stockcategory
1134						ON stockmaster.categoryid=stockcategory.categoryid
1135						INNER JOIN purchdata
1136						ON stockmaster.stockid=purchdata.stockid
1137						WHERE (stockmaster.mbflag<>'D' OR stockcategory.stocktype='L')
1138						AND stockmaster.mbflag<>'A'
1139						AND stockmaster.mbflag<>'K'
1140						AND stockmaster.mbflag<>'G'
1141						AND purchdata.supplierno='" . $_SESSION['PO'.$identifier]->SupplierID . "'
1142						and stockmaster.discontinued<>1
1143						AND stockmaster.stockid " . LIKE  . " '" . $_POST['StockCode'] . "'
1144						AND stockmaster.categoryid='" . $_POST['StockCat'] . "'
1145						GROUP BY stockmaster.stockid
1146						ORDER BY stockmaster.stockid ";
1147			} else {
1148				$sql = "SELECT stockmaster.stockid,
1149							stockmaster.description,
1150							stockmaster.units
1151					FROM stockmaster INNER JOIN stockcategory
1152					ON stockmaster.categoryid=stockcategory.categoryid
1153					WHERE (stockmaster.mbflag<>'D' OR stockcategory.stocktype='L')
1154					AND stockmaster.mbflag<>'A'
1155					AND stockmaster.mbflag<>'K'
1156					AND stockmaster.mbflag<>'G'
1157					and stockmaster.discontinued<>1
1158					AND stockmaster.stockid " . LIKE  . " '" . $_POST['StockCode'] . "'
1159					AND stockmaster.categoryid='" . $_POST['StockCat'] . "'
1160					ORDER BY stockmaster.stockid ";
1161			}
1162		}
1163
1164	} else {
1165		if ($_POST['StockCat']=='All'){
1166			if (isset($_POST['SupplierItemsOnly'])){
1167				$sql = "SELECT stockmaster.stockid,
1168								stockmaster.description,
1169								stockmaster.units
1170						FROM stockmaster INNER JOIN stockcategory
1171						ON stockmaster.categoryid=stockcategory.categoryid
1172						INNER JOIN purchdata
1173						ON stockmaster.stockid=purchdata.stockid
1174						WHERE (stockmaster.mbflag<>'D' OR stockcategory.stocktype='L')
1175						AND stockmaster.mbflag<>'A'
1176						AND stockmaster.mbflag<>'K'
1177						AND stockmaster.mbflag<>'G'
1178						AND purchdata.supplierno='" . $_SESSION['PO'.$identifier]->SupplierID . "'
1179						AND stockmaster.discontinued<>1
1180						GROUP BY stockmaster.stockid
1181						ORDER BY stockmaster.stockid ";
1182			} else {
1183				$sql = "SELECT stockmaster.stockid,
1184							stockmaster.description,
1185							stockmaster.units
1186					FROM stockmaster INNER JOIN stockcategory
1187					ON stockmaster.categoryid=stockcategory.categoryid
1188					WHERE (stockmaster.mbflag<>'D' OR stockcategory.stocktype='L')
1189					AND stockmaster.mbflag<>'A'
1190					AND stockmaster.mbflag<>'K'
1191					AND stockmaster.mbflag<>'G'
1192					AND stockmaster.discontinued<>1
1193					ORDER BY stockmaster.stockid ";
1194			}
1195		} else { // for a specific stock category
1196			if (isset($_POST['SupplierItemsOnly']) AND $_POST['SupplierItemsOnly']=='on'){
1197				$sql = "SELECT stockmaster.stockid,
1198								stockmaster.description,
1199								stockmaster.units
1200						FROM stockmaster INNER JOIN stockcategory
1201						ON stockmaster.categoryid=stockcategory.categoryid
1202						INNER JOIN purchdata
1203						ON stockmaster.stockid=purchdata.stockid
1204						WHERE (stockmaster.mbflag<>'D' OR stockcategory.stocktype='L')
1205						AND stockmaster.mbflag<>'A'
1206						AND stockmaster.mbflag<>'K'
1207						AND stockmaster.mbflag<>'G'
1208						AND purchdata.supplierno='" . $_SESSION['PO'.$identifier]->SupplierID . "'
1209						AND stockmaster.discontinued<>1
1210						AND stockmaster.categoryid='" . $_POST['StockCat'] . "'
1211						GROUP BY stockmaster.stockid
1212						ORDER BY stockmaster.stockid ";
1213			} else {
1214				$sql = "SELECT stockmaster.stockid,
1215							stockmaster.description,
1216							stockmaster.units
1217					FROM stockmaster INNER JOIN stockcategory
1218					ON stockmaster.categoryid=stockcategory.categoryid
1219					WHERE (stockmaster.mbflag<>'D' OR stockcategory.stocktype='L')
1220					AND stockmaster.mbflag<>'A'
1221					AND stockmaster.mbflag<>'K'
1222					AND stockmaster.mbflag<>'G'
1223					AND stockmaster.discontinued<>1
1224					AND stockmaster.categoryid='" . $_POST['StockCat'] . "'
1225					ORDER BY stockmaster.stockid ";
1226			}
1227		}
1228	}
1229
1230	$SQLCount = substr($sql,strpos($sql,   "FROM"));
1231	$SQLCount = substr($SQLCount,0, strpos($SQLCount,   "ORDER"));
1232	$SQLCount = 'SELECT COUNT(*) '.$SQLCount;
1233	$ErrMsg = _('Failed to retrieve result count');
1234	$DbgMsg = _('The SQL failed is ');
1235	$SearchResult = DB_query($SQLCount,$ErrMsg,$DbgMsg);
1236	$myrow=DB_fetch_array($SearchResult);
1237	DB_free_result($SearchResult);
1238	unset($SearchResult);
1239	$ListCount = $myrow[0];
1240	$ListPageMax = ceil($ListCount / $_SESSION['DisplayRecordsMax'])-1;
1241	if ($ListPageMax < 0) {
1242		$ListPageMax = 0;
1243	}
1244	if (isset($_POST['Next'])) {
1245		$Offset = $_POST['currpage']+1;
1246	}
1247	if (isset($_POST['Prev'])) {
1248		$Offset = $_POST['currpage']-1;
1249	}
1250	if (!isset($Offset)) {
1251		$Offset = 0;
1252	}
1253	if($Offset < 0){
1254		$Offset = 0;
1255	}
1256	if($Offset > $ListPageMax) {
1257		$Offset = $ListPageMax;
1258	}
1259
1260	$sql = $sql . " LIMIT " . $_SESSION['DisplayRecordsMax']." OFFSET " . strval($_SESSION['DisplayRecordsMax']*$Offset);
1261
1262
1263
1264	$ErrMsg = _('There is a problem selecting the part records to display because');
1265	$DbgMsg = _('The SQL statement that failed was');
1266	$SearchResult = DB_query($sql,$ErrMsg,$DbgMsg);
1267
1268	if (DB_num_rows($SearchResult)==0 AND $debug==1){
1269		prnMsg( _('There are no products to display matching the criteria provided'),'warn');
1270	}
1271	if (DB_num_rows($SearchResult)==1){
1272
1273		$myrow=DB_fetch_array($SearchResult);
1274		$_GET['NewItem'] = $myrow['stockid'];
1275		DB_data_seek($SearchResult,0);
1276	}
1277
1278} //end of if search
1279
1280if (!isset($_GET['Edit'])) {
1281	$sql="SELECT categoryid,
1282				categorydescription
1283			FROM stockcategory
1284			WHERE stocktype<>'D'
1285			ORDER BY categorydescription";
1286	$ErrMsg = _('The supplier category details could not be retrieved because');
1287	$DbgMsg = _('The SQL used to retrieve the category details but failed was');
1288	$result1 = DB_query($sql,$ErrMsg,$DbgMsg);
1289
1290	echo '<table class="selection">
1291			<tr>
1292				<th colspan="3"><h3>' .  _('Search For Stock Items') . ':</h3></th>';
1293
1294	echo '</tr>
1295			<tr><td>' . _('Item Category') . ': <select name="StockCat">
1296
1297			<option selected="selected" value="All">' . _('All') . '</option>';
1298
1299	while ($myrow1 = DB_fetch_array($result1)) {
1300		if (isset($_POST['StockCat']) and $_POST['StockCat']==$myrow1['categoryid']){
1301			echo '<option selected="selected" value="'. $myrow1['categoryid'] . '">' . $myrow1['categorydescription'] . '</option>';
1302		} else {
1303			echo '<option value="'. $myrow1['categoryid'] . '">' . $myrow1['categorydescription'] . '</option>';
1304		}
1305	}
1306
1307	unset($_POST['Keywords']);
1308	unset($_POST['StockCode']);
1309
1310	if (!isset($_POST['Keywords'])) {
1311		$_POST['Keywords']='';
1312	}
1313
1314	if (!isset($_POST['StockCode'])) {
1315		$_POST['StockCode']='';
1316	}
1317
1318	if (isset($_POST['SupplierItemsOnly'])) {
1319		$Checked = 'checked';
1320	} else {
1321		$Checked = '';
1322	}
1323
1324	echo '</select></td>
1325		<td>' . _('Enter text extracts in the description') . ':</td>
1326		<td><input type="text" name="Keywords" size="20" maxlength="25" value="' . $_POST['Keywords'] . '" /></td></tr>
1327		<tr><td>' . _('Only items defined as from this Supplier') . ' <input type="checkbox" ' . $Checked . ' name="SupplierItemsOnly" /></td>
1328		<td><b>' . _('OR') . ' </b>' . _('Enter extract of the Stock Code') . ':</td>
1329		<td><input type="text" name="StockCode" size="15" maxlength="18" value="' . $_POST['StockCode'] . '" /></td>
1330		</tr>
1331		<tr><td></td>
1332		<td><b>' . _('OR') . ' </b><a target="_blank" href="'.$RootPath.'/Stocks.php">' . _('Insert New Item') . '</a></td></tr>
1333		<tr>
1334				<td colspan="10">
1335					<div class="centre">
1336						<h2>' . _('Or') . '</h2>
1337						' . _('Upload items from csv file') . '<input type="file" name="CSVFile" />
1338						<input type="submit" name="UploadFile" value="' . _('Upload File') . '" />
1339					</div>
1340				</td>
1341			</tr>
1342		</table>
1343		<br />
1344
1345		<div class="centre"><input type="submit" name="Search" value="' . _('Search Now') . '" />
1346		<input type="submit" name="NonStockOrder" value="' . _('Order a non stock item') . '" />
1347		</div><br />';
1348
1349	$PartsDisplayed =0;
1350}
1351
1352if (isset($SearchResult)) {
1353	$PageBar = '<tr><td><input type="hidden" name="currpage" value="'.$Offset.'">';
1354	if($Offset>0)
1355		$PageBar .= '<input type="submit" name="Prev" value="'._('Prev').'" />';
1356	else
1357		$PageBar .= '<input type="submit" name="Prev" value="'._('Prev').'" disabled="disabled"/>';
1358	$PageBar .= '</td><td class="centre" colspan="4"><input type="submit" value="'._('Order some').'" name="NewItem"/></td><td>';
1359	if($Offset<$ListPageMax)
1360		$PageBar .= '<input type="submit" name="Next" value="'._('Next').'" />';
1361	else
1362		$PageBar .= '<input type="submit" name="Next" value="'._('Next').'" disabled="disabled"/>';
1363	$PageBar .= '</td></tr>';
1364
1365
1366
1367	echo '<table cellpadding="1" class="selection">';
1368	echo $PageBar;
1369	$TableHeader = '<tr>
1370						<th class="ascending">' . _('Code')  . '</th>
1371						<th class="ascending">' . _('Description') . '</th>
1372						<th>' . _('Our Units') . '</th>
1373						<th>' . _('Conversion') . '<br />' ._('Factor') . '</th>
1374						<th>' . _('Supplier/Order') . '<br />' .  _('Units') . '</th>
1375						<th colspan="2"><a href="#end">' . _('Go to end of list') . '</a></th>
1376					</tr>';
1377	echo $TableHeader;
1378
1379	$j = 1;
1380
1381	while ($myrow=DB_fetch_array($SearchResult)) {
1382
1383		$SupportedImgExt = array('png','jpg','jpeg');
1384
1385		$imagefilearray = (glob($_SESSION['part_pics_dir'] . '/' . $myrow['stockid'] . '.{' . implode(",", $SupportedImgExt) . '}', GLOB_BRACE));
1386		$imagefile = reset($imagefilearray);
1387
1388		if (extension_loaded('gd') && function_exists('gd_info') && file_exists ($imagefile) ) {
1389			$ImageSource = '<img src="GetStockImage.php?automake=1&amp;textcolor=FFFFFF&amp;bgcolor=CCCCCC'.
1390			'&amp;StockID='.urlencode($myrow['stockid']).
1391			'&amp;text='.
1392			'&amp;width=64'.
1393			'&amp;height=64'.
1394			'" alt="" />';
1395		} else if (file_exists ($imagefile)) {
1396			$ImageSource = '<img src="' . $imagefile . '" height="100" width="100" />';
1397		} else {
1398			$ImageSource = _('No Image');
1399		}
1400
1401		/*Get conversion factor and supplier units if any */
1402		$sql =  "SELECT purchdata.conversionfactor,
1403						purchdata.suppliersuom
1404					FROM purchdata
1405					WHERE purchdata.supplierno='" . $_SESSION['PO'.$identifier]->SupplierID . "'
1406					AND purchdata.stockid='" . $myrow['stockid'] . "'";
1407		$ErrMsg = _('Could not retrieve the purchasing data for the item');
1408		$PurchDataResult = DB_query($sql,$ErrMsg);
1409
1410		if (DB_num_rows($PurchDataResult)>0) {
1411			$PurchDataRow = DB_fetch_array($PurchDataResult);
1412			$OrderUnits=$PurchDataRow['suppliersuom'];
1413			$ConversionFactor = locale_number_format($PurchDataRow['conversionfactor'],'Variable');
1414		} else {
1415			$OrderUnits=$myrow['units'];
1416			$ConversionFactor =1;
1417		}
1418		echo '<tr class="striped_row">
1419			<td>' . $myrow['stockid']  . '</td>
1420			<td>' . $myrow['description']  . '</td>
1421			<td>' . $myrow['units']  . '</td>
1422			<td class="number">' . $ConversionFactor  . '</td>
1423			<td>' . $OrderUnits . '</td>
1424			<td>' . $ImageSource . '</td>
1425			<td><input class="number" type="text" size="6" value="0" name="NewQty' . $j . '" /></td>
1426			<input type="hidden" name="StockID' . $j .'" . value="' . $myrow['stockid'] . '" />
1427			</tr>';
1428		$j++;
1429		$PartsDisplayed++;
1430#end of page full new headings if
1431	}
1432
1433	echo $PageBar;
1434#end of while loop
1435	echo '</table>';
1436	echo '<input type="hidden" name="PO_ItemsResubmitFormValue" value="' . $_SESSION['PO_ItemsResubmitForm' . $identifier] . '" />';
1437	echo '<a name="end"></a><br /><div class="centre"><input type="submit" name="NewItem" value="' . _('Order some') . '" /></div>';
1438}#end if SearchResults to show
1439
1440echo '</div>
1441      </form>';
1442include('includes/footer.php');
1443?>
1444