218 lines
8.6 KiB
Go
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
|
||
|
|
}
|