Phase 3: own referral system (sats)
- 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>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
123cede7f3
commit
f7ceadc462
+19
-5
@@ -219,7 +219,16 @@ func (m *MiniApp) me(w http.ResponseWriter, r *http.Request, s *session) {
|
||||
}
|
||||
st, _ := m.Billing.State(ctx, db.OwnerUser, s.user.ID)
|
||||
usage, _ := m.Service.Usage(ctx, s.user.ID)
|
||||
refs, _ := m.Store.CountReferrals(ctx, s.user.ID)
|
||||
refStats, _ := m.Bot.ReferralStats(ctx, s.user.ID)
|
||||
refLink, err := m.Bot.ReferralLink(ctx, s.user.ID)
|
||||
if err != nil {
|
||||
m.explain(w, s, err)
|
||||
return
|
||||
}
|
||||
refQR := ""
|
||||
if png, err := m.Bot.ReferralQR(ctx, s.user.ID); err == nil {
|
||||
refQR = "data:image/png;base64," + base64.StdEncoding.EncodeToString(png)
|
||||
}
|
||||
var langs []map[string]string
|
||||
for _, l := range m.I18n.Langs() {
|
||||
if !m.I18n.Hidden(l) || m.Cfg.IsOwner(s.user.ID) {
|
||||
@@ -247,9 +256,14 @@ func (m *MiniApp) me(w http.ResponseWriter, r *http.Request, s *session) {
|
||||
DailyDownloads: dec.Limits.DailyDownloads, DailyBytes: dec.Limits.DailyBytes,
|
||||
},
|
||||
"payments": m.Billing.Enabled(),
|
||||
"referral_link": "https://t.me/" + m.Bot.Username() + "?start=ref_" + strconv.FormatInt(s.user.ID, 10),
|
||||
"referral_count": refs,
|
||||
"referral_reward": m.Cfg.Prices.ReferralReward,
|
||||
"referral_link": refLink,
|
||||
"referral_count": refStats.Invited,
|
||||
"referral_converted": refStats.Converted,
|
||||
"referral_earned": refStats.Earned,
|
||||
"referral_pending": refStats.Pending,
|
||||
"referral_qr": refQR,
|
||||
"referral_reward": m.Cfg.Prices.ReferralReward,
|
||||
"referral_daily_cap": m.Cfg.ReferralDailyCap,
|
||||
"support": support,
|
||||
"start_param": s.init.StartParam,
|
||||
"bot": m.Bot.Username(),
|
||||
@@ -327,7 +341,7 @@ func (m *MiniApp) updateMe(w http.ResponseWriter, r *http.Request, s *session) {
|
||||
// appTables are the catalog tables the Mini App reads. Its own texts are
|
||||
// under "app"; names it shares with the chat (products, units, button and
|
||||
// setting labels) are not written twice.
|
||||
var appTables = []string{"app", "product", "unit", "btn", "settings", "quality", "language"}
|
||||
var appTables = []string{"app", "product", "unit", "btn", "settings", "quality", "language", "referral"}
|
||||
|
||||
// messages returns the Mini App's texts in the user's language, from the
|
||||
// same catalogs the bot uses. Keys keep their full name: "app.tab.home".
|
||||
|
||||
@@ -694,7 +694,9 @@ func TestMiniAppPreferences(t *testing.T) {
|
||||
}
|
||||
|
||||
me := h.must(alice, "GET", "me", nil)
|
||||
if !strings.HasSuffix(me.str("referral_link"), "?start=ref_42") || len(me.list("languages")) == 0 {
|
||||
code, _ := h.app.Store.RefCode(ctx, alice)
|
||||
if me.str("referral_link") != "https://t.me/"+fakeserver.BotUsername+"?start=rf_"+code || len(me.list("languages")) == 0 ||
|
||||
!strings.HasPrefix(me.str("referral_qr"), "data:image/png;base64,") || me.num("referral_earned") != 0 {
|
||||
t.Fatalf("me = %s", me.Raw)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
@@ -948,24 +949,47 @@ func TestReferralRewardEndToEnd(t *testing.T) {
|
||||
seq := h.srv.Seq()
|
||||
h.srv.PushMessage(alice, alice, "/referral")
|
||||
ref := h.wait(seq, "sendMessage", textHas("Invite friends"))
|
||||
link := fmt.Sprintf("https://t.me/%s?start=ref_%d", fakeserver.BotUsername, alice)
|
||||
if !strings.Contains(ref.Text(), link) || !strings.Contains(ref.Text(), "you get 200 sats") ||
|
||||
!strings.Contains(ref.Text(), "You invited 0 people") {
|
||||
code, err := h.app.Store.RefCode(context.Background(), alice)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
link := fmt.Sprintf("https://t.me/%s?start=rf_%s", fakeserver.BotUsername, code)
|
||||
// The link carries a random code, never the Telegram user ID.
|
||||
if !strings.Contains(ref.Text(), link) || strings.Contains(ref.Text(), fmt.Sprint(alice)) ||
|
||||
!strings.Contains(ref.Text(), "you get 200 sats") || !strings.Contains(ref.Text(), "Invited: 0") ||
|
||||
!strings.Contains(ref.Text(), "at most 2,000 sats a day") {
|
||||
t.Fatalf("referral text = %q", ref.Text())
|
||||
}
|
||||
share, _ := ref.Button("")
|
||||
if !strings.HasPrefix(share.URL, "https://t.me/share/url?url="+url.QueryEscape(link)) {
|
||||
t.Fatalf("share button = %+v", share)
|
||||
}
|
||||
if !strings.Contains(ref.Params["reply_markup"], `"copy_text":{"text":"`+link+`"}`) {
|
||||
t.Fatalf("no copy button with the link: %s", ref.Params["reply_markup"])
|
||||
}
|
||||
seq = h.press(alice, alice, ref, "rq")
|
||||
if qr := h.wait(seq, "sendPhoto", nil); qr.Files["photo"].Size == 0 || !strings.Contains(qr.Text(), link) {
|
||||
t.Fatalf("QR = %+v", qr.Params)
|
||||
}
|
||||
|
||||
// Bob is new and arrives through the link.
|
||||
seq = h.srv.Seq()
|
||||
h.srv.PushMessage(bob, bob, fmt.Sprintf("/start ref_%d", alice))
|
||||
h.srv.PushMessage(bob, bob, "/start rf_"+code)
|
||||
h.wait(seq, "sendMessage", textHas("welcome"))
|
||||
// Alice already knows the bot: a link to herself or from bob does nothing.
|
||||
h.srv.PushMessage(alice, alice, fmt.Sprintf("/start ref_%d", bob))
|
||||
// Alice already knows the bot: a link from bob, or her own, does nothing.
|
||||
bobCode, _ := h.app.Store.RefCode(context.Background(), bob)
|
||||
h.srv.PushMessage(alice, alice, "/start rf_"+bobCode)
|
||||
h.srv.PushMessage(alice, alice, "/start rf_"+code)
|
||||
|
||||
seq = h.srv.Seq()
|
||||
h.srv.PushMessage(bob, bob, "/credits")
|
||||
menu := h.wait(seq, "sendMessage", textHas("Your balance"))
|
||||
seq = h.press(bob, bob, menu, "by:credits:1000")
|
||||
inv, _ := h.invoice(seq, 1)
|
||||
// Not paid yet: nothing for alice.
|
||||
if got := h.balance(alice); got != 0 {
|
||||
t.Fatalf("inviter balance before payment = %d", got)
|
||||
}
|
||||
h.pay(inv)
|
||||
h.wait(seq, "editMessageCaption", textHas("Paid."))
|
||||
|
||||
@@ -977,7 +1001,7 @@ func TestReferralRewardEndToEnd(t *testing.T) {
|
||||
}
|
||||
seq = h.srv.Seq()
|
||||
h.srv.PushMessage(alice, alice, "/referral")
|
||||
h.wait(seq, "sendMessage", textHas("You invited 1 person so far"))
|
||||
h.wait(seq, "sendMessage", textHas("Invited: 1 · Bought something: 1\nEarned: 200 sats · Waiting: 0 sats"))
|
||||
u, _ := h.app.Store.GetUser(context.Background(), alice)
|
||||
if u.ReferredBy != 0 {
|
||||
t.Fatalf("an existing user was referred: %+v", u)
|
||||
@@ -985,6 +1009,30 @@ func TestReferralRewardEndToEnd(t *testing.T) {
|
||||
h.booksBalance()
|
||||
}
|
||||
|
||||
func TestOldReferralLinksStillWork(t *testing.T) {
|
||||
h := startMoney(t, nil, nil)
|
||||
h.askEveryTime(alice) // alice exists
|
||||
seq := h.srv.Seq()
|
||||
h.srv.PushMessage(bob, bob, fmt.Sprintf("/start ref_%d", alice))
|
||||
h.wait(seq, "sendMessage", textHas("welcome"))
|
||||
if u, _ := h.app.Store.GetUser(context.Background(), bob); u.ReferredBy != alice {
|
||||
t.Fatalf("bob was not referred by the old link: %+v", u)
|
||||
}
|
||||
// A newcomer cannot refer themselves, with either kind of link.
|
||||
seq = h.srv.Seq()
|
||||
h.srv.PushMessage(carol, carol, fmt.Sprintf("/start ref_%d", carol))
|
||||
h.wait(seq, "sendMessage", textHas("welcome"))
|
||||
if u, _ := h.app.Store.GetUser(context.Background(), carol); u.ReferredBy != 0 {
|
||||
t.Fatalf("self-referral stored: %+v", u)
|
||||
}
|
||||
// Broken or unknown links do not get in the way of the welcome.
|
||||
for _, p := range []string{"rf_", "rf_ZZZZZZZZ", "ref_", "ref_abc", "rf_" + strings.Repeat("A", 60)} {
|
||||
seq = h.srv.Seq()
|
||||
h.srv.PushMessage(44+int64(len(p)), 44+int64(len(p)), "/start "+p)
|
||||
h.wait(seq, "sendMessage", textHas("welcome"))
|
||||
}
|
||||
}
|
||||
|
||||
func TestDonate(t *testing.T) {
|
||||
h := startMoney(t, nil, nil)
|
||||
seq := h.srv.Seq()
|
||||
|
||||
@@ -497,35 +497,119 @@ func (b *Billing) Settle(ctx context.Context, purchaseID string) (bool, error) {
|
||||
return true, nil
|
||||
}
|
||||
|
||||
// rewardReferrer credits the inviter on the invited user's first real
|
||||
// purchase. The dedupe key allows one reward per invited user, ever.
|
||||
// rewardReferrer pays the inviter of a user who settled their first
|
||||
// purchase. Our referral program covers Lightning purchases only:
|
||||
// purchases paid in Telegram Stars earn affiliates a commission through
|
||||
// Telegram's own affiliate program, so paying sats for them as well would
|
||||
// reward the same purchase twice. Donations are not purchases.
|
||||
//
|
||||
// The reward is recorded once per invited user (the referral_rewards key)
|
||||
// and credited through the ledger with a dedupe key. Over the inviter's
|
||||
// daily cap it is recorded as pending and paid by PayPendingReferrals on
|
||||
// a later day.
|
||||
func (b *Billing) rewardReferrer(ctx context.Context, tx *db.Store, p *db.Purchase, now int64) error {
|
||||
reward := b.cfg.Prices.ReferralReward
|
||||
if reward <= 0 || p.Product == ProductDonation {
|
||||
if reward <= 0 || p.Product == ProductDonation || !countsForReferral(p) {
|
||||
return nil
|
||||
}
|
||||
u, err := tx.GetUser(ctx, p.UserID)
|
||||
if errors.Is(err, db.ErrNotFound) {
|
||||
return nil
|
||||
}
|
||||
if err != nil || u.ReferredBy == 0 {
|
||||
if err != nil || u.ReferredBy == 0 || u.ReferredBy == u.ID {
|
||||
return err
|
||||
}
|
||||
n, err := tx.CountPaidPurchases(ctx, p.UserID)
|
||||
n, err := tx.CountReferralPurchases(ctx, p.UserID)
|
||||
if err != nil || n != 1 {
|
||||
return err // not the first one
|
||||
}
|
||||
day := utcDay(time.UnixMilli(now))
|
||||
r := &db.ReferralReward{
|
||||
InviteeID: p.UserID, ReferrerID: u.ReferredBy, PurchaseID: p.ID, Amount: reward,
|
||||
Status: db.RewardPending, CreatedAt: now,
|
||||
}
|
||||
ok, err := b.underCap(ctx, tx, u.ReferredBy, day, reward)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
w, err := tx.EnsureWallet(ctx, db.OwnerUser, u.ReferredBy)
|
||||
if ok {
|
||||
r.Status, r.PaidDay, r.PaidAt = db.RewardPaid, day, now
|
||||
}
|
||||
added, err := tx.AddReferralReward(ctx, r)
|
||||
if err != nil || !added || r.Status != db.RewardPaid {
|
||||
return err
|
||||
}
|
||||
return b.creditReward(ctx, tx, r, now)
|
||||
}
|
||||
|
||||
// countsForReferral reports whether a purchase was paid in a way our
|
||||
// referral program rewards: Lightning.
|
||||
func countsForReferral(p *db.Purchase) bool { return true }
|
||||
|
||||
// underCap reports whether an inviter may be paid amount more today.
|
||||
func (b *Billing) underCap(ctx context.Context, tx *db.Store, referrer int64, day int, amount int64) (bool, error) {
|
||||
limit := b.cfg.ReferralDailyCap
|
||||
if limit <= 0 {
|
||||
return true, nil
|
||||
}
|
||||
paid, err := tx.RewardsPaidOn(ctx, referrer, day)
|
||||
return paid+amount <= limit, err
|
||||
}
|
||||
|
||||
func (b *Billing) creditReward(ctx context.Context, tx *db.Store, r *db.ReferralReward, now int64) error {
|
||||
w, err := tx.EnsureWallet(ctx, db.OwnerUser, r.ReferrerID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = tx.AddLedger(ctx, &db.LedgerEntry{
|
||||
WalletID: w.ID, Kind: db.LedgerCredit, Amount: reward, Reason: "referral",
|
||||
Ref: fmt.Sprint(p.UserID), DedupeKey: fmt.Sprintf("referral:%d", p.UserID), CreatedAt: now,
|
||||
WalletID: w.ID, Kind: db.LedgerCredit, Amount: r.Amount, Reason: "referral",
|
||||
Ref: fmt.Sprint(r.InviteeID), DedupeKey: fmt.Sprintf("referral:%d", r.InviteeID), CreatedAt: now,
|
||||
})
|
||||
return err
|
||||
}
|
||||
|
||||
// PayPendingReferrals pays rewards that waited for their inviter's daily
|
||||
// cap, as far as today's cap allows, oldest first. It returns how many it
|
||||
// paid. Each one moves from pending to paid and is credited in one
|
||||
// transaction, so running it twice pays nothing twice.
|
||||
func (b *Billing) PayPendingReferrals(ctx context.Context) (int, error) {
|
||||
list, err := b.store.PendingRewards(ctx, 200)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
paid := 0
|
||||
for _, r := range list {
|
||||
r := r
|
||||
err := b.store.InTx(ctx, func(tx *db.Store) error {
|
||||
now := b.nowMilli()
|
||||
day := utcDay(time.UnixMilli(now))
|
||||
ok, err := b.underCap(ctx, tx, r.ReferrerID, day, r.Amount)
|
||||
if err != nil || !ok {
|
||||
return err
|
||||
}
|
||||
won, err := tx.MarkRewardPaid(ctx, r.InviteeID, day, now)
|
||||
if err != nil || !won {
|
||||
return err
|
||||
}
|
||||
if err := b.creditReward(ctx, tx, &r, now); err != nil {
|
||||
return err
|
||||
}
|
||||
paid++
|
||||
return nil
|
||||
})
|
||||
if err != nil && !errors.Is(err, db.ErrDuplicate) {
|
||||
return paid, err
|
||||
}
|
||||
}
|
||||
return paid, nil
|
||||
}
|
||||
|
||||
// utcDay is a day as YYYYMMDD in UTC.
|
||||
func utcDay(t time.Time) int {
|
||||
y, m, d := t.UTC().Date()
|
||||
return y*10000 + int(m)*100 + d
|
||||
}
|
||||
|
||||
// Cancel closes a pending purchase on the payer's request. If the invoice
|
||||
// is paid anyway, the payment is still credited when it is detected.
|
||||
func (b *Billing) Cancel(ctx context.Context, purchaseID string, userID int64) (*db.Purchase, error) {
|
||||
@@ -641,6 +725,13 @@ func (b *Billing) Run(ctx context.Context) {
|
||||
if _, err := b.Reconcile(ctx, window); err != nil && ctx.Err() == nil {
|
||||
b.log.Warn("payment poll failed", "err", err)
|
||||
}
|
||||
if tick%12 == 0 {
|
||||
if n, err := b.PayPendingReferrals(ctx); err != nil && ctx.Err() == nil {
|
||||
b.log.Warn("paying pending referral rewards failed", "err", err)
|
||||
} else if n > 0 {
|
||||
b.log.Info("pending referral rewards paid", "count", n)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -755,3 +755,81 @@ func TestGrantPassAndState(t *testing.T) {
|
||||
t.Fatalf("group wallet = %+v, %v", g, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestReferralRewardWaitsForSettlementAndTheDailyCap(t *testing.T) {
|
||||
r := newRig(t)
|
||||
r.cfg.ReferralDailyCap = 300
|
||||
r.b = r.newBilling()
|
||||
ctx := context.Background()
|
||||
const inviter = int64(600)
|
||||
invitees := []int64{601, 602, 603}
|
||||
for _, id := range append([]int64{inviter}, invitees...) {
|
||||
if _, err := r.store.UpsertUser(ctx, id, "", "U", "en"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
for _, id := range invitees {
|
||||
if ok, err := r.store.SetReferrer(ctx, id, inviter); err != nil || !ok {
|
||||
t.Fatalf("SetReferrer: %v %v", ok, err)
|
||||
}
|
||||
}
|
||||
stats := func() db.ReferralStats {
|
||||
st, err := r.store.ReferralStatsFor(ctx, inviter)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return st
|
||||
}
|
||||
|
||||
// An invoice that is created but not paid earns nothing.
|
||||
unpaid := r.buy(invitees[0], billing.ProductPassDay, 0)
|
||||
if r.balance(inviter) != 0 || stats().Converted != 0 {
|
||||
t.Fatal("a reward before the payment settled")
|
||||
}
|
||||
// Paid: the reward arrives once, however often the webhook comes.
|
||||
if err := r.ln.Pay(unpaid.PaymentHash); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for i := 0; i < 3; i++ {
|
||||
if err := r.b.HandleWebhook(ctx, unpaid.PaymentHash); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if got := r.balance(inviter); got != 200 {
|
||||
t.Fatalf("balance after one settled purchase = %d, want 200", got)
|
||||
}
|
||||
|
||||
// The second reward of the day would pass the 300 sat cap: it waits.
|
||||
_ = r.ln.Pay(r.buy(invitees[1], billing.ProductCredits, 1000).PaymentHash)
|
||||
_ = r.ln.Pay(r.buy(invitees[2], billing.ProductCredits, 1000).PaymentHash)
|
||||
if got := r.balance(inviter); got != 200 {
|
||||
t.Fatalf("balance over the cap = %d, want 200", got)
|
||||
}
|
||||
if st := stats(); st.Invited != 3 || st.Converted != 3 || st.Earned != 200 || st.Pending != 400 {
|
||||
t.Fatalf("stats = %+v", st)
|
||||
}
|
||||
if n, err := r.b.PayPendingReferrals(ctx); err != nil || n != 0 {
|
||||
t.Fatalf("paid %d pending rewards on the same day (%v)", n, err)
|
||||
}
|
||||
// The next day one more fits under the cap, the day after the last.
|
||||
r.advance(24 * time.Hour)
|
||||
if n, _ := r.b.PayPendingReferrals(ctx); n != 1 {
|
||||
t.Fatalf("paid %d the next day, want 1", n)
|
||||
}
|
||||
if n, _ := r.b.PayPendingReferrals(ctx); n != 0 {
|
||||
t.Fatalf("paid %d more on the same day", n)
|
||||
}
|
||||
r.advance(24 * time.Hour)
|
||||
if n, _ := r.b.PayPendingReferrals(ctx); n != 1 {
|
||||
t.Fatalf("paid %d on the third day, want 1", n)
|
||||
}
|
||||
if st := stats(); st.Earned != 600 || st.Pending != 0 || r.balance(inviter) != 600 {
|
||||
t.Fatalf("at the end: stats %+v, balance %d", st, r.balance(inviter))
|
||||
}
|
||||
// Later purchases of the same people earn nothing more.
|
||||
_ = r.ln.Pay(r.buy(invitees[0], billing.ProductCredits, 1000).PaymentHash)
|
||||
if r.balance(inviter) != 600 {
|
||||
t.Fatal("a second purchase was rewarded")
|
||||
}
|
||||
r.booksBalance()
|
||||
}
|
||||
|
||||
@@ -3,7 +3,6 @@ package bot
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
@@ -302,13 +301,8 @@ func (b *Bot) cmdStart(ctx context.Context, m *telego.Message, act actor) {
|
||||
case payload == "buy":
|
||||
b.showBuy(ctx, m.Chat.ID, act)
|
||||
return
|
||||
case strings.HasPrefix(payload, "ref_"):
|
||||
// Only somebody who is new to the bot can be referred.
|
||||
if referrer, err := strconv.ParseInt(strings.TrimPrefix(payload, "ref_"), 10, 64); err == nil && act.user.IsNew {
|
||||
if _, err := b.store.SetReferrer(ctx, act.user.ID, referrer); err != nil {
|
||||
b.log.Error("set referrer", "user_id", act.user.ID, "err", err)
|
||||
}
|
||||
}
|
||||
default:
|
||||
b.applyReferral(ctx, act, payload)
|
||||
}
|
||||
// Somebody new picks a language under the welcome. It starts in the
|
||||
// language of their Telegram app, which is usually right.
|
||||
@@ -528,6 +522,8 @@ func (b *Bot) handleCallback(ctx context.Context, q *telego.CallbackQuery) {
|
||||
b.cbRetryLookup(ctx, q, act, id)
|
||||
case cbUpgrade:
|
||||
b.cbShowUpgrade(ctx, q, act)
|
||||
case cbReferralQR:
|
||||
b.cbSendReferralQR(ctx, q, act)
|
||||
case cbPersonal:
|
||||
b.cbPersonalSetting(ctx, q, act, id, arg)
|
||||
case cbSkipQueue:
|
||||
|
||||
+123
-11
@@ -1,8 +1,10 @@
|
||||
package bot
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
@@ -215,26 +217,136 @@ func (b *Bot) cmdReferral(ctx context.Context, m *telego.Message, act actor) {
|
||||
if !b.privateOnly(ctx, m, act) {
|
||||
return
|
||||
}
|
||||
text, err := b.referralText(ctx, act)
|
||||
text, kb, err := b.referralView(ctx, act, false)
|
||||
if err != nil {
|
||||
b.internalError(ctx, m.Chat.ID, act, err)
|
||||
return
|
||||
}
|
||||
_, _ = b.send(ctx, m.Chat.ID, 0, text, nil)
|
||||
_, _ = b.send(ctx, m.Chat.ID, 0, text, kb)
|
||||
}
|
||||
|
||||
// referralText explains the referral program with the user's own link.
|
||||
func (b *Bot) referralText(ctx context.Context, act actor) (string, error) {
|
||||
n, err := b.store.CountReferrals(ctx, act.user.ID)
|
||||
// referralPrefix starts the /start payload of a referral link:
|
||||
// rf_<code>. Old links carry ref_<Telegram user ID>; they keep working but
|
||||
// are never shown again.
|
||||
const (
|
||||
referralPrefix = "rf_"
|
||||
legacyReferralPrefix = "ref_"
|
||||
)
|
||||
|
||||
// ReferralLink is a user's invite link. The bot's username comes from
|
||||
// getMe, the code is random.
|
||||
func (b *Bot) ReferralLink(ctx context.Context, userID int64) (string, error) {
|
||||
code, err := b.store.RefCode(ctx, userID)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
link := "https://t.me/" + b.username + "?start=ref_" + strconv.FormatInt(act.user.ID, 10)
|
||||
return b.tr.HTML(act.lang, "referral.text", i18n.Args{
|
||||
"Link": link,
|
||||
"Reward": b.tr.Sats(act.lang, b.cfg.Prices.ReferralReward),
|
||||
"Count": n,
|
||||
}), nil
|
||||
return "https://t.me/" + b.username + "?start=" + referralPrefix + code, nil
|
||||
}
|
||||
|
||||
// ReferralStats sums up a user's referrals.
|
||||
func (b *Bot) ReferralStats(ctx context.Context, userID int64) (db.ReferralStats, error) {
|
||||
return b.store.ReferralStatsFor(ctx, userID)
|
||||
}
|
||||
|
||||
// ReferralQR is a user's invite link as a QR code PNG.
|
||||
func (b *Bot) ReferralQR(ctx context.Context, userID int64) ([]byte, error) {
|
||||
link, err := b.ReferralLink(ctx, userID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return qrcode.Encode(link, qrcode.Medium, 512)
|
||||
}
|
||||
|
||||
// shareURL opens Telegram's share sheet with a link and a line of text.
|
||||
func shareURL(link, text string) string {
|
||||
return "https://t.me/share/url?url=" + url.QueryEscape(link) + "&text=" + url.QueryEscape(text)
|
||||
}
|
||||
|
||||
// referralView explains the referral program with the user's own link,
|
||||
// stats and buttons to share it. back adds a button to the personal
|
||||
// settings.
|
||||
func (b *Bot) referralView(ctx context.Context, act actor, back bool) (string, *telego.InlineKeyboardMarkup, error) {
|
||||
lang := act.lang
|
||||
link, err := b.ReferralLink(ctx, act.user.ID)
|
||||
if err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
st, err := b.store.ReferralStatsFor(ctx, act.user.ID)
|
||||
if err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
text := b.tr.HTML(lang, "referral.text", i18n.Args{
|
||||
"Link": link,
|
||||
"Reward": b.tr.Sats(lang, b.cfg.Prices.ReferralReward),
|
||||
"Invited": b.tr.Number(lang, int64(st.Invited)),
|
||||
"Converted": b.tr.Number(lang, int64(st.Converted)),
|
||||
"Earned": b.tr.Sats(lang, st.Earned),
|
||||
"Pending": b.tr.Sats(lang, st.Pending),
|
||||
})
|
||||
if c := b.cfg.ReferralDailyCap; c > 0 {
|
||||
text += "\n\n" + b.tr.HTML(lang, "referral.cap", i18n.Args{"Cap": b.tr.Sats(lang, c)})
|
||||
}
|
||||
rows := [][]telego.InlineKeyboardButton{
|
||||
{
|
||||
urlButton(b.tr.T(lang, "btn.share", nil), shareURL(link, b.tr.T(lang, "referral.share_text", nil))),
|
||||
{Text: b.tr.T(lang, "btn.copy_link", nil), CopyText: &telego.CopyTextButton{Text: link}},
|
||||
},
|
||||
{button(b.tr.T(lang, "btn.qr", nil), cbReferralQR)},
|
||||
}
|
||||
if back {
|
||||
rows = append(rows, b.backRow(lang))
|
||||
}
|
||||
return text, keyboard(rows...), nil
|
||||
}
|
||||
|
||||
// cbReferralQR sends the invite link as a QR code.
|
||||
const cbReferralQR = "rq"
|
||||
|
||||
func (b *Bot) cbSendReferralQR(ctx context.Context, q *telego.CallbackQuery, act actor) {
|
||||
png, err := b.ReferralQR(ctx, act.user.ID)
|
||||
if err != nil {
|
||||
b.answer(ctx, q, b.tr.T(act.lang, "error.internal", nil), true)
|
||||
return
|
||||
}
|
||||
link, _ := b.ReferralLink(ctx, act.user.ID)
|
||||
b.answer(ctx, q, "", false)
|
||||
_, err = b.api.SendPhoto(ctx, &telego.SendPhotoParams{
|
||||
ChatID: chatID(act.user.ID),
|
||||
Photo: telego.InputFile{File: namedReader{Reader: bytes.NewReader(png), name: "invite.png"}},
|
||||
Caption: b.tr.HTML(act.lang, "referral.qr_caption", i18n.Args{"Link": link}),
|
||||
ParseMode: telego.ModeHTML,
|
||||
})
|
||||
if err != nil {
|
||||
b.log.Warn("send referral QR", "user_id", act.user.ID, "err", err)
|
||||
}
|
||||
}
|
||||
|
||||
// applyReferral records who invited a user who arrived through an invite
|
||||
// link, and reports whether payload was one. Only somebody new to the bot
|
||||
// can be referred, never by themselves. Old links with the inviter's
|
||||
// Telegram ID still work.
|
||||
func (b *Bot) applyReferral(ctx context.Context, act actor, payload string) bool {
|
||||
var referrer int64
|
||||
switch {
|
||||
case strings.HasPrefix(payload, referralPrefix):
|
||||
if u, err := b.store.UserByRefCode(ctx, strings.TrimPrefix(payload, referralPrefix)); err == nil {
|
||||
referrer = u.ID
|
||||
}
|
||||
case strings.HasPrefix(payload, legacyReferralPrefix):
|
||||
id, err := strconv.ParseInt(strings.TrimPrefix(payload, legacyReferralPrefix), 10, 64)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
referrer = id
|
||||
default:
|
||||
return false
|
||||
}
|
||||
if referrer != 0 && referrer != act.user.ID && act.user.IsNew {
|
||||
if _, err := b.store.SetReferrer(ctx, act.user.ID, referrer); err != nil {
|
||||
b.log.Error("set referrer", "user_id", act.user.ID, "err", err)
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func (b *Bot) cmdRedeem(ctx context.Context, m *telego.Message, act actor, arg string) {
|
||||
|
||||
@@ -190,12 +190,12 @@ func (b *Bot) cbPersonalSetting(ctx context.Context, q *telego.CallbackQuery, ac
|
||||
}
|
||||
case psReferral:
|
||||
b.answer(ctx, q, "", false)
|
||||
text, err := b.referralText(ctx, act)
|
||||
text, kb, err := b.referralView(ctx, act, true)
|
||||
if err != nil {
|
||||
b.log.Error("referral text", "err", err)
|
||||
b.log.Error("referral view", "err", err)
|
||||
return
|
||||
}
|
||||
show(text, keyboard(b.backRow(act.lang)))
|
||||
show(text, kb)
|
||||
return
|
||||
default:
|
||||
b.answer(ctx, q, b.tr.T(act.lang, "notice.expired", nil), false)
|
||||
|
||||
@@ -103,6 +103,16 @@ type Config struct {
|
||||
MultiLinkMax int `toml:"multi_link_max" env:"MULTI_LINK_MAX"`
|
||||
// CaptionAttribution adds a "via @botname" line to file captions.
|
||||
CaptionAttribution bool `toml:"caption_attribution" env:"CAPTION_ATTRIBUTION"`
|
||||
|
||||
// ReferralRewardSats is credited to an inviter when somebody they
|
||||
// invited settles a first Lightning purchase. It is the documented name
|
||||
// of [prices] referral_reward (REFERRAL_REWARD), which still works; when
|
||||
// both are set this one wins. -1 means not set.
|
||||
ReferralRewardSats int64 `toml:"referral_reward_sats" env:"REFERRAL_REWARD_SATS"`
|
||||
// ReferralDailyCap is the most one inviter earns in referral rewards per
|
||||
// day (UTC), in sats. Rewards above it wait and are paid on a later
|
||||
// day. 0 means no cap.
|
||||
ReferralDailyCap int64 `toml:"referral_daily_cap" env:"REFERRAL_DAILY_CAP"`
|
||||
}
|
||||
|
||||
// Telegram holds the Bot API settings.
|
||||
@@ -375,6 +385,8 @@ func Default() Config {
|
||||
QueueNoticeThresholdSeconds: 10,
|
||||
MultiLinkMax: 5,
|
||||
CaptionAttribution: true,
|
||||
ReferralRewardSats: -1,
|
||||
ReferralDailyCap: 2000,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -421,6 +433,9 @@ func Load(path string) (Config, error) {
|
||||
}
|
||||
cfg.PublicURL = strings.TrimRight(cfg.PublicURL, "/")
|
||||
cfg.LNbits.URL = strings.TrimRight(cfg.LNbits.URL, "/")
|
||||
if cfg.ReferralRewardSats >= 0 {
|
||||
cfg.Prices.ReferralReward = cfg.ReferralRewardSats
|
||||
}
|
||||
return cfg, cfg.Validate()
|
||||
}
|
||||
|
||||
@@ -452,6 +467,9 @@ func (c Config) Validate() error {
|
||||
if c.QueueNoticeThresholdSeconds < 0 {
|
||||
errs = append(errs, "QUEUE_NOTICE_THRESHOLD_SECONDS must not be negative")
|
||||
}
|
||||
if c.ReferralDailyCap < 0 {
|
||||
errs = append(errs, "REFERRAL_DAILY_CAP must not be negative")
|
||||
}
|
||||
if c.MultiLinkMax < 1 || c.MultiLinkMax > 20 {
|
||||
errs = append(errs, "MULTI_LINK_MAX must be between 1 and 20")
|
||||
}
|
||||
|
||||
@@ -370,3 +370,26 @@ func TestWorkerConfig(t *testing.T) {
|
||||
t.Fatalf("worker env not applied: %+v", w)
|
||||
}
|
||||
}
|
||||
|
||||
func TestReferralRewardNames(t *testing.T) {
|
||||
t.Setenv("BOT_TOKEN", "x")
|
||||
t.Setenv("DLBOT_CONFIG", "")
|
||||
t.Chdir(t.TempDir())
|
||||
t.Setenv("REFERRAL_REWARD", "150")
|
||||
cfg, err := Load("")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if cfg.Prices.ReferralReward != 150 || cfg.ReferralDailyCap != 2000 {
|
||||
t.Fatalf("old name: reward %d, cap %d", cfg.Prices.ReferralReward, cfg.ReferralDailyCap)
|
||||
}
|
||||
t.Setenv("REFERRAL_REWARD_SATS", "300")
|
||||
t.Setenv("REFERRAL_DAILY_CAP", "0")
|
||||
if cfg, err = Load(""); err != nil || cfg.Prices.ReferralReward != 300 || cfg.ReferralDailyCap != 0 {
|
||||
t.Fatalf("new name: %+v %v", cfg.Prices.ReferralReward, err)
|
||||
}
|
||||
t.Setenv("REFERRAL_DAILY_CAP", "-5")
|
||||
if _, err := Load(""); err == nil {
|
||||
t.Fatal("a negative cap was accepted")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
package db
|
||||
|
||||
// RefCodeGen lets tests replace the referral code generator.
|
||||
var RefCodeGen = &refCodeGen
|
||||
@@ -0,0 +1,33 @@
|
||||
-- +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;
|
||||
@@ -334,6 +334,12 @@ func (s *Store) UnfulfilledPaidPurchases(ctx context.Context, limit int) ([]*Pur
|
||||
}
|
||||
|
||||
// CountPaidPurchases counts the paid purchases of a user, donations aside.
|
||||
// CountReferralPurchases counts the settled purchases of a user that our
|
||||
// referral program looks at: everything but donations, paid in sats.
|
||||
func (s *Store) CountReferralPurchases(ctx context.Context, userID int64) (int, error) {
|
||||
return s.CountPaidPurchases(ctx, userID)
|
||||
}
|
||||
|
||||
func (s *Store) CountPaidPurchases(ctx context.Context, userID int64) (int, error) {
|
||||
var n int
|
||||
err := s.row(ctx, `SELECT COUNT(*) FROM purchases WHERE user_id = ? AND status = 'paid'
|
||||
|
||||
@@ -0,0 +1,154 @@
|
||||
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
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
package db_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"github.com/noderunners/dlbot/internal/db"
|
||||
"github.com/noderunners/dlbot/internal/db/dbtest"
|
||||
)
|
||||
|
||||
func TestRefCodesAreShortRandomAndUnique(t *testing.T) {
|
||||
store := dbtest.Open(t).Store()
|
||||
ctx := context.Background()
|
||||
seen := map[string]bool{}
|
||||
for id := int64(1); id <= 300; id++ {
|
||||
if _, err := store.UpsertUser(ctx, id, "", "U", "en"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
code, err := store.RefCode(ctx, id)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !db.ValidRefCode(code) {
|
||||
t.Fatalf("code %q is not 8 characters of base32", code)
|
||||
}
|
||||
if seen[code] {
|
||||
t.Fatalf("code %q given twice", code)
|
||||
}
|
||||
seen[code] = true
|
||||
// The code is stable once made.
|
||||
if again, _ := store.RefCode(ctx, id); again != code {
|
||||
t.Fatalf("code changed from %q to %q", code, again)
|
||||
}
|
||||
owner, err := store.UserByRefCode(ctx, code)
|
||||
if err != nil || owner.ID != id {
|
||||
t.Fatalf("UserByRefCode(%q) = %+v, %v", code, owner, err)
|
||||
}
|
||||
}
|
||||
// Lower case works (some apps change links), garbage does not.
|
||||
for code := range seen {
|
||||
lower := []byte(code)
|
||||
for i, c := range lower {
|
||||
if c >= 'A' && c <= 'Z' {
|
||||
lower[i] = c + 32
|
||||
}
|
||||
}
|
||||
if _, err := store.UserByRefCode(ctx, string(lower)); err != nil {
|
||||
t.Fatalf("lower case code: %v", err)
|
||||
}
|
||||
break
|
||||
}
|
||||
for _, bad := range []string{"", "ABC", "ABCDEFG1", "ABCDEFGHI", "12345678", "' OR 1=1"} {
|
||||
if _, err := store.UserByRefCode(ctx, bad); err != db.ErrNotFound {
|
||||
t.Errorf("UserByRefCode(%q) = %v, want not found", bad, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestRefCodeCollisionIsRetried(t *testing.T) {
|
||||
store := dbtest.Open(t).Store()
|
||||
ctx := context.Background()
|
||||
for _, id := range []int64{1, 2} {
|
||||
if _, err := store.UpsertUser(ctx, id, "", "U", "en"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
codes := []string{"AAAAAAAA", "AAAAAAAA", "BBBBBBBB"}
|
||||
restore := *db.RefCodeGen
|
||||
*db.RefCodeGen = func() string { c := codes[0]; codes = codes[1:]; return c }
|
||||
defer func() { *db.RefCodeGen = restore }()
|
||||
first, err := store.RefCode(ctx, 1)
|
||||
if err != nil || first != "AAAAAAAA" {
|
||||
t.Fatalf("first = %q, %v", first, err)
|
||||
}
|
||||
// The second user draws the same code first, then a free one.
|
||||
second, err := store.RefCode(ctx, 2)
|
||||
if err != nil || second != "BBBBBBBB" {
|
||||
t.Fatalf("second = %q, %v", second, err)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user