Files
sorsfonalak/crates/db/migrations/0035_gifts.sql
T

41 lines
2.0 KiB
SQL
Raw Normal View History

-- Gifts: a package of the main ladder paid for someone else. The buyer pays
-- as for any package (stripe_checkouts.gift_id); when the payment is
-- confirmed the gift gets its code, which is e-mailed to the recipient, or
-- the buyer hands it over (the gift card can be downloaded as a PDF).
-- A gift code is not a promo code: it cannot be withdrawn (it was paid for),
-- and it adds the whole package.
CREATE TABLE gifts (
id uuid PRIMARY KEY,
buyer_id uuid REFERENCES users (id) ON DELETE SET NULL,
package text NOT NULL,
-- Whom it is for (on the card and in the e-mail); cleared with the buyer's account.
recipient_name text,
-- Who gets it by e-mail; NULL: the buyer hands the card over.
recipient_email text,
-- The giver's name and message, on the card and in the e-mail.
from_name text,
message text,
created_at timestamptz NOT NULL DEFAULT now(),
-- Paid: the code is made (and sent).
paid_at timestamptz,
-- Upper case, without separators (shown in groups of four), like promo
-- codes, and never the same as one.
code text UNIQUE CHECK (code ~ '^[2-9A-HJKMNP-Z]{8,32}$'),
redeemed_by uuid REFERENCES users (id) ON DELETE SET NULL,
redeemed_at timestamptz,
order_id uuid REFERENCES package_orders (id) ON DELETE SET NULL,
-- E-mails to the recipient so far (sending again is limited).
sendings integer NOT NULL DEFAULT 0,
last_sent_at timestamptz,
CHECK (paid_at IS NULL OR code IS NOT NULL),
CHECK (redeemed_at IS NULL OR paid_at IS NOT NULL)
);
CREATE INDEX gifts_buyer_idx ON gifts (buyer_id, created_at DESC);
ALTER TABLE stripe_checkouts ADD COLUMN gift_id uuid UNIQUE REFERENCES gifts (id) ON DELETE SET NULL;
-- A redeemed gift is recorded as an order with source `gift`.
ALTER TABLE package_orders DROP CONSTRAINT package_orders_source_check;
ALTER TABLE package_orders ADD CONSTRAINT package_orders_source_check
CHECK (source IN ('admin', 'mock', 'stripe', 'promo', 'gift'));