feat(enakgame): budget controller recommendations and analytics

EnakGame phase 9 of docs/tasks-enakgame.md (EG-901 to EG-903).

Budget Controller (EG-901, EG-902)
- GET /marketing/enakgame/budgets/:id/recommendation, GLOBAL budgets only: the
  multiplier (budget − realized) / (forecast − realized), within one step of 1,
  rounded down to two decimals, either way. Shows each game's new rules.
- POST .../recommendation/accept with the multiplier the admin saw: recomputed in the
  transaction, then one new ACTIVE version per game, the old one RETIRED, audited
  with source budget_controller and RECOMMENDATION_ACCEPTED on the budget.
- Migration 000112: base_config_id, multiplier and budget_id on
  game_reward_configs. Rules are always scaled from the admin's last version, so
  rounding does not compound and min/max are against what the admin set.
- Guardrails in game_budgets.thresholds: max_step_percent 10, min/max multiplier
  50-150%, cooldown_days 7 per organization. Provisional pending RFC §19.2 #4.
- RewardCalculator.Scale for the four reward types: amounts only, rounded down.

Analytics (EG-903)
- GET /marketing/enakgame/analytics/games and /analytics/economy over a range of
  Asia/Jakarta days (at most 366), from game_sessions and the wallet ledger.
- Migrations 000113 (game_sessions by organization and start) and 000114
  (wallet_transactions by organization and time, CONCURRENTLY).

The Postgres tests for accepting and analytics were not run: no test database here.
Migrations 000112-000114 have not been run anywhere.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
efrilm
2026-10-07 21:18:31 +07:00
co-authored by Claude Opus 5.5
parent 798a36bd6c
commit 296708244e
28 changed files with 1647 additions and 25 deletions
+49 -3
View File
@@ -62,6 +62,19 @@ type EnakGameRepository interface {
// change a configuration allows (D7). It reports false when the configuration was
// not in from.
SetRewardConfigStatus(ctx context.Context, organizationID, id uuid.UUID, from, to string) (bool, error)
// ListActiveRewardConfigs returns the active configuration of every game of the
// organization that is not archived, by game name.
ListActiveRewardConfigs(ctx context.Context, organizationID uuid.UUID) ([]ActiveRewardConfig, error)
// LastBudgetControllerChange is when the organization last accepted a Budget
// Controller recommendation, or nil when it never did.
LastBudgetControllerChange(ctx context.Context, organizationID uuid.UUID) (*time.Time, error)
}
// ActiveRewardConfig is a game's active configuration with the game's name.
type ActiveRewardConfig struct {
entities.GameRewardConfig `gorm:"embedded"`
GameName string
}
type enakGameRepository struct {
@@ -176,14 +189,15 @@ func (r *enakGameRepository) CreateRewardConfig(ctx context.Context, config *ent
}
err := DBFromContext(ctx, r.db).WithContext(ctx).Raw(`
INSERT INTO game_reward_configs (id, organization_id, game_id, version, reward_type, rules,
max_reward, status, effective_at, created_by, reason)
max_reward, status, effective_at, created_by, reason, base_config_id, multiplier, budget_id)
SELECT ?, g.organization_id, g.id,
COALESCE((SELECT MAX(version) FROM game_reward_configs WHERE game_id = g.id), 0) + 1,
?, ?::jsonb, ?, ?, ?, ?, ?
?, ?::jsonb, ?, ?, ?, ?, ?, ?, ?, ?
FROM games g WHERE g.organization_id = ? AND g.id = ?
RETURNING version, created_at`,
config.ID, config.RewardType, config.Rules, config.MaxReward, config.Status, config.EffectiveAt,
config.CreatedBy, config.Reason, config.OrganizationID, config.GameID).Scan(&rows).Error
config.CreatedBy, config.Reason, config.BaseConfigID, config.Multiplier, config.BudgetID,
config.OrganizationID, config.GameID).Scan(&rows).Error
if err != nil {
return fmt.Errorf("failed to create reward config: %w", err)
}
@@ -235,3 +249,35 @@ func (r *enakGameRepository) SetRewardConfigStatus(ctx context.Context, organiza
}
return result.RowsAffected == 1, nil
}
func (r *enakGameRepository) ListActiveRewardConfigs(ctx context.Context, organizationID uuid.UUID) ([]ActiveRewardConfig, error) {
var configs []ActiveRewardConfig
err := DBFromContext(ctx, r.db).WithContext(ctx).Raw(`
SELECT c.*, g.name AS game_name
FROM game_reward_configs c
JOIN games g ON g.id = c.game_id
WHERE c.organization_id = ? AND c.status = ? AND g.status <> ?
ORDER BY g.name, g.id`,
organizationID, constants.GameRewardConfigStatusActive, constants.GameStatusArchived).Scan(&configs).Error
if err != nil {
return nil, fmt.Errorf("failed to list active reward configs: %w", err)
}
return configs, nil
}
func (r *enakGameRepository) LastBudgetControllerChange(ctx context.Context, organizationID uuid.UUID) (*time.Time, error) {
// effective_at, set by the Budget Controller from its clock, not created_at from
// the database's.
var last []time.Time
err := DBFromContext(ctx, r.db).WithContext(ctx).Raw(`
SELECT effective_at FROM game_reward_configs
WHERE organization_id = ? AND budget_id IS NOT NULL
ORDER BY effective_at DESC LIMIT 1`, organizationID).Scan(&last).Error
if err != nil {
return nil, fmt.Errorf("failed to read the last Budget Controller change: %w", err)
}
if len(last) == 0 {
return nil, nil
}
return &last[0], nil
}