package db import ( "context" "crypto/rand" "encoding/base32" "errors" "strings" ) // RefCodeLength is the length of a referral code. const RefCodeLength = 8 // NewRefCode makes a random referral code: 8 characters of RFC 4648 // base32 (A to Z, 2 to 7), 40 random bits. func NewRefCode() string { var b [5]byte if _, err := rand.Read(b[:]); err != nil { panic(err) // the system has no randomness; nothing is safe then } return base32.StdEncoding.EncodeToString(b[:]) } // ValidRefCode reports whether s has the shape of a referral code. func ValidRefCode(s string) bool { if len(s) != RefCodeLength { return false } for _, r := range s { if !(r >= 'A' && r <= 'Z' || r >= '2' && r <= '7') { return false } } return true } // refCodeGen makes codes; tests replace it to force collisions. var refCodeGen = NewRefCode // RefCode returns the user's referral code, creating it on first use. A // collision with another user's code, which is rare with 40 bits, is // retried with a new code. func (s *Store) RefCode(ctx context.Context, userID int64) (string, error) { for attempt := 0; attempt < 8; attempt++ { var code string if err := s.row(ctx, `SELECT ref_code FROM users WHERE id = ?`, userID).Scan(&code); err != nil { return "", notFound(err) } if code != "" { return code, nil } _, err := s.exec(ctx, `UPDATE users SET ref_code = ? WHERE id = ? AND ref_code = ''`, refCodeGen(), userID) if err != nil && !isUniqueViolation(err) { return "", err } // Either it was stored, or another request stored one first, or the // code was taken: read again. } return "", errors.New("db: no free referral code") } // UserByRefCode finds the owner of a referral code. Codes are compared // in upper case, since some apps change the case of links. func (s *Store) UserByRefCode(ctx context.Context, code string) (*User, error) { code = strings.ToUpper(code) if !ValidRefCode(code) { return nil, ErrNotFound } return scanUser(s.row(ctx, `SELECT `+userCols+` FROM users WHERE ref_code = ?`, code)) } // Reward statuses. const ( RewardPaid = "paid" RewardPending = "pending" ) // ReferralReward is the reward an inviter earned for one invited user. type ReferralReward struct { InviteeID int64 ReferrerID int64 PurchaseID string Amount int64 Status string PaidDay int CreatedAt int64 PaidAt int64 } // AddReferralReward records a reward. It reports false when the invited // user already earned their inviter a reward. func (s *Store) AddReferralReward(ctx context.Context, r *ReferralReward) (bool, error) { n, err := s.exec(ctx, `INSERT INTO referral_rewards (invitee_id, referrer_id, purchase_id, amount, status, paid_day, created_at, paid_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT (invitee_id) DO NOTHING`, r.InviteeID, r.ReferrerID, r.PurchaseID, r.Amount, r.Status, r.PaidDay, r.CreatedAt, r.PaidAt) return n == 1, err } // MarkRewardPaid moves a pending reward to paid. It reports false when it // was not pending, so a reward is paid once. func (s *Store) MarkRewardPaid(ctx context.Context, inviteeID int64, day int, now int64) (bool, error) { n, err := s.exec(ctx, `UPDATE referral_rewards SET status = 'paid', paid_day = ?, paid_at = ? WHERE invitee_id = ? AND status = 'pending'`, day, now, inviteeID) return n == 1, err } // RewardsPaidOn sums what an inviter was paid in rewards on a day. func (s *Store) RewardsPaidOn(ctx context.Context, referrerID int64, day int) (int64, error) { var n int64 err := s.row(ctx, `SELECT COALESCE(SUM(amount), 0) FROM referral_rewards WHERE referrer_id = ? AND status = 'paid' AND paid_day = ?`, referrerID, day).Scan(&n) return n, err } // PendingRewards lists rewards waiting for their inviter's daily cap, // oldest first. func (s *Store) PendingRewards(ctx context.Context, limit int) ([]ReferralReward, error) { rows, err := s.rows(ctx, `SELECT invitee_id, referrer_id, purchase_id, amount, status, paid_day, created_at, paid_at FROM referral_rewards WHERE status = 'pending' ORDER BY created_at, invitee_id LIMIT ?`, limit) if err != nil { return nil, err } defer rows.Close() var out []ReferralReward for rows.Next() { var r ReferralReward if err := rows.Scan(&r.InviteeID, &r.ReferrerID, &r.PurchaseID, &r.Amount, &r.Status, &r.PaidDay, &r.CreatedAt, &r.PaidAt); err != nil { return nil, err } out = append(out, r) } return out, rows.Err() } // ReferralStats is what /referral shows an inviter. type ReferralStats struct { Invited int // users who joined through their link Converted int // of those, users who settled a first purchase Earned int64 // sats paid out Pending int64 // sats earned, waiting for the daily cap } // ReferralStatsFor sums up an inviter's referrals. func (s *Store) ReferralStatsFor(ctx context.Context, referrerID int64) (ReferralStats, error) { var st ReferralStats if err := s.row(ctx, `SELECT COUNT(*) FROM users WHERE referred_by = ?`, referrerID).Scan(&st.Invited); err != nil { return st, err } err := s.row(ctx, `SELECT COUNT(*), COALESCE(SUM(CASE WHEN status = 'paid' THEN amount ELSE 0 END), 0), COALESCE(SUM(CASE WHEN status = 'pending' THEN amount ELSE 0 END), 0) FROM referral_rewards WHERE referrer_id = ?`, referrerID).Scan(&st.Converted, &st.Earned, &st.Pending) return st, err }