-
Notifications
You must be signed in to change notification settings - Fork 1
/
CounterSales.php
executable file
·1925 lines (1664 loc) · 84.7 KB
/
CounterSales.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/* $Id: CounterSales.php 4469 2011-01-15 02:28:37Z daintree $*/
include('includes/DefineCartClass.php');
/* Session started in session.inc for password checking and authorisation level check
config.php is in turn included in session.inc $PageSecurity now comes from session.inc (and gets read in by GetConfig.php*/
include('includes/session.inc');
$title = _('Counter Sales');
include('includes/header.inc');
include('includes/GetPrice.inc');
include('includes/SQL_CommonFunctions.inc');
include('includes/GetSalesTransGLCodes.inc');
include('includes/ItemSearch.php');
if (empty($_GET['identifier'])) {
$identifier=date('U');
$_POST['PartSearch']=True;
} else {
$identifier=$_GET['identifier'];
}
if (isset($_SESSION['Items'.$identifier])){
//update the Items object variable with the data posted from the form
$_SESSION['Items'.$identifier]->CustRef = _('Cash Sale');
$_SESSION['Items'.$identifier]->Comments = _('Cash sale on') . ' ' . date($_SESSION['DefaultDateFormat']);
}
if (isset($_POST['OrderItems'])){
foreach ($_POST as $key => $value) {
if (mb_strstr($key,'StockID')) {
$Index=substr($key,7);
$StockID=$value;
$Quantity=filter_number_input($_POST['Quantity'.$Index]);
$_POST['Units'.$StockID]=$_POST['Units'.$Index];
if (isset($_POST['Batch'.$Index])) {
$Batch=$_POST['Batch'.$Index];
$sql="SELECT quantity
FROM stockserialitems
WHERE stockid='".$StockID."'
AND serialno='".$Batch."'";
$BatchQuantityResult=DB_query($sql, $db);
$BatchQuantityRow=DB_fetch_array($BatchQuantityResult);
if (!isset($NewItemArray[$StockID])) {
if ($BatchQuantityRow['quantity']<$Quantity and $Quantity>0) {
prnMsg( _('Batch number').' '.$Batch.' '.
_('of item number').' '.$StockID.' '.
_('has insufficient items remaining in it to complete this sale') , 'info');
} else {
$NewItemArray[$StockID]['Quantity'] = $Quantity;
$NewItemArray[$StockID]['Batch']['Number'][] = $Batch;
$NewItemArray[$StockID]['Batch']['Quantity'][] = $Quantity;
}
} else {
if ($BatchQuantityRow['quantity']<$Quantity+$NewItemArray[$StockID]['Quantity'] and $NewItemArray[$StockID]['Quantity']>0) {
prnMsg( _('Batch number').' '.$Batch.' '.
_('of item number').' '.$StockID.' '.
_('has insufficient items remaining in it to complete this sale'), 'info');
} else {
$NewItemArray[$StockID]['Quantity'] += $Quantity;
$NewItemArray[$StockID]['Batch']['Number'][] = $Batch;
$NewItemArray[$StockID]['Batch']['Quantity'][] = $Quantity;
}
}
} else {
$NewItemArray[$StockID]['Quantity'] = $Quantity;
}
}
}
}
if (isset($_GET['NewItem'])){
$NewItem = trim($_GET['NewItem']);
}
if (isset($_GET['NewOrder'])){
/*New order entry - clear any existing order details from the Items object and initiate a newy*/
if (isset($_SESSION['Items'.$identifier])){
unset ($_SESSION['Items'.$identifier]->LineItems);
$_SESSION['Items'.$identifier]->ItemsOrdered=0;
unset ($_SESSION['Items'.$identifier]);
}
}
if (!isset($_SESSION['Items'.$identifier])){
/* It must be a new order being created $_SESSION['Items'.$identifier] would be set up from the order
modification code above if a modification to an existing order. Also $ExistingOrder would be
set to 1. The delivery check screen is where the details of the order are either updated or
inserted depending on the value of ExistingOrder */
$_SESSION['ExistingOrder'] = 0;
$_SESSION['Items'.$identifier] = new cart;
$_SESSION['PrintedPackingSlip'] = 0; /*Of course 'cos the order ain't even started !!*/
/*Get the default customer-branch combo from the user's default location record */
$sql = "SELECT cashsalecustomer,
cashsalebranch,
locationname,
taxprovinceid
FROM locations
WHERE loccode='" . $_SESSION['UserStockLocation'] ."'";
$result = DB_query($sql,$db);
if (DB_num_rows($result)==0) {
prnMsg(_('Your user account does not have a valid default inventory location set up. Please see the system administrator to modify your user account.'),'error');
include('includes/footer.inc');
exit;
} else {
$myrow = DB_fetch_array($result); //get the only row returned
if ($myrow['cashsalecustomer']=='' or $myrow['cashsalebranch']==''){
prnMsg(_('To use this script it is first necessary to define a cash sales customer for the location that is your default location.').' '.
_('This should be setup by modifying the appropriate Customer/Branch details.'),'error');
include('includes/footer.inc');
exit;
}
if (isset($_GET['DebtorNo'])) {
$CashSaleCustomer[0]=$_GET['DebtorNo'];
$CashSaleCustomer[1]=$_GET['BranchNo'];
} else {
$CashSaleCustomer[0]=$myrow['cashsalecustomer'];
$CashSaleCustomer[1]=$myrow['cashsalebranch'];
}
$_SESSION['Items'.$identifier]->Branch = $CashSaleCustomer[1];
$_SESSION['Items'.$identifier]->DebtorNo = $CashSaleCustomer[0];
$_SESSION['Items'.$identifier]->LocationName = $myrow['locationname'];
$_SESSION['Items'.$identifier]->Location = $_SESSION['UserStockLocation'];
$_SESSION['Items'.$identifier]->DispatchTaxProvince = $myrow['taxprovinceid'];
// Now check to ensure this account exists and set defaults */
$sql = "SELECT debtorsmaster.name,
holdreasons.dissallowinvoices,
debtorsmaster.salestype,
salestypes.sales_type,
debtorsmaster.currcode,
debtorsmaster.customerpoline,
paymentterms.terms
FROM debtorsmaster,
holdreasons,
salestypes,
paymentterms
WHERE debtorsmaster.salestype=salestypes.typeabbrev
AND debtorsmaster.holdreason=holdreasons.reasoncode
AND debtorsmaster.paymentterms=paymentterms.termsindicator
AND debtorsmaster.debtorno = '" . $_SESSION['Items'.$identifier]->DebtorNo . "'";
$ErrMsg = _('The details of the customer selected') . ': ' . $_SESSION['Items'.$identifier]->DebtorNo . ' ' . _('cannot be retrieved because');
$DbgMsg = _('The SQL used to retrieve the customer details and failed was') . ':';
// echo $sql;
$result =DB_query($sql,$db,$ErrMsg,$DbgMsg);
$myrow = DB_fetch_array($result);
// $SalesType=$myrow['salestype'];
if ($myrow['dissallowinvoices'] != 1){
if ($myrow['dissallowinvoices']==2){
prnMsg($myrow['name'] . ' ' . _('Although this account is defined as the cash sale account for the location. The account is currently flagged as an account that needs to be watched. Please contact the credit control personnel to discuss'),'warn');
}
$_SESSION['RequireCustomerSelection']=0;
$_SESSION['Items'.$identifier]->CustomerName = $myrow['name'];
// the sales type is the price list to be used for this sale
$_SESSION['Items'.$identifier]->DefaultSalesType = $myrow['salestype'];
$_SESSION['Items'.$identifier]->SalesTypeName = $myrow['sales_type'];
$_SESSION['Items'.$identifier]->DefaultCurrency = $myrow['currcode'];
$_SESSION['Items'.$identifier]->DefaultPOLine = $myrow['customerpoline'];
$_SESSION['Items'.$identifier]->PaymentTerms = $myrow['terms'];
/* now get the branch defaults from the customer branches table CustBranch. */
$sql = "SELECT custbranch.brname,
custbranch.braddress1,
custbranch.defaultshipvia,
custbranch.deliverblind,
custbranch.specialinstructions,
custbranch.estdeliverydays,
custbranch.salesman,
custbranch.taxgroupid,
custbranch.defaultshipvia
FROM custbranch
WHERE custbranch.branchcode='" . $_SESSION['Items'.$identifier]->Branch . "'
AND custbranch.debtorno = '" . $_SESSION['Items'.$identifier]->DebtorNo . "'";
$ErrMsg = _('The customer branch record of the customer selected') . ': ' . $_SESSION['Items'.$identifier]->Branch . ' ' . _('cannot be retrieved because');
$DbgMsg = _('SQL used to retrieve the branch details was') . ':';
$result = DB_query($sql,$db,$ErrMsg,$DbgMsg);
if (DB_num_rows($result)==0){
prnMsg(_('The branch details for branch code') . ': ' . $_SESSION['Items'.$identifier]->Branch . ' ' . _('against customer code') . ': ' . $_POST['Select'] . ' ' . _('could not be retrieved') . '. ' . _('Check the set up of the customer and branch'),'error');
if ($debug==1){
echo '<br />' . _('The SQL that failed to get the branch details was') . ':<br />' . $sql;
}
include('includes/footer.inc');
exit;
}
// add echo
$myrow = DB_fetch_array($result);
$_SESSION['Items'.$identifier]->DeliverTo = '';
$_SESSION['Items'.$identifier]->DelAdd1 = $myrow['braddress1'];
$_SESSION['Items'.$identifier]->ShipVia = $myrow['defaultshipvia'];
$_SESSION['Items'.$identifier]->DeliverBlind = $myrow['deliverblind'];
$_SESSION['Items'.$identifier]->SpecialInstructions = $myrow['specialinstructions'];
$_SESSION['Items'.$identifier]->DeliveryDays = $myrow['estdeliverydays'];
$_SESSION['Items'.$identifier]->TaxGroup = $myrow['taxgroupid'];
if ($_SESSION['Items'.$identifier]->SpecialInstructions) {
prnMsg($_SESSION['Items'.$identifier]->SpecialInstructions,'warn');
}
if ($_SESSION['CheckCreditLimits'] > 0) { /*Check credit limits is 1 for warn and 2 for prohibit sales */
$_SESSION['Items'.$identifier]->CreditAvailable = GetCreditAvailable($_SESSION['Items'.$identifier]->DebtorNo,$db);
if ($_SESSION['CheckCreditLimits']==1 AND $_SESSION['Items'.$identifier]->CreditAvailable <=0){
prnMsg(_('The') . ' ' . $myrow['brname'] . ' ' . _('account is currently at or over their credit limit'),'warn');
} elseif ($_SESSION['CheckCreditLimits']==2 AND $_SESSION['Items'.$identifier]->CreditAvailable <=0){
prnMsg(_('No more orders can be placed by') . ' ' . $myrow[0] . ' ' . _(' their account is currently at or over their credit limit'),'warn');
include('includes/footer.inc');
exit;
}
}
} else {
prnMsg($myrow['brname'] . ' ' . _('Although the account is defined as the cash sale account for the location the account is currently on hold. Please contact the credit control personnel to discuss'),'warn');
}
}
} // end if its a new sale to be set up ...
if (isset($_POST['CancelOrder'])) {
unset($_SESSION['Items'.$identifier]->LineItems);
$_SESSION['Items'.$identifier]->ItemsOrdered = 0;
unset($_SESSION['Items'.$identifier]);
$_SESSION['Items'.$identifier] = new cart;
echo '<br /><br />';
prnMsg(_('This sale has been cancelled as requested'),'success');
echo '<br /><br /><a href="' .htmlspecialchars($_SERVER['PHP_SELF'], ENT_QUOTES, 'UTF-8') . '">' . _('Start a new Counter Sale') . '</a>';
include('includes/footer.inc');
exit;
} else { /*Not cancelling the order */
echo '<p class="page_title_text"><img src="'.$rootpath.'/css/'.$theme.'/images/inventory.png" title="' . _('Counter Sales') . '" alt="" />' . ' ';
echo _('Counter Sale') . ' - ' . $_SESSION['Items'.$identifier]->LocationName . ' (' . _('all amounts in') . ' ' . $_SESSION['Items'.$identifier]->DefaultCurrency . ')<br />';
echo _('Customer') . ' - ' . $_SESSION['Items'.$identifier]->CustomerName;
echo '</p>';
}
/* Always do the stuff below */
echo '<form action="' . htmlspecialchars($_SERVER['PHP_SELF'], ENT_QUOTES, 'UTF-8') . '?identifier='.$identifier . '" name="SelectParts" method="post">';
echo '<input type="hidden" name="FormID" value="' . $_SESSION['FormID'] . '" />';
//Get The exchange rate used for GPPercent calculations on adding or amending items
if ($_SESSION['Items'.$identifier]->DefaultCurrency != $_SESSION['CompanyRecord']['currencydefault']){
$ExRateResult = DB_query("SELECT rate FROM currencies WHERE currabrev='" . $_SESSION['Items'.$identifier]->DefaultCurrency . "'",$db);
if (DB_num_rows($ExRateResult)>0){
$ExRateRow = DB_fetch_row($ExRateResult);
$ExRate = $ExRateRow[0];
} else {
$ExRate =1;
}
} else {
$ExRate = 1;
}
if ($ExRate==0) {
$ExRate=1;
}
/*Process Quick Entry */
/* If enter is pressed on the quick entry screen, the default button may be Recalculate */
if (isset($_POST['OrderItems'])
OR isset($_POST['QuickEntry'])
OR isset($_POST['Recalculate'])){
/* get the item details from the database and hold them in the cart object */
/*Discount can only be set later on -- after quick entry -- so default discount to 0 in the first place */
$Discount = 0;
$i=1;
while ($i<=$_SESSION['QuickEntries'] and isset($_POST['part_' . $i]) and $_POST['part_' . $i]!='') {
$QuickEntryCode = 'part_' . $i;
$QuickEntryQty = 'qty_' . $i;
$QuickEntryPOLine = 'poline_' . $i;
$QuickEntryItemDue = 'ItemDue_' . $i;
$i++;
if (isset($_POST[$QuickEntryCode])) {
$NewItem = strtoupper($_POST[$QuickEntryCode]);
}
if (isset($_POST[$QuickEntryQty])) {
$NewItemQty = $_POST[$QuickEntryQty];
}
if (isset($_POST[$QuickEntryItemDue])) {
$NewItemDue = $_POST[$QuickEntryItemDue];
} else {
$NewItemDue = DateAdd (Date($_SESSION['DefaultDateFormat']),'d', $_SESSION['Items'.$identifier]->DeliveryDays);
}
if (isset($_POST[$QuickEntryPOLine])) {
$NewPOLine = $_POST[$QuickEntryPOLine];
} else {
$NewPOLine = 0;
}
if (!isset($NewItem)){
unset($NewItem);
break; /* break out of the loop if nothing in the quick entry fields*/
}
if(!Is_Date($NewItemDue)) {
prnMsg(_('An invalid date entry was made for ') . ' ' . $NewItem . ' ' . _('The date entry') . ' ' . $NewItemDue . ' ' . _('must be in the format') . ' ' . $_SESSION['DefaultDateFormat'],'warn');
//Attempt to default the due date to something sensible?
$NewItemDue = DateAdd (Date($_SESSION['DefaultDateFormat']),'d', $_SESSION['Items'.$identifier]->DeliveryDays);
}
/*Now figure out if the item is a kit set - the field MBFlag='K'*/
$sql = "SELECT stockmaster.mbflag,
stockmaster.controlled
FROM stockmaster
WHERE stockmaster.stockid='". $NewItem ."'";
$ErrMsg = _('Could not determine if the part being ordered was a kitset or not because');
$DbgMsg = _('The sql that was used to determine if the part being ordered was a kitset or not was ');
$KitResult = DB_query($sql, $db,$ErrMsg,$DbgMsg);
if (DB_num_rows($KitResult)==0){
prnMsg( _('The item code') . ' ' . $NewItem . ' ' . _('could not be retrieved from the database and has not been added to the order'),'warn');
} elseif ($myrow=DB_fetch_array($KitResult)){
if ($myrow['mbflag']=='K'){ /*It is a kit set item */
$sql = "SELECT bom.component,
bom.quantity
FROM bom
WHERE bom.parent='" . $NewItem . "'
AND bom.effectiveto > '" . Date('Y-m-d') . "'
AND bom.effectiveafter < '" . Date('Y-m-d') . "'";
$ErrMsg = _('Could not retrieve kitset components from the database because') . ' ';
$KitResult = DB_query($sql,$db,$ErrMsg,$DbgMsg);
$ParentQty = $NewItemQty;
while ($KitParts = DB_fetch_array($KitResult,$db)) {
$NewItem = $KitParts['component'];
$NewItemQty = $KitParts['quantity'] * $ParentQty;
$NewPOLine = 0;
include('includes/SelectOrderItems_IntoCart.inc');
}
} else if ($myrow['mbflag']=='G'){
prnMsg(_('Phantom assemblies cannot be sold, these items exist only as bills of materials used in other manufactured items. The following item has not been added to the order:') . ' ' . $NewItem, 'warn');
} else { /*Its not a kit set item*/
include('includes/SelectOrderItems_IntoCart.inc');
}
}
}
unset($NewItem);
} /* end of if quick entry */
/*Now do non-quick entry delete/edits/adds */
if ((isset($_SESSION['Items'.$identifier])) OR isset($NewItem)) {
if (isset($_GET['Delete'])){
$_SESSION['Items'.$identifier]->remove_from_cart($_GET['Delete']); /*Don't do any DB updates*/
}
foreach ($_SESSION['Items'.$identifier]->LineItems as $OrderLine) {
if (isset($_POST['Quantity_' . $OrderLine->LineNumber])){
$Quantity = filter_number_input($_POST['Quantity_' . $OrderLine->LineNumber]);
if (abs($OrderLine->Price - $_POST['Price_' . $OrderLine->LineNumber])>0.01){
$Price = filter_number_input($_POST['Price_' . $OrderLine->LineNumber]);
$_POST['GPPercent_' . $OrderLine->LineNumber] = (($Price*(1-($_POST['Discount_' . $OrderLine->LineNumber]/100))) - $OrderLine->StandardCost*$ExRate)/($Price *(1-$_POST['Discount_' . $OrderLine->LineNumber])/100);
} else if (abs($OrderLine->GPPercent - $_POST['GPPercent_' . $OrderLine->LineNumber])>=0.001) {
//then do a recalculation of the price at this new GP Percentage
$Price = ($OrderLine->StandardCost*$ExRate)/(1 -(($_POST['GPPercent_' . $OrderLine->LineNumber] + $_POST['Discount_' . $OrderLine->LineNumber])/100));
} else {
$Price = filter_number_input($_POST['Price_' . $OrderLine->LineNumber]);
}
$DiscountPercentage = filter_number_input($_POST['Discount_' . $OrderLine->LineNumber]);
if ($_SESSION['AllowOrderLineItemNarrative'] == 1) {
$Narrative = $_POST['Narrative_' . $OrderLine->LineNumber];
} else {
$Narrative = '';
}
if (!isset($OrderLine->DiscountPercent)) {
$OrderLine->DiscountPercent = 0;
}
if ($Quantity<0 or $Price <0 or $DiscountPercentage >100 or $DiscountPercentage <0){
prnMsg(_('The item could not be updated because you are attempting to set the quantity ordered to less than 0 or the price less than 0 or the discount more than 100% or less than 0%'),'warn');
} else if ($OrderLine->Quantity !=$Quantity
or $OrderLine->Price != $Price
or abs($OrderLine->DiscountPercent -$DiscountPercentage/100) >0.001
or $OrderLine->Narrative != $Narrative
or $OrderLine->ItemDue != $_POST['ItemDue_' . $OrderLine->LineNumber]
or $OrderLine->POLine != $_POST['POLine_' . $OrderLine->LineNumber]) {
$_SESSION['Items'.$identifier]->update_cart_item($OrderLine->LineNumber,
$Quantity,
$Price,
$OrderLine->Units,
$OrderLine->ConversionFactor,
($DiscountPercentage/100),
0,
$Narrative,
'No', /*Update DB */
$_POST['ItemDue_' . $OrderLine->LineNumber],
$_POST['POLine_' . $OrderLine->LineNumber],
filter_number_input($_POST['GPPercent_' . $OrderLine->LineNumber])
);
}
} //page not called from itself - POST variables not set
}
}
if (isset($_POST['Recalculate'])) {
foreach ($_SESSION['Items'.$identifier]->LineItems as $OrderLine) {
$NewItem=$OrderLine->StockID;
$sql = "SELECT stockmaster.mbflag,
stockmaster.controlled
FROM stockmaster
WHERE stockmaster.stockid='". $OrderLine->StockID."'";
$ErrMsg = _('Could not determine if the part being ordered was a kitset or not because');
$DbgMsg = _('The sql that was used to determine if the part being ordered was a kitset or not was ');
$KitResult = DB_query($sql, $db,$ErrMsg,$DbgMsg);
if ($myrow=DB_fetch_array($KitResult)){
if ($myrow['mbflag']=='K'){ /*It is a kit set item */
$sql = "SELECT bom.component,
bom.quantity
FROM bom
WHERE bom.parent='" . $OrderLine->StockID. "'
AND bom.effectiveto > '" . Date('Y-m-d') . "'
AND bom.effectiveafter < '" . Date('Y-m-d') . "'";
$ErrMsg = _('Could not retrieve kitset components from the database because');
$KitResult = DB_query($sql,$db,$ErrMsg);
$ParentQty = $NewItemQty;
while ($KitParts = DB_fetch_array($KitResult,$db)){
$NewItem = $KitParts['component'];
$NewItemQty = $KitParts['quantity'] * $ParentQty;
$NewPOLine = 0;
$NewItemDue = date($_SESSION['DefaultDateFormat']);
$_SESSION['Items'.$identifier]->GetTaxes($OrderLine->LineNumber);
}
} else { /*Its not a kit set item*/
$NewItemDue = date($_SESSION['DefaultDateFormat']);
$NewPOLine = 0;
$_SESSION['Items'.$identifier]->GetTaxes($OrderLine->LineNumber);
}
}
unset($NewItem);
} /* end of if its a new item */
}
if (isset($NewItem)){
/* 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
Now figure out if the item is a kit set - the field MBFlag='K'
* controlled items and ghost/phantom items cannot be selected because the SQL to show items to select doesn't show 'em
* */
$sql = "SELECT stockmaster.mbflag,
stockmaster.taxcatid
FROM stockmaster
WHERE stockmaster.stockid='". $NewItem ."'";
$ErrMsg = _('Could not determine if the part being ordered was a kitset or not because');
$KitResult = DB_query($sql, $db,$ErrMsg);
$NewItemQty = 1; /*By Default */
$Discount = 0; /*By default - can change later or discount category override */
if ($myrow=DB_fetch_array($KitResult)){
if ($myrow['mbflag']=='K'){ /*It is a kit set item */
$sql = "SELECT bom.component,
bom.quantity
FROM bom
WHERE bom.parent='" . $NewItem . "'
AND bom.effectiveto > '" . Date('Y-m-d') . "'
AND bom.effectiveafter < '" . Date('Y-m-d') . "'";
$ErrMsg = _('Could not retrieve kitset components from the database because');
$KitResult = DB_query($sql,$db,$ErrMsg);
$ParentQty = $NewItemQty;
while ($KitParts = DB_fetch_array($KitResult,$db)){
$NewItem = $KitParts['component'];
$NewItemQty = $KitParts['quantity'] * $ParentQty;
$NewPOLine = 0;
$NewItemDue = date($_SESSION['DefaultDateFormat']);
include('includes/SelectOrderItems_IntoCart.inc');
$_SESSION['Items'.$identifier]->GetTaxes(($_SESSION['Items'.$identifier]->LineCounter - 1));
}
} else { /*Its not a kit set item*/
$NewItemDue = date($_SESSION['DefaultDateFormat']);
$NewPOLine = 0;
include('includes/SelectOrderItems_IntoCart.inc');
$_SESSION['Items'.$identifier]->GetTaxes(($_SESSION['Items'.$identifier]->LineCounter - 1));
}
} /* end of if its a new item */
} /*end of if its a new item */
if (isset($NewItemArray) and isset($_POST['OrderItems'])){
/* 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 */
/*Now figure out if the item is a kit set - the field MBFlag='K'*/
foreach($NewItemArray as $NewItem => $NewItemArray) {
$NewItemQty=$NewItemArray['Quantity'];
if($NewItemQty > 0) {
$sql = "SELECT stockmaster.mbflag
FROM stockmaster
WHERE stockmaster.stockid='". $NewItem ."'";
$ErrMsg = _('Could not determine if the part being ordered was a kitset or not because');
$KitResult = DB_query($sql, $db,$ErrMsg);
//$NewItemQty = 1; /*By Default */
$Discount = 0; /*By default - can change later or discount category override */
if ($myrow=DB_fetch_array($KitResult)){
if ($myrow['mbflag']=='K'){ /*It is a kit set item */
$sql = "SELECT bom.component,
bom.quantity
FROM bom
WHERE bom.parent='" . $NewItem . "'
AND bom.effectiveto > '" . Date('Y-m-d') . "'
AND bom.effectiveafter < '" . Date('Y-m-d') . "'";
$ErrMsg = _('Could not retrieve kitset components from the database because');
$KitResult = DB_query($sql,$db,$ErrMsg);
$ParentQty = $NewItemQty;
while ($KitParts = DB_fetch_array($KitResult,$db)){
$NewItem = $KitParts['component'];
$NewItemQty = $KitParts['quantity'] * $ParentQty;
$NewItemDue = date($_SESSION['DefaultDateFormat']);
$NewPOLine = 0;
include('includes/SelectOrderItems_IntoCart.inc');
$_SESSION['Items'.$identifier]->GetTaxes(($_SESSION['Items'.$identifier]->LineCounter - 1));
}
} else { /*Its not a kit set item*/
$NewItemDue = date($_SESSION['DefaultDateFormat']);
$NewPOLine = 0;
include('includes/SelectOrderItems_IntoCart.inc');
if ($_SESSION['Items'.$identifier]->LineCounter>0 and
$_SESSION['Items'.$identifier]->LineItems[$_SESSION['Items'.$identifier]->LineCounter - 1]->Controlled==1) {
$_SESSION['Items'.$identifier]->LineItems[$_SESSION['Items'.$identifier]->LineCounter - 1]->SerialItems=$NewItemArray['Batch'];
}
if ($_SESSION['Items'.$identifier]->LineCounter>0) {
$_SESSION['Items'.$identifier]->GetTaxes(($_SESSION['Items'.$identifier]->LineCounter - 1));
}
}
} /* end of if its a new item */
} /*end of if its a new item */
}
}
/* Run through each line of the order and work out the appropriate discount from the discount matrix */
$DiscCatsDone = array();
$counter =0;
foreach ($_SESSION['Items'.$identifier]->LineItems as $OrderLine) {
if ($OrderLine->DiscCat !="" AND ! in_array($OrderLine->DiscCat,$DiscCatsDone)){
$DiscCatsDone[]=$OrderLine->DiscCat;
$QuantityOfDiscCat = 0;
foreach ($_SESSION['Items'.$identifier]->LineItems as $OrderLine_2) {
/* add up total quantity of all lines of this DiscCat */
if ($OrderLine_2->DiscCat==$OrderLine->DiscCat){
$QuantityOfDiscCat += $OrderLine_2->Quantity;
}
}
$result = DB_query("SELECT MAX(discountrate) AS discount
FROM discountmatrix
WHERE salestype='" . $_SESSION['Items'.$identifier]->DefaultSalesType . "'
AND discountcategory ='" . $OrderLine->DiscCat . "'
AND quantitybreak <='" . $QuantityOfDiscCat . "'",$db);
$myrow = DB_fetch_row($result);
if ($myrow[0]==NULL){
$DiscountMatrixRate = 0;
} else {
$DiscountMatrixRate = $myrow[0];
}
if ($myrow[0]!=0){ /* need to update the lines affected */
foreach ($_SESSION['Items'.$identifier]->LineItems as $OrderLine_2) {
/* add up total quantity of all lines of this DiscCat */
if ($OrderLine_2->DiscCat==$OrderLine->DiscCat){
$_SESSION['Items'.$identifier]->LineItems[$OrderLine_2->LineNumber]->DiscountPercent = $DiscountMatrixRate;
$_SESSION['Items'.$identifier]->LineItems[$OrderLine_2->LineNumber]->GPPercent = (($_SESSION['Items'.$identifier]->LineItems[$OrderLine_2->LineNumber]->Price*(1-$DiscountMatrixRate)) - $_SESSION['Items'.$identifier]->LineItems[$OrderLine_2->LineNumber]->StandardCost*$ExRate)/($_SESSION['Items'.$identifier]->LineItems[$OrderLine_2->LineNumber]->Price *(1-$DiscountMatrixRate)/100);
}
}
}
}
} /* end of discount matrix lookup code */
if (count($_SESSION['Items'.$identifier]->LineItems)>0 and !isset($_POST['ProcessSale']) and !isset($_POST['PartSearch'])){ /*only show order lines if there are any */
/*
// *************************************************************************
// T H I S W H E R E T H E S A L E I S D I S P L A Y E D
// *************************************************************************
*/
echo '<br /><table width="90%" cellpadding="2" class="selection">
<tr>
<th>' . _('Item Code') . '</th>
<th>' . _('Item Description') . '</th>
<th>' . _('Quantity') . '</th>
<th>' . _('QOH') . '</th>
<th>' . _('Unit') . '</th>
<th>' . _('Price') . '</th>
<th>' . _('Discount') . '</th>
<th>' . _('GP %') . '</th>
<th>' . _('Net') . '</th>
<th>' . _('Tax') . '</th>
<th>' . _('Total') . '<br />' . _('Incl Tax') . '</th>
</tr>';
$_SESSION['Items'.$identifier]->total = 0;
$_SESSION['Items'.$identifier]->totalVolume = 0;
$_SESSION['Items'.$identifier]->totalWeight = 0;
$TaxTotals = array();
$TaxGLCodes = array();
$TaxTotal =0;
$k =0; //row colour counter
foreach ($_SESSION['Items'.$identifier]->LineItems as $OrderLine) {
$SubTotal = $OrderLine->Quantity * $OrderLine->Price * (1 - $OrderLine->DiscountPercent);
$QtyOrdered = $OrderLine->Quantity;
$QtyRemain = $QtyOrdered - $OrderLine->QtyInv;
if ($OrderLine->QOHatLoc < $OrderLine->Quantity AND ($OrderLine->MBflag=='B' OR $OrderLine->MBflag=='M')) {
/*There is a stock deficiency in the stock location selected */
$RowStarter = '<tr bgcolor="#EEAABB">';
} elseif ($k==1){
$RowStarter = '<tr class="OddTableRows">';
$k=0;
} else {
$RowStarter = '<tr class="EvenTableRows">';
$k=1;
}
echo $RowStarter;
echo '<input type="hidden" name="POLine_' . $OrderLine->LineNumber . '" value="" />';
echo '<input type="hidden" name="ItemDue_' . $OrderLine->LineNumber . '" value="'.$OrderLine->ItemDue.'" />';
echo '<td><a target="_blank" href="' . $rootpath . '/StockStatus.php?identifier='.$identifier . '&StockID=' . $OrderLine->StockID . '&DebtorNo=' . $_SESSION['Items'.$identifier]->DebtorNo . '">' . $OrderLine->StockID . '</a></td>
<td>' . $OrderLine->ItemDescription . '</td>';
echo '<td><input class="number" tabindex="2" type="text" name="Quantity_' . ($OrderLine->LineNumber) . '" size="6" maxlength="6" value="' . locale_number_format($OrderLine->Quantity,$OrderLine->DecimalPlaces) . '" /></td>';
echo '<td class="number">' . locale_number_format($OrderLine->QOHatLoc/$OrderLine->ConversionFactor,$OrderLine->DecimalPlaces) . '</td>
<td>' . $OrderLine->Units . '</td>';
if ($_SESSION['CanViewPrices']==1) {
echo '<td><input class="number" type="text" name="Price_' . $OrderLine->LineNumber . '" size="16" maxlength="16" value="' . locale_number_format($OrderLine->Price,4) . '" /></td>';
} else {
echo '<input type="hidden" name="Price_' . $OrderLine->LineNumber . '" value="' . locale_number_format($OrderLine->Price,4) . '" />';
echo '<td class="number">' . locale_number_format($OrderLine->Price,4) . '</td>';
}
if ($_SESSION['CanViewPrices']==1) {
echo '<td><input class="number" type="text" name="Discount_' . $OrderLine->LineNumber . '" size="5" maxlength="4" value="' . locale_number_format($OrderLine->DiscountPercent * 100,2) . '" /></td>
<td><input class="number" type="text" name="GPPercent_' . $OrderLine->LineNumber . '" size="8" maxlength="8" value="' . locale_number_format($OrderLine->GPPercent,4) . '" /></td>';
} else {
echo '<input type="hidden" name="Discount_' . $OrderLine->LineNumber . '" value="' . locale_number_format($OrderLine->DiscountPercent * 100,2) . '" />
<input type="hidden" name="GPPercent_' . $OrderLine->LineNumber . '" value="' . locale_number_format($OrderLine->GPPercent,4) . '" />';
echo '<td class="number">' . locale_number_format($OrderLine->DiscountPercent * 100,2) . '</td>
<td class="number">' . locale_number_format($OrderLine->GPPercent,4) . '%</td>';
}
echo '<td class="number">' . locale_money_format($SubTotal,$_SESSION['Items'.$identifier]->DefaultCurrency) . '</td>';
$LineDueDate = $OrderLine->ItemDue;
if (!Is_Date($OrderLine->ItemDue)){
$LineDueDate = DateAdd (Date($_SESSION['DefaultDateFormat']),'d', $_SESSION['Items'.$identifier]->DeliveryDays);
$_SESSION['Items'.$identifier]->LineItems[$OrderLine->LineNumber]->ItemDue= $LineDueDate;
}
$i=0; // initialise the number of taxes iterated through
$TaxLineTotal =0; //initialise tax total for the line
foreach ($OrderLine->Taxes AS $Tax) {
if (empty($TaxTotals[$Tax->TaxAuthID])) {
$TaxTotals[$Tax->TaxAuthID]=0;
}
if ($Tax->TaxOnTax ==1){
$TaxTotals[$Tax->TaxAuthID] += ($Tax->TaxRate * ($SubTotal + $TaxLineTotal));
$TaxLineTotal += ($Tax->TaxRate * ($SubTotal + $TaxLineTotal));
} else {
$TaxTotals[$Tax->TaxAuthID] += ($Tax->TaxRate * $SubTotal);
$TaxLineTotal += ($Tax->TaxRate * $SubTotal);
}
$TaxGLCodes[$Tax->TaxAuthID] = $Tax->TaxGLCode;
}
$TaxTotal += $TaxLineTotal;
$_SESSION['Items'.$identifier]->TaxTotals=$TaxTotals;
$_SESSION['Items'.$identifier]->TaxGLCodes=$TaxGLCodes;
echo '<td class="number">' . locale_money_format($TaxLineTotal ,$_SESSION['Items'.$identifier]->DefaultCurrency) . '</td>';
echo '<td class="number">' . locale_money_format($SubTotal + $TaxLineTotal ,$_SESSION['Items'.$identifier]->DefaultCurrency) . '</td>';
echo '<td><a href="' . htmlspecialchars($_SERVER['PHP_SELF'], ENT_QUOTES, 'UTF-8') . '?identifier='.$identifier . '&Delete=' . $OrderLine->LineNumber . '" onclick="return confirm(\'' . _('Are You Sure?') . '\');">' . _('Delete') . '</a></td></tr>';
if ($_SESSION['AllowOrderLineItemNarrative'] == 1){
echo $RowStarter;
echo '<td valign="top" colspan="11">' . _('Narrative') . ':<textarea name="Narrative_' . $OrderLine->LineNumber . '" cols="100" rows="1">' . stripslashes(AddCarriageReturns($OrderLine->Narrative)) . '</textarea><br /></td></tr>';
} else {
echo '<input type="hidden" name="Narrative" value="" />';
}
$_SESSION['Items'.$identifier]->total = $_SESSION['Items'.$identifier]->total + $SubTotal;
$_SESSION['Items'.$identifier]->totalVolume = $_SESSION['Items'.$identifier]->totalVolume + $OrderLine->Quantity * $OrderLine->Volume;
$_SESSION['Items'.$identifier]->totalWeight = $_SESSION['Items'.$identifier]->totalWeight + $OrderLine->Quantity * $OrderLine->Weight;
} /* end of loop around items */
echo '<tr class="EvenTableRows">
<td colspan="8" class="number"><b>' . _('Total') . '</b></td>
<td class="number">' . locale_money_format(($_SESSION['Items'.$identifier]->total),$_SESSION['Items'.$identifier]->DefaultCurrency) . '</td>
<td class="number">' . locale_money_format($TaxTotal,$_SESSION['Items'.$identifier]->DefaultCurrency) . '</td>
<td class="number">' . locale_money_format(($_SESSION['Items'.$identifier]->total+$TaxTotal),$_SESSION['Items'.$identifier]->DefaultCurrency) . '</td>
</tr>
</table>';
echo '<input type="hidden" name="TaxTotal" value="'.$TaxTotal.'" />';
echo '<br /><table><tr><td>';
//nested table
echo '<table class="selection">
<tr>
<td>'. _('Picked Up By') .':</td>
<td><input type="text" size="25" maxlength="25" name="DeliverTo" value="' . stripslashes($_SESSION['Items'.$identifier]->DeliverTo) . '" /></td>
</tr>';
echo '<tr>
<td>'. _('Contact Phone Number') .':</td>
<td><input type="text" size="25" maxlength="25" name="PhoneNo" value="' . stripslashes($_SESSION['Items'.$identifier]->PhoneNo) . '" /></td>
</tr>';
echo '<tr>
<td>' . _('Contact Email') . ':</td>
<td><input type="text" size="25" maxlength="30" name="Email" value="' . stripslashes($_SESSION['Items'.$identifier]->Email) . '" /></td>
</tr>';
echo '<tr>
<td>'. _('Customer Reference') .':</td>
<td><input type="text" size="25" maxlength="25" name="CustRef" value="' . stripcslashes($_SESSION['Items'.$identifier]->CustRef) . '" /></td>
</tr>';
echo '<tr>
<td>'. _('Comments') .':</td>
<td><textarea name="Comments" cols="23" rows="5">' . stripcslashes($_SESSION['Items'.$identifier]->Comments) .'</textarea></td>
</tr>';
echo '</table>'; //end the sub table in the first column of master table
echo '</td><th style="vertical-align: top;border-width: 0px;">'; //for the master table
echo '<table class="selection">'; // a new nested table in the second column of master table
//now the payment stuff in this column
$PaymentMethodsResult = DB_query("SELECT paymentid, paymentname FROM paymentmethods",$db);
$_POST['PaymentMethod']='Cash';
echo '<tr>
<td>' . _('Payment Type') . ':</td>
<td><select name="PaymentMethod">';
while ($PaymentMethodRow = DB_fetch_array($PaymentMethodsResult)){
if (isset($_POST['PaymentMethod']) and $_POST['PaymentMethod'] == $PaymentMethodRow['paymentname']){
echo '<option selected="True" value="' . $PaymentMethodRow['paymentid'] . '">' . $PaymentMethodRow['paymentname'] . '</option>';
} else {
echo '<option value="' . $PaymentMethodRow['paymentid'] . '">' . $PaymentMethodRow['paymentname'] . '</option>';
}
}
echo '</select></td></tr>';
$BankAccountsResult = DB_query("SELECT bankaccountname, accountcode FROM bankaccounts",$db);
echo '<tr>
<td>' . _('Banked to') . ':</td>
<td><select name="BankAccount">';
while ($BankAccountsRow = DB_fetch_array($BankAccountsResult)){
if (isset($_POST['BankAccount']) and $_POST['BankAccount'] == $BankAccountsRow['accountcode']){
echo '<option selected="True" value="' . $BankAccountsRow['accountcode'] . '">' . $BankAccountsRow['bankaccountname'] . '</option>';
} else {
echo '<option value="' . $BankAccountsRow['accountcode'] . '">' . $BankAccountsRow['bankaccountname'] . '</option>';
}
}
echo '</select></td></tr>';
$_POST['AmountPaid'] =($_SESSION['Items'.$identifier]->total+$TaxTotal);
echo '<tr><td>' . _('Amount Paid') . ':</td><td><input type="text" class="number" name="AmountPaid" maxlength="12" size="12" value="' . locale_money_format(round($_POST['AmountPaid'],2),$_SESSION['Items'.$identifier]->DefaultCurrency) . '" /></td></tr>';
echo '</table>'; //end the sub table in the second column of master table
echo '</th></tr></table>'; //end of column/row/master table
echo '<br /><div class="centre">
<button type="submit" name="Recalculate">' . _('Re-Calculate') . '</button>
<button type="submit" name="ProcessSale">' . _('Process The Sale') . '</button>
<button type="submit" name="PartSearch">' . _('Add more items') . '</button>
<button type="submit" name="CancelOrder" onclick="return confirm(\'' . _('Are you sure you wish to cancel this sale?') . '\');">' . _('Cancel Sale') . '</button>
</div>';
} # end of if lines
if (isset($_SESSION['Items'.$identifier]) and $_SESSION['Items'.$identifier]->ItemsOrdered==0) {
$_POST['PartSearch']='Yes';
}
/* **********************************
* Invoice Processing Here
* **********************************
* */
if (isset($_POST['ProcessSale'])){
$InputError = false; //always assume the best
//but check for the worst
if ($_SESSION['Items'.$identifier]->LineCounter == 0){
prnMsg(_('There are no lines on this sale. Please enter lines to invoice first'),'error');
$InputError = true;
}
if (abs(filter_currency_input($_POST['AmountPaid'])-($_SESSION['Items'.$identifier]->total+filter_currency_input($_POST['TaxTotal'])))>=0.01) {
prnMsg(_('The amount entered as payment does not equal the amount of the invoice. Please ensure the customer has paid the correct amount and re-enter'),'error');
$InputError = true;
}
if ($_SESSION['ProhibitNegativeStock']==1){ // checks for negative stock after processing invoice
//sadly this check does not combine quantities occuring twice on and order and each line is considered individually :-(
$NegativesFound = false;
foreach ($_SESSION['Items'.$identifier]->LineItems as $OrderLine) {
$SQL = "SELECT stockmaster.description,
locstock.quantity,
stockmaster.mbflag
FROM locstock
INNER JOIN stockmaster
ON stockmaster.stockid=locstock.stockid
WHERE stockmaster.stockid='" . $OrderLine->StockID . "'
AND locstock.loccode='" . $_SESSION['Items'.$identifier]->Location . "'";
$ErrMsg = _('Could not retrieve the quantity left at the location once this order is invoiced (for the purposes of checking that stock will not go negative because)');
$Result = DB_query($SQL,$db,$ErrMsg);
$CheckNegRow = DB_fetch_array($Result);
if ($CheckNegRow['mbflag']=='B' OR $CheckNegRow['mbflag']=='M'){
if ($CheckNegRow['quantity'] < ($OrderLine->Quantity*$OrderLine->ConversionFactor)){
prnMsg( _('Invoicing the selected order would result in negative stock. The system parameters are set to prohibit negative stocks from occurring. This invoice cannot be created until the stock on hand is corrected.'),'error',$OrderLine->StockID . ' ' . $CheckNegRow['description'] . ' - ' . _('Negative Stock Prohibited'));
$NegativesFound = true;
}
} else if ($CheckNegRow['mbflag']=='A') {
/*Now look for assembly components that would go negative */
$SQL = "SELECT bom.component,
stockmaster.description,
locstock.quantity-(" . $OrderLine->Quantity . "*bom.quantity) AS qtyleft
FROM bom
INNER JOIN locstock
ON bom.component=locstock.stockid
INNER JOIN stockmaster
ON stockmaster.stockid=bom.component
WHERE bom.parent='" . $OrderLine->StockID . "'
AND locstock.loccode='" . $_SESSION['Items'.$identifier]->Location . "'
AND effectiveafter <'" . Date('Y-m-d') . "'
AND effectiveto >='" . Date('Y-m-d') . "'";
$ErrMsg = _('Could not retrieve the component quantity left at the location once the assembly item on this order is invoiced (for the purposes of checking that stock will not go negative because)');
$Result = DB_query($SQL,$db,$ErrMsg);
while ($NegRow = DB_fetch_array($Result)){
if ($NegRow['qtyleft']<0){
prnMsg(_('Invoicing the selected order would result in negative stock for a component of an assembly item on the order. The system parameters are set to prohibit negative stocks from occurring. This invoice cannot be created until the stock on hand is corrected.'),'error',$NegRow['component'] . ' ' . $NegRow['description'] . ' - ' . _('Negative Stock Prohibited'));
$NegativesFound = true;
} // end if negative would result
} //loop around the components of an assembly item
}//end if its an assembly item - check component stock
} //end of loop around items on the order for negative check
if ($NegativesFound){
prnMsg(_('The parameter to prohibit negative stock is set and invoicing this sale would result in negative stock. No futher processing can be performed. Alter the sale first changing quantities or deleting lines which do not have sufficient stock.'),'error');
$InputError = true;
}
}//end of testing for negative stocks
if ($InputError == false) { //all good so let's get on with the processing
/* Now Get the area where the sale is to from the branches table */
$SQL = "SELECT area,
defaultshipvia
FROM custbranch
WHERE custbranch.debtorno ='". $_SESSION['Items'.$identifier]->DebtorNo . "'
AND custbranch.branchcode = '" . $_SESSION['Items'.$identifier]->Branch . "'";
$ErrMsg = _('We were unable to load the area where the sale is to from the custbranch table');
$Result = DB_query($SQL,$db, $ErrMsg);
$myrow = DB_fetch_row($Result);
$Area = $myrow[0];
$DefaultShipVia = $myrow[1];
DB_free_result($Result);
/*company record read in on login with info on GL Links and debtors GL account*/
if ($_SESSION['CompanyRecord']==0){
/*The company data and preferences could not be retrieved for some reason */
prnMsg( _('The company information and preferences could not be retrieved. See your system administrator'), 'error');
include('includes/footer.inc');
exit;
}
// *************************************************************************
// S T A R T O F I N V O I C E S Q L P R O C E S S I N G
// *************************************************************************
/*First add the order to the database - it only exists in the session currently! */
$OrderNo = GetNextTransNo(30, $db);
$HeaderSQL = "INSERT INTO salesorders ( orderno,
debtorno,
branchcode,
customerref,
comments,
orddate,
ordertype,
shipvia,
deliverto,
deladd1,
contactphone,
contactemail,
fromstkloc,
deliverydate,
confirmeddate,
deliverblind)
VALUES (
'" . $OrderNo . "',
'" . $_SESSION['Items'.$identifier]->DebtorNo . "',
'" . $_SESSION['Items'.$identifier]->Branch . "',
'" . DB_escape_string($_SESSION['Items'.$identifier]->CustRef) ."',
'" . DB_escape_string($_SESSION['Items'.$identifier]->Comments) ."',
'" . Date('Y-m-d H:i') . "',
'" . $_SESSION['Items'.$identifier]->DefaultSalesType . "',
'" . $_SESSION['Items'.$identifier]->ShipVia . "',
'" . DB_escape_string($_SESSION['Items'.$identifier]->DeliverTo) . "',
'" . _('Counter Sale') . "',
'" . $_SESSION['Items'.$identifier]->PhoneNo . "',
'" . $_SESSION['Items'.$identifier]->Email . "',
'" . $_SESSION['Items'.$identifier]->Location ."',
'" . Date('Y-m-d') . "',
'" . Date('Y-m-d') . "',
0)";
$ErrMsg = _('The order cannot be added because');
$InsertQryResult = DB_query($HeaderSQL,$db,$ErrMsg);
$StartOf_LineItemsSQL = "INSERT INTO salesorderdetails (orderlineno,
orderno,
stkcode,
unitprice,
quantity,
discountpercent,
narrative,
itemdue,
actualdispatchdate,
qtyinvoiced,
completed)
VALUES (";
$DbgMsg = _('Trouble inserting a line of a sales order. The SQL that failed was');
foreach ($_SESSION['Items'.$identifier]->LineItems as $StockItem) {
$LineItemsSQL = $StartOf_LineItemsSQL . "
'" . $StockItem->LineNumber . "',
'" . $OrderNo . "',
'" . $StockItem->StockID . "',
'" . $StockItem->Price . "',
'" . $StockItem->Quantity . "',
'" . floatval($StockItem->DiscountPercent) . "',
'" . DB_escape_string($StockItem->Narrative) . "',
'" . Date('Y-m-d') . "',
'" . Date('Y-m-d') . "',
'" . $StockItem->Quantity . "',
1)";
$ErrMsg = _('Unable to add the sales order line');
$Ins_LineItemResult = DB_query($LineItemsSQL,$db,$ErrMsg,$DbgMsg,true);
/*Now check to see if the item is manufactured