feat(payments): chip wallet, store-compliance gate and benefit application
CI / changes (pull_request) Successful in 2s
CI / unit (pull_request) Successful in 11s
CI / integration (pull_request) Successful in 22s
CI / ui (pull_request) Successful in 1m7s
CI / conformance (pull_request) Successful in 9s
CI / gate (pull_request) Successful in 0s
CI / deploy (pull_request) Successful in 1m41s
CI / changes (pull_request) Successful in 2s
CI / unit (pull_request) Successful in 11s
CI / integration (pull_request) Successful in 22s
CI / ui (pull_request) Successful in 1m7s
CI / conformance (pull_request) Successful in 9s
CI / gate (pull_request) Successful in 0s
CI / deploy (pull_request) Successful in 1m41s
Stand up the internal chip/benefit mechanic behind the narrow payments interface: context-aware balances and benefits, an atomic chip spend, admin grants as zero-price value sales, the one-directional store-compliance gate (VK/TG same- origin only, web draws direct→vk→tg, VK-iOS frozen, untrusted fail-closed), and per-origin hint and no-ads application with term stacking. Reads are served from an in-process, account-keyed write-through cache (mirroring the suspension gate), so hot paths issue no query to the payments schema. Flip the online-game hint wallet and the ad-banner suppression from the deprecated accounts.hint_balance / paid_account columns to the payments benefit (a hint balance no longer suppresses the banner — only a no-ads benefit does), and fold chip segments and benefits by origin on account merge, inside the merge tx. Add the GET/POST /api/v1/user/wallet edge chain (REST → Connect → FlatBuffers) plus its codec unit test; no wallet UI yet. Bring the frozen owner decisions log into the repo at docs/PAYMENTS_DECISIONS_ru.md (it was untracked under .vscode) and reference it from PLAN.md; record the read-cache design and the present-sources interface in PLAN.md and docs/PAYMENTS.md (+ RU mirror).
This commit is contained in:
@@ -195,7 +195,8 @@ func run(ctx context.Context, cfg config.Config, logger *zap.Logger) error {
|
||||
emails.SetSendLimiter(account.NewSendLimiter(time.Minute, 5))
|
||||
// Account linking & merge: the orchestrator over the account, merge and
|
||||
// session layers. Wired to the /api/v1/user/link REST surface below.
|
||||
links := link.NewService(emails, accounts, accountmerge.NewMerger(db), sessions)
|
||||
merger := accountmerge.NewMerger(db)
|
||||
links := link.NewService(emails, accounts, merger, sessions)
|
||||
socialSvc := social.NewService(social.NewStore(db), accounts, games)
|
||||
socialSvc.SetNotifier(hub)
|
||||
socialSvc.SetMetrics(tel.MeterProvider().Meter("scrabble/backend/social"))
|
||||
@@ -270,6 +271,12 @@ func run(ctx context.Context, cfg config.Config, logger *zap.Logger) error {
|
||||
}
|
||||
logger.Info("payments domain ready")
|
||||
|
||||
// Wire the payments surface into the domains that consume it: the online-game hint wallet
|
||||
// and the account-merge wallet fold. Done after the reachability check so a broken payments
|
||||
// schema fails boot before anything depends on it.
|
||||
games.SetHintWallet(paymentsSvc)
|
||||
merger.SetPayments(paymentsSvc)
|
||||
|
||||
// The image-render sidecar client for the PNG export artifact; nil (PNG
|
||||
// download answers 404) when BACKEND_RENDERER_URL is unset.
|
||||
var renderer *render.Client
|
||||
|
||||
@@ -51,8 +51,24 @@ var ErrSameAccount = errors.New("accountmerge: primary and secondary are the sam
|
||||
type Merger struct {
|
||||
db *sql.DB
|
||||
now func() time.Time
|
||||
// payments, when set, merges the two accounts' chip segments and benefits by origin inside
|
||||
// the merge transaction (SetPayments). Nil leaves payments untouched (tests that do not
|
||||
// exercise the wallet).
|
||||
payments PaymentsMerger
|
||||
}
|
||||
|
||||
// PaymentsMerger is the payments surface the account merge enlists: fold the secondary's
|
||||
// segments and benefits into the primary within the merge transaction, then invalidate the
|
||||
// affected read caches after the commit. *payments.Service satisfies it.
|
||||
type PaymentsMerger interface {
|
||||
MergeTx(ctx context.Context, tx *sql.Tx, primary, secondary uuid.UUID) error
|
||||
Invalidate(ids ...uuid.UUID)
|
||||
}
|
||||
|
||||
// SetPayments installs the payments merge hook. It must be called during startup wiring; the
|
||||
// default (nil) merges no wallet state.
|
||||
func (m *Merger) SetPayments(p PaymentsMerger) { m.payments = p }
|
||||
|
||||
// NewMerger constructs a Merger over db.
|
||||
func NewMerger(db *sql.DB) *Merger {
|
||||
return &Merger{db: db, now: func() time.Time { return time.Now().UTC() }}
|
||||
@@ -67,7 +83,7 @@ func (m *Merger) Merge(ctx context.Context, primary, secondary uuid.UUID) error
|
||||
return ErrSameAccount
|
||||
}
|
||||
now := m.now()
|
||||
return withTx(ctx, m.db, func(tx *sql.Tx) error {
|
||||
if err := withTx(ctx, m.db, func(tx *sql.Tx) error {
|
||||
if err := guardActiveSharedGame(ctx, tx, primary, secondary); err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -107,8 +123,21 @@ func (m *Merger) Merge(ctx context.Context, primary, secondary uuid.UUID) error
|
||||
if err := deleteEphemerals(ctx, tx, secondary); err != nil {
|
||||
return err
|
||||
}
|
||||
if m.payments != nil {
|
||||
if err := m.payments.MergeTx(ctx, tx, primary, secondary); err != nil {
|
||||
return fmt.Errorf("accountmerge: payments: %w", err)
|
||||
}
|
||||
}
|
||||
return tombstone(ctx, tx, primary, secondary, now)
|
||||
})
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
// The payments read cache is invalidated only after the merge commits, so a read racing the
|
||||
// transaction cannot re-cache pre-merge state (both accounts' rows are moved or dropped).
|
||||
if m.payments != nil {
|
||||
m.payments.Invalidate(primary, secondary)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// guardActiveSharedGame returns ErrActiveGameConflict when primary and secondary
|
||||
@@ -248,25 +277,16 @@ func mergeBestMoves(ctx context.Context, tx *sql.Tx, primary, secondary uuid.UUI
|
||||
return nil
|
||||
}
|
||||
|
||||
// mergeAccountFields adds secondary's hint wallet to primary and ORs the paid flag;
|
||||
// all other profile fields stay the primary's.
|
||||
func mergeAccountFields(ctx context.Context, tx *sql.Tx, primary, secondary uuid.UUID, now time.Time) error {
|
||||
var sec model.Accounts
|
||||
if err := postgres.SELECT(table.Accounts.AllColumns).
|
||||
FROM(table.Accounts).
|
||||
WHERE(table.Accounts.AccountID.EQ(postgres.UUID(secondary))).
|
||||
QueryContext(ctx, tx, &sec); err != nil {
|
||||
return fmt.Errorf("accountmerge: load secondary account: %w", err)
|
||||
}
|
||||
upd := table.Accounts.UPDATE(
|
||||
table.Accounts.HintBalance, table.Accounts.PaidAccount, table.Accounts.UpdatedAt,
|
||||
).SET(
|
||||
table.Accounts.HintBalance.ADD(postgres.Int(int64(sec.HintBalance))),
|
||||
table.Accounts.PaidAccount.OR(postgres.Bool(sec.PaidAccount)),
|
||||
postgres.TimestampzT(now),
|
||||
).WHERE(table.Accounts.AccountID.EQ(postgres.UUID(primary)))
|
||||
// mergeAccountFields bumps the primary account's updated_at to reflect the merge. The former
|
||||
// hint-wallet and paid-flag merge moved to the payments domain, where segments and benefits
|
||||
// merge by origin (see the payments MergeTx step and docs/PAYMENTS.md §6); the legacy
|
||||
// accounts.hint_balance / paid_account columns are deprecated and no longer read or written.
|
||||
func mergeAccountFields(ctx context.Context, tx *sql.Tx, primary, _ uuid.UUID, now time.Time) error {
|
||||
upd := table.Accounts.UPDATE(table.Accounts.UpdatedAt).
|
||||
SET(postgres.TimestampzT(now)).
|
||||
WHERE(table.Accounts.AccountID.EQ(postgres.UUID(primary)))
|
||||
if _, err := upd.ExecContext(ctx, tx); err != nil {
|
||||
return fmt.Errorf("accountmerge: update primary account: %w", err)
|
||||
return fmt.Errorf("accountmerge: touch primary account: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -100,14 +100,6 @@ type ActiveCampaign struct {
|
||||
OverrideDark *ColorSet
|
||||
}
|
||||
|
||||
// Eligible reports whether an account should be shown the advertising banner: a
|
||||
// free account (not paid) with an empty hint wallet and without the no_banner
|
||||
// role. The no_banner role suppresses the banner unconditionally; buying a paid
|
||||
// account or any hints also removes it.
|
||||
func Eligible(paidAccount bool, hintBalance int, hasNoBanner bool) bool {
|
||||
return !paidAccount && hintBalance <= 0 && !hasNoBanner
|
||||
}
|
||||
|
||||
// computeActiveSet builds the resolved rotation feed from the enabled campaigns
|
||||
// at time now, in language lang, and reports whether the feed is an urgent one.
|
||||
// Campaigns outside their validity window, and campaigns with no messages, are
|
||||
|
||||
@@ -6,30 +6,6 @@ import (
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestEligible(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
paidAccount bool
|
||||
hintBalance int
|
||||
hasNoBanner bool
|
||||
want bool
|
||||
}{
|
||||
{name: "free, empty wallet, no role", want: true},
|
||||
{name: "paid", paidAccount: true, want: false},
|
||||
{name: "has hints", hintBalance: 3, want: false},
|
||||
{name: "no_banner role", hasNoBanner: true, want: false},
|
||||
{name: "paid and has hints", paidAccount: true, hintBalance: 5, want: false},
|
||||
{name: "no_banner overrides everything", hasNoBanner: true, want: false},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
if got := Eligible(tt.paidAccount, tt.hintBalance, tt.hasNoBanner); got != tt.want {
|
||||
t.Errorf("Eligible(%v,%d,%v) = %v, want %v", tt.paidAccount, tt.hintBalance, tt.hasNoBanner, got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestComputeActiveSet(t *testing.T) {
|
||||
now := time.Date(2026, 6, 15, 12, 0, 0, 0, time.UTC)
|
||||
past := now.Add(-24 * time.Hour)
|
||||
|
||||
@@ -18,6 +18,8 @@ import (
|
||||
"scrabble/backend/internal/account"
|
||||
"scrabble/backend/internal/engine"
|
||||
"scrabble/backend/internal/notify"
|
||||
"scrabble/backend/internal/payments"
|
||||
"scrabble/backend/internal/session"
|
||||
)
|
||||
|
||||
// Service is the game domain: it drives the engine over a single match, persists
|
||||
@@ -50,6 +52,11 @@ type Service struct {
|
||||
// its asynchronous TriggerMove); nil disables the fast path (the scan still covers
|
||||
// these games). Kept as a func so the game package never imports the robot package.
|
||||
aiTrigger func(gameID uuid.UUID)
|
||||
// hintWallet is the payments surface the online-game hint path spends against (the
|
||||
// segmented, context-aware hint balance). It is set by SetHintWallet during wiring; when
|
||||
// nil, only the free per-game allowance is served (no purchased hints). vs_ai hints are
|
||||
// wallet-free and never touch it.
|
||||
hintWallet HintWallet
|
||||
// clearNudges, when set, marks the actor's pending nudges in a game read once they
|
||||
// have committed a move (a nudge answered by moving stops counting as unread). It is
|
||||
// best-effort and kept as a func so the game package never imports the social package.
|
||||
@@ -105,6 +112,39 @@ func (svc *Service) SetAITrigger(trigger func(gameID uuid.UUID)) {
|
||||
svc.aiTrigger = trigger
|
||||
}
|
||||
|
||||
// HintWallet is the payments surface the online-game hint path uses: the context-aware hint
|
||||
// balance (HintsAvailable) and a one-hint spend (SpendHint), both keyed by the trusted execution
|
||||
// context and the account's present identity sources. *payments.Service satisfies it.
|
||||
type HintWallet interface {
|
||||
HintsAvailable(ctx context.Context, accountID uuid.UUID, cxt payments.Context, present []payments.Source) (int, error)
|
||||
SpendHint(ctx context.Context, accountID uuid.UUID, cxt payments.Context, present []payments.Source) (bool, error)
|
||||
}
|
||||
|
||||
// SetHintWallet installs the payments hint wallet the online-game hint path spends against. It
|
||||
// must be called during startup wiring; the default (nil) serves only the free per-game allowance.
|
||||
func (svc *Service) SetHintWallet(w HintWallet) {
|
||||
svc.hintWallet = w
|
||||
}
|
||||
|
||||
// walletContext resolves the payments gate inputs for an account on the current request: the
|
||||
// trusted execution context (from the session platform carried on ctx; absent ⇒ untrusted) and
|
||||
// the account's present identity sources (which chip/benefit segments are awake, §6).
|
||||
func (svc *Service) walletContext(ctx context.Context, accountID uuid.UUID) (payments.Context, []payments.Source, error) {
|
||||
var cxt payments.Context
|
||||
if p, ok := session.PlatformFromContext(ctx); ok {
|
||||
cxt = payments.NewContext(p.Kind, p.Subtype)
|
||||
}
|
||||
ids, err := svc.accounts.Identities(ctx, accountID)
|
||||
if err != nil {
|
||||
return payments.Context{}, nil, err
|
||||
}
|
||||
kinds := make([]string, len(ids))
|
||||
for i, id := range ids {
|
||||
kinds[i] = id.Kind
|
||||
}
|
||||
return cxt, payments.PresentSources(kinds), nil
|
||||
}
|
||||
|
||||
// SetNudgeClearer installs the hook that marks a mover's pending nudges read after
|
||||
// their move commits. It must be called during startup wiring; the default (nil)
|
||||
// leaves nudges to be cleared only when the recipient opens the move history or chat.
|
||||
@@ -1121,13 +1161,20 @@ func (svc *Service) Hint(ctx context.Context, gameID, accountID uuid.UUID) (Hint
|
||||
}
|
||||
return HintResult{Move: move}, nil
|
||||
}
|
||||
acc, err := svc.accounts.GetByID(ctx, accountID)
|
||||
cxt, present, err := svc.walletContext(ctx, accountID)
|
||||
if err != nil {
|
||||
return HintResult{}, err
|
||||
}
|
||||
wallet := 0
|
||||
if svc.hintWallet != nil {
|
||||
wallet, err = svc.hintWallet.HintsAvailable(ctx, accountID, cxt, present)
|
||||
if err != nil {
|
||||
return HintResult{}, err
|
||||
}
|
||||
}
|
||||
used := pre.Seats[seat].HintsUsed
|
||||
fromAllowance := used < pre.HintsPerPlayer
|
||||
if !fromAllowance && acc.HintBalance <= 0 {
|
||||
if !fromAllowance && wallet <= 0 {
|
||||
return HintResult{}, ErrNoHintsLeft
|
||||
}
|
||||
|
||||
@@ -1142,9 +1189,9 @@ func (svc *Service) Hint(ctx context.Context, gameID, accountID uuid.UUID) (Hint
|
||||
return HintResult{}, ErrNoHintAvailable
|
||||
}
|
||||
|
||||
walletAfter := acc.HintBalance
|
||||
walletAfter := wallet
|
||||
if !fromAllowance {
|
||||
spent, err := svc.accounts.SpendHint(ctx, accountID)
|
||||
spent, err := svc.hintWallet.SpendHint(ctx, accountID, cxt, present)
|
||||
if err != nil {
|
||||
return HintResult{}, err
|
||||
}
|
||||
|
||||
@@ -15,13 +15,15 @@ import (
|
||||
|
||||
"scrabble/backend/internal/account"
|
||||
"scrabble/backend/internal/ads"
|
||||
"scrabble/backend/internal/payments"
|
||||
"scrabble/backend/internal/server"
|
||||
)
|
||||
|
||||
// bannerServer assembles a console-capable server with the ads domain wired.
|
||||
func bannerServer(t *testing.T) (*server.Server, *ads.Service) {
|
||||
func bannerServer(t *testing.T) (*server.Server, *ads.Service, *payments.Service) {
|
||||
t.Helper()
|
||||
adsSvc := ads.NewService(ads.NewStore(testDB))
|
||||
paySvc := newPaymentsService()
|
||||
srv := server.New(":0", server.Deps{
|
||||
Logger: zap.NewNop(),
|
||||
Accounts: account.NewStore(testDB),
|
||||
@@ -29,8 +31,9 @@ func bannerServer(t *testing.T) (*server.Server, *ads.Service) {
|
||||
Registry: testRegistry,
|
||||
DictDir: dictDir(),
|
||||
Ads: adsSvc,
|
||||
Payments: paySvc,
|
||||
})
|
||||
return srv, adsSvc
|
||||
return srv, adsSvc, paySvc
|
||||
}
|
||||
|
||||
// findCampaign returns the id of the campaign with the given name, or fails.
|
||||
@@ -71,7 +74,7 @@ func defaultCampaign(t *testing.T, svc *ads.Service) ads.Campaign {
|
||||
// reorder/delete.
|
||||
func TestBannerConsoleCRUD(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
srv, adsSvc := bannerServer(t)
|
||||
srv, adsSvc, _ := bannerServer(t)
|
||||
h := srv.Handler()
|
||||
base := "http://admin.test/_gm"
|
||||
const origin = "http://admin.test"
|
||||
@@ -151,7 +154,7 @@ func TestBannerConsoleCRUD(t *testing.T) {
|
||||
// unrelated campaign's URL must be refused.
|
||||
func TestBannerMessageOwnership(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
srv, adsSvc := bannerServer(t)
|
||||
srv, adsSvc, _ := bannerServer(t)
|
||||
h := srv.Handler()
|
||||
base := "http://admin.test/_gm"
|
||||
const origin = "http://admin.test"
|
||||
@@ -207,10 +210,11 @@ type profileBanner struct {
|
||||
// wallet each suppress it.
|
||||
func TestBannerProfileEligibility(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
srv, _ := bannerServer(t)
|
||||
srv, _, pay := bannerServer(t)
|
||||
accounts := account.NewStore(testDB)
|
||||
id := provisionAccount(t)
|
||||
|
||||
// getBanner fetches the profile banner with no platform header (an untrusted context).
|
||||
getBanner := func() profileBanner {
|
||||
t.Helper()
|
||||
rec := userGet(t, srv, "/api/v1/user/profile", id)
|
||||
@@ -223,10 +227,27 @@ func TestBannerProfileEligibility(t *testing.T) {
|
||||
}
|
||||
return p
|
||||
}
|
||||
// getBannerTG fetches the profile banner in a trusted Telegram context — the account's
|
||||
// telegram identity makes telegram the applicable origin for its benefits.
|
||||
getBannerTG := func() profileBanner {
|
||||
t.Helper()
|
||||
rec := httptest.NewRecorder()
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/v1/user/profile", nil)
|
||||
req.Header.Set("X-User-ID", id.String())
|
||||
req.Header.Set("X-Platform", "telegram/android")
|
||||
srv.Handler().ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("profile = %d, want 200", rec.Code)
|
||||
}
|
||||
var p profileBanner
|
||||
if err := json.Unmarshal(rec.Body.Bytes(), &p); err != nil {
|
||||
t.Fatalf("decode profile: %v", err)
|
||||
}
|
||||
return p
|
||||
}
|
||||
|
||||
// A free account with an empty hint wallet and no role is eligible.
|
||||
p := getBanner()
|
||||
if p.Banner == nil || len(p.Banner.Campaigns) == 0 || p.Banner.Timings.HoldMs <= 0 {
|
||||
// A free account with no role and no benefit is eligible.
|
||||
if p := getBanner(); p.Banner == nil || len(p.Banner.Campaigns) == 0 || p.Banner.Timings.HoldMs <= 0 {
|
||||
t.Fatalf("eligible account: banner=%v", p.Banner)
|
||||
}
|
||||
|
||||
@@ -241,19 +262,31 @@ func TestBannerProfileEligibility(t *testing.T) {
|
||||
t.Fatalf("revoke role: %v", err)
|
||||
}
|
||||
|
||||
// A non-empty hint wallet suppresses it.
|
||||
if _, err := accounts.GrantHints(ctx, id, 5); err != nil {
|
||||
// A hint wallet no longer suppresses the banner — hints and no-ads are distinct benefits now.
|
||||
if err := pay.Grant(ctx, id, payments.SourceTelegram, 5, 0, false); err != nil {
|
||||
t.Fatalf("grant hints: %v", err)
|
||||
}
|
||||
if p := getBanner(); p.Banner != nil {
|
||||
t.Fatal("a non-empty hint wallet still shows the banner")
|
||||
if p := getBannerTG(); p.Banner == nil {
|
||||
t.Fatal("a hint wallet must NOT suppress the banner")
|
||||
}
|
||||
|
||||
// An active no-ads benefit applicable in the context suppresses the banner.
|
||||
if err := pay.Grant(ctx, id, payments.SourceTelegram, 0, 30, false); err != nil {
|
||||
t.Fatalf("grant no-ads: %v", err)
|
||||
}
|
||||
if p := getBannerTG(); p.Banner != nil {
|
||||
t.Fatal("an active no-ads benefit must suppress the banner")
|
||||
}
|
||||
// Fail-closed: without a trusted platform the same benefit does not apply, so the banner shows.
|
||||
if p := getBanner(); p.Banner == nil {
|
||||
t.Fatal("an untrusted context must not apply the no-ads benefit (banner should show)")
|
||||
}
|
||||
}
|
||||
|
||||
// TestBannerSurvivesProfileUpdate guards that a profile update (e.g. a language switch) returns the
|
||||
// banner block too, so the client's profile keeps the banner instead of losing it until reload.
|
||||
func TestBannerSurvivesProfileUpdate(t *testing.T) {
|
||||
srv, _ := bannerServer(t)
|
||||
srv, _, _ := bannerServer(t)
|
||||
id := provisionAccount(t)
|
||||
|
||||
body := `{"display_name":"Tester","preferred_language":"ru","time_zone":"UTC","away_start":"00:00",` +
|
||||
@@ -283,7 +316,7 @@ func TestBannerSurvivesProfileUpdate(t *testing.T) {
|
||||
// default campaign stays plain (colours + urgent are ignored for it).
|
||||
func TestBannerConsoleColorsAndUrgent(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
srv, adsSvc := bannerServer(t)
|
||||
srv, adsSvc, _ := bannerServer(t)
|
||||
h := srv.Handler()
|
||||
base := "http://admin.test/_gm"
|
||||
const origin = "http://admin.test"
|
||||
@@ -351,7 +384,7 @@ func TestBannerConsoleColorsAndUrgent(t *testing.T) {
|
||||
// otherwise suppress the banner.
|
||||
func TestBannerUrgentBypassesEligibility(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
srv, adsSvc := bannerServer(t)
|
||||
srv, adsSvc, _ := bannerServer(t)
|
||||
accounts := account.NewStore(testDB)
|
||||
id := provisionAccount(t)
|
||||
|
||||
|
||||
@@ -14,6 +14,8 @@ import (
|
||||
"scrabble/backend/internal/account"
|
||||
"scrabble/backend/internal/engine"
|
||||
"scrabble/backend/internal/game"
|
||||
"scrabble/backend/internal/payments"
|
||||
"scrabble/backend/internal/session"
|
||||
)
|
||||
|
||||
// TestListForAccount checks the lobby "my games" query: it returns exactly the
|
||||
@@ -401,8 +403,13 @@ func gameStatus(t *testing.T, svc *game.Service, id uuid.UUID) (status, endReaso
|
||||
// TestHintPolicy exercises the per-game allowance, the profile wallet and the
|
||||
// disabled switch.
|
||||
func TestHintPolicy(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
// A trusted platform context so the online hint wallet (payments) is reachable; a provisioned
|
||||
// account carries a telegram identity, so the telegram origin is the applicable one here.
|
||||
ctx := session.WithPlatform(context.Background(),
|
||||
session.Platform{Kind: session.PlatformKindTelegram, Subtype: session.SubtypeAndroid})
|
||||
svc := newGameService()
|
||||
pay := newPaymentsService()
|
||||
svc.SetHintWallet(pay) // share the handle so a grant invalidates the wallet the game reads
|
||||
seats := []uuid.UUID{provisionAccount(t), provisionAccount(t)}
|
||||
seed := openingSeed(t)
|
||||
g, err := svc.Create(ctx, game.CreateParams{
|
||||
@@ -428,7 +435,11 @@ func TestHintPolicy(t *testing.T) {
|
||||
if _, err := svc.Hint(ctx, g.ID, seats[0]); !errors.Is(err, game.ErrNoHintsLeft) {
|
||||
t.Fatalf("second hint = %v, want ErrNoHintsLeft", err)
|
||||
}
|
||||
setHintBalance(t, seats[0], 2)
|
||||
// Grant 2 hints on the telegram origin through the service so its read cache is invalidated
|
||||
// (a raw insert would leave the cache warmed at zero by the allowance hint above).
|
||||
if err := pay.Grant(ctx, seats[0], payments.SourceTelegram, 2, 0, false); err != nil {
|
||||
t.Fatalf("grant hints: %v", err)
|
||||
}
|
||||
res, err := svc.Hint(ctx, g.ID, seats[0]) // spends the wallet
|
||||
if err != nil {
|
||||
t.Fatalf("wallet hint: %v", err)
|
||||
@@ -603,14 +614,6 @@ func setAway(t *testing.T, id uuid.UUID, tz, start, end string) {
|
||||
}
|
||||
}
|
||||
|
||||
func setHintBalance(t *testing.T, id uuid.UUID, n int) {
|
||||
t.Helper()
|
||||
if _, err := testDB.ExecContext(context.Background(),
|
||||
`UPDATE backend.accounts SET hint_balance = $1 WHERE account_id = $2`, n, id); err != nil {
|
||||
t.Fatalf("set hint balance: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func equalStrings(a, b []string) bool {
|
||||
if len(a) != len(b) {
|
||||
return false
|
||||
|
||||
@@ -17,6 +17,7 @@ import (
|
||||
"scrabble/backend/internal/engine"
|
||||
"scrabble/backend/internal/game"
|
||||
"scrabble/backend/internal/lobby"
|
||||
"scrabble/backend/internal/payments"
|
||||
"scrabble/backend/internal/robot"
|
||||
"scrabble/backend/internal/social"
|
||||
)
|
||||
@@ -42,9 +43,42 @@ func newGameService() *game.Service {
|
||||
zap.NewNop(),
|
||||
)
|
||||
svc.SetFirstMoveEntropy(seatZeroFirstMove)
|
||||
svc.SetHintWallet(newPaymentsService())
|
||||
return svc
|
||||
}
|
||||
|
||||
// newPaymentsService builds a payments service over the shared pool (its own in-process read
|
||||
// cache), for wiring the game hint wallet and the account-merge fold in the integration suite.
|
||||
func newPaymentsService() *payments.Service {
|
||||
return payments.NewService(payments.NewStore(testDB))
|
||||
}
|
||||
|
||||
// seedBenefit writes a payments benefit row for an account+origin directly (bypassing the
|
||||
// service), used to stand up wallet state a test then spends or merges. A non-zero hints count
|
||||
// and/or the forever flag are set; a caller wanting a no-ads term sets it via seedBenefitUntil.
|
||||
func seedBenefit(t *testing.T, id uuid.UUID, origin string, hints int, forever bool) {
|
||||
t.Helper()
|
||||
if _, err := testDB.ExecContext(context.Background(),
|
||||
`INSERT INTO payments.benefits (account_id, origin, hints, ads_forever) VALUES ($1,$2,$3,$4)
|
||||
ON CONFLICT (account_id, origin) DO UPDATE SET hints = EXCLUDED.hints, ads_forever = EXCLUDED.ads_forever`,
|
||||
id, origin, hints, forever); err != nil {
|
||||
t.Fatalf("seed benefit: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// readBenefit reads an account's benefit row for an origin: the hint count and the forever flag
|
||||
// (both zero/false when the row is absent).
|
||||
func readBenefit(t *testing.T, id uuid.UUID, origin string) (hints int, forever bool) {
|
||||
t.Helper()
|
||||
err := testDB.QueryRowContext(context.Background(),
|
||||
`SELECT hints, ads_forever FROM payments.benefits WHERE account_id=$1 AND origin=$2`, id, origin).
|
||||
Scan(&hints, &forever)
|
||||
if err != nil && !errors.Is(err, sql.ErrNoRows) {
|
||||
t.Fatalf("read benefit: %v", err)
|
||||
}
|
||||
return hints, forever
|
||||
}
|
||||
|
||||
// seatZeroFirstMove is a first-move-draw entropy factory that always elects the first
|
||||
// listed account as the leader, keeping the integration suite's turn order stable
|
||||
// despite the real draw's randomness: the first contender draws a blank — the best
|
||||
|
||||
@@ -58,14 +58,6 @@ func bestMoveCount(t *testing.T, id uuid.UUID) int {
|
||||
return n
|
||||
}
|
||||
|
||||
func setWallet(t *testing.T, id uuid.UUID, hints int, paid bool) {
|
||||
t.Helper()
|
||||
if _, err := testDB.ExecContext(context.Background(),
|
||||
`UPDATE backend.accounts SET hint_balance=$2, paid_account=$3 WHERE account_id=$1`, id, hints, paid); err != nil {
|
||||
t.Fatalf("set wallet: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func bindEmailIdentity(t *testing.T, acc uuid.UUID, email string) {
|
||||
t.Helper()
|
||||
if _, err := testDB.ExecContext(context.Background(),
|
||||
@@ -131,6 +123,7 @@ func TestAccountMergeCore(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
store := account.NewStore(testDB)
|
||||
merger := accountmerge.NewMerger(testDB)
|
||||
merger.SetPayments(newPaymentsService())
|
||||
|
||||
primary := provisionAccount(t)
|
||||
secondary := provisionAccount(t)
|
||||
@@ -140,8 +133,8 @@ func TestAccountMergeCore(t *testing.T) {
|
||||
setStats(t, secondary, 3, 1, 2, 400, 80)
|
||||
setStatsCounts(t, primary, 100, 5)
|
||||
setStatsCounts(t, secondary, 50, 8)
|
||||
setWallet(t, primary, 2, false)
|
||||
setWallet(t, secondary, 5, true)
|
||||
seedBenefit(t, primary, "telegram", 2, false)
|
||||
seedBenefit(t, secondary, "telegram", 5, true) // hints sum, forever OR-s on merge
|
||||
// Best moves: secondary's scrabble_en (80) beats primary's (50) and is kept; secondary's
|
||||
// scrabble_ru (30) is new to primary and carried over.
|
||||
setBestMove(t, primary, "scrabble_en", 50)
|
||||
@@ -165,15 +158,13 @@ func TestAccountMergeCore(t *testing.T) {
|
||||
t.Error("secondary stats row should be deleted after merge")
|
||||
}
|
||||
|
||||
acc, err := store.GetByID(ctx, primary)
|
||||
if err != nil {
|
||||
t.Fatalf("get primary: %v", err)
|
||||
// The payments wallet merged by origin: hints sum (2+5) and the forever flag OR-s; the
|
||||
// deprecated accounts.hint_balance / paid_account columns are no longer touched by a merge.
|
||||
if hints, forever := readBenefit(t, primary, "telegram"); hints != 7 || !forever {
|
||||
t.Errorf("merged telegram benefit = hints %d forever %v, want 7/true", hints, forever)
|
||||
}
|
||||
if acc.HintBalance != 7 {
|
||||
t.Errorf("hint balance = %d, want 7", acc.HintBalance)
|
||||
}
|
||||
if !acc.PaidAccount {
|
||||
t.Error("paid_account should be true (ORed from secondary)")
|
||||
if hints, _ := readBenefit(t, secondary, "telegram"); hints != 0 {
|
||||
t.Errorf("secondary benefit should be cleared after merge, got hints %d", hints)
|
||||
}
|
||||
|
||||
if owner, ok, _ := store.AccountIDByIdentity(ctx, account.KindEmail, email); !ok || owner != primary {
|
||||
|
||||
@@ -0,0 +1,279 @@
|
||||
//go:build integration
|
||||
|
||||
package inttest
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"scrabble/backend/internal/payments"
|
||||
)
|
||||
|
||||
// seedBalance writes a chip balance for an account+source directly (payments has no FK to
|
||||
// accounts, so a bare uuid is a valid account id here).
|
||||
func seedBalance(t *testing.T, id uuid.UUID, source string, chips int) {
|
||||
t.Helper()
|
||||
if _, err := testDB.ExecContext(context.Background(),
|
||||
`INSERT INTO payments.balances (account_id, source, chips) VALUES ($1,$2,$3)
|
||||
ON CONFLICT (account_id, source) DO UPDATE SET chips = EXCLUDED.chips`,
|
||||
id, source, chips); err != nil {
|
||||
t.Fatalf("seed balance: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// readBalance reads an account's chip balance for a source (0 when the row is absent).
|
||||
func readBalance(t *testing.T, id uuid.UUID, source string) int {
|
||||
t.Helper()
|
||||
var chips int
|
||||
err := testDB.QueryRowContext(context.Background(),
|
||||
`SELECT chips FROM payments.balances WHERE account_id=$1 AND source=$2`, id, source).Scan(&chips)
|
||||
if err != nil && !errors.Is(err, sql.ErrNoRows) {
|
||||
t.Fatalf("read balance: %v", err)
|
||||
}
|
||||
return chips
|
||||
}
|
||||
|
||||
// benefitUntil reads an account's no-ads term end for an origin (nil when none).
|
||||
func benefitUntil(t *testing.T, id uuid.UUID, origin string) *time.Time {
|
||||
t.Helper()
|
||||
var until *time.Time
|
||||
err := testDB.QueryRowContext(context.Background(),
|
||||
`SELECT ads_paid_until FROM payments.benefits WHERE account_id=$1 AND origin=$2`, id, origin).Scan(&until)
|
||||
if err != nil && !errors.Is(err, sql.ErrNoRows) {
|
||||
t.Fatalf("read benefit until: %v", err)
|
||||
}
|
||||
return until
|
||||
}
|
||||
|
||||
// ledgerRows counts an account's ledger rows of a given kind.
|
||||
func ledgerRows(t *testing.T, id uuid.UUID, kind string) int {
|
||||
t.Helper()
|
||||
var n int
|
||||
if err := testDB.QueryRowContext(context.Background(),
|
||||
`SELECT count(*) FROM payments.ledger WHERE account_id=$1 AND kind=$2`, id, kind).Scan(&n); err != nil {
|
||||
t.Fatalf("ledger count: %v", err)
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
// seedValueProduct creates an active chip-priced value: a product with a CHIP price (method
|
||||
// NULL) and the given hint / no-ads-day atoms. It returns the product id.
|
||||
func seedValueProduct(t *testing.T, priceChips, hints, noAdsDays int) uuid.UUID {
|
||||
t.Helper()
|
||||
ctx := context.Background()
|
||||
prod := uuid.New()
|
||||
if _, err := testDB.ExecContext(ctx,
|
||||
`INSERT INTO payments.product (product_id, title, active) VALUES ($1,'test value',true)`, prod); err != nil {
|
||||
t.Fatalf("seed product: %v", err)
|
||||
}
|
||||
if _, err := testDB.ExecContext(ctx,
|
||||
`INSERT INTO payments.product_price (product_id, method, currency, amount) VALUES ($1, NULL, 'CHIP', $2)`,
|
||||
prod, priceChips); err != nil {
|
||||
t.Fatalf("seed price: %v", err)
|
||||
}
|
||||
if hints > 0 {
|
||||
if _, err := testDB.ExecContext(ctx,
|
||||
`INSERT INTO payments.product_item (product_id, atom_type, quantity) VALUES ($1,'hints',$2)`, prod, hints); err != nil {
|
||||
t.Fatalf("seed hints item: %v", err)
|
||||
}
|
||||
}
|
||||
if noAdsDays > 0 {
|
||||
if _, err := testDB.ExecContext(ctx,
|
||||
`INSERT INTO payments.product_item (product_id, atom_type, quantity) VALUES ($1,'noads_days',$2)`, prod, noAdsDays); err != nil {
|
||||
t.Fatalf("seed noads item: %v", err)
|
||||
}
|
||||
}
|
||||
return prod
|
||||
}
|
||||
|
||||
// TestPaymentsSpendAppliesAtomically verifies a chip spend writes the ledger row, decrements the
|
||||
// balance and applies the benefit together over Postgres.
|
||||
func TestPaymentsSpendAppliesAtomically(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
svc := newPaymentsService()
|
||||
acc := uuid.New()
|
||||
seedBalance(t, acc, "direct", 100)
|
||||
prod := seedValueProduct(t, 60, 3, 30)
|
||||
|
||||
if err := svc.Spend(ctx, acc, payments.NewContext("direct", "web"), []payments.Source{payments.SourceDirect}, prod); err != nil {
|
||||
t.Fatalf("spend: %v", err)
|
||||
}
|
||||
if got := readBalance(t, acc, "direct"); got != 40 {
|
||||
t.Errorf("balance after spend = %d, want 40", got)
|
||||
}
|
||||
if hints, _ := readBenefit(t, acc, "direct"); hints != 3 {
|
||||
t.Errorf("hints after spend = %d, want 3", hints)
|
||||
}
|
||||
if benefitUntil(t, acc, "direct") == nil {
|
||||
t.Error("no-ads term not applied by the spend")
|
||||
}
|
||||
if n := ledgerRows(t, acc, "spend"); n != 1 {
|
||||
t.Errorf("spend ledger rows = %d, want 1", n)
|
||||
}
|
||||
}
|
||||
|
||||
// TestPaymentsSpendInsufficientNoWrite verifies an under-funded spend is refused and writes
|
||||
// nothing (the balance, benefit and ledger are untouched).
|
||||
func TestPaymentsSpendInsufficientNoWrite(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
svc := newPaymentsService()
|
||||
acc := uuid.New()
|
||||
seedBalance(t, acc, "direct", 10)
|
||||
prod := seedValueProduct(t, 60, 3, 0)
|
||||
|
||||
if err := svc.Spend(ctx, acc, payments.NewContext("direct", "web"), []payments.Source{payments.SourceDirect}, prod); !errors.Is(err, payments.ErrInsufficientChips) {
|
||||
t.Fatalf("spend = %v, want ErrInsufficientChips", err)
|
||||
}
|
||||
if got := readBalance(t, acc, "direct"); got != 10 {
|
||||
t.Errorf("balance changed to %d, want 10 (no write)", got)
|
||||
}
|
||||
if h, _ := readBenefit(t, acc, "direct"); h != 0 {
|
||||
t.Errorf("benefit applied on a refused spend: hints %d", h)
|
||||
}
|
||||
if ledgerRows(t, acc, "spend") != 0 {
|
||||
t.Error("spend ledger row written on a refused spend")
|
||||
}
|
||||
}
|
||||
|
||||
// TestPaymentsSpendGuardRollsBack forces the in-transaction guard to bite: with a stale read
|
||||
// cache the draw plan looks affordable, but the guarded decrement matches no row and the whole
|
||||
// transaction rolls back — no ledger row, no benefit, balance unchanged.
|
||||
func TestPaymentsSpendGuardRollsBack(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
svc := newPaymentsService()
|
||||
acc := uuid.New()
|
||||
seedBalance(t, acc, "direct", 100)
|
||||
present := []payments.Source{payments.SourceDirect}
|
||||
cxt := payments.NewContext("direct", "web")
|
||||
if _, err := svc.Wallet(ctx, acc, cxt, present); err != nil { // warm the cache at 100
|
||||
t.Fatalf("warm: %v", err)
|
||||
}
|
||||
// Drain the real balance behind the cache's back (no invalidation), so the plan over-commits.
|
||||
if _, err := testDB.ExecContext(ctx, `UPDATE payments.balances SET chips = 10 WHERE account_id=$1 AND source='direct'`, acc); err != nil {
|
||||
t.Fatalf("drain: %v", err)
|
||||
}
|
||||
prod := seedValueProduct(t, 60, 3, 0)
|
||||
|
||||
if err := svc.Spend(ctx, acc, cxt, present, prod); !errors.Is(err, payments.ErrInsufficientChips) {
|
||||
t.Fatalf("spend = %v, want ErrInsufficientChips", err)
|
||||
}
|
||||
if got := readBalance(t, acc, "direct"); got != 10 {
|
||||
t.Errorf("balance = %d, want 10 (rolled back)", got)
|
||||
}
|
||||
if ledgerRows(t, acc, "spend") != 0 {
|
||||
t.Error("spend ledger row written despite the rollback")
|
||||
}
|
||||
if h, _ := readBenefit(t, acc, "direct"); h != 0 {
|
||||
t.Error("benefit applied despite the rollback")
|
||||
}
|
||||
}
|
||||
|
||||
// TestPaymentsGrantCreditsValuesNotChips verifies admin_grant applies a benefit at price 0
|
||||
// without ever crediting chips (D16).
|
||||
func TestPaymentsGrantCreditsValuesNotChips(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
svc := newPaymentsService()
|
||||
acc := uuid.New()
|
||||
|
||||
if err := svc.Grant(ctx, acc, payments.SourceDirect, 5, 0, true); err != nil {
|
||||
t.Fatalf("grant: %v", err)
|
||||
}
|
||||
if hints, forever := readBenefit(t, acc, "direct"); hints != 5 || !forever {
|
||||
t.Errorf("granted benefit = hints %d forever %v, want 5/true", hints, forever)
|
||||
}
|
||||
if readBalance(t, acc, "direct") != 0 {
|
||||
t.Error("a grant must not credit chips")
|
||||
}
|
||||
if ledgerRows(t, acc, "admin_grant") != 1 {
|
||||
t.Error("admin_grant ledger row missing")
|
||||
}
|
||||
if ledgerRows(t, acc, "spend") != 0 || ledgerRows(t, acc, "fund") != 0 {
|
||||
t.Error("a grant wrote a non-grant ledger row")
|
||||
}
|
||||
}
|
||||
|
||||
// TestPaymentsSpendHintByContext verifies a hint is drawn from an applicable origin, and that a
|
||||
// direct-origin hint is not usable inside a VK context (the compliance wall for hints).
|
||||
func TestPaymentsSpendHintByContext(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
svc := newPaymentsService()
|
||||
acc := uuid.New()
|
||||
seedBenefit(t, acc, "direct", 2, false)
|
||||
present := []payments.Source{payments.SourceDirect, payments.SourceVK}
|
||||
|
||||
if spent, err := svc.SpendHint(ctx, acc, payments.NewContext("direct", "web"), present); err != nil || !spent {
|
||||
t.Fatalf("web spend hint = %v (err %v), want true", spent, err)
|
||||
}
|
||||
if h, _ := readBenefit(t, acc, "direct"); h != 1 {
|
||||
t.Errorf("hints after spend = %d, want 1", h)
|
||||
}
|
||||
// Inside VK the applicable origins are {vk} only, so the direct-origin hint is untouched.
|
||||
if spent, _ := svc.SpendHint(ctx, acc, payments.NewContext("vk", "android"), present); spent {
|
||||
t.Error("direct-origin hint spent inside VK — compliance wall breached")
|
||||
}
|
||||
if h, _ := readBenefit(t, acc, "direct"); h != 1 {
|
||||
t.Errorf("direct hints changed inside VK = %d, want 1 (untouched)", h)
|
||||
}
|
||||
}
|
||||
|
||||
// TestPaymentsComplianceGateOverPostgres is the named compliance regression at the integration
|
||||
// layer: a direct-origin no-ads benefit applies on the web but never inside a store wrapper.
|
||||
func TestPaymentsComplianceGateOverPostgres(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
svc := newPaymentsService()
|
||||
acc := uuid.New()
|
||||
if err := svc.Grant(ctx, acc, payments.SourceDirect, 0, 30, false); err != nil {
|
||||
t.Fatalf("grant: %v", err)
|
||||
}
|
||||
present := []payments.Source{payments.SourceDirect, payments.SourceVK}
|
||||
|
||||
if adFree, _ := svc.AdFree(ctx, acc, payments.NewContext("direct", "web"), present); !adFree {
|
||||
t.Error("direct no-ads should apply on web")
|
||||
}
|
||||
if adFree, _ := svc.AdFree(ctx, acc, payments.NewContext("vk", "android"), present); adFree {
|
||||
t.Error("direct no-ads must NOT apply inside VK (compliance wall)")
|
||||
}
|
||||
if adFree, _ := svc.AdFree(ctx, acc, payments.NewContext("telegram", "web"), present); adFree {
|
||||
t.Error("direct no-ads must NOT apply inside Telegram (compliance wall)")
|
||||
}
|
||||
}
|
||||
|
||||
// TestPaymentsMergeFoldsSegmentsAndBenefits verifies the merge folds chip segments (sum) and
|
||||
// benefits (hints sum, forever OR) by origin, and clears the secondary's rows, over Postgres.
|
||||
func TestPaymentsMergeFoldsSegmentsAndBenefits(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
svc := newPaymentsService()
|
||||
primary, secondary := uuid.New(), uuid.New()
|
||||
seedBalance(t, primary, "vk", 10)
|
||||
seedBalance(t, secondary, "vk", 25)
|
||||
seedBenefit(t, primary, "vk", 1, false)
|
||||
seedBenefit(t, secondary, "vk", 4, true)
|
||||
|
||||
tx, err := testDB.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("begin: %v", err)
|
||||
}
|
||||
if err := svc.MergeTx(ctx, tx, primary, secondary); err != nil {
|
||||
_ = tx.Rollback()
|
||||
t.Fatalf("merge: %v", err)
|
||||
}
|
||||
if err := tx.Commit(); err != nil {
|
||||
t.Fatalf("commit: %v", err)
|
||||
}
|
||||
svc.Invalidate(primary, secondary)
|
||||
|
||||
if got := readBalance(t, primary, "vk"); got != 35 {
|
||||
t.Errorf("merged chips = %d, want 35", got)
|
||||
}
|
||||
if h, forever := readBenefit(t, primary, "vk"); h != 5 || !forever {
|
||||
t.Errorf("merged benefit = hints %d forever %v, want 5/true", h, forever)
|
||||
}
|
||||
if readBalance(t, secondary, "vk") != 0 {
|
||||
t.Error("secondary balance not cleared after merge")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
package payments
|
||||
|
||||
import (
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// benefitState is an account's benefit row for one origin: the no-ads term end (nil = none),
|
||||
// the perpetual forever flag, and the hint count. It is the context-independent stored form;
|
||||
// the read paths aggregate it over the origins applicable in a context.
|
||||
type benefitState struct {
|
||||
adsPaidUntil *time.Time
|
||||
adsForever bool
|
||||
hints int
|
||||
}
|
||||
|
||||
// walletState is an account's full payments state: chip balances by source and benefits by
|
||||
// origin. It is the raw, context-independent data every read path filters per execution
|
||||
// context — the value the cache holds and the store recomputes from the materialized tables.
|
||||
type walletState struct {
|
||||
chips map[Source]int
|
||||
benefits map[Source]benefitState
|
||||
}
|
||||
|
||||
// chipsOf returns the chip balance for a source, zero when the segment has no row (an absent
|
||||
// segment reads as zero, §2).
|
||||
func (w walletState) chipsOf(s Source) int { return w.chips[s] }
|
||||
|
||||
// benefitOf returns the benefit for an origin, the zero benefit when the origin has no row.
|
||||
func (w walletState) benefitOf(o Source) benefitState { return w.benefits[o] }
|
||||
|
||||
// walletCache is the payments read model: each account's chip/benefit state, keyed by account
|
||||
// id, read on every ad-eligibility / hint / wallet / gate request and invalidated on every
|
||||
// payments mutation (spend, grant, fund, refund, merge). It is a write-through cache in front
|
||||
// of the materialized balances/benefits tables — the same pattern the account-suspension gate
|
||||
// uses (backend/internal/account/suspension.go) — so the steady-state hot path issues no query
|
||||
// to the payments schema. It is single-instance, matching the deployment (one shared Store); a
|
||||
// multi-instance backend would need a shared cache.
|
||||
type walletCache struct {
|
||||
mu sync.RWMutex
|
||||
m map[uuid.UUID]walletState
|
||||
}
|
||||
|
||||
// newWalletCache constructs an empty cache.
|
||||
func newWalletCache() *walletCache {
|
||||
return &walletCache{m: make(map[uuid.UUID]walletState)}
|
||||
}
|
||||
|
||||
// get returns the cached state for an account and whether it was present.
|
||||
func (c *walletCache) get(id uuid.UUID) (walletState, bool) {
|
||||
c.mu.RLock()
|
||||
defer c.mu.RUnlock()
|
||||
s, ok := c.m[id]
|
||||
return s, ok
|
||||
}
|
||||
|
||||
// put stores an account's state.
|
||||
func (c *walletCache) put(id uuid.UUID, s walletState) {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
c.m[id] = s
|
||||
}
|
||||
|
||||
// invalidate drops an account's entry so the next read reloads it from the materialized tables.
|
||||
// Called after every mutation once its transaction has committed.
|
||||
func (c *walletCache) invalidate(id uuid.UUID) {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
delete(c.m, id)
|
||||
}
|
||||
@@ -0,0 +1,202 @@
|
||||
package payments
|
||||
|
||||
import (
|
||||
"slices"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Source is the platform axis a chip balance is segmented by (where it was funded) and a
|
||||
// benefit is stamped with (where it was bought — its origin). The two roles share this value
|
||||
// set but mean different things (see docs/PAYMENTS.md §3); Source names the axis for both.
|
||||
type Source string
|
||||
|
||||
const (
|
||||
// SourceVK is the VK platform: Votes purchases and VK rewarded ads fund here.
|
||||
SourceVK Source = "vk"
|
||||
// SourceTelegram is the Telegram platform: Stars purchases fund here.
|
||||
SourceTelegram Source = "telegram"
|
||||
// SourceDirect is the open web / native context: Robokassa purchases fund here.
|
||||
SourceDirect Source = "direct"
|
||||
)
|
||||
|
||||
// Valid reports whether s is one of the three known platform sources.
|
||||
func (s Source) Valid() bool {
|
||||
switch s {
|
||||
case SourceVK, SourceTelegram, SourceDirect:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// SubtypeIOS is the one device subtype the gate keys on: VK on iOS is frozen for spending
|
||||
// (Apple forbids spending virtual currency on digital goods outside IAP). It is trusted only
|
||||
// for VK, where it rides inside the signed launch parameters.
|
||||
const SubtypeIOS = "ios"
|
||||
|
||||
// SourceForIdentityKind maps a backend identity kind to the payments source whose segment that
|
||||
// identity makes available: a vk/telegram identity to its own source, a durable email identity
|
||||
// to the direct source (the web/native recovery anchor). A robot identity — or any unknown
|
||||
// kind — maps to no source (second return false). Callers use it to build the present set the
|
||||
// payments interface takes, since payments cannot read the account schema.
|
||||
func SourceForIdentityKind(kind string) (Source, bool) {
|
||||
switch kind {
|
||||
case "vk":
|
||||
return SourceVK, true
|
||||
case "telegram":
|
||||
return SourceTelegram, true
|
||||
case "email":
|
||||
return SourceDirect, true
|
||||
default:
|
||||
return "", false
|
||||
}
|
||||
}
|
||||
|
||||
// PresentSources maps an account's identity kinds to the payments sources they make available
|
||||
// (§6), de-duplicated: vk→vk, telegram→telegram, email→direct; a robot or unknown kind maps to
|
||||
// nothing. Callers pass the kinds from account.Identities so the gate — which holds no
|
||||
// cross-schema identity knowledge — can resolve which segments are awake.
|
||||
func PresentSources(kinds []string) []Source {
|
||||
var out []Source
|
||||
for _, k := range kinds {
|
||||
if s, ok := SourceForIdentityKind(k); ok && !has(out, s) {
|
||||
out = append(out, s)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// Context is the trusted execution context the store-compliance gate keys on: the platform
|
||||
// Kind (the source the wrapper enforces) plus, for VK, the trusted Subtype (only the VK-iOS
|
||||
// freeze depends on it). The zero Context (empty Kind) is an untrusted platform — the gate is
|
||||
// fail-closed there: no spend, no purchase, no foreign-origin benefit, view only.
|
||||
type Context struct {
|
||||
Kind Source
|
||||
Subtype string
|
||||
}
|
||||
|
||||
// NewContext builds a Context from the session platform's kind and subtype strings (as carried
|
||||
// on the trusted X-Platform signal). An unrecognised or empty kind yields an untrusted Context.
|
||||
func NewContext(kind, subtype string) Context {
|
||||
k := Source(kind)
|
||||
if !k.Valid() {
|
||||
return Context{}
|
||||
}
|
||||
return Context{Kind: k, Subtype: subtype}
|
||||
}
|
||||
|
||||
// Trusted reports whether the platform is trusted (a known kind). An untrusted context denies
|
||||
// every spend/purchase and the application of any foreign origin.
|
||||
func (c Context) Trusted() bool { return c.Kind.Valid() }
|
||||
|
||||
// vkFrozen reports whether this is the VK-iOS spend freeze: VK context on the trusted iOS
|
||||
// subtype. A previously bought benefit still applies there, but no spend or purchase is possible.
|
||||
func (c Context) vkFrozen() bool { return c.Kind == SourceVK && c.Subtype == SubtypeIOS }
|
||||
|
||||
// spendPriority is the fixed draw order when several segments are spendable in one context
|
||||
// (D7): the "home" direct segment first, the store-funded segments after.
|
||||
var spendPriority = []Source{SourceDirect, SourceVK, SourceTelegram}
|
||||
|
||||
// has reports whether present contains s.
|
||||
func has(present []Source, s Source) bool {
|
||||
return slices.Contains(present, s)
|
||||
}
|
||||
|
||||
// spendableSources returns the chip segments that may be SPENT in the context, in draw-priority
|
||||
// order, restricted to the sources the account actually has (present). It is empty when the
|
||||
// platform is untrusted (fail-closed) or VK-iOS (frozen): inside VK/TG only the same-named
|
||||
// segment is spendable; on web/native all attached segments are, drained direct→vk→tg.
|
||||
func spendableSources(c Context, present []Source) []Source {
|
||||
if !c.Trusted() || c.vkFrozen() {
|
||||
return nil
|
||||
}
|
||||
switch c.Kind {
|
||||
case SourceVK, SourceTelegram:
|
||||
if has(present, c.Kind) {
|
||||
return []Source{c.Kind}
|
||||
}
|
||||
return nil
|
||||
default: // direct (web/native)
|
||||
var out []Source
|
||||
for _, s := range spendPriority {
|
||||
if has(present, s) {
|
||||
out = append(out, s)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
}
|
||||
|
||||
// applicableOrigins returns the benefit origins that APPLY in the context, in draw-priority
|
||||
// order, restricted to present sources. It differs from spendableSources in one way: VK-iOS is
|
||||
// NOT excluded — a benefit bought earlier still applies while spending is frozen. Inside VK/TG
|
||||
// only the same-named origin applies (a foreign, e.g. direct, origin never activates inside a
|
||||
// store — the compliance wall); on web/native direct+vk+tg all apply, drained direct→vk→tg.
|
||||
func applicableOrigins(c Context, present []Source) []Source {
|
||||
if !c.Trusted() {
|
||||
return nil
|
||||
}
|
||||
switch c.Kind {
|
||||
case SourceVK, SourceTelegram:
|
||||
if has(present, c.Kind) {
|
||||
return []Source{c.Kind}
|
||||
}
|
||||
return nil
|
||||
default: // direct (web/native)
|
||||
var out []Source
|
||||
for _, s := range spendPriority {
|
||||
if has(present, s) {
|
||||
out = append(out, s)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
}
|
||||
|
||||
// visibleSources returns the segments the wallet shows in the context, regardless of whether
|
||||
// they are spendable: inside a store only the same-named segment (the others are invisible
|
||||
// there); on web/native or an untrusted context all three (untrusted shows them view-only).
|
||||
func visibleSources(c Context) []Source {
|
||||
switch c.Kind {
|
||||
case SourceVK, SourceTelegram:
|
||||
return []Source{c.Kind}
|
||||
default:
|
||||
return spendPriority
|
||||
}
|
||||
}
|
||||
|
||||
// Segment is one chip balance the wallet shows: the source, its chip count, and whether it can
|
||||
// be spent in the current context (false for a frozen VK-iOS balance or an untrusted platform).
|
||||
type Segment struct {
|
||||
Source Source
|
||||
Chips int
|
||||
Spendable bool
|
||||
}
|
||||
|
||||
// BenefitView is the benefit state applicable in the current context: whether ads are off (and
|
||||
// until when, or forever) and how many hints are available. It aggregates over the origins
|
||||
// applicable in the context (§5).
|
||||
type BenefitView struct {
|
||||
AdsForever bool
|
||||
AdsPaidUntil *time.Time
|
||||
Hints int
|
||||
}
|
||||
|
||||
// WalletView is the read model returned to the wallet: the visible segments plus the
|
||||
// context-applicable benefits.
|
||||
type WalletView struct {
|
||||
Segments []Segment
|
||||
Benefits BenefitView
|
||||
}
|
||||
|
||||
// benefitDelta is the benefit change a spend or grant applies to one origin: hints added, a
|
||||
// no-ads term in whole days (stacked from max(now, current end)), and the perpetual forever
|
||||
// flag (which overrides terms).
|
||||
type benefitDelta struct {
|
||||
hintsAdd int
|
||||
noAdsDays int
|
||||
forever bool
|
||||
}
|
||||
|
||||
// zero reports whether the delta changes nothing.
|
||||
func (d benefitDelta) zero() bool { return d.hintsAdd == 0 && d.noAdsDays == 0 && !d.forever }
|
||||
@@ -0,0 +1,132 @@
|
||||
package payments
|
||||
|
||||
import (
|
||||
"slices"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// allPresent is an account attached to every source (the maximal present set).
|
||||
var allPresent = []Source{SourceDirect, SourceVK, SourceTelegram}
|
||||
|
||||
func TestSpendableSources(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
ctx Context
|
||||
present []Source
|
||||
want []Source
|
||||
}{
|
||||
{"vk android, vk present", Context{Kind: SourceVK, Subtype: "android"}, allPresent, []Source{SourceVK}},
|
||||
{"vk ios frozen", Context{Kind: SourceVK, Subtype: SubtypeIOS}, allPresent, nil},
|
||||
{"vk android, vk absent", Context{Kind: SourceVK, Subtype: "android"}, []Source{SourceDirect}, nil},
|
||||
{"telegram", Context{Kind: SourceTelegram, Subtype: "web"}, allPresent, []Source{SourceTelegram}},
|
||||
{"telegram, tg absent", Context{Kind: SourceTelegram}, []Source{SourceVK}, nil},
|
||||
{"direct all present, priority", Context{Kind: SourceDirect, Subtype: "web"}, allPresent, []Source{SourceDirect, SourceVK, SourceTelegram}},
|
||||
{"direct, only vk+tg attached", Context{Kind: SourceDirect}, []Source{SourceTelegram, SourceVK}, []Source{SourceVK, SourceTelegram}},
|
||||
{"direct, nothing attached", Context{Kind: SourceDirect}, nil, nil},
|
||||
{"untrusted fail-closed", Context{}, allPresent, nil},
|
||||
}
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
if got := spendableSources(tc.ctx, tc.present); !slices.Equal(got, tc.want) {
|
||||
t.Errorf("spendableSources(%+v, %v) = %v, want %v", tc.ctx, tc.present, got, tc.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestApplicableOrigins(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
ctx Context
|
||||
present []Source
|
||||
want []Source
|
||||
}{
|
||||
// A benefit still APPLIES on VK-iOS while spending is frozen.
|
||||
{"vk ios still applies", Context{Kind: SourceVK, Subtype: SubtypeIOS}, allPresent, []Source{SourceVK}},
|
||||
{"vk android", Context{Kind: SourceVK, Subtype: "android"}, allPresent, []Source{SourceVK}},
|
||||
{"telegram", Context{Kind: SourceTelegram}, allPresent, []Source{SourceTelegram}},
|
||||
{"direct all, priority", Context{Kind: SourceDirect}, allPresent, []Source{SourceDirect, SourceVK, SourceTelegram}},
|
||||
{"untrusted fail-closed", Context{}, allPresent, nil},
|
||||
}
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
if got := applicableOrigins(tc.ctx, tc.present); !slices.Equal(got, tc.want) {
|
||||
t.Errorf("applicableOrigins(%+v, %v) = %v, want %v", tc.ctx, tc.present, got, tc.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestComplianceWall is the named unit-level compliance regression: a direct origin (externally
|
||||
// paid, outside any store cash desk) must NEVER be applicable inside a VK or TG wrapper, and no
|
||||
// segment is ever spendable there beyond the same-named one. The dangerous direction stays shut.
|
||||
func TestComplianceWall(t *testing.T) {
|
||||
for _, kind := range []Source{SourceVK, SourceTelegram} {
|
||||
for _, sub := range []string{"android", "ios", "web"} {
|
||||
ctx := Context{Kind: kind, Subtype: sub}
|
||||
if slices.Contains(applicableOrigins(ctx, allPresent), SourceDirect) {
|
||||
t.Errorf("direct origin applies inside %s/%s — compliance wall breached", kind, sub)
|
||||
}
|
||||
for _, s := range spendableSources(ctx, allPresent) {
|
||||
if s != kind {
|
||||
t.Errorf("foreign segment %s spendable inside %s/%s", s, kind, sub)
|
||||
}
|
||||
}
|
||||
// The opposite store's origin must not leak in either (vk⊥tg).
|
||||
other := SourceVK
|
||||
if kind == SourceVK {
|
||||
other = SourceTelegram
|
||||
}
|
||||
if slices.Contains(applicableOrigins(ctx, allPresent), other) {
|
||||
t.Errorf("%s origin applies inside %s — cross-store leak", other, kind)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestVisibleSources(t *testing.T) {
|
||||
if got := visibleSources(Context{Kind: SourceVK, Subtype: SubtypeIOS}); !slices.Equal(got, []Source{SourceVK}) {
|
||||
t.Errorf("VK visible = %v, want [vk] (direct/tg hidden in a store)", got)
|
||||
}
|
||||
if got := visibleSources(Context{Kind: SourceDirect}); !slices.Equal(got, allPresent) {
|
||||
t.Errorf("direct visible = %v, want all three", got)
|
||||
}
|
||||
if got := visibleSources(Context{}); !slices.Equal(got, allPresent) {
|
||||
t.Errorf("untrusted visible = %v, want all three (view-only)", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSourceForIdentityKind(t *testing.T) {
|
||||
tests := []struct {
|
||||
kind string
|
||||
want Source
|
||||
ok bool
|
||||
}{
|
||||
{"vk", SourceVK, true},
|
||||
{"telegram", SourceTelegram, true},
|
||||
{"email", SourceDirect, true},
|
||||
{"robot", "", false},
|
||||
{"unknown", "", false},
|
||||
}
|
||||
for _, tc := range tests {
|
||||
got, ok := SourceForIdentityKind(tc.kind)
|
||||
if got != tc.want || ok != tc.ok {
|
||||
t.Errorf("SourceForIdentityKind(%q) = %q,%v want %q,%v", tc.kind, got, ok, tc.want, tc.ok)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewContextTrusted(t *testing.T) {
|
||||
if c := NewContext("vk", "ios"); !c.Trusted() || !c.vkFrozen() {
|
||||
t.Errorf("vk/ios: trusted=%v frozen=%v, want true/true", c.Trusted(), c.vkFrozen())
|
||||
}
|
||||
if c := NewContext("bogus", "web"); c.Trusted() {
|
||||
t.Errorf("bogus kind should be untrusted")
|
||||
}
|
||||
if c := NewContext("", ""); c.Trusted() {
|
||||
t.Errorf("empty kind should be untrusted")
|
||||
}
|
||||
if c := NewContext("direct", "web"); c.vkFrozen() {
|
||||
t.Errorf("direct is never frozen")
|
||||
}
|
||||
}
|
||||
@@ -1,17 +1,234 @@
|
||||
package payments
|
||||
|
||||
import "context"
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
// Service is the payments domain's application layer — the narrow surface other
|
||||
// domains depend on, keeping the schema reachable through one seam. The
|
||||
// data-foundation layer exposes only a health check; the wallet, benefit and
|
||||
// store-compliance operations arrive with the currency mechanics.
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// Service is the payments domain's application layer — the narrow surface other domains depend
|
||||
// on, keeping the schema reachable through one seam. Every read/gate method takes the trusted
|
||||
// execution Context and the account's present identity sources (which segments are awake, §6);
|
||||
// payments holds no cross-schema identity knowledge, so the caller supplies present. Reads are
|
||||
// served from the store's in-process cache, so the steady-state hot path issues no query to the
|
||||
// payments schema.
|
||||
type Service struct {
|
||||
store *Store
|
||||
clock func() time.Time
|
||||
}
|
||||
|
||||
// NewService constructs a Service over store.
|
||||
func NewService(store *Store) *Service { return &Service{store: store} }
|
||||
// NewService constructs a Service over store with a wall-clock time source.
|
||||
func NewService(store *Store) *Service {
|
||||
return &Service{store: store, clock: func() time.Time { return time.Now().UTC() }}
|
||||
}
|
||||
|
||||
// Ping reports whether the payments schema is reachable.
|
||||
func (s *Service) Ping(ctx context.Context) error { return s.store.Ping(ctx) }
|
||||
|
||||
// Wallet returns the read model for the account in the execution context: the segments visible
|
||||
// there (each with its chip count and whether it is spendable) plus the context-applicable
|
||||
// benefits. In a store context only the same-named segment is shown; on web/native or an
|
||||
// untrusted platform all attached segments are shown, spendable only when the gate allows.
|
||||
func (s *Service) Wallet(ctx context.Context, accountID uuid.UUID, cxt Context, present []Source) (WalletView, error) {
|
||||
st, err := s.store.state(ctx, accountID)
|
||||
if err != nil {
|
||||
return WalletView{}, err
|
||||
}
|
||||
now := s.clock()
|
||||
view := WalletView{Benefits: benefitView(st, cxt, present, now)}
|
||||
spendable := spendableSources(cxt, present)
|
||||
for _, src := range visibleSources(cxt) {
|
||||
if !has(present, src) {
|
||||
continue // only the account's own (attached) segments are shown
|
||||
}
|
||||
view.Segments = append(view.Segments, Segment{
|
||||
Source: src,
|
||||
Chips: st.chipsOf(src),
|
||||
Spendable: has(spendable, src),
|
||||
})
|
||||
}
|
||||
return view, nil
|
||||
}
|
||||
|
||||
// AdFree reports whether ads are suppressed for the account in the context: some origin
|
||||
// applicable there has an active no-ads term or the forever flag. Fail-closed on an untrusted
|
||||
// platform (no origin applies).
|
||||
func (s *Service) AdFree(ctx context.Context, accountID uuid.UUID, cxt Context, present []Source) (bool, error) {
|
||||
st, err := s.store.state(ctx, accountID)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
now := s.clock()
|
||||
for _, o := range applicableOrigins(cxt, present) {
|
||||
b := st.benefitOf(o)
|
||||
if b.adsForever || (b.adsPaidUntil != nil && b.adsPaidUntil.After(now)) {
|
||||
return true, nil
|
||||
}
|
||||
}
|
||||
return false, nil
|
||||
}
|
||||
|
||||
// HintsAvailable returns how many hints the account can use in the context — the sum over the
|
||||
// applicable origins. Zero on an untrusted platform.
|
||||
func (s *Service) HintsAvailable(ctx context.Context, accountID uuid.UUID, cxt Context, present []Source) (int, error) {
|
||||
st, err := s.store.state(ctx, accountID)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
total := 0
|
||||
for _, o := range applicableOrigins(cxt, present) {
|
||||
total += st.benefitOf(o).hints
|
||||
}
|
||||
return total, nil
|
||||
}
|
||||
|
||||
// SpendHint consumes one hint from the first applicable origin that has one (priority
|
||||
// direct→vk→tg), returning whether a hint was spent. It spends nothing when no origin is
|
||||
// applicable (untrusted platform or no attached segment).
|
||||
func (s *Service) SpendHint(ctx context.Context, accountID uuid.UUID, cxt Context, present []Source) (bool, error) {
|
||||
origins := applicableOrigins(cxt, present)
|
||||
if len(origins) == 0 {
|
||||
return false, nil
|
||||
}
|
||||
return s.store.consumeHint(ctx, accountID, origins, s.clock())
|
||||
}
|
||||
|
||||
// Spend buys a chip-priced value: it gate-checks the context, draws the price across the
|
||||
// spendable segments by priority direct→vk→tg, and applies the benefit — atomically. The
|
||||
// benefit's origin is the purchase context. It fails closed on an untrusted or frozen platform
|
||||
// (ErrUntrusted) and on insufficient chips (ErrInsufficientChips).
|
||||
func (s *Service) Spend(ctx context.Context, accountID uuid.UUID, cxt Context, present []Source, productID uuid.UUID) error {
|
||||
spendable := spendableSources(cxt, present)
|
||||
if len(spendable) == 0 {
|
||||
return ErrUntrusted // untrusted, frozen, or no attached segment — no spend
|
||||
}
|
||||
prod, err := s.store.loadProduct(ctx, productID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
st, err := s.store.state(ctx, accountID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
draws, ok := planDraws(st, spendable, prod.priceChips)
|
||||
if !ok {
|
||||
return ErrInsufficientChips
|
||||
}
|
||||
snapshot, err := marshalSnapshot(prod)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return s.store.spend(ctx, accountID, draws, cxt.Kind, productID, prod.delta, snapshot, s.clock())
|
||||
}
|
||||
|
||||
// Grant applies a benefit to an origin as a zero-price sale — an admin_grant ledger row and the
|
||||
// benefit (hints, a no-ads term in whole days, or the forever flag). It never grants chips (no
|
||||
// balance is touched — D16), so its signature has no chip amount. The origin is the admin's
|
||||
// compliance choice.
|
||||
func (s *Service) Grant(ctx context.Context, accountID uuid.UUID, origin Source, hints, noAdsDays int, forever bool) error {
|
||||
if !origin.Valid() {
|
||||
return fmt.Errorf("payments: invalid grant origin %q", origin)
|
||||
}
|
||||
d := benefitDelta{hintsAdd: hints, noAdsDays: noAdsDays, forever: forever}
|
||||
if d.zero() {
|
||||
return fmt.Errorf("payments: empty grant")
|
||||
}
|
||||
snapshot, err := marshalGrant(d)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return s.store.grant(ctx, accountID, origin, d, snapshot, s.clock())
|
||||
}
|
||||
|
||||
// MergeTx merges the secondary account's segments and benefits into the primary inside the
|
||||
// caller's transaction (the account-merge flow). The caller invalidates the affected caches
|
||||
// after committing (Invalidate).
|
||||
func (s *Service) MergeTx(ctx context.Context, tx *sql.Tx, primary, secondary uuid.UUID) error {
|
||||
return s.store.MergeTx(ctx, tx, primary, secondary, s.clock())
|
||||
}
|
||||
|
||||
// Invalidate drops the cached state of the listed accounts (called after a merge commit).
|
||||
func (s *Service) Invalidate(ids ...uuid.UUID) { s.store.Invalidate(ids...) }
|
||||
|
||||
// benefitView aggregates the benefits applicable in the context into the wallet view: ads-off
|
||||
// forever if any applicable origin is perpetual, else the latest active term end, plus the total
|
||||
// available hints.
|
||||
func benefitView(st walletState, cxt Context, present []Source, now time.Time) BenefitView {
|
||||
var v BenefitView
|
||||
for _, o := range applicableOrigins(cxt, present) {
|
||||
b := st.benefitOf(o)
|
||||
if b.adsForever {
|
||||
v.AdsForever = true
|
||||
}
|
||||
if b.adsPaidUntil != nil && b.adsPaidUntil.After(now) {
|
||||
if v.AdsPaidUntil == nil || b.adsPaidUntil.After(*v.AdsPaidUntil) {
|
||||
v.AdsPaidUntil = b.adsPaidUntil
|
||||
}
|
||||
}
|
||||
v.Hints += b.hints
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
// planDraws greedily allocates price across the spendable segments in priority order, draining
|
||||
// each before moving on. It returns the per-segment draws and whether the segments together held
|
||||
// enough.
|
||||
func planDraws(st walletState, spendable []Source, price int) ([]sourceAmount, bool) {
|
||||
remaining := price
|
||||
var draws []sourceAmount
|
||||
for _, src := range spendable {
|
||||
if remaining <= 0 {
|
||||
break
|
||||
}
|
||||
avail := st.chipsOf(src)
|
||||
if avail <= 0 {
|
||||
continue
|
||||
}
|
||||
take := min(avail, remaining)
|
||||
draws = append(draws, sourceAmount{source: src, amount: take})
|
||||
remaining -= take
|
||||
}
|
||||
if remaining > 0 {
|
||||
return nil, false
|
||||
}
|
||||
return draws, true
|
||||
}
|
||||
|
||||
// purchaseSnapshot is the catalog snapshot stored on a spend/grant ledger row, so history and
|
||||
// receipts stay independent of later catalog edits (§7/D34).
|
||||
type purchaseSnapshot struct {
|
||||
ProductID string `json:"product_id,omitempty"`
|
||||
Title string `json:"title,omitempty"`
|
||||
Atoms map[string]int `json:"atoms,omitempty"`
|
||||
PriceChips int `json:"price_chips"`
|
||||
Forever bool `json:"forever,omitempty"`
|
||||
}
|
||||
|
||||
// marshalSnapshot builds the snapshot for a chip spend.
|
||||
func marshalSnapshot(p catalogProduct) ([]byte, error) {
|
||||
b, err := json.Marshal(purchaseSnapshot{ProductID: p.id.String(), Title: p.title, Atoms: p.atoms, PriceChips: p.priceChips})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("payments: marshal snapshot: %w", err)
|
||||
}
|
||||
return b, nil
|
||||
}
|
||||
|
||||
// marshalGrant builds the snapshot for an admin grant (price 0).
|
||||
func marshalGrant(d benefitDelta) ([]byte, error) {
|
||||
atoms := map[string]int{}
|
||||
if d.hintsAdd > 0 {
|
||||
atoms["hints"] = d.hintsAdd
|
||||
}
|
||||
if d.noAdsDays > 0 {
|
||||
atoms["noads_days"] = d.noAdsDays
|
||||
}
|
||||
b, err := json.Marshal(purchaseSnapshot{Atoms: atoms, PriceChips: 0, Forever: d.forever})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("payments: marshal grant snapshot: %w", err)
|
||||
}
|
||||
return b, nil
|
||||
}
|
||||
|
||||
@@ -14,13 +14,16 @@ import (
|
||||
// Store is the Postgres-backed query surface for the payments schema. It is the
|
||||
// only place in the backend that issues SQL against payments.* (an
|
||||
// import-boundary test enforces it), so the domain stays extractable into its
|
||||
// own database.
|
||||
// own database. It fronts the materialized balances/benefits tables with an
|
||||
// in-process write-through cache (see cache.go) so hot reads issue no query on
|
||||
// the steady-state path.
|
||||
type Store struct {
|
||||
db *sql.DB
|
||||
db *sql.DB
|
||||
cache *walletCache
|
||||
}
|
||||
|
||||
// NewStore constructs a Store wrapping db.
|
||||
func NewStore(db *sql.DB) *Store { return &Store{db: db} }
|
||||
// NewStore constructs a Store wrapping db, with an empty read cache.
|
||||
func NewStore(db *sql.DB) *Store { return &Store{db: db, cache: newWalletCache()} }
|
||||
|
||||
// Ping verifies the payments schema is reachable by reading the singleton config
|
||||
// row. It is the data-foundation health check; the wallet query surface arrives
|
||||
|
||||
@@ -0,0 +1,421 @@
|
||||
package payments
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/go-jet/jet/v2/postgres"
|
||||
"github.com/go-jet/jet/v2/qrm"
|
||||
"github.com/google/uuid"
|
||||
|
||||
"scrabble/backend/internal/postgres/jet/payments/model"
|
||||
"scrabble/backend/internal/postgres/jet/payments/table"
|
||||
)
|
||||
|
||||
// Domain errors surfaced by the payments store and service.
|
||||
var (
|
||||
// ErrInsufficientChips means the spendable segments held fewer chips than the price.
|
||||
ErrInsufficientChips = errors.New("payments: insufficient chips")
|
||||
// ErrUntrusted means the platform context is untrusted, so the gate is fail-closed.
|
||||
ErrUntrusted = errors.New("payments: untrusted platform")
|
||||
// ErrProductNotFound means the product is absent or deactivated.
|
||||
ErrProductNotFound = errors.New("payments: product not found")
|
||||
// ErrNotAValue means the product has no chip price (it is a chip pack or unpriced), so it
|
||||
// cannot be bought with chips.
|
||||
ErrNotAValue = errors.New("payments: product is not a chip-priced value")
|
||||
)
|
||||
|
||||
// withTx runs fn inside a transaction on db, rolling back on error or panic.
|
||||
func withTx(ctx context.Context, db *sql.DB, fn func(*sql.Tx) error) (err error) {
|
||||
tx, err := db.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return fmt.Errorf("payments: begin tx: %w", err)
|
||||
}
|
||||
defer func() {
|
||||
if p := recover(); p != nil {
|
||||
_ = tx.Rollback()
|
||||
panic(p)
|
||||
}
|
||||
}()
|
||||
if err := fn(tx); err != nil {
|
||||
_ = tx.Rollback()
|
||||
return err
|
||||
}
|
||||
if err := tx.Commit(); err != nil {
|
||||
return fmt.Errorf("payments: commit tx: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// sourceAmount is one chip draw from a single segment during a spend.
|
||||
type sourceAmount struct {
|
||||
source Source
|
||||
amount int
|
||||
}
|
||||
|
||||
// catalogProduct is a product resolved for a chip spend: its chip price, the benefit its atoms
|
||||
// fold into, and the raw atom composition for the purchase snapshot.
|
||||
type catalogProduct struct {
|
||||
id uuid.UUID
|
||||
title string
|
||||
priceChips int
|
||||
delta benefitDelta
|
||||
atoms map[string]int
|
||||
}
|
||||
|
||||
// loadState reads an account's balances and benefits straight from the materialized tables.
|
||||
func (s *Store) loadState(ctx context.Context, accountID uuid.UUID) (walletState, error) {
|
||||
st := walletState{chips: map[Source]int{}, benefits: map[Source]benefitState{}}
|
||||
var brows []model.Balances
|
||||
if err := postgres.SELECT(table.Balances.AllColumns).
|
||||
FROM(table.Balances).
|
||||
WHERE(table.Balances.AccountID.EQ(postgres.UUID(accountID))).
|
||||
QueryContext(ctx, s.db, &brows); err != nil {
|
||||
return walletState{}, fmt.Errorf("payments: load balances %s: %w", accountID, err)
|
||||
}
|
||||
for _, r := range brows {
|
||||
st.chips[Source(r.Source)] = int(r.Chips)
|
||||
}
|
||||
var frows []model.Benefits
|
||||
if err := postgres.SELECT(table.Benefits.AllColumns).
|
||||
FROM(table.Benefits).
|
||||
WHERE(table.Benefits.AccountID.EQ(postgres.UUID(accountID))).
|
||||
QueryContext(ctx, s.db, &frows); err != nil {
|
||||
return walletState{}, fmt.Errorf("payments: load benefits %s: %w", accountID, err)
|
||||
}
|
||||
for _, r := range frows {
|
||||
st.benefits[Source(r.Origin)] = benefitState{adsPaidUntil: r.AdsPaidUntil, adsForever: r.AdsForever, hints: int(r.Hints)}
|
||||
}
|
||||
return st, nil
|
||||
}
|
||||
|
||||
// state returns an account's payments state, served from the read cache when warm, otherwise
|
||||
// loaded from the materialized tables and cached. The returned maps are read-only.
|
||||
func (s *Store) state(ctx context.Context, accountID uuid.UUID) (walletState, error) {
|
||||
if st, ok := s.cache.get(accountID); ok {
|
||||
return st, nil
|
||||
}
|
||||
st, err := s.loadState(ctx, accountID)
|
||||
if err != nil {
|
||||
return walletState{}, err
|
||||
}
|
||||
s.cache.put(accountID, st)
|
||||
return st, nil
|
||||
}
|
||||
|
||||
// Invalidate drops the cached state of every listed account so the next read reloads it. It is
|
||||
// called after a committed mutation whose transaction the payments package does not own — the
|
||||
// account-merge flow (after its own commit) and, later, external fund/refund intake.
|
||||
func (s *Store) Invalidate(ids ...uuid.UUID) {
|
||||
for _, id := range ids {
|
||||
s.cache.invalidate(id)
|
||||
}
|
||||
}
|
||||
|
||||
// loadProduct resolves a chip-priced value: an active product with a CHIP price row
|
||||
// (method NULL) whose atoms are benefits (hints / no-ads days). It rejects a missing or
|
||||
// deactivated product (ErrProductNotFound), a product with no chip price (ErrNotAValue), and a
|
||||
// product carrying the chips atom (a chip pack is funded, never bought with chips — ErrNotAValue).
|
||||
func (s *Store) loadProduct(ctx context.Context, productID uuid.UUID) (catalogProduct, error) {
|
||||
var p model.Product
|
||||
err := postgres.SELECT(table.Product.AllColumns).
|
||||
FROM(table.Product).
|
||||
WHERE(table.Product.ProductID.EQ(postgres.UUID(productID))).
|
||||
LIMIT(1).
|
||||
QueryContext(ctx, s.db, &p)
|
||||
if errors.Is(err, qrm.ErrNoRows) || (err == nil && !p.Active) {
|
||||
return catalogProduct{}, ErrProductNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return catalogProduct{}, fmt.Errorf("payments: load product %s: %w", productID, err)
|
||||
}
|
||||
|
||||
var price model.ProductPrice
|
||||
err = postgres.SELECT(table.ProductPrice.AllColumns).
|
||||
FROM(table.ProductPrice).
|
||||
WHERE(table.ProductPrice.ProductID.EQ(postgres.UUID(productID)).
|
||||
AND(table.ProductPrice.Method.IS_NULL()).
|
||||
AND(table.ProductPrice.Currency.EQ(postgres.String(string(CurrencyChip))))).
|
||||
LIMIT(1).
|
||||
QueryContext(ctx, s.db, &price)
|
||||
if errors.Is(err, qrm.ErrNoRows) {
|
||||
return catalogProduct{}, ErrNotAValue
|
||||
}
|
||||
if err != nil {
|
||||
return catalogProduct{}, fmt.Errorf("payments: load price %s: %w", productID, err)
|
||||
}
|
||||
|
||||
var items []model.ProductItem
|
||||
if err := postgres.SELECT(table.ProductItem.AllColumns).
|
||||
FROM(table.ProductItem).
|
||||
WHERE(table.ProductItem.ProductID.EQ(postgres.UUID(productID))).
|
||||
QueryContext(ctx, s.db, &items); err != nil {
|
||||
return catalogProduct{}, fmt.Errorf("payments: load items %s: %w", productID, err)
|
||||
}
|
||||
|
||||
cp := catalogProduct{id: productID, title: p.Title, priceChips: int(price.Amount), atoms: map[string]int{}}
|
||||
for _, it := range items {
|
||||
cp.atoms[it.AtomType] = int(it.Quantity)
|
||||
switch it.AtomType {
|
||||
case "hints":
|
||||
cp.delta.hintsAdd += int(it.Quantity)
|
||||
case "noads_days":
|
||||
cp.delta.noAdsDays += int(it.Quantity)
|
||||
case "chips":
|
||||
return catalogProduct{}, ErrNotAValue // a value never grants chips
|
||||
}
|
||||
}
|
||||
return cp, nil
|
||||
}
|
||||
|
||||
// stackNoAds returns the new no-ads term end after adding addDays whole days from
|
||||
// max(now, current end) — terms add up, the remainder is never lost (§5/D33). A non-positive
|
||||
// addDays leaves the term unchanged; a nil current means no term yet.
|
||||
func stackNoAds(current *time.Time, addDays int, now time.Time) *time.Time {
|
||||
if addDays <= 0 {
|
||||
return current
|
||||
}
|
||||
base := now
|
||||
if current != nil && current.After(now) {
|
||||
base = *current
|
||||
}
|
||||
end := base.Add(time.Duration(addDays) * 24 * time.Hour)
|
||||
return &end
|
||||
}
|
||||
|
||||
// combineNoAds folds secondary's remaining no-ads term onto primary's during a merge: the
|
||||
// remaining duration of each is preserved (§6/D15 "terms extend per origin").
|
||||
func combineNoAds(primary, secondary *time.Time, now time.Time) *time.Time {
|
||||
if secondary == nil || !secondary.After(now) {
|
||||
return primary
|
||||
}
|
||||
base := now
|
||||
if primary != nil && primary.After(now) {
|
||||
base = *primary
|
||||
}
|
||||
end := base.Add(secondary.Sub(now))
|
||||
return &end
|
||||
}
|
||||
|
||||
// applyBenefitTx applies a benefit delta to one origin inside tx, stacking the no-ads term,
|
||||
// OR-ing the forever flag and adding hints. It ensures the (account, origin) row exists, locks
|
||||
// it, then writes the recomputed values — so concurrent applies serialise on the row lock.
|
||||
func applyBenefitTx(ctx context.Context, tx *sql.Tx, accountID uuid.UUID, origin Source, d benefitDelta, now time.Time) error {
|
||||
if d.zero() {
|
||||
return nil
|
||||
}
|
||||
if _, err := tx.ExecContext(ctx,
|
||||
`INSERT INTO payments.benefits (account_id, origin) VALUES ($1, $2) ON CONFLICT DO NOTHING`,
|
||||
accountID, string(origin)); err != nil {
|
||||
return fmt.Errorf("payments: ensure benefit row %s: %w", origin, err)
|
||||
}
|
||||
var untilCur *time.Time
|
||||
var foreverCur bool
|
||||
var hintsCur int32
|
||||
if err := tx.QueryRowContext(ctx,
|
||||
`SELECT ads_paid_until, ads_forever, hints FROM payments.benefits
|
||||
WHERE account_id = $1 AND origin = $2 FOR UPDATE`, accountID, string(origin)).
|
||||
Scan(&untilCur, &foreverCur, &hintsCur); err != nil {
|
||||
return fmt.Errorf("payments: lock benefit %s: %w", origin, err)
|
||||
}
|
||||
if _, err := tx.ExecContext(ctx,
|
||||
`UPDATE payments.benefits SET ads_paid_until = $3, ads_forever = $4, hints = $5, updated_at = now()
|
||||
WHERE account_id = $1 AND origin = $2`,
|
||||
accountID, string(origin), stackNoAds(untilCur, d.noAdsDays, now), foreverCur || d.forever, int(hintsCur)+d.hintsAdd); err != nil {
|
||||
return fmt.Errorf("payments: apply benefit %s: %w", origin, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// insertLedgerTx appends one append-only ledger row inside tx.
|
||||
func insertLedgerTx(ctx context.Context, tx *sql.Tx, accountID uuid.UUID, kind string, source, origin *Source, chipsDelta int, productID *uuid.UUID, snapshot []byte, now time.Time) error {
|
||||
id, err := uuid.NewV7()
|
||||
if err != nil {
|
||||
return fmt.Errorf("payments: ledger id: %w", err)
|
||||
}
|
||||
// The snapshot is a bare value, not a postgres.String literal: a jsonb column infers its
|
||||
// type from an untyped parameter (the game-moves payload idiom), whereas a text-typed
|
||||
// literal is rejected against jsonb.
|
||||
var snap any = postgres.NULL
|
||||
if snapshot != nil {
|
||||
snap = string(snapshot)
|
||||
}
|
||||
stmt := table.Ledger.INSERT(
|
||||
table.Ledger.LedgerID, table.Ledger.AccountID, table.Ledger.Kind,
|
||||
table.Ledger.Source, table.Ledger.Origin, table.Ledger.ChipsDelta,
|
||||
table.Ledger.ProductID, table.Ledger.Snapshot, table.Ledger.CreatedAt,
|
||||
).VALUES(
|
||||
id, accountID, kind,
|
||||
sourceOrNull(source), sourceOrNull(origin), int32(chipsDelta),
|
||||
uuidOrNull(productID), snap, now,
|
||||
)
|
||||
if _, err := stmt.ExecContext(ctx, tx); err != nil {
|
||||
return fmt.Errorf("payments: insert %s ledger: %w", kind, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// spend draws the chips across the given segments, appends a spend ledger row per draw (carrying
|
||||
// the purchase snapshot), and applies the benefit — all in one transaction. It fails closed on
|
||||
// an insufficient balance (a guarded decrement), rolling everything back.
|
||||
func (s *Store) spend(ctx context.Context, accountID uuid.UUID, draws []sourceAmount, origin Source, productID uuid.UUID, d benefitDelta, snapshot []byte, now time.Time) error {
|
||||
err := withTx(ctx, s.db, func(tx *sql.Tx) error {
|
||||
for _, dr := range draws {
|
||||
res, err := table.Balances.
|
||||
UPDATE(table.Balances.Chips, table.Balances.UpdatedAt).
|
||||
SET(table.Balances.Chips.SUB(postgres.Int(int64(dr.amount))), postgres.TimestampzT(now)).
|
||||
WHERE(table.Balances.AccountID.EQ(postgres.UUID(accountID)).
|
||||
AND(table.Balances.Source.EQ(postgres.String(string(dr.source)))).
|
||||
AND(table.Balances.Chips.GT_EQ(postgres.Int(int64(dr.amount))))).
|
||||
ExecContext(ctx, tx)
|
||||
if err != nil {
|
||||
return fmt.Errorf("payments: decrement %s: %w", dr.source, err)
|
||||
}
|
||||
if n, _ := res.RowsAffected(); n == 0 {
|
||||
return ErrInsufficientChips
|
||||
}
|
||||
src := dr.source
|
||||
if err := insertLedgerTx(ctx, tx, accountID, "spend", &src, &origin, -dr.amount, &productID, snapshot, now); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return applyBenefitTx(ctx, tx, accountID, origin, d, now)
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
s.cache.invalidate(accountID)
|
||||
return nil
|
||||
}
|
||||
|
||||
// grant records an admin_grant ledger row (price 0, no chips) and applies the granted benefit to
|
||||
// the chosen origin, in one transaction — a zero-price sale of a value.
|
||||
func (s *Store) grant(ctx context.Context, accountID uuid.UUID, origin Source, d benefitDelta, snapshot []byte, now time.Time) error {
|
||||
err := withTx(ctx, s.db, func(tx *sql.Tx) error {
|
||||
if err := insertLedgerTx(ctx, tx, accountID, "admin_grant", nil, &origin, 0, nil, snapshot, now); err != nil {
|
||||
return err
|
||||
}
|
||||
return applyBenefitTx(ctx, tx, accountID, origin, d, now)
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
s.cache.invalidate(accountID)
|
||||
return nil
|
||||
}
|
||||
|
||||
// consumeHint decrements one hint from the first applicable origin (in the given priority order)
|
||||
// that has one, with a guarded update. It returns whether a hint was spent.
|
||||
func (s *Store) consumeHint(ctx context.Context, accountID uuid.UUID, origins []Source, now time.Time) (bool, error) {
|
||||
for _, o := range origins {
|
||||
res, err := table.Benefits.
|
||||
UPDATE(table.Benefits.Hints, table.Benefits.UpdatedAt).
|
||||
SET(table.Benefits.Hints.SUB(postgres.Int(1)), postgres.TimestampzT(now)).
|
||||
WHERE(table.Benefits.AccountID.EQ(postgres.UUID(accountID)).
|
||||
AND(table.Benefits.Origin.EQ(postgres.String(string(o)))).
|
||||
AND(table.Benefits.Hints.GT(postgres.Int(0)))).
|
||||
ExecContext(ctx, s.db)
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("payments: consume hint %s: %w", o, err)
|
||||
}
|
||||
if n, _ := res.RowsAffected(); n > 0 {
|
||||
s.cache.invalidate(accountID)
|
||||
return true, nil
|
||||
}
|
||||
}
|
||||
return false, nil
|
||||
}
|
||||
|
||||
// MergeTx folds the secondary account's segments and benefits into the primary, by source and by
|
||||
// origin, inside the caller's transaction (the account-merge flow): chips sum, no-ads terms
|
||||
// extend per origin, forever OR-s, hints add. The secondary's payments rows are removed. The
|
||||
// caller invalidates the primary's cache after its own commit (Invalidate). It does not touch
|
||||
// the account schema — the JET import boundary stays intact, only the shared connection is used.
|
||||
func (s *Store) MergeTx(ctx context.Context, tx *sql.Tx, primary, secondary uuid.UUID, now time.Time) error {
|
||||
if _, err := tx.ExecContext(ctx,
|
||||
`INSERT INTO payments.balances (account_id, source, chips, updated_at)
|
||||
SELECT $1, source, chips, now() FROM payments.balances WHERE account_id = $2
|
||||
ON CONFLICT (account_id, source) DO UPDATE
|
||||
SET chips = payments.balances.chips + EXCLUDED.chips, updated_at = now()`,
|
||||
primary, secondary); err != nil {
|
||||
return fmt.Errorf("payments: merge balances: %w", err)
|
||||
}
|
||||
if _, err := tx.ExecContext(ctx, `DELETE FROM payments.balances WHERE account_id = $1`, secondary); err != nil {
|
||||
return fmt.Errorf("payments: clear secondary balances: %w", err)
|
||||
}
|
||||
|
||||
rows, err := tx.QueryContext(ctx,
|
||||
`SELECT origin, ads_paid_until, ads_forever, hints FROM payments.benefits WHERE account_id = $1`, secondary)
|
||||
if err != nil {
|
||||
return fmt.Errorf("payments: read secondary benefits: %w", err)
|
||||
}
|
||||
type secBenefit struct {
|
||||
origin Source
|
||||
until *time.Time
|
||||
forever bool
|
||||
hints int
|
||||
}
|
||||
var secs []secBenefit
|
||||
for rows.Next() {
|
||||
var b secBenefit
|
||||
var o string
|
||||
var h int32
|
||||
if err := rows.Scan(&o, &b.until, &b.forever, &h); err != nil {
|
||||
rows.Close()
|
||||
return fmt.Errorf("payments: scan secondary benefit: %w", err)
|
||||
}
|
||||
b.origin, b.hints = Source(o), int(h)
|
||||
secs = append(secs, b)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
rows.Close()
|
||||
return fmt.Errorf("payments: iterate secondary benefits: %w", err)
|
||||
}
|
||||
rows.Close()
|
||||
|
||||
for _, b := range secs {
|
||||
if _, err := tx.ExecContext(ctx,
|
||||
`INSERT INTO payments.benefits (account_id, origin) VALUES ($1, $2) ON CONFLICT DO NOTHING`,
|
||||
primary, string(b.origin)); err != nil {
|
||||
return fmt.Errorf("payments: ensure primary benefit %s: %w", b.origin, err)
|
||||
}
|
||||
var untilCur *time.Time
|
||||
var foreverCur bool
|
||||
var hintsCur int32
|
||||
if err := tx.QueryRowContext(ctx,
|
||||
`SELECT ads_paid_until, ads_forever, hints FROM payments.benefits
|
||||
WHERE account_id = $1 AND origin = $2 FOR UPDATE`, primary, string(b.origin)).
|
||||
Scan(&untilCur, &foreverCur, &hintsCur); err != nil {
|
||||
return fmt.Errorf("payments: lock primary benefit %s: %w", b.origin, err)
|
||||
}
|
||||
if _, err := tx.ExecContext(ctx,
|
||||
`UPDATE payments.benefits SET ads_paid_until = $3, ads_forever = $4, hints = $5, updated_at = now()
|
||||
WHERE account_id = $1 AND origin = $2`,
|
||||
primary, string(b.origin), combineNoAds(untilCur, b.until, now), foreverCur || b.forever, int(hintsCur)+b.hints); err != nil {
|
||||
return fmt.Errorf("payments: merge benefit %s: %w", b.origin, err)
|
||||
}
|
||||
}
|
||||
if _, err := tx.ExecContext(ctx, `DELETE FROM payments.benefits WHERE account_id = $1`, secondary); err != nil {
|
||||
return fmt.Errorf("payments: clear secondary benefits: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// sourceOrNull renders an optional source as a SQL string or NULL.
|
||||
func sourceOrNull(s *Source) postgres.Expression {
|
||||
if s == nil {
|
||||
return postgres.NULL
|
||||
}
|
||||
return postgres.String(string(*s))
|
||||
}
|
||||
|
||||
// uuidOrNull renders an optional id as a SQL uuid or NULL.
|
||||
func uuidOrNull(id *uuid.UUID) postgres.Expression {
|
||||
if id == nil {
|
||||
return postgres.NULL
|
||||
}
|
||||
return postgres.UUID(*id)
|
||||
}
|
||||
@@ -0,0 +1,182 @@
|
||||
package payments
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// base is a fixed clock instant for the deterministic tests.
|
||||
var base = time.Date(2026, 7, 8, 12, 0, 0, 0, time.UTC)
|
||||
|
||||
// seededService builds a Service whose read cache already holds st for id, so the read methods
|
||||
// resolve without a database (the store's db is nil). The clock is pinned to base.
|
||||
func seededService(id uuid.UUID, st walletState) *Service {
|
||||
store := NewStore(nil)
|
||||
store.cache.put(id, st)
|
||||
return &Service{store: store, clock: func() time.Time { return base }}
|
||||
}
|
||||
|
||||
func TestStackNoAds(t *testing.T) {
|
||||
future := base.Add(48 * time.Hour)
|
||||
past := base.Add(-time.Hour)
|
||||
tests := []struct {
|
||||
name string
|
||||
current *time.Time
|
||||
addDays int
|
||||
want *time.Time
|
||||
}{
|
||||
{"fresh term", nil, 3, new(base.Add(72 * time.Hour))},
|
||||
{"stack onto future", new(future), 2, new(future.Add(48 * time.Hour))},
|
||||
{"lapsed term restarts from now", new(past), 1, new(base.Add(24 * time.Hour))},
|
||||
{"zero days unchanged", new(future), 0, new(future)},
|
||||
{"zero days, nil stays nil", nil, 0, nil},
|
||||
}
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
got := stackNoAds(tc.current, tc.addDays, base)
|
||||
if (got == nil) != (tc.want == nil) || (got != nil && !got.Equal(*tc.want)) {
|
||||
t.Errorf("stackNoAds = %v, want %v", got, tc.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestCombineNoAds(t *testing.T) {
|
||||
pFuture := base.Add(24 * time.Hour)
|
||||
sFuture := base.Add(72 * time.Hour) // 3 days remaining
|
||||
// primary future + secondary future: primary end + secondary's remaining (72h).
|
||||
if got := combineNoAds(new(pFuture), new(sFuture), base); !got.Equal(pFuture.Add(72 * time.Hour)) {
|
||||
t.Errorf("combine both future = %v, want %v", got, pFuture.Add(72*time.Hour))
|
||||
}
|
||||
// primary nil + secondary future: now + secondary's remaining.
|
||||
if got := combineNoAds(nil, new(sFuture), base); !got.Equal(base.Add(72 * time.Hour)) {
|
||||
t.Errorf("combine nil primary = %v, want %v", got, base.Add(72*time.Hour))
|
||||
}
|
||||
// secondary lapsed: primary unchanged.
|
||||
if got := combineNoAds(new(pFuture), new(base.Add(-time.Hour)), base); !got.Equal(pFuture) {
|
||||
t.Errorf("combine lapsed secondary = %v, want %v", got, pFuture)
|
||||
}
|
||||
// secondary nil: primary unchanged.
|
||||
if got := combineNoAds(new(pFuture), nil, base); !got.Equal(pFuture) {
|
||||
t.Errorf("combine nil secondary = %v, want %v", got, pFuture)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPlanDraws(t *testing.T) {
|
||||
st := walletState{chips: map[Source]int{SourceDirect: 30, SourceVK: 50, SourceTelegram: 5}}
|
||||
// price met entirely by the first (direct) segment.
|
||||
if draws, ok := planDraws(st, []Source{SourceDirect, SourceVK}, 20); !ok || len(draws) != 1 || draws[0] != (sourceAmount{SourceDirect, 20}) {
|
||||
t.Errorf("single-segment draw = %v ok=%v", draws, ok)
|
||||
}
|
||||
// price spills from direct into vk by priority.
|
||||
draws, ok := planDraws(st, []Source{SourceDirect, SourceVK, SourceTelegram}, 60)
|
||||
want := []sourceAmount{{SourceDirect, 30}, {SourceVK, 30}}
|
||||
if !ok || len(draws) != 2 || draws[0] != want[0] || draws[1] != want[1] {
|
||||
t.Errorf("priority spill draw = %v ok=%v, want %v", draws, ok, want)
|
||||
}
|
||||
// insufficient total.
|
||||
if _, ok := planDraws(st, []Source{SourceDirect, SourceVK, SourceTelegram}, 200); ok {
|
||||
t.Error("expected insufficient")
|
||||
}
|
||||
}
|
||||
|
||||
func TestWalletSegments(t *testing.T) {
|
||||
id := uuid.New()
|
||||
st := walletState{chips: map[Source]int{SourceDirect: 100, SourceVK: 50}}
|
||||
svc := seededService(id, st)
|
||||
present := []Source{SourceDirect, SourceVK}
|
||||
|
||||
// Web/native: both attached segments shown, both spendable.
|
||||
got, err := svc.Wallet(context.Background(), id, NewContext("direct", "web"), present)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(got.Segments) != 2 || !got.Segments[0].Spendable || got.Segments[0].Source != SourceDirect {
|
||||
t.Errorf("direct wallet segments = %+v", got.Segments)
|
||||
}
|
||||
// VK Android: only vk shown, spendable.
|
||||
got, _ = svc.Wallet(context.Background(), id, NewContext("vk", "android"), present)
|
||||
if len(got.Segments) != 1 || got.Segments[0].Source != SourceVK || !got.Segments[0].Spendable {
|
||||
t.Errorf("vk-android wallet = %+v", got.Segments)
|
||||
}
|
||||
// VK iOS: only vk shown, frozen (not spendable) but the balance is visible.
|
||||
got, _ = svc.Wallet(context.Background(), id, NewContext("vk", "ios"), present)
|
||||
if len(got.Segments) != 1 || got.Segments[0].Chips != 50 || got.Segments[0].Spendable {
|
||||
t.Errorf("vk-ios wallet = %+v (want vk 50 frozen)", got.Segments)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAdFreeByContext(t *testing.T) {
|
||||
id := uuid.New()
|
||||
future := base.Add(48 * time.Hour)
|
||||
ctx := context.Background()
|
||||
|
||||
// A vk-origin no-ads term applies inside VK and out on web, but a direct-origin term never
|
||||
// applies inside VK (the compliance wall).
|
||||
svc := seededService(id, walletState{benefits: map[Source]benefitState{
|
||||
SourceVK: {adsPaidUntil: new(future)},
|
||||
SourceDirect: {adsPaidUntil: new(future)},
|
||||
}})
|
||||
present := []Source{SourceDirect, SourceVK}
|
||||
|
||||
cases := []struct {
|
||||
name string
|
||||
cxt Context
|
||||
want bool
|
||||
}{
|
||||
{"vk term inside vk", NewContext("vk", "android"), true},
|
||||
{"vk term inside vk-ios (applies while frozen)", NewContext("vk", "ios"), true},
|
||||
{"terms on web", NewContext("direct", "web"), true},
|
||||
{"untrusted fail-closed", NewContext("", ""), false},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
got, err := svc.AdFree(ctx, id, tc.cxt, present)
|
||||
if err != nil || got != tc.want {
|
||||
t.Errorf("AdFree = %v (err %v), want %v", got, err, tc.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// Compliance: ONLY a direct-origin term, checked inside VK, must not suppress ads.
|
||||
svc2 := seededService(id, walletState{benefits: map[Source]benefitState{SourceDirect: {adsPaidUntil: new(future)}}})
|
||||
if got, _ := svc2.AdFree(ctx, id, NewContext("vk", "android"), present); got {
|
||||
t.Error("direct-origin no-ads must NOT apply inside VK (compliance wall)")
|
||||
}
|
||||
}
|
||||
|
||||
func TestHintsAvailableByContext(t *testing.T) {
|
||||
id := uuid.New()
|
||||
svc := seededService(id, walletState{benefits: map[Source]benefitState{
|
||||
SourceDirect: {hints: 3},
|
||||
SourceVK: {hints: 2},
|
||||
}})
|
||||
present := []Source{SourceDirect, SourceVK}
|
||||
ctx := context.Background()
|
||||
|
||||
// Web: both applicable origins summed.
|
||||
if n, _ := svc.HintsAvailable(ctx, id, NewContext("direct", "web"), present); n != 5 {
|
||||
t.Errorf("web hints = %d, want 5", n)
|
||||
}
|
||||
// VK: only vk-origin hints.
|
||||
if n, _ := svc.HintsAvailable(ctx, id, NewContext("vk", "android"), present); n != 2 {
|
||||
t.Errorf("vk hints = %d, want 2", n)
|
||||
}
|
||||
// Untrusted: none.
|
||||
if n, _ := svc.HintsAvailable(ctx, id, NewContext("", ""), present); n != 0 {
|
||||
t.Errorf("untrusted hints = %d, want 0", n)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSpendHintUntrustedNoOp(t *testing.T) {
|
||||
id := uuid.New()
|
||||
svc := seededService(id, walletState{benefits: map[Source]benefitState{SourceDirect: {hints: 3}}})
|
||||
// Untrusted context: no applicable origin, so nothing is spent and the DB (nil) is never hit.
|
||||
spent, err := svc.SpendHint(context.Background(), id, NewContext("", ""), []Source{SourceDirect})
|
||||
if err != nil || spent {
|
||||
t.Errorf("untrusted SpendHint = %v (err %v), want false", spent, err)
|
||||
}
|
||||
}
|
||||
@@ -10,6 +10,7 @@ import (
|
||||
"scrabble/backend/internal/ads"
|
||||
"scrabble/backend/internal/engine"
|
||||
"scrabble/backend/internal/notify"
|
||||
"scrabble/backend/internal/payments"
|
||||
)
|
||||
|
||||
// bannerDTO is the advertising-banner block attached to an eligible viewer's
|
||||
@@ -55,7 +56,21 @@ type bannerTimingsDTO struct {
|
||||
// a language switch).
|
||||
func (s *Server) profileResponse(ctx context.Context, acc account.Account) profileResponse {
|
||||
r := profileResponseFor(acc)
|
||||
r.Banner = s.bannerFor(ctx, acc)
|
||||
// Resolve the payments gate once (execution context + present sources) and feed it to both
|
||||
// the hint count and the banner. The profile hint balance now comes from the payments benefit
|
||||
// (context-aware), not the deprecated accounts.hint_balance column; on any failure the legacy
|
||||
// value from profileResponseFor (zeroed in production) stands.
|
||||
cxt, present, err := s.walletGate(ctx, acc.ID)
|
||||
if err != nil {
|
||||
s.log.Warn("profile: wallet gate failed", zap.String("account", acc.ID.String()), zap.Error(err))
|
||||
} else if s.payments != nil {
|
||||
if hints, herr := s.payments.HintsAvailable(ctx, acc.ID, cxt, present); herr == nil {
|
||||
r.HintBalance = hints
|
||||
} else {
|
||||
s.log.Warn("profile: hint balance read failed", zap.String("account", acc.ID.String()), zap.Error(herr))
|
||||
}
|
||||
}
|
||||
r.Banner = s.bannerFor(ctx, acc, cxt, present)
|
||||
s.fillLinkedIdentities(ctx, &r, acc.ID)
|
||||
r.DictVersions = s.currentDictVersions()
|
||||
return r
|
||||
@@ -115,7 +130,7 @@ func (s *Server) fillLinkedIdentities(ctx context.Context, r *profileResponse, a
|
||||
// language, falling back to its interface language and then English. A failure
|
||||
// reading roles or campaigns is logged and treated as "no banner" so the profile
|
||||
// response still succeeds.
|
||||
func (s *Server) bannerFor(ctx context.Context, acc account.Account) *bannerDTO {
|
||||
func (s *Server) bannerFor(ctx context.Context, acc account.Account, cxt payments.Context, present []payments.Source) *bannerDTO {
|
||||
if s.ads == nil {
|
||||
return nil
|
||||
}
|
||||
@@ -124,16 +139,24 @@ func (s *Server) bannerFor(ctx context.Context, acc account.Account) *bannerDTO
|
||||
s.log.Warn("banner: active set failed", zap.String("account", acc.ID.String()), zap.Error(err))
|
||||
return nil
|
||||
}
|
||||
// An urgent campaign is shown to every viewer; otherwise the normal eligibility
|
||||
// gate applies (a paid account, a non-empty hint wallet or the no_banner role
|
||||
// hides the banner).
|
||||
// An urgent campaign is shown to every viewer; otherwise the banner is suppressed by the
|
||||
// no_banner role or by an active no-ads benefit applicable in the viewer's context (the
|
||||
// payments gate — a hint balance no longer suppresses the banner). An untrusted platform is
|
||||
// fail-closed by the gate, so it does not suppress the banner.
|
||||
if !urgent {
|
||||
hasNoBanner, err := s.accounts.HasRole(ctx, acc.ID, account.RoleNoBanner)
|
||||
if err != nil {
|
||||
s.log.Warn("banner: role check failed", zap.String("account", acc.ID.String()), zap.Error(err))
|
||||
return nil
|
||||
}
|
||||
if !ads.Eligible(acc.PaidAccount, acc.HintBalance, hasNoBanner) {
|
||||
adFree := false
|
||||
if s.payments != nil {
|
||||
if adFree, err = s.payments.AdFree(ctx, acc.ID, cxt, present); err != nil {
|
||||
s.log.Warn("banner: ad-free check failed", zap.String("account", acc.ID.String()), zap.Error(err))
|
||||
return nil
|
||||
}
|
||||
}
|
||||
if hasNoBanner || adFree {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,6 +15,7 @@ import (
|
||||
"scrabble/backend/internal/feedback"
|
||||
"scrabble/backend/internal/game"
|
||||
"scrabble/backend/internal/lobby"
|
||||
"scrabble/backend/internal/payments"
|
||||
"scrabble/backend/internal/session"
|
||||
"scrabble/backend/internal/social"
|
||||
)
|
||||
@@ -65,6 +66,11 @@ func (s *Server) registerRoutes() {
|
||||
// client may still reach, to fetch the block's expiry and reason for the blocked screen.
|
||||
u.GET("/block-status", s.handleBlockStatus)
|
||||
}
|
||||
if s.payments != nil {
|
||||
// The wallet: the context-visible chip segments + benefits, and a chip spend on a value.
|
||||
u.GET("/wallet", s.handleWallet)
|
||||
u.POST("/wallet/buy", s.handleWalletBuy)
|
||||
}
|
||||
if s.links != nil {
|
||||
// Account linking & merge. The request step always mails a code;
|
||||
// a required merge is revealed only after the code is verified, and the
|
||||
@@ -250,6 +256,14 @@ func statusForError(err error) (int, string) {
|
||||
return http.StatusConflict, "last_identity"
|
||||
case errors.Is(err, accountmerge.ErrActiveGameConflict):
|
||||
return http.StatusConflict, "merge_active_game_conflict"
|
||||
case errors.Is(err, payments.ErrUntrusted):
|
||||
return http.StatusForbidden, "payments_untrusted"
|
||||
case errors.Is(err, payments.ErrInsufficientChips):
|
||||
return http.StatusConflict, "insufficient_chips"
|
||||
case errors.Is(err, payments.ErrProductNotFound):
|
||||
return http.StatusNotFound, "product_not_found"
|
||||
case errors.Is(err, payments.ErrNotAValue):
|
||||
return http.StatusBadRequest, "not_a_value"
|
||||
case errors.Is(err, account.ErrInvalidEmail):
|
||||
return http.StatusBadRequest, "invalid_email"
|
||||
case errors.Is(err, account.ErrCodeMismatch), errors.Is(err, account.ErrCodeExpired),
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/google/uuid"
|
||||
|
||||
"scrabble/backend/internal/payments"
|
||||
)
|
||||
|
||||
// walletSegmentDTO is one chip balance in the wallet view: the funding source, the chip count,
|
||||
// and whether it can be spent in the current execution context (false for a frozen VK-iOS
|
||||
// balance or an untrusted platform).
|
||||
type walletSegmentDTO struct {
|
||||
Source string `json:"source"`
|
||||
Chips int `json:"chips"`
|
||||
Spendable bool `json:"spendable"`
|
||||
}
|
||||
|
||||
// walletDTO is the user-facing wallet: the context-visible chip segments and the
|
||||
// context-applicable benefits (the no-ads term or forever flag, and the available hints).
|
||||
type walletDTO struct {
|
||||
Segments []walletSegmentDTO `json:"segments"`
|
||||
AdsForever bool `json:"ads_forever"`
|
||||
AdsPaidUntil int64 `json:"ads_paid_until_ms"` // unix millis; 0 = no active term
|
||||
Hints int `json:"hints"`
|
||||
}
|
||||
|
||||
// walletBuyRequest is the POST body of a chip spend: the product to buy with chips.
|
||||
type walletBuyRequest struct {
|
||||
ProductID string `json:"product_id"`
|
||||
}
|
||||
|
||||
// walletDTOFrom projects a payments wallet view into the wire DTO.
|
||||
func walletDTOFrom(v payments.WalletView) walletDTO {
|
||||
out := walletDTO{AdsForever: v.Benefits.AdsForever, Hints: v.Benefits.Hints}
|
||||
if v.Benefits.AdsPaidUntil != nil {
|
||||
out.AdsPaidUntil = v.Benefits.AdsPaidUntil.UnixMilli()
|
||||
}
|
||||
out.Segments = make([]walletSegmentDTO, 0, len(v.Segments))
|
||||
for _, seg := range v.Segments {
|
||||
out.Segments = append(out.Segments, walletSegmentDTO{Source: string(seg.Source), Chips: seg.Chips, Spendable: seg.Spendable})
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// handleWallet returns the caller's wallet — the segments and benefits visible in the current
|
||||
// trusted execution context.
|
||||
func (s *Server) handleWallet(c *gin.Context) {
|
||||
uid, ok := userID(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
ctx := c.Request.Context()
|
||||
cxt, present, err := s.walletGate(ctx, uid)
|
||||
if err != nil {
|
||||
s.abortErr(c, err)
|
||||
return
|
||||
}
|
||||
view, err := s.payments.Wallet(ctx, uid, cxt, present)
|
||||
if err != nil {
|
||||
s.abortErr(c, err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, walletDTOFrom(view))
|
||||
}
|
||||
|
||||
// handleWalletBuy spends chips on a chip-priced value and returns the updated wallet. It is
|
||||
// fail-closed: an untrusted or frozen context, or an insufficient balance, is refused.
|
||||
func (s *Server) handleWalletBuy(c *gin.Context) {
|
||||
uid, ok := userID(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
var req walletBuyRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.AbortWithStatusJSON(http.StatusBadRequest, errorResponse{Error: errorBody{Code: "invalid_request", Message: "invalid request body"}})
|
||||
return
|
||||
}
|
||||
productID, err := uuid.Parse(req.ProductID)
|
||||
if err != nil {
|
||||
c.AbortWithStatusJSON(http.StatusBadRequest, errorResponse{Error: errorBody{Code: "invalid_request", Message: "invalid product id"}})
|
||||
return
|
||||
}
|
||||
ctx := c.Request.Context()
|
||||
cxt, present, err := s.walletGate(ctx, uid)
|
||||
if err != nil {
|
||||
s.abortErr(c, err)
|
||||
return
|
||||
}
|
||||
if err := s.payments.Spend(ctx, uid, cxt, present, productID); err != nil {
|
||||
s.abortErr(c, err)
|
||||
return
|
||||
}
|
||||
view, err := s.payments.Wallet(ctx, uid, cxt, present)
|
||||
if err != nil {
|
||||
s.abortErr(c, err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, walletDTOFrom(view))
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"scrabble/backend/internal/payments"
|
||||
"scrabble/backend/internal/session"
|
||||
)
|
||||
|
||||
// walletGate resolves the payments gate inputs for an account on the current request: the
|
||||
// trusted execution context (the session platform carried on ctx by the platformContext
|
||||
// middleware; absent ⇒ untrusted, fail-closed) and the account's present identity sources
|
||||
// (which chip/benefit segments are awake, §6). The payments domain holds no cross-schema
|
||||
// identity knowledge, so the server supplies present from account.Identities.
|
||||
func (s *Server) walletGate(ctx context.Context, accountID uuid.UUID) (payments.Context, []payments.Source, error) {
|
||||
var cxt payments.Context
|
||||
if p, ok := session.PlatformFromContext(ctx); ok {
|
||||
cxt = payments.NewContext(p.Kind, p.Subtype)
|
||||
}
|
||||
ids, err := s.accounts.Identities(ctx, accountID)
|
||||
if err != nil {
|
||||
return payments.Context{}, nil, err
|
||||
}
|
||||
kinds := make([]string, len(ids))
|
||||
for i, id := range ids {
|
||||
kinds[i] = id.Kind
|
||||
}
|
||||
return cxt, payments.PresentSources(kinds), nil
|
||||
}
|
||||
Reference in New Issue
Block a user