18 KiB
18 KiB
Subtask: Database Schema for Order Processing
Parent Task: Decomp/004 Subtask ID: Decomp-004-01 Dependencies: None
Description
Design and implement database schema for e-commerce order processing system. Support inventory management, order lifecycle, payment processing, and shipping with ACID guarantees for critical operations.
Requirements
- Products and inventory tracking
- Shopping cart persistence
- Order lifecycle management (pending → paid → shipped → delivered)
- Payment transaction records
- Shipping information and labels
- Order cancellation and refund tracking
- Customer addresses and profiles
- Order history and audit trail
Technical Specifications
Database choice: PostgreSQL for ACID compliance
Core schema:
-- ============================================
-- PRODUCTS AND INVENTORY
-- ============================================
CREATE TABLE products (
id BIGSERIAL PRIMARY KEY,
sku VARCHAR(50) NOT NULL UNIQUE,
name VARCHAR(500) NOT NULL,
description TEXT,
category_id INTEGER REFERENCES categories(id),
price DECIMAL(10, 2) NOT NULL CHECK (price >= 0),
cost_price DECIMAL(10, 2) CHECK (cost_price >= 0),
weight_grams INTEGER,
is_active BOOLEAN DEFAULT TRUE,
is_digital BOOLEAN DEFAULT FALSE,
metadata JSONB DEFAULT '{}'::jsonb,
created_at TIMESTAMP NOT NULL DEFAULT NOW(),
updated_at TIMESTAMP NOT NULL DEFAULT NOW()
);
CREATE INDEX idx_products_sku ON products(sku);
CREATE INDEX idx_products_category ON products(category_id);
CREATE INDEX idx_products_active ON products(is_active) WHERE is_active = TRUE;
CREATE TABLE categories (
id SERIAL PRIMARY KEY,
name VARCHAR(200) NOT NULL,
parent_id INTEGER REFERENCES categories(id),
path VARCHAR(500), -- e.g., "Electronics/Computers/Laptops"
metadata JSONB DEFAULT '{}'::jsonb,
created_at TIMESTAMP NOT NULL DEFAULT NOW()
);
CREATE INDEX idx_categories_parent ON categories(parent_id);
CREATE TABLE inventory_items (
id BIGSERIAL PRIMARY KEY,
product_id BIGINT NOT NULL REFERENCES products(id) ON DELETE CASCADE,
location_id INTEGER REFERENCES inventory_locations(id),
quantity_on_hand INTEGER NOT NULL DEFAULT 0 CHECK (quantity_on_hand >= 0),
quantity_reserved INTEGER NOT NULL DEFAULT 0 CHECK (quantity_reserved >= 0),
quantity_available INTEGER GENERATED ALWAYS AS (
quantity_on_hand - quantity_reserved
) STORED,
reorder_threshold INTEGER DEFAULT 10,
reorder_amount INTEGER DEFAULT 50,
last_restocked_at TIMESTAMP,
metadata JSONB DEFAULT '{}'::jsonb,
updated_at TIMESTAMP NOT NULL DEFAULT NOW(),
UNIQUE(product_id, location_id)
);
CREATE INDEX idx_inventory_product ON inventory_items(product_id);
CREATE INDEX idx_inventory_location ON inventory_items(location_id);
CREATE INDEX idx_inventory_reorder ON inventory_items(product_id)
WHERE quantity_available <= reorder_threshold;
CREATE TABLE inventory_locations (
id SERIAL PRIMARY KEY,
name VARCHAR(200) NOT NULL,
location_type VARCHAR(50) NOT NULL, -- 'warehouse', 'store', 'supplier'
address TEXT,
is_primary BOOLEAN DEFAULT FALSE,
metadata JSONB DEFAULT '{}'::jsonb,
created_at TIMESTAMP NOT NULL DEFAULT NOW()
);
-- Inventory reservation locks (for order processing)
CREATE TABLE inventory_reservations (
id BIGSERIAL PRIMARY KEY,
order_id BIGINT NOT NULL REFERENCES orders(id) ON DELETE CASCADE,
product_id BIGINT NOT NULL REFERENCES products(id),
quantity INTEGER NOT NULL CHECK (quantity > 0),
location_id INTEGER REFERENCES inventory_locations(id),
status VARCHAR(20) NOT NULL DEFAULT 'pending', -- pending, committed, released, expired
expires_at TIMESTAMP NOT NULL,
created_at TIMESTAMP NOT NULL DEFAULT NOW(),
committed_at TIMESTAMP
);
CREATE INDEX idx_reservations_order ON inventory_reservations(order_id);
CREATE INDEX idx_reservations_product ON inventory_reservations(product_id);
CREATE INDEX idx_reservations_status ON inventory_reservations(status, expires_at)
WHERE status = 'pending';
-- ============================================
-- CUSTOMERS
-- ============================================
CREATE TABLE customers (
id BIGSERIAL PRIMARY KEY,
email VARCHAR(255) NOT NULL UNIQUE,
password_hash VARCHAR(255),
first_name VARCHAR(100),
last_name VARCHAR(100),
phone VARCHAR(50),
date_of_birth DATE,
is_active BOOLEAN DEFAULT TRUE,
email_verified BOOLEAN DEFAULT FALSE,
metadata JSONB DEFAULT '{}'::jsonb,
created_at TIMESTAMP NOT NULL DEFAULT NOW(),
updated_at TIMESTAMP NOT NULL DEFAULT NOW(),
last_login_at TIMESTAMP
);
CREATE INDEX idx_customers_email ON customers(email);
CREATE INDEX idx_customers_active ON customers(is_active) WHERE is_active = TRUE;
CREATE TABLE customer_addresses (
id BIGSERIAL PRIMARY KEY,
customer_id BIGINT NOT NULL REFERENCES customers(id) ON DELETE CASCADE,
address_type VARCHAR(20) NOT NULL, -- 'billing', 'shipping'
is_default BOOLEAN DEFAULT FALSE,
first_name VARCHAR(100),
last_name VARCHAR(100),
company VARCHAR(200),
address_line1 VARCHAR(255) NOT NULL,
address_line2 VARCHAR(255),
city VARCHAR(100) NOT NULL,
state_province VARCHAR(100),
postal_code VARCHAR(20) NOT NULL,
country_code CHAR(2) NOT NULL,
phone VARCHAR(50),
metadata JSONB DEFAULT '{}'::jsonb,
created_at TIMESTAMP NOT NULL DEFAULT NOW(),
updated_at TIMESTAMP NOT NULL DEFAULT NOW()
);
CREATE INDEX idx_addresses_customer ON customer_addresses(customer_id, address_type);
-- ============================================
-- SHOPPING CARTS
-- ============================================
CREATE TABLE shopping_carts (
id BIGSERIAL PRIMARY KEY,
customer_id BIGINT REFERENCES customers(id) ON DELETE SET NULL,
session_id VARCHAR(255), -- For guest carts
created_at TIMESTAMP NOT NULL DEFAULT NOW(),
updated_at TIMESTAMP NOT NULL DEFAULT NOW(),
expires_at TIMESTAMP,
CHECK (customer_id IS NOT NULL OR session_id IS NOT NULL)
);
CREATE INDEX idx_carts_customer ON shopping_carts(customer_id);
CREATE INDEX idx_carts_session ON shopping_carts(session_id);
CREATE INDEX idx_carts_expires ON shopping_carts(expires_at)
WHERE expires_at > NOW();
CREATE TABLE 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),
quantity INTEGER NOT NULL CHECK (quantity > 0),
unit_price DECIMAL(10, 2) NOT NULL, -- Price at time of adding
product_snapshot JSONB, -- Product data snapshot
created_at TIMESTAMP NOT NULL DEFAULT NOW(),
updated_at TIMESTAMP NOT NULL DEFAULT NOW(),
UNIQUE(cart_id, product_id)
);
CREATE INDEX idx_cart_items_cart ON cart_items(cart_id);
-- ============================================
-- ORDERS
-- ============================================
CREATE TABLE orders (
id BIGSERIAL PRIMARY KEY,
order_number VARCHAR(50) NOT NULL UNIQUE,
customer_id BIGINT NOT NULL REFERENCES customers(id),
status VARCHAR(20) NOT NULL DEFAULT 'pending',
-- Status flow: pending -> processing -> paid -> shipped -> delivered
-- Alternative: pending -> cancelled
-- paid -> refunded
currency CHAR(3) NOT NULL DEFAULT 'USD',
subtotal DECIMAL(10, 2) NOT NULL CHECK (subtotal >= 0),
tax_amount DECIMAL(10, 2) NOT NULL DEFAULT 0 CHECK (tax_amount >= 0),
shipping_amount DECIMAL(10, 2) NOT NULL DEFAULT 0 CHECK (shipping_amount >= 0),
discount_amount DECIMAL(10, 2) NOT NULL DEFAULT 0 CHECK (discount_amount >= 0),
total_amount DECIMAL(10, 2) NOT NULL CHECK (total_amount >= 0),
paid_amount DECIMAL(10, 2) NOT NULL DEFAULT 0 CHECK (paid_amount >= 0),
refunded_amount DECIMAL(10, 2) NOT NULL DEFAULT 0 CHECK (refunded_amount >= 0),
-- Addresses (snapshotted at order time)
billing_address JSONB NOT NULL,
shipping_address JSONB NOT NULL,
-- Shipping
shipping_method VARCHAR(100),
shipping_carrier VARCHAR(100),
tracking_number VARCHAR(100),
estimated_delivery_at TIMESTAMP,
actual_delivery_at TIMESTAMP,
shipped_at TIMESTAMP,
-- Payment
payment_method VARCHAR(50),
payment_provider VARCHAR(50),
paid_at TIMESTAMP,
-- Timestamps
created_at TIMESTAMP NOT NULL DEFAULT NOW(),
updated_at TIMESTAMP NOT NULL DEFAULT NOW(),
completed_at TIMESTAMP,
cancelled_at TIMESTAMP,
cancelled_reason TEXT,
metadata JSONB DEFAULT '{}'::jsonb
);
CREATE INDEX idx_orders_customer ON orders(customer_id);
CREATE INDEX idx_orders_status ON orders(status);
CREATE INDEX idx_orders_created ON orders(created_at DESC);
CREATE INDEX idx_orders_number ON orders(order_number);
CREATE INDEX idx_orders_tracking ON orders(tracking_number);
CREATE TABLE 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),
sku VARCHAR(50) NOT NULL,
product_name VARCHAR(500) NOT NULL,
quantity INTEGER NOT NULL CHECK (quantity > 0),
unit_price DECIMAL(10, 2) NOT NULL,
tax_amount DECIMAL(10, 2) NOT NULL DEFAULT 0,
discount_amount DECIMAL(10, 2) NOT NULL DEFAULT 0,
total_amount DECIMAL(10, 2) NOT NULL,
product_snapshot JSONB,
created_at TIMESTAMP NOT NULL DEFAULT NOW()
);
CREATE INDEX idx_order_items_order ON order_items(order_id);
CREATE INDEX idx_order_items_product ON order_items(product_id);
-- ============================================
-- PAYMENTS
-- ============================================
CREATE TABLE payment_transactions (
id BIGSERIAL PRIMARY KEY,
order_id BIGINT NOT NULL REFERENCES orders(id),
transaction_id VARCHAR(100) NOT NULL UNIQUE, -- External provider ID
provider VARCHAR(50) NOT NULL, -- 'stripe', 'paypal', etc.
payment_method VARCHAR(50) NOT NULL, -- 'card', 'paypal', etc.
payment_method_details JSONB, -- Card last4, brand, etc.
amount DECIMAL(10, 2) NOT NULL,
currency CHAR(3) NOT NULL,
status VARCHAR(20) NOT NULL, -- pending, succeeded, failed, refunded
failure_reason TEXT,
created_at TIMESTAMP NOT NULL DEFAULT NOW(),
processed_at TIMESTAMP,
refunded_at TIMESTAMP,
metadata JSONB DEFAULT '{}'::jsonb
);
CREATE INDEX idx_payments_order ON payment_transactions(order_id);
CREATE INDEX idx_payments_transaction ON payment_transactions(transaction_id);
CREATE INDEX idx_payments_status ON payment_transactions(status);
-- Refunds
CREATE TABLE refunds (
id BIGSERIAL PRIMARY KEY,
payment_transaction_id BIGINT NOT NULL REFERENCES payment_transactions(id),
refund_id VARCHAR(100), -- External provider refund ID
amount DECIMAL(10, 2) NOT NULL,
reason TEXT,
status VARCHAR(20) NOT NULL, -- pending, succeeded, failed
created_at TIMESTAMP NOT NULL DEFAULT NOW(),
processed_at TIMESTAMP,
metadata JSONB DEFAULT '{}'::jsonb
);
CREATE INDEX idx_refunds_payment ON refunds(payment_transaction_id);
-- ============================================
-- SHIPPING
-- ============================================
CREATE TABLE shipping_labels (
id BIGSERIAL PRIMARY KEY,
order_id BIGINT NOT NULL REFERENCES orders(id),
label_id VARCHAR(100) NOT NULL UNIQUE, -- Provider label ID
provider VARCHAR(50) NOT NULL, -- 'ups', 'fedex', 'usps'
service_level VARCHAR(100), -- 'ground', 'express', etc.
tracking_number VARCHAR(100) NOT NULL,
shipment_cost DECIMAL(10, 2) NOT NULL,
label_data BYTEA, -- PDF label data
from_address JSONB NOT NULL,
to_address JSONB NOT NULL,
package_details JSONB, -- weight, dimensions
status VARCHAR(20) DEFAULT 'created', -- created, shipped, delivered, exception
created_at TIMESTAMP NOT NULL DEFAULT NOW(),
shipped_at TIMESTAMP,
delivered_at TIMESTAMP,
metadata JSONB DEFAULT '{}'::jsonb
);
CREATE INDEX idx_labels_order ON shipping_labels(order_id);
CREATE INDEX idx_labels_tracking ON shipping_labels(tracking_number);
-- ============================================
-- ORDER STATUS HISTORY
-- ============================================
CREATE TABLE order_status_history (
id BIGSERIAL PRIMARY KEY,
order_id BIGINT NOT NULL REFERENCES orders(id) ON DELETE CASCADE,
from_status VARCHAR(20),
to_status VARCHAR(20) NOT NULL,
reason TEXT,
changed_by VARCHAR(100), -- User or system
created_at TIMESTAMP NOT NULL DEFAULT NOW(),
metadata JSONB DEFAULT '{}'::jsonb
);
CREATE INDEX idx_status_history_order ON order_status_history(order_id, created_at DESC);
-- ============================================
-- NOTIFICATIONS
-- ============================================
CREATE TABLE notifications (
id BIGSERIAL PRIMARY KEY,
customer_id BIGINT REFERENCES customers(id) ON DELETE SET NULL,
order_id BIGINT REFERENCES orders(id) ON DELETE SET NULL,
type VARCHAR(50) NOT NULL, -- 'email', 'sms', 'push'
template VARCHAR(100) NOT NULL,
status VARCHAR(20) NOT NULL DEFAULT 'pending', -- pending, sent, failed
recipient VARCHAR(255) NOT NULL,
subject VARCHAR(500),
body TEXT,
metadata JSONB DEFAULT '{}'::jsonb,
created_at TIMESTAMP NOT NULL DEFAULT NOW(),
sent_at TIMESTAMP,
failed_at TIMESTAMP,
error_message TEXT
);
CREATE INDEX idx_notifications_customer ON notifications(customer_id);
CREATE INDEX idx_notifications_order ON notifications(order_id);
CREATE INDEX idx_notifications_status ON notifications(status);
-- ============================================
-- FUNCTIONS AND TRIGGERS
-- ============================================
-- Updated at trigger function
CREATE OR REPLACE FUNCTION update_updated_at()
RETURNS TRIGGER AS $$
BEGIN
NEW.updated_at = NOW();
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
-- Apply updated_at trigger
CREATE TRIGGER products_updated_at BEFORE UPDATE ON products
FOR EACH ROW EXECUTE FUNCTION update_updated_at();
CREATE TRIGGER customers_updated_at BEFORE UPDATE ON customers
FOR EACH ROW EXECUTE FUNCTION update_updated_at();
CREATE TRIGGER customer_addresses_updated_at BEFORE UPDATE ON customer_addresses
FOR EACH ROW EXECUTE FUNCTION update_updated_at();
CREATE TRIGGER shopping_carts_updated_at BEFORE UPDATE ON shopping_carts
FOR EACH ROW EXECUTE FUNCTION update_updated_at();
CREATE TRIGGER cart_items_updated_at BEFORE UPDATE ON cart_items
FOR EACH ROW EXECUTE FUNCTION update_updated_at();
CREATE TRIGGER orders_updated_at BEFORE UPDATE ON orders
FOR EACH ROW EXECUTE FUNCTION update_updated_at();
CREATE TRIGGER inventory_items_updated_at BEFORE UPDATE ON inventory_items
FOR EACH ROW EXECUTE FUNCTION update_updated_at();
-- Generate order number
CREATE OR REPLACE FUNCTION generate_order_number()
RETURNS TRIGGER AS $$
BEGIN
NEW.order_number := 'ORD-' || TO_CHAR(NOW(), 'YYYYMMDD') || '-' ||
LPAD(nextval('order_number_seq')::TEXT, 6, '0');
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
CREATE SEQUENCE order_number_seq;
CREATE TRIGGER orders_generate_number BEFORE INSERT ON orders
FOR EACH ROW EXECUTE FUNCTION generate_order_number();
-- Update cart totals
CREATE OR REPLACE FUNCTION update_cart_totals()
RETURNS TRIGGER AS $$
BEGIN
UPDATE shopping_carts
SET updated_at = NOW()
WHERE id = NEW.cart_id;
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
CREATE TRIGGER cart_items_update_totals AFTER INSERT OR UPDATE OR DELETE ON cart_items
FOR EACH ROW EXECUTE FUNCTION update_cart_totals();
-- Log order status changes
CREATE OR REPLACE FUNCTION log_order_status_change()
RETURNS TRIGGER AS $$
BEGIN
IF OLD.status IS DISTINCT FROM NEW.status THEN
INSERT INTO order_status_history (order_id, from_status, to_status)
VALUES (NEW.id, OLD.status, NEW.status);
END IF;
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
CREATE TRIGGER orders_log_status_change BEFORE UPDATE ON orders
FOR EACH ROW EXECUTE FUNCTION log_order_status_change();
-- ============================================
-- VIEWS FOR REPORTING
-- ============================================
-- Order summary view
CREATE VIEW order_summary AS
SELECT
o.id,
o.order_number,
o.customer_id,
o.status,
o.total_amount,
o.paid_amount,
o.refunded_amount,
o.created_at,
o.paid_at,
o.shipped_at,
COUNT(DISTINCT oi.id) as item_count,
SUM(oi.quantity) as total_quantity
FROM orders o
LEFT JOIN order_items oi ON oi.order_id = o.id
GROUP BY o.id;
-- Low inventory view
CREATE VIEW low_inventory AS
SELECT
p.id,
p.sku,
p.name,
i.quantity_on_hand,
i.quantity_reserved,
i.quantity_available,
i.reorder_threshold,
(i.quantity_available <= i.reorder_threshold) as needs_reorder
FROM products p
JOIN inventory_items i ON i.product_id = p.id
WHERE i.quantity_available <= i.reorder_threshold;
-- Daily sales view
CREATE VIEW daily_sales AS
SELECT
DATE(created_at) as date,
COUNT(*) as order_count,
SUM(total_amount) as total_sales,
SUM(paid_amount) as total_paid
FROM orders
WHERE status NOT IN ('pending', 'cancelled')
GROUP BY DATE(created_at);
Acceptance Criteria
- All tables created without errors
- Foreign key constraints enforced
- Check constraints validate data
- Indexes created for common queries
- Triggers fire correctly
- Views return expected data
- Order numbers generate uniquely
Notes
Trade-offs:
- JSONB for addresses: Snapshot at order time vs normalized. Chose snapshot for historical accuracy.
- Separate reservations table: Needed for concurrent order processing.
Scalability:
- Partition orders by date for large deployments
- Consider read replicas for reporting queries
Alternatives considered:
- NoSQL for orders: Rejected, need ACID for inventory
- Event sourcing: Added status history table as middle ground