-- +goose Up -- Referral links carry a random code instead of the inviter's Telegram ID. -- A user gets a code the first time they need one; '' means none yet. ALTER TABLE users ADD COLUMN ref_code TEXT NOT NULL DEFAULT ''; CREATE UNIQUE INDEX users_ref_code_idx ON users (ref_code) WHERE ref_code <> ''; -- One row per invited user who settled a first Lightning purchase: the -- reward their inviter earned for it. The primary key makes it one reward -- per invited user, ever. A reward over the inviter's daily cap waits as -- 'pending' and is paid (credited through the ledger) on a later day. CREATE TABLE referral_rewards ( invitee_id BIGINT PRIMARY KEY, referrer_id BIGINT NOT NULL, purchase_id TEXT NOT NULL DEFAULT '', amount BIGINT NOT NULL, status TEXT NOT NULL, -- paid or pending paid_day INTEGER NOT NULL DEFAULT 0, -- YYYYMMDD (UTC) it was paid on created_at BIGINT NOT NULL, paid_at BIGINT NOT NULL DEFAULT 0 ); CREATE INDEX referral_rewards_referrer_idx ON referral_rewards (referrer_id, status, paid_day); CREATE INDEX referral_rewards_pending_idx ON referral_rewards (status, created_at); -- Rewards paid before this table existed are in the ledger. INSERT INTO referral_rewards (invitee_id, referrer_id, purchase_id, amount, status, paid_day, created_at, paid_at) SELECT CAST(l.ref AS BIGINT), w.owner_id, '', l.amount, 'paid', 0, l.created_at, l.created_at FROM ledger l JOIN wallets w ON w.id = l.wallet_id WHERE l.reason = 'referral' AND w.owner_type = 'user' AND l.ref <> ''; -- +goose Down DROP TABLE referral_rewards; DROP INDEX users_ref_code_idx; ALTER TABLE users DROP COLUMN ref_code;