Bỏ qua, tới nội dung chính

Kiến trúc · ADR 0048

Points → AI credits: one transaction under the wallet lock, limits counted there

Trạng thái
superseded by ADR-0057 (AI is paid in points directly; the exchange is retired).
Ngày
2026-11-21
Người quyết định
SmartLearn team (#128)

Context

Students earn points; the AI tutor is limited by a free monthly quota, then by purchased credits in AiCreditBalance (ADR-0044). #128 lets a student turn points into those credits at a rate an admin sets. The M6 schema already had RewardItem (kind AI_CREDITS, payload { "credits": n }, perUserMonthlyLimit) and RewardRedemption linking a PointLedger row and an AiUsageLedger row, but nothing wrote them. The real economy (#123) is not priced yet.

Decision

  • Offers are RewardItem rows of kind AI_CREDITS, managed by ADMIN at /admin/points/rewards (list, create, PATCH; isActive: false switches one off, never delete: redemptions reference it). No seed: an admin creates the first offer; the UI says the rates are placeholders until #123. Audit reward_item.created / reward_item.updated.
  • POST /points/redemptions { rewardItemId, quantity 1–20, clientRequestId } runs in one transaction: lock the points wallet row (SELECT … FOR UPDATE, as PointsService does), look the clientRequestId up under the lock (a hit returns the first exchange, replayed: true), read the offer (missing, off, or a malformed payload → 404 REWARD_NOT_FOUND), check the monthly limit, check the balance, then PointsService.debit (SPEND / REDEMPTION, redeem:<redemptionId>), AiQuotaService.grantCredits (GRANT_REWARD / CREDIT, reward:<redemptionId>) and the RewardRedemption row. The price comes from the offer, never the client.
  • The wallet lock is the one serialisation point. Every exchange of a user queues on it, so the replay check, the limit count and the balance check all see the previous exchange committed. No separate lock on the offer or the redemption table.
  • perUserMonthlyLimit counts units (SUM(quantity)) in the ICT month (periodMonth, the same ictQuotaWindow as the AI quota). Exceeding it → 409 REWARD_MONTHLY_LIMIT_REACHED with limit, used, remaining, resetsAt.
  • Insufficient points → 409 INSUFFICIENT_POINTS, "Không đủ điểm để đổi: cần X điểm, ví của bạn còn Y điểm.", details { balance, required, shortfall }, checked before the debit so the message names the exchange; the debit's own conditional UPDATE still guards.
  • grantCredits is one upsert (INSERT … ON CONFLICT ("userId") DO UPDATE … RETURNING) plus the ledger row, in the caller's transaction. It row-locks the balance, so it serialises with the tutor's conditional spend; the credits are in the bucket the tutor reads after the free quota, so they are usable on commit.
  • Migration 20261121163000_reward_redemption_quantity (additive): quantity and a creditsGranted snapshot on RewardRedemption, and the RewardItem cost/limit and redemption amount CHECKs from constraints.sql.
  • GET /points/rewards answers the active offers with the caller's use this month and the caller's credits (free quota left, purchased credits left, tutor cost) in one read.

Consequences

Proven on real Postgres by apps/api/test/integration/point-redemptions.int-spec.ts: one key fired 10× concurrently exchanges once; 10 keys against points for 3 → exactly 3; a monthly limit of 2 under 10 concurrent exchanges → exactly 2; after the free quota is spent, the tutor answers from the new credits. A rate change applies to the next exchange only; the history keeps the points and credits of each exchange. Points spent on credits are not refunded. Only AI_CREDITS is redeemable; STREAK_FREEZE and BADGE items would need their own grant step.