1<?php
2
3$PricesSecurity = 12;
4
5include ('includes/session.php');
6$Title = _('Search Outstanding Sales Orders');
7$ViewTopic = 'SalesOrders';
8$BookMark = 'SelectSalesOrder';
9include ('includes/header.php');
10include ('includes/SQL_CommonFunctions.inc');
11
12if (isset($_POST['Reset'])) {
13	unset($_POST);
14}
15
16if (isset($_GET['SelectedStockItem'])) {
17	$SelectedStockItem = $_GET['SelectedStockItem'];
18} elseif (isset($_POST['SelectedStockItem'])) {
19	$SelectedStockItem = $_POST['SelectedStockItem'];
20} else {
21	unset($SelectedStockItem);
22}
23
24if (isset($_GET['SelectedCustomer'])) {
25	$SelectedCustomer = $_GET['SelectedCustomer'];
26} elseif (isset($_POST['SelectedCustomer'])) {
27	$SelectedCustomer = $_POST['SelectedCustomer'];
28} else {
29	unset($SelectedCustomer);
30}
31
32if ( isset($_GET['Quotations']) ) {
33	$_POST['Quotations'] = $_GET['Quotations'];
34}
35else if ( !isset($_POST['Quotations']) ) {
36	$_POST['Quotations'] = '';
37}
38
39if (isset($_POST['PlacePO'])) { /*user hit button to place PO for selected orders */
40
41	/*Note the button would not have been displayed if the user had no authority to create purchase orders */
42	$OrdersToPlacePOFor = '';
43	for ($i = 0; $i <= count($_POST['PlacePO_']); $i++) {
44		if ($OrdersToPlacePOFor == '') {
45			$OrdersToPlacePOFor .= " orderno= '" . $_POST['PlacePO_'][$i] . "'";
46		} else {
47			$OrdersToPlacePOFor .= " OR orderno= '" . $_POST['PlacePO_'][$i] . "'";
48		}
49	}
50	if (mb_strlen($OrdersToPlacePOFor) == '') {
51		prnMsg(_('There were no sales orders checked to place purchase orders for. No purchase orders will be created.'),'info');
52	} else {
53   /*  Now build SQL of items to purchase with purchasing data and preferred suppliers - sorted by preferred supplier */
54		$SQL = "SELECT purchdata.supplierno,
55						purchdata.stockid,
56						purchdata.price,
57						purchdata.suppliers_partno,
58						purchdata.supplierdescription,
59						purchdata.conversionfactor,
60						purchdata.leadtime,
61						purchdata.suppliersuom,
62						stockmaster.grossweight,
63						stockmaster.volume,
64						stockcategory.stockact,
65						SUM(salesorderdetails.quantity-salesorderdetails.qtyinvoiced) AS orderqty
66				FROM purchdata
67				INNER JOIN salesorderdetails
68					ON purchdata.stockid = salesorderdetails.stkcode
69				INNER JOIN stockmaster
70					ON purchdata.stockid = stockmaster.stockid
71				INNER JOIN stockcategory
72					ON stockmaster.categoryid = stockcategory.categoryid
73				WHERE purchdata.preferred = 1
74					AND purchdata.effectivefrom <= CURRENT_DATE
75					AND (" . $OrdersToPlacePOFor . ")
76				GROUP BY purchdata.supplierno,
77					purchdata.stockid,
78					purchdata.price,
79					purchdata.suppliers_partno,
80					purchdata.supplierdescription,
81					purchdata.conversionfactor,
82					purchdata.leadtime,
83					purchdata.suppliersuom,
84					stockmaster.grossweight,
85					stockmaster.volume,
86					stockcategory.stockact
87				ORDER BY purchdata.supplierno,
88					 purchdata.stockid";
89
90		$ErrMsg = _('Unable to retrieve the items on the selected orders for creating purchase orders for');
91		$ItemResult = DB_query($SQL, $ErrMsg);
92
93		$ItemArray = array();
94
95		while ($MyRow = DB_fetch_array($ItemResult)) {
96			$ItemArray[$MyRow['stockid']] = $MyRow;
97		}
98
99		/* Now figure out if there are any components of Assembly items that  need to be ordered too */
100		$SQL = "SELECT purchdata.supplierno,
101						purchdata.stockid,
102						purchdata.price,
103						purchdata.suppliers_partno,
104						purchdata.supplierdescription,
105						purchdata.conversionfactor,
106						purchdata.leadtime,
107						purchdata.suppliersuom,
108						stockmaster.grossweight,
109						stockmaster.volume,
110						stockcategory.stockact,
111						SUM(bom.quantity *(salesorderdetails.quantity-salesorderdetails.qtyinvoiced)) AS orderqty
112				FROM purchdata
113				INNER JOIN bom
114					ON purchdata.stockid = bom.component
115				INNER JOIN salesorderdetails
116					ON bom.parent = salesorderdetails.stkcode
117				INNER JOIN stockmaster
118					ON purchdata.stockid = stockmaster.stockid
119				INNER JOIN stockmaster AS stockmaster2
120					ON stockmaster2.stockid = salesorderdetails.stkcode
121				INNER JOIN stockcategory
122					ON stockmaster.categoryid = stockcategory.categoryid
123				WHERE purchdata.preferred = 1
124					AND stockmaster2.mbflag = 'A'
125					AND bom.loccode = '" . $_SESSION['UserStockLocation'] . "'
126					AND purchdata.effectivefrom <= CURRENT_DATE
127					AND bom.effectiveafter <= CURRENT_DATE
128					AND bom.effectiveto > CURRENT_DATE
129					AND (" . $OrdersToPlacePOFor . ")
130				GROUP BY purchdata.supplierno,
131					purchdata.stockid,
132					purchdata.price,
133					purchdata.suppliers_partno,
134					purchdata.supplierdescription,
135					purchdata.conversionfactor,
136					purchdata.leadtime,
137					purchdata.suppliersuom,
138					stockmaster.grossweight,
139					stockmaster.volume,
140					stockcategory.stockact
141				ORDER BY purchdata.supplierno,
142					 purchdata.stockid";
143		$ErrMsg = _('Unable to retrieve the items on the selected orders for creating purchase orders for');
144		$ItemResult = DB_query($SQL, $ErrMsg);
145
146		/* add any assembly item components from salesorders to the ItemArray */
147		while ($MyRow = DB_fetch_array($ItemResult)) {
148			if (isset($ItemArray[$MyRow['stockid']])) {
149			  /* if the item is already in the ItemArray then just add the quantity to the existing item */
150			   $ItemArray[$MyRow['stockid']]['orderqty'] += $MyRow['orderqty'];
151			} else { /*it is not already in the ItemArray so add it */
152				$ItemArray[$MyRow['stockid']] = $MyRow;
153			}
154		}
155
156
157		/* We need the items to order to be in supplier order so that only a single order is created for a supplier - so need to sort the multi-dimensional array to ensure it is listed by supplier sequence. To use array_multisort we need to get arrays of supplier with the same keys as the main array of rows
158		 */
159		$SupplierArray =array();
160		foreach ($ItemArray as $key => $row) {
161			//to make the Supplier array with the keys of the $ItemArray
162			$SupplierArray[$key]  = $row['supplierno'];
163		}
164
165		/* Use array_multisort to Sort the ItemArray with supplierno ascending
166		Add $ItemArray as the last parameter, to sort by the common key
167		*/
168		if (count($SupplierArray) > 1) {
169			array_multisort($SupplierArray, SORT_ASC, $ItemArray);
170		}
171
172		if (count($ItemArray) == 0) {
173			prnMsg(_('There might be no supplier purchasing data set up for any items on the selected sales order(s). No purchase orders have been created'),'warn');
174		} else {
175			/*Now get the default delivery address details from the users default stock location */
176			$SQL = "SELECT locationname,
177							deladd1,
178							deladd2,
179							deladd3,
180							deladd4,
181							deladd5,
182							deladd6,
183							tel,
184							contact
185						FROM locations
186						INNER JOIN locationusers
187							ON locationusers.loccode = locations.loccode
188							AND locationusers.userid = '" .  $_SESSION['UserID'] . "'
189							AND locationusers.canupd = 1
190						WHERE locations.loccode = '" . $_SESSION['UserStockLocation']  . "'";
191			$ErrMsg = _('The delivery address for the order could not be obtained from the user default stock location');
192			$DelAddResult = DB_query($SQL, $ErrMsg);
193			$DelAddRow = DB_fetch_array($DelAddResult);
194
195			$SupplierID = '';
196
197			if (IsEmailAddress($_SESSION['UserEmail'])) {
198				$UserDetails  = ' <a href="mailto:' . $_SESSION['UserEmail'] . '">' . $_SESSION['UsersRealName']. '</a>';
199			} else {
200				$UserDetails  = ' ' . $_SESSION['UsersRealName'] . ' ';
201			}
202
203			foreach ($ItemArray as $ItemRow) {
204
205				if ($SupplierID != $ItemRow['supplierno']) {
206				/* This order item is purchased from a different supplier so need to finish off the authorisation of the previous order and start a new order */
207
208					if ($SupplierID != '' AND $_SESSION['AutoAuthorisePO'] == 1) {
209						/* if an order is/has been created already and the supplier of this item has changed - so need to finish off the order */
210						//if the user has authority to authorise the PO then it should be created as authorised
211						$AuthSQL ="SELECT authlevel
212					 				FROM purchorderauth
213								    WHERE userid = '" . $_SESSION['UserID'] . "'
214									AND currabrev = '" . $SuppRow['currcode'] . "'";
215
216						$AuthResult = DB_query($AuthSQL);
217						$AuthRow = DB_fetch_array($AuthResult);
218						if ($AuthRow['authlevel'] == '') {
219							$AuthRow['authlevel'] = 0;
220						}
221
222						if (DB_num_rows($AuthResult) > 0 AND $AuthRow['authlevel'] > $Order_Value) { //user has authority to authrorise as well as create the order
223							$StatusComment = date($_SESSION['DefaultDateFormat']) . ' - ' . _('Order Created and Authorised by') . ' ' . $UserDetails . ' - ' . _('Auto created from sales orders')  . '<br />';
224							$ErrMsg = _('Could not update purchase order status to Authorised');
225							$DbgMsg = _('The SQL that failed was');
226							$Result = DB_query("UPDATE purchorders SET allowprint = 1,
227												   status = 'Authorised',
228												   stat_comment = '" . $StatusComment . "'
229												WHERE orderno = '" . $PO_OrderNo . "'",
230												$ErrMsg,
231												$DbgMsg,
232												true);
233						} else { // no authority to authorise this order
234							if (DB_num_rows($AuthResult) == 0) {
235								$AuthMessage = _('Your authority to approve purchase orders in') . ' ' . $SuppRow['currcode'] . ' ' . _('has not yet been set up') . '<br />';
236							} else {
237								$AuthMessage = _('You can only authorise up to') . ' ' . $SuppRow['currcode'] . ' ' . $AuthRow['authlevel'] . '.<br />';
238							}
239
240							prnMsg( _('You do not have permission to authorise this purchase order') . '.<br />' .  _('This order is for') . ' ' .
241							$SuppRow['currcode'] . ' ' . $Order_Value . '. ' .
242							$AuthMessage . _('If you think this is a mistake please contact the systems administrator') . '<br />' .
243							_('The order has been created with a status of pending and will require authorisation'), 'warn');
244						}
245					} //end of authorisation status settings
246
247					if ($SupplierID != '') { //then we have just added a purchase order
248						echo '<br />';
249						prnMsg(_('Purchase Order') . ' ' . $PO_OrderNo . ' ' . _('on') . ' ' . $SupplierID . ' ' . _('has been created'),'success');
250						DB_Txn_Commit();
251					}
252
253		      /*Starting a new purchase order with a different supplier */
254					$Result = DB_Txn_Begin();
255
256					$PO_OrderNo =  GetNextTransNo(18); //get the next PO number
257
258					$SupplierID = $ItemRow['supplierno'];
259					$Order_Value = 0;
260					/*Now get all the required details for the supplier */
261					$SQL = "SELECT address1,
262	 							address2,
263	 							address3,
264	 							address4,
265	 							address5,
266	 							address6,
267	 							telephone,
268	 							paymentterms,
269	 							currcode,
270	 							rate
271						 FROM suppliers INNER JOIN currencies
272						    ON suppliers.currcode = currencies.currabrev
273						    WHERE supplierid = '" . $SupplierID . "'";
274
275					$ErrMsg = _('Could not get the supplier information for the order');
276					$SuppResult = DB_query($SQL, $ErrMsg);
277					$SuppRow = DB_fetch_array($SuppResult);
278
279					$StatusComment = date($_SESSION['DefaultDateFormat']) . ' - ' . _('Order Created by') . ' ' . $UserDetails . ' - ' . _('Auto created from sales orders')  . '<br />';
280					/*Insert to purchase order header record */
281					$SQL = "INSERT INTO purchorders ( orderno,
282		  									  supplierno,
283		  									  orddate,
284		  									  rate,
285		  									  initiator,
286		  									  intostocklocation,
287		  									  deladd1,
288		  									  deladd2,
289		  									  deladd3,
290		  									  deladd4,
291		  									  deladd5,
292		  									  deladd6,
293		  									  tel,
294		  									  suppdeladdress1,
295		  									  suppdeladdress2,
296		  									  suppdeladdress3,
297		  									  suppdeladdress4,
298		  									  suppdeladdress5,
299		  									  suppdeladdress6,
300		  									  supptel,
301		  									  contact,
302		  									  version,
303		  									  revised,
304		  									  deliveryby,
305		  									  status,
306		  									  stat_comment,
307		  									  deliverydate,
308		  									  paymentterms,
309		  									  allowprint)
310		  									VALUES(	'" . $PO_OrderNo . "',
311		  										'" . $SupplierID . "',
312		  										CURRENT_DATE,
313		  										'" . $SuppRow['rate'] . "',
314		  										'" . $_SESSION['UserID'] . "',
315		  										'" . $_SESSION['UserStockLocation'] . "',
316		  										'" . $DelAddRow['deladd1'] . "',
317		  										'" . $DelAddRow['deladd2'] . "',
318		  										'" . $DelAddRow['deladd3'] . "',
319		  										'" . $DelAddRow['deladd4'] . "',
320		  										'" . $DelAddRow['deladd5'] . "',
321		  										'" . $DelAddRow['deladd6'] . "',
322		  										'" . $DelAddRow['tel'] . "',
323		  										'" . $SuppRow['address1'] . "',
324		  										'" . $SuppRow['address2'] . "',
325		  										'" . $SuppRow['address3'] . "',
326		  										'" . $SuppRow['address4'] . "',
327		  										'" . $SuppRow['address5'] . "',
328		  										'" . $SuppRow['address6'] . "',
329		  										'" . $SuppRow['telephone'] . "',
330		  										'" . $SuppRow['contact'] . "',
331		  										'1.0',
332		  										CURRENT_DATE,
333		  										'" . $_SESSION['Default_Shipper'] . "',
334		  										'Pending',
335		  										'" . $StatusComment . "',
336		  										CURRENT_DATE,
337		  										'" . $SuppRow['paymentterms'] . "',
338		  										0)";
339
340					$ErrMsg =  _('The purchase order header record could not be inserted into the database because');
341					$DbgMsg = _('The SQL statement used to insert the purchase order header record and failed was');
342					$Result = DB_query($SQL, $ErrMsg, $DbgMsg, true);
343				} //end if it's a new supplier and PO to create
344
345				/*reminder we are in a loop of the total of each item to place a purchase order for based on a selection of sales orders */
346				$DeliveryDate = DateAdd(Date($_SESSION['DefaultDateFormat']),'d',$ItemRow['leadtime']);
347				$SQL = "INSERT INTO purchorderdetails ( orderno,
348		      									itemcode,
349		      									deliverydate,
350		      									itemdescription,
351		      									glcode,
352		      									unitprice,
353		      									quantityord,
354		      									suppliersunit,
355		      									suppliers_partno,
356		      									conversionfactor )
357					      VALUES ('" . $PO_OrderNo . "',
358		      						     '" . $ItemRow['stockid'] . "',
359		      						     '" . FormatDateForSQL($DeliveryDate) . "',
360		      						     '" . $ItemRow['suppliers_partno']  . '  ' . $ItemRow['supplierdescription']  . "',
361		      						     '" . $ItemRow['stockact'] . "',
362		      						     '" . $ItemRow['price']/$ItemRow['conversionfactor'] . "',
363		      						     '" . $ItemRow['orderqty'] . "',
364		      						     '" . $ItemRow['suppliersuom'] . "',
365		      						     '" . $ItemRow['suppliers_partno'] . "',
366		      						     '" . $ItemRow['conversionfactor']  . "')";
367				$ErrMsg =_('One of the purchase order detail records could not be inserted into the database because');
368				$DbgMsg =_('The SQL statement used to insert the purchase order detail record and failed was');
369
370				$Result =DB_query($SQL, $ErrMsg, $DbgMsg, true);
371				$Order_Value  += ($ItemRow['price']*$ItemRow['orderqty'] / $ItemRow['conversionfactor']);
372			} /* end of the loop round the items on the sales order  that we wish to place purchase orders for */
373
374
375			/* The last line to be purchase ordered was reach so there will be an order which is not yet completed in progress now to completed it */
376
377			if ($SupplierID != '' AND $_SESSION['AutoAuthorisePO'] == 1) {
378				//if the user has authority to authorise the PO then it should be created as authorised
379				$AuthSQL ="SELECT authlevel
380							FROM purchorderauth
381							WHERE userid = '" . $_SESSION['UserID'] . "'
382							AND currabrev = '" . $SuppRow['currcode'] . "'";
383
384				$AuthResult = DB_query($AuthSQL);
385				$AuthRow = DB_fetch_array($AuthResult);
386				if ($AuthRow['authlevel'] == '') {
387				      $AuthRow['authlevel'] = 0;
388				}
389
390				if (DB_num_rows($AuthResult) > 0 AND $AuthRow['authlevel'] > $Order_Value) { //user has authority to authrorise as well as create the order
391					$StatusComment = date($_SESSION['DefaultDateFormat']) . ' - ' . _('Order Created and Authorised by') . $UserDetails . ' - ' . _('Auto created from sales orders') . '<br />';
392					$ErrMsg = _('Could not update purchase order status to Authorised');
393					$DbgMsg = _('The SQL that failed was');
394					$Result = DB_query("UPDATE purchorders SET allowprint = 1,
395															status = 'Authorised',
396															stat_comment = '" . $StatusComment . "'
397												 WHERE orderno = '" . $PO_OrderNo . "'",
398												$ErrMsg,
399												$DbgMsg,
400												true);
401				} else { // no authority to authorise this order
402					if (DB_num_rows($AuthResult) == 0) {
403						$AuthMessage = _('Your authority to approve purchase orders in') . ' ' . $SuppRow['currcode'] . ' ' . _('has not yet been set up') . '<br />';
404					} else {
405						$AuthMessage = _('You can only authorise up to') . ' ' . $SuppRow['currcode'] . ' ' . $AuthRow['authlevel'] . '.<br />';
406					}
407
408					prnMsg( _('You do not have permission to authorise this purchase order') . '.<br />' .  _('This order is for') . ' ' . $SuppRow['currcode'] . ' ' . $Order_Value . '. ' . $AuthMessage . _('If you think this is a mistake please contact the systems administrator') . '<br />' .  _('The order has been created with a status of pending and will require authorisation'), 'warn');
409				}
410			} //end of authorisation status settings
411
412			if ($SupplierID != '') { //then we have just added a purchase order irrespective of autoauthorise status
413				echo '<br />';
414				prnMsg(_('Purchase Order') . ' ' . $PO_OrderNo . ' ' . _('on') . ' ' . $SupplierID . ' ' . _('has been created'),'success');
415				DB_Txn_Commit();
416			}
417			$Result = DB_query("UPDATE salesorders SET poplaced = 1 WHERE " . $OrdersToPlacePOFor);
418		}/*There were items that had purchasing data set up to create POs for */
419	} /* there were sales orders checked to place POs for */
420}/*end of purchase order creation code */
421/* ******************************************************************************************* */
422
423/*To the sales order selection form */
424
425echo '<p class="page_title_text"><img src="' . $RootPath . '/css/' . $Theme . '/images/sales.png" title="' . _('Sales') . '" alt="" />' . ' ' . _('Outstanding Sales Orders') . '</p> ';
426
427echo '<form action="' . htmlspecialchars($_SERVER['PHP_SELF'], ENT_QUOTES, 'UTF-8') . '" method="post">';
428echo '<div>';
429echo '<input type="hidden" name="FormID" value="' . $_SESSION['FormID'] . '" />';
430
431
432if (isset($_POST['ResetPart'])) {
433     unset($SelectedStockItem);
434}
435
436echo '<br /><div class="centre">';
437
438if (isset($_GET['OrderNumber'])) {
439	$OrderNumber = $_GET['OrderNumber'];
440} elseif (isset($_POST['OrderNumber'])) {
441	$OrderNumber = $_POST['OrderNumber'];
442} else {
443	unset($OrderNumber);
444}
445if (isset($_POST['CustomerRef'])) {
446	$CustomerRef = $_POST['CustomerRef'];
447}
448
449if (isset($OrderNumber) AND $OrderNumber != '') {
450	$OrderNumber = trim($OrderNumber);
451	if (!is_numeric($OrderNumber)) {
452		echo '<br />
453			<b>' . _('The Order Number entered MUST be numeric') . '</b>
454			<br />';
455		unset ($OrderNumber);
456		include('includes/footer.php');
457		exit;
458	} else {
459		echo _('Order Number') . ' - ' . $OrderNumber;
460	}
461} else {
462	if (isset($SelectedCustomer)) {
463		echo _('For customer') . ': ' . $SelectedCustomer . ' ' . _('and') . ' ';
464		echo '<input type="hidden" name="SelectedCustomer" value="' . $SelectedCustomer . '" />';
465	}
466	if (isset($SelectedStockItem)) {
467		 echo _('for the part') . ': ' . $SelectedStockItem . ' ' . _('and') . ' <input type="hidden" name="SelectedStockItem" value="' . $SelectedStockItem . '" />';
468	}
469}
470
471if (isset($_POST['SearchParts'])) {
472
473	$StockItemsResult = GetSearchItems();
474
475}
476
477if (isset($_POST['StockID'])) {
478	$StockID = trim(mb_strtoupper($_POST['StockID']));
479} elseif (isset($_GET['StockID'])) {
480	$StockID = trim(mb_strtoupper($_GET['StockID']));
481}
482
483if (!isset($StockID)) {
484
485     /* Not appropriate really to restrict search by date since may miss older
486     ouststanding orders
487	$OrdersAfterDate = Date('d/m/Y',Mktime(0,0,0,Date('m')-2,Date('d'),Date('Y')));
488     */
489
490	if (!isset($OrderNumber) OR $OrderNumber == '') {
491
492		echo '<table class="selection">
493			<tr>
494				<td>' . _('Order number') . ': </td>
495				<td><input type="text" name="OrderNumber" maxlength="8" size="9" /></td>
496				<td>' . _('From Stock Location') . ':</td>
497				<td><select name="StockLocation"> ';
498
499		$SQL = "SELECT locationname,
500						locations.loccode
501				FROM locations
502				INNER JOIN locationusers
503					ON locationusers.loccode = locations.loccode
504					AND locationusers.userid = '" .  $_SESSION['UserID'] . "'
505					AND locationusers.canview = 1";
506		$ResultStkLocs = DB_query($SQL);
507
508		while ($MyRow = DB_fetch_array($ResultStkLocs)) {
509			if (isset($_POST['StockLocation'])) {
510				if ($MyRow['loccode'] == $_POST['StockLocation']) {
511				     echo '<option selected="selected" value="' . $MyRow['loccode'] . '">' . $MyRow['locationname'] . '</option>';
512				} else {
513				     echo '<option value="' . $MyRow['loccode'] . '">' . $MyRow['locationname']. '</option>';
514				}
515			} elseif ($MyRow['loccode'] == $_SESSION['UserStockLocation']) {
516				 echo '<option selected="selected" value="' . $MyRow['loccode'] . '">' . $MyRow['locationname']. '</option>';
517			} else {
518				 echo '<option value="' . $MyRow['loccode'] . '">' . $MyRow['locationname']. '</option>';
519			}
520		}
521
522		echo '</select></td>
523			<td><select name="Quotations">';
524
525		if ( $_POST['Quotations'] == 'Quotes_Only' ) {
526			echo '<option selected="selected" value="Quotes_Only">' . _('Quotations Only') . '</option>';
527			echo '<option value="Orders_Only">' . _('Orders Only')  . '</option>';
528			echo '<option value="Overdue_Only">' . _('Overdue Only') . '</option>';
529		} elseif ( $_POST['Quotations'] == 'Overdue_Only' ) {
530			echo '<option selected="selected" value="Overdue_Only">' . _('Overdue Only') . '</option>';
531			echo '<option value="Quotes_Only">' . _('Quotations Only') . '</option>';
532			echo '<option value="Orders_Only">' . _('Orders Only') . '</option>';
533		} else {
534			echo '<option selected="selected" value="Orders_Only">' . _('Orders Only') . '</option>';
535			echo '<option value="Quotes_Only">' . _('Quotations Only') . '</option>';
536			echo '<option value="Overdue_Only">' . _('Overdue Only') . '</option>';
537		}
538
539		if (!isset($_POST['DueDateFrom'])) {
540			$_POST['DueDateFrom'] = '';
541		}
542		if (!isset($_POST['DueDateTo'])) {
543			$_POST['DueDateTo'] = '';
544		}
545		if (!isset($_POST['CustomerRef'])) {
546			$_POST['CustomerRef'] = '';
547		}
548		if (!isset($_POST['OrderDateFrom'])) {
549			$_POST['OrderDateFrom'] = '';
550		}
551		if (!isset($_POST['OrderDateTo'])) {
552			$_POST['OrderDateTo'] = '';
553		}
554
555
556		echo '</select>
557				</td>
558			</tr>
559			<tr>
560				<td>' . _('Customer Ref') . '</td>
561				<td><input type="text" name="CustomerRef" value="' . $_POST['CustomerRef'] . '" size="12" /></td>
562			</tr>
563			<tr>
564				<td>' . _('Due Date From') . '</td>
565				<td><input type="text" class="date" name="DueDateFrom" value="' . $_POST['DueDateFrom'] . '" size="10" /></td>
566				<td>' . _('Due Date To') . '</td>
567				<td><input type="text" class="date" name="DueDateTo" value="' . $_POST['DueDateTo'] . '" size="10" /></td>
568			</tr>
569			<tr>
570				<td>' . _('Order Date From') . '</td>
571				<td><input type="text" name="OrderDateFrom" value="' . $_POST['OrderDateFrom'] . '" size="10" class="date" /></td>
572				<td>' . _('Order Date To') . '</td>
573				<td><input type="text" name="OrderDateTo" value="' . $_POST['OrderDateTo'] . '" size="10" class="date" /></td>
574			</tr>
575			<tr>
576				<td>&nbsp;</td>
577				<td><input type="submit" name="SearchOrders" value="' . _('Search') . '" /></td>
578				<td><input type="submit" name="Reset" value="' . _('Reset') . '" /></td>
579				<td><a href="' . $RootPath . '/SelectOrderItems.php?NewOrder=Yes">' . _('Add Sales Order') . '</a></td>
580				<td>&nbsp;</td>
581			</tr>
582		</table>';
583	}
584
585	$SQL="SELECT categoryid,
586			categorydescription
587		FROM stockcategory
588		ORDER BY categorydescription";
589
590	$Result1 = DB_query($SQL);
591
592	if (!isset($_POST['Keywords'])) {
593		$_POST['Keywords'] = '';
594	}
595	if (!isset($_POST['StockCode'])) {
596		$_POST['StockCode'] = '';
597	}
598
599	echo '<br />
600		<table class="selection">
601		<tr>
602			<th colspan="6"><h3>' . _('To search for sales orders for a specific part use the part selection facilities below') . '</h3></th>
603		</tr>
604		<tr>
605      		<td>' . _('Select a stock category') . ':
606      			<select name="StockCat">';
607		echo '<option value="All">' . _('All') . '</option>';
608
609	while ($MyRow1 = DB_fetch_array($Result1)) {
610		if (isset($_POST['StockCat']) and $_POST['StockCat'] == $MyRow1['categoryid']) {
611			echo '<option selected="selected" value="'. $MyRow1['categoryid'] . '">' . $MyRow1['categorydescription'] . '</option>';
612		} else {
613			echo '<option value="'. $MyRow1['categoryid'] . '">' . $MyRow1['categorydescription'] . '</option>';
614		}
615	}
616
617	echo '</select></td>
618			<td>' . _('Enter text extract(s) in the description') . ':</td>
619			<td><input type="text" name="Keywords" size="20" maxlength="25" /></td>
620		</tr>
621      	<tr>
622			<td></td>
623      		<td><b>' . _('OR') . ' </b>' . _('Enter extract of the Stock Code') . ':</td>
624      		<td><input type="text" name="StockCode" size="15" maxlength="18"  value="' . $_POST['StockCode'] . '" /></td>
625      	</tr>
626      </table>';
627	echo '<br />
628			<input type="submit" name="SearchParts" value="' . _('Search Parts Now') . '" />
629			<input type="submit" name="ResetPart" value="' . _('Show All') . '" />
630		</div>
631		<br />';
632
633if (isset($StockItemsResult)
634	AND DB_num_rows($StockItemsResult) > 1) {
635
636	echo '<table cellpadding="2" class="selection">
637		<thead>
638			<tr>
639			<th class="ascending" >' . _('Code') . '</th>
640			<th class="ascending" >' . _('Description') . '</th>
641			<th class="ascending" >' . _('On Hand') . '</th>
642			<th>' . _('Units') . '</th>
643			</tr>
644		</thead>
645		<tbody>';
646
647	while ($MyRow = DB_fetch_array($StockItemsResult)) {
648
649		printf('<tr class="striped_row">
650				<td><input type="submit" name="SelectedStockItem" value="%s" /></td>
651				<td>%s</td>
652				<td class="number">%s</td>
653				<td>%s</td>
654				</tr>',
655				$MyRow['stockid'],
656				$MyRow['description'],
657				locale_number_format($MyRow['qoh'],$MyRow['decimalplaces']),
658				$MyRow['units']);
659//end of page full new headings if
660	}
661//end of while loop
662
663	echo '</tbody></table>';
664
665}
666//end if stock search results to show
667  else {
668	 if (isset($StockItemsResult) AND DB_num_rows($StockItemsResult) == 1) {
669		 $mystkrow = DB_fetch_array($StockItemsResult);
670		 $SelectedStockItem = $mystkrow['stockid'];
671	 }
672
673	//figure out the SQL required from the inputs available
674	if( $_POST['Quotations'] == 'Orders_Only' ) {
675		$Quotations = 0;
676	}
677	elseif( $_POST['Quotations'] == 'Quotes_Only' ) {
678		$Quotations = 1;
679	}
680	elseif( $_POST['Quotations'] == 'Overdue_Only' ) {
681		$Quotations = "0 AND itemdue < CURRENT_DATE";
682	}
683	else {
684		$_POST['Quotations'] = 'Orders_Only';
685		$Quotations = 0;
686	}
687
688	if (isset($_POST['DueDateFrom']) AND is_date($_POST['DueDateFrom'])) {
689		$DueDateFrom = " AND itemdue >= '"  . FormatDateForSQL($_POST['DueDateFrom']) . "' ";
690	} else {
691		$DueDateFrom = '';
692	}
693	if (isset($_POST['DueDateTo']) AND is_date($_POST['DueDateTo'])) {
694		$DueDateTo = " AND itemdue <= '" . FormatDateForSQL($_POST['DueDateTo']) . "'";
695	} else {
696		$DueDateTo = '';
697	}
698	if (isset($_POST['OrderDateFrom']) AND is_date($_POST['OrderDateFrom'])) {
699		$OrderDateFrom = " AND orddate >= '" . FormatDateForSQL($_POST['OrderDateFrom']) . "' ";
700	} else {
701		$OrderDateFrom = '';
702	}
703	if (isset($_POST['OrderDateTo']) AND is_date($_POST['OrderDateTo'])) {
704		$OrderDateTo = " AND orddate <= '" . FormatDateForSQL($_POST['OrderDateTo']) . "' ";
705	} else {
706		$OrderDateTo = '';
707	}
708
709	if(!isset($_POST['StockLocation'])) {
710		$_POST['StockLocation'] = $_SESSION['UserStockLocation'];
711	}
712
713	if ($_SESSION['SalesmanLogin'] != '') {
714		$SalesMan = '=\'' . $_SESSION['SalesmanLogin'] . '\'';
715	} else {
716		$SalesMan = ' LIKE \'%\'';
717	}
718
719	//Harmonize the ordervalue with SUM function since webERP allowed same items appeared several times in one sales orders. If there is no sum value, this situation not inclued.
720	//We should separate itemdue inquiry from normal inquiry.
721	if (($Quotations === 0 OR $Quotations === 1)
722		AND (!isset($DueDateFrom) OR !is_date($DueDateFrom))
723		AND (!isset($DueDateTo) OR !is_date($DueDateTo))) {
724
725			$SQL = "SELECT salesorders.orderno,
726					debtorsmaster.name,
727					custbranch.brname,
728					salesorders.customerref,
729					salesorders.orddate,
730					salesorders.deliverydate,
731					salesorders.deliverto,
732					salesorders.printedpackingslip,
733					salesorders.poplaced,
734					SUM(salesorderdetails.unitprice*(salesorderdetails.quantity-salesorderdetails.qtyinvoiced)*(1-salesorderdetails.discountpercent)/currencies.rate) AS ordervalue,
735					pickreq.prid
736				FROM salesorders
737				INNER JOIN salesorderdetails
738					ON salesorders.orderno = salesorderdetails.orderno
739				INNER JOIN debtorsmaster
740					ON salesorders.debtorno = debtorsmaster.debtorno
741				INNER JOIN custbranch
742					ON debtorsmaster.debtorno = custbranch.debtorno
743					AND salesorders.branchcode = custbranch.branchcode
744				INNER JOIN currencies
745					ON debtorsmaster.currcode = currencies.currabrev
746				LEFT OUTER JOIN pickreq
747					ON pickreq.orderno = salesorders.orderno
748					AND pickreq.closed = 0
749				WHERE salesorderdetails.completed = 0 ";
750			$SQL .= $OrderDateFrom . $OrderDateTo;
751		} else {
752			if ($Quotations !== 0 AND $Quotations !== 1) {//overdue inquiry only
753				$SQL = "SELECT salesorders.orderno,
754						debtorsmaster.name,
755						custbranch.brname,
756						salesorders.customerref,
757						salesorders.orddate,
758						salesorders.deliverydate,
759						salesorders.deliverto,
760						salesorders.printedpackingslip,
761						salesorders.poplaced,
762						SUM(CASE WHEN itemdue < CURRENT_DATE
763						     THEN salesorderdetails.unitprice*(salesorderdetails.quantity-salesorderdetails.qtyinvoiced)*(1-salesorderdetails.discountpercent)/currencies.rate
764						     ELSE 0 END) as ordervalue";
765			} elseif (isset($DueDateFrom) AND is_date($DueDateFrom) AND (!isset($DueDateTo) OR !is_date($DueDateTo))) {
766					$SQL = "SELECT salesorders.orderno,
767						debtorsmaster.name,
768						custbranch.brname,
769						salesorders.customerref,
770						salesorders.orddate,
771						salesorders.deliverydate,
772						salesorders.deliverto,
773						salesorders.printedpackingslip,
774						salesorders.poplaced,
775						SUM(CASE WHEN itemdue >= '" . FormatDateFromSQL($DueDateFrom) . "'
776						     THEN salesorderdetails.unitprice*(salesorderdetails.quantity-salesorderdetails.qtyinvoiced)*(1-salesorderdetails.discountpercent)/currencies.rate
777						     ELSE 0 END) as ordervalue";
778			} elseif (isset($DueDateFrom) AND is_date($DueDateFrom) AND isset($DueDateTo) AND is_date($DueDateTo)) {
779					$SQL = "SELECT salesorders.orderno,
780						debtorsmaster.name,
781						custbranch.brname,
782						salesorders.customerref,
783						salesorders.orddate,
784						salesorders.deliverydate,
785						salesorders.deliverto,
786						salesorders.printedpackingslip,
787						salesorders.poplaced,
788						SUM (CASE WHEN itemdue >= '" . FormatDateForSQL($DueDateFrom) . "' AND itemdue <= '" . FormatDateForSQL($DueDateTo) . "'
789						     THEN salesorderdetails.unitprice*(salesorderdetails.quantity-salesorderdetails.qtyinvoiced)*(1-salesorderdetails.discountpercent)/currencies.rate
790						     ELSE 0 END) as ordervalue";
791			} elseif ((!isset($DueDateFrom) OR !is_date($DueDateFrom)) AND isset($DueDateTo) AND is_date($DueDateTo)) {
792						$SQL = "SELECT salesorders.orderno,
793						debtorsmaster.name,
794						custbranch.brname,
795						salesorders.customerref,
796						salesorders.orddate,
797						salesorders.deliverydate,
798						salesorders.deliverto,
799						salesorders.printedpackingslip,
800						salesorders.poplaced,
801						SUM(CASE WHEN AND itemdue <= '" . FormatDateForSQL($DueDateTo) . "'
802						     THEN salesorderdetails.unitprice*(salesorderdetails.quantity-salesorderdetails.qtyinvoiced)*(1-salesorderdetails.discountpercent)/currencies.rate
803						     ELSE 0 END) as ordervalue";
804			}//end of due date inquiry
805
806				$SQL .= " FROM salesorders INNER JOIN salesorderdetails
807						ON salesorders.orderno = salesorderdetails.orderno
808						INNER JOIN debtorsmaster
809						ON salesorders.debtorno = debtorsmaster.debtorno
810						INNER JOIN custbranch
811						ON debtorsmaster.debtorno = custbranch.debtorno
812						AND salesorders.branchcode = custbranch.branchcode
813						INNER JOIN currencies
814						ON debtorsmaster.currcode = currencies.currabrev
815						WHERE salesorderdetails.completed = 0 ";
816
817				$SQL .= $OrderDateFrom . $OrderDateTo;
818		}
819
820		//Add salesman role control
821			if ($_SESSION['SalesmanLogin'] != '') {
822				$SQL .= " AND salesorders.salesperson = '" . $_SESSION['SalesmanLogin'] . "'";
823			}
824
825			if (isset($OrderNumber) AND $OrderNumber != '') {
826
827				$SQL .= "AND salesorders.orderno = " . $OrderNumber . "
828				    AND salesorders.quotation = " . $Quotations;
829
830			} elseif (isset($CustomerRef) AND $CustomerRef != '') {
831				$SQL .= "AND salesorders.customerref = '" . $CustomerRef . "'
832					AND salesorders.quotation = " . $Quotations;
833
834			} else {
835
836				if (isset($SelectedCustomer)) {
837
838					if (isset($SelectedStockItem)) {
839						$SQL .= "AND salesorders.quotation = " . $Quotations . "
840							AND salesorderdetails.stkcode = '" . $SelectedStockItem . "'
841							AND salesorders.debtorno = '" . $SelectedCustomer . "'
842							AND salesorders.fromstkloc = '" . $_POST['StockLocation'] . "'";
843
844					} else {
845						$SQL .= "AND  salesorders.quotation = " . $Quotations . "
846							AND salesorders.debtorno = '" . $SelectedCustomer . "'
847							AND salesorders.fromstkloc = '" . $_POST['StockLocation'] . "'";
848
849					}
850				} else { //no customer selected
851					if (isset($SelectedStockItem)) {
852							$SQL .= "AND salesorders.quotation = " . $Quotations . "
853								AND salesorderdetails.stkcode = '" . $SelectedStockItem . "'
854								AND salesorders.fromstkloc = '" . $_POST['StockLocation'] . "'";
855					} else {
856							$SQL .= "AND salesorders.quotation = " . $Quotations . "
857								AND salesorders.fromstkloc = '" . $_POST['StockLocation'] . "'";
858					}
859
860				} //end selected customer
861				$SQL .= $DueDateFrom . $DueDateTo;
862
863				$SQL .= ' GROUP BY salesorders.orderno,
864							debtorsmaster.name,
865							custbranch.brname,
866							salesorders.customerref,
867							salesorders.orddate,
868							salesorders.deliverydate,
869							salesorders.deliverto,
870							salesorders.printedpackingslip,
871							salesorders.poplaced
872							ORDER BY salesorders.orderno';
873			} //end not order number selected
874
875	$ErrMsg = _('No orders or quotations were returned by the SQL because');
876	$SalesOrdersResult = DB_query($SQL, $ErrMsg);
877
878	/*show a table of the orders returned by the SQL */
879	if (DB_num_rows($SalesOrdersResult) > 0) {
880
881		/* Get users authority to place POs */
882		$AuthSQL = "SELECT cancreate
883					FROM purchorderauth
884					WHERE userid = '" . $_SESSION['UserID'] . "'";
885
886		/*we don't know what currency these orders might be in but if no authority at all then don't show option*/
887		$AuthResult = DB_query($AuthSQL);
888
889		$AuthRow = DB_fetch_array($AuthResult);
890
891		echo '<table cellpadding="2" width="95%" class="selection">';
892		if (is_null($AuthRow['cancreate']) or !isset($AuthRow)) {
893			$AuthRow['cancreate'] = 1;
894		}
895
896		$PrintPickLabel = '';
897		if ($_SESSION['RequirePickingNote'] == 1) {
898			$PrintPickLabel = '<th>' . _('Pick Lists') . '</th>';
899		}
900
901		echo '<thead>';
902
903		if ( $_POST['Quotations'] == 'Orders_Only' OR $_POST['Quotations'] == 'Overdue_Only' ) {
904			echo '<tr>
905								<th class="ascending" >' . _('Modify') . '</th>
906								<th>' . _('Acknowledge') . '</th>
907								' . $PrintPickLabel . '
908								<th>' . _('Invoice') . '</th>
909								<th>' . _('Dispatch Note') . '</th>
910								<th>' . _('Labels') . '</th>
911								<th class="ascending" >' . _('Customer') . '</th>
912								<th class="ascending" >' . _('Branch') . '</th>
913								<th class="ascending" >' . _('Cust Order') . ' #</th>
914								<th class="ascending" >' . _('Order Date') . '</th>
915								<th class="ascending" >' . _('Req Del Date') . '</th>
916								<th class="ascending" >' . _('Delivery To') . '</th>
917								<th class="ascending" >' . _('Order Total') . '<br />' . $_SESSION['CompanyRecord']['currencydefault'] . '</th>';
918
919			if ($AuthRow['cancreate'] == 0) { //If cancreate == 0 then this means the user can create orders hmmm!!
920				echo '<th>' . _('Place PO') . '</th>';
921			}
922
923			echo '</tr>';
924		} else {  /* displaying only quotations */
925			echo '<tr>
926								<th class="ascending">' . _('Modify') . '</th>
927								<th>' . _('Print Quote') . '</th>
928								<th class="ascending" >' . _('Customer') . '</th>
929								<th class="ascending" >' . _('Branch') . '</th>
930								<th class="ascending" >' . _('Cust Ref') . ' #</th>
931								<th class="ascending" >' . _('Quote Date') . '</th>
932								<th class="ascending" >' . _('Req Del Date') . '</th>
933								<th class="ascending" >' . _('Delivery To') . '</th>
934								<th class="ascending" >' . _('Quote Total') .  '<br />' . $_SESSION['CompanyRecord']['currencydefault'] . '</th>
935							</tr>';
936		}
937
938		echo '</thead>
939			<tbody>';
940
941		$OrdersTotal = 0;
942
943		while ($MyRow = DB_fetch_array($SalesOrdersResult)) {
944
945			$ModifyPage = $RootPath . '/SelectOrderItems.php?ModifyOrderNumber=' . urlencode($MyRow['orderno']);
946			$Confirm_Invoice = $RootPath . '/ConfirmDispatch_Invoice.php?OrderNumber=' . urlencode($MyRow['orderno']);
947			$PrintPickList = '';
948			$PrintPickLabel = '';
949			$PrintDummyFlag = '<input type="hidden" name="dummy" value="%s" />';
950			if ($_SESSION['RequirePickingNote'] == 1) {
951				$PrintPickList = $RootPath . '/GeneratePickingList.php?TransNo=' . urlencode($MyRow['orderno']);
952				if (isset($MyRow['prid']) and $MyRow['prid'] > '') {
953					$PrintPickLabel = '<td><a href="' . $RootPath . '/GeneratePickingList.php?TransNo=' . urlencode($MyRow['orderno']) . '">' . str_pad($MyRow['prid'], 10, '0', STR_PAD_LEFT) . '</a></td>';
954				} else {
955					$PrintPickLabel = '<td><a href="' . $RootPath . '/GeneratePickingList.php?TransNo=' . urlencode($MyRow['orderno']) . '">' . _('Pick') . '</a></td>';
956				}
957				$PrintDummyFlag = '';
958			}
959
960			if ($_SESSION['PackNoteFormat'] == 1) { /*Laser printed A4 default */
961				$PrintDispatchNote = $RootPath . '/PrintCustOrder_generic.php?TransNo=' . urlencode($MyRow['orderno']);
962			} else { /*pre-printed stationery default */
963				$PrintDispatchNote = $RootPath . '/PrintCustOrder.php?TransNo=' . urlencode($MyRow['orderno']);
964			}
965			$PrintQuotation = $RootPath . '/PDFQuotation.php?QuotationNo=' . urlencode($MyRow['orderno']);
966			$PrintQuotationPortrait = $RootPath . '/PDFQuotationPortrait.php?QuotationNo=' . urlencode($MyRow['orderno']);
967			$FormatedDelDate = ConvertSQLDate($MyRow['deliverydate']);
968			$FormatedOrderDate = ConvertSQLDate($MyRow['orddate']);
969			$FormatedOrderValue = locale_number_format($MyRow['ordervalue'],$_SESSION['CompanyRecord']['decimalplaces']);
970			if ($MyRow['customerref'] !== '') {
971				$CustomerRef = '<a href="' . $RootPath . '/SelectCompletedOrder.php?CustomerRef=' . urlencode($MyRow['customerref']) . '" target="_blank">' . $MyRow['customerref'] . '</a>';
972			} else {
973				$CustomerRef = '';
974			}
975			$OrdersTotal += $MyRow['ordervalue'];
976			$PrintAck = $RootPath . '/PDFAck.php?AcknowledgementNo=' . urlencode($MyRow['orderno']);
977
978			if (!isset($PricesSecurity) or !in_array($PricesSecurity, $_SESSION['AllowedPageSecurityTokens'])) {
979				$FormatedOrderValue = '---------';
980			}
981
982			if ($MyRow['printedpackingslip'] == 0) {
983			  $PrintText = _('Print');
984			} else {
985			  $PrintText = _('Reprint');
986			}
987
988			$PrintLabels = $RootPath . '/PDFShipLabel.php?Type=Sales&ORD=' . urlencode($MyRow['orderno']);
989
990			if ($_POST['Quotations'] == 'Orders_Only' OR $_POST['Quotations'] == 'Overdue_Only') {
991				echo '<tr class="striped_row">
992							<td><a href="', $ModifyPage, '">', $MyRow['orderno'], '</a></td>
993							<td><a href="', $PrintAck, '">', _('Acknowledge'), '</a>', $PrintDummyFlag, '</td>
994							', $PrintPickLabel, '
995							<td><a href="', $Confirm_Invoice, '">', _('Invoice'), '</a></td>
996			 				<td><a href="', $PrintDispatchNote, '" target="_blank">', $PrintText, ' <img src="', $RootPath, '/css/', $Theme, '/images/pdf.png" title="', _('Click for PDF'), '" alt="" /></a></td>
997							<td><a href="', $PrintLabels, '">', _('Labels'), '</a></td>
998			 				<td>', $MyRow['name'], '</td>
999			 				<td>', $MyRow['brname'], '</td>
1000							<td>', $CustomerRef, '</td>
1001			 				<td>', $FormatedOrderDate, '</td>
1002			 				<td>', $FormatedDelDate, '</td>
1003			 				<td>', html_entity_decode($MyRow['deliverto'], ENT_QUOTES, 'UTF-8'), '</td>
1004			 				<td class="number">', $FormatedOrderValue, '</td>
1005			 				<td class="centre">';
1006			 /*Check authority to create POs if user has authority then show the check boxes to select sales orders to place POs for otherwise don't provide this option */
1007				if ($AuthRow['cancreate'] == 0 AND $MyRow['poplaced'] == 0) { //cancreate == 0 if the user can create POs and not already placed
1008					echo '<input type="checkbox" name="PlacePO_[]" value="', $MyRow['orderno'], '"/>';
1009				} else {  /*User is not authorised to create POs so don't even show the option */
1010					echo '&nbsp;';
1011				}
1012				echo		'</td>
1013						</tr>';
1014
1015			} else { /*must be quotes only */
1016				printf('<tr class="striped_row">
1017						<td><a href="%s">%s</a></td>
1018						<td><a href="%s" target="_blank">' . _('Landscape') . '</a>&nbsp;&nbsp;<a target="_blank" href="%s">' . _('Portrait') . '</a></td>
1019						<td>%s</td>
1020						<td>%s</td>
1021						<td>%s</td>
1022						<td>%s</td>
1023						<td>%s</td>
1024						<td>%s</td>
1025						<td class="number">%s</td>
1026						</tr>',
1027						$ModifyPage,
1028						$MyRow['orderno'],
1029						$PrintQuotation,
1030						$PrintQuotationPortrait,
1031						$MyRow['name'],
1032						$MyRow['brname'],
1033						$MyRow['customerref'],
1034						$FormatedOrderDate,
1035						$FormatedDelDate,
1036						html_entity_decode($MyRow['deliverto'], ENT_QUOTES, 'UTF-8'),
1037						$FormatedOrderValue);
1038			}
1039		}//end while loop through orders to display
1040
1041		echo '</tbody>
1042			<tfoot>
1043				<tr>
1044					<td colspan="', ($PrintPickLabel <> '' ? '12' : '11'), '" class="number"><b>';
1045
1046		if ($_POST['Quotations'] == 'Orders_Only') {
1047			echo _('Total Order(s) Value in');
1048		} else {
1049			echo _('Total Quotation(s) Value in');
1050		}
1051		if (!isset($PricesSecurity) or !in_array($PricesSecurity, $_SESSION['AllowedPageSecurityTokens'])) {
1052			$OrdersTotal = '---------';
1053		}
1054
1055		echo ' ' . $_SESSION['CompanyRecord']['currencydefault'] . ':</b></td>
1056			<td class="number"><b>' . locale_number_format($OrdersTotal,$_SESSION['CompanyRecord']['decimalplaces']) . '</b></td>';
1057
1058		if ($_POST['Quotations'] == 'Orders_Only' AND $AuthRow['cancreate'] == 0) { //cancreate == 0 means can create POs
1059			echo '<td>
1060					<input type="submit" name="PlacePO" value="' . _('Place') . " " . _('PO') . '" onclick="return confirm(\'' . _('This will create purchase orders for all the items on the checked sales orders above, based on the preferred supplier purchasing data held in the system. Are You Absolutely Sure?') . '\');" />
1061				</td>';
1062		}
1063
1064		echo '</tr>
1065			</tfoot>
1066		</table>';
1067	} //end if there are some orders to show
1068}
1069
1070echo '</div>
1071      </form>';
1072
1073} //end StockID already selected
1074
1075include('includes/footer.php');
1076
1077function GetSearchItems ($SqlConstraint = '') {
1078
1079	if ($_POST['Keywords'] AND $_POST['StockCode']) {
1080		 echo _('Stock description keywords have been used in preference to the Stock code extract entered');
1081	}
1082
1083	$SQL =  "SELECT stockmaster.stockid,
1084				   stockmaster.description,
1085				   stockmaster.decimalplaces,
1086				   SUM(locstock.quantity) AS qoh,
1087				   stockmaster.units
1088			FROM salesorderdetails INNER JOIN stockmaster
1089				ON salesorderdetails.stkcode = stockmaster.stockid AND completed = 0
1090			INNER JOIN locstock
1091			  ON stockmaster.stockid = locstock.stockid";
1092
1093	if (isset($_POST['StockCat'])
1094		AND ((trim($_POST['StockCat']) == '') OR $_POST['StockCat'] == 'All')) {
1095		 $WhereStockCat = '';
1096	} else {
1097		 $WhereStockCat = " AND stockmaster.categoryid = '" . $_POST['StockCat'] . "' ";
1098	}
1099
1100	if ($_POST['Keywords']) {
1101		 //insert wildcard characters in spaces
1102		 $SearchString = '%' . str_replace(' ', '%', $_POST['Keywords']) . '%';
1103
1104		 $SQL .= " WHERE stockmaster.description " . LIKE . " '" . $SearchString . "' " . $WhereStockCat;
1105
1106	 } elseif (isset($_POST['StockCode'])) {
1107		 $SQL .= " WHERE stockmaster.stockid " . LIKE . " '%" . $_POST['StockCode'] . "%'" . $WhereStockCat;
1108
1109	 } elseif (!isset($_POST['StockCode']) AND !isset($_POST['Keywords'])) {
1110		 $SQL .= " WHERE stockmaster.categoryid = '" . $_POST['StockCat'] . "'";
1111
1112	 }
1113
1114	$SQL .= $SqlConstraint;
1115	$SQL .= " GROUP BY stockmaster.stockid,
1116					    stockmaster.description,
1117					    stockmaster.decimalplaces,
1118					    stockmaster.units
1119					    ORDER BY stockmaster.stockid";
1120
1121	$ErrMsg =  _('No stock items were returned by the SQL because');
1122	$DbgMsg = _('The SQL used to retrieve the searched parts was');
1123	$StockItemsResult = DB_query($SQL, $ErrMsg, $DbgMsg);
1124
1125	return $StockItemsResult;
1126}
1127?>
1128