CREATE TABLE orders ( id uuid PRIMARY KEY, user_id uuid REFERENCES users (id) ON DELETE SET NULL, org_id uuid REFERENCES organizations (id) ON DELETE SET NULL, offer_id text NOT NULL, amount_kopecks bigint NOT NULL CHECK (amount_kopecks > 0), currency text NOT NULL DEFAULT 'RUB', status text NOT NULL DEFAULT 'pending' CHECK (status IN ('pending', 'paid')), created_at timestamptz NOT NULL DEFAULT now() ); CREATE INDEX orders_user_id_idx ON orders (user_id); CREATE TABLE payments ( id uuid PRIMARY KEY, provider_payment_id text NOT NULL UNIQUE, order_id uuid NOT NULL REFERENCES orders (id) ON DELETE CASCADE, amount_kopecks bigint NOT NULL, currency text NOT NULL, status text NOT NULL CHECK (status IN ('accepted', 'rejected')), created_at timestamptz NOT NULL DEFAULT now() ); CREATE TABLE entitlements ( id uuid PRIMARY KEY, user_id uuid REFERENCES users (id) ON DELETE CASCADE, org_id uuid REFERENCES organizations (id) ON DELETE CASCADE, offer_id text NOT NULL, status text NOT NULL DEFAULT 'active' CHECK (status IN ('active', 'suspended')), valid_until timestamptz, created_at timestamptz NOT NULL DEFAULT now(), CHECK ((user_id IS NULL) <> (org_id IS NULL)) ); CREATE UNIQUE INDEX entitlements_user_offer_idx ON entitlements (user_id, offer_id) WHERE user_id IS NOT NULL; CREATE UNIQUE INDEX entitlements_org_offer_idx ON entitlements (org_id, offer_id) WHERE org_id IS NOT NULL; CREATE TABLE billing_notifications ( id uuid PRIMARY KEY, entitlement_id uuid NOT NULL REFERENCES entitlements (id) ON DELETE CASCADE, kind text NOT NULL, valid_until timestamptz NOT NULL, created_at timestamptz NOT NULL DEFAULT now(), UNIQUE (entitlement_id, kind, valid_until) );