feat(enakgame): game sessions, rewards, vouchers, budgets and events

EnakGame phases 1-8 of docs/tasks-enakgame.md (EG-101 to EG-803), built on the
existing EnakPoint/EnakCoin wallet (docs/rfc-enakgame.md).

Foundation (phase 1)
- Migrations 000103-000106: games extended with organization, slug, status,
  entry cost and result rules, old games archived (not deleted); budgets,
  versioned reward configs, sessions and session rewards; the ledger types
  GAME_SPEND_REFUND, GAME_REWARD and REWARD_REDEEM_REFUND; audit_logs.
- AuditLogger writes in the caller's transaction only.
- enakgame.limit.user_daily and global_daily organization settings.

Games and sessions (phases 2-4)
- Admin /marketing/enakgame: games, reward config versions (immutable but for
  status, one ACTIVE per game), budgets with non-overlapping global periods and
  a daily job opening the next month.
- Customer /customer/enakgame: start (Idempotency-Key, entry cost and config
  frozen on the session), complete (result validation, reward engine, max_reward
  cap, daily limits via game_reward_counters, one GAME_REWARD per budget),
  automatic refunds for system errors and deactivated games, and a session job.
- Reward engine: FIXED, SCORE_BASED, OUTCOME_BASED, PROBABILITY (crypto/rand),
  rounded down.

Vouchers and budgets (phases 5-6)
- Migration 000108 and 000107: vouchers, codes, redemptions, cost attribution;
  Economy Guard counters.
- STATIC and CODE_POOL redemption in one transaction with the REDEEM PIN action;
  realized cost traced through the lots to the budget that paid the reward.
- Budget metrics: realized cost, forecast, exposure and status. Migrations
  000109-000110 add the wallet_lots indexes they need, built CONCURRENTLY.

Events (phase 7)
- Migration 000111: game events, each with its own EVENT budget. Event extras
  stack per PRD §16 defaults, with event and per-customer limits.

External vouchers (phase 8)
- VoucherProvider contract, two-step PENDING redemption and a recovery job,
  tested with a fake provider. No provider adapter is registered yet, so
  EXTERNAL vouchers stay out of the catalog.

Not yet decided before release: reward rounding, event stacking, budget
exhaustion policy and thresholds (RFC §19.2). Migrations 000103-000111 have
not been run on any shared database.

