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>
96 lines
4.7 KiB
Go
96 lines
4.7 KiB
Go
package processor
|
|
|
|
import (
|
|
"testing"
|
|
"time"
|
|
|
|
"github.com/google/uuid"
|
|
"github.com/stretchr/testify/assert"
|
|
"github.com/stretchr/testify/require"
|
|
|
|
"apskel-pos-be/internal/constants"
|
|
"apskel-pos-be/internal/models"
|
|
"apskel-pos-be/internal/repository"
|
|
)
|
|
|
|
// EG-601 against Postgres, with fixed data giving the PRD §30 numbers. Needs
|
|
// TEST_DATABASE_URL; see internal/repository/wallet_repository_test.go.
|
|
func TestGameBudgetMetrics_AgainstPostgres(t *testing.T) {
|
|
e := newEnakGameEnv(t)
|
|
ctx := e.ctx()
|
|
e.now = time.Date(2026, 10, 21, 12, 0, 0, 0, walletDisplayLocation)
|
|
metrics := NewGameBudgetMetricsProcessor(repository.NewGameBudgetRepository(e.db), repository.NewGameBudgetMetricsRepository(e.db))
|
|
metrics.now = func() time.Time { return e.now }
|
|
|
|
october := e.globalBudget(e.orgA, e.now)
|
|
event, err := e.budgets.CreateBudget(ctx, e.orgA, e.manager, models.GameBudgetInput{
|
|
Scope: "EVENT", Name: "Ramadan", PeriodStart: "2026-10-10", PeriodEnd: "2026-10-20", Amount: 10_000_000,
|
|
Thresholds: models.GameBudgetThresholds{Warning: ptr(int64(20)), Critical: ptr(int64(50))},
|
|
})
|
|
require.NoError(t, err)
|
|
|
|
voucher := e.staticVoucher(1_000, 1, 1)
|
|
// cost records a completed redemption whose face value went to budget (nil: EnakPoint
|
|
// not from EnakGame), recognized at a time in Jakarta.
|
|
cost := func(budget *uuid.UUID, source string, amount int64, day, hour int) {
|
|
t.Helper()
|
|
at := time.Date(2026, time.Month(day/100), day%100, hour, 0, 0, 0, walletDisplayLocation)
|
|
debit, redemption := uuid.New(), uuid.New()
|
|
require.NoError(t, e.db.Exec(`INSERT INTO wallet_transactions (id, organization_id, customer_id, currency, type, amount, balance_after, reference_type, reference_id, description)
|
|
VALUES (?, ?, ?, 'POINT', 'REWARD_REDEEM', -1, 0, 'REWARD_REDEMPTION', ?, 'x')`, debit, e.orgA, e.bob, redemption).Error)
|
|
require.NoError(t, e.db.Exec(`INSERT INTO voucher_redemptions (id, organization_id, customer_id, voucher_id, idempotency_key, status, face_value, point_cost, debit_transaction_id, completed_at)
|
|
VALUES (?, ?, ?, ?, ?, 'COMPLETED', ?, 1, ?, ?)`, redemption, e.orgA, e.bob, voucher.ID, redemption.String(), amount, debit, at).Error)
|
|
require.NoError(t, e.db.Exec(`INSERT INTO voucher_redemption_costs (redemption_id, budget_id, source_type, points, cost, recognized_at) VALUES (?, ?, ?, 1, ?, ?)`,
|
|
redemption, budget, source, amount, at).Error)
|
|
}
|
|
global, ev := october.ID, event.ID
|
|
cost(&global, "GAME_REWARD", 5_000_000, 930, 23) // 30 Sep 23:00 WIB: the month before
|
|
cost(&global, "GAME_REWARD", 21_500_000, 1005, 1) // before the forecast window
|
|
for day := 1015; day <= 1021; day++ { // the last seven days, today included
|
|
cost(&global, "GAME_REWARD", 5_500_000, day, 0)
|
|
}
|
|
cost(nil, "EARN", 9_000_000, 1020, 10) // shopping EnakPoint: no budget
|
|
cost(&ev, "GAME_REWARD", 1_000_000, 1012, 10)
|
|
cost(&ev, "GAME_REWARD", 2_000_000, 1021, 9) // after the event ended: still its cost
|
|
|
|
// EnakCoin the global budget paid for, partly exchanged into EnakPoint.
|
|
paid := e.rewardCoins(e.alice, 100)
|
|
require.Equal(t, october.ID, paid)
|
|
e.exchangeCoins(e.alice, 40)
|
|
|
|
m, err := metrics.Metrics(ctx, e.orgA, october.ID)
|
|
require.NoError(t, err)
|
|
assert.Equal(t, "2026-10-21", m.AsOf)
|
|
assert.EqualValues(t, 100_000_000, m.Amount)
|
|
assert.EqualValues(t, 60_000_000, m.RealizedCost, "within October, from EnakGame only")
|
|
assert.EqualValues(t, 40_000_000, m.Remaining)
|
|
assert.EqualValues(t, 60, m.UtilizationPercent)
|
|
assert.EqualValues(t, 7, m.WindowDays)
|
|
assert.EqualValues(t, 10, m.RemainingDays)
|
|
assert.EqualValues(t, 5_500_000, m.DailyBurn)
|
|
assert.EqualValues(t, 115_000_000, m.ForecastCost)
|
|
assert.EqualValues(t, -15_000_000, m.ForecastRemaining)
|
|
assert.Equal(t, constants.GameBudgetCritical, m.Status)
|
|
assert.EqualValues(t, 100, m.CoinIssued)
|
|
assert.Equal(t, models.GameBudgetExposure{Coins: 60, Points: 40}, m.Exposure, "followed through the exchange")
|
|
|
|
m, err = metrics.Metrics(ctx, e.orgA, event.ID)
|
|
require.NoError(t, err)
|
|
assert.EqualValues(t, 3_000_000, m.RealizedCost, "an event budget has no time bound")
|
|
assert.Zero(t, m.RemainingDays, "the event is over")
|
|
assert.EqualValues(t, 3_000_000, m.ForecastCost)
|
|
assert.EqualValues(t, 30, m.UtilizationPercent)
|
|
assert.Equal(t, constants.GameBudgetWarning, m.Status, "its own thresholds: 20 and 50")
|
|
assert.Zero(t, m.CoinIssued)
|
|
|
|
_, err = metrics.Metrics(ctx, e.orgB, october.ID)
|
|
assert.ErrorIs(t, err, repository.ErrGameBudgetNotFound)
|
|
|
|
// Redeeming the EnakPoint lowers the exposure; spending EnakCoin on a game does too.
|
|
_, err = e.redeemVoucher(e.alice, voucher.ID, "metrics")
|
|
require.NoError(t, err)
|
|
m, err = metrics.Metrics(ctx, e.orgA, october.ID)
|
|
require.NoError(t, err)
|
|
assert.Equal(t, models.GameBudgetExposure{Coins: 60, Points: 39}, m.Exposure)
|
|
}
|