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
@@ -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)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user