Also fixes a leftover PAYMENT filter in a wallet test and a data race in a
test PIN fake.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
efrilm
2026-10-07 20:53:14 +07:00
co-authored by Claude Opus 5.5
parent 2c9753fae7
commit 798a36bd6c
92 changed files with 12392 additions and 23 deletions
@@ -0,0 +1,148 @@
package handler
import (
"bytes"
"encoding/json"
"strconv"
"github.com/gin-gonic/gin"
"apskel-pos-be/internal/constants"
"apskel-pos-be/internal/contract"
"apskel-pos-be/internal/models"
"apskel-pos-be/internal/service"
"apskel-pos-be/internal/util"
)
// EnakGameCustomerHandler serves /customer/enakgame (docs/rfc-enakgame.md §11).
type EnakGameCustomerHandler struct {
service service.EnakGameCustomerService
}
func NewEnakGameCustomerHandler(s service.EnakGameCustomerService) *EnakGameCustomerHandler {
return &EnakGameCustomerHandler{service: s}
}
// ListGames is GET /customer/enakgame/games.
func (h *EnakGameCustomerHandler) ListGames(c *gin.Context) {
const method = "EnakGameCustomerHandler::ListGames"
customerID, ok := customerIDFromGin(c, method)
if !ok {
return
}
util.HandleResponse(c.Writer, c.Request, h.service.ListGames(c.Request.Context(), customerID), method)
}
// StartSession is POST /customer/enakgame/sessions. It requires Idempotency-Key.
func (h *EnakGameCustomerHandler) StartSession(c *gin.Context) {
const method = "EnakGameCustomerHandler::StartSession"
customerID, ok := customerIDFromGin(c, method)
if !ok {
return
}
var req contract.StartGameSessionRequest
if err := c.ShouldBindJSON(&req); err != nil {
util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{
contract.NewResponseError(constants.MissingFieldErrorCode, constants.RequestEntity, "game_id is required"),
}), method)
return
}
util.HandleResponse(c.Writer, c.Request, h.service.StartSession(c.Request.Context(), customerID, &req, idempotencyKey(c)), method)
}
// ListSessions is GET /customer/enakgame/sessions?page=&limit=.
func (h *EnakGameCustomerHandler) ListSessions(c *gin.Context) {
const method = "EnakGameCustomerHandler::ListSessions"
customerID, ok := customerIDFromGin(c, method)
if !ok {
return
}
page, _ := strconv.Atoi(c.Query("page"))
limit, _ := strconv.Atoi(c.Query("limit"))
util.HandleResponse(c.Writer, c.Request, h.service.ListSessions(c.Request.Context(), customerID, page, limit), method)
}
// GetSession is GET /customer/enakgame/sessions/:id.
func (h *EnakGameCustomerHandler) GetSession(c *gin.Context) {
const method = "EnakGameCustomerHandler::GetSession"
customerID, ok := customerIDFromGin(c, method)
if !ok {
return
}
id, ok := pathID(c, "id", method)
if !ok {
return
}
util.HandleResponse(c.Writer, c.Request, h.service.GetSession(c.Request.Context(), customerID, id), method)
}
// CompleteSession is POST /customer/enakgame/sessions/:id/complete. The body is read
// leniently on purpose: a reward amount, or anything else the backend does not take
// from the client, is ignored rather than refused (P1). An empty body is a result
// with nothing in it.
func (h *EnakGameCustomerHandler) CompleteSession(c *gin.Context) {
const method = "EnakGameCustomerHandler::CompleteSession"
customerID, ok := customerIDFromGin(c, method)
if !ok {
return
}
id, ok := pathID(c, "id", method)
if !ok {
return
}
body, ok := rawBody(c, method)
if !ok {
return
}
var in models.GameSessionCompleteInput
if len(bytes.TrimSpace(body)) > 0 {
if err := json.Unmarshal(body, &in); err != nil {
util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{
contract.NewResponseError(constants.MalformedFieldErrorCode, constants.RequestEntity, "score must be a whole number and outcome a text"),
}), method)
return
}
}
util.HandleResponse(c.Writer, c.Request, h.service.CompleteSession(c.Request.Context(), customerID, id, in), method)
}
// ListVouchers is GET /customer/enakgame/vouchers.
func (h *EnakGameCustomerHandler) ListVouchers(c *gin.Context) {
const method = "EnakGameCustomerHandler::ListVouchers"
customerID, ok := customerIDFromGin(c, method)
if !ok {
return
}
util.HandleResponse(c.Writer, c.Request, h.service.ListVouchers(c.Request.Context(), customerID), method)
}
// RedeemVoucher is POST /customer/enakgame/vouchers/:id/redeem. It requires the PIN
// and Idempotency-Key; the body holds the PIN, so it is never logged.
func (h *EnakGameCustomerHandler) RedeemVoucher(c *gin.Context) {
const method = "EnakGameCustomerHandler::RedeemVoucher"
customerID, ok := customerIDFromGin(c, method)
if !ok {
return
}
id, ok := pathID(c, "id", method)
if !ok {
return
}
var req contract.RedeemVoucherRequest
if !bindPinRequest(c, &req, method) {
return
}
util.HandleResponse(c.Writer, c.Request, h.service.RedeemVoucher(c.Request.Context(), customerID, id, &req, idempotencyKey(c), pinRequestInfo(c)), method)
}
// ListRedemptions is GET /customer/enakgame/redemptions?page=&limit=.
func (h *EnakGameCustomerHandler) ListRedemptions(c *gin.Context) {
const method = "EnakGameCustomerHandler::ListRedemptions"
customerID, ok := customerIDFromGin(c, method)
if !ok {
return
}
page, _ := strconv.Atoi(c.Query("page"))
limit, _ := strconv.Atoi(c.Query("limit"))
util.HandleResponse(c.Writer, c.Request, h.service.ListRedemptions(c.Request.Context(), customerID, page, limit), method)
}