-- New enum values are only referenced as text below, so they are safe in this transaction. ALTER TYPE "OrderStatus" ADD VALUE 'CONFIRMED'; ALTER TYPE "OrderStatus" ADD VALUE 'SHIPPED'; ALTER TYPE "OrderStatus" ADD VALUE 'DELIVERED'; CREATE TYPE "PaymentMethod" AS ENUM ('COD', 'UPI_MANUAL'); ALTER TABLE orders ADD COLUMN payment_method "PaymentMethod"; CREATE TABLE order_status_events ( id UUID NOT NULL, order_id UUID NOT NULL, organization_id UUID NOT NULL, actor_id UUID NOT NULL, status "OrderStatus" NOT NULL, note VARCHAR(200) NOT NULL DEFAULT '', created_at TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, CONSTRAINT order_status_events_pkey PRIMARY KEY (id), CONSTRAINT order_status_events_order_id_organization_id_fkey FOREIGN KEY (order_id, organization_id) REFERENCES orders(id, organization_id) ON DELETE RESTRICT ON UPDATE CASCADE, CONSTRAINT order_status_events_actor_id_organization_id_fkey FOREIGN KEY (actor_id, organization_id) REFERENCES users(id, organization_id) ON DELETE RESTRICT ON UPDATE CASCADE ); CREATE INDEX order_status_events_order_id_created_at_id_idx ON order_status_events (order_id, created_at, id); CREATE FUNCTION protect_order_status_event() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN RAISE EXCEPTION 'Order status history is immutable'; END; $$; CREATE TRIGGER order_status_events_immutable BEFORE UPDATE OR DELETE ON order_status_events FOR EACH ROW EXECUTE FUNCTION protect_order_status_event(); -- Only status may change, and only along the fulfilment path. CREATE OR REPLACE FUNCTION protect_order_snapshot() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN IF TG_OP = 'DELETE' THEN RAISE EXCEPTION 'Orders cannot be deleted'; END IF; IF (to_jsonb(NEW) - 'status') IS DISTINCT FROM (to_jsonb(OLD) - 'status') THEN RAISE EXCEPTION 'Order snapshots are immutable'; END IF; IF OLD.status = 'CANCELLED' AND NEW.status <> 'CANCELLED' THEN RAISE EXCEPTION 'Cancelled orders cannot be reopened'; END IF; IF NEW.status IS DISTINCT FROM OLD.status AND NOT ( (OLD.status::text = 'PENDING_PAYMENT' AND NEW.status::text IN ('CONFIRMED', 'CANCELLED')) OR (OLD.status::text = 'CONFIRMED' AND NEW.status::text IN ('SHIPPED', 'CANCELLED')) OR (OLD.status::text = 'SHIPPED' AND NEW.status::text = 'DELIVERED') ) THEN RAISE EXCEPTION 'Invalid order status transition'; END IF; RETURN NEW; END; $$;