Repository navigation
Expand file tree
/
Copy pathschema.sql
More file actions
1594 lines (1401 loc) · 48.7 KB
/
Copy pathschema.sql
File metadata and controls
1594 lines (1401 loc) · 48.7 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
-- Tech Axis DB schema designed and authored by Rayyan (240212160)
-- Notes:
-- NOTIFY is used to create stock alerts like an event system and we need to LISTEN to it within the backend.
-- Extensions
CREATE EXTENSION IF NOT EXISTS pg_trgm;
-- documentation reference: https://www.postgresql.org/docs/current/pgtrgm.html
-- tsvector: https://www.postgresql.org/docs/current/datatype-textsearch.html
-- ts_rank, websearch_to_tsquery, setweight: https://www.postgresql.org/docs/current/textsearch-controls.html
-- I ended up choosing websearch_to_tsquery instead of plainto_tsquery or to_tsquery for the following reasons:
-- 1) websearch_to_tsquery is a simplified version of to_tsquery
-- 2) websearch_to_tsquery provides a common syntax used by modern web search engines such as google
-- For example the following syntax is supported while making use of the GIN indexes
-- 1) "nintendo switch" -> exact phrase
-- 2) ps5 -controller -> exclude controller
-- 3) pc OR console -> boolean OR
-- By default unquoted text: text not inside quote marks will be converted to terms separated by & operators, as if processed by plainto_tsquery.
CREATE EXTENSION IF NOT EXISTS citext;
-- case insensitive emails & usernames reference: https://www.postgresql.org/docs/current/citext.html
-- The standard approach to doing case-insensitive matches in PostgreSQL has been to use the lower function when comparing values, for example
-- SELECT * FROM tab WHERE lower(col) = LOWER(?);
-- This works reasonably well, but has a number of drawbacks:
-- It makes your SQL statements verbose, and you always have to remember to use lower on both the column and the query value.
-- It won't use an index, unless you create a functional index using lower.
-- If you declare a column as UNIQUE or PRIMARY KEY, the implicitly generated index is case-sensitive. So it's useless for case-insensitive searches, and it won't enforce uniqueness case-insensitively.
-- The citext data type allows you to eliminate calls to lower in SQL queries, and allows a primary key to be case-insensitive.
-- Enums
DO $$
BEGIN
IF NOT EXISTS (SELECT 1 FROM pg_type WHERE typname = 'user_role') THEN
CREATE TYPE user_role AS ENUM ('customer','admin');
END IF;
IF NOT EXISTS (SELECT 1 FROM pg_type WHERE typname = 'product_status') THEN
CREATE TYPE product_status AS ENUM ('draft','active','archived');
END IF;
IF NOT EXISTS (SELECT 1 FROM pg_type WHERE typname = 'order_status') THEN
CREATE TYPE order_status AS ENUM ('pending','placed','processing','shipped','completed','cancelled','returned');
END IF;
IF NOT EXISTS (SELECT 1 FROM pg_type WHERE typname = 'return_status') THEN
CREATE TYPE return_status AS ENUM ('requested','approved','rejected','received','restocked','closed');
END IF;
IF NOT EXISTS (SELECT 1 FROM pg_type WHERE typname = 'inventory_alert_type') THEN
CREATE TYPE inventory_alert_type AS ENUM ('OUT_OF_STOCK','LOW_STOCK','IN_STOCK');
END IF;
IF NOT EXISTS (SELECT 1 FROM pg_type WHERE typname = 'discount_type') THEN
CREATE TYPE discount_type AS ENUM ('percentage','fixed');
END IF;
IF NOT EXISTS (SELECT 1 FROM pg_type WHERE typname = 'inventory_item_type') THEN
CREATE TYPE inventory_item_type AS ENUM ('product','variant');
END IF;
IF NOT EXISTS (SELECT 1 FROM pg_type WHERE typname = 'ticket_status') THEN
CREATE TYPE ticket_status AS ENUM ('open', 'waiting_on_admin', 'waiting_on_customer', 'closed');
END IF;
IF NOT EXISTS (SELECT 1 FROM pg_type WHERE typname = 'support_ticket_kind') THEN
CREATE TYPE support_ticket_kind AS ENUM ('general', 'product_support', 'refund_request');
END IF;
END$$;
-- helper function to update the updated_at timestamp
CREATE OR REPLACE FUNCTION fn_touch_updated_at()
RETURNS TRIGGER
LANGUAGE PLPGSQL
AS $$
BEGIN
NEW.updated_at := NOW();
RETURN NEW;
END$$;
-- User table
CREATE TABLE IF NOT EXISTS users (
id BIGSERIAL PRIMARY KEY,
role user_role NOT NULL DEFAULT 'customer',
name TEXT NOT NULL,
email CITEXT NOT NULL UNIQUE,
email_verified_at TIMESTAMPTZ,
-- store hash only Argon2id or bcrypt
password_hash TEXT NOT NULL,
CONSTRAINT users_password_hash_ck CHECK (
password_hash ~ '^\$argon2id\$' OR password_hash ~ '^\$2[aby]\$'
),
-- Force password change after a year since password_changed_at
password_must_change BOOLEAN NOT NULL DEFAULT FALSE,
password_changed_at TIMESTAMPTZ,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
CREATE OR REPLACE TRIGGER trg_users_touch_upd BEFORE UPDATE ON users
FOR EACH ROW EXECUTE FUNCTION fn_touch_updated_at();
-- Tickets for contact system
CREATE TABLE IF NOT EXISTS support_tickets (
id BIGSERIAL PRIMARY KEY,
created_by_user_id BIGINT REFERENCES users(id) ON DELETE SET NULL, -- requester (customer)
subject TEXT NOT NULL,
status ticket_status NOT NULL DEFAULT 'open',
ticket_kind support_ticket_kind NOT NULL DEFAULT 'general',
order_id BIGINT,
order_item_id BIGINT,
product_id BIGINT,
variant_id BIGINT,
assigned_to_user_id BIGINT REFERENCES users(id) ON DELETE SET NULL, -- optional, which admin owns it
last_message_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), -- for sorting inboxes
closed_at TIMESTAMPTZ,
closed_by_user_id BIGINT REFERENCES users(id) ON DELETE SET NULL, -- admin who closed it
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
ALTER TABLE support_tickets ADD COLUMN IF NOT EXISTS ticket_kind support_ticket_kind NOT NULL DEFAULT 'general';
ALTER TABLE support_tickets ADD COLUMN IF NOT EXISTS order_id BIGINT;
ALTER TABLE support_tickets ADD COLUMN IF NOT EXISTS order_item_id BIGINT;
ALTER TABLE support_tickets ADD COLUMN IF NOT EXISTS product_id BIGINT;
ALTER TABLE support_tickets ADD COLUMN IF NOT EXISTS variant_id BIGINT;
CREATE INDEX IF NOT EXISTS idx_support_tickets_status ON support_tickets(status);
CREATE INDEX IF NOT EXISTS idx_support_tickets_created_by ON support_tickets(created_by_user_id);
CREATE INDEX IF NOT EXISTS idx_support_tickets_assigned_to ON support_tickets(assigned_to_user_id);
CREATE INDEX IF NOT EXISTS idx_support_tickets_last_msg ON support_tickets(last_message_at DESC);
CREATE INDEX IF NOT EXISTS idx_support_tickets_kind ON support_tickets(ticket_kind);
CREATE INDEX IF NOT EXISTS idx_support_tickets_order_id ON support_tickets(order_id);
CREATE INDEX IF NOT EXISTS idx_support_tickets_order_item_id ON support_tickets(order_item_id);
CREATE INDEX IF NOT EXISTS idx_support_tickets_product_id ON support_tickets(product_id);
CREATE OR REPLACE TRIGGER trg_support_tickets_touch_upd BEFORE UPDATE ON support_tickets
FOR EACH ROW EXECUTE FUNCTION fn_touch_updated_at();
-- Ticket Messages
CREATE TABLE IF NOT EXISTS support_messages (
id BIGSERIAL PRIMARY KEY,
ticket_id BIGINT NOT NULL REFERENCES support_tickets(id) ON DELETE CASCADE,
sender_user_id BIGINT REFERENCES users(id) ON DELETE SET NULL, -- customer or admin
body TEXT NOT NULL,
is_internal BOOLEAN NOT NULL DEFAULT FALSE, -- admin-only note
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
CREATE INDEX IF NOT EXISTS idx_support_messages_ticket ON support_messages(ticket_id);
CREATE INDEX IF NOT EXISTS idx_support_messages_created_at ON support_messages(created_at);
-- Customer profile and addresses
CREATE TABLE IF NOT EXISTS customer_profiles (
user_id BIGINT PRIMARY KEY REFERENCES users(id) ON DELETE CASCADE,
phone VARCHAR(30),
date_of_birth DATE,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
CREATE OR REPLACE TRIGGER trg_customer_profiles_touch_upd BEFORE UPDATE ON customer_profiles
FOR EACH ROW EXECUTE FUNCTION fn_touch_updated_at();
CREATE TABLE IF NOT EXISTS addresses (
id BIGSERIAL PRIMARY KEY,
user_id BIGINT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
label TEXT, -- "Home", "Office"
recipient_name TEXT,
line1 TEXT NOT NULL,
line2 TEXT,
city TEXT NOT NULL,
region TEXT,
postal_code TEXT NOT NULL,
is_default_shipping BOOLEAN NOT NULL DEFAULT FALSE,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
CREATE UNIQUE INDEX IF NOT EXISTS ux_addresses_default_shipping ON addresses(user_id) WHERE is_default_shipping;
CREATE INDEX IF NOT EXISTS idx_addresses_user_id ON addresses(user_id);
CREATE OR REPLACE TRIGGER trg_addresses_touch_upd BEFORE UPDATE ON addresses
FOR EACH ROW EXECUTE FUNCTION fn_touch_updated_at();
-- Product Information (Miscellaneous)
CREATE TABLE IF NOT EXISTS brands (
id BIGSERIAL PRIMARY KEY,
name TEXT NOT NULL UNIQUE,
slug TEXT NOT NULL UNIQUE,
description TEXT, -- TODO: might not be needed
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
CONSTRAINT brands_slug_ck CHECK (slug = LOWER(slug) AND slug ~ '^[a-z0-9]+(?:-[a-z0-9]+)*$')
);
CREATE OR REPLACE TRIGGER trg_brands_touch_upd BEFORE UPDATE ON brands
FOR EACH ROW EXECUTE FUNCTION fn_touch_updated_at();
CREATE TABLE IF NOT EXISTS categories (
id BIGSERIAL PRIMARY KEY,
parent_id BIGINT REFERENCES categories(id) ON DELETE SET NULL,
name TEXT NOT NULL,
slug TEXT NOT NULL UNIQUE,
description TEXT,
sort_order INT NOT NULL DEFAULT 0,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
CONSTRAINT categories_name_ck CHECK (LENGTH(name) > 0),
CONSTRAINT categories_sibling_sort_unique UNIQUE (parent_id, sort_order) DEFERRABLE INITIALLY DEFERRED,
CONSTRAINT categories_slug_ck CHECK (slug = LOWER(slug) AND slug ~ '^[a-z0-9]+(?:-[a-z0-9]+)*$')
);
CREATE INDEX IF NOT EXISTS idx_categories_parent_id ON categories(parent_id);
CREATE TABLE IF NOT EXISTS products (
id BIGSERIAL PRIMARY KEY,
category_id BIGINT NOT NULL REFERENCES categories(id) ON DELETE RESTRICT,
brand_id BIGINT REFERENCES brands(id) ON DELETE SET NULL,
name TEXT NOT NULL,
slug TEXT NOT NULL UNIQUE,
sku TEXT UNIQUE, -- for simple products
status product_status NOT NULL DEFAULT 'draft',
summary TEXT,
description TEXT,
price NUMERIC(12,2) NOT NULL DEFAULT 0.00, -- simple product price
stock_quantity INT NOT NULL DEFAULT 0, -- simple product stock
has_variants BOOLEAN NOT NULL DEFAULT FALSE,
low_stock_threshold INT NOT NULL DEFAULT 5,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
CONSTRAINT products_price_ck CHECK (price >= 0),
CONSTRAINT products_stock_ck CHECK (stock_quantity >= 0),
CONSTRAINT products_slug_ck CHECK (slug = LOWER(slug) AND slug ~ '^[a-z0-9]+(?:-[a-z0-9]+)*$')
);
CREATE INDEX IF NOT EXISTS idx_products_category_id ON products(category_id);
CREATE INDEX IF NOT EXISTS idx_products_brand_id ON products(brand_id);
CREATE INDEX IF NOT EXISTS idx_products_status ON products(status);
CREATE INDEX IF NOT EXISTS idx_products_price ON products(price);
-- FTS (name > description)
DROP INDEX IF EXISTS idx_products_fts;
CREATE INDEX IF NOT EXISTS idx_products_fts ON products USING GIN (
(
setweight(to_tsvector('english', COALESCE(name,'')), 'A') ||
setweight(to_tsvector('english', COALESCE(summary,'')), 'B') ||
setweight(to_tsvector('english', COALESCE(description,'')), 'C')
)
)
WHERE status = 'active';
CREATE INDEX IF NOT EXISTS idx_products_name_trgm
ON products USING GIN (name gin_trgm_ops)
WHERE status='active';
CREATE INDEX IF NOT EXISTS idx_products_summary_trgm
ON products USING GIN (summary gin_trgm_ops)
WHERE status = 'active';
CREATE INDEX IF NOT EXISTS idx_products_description_trgm
ON products USING GIN (description gin_trgm_ops)
WHERE status = 'active';
CREATE OR REPLACE TRIGGER trg_products_touch_upd BEFORE UPDATE ON products
FOR EACH ROW EXECUTE FUNCTION fn_touch_updated_at();
CREATE TABLE IF NOT EXISTS product_images (
id BIGSERIAL PRIMARY KEY,
product_id BIGINT NOT NULL REFERENCES products(id) ON DELETE CASCADE,
url TEXT NOT NULL,
alt_text TEXT,
sort_order INT NOT NULL DEFAULT 0,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
CONSTRAINT product_images_sort_unique
UNIQUE (product_id, sort_order)
DEFERRABLE INITIALLY DEFERRED
);
CREATE INDEX IF NOT EXISTS idx_product_images_product_id ON product_images(product_id);
-- Options/Variants
CREATE TABLE IF NOT EXISTS option_types (
id BIGSERIAL PRIMARY KEY,
name TEXT NOT NULL UNIQUE,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
CREATE TABLE IF NOT EXISTS option_values (
id BIGSERIAL PRIMARY KEY,
option_type_id BIGINT NOT NULL REFERENCES option_types(id) ON DELETE CASCADE,
value TEXT NOT NULL,
UNIQUE(option_type_id, value)
);
CREATE INDEX IF NOT EXISTS idx_option_values_type ON option_values(option_type_id);
CREATE TABLE IF NOT EXISTS product_option_types (
product_id BIGINT NOT NULL REFERENCES products(id) ON DELETE CASCADE,
option_type_id BIGINT NOT NULL REFERENCES option_types(id) ON DELETE RESTRICT,
PRIMARY KEY (product_id, option_type_id)
);
CREATE TABLE IF NOT EXISTS product_variants (
id BIGSERIAL PRIMARY KEY,
product_id BIGINT NOT NULL REFERENCES products(id) ON DELETE CASCADE,
sku TEXT NOT NULL UNIQUE,
title TEXT, -- "Black / Large"
price NUMERIC(12,2) NOT NULL,
stock_quantity INT NOT NULL DEFAULT 0,
low_stock_threshold INT NOT NULL DEFAULT 5,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
CONSTRAINT product_variants_price_ck CHECK (price >= 0),
CONSTRAINT product_variants_stock_ck CHECK (stock_quantity >= 0)
);
CREATE INDEX IF NOT EXISTS idx_product_variants_product_id ON product_variants(product_id);
CREATE INDEX IF NOT EXISTS idx_product_variants_product_price ON product_variants(product_id, price);
CREATE OR REPLACE TRIGGER trg_product_variants_touch_upd BEFORE UPDATE ON product_variants
FOR EACH ROW EXECUTE FUNCTION fn_touch_updated_at();
CREATE TABLE IF NOT EXISTS product_variant_option_values (
variant_id BIGINT NOT NULL REFERENCES product_variants(id) ON DELETE CASCADE,
option_value_id BIGINT NOT NULL REFERENCES option_values(id) ON DELETE RESTRICT,
PRIMARY KEY (variant_id, option_value_id)
);
-- Cart
CREATE TABLE IF NOT EXISTS shopping_carts (
id BIGSERIAL PRIMARY KEY,
user_id BIGINT REFERENCES users(id) ON DELETE SET NULL, -- guest carts allowed
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
CREATE UNIQUE INDEX IF NOT EXISTS ux_carts_one_per_user
ON shopping_carts(user_id)
WHERE user_id IS NOT NULL;
CREATE INDEX IF NOT EXISTS idx_carts_user_id ON shopping_carts(user_id);
CREATE OR REPLACE TRIGGER trg_carts_touch_upd BEFORE UPDATE ON shopping_carts
FOR EACH ROW EXECUTE FUNCTION fn_touch_updated_at();
CREATE TABLE IF NOT EXISTS cart_items (
id BIGSERIAL PRIMARY KEY,
cart_id BIGINT NOT NULL REFERENCES shopping_carts(id) ON DELETE CASCADE,
product_id BIGINT NOT NULL REFERENCES products(id) ON DELETE RESTRICT,
variant_id BIGINT REFERENCES product_variants(id) ON DELETE RESTRICT,
quantity INT NOT NULL CHECK (quantity > 0),
unit_price NUMERIC(12,2) NOT NULL CHECK (unit_price >= 0), -- snapshot at add time
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
-- one item per (cart, product) when variant_id IS NULL
CREATE UNIQUE INDEX IF NOT EXISTS ux_cart_items_no_variant
ON cart_items(cart_id, product_id)
WHERE variant_id IS NULL;
-- one item per (cart, product, variant) when variant_id IS NOT NULL
CREATE UNIQUE INDEX IF NOT EXISTS ux_cart_items_with_variant
ON cart_items(cart_id, product_id, variant_id)
WHERE variant_id IS NOT NULL;
CREATE INDEX IF NOT EXISTS idx_cart_items_cart_id ON cart_items(cart_id);
-- Orders / discount / shipments / returns
CREATE TABLE IF NOT EXISTS orders (
id BIGSERIAL PRIMARY KEY,
user_id BIGINT REFERENCES users(id) ON DELETE SET NULL,
status order_status NOT NULL DEFAULT 'pending',
total_amount NUMERIC(12,2) NOT NULL DEFAULT 0.00, -- the amount that is charged
subtotal_amount NUMERIC(12,2) NOT NULL DEFAULT 0.00, -- the total before discount
discount_total NUMERIC(12,2) NOT NULL DEFAULT 0.00, -- the discounted amount
billing_address_id BIGINT REFERENCES addresses(id) ON DELETE SET NULL,
shipping_address_id BIGINT REFERENCES addresses(id) ON DELETE SET NULL,
notes TEXT,
placed_at TIMESTAMPTZ,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
CREATE INDEX IF NOT EXISTS idx_orders_user_id ON orders(user_id);
CREATE INDEX IF NOT EXISTS idx_orders_status ON orders(status);
CREATE OR REPLACE TRIGGER trg_orders_touch_upd BEFORE UPDATE ON orders
FOR EACH ROW EXECUTE FUNCTION fn_touch_updated_at();
CREATE TABLE IF NOT EXISTS discount_codes (
id BIGSERIAL PRIMARY KEY,
code TEXT NOT NULL UNIQUE,
type discount_type NOT NULL,
amount NUMERIC(12,2) NOT NULL CHECK (amount > 0),
max_uses INT,
max_uses_per_user INT,
min_order_total NUMERIC(12,2),
starts_at TIMESTAMPTZ,
expires_at TIMESTAMPTZ,
is_active BOOLEAN NOT NULL DEFAULT TRUE,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
CREATE OR REPLACE TRIGGER trg_discount_codes_touch_upd BEFORE UPDATE ON discount_codes
FOR EACH ROW EXECUTE FUNCTION fn_touch_updated_at();
CREATE TABLE IF NOT EXISTS discount_redemptions (
id BIGSERIAL PRIMARY KEY,
discount_code_id BIGINT NOT NULL REFERENCES discount_codes(id) ON DELETE CASCADE,
order_id BIGINT NOT NULL REFERENCES orders(id) ON DELETE CASCADE,
user_id BIGINT REFERENCES users(id) ON DELETE SET NULL,
amount_applied NUMERIC(12,2) NOT NULL CHECK (amount_applied >= 0),
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
UNIQUE (discount_code_id, order_id)
);
CREATE TABLE IF NOT EXISTS order_items (
id BIGSERIAL PRIMARY KEY,
order_id BIGINT NOT NULL REFERENCES orders(id) ON DELETE CASCADE,
product_id BIGINT NOT NULL REFERENCES products(id) ON DELETE RESTRICT,
variant_id BIGINT REFERENCES product_variants(id) ON DELETE RESTRICT,
name_snapshot TEXT NOT NULL,
sku_snapshot TEXT,
unit_price NUMERIC(12,2) NOT NULL CHECK (unit_price >= 0),
quantity INT NOT NULL CHECK (quantity > 0),
line_total NUMERIC(12,2) NOT NULL CHECK (line_total >= 0),
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
CREATE INDEX IF NOT EXISTS idx_order_items_order_id ON order_items(order_id);
CREATE TABLE IF NOT EXISTS shipments (
id BIGSERIAL PRIMARY KEY,
order_id BIGINT NOT NULL REFERENCES orders(id) ON DELETE CASCADE,
carrier TEXT,
tracking_number TEXT,
shipped_at TIMESTAMPTZ,
delivered_at TIMESTAMPTZ,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
CREATE INDEX IF NOT EXISTS idx_shipments_order_id ON shipments(order_id);
CREATE TABLE IF NOT EXISTS return_requests (
id BIGSERIAL PRIMARY KEY,
order_item_id BIGINT NOT NULL REFERENCES order_items(id) ON DELETE CASCADE,
user_id BIGINT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
quantity INT NOT NULL CHECK (quantity > 0),
reason TEXT,
status return_status NOT NULL DEFAULT 'requested',
processed_by BIGINT REFERENCES users(id) ON DELETE SET NULL, -- admin
approved_quantity INT,
restock BOOLEAN,
requested_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
processed_at TIMESTAMPTZ
);
CREATE INDEX IF NOT EXISTS idx_returns_user ON return_requests(user_id);
CREATE INDEX IF NOT EXISTS idx_returns_status ON return_requests(status);
DO $$
BEGIN
IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'fk_support_tickets_order_id') THEN
ALTER TABLE support_tickets
ADD CONSTRAINT fk_support_tickets_order_id
FOREIGN KEY (order_id) REFERENCES orders(id) ON DELETE SET NULL;
END IF;
IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'fk_support_tickets_order_item_id') THEN
ALTER TABLE support_tickets
ADD CONSTRAINT fk_support_tickets_order_item_id
FOREIGN KEY (order_item_id) REFERENCES order_items(id) ON DELETE SET NULL;
END IF;
IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'fk_support_tickets_product_id') THEN
ALTER TABLE support_tickets
ADD CONSTRAINT fk_support_tickets_product_id
FOREIGN KEY (product_id) REFERENCES products(id) ON DELETE SET NULL;
END IF;
IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'fk_support_tickets_variant_id') THEN
ALTER TABLE support_tickets
ADD CONSTRAINT fk_support_tickets_variant_id
FOREIGN KEY (variant_id) REFERENCES product_variants(id) ON DELETE SET NULL;
END IF;
END$$;
-- Inventory ledger + alerts
CREATE TABLE IF NOT EXISTS inventory_transactions (
id BIGSERIAL PRIMARY KEY,
product_id BIGINT NOT NULL REFERENCES products(id) ON DELETE RESTRICT,
variant_id BIGINT REFERENCES product_variants(id) ON DELETE RESTRICT,
quantity_change INT NOT NULL, -- +in / -out
reason TEXT NOT NULL, -- "order_placed","order_cancelled","manual_adjustment","incoming_stock","return_received"
order_id BIGINT REFERENCES orders(id) ON DELETE SET NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
CONSTRAINT inventory_qty_nonzero CHECK (quantity_change <> 0)
);
CREATE INDEX IF NOT EXISTS idx_inventory_product ON inventory_transactions(product_id, variant_id);
CREATE INDEX IF NOT EXISTS idx_inventory_order ON inventory_transactions(order_id);
CREATE TABLE IF NOT EXISTS inventory_alerts (
id BIGSERIAL PRIMARY KEY,
item_type inventory_item_type NOT NULL, -- "product" | "variant"
product_id BIGINT NOT NULL,
variant_id BIGINT,
previous_qty INT,
new_qty INT,
alert_type inventory_alert_type NOT NULL, -- "OUT_OF_STOCK","LOW_STOCK","IN_STOCK"
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
CONSTRAINT inventory_alerts_item_type_ck CHECK (
(item_type = 'product' AND variant_id IS NULL)
OR
(item_type = 'variant' AND variant_id IS NOT NULL)
)
);
CREATE INDEX IF NOT EXISTS idx_inventory_alerts_product ON inventory_alerts(product_id);
CREATE INDEX IF NOT EXISTS idx_inventory_alerts_variant ON inventory_alerts(variant_id);
CREATE OR REPLACE FUNCTION fn_emit_stock_alert_product()
RETURNS TRIGGER
LANGUAGE PLPGSQL
AS $$
DECLARE
v_alert inventory_alert_type;
BEGIN
IF NEW.stock_quantity <= 0 AND (OLD.stock_quantity IS NULL OR OLD.stock_quantity > 0) THEN
v_alert := 'OUT_OF_STOCK';
ELSIF NEW.stock_quantity > 0 AND (OLD.stock_quantity IS NULL OR OLD.stock_quantity <= 0) THEN
v_alert := 'IN_STOCK';
ELSIF NEW.stock_quantity <= NEW.low_stock_threshold
AND (OLD.stock_quantity IS NULL OR OLD.stock_quantity > NEW.low_stock_threshold) THEN
v_alert := 'LOW_STOCK';
END IF;
IF v_alert IS NOT NULL THEN
INSERT INTO inventory_alerts(item_type, product_id, previous_qty, new_qty, alert_type)
VALUES ('product', NEW.id, COALESCE(OLD.stock_quantity, 0), NEW.stock_quantity, v_alert);
PERFORM pg_notify(
'stock_alerts',
json_build_object(
'item_type','product',
'product_id',NEW.id,
'alert_type',v_alert,
'qty',NEW.stock_quantity
)::TEXT
);
END IF;
RETURN NEW;
END$$;
CREATE OR REPLACE FUNCTION fn_emit_stock_alert_variant()
RETURNS TRIGGER
LANGUAGE PLPGSQL
AS $$
DECLARE
v_alert inventory_alert_type;
BEGIN
IF NEW.stock_quantity <= 0 AND (OLD.stock_quantity IS NULL OR OLD.stock_quantity > 0) THEN
v_alert := 'OUT_OF_STOCK';
ELSIF NEW.stock_quantity > 0 AND (OLD.stock_quantity IS NULL OR OLD.stock_quantity <= 0) THEN
v_alert := 'IN_STOCK';
ELSIF NEW.stock_quantity <= NEW.low_stock_threshold
AND (OLD.stock_quantity IS NULL OR OLD.stock_quantity > NEW.low_stock_threshold) THEN
v_alert := 'LOW_STOCK';
END IF;
IF v_alert IS NOT NULL THEN
INSERT INTO inventory_alerts(item_type, product_id, variant_id, previous_qty, new_qty, alert_type)
VALUES ('variant', NEW.product_id, NEW.id, COALESCE(OLD.stock_quantity, 0), NEW.stock_quantity, v_alert);
PERFORM pg_notify(
'stock_alerts',
json_build_object(
'item_type','variant',
'product_id',NEW.product_id,
'variant_id',NEW.id,
'alert_type',v_alert,
'qty',NEW.stock_quantity
)::TEXT
);
END IF;
RETURN NEW;
END$$;
CREATE OR REPLACE TRIGGER trg_products_stock_alert
AFTER INSERT OR UPDATE OF stock_quantity ON products
FOR EACH ROW EXECUTE FUNCTION fn_emit_stock_alert_product();
CREATE OR REPLACE TRIGGER trg_variants_stock_alert
AFTER INSERT OR UPDATE OF stock_quantity ON product_variants
FOR EACH ROW EXECUTE FUNCTION fn_emit_stock_alert_variant();
-- Reviews
CREATE TABLE IF NOT EXISTS product_reviews (
id BIGSERIAL PRIMARY KEY,
product_id BIGINT NOT NULL REFERENCES products(id) ON DELETE CASCADE,
user_id BIGINT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
order_item_id BIGINT REFERENCES order_items(id) ON DELETE SET NULL, -- for verified purchase
rating INT NOT NULL CHECK (rating BETWEEN 1 AND 5),
title TEXT,
body TEXT,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
UNIQUE (product_id, user_id)
);
CREATE INDEX IF NOT EXISTS idx_product_reviews_product ON product_reviews(product_id);
CREATE INDEX IF NOT EXISTS idx_product_reviews_user ON product_reviews(user_id);
CREATE INDEX IF NOT EXISTS idx_product_reviews_order_item ON product_reviews(order_item_id);
CREATE INDEX IF NOT EXISTS idx_product_reviews_created_at ON product_reviews(created_at DESC);
CREATE TABLE IF NOT EXISTS service_reviews (
id BIGSERIAL PRIMARY KEY,
user_id BIGINT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
rating INT NOT NULL CHECK (rating BETWEEN 1 AND 5),
comment TEXT,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
UNIQUE (user_id)
);
CREATE INDEX IF NOT EXISTS idx_service_reviews_created_at ON service_reviews(created_at DESC);
CREATE OR REPLACE FUNCTION fn_get_product_review_summary(p_product_id BIGINT)
RETURNS TABLE(
average_rating NUMERIC(4,2),
review_count BIGINT,
verified_review_count BIGINT,
five_star_count BIGINT,
four_star_count BIGINT,
three_star_count BIGINT,
two_star_count BIGINT,
one_star_count BIGINT
)
LANGUAGE SQL
AS $$
SELECT
COALESCE(ROUND(AVG(r.rating)::numeric, 2), 0.00)::NUMERIC(4,2) AS average_rating,
COUNT(*)::BIGINT AS review_count,
COUNT(r.order_item_id)::BIGINT AS verified_review_count,
COUNT(*) FILTER (WHERE r.rating = 5)::BIGINT AS five_star_count,
COUNT(*) FILTER (WHERE r.rating = 4)::BIGINT AS four_star_count,
COUNT(*) FILTER (WHERE r.rating = 3)::BIGINT AS three_star_count,
COUNT(*) FILTER (WHERE r.rating = 2)::BIGINT AS two_star_count,
COUNT(*) FILTER (WHERE r.rating = 1)::BIGINT AS one_star_count
FROM product_reviews r
WHERE r.product_id = p_product_id;
$$;
CREATE OR REPLACE FUNCTION fn_get_service_review_summary()
RETURNS TABLE(
average_rating NUMERIC(4,2),
review_count BIGINT,
five_star_count BIGINT,
four_star_count BIGINT,
three_star_count BIGINT,
two_star_count BIGINT,
one_star_count BIGINT
)
LANGUAGE SQL
AS $$
SELECT
COALESCE(ROUND(AVG(r.rating)::numeric, 2), 0.00)::NUMERIC(4,2) AS average_rating,
COUNT(*)::BIGINT AS review_count,
COUNT(*) FILTER (WHERE r.rating = 5)::BIGINT AS five_star_count,
COUNT(*) FILTER (WHERE r.rating = 4)::BIGINT AS four_star_count,
COUNT(*) FILTER (WHERE r.rating = 3)::BIGINT AS three_star_count,
COUNT(*) FILTER (WHERE r.rating = 2)::BIGINT AS two_star_count,
COUNT(*) FILTER (WHERE r.rating = 1)::BIGINT AS one_star_count
FROM service_reviews r;
$$;
CREATE OR REPLACE FUNCTION fn_get_review_eligible_order_items(p_user_id BIGINT, p_product_id BIGINT)
RETURNS TABLE(
order_item_id BIGINT,
order_id BIGINT,
variant_id BIGINT,
variant_title TEXT,
quantity INT,
unit_price NUMERIC(12,2),
order_completed_at TIMESTAMPTZ
)
LANGUAGE SQL
AS $$
SELECT
oi.id AS order_item_id,
oi.order_id,
oi.variant_id,
pv.title AS variant_title,
oi.quantity,
oi.unit_price,
COALESCE(o.updated_at, o.created_at) AS order_completed_at
FROM order_items oi
JOIN orders o ON o.id = oi.order_id
LEFT JOIN product_variants pv ON pv.id = oi.variant_id
WHERE o.user_id = p_user_id
AND oi.product_id = p_product_id
AND o.status = 'completed'
ORDER BY COALESCE(o.updated_at, o.created_at) DESC, oi.id DESC;
$$;
-- Search function
CREATE OR REPLACE FUNCTION fn_search_products(
query_text TEXT,
category_slugs TEXT[] DEFAULT NULL,
min_price NUMERIC DEFAULT NULL,
max_price NUMERIC DEFAULT NULL,
limit_count INT DEFAULT 20,
offset_count INT DEFAULT 0
)
RETURNS TABLE(
product_id BIGINT,
product_name TEXT,
product_slug TEXT,
product_price NUMERIC,
category_slug TEXT,
search_rank REAL
)
LANGUAGE SQL
AS $$
WITH q AS (
SELECT
NULLIF(BTRIM(COALESCE(query_text, ''), E' \t\n\r\f\v'), '') AS qt,
CASE
WHEN NULLIF(BTRIM(COALESCE(query_text, ''), E' \t\n\r\f\v'), '') IS NULL
THEN NULL
ELSE websearch_to_tsquery('english', NULLIF(BTRIM(COALESCE(query_text, ''), E' \t\n\r\f\v'), ''))
END AS tsq
),
d AS (
SELECT
p.*,
c.slug AS category_slug,
(
setweight(to_tsvector('english', COALESCE(p.name,'')), 'A') ||
setweight(to_tsvector('english', COALESCE(p.summary,'')), 'B') ||
setweight(to_tsvector('english', COALESCE(p.description,'')), 'C')
) AS doc
FROM products p
JOIN categories c ON c.id = p.category_id
)
SELECT
d.id AS product_id,
d.name AS product_name,
d.slug AS product_slug,
COALESCE(vmin.min_variant_price, d.price) AS product_price,
d.category_slug,
CASE
WHEN q.qt IS NULL OR COALESCE(q.tsq::TEXT, '') = '' THEN 0
ELSE ts_rank(d.doc, q.tsq)
END AS search_rank
FROM d
CROSS JOIN q
LEFT JOIN LATERAL (
SELECT MIN(v.price) AS min_variant_price
FROM product_variants v
WHERE v.product_id = d.id
) vmin ON TRUE
WHERE d.status = 'active'
AND (
q.qt IS NULL
OR
(
(COALESCE(q.tsq::TEXT, '') <> '' AND d.doc @@ q.tsq)
OR
(COALESCE(q.tsq::TEXT, '') = '' AND (
d.name ILIKE '%' || q.qt || '%'
OR COALESCE(d.summary,'') ILIKE '%' || q.qt || '%'
OR COALESCE(d.description,'') ILIKE '%' || q.qt || '%'
))
)
)
AND (category_slugs IS NULL OR d.category_slug = ANY(category_slugs))
AND (
(d.has_variants = FALSE AND
(min_price IS NULL OR d.price >= min_price) AND
(max_price IS NULL OR d.price <= max_price)
)
OR
(d.has_variants = TRUE AND EXISTS (
SELECT 1 FROM product_variants v
WHERE v.product_id = d.id
AND (min_price IS NULL OR v.price >= min_price)
AND (max_price IS NULL OR v.price <= max_price)
))
)
ORDER BY search_rank DESC, d.created_at DESC
LIMIT limit_count OFFSET offset_count;
$$;
-- Cart + checkout helpers
CREATE OR REPLACE FUNCTION fn_add_to_cart(
p_cart_id BIGINT,
p_product_id BIGINT,
p_variant_id BIGINT,
p_quantity INT,
p_unit_price NUMERIC
)
RETURNS VOID
LANGUAGE PLPGSQL
AS $$
BEGIN
IF p_variant_id IS NULL THEN
INSERT INTO cart_items (cart_id, product_id, variant_id, quantity, unit_price)
VALUES (p_cart_id, p_product_id, NULL, p_quantity, p_unit_price)
ON CONFLICT (cart_id, product_id) WHERE variant_id IS NULL
DO UPDATE
SET quantity = cart_items.quantity + EXCLUDED.quantity;
ELSE
INSERT INTO cart_items (cart_id, product_id, variant_id, quantity, unit_price)
VALUES (p_cart_id, p_product_id, p_variant_id, p_quantity, p_unit_price)
ON CONFLICT (cart_id, product_id, variant_id) WHERE variant_id IS NOT NULL
DO UPDATE
SET quantity = cart_items.quantity + EXCLUDED.quantity;
END IF;
END;
$$;
CREATE OR REPLACE FUNCTION fn_update_cart_item_quantity(
p_cart_item_id BIGINT,
p_quantity INT
)
RETURNS VOID
LANGUAGE PLPGSQL
AS $$
BEGIN
IF p_quantity <= 0 THEN
DELETE FROM cart_items WHERE id = p_cart_item_id;
ELSE
UPDATE cart_items SET quantity = p_quantity WHERE id = p_cart_item_id;
END IF;
END$$;
CREATE OR REPLACE FUNCTION fn_remove_from_cart(
p_cart_id BIGINT,
p_product_id BIGINT,
p_variant_id BIGINT
)
RETURNS VOID
LANGUAGE SQL
AS $$
DELETE FROM cart_items
WHERE cart_id = p_cart_id
AND product_id = p_product_id
AND ((p_variant_id IS NULL AND variant_id IS NULL) OR variant_id = p_variant_id);
$$;
CREATE OR REPLACE FUNCTION fn_preview_cart_discount(
p_cart_id BIGINT,
p_user_id BIGINT,
p_discount_code TEXT DEFAULT NULL
)
RETURNS TABLE (
subtotal_amount NUMERIC(12,2),
discount_total NUMERIC(12,2),
total_amount NUMERIC(12,2),
applied_code TEXT
)
LANGUAGE PLPGSQL
AS $$
DECLARE
v_now TIMESTAMPTZ := NOW();
v_subtotal NUMERIC(12,2);
v_discount NUMERIC(12,2) := 0;
v_total NUMERIC(12,2);
v_code_id BIGINT;
v_code_type discount_type;
v_code_amount NUMERIC(12,2);
v_max_uses INT;
v_max_uses_per_user INT;
v_min_order_total NUMERIC(12,2);
v_code_starts_at TIMESTAMPTZ;
v_code_expires_at TIMESTAMPTZ;
BEGIN
SELECT COALESCE(SUM(quantity * unit_price), 0)::NUMERIC(12,2)
INTO v_subtotal
FROM cart_items
WHERE cart_id = p_cart_id;
IF v_subtotal <= 0 THEN
RAISE EXCEPTION 'Cart % is empty', p_cart_id;
END IF;
IF p_discount_code IS NOT NULL THEN
SELECT
id,
type,
amount,
max_uses,
max_uses_per_user,
min_order_total,
starts_at,
expires_at
INTO
v_code_id,
v_code_type,
v_code_amount,
v_max_uses,
v_max_uses_per_user,
v_min_order_total,
v_code_starts_at,
v_code_expires_at
FROM discount_codes
WHERE code = p_discount_code
AND is_active = TRUE;
IF NOT FOUND THEN
RAISE EXCEPTION 'Invalid discount code';
END IF;
IF v_code_starts_at IS NOT NULL AND v_now < v_code_starts_at THEN
RAISE EXCEPTION 'Discount code not yet active';
END IF;
IF v_code_expires_at IS NOT NULL AND v_now >= v_code_expires_at THEN
RAISE EXCEPTION 'Discount code expired';
END IF;
IF v_min_order_total IS NOT NULL AND v_subtotal < v_min_order_total THEN
RAISE EXCEPTION 'Order subtotal % is below required minimum % for code %',
v_subtotal, v_min_order_total, p_discount_code;
END IF;
IF v_max_uses IS NOT NULL THEN
PERFORM 1
FROM discount_redemptions
WHERE discount_code_id = v_code_id
GROUP BY discount_code_id
HAVING COUNT(*) >= v_max_uses;
IF FOUND THEN
RAISE EXCEPTION 'Discount code usage limit reached';
END IF;
END IF;
IF v_max_uses_per_user IS NOT NULL AND p_user_id IS NOT NULL THEN
PERFORM 1
FROM discount_redemptions
WHERE discount_code_id = v_code_id
AND user_id = p_user_id
GROUP BY discount_code_id
HAVING COUNT(*) >= v_max_uses_per_user;
IF FOUND THEN
RAISE EXCEPTION 'You have used this discount code the maximum allowed times';
END IF;
END IF;
IF v_code_type = 'percentage' THEN
v_discount := ROUND(v_subtotal * (v_code_amount / 100.0), 2);
ELSE
v_discount := v_code_amount;
END IF;
IF v_discount > v_subtotal THEN
v_discount := v_subtotal;
END IF;
END IF;
v_total := v_subtotal - v_discount;
RETURN QUERY SELECT
v_subtotal,
v_discount,
v_total,
p_discount_code;
END$$;
-- Creates order from cart, posts inventory, clears cart
CREATE OR REPLACE FUNCTION fn_checkout_cart(
p_cart_id BIGINT,
p_user_id BIGINT,
p_billing_address_id BIGINT,
p_shipping_address_id BIGINT,
p_discount_code TEXT DEFAULT NULL
)
RETURNS BIGINT
LANGUAGE PLPGSQL