feat(enakgame): spin as an EnakGame game; remove the old game flow

EnakGame phase 10 of docs/tasks-enakgame.md (EG-1001 to EG-1003).

Spin (EG-1001)
- PROBABILITY entries take an optional label (a wheel segment). The customer game
  list shows a PROBABILITY game's prizes (entry, label, amount, never weights), and
  completing returns the drawn prize, so the client can draw the wheel and stop it
  on the server's draw.
- docs/enakgame-spin.md: the admin steps to set up spin per organization (no
  seeder) and the customer app flow. An HTTP test plays it end to end.

Old game flow removed (EG-1002)
- Routes POST /customer/spin, GET /customer/games, GET /customer/ferris-wheel, and
  admin /marketing/games, /marketing/game-prizes, /marketing/rewards, with their
  handlers, services, processors, repositories, validators, models, contracts,
  mappers and tests (GamePlayProcessor, SpinGameService, rewards, ...). This also
  closes RFC §15 findings 1 and 2 (double charge, spinning another org's game).
- Tables games, game_prizes, game_plays and rewards stay for ledger history.
  entities.StringSlice moves to its own file; the omset tracker (unrouted) keeps
  game_id but no longer embeds the old game response.

games.is_active dropped (EG-1003)
- Migration 000115; nothing reads metadata.coin_cost any more.

The EnakPoint integration docs now point at /customer/enakgame. The Postgres tests
were not run: no test database here. Migration 000115 has not been run anywhere.
The customer app must stop calling the removed endpoints before this is deployed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
efrilm
2026-10-07 21:31:56 +07:00
co-authored by Claude Opus 5.5
parent 296708244e
commit 18e87398bb
68 changed files with 467 additions and 5064 deletions
+131
View File
@@ -476,3 +476,134 @@ func TestEnakGameEventEndpoints_AgainstPostgres(t *testing.T) {
assert.EqualValues(t, 5, events[0].(map[string]any)["bonus"])
assert.NotContains(t, events[0], "budget_id", "the budget stays internal")
}
// EG-1001: the admin steps of docs/enakgame-spin.md make a spin wheel, and a customer
// plays it through /customer/enakgame/sessions, over HTTP down to Postgres.
func TestEnakGameSpin_AgainstPostgres(t *testing.T) {
dsn := os.Getenv("TEST_DATABASE_URL")
if dsn == "" {
t.Skip("TEST_DATABASE_URL not set")
}
applogger.Setup("fatal", "json")
db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{Logger: logger.Default.LogMode(logger.Silent)})
require.NoError(t, err)
org, admin, customer := uuid.New(), uuid.New(), uuid.New()
require.NoError(t, db.Exec(`INSERT INTO organizations (id, name, plan_type) VALUES (?, 'enakgame spin', 'basic')`, org).Error)
require.NoError(t, db.Exec(`INSERT INTO customers (id, organization_id, name) VALUES (?, ?, 'Budi')`, customer, org).Error)
t.Cleanup(func() {
for _, q := range []string{
`DELETE FROM audit_logs WHERE organization_id = ?`,
`DELETE FROM game_reward_counters WHERE organization_id = ?`,
`DELETE FROM game_session_rewards WHERE session_id IN (SELECT id FROM game_sessions WHERE organization_id = ?)`,
`DELETE FROM game_sessions WHERE organization_id = ?`,
`DELETE FROM wallet_lot_allocations WHERE lot_id IN (SELECT id FROM wallet_lots WHERE organization_id = ?)`,
`DELETE FROM wallet_lots WHERE organization_id = ?`,
`DELETE FROM wallet_transactions WHERE organization_id = ?`,
`DELETE FROM customer_wallets WHERE organization_id = ?`,
`DELETE FROM game_reward_configs WHERE organization_id = ?`,
`DELETE FROM game_budgets WHERE organization_id = ?`,
`DELETE FROM games WHERE organization_id = ?`,
`DELETE FROM customers WHERE organization_id = ?`,
`DELETE FROM organizations WHERE id = ?`,
} {
db.Exec(q, org)
}
})
txm := repository.NewTxManager(db)
wallet := processor.NewWalletProcessor(repository.NewWalletRepository(db))
require.NoError(t, txm.WithTransaction(context.Background(), func(ctx context.Context) error {
_, err := wallet.Credit(ctx, processor.WalletCreditInput{WalletEntry: processor.WalletEntry{
CustomerID: customer, Currency: "COIN", Type: "MIGRATION", Amount: 20,
ReferenceType: "LEGACY_TOKENS", ReferenceID: uuid.New(), Description: "Saldo awal"}})
return err
}))
adminHandler, customerHandler := enakGameHandlers(db)
gin.SetMode(gin.TestMode)
router := gin.New()
m := router.Group("/marketing/enakgame", func(c *gin.Context) {
ctx := context.WithValue(c.Request.Context(), appcontext.OrganizationIDKey, org.String())
ctx = context.WithValue(ctx, appcontext.UserIDKey, admin.String())
ctx = context.WithValue(ctx, appcontext.UserRoleKey, "manager")
c.Request = c.Request.WithContext(ctx)
})
m.POST("/games", adminHandler.CreateGame)
m.POST("/games/:id/reward-configs", adminHandler.CreateRewardConfig)
m.POST("/reward-configs/:id/activate", adminHandler.ActivateRewardConfig)
m.POST("/budgets", adminHandler.CreateBudget)
c := router.Group("/customer/enakgame", func(c *gin.Context) { c.Set("customer_id", customer.String()) })
c.GET("/games", customerHandler.ListGames)
c.POST("/sessions", customerHandler.StartSession)
c.POST("/sessions/:id/complete", customerHandler.CompleteSession)
call := func(method, path, body string, headers ...string) map[string]any {
t.Helper()
req := httptest.NewRequest(method, path, bytes.NewBufferString(body))
for i := 0; i+1 < len(headers); i += 2 {
req.Header.Set(headers[i], headers[i+1])
}
rec := httptest.NewRecorder()
router.ServeHTTP(rec, req)
var out map[string]any
require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &out), rec.Body.String())
require.Equal(t, http.StatusOK, rec.Code, out)
return out["data"].(map[string]any)
}
// The admin steps.
game := call(http.MethodPost, "/marketing/enakgame/games",
`{"name": "Spin Harian", "slug": "spin", "type": "SPIN", "entry_cost": 5, "status": "ACTIVE"}`)
gameID := game["id"].(string)
config := call(http.MethodPost, "/marketing/enakgame/games/"+gameID+"/reward-configs", `{"reward_type": "PROBABILITY", "max_reward": 50,
"rules": {"table": [
{"weight": 50, "amount": 0, "label": "Zonk"},
{"weight": 30, "amount": 3, "label": "3 Coin"},
{"weight": 15, "amount": 10, "label": "10 Coin"},
{"weight": 5, "amount": 50, "label": "Jackpot"}]}}`)
call(http.MethodPost, "/marketing/enakgame/reward-configs/"+config["id"].(string)+"/activate", `{}`)
now := time.Now().In(time.FixedZone("WIB", 7*3600))
first := time.Date(now.Year(), now.Month(), 1, 0, 0, 0, 0, time.UTC)
call(http.MethodPost, "/marketing/enakgame/budgets", `{"scope": "GLOBAL", "name": "Bulan ini", "period_start": "`+
first.Format("2006-01-02")+`", "period_end": "`+first.AddDate(0, 1, -1).Format("2006-01-02")+`", "amount": 1000000}`)
// The wheel shows the segments, never their odds.
req := httptest.NewRequest(http.MethodGet, "/customer/enakgame/games", nil)
rec := httptest.NewRecorder()
router.ServeHTTP(rec, req)
require.Equal(t, http.StatusOK, rec.Code, rec.Body.String())
var listed struct {
Data []struct {
ID string `json:"id"`
Prizes []struct {
Entry int `json:"entry"`
Label *string `json:"label"`
Amount int64 `json:"amount"`
} `json:"prizes"`
} `json:"data"`
}
require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &listed))
require.Len(t, listed.Data, 1)
require.Len(t, listed.Data[0].Prizes, 4)
assert.Equal(t, "Jackpot", *listed.Data[0].Prizes[3].Label)
assert.NotContains(t, rec.Body.String(), "weight")
// Two spins: each lands on a listed segment and pays what it shows.
balance := int64(20)
for _, key := range []string{"spin-1", "spin-2"} {
started := call(http.MethodPost, "/customer/enakgame/sessions", `{"game_id": "`+gameID+`"}`, "Idempotency-Key", key)
balance -= 5
assert.EqualValues(t, balance, started["coin_balance"])
done := call(http.MethodPost, "/customer/enakgame/sessions/"+started["session_id"].(string)+"/complete", `{}`)
prize := done["prize"].(map[string]any)
entry := int(prize["entry"].(float64))
require.True(t, entry >= 1 && entry <= 4, prize)
segment := listed.Data[0].Prizes[entry-1]
assert.Equal(t, *segment.Label, prize["label"])
assert.EqualValues(t, segment.Amount, prize["amount"])
assert.EqualValues(t, segment.Amount, done["reward_total"])
balance += segment.Amount
assert.EqualValues(t, balance, done["coin_balance"])
}
}