- modules/fotolab updated imagej to current version & some cod fixes to make it work
[care2x.git] / Care2007 / modules / weberp / SelectCreditItems.php
blobcdfe31c3279ba31041ca39d81849437c054ce4cf
1 <?php
3 /* $Revision: 1.25 $ */
5 /*The credit selection screen uses the Cart class used for the making up orders
6 some of the variable names refer to order - please think credit when you read order */
8 $PageSecurity = 3;
10 include('includes/DefineCartClass.php');
11 include('includes/DefineSerialItems.php');
12 /* Session started in session.inc for password checking and authorisation level check */
13 include('includes/session.inc');
15 $title = _('Create Credit Note');
17 include('includes/header.inc');
18 include('includes/SQL_CommonFunctions.inc');
19 include('includes/GetSalesTransGLCodes.inc');
20 include('includes/GetPrice.inc');
23 if (isset($_POST['ProcessCredit']) AND !isset($_SESSION['CreditItems'])){
24 prnMsg(_('This credit note has already been processed. Refreshing the page will not enter the credit note again') . '<BR>' . _('Please use the navigation links provided rather than using the browser back button and then having to refresh'),'info');
25 echo '<BR><A HREF="' . $rootpath . '/index.php?' . SID . '">' . _('Back to the menu') . '</A>';
26 include('includes/footer.inc');
27 exit;
30 if (isset($_GET['NewCredit'])){
31 /*New credit note entry - clear any existing credit note details from the Items object and initiate a newy*/
32 if (isset($_SESSION['CreditItems'])){
33 unset ($_SESSION['CreditItems']->LineItems);
34 unset ($_SESSION['CreditItems']);
39 if (!isset($_SESSION['CreditItems'])){
40 /* It must be a new credit note being created $_SESSION['CreditItems'] would be set up from a previous call*/
42 $_SESSION['CreditItems'] = new cart;
44 $_SESSION['RequireCustomerSelection'] = 1;
47 if (isset($_POST['ChangeCustomer'])){
48 $_SESSION['RequireCustomerSelection']=1;
51 if (isset($_POST['Quick'])){
52 unset($_POST['PartSearch']);
55 if (isset($_POST['CancelCredit'])) {
56 unset($_SESSION['CreditItems']->LineItems);
57 unset($_SESSION['CreditItems']);
58 $_SESSION['CreditItems'] = new cart;
59 $_SESSION['RequireCustomerSelection'] = 1;
63 if (isset($_POST['SearchCust']) AND $_SESSION['RequireCustomerSelection']==1){
65 If ($_POST['Keywords'] AND $_POST['CustCode']) {
66 $msg=_('Customer name keywords have been used in preference to the customer code extract entered');
68 If ($_POST['Keywords']=='' AND $_POST['CustCode']=='') {
69 $msg=_('At least one Customer Name keyword OR an extract of a Customer Code must be entered for the search');
70 } else {
71 If (strlen($_POST['Keywords'])>0) {
72 //insert wildcard characters in spaces
74 $i=0;
75 $SearchString = '%';
76 while (strpos($_POST['Keywords'], ' ', $i)) {
77 $wrdlen=strpos($_POST['Keywords'],' ',$i) - $i;
78 $SearchString=$SearchString . substr($_POST['Keywords'],$i,$wrdlen) . '%';
79 $i=strpos($_POST['Keywords'],' ',$i) +1;
81 $SearchString = $SearchString. substr($_POST['Keywords'],$i).'%';
84 $SQL = 'SELECT
85 custbranch.debtorno,
86 custbranch.brname,
87 custbranch.contactname,
88 custbranch.phoneno,
89 custbranch.faxno,
90 custbranch.branchcode
91 FROM custbranch
92 WHERE custbranch.brname ' . LIKE ."'$SearchString'
93 AND custbranch.disabletrans=0";
95 } elseif (strlen($_POST['CustCode'])>0){
96 $SQL = 'SELECT
97 custbranch.debtorno,
98 custbranch.brname,
99 custbranch.contactname,
100 custbranch.phoneno,
101 custbranch.faxno,
102 custbranch.branchcode
103 FROM custbranch
104 WHERE custbranch.branchcode ' . LIKE . "'%" . $_POST['CustCode'] . "%'
105 AND custbranch.disabletrans=0";
108 $ErrMsg = _('Customer branch records requested cannot be retrieved because');
109 $DbgMsg = _('SQL used to retrieve the customer details was');
110 $result_CustSelect = DB_query($SQL,$db,$ErrMsg,$DbgMsg);
113 if (DB_num_rows($result_CustSelect)==1){
114 $myrow=DB_fetch_array($result_CustSelect);
115 $_POST['Select'] = $myrow['debtorno'] . ' - ' . $myrow['branchcode'];
116 } elseif (DB_num_rows($result_CustSelect)==0){
117 prnMsg(_('Sorry') . ' ... ' . _('there are no customer branch records contain the selected text') . ' - ' . _('please alter your search criteria and try again'),'info');
120 } /*one of keywords or custcode was more than a zero length string */
121 } /*end of if search button for customers was hit*/
124 if (isset($_POST['Select']) AND $_POST['Select']!='') {
126 /*will only be true if page called from customer selection form
127 parse the $Select string into customer code and branch code */
129 $_SESSION['CreditItems']->Branch = substr($_POST['Select'],strpos($_POST['Select'],' - ')+3);
130 $_POST['Select'] = substr($_POST['Select'],0,strpos($_POST['Select'],' - '));
132 /*Now retrieve customer information - name, salestype, currency, terms etc */
134 $sql = "SELECT
135 debtorsmaster.name,
136 debtorsmaster.salestype,
137 debtorsmaster.currcode,
138 currencies.rate
139 FROM debtorsmaster,
140 currencies
141 WHERE debtorsmaster.currcode=currencies.currabrev
142 AND debtorsmaster.debtorno = '" . $_POST['Select'] . "'";
144 $ErrMsg = _('The customer record of the customer selected') . ': ' . $_POST['Select'] . ' ' . _('cannot be retrieved because');
145 $DbgMsg = _('The SQL used to retrieve the customer details and failed was');
146 $result =DB_query($sql,$db,$ErrMsg,$DbgMsg);
148 $myrow = DB_fetch_row($result);
150 $_SESSION['CreditItems']->DebtorNo = $_POST['Select'];
151 $_SESSION['RequireCustomerSelection'] = 0;
152 $_SESSION['CreditItems']->CustomerName = $myrow[0];
154 /* the sales type determines the price list to be used by default the customer of the user is
155 defaulted from the entry of the userid and password. */
157 $_SESSION['CreditItems']->DefaultSalesType = $myrow[1];
158 $_SESSION['CreditItems']->DefaultCurrency = $myrow[2];
159 $_SESSION['CurrencyRate'] = $myrow[3];
161 /* default the branch information from the customer branches table CustBranch -particularly where the stock
162 will be booked back into. */
164 $sql = "SELECT
165 custbranch.brname,
166 custbranch.braddress1,
167 custbranch.braddress2,
168 custbranch.braddress3,
169 custbranch.braddress4,
170 custbranch.braddress5,
171 custbranch.braddress6,
172 custbranch.phoneno,
173 custbranch.email,
174 custbranch.defaultlocation,
175 custbranch.taxgroupid,
176 locations.taxprovinceid
177 FROM custbranch
178 INNER JOIN locations ON locations.loccode=custbranch.defaultlocation
179 WHERE custbranch.branchcode='" . $_SESSION['CreditItems']->Branch . "'
180 AND custbranch.debtorno = '" . $_SESSION['CreditItems']->DebtorNo . "'";
182 $ErrMsg = _('The customer branch record of the customer selected') . ': ' . $_POST['Select'] . ' ' . _('cannot be retrieved because');
183 $DbgMsg = _('SQL used to retrieve the branch details was');
184 $result =DB_query($sql,$db,$ErrMsg,$DbgMsg);
186 $myrow = DB_fetch_array($result);
187 $_SESSION['CreditItems']->DeliverTo = $myrow['brname'];
188 $_SESSION['CreditItems']->BrAdd1 = $myrow['braddress1'];
189 $_SESSION['CreditItems']->BrAdd2 = $myrow['braddress2'];
190 $_SESSION['CreditItems']->BrAdd3 = $myrow['braddress3'];
191 $_SESSION['CreditItems']->BrAdd4 = $myrow['braddress4'];
192 $_SESSION['CreditItems']->BrAdd5 = $myrow['braddress5'];
193 $_SESSION['CreditItems']->BrAdd6 = $myrow['braddress6'];
194 $_SESSION['CreditItems']->PhoneNo = $myrow['phoneno'];
195 $_SESSION['CreditItems']->Email = $myrow['email'];
196 $_SESSION['CreditItems']->Location = $myrow['defaultlocation'];
197 $_SESSION['CreditItems']->TaxGroup = $myrow['taxgroupid'];
198 $_SESSION['CreditItems']->DispatchTaxProvince = $myrow['taxprovinceid'];
199 $_SESSION['CreditItems']->GetFreightTaxes();
204 /* if the change customer button hit or the customer has not already been selected */
205 if ($_SESSION['RequireCustomerSelection'] ==1
206 OR !isset($_SESSION['CreditItems']->DebtorNo)
207 OR $_SESSION['CreditItems']->DebtorNo=='' ) {
209 echo '<FONT SIZE=3><B> - ' . _('Customer Selection') . '</B></FONT><BR>';
210 echo '<FORM ACTION="' . $_SERVER['PHP_SELF'] . '?' . SID . '" METHOD=POST>';
211 echo '<B><BR>' . $msg . '</B>';
212 echo '<TABLE CELLPADDING=3 COLSPAN=4>';
213 echo '<TR>';
214 echo '<TD><FONT SIZE=1>' . _('Enter text in the customer name') . ':</FONT></TD>';
215 echo '<TD><INPUT TYPE="Text" NAME="Keywords" SIZE=20 MAXLENGTH=25></TD>';
216 echo '<TD><FONT SIZE=3><B>' . _('OR') . '</B></FONT></TD>';
217 echo '<TD><FONT SIZE=1>' . _('Enter text extract in the customer code') . ':</FONT></TD>';
218 echo '<TD><INPUT TYPE="Text" NAME="CustCode" SIZE=15 MAXLENGTH=18></TD>';
219 echo '</TR>';
220 echo '</TABLE>';
221 echo '<CENTER><INPUT TYPE=SUBMIT NAME="SearchCust" VALUE="' . _('Search Now') . '"></CENTER>';
223 if ($result_CustSelect) {
225 echo '<TABLE CELLPADDING=2 COLSPAN=7 BORDER=1>';
227 $TableHeader = '<TR>
228 <TD class="tableheader">' . _('Code') . '</TD>
229 <TD class="tableheader">' . _('Branch') . '</TD>
230 <TD class="tableheader">' . _('Contact') . '</TD>
231 <TD class="tableheader">' . _('Phone') . '</TD>
232 <TD class="tableheader">' . _('Fax') . '</TD>
233 </TR>';
235 echo $TableHeader;
237 $j = 1;
238 $k = 0; //row counter to determine background colour
240 while ($myrow=DB_fetch_array($result_CustSelect)) {
242 if ($k==1){
243 echo '<tr bgcolor="#CCCCCC">';
244 $k=0;
245 } else {
246 echo '<tr bgcolor="#EEEEEE">';
247 $k=1;
250 printf("<td><FONT SIZE=1><INPUT TYPE=SUBMIT NAME='Select' VALUE='%s - %s'</FONT></td>
251 <td><FONT SIZE=1>%s</FONT></td>
252 <td><FONT SIZE=1>%s</FONT></td>
253 <td><FONT SIZE=1>%s</FONT></td>
254 <td><FONT SIZE=1>%s</FONT></td>
255 </tr>",
256 $myrow['debtorno'],
257 $myrow['branchcode'],
258 $myrow['brname'],
259 $myrow['contactname'],
260 $myrow['phoneno'],
261 $myrow['faxno']);
263 $j++;
264 If ($j == 11){
265 $j=1;
266 echo $TableHeader;
268 //end of page full new headings if
270 //end of while loop
272 echo '</TABLE>';
275 //end if results to show
277 //end if RequireCustomerSelection
278 } else {
279 /* everything below here only do if a customer is selected
280 first add a header to show who we are making a credit note for */
282 echo '<FONT SIZE=4><B><U>' . $_SESSION['CreditItems']->CustomerName . ' - ' . $_SESSION['CreditItems']->DeliverTo . '</U></B></FONT></CENTER><BR>';
284 /* do the search for parts that might be being looked up to add to the credit note */
285 If (isset($_POST['Search'])){
287 If ($_POST['Keywords']!='' AND $_POST['StockCode']!='') {
288 $msg=_('Stock description keywords have been used in preference to the Stock code extract entered') . '.';
291 If ($_POST['Keywords']!="") {
292 //insert wildcard characters in spaces
294 $i=0;
295 $SearchString = '%';
296 while (strpos($_POST['Keywords'], ' ', $i)) {
297 $wrdlen=strpos($_POST['Keywords'],' ',$i) - $i;
298 $SearchString=$SearchString . substr($_POST['Keywords'],$i,$wrdlen) . '%';
299 $i=strpos($_POST['Keywords'],' ',$i) +1;
301 $SearchString = $SearchString. substr($_POST['Keywords'],$i).'%';
303 if ($_POST['StockCat']=='All'){
304 $SQL = "SELECT stockmaster.stockid,
305 stockmaster.description,
306 stockmaster.units
307 FROM stockmaster, stockcategory
308 WHERE stockmaster.categoryid=stockcategory.categoryid
309 AND (stockcategory.stocktype='F' OR stockcategory.stocktype='D')
310 AND stockmaster.description " . LIKE . "'$SearchString'
311 GROUP BY stockmaster.stockid,
312 stockmaster.description,
313 stockmaster.units
314 ORDER BY stockmaster.stockid";
315 } else {
316 $SQL = "SELECT stockmaster.stockid,
317 stockmaster.description,
318 stockmaster.units
319 FROM stockmaster,
320 stockcategory
321 WHERE stockmaster.categoryid=stockcategory.categoryid
322 AND (stockcategory.stocktype='F' OR stockcategory.stocktype='D')
323 AND stockmaster.description " . LIKE . "'$SearchString'
324 AND stockmaster.categoryid='" . $_POST['StockCat'] . "'
325 GROUP BY stockmaster.stockid,
326 stockmaster.description,
327 stockmaster.units
328 ORDER BY stockmaster.stockid";
331 } elseif ($_POST['StockCode']!=''){
332 $_POST['StockCode'] = '%' . $_POST['StockCode'] . '%';
333 if ($_POST['StockCat']=='All'){
334 $SQL = "SELECT stockmaster.stockid,
335 stockmaster.description,
336 stockmaster.units
337 FROM stockmaster,
338 stockcategory
339 WHERE stockmaster.categoryid=stockcategory.categoryid
340 AND (stockcategory.stocktype='F' OR stockcategory.stocktype='D')
341 AND stockmaster.stockid " . LIKE . " '" . $_POST['StockCode'] . "'
342 GROUP BY stockmaster.stockid,
343 stockmaster.description,
344 stockmaster.units
345 ORDER BY stockmaster.stockid";
346 } else {
347 $SQL = "SELECT stockmaster.stockid,
348 stockmaster.description,
349 stockmaster.units
350 FROM stockmaster,
351 stockcategory
352 WHERE stockmaster.categoryid=stockcategory.categoryid
353 AND (stockcategory.stocktype='F' OR stockcategory.stocktype='D')
354 AND stockmaster.stockid " . LIKE . " '" . $_POST['StockCode'] . "' AND stockmaster.categoryid='" . $_POST['StockCat'] . "'
355 GROUP BY stockmaster.stockid,
356 stockmaster.description,
357 stockmaster.units
358 ORDER BY stockmaster.stockid";
360 } else {
361 if ($_POST['StockCat']=='All'){
362 $SQL = "SELECT stockmaster.stockid,
363 stockmaster.description,
364 stockmaster.units
365 FROM stockmaster, stockcategory
366 WHERE stockmaster.categoryid=stockcategory.categoryid
367 AND (stockcategory.stocktype='F' OR stockcategory.stocktype='D')
368 GROUP BY stockmaster.stockid,
369 stockmaster.description,
370 stockmaster.units
371 ORDER BY stockmaster.stockid";
372 } else {
373 $SQL = "SELECT stockmaster.stockid,
374 stockmaster.description,
375 stockmaster.units
376 FROM stockmaster,
377 stockcategory
378 WHERE stockmaster.categoryid=stockcategory.categoryid
379 AND (stockcategory.stocktype='F' OR stockcategory.stocktype='D')
380 AND stockmaster.categoryid='" . $_POST['StockCat'] . "'
381 GROUP BY stockmaster.stockid,
382 stockmaster.description,
383 stockmaster.units
384 ORDER BY stockmaster.stockid";
388 $ErrMsg = _('There is a problem selecting the part records to display because');
389 $SearchResult = DB_query($SQL,$db,$ErrMsg);
391 if (DB_num_rows($SearchResult)==0){
392 prnMsg(_('There are no products available that match the criteria specified'),'info');
393 if ($debug==1){
394 prnMsg(_('The SQL statement used was') . ':<BR>' . $SQL,'info');
397 if (DB_num_rows($SearchResult)==1){
398 $myrow=DB_fetch_array($SearchResult);
399 $_POST['NewItem'] = $myrow['stockid'];
400 DB_data_seek($SearchResult,0);
403 } //end of if search for parts to add to the credit note
405 /*Always do the stuff below if not looking for a customerid
406 Set up the form for the credit note display and entry*/
408 echo '<FORM ACTION="' . $_SERVER['PHP_SELF'] . '?' . SID . '" METHOD=POST>';
411 /*Process Quick Entry */
413 If (isset($_POST['QuickEntry'])){
414 /* get the item details from the database and hold them in the cart object make the quantity 1 by default then add it to the cart */
415 $i=1;
416 do {
417 do {
418 $QuickEntryCode = 'part_' . $i;
419 $QuickEntryQty = 'qty_' . $i;
420 $i++;
421 } while (!is_numeric($_POST[$QuickEntryQty]) AND $_POST[$QuickEntryQty] <=0 AND strlen($_POST[$QuickEntryCode])!=0 AND $i<=$QuickEntires);
423 $_POST['NewItem'] = trim($_POST[$QuickEntryCode]);
424 $NewItemQty = trim($_POST[$QuickEntryQty]);
426 if (strlen($_POST['NewItem'])==0){
427 break; /* break out of the loop if nothing in the quick entry fields*/
430 $AlreadyOnThisCredit =0;
432 foreach ($_SESSION['CreditItems']->LineItems AS $OrderItem) {
434 /* do a loop round the items on the credit note to see that the item
435 is not already on this credit note */
437 if ($_SESSION['SO_AllowSameItemMultipleTimes']==0 && strcasecmp($OrderItem->StockID, $_POST['NewItem']) == 0) {
438 $AlreadyOnThisCredit = 1;
439 prnMsg($_POST['NewItem'] . ' ' . _('is already on this credit - the system will not allow the same item on the credit note more than once. However you can change the quantity credited of the existing line if necessary'),'warn');
441 } /* end of the foreach loop to look for preexisting items of the same code */
443 if ($AlreadyOnThisCredit!=1){
445 $sql = "SELECT
446 stockmaster.description,
447 stockmaster.stockid,
448 stockmaster.units,
449 stockmaster.volume,
450 stockmaster.kgs,
451 (materialcost+labourcost+overheadcost) AS standardcost,
452 stockmaster.mbflag,
453 stockmaster.decimalplaces,
454 stockmaster.controlled,
455 stockmaster.serialised,
456 stockmaster.discountcategory,
457 stockmaster.taxcatid
458 FROM stockmaster
459 WHERE stockmaster.stockid = '". $_POST['NewItem'] . "'";
461 $ErrMsg = _('There is a problem selecting the part because');
462 $result1 = DB_query($sql,$db,$ErrMsg);
464 if ($myrow = DB_fetch_array($result1)){
466 $LineNumber = $_SESSION['CreditItems']->LineCounter;
468 if ($_SESSION['CreditItems']->add_to_cart ($myrow['stockid'],
469 $NewItemQty,
470 $myrow['description'],
471 GetPrice ($_POST['NewItem'],
472 $_SESSION['CreditItems']->DebtorNo,
473 $_SESSION['CreditItems']->Branch, $db),
475 $myrow['units'],
476 $myrow['volume'],
477 $myrow['kgs'],
479 $myrow['mbflag'],
480 Date($_SESSION['DefaultDateFormat']),
482 $myrow['discountcategory'],
483 $myrow['controlled'],
484 $myrow['serialised'],
485 $myrow['decimalplaces'],
487 'No',
489 $myrow['taxcatid']) ==1){
491 $_SESSION['CreditItems']->LineItems[$LineNumber]->StandardCost = $myrow['standardcost'];
493 $_SESSION['CreditItems']->GetTaxes($LineNumber);
495 if ($myrow['controlled']==1){
496 /*Qty must be built up from serial item entries */
497 $_SESSION['CreditItems']->LineItems[$LineNumber]->Quantity = 0;
501 } else {
502 prnMsg( $_POST['NewItem'] . ' ' . _('does not exist in the database and cannot therefore be added to the credit note'),'warn');
504 } /* end of if not already on the credit note */
505 } while ($i<=$_SESSION['QuickEntries']); /*loop to the next quick entry record */
506 unset($_POST['NewItem']);
507 } /* end of if quick entry */
510 /* setup system defaults for looking up prices and the number of ordered items
511 if an item has been selected for adding to the basket add it to the session arrays */
513 if ($_SESSION['CreditItems']->ItemsOrdered > 0 OR isset($_POST['NewItem'])){
515 if (isset($_GET['Delete'])){
516 $_SESSION['CreditItems']->remove_from_cart($_GET['Delete']);
519 if (isset($_POST['ChargeFreightCost'])){
520 $_SESSION['CreditItems']->FreightCost = $_POST['ChargeFreightCost'];
523 If (isset($_POST['Location']) AND $_POST['Location'] != $_SESSION['CreditItems']->Location){
525 $_SESSION['CreditItems']->Location = $_POST['Location'];
527 $NewDispatchTaxProvResult = DB_query('SELECT taxprovinceid FROM locations WHERE loccode="' . $_POST['Location'] . '"',$db);
528 $myrow = DB_fetch_array($NewDispatchTaxProvResult);
530 $_SESSION['CreditItems']->DispatchTaxProvince = $myrow['taxprovinceid'];
532 foreach ($_SESSION['CreditItems']->LineItems as $LineItem) {
533 $_SESSION['CreditItems']->GetTaxes($LineItem->LineNumber);
537 foreach ($_SESSION['CreditItems']->LineItems as $LineItem) {
539 if (isset($_POST['Quantity_' . $LineItem->LineNumber])){
541 $Quantity = $_POST['Quantity_' . $LineItem->LineNumber];
542 $Narrative = $_POST['Narrative_' . $LineItem->LineNumber];
544 if (isset($_POST['Price_' . $LineItem->LineNumber])){
545 if ($_POST['Gross']==True){
546 $TaxTotalPercent =0;
547 foreach ($LineItem->Taxes AS $Tax) {
548 if ($Tax->TaxOnTax ==1){
549 $TaxTotalPercent += (1 + $TaxTotalPercent) * $Tax->TaxRate;
550 } else {
551 $TaxTotalPercent += $Tax->TaxRate;
554 $Price = round($_POST['Price_' . $LineItem->LineNumber]/($TaxTotalPercent + 1),2);
555 } else {
556 $Price = $_POST['Price_' . $LineItem->LineNumber];
559 $DiscountPercentage = $_POST['Discount_' . $LineItem->LineNumber];
561 foreach ($LineItem->Taxes as $TaxLine) {
562 if (isset($_POST[$LineItem->LineNumber . $TaxLine->TaxCalculationOrder . '_TaxRate'])){
563 $_SESSION['CreditItems']->LineItems[$LineItem->LineNumber]->Taxes[$TaxLine->TaxCalculationOrder]->TaxRate = $_POST[$LineItem->LineNumber . $TaxLine->TaxCalculationOrder . '_TaxRate']/100;
569 If ($Quantity<0 OR $Price <0 OR $DiscountPercentage >100 OR $DiscountPercentage <0){
570 prnMsg(_('The item could not be updated because you are attempting to set the quantity credited to less than 0 or the price less than 0 or the discount more than 100% or less than 0%'),'warn');
571 } elseif (isset($_POST['Quantity_' . $LineItem->LineNumber])) {
572 $_SESSION['CreditItems']->update_cart_item($LineItem->LineNumber, $Quantity, $Price, $DiscountPercentage/100, $Narrative);
576 foreach ($_SESSION['CreditItems']->FreightTaxes as $FreightTaxLine) {
577 if (isset($_POST['FreightTaxRate' . $FreightTaxLine->TaxCalculationOrder])){
578 $_SESSION['CreditItems']->FreightTaxes[$FreightTaxLine->TaxCalculationOrder]->TaxRate = $_POST['FreightTaxRate' . $FreightTaxLine->TaxCalculationOrder]/100;
582 If (isset($_POST['NewItem'])){
583 /* get the item details from the database and hold them in the cart object make the quantity 1 by default then add it to the cart */
585 $AlreadyOnThisCredit =0;
587 foreach ($_SESSION['CreditItems']->LineItems AS $OrderItem) {
589 /* do a loop round the items on the credit note to see that the item
590 is not already on this credit note */
592 if ($_SESSION['SO_AllowSameItemMultipleTimes']==0 && strcasecmp($OrderItem->StockID, $_POST['NewItem']) == 0) {
593 $AlreadyOnThisCredit = 1;
594 prnMsg(_('The item selected is already on this credit the system will not allow the same item on the credit note more than once. However you can change the quantity credited of the existing line if necessary.'),'warn');
596 } /* end of the foreach loop to look for preexisting items of the same code */
598 if ($AlreadyOnThisCredit!=1){
600 $sql = "SELECT stockmaster.description,
601 stockmaster.stockid,
602 stockmaster.units,
603 stockmaster.volume,
604 stockmaster.kgs,
605 stockmaster.mbflag,
606 stockmaster.discountcategory,
607 stockmaster.controlled,
608 stockmaster.decimalplaces,
609 stockmaster.serialised,
610 (materialcost+labourcost+overheadcost) AS standardcost,
611 stockmaster.taxcatid
612 FROM stockmaster
613 WHERE stockmaster.stockid = '". $_POST['NewItem'] . "'";
615 $ErrMsg = _('The item details could not be retrieved because');
616 $DbgMsg = _('The SQL used to retrieve the item details but failed was');
617 $result1 = DB_query($sql,$db,$ErrMsg,$DbgMsg);
618 $myrow = DB_fetch_array($result1);
620 $LineNumber = $_SESSION['CreditItems']->LineCounter;
621 /*validate the data returned before adding to the items to credit */
622 if ($_SESSION['CreditItems']->add_to_cart ($myrow['stockid'],
624 $myrow['description'],
625 GetPrice($_POST['NewItem'],
626 $_SESSION['CreditItems']->DebtorNo,
627 $_SESSION['CreditItems']->Branch,
628 $db),
630 $myrow['units'],
631 $myrow['volume'],
632 $myrow['kgs'],
634 $myrow['mbflag'],
635 Date($_SESSION['DefaultDateFormat']),
637 $myrow['discountcategory'],
638 $myrow['controlled'],
639 $myrow['serialised'],
640 $myrow['decimalplaces'],
642 'No',
644 $myrow['taxcatid']) ==1){
646 $_SESSION['CreditItems']->LineItems[$LineNumber]->StandardCost = $myrow['standardcost'];
648 $_SESSION['CreditItems']->GetTaxes($LineNumber);
650 if ($myrow['controlled']==1){
651 /*Qty must be built up from serial item entries */
652 $_SESSION['CreditItems']->LineItems[$LineNumber]->Quantity = 0;
655 } /* end of if not already on the credit note */
656 } /* end of if its a new item */
658 /* This is where the credit note as selected should be displayed reflecting any deletions or insertions*/
660 echo '<CENTER>
661 <TABLE CELLPADDING=2 COLSPAN=7>
662 <TR>
663 <TD class="tableheader">' . _('Item Code') . '</TD>
664 <TD class="tableheader">' . _('Item Description') . '</TD>
665 <TD class="tableheader">' . _('Quantity') . '</TD>
666 <TD class="tableheader">' . _('Unit') . '</TD>
667 <TD class="tableheader">' . _('Price') . '</TD>
668 <TD class="tableheader">' . _('Gross') . '</TD>
669 <TD class="tableheader">' . _('Discount') . '</TD>
670 <TD class="tableheader">' . _('Total') . '<BR>' . _('Excl Tax') . '</TD>
671 <TD class="tableheader">' . _('Tax Authority') . '</TD>
672 <TD class="tableheader">' . _('Tax') . '<BR>' . _('Rate') . '</TD>
673 <TD class="tableheader">' . _('Tax') . '<BR>' . _('Amount') . '</TD>
674 <TD class="tableheader">' . _('Total') . '<BR>' . _('Incl Tax') . '</TD>
675 </TR>';
677 $_SESSION['CreditItems']->total = 0;
678 $_SESSION['CreditItems']->totalVolume = 0;
679 $_SESSION['CreditItems']->totalWeight = 0;
681 $TaxTotal = 0;
682 $TaxTotals = array();
683 $TaxGLCodes = array();
685 $k =0; //row colour counter
686 foreach ($_SESSION['CreditItems']->LineItems as $LineItem) {
688 $LineTotal = $LineItem->Quantity * $LineItem->Price * (1 - $LineItem->DiscountPercent);
689 $DisplayLineTotal = number_format($LineTotal,2);
691 if ($k==1){
692 $RowStarter = '<tr bgcolor="#EEAABB">';
693 } elseif ($k==1){
694 $RowStarter = '<tr bgcolor="#CCCCCC">';
695 $k=0;
696 } else {
697 $RowStarter = '<tr bgcolor="#EEEEEE">';
698 $k=1;
702 echo $RowStarter . '<TD>' . $LineItem->StockID . '</TD>
703 <TD>' . $LineItem->ItemDescription . '</TD>';
705 if ($LineItem->Controlled==0){
706 echo '<TD><INPUT TYPE=TEXT NAME="Quantity_' . $LineItem->LineNumber . '" MAXLENGTH=6 SIZE=6 VALUE=' . $LineItem->Quantity . '></TD>';
707 } else {
708 echo '<TD ALIGN=RIGHT><A HREF="' . $rootpath . '/CreditItemsControlled.php?' . SID . '&LineNo=' . $LineItem->LineNumber . '">' . $LineItem->Quantity . '</A>
709 <INPUT TYPE=HIDDEN NAME="Quantity_' . $LineItem->LineNumber . '" VALUE=' . $LineItem->Quantity . '></TD>';
712 echo '<TD>' . $LineItem->Units . '</TD>
713 <TD><INPUT TYPE=TEXT NAME="Price_' . $LineItem->LineNumber . '" SIZE=10 MAXLENGTH=12 VALUE=' . $LineItem->Price . '></TD>
714 <TD><INPUT TYPE="CheckBox" NAME="Gross" VALUE=False></TD>
715 <TD><INPUT TYPE=TEXT NAME="Discount_' . $LineItem->LineNumber . '" SIZE=3 MAXLENGTH=3 VALUE=' . ($LineItem->DiscountPercent * 100) . '>%</TD>
716 <TD ALIGN=RIGHT>' . $DisplayLineTotal . '</TD>';
719 /*Need to list the taxes applicable to this line */
720 echo '<TD>';
721 $i=0;
722 foreach ($_SESSION['CreditItems']->LineItems[$LineItem->LineNumber]->Taxes AS $Tax) {
723 if ($i>0){
724 echo '<BR>';
726 echo $Tax->TaxAuthDescription;
727 $i++;
729 echo '</TD>';
730 echo '<TD ALIGN=RIGHT>';
732 $i=0; // initialise the number of taxes iterated through
733 $TaxLineTotal =0; //initialise tax total for the line
735 foreach ($LineItem->Taxes AS $Tax) {
736 if ($i>0){
737 echo '<BR>';
739 echo '<input type=text name="' . $LineItem->LineNumber . $Tax->TaxCalculationOrder . '_TaxRate" maxlength=4 SIZE=4 value="' . $Tax->TaxRate*100 . '">';
740 $i++;
741 if ($Tax->TaxOnTax ==1){
742 $TaxTotals[$Tax->TaxAuthID] += ($Tax->TaxRate * ($LineTotal + $TaxLineTotal));
743 $TaxLineTotal += ($Tax->TaxRate * ($LineTotal + $TaxLineTotal));
744 } else {
745 $TaxTotals[$Tax->TaxAuthID] += ($Tax->TaxRate * $LineTotal);
746 $TaxLineTotal += ($Tax->TaxRate * $LineTotal);
748 $TaxGLCodes[$Tax->TaxAuthID] = $Tax->TaxGLCode;
750 echo '</TD>';
752 $TaxTotal += $TaxLineTotal;
754 $DisplayTaxAmount = number_format($TaxLineTotal ,2);
755 $DisplayGrossLineTotal = number_format($LineTotal+ $TaxLineTotal,2);
757 echo '<TD ALIGN=RIGHT>' . $DisplayTaxAmount . '</TD>
758 <TD ALIGN=RIGHT>' . $DisplayGrossLineTotal . '</TD>
759 <TD><A HREF="' . $_SERVER['PHP_SELF'] . '?' . SID . '&Delete=' . $LineItem->LineNumber . '" onclick="return confirm(\'' . _('Are you sure you wish to delete this line item from the credit note?') . '\');">' . _('Delete') . '</A></TD>
762 <TD>' . $LineItem->LineNumber . '</TD>
763 </TR>';
765 echo $RowStarter;
766 echo '<TD COLSPAN=11><TEXTAREA NAME="Narrative_' . $LineItem->LineNumber . '" cols=100% rows=1>' . $LineItem->Narrative . '</TEXTAREA><BR><HR></TD></TR>';
769 $_SESSION['CreditItems']->total = $_SESSION['CreditItems']->total + $LineTotal;
770 $_SESSION['CreditItems']->totalVolume = $_SESSION['CreditItems']->totalVolume + $LineItem->Quantity * $LineItem->Volume; $_SESSION['CreditItems']->totalWeight = $_SESSION['CreditItems']->totalWeight + $LineItem->Quantity * $LineItem->Weight;
773 if (!isset($_POST['ChargeFreightCost']) AND !isset($_SESSION['CreditItems']->FreightCost)){
774 $_POST['ChargeFreightCost']=0;
776 echo '<TR>
777 <TD COLSPAN=5></TD>';
780 echo '<TD COLSPAN=2 ALIGN=RIGHT>'. _('Credit Freight').'</TD>
781 <TD><INPUT TYPE=TEXT SIZE=6 MAXLENGTH=6 NAME=ChargeFreightCost VALUE=' . $_SESSION['CreditItems']->FreightCost . '></TD>';
783 $FreightTaxTotal =0; //initialise tax total
785 echo '<TD>';
787 $i=0; // initialise the number of taxes iterated through
788 foreach ($_SESSION['CreditItems']->FreightTaxes as $FreightTaxLine) {
789 if ($i>0){
790 echo '<BR>';
792 echo $FreightTaxLine->TaxAuthDescription;
793 $i++;
796 echo '</TD><TD>';
798 $i=0;
799 foreach ($_SESSION['CreditItems']->FreightTaxes as $FreightTaxLine) {
800 if ($i>0){
801 echo '<BR>';
804 echo '<INPUT TYPE=TEXT NAME=FreightTaxRate' . $FreightTaxLine->TaxCalculationOrder . ' MAXLENGTH=4 SIZE=4 VALUE=' . $FreightTaxLine->TaxRate * 100 . '>';
806 if ($FreightTaxLine->TaxOnTax ==1){
807 $TaxTotals[$FreightTaxLine->TaxAuthID] += ($FreightTaxLine->TaxRate * ($_SESSION['CreditItems']->FreightCost + $FreightTaxTotal));
808 $FreightTaxTotal += ($FreightTaxLine->TaxRate * ($_SESSION['CreditItems']->FreightCost + $FreightTaxTotal));
809 } else {
810 $TaxTotals[$FreightTaxLine->TaxAuthID] += ($FreightTaxLine->TaxRate * $_SESSION['CreditItems']->FreightCost);
811 $FreightTaxTotal += ($FreightTaxLine->TaxRate * $_SESSION['CreditItems']->FreightCost);
813 $i++;
814 $TaxGLCodes[$FreightTaxLine->TaxAuthID] = $FreightTaxLine->TaxGLCode;
816 echo '</TD>';
818 echo '<TD ALIGN=RIGHT>' . number_format($FreightTaxTotal,2) . '</TD>
819 <TD ALIGN=RIGHT>' . number_format($FreightTaxTotal+ $_SESSION['CreditItems']->FreightCost,2) . '</TD>
820 </TR>';
822 $TaxTotal += $FreightTaxTotal;
823 $DisplayTotal = number_format($_SESSION['CreditItems']->total + $_SESSION['CreditItems']->FreightCost,2);
826 echo '<TR>
827 <TD COLSPAN=7 ALIGN=RIGHT>' . _('Credit Totals') . "</TD>
828 <TD ALIGN=RIGHT><HR><B>$DisplayTotal</B><HR></TD>
829 <TD COLSPAN=2></TD>
830 <TD ALIGN=RIGHT><HR><B>" . number_format($TaxTotal,2) . "<HR></TD>
831 <TD ALIGN=RIGHT><HR><B>" . number_format($TaxTotal+($_SESSION['CreditItems']->total + $_SESSION['CreditItems']->FreightCost),2) . "</B><HR></TD>
832 </TR></TABLE>";
835 /*Now show options for the credit note */
837 echo '<BR><CENTER><TABLE><TR><TD>' . _('Credit Note Type') . ' :</TD><TD><SELECT NAME=CreditType>';
838 if (!isset($_POST['CreditType']) OR $_POST['CreditType']=='Return'){
839 echo '<OPTION SELECTED VALUE="Return">' . _('Goods returned to store');
840 echo '<OPTION VALUE="WriteOff">' . _('Goods written off');
841 echo '<OPTION VALUE="ReverseOverCharge">' . _('Reverse an Overcharge');
842 } elseif ($_POST['CreditType']=='WriteOff') {
843 echo '<OPTION SELECTED VALUE="WriteOff">' . _('Goods written off');
844 echo '<OPTION VALUE="Return">' . _('Goods returned to store');
845 echo '<OPTION VALUE="ReverseOverCharge">' . _('Reverse an Overcharge');
846 } elseif($_POST['CreditType']=='ReverseOverCharge'){
847 echo '<OPTION SELECTED VALUE="ReverseOverCharge">' . _('Reverse Overcharge Only');
848 echo '<OPTION VALUE="Return">' . _('Goods Returned To Store');
849 echo '<OPTION VALUE="WriteOff">' . _('Good written off');
852 echo '</SELECT></TD></TR>';
855 if (!isset($_POST['CreditType']) OR $_POST['CreditType']=='Return'){
857 /*if the credit note is a return of goods then need to know which location to receive them into */
859 echo '<TR><TD>' . _('Goods Returned to Location') . ' :</TD><TD><SELECT NAME=Location>';
861 $SQL="SELECT loccode, locationname FROM locations";
862 $Result = DB_query($SQL,$db);
864 if (!isset($_POST['Location'])){
865 $_POST['Location'] = $_SESSION['CreditItems']->Location;
867 while ($myrow = DB_fetch_array($Result)) {
869 if ($_POST['Location']==$myrow['loccode']){
870 echo '<OPTION SELECTED VALUE="' . $myrow['loccode'] . '">' . $myrow['locationname'];
871 } else {
872 echo '<OPTION VALUE="' . $myrow['loccode'] . '">' . $myrow['locationname'];
875 echo '</SELECT></TD></TR>';
877 } elseif ($_POST['CreditType']=='WriteOff') { /* the goods are to be written off to somewhere */
879 echo '<TR><TD>' . _('Write off the cost of the goods to') . '</TD><TD><SELECT NAME=WriteOffGLCode>';
881 $SQL="SELECT accountcode,
882 accountname
883 FROM chartmaster,
884 accountgroups
885 WHERE chartmaster.group_=accountgroups.groupname
886 AND accountgroups.pandl=1 ORDER BY accountcode";
887 $Result = DB_query($SQL,$db);
889 while ($myrow = DB_fetch_array($Result)) {
891 if ($_POST['WriteOffGLCode']==$myrow['accountcode']){
892 echo '<OPTION SELECTED VALUE=' . $myrow['accountcode'] . '>' . $myrow['accountcode'] . ' - ' . $myrow['accountname'];
893 } else {
894 echo '<OPTION VALUE=' . $myrow['accountcode'] . '>' . $myrow['accountcode'] . ' - ' . $myrow['accountname'];
897 echo '</SELECT></TD></TR>';
899 echo '<TR><TD>' . _('Credit Note Text') . ' :</TD>
900 <TD><TEXTAREA NAME=CreditText COLS=31 ROWS=5>' . $_POST['CreditText'] . '</TEXTAREA></TD>
901 </TR>
902 </TABLE></CENTER>';
904 $OKToProcess = true;
905 /*Check for the worst */
906 if ($_POST['CreditType']=='WriteOff' AND !isset($_POST['WriteOffGLCode'])){
907 prnMsg (_('The GL code to write off the credit value to must be specified. Please select the appropriate GL code for the selection box'),'info');
908 $OKToProcess = false;
910 echo '<CENTER><INPUT TYPE=SUBMIT NAME="Update" VALUE="' . _('Update') . '">
911 <INPUT TYPE=SUBMIT NAME="CancelCredit" VALUE="' . _('Cancel') . '" onclick="return confirm(\'' . _('Are you sure you wish to cancel the whole of this credit note?') . '\');">';
912 if (!isset($_POST['ProcessCredit']) AND $OKToProcess == true){
913 echo '<INPUT TYPE=SUBMIT NAME="ProcessCredit" VALUE="' . _('Process Credit Note') . '">';
915 echo '</CENTER><HR>';
916 } # end of if lines
919 /* Now show the stock item selection search stuff below */
921 if (isset($_POST['PartSearch']) AND $_POST['PartSearch']!="" AND !isset($_POST['ProcessCredit'])){
923 echo '<input type="hidden" name="PartSearch" value="' . _('Yes Please') . '">';
925 $SQL="SELECT categoryid,
926 categorydescription
927 FROM stockcategory
928 WHERE stocktype='F'
929 ORDER BY categorydescription";
931 $result1 = DB_query($SQL,$db);
933 echo '<BR><TABLE>
934 <TR><TD><FONT SIZE=2>' . _('Select a stock category') . ':</FONT><SELECT NAME="StockCat">';
936 echo '<OPTION SELECTED VALUE="All">' . _('All');
937 while ($myrow1 = DB_fetch_array($result1)) {
938 if ($_POST['StockCat']==$myrow1['categoryid']){
939 echo '<OPTION SELECTED VALUE=' . $myrow1['categoryid'] . '>' . $myrow1['categorydescription'];
940 } else {
941 echo '<OPTION VALUE=' . $myrow1['categoryid'] . '>' . $myrow1['categorydescription'];
945 echo '</SELECT>';
947 echo '<TD><FONT SIZE=2>' . _('Enter text extracts in the description') . ':</FONT></TD>';
948 echo '<TD><INPUT TYPE="Text" NAME="Keywords" SIZE=20 MAXLENGTH=25 VALUE="' . $_POST['Keywords'] . '"></TD></TR>';
949 echo '<TR><TD></TD>';
950 echo '<TD><FONT SIZE 3><B>' ._('OR') . '</B></FONT><FONT SIZE=2>' . _('Enter extract of the Stock Code') . ':</FONT></TD>';
951 echo '<TD><INPUT TYPE="Text" NAME="StockCode" SIZE=15 MAXLENGTH=18 VALUE="' . $_POST['StockCode'] . '"></TD>';
952 echo '</TR>';
953 echo '</TABLE>';
955 echo '<CENTER><INPUT TYPE=SUBMIT NAME="Search" VALUE="' . _('Search Now') .'">';
956 echo '<INPUT TYPE=SUBMIT Name="ChangeCustomer" VALUE="' . _('Change Customer') . '">';
957 echo '<INPUT TYPE=SUBMIT Name="Quick" VALUE="' . _('Quick Entry') . '">';
958 echo '</CENTER>';
960 if (isset($SearchResult)) {
962 echo '<CENTER><TABLE CELLPADDING=2 COLSPAN=7 BORDER=1>';
963 $TableHeader = '<TR><TD class="tableheader">' . _('Code') . '</TD>
964 <TD class="tableheader">' . _('Description') . '</TD>
965 <TD class="tableheader">' . _('Units') .'</TD></TR>';
966 echo $TableHeader;
968 $j = 1;
969 $k=0; //row colour counter
971 while ($myrow=DB_fetch_array($SearchResult)) {
973 $ImageSource = $_SESSION['part_pics_dir'] . "/" . $myrow["stockid"] . ".jpg";
974 if (file_exists($ImageSource)){
975 $ImageSource = '<img src="'.$ImageSource.'">';
976 } else {
977 $ImageSource = '<i>'._('No Image').'</i>';
979 /* $_SESSION['part_pics_dir'] is a user defined variable in config.php */
981 if ($k==1){
982 echo '<tr bgcolor="#CCCCCC">';
983 $k=0;
984 } else {
985 echo '<tr bgcolor="#EEEEEE">';
986 $k++;
989 printf("<td><FONT SIZE=1><INPUT TYPE=SUBMIT NAME='NewItem' VALUE='%s'></FONT></td>
990 <td><FONT SIZE=1>%s</FONT></td>
991 <td><FONT SIZE=1>%s</FONT></td>
992 <td>%s</td></tr>",
993 $myrow['stockid'],
994 $myrow['description'],
995 $myrow['units'],
996 $ImageSource);
998 $j++;
999 If ($j == 20){
1000 $j=1;
1001 echo $TableHeader;
1003 #end of page full new headings if
1005 #end of while loop
1006 echo '</TABLE>';
1007 }#end if SearchResults to show
1008 } /*end if part searching required */ elseif(!isset($_POST['ProcessCredit'])) { /*quick entry form */
1010 /*FORM VARIABLES TO POST TO THE CREDIT NOTE 10 AT A TIME WITH PART CODE AND QUANTITY */
1011 echo '<FONT SIZE=4 COLOR=BLUE><B>' . _('Quick Entry') . '</B></FONT><BR><CENTER><TABLE BORDER=1>
1012 <TR>
1013 <TD class="tableheader">' . _('Part Code') . '</TD>
1014 <TD class="tableheader">' . _('Quantity') . '</TD>
1015 </TR>';
1017 for ($i=1;$i<=$_SESSION['QuickEntries'];$i++){
1019 echo '<tr bgcolor="#CCCCCC"><TD><INPUT TYPE="text" name="part_' . $i . '" size=21 maxlength=20></TD>
1020 <TD><INPUT TYPE="text" name="qty_' . $i . '" size=6 maxlength=6></TD></TR>';
1023 echo '</TABLE><INPUT TYPE="submit" name="QuickEntry" value="' . _('Process Entries') . '">
1024 <INPUT TYPE="submit" name="PartSearch" value="' . _('Search Parts') . '">';
1028 } //end of else not selecting a customer
1030 if (isset($_POST['ProcessCredit']) AND $OKToProcess==true){
1032 /* SQL to process the postings for sales credit notes...
1033 First Get the area where the credit note is to from the branches table */
1035 $SQL = "SELECT area
1036 FROM custbranch
1037 WHERE custbranch.debtorno ='". $_SESSION['CreditItems']->DebtorNo . "'
1038 AND custbranch.branchcode = '" . $_SESSION['CreditItems']->Branch . "'";
1039 $ErrMsg = '<BR>' . _('CRITICAL ERROR') . '! ' . _('NOTE DOWN THIS ERROR AND SEEK ASSISTANCE') . ': ' . _('The area cannot be determined for this customer');
1040 $DbgMsg = '<BR>' . _('The following SQL to insert the customer credit note was used');
1041 $Result = DB_query($SQL,$db,$ErrMsg,$DbgMsg);
1043 if ($myrow = DB_fetch_row($Result)){
1044 $Area = $myrow[0];
1047 DB_free_result($Result);
1049 if ($_SESSION['CompanyRecord']['gllink_stock']==1
1050 AND $_POST['CreditType']=='WriteOff'
1051 AND (!isset($_POST['WriteOffGLCode'])
1052 OR $_POST['WriteOffGLCode']=='')){
1054 prnMsg(_('For credit notes created to write off the stock a general ledger account is required to be selected. Please select an account to write the cost of the stock off to then click on Process again'),'error');
1055 include('includes/footer.inc');
1056 exit;
1060 /*Now Get the next credit note number - function in SQL_CommonFunctions*/
1062 $CreditNo = GetNextTransNo(11, $db);
1063 $SQLCreditDate = Date("Y-m-d");
1064 $PeriodNo = GetPeriod(Date($_SESSION['DefaultDateFormat']), $db);
1066 /*Start an SQL transaction */
1068 $ErrMsg = _('CRITICAL ERROR') . '! ' . _('NOTE DOWN THIS ERROR AND SEEK ASSISTANCE') . ': ' . _('The database does not support transactions') . ' - ' . _('A RDBMS that supports database transactions is required');
1069 $DbgMsg = '<BR>' . _('The following SQL to initiate a database transaction was used');
1071 $Result = DB_query("BEGIN",$db,$ErrMsg,$DbgMsg);
1074 /*Now insert the Credit Note into the DebtorTrans table allocations will have to be done seperately*/
1076 $SQL = "INSERT INTO debtortrans (
1077 transno,
1078 type,
1079 debtorno,
1080 branchcode,
1081 trandate,
1082 prd,
1083 tpe,
1084 ovamount,
1085 ovgst,
1086 ovfreight,
1087 rate,
1088 invtext)
1089 VALUES (". $CreditNo . ",
1091 '" . $_SESSION['CreditItems']->DebtorNo . "',
1092 '" . $_SESSION['CreditItems']->Branch . "',
1093 '" . $SQLCreditDate . "', " . $PeriodNo . ",
1094 '" . $_SESSION['CreditItems']->DefaultSalesType . "',
1095 " . -($_SESSION['CreditItems']->total) . ",
1096 " . -$TaxTotal . ",
1097 " . -$_SESSION['CreditItems']->FreightCost . ",
1098 " . $_SESSION['CurrencyRate'] . ",
1099 '" . $_POST['CreditText'] . "'
1102 $ErrMsg = _('CRITICAL ERROR') . '! ' . _('NOTE DOWN THIS ERROR AND SEEK ASSISTANCE') . ': ' . _('The customer credit note transaction could not be added to the database because');
1103 $DbgMsg = _('The following SQL to insert the customer credit note was used');
1104 $Result = DB_query($SQL,$db,$ErrMsg,$DbgMsg,true);
1107 $CreditTransID = DB_Last_Insert_ID($db,'debtortrans','id');
1109 /* Insert the tax totals for each tax authority where tax was charged on the invoice */
1110 foreach ($TaxTotals AS $TaxAuthID => $TaxAmount) {
1112 $SQL = 'INSERT INTO debtortranstaxes (debtortransid,
1113 taxauthid,
1114 taxamount)
1115 VALUES (' . $CreditTransID . ',
1116 ' . $TaxAuthID . ',
1117 ' . -($TaxAmount)/$_SESSION['CurrencyRate'] . ')';
1119 $ErrMsg =_('CRITICAL ERROR') . '! ' . _('NOTE DOWN THIS ERROR AND SEEK ASSISTANCE') . ': ' . _('The debtor transaction taxes records could not be inserted because');
1120 $DbgMsg = _('The following SQL to insert the debtor transaction taxes record was used');
1121 $Result = DB_query($SQL,$db,$ErrMsg,$DbgMsg,true);
1124 /* Insert stock movements for stock coming back in if the Credit is a return of goods */
1126 foreach ($_SESSION['CreditItems']->LineItems as $CreditLine) {
1128 If ($CreditLine->Quantity > 0){
1130 $LocalCurrencyPrice = ($CreditLine->Price / $_SESSION['CurrencyRate']);
1132 if ($CreditLine->MBflag=='M' oR $CreditLine->MBflag=='B'){
1133 /*Need to get the current location quantity will need it later for the stock movement */
1134 $SQL="SELECT locstock.quantity
1135 FROM locstock
1136 WHERE locstock.stockid='" . $CreditLine->StockID . "'
1137 AND loccode= '" . $_SESSION['CreditItems']->Location . "'";
1139 $Result = DB_query($SQL, $db);
1140 if (DB_num_rows($Result)==1){
1141 $LocQtyRow = DB_fetch_row($Result);
1142 $QtyOnHandPrior = $LocQtyRow[0];
1143 } else {
1144 /*There must actually be some error this should never happen */
1145 $QtyOnHandPrior = 0;
1147 } else {
1148 $QtyOnHandPrior =0; //because its a dummy/assembly/kitset part
1151 if ($_POST['CreditType']=='ReverseOverCharge') {
1152 /*Insert a stock movement coming back in to show the credit note - flag the stockmovement not to show on stock movement enquiries - its is not a real stock movement only for invoice line - also no mods to location stock records*/
1153 $SQL = "INSERT INTO stockmoves (stockid,
1154 type,
1155 transno,
1156 loccode,
1157 trandate,
1158 debtorno,
1159 branchcode,
1160 price,
1161 prd,
1162 reference,
1163 qty,
1164 discountpercent,
1165 standardcost,
1166 newqoh,
1167 hidemovt,
1168 narrative)
1169 VALUES
1170 ('" . $CreditLine->StockID . "',
1172 " . $CreditNo . ",
1173 '" . $_SESSION['CreditItems']->Location . "',
1174 '" . $SQLCreditDate . "',
1175 '" . $_SESSION['CreditItems']->DebtorNo . "',
1176 '" . $_SESSION['CreditItems']->Branch . "',
1177 " . $LocalCurrencyPrice . ",
1178 " . $PeriodNo . ",
1179 '" . $_POST['CreditText'] . "',
1180 " . $CreditLine->Quantity . ",
1181 " . $CreditLine->DiscountPercent . ",
1182 " . $CreditLine->StandardCost . ",
1183 " . $QtyOnHandPrior . ",
1185 '" . $CreditLine->Narrative . "')";
1187 $ErrMsg = _('CRITICAL ERROR') . '! ' . _('NOTE DOWN THIS ERROR AND SEEK ASSISTANCE') . ': ' . _('Stock movement records could not be inserted because');
1188 $DbgMsg = _('The following SQL to insert the stock movement records for the purpose of display on the credit note was used');
1189 $Result = DB_query($SQL, $db,$ErrMsg,$DbgMsg,true);
1191 } else { //its a return or a write off need to record goods coming in first
1193 if ($CreditLine->MBflag=="M" OR $CreditLine->MBflag=="B"){
1194 $SQL = "INSERT INTO stockmoves
1195 (stockid,
1196 type,
1197 transno,
1198 loccode,
1199 trandate,
1200 debtorno,
1201 branchcode,
1202 price,
1203 prd,
1204 qty,
1205 discountpercent,
1206 standardcost,
1207 reference,
1208 newqoh,
1209 narrative)
1210 VALUES (
1211 '" . $CreditLine->StockID . "',
1213 " . $CreditNo . ",
1214 '" . $_SESSION['CreditItems']->Location . "',
1215 '" . $SQLCreditDate . "',
1216 '" . $_SESSION['CreditItems']->DebtorNo . "',
1217 '" . $_SESSION['CreditItems']->Branch . "',
1218 " . $LocalCurrencyPrice . ",
1219 " . $PeriodNo . ",
1220 " . $CreditLine->Quantity . ",
1221 " . $CreditLine->DiscountPercent . ",
1222 " . $CreditLine->StandardCost . ",
1223 '" . $_POST['CreditText'] . "',
1224 " . ($QtyOnHandPrior + $CreditLine->Quantity) . ",
1225 '" . $CreditLine->Narrative . "'
1228 } else { /*its an assembly/kitset or dummy so don't attempt to figure out new qoh */
1229 $SQL = "INSERT INTO stockmoves
1230 (stockid,
1231 type,
1232 transno,
1233 loccode,
1234 trandate,
1235 debtorno,
1236 branchcode,
1237 price,
1238 prd,
1239 qty,
1240 discountpercent,
1241 standardcost,
1242 reference,
1243 narrative)
1244 VALUES (
1245 '" . $CreditLine->StockID . "',
1247 " . $CreditNo . ",
1248 '" . $_SESSION['CreditItems']->Location . "',
1249 '" . $SQLCreditDate . "',
1250 '" . $_SESSION['CreditItems']->DebtorNo . "',
1251 '" . $_SESSION['CreditItems']->Branch . "',
1252 " . $LocalCurrencyPrice . ",
1253 " . $PeriodNo . ",
1254 " . $CreditLine->Quantity . ",
1255 " . $CreditLine->DiscountPercent . ",
1256 " . $CreditLine->StandardCost . ",
1257 '" . $_POST['CreditText'] . "',
1258 '" . $CreditLine->Narrative . "'
1262 $ErrMsg = _('CRITICAL ERROR') . '! ' . _('NOTE DOWN THIS ERROR AND SEEK ASSISTANCE') . ': ' . _('Stock movement records could not be inserted because');
1263 $DbgMsg = _('The following SQL to insert the stock movement records was used');
1264 $Result = DB_query($SQL, $db, $ErrMsg, $DbgMsg, true);
1266 /*Get the stockmoveno from above - need to ref StockMoveTaxes and possibly SerialStockMoves */
1267 $StkMoveNo = DB_Last_Insert_ID($db,'stockmoves','stkmoveno');
1269 /*Insert the taxes that applied to this line */
1270 foreach ($CreditLine->Taxes as $Tax) {
1272 $SQL = 'INSERT INTO stockmovestaxes (stkmoveno,
1273 taxauthid,
1274 taxrate,
1275 taxcalculationorder,
1276 taxontax)
1277 VALUES (' . $StkMoveNo . ',
1278 ' . $Tax->TaxAuthID . ',
1279 ' . $Tax->TaxRate . ',
1280 ' . $Tax->TaxCalculationOrder . ',
1281 ' . $Tax->TaxOnTax . ')';
1283 $ErrMsg = _('CRITICAL ERROR') . '! ' . _('NOTE DOWN THIS ERROR AND SEEK ASSISTANCE') . ': ' . _('Taxes and rates applicable to this credit note line item could not be inserted because');
1284 $DbgMsg = _('The following SQL to insert the stock movement tax detail records was used');
1285 $Result = DB_query($SQL,$db,$ErrMsg,$DbgMsg,true);
1289 if (($CreditLine->MBflag=='M' OR $CreditLine->MBflag=='B') AND $CreditLine->Controlled==1){
1290 /*Need to do the serial stuff in here now */
1292 foreach($CreditLine->SerialItems as $Item){
1294 /*1st off check if StockSerialItems already exists */
1295 $SQL = "SELECT COUNT(*)
1296 FROM stockserialitems
1297 WHERE stockid='" . $CreditLine->StockID . "'
1298 AND loccode='" . $_SESSION['CreditItems']->Location . "'
1299 AND serialno='" . $Item->BundleRef . "'";
1300 $ErrMsg = _('CRITICAL ERROR') . '! ' . _('NOTE DOWN THIS ERROR AND SEEK ASSISTANCE') . ': ' . _('The existence of the serial stock item record could not be determined because');
1301 $DbgMsg = _('The following SQL to find out if the serial stock item record existed already was used');
1302 $Result = DB_query($SQL, $db, $ErrMsg, $DbgMsg, true);
1303 $myrow = DB_fetch_row($Result);
1305 if ($myrow[0]==0) {
1306 /*The StockSerialItem record didnt exist
1307 so insert a new record */
1308 $SQL = "INSERT INTO stockserialitems (
1309 stockid,
1310 loccode,
1311 serialno,
1312 quantity)
1313 VALUES (
1314 '" . $CreditLine->StockID . "',
1315 '" . $_SESSION['CreditItems']->Location . "',
1316 '" . $Item->BundleRef . "',
1317 " . $Item->BundleQty . "
1320 $ErrMsg = _('CRITICAL ERROR') . '! ' . _('NOTE DOWN THIS ERROR AND SEEK ASSISTANCE') . ': ' . _('The new serial stock item record could not be inserted because');
1321 $DbgMsg = _('The following SQL to insert the new serial stock item record was used') ;
1322 $Result = DB_query($SQL, $db, $ErrMsg, $DbgMsg, true);
1323 } else { /*Update the existing StockSerialItems record */
1324 $SQL = "UPDATE stockserialitems SET
1325 quantity= quantity + " . $Item->BundleQty . "
1326 WHERE stockid='" . $CreditLine->StockID . "'
1327 AND loccode='" . $_SESSION['CreditItems']->Location . "'
1328 AND serialno='" . $Item->BundleRef . "'";
1330 $ErrMsg = _('CRITICAL ERROR') . '! ' . _('NOTE DOWN THIS ERROR AND SEEK ASSISTANCE') . ': ' . _('The serial stock item record could not be updated because');
1331 $DbgMsg = _('The following SQL to update the serial stock item record was used');
1332 $Result = DB_query($SQL, $db, $ErrMsg, $DbgMsg, true);
1334 /* now insert the serial stock movement */
1336 $SQL = "INSERT INTO stockserialmoves (
1337 stockmoveno,
1338 stockid,
1339 serialno,
1340 moveqty)
1341 VALUES (
1342 " . $StkMoveNo . ",
1343 '" . $CreditLine->StockID . "',
1344 '" . $Item->BundleRef . "',
1345 " . $Item->BundleQty . "
1347 $ErrMsg = _('CRITICAL ERROR') . '! ' . _('NOTE DOWN THIS ERROR AND SEEK ASSISTANCE') . ': ' . _('The serial stock movement record could not be inserted because');
1348 $DbgMsg = _('The following SQL to insert the serial stock movement record was used');
1349 $Result = DB_query($SQL, $db, $ErrMsg, $DbgMsg, true);
1351 }/* foreach serial item in the serialitems array */
1353 } /*end if the credit line is a controlled item */
1355 }/*End of its a return or a write off */
1357 if ($_POST['CreditType']=='Return'){
1359 /* Update location stock records if not a dummy stock item */
1361 if ($CreditLine->MBflag=='B' OR $CreditLine->MBflag=='M') {
1363 $SQL = "UPDATE locstock
1364 SET locstock.quantity = locstock.quantity + " . $CreditLine->Quantity . "
1365 WHERE locstock.stockid = '" . $CreditLine->StockID . "'
1366 AND locstock.loccode = '" . $_SESSION['CreditItems']->Location . "'";
1368 $ErrMsg = _('CRITICAL ERROR') . '! ' . _('NOTE DOWN THIS ERROR AND SEEK ASSISTANCE') . ': ' . _('Location stock record could not be updated because');
1369 $DbgMsg = _('The following SQL to update the location stock record was used');
1370 $Result = DB_query($SQL, $db,$ErrMsg,$DbgMsg,true);
1372 } else if ($CreditLine->MBflag=='A'){ /* its an assembly */
1373 /*Need to get the BOM for this part and make stock moves
1374 for the componentsand of course update the Location stock
1375 balances for all the components*/
1377 $StandardCost =0; /*To start with then accumulate the cost of the comoponents
1378 for use in journals later on */
1380 $SQL = "SELECT
1381 bom.component,
1382 bom.quantity, stockmaster.materialcost+stockmaster.labourcost+stockmaster.overheadcost AS standard
1383 FROM bom, stockmaster
1384 WHERE bom.component=stockmaster.stockid
1385 AND bom.parent='" . $CreditLine->StockID . "'
1386 AND bom.effectiveto > '" . Date('Y-m-d') . "'
1387 AND bom.effectiveafter < '" . Date('Y-m-d') . "'";
1389 $ErrMsg = _('Could not retrieve assembly components from the database for') . ' ' . $CreditLine->StockID . ' ' . _('because');
1390 $DbgMsg = _('The SQL that failed was');
1391 $AssResult = DB_query($SQL,$db,$ErrMsg,$DbgMsg,true);
1393 while ($AssParts = DB_fetch_array($AssResult,$db)){
1395 $StandardCost += $AssParts['standard'];
1397 /*Need to get the current location quantity will need it later for the stock movement */
1398 $SQL="SELECT locstock.quantity
1399 FROM locstock
1400 WHERE locstock.stockid='" . $AssParts['component'] . "'
1401 AND locstock.loccode= '" . $_SESSION['CreditItems']->Location . "'";
1403 $Result = DB_query($SQL, $db);
1404 if (DB_num_rows($Result)==1){
1405 $LocQtyRow = DB_fetch_row($Result);
1406 $QtyOnHandPrior = $LocQtyRow[0];
1407 } else {
1408 /*There must actually be some error this should never happen */
1409 $QtyOnHandPrior = 0;
1412 /*Add stock movements for the assembly component items */
1413 $SQL = "INSERT INTO stockmoves
1414 (stockid,
1415 type,
1416 transno,
1417 loccode,
1418 trandate,
1419 debtorno,
1420 branchcode,
1421 prd,
1422 reference,
1423 qty,
1424 standardcost,
1425 show_on_inv_crds,
1426 newqoh)
1427 VALUES (
1428 '" . $AssParts['component'] . "',
1430 " . $CreditNo . ",
1431 '" . $_SESSION['CreditItems']->Location . "',
1432 '" . $SQLCreditDate . "',
1433 '" . $_SESSION['CreditItems']->DebtorNo . "',
1434 '" . $_SESSION['CreditItems']->Branch . "',
1435 " . $PeriodNo . ",
1436 '" . _('Assembly') .': ' . $CreditLine->StockID . "',
1437 " . $AssParts['quantity'] * $CreditLine->Quantity . ", " . $AssParts['standard'] . ",
1439 " . ($QtyOnHandPrior + ($AssParts['quantity'] * $CreditLine->Quantity)) . "
1442 $ErrMsg = _('CRITICAL ERROR') . '! ' . _('NOTE DOWN THIS ERROR AND SEEK ASSISTANCE') . ': ' . _('Stock movement records for the assembly components of') . ' ' . $CreditLine->StockID . ' ' . _('could not be inserted because');
1443 $DbgMsg = _('The following SQL to insert the assembly components stock movement records was used');
1444 $Result = DB_query($SQL,$db,$ErrMsg,$DbgMsg,true);
1446 /*Update the stock quantities for the assembly components */
1447 $SQL = "UPDATE locstock
1448 SET locstock.quantity = locstock.quantity + " . $AssParts['quantity'] * $CreditLine->Quantity . "
1449 WHERE locstock.stockid = '" . $AssParts['component'] . "'
1450 AND locstock.loccode = '" . $_SESSION['CreditItems']->Location . "'";
1452 $ErrMsg = _('CRITICAL ERROR') . '! ' . _('NOTE DOWN THIS ERROR AND SEEK ASSISTANCE') . ': ' . _('Location stock record could not be updated for an assembly component because');
1453 $DbgMsg = _('The following SQL to update the component location stock record was used');
1454 $Result = DB_query($SQL, $db,$ErrMsg, $DbgMsg,true);
1455 } /* end of assembly explosion and updates */
1458 /*Update the cart with the recalculated standard cost
1459 from the explosion of the assembly's components*/
1460 $_SESSION['CreditItems']->LineItems[$CreditLine->LineNumber]->StandardCost = $StandardCost;
1461 $CreditLine->StandardCost = $StandardCost;
1463 /*end of its a return of stock */
1464 } elseif ($_POST['CreditType']=='WriteOff'){ /*its a stock write off */
1466 if ($CreditLine->MBflag=="B" OR $CreditLine->MBflag=="M"){
1467 /* Insert stock movements for the
1468 item being written off - with unit cost */
1469 $SQL = "INSERT INTO stockmoves (
1470 stockid,
1471 type,
1472 transno,
1473 loccode,
1474 trandate,
1475 debtorno,
1476 branchcode,
1477 price,
1478 prd,
1479 qty,
1480 discountpercent,
1481 standardcost,
1482 reference,
1483 show_on_inv_crds,
1484 newqoh,
1485 narrative)
1486 VALUES (
1487 '" . $CreditLine->StockID . "',
1489 " . $CreditNo . ",
1490 '" . $_SESSION['CreditItems']->Location . "',
1491 '" . $SQLCreditDate . "',
1492 '" . $_SESSION['CreditItems']->DebtorNo . "',
1493 '" . $_SESSION['CreditItems']->Branch . "',
1494 " . $LocalCurrencyPrice . ",
1495 " . $PeriodNo . ",
1496 " . -$CreditLine->Quantity . ",
1497 " . $CreditLine->DiscountPercent . ",
1498 " . $CreditLine->StandardCost . ",
1499 '" . $_POST['CreditText'] . "',
1501 " . $QtyOnHandPrior . ",
1502 '" . $CreditLine->Narrative . "'
1505 } else { /* its an assembly, so dont figure out the new qoh */
1507 $SQL = "INSERT INTO stockmoves (
1508 stockid,
1509 type,
1510 transno,
1511 loccode,
1512 trandate,
1513 debtorno,
1514 branchcode,
1515 price,
1516 prd,
1517 qty,
1518 discountpercent,
1519 standardcost,
1520 reference,
1521 show_on_inv_crds)
1522 VALUES (
1523 '" . $CreditLine->StockID . "',
1525 " . $CreditNo . ",
1526 '" . $_SESSION['CreditItems']->Location . "',
1527 '" . $SQLCreditDate . "',
1528 '" . $_SESSION['CreditItems']->DebtorNo . "',
1529 '" . $_SESSION['CreditItems']->Branch . "',
1530 " . $LocalCurrencyPrice . ",
1531 " . $PeriodNo . ",
1532 " . -$CreditLine->Quantity . ",
1533 " . $CreditLine->DiscountPercent . ",
1534 " . $CreditLine->StandardCost . ",
1535 '" . $_POST['CreditText'] . "',
1536 0)";
1540 $ErrMsg = _('CRITICAL ERROR') . '! ' . _('NOTE DOWN THIS ERROR AND SEEK ASSISTANCE') . ': ' . _('Stock movement record to write the stock off could not be inserted because');
1541 $DbgMsg = _('The following SQL to insert the stock movement to write off the stock was used');
1542 $Result = DB_query($SQL, $db, $ErrMsg, $DbgMsg, true);
1544 if (($CreditLine->MBflag=="M" OR $CreditLine->MBflag=="B") AND $CreditLine->Controlled==1){
1545 /*Its a write off too still so need to process the serial items
1546 written off */
1548 $StkMoveNo = DB_Last_Insert_ID($db,'stockmoves','stkmoveno');
1550 foreach($CreditLine->SerialItems as $Item){
1551 /*no need to check StockSerialItems record exists
1552 it would have been added by the return stock movement above */
1553 $SQL = "UPDATE stockserialitems SET
1554 quantity= quantity - " . $Item->BundleQty . "
1555 WHERE stockid='" . $CreditLine->StockID . "'
1556 AND loccode='" . $_SESSION['CreditItems']->Location . "'
1557 AND serialno='" . $Item->BundleRef . "'";
1559 $ErrMsg = _('CRITICAL ERROR') . '! ' . _('NOTE DOWN THIS ERROR AND SEEK ASSISTANCE') . ': ' . _('The serial stock item record could not be updated for the write off because');
1560 $DbgMsg = _('The following SQL to update the serial stock item record was used');
1561 $Result = DB_query($SQL, $db, $ErrMsg, $DbgMsg, true);
1563 /* now insert the serial stock movement */
1565 $SQL = "INSERT INTO stockserialmoves (
1566 stockmoveno,
1567 stockid,
1568 serialno,
1569 moveqty)
1570 VALUES (
1571 " . $StkMoveNo . ",
1572 '" . $CreditLine->StockID . "',
1573 '" . $Item->BundleRef . "',
1574 " . -$Item->BundleQty . "
1576 $ErrMsg = _('CRITICAL ERROR') . '! ' . _('NOTE DOWN THIS ERROR AND SEEK ASSISTANCE') . ': ' . _('The serial stock movement record for the write off could not be inserted because');
1577 $DbgMsg = _('The following SQL to insert the serial stock movement write off record was used');
1578 $Result = DB_query($SQL, $db, $ErrMsg, $DbgMsg, true);
1580 }/* foreach serial item in the serialitems array */
1582 } /*end if the credit line is a controlled item */
1584 } /*end if its a stock write off */
1586 /*Insert Sales Analysis records use links to the customer master and branch tables to ensure that if
1587 the salesman or area has changed a new record is inserted for the customer and salesman of the new
1588 set up. Considered just getting the area and salesman from the branch table but these can alter and the
1589 sales analysis needs to reflect the sales made before and after the changes*/
1591 $SQL="SELECT
1592 COUNT(*),
1593 salesanalysis.stkcategory,
1594 salesanalysis.area,
1595 salesanalysis.salesperson
1596 FROM salesanalysis,
1597 custbranch,
1598 stockmaster
1599 WHERE salesanalysis.stkcategory=stockmaster.categoryid
1600 AND salesanalysis.stockid=stockmaster.stockid
1601 AND salesanalysis.cust=custbranch.debtorno
1602 AND salesanalysis.custbranch=custbranch.branchcode
1603 AND salesanalysis.area=custbranch.area
1604 AND salesanalysis.salesperson=custbranch.salesman
1605 AND salesanalysis.typeabbrev ='" . $_SESSION['CreditItems']->DefaultSalesType . "'
1606 AND salesanalysis.periodno=" . $PeriodNo . "
1607 AND salesanalysis.cust = '" . $_SESSION['CreditItems']->DebtorNo . "'
1608 AND salesanalysis.custbranch = '" . $_SESSION['CreditItems']->Branch . "'
1609 AND salesanalysis.stockid = '" . $CreditLine->StockID . "'
1610 AND salesanalysis.budgetoractual=1
1611 GROUP BY salesanalysis.stkcategory,
1612 salesanalysis.area,
1613 salesanalysis.salesperson";
1615 $ErrMsg = _('The count to check for existing Sales analysis records could not run because');
1616 $DbgMsg = _('SQL to count the no of sales analysis records');
1617 $Result = DB_query($SQL,$db, $ErrMsg, $DbgMsg, true);
1619 $myrow = DB_fetch_row($Result);
1621 if ($myrow[0]>0){ /*Update the existing record that already exists */
1623 if ($_POST['CreditType']=='ReverseOverCharge'){
1625 /*No updates to qty or cost data */
1627 $SQL = "UPDATE salesanalysis
1628 SET amt=amt-" . ($CreditLine->Price * $CreditLine->Quantity / $_SESSION['CurrencyRate']) . ",
1629 disc=disc-" . ($CreditLine->DiscountPercent * $CreditLine->Price * $CreditLine->Quantity / $_SESSION['CurrencyRate']) . "
1630 WHERE salesanalysis.area='" . $myrow[2] . "'
1631 AND salesanalysis.salesperson='" . $myrow[3] . "'
1632 AND salesanalysis.typeabbrev ='" . $_SESSION['CreditItems']->DefaultSalesType . "'
1633 AND salesanalysis.periodno = " . $PeriodNo . "
1634 AND salesanalysis.cust = '" . $_SESSION['CreditItems']->DebtorNo . "'
1635 AND salesanalysis.custbranch = '" . $_SESSION['CreditItems']->Branch . "'
1636 AND salesanalysis.stockid = '" . $CreditLine->StockID . "'
1637 AND salesanalysis.stkcategory ='" . $myrow[1] . "'
1638 AND salesanalysis.budgetoractual=1";
1640 } else {
1642 $SQL = "UPDATE salesanalysis
1643 SET Amt=Amt-" . ($CreditLine->Price * $CreditLine->Quantity / $_SESSION['CurrencyRate']) . ",
1644 Cost=Cost-" . ($CreditLine->StandardCost * $CreditLine->Quantity) . ",
1645 Qty=Qty-" . $CreditLine->Quantity . ",
1646 Disc=Disc-" . ($CreditLine->DiscountPercent * $CreditLine->Price * $CreditLine->Quantity / $_SESSION['CurrencyRate']) . "
1647 WHERE salesanalysis.area='" . $myrow[2] . "'
1648 AND salesanalysis.salesperson='" . $myrow[3] . "'
1649 AND salesanalysis.typeabbrev ='" . $_SESSION['CreditItems']->DefaultSalesType . "'
1650 AND salesanalysis.periodno = " . $PeriodNo . "
1651 AND salesanalysis.cust = '" . $_SESSION['CreditItems']->DebtorNo . "'
1652 AND salesanalysis.custbranch = '" . $_SESSION['CreditItems']->Branch . "'
1653 AND salesanalysis.stockid = '" . $CreditLine->StockID . "'
1654 AND salesanalysis.stkcategory ='" . $myrow[1] . "'
1655 AND salesanalysis.budgetoractual=1";
1658 } else { /* insert a new sales analysis record */
1660 if ($_POST['CreditType']=='ReverseOverCharge'){
1662 $SQL = "INSERT salesanalysis (
1663 typeabbrev,
1664 periodno,
1665 amt,
1666 cust,
1667 custbranch,
1668 qty,
1669 disc,
1670 stockid,
1671 area,
1672 budgetoractual,
1673 salesperson,
1674 stkcategory)
1675 SELECT
1676 '" . $_SESSION['CreditItems']->DefaultSalesType . "',
1677 " . $PeriodNo . ",
1678 " . -($CreditLine->Price * $CreditLine->Quantity / $_SESSION['CurrencyRate']) . ",
1679 '" . $_SESSION['CreditItems']->DebtorNo . "',
1680 '" . $_SESSION['CreditItems']->Branch . "',
1682 " . -($CreditLine->DiscountPercent * $CreditLine->Price * $CreditLine->Quantity / $_SESSION['CurrencyRate']) . ",
1683 '" . $CreditLine->StockID . "',
1684 custbranch.area,
1686 custbranch.salesman,
1687 stockmaster.categoryid
1688 FROM stockmaster, custbranch
1689 WHERE stockmaster.stockid = '" . $CreditLine->StockID . "'
1690 AND custbranch.debtorno = '" . $_SESSION['CreditItems']->DebtorNo . "'
1691 AND custbranch.branchcode='" . $_SESSION['CreditItems']->Branch . "'";
1693 } else {
1695 $SQL = "INSERT salesanalysis (
1696 typeabbrev,
1697 periodno,
1698 amt,
1699 cost,
1700 cust,
1701 custbranch,
1702 qty,
1703 disc,
1704 stockid,
1705 area,
1706 budgetoractual,
1707 salesperson,
1708 stkcategory)
1709 SELECT '" . $_SESSION['CreditItems']->DefaultSalesType . "',
1710 " . $PeriodNo . ",
1711 " . -($CreditLine->Price * $CreditLine->Quantity / $_SESSION['CurrencyRate']) . ",
1712 " . -($CreditLine->StandardCost * $CreditLine->Quantity) . ",
1713 '" . $_SESSION['CreditItems']->DebtorNo . "',
1714 '" . $_SESSION['CreditItems']->Branch . "',
1715 " . -$CreditLine->Quantity . ",
1716 " . -($CreditLine->DiscountPercent * $CreditLine->Price * $CreditLine->Quantity / $_SESSION['CurrencyRate']) . ",
1717 '" . $CreditLine->StockID . "',
1718 custbranch.area,
1720 custbranch.salesman,
1721 stockmaster.categoryid
1722 FROM stockmaster,
1723 custbranch
1724 WHERE stockmaster.stockid = '" . $CreditLine->StockID . "'
1725 AND custbranch.debtorno = '" . $_SESSION['CreditItems']->DebtorNo . "'
1726 AND custbranch.branchcode='" . $_SESSION['CreditItems']->Branch . "'";
1730 $ErrMsg = _('The sales analysis record for this credit note could not be added because');
1731 $DbgMsg = _('The following SQL to insert the sales analysis record was used');
1732 $Result = DB_query($SQL,$db,$ErrMsg, $DbgMsg, true);
1735 /* If GLLink_Stock then insert GLTrans to either debit stock or an expense
1736 depending on the valuve of $_POST['CreditType'] and then credit the cost of sales
1737 at standard cost*/
1739 if ($_SESSION['CompanyRecord']['gllink_stock']==1
1740 AND $CreditLine->StandardCost !=0
1741 AND $_POST['CreditType']!='ReverseOverCharge'){
1743 /*first reverse credit the cost of sales entry*/
1744 $COGSAccount = GetCOGSGLAccount($Area,
1745 $CreditLine->StockID,
1746 $_SESSION['CreditItems']->DefaultSalesType,
1747 $db);
1748 $SQL = "INSERT INTO gltrans (
1749 type,
1750 typeno,
1751 trandate,
1752 periodno,
1753 account,
1754 narrative,
1755 amount)
1756 VALUES (
1758 " . $CreditNo . ",
1759 '" . $SQLCreditDate . "',
1760 " . $PeriodNo . ",
1761 " . $COGSAccount . ",
1762 '" . $_SESSION['CreditItems']->DebtorNo . " - " . $CreditLine->StockID . " x " . $CreditLine->Quantity . " @ " . $CreditLine->StandardCost . "',
1763 " . ($CreditLine->StandardCost * -$CreditLine->Quantity) . ")";
1765 $ErrMsg = _('CRITICAL ERROR') . '! ' . _('NOTE DOWN THIS ERROR AND SEEK ASSISTANCE') . ': ' . _('The cost of the stock credited GL posting could not be inserted because');
1766 $DbgMsg = _('The following SQL to insert the GLTrans record was used');
1767 $Result = DB_query($SQL, $db, $ErrMsg, $DbgMsg, true);
1770 if ($_POST['CreditType']=='WriteOff'){
1772 /* The double entry required is to reverse the cost of sales entry as above
1773 then debit the expense account the stock is to written off to */
1775 $SQL = "INSERT INTO gltrans (
1776 type,
1777 typeno,
1778 trandate,
1779 periodno,
1780 account,
1781 narrative,
1782 amount)
1783 VALUES (
1785 " . $CreditNo . ",
1786 '" . $SQLCreditDate . "',
1787 " . $PeriodNo . ",
1788 " . $_POST['WriteOffGLCode'] . ",
1789 '" . $_SESSION['CreditItems']->DebtorNo . " - " . $CreditLine->StockID . " x " . $CreditLine->Quantity . " @ " . $CreditLine->StandardCost . "',
1790 " . ($CreditLine->StandardCost * $CreditLine->Quantity) . "
1793 $ErrMsg = _('CRITICAL ERROR') . '! ' . _('NOTE DOWN THIS ERROR AND SEEK ASSISTANCE') . ': ' . _('The cost of the stock credited GL posting could not be inserted because');
1794 $DbgMsg = _('The following SQL to insert the GLTrans record was used');
1795 $Result = DB_query($SQL, $db, $ErrMsg, $DbgMsg, true);
1796 } else {
1798 /*the goods are coming back into stock so debit the stock account*/
1799 $StockGLCode = GetStockGLCode($CreditLine->StockID, $db);
1800 $SQL = "INSERT INTO gltrans (
1801 type,
1802 typeno,
1803 trandate,
1804 periodno,
1805 account,
1806 narrative,
1807 amount)
1808 VALUES (
1810 " . $CreditNo . ",
1811 '" . $SQLCreditDate . "',
1812 " . $PeriodNo . ", " . $StockGLCode['stockact'] . ",
1813 '" . $_SESSION['CreditItems']->DebtorNo . " - " . $CreditLine->StockID . " x " . $CreditLine->Quantity . " @ " . $CreditLine->StandardCost . "',
1814 " . ($CreditLine->StandardCost * $CreditLine->Quantity) . "
1817 $ErrMsg = _('CRITICAL ERROR') . '! ' . _('NOTE DOWN THIS ERROR AND SEEK ASSISTANCE') . ': ' . _('The stock side (or write off) of the cost of sales GL posting could not be inserted because');
1818 $DbgMsg = _('The following SQL to insert the GLTrans record was used');
1819 $Result = DB_query($SQL, $db, $ErrMsg, $DbgMsg, true);
1822 } /* end of if GL and stock integrated and standard cost !=0 */
1824 if ($_SESSION['CompanyRecord']['gllink_debtors']==1 AND $CreditLine->Price !=0){
1826 //Post sales transaction to GL credit sales
1827 $SalesGLAccounts = GetSalesGLAccount($Area,
1828 $CreditLine->StockID,
1829 $_SESSION['CreditItems']->DefaultSalesType,
1830 $db);
1832 $SQL = "INSERT INTO gltrans (
1833 type,
1834 typeno,
1835 trandate,
1836 periodno,
1837 account,
1838 narrative,
1839 amount)
1840 VALUES (
1842 " . $CreditNo . ",
1843 '" . $SQLCreditDate . "',
1844 " . $PeriodNo . ",
1845 " . $SalesGLAccounts['salesglcode'] . ",
1846 '" . $_SESSION['CreditItems']->DebtorNo . " - " . $CreditLine->StockID . " x " . $CreditLine->Quantity . " @ " . $CreditLine->Price . "',
1847 " . ($CreditLine->Price * $CreditLine->Quantity)/$_SESSION['CurrencyRate'] . "
1850 $ErrMsg = _('CRITICAL ERROR') . '! ' . _('NOTE DOWN THIS ERROR AND SEEK ASSISTANCE') . ': ' . _('The credit note GL posting could not be inserted because');
1851 $DbgMsg = _('The following SQL to insert the GLTrans record was used');
1852 $Result = DB_query($SQL, $db, $ErrMsg, $DbgMsg, true);
1854 if ($CreditLine->DiscountPercent !=0){
1856 $SQL = "INSERT INTO gltrans (
1857 type,
1858 typeno,
1859 trandate,
1860 periodno,
1861 account,
1862 narrative,
1863 amount)
1864 VALUES (
1866 " . $CreditNo . ",
1867 '" . $SQLCreditDate . "',
1868 " . $PeriodNo . ",
1869 " . $SalesGLAccounts['discountglcode'] . ",
1870 '" . $_SESSION['CreditItems']->DebtorNo . " - " . $CreditLine->StockID . " @ " . ($CreditLine->DiscountPercent * 100) . "%',
1871 " . -($CreditLine->Price * $CreditLine->Quantity * $CreditLine->DiscountPercent)/$_SESSION['CurrencyRate'] . "
1875 $ErrMsg = _('CRITICAL ERROR') . '! ' . _('NOTE DOWN THIS ERROR AND SEEK ASSISTANCE') . ': ' . _('The credit note discount GL posting could not be inserted because');
1876 $DbgMsg = _('The following SQL to insert the GLTrans record was used');
1877 $Result = DB_query($SQL, $db, $ErrMsg, $DbgMsg, true);
1878 }/* end of if discount not equal to 0 */
1879 } /*end of if sales integrated with debtors */
1880 } /*Quantity credited is more than 0 */
1881 } /*end of CreditLine loop */
1884 if ($_SESSION['CompanyRecord']['gllink_debtors']==1){
1886 /*Post credit note transaction to GL credit debtors, debit freight re-charged and debit sales */
1887 if (($_SESSION['CreditItems']->total + $_SESSION['CreditItems']->FreightCost + $TaxTotal) !=0) {
1888 $SQL = "INSERT INTO gltrans (
1889 type,
1890 typeno,
1891 trandate,
1892 periodno,
1893 account,
1894 narrative,
1895 amount)
1896 VALUES (
1898 " . $CreditNo . ",
1899 '" . $SQLCreditDate . "',
1900 " . $PeriodNo . ",
1901 " . $_SESSION['CompanyRecord']['debtorsact'] . ",
1902 '" . $_SESSION['CreditItems']->DebtorNo . "',
1903 " . -($_SESSION['CreditItems']->total + $_SESSION['CreditItems']->FreightCost + $TaxTotal)/$_SESSION['CurrencyRate'] . ")";
1905 $ErrMsg = _('CRITICAL ERROR') . '! ' . _('NOTE DOWN THIS ERROR AND SEEK ASSISTANCE') . ': ' . _('The total debtor GL posting for the credit note could not be inserted because');
1906 $DbgMsg = _('The following SQL to insert the GLTrans record was used');
1907 $Result = DB_query($SQL, $db, $ErrMsg, $DbgMsg, true);
1909 if ($_SESSION['CreditItems']->FreightCost !=0) {
1910 $SQL = "INSERT INTO gltrans (
1911 type,
1912 typeno,
1913 trandate,
1914 periodno,
1915 account,
1916 narrative,
1917 amount)
1918 VALUES (
1920 " . $CreditNo . ",
1921 '" . $SQLCreditDate . "',
1922 " . $PeriodNo . ",
1923 " . $_SESSION['CompanyRecord']['freightact'] . ",
1924 '" . $_SESSION['CreditItems']->DebtorNo . "',
1925 " . $_SESSION['CreditItems']->FreightCost/$_SESSION['CurrencyRate'] . "
1928 $ErrMsg = _('CRITICAL ERROR') . '! ' . _('NOTE DOWN THIS ERROR AND SEEK ASSISTANCE') . ': ' . _('The freight GL posting for this credit note could not be inserted because');
1929 $DbgMsg = _('The following SQL to insert the GLTrans record was used');
1930 $Result = DB_query($SQL, $db, $ErrMsg, $DbgMsg, true);
1932 foreach ( $TaxTotals as $TaxAuthID => $TaxAmount){
1933 if ($TaxAmount !=0 ){
1934 $SQL = "INSERT INTO gltrans (
1935 type,
1936 typeno,
1937 trandate,
1938 periodno,
1939 account,
1940 narrative,
1941 amount
1943 VALUES (
1944 11,
1945 " . $CreditNo . ",
1946 '" . $SQLCreditDate . "',
1947 " . $PeriodNo . ",
1948 " . $TaxGLCodes[$TaxAuthID] . ",
1949 '" . $_SESSION['CreditItems']->DebtorNo . "',
1950 " . ($TaxAmount/$_SESSION['CurrencyRate']) . "
1953 $ErrMsg = _('CRITICAL ERROR') . '! ' . _('NOTE DOWN THIS ERROR AND SEEK ASSISTANCE') . ': ' . _('The tax GL posting could not be inserted because');
1954 $DbgMsg = _('The following SQL to insert the GLTrans record was used');
1955 $Result = DB_query($SQL,$db,$ErrMsg,$DbgMsg,true);
1958 } /*end of if Sales and GL integrated */
1960 $SQL='COMMIT';
1961 $Result = DB_query($SQL,$db);
1963 unset($_SESSION['CreditItems']->LineItems);
1964 unset($_SESSION['CreditItems']);
1966 echo _('Credit Note number') . ' ' . $CreditNo . ' ' . _('processed') . '<BR>';
1967 echo '<A target="_blank" HREF="' . $rootpath . '/PrintCustTrans.php?' . SID . '&FromTransNo=' . $CreditNo . '&InvOrCredit=Credit">' . _('Show this Credit Note on screen') . '</A><BR>';
1968 if ($_SESSION['InvoicePortraitFormat']==0){
1969 echo '<A HREF="' . $rootpath . '/PrintCustTrans.php?' . SID . '&FromTransNo=' . $CreditNo . '&InvOrCredit=Credit&PrintPDF=True">' . _('Print this Credit Note') . '</A>';
1970 } else {
1971 echo '<A HREF="' . $rootpath . '/PrintCustTransPortrait.php?' . SID . '&FromTransNo=' . $CreditNo . '&InvOrCredit=Credit&PrintPDF=True">' . _('Print this Credit Note') . '</A>';
1973 echo '<P><A HREF="' . $rootpath . '/SelectCreditItems.php">' . _('Enter Another Credit Note') . '</A>';
1975 } /*end of process credit note */
1977 echo '</FORM>';
1978 include('includes/footer.inc');