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:
co-authored by
Claude Opus 5.5
parent
798a36bd6c
commit
296708244e
@@ -0,0 +1,129 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// GameSessionStats is what an organization's sessions in a range add up to, for one
|
||||
// game, or for all of them when GameID is nil.
|
||||
type GameSessionStats struct {
|
||||
GameID *uuid.UUID
|
||||
GameName *string
|
||||
Plays int64
|
||||
Completed int64
|
||||
Refunded int64
|
||||
Expired int64
|
||||
Flagged int64
|
||||
Players int64
|
||||
AverageScore *float64
|
||||
CoinIssued int64
|
||||
EntryCost int64
|
||||
CoinRefunded int64
|
||||
}
|
||||
|
||||
// WalletFlow is what one ledger type moved in one currency over a range.
|
||||
type WalletFlow struct {
|
||||
Currency string
|
||||
Type string
|
||||
Credit int64
|
||||
Debit int64
|
||||
Transactions int64
|
||||
}
|
||||
|
||||
// EnakGameAnalyticsRepository reads EnakGame analytics (docs/tasks-enakgame.md
|
||||
// EG-903, PRD §36) from the tables that hold the facts, on read. Ranges are [from, to).
|
||||
type EnakGameAnalyticsRepository interface {
|
||||
// SessionStats returns one row per game with a session started in the range,
|
||||
// most played first, then the row for all of them. gameID narrows it to one game.
|
||||
SessionStats(ctx context.Context, organizationID uuid.UUID, from, to time.Time, gameID *uuid.UUID) ([]GameSessionStats, error)
|
||||
// WalletFlows sums the organization's ledger in the range per currency and type.
|
||||
WalletFlows(ctx context.Context, organizationID uuid.UUID, from, to time.Time) ([]WalletFlow, error)
|
||||
// BalancesAt sums what the organization's customers held just before at.
|
||||
BalancesAt(ctx context.Context, organizationID uuid.UUID, at time.Time) (map[string]int64, error)
|
||||
}
|
||||
|
||||
type enakGameAnalyticsRepository struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
func NewEnakGameAnalyticsRepository(db *gorm.DB) EnakGameAnalyticsRepository {
|
||||
return &enakGameAnalyticsRepository{db: db}
|
||||
}
|
||||
|
||||
func (r *enakGameAnalyticsRepository) SessionStats(ctx context.Context, organizationID uuid.UUID, from, to time.Time, gameID *uuid.UUID) ([]GameSessionStats, error) {
|
||||
filter := ""
|
||||
args := []any{organizationID, from, to}
|
||||
if gameID != nil {
|
||||
filter = "AND s.game_id = ?"
|
||||
args = append(args, *gameID)
|
||||
}
|
||||
// The empty grouping set adds the row for all games, also when there is no
|
||||
// session at all.
|
||||
var rows []GameSessionStats
|
||||
err := DBFromContext(ctx, r.db).WithContext(ctx).Raw(`
|
||||
SELECT s.game_id, g.name AS game_name,
|
||||
COUNT(*) AS plays,
|
||||
COUNT(*) FILTER (WHERE s.status = 'COMPLETED') AS completed,
|
||||
COUNT(*) FILTER (WHERE s.status = 'REFUNDED') AS refunded,
|
||||
COUNT(*) FILTER (WHERE s.status = 'EXPIRED') AS expired,
|
||||
COUNT(*) FILTER (WHERE s.flagged) AS flagged,
|
||||
COUNT(DISTINCT s.customer_id) AS players,
|
||||
AVG((s.result->>'score')::float8)
|
||||
FILTER (WHERE s.status = 'COMPLETED' AND jsonb_typeof(s.result->'score') = 'number') AS average_score,
|
||||
COALESCE(SUM(s.reward_total) FILTER (WHERE s.status = 'COMPLETED'), 0) AS coin_issued,
|
||||
COALESCE(SUM(s.entry_cost), 0) AS entry_cost,
|
||||
COALESCE(SUM(s.entry_cost) FILTER (WHERE s.status = 'REFUNDED'), 0) AS coin_refunded
|
||||
FROM game_sessions s
|
||||
JOIN games g ON g.id = s.game_id
|
||||
WHERE s.organization_id = ? AND s.started_at >= ? AND s.started_at < ? `+filter+`
|
||||
GROUP BY GROUPING SETS ((s.game_id, g.name), ())
|
||||
ORDER BY GROUPING(s.game_id), plays DESC, g.name`, args...).Scan(&rows).Error
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to read game session stats: %w", err)
|
||||
}
|
||||
return rows, nil
|
||||
}
|
||||
|
||||
func (r *enakGameAnalyticsRepository) WalletFlows(ctx context.Context, organizationID uuid.UUID, from, to time.Time) ([]WalletFlow, error) {
|
||||
var rows []WalletFlow
|
||||
err := DBFromContext(ctx, r.db).WithContext(ctx).Raw(`
|
||||
SELECT currency, type,
|
||||
COALESCE(SUM(amount) FILTER (WHERE amount > 0), 0) AS credit,
|
||||
COALESCE(-SUM(amount) FILTER (WHERE amount < 0), 0) AS debit,
|
||||
COUNT(*) AS transactions
|
||||
FROM wallet_transactions
|
||||
WHERE organization_id = ? AND created_at >= ? AND created_at < ?
|
||||
GROUP BY currency, type
|
||||
ORDER BY currency, type`, organizationID, from, to).Scan(&rows).Error
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to sum wallet flows: %w", err)
|
||||
}
|
||||
return rows, nil
|
||||
}
|
||||
|
||||
func (r *enakGameAnalyticsRepository) BalancesAt(ctx context.Context, organizationID uuid.UUID, at time.Time) (map[string]int64, error) {
|
||||
// The ledger is signed and append-only, so what it adds up to before at is what
|
||||
// customers held then.
|
||||
var rows []struct {
|
||||
Currency string
|
||||
Total int64
|
||||
}
|
||||
err := DBFromContext(ctx, r.db).WithContext(ctx).Raw(`
|
||||
SELECT currency, COALESCE(SUM(amount), 0) AS total
|
||||
FROM wallet_transactions
|
||||
WHERE organization_id = ? AND created_at < ?
|
||||
GROUP BY currency`, organizationID, at).Scan(&rows).Error
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to sum wallet balances: %w", err)
|
||||
}
|
||||
out := make(map[string]int64, len(rows))
|
||||
for _, row := range rows {
|
||||
out[row.Currency] = row.Total
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user