- Referral links carry a random 8 character base32 code (rf_<code>) built from the bot username from getMe. Old ref_<id> links still work but are never shown. - The reward (REFERRAL_REWARD_SATS, old name REFERRAL_REWARD still read) is paid through the ledger once the invited user's first purchase settles, once per invited user, never for self-referrals. - REFERRAL_DAILY_CAP limits what an inviter earns per UTC day; rewards above it wait as pending and are paid on a later day by the billing loop. - /referral shows invited, converted, earned and pending, with Share, Copy link and QR code buttons. The Mini App Me page mirrors it. - Migration 00008: users.ref_code (unique) and referral_rewards, backfilled from earlier referral credits in the ledger. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
34 lines
1.6 KiB
SQL
34 lines
1.6 KiB
SQL
-- +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;
|