Files
apskel-pos-backend/internal/repository/game_event_repository.go
T
efrilmandClaude Opus 5.5 798a36bd6c 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>
2026-10-07 20:53:14 +07:00

218 lines
8.6 KiB
Go

package repository
import (
"context"
"errors"
"fmt"
"time"
"github.com/google/uuid"
"gorm.io/gorm"
"gorm.io/gorm/clause"
"apskel-pos-be/internal/constants"
"apskel-pos-be/internal/entities"
)
var (
// ErrGameEventNotFound means no event with that id in the organization.
ErrGameEventNotFound = errors.New("enakgame: event not found")
// ErrGameEventSlugTaken means another event of the organization has the slug.
ErrGameEventSlugTaken = errors.New("enakgame: event slug already used")
)
// GameEventFilter selects an organization's events.
type GameEventFilter struct {
OrganizationID uuid.UUID
// Empty for every status.
Statuses []string
Offset int
Limit int
}
// GameEventRepository stores EnakGame events and the games they cover
// (docs/rfc-enakgame.md §5.5), always scoped to an organization.
type GameEventRepository interface {
// CreateEvent stores an event and the games it covers.
CreateEvent(ctx context.Context, event *entities.GameEvent, gameIDs []uuid.UUID) error
GetEvent(ctx context.Context, organizationID, id uuid.UUID) (*entities.GameEvent, error)
// LockEvent is GetEvent with the row locked until the transaction ends.
LockEvent(ctx context.Context, organizationID, id uuid.UUID) (*entities.GameEvent, error)
// EventGames returns the games each event covers.
EventGames(ctx context.Context, eventIDs []uuid.UUID) (map[uuid.UUID][]uuid.UUID, error)
// ListEvents returns a page of events, latest start first, and the total.
ListEvents(ctx context.Context, filter GameEventFilter) ([]entities.GameEvent, int64, error)
// UpdateEvent stores everything but the organization and the status, and replaces
// the games it covers.
UpdateEvent(ctx context.Context, event *entities.GameEvent, gameIDs []uuid.UUID) error
SetEventStatus(ctx context.Context, organizationID, id uuid.UUID, status string) error
// ActiveEventsForGame returns the events changing a game's rewards at now: ACTIVE,
// started, not ended. Highest priority first, then oldest.
ActiveEventsForGame(ctx context.Context, organizationID, gameID uuid.UUID, now time.Time) ([]entities.GameEvent, error)
// ActiveEventsByGame is ActiveEventsForGame for every game of the organization.
ActiveEventsByGame(ctx context.Context, organizationID uuid.UUID, now time.Time) (map[uuid.UUID][]entities.GameEvent, error)
}
type gameEventRepository struct {
db *gorm.DB
}
func NewGameEventRepository(db *gorm.DB) GameEventRepository {
return &gameEventRepository{db: db}
}
func (r *gameEventRepository) CreateEvent(ctx context.Context, event *entities.GameEvent, gameIDs []uuid.UUID) error {
db := DBFromContext(ctx, r.db).WithContext(ctx)
if err := db.Create(event).Error; err != nil {
if isUniqueViolation(err, "uq_game_events_slug") {
return ErrGameEventSlugTaken
}
return fmt.Errorf("failed to create game event: %w", err)
}
return r.linkGames(db, event.ID, gameIDs)
}
func (r *gameEventRepository) linkGames(db *gorm.DB, eventID uuid.UUID, gameIDs []uuid.UUID) error {
for _, gameID := range gameIDs {
if err := db.Exec(`INSERT INTO game_event_games (event_id, game_id) VALUES (?, ?) ON CONFLICT DO NOTHING`, eventID, gameID).Error; err != nil {
return fmt.Errorf("failed to link game to event: %w", err)
}
}
return nil
}
func (r *gameEventRepository) getEvent(ctx context.Context, organizationID, id uuid.UUID, lock bool) (*entities.GameEvent, error) {
q := DBFromContext(ctx, r.db).WithContext(ctx).Where("organization_id = ? AND id = ?", organizationID, id)
if lock {
q = q.Clauses(clause.Locking{Strength: "UPDATE"})
}
var event entities.GameEvent
if err := q.First(&event).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, ErrGameEventNotFound
}
return nil, fmt.Errorf("failed to read game event: %w", err)
}
return &event, nil
}
func (r *gameEventRepository) GetEvent(ctx context.Context, organizationID, id uuid.UUID) (*entities.GameEvent, error) {
return r.getEvent(ctx, organizationID, id, false)
}
func (r *gameEventRepository) LockEvent(ctx context.Context, organizationID, id uuid.UUID) (*entities.GameEvent, error) {
return r.getEvent(ctx, organizationID, id, true)
}
func (r *gameEventRepository) EventGames(ctx context.Context, eventIDs []uuid.UUID) (map[uuid.UUID][]uuid.UUID, error) {
out := map[uuid.UUID][]uuid.UUID{}
if len(eventIDs) == 0 {
return out, nil
}
var rows []struct{ EventID, GameID string }
err := DBFromContext(ctx, r.db).WithContext(ctx).Raw(`
SELECT event_id::text AS event_id, game_id::text AS game_id FROM game_event_games
WHERE event_id IN ? ORDER BY game_id`, eventIDs).Scan(&rows).Error
if err != nil {
return nil, fmt.Errorf("failed to read event games: %w", err)
}
for _, row := range rows {
eventID, _ := uuid.Parse(row.EventID)
gameID, _ := uuid.Parse(row.GameID)
out[eventID] = append(out[eventID], gameID)
}
return out, nil
}
func (r *gameEventRepository) ListEvents(ctx context.Context, filter GameEventFilter) ([]entities.GameEvent, int64, error) {
q := DBFromContext(ctx, r.db).WithContext(ctx).Model(&entities.GameEvent{}).Where("organization_id = ?", filter.OrganizationID)
if len(filter.Statuses) > 0 {
q = q.Where("status IN ?", filter.Statuses)
}
var total int64
if err := q.Count(&total).Error; err != nil {
return nil, 0, fmt.Errorf("failed to count game events: %w", err)
}
var events []entities.GameEvent
if err := q.Order("start_at DESC, id").Offset(filter.Offset).Limit(filter.Limit).Find(&events).Error; err != nil {
return nil, 0, fmt.Errorf("failed to list game events: %w", err)
}
return events, total, nil
}
func (r *gameEventRepository) UpdateEvent(ctx context.Context, e *entities.GameEvent, gameIDs []uuid.UUID) error {
db := DBFromContext(ctx, r.db).WithContext(ctx)
result := db.Exec(`
UPDATE game_events SET name = ?, slug = ?, description = ?, banner_url = ?, start_at = ?, end_at = ?,
timezone = ?, priority = ?, multiplier = ?, bonus = ?, budget_id = ?, reward_limit = ?,
user_daily_limit = ?, updated_at = NOW()
WHERE organization_id = ? AND id = ?`,
e.Name, e.Slug, e.Description, e.BannerURL, e.StartAt, e.EndAt, e.Timezone, e.Priority, e.Multiplier,
e.Bonus, e.BudgetID, e.RewardLimit, e.UserDailyLimit, e.OrganizationID, e.ID)
if result.Error != nil {
if isUniqueViolation(result.Error, "uq_game_events_slug") {
return ErrGameEventSlugTaken
}
return fmt.Errorf("failed to update game event: %w", result.Error)
}
if result.RowsAffected == 0 {
return ErrGameEventNotFound
}
if err := db.Exec(`DELETE FROM game_event_games WHERE event_id = ?`, e.ID).Error; err != nil {
return fmt.Errorf("failed to unlink event games: %w", err)
}
return r.linkGames(db, e.ID, gameIDs)
}
func (r *gameEventRepository) SetEventStatus(ctx context.Context, organizationID, id uuid.UUID, status string) error {
result := DBFromContext(ctx, r.db).WithContext(ctx).Exec(`
UPDATE game_events SET status = ?, updated_at = NOW() WHERE organization_id = ? AND id = ?`, status, organizationID, id)
if result.Error != nil {
return fmt.Errorf("failed to change game event status: %w", result.Error)
}
if result.RowsAffected == 0 {
return ErrGameEventNotFound
}
return nil
}
func (r *gameEventRepository) ActiveEventsForGame(ctx context.Context, organizationID, gameID uuid.UUID, now time.Time) ([]entities.GameEvent, error) {
var events []entities.GameEvent
err := DBFromContext(ctx, r.db).WithContext(ctx).
Joins("JOIN game_event_games eg ON eg.event_id = game_events.id").
Where("game_events.organization_id = ? AND eg.game_id = ? AND game_events.status = ? AND game_events.start_at <= ? AND game_events.end_at > ?",
organizationID, gameID, constants.GameEventStatusActive, now, now).
Order("game_events.priority DESC, game_events.created_at, game_events.id").
Find(&events).Error
if err != nil {
return nil, fmt.Errorf("failed to read active game events: %w", err)
}
return events, nil
}
func (r *gameEventRepository) ActiveEventsByGame(ctx context.Context, organizationID uuid.UUID, now time.Time) (map[uuid.UUID][]entities.GameEvent, error) {
db := DBFromContext(ctx, r.db).WithContext(ctx)
var events []entities.GameEvent
err := db.Where("organization_id = ? AND status = ? AND start_at <= ? AND end_at > ?", organizationID, constants.GameEventStatusActive, now, now).
Order("priority DESC, created_at, id").Find(&events).Error
if err != nil {
return nil, fmt.Errorf("failed to read active game events: %w", err)
}
ids := make([]uuid.UUID, 0, len(events))
for _, e := range events {
ids = append(ids, e.ID)
}
games, err := r.EventGames(ctx, ids)
if err != nil {
return nil, err
}
out := map[uuid.UUID][]entities.GameEvent{}
for _, e := range events {
for _, gameID := range games[e.ID] {
out[gameID] = append(out[gameID], e)
}
}
return out, nil
}