-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFinalDatabase.sql
2157 lines (1841 loc) · 94.7 KB
/
FinalDatabase.sql
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
drop database if exists ECommerceDatabase;
create schema ECommerceDatabase;
use ECommerceDatabase;
CREATE TABLE `Category` (
`category_id` INT AUTO_INCREMENT,
`category_name` VARCHAR(255) NOT NULL UNIQUE,
`description` VARCHAR(255),
PRIMARY KEY (`category_id`)
);
-- Table to store parent-child category relationships
CREATE TABLE `ParentCategory_Match` (
`category_id` INT,
`parent_category_id` INT,
PRIMARY KEY (`category_id`, `parent_category_id`),
FOREIGN KEY (`category_id`) REFERENCES `Category`(`category_id`)
ON UPDATE CASCADE
ON DELETE CASCADE,
FOREIGN KEY (`parent_category_id`) REFERENCES `Category`(`category_id`)
ON UPDATE CASCADE
ON DELETE RESTRICT
);
-- Add indexes to improve performance
CREATE INDEX idx_parent_category_match_category_id ON `ParentCategory_Match` (`category_id`);
CREATE INDEX idx_parent_category_match_parent_category_id ON `ParentCategory_Match` (`parent_category_id`);
CREATE TABLE `Warehouse` (
`warehouse_id` INT AUTO_INCREMENT,
`location` VARCHAR(255) not null,
`capacity` INT NOT null,
`available_capacity` INT,
PRIMARY KEY (`warehouse_id`)
);
delimiter $$
CREATE TRIGGER enter_avalible_capacity
BEFORE INSERT ON Warehouse
FOR EACH ROW
BEGIN
SET NEW.available_capacity = NEW.capacity ;
END$$
delimiter ;
CREATE TABLE `Product` (
`product_id` INT AUTO_INCREMENT,
`title` VARCHAR(255) NOT NULL,
`description` VARCHAR(255),
`sku` VARCHAR(255),
`weight` FLOAT,
`default_price` FLOAT,
`default_image` VARCHAR(255),
-- `warehouse_id` INT,
`created_at` DATETIME NOT NULL,
`updated_at` DATETIME,
PRIMARY KEY (`product_id`)
-- FOREIGN KEY (`warehouse_id`) REFERENCES `Warehouse`(`warehouse_id`)
-- ON DELETE RESTRICT
-- ON UPDATE CASCADE
);
-- Table to store many-to-many relationship between products and categories
CREATE TABLE `Product_Category_Match` (
`product_id` INT,
`category_id` INT,
PRIMARY KEY (`product_id`, `category_id`),
FOREIGN KEY (`product_id`) REFERENCES `Product`(`product_id`)
ON DELETE CASCADE
ON UPDATE CASCADE,
FOREIGN KEY (`category_id`) REFERENCES `Category`(`category_id`)
ON DELETE RESTRICT
ON UPDATE CASCADE
);
-- Add indexes to improve performance
CREATE INDEX idx_product_category_match_product_id ON `Product_Category_Match` (`product_id`);
CREATE INDEX idx_product_category_match_category_id ON `Product_Category_Match` (`category_id`);
CREATE TABLE `Variant` (
`variant_id` INT AUTO_INCREMENT,
`product_id` INT,
`name` VARCHAR(255),
`image_url` VARCHAR(255),
`price` FLOAT,
`created_at` DATETIME NOT NULL,
`updated_at` DATETIME,
`interested` INT default 0,
PRIMARY KEY (`variant_id`),
FOREIGN KEY (`product_id`) REFERENCES `Product`(`product_id`)
ON DELETE RESTRICT
ON UPDATE CASCADE
);
-- Indexes to improve performance
CREATE INDEX idx_variant_product_id ON `Variant` (`product_id`);
CREATE TABLE `Custom_Attribute` (
`attribute_id` INT AUTO_INCREMENT,
`product_id` INT,
`attribute_name` VARCHAR(255),
PRIMARY KEY (`attribute_id`),
FOREIGN KEY (`product_id`) REFERENCES `Product`(`product_id`)
);
CREATE INDEX idx_custom_attribute_product_id ON `Custom_Attribute` (`product_id`);
CREATE TABLE `Custom_Attribute_Value` (
`variant_id` INT,
`attribute_id` INT,
`attribute_value` VARCHAR(255),
PRIMARY KEY (`variant_id`, `attribute_id`),
FOREIGN KEY (`variant_id`) REFERENCES `Variant`(`variant_id`),
FOREIGN KEY (`attribute_id`) REFERENCES `Custom_Attribute`(`attribute_id`)
);
CREATE INDEX idx_custom_attribute_value_variant_id ON `Custom_Attribute_Value` (`variant_id`);
CREATE INDEX idx_custom_attribute_value_attribute_id ON `Custom_Attribute_Value` (`attribute_id`);
CREATE TABLE `Inventory` (
`inventory_id` INT AUTO_INCREMENT,
`warehouse_id` INT,
`variant_id` INT,
`quantity_available` INT not null,
`assigned_capacity` INT default 50,
`last_updated` DATETIME,
PRIMARY KEY (`inventory_id`),
FOREIGN KEY (`warehouse_id`) REFERENCES `Warehouse`(`warehouse_id`)
on delete restrict
on update cascade,
FOREIGN KEY (`variant_id`) REFERENCES `Variant`(`variant_id`)
on delete restrict
on update cascade
);
CREATE TABLE `DeliveryLocation` (
`delivery_location_id` INT AUTO_INCREMENT,
`location_name` VARCHAR(255) NOT NULL,
`location_type` ENUM('store', 'city') NOT NULL DEFAULT 'city',
`with_stock_delivery_days` INT,
`without_stock_delivery_days` INT,
PRIMARY KEY (`delivery_location_id`)
);
CREATE TABLE `Role` (
`role_id` INT AUTO_INCREMENT,
`role_name` ENUM("Admin", "User", "Guest") NOT null,
`description` VARCHAR(255),
PRIMARY KEY (`role_id`)
);
CREATE TABLE `User` (
`user_id` INT AUTO_INCREMENT,
`first_name` VARCHAR(255) not null,
`last_name` VARCHAR(255),
`email` VARCHAR(255) unique,
`password_hash` VARCHAR(255),
`phone_number` VARCHAR(255),
`delivery_location_id` INT,
`address` VARCHAR(255),
`is_guest` BOOLEAN not null,
`role_id` INT not null,
`created_at` DATETIME not null,
`last_login` DATETIME,
PRIMARY KEY (`user_id`),
FOREIGN KEY (`delivery_location_id`) REFERENCES `DeliveryLocation`(`delivery_location_id`)
ON DELETE RESTRICT
ON UPDATE CASCADE,
FOREIGN KEY (`role_id`) REFERENCES `Role`(`role_id`)
ON DELETE RESTRICT
ON UPDATE CASCADE
);
CREATE TABLE `Cart` (
-- `cart_item_id` INT AUTO_INCREMENT,
`user_id` INT not null,
`variant_id` INT not null,
`quantity` INT not null,
-- PRIMARY KEY (`cart_item_id`),
PRIMARY KEY (`user_id`,`variant_id`),
FOREIGN KEY (`user_id`) REFERENCES `User`(`user_id`)
on delete cascade
on update cascade,
FOREIGN KEY (`variant_id`) REFERENCES `Variant`(`variant_id`)
on delete cascade
on update cascade
);
CREATE INDEX idx_cart_user_id ON Cart(user_id);
delimiter $$
create trigger increase_interested
after insert on Cart
for each row
begin
update Variant
set interested = interested + 1
where variant_id = new.variant_id ;
end$$
create trigger decrease_interested
after delete on Cart
for each row
begin
update Variant
set interested = interested - 1
where variant_id = old.variant_id ;
end$$
delimiter ;
CREATE TABLE `Order` (
`order_id` INT AUTO_INCREMENT,
`customer_id` INT,
`customer_name` VARCHAR(255),
`contact_email` VARCHAR(255),
`contact_phone` VARCHAR(255),
`delivery_method` ENUM('store_pickup', 'delivery') NOT NULL,
`delivery_location_id` INT,
`delivery_address` VARCHAR(255),
`payment_method` ENUM('cash_on_delivery', 'card'),
`total_amount` FLOAT,
`order_status` ENUM('Processing', 'Confirmed', 'Shipped', 'Completed', 'Failed'),
`purchased_time` DATETIME,
`delivery_estimate` INT,
`created_at` DATETIME,
`updated_at` DATETIME,
PRIMARY KEY (`order_id`),
FOREIGN KEY (`customer_id`) REFERENCES `User`(`user_id`),
FOREIGN KEY (`delivery_location_id`) REFERENCES `DeliveryLocation`(`delivery_location_id`)
);
CREATE TABLE `OrderItem` (
`order_item_id` INT AUTO_INCREMENT,
`order_id` INT,
`variant_id` INT,
`discount` FLOAT,
`quantity` INT,
`price` FLOAT,
PRIMARY KEY (`order_item_id`),
FOREIGN KEY (`order_id`) REFERENCES `Order`(`order_id`),
FOREIGN KEY (`variant_id`) REFERENCES `Variant`(`variant_id`)
);
DELIMITER $$
CREATE PROCEDURE GetProductDetails(IN product_id INT)
BEGIN
SELECT
p.product_id AS product_id,
p.title AS product_name,
p.description AS product_description,
p.default_price AS price,
p.default_image AS image_url,
p.sku,
p.weight,
JSON_ARRAYAGG(c.category_name) AS categories,
(
SELECT JSON_ARRAYAGG(
JSON_OBJECT(
'variant_id', dv.variant_id,
'variant_name', dv.name,
'price', dv.price,
'image_url', dv.image_url,
'quantity_available', dv.quantity_available,
'attributes', (
SELECT JSON_ARRAYAGG(
JSON_OBJECT(
'attribute_name', ca.attribute_name,
'attribute_value', cav.attribute_value
)
)
FROM Custom_Attribute ca
JOIN Custom_Attribute_Value cav ON ca.attribute_id = cav.attribute_id
WHERE cav.variant_id = dv.variant_id
)
)
)
FROM (
SELECT DISTINCT v.*, i.quantity_available
FROM Variant v
LEFT JOIN Inventory i ON v.variant_id = i.variant_id
WHERE v.product_id = p.product_id
) AS dv
) AS variants
FROM Product p
JOIN Product_Category_Match pcm ON p.product_id = pcm.product_id
JOIN Category c ON pcm.category_id = c.category_id
WHERE p.product_id = product_id
GROUP BY p.product_id
ORDER BY p.title;
END$$
CREATE PROCEDURE move_cart_to_order(IN p_user_id INT, OUT p_order_id INT)
BEGIN
DECLARE v_total_amount FLOAT DEFAULT 0;
DECLARE v_contact_email VARCHAR(255);
DECLARE v_contact_phone VARCHAR(255);
DECLARE v_delivery_address VARCHAR(255);
DECLARE v_first_name VARCHAR(255);
DECLARE v_last_name VARCHAR(255);
DECLARE v_customer_name VARCHAR(255);
-- Start transaction
START TRANSACTION;
-- Step 1: Retrieve the user's email, phone number, address, first name, and last name from the User table
SELECT email, phone_number, address, first_name, last_name
INTO v_contact_email, v_contact_phone, v_delivery_address, v_first_name, v_last_name
FROM User
WHERE user_id = p_user_id;
-- Step 2: Concatenate the first and last names to form customer_name
SET v_customer_name = CONCAT(v_first_name, ' ', v_last_name);
-- Step 3: Create a new order with the retrieved contact information, delivery address, and customer_name
INSERT INTO `Order` (customer_id, contact_email, contact_phone, delivery_address, customer_name, order_status, purchased_time, created_at, updated_at)
VALUES (p_user_id, v_contact_email, v_contact_phone, v_delivery_address, v_customer_name, 'Processing', NOW(), NOW(), NOW());
-- Step 4: Get the order_id of the newly created order
SET p_order_id = LAST_INSERT_ID();
-- Step 5: Move items from Cart to OrderItem and calculate total amount
INSERT INTO OrderItem (order_id, variant_id, quantity, price)
SELECT p_order_id, c.variant_id, c.quantity, v.price
FROM Cart c
JOIN Variant v ON c.variant_id = v.variant_id
WHERE c.user_id = p_user_id;
-- Step 6: Calculate total amount
SELECT SUM(oi.price * oi.quantity) INTO v_total_amount
FROM OrderItem oi
WHERE oi.order_id = p_order_id;
-- Step 7: Update the total_amount in the Order table
UPDATE `Order`
SET total_amount = v_total_amount
WHERE order_id = p_order_id;
-- Step 8: Clear the Cart for the user
DELETE FROM Cart WHERE user_id = p_user_id;
-- If all operations are successful, commit the transaction
COMMIT;
END$$
CREATE TRIGGER update_inventory_and_calculate_total
AFTER INSERT ON OrderItem
FOR EACH ROW
BEGIN
DECLARE v_total_amount FLOAT DEFAULT 0;
-- Step 1: Decrement the quantity in Inventory, even if it results in negative stock
UPDATE Inventory
SET quantity_available = quantity_available - NEW.quantity
WHERE variant_id = NEW.variant_id;
-- Step 2: Recalculate total_amount in the Order table
SELECT SUM(price * quantity) INTO v_total_amount
FROM OrderItem
WHERE order_id = NEW.order_id;
-- Step 3: Update the total_amount in the Order table
UPDATE `Order`
SET total_amount = v_total_amount
WHERE order_id = NEW.order_id;
END$$
CREATE PROCEDURE complete_checkout(
IN orderId INT,
IN userId INT,
IN name VARCHAR(255),
IN phone VARCHAR(255),
IN email VARCHAR(255),
IN address VARCHAR(255),
IN deliveryMethod ENUM('store_pickup', 'delivery'),
IN deliveryLocationId INT,
IN paymentMethod ENUM('cash_on_delivery', 'card')
)
BEGIN
-- Declare variables at the beginning of the procedure
DECLARE v_total_amount FLOAT DEFAULT 0;
DECLARE v_delivery_estimate INT;
DECLARE v_with_stock_delivery_days INT;
DECLARE v_without_stock_delivery_days INT;
DECLARE v_item_quantity INT;
DECLARE v_inventory_quantity INT;
DECLARE done INT DEFAULT FALSE;
-- Declare cursor for order items
DECLARE order_item_cursor CURSOR FOR
SELECT quantity, variant_id
FROM OrderItem
WHERE order_id = orderId;
-- Declare continue handler for cursor
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
-- Start transaction
START TRANSACTION;
-- Check if the user is the owner of the order
IF NOT EXISTS (
SELECT 1
FROM `Order`
WHERE order_id = orderId AND customer_id = userId
) THEN
SIGNAL SQLSTATE '45000'
SET MESSAGE_TEXT = 'User does not have permission to complete this order';
END IF;
-- Step 1: Retrieve the delivery location details
SELECT with_stock_delivery_days, without_stock_delivery_days
INTO v_with_stock_delivery_days, v_without_stock_delivery_days
FROM DeliveryLocation
WHERE delivery_location_id = deliveryLocationId;
-- Initialize the delivery estimate
SET v_delivery_estimate = v_with_stock_delivery_days;
-- Open the cursor
OPEN order_item_cursor;
-- Loop through order items
read_loop: LOOP
FETCH order_item_cursor INTO v_item_quantity, v_inventory_quantity;
IF done THEN
LEAVE read_loop;
END IF;
-- Step 2: Check if item quantity exceeds inventory stock
SELECT quantity_available INTO v_inventory_quantity
FROM Inventory
WHERE variant_id = v_item_quantity;
IF v_item_quantity > v_inventory_quantity THEN
SET v_delivery_estimate = v_without_stock_delivery_days;
END IF;
END LOOP;
-- Close the cursor
CLOSE order_item_cursor;
-- Step 3: Update the Order with provided details and estimated delivery time
UPDATE `Order`
SET contact_email = email,
contact_phone = phone,
delivery_address = address,
customer_name = name,
delivery_method = deliveryMethod,
delivery_location_id = deliveryLocationId,
payment_method = paymentMethod,
delivery_estimate = v_delivery_estimate,
order_status = 'Confirmed', -- Updated status to 'Confirmed'
updated_at = NOW()
WHERE order_id = orderId;
-- Commit the transaction if everything is successful
COMMIT;
END$$
-- DROP EVENT IF EXISTS `30minutes__cancel_processing_orders`;
CREATE EVENT `30minutes__cancel_processing_orders`
ON SCHEDULE
EVERY 30 MINUTE
DO
BEGIN
START TRANSACTION;
UPDATE Inventory i
JOIN OrderItem oi ON i.variant_id = oi.variant_id
JOIN `Order` o ON oi.order_id = o.order_id
SET i.quantity_available = i.quantity_available + oi.quantity,
o.order_status = 'Failed'
WHERE o.order_status = 'Processing'
AND o.updated_at + INTERVAL 30 MINUTE <= CURRENT_TIMESTAMP();
COMMIT;
END$$
-- Added indexes for optimization
ALTER TABLE `Order`
ADD INDEX `idx_order_status_updated_at` (order_status, updated_at);
CREATE PROCEDURE ADD_WAREHOUSE (location VARCHAR(255) , capacity INT)
BEGIN
INSERT INTO Warehouse VALUES (default,location,capacity);
END$$
CREATE PROCEDURE InsertCustomAttributeWithDefaultValues (
IN input_product_id INT,
IN input_attribute_name VARCHAR(255)
)
BEGIN
DECLARE new_attribute_id INT;
-- Step 1: Insert new custom attribute for the product
INSERT INTO Custom_Attribute (product_id, attribute_name)
VALUES (input_product_id, input_attribute_name);
-- Retrieve the new attribute_id generated
SET new_attribute_id = LAST_INSERT_ID();
-- Step 2: Insert 'not specified' for each variant of the product
INSERT INTO Custom_Attribute_Value (variant_id, attribute_id, attribute_value)
SELECT v.variant_id, new_attribute_id, 'Not specified'
FROM Variant v
WHERE v.product_id = input_product_id;
END $$
create procedure CHANGE_VARIANT_ATTRIBUTE_VALUE (variant_id INT, attribute_id INT, new_attribute_value VARCHAR(255))
BEGIN
update Custom_Attribute_Value set attribute_value = new_attribute_value
where Custom_Attribute_Value.variant_id = variant_id and Custom_Attribute_Value.attribute_id = attribute_id;
END$$
-- when a product is added, a variant should be added to variant table as well
-- Otherwise adding a product is not allowed.
-- adding a product must always add a variant.
create procedure ADD_PRODUCT (title VARCHAR(255) , description varchar(255) , sku varchar(255), weight float)
begin
insert into Product values (default,title,description,sku,weight,warehouse_id,now(),now());
END$$
CREATE PROCEDURE ADD_VARIANT( product_id INT , name varchar(255), price float,quantity INT, warehouse_id INT,assigned_capacity INT)
begin
insert into Variant values (default,product_id,name,price,now(),now());
-- set @warehouse_id = (
-- select warehouse_id
-- from Product p
-- where p.product_id = product_id
-- );
set @variant_id = LAST_INSERT_ID();
insert into Inventory values (default,warehouse_id,@varinat_id,quantity,assigned_capacity,now());
end$$
CREATE PROCEDURE SET_CATEGORY (IN product_id INT, IN category_id INT)
BEGIN
INSERT INTO Product_Category_Match values (product_id, category_id);
END$$
CREATE FUNCTION GetSubCategories(
input_category_id INT
)
RETURNS text -- Adjust the length as per your needs
DETERMINISTIC
BEGIN
-- Variable to hold the concatenated result
DECLARE subcategories_list text DEFAULT '';
-- Use a recursive Common Table Expression (CTE)
WITH RECURSIVE SubCategoryCTE AS (
-- Anchor member: Select all immediate subcategories of the given category
SELECT
pc.category_id,
pc.parent_category_id
FROM
ParentCategory_Match pc
WHERE
pc.parent_category_id = input_category_id
UNION ALL
-- Recursive member: Find the subcategories of the current subcategory
SELECT
pcm.category_id,
pcm.parent_category_id
FROM
ParentCategory_Match pcm
INNER JOIN
SubCategoryCTE sc ON pcm.parent_category_id = sc.category_id
)
-- Build a comma-separated list of subcategory IDs
SELECT GROUP_CONCAT(sc.category_id)
INTO subcategories_list
FROM SubCategoryCTE sc
JOIN Category c ON sc.category_id = c.category_id;
-- Return the comma-separated list
RETURN subcategories_list;
END $$
CREATE FUNCTION GetProductsInSubCategories(
input_category_id INT
)
RETURNS text -- Adjust the length as needed
DETERMINISTIC
BEGIN
-- Declare a variable to store the concatenated product IDs
DECLARE product_list text DEFAULT '';
-- Retrieve subcategories using the GetSubCategories function
DECLARE subcategories_list text;
SET subcategories_list = GetSubCategories(input_category_id);
-- If subcategories list is empty, return NULL (no products)
IF subcategories_list IS NULL THEN
RETURN NULL;
END IF;
-- Retrieve product IDs belonging to the subcategories
SELECT GROUP_CONCAT(p.product_id)
INTO product_list
FROM Product p
WHERE FIND_IN_SET(p.category_id, subcategories_list);
-- Return the concatenated list of product IDs
RETURN product_list;
END $$
CREATE FUNCTION GetVariantsForSubCategories(
category_id INT
)
RETURNS text -- Adjust the length as necessary
DETERMINISTIC
BEGIN
-- Variable to hold the concatenated result of variant IDs
DECLARE variant_list text DEFAULT '';
-- Temporary variable to hold product IDs
DECLARE product_ids text;
-- Step 1: Get product IDs returned by GetProductsInSubCategories
SET product_ids = GetProductsInSubCategories(category_id);
-- If no product IDs found, return NULL
IF product_ids IS NULL THEN
RETURN NULL;
END IF;
-- Step 2: Get all variants for the products
SELECT GROUP_CONCAT(v.variant_id)
INTO variant_list
FROM Variant v
WHERE FIND_IN_SET(v.product_id, product_ids);
-- Step 3: Return the comma-separated list of variant IDs
RETURN variant_list;
END $$
-- Register the user
CREATE PROCEDURE RegisterUser (
IN p_first_name VARCHAR(255),
IN p_last_name VARCHAR(255),
IN p_email VARCHAR(255),
IN p_password VARCHAR(255),
IN p_phone_number VARCHAR(255),
IN p_is_guest BOOLEAN
)
BEGIN
DECLARE hashed_password VARCHAR(255);
-- Hash the password using SHA2 (you can use a more secure hashing function as needed)
SET hashed_password = SHA2(p_password, 256);
INSERT INTO User (first_name, last_name, email, password_hash, phone_number, is_guest, role_id, created_at)
VALUES (
p_first_name,
p_last_name,
p_email,
hashed_password,
p_phone_number,
p_is_guest,
(SELECT role_id FROM Role WHERE role_name = 'User'), -- Assign default role
NOW()
);
END;
-- Update inventory..
CREATE PROCEDURE UpdateInventory (
IN p_variant_id INT,
IN p_quantity_change INT
)
BEGIN
UPDATE Inventory
SET
quantity_available = quantity_available + p_quantity_change,
last_updated = NOW()
WHERE variant_id = p_variant_id;
END;
-- Add to cart
CREATE PROCEDURE AddToCart (
IN p_user_id INT,
IN p_variant_id INT,
IN p_quantity INT
)
BEGIN
DECLARE existing_quantity INT;
SELECT quantity INTO existing_quantity
FROM Cart
WHERE user_id = p_user_id AND variant_id = p_variant_id;
IF existing_quantity IS NOT NULL THEN
UPDATE Cart
SET quantity = p_quantity
WHERE user_id = p_user_id AND variant_id = p_variant_id;
ELSE
INSERT INTO Cart (user_id, variant_id, quantity)
VALUES (p_user_id, p_variant_id, p_quantity);
END IF;
END;
-- Show cart of user
DROP PROCEDURE IF EXISTS `ShowCartofUser`;
CREATE PROCEDURE `ShowCartofUser` (
IN p_user_id INT
)
BEGIN
SELECT
v.variant_id,
v.product_id,
p.title as product_name,
v.name as variant_name,
v.price,
v.image_url,
c.quantity,
i.quantity_available,
(
SELECT JSON_ARRAYAGG(
JSON_OBJECT(
'attribute_name', a.attribute_name,
'attribute_value', va.attribute_value
)
)
FROM custom_attribute_value va
JOIN custom_attribute a ON va.attribute_id = a.attribute_id
WHERE va.variant_id = v.variant_id
) AS attributes
FROM variant v
JOIN cart c ON v.variant_id = c.variant_id
JOIN product p ON v.product_id = p.product_id
JOIN inventory i ON v.variant_id = i.variant_id
WHERE c.user_id = p_user_id;
END$$
-- remove from cart.
CREATE PROCEDURE RemoveFromCart (
IN p_user_id INT,
IN p_variant_id INT
)
BEGIN
DELETE FROM Cart
WHERE user_id = p_user_id AND variant_id = p_variant_id;
END;
-- Get cart items
-- CREATE PROCEDURE CheckoutOrder(IN orderID INT)
-- BEGIN
-- DECLARE variantID INT;
-- DECLARE orderQuantity INT;
-- DECLARE availableQuantity INT;
-- DECLARE done INT DEFAULT FALSE;
--
-- -- Cursor to loop through all items in the order
-- DECLARE orderItems CURSOR FOR
-- SELECT variant_id, quantity
-- FROM OrderItem
-- WHERE order_id = orderID;
-- -- Handler to exit the loop
-- DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
-- OPEN orderItems;
-- orderLoop: LOOP
-- FETCH orderItems INTO variantID, orderQuantity;
--
-- IF done THEN
-- LEAVE orderLoop;
-- END IF;
--
-- -- Check the available stock
-- SELECT quantity_available INTO availableQuantity
-- FROM Inventory
-- WHERE variant_id = variantID;
-- IF availableQuantity < orderQuantity THEN
-- SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'Insufficient stock for one or more items';
-- ELSE
-- -- Reduce the stock
-- UPDATE Inventory
-- SET quantity_available = quantity_available - orderQuantity
-- WHERE variant_id = variantID;
-- END IF;
-- END LOOP;
-- CLOSE orderItems;
-- END$$
-- Update product price
CREATE PROCEDURE UpdateProductPrice(
IN variantID INT,
IN newPrice FLOAT
)
BEGIN
-- Update the price of the product variant
UPDATE Variant
SET price = newPrice
WHERE variant_id = variantID;
END$$
-- Add stock quantity
CREATE PROCEDURE AddStockQuantity(
IN variantID INT,
IN additionalQuantity INT
)
BEGIN
-- Update the stock by adding the new quantity to the existing quantity
UPDATE Inventory
SET quantity_available = quantity_available + additionalQuantity
WHERE variant_id = variantID;
END$$
CREATE PROCEDURE CheckoutOrder(IN orderID INT)
BEGIN
DECLARE variantID INT;
DECLARE orderQuantity INT;
DECLARE availableQuantity INT;
DECLARE done INT DEFAULT FALSE;
-- Cursor to loop through all items in the order
DECLARE orderItems CURSOR FOR
SELECT variant_id, quantity
FROM OrderItem
WHERE order_id = orderID;
-- Handler to exit the loop
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
OPEN orderItems;
orderLoop: LOOP
FETCH orderItems INTO variantID, orderQuantity;
IF done THEN
LEAVE orderLoop;
END IF;
-- Check the available stock
SELECT quantity_available INTO availableQuantity
FROM Inventory
WHERE variant_id = variantID;
IF availableQuantity < orderQuantity THEN
SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'Insufficient stock for one or more items';
ELSE
-- Reduce the stock
UPDATE Inventory
SET quantity_available = quantity_available - orderQuantity
WHERE variant_id = variantID;
END IF;
END LOOP;
CLOSE orderItems;
END$$
CREATE PROCEDURE Get_Quarterly_Sales_By_Year (IN input_year INT)
BEGIN
-- Create a temporary table for quarters
CREATE TEMPORARY TABLE Quarters (
quarter INT
);
-- Insert the quarters 1 to 4 into the temporary table
INSERT INTO Quarters (quarter) VALUES (1), (2), (3), (4);
-- Select the sales data for all quarters in the specified year
SELECT
q.quarter,
IFNULL(SUM(o.total_amount), 0) AS total_sales
FROM
Quarters q
LEFT JOIN
`Order` o ON QUARTER(o.purchased_time) = q.quarter
AND YEAR(o.purchased_time) = input_year
GROUP BY
q.quarter
ORDER BY
q.quarter;
-- Drop the temporary table
DROP TEMPORARY TABLE Quarters;
END$$
DELIMITER ;
-- Insert roles
INSERT INTO `Role` (`role_name`, `description`)
VALUES
('Admin', 'Administrator role'),
('User', 'Regular user'),
('Guest', 'Guest user');
-- Insert Warehouse Data
INSERT INTO `Warehouse` (`location`, `capacity`, `available_capacity`)
VALUES
('New York Warehouse', 10000, 10000),
('Los Angeles Warehouse', 8000, 8000);
INSERT INTO `DeliveryLocation` (`location_name`, `location_type`, `with_stock_delivery_days`, `without_stock_delivery_days`)
VALUES
('Texas', 'store', 1, 3),
('New York', 'store', 3, 5),
('Texas', 'city', 5, 8), -- Main city in Texas
('New York', 'city', 7, 10),
('Los Angeles', 'city', 7, 10),
('California', 'city', 7, 10);
-- Insert users
INSERT INTO `User` (`first_name`, `last_name`, `email`, `password_hash`, `phone_number`, `delivery_location_id`, `is_guest`, `role_id`, `created_at`)
VALUES
('Admin', 'C', '[email protected]', '$2a$10$j/DeFvwmLpBjAbJjFRJo6uwQb8/0UnejZOqWKmXTwASwwm.m5DDxq', '1234567890', 1, 0, 1, NOW()),
('Jane', 'Smith', '[email protected]', '$2a$10$j/DeFvwmLpBjAbJjFRJo6uwQb8/0UnejZOqWKmXTwASwwm.m5DDxq', '0987654321', 2, 0, 2, NOW()),
('John', 'Doe', '[email protected]', '$2a$10$j/DeFvwmLpBjAbJjFRJo6uwQb8/0UnejZOqWKmXTwASwwm.m5DDxq', '0987654321', 2, 0, 2, NOW()),
('Nick', 'Noah', '[email protected]', '$2a$10$j/DeFvwmLpBjAbJjFRJo6uwQb8/0UnejZOqWKmXTwASwwm.m5DDxq', '0987654321', 2, 0, 2, NOW()),
('Pilip', 'Man', '[email protected]', '$2a$10$j/DeFvwmLpBjAbJjFRJo6uwQb8/0UnejZOqWKmXTwASwwm.m5DDxq', '0987654321', 2, 0, 2, NOW());
-- Insert Main Categories
INSERT INTO `Category` (`category_name`, `description`)
VALUES
('Computers', 'Desktops, Laptops, and Computer Accessories'), -- ID 1
('Mobile Phones', 'Smartphones and Mobile Accessories'), -- ID 2
('Speakers', 'Audio speakers and sound systems'), -- ID 3
('Toys', 'Children\'s toys and games'); -- ID 4
-- Insert Sub-Categories
INSERT INTO `Category` (`category_name`, `description`)
VALUES
('Apple', 'Apple products'), -- ID 5
('Samsung', 'Samsung products'), -- ID 6
('Lenovo', 'Lenovo products'), -- ID 7
('HP', 'HP products'), -- ID 8
('OnePlus', 'OnePlus smartphones'), -- ID 9
('JBL', 'JBL Speakers'), -- ID 10
('Sony', 'Sony Speakers'), -- ID 11
('Bose', 'Bose Speakers'), -- ID 12
('Building Blocks', 'Building and construction toys'),-- ID 13
('Action Figures', 'Action figure toys'), -- ID 14
('Board Games', 'Board games for all ages'), -- ID 15
('Puzzles', 'Puzzles and brain teasers'), -- ID 16
('Outdoor Toys', 'Toys for outdoor play'), -- ID 17
('Toy Vehicles', 'Toy cars, trucks, and other vehicles'), -- ID 18
('Musical Toys', 'Musical instruments for kids'), -- ID 19
('Educational Toys', 'Learning and educational toys'),-- ID 20
('Trading Card Games', 'Collectible card games'); -- ID 21
-- Parent Category Relationships
INSERT INTO `ParentCategory_Match` (`category_id`, `parent_category_id`)
VALUES
(5, 1), -- Apple under Computers
(5, 2), -- Apple under Mobile Phones
(6, 2), -- Samsung under Mobile Phones
(7, 1), -- Lenovo under Computers
(8, 1), -- HP under Computers
(9, 2), -- OnePlus under Mobile Phones
(10, 3), -- JBL under Speakers
(11, 3), -- Sony under Speakers
(12, 3), -- Bose under Speakers
(13, 4), -- Building Blocks under Toys
(14, 4), -- Action Figures under Toys
(15, 4), -- Board Games under Toys
(16, 4), -- Puzzles under Toys