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>
215 lines
7.7 KiB
Go
215 lines
7.7 KiB
Go
package processor
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"sync"
|
|
"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"
|
|
)
|
|
|
|
// fakeVoucherProvider stands in for a provider. issueMode says what Issue does:
|
|
// "ok" issues, "reject" refuses, "lost" issues but the answer never arrives, "down"
|
|
// never gets the request. lookupMode "down" makes Lookup fail as well.
|
|
type fakeVoucherProvider struct {
|
|
mu sync.Mutex
|
|
issueMode string
|
|
lookupMode string
|
|
issued map[uuid.UUID]*VoucherIssue
|
|
issueCalls int
|
|
}
|
|
|
|
func (f *fakeVoucherProvider) set(issue, lookup string) {
|
|
f.mu.Lock()
|
|
defer f.mu.Unlock()
|
|
f.issueMode, f.lookupMode = issue, lookup
|
|
}
|
|
|
|
func (f *fakeVoucherProvider) Issue(_ context.Context, req VoucherIssueRequest) (*VoucherIssue, error) {
|
|
f.mu.Lock()
|
|
defer f.mu.Unlock()
|
|
f.issueCalls++
|
|
switch f.issueMode {
|
|
case "reject":
|
|
return nil, fmt.Errorf("%w: sold out", ErrVoucherProviderRejected)
|
|
case "down":
|
|
return nil, context.DeadlineExceeded
|
|
}
|
|
issue, ok := f.issued[req.RedemptionID]
|
|
if !ok {
|
|
// The redemption id is the provider's idempotency key.
|
|
issue = &VoucherIssue{Code: fmt.Sprintf("EXT-%d", len(f.issued)+1), Ref: "ref-" + req.RedemptionID.String()[:8]}
|
|
f.issued[req.RedemptionID] = issue
|
|
}
|
|
if f.issueMode == "lost" {
|
|
return nil, context.DeadlineExceeded
|
|
}
|
|
return issue, nil
|
|
}
|
|
|
|
func (f *fakeVoucherProvider) Lookup(_ context.Context, req VoucherIssueRequest) (*VoucherIssue, error) {
|
|
f.mu.Lock()
|
|
defer f.mu.Unlock()
|
|
if f.lookupMode == "down" {
|
|
return nil, context.DeadlineExceeded
|
|
}
|
|
if issue, ok := f.issued[req.RedemptionID]; ok {
|
|
return issue, nil
|
|
}
|
|
return nil, ErrVoucherProviderNotFound
|
|
}
|
|
|
|
func (e *enakGameEnv) redemptionStatus(id uuid.UUID) (string, *string, int) {
|
|
e.t.Helper()
|
|
var row struct {
|
|
Status string
|
|
ExternalCode *string
|
|
Attempts int
|
|
}
|
|
require.NoError(e.t, e.db.Raw(`SELECT status, external_code, attempts FROM voucher_redemptions WHERE id = ?`, id).Scan(&row).Error)
|
|
return row.Status, row.ExternalCode, row.Attempts
|
|
}
|
|
|
|
// EG-801, EG-802, EG-803
|
|
func TestVoucherRedemption_External(t *testing.T) {
|
|
e := newEnakGameEnv(t)
|
|
ctx := e.ctx()
|
|
external := e.voucher(e.orgA, models.VoucherInput{Name: "Pulsa", FaceValue: 10_000, PointCost: 1_000, StockMode: "EXTERNAL",
|
|
Provider: ptr("acme"), ProviderRef: ptr("PULSA-10K")})
|
|
e.points(e.alice, constants.WalletTxTypeAdjustment, 100_000)
|
|
refunds := func(id uuid.UUID) int64 {
|
|
return e.count(`SELECT COUNT(*) FROM wallet_transactions WHERE type = 'REWARD_REDEEM_REFUND' AND reference_id = ?`, id)
|
|
}
|
|
// The job works across organizations and other tests may share the database, so
|
|
// each step checks its own redemption, not the job's totals.
|
|
recover := func() {
|
|
t.Helper()
|
|
_, _, err := e.redeem.RecoverPending(ctx)
|
|
require.NoError(t, err)
|
|
}
|
|
|
|
catalog, err := e.redeem.Catalog(ctx, e.alice)
|
|
require.NoError(t, err)
|
|
require.Len(t, catalog, 1, "listed: its provider has an adapter")
|
|
assert.Nil(t, catalog[0].Available)
|
|
|
|
t.Run("issued at once", func(t *testing.T) {
|
|
e.provider.set("ok", "ok")
|
|
before := e.pointBalance(e.alice)
|
|
res, err := e.redeemVoucher(e.alice, external.ID, "ok")
|
|
require.NoError(t, err)
|
|
assert.Equal(t, constants.VoucherRedemptionCompleted, res.Status)
|
|
require.NotNil(t, res.Code)
|
|
assert.Contains(t, *res.Code, "EXT-")
|
|
assert.EqualValues(t, before-1_000, res.PointBalance)
|
|
assert.Len(t, e.costs(res.ID), 1, "the cost is split once issued")
|
|
})
|
|
|
|
t.Run("refused: FAILED and the EnakPoint back", func(t *testing.T) {
|
|
e.provider.set("reject", "ok")
|
|
before := e.pointBalance(e.alice)
|
|
res, err := e.redeemVoucher(e.alice, external.ID, "reject")
|
|
require.NoError(t, err)
|
|
assert.Equal(t, constants.VoucherRedemptionFailed, res.Status)
|
|
assert.Nil(t, res.Code)
|
|
assert.EqualValues(t, before, res.PointBalance)
|
|
assert.Equal(t, int64(1), refunds(res.ID))
|
|
assert.Empty(t, e.costs(res.ID))
|
|
var reason string
|
|
require.NoError(t, e.db.Raw(`SELECT failure_reason FROM voucher_redemptions WHERE id = ?`, res.ID).Scan(&reason).Error)
|
|
assert.Contains(t, reason, "sold out")
|
|
// The refund lot points back at the lot the EnakPoint came from.
|
|
assert.Equal(t, int64(1), e.count(`SELECT COUNT(*) FROM wallet_lots l JOIN wallet_transactions t ON t.id = l.source_transaction_id
|
|
WHERE t.type = 'REWARD_REDEEM_REFUND' AND t.reference_id = ? AND l.origin_lot_id IS NOT NULL`, res.ID))
|
|
})
|
|
|
|
t.Run("answer lost: PENDING, then the job finds it issued", func(t *testing.T) {
|
|
e.provider.set("lost", "ok")
|
|
before := e.pointBalance(e.alice)
|
|
res, err := e.redeemVoucher(e.alice, external.ID, "lost")
|
|
require.NoError(t, err)
|
|
assert.Equal(t, constants.VoucherRedemptionPending, res.Status, "being processed")
|
|
assert.Nil(t, res.Code)
|
|
assert.EqualValues(t, before-1_000, e.pointBalance(e.alice), "the EnakPoint stay taken meanwhile")
|
|
calls := e.provider.issueCalls
|
|
again, err := e.redeemVoucher(e.alice, external.ID, "lost")
|
|
require.NoError(t, err)
|
|
assert.True(t, again.Replayed)
|
|
assert.Equal(t, constants.VoucherRedemptionPending, again.Status)
|
|
assert.Equal(t, calls, e.provider.issueCalls, "a retry does not call the provider")
|
|
|
|
recover()
|
|
status, _, _ := e.redemptionStatus(res.ID)
|
|
assert.Equal(t, constants.VoucherRedemptionPending, status, "too fresh for the job")
|
|
e.now = e.now.Add(3 * time.Minute)
|
|
recover()
|
|
status, code, _ := e.redemptionStatus(res.ID)
|
|
assert.Equal(t, constants.VoucherRedemptionCompleted, status)
|
|
assert.Equal(t, *e.provider.issued[res.ID], VoucherIssue{Code: *code, Ref: e.provider.issued[res.ID].Ref}, "the code the provider issued the first time")
|
|
assert.Equal(t, calls, e.provider.issueCalls, "found by lookup, not issued again")
|
|
assert.Len(t, e.costs(res.ID), 1)
|
|
e.now = e.now.Add(3 * time.Minute)
|
|
recover()
|
|
assert.Len(t, e.costs(res.ID), 1, "settled once")
|
|
})
|
|
|
|
t.Run("never reached: the job issues it", func(t *testing.T) {
|
|
e.provider.set("down", "ok")
|
|
res, err := e.redeemVoucher(e.alice, external.ID, "down")
|
|
require.NoError(t, err)
|
|
assert.Equal(t, constants.VoucherRedemptionPending, res.Status)
|
|
e.provider.set("ok", "ok")
|
|
e.now = e.now.Add(3 * time.Minute)
|
|
recover()
|
|
status, code, _ := e.redemptionStatus(res.ID)
|
|
assert.Equal(t, constants.VoucherRedemptionCompleted, status)
|
|
assert.NotNil(t, code)
|
|
list, err := e.redeem.ListRedemptions(ctx, e.alice, 1, 1)
|
|
require.NoError(t, err)
|
|
assert.Equal(t, code, list.Data[0].Code, "the customer sees the provider's code")
|
|
})
|
|
|
|
t.Run("no answer at all: refunded once after the last attempt", func(t *testing.T) {
|
|
e.provider.set("down", "down")
|
|
before := e.pointBalance(e.alice)
|
|
res, err := e.redeemVoucher(e.alice, external.ID, "silent")
|
|
require.NoError(t, err)
|
|
for attempt := 2; attempt < voucherMaxAttempts; attempt++ {
|
|
e.now = e.now.Add(3 * time.Minute)
|
|
recover()
|
|
status, _, _ := e.redemptionStatus(res.ID)
|
|
assert.Equal(t, constants.VoucherRedemptionPending, status, "attempt %d", attempt)
|
|
}
|
|
status, _, attempts := e.redemptionStatus(res.ID)
|
|
assert.Equal(t, constants.VoucherRedemptionPending, status)
|
|
assert.Equal(t, voucherMaxAttempts-1, attempts)
|
|
|
|
// Two instances run the last attempt at once: one refund.
|
|
e.now = e.now.Add(3 * time.Minute)
|
|
var wg sync.WaitGroup
|
|
for i := 0; i < 2; i++ {
|
|
wg.Add(1)
|
|
go func() {
|
|
defer wg.Done()
|
|
_, _, err := e.redeem.RecoverPending(ctx)
|
|
assert.NoError(t, err)
|
|
}()
|
|
}
|
|
wg.Wait()
|
|
status, _, _ = e.redemptionStatus(res.ID)
|
|
assert.Equal(t, constants.VoucherRedemptionFailed, status)
|
|
assert.Equal(t, int64(1), refunds(res.ID))
|
|
assert.EqualValues(t, before, e.pointBalance(e.alice))
|
|
e.now = e.now.Add(3 * time.Minute)
|
|
recover()
|
|
assert.Equal(t, int64(1), refunds(res.ID), "running again refunds nothing more")
|
|
})
|
|
}
|