forked from timschofield/webERP
-
Notifications
You must be signed in to change notification settings - Fork 89
/
ConfirmDispatch_Invoice.php
1824 lines (1584 loc) · 80.6 KB
/
ConfirmDispatch_Invoice.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
/* ConfirmDispatch_Invoice.php */
/* Creates sales invoices from entered sales orders based on the quantities dispatched that can be modified */
/* Session started in session.php for password checking and authorisation level check */
include ('includes/DefineCartClass.php');
include ('includes/DefineSerialItems.php');
include ('includes/session.php');
$Title = _('Confirm Dispatches and Invoice An Order');
$ViewTopic = 'ARTransactions';
$BookMark = 'ConfirmInvoice';
include ('includes/header.php');
include ('includes/CurrenciesArray.php');
include ('includes/SQL_CommonFunctions.inc');
include ('includes/FreightCalculation.inc');
include ('includes/GetSalesTransGLCodes.inc');
if (empty($_GET['identifier'])) {
/*unique session identifier to ensure that there is no conflict with other order entry sessions on the same machine */
$identifier=date('U');
} else {
$identifier=$_GET['identifier'];
}
if (!isset($_GET['OrderNumber']) AND !isset($_SESSION['ProcessingOrder'])) {
/* This page can only be called with an order number for invoicing*/
echo '<div class="centre">
<a href="' . $RootPath . '/SelectSalesOrder.php">' . _('Select a sales order to invoice'). '</a>
</div>
<br />';
prnMsg( _('This page can only be opened if an order has been selected Please select an order first from the delivery details screen click on Confirm for invoicing'), 'error' );
include ('includes/footer.php');
exit;
} elseif (isset($_GET['OrderNumber']) and $_GET['OrderNumber']>0) {
unset($_SESSION['Items'.$identifier]->LineItems);
unset($_SESSION['Items'.$identifier]);
$_SESSION['ProcessingOrder']=(int)$_GET['OrderNumber'];
$_GET['OrderNumber']=(int)$_GET['OrderNumber'];
$_SESSION['Items'.$identifier] = new cart;
/*read in all the guff from the selected order into the Items cart */
$OrderHeaderSQL = "SELECT salesorders.orderno,
salesorders.debtorno,
debtorsmaster.name,
salesorders.branchcode,
salesorders.customerref,
salesorders.comments,
salesorders.internalcomment,
salesorders.orddate,
salesorders.ordertype,
salesorders.shipvia,
salesorders.deliverto,
salesorders.deladd1,
salesorders.deladd2,
salesorders.deladd3,
salesorders.deladd4,
salesorders.deladd5,
salesorders.deladd6,
salesorders.contactphone,
salesorders.contactemail,
salesorders.salesperson,
salesorders.freightcost,
salesorders.deliverydate,
debtorsmaster.currcode,
salesorders.fromstkloc,
locations.taxprovinceid,
custbranch.taxgroupid,
currencies.rate as currency_rate,
currencies.decimalplaces,
custbranch.defaultshipvia,
custbranch.specialinstructions,
pickreq.consignment,
pickreq.packages
FROM salesorders
INNER JOIN debtorsmaster
ON salesorders.debtorno = debtorsmaster.debtorno
INNER JOIN custbranch
ON salesorders.branchcode = custbranch.branchcode
AND salesorders.debtorno = custbranch.debtorno
INNER JOIN currencies
ON debtorsmaster.currcode = currencies.currabrev
INNER JOIN locations
ON locations.loccode=salesorders.fromstkloc
INNER JOIN locationusers
ON locationusers.loccode=salesorders.fromstkloc
AND locationusers.userid='" . $_SESSION['UserID'] . "'
AND locationusers.canupd=1
LEFT OUTER JOIN pickreq
ON pickreq.orderno=salesorders.orderno
AND pickreq.closed=0
WHERE salesorders.orderno = '" . $_GET['OrderNumber']."'";
if ($_SESSION['SalesmanLogin'] != '') {
$OrderHeaderSQL .= " AND salesorders.salesperson='" . $_SESSION['SalesmanLogin'] . "'";
}
$ErrMsg = _('The order cannot be retrieved because');
$DbgMsg = _('The SQL to get the order header was');
$GetOrdHdrResult = DB_query($OrderHeaderSQL,$ErrMsg,$DbgMsg);
if (DB_num_rows($GetOrdHdrResult)==1) {
$myrow = DB_fetch_array($GetOrdHdrResult);
$_SESSION['Items'.$identifier]->DebtorNo = $myrow['debtorno'];
$_SESSION['Items'.$identifier]->OrderNo = $myrow['orderno'];
$_SESSION['Items'.$identifier]->Branch = $myrow['branchcode'];
$_SESSION['Items'.$identifier]->CustomerName = $myrow['name'];
$_SESSION['Items'.$identifier]->CustRef = $myrow['customerref'];
$_SESSION['Items'.$identifier]->Comments = $myrow['comments'];
$_SESSION['Items'.$identifier]->DefaultSalesType =$myrow['ordertype'];
$_SESSION['Items'.$identifier]->DefaultCurrency = $myrow['currcode'];
$_SESSION['Items'.$identifier]->CurrDecimalPlaces = $myrow['decimalplaces'];
$BestShipper = $myrow['shipvia'];
$_SESSION['Items'.$identifier]->ShipVia = $myrow['shipvia'];
$_SESSION['Items'.$identifier]->InternalComments = reverse_escape($myrow['internalcomment']);
$_SESSION['Items'.$identifier]->Consignment = $myrow['consignment'];
$_SESSION['Items'.$identifier]->Packages = $myrow['packages'];
if (is_null($BestShipper)) {
$BestShipper=0;
}
$_SESSION['Items'.$identifier]->DeliverTo = $myrow['deliverto'];
$_SESSION['Items'.$identifier]->DeliveryDate = ConvertSQLDate($myrow['deliverydate']);
$_SESSION['Items'.$identifier]->BrAdd1 = $myrow['deladd1'];
$_SESSION['Items'.$identifier]->BrAdd2 = $myrow['deladd2'];
$_SESSION['Items'.$identifier]->BrAdd3 = $myrow['deladd3'];
$_SESSION['Items'.$identifier]->BrAdd4 = $myrow['deladd4'];
$_SESSION['Items'.$identifier]->BrAdd5 = $myrow['deladd5'];
$_SESSION['Items'.$identifier]->BrAdd6 = $myrow['deladd6'];
$_SESSION['Items'.$identifier]->PhoneNo = $myrow['contactphone'];
$_SESSION['Items'.$identifier]->Email = $myrow['contactemail'];
$_SESSION['Items'.$identifier]->SalesPerson = $myrow['salesperson'];
$_SESSION['Items'.$identifier]->Location = $myrow['fromstkloc'];
$_SESSION['Items'.$identifier]->FreightCost = $myrow['freightcost'];
$_SESSION['Old_FreightCost'] = $myrow['freightcost'];
// $_POST['ChargeFreightCost'] = $_SESSION['Old_FreightCost'];
$_SESSION['Items'.$identifier]->Orig_OrderDate = $myrow['orddate'];
$_SESSION['CurrencyRate'] = $myrow['currency_rate'];
$_SESSION['Items'.$identifier]->TaxGroup = $myrow['taxgroupid'];
$_SESSION['Items'.$identifier]->DispatchTaxProvince = $myrow['taxprovinceid'];
$_SESSION['Items'.$identifier]->GetFreightTaxes();
$_SESSION['Items'.$identifier]->SpecialInstructions = $myrow['specialinstructions'];
DB_free_result($GetOrdHdrResult);
/*now populate the line items array with the sales order details records */
$LineItemsSQL = "SELECT stkcode,
stockmaster.description,
stockmaster.longdescription,
stockmaster.controlled,
stockmaster.serialised,
stockmaster.volume,
stockmaster.grossweight,
stockmaster.units,
stockmaster.decimalplaces,
stockmaster.mbflag,
stockmaster.taxcatid,
stockmaster.discountcategory,
salesorderdetails.unitprice,
salesorderdetails.quantity,
salesorderdetails.discountpercent,
salesorderdetails.actualdispatchdate,
salesorderdetails.qtyinvoiced,
salesorderdetails.narrative,
salesorderdetails.orderlineno,
salesorderdetails.poline,
salesorderdetails.itemdue,
stockmaster.materialcost + stockmaster.labourcost + stockmaster.overheadcost AS standardcost
FROM salesorderdetails INNER JOIN stockmaster
ON salesorderdetails.stkcode = stockmaster.stockid
WHERE salesorderdetails.orderno ='" . $_GET['OrderNumber'] . "'
AND salesorderdetails.quantity - salesorderdetails.qtyinvoiced >0
ORDER BY salesorderdetails.orderlineno";
$ErrMsg = _('The line items of the order cannot be retrieved because');
$DbgMsg = _('The SQL that failed was');
$LineItemsResult = DB_query($LineItemsSQL,$ErrMsg,$DbgMsg);
if (DB_num_rows($LineItemsResult)>0) {
while ($myrow=DB_fetch_array($LineItemsResult)) {
$QOHSQL = "SELECT quantity FROM locstock WHERE stockid='" . $myrow['stkcode'] . "' and loccode='" . $_SESSION['Items'.$identifier]->Location . "'";
$QOHResult = DB_query($QOHSQL);
$QOHRow = DB_fetch_array($QOHResult);
$_SESSION['Items'.$identifier]->add_to_cart($myrow['stkcode'],
$myrow['quantity'],
$myrow['description'],
$myrow['longdescription'],
$myrow['unitprice'],
$myrow['discountpercent'],
$myrow['units'],
$myrow['volume'],
$myrow['grossweight'],
$QOHRow['quantity'],
$myrow['mbflag'],
$myrow['actualdispatchdate'],
$myrow['qtyinvoiced'],
$myrow['discountcategory'],
$myrow['controlled'],
$myrow['serialised'],
$myrow['decimalplaces'],
htmlspecialchars_decode($myrow['narrative']),
'No',
$myrow['orderlineno'],
$myrow['taxcatid'],
'',
$myrow['itemdue'],
$myrow['poline'],
$myrow['standardcost']); /*NB NO Updates to DB */
/*Calculate the taxes applicable to this line item from the customer branch Tax Group and Item Tax Category */
$_SESSION['Items'.$identifier]->GetTaxes($myrow['orderlineno']);
$SerialItemsSQL = "SELECT pickreqdetails.qtypicked,
pickserialdetails.stockid,
serialno,
moveqty
FROM pickreq
INNER JOIN pickreqdetails
ON pickreqdetails.prid=pickreq.prid
LEFT OUTER JOIN pickserialdetails
ON pickserialdetails.detailno=pickreqdetails.detailno
WHERE pickreq.orderno ='" . $_GET['OrderNumber'] . "'
AND pickreq.closed=0
AND pickreqdetails.orderlineno='" . $myrow['orderlineno'] . "'";
$ErrMsg = _('The serial items of the pick list cannot be retrieved because');
$DbgMsg = _('The SQL that failed was');
$SerialItemsResult = DB_query($SerialItemsSQL, $ErrMsg, $DbgMsg);
if (DB_num_rows($SerialItemsResult) > 0) {
$InOutModifier = 1;
while ($MySerial = DB_fetch_array($SerialItemsResult)) {
if (isset($MySerial['serialno'])) {
$_SESSION['Items'.$identifier]->LineItems[$myrow['orderlineno']]->SerialItems[$MySerial['serialno']] = new SerialItem($MySerial['serialno'], ($InOutModifier > 0 ? 1 : 1) * filter_number_format($MySerial['moveqty']));
} else {
if ($_SESSION['RequirePickingNote'] == 1) {
$_SESSION['Items'.$identifier]->LineItems[$myrow['orderlineno']]->QtyDispatched = $MySerial['qtypicked'];
}
}
}
}
} /* line items from sales order details */
} else { /* there are no line items that have a quantity to deliver */
echo '<br />';
prnMsg( _('There are no ordered items with a quantity left to deliver. There is nothing left to invoice'));
include ('includes/footer.php');
exit;
} //end of checks on returned data set
DB_free_result($LineItemsResult);
} else {// End if the order was returned successfully.
echo '<br />' .
prnMsg( _('This order item could not be retrieved. Please select another order'), 'warn');
include ('includes/footer.php');
exit;
} //valid order returned from the entered order number
} else {
/* if processing, a dispatch page has been called and ${$StkItm->LineNumber} would have been set from the post
set all the necessary session variables changed by the POST */
if (isset($_POST['ShipVia'])) {
$_SESSION['Items'.$identifier]->ShipVia = $_POST['ShipVia'];
}
if (isset($_POST['ChargeFreightCost'])) {
$_SESSION['Items'.$identifier]->FreightCost = filter_number_format($_POST['ChargeFreightCost']);
}
if (isset($_POST['InternalComments'])) {
$_SESSION['Items'.$identifier]->InternalComments = $_POST['InternalComments'];
}
$i=1;
foreach ($_SESSION['Items'.$identifier]->FreightTaxes as $FreightTaxLine) {
if (isset($_POST['FreightTaxRate' . $i])) {
$_SESSION['Items'.$identifier]->FreightTaxes[$i]->TaxRate = filter_number_format($_POST['FreightTaxRate' . $i])/100;
}
$i++;
}
foreach ($_SESSION['Items'.$identifier]->LineItems as $Itm) {
if (sizeOf($Itm->SerialItems) > 0) {
$_SESSION['Items'.$identifier]->LineItems[$Itm->LineNumber]->QtyDispatched = 0; //initialise QtyDispatched
foreach ($Itm->SerialItems as $SerialItem) { //calculate QtyDispatched from bundle quantities
$_SESSION['Items'.$identifier]->LineItems[$Itm->LineNumber]->QtyDispatched += $SerialItem->BundleQty;
}
//Preventing from dispatched more than ordered. Since it's controlled items, users must select the batch/lot again.
if ($_SESSION['Items'.$identifier]->LineItems[$Itm->LineNumber]->QtyDispatched > ($_SESSION['Items'.$identifier]->LineItems[$Itm->LineNumber]->Quantity - $_SESSION['Items'.$identifier]->LineItems[$Itm->LineNumber]->QtyInv)) {
prnMsg(_('Dispatched Quantity should not be more than order balanced quantity').'. '._('To dispatch quantity is').' '.$_SESSION['Items'.$identifier]->LineItems[$Itm->LineNumber]->QtyDispatched.' '._('And the order balance is ').' '.($_SESSION['Items'.$identifier]->LineItems[$Itm->LineNumber]->Quantity - $_SESSION['Items'.$identifier]->LineItems[$Itm->LineNumber]->QtyInv),'error');
include ('includes/footer.php');
exit;
}
} elseif (isset($_POST[$Itm->LineNumber . '_QtyDispatched' ])) {
if (is_numeric(filter_number_format($_POST[$Itm->LineNumber . '_QtyDispatched' ]))
AND filter_number_format($_POST[$Itm->LineNumber . '_QtyDispatched']) <= ($_SESSION['Items'.$identifier]->LineItems[$Itm->LineNumber]->Quantity - $_SESSION['Items'.$identifier]->LineItems[$Itm->LineNumber]->QtyInv)) {
$_SESSION['Items'.$identifier]->LineItems[$Itm->LineNumber]->QtyDispatched = round(filter_number_format($_POST[$Itm->LineNumber . '_QtyDispatched']),$Itm->DecimalPlaces);
}
}
$i=1;
foreach ($Itm->Taxes as $TaxLine) {
if (isset($_POST[$Itm->LineNumber . $i . '_TaxRate'])) {
$_SESSION['Items'.$identifier]->LineItems[$Itm->LineNumber]->Taxes[$i]->TaxRate = filter_number_format($_POST[$Itm->LineNumber . $i . '_TaxRate'])/100;
}
$i++;
}
} //end foreach lineitem
}
/* Always display dispatch quantities and recalc freight for items being dispatched */
if ($_SESSION['Items'.$identifier]->SpecialInstructions) {
prnMsg($_SESSION['Items'.$identifier]->SpecialInstructions,'warn');
}
echo '<p class="page_title_text"><img alt="" src="', $RootPath, '/css/', $Theme,
'/images/inventory.png" title="', // Icon image.
_('Confirm Dispatch and Invoice'), '" /> ', // Icon title.
_('Confirm Dispatch and Invoice'), '</p>', // Page title.
'<table class="selection">
<tr>
<td>', _('Customer Code'), '</td>
<td class="text">', $_SESSION['Items'.$identifier]->DebtorNo, '</td>
</tr>
<tr>
<td>', _('Customer Name'), '</td>
<td class="text">', $_SESSION['Items'.$identifier]->CustomerName, '</td>
</tr>
<tr>
<td>', _('Invoice amounts stated in'), '</td>
<td class="text">', $_SESSION['Items'.$identifier]->DefaultCurrency, ' - ', $CurrencyName[$_SESSION['Items'.$identifier]->DefaultCurrency], '</td>
</tr>
</table>
<br />';
echo '<form action="' . htmlspecialchars($_SERVER['PHP_SELF'],ENT_QUOTES,'UTF-8') . '?identifier='.$identifier . '" method="post">';
echo '<div>';
echo '<input type="hidden" name="FormID" value="' . $_SESSION['FormID'] . '" />';
/***************************************************************
Line Item Display
***************************************************************/
echo '<table class="selection">
<thead>
<tr>
<th>' . _('Item Code') . '</th>
<th>' . _('Item Description') . '</th>
<th>' . _('Ordered') . '</th>
<th>' . _('Units') . '</th>
<th>' . _('Already') . '<br />' . _('Sent') . '</th>
<th>' . _('This Dispatch') . '</th>
<th>' . _('Price') . '</th>
<th>' . _('Discount') . '</th>
<th>' . _('Total') . '<br />' . _('Excl Tax') . '</th>
<th>' . _('Tax Authority') . '</th>
<th>' . _('Tax %') . '</th>
<th>' . _('Tax Amount') . '</th>
<th>' . _('Total') . '<br />' . _('Incl Tax') . '</th>
</tr>
</thead><tbody>';
$_SESSION['Items'.$identifier]->total = 0;
$_SESSION['Items'.$identifier]->totalVolume = 0;
$_SESSION['Items'.$identifier]->totalWeight = 0;
$TaxTotals = array();
$TaxGLCodes = array();
$TaxTotal =0;
/*show the line items on the order with the quantity being dispatched available for modification */
$j = 0;// Used for autofocus on first field.
foreach ($_SESSION['Items'.$identifier]->LineItems as $LnItm) {
if ($LnItm->QOHatLoc < $LnItm->Quantity and ($LnItm->MBflag == 'B' or $LnItm->MBflag == 'M')) {
/*There is a stock deficiency in the stock location selected */
$RowStarter = '<tr style="background:#FF0000;color:#FFC0CB">'; //rows show red where stock deficiency
} else {
$RowStarter = '<tr class="striped_row">';
}
if (sizeOf($LnItm->SerialItems) > 0) {
$_SESSION['Items'.$identifier]->LineItems[$LnItm->LineNumber]->QtyDispatched = 0; //initialise QtyDispatched
foreach ($LnItm->SerialItems as $SerialItem) { //calculate QtyDispatched from bundle quantities
$_SESSION['Items'.$identifier]->LineItems[$LnItm->LineNumber]->QtyDispatched += $SerialItem->BundleQty;
}
} elseif (isset($_POST[$LnItm->LineNumber . '_QtyDispatched'])) {
if (is_numeric(filter_number_format($_POST[$LnItm->LineNumber . '_QtyDispatched'])) and filter_number_format($_POST[$LnItm->LineNumber . '_QtyDispatched']) <= ($_SESSION['Items'.$identifier]->LineItems[$LnItm->LineNumber]->Quantity - $_SESSION['Items'.$identifier]->LineItems[$LnItm->LineNumber]->QtyInv)) {
$_SESSION['Items'.$identifier]->LineItems[$LnItm->LineNumber]->QtyDispatched = round(filter_number_format($_POST[$LnItm->LineNumber . '_QtyDispatched']), $LnItm->DecimalPlaces);
}
}
$LineTotal = $LnItm->QtyDispatched * $LnItm->Price * (1 - $LnItm->DiscountPercent);
$_SESSION['Items'.$identifier]->total += $LineTotal;
$_SESSION['Items'.$identifier]->totalVolume += ($LnItm->QtyDispatched * $LnItm->Volume);
$_SESSION['Items'.$identifier]->totalWeight += ($LnItm->QtyDispatched * $LnItm->Weight);
echo $RowStarter;
echo '<td>' . $LnItm->StockID . '</td>
<td class="text" title="' . $LnItm->LongDescription . '">' . $LnItm->ItemDescription . '</td>
<td class="number">' . locale_number_format($LnItm->Quantity, $LnItm->DecimalPlaces) . '</td>
<td class="text">' . $LnItm->Units . '</td>
<td class="number">' . locale_number_format($LnItm->QtyInv, $LnItm->DecimalPlaces) . '</td>';
if ($LnItm->Controlled==1) {
if (isset($_POST['ProcessInvoice'])) {
echo '<td class="number">' . locale_number_format($LnItm->QtyDispatched,$LnItm->DecimalPlaces) . '</td>';
} else {
echo '<td class="number"><input type="hidden" name="' . $LnItm->LineNumber . '_QtyDispatched" required="required" maxlength="11" value="' . $LnItm->QtyDispatched . '" /><a href="' . $RootPath .'/ConfirmDispatchControlled_Invoice.php?identifier=' . urlencode($identifier) . '&LineNo=' . urlencode($LnItm->LineNumber) . '">' .locale_number_format($LnItm->QtyDispatched,$LnItm->DecimalPlaces) . '</a></td>';
}
} else {
if (isset($_POST['ProcessInvoice'])) {
echo '<td class="number">', locale_number_format($LnItm->QtyDispatched,$LnItm->DecimalPlaces), '</td>';
} else {
echo '<td class="number"><input ', (++$j==1 ? 'autofocus="autofocus" ' : ''), 'class="number" maxlength="12" name="', $LnItm->LineNumber, '_QtyDispatched" required="required" title="', _('Enter the quantity to charge the customer for, that has been dispatched'), '" type="text" size="12" value="', locale_number_format($LnItm->QtyDispatched,$LnItm->DecimalPlaces), '" /></td>';
}
}
$DisplayDiscountPercent = locale_number_format($LnItm->DiscountPercent*100,2) . '%';
$DisplayLineNetTotal = locale_number_format($LineTotal,$_SESSION['Items'.$identifier]->CurrDecimalPlaces);
$DisplayPrice = locale_number_format($LnItm->Price,$_SESSION['Items'.$identifier]->CurrDecimalPlaces);
echo '<td class="number">' . $DisplayPrice . '</td>
<td class="number">' . $DisplayDiscountPercent . '</td>
<td class="number">' . $DisplayLineNetTotal . '</td>';
/*Need to list the taxes applicable to this line */
echo '<td>';
$i=0;
foreach ($_SESSION['Items'.$identifier]->LineItems[$LnItm->LineNumber]->Taxes AS $Tax) {
if ($i>0) {
echo '<br />';
}
echo $Tax->TaxAuthDescription;
$i++;
}
echo '</td>
<td class="number">';
$i=1; // initialise the number of taxes iterated through
$TaxLineTotal =0; //initialise tax total for the line
foreach ($LnItm->Taxes AS $Tax) {
if (empty($TaxTotals[$Tax->TaxAuthID])) {
$TaxTotals[$Tax->TaxAuthID]=0;
}
if ($i>1) {
echo '<br />';
}
if (isset($_POST['ProcessInvoice'])) {
echo $Tax->TaxRate*100;
} else {
echo '<input type="text" class="number" required="required" title="' . _('Enter the tax rate applicable as a number') . '" name="' . $LnItm->LineNumber . $i . '_TaxRate" maxlength="4" size="4" value="' . $Tax->TaxRate*100 . '" />';
}
$i++;
if ($Tax->TaxOnTax ==1) {
$TaxTotals[$Tax->TaxAuthID] += ($Tax->TaxRate * ($LineTotal + $TaxLineTotal));
$TaxLineTotal += ($Tax->TaxRate * ($LineTotal + $TaxLineTotal));
} else {
$TaxTotals[$Tax->TaxAuthID] += ($Tax->TaxRate * $LineTotal);
$TaxLineTotal += ($Tax->TaxRate * $LineTotal);
}
$TaxGLCodes[$Tax->TaxAuthID] = $Tax->TaxGLCode;
}
echo '</td>';
$TaxTotal += $TaxLineTotal;
$DisplayTaxAmount = locale_number_format($TaxLineTotal ,$_SESSION['Items'.$identifier]->CurrDecimalPlaces);
$DisplayGrossLineTotal = locale_number_format($LineTotal+ $TaxLineTotal,$_SESSION['Items'.$identifier]->CurrDecimalPlaces);
echo '<td class="number">' . $DisplayTaxAmount . '</td>
<td class="number">' . $DisplayGrossLineTotal . '</td>';
if ($LnItm->Controlled==1) {
if (!isset($_POST['ProcessInvoice'])) {
echo '<td><a href="' . $RootPath . '/ConfirmDispatchControlled_Invoice.php?identifier=' . urlencode($identifier) . '&LineNo=' . urlencode($LnItm->LineNumber) . '">';
if ($LnItm->Serialised==1) {
echo _('Enter Serial Numbers');
} else { /*Just batch/roll/lot control */
echo _('Enter Batch/Roll/Lot #');
}
echo '</a></td>';
}
}
echo '</tr>';
if (mb_strlen($LnItm->Narrative)>1) {
$Narrative=str_replace('\r\n','<br />', $LnItm->Narrative);
echo $RowStarter . '<td colspan="12">' . stripslashes($Narrative) . '</td></tr>';
}
}//end foreach ($line)
/*Don't re-calculate freight if some of the order has already been delivered -
depending on the business logic required this condition may not be required.
It seems unfair to charge the customer twice for freight if the order
was not fully delivered the first time ?? */
if (!isset($_SESSION['Items'.$identifier]->FreightCost) or $_SESSION['Items'.$identifier]->FreightCost == 0) {
if ($_SESSION['DoFreightCalc']==True) {
list ($FreightCost, $BestShipper) = CalcFreightCost($_SESSION['Items'.$identifier]->total,
$_SESSION['Items'.$identifier]->BrAdd2,
$_SESSION['Items'.$identifier]->BrAdd3,
$_SESSION['Items'.$identifier]->BrAdd4,
$_SESSION['Items'.$identifier]->BrAdd5,
$_SESSION['Items'.$identifier]->BrAdd6,
$_SESSION['Items'.$identifier]->totalVolume,
$_SESSION['Items'.$identifier]->totalWeight,
$_SESSION['Items'.$identifier]->Location,
$_SESSION['Items'.$identifier]->DefaultCurrency);
$_SESSION['Items'.$identifier]->ShipVia = $BestShipper;
}
if (isset($FreightCost) and is_numeric($FreightCost)) {
$FreightCost = $FreightCost / $_SESSION['CurrencyRate'];
} else {
$FreightCost =0;
}
if (!is_numeric($BestShipper)) {
$SQL = "SELECT shipper_id FROM shippers WHERE shipper_id='" . $_SESSION['Default_Shipper'] . "'";
$ErrMsg = _('There was a problem testing for a default shipper because');
$TestShipperExists = DB_query($SQL, $ErrMsg);
if (DB_num_rows($TestShipperExists)==1) {
$BestShipper = $_SESSION['Default_Shipper'];
} else {
$SQL = "SELECT shipper_id FROM shippers";
$ErrMsg = _('There was a problem testing for a default shipper');
$TestShipperExists = DB_query($SQL, $ErrMsg);
if (DB_num_rows($TestShipperExists)>=1) {
$ShipperReturned = DB_fetch_row($TestShipperExists);
$BestShipper = $ShipperReturned[0];
} else {
prnMsg( _('There are no shippers defined') . '. ' . _('Please use the link below to set up shipping freight companies, the system expects the shipping company to be selected or a default freight company to be used'),'error');
echo '<a href="' . $RootPath . 'Shippers.php">' . _('Enter') . '/' . _('Amend Freight Companies'). '</a>';
}
}
}
}
if (isset($_POST['ChargeFreightCost']) AND !is_numeric(filter_number_format($_POST['ChargeFreightCost']))) {
$_POST['ChargeFreightCost'] = 0;
}
echo '<tr>
<td class="number" colspan="2">', _('Order Freight Cost'), '</td>
<td class="number">', locale_number_format($_SESSION['Old_FreightCost'], $_SESSION['Items'.$identifier]->CurrDecimalPlaces), '</td>';
if ($_SESSION['DoFreightCalc']==True) {
echo '<td class="number" colspan="2">', _('Recalculated Freight Cost'), '</td>
<td class="number">', locale_number_format($FreightCost, $_SESSION['Items'.$identifier]->CurrDecimalPlaces), '</td>';
} else {
// echo '<td colspan="1"></td>';// Should be?: echo '<td colspan="3"> </td>';
}
if (!isset($_POST['ChargeFreightCost'])) {
$_POST['ChargeFreightCost']=0;
}
echo '<td class="number" colspan="2">', _('Charge Freight Cost ex Tax'), '</td>';
if ($_SESSION['Items'.$identifier]->Any_Already_Delivered()==1
AND (!isset($_SESSION['Items'.$identifier]->FreightCost)
OR $_POST['ChargeFreightCost']==0)) {
echo '<td><input class="number" maxlength="12" name="ChargeFreightCost" required="required" size="10" type="text" value="0" /></td>';
$_SESSION['Items'.$identifier]->FreightCost = 0;
} else {
if (isset($_POST['ProcessInvoice'])) {
echo '<td class="number">' . locale_number_format($_SESSION['Items'.$identifier]->FreightCost,$_SESSION['Items'.$identifier]->CurrDecimalPlaces) . '</td>';
} else {
echo '<td class="number"><input class="number" maxlength="12" name="ChargeFreightCost" size="10" type="text" value="'. locale_number_format($_SESSION['Items'.$identifier]->FreightCost,$_SESSION['Items'.$identifier]->CurrDecimalPlaces). '" /></td>';
}
$_POST['ChargeFreightCost'] = locale_number_format($_SESSION['Items'.$identifier]->FreightCost,$_SESSION['Items'.$identifier]->CurrDecimalPlaces);
}
$FreightTaxTotal = 0;// initialise tax total
echo '<td>';
$i=0; // initialise the number of taxes iterated through
foreach ($_SESSION['Items'.$identifier]->FreightTaxes as $FreightTaxLine) {
if ($i>0) {
echo '<br />';
}
echo $FreightTaxLine->TaxAuthDescription;
$i++;
}
echo '</td><td class="number">';
$i=0;
foreach ($_SESSION['Items'.$identifier]->FreightTaxes as $FreightTaxLine) {
if ($i>0) {
echo '<br />';
}
if (isset($_POST['ProcessInvoice'])) {
echo $FreightTaxLine->TaxRate * 100 ;
} else {
echo '<input class="number" maxlength="4" name="FreightTaxRate'. $FreightTaxLine->TaxCalculationOrder. '" size="4" type="text" value="'. locale_number_format($FreightTaxLine->TaxRate * 100, $_SESSION['Items'.$identifier]->CurrDecimalPlaces) . '" />';
}
if ($FreightTaxLine->TaxOnTax ==1) {
$TaxTotals[$FreightTaxLine->TaxAuthID] += ($FreightTaxLine->TaxRate * ($_SESSION['Items'.$identifier]->FreightCost + $FreightTaxTotal));
$FreightTaxTotal += ($FreightTaxLine->TaxRate * ($_SESSION['Items'.$identifier]->FreightCost + $FreightTaxTotal));
} else {
$TaxTotals[$FreightTaxLine->TaxAuthID] += ($FreightTaxLine->TaxRate * $_SESSION['Items'.$identifier]->FreightCost);
$FreightTaxTotal += ($FreightTaxLine->TaxRate * $_SESSION['Items'.$identifier]->FreightCost);
}
$i++;
$TaxGLCodes[$FreightTaxLine->TaxAuthID] = $FreightTaxLine->TaxGLCode;
}
echo '</td>';
echo '<td class="number">' . locale_number_format($FreightTaxTotal,$_SESSION['Items'.$identifier]->CurrDecimalPlaces) . '</td>
<td class="number">' . locale_number_format($FreightTaxTotal + filter_number_format($_POST['ChargeFreightCost']),$_SESSION['Items'.$identifier]->CurrDecimalPlaces) . '</td>
</tr>';
$TaxTotal += $FreightTaxTotal;
$DisplaySubTotal = locale_number_format(($_SESSION['Items'.$identifier]->total + filter_number_format($_POST['ChargeFreightCost'])),$_SESSION['Items'.$identifier]->CurrDecimalPlaces);
echo '<tr>
<td colspan="8" class="number">' . _('Invoice Totals'). '</td>
<td class="number"><hr /><b>' . $DisplaySubTotal . '</b><hr /></td>
<td colspan="2"></td>
<td class="number"><hr /><b>' . locale_number_format($TaxTotal,$_SESSION['Items'.$identifier]->CurrDecimalPlaces) . '</b><hr /></td>
<td class="number"><hr /><b>' . locale_number_format($TaxTotal+($_SESSION['Items'.$identifier]->total + $_POST['ChargeFreightCost']),$_SESSION['Items'.$identifier]->CurrDecimalPlaces) . '</b><hr /></td>
</tr>';
if (! isset($_POST['DispatchDate']) OR ! Is_Date($_POST['DispatchDate'])) {
$DefaultDispatchDate = Date($_SESSION['DefaultDateFormat'],CalcEarliestDispatchDate());
} else {
$DefaultDispatchDate = $_POST['DispatchDate'];
}
echo '<tbody></table><br />';
if (isset($_POST['ProcessInvoice']) AND $_POST['ProcessInvoice'] != '') {
/* SQL to process the postings for sales invoices...
/*First check there are lines on the dipatch with quantities to invoice
invoices can have a zero amount but there must be a quantity to invoice */
$QuantityInvoicedIsPositive = false;
foreach ($_SESSION['Items'.$identifier]->LineItems as $OrderLine) {
if ($OrderLine->QtyDispatched > 0) {
$QuantityInvoicedIsPositive =true;
}
}
if (! $QuantityInvoicedIsPositive) {
prnMsg( _('There are no lines on this order with a quantity to invoice') . '. ' . _('No further processing has been done'),'error');
include ('includes/footer.php');
exit;
}
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,$ErrMsg);
$CheckNegRow = DB_fetch_array($Result);
if (($CheckNegRow['mbflag']=='B' OR $CheckNegRow['mbflag']=='M') AND mb_substr($OrderLine->StockID,0,4)!='ASSET') {
if ($CheckNegRow['quantity'] < $OrderLine->QtyDispatched) {
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;
}
} elseif ($CheckNegRow['mbflag']=='A') {
/*Now look for assembly components that would go negative */
$SQL = "SELECT bom.component,
stockmaster.description,
locstock.quantity-(" . $OrderLine->QtyDispatched . "*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 <= CURRENT_DATE
AND effectiveto > CURRENT_DATE";
$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,$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) {
echo '</div>';
echo '</form>';
echo '<div class="centre">
<input type="submit" name="Update" value="' . _('Update'). '" /></div>';
include ('includes/footer.php');
exit;
}
}//end of testing for negative stocks
/* 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 Area where the Sale is to from the BRANCHES table') . '. ' . _('Please remedy this');
$Result = DB_query($SQL, $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.php');
exit;
}
/*Now need to check that the order details are the same as they were when they were read into the Items array. If they've changed then someone else may have invoiced them */
$SQL = "SELECT stkcode,
quantity,
qtyinvoiced,
orderlineno
FROM salesorderdetails
WHERE completed=0 AND quantity-qtyinvoiced > 0
AND orderno = '" . $_SESSION['ProcessingOrder']."'";
$Result = DB_query($SQL);
if (DB_num_rows($Result) != count($_SESSION['Items'.$identifier]->LineItems)) {
/*there should be the same number of items returned from this query as there are lines on the invoice - if not then someone has already invoiced or credited some lines */
if ($debug==1) {
echo '<br />' . $SQL;
echo '<br />' . _('Number of rows returned by SQL') . ':' . DB_num_rows($Result);
echo '<br />' . _('Count of items in the session') . ' ' . count($_SESSION['Items'.$identifier]->LineItems);
}
echo '<br />';
prnMsg( _('This order has been changed or invoiced since this delivery was started to be confirmed') . '. ' . _('Processing halted') . '. ' . _('To enter and confirm this dispatch') . '/' . _('invoice the order must be re-selected and re-read again to update the changes made by the other user'), 'error');
unset($_SESSION['Items'.$identifier]->LineItems);
unset($_SESSION['Items'.$identifier]);
unset($_SESSION['ProcessingOrder']);
include ('includes/footer.php'); exit;
}
$Changes =0;
while ($myrow = DB_fetch_array($Result)) {
if ($_SESSION['Items'.$identifier]->LineItems[$myrow['orderlineno']]->Quantity != $myrow['quantity']
OR $_SESSION['Items'.$identifier]->LineItems[$myrow['orderlineno']]->QtyInv != $myrow['qtyinvoiced']) {
echo '<br />' . _('Orig order for'). ' ' . $myrow['orderlineno'] . ' '. _('has a quantity of'). ' ' . $myrow['quantity'] . ' '. _('and an invoiced qty of'). ' ' . $myrow['qtyinvoiced'] . ' '. _('the session shows quantity of'). ' ' . $_SESSION['Items'.$identifier]->LineItems[$myrow['orderlineno']]->Quantity . ' ' . _('and quantity invoice of'). ' ' . $_SESSION['Items'.$identifier]->LineItems[$myrow['orderlineno']]->QtyInv;
prnMsg( _('This order has been changed or invoiced since this delivery was started to be confirmed') . ' ' . _('Processing halted.') . ' ' . _('To enter and confirm this dispatch, it must be re-selected and re-read again to update the changes made by the other user'), 'error');
echo '<br />';
echo '<div class="centre"><a href="'. $RootPath . '/SelectSalesOrder.php">' . _('Select a sales order for confirming deliveries and invoicing'). '</a></div>';
unset($_SESSION['Items'.$identifier]->LineItems);
unset($_SESSION['Items'.$identifier]);
unset($_SESSION['ProcessingOrder']);
include ('includes/footer.php');
exit;
}
} /*loop through all line items of the order to ensure none have been invoiced since started looking at this order*/
DB_free_result($Result);
// *************************************************************************
// 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
// *************************************************************************
/*Now Get the next invoice number - function in SQL_CommonFunctions*/
$InvoiceNo = GetNextTransNo(10);
$PeriodNo = GetPeriod($DefaultDispatchDate);
/*Start an SQL transaction */
DB_Txn_Begin();
if ($DefaultShipVia != $_SESSION['Items'.$identifier]->ShipVia) {
$SQL = "UPDATE custbranch
SET defaultshipvia ='" . $_SESSION['Items'.$identifier]->ShipVia . "'
WHERE debtorno='" . $_SESSION['Items'.$identifier]->DebtorNo . "'
AND branchcode='" . $_SESSION['Items'.$identifier]->Branch . "'";
$ErrMsg = _('Could not update the default shipping carrier for this branch because');
$DbgMsg = _('The SQL used to update the branch default carrier was');
$result = DB_query($SQL, $ErrMsg, $DbgMsg, true);
}
$DefaultDispatchDate = FormatDateForSQL($DefaultDispatchDate);
/*Update order header for invoice charged on */
$SQL = "UPDATE salesorders
SET comments = CONCAT(comments,' Inv ','" . $InvoiceNo . "'),
internalcomment = '" . $_POST['InternalComments'] . "',
printedpackingslip=0
WHERE orderno= '" . $_SESSION['ProcessingOrder']."'";
$ErrMsg = _('CRITICAL ERROR') . ' ' . _('NOTE DOWN THIS ERROR AND SEEK ASSISTANCE') . ': ' . _('The sales order header could not be updated with the invoice number');
$DbgMsg = _('The following SQL to update the sales order was used');
$Result = DB_query($SQL,$ErrMsg,$DbgMsg,true);
/*Now insert the DebtorTrans */
$SQL = "INSERT INTO debtortrans (transno,
type,
debtorno,
branchcode,
trandate,
inputdate,
prd,
reference,
tpe,
order_,
ovamount,
ovgst,
ovfreight,
rate,
invtext,
shipvia,
consignment,
packages,
salesperson )
VALUES (
'". $InvoiceNo . "',
10,
'" . $_SESSION['Items'.$identifier]->DebtorNo . "',
'" . $_SESSION['Items'.$identifier]->Branch . "',
'" . $DefaultDispatchDate . "',
'" . date('Y-m-d H-i-s') . "',
'" . $PeriodNo . "',
'" . $_SESSION['Items'.$identifier]->CustRef . "',
'" . $_SESSION['Items'.$identifier]->DefaultSalesType . "',
'" . $_SESSION['ProcessingOrder'] . "',
'" . $_SESSION['Items'.$identifier]->total . "',
'" . $TaxTotal . "',
'" . filter_number_format($_POST['ChargeFreightCost']) . "',
'" . $_SESSION['CurrencyRate'] . "',
'" . $_POST['InvoiceText'] . "',
'" . $_SESSION['Items'.$identifier]->ShipVia . "',
'" . $_POST['Consignment'] . "',
'" . $_POST['Packages'] . "',
'" . $_SESSION['Items'.$identifier]->SalesPerson . "' )";
$ErrMsg =_('CRITICAL ERROR') . '! ' . _('NOTE DOWN THIS ERROR AND SEEK ASSISTANCE') . ': ' . _('The debtor transaction record could not be inserted because');
$DbgMsg = _('The following SQL to insert the debtor transaction record was used');
$Result = DB_query($SQL,$ErrMsg,$DbgMsg,true);
$DebtorTransID = DB_Last_Insert_ID('debtortrans','id');
/* Insert the tax totals for each tax authority where tax was charged on the invoice */
foreach ($TaxTotals AS $TaxAuthID => $TaxAmount) {
$SQL = "INSERT INTO debtortranstaxes (debtortransid,
taxauthid,
taxamount)
VALUES ('" . $DebtorTransID . "',
'" . $TaxAuthID . "',
'" . $TaxAmount/$_SESSION['CurrencyRate'] . "')";
$ErrMsg =_('CRITICAL ERROR') . '! ' . _('NOTE DOWN THIS ERROR AND SEEK ASSISTANCE') . ': ' . _('The debtor transaction taxes records could not be inserted because');
$DbgMsg = _('The following SQL to insert the debtor transaction taxes record was used');
$Result = DB_query($SQL,$ErrMsg,$DbgMsg,true);
}
/* If balance of the order cancelled update sales order details quantity. Also insert log records for OrderDeliveryDifferencesLog */
foreach ($_SESSION['Items'.$identifier]->LineItems as $OrderLine) {
/*Test to see if the item being sold is an asset */
if (mb_substr($OrderLine->StockID,0,6)=='ASSET-') {
$IsAsset = true;
$HyphenOccursAt = mb_strpos($OrderLine->StockID,'-',6);
if ($HyphenOccursAt == false) {
$AssetNumber = intval(mb_substr($OrderLine->StockID,6));
} else {
$AssetNumber = intval(mb_substr($OrderLine->StockID,6,mb_strlen($OrderLine->StockID)-$HyphenOccursAt-1));
}
prnMsg (_('The asset number being disposed of is:') . ' ' . $AssetNumber, 'info');
} else {
$IsAsset = false;
$AssetNumber = 0;
}
if ($_POST['BOPolicy']=='CAN') {
$SQL = "UPDATE salesorderdetails
SET quantity = quantity - " . ($OrderLine->Quantity - $OrderLine->QtyDispatched - $OrderLine->QtyInv) . "
WHERE orderno = '" . $_SESSION['ProcessingOrder'] . " '
AND orderlineno = '" . $OrderLine->LineNumber . "'";
$ErrMsg = _('CRITICAL ERROR') . '! ' . _('NOTE DOWN THIS ERROR AND SEEK ASSISTANCE') . ': ' . _('The sales order detail record could not be updated because');
$DbgMsg = _('The following SQL to update the sales order detail record was used');
$Result = DB_query($SQL,$ErrMsg,$DbgMsg,true);
if (($OrderLine->Quantity - $OrderLine->QtyDispatched)>0) {
$SQL = "INSERT INTO orderdeliverydifferenceslog (orderno,
invoiceno,
stockid,
quantitydiff,
debtorno,
branch,
can_or_bo)
VALUES (
'" . $_SESSION['ProcessingOrder'] . "',
'" . $InvoiceNo . "',
'" . $OrderLine->StockID . "',
'" . ($OrderLine->Quantity - $OrderLine->QtyDispatched - $OrderLine->QtyInv) . "',
'" . $_SESSION['Items'.$identifier]->DebtorNo . "',
'" . $_SESSION['Items'.$identifier]->Branch . "',
'CAN')";
$ErrMsg =_('CRITICAL ERROR') . '! ' . _('NOTE DOWN THIS ERROR AND SEEK ASSISTANCE') . ': ' . _('The order delivery differences log record could not be inserted because');
$DbgMsg = _('The following SQL to insert the order delivery differences record was used');
$Result = DB_query($SQL,$ErrMsg,$DbgMsg,true);
}
} elseif (($OrderLine->Quantity - $OrderLine->QtyDispatched)>0
AND DateDiff(ConvertSQLDate($DefaultDispatchDate),$_SESSION['Items'.$identifier]->DeliveryDate,'d')>0) {
/*The order is being short delivered after the due date - need to insert a delivery differnce log */
$SQL = "INSERT INTO orderdeliverydifferenceslog (orderno,
invoiceno,
stockid,
quantitydiff,
debtorno,
branch,
can_or_bo
)
VALUES (
'" . $_SESSION['ProcessingOrder'] . "',
'" . $InvoiceNo . "',
'" . $OrderLine->StockID . "',
'" . ($OrderLine->Quantity - $OrderLine->QtyDispatched - $OrderLine->QtyInv) . "',
'" . $_SESSION['Items'.$identifier]->DebtorNo . "',
'" . $_SESSION['Items'.$identifier]->Branch . "',
'BO'
)";
$ErrMsg = '<br />' . _('CRITICAL ERROR') . '! ' . _('NOTE DOWN THIS ERROR AND SEEK ASSISTANCE') . ': ' . _('The order delivery differences log record could not be inserted because');
$DbgMsg = _('The following SQL to insert the order delivery differences record was used');
$Result = DB_query($SQL,$ErrMsg,$DbgMsg,true);
} /*end of order delivery differences log entries */
/*Now update SalesOrderDetails for the quantity invoiced and the actual dispatch dates. */
if ($OrderLine->QtyDispatched !=0 AND $OrderLine->QtyDispatched!='' AND $OrderLine->QtyDispatched) {
// Test above to see if the line is completed or not
if ($OrderLine->QtyDispatched>=($OrderLine->Quantity - $OrderLine->QtyInv) OR $_POST['BOPolicy']=='CAN') {
$SQL = "UPDATE salesorderdetails
SET qtyinvoiced = qtyinvoiced + " . $OrderLine->QtyDispatched . ",
actualdispatchdate = '" . $DefaultDispatchDate . "',
completed=1
WHERE orderno = '" . $_SESSION['ProcessingOrder'] . "'
AND orderlineno = '" . $OrderLine->LineNumber . "'";
} else {
$SQL = "UPDATE salesorderdetails
SET qtyinvoiced = qtyinvoiced + " . $OrderLine->QtyDispatched . ",