-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJTA_Packages.sql
More file actions
2017 lines (1708 loc) · 74.2 KB
/
Copy pathJTA_Packages.sql
File metadata and controls
2017 lines (1708 loc) · 74.2 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
-- Earl Tilluck
-- This is a package that contains 25 subprograms and supporting constructs for the JTA database.
/*
01
Exception Package
This package keeps our exceptions in on place for reference
and gives us procedures to call, so we can raise an exception
and also log the exception into an error table.
*/
CREATE OR REPLACE PACKAGE jta_error
IS
invalid_input EXCEPTION;
PRAGMA exception_init (invalid_input, -20201);
missing_data EXCEPTION;
PRAGMA exception_init (missing_data, -20202);
-- procedures for quick exception handling
PROCEDURE throw (
p_code IN NUMBER,
p_message IN VARCHAR2
);
PROCEDURE log_error (
p_code IN NUMBER,
p_message IN VARCHAR2
);
PROCEDURE show_in_console (
p_code IN NUMBER := NULL,
p_message IN VARCHAR2
);
END jta_error;
/
-- package body for jta_error
CREATE OR REPLACE PACKAGE BODY jta_error
IS
/*
Throw an exception, this makes coding a little simpler
*/
PROCEDURE throw (
p_code IN NUMBER,
p_message IN VARCHAR2
)
IS
BEGIN
raise_application_error(p_code, p_message);
END;
/*
Log the exception to an error table.
Most procedures will do this when exceptions occur.
For development we will show the error in console as well.
*/
PROCEDURE log_error (
p_code IN NUMBER,
p_message IN VARCHAR2
)
IS
-- autonomous transaction needed, otherwise rollback will remove log entry
PRAGMA autonomous_transaction;
BEGIN
-- show info in console, disable this line in production
dbms_output.put_line('error logged: ' || p_message);
-- log error into error table
INSERT INTO jta_errors (error_id, date_time, user_name, code, message)
VALUES (error_seq.NEXTVAL, sysdate, USER, p_code, p_message);
COMMIT;
END;
/*
Show an error in the console.
Sometimes you don't want to log an error because it is not a
note worthy failure, e.g. it is not a problem if no data was
found for a query.
This procedure is available for testing purposes
*/
PROCEDURE show_in_console (
p_code IN NUMBER := NULL,
p_message IN VARCHAR2
)
IS
BEGIN
dbms_output.put_line('A trivial error occured: ' || p_message);
END;
END jta_error;
/
-- JTA Package Specification
-- This package contains the main constructs for the jta database
CREATE OR REPLACE PACKAGE jta
IS
-- some constants
nat_insurance_rate CONSTANT NUMBER := 0.132;
hlt_surcharge_rate CONSTANT NUMBER := 0.005;
-- public procedures and functions
PROCEDURE process_payroll (
p_date IN DATE
);
PROCEDURE update_inventory (
p_product_id IN cost_sales_tracker.product_id%TYPE,
p_quantity IN NUMBER,
p_new_cost IN cost_sales_tracker.cost_per_unit%TYPE
);
PROCEDURE restock_urgent (
p_staff_id IN staff.staff_id%TYPE
);
FUNCTION get_last_cashier_payout (
p_staff_id staff.staff_id%TYPE
) RETURN cashier_drawer_assignments.cash_amount_end%TYPE;
FUNCTION get_money_inflow (
p_location_id locations.location_id%TYPE,
p_start_date DATE,
p_end_date DATE,
p_type VARCHAR2 := 'cash'
) RETURN cashier_drawer_assignments.cash_amount_start%TYPE;
PROCEDURE update_taxes;
TYPE price_change_record IS RECORD (
product_id products.product_id%TYPE,
product_name products.product_name%TYPE,
date_changed price_history.start_date%TYPE,
old_price price_history.price_rate%TYPE,
new_price price_history.price_rate%TYPE,
direction VARCHAR2(5)
);
TYPE price_changes_table IS TABLE OF price_change_record
INDEX BY BINARY_INTEGER;
FUNCTION get_price_changes (
p_product_id products.product_id%type,
p_start_date DATE,
p_end_date DATE
) RETURN price_changes_table;
PROCEDURE get_profits_for (
p_start_date IN DATE,
p_end_date IN DATE,
p_goods_sold OUT NOCOPY NUMBER,
p_gross_gain OUT NOCOPY NUMBER,
p_costs OUT NOCOPY NUMBER,
p_net_gain OUT NOCOPY NUMBER
);
PROCEDURE get_recommended_price_for (
p_product_id IN products.product_id%TYPE,
p_avg_cost OUT NOCOPY products.price_rate%TYPE,
p_old_price OUT NOCOPY products.price_rate%TYPE,
p_new_price OUT NOCOPY products.price_rate%TYPE
);
PROCEDURE evaluate_po_order_line (
p_line_id IN purchase_order_lines.po_line_id%TYPE,
p_not_enough_to_restock OUT NOCOPY BOOLEAN,
p_not_at_min_level OUT NOCOPY BOOLEAN
);
PROCEDURE lookup_barcode (
p_barcode IN VARCHAR2,
p_product_id OUT NOCOPY products.product_id%TYPE,
p_product_name OUT NOCOPY products.product_name%TYPE,
p_price_rate OUT NOCOPY products.price_rate%TYPE,
p_tax_code OUT NOCOPY tax_rates.tax_code%TYPE,
p_tax_rate OUT NOCOPY tax_rates.tax_rate%TYPE
);
PROCEDURE update_from_bill (
p_bill_id IN customer_bills.bill_id%TYPE
);
PROCEDURE update_sales;
FUNCTION receive_payment (
p_bill_id customer_bills.bill_id%TYPE,
p_type customer_bills.payment_type%TYPE,
p_amount customer_bills.payment_amount%TYPE
) RETURN NUMBER;
PROCEDURE add_item_to_bill (
p_bill_id IN customer_bills.bill_id%TYPE,
p_barcode IN products.barcode%TYPE
);
FUNCTION get_tax_payment_due (
p_tax_code tax_rates.tax_code%TYPE,
p_year DATE
) RETURN NUMBER;
FUNCTION get_quantity_sold (
p_product_id products.product_id%TYPE,
p_location_id locations.location_id%TYPE,
p_date_start DATE,
p_date_end DATE
) RETURN NUMBER;
PROCEDURE stock_check (
p_product_id IN products.product_id%TYPE,
p_location_id IN locations.location_id%TYPE,
p_value_counted INTEGER,
p_in_stock OUT NOCOPY INTEGER
);
PROCEDURE sunday_check (
p_staff_id IN staff.staff_id%TYPE,
p_month IN DATE,
p_sundays OUT NOCOPY INTEGER,
p_available OUT NOCOPY BOOLEAN
);
PROCEDURE payout (
p_staff_id IN staff.staff_id%TYPE,
p_begin_date IN DATE,
p_end_date IN DATE,
p_gross_pay OUT NOCOPY payroll.gross_pay%TYPE,
p_net_pay OUT NOCOPY payroll.net_pay%TYPE,
p_hlt OUT NOCOPY payroll.hlt_surcharge_deduction%TYPE,
p_nat OUT NOCOPY payroll.nat_insurance_deduction%TYPE,
p_deductions OUT NOCOPY payroll.net_pay%TYPE
);
FUNCTION get_name (
p_staff_id staff.staff_id%TYPE
) RETURN VARCHAR2;
-- end specification
END jta;
/
-- JTA Package Body
CREATE OR REPLACE PACKAGE BODY jta IS
/*
02
Private procedure: Get Hours
Given staff_id and time period, retrieve the regular,
overtime and doubletime hours that a staff member has
worked for.
*/
PROCEDURE get_hours (
p_staff_id IN staff.staff_id%TYPE,
start_date IN DATE,
end_date IN DATE,
basic OUT NOCOPY INTEGER,
overtime OUT NOCOPY INTEGER,
doubletime OUT NOCOPY INTEGER
)
IS
BEGIN
basic := 0;
overtime := 0;
doubletime := 0;
SELECT nvl(SUM(hours_worked), 0) INTO doubletime
FROM work_hours
WHERE work_date BETWEEN start_date AND end_date
AND staff_id = p_staff_id
AND to_char(work_date, 'd') = '1';
SELECT nvl(SUM(hours_worked), 0) INTO basic
FROM work_hours
WHERE work_date BETWEEN start_date AND end_date
AND staff_id = p_staff_id
AND to_char(work_date, 'd') != '1';
IF basic > 40 THEN
overtime := basic - 40;
basic := 40;
END IF;
-- excpetions will be handled in called procedure
END;
/*
03
Process payroll
Given any date in a week,
retrieve the hours worked for each relevant employee from the
work_hours table and populate the payroll table with payroll data
for the week.
Payroll Rules:
> First forty hours is regular rate
> Above forty hours is overtime x1.5
> Sunday is double time
Note1: this query only considers basic deductions. In the real world payroll
is far more complex, however we couldn't find enough information and didn't
have the time to learn all Accounting practices for this organization. This
procedure can be modified easily to calculate other automatic deductions as needed.
*/
PROCEDURE process_payroll (
p_date IN DATE
)
IS
-- date range is Sunday to Sat for this day (friday)
v_start_date DATE := TRUNC(p_date, 'DAY');
v_end_date DATE := v_start_date + 6
+ numtodsinterval(23, 'hour')
+ numtodsinterval(59, 'minute')
+ numtodsinterval(59, 'second');
-- gets a list of staff_ids for workers who worked for the week
CURSOR c_staff_worked
IS SELECT DISTINCT staff_id FROM work_hours
WHERE work_date BETWEEN v_start_date AND v_end_date
ORDER BY staff_id;
doubletime payroll.hours_doubletime%TYPE;
overtime payroll.hours_overtime%TYPE;
basic payroll.hours_basic%TYPE;
payrate staff.wage_rate%TYPE;
gross_pay payroll.gross_pay%TYPE;
nat_insurance_deduction payroll.nat_insurance_deduction%TYPE;
hlt_surcharge_deduction payroll.hlt_surcharge_deduction%TYPE;
net_pay payroll.net_pay%TYPE;
v_count INTEGER := 0;
BEGIN
--dbms_output.put_line(to_char(v_start_date, 'yyyy-Mon-dd, HH24:MI:SS'));
--dbms_output.put_line(to_char(v_end_date, 'yyyy-Mon-dd, HH24:MI:SS'));
-- note that the procedure essentially do nothing if there are no work data for this week
-- delete rows from payroll table if they already exist with current dates
DELETE FROM payroll WHERE payroll.start_date = v_start_date AND payroll.end_date = v_end_date;
-- for each staff that worked this week
FOR current_staff IN c_staff_worked LOOP
-- get the hours each staff member worked for
get_hours(current_staff.staff_id, v_start_date, v_end_date, basic, overtime, doubletime);
-- get staff pay rate
SELECT wage_rate INTO payrate FROM staff WHERE staff_id = current_staff.staff_id;
-- calculate and save gross pay
gross_pay := (basic * payrate) + (overtime * payrate * 1.5) + (doubletime * payrate * 2);
-- calculate and save deductions
nat_insurance_deduction := ROUND((gross_pay * nat_insurance_rate) / 3, 2);
hlt_surcharge_deduction := ROUND((gross_pay * hlt_surcharge_rate), 2);
-- calculate and save net pay
net_pay := gross_pay - (nat_insurance_deduction + hlt_surcharge_deduction);
-- insert new row into payroll table
INSERT INTO payroll (
payroll_id, staff_id, start_date, end_date,
hours_basic, hours_overtime, hours_doubletime,
basic_pay_rate, gross_pay,
nat_insurance_deduction, hlt_surcharge_deduction,
net_pay)
VALUES (
payroll_id_seq.NEXTVAL, current_staff.staff_id, v_start_date, v_end_date,
basic, overtime, doubletime,
payrate, gross_pay,
nat_insurance_deduction, hlt_surcharge_deduction,
net_pay);
v_count := v_count + 1;
END LOOP;
IF v_count > 0 THEN
COMMIT; -- commit when done and only when rows modified
ELSE
-- this exception is caught but not logged since it is trivial
jta_error.throw(-20201, 'There was no work hours recorded for this week: '
|| to_char(v_start_date, 'yyyy-Mon-dd, HH24:MI:SS') || ' to '
|| to_char(v_end_date, 'yyyy-Mon-dd, HH24:MI:SS'));
END IF;
EXCEPTION
WHEN jta_error.invalid_input THEN
jta_error.show_in_console(SQLCODE, SQLERRM);
ROLLBACK;
WHEN OTHERS THEN
-- all OTHER exceptions will be logged into error table...
jta_error.log_error(SQLCODE, SQLERRM);
ROLLBACK;
END process_payroll;
/*
04
Update Inventory
Add or remove items from the overall inventory (all lcoations).
This procedure also updates the average cost per unit whenever items are added.
This procedure would be called whenever new items are recieved into the warehouse
and also called for every item at the end of the day to remove items.
The cost_sales_tracker table is slighlty redundant, however it improves speed when
the supermarket needs to quickly check the inventory total for a product as well as
its current avg_cost_price. This is a query that is run very often in the business as
prices change daily for the organization.
p_product_id: the product to update
p_quantity: the quantity to update, negative numbers for removing, positive for adding
p_new_cost: the cost per unit when adding new items, set to null when removing
*/
PROCEDURE update_inventory (
p_product_id IN cost_sales_tracker.product_id%TYPE,
p_quantity IN NUMBER,
p_new_cost IN cost_sales_tracker.cost_per_unit%TYPE
)
IS
v_direction cost_sales_tracker.direction%TYPE := 'OUT';
v_old_total cost_sales_tracker.total%TYPE;
v_new_total cost_sales_tracker.total%TYPE;
v_old_avg cost_sales_tracker.average_cost_per_unit%TYPE;
v_new_avg cost_sales_tracker.average_cost_per_unit%TYPE;
v_test_id products.product_id%TYPE;
v_cost cost_sales_tracker.cost_per_unit%TYPE;
BEGIN
-- if zero quantity, raise error
IF p_quantity = 0 THEN
jta_error.throw(-20201, 'cannot update a zero amount to inventory');
END IF;
-- if not actual product raise error
BEGIN
-- see if product id exists in product table
SELECT product_id INTO v_test_id FROM products WHERE product_id = p_product_id;
EXCEPTION
WHEN no_data_found THEN
jta_error.throw(-20201, 'non existing product being updated to inventory');
WHEN OTHERS THEN
RAISE; -- outer procedure will deal with it
END;
-- get old total from db, if exists
v_old_total := 0;
BEGIN
SELECT total INTO v_old_total
FROM cost_sales_tracker
WHERE product_id = p_product_id
AND transaction_id IN (
SELECT MAX(transaction_id) FROM cost_sales_tracker WHERE product_id = p_product_id);
EXCEPTION
WHEN no_data_found THEN
-- if a previous entry was not made for this product it will remain zero
NULL;
WHEN OTHERS THEN
RAISE;
END;
-- get old average if exists
v_old_avg := 0;
BEGIN
SELECT average_cost_per_unit INTO v_old_avg
FROM cost_sales_tracker
WHERE product_id = p_product_id
AND transaction_id IN (SELECT MAX(transaction_id) FROM cost_sales_tracker
WHERE product_id = p_product_id);
EXCEPTION
WHEN no_data_found THEN
-- if we never added a this product before, the old average is zero
NULL;
WHEN OTHERS THEN
RAISE;
END;
-- update to new total,
IF p_quantity > 0 THEN
-- if adding an item, the cost must be positive, otherwise it is ignored
IF p_new_cost <= 0 OR p_new_cost IS NULL THEN
jta_error.throw(-20201, 'cannot update inventory with non positive cost per unit');
ELSE
v_cost := p_new_cost;
END IF;
-- switch direction
v_direction := 'IN';
-- update new average
v_new_avg := ROUND(((v_old_avg * v_old_total) + (p_quantity * p_new_cost) ) / (v_old_total + p_quantity), 2);
-- calculate new total
v_new_total := v_old_total + p_quantity;
ELSE
-- cost is ignored if removing items,
v_cost := NULL;
-- average also remains the same
-- reduce quantity (its a negative number)
v_new_total := v_old_total + p_quantity;
-- throw error if negative
IF v_new_total < 0 THEN
jta_error.throw(-20201, 'cannot remove more items than already exists in inventory');
END IF;
-- set old average as new average,
-- if old average doesn't exist, the above negative error would have been thrown
v_new_avg := v_old_avg;
END IF;
-- insert data into database
INSERT INTO cost_sales_tracker (
transaction_id, product_id, direction, date_time, quantity,
total, average_cost_per_unit, cost_per_unit
)
VALUES (
transaction_id_seq.NEXTVAL, p_product_id, v_direction, sysdate, p_quantity,
v_new_total, v_new_avg, v_cost
);
COMMIT;
EXCEPTION
WHEN OTHERS THEN
-- all exceptions will be logged into error table...
jta_error.log_error(SQLCODE, SQLERRM);
ROLLBACK;
END update_inventory;
/*
05
Restock Urgent
Find items that need restocking, and automatically create a purchase order for them.
The application can then allow the user to modify the purchase order to suit or delete
it if they want. Items are choosen based on the re-order level stored for each product.
*/
PROCEDURE restock_urgent (
p_staff_id IN staff.staff_id%TYPE
)
IS
-- find products that need to be restocked
-- by checking reorder-level and min_stock_level and quantity
-- for a specific supplier's goods and location
CURSOR urgent(
p_supplier_id suppliers_per_products.supplier_id%TYPE,
p_location_id inventory_by_location.location_id%TYPE
) IS
SELECT inv.product_id, inv.reorder_level
FROM inventory_by_location inv
JOIN products pr ON (inv.product_id = pr.product_id)
JOIN suppliers_per_products sp ON (sp.product_id = pr.product_id)
WHERE inv.reorder_level <= (inv.min_stock_level - inv.quantity)
AND inv.location_id = p_location_id AND sp.supplier_id = p_supplier_id;
-- find distinct list of suppliers whose products need restocking
CURSOR suppliers IS
SELECT DISTINCT supplier_id, location_id
FROM inventory_by_location inv
JOIN products pr ON (inv.product_id = pr.product_id)
JOIN suppliers_per_products sp ON (sp.product_id = pr.product_id)
WHERE inv.reorder_level <= (inv.min_stock_level - inv.quantity);
-- current purchase order being worked on
v_current_po purchase_orders.po_id%TYPE;
BEGIN
-- for all suppliers who need restocking at each inventory location...
FOR supplier IN suppliers LOOP
-- create purchase orders for each supplier
v_current_po := po_id_seq.NEXTVAL;
INSERT INTO purchase_orders (po_id, supplier_id, staff_id, location_id, pending, approved, submitted_date)
VALUES (v_current_po, supplier.supplier_id, p_staff_id, supplier.location_id, 'T', 'F', sysdate);
-- add purchase order lines for this supplier
FOR stock IN urgent(supplier.supplier_id, supplier.location_id) LOOP
INSERT INTO purchase_order_lines (po_line_id, po_id, product_id, quantity, price_rate)
VALUES(po_line_id_seq.NEXTVAL, v_current_po, stock.product_id, stock.reorder_level, NULL );
END LOOP;
END LOOP;
COMMIT;
EXCEPTION
WHEN OTHERS THEN
-- all exceptions will be logged into error table...
jta_error.log_error(SQLCODE, SQLERRM);
ROLLBACK;
END restock_urgent;
/*
06
Get last cashier payout.
This function processes all bills created by a cashier
for his/her last shift. This function would be called
everytime a cashier finishes a shift in order to find out
how much money should be recieved from them.
*/
FUNCTION get_last_cashier_payout (
p_staff_id staff.staff_id%TYPE
)
RETURN cashier_drawer_assignments.cash_amount_end%TYPE
IS
v_assignment_id cashier_drawer_assignments.assignment_id%TYPE;
v_cash_sum cashier_drawer_assignments.cash_amount_end%TYPE := 0;
BEGIN
-- get last cashier assingment (shift)
SELECT MAX(assignment_id) INTO v_assignment_id
FROM cashier_drawer_assignments
WHERE staff_id = p_staff_id;
-- we can sum the bill amounts, however we do something else instead
/*
SELECT SUM(nvl(payment_tender, 0)) INTO v_cash_sum
FROM customer_bills b
WHERE LOWER(payment_type) = 'cash'
AND assignment_id = v_assignment_id;
*/
-- we can get the payout from the assignment table instead,
-- this is because we have now set up the package so that this table
-- is automatically updated when the recieve_payment procedure is called
-- to pay a bill.
SELECT nvl(cash_amount_end, 0) INTO v_cash_sum
FROM cashier_drawer_assignments
WHERE assignment_id = v_assignment_id;
-- return sum
return v_cash_sum;
EXCEPTION
WHEN no_data_found THEN
-- no shift for cashier, no cashier with that id etc...
RETURN 0;
WHEN OTHERS THEN
-- all exceptions will be logged into error table...
jta_error.log_error(SQLCODE, SQLERRM);
-- return null because the function failed
RETURN NULL;
END get_last_cashier_payout;
/*
07
Cash flow query
Find the total cash amount retrieved by cashiers for a certain period
This query is useful in determining how much cash is on hand and when to
arrange with the bank to collect.
Date range can be changed to reflect days, week�s months etc.
The default type value of cash can be changed to non-cash to find out
how much was gained via credit card, linx etc.
*/
FUNCTION get_money_inflow (
p_location_id locations.location_id%TYPE,
p_start_date DATE,
p_end_date DATE,
p_type VARCHAR2 := 'cash'
) RETURN cashier_drawer_assignments.cash_amount_start%TYPE
IS
v_cash_flow cashier_drawer_assignments.cash_amount_start%TYPE;
v_location locations.location_id%TYPE;
BEGIN
BEGIN
SELECT location_id INTO v_location
FROM locations
where location_id = p_location_id;
EXCEPTION
WHEN no_data_found THEN
jta_error.throw(-20201, 'location does not exist');
END;
IF p_type = 'cash' THEN
SELECT SUM(cash_amount_end) INTO v_cash_flow
FROM cashier_drawer_assignments cda
JOIN cashier_stations cs ON (cs.station_id = cda.station_id)
WHERE TRUNC(cda.start_time, 'dd') BETWEEN p_start_date AND p_end_date
AND cs.location_id = p_location_id;
ELSIF p_type = 'non-cash' THEN
SELECT SUM(non_cash_tender) INTO v_cash_flow
FROM cashier_drawer_assignments cda
JOIN cashier_stations cs ON (cs.station_id = cda.station_id)
WHERE TRUNC(cda.start_time, 'dd') BETWEEN p_start_date AND p_end_date
AND cs.location_id = p_location_id;
ELSE
jta_error.throw(-20201, 'invalid type, valid types: cash, non-cash');
END IF;
RETURN v_cash_flow;
EXCEPTION
WHEN no_data_found THEN
-- no need to log an error
-- this means that there was no gain for that day or payment type
RETURN 0;
WHEN jta_error.invalid_input THEN
-- no need to log error, will output something to console for us to see
jta_error.show_in_console(SQLCODE, SQLERRM);
RETURN NULL;
WHEN OTHERS THEN
-- all other exceptions will be logged into error table...
jta_error.log_error(SQLCODE, SQLERRM);
-- return null instead of zero because of fail
RETURN NULL;
END get_money_inflow;
/*
08
Update Taxes
This procedure reads the pending tax rates table, and updates the tax_rates and
tax_rate_history table to reflect the changes that should take place that day.
It then deletes the pending tax rates once changes have been made.
This procedure should be scheduled to run every day 6 am via dbms_scheduler.
A similar procedure should be run for pending price changes as well. However,
since that would just be a copy of this algorithm, we didn't bother including it.
*/
PROCEDURE update_taxes
IS
-- for update cursor, gets all changes starting today only
CURSOR changes IS
SELECT * FROM pending_tax_changes
WHERE start_date = TRUNC(SYSDATE, 'dd')
FOR UPDATE;
BEGIN
-- open cursor and update the taxes
FOR new_rate IN changes LOOP
-- an exception may be raised if the tax code is the same
-- in which case, the loop should continue in on to the next rate
BEGIN
-- update the current taxes table
UPDATE tax_rates SET
tax_rate = new_rate.tax_rate,
DESCRIPTION = new_rate.DESCRIPTION
WHERE tax_code = new_rate.tax_code
AND tax_rate != new_rate.tax_rate; -- only if tax rate not the same
-- if no rows updated, that means the tax rate was the same
IF SQL%rowcount = 0 THEN
jta_error.throw(-20201, 'attempt to update tax to same rate');
END IF;
-- update the tax_rate_history table, set old rate to end
UPDATE tax_rate_history SET
end_date = sysdate
WHERE tax_code = new_rate.tax_code AND
start_date IN ( SELECT MAX(start_date) FROM tax_rate_history
WHERE tax_code = new_rate.tax_code);
-- insert new rate into tax_rate_history
INSERT INTO tax_rate_history (tax_code, start_date, end_date, tax_rate)
VALUES (new_rate.tax_code, sysdate, NULL, new_rate.tax_rate);
EXCEPTION
WHEN jta_error.invalid_input THEN
-- log error and proceed to next row
jta_error.log_error(SQLCODE, SQLERRM);
END;
END LOOP;
-- delete relevant entries from pending tax changes table
DELETE FROM pending_tax_changes
WHERE start_date = TRUNC(SYSDATE, 'dd');
COMMIT;
EXCEPTION
WHEN no_data_found THEN
-- ignore no data found error, there are no pending changes to be made
NULL;
WHEN OTHERS THEN
-- all other exceptions will be logged into error table (not the no_data_exception)
jta_error.log_error(SQLCODE, SQLERRM);
ROLLBACK;
END update_taxes;
/*
09
Get price changes
Retreive a table (not stored) containing the price changes
that have occured for a given product within a time frame
It can be used to track how a products price fluctuates over time
for planning purposes
The return type is an index by table of records, this would
then have to be read by the application layer and displayed on screen
or printed out somewhere.
*/
FUNCTION get_price_changes (
p_product_id products.product_id%type,
p_start_date DATE,
p_end_date DATE
) RETURN price_changes_table
IS
-- cursor, retrieves price change history for this product
CURSOR price_changes IS
SELECT
hist.product_id,
pr.product_name,
hist.start_date,
hist.price_rate
FROM price_history hist JOIN products pr
ON (hist.product_id = pr.product_id)
WHERE hist.product_id = p_product_id
AND hist.start_date BETWEEN p_start_date AND p_end_date
ORDER BY start_date;
-- record for each change
v_price_record price_change_record;
-- return this index by table of records
v_return_table price_changes_table;
-- return empty table if exception
v_empty price_changes_table;
-- index for table
v_index BINARY_INTEGER := 1;
BEGIN
FOR pc_record IN price_changes LOOP
-- insert values into record
v_price_record.product_id := pc_record.product_id;
v_price_record.product_name := pc_record.product_name;
v_price_record.date_changed := pc_record.start_date;
v_price_record.new_price := pc_record.price_rate;
-- get old price for this product change
BEGIN
SELECT price_rate into v_price_record.old_price
FROM price_history
WHERE start_date = (
SELECT MAX(start_date)
FROM price_history
WHERE start_date < v_price_record.date_changed
) AND product_id = p_product_id;
EXCEPTION
WHEN no_data_found THEN
v_price_record.old_price := 0;
END;
-- calculate direcion
IF v_price_record.new_price > v_price_record.old_price THEN
v_price_record.direction := 'UP';
ELSIF v_price_record.new_price < v_price_record.old_price THEN
v_price_record.direction := 'DOWN';
ELSE
v_price_record.direction := '--';
END IF;
-- add to index by table of records
v_return_table(v_index) := v_price_record;
v_index := v_index + 1;
END LOOP;
RETURN v_return_table;
EXCEPTION
WHEN OTHERS THEN
-- all exceptions will be logged into error table...
jta_error.log_error(SQLCODE, SQLERRM);
RETURN v_empty;
END get_price_changes;
/*
10
Get profits for
Retrieve total number of goods sold, and total profit for a given time period
*/
PROCEDURE get_profits_for (
p_start_date IN DATE,
p_end_date IN DATE,
p_goods_sold OUT NOCOPY NUMBER,
p_gross_gain OUT NOCOPY NUMBER,
p_costs OUT NOCOPY NUMBER,
p_net_gain OUT NOCOPY NUMBER
)
IS
BEGIN
-- complex query to get values
-- this is actually more efficient that using several cursors
WITH avg_cost AS (
SELECT
bi.bill_line_id,
bi.quantity AS "Quantity",
bi.quantity * bi.price_rate AS "Gross Gain",
cb.date_time_created AS "Date",
( SELECT average_cost_per_unit
FROM cost_sales_tracker
WHERE date_time = (SELECT MAX(date_time)
FROM cost_sales_tracker
WHERE cb.date_time_created >= date_time AND bi.product_id = product_id)
) AS "Average Cost"
FROM billed_items bi JOIN customer_bills cb ON (cb.bill_id = bi.bill_id)
),
total_cost AS (
SELECT
bi.bill_line_id,
bi.quantity * av."Average Cost" AS "Cost"
FROM billed_items bi JOIN avg_cost av ON (bi.bill_line_id = av.bill_line_id)
),
net_gain AS (
SELECT
av.bill_line_id,
av."Gross Gain" - co."Cost" AS "Net Gain"
FROM avg_cost av JOIN total_cost co ON (av.bill_line_id = co.bill_line_id)
)
SELECT
SUM(av."Quantity"), SUM(av."Gross Gain"), SUM(co."Cost"), SUM(ng."Net Gain")
INTO p_goods_sold, p_gross_gain, p_costs, p_net_gain
FROM avg_cost av JOIN total_cost co ON (av.bill_line_id = co.bill_line_id)
JOIN net_gain ng ON (ng.bill_line_id = av.bill_line_id)
WHERE av."Date" BETWEEN p_start_date AND p_end_date;
EXCEPTION
WHEN OTHERS THEN
-- all exceptions will be logged into error table...
jta_error.log_error(SQLCODE, SQLERRM);
p_goods_sold := NULL;
p_gross_gain := NULL;
p_costs := NULL;
p_net_gain := NULL;
END get_profits_for;
/*
11
Get recommended price for
given a product_id, recommend a new price based on the average cost
calculation:
> find the average cost price from the cost sales tracker table,
> add a minimum markup of 30%
> add the correct vat rate from the tax_rate table
> round the value up to the nearest integer,
> subtracts 0.01 to produce a nice $19.99 like price
*/
PROCEDURE get_recommended_price_for (
p_product_id IN products.product_id%TYPE,
p_avg_cost OUT NOCOPY products.price_rate%TYPE,
p_old_price OUT NOCOPY products.price_rate%TYPE,
p_new_price OUT NOCOPY products.price_rate%TYPE
)
IS
v_avg products.price_rate%TYPE;
v_tax tax_rates.tax_rate%TYPE;
BEGIN
-- try to get current price and average cost and perform calculations,
-- log our own error if doesn't exist.
BEGIN
SELECT price_rate, tax_rate INTO p_old_price, v_tax
FROM products pr JOIN tax_rates tr ON (pr.tax_code = tr.tax_code)
WHERE pr.product_id = p_product_id;
SELECT average_cost_per_unit INTO v_avg
FROM cost_sales_tracker
WHERE transaction_id IN (SELECT
MAX(transaction_id) FROM cost_sales_tracker
WHERE product_id = p_product_id);
p_avg_cost := v_avg;
p_new_price := CEIL((v_avg * 1.3)
+ (v_avg * 1.3 * (v_tax/100)))
- 0.01;