forked from opensourcepos/opensourcepos
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSales.php
More file actions
1867 lines (1593 loc) · 81.1 KB
/
Copy pathSales.php
File metadata and controls
1867 lines (1593 loc) · 81.1 KB
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
namespace App\Controllers;
use App\Libraries\Barcode_lib;
use App\Libraries\Email_lib;
use App\Libraries\Sale_lib;
use App\Libraries\Tax_lib;
use App\Libraries\Token_lib;
use App\Models\Customer;
use App\Models\Customer_rewards;
use App\Models\Dinner_table;
use App\Models\Employee;
use App\Models\Giftcard;
use App\Models\Inventory;
use App\Models\Item;
use App\Models\Item_kit;
use App\Models\Sale;
use App\Models\Stock_location;
use App\Models\Tokens\Token_invoice_count;
use App\Models\Tokens\Token_customer;
use App\Models\Tokens\Token_invoice_sequence;
use CodeIgniter\HTTP\ResponseInterface;
use Config\Services;
use Config\OSPOS;
use ReflectionException;
use stdClass;
class Sales extends Secure_Controller
{
protected $helpers = ['file'];
private Barcode_lib $barcode_lib;
private Email_lib $email_lib;
private Sale_lib $sale_lib;
private Tax_lib $tax_lib;
private Token_lib $token_lib;
private Customer $customer;
private Customer_rewards $customer_rewards;
private Dinner_table $dinner_table;
protected Employee $employee;
private Item $item;
private Item_kit $item_kit;
private Sale $sale;
private Stock_location $stock_location;
private array $config;
public function __construct()
{
parent::__construct('sales');
$this->session = session();
$this->barcode_lib = new Barcode_lib();
$this->email_lib = new Email_lib();
$this->sale_lib = new Sale_lib();
$this->tax_lib = new Tax_lib();
$this->token_lib = new Token_lib();
$this->config = config(OSPOS::class)->settings;
$this->customer = model(Customer::class);
$this->sale = model(Sale::class);
$this->item = model(Item::class);
$this->item_kit = model(Item_kit::class);
$this->stock_location = model(Stock_location::class);
$this->customer_rewards = model(Customer_rewards::class);
$this->dinner_table = model(Dinner_table::class);
$this->employee = model(Employee::class);
}
public function getIndex(): ResponseInterface|string
{
$this->session->set('allow_temp_items', 1);
return $this->_reload(); // TODO: Hungarian Notation
}
/**
* Load the customer display popup.
*
* @return ResponseInterface|string
* @noinspection PhpUnused
*/
public function getCustomerDisplay(): ResponseInterface|string
{
if (($this->config['customer_display_enabled'] ?? false) != 1) {
return $this->response->setStatusCode(404)->setBody('');
}
if ($this->session->get('sale_id') == '') {
$this->session->set('sale_id', NEW_ENTRY);
}
$cashRounding = $this->sale_lib->reset_cash_rounding();
$companyLines = preg_split("/\r\n|\r|\n/", (string) ($this->config['company'] ?? '')) ?: [];
$companyName = array_shift($companyLines) ?? '';
$companyDetails = trim(implode("\n", $companyLines));
$cartColspan = 5;
$cartItemWidth = 45;
$cartPriceWidth = 15;
$cartQuantityWidth = 15;
$cartDiscountWidth = 10;
$cartTotalWidth = 15;
$data = [
'cash_rounding' => $cashRounding,
'cart' => $this->sale_lib->get_cart()
];
$customer_info = $this->_load_customer_data($this->sale_lib->get_customer(), $data, true);
$data += [
'customer_name' => $data['customer'] ?? lang('Sales.walk_in_customer'),
'customer_reward_points' => (int) ($data['customer_rewards']['points'] ?? 0),
'customer_reward_package' => $data['customer_rewards']['package_name'] ?? '',
'giftcard_remainder' => $this->sale_lib->get_giftcard_remainder(),
'rewards_remainder' => $this->sale_lib->get_rewards_remainder(),
'customerName' => $data['customer'] ?? lang('Sales.walk_in_customer'),
'customerRewardPoints' => (int) ($data['customer_rewards']['points'] ?? 0),
'giftcardRemainder' => $this->sale_lib->get_giftcard_remainder()
];
$tax_details = $this->tax_lib->get_taxes($data['cart']);
$data += [
'tax_exclusive_subtotal' => $this->sale_lib->get_subtotal(true, true),
'taxes' => $tax_details[0],
'discount' => $this->sale_lib->get_discount(),
'payments' => $this->sale_lib->get_payments()
];
$totals = $this->sale_lib->get_totals($tax_details[0]);
$data += [
'item_count' => $totals['item_count'],
'total_units' => $totals['total_units'],
'subtotal' => $totals['subtotal'],
'total' => $totals['total'],
'payments_total' => $totals['payment_total'],
'payments_cover_total' => $totals['payments_cover_total'],
'prediscount_subtotal' => $totals['prediscount_subtotal'],
'cash_total' => $totals['cash_total'],
'non_cash_total' => $totals['total'],
'cash_amount_due' => $totals['cash_amount_due'],
'non_cash_amount_due' => $totals['amount_due'],
'cash_mode' => $this->session->get('cash_mode'),
'selected_payment_type' => $this->sale_lib->get_payment_type(),
'comment' => $this->sale_lib->get_comment(),
'email_receipt' => $this->sale_lib->is_email_receipt(),
'config' => $this->config,
'mode' => $this->sale_lib->get_mode(),
'companyName' => $companyName,
'companyDetails' => $companyDetails,
'cartColspan' => $cartColspan,
'cartItemWidth' => $cartItemWidth,
'cartPriceWidth' => $cartPriceWidth,
'cartQuantityWidth' => $cartQuantityWidth,
'cartDiscountWidth' => $cartDiscountWidth,
'cartTotalWidth' => $cartTotalWidth,
'items_module_allowed' => $this->employee->has_grant('items', $this->employee->get_logged_in_employee_info()->person_id),
'change_price' => $this->employee->has_grant('sales_change_price', $this->employee->get_logged_in_employee_info()->person_id)
];
$invoice_number = $this->sale_lib->get_invoice_number();
if ($invoice_number == null || $invoice_number == '') {
$invoice_number = $this->token_lib->render($this->config['sales_invoice_format'], [], false);
}
$data += [
'invoice_number' => $invoice_number,
'print_after_sale' => $this->sale_lib->is_print_after_sale(),
'price_work_orders' => $this->sale_lib->is_price_work_orders(),
'pos_mode' => $data['mode'] == 'sale' || $data['mode'] == 'return',
'quote_number' => $this->sale_lib->get_quote_number(),
'work_order_number' => $this->sale_lib->get_work_order_number(),
'amount_due' => $data['cash_mode'] && ($data['selected_payment_type'] === lang('Sales.cash') || $data['payments_total'] > 0) ? $totals['cash_amount_due'] : $totals['amount_due']
];
$data['amount_change'] = $data['amount_due'] * -1;
$data['payment_change_due'] = ((float) $data['amount_due'] < 0)
? abs((float) $data['amount_due'])
: max(((float) $data['payments_total']) - ((float) $data['amount_due']), 0);
$data['paymentChangeDue'] = $data['payment_change_due'];
return view('sales/customer_display', $data);
}
/**
* Load the sale edit modal. Used in app/Views/sales/register.php.
*
* @return ResponseInterface|string
* @noinspection PhpUnused
*/
public function getManage(): ResponseInterface|string
{
$personId = $this->session->get('person_id');
if (!$this->employee->has_grant('reports_sales', $personId)) {
return redirect()->to('no_access/sales/reports_sales');
} else {
$data['table_headers'] = get_sales_manage_table_headers();
$data['filters'] = [
'only_cash' => lang('Sales.cash_filter'),
'only_due' => lang('Sales.due_filter'),
'only_check' => lang('Sales.check_filter'),
'only_creditcard' => lang('Sales.credit_filter'),
'only_debit' => lang('Sales.debit'),
'only_invoices' => lang('Sales.invoice_filter'),
'selected_customer' => lang('Sales.selected_customer')
];
if ($this->sale_lib->get_customer() != -1) {
$selectedFilters = ['selected_customer'];
$data['customer_selected'] = true;
} else {
$data['customer_selected'] = false;
$selectedFilters = [];
}
// Restore filters from URL query string
$filters = restoreTableFilters($this->request);
if (!empty($filters['selected_filters'])) {
$selectedFilters = array_merge($selectedFilters, $filters['selected_filters']);
}
if (isset($filters['start_date'])) {
$data['start_date'] = $filters['start_date'];
}
if (isset($filters['end_date'])) {
$data['end_date'] = $filters['end_date'];
}
$data['selected_filters'] = $selectedFilters;
return view('sales/manage', $data);
}
}
/**
* @param int $row_id
* @return ResponseInterface
*/
public function getRow(int $row_id): ResponseInterface
{
$sale_info = $this->sale->get_info($row_id)->getRow();
$data_row = get_sale_data_row($sale_info);
return $this->response->setJSON($data_row);
}
/**
* @return void
*/
public function getSearch(): ResponseInterface
{
$search = $this->request->getGet('search', FILTER_SANITIZE_FULL_SPECIAL_CHARS);
$limit = $this->request->getGet('limit', FILTER_SANITIZE_NUMBER_INT);
$offset = $this->request->getGet('offset', FILTER_SANITIZE_NUMBER_INT);
$sort = $this->sanitizeSortColumn(sales_headers(), $this->request->getGet('sort', FILTER_SANITIZE_FULL_SPECIAL_CHARS), 'sale_id');
$order = $this->request->getGet('order', FILTER_SANITIZE_FULL_SPECIAL_CHARS);
$filters = [
'sale_type' => 'all',
'location_id' => 'all',
'start_date' => $this->request->getGet('start_date', FILTER_SANITIZE_FULL_SPECIAL_CHARS),
'end_date' => $this->request->getGet('end_date', FILTER_SANITIZE_FULL_SPECIAL_CHARS),
'only_cash' => false,
'only_due' => false,
'only_check' => false,
'selected_customer' => false,
'only_creditcard' => false,
'only_debit' => false,
'only_invoices' => $this->config['invoice_enable'] && $this->request->getGet('only_invoices', FILTER_SANITIZE_NUMBER_INT),
'is_valid_receipt' => $this->sale->is_valid_receipt($search)
];
// Check if any filter is set in the multiselect dropdown
$request_filters = array_fill_keys($this->request->getGet('filters', FILTER_SANITIZE_FULL_SPECIAL_CHARS) ?? [], true);
$filters = array_merge($filters, $request_filters);
$sales = $this->sale->search($search, $filters, $limit, $offset, $sort, $order);
$total_rows = $this->sale->get_found_rows($search, $filters);
$payments = $this->sale->get_payments_summary($search, $filters);
$payment_summary = get_sales_manage_payments_summary($payments);
$data_rows = [];
foreach ($sales->getResult() as $sale) {
$data_rows[] = get_sale_data_row($sale);
}
if ($total_rows > 0) {
$data_rows[] = get_sale_data_last_row($sales);
}
return $this->response->setJSON(['total' => $total_rows, 'rows' => $data_rows, 'payment_summary' => $payment_summary]);
}
/**
* Gets search suggestions for an item or item kit. Used in app/Views/sales/register.php.
*
* @return ResponseInterface
* @noinspection PhpUnused
*/
public function getItemSearch(): ResponseInterface
{
$suggestions = [];
$receipt = $search = $this->request->getGet('term') != ''
? $this->request->getGet('term')
: null;
if ($this->sale_lib->get_mode() == 'return' && $this->sale->is_valid_receipt($receipt)) {
// If a valid receipt or invoice was found the search term will be replaced with a receipt number (POS #)
$suggestions[] = $receipt;
}
$suggestions = array_merge($suggestions, $this->item->get_search_suggestions($search, ['search_custom' => false, 'is_deleted' => false], true));
$suggestions = array_merge($suggestions, $this->item_kit->get_search_suggestions($search));
return $this->response->setJSON($suggestions);
}
/**
* @return ResponseInterface
*/
public function suggest_search(): ResponseInterface
{
$search = $this->request->getPost('term') != ''
? $this->request->getPost('term')
: null;
$suggestions = $this->sale->get_search_suggestions($search);
return $this->response->setJSON($suggestions);
}
/**
* Set a given customer. Used in app/Views/sales/register.php.
*
* @return ResponseInterface|string
* @noinspection PhpUnused
*/
public function postSelectCustomer(): ResponseInterface|string
{
$customer_id = (int)$this->request->getPost('customer', FILTER_SANITIZE_NUMBER_INT);
if ($this->customer->exists($customer_id)) {
$this->sale_lib->set_customer($customer_id);
$discount = $this->customer->get_info($customer_id)->discount;
$discount_type = $this->customer->get_info($customer_id)->discount_type;
// Apply customer default discount to items that have 0 discount
if ($discount != '') {
$this->sale_lib->apply_customer_discount($discount, $discount_type);
}
}
return $this->_reload();
}
/**
* Changes the sale mode in the register to carry out different types of sales
*
* @return ResponseInterface|string
* @noinspection PhpUnused
*/
public function postChangeMode(): ResponseInterface|string
{
$mode = $this->request->getPost('mode', FILTER_SANITIZE_FULL_SPECIAL_CHARS);
$this->sale_lib->set_mode($mode);
if ($mode == 'sale') {
$this->sale_lib->set_sale_type(SALE_TYPE_POS);
} elseif ($mode == 'sale_quote') {
$this->sale_lib->set_sale_type(SALE_TYPE_QUOTE);
} elseif ($mode == 'sale_work_order') {
$this->sale_lib->set_sale_type(SALE_TYPE_WORK_ORDER);
} elseif ($mode == 'sale_invoice') {
$this->sale_lib->set_sale_type(SALE_TYPE_INVOICE);
} else {
$this->sale_lib->set_sale_type(SALE_TYPE_RETURN);
}
if ($this->config['dinner_table_enable']) {
$occupied_dinner_table = $this->request->getPost('dinner_table', FILTER_SANITIZE_NUMBER_INT);
$released_dinner_table = $this->sale_lib->get_dinner_table();
$occupied = $this->dinner_table->is_occupied($released_dinner_table);
if ($occupied && ($occupied_dinner_table != $released_dinner_table)) {
$this->dinner_table->swap_tables($released_dinner_table, $occupied_dinner_table);
}
$this->sale_lib->set_dinner_table($occupied_dinner_table);
}
$stock_location = $this->request->getPost('stock_location', FILTER_SANITIZE_NUMBER_INT);
if (!$stock_location || $stock_location == $this->sale_lib->get_sale_location()) {
// TODO: The code below was removed in 2017 by @steveireland. We either need to reinstate some of it or remove this entire if block but we can't leave an empty if block
// $dinner_table = $this->request->getPost('dinner_table');
// $this->sale_lib->set_dinner_table($dinner_table);
} elseif ($this->stock_location->is_allowed_location($stock_location, 'sales')) {
$this->sale_lib->set_sale_location($stock_location);
}
$this->sale_lib->empty_payments();
return $this->_reload();
}
/**
* @param int $sale_type
* @return ResponseInterface|string
*/
public function change_register_mode(int $sale_type): ResponseInterface|string
{
$mode = match ($sale_type) {
SALE_TYPE_QUOTE => 'sale_quote',
SALE_TYPE_WORK_ORDER => 'sale_work_order',
SALE_TYPE_INVOICE => 'sale_invoice',
SALE_TYPE_RETURN => 'return',
default => 'sale' // SALE_TYPE_POS
};
$this->sale_lib->set_mode($mode);
return $this->_reload();
}
/**
* Sets the sales comment. Used in app/Views/sales/register.php
*
* @return ResponseInterface
* @noinspection PhpUnused
*/
public function postSetComment(): ResponseInterface
{
$this->sale_lib->set_comment($this->request->getPost('comment', FILTER_SANITIZE_FULL_SPECIAL_CHARS));
return $this->response->setJSON(['success' => true]);
}
/**
* Sets the invoice number. Used in app/Views/sales/register.php
*
* @return ResponseInterface
* @noinspection PhpUnused
*/
public function postSetInvoiceNumber(): ResponseInterface|string
{
$this->sale_lib->set_invoice_number($this->request->getPost('sales_invoice_number', FILTER_SANITIZE_NUMBER_INT));
return $this->response->setJSON(['success' => true]);
}
/**
* @return ResponseInterface
*/
public function postSetPaymentType(): ResponseInterface|string // TODO: This function does not appear to be called anywhere in the code.
{
$this->sale_lib->set_payment_type($this->request->getPost('selected_payment_type', FILTER_SANITIZE_FULL_SPECIAL_CHARS));
return $this->_reload(); // TODO: Hungarian notation.
}
/**
* Sets PrintAfterSale flag. Used in app/Views/sales/register.php
*
* @return ResponseInterface|string
* @noinspection PhpUnused
*/
public function postSetPrintAfterSale(): ResponseInterface
{
$this->sale_lib->set_print_after_sale($this->request->getPost('sales_print_after_sale') != 'false');
return $this->response->setJSON(['success' => true]);
}
/**
* Sets the flag to include prices in the work order. Used in app/Views/sales/register.php
*
* @return ResponseInterface
* @noinspection PhpUnused
*/
public function postSetPriceWorkOrders(): ResponseInterface
{
$price_work_orders = parse_decimals($this->request->getPost('price_work_orders'));
$this->sale_lib->set_price_work_orders($price_work_orders);
return $this->response->setJSON(['success' => true]);
}
/**
* Sets the flag to email receipt to the customer. Used in app/Views/sales/register.php
*
* @return ResponseInterface
* @noinspection PhpUnused
*/
public function postSetEmailReceipt(): ResponseInterface
{
$this->sale_lib->set_email_receipt($this->request->getPost('email_receipt', FILTER_SANITIZE_FULL_SPECIAL_CHARS));
return $this->response->setJSON(['success' => true]);
}
/**
* Add a payment to the sale. Used in app/Views/sales/register.php
*
* @return ResponseInterface|string
* @noinspection PhpUnused
*/
public function postAddPayment(): ResponseInterface|string
{
$data = [];
$giftcard = model(Giftcard::class);
$payment_type = $this->request->getPost('payment_type', FILTER_SANITIZE_FULL_SPECIAL_CHARS);
if ($payment_type !== lang('Sales.giftcard')) {
$rules = ['amount_tendered' => 'trim|required|decimal_locale',];
$messages = ['amount_tendered' => lang('Sales.must_enter_numeric')];
} else {
$rules = ['amount_tendered' => 'trim|required',];
$messages = ['amount_tendered' => lang('Sales.must_enter_numeric_giftcard')];
}
if (!$this->validate($rules, $messages)) {
$data['error'] = $payment_type === lang('Sales.giftcard')
? lang('Sales.must_enter_numeric_giftcard')
: lang('Sales.must_enter_numeric');
} else {
if ($payment_type === lang('Sales.giftcard')) {
// In the case of giftcard payment the register input amount_tendered becomes the giftcard number
$amount_tendered = parse_decimals($this->request->getPost('amount_tendered'));
$giftcard_num = $amount_tendered;
$payments = $this->sale_lib->get_payments();
$payment_type = $payment_type . ':' . $giftcard_num;
$current_payments_with_giftcard = isset($payments[$payment_type]) ? $payments[$payment_type]['payment_amount'] : 0;
$cur_giftcard_value = $giftcard->get_giftcard_value($giftcard_num);
$cur_giftcard_customer = $giftcard->get_giftcard_customer($giftcard_num);
$customer_id = $this->sale_lib->get_customer();
if (isset($cur_giftcard_customer) && $cur_giftcard_customer != $customer_id && $cur_giftcard_customer != null) {
$data['error'] = lang('Giftcards.cannot_use', [$giftcard_num]);
} elseif (($cur_giftcard_value - $current_payments_with_giftcard) <= 0 && $this->sale_lib->get_mode() === 'sale') {
$data['error'] = lang('Giftcards.remaining_balance', [$giftcard_num, $cur_giftcard_value]);
} else {
$new_giftcard_value = $giftcard->get_giftcard_value($giftcard_num) - $this->sale_lib->get_amount_due();
$new_giftcard_value = max($new_giftcard_value, 0);
$this->sale_lib->set_giftcard_remainder($new_giftcard_value);
$new_giftcard_value = to_currency($new_giftcard_value);
$data['warning'] = lang('Giftcards.remaining_balance', [$giftcard_num, $new_giftcard_value]);
$amount_tendered = min($this->sale_lib->get_amount_due(), $giftcard->get_giftcard_value($giftcard_num));
$this->sale_lib->add_payment($payment_type, $amount_tendered);
}
} elseif ($payment_type === lang('Sales.rewards')) {
$customer_id = $this->sale_lib->get_customer();
$package_id = $this->customer->get_info($customer_id)->package_id;
if (!empty($package_id)) {
$points = $this->customer->get_info($customer_id)->points;
$points = ($points == null ? 0 : $points);
$payments = $this->sale_lib->get_payments();
$current_payments_with_rewards = isset($payments[$payment_type]) ? $payments[$payment_type]['payment_amount'] : 0;
$cur_rewards_value = $points;
if (($cur_rewards_value - $current_payments_with_rewards) <= 0) {
$data['error'] = lang('Sales.rewards_remaining_balance') . to_currency($cur_rewards_value);
} else {
$new_reward_value = $points - $this->sale_lib->get_amount_due();
$new_reward_value = max($new_reward_value, 0);
$this->sale_lib->set_rewards_remainder($new_reward_value);
$new_reward_value = str_replace('$', '\$', to_currency($new_reward_value));
$data['warning'] = lang('Sales.rewards_remaining_balance') . $new_reward_value;
$amount_tendered = min($this->sale_lib->get_amount_due(), $points);
$this->sale_lib->add_payment($payment_type, $amount_tendered);
}
}
} elseif ($payment_type === lang('Sales.cash')) {
$amount_due = $this->sale_lib->get_total();
$sales_total = $this->sale_lib->get_total(false);
$amount_tendered = parse_decimals($this->request->getPost('amount_tendered'));
$this->sale_lib->add_payment($payment_type, $amount_tendered);
$cash_adjustment_amount = $amount_due - $sales_total;
if ($cash_adjustment_amount <> 0) {
$this->session->set('cash_mode', CASH_MODE_TRUE);
$this->sale_lib->add_payment(lang('Sales.cash_adjustment'), $cash_adjustment_amount, CASH_ADJUSTMENT_TRUE);
}
} else {
$amount_tendered = parse_decimals($this->request->getPost('amount_tendered'));
$this->sale_lib->add_payment($payment_type, $amount_tendered);
}
}
return $this->_reload($data);
}
/**
* Multiple Payments. Used in app/Views/sales/register.php
*
* @param string $payment_id
* @return ResponseInterface
* @noinspection PhpUnused
*/
public function getDeletePayment(string $payment_id): ResponseInterface|string
{
helper('url');
$this->sale_lib->delete_payment(base64url_decode($payment_id));
return $this->_reload();
}
/**
* Add an item to the sale. Used in app/Views/sales/register.php
*
* @return ResponseInterface
* @noinspection PhpUnused
*/
public function postAdd(): ResponseInterface|string
{
$data = [];
$discount = $this->config['default_sales_discount'];
$discount_type = $this->config['default_sales_discount_type'];
// Check if any discount is assigned to the selected customer
$customer_id = $this->sale_lib->get_customer();
if ($customer_id != NEW_ENTRY) {
// Load the customer discount if any
$customer_discount = $this->customer->get_info($customer_id)->discount;
$customer_discount_type = $this->customer->get_info($customer_id)->discount_type;
if ($customer_discount != '') {
$discount = $customer_discount;
$discount_type = $customer_discount_type;
}
}
$item_id_or_number_or_item_kit_or_receipt = $this->request->getPost('item', FILTER_SANITIZE_FULL_SPECIAL_CHARS);
$this->token_lib->parse_barcode($quantity, $price, $item_id_or_number_or_item_kit_or_receipt);
$mode = $this->sale_lib->get_mode();
$quantity = ($mode == 'return') ? -$quantity : $quantity;
$item_location = $this->sale_lib->get_sale_location();
if ($mode == 'return' && $this->sale->is_valid_receipt($item_id_or_number_or_item_kit_or_receipt)) {
$this->sale_lib->return_entire_sale($item_id_or_number_or_item_kit_or_receipt);
} elseif ($this->item_kit->is_valid_item_kit($item_id_or_number_or_item_kit_or_receipt)) {
// Add kit item to order if one is assigned
$pieces = explode(' ', $item_id_or_number_or_item_kit_or_receipt);
$item_kit_id = (count($pieces) > 1) ? $pieces[1] : $item_id_or_number_or_item_kit_or_receipt;
$item_kit_info = $this->item_kit->get_info($item_kit_id);
$kit_item_id = $item_kit_info->kit_item_id;
$kit_price_option = $item_kit_info->price_option;
$kit_print_option = $item_kit_info->print_option; // 0-all, 1-priced, 2-kit-only
if ($discount_type == $item_kit_info->kit_discount_type) {
if ($item_kit_info->kit_discount > $discount) {
$discount = $item_kit_info->kit_discount;
}
} else {
$discount = $item_kit_info->kit_discount;
$discount_type = $item_kit_info->kit_discount_type;
}
$print_option = PRINT_ALL; // Always include in list of items on invoice // TODO: This variable is never used in the code
if (!empty($kit_item_id)) {
if (!$this->sale_lib->add_item($kit_item_id, $item_location, $quantity, $discount, $discount_type, PRICE_MODE_KIT, $kit_price_option, $kit_print_option, $price)) {
$data['error'] = lang('Sales.unable_to_add_item');
} else {
$data['warning'] = $this->sale_lib->out_of_stock($item_kit_id, $item_location);
}
}
// Add item kit items to order
$stock_warning = null;
if (!$this->sale_lib->add_item_kit($item_id_or_number_or_item_kit_or_receipt, $item_location, $discount, $discount_type, $kit_price_option, $kit_print_option, $stock_warning)) {
$data['error'] = lang('Sales.unable_to_add_item');
} elseif ($stock_warning != null) {
$data['warning'] = $stock_warning;
}
} else {
if ($item_id_or_number_or_item_kit_or_receipt == '' || !$this->sale_lib->add_item($item_id_or_number_or_item_kit_or_receipt, $item_location, $quantity, $discount, $discount_type, PRICE_MODE_STANDARD, null, null, $price)) {
$data['error'] = lang('Sales.unable_to_add_item');
} else {
$data['warning'] = $this->sale_lib->out_of_stock($item_id_or_number_or_item_kit_or_receipt, $item_location);
}
}
return $this->_reload($data);
}
/**
* Edit an item in the sale. Used in app/Views/sales/register.php
*
* @param string $line
* @return ResponseInterface|string
* @noinspection PhpUnused
*/
public function postEditItem(string $line): ResponseInterface|string
{
$data = [];
$rules = [
'price' => 'trim|required|decimal_locale|nonNegativeDecimal',
'quantity' => 'trim|required|decimal_locale',
'discount' => 'trim|permit_empty|decimal_locale|nonNegativeDecimal',
];
$messages = [
'price' => [
'nonNegativeDecimal' => lang('Sales.negative_price_invalid'),
],
'discount' => [
'nonNegativeDecimal' => lang('Sales.negative_discount_invalid'),
],
];
if ($this->validate($rules, $messages)) {
$description = $this->request->getPost('description', FILTER_SANITIZE_FULL_SPECIAL_CHARS);
$serialnumber = $this->request->getPost('serialnumber', FILTER_SANITIZE_FULL_SPECIAL_CHARS);
$price = parse_decimals($this->request->getPost('price'));
$quantity = parse_decimals($this->request->getPost('quantity'));
$discount_type = $this->request->getPost('discount_type', FILTER_SANITIZE_FULL_SPECIAL_CHARS);
$discount = $discount_type
? parse_quantity($this->request->getPost('discount'))
: parse_decimals($this->request->getPost('discount'));
$discount = $discount ?: 0;
// Return mode legitimately uses negative quantities for refunds
if ($this->sale_lib->get_mode() != 'return' && $quantity < 0) {
$data['error'] = lang('Sales.negative_quantity_invalid');
return $this->_reload($data);
}
// Business logic: discount bounds depend on discount_type and item values
if ($discount_type == PERCENT && $discount > 100) {
$data['error'] = lang('Sales.discount_percent_exceeds_100');
return $this->_reload($data);
}
if ($discount_type == FIXED && bccomp((string)$discount, bcmul((string)abs($quantity), (string)$price, 2), 2) > 0) {
$data['error'] = lang('Sales.discount_exceeds_item_total');
return $this->_reload($data);
}
$item_location = $this->request->getPost('location', FILTER_SANITIZE_NUMBER_INT);
$discounted_total = $this->request->getPost('discounted_total') != ''
? parse_decimals($this->request->getPost('discounted_total') ?? '')
: null;
$this->sale_lib->edit_item($line, $description, $serialnumber, $quantity, $discount, $discount_type, $price, $discounted_total);
$this->sale_lib->empty_payments();
$data['warning'] = $this->sale_lib->out_of_stock($this->sale_lib->get_item_id($line), $item_location);
} else {
$errors = $this->validator->getErrors();
$data['error'] = $errors ? reset($errors) : lang('Sales.error_editing_item');
}
return $this->_reload($data);
}
/**
* Deletes an item specified in the parameter from the shopping cart. Used in app/Views/sales/register.php
*
* @param int $item_id
* @return ResponseInterface
* @throws ReflectionException
* @noinspection PhpUnused
*/
public function postDeleteItem(int $item_id): ResponseInterface|string
{
$this->sale_lib->delete_item($item_id);
$this->sale_lib->empty_payments();
return $this->_reload();
}
/**
* Remove the current customer from the sale. Used in app/Views/sales/register.php
*
* @return ResponseInterface
* @noinspection PhpUnused
*/
public function getRemoveCustomer(): ResponseInterface|string
{
$this->sale_lib->clear_giftcard_remainder();
$this->sale_lib->clear_rewards_remainder();
$this->sale_lib->delete_payment(lang('Sales.rewards'));
$this->sale_lib->clear_invoice_number();
$this->sale_lib->clear_quote_number();
$this->sale_lib->remove_customer();
return $this->_reload();
}
/**
* Complete and finalize a sale. Used in app/Views/sales/register.php
*
* @return string
* @throws ReflectionException
* @noinspection PhpUnused
*/
public function postComplete(): string // TODO: this function is huge. Probably should be refactored.
{
$sale_id = $this->sale_lib->get_sale_id();
$data = [];
$data['dinner_table'] = $this->sale_lib->get_dinner_table();
$data['cart'] = $this->sale_lib->get_cart();
$data['include_hsn'] = (bool)$this->config['include_hsn'];
$__time = time();
$data['transaction_time'] = to_datetime($__time);
$data['transaction_date'] = to_date($__time);
$data['show_stock_locations'] = $this->stock_location->show_locations('sales');
$data['comments'] = $this->sale_lib->get_comment();
$employee_id = $this->employee->get_logged_in_employee_info()->person_id;
$employee_info = $this->employee->get_info($employee_id);
$data['employee'] = $employee_info->first_name . ' ' . mb_substr($employee_info->last_name, 0, 1);
$data['company_info'] = implode("\n", [$this->config['address'], $this->config['phone']]);
if ($this->config['account_number']) {
$data['company_info'] .= "\n" . lang('Sales.account_number') . ": " . $this->config['account_number'];
}
if ($this->config['tax_id'] != '') {
$data['company_info'] .= "\n" . lang('Sales.tax_id') . ": " . $this->config['tax_id'];
}
$data['invoice_number_enabled'] = $this->sale_lib->is_invoice_mode();
$data['cur_giftcard_value'] = $this->sale_lib->get_giftcard_remainder();
$data['cur_rewards_value'] = $this->sale_lib->get_rewards_remainder();
$data['print_after_sale'] = $this->session->get('sales_print_after_sale');
$data['price_work_orders'] = $this->sale_lib->is_price_work_orders();
$data['email_receipt'] = $this->sale_lib->is_email_receipt();
$customer_id = $this->sale_lib->get_customer();
$invoice_number = $this->sale_lib->get_invoice_number();
$data["invoice_number"] = $invoice_number;
$work_order_number = $this->sale_lib->get_work_order_number();
$data["work_order_number"] = $work_order_number;
$quote_number = $this->sale_lib->get_quote_number();
$data["quote_number"] = $quote_number;
$customer_info = $this->_load_customer_data($customer_id, $data);
if ($customer_info != null) {
$data["customer_comments"] = $customer_info->comments;
$data['tax_id'] = $customer_info->tax_id;
}
$tax_details = $this->tax_lib->get_taxes($data['cart']); // TODO: Duplicated code
$data['taxes'] = $tax_details[0];
$data['discount'] = $this->sale_lib->get_discount();
$data['payments'] = $this->sale_lib->get_payments();
// Returns 'subtotal', 'total', 'cash_total', 'payment_total', 'amount_due', 'cash_amount_due', 'payments_cover_total'
$totals = $this->sale_lib->get_totals($tax_details[0]);
$data['subtotal'] = $totals['subtotal'];
$data['total'] = $totals['total'];
$data['payments_total'] = $totals['payment_total'];
$data['payments_cover_total'] = $totals['payments_cover_total'];
$data['cash_rounding'] = $this->session->get('cash_rounding');
$data['cash_mode'] = $this->session->get('cash_mode'); // TODO: Duplicated code
$data['prediscount_subtotal'] = $totals['prediscount_subtotal'];
$data['cash_total'] = $totals['cash_total'];
$data['non_cash_total'] = $totals['total'];
$data['cash_amount_due'] = $totals['cash_amount_due'];
$data['non_cash_amount_due'] = $totals['amount_due'];
// Prevent negative total sales (fraud/theft vector) - returns can have negative totals for legitimate refunds
if ($this->sale_lib->get_mode() != 'return' && bccomp($totals['total'], '0') < 0) {
$data['error'] = lang('Sales.negative_total_invalid');
return $this->_reload($data);
}
if ($data['cash_mode']) { // TODO: Convert this to ternary notation
$data['amount_due'] = $totals['cash_amount_due'];
} else {
$data['amount_due'] = $totals['amount_due'];
}
$data['amount_change'] = $data['amount_due'] * -1;
if ($data['amount_change'] > 0) {
// Save cash refund to the cash payment transaction if found, if not then add as new Cash transaction
if (array_key_exists(lang('Sales.cash'), $data['payments'])) {
$data['payments'][lang('Sales.cash')]['cash_refund'] = $data['amount_change'];
} else {
$payment = [
lang('Sales.cash') => [
'payment_type' => lang('Sales.cash'),
'payment_amount' => 0,
'cash_refund' => $data['amount_change']
]
];
$data['payments'] += $payment;
}
}
$data['print_price_info'] = true;
if ($this->sale_lib->is_invoice_mode()) {
$invoice_format = $this->config['sales_invoice_format'];
// Generate final invoice number (if using the invoice in sales by receipt mode then the invoice number can be manually entered or altered in some way
if (!empty($invoice_format) && $invoice_number == null) {
// The user can retain the default encoded format or can manually override it. It still passes through the rendering step.
$invoice_number = $this->token_lib->render($invoice_format);
}
if ($sale_id == NEW_ENTRY && $this->sale->check_invoice_number_exists($invoice_number)) {
$data['error'] = lang('Sales.invoice_number_duplicate', [$invoice_number]);
return $this->_reload($data);
} else {
$data['invoice_number'] = $invoice_number;
$data['sale_status'] = COMPLETED;
$sale_type = SALE_TYPE_INVOICE;
$invoice_type = $this->config['invoice_type'];
if (!Sale_lib::isValidInvoiceType($invoice_type)) {
$invoice_type = 'invoice';
}
$invoice_view = $invoice_type;
// Save the data to the sales table
$data['sale_id_num'] = $this->sale->save_value($sale_id, $data['sale_status'], $data['cart'], $customer_id, $employee_id, $data['comments'], $invoice_number, $work_order_number, $quote_number, $sale_type, $data['payments'], $data['dinner_table'], $tax_details);
$data['sale_id'] = 'POS ' . $data['sale_id_num'];
// Resort and filter cart lines for printing
$data['cart'] = $this->sale_lib->sort_and_filter_cart($data['cart']);
if ($data['sale_id_num'] == NEW_ENTRY) {
$data['error_message'] = lang('Sales.transaction_failed');
return $this->_reload($data);
} else {
$data['barcode'] = $this->barcode_lib->generate_receipt_barcode($data['sale_id']);
$this->sale_lib->clear_all();
return view('sales/' . $invoice_view, $data);
}
}
} elseif ($this->sale_lib->is_work_order_mode()) {
if (!($data['price_work_orders'] == 1)) {
$data['print_price_info'] = false;
}
$data['sales_work_order'] = lang('Sales.work_order');
$data['work_order_number_label'] = lang('Sales.work_order_number');
if ($work_order_number == null) {
// Generate work order number
$work_order_format = $this->config['work_order_format'];
$work_order_number = $this->token_lib->render($work_order_format);
}
if ($sale_id == NEW_ENTRY && $this->sale->check_work_order_number_exists($work_order_number)) {
$data['error'] = lang('Sales.work_order_number_duplicate');
return $this->_reload($data);
} else {
$data['work_order_number'] = $work_order_number;
$data['sale_status'] = SUSPENDED;
$sale_type = SALE_TYPE_WORK_ORDER;
$data['sale_id_num'] = $this->sale->save_value($sale_id, $data['sale_status'], $data['cart'], $customer_id, $employee_id, $data['comments'], $invoice_number, $work_order_number, $quote_number, $sale_type, $data['payments'], $data['dinner_table'], $tax_details);
$this->sale_lib->set_suspended_id($data['sale_id_num']);
$data['cart'] = $this->sale_lib->sort_and_filter_cart($data['cart']);
$data['barcode'] = null;
$this->sale_lib->clear_all();
return view('sales/work_order', $data);
}
} elseif ($this->sale_lib->is_quote_mode()) {
$data['sales_quote'] = lang('Sales.quote');
$data['quote_number_label'] = lang('Sales.quote_number');
if ($quote_number == null) {
// Generate quote number
$quote_format = $this->config['sales_quote_format'];
$quote_number = $this->token_lib->render($quote_format);
}
if ($sale_id == NEW_ENTRY && $this->sale->check_quote_number_exists($quote_number)) {
$data['error'] = lang('Sales.quote_number_duplicate');
return $this->_reload($data);
} else {
$data['quote_number'] = $quote_number;
$data['sale_status'] = SUSPENDED;
$sale_type = SALE_TYPE_QUOTE;
$data['sale_id_num'] = $this->sale->save_value($sale_id, $data['sale_status'], $data['cart'], $customer_id, $employee_id, $data['comments'], $invoice_number, $work_order_number, $quote_number, $sale_type, $data['payments'], $data['dinner_table'], $tax_details);
$this->sale_lib->set_suspended_id($data['sale_id_num']);
$data['cart'] = $this->sale_lib->sort_and_filter_cart($data['cart']);
$data['barcode'] = null;
$this->sale_lib->clear_all();
return view('sales/quote', $data);
}
} else {
// Save the data to the sales table
$data['sale_status'] = COMPLETED;
if ($this->sale_lib->is_return_mode()) {
$sale_type = SALE_TYPE_RETURN;
} else {
$sale_type = SALE_TYPE_POS;
}
$data['sale_id_num'] = $this->sale->save_value($sale_id, $data['sale_status'], $data['cart'], $customer_id, $employee_id, $data['comments'], $invoice_number, $work_order_number, $quote_number, $sale_type, $data['payments'], $data['dinner_table'], $tax_details);
$data['sale_id'] = 'POS ' . $data['sale_id_num'];