Merge pull request 'Feat/enakgame' (#43) from feat/enakgame into staging
Reviewed-on: #43
This commit was merged in pull request #43.
This commit is contained in:
+9
-12
@@ -151,7 +151,7 @@ PIN baru ditolak `304` bila bukan 6 digit, konfirmasinya beda, semua digit sama
|
||||
| POST | `/customer/wallet/exchange` | Ya | Wajib |
|
||||
| GET | `/customer/wallet/transfer/recipient?phone=` | – | – |
|
||||
| POST | `/customer/wallet/transfer` | Ya | Wajib |
|
||||
| POST | `/customer/spin` | – | – |
|
||||
| POST | `/customer/enakgame/sessions` | – | Wajib |
|
||||
|
||||
### GET /customer/wallet/exchange/preview?coins=30
|
||||
|
||||
@@ -210,19 +210,15 @@ Body `{ "currency": "POINT", "amount": 120, "recipient_phone": "081234561234", "
|
||||
|
||||
`currency` = `POINT` atau `COIN`. Batas organisasi (transfer aktif, minimal, maksimal per transaksi, batas harian per currency yang reset tengah malam WIB) ditolak `304` sebelum PIN dicek. Transfer final. Saldo membawa tanggal kedaluwarsa aslinya ke penerima (`lots`), dan penerima mendapat push `WALLET_TRANSFER_IN`.
|
||||
|
||||
### POST /customer/spin
|
||||
### Game (EnakGame)
|
||||
|
||||
Body `{ "spin_id": "<id game>" }`. Memotong EnakCoin sebesar `metadata.coin_cost` game itu (default 1).
|
||||
`POST /customer/spin`, `GET /customer/games`, dan `GET /customer/ferris-wheel` sudah dihapus. Semua game, termasuk spin, dimainkan lewat `/customer/enakgame`:
|
||||
|
||||
```json
|
||||
{
|
||||
"game_play": { "id": "…", "game_id": "…", "coins_used": 1, "created_at": "…" },
|
||||
"prize_won": { "id": "…", "name": "Voucher 10rb" },
|
||||
"coins_remaining": 7
|
||||
}
|
||||
```
|
||||
- `GET /customer/enakgame/games`: game aktif dengan `entry_cost` (EnakCoin per main) dan, untuk spin, `prizes` (segmen roda).
|
||||
- `POST /customer/enakgame/sessions` dengan `{ "game_id": "…" }` dan `Idempotency-Key`: memotong `entry_cost`.
|
||||
- `POST /customer/enakgame/sessions/:id/complete`: server menghitung hadiah EnakCoin; untuk spin, response berisi `prize` (segmen yang keluar).
|
||||
|
||||
EnakCoin kurang, game nonaktif, atau hadiah baru saja habis → `304`, tidak ada EnakCoin yang terpotong.
|
||||
Alur spin lengkap ada di [`enakgame-spin.md`](./enakgame-spin.md).
|
||||
|
||||
## POS: earning, void, dan refund
|
||||
|
||||
@@ -273,7 +269,8 @@ Response menambahkan `outlet_id`, `point_value`, `point_cashback_percent` (defau
|
||||
"end_of_month": false,
|
||||
"reminder_days": 7
|
||||
},
|
||||
"coin_expiry": { "…": "sama dengan point_expiry" }
|
||||
"coin_expiry": { "…": "sama dengan point_expiry" },
|
||||
"enakgame": { "user_daily_limit": 0, "global_daily_limit": 0 }
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
@@ -18,7 +18,7 @@ Semua endpoint di bawah base URL `/api/v1`, butuh login user dengan role Admin a
|
||||
| Wallet customer | `GET /marketing/customers/:id/wallet`, `POST …/wallet/adjust` | Customer → detail customer → tab Wallet |
|
||||
| Telusuri mutasi | `GET /marketing/wallet-transactions/:id/trace` | Dibuka dari baris riwayat wallet |
|
||||
| PIN & keamanan customer | `DELETE /marketing/customers/:id/pin`, `GET …/security-events` | Customer → detail customer → tab Keamanan |
|
||||
| Biaya main game | `PUT` game yang sudah ada, `metadata.coin_cost` | Marketing → Game → edit game |
|
||||
| Biaya main game | `entry_cost` di `/marketing/enakgame/games` | Marketing → EnakGame → game |
|
||||
|
||||
Penempatan menu di atas adalah usulan; sesuaikan dengan struktur backoffice yang ada.
|
||||
|
||||
@@ -67,7 +67,8 @@ Nilai rupiah EnakPoint, kurs exchange, batas transfer, dan kedaluwarsa berlaku s
|
||||
"exchange": { "coin_amount": 1, "point_amount": 1 },
|
||||
"transfer": { "enabled": true, "min_amount": 1, "max_per_transaction": null, "daily_limit": null },
|
||||
"point_expiry": { "…": "lihat bagian kedaluwarsa" },
|
||||
"coin_expiry": { "…": "lihat bagian kedaluwarsa" }
|
||||
"coin_expiry": { "…": "lihat bagian kedaluwarsa" },
|
||||
"enakgame": { "user_daily_limit": 0, "global_daily_limit": 0 }
|
||||
}
|
||||
```
|
||||
|
||||
@@ -79,6 +80,8 @@ Nilai rupiah EnakPoint, kurs exchange, batas transfer, dan kedaluwarsa berlaku s
|
||||
| `transfer.min_amount` | Minimal per transfer | 1 | ≥ 1 |
|
||||
| `transfer.max_per_transaction` | Maksimal per transfer | kosong = tanpa batas | ≥ 1 |
|
||||
| `transfer.daily_limit` | Batas harian per customer | kosong = tanpa batas | ≥ 1, dihitung per currency, reset tengah malam WIB |
|
||||
| `enakgame.user_daily_limit` | Maksimal EnakCoin dari EnakGame per customer per hari | 0 = tanpa batas | ≥ 0, reset tengah malam WIB |
|
||||
| `enakgame.global_daily_limit` | Maksimal EnakCoin dari EnakGame seluruh organisasi per hari | 0 = tanpa batas | ≥ 0, reset tengah malam WIB |
|
||||
|
||||
### Alur simpan
|
||||
|
||||
@@ -266,7 +269,7 @@ Admin tidak bisa membuat, mengganti, atau melihat PIN customer; satu-satunya aks
|
||||
|
||||
### Biaya main game
|
||||
|
||||
Semua game (spin, raffle, minigame) memakai EnakCoin yang sama. Biaya per main diisi di `metadata.coin_cost` saat membuat atau mengedit game (`/marketing/games`): bilangan bulat ≥ 1, default 1 bila kosong. Nilai pecahan, 0, atau teks membuat game tidak bisa dimainkan. Karena `metadata` dikirim utuh, pertahankan key metadata lain saat menyimpan. Hadiah game juga bernilai rupiah secara tidak langsung, karena EnakCoin bisa ditukar ke EnakPoint.
|
||||
Semua game (spin, raffle, minigame) memakai EnakCoin yang sama dan dikelola di `/marketing/enakgame/games`. Menu lama `/marketing/games`, `/marketing/game-prizes`, dan `/marketing/rewards` sudah dihapus. Biaya per main adalah `entry_cost` game (bilangan bulat ≥ 1), hadiahnya diatur di reward config game itu. Langkah membuat spin ada di [`enakgame-spin.md`](./enakgame-spin.md). Hadiah game juga bernilai rupiah secara tidak langsung, karena EnakCoin bisa ditukar ke EnakPoint.
|
||||
|
||||
## Pesan error dan checklist
|
||||
|
||||
@@ -290,7 +293,7 @@ Pesan `cause` saat ini berbahasa Inggris, mis. `invalid loyalty settings: loyalt
|
||||
- [ ] Adjustment mewajibkan alasan dan mengirim `idempotency_key`.
|
||||
- [ ] Tombol Telusuri ada di setiap baris riwayat.
|
||||
- [ ] Hapus PIN mewajibkan alasan; tab Keamanan menampilkan log.
|
||||
- [ ] Form game punya input `coin_cost`.
|
||||
- [ ] Form game EnakGame punya input `entry_cost`.
|
||||
- [ ] Semua nilai rupiah EnakPoint ditulis "setara potongan Rp …".
|
||||
|
||||
Transfer belum boleh dirilis sebelum tinjauan legal (N3) selesai. Layar backoffice boleh disiapkan lebih dulu.
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
# Spin sebagai Game EnakGame
|
||||
|
||||
**Sumber:** [RFC EnakGame](rfc-enakgame.md) §14, task EG-1001
|
||||
**Pembaca:** admin organisasi dan tim backoffice / aplikasi customer
|
||||
|
||||
Spin lama (`POST /customer/spin`) diganti dengan game EnakGame biasa: tipe `SPIN`,
|
||||
reward `PROBABILITY`, hadiah berupa EnakCoin. Spin dimainkan lewat endpoint session
|
||||
yang sama dengan game lain, sehingga ikut mendapat idempotency, refund otomatis, budget,
|
||||
event, dan Economy Guard.
|
||||
|
||||
Tidak ada seeder: setiap organisasi membuat spin-nya sendiri lewat API admin di bawah.
|
||||
Semua langkah memakai token admin organisasi; langkah 2–4 butuh loyalty manager.
|
||||
|
||||
## Langkah Admin
|
||||
|
||||
### 1. Buat game
|
||||
|
||||
`POST /api/v1/marketing/enakgame/games`
|
||||
|
||||
```json
|
||||
{
|
||||
"name": "Spin Harian",
|
||||
"slug": "spin",
|
||||
"type": "SPIN",
|
||||
"entry_cost": 5,
|
||||
"status": "ACTIVE",
|
||||
"thumbnail_url": "https://…/spin.png",
|
||||
"game_url": "https://…/spin/index.html"
|
||||
}
|
||||
```
|
||||
|
||||
`entry_cost` adalah EnakCoin yang dipotong setiap kali spin (minimal 1).
|
||||
|
||||
### 2. Buat reward config `PROBABILITY`
|
||||
|
||||
`POST /api/v1/marketing/enakgame/games/:id/reward-configs`
|
||||
|
||||
```json
|
||||
{
|
||||
"reward_type": "PROBABILITY",
|
||||
"max_reward": 50,
|
||||
"rules": {
|
||||
"table": [
|
||||
{ "weight": 50, "amount": 0, "label": "Zonk" },
|
||||
{ "weight": 30, "amount": 3, "label": "3 Coin" },
|
||||
{ "weight": 15, "amount": 10, "label": "10 Coin" },
|
||||
{ "weight": 5, "amount": 50, "label": "Jackpot" }
|
||||
]
|
||||
},
|
||||
"reason": "Spin pertama"
|
||||
}
|
||||
```
|
||||
|
||||
- Satu baris `table` = satu segmen roda, urut searah gambar roda.
|
||||
- `weight` bilangan bulat ≥ 1. Peluang segmen = `weight` ÷ total weight (di atas: 50%,
|
||||
30%, 15%, 5%). Weight tidak pernah dikirim ke customer.
|
||||
- `amount` EnakCoin yang didapat (boleh 0). `label` opsional, maksimal 100 karakter,
|
||||
ditampilkan di roda.
|
||||
- `max_reward` minimal sebesar `amount` terbesar, kalau tidak hadiah besar terpotong.
|
||||
|
||||
### 3. Aktifkan config
|
||||
|
||||
`POST /api/v1/marketing/enakgame/reward-configs/:id/activate`
|
||||
|
||||
Mengganti hadiah nanti berarti membuat versi config baru lalu mengaktifkannya; session
|
||||
yang sedang berjalan tetap memakai versi saat dimulai.
|
||||
|
||||
### 4. Pastikan ada budget global bulan berjalan
|
||||
|
||||
`POST /api/v1/marketing/enakgame/budgets` dengan `scope: "GLOBAL"`, bila belum ada. Tanpa
|
||||
budget global, customer tidak bisa memulai game apa pun.
|
||||
|
||||
## Alur di Aplikasi Customer
|
||||
|
||||
1. `GET /api/v1/customer/enakgame/games`: game spin punya `prizes`, yaitu segmen roda
|
||||
(`entry`, `label`, `amount`) dalam urutan config. Gambar roda dari sini.
|
||||
2. `POST /api/v1/customer/enakgame/sessions` dengan `{"game_id": "…"}` dan header
|
||||
`Idempotency-Key`. Entry cost dipotong di sini.
|
||||
3. `POST /api/v1/customer/enakgame/sessions/:id/complete` dengan body `{}`. Server yang
|
||||
mengundi. Response berisi `prize` (`entry`, `label`, `amount`): putar roda sampai
|
||||
berhenti di segmen `entry` itu. `reward_total` adalah Coin yang benar-benar masuk,
|
||||
bisa lebih besar dari `prize.amount` karena event, atau lebih kecil karena limit
|
||||
harian (`limited_by`).
|
||||
|
||||
Aplikasi tidak boleh mengundi sendiri atau mengirim hadiah: apa pun yang dikirim selain
|
||||
data hasil diabaikan.
|
||||
@@ -367,23 +367,18 @@ Kurs per organisasi: `coin_amount` EnakCoin = `point_amount` EnakPoint (default
|
||||
|
||||
## 7. Game
|
||||
|
||||
`POST /api/v1/customer/spin` dengan `{ "spin_id": "<id game>" }`. Tanpa PIN.
|
||||
Game lama (`POST /api/v1/customer/spin`, `GET /customer/games`,
|
||||
`GET /customer/ferris-wheel`, dan admin `/marketing/games`, `/marketing/game-prizes`,
|
||||
`/marketing/rewards`) sudah dihapus. Semua game, termasuk spin, sekarang game EnakGame:
|
||||
|
||||
Setiap game memotong EnakCoin sebesar `metadata.coin_cost` game itu (default 1).
|
||||
Response:
|
||||
- Customer: `GET /api/v1/customer/enakgame/games`, lalu
|
||||
`POST /api/v1/customer/enakgame/sessions` (wajib `Idempotency-Key`, memotong
|
||||
`entry_cost` EnakCoin), lalu `POST /api/v1/customer/enakgame/sessions/:id/complete`
|
||||
(server menghitung hadiah EnakCoin). Tanpa PIN.
|
||||
- Dashboard: game dan biaya per main (`entry_cost`, bilangan bulat ≥ 1) diatur di
|
||||
`/marketing/enakgame/games`, hadiahnya di reward config.
|
||||
|
||||
```json
|
||||
{
|
||||
"game_play": { "id": "…", "game_id": "…", "coins_used": 1, "created_at": "…" },
|
||||
"prize_won": { "id": "…", "name": "Voucher 10rb", … },
|
||||
"coins_remaining": 7
|
||||
}
|
||||
```
|
||||
|
||||
EnakCoin kurang, game nonaktif, atau hadiah baru saja habis dijawab `304`; tidak ada
|
||||
EnakCoin yang terpotong.
|
||||
|
||||
Di dashboard, `metadata.coin_cost` diisi per game dengan bilangan bulat ≥ 1.
|
||||
Langkah admin dan alur aplikasi untuk spin ada di [`enakgame-spin.md`](enakgame-spin.md).
|
||||
|
||||
---
|
||||
|
||||
@@ -467,7 +462,8 @@ tanpa menyimpan)
|
||||
"end_of_month": false,
|
||||
"reminder_days": 7
|
||||
},
|
||||
"coin_expiry": { … sama … }
|
||||
"coin_expiry": { … sama … },
|
||||
"enakgame": { "user_daily_limit": 0, "global_daily_limit": 0 }
|
||||
}
|
||||
```
|
||||
|
||||
@@ -548,4 +544,5 @@ Riwayat perubahan: `GET /api/v1/marketing/loyalty-settings/history?page=1&limit=
|
||||
**Dashboard**
|
||||
- [ ] Tampilkan `point_cashback_percent`, `impact`, `expiry_preview`, dan
|
||||
`expiry_activations` sebelum owner menyimpan setting.
|
||||
- [ ] Isi `metadata.coin_cost` untuk setiap game.
|
||||
- [ ] Buat ulang game (termasuk spin) di `/marketing/enakgame/games` dengan `entry_cost`
|
||||
dan reward config ([`enakgame-spin.md`](enakgame-spin.md)).
|
||||
|
||||
@@ -116,7 +116,7 @@ Endpoint **tukar** dan **transfer** wajib header `Idempotency-Key` (string unik,
|
||||
| Tukar EnakCoin | `GET …/exchange/preview`, `POST /customer/wallet/exchange` | Ya |
|
||||
| Transfer | `GET …/transfer/recipient`, `POST /customer/wallet/transfer` | Ya |
|
||||
| PIN (buat, ganti, lupa) | `/customer/pin/*` | – |
|
||||
| Game | `POST /customer/spin` | – |
|
||||
| Game | `GET /customer/enakgame/games`, `POST /customer/enakgame/sessions`, `POST …/sessions/:id/complete` | – |
|
||||
| (latar belakang) registrasi push | `PUT` / `DELETE /customer/devices` | – |
|
||||
|
||||
---
|
||||
@@ -524,22 +524,20 @@ Penerima mendapat push `WALLET_TRANSFER_IN`.
|
||||
|
||||
## 8. Game (memakai EnakCoin)
|
||||
|
||||
`POST /api/v1/customer/spin` dengan `{ "spin_id": "<id game>" }`. Tanpa PIN.
|
||||
`POST /api/v1/customer/spin`, `GET /customer/games`, dan `GET /customer/ferris-wheel`
|
||||
sudah dihapus. Semua game, termasuk spin, dimainkan lewat EnakGame. Tanpa PIN.
|
||||
|
||||
```json
|
||||
{
|
||||
"game_play": { "id": "…", "game_id": "…", "coins_used": 1, "created_at": "…" },
|
||||
"prize_won": { "id": "…", "name": "Voucher 10rb" },
|
||||
"coins_remaining": 7
|
||||
}
|
||||
```
|
||||
1. `GET /api/v1/customer/enakgame/games`: daftar game dengan `entry_cost` (EnakCoin per
|
||||
main). Tampilkan biaya sebelum main, dan nonaktifkan tombol bila `coin_balance`
|
||||
kurang. Spin punya `prizes` untuk menggambar roda.
|
||||
2. `POST /api/v1/customer/enakgame/sessions` dengan `{ "game_id": "…" }` dan header
|
||||
`Idempotency-Key` (satu key per tap; retry memakai key yang sama). Response berisi
|
||||
`session_id` dan `coin_balance` setelah dipotong.
|
||||
3. `POST /api/v1/customer/enakgame/sessions/:id/complete` dengan hasil main (`score`
|
||||
atau `outcome`; spin cukup `{}`). Server yang menentukan hadiah: perbarui saldo dari
|
||||
`coin_balance`, tampilkan `reward_total`, dan untuk spin hentikan roda di `prize.entry`.
|
||||
|
||||
- Setiap game punya biaya sendiri: `metadata.coin_cost` pada data game dari
|
||||
`GET /api/v1/customer/games` (atau `GET /customer/ferris-wheel`), default 1 bila kosong.
|
||||
Tampilkan biaya sebelum main, dan nonaktifkan tombol bila `coin_balance` kurang.
|
||||
- `304`: EnakCoin kurang, game nonaktif, atau hadiah baru saja habis. Tidak ada
|
||||
EnakCoin yang terpotong; tampilkan pesan dan biarkan customer mencoba lagi.
|
||||
- Setelah main, perbarui saldo EnakCoin dari `coins_remaining`.
|
||||
Rincian spin ada di [`enakgame-spin.md`](./enakgame-spin.md).
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -385,6 +385,12 @@ beredar. Karena itu:
|
||||
|
||||
### F8 — Game Memakai EnakCoin
|
||||
|
||||
> **Diganti EnakGame (2026-10-07).** Alur game di bawah (`POST /customer/spin`,
|
||||
> `metadata.coin_cost`, `game_plays`) sudah dihapus. Game sekarang dimainkan lewat
|
||||
> `/customer/enakgame/sessions` dengan `games.entry_cost`; lihat
|
||||
> [RFC EnakGame](rfc-enakgame.md) §14 dan [enakgame-spin.md](enakgame-spin.md).
|
||||
> EnakCoin tetap mata uang untuk bermain game.
|
||||
|
||||
- **Semua jenis game** (`SPIN`, ferris wheel, `RAFFLE`, `MINIGAME`) memotong EnakCoin
|
||||
yang sama. `POST /customer/spin` memotong EnakCoin, bukan Token `SPIN`.
|
||||
- Biaya per main diatur per game di `games.metadata.coin_cost` (default 1), sehingga
|
||||
|
||||
+27
-2
@@ -804,6 +804,29 @@ membuat forecast = budget, lalu batasi dengan step maksimum dan min/max multipli
|
||||
§31). Rekomendasi ditampilkan ke admin. Bila disetujui, admin membuat **reward config
|
||||
versi baru** (§5.2). Tidak ada perubahan reward tanpa versi baru dan tanpa audit.
|
||||
|
||||
Implementasi (EG-901, EG-902):
|
||||
|
||||
- Hanya budget `GLOBAL` (yang membayar base reward). Budget `EVENT` ditolak; tambahan
|
||||
event diatur di event-nya.
|
||||
- Target = (budget − realized) / (forecast − realized), karena hanya biaya ke depan yang
|
||||
ikut berubah bila reward diubah. Target dibatasi ±step dari 1 lalu dibulatkan ke bawah
|
||||
ke dua desimal. Bisa turun **atau naik**.
|
||||
- Multiplier tiap game diukur terhadap **base**: versi terakhir yang ditulis admin.
|
||||
Versi buatan Budget Controller menyimpan `base_config_id`, `multiplier`, dan
|
||||
`budget_id` (migrasi 000112), dan aturannya selalu dihitung ulang dari base (dibulatkan
|
||||
ke bawah), jadi pembulatan tidak menumpuk. Min/max berlaku untuk multiplier kumulatif
|
||||
ini. Admin yang menulis versi baru memulai base baru di 1.
|
||||
- Cooldown per organisasi: setelah rekomendasi diterima, rekomendasi berikutnya baru bisa
|
||||
diterima setelah `cooldown_days`.
|
||||
- Guardrail disimpan di `game_budgets.thresholds` bersama warning/critical:
|
||||
`max_step_percent` (default 10), `min_multiplier_percent` (50),
|
||||
`max_multiplier_percent` (150), `cooldown_days` (7). Nilai default ini **sementara**,
|
||||
menunggu §19.2 #4.
|
||||
- Terima: `POST /budgets/:id/recommendation/accept` dengan `multiplier` yang dilihat
|
||||
admin. Rekomendasi dihitung ulang di dalam transaksi; bila berbeda, tidak ada yang
|
||||
berubah. Satu transaksi: versi lama `RETIRED`, versi baru langsung `ACTIVE`, audit
|
||||
`source = budget_controller` per config dan `RECOMMENDATION_ACCEPTED` di budget.
|
||||
|
||||
`GET` metrik cukup cepat untuk dashboard selama index di §5.7 ada. Bila nanti lambat,
|
||||
tambahkan snapshot harian, bukan cache yang di-invalidate.
|
||||
|
||||
@@ -833,7 +856,8 @@ Prefix `/enakgame` dipakai karena `/customer/games` sudah dipakai alur spin lama
|
||||
| Games | CRUD, `PUT /:id/status` |
|
||||
| Reward configs | `POST /games/:id/reward-configs` (versi baru), `POST /reward-configs/:id/activate`, `GET` daftar versi |
|
||||
| Events | CRUD, `PUT /:id/status` |
|
||||
| Budgets | CRUD, `GET /:id/metrics`, `GET /:id/recommendation` |
|
||||
| Budgets | CRUD, `GET /:id/metrics`, `GET /:id/recommendation`, `POST /:id/recommendation/accept` |
|
||||
| Analytics | `GET /analytics/games?from=&to=&game_id=`, `GET /analytics/economy?from=&to=` (tanggal Asia/Jakarta, maks 366 hari) |
|
||||
| Vouchers | CRUD, `POST /:id/codes` (impor CSV), `GET /:id/codes` |
|
||||
| Redemptions | `GET` list, `GET /:id` dengan atribusi cost |
|
||||
| Sessions | `GET` list + filter `flagged` |
|
||||
@@ -974,7 +998,8 @@ Dari PRD §43:
|
||||
1. **Pembulatan reward.** Usulan §8: bulatkan ke bawah, mengikuti K6.
|
||||
2. **Event stacking.** Sementara memakai default PRD §16.
|
||||
3. **Budget exhaustion policy**, untuk budget global dan budget event.
|
||||
4. **Threshold Budget Controller.**
|
||||
4. **Threshold Budget Controller.** Sementara memakai default di §10 (step 10%,
|
||||
multiplier 50%–150%, cooldown 7 hari), bisa diubah per budget.
|
||||
5. **Timeout reservasi voucher.** Dengan §7.4, hanya relevan untuk voucher eksternal.
|
||||
|
||||
Tidak ada yang memblokir langkah 1–7 di §17. Nomor 3 dan 4 harus diputuskan sebelum langkah
|
||||
|
||||
@@ -52,7 +52,6 @@ require (
|
||||
github.com/hashicorp/hcl v1.0.0 // indirect
|
||||
github.com/jackc/pgpassfile v1.0.0 // indirect
|
||||
github.com/jackc/pgservicefile v0.0.0-20221227161230-091c0ba34f0a // indirect
|
||||
github.com/jackc/pgx/v5 v5.3.0 // indirect
|
||||
github.com/jinzhu/inflection v1.0.0 // indirect
|
||||
github.com/jinzhu/now v1.1.5 // indirect
|
||||
github.com/jmespath/go-jmespath v0.4.0 // indirect
|
||||
@@ -110,6 +109,7 @@ require (
|
||||
github.com/aws/aws-sdk-go v1.55.7
|
||||
github.com/boombuler/barcode v1.1.0
|
||||
github.com/golang-jwt/jwt/v5 v5.2.3
|
||||
github.com/jackc/pgx/v5 v5.3.0
|
||||
github.com/redis/go-redis/v9 v9.19.0
|
||||
github.com/sirupsen/logrus v1.9.3
|
||||
github.com/stretchr/testify v1.10.0
|
||||
|
||||
+73
-29
@@ -34,6 +34,10 @@ type App struct {
|
||||
walletRecon *service.WalletReconciliationJob
|
||||
earningRetry *service.EarningBackfillJob
|
||||
walletExpiry *service.WalletExpiryJob
|
||||
gameSessions *service.GameSessionJob
|
||||
gameBudgets *service.GameBudgetPeriodJob
|
||||
voucherCodes *service.VoucherCodeExpiryJob
|
||||
voucherRecover *service.VoucherRedemptionRecoveryJob
|
||||
}
|
||||
|
||||
func NewApp(db *gorm.DB, redisClient *redis.Client) *App {
|
||||
@@ -67,6 +71,14 @@ func (a *App) Initialize(cfg *config.Config) error {
|
||||
// Expires balances whose time is up and reminds customers before (docs/prd-point-coin.md F12)
|
||||
a.walletExpiry = service.NewWalletExpiryJob(processor.NewWalletExpiryProcessor(
|
||||
repository.NewWalletExpiryRepository(a.db), processors.loyaltySettingsProcessor, processor.NewWalletProcessor(repos.walletRepo), repos.txManager, processors.customerDeviceProcessor))
|
||||
// Refunds or expires EnakGame sessions left open (docs/rfc-enakgame.md §7.3)
|
||||
a.gameSessions = service.NewGameSessionJob(processors.gameSessionProcessor)
|
||||
// Opens next month's global EnakGame budget (docs/rfc-enakgame.md §12)
|
||||
a.gameBudgets = service.NewGameBudgetPeriodJob(processors.gameBudgetProcessor)
|
||||
// Expires voucher codes past their date (docs/rfc-enakgame.md §12)
|
||||
a.voucherCodes = service.NewVoucherCodeExpiryJob(processors.voucherAdminProcessor)
|
||||
// Settles EXTERNAL voucher redemptions left PENDING (docs/rfc-enakgame.md §7.5)
|
||||
a.voucherRecover = service.NewVoucherRedemptionRecoveryJob(processors.voucherRedemptionProcessor)
|
||||
|
||||
services := a.initServices(processors, repos, cfg)
|
||||
validators := a.initValidators()
|
||||
@@ -137,14 +149,11 @@ func (a *App) Initialize(cfg *config.Config) error {
|
||||
validators.orderIngredientTransactionValidator,
|
||||
services.gamificationService,
|
||||
validators.gamificationValidator,
|
||||
services.rewardService,
|
||||
validators.rewardValidator,
|
||||
services.campaignService,
|
||||
validators.campaignValidator,
|
||||
services.customerAuthService,
|
||||
validators.customerAuthValidator,
|
||||
services.customerPointsService,
|
||||
services.spinGameService,
|
||||
middleware.customerAuthMiddleware,
|
||||
services.userDeviceService,
|
||||
validators.userDeviceValidator,
|
||||
@@ -165,6 +174,8 @@ func (a *App) Initialize(cfg *config.Config) error {
|
||||
services.customerDeviceService,
|
||||
services.customerOutletService,
|
||||
services.customerOrderService,
|
||||
services.enakGameAdminService,
|
||||
services.enakGameCustomerService,
|
||||
a.redisClient,
|
||||
)
|
||||
|
||||
@@ -185,6 +196,18 @@ func (a *App) Start(port string) error {
|
||||
if a.walletExpiry != nil {
|
||||
a.walletExpiry.Start(15 * time.Minute)
|
||||
}
|
||||
if a.gameSessions != nil {
|
||||
a.gameSessions.Start(time.Minute)
|
||||
}
|
||||
if a.gameBudgets != nil {
|
||||
a.gameBudgets.Start(24 * time.Hour)
|
||||
}
|
||||
if a.voucherCodes != nil {
|
||||
a.voucherCodes.Start(time.Hour)
|
||||
}
|
||||
if a.voucherRecover != nil {
|
||||
a.voucherRecover.Start(time.Minute)
|
||||
}
|
||||
|
||||
engine := a.router.Init()
|
||||
|
||||
@@ -233,6 +256,18 @@ func (a *App) Shutdown() {
|
||||
if a.walletExpiry != nil {
|
||||
a.walletExpiry.Stop()
|
||||
}
|
||||
if a.gameSessions != nil {
|
||||
a.gameSessions.Stop()
|
||||
}
|
||||
if a.gameBudgets != nil {
|
||||
a.gameBudgets.Stop()
|
||||
}
|
||||
if a.voucherCodes != nil {
|
||||
a.voucherCodes.Stop()
|
||||
}
|
||||
if a.voucherRecover != nil {
|
||||
a.voucherRecover.Stop()
|
||||
}
|
||||
close(a.shutdown)
|
||||
}
|
||||
|
||||
@@ -268,11 +303,7 @@ type repositories struct {
|
||||
accountRepo *repository.AccountRepositoryImpl
|
||||
orderIngredientTransactionRepo *repository.OrderIngredientTransactionRepositoryImpl
|
||||
tierRepo *repository.TierRepository
|
||||
gameRepo *repository.GameRepository
|
||||
gamePrizeRepo *repository.GamePrizeRepository
|
||||
gamePlayRepo repository.GamePlayRepository
|
||||
omsetTrackerRepo *repository.OmsetTrackerRepository
|
||||
rewardRepo repository.RewardRepository
|
||||
campaignRepo repository.CampaignRepository
|
||||
campaignRuleRepo repository.CampaignRuleRepository
|
||||
customerAuthRepo repository.CustomerAuthRepository
|
||||
@@ -324,11 +355,7 @@ func (a *App) initRepositories() *repositories {
|
||||
accountRepo: repository.NewAccountRepositoryImpl(a.db),
|
||||
orderIngredientTransactionRepo: repository.NewOrderIngredientTransactionRepositoryImpl(a.db).(*repository.OrderIngredientTransactionRepositoryImpl),
|
||||
tierRepo: repository.NewTierRepository(a.db),
|
||||
gameRepo: repository.NewGameRepository(a.db),
|
||||
gamePrizeRepo: repository.NewGamePrizeRepository(a.db),
|
||||
gamePlayRepo: repository.NewGamePlayRepository(a.db),
|
||||
omsetTrackerRepo: repository.NewOmsetTrackerRepository(a.db),
|
||||
rewardRepo: repository.NewRewardRepository(a.db),
|
||||
campaignRepo: repository.NewCampaignRepository(a.db),
|
||||
campaignRuleRepo: repository.NewCampaignRuleRepository(a.db),
|
||||
customerAuthRepo: repository.NewCustomerAuthRepository(a.db),
|
||||
@@ -375,11 +402,7 @@ type processors struct {
|
||||
accountProcessor *processor.AccountProcessorImpl
|
||||
orderIngredientTransactionProcessor *processor.OrderIngredientTransactionProcessorImpl
|
||||
tierProcessor *processor.TierProcessor
|
||||
gameProcessor *processor.GameProcessor
|
||||
gamePrizeProcessor *processor.GamePrizeProcessor
|
||||
gamePlayProcessor *processor.GamePlayProcessor
|
||||
omsetTrackerProcessor *processor.OmsetTrackerProcessor
|
||||
rewardProcessor processor.RewardProcessor
|
||||
campaignProcessor processor.CampaignProcessor
|
||||
campaignRuleProcessor processor.CampaignRuleProcessor
|
||||
customerAuthProcessor processor.CustomerAuthProcessor
|
||||
@@ -403,6 +426,11 @@ type processors struct {
|
||||
customerDeviceProcessor *processor.CustomerDeviceProcessor
|
||||
customerOutletProcessor *processor.CustomerOutletProcessor
|
||||
customerOrderProcessor *processor.CustomerOrderProcessor
|
||||
enakGameAdminProcessor *processor.EnakGameAdminProcessor
|
||||
gameBudgetProcessor *processor.GameBudgetProcessor
|
||||
gameSessionProcessor *processor.GameSessionProcessor
|
||||
voucherAdminProcessor *processor.VoucherAdminProcessor
|
||||
voucherRedemptionProcessor *processor.VoucherRedemptionProcessor
|
||||
}
|
||||
|
||||
func (a *App) initProcessors(cfg *config.Config, repos *repositories) *processors {
|
||||
@@ -418,6 +446,10 @@ func (a *App) initProcessors(cfg *config.Config, repos *repositories) *processor
|
||||
|
||||
orderProcessor := processor.NewOrderProcessorImpl(repos.orderRepo, repos.orderItemRepo, repos.paymentRepo, repos.paymentOrderItemRepo, repos.productRepo, repos.paymentMethodRepo, repos.inventoryRepo, repos.inventoryMovementRepo, repos.productVariantRepo, repos.outletRepo, repos.customerRepo, repos.txManager, repos.productRecipeRepo, repos.ingredientRepo, inventoryMovementService, repos.productOutletPriceRepo)
|
||||
loyaltySettingsProcessor := processor.NewLoyaltySettingsProcessor(repos.loyaltySettingsRepo, repos.txManager)
|
||||
auditLogger := processor.NewAuditLogger(repository.NewAuditLogRepository(a.db))
|
||||
enakGameRepo := repository.NewEnakGameRepository(a.db)
|
||||
gameBudgetRepo := repository.NewGameBudgetRepository(a.db)
|
||||
voucherRepo := repository.NewVoucherRepository(a.db)
|
||||
// Earn EnakPoint and EnakCoin when an order becomes fully paid (docs/prd-point-coin.md F3)
|
||||
earningProcessor := processor.NewEarningProcessor(repository.NewEarningRepository(a.db), loyaltySettingsProcessor, processor.NewWalletProcessor(repos.walletRepo), repos.txManager)
|
||||
orderProcessor.SetLoyalty(earningProcessor)
|
||||
@@ -453,15 +485,11 @@ func (a *App) initProcessors(cfg *config.Config, repos *repositories) *processor
|
||||
accountProcessor: processor.NewAccountProcessorImpl(repos.accountRepo, repos.chartOfAccountRepo),
|
||||
orderIngredientTransactionProcessor: processor.NewOrderIngredientTransactionProcessorImpl(repos.orderIngredientTransactionRepo, repos.productRecipeRepo, repos.ingredientRepo, repos.unitRepo).(*processor.OrderIngredientTransactionProcessorImpl),
|
||||
tierProcessor: processor.NewTierProcessor(repos.tierRepo),
|
||||
gameProcessor: processor.NewGameProcessor(repos.gameRepo),
|
||||
gamePrizeProcessor: processor.NewGamePrizeProcessor(repos.gamePrizeRepo),
|
||||
gamePlayProcessor: processor.NewGamePlayProcessor(repos.gamePlayRepo, repos.gameRepo, repos.gamePrizeRepo, processor.NewWalletProcessor(repos.walletRepo), repos.walletQueryRepo, repos.txManager),
|
||||
omsetTrackerProcessor: processor.NewOmsetTrackerProcessor(repos.omsetTrackerRepo),
|
||||
rewardProcessor: processor.NewRewardProcessor(repos.rewardRepo),
|
||||
campaignProcessor: processor.NewCampaignProcessor(repos.campaignRepo),
|
||||
campaignRuleProcessor: processor.NewCampaignRuleProcessor(repos.campaignRuleRepo),
|
||||
customerAuthProcessor: processor.NewCustomerAuthProcessor(repos.customerAuthRepo, otpProcessor, repos.otpRepo, cfg.GetCustomerJWTSecret(), cfg.GetCustomerJWTExpiresTTL()),
|
||||
customerPointsProcessor: processor.NewCustomerPointsProcessor(processor.NewWalletQueryProcessor(repos.walletQueryRepo, processor.NewLoyaltySettingsProcessor(repos.loyaltySettingsRepo, repos.txManager)), repos.gameRepo),
|
||||
customerPointsProcessor: processor.NewCustomerPointsProcessor(processor.NewWalletQueryProcessor(repos.walletQueryRepo, processor.NewLoyaltySettingsProcessor(repos.loyaltySettingsRepo, repos.txManager))),
|
||||
otpProcessor: otpProcessor,
|
||||
fileClient: fileClient,
|
||||
inventoryMovementService: inventoryMovementService,
|
||||
@@ -481,6 +509,17 @@ func (a *App) initProcessors(cfg *config.Config, repos *repositories) *processor
|
||||
customerOutletProcessor: processor.NewCustomerOutletProcessor(repository.NewCustomerOutletRepository(a.db), loyaltySettingsProcessor),
|
||||
customerOrderProcessor: processor.NewCustomerOrderProcessor(repository.NewCustomerOrderRepository(a.db), earningProcessor),
|
||||
walletAdminProcessor: processor.NewWalletAdminProcessor(repository.NewWalletAdminRepository(a.db), repos.walletQueryRepo, processor.NewWalletProcessor(repos.walletRepo), loyaltySettingsProcessor, repos.txManager),
|
||||
// EnakGame (docs/rfc-enakgame.md)
|
||||
enakGameAdminProcessor: processor.NewEnakGameAdminProcessor(enakGameRepo, auditLogger, repos.txManager),
|
||||
gameBudgetProcessor: processor.NewGameBudgetProcessor(gameBudgetRepo, auditLogger, repos.txManager),
|
||||
gameSessionProcessor: processor.NewGameSessionProcessor(repository.NewWalletMoveRepository(a.db), enakGameRepo,
|
||||
repository.NewGameSessionRepository(a.db), gameBudgetRepo, repository.NewGameEventRepository(a.db), repository.NewGameRewardCounterRepository(a.db), loyaltySettingsProcessor, repos.walletQueryRepo, processor.NewWalletProcessor(repos.walletRepo), auditLogger, repos.txManager),
|
||||
voucherAdminProcessor: processor.NewVoucherAdminProcessor(voucherRepo, auditLogger, repos.txManager),
|
||||
voucherRedemptionProcessor: processor.NewVoucherRedemptionProcessor(repository.NewWalletMoveRepository(a.db), voucherRepo,
|
||||
repository.NewVoucherRedemptionRepository(a.db), customerPinProcessor, repos.walletQueryRepo, processor.NewWalletProcessor(repos.walletRepo),
|
||||
// No provider has an adapter yet (EG-801): EXTERNAL vouchers stay out of the
|
||||
// catalog and cannot be redeemed until one is added here.
|
||||
processor.VoucherProviders{}, repos.txManager),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -513,11 +552,9 @@ type services struct {
|
||||
accountService service.AccountService
|
||||
orderIngredientTransactionService *service.OrderIngredientTransactionService
|
||||
gamificationService service.GamificationService
|
||||
rewardService service.RewardService
|
||||
campaignService service.CampaignService
|
||||
customerAuthService service.CustomerAuthService
|
||||
customerPointsService service.CustomerPointsService
|
||||
spinGameService service.SpinGameService
|
||||
userDeviceService service.UserDeviceService
|
||||
notificationService service.NotificationService
|
||||
productOutletPriceService service.ProductOutletPriceService
|
||||
@@ -530,6 +567,8 @@ type services struct {
|
||||
customerDeviceService *service.CustomerDeviceServiceImpl
|
||||
customerOutletService *service.CustomerOutletServiceImpl
|
||||
customerOrderService *service.CustomerOrderServiceImpl
|
||||
enakGameAdminService *service.EnakGameAdminServiceImpl
|
||||
enakGameCustomerService *service.EnakGameCustomerServiceImpl
|
||||
}
|
||||
|
||||
func (a *App) initServices(processors *processors, repos *repositories, cfg *config.Config) *services {
|
||||
@@ -544,6 +583,8 @@ func (a *App) initServices(processors *processors, repos *repositories, cfg *con
|
||||
inventoryService := service.NewInventoryService(processors.inventoryProcessor)
|
||||
orderService := service.NewOrderServiceImpl(processors.orderProcessor, repos.tableRepo, nil, processors.orderIngredientTransactionProcessor, *repos.productRecipeRepo, repos.txManager, repos.sessionRepo, processors.notificationProcessor, repos.userRepo) // Will be updated after orderIngredientTransactionService is created
|
||||
paymentMethodService := service.NewPaymentMethodService(processors.paymentMethodProcessor)
|
||||
enakGameAudit := processor.NewAuditLogger(repository.NewAuditLogRepository(a.db))
|
||||
gameBudgetMetrics := processor.NewGameBudgetMetricsProcessor(repository.NewGameBudgetRepository(a.db), repository.NewGameBudgetMetricsRepository(a.db))
|
||||
fileService := service.NewFileServiceImpl(processors.fileProcessor)
|
||||
var customerService service.CustomerService = service.NewCustomerService(processors.customerProcessor)
|
||||
analyticsService := service.NewAnalyticsServiceImpl(processors.analyticsProcessor)
|
||||
@@ -560,12 +601,10 @@ func (a *App) initServices(processors *processors, repos *repositories, cfg *con
|
||||
chartOfAccountService := service.NewChartOfAccountService(processors.chartOfAccountProcessor)
|
||||
accountService := service.NewAccountService(processors.accountProcessor)
|
||||
orderIngredientTransactionService := service.NewOrderIngredientTransactionService(processors.orderIngredientTransactionProcessor, repos.txManager)
|
||||
gamificationService := service.NewGamificationService(processors.tierProcessor, processors.gameProcessor, processors.gamePrizeProcessor, processors.gamePlayProcessor, processors.omsetTrackerProcessor)
|
||||
rewardService := service.NewRewardService(processors.rewardProcessor)
|
||||
gamificationService := service.NewGamificationService(processors.tierProcessor, processors.omsetTrackerProcessor)
|
||||
campaignService := service.NewCampaignService(processors.campaignProcessor, processors.campaignRuleProcessor)
|
||||
customerAuthService := service.NewCustomerAuthService(processors.customerAuthProcessor)
|
||||
customerPointsService := service.NewCustomerPointsService(processors.customerPointsProcessor)
|
||||
spinGameService := service.NewSpinGameService(processors.gamePlayProcessor)
|
||||
userDeviceService := service.NewUserDeviceService(processors.userDeviceProcessor)
|
||||
notificationService := service.NewNotificationService(processors.notificationProcessor)
|
||||
|
||||
@@ -601,11 +640,9 @@ func (a *App) initServices(processors *processors, repos *repositories, cfg *con
|
||||
accountService: accountService,
|
||||
orderIngredientTransactionService: orderIngredientTransactionService,
|
||||
gamificationService: gamificationService,
|
||||
rewardService: rewardService,
|
||||
campaignService: campaignService,
|
||||
customerAuthService: customerAuthService,
|
||||
customerPointsService: customerPointsService,
|
||||
spinGameService: spinGameService,
|
||||
userDeviceService: userDeviceService,
|
||||
notificationService: notificationService,
|
||||
productOutletPriceService: service.NewProductOutletPriceService(processors.productOutletPriceProcessor),
|
||||
@@ -618,6 +655,15 @@ func (a *App) initServices(processors *processors, repos *repositories, cfg *con
|
||||
customerDeviceService: service.NewCustomerDeviceService(processors.customerDeviceProcessor),
|
||||
customerOutletService: service.NewCustomerOutletService(processors.customerOutletProcessor),
|
||||
customerOrderService: service.NewCustomerOrderService(processors.customerOrderProcessor),
|
||||
enakGameAdminService: service.NewEnakGameAdminService(processors.enakGameAdminProcessor, processors.gameBudgetProcessor,
|
||||
gameBudgetMetrics,
|
||||
processor.NewGameBudgetControllerProcessor(repository.NewGameBudgetRepository(a.db), gameBudgetMetrics, repository.NewEnakGameRepository(a.db),
|
||||
enakGameAudit, repos.txManager),
|
||||
processor.NewGameEventProcessor(repository.NewGameEventRepository(a.db), repository.NewEnakGameRepository(a.db), repository.NewGameBudgetRepository(a.db),
|
||||
enakGameAudit, repos.txManager),
|
||||
processors.voucherAdminProcessor,
|
||||
processor.NewEnakGameAnalyticsProcessor(repository.NewEnakGameAnalyticsRepository(a.db))),
|
||||
enakGameCustomerService: service.NewEnakGameCustomerService(processors.gameSessionProcessor, processors.voucherRedemptionProcessor),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -655,7 +701,6 @@ type validators struct {
|
||||
accountValidator *validator.AccountValidatorImpl
|
||||
orderIngredientTransactionValidator *validator.OrderIngredientTransactionValidatorImpl
|
||||
gamificationValidator *validator.GamificationValidatorImpl
|
||||
rewardValidator validator.RewardValidator
|
||||
campaignValidator validator.CampaignValidator
|
||||
customerAuthValidator validator.CustomerAuthValidator
|
||||
userDeviceValidator *validator.UserDeviceValidatorImpl
|
||||
@@ -689,7 +734,6 @@ func (a *App) initValidators() *validators {
|
||||
accountValidator: validator.NewAccountValidator().(*validator.AccountValidatorImpl),
|
||||
orderIngredientTransactionValidator: validator.NewOrderIngredientTransactionValidator().(*validator.OrderIngredientTransactionValidatorImpl),
|
||||
gamificationValidator: validator.NewGamificationValidator(),
|
||||
rewardValidator: validator.NewRewardValidator(),
|
||||
campaignValidator: validator.NewCampaignValidator(),
|
||||
customerAuthValidator: validator.NewCustomerAuthValidator(),
|
||||
userDeviceValidator: validator.NewUserDeviceValidator(),
|
||||
|
||||
@@ -0,0 +1,178 @@
|
||||
package constants
|
||||
|
||||
// EnakGame values (docs/rfc-enakgame.md §5). Each set matches a CHECK in the
|
||||
// migrations.
|
||||
|
||||
// games.status.
|
||||
const (
|
||||
GameStatusDraft = "DRAFT"
|
||||
GameStatusActive = "ACTIVE"
|
||||
GameStatusInactive = "INACTIVE"
|
||||
// The old games, and games taken out of EnakGame for good. Never changed again.
|
||||
GameStatusArchived = "ARCHIVED"
|
||||
)
|
||||
|
||||
// game_reward_configs.reward_type (§8).
|
||||
const (
|
||||
GameRewardTypeFixed = "FIXED"
|
||||
GameRewardTypeScoreBased = "SCORE_BASED"
|
||||
GameRewardTypeOutcomeBased = "OUTCOME_BASED"
|
||||
GameRewardTypeProbability = "PROBABILITY"
|
||||
)
|
||||
|
||||
// game_reward_configs.status. Only status ever changes on a config (D7).
|
||||
const (
|
||||
GameRewardConfigStatusDraft = "DRAFT"
|
||||
GameRewardConfigStatusActive = "ACTIVE"
|
||||
GameRewardConfigStatusRetired = "RETIRED"
|
||||
)
|
||||
|
||||
// game_sessions.status: STARTED → COMPLETED | REFUNDED | EXPIRED (D4).
|
||||
const (
|
||||
GameSessionStatusStarted = "STARTED"
|
||||
GameSessionStatusCompleted = "COMPLETED"
|
||||
GameSessionStatusRefunded = "REFUNDED"
|
||||
GameSessionStatusExpired = "EXPIRED"
|
||||
)
|
||||
|
||||
// game_sessions.refund_reason (§7.3).
|
||||
const (
|
||||
GameSessionRefundSystemError = "SYSTEM_ERROR"
|
||||
GameSessionRefundGameDeactivated = "GAME_DEACTIVATED"
|
||||
)
|
||||
|
||||
// game_budgets.scope (§5.6).
|
||||
const (
|
||||
GameBudgetScopeGlobal = "GLOBAL"
|
||||
GameBudgetScopeEvent = "EVENT"
|
||||
)
|
||||
|
||||
// audit_logs.actor_type (§5.9).
|
||||
const (
|
||||
AuditActorUser = "USER"
|
||||
AuditActorSystem = "SYSTEM"
|
||||
)
|
||||
|
||||
// audit_logs.source: where a change came from.
|
||||
const (
|
||||
AuditSourceAdminAPI = "admin_api"
|
||||
AuditSourceBudgetController = "budget_controller"
|
||||
AuditSourceSessionJob = "session_job"
|
||||
AuditSourceBudgetPeriodJob = "budget_period_job"
|
||||
AuditSourceCustomerAPI = "customer_api"
|
||||
)
|
||||
|
||||
// audit_logs.entity_type: what an audit row is about (§13).
|
||||
const (
|
||||
AuditEntityGame = "GAME"
|
||||
AuditEntityGameRewardConfig = "GAME_REWARD_CONFIG"
|
||||
AuditEntityGameBudget = "GAME_BUDGET"
|
||||
AuditEntityGameEvent = "GAME_EVENT"
|
||||
AuditEntityGameSession = "GAME_SESSION"
|
||||
AuditEntityVoucher = "VOUCHER"
|
||||
)
|
||||
|
||||
// audit_logs.action on a GAME_BUDGET whose recommendation was accepted.
|
||||
const AuditActionRecommendationAccepted = "RECOMMENDATION_ACCEPTED"
|
||||
|
||||
// game_reward_counters.scope_type: what an Economy Guard counter counts for (§5.8).
|
||||
const (
|
||||
GameRewardScopeUser = "USER"
|
||||
GameRewardScopeGame = "GAME"
|
||||
GameRewardScopeEvent = "EVENT"
|
||||
GameRewardScopeGlobal = "GLOBAL"
|
||||
)
|
||||
|
||||
// vouchers.voucher_type (§5.7).
|
||||
const (
|
||||
VoucherTypeFixedValue = "FIXED_VALUE"
|
||||
VoucherTypePercentage = "PERCENTAGE"
|
||||
VoucherTypeFreeItem = "FREE_ITEM"
|
||||
VoucherTypeMerchantBenefit = "MERCHANT_BENEFIT"
|
||||
)
|
||||
|
||||
// vouchers.stock_mode: where a redemption's voucher comes from.
|
||||
const (
|
||||
// A counted stock with nothing to hand out but the redemption itself.
|
||||
VoucherStockStatic = "STATIC"
|
||||
// One imported code per redemption.
|
||||
VoucherStockCodePool = "CODE_POOL"
|
||||
// Issued by a provider (§7.5), not before EG-801.
|
||||
VoucherStockExternal = "EXTERNAL"
|
||||
)
|
||||
|
||||
// vouchers.status.
|
||||
const (
|
||||
VoucherStatusDraft = "DRAFT"
|
||||
VoucherStatusActive = "ACTIVE"
|
||||
VoucherStatusInactive = "INACTIVE"
|
||||
VoucherStatusArchived = "ARCHIVED"
|
||||
)
|
||||
|
||||
// voucher_codes.status.
|
||||
const (
|
||||
VoucherCodeAvailable = "AVAILABLE"
|
||||
VoucherCodeReserved = "RESERVED"
|
||||
VoucherCodeRedeemed = "REDEEMED"
|
||||
VoucherCodeExpired = "EXPIRED"
|
||||
VoucherCodeCancelled = "CANCELLED"
|
||||
)
|
||||
|
||||
// voucher_redemptions.status.
|
||||
const (
|
||||
VoucherRedemptionPending = "PENDING"
|
||||
VoucherRedemptionCompleted = "COMPLETED"
|
||||
VoucherRedemptionFailed = "FAILED"
|
||||
)
|
||||
|
||||
// Budget statuses (PRD §32), from its utilization and forecast against its thresholds.
|
||||
const (
|
||||
GameBudgetHealthy = "HEALTHY"
|
||||
GameBudgetWarning = "WARNING"
|
||||
GameBudgetCritical = "CRITICAL"
|
||||
GameBudgetExhausted = "EXHAUSTED"
|
||||
)
|
||||
|
||||
// Thresholds of a budget that sets none, in percent (PRD §8). Pending RFC §19.2 #4.
|
||||
const (
|
||||
GameBudgetWarningDefault = int64(70)
|
||||
GameBudgetCriticalDefault = int64(90)
|
||||
)
|
||||
|
||||
// game_events.status. An ACTIVE event changes rewards only between its start_at and
|
||||
// end_at.
|
||||
const (
|
||||
GameEventStatusDraft = "DRAFT"
|
||||
GameEventStatusActive = "ACTIVE"
|
||||
GameEventStatusEnded = "ENDED"
|
||||
GameEventStatusCancelled = "CANCELLED"
|
||||
)
|
||||
|
||||
// Budget Controller guardrails of a budget that sets none (PRD §31). Pending RFC
|
||||
// §19.2 #4.
|
||||
const (
|
||||
// Percent a recommendation may move rewards by, either way.
|
||||
GameBudgetMaxStepDefault = int64(10)
|
||||
// Bounds of a game's multiplier, in percent of the configuration its admin wrote.
|
||||
GameBudgetMinMultiplierDefault = int64(50)
|
||||
GameBudgetMaxMultiplierDefault = int64(150)
|
||||
// Days after an accepted recommendation before the next one, in the organization.
|
||||
// The same as the forecast window, so the next one sees the effect of the last.
|
||||
GameBudgetCooldownDaysDefault = int64(7)
|
||||
)
|
||||
|
||||
// What a Budget Controller recommendation says (docs/rfc-enakgame.md §10). Only
|
||||
// RECOMMENDED can be accepted.
|
||||
const (
|
||||
GameBudgetRecommended = "RECOMMENDED"
|
||||
// The forecast meets the budget closely enough that rewards stay.
|
||||
GameBudgetRecommendationNoChange = "NO_CHANGE"
|
||||
// The last accepted recommendation of the organization is too recent.
|
||||
GameBudgetRecommendationCooldown = "COOLDOWN"
|
||||
// Every game is already at its min or max multiplier.
|
||||
GameBudgetRecommendationAtLimit = "AT_LIMIT"
|
||||
// No cost in the forecast window to extrapolate from.
|
||||
GameBudgetRecommendationNoData = "INSUFFICIENT_DATA"
|
||||
// The budget's period has not started or has no day left after today.
|
||||
GameBudgetRecommendationOutOfPeriod = "OUT_OF_PERIOD"
|
||||
)
|
||||
@@ -53,15 +53,10 @@ const (
|
||||
// Gamification entities
|
||||
CustomerPointsEntity = "customer_points"
|
||||
TierEntity = "tier"
|
||||
GameEntity = "game"
|
||||
GamePrizeEntity = "game_prize"
|
||||
GamePlayEntity = "game_play"
|
||||
OmsetTrackerEntity = "omset_tracker"
|
||||
RewardEntity = "reward"
|
||||
CampaignEntity = "campaign"
|
||||
CampaignRuleEntity = "campaign_rule"
|
||||
CustomerEntity = "customer"
|
||||
SpinGameHandlerEntity = "spin_game_handler"
|
||||
UserDeviceServiceEntity = "user_device_service"
|
||||
NotificationServiceEntity = "notification_service"
|
||||
NotificationHandlerEntity = "notification_handler"
|
||||
@@ -69,6 +64,7 @@ const (
|
||||
ExpenseServiceEntity = "expense_service"
|
||||
CashAdvanceServiceEntity = "cash_advance_service"
|
||||
WalletServiceEntity = "wallet_service"
|
||||
EnakGameServiceEntity = "enakgame_service"
|
||||
LoyaltySettingsServiceEntity = "loyalty_settings_service"
|
||||
CustomerPinServiceEntity = "customer_pin_service"
|
||||
)
|
||||
|
||||
@@ -47,6 +47,13 @@ const (
|
||||
LoyaltyExpiryGraceMonthsSuffix = "expiry_grace_months"
|
||||
)
|
||||
|
||||
// Per organization: EnakGame reward limits (docs/rfc-enakgame.md §5.10). 0 means no
|
||||
// limit. A reward over a limit is cut to what is left of it (§9).
|
||||
const (
|
||||
EnakGameLimitUserDailyKey = "enakgame.limit.user_daily"
|
||||
EnakGameLimitGlobalDailyKey = "enakgame.limit.global_daily"
|
||||
)
|
||||
|
||||
// Modes of loyalty.{point,coin}.earn_mode.
|
||||
const (
|
||||
// earn_value for every earn_per_amount rupiah of the basis.
|
||||
|
||||
@@ -25,6 +25,11 @@ const (
|
||||
WalletTxTypeAdjustment = "ADJUSTMENT"
|
||||
WalletTxTypeMigration = "MIGRATION"
|
||||
WalletTxTypeRewardRedeem = "REWARD_REDEEM"
|
||||
|
||||
// EnakGame (docs/rfc-enakgame.md §6.1).
|
||||
WalletTxTypeGameSpendRefund = "GAME_SPEND_REFUND"
|
||||
WalletTxTypeGameReward = "GAME_REWARD"
|
||||
WalletTxTypeRewardRedeemRefund = "REWARD_REDEEM_REFUND"
|
||||
)
|
||||
|
||||
// What a ledger row's reference_id points at: where the value came from for a
|
||||
@@ -38,4 +43,5 @@ const (
|
||||
WalletRefTypeLegacyPoints = "LEGACY_POINTS"
|
||||
WalletRefTypeLegacyTokens = "LEGACY_TOKENS"
|
||||
WalletRefTypeRewardRedemption = "REWARD_REDEMPTION"
|
||||
WalletRefTypeGameSession = "GAME_SESSION"
|
||||
)
|
||||
|
||||
@@ -1,60 +0,0 @@
|
||||
package contract
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// Request Contracts
|
||||
type GetCustomerGamesRequest struct {
|
||||
// No additional fields needed - customer ID comes from JWT token
|
||||
}
|
||||
|
||||
// Response Contracts
|
||||
type GetCustomerGamesResponse struct {
|
||||
Status string `json:"status"`
|
||||
Message string `json:"message"`
|
||||
Data *GetCustomerGamesResponseData `json:"data,omitempty"`
|
||||
}
|
||||
|
||||
type GetCustomerGamesResponseData struct {
|
||||
Games []CustomerGameResponse `json:"games"`
|
||||
}
|
||||
|
||||
type CustomerGameResponse struct {
|
||||
ID uuid.UUID `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Type string `json:"type"`
|
||||
IsActive bool `json:"is_active"`
|
||||
Metadata *map[string]interface{} `json:"metadata,omitempty"`
|
||||
Prizes []CustomerGamePrizeResponse `json:"prizes,omitempty"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
type CustomerGamePrizeResponse struct {
|
||||
ID uuid.UUID `json:"id"`
|
||||
GameID uuid.UUID `json:"game_id"`
|
||||
Name string `json:"name"`
|
||||
Image *string `json:"image,omitempty"`
|
||||
Metadata *map[string]interface{} `json:"metadata,omitempty"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
// Ferris Wheel Game Contracts
|
||||
type GetFerrisWheelGameRequest struct {
|
||||
// No additional fields needed - customer ID comes from JWT token
|
||||
}
|
||||
|
||||
type GetFerrisWheelGameResponse struct {
|
||||
Status string `json:"status"`
|
||||
Message string `json:"message"`
|
||||
Data *GetFerrisWheelGameResponseData `json:"data,omitempty"`
|
||||
}
|
||||
|
||||
type GetFerrisWheelGameResponseData struct {
|
||||
Game CustomerGameResponse `json:"game"`
|
||||
Prizes []CustomerGamePrizeResponse `json:"prizes"`
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package contract
|
||||
|
||||
import "github.com/google/uuid"
|
||||
|
||||
// StartGameSessionRequest is POST /customer/enakgame/sessions (docs/rfc-enakgame.md
|
||||
// §7.1). The Idempotency-Key header is required.
|
||||
type StartGameSessionRequest struct {
|
||||
GameID uuid.UUID `json:"game_id" binding:"required"`
|
||||
}
|
||||
|
||||
// RedeemVoucherRequest is POST /customer/enakgame/vouchers/:id/redeem (§7.4). The
|
||||
// Idempotency-Key header is required.
|
||||
type RedeemVoucherRequest struct {
|
||||
Pin string `json:"pin" binding:"required"`
|
||||
}
|
||||
@@ -1,49 +0,0 @@
|
||||
package contract
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
type CreateGameRequest struct {
|
||||
Name string `json:"name" validate:"required"`
|
||||
Type string `json:"type" validate:"required,oneof=SPIN RAFFLE MINIGAME"`
|
||||
IsActive bool `json:"is_active"`
|
||||
Metadata map[string]interface{} `json:"metadata"`
|
||||
}
|
||||
|
||||
type UpdateGameRequest struct {
|
||||
Name *string `json:"name,omitempty" validate:"omitempty,required"`
|
||||
Type *string `json:"type,omitempty" validate:"omitempty,oneof=SPIN RAFFLE MINIGAME"`
|
||||
IsActive *bool `json:"is_active,omitempty"`
|
||||
Metadata map[string]interface{} `json:"metadata,omitempty"`
|
||||
}
|
||||
|
||||
type GameResponse struct {
|
||||
ID uuid.UUID `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Type string `json:"type"`
|
||||
IsActive bool `json:"is_active"`
|
||||
Metadata map[string]interface{} `json:"metadata"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
type ListGamesRequest struct {
|
||||
Page int `json:"page" form:"page" validate:"min=1"`
|
||||
Limit int `json:"limit" form:"limit" validate:"min=1,max=100"`
|
||||
Search string `json:"search" form:"search"`
|
||||
Type string `json:"type" form:"type" validate:"omitempty,oneof=SPIN RAFFLE MINIGAME"`
|
||||
IsActive *bool `json:"is_active" form:"is_active"`
|
||||
SortBy string `json:"sort_by" form:"sort_by" validate:"omitempty,oneof=name type created_at updated_at"`
|
||||
SortOrder string `json:"sort_order" form:"sort_order" validate:"omitempty,oneof=asc desc"`
|
||||
}
|
||||
|
||||
type PaginatedGamesResponse struct {
|
||||
Data []GameResponse `json:"data"`
|
||||
TotalCount int `json:"total_count"`
|
||||
Page int `json:"page"`
|
||||
Limit int `json:"limit"`
|
||||
TotalPages int `json:"total_pages"`
|
||||
}
|
||||
@@ -1,59 +0,0 @@
|
||||
package contract
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
type CreateGamePlayRequest struct {
|
||||
GameID uuid.UUID `json:"game_id" validate:"required"`
|
||||
CustomerID uuid.UUID `json:"customer_id" validate:"required"`
|
||||
CoinsUsed int `json:"coins_used" validate:"min=0"`
|
||||
RandomSeed *string `json:"random_seed,omitempty"`
|
||||
}
|
||||
|
||||
type GamePlayResponse struct {
|
||||
ID uuid.UUID `json:"id"`
|
||||
GameID uuid.UUID `json:"game_id"`
|
||||
CustomerID uuid.UUID `json:"customer_id"`
|
||||
PrizeID *uuid.UUID `json:"prize_id,omitempty"`
|
||||
CoinsUsed int `json:"coins_used"`
|
||||
RandomSeed *string `json:"random_seed,omitempty"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
Game *GameResponse `json:"game,omitempty"`
|
||||
Customer *CustomerResponse `json:"customer,omitempty"`
|
||||
Prize *GamePrizeResponse `json:"prize,omitempty"`
|
||||
}
|
||||
|
||||
type ListGamePlaysRequest struct {
|
||||
Page int `json:"page" validate:"min=1"`
|
||||
Limit int `json:"limit" validate:"min=1,max=100"`
|
||||
Search string `json:"search"`
|
||||
GameID *uuid.UUID `json:"game_id"`
|
||||
CustomerID *uuid.UUID `json:"customer_id"`
|
||||
PrizeID *uuid.UUID `json:"prize_id"`
|
||||
SortBy string `json:"sort_by" validate:"omitempty,oneof=created_at coins_used"`
|
||||
SortOrder string `json:"sort_order" validate:"omitempty,oneof=asc desc"`
|
||||
}
|
||||
|
||||
type PaginatedGamePlaysResponse struct {
|
||||
Data []GamePlayResponse `json:"data"`
|
||||
TotalCount int `json:"total_count"`
|
||||
Page int `json:"page"`
|
||||
Limit int `json:"limit"`
|
||||
TotalPages int `json:"total_pages"`
|
||||
}
|
||||
|
||||
// PlayGameRequest plays a game for a customer. What it costs is the game's
|
||||
// metadata.coin_cost (docs/prd-point-coin.md F8), never the caller's choice.
|
||||
type PlayGameRequest struct {
|
||||
GameID uuid.UUID `json:"game_id" validate:"required"`
|
||||
CustomerID uuid.UUID `json:"customer_id" validate:"required"`
|
||||
}
|
||||
|
||||
type PlayGameResponse struct {
|
||||
GamePlay GamePlayResponse `json:"game_play"`
|
||||
PrizeWon *GamePrizeResponse `json:"prize_won,omitempty"`
|
||||
CoinsRemaining int64 `json:"coins_remaining"`
|
||||
}
|
||||
@@ -1,64 +0,0 @@
|
||||
package contract
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
type CreateGamePrizeRequest struct {
|
||||
GameID uuid.UUID `json:"game_id" validate:"required"`
|
||||
Name string `json:"name" validate:"required"`
|
||||
Weight int `json:"weight" validate:"min=1"`
|
||||
Stock int `json:"stock" validate:"min=0"`
|
||||
MaxStock *int `json:"max_stock,omitempty"`
|
||||
Threshold *int64 `json:"threshold,omitempty"`
|
||||
FallbackPrizeID *uuid.UUID `json:"fallback_prize_id,omitempty"`
|
||||
Image *string `json:"image,omitempty" validate:"omitempty,max=500"`
|
||||
Metadata map[string]interface{} `json:"metadata"`
|
||||
}
|
||||
|
||||
type UpdateGamePrizeRequest struct {
|
||||
Name *string `json:"name,omitempty" validate:"omitempty,required"`
|
||||
Weight *int `json:"weight,omitempty" validate:"omitempty,min=1"`
|
||||
Stock *int `json:"stock,omitempty" validate:"omitempty,min=0"`
|
||||
MaxStock *int `json:"max_stock,omitempty"`
|
||||
Threshold *int64 `json:"threshold,omitempty"`
|
||||
FallbackPrizeID *uuid.UUID `json:"fallback_prize_id,omitempty"`
|
||||
Image *string `json:"image,omitempty" validate:"omitempty,max=500"`
|
||||
Metadata map[string]interface{} `json:"metadata,omitempty"`
|
||||
}
|
||||
|
||||
type GamePrizeResponse struct {
|
||||
ID uuid.UUID `json:"id"`
|
||||
GameID uuid.UUID `json:"game_id"`
|
||||
Name string `json:"name"`
|
||||
Weight int `json:"weight"`
|
||||
Stock int `json:"stock"`
|
||||
MaxStock *int `json:"max_stock,omitempty"`
|
||||
Threshold *int64 `json:"threshold,omitempty"`
|
||||
FallbackPrizeID *uuid.UUID `json:"fallback_prize_id,omitempty"`
|
||||
Image *string `json:"image,omitempty"`
|
||||
Metadata map[string]interface{} `json:"metadata"`
|
||||
Game *GameResponse `json:"game,omitempty"`
|
||||
FallbackPrize *GamePrizeResponse `json:"fallback_prize,omitempty"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
type ListGamePrizesRequest struct {
|
||||
Page int `json:"page" form:"page" validate:"min=1"`
|
||||
Limit int `json:"limit" form:"limit" validate:"min=1,max=100"`
|
||||
Search string `json:"search" form:"search"`
|
||||
GameID *uuid.UUID `json:"game_id" form:"game_id"`
|
||||
SortBy string `json:"sort_by" form:"sort_by" validate:"omitempty,oneof=name weight stock created_at updated_at"`
|
||||
SortOrder string `json:"sort_order" form:"sort_order" validate:"omitempty,oneof=asc desc"`
|
||||
}
|
||||
|
||||
type PaginatedGamePrizesResponse struct {
|
||||
Data []GamePrizeResponse `json:"data"`
|
||||
TotalCount int `json:"total_count"`
|
||||
Page int `json:"page"`
|
||||
Limit int `json:"limit"`
|
||||
TotalPages int `json:"total_pages"`
|
||||
}
|
||||
@@ -27,15 +27,14 @@ type AddOmsetRequest struct {
|
||||
}
|
||||
|
||||
type OmsetTrackerResponse struct {
|
||||
ID uuid.UUID `json:"id"`
|
||||
PeriodType string `json:"period_type"`
|
||||
PeriodStart time.Time `json:"period_start"`
|
||||
PeriodEnd time.Time `json:"period_end"`
|
||||
Total int64 `json:"total"`
|
||||
GameID *uuid.UUID `json:"game_id,omitempty"`
|
||||
Game *GameResponse `json:"game,omitempty"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
ID uuid.UUID `json:"id"`
|
||||
PeriodType string `json:"period_type"`
|
||||
PeriodStart time.Time `json:"period_start"`
|
||||
PeriodEnd time.Time `json:"period_end"`
|
||||
Total int64 `json:"total"`
|
||||
GameID *uuid.UUID `json:"game_id,omitempty"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
type ListOmsetTrackerRequest struct {
|
||||
|
||||
@@ -1,82 +0,0 @@
|
||||
package contract
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// Request Contracts
|
||||
type CreateRewardRequest struct {
|
||||
Name string `json:"name" binding:"required,min=1,max=150"`
|
||||
RewardType string `json:"reward_type" binding:"required,oneof=VOUCHER PHYSICAL DIGITAL"`
|
||||
CostPoints int64 `json:"cost_points" binding:"required,min=1"`
|
||||
Stock *int `json:"stock,omitempty"`
|
||||
MaxPerCustomer int `json:"max_per_customer" binding:"min=1"`
|
||||
Tnc *TermsAndConditionsStruct `json:"tnc,omitempty"`
|
||||
Metadata *map[string]interface{} `json:"metadata,omitempty"`
|
||||
Images *[]string `json:"images,omitempty"`
|
||||
}
|
||||
|
||||
type UpdateRewardRequest struct {
|
||||
ID uuid.UUID `json:"id" binding:"required"`
|
||||
Name string `json:"name" binding:"required,min=1,max=150"`
|
||||
RewardType string `json:"reward_type" binding:"required,oneof=VOUCHER PHYSICAL DIGITAL BALANCE"`
|
||||
CostPoints int64 `json:"cost_points" binding:"required,min=1"`
|
||||
Stock *int `json:"stock,omitempty"`
|
||||
MaxPerCustomer int `json:"max_per_customer" binding:"min=1"`
|
||||
Tnc *TermsAndConditionsStruct `json:"tnc,omitempty"`
|
||||
Metadata *map[string]interface{} `json:"metadata,omitempty"`
|
||||
Images *[]string `json:"images,omitempty"`
|
||||
}
|
||||
|
||||
type ListRewardsRequest struct {
|
||||
Page int `form:"page" binding:"min=1"`
|
||||
Limit int `form:"limit" binding:"min=1,max=100"`
|
||||
Search string `form:"search"`
|
||||
RewardType string `form:"reward_type"`
|
||||
MinPoints *int64 `form:"min_points"`
|
||||
MaxPoints *int64 `form:"max_points"`
|
||||
HasStock *bool `form:"has_stock"`
|
||||
}
|
||||
|
||||
type GetRewardRequest struct {
|
||||
ID uuid.UUID `uri:"id" binding:"required"`
|
||||
}
|
||||
|
||||
type DeleteRewardRequest struct {
|
||||
ID uuid.UUID `uri:"id" binding:"required"`
|
||||
}
|
||||
|
||||
// Response Contracts
|
||||
type RewardResponse struct {
|
||||
ID uuid.UUID `json:"id"`
|
||||
Name string `json:"name"`
|
||||
RewardType string `json:"reward_type"`
|
||||
CostPoints int64 `json:"cost_points"`
|
||||
Stock *int `json:"stock,omitempty"`
|
||||
MaxPerCustomer int `json:"max_per_customer"`
|
||||
Tnc *TermsAndConditionsStruct `json:"tnc,omitempty"`
|
||||
Metadata *map[string]interface{} `json:"metadata,omitempty"`
|
||||
Images *[]string `json:"images,omitempty"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
type ListRewardsResponse struct {
|
||||
Rewards []RewardResponse `json:"rewards"`
|
||||
Total int64 `json:"total"`
|
||||
Page int `json:"page"`
|
||||
Limit int `json:"limit"`
|
||||
}
|
||||
|
||||
// Helper structs
|
||||
type TermsAndConditionsStruct struct {
|
||||
Sections []TncSectionStruct `json:"sections"`
|
||||
ExpiryDays int `json:"expiry_days"`
|
||||
}
|
||||
|
||||
type TncSectionStruct struct {
|
||||
Title string `json:"title"`
|
||||
Rules []string `json:"rules"`
|
||||
}
|
||||
@@ -1,20 +0,0 @@
|
||||
package contract
|
||||
|
||||
// SpinGameRequest represents the request to play a spin game
|
||||
type SpinGameRequest struct {
|
||||
SpinID string `json:"spin_id" validate:"required,uuid"`
|
||||
}
|
||||
|
||||
// SpinGameResponse represents the response from playing a spin game
|
||||
type SpinGameResponse struct {
|
||||
Status string `json:"status"`
|
||||
Message string `json:"message"`
|
||||
Data *SpinGameResponseData `json:"data,omitempty"`
|
||||
}
|
||||
|
||||
// SpinGameResponseData contains the game play result
|
||||
type SpinGameResponseData struct {
|
||||
GamePlay GamePlayResponse `json:"game_play"`
|
||||
PrizeWon *CustomerGamePrizeResponse `json:"prize_won,omitempty"`
|
||||
CoinsRemaining int64 `json:"coins_remaining"`
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package entities
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// AuditLog is one change to EnakGame configuration or state: who made it, to what,
|
||||
// from what, to what (docs/rfc-enakgame.md §5.9, §13). Append-only.
|
||||
type AuditLog struct {
|
||||
ID uuid.UUID
|
||||
OrganizationID uuid.UUID
|
||||
// USER or SYSTEM.
|
||||
ActorType string
|
||||
// The admin for USER; nil for SYSTEM.
|
||||
ActorID *uuid.UUID
|
||||
EntityType string
|
||||
EntityID uuid.UUID
|
||||
Action string
|
||||
// JSON snapshots of the entity; nil when there was nothing before (a create) or
|
||||
// after (a delete).
|
||||
Before json.RawMessage
|
||||
After json.RawMessage
|
||||
Reason *string
|
||||
// admin_api, budget_controller, session_job, ...
|
||||
Source string
|
||||
CreatedAt time.Time
|
||||
}
|
||||
@@ -0,0 +1,202 @@
|
||||
package entities
|
||||
|
||||
import (
|
||||
"database/sql/driver"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// JSONDocument is a JSONB column kept as raw JSON, for documents whose shape depends
|
||||
// on another column or is only read back as a whole. Empty is SQL NULL.
|
||||
type JSONDocument json.RawMessage
|
||||
|
||||
func (d JSONDocument) Value() (driver.Value, error) {
|
||||
if len(d) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
return string(d), nil
|
||||
}
|
||||
|
||||
func (d *JSONDocument) Scan(value interface{}) error {
|
||||
switch v := value.(type) {
|
||||
case nil:
|
||||
*d = nil
|
||||
case []byte:
|
||||
*d = append(JSONDocument(nil), v...)
|
||||
case string:
|
||||
*d = JSONDocument(v)
|
||||
default:
|
||||
return errors.New("JSONDocument: unsupported type")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (d JSONDocument) MarshalJSON() ([]byte, error) {
|
||||
if len(d) == 0 {
|
||||
return []byte("null"), nil
|
||||
}
|
||||
return d, nil
|
||||
}
|
||||
|
||||
func (d *JSONDocument) UnmarshalJSON(data []byte) error {
|
||||
*d = append(JSONDocument(nil), data...)
|
||||
return nil
|
||||
}
|
||||
|
||||
// GameResultRules are a game's limits on a result (docs/rfc-enakgame.md §5.1, §7.2)
|
||||
// and its daily reward limit (§5.10, §9). A limit left out does not apply.
|
||||
type GameResultRules struct {
|
||||
MaxScore *int64 `json:"max_score,omitempty"`
|
||||
MinDurationSeconds *int64 `json:"min_duration_seconds,omitempty"`
|
||||
MaxScorePerSecond *float64 `json:"max_score_per_second,omitempty"`
|
||||
// The outcomes a result may report. Empty accepts any.
|
||||
Outcomes []string `json:"outcomes,omitempty"`
|
||||
// EnakCoin the game may give out per day, in Asia/Jakarta.
|
||||
DailyRewardLimit *int64 `json:"daily_reward_limit,omitempty"`
|
||||
}
|
||||
|
||||
func (r GameResultRules) Value() (driver.Value, error) {
|
||||
b, err := json.Marshal(r)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return string(b), nil
|
||||
}
|
||||
|
||||
func (r *GameResultRules) Scan(value interface{}) error {
|
||||
*r = GameResultRules{}
|
||||
switch v := value.(type) {
|
||||
case nil:
|
||||
return nil
|
||||
case []byte:
|
||||
return json.Unmarshal(v, r)
|
||||
case string:
|
||||
return json.Unmarshal([]byte(v), r)
|
||||
default:
|
||||
return errors.New("GameResultRules: unsupported type")
|
||||
}
|
||||
}
|
||||
|
||||
// GameRewardConfig is one version of how a game computes its base reward (§5.2, §8).
|
||||
// Never updated apart from Status (D7): a change is a new version.
|
||||
type GameRewardConfig struct {
|
||||
ID uuid.UUID `gorm:"type:uuid;primary_key;default:gen_random_uuid()" json:"id"`
|
||||
OrganizationID uuid.UUID `gorm:"type:uuid;not null" json:"organization_id"`
|
||||
GameID uuid.UUID `gorm:"type:uuid;not null" json:"game_id"`
|
||||
Version int `gorm:"not null" json:"version"`
|
||||
// FIXED, SCORE_BASED, OUTCOME_BASED or PROBABILITY.
|
||||
RewardType string `gorm:"size:30;not null" json:"reward_type"`
|
||||
// Shape per RewardType in §8.
|
||||
Rules JSONDocument `gorm:"type:jsonb;not null" json:"rules"`
|
||||
MaxReward int64 `gorm:"not null" json:"max_reward"`
|
||||
// DRAFT, ACTIVE or RETIRED.
|
||||
Status string `gorm:"size:20;not null" json:"status"`
|
||||
EffectiveAt *time.Time `json:"effective_at"`
|
||||
CreatedBy uuid.UUID `gorm:"type:uuid;not null" json:"created_by"`
|
||||
Reason *string `gorm:"size:255" json:"reason"`
|
||||
// Set together on a version made by accepting a Budget Controller recommendation
|
||||
// (§10): the admin's version it scales, by how much, and for which budget.
|
||||
BaseConfigID *uuid.UUID `gorm:"type:uuid" json:"base_config_id"`
|
||||
Multiplier *float64 `gorm:"type:numeric(6,4)" json:"multiplier"`
|
||||
BudgetID *uuid.UUID `gorm:"type:uuid" json:"budget_id"`
|
||||
CreatedAt time.Time `gorm:"autoCreateTime" json:"created_at"`
|
||||
}
|
||||
|
||||
func (GameRewardConfig) TableName() string { return "game_reward_configs" }
|
||||
|
||||
// GameSession is one play of a game by a customer (§5.3): STARTED, then COMPLETED,
|
||||
// REFUNDED or EXPIRED, each move a conditional update (D4).
|
||||
type GameSession struct {
|
||||
ID uuid.UUID `gorm:"type:uuid;primary_key;default:gen_random_uuid()" json:"id"`
|
||||
OrganizationID uuid.UUID `gorm:"type:uuid;not null" json:"organization_id"`
|
||||
CustomerID uuid.UUID `gorm:"type:uuid;not null" json:"customer_id"`
|
||||
GameID uuid.UUID `gorm:"type:uuid;not null" json:"game_id"`
|
||||
// Snapshots taken at start (D7, P3).
|
||||
RewardConfigID uuid.UUID `gorm:"type:uuid;not null" json:"reward_config_id"`
|
||||
EntryCost int64 `gorm:"not null" json:"entry_cost"`
|
||||
|
||||
Status string `gorm:"size:20;not null" json:"status"`
|
||||
StartedAt time.Time `gorm:"not null" json:"started_at"`
|
||||
ExpiresAt time.Time `gorm:"not null" json:"expires_at"`
|
||||
EndedAt *time.Time `json:"ended_at"`
|
||||
|
||||
// What the client sent: data only, never a reward amount (P1).
|
||||
Result JSONDocument `gorm:"type:jsonb" json:"result"`
|
||||
RewardBreakdown JSONDocument `gorm:"type:jsonb" json:"reward_breakdown"`
|
||||
RewardTotal int64 `gorm:"not null;default:0" json:"reward_total"`
|
||||
Flagged bool `gorm:"not null;default:false" json:"flagged"`
|
||||
|
||||
SpendTransactionID uuid.UUID `gorm:"type:uuid;not null" json:"spend_transaction_id"`
|
||||
RefundTransactionID *uuid.UUID `gorm:"type:uuid" json:"refund_transaction_id"`
|
||||
// SYSTEM_ERROR or GAME_DEACTIVATED.
|
||||
RefundReason *string `gorm:"size:30" json:"refund_reason"`
|
||||
CompletionFailedAt *time.Time `json:"completion_failed_at"`
|
||||
|
||||
CreatedAt time.Time `gorm:"autoCreateTime" json:"created_at"`
|
||||
}
|
||||
|
||||
func (GameSession) TableName() string { return "game_sessions" }
|
||||
|
||||
// GameSessionReward is the part of a session's reward one budget paid for, with its
|
||||
// own ledger row (D6).
|
||||
type GameSessionReward struct {
|
||||
SessionID uuid.UUID `gorm:"type:uuid;primary_key" json:"session_id"`
|
||||
BudgetID uuid.UUID `gorm:"type:uuid;primary_key" json:"budget_id"`
|
||||
Amount int64 `gorm:"not null" json:"amount"`
|
||||
WalletTransactionID uuid.UUID `gorm:"type:uuid;not null" json:"wallet_transaction_id"`
|
||||
}
|
||||
|
||||
func (GameSessionReward) TableName() string { return "game_session_rewards" }
|
||||
|
||||
// GameBudget is what an organization may spend on EnakGame rewards over a period
|
||||
// (§5.6): GLOBAL for base rewards, EVENT for what an event adds.
|
||||
type GameBudget struct {
|
||||
ID uuid.UUID `gorm:"type:uuid;primary_key;default:gen_random_uuid()" json:"id"`
|
||||
OrganizationID uuid.UUID `gorm:"type:uuid;not null" json:"organization_id"`
|
||||
// GLOBAL or EVENT.
|
||||
Scope string `gorm:"size:20;not null" json:"scope"`
|
||||
Name string `gorm:"size:255;not null" json:"name"`
|
||||
// Dates, inclusive at both ends.
|
||||
PeriodStart time.Time `gorm:"type:date;not null" json:"period_start"`
|
||||
PeriodEnd time.Time `gorm:"type:date;not null" json:"period_end"`
|
||||
// Rupiah.
|
||||
Amount int64 `gorm:"not null" json:"amount"`
|
||||
// {"warning": 70, "critical": 90}.
|
||||
Thresholds JSONDocument `gorm:"type:jsonb;not null;default:'{}'" json:"thresholds"`
|
||||
ExhaustionPolicy *string `gorm:"size:30" json:"exhaustion_policy"`
|
||||
CreatedBy uuid.UUID `gorm:"type:uuid;not null" json:"created_by"`
|
||||
CreatedAt time.Time `gorm:"autoCreateTime" json:"created_at"`
|
||||
UpdatedAt time.Time `gorm:"autoUpdateTime" json:"updated_at"`
|
||||
}
|
||||
|
||||
func (GameBudget) TableName() string { return "game_budgets" }
|
||||
|
||||
// GameEvent is a period in which some games pay more, the extra paid by the event's
|
||||
// own budget (docs/rfc-enakgame.md §5.5, D6). Event and campaign are the same thing.
|
||||
type GameEvent struct {
|
||||
ID uuid.UUID `gorm:"type:uuid;primary_key;default:gen_random_uuid()" json:"id"`
|
||||
OrganizationID uuid.UUID `gorm:"type:uuid;not null" json:"organization_id"`
|
||||
Name string `gorm:"size:255;not null" json:"name"`
|
||||
Slug string `gorm:"size:100;not null" json:"slug"`
|
||||
Description *string `gorm:"type:text" json:"description"`
|
||||
BannerURL *string `gorm:"column:banner_url;size:500" json:"banner_url"`
|
||||
StartAt time.Time `gorm:"not null" json:"start_at"`
|
||||
EndAt time.Time `gorm:"not null" json:"end_at"`
|
||||
Timezone string `gorm:"size:50;not null" json:"timezone"`
|
||||
// DRAFT, ACTIVE, ENDED or CANCELLED.
|
||||
Status string `gorm:"size:20;not null" json:"status"`
|
||||
Priority int `gorm:"not null" json:"priority"`
|
||||
// NUMERIC(5,2): at most two decimals.
|
||||
Multiplier *float64 `gorm:"type:numeric(5,2)" json:"multiplier"`
|
||||
Bonus *int64 `json:"bonus"`
|
||||
BudgetID uuid.UUID `gorm:"type:uuid;not null" json:"budget_id"`
|
||||
RewardLimit *int64 `json:"reward_limit"`
|
||||
UserDailyLimit *int64 `json:"user_daily_limit"`
|
||||
CreatedAt time.Time `gorm:"autoCreateTime" json:"created_at"`
|
||||
UpdatedAt time.Time `gorm:"autoUpdateTime" json:"updated_at"`
|
||||
}
|
||||
|
||||
func (GameEvent) TableName() string { return "game_events" }
|
||||
@@ -28,10 +28,7 @@ func GetAllEntities() []interface{} {
|
||||
&CustomerTokens{},
|
||||
&Tier{},
|
||||
&Game{},
|
||||
&GamePrize{},
|
||||
&GamePlay{},
|
||||
&OmsetTracker{},
|
||||
&Reward{},
|
||||
&Campaign{},
|
||||
&CampaignRule{},
|
||||
&OtpSession{},
|
||||
|
||||
@@ -16,16 +16,30 @@ const (
|
||||
)
|
||||
|
||||
type Game struct {
|
||||
ID uuid.UUID `gorm:"type:uuid;primary_key;default:gen_random_uuid()" json:"id"`
|
||||
Name string `gorm:"type:varchar(255);not null" json:"name" validate:"required"`
|
||||
Type GameType `gorm:"type:varchar(50);not null" json:"type" validate:"required,oneof=SPIN RAFFLE MINIGAME"`
|
||||
IsActive bool `gorm:"default:true" json:"is_active"`
|
||||
Metadata Metadata `gorm:"type:jsonb;default:'{}'" json:"metadata"`
|
||||
ID uuid.UUID `gorm:"type:uuid;primary_key;default:gen_random_uuid()" json:"id"`
|
||||
Name string `gorm:"type:varchar(255);not null" json:"name" validate:"required"`
|
||||
Type GameType `gorm:"type:varchar(50);not null" json:"type" validate:"required,oneof=SPIN RAFFLE MINIGAME"`
|
||||
// The old games' settings. Nothing reads it any more; their coin_cost became
|
||||
// entry_cost (migration 000103).
|
||||
Metadata Metadata `gorm:"type:jsonb;default:'{}'" json:"metadata"`
|
||||
|
||||
// EnakGame (docs/rfc-enakgame.md §5.1). Only an ARCHIVED game, which every old game
|
||||
// is, may lack an organization and a slug.
|
||||
OrganizationID *uuid.UUID `gorm:"type:uuid" json:"organization_id"`
|
||||
Slug *string `gorm:"size:100" json:"slug"`
|
||||
Description *string `gorm:"type:text" json:"description"`
|
||||
ThumbnailURL *string `gorm:"column:thumbnail_url;size:500" json:"thumbnail_url"`
|
||||
GameURL *string `gorm:"column:game_url;size:500" json:"game_url"`
|
||||
Version *string `gorm:"size:50" json:"version"`
|
||||
// DRAFT, ACTIVE, INACTIVE or ARCHIVED.
|
||||
Status string `gorm:"size:20;not null;default:ACTIVE" json:"status"`
|
||||
// EnakCoin a session costs; at least 1.
|
||||
EntryCost int64 `gorm:"not null" json:"entry_cost"`
|
||||
SessionTTLSeconds int `gorm:"column:session_ttl_seconds;not null;default:600" json:"session_ttl_seconds"`
|
||||
ResultRules GameResultRules `gorm:"type:jsonb;not null;default:'{}'" json:"result_rules"`
|
||||
|
||||
CreatedAt time.Time `gorm:"autoCreateTime" json:"created_at"`
|
||||
UpdatedAt time.Time `gorm:"autoUpdateTime" json:"updated_at"`
|
||||
|
||||
Prizes []GamePrize `gorm:"foreignKey:GameID" json:"prizes,omitempty"`
|
||||
Plays []GamePlay `gorm:"foreignKey:GameID" json:"plays,omitempty"`
|
||||
}
|
||||
|
||||
func (g *Game) BeforeCreate(tx *gorm.DB) error {
|
||||
|
||||
@@ -1,33 +0,0 @@
|
||||
package entities
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type GamePlay struct {
|
||||
ID uuid.UUID `gorm:"type:uuid;primary_key;default:gen_random_uuid()" json:"id"`
|
||||
GameID uuid.UUID `gorm:"type:uuid;not null;index" json:"game_id" validate:"required"`
|
||||
CustomerID uuid.UUID `gorm:"type:uuid;not null;index" json:"customer_id" validate:"required"`
|
||||
PrizeID *uuid.UUID `gorm:"type:uuid" json:"prize_id,omitempty"`
|
||||
CoinsUsed int `gorm:"column:coins_used;default:0" json:"coins_used" validate:"min=0"`
|
||||
RandomSeed *string `gorm:"type:varchar(255)" json:"random_seed,omitempty"`
|
||||
CreatedAt time.Time `gorm:"autoCreateTime" json:"created_at"`
|
||||
|
||||
Game Game `gorm:"foreignKey:GameID" json:"game,omitempty"`
|
||||
Customer Customer `gorm:"foreignKey:CustomerID" json:"customer,omitempty"`
|
||||
Prize *GamePrize `gorm:"foreignKey:PrizeID" json:"prize,omitempty"`
|
||||
}
|
||||
|
||||
func (gp *GamePlay) BeforeCreate(tx *gorm.DB) error {
|
||||
if gp.ID == uuid.Nil {
|
||||
gp.ID = uuid.New()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (GamePlay) TableName() string {
|
||||
return "game_plays"
|
||||
}
|
||||
@@ -1,38 +0,0 @@
|
||||
package entities
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type GamePrize struct {
|
||||
ID uuid.UUID `gorm:"type:uuid;primary_key;default:gen_random_uuid()" json:"id"`
|
||||
GameID uuid.UUID `gorm:"type:uuid;not null;index" json:"game_id" validate:"required"`
|
||||
Name string `gorm:"type:varchar(255);not null" json:"name" validate:"required"`
|
||||
Weight int `gorm:"not null" json:"weight" validate:"min=1"`
|
||||
Stock int `gorm:"default:0" json:"stock" validate:"min=0"`
|
||||
MaxStock *int `gorm:"" json:"max_stock,omitempty"`
|
||||
Threshold *int64 `gorm:"" json:"threshold,omitempty"`
|
||||
FallbackPrizeID *uuid.UUID `gorm:"type:uuid" json:"fallback_prize_id,omitempty"`
|
||||
Image *string `gorm:"type:varchar(500)" json:"image,omitempty"`
|
||||
Metadata Metadata `gorm:"type:jsonb;default:'{}'" json:"metadata"`
|
||||
CreatedAt time.Time `gorm:"autoCreateTime" json:"created_at"`
|
||||
UpdatedAt time.Time `gorm:"autoUpdateTime" json:"updated_at"`
|
||||
|
||||
Game Game `gorm:"foreignKey:GameID" json:"game,omitempty"`
|
||||
FallbackPrize *GamePrize `gorm:"foreignKey:FallbackPrizeID" json:"fallback_prize,omitempty"`
|
||||
Plays []GamePlay `gorm:"foreignKey:PrizeID" json:"plays,omitempty"`
|
||||
}
|
||||
|
||||
func (gp *GamePrize) BeforeCreate(tx *gorm.DB) error {
|
||||
if gp.ID == uuid.Nil {
|
||||
gp.ID = uuid.New()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (GamePrize) TableName() string {
|
||||
return "game_prizes"
|
||||
}
|
||||
@@ -1,126 +0,0 @@
|
||||
package entities
|
||||
|
||||
import (
|
||||
"database/sql/driver"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type RewardType string
|
||||
|
||||
const (
|
||||
RewardTypeVoucher RewardType = "VOUCHER"
|
||||
RewardTypePhysical RewardType = "PHYSICAL"
|
||||
RewardTypeDigital RewardType = "DIGITAL"
|
||||
RewardTypeBalance RewardType = "BALANCE"
|
||||
)
|
||||
|
||||
// StringSlice is a custom type for []string that implements sql.Scanner and driver.Valuer
|
||||
type StringSlice []string
|
||||
|
||||
// Scan implements the sql.Scanner interface for StringSlice
|
||||
func (s *StringSlice) Scan(value interface{}) error {
|
||||
if value == nil {
|
||||
*s = StringSlice{}
|
||||
return nil
|
||||
}
|
||||
|
||||
var bytes []byte
|
||||
switch v := value.(type) {
|
||||
case []byte:
|
||||
bytes = v
|
||||
case string:
|
||||
bytes = []byte(v)
|
||||
default:
|
||||
return fmt.Errorf("cannot scan %T into StringSlice", value)
|
||||
}
|
||||
|
||||
return json.Unmarshal(bytes, s)
|
||||
}
|
||||
|
||||
// Value implements the driver.Valuer interface for StringSlice
|
||||
func (s StringSlice) Value() (driver.Value, error) {
|
||||
if s == nil {
|
||||
return nil, nil
|
||||
}
|
||||
return json.Marshal(s)
|
||||
}
|
||||
|
||||
type TermsAndConditions struct {
|
||||
Sections []TncSection `json:"sections"`
|
||||
ExpiryDays int `json:"expiry_days"`
|
||||
}
|
||||
|
||||
// Scan implements the sql.Scanner interface for TermsAndConditions
|
||||
func (t *TermsAndConditions) Scan(value interface{}) error {
|
||||
if value == nil {
|
||||
*t = TermsAndConditions{}
|
||||
return nil
|
||||
}
|
||||
|
||||
var bytes []byte
|
||||
switch v := value.(type) {
|
||||
case []byte:
|
||||
bytes = v
|
||||
case string:
|
||||
bytes = []byte(v)
|
||||
default:
|
||||
return fmt.Errorf("cannot scan %T into TermsAndConditions", value)
|
||||
}
|
||||
|
||||
return json.Unmarshal(bytes, t)
|
||||
}
|
||||
|
||||
// Value implements the driver.Valuer interface for TermsAndConditions
|
||||
func (t TermsAndConditions) Value() (driver.Value, error) {
|
||||
return json.Marshal(t)
|
||||
}
|
||||
|
||||
type TncSection struct {
|
||||
Title string `json:"title"`
|
||||
Rules []string `json:"rules"`
|
||||
}
|
||||
|
||||
type Reward struct {
|
||||
ID uuid.UUID `gorm:"type:uuid;primary_key;default:gen_random_uuid()" json:"id"`
|
||||
Name string `gorm:"type:varchar(150);not null" json:"name"`
|
||||
RewardType RewardType `gorm:"type:varchar(50);not null" json:"reward_type"`
|
||||
CostPoints int64 `gorm:"type:bigint;not null" json:"cost_points"`
|
||||
Stock *int `gorm:"type:int" json:"stock,omitempty"`
|
||||
MaxPerCustomer int `gorm:"type:int;default:1" json:"max_per_customer"`
|
||||
Tnc *TermsAndConditions `gorm:"type:jsonb" json:"tnc,omitempty"`
|
||||
Metadata *map[string]interface{} `gorm:"type:jsonb" json:"metadata,omitempty"`
|
||||
Images *StringSlice `gorm:"type:jsonb" json:"images,omitempty"`
|
||||
CreatedAt time.Time `gorm:"type:timestamp;default:now()" json:"created_at"`
|
||||
UpdatedAt time.Time `gorm:"type:timestamp;default:now()" json:"updated_at"`
|
||||
}
|
||||
|
||||
func (Reward) TableName() string {
|
||||
return "rewards"
|
||||
}
|
||||
|
||||
func (r *Reward) BeforeCreate(tx *gorm.DB) error {
|
||||
if r.ID == uuid.Nil {
|
||||
r.ID = uuid.New()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *Reward) BeforeUpdate(tx *gorm.DB) error {
|
||||
r.UpdatedAt = time.Now()
|
||||
return nil
|
||||
}
|
||||
|
||||
type ListRewardsRequest struct {
|
||||
Page int `form:"page" binding:"min=1"`
|
||||
Limit int `form:"limit" binding:"min=1,max=100"`
|
||||
Search string `form:"search"`
|
||||
RewardType string `form:"reward_type"`
|
||||
MinPoints *int64 `form:"min_points"`
|
||||
MaxPoints *int64 `form:"max_points"`
|
||||
HasStock *bool `form:"has_stock"`
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package entities
|
||||
|
||||
import (
|
||||
"database/sql/driver"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
// StringSlice is a custom type for []string that implements sql.Scanner and driver.Valuer
|
||||
type StringSlice []string
|
||||
|
||||
// Scan implements the sql.Scanner interface for StringSlice
|
||||
func (s *StringSlice) Scan(value interface{}) error {
|
||||
if value == nil {
|
||||
*s = StringSlice{}
|
||||
return nil
|
||||
}
|
||||
|
||||
var bytes []byte
|
||||
switch v := value.(type) {
|
||||
case []byte:
|
||||
bytes = v
|
||||
case string:
|
||||
bytes = []byte(v)
|
||||
default:
|
||||
return fmt.Errorf("cannot scan %T into StringSlice", value)
|
||||
}
|
||||
|
||||
return json.Unmarshal(bytes, s)
|
||||
}
|
||||
|
||||
// Value implements the driver.Valuer interface for StringSlice
|
||||
func (s StringSlice) Value() (driver.Value, error) {
|
||||
if s == nil {
|
||||
return nil, nil
|
||||
}
|
||||
return json.Marshal(s)
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
package entities
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// Voucher is what EnakPoint is redeemed for (docs/rfc-enakgame.md §5.7).
|
||||
type Voucher struct {
|
||||
ID uuid.UUID `gorm:"type:uuid;primary_key;default:gen_random_uuid()" json:"id"`
|
||||
OrganizationID uuid.UUID `gorm:"type:uuid;not null" json:"organization_id"`
|
||||
Name string `gorm:"size:255;not null" json:"name"`
|
||||
Description *string `gorm:"type:text" json:"description"`
|
||||
ImageURL *string `gorm:"column:image_url;size:500" json:"image_url"`
|
||||
VoucherType string `gorm:"size:30;not null" json:"voucher_type"`
|
||||
// Rupiah: the basis of realized cost.
|
||||
FaceValue int64 `gorm:"not null" json:"face_value"`
|
||||
PointCost int64 `gorm:"not null" json:"point_cost"`
|
||||
// Reporting only.
|
||||
BusinessCost *int64 `json:"business_cost"`
|
||||
StockMode string `gorm:"size:20;not null" json:"stock_mode"`
|
||||
// STATIC only.
|
||||
Stock *int64 `json:"stock"`
|
||||
// EXTERNAL only.
|
||||
Provider *string `gorm:"size:50" json:"provider"`
|
||||
ProviderRef *string `gorm:"size:255" json:"provider_ref"`
|
||||
MaxPerCustomer *int `json:"max_per_customer"`
|
||||
ValidFrom *time.Time `json:"valid_from"`
|
||||
ValidUntil *time.Time `json:"valid_until"`
|
||||
Terms JSONDocument `gorm:"type:jsonb;not null;default:'{}'" json:"terms"`
|
||||
Status string `gorm:"size:20;not null" json:"status"`
|
||||
CreatedAt time.Time `gorm:"autoCreateTime" json:"created_at"`
|
||||
UpdatedAt time.Time `gorm:"autoUpdateTime" json:"updated_at"`
|
||||
}
|
||||
|
||||
func (Voucher) TableName() string { return "vouchers" }
|
||||
|
||||
// VoucherCode is one code of a CODE_POOL voucher.
|
||||
type VoucherCode struct {
|
||||
ID uuid.UUID `gorm:"type:uuid;primary_key;default:gen_random_uuid()" json:"id"`
|
||||
VoucherID uuid.UUID `gorm:"type:uuid;not null" json:"voucher_id"`
|
||||
Code string `gorm:"size:255;not null" json:"code"`
|
||||
Status string `gorm:"size:20;not null" json:"status"`
|
||||
RedemptionID *uuid.UUID `gorm:"type:uuid" json:"redemption_id"`
|
||||
ExpiresAt *time.Time `json:"expires_at"`
|
||||
CreatedAt time.Time `gorm:"autoCreateTime" json:"created_at"`
|
||||
UpdatedAt time.Time `gorm:"autoUpdateTime" json:"updated_at"`
|
||||
}
|
||||
|
||||
func (VoucherCode) TableName() string { return "voucher_codes" }
|
||||
|
||||
// VoucherRedemption is one redemption, with the voucher's numbers frozen (P3).
|
||||
type VoucherRedemption struct {
|
||||
ID uuid.UUID `gorm:"type:uuid;primary_key;default:gen_random_uuid()" json:"id"`
|
||||
OrganizationID uuid.UUID `gorm:"type:uuid;not null" json:"organization_id"`
|
||||
CustomerID uuid.UUID `gorm:"type:uuid;not null" json:"customer_id"`
|
||||
VoucherID uuid.UUID `gorm:"type:uuid;not null" json:"voucher_id"`
|
||||
IdempotencyKey string `gorm:"size:100;not null" json:"idempotency_key"`
|
||||
Status string `gorm:"size:20;not null" json:"status"`
|
||||
FaceValue int64 `gorm:"not null" json:"face_value"`
|
||||
PointCost int64 `gorm:"not null" json:"point_cost"`
|
||||
VoucherCodeID *uuid.UUID `gorm:"type:uuid" json:"voucher_code_id"`
|
||||
ExternalCode *string `gorm:"size:255" json:"external_code"`
|
||||
ExternalRef *string `gorm:"size:255" json:"external_ref"`
|
||||
DebitTransactionID uuid.UUID `gorm:"type:uuid;not null" json:"debit_transaction_id"`
|
||||
RefundTransactionID *uuid.UUID `gorm:"type:uuid" json:"refund_transaction_id"`
|
||||
FailureReason *string `gorm:"size:255" json:"failure_reason"`
|
||||
Attempts int `gorm:"not null;default:0" json:"attempts"`
|
||||
CompletedAt *time.Time `json:"completed_at"`
|
||||
CreatedAt time.Time `gorm:"autoCreateTime" json:"created_at"`
|
||||
UpdatedAt time.Time `gorm:"autoUpdateTime" json:"updated_at"`
|
||||
}
|
||||
|
||||
func (VoucherRedemption) TableName() string { return "voucher_redemptions" }
|
||||
|
||||
// VoucherRedemptionCost is the part of a redemption's face value one source of its
|
||||
// EnakPoint accounts for (D5). BudgetID is nil for EnakPoint not from EnakGame.
|
||||
type VoucherRedemptionCost struct {
|
||||
RedemptionID uuid.UUID `gorm:"type:uuid;not null" json:"redemption_id"`
|
||||
BudgetID *uuid.UUID `gorm:"type:uuid" json:"budget_id"`
|
||||
SourceType string `gorm:"size:30;not null" json:"source_type"`
|
||||
Points int64 `gorm:"not null" json:"points"`
|
||||
Cost int64 `gorm:"not null" json:"cost"`
|
||||
RecognizedAt time.Time `gorm:"not null" json:"recognized_at"`
|
||||
}
|
||||
|
||||
func (VoucherRedemptionCost) TableName() string { return "voucher_redemption_costs" }
|
||||
@@ -93,36 +93,6 @@ func (h *CustomerPointsHandler) GetCustomerWallet(c *gin.Context) {
|
||||
util.HandleResponse(c.Writer, c.Request, contract.BuildSuccessResponse(response), "CustomerPointsHandler::GetCustomerWallet")
|
||||
}
|
||||
|
||||
func (h *CustomerPointsHandler) GetCustomerGames(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
|
||||
response, err := h.customerPointsService.GetCustomerGames(ctx)
|
||||
if err != nil {
|
||||
logger.FromContext(ctx).WithError(err).Error("CustomerPointsHandler::GetCustomerGames -> service call failed")
|
||||
util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{
|
||||
contract.NewResponseError(constants.InternalServerErrorCode, constants.RequestEntity, err.Error()),
|
||||
}), "CustomerPointsHandler::GetCustomerGames")
|
||||
return
|
||||
}
|
||||
|
||||
util.HandleResponse(c.Writer, c.Request, contract.BuildSuccessResponse(response), "CustomerPointsHandler::GetCustomerGames")
|
||||
}
|
||||
|
||||
func (h *CustomerPointsHandler) GetFerrisWheelGame(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
|
||||
response, err := h.customerPointsService.GetFerrisWheelGame(ctx)
|
||||
if err != nil {
|
||||
logger.FromContext(ctx).WithError(err).Error("CustomerPointsHandler::GetFerrisWheelGame -> service call failed")
|
||||
util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{
|
||||
contract.NewResponseError(constants.InternalServerErrorCode, constants.RequestEntity, err.Error()),
|
||||
}), "CustomerPointsHandler::GetFerrisWheelGame")
|
||||
return
|
||||
}
|
||||
|
||||
util.HandleResponse(c.Writer, c.Request, contract.BuildSuccessResponse(response), "CustomerPointsHandler::GetFerrisWheelGame")
|
||||
}
|
||||
|
||||
// GetCustomerWalletTransactions is GET /customer/wallet/transactions: the ledger, newest
|
||||
// first, filterable by currency, type and date (docs/prd-point-coin.md F6).
|
||||
func (h *CustomerPointsHandler) GetCustomerWalletTransactions(c *gin.Context) {
|
||||
|
||||
@@ -98,7 +98,6 @@ func TestCustomerWalletEndpoints_AgainstPostgres(t *testing.T) {
|
||||
|
||||
h := NewCustomerPointsHandler(service.NewCustomerPointsService(processor.NewCustomerPointsProcessor(
|
||||
processor.NewWalletQueryProcessor(repository.NewWalletQueryRepository(db), processor.NewLoyaltySettingsProcessor(repository.NewLoyaltySettingsRepository(db), repository.NewTxManager(db))),
|
||||
nil,
|
||||
)))
|
||||
gin.SetMode(gin.TestMode)
|
||||
router := gin.New()
|
||||
@@ -181,7 +180,7 @@ func TestCustomerWalletEndpoints_AgainstPostgres(t *testing.T) {
|
||||
assert.Len(t, first["lots"], 2)
|
||||
|
||||
today := time.Now().In(time.FixedZone("WIB", 7*3600)).Format("2006-01-02")
|
||||
status, body = get("/a/wallet/transactions?from=" + today + "&to=" + today + "&type=PAYMENT,MIGRATION")
|
||||
status, body = get("/a/wallet/transactions?from=" + today + "&to=" + today + "&type=REWARD_REDEEM,MIGRATION")
|
||||
require.Equal(t, http.StatusOK, status, body)
|
||||
assert.EqualValues(t, 2, body["data"].(map[string]any)["pagination"].(map[string]any)["total_count"])
|
||||
|
||||
|
||||
@@ -0,0 +1,458 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"io"
|
||||
"mime/multipart"
|
||||
"strings"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/google/uuid"
|
||||
|
||||
"apskel-pos-be/internal/appcontext"
|
||||
"apskel-pos-be/internal/constants"
|
||||
"apskel-pos-be/internal/contract"
|
||||
"apskel-pos-be/internal/models"
|
||||
"apskel-pos-be/internal/service"
|
||||
"apskel-pos-be/internal/util"
|
||||
)
|
||||
|
||||
// EnakGameAdminHandler serves /marketing/enakgame (docs/rfc-enakgame.md §11). Every
|
||||
// request works on the admin's own organization.
|
||||
type EnakGameAdminHandler struct {
|
||||
service service.EnakGameAdminService
|
||||
}
|
||||
|
||||
func NewEnakGameAdminHandler(s service.EnakGameAdminService) *EnakGameAdminHandler {
|
||||
return &EnakGameAdminHandler{service: s}
|
||||
}
|
||||
|
||||
// voucherCodeUploadLimit caps a CSV of codes: 50 000 lines of up to 255 characters.
|
||||
const voucherCodeUploadLimit = 16 << 20
|
||||
|
||||
// pathID reads a UUID path parameter, answering 400 when it is not one.
|
||||
func pathID(c *gin.Context, name, method string) (uuid.UUID, bool) {
|
||||
id, err := uuid.Parse(c.Param(name))
|
||||
if err != nil {
|
||||
util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{
|
||||
contract.NewResponseError(constants.MalformedFieldErrorCode, constants.RequestEntity, "invalid "+name),
|
||||
}), method)
|
||||
return uuid.Nil, false
|
||||
}
|
||||
return id, true
|
||||
}
|
||||
|
||||
// rawBody reads the request body, answering 400 when it cannot.
|
||||
func rawBody(c *gin.Context, method string) ([]byte, bool) {
|
||||
body, err := c.GetRawData()
|
||||
if err != nil {
|
||||
util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{
|
||||
contract.NewResponseError(constants.MalformedFieldErrorCode, constants.RequestEntity, "cannot read the request body"),
|
||||
}), method)
|
||||
return nil, false
|
||||
}
|
||||
return body, true
|
||||
}
|
||||
|
||||
func bindQuery(c *gin.Context, q any, method string) bool {
|
||||
if err := c.ShouldBindQuery(q); err != nil {
|
||||
util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{
|
||||
contract.NewResponseError(constants.MalformedFieldErrorCode, constants.RequestEntity, err.Error()),
|
||||
}), method)
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// CreateGame is POST /marketing/enakgame/games.
|
||||
func (h *EnakGameAdminHandler) CreateGame(c *gin.Context) {
|
||||
const method = "EnakGameAdminHandler::CreateGame"
|
||||
body, ok := rawBody(c, method)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
ctx := c.Request.Context()
|
||||
util.HandleResponse(c.Writer, c.Request, h.service.CreateGame(ctx, appcontext.FromGinContext(ctx), body), method)
|
||||
}
|
||||
|
||||
// ListGames is GET /marketing/enakgame/games?status=&search=&page=&limit=.
|
||||
func (h *EnakGameAdminHandler) ListGames(c *gin.Context) {
|
||||
const method = "EnakGameAdminHandler::ListGames"
|
||||
var q models.EnakGameListQuery
|
||||
if !bindQuery(c, &q, method) {
|
||||
return
|
||||
}
|
||||
ctx := c.Request.Context()
|
||||
util.HandleResponse(c.Writer, c.Request, h.service.ListGames(ctx, appcontext.FromGinContext(ctx), q), method)
|
||||
}
|
||||
|
||||
// GetGame is GET /marketing/enakgame/games/:id.
|
||||
func (h *EnakGameAdminHandler) GetGame(c *gin.Context) {
|
||||
const method = "EnakGameAdminHandler::GetGame"
|
||||
id, ok := pathID(c, "id", method)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
ctx := c.Request.Context()
|
||||
util.HandleResponse(c.Writer, c.Request, h.service.GetGame(ctx, appcontext.FromGinContext(ctx), id), method)
|
||||
}
|
||||
|
||||
// UpdateGame is PUT /marketing/enakgame/games/:id.
|
||||
func (h *EnakGameAdminHandler) UpdateGame(c *gin.Context) {
|
||||
const method = "EnakGameAdminHandler::UpdateGame"
|
||||
id, ok := pathID(c, "id", method)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
body, ok := rawBody(c, method)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
ctx := c.Request.Context()
|
||||
util.HandleResponse(c.Writer, c.Request, h.service.UpdateGame(ctx, appcontext.FromGinContext(ctx), id, body), method)
|
||||
}
|
||||
|
||||
// SetGameStatus is PUT /marketing/enakgame/games/:id/status.
|
||||
func (h *EnakGameAdminHandler) SetGameStatus(c *gin.Context) {
|
||||
const method = "EnakGameAdminHandler::SetGameStatus"
|
||||
id, ok := pathID(c, "id", method)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
body, ok := rawBody(c, method)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
ctx := c.Request.Context()
|
||||
util.HandleResponse(c.Writer, c.Request, h.service.SetGameStatus(ctx, appcontext.FromGinContext(ctx), id, body), method)
|
||||
}
|
||||
|
||||
// CreateRewardConfig is POST /marketing/enakgame/games/:id/reward-configs.
|
||||
func (h *EnakGameAdminHandler) CreateRewardConfig(c *gin.Context) {
|
||||
const method = "EnakGameAdminHandler::CreateRewardConfig"
|
||||
id, ok := pathID(c, "id", method)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
body, ok := rawBody(c, method)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
ctx := c.Request.Context()
|
||||
util.HandleResponse(c.Writer, c.Request, h.service.CreateRewardConfig(ctx, appcontext.FromGinContext(ctx), id, body), method)
|
||||
}
|
||||
|
||||
// ListRewardConfigs is GET /marketing/enakgame/games/:id/reward-configs.
|
||||
func (h *EnakGameAdminHandler) ListRewardConfigs(c *gin.Context) {
|
||||
const method = "EnakGameAdminHandler::ListRewardConfigs"
|
||||
id, ok := pathID(c, "id", method)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
ctx := c.Request.Context()
|
||||
util.HandleResponse(c.Writer, c.Request, h.service.ListRewardConfigs(ctx, appcontext.FromGinContext(ctx), id), method)
|
||||
}
|
||||
|
||||
// ActivateRewardConfig is POST /marketing/enakgame/reward-configs/:id/activate.
|
||||
func (h *EnakGameAdminHandler) ActivateRewardConfig(c *gin.Context) {
|
||||
const method = "EnakGameAdminHandler::ActivateRewardConfig"
|
||||
id, ok := pathID(c, "id", method)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
body, ok := rawBody(c, method)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
ctx := c.Request.Context()
|
||||
util.HandleResponse(c.Writer, c.Request, h.service.ActivateRewardConfig(ctx, appcontext.FromGinContext(ctx), id, body), method)
|
||||
}
|
||||
|
||||
// CreateBudget is POST /marketing/enakgame/budgets.
|
||||
func (h *EnakGameAdminHandler) CreateBudget(c *gin.Context) {
|
||||
const method = "EnakGameAdminHandler::CreateBudget"
|
||||
body, ok := rawBody(c, method)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
ctx := c.Request.Context()
|
||||
util.HandleResponse(c.Writer, c.Request, h.service.CreateBudget(ctx, appcontext.FromGinContext(ctx), body), method)
|
||||
}
|
||||
|
||||
// ListBudgets is GET /marketing/enakgame/budgets?scope=&page=&limit=.
|
||||
func (h *EnakGameAdminHandler) ListBudgets(c *gin.Context) {
|
||||
const method = "EnakGameAdminHandler::ListBudgets"
|
||||
var q models.GameBudgetListQuery
|
||||
if !bindQuery(c, &q, method) {
|
||||
return
|
||||
}
|
||||
ctx := c.Request.Context()
|
||||
util.HandleResponse(c.Writer, c.Request, h.service.ListBudgets(ctx, appcontext.FromGinContext(ctx), q), method)
|
||||
}
|
||||
|
||||
// GetBudget is GET /marketing/enakgame/budgets/:id.
|
||||
func (h *EnakGameAdminHandler) GetBudget(c *gin.Context) {
|
||||
const method = "EnakGameAdminHandler::GetBudget"
|
||||
id, ok := pathID(c, "id", method)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
ctx := c.Request.Context()
|
||||
util.HandleResponse(c.Writer, c.Request, h.service.GetBudget(ctx, appcontext.FromGinContext(ctx), id), method)
|
||||
}
|
||||
|
||||
// UpdateBudget is PUT /marketing/enakgame/budgets/:id.
|
||||
func (h *EnakGameAdminHandler) UpdateBudget(c *gin.Context) {
|
||||
const method = "EnakGameAdminHandler::UpdateBudget"
|
||||
id, ok := pathID(c, "id", method)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
body, ok := rawBody(c, method)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
ctx := c.Request.Context()
|
||||
util.HandleResponse(c.Writer, c.Request, h.service.UpdateBudget(ctx, appcontext.FromGinContext(ctx), id, body), method)
|
||||
}
|
||||
|
||||
// DeleteBudget is DELETE /marketing/enakgame/budgets/:id.
|
||||
func (h *EnakGameAdminHandler) DeleteBudget(c *gin.Context) {
|
||||
const method = "EnakGameAdminHandler::DeleteBudget"
|
||||
id, ok := pathID(c, "id", method)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
ctx := c.Request.Context()
|
||||
util.HandleResponse(c.Writer, c.Request, h.service.DeleteBudget(ctx, appcontext.FromGinContext(ctx), id), method)
|
||||
}
|
||||
|
||||
// BudgetMetrics is GET /marketing/enakgame/budgets/:id/metrics.
|
||||
func (h *EnakGameAdminHandler) BudgetMetrics(c *gin.Context) {
|
||||
const method = "EnakGameAdminHandler::BudgetMetrics"
|
||||
id, ok := pathID(c, "id", method)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
ctx := c.Request.Context()
|
||||
util.HandleResponse(c.Writer, c.Request, h.service.BudgetMetrics(ctx, appcontext.FromGinContext(ctx), id), method)
|
||||
}
|
||||
|
||||
// BudgetRecommendation is GET /marketing/enakgame/budgets/:id/recommendation.
|
||||
func (h *EnakGameAdminHandler) BudgetRecommendation(c *gin.Context) {
|
||||
const method = "EnakGameAdminHandler::BudgetRecommendation"
|
||||
id, ok := pathID(c, "id", method)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
ctx := c.Request.Context()
|
||||
util.HandleResponse(c.Writer, c.Request, h.service.BudgetRecommendation(ctx, appcontext.FromGinContext(ctx), id), method)
|
||||
}
|
||||
|
||||
// AcceptBudgetRecommendation is POST /marketing/enakgame/budgets/:id/recommendation/accept.
|
||||
func (h *EnakGameAdminHandler) AcceptBudgetRecommendation(c *gin.Context) {
|
||||
const method = "EnakGameAdminHandler::AcceptBudgetRecommendation"
|
||||
id, ok := pathID(c, "id", method)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
body, ok := rawBody(c, method)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
ctx := c.Request.Context()
|
||||
util.HandleResponse(c.Writer, c.Request, h.service.AcceptBudgetRecommendation(ctx, appcontext.FromGinContext(ctx), id, body), method)
|
||||
}
|
||||
|
||||
// GameAnalytics is GET /marketing/enakgame/analytics/games?from=&to=&game_id=.
|
||||
func (h *EnakGameAdminHandler) GameAnalytics(c *gin.Context) {
|
||||
const method = "EnakGameAdminHandler::GameAnalytics"
|
||||
var q models.EnakGameAnalyticsQuery
|
||||
if !bindQuery(c, &q, method) {
|
||||
return
|
||||
}
|
||||
ctx := c.Request.Context()
|
||||
util.HandleResponse(c.Writer, c.Request, h.service.GameAnalytics(ctx, appcontext.FromGinContext(ctx), q), method)
|
||||
}
|
||||
|
||||
// EconomyAnalytics is GET /marketing/enakgame/analytics/economy?from=&to=.
|
||||
func (h *EnakGameAdminHandler) EconomyAnalytics(c *gin.Context) {
|
||||
const method = "EnakGameAdminHandler::EconomyAnalytics"
|
||||
var q models.EnakGameAnalyticsQuery
|
||||
if !bindQuery(c, &q, method) {
|
||||
return
|
||||
}
|
||||
ctx := c.Request.Context()
|
||||
util.HandleResponse(c.Writer, c.Request, h.service.EconomyAnalytics(ctx, appcontext.FromGinContext(ctx), q), method)
|
||||
}
|
||||
|
||||
// CreateVoucher is POST /marketing/enakgame/vouchers.
|
||||
func (h *EnakGameAdminHandler) CreateVoucher(c *gin.Context) {
|
||||
const method = "EnakGameAdminHandler::CreateVoucher"
|
||||
body, ok := rawBody(c, method)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
ctx := c.Request.Context()
|
||||
util.HandleResponse(c.Writer, c.Request, h.service.CreateVoucher(ctx, appcontext.FromGinContext(ctx), body), method)
|
||||
}
|
||||
|
||||
// ListVouchers is GET /marketing/enakgame/vouchers?status=&search=&page=&limit=.
|
||||
func (h *EnakGameAdminHandler) ListVouchers(c *gin.Context) {
|
||||
const method = "EnakGameAdminHandler::ListVouchers"
|
||||
var q models.VoucherListQuery
|
||||
if !bindQuery(c, &q, method) {
|
||||
return
|
||||
}
|
||||
ctx := c.Request.Context()
|
||||
util.HandleResponse(c.Writer, c.Request, h.service.ListVouchers(ctx, appcontext.FromGinContext(ctx), q), method)
|
||||
}
|
||||
|
||||
// GetVoucher is GET /marketing/enakgame/vouchers/:id.
|
||||
func (h *EnakGameAdminHandler) GetVoucher(c *gin.Context) {
|
||||
const method = "EnakGameAdminHandler::GetVoucher"
|
||||
id, ok := pathID(c, "id", method)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
ctx := c.Request.Context()
|
||||
util.HandleResponse(c.Writer, c.Request, h.service.GetVoucher(ctx, appcontext.FromGinContext(ctx), id), method)
|
||||
}
|
||||
|
||||
// UpdateVoucher is PUT /marketing/enakgame/vouchers/:id.
|
||||
func (h *EnakGameAdminHandler) UpdateVoucher(c *gin.Context) {
|
||||
const method = "EnakGameAdminHandler::UpdateVoucher"
|
||||
id, ok := pathID(c, "id", method)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
body, ok := rawBody(c, method)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
ctx := c.Request.Context()
|
||||
util.HandleResponse(c.Writer, c.Request, h.service.UpdateVoucher(ctx, appcontext.FromGinContext(ctx), id, body), method)
|
||||
}
|
||||
|
||||
// SetVoucherStatus is PUT /marketing/enakgame/vouchers/:id/status.
|
||||
func (h *EnakGameAdminHandler) SetVoucherStatus(c *gin.Context) {
|
||||
const method = "EnakGameAdminHandler::SetVoucherStatus"
|
||||
id, ok := pathID(c, "id", method)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
body, ok := rawBody(c, method)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
ctx := c.Request.Context()
|
||||
util.HandleResponse(c.Writer, c.Request, h.service.SetVoucherStatus(ctx, appcontext.FromGinContext(ctx), id, body), method)
|
||||
}
|
||||
|
||||
// ImportVoucherCodes is POST /marketing/enakgame/vouchers/:id/codes, with the CSV as
|
||||
// a multipart file named "file" or as the request body.
|
||||
func (h *EnakGameAdminHandler) ImportVoucherCodes(c *gin.Context) {
|
||||
const method = "EnakGameAdminHandler::ImportVoucherCodes"
|
||||
id, ok := pathID(c, "id", method)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
var data []byte
|
||||
if strings.HasPrefix(c.ContentType(), "multipart/") {
|
||||
file, err := c.FormFile("file")
|
||||
if err == nil {
|
||||
var f multipart.File
|
||||
if f, err = file.Open(); err == nil {
|
||||
data, err = io.ReadAll(io.LimitReader(f, voucherCodeUploadLimit))
|
||||
f.Close()
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{
|
||||
contract.NewResponseError(constants.MalformedFieldErrorCode, constants.RequestEntity, "send the CSV as a file named \"file\""),
|
||||
}), method)
|
||||
return
|
||||
}
|
||||
} else if data, ok = rawBody(c, method); !ok {
|
||||
return
|
||||
}
|
||||
ctx := c.Request.Context()
|
||||
util.HandleResponse(c.Writer, c.Request, h.service.ImportVoucherCodes(ctx, appcontext.FromGinContext(ctx), id, data), method)
|
||||
}
|
||||
|
||||
// ListVoucherCodes is GET /marketing/enakgame/vouchers/:id/codes?status=&page=&limit=.
|
||||
func (h *EnakGameAdminHandler) ListVoucherCodes(c *gin.Context) {
|
||||
const method = "EnakGameAdminHandler::ListVoucherCodes"
|
||||
id, ok := pathID(c, "id", method)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
var q models.VoucherCodeListQuery
|
||||
if !bindQuery(c, &q, method) {
|
||||
return
|
||||
}
|
||||
ctx := c.Request.Context()
|
||||
util.HandleResponse(c.Writer, c.Request, h.service.ListVoucherCodes(ctx, appcontext.FromGinContext(ctx), id, q), method)
|
||||
}
|
||||
|
||||
// CreateEvent is POST /marketing/enakgame/events.
|
||||
func (h *EnakGameAdminHandler) CreateEvent(c *gin.Context) {
|
||||
const method = "EnakGameAdminHandler::CreateEvent"
|
||||
body, ok := rawBody(c, method)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
ctx := c.Request.Context()
|
||||
util.HandleResponse(c.Writer, c.Request, h.service.CreateEvent(ctx, appcontext.FromGinContext(ctx), body), method)
|
||||
}
|
||||
|
||||
// ListEvents is GET /marketing/enakgame/events?status=&page=&limit=.
|
||||
func (h *EnakGameAdminHandler) ListEvents(c *gin.Context) {
|
||||
const method = "EnakGameAdminHandler::ListEvents"
|
||||
var q models.GameEventListQuery
|
||||
if !bindQuery(c, &q, method) {
|
||||
return
|
||||
}
|
||||
ctx := c.Request.Context()
|
||||
util.HandleResponse(c.Writer, c.Request, h.service.ListEvents(ctx, appcontext.FromGinContext(ctx), q), method)
|
||||
}
|
||||
|
||||
// GetEvent is GET /marketing/enakgame/events/:id.
|
||||
func (h *EnakGameAdminHandler) GetEvent(c *gin.Context) {
|
||||
const method = "EnakGameAdminHandler::GetEvent"
|
||||
id, ok := pathID(c, "id", method)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
ctx := c.Request.Context()
|
||||
util.HandleResponse(c.Writer, c.Request, h.service.GetEvent(ctx, appcontext.FromGinContext(ctx), id), method)
|
||||
}
|
||||
|
||||
// UpdateEvent is PUT /marketing/enakgame/events/:id.
|
||||
func (h *EnakGameAdminHandler) UpdateEvent(c *gin.Context) {
|
||||
const method = "EnakGameAdminHandler::UpdateEvent"
|
||||
id, ok := pathID(c, "id", method)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
body, ok := rawBody(c, method)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
ctx := c.Request.Context()
|
||||
util.HandleResponse(c.Writer, c.Request, h.service.UpdateEvent(ctx, appcontext.FromGinContext(ctx), id, body), method)
|
||||
}
|
||||
|
||||
// SetEventStatus is PUT /marketing/enakgame/events/:id/status.
|
||||
func (h *EnakGameAdminHandler) SetEventStatus(c *gin.Context) {
|
||||
const method = "EnakGameAdminHandler::SetEventStatus"
|
||||
id, ok := pathID(c, "id", method)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
body, ok := rawBody(c, method)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
ctx := c.Request.Context()
|
||||
util.HandleResponse(c.Writer, c.Request, h.service.SetEventStatus(ctx, appcontext.FromGinContext(ctx), id, body), method)
|
||||
}
|
||||
@@ -0,0 +1,148 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"strconv"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"apskel-pos-be/internal/constants"
|
||||
"apskel-pos-be/internal/contract"
|
||||
"apskel-pos-be/internal/models"
|
||||
"apskel-pos-be/internal/service"
|
||||
"apskel-pos-be/internal/util"
|
||||
)
|
||||
|
||||
// EnakGameCustomerHandler serves /customer/enakgame (docs/rfc-enakgame.md §11).
|
||||
type EnakGameCustomerHandler struct {
|
||||
service service.EnakGameCustomerService
|
||||
}
|
||||
|
||||
func NewEnakGameCustomerHandler(s service.EnakGameCustomerService) *EnakGameCustomerHandler {
|
||||
return &EnakGameCustomerHandler{service: s}
|
||||
}
|
||||
|
||||
// ListGames is GET /customer/enakgame/games.
|
||||
func (h *EnakGameCustomerHandler) ListGames(c *gin.Context) {
|
||||
const method = "EnakGameCustomerHandler::ListGames"
|
||||
customerID, ok := customerIDFromGin(c, method)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
util.HandleResponse(c.Writer, c.Request, h.service.ListGames(c.Request.Context(), customerID), method)
|
||||
}
|
||||
|
||||
// StartSession is POST /customer/enakgame/sessions. It requires Idempotency-Key.
|
||||
func (h *EnakGameCustomerHandler) StartSession(c *gin.Context) {
|
||||
const method = "EnakGameCustomerHandler::StartSession"
|
||||
customerID, ok := customerIDFromGin(c, method)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
var req contract.StartGameSessionRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{
|
||||
contract.NewResponseError(constants.MissingFieldErrorCode, constants.RequestEntity, "game_id is required"),
|
||||
}), method)
|
||||
return
|
||||
}
|
||||
util.HandleResponse(c.Writer, c.Request, h.service.StartSession(c.Request.Context(), customerID, &req, idempotencyKey(c)), method)
|
||||
}
|
||||
|
||||
// ListSessions is GET /customer/enakgame/sessions?page=&limit=.
|
||||
func (h *EnakGameCustomerHandler) ListSessions(c *gin.Context) {
|
||||
const method = "EnakGameCustomerHandler::ListSessions"
|
||||
customerID, ok := customerIDFromGin(c, method)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
page, _ := strconv.Atoi(c.Query("page"))
|
||||
limit, _ := strconv.Atoi(c.Query("limit"))
|
||||
util.HandleResponse(c.Writer, c.Request, h.service.ListSessions(c.Request.Context(), customerID, page, limit), method)
|
||||
}
|
||||
|
||||
// GetSession is GET /customer/enakgame/sessions/:id.
|
||||
func (h *EnakGameCustomerHandler) GetSession(c *gin.Context) {
|
||||
const method = "EnakGameCustomerHandler::GetSession"
|
||||
customerID, ok := customerIDFromGin(c, method)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
id, ok := pathID(c, "id", method)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
util.HandleResponse(c.Writer, c.Request, h.service.GetSession(c.Request.Context(), customerID, id), method)
|
||||
}
|
||||
|
||||
// CompleteSession is POST /customer/enakgame/sessions/:id/complete. The body is read
|
||||
// leniently on purpose: a reward amount, or anything else the backend does not take
|
||||
// from the client, is ignored rather than refused (P1). An empty body is a result
|
||||
// with nothing in it.
|
||||
func (h *EnakGameCustomerHandler) CompleteSession(c *gin.Context) {
|
||||
const method = "EnakGameCustomerHandler::CompleteSession"
|
||||
customerID, ok := customerIDFromGin(c, method)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
id, ok := pathID(c, "id", method)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
body, ok := rawBody(c, method)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
var in models.GameSessionCompleteInput
|
||||
if len(bytes.TrimSpace(body)) > 0 {
|
||||
if err := json.Unmarshal(body, &in); err != nil {
|
||||
util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{
|
||||
contract.NewResponseError(constants.MalformedFieldErrorCode, constants.RequestEntity, "score must be a whole number and outcome a text"),
|
||||
}), method)
|
||||
return
|
||||
}
|
||||
}
|
||||
util.HandleResponse(c.Writer, c.Request, h.service.CompleteSession(c.Request.Context(), customerID, id, in), method)
|
||||
}
|
||||
|
||||
// ListVouchers is GET /customer/enakgame/vouchers.
|
||||
func (h *EnakGameCustomerHandler) ListVouchers(c *gin.Context) {
|
||||
const method = "EnakGameCustomerHandler::ListVouchers"
|
||||
customerID, ok := customerIDFromGin(c, method)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
util.HandleResponse(c.Writer, c.Request, h.service.ListVouchers(c.Request.Context(), customerID), method)
|
||||
}
|
||||
|
||||
// RedeemVoucher is POST /customer/enakgame/vouchers/:id/redeem. It requires the PIN
|
||||
// and Idempotency-Key; the body holds the PIN, so it is never logged.
|
||||
func (h *EnakGameCustomerHandler) RedeemVoucher(c *gin.Context) {
|
||||
const method = "EnakGameCustomerHandler::RedeemVoucher"
|
||||
customerID, ok := customerIDFromGin(c, method)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
id, ok := pathID(c, "id", method)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
var req contract.RedeemVoucherRequest
|
||||
if !bindPinRequest(c, &req, method) {
|
||||
return
|
||||
}
|
||||
util.HandleResponse(c.Writer, c.Request, h.service.RedeemVoucher(c.Request.Context(), customerID, id, &req, idempotencyKey(c), pinRequestInfo(c)), method)
|
||||
}
|
||||
|
||||
// ListRedemptions is GET /customer/enakgame/redemptions?page=&limit=.
|
||||
func (h *EnakGameCustomerHandler) ListRedemptions(c *gin.Context) {
|
||||
const method = "EnakGameCustomerHandler::ListRedemptions"
|
||||
customerID, ok := customerIDFromGin(c, method)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
page, _ := strconv.Atoi(c.Query("page"))
|
||||
limit, _ := strconv.Atoi(c.Query("limit"))
|
||||
util.HandleResponse(c.Writer, c.Request, h.service.ListRedemptions(c.Request.Context(), customerID, page, limit), method)
|
||||
}
|
||||
@@ -0,0 +1,609 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"mime/multipart"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/google/uuid"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
"gorm.io/driver/postgres"
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/logger"
|
||||
|
||||
"apskel-pos-be/internal/appcontext"
|
||||
applogger "apskel-pos-be/internal/logger"
|
||||
"apskel-pos-be/internal/middleware"
|
||||
"apskel-pos-be/internal/processor"
|
||||
"apskel-pos-be/internal/repository"
|
||||
"apskel-pos-be/internal/service"
|
||||
)
|
||||
|
||||
// enakGameHandlers builds both EnakGame handlers on db, the way app.go does.
|
||||
func enakGameHandlers(db *gorm.DB) (*EnakGameAdminHandler, *EnakGameCustomerHandler) {
|
||||
txm := repository.NewTxManager(db)
|
||||
audit := processor.NewAuditLogger(repository.NewAuditLogRepository(db))
|
||||
games := repository.NewEnakGameRepository(db)
|
||||
budgets := repository.NewGameBudgetRepository(db)
|
||||
vouchers := repository.NewVoucherRepository(db)
|
||||
wallet := processor.NewWalletProcessor(repository.NewWalletRepository(db))
|
||||
customers := repository.NewWalletMoveRepository(db)
|
||||
spendable := repository.NewWalletQueryRepository(db)
|
||||
metrics := processor.NewGameBudgetMetricsProcessor(budgets, repository.NewGameBudgetMetricsRepository(db))
|
||||
admin := NewEnakGameAdminHandler(service.NewEnakGameAdminService(
|
||||
processor.NewEnakGameAdminProcessor(games, audit, txm), processor.NewGameBudgetProcessor(budgets, audit, txm), metrics,
|
||||
processor.NewGameBudgetControllerProcessor(budgets, metrics, games, audit, txm),
|
||||
processor.NewGameEventProcessor(repository.NewGameEventRepository(db), games, budgets, audit, txm),
|
||||
processor.NewVoucherAdminProcessor(vouchers, audit, txm),
|
||||
processor.NewEnakGameAnalyticsProcessor(repository.NewEnakGameAnalyticsRepository(db))))
|
||||
customer := NewEnakGameCustomerHandler(service.NewEnakGameCustomerService(
|
||||
processor.NewGameSessionProcessor(customers, games, repository.NewGameSessionRepository(db), budgets,
|
||||
repository.NewGameEventRepository(db), repository.NewGameRewardCounterRepository(db), processor.NewLoyaltySettingsProcessor(repository.NewLoyaltySettingsRepository(db), txm),
|
||||
spendable, wallet, audit, txm),
|
||||
processor.NewVoucherRedemptionProcessor(customers, vouchers, repository.NewVoucherRedemptionRepository(db),
|
||||
processor.NewCustomerPinProcessor(repository.NewCustomerPinRepository(db), nil, nil), spendable, wallet, processor.VoucherProviders{}, txm)))
|
||||
return admin, customer
|
||||
}
|
||||
|
||||
// Drives /marketing/enakgame and /customer/enakgame over HTTP down to Postgres
|
||||
// (docs/rfc-enakgame.md §11). Needs TEST_DATABASE_URL; see
|
||||
// internal/repository/wallet_repository_test.go.
|
||||
func TestEnakGameEndpoints_AgainstPostgres(t *testing.T) {
|
||||
dsn := os.Getenv("TEST_DATABASE_URL")
|
||||
if dsn == "" {
|
||||
t.Skip("TEST_DATABASE_URL not set")
|
||||
}
|
||||
applogger.Setup("fatal", "json")
|
||||
db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{Logger: logger.Default.LogMode(logger.Silent)})
|
||||
require.NoError(t, err)
|
||||
|
||||
org, admin, customer := uuid.New(), uuid.New(), uuid.New()
|
||||
require.NoError(t, db.Exec(`INSERT INTO organizations (id, name, plan_type) VALUES (?, 'enakgame http', 'basic')`, org).Error)
|
||||
require.NoError(t, db.Exec(`INSERT INTO customers (id, organization_id, name) VALUES (?, ?, 'Budi')`, customer, org).Error)
|
||||
t.Cleanup(func() {
|
||||
for _, q := range []string{
|
||||
`DELETE FROM audit_logs WHERE organization_id = ?`,
|
||||
`DELETE FROM game_reward_counters WHERE organization_id = ?`,
|
||||
`DELETE FROM game_sessions WHERE organization_id = ?`,
|
||||
`DELETE FROM wallet_lot_allocations WHERE lot_id IN (SELECT id FROM wallet_lots WHERE organization_id = ?)`,
|
||||
`DELETE FROM wallet_lots WHERE organization_id = ?`,
|
||||
`DELETE FROM wallet_transactions WHERE organization_id = ?`,
|
||||
`DELETE FROM customer_wallets WHERE organization_id = ?`,
|
||||
`DELETE FROM game_event_games WHERE event_id IN (SELECT id FROM game_events WHERE organization_id = ?)`,
|
||||
`DELETE FROM game_events WHERE organization_id = ?`,
|
||||
`DELETE FROM game_reward_configs WHERE organization_id = ?`,
|
||||
`DELETE FROM game_budgets WHERE organization_id = ?`,
|
||||
`DELETE FROM games WHERE organization_id = ?`,
|
||||
`DELETE FROM customers WHERE organization_id = ?`,
|
||||
`DELETE FROM organizations WHERE id = ?`,
|
||||
} {
|
||||
db.Exec(q, org)
|
||||
}
|
||||
})
|
||||
|
||||
txm := repository.NewTxManager(db)
|
||||
wallet := processor.NewWalletProcessor(repository.NewWalletRepository(db))
|
||||
adminHandler, customerHandler := enakGameHandlers(db)
|
||||
|
||||
auth := middleware.NewAuthMiddleware(nil)
|
||||
gin.SetMode(gin.TestMode)
|
||||
router := gin.New()
|
||||
for prefix, role := range map[string]string{"/manager": "manager", "/purchasing": "purchasing"} {
|
||||
role := role
|
||||
g := router.Group(prefix+"/enakgame", func(c *gin.Context) {
|
||||
ctx := context.WithValue(c.Request.Context(), appcontext.OrganizationIDKey, org.String())
|
||||
ctx = context.WithValue(ctx, appcontext.UserIDKey, admin.String())
|
||||
ctx = context.WithValue(ctx, appcontext.UserRoleKey, role)
|
||||
c.Request = c.Request.WithContext(ctx)
|
||||
})
|
||||
g.POST("/games", adminHandler.CreateGame)
|
||||
g.GET("/games/:id", adminHandler.GetGame)
|
||||
g.PUT("/games/:id", adminHandler.UpdateGame)
|
||||
g.PUT("/games/:id/status", adminHandler.SetGameStatus)
|
||||
g.POST("/games/:id/reward-configs", auth.RequireLoyaltyManager(), adminHandler.CreateRewardConfig)
|
||||
g.POST("/reward-configs/:id/activate", auth.RequireLoyaltyManager(), adminHandler.ActivateRewardConfig)
|
||||
g.POST("/budgets", auth.RequireLoyaltyManager(), adminHandler.CreateBudget)
|
||||
g.GET("/budgets/:id/metrics", adminHandler.BudgetMetrics)
|
||||
}
|
||||
c := router.Group("/customer/enakgame", func(c *gin.Context) { c.Set("customer_id", customer.String()) })
|
||||
c.GET("/games", customerHandler.ListGames)
|
||||
c.POST("/sessions", customerHandler.StartSession)
|
||||
c.GET("/sessions/:id", customerHandler.GetSession)
|
||||
|
||||
call := func(method, path, body string, headers ...string) (int, map[string]any) {
|
||||
t.Helper()
|
||||
req := httptest.NewRequest(method, path, bytes.NewBufferString(body))
|
||||
for i := 0; i+1 < len(headers); i += 2 {
|
||||
req.Header.Set(headers[i], headers[i+1])
|
||||
}
|
||||
rec := httptest.NewRecorder()
|
||||
router.ServeHTTP(rec, req)
|
||||
var out map[string]any
|
||||
require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &out), rec.Body.String())
|
||||
return rec.Code, out
|
||||
}
|
||||
data := func(body map[string]any) map[string]any { return body["data"].(map[string]any) }
|
||||
|
||||
status, body := call(http.MethodPost, "/manager/enakgame/games", `{"name": "Runner", "slug": "runner", "entry_cost": 2, "status": "ACTIVE",
|
||||
"result_rules": {"max_score": 5000, "outcomes": ["WIN", "LOSE"]}}`)
|
||||
require.Equal(t, http.StatusOK, status, body)
|
||||
gameID := data(body)["id"].(string)
|
||||
assert.Equal(t, map[string]any{"max_score": float64(5000), "outcomes": []any{"WIN", "LOSE"}}, data(body)["result_rules"])
|
||||
|
||||
status, _ = call(http.MethodPost, "/manager/enakgame/games", `{"name": "X", "slug": "x", "entry_cost": 1, "entry_cots": 2}`)
|
||||
assert.Equal(t, http.StatusBadRequest, status, "a misspelt field is refused")
|
||||
status, _ = call(http.MethodPost, "/manager/enakgame/games", `{"name": "X", "slug": "runner", "entry_cost": 1}`)
|
||||
assert.Equal(t, http.StatusBadRequest, status, "slug in use")
|
||||
status, _ = call(http.MethodGet, "/manager/enakgame/games/"+uuid.NewString(), "")
|
||||
assert.Equal(t, http.StatusNotFound, status)
|
||||
status, _ = call(http.MethodGet, "/manager/enakgame/games/not-a-uuid", "")
|
||||
assert.Equal(t, http.StatusBadRequest, status)
|
||||
|
||||
// A change keeps the fields it does not send.
|
||||
status, body = call(http.MethodPut, "/manager/enakgame/games/"+gameID, `{"entry_cost": 3}`)
|
||||
require.Equal(t, http.StatusOK, status, body)
|
||||
assert.EqualValues(t, 3, data(body)["entry_cost"])
|
||||
assert.Equal(t, "runner", data(body)["slug"])
|
||||
assert.EqualValues(t, 5000, data(body)["result_rules"].(map[string]any)["max_score"])
|
||||
|
||||
// Reward configurations and budgets need a loyalty manager.
|
||||
config := `{"reward_type": "OUTCOME_BASED", "rules": {"outcomes": {"WIN": 10, "LOSE": 1}}, "max_reward": 10}`
|
||||
status, _ = call(http.MethodPost, "/purchasing/enakgame/games/"+gameID+"/reward-configs", config)
|
||||
assert.Equal(t, http.StatusForbidden, status)
|
||||
status, body = call(http.MethodPost, "/manager/enakgame/games/"+gameID+"/reward-configs", config)
|
||||
require.Equal(t, http.StatusOK, status, body)
|
||||
status, body = call(http.MethodPost, "/manager/enakgame/reward-configs/"+data(body)["id"].(string)+"/activate", "")
|
||||
require.Equal(t, http.StatusOK, status, body)
|
||||
assert.Equal(t, "ACTIVE", data(body)["status"])
|
||||
|
||||
// The customer cannot start before the period has a budget.
|
||||
require.NoError(t, txm.WithTransaction(context.Background(), func(ctx context.Context) error {
|
||||
_, err := wallet.Credit(ctx, processor.WalletCreditInput{WalletEntry: processor.WalletEntry{
|
||||
CustomerID: customer, Currency: "COIN", Type: "MIGRATION", Amount: 10,
|
||||
ReferenceType: "LEGACY_TOKENS", ReferenceID: uuid.New(), Description: "Saldo awal"}})
|
||||
return err
|
||||
}))
|
||||
start := `{"game_id": "` + gameID + `"}`
|
||||
status, body = call(http.MethodPost, "/customer/enakgame/sessions", start, "Idempotency-Key", "k1")
|
||||
assert.Equal(t, http.StatusBadRequest, status, body)
|
||||
now := time.Now().In(time.FixedZone("WIB", 7*3600))
|
||||
first := time.Date(now.Year(), now.Month(), 1, 0, 0, 0, 0, time.UTC)
|
||||
budget := `{"scope": "GLOBAL", "name": "Bulan ini", "period_start": "` + first.Format("2006-01-02") +
|
||||
`", "period_end": "` + first.AddDate(0, 1, -1).Format("2006-01-02") + `", "amount": 1000000}`
|
||||
status, _ = call(http.MethodPost, "/purchasing/enakgame/budgets", budget)
|
||||
assert.Equal(t, http.StatusForbidden, status)
|
||||
status, body = call(http.MethodPost, "/manager/enakgame/budgets", budget)
|
||||
require.Equal(t, http.StatusOK, status, body)
|
||||
status, body = call(http.MethodGet, "/purchasing/enakgame/budgets/"+data(body)["id"].(string)+"/metrics", "")
|
||||
require.Equal(t, http.StatusOK, status, body)
|
||||
assert.Equal(t, "HEALTHY", data(body)["status"])
|
||||
assert.EqualValues(t, 1000000, data(body)["remaining"])
|
||||
status, _ = call(http.MethodGet, "/manager/enakgame/budgets/"+uuid.NewString()+"/metrics", "")
|
||||
assert.Equal(t, http.StatusNotFound, status)
|
||||
|
||||
status, body = call(http.MethodGet, "/customer/enakgame/games", "")
|
||||
require.Equal(t, http.StatusOK, status, body)
|
||||
listed := body["data"].([]any)
|
||||
require.Len(t, listed, 1)
|
||||
assert.NotContains(t, listed[0], "result_rules", "the validation limits stay internal")
|
||||
|
||||
status, body = call(http.MethodPost, "/customer/enakgame/sessions", start)
|
||||
assert.Equal(t, http.StatusBadRequest, status, "Idempotency-Key is required")
|
||||
status, body = call(http.MethodPost, "/customer/enakgame/sessions", start, "Idempotency-Key", "k1")
|
||||
require.Equal(t, http.StatusOK, status, body)
|
||||
sessionID := data(body)["session_id"].(string)
|
||||
assert.EqualValues(t, 7, data(body)["coin_balance"])
|
||||
status, body = call(http.MethodPost, "/customer/enakgame/sessions", start, "X-Idempotency-Key", "k1")
|
||||
require.Equal(t, http.StatusOK, status, body)
|
||||
assert.Equal(t, sessionID, data(body)["session_id"])
|
||||
assert.Equal(t, true, data(body)["replayed"])
|
||||
status, body = call(http.MethodPost, "/customer/enakgame/sessions", `{}`, "Idempotency-Key", "k2")
|
||||
assert.Equal(t, http.StatusBadRequest, status, body)
|
||||
|
||||
status, body = call(http.MethodGet, "/customer/enakgame/sessions/"+sessionID, "")
|
||||
require.Equal(t, http.StatusOK, status, body)
|
||||
assert.Equal(t, "STARTED", data(body)["status"])
|
||||
status, _ = call(http.MethodGet, "/customer/enakgame/sessions/"+uuid.NewString(), "")
|
||||
assert.Equal(t, http.StatusNotFound, status)
|
||||
|
||||
// The backend alone decides the reward (P1): a reward in the body is ignored.
|
||||
c.POST("/sessions/:id/complete", customerHandler.CompleteSession)
|
||||
status, body = call(http.MethodPost, "/customer/enakgame/sessions/"+sessionID+"/complete", `{"outcome": "LOSE", "reward": 999, "reward_total": 999}`)
|
||||
require.Equal(t, http.StatusOK, status, body)
|
||||
assert.EqualValues(t, 1, data(body)["reward_total"])
|
||||
assert.EqualValues(t, 8, data(body)["coin_balance"])
|
||||
status, body = call(http.MethodPost, "/customer/enakgame/sessions/"+sessionID+"/complete", `{"outcome": "WIN"}`)
|
||||
require.Equal(t, http.StatusOK, status, body)
|
||||
assert.EqualValues(t, 1, data(body)["reward_total"], "the first completion stands")
|
||||
status, _ = call(http.MethodPost, "/customer/enakgame/sessions/"+sessionID+"/complete", `{"score": "high"}`)
|
||||
assert.Equal(t, http.StatusBadRequest, status)
|
||||
status, _ = call(http.MethodPost, "/customer/enakgame/sessions/"+uuid.NewString()+"/complete", ``)
|
||||
assert.Equal(t, http.StatusNotFound, status)
|
||||
|
||||
// Deactivating the game is audited; the session waits for the job.
|
||||
status, body = call(http.MethodPut, "/manager/enakgame/games/"+gameID+"/status", `{"status": "INACTIVE", "reason": "bug"}`)
|
||||
require.Equal(t, http.StatusOK, status, body)
|
||||
status, _ = call(http.MethodPost, "/customer/enakgame/sessions", start, "Idempotency-Key", "k3")
|
||||
assert.Equal(t, http.StatusBadRequest, status, "an inactive game cannot start")
|
||||
}
|
||||
|
||||
// Drives the voucher endpoints over HTTP down to Postgres (docs/rfc-enakgame.md §7.4,
|
||||
// §11).
|
||||
func TestEnakGameVoucherEndpoints_AgainstPostgres(t *testing.T) {
|
||||
dsn := os.Getenv("TEST_DATABASE_URL")
|
||||
if dsn == "" {
|
||||
t.Skip("TEST_DATABASE_URL not set")
|
||||
}
|
||||
applogger.Setup("fatal", "json")
|
||||
db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{Logger: logger.Default.LogMode(logger.Silent)})
|
||||
require.NoError(t, err)
|
||||
|
||||
org, admin, customer := uuid.New(), uuid.New(), uuid.New()
|
||||
hash, err := bcrypt.GenerateFromPassword([]byte("482913"), bcrypt.MinCost)
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, db.Exec(`INSERT INTO organizations (id, name, plan_type) VALUES (?, 'voucher http', 'basic')`, org).Error)
|
||||
require.NoError(t, db.Exec(`INSERT INTO customers (id, organization_id, name, pin_hash, pin_set_at) VALUES (?, ?, 'Budi', ?, NOW())`, customer, org, string(hash)).Error)
|
||||
t.Cleanup(func() {
|
||||
for _, q := range []string{
|
||||
`DELETE FROM audit_logs WHERE organization_id = ?`,
|
||||
`DELETE FROM voucher_redemption_costs WHERE redemption_id IN (SELECT id FROM voucher_redemptions WHERE organization_id = ?)`,
|
||||
`DELETE FROM voucher_redemptions WHERE organization_id = ?`,
|
||||
`DELETE FROM voucher_codes WHERE voucher_id IN (SELECT id FROM vouchers WHERE organization_id = ?)`,
|
||||
`DELETE FROM vouchers WHERE organization_id = ?`,
|
||||
`DELETE FROM customer_security_events WHERE customer_id IN (SELECT id FROM customers WHERE organization_id = ?)`,
|
||||
`DELETE FROM wallet_lot_allocations WHERE lot_id IN (SELECT id FROM wallet_lots WHERE organization_id = ?)`,
|
||||
`DELETE FROM wallet_lots WHERE organization_id = ?`,
|
||||
`DELETE FROM wallet_transactions WHERE organization_id = ?`,
|
||||
`DELETE FROM customer_wallets WHERE organization_id = ?`,
|
||||
`DELETE FROM customers WHERE organization_id = ?`,
|
||||
`DELETE FROM organizations WHERE id = ?`,
|
||||
} {
|
||||
db.Exec(q, org)
|
||||
}
|
||||
})
|
||||
txm := repository.NewTxManager(db)
|
||||
wallet := processor.NewWalletProcessor(repository.NewWalletRepository(db))
|
||||
require.NoError(t, txm.WithTransaction(context.Background(), func(ctx context.Context) error {
|
||||
_, err := wallet.Credit(ctx, processor.WalletCreditInput{WalletEntry: processor.WalletEntry{
|
||||
CustomerID: customer, Currency: "POINT", Type: "MIGRATION", Amount: 50_000,
|
||||
ReferenceType: "LEGACY_POINTS", ReferenceID: uuid.New(), Description: "Saldo awal"}})
|
||||
return err
|
||||
}))
|
||||
|
||||
adminHandler, customerHandler := enakGameHandlers(db)
|
||||
auth := middleware.NewAuthMiddleware(nil)
|
||||
gin.SetMode(gin.TestMode)
|
||||
router := gin.New()
|
||||
for prefix, role := range map[string]string{"/manager": "manager", "/purchasing": "purchasing"} {
|
||||
role := role
|
||||
g := router.Group(prefix+"/enakgame", func(c *gin.Context) {
|
||||
ctx := context.WithValue(c.Request.Context(), appcontext.OrganizationIDKey, org.String())
|
||||
ctx = context.WithValue(ctx, appcontext.UserIDKey, admin.String())
|
||||
ctx = context.WithValue(ctx, appcontext.UserRoleKey, role)
|
||||
c.Request = c.Request.WithContext(ctx)
|
||||
})
|
||||
g.POST("/vouchers", auth.RequireLoyaltyManager(), adminHandler.CreateVoucher)
|
||||
g.PUT("/vouchers/:id", auth.RequireLoyaltyManager(), adminHandler.UpdateVoucher)
|
||||
g.POST("/vouchers/:id/codes", auth.RequireLoyaltyManager(), adminHandler.ImportVoucherCodes)
|
||||
g.GET("/vouchers/:id/codes", adminHandler.ListVoucherCodes)
|
||||
}
|
||||
c := router.Group("/customer/enakgame", func(c *gin.Context) { c.Set("customer_id", customer.String()) })
|
||||
c.GET("/vouchers", customerHandler.ListVouchers)
|
||||
c.POST("/vouchers/:id/redeem", customerHandler.RedeemVoucher)
|
||||
c.GET("/redemptions", customerHandler.ListRedemptions)
|
||||
|
||||
send := func(req *http.Request) (int, map[string]any) {
|
||||
t.Helper()
|
||||
rec := httptest.NewRecorder()
|
||||
router.ServeHTTP(rec, req)
|
||||
var out map[string]any
|
||||
require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &out), rec.Body.String())
|
||||
return rec.Code, out
|
||||
}
|
||||
call := func(method, path, body string, headers ...string) (int, map[string]any) {
|
||||
t.Helper()
|
||||
req := httptest.NewRequest(method, path, bytes.NewBufferString(body))
|
||||
for i := 0; i+1 < len(headers); i += 2 {
|
||||
req.Header.Set(headers[i], headers[i+1])
|
||||
}
|
||||
return send(req)
|
||||
}
|
||||
data := func(body map[string]any) map[string]any { return body["data"].(map[string]any) }
|
||||
|
||||
voucher := `{"name": "Kopi", "voucher_type": "FREE_ITEM", "face_value": 20000, "point_cost": 15000, "stock_mode": "CODE_POOL", "status": "ACTIVE"}`
|
||||
status, _ := call(http.MethodPost, "/purchasing/enakgame/vouchers", voucher)
|
||||
assert.Equal(t, http.StatusForbidden, status)
|
||||
status, body := call(http.MethodPost, "/manager/enakgame/vouchers", voucher)
|
||||
require.Equal(t, http.StatusOK, status, body)
|
||||
id := data(body)["id"].(string)
|
||||
status, _ = call(http.MethodPut, "/manager/enakgame/vouchers/"+id, `{"stock_mode": "STATIC", "stock": 5}`)
|
||||
assert.Equal(t, http.StatusBadRequest, status, "the stock mode stays")
|
||||
|
||||
// Codes as a multipart file, then the same as a plain body.
|
||||
var form bytes.Buffer
|
||||
w := multipart.NewWriter(&form)
|
||||
part, err := w.CreateFormFile("file", "codes.csv")
|
||||
require.NoError(t, err)
|
||||
_, _ = part.Write([]byte("code\nKOPI-1\nKOPI-2\n"))
|
||||
require.NoError(t, w.Close())
|
||||
req := httptest.NewRequest(http.MethodPost, "/manager/enakgame/vouchers/"+id+"/codes", &form)
|
||||
req.Header.Set("Content-Type", w.FormDataContentType())
|
||||
status, body = send(req)
|
||||
require.Equal(t, http.StatusOK, status, body)
|
||||
assert.EqualValues(t, 2, data(body)["imported"])
|
||||
status, body = call(http.MethodPost, "/manager/enakgame/vouchers/"+id+"/codes", "KOPI-2\nKOPI-3\n", "Content-Type", "text/csv")
|
||||
require.Equal(t, http.StatusOK, status, body)
|
||||
assert.EqualValues(t, 1, data(body)["imported"])
|
||||
assert.Equal(t, []any{"KOPI-2"}, data(body)["duplicates"])
|
||||
status, body = call(http.MethodGet, "/manager/enakgame/vouchers/"+id+"/codes", "")
|
||||
require.Equal(t, http.StatusOK, status, body)
|
||||
assert.Equal(t, map[string]any{"AVAILABLE": float64(3)}, data(body)["counts"])
|
||||
|
||||
status, body = call(http.MethodGet, "/customer/enakgame/vouchers", "")
|
||||
require.Equal(t, http.StatusOK, status, body)
|
||||
require.Len(t, body["data"], 1)
|
||||
assert.EqualValues(t, 3, body["data"].([]any)[0].(map[string]any)["available"])
|
||||
|
||||
redeem := "/customer/enakgame/vouchers/" + id + "/redeem"
|
||||
status, body = call(http.MethodPost, redeem, `{"pin": "482913"}`)
|
||||
assert.Equal(t, http.StatusBadRequest, status, "Idempotency-Key is required")
|
||||
status, body = call(http.MethodPost, redeem, `{}`, "Idempotency-Key", "r1")
|
||||
assert.Equal(t, http.StatusBadRequest, status, "the PIN is required")
|
||||
status, body = call(http.MethodPost, redeem, `{"pin": "000000"}`, "Idempotency-Key", "r1")
|
||||
assert.Equal(t, http.StatusBadRequest, status)
|
||||
assert.Equal(t, "PIN_INVALID", body["errors"].([]any)[0].(map[string]any)["code"])
|
||||
status, body = call(http.MethodPost, redeem, `{"pin": "482913"}`, "Idempotency-Key", "r1")
|
||||
require.Equal(t, http.StatusOK, status, body)
|
||||
code := data(body)["code"]
|
||||
assert.NotEmpty(t, code)
|
||||
assert.EqualValues(t, 35_000, data(body)["point_balance"])
|
||||
status, body = call(http.MethodPost, redeem, `{"pin": "482913"}`, "Idempotency-Key", "r1")
|
||||
require.Equal(t, http.StatusOK, status, body)
|
||||
assert.Equal(t, code, data(body)["code"])
|
||||
assert.Equal(t, true, data(body)["replayed"])
|
||||
status, body = call(http.MethodPost, redeem, `{"pin": "482913"}`, "Idempotency-Key", "r2")
|
||||
require.Equal(t, http.StatusOK, status, body)
|
||||
status, body = call(http.MethodPost, redeem, `{"pin": "482913"}`, "Idempotency-Key", "r3")
|
||||
require.Equal(t, http.StatusOK, status, body)
|
||||
assert.EqualValues(t, 5_000, data(body)["point_balance"])
|
||||
status, _ = call(http.MethodPost, redeem, `{"pin": "482913"}`, "Idempotency-Key", "r5")
|
||||
assert.Equal(t, http.StatusBadRequest, status, "out of codes and of EnakPoint")
|
||||
status, _ = call(http.MethodPost, "/customer/enakgame/vouchers/"+uuid.NewString()+"/redeem", `{"pin": "482913"}`, "Idempotency-Key", "r4")
|
||||
assert.Equal(t, http.StatusNotFound, status)
|
||||
|
||||
status, body = call(http.MethodGet, "/customer/enakgame/redemptions", "")
|
||||
require.Equal(t, http.StatusOK, status, body)
|
||||
assert.EqualValues(t, 3, data(body)["pagination"].(map[string]any)["total_count"])
|
||||
}
|
||||
|
||||
// Drives /marketing/enakgame/events over HTTP, and the events on the customer's game
|
||||
// list (docs/rfc-enakgame.md §11).
|
||||
func TestEnakGameEventEndpoints_AgainstPostgres(t *testing.T) {
|
||||
dsn := os.Getenv("TEST_DATABASE_URL")
|
||||
if dsn == "" {
|
||||
t.Skip("TEST_DATABASE_URL not set")
|
||||
}
|
||||
applogger.Setup("fatal", "json")
|
||||
db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{Logger: logger.Default.LogMode(logger.Silent)})
|
||||
require.NoError(t, err)
|
||||
org, admin, customer := uuid.New(), uuid.New(), uuid.New()
|
||||
require.NoError(t, db.Exec(`INSERT INTO organizations (id, name, plan_type) VALUES (?, 'event http', 'basic')`, org).Error)
|
||||
require.NoError(t, db.Exec(`INSERT INTO customers (id, organization_id, name) VALUES (?, ?, 'Budi')`, customer, org).Error)
|
||||
t.Cleanup(func() {
|
||||
for _, q := range []string{
|
||||
`DELETE FROM audit_logs WHERE organization_id = ?`,
|
||||
`DELETE FROM game_event_games WHERE event_id IN (SELECT id FROM game_events WHERE organization_id = ?)`,
|
||||
`DELETE FROM game_events WHERE organization_id = ?`,
|
||||
`DELETE FROM game_budgets WHERE organization_id = ?`,
|
||||
`DELETE FROM games WHERE organization_id = ?`,
|
||||
`DELETE FROM customers WHERE organization_id = ?`,
|
||||
`DELETE FROM organizations WHERE id = ?`,
|
||||
} {
|
||||
db.Exec(q, org)
|
||||
}
|
||||
})
|
||||
adminHandler, customerHandler := enakGameHandlers(db)
|
||||
auth := middleware.NewAuthMiddleware(nil)
|
||||
gin.SetMode(gin.TestMode)
|
||||
router := gin.New()
|
||||
for prefix, role := range map[string]string{"/manager": "manager", "/purchasing": "purchasing"} {
|
||||
role := role
|
||||
g := router.Group(prefix+"/enakgame", func(c *gin.Context) {
|
||||
ctx := context.WithValue(c.Request.Context(), appcontext.OrganizationIDKey, org.String())
|
||||
ctx = context.WithValue(ctx, appcontext.UserIDKey, admin.String())
|
||||
ctx = context.WithValue(ctx, appcontext.UserRoleKey, role)
|
||||
c.Request = c.Request.WithContext(ctx)
|
||||
})
|
||||
g.POST("/games", adminHandler.CreateGame)
|
||||
g.POST("/budgets", auth.RequireLoyaltyManager(), adminHandler.CreateBudget)
|
||||
g.POST("/events", auth.RequireLoyaltyManager(), adminHandler.CreateEvent)
|
||||
g.PUT("/events/:id", auth.RequireLoyaltyManager(), adminHandler.UpdateEvent)
|
||||
g.GET("/events", adminHandler.ListEvents)
|
||||
}
|
||||
router.GET("/customer/enakgame/games", func(c *gin.Context) { c.Set("customer_id", customer.String()) }, customerHandler.ListGames)
|
||||
call := func(method, path, body string) (int, map[string]any) {
|
||||
t.Helper()
|
||||
rec := httptest.NewRecorder()
|
||||
router.ServeHTTP(rec, httptest.NewRequest(method, path, bytes.NewBufferString(body)))
|
||||
var out map[string]any
|
||||
require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &out), rec.Body.String())
|
||||
return rec.Code, out
|
||||
}
|
||||
data := func(body map[string]any) map[string]any { return body["data"].(map[string]any) }
|
||||
|
||||
status, body := call(http.MethodPost, "/manager/enakgame/games", `{"name": "Runner", "slug": "runner", "entry_cost": 1, "status": "ACTIVE"}`)
|
||||
require.Equal(t, http.StatusOK, status, body)
|
||||
gameID := data(body)["id"].(string)
|
||||
status, body = call(http.MethodPost, "/manager/enakgame/budgets", `{"scope": "EVENT", "name": "Ramadan", "period_start": "2026-01-01", "period_end": "2030-12-31", "amount": 5000000}`)
|
||||
require.Equal(t, http.StatusOK, status, body)
|
||||
budgetID := data(body)["id"].(string)
|
||||
|
||||
start := time.Now().Add(-time.Hour).UTC().Format(time.RFC3339)
|
||||
end := time.Now().Add(48 * time.Hour).UTC().Format(time.RFC3339)
|
||||
event := `{"name": "Ramadan", "slug": "ramadan", "start_at": "` + start + `", "end_at": "` + end + `", "multiplier": 2,
|
||||
"budget_id": "` + budgetID + `", "game_ids": ["` + gameID + `"], "status": "ACTIVE"}`
|
||||
status, _ = call(http.MethodPost, "/purchasing/enakgame/events", event)
|
||||
assert.Equal(t, http.StatusForbidden, status)
|
||||
status, body = call(http.MethodPost, "/manager/enakgame/events", event)
|
||||
require.Equal(t, http.StatusOK, status, body)
|
||||
eventID := data(body)["id"].(string)
|
||||
status, _ = call(http.MethodPut, "/manager/enakgame/events/"+eventID, `{"multipler": 3}`)
|
||||
assert.Equal(t, http.StatusBadRequest, status, "a misspelt field is refused")
|
||||
status, body = call(http.MethodPut, "/manager/enakgame/events/"+eventID, `{"bonus": 5}`)
|
||||
require.Equal(t, http.StatusOK, status, body)
|
||||
assert.EqualValues(t, 2, data(body)["multiplier"], "kept")
|
||||
assert.EqualValues(t, 5, data(body)["bonus"])
|
||||
status, body = call(http.MethodGet, "/purchasing/enakgame/events?status=active", "")
|
||||
require.Equal(t, http.StatusOK, status, body)
|
||||
assert.EqualValues(t, 1, data(body)["pagination"].(map[string]any)["total_count"])
|
||||
|
||||
status, body = call(http.MethodGet, "/customer/enakgame/games", "")
|
||||
require.Equal(t, http.StatusOK, status, body)
|
||||
games := body["data"].([]any)
|
||||
require.Len(t, games, 1)
|
||||
events := games[0].(map[string]any)["events"].([]any)
|
||||
require.Len(t, events, 1)
|
||||
assert.Equal(t, "Ramadan", events[0].(map[string]any)["name"])
|
||||
assert.EqualValues(t, 5, events[0].(map[string]any)["bonus"])
|
||||
assert.NotContains(t, events[0], "budget_id", "the budget stays internal")
|
||||
}
|
||||
|
||||
// EG-1001: the admin steps of docs/enakgame-spin.md make a spin wheel, and a customer
|
||||
// plays it through /customer/enakgame/sessions, over HTTP down to Postgres.
|
||||
func TestEnakGameSpin_AgainstPostgres(t *testing.T) {
|
||||
dsn := os.Getenv("TEST_DATABASE_URL")
|
||||
if dsn == "" {
|
||||
t.Skip("TEST_DATABASE_URL not set")
|
||||
}
|
||||
applogger.Setup("fatal", "json")
|
||||
db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{Logger: logger.Default.LogMode(logger.Silent)})
|
||||
require.NoError(t, err)
|
||||
|
||||
org, admin, customer := uuid.New(), uuid.New(), uuid.New()
|
||||
require.NoError(t, db.Exec(`INSERT INTO organizations (id, name, plan_type) VALUES (?, 'enakgame spin', 'basic')`, org).Error)
|
||||
require.NoError(t, db.Exec(`INSERT INTO customers (id, organization_id, name) VALUES (?, ?, 'Budi')`, customer, org).Error)
|
||||
t.Cleanup(func() {
|
||||
for _, q := range []string{
|
||||
`DELETE FROM audit_logs WHERE organization_id = ?`,
|
||||
`DELETE FROM game_reward_counters WHERE organization_id = ?`,
|
||||
`DELETE FROM game_session_rewards WHERE session_id IN (SELECT id FROM game_sessions WHERE organization_id = ?)`,
|
||||
`DELETE FROM game_sessions WHERE organization_id = ?`,
|
||||
`DELETE FROM wallet_lot_allocations WHERE lot_id IN (SELECT id FROM wallet_lots WHERE organization_id = ?)`,
|
||||
`DELETE FROM wallet_lots WHERE organization_id = ?`,
|
||||
`DELETE FROM wallet_transactions WHERE organization_id = ?`,
|
||||
`DELETE FROM customer_wallets WHERE organization_id = ?`,
|
||||
`DELETE FROM game_reward_configs WHERE organization_id = ?`,
|
||||
`DELETE FROM game_budgets WHERE organization_id = ?`,
|
||||
`DELETE FROM games WHERE organization_id = ?`,
|
||||
`DELETE FROM customers WHERE organization_id = ?`,
|
||||
`DELETE FROM organizations WHERE id = ?`,
|
||||
} {
|
||||
db.Exec(q, org)
|
||||
}
|
||||
})
|
||||
|
||||
txm := repository.NewTxManager(db)
|
||||
wallet := processor.NewWalletProcessor(repository.NewWalletRepository(db))
|
||||
require.NoError(t, txm.WithTransaction(context.Background(), func(ctx context.Context) error {
|
||||
_, err := wallet.Credit(ctx, processor.WalletCreditInput{WalletEntry: processor.WalletEntry{
|
||||
CustomerID: customer, Currency: "COIN", Type: "MIGRATION", Amount: 20,
|
||||
ReferenceType: "LEGACY_TOKENS", ReferenceID: uuid.New(), Description: "Saldo awal"}})
|
||||
return err
|
||||
}))
|
||||
|
||||
adminHandler, customerHandler := enakGameHandlers(db)
|
||||
gin.SetMode(gin.TestMode)
|
||||
router := gin.New()
|
||||
m := router.Group("/marketing/enakgame", func(c *gin.Context) {
|
||||
ctx := context.WithValue(c.Request.Context(), appcontext.OrganizationIDKey, org.String())
|
||||
ctx = context.WithValue(ctx, appcontext.UserIDKey, admin.String())
|
||||
ctx = context.WithValue(ctx, appcontext.UserRoleKey, "manager")
|
||||
c.Request = c.Request.WithContext(ctx)
|
||||
})
|
||||
m.POST("/games", adminHandler.CreateGame)
|
||||
m.POST("/games/:id/reward-configs", adminHandler.CreateRewardConfig)
|
||||
m.POST("/reward-configs/:id/activate", adminHandler.ActivateRewardConfig)
|
||||
m.POST("/budgets", adminHandler.CreateBudget)
|
||||
c := router.Group("/customer/enakgame", func(c *gin.Context) { c.Set("customer_id", customer.String()) })
|
||||
c.GET("/games", customerHandler.ListGames)
|
||||
c.POST("/sessions", customerHandler.StartSession)
|
||||
c.POST("/sessions/:id/complete", customerHandler.CompleteSession)
|
||||
|
||||
call := func(method, path, body string, headers ...string) map[string]any {
|
||||
t.Helper()
|
||||
req := httptest.NewRequest(method, path, bytes.NewBufferString(body))
|
||||
for i := 0; i+1 < len(headers); i += 2 {
|
||||
req.Header.Set(headers[i], headers[i+1])
|
||||
}
|
||||
rec := httptest.NewRecorder()
|
||||
router.ServeHTTP(rec, req)
|
||||
var out map[string]any
|
||||
require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &out), rec.Body.String())
|
||||
require.Equal(t, http.StatusOK, rec.Code, out)
|
||||
return out["data"].(map[string]any)
|
||||
}
|
||||
|
||||
// The admin steps.
|
||||
game := call(http.MethodPost, "/marketing/enakgame/games",
|
||||
`{"name": "Spin Harian", "slug": "spin", "type": "SPIN", "entry_cost": 5, "status": "ACTIVE"}`)
|
||||
gameID := game["id"].(string)
|
||||
config := call(http.MethodPost, "/marketing/enakgame/games/"+gameID+"/reward-configs", `{"reward_type": "PROBABILITY", "max_reward": 50,
|
||||
"rules": {"table": [
|
||||
{"weight": 50, "amount": 0, "label": "Zonk"},
|
||||
{"weight": 30, "amount": 3, "label": "3 Coin"},
|
||||
{"weight": 15, "amount": 10, "label": "10 Coin"},
|
||||
{"weight": 5, "amount": 50, "label": "Jackpot"}]}}`)
|
||||
call(http.MethodPost, "/marketing/enakgame/reward-configs/"+config["id"].(string)+"/activate", `{}`)
|
||||
now := time.Now().In(time.FixedZone("WIB", 7*3600))
|
||||
first := time.Date(now.Year(), now.Month(), 1, 0, 0, 0, 0, time.UTC)
|
||||
call(http.MethodPost, "/marketing/enakgame/budgets", `{"scope": "GLOBAL", "name": "Bulan ini", "period_start": "`+
|
||||
first.Format("2006-01-02")+`", "period_end": "`+first.AddDate(0, 1, -1).Format("2006-01-02")+`", "amount": 1000000}`)
|
||||
|
||||
// The wheel shows the segments, never their odds.
|
||||
req := httptest.NewRequest(http.MethodGet, "/customer/enakgame/games", nil)
|
||||
rec := httptest.NewRecorder()
|
||||
router.ServeHTTP(rec, req)
|
||||
require.Equal(t, http.StatusOK, rec.Code, rec.Body.String())
|
||||
var listed struct {
|
||||
Data []struct {
|
||||
ID string `json:"id"`
|
||||
Prizes []struct {
|
||||
Entry int `json:"entry"`
|
||||
Label *string `json:"label"`
|
||||
Amount int64 `json:"amount"`
|
||||
} `json:"prizes"`
|
||||
} `json:"data"`
|
||||
}
|
||||
require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &listed))
|
||||
require.Len(t, listed.Data, 1)
|
||||
require.Len(t, listed.Data[0].Prizes, 4)
|
||||
assert.Equal(t, "Jackpot", *listed.Data[0].Prizes[3].Label)
|
||||
assert.NotContains(t, rec.Body.String(), "weight")
|
||||
|
||||
// Two spins: each lands on a listed segment and pays what it shows.
|
||||
balance := int64(20)
|
||||
for _, key := range []string{"spin-1", "spin-2"} {
|
||||
started := call(http.MethodPost, "/customer/enakgame/sessions", `{"game_id": "`+gameID+`"}`, "Idempotency-Key", key)
|
||||
balance -= 5
|
||||
assert.EqualValues(t, balance, started["coin_balance"])
|
||||
done := call(http.MethodPost, "/customer/enakgame/sessions/"+started["session_id"].(string)+"/complete", `{}`)
|
||||
prize := done["prize"].(map[string]any)
|
||||
entry := int(prize["entry"].(float64))
|
||||
require.True(t, entry >= 1 && entry <= 4, prize)
|
||||
segment := listed.Data[0].Prizes[entry-1]
|
||||
assert.Equal(t, *segment.Label, prize["label"])
|
||||
assert.EqualValues(t, segment.Amount, prize["amount"])
|
||||
assert.EqualValues(t, segment.Amount, done["reward_total"])
|
||||
balance += segment.Amount
|
||||
assert.EqualValues(t, balance, done["coin_balance"])
|
||||
}
|
||||
}
|
||||
@@ -1,14 +1,8 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"apskel-pos-be/internal/constants"
|
||||
"apskel-pos-be/internal/contract"
|
||||
"apskel-pos-be/internal/logger"
|
||||
"apskel-pos-be/internal/service"
|
||||
"apskel-pos-be/internal/util"
|
||||
"apskel-pos-be/internal/validator"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
type GamificationHandler struct {
|
||||
@@ -25,32 +19,3 @@ func NewGamificationHandler(
|
||||
gamificationValidator: gamificationValidator,
|
||||
}
|
||||
}
|
||||
|
||||
// Play Game Handler
|
||||
func (h *GamificationHandler) PlayGame(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
var req contract.PlayGameRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
logger.FromContext(c.Request.Context()).WithError(err).Error("GamificationHandler::PlayGame -> request binding failed")
|
||||
validationResponseError := contract.NewResponseError(constants.MissingFieldErrorCode, constants.RequestEntity, err.Error())
|
||||
util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{validationResponseError}), "GamificationHandler::PlayGame")
|
||||
return
|
||||
}
|
||||
|
||||
validationError, validationErrorCode := h.gamificationValidator.ValidatePlayGameRequest(&req)
|
||||
if validationError != nil {
|
||||
logger.FromContext(c.Request.Context()).WithError(validationError).Error("GamificationHandler::PlayGame -> request validation failed")
|
||||
validationResponseError := contract.NewResponseError(validationErrorCode, constants.RequestEntity, validationError.Error())
|
||||
util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{validationResponseError}), "GamificationHandler::PlayGame")
|
||||
return
|
||||
}
|
||||
|
||||
response, err := h.gamificationService.PlayGame(ctx, &req)
|
||||
if err != nil {
|
||||
logger.FromContext(c.Request.Context()).WithError(err).Error("GamificationHandler::PlayGame -> service call failed")
|
||||
util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{contract.NewResponseError(constants.InternalServerErrorCode, constants.GameEntity, err.Error())}), "GamificationHandler::PlayGame")
|
||||
return
|
||||
}
|
||||
|
||||
util.HandleResponse(c.Writer, c.Request, contract.BuildSuccessResponse(response), "GamificationHandler::PlayGame")
|
||||
}
|
||||
|
||||
@@ -168,410 +168,6 @@ func (h *GamificationHandler) GetTierByPoints(c *gin.Context) {
|
||||
util.HandleResponse(c.Writer, c.Request, contract.BuildSuccessResponse(response), "GamificationHandler::GetTierByPoints")
|
||||
}
|
||||
|
||||
// Game Handlers
|
||||
func (h *GamificationHandler) CreateGame(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
var req contract.CreateGameRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
logger.FromContext(c.Request.Context()).WithError(err).Error("GamificationHandler::CreateGame -> request binding failed")
|
||||
validationResponseError := contract.NewResponseError(constants.MissingFieldErrorCode, constants.RequestEntity, err.Error())
|
||||
util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{validationResponseError}), "GamificationHandler::CreateGame")
|
||||
return
|
||||
}
|
||||
|
||||
validationError, validationErrorCode := h.gamificationValidator.ValidateCreateGameRequest(&req)
|
||||
if validationError != nil {
|
||||
logger.FromContext(c.Request.Context()).WithError(validationError).Error("GamificationHandler::CreateGame -> request validation failed")
|
||||
validationResponseError := contract.NewResponseError(validationErrorCode, constants.RequestEntity, validationError.Error())
|
||||
util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{validationResponseError}), "GamificationHandler::CreateGame")
|
||||
return
|
||||
}
|
||||
|
||||
response, err := h.gamificationService.CreateGame(ctx, &req)
|
||||
if err != nil {
|
||||
logger.FromContext(c.Request.Context()).WithError(err).Error("GamificationHandler::CreateGame -> service call failed")
|
||||
util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{contract.NewResponseError(constants.InternalServerErrorCode, constants.GameEntity, err.Error())}), "GamificationHandler::CreateGame")
|
||||
return
|
||||
}
|
||||
|
||||
util.HandleResponse(c.Writer, c.Request, contract.BuildSuccessResponse(response), "GamificationHandler::CreateGame")
|
||||
}
|
||||
|
||||
func (h *GamificationHandler) GetGame(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
idStr := c.Param("id")
|
||||
id, err := uuid.Parse(idStr)
|
||||
if err != nil {
|
||||
logger.FromContext(c.Request.Context()).WithError(err).Error("GamificationHandler::GetGame -> invalid ID")
|
||||
validationResponseError := contract.NewResponseError(constants.InvalidFieldErrorCode, constants.GameEntity, "Invalid ID format")
|
||||
util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{validationResponseError}), "GamificationHandler::GetGame")
|
||||
return
|
||||
}
|
||||
|
||||
response, err := h.gamificationService.GetGame(ctx, id)
|
||||
if err != nil {
|
||||
logger.FromContext(c.Request.Context()).WithError(err).Error("GamificationHandler::GetGame -> service call failed")
|
||||
util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{contract.NewResponseError(constants.InternalServerErrorCode, constants.GameEntity, err.Error())}), "GamificationHandler::GetGame")
|
||||
return
|
||||
}
|
||||
|
||||
util.HandleResponse(c.Writer, c.Request, contract.BuildSuccessResponse(response), "GamificationHandler::GetGame")
|
||||
}
|
||||
|
||||
func (h *GamificationHandler) ListGames(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
var req contract.ListGamesRequest
|
||||
if err := c.ShouldBindQuery(&req); err != nil {
|
||||
logger.FromContext(c.Request.Context()).WithError(err).Error("GamificationHandler::ListGames -> request binding failed")
|
||||
validationResponseError := contract.NewResponseError(constants.MissingFieldErrorCode, constants.RequestEntity, err.Error())
|
||||
util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{validationResponseError}), "GamificationHandler::ListGames")
|
||||
return
|
||||
}
|
||||
|
||||
validationError, validationErrorCode := h.gamificationValidator.ValidateListGamesRequest(&req)
|
||||
if validationError != nil {
|
||||
logger.FromContext(c.Request.Context()).WithError(validationError).Error("GamificationHandler::ListGames -> request validation failed")
|
||||
validationResponseError := contract.NewResponseError(validationErrorCode, constants.RequestEntity, validationError.Error())
|
||||
util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{validationResponseError}), "GamificationHandler::ListGames")
|
||||
return
|
||||
}
|
||||
|
||||
response, err := h.gamificationService.ListGames(ctx, &req)
|
||||
if err != nil {
|
||||
logger.FromContext(c.Request.Context()).WithError(err).Error("GamificationHandler::ListGames -> service call failed")
|
||||
util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{contract.NewResponseError(constants.InternalServerErrorCode, constants.GameEntity, err.Error())}), "GamificationHandler::ListGames")
|
||||
return
|
||||
}
|
||||
|
||||
util.HandleResponse(c.Writer, c.Request, contract.BuildSuccessResponse(response), "GamificationHandler::ListGames")
|
||||
}
|
||||
|
||||
func (h *GamificationHandler) GetActiveGames(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
response, err := h.gamificationService.GetActiveGames(ctx)
|
||||
if err != nil {
|
||||
logger.FromContext(c.Request.Context()).WithError(err).Error("GamificationHandler::GetActiveGames -> service call failed")
|
||||
util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{contract.NewResponseError(constants.InternalServerErrorCode, constants.GameEntity, err.Error())}), "GamificationHandler::GetActiveGames")
|
||||
return
|
||||
}
|
||||
|
||||
util.HandleResponse(c.Writer, c.Request, contract.BuildSuccessResponse(response), "GamificationHandler::GetActiveGames")
|
||||
}
|
||||
|
||||
func (h *GamificationHandler) UpdateGame(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
idStr := c.Param("id")
|
||||
id, err := uuid.Parse(idStr)
|
||||
if err != nil {
|
||||
logger.FromContext(c.Request.Context()).WithError(err).Error("GamificationHandler::UpdateGame -> invalid ID")
|
||||
validationResponseError := contract.NewResponseError(constants.InvalidFieldErrorCode, constants.GameEntity, "Invalid ID format")
|
||||
util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{validationResponseError}), "GamificationHandler::UpdateGame")
|
||||
return
|
||||
}
|
||||
|
||||
var req contract.UpdateGameRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
logger.FromContext(c.Request.Context()).WithError(err).Error("GamificationHandler::UpdateGame -> request binding failed")
|
||||
validationResponseError := contract.NewResponseError(constants.MissingFieldErrorCode, constants.RequestEntity, err.Error())
|
||||
util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{validationResponseError}), "GamificationHandler::UpdateGame")
|
||||
return
|
||||
}
|
||||
|
||||
validationError, validationErrorCode := h.gamificationValidator.ValidateUpdateGameRequest(&req)
|
||||
if validationError != nil {
|
||||
logger.FromContext(c.Request.Context()).WithError(validationError).Error("GamificationHandler::UpdateGame -> request validation failed")
|
||||
validationResponseError := contract.NewResponseError(validationErrorCode, constants.RequestEntity, validationError.Error())
|
||||
util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{validationResponseError}), "GamificationHandler::UpdateGame")
|
||||
return
|
||||
}
|
||||
|
||||
response, err := h.gamificationService.UpdateGame(ctx, id, &req)
|
||||
if err != nil {
|
||||
logger.FromContext(c.Request.Context()).WithError(err).Error("GamificationHandler::UpdateGame -> service call failed")
|
||||
util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{contract.NewResponseError(constants.InternalServerErrorCode, constants.GameEntity, err.Error())}), "GamificationHandler::UpdateGame")
|
||||
return
|
||||
}
|
||||
|
||||
util.HandleResponse(c.Writer, c.Request, contract.BuildSuccessResponse(response), "GamificationHandler::UpdateGame")
|
||||
}
|
||||
|
||||
func (h *GamificationHandler) DeleteGame(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
idStr := c.Param("id")
|
||||
id, err := uuid.Parse(idStr)
|
||||
if err != nil {
|
||||
logger.FromContext(c.Request.Context()).WithError(err).Error("GamificationHandler::DeleteGame -> invalid ID")
|
||||
validationResponseError := contract.NewResponseError(constants.InvalidFieldErrorCode, constants.GameEntity, "Invalid ID format")
|
||||
util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{validationResponseError}), "GamificationHandler::DeleteGame")
|
||||
return
|
||||
}
|
||||
|
||||
err = h.gamificationService.DeleteGame(ctx, id)
|
||||
if err != nil {
|
||||
logger.FromContext(c.Request.Context()).WithError(err).Error("GamificationHandler::DeleteGame -> service call failed")
|
||||
util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{contract.NewResponseError(constants.InternalServerErrorCode, constants.GameEntity, err.Error())}), "GamificationHandler::DeleteGame")
|
||||
return
|
||||
}
|
||||
|
||||
util.HandleResponse(c.Writer, c.Request, contract.BuildSuccessResponse(nil), "GamificationHandler::DeleteGame")
|
||||
}
|
||||
|
||||
// Game Prize Handlers
|
||||
func (h *GamificationHandler) CreateGamePrize(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
var req contract.CreateGamePrizeRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
logger.FromContext(c.Request.Context()).WithError(err).Error("GamificationHandler::CreateGamePrize -> request binding failed")
|
||||
validationResponseError := contract.NewResponseError(constants.MissingFieldErrorCode, constants.RequestEntity, err.Error())
|
||||
util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{validationResponseError}), "GamificationHandler::CreateGamePrize")
|
||||
return
|
||||
}
|
||||
|
||||
validationError, validationErrorCode := h.gamificationValidator.ValidateCreateGamePrizeRequest(&req)
|
||||
if validationError != nil {
|
||||
logger.FromContext(c.Request.Context()).WithError(validationError).Error("GamificationHandler::CreateGamePrize -> request validation failed")
|
||||
validationResponseError := contract.NewResponseError(validationErrorCode, constants.RequestEntity, validationError.Error())
|
||||
util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{validationResponseError}), "GamificationHandler::CreateGamePrize")
|
||||
return
|
||||
}
|
||||
|
||||
response, err := h.gamificationService.CreateGamePrize(ctx, &req)
|
||||
if err != nil {
|
||||
logger.FromContext(c.Request.Context()).WithError(err).Error("GamificationHandler::CreateGamePrize -> service call failed")
|
||||
util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{contract.NewResponseError(constants.InternalServerErrorCode, constants.GamePrizeEntity, err.Error())}), "GamificationHandler::CreateGamePrize")
|
||||
return
|
||||
}
|
||||
|
||||
util.HandleResponse(c.Writer, c.Request, contract.BuildSuccessResponse(response), "GamificationHandler::CreateGamePrize")
|
||||
}
|
||||
|
||||
func (h *GamificationHandler) GetGamePrize(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
idStr := c.Param("id")
|
||||
id, err := uuid.Parse(idStr)
|
||||
if err != nil {
|
||||
logger.FromContext(c.Request.Context()).WithError(err).Error("GamificationHandler::GetGamePrize -> invalid ID")
|
||||
validationResponseError := contract.NewResponseError(constants.InvalidFieldErrorCode, constants.GamePrizeEntity, "Invalid ID format")
|
||||
util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{validationResponseError}), "GamificationHandler::GetGamePrize")
|
||||
return
|
||||
}
|
||||
|
||||
response, err := h.gamificationService.GetGamePrize(ctx, id)
|
||||
if err != nil {
|
||||
logger.FromContext(c.Request.Context()).WithError(err).Error("GamificationHandler::GetGamePrize -> service call failed")
|
||||
util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{contract.NewResponseError(constants.InternalServerErrorCode, constants.GamePrizeEntity, err.Error())}), "GamificationHandler::GetGamePrize")
|
||||
return
|
||||
}
|
||||
|
||||
util.HandleResponse(c.Writer, c.Request, contract.BuildSuccessResponse(response), "GamificationHandler::GetGamePrize")
|
||||
}
|
||||
|
||||
func (h *GamificationHandler) ListGamePrizes(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
var req contract.ListGamePrizesRequest
|
||||
if err := c.ShouldBindQuery(&req); err != nil {
|
||||
logger.FromContext(c.Request.Context()).WithError(err).Error("GamificationHandler::ListGamePrizes -> request binding failed")
|
||||
validationResponseError := contract.NewResponseError(constants.MissingFieldErrorCode, constants.RequestEntity, err.Error())
|
||||
util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{validationResponseError}), "GamificationHandler::ListGamePrizes")
|
||||
return
|
||||
}
|
||||
|
||||
validationError, validationErrorCode := h.gamificationValidator.ValidateListGamePrizesRequest(&req)
|
||||
if validationError != nil {
|
||||
logger.FromContext(c.Request.Context()).WithError(validationError).Error("GamificationHandler::ListGamePrizes -> request validation failed")
|
||||
validationResponseError := contract.NewResponseError(validationErrorCode, constants.RequestEntity, validationError.Error())
|
||||
util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{validationResponseError}), "GamificationHandler::ListGamePrizes")
|
||||
return
|
||||
}
|
||||
|
||||
response, err := h.gamificationService.ListGamePrizes(ctx, &req)
|
||||
if err != nil {
|
||||
logger.FromContext(c.Request.Context()).WithError(err).Error("GamificationHandler::ListGamePrizes -> service call failed")
|
||||
util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{contract.NewResponseError(constants.InternalServerErrorCode, constants.GamePrizeEntity, err.Error())}), "GamificationHandler::ListGamePrizes")
|
||||
return
|
||||
}
|
||||
|
||||
util.HandleResponse(c.Writer, c.Request, contract.BuildSuccessResponse(response), "GamificationHandler::ListGamePrizes")
|
||||
}
|
||||
|
||||
func (h *GamificationHandler) UpdateGamePrize(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
idStr := c.Param("id")
|
||||
id, err := uuid.Parse(idStr)
|
||||
if err != nil {
|
||||
logger.FromContext(c.Request.Context()).WithError(err).Error("GamificationHandler::UpdateGamePrize -> invalid ID")
|
||||
validationResponseError := contract.NewResponseError(constants.InvalidFieldErrorCode, constants.GamePrizeEntity, "Invalid ID format")
|
||||
util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{validationResponseError}), "GamificationHandler::UpdateGamePrize")
|
||||
return
|
||||
}
|
||||
|
||||
var req contract.UpdateGamePrizeRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
logger.FromContext(c.Request.Context()).WithError(err).Error("GamificationHandler::UpdateGamePrize -> request binding failed")
|
||||
validationResponseError := contract.NewResponseError(constants.MissingFieldErrorCode, constants.RequestEntity, err.Error())
|
||||
util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{validationResponseError}), "GamificationHandler::UpdateGamePrize")
|
||||
return
|
||||
}
|
||||
|
||||
validationError, validationErrorCode := h.gamificationValidator.ValidateUpdateGamePrizeRequest(&req)
|
||||
if validationError != nil {
|
||||
logger.FromContext(c.Request.Context()).WithError(validationError).Error("GamificationHandler::UpdateGamePrize -> request validation failed")
|
||||
validationResponseError := contract.NewResponseError(validationErrorCode, constants.RequestEntity, validationError.Error())
|
||||
util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{validationResponseError}), "GamificationHandler::UpdateGamePrize")
|
||||
return
|
||||
}
|
||||
|
||||
response, err := h.gamificationService.UpdateGamePrize(ctx, id, &req)
|
||||
if err != nil {
|
||||
logger.FromContext(c.Request.Context()).WithError(err).Error("GamificationHandler::UpdateGamePrize -> service call failed")
|
||||
util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{contract.NewResponseError(constants.InternalServerErrorCode, constants.GamePrizeEntity, err.Error())}), "GamificationHandler::UpdateGamePrize")
|
||||
return
|
||||
}
|
||||
|
||||
util.HandleResponse(c.Writer, c.Request, contract.BuildSuccessResponse(response), "GamificationHandler::UpdateGamePrize")
|
||||
}
|
||||
|
||||
func (h *GamificationHandler) DeleteGamePrize(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
idStr := c.Param("id")
|
||||
id, err := uuid.Parse(idStr)
|
||||
if err != nil {
|
||||
logger.FromContext(c.Request.Context()).WithError(err).Error("GamificationHandler::DeleteGamePrize -> invalid ID")
|
||||
validationResponseError := contract.NewResponseError(constants.InvalidFieldErrorCode, constants.GamePrizeEntity, "Invalid ID format")
|
||||
util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{validationResponseError}), "GamificationHandler::DeleteGamePrize")
|
||||
return
|
||||
}
|
||||
|
||||
err = h.gamificationService.DeleteGamePrize(ctx, id)
|
||||
if err != nil {
|
||||
logger.FromContext(c.Request.Context()).WithError(err).Error("GamificationHandler::DeleteGamePrize -> service call failed")
|
||||
util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{contract.NewResponseError(constants.InternalServerErrorCode, constants.GamePrizeEntity, err.Error())}), "GamificationHandler::DeleteGamePrize")
|
||||
return
|
||||
}
|
||||
|
||||
util.HandleResponse(c.Writer, c.Request, contract.BuildSuccessResponse(nil), "GamificationHandler::DeleteGamePrize")
|
||||
}
|
||||
|
||||
func (h *GamificationHandler) GetGamePrizesByGameID(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
gameIDStr := c.Param("game_id")
|
||||
gameID, err := uuid.Parse(gameIDStr)
|
||||
if err != nil {
|
||||
logger.FromContext(c.Request.Context()).WithError(err).Error("GamificationHandler::GetGamePrizesByGameID -> invalid game ID")
|
||||
validationResponseError := contract.NewResponseError(constants.InvalidFieldErrorCode, constants.GamePrizeEntity, "Invalid game ID format")
|
||||
util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{validationResponseError}), "GamificationHandler::GetGamePrizesByGameID")
|
||||
return
|
||||
}
|
||||
|
||||
response, err := h.gamificationService.GetGamePrizesByGameID(ctx, gameID)
|
||||
if err != nil {
|
||||
logger.FromContext(c.Request.Context()).WithError(err).Error("GamificationHandler::GetGamePrizesByGameID -> service call failed")
|
||||
util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{contract.NewResponseError(constants.InternalServerErrorCode, constants.GamePrizeEntity, err.Error())}), "GamificationHandler::GetGamePrizesByGameID")
|
||||
return
|
||||
}
|
||||
|
||||
util.HandleResponse(c.Writer, c.Request, contract.BuildSuccessResponse(response), "GamificationHandler::GetGamePrizesByGameID")
|
||||
}
|
||||
|
||||
func (h *GamificationHandler) GetAvailablePrizes(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
gameIDStr := c.Param("game_id")
|
||||
gameID, err := uuid.Parse(gameIDStr)
|
||||
if err != nil {
|
||||
logger.FromContext(c.Request.Context()).WithError(err).Error("GamificationHandler::GetAvailablePrizes -> invalid game ID")
|
||||
validationResponseError := contract.NewResponseError(constants.InvalidFieldErrorCode, constants.GamePrizeEntity, "Invalid game ID format")
|
||||
util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{validationResponseError}), "GamificationHandler::GetAvailablePrizes")
|
||||
return
|
||||
}
|
||||
|
||||
response, err := h.gamificationService.GetAvailablePrizes(ctx, gameID)
|
||||
if err != nil {
|
||||
logger.FromContext(c.Request.Context()).WithError(err).Error("GamificationHandler::GetAvailablePrizes -> service call failed")
|
||||
util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{contract.NewResponseError(constants.InternalServerErrorCode, constants.GamePrizeEntity, err.Error())}), "GamificationHandler::GetAvailablePrizes")
|
||||
return
|
||||
}
|
||||
|
||||
util.HandleResponse(c.Writer, c.Request, contract.BuildSuccessResponse(response), "GamificationHandler::GetAvailablePrizes")
|
||||
}
|
||||
|
||||
// Game Play Handlers
|
||||
func (h *GamificationHandler) CreateGamePlay(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
var req contract.CreateGamePlayRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
logger.FromContext(c.Request.Context()).WithError(err).Error("GamificationHandler::CreateGamePlay -> request binding failed")
|
||||
validationResponseError := contract.NewResponseError(constants.MissingFieldErrorCode, constants.RequestEntity, err.Error())
|
||||
util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{validationResponseError}), "GamificationHandler::CreateGamePlay")
|
||||
return
|
||||
}
|
||||
|
||||
validationError, validationErrorCode := h.gamificationValidator.ValidateCreateGamePlayRequest(&req)
|
||||
if validationError != nil {
|
||||
logger.FromContext(c.Request.Context()).WithError(validationError).Error("GamificationHandler::CreateGamePlay -> request validation failed")
|
||||
validationResponseError := contract.NewResponseError(validationErrorCode, constants.RequestEntity, validationError.Error())
|
||||
util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{validationResponseError}), "GamificationHandler::CreateGamePlay")
|
||||
return
|
||||
}
|
||||
|
||||
response, err := h.gamificationService.CreateGamePlay(ctx, &req)
|
||||
if err != nil {
|
||||
logger.FromContext(c.Request.Context()).WithError(err).Error("GamificationHandler::CreateGamePlay -> service call failed")
|
||||
util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{contract.NewResponseError(constants.InternalServerErrorCode, constants.GamePlayEntity, err.Error())}), "GamificationHandler::CreateGamePlay")
|
||||
return
|
||||
}
|
||||
|
||||
util.HandleResponse(c.Writer, c.Request, contract.BuildSuccessResponse(response), "GamificationHandler::CreateGamePlay")
|
||||
}
|
||||
|
||||
func (h *GamificationHandler) GetGamePlay(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
idStr := c.Param("id")
|
||||
id, err := uuid.Parse(idStr)
|
||||
if err != nil {
|
||||
logger.FromContext(c.Request.Context()).WithError(err).Error("GamificationHandler::GetGamePlay -> invalid ID")
|
||||
validationResponseError := contract.NewResponseError(constants.InvalidFieldErrorCode, constants.GamePlayEntity, "Invalid ID format")
|
||||
util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{validationResponseError}), "GamificationHandler::GetGamePlay")
|
||||
return
|
||||
}
|
||||
|
||||
response, err := h.gamificationService.GetGamePlay(ctx, id)
|
||||
if err != nil {
|
||||
logger.FromContext(c.Request.Context()).WithError(err).Error("GamificationHandler::GetGamePlay -> service call failed")
|
||||
util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{contract.NewResponseError(constants.InternalServerErrorCode, constants.GamePlayEntity, err.Error())}), "GamificationHandler::GetGamePlay")
|
||||
return
|
||||
}
|
||||
|
||||
util.HandleResponse(c.Writer, c.Request, contract.BuildSuccessResponse(response), "GamificationHandler::GetGamePlay")
|
||||
}
|
||||
|
||||
func (h *GamificationHandler) ListGamePlays(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
var req contract.ListGamePlaysRequest
|
||||
if err := c.ShouldBindQuery(&req); err != nil {
|
||||
logger.FromContext(c.Request.Context()).WithError(err).Error("GamificationHandler::ListGamePlays -> request binding failed")
|
||||
validationResponseError := contract.NewResponseError(constants.MissingFieldErrorCode, constants.RequestEntity, err.Error())
|
||||
util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{validationResponseError}), "GamificationHandler::ListGamePlays")
|
||||
return
|
||||
}
|
||||
|
||||
validationError, validationErrorCode := h.gamificationValidator.ValidateListGamePlaysRequest(&req)
|
||||
if validationError != nil {
|
||||
logger.FromContext(c.Request.Context()).WithError(validationError).Error("GamificationHandler::ListGamePlays -> request validation failed")
|
||||
validationResponseError := contract.NewResponseError(validationErrorCode, constants.RequestEntity, validationError.Error())
|
||||
util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{validationResponseError}), "GamificationHandler::ListGamePlays")
|
||||
return
|
||||
}
|
||||
|
||||
response, err := h.gamificationService.ListGamePlays(ctx, &req)
|
||||
if err != nil {
|
||||
logger.FromContext(c.Request.Context()).WithError(err).Error("GamificationHandler::ListGamePlays -> service call failed")
|
||||
util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{contract.NewResponseError(constants.InternalServerErrorCode, constants.GamePlayEntity, err.Error())}), "GamificationHandler::ListGamePlays")
|
||||
return
|
||||
}
|
||||
|
||||
util.HandleResponse(c.Writer, c.Request, contract.BuildSuccessResponse(response), "GamificationHandler::ListGamePlays")
|
||||
}
|
||||
|
||||
// Omset Tracker Handlers
|
||||
func (h *GamificationHandler) CreateOmsetTracker(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
|
||||
@@ -105,6 +105,7 @@ func TestOrganizationLoyaltySettingsEndpoints_AgainstPostgres(t *testing.T) {
|
||||
assert.Equal(t, map[string]any{"coin_amount": float64(1), "point_amount": float64(1)}, got["exchange"])
|
||||
assert.Equal(t, true, got["transfer"].(map[string]any)["enabled"])
|
||||
assert.Equal(t, "MONTH", got["point_expiry"].(map[string]any)["unit"])
|
||||
assert.Equal(t, map[string]any{"user_daily_limit": float64(0), "global_daily_limit": float64(0)}, got["enakgame"], "0 is no limit")
|
||||
impact := got["impact"].(map[string]any)
|
||||
assert.EqualValues(t, 50000, impact["outstanding_points"])
|
||||
assert.EqualValues(t, impact["point_rupiah_before"], impact["point_rupiah_after"])
|
||||
@@ -177,4 +178,17 @@ func TestOrganizationLoyaltySettingsEndpoints_AgainstPostgres(t *testing.T) {
|
||||
status, body = call(http.MethodGet, "/manager/loyalty-settings", "")
|
||||
require.Equal(t, http.StatusOK, status, body)
|
||||
assert.EqualValues(t, 100, data(body)["point_value"])
|
||||
|
||||
// The EnakGame limits (docs/rfc-enakgame.md §5.10) go through the same endpoint and
|
||||
// history.
|
||||
status, body = call(http.MethodPut, "/manager/loyalty-settings", `{"enakgame": {"user_daily_limit": 50, "global_daily_limit": 10000}}`)
|
||||
require.Equal(t, http.StatusOK, status, body)
|
||||
assert.Equal(t, map[string]any{"user_daily_limit": float64(50), "global_daily_limit": float64(10000)}, data(body)["enakgame"])
|
||||
var limits []struct{ Key, NewValue string }
|
||||
require.NoError(t, db.Raw(`SELECT key, new_value FROM loyalty_setting_changes WHERE organization_id = ? AND key LIKE 'enakgame.%' ORDER BY key`, org).Scan(&limits).Error)
|
||||
assert.Equal(t, []struct{ Key, NewValue string }{{"enakgame.limit.global_daily", "10000"}, {"enakgame.limit.user_daily", "50"}}, limits)
|
||||
status, _ = call(http.MethodPut, "/manager/loyalty-settings", `{"enakgame": {"user_daily_limit": -1}}`)
|
||||
assert.Equal(t, http.StatusBadRequest, status)
|
||||
status, _ = call(http.MethodPut, "/purchasing/loyalty-settings", `{"enakgame": {"user_daily_limit": 1}}`)
|
||||
assert.Equal(t, http.StatusForbidden, status)
|
||||
}
|
||||
|
||||
@@ -1,206 +0,0 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"strconv"
|
||||
|
||||
"apskel-pos-be/internal/constants"
|
||||
"apskel-pos-be/internal/contract"
|
||||
"apskel-pos-be/internal/logger"
|
||||
"apskel-pos-be/internal/service"
|
||||
"apskel-pos-be/internal/util"
|
||||
"apskel-pos-be/internal/validator"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
type RewardHandler struct {
|
||||
rewardService service.RewardService
|
||||
rewardValidator validator.RewardValidator
|
||||
}
|
||||
|
||||
func NewRewardHandler(rewardService service.RewardService, rewardValidator validator.RewardValidator) *RewardHandler {
|
||||
return &RewardHandler{
|
||||
rewardService: rewardService,
|
||||
rewardValidator: rewardValidator,
|
||||
}
|
||||
}
|
||||
|
||||
func (h *RewardHandler) CreateReward(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
|
||||
var req contract.CreateRewardRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
logger.FromContext(c.Request.Context()).WithError(err).Error("RewardHandler::CreateReward -> request binding failed")
|
||||
validationResponseError := contract.NewResponseError(constants.MissingFieldErrorCode, constants.RequestEntity, err.Error())
|
||||
util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{validationResponseError}), "RewardHandler::CreateReward")
|
||||
return
|
||||
}
|
||||
|
||||
validationError, validationErrorCode := h.rewardValidator.ValidateCreateRewardRequest(&req)
|
||||
if validationError != nil {
|
||||
logger.FromContext(c.Request.Context()).WithError(validationError).Error("RewardHandler::CreateReward -> request validation failed")
|
||||
validationResponseError := contract.NewResponseError(validationErrorCode, constants.RequestEntity, validationError.Error())
|
||||
util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{validationResponseError}), "RewardHandler::CreateReward")
|
||||
return
|
||||
}
|
||||
|
||||
response, err := h.rewardService.CreateReward(ctx, &req)
|
||||
if err != nil {
|
||||
logger.FromContext(c.Request.Context()).WithError(err).Error("RewardHandler::CreateReward -> service call failed")
|
||||
util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{contract.NewResponseError(constants.InternalServerErrorCode, constants.RewardEntity, err.Error())}), "RewardHandler::CreateReward")
|
||||
return
|
||||
}
|
||||
|
||||
util.HandleResponse(c.Writer, c.Request, contract.BuildSuccessResponse(response), "RewardHandler::CreateReward")
|
||||
}
|
||||
|
||||
func (h *RewardHandler) GetReward(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
|
||||
idStr := c.Param("id")
|
||||
if idStr == "" {
|
||||
logger.FromContext(c.Request.Context()).Error("RewardHandler::GetReward -> missing ID parameter")
|
||||
validationResponseError := contract.NewResponseError(constants.MissingFieldErrorCode, constants.RewardEntity, "ID parameter is required")
|
||||
util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{validationResponseError}), "RewardHandler::GetReward")
|
||||
return
|
||||
}
|
||||
|
||||
response, err := h.rewardService.GetReward(ctx, idStr)
|
||||
if err != nil {
|
||||
logger.FromContext(c.Request.Context()).WithError(err).Error("RewardHandler::GetReward -> service call failed")
|
||||
util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{contract.NewResponseError(constants.InternalServerErrorCode, constants.RewardEntity, err.Error())}), "RewardHandler::GetReward")
|
||||
return
|
||||
}
|
||||
|
||||
util.HandleResponse(c.Writer, c.Request, contract.BuildSuccessResponse(response), "RewardHandler::GetReward")
|
||||
}
|
||||
|
||||
func (h *RewardHandler) ListRewards(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
|
||||
var req contract.ListRewardsRequest
|
||||
if err := c.ShouldBindQuery(&req); err != nil {
|
||||
logger.FromContext(c.Request.Context()).WithError(err).Error("RewardHandler::ListRewards -> request binding failed")
|
||||
validationResponseError := contract.NewResponseError(constants.MissingFieldErrorCode, constants.RequestEntity, err.Error())
|
||||
util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{validationResponseError}), "RewardHandler::ListRewards")
|
||||
return
|
||||
}
|
||||
|
||||
validationError, validationErrorCode := h.rewardValidator.ValidateListRewardsRequest(&req)
|
||||
if validationError != nil {
|
||||
logger.FromContext(c.Request.Context()).WithError(validationError).Error("RewardHandler::ListRewards -> request validation failed")
|
||||
validationResponseError := contract.NewResponseError(validationErrorCode, constants.RequestEntity, validationError.Error())
|
||||
util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{validationResponseError}), "RewardHandler::ListRewards")
|
||||
return
|
||||
}
|
||||
|
||||
response, err := h.rewardService.ListRewards(ctx, &req)
|
||||
if err != nil {
|
||||
logger.FromContext(c.Request.Context()).WithError(err).Error("RewardHandler::ListRewards -> service call failed")
|
||||
util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{contract.NewResponseError(constants.InternalServerErrorCode, constants.RewardEntity, err.Error())}), "RewardHandler::ListRewards")
|
||||
return
|
||||
}
|
||||
|
||||
util.HandleResponse(c.Writer, c.Request, contract.BuildSuccessResponse(response), "RewardHandler::ListRewards")
|
||||
}
|
||||
|
||||
func (h *RewardHandler) UpdateReward(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
|
||||
var req contract.UpdateRewardRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
logger.FromContext(c.Request.Context()).WithError(err).Error("RewardHandler::UpdateReward -> request binding failed")
|
||||
validationResponseError := contract.NewResponseError(constants.MissingFieldErrorCode, constants.RequestEntity, err.Error())
|
||||
util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{validationResponseError}), "RewardHandler::UpdateReward")
|
||||
return
|
||||
}
|
||||
|
||||
validationError, validationErrorCode := h.rewardValidator.ValidateUpdateRewardRequest(&req)
|
||||
if validationError != nil {
|
||||
logger.FromContext(c.Request.Context()).WithError(validationError).Error("RewardHandler::UpdateReward -> request validation failed")
|
||||
validationResponseError := contract.NewResponseError(validationErrorCode, constants.RequestEntity, validationError.Error())
|
||||
util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{validationResponseError}), "RewardHandler::UpdateReward")
|
||||
return
|
||||
}
|
||||
|
||||
response, err := h.rewardService.UpdateReward(ctx, &req)
|
||||
if err != nil {
|
||||
logger.FromContext(c.Request.Context()).WithError(err).Error("RewardHandler::UpdateReward -> service call failed")
|
||||
util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{contract.NewResponseError(constants.InternalServerErrorCode, constants.RewardEntity, err.Error())}), "RewardHandler::UpdateReward")
|
||||
return
|
||||
}
|
||||
|
||||
util.HandleResponse(c.Writer, c.Request, contract.BuildSuccessResponse(response), "RewardHandler::UpdateReward")
|
||||
}
|
||||
|
||||
func (h *RewardHandler) DeleteReward(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
|
||||
idStr := c.Param("id")
|
||||
if idStr == "" {
|
||||
logger.FromContext(c.Request.Context()).Error("RewardHandler::DeleteReward -> missing ID parameter")
|
||||
validationResponseError := contract.NewResponseError(constants.MissingFieldErrorCode, constants.RewardEntity, "ID parameter is required")
|
||||
util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{validationResponseError}), "RewardHandler::DeleteReward")
|
||||
return
|
||||
}
|
||||
|
||||
err := h.rewardService.DeleteReward(ctx, idStr)
|
||||
if err != nil {
|
||||
logger.FromContext(c.Request.Context()).WithError(err).Error("RewardHandler::DeleteReward -> service call failed")
|
||||
util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{contract.NewResponseError(constants.InternalServerErrorCode, constants.RewardEntity, err.Error())}), "RewardHandler::DeleteReward")
|
||||
return
|
||||
}
|
||||
|
||||
util.HandleResponse(c.Writer, c.Request, contract.BuildSuccessResponse("Reward deleted successfully"), "RewardHandler::DeleteReward")
|
||||
}
|
||||
|
||||
func (h *RewardHandler) UpdateRewardStock(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
|
||||
idStr := c.Param("id")
|
||||
if idStr == "" {
|
||||
logger.FromContext(c.Request.Context()).Error("RewardHandler::UpdateRewardStock -> missing ID parameter")
|
||||
validationResponseError := contract.NewResponseError(constants.MissingFieldErrorCode, constants.RewardEntity, "ID parameter is required")
|
||||
util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{validationResponseError}), "RewardHandler::UpdateRewardStock")
|
||||
return
|
||||
}
|
||||
|
||||
stockStr := c.Param("stock")
|
||||
stock, err := strconv.Atoi(stockStr)
|
||||
if err != nil {
|
||||
logger.FromContext(c.Request.Context()).WithError(err).Error("RewardHandler::UpdateRewardStock -> invalid stock parameter")
|
||||
validationResponseError := contract.NewResponseError(constants.InvalidFieldErrorCode, constants.RewardEntity, "Invalid stock parameter")
|
||||
util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{validationResponseError}), "RewardHandler::UpdateRewardStock")
|
||||
return
|
||||
}
|
||||
|
||||
err = h.rewardService.UpdateRewardStock(ctx, idStr, stock)
|
||||
if err != nil {
|
||||
logger.FromContext(c.Request.Context()).WithError(err).Error("RewardHandler::UpdateRewardStock -> service call failed")
|
||||
util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{contract.NewResponseError(constants.InternalServerErrorCode, constants.RewardEntity, err.Error())}), "RewardHandler::UpdateRewardStock")
|
||||
return
|
||||
}
|
||||
|
||||
util.HandleResponse(c.Writer, c.Request, contract.BuildSuccessResponse("Reward stock updated successfully"), "RewardHandler::UpdateRewardStock")
|
||||
}
|
||||
|
||||
func (h *RewardHandler) GetRewardsByType(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
|
||||
rewardType := c.Param("type")
|
||||
if rewardType == "" {
|
||||
logger.FromContext(c.Request.Context()).Error("RewardHandler::GetRewardsByType -> missing type parameter")
|
||||
validationResponseError := contract.NewResponseError(constants.MissingFieldErrorCode, constants.RewardEntity, "Type parameter is required")
|
||||
util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{validationResponseError}), "RewardHandler::GetRewardsByType")
|
||||
return
|
||||
}
|
||||
|
||||
response, err := h.rewardService.GetRewardsByType(ctx, rewardType)
|
||||
if err != nil {
|
||||
logger.FromContext(c.Request.Context()).WithError(err).Error("RewardHandler::GetRewardsByType -> service call failed")
|
||||
util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{contract.NewResponseError(constants.InternalServerErrorCode, constants.RewardEntity, err.Error())}), "RewardHandler::GetRewardsByType")
|
||||
return
|
||||
}
|
||||
|
||||
util.HandleResponse(c.Writer, c.Request, contract.BuildSuccessResponse(response), "RewardHandler::GetRewardsByType")
|
||||
}
|
||||
@@ -1,71 +0,0 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"errors"
|
||||
|
||||
"apskel-pos-be/internal/constants"
|
||||
"apskel-pos-be/internal/contract"
|
||||
"apskel-pos-be/internal/mappers"
|
||||
"apskel-pos-be/internal/models"
|
||||
"apskel-pos-be/internal/processor"
|
||||
"apskel-pos-be/internal/service"
|
||||
"apskel-pos-be/internal/util"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
type SpinGameHandler struct {
|
||||
spinGameService service.SpinGameService
|
||||
}
|
||||
|
||||
func NewSpinGameHandler(spinGameService service.SpinGameService) *SpinGameHandler {
|
||||
return &SpinGameHandler{
|
||||
spinGameService: spinGameService,
|
||||
}
|
||||
}
|
||||
|
||||
// PlaySpinGame handles the spin game play request
|
||||
func (h *SpinGameHandler) PlaySpinGame(c *gin.Context) {
|
||||
// Get customer ID from JWT token (set by middleware)
|
||||
customerID, exists := c.Get("customer_id")
|
||||
if !exists {
|
||||
util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{
|
||||
contract.NewResponseError(constants.ValidationErrorCode, constants.SpinGameHandlerEntity, "Customer ID not found in context"),
|
||||
}), "SpinGameHandler::PlaySpinGame")
|
||||
return
|
||||
}
|
||||
|
||||
// Parse spin ID from request body
|
||||
var req contract.SpinGameRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{
|
||||
contract.NewResponseError(constants.ValidationErrorCode, constants.SpinGameHandlerEntity, err.Error()),
|
||||
}), "SpinGameHandler::PlaySpinGame")
|
||||
return
|
||||
}
|
||||
|
||||
// Convert to model
|
||||
modelReq := &models.SpinGameRequest{
|
||||
SpinID: req.SpinID,
|
||||
}
|
||||
|
||||
// Play the spin game
|
||||
response, err := h.spinGameService.PlaySpinGame(c.Request.Context(), customerID.(string), modelReq)
|
||||
if err != nil {
|
||||
// Not enough EnakCoin, an inactive game or a prize that just ran out is the
|
||||
// customer's to fix, not a server failure.
|
||||
code := constants.InternalServerErrorCode
|
||||
if errors.Is(err, processor.ErrGamePlayRefused) {
|
||||
code = constants.ValidationErrorCode
|
||||
}
|
||||
util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{
|
||||
contract.NewResponseError(code, constants.SpinGameHandlerEntity, err.Error()),
|
||||
}), "SpinGameHandler::PlaySpinGame")
|
||||
return
|
||||
}
|
||||
|
||||
// Convert model response to contract response
|
||||
contractResponse := mappers.SpinGameResponseModelToContract(response)
|
||||
|
||||
util.HandleResponse(c.Writer, c.Request, contract.BuildSuccessResponse(contractResponse.Data), "SpinGameHandler::PlaySpinGame")
|
||||
}
|
||||
@@ -186,7 +186,7 @@ func TestWalletAdminEndpoints_AgainstPostgres(t *testing.T) {
|
||||
// The customer's own history shows the adjustment too, with the reason in the
|
||||
// description and without the admin's identity fields.
|
||||
customerView := NewCustomerPointsHandler(service.NewCustomerPointsService(processor.NewCustomerPointsProcessor(
|
||||
processor.NewWalletQueryProcessor(queryRepo, processor.NewLoyaltySettingsProcessor(repository.NewLoyaltySettingsRepository(db), repository.NewTxManager(db))), nil)))
|
||||
processor.NewWalletQueryProcessor(queryRepo, processor.NewLoyaltySettingsProcessor(repository.NewLoyaltySettingsRepository(db), repository.NewTxManager(db))))))
|
||||
crouter := gin.New()
|
||||
crouter.GET("/wallet/transactions", func(c *gin.Context) { c.Set("customer_id", customer.String()) }, customerView.GetCustomerWalletTransactions)
|
||||
rec := httptest.NewRecorder()
|
||||
|
||||
@@ -1,58 +0,0 @@
|
||||
package mappers
|
||||
|
||||
import (
|
||||
"apskel-pos-be/internal/entities"
|
||||
"apskel-pos-be/internal/models"
|
||||
)
|
||||
|
||||
// ToGameResponse converts a game entity to a game response
|
||||
func ToGameResponse(game *entities.Game) *models.GameResponse {
|
||||
if game == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
return &models.GameResponse{
|
||||
ID: game.ID,
|
||||
Name: game.Name,
|
||||
Type: string(game.Type),
|
||||
IsActive: game.IsActive,
|
||||
Metadata: game.Metadata,
|
||||
CreatedAt: game.CreatedAt,
|
||||
UpdatedAt: game.UpdatedAt,
|
||||
}
|
||||
}
|
||||
|
||||
// ToGameResponses converts a slice of game entities to game responses
|
||||
func ToGameResponses(games []entities.Game) []models.GameResponse {
|
||||
responses := make([]models.GameResponse, len(games))
|
||||
for i, game := range games {
|
||||
responses[i] = *ToGameResponse(&game)
|
||||
}
|
||||
return responses
|
||||
}
|
||||
|
||||
// ToGameEntity converts a create game request to a game entity
|
||||
func ToGameEntity(req *models.CreateGameRequest) *entities.Game {
|
||||
return &entities.Game{
|
||||
Name: req.Name,
|
||||
Type: entities.GameType(req.Type),
|
||||
IsActive: req.IsActive,
|
||||
Metadata: req.Metadata,
|
||||
}
|
||||
}
|
||||
|
||||
// UpdateGameEntity updates a game entity with update request data
|
||||
func UpdateGameEntity(game *entities.Game, req *models.UpdateGameRequest) {
|
||||
if req.Name != nil {
|
||||
game.Name = *req.Name
|
||||
}
|
||||
if req.Type != nil {
|
||||
game.Type = entities.GameType(*req.Type)
|
||||
}
|
||||
if req.IsActive != nil {
|
||||
game.IsActive = *req.IsActive
|
||||
}
|
||||
if req.Metadata != nil {
|
||||
game.Metadata = req.Metadata
|
||||
}
|
||||
}
|
||||
@@ -1,54 +0,0 @@
|
||||
package mappers
|
||||
|
||||
import (
|
||||
"apskel-pos-be/internal/entities"
|
||||
"apskel-pos-be/internal/models"
|
||||
)
|
||||
|
||||
// ToGamePlayResponse converts a game play entity to a game play response
|
||||
func ToGamePlayResponse(gamePlay *entities.GamePlay) *models.GamePlayResponse {
|
||||
if gamePlay == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
return &models.GamePlayResponse{
|
||||
ID: gamePlay.ID,
|
||||
GameID: gamePlay.GameID,
|
||||
CustomerID: gamePlay.CustomerID,
|
||||
PrizeID: gamePlay.PrizeID,
|
||||
CoinsUsed: gamePlay.CoinsUsed,
|
||||
RandomSeed: gamePlay.RandomSeed,
|
||||
CreatedAt: gamePlay.CreatedAt,
|
||||
Game: ToGameResponse(&gamePlay.Game),
|
||||
Customer: ToCustomerResponse(&gamePlay.Customer),
|
||||
Prize: ToGamePrizeResponse(gamePlay.Prize),
|
||||
}
|
||||
}
|
||||
|
||||
// ToGamePlayResponses converts a slice of game play entities to game play responses
|
||||
func ToGamePlayResponses(gamePlays []entities.GamePlay) []models.GamePlayResponse {
|
||||
responses := make([]models.GamePlayResponse, len(gamePlays))
|
||||
for i, gp := range gamePlays {
|
||||
responses[i] = *ToGamePlayResponse(&gp)
|
||||
}
|
||||
return responses
|
||||
}
|
||||
|
||||
// ToGamePlayResponsesFromPointers converts a slice of game play entity pointers to game play responses
|
||||
func ToGamePlayResponsesFromPointers(gamePlays []*entities.GamePlay) []models.GamePlayResponse {
|
||||
responses := make([]models.GamePlayResponse, len(gamePlays))
|
||||
for i, gp := range gamePlays {
|
||||
responses[i] = *ToGamePlayResponse(gp)
|
||||
}
|
||||
return responses
|
||||
}
|
||||
|
||||
// ToGamePlayEntity converts a create game play request to a game play entity
|
||||
func ToGamePlayEntity(req *models.CreateGamePlayRequest) *entities.GamePlay {
|
||||
return &entities.GamePlay{
|
||||
GameID: req.GameID,
|
||||
CustomerID: req.CustomerID,
|
||||
CoinsUsed: req.CoinsUsed,
|
||||
RandomSeed: req.RandomSeed,
|
||||
}
|
||||
}
|
||||
@@ -1,82 +0,0 @@
|
||||
package mappers
|
||||
|
||||
import (
|
||||
"apskel-pos-be/internal/entities"
|
||||
"apskel-pos-be/internal/models"
|
||||
)
|
||||
|
||||
// ToGamePrizeResponse converts a game prize entity to a game prize response
|
||||
func ToGamePrizeResponse(gamePrize *entities.GamePrize) *models.GamePrizeResponse {
|
||||
if gamePrize == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
return &models.GamePrizeResponse{
|
||||
ID: gamePrize.ID,
|
||||
GameID: gamePrize.GameID,
|
||||
Name: gamePrize.Name,
|
||||
Weight: gamePrize.Weight,
|
||||
Stock: gamePrize.Stock,
|
||||
MaxStock: gamePrize.MaxStock,
|
||||
Threshold: gamePrize.Threshold,
|
||||
FallbackPrizeID: gamePrize.FallbackPrizeID,
|
||||
Image: gamePrize.Image,
|
||||
Metadata: gamePrize.Metadata,
|
||||
Game: ToGameResponse(&gamePrize.Game),
|
||||
FallbackPrize: ToGamePrizeResponse(gamePrize.FallbackPrize),
|
||||
CreatedAt: gamePrize.CreatedAt,
|
||||
UpdatedAt: gamePrize.UpdatedAt,
|
||||
}
|
||||
}
|
||||
|
||||
// ToGamePrizeResponses converts a slice of game prize entities to game prize responses
|
||||
func ToGamePrizeResponses(gamePrizes []entities.GamePrize) []models.GamePrizeResponse {
|
||||
responses := make([]models.GamePrizeResponse, len(gamePrizes))
|
||||
for i, gp := range gamePrizes {
|
||||
responses[i] = *ToGamePrizeResponse(&gp)
|
||||
}
|
||||
return responses
|
||||
}
|
||||
|
||||
// ToGamePrizeEntity converts a create game prize request to a game prize entity
|
||||
func ToGamePrizeEntity(req *models.CreateGamePrizeRequest) *entities.GamePrize {
|
||||
return &entities.GamePrize{
|
||||
GameID: req.GameID,
|
||||
Name: req.Name,
|
||||
Weight: req.Weight,
|
||||
Stock: req.Stock,
|
||||
MaxStock: req.MaxStock,
|
||||
Threshold: req.Threshold,
|
||||
FallbackPrizeID: req.FallbackPrizeID,
|
||||
Image: req.Image,
|
||||
Metadata: req.Metadata,
|
||||
}
|
||||
}
|
||||
|
||||
// UpdateGamePrizeEntity updates a game prize entity with update request data
|
||||
func UpdateGamePrizeEntity(gamePrize *entities.GamePrize, req *models.UpdateGamePrizeRequest) {
|
||||
if req.Name != nil {
|
||||
gamePrize.Name = *req.Name
|
||||
}
|
||||
if req.Weight != nil {
|
||||
gamePrize.Weight = *req.Weight
|
||||
}
|
||||
if req.Stock != nil {
|
||||
gamePrize.Stock = *req.Stock
|
||||
}
|
||||
if req.MaxStock != nil {
|
||||
gamePrize.MaxStock = req.MaxStock
|
||||
}
|
||||
if req.Threshold != nil {
|
||||
gamePrize.Threshold = req.Threshold
|
||||
}
|
||||
if req.FallbackPrizeID != nil {
|
||||
gamePrize.FallbackPrizeID = req.FallbackPrizeID
|
||||
}
|
||||
if req.Image != nil {
|
||||
gamePrize.Image = req.Image
|
||||
}
|
||||
if req.Metadata != nil {
|
||||
gamePrize.Metadata = req.Metadata
|
||||
}
|
||||
}
|
||||
@@ -18,7 +18,6 @@ func ToOmsetTrackerResponse(omsetTracker *entities.OmsetTracker) *models.OmsetTr
|
||||
PeriodEnd: omsetTracker.PeriodEnd,
|
||||
Total: omsetTracker.Total,
|
||||
GameID: omsetTracker.GameID,
|
||||
Game: ToGameResponse(omsetTracker.Game),
|
||||
CreatedAt: omsetTracker.CreatedAt,
|
||||
UpdatedAt: omsetTracker.UpdatedAt,
|
||||
}
|
||||
|
||||
@@ -1,138 +0,0 @@
|
||||
package mappers
|
||||
|
||||
import (
|
||||
"apskel-pos-be/internal/contract"
|
||||
"apskel-pos-be/internal/entities"
|
||||
"apskel-pos-be/internal/models"
|
||||
)
|
||||
|
||||
func ToRewardResponse(entity *entities.Reward) *models.RewardResponse {
|
||||
if entity == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
var tnc *models.TermsAndConditionsStruct
|
||||
if entity.Tnc != nil {
|
||||
var sections []models.TncSectionStruct
|
||||
for _, section := range entity.Tnc.Sections {
|
||||
sections = append(sections, models.TncSectionStruct{
|
||||
Title: section.Title,
|
||||
Rules: section.Rules,
|
||||
})
|
||||
}
|
||||
tnc = &models.TermsAndConditionsStruct{
|
||||
Sections: sections,
|
||||
ExpiryDays: entity.Tnc.ExpiryDays,
|
||||
}
|
||||
}
|
||||
|
||||
var images *[]string
|
||||
if entity.Images != nil {
|
||||
imagesSlice := []string(*entity.Images)
|
||||
images = &imagesSlice
|
||||
}
|
||||
|
||||
return &models.RewardResponse{
|
||||
ID: entity.ID,
|
||||
Name: entity.Name,
|
||||
RewardType: string(entity.RewardType),
|
||||
CostPoints: entity.CostPoints,
|
||||
Stock: entity.Stock,
|
||||
MaxPerCustomer: entity.MaxPerCustomer,
|
||||
Tnc: tnc,
|
||||
Metadata: entity.Metadata,
|
||||
Images: images,
|
||||
CreatedAt: entity.CreatedAt,
|
||||
UpdatedAt: entity.UpdatedAt,
|
||||
}
|
||||
}
|
||||
|
||||
func ToRewardEntity(request *contract.CreateRewardRequest) *entities.Reward {
|
||||
if request == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
var tnc *entities.TermsAndConditions
|
||||
if request.Tnc != nil {
|
||||
var sections []entities.TncSection
|
||||
for _, section := range request.Tnc.Sections {
|
||||
sections = append(sections, entities.TncSection{
|
||||
Title: section.Title,
|
||||
Rules: section.Rules,
|
||||
})
|
||||
}
|
||||
tnc = &entities.TermsAndConditions{
|
||||
Sections: sections,
|
||||
ExpiryDays: request.Tnc.ExpiryDays,
|
||||
}
|
||||
}
|
||||
|
||||
var images *entities.StringSlice
|
||||
if request.Images != nil {
|
||||
stringSlice := entities.StringSlice(*request.Images)
|
||||
images = &stringSlice
|
||||
}
|
||||
|
||||
return &entities.Reward{
|
||||
Name: request.Name,
|
||||
RewardType: entities.RewardType(request.RewardType),
|
||||
CostPoints: request.CostPoints,
|
||||
Stock: request.Stock,
|
||||
MaxPerCustomer: request.MaxPerCustomer,
|
||||
Tnc: tnc,
|
||||
Metadata: request.Metadata,
|
||||
Images: images,
|
||||
}
|
||||
}
|
||||
|
||||
func ToRewardEntityFromUpdate(request *contract.UpdateRewardRequest) *entities.Reward {
|
||||
if request == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
var tnc *entities.TermsAndConditions
|
||||
if request.Tnc != nil {
|
||||
var sections []entities.TncSection
|
||||
for _, section := range request.Tnc.Sections {
|
||||
sections = append(sections, entities.TncSection{
|
||||
Title: section.Title,
|
||||
Rules: section.Rules,
|
||||
})
|
||||
}
|
||||
tnc = &entities.TermsAndConditions{
|
||||
Sections: sections,
|
||||
ExpiryDays: request.Tnc.ExpiryDays,
|
||||
}
|
||||
}
|
||||
|
||||
var images *entities.StringSlice
|
||||
if request.Images != nil {
|
||||
stringSlice := entities.StringSlice(*request.Images)
|
||||
images = &stringSlice
|
||||
}
|
||||
|
||||
return &entities.Reward{
|
||||
ID: request.ID,
|
||||
Name: request.Name,
|
||||
RewardType: entities.RewardType(request.RewardType),
|
||||
CostPoints: request.CostPoints,
|
||||
Stock: request.Stock,
|
||||
MaxPerCustomer: request.MaxPerCustomer,
|
||||
Tnc: tnc,
|
||||
Metadata: request.Metadata,
|
||||
Images: images,
|
||||
}
|
||||
}
|
||||
|
||||
func ToRewardResponseSlice(entities []entities.Reward) []models.RewardResponse {
|
||||
if entities == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
responses := make([]models.RewardResponse, len(entities))
|
||||
for i, entity := range entities {
|
||||
responses[i] = *ToRewardResponse(&entity)
|
||||
}
|
||||
|
||||
return responses
|
||||
}
|
||||
@@ -1,80 +0,0 @@
|
||||
package mappers
|
||||
|
||||
import (
|
||||
"apskel-pos-be/internal/contract"
|
||||
"apskel-pos-be/internal/models"
|
||||
)
|
||||
|
||||
// SpinGameRequestContractToModel converts spin game request from contract to model
|
||||
func SpinGameRequestContractToModel(req *contract.SpinGameRequest) *models.SpinGameRequest {
|
||||
if req == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
return &models.SpinGameRequest{
|
||||
SpinID: req.SpinID,
|
||||
}
|
||||
}
|
||||
|
||||
// SpinGameResponseModelToContract converts spin game response from model to contract
|
||||
func SpinGameResponseModelToContract(resp *models.SpinGameResponse) *contract.SpinGameResponse {
|
||||
if resp == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
return &contract.SpinGameResponse{
|
||||
Status: resp.Status,
|
||||
Message: resp.Message,
|
||||
Data: SpinGameResponseDataModelToContract(resp.Data),
|
||||
}
|
||||
}
|
||||
|
||||
// SpinGameResponseDataModelToContract converts spin game response data from model to contract
|
||||
func SpinGameResponseDataModelToContract(data *models.SpinGameResponseData) *contract.SpinGameResponseData {
|
||||
if data == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
return &contract.SpinGameResponseData{
|
||||
GamePlay: GamePlayResponseModelToContract(&data.GamePlay),
|
||||
PrizeWon: CustomerGamePrizeResponseModelToContract(data.PrizeWon),
|
||||
CoinsRemaining: data.CoinsRemaining,
|
||||
}
|
||||
}
|
||||
|
||||
// GamePlayResponseModelToContract converts game play response from model to contract
|
||||
func GamePlayResponseModelToContract(resp *models.GamePlayResponse) contract.GamePlayResponse {
|
||||
if resp == nil {
|
||||
return contract.GamePlayResponse{}
|
||||
}
|
||||
|
||||
return contract.GamePlayResponse{
|
||||
ID: resp.ID,
|
||||
GameID: resp.GameID,
|
||||
CustomerID: resp.CustomerID,
|
||||
PrizeID: resp.PrizeID,
|
||||
CoinsUsed: resp.CoinsUsed,
|
||||
RandomSeed: resp.RandomSeed,
|
||||
CreatedAt: resp.CreatedAt,
|
||||
Game: nil, // Optional field - can be populated separately if needed
|
||||
Customer: nil, // Optional field - can be populated separately if needed
|
||||
Prize: nil, // Optional field - can be populated separately if needed
|
||||
}
|
||||
}
|
||||
|
||||
// CustomerGamePrizeResponseModelToContract converts customer game prize response from model to contract
|
||||
func CustomerGamePrizeResponseModelToContract(resp *models.CustomerGamePrizeResponse) *contract.CustomerGamePrizeResponse {
|
||||
if resp == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
return &contract.CustomerGamePrizeResponse{
|
||||
ID: resp.ID,
|
||||
GameID: resp.GameID,
|
||||
Name: resp.Name,
|
||||
Image: resp.Image,
|
||||
Metadata: resp.Metadata,
|
||||
CreatedAt: resp.CreatedAt,
|
||||
UpdatedAt: resp.UpdatedAt,
|
||||
}
|
||||
}
|
||||
@@ -1,59 +0,0 @@
|
||||
package models
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// Request Models
|
||||
type GetCustomerGamesRequest struct {
|
||||
// No additional fields needed - customer ID comes from JWT token
|
||||
}
|
||||
|
||||
// Response Models
|
||||
type GetCustomerGamesResponse struct {
|
||||
Status string `json:"status"`
|
||||
Message string `json:"message"`
|
||||
Data *GetCustomerGamesResponseData `json:"data,omitempty"`
|
||||
}
|
||||
|
||||
type GetCustomerGamesResponseData struct {
|
||||
Games []CustomerGameResponse `json:"games"`
|
||||
}
|
||||
|
||||
type CustomerGameResponse struct {
|
||||
ID uuid.UUID `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Type string `json:"type"`
|
||||
IsActive bool `json:"is_active"`
|
||||
Metadata *map[string]interface{} `json:"metadata,omitempty"`
|
||||
Prizes []CustomerGamePrizeResponse `json:"prizes,omitempty"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
type CustomerGamePrizeResponse struct {
|
||||
ID uuid.UUID `json:"id"`
|
||||
GameID uuid.UUID `json:"game_id"`
|
||||
Name string `json:"name"`
|
||||
Image *string `json:"image,omitempty"`
|
||||
Metadata *map[string]interface{} `json:"metadata,omitempty"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
// Ferris Wheel Game Models
|
||||
type GetFerrisWheelGameRequest struct {
|
||||
// No additional fields needed - customer ID comes from JWT token
|
||||
}
|
||||
|
||||
type GetFerrisWheelGameResponse struct {
|
||||
Status string `json:"status"`
|
||||
Message string `json:"message"`
|
||||
Data *GetFerrisWheelGameResponseData `json:"data,omitempty"`
|
||||
}
|
||||
|
||||
type GetFerrisWheelGameResponseData struct {
|
||||
Game CustomerGameResponse `json:"game"`
|
||||
}
|
||||
@@ -0,0 +1,613 @@
|
||||
package models
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"apskel-pos-be/internal/entities"
|
||||
)
|
||||
|
||||
// EnakGameInput is what an admin sends to create or change a game
|
||||
// (docs/rfc-enakgame.md §11). On a change, fields left out keep their value.
|
||||
type EnakGameInput struct {
|
||||
Name string `json:"name"`
|
||||
// SPIN, RAFFLE or MINIGAME; MINIGAME when left out on create.
|
||||
Type string `json:"type"`
|
||||
Slug string `json:"slug"`
|
||||
Description *string `json:"description"`
|
||||
ThumbnailURL *string `json:"thumbnail_url"`
|
||||
GameURL *string `json:"game_url"`
|
||||
Version *string `json:"version"`
|
||||
// Create only: DRAFT (default), ACTIVE or INACTIVE. Changed later through the
|
||||
// status endpoint.
|
||||
Status string `json:"status"`
|
||||
EntryCost int64 `json:"entry_cost"`
|
||||
// 600 when left out on create.
|
||||
SessionTTLSeconds int `json:"session_ttl_seconds"`
|
||||
ResultRules entities.GameResultRules `json:"result_rules"`
|
||||
}
|
||||
|
||||
type EnakGame struct {
|
||||
ID uuid.UUID `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Type string `json:"type"`
|
||||
Slug string `json:"slug"`
|
||||
Description *string `json:"description"`
|
||||
ThumbnailURL *string `json:"thumbnail_url"`
|
||||
GameURL *string `json:"game_url"`
|
||||
Version *string `json:"version"`
|
||||
Status string `json:"status"`
|
||||
EntryCost int64 `json:"entry_cost"`
|
||||
SessionTTLSeconds int `json:"session_ttl_seconds"`
|
||||
ResultRules entities.GameResultRules `json:"result_rules"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
// EnakGameListQuery filters the admin game list. ARCHIVED games are left out unless
|
||||
// asked for by status.
|
||||
type EnakGameListQuery struct {
|
||||
Status string `form:"status"`
|
||||
Search string `form:"search"`
|
||||
Page int `form:"page"`
|
||||
Limit int `form:"limit"`
|
||||
}
|
||||
|
||||
type EnakGameStatusInput struct {
|
||||
Status string `json:"status"`
|
||||
Reason *string `json:"reason"`
|
||||
}
|
||||
|
||||
// GameRewardConfigInput is a new version of a game's reward configuration (§5.2).
|
||||
type GameRewardConfigInput struct {
|
||||
RewardType string `json:"reward_type"`
|
||||
Rules json.RawMessage `json:"rules"`
|
||||
MaxReward int64 `json:"max_reward"`
|
||||
EffectiveAt *time.Time `json:"effective_at"`
|
||||
Reason *string `json:"reason"`
|
||||
}
|
||||
|
||||
type GameRewardConfigActivateInput struct {
|
||||
Reason *string `json:"reason"`
|
||||
}
|
||||
|
||||
type GameRewardConfig struct {
|
||||
ID uuid.UUID `json:"id"`
|
||||
GameID uuid.UUID `json:"game_id"`
|
||||
Version int `json:"version"`
|
||||
RewardType string `json:"reward_type"`
|
||||
Rules json.RawMessage `json:"rules"`
|
||||
MaxReward int64 `json:"max_reward"`
|
||||
Status string `json:"status"`
|
||||
EffectiveAt *time.Time `json:"effective_at"`
|
||||
CreatedBy uuid.UUID `json:"created_by"`
|
||||
Reason *string `json:"reason"`
|
||||
// Set on a version made by accepting a Budget Controller recommendation: the
|
||||
// admin's version it scales, by how much, and for which budget.
|
||||
BaseConfigID *uuid.UUID `json:"base_config_id"`
|
||||
Multiplier *float64 `json:"multiplier"`
|
||||
BudgetID *uuid.UUID `json:"budget_id"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
}
|
||||
|
||||
// GameBudgetThresholds are percents of utilization or forecast (PRD §8, §32), and the
|
||||
// guardrails of the Budget Controller (PRD §31).
|
||||
type GameBudgetThresholds struct {
|
||||
Warning *int64 `json:"warning,omitempty"`
|
||||
Critical *int64 `json:"critical,omitempty"`
|
||||
// Percent one recommendation may move rewards by, either way.
|
||||
MaxStepPercent *int64 `json:"max_step_percent,omitempty"`
|
||||
// Bounds of a game's multiplier, in percent of the configuration its admin wrote.
|
||||
MinMultiplierPercent *int64 `json:"min_multiplier_percent,omitempty"`
|
||||
MaxMultiplierPercent *int64 `json:"max_multiplier_percent,omitempty"`
|
||||
// Days after an accepted recommendation before the organization gets another.
|
||||
CooldownDays *int64 `json:"cooldown_days,omitempty"`
|
||||
}
|
||||
|
||||
// GameBudgetInput creates or changes a budget (§5.6). Dates are YYYY-MM-DD and
|
||||
// inclusive. On a change, fields left out keep their value; the scope never changes.
|
||||
type GameBudgetInput struct {
|
||||
Scope string `json:"scope"`
|
||||
Name string `json:"name"`
|
||||
PeriodStart string `json:"period_start"`
|
||||
PeriodEnd string `json:"period_end"`
|
||||
Amount int64 `json:"amount"`
|
||||
Thresholds GameBudgetThresholds `json:"thresholds"`
|
||||
}
|
||||
|
||||
type GameBudget struct {
|
||||
ID uuid.UUID `json:"id"`
|
||||
Scope string `json:"scope"`
|
||||
Name string `json:"name"`
|
||||
PeriodStart string `json:"period_start"`
|
||||
PeriodEnd string `json:"period_end"`
|
||||
Amount int64 `json:"amount"`
|
||||
Thresholds GameBudgetThresholds `json:"thresholds"`
|
||||
CreatedBy uuid.UUID `json:"created_by"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
type GameBudgetListQuery struct {
|
||||
Scope string `form:"scope"`
|
||||
Page int `form:"page"`
|
||||
Limit int `form:"limit"`
|
||||
}
|
||||
|
||||
// CustomerEnakGame is a game as the customer app sees it: what it costs and where to
|
||||
// load it, without the validation limits.
|
||||
type CustomerEnakGame struct {
|
||||
ID uuid.UUID `json:"id"`
|
||||
Slug string `json:"slug"`
|
||||
Name string `json:"name"`
|
||||
Description *string `json:"description"`
|
||||
ThumbnailURL *string `json:"thumbnail_url"`
|
||||
GameURL *string `json:"game_url"`
|
||||
Version *string `json:"version"`
|
||||
EntryCost int64 `json:"entry_cost"`
|
||||
SessionTTLSeconds int `json:"session_ttl_seconds"`
|
||||
// The events making the game pay more right now, highest priority first.
|
||||
Events []CustomerGameEvent `json:"events"`
|
||||
// What a PROBABILITY game, such as a spin wheel, can pay, in the order of its
|
||||
// configuration. Left out for the other reward types.
|
||||
Prizes []GamePrize `json:"prizes,omitempty"`
|
||||
}
|
||||
|
||||
// GamePrize is one entry of a PROBABILITY game, such as a segment of a spin wheel, as
|
||||
// the customer sees it: never its odds.
|
||||
type GamePrize struct {
|
||||
// 1 for the first entry of the configuration.
|
||||
Entry int `json:"entry"`
|
||||
Label *string `json:"label"`
|
||||
Amount int64 `json:"amount"`
|
||||
}
|
||||
|
||||
// GameSessionStart is the response of starting a game (§7.1).
|
||||
type GameSessionStart struct {
|
||||
SessionID uuid.UUID `json:"session_id"`
|
||||
GameID uuid.UUID `json:"game_id"`
|
||||
EntryCost int64 `json:"entry_cost"`
|
||||
ExpiresAt time.Time `json:"expires_at"`
|
||||
CoinBalance int64 `json:"coin_balance"`
|
||||
// True when this repeats an earlier start with the same Idempotency-Key.
|
||||
Replayed bool `json:"replayed"`
|
||||
}
|
||||
|
||||
// CustomerGameSession is a session as its customer sees it. The reward breakdown,
|
||||
// the RNG draw and whether it was flagged stay internal.
|
||||
type CustomerGameSession struct {
|
||||
ID uuid.UUID `json:"id"`
|
||||
GameID uuid.UUID `json:"game_id"`
|
||||
Status string `json:"status"`
|
||||
EntryCost int64 `json:"entry_cost"`
|
||||
RewardTotal int64 `json:"reward_total"`
|
||||
StartedAt time.Time `json:"started_at"`
|
||||
ExpiresAt time.Time `json:"expires_at"`
|
||||
EndedAt *time.Time `json:"ended_at"`
|
||||
RefundReason *string `json:"refund_reason"`
|
||||
}
|
||||
|
||||
// GameSessionCompleteInput is what the client reports at the end of a play (§7.2): data
|
||||
// only. Anything else it sends, a reward amount above all, is ignored (P1).
|
||||
type GameSessionCompleteInput struct {
|
||||
Score *int64 `json:"score"`
|
||||
Outcome *string `json:"outcome"`
|
||||
Data json.RawMessage `json:"data"`
|
||||
}
|
||||
|
||||
// GameSessionCompletion is the response of completing a session. Sending the same
|
||||
// completion again returns the same response.
|
||||
type GameSessionCompletion struct {
|
||||
SessionID uuid.UUID `json:"session_id"`
|
||||
// COMPLETED, or REFUNDED when the game was turned off during the play.
|
||||
Status string `json:"status"`
|
||||
RefundReason *string `json:"refund_reason,omitempty"`
|
||||
RewardTotal int64 `json:"reward_total"`
|
||||
// The parts of the reward that are safe to show.
|
||||
Reward GameSessionRewardParts `json:"reward"`
|
||||
CoinBalance int64 `json:"coin_balance"`
|
||||
// The daily limits that made the reward smaller than earned: USER_DAILY,
|
||||
// GAME_DAILY or GLOBAL_DAILY.
|
||||
LimitedBy []string `json:"limited_by,omitempty"`
|
||||
// The entry a PROBABILITY game drew, for a spin wheel to stop on. Its amount is
|
||||
// the base reward, before events and limits.
|
||||
Prize *GamePrize `json:"prize,omitempty"`
|
||||
}
|
||||
|
||||
type GameSessionRewardParts struct {
|
||||
Base int64 `json:"base"`
|
||||
// Added by events; 0 until events exist.
|
||||
Event int64 `json:"event"`
|
||||
}
|
||||
|
||||
// VoucherInput creates or changes a voucher (§5.7). On a change, fields left out keep
|
||||
// their value; the stock mode never changes.
|
||||
type VoucherInput struct {
|
||||
Name string `json:"name"`
|
||||
Description *string `json:"description"`
|
||||
ImageURL *string `json:"image_url"`
|
||||
VoucherType string `json:"voucher_type"`
|
||||
FaceValue int64 `json:"face_value"`
|
||||
PointCost int64 `json:"point_cost"`
|
||||
BusinessCost *int64 `json:"business_cost"`
|
||||
StockMode string `json:"stock_mode"`
|
||||
// STATIC only.
|
||||
Stock *int64 `json:"stock"`
|
||||
// EXTERNAL only.
|
||||
Provider *string `json:"provider"`
|
||||
ProviderRef *string `json:"provider_ref"`
|
||||
MaxPerCustomer *int `json:"max_per_customer"`
|
||||
ValidFrom *time.Time `json:"valid_from"`
|
||||
ValidUntil *time.Time `json:"valid_until"`
|
||||
Terms json.RawMessage `json:"terms"`
|
||||
// Create only: DRAFT (default), ACTIVE or INACTIVE.
|
||||
Status string `json:"status"`
|
||||
}
|
||||
|
||||
type Voucher struct {
|
||||
ID uuid.UUID `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Description *string `json:"description"`
|
||||
ImageURL *string `json:"image_url"`
|
||||
VoucherType string `json:"voucher_type"`
|
||||
FaceValue int64 `json:"face_value"`
|
||||
PointCost int64 `json:"point_cost"`
|
||||
BusinessCost *int64 `json:"business_cost"`
|
||||
StockMode string `json:"stock_mode"`
|
||||
Stock *int64 `json:"stock"`
|
||||
Provider *string `json:"provider"`
|
||||
ProviderRef *string `json:"provider_ref"`
|
||||
MaxPerCustomer *int `json:"max_per_customer"`
|
||||
ValidFrom *time.Time `json:"valid_from"`
|
||||
ValidUntil *time.Time `json:"valid_until"`
|
||||
Terms json.RawMessage `json:"terms"`
|
||||
Status string `json:"status"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
type VoucherListQuery struct {
|
||||
Status string `form:"status"`
|
||||
Search string `form:"search"`
|
||||
Page int `form:"page"`
|
||||
Limit int `form:"limit"`
|
||||
}
|
||||
|
||||
type VoucherStatusInput struct {
|
||||
Status string `json:"status"`
|
||||
Reason *string `json:"reason"`
|
||||
}
|
||||
|
||||
// VoucherCodeImportResult says what an import of codes did.
|
||||
type VoucherCodeImportResult struct {
|
||||
Imported int `json:"imported"`
|
||||
// Codes already in the pool or repeated in the file, skipped.
|
||||
DuplicateCount int `json:"duplicate_count"`
|
||||
Duplicates []string `json:"duplicates"`
|
||||
// Lines that could not be read, skipped.
|
||||
Invalid []VoucherCodeImportProblem `json:"invalid"`
|
||||
}
|
||||
|
||||
type VoucherCodeImportProblem struct {
|
||||
Line int `json:"line"`
|
||||
Reason string `json:"reason"`
|
||||
}
|
||||
|
||||
type VoucherCodeListQuery struct {
|
||||
Status string `form:"status"`
|
||||
Page int `form:"page"`
|
||||
Limit int `form:"limit"`
|
||||
}
|
||||
|
||||
type VoucherCode struct {
|
||||
ID uuid.UUID `json:"id"`
|
||||
Code string `json:"code"`
|
||||
Status string `json:"status"`
|
||||
RedemptionID *uuid.UUID `json:"redemption_id"`
|
||||
ExpiresAt *time.Time `json:"expires_at"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
}
|
||||
|
||||
// VoucherCodes is a pool's codes: how many in each status, and one page of them.
|
||||
type VoucherCodes struct {
|
||||
Counts map[string]int64 `json:"counts"`
|
||||
Codes PaginatedResponse[VoucherCode] `json:"codes"`
|
||||
}
|
||||
|
||||
// CustomerVoucher is a voucher in the customer app's catalog. Available is how many
|
||||
// are left, without saying how many were redeemed or expired.
|
||||
type CustomerVoucher struct {
|
||||
ID uuid.UUID `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Description *string `json:"description"`
|
||||
ImageURL *string `json:"image_url"`
|
||||
VoucherType string `json:"voucher_type"`
|
||||
FaceValue int64 `json:"face_value"`
|
||||
PointCost int64 `json:"point_cost"`
|
||||
MaxPerCustomer *int `json:"max_per_customer"`
|
||||
ValidUntil *time.Time `json:"valid_until"`
|
||||
Terms json.RawMessage `json:"terms"`
|
||||
Available *int64 `json:"available"`
|
||||
}
|
||||
|
||||
// CustomerVoucherRedemption is a redemption as its customer sees it, with the code to
|
||||
// use. The response of a redeem adds the EnakPoint balance.
|
||||
type CustomerVoucherRedemption struct {
|
||||
ID uuid.UUID `json:"id"`
|
||||
VoucherID uuid.UUID `json:"voucher_id"`
|
||||
VoucherName string `json:"voucher_name"`
|
||||
VoucherImageURL *string `json:"voucher_image_url"`
|
||||
VoucherType string `json:"voucher_type"`
|
||||
Status string `json:"status"`
|
||||
FaceValue int64 `json:"face_value"`
|
||||
PointCost int64 `json:"point_cost"`
|
||||
Code *string `json:"code"`
|
||||
CodeExpiresAt *time.Time `json:"code_expires_at"`
|
||||
CompletedAt *time.Time `json:"completed_at"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
}
|
||||
|
||||
type VoucherRedeemResult struct {
|
||||
CustomerVoucherRedemption
|
||||
PointBalance int64 `json:"point_balance"`
|
||||
// True when this repeats an earlier redeem with the same Idempotency-Key.
|
||||
Replayed bool `json:"replayed"`
|
||||
}
|
||||
|
||||
// GameBudgetMetrics is how a budget stands (docs/rfc-enakgame.md §10, PRD §8). Money is
|
||||
// in rupiah, percents have two decimals.
|
||||
type GameBudgetMetrics struct {
|
||||
BudgetID uuid.UUID `json:"budget_id"`
|
||||
Scope string `json:"scope"`
|
||||
PeriodStart string `json:"period_start"`
|
||||
PeriodEnd string `json:"period_end"`
|
||||
// The day, in Asia/Jakarta, the metrics are for.
|
||||
AsOf string `json:"as_of"`
|
||||
Amount int64 `json:"amount"`
|
||||
|
||||
RealizedCost int64 `json:"realized_cost"`
|
||||
Remaining int64 `json:"remaining"`
|
||||
UtilizationPercent float64 `json:"utilization_percent"`
|
||||
|
||||
// Average realized cost per day over the last WindowDays days, today included.
|
||||
DailyBurn int64 `json:"daily_burn"`
|
||||
WindowDays int64 `json:"window_days"`
|
||||
// Days of the period after today.
|
||||
RemainingDays int64 `json:"remaining_days"`
|
||||
ForecastCost int64 `json:"forecast_cost"`
|
||||
ForecastRemaining int64 `json:"forecast_remaining"`
|
||||
ForecastUtilizationPercent float64 `json:"forecast_utilization_percent"`
|
||||
|
||||
CoinIssued int64 `json:"coin_issued"`
|
||||
// What the budget's rewards still hold, spendable: the most that can still turn
|
||||
// into cost.
|
||||
Exposure GameBudgetExposure `json:"exposure"`
|
||||
|
||||
// The thresholds used: the budget's own, or the defaults for those it does not set.
|
||||
Thresholds GameBudgetThresholds `json:"thresholds"`
|
||||
// HEALTHY, WARNING, CRITICAL or EXHAUSTED.
|
||||
Status string `json:"status"`
|
||||
}
|
||||
|
||||
type GameBudgetExposure struct {
|
||||
Coins int64 `json:"coins"`
|
||||
Points int64 `json:"points"`
|
||||
}
|
||||
|
||||
// GameBudgetRecommendation is what the Budget Controller suggests for a global budget
|
||||
// (docs/rfc-enakgame.md §10, PRD §29–§31): a multiplier on every game's reward that
|
||||
// brings the forecast to the budget, within the guardrails.
|
||||
type GameBudgetRecommendation struct {
|
||||
BudgetID uuid.UUID `json:"budget_id"`
|
||||
// RECOMMENDED, NO_CHANGE, COOLDOWN, AT_LIMIT, INSUFFICIENT_DATA or OUT_OF_PERIOD.
|
||||
// Only RECOMMENDED can be accepted.
|
||||
State string `json:"state"`
|
||||
Message string `json:"message"`
|
||||
|
||||
Metrics GameBudgetMetrics `json:"metrics"`
|
||||
// The guardrails used: the budget's own, or the defaults for those it does not set.
|
||||
Guardrails GameBudgetThresholds `json:"guardrails"`
|
||||
|
||||
// The multiplier that would make the forecast meet the budget, before the
|
||||
// guardrails; nil when there is no cost to extrapolate.
|
||||
TargetMultiplier *float64 `json:"target_multiplier"`
|
||||
// The target within one step, rounded down to two decimals. Accepting sends it back.
|
||||
Multiplier float64 `json:"multiplier"`
|
||||
// When the organization may accept again, during a cooldown.
|
||||
CooldownUntil *time.Time `json:"cooldown_until,omitempty"`
|
||||
// The games whose reward would change, each with its new version.
|
||||
Games []GameRewardAdjustment `json:"games"`
|
||||
}
|
||||
|
||||
// GameRewardAdjustment is how accepting a recommendation changes a game's reward: a
|
||||
// new version of its active configuration, with the base's amounts scaled.
|
||||
type GameRewardAdjustment struct {
|
||||
GameID uuid.UUID `json:"game_id"`
|
||||
GameName string `json:"game_name"`
|
||||
// The active version, and the admin's version both are measured against.
|
||||
RewardConfigID uuid.UUID `json:"reward_config_id"`
|
||||
Version int `json:"version"`
|
||||
BaseConfigID uuid.UUID `json:"base_config_id"`
|
||||
RewardType string `json:"reward_type"`
|
||||
|
||||
CurrentMultiplier float64 `json:"current_multiplier"`
|
||||
NewMultiplier float64 `json:"new_multiplier"`
|
||||
CurrentRules json.RawMessage `json:"current_rules"`
|
||||
NewRules json.RawMessage `json:"new_rules"`
|
||||
CurrentMaxReward int64 `json:"current_max_reward"`
|
||||
NewMaxReward int64 `json:"new_max_reward"`
|
||||
}
|
||||
|
||||
// GameBudgetRecommendationAcceptInput accepts the recommendation the admin saw. When
|
||||
// the recommendation changed since, nothing is applied.
|
||||
type GameBudgetRecommendationAcceptInput struct {
|
||||
Multiplier *float64 `json:"multiplier"`
|
||||
Reason *string `json:"reason"`
|
||||
}
|
||||
|
||||
// GameBudgetRecommendationAccepted is what accepting made: one active version per
|
||||
// game.
|
||||
type GameBudgetRecommendationAccepted struct {
|
||||
BudgetID uuid.UUID `json:"budget_id"`
|
||||
Multiplier float64 `json:"multiplier"`
|
||||
RewardConfigs []GameRewardConfig `json:"reward_configs"`
|
||||
}
|
||||
|
||||
// EnakGameAnalyticsQuery is a range of days in Asia/Jakarta, both ends included.
|
||||
type EnakGameAnalyticsQuery struct {
|
||||
From string `form:"from"`
|
||||
To string `form:"to"`
|
||||
// Games analytics only: one game instead of all.
|
||||
GameID string `form:"game_id"`
|
||||
}
|
||||
|
||||
// EnakGameAnalytics is how an organization's games were played over a range of days
|
||||
// (PRD §36 Game), by the day each session started.
|
||||
type EnakGameAnalytics struct {
|
||||
From string `json:"from"`
|
||||
To string `json:"to"`
|
||||
Totals EnakGameStats `json:"totals"`
|
||||
Games []EnakGameGameStats `json:"games"`
|
||||
}
|
||||
|
||||
type EnakGameGameStats struct {
|
||||
GameID uuid.UUID `json:"game_id"`
|
||||
GameName string `json:"game_name"`
|
||||
EnakGameStats
|
||||
}
|
||||
|
||||
type EnakGameStats struct {
|
||||
// Sessions started, whatever became of them.
|
||||
Plays int64 `json:"plays"`
|
||||
Completed int64 `json:"completed"`
|
||||
Refunded int64 `json:"refunded"`
|
||||
Expired int64 `json:"expired"`
|
||||
Flagged int64 `json:"flagged"`
|
||||
// Customers who started at least one session.
|
||||
Players int64 `json:"players"`
|
||||
// Over completed sessions that reported a score; nil when none did.
|
||||
AverageScore *float64 `json:"average_score"`
|
||||
// EnakCoin per completed session, and per play.
|
||||
AverageReward float64 `json:"average_reward"`
|
||||
RewardPerPlay float64 `json:"reward_per_play"`
|
||||
CoinIssued int64 `json:"coin_issued"`
|
||||
// EnakCoin paid to start, and the part refunded.
|
||||
EntryCostPaid int64 `json:"entry_cost_paid"`
|
||||
CoinRefunded int64 `json:"coin_refunded"`
|
||||
}
|
||||
|
||||
// EnakGameEconomyAnalytics is how EnakCoin and EnakPoint moved in an organization over
|
||||
// a range of days (PRD §36 Economy), from the ledger.
|
||||
type EnakGameEconomyAnalytics struct {
|
||||
From string `json:"from"`
|
||||
To string `json:"to"`
|
||||
Coin EnakGameCoinFlows `json:"coin"`
|
||||
Point EnakGamePointFlows `json:"point"`
|
||||
// Every ledger type that moved, for what the headline numbers leave out.
|
||||
ByType []WalletFlowTotals `json:"by_type"`
|
||||
}
|
||||
|
||||
type EnakGameCoinFlows struct {
|
||||
// New EnakCoin: game rewards, earning less its reversals, migration and upward
|
||||
// adjustments.
|
||||
Generated int64 `json:"generated"`
|
||||
GameRewards int64 `json:"game_rewards"`
|
||||
// Entry costs, less the refunded ones.
|
||||
SpentOnGames int64 `json:"spent_on_games"`
|
||||
// Exchanged into EnakPoint.
|
||||
Exchanged int64 `json:"exchanged"`
|
||||
// SpentOnGames + Exchanged.
|
||||
Spent int64 `json:"spent"`
|
||||
Expired int64 `json:"expired"`
|
||||
// Held by customers at the end of the range.
|
||||
Outstanding int64 `json:"outstanding"`
|
||||
}
|
||||
|
||||
type EnakGamePointFlows struct {
|
||||
// From shopping, less its reversals.
|
||||
Earned int64 `json:"earned"`
|
||||
// Received from exchanging EnakCoin.
|
||||
Exchanged int64 `json:"exchanged"`
|
||||
// Spent on vouchers, less the refunded redemptions.
|
||||
Redeemed int64 `json:"redeemed"`
|
||||
Expired int64 `json:"expired"`
|
||||
// Held by customers at the end of the range.
|
||||
Balance int64 `json:"balance"`
|
||||
}
|
||||
|
||||
// WalletFlowTotals is what one ledger type moved in one currency.
|
||||
type WalletFlowTotals struct {
|
||||
Currency string `json:"currency"`
|
||||
Type string `json:"type"`
|
||||
Credit int64 `json:"credit"`
|
||||
Debit int64 `json:"debit"`
|
||||
Transactions int64 `json:"transactions"`
|
||||
}
|
||||
|
||||
// GameEventInput creates or changes an event (§5.5). On a change, fields left out
|
||||
// keep their value.
|
||||
type GameEventInput struct {
|
||||
Name string `json:"name"`
|
||||
Slug string `json:"slug"`
|
||||
Description *string `json:"description"`
|
||||
BannerURL *string `json:"banner_url"`
|
||||
StartAt time.Time `json:"start_at"`
|
||||
EndAt time.Time `json:"end_at"`
|
||||
// Asia/Jakarta when left out.
|
||||
Timezone string `json:"timezone"`
|
||||
Priority int `json:"priority"`
|
||||
// At least 1, two decimals at most. 2 adds the base reward once more.
|
||||
Multiplier *float64 `json:"multiplier"`
|
||||
Bonus *int64 `json:"bonus"`
|
||||
// An EVENT budget of the organization; it pays what the event adds.
|
||||
BudgetID uuid.UUID `json:"budget_id"`
|
||||
RewardLimit *int64 `json:"reward_limit"`
|
||||
UserDailyLimit *int64 `json:"user_daily_limit"`
|
||||
GameIDs []uuid.UUID `json:"game_ids"`
|
||||
// Create only: DRAFT (default) or ACTIVE.
|
||||
Status string `json:"status"`
|
||||
}
|
||||
|
||||
type GameEvent struct {
|
||||
ID uuid.UUID `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Slug string `json:"slug"`
|
||||
Description *string `json:"description"`
|
||||
BannerURL *string `json:"banner_url"`
|
||||
StartAt time.Time `json:"start_at"`
|
||||
EndAt time.Time `json:"end_at"`
|
||||
Timezone string `json:"timezone"`
|
||||
Status string `json:"status"`
|
||||
Priority int `json:"priority"`
|
||||
Multiplier *float64 `json:"multiplier"`
|
||||
Bonus *int64 `json:"bonus"`
|
||||
BudgetID uuid.UUID `json:"budget_id"`
|
||||
RewardLimit *int64 `json:"reward_limit"`
|
||||
UserDailyLimit *int64 `json:"user_daily_limit"`
|
||||
GameIDs []uuid.UUID `json:"game_ids"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
type GameEventListQuery struct {
|
||||
Status string `form:"status"`
|
||||
Page int `form:"page"`
|
||||
Limit int `form:"limit"`
|
||||
}
|
||||
|
||||
type GameEventStatusInput struct {
|
||||
Status string `json:"status"`
|
||||
Reason *string `json:"reason"`
|
||||
}
|
||||
|
||||
// CustomerGameEvent is an event running on a game, as the customer app shows it.
|
||||
type CustomerGameEvent struct {
|
||||
ID uuid.UUID `json:"id"`
|
||||
Name string `json:"name"`
|
||||
BannerURL *string `json:"banner_url"`
|
||||
Multiplier *float64 `json:"multiplier"`
|
||||
Bonus *int64 `json:"bonus"`
|
||||
EndAt time.Time `json:"end_at"`
|
||||
}
|
||||
@@ -1,41 +0,0 @@
|
||||
package models
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
type CreateGameRequest struct {
|
||||
Name string `json:"name" validate:"required"`
|
||||
Type string `json:"type" validate:"required,oneof=SPIN RAFFLE MINIGAME"`
|
||||
IsActive bool `json:"is_active"`
|
||||
Metadata map[string]interface{} `json:"metadata"`
|
||||
}
|
||||
|
||||
type UpdateGameRequest struct {
|
||||
Name *string `json:"name,omitempty" validate:"omitempty,required"`
|
||||
Type *string `json:"type,omitempty" validate:"omitempty,oneof=SPIN RAFFLE MINIGAME"`
|
||||
IsActive *bool `json:"is_active,omitempty"`
|
||||
Metadata map[string]interface{} `json:"metadata,omitempty"`
|
||||
}
|
||||
|
||||
type GameResponse struct {
|
||||
ID uuid.UUID `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Type string `json:"type"`
|
||||
IsActive bool `json:"is_active"`
|
||||
Metadata map[string]interface{} `json:"metadata"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
type ListGamesQuery struct {
|
||||
Page int `query:"page" validate:"min=1"`
|
||||
Limit int `query:"limit" validate:"min=1,max=100"`
|
||||
Search string `query:"search"`
|
||||
Type string `query:"type" validate:"omitempty,oneof=SPIN RAFFLE MINIGAME"`
|
||||
IsActive *bool `query:"is_active"`
|
||||
SortBy string `query:"sort_by" validate:"omitempty,oneof=name type created_at updated_at"`
|
||||
SortOrder string `query:"sort_order" validate:"omitempty,oneof=asc desc"`
|
||||
}
|
||||
@@ -1,50 +0,0 @@
|
||||
package models
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
type CreateGamePlayRequest struct {
|
||||
GameID uuid.UUID `json:"game_id" validate:"required"`
|
||||
CustomerID uuid.UUID `json:"customer_id" validate:"required"`
|
||||
CoinsUsed int `json:"coins_used" validate:"min=0"`
|
||||
RandomSeed *string `json:"random_seed,omitempty"`
|
||||
}
|
||||
|
||||
type GamePlayResponse struct {
|
||||
ID uuid.UUID `json:"id"`
|
||||
GameID uuid.UUID `json:"game_id"`
|
||||
CustomerID uuid.UUID `json:"customer_id"`
|
||||
PrizeID *uuid.UUID `json:"prize_id,omitempty"`
|
||||
CoinsUsed int `json:"coins_used"`
|
||||
RandomSeed *string `json:"random_seed,omitempty"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
Game *GameResponse `json:"game,omitempty"`
|
||||
Customer *CustomerResponse `json:"customer,omitempty"`
|
||||
Prize *GamePrizeResponse `json:"prize,omitempty"`
|
||||
}
|
||||
|
||||
type ListGamePlaysQuery struct {
|
||||
Page int `query:"page" validate:"min=1"`
|
||||
Limit int `query:"limit" validate:"min=1,max=100"`
|
||||
Search string `query:"search"`
|
||||
GameID *uuid.UUID `query:"game_id"`
|
||||
CustomerID *uuid.UUID `query:"customer_id"`
|
||||
PrizeID *uuid.UUID `query:"prize_id"`
|
||||
SortBy string `query:"sort_by" validate:"omitempty,oneof=created_at coins_used"`
|
||||
SortOrder string `query:"sort_order" validate:"omitempty,oneof=asc desc"`
|
||||
}
|
||||
|
||||
// PlayGameRequest plays a game for a customer, at the game's metadata.coin_cost.
|
||||
type PlayGameRequest struct {
|
||||
GameID uuid.UUID `json:"game_id" validate:"required"`
|
||||
CustomerID uuid.UUID `json:"customer_id" validate:"required"`
|
||||
}
|
||||
|
||||
type PlayGameResponse struct {
|
||||
GamePlay GamePlayResponse `json:"game_play"`
|
||||
PrizeWon *GamePrizeResponse `json:"prize_won,omitempty"`
|
||||
CoinsRemaining int64 `json:"coins_remaining"`
|
||||
}
|
||||
@@ -1,56 +0,0 @@
|
||||
package models
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
type CreateGamePrizeRequest struct {
|
||||
GameID uuid.UUID `json:"game_id" validate:"required"`
|
||||
Name string `json:"name" validate:"required"`
|
||||
Weight int `json:"weight" validate:"min=1"`
|
||||
Stock int `json:"stock" validate:"min=0"`
|
||||
MaxStock *int `json:"max_stock,omitempty"`
|
||||
Threshold *int64 `json:"threshold,omitempty"`
|
||||
FallbackPrizeID *uuid.UUID `json:"fallback_prize_id,omitempty"`
|
||||
Image *string `json:"image,omitempty" validate:"omitempty,max=500"`
|
||||
Metadata map[string]interface{} `json:"metadata"`
|
||||
}
|
||||
|
||||
type UpdateGamePrizeRequest struct {
|
||||
Name *string `json:"name,omitempty" validate:"omitempty,required"`
|
||||
Weight *int `json:"weight,omitempty" validate:"omitempty,min=1"`
|
||||
Stock *int `json:"stock,omitempty" validate:"omitempty,min=0"`
|
||||
MaxStock *int `json:"max_stock,omitempty"`
|
||||
Threshold *int64 `json:"threshold,omitempty"`
|
||||
FallbackPrizeID *uuid.UUID `json:"fallback_prize_id,omitempty"`
|
||||
Image *string `json:"image,omitempty" validate:"omitempty,max=500"`
|
||||
Metadata map[string]interface{} `json:"metadata,omitempty"`
|
||||
}
|
||||
|
||||
type GamePrizeResponse struct {
|
||||
ID uuid.UUID `json:"id"`
|
||||
GameID uuid.UUID `json:"game_id"`
|
||||
Name string `json:"name"`
|
||||
Weight int `json:"weight"`
|
||||
Stock int `json:"stock"`
|
||||
MaxStock *int `json:"max_stock,omitempty"`
|
||||
Threshold *int64 `json:"threshold,omitempty"`
|
||||
FallbackPrizeID *uuid.UUID `json:"fallback_prize_id,omitempty"`
|
||||
Image *string `json:"image,omitempty"`
|
||||
Metadata map[string]interface{} `json:"metadata"`
|
||||
Game *GameResponse `json:"game,omitempty"`
|
||||
FallbackPrize *GamePrizeResponse `json:"fallback_prize,omitempty"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
type ListGamePrizesQuery struct {
|
||||
Page int `query:"page" validate:"min=1"`
|
||||
Limit int `query:"limit" validate:"min=1,max=100"`
|
||||
Search string `query:"search"`
|
||||
GameID *uuid.UUID `query:"game_id"`
|
||||
SortBy string `query:"sort_by" validate:"omitempty,oneof=name weight stock created_at updated_at"`
|
||||
SortOrder string `query:"sort_order" validate:"omitempty,oneof=asc desc"`
|
||||
}
|
||||
@@ -44,6 +44,16 @@ type OrganizationLoyaltySettings struct {
|
||||
Transfer LoyaltyTransferSettings `json:"transfer"`
|
||||
PointExpiry LoyaltyExpirySettings `json:"point_expiry"`
|
||||
CoinExpiry LoyaltyExpirySettings `json:"coin_expiry"`
|
||||
EnakGame EnakGameLimitSettings `json:"enakgame"`
|
||||
}
|
||||
|
||||
// EnakGameLimitSettings caps the EnakCoin EnakGame rewards per day, in Asia/Jakarta
|
||||
// (docs/rfc-enakgame.md §5.10). 0 means no limit.
|
||||
type EnakGameLimitSettings struct {
|
||||
// What one customer may receive.
|
||||
UserDailyLimit int64 `json:"user_daily_limit"`
|
||||
// What the whole organization may give out.
|
||||
GlobalDailyLimit int64 `json:"global_daily_limit"`
|
||||
}
|
||||
|
||||
type LoyaltyExchangeSettings struct {
|
||||
|
||||
@@ -27,15 +27,14 @@ type AddOmsetRequest struct {
|
||||
}
|
||||
|
||||
type OmsetTrackerResponse struct {
|
||||
ID uuid.UUID `json:"id"`
|
||||
PeriodType string `json:"period_type"`
|
||||
PeriodStart time.Time `json:"period_start"`
|
||||
PeriodEnd time.Time `json:"period_end"`
|
||||
Total int64 `json:"total"`
|
||||
GameID *uuid.UUID `json:"game_id,omitempty"`
|
||||
Game *GameResponse `json:"game,omitempty"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
ID uuid.UUID `json:"id"`
|
||||
PeriodType string `json:"period_type"`
|
||||
PeriodStart time.Time `json:"period_start"`
|
||||
PeriodEnd time.Time `json:"period_end"`
|
||||
Total int64 `json:"total"`
|
||||
GameID *uuid.UUID `json:"game_id,omitempty"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
type ListOmsetTrackerQuery struct {
|
||||
|
||||
@@ -1,71 +0,0 @@
|
||||
package models
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
type CreateRewardRequest struct {
|
||||
Name string `json:"name" binding:"required,min=1,max=150"`
|
||||
RewardType string `json:"reward_type" binding:"required,oneof=VOUCHER PHYSICAL DIGITAL BALANCE"`
|
||||
CostPoints int64 `json:"cost_points" binding:"required,min=1"`
|
||||
Stock *int `json:"stock,omitempty"`
|
||||
MaxPerCustomer int `json:"max_per_customer" binding:"min=1"`
|
||||
Tnc *TermsAndConditionsStruct `json:"tnc,omitempty"`
|
||||
Metadata *map[string]interface{} `json:"metadata,omitempty"`
|
||||
Images *[]string `json:"images,omitempty"`
|
||||
}
|
||||
|
||||
type UpdateRewardRequest struct {
|
||||
ID uuid.UUID `json:"id" binding:"required"`
|
||||
Name string `json:"name" binding:"required,min=1,max=150"`
|
||||
RewardType string `json:"reward_type" binding:"required,oneof=VOUCHER PHYSICAL DIGITAL BALANCE"`
|
||||
CostPoints int64 `json:"cost_points" binding:"required,min=1"`
|
||||
Stock *int `json:"stock,omitempty"`
|
||||
MaxPerCustomer int `json:"max_per_customer" binding:"min=1"`
|
||||
Tnc *TermsAndConditionsStruct `json:"tnc,omitempty"`
|
||||
Metadata *map[string]interface{} `json:"metadata,omitempty"`
|
||||
Images *[]string `json:"images,omitempty"`
|
||||
}
|
||||
|
||||
type ListRewardsRequest struct {
|
||||
Page int `form:"page" binding:"min=1"`
|
||||
Limit int `form:"limit" binding:"min=1,max=100"`
|
||||
Search string `form:"search"`
|
||||
RewardType string `form:"reward_type"`
|
||||
MinPoints *int64 `form:"min_points"`
|
||||
MaxPoints *int64 `form:"max_points"`
|
||||
HasStock *bool `form:"has_stock"`
|
||||
}
|
||||
|
||||
type RewardResponse struct {
|
||||
ID uuid.UUID `json:"id"`
|
||||
Name string `json:"name"`
|
||||
RewardType string `json:"reward_type"`
|
||||
CostPoints int64 `json:"cost_points"`
|
||||
Stock *int `json:"stock,omitempty"`
|
||||
MaxPerCustomer int `json:"max_per_customer"`
|
||||
Tnc *TermsAndConditionsStruct `json:"tnc,omitempty"`
|
||||
Metadata *map[string]interface{} `json:"metadata,omitempty"`
|
||||
Images *[]string `json:"images,omitempty"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
type ListRewardsResponse struct {
|
||||
Rewards []RewardResponse `json:"rewards"`
|
||||
Total int64 `json:"total"`
|
||||
Page int `json:"page"`
|
||||
Limit int `json:"limit"`
|
||||
}
|
||||
|
||||
type TermsAndConditionsStruct struct {
|
||||
Sections []TncSectionStruct `json:"sections"`
|
||||
ExpiryDays int `json:"expiry_days"`
|
||||
}
|
||||
|
||||
type TncSectionStruct struct {
|
||||
Title string `json:"title"`
|
||||
Rules []string `json:"rules"`
|
||||
}
|
||||
@@ -1,37 +0,0 @@
|
||||
package models
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// SpinGameRequest represents the request to play a spin game
|
||||
type SpinGameRequest struct {
|
||||
SpinID string `json:"spin_id" validate:"required,uuid"`
|
||||
}
|
||||
|
||||
// SpinGameResponse represents the response from playing a spin game
|
||||
type SpinGameResponse struct {
|
||||
Status string `json:"status"`
|
||||
Message string `json:"message"`
|
||||
Data *SpinGameResponseData `json:"data,omitempty"`
|
||||
}
|
||||
|
||||
// SpinGameResponseData contains the game play result
|
||||
type SpinGameResponseData struct {
|
||||
GamePlay GamePlayResponse `json:"game_play"`
|
||||
PrizeWon *CustomerGamePrizeResponse `json:"prize_won,omitempty"`
|
||||
CoinsRemaining int64 `json:"coins_remaining"`
|
||||
}
|
||||
|
||||
// SpinGamePrizeResponse represents a prize won in the spin game
|
||||
type SpinGamePrizeResponse struct {
|
||||
ID uuid.UUID `json:"id"`
|
||||
GameID uuid.UUID `json:"game_id"`
|
||||
Name string `json:"name"`
|
||||
Image *string `json:"image,omitempty"`
|
||||
Metadata *map[string]interface{} `json:"metadata,omitempty"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
package processor
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"apskel-pos-be/internal/constants"
|
||||
"apskel-pos-be/internal/entities"
|
||||
"apskel-pos-be/internal/repository"
|
||||
)
|
||||
|
||||
// ErrInvalidAuditEntry means an audit entry lacks what every row must say.
|
||||
var ErrInvalidAuditEntry = errors.New("invalid audit entry")
|
||||
|
||||
// AuditEntry is one change to record. Before and After are marshalled to JSON; leave
|
||||
// one nil when there was nothing before (a create) or after (a delete).
|
||||
type AuditEntry struct {
|
||||
OrganizationID uuid.UUID
|
||||
// USER or SYSTEM. A USER entry needs ActorID.
|
||||
ActorType string
|
||||
ActorID *uuid.UUID
|
||||
EntityType string
|
||||
EntityID uuid.UUID
|
||||
Action string
|
||||
Before any
|
||||
After any
|
||||
Reason *string
|
||||
Source string
|
||||
}
|
||||
|
||||
// AuditLogger writes audit_logs (docs/rfc-enakgame.md §13). It must be called inside
|
||||
// the transaction that makes the change, so the change and its row commit or roll
|
||||
// back together: outside one it returns repository.ErrAuditTxRequired.
|
||||
type AuditLogger struct {
|
||||
repo repository.AuditLogRepository
|
||||
}
|
||||
|
||||
func NewAuditLogger(repo repository.AuditLogRepository) *AuditLogger {
|
||||
return &AuditLogger{repo: repo}
|
||||
}
|
||||
|
||||
func (l *AuditLogger) Record(ctx context.Context, e AuditEntry) error {
|
||||
invalid := func(format string, args ...any) error {
|
||||
return fmt.Errorf("%w: %s", ErrInvalidAuditEntry, fmt.Sprintf(format, args...))
|
||||
}
|
||||
switch {
|
||||
case e.OrganizationID == uuid.Nil:
|
||||
return invalid("organization is required")
|
||||
case e.ActorType != constants.AuditActorUser && e.ActorType != constants.AuditActorSystem:
|
||||
return invalid("unknown actor type %q", e.ActorType)
|
||||
case e.ActorType == constants.AuditActorUser && isNilID(e.ActorID):
|
||||
return invalid("a USER entry requires the actor")
|
||||
case strings.TrimSpace(e.EntityType) == "" || e.EntityID == uuid.Nil:
|
||||
return invalid("entity is required")
|
||||
case strings.TrimSpace(e.Action) == "":
|
||||
return invalid("action is required")
|
||||
case strings.TrimSpace(e.Source) == "":
|
||||
return invalid("source is required")
|
||||
}
|
||||
before, err := auditJSON(e.Before)
|
||||
if err != nil {
|
||||
return invalid("before: %v", err)
|
||||
}
|
||||
after, err := auditJSON(e.After)
|
||||
if err != nil {
|
||||
return invalid("after: %v", err)
|
||||
}
|
||||
return l.repo.Insert(ctx, &entities.AuditLog{
|
||||
OrganizationID: e.OrganizationID,
|
||||
ActorType: e.ActorType,
|
||||
ActorID: e.ActorID,
|
||||
EntityType: e.EntityType,
|
||||
EntityID: e.EntityID,
|
||||
Action: e.Action,
|
||||
Before: before,
|
||||
After: after,
|
||||
Reason: e.Reason,
|
||||
Source: e.Source,
|
||||
})
|
||||
}
|
||||
|
||||
func auditJSON(v any) (json.RawMessage, error) {
|
||||
if v == nil {
|
||||
return nil, nil
|
||||
}
|
||||
raw, ok := v.(json.RawMessage)
|
||||
if !ok {
|
||||
var err error
|
||||
if raw, err = json.Marshal(v); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
// A nil pointer is nothing, the same as nil.
|
||||
if string(raw) == "null" {
|
||||
return nil, nil
|
||||
}
|
||||
return raw, nil
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
package processor
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"testing"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
"gorm.io/driver/postgres"
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/logger"
|
||||
|
||||
"apskel-pos-be/internal/constants"
|
||||
"apskel-pos-be/internal/entities"
|
||||
"apskel-pos-be/internal/repository"
|
||||
)
|
||||
|
||||
type auditRepoFake struct{ rows []entities.AuditLog }
|
||||
|
||||
func (f *auditRepoFake) Insert(_ context.Context, e *entities.AuditLog) error {
|
||||
f.rows = append(f.rows, *e)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *auditRepoFake) ListByEntity(context.Context, uuid.UUID, string, uuid.UUID, int) ([]entities.AuditLog, error) {
|
||||
return f.rows, nil
|
||||
}
|
||||
|
||||
func validAuditEntry() AuditEntry {
|
||||
return AuditEntry{
|
||||
OrganizationID: uuid.New(),
|
||||
ActorType: constants.AuditActorUser,
|
||||
ActorID: ptr(uuid.New()),
|
||||
EntityType: constants.AuditEntityGame,
|
||||
EntityID: uuid.New(),
|
||||
Action: "STATUS_CHANGED",
|
||||
Before: map[string]string{"status": "DRAFT"},
|
||||
After: map[string]string{"status": "ACTIVE"},
|
||||
Source: constants.AuditSourceAdminAPI,
|
||||
}
|
||||
}
|
||||
|
||||
func TestAuditLogger_RecordsSnapshotsAsJSON(t *testing.T) {
|
||||
repo := &auditRepoFake{}
|
||||
l := NewAuditLogger(repo)
|
||||
require.NoError(t, l.Record(context.Background(), validAuditEntry()))
|
||||
|
||||
created := validAuditEntry()
|
||||
created.ActorType, created.ActorID = constants.AuditActorSystem, nil
|
||||
var nothing *entities.Game
|
||||
created.Before = nothing
|
||||
require.NoError(t, l.Record(context.Background(), created))
|
||||
|
||||
require.Len(t, repo.rows, 2)
|
||||
assert.JSONEq(t, `{"status": "DRAFT"}`, string(repo.rows[0].Before))
|
||||
assert.JSONEq(t, `{"status": "ACTIVE"}`, string(repo.rows[0].After))
|
||||
assert.Nil(t, repo.rows[1].Before, "a nil pointer is stored as NULL, not as JSON null")
|
||||
}
|
||||
|
||||
func TestAuditLogger_RejectsIncompleteEntries(t *testing.T) {
|
||||
for name, mutate := range map[string]func(*AuditEntry){
|
||||
"no organization": func(e *AuditEntry) { e.OrganizationID = uuid.Nil },
|
||||
"unknown actor type": func(e *AuditEntry) { e.ActorType = "ROBOT" },
|
||||
"USER without actor": func(e *AuditEntry) { e.ActorID = nil },
|
||||
"no entity type": func(e *AuditEntry) { e.EntityType = " " },
|
||||
"no entity id": func(e *AuditEntry) { e.EntityID = uuid.Nil },
|
||||
"no action": func(e *AuditEntry) { e.Action = "" },
|
||||
"no source": func(e *AuditEntry) { e.Source = "" },
|
||||
"unmarshallable": func(e *AuditEntry) { e.After = func() {} },
|
||||
} {
|
||||
repo := &auditRepoFake{}
|
||||
e := validAuditEntry()
|
||||
mutate(&e)
|
||||
err := NewAuditLogger(repo).Record(context.Background(), e)
|
||||
assert.ErrorIs(t, err, ErrInvalidAuditEntry, name)
|
||||
assert.Empty(t, repo.rows, name)
|
||||
}
|
||||
}
|
||||
|
||||
// An audit row commits and rolls back with the change it records. Needs
|
||||
// TEST_DATABASE_URL; see internal/repository/wallet_repository_test.go.
|
||||
func TestAuditLogger_AgainstPostgres(t *testing.T) {
|
||||
dsn := os.Getenv("TEST_DATABASE_URL")
|
||||
if dsn == "" {
|
||||
t.Skip("TEST_DATABASE_URL not set")
|
||||
}
|
||||
db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{Logger: logger.Default.LogMode(logger.Silent)})
|
||||
require.NoError(t, err)
|
||||
org := uuid.New()
|
||||
t.Cleanup(func() { db.Exec(`DELETE FROM audit_logs WHERE organization_id = ?`, org) })
|
||||
|
||||
repo := repository.NewAuditLogRepository(db)
|
||||
l := NewAuditLogger(repo)
|
||||
txm := repository.NewTxManager(db)
|
||||
entry := func(entityID uuid.UUID) AuditEntry {
|
||||
e := validAuditEntry()
|
||||
e.OrganizationID, e.EntityID, e.Reason = org, entityID, ptr("promo")
|
||||
return e
|
||||
}
|
||||
ctx := context.Background()
|
||||
|
||||
committed, rolledBack := uuid.New(), uuid.New()
|
||||
require.NoError(t, txm.WithTransaction(ctx, func(ctx context.Context) error {
|
||||
return l.Record(ctx, entry(committed))
|
||||
}))
|
||||
failure := assert.AnError
|
||||
err = txm.WithTransaction(ctx, func(ctx context.Context) error {
|
||||
require.NoError(t, l.Record(ctx, entry(rolledBack)))
|
||||
return failure
|
||||
})
|
||||
require.ErrorIs(t, err, failure)
|
||||
|
||||
rows, err := repo.ListByEntity(ctx, org, constants.AuditEntityGame, committed, 10)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, rows, 1)
|
||||
assert.Equal(t, "STATUS_CHANGED", rows[0].Action)
|
||||
assert.JSONEq(t, `{"status": "DRAFT"}`, string(rows[0].Before))
|
||||
assert.JSONEq(t, `{"status": "ACTIVE"}`, string(rows[0].After))
|
||||
assert.Equal(t, "promo", *rows[0].Reason)
|
||||
assert.False(t, rows[0].CreatedAt.IsZero())
|
||||
|
||||
rows, err = repo.ListByEntity(ctx, org, constants.AuditEntityGame, rolledBack, 10)
|
||||
require.NoError(t, err)
|
||||
assert.Empty(t, rows, "a rolled back change leaves no audit row")
|
||||
|
||||
assert.ErrorIs(t, l.Record(ctx, entry(uuid.New())), repository.ErrAuditTxRequired)
|
||||
}
|
||||
@@ -45,6 +45,8 @@ const (
|
||||
PinActionPay PinAction = "PAY"
|
||||
PinActionExchange PinAction = "EXCHANGE"
|
||||
PinActionTransfer PinAction = "TRANSFER"
|
||||
// Redeeming EnakPoint for an EnakGame voucher (docs/rfc-enakgame.md §7.4).
|
||||
PinActionRedeem PinAction = "REDEEM"
|
||||
)
|
||||
|
||||
type pinVerifier interface {
|
||||
|
||||
@@ -105,3 +105,35 @@ func TestCustomerPin_LockIsPushedThroughFCM(t *testing.T) {
|
||||
assert.Equal(t, "PIN EnakPoint kamu terkunci sampai 30 Sep 2026 10:30 WIB karena salah dimasukkan 5 kali. Jika ini bukan kamu, segera reset PIN lewat aplikasi.", push.body)
|
||||
assert.Equal(t, map[string]string{"type": NotificationTypePinLocked, "locked_until": "2026-09-30T03:30:00Z"}, push.data)
|
||||
}
|
||||
|
||||
// EG-503: redeeming a voucher follows the same PIN rules: five wrong attempts lock
|
||||
// it for 30 minutes, and a locked PIN is refused even when right. A transfer hold
|
||||
// after a reset does not apply to it.
|
||||
func TestCustomerPin_RedeemFollowsTheLockRules(t *testing.T) {
|
||||
customer := uuid.New()
|
||||
hash, err := bcrypt.GenerateFromPassword([]byte("482913"), bcrypt.MinCost)
|
||||
require.NoError(t, err)
|
||||
h := string(hash)
|
||||
now := time.Date(2026, 10, 7, 3, 0, 0, 0, time.UTC)
|
||||
held := now.Add(24 * time.Hour)
|
||||
repo := &pinRepoFake{state: repository.CustomerPinState{CustomerID: customer, PinHash: &h, TransferBlockedUntil: &held}}
|
||||
p := NewCustomerPinProcessor(repo, nil, ¬ifierFake{})
|
||||
p.now = func() time.Time { return now }
|
||||
ctx := context.Background()
|
||||
|
||||
require.NoError(t, p.VerifyPin(ctx, customer, "482913", PinActionRedeem, models.CustomerPinRequestInfo{}), "not held like a transfer")
|
||||
var pinErr *PinError
|
||||
for i := 1; i <= 4; i++ {
|
||||
err := p.VerifyPin(ctx, customer, "000000", PinActionRedeem, models.CustomerPinRequestInfo{})
|
||||
require.ErrorAs(t, err, &pinErr)
|
||||
assert.Equal(t, PinErrInvalid, pinErr.Code)
|
||||
assert.Equal(t, 5-i, pinErr.RemainingAttempts)
|
||||
}
|
||||
err = p.VerifyPin(ctx, customer, "000000", PinActionRedeem, models.CustomerPinRequestInfo{})
|
||||
require.ErrorAs(t, err, &pinErr)
|
||||
assert.Equal(t, PinErrLocked, pinErr.Code)
|
||||
assert.Equal(t, now.Add(30*time.Minute), *pinErr.Until)
|
||||
err = p.VerifyPin(ctx, customer, "482913", PinActionRedeem, models.CustomerPinRequestInfo{})
|
||||
require.ErrorAs(t, err, &pinErr)
|
||||
assert.Equal(t, PinErrLocked, pinErr.Code, "locked even with the right PIN")
|
||||
}
|
||||
|
||||
@@ -5,20 +5,17 @@ import (
|
||||
"fmt"
|
||||
|
||||
"apskel-pos-be/internal/models"
|
||||
"apskel-pos-be/internal/repository"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
type CustomerPointsProcessor struct {
|
||||
walletQuery *WalletQueryProcessor
|
||||
gameRepo *repository.GameRepository
|
||||
}
|
||||
|
||||
func NewCustomerPointsProcessor(walletQuery *WalletQueryProcessor, gameRepo *repository.GameRepository) *CustomerPointsProcessor {
|
||||
func NewCustomerPointsProcessor(walletQuery *WalletQueryProcessor) *CustomerPointsProcessor {
|
||||
return &CustomerPointsProcessor{
|
||||
walletQuery: walletQuery,
|
||||
gameRepo: gameRepo,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -74,94 +71,6 @@ func parseWalletCustomerID(customerID string) (uuid.UUID, error) {
|
||||
return id, nil
|
||||
}
|
||||
|
||||
// GetCustomerGamesAPI gets active SPIN games for customers
|
||||
func (p *CustomerPointsProcessor) GetCustomerGamesAPI(ctx context.Context) (*models.GetCustomerGamesResponse, error) {
|
||||
// Get active SPIN games
|
||||
games, err := p.gameRepo.GetActiveSpinGames(ctx)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to get active SPIN games: %w", err)
|
||||
}
|
||||
|
||||
// Convert to response format
|
||||
var gameResponses []models.CustomerGameResponse
|
||||
for _, game := range games {
|
||||
var prizeResponses []models.CustomerGamePrizeResponse
|
||||
for _, prize := range game.Prizes {
|
||||
prizeResponses = append(prizeResponses, models.CustomerGamePrizeResponse{
|
||||
ID: prize.ID,
|
||||
GameID: prize.GameID,
|
||||
Name: prize.Name,
|
||||
Image: prize.Image,
|
||||
Metadata: (*map[string]interface{})(&prize.Metadata),
|
||||
CreatedAt: prize.CreatedAt,
|
||||
UpdatedAt: prize.UpdatedAt,
|
||||
})
|
||||
}
|
||||
|
||||
gameResponses = append(gameResponses, models.CustomerGameResponse{
|
||||
ID: game.ID,
|
||||
Name: game.Name,
|
||||
Type: string(game.Type),
|
||||
IsActive: game.IsActive,
|
||||
Metadata: (*map[string]interface{})(&game.Metadata),
|
||||
Prizes: prizeResponses,
|
||||
CreatedAt: game.CreatedAt,
|
||||
UpdatedAt: game.UpdatedAt,
|
||||
})
|
||||
}
|
||||
|
||||
return &models.GetCustomerGamesResponse{
|
||||
Status: "SUCCESS",
|
||||
Message: "Customer games retrieved successfully.",
|
||||
Data: &models.GetCustomerGamesResponseData{
|
||||
Games: gameResponses,
|
||||
},
|
||||
}, nil
|
||||
}
|
||||
|
||||
// GetFerrisWheelGameAPI gets the Ferris Wheel game for customers
|
||||
func (p *CustomerPointsProcessor) GetFerrisWheelGameAPI(ctx context.Context) (*models.GetFerrisWheelGameResponse, error) {
|
||||
// Get Ferris Wheel game
|
||||
game, err := p.gameRepo.GetFerrisWheelGame(ctx)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to get Ferris Wheel game: %w", err)
|
||||
}
|
||||
|
||||
// Convert prizes to response format
|
||||
var prizeResponses []models.CustomerGamePrizeResponse
|
||||
for _, prize := range game.Prizes {
|
||||
prizeResponses = append(prizeResponses, models.CustomerGamePrizeResponse{
|
||||
ID: prize.ID,
|
||||
GameID: prize.GameID,
|
||||
Name: prize.Name,
|
||||
Image: prize.Image,
|
||||
Metadata: (*map[string]interface{})(&prize.Metadata),
|
||||
CreatedAt: prize.CreatedAt,
|
||||
UpdatedAt: prize.UpdatedAt,
|
||||
})
|
||||
}
|
||||
|
||||
// Convert game to response format
|
||||
gameResponse := models.CustomerGameResponse{
|
||||
ID: game.ID,
|
||||
Name: game.Name,
|
||||
Type: string(game.Type),
|
||||
IsActive: game.IsActive,
|
||||
Metadata: (*map[string]interface{})(&game.Metadata),
|
||||
Prizes: prizeResponses,
|
||||
CreatedAt: game.CreatedAt,
|
||||
UpdatedAt: game.UpdatedAt,
|
||||
}
|
||||
|
||||
return &models.GetFerrisWheelGameResponse{
|
||||
Status: "SUCCESS",
|
||||
Message: "Ferris Wheel game retrieved successfully.",
|
||||
Data: &models.GetFerrisWheelGameResponseData{
|
||||
Game: gameResponse,
|
||||
},
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (p *CustomerPointsProcessor) GetCustomerWalletExpiringAPI(ctx context.Context, customerID string) (*models.CustomerWalletExpiringList, error) {
|
||||
id, err := parseWalletCustomerID(customerID)
|
||||
if err != nil {
|
||||
|
||||
@@ -0,0 +1,462 @@
|
||||
package processor
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"regexp"
|
||||
"strings"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"apskel-pos-be/internal/constants"
|
||||
"apskel-pos-be/internal/entities"
|
||||
"apskel-pos-be/internal/models"
|
||||
"apskel-pos-be/internal/repository"
|
||||
)
|
||||
|
||||
// ErrEnakGameRejected wraps every reason an EnakGame request is refused: a field out
|
||||
// of bounds, a slug in use, an archived game, a retired configuration. The message
|
||||
// says which.
|
||||
var ErrEnakGameRejected = errors.New("enakgame request refused")
|
||||
|
||||
const (
|
||||
enakGameDefaultSessionTTL = 600
|
||||
enakGameMaxSessionTTL = 24 * 60 * 60
|
||||
enakGamePageLimit = 20
|
||||
enakGameMaxPageLimit = 100
|
||||
)
|
||||
|
||||
var enakGameSlugPattern = regexp.MustCompile(`^[a-z0-9]+(-[a-z0-9]+)*$`)
|
||||
|
||||
func enakGameRejected(format string, args ...any) error {
|
||||
return fmt.Errorf("%w: %s", ErrEnakGameRejected, fmt.Sprintf(format, args...))
|
||||
}
|
||||
|
||||
// EnakGameAdminProcessor manages an organization's EnakGame games and their reward
|
||||
// configurations (docs/rfc-enakgame.md §5.1, §5.2, §11). Every change is written to
|
||||
// audit_logs in the same transaction (§13).
|
||||
type EnakGameAdminProcessor struct {
|
||||
games repository.EnakGameRepository
|
||||
audit *AuditLogger
|
||||
tx TxRunner
|
||||
}
|
||||
|
||||
func NewEnakGameAdminProcessor(games repository.EnakGameRepository, audit *AuditLogger, tx TxRunner) *EnakGameAdminProcessor {
|
||||
return &EnakGameAdminProcessor{games: games, audit: audit, tx: tx}
|
||||
}
|
||||
|
||||
func (p *EnakGameAdminProcessor) record(ctx context.Context, organizationID, actor uuid.UUID, entityType string, entityID uuid.UUID, action string, before, after any, reason *string) error {
|
||||
return p.audit.Record(ctx, AuditEntry{
|
||||
OrganizationID: organizationID,
|
||||
ActorType: constants.AuditActorUser,
|
||||
ActorID: &actor,
|
||||
EntityType: entityType,
|
||||
EntityID: entityID,
|
||||
Action: action,
|
||||
Before: before,
|
||||
After: after,
|
||||
Reason: reason,
|
||||
Source: constants.AuditSourceAdminAPI,
|
||||
})
|
||||
}
|
||||
|
||||
// EnakGameInputFrom is a game's current values as an input, for a change that only
|
||||
// sends the fields it changes.
|
||||
func EnakGameInputFrom(game *models.EnakGame) models.EnakGameInput {
|
||||
return models.EnakGameInput{
|
||||
Name: game.Name, Type: game.Type, Slug: game.Slug, Description: game.Description,
|
||||
ThumbnailURL: game.ThumbnailURL, GameURL: game.GameURL, Version: game.Version, Status: game.Status,
|
||||
EntryCost: game.EntryCost, SessionTTLSeconds: game.SessionTTLSeconds, ResultRules: game.ResultRules,
|
||||
}
|
||||
}
|
||||
|
||||
func (p *EnakGameAdminProcessor) CreateGame(ctx context.Context, organizationID, actor uuid.UUID, in models.EnakGameInput) (*models.EnakGame, error) {
|
||||
if in.Type == "" {
|
||||
in.Type = string(entities.GameTypeMinigame)
|
||||
}
|
||||
if in.Status == "" {
|
||||
in.Status = constants.GameStatusDraft
|
||||
}
|
||||
if in.SessionTTLSeconds == 0 {
|
||||
in.SessionTTLSeconds = enakGameDefaultSessionTTL
|
||||
}
|
||||
if err := validateEnakGameInput(&in); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
switch in.Status {
|
||||
case constants.GameStatusDraft, constants.GameStatusActive, constants.GameStatusInactive:
|
||||
default:
|
||||
return nil, enakGameRejected("a new game must be DRAFT, ACTIVE or INACTIVE")
|
||||
}
|
||||
|
||||
game := &entities.Game{OrganizationID: &organizationID, Status: in.Status}
|
||||
applyEnakGameInput(game, in)
|
||||
err := p.tx.WithTransaction(ctx, func(ctx context.Context) error {
|
||||
if err := p.games.CreateGame(ctx, game); err != nil {
|
||||
return err
|
||||
}
|
||||
return p.record(ctx, organizationID, actor, constants.AuditEntityGame, game.ID, "CREATED", nil, enakGameModel(game), nil)
|
||||
})
|
||||
if err != nil {
|
||||
return nil, enakGameError(err)
|
||||
}
|
||||
return enakGameModel(game), nil
|
||||
}
|
||||
|
||||
func (p *EnakGameAdminProcessor) GetGame(ctx context.Context, organizationID, id uuid.UUID) (*models.EnakGame, error) {
|
||||
game, err := p.games.GetGame(ctx, organizationID, id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return enakGameModel(game), nil
|
||||
}
|
||||
|
||||
func (p *EnakGameAdminProcessor) ListGames(ctx context.Context, organizationID uuid.UUID, q models.EnakGameListQuery) (*models.PaginatedResponse[models.EnakGame], error) {
|
||||
page, limit := enakGamePage(q.Page, q.Limit)
|
||||
statuses := []string{constants.GameStatusDraft, constants.GameStatusActive, constants.GameStatusInactive}
|
||||
if q.Status != "" {
|
||||
status := strings.ToUpper(strings.TrimSpace(q.Status))
|
||||
if !isEnakGameStatus(status) {
|
||||
return nil, enakGameRejected("unknown status %q", q.Status)
|
||||
}
|
||||
statuses = []string{status}
|
||||
}
|
||||
games, total, err := p.games.ListGames(ctx, repository.EnakGameFilter{
|
||||
OrganizationID: organizationID, Statuses: statuses, Search: strings.TrimSpace(q.Search),
|
||||
Offset: (page - 1) * limit, Limit: limit,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items := make([]models.EnakGame, 0, len(games))
|
||||
for i := range games {
|
||||
items = append(items, *enakGameModel(&games[i]))
|
||||
}
|
||||
return &models.PaginatedResponse[models.EnakGame]{Data: items, Pagination: enakGamePagination(page, limit, total)}, nil
|
||||
}
|
||||
|
||||
// UpdateGame changes everything but the status, which has its own endpoint. An
|
||||
// archived game never changes.
|
||||
func (p *EnakGameAdminProcessor) UpdateGame(ctx context.Context, organizationID, actor, id uuid.UUID, in models.EnakGameInput) (*models.EnakGame, error) {
|
||||
if err := validateEnakGameInput(&in); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var after *models.EnakGame
|
||||
err := p.tx.WithTransaction(ctx, func(ctx context.Context) error {
|
||||
game, err := p.games.LockGame(ctx, organizationID, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if game.Status == constants.GameStatusArchived {
|
||||
return enakGameRejected("an archived game cannot change")
|
||||
}
|
||||
before := enakGameModel(game)
|
||||
applyEnakGameInput(game, in)
|
||||
if err := p.games.UpdateGame(ctx, game); err != nil {
|
||||
return err
|
||||
}
|
||||
after = enakGameModel(game)
|
||||
return p.record(ctx, organizationID, actor, constants.AuditEntityGame, id, "UPDATED", before, after, nil)
|
||||
})
|
||||
if err != nil {
|
||||
return nil, enakGameError(err)
|
||||
}
|
||||
return p.GetGame(ctx, organizationID, after.ID)
|
||||
}
|
||||
|
||||
// SetGameStatus moves a game between DRAFT, ACTIVE and INACTIVE, or archives it for
|
||||
// good. Sessions still open on a game leaving ACTIVE are refunded by the session job
|
||||
// (§7.3), not here.
|
||||
func (p *EnakGameAdminProcessor) SetGameStatus(ctx context.Context, organizationID, actor, id uuid.UUID, in models.EnakGameStatusInput) (*models.EnakGame, error) {
|
||||
status := strings.ToUpper(strings.TrimSpace(in.Status))
|
||||
if !isEnakGameStatus(status) {
|
||||
return nil, enakGameRejected("status must be DRAFT, ACTIVE, INACTIVE or ARCHIVED")
|
||||
}
|
||||
if err := validateReason(in.Reason); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
err := p.tx.WithTransaction(ctx, func(ctx context.Context) error {
|
||||
game, err := p.games.LockGame(ctx, organizationID, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if game.Status == status {
|
||||
return nil
|
||||
}
|
||||
if game.Status == constants.GameStatusArchived {
|
||||
return enakGameRejected("an archived game cannot change")
|
||||
}
|
||||
if err := p.games.SetGameStatus(ctx, organizationID, id, status); err != nil {
|
||||
return err
|
||||
}
|
||||
return p.record(ctx, organizationID, actor, constants.AuditEntityGame, id, "STATUS_CHANGED",
|
||||
map[string]string{"status": game.Status}, map[string]string{"status": status}, in.Reason)
|
||||
})
|
||||
if err != nil {
|
||||
return nil, enakGameError(err)
|
||||
}
|
||||
return p.GetGame(ctx, organizationID, id)
|
||||
}
|
||||
|
||||
// CreateRewardConfig stores a new DRAFT version of a game's reward configuration. A
|
||||
// configuration is never edited (D7): a change is a new version, activated on its
|
||||
// own.
|
||||
func (p *EnakGameAdminProcessor) CreateRewardConfig(ctx context.Context, organizationID, actor, gameID uuid.UUID, in models.GameRewardConfigInput) (*models.GameRewardConfig, error) {
|
||||
rewardType := strings.ToUpper(strings.TrimSpace(in.RewardType))
|
||||
calculator, err := RewardCalculatorFor(rewardType)
|
||||
if err != nil {
|
||||
return nil, enakGameRejected("%v", err)
|
||||
}
|
||||
if len(in.Rules) == 0 {
|
||||
return nil, enakGameRejected("rules are required")
|
||||
}
|
||||
if err := calculator.Validate(in.Rules); err != nil {
|
||||
return nil, enakGameRejected("%v", err)
|
||||
}
|
||||
if in.MaxReward < 0 {
|
||||
return nil, enakGameRejected("max_reward must be 0 or more")
|
||||
}
|
||||
if err := validateReason(in.Reason); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var rules bytes.Buffer
|
||||
if err := json.Compact(&rules, in.Rules); err != nil {
|
||||
return nil, enakGameRejected("rules: %v", err)
|
||||
}
|
||||
|
||||
config := &entities.GameRewardConfig{
|
||||
OrganizationID: organizationID, GameID: gameID, RewardType: rewardType,
|
||||
Rules: entities.JSONDocument(rules.Bytes()), MaxReward: in.MaxReward,
|
||||
Status: constants.GameRewardConfigStatusDraft, EffectiveAt: in.EffectiveAt, CreatedBy: actor, Reason: in.Reason,
|
||||
}
|
||||
err = p.tx.WithTransaction(ctx, func(ctx context.Context) error {
|
||||
// The game lock also orders versions of the same game one after the other.
|
||||
game, err := p.games.LockGame(ctx, organizationID, gameID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if game.Status == constants.GameStatusArchived {
|
||||
return enakGameRejected("an archived game cannot change")
|
||||
}
|
||||
if err := p.games.CreateRewardConfig(ctx, config); err != nil {
|
||||
return err
|
||||
}
|
||||
return p.record(ctx, organizationID, actor, constants.AuditEntityGameRewardConfig, config.ID, "CREATED",
|
||||
nil, rewardConfigModel(config), in.Reason)
|
||||
})
|
||||
if err != nil {
|
||||
return nil, enakGameError(err)
|
||||
}
|
||||
return rewardConfigModel(config), nil
|
||||
}
|
||||
|
||||
// ActivateRewardConfig makes a DRAFT version the game's active configuration and
|
||||
// retires the one active before, in one transaction. Activating the active version
|
||||
// again changes nothing. A retired version stays retired: going back means a new
|
||||
// version with the old rules.
|
||||
func (p *EnakGameAdminProcessor) ActivateRewardConfig(ctx context.Context, organizationID, actor, id uuid.UUID, in models.GameRewardConfigActivateInput) (*models.GameRewardConfig, error) {
|
||||
if err := validateReason(in.Reason); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var activated *entities.GameRewardConfig
|
||||
err := p.tx.WithTransaction(ctx, func(ctx context.Context) error {
|
||||
config, err := p.games.GetRewardConfig(ctx, organizationID, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// Activations of the same game wait for each other here, so exactly one
|
||||
// version ends up active.
|
||||
game, err := p.games.LockGame(ctx, organizationID, config.GameID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if game.Status == constants.GameStatusArchived {
|
||||
return enakGameRejected("an archived game cannot change")
|
||||
}
|
||||
if config, err = p.games.GetRewardConfig(ctx, organizationID, id); err != nil {
|
||||
return err
|
||||
}
|
||||
activated = config
|
||||
switch config.Status {
|
||||
case constants.GameRewardConfigStatusActive:
|
||||
return nil
|
||||
case constants.GameRewardConfigStatusRetired:
|
||||
return enakGameRejected("version %d is retired; create a new version instead", config.Version)
|
||||
}
|
||||
|
||||
current, err := p.games.GetActiveRewardConfig(ctx, organizationID, config.GameID)
|
||||
if err != nil && !errors.Is(err, repository.ErrGameRewardConfigNotFound) {
|
||||
return err
|
||||
}
|
||||
if current != nil {
|
||||
if _, err := p.moveRewardConfig(ctx, organizationID, actor, current, constants.GameRewardConfigStatusRetired, "RETIRED", in.Reason); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
activated, err = p.moveRewardConfig(ctx, organizationID, actor, config, constants.GameRewardConfigStatusActive, "ACTIVATED", in.Reason)
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
return nil, enakGameError(err)
|
||||
}
|
||||
return rewardConfigModel(activated), nil
|
||||
}
|
||||
|
||||
func (p *EnakGameAdminProcessor) moveRewardConfig(ctx context.Context, organizationID, actor uuid.UUID, config *entities.GameRewardConfig, to, action string, reason *string) (*entities.GameRewardConfig, error) {
|
||||
moved, err := p.games.SetRewardConfigStatus(ctx, organizationID, config.ID, config.Status, to)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !moved {
|
||||
return nil, enakGameRejected("version %d changed meanwhile; try again", config.Version)
|
||||
}
|
||||
before := config.Status
|
||||
next := *config
|
||||
next.Status = to
|
||||
err = p.record(ctx, organizationID, actor, constants.AuditEntityGameRewardConfig, config.ID, action,
|
||||
map[string]string{"status": before}, map[string]string{"status": to}, reason)
|
||||
return &next, err
|
||||
}
|
||||
|
||||
// ListRewardConfigs returns every version of a game's configuration, newest first.
|
||||
func (p *EnakGameAdminProcessor) ListRewardConfigs(ctx context.Context, organizationID, gameID uuid.UUID) ([]models.GameRewardConfig, error) {
|
||||
if _, err := p.games.GetGame(ctx, organizationID, gameID); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
configs, err := p.games.ListRewardConfigs(ctx, organizationID, gameID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out := make([]models.GameRewardConfig, 0, len(configs))
|
||||
for i := range configs {
|
||||
out = append(out, *rewardConfigModel(&configs[i]))
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// enakGameError turns a slug collision into a refusal; anything else passes as is.
|
||||
func enakGameError(err error) error {
|
||||
if errors.Is(err, repository.ErrEnakGameSlugTaken) {
|
||||
return enakGameRejected("another game already uses this slug")
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func isEnakGameStatus(s string) bool {
|
||||
switch s {
|
||||
case constants.GameStatusDraft, constants.GameStatusActive, constants.GameStatusInactive, constants.GameStatusArchived:
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func validateReason(reason *string) error {
|
||||
if reason != nil && len(*reason) > 255 {
|
||||
return enakGameRejected("reason must be at most 255 characters")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func validateEnakGameInput(in *models.EnakGameInput) error {
|
||||
in.Name = strings.TrimSpace(in.Name)
|
||||
in.Slug = strings.TrimSpace(in.Slug)
|
||||
in.Type = strings.ToUpper(strings.TrimSpace(in.Type))
|
||||
in.Status = strings.ToUpper(strings.TrimSpace(in.Status))
|
||||
switch {
|
||||
case in.Name == "" || len(in.Name) > 255:
|
||||
return enakGameRejected("name is required, at most 255 characters")
|
||||
case in.Type != string(entities.GameTypeSpin) && in.Type != string(entities.GameTypeRaffle) && in.Type != string(entities.GameTypeMinigame):
|
||||
return enakGameRejected("type must be SPIN, RAFFLE or MINIGAME")
|
||||
case len(in.Slug) > 100 || !enakGameSlugPattern.MatchString(in.Slug):
|
||||
return enakGameRejected("slug must be lowercase letters, digits and single dashes, at most 100 characters")
|
||||
case in.EntryCost < 1:
|
||||
// PRD §10.1: no game is free.
|
||||
return enakGameRejected("entry_cost must be at least 1")
|
||||
case in.SessionTTLSeconds < 1 || in.SessionTTLSeconds > enakGameMaxSessionTTL:
|
||||
return enakGameRejected("session_ttl_seconds must be between 1 and %d", enakGameMaxSessionTTL)
|
||||
}
|
||||
for field, value := range map[string]*string{"thumbnail_url": in.ThumbnailURL, "game_url": in.GameURL} {
|
||||
if value != nil && len(*value) > 500 {
|
||||
return enakGameRejected("%s must be at most 500 characters", field)
|
||||
}
|
||||
}
|
||||
if in.Version != nil && len(*in.Version) > 50 {
|
||||
return enakGameRejected("version must be at most 50 characters")
|
||||
}
|
||||
return validateResultRules(in.ResultRules)
|
||||
}
|
||||
|
||||
func validateResultRules(r entities.GameResultRules) error {
|
||||
switch {
|
||||
case r.MaxScore != nil && *r.MaxScore < 0:
|
||||
return enakGameRejected("result_rules.max_score must be 0 or more")
|
||||
case r.MinDurationSeconds != nil && *r.MinDurationSeconds < 0:
|
||||
return enakGameRejected("result_rules.min_duration_seconds must be 0 or more")
|
||||
case r.MaxScorePerSecond != nil && !(*r.MaxScorePerSecond > 0):
|
||||
return enakGameRejected("result_rules.max_score_per_second must be more than 0")
|
||||
case r.DailyRewardLimit != nil && *r.DailyRewardLimit < 0:
|
||||
return enakGameRejected("result_rules.daily_reward_limit must be 0 or more")
|
||||
}
|
||||
seen := map[string]bool{}
|
||||
for _, outcome := range r.Outcomes {
|
||||
if strings.TrimSpace(outcome) == "" {
|
||||
return enakGameRejected("result_rules.outcomes cannot hold an empty outcome")
|
||||
}
|
||||
if seen[outcome] {
|
||||
return enakGameRejected("result_rules.outcomes lists %q twice", outcome)
|
||||
}
|
||||
seen[outcome] = true
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func applyEnakGameInput(game *entities.Game, in models.EnakGameInput) {
|
||||
slug := in.Slug
|
||||
game.Name = in.Name
|
||||
game.Type = entities.GameType(in.Type)
|
||||
game.Slug = &slug
|
||||
game.Description = in.Description
|
||||
game.ThumbnailURL = in.ThumbnailURL
|
||||
game.GameURL = in.GameURL
|
||||
game.Version = in.Version
|
||||
game.EntryCost = in.EntryCost
|
||||
game.SessionTTLSeconds = in.SessionTTLSeconds
|
||||
game.ResultRules = in.ResultRules
|
||||
}
|
||||
|
||||
func enakGameModel(g *entities.Game) *models.EnakGame {
|
||||
m := &models.EnakGame{
|
||||
ID: g.ID, Name: g.Name, Type: string(g.Type), Description: g.Description, ThumbnailURL: g.ThumbnailURL,
|
||||
GameURL: g.GameURL, Version: g.Version, Status: g.Status, EntryCost: g.EntryCost,
|
||||
SessionTTLSeconds: g.SessionTTLSeconds, ResultRules: g.ResultRules, CreatedAt: g.CreatedAt, UpdatedAt: g.UpdatedAt,
|
||||
}
|
||||
if g.Slug != nil {
|
||||
m.Slug = *g.Slug
|
||||
}
|
||||
return m
|
||||
}
|
||||
|
||||
func rewardConfigModel(c *entities.GameRewardConfig) *models.GameRewardConfig {
|
||||
return &models.GameRewardConfig{
|
||||
ID: c.ID, GameID: c.GameID, Version: c.Version, RewardType: c.RewardType, Rules: json.RawMessage(c.Rules),
|
||||
MaxReward: c.MaxReward, Status: c.Status, EffectiveAt: c.EffectiveAt, CreatedBy: c.CreatedBy,
|
||||
Reason: c.Reason, BaseConfigID: c.BaseConfigID, Multiplier: c.Multiplier, BudgetID: c.BudgetID, CreatedAt: c.CreatedAt,
|
||||
}
|
||||
}
|
||||
|
||||
func enakGamePage(page, limit int) (int, int) {
|
||||
if page < 1 {
|
||||
page = 1
|
||||
}
|
||||
if limit < 1 || limit > enakGameMaxPageLimit {
|
||||
limit = enakGamePageLimit
|
||||
}
|
||||
return page, limit
|
||||
}
|
||||
|
||||
func enakGamePagination(page, limit int, total int64) models.Pagination {
|
||||
return models.Pagination{Page: page, Limit: limit, Total: total, TotalPages: int((total + int64(limit) - 1) / int64(limit))}
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
package processor
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"apskel-pos-be/internal/constants"
|
||||
"apskel-pos-be/internal/entities"
|
||||
"apskel-pos-be/internal/models"
|
||||
"apskel-pos-be/internal/repository"
|
||||
)
|
||||
|
||||
// EG-903 against Postgres. Needs TEST_DATABASE_URL; see
|
||||
// internal/repository/wallet_repository_test.go.
|
||||
func TestEnakGameAnalytics_AgainstPostgres(t *testing.T) {
|
||||
e := newEnakGameEnv(t)
|
||||
ctx := e.ctx()
|
||||
analytics := NewEnakGameAnalyticsProcessor(repository.NewEnakGameAnalyticsRepository(e.db))
|
||||
|
||||
// Sessions and ledger rows are stamped with the test clock and the database's,
|
||||
// both now: a range around today holds them all.
|
||||
today := walletDay(e.now)
|
||||
q := models.EnakGameAnalyticsQuery{From: today.AddDate(0, 0, -1).Format("2006-01-02"), To: today.AddDate(0, 0, 1).Format("2006-01-02")}
|
||||
|
||||
tap := e.gameWith("tap", entities.GameResultRules{}, constants.GameRewardTypeFixed, `{"amount": 10}`, 10)
|
||||
run := e.gameWith("run", entities.GameResultRules{}, constants.GameRewardTypeScoreBased,
|
||||
`{"bands": [{"min": 0, "max": 100, "amount": 5}, {"min": 101, "amount": 20}]}`, 20)
|
||||
e.coins(e.alice, 10, nil)
|
||||
e.coins(e.bob, 10, nil)
|
||||
for i, key := range []string{"tap-1", "tap-2"} {
|
||||
started, err := e.sessions.Start(ctx, e.alice, tap.ID, key)
|
||||
require.NoError(t, err, i)
|
||||
_, err = e.sessions.Complete(ctx, e.alice, started.SessionID, models.GameSessionCompleteInput{})
|
||||
require.NoError(t, err, i)
|
||||
}
|
||||
_, err := e.sessions.Start(ctx, e.bob, tap.ID, "tap-3") // left open
|
||||
require.NoError(t, err)
|
||||
started, err := e.sessions.Start(ctx, e.alice, run.ID, "run-1")
|
||||
require.NoError(t, err)
|
||||
_, err = e.sessions.Complete(ctx, e.alice, started.SessionID, models.GameSessionCompleteInput{Score: ptr(int64(150))})
|
||||
require.NoError(t, err)
|
||||
|
||||
games, err := analytics.Games(ctx, e.orgA, q)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, models.EnakGameStats{
|
||||
Plays: 4, Completed: 3, Players: 2, AverageScore: ptr(150.0),
|
||||
AverageReward: 13.33, RewardPerPlay: 10, CoinIssued: 40, EntryCostPaid: 8,
|
||||
}, games.Totals)
|
||||
require.Len(t, games.Games, 2)
|
||||
assert.Equal(t, tap.ID, games.Games[0].GameID, "most played first")
|
||||
assert.EqualValues(t, 3, games.Games[0].Plays)
|
||||
assert.EqualValues(t, 2, games.Games[0].Players)
|
||||
assert.Nil(t, games.Games[0].AverageScore, "FIXED reports no score")
|
||||
assert.EqualValues(t, 20, games.Games[1].CoinIssued)
|
||||
|
||||
one, err := analytics.Games(ctx, e.orgA, models.EnakGameAnalyticsQuery{From: q.From, To: q.To, GameID: run.ID.String()})
|
||||
require.NoError(t, err)
|
||||
assert.EqualValues(t, 1, one.Totals.Plays)
|
||||
require.Len(t, one.Games, 1)
|
||||
|
||||
other, err := analytics.Games(ctx, e.orgB, q)
|
||||
require.NoError(t, err)
|
||||
assert.Zero(t, other.Totals.Plays, "another organization's sessions never show")
|
||||
assert.Empty(t, other.Games)
|
||||
|
||||
economy, err := analytics.Economy(ctx, e.orgA, q)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, models.EnakGameCoinFlows{
|
||||
Generated: 60, GameRewards: 40, SpentOnGames: 8, Spent: 8, Outstanding: 52,
|
||||
}, economy.Coin)
|
||||
assert.Zero(t, economy.Point)
|
||||
|
||||
// A range before anything happened.
|
||||
empty, err := analytics.Economy(ctx, e.orgA, models.EnakGameAnalyticsQuery{From: "2020-01-01", To: "2020-01-31"})
|
||||
require.NoError(t, err)
|
||||
assert.Zero(t, empty.Coin)
|
||||
assert.Empty(t, empty.ByType)
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
package processor
|
||||
|
||||
import (
|
||||
"context"
|
||||
"math"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"apskel-pos-be/internal/constants"
|
||||
"apskel-pos-be/internal/models"
|
||||
"apskel-pos-be/internal/repository"
|
||||
)
|
||||
|
||||
// enakGameAnalyticsMaxDays bounds a range, so one request cannot scan years of ledger.
|
||||
const enakGameAnalyticsMaxDays = 366
|
||||
|
||||
// EnakGameAnalyticsProcessor answers the EnakGame dashboards (docs/tasks-enakgame.md
|
||||
// EG-903, PRD §36) for an organization and a range of days in Asia/Jakarta.
|
||||
type EnakGameAnalyticsProcessor struct {
|
||||
analytics repository.EnakGameAnalyticsRepository
|
||||
}
|
||||
|
||||
func NewEnakGameAnalyticsProcessor(analytics repository.EnakGameAnalyticsRepository) *EnakGameAnalyticsProcessor {
|
||||
return &EnakGameAnalyticsProcessor{analytics: analytics}
|
||||
}
|
||||
|
||||
// analyticsRange reads from and to, both days included, as [start, end).
|
||||
func analyticsRange(q models.EnakGameAnalyticsQuery) (start, end time.Time, err error) {
|
||||
from, err := time.Parse("2006-01-02", strings.TrimSpace(q.From))
|
||||
if err != nil {
|
||||
return start, end, enakGameRejected("from must be a date like 2026-10-01")
|
||||
}
|
||||
to, err := time.Parse("2006-01-02", strings.TrimSpace(q.To))
|
||||
if err != nil {
|
||||
return start, end, enakGameRejected("to must be a date like 2026-10-31")
|
||||
}
|
||||
if to.Before(from) {
|
||||
return start, end, enakGameRejected("to cannot be before from")
|
||||
}
|
||||
if daysBetween(from, to)+1 > enakGameAnalyticsMaxDays {
|
||||
return start, end, enakGameRejected("the range can span at most %d days", enakGameAnalyticsMaxDays)
|
||||
}
|
||||
return jakartaMidnight(from), jakartaMidnight(to.AddDate(0, 0, 1)), nil
|
||||
}
|
||||
|
||||
// Games is how the organization's games were played, by the day each session
|
||||
// started.
|
||||
func (p *EnakGameAnalyticsProcessor) Games(ctx context.Context, organizationID uuid.UUID, q models.EnakGameAnalyticsQuery) (*models.EnakGameAnalytics, error) {
|
||||
start, end, err := analyticsRange(q)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var gameID *uuid.UUID
|
||||
if s := strings.TrimSpace(q.GameID); s != "" {
|
||||
id, err := uuid.Parse(s)
|
||||
if err != nil {
|
||||
return nil, enakGameRejected("game_id must be a UUID")
|
||||
}
|
||||
gameID = &id
|
||||
}
|
||||
rows, err := p.analytics.SessionStats(ctx, organizationID, start, end, gameID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out := &models.EnakGameAnalytics{From: strings.TrimSpace(q.From), To: strings.TrimSpace(q.To), Games: []models.EnakGameGameStats{}}
|
||||
for _, row := range rows {
|
||||
if row.GameID == nil {
|
||||
out.Totals = gameStats(row)
|
||||
continue
|
||||
}
|
||||
g := models.EnakGameGameStats{GameID: *row.GameID, EnakGameStats: gameStats(row)}
|
||||
if row.GameName != nil {
|
||||
g.GameName = *row.GameName
|
||||
}
|
||||
out.Games = append(out.Games, g)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func gameStats(r repository.GameSessionStats) models.EnakGameStats {
|
||||
s := models.EnakGameStats{
|
||||
Plays: r.Plays, Completed: r.Completed, Refunded: r.Refunded, Expired: r.Expired, Flagged: r.Flagged,
|
||||
Players: r.Players, AverageScore: r.AverageScore, CoinIssued: r.CoinIssued,
|
||||
EntryCostPaid: r.EntryCost, CoinRefunded: r.CoinRefunded,
|
||||
}
|
||||
if r.Completed > 0 {
|
||||
s.AverageReward = ratio(r.CoinIssued, r.Completed)
|
||||
}
|
||||
if r.Plays > 0 {
|
||||
s.RewardPerPlay = ratio(r.CoinIssued, r.Plays)
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
// ratio is part / whole with two decimals.
|
||||
func ratio(part, whole int64) float64 {
|
||||
return math.Round(float64(part)*100/float64(whole)) / 100
|
||||
}
|
||||
|
||||
// Economy is how EnakCoin and EnakPoint moved in the organization, from the ledger.
|
||||
func (p *EnakGameAnalyticsProcessor) Economy(ctx context.Context, organizationID uuid.UUID, q models.EnakGameAnalyticsQuery) (*models.EnakGameEconomyAnalytics, error) {
|
||||
start, end, err := analyticsRange(q)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
flows, err := p.analytics.WalletFlows(ctx, organizationID, start, end)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
balances, err := p.analytics.BalancesAt(ctx, organizationID, end)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out := economy(flows, balances)
|
||||
out.From, out.To = strings.TrimSpace(q.From), strings.TrimSpace(q.To)
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// economy turns ledger totals into the headline numbers. Transfers move value between
|
||||
// customers and count in none of them; ByType still lists them.
|
||||
func economy(flows []repository.WalletFlow, balances map[string]int64) *models.EnakGameEconomyAnalytics {
|
||||
type key struct{ currency, txType string }
|
||||
byKey := make(map[key]repository.WalletFlow, len(flows))
|
||||
out := &models.EnakGameEconomyAnalytics{ByType: make([]models.WalletFlowTotals, 0, len(flows))}
|
||||
for _, f := range flows {
|
||||
byKey[key{f.Currency, f.Type}] = f
|
||||
out.ByType = append(out.ByType, models.WalletFlowTotals{
|
||||
Currency: f.Currency, Type: f.Type, Credit: f.Credit, Debit: f.Debit, Transactions: f.Transactions,
|
||||
})
|
||||
}
|
||||
coin := func(txType string) repository.WalletFlow { return byKey[key{constants.WalletCurrencyCoin, txType}] }
|
||||
point := func(txType string) repository.WalletFlow { return byKey[key{constants.WalletCurrencyPoint, txType}] }
|
||||
|
||||
c := &out.Coin
|
||||
c.GameRewards = coin(constants.WalletTxTypeGameReward).Credit
|
||||
c.Generated = c.GameRewards + coin(constants.WalletTxTypeEarn).Credit - coin(constants.WalletTxTypeEarnReversal).Debit +
|
||||
coin(constants.WalletTxTypeMigration).Credit + coin(constants.WalletTxTypeAdjustment).Credit
|
||||
c.SpentOnGames = coin(constants.WalletTxTypeGameSpend).Debit - coin(constants.WalletTxTypeGameSpendRefund).Credit
|
||||
c.Exchanged = coin(constants.WalletTxTypeExchangeOut).Debit
|
||||
c.Spent = c.SpentOnGames + c.Exchanged
|
||||
c.Expired = coin(constants.WalletTxTypeExpire).Debit
|
||||
c.Outstanding = balances[constants.WalletCurrencyCoin]
|
||||
|
||||
pt := &out.Point
|
||||
pt.Earned = point(constants.WalletTxTypeEarn).Credit - point(constants.WalletTxTypeEarnReversal).Debit
|
||||
pt.Exchanged = point(constants.WalletTxTypeExchangeIn).Credit
|
||||
pt.Redeemed = point(constants.WalletTxTypeRewardRedeem).Debit - point(constants.WalletTxTypeRewardRedeemRefund).Credit
|
||||
pt.Expired = point(constants.WalletTxTypeExpire).Debit
|
||||
pt.Balance = balances[constants.WalletCurrencyPoint]
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
package processor
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"apskel-pos-be/internal/constants"
|
||||
"apskel-pos-be/internal/models"
|
||||
"apskel-pos-be/internal/repository"
|
||||
)
|
||||
|
||||
func TestAnalyticsRange(t *testing.T) {
|
||||
start, end, err := analyticsRange(models.EnakGameAnalyticsQuery{From: "2026-10-01", To: "2026-10-31"})
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, time.Date(2026, 9, 30, 17, 0, 0, 0, time.UTC), start.UTC(), "midnight in Jakarta")
|
||||
assert.Equal(t, time.Date(2026, 10, 31, 17, 0, 0, 0, time.UTC), end.UTC(), "the last day included")
|
||||
|
||||
_, _, err = analyticsRange(models.EnakGameAnalyticsQuery{From: "2026-01-01", To: "2027-01-01"})
|
||||
require.NoError(t, err, "366 days")
|
||||
for name, q := range map[string]models.EnakGameAnalyticsQuery{
|
||||
"no from": {To: "2026-10-31"},
|
||||
"no to": {From: "2026-10-01"},
|
||||
"backwards": {From: "2026-10-31", To: "2026-10-01"},
|
||||
"too long": {From: "2026-01-01", To: "2027-01-02"},
|
||||
"not dates": {From: "1 Oct", To: "31 Oct"},
|
||||
} {
|
||||
_, _, err := analyticsRange(q)
|
||||
assert.ErrorIs(t, err, ErrEnakGameRejected, name)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGameStats(t *testing.T) {
|
||||
s := gameStats(repository.GameSessionStats{Plays: 3, Completed: 2, CoinIssued: 25, EntryCost: 6, CoinRefunded: 2})
|
||||
assert.EqualValues(t, 12.5, s.AverageReward)
|
||||
assert.InDelta(t, 8.33, s.RewardPerPlay, 1e-9)
|
||||
assert.EqualValues(t, 6, s.EntryCostPaid)
|
||||
|
||||
s = gameStats(repository.GameSessionStats{})
|
||||
assert.Zero(t, s.AverageReward, "no division by zero")
|
||||
assert.Zero(t, s.RewardPerPlay)
|
||||
assert.Nil(t, s.AverageScore)
|
||||
}
|
||||
|
||||
// EG-903: the economy's headline numbers from the ledger's totals.
|
||||
func TestEconomy(t *testing.T) {
|
||||
coin, point := constants.WalletCurrencyCoin, constants.WalletCurrencyPoint
|
||||
flows := []repository.WalletFlow{
|
||||
{Currency: coin, Type: constants.WalletTxTypeGameReward, Credit: 500, Transactions: 40},
|
||||
{Currency: coin, Type: constants.WalletTxTypeMigration, Credit: 100, Transactions: 2},
|
||||
{Currency: coin, Type: constants.WalletTxTypeAdjustment, Credit: 30, Debit: 10, Transactions: 2},
|
||||
{Currency: coin, Type: constants.WalletTxTypeGameSpend, Debit: 200, Transactions: 50},
|
||||
{Currency: coin, Type: constants.WalletTxTypeGameSpendRefund, Credit: 8, Transactions: 2},
|
||||
{Currency: coin, Type: constants.WalletTxTypeExchangeOut, Debit: 120, Transactions: 3},
|
||||
{Currency: coin, Type: constants.WalletTxTypeExpire, Debit: 15, Transactions: 1},
|
||||
{Currency: coin, Type: constants.WalletTxTypeTransferOut, Debit: 50, Transactions: 1},
|
||||
{Currency: coin, Type: constants.WalletTxTypeTransferIn, Credit: 50, Transactions: 1},
|
||||
{Currency: point, Type: constants.WalletTxTypeEarn, Credit: 1_000, Transactions: 9},
|
||||
{Currency: point, Type: constants.WalletTxTypeEarnReversal, Debit: 100, Transactions: 1},
|
||||
{Currency: point, Type: constants.WalletTxTypeExchangeIn, Credit: 120, Transactions: 3},
|
||||
{Currency: point, Type: constants.WalletTxTypeRewardRedeem, Debit: 700, Transactions: 7},
|
||||
{Currency: point, Type: constants.WalletTxTypeRewardRedeemRefund, Credit: 100, Transactions: 1},
|
||||
{Currency: point, Type: constants.WalletTxTypeExpire, Debit: 40, Transactions: 2},
|
||||
}
|
||||
e := economy(flows, map[string]int64{coin: 900, point: 2_500})
|
||||
|
||||
assert.Equal(t, models.EnakGameCoinFlows{
|
||||
Generated: 630, GameRewards: 500, SpentOnGames: 192, Exchanged: 120, Spent: 312, Expired: 15, Outstanding: 900,
|
||||
}, e.Coin, "transfers count nowhere")
|
||||
assert.Equal(t, models.EnakGamePointFlows{Earned: 900, Exchanged: 120, Redeemed: 600, Expired: 40, Balance: 2_500}, e.Point)
|
||||
assert.Len(t, e.ByType, len(flows))
|
||||
|
||||
empty := economy(nil, map[string]int64{})
|
||||
assert.Zero(t, empty.Coin)
|
||||
assert.NotNil(t, empty.ByType, "an empty list, not null")
|
||||
}
|
||||
@@ -0,0 +1,974 @@
|
||||
package processor
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"os"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
"gorm.io/driver/postgres"
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/logger"
|
||||
|
||||
"apskel-pos-be/internal/constants"
|
||||
"apskel-pos-be/internal/entities"
|
||||
"apskel-pos-be/internal/models"
|
||||
"apskel-pos-be/internal/repository"
|
||||
)
|
||||
|
||||
// EnakGame admin, start, refund and the session job against Postgres
|
||||
// (docs/rfc-enakgame.md §7.1, §7.3, §11). Needs TEST_DATABASE_URL; see
|
||||
// internal/repository/wallet_repository_test.go.
|
||||
|
||||
type enakGameEnv struct {
|
||||
t *testing.T
|
||||
db *gorm.DB
|
||||
admin *EnakGameAdminProcessor
|
||||
budgets *GameBudgetProcessor
|
||||
sessions *GameSessionProcessor
|
||||
events *GameEventProcessor
|
||||
vouchers *VoucherAdminProcessor
|
||||
redeem *VoucherRedemptionProcessor
|
||||
exchange *WalletExchangeProcessor
|
||||
provider *fakeVoucherProvider
|
||||
wallet *WalletProcessor
|
||||
txm *repository.TxManager
|
||||
orgA uuid.UUID
|
||||
orgB uuid.UUID
|
||||
alice uuid.UUID // customer of A
|
||||
bob uuid.UUID // customer of A
|
||||
carol uuid.UUID // customer of B
|
||||
manager uuid.UUID
|
||||
now time.Time
|
||||
}
|
||||
|
||||
func newEnakGameEnv(t *testing.T) *enakGameEnv {
|
||||
t.Helper()
|
||||
dsn := os.Getenv("TEST_DATABASE_URL")
|
||||
if dsn == "" {
|
||||
t.Skip("TEST_DATABASE_URL not set")
|
||||
}
|
||||
db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{Logger: logger.Default.LogMode(logger.Silent)})
|
||||
require.NoError(t, err)
|
||||
e := &enakGameEnv{
|
||||
t: t, db: db, txm: repository.NewTxManager(db),
|
||||
orgA: uuid.New(), orgB: uuid.New(), alice: uuid.New(), bob: uuid.New(), carol: uuid.New(), manager: uuid.New(),
|
||||
now: time.Now(),
|
||||
}
|
||||
orgs := []uuid.UUID{e.orgA, e.orgB}
|
||||
for _, org := range orgs {
|
||||
require.NoError(t, db.Exec(`INSERT INTO organizations (id, name, plan_type) VALUES (?, 'enakgame test', 'basic')`, org).Error)
|
||||
}
|
||||
require.NoError(t, db.Exec(`INSERT INTO customers (id, organization_id, name) VALUES (?, ?, 'Alice'), (?, ?, 'Bob'), (?, ?, 'Carol')`,
|
||||
e.alice, e.orgA, e.bob, e.orgA, e.carol, e.orgB).Error)
|
||||
t.Cleanup(func() {
|
||||
for _, q := range []string{
|
||||
`DELETE FROM audit_logs WHERE organization_id IN ?`,
|
||||
`DELETE FROM voucher_redemption_costs WHERE redemption_id IN (SELECT id FROM voucher_redemptions WHERE organization_id IN ?)`,
|
||||
`DELETE FROM voucher_redemptions WHERE organization_id IN ?`,
|
||||
`DELETE FROM voucher_codes WHERE voucher_id IN (SELECT id FROM vouchers WHERE organization_id IN ?)`,
|
||||
`DELETE FROM vouchers WHERE organization_id IN ?`,
|
||||
`DELETE FROM customer_security_events WHERE customer_id IN (SELECT id FROM customers WHERE organization_id IN ?)`,
|
||||
`DELETE FROM game_reward_counters WHERE organization_id IN ?`,
|
||||
`DELETE FROM game_session_rewards WHERE session_id IN (SELECT id FROM game_sessions WHERE organization_id IN ?)`,
|
||||
`DELETE FROM game_sessions WHERE organization_id IN ?`,
|
||||
`DELETE FROM wallet_lot_allocations WHERE lot_id IN (SELECT id FROM wallet_lots WHERE organization_id IN ?)`,
|
||||
`DELETE FROM wallet_lots WHERE organization_id IN ?`,
|
||||
`DELETE FROM wallet_transactions WHERE organization_id IN ?`,
|
||||
`DELETE FROM customer_wallets WHERE organization_id IN ?`,
|
||||
`DELETE FROM game_event_games WHERE event_id IN (SELECT id FROM game_events WHERE organization_id IN ?)`,
|
||||
`DELETE FROM game_events WHERE organization_id IN ?`,
|
||||
`DELETE FROM game_reward_configs WHERE organization_id IN ?`,
|
||||
`DELETE FROM game_budgets WHERE organization_id IN ?`,
|
||||
`DELETE FROM games WHERE organization_id IN ?`,
|
||||
`DELETE FROM customers WHERE organization_id IN ?`,
|
||||
`DELETE FROM organizations WHERE id IN ?`,
|
||||
} {
|
||||
db.Exec(q, orgs)
|
||||
}
|
||||
})
|
||||
|
||||
audit := NewAuditLogger(repository.NewAuditLogRepository(db))
|
||||
games := repository.NewEnakGameRepository(db)
|
||||
budgets := repository.NewGameBudgetRepository(db)
|
||||
e.wallet = NewWalletProcessor(repository.NewWalletRepository(db))
|
||||
e.admin = NewEnakGameAdminProcessor(games, audit, e.txm)
|
||||
e.budgets = NewGameBudgetProcessor(budgets, audit, e.txm)
|
||||
e.sessions = NewGameSessionProcessor(repository.NewWalletMoveRepository(db), games, repository.NewGameSessionRepository(db),
|
||||
budgets, repository.NewGameEventRepository(db), repository.NewGameRewardCounterRepository(db), NewLoyaltySettingsProcessor(repository.NewLoyaltySettingsRepository(db), e.txm), repository.NewWalletQueryRepository(db), e.wallet, audit, e.txm)
|
||||
settings := NewLoyaltySettingsProcessor(repository.NewLoyaltySettingsRepository(db), e.txm)
|
||||
pins := NewCustomerPinProcessor(repository.NewCustomerPinRepository(db), nil, nil)
|
||||
vouchers := repository.NewVoucherRepository(db)
|
||||
e.provider = &fakeVoucherProvider{issued: map[uuid.UUID]*VoucherIssue{}}
|
||||
e.events = NewGameEventProcessor(repository.NewGameEventRepository(db), games, budgets, audit, e.txm)
|
||||
e.vouchers = NewVoucherAdminProcessor(vouchers, audit, e.txm)
|
||||
e.redeem = NewVoucherRedemptionProcessor(repository.NewWalletMoveRepository(db), vouchers, repository.NewVoucherRedemptionRepository(db),
|
||||
pins, repository.NewWalletQueryRepository(db), e.wallet, VoucherProviders{"acme": e.provider}, e.txm)
|
||||
e.exchange = NewWalletExchangeProcessor(repository.NewWalletMoveRepository(db), settings, repository.NewWalletQueryRepository(db), pins, e.wallet, e.txm)
|
||||
hash, err := bcrypt.GenerateFromPassword([]byte(testPin), bcrypt.MinCost)
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, db.Exec(`UPDATE customers SET pin_hash = ?, pin_set_at = NOW() WHERE organization_id IN ?`, string(hash), orgs).Error)
|
||||
|
||||
clock := func() time.Time { return e.now }
|
||||
e.budgets.now, e.sessions.now, e.wallet.now, e.redeem.now, e.exchange.now = clock, clock, clock, clock, clock
|
||||
return e
|
||||
}
|
||||
|
||||
// testPin is every test customer's PIN.
|
||||
const testPin = "482913"
|
||||
|
||||
func (e *enakGameEnv) ctx() context.Context { return context.Background() }
|
||||
|
||||
// coins gives a customer EnakCoin in one lot expiring at expiresAt (nil: never).
|
||||
func (e *enakGameEnv) coins(customer uuid.UUID, amount int64, expiresAt *time.Time) {
|
||||
e.t.Helper()
|
||||
require.NoError(e.t, e.txm.WithTransaction(e.ctx(), func(ctx context.Context) error {
|
||||
_, err := e.wallet.Credit(ctx, WalletCreditInput{
|
||||
WalletEntry: WalletEntry{
|
||||
CustomerID: customer, Currency: constants.WalletCurrencyCoin, Type: constants.WalletTxTypeMigration,
|
||||
Amount: amount, ReferenceType: constants.WalletRefTypeLegacyTokens, ReferenceID: uuid.New(), Description: "Saldo awal",
|
||||
},
|
||||
Lots: []WalletLotInput{{Amount: amount, ExpiresAt: expiresAt}},
|
||||
})
|
||||
return err
|
||||
}))
|
||||
}
|
||||
|
||||
func (e *enakGameEnv) coinBalance(customer uuid.UUID) int64 {
|
||||
e.t.Helper()
|
||||
var balance int64
|
||||
require.NoError(e.t, e.db.Raw(`SELECT COALESCE((SELECT coin_balance FROM customer_wallets WHERE customer_id = ?), 0)`, customer).Scan(&balance).Error)
|
||||
return balance
|
||||
}
|
||||
|
||||
func (e *enakGameEnv) count(query string, args ...any) int64 {
|
||||
e.t.Helper()
|
||||
var n int64
|
||||
require.NoError(e.t, e.db.Raw(query, args...).Scan(&n).Error)
|
||||
return n
|
||||
}
|
||||
|
||||
// playableGame makes an ACTIVE game of org with an active FIXED config, and a global
|
||||
// budget for the month if there is none.
|
||||
func (e *enakGameEnv) playableGame(org uuid.UUID, slug string, entryCost int64) *models.EnakGame {
|
||||
e.t.Helper()
|
||||
game, err := e.admin.CreateGame(e.ctx(), org, e.manager, models.EnakGameInput{
|
||||
Name: "Game " + slug, Slug: slug, Status: constants.GameStatusActive, EntryCost: entryCost,
|
||||
})
|
||||
require.NoError(e.t, err)
|
||||
config, err := e.admin.CreateRewardConfig(e.ctx(), org, e.manager, game.ID, models.GameRewardConfigInput{
|
||||
RewardType: constants.GameRewardTypeFixed, Rules: json.RawMessage(`{"amount": 10}`), MaxReward: 10,
|
||||
})
|
||||
require.NoError(e.t, err)
|
||||
_, err = e.admin.ActivateRewardConfig(e.ctx(), org, e.manager, config.ID, models.GameRewardConfigActivateInput{})
|
||||
require.NoError(e.t, err)
|
||||
if e.count(`SELECT COUNT(*) FROM game_budgets WHERE organization_id = ? AND scope = 'GLOBAL'`, org) == 0 {
|
||||
e.globalBudget(org, e.now)
|
||||
}
|
||||
return game
|
||||
}
|
||||
|
||||
func (e *enakGameEnv) globalBudget(org uuid.UUID, day time.Time) *models.GameBudget {
|
||||
e.t.Helper()
|
||||
d := day.In(walletDisplayLocation)
|
||||
start := time.Date(d.Year(), d.Month(), 1, 0, 0, 0, 0, time.UTC)
|
||||
budget, err := e.budgets.CreateBudget(e.ctx(), org, e.manager, models.GameBudgetInput{
|
||||
Scope: constants.GameBudgetScopeGlobal, Name: "Bulanan", Amount: 100_000_000,
|
||||
PeriodStart: start.Format("2006-01-02"), PeriodEnd: start.AddDate(0, 1, -1).Format("2006-01-02"),
|
||||
})
|
||||
require.NoError(e.t, err)
|
||||
return budget
|
||||
}
|
||||
|
||||
func (e *enakGameEnv) auditActions(entityType string, id uuid.UUID) []string {
|
||||
e.t.Helper()
|
||||
var actions []string
|
||||
require.NoError(e.t, e.db.Raw(`SELECT action FROM audit_logs WHERE entity_type = ? AND entity_id = ? ORDER BY created_at, action`, entityType, id).Scan(&actions).Error)
|
||||
return actions
|
||||
}
|
||||
|
||||
// EG-201
|
||||
func TestEnakGameAdmin_Games(t *testing.T) {
|
||||
e := newEnakGameEnv(t)
|
||||
ctx := e.ctx()
|
||||
|
||||
game, err := e.admin.CreateGame(ctx, e.orgA, e.manager, models.EnakGameInput{Name: " Tap Tap ", Slug: "tap-tap", EntryCost: 3})
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "Tap Tap", game.Name)
|
||||
assert.Equal(t, constants.GameStatusDraft, game.Status, "a new game starts as a draft")
|
||||
assert.Equal(t, "MINIGAME", game.Type)
|
||||
assert.Equal(t, 600, game.SessionTTLSeconds)
|
||||
|
||||
for name, in := range map[string]models.EnakGameInput{
|
||||
"no name": {Slug: "a", EntryCost: 1},
|
||||
"bad slug": {Name: "x", Slug: "Tap Tap", EntryCost: 1},
|
||||
"free": {Name: "x", Slug: "free", EntryCost: 0},
|
||||
"archived on start": {Name: "x", Slug: "arch", EntryCost: 1, Status: "ARCHIVED"},
|
||||
"unknown type": {Name: "x", Slug: "t", EntryCost: 1, Type: "PUZZLE"},
|
||||
"negative max": {Name: "x", Slug: "m", EntryCost: 1, ResultRules: entities.GameResultRules{MaxScore: ptr(int64(-1))}},
|
||||
"same outcome": {Name: "x", Slug: "o", EntryCost: 1, ResultRules: entities.GameResultRules{Outcomes: []string{"WIN", "WIN"}}},
|
||||
"slug in use": {Name: "x", Slug: "tap-tap", EntryCost: 1},
|
||||
} {
|
||||
_, err := e.admin.CreateGame(ctx, e.orgA, e.manager, in)
|
||||
assert.ErrorIs(t, err, ErrEnakGameRejected, name)
|
||||
}
|
||||
_, err = e.admin.CreateGame(ctx, e.orgB, e.manager, models.EnakGameInput{Name: "Tap", Slug: "tap-tap", EntryCost: 1})
|
||||
require.NoError(t, err, "another organization may use the slug")
|
||||
|
||||
// Organization B sees nothing of A's game.
|
||||
_, err = e.admin.GetGame(ctx, e.orgB, game.ID)
|
||||
assert.ErrorIs(t, err, repository.ErrEnakGameNotFound)
|
||||
_, err = e.admin.UpdateGame(ctx, e.orgB, e.manager, game.ID, EnakGameInputFrom(game))
|
||||
assert.ErrorIs(t, err, repository.ErrEnakGameNotFound)
|
||||
_, err = e.admin.SetGameStatus(ctx, e.orgB, e.manager, game.ID, models.EnakGameStatusInput{Status: "ACTIVE"})
|
||||
assert.ErrorIs(t, err, repository.ErrEnakGameNotFound)
|
||||
list, err := e.admin.ListGames(ctx, e.orgB, models.EnakGameListQuery{})
|
||||
require.NoError(t, err)
|
||||
require.Len(t, list.Data, 1)
|
||||
assert.NotEqual(t, game.ID, list.Data[0].ID)
|
||||
|
||||
in := EnakGameInputFrom(game)
|
||||
in.EntryCost = 5
|
||||
updated, err := e.admin.UpdateGame(ctx, e.orgA, e.manager, game.ID, in)
|
||||
require.NoError(t, err)
|
||||
assert.EqualValues(t, 5, updated.EntryCost)
|
||||
assert.Equal(t, constants.GameStatusDraft, updated.Status, "an update does not touch the status")
|
||||
|
||||
reason := "launch"
|
||||
_, err = e.admin.SetGameStatus(ctx, e.orgA, e.manager, game.ID, models.EnakGameStatusInput{Status: "active", Reason: &reason})
|
||||
require.NoError(t, err)
|
||||
var audit struct {
|
||||
ActorID string
|
||||
Before string
|
||||
After string
|
||||
Reason string
|
||||
}
|
||||
require.NoError(t, e.db.Raw(`SELECT actor_id::text AS actor_id, before::text AS before, after::text AS after, reason FROM audit_logs
|
||||
WHERE entity_id = ? AND action = 'STATUS_CHANGED'`, game.ID).Scan(&audit).Error)
|
||||
assert.Equal(t, e.manager.String(), audit.ActorID)
|
||||
assert.JSONEq(t, `{"status": "DRAFT"}`, audit.Before)
|
||||
assert.JSONEq(t, `{"status": "ACTIVE"}`, audit.After)
|
||||
assert.Equal(t, "launch", audit.Reason)
|
||||
|
||||
// Archived: hidden from the default list, never changed again.
|
||||
_, err = e.admin.SetGameStatus(ctx, e.orgA, e.manager, game.ID, models.EnakGameStatusInput{Status: "ARCHIVED"})
|
||||
require.NoError(t, err)
|
||||
_, err = e.admin.SetGameStatus(ctx, e.orgA, e.manager, game.ID, models.EnakGameStatusInput{Status: "ACTIVE"})
|
||||
assert.ErrorIs(t, err, ErrEnakGameRejected)
|
||||
_, err = e.admin.UpdateGame(ctx, e.orgA, e.manager, game.ID, in)
|
||||
assert.ErrorIs(t, err, ErrEnakGameRejected)
|
||||
list, err = e.admin.ListGames(ctx, e.orgA, models.EnakGameListQuery{})
|
||||
require.NoError(t, err)
|
||||
assert.Empty(t, list.Data)
|
||||
list, err = e.admin.ListGames(ctx, e.orgA, models.EnakGameListQuery{Status: "archived"})
|
||||
require.NoError(t, err)
|
||||
assert.Len(t, list.Data, 1)
|
||||
|
||||
assert.Equal(t, []string{"CREATED", "UPDATED", "STATUS_CHANGED", "STATUS_CHANGED"}, e.auditActions(constants.AuditEntityGame, game.ID))
|
||||
}
|
||||
|
||||
// EG-202
|
||||
func TestEnakGameAdmin_RewardConfigs(t *testing.T) {
|
||||
e := newEnakGameEnv(t)
|
||||
ctx := e.ctx()
|
||||
game, err := e.admin.CreateGame(ctx, e.orgA, e.manager, models.EnakGameInput{Name: "Runner", Slug: "runner", EntryCost: 1})
|
||||
require.NoError(t, err)
|
||||
|
||||
newVersion := func(amount int) *models.GameRewardConfig {
|
||||
t.Helper()
|
||||
c, err := e.admin.CreateRewardConfig(ctx, e.orgA, e.manager, game.ID, models.GameRewardConfigInput{
|
||||
RewardType: "fixed", Rules: json.RawMessage(`{ "amount" : ` + string(rune('0'+amount)) + ` }`), MaxReward: 10,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
return c
|
||||
}
|
||||
v1, v2 := newVersion(8), newVersion(9)
|
||||
assert.Equal(t, []int{1, 2}, []int{v1.Version, v2.Version})
|
||||
assert.Equal(t, constants.GameRewardConfigStatusDraft, v1.Status)
|
||||
assert.JSONEq(t, `{"amount": 8}`, string(v1.Rules))
|
||||
|
||||
for name, in := range map[string]models.GameRewardConfigInput{
|
||||
"unknown type": {RewardType: "TIERED", Rules: json.RawMessage(`{}`)},
|
||||
"no rules": {RewardType: "FIXED"},
|
||||
"rules invalid": {RewardType: "SCORE_BASED", Rules: json.RawMessage(`{"bands": [{"min": 5, "amount": 1}]}`)},
|
||||
"negative max": {RewardType: "FIXED", Rules: json.RawMessage(`{"amount": 1}`), MaxReward: -1},
|
||||
"unknown rule key": {RewardType: "FIXED", Rules: json.RawMessage(`{"amount": 1, "bonus": 2}`)},
|
||||
} {
|
||||
_, err := e.admin.CreateRewardConfig(ctx, e.orgA, e.manager, game.ID, in)
|
||||
assert.ErrorIs(t, err, ErrEnakGameRejected, name)
|
||||
}
|
||||
_, err = e.admin.CreateRewardConfig(ctx, e.orgB, e.manager, game.ID, models.GameRewardConfigInput{RewardType: "FIXED", Rules: json.RawMessage(`{"amount": 1}`)})
|
||||
assert.ErrorIs(t, err, repository.ErrEnakGameNotFound, "another organization's game")
|
||||
_, err = e.admin.ActivateRewardConfig(ctx, e.orgB, e.manager, v1.ID, models.GameRewardConfigActivateInput{})
|
||||
assert.ErrorIs(t, err, repository.ErrGameRewardConfigNotFound)
|
||||
|
||||
// Two versions activated at once: exactly one ends up active.
|
||||
var wg sync.WaitGroup
|
||||
for _, v := range []*models.GameRewardConfig{v1, v2} {
|
||||
v := v
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
_, err := e.admin.ActivateRewardConfig(ctx, e.orgA, e.manager, v.ID, models.GameRewardConfigActivateInput{})
|
||||
assert.NoError(t, err)
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
configs, err := e.admin.ListRewardConfigs(ctx, e.orgA, game.ID)
|
||||
require.NoError(t, err)
|
||||
active := 0
|
||||
for _, c := range configs {
|
||||
if c.Status == constants.GameRewardConfigStatusActive {
|
||||
active++
|
||||
}
|
||||
}
|
||||
assert.Equal(t, 1, active)
|
||||
|
||||
// Activating the active one again changes nothing; a retired one stays retired.
|
||||
var retired *models.GameRewardConfig
|
||||
for i := range configs {
|
||||
if configs[i].Status == constants.GameRewardConfigStatusRetired {
|
||||
retired = &configs[i]
|
||||
}
|
||||
}
|
||||
require.NotNil(t, retired, "the version activated first was retired by the second")
|
||||
_, err = e.admin.ActivateRewardConfig(ctx, e.orgA, e.manager, retired.ID, models.GameRewardConfigActivateInput{})
|
||||
assert.ErrorIs(t, err, ErrEnakGameRejected)
|
||||
|
||||
// Nothing but status ever changed: the rules are as created.
|
||||
for _, c := range configs {
|
||||
want := map[uuid.UUID]string{v1.ID: `{"amount": 8}`, v2.ID: `{"amount": 9}`}[c.ID]
|
||||
assert.JSONEq(t, want, string(c.Rules))
|
||||
}
|
||||
assert.Equal(t, int64(2), e.count(`SELECT COUNT(*) FROM audit_logs WHERE entity_type = 'GAME_REWARD_CONFIG' AND action = 'CREATED' AND organization_id = ?`, e.orgA))
|
||||
assert.Equal(t, int64(2), e.count(`SELECT COUNT(*) FROM audit_logs WHERE entity_type = 'GAME_REWARD_CONFIG' AND action = 'ACTIVATED' AND organization_id = ?`, e.orgA))
|
||||
assert.Equal(t, int64(1), e.count(`SELECT COUNT(*) FROM audit_logs WHERE entity_type = 'GAME_REWARD_CONFIG' AND action = 'RETIRED' AND organization_id = ?`, e.orgA))
|
||||
}
|
||||
|
||||
// EG-203
|
||||
func TestEnakGameAdmin_Budgets(t *testing.T) {
|
||||
e := newEnakGameEnv(t)
|
||||
ctx := e.ctx()
|
||||
e.now = time.Date(2026, 10, 15, 12, 0, 0, 0, walletDisplayLocation)
|
||||
october, err := e.budgets.CreateBudget(ctx, e.orgA, e.manager, models.GameBudgetInput{
|
||||
Scope: "global", Name: "Oktober", PeriodStart: "2026-10-01", PeriodEnd: "2026-10-31", Amount: 100_000_000,
|
||||
Thresholds: models.GameBudgetThresholds{Warning: ptr(int64(70)), Critical: ptr(int64(90))},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "2026-10-01", october.PeriodStart)
|
||||
assert.EqualValues(t, 90, *october.Thresholds.Critical)
|
||||
|
||||
for name, in := range map[string]models.GameBudgetInput{
|
||||
"overlaps": {Scope: "GLOBAL", Name: "x", PeriodStart: "2026-10-20", PeriodEnd: "2026-11-19", Amount: 1},
|
||||
"same start": {Scope: "GLOBAL", Name: "x", PeriodStart: "2026-10-01", PeriodEnd: "2026-10-01", Amount: 1},
|
||||
"end before": {Scope: "GLOBAL", Name: "x", PeriodStart: "2026-12-02", PeriodEnd: "2026-12-01", Amount: 1},
|
||||
"no amount": {Scope: "GLOBAL", Name: "x", PeriodStart: "2026-12-01", PeriodEnd: "2026-12-31"},
|
||||
"bad date": {Scope: "GLOBAL", Name: "x", PeriodStart: "1/12/2026", PeriodEnd: "2026-12-31", Amount: 1},
|
||||
"unknown scope": {Scope: "OUTLET", Name: "x", PeriodStart: "2026-12-01", PeriodEnd: "2026-12-31", Amount: 1},
|
||||
"warning > crit": {Scope: "EVENT", Name: "x", PeriodStart: "2026-12-01", PeriodEnd: "2026-12-31", Amount: 1, Thresholds: models.GameBudgetThresholds{Warning: ptr(int64(95)), Critical: ptr(int64(90))}},
|
||||
"threshold > 100": {Scope: "EVENT", Name: "x", PeriodStart: "2026-12-01", PeriodEnd: "2026-12-31", Amount: 1, Thresholds: models.GameBudgetThresholds{Critical: ptr(int64(101))}},
|
||||
} {
|
||||
_, err := e.budgets.CreateBudget(ctx, e.orgA, e.manager, in)
|
||||
assert.ErrorIs(t, err, ErrEnakGameRejected, name)
|
||||
}
|
||||
_, err = e.budgets.CreateBudget(ctx, e.orgA, e.manager, models.GameBudgetInput{Scope: "EVENT", Name: "Ramadan", PeriodStart: "2026-10-10", PeriodEnd: "2026-10-20", Amount: 5_000_000})
|
||||
require.NoError(t, err, "an event budget may share days with the global one")
|
||||
|
||||
// A change records the amount before and after.
|
||||
in := GameBudgetInputFrom(october)
|
||||
in.Amount = 120_000_000
|
||||
updated, err := e.budgets.UpdateBudget(ctx, e.orgA, e.manager, october.ID, in)
|
||||
require.NoError(t, err)
|
||||
assert.EqualValues(t, 120_000_000, updated.Amount)
|
||||
var change struct{ Before, After string }
|
||||
require.NoError(t, e.db.Raw(`SELECT before->>'amount' AS before, after->>'amount' AS after FROM audit_logs WHERE entity_id = ? AND action = 'UPDATED'`, october.ID).Scan(&change).Error)
|
||||
assert.Equal(t, struct{ Before, After string }{"100000000", "120000000"}, change)
|
||||
in.Scope = "EVENT"
|
||||
_, err = e.budgets.UpdateBudget(ctx, e.orgA, e.manager, october.ID, in)
|
||||
assert.ErrorIs(t, err, ErrEnakGameRejected, "the scope stays")
|
||||
_, err = e.budgets.UpdateBudget(ctx, e.orgB, e.manager, october.ID, GameBudgetInputFrom(october))
|
||||
assert.ErrorIs(t, err, repository.ErrGameBudgetNotFound)
|
||||
|
||||
// The period job opens November once, however often it runs. It works across
|
||||
// organizations, so this organization's budgets are what is checked.
|
||||
for run := 0; run < 3; run++ {
|
||||
_, err := e.budgets.CreateNextPeriods(ctx)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, int64(2), e.count(`SELECT COUNT(*) FROM game_budgets WHERE organization_id = ? AND scope = 'GLOBAL'`, e.orgA), "run %d", run)
|
||||
}
|
||||
list, err := e.budgets.ListBudgets(ctx, e.orgA, models.GameBudgetListQuery{Scope: "GLOBAL"})
|
||||
require.NoError(t, err)
|
||||
require.Len(t, list.Data, 2)
|
||||
november := list.Data[0]
|
||||
assert.Equal(t, "2026-11-01", november.PeriodStart)
|
||||
assert.Equal(t, "2026-11-30", november.PeriodEnd)
|
||||
assert.EqualValues(t, 120_000_000, november.Amount)
|
||||
assert.EqualValues(t, 70, *november.Thresholds.Warning)
|
||||
assert.Equal(t, int64(1), e.count(`SELECT COUNT(*) FROM audit_logs WHERE entity_id = ? AND actor_type = 'SYSTEM'`, november.ID))
|
||||
|
||||
// A budget a reward points at stays; an unused one goes.
|
||||
game := e.playableGame(e.orgA, "budget-in-use", 1)
|
||||
e.coins(e.alice, 5, nil)
|
||||
started, err := e.sessions.Start(ctx, e.alice, game.ID, "k1")
|
||||
require.NoError(t, err)
|
||||
reward := uuid.New()
|
||||
require.NoError(t, e.db.Exec(`INSERT INTO wallet_transactions (id, organization_id, customer_id, currency, type, amount, balance_after, reference_type, reference_id, description)
|
||||
VALUES (?, ?, ?, 'COIN', 'GAME_REWARD', 1, 0, 'GAME_SESSION', ?, 'x')`, reward, e.orgA, e.alice, started.SessionID).Error)
|
||||
require.NoError(t, e.db.Exec(`INSERT INTO game_session_rewards (session_id, budget_id, amount, wallet_transaction_id) VALUES (?, ?, 1, ?)`,
|
||||
started.SessionID, october.ID, reward).Error)
|
||||
assert.ErrorIs(t, e.budgets.DeleteBudget(ctx, e.orgA, e.manager, october.ID), ErrEnakGameRejected)
|
||||
require.NoError(t, e.budgets.DeleteBudget(ctx, e.orgA, e.manager, november.ID))
|
||||
assert.Equal(t, []string{"CREATED", "DELETED"}, e.auditActions(constants.AuditEntityGameBudget, november.ID))
|
||||
}
|
||||
|
||||
// EG-204
|
||||
func TestGameSession_Start(t *testing.T) {
|
||||
e := newEnakGameEnv(t)
|
||||
ctx := e.ctx()
|
||||
game := e.playableGame(e.orgA, "runner", 3)
|
||||
e.coins(e.alice, 10, nil)
|
||||
|
||||
first, err := e.sessions.Start(ctx, e.alice, game.ID, "tap-1")
|
||||
require.NoError(t, err)
|
||||
assert.False(t, first.Replayed)
|
||||
assert.EqualValues(t, 3, first.EntryCost)
|
||||
assert.EqualValues(t, 7, first.CoinBalance)
|
||||
assert.WithinDuration(t, e.now.Add(600*time.Second), first.ExpiresAt, time.Second)
|
||||
|
||||
// The same key again: the same session, nothing more taken.
|
||||
again, err := e.sessions.Start(ctx, e.alice, game.ID, "tap-1")
|
||||
require.NoError(t, err)
|
||||
assert.True(t, again.Replayed)
|
||||
assert.Equal(t, first.SessionID, again.SessionID)
|
||||
assert.EqualValues(t, 7, e.coinBalance(e.alice))
|
||||
assert.Equal(t, int64(1), e.count(`SELECT COUNT(*) FROM wallet_transactions WHERE customer_id = ? AND type = 'GAME_SPEND'`, e.alice))
|
||||
assert.Equal(t, int64(1), e.count(`SELECT COUNT(*) FROM game_sessions WHERE customer_id = ?`, e.alice))
|
||||
var spend struct {
|
||||
ReferenceType string
|
||||
ReferenceID string
|
||||
Amount int64
|
||||
}
|
||||
require.NoError(t, e.db.Raw(`SELECT reference_type, reference_id::text AS reference_id, amount FROM wallet_transactions WHERE customer_id = ? AND type = 'GAME_SPEND'`, e.alice).Scan(&spend).Error)
|
||||
assert.Equal(t, constants.WalletRefTypeGameSession, spend.ReferenceType)
|
||||
assert.Equal(t, first.SessionID.String(), spend.ReferenceID)
|
||||
assert.EqualValues(t, -3, spend.Amount)
|
||||
|
||||
// The session keeps what it started with.
|
||||
configs, err := e.admin.ListRewardConfigs(ctx, e.orgA, game.ID)
|
||||
require.NoError(t, err)
|
||||
in := EnakGameInputFrom(game)
|
||||
in.EntryCost = 9
|
||||
_, err = e.admin.UpdateGame(ctx, e.orgA, e.manager, game.ID, in)
|
||||
require.NoError(t, err)
|
||||
v2, err := e.admin.CreateRewardConfig(ctx, e.orgA, e.manager, game.ID, models.GameRewardConfigInput{RewardType: "FIXED", Rules: json.RawMessage(`{"amount": 1}`)})
|
||||
require.NoError(t, err)
|
||||
_, err = e.admin.ActivateRewardConfig(ctx, e.orgA, e.manager, v2.ID, models.GameRewardConfigActivateInput{})
|
||||
require.NoError(t, err)
|
||||
var snapshot struct {
|
||||
EntryCost int64
|
||||
RewardConfigID string
|
||||
}
|
||||
require.NoError(t, e.db.Raw(`SELECT entry_cost, reward_config_id::text AS reward_config_id FROM game_sessions WHERE id = ?`, first.SessionID).Scan(&snapshot).Error)
|
||||
assert.EqualValues(t, 3, snapshot.EntryCost)
|
||||
assert.Equal(t, configs[0].ID.String(), snapshot.RewardConfigID)
|
||||
_, err = e.sessions.Start(ctx, e.alice, uuid.New(), "tap-1")
|
||||
assert.ErrorIs(t, err, ErrGameSessionRejected, "the key started another game")
|
||||
|
||||
// Refusals leave neither a ledger row nor a session.
|
||||
inactive := e.playableGame(e.orgA, "inactive", 1)
|
||||
_, err = e.admin.SetGameStatus(ctx, e.orgA, e.manager, inactive.ID, models.EnakGameStatusInput{Status: "INACTIVE"})
|
||||
require.NoError(t, err)
|
||||
unconfigured, err := e.admin.CreateGame(ctx, e.orgA, e.manager, models.EnakGameInput{Name: "x", Slug: "no-config", EntryCost: 1, Status: "ACTIVE"})
|
||||
require.NoError(t, err)
|
||||
theirs := e.playableGame(e.orgB, "theirs", 1)
|
||||
e.coins(e.carol, 10, nil)
|
||||
noBudget, err := e.admin.CreateGame(ctx, e.orgB, e.manager, models.EnakGameInput{Name: "x", Slug: "no-budget", EntryCost: 1, Status: "ACTIVE"})
|
||||
require.NoError(t, err)
|
||||
|
||||
for name, tc := range map[string]struct {
|
||||
customer uuid.UUID
|
||||
game uuid.UUID
|
||||
key string
|
||||
want error
|
||||
}{
|
||||
"not enough EnakCoin": {e.bob, game.ID, "b1", ErrGameSessionRejected},
|
||||
"another org's game": {e.alice, theirs.ID, "a2", repository.ErrEnakGameNotFound},
|
||||
"inactive game": {e.alice, inactive.ID, "a3", ErrGameSessionRejected},
|
||||
"no active config": {e.alice, unconfigured.ID, "a4", ErrGameSessionRejected},
|
||||
"no key": {e.alice, game.ID, " ", ErrGameSessionRejected},
|
||||
"key too long": {e.alice, game.ID, string(make([]byte, 51)), ErrGameSessionRejected},
|
||||
"unknown customer": {uuid.New(), game.ID, "u1", repository.ErrWalletNotFound},
|
||||
"unknown game": {e.alice, uuid.New(), "a5", repository.ErrEnakGameNotFound},
|
||||
"no budget for period": {e.carol, noBudget.ID, "c1", nil},
|
||||
} {
|
||||
if name == "no budget for period" {
|
||||
// B has a budget from playableGame; move it out of this period.
|
||||
require.NoError(t, e.db.Exec(`UPDATE game_budgets SET period_start = '2000-01-01', period_end = '2000-01-31' WHERE organization_id = ?`, e.orgB).Error)
|
||||
cfg, err := e.admin.CreateRewardConfig(ctx, e.orgB, e.manager, noBudget.ID, models.GameRewardConfigInput{RewardType: "FIXED", Rules: json.RawMessage(`{"amount": 1}`)})
|
||||
require.NoError(t, err)
|
||||
_, err = e.admin.ActivateRewardConfig(ctx, e.orgB, e.manager, cfg.ID, models.GameRewardConfigActivateInput{})
|
||||
require.NoError(t, err)
|
||||
tc.want = ErrGameSessionRejected
|
||||
}
|
||||
before := e.count(`SELECT COUNT(*) FROM wallet_transactions WHERE type = 'GAME_SPEND' AND organization_id IN (?, ?)`, e.orgA, e.orgB)
|
||||
_, err := e.sessions.Start(ctx, tc.customer, tc.game, tc.key)
|
||||
assert.ErrorIs(t, err, tc.want, name)
|
||||
assert.Equal(t, before, e.count(`SELECT COUNT(*) FROM wallet_transactions WHERE type = 'GAME_SPEND' AND organization_id IN (?, ?)`, e.orgA, e.orgB), name)
|
||||
}
|
||||
assert.Equal(t, int64(1), e.count(`SELECT COUNT(*) FROM game_sessions WHERE organization_id IN (?, ?)`, e.orgA, e.orgB))
|
||||
}
|
||||
|
||||
// EG-205
|
||||
func TestGameSession_RefundAndJob(t *testing.T) {
|
||||
e := newEnakGameEnv(t)
|
||||
ctx := e.ctx()
|
||||
game := e.playableGame(e.orgA, "runner", 4)
|
||||
other := e.playableGame(e.orgA, "other", 4)
|
||||
soon := e.now.Add(48 * time.Hour)
|
||||
e.coins(e.alice, 100, &soon)
|
||||
e.coins(e.bob, 100, nil)
|
||||
|
||||
start := func(customer, gameID uuid.UUID, key string) uuid.UUID {
|
||||
t.Helper()
|
||||
s, err := e.sessions.Start(ctx, customer, gameID, key)
|
||||
require.NoError(t, err)
|
||||
return s.SessionID
|
||||
}
|
||||
deactivated := start(e.alice, game.ID, "a1")
|
||||
failed := start(e.alice, other.ID, "a2")
|
||||
abandoned := start(e.bob, other.ID, "b1")
|
||||
stillOpen := start(e.bob, other.ID, "b2")
|
||||
require.NoError(t, e.db.Exec(`UPDATE game_sessions SET expires_at = ? WHERE id IN ?`, e.now.Add(-time.Minute), []uuid.UUID{failed, abandoned}).Error)
|
||||
require.NoError(t, e.db.Exec(`UPDATE game_sessions SET completion_failed_at = ? WHERE id = ?`, e.now.Add(-2*time.Minute), failed).Error)
|
||||
_, err := e.admin.SetGameStatus(ctx, e.orgA, e.manager, game.ID, models.EnakGameStatusInput{Status: "INACTIVE"})
|
||||
require.NoError(t, err)
|
||||
assert.EqualValues(t, 92, e.coinBalance(e.alice))
|
||||
assert.EqualValues(t, 92, e.coinBalance(e.bob))
|
||||
|
||||
// Run the job twice: the second run finds nothing more to do here. The job works
|
||||
// across organizations, and other tests may share the database, so what is
|
||||
// checked is this organization's sessions, not the job's totals.
|
||||
refunded, expired, err := e.sessions.ProcessDueSessions(ctx)
|
||||
require.NoError(t, err)
|
||||
assert.GreaterOrEqual(t, refunded, 2)
|
||||
assert.GreaterOrEqual(t, expired, 1)
|
||||
_, _, err = e.sessions.ProcessDueSessions(ctx)
|
||||
require.NoError(t, err)
|
||||
|
||||
status := func(id uuid.UUID) (string, *string) {
|
||||
var row struct {
|
||||
Status string
|
||||
RefundReason *string
|
||||
}
|
||||
require.NoError(t, e.db.Raw(`SELECT status, refund_reason FROM game_sessions WHERE id = ?`, id).Scan(&row).Error)
|
||||
return row.Status, row.RefundReason
|
||||
}
|
||||
s, reason := status(deactivated)
|
||||
assert.Equal(t, constants.GameSessionStatusRefunded, s, "refunded without waiting for its expiry")
|
||||
assert.Equal(t, constants.GameSessionRefundGameDeactivated, *reason)
|
||||
s, reason = status(failed)
|
||||
assert.Equal(t, constants.GameSessionStatusRefunded, s)
|
||||
assert.Equal(t, constants.GameSessionRefundSystemError, *reason)
|
||||
s, reason = status(abandoned)
|
||||
assert.Equal(t, constants.GameSessionStatusExpired, s, "left behind: no refund")
|
||||
assert.Nil(t, reason)
|
||||
s, _ = status(stillOpen)
|
||||
assert.Equal(t, constants.GameSessionStatusStarted, s)
|
||||
assert.EqualValues(t, 100, e.coinBalance(e.alice), "both entry costs came back")
|
||||
assert.EqualValues(t, 92, e.coinBalance(e.bob), "abandoned and open sessions keep their cost")
|
||||
assert.Equal(t, int64(2), e.count(`SELECT COUNT(*) FROM wallet_transactions WHERE customer_id = ? AND type = 'GAME_SPEND_REFUND'`, e.alice))
|
||||
|
||||
// The refund lot points at the lot the entry cost came from and lasts at least
|
||||
// seven days, although that lot expires in two.
|
||||
var lot struct {
|
||||
OriginLotID string
|
||||
ExpiresAt time.Time
|
||||
Reverses string
|
||||
}
|
||||
require.NoError(t, e.db.Raw(`
|
||||
SELECT l.origin_lot_id::text AS origin_lot_id, l.expires_at, t.reverses_transaction_id::text AS reverses
|
||||
FROM game_sessions s
|
||||
JOIN wallet_transactions t ON t.id = s.refund_transaction_id
|
||||
JOIN wallet_lots l ON l.source_transaction_id = t.id
|
||||
WHERE s.id = ?`, deactivated).Scan(&lot).Error)
|
||||
var spendLot, spendTx string
|
||||
require.NoError(t, e.db.Raw(`SELECT a.lot_id::text FROM wallet_lot_allocations a JOIN game_sessions s ON s.spend_transaction_id = a.transaction_id WHERE s.id = ?`, deactivated).Scan(&spendLot).Error)
|
||||
require.NoError(t, e.db.Raw(`SELECT spend_transaction_id::text FROM game_sessions WHERE id = ?`, deactivated).Scan(&spendTx).Error)
|
||||
assert.Equal(t, spendLot, lot.OriginLotID)
|
||||
assert.Equal(t, spendTx, lot.Reverses)
|
||||
assert.True(t, !lot.ExpiresAt.Before(e.now.Add(7*24*time.Hour-time.Minute)), "expires %s", lot.ExpiresAt)
|
||||
assert.Equal(t, int64(2), e.count(`SELECT COUNT(*) FROM audit_logs WHERE entity_type = 'GAME_SESSION' AND action = 'REFUNDED' AND actor_type = 'SYSTEM' AND source = 'session_job' AND organization_id = ?`, e.orgA))
|
||||
|
||||
refundedAgain, err := e.sessions.RefundSession(ctx, e.orgA, deactivated, constants.GameSessionRefundSystemError, constants.AuditSourceSessionJob)
|
||||
require.NoError(t, err)
|
||||
assert.False(t, refundedAgain, "a session is refunded once")
|
||||
|
||||
// Completing and refunding the same session at once: exactly one wins.
|
||||
sessionsRepo := repository.NewGameSessionRepository(e.db)
|
||||
for round := 0; round < 5; round++ {
|
||||
id := start(e.bob, other.ID, "race-"+string(rune('a'+round)))
|
||||
var wg sync.WaitGroup
|
||||
var completed, refundedNow bool
|
||||
begin := make(chan struct{})
|
||||
wg.Add(2)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
<-begin
|
||||
assert.NoError(t, e.txm.WithTransaction(ctx, func(ctx context.Context) error {
|
||||
if err := e.wallet.LockWallet(ctx, e.bob); err != nil {
|
||||
return err
|
||||
}
|
||||
var err error
|
||||
completed, err = sessionsRepo.CompleteSession(ctx, id, repository.GameSessionCompletion{EndedAt: e.now})
|
||||
return err
|
||||
}))
|
||||
}()
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
<-begin
|
||||
var err error
|
||||
refundedNow, err = e.sessions.RefundSession(ctx, e.orgA, id, constants.GameSessionRefundSystemError, constants.AuditSourceSessionJob)
|
||||
assert.NoError(t, err)
|
||||
}()
|
||||
close(begin)
|
||||
wg.Wait()
|
||||
assert.True(t, completed != refundedNow, "round %d: completed %v, refunded %v", round, completed, refundedNow)
|
||||
refunds := e.count(`SELECT COUNT(*) FROM wallet_transactions WHERE type = 'GAME_SPEND_REFUND' AND reference_id = ?`, id)
|
||||
assert.Equal(t, map[bool]int64{true: 1, false: 0}[refundedNow], refunds, "round %d", round)
|
||||
}
|
||||
}
|
||||
|
||||
// EG-206
|
||||
func TestGameSession_CustomerReads(t *testing.T) {
|
||||
e := newEnakGameEnv(t)
|
||||
ctx := e.ctx()
|
||||
game := e.playableGame(e.orgA, "runner", 2)
|
||||
_, err := e.admin.CreateGame(ctx, e.orgA, e.manager, models.EnakGameInput{Name: "Draft", Slug: "draft", EntryCost: 1})
|
||||
require.NoError(t, err)
|
||||
e.playableGame(e.orgB, "theirs", 1)
|
||||
e.coins(e.alice, 10, nil)
|
||||
|
||||
games, err := e.sessions.ListGames(ctx, e.alice)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, games, 1, "only the ACTIVE games of the customer's organization")
|
||||
assert.Equal(t, game.ID, games[0].ID)
|
||||
assert.Equal(t, "runner", games[0].Slug)
|
||||
assert.EqualValues(t, 2, games[0].EntryCost)
|
||||
|
||||
started, err := e.sessions.Start(ctx, e.alice, game.ID, "k")
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, e.db.Exec(`UPDATE game_sessions SET reward_breakdown = '{"roll": 7}', flagged = TRUE WHERE id = ?`, started.SessionID).Error)
|
||||
session, err := e.sessions.GetSession(ctx, e.alice, started.SessionID)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, constants.GameSessionStatusStarted, session.Status)
|
||||
raw, err := json.Marshal(session)
|
||||
require.NoError(t, err)
|
||||
for _, internal := range []string{"reward_breakdown", "roll", "flagged", "result"} {
|
||||
assert.NotContains(t, string(raw), internal)
|
||||
}
|
||||
_, err = e.sessions.GetSession(ctx, e.bob, started.SessionID)
|
||||
assert.ErrorIs(t, err, repository.ErrGameSessionNotFound, "another customer's session")
|
||||
|
||||
page, err := e.sessions.ListSessions(ctx, e.alice, 1, 10)
|
||||
require.NoError(t, err)
|
||||
assert.EqualValues(t, 1, page.Pagination.Total)
|
||||
page, err = e.sessions.ListSessions(ctx, e.bob, 1, 10)
|
||||
require.NoError(t, err)
|
||||
assert.Empty(t, page.Data)
|
||||
}
|
||||
|
||||
// gameWith makes an ACTIVE game of org A with the given result rules and an active
|
||||
// config of the given type, rules and cap.
|
||||
func (e *enakGameEnv) gameWith(slug string, resultRules entities.GameResultRules, rewardType, rules string, maxReward int64) *models.EnakGame {
|
||||
e.t.Helper()
|
||||
game, err := e.admin.CreateGame(e.ctx(), e.orgA, e.manager, models.EnakGameInput{
|
||||
Name: "Game " + slug, Slug: slug, Status: constants.GameStatusActive, EntryCost: 2, ResultRules: resultRules,
|
||||
})
|
||||
require.NoError(e.t, err)
|
||||
config, err := e.admin.CreateRewardConfig(e.ctx(), e.orgA, e.manager, game.ID, models.GameRewardConfigInput{
|
||||
RewardType: rewardType, Rules: json.RawMessage(rules), MaxReward: maxReward,
|
||||
})
|
||||
require.NoError(e.t, err)
|
||||
_, err = e.admin.ActivateRewardConfig(e.ctx(), e.orgA, e.manager, config.ID, models.GameRewardConfigActivateInput{})
|
||||
require.NoError(e.t, err)
|
||||
if e.count(`SELECT COUNT(*) FROM game_budgets WHERE organization_id = ? AND scope = 'GLOBAL'`, e.orgA) == 0 {
|
||||
e.globalBudget(e.orgA, e.now)
|
||||
}
|
||||
return game
|
||||
}
|
||||
|
||||
func (e *enakGameEnv) session(id uuid.UUID) entities.GameSession {
|
||||
e.t.Helper()
|
||||
var s entities.GameSession
|
||||
require.NoError(e.t, e.db.Where("id = ?", id).First(&s).Error)
|
||||
return s
|
||||
}
|
||||
|
||||
// failingRewards fails right after the reward credit, to show the whole completion
|
||||
// rolls back.
|
||||
type failingRewards struct {
|
||||
repository.GameSessionRepository
|
||||
}
|
||||
|
||||
func (failingRewards) CreateSessionRewards(context.Context, []entities.GameSessionReward) error {
|
||||
return assert.AnError
|
||||
}
|
||||
|
||||
// EG-303
|
||||
func TestGameSession_Complete(t *testing.T) {
|
||||
e := newEnakGameEnv(t)
|
||||
ctx := e.ctx()
|
||||
score := func(v int64) *int64 { return &v }
|
||||
maxScore, minDuration := int64(1000), int64(5)
|
||||
scored := e.gameWith("scored", entities.GameResultRules{MaxScore: &maxScore, MinDurationSeconds: &minDuration},
|
||||
constants.GameRewardTypeScoreBased, `{"bands": [{"min": 0, "max": 100, "amount": 1}, {"min": 101, "amount": 20}]}`, 15)
|
||||
e.coins(e.alice, 100, nil)
|
||||
e.coins(e.bob, 100, nil)
|
||||
start := func(customer, gameID uuid.UUID, key string) uuid.UUID {
|
||||
t.Helper()
|
||||
s, err := e.sessions.Start(ctx, customer, gameID, key)
|
||||
require.NoError(t, err)
|
||||
return s.SessionID
|
||||
}
|
||||
later := func(d time.Duration) { e.now = e.now.Add(d) }
|
||||
|
||||
t.Run("pays the base reward once, capped by max_reward", func(t *testing.T) {
|
||||
id := start(e.alice, scored.ID, "a1")
|
||||
later(30 * time.Second)
|
||||
first, err := e.sessions.Complete(ctx, e.alice, id, models.GameSessionCompleteInput{Score: score(500)})
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, constants.GameSessionStatusCompleted, first.Status)
|
||||
assert.EqualValues(t, 15, first.RewardTotal, "20 capped at 15")
|
||||
assert.EqualValues(t, 15, first.Reward.Base)
|
||||
assert.EqualValues(t, 100-2+15, first.CoinBalance)
|
||||
|
||||
second, err := e.sessions.Complete(ctx, e.alice, id, models.GameSessionCompleteInput{Score: score(999)})
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, first, second, "completing again answers the same")
|
||||
assert.Equal(t, int64(1), e.count(`SELECT COUNT(*) FROM wallet_transactions WHERE type = 'GAME_REWARD' AND reference_id = ?`, id))
|
||||
|
||||
var reward struct {
|
||||
Amount int64
|
||||
IdempotencyKey string
|
||||
BudgetID string
|
||||
}
|
||||
require.NoError(t, e.db.Raw(`SELECT t.amount, t.idempotency_key, r.budget_id::text AS budget_id
|
||||
FROM game_session_rewards r JOIN wallet_transactions t ON t.id = r.wallet_transaction_id WHERE r.session_id = ?`, id).Scan(&reward).Error)
|
||||
var global string
|
||||
require.NoError(t, e.db.Raw(`SELECT id::text FROM game_budgets WHERE organization_id = ? AND scope = 'GLOBAL'`, e.orgA).Scan(&global).Error)
|
||||
assert.EqualValues(t, 15, reward.Amount)
|
||||
assert.Equal(t, "game-reward:"+id.String()+":"+global, reward.IdempotencyKey)
|
||||
assert.Equal(t, global, reward.BudgetID)
|
||||
|
||||
s := e.session(id)
|
||||
assert.False(t, s.Flagged)
|
||||
var breakdown map[string]any
|
||||
require.NoError(t, json.Unmarshal(s.RewardBreakdown, &breakdown))
|
||||
assert.EqualValues(t, 20, breakdown["base"])
|
||||
assert.Equal(t, true, breakdown["capped"])
|
||||
assert.EqualValues(t, 1, breakdown["config_version"])
|
||||
assert.JSONEq(t, `{"score": 500}`, string(s.Result))
|
||||
})
|
||||
|
||||
t.Run("an unbelievable result earns nothing and is flagged", func(t *testing.T) {
|
||||
for name, tc := range map[string]struct {
|
||||
after time.Duration
|
||||
in models.GameSessionCompleteInput
|
||||
}{
|
||||
"too fast": {time.Second, models.GameSessionCompleteInput{Score: score(10)}},
|
||||
"score above max": {time.Minute, models.GameSessionCompleteInput{Score: score(5000)}},
|
||||
"no score": {time.Minute, models.GameSessionCompleteInput{}},
|
||||
} {
|
||||
before := e.coinBalance(e.bob)
|
||||
id := start(e.bob, scored.ID, "flag-"+name)
|
||||
later(tc.after)
|
||||
out, err := e.sessions.Complete(ctx, e.bob, id, tc.in)
|
||||
require.NoError(t, err, name)
|
||||
assert.Equal(t, constants.GameSessionStatusCompleted, out.Status, name)
|
||||
assert.Zero(t, out.RewardTotal, name)
|
||||
s := e.session(id)
|
||||
assert.True(t, s.Flagged, name)
|
||||
assert.Nil(t, s.RefundTransactionID, name)
|
||||
assert.Contains(t, string(s.RewardBreakdown), "rejections", name)
|
||||
assert.EqualValues(t, before-2, e.coinBalance(e.bob), "%s: the entry cost stays spent", name)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("someone else's session, an expired one", func(t *testing.T) {
|
||||
id := start(e.alice, scored.ID, "a2")
|
||||
_, err := e.sessions.Complete(ctx, e.bob, id, models.GameSessionCompleteInput{Score: score(1)})
|
||||
assert.ErrorIs(t, err, repository.ErrGameSessionNotFound)
|
||||
later(11 * time.Minute)
|
||||
_, err = e.sessions.Complete(ctx, e.alice, id, models.GameSessionCompleteInput{Score: score(1)})
|
||||
assert.ErrorIs(t, err, ErrGameSessionRejected)
|
||||
assert.Equal(t, constants.GameSessionStatusStarted, e.session(id).Status, "left for the session job")
|
||||
assert.Nil(t, e.session(id).CompletionFailedAt, "a refusal is not a system error")
|
||||
})
|
||||
|
||||
t.Run("a game turned off during the play refunds the entry cost", func(t *testing.T) {
|
||||
off := e.gameWith("turned-off", entities.GameResultRules{}, constants.GameRewardTypeFixed, `{"amount": 5}`, 0)
|
||||
before := e.coinBalance(e.alice)
|
||||
id := start(e.alice, off.ID, "a3")
|
||||
_, err := e.admin.SetGameStatus(ctx, e.orgA, e.manager, off.ID, models.EnakGameStatusInput{Status: "INACTIVE"})
|
||||
require.NoError(t, err)
|
||||
out, err := e.sessions.Complete(ctx, e.alice, id, models.GameSessionCompleteInput{})
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, constants.GameSessionStatusRefunded, out.Status)
|
||||
assert.Equal(t, constants.GameSessionRefundGameDeactivated, *out.RefundReason)
|
||||
assert.EqualValues(t, before, out.CoinBalance)
|
||||
assert.Equal(t, int64(1), e.count(`SELECT COUNT(*) FROM audit_logs WHERE entity_id = ? AND source = 'customer_api'`, id))
|
||||
again, err := e.sessions.Complete(ctx, e.alice, id, models.GameSessionCompleteInput{})
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, out, again)
|
||||
})
|
||||
|
||||
t.Run("a failure after the credit rolls everything back and marks the session", func(t *testing.T) {
|
||||
broken := *e.sessions
|
||||
broken.sessions = failingRewards{repository.NewGameSessionRepository(e.db)}
|
||||
before := e.coinBalance(e.alice)
|
||||
id := start(e.alice, scored.ID, "a4")
|
||||
later(time.Minute)
|
||||
_, err := broken.Complete(ctx, e.alice, id, models.GameSessionCompleteInput{Score: score(50)})
|
||||
require.ErrorIs(t, err, assert.AnError)
|
||||
s := e.session(id)
|
||||
assert.Equal(t, constants.GameSessionStatusStarted, s.Status)
|
||||
assert.Zero(t, s.RewardTotal)
|
||||
assert.NotNil(t, s.CompletionFailedAt)
|
||||
assert.Zero(t, e.count(`SELECT COUNT(*) FROM wallet_transactions WHERE type = 'GAME_REWARD' AND reference_id = ?`, id))
|
||||
assert.EqualValues(t, before-2, e.coinBalance(e.alice))
|
||||
|
||||
// Once it expires, the session job refunds it as a system error.
|
||||
later(11 * time.Minute)
|
||||
refunded, _, err := e.sessions.ProcessDueSessions(ctx)
|
||||
require.NoError(t, err)
|
||||
assert.GreaterOrEqual(t, refunded, 1)
|
||||
assert.Equal(t, constants.GameSessionRefundSystemError, *e.session(id).RefundReason)
|
||||
assert.EqualValues(t, before, e.coinBalance(e.alice))
|
||||
})
|
||||
|
||||
t.Run("PROBABILITY draws on complete and keeps the draw", func(t *testing.T) {
|
||||
lucky := e.gameWith("lucky", entities.GameResultRules{}, constants.GameRewardTypeProbability,
|
||||
`{"table": [{"weight": 1, "amount": 1000}, {"weight": 999, "amount": 0}]}`, 0)
|
||||
id := start(e.bob, lucky.ID, "b-lucky")
|
||||
e.sessions.rng = &fixedRNG{draws: []int64{0}}
|
||||
defer func() { e.sessions.rng = CryptoRewardRNG{} }()
|
||||
out, err := e.sessions.Complete(ctx, e.bob, id, models.GameSessionCompleteInput{})
|
||||
require.NoError(t, err)
|
||||
assert.EqualValues(t, 1000, out.RewardTotal)
|
||||
var breakdown map[string]any
|
||||
require.NoError(t, json.Unmarshal(e.session(id).RewardBreakdown, &breakdown))
|
||||
assert.EqualValues(t, 0, breakdown["detail"].(map[string]any)["roll"])
|
||||
})
|
||||
|
||||
t.Run("an outcome worth nothing completes without a ledger row", func(t *testing.T) {
|
||||
outcomes := e.gameWith("outcomes", entities.GameResultRules{}, constants.GameRewardTypeOutcomeBased, `{"outcomes": {"WIN": 5, "FAIL": 0}}`, 0)
|
||||
id := start(e.bob, outcomes.ID, "b-fail")
|
||||
fail := "FAIL"
|
||||
out, err := e.sessions.Complete(ctx, e.bob, id, models.GameSessionCompleteInput{Outcome: &fail})
|
||||
require.NoError(t, err)
|
||||
assert.Zero(t, out.RewardTotal)
|
||||
assert.False(t, e.session(id).Flagged)
|
||||
assert.Zero(t, e.count(`SELECT COUNT(*) FROM game_session_rewards WHERE session_id = ?`, id))
|
||||
})
|
||||
}
|
||||
|
||||
// EG-402
|
||||
func TestGameSession_EconomyGuard(t *testing.T) {
|
||||
e := newEnakGameEnv(t)
|
||||
ctx := e.ctx()
|
||||
settings := NewLoyaltySettingsProcessor(repository.NewLoyaltySettingsRepository(e.db), e.txm)
|
||||
t.Cleanup(func() {
|
||||
e.db.Exec(`DELETE FROM loyalty_setting_changes WHERE organization_id = ?`, e.orgA)
|
||||
e.db.Exec(`DELETE FROM organization_settings WHERE organization_id = ?`, e.orgA)
|
||||
})
|
||||
setLimits := func(user, global int64) {
|
||||
t.Helper()
|
||||
s, err := settings.Organization(ctx, e.orgA)
|
||||
require.NoError(t, err)
|
||||
s.EnakGame = models.EnakGameLimitSettings{UserDailyLimit: user, GlobalDailyLimit: global}
|
||||
_, _, err = settings.UpdateOrganization(ctx, e.orgA, e.manager, *s)
|
||||
require.NoError(t, err)
|
||||
}
|
||||
counter := func(scope string, id uuid.UUID) int64 {
|
||||
t.Helper()
|
||||
got, err := repository.NewGameRewardCounterRepository(e.db).Get(ctx, e.orgA, scope, id, walletDay(e.now))
|
||||
require.NoError(t, err)
|
||||
return got
|
||||
}
|
||||
gameDaily := int64(1000)
|
||||
thirty := e.gameWith("thirty", entities.GameResultRules{DailyRewardLimit: &gameDaily}, constants.GameRewardTypeFixed, `{"amount": 30}`, 0)
|
||||
e.coins(e.alice, 100, nil)
|
||||
e.coins(e.bob, 100, nil)
|
||||
play := func(customer uuid.UUID, gameID uuid.UUID, key string) (*models.GameSessionCompletion, uuid.UUID) {
|
||||
t.Helper()
|
||||
s, err := e.sessions.Start(ctx, customer, gameID, key)
|
||||
require.NoError(t, err)
|
||||
out, err := e.sessions.Complete(ctx, customer, s.SessionID, models.GameSessionCompleteInput{})
|
||||
require.NoError(t, err)
|
||||
return out, s.SessionID
|
||||
}
|
||||
|
||||
// No limits: every reward is counted all the same.
|
||||
out, _ := play(e.alice, thirty.ID, "a0")
|
||||
assert.EqualValues(t, 30, out.RewardTotal)
|
||||
assert.Empty(t, out.LimitedBy)
|
||||
assert.EqualValues(t, 30, counter(constants.GameRewardScopeUser, e.alice))
|
||||
assert.EqualValues(t, 30, counter(constants.GameRewardScopeGlobal, e.orgA))
|
||||
|
||||
// Alice has 10 left of her 40: a reward of 30 pays 10 and says why.
|
||||
setLimits(40, 0)
|
||||
out, id := play(e.alice, thirty.ID, "a1")
|
||||
assert.EqualValues(t, 10, out.RewardTotal)
|
||||
assert.Equal(t, []string{"USER_DAILY"}, out.LimitedBy)
|
||||
var breakdown gameRewardBreakdown
|
||||
require.NoError(t, json.Unmarshal(e.session(id).RewardBreakdown, &breakdown))
|
||||
assert.Equal(t, []gameGuardCut{{Limit: "USER_DAILY", Value: 40, Asked: 30, Allowed: 10}}, breakdown.Guard)
|
||||
assert.EqualValues(t, 30, breakdown.Base, "the base stays what was earned")
|
||||
assert.EqualValues(t, 10, breakdown.Total)
|
||||
assert.Equal(t, int64(10), e.count(`SELECT amount FROM wallet_transactions WHERE type = 'GAME_REWARD' AND reference_id = ?`, id))
|
||||
again, err := e.sessions.Complete(ctx, e.alice, id, models.GameSessionCompleteInput{})
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, out, again, "the limit is part of the repeated answer")
|
||||
|
||||
// Nothing left: the session completes with no reward and no ledger row.
|
||||
out, id = play(e.alice, thirty.ID, "a2")
|
||||
assert.Zero(t, out.RewardTotal)
|
||||
assert.Equal(t, []string{"USER_DAILY"}, out.LimitedBy)
|
||||
assert.Equal(t, constants.GameSessionStatusCompleted, e.session(id).Status)
|
||||
assert.False(t, e.session(id).Flagged)
|
||||
assert.Zero(t, e.count(`SELECT COUNT(*) FROM wallet_transactions WHERE type = 'GAME_REWARD' AND reference_id = ?`, id))
|
||||
assert.EqualValues(t, 40, counter(constants.GameRewardScopeUser, e.alice))
|
||||
|
||||
// The organization's limit cuts Bob, and the counters before it give the
|
||||
// difference back: every counter holds what was paid.
|
||||
setLimits(0, 75)
|
||||
out, _ = play(e.bob, thirty.ID, "b1")
|
||||
assert.EqualValues(t, 30, out.RewardTotal)
|
||||
out, _ = play(e.bob, thirty.ID, "b2")
|
||||
assert.EqualValues(t, 5, out.RewardTotal, "70 of 75 already given today")
|
||||
assert.Equal(t, []string{"GLOBAL_DAILY"}, out.LimitedBy)
|
||||
assert.EqualValues(t, 35, counter(constants.GameRewardScopeUser, e.bob))
|
||||
assert.EqualValues(t, 75, counter(constants.GameRewardScopeGame, thirty.ID))
|
||||
assert.EqualValues(t, 75, counter(constants.GameRewardScopeGlobal, e.orgA))
|
||||
|
||||
// The game's own daily limit, and a new day starting over.
|
||||
setLimits(0, 0)
|
||||
small := int64(12)
|
||||
capped := e.gameWith("capped", entities.GameResultRules{DailyRewardLimit: &small}, constants.GameRewardTypeFixed, `{"amount": 30}`, 0)
|
||||
out, _ = play(e.bob, capped.ID, "b3")
|
||||
assert.EqualValues(t, 12, out.RewardTotal)
|
||||
assert.Equal(t, []string{"GAME_DAILY"}, out.LimitedBy)
|
||||
e.now = e.now.Add(24 * time.Hour)
|
||||
if e.count(`SELECT COUNT(*) FROM game_budgets WHERE organization_id = ? AND period_start <= ?::date AND period_end >= ?::date`,
|
||||
e.orgA, walletDay(e.now).Format("2006-01-02"), walletDay(e.now).Format("2006-01-02")) == 0 {
|
||||
e.globalBudget(e.orgA, e.now)
|
||||
}
|
||||
out, _ = play(e.bob, capped.ID, "b4")
|
||||
assert.EqualValues(t, 12, out.RewardTotal, "the next day has its own count")
|
||||
}
|
||||
@@ -0,0 +1,164 @@
|
||||
package processor
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"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/entities"
|
||||
"apskel-pos-be/internal/models"
|
||||
"apskel-pos-be/internal/repository"
|
||||
)
|
||||
|
||||
// realizedCost records a completed redemption whose face value the budget paid,
|
||||
// recognized at at.
|
||||
func (e *enakGameEnv) realizedCost(voucherID, budgetID uuid.UUID, amount int64, at time.Time) {
|
||||
e.t.Helper()
|
||||
debit, redemption := uuid.New(), uuid.New()
|
||||
require.NoError(e.t, e.db.Exec(`INSERT INTO wallet_transactions (id, organization_id, customer_id, currency, type, amount, balance_after, reference_type, reference_id, description)
|
||||
VALUES (?, ?, ?, 'POINT', 'REWARD_REDEEM', -1, 0, 'REWARD_REDEMPTION', ?, 'x')`, debit, e.orgA, e.bob, redemption).Error)
|
||||
require.NoError(e.t, e.db.Exec(`INSERT INTO voucher_redemptions (id, organization_id, customer_id, voucher_id, idempotency_key, status, face_value, point_cost, debit_transaction_id, completed_at)
|
||||
VALUES (?, ?, ?, ?, ?, 'COMPLETED', ?, 1, ?, ?)`, redemption, e.orgA, e.bob, voucherID, redemption.String(), amount, debit, at).Error)
|
||||
require.NoError(e.t, e.db.Exec(`INSERT INTO voucher_redemption_costs (redemption_id, budget_id, source_type, points, cost, recognized_at) VALUES (?, ?, 'GAME_REWARD', 1, ?, ?)`,
|
||||
redemption, budgetID, amount, at).Error)
|
||||
}
|
||||
|
||||
func (e *enakGameEnv) activeConfig(gameID uuid.UUID) *entities.GameRewardConfig {
|
||||
e.t.Helper()
|
||||
c, err := repository.NewEnakGameRepository(e.db).GetActiveRewardConfig(e.ctx(), e.orgA, gameID)
|
||||
require.NoError(e.t, err)
|
||||
return c
|
||||
}
|
||||
|
||||
// EG-901 and EG-902 against Postgres, from the PRD §30 numbers. Needs
|
||||
// TEST_DATABASE_URL; see internal/repository/wallet_repository_test.go.
|
||||
func TestGameBudgetController_AgainstPostgres(t *testing.T) {
|
||||
e := newEnakGameEnv(t)
|
||||
ctx := e.ctx()
|
||||
e.now = time.Date(2026, 10, 21, 12, 0, 0, 0, walletDisplayLocation)
|
||||
budgets := repository.NewGameBudgetRepository(e.db)
|
||||
metrics := NewGameBudgetMetricsProcessor(budgets, repository.NewGameBudgetMetricsRepository(e.db))
|
||||
controller := NewGameBudgetControllerProcessor(budgets, metrics, repository.NewEnakGameRepository(e.db),
|
||||
NewAuditLogger(repository.NewAuditLogRepository(e.db)), e.txm)
|
||||
controller.now = func() time.Time { return e.now }
|
||||
|
||||
october := e.globalBudget(e.orgA, e.now)
|
||||
tap := e.gameWith("tap", entities.GameResultRules{}, constants.GameRewardTypeFixed, `{"amount": 10}`, 10)
|
||||
run := e.gameWith("run", entities.GameResultRules{}, constants.GameRewardTypeScoreBased,
|
||||
`{"bands": [{"min": 0, "max": 100, "amount": 5}, {"min": 101, "amount": 20}]}`, 20)
|
||||
tapV1, runV1 := e.activeConfig(tap.ID), e.activeConfig(run.ID)
|
||||
|
||||
// Rp60M realized, Rp5,5M a day over the last week, 10 days left → Rp115M.
|
||||
voucher := e.staticVoucher(1_000, 1, 1)
|
||||
e.realizedCost(voucher.ID, october.ID, 21_500_000, time.Date(2026, 10, 5, 10, 0, 0, 0, walletDisplayLocation))
|
||||
for day := 15; day <= 21; day++ {
|
||||
e.realizedCost(voucher.ID, october.ID, 5_500_000, time.Date(2026, 10, day, 0, 0, 0, 0, walletDisplayLocation))
|
||||
}
|
||||
|
||||
rec, err := controller.Recommendation(ctx, e.orgA, october.ID)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, constants.GameBudgetRecommended, rec.State)
|
||||
assert.EqualValues(t, 115_000_000, rec.Metrics.ForecastCost)
|
||||
assert.InDelta(t, 0.7272, *rec.TargetMultiplier, 1e-9)
|
||||
assert.EqualValues(t, 0.9, rec.Multiplier, "one step of 10%")
|
||||
assert.EqualValues(t, 10, *rec.Guardrails.MaxStepPercent)
|
||||
require.Len(t, rec.Games, 2)
|
||||
assert.Equal(t, run.ID, rec.Games[0].GameID, "by game name")
|
||||
assert.JSONEq(t, `{"bands":[{"min":0,"max":100,"amount":4},{"min":101,"amount":18}]}`, string(rec.Games[0].NewRules))
|
||||
assert.EqualValues(t, 18, rec.Games[0].NewMaxReward)
|
||||
assert.JSONEq(t, `{"amount":9}`, string(rec.Games[1].NewRules))
|
||||
assert.Zero(t, e.count(`SELECT COUNT(*) FROM game_reward_configs WHERE organization_id = ? AND budget_id IS NOT NULL`, e.orgA), "showing changes nothing")
|
||||
|
||||
// Only what the admin saw is applied.
|
||||
_, err = controller.Accept(ctx, e.orgA, e.manager, october.ID, models.GameBudgetRecommendationAcceptInput{})
|
||||
assert.ErrorIs(t, err, ErrEnakGameRejected)
|
||||
_, err = controller.Accept(ctx, e.orgA, e.manager, october.ID, models.GameBudgetRecommendationAcceptInput{Multiplier: ptr(0.85)})
|
||||
assert.ErrorIs(t, err, ErrEnakGameRejected)
|
||||
assert.Zero(t, e.count(`SELECT COUNT(*) FROM game_reward_configs WHERE organization_id = ? AND budget_id IS NOT NULL`, e.orgA))
|
||||
|
||||
accepted, err := controller.Accept(ctx, e.orgA, e.manager, october.ID, models.GameBudgetRecommendationAcceptInput{
|
||||
Multiplier: ptr(0.9), Reason: ptr("Burn rate terlalu tinggi"),
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.Len(t, accepted.RewardConfigs, 2)
|
||||
tapV2 := e.activeConfig(tap.ID)
|
||||
assert.Equal(t, 2, tapV2.Version)
|
||||
assert.JSONEq(t, `{"amount":9}`, string(tapV2.Rules))
|
||||
assert.EqualValues(t, 9, tapV2.MaxReward)
|
||||
assert.EqualValues(t, 0.9, *tapV2.Multiplier)
|
||||
assert.Equal(t, tapV1.ID, *tapV2.BaseConfigID)
|
||||
assert.Equal(t, october.ID, *tapV2.BudgetID)
|
||||
assert.Equal(t, "Burn rate terlalu tinggi", *tapV2.Reason)
|
||||
assert.EqualValues(t, 1, e.count(`SELECT COUNT(*) FROM game_reward_configs WHERE id = ? AND status = 'RETIRED'`, tapV1.ID))
|
||||
assert.EqualValues(t, 1, e.count(`SELECT COUNT(*) FROM game_reward_configs WHERE id = ? AND status = 'RETIRED'`, runV1.ID))
|
||||
assert.Equal(t, []string{"CREATED", constants.AuditActionRecommendationAccepted}, e.auditActions(constants.AuditEntityGameBudget, october.ID))
|
||||
assert.Equal(t, []string{"ACTIVATED", "CREATED"}, e.auditActions(constants.AuditEntityGameRewardConfig, tapV2.ID))
|
||||
assert.EqualValues(t, 7, e.count(`SELECT COUNT(*) FROM audit_logs WHERE organization_id = ? AND source = ?`, e.orgA, constants.AuditSourceBudgetController),
|
||||
"per game: retired, created, activated; and the budget")
|
||||
|
||||
// The game pays the new amount.
|
||||
e.coins(e.alice, 2, nil)
|
||||
started, err := e.sessions.Start(ctx, e.alice, tap.ID, "after")
|
||||
require.NoError(t, err)
|
||||
done, err := e.sessions.Complete(ctx, e.alice, started.SessionID, models.GameSessionCompleteInput{})
|
||||
require.NoError(t, err)
|
||||
assert.EqualValues(t, 9, done.RewardTotal)
|
||||
|
||||
// Not again within the cooldown, though the forecast is still over.
|
||||
rec, err = controller.Recommendation(ctx, e.orgA, october.ID)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, constants.GameBudgetRecommendationCooldown, rec.State)
|
||||
require.NotNil(t, rec.CooldownUntil)
|
||||
assert.WithinDuration(t, e.now.AddDate(0, 0, 7), *rec.CooldownUntil, time.Second)
|
||||
assert.EqualValues(t, 0.81, rec.Games[1].NewMultiplier, "what it would be")
|
||||
_, err = controller.Accept(ctx, e.orgA, e.manager, october.ID, models.GameBudgetRecommendationAcceptInput{Multiplier: ptr(0.9)})
|
||||
assert.ErrorIs(t, err, ErrEnakGameRejected)
|
||||
|
||||
// No cooldown and a floor of 85%: 0.81 stops at 0.85, scaled from version 1.
|
||||
current, err := e.budgets.GetBudget(ctx, e.orgA, october.ID)
|
||||
require.NoError(t, err)
|
||||
in := GameBudgetInputFrom(current)
|
||||
in.Thresholds.CooldownDays, in.Thresholds.MinMultiplierPercent = ptr(int64(0)), ptr(int64(85))
|
||||
_, err = e.budgets.UpdateBudget(ctx, e.orgA, e.manager, october.ID, in)
|
||||
require.NoError(t, err)
|
||||
rec, err = controller.Recommendation(ctx, e.orgA, october.ID)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, constants.GameBudgetRecommended, rec.State)
|
||||
_, err = controller.Accept(ctx, e.orgA, e.manager, october.ID, models.GameBudgetRecommendationAcceptInput{Multiplier: ptr(0.9)})
|
||||
require.NoError(t, err)
|
||||
tapV3 := e.activeConfig(tap.ID)
|
||||
assert.EqualValues(t, 0.85, *tapV3.Multiplier)
|
||||
assert.JSONEq(t, `{"amount":8}`, string(tapV3.Rules), "10 × 0.85, rounded down")
|
||||
assert.Equal(t, tapV1.ID, *tapV3.BaseConfigID, "always from the admin's version")
|
||||
|
||||
rec, err = controller.Recommendation(ctx, e.orgA, october.ID)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, constants.GameBudgetRecommendationAtLimit, rec.State)
|
||||
assert.Empty(t, rec.Games)
|
||||
|
||||
// An admin's new version starts over from 1.
|
||||
config, err := e.admin.CreateRewardConfig(ctx, e.orgA, e.manager, tap.ID, models.GameRewardConfigInput{
|
||||
RewardType: constants.GameRewardTypeFixed, Rules: json.RawMessage(`{"amount": 12}`), MaxReward: 12,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
_, err = e.admin.ActivateRewardConfig(ctx, e.orgA, e.manager, config.ID, models.GameRewardConfigActivateInput{})
|
||||
require.NoError(t, err)
|
||||
rec, err = controller.Recommendation(ctx, e.orgA, october.ID)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, constants.GameBudgetRecommended, rec.State)
|
||||
require.Len(t, rec.Games, 1)
|
||||
assert.Equal(t, config.ID, rec.Games[0].BaseConfigID)
|
||||
assert.JSONEq(t, `{"amount":10}`, string(rec.Games[0].NewRules), "12 × 0.9, rounded down")
|
||||
|
||||
// Event budgets pay for what events add, which is set on the event.
|
||||
event := e.eventBudget(e.orgA, "Ramadan")
|
||||
_, err = controller.Recommendation(ctx, e.orgA, event.ID)
|
||||
assert.ErrorIs(t, err, ErrEnakGameRejected)
|
||||
_, err = controller.Recommendation(ctx, e.orgB, october.ID)
|
||||
assert.ErrorIs(t, err, repository.ErrGameBudgetNotFound)
|
||||
}
|
||||
@@ -0,0 +1,368 @@
|
||||
package processor
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"math"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"apskel-pos-be/internal/constants"
|
||||
"apskel-pos-be/internal/entities"
|
||||
"apskel-pos-be/internal/models"
|
||||
"apskel-pos-be/internal/repository"
|
||||
)
|
||||
|
||||
// GameBudgetControllerProcessor is the Budget Controller in recommendation mode
|
||||
// (docs/rfc-enakgame.md §10, D9; PRD §29–§33). For a global budget it computes the
|
||||
// multiplier that brings the forecast to the budget, keeps it within the guardrails,
|
||||
// and shows what every game's reward would become. Nothing changes until an admin
|
||||
// accepts; accepting writes a new active version of each game's configuration, audited
|
||||
// with source budget_controller.
|
||||
//
|
||||
// A game's multiplier is kept against its base, the version its admin wrote last, so
|
||||
// adjustments do not compound their rounding and min/max mean "of what the admin
|
||||
// set". An admin writing a new version starts a new base at 1.
|
||||
type GameBudgetControllerProcessor struct {
|
||||
budgets repository.GameBudgetRepository
|
||||
metrics *GameBudgetMetricsProcessor
|
||||
games repository.EnakGameRepository
|
||||
audit *AuditLogger
|
||||
tx TxRunner
|
||||
now func() time.Time
|
||||
}
|
||||
|
||||
func NewGameBudgetControllerProcessor(budgets repository.GameBudgetRepository, metrics *GameBudgetMetricsProcessor, games repository.EnakGameRepository,
|
||||
audit *AuditLogger, tx TxRunner) *GameBudgetControllerProcessor {
|
||||
return &GameBudgetControllerProcessor{budgets: budgets, metrics: metrics, games: games, audit: audit, tx: tx, now: time.Now}
|
||||
}
|
||||
|
||||
// budgetGuardrails are a budget's guardrails in percent (PRD §31), with the defaults
|
||||
// for those it does not set.
|
||||
type budgetGuardrails struct {
|
||||
step, min, max, cooldownDays int64
|
||||
}
|
||||
|
||||
func guardrailsOf(b *entities.GameBudget) budgetGuardrails {
|
||||
g := budgetGuardrails{
|
||||
step: constants.GameBudgetMaxStepDefault, min: constants.GameBudgetMinMultiplierDefault,
|
||||
max: constants.GameBudgetMaxMultiplierDefault, cooldownDays: constants.GameBudgetCooldownDaysDefault,
|
||||
}
|
||||
var set models.GameBudgetThresholds
|
||||
if len(b.Thresholds) > 0 {
|
||||
_ = json.Unmarshal(b.Thresholds, &set)
|
||||
}
|
||||
for _, v := range []struct {
|
||||
from *int64
|
||||
to *int64
|
||||
}{{set.MaxStepPercent, &g.step}, {set.MinMultiplierPercent, &g.min}, {set.MaxMultiplierPercent, &g.max}, {set.CooldownDays, &g.cooldownDays}} {
|
||||
if v.from != nil {
|
||||
*v.to = *v.from
|
||||
}
|
||||
}
|
||||
return g
|
||||
}
|
||||
|
||||
func (g budgetGuardrails) model() models.GameBudgetThresholds {
|
||||
step, lo, hi, cooldown := g.step, g.min, g.max, g.cooldownDays
|
||||
return models.GameBudgetThresholds{MaxStepPercent: &step, MinMultiplierPercent: &lo, MaxMultiplierPercent: &hi, CooldownDays: &cooldown}
|
||||
}
|
||||
|
||||
// budgetStepMultiplier is the multiplier, in ten-thousandths, that one accepted
|
||||
// recommendation applies to every game's reward. target is what would make the
|
||||
// forecast meet the budget, nil when there is no cost to extrapolate from. step is
|
||||
// target within one step of 1, rounded down to two decimals: down never pays more than
|
||||
// the forecast allows. state is set when there is nothing to recommend.
|
||||
//
|
||||
// The forecast is realized + burn × days left, and only the future part follows the
|
||||
// rewards, so the target is (budget − realized) / (forecast − realized).
|
||||
func budgetStepMultiplier(m models.GameBudgetMetrics, g budgetGuardrails) (target *int64, step int64, state string) {
|
||||
one := rewardMultiplierOne
|
||||
if m.WindowDays == 0 || m.RemainingDays == 0 {
|
||||
return nil, one, constants.GameBudgetRecommendationOutOfPeriod
|
||||
}
|
||||
future := m.ForecastCost - m.RealizedCost
|
||||
if future <= 0 {
|
||||
return nil, one, constants.GameBudgetRecommendationNoData
|
||||
}
|
||||
t := int64(math.Floor(float64(m.Amount-m.RealizedCost) * float64(one) / float64(future)))
|
||||
t = max(t, 0)
|
||||
step = min(max(t, one-g.step*100), one+g.step*100)
|
||||
step -= step % 100
|
||||
if step == one {
|
||||
return &t, one, constants.GameBudgetRecommendationNoChange
|
||||
}
|
||||
return &t, step, ""
|
||||
}
|
||||
|
||||
// nextGameMultiplier is a game's multiplier after a step: current × step, rounded
|
||||
// down, within min and max. A game outside min and max, because they changed since
|
||||
// its last adjustment, is brought inside, but never moved against the step.
|
||||
func nextGameMultiplier(current, step int64, g budgetGuardrails) int64 {
|
||||
next := current * step / rewardMultiplierOne
|
||||
next = min(max(next, g.min*100), g.max*100)
|
||||
if (step < rewardMultiplierOne && next > current) || (step > rewardMultiplierOne && next < current) {
|
||||
return current
|
||||
}
|
||||
return next
|
||||
}
|
||||
|
||||
// rewardAdjustment is a game's part of a recommendation, with what accepting it needs.
|
||||
type rewardAdjustment struct {
|
||||
model models.GameRewardAdjustment
|
||||
active *entities.GameRewardConfig
|
||||
base *entities.GameRewardConfig
|
||||
multiplier int64
|
||||
rules json.RawMessage
|
||||
maxReward int64
|
||||
}
|
||||
|
||||
func multiplierOf(c *entities.GameRewardConfig) int64 {
|
||||
if c.Multiplier == nil {
|
||||
return rewardMultiplierOne
|
||||
}
|
||||
return int64(math.Round(*c.Multiplier * float64(rewardMultiplierOne)))
|
||||
}
|
||||
|
||||
func multiplierValue(m int64) float64 {
|
||||
return float64(m) / float64(rewardMultiplierOne)
|
||||
}
|
||||
|
||||
// Recommendation is GET /marketing/enakgame/budgets/:id/recommendation.
|
||||
func (p *GameBudgetControllerProcessor) Recommendation(ctx context.Context, organizationID, budgetID uuid.UUID) (*models.GameBudgetRecommendation, error) {
|
||||
budget, err := p.budgets.GetBudget(ctx, organizationID, budgetID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
rec, _, err := p.recommend(ctx, budget, p.now())
|
||||
return rec, err
|
||||
}
|
||||
|
||||
func (p *GameBudgetControllerProcessor) recommend(ctx context.Context, budget *entities.GameBudget, now time.Time) (*models.GameBudgetRecommendation, []rewardAdjustment, error) {
|
||||
if budget.Scope != constants.GameBudgetScopeGlobal {
|
||||
return nil, nil, enakGameRejected("the Budget Controller only adjusts base rewards, paid by GLOBAL budgets; an event's extra is set on the event")
|
||||
}
|
||||
metrics, err := p.metrics.metricsAt(ctx, budget, now)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
g := guardrailsOf(budget)
|
||||
target, step, state := budgetStepMultiplier(*metrics, g)
|
||||
rec := &models.GameBudgetRecommendation{
|
||||
BudgetID: budget.ID, Metrics: *metrics, Guardrails: g.model(), Multiplier: multiplierValue(step),
|
||||
Games: []models.GameRewardAdjustment{},
|
||||
}
|
||||
if target != nil {
|
||||
t := multiplierValue(*target)
|
||||
rec.TargetMultiplier = &t
|
||||
}
|
||||
switch state {
|
||||
case constants.GameBudgetRecommendationOutOfPeriod:
|
||||
rec.State, rec.Message = state, "the budget's period has not started, or has no day left after today"
|
||||
return rec, nil, nil
|
||||
case constants.GameBudgetRecommendationNoData:
|
||||
rec.State, rec.Message = state, fmt.Sprintf("no voucher cost in the last %d days to forecast from", metrics.WindowDays)
|
||||
return rec, nil, nil
|
||||
case constants.GameBudgetRecommendationNoChange:
|
||||
rec.State, rec.Message = state, "the forecast meets the budget; rewards stay"
|
||||
return rec, nil, nil
|
||||
}
|
||||
|
||||
configs, err := p.games.ListActiveRewardConfigs(ctx, budget.OrganizationID)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
var adjustments []rewardAdjustment
|
||||
for i := range configs {
|
||||
active := &configs[i].GameRewardConfig
|
||||
current := multiplierOf(active)
|
||||
next := nextGameMultiplier(current, step, g)
|
||||
if next == current {
|
||||
continue
|
||||
}
|
||||
base := active
|
||||
if active.BaseConfigID != nil {
|
||||
if base, err = p.games.GetRewardConfig(ctx, budget.OrganizationID, *active.BaseConfigID); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
}
|
||||
a, err := adjust(configs[i].GameName, active, base, next)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
adjustments = append(adjustments, a)
|
||||
rec.Games = append(rec.Games, a.model)
|
||||
}
|
||||
|
||||
last, err := p.games.LastBudgetControllerChange(ctx, budget.OrganizationID)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
var until *time.Time
|
||||
if last != nil && g.cooldownDays > 0 {
|
||||
if u := last.AddDate(0, 0, int(g.cooldownDays)); now.Before(u) {
|
||||
until = &u
|
||||
}
|
||||
}
|
||||
switch {
|
||||
case len(adjustments) == 0:
|
||||
rec.State, rec.Message = constants.GameBudgetRecommendationAtLimit, "every game is already at its min or max multiplier"
|
||||
case until != nil:
|
||||
rec.State, rec.CooldownUntil = constants.GameBudgetRecommendationCooldown, until
|
||||
rec.Message = fmt.Sprintf("a recommendation was accepted less than %d days ago", g.cooldownDays)
|
||||
default:
|
||||
rec.State = constants.GameBudgetRecommended
|
||||
rec.Message = fmt.Sprintf("forecast Rp%d against a budget of Rp%d: multiply rewards by %.2f", metrics.ForecastCost, metrics.Amount, rec.Multiplier)
|
||||
}
|
||||
return rec, adjustments, nil
|
||||
}
|
||||
|
||||
// adjust scales a game's base configuration to a multiplier.
|
||||
func adjust(gameName string, active, base *entities.GameRewardConfig, multiplier int64) (rewardAdjustment, error) {
|
||||
calculator, err := RewardCalculatorFor(base.RewardType)
|
||||
if err != nil {
|
||||
return rewardAdjustment{}, err
|
||||
}
|
||||
rules, err := calculator.Scale(json.RawMessage(base.Rules), multiplier)
|
||||
if err != nil {
|
||||
return rewardAdjustment{}, enakGameRejected("cannot scale the reward of %s: %v", gameName, err)
|
||||
}
|
||||
maxReward, err := scaleRewardAmount(base.MaxReward, multiplier)
|
||||
if err != nil {
|
||||
return rewardAdjustment{}, enakGameRejected("cannot scale the max_reward of %s: %v", gameName, err)
|
||||
}
|
||||
return rewardAdjustment{
|
||||
model: models.GameRewardAdjustment{
|
||||
GameID: active.GameID, GameName: gameName, RewardConfigID: active.ID, Version: active.Version,
|
||||
BaseConfigID: base.ID, RewardType: base.RewardType,
|
||||
CurrentMultiplier: multiplierValue(multiplierOf(active)), NewMultiplier: multiplierValue(multiplier),
|
||||
CurrentRules: json.RawMessage(active.Rules), NewRules: rules,
|
||||
CurrentMaxReward: active.MaxReward, NewMaxReward: maxReward,
|
||||
},
|
||||
active: active, base: base, multiplier: multiplier, rules: rules, maxReward: maxReward,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Accept applies the recommendation the admin saw: for every game it changes, a new
|
||||
// active version of the configuration replaces the active one, in one transaction.
|
||||
// When the recommendation is no longer what the admin saw, nothing changes.
|
||||
func (p *GameBudgetControllerProcessor) Accept(ctx context.Context, organizationID, actor, budgetID uuid.UUID, in models.GameBudgetRecommendationAcceptInput) (*models.GameBudgetRecommendationAccepted, error) {
|
||||
if in.Multiplier == nil {
|
||||
return nil, enakGameRejected("multiplier is required: the one the recommendation showed")
|
||||
}
|
||||
if err := validateReason(in.Reason); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
seen := int64(math.Round(*in.Multiplier * float64(rewardMultiplierOne)))
|
||||
|
||||
var out *models.GameBudgetRecommendationAccepted
|
||||
err := p.tx.WithTransaction(ctx, func(ctx context.Context) error {
|
||||
// One acceptance at a time in the organization, so two cannot both pass the
|
||||
// cooldown, and none while a budget is being changed.
|
||||
if err := p.budgets.LockGlobalBudgets(ctx, organizationID); err != nil {
|
||||
return err
|
||||
}
|
||||
budget, err := p.budgets.GetBudget(ctx, organizationID, budgetID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
now := p.now()
|
||||
rec, adjustments, err := p.recommend(ctx, budget, now)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if rec.State != constants.GameBudgetRecommended {
|
||||
return enakGameRejected("nothing to accept: %s", rec.Message)
|
||||
}
|
||||
if seen != int64(math.Round(rec.Multiplier*float64(rewardMultiplierOne))) {
|
||||
return enakGameRejected("the recommendation is now %.2f; review it again", rec.Multiplier)
|
||||
}
|
||||
reason := in.Reason
|
||||
if reason == nil {
|
||||
r := fmt.Sprintf("Budget Controller: rewards × %.2f for budget %s", rec.Multiplier, budget.ID)
|
||||
reason = &r
|
||||
}
|
||||
|
||||
out = &models.GameBudgetRecommendationAccepted{BudgetID: budget.ID, Multiplier: rec.Multiplier}
|
||||
configIDs := make([]uuid.UUID, 0, len(adjustments))
|
||||
for _, a := range adjustments {
|
||||
config, err := p.apply(ctx, organizationID, actor, budget.ID, a, now, reason)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
out.RewardConfigs = append(out.RewardConfigs, *rewardConfigModel(config))
|
||||
configIDs = append(configIDs, config.ID)
|
||||
}
|
||||
return p.record(ctx, organizationID, actor, constants.AuditEntityGameBudget, budget.ID, constants.AuditActionRecommendationAccepted, nil,
|
||||
map[string]any{
|
||||
"multiplier": rec.Multiplier, "target_multiplier": rec.TargetMultiplier, "amount": rec.Metrics.Amount,
|
||||
"realized_cost": rec.Metrics.RealizedCost, "forecast_cost": rec.Metrics.ForecastCost,
|
||||
"guardrails": rec.Guardrails, "reward_config_ids": configIDs,
|
||||
}, reason)
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// apply retires a game's active configuration and activates its adjusted version.
|
||||
func (p *GameBudgetControllerProcessor) apply(ctx context.Context, organizationID, actor, budgetID uuid.UUID, a rewardAdjustment, now time.Time, reason *string) (*entities.GameRewardConfig, error) {
|
||||
// Waits for an admin changing the same game's configuration, then checks the
|
||||
// recommendation was made from the version still active.
|
||||
changed := enakGameRejected("%s changed meanwhile; review the recommendation again", a.model.GameName)
|
||||
game, err := p.games.LockGame(ctx, organizationID, a.active.GameID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if game.Status == constants.GameStatusArchived {
|
||||
return nil, changed
|
||||
}
|
||||
active, err := p.games.GetActiveRewardConfig(ctx, organizationID, a.active.GameID)
|
||||
if errors.Is(err, repository.ErrGameRewardConfigNotFound) {
|
||||
return nil, changed
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if active.ID != a.active.ID {
|
||||
return nil, changed
|
||||
}
|
||||
moved, err := p.games.SetRewardConfigStatus(ctx, organizationID, active.ID, constants.GameRewardConfigStatusActive, constants.GameRewardConfigStatusRetired)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !moved {
|
||||
return nil, changed
|
||||
}
|
||||
if err := p.record(ctx, organizationID, actor, constants.AuditEntityGameRewardConfig, active.ID, "RETIRED",
|
||||
map[string]string{"status": constants.GameRewardConfigStatusActive}, map[string]string{"status": constants.GameRewardConfigStatusRetired}, reason); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
multiplier, baseID, budget := multiplierValue(a.multiplier), a.base.ID, budgetID
|
||||
config := &entities.GameRewardConfig{
|
||||
OrganizationID: organizationID, GameID: active.GameID, RewardType: a.base.RewardType,
|
||||
Rules: entities.JSONDocument(a.rules), MaxReward: a.maxReward, Status: constants.GameRewardConfigStatusActive,
|
||||
EffectiveAt: &now, CreatedBy: actor, Reason: reason, BaseConfigID: &baseID, Multiplier: &multiplier, BudgetID: &budget,
|
||||
}
|
||||
if err := p.games.CreateRewardConfig(ctx, config); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := p.record(ctx, organizationID, actor, constants.AuditEntityGameRewardConfig, config.ID, "CREATED", nil, rewardConfigModel(config), reason); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return config, p.record(ctx, organizationID, actor, constants.AuditEntityGameRewardConfig, config.ID, "ACTIVATED",
|
||||
nil, map[string]string{"status": constants.GameRewardConfigStatusActive}, reason)
|
||||
}
|
||||
|
||||
func (p *GameBudgetControllerProcessor) record(ctx context.Context, organizationID, actor uuid.UUID, entityType string, entityID uuid.UUID, action string, before, after any, reason *string) error {
|
||||
return p.audit.Record(ctx, AuditEntry{
|
||||
OrganizationID: organizationID, ActorType: constants.AuditActorUser, ActorID: &actor,
|
||||
EntityType: entityType, EntityID: entityID, Action: action,
|
||||
Before: before, After: after, Reason: reason, Source: constants.AuditSourceBudgetController,
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
package processor
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
|
||||
"apskel-pos-be/internal/constants"
|
||||
"apskel-pos-be/internal/entities"
|
||||
"apskel-pos-be/internal/models"
|
||||
)
|
||||
|
||||
var defaultGuardrails = budgetGuardrails{step: 10, min: 50, max: 150, cooldownDays: 7}
|
||||
|
||||
// EG-901: the multiplier of one recommendation.
|
||||
func TestBudgetStepMultiplier(t *testing.T) {
|
||||
// metrics is a running budget of Rp100M: realized so far, forecast at period end.
|
||||
metrics := func(realized, forecast int64) models.GameBudgetMetrics {
|
||||
return models.GameBudgetMetrics{Amount: 100_000_000, RealizedCost: realized, ForecastCost: forecast, WindowDays: 7, RemainingDays: 10}
|
||||
}
|
||||
for name, tc := range map[string]struct {
|
||||
m models.GameBudgetMetrics
|
||||
g budgetGuardrails
|
||||
wantTarget *int64
|
||||
wantStep int64
|
||||
wantState string
|
||||
}{
|
||||
// PRD §30: Rp40M left for Rp55M forecast → 0.7272, one step down.
|
||||
"PRD §30": {metrics(60_000_000, 115_000_000), defaultGuardrails, ptr(int64(7272)), 9_000, ""},
|
||||
"wider step": {metrics(60_000_000, 115_000_000), budgetGuardrails{step: 30, min: 50, max: 150}, ptr(int64(7272)), 7_200, ""},
|
||||
"slightly over": {metrics(60_000_000, 100_400_000), defaultGuardrails, ptr(int64(9900)), 9_900, ""},
|
||||
"under budget": {metrics(20_000_000, 60_000_000), defaultGuardrails, ptr(int64(20000)), 11_000, ""},
|
||||
"slightly under": {metrics(60_000_000, 99_000_000), defaultGuardrails, ptr(int64(10256)), 10_200, ""},
|
||||
"on budget": {metrics(60_000_000, 100_000_000), defaultGuardrails, ptr(int64(10000)), 10_000, constants.GameBudgetRecommendationNoChange},
|
||||
"a hair under": {metrics(60_000_000, 99_900_000), defaultGuardrails, ptr(int64(10025)), 10_000, constants.GameBudgetRecommendationNoChange},
|
||||
"already over budget": {metrics(110_000_000, 120_000_000), defaultGuardrails, ptr(int64(0)), 9_000, ""},
|
||||
"no recent cost": {metrics(60_000_000, 60_000_000), defaultGuardrails, nil, 10_000, constants.GameBudgetRecommendationNoData},
|
||||
"not started": {models.GameBudgetMetrics{Amount: 100_000_000}, defaultGuardrails,
|
||||
nil, 10_000, constants.GameBudgetRecommendationOutOfPeriod},
|
||||
"last day": {models.GameBudgetMetrics{Amount: 100_000_000, RealizedCost: 1, ForecastCost: 1, WindowDays: 7}, defaultGuardrails,
|
||||
nil, 10_000, constants.GameBudgetRecommendationOutOfPeriod},
|
||||
} {
|
||||
target, step, state := budgetStepMultiplier(tc.m, tc.g)
|
||||
assert.Equal(t, tc.wantTarget, target, name)
|
||||
assert.Equal(t, tc.wantStep, step, name)
|
||||
assert.Equal(t, tc.wantState, state, name)
|
||||
}
|
||||
}
|
||||
|
||||
// EG-901: a game's multiplier after a step, against its admin's configuration.
|
||||
func TestNextGameMultiplier(t *testing.T) {
|
||||
for name, tc := range map[string]struct {
|
||||
current, step, want int64
|
||||
g budgetGuardrails
|
||||
}{
|
||||
"first step down": {10_000, 9_000, 9_000, defaultGuardrails},
|
||||
"compounds": {9_000, 9_000, 8_100, defaultGuardrails},
|
||||
"rounds down": {8_100, 9_900, 8_019, defaultGuardrails},
|
||||
"stops at min": {5_500, 9_000, 5_000, defaultGuardrails},
|
||||
"stays at min": {5_000, 9_000, 5_000, defaultGuardrails},
|
||||
"stops at max": {14_000, 11_000, 15_000, defaultGuardrails},
|
||||
"up from a cut": {8_100, 11_000, 8_910, defaultGuardrails},
|
||||
"min raised since: up": {4_000, 11_000, 5_000, defaultGuardrails},
|
||||
"min raised since: stays": {4_000, 9_000, 4_000, defaultGuardrails},
|
||||
"max lowered since: down": {20_000, 9_000, 15_000, defaultGuardrails},
|
||||
"max lowered since: stay": {20_000, 11_000, 20_000, defaultGuardrails},
|
||||
"own bounds": {10_000, 9_000, 9_500, budgetGuardrails{step: 10, min: 95, max: 100}},
|
||||
} {
|
||||
assert.Equal(t, tc.want, nextGameMultiplier(tc.current, tc.step, tc.g), name)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGuardrailsOf(t *testing.T) {
|
||||
assert.Equal(t, defaultGuardrails, guardrailsOf(&entities.GameBudget{}), "the defaults")
|
||||
assert.Equal(t, defaultGuardrails, guardrailsOf(&entities.GameBudget{Thresholds: entities.JSONDocument(`{"warning": 50}`)}))
|
||||
assert.Equal(t, budgetGuardrails{step: 5, min: 80, max: 150, cooldownDays: 0},
|
||||
guardrailsOf(&entities.GameBudget{Thresholds: entities.JSONDocument(`{"max_step_percent": 5, "min_multiplier_percent": 80, "cooldown_days": 0}`)}))
|
||||
}
|
||||
|
||||
func TestGameBudgetGuardrailValidation(t *testing.T) {
|
||||
in := func(th models.GameBudgetThresholds) models.GameBudgetInput {
|
||||
return models.GameBudgetInput{Scope: "GLOBAL", Name: "Oktober", PeriodStart: "2026-10-01", PeriodEnd: "2026-10-31", Amount: 1, Thresholds: th}
|
||||
}
|
||||
_, err := gameBudgetFromInput(in(models.GameBudgetThresholds{
|
||||
MaxStepPercent: ptr(int64(50)), MinMultiplierPercent: ptr(int64(1)), MaxMultiplierPercent: ptr(int64(1000)), CooldownDays: ptr(int64(0)),
|
||||
}))
|
||||
assert.NoError(t, err)
|
||||
for name, th := range map[string]models.GameBudgetThresholds{
|
||||
"step 0": {MaxStepPercent: ptr(int64(0))},
|
||||
"step 51": {MaxStepPercent: ptr(int64(51))},
|
||||
"min 0": {MinMultiplierPercent: ptr(int64(0))},
|
||||
"min above 1x": {MinMultiplierPercent: ptr(int64(101))},
|
||||
"max below 1x": {MaxMultiplierPercent: ptr(int64(99))},
|
||||
"max too high": {MaxMultiplierPercent: ptr(int64(1001))},
|
||||
"cooldown -1": {CooldownDays: ptr(int64(-1))},
|
||||
"cooldown 91": {CooldownDays: ptr(int64(91))},
|
||||
} {
|
||||
_, err := gameBudgetFromInput(in(th))
|
||||
assert.ErrorIs(t, err, ErrEnakGameRejected, name)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
package processor
|
||||
|
||||
import (
|
||||
"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"
|
||||
"apskel-pos-be/internal/repository"
|
||||
)
|
||||
|
||||
// EG-601 against Postgres, with fixed data giving the PRD §30 numbers. Needs
|
||||
// TEST_DATABASE_URL; see internal/repository/wallet_repository_test.go.
|
||||
func TestGameBudgetMetrics_AgainstPostgres(t *testing.T) {
|
||||
e := newEnakGameEnv(t)
|
||||
ctx := e.ctx()
|
||||
e.now = time.Date(2026, 10, 21, 12, 0, 0, 0, walletDisplayLocation)
|
||||
metrics := NewGameBudgetMetricsProcessor(repository.NewGameBudgetRepository(e.db), repository.NewGameBudgetMetricsRepository(e.db))
|
||||
metrics.now = func() time.Time { return e.now }
|
||||
|
||||
october := e.globalBudget(e.orgA, e.now)
|
||||
event, err := e.budgets.CreateBudget(ctx, e.orgA, e.manager, models.GameBudgetInput{
|
||||
Scope: "EVENT", Name: "Ramadan", PeriodStart: "2026-10-10", PeriodEnd: "2026-10-20", Amount: 10_000_000,
|
||||
Thresholds: models.GameBudgetThresholds{Warning: ptr(int64(20)), Critical: ptr(int64(50))},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
voucher := e.staticVoucher(1_000, 1, 1)
|
||||
// cost records a completed redemption whose face value went to budget (nil: EnakPoint
|
||||
// not from EnakGame), recognized at a time in Jakarta.
|
||||
cost := func(budget *uuid.UUID, source string, amount int64, day, hour int) {
|
||||
t.Helper()
|
||||
at := time.Date(2026, time.Month(day/100), day%100, hour, 0, 0, 0, walletDisplayLocation)
|
||||
debit, redemption := uuid.New(), uuid.New()
|
||||
require.NoError(t, e.db.Exec(`INSERT INTO wallet_transactions (id, organization_id, customer_id, currency, type, amount, balance_after, reference_type, reference_id, description)
|
||||
VALUES (?, ?, ?, 'POINT', 'REWARD_REDEEM', -1, 0, 'REWARD_REDEMPTION', ?, 'x')`, debit, e.orgA, e.bob, redemption).Error)
|
||||
require.NoError(t, e.db.Exec(`INSERT INTO voucher_redemptions (id, organization_id, customer_id, voucher_id, idempotency_key, status, face_value, point_cost, debit_transaction_id, completed_at)
|
||||
VALUES (?, ?, ?, ?, ?, 'COMPLETED', ?, 1, ?, ?)`, redemption, e.orgA, e.bob, voucher.ID, redemption.String(), amount, debit, at).Error)
|
||||
require.NoError(t, e.db.Exec(`INSERT INTO voucher_redemption_costs (redemption_id, budget_id, source_type, points, cost, recognized_at) VALUES (?, ?, ?, 1, ?, ?)`,
|
||||
redemption, budget, source, amount, at).Error)
|
||||
}
|
||||
global, ev := october.ID, event.ID
|
||||
cost(&global, "GAME_REWARD", 5_000_000, 930, 23) // 30 Sep 23:00 WIB: the month before
|
||||
cost(&global, "GAME_REWARD", 21_500_000, 1005, 1) // before the forecast window
|
||||
for day := 1015; day <= 1021; day++ { // the last seven days, today included
|
||||
cost(&global, "GAME_REWARD", 5_500_000, day, 0)
|
||||
}
|
||||
cost(nil, "EARN", 9_000_000, 1020, 10) // shopping EnakPoint: no budget
|
||||
cost(&ev, "GAME_REWARD", 1_000_000, 1012, 10)
|
||||
cost(&ev, "GAME_REWARD", 2_000_000, 1021, 9) // after the event ended: still its cost
|
||||
|
||||
// EnakCoin the global budget paid for, partly exchanged into EnakPoint.
|
||||
paid := e.rewardCoins(e.alice, 100)
|
||||
require.Equal(t, october.ID, paid)
|
||||
e.exchangeCoins(e.alice, 40)
|
||||
|
||||
m, err := metrics.Metrics(ctx, e.orgA, october.ID)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "2026-10-21", m.AsOf)
|
||||
assert.EqualValues(t, 100_000_000, m.Amount)
|
||||
assert.EqualValues(t, 60_000_000, m.RealizedCost, "within October, from EnakGame only")
|
||||
assert.EqualValues(t, 40_000_000, m.Remaining)
|
||||
assert.EqualValues(t, 60, m.UtilizationPercent)
|
||||
assert.EqualValues(t, 7, m.WindowDays)
|
||||
assert.EqualValues(t, 10, m.RemainingDays)
|
||||
assert.EqualValues(t, 5_500_000, m.DailyBurn)
|
||||
assert.EqualValues(t, 115_000_000, m.ForecastCost)
|
||||
assert.EqualValues(t, -15_000_000, m.ForecastRemaining)
|
||||
assert.Equal(t, constants.GameBudgetCritical, m.Status)
|
||||
assert.EqualValues(t, 100, m.CoinIssued)
|
||||
assert.Equal(t, models.GameBudgetExposure{Coins: 60, Points: 40}, m.Exposure, "followed through the exchange")
|
||||
|
||||
m, err = metrics.Metrics(ctx, e.orgA, event.ID)
|
||||
require.NoError(t, err)
|
||||
assert.EqualValues(t, 3_000_000, m.RealizedCost, "an event budget has no time bound")
|
||||
assert.Zero(t, m.RemainingDays, "the event is over")
|
||||
assert.EqualValues(t, 3_000_000, m.ForecastCost)
|
||||
assert.EqualValues(t, 30, m.UtilizationPercent)
|
||||
assert.Equal(t, constants.GameBudgetWarning, m.Status, "its own thresholds: 20 and 50")
|
||||
assert.Zero(t, m.CoinIssued)
|
||||
|
||||
_, err = metrics.Metrics(ctx, e.orgB, october.ID)
|
||||
assert.ErrorIs(t, err, repository.ErrGameBudgetNotFound)
|
||||
|
||||
// Redeeming the EnakPoint lowers the exposure; spending EnakCoin on a game does too.
|
||||
_, err = e.redeemVoucher(e.alice, voucher.ID, "metrics")
|
||||
require.NoError(t, err)
|
||||
m, err = metrics.Metrics(ctx, e.orgA, october.ID)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, models.GameBudgetExposure{Coins: 60, Points: 39}, m.Exposure)
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
package processor
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"math"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"apskel-pos-be/internal/constants"
|
||||
"apskel-pos-be/internal/entities"
|
||||
"apskel-pos-be/internal/models"
|
||||
"apskel-pos-be/internal/repository"
|
||||
)
|
||||
|
||||
// budgetForecastWindowDays is how many days of realized cost the forecast averages
|
||||
// (docs/rfc-enakgame.md §10).
|
||||
const budgetForecastWindowDays = 7
|
||||
|
||||
// GameBudgetMetricsProcessor computes how a budget stands (§10, PRD §8, §32), on read.
|
||||
//
|
||||
// Realized cost is what redeemed vouchers cost the budget: for a global budget, what
|
||||
// was recognized within its period; for an event budget, whenever it was recognized,
|
||||
// because the cost was born from that event's rewards. The forecast adds the average
|
||||
// daily cost of the last seven days, today included, for each day left.
|
||||
type GameBudgetMetricsProcessor struct {
|
||||
budgets repository.GameBudgetRepository
|
||||
metrics repository.GameBudgetMetricsRepository
|
||||
now func() time.Time
|
||||
}
|
||||
|
||||
func NewGameBudgetMetricsProcessor(budgets repository.GameBudgetRepository, metrics repository.GameBudgetMetricsRepository) *GameBudgetMetricsProcessor {
|
||||
return &GameBudgetMetricsProcessor{budgets: budgets, metrics: metrics, now: time.Now}
|
||||
}
|
||||
|
||||
// budgetMetricInputs is what the metrics are computed from.
|
||||
type budgetMetricInputs struct {
|
||||
Realized int64
|
||||
RealizedWindow int64
|
||||
WindowDays int64
|
||||
RemainingDays int64
|
||||
CoinIssued int64
|
||||
Coins, Points int64
|
||||
}
|
||||
|
||||
func (p *GameBudgetMetricsProcessor) Metrics(ctx context.Context, organizationID, budgetID uuid.UUID) (*models.GameBudgetMetrics, error) {
|
||||
budget, err := p.budgets.GetBudget(ctx, organizationID, budgetID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return p.metricsAt(ctx, budget, p.now())
|
||||
}
|
||||
|
||||
// metricsAt computes a budget's metrics as of now.
|
||||
func (p *GameBudgetMetricsProcessor) metricsAt(ctx context.Context, budget *entities.GameBudget, now time.Time) (*models.GameBudgetMetrics, error) {
|
||||
var err error
|
||||
today := civilDay(walletDay(now))
|
||||
start, end := civilDay(budget.PeriodStart), civilDay(budget.PeriodEnd)
|
||||
|
||||
var in budgetMetricInputs
|
||||
var from, to *time.Time
|
||||
if budget.Scope == constants.GameBudgetScopeGlobal {
|
||||
f, t := jakartaMidnight(start), jakartaMidnight(end.AddDate(0, 0, 1))
|
||||
from, to = &f, &t
|
||||
}
|
||||
if in.Realized, err = p.metrics.RealizedCost(ctx, budget.ID, from, to); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !today.Before(start) {
|
||||
windowStart := today.AddDate(0, 0, 1-budgetForecastWindowDays)
|
||||
if windowStart.Before(start) {
|
||||
windowStart = start
|
||||
}
|
||||
in.WindowDays = daysBetween(windowStart, today) + 1
|
||||
w := jakartaMidnight(windowStart)
|
||||
if in.RealizedWindow, err = p.metrics.RealizedCost(ctx, budget.ID, &w, to); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if in.RemainingDays = daysBetween(today, end); in.RemainingDays < 0 {
|
||||
in.RemainingDays = 0
|
||||
}
|
||||
}
|
||||
if in.CoinIssued, err = p.metrics.CoinIssued(ctx, budget.ID); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if in.Coins, in.Points, err = p.metrics.Exposure(ctx, budget.ID, now); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
m := budgetMetrics(budget, today, in)
|
||||
return &m, nil
|
||||
}
|
||||
|
||||
// budgetMetrics computes the metrics of a budget on a day from what was read.
|
||||
func budgetMetrics(b *entities.GameBudget, today time.Time, in budgetMetricInputs) models.GameBudgetMetrics {
|
||||
m := models.GameBudgetMetrics{
|
||||
BudgetID: b.ID, Scope: b.Scope, Amount: b.Amount,
|
||||
PeriodStart: b.PeriodStart.Format("2006-01-02"), PeriodEnd: b.PeriodEnd.Format("2006-01-02"), AsOf: today.Format("2006-01-02"),
|
||||
RealizedCost: in.Realized, Remaining: b.Amount - in.Realized,
|
||||
WindowDays: in.WindowDays, RemainingDays: in.RemainingDays, ForecastCost: in.Realized,
|
||||
CoinIssued: in.CoinIssued, Exposure: models.GameBudgetExposure{Coins: in.Coins, Points: in.Points},
|
||||
}
|
||||
if in.WindowDays > 0 {
|
||||
m.DailyBurn = in.RealizedWindow / in.WindowDays
|
||||
// Computed from the window's total, not the rounded daily average, so whole
|
||||
// rupiah are not lost day after day.
|
||||
m.ForecastCost += in.RealizedWindow * in.RemainingDays / in.WindowDays
|
||||
}
|
||||
m.ForecastRemaining = b.Amount - m.ForecastCost
|
||||
m.UtilizationPercent = percentOf(m.RealizedCost, b.Amount)
|
||||
m.ForecastUtilizationPercent = percentOf(m.ForecastCost, b.Amount)
|
||||
|
||||
warning, critical := constants.GameBudgetWarningDefault, constants.GameBudgetCriticalDefault
|
||||
var set models.GameBudgetThresholds
|
||||
if len(b.Thresholds) > 0 {
|
||||
_ = json.Unmarshal(b.Thresholds, &set)
|
||||
}
|
||||
if set.Warning != nil {
|
||||
warning = *set.Warning
|
||||
}
|
||||
if set.Critical != nil {
|
||||
critical = *set.Critical
|
||||
}
|
||||
m.Thresholds = models.GameBudgetThresholds{Warning: &warning, Critical: &critical}
|
||||
|
||||
highest := math.Max(m.UtilizationPercent, m.ForecastUtilizationPercent)
|
||||
switch {
|
||||
case m.RealizedCost >= b.Amount:
|
||||
m.Status = constants.GameBudgetExhausted
|
||||
case m.ForecastCost > b.Amount, highest >= float64(critical):
|
||||
m.Status = constants.GameBudgetCritical
|
||||
case highest >= float64(warning):
|
||||
m.Status = constants.GameBudgetWarning
|
||||
default:
|
||||
m.Status = constants.GameBudgetHealthy
|
||||
}
|
||||
return m
|
||||
}
|
||||
|
||||
// percentOf is part as a percent of whole, with two decimals.
|
||||
func percentOf(part, whole int64) float64 {
|
||||
if whole <= 0 {
|
||||
return 0
|
||||
}
|
||||
return math.Round(float64(part)*10000/float64(whole)) / 100
|
||||
}
|
||||
|
||||
// civilDay is the calendar date of t, as midnight UTC, for counting days.
|
||||
func civilDay(t time.Time) time.Time {
|
||||
return time.Date(t.Year(), t.Month(), t.Day(), 0, 0, 0, 0, time.UTC)
|
||||
}
|
||||
|
||||
// jakartaMidnight is when a calendar date starts in Asia/Jakarta.
|
||||
func jakartaMidnight(day time.Time) time.Time {
|
||||
return time.Date(day.Year(), day.Month(), day.Day(), 0, 0, 0, 0, walletDisplayLocation)
|
||||
}
|
||||
|
||||
func daysBetween(a, b time.Time) int64 {
|
||||
return int64(math.Round(b.Sub(a).Hours() / 24))
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
package processor
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
|
||||
"apskel-pos-be/internal/constants"
|
||||
"apskel-pos-be/internal/entities"
|
||||
)
|
||||
|
||||
func TestBudgetMetrics(t *testing.T) {
|
||||
october := &entities.GameBudget{
|
||||
Scope: constants.GameBudgetScopeGlobal, Amount: 100_000_000,
|
||||
PeriodStart: time.Date(2026, 10, 1, 0, 0, 0, 0, time.UTC), PeriodEnd: time.Date(2026, 10, 31, 0, 0, 0, 0, time.UTC),
|
||||
}
|
||||
today := time.Date(2026, 10, 21, 0, 0, 0, 0, time.UTC)
|
||||
|
||||
// PRD §30: Rp100M, Rp60M realized, 10 days left, burning Rp5,5M a day → Rp115M.
|
||||
m := budgetMetrics(october, today, budgetMetricInputs{Realized: 60_000_000, RealizedWindow: 38_500_000, WindowDays: 7, RemainingDays: 10})
|
||||
assert.EqualValues(t, 40_000_000, m.Remaining)
|
||||
assert.EqualValues(t, 60, m.UtilizationPercent)
|
||||
assert.EqualValues(t, 5_500_000, m.DailyBurn)
|
||||
assert.EqualValues(t, 115_000_000, m.ForecastCost)
|
||||
assert.EqualValues(t, -15_000_000, m.ForecastRemaining)
|
||||
assert.EqualValues(t, 115, m.ForecastUtilizationPercent)
|
||||
assert.Equal(t, constants.GameBudgetCritical, m.Status, "the forecast passes the budget")
|
||||
assert.EqualValues(t, 70, *m.Thresholds.Warning, "the default when the budget sets none")
|
||||
assert.EqualValues(t, 90, *m.Thresholds.Critical)
|
||||
assert.Equal(t, "2026-10-21", m.AsOf)
|
||||
|
||||
for name, tc := range map[string]struct {
|
||||
thresholds string
|
||||
realized, burn int64
|
||||
want string
|
||||
}{
|
||||
"quiet": {"", 10_000_000, 0, constants.GameBudgetHealthy},
|
||||
"forecast at warning": {"", 30_000_000, 4_000_000, constants.GameBudgetWarning}, // 30 + 4 × 10 = 70%
|
||||
"realized at critical": {"", 90_000_000, 0, constants.GameBudgetCritical}, // 90%
|
||||
"spent": {"", 100_000_000, 0, constants.GameBudgetExhausted}, // 100%
|
||||
"over": {"", 120_000_000, 0, constants.GameBudgetExhausted}, // 120%
|
||||
"own thresholds": {`{"warning": 20, "critical": 50}`, 25_000_000, 0, constants.GameBudgetWarning},
|
||||
"own critical only": {`{"critical": 30}`, 31_000_000, 0, constants.GameBudgetCritical},
|
||||
"own warning above default": {`{"warning": 80}`, 75_000_000, 0, constants.GameBudgetHealthy},
|
||||
} {
|
||||
b := *october
|
||||
b.Thresholds = entities.JSONDocument(tc.thresholds)
|
||||
m := budgetMetrics(&b, today, budgetMetricInputs{Realized: tc.realized, RealizedWindow: tc.burn * 7, WindowDays: 7, RemainingDays: 10})
|
||||
assert.Equal(t, tc.want, m.Status, name)
|
||||
}
|
||||
|
||||
// Not started yet: nothing to average, the forecast is what is realized.
|
||||
m = budgetMetrics(october, time.Date(2026, 9, 20, 0, 0, 0, 0, time.UTC), budgetMetricInputs{})
|
||||
assert.Zero(t, m.ForecastCost)
|
||||
assert.Equal(t, constants.GameBudgetHealthy, m.Status)
|
||||
// A third of a rupiah per day is not lost: 10 over 3 days, 3 days left → 10 more.
|
||||
m = budgetMetrics(october, today, budgetMetricInputs{Realized: 10, RealizedWindow: 10, WindowDays: 3, RemainingDays: 3})
|
||||
assert.EqualValues(t, 20, m.ForecastCost)
|
||||
assert.EqualValues(t, 3, m.DailyBurn)
|
||||
}
|
||||
@@ -0,0 +1,272 @@
|
||||
package processor
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"apskel-pos-be/internal/constants"
|
||||
"apskel-pos-be/internal/entities"
|
||||
"apskel-pos-be/internal/models"
|
||||
"apskel-pos-be/internal/repository"
|
||||
)
|
||||
|
||||
// GameBudgetProcessor manages what an organization may spend on EnakGame rewards
|
||||
// (docs/rfc-enakgame.md §5.6, §12). Global budgets of an organization never share a
|
||||
// day; every change is audited in its transaction (§13).
|
||||
type GameBudgetProcessor struct {
|
||||
budgets repository.GameBudgetRepository
|
||||
audit *AuditLogger
|
||||
tx TxRunner
|
||||
now func() time.Time
|
||||
}
|
||||
|
||||
// gameBudgetMaxMultiplierLimit is the highest max_multiplier_percent a budget may set.
|
||||
const gameBudgetMaxMultiplierLimit = 1000
|
||||
|
||||
func NewGameBudgetProcessor(budgets repository.GameBudgetRepository, audit *AuditLogger, tx TxRunner) *GameBudgetProcessor {
|
||||
return &GameBudgetProcessor{budgets: budgets, audit: audit, tx: tx, now: time.Now}
|
||||
}
|
||||
|
||||
// GameBudgetInputFrom is a budget's current values as an input, for a change that only
|
||||
// sends the fields it changes.
|
||||
func GameBudgetInputFrom(b *models.GameBudget) models.GameBudgetInput {
|
||||
return models.GameBudgetInput{
|
||||
Scope: b.Scope, Name: b.Name, PeriodStart: b.PeriodStart, PeriodEnd: b.PeriodEnd,
|
||||
Amount: b.Amount, Thresholds: b.Thresholds,
|
||||
}
|
||||
}
|
||||
|
||||
func (p *GameBudgetProcessor) record(ctx context.Context, organizationID, actor, id uuid.UUID, action string, before, after any) error {
|
||||
return p.audit.Record(ctx, AuditEntry{
|
||||
OrganizationID: organizationID, ActorType: constants.AuditActorUser, ActorID: &actor,
|
||||
EntityType: constants.AuditEntityGameBudget, EntityID: id, Action: action,
|
||||
Before: before, After: after, Source: constants.AuditSourceAdminAPI,
|
||||
})
|
||||
}
|
||||
|
||||
func (p *GameBudgetProcessor) CreateBudget(ctx context.Context, organizationID, actor uuid.UUID, in models.GameBudgetInput) (*models.GameBudget, error) {
|
||||
budget, err := gameBudgetFromInput(in)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
budget.OrganizationID, budget.CreatedBy = organizationID, actor
|
||||
err = p.tx.WithTransaction(ctx, func(ctx context.Context) error {
|
||||
if err := p.checkGlobalPeriod(ctx, budget, nil); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := p.budgets.CreateBudget(ctx, budget); err != nil {
|
||||
return err
|
||||
}
|
||||
return p.record(ctx, organizationID, actor, budget.ID, "CREATED", nil, gameBudgetModel(budget))
|
||||
})
|
||||
if err != nil {
|
||||
return nil, gameBudgetError(err)
|
||||
}
|
||||
return gameBudgetModel(budget), nil
|
||||
}
|
||||
|
||||
func (p *GameBudgetProcessor) GetBudget(ctx context.Context, organizationID, id uuid.UUID) (*models.GameBudget, error) {
|
||||
budget, err := p.budgets.GetBudget(ctx, organizationID, id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return gameBudgetModel(budget), nil
|
||||
}
|
||||
|
||||
func (p *GameBudgetProcessor) ListBudgets(ctx context.Context, organizationID uuid.UUID, q models.GameBudgetListQuery) (*models.PaginatedResponse[models.GameBudget], error) {
|
||||
page, limit := enakGamePage(q.Page, q.Limit)
|
||||
scope := strings.ToUpper(strings.TrimSpace(q.Scope))
|
||||
if scope != "" && scope != constants.GameBudgetScopeGlobal && scope != constants.GameBudgetScopeEvent {
|
||||
return nil, enakGameRejected("scope must be GLOBAL or EVENT")
|
||||
}
|
||||
budgets, total, err := p.budgets.ListBudgets(ctx, repository.GameBudgetFilter{
|
||||
OrganizationID: organizationID, Scope: scope, Offset: (page - 1) * limit, Limit: limit,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items := make([]models.GameBudget, 0, len(budgets))
|
||||
for i := range budgets {
|
||||
items = append(items, *gameBudgetModel(&budgets[i]))
|
||||
}
|
||||
return &models.PaginatedResponse[models.GameBudget]{Data: items, Pagination: enakGamePagination(page, limit, total)}, nil
|
||||
}
|
||||
|
||||
// UpdateBudget changes a budget's name, period, amount and thresholds. Its scope stays.
|
||||
func (p *GameBudgetProcessor) UpdateBudget(ctx context.Context, organizationID, actor, id uuid.UUID, in models.GameBudgetInput) (*models.GameBudget, error) {
|
||||
next, err := gameBudgetFromInput(in)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var after *models.GameBudget
|
||||
err = p.tx.WithTransaction(ctx, func(ctx context.Context) error {
|
||||
current, err := p.budgets.GetBudget(ctx, organizationID, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if next.Scope != current.Scope {
|
||||
return enakGameRejected("the scope of a budget cannot change")
|
||||
}
|
||||
next.ID, next.OrganizationID, next.CreatedBy, next.CreatedAt = current.ID, current.OrganizationID, current.CreatedBy, current.CreatedAt
|
||||
if err := p.checkGlobalPeriod(ctx, next, &id); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := p.budgets.UpdateBudget(ctx, next); err != nil {
|
||||
return err
|
||||
}
|
||||
saved, err := p.budgets.GetBudget(ctx, organizationID, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
after = gameBudgetModel(saved)
|
||||
return p.record(ctx, organizationID, actor, id, "UPDATED", gameBudgetModel(current), after)
|
||||
})
|
||||
if err != nil {
|
||||
return nil, gameBudgetError(err)
|
||||
}
|
||||
return after, nil
|
||||
}
|
||||
|
||||
// DeleteBudget removes a budget that no reward or event points at.
|
||||
func (p *GameBudgetProcessor) DeleteBudget(ctx context.Context, organizationID, actor, id uuid.UUID) error {
|
||||
err := p.tx.WithTransaction(ctx, func(ctx context.Context) error {
|
||||
current, err := p.budgets.GetBudget(ctx, organizationID, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := p.budgets.DeleteBudget(ctx, organizationID, id); err != nil {
|
||||
return err
|
||||
}
|
||||
return p.record(ctx, organizationID, actor, id, "DELETED", gameBudgetModel(current), nil)
|
||||
})
|
||||
return gameBudgetError(err)
|
||||
}
|
||||
|
||||
// CreateNextPeriods gives each global budget running today its successor for the
|
||||
// following month, when there is none yet (§12). Running it again creates nothing
|
||||
// more. It returns how many budgets it created.
|
||||
func (p *GameBudgetProcessor) CreateNextPeriods(ctx context.Context) (int, error) {
|
||||
var created []entities.GameBudget
|
||||
err := p.tx.WithTransaction(ctx, func(ctx context.Context) error {
|
||||
var err error
|
||||
created, err = p.budgets.CreateNextGlobalBudgets(ctx, walletDay(p.now()))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for i := range created {
|
||||
err := p.audit.Record(ctx, AuditEntry{
|
||||
OrganizationID: created[i].OrganizationID, ActorType: constants.AuditActorSystem,
|
||||
EntityType: constants.AuditEntityGameBudget, EntityID: created[i].ID, Action: "CREATED",
|
||||
After: gameBudgetModel(&created[i]), Source: constants.AuditSourceBudgetPeriodJob,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return len(created), nil
|
||||
}
|
||||
|
||||
// checkGlobalPeriod refuses a global budget sharing a day with another of the
|
||||
// organization. The lock makes two saves at once see each other.
|
||||
func (p *GameBudgetProcessor) checkGlobalPeriod(ctx context.Context, b *entities.GameBudget, except *uuid.UUID) error {
|
||||
if b.Scope != constants.GameBudgetScopeGlobal {
|
||||
return nil
|
||||
}
|
||||
if err := p.budgets.LockGlobalBudgets(ctx, b.OrganizationID); err != nil {
|
||||
return err
|
||||
}
|
||||
overlaps, err := p.budgets.GlobalBudgetOverlaps(ctx, b.OrganizationID, b.PeriodStart, b.PeriodEnd, except)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if overlaps {
|
||||
return enakGameRejected("another global budget already covers part of this period")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func gameBudgetError(err error) error {
|
||||
switch {
|
||||
case errors.Is(err, repository.ErrGameBudgetPeriodTaken):
|
||||
return enakGameRejected("another global budget already starts on that day")
|
||||
case errors.Is(err, repository.ErrGameBudgetInUse):
|
||||
return enakGameRejected("rewards or events use this budget, so it cannot be deleted")
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func gameBudgetFromInput(in models.GameBudgetInput) (*entities.GameBudget, error) {
|
||||
scope := strings.ToUpper(strings.TrimSpace(in.Scope))
|
||||
name := strings.TrimSpace(in.Name)
|
||||
if scope != constants.GameBudgetScopeGlobal && scope != constants.GameBudgetScopeEvent {
|
||||
return nil, enakGameRejected("scope must be GLOBAL or EVENT")
|
||||
}
|
||||
if name == "" || len(name) > 255 {
|
||||
return nil, enakGameRejected("name is required, at most 255 characters")
|
||||
}
|
||||
start, err := time.Parse("2006-01-02", strings.TrimSpace(in.PeriodStart))
|
||||
if err != nil {
|
||||
return nil, enakGameRejected("period_start must be a date like 2026-10-01")
|
||||
}
|
||||
end, err := time.Parse("2006-01-02", strings.TrimSpace(in.PeriodEnd))
|
||||
if err != nil {
|
||||
return nil, enakGameRejected("period_end must be a date like 2026-10-31")
|
||||
}
|
||||
if end.Before(start) {
|
||||
return nil, enakGameRejected("period_end cannot be before period_start")
|
||||
}
|
||||
if in.Amount <= 0 {
|
||||
return nil, enakGameRejected("amount must be more than 0")
|
||||
}
|
||||
t := in.Thresholds
|
||||
for field, v := range map[string]*int64{"warning": t.Warning, "critical": t.Critical} {
|
||||
if v != nil && (*v < 0 || *v > 100) {
|
||||
return nil, enakGameRejected("thresholds.%s must be between 0 and 100", field)
|
||||
}
|
||||
}
|
||||
if t.Warning != nil && t.Critical != nil && *t.Warning > *t.Critical {
|
||||
return nil, enakGameRejected("thresholds.warning cannot be above thresholds.critical")
|
||||
}
|
||||
switch {
|
||||
case t.MaxStepPercent != nil && (*t.MaxStepPercent < 1 || *t.MaxStepPercent > 50):
|
||||
return nil, enakGameRejected("thresholds.max_step_percent must be between 1 and 50")
|
||||
case t.MinMultiplierPercent != nil && (*t.MinMultiplierPercent < 1 || *t.MinMultiplierPercent > 100):
|
||||
return nil, enakGameRejected("thresholds.min_multiplier_percent must be between 1 and 100")
|
||||
case t.MaxMultiplierPercent != nil && (*t.MaxMultiplierPercent < 100 || *t.MaxMultiplierPercent > gameBudgetMaxMultiplierLimit):
|
||||
// NUMERIC(6,4) on game_reward_configs.multiplier holds far more; this keeps a
|
||||
// typo from multiplying rewards a hundredfold.
|
||||
return nil, enakGameRejected("thresholds.max_multiplier_percent must be between 100 and %d", gameBudgetMaxMultiplierLimit)
|
||||
case t.CooldownDays != nil && (*t.CooldownDays < 0 || *t.CooldownDays > 90):
|
||||
return nil, enakGameRejected("thresholds.cooldown_days must be between 0 and 90")
|
||||
}
|
||||
thresholds, err := json.Marshal(t)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &entities.GameBudget{
|
||||
Scope: scope, Name: name, PeriodStart: start, PeriodEnd: end, Amount: in.Amount,
|
||||
Thresholds: entities.JSONDocument(thresholds),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func gameBudgetModel(b *entities.GameBudget) *models.GameBudget {
|
||||
m := &models.GameBudget{
|
||||
ID: b.ID, Scope: b.Scope, Name: b.Name,
|
||||
PeriodStart: b.PeriodStart.Format("2006-01-02"), PeriodEnd: b.PeriodEnd.Format("2006-01-02"),
|
||||
Amount: b.Amount, CreatedBy: b.CreatedBy, CreatedAt: b.CreatedAt, UpdatedAt: b.UpdatedAt,
|
||||
}
|
||||
if len(b.Thresholds) > 0 {
|
||||
_ = json.Unmarshal(b.Thresholds, &m.Thresholds)
|
||||
}
|
||||
return m
|
||||
}
|
||||
@@ -0,0 +1,289 @@
|
||||
package processor
|
||||
|
||||
import (
|
||||
"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/entities"
|
||||
"apskel-pos-be/internal/models"
|
||||
"apskel-pos-be/internal/repository"
|
||||
)
|
||||
|
||||
// EnakGame events against Postgres (docs/rfc-enakgame.md §5.5, §7.2 step 7). Needs
|
||||
// TEST_DATABASE_URL; see internal/repository/wallet_repository_test.go.
|
||||
|
||||
func (e *enakGameEnv) eventBudget(org uuid.UUID, name string) *models.GameBudget {
|
||||
e.t.Helper()
|
||||
b, err := e.budgets.CreateBudget(e.ctx(), org, e.manager, models.GameBudgetInput{
|
||||
Scope: "EVENT", Name: name, PeriodStart: "2026-01-01", PeriodEnd: "2026-12-31", Amount: 10_000_000,
|
||||
})
|
||||
require.NoError(e.t, err)
|
||||
return b
|
||||
}
|
||||
|
||||
func (e *enakGameEnv) event(in models.GameEventInput) *models.GameEvent {
|
||||
e.t.Helper()
|
||||
if in.Name == "" {
|
||||
in.Name = "Event"
|
||||
}
|
||||
if in.Slug == "" {
|
||||
in.Slug = "event-" + uuid.NewString()[:8]
|
||||
}
|
||||
if in.StartAt.IsZero() {
|
||||
in.StartAt, in.EndAt = e.now.Add(-time.Hour), e.now.Add(24*time.Hour)
|
||||
}
|
||||
if in.Status == "" {
|
||||
in.Status = constants.GameEventStatusActive
|
||||
}
|
||||
ev, err := e.events.CreateEvent(e.ctx(), e.orgA, e.manager, in)
|
||||
require.NoError(e.t, err)
|
||||
return ev
|
||||
}
|
||||
|
||||
// EG-702
|
||||
func TestGameEventAdmin(t *testing.T) {
|
||||
e := newEnakGameEnv(t)
|
||||
ctx := e.ctx()
|
||||
game := e.playableGame(e.orgA, "runner", 1)
|
||||
theirGame := e.playableGame(e.orgB, "theirs", 1)
|
||||
budget := e.eventBudget(e.orgA, "Ramadan")
|
||||
theirBudget := e.eventBudget(e.orgB, "Theirs")
|
||||
var global string
|
||||
require.NoError(t, e.db.Raw(`SELECT id::text FROM game_budgets WHERE organization_id = ? AND scope = 'GLOBAL'`, e.orgA).Scan(&global).Error)
|
||||
valid := func() models.GameEventInput {
|
||||
return models.GameEventInput{Name: "Ramadan", Slug: "ramadan", StartAt: e.now, EndAt: e.now.Add(time.Hour),
|
||||
Multiplier: ptr(2.0), BudgetID: budget.ID, GameIDs: []uuid.UUID{game.ID}}
|
||||
}
|
||||
|
||||
for name, mutate := range map[string]func(*models.GameEventInput){
|
||||
"global budget": func(in *models.GameEventInput) { in.BudgetID = uuid.MustParse(global) },
|
||||
"another org's budget": func(in *models.GameEventInput) { in.BudgetID = theirBudget.ID },
|
||||
"another org's game": func(in *models.GameEventInput) { in.GameIDs = []uuid.UUID{theirGame.ID} },
|
||||
"no games": func(in *models.GameEventInput) { in.GameIDs = nil },
|
||||
"ends before start": func(in *models.GameEventInput) { in.EndAt = in.StartAt },
|
||||
"nothing to add": func(in *models.GameEventInput) { in.Multiplier = ptr(1.0) },
|
||||
"multiplier below 1": func(in *models.GameEventInput) { in.Multiplier = ptr(0.5) },
|
||||
"three decimals": func(in *models.GameEventInput) { in.Multiplier = ptr(1.125) },
|
||||
"zero bonus": func(in *models.GameEventInput) { in.Bonus = ptr(int64(0)) },
|
||||
"unknown timezone": func(in *models.GameEventInput) { in.Timezone = "Mars/Olympus" },
|
||||
"ended on create": func(in *models.GameEventInput) { in.Status = "ENDED" },
|
||||
} {
|
||||
in := valid()
|
||||
mutate(&in)
|
||||
_, err := e.events.CreateEvent(ctx, e.orgA, e.manager, in)
|
||||
assert.ErrorIs(t, err, ErrEnakGameRejected, name)
|
||||
}
|
||||
|
||||
ev, err := e.events.CreateEvent(ctx, e.orgA, e.manager, valid())
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, constants.GameEventStatusDraft, ev.Status)
|
||||
assert.Equal(t, "Asia/Jakarta", ev.Timezone)
|
||||
assert.Equal(t, []uuid.UUID{game.ID}, ev.GameIDs)
|
||||
_, err = e.events.CreateEvent(ctx, e.orgA, e.manager, valid())
|
||||
assert.ErrorIs(t, err, ErrEnakGameRejected, "slug in use")
|
||||
_, err = e.events.GetEvent(ctx, e.orgB, ev.ID)
|
||||
assert.ErrorIs(t, err, repository.ErrGameEventNotFound)
|
||||
|
||||
in := GameEventInputFrom(ev)
|
||||
in.Bonus = ptr(int64(5))
|
||||
updated, err := e.events.UpdateEvent(ctx, e.orgA, e.manager, ev.ID, in)
|
||||
require.NoError(t, err)
|
||||
assert.EqualValues(t, 5, *updated.Bonus)
|
||||
assert.EqualValues(t, 2, *updated.Multiplier)
|
||||
|
||||
for _, step := range []struct {
|
||||
to string
|
||||
ok bool
|
||||
}{{"ENDED", false}, {"ACTIVE", true}, {"DRAFT", false}, {"ENDED", true}, {"ACTIVE", false}, {"CANCELLED", false}} {
|
||||
_, err := e.events.SetEventStatus(ctx, e.orgA, e.manager, ev.ID, models.GameEventStatusInput{Status: step.to})
|
||||
if step.ok {
|
||||
assert.NoError(t, err, step.to)
|
||||
} else {
|
||||
assert.ErrorIs(t, err, ErrEnakGameRejected, step.to)
|
||||
}
|
||||
}
|
||||
_, err = e.events.UpdateEvent(ctx, e.orgA, e.manager, ev.ID, in)
|
||||
assert.ErrorIs(t, err, ErrEnakGameRejected, "an ended event never changes")
|
||||
assert.Equal(t, []string{"CREATED", "UPDATED", "STATUS_CHANGED", "STATUS_CHANGED"}, e.auditActions(constants.AuditEntityGameEvent, ev.ID))
|
||||
|
||||
// A budget an event points at cannot be deleted.
|
||||
assert.ErrorIs(t, e.budgets.DeleteBudget(ctx, e.orgA, e.manager, budget.ID), ErrEnakGameRejected)
|
||||
}
|
||||
|
||||
// EG-703, EG-704
|
||||
func TestGameEvent_RewardsAndLimits(t *testing.T) {
|
||||
e := newEnakGameEnv(t)
|
||||
ctx := e.ctx()
|
||||
ten := e.gameWith("ten", entities.GameResultRules{}, constants.GameRewardTypeFixed, `{"amount": 10}`, 0)
|
||||
other := e.gameWith("other", entities.GameResultRules{}, constants.GameRewardTypeFixed, `{"amount": 10}`, 0)
|
||||
e.coins(e.alice, 100, nil)
|
||||
e.coins(e.bob, 100, nil)
|
||||
var global string
|
||||
require.NoError(t, e.db.Raw(`SELECT id::text FROM game_budgets WHERE organization_id = ? AND scope = 'GLOBAL'`, e.orgA).Scan(&global).Error)
|
||||
play := func(customer, gameID uuid.UUID) (*models.GameSessionCompletion, uuid.UUID) {
|
||||
t.Helper()
|
||||
s, err := e.sessions.Start(ctx, customer, gameID, uuid.NewString())
|
||||
require.NoError(t, err)
|
||||
out, err := e.sessions.Complete(ctx, customer, s.SessionID, models.GameSessionCompleteInput{})
|
||||
require.NoError(t, err)
|
||||
return out, s.SessionID
|
||||
}
|
||||
rewards := func(session uuid.UUID) map[string]int64 {
|
||||
t.Helper()
|
||||
var rows []struct {
|
||||
BudgetID string
|
||||
Amount int64
|
||||
Ledger int64
|
||||
}
|
||||
require.NoError(t, e.db.Raw(`SELECT r.budget_id::text AS budget_id, r.amount, t.amount AS ledger
|
||||
FROM game_session_rewards r JOIN wallet_transactions t ON t.id = r.wallet_transaction_id
|
||||
WHERE r.session_id = ? AND t.type = 'GAME_REWARD'`, session).Scan(&rows).Error)
|
||||
out := map[string]int64{}
|
||||
for _, row := range rows {
|
||||
assert.Equal(t, row.Amount, row.Ledger)
|
||||
out[row.BudgetID] = row.Amount
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// PRD §7: 10 Coin with Ramadan 2x is two GAME_REWARD rows, 10 from each budget.
|
||||
ramadanBudget := e.eventBudget(e.orgA, "Ramadan")
|
||||
ramadan := e.event(models.GameEventInput{Name: "Ramadan", Multiplier: ptr(2.0), BudgetID: ramadanBudget.ID, GameIDs: []uuid.UUID{ten.ID}, Priority: 10})
|
||||
out, id := play(e.alice, ten.ID)
|
||||
assert.EqualValues(t, 20, out.RewardTotal)
|
||||
assert.Equal(t, models.GameSessionRewardParts{Base: 10, Event: 10}, out.Reward)
|
||||
assert.Equal(t, map[string]int64{global: 10, ramadanBudget.ID.String(): 10}, rewards(id))
|
||||
|
||||
// The other game is not in the event.
|
||||
out, id = play(e.alice, other.ID)
|
||||
assert.EqualValues(t, 10, out.RewardTotal)
|
||||
assert.Equal(t, map[string]int64{global: 10}, rewards(id))
|
||||
|
||||
// Events that are not running change nothing: not started, over, a draft.
|
||||
later := e.eventBudget(e.orgA, "Later")
|
||||
e.event(models.GameEventInput{Bonus: ptr(int64(50)), BudgetID: later.ID, GameIDs: []uuid.UUID{other.ID}, StartAt: e.now.Add(time.Hour), EndAt: e.now.Add(2 * time.Hour)})
|
||||
e.event(models.GameEventInput{Bonus: ptr(int64(50)), BudgetID: later.ID, GameIDs: []uuid.UUID{other.ID}, StartAt: e.now.Add(-2 * time.Hour), EndAt: e.now.Add(-time.Minute)})
|
||||
e.event(models.GameEventInput{Bonus: ptr(int64(50)), BudgetID: later.ID, GameIDs: []uuid.UUID{other.ID}, Status: "DRAFT"})
|
||||
out, _ = play(e.alice, other.ID)
|
||||
assert.EqualValues(t, 10, out.RewardTotal)
|
||||
|
||||
// The customer list shows the event on its game only.
|
||||
games, err := e.sessions.ListGames(ctx, e.alice)
|
||||
require.NoError(t, err)
|
||||
for _, g := range games {
|
||||
if g.ID == ten.ID {
|
||||
require.Len(t, g.Events, 1)
|
||||
assert.Equal(t, "Ramadan", g.Events[0].Name)
|
||||
assert.EqualValues(t, 2, *g.Events[0].Multiplier)
|
||||
assert.Equal(t, ramadan.EndAt.Unix(), g.Events[0].EndAt.Unix())
|
||||
} else {
|
||||
assert.Empty(t, g.Events, g.Slug)
|
||||
}
|
||||
}
|
||||
|
||||
// A second event on the same game: its bonus is counted on its own; its limit over
|
||||
// the whole event cuts it, then a customer's daily limit within it.
|
||||
bonusBudget := e.eventBudget(e.orgA, "Bonus")
|
||||
bonus := e.event(models.GameEventInput{Name: "Bonus", Bonus: ptr(int64(5)), BudgetID: bonusBudget.ID, GameIDs: []uuid.UUID{ten.ID},
|
||||
RewardLimit: ptr(int64(12)), UserDailyLimit: ptr(int64(7))})
|
||||
out, id = play(e.bob, ten.ID)
|
||||
assert.EqualValues(t, 25, out.RewardTotal, "10 + 10 + 5")
|
||||
assert.Equal(t, map[string]int64{global: 10, ramadanBudget.ID.String(): 10, bonusBudget.ID.String(): 5}, rewards(id))
|
||||
out, _ = play(e.bob, ten.ID)
|
||||
assert.EqualValues(t, 22, out.RewardTotal, "Bob has 2 left of his 7 today")
|
||||
assert.Equal(t, []string{"EVENT_USER_DAILY"}, out.LimitedBy)
|
||||
out, _ = play(e.alice, ten.ID)
|
||||
assert.EqualValues(t, 25, out.RewardTotal, "Alice has her own 7")
|
||||
out, _ = play(e.alice, ten.ID)
|
||||
assert.EqualValues(t, 20, out.RewardTotal, "the event's 12 are given out: 5 + 2 + 5")
|
||||
assert.Equal(t, []string{"EVENT_LIMIT"}, out.LimitedBy)
|
||||
counter := repository.NewGameRewardCounterRepository(e.db)
|
||||
got, err := counter.Get(ctx, e.orgA, constants.GameRewardScopeEvent, bonus.ID, eventLifetimeDay)
|
||||
require.NoError(t, err)
|
||||
assert.EqualValues(t, 12, got)
|
||||
|
||||
// The daily limit of the customer cuts events before the base, and the event
|
||||
// counters give back what was cut.
|
||||
carla := e.newCustomer(e.orgA)
|
||||
e.coins(carla, 10, nil)
|
||||
settings := NewLoyaltySettingsProcessor(repository.NewLoyaltySettingsRepository(e.db), e.txm)
|
||||
t.Cleanup(func() {
|
||||
e.db.Exec(`DELETE FROM loyalty_setting_changes WHERE organization_id = ?`, e.orgA)
|
||||
e.db.Exec(`DELETE FROM organization_settings WHERE organization_id = ?`, e.orgA)
|
||||
})
|
||||
s, err := settings.Organization(ctx, e.orgA)
|
||||
require.NoError(t, err)
|
||||
s.EnakGame.UserDailyLimit = 14
|
||||
_, _, err = settings.UpdateOrganization(ctx, e.orgA, e.manager, *s)
|
||||
require.NoError(t, err)
|
||||
before, err := counter.Get(ctx, e.orgA, constants.GameRewardScopeEvent, ramadan.ID, eventLifetimeDay)
|
||||
require.NoError(t, err)
|
||||
out, id = play(carla, ten.ID)
|
||||
assert.EqualValues(t, 14, out.RewardTotal)
|
||||
assert.Equal(t, models.GameSessionRewardParts{Base: 10, Event: 4}, out.Reward, "the base first, the event gets what is left")
|
||||
assert.Equal(t, []string{"EVENT_LIMIT", "USER_DAILY"}, out.LimitedBy, "Bonus is used up; then her daily 14")
|
||||
assert.Equal(t, map[string]int64{global: 10, ramadanBudget.ID.String(): 4}, rewards(id))
|
||||
after, err := counter.Get(ctx, e.orgA, constants.GameRewardScopeEvent, ramadan.ID, eventLifetimeDay)
|
||||
require.NoError(t, err)
|
||||
assert.EqualValues(t, 4, after-before, "the event counter holds what was paid")
|
||||
|
||||
// D5: EnakPoint from the event's part of a reward cost the event's budget when
|
||||
// redeemed, the base part the global budget.
|
||||
s.EnakGame.UserDailyLimit = 0
|
||||
_, _, err = settings.UpdateOrganization(ctx, e.orgA, e.manager, *s)
|
||||
require.NoError(t, err)
|
||||
dina := e.newCustomer(e.orgA)
|
||||
e.coins(dina, 2, nil)
|
||||
_, id = play(dina, ten.ID)
|
||||
assert.Equal(t, map[string]int64{global: 10, ramadanBudget.ID.String(): 10}, rewards(id), "Bonus is used up")
|
||||
e.exchangeCoins(dina, 20)
|
||||
voucher := e.staticVoucher(5, 2_000, 20)
|
||||
res, err := e.redeemVoucher(dina, voucher.ID, "event-cost")
|
||||
require.NoError(t, err)
|
||||
r := ramadanBudget.ID.String()
|
||||
assert.ElementsMatch(t, []costRow{
|
||||
{BudgetID: &global, SourceType: "GAME_REWARD", Points: 10, Cost: 1_000},
|
||||
{BudgetID: &r, SourceType: "GAME_REWARD", Points: 10, Cost: 1_000},
|
||||
}, e.costs(res.ID))
|
||||
}
|
||||
|
||||
// Customers completing at once never take an event past its limit.
|
||||
func TestGameEvent_LimitHoldsUnderConcurrency(t *testing.T) {
|
||||
e := newEnakGameEnv(t)
|
||||
ctx := e.ctx()
|
||||
game := e.gameWith("rush", entities.GameResultRules{}, constants.GameRewardTypeFixed, `{"amount": 10}`, 0)
|
||||
budget := e.eventBudget(e.orgA, "Rush")
|
||||
e.event(models.GameEventInput{Bonus: ptr(int64(5)), BudgetID: budget.ID, GameIDs: []uuid.UUID{game.ID}, RewardLimit: ptr(int64(12))})
|
||||
|
||||
sessions := map[uuid.UUID]uuid.UUID{}
|
||||
for i := 0; i < 6; i++ {
|
||||
c := e.newCustomer(e.orgA)
|
||||
e.coins(c, 2, nil)
|
||||
s, err := e.sessions.Start(ctx, c, game.ID, "rush")
|
||||
require.NoError(t, err)
|
||||
sessions[c] = s.SessionID
|
||||
}
|
||||
var wg sync.WaitGroup
|
||||
begin := make(chan struct{})
|
||||
for c, id := range sessions {
|
||||
c, id := c, id
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
<-begin
|
||||
_, err := e.sessions.Complete(ctx, c, id, models.GameSessionCompleteInput{})
|
||||
assert.NoError(t, err)
|
||||
}()
|
||||
}
|
||||
close(begin)
|
||||
wg.Wait()
|
||||
assert.Equal(t, int64(12), e.count(`SELECT COALESCE(SUM(amount), 0) FROM game_session_rewards WHERE budget_id = ?`, budget.ID))
|
||||
assert.Equal(t, int64(60), e.count(`SELECT COALESCE(SUM(r.amount), 0) FROM game_session_rewards r JOIN game_budgets b ON b.id = r.budget_id
|
||||
WHERE b.scope = 'GLOBAL' AND r.session_id IN (SELECT id FROM game_sessions WHERE game_id = ?)`, game.ID), "every base paid")
|
||||
}
|
||||
@@ -0,0 +1,306 @@
|
||||
package processor
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"math"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"apskel-pos-be/internal/constants"
|
||||
"apskel-pos-be/internal/entities"
|
||||
"apskel-pos-be/internal/models"
|
||||
"apskel-pos-be/internal/repository"
|
||||
)
|
||||
|
||||
// gameEventMaxMultiplier is the largest multiplier NUMERIC(5,2) holds.
|
||||
const gameEventMaxMultiplier = 999.99
|
||||
|
||||
// GameEventProcessor manages an organization's EnakGame events
|
||||
// (docs/rfc-enakgame.md §5.5, §11). Every change is audited in its transaction.
|
||||
type GameEventProcessor struct {
|
||||
events repository.GameEventRepository
|
||||
games repository.EnakGameRepository
|
||||
budgets repository.GameBudgetRepository
|
||||
audit *AuditLogger
|
||||
tx TxRunner
|
||||
}
|
||||
|
||||
func NewGameEventProcessor(events repository.GameEventRepository, games repository.EnakGameRepository, budgets repository.GameBudgetRepository, audit *AuditLogger, tx TxRunner) *GameEventProcessor {
|
||||
return &GameEventProcessor{events: events, games: games, budgets: budgets, audit: audit, tx: tx}
|
||||
}
|
||||
|
||||
func (p *GameEventProcessor) record(ctx context.Context, organizationID, actor, id uuid.UUID, action string, before, after any, reason *string) error {
|
||||
return p.audit.Record(ctx, AuditEntry{
|
||||
OrganizationID: organizationID, ActorType: constants.AuditActorUser, ActorID: &actor,
|
||||
EntityType: constants.AuditEntityGameEvent, EntityID: id, Action: action,
|
||||
Before: before, After: after, Reason: reason, Source: constants.AuditSourceAdminAPI,
|
||||
})
|
||||
}
|
||||
|
||||
// GameEventInputFrom is an event's current values as an input, for a change that only
|
||||
// sends the fields it changes.
|
||||
func GameEventInputFrom(e *models.GameEvent) models.GameEventInput {
|
||||
return models.GameEventInput{
|
||||
Name: e.Name, Slug: e.Slug, Description: e.Description, BannerURL: e.BannerURL, StartAt: e.StartAt, EndAt: e.EndAt,
|
||||
Timezone: e.Timezone, Priority: e.Priority, Multiplier: e.Multiplier, Bonus: e.Bonus, BudgetID: e.BudgetID,
|
||||
RewardLimit: e.RewardLimit, UserDailyLimit: e.UserDailyLimit, GameIDs: e.GameIDs, Status: e.Status,
|
||||
}
|
||||
}
|
||||
|
||||
func (p *GameEventProcessor) CreateEvent(ctx context.Context, organizationID, actor uuid.UUID, in models.GameEventInput) (*models.GameEvent, error) {
|
||||
status := strings.ToUpper(strings.TrimSpace(in.Status))
|
||||
if status == "" {
|
||||
status = constants.GameEventStatusDraft
|
||||
}
|
||||
if status != constants.GameEventStatusDraft && status != constants.GameEventStatusActive {
|
||||
return nil, enakGameRejected("a new event must be DRAFT or ACTIVE")
|
||||
}
|
||||
event := &entities.GameEvent{OrganizationID: organizationID, Status: status}
|
||||
gameIDs, err := applyGameEventInput(event, in)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
err = p.tx.WithTransaction(ctx, func(ctx context.Context) error {
|
||||
if err := p.checkReferences(ctx, organizationID, event.BudgetID, gameIDs); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := p.events.CreateEvent(ctx, event, gameIDs); err != nil {
|
||||
return err
|
||||
}
|
||||
return p.record(ctx, organizationID, actor, event.ID, "CREATED", nil, gameEventModel(event, gameIDs), nil)
|
||||
})
|
||||
if err != nil {
|
||||
return nil, gameEventError(err)
|
||||
}
|
||||
return gameEventModel(event, gameIDs), nil
|
||||
}
|
||||
|
||||
func (p *GameEventProcessor) GetEvent(ctx context.Context, organizationID, id uuid.UUID) (*models.GameEvent, error) {
|
||||
event, err := p.events.GetEvent(ctx, organizationID, id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
games, err := p.events.EventGames(ctx, []uuid.UUID{id})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return gameEventModel(event, games[id]), nil
|
||||
}
|
||||
|
||||
func (p *GameEventProcessor) ListEvents(ctx context.Context, organizationID uuid.UUID, q models.GameEventListQuery) (*models.PaginatedResponse[models.GameEvent], error) {
|
||||
page, limit := enakGamePage(q.Page, q.Limit)
|
||||
var statuses []string
|
||||
if q.Status != "" {
|
||||
status := strings.ToUpper(strings.TrimSpace(q.Status))
|
||||
if !isGameEventStatus(status) {
|
||||
return nil, enakGameRejected("unknown status %q", q.Status)
|
||||
}
|
||||
statuses = []string{status}
|
||||
}
|
||||
events, total, err := p.events.ListEvents(ctx, repository.GameEventFilter{
|
||||
OrganizationID: organizationID, Statuses: statuses, Offset: (page - 1) * limit, Limit: limit,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
ids := make([]uuid.UUID, 0, len(events))
|
||||
for _, e := range events {
|
||||
ids = append(ids, e.ID)
|
||||
}
|
||||
games, err := p.events.EventGames(ctx, ids)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items := make([]models.GameEvent, 0, len(events))
|
||||
for i := range events {
|
||||
items = append(items, *gameEventModel(&events[i], games[events[i].ID]))
|
||||
}
|
||||
return &models.PaginatedResponse[models.GameEvent]{Data: items, Pagination: enakGamePagination(page, limit, total)}, nil
|
||||
}
|
||||
|
||||
// UpdateEvent changes everything but the status. An event that ended or was cancelled
|
||||
// never changes.
|
||||
func (p *GameEventProcessor) UpdateEvent(ctx context.Context, organizationID, actor, id uuid.UUID, in models.GameEventInput) (*models.GameEvent, error) {
|
||||
var after *models.GameEvent
|
||||
err := p.tx.WithTransaction(ctx, func(ctx context.Context) error {
|
||||
event, err := p.events.LockEvent(ctx, organizationID, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if event.Status == constants.GameEventStatusEnded || event.Status == constants.GameEventStatusCancelled {
|
||||
return enakGameRejected("an event that ended or was cancelled cannot change")
|
||||
}
|
||||
games, err := p.events.EventGames(ctx, []uuid.UUID{id})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
before := gameEventModel(event, games[id])
|
||||
gameIDs, err := applyGameEventInput(event, in)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := p.checkReferences(ctx, organizationID, event.BudgetID, gameIDs); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := p.events.UpdateEvent(ctx, event, gameIDs); err != nil {
|
||||
return err
|
||||
}
|
||||
saved, err := p.events.GetEvent(ctx, organizationID, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
after = gameEventModel(saved, gameIDs)
|
||||
return p.record(ctx, organizationID, actor, id, "UPDATED", before, after, nil)
|
||||
})
|
||||
if err != nil {
|
||||
return nil, gameEventError(err)
|
||||
}
|
||||
return after, nil
|
||||
}
|
||||
|
||||
// SetEventStatus moves an event: DRAFT to ACTIVE or CANCELLED, ACTIVE to ENDED or
|
||||
// CANCELLED. ENDED and CANCELLED are final.
|
||||
func (p *GameEventProcessor) SetEventStatus(ctx context.Context, organizationID, actor, id uuid.UUID, in models.GameEventStatusInput) (*models.GameEvent, error) {
|
||||
status := strings.ToUpper(strings.TrimSpace(in.Status))
|
||||
if !isGameEventStatus(status) {
|
||||
return nil, enakGameRejected("status must be DRAFT, ACTIVE, ENDED or CANCELLED")
|
||||
}
|
||||
if err := validateReason(in.Reason); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
err := p.tx.WithTransaction(ctx, func(ctx context.Context) error {
|
||||
event, err := p.events.LockEvent(ctx, organizationID, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if event.Status == status {
|
||||
return nil
|
||||
}
|
||||
allowed := map[string][]string{
|
||||
constants.GameEventStatusDraft: {constants.GameEventStatusActive, constants.GameEventStatusCancelled},
|
||||
constants.GameEventStatusActive: {constants.GameEventStatusEnded, constants.GameEventStatusCancelled},
|
||||
}[event.Status]
|
||||
if !containsString(allowed, status) {
|
||||
return enakGameRejected("an event cannot go from %s to %s", event.Status, status)
|
||||
}
|
||||
if err := p.events.SetEventStatus(ctx, organizationID, id, status); err != nil {
|
||||
return err
|
||||
}
|
||||
return p.record(ctx, organizationID, actor, id, "STATUS_CHANGED",
|
||||
map[string]string{"status": event.Status}, map[string]string{"status": status}, in.Reason)
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return p.GetEvent(ctx, organizationID, id)
|
||||
}
|
||||
|
||||
// checkReferences refuses a budget that is not an EVENT budget of the organization,
|
||||
// and games that are not the organization's or are archived.
|
||||
func (p *GameEventProcessor) checkReferences(ctx context.Context, organizationID, budgetID uuid.UUID, gameIDs []uuid.UUID) error {
|
||||
budget, err := p.budgets.GetBudget(ctx, organizationID, budgetID)
|
||||
if errors.Is(err, repository.ErrGameBudgetNotFound) {
|
||||
return enakGameRejected("budget_id is not a budget of this organization")
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if budget.Scope != constants.GameBudgetScopeEvent {
|
||||
return enakGameRejected("an event is paid by an EVENT budget, not a %s one", budget.Scope)
|
||||
}
|
||||
for _, gameID := range gameIDs {
|
||||
game, err := p.games.GetGame(ctx, organizationID, gameID)
|
||||
if errors.Is(err, repository.ErrEnakGameNotFound) {
|
||||
return enakGameRejected("game %s is not a game of this organization", gameID)
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if game.Status == constants.GameStatusArchived {
|
||||
return enakGameRejected("game %s is archived", gameID)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func gameEventError(err error) error {
|
||||
if errors.Is(err, repository.ErrGameEventSlugTaken) {
|
||||
return enakGameRejected("another event already uses this slug")
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func isGameEventStatus(s string) bool {
|
||||
switch s {
|
||||
case constants.GameEventStatusDraft, constants.GameEventStatusActive, constants.GameEventStatusEnded, constants.GameEventStatusCancelled:
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// applyGameEventInput checks an input and copies it onto the event, leaving its
|
||||
// organization and status alone. It returns the games, without repeats.
|
||||
func applyGameEventInput(e *entities.GameEvent, in models.GameEventInput) ([]uuid.UUID, error) {
|
||||
name, slug := strings.TrimSpace(in.Name), strings.TrimSpace(in.Slug)
|
||||
timezone := strings.TrimSpace(in.Timezone)
|
||||
if timezone == "" {
|
||||
timezone = "Asia/Jakarta"
|
||||
}
|
||||
switch {
|
||||
case name == "" || len(name) > 255:
|
||||
return nil, enakGameRejected("name is required, at most 255 characters")
|
||||
case len(slug) > 100 || !enakGameSlugPattern.MatchString(slug):
|
||||
return nil, enakGameRejected("slug must be lowercase letters, digits and single dashes, at most 100 characters")
|
||||
case in.StartAt.IsZero() || !in.EndAt.After(in.StartAt):
|
||||
return nil, enakGameRejected("start_at is required and end_at must be after it")
|
||||
case in.Multiplier != nil && (*in.Multiplier < 1 || *in.Multiplier > gameEventMaxMultiplier):
|
||||
return nil, enakGameRejected("multiplier must be between 1 and %g", gameEventMaxMultiplier)
|
||||
case in.Multiplier != nil && math.Abs(*in.Multiplier*100-math.Round(*in.Multiplier*100)) > 1e-9:
|
||||
return nil, enakGameRejected("multiplier must have at most two decimals")
|
||||
case in.Bonus != nil && *in.Bonus < 1:
|
||||
return nil, enakGameRejected("bonus must be at least 1")
|
||||
case (in.Multiplier == nil || *in.Multiplier == 1) && in.Bonus == nil:
|
||||
return nil, enakGameRejected("an event needs a multiplier above 1 or a bonus")
|
||||
case in.RewardLimit != nil && *in.RewardLimit < 1:
|
||||
return nil, enakGameRejected("reward_limit must be at least 1, or left out for no limit")
|
||||
case in.UserDailyLimit != nil && *in.UserDailyLimit < 1:
|
||||
return nil, enakGameRejected("user_daily_limit must be at least 1, or left out for no limit")
|
||||
case in.BudgetID == uuid.Nil:
|
||||
return nil, enakGameRejected("budget_id is required")
|
||||
case len(in.GameIDs) == 0:
|
||||
return nil, enakGameRejected("game_ids needs at least one game")
|
||||
case in.BannerURL != nil && len(*in.BannerURL) > 500:
|
||||
return nil, enakGameRejected("banner_url must be at most 500 characters")
|
||||
}
|
||||
if _, err := time.LoadLocation(timezone); err != nil || len(timezone) > 50 {
|
||||
return nil, enakGameRejected("timezone %q is not a known time zone", timezone)
|
||||
}
|
||||
seen := map[uuid.UUID]bool{}
|
||||
var gameIDs []uuid.UUID
|
||||
for _, id := range in.GameIDs {
|
||||
if !seen[id] {
|
||||
seen[id] = true
|
||||
gameIDs = append(gameIDs, id)
|
||||
}
|
||||
}
|
||||
e.Name, e.Slug, e.Description, e.BannerURL = name, slug, in.Description, in.BannerURL
|
||||
e.StartAt, e.EndAt, e.Timezone, e.Priority = in.StartAt, in.EndAt, timezone, in.Priority
|
||||
e.Multiplier, e.Bonus, e.BudgetID = in.Multiplier, in.Bonus, in.BudgetID
|
||||
e.RewardLimit, e.UserDailyLimit = in.RewardLimit, in.UserDailyLimit
|
||||
return gameIDs, nil
|
||||
}
|
||||
|
||||
func gameEventModel(e *entities.GameEvent, gameIDs []uuid.UUID) *models.GameEvent {
|
||||
if gameIDs == nil {
|
||||
gameIDs = []uuid.UUID{}
|
||||
}
|
||||
return &models.GameEvent{
|
||||
ID: e.ID, Name: e.Name, Slug: e.Slug, Description: e.Description, BannerURL: e.BannerURL, StartAt: e.StartAt,
|
||||
EndAt: e.EndAt, Timezone: e.Timezone, Status: e.Status, Priority: e.Priority, Multiplier: e.Multiplier,
|
||||
Bonus: e.Bonus, BudgetID: e.BudgetID, RewardLimit: e.RewardLimit, UserDailyLimit: e.UserDailyLimit,
|
||||
GameIDs: gameIDs, CreatedAt: e.CreatedAt, UpdatedAt: e.UpdatedAt,
|
||||
}
|
||||
}
|
||||
@@ -1,301 +0,0 @@
|
||||
package processor
|
||||
|
||||
import (
|
||||
"apskel-pos-be/internal/constants"
|
||||
"apskel-pos-be/internal/entities"
|
||||
"apskel-pos-be/internal/mappers"
|
||||
"apskel-pos-be/internal/models"
|
||||
"apskel-pos-be/internal/repository"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"math"
|
||||
"math/rand"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// ErrGamePlayRefused wraps every reason a customer cannot play right now: the game,
|
||||
// its prizes or their EnakCoin. The message says which.
|
||||
var ErrGamePlayRefused = errors.New("game cannot be played")
|
||||
|
||||
const (
|
||||
gameCoinCostKey = "coin_cost"
|
||||
defaultGameCoinCost = 1
|
||||
)
|
||||
|
||||
type gameReader interface {
|
||||
GetByID(ctx context.Context, id uuid.UUID) (*entities.Game, error)
|
||||
}
|
||||
|
||||
type gamePrizeStock interface {
|
||||
GetAvailablePrizes(ctx context.Context, gameID uuid.UUID) ([]entities.GamePrize, error)
|
||||
DecreaseStock(ctx context.Context, id uuid.UUID, amount int) error
|
||||
}
|
||||
|
||||
type GamePlayProcessor struct {
|
||||
gamePlayRepo repository.GamePlayRepository
|
||||
gameRepo gameReader
|
||||
gamePrizeRepo gamePrizeStock
|
||||
wallet *WalletProcessor
|
||||
spendable spendableReader
|
||||
tx TxRunner
|
||||
}
|
||||
|
||||
func NewGamePlayProcessor(
|
||||
gamePlayRepo repository.GamePlayRepository,
|
||||
gameRepo gameReader,
|
||||
gamePrizeRepo gamePrizeStock,
|
||||
wallet *WalletProcessor,
|
||||
spendable spendableReader,
|
||||
tx TxRunner,
|
||||
) *GamePlayProcessor {
|
||||
return &GamePlayProcessor{
|
||||
gamePlayRepo: gamePlayRepo,
|
||||
gameRepo: gameRepo,
|
||||
gamePrizeRepo: gamePrizeRepo,
|
||||
wallet: wallet,
|
||||
spendable: spendable,
|
||||
tx: tx,
|
||||
}
|
||||
}
|
||||
|
||||
// CreateGamePlay creates a new game play record
|
||||
func (p *GamePlayProcessor) CreateGamePlay(ctx context.Context, req *models.CreateGamePlayRequest) (*models.GamePlayResponse, error) {
|
||||
// Convert request to entity
|
||||
gamePlay := mappers.ToGamePlayEntity(req)
|
||||
|
||||
// Create game play
|
||||
err := p.gamePlayRepo.Create(ctx, gamePlay)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to create game play: %w", err)
|
||||
}
|
||||
|
||||
return mappers.ToGamePlayResponse(gamePlay), nil
|
||||
}
|
||||
|
||||
// GetGamePlay retrieves a game play by ID
|
||||
func (p *GamePlayProcessor) GetGamePlay(ctx context.Context, id uuid.UUID) (*models.GamePlayResponse, error) {
|
||||
gamePlay, err := p.gamePlayRepo.GetByID(ctx, id)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("game play not found: %w", err)
|
||||
}
|
||||
|
||||
return mappers.ToGamePlayResponse(gamePlay), nil
|
||||
}
|
||||
|
||||
// ListGamePlays retrieves game plays with pagination and filtering
|
||||
func (p *GamePlayProcessor) ListGamePlays(ctx context.Context, query *models.ListGamePlaysQuery) (*models.PaginatedResponse[models.GamePlayResponse], error) {
|
||||
// Set default values
|
||||
if query.Page <= 0 {
|
||||
query.Page = 1
|
||||
}
|
||||
if query.Limit <= 0 {
|
||||
query.Limit = 10
|
||||
}
|
||||
if query.Limit > 100 {
|
||||
query.Limit = 100
|
||||
}
|
||||
|
||||
offset := (query.Page - 1) * query.Limit
|
||||
|
||||
// Get game plays from repository
|
||||
gamePlays, total, err := p.gamePlayRepo.List(
|
||||
ctx,
|
||||
offset,
|
||||
query.Limit,
|
||||
query.Search,
|
||||
query.GameID,
|
||||
query.CustomerID,
|
||||
query.PrizeID,
|
||||
query.SortBy,
|
||||
query.SortOrder,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to list game plays: %w", err)
|
||||
}
|
||||
|
||||
// Convert to responses
|
||||
responses := mappers.ToGamePlayResponsesFromPointers(gamePlays)
|
||||
|
||||
// Calculate pagination info
|
||||
totalPages := int((total + int64(query.Limit) - 1) / int64(query.Limit))
|
||||
|
||||
return &models.PaginatedResponse[models.GamePlayResponse]{
|
||||
Data: responses,
|
||||
Pagination: models.Pagination{
|
||||
Page: query.Page,
|
||||
Limit: query.Limit,
|
||||
Total: total,
|
||||
TotalPages: totalPages,
|
||||
},
|
||||
}, nil
|
||||
}
|
||||
|
||||
// PlayGame plays a game for a customer, paid with EnakCoin (docs/prd-point-coin.md
|
||||
// F8, K1). Every kind of game spends the same EnakCoin, at the game's
|
||||
// metadata.coin_cost. Taking the EnakCoin (GAME_SPEND), recording the play and taking
|
||||
// the prize from stock happen in one transaction, so a play that cannot be completed,
|
||||
// for instance because the prize just ran out, takes nothing and records nothing.
|
||||
func (p *GamePlayProcessor) PlayGame(ctx context.Context, req *models.PlayGameRequest) (*models.PlayGameResponse, error) {
|
||||
refuse := func(format string, args ...any) error {
|
||||
return fmt.Errorf("%w: %s", ErrGamePlayRefused, fmt.Sprintf(format, args...))
|
||||
}
|
||||
game, err := p.gameRepo.GetByID(ctx, req.GameID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("game not found: %w", err)
|
||||
}
|
||||
if !game.IsActive {
|
||||
return nil, refuse("game is not active")
|
||||
}
|
||||
cost, err := gameCoinCost(game.Metadata)
|
||||
if err != nil {
|
||||
return nil, refuse("%s", err.Error())
|
||||
}
|
||||
|
||||
var gamePlay *entities.GamePlay
|
||||
var selectedPrize *models.GamePrizeResponse
|
||||
err = p.tx.WithTransaction(ctx, func(ctx context.Context) error {
|
||||
availablePrizes, err := p.gamePrizeRepo.GetAvailablePrizes(ctx, req.GameID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to get available prizes: %w", err)
|
||||
}
|
||||
if len(availablePrizes) == 0 {
|
||||
return refuse("no prizes available")
|
||||
}
|
||||
prizeResponses := make([]models.GamePrizeResponse, len(availablePrizes))
|
||||
for i, prize := range availablePrizes {
|
||||
prizeResponses[i] = *mappers.ToGamePrizeResponse(&prize)
|
||||
}
|
||||
selectedPrize = p.selectPrizeByWeight(prizeResponses)
|
||||
|
||||
// Random seed kept for audit.
|
||||
randomSeed := fmt.Sprintf("%d", time.Now().UnixNano())
|
||||
gamePlay = &entities.GamePlay{
|
||||
ID: uuid.New(),
|
||||
GameID: req.GameID,
|
||||
CustomerID: req.CustomerID,
|
||||
CoinsUsed: int(cost),
|
||||
RandomSeed: &randomSeed,
|
||||
}
|
||||
if selectedPrize != nil {
|
||||
gamePlay.PrizeID = &selectedPrize.ID
|
||||
}
|
||||
|
||||
// The EnakCoin go first: the debit locks the wallet, so plays by the same
|
||||
// customer at the same time queue up instead of spending the same balance.
|
||||
_, err = p.wallet.Debit(ctx, WalletDebitInput{WalletEntry: WalletEntry{
|
||||
CustomerID: req.CustomerID,
|
||||
Currency: constants.WalletCurrencyCoin,
|
||||
Type: constants.WalletTxTypeGameSpend,
|
||||
Amount: cost,
|
||||
ReferenceType: constants.WalletRefTypeGamePlay,
|
||||
ReferenceID: gamePlay.ID,
|
||||
Description: gameSpendDescription(game.Name, selectedPrize),
|
||||
Metadata: entities.Metadata{"game_id": game.ID.String(), "coin_cost": cost},
|
||||
}})
|
||||
if errors.Is(err, repository.ErrWalletInsufficientBalance) {
|
||||
return refuse("not enough EnakCoin: this game costs %d", cost)
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := p.gamePlayRepo.Create(ctx, gamePlay); err != nil {
|
||||
return err
|
||||
}
|
||||
if selectedPrize != nil {
|
||||
err := p.gamePrizeRepo.DecreaseStock(ctx, selectedPrize.ID, 1)
|
||||
if errors.Is(err, repository.ErrGamePrizeOutOfStock) {
|
||||
return refuse("the prize just ran out, please play again")
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
balances, err := p.spendable.SpendableBalances(ctx, req.CustomerID, time.Now())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &models.PlayGameResponse{
|
||||
GamePlay: *mappers.ToGamePlayResponse(gamePlay),
|
||||
PrizeWon: selectedPrize,
|
||||
CoinsRemaining: balances[constants.WalletCurrencyCoin],
|
||||
}, nil
|
||||
}
|
||||
|
||||
// gameCoinCost is what one play of a game costs, from games.metadata.coin_cost: a
|
||||
// whole number of EnakCoin, 1 when it is not set (F8).
|
||||
func gameCoinCost(metadata entities.Metadata) (int64, error) {
|
||||
raw, ok := metadata[gameCoinCostKey]
|
||||
if !ok || raw == nil {
|
||||
return defaultGameCoinCost, nil
|
||||
}
|
||||
var cost int64
|
||||
switch v := raw.(type) {
|
||||
case float64:
|
||||
if v != math.Trunc(v) {
|
||||
return 0, fmt.Errorf("the game's coin_cost %v is not a whole number", v)
|
||||
}
|
||||
cost = int64(v)
|
||||
case int:
|
||||
cost = int64(v)
|
||||
case int64:
|
||||
cost = v
|
||||
default:
|
||||
return 0, fmt.Errorf("the game's coin_cost %v is not a number", raw)
|
||||
}
|
||||
if cost < 1 {
|
||||
return 0, fmt.Errorf("the game's coin_cost must be at least 1, got %d", cost)
|
||||
}
|
||||
return cost, nil
|
||||
}
|
||||
|
||||
// gameSpendDescription is what the customer's history shows for a play, frozen when it
|
||||
// happens (§8.1): "Main Spin Wheel: dapat Voucher 10rb".
|
||||
func gameSpendDescription(gameName string, prize *models.GamePrizeResponse) string {
|
||||
description := "Main " + gameName
|
||||
if prize != nil {
|
||||
description += ": dapat " + prize.Name
|
||||
}
|
||||
return truncateRunes(description, walletDescriptionLimit)
|
||||
}
|
||||
|
||||
// selectPrizeByWeight selects a prize based on weight distribution
|
||||
func (p *GamePlayProcessor) selectPrizeByWeight(prizes []models.GamePrizeResponse) *models.GamePrizeResponse {
|
||||
if len(prizes) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
// Calculate total weight
|
||||
totalWeight := 0
|
||||
for _, prize := range prizes {
|
||||
totalWeight += prize.Weight
|
||||
}
|
||||
|
||||
if totalWeight == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
// Generate random number
|
||||
rand.Seed(time.Now().UnixNano())
|
||||
randomNumber := rand.Intn(totalWeight)
|
||||
|
||||
// Select prize based on cumulative weight
|
||||
currentWeight := 0
|
||||
for _, prize := range prizes {
|
||||
currentWeight += prize.Weight
|
||||
if randomNumber < currentWeight {
|
||||
return &prize
|
||||
}
|
||||
}
|
||||
|
||||
// Fallback to last prize
|
||||
return &prizes[len(prizes)-1]
|
||||
}
|
||||
@@ -1,69 +0,0 @@
|
||||
package processor
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"apskel-pos-be/internal/constants"
|
||||
"apskel-pos-be/internal/models"
|
||||
"apskel-pos-be/internal/repository"
|
||||
)
|
||||
|
||||
// Plays against Postgres, so the game repositories really join the transaction: a
|
||||
// refused play leaves no game_plays row and no GAME_SPEND.
|
||||
func TestPlayGame_AgainstPostgres(t *testing.T) {
|
||||
db, _, player, _ := walletMoveDB(t)
|
||||
gameID, prizeID := uuid.New(), uuid.New()
|
||||
require.NoError(t, db.Exec(`INSERT INTO games (id, name, type, metadata) VALUES (?, 'Raffle', 'RAFFLE', '{"coin_cost": 2}')`, gameID).Error)
|
||||
require.NoError(t, db.Exec(`INSERT INTO game_prizes (id, game_id, name, weight, stock) VALUES (?, ?, 'Tumbler', 1, 1)`, prizeID, gameID).Error)
|
||||
t.Cleanup(func() {
|
||||
db.Exec(`DELETE FROM wallet_lot_allocations WHERE transaction_id IN (SELECT id FROM wallet_transactions WHERE customer_id = ?)`, player)
|
||||
db.Exec(`DELETE FROM game_plays WHERE game_id = ?`, gameID)
|
||||
db.Exec(`DELETE FROM game_prizes WHERE game_id = ?`, gameID)
|
||||
db.Exec(`DELETE FROM games WHERE id = ?`, gameID)
|
||||
})
|
||||
|
||||
wallet := NewWalletProcessor(repository.NewWalletRepository(db))
|
||||
txm := repository.NewTxManager(db)
|
||||
require.NoError(t, txm.WithTransaction(context.Background(), func(ctx context.Context) error {
|
||||
in := earn(player, 3, nil)
|
||||
in.Currency = constants.WalletCurrencyCoin
|
||||
_, err := wallet.Credit(ctx, in)
|
||||
return err
|
||||
}))
|
||||
p := NewGamePlayProcessor(repository.NewGamePlayRepository(db), repository.NewGameRepository(db), repository.NewGamePrizeRepository(db),
|
||||
wallet, repository.NewWalletQueryRepository(db), txm)
|
||||
play := func() (*models.PlayGameResponse, error) {
|
||||
return p.PlayGame(context.Background(), &models.PlayGameRequest{GameID: gameID, CustomerID: player})
|
||||
}
|
||||
|
||||
res, err := play()
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, int64(1), res.CoinsRemaining)
|
||||
assert.Equal(t, 2, res.GamePlay.CoinsUsed)
|
||||
|
||||
var spend struct {
|
||||
ReferenceID uuid.UUID
|
||||
Amount int64
|
||||
}
|
||||
require.NoError(t, db.Raw(`SELECT reference_id, amount FROM wallet_transactions WHERE customer_id = ? AND type = 'GAME_SPEND'`, player).Scan(&spend).Error)
|
||||
assert.Equal(t, res.GamePlay.ID, spend.ReferenceID)
|
||||
assert.Equal(t, int64(-2), spend.Amount)
|
||||
|
||||
// The only prize is gone, then the EnakCoin are too short: neither play leaves a row.
|
||||
_, err = play()
|
||||
assert.ErrorIs(t, err, ErrGamePlayRefused)
|
||||
require.NoError(t, db.Exec(`UPDATE game_prizes SET stock = 5 WHERE id = ?`, prizeID).Error)
|
||||
_, err = play()
|
||||
assert.ErrorIs(t, err, ErrGamePlayRefused)
|
||||
|
||||
var plays, spends int64
|
||||
require.NoError(t, db.Raw(`SELECT COUNT(*) FROM game_plays WHERE game_id = ? AND coins_used = 2`, gameID).Scan(&plays).Error)
|
||||
require.NoError(t, db.Raw(`SELECT COUNT(*) FROM wallet_transactions WHERE customer_id = ? AND type = 'GAME_SPEND'`, player).Scan(&spends).Error)
|
||||
assert.Equal(t, int64(1), plays)
|
||||
assert.Equal(t, int64(1), spends)
|
||||
}
|
||||
@@ -1,245 +0,0 @@
|
||||
package processor
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"apskel-pos-be/internal/constants"
|
||||
"apskel-pos-be/internal/entities"
|
||||
"apskel-pos-be/internal/models"
|
||||
"apskel-pos-be/internal/repository"
|
||||
)
|
||||
|
||||
// snapshot saves everything the fake wallet holds and returns what puts it back, so
|
||||
// a test transaction can roll back like a real one.
|
||||
func (f *walletRepoFake) snapshot() func() {
|
||||
wallets := make(map[uuid.UUID]*entities.CustomerWallet, len(f.wallets))
|
||||
for id, w := range f.wallets {
|
||||
c := *w
|
||||
wallets[id] = &c
|
||||
}
|
||||
transactions := make([]*entities.WalletTransaction, len(f.transactions))
|
||||
for i, t := range f.transactions {
|
||||
c := *t
|
||||
transactions[i] = &c
|
||||
}
|
||||
lots := make([]*entities.WalletLot, len(f.lots))
|
||||
for i, l := range f.lots {
|
||||
c := *l
|
||||
lots[i] = &c
|
||||
}
|
||||
allocations := append([]entities.WalletLotAllocation(nil), f.allocations...)
|
||||
return func() {
|
||||
f.wallets, f.transactions, f.lots, f.allocations = wallets, transactions, lots, allocations
|
||||
}
|
||||
}
|
||||
|
||||
// rollbackTx runs fn in place and, when it fails, puts back what each save saved.
|
||||
type rollbackTx struct{ saves []func() func() }
|
||||
|
||||
func (r rollbackTx) WithTransaction(ctx context.Context, fn func(ctx context.Context) error) error {
|
||||
restores := make([]func(), 0, len(r.saves))
|
||||
for _, save := range r.saves {
|
||||
restores = append(restores, save())
|
||||
}
|
||||
err := fn(ctx)
|
||||
if err != nil {
|
||||
for _, restore := range restores {
|
||||
restore()
|
||||
}
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
type gameFake struct{ games map[uuid.UUID]*entities.Game }
|
||||
|
||||
func (f gameFake) GetByID(_ context.Context, id uuid.UUID) (*entities.Game, error) {
|
||||
g, ok := f.games[id]
|
||||
if !ok {
|
||||
return nil, errors.New("record not found")
|
||||
}
|
||||
return g, nil
|
||||
}
|
||||
|
||||
type prizeStockFake struct {
|
||||
prizes []entities.GamePrize
|
||||
stockErr error
|
||||
}
|
||||
|
||||
func (f *prizeStockFake) GetAvailablePrizes(_ context.Context, gameID uuid.UUID) ([]entities.GamePrize, error) {
|
||||
var out []entities.GamePrize
|
||||
for _, p := range f.prizes {
|
||||
if p.GameID == gameID && p.Stock > 0 {
|
||||
out = append(out, p)
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (f *prizeStockFake) DecreaseStock(_ context.Context, id uuid.UUID, amount int) error {
|
||||
if f.stockErr != nil {
|
||||
return f.stockErr
|
||||
}
|
||||
for i := range f.prizes {
|
||||
if f.prizes[i].ID == id {
|
||||
if f.prizes[i].Stock < amount {
|
||||
return repository.ErrGamePrizeOutOfStock
|
||||
}
|
||||
f.prizes[i].Stock -= amount
|
||||
return nil
|
||||
}
|
||||
}
|
||||
return repository.ErrGamePrizeOutOfStock
|
||||
}
|
||||
|
||||
func (f *prizeStockFake) snapshot() func() {
|
||||
prizes := append([]entities.GamePrize(nil), f.prizes...)
|
||||
return func() { f.prizes = prizes }
|
||||
}
|
||||
|
||||
// gamePlayRepoFake records plays; the other methods of the interface are not used.
|
||||
type gamePlayRepoFake struct {
|
||||
repository.GamePlayRepository
|
||||
plays []entities.GamePlay
|
||||
}
|
||||
|
||||
func (f *gamePlayRepoFake) Create(_ context.Context, gp *entities.GamePlay) error {
|
||||
f.plays = append(f.plays, *gp)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *gamePlayRepoFake) snapshot() func() {
|
||||
plays := append([]entities.GamePlay(nil), f.plays...)
|
||||
return func() { f.plays = plays }
|
||||
}
|
||||
|
||||
type gameTestEnv struct {
|
||||
*walletMoveEnv
|
||||
game *entities.Game
|
||||
prize entities.GamePrize
|
||||
stock *prizeStockFake
|
||||
plays *gamePlayRepoFake
|
||||
player uuid.UUID
|
||||
p *GamePlayProcessor
|
||||
}
|
||||
|
||||
func newGameTestEnv(t *testing.T, metadata entities.Metadata) *gameTestEnv {
|
||||
e := &gameTestEnv{walletMoveEnv: newWalletMoveEnv(t)}
|
||||
e.game = &entities.Game{ID: uuid.New(), Name: "Spin Wheel", Type: entities.GameTypeSpin, IsActive: true, Metadata: metadata}
|
||||
e.prize = entities.GamePrize{ID: uuid.New(), GameID: e.game.ID, Name: "Voucher 10rb", Weight: 1, Stock: 5}
|
||||
e.stock = &prizeStockFake{prizes: []entities.GamePrize{e.prize}}
|
||||
e.plays = &gamePlayRepoFake{}
|
||||
e.player = e.member("Budi", "081234561234")
|
||||
tx := rollbackTx{saves: []func() func(){e.repo.snapshot, e.stock.snapshot, e.plays.snapshot}}
|
||||
e.p = NewGamePlayProcessor(e.plays, gameFake{games: map[uuid.UUID]*entities.Game{e.game.ID: e.game}}, e.stock, e.walletTestEnv.p, e, tx)
|
||||
return e
|
||||
}
|
||||
|
||||
func (e *gameTestEnv) play() (*models.PlayGameResponse, error) {
|
||||
return e.p.PlayGame(e.ctx, &models.PlayGameRequest{GameID: e.game.ID, CustomerID: e.player})
|
||||
}
|
||||
|
||||
func TestPlayGame_SpendsTheGamesCoinCost(t *testing.T) {
|
||||
// coin_cost comes back from JSONB as a float64.
|
||||
e := newGameTestEnv(t, entities.Metadata{"coin_cost": float64(3)})
|
||||
e.earnCoins(t, e.player, 10, nil)
|
||||
|
||||
res, err := e.play()
|
||||
require.NoError(t, err)
|
||||
|
||||
assert.Equal(t, int64(7), res.CoinsRemaining)
|
||||
require.NotNil(t, res.PrizeWon)
|
||||
assert.Equal(t, e.prize.ID, res.PrizeWon.ID)
|
||||
require.Len(t, e.plays.plays, 1)
|
||||
play := e.plays.plays[0]
|
||||
assert.Equal(t, 3, play.CoinsUsed)
|
||||
assert.Equal(t, e.prize.ID, *play.PrizeID)
|
||||
assert.Equal(t, 4, e.stock.prizes[0].Stock)
|
||||
|
||||
spend := e.repo.transactions[len(e.repo.transactions)-1]
|
||||
assert.Equal(t, constants.WalletTxTypeGameSpend, spend.Type)
|
||||
assert.Equal(t, constants.WalletCurrencyCoin, spend.Currency)
|
||||
assert.Equal(t, int64(-3), spend.Amount)
|
||||
assert.Equal(t, constants.WalletRefTypeGamePlay, spend.ReferenceType)
|
||||
assert.Equal(t, play.ID, spend.ReferenceID, "GAME_SPEND points at the game play")
|
||||
assert.Equal(t, "Main Spin Wheel: dapat Voucher 10rb", spend.Description)
|
||||
}
|
||||
|
||||
func TestPlayGame_CostsOneCoinByDefault(t *testing.T) {
|
||||
e := newGameTestEnv(t, entities.Metadata{})
|
||||
e.earnCoins(t, e.player, 2, nil)
|
||||
|
||||
res, err := e.play()
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, int64(1), res.CoinsRemaining)
|
||||
assert.Equal(t, 1, e.plays.plays[0].CoinsUsed)
|
||||
}
|
||||
|
||||
func TestPlayGame_NotEnoughCoinsRecordsNothing(t *testing.T) {
|
||||
e := newGameTestEnv(t, entities.Metadata{"coin_cost": float64(3)})
|
||||
e.earnCoins(t, e.player, 2, nil)
|
||||
|
||||
_, err := e.play()
|
||||
assert.ErrorIs(t, err, ErrGamePlayRefused)
|
||||
assert.Empty(t, e.plays.plays)
|
||||
assert.Equal(t, 5, e.stock.prizes[0].Stock)
|
||||
assert.Equal(t, int64(2), e.coinBalance(t, e.player))
|
||||
}
|
||||
|
||||
func TestPlayGame_PrizeStockFailureCancelsThePlay(t *testing.T) {
|
||||
e := newGameTestEnv(t, entities.Metadata{})
|
||||
e.earnCoins(t, e.player, 5, nil)
|
||||
rows := len(e.repo.transactions)
|
||||
|
||||
// Another play took the last one between reading the prizes and taking it.
|
||||
e.stock.stockErr = repository.ErrGamePrizeOutOfStock
|
||||
_, err := e.play()
|
||||
assert.ErrorIs(t, err, ErrGamePlayRefused)
|
||||
|
||||
// Anything else going wrong with the stock cancels it too.
|
||||
e.stock.stockErr = errors.New("connection reset")
|
||||
_, err = e.play()
|
||||
assert.Error(t, err)
|
||||
|
||||
assert.Empty(t, e.plays.plays)
|
||||
assert.Len(t, e.repo.transactions, rows, "no GAME_SPEND is left behind")
|
||||
assert.Equal(t, int64(5), e.coinBalance(t, e.player))
|
||||
}
|
||||
|
||||
func TestPlayGame_RefusesWhatCannotBePlayed(t *testing.T) {
|
||||
for name, metadata := range map[string]entities.Metadata{
|
||||
"zero": {"coin_cost": float64(0)},
|
||||
"fraction": {"coin_cost": 1.5},
|
||||
"not number": {"coin_cost": "2"},
|
||||
} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
e := newGameTestEnv(t, metadata)
|
||||
e.earnCoins(t, e.player, 5, nil)
|
||||
_, err := e.play()
|
||||
assert.ErrorIs(t, err, ErrGamePlayRefused)
|
||||
assert.Equal(t, int64(5), e.coinBalance(t, e.player))
|
||||
})
|
||||
}
|
||||
|
||||
t.Run("inactive", func(t *testing.T) {
|
||||
e := newGameTestEnv(t, entities.Metadata{})
|
||||
e.earnCoins(t, e.player, 5, nil)
|
||||
e.game.IsActive = false
|
||||
_, err := e.play()
|
||||
assert.ErrorIs(t, err, ErrGamePlayRefused)
|
||||
})
|
||||
|
||||
t.Run("no prizes left", func(t *testing.T) {
|
||||
e := newGameTestEnv(t, entities.Metadata{})
|
||||
e.earnCoins(t, e.player, 5, nil)
|
||||
e.stock.prizes[0].Stock = 0
|
||||
_, err := e.play()
|
||||
assert.ErrorIs(t, err, ErrGamePlayRefused)
|
||||
assert.Equal(t, int64(5), e.coinBalance(t, e.player))
|
||||
})
|
||||
}
|
||||
@@ -1,148 +0,0 @@
|
||||
package processor
|
||||
|
||||
import (
|
||||
"apskel-pos-be/internal/mappers"
|
||||
"apskel-pos-be/internal/models"
|
||||
"apskel-pos-be/internal/repository"
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
type GamePrizeProcessor struct {
|
||||
gamePrizeRepo *repository.GamePrizeRepository
|
||||
}
|
||||
|
||||
func NewGamePrizeProcessor(gamePrizeRepo *repository.GamePrizeRepository) *GamePrizeProcessor {
|
||||
return &GamePrizeProcessor{
|
||||
gamePrizeRepo: gamePrizeRepo,
|
||||
}
|
||||
}
|
||||
|
||||
// CreateGamePrize creates a new game prize
|
||||
func (p *GamePrizeProcessor) CreateGamePrize(ctx context.Context, req *models.CreateGamePrizeRequest) (*models.GamePrizeResponse, error) {
|
||||
// Convert request to entity
|
||||
gamePrize := mappers.ToGamePrizeEntity(req)
|
||||
|
||||
// Create game prize
|
||||
err := p.gamePrizeRepo.Create(ctx, gamePrize)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to create game prize: %w", err)
|
||||
}
|
||||
|
||||
return mappers.ToGamePrizeResponse(gamePrize), nil
|
||||
}
|
||||
|
||||
// GetGamePrize retrieves a game prize by ID
|
||||
func (p *GamePrizeProcessor) GetGamePrize(ctx context.Context, id uuid.UUID) (*models.GamePrizeResponse, error) {
|
||||
gamePrize, err := p.gamePrizeRepo.GetByID(ctx, id)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("game prize not found: %w", err)
|
||||
}
|
||||
|
||||
return mappers.ToGamePrizeResponse(gamePrize), nil
|
||||
}
|
||||
|
||||
// GetGamePrizesByGameID retrieves all prizes for a specific game
|
||||
func (p *GamePrizeProcessor) GetGamePrizesByGameID(ctx context.Context, gameID uuid.UUID) ([]models.GamePrizeResponse, error) {
|
||||
gamePrizes, err := p.gamePrizeRepo.GetByGameID(ctx, gameID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to get game prizes: %w", err)
|
||||
}
|
||||
|
||||
return mappers.ToGamePrizeResponses(gamePrizes), nil
|
||||
}
|
||||
|
||||
// ListGamePrizes retrieves game prizes with pagination and filtering
|
||||
func (p *GamePrizeProcessor) ListGamePrizes(ctx context.Context, query *models.ListGamePrizesQuery) (*models.PaginatedResponse[models.GamePrizeResponse], error) {
|
||||
// Set default values
|
||||
if query.Page <= 0 {
|
||||
query.Page = 1
|
||||
}
|
||||
if query.Limit <= 0 {
|
||||
query.Limit = 10
|
||||
}
|
||||
if query.Limit > 100 {
|
||||
query.Limit = 100
|
||||
}
|
||||
|
||||
offset := (query.Page - 1) * query.Limit
|
||||
|
||||
// Get game prizes from repository
|
||||
gamePrizes, total, err := p.gamePrizeRepo.List(
|
||||
ctx,
|
||||
offset,
|
||||
query.Limit,
|
||||
query.Search,
|
||||
query.GameID,
|
||||
query.SortBy,
|
||||
query.SortOrder,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to list game prizes: %w", err)
|
||||
}
|
||||
|
||||
// Convert to responses
|
||||
responses := mappers.ToGamePrizeResponses(gamePrizes)
|
||||
|
||||
// Calculate pagination info
|
||||
totalPages := int((total + int64(query.Limit) - 1) / int64(query.Limit))
|
||||
|
||||
return &models.PaginatedResponse[models.GamePrizeResponse]{
|
||||
Data: responses,
|
||||
Pagination: models.Pagination{
|
||||
Page: query.Page,
|
||||
Limit: query.Limit,
|
||||
Total: total,
|
||||
TotalPages: totalPages,
|
||||
},
|
||||
}, nil
|
||||
}
|
||||
|
||||
// UpdateGamePrize updates an existing game prize
|
||||
func (p *GamePrizeProcessor) UpdateGamePrize(ctx context.Context, id uuid.UUID, req *models.UpdateGamePrizeRequest) (*models.GamePrizeResponse, error) {
|
||||
// Get existing game prize
|
||||
gamePrize, err := p.gamePrizeRepo.GetByID(ctx, id)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("game prize not found: %w", err)
|
||||
}
|
||||
|
||||
// Update game prize fields
|
||||
mappers.UpdateGamePrizeEntity(gamePrize, req)
|
||||
|
||||
// Save updated game prize
|
||||
err = p.gamePrizeRepo.Update(ctx, gamePrize)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to update game prize: %w", err)
|
||||
}
|
||||
|
||||
return mappers.ToGamePrizeResponse(gamePrize), nil
|
||||
}
|
||||
|
||||
// DeleteGamePrize deletes a game prize
|
||||
func (p *GamePrizeProcessor) DeleteGamePrize(ctx context.Context, id uuid.UUID) error {
|
||||
// Get existing game prize
|
||||
_, err := p.gamePrizeRepo.GetByID(ctx, id)
|
||||
if err != nil {
|
||||
return fmt.Errorf("game prize not found: %w", err)
|
||||
}
|
||||
|
||||
// Delete game prize
|
||||
err = p.gamePrizeRepo.Delete(ctx, id)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to delete game prize: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetAvailablePrizes gets all available prizes for a game (with stock > 0)
|
||||
func (p *GamePrizeProcessor) GetAvailablePrizes(ctx context.Context, gameID uuid.UUID) ([]models.GamePrizeResponse, error) {
|
||||
gamePrizes, err := p.gamePrizeRepo.GetAvailablePrizes(ctx, gameID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to get available prizes: %w", err)
|
||||
}
|
||||
|
||||
return mappers.ToGamePrizeResponses(gamePrizes), nil
|
||||
}
|
||||
@@ -1,139 +0,0 @@
|
||||
package processor
|
||||
|
||||
import (
|
||||
"apskel-pos-be/internal/mappers"
|
||||
"apskel-pos-be/internal/models"
|
||||
"apskel-pos-be/internal/repository"
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
type GameProcessor struct {
|
||||
gameRepo *repository.GameRepository
|
||||
}
|
||||
|
||||
func NewGameProcessor(gameRepo *repository.GameRepository) *GameProcessor {
|
||||
return &GameProcessor{
|
||||
gameRepo: gameRepo,
|
||||
}
|
||||
}
|
||||
|
||||
// CreateGame creates a new game
|
||||
func (p *GameProcessor) CreateGame(ctx context.Context, req *models.CreateGameRequest) (*models.GameResponse, error) {
|
||||
// Convert request to entity
|
||||
game := mappers.ToGameEntity(req)
|
||||
|
||||
// Create game
|
||||
err := p.gameRepo.Create(ctx, game)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to create game: %w", err)
|
||||
}
|
||||
|
||||
return mappers.ToGameResponse(game), nil
|
||||
}
|
||||
|
||||
// GetGame retrieves a game by ID
|
||||
func (p *GameProcessor) GetGame(ctx context.Context, id uuid.UUID) (*models.GameResponse, error) {
|
||||
game, err := p.gameRepo.GetByID(ctx, id)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("game not found: %w", err)
|
||||
}
|
||||
|
||||
return mappers.ToGameResponse(game), nil
|
||||
}
|
||||
|
||||
// ListGames retrieves games with pagination and filtering
|
||||
func (p *GameProcessor) ListGames(ctx context.Context, query *models.ListGamesQuery) (*models.PaginatedResponse[models.GameResponse], error) {
|
||||
// Set default values
|
||||
if query.Page <= 0 {
|
||||
query.Page = 1
|
||||
}
|
||||
if query.Limit <= 0 {
|
||||
query.Limit = 10
|
||||
}
|
||||
if query.Limit > 100 {
|
||||
query.Limit = 100
|
||||
}
|
||||
|
||||
offset := (query.Page - 1) * query.Limit
|
||||
|
||||
// Get games from repository
|
||||
games, total, err := p.gameRepo.List(
|
||||
ctx,
|
||||
offset,
|
||||
query.Limit,
|
||||
query.Search,
|
||||
query.Type,
|
||||
query.IsActive,
|
||||
query.SortBy,
|
||||
query.SortOrder,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to list games: %w", err)
|
||||
}
|
||||
|
||||
// Convert to responses
|
||||
responses := mappers.ToGameResponses(games)
|
||||
|
||||
// Calculate pagination info
|
||||
totalPages := int((total + int64(query.Limit) - 1) / int64(query.Limit))
|
||||
|
||||
return &models.PaginatedResponse[models.GameResponse]{
|
||||
Data: responses,
|
||||
Pagination: models.Pagination{
|
||||
Page: query.Page,
|
||||
Limit: query.Limit,
|
||||
Total: total,
|
||||
TotalPages: totalPages,
|
||||
},
|
||||
}, nil
|
||||
}
|
||||
|
||||
// UpdateGame updates an existing game
|
||||
func (p *GameProcessor) UpdateGame(ctx context.Context, id uuid.UUID, req *models.UpdateGameRequest) (*models.GameResponse, error) {
|
||||
// Get existing game
|
||||
game, err := p.gameRepo.GetByID(ctx, id)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("game not found: %w", err)
|
||||
}
|
||||
|
||||
// Update game fields
|
||||
mappers.UpdateGameEntity(game, req)
|
||||
|
||||
// Save updated game
|
||||
err = p.gameRepo.Update(ctx, game)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to update game: %w", err)
|
||||
}
|
||||
|
||||
return mappers.ToGameResponse(game), nil
|
||||
}
|
||||
|
||||
// DeleteGame deletes a game
|
||||
func (p *GameProcessor) DeleteGame(ctx context.Context, id uuid.UUID) error {
|
||||
// Get existing game
|
||||
_, err := p.gameRepo.GetByID(ctx, id)
|
||||
if err != nil {
|
||||
return fmt.Errorf("game not found: %w", err)
|
||||
}
|
||||
|
||||
// Delete game
|
||||
err = p.gameRepo.Delete(ctx, id)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to delete game: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetActiveGames gets all active games
|
||||
func (p *GameProcessor) GetActiveGames(ctx context.Context) ([]models.GameResponse, error) {
|
||||
games, err := p.gameRepo.GetActiveGames(ctx)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to get active games: %w", err)
|
||||
}
|
||||
|
||||
return mappers.ToGameResponses(games), nil
|
||||
}
|
||||
@@ -0,0 +1,370 @@
|
||||
package processor
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"apskel-pos-be/internal/constants"
|
||||
"apskel-pos-be/internal/entities"
|
||||
"apskel-pos-be/internal/logger"
|
||||
"apskel-pos-be/internal/models"
|
||||
"apskel-pos-be/internal/repository"
|
||||
)
|
||||
|
||||
// gameResultDataLimit bounds the free-form data a client may attach to a result.
|
||||
const gameResultDataLimit = 16 * 1024
|
||||
|
||||
// gameRewardBreakdown is how a session's reward was reached, kept in
|
||||
// game_sessions.reward_breakdown. It is internal: the customer only sees the totals.
|
||||
type gameRewardBreakdown struct {
|
||||
RewardConfigID uuid.UUID `json:"reward_config_id"`
|
||||
ConfigVersion int `json:"config_version"`
|
||||
RewardType string `json:"reward_type"`
|
||||
// Why the result was not believed, if it was not (§7.2 step 5).
|
||||
Rejections []string `json:"rejections,omitempty"`
|
||||
Base int64 `json:"base"`
|
||||
Detail map[string]any `json:"detail,omitempty"`
|
||||
MaxReward int64 `json:"max_reward"`
|
||||
Capped bool `json:"capped"`
|
||||
// The events running on the game when it completed, highest priority first.
|
||||
Events []uuid.UUID `json:"events,omitempty"`
|
||||
// The limits that cut the reward (§9), in the order they were applied.
|
||||
Guard []gameGuardCut `json:"guard,omitempty"`
|
||||
LimitedBy []string `json:"limited_by,omitempty"`
|
||||
// The base and what each event adds, each paid by its budget (D6).
|
||||
Components []gameRewardComponent `json:"components"`
|
||||
Total int64 `json:"total"`
|
||||
}
|
||||
|
||||
type gameRewardComponent struct {
|
||||
// BASE or EVENT.
|
||||
Kind string `json:"kind"`
|
||||
BudgetID uuid.UUID `json:"budget_id"`
|
||||
// EVENT only: the event and what it applied.
|
||||
EventID *uuid.UUID `json:"event_id,omitempty"`
|
||||
Multiplier *float64 `json:"multiplier,omitempty"`
|
||||
Bonus *int64 `json:"bonus,omitempty"`
|
||||
// Before the cap and the limits, and what was paid.
|
||||
Earned int64 `json:"earned"`
|
||||
Amount int64 `json:"amount"`
|
||||
LimitedBy []string `json:"limited_by,omitempty"`
|
||||
}
|
||||
|
||||
// gameGuardCut is one limit that cut a reward: how much it allowed of what was asked.
|
||||
type gameGuardCut struct {
|
||||
Limit string `json:"limit"`
|
||||
// For an event's own limits.
|
||||
EventID *uuid.UUID `json:"event_id,omitempty"`
|
||||
Value int64 `json:"value"`
|
||||
Asked int64 `json:"asked"`
|
||||
Allowed int64 `json:"allowed"`
|
||||
}
|
||||
|
||||
// The limits of §5.10 and §9, by the name the breakdown and the response give them.
|
||||
const (
|
||||
gameLimitUserDaily = "USER_DAILY"
|
||||
gameLimitGameDaily = "GAME_DAILY"
|
||||
gameLimitGlobalDaily = "GLOBAL_DAILY"
|
||||
)
|
||||
|
||||
// storedGameResult is what is kept of the client's result: the data only (P1).
|
||||
type storedGameResult struct {
|
||||
Score *int64 `json:"score,omitempty"`
|
||||
Outcome *string `json:"outcome,omitempty"`
|
||||
Data json.RawMessage `json:"data,omitempty"`
|
||||
}
|
||||
|
||||
// Complete ends a session with the client's result and pays its reward, in one
|
||||
// transaction (docs/rfc-enakgame.md §7.2). The backend alone decides the reward
|
||||
// (P1): the result is checked against the game's result_rules, priced with the
|
||||
// configuration frozen at start, and capped by its max_reward. A result that is not
|
||||
// believed completes the session with no reward and flags it; the entry cost stays
|
||||
// spent.
|
||||
//
|
||||
// Completing again returns the first completion. When the game was turned off during
|
||||
// the play, the entry cost is refunded instead. A failure that is not the customer's
|
||||
// marks the session, in a transaction of its own, so the session job refunds it once
|
||||
// it expires (§7.3).
|
||||
func (p *GameSessionProcessor) Complete(ctx context.Context, customerID, sessionID uuid.UUID, in models.GameSessionCompleteInput) (*models.GameSessionCompletion, error) {
|
||||
if len(in.Data) > gameResultDataLimit {
|
||||
return nil, gameSessionRejected("data must be at most %d bytes", gameResultDataLimit)
|
||||
}
|
||||
session, err := p.complete(ctx, customerID, sessionID, in)
|
||||
if errors.Is(err, errGameSessionMoved) {
|
||||
// The session job finished it between our read and our update: answer with
|
||||
// what it is now.
|
||||
session, err = p.complete(ctx, customerID, sessionID, in)
|
||||
}
|
||||
if err != nil {
|
||||
if !isGameSessionBusinessError(err) {
|
||||
p.markCompletionFailed(ctx, customerID, sessionID)
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
balances, err := p.spendable.SpendableBalances(ctx, customerID, p.now())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out := &models.GameSessionCompletion{
|
||||
SessionID: session.ID,
|
||||
Status: session.Status,
|
||||
RefundReason: session.RefundReason,
|
||||
RewardTotal: session.RewardTotal,
|
||||
CoinBalance: balances[constants.WalletCurrencyCoin],
|
||||
}
|
||||
// Read back from the stored breakdown, so a repeated completion answers the same.
|
||||
if len(session.RewardBreakdown) > 0 {
|
||||
var stored gameRewardBreakdown
|
||||
if err := json.Unmarshal(session.RewardBreakdown, &stored); err == nil {
|
||||
out.LimitedBy = stored.LimitedBy
|
||||
out.Reward = rewardParts(stored)
|
||||
out.Prize = drawnPrize(stored.RewardType, stored.Base, stored.Detail)
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (p *GameSessionProcessor) complete(ctx context.Context, customerID, sessionID uuid.UUID, in models.GameSessionCompleteInput) (*entities.GameSession, error) {
|
||||
var session *entities.GameSession
|
||||
err := p.tx.WithTransaction(ctx, func(ctx context.Context) error {
|
||||
if err := p.wallet.LockWallet(ctx, customerID); err != nil {
|
||||
return err
|
||||
}
|
||||
var err error
|
||||
session, err = p.sessions.GetCustomerSession(ctx, customerID, sessionID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
switch session.Status {
|
||||
case constants.GameSessionStatusCompleted, constants.GameSessionStatusRefunded:
|
||||
// Already settled: the same answer again (PRD §20).
|
||||
return nil
|
||||
case constants.GameSessionStatusExpired:
|
||||
return gameSessionRejected("the session has expired")
|
||||
}
|
||||
now := p.now()
|
||||
if now.After(session.ExpiresAt) {
|
||||
// Left for the session job, which knows whether to refund it.
|
||||
return gameSessionRejected("the session has expired")
|
||||
}
|
||||
|
||||
game, err := p.games.GetGame(ctx, session.OrganizationID, session.GameID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if game.Status != constants.GameStatusActive {
|
||||
_, err := p.refundLocked(ctx, session, constants.GameSessionRefundGameDeactivated, constants.AuditSourceCustomerAPI)
|
||||
return err
|
||||
}
|
||||
|
||||
config, err := p.games.GetRewardConfig(ctx, session.OrganizationID, session.RewardConfigID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("reward config of session %s: %w", session.ID, err)
|
||||
}
|
||||
result := SessionResult{Score: in.Score, Outcome: in.Outcome}
|
||||
breakdown := gameRewardBreakdown{
|
||||
RewardConfigID: config.ID, ConfigVersion: config.Version, RewardType: config.RewardType,
|
||||
MaxReward: config.MaxReward, Components: []gameRewardComponent{},
|
||||
}
|
||||
breakdown.Rejections = ValidateResult(game.ResultRules, result, session.StartedAt, now)
|
||||
if len(breakdown.Rejections) == 0 {
|
||||
calculator, err := RewardCalculatorFor(config.RewardType)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
breakdown.Base, breakdown.Detail, err = calculator.Calculate(json.RawMessage(config.Rules), result, p.rng)
|
||||
switch {
|
||||
case errors.Is(err, ErrRewardResultUnusable):
|
||||
breakdown.Rejections = append(breakdown.Rejections, err.Error())
|
||||
breakdown.Base = 0
|
||||
case err != nil:
|
||||
return err
|
||||
}
|
||||
}
|
||||
var events []entities.GameEvent
|
||||
if breakdown.Base > 0 {
|
||||
if events, err = p.events.ActiveEventsForGame(ctx, session.OrganizationID, session.GameID, now); err != nil {
|
||||
return err
|
||||
}
|
||||
for _, e := range events {
|
||||
breakdown.Events = append(breakdown.Events, e.ID)
|
||||
}
|
||||
}
|
||||
parts, capped := rewardComponents(breakdown.Base, config.MaxReward, events)
|
||||
breakdown.Capped = capped
|
||||
|
||||
var settings *models.OrganizationLoyaltySettings
|
||||
if sumComponents(parts) > 0 {
|
||||
if settings, err = p.settings.Organization(ctx, session.OrganizationID); err != nil {
|
||||
return err
|
||||
}
|
||||
if breakdown.Guard, err = p.guardReward(ctx, session, game, events, settings, now, parts); err != nil {
|
||||
return err
|
||||
}
|
||||
for _, cut := range breakdown.Guard {
|
||||
if !containsString(breakdown.LimitedBy, cut.Limit) {
|
||||
breakdown.LimitedBy = append(breakdown.LimitedBy, cut.Limit)
|
||||
}
|
||||
}
|
||||
}
|
||||
if len(parts) > 0 && parts[0].Amount > 0 {
|
||||
budget, err := p.rewardBudget(ctx, session, now)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
parts[0].BudgetID = budget.ID
|
||||
}
|
||||
breakdown.Components = []gameRewardComponent{}
|
||||
for _, part := range parts {
|
||||
if part.Amount > 0 {
|
||||
breakdown.Components = append(breakdown.Components, part)
|
||||
}
|
||||
}
|
||||
total := sumComponents(breakdown.Components)
|
||||
breakdown.Total = total
|
||||
|
||||
resultDoc, err := json.Marshal(storedGameResult{Score: in.Score, Outcome: in.Outcome, Data: in.Data})
|
||||
if err != nil {
|
||||
return gameSessionRejected("data must be valid JSON")
|
||||
}
|
||||
breakdownDoc, err := json.Marshal(breakdown)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
flagged := len(breakdown.Rejections) > 0
|
||||
moved, err := p.sessions.CompleteSession(ctx, session.ID, repository.GameSessionCompletion{
|
||||
Result: entities.JSONDocument(resultDoc), RewardBreakdown: entities.JSONDocument(breakdownDoc),
|
||||
RewardTotal: total, Flagged: flagged, EndedAt: now,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !moved {
|
||||
return errGameSessionMoved
|
||||
}
|
||||
session.Status, session.RewardTotal, session.Flagged, session.EndedAt = constants.GameSessionStatusCompleted, total, flagged, &now
|
||||
session.Result, session.RewardBreakdown = entities.JSONDocument(resultDoc), entities.JSONDocument(breakdownDoc)
|
||||
|
||||
for _, payment := range paymentsByBudget(breakdown.Components) {
|
||||
if err := p.payReward(ctx, session, game, settings, payment, now); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
return session, err
|
||||
}
|
||||
|
||||
// rewardBudget is the global budget paying a session's base reward: the one running
|
||||
// today, or, across a month end without a budget yet, the one the session started
|
||||
// under.
|
||||
func (p *GameSessionProcessor) rewardBudget(ctx context.Context, session *entities.GameSession, now time.Time) (*entities.GameBudget, error) {
|
||||
budget, err := p.budgets.GetGlobalBudgetOn(ctx, session.OrganizationID, walletDay(now))
|
||||
if errors.Is(err, repository.ErrGameBudgetNotFound) {
|
||||
budget, err = p.budgets.GetGlobalBudgetOn(ctx, session.OrganizationID, walletDay(session.StartedAt))
|
||||
}
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("no global budget for session %s: %w", session.ID, err)
|
||||
}
|
||||
return budget, nil
|
||||
}
|
||||
|
||||
// payReward credits one budget's part of a reward as its own GAME_REWARD row and lot
|
||||
// (D6), and records which budget paid it.
|
||||
func (p *GameSessionProcessor) payReward(ctx context.Context, session *entities.GameSession, game *entities.Game, settings *models.OrganizationLoyaltySettings, c gameRewardComponent, now time.Time) error {
|
||||
credit, err := p.wallet.Credit(ctx, WalletCreditInput{
|
||||
WalletEntry: WalletEntry{
|
||||
CustomerID: session.CustomerID,
|
||||
Currency: constants.WalletCurrencyCoin,
|
||||
Type: constants.WalletTxTypeGameReward,
|
||||
Amount: c.Amount,
|
||||
ReferenceType: constants.WalletRefTypeGameSession,
|
||||
ReferenceID: session.ID,
|
||||
Description: truncateDescription("Hadiah " + game.Name),
|
||||
Metadata: entities.Metadata{"game_id": game.ID.String(), "budget_id": c.BudgetID.String(), "kind": c.Kind},
|
||||
IdempotencyKey: fmt.Sprintf("game-reward:%s:%s", session.ID, c.BudgetID),
|
||||
},
|
||||
Lots: []WalletLotInput{{Amount: c.Amount, ExpiresAt: ComputeExpiry(settings.CoinExpiry, now)}},
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return p.sessions.CreateSessionRewards(ctx, []entities.GameSessionReward{{
|
||||
SessionID: session.ID, BudgetID: c.BudgetID, Amount: c.Amount, WalletTransactionID: credit.Transaction.ID,
|
||||
}})
|
||||
}
|
||||
|
||||
// applyGuard runs a reward through the daily limits (§9): what one customer may get,
|
||||
// what the game may give, what the whole organization may give, each counted per day
|
||||
// in Asia/Jakarta. A reward over a limit is cut to what is left of it, down to 0. It
|
||||
// returns what may be paid and the limits that cut it.
|
||||
//
|
||||
// Every counter takes the reward even when its limit is off, so a limit switched on
|
||||
// during the day counts what was already given. The counters are taken in a fixed
|
||||
// order, so two completions never wait on each other's rows the other way round; a
|
||||
// counter that took more than a later limit allowed gives the difference back.
|
||||
func (p *GameSessionProcessor) applyGuard(ctx context.Context, session *entities.GameSession, game *entities.Game, settings *models.OrganizationLoyaltySettings, now time.Time, amount int64) (int64, []gameGuardCut, error) {
|
||||
gameDaily := int64(0)
|
||||
if game.ResultRules.DailyRewardLimit != nil {
|
||||
gameDaily = *game.ResultRules.DailyRewardLimit
|
||||
}
|
||||
limits := []struct {
|
||||
name, scope string
|
||||
scopeID uuid.UUID
|
||||
value int64
|
||||
}{
|
||||
{gameLimitUserDaily, constants.GameRewardScopeUser, session.CustomerID, settings.EnakGame.UserDailyLimit},
|
||||
{gameLimitGameDaily, constants.GameRewardScopeGame, session.GameID, gameDaily},
|
||||
{gameLimitGlobalDaily, constants.GameRewardScopeGlobal, session.OrganizationID, settings.EnakGame.GlobalDailyLimit},
|
||||
}
|
||||
day := walletDay(now)
|
||||
taken := make([]int64, len(limits))
|
||||
var cuts []gameGuardCut
|
||||
for i, l := range limits {
|
||||
got, err := p.counters.Consume(ctx, session.OrganizationID, l.scope, l.scopeID, day, amount, l.value)
|
||||
if err != nil {
|
||||
return 0, nil, err
|
||||
}
|
||||
taken[i] = got
|
||||
if got < amount {
|
||||
cuts = append(cuts, gameGuardCut{Limit: l.name, Value: l.value, Asked: amount, Allowed: got})
|
||||
amount = got
|
||||
}
|
||||
if amount == 0 {
|
||||
break
|
||||
}
|
||||
}
|
||||
for i, l := range limits {
|
||||
if extra := taken[i] - amount; extra > 0 {
|
||||
if err := p.counters.Release(ctx, session.OrganizationID, l.scope, l.scopeID, day, extra); err != nil {
|
||||
return 0, nil, err
|
||||
}
|
||||
}
|
||||
}
|
||||
return amount, cuts, nil
|
||||
}
|
||||
|
||||
// markCompletionFailed records, outside the failed transaction, that completing the
|
||||
// customer's session failed on a system error (§7.3).
|
||||
func (p *GameSessionProcessor) markCompletionFailed(ctx context.Context, customerID, sessionID uuid.UUID) {
|
||||
ctx = repository.DetachTransaction(ctx)
|
||||
if _, err := p.sessions.GetCustomerSession(ctx, customerID, sessionID); err != nil {
|
||||
return
|
||||
}
|
||||
if _, err := p.sessions.MarkCompletionFailed(ctx, sessionID, p.now()); err != nil {
|
||||
logger.FromContext(ctx).WithError(err).Error("GameSessionProcessor::Complete -> failed to mark the session")
|
||||
}
|
||||
}
|
||||
|
||||
// isGameSessionBusinessError tells a refusal the customer caused from a failure of
|
||||
// the system.
|
||||
func isGameSessionBusinessError(err error) bool {
|
||||
return errors.Is(err, ErrGameSessionRejected) ||
|
||||
errors.Is(err, repository.ErrGameSessionNotFound) ||
|
||||
errors.Is(err, repository.ErrWalletNotFound)
|
||||
}
|
||||
@@ -0,0 +1,460 @@
|
||||
package processor
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"apskel-pos-be/internal/constants"
|
||||
"apskel-pos-be/internal/entities"
|
||||
"apskel-pos-be/internal/logger"
|
||||
"apskel-pos-be/internal/models"
|
||||
"apskel-pos-be/internal/repository"
|
||||
)
|
||||
|
||||
// ErrGameSessionRejected wraps every reason a customer cannot start a game: the key,
|
||||
// the game, its configuration, the budget, the EnakCoin balance. The message says
|
||||
// which.
|
||||
var ErrGameSessionRejected = errors.New("game session refused")
|
||||
|
||||
// errGameSessionMoved rolls back a refund whose session another flow finished first.
|
||||
var errGameSessionMoved = errors.New("game session is no longer started")
|
||||
|
||||
const (
|
||||
// gameSessionKeyLimit keeps the client's Idempotency-Key short enough to fit, with
|
||||
// the prefix scoping it to the customer, in wallet_transactions.idempotency_key.
|
||||
gameSessionKeyLimit = 50
|
||||
// gameSessionJobBatch is how many sessions the job reads at a time, and
|
||||
// gameSessionJobBatches how many batches one run goes through at most.
|
||||
gameSessionJobBatch = 100
|
||||
gameSessionJobBatches = 10
|
||||
// customerGameListLimit caps the games the customer app gets in one list.
|
||||
customerGameListLimit = 100
|
||||
)
|
||||
|
||||
func gameSessionRejected(format string, args ...any) error {
|
||||
return fmt.Errorf("%w: %s", ErrGameSessionRejected, fmt.Sprintf(format, args...))
|
||||
}
|
||||
|
||||
type gameCustomerReader interface {
|
||||
GetCustomer(ctx context.Context, customerID uuid.UUID) (*repository.WalletMoveCustomer, error)
|
||||
}
|
||||
|
||||
// GameSessionProcessor starts and completes EnakGame sessions, refunds their entry
|
||||
// cost when the system is at fault, and ends the ones left behind
|
||||
// (docs/rfc-enakgame.md §7.1–§7.3).
|
||||
//
|
||||
// Every flow locks the customer's wallet before anything else (P4), and a session
|
||||
// leaves STARTED only through a conditional update (D4), so a refund never races a
|
||||
// completion or another refund of the same session.
|
||||
type GameSessionProcessor struct {
|
||||
customers gameCustomerReader
|
||||
games repository.EnakGameRepository
|
||||
sessions repository.GameSessionRepository
|
||||
budgets repository.GameBudgetRepository
|
||||
events repository.GameEventRepository
|
||||
counters repository.GameRewardCounterRepository
|
||||
settings organizationSettingsReader
|
||||
spendable spendableReader
|
||||
wallet *WalletProcessor
|
||||
audit *AuditLogger
|
||||
tx TxRunner
|
||||
rng RewardRNG
|
||||
now func() time.Time
|
||||
}
|
||||
|
||||
func NewGameSessionProcessor(customers gameCustomerReader, games repository.EnakGameRepository, sessions repository.GameSessionRepository,
|
||||
budgets repository.GameBudgetRepository, events repository.GameEventRepository, counters repository.GameRewardCounterRepository,
|
||||
settings organizationSettingsReader, spendable spendableReader, wallet *WalletProcessor, audit *AuditLogger, tx TxRunner) *GameSessionProcessor {
|
||||
return &GameSessionProcessor{
|
||||
customers: customers, games: games, sessions: sessions, budgets: budgets, events: events, counters: counters, settings: settings, spendable: spendable,
|
||||
wallet: wallet, audit: audit, tx: tx, rng: CryptoRewardRNG{}, now: time.Now,
|
||||
}
|
||||
}
|
||||
|
||||
// Start takes a game's entry cost in EnakCoin and opens a session, in one transaction
|
||||
// (§7.1, PRD §10.1). The entry cost and the active reward configuration are frozen on
|
||||
// the session, so changing the game later does not change it.
|
||||
//
|
||||
// idempotencyKey is the client's Idempotency-Key: a retry with the same key returns
|
||||
// the session the first attempt opened and takes nothing more.
|
||||
func (p *GameSessionProcessor) Start(ctx context.Context, customerID, gameID uuid.UUID, idempotencyKey string) (*models.GameSessionStart, error) {
|
||||
key := strings.TrimSpace(idempotencyKey)
|
||||
if key == "" {
|
||||
return nil, gameSessionRejected("the Idempotency-Key header is required")
|
||||
}
|
||||
if len(key) > gameSessionKeyLimit {
|
||||
return nil, gameSessionRejected("the Idempotency-Key header must be at most %d characters", gameSessionKeyLimit)
|
||||
}
|
||||
customer, err := p.customers.GetCustomer(ctx, customerID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !customer.IsActive {
|
||||
return nil, gameSessionRejected("the customer is not active")
|
||||
}
|
||||
|
||||
walletKey := fmt.Sprintf("game-entry:%s:%s", customerID, key)
|
||||
var session *entities.GameSession
|
||||
replayed := false
|
||||
err = p.tx.WithTransaction(ctx, func(ctx context.Context) error {
|
||||
if err := p.wallet.LockWallet(ctx, customerID); err != nil {
|
||||
return err
|
||||
}
|
||||
previous, err := p.wallet.FindTransaction(ctx, walletKey)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if previous != nil {
|
||||
session, err = p.sessions.GetSessionBySpendTransaction(ctx, previous.ID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if session.GameID != gameID {
|
||||
return gameSessionRejected("this Idempotency-Key was already used to start another game")
|
||||
}
|
||||
replayed = true
|
||||
return nil
|
||||
}
|
||||
|
||||
game, err := p.games.GetGame(ctx, customer.OrganizationID, gameID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if game.Status != constants.GameStatusActive {
|
||||
return gameSessionRejected("the game is not available")
|
||||
}
|
||||
config, err := p.games.GetActiveRewardConfig(ctx, customer.OrganizationID, gameID)
|
||||
if errors.Is(err, repository.ErrGameRewardConfigNotFound) {
|
||||
return gameSessionRejected("the game has no active reward configuration")
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// A reward must name the budget paying for it (D6), so no game starts while
|
||||
// none is set for the period.
|
||||
now := p.now()
|
||||
if _, err := p.budgets.GetGlobalBudgetOn(ctx, customer.OrganizationID, walletDay(now)); err != nil {
|
||||
if errors.Is(err, repository.ErrGameBudgetNotFound) {
|
||||
return gameSessionRejected("no EnakGame budget is set for this period")
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
sessionID := uuid.New()
|
||||
spend, err := p.wallet.Debit(ctx, WalletDebitInput{WalletEntry: WalletEntry{
|
||||
CustomerID: customerID,
|
||||
Currency: constants.WalletCurrencyCoin,
|
||||
Type: constants.WalletTxTypeGameSpend,
|
||||
Amount: game.EntryCost,
|
||||
ReferenceType: constants.WalletRefTypeGameSession,
|
||||
ReferenceID: sessionID,
|
||||
Description: truncateDescription("Main " + game.Name),
|
||||
Metadata: entities.Metadata{"game_id": game.ID.String(), "entry_cost": game.EntryCost},
|
||||
IdempotencyKey: walletKey,
|
||||
}})
|
||||
if errors.Is(err, repository.ErrWalletInsufficientBalance) {
|
||||
return gameSessionRejected("not enough EnakCoin")
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
session = &entities.GameSession{
|
||||
ID: sessionID,
|
||||
OrganizationID: customer.OrganizationID,
|
||||
CustomerID: customerID,
|
||||
GameID: game.ID,
|
||||
RewardConfigID: config.ID,
|
||||
EntryCost: game.EntryCost,
|
||||
Status: constants.GameSessionStatusStarted,
|
||||
StartedAt: now,
|
||||
ExpiresAt: now.Add(time.Duration(game.SessionTTLSeconds) * time.Second),
|
||||
SpendTransactionID: spend.Transaction.ID,
|
||||
}
|
||||
return p.sessions.CreateSession(ctx, session)
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
balances, err := p.spendable.SpendableBalances(ctx, customerID, p.now())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &models.GameSessionStart{
|
||||
SessionID: session.ID,
|
||||
GameID: session.GameID,
|
||||
EntryCost: session.EntryCost,
|
||||
ExpiresAt: session.ExpiresAt,
|
||||
CoinBalance: balances[constants.WalletCurrencyCoin],
|
||||
Replayed: replayed,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// RefundSession gives back the entry cost of a STARTED session, in a transaction of
|
||||
// its own (§7.3, PRD §10.2). It reports false when the session had already left
|
||||
// STARTED, which changes nothing.
|
||||
func (p *GameSessionProcessor) RefundSession(ctx context.Context, organizationID, sessionID uuid.UUID, reason, source string) (bool, error) {
|
||||
refunded := false
|
||||
err := p.tx.WithTransaction(ctx, func(ctx context.Context) error {
|
||||
session, err := p.sessions.GetSession(ctx, organizationID, sessionID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := p.wallet.LockWallet(ctx, session.CustomerID); err != nil {
|
||||
return err
|
||||
}
|
||||
// Read again under the lock: another flow may have finished it meanwhile.
|
||||
if session, err = p.sessions.GetSession(ctx, organizationID, sessionID); err != nil {
|
||||
return err
|
||||
}
|
||||
refunded, err = p.refundLocked(ctx, session, reason, source)
|
||||
return err
|
||||
})
|
||||
if errors.Is(err, errGameSessionMoved) {
|
||||
return false, nil
|
||||
}
|
||||
return refunded, err
|
||||
}
|
||||
|
||||
// refundLocked refunds a session inside the caller's transaction, with the
|
||||
// customer's wallet already locked. The EnakCoin go back to lots that keep the expiry
|
||||
// of those the entry cost was taken from, but last at least seven days (§6.3).
|
||||
//
|
||||
// When the session leaves STARTED between the read and the update, it returns
|
||||
// errGameSessionMoved so the caller rolls the credit back.
|
||||
func (p *GameSessionProcessor) refundLocked(ctx context.Context, session *entities.GameSession, reason, source string) (bool, error) {
|
||||
if session.Status != constants.GameSessionStatusStarted {
|
||||
return false, nil
|
||||
}
|
||||
lots, err := p.wallet.RefundLots(ctx, session.SpendTransactionID)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
spendID := session.SpendTransactionID
|
||||
refund, err := p.wallet.Credit(ctx, WalletCreditInput{
|
||||
WalletEntry: WalletEntry{
|
||||
CustomerID: session.CustomerID,
|
||||
Currency: constants.WalletCurrencyCoin,
|
||||
Type: constants.WalletTxTypeGameSpendRefund,
|
||||
Amount: session.EntryCost,
|
||||
ReferenceType: constants.WalletRefTypeGameSession,
|
||||
ReferenceID: session.ID,
|
||||
ReversesTransactionID: &spendID,
|
||||
Description: "Pengembalian biaya main game",
|
||||
Metadata: entities.Metadata{"game_id": session.GameID.String(), "refund_reason": reason},
|
||||
IdempotencyKey: "game-refund:" + session.ID.String(),
|
||||
},
|
||||
Lots: lots,
|
||||
})
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
now := p.now()
|
||||
moved, err := p.sessions.RefundSession(ctx, session.ID, refund.Transaction.ID, reason, now)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
if !moved {
|
||||
return false, errGameSessionMoved
|
||||
}
|
||||
err = p.audit.Record(ctx, AuditEntry{
|
||||
OrganizationID: session.OrganizationID,
|
||||
ActorType: constants.AuditActorSystem,
|
||||
EntityType: constants.AuditEntityGameSession,
|
||||
EntityID: session.ID,
|
||||
Action: "REFUNDED",
|
||||
Before: map[string]any{"status": constants.GameSessionStatusStarted},
|
||||
After: map[string]any{
|
||||
"status": constants.GameSessionStatusRefunded, "refund_reason": reason,
|
||||
"refund_transaction_id": refund.Transaction.ID, "amount": session.EntryCost,
|
||||
},
|
||||
Reason: &reason,
|
||||
Source: source,
|
||||
})
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
session.Status, session.RefundReason, session.RefundTransactionID, session.EndedAt = constants.GameSessionStatusRefunded, &reason, &refund.Transaction.ID, &now
|
||||
return true, nil
|
||||
}
|
||||
|
||||
// ProcessDueSessions is the session job (§7.3): a STARTED session whose game is no
|
||||
// longer ACTIVE is refunded at once; an expired one is refunded when completing it
|
||||
// failed on a system error, and otherwise only expired, keeping the entry cost.
|
||||
// Each session is handled in its own transaction. It returns how many it refunded and
|
||||
// expired.
|
||||
func (p *GameSessionProcessor) ProcessDueSessions(ctx context.Context) (refunded, expired int, err error) {
|
||||
var failures []error
|
||||
for batch := 0; batch < gameSessionJobBatches; batch++ {
|
||||
due, err := p.sessions.ListDueSessions(ctx, p.now(), gameSessionJobBatch)
|
||||
if err != nil {
|
||||
return refunded, expired, err
|
||||
}
|
||||
changed := 0
|
||||
for _, d := range due {
|
||||
action, err := p.processDue(ctx, d)
|
||||
switch {
|
||||
case err != nil:
|
||||
failures = append(failures, fmt.Errorf("session %s: %w", d.ID, err))
|
||||
logger.NonContext.Error("Game session job failed on a session", err)
|
||||
case action == constants.GameSessionStatusRefunded:
|
||||
refunded++
|
||||
changed++
|
||||
case action == constants.GameSessionStatusExpired:
|
||||
expired++
|
||||
changed++
|
||||
}
|
||||
}
|
||||
// A short batch was the last; a batch where nothing changed would only be
|
||||
// read again.
|
||||
if len(due) < gameSessionJobBatch || changed == 0 {
|
||||
break
|
||||
}
|
||||
}
|
||||
return refunded, expired, errors.Join(failures...)
|
||||
}
|
||||
|
||||
// processDue handles one session and returns the status it moved it to, or "" when it
|
||||
// left it alone.
|
||||
func (p *GameSessionProcessor) processDue(ctx context.Context, d repository.DueGameSession) (string, error) {
|
||||
action := ""
|
||||
err := p.tx.WithTransaction(ctx, func(ctx context.Context) error {
|
||||
if err := p.wallet.LockWallet(ctx, d.CustomerID); err != nil {
|
||||
return err
|
||||
}
|
||||
session, err := p.sessions.GetSession(ctx, d.OrganizationID, d.ID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if session.Status != constants.GameSessionStatusStarted {
|
||||
return nil
|
||||
}
|
||||
game, err := p.games.GetGame(ctx, session.OrganizationID, session.GameID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
now := p.now()
|
||||
reason := ""
|
||||
switch {
|
||||
case game.Status != constants.GameStatusActive:
|
||||
reason = constants.GameSessionRefundGameDeactivated
|
||||
case now.Before(session.ExpiresAt):
|
||||
return nil
|
||||
case session.CompletionFailedAt != nil:
|
||||
reason = constants.GameSessionRefundSystemError
|
||||
default:
|
||||
// Left behind by the customer: no refund (PRD §10.2).
|
||||
moved, err := p.sessions.ExpireSession(ctx, session.ID, now)
|
||||
if moved {
|
||||
action = constants.GameSessionStatusExpired
|
||||
}
|
||||
return err
|
||||
}
|
||||
refunded, err := p.refundLocked(ctx, session, reason, constants.AuditSourceSessionJob)
|
||||
if refunded {
|
||||
action = constants.GameSessionStatusRefunded
|
||||
}
|
||||
return err
|
||||
})
|
||||
if errors.Is(err, errGameSessionMoved) {
|
||||
return "", nil
|
||||
}
|
||||
return action, err
|
||||
}
|
||||
|
||||
// ListGames returns the ACTIVE games of the customer's organization, each with the
|
||||
// events making it pay more right now.
|
||||
func (p *GameSessionProcessor) ListGames(ctx context.Context, customerID uuid.UUID) ([]models.CustomerEnakGame, error) {
|
||||
customer, err := p.customers.GetCustomer(ctx, customerID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
games, _, err := p.games.ListGames(ctx, repository.EnakGameFilter{
|
||||
OrganizationID: customer.OrganizationID, Statuses: []string{constants.GameStatusActive}, Limit: customerGameListLimit,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
events, err := p.events.ActiveEventsByGame(ctx, customer.OrganizationID, p.now())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
configs, err := p.games.ListActiveRewardConfigs(ctx, customer.OrganizationID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
prizes := make(map[uuid.UUID][]models.GamePrize, len(configs))
|
||||
for _, c := range configs {
|
||||
if c.RewardType != constants.GameRewardTypeProbability {
|
||||
continue
|
||||
}
|
||||
// Rules passed Validate when the configuration was made.
|
||||
if list, err := probabilityPrizes(json.RawMessage(c.Rules)); err == nil {
|
||||
prizes[c.GameID] = list
|
||||
}
|
||||
}
|
||||
out := make([]models.CustomerEnakGame, 0, len(games))
|
||||
for _, g := range games {
|
||||
item := models.CustomerEnakGame{
|
||||
ID: g.ID, Name: g.Name, Description: g.Description, ThumbnailURL: g.ThumbnailURL, GameURL: g.GameURL,
|
||||
Version: g.Version, EntryCost: g.EntryCost, SessionTTLSeconds: g.SessionTTLSeconds, Events: []models.CustomerGameEvent{},
|
||||
Prizes: prizes[g.ID],
|
||||
}
|
||||
for _, e := range events[g.ID] {
|
||||
item.Events = append(item.Events, models.CustomerGameEvent{
|
||||
ID: e.ID, Name: e.Name, BannerURL: e.BannerURL, Multiplier: e.Multiplier, Bonus: e.Bonus, EndAt: e.EndAt,
|
||||
})
|
||||
}
|
||||
if g.Slug != nil {
|
||||
item.Slug = *g.Slug
|
||||
}
|
||||
out = append(out, item)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// ListSessions returns a page of the customer's sessions, newest first.
|
||||
func (p *GameSessionProcessor) ListSessions(ctx context.Context, customerID uuid.UUID, page, limit int) (*models.PaginatedResponse[models.CustomerGameSession], error) {
|
||||
page, limit = enakGamePage(page, limit)
|
||||
sessions, total, err := p.sessions.ListCustomerSessions(ctx, customerID, (page-1)*limit, limit)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items := make([]models.CustomerGameSession, 0, len(sessions))
|
||||
for i := range sessions {
|
||||
items = append(items, customerGameSessionModel(&sessions[i]))
|
||||
}
|
||||
return &models.PaginatedResponse[models.CustomerGameSession]{Data: items, Pagination: enakGamePagination(page, limit, total)}, nil
|
||||
}
|
||||
|
||||
// GetSession returns one of the customer's sessions; another customer's is not found.
|
||||
func (p *GameSessionProcessor) GetSession(ctx context.Context, customerID, sessionID uuid.UUID) (*models.CustomerGameSession, error) {
|
||||
session, err := p.sessions.GetCustomerSession(ctx, customerID, sessionID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
m := customerGameSessionModel(session)
|
||||
return &m, nil
|
||||
}
|
||||
|
||||
func customerGameSessionModel(s *entities.GameSession) models.CustomerGameSession {
|
||||
return models.CustomerGameSession{
|
||||
ID: s.ID, GameID: s.GameID, Status: s.Status, EntryCost: s.EntryCost, RewardTotal: s.RewardTotal,
|
||||
StartedAt: s.StartedAt, ExpiresAt: s.ExpiresAt, EndedAt: s.EndedAt, RefundReason: s.RefundReason,
|
||||
}
|
||||
}
|
||||
|
||||
// truncateDescription keeps a ledger description within its 255 characters.
|
||||
func truncateDescription(s string) string {
|
||||
runes := []rune(s)
|
||||
if len(runes) <= 255 {
|
||||
return s
|
||||
}
|
||||
return string(runes[:255])
|
||||
}
|
||||
@@ -0,0 +1,222 @@
|
||||
package processor
|
||||
|
||||
import (
|
||||
"context"
|
||||
"math"
|
||||
"sort"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"apskel-pos-be/internal/constants"
|
||||
"apskel-pos-be/internal/entities"
|
||||
"apskel-pos-be/internal/models"
|
||||
)
|
||||
|
||||
// The kinds of reward component (D6).
|
||||
const (
|
||||
// The game's own reward, paid by the global budget.
|
||||
gameRewardKindBase = "BASE"
|
||||
// What one event adds, paid by the event's budget.
|
||||
gameRewardKindEvent = "EVENT"
|
||||
)
|
||||
|
||||
// The event limits (PRD §35), by the name the breakdown and the response give them.
|
||||
const (
|
||||
gameLimitEvent = "EVENT_LIMIT"
|
||||
gameLimitEventUserDaily = "EVENT_USER_DAILY"
|
||||
)
|
||||
|
||||
// eventLifetimeDay is the day of an event's counter over its whole run (§5.8).
|
||||
var eventLifetimeDay = time.Date(1, 1, 1, 0, 0, 0, 0, time.UTC)
|
||||
|
||||
// eventUserScope is the counter of one customer in one event: a name derived from
|
||||
// both, since a counter has one scope id (§5.8).
|
||||
func eventUserScope(eventID, customerID uuid.UUID) uuid.UUID {
|
||||
return uuid.NewSHA1(eventID, customerID[:])
|
||||
}
|
||||
|
||||
// eventExtra is what an event adds to a base reward: base × (multiplier − 1), rounded
|
||||
// down to whole EnakCoin, plus the bonus. Each event works on the base, so events do
|
||||
// not multiply each other (PRD §16, "controlled stacking").
|
||||
func eventExtra(base int64, e *entities.GameEvent) int64 {
|
||||
var extra int64
|
||||
if e.Multiplier != nil {
|
||||
hundredths := int64(math.Round(*e.Multiplier * 100))
|
||||
extra = base * (hundredths - 100) / 100
|
||||
}
|
||||
if e.Bonus != nil {
|
||||
extra += *e.Bonus
|
||||
}
|
||||
return extra
|
||||
}
|
||||
|
||||
// rewardComponents prices a believed base reward into its parts: the base, capped by
|
||||
// max_reward, then what each active event adds, highest priority first. The cap holds
|
||||
// for the total: what passes it is cut from the lowest priority event first. An event
|
||||
// adds nothing to a play that earned nothing.
|
||||
func rewardComponents(base, maxReward int64, events []entities.GameEvent) ([]gameRewardComponent, bool) {
|
||||
capped := false
|
||||
if maxReward > 0 && base > maxReward {
|
||||
base, capped = maxReward, true
|
||||
}
|
||||
if base <= 0 {
|
||||
return nil, capped
|
||||
}
|
||||
parts := []gameRewardComponent{{Kind: gameRewardKindBase, Earned: base, Amount: base}}
|
||||
total := base
|
||||
for i := range events {
|
||||
e := &events[i]
|
||||
extra := eventExtra(base, e)
|
||||
if extra <= 0 {
|
||||
continue
|
||||
}
|
||||
id := e.ID
|
||||
parts = append(parts, gameRewardComponent{
|
||||
Kind: gameRewardKindEvent, BudgetID: e.BudgetID, EventID: &id, Multiplier: e.Multiplier, Bonus: e.Bonus,
|
||||
Earned: extra, Amount: extra,
|
||||
})
|
||||
total += extra
|
||||
}
|
||||
if maxReward > 0 && total > maxReward {
|
||||
capped = true
|
||||
trimFromEnd(parts, total-maxReward, nil)
|
||||
}
|
||||
return parts, capped
|
||||
}
|
||||
|
||||
// trimFromEnd takes cut off the parts, lowest priority event first and the base last.
|
||||
// release, when given, is told what came off each part.
|
||||
func trimFromEnd(parts []gameRewardComponent, cut int64, release func(*gameRewardComponent, int64) error) error {
|
||||
for i := len(parts) - 1; i >= 0 && cut > 0; i-- {
|
||||
d := parts[i].Amount
|
||||
if d > cut {
|
||||
d = cut
|
||||
}
|
||||
parts[i].Amount -= d
|
||||
cut -= d
|
||||
if release != nil && d > 0 {
|
||||
if err := release(&parts[i], d); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// guardReward runs the parts of a reward through every limit (§9, PRD §35): first
|
||||
// each event's own limits on what it adds, then the daily limits on the total, which
|
||||
// cut events before the base. It returns the limits that cut.
|
||||
//
|
||||
// Counters are taken in one order for every completion (events by id, then user,
|
||||
// game, organization), so no two completions wait on each other the other way round.
|
||||
func (p *GameSessionProcessor) guardReward(ctx context.Context, session *entities.GameSession, game *entities.Game, events []entities.GameEvent,
|
||||
settings *models.OrganizationLoyaltySettings, now time.Time, parts []gameRewardComponent) ([]gameGuardCut, error) {
|
||||
byID := map[uuid.UUID]*entities.GameEvent{}
|
||||
for i := range events {
|
||||
byID[events[i].ID] = &events[i]
|
||||
}
|
||||
day := walletDay(now)
|
||||
order := make([]int, 0, len(parts))
|
||||
for i := range parts {
|
||||
if parts[i].Kind == gameRewardKindEvent {
|
||||
order = append(order, i)
|
||||
}
|
||||
}
|
||||
sort.Slice(order, func(a, b int) bool { return parts[order[a]].EventID.String() < parts[order[b]].EventID.String() })
|
||||
|
||||
var cuts []gameGuardCut
|
||||
for _, i := range order {
|
||||
part := &parts[i]
|
||||
e := byID[*part.EventID]
|
||||
asked := part.Amount
|
||||
lifetime, err := p.counters.Consume(ctx, session.OrganizationID, constants.GameRewardScopeEvent, e.ID, eventLifetimeDay, asked, optionalLimit(e.RewardLimit))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if lifetime < asked {
|
||||
cuts = append(cuts, gameGuardCut{Limit: gameLimitEvent, EventID: part.EventID, Value: optionalLimit(e.RewardLimit), Asked: asked, Allowed: lifetime})
|
||||
part.LimitedBy = append(part.LimitedBy, gameLimitEvent)
|
||||
}
|
||||
perUser, err := p.counters.Consume(ctx, session.OrganizationID, constants.GameRewardScopeEvent, eventUserScope(e.ID, session.CustomerID), day, lifetime, optionalLimit(e.UserDailyLimit))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if perUser < lifetime {
|
||||
cuts = append(cuts, gameGuardCut{Limit: gameLimitEventUserDaily, EventID: part.EventID, Value: optionalLimit(e.UserDailyLimit), Asked: lifetime, Allowed: perUser})
|
||||
part.LimitedBy = append(part.LimitedBy, gameLimitEventUserDaily)
|
||||
if err := p.counters.Release(ctx, session.OrganizationID, constants.GameRewardScopeEvent, e.ID, eventLifetimeDay, lifetime-perUser); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
part.Amount = perUser
|
||||
}
|
||||
|
||||
total := sumComponents(parts)
|
||||
if total == 0 {
|
||||
return cuts, nil
|
||||
}
|
||||
allowed, daily, err := p.applyGuard(ctx, session, game, settings, now, total)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
cuts = append(cuts, daily...)
|
||||
// The event counters took what the daily limits then cut: give it back.
|
||||
err = trimFromEnd(parts, total-allowed, func(part *gameRewardComponent, d int64) error {
|
||||
if part.Kind != gameRewardKindEvent {
|
||||
return nil
|
||||
}
|
||||
if err := p.counters.Release(ctx, session.OrganizationID, constants.GameRewardScopeEvent, *part.EventID, eventLifetimeDay, d); err != nil {
|
||||
return err
|
||||
}
|
||||
return p.counters.Release(ctx, session.OrganizationID, constants.GameRewardScopeEvent, eventUserScope(*part.EventID, session.CustomerID), day, d)
|
||||
})
|
||||
return cuts, err
|
||||
}
|
||||
|
||||
func optionalLimit(limit *int64) int64 {
|
||||
if limit == nil {
|
||||
return 0
|
||||
}
|
||||
return *limit
|
||||
}
|
||||
|
||||
func sumComponents(parts []gameRewardComponent) int64 {
|
||||
var total int64
|
||||
for _, part := range parts {
|
||||
total += part.Amount
|
||||
}
|
||||
return total
|
||||
}
|
||||
|
||||
// rewardParts sums a stored breakdown's components into what the customer sees.
|
||||
func rewardParts(b gameRewardBreakdown) models.GameSessionRewardParts {
|
||||
var out models.GameSessionRewardParts
|
||||
for _, c := range b.Components {
|
||||
if c.Kind == gameRewardKindEvent {
|
||||
out.Event += c.Amount
|
||||
} else {
|
||||
out.Base += c.Amount
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// paymentsByBudget merges the components paid by the same budget, in order, since a
|
||||
// budget pays one ledger row per session (D6).
|
||||
func paymentsByBudget(parts []gameRewardComponent) []gameRewardComponent {
|
||||
var out []gameRewardComponent
|
||||
index := map[uuid.UUID]int{}
|
||||
for _, part := range parts {
|
||||
if part.Amount <= 0 {
|
||||
continue
|
||||
}
|
||||
if i, ok := index[part.BudgetID]; ok {
|
||||
out[i].Amount += part.Amount
|
||||
continue
|
||||
}
|
||||
index[part.BudgetID] = len(out)
|
||||
out = append(out, gameRewardComponent{BudgetID: part.BudgetID, Kind: part.Kind, Amount: part.Amount})
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
package processor
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/stretchr/testify/assert"
|
||||
|
||||
"apskel-pos-be/internal/entities"
|
||||
)
|
||||
|
||||
func gameEvent(multiplier *float64, bonus *int64) entities.GameEvent {
|
||||
return entities.GameEvent{ID: uuid.New(), BudgetID: uuid.New(), Multiplier: multiplier, Bonus: bonus}
|
||||
}
|
||||
|
||||
func amounts(parts []gameRewardComponent) []int64 {
|
||||
out := make([]int64, 0, len(parts))
|
||||
for _, p := range parts {
|
||||
out = append(out, p.Amount)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// PRD §7, §14, §16 with the default stacking rules.
|
||||
func TestRewardComponents(t *testing.T) {
|
||||
ramadan := gameEvent(ptr(2.0), nil)
|
||||
parts, capped := rewardComponents(10, 0, []entities.GameEvent{ramadan})
|
||||
assert.False(t, capped)
|
||||
assert.Equal(t, []int64{10, 10}, amounts(parts), "10 Coin + Ramadan 2x: 10 from the global budget, 10 from the event's")
|
||||
assert.Equal(t, gameRewardKindBase, parts[0].Kind)
|
||||
assert.Equal(t, gameRewardKindEvent, parts[1].Kind)
|
||||
assert.Equal(t, ramadan.BudgetID, parts[1].BudgetID)
|
||||
assert.Equal(t, ramadan.ID, *parts[1].EventID)
|
||||
|
||||
// Each event works on the base: 2x and 1.5x add 10 and 5, they do not compound.
|
||||
// Bonuses are counted on their own.
|
||||
parts, _ = rewardComponents(10, 0, []entities.GameEvent{gameEvent(ptr(2.0), nil), gameEvent(ptr(1.5), ptr(int64(3))), gameEvent(nil, ptr(int64(5)))})
|
||||
assert.Equal(t, []int64{10, 10, 8, 5}, amounts(parts))
|
||||
|
||||
// Rounded down to whole EnakCoin.
|
||||
parts, _ = rewardComponents(3, 0, []entities.GameEvent{gameEvent(ptr(1.5), nil), gameEvent(ptr(1.33), nil)})
|
||||
assert.Equal(t, []int64{3, 1}, amounts(parts), "1.5 adds 1.5 → 1; 1.33 adds 0.99 → 0 and is left out")
|
||||
|
||||
// The cap holds for the total, cutting the lowest priority event first.
|
||||
parts, capped = rewardComponents(10, 22, []entities.GameEvent{gameEvent(ptr(2.0), nil), gameEvent(nil, ptr(int64(5)))})
|
||||
assert.True(t, capped)
|
||||
assert.Equal(t, []int64{10, 10, 2}, amounts(parts))
|
||||
assert.Equal(t, []int64{10, 10, 5}, []int64{parts[0].Earned, parts[1].Earned, parts[2].Earned})
|
||||
parts, _ = rewardComponents(30, 20, []entities.GameEvent{gameEvent(ptr(2.0), nil)})
|
||||
assert.Equal(t, []int64{20, 0}, amounts(parts), "a base at the cap leaves events nothing")
|
||||
|
||||
// Nothing earned, nothing added: a bonus needs a play that earned.
|
||||
parts, _ = rewardComponents(0, 0, []entities.GameEvent{gameEvent(nil, ptr(int64(5)))})
|
||||
assert.Empty(t, parts)
|
||||
|
||||
// Events paid by the same budget pay one ledger row.
|
||||
shared := uuid.New()
|
||||
a, b := gameEvent(nil, ptr(int64(2))), gameEvent(nil, ptr(int64(3)))
|
||||
a.BudgetID, b.BudgetID = shared, shared
|
||||
parts, _ = rewardComponents(10, 0, []entities.GameEvent{a, b})
|
||||
parts[0].BudgetID = uuid.New()
|
||||
payments := paymentsByBudget(parts)
|
||||
assert.Len(t, payments, 2)
|
||||
assert.EqualValues(t, 5, payments[1].Amount)
|
||||
}
|
||||
@@ -260,7 +260,8 @@ func outletLoyaltyFields(s *models.OutletLoyaltySettings) []loyaltyField {
|
||||
}
|
||||
}
|
||||
|
||||
// organizationLoyaltyFields describes every organization key (F2, F12), bound to s.
|
||||
// organizationLoyaltyFields describes every organization key (F2, F12, and the EnakGame
|
||||
// limits of docs/rfc-enakgame.md §5.10), bound to s.
|
||||
func organizationLoyaltyFields(s *models.OrganizationLoyaltySettings) []loyaltyField {
|
||||
fields := []loyaltyField{
|
||||
intLoyaltyField(constants.LoyaltyPointValueKey, &s.PointValue, constants.LoyaltyPointValueDefault, 1, noLoyaltyMax),
|
||||
@@ -270,6 +271,8 @@ func organizationLoyaltyFields(s *models.OrganizationLoyaltySettings) []loyaltyF
|
||||
intLoyaltyField(constants.LoyaltyTransferMinAmountKey, &s.Transfer.MinAmount, constants.LoyaltyTransferMinAmountDefault, 1, noLoyaltyMax),
|
||||
optionalIntLoyaltyField(constants.LoyaltyTransferMaxPerTransactionKey, &s.Transfer.MaxPerTransaction, 1),
|
||||
optionalIntLoyaltyField(constants.LoyaltyTransferDailyLimitKey, &s.Transfer.DailyLimit, 1),
|
||||
intLoyaltyField(constants.EnakGameLimitUserDailyKey, &s.EnakGame.UserDailyLimit, 0, 0, noLoyaltyMax),
|
||||
intLoyaltyField(constants.EnakGameLimitGlobalDailyKey, &s.EnakGame.GlobalDailyLimit, 0, 0, noLoyaltyMax),
|
||||
}
|
||||
fields = append(fields, expiryLoyaltyFields("loyalty.point.", &s.PointExpiry)...)
|
||||
return append(fields, expiryLoyaltyFields("loyalty.coin.", &s.CoinExpiry)...)
|
||||
|
||||
@@ -123,6 +123,7 @@ func TestLoyaltySettings_OrganizationWithoutSettingsGetsEveryDefault(t *testing.
|
||||
Transfer: models.LoyaltyTransferSettings{Enabled: true, MinAmount: 1},
|
||||
PointExpiry: expiry,
|
||||
CoinExpiry: expiry,
|
||||
EnakGame: models.EnakGameLimitSettings{UserDailyLimit: 0, GlobalDailyLimit: 0},
|
||||
}, *s)
|
||||
}
|
||||
|
||||
@@ -261,6 +262,7 @@ func TestLoyaltySettings_UpdateOrganization(t *testing.T) {
|
||||
settings.PointValue = 100
|
||||
settings.CoinExpiry.Enabled = true
|
||||
settings.CoinExpiry.Unit = constants.LoyaltyExpiryUnitDay
|
||||
settings.EnakGame.UserDailyLimit = 50
|
||||
|
||||
changes, _, err := p.UpdateOrganization(ctx, org, admin, *settings)
|
||||
require.NoError(t, err)
|
||||
@@ -269,11 +271,14 @@ func TestLoyaltySettings_UpdateOrganization(t *testing.T) {
|
||||
keys = append(keys, c.Key)
|
||||
assert.Nil(t, c.OutletID, "organization settings have no outlet")
|
||||
}
|
||||
assert.ElementsMatch(t, []string{constants.LoyaltyPointValueKey, "loyalty.coin.expiry_enabled", "loyalty.coin.expiry_unit"}, keys)
|
||||
assert.ElementsMatch(t, []string{constants.LoyaltyPointValueKey, "loyalty.coin.expiry_enabled", "loyalty.coin.expiry_unit", "enakgame.limit.user_daily"}, keys)
|
||||
|
||||
value, err := p.PointValue(ctx, org)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, int64(100), value)
|
||||
saved, err := p.Organization(ctx, org)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, models.EnakGameLimitSettings{UserDailyLimit: 50, GlobalDailyLimit: 0}, saved.EnakGame)
|
||||
}
|
||||
|
||||
func TestLoyaltySettings_UpdateRejectsInvalidValues(t *testing.T) {
|
||||
@@ -312,6 +317,8 @@ func TestLoyaltySettings_UpdateRejectsInvalidValues(t *testing.T) {
|
||||
"fixed date 13-01": func(s *models.OrganizationLoyaltySettings) { s.PointExpiry.FixedDates = []string{"13-01"} },
|
||||
"fixed date 02-29": func(s *models.OrganizationLoyaltySettings) { s.CoinExpiry.FixedDates = []string{"02-29"} },
|
||||
"negative grace": func(s *models.OrganizationLoyaltySettings) { s.CoinExpiry.GraceMonths = -1 },
|
||||
"negative user daily": func(s *models.OrganizationLoyaltySettings) { s.EnakGame.UserDailyLimit = -1 },
|
||||
"negative global daily": func(s *models.OrganizationLoyaltySettings) { s.EnakGame.GlobalDailyLimit = -1 },
|
||||
} {
|
||||
s, err := p.Organization(ctx, org)
|
||||
require.NoError(t, err)
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
package processor
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"apskel-pos-be/internal/entities"
|
||||
)
|
||||
|
||||
// ValidateResult checks a result against a game's result_rules (docs/rfc-enakgame.md
|
||||
// §7.2 step 5) and returns why it is not believable, or nil when it is. A rule left
|
||||
// out does not apply, so a game without result_rules accepts every result.
|
||||
//
|
||||
// A failed result is not an error: the session completes, earns nothing and is
|
||||
// flagged, with these reasons in its reward_breakdown.
|
||||
func ValidateResult(rules entities.GameResultRules, result SessionResult, startedAt, submittedAt time.Time) []string {
|
||||
var reasons []string
|
||||
elapsed := submittedAt.Sub(startedAt).Seconds()
|
||||
if rules.MinDurationSeconds != nil && elapsed < float64(*rules.MinDurationSeconds) {
|
||||
reasons = append(reasons, fmt.Sprintf("played %.0f seconds, under the minimum of %d", elapsed, *rules.MinDurationSeconds))
|
||||
}
|
||||
if result.Score != nil {
|
||||
score := *result.Score
|
||||
if score < 0 {
|
||||
reasons = append(reasons, "score cannot be negative")
|
||||
}
|
||||
if rules.MaxScore != nil && score > *rules.MaxScore {
|
||||
reasons = append(reasons, fmt.Sprintf("score %d is above the maximum of %d", score, *rules.MaxScore))
|
||||
}
|
||||
if rules.MaxScorePerSecond != nil && score > 0 {
|
||||
// A score with no time played at all is never believable.
|
||||
if elapsed <= 0 || float64(score)/elapsed > *rules.MaxScorePerSecond {
|
||||
reasons = append(reasons, fmt.Sprintf("score %d in %.0f seconds is above %g per second", score, elapsed, *rules.MaxScorePerSecond))
|
||||
}
|
||||
}
|
||||
}
|
||||
if result.Outcome != nil && len(rules.Outcomes) > 0 && !containsString(rules.Outcomes, *result.Outcome) {
|
||||
reasons = append(reasons, fmt.Sprintf("unknown outcome %q", *result.Outcome))
|
||||
}
|
||||
return reasons
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package processor
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
|
||||
"apskel-pos-be/internal/entities"
|
||||
)
|
||||
|
||||
func TestValidateResult(t *testing.T) {
|
||||
start := time.Date(2026, 10, 7, 12, 0, 0, 0, time.UTC)
|
||||
after := func(seconds int) time.Time { return start.Add(time.Duration(seconds) * time.Second) }
|
||||
score := func(v int64) *int64 { return &v }
|
||||
outcome := func(v string) *string { return &v }
|
||||
rules := entities.GameResultRules{
|
||||
MaxScore: score(1000),
|
||||
MinDurationSeconds: score(10),
|
||||
MaxScorePerSecond: ptr(20.0),
|
||||
Outcomes: []string{"WIN", "LOSE"},
|
||||
}
|
||||
|
||||
for name, tc := range map[string]struct {
|
||||
rules entities.GameResultRules
|
||||
result SessionResult
|
||||
elapsed int
|
||||
reasons int
|
||||
}{
|
||||
"no rules accept anything": {entities.GameResultRules{}, SessionResult{Score: score(999999), Outcome: outcome("ANY")}, 0, 0},
|
||||
"within every rule": {rules, SessionResult{Score: score(1000), Outcome: outcome("WIN")}, 60, 0},
|
||||
"no score, no outcome": {rules, SessionResult{}, 10, 0},
|
||||
"too short": {rules, SessionResult{}, 9, 1},
|
||||
"score above max": {rules, SessionResult{Score: score(1001)}, 600, 1},
|
||||
"too fast": {rules, SessionResult{Score: score(201)}, 10, 1},
|
||||
"exactly the per-second cap": {rules, SessionResult{Score: score(200)}, 10, 0},
|
||||
"negative score": {rules, SessionResult{Score: score(-1)}, 60, 1},
|
||||
"unknown outcome": {rules, SessionResult{Outcome: outcome("DRAW")}, 60, 1},
|
||||
"zero time, some score": {entities.GameResultRules{MaxScorePerSecond: ptr(5.0)}, SessionResult{Score: score(1)}, 0, 1},
|
||||
"zero time, zero score": {entities.GameResultRules{MaxScorePerSecond: ptr(5.0)}, SessionResult{Score: score(0)}, 0, 0},
|
||||
"every rule broken": {rules, SessionResult{Score: score(5000), Outcome: outcome("DRAW")}, 1, 4},
|
||||
} {
|
||||
reasons := ValidateResult(tc.rules, tc.result, start, after(tc.elapsed))
|
||||
assert.Len(t, reasons, tc.reasons, "%s: %v", name, reasons)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,463 @@
|
||||
package processor
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/rand"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"math"
|
||||
"math/big"
|
||||
"strings"
|
||||
|
||||
"apskel-pos-be/internal/constants"
|
||||
"apskel-pos-be/internal/models"
|
||||
)
|
||||
|
||||
var (
|
||||
// ErrInvalidRewardRules means a reward configuration's rules do not fit its type
|
||||
// (docs/rfc-enakgame.md §8). Checked when the configuration is created.
|
||||
ErrInvalidRewardRules = errors.New("invalid reward rules")
|
||||
// ErrRewardResultUnusable means a result lacks what the rules need to price it: no
|
||||
// score for SCORE_BASED, an outcome the rules do not list, a score outside every
|
||||
// band. The session earns nothing and is flagged.
|
||||
ErrRewardResultUnusable = errors.New("result cannot be rewarded")
|
||||
)
|
||||
|
||||
// rewardWeightLimit bounds the total weight of a PROBABILITY table, far below where
|
||||
// the sum could overflow.
|
||||
const rewardWeightLimit = int64(1_000_000_000_000)
|
||||
|
||||
// SessionResult is what the client reports about a play: data only, never a reward
|
||||
// amount (P1).
|
||||
type SessionResult struct {
|
||||
Score *int64 `json:"score,omitempty"`
|
||||
Outcome *string `json:"outcome,omitempty"`
|
||||
}
|
||||
|
||||
// RewardRNG draws the random number of a PROBABILITY reward.
|
||||
type RewardRNG interface {
|
||||
// Int63n returns a uniform number in [0, n).
|
||||
Int63n(n int64) (int64, error)
|
||||
}
|
||||
|
||||
// CryptoRewardRNG draws from crypto/rand, so the outcome cannot be predicted from the
|
||||
// time the way a reseeded math/rand can (§8).
|
||||
type CryptoRewardRNG struct{}
|
||||
|
||||
func (CryptoRewardRNG) Int63n(n int64) (int64, error) {
|
||||
v, err := rand.Int(rand.Reader, big.NewInt(n))
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return v.Int64(), nil
|
||||
}
|
||||
|
||||
// RewardCalculator computes the base reward of one reward type (§8). Base rewards are
|
||||
// whole EnakCoin; event modifiers and the max_reward cap come after.
|
||||
type RewardCalculator interface {
|
||||
// Validate checks rules when a configuration is created.
|
||||
Validate(rules json.RawMessage) error
|
||||
// Calculate prices a result under rules that passed Validate. detail says how the
|
||||
// amount was reached, for reward_breakdown.
|
||||
Calculate(rules json.RawMessage, result SessionResult, rng RewardRNG) (base int64, detail map[string]any, err error)
|
||||
// Scale multiplies every amount in rules by multiplier/10000, rounded down, for
|
||||
// the Budget Controller (§10). Everything else, such as score bands and weights,
|
||||
// stays.
|
||||
Scale(rules json.RawMessage, multiplier int64) (json.RawMessage, error)
|
||||
}
|
||||
|
||||
// rewardMultiplierOne is a multiplier of 1 in the ten-thousandths Scale takes.
|
||||
const rewardMultiplierOne = int64(10_000)
|
||||
|
||||
// scaleRewardAmount is amount × multiplier/10000, rounded down (RFC §19.2 #1).
|
||||
func scaleRewardAmount(amount, multiplier int64) (int64, error) {
|
||||
if multiplier < 0 {
|
||||
return 0, invalidRules("multiplier cannot be negative")
|
||||
}
|
||||
if amount != 0 && multiplier > math.MaxInt64/amount {
|
||||
return 0, invalidRules("amount %d is too large to scale", amount)
|
||||
}
|
||||
return amount * multiplier / rewardMultiplierOne, nil
|
||||
}
|
||||
|
||||
func scaleRewardAmounts(multiplier int64, amounts ...*int64) error {
|
||||
for _, a := range amounts {
|
||||
scaled, err := scaleRewardAmount(*a, multiplier)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
*a = scaled
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func marshalRules(v any) (json.RawMessage, error) {
|
||||
b, err := json.Marshal(v)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return b, nil
|
||||
}
|
||||
|
||||
var rewardCalculators = map[string]RewardCalculator{
|
||||
constants.GameRewardTypeFixed: fixedReward{},
|
||||
constants.GameRewardTypeScoreBased: scoreBasedReward{},
|
||||
constants.GameRewardTypeOutcomeBased: outcomeBasedReward{},
|
||||
constants.GameRewardTypeProbability: probabilityReward{},
|
||||
}
|
||||
|
||||
// RewardCalculatorFor returns the calculator of a reward type.
|
||||
func RewardCalculatorFor(rewardType string) (RewardCalculator, error) {
|
||||
c, ok := rewardCalculators[rewardType]
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("%w: unknown reward type %q", ErrInvalidRewardRules, rewardType)
|
||||
}
|
||||
return c, nil
|
||||
}
|
||||
|
||||
func invalidRules(format string, args ...any) error {
|
||||
return fmt.Errorf("%w: %s", ErrInvalidRewardRules, fmt.Sprintf(format, args...))
|
||||
}
|
||||
|
||||
func unusableResult(format string, args ...any) error {
|
||||
return fmt.Errorf("%w: %s", ErrRewardResultUnusable, fmt.Sprintf(format, args...))
|
||||
}
|
||||
|
||||
// decodeRules reads rules strictly: an unknown field is a typo, not something to
|
||||
// ignore.
|
||||
func decodeRules(rules json.RawMessage, v any) error {
|
||||
dec := json.NewDecoder(bytes.NewReader(rules))
|
||||
dec.DisallowUnknownFields()
|
||||
if err := dec.Decode(v); err != nil {
|
||||
return invalidRules("%v", err)
|
||||
}
|
||||
if _, err := dec.Token(); err != io.EOF {
|
||||
return invalidRules("unexpected data after the rules")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// FIXED: {"amount": 5}.
|
||||
type fixedReward struct{}
|
||||
|
||||
type fixedRules struct {
|
||||
Amount *int64 `json:"amount"`
|
||||
}
|
||||
|
||||
func (fixedReward) parse(rules json.RawMessage) (fixedRules, error) {
|
||||
var r fixedRules
|
||||
if err := decodeRules(rules, &r); err != nil {
|
||||
return r, err
|
||||
}
|
||||
if r.Amount == nil || *r.Amount < 0 {
|
||||
return r, invalidRules("amount must be 0 or more")
|
||||
}
|
||||
return r, nil
|
||||
}
|
||||
|
||||
func (f fixedReward) Validate(rules json.RawMessage) error {
|
||||
_, err := f.parse(rules)
|
||||
return err
|
||||
}
|
||||
|
||||
func (f fixedReward) Calculate(rules json.RawMessage, _ SessionResult, _ RewardRNG) (int64, map[string]any, error) {
|
||||
r, err := f.parse(rules)
|
||||
if err != nil {
|
||||
return 0, nil, err
|
||||
}
|
||||
return *r.Amount, map[string]any{"reward_type": constants.GameRewardTypeFixed}, nil
|
||||
}
|
||||
|
||||
func (f fixedReward) Scale(rules json.RawMessage, multiplier int64) (json.RawMessage, error) {
|
||||
r, err := f.parse(rules)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := scaleRewardAmounts(multiplier, r.Amount); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return marshalRules(r)
|
||||
}
|
||||
|
||||
// SCORE_BASED: {"bands": [{"min": 0, "max": 100, "amount": 1}, {"min": 101, "amount": 20}]}.
|
||||
// Bands run in order from 0, each starting right after the previous one ends; only the
|
||||
// last may leave max out, to cover every higher score.
|
||||
type scoreBasedReward struct{}
|
||||
|
||||
type scoreBand struct {
|
||||
Min *int64 `json:"min"`
|
||||
// Left out of the last band, also when scaled rules are written back.
|
||||
Max *int64 `json:"max,omitempty"`
|
||||
Amount *int64 `json:"amount"`
|
||||
}
|
||||
|
||||
type scoreRules struct {
|
||||
Bands []scoreBand `json:"bands"`
|
||||
}
|
||||
|
||||
func (scoreBasedReward) parse(rules json.RawMessage) (scoreRules, error) {
|
||||
var r scoreRules
|
||||
if err := decodeRules(rules, &r); err != nil {
|
||||
return r, err
|
||||
}
|
||||
if len(r.Bands) == 0 {
|
||||
return r, invalidRules("at least one band is required")
|
||||
}
|
||||
for i, b := range r.Bands {
|
||||
if b.Min == nil || b.Amount == nil {
|
||||
return r, invalidRules("band %d needs min and amount", i+1)
|
||||
}
|
||||
if *b.Amount < 0 {
|
||||
return r, invalidRules("band %d amount must be 0 or more", i+1)
|
||||
}
|
||||
if b.Max != nil && *b.Max < *b.Min {
|
||||
return r, invalidRules("band %d max is below its min", i+1)
|
||||
}
|
||||
if i == 0 {
|
||||
if *b.Min != 0 {
|
||||
return r, invalidRules("the first band must start at 0")
|
||||
}
|
||||
continue
|
||||
}
|
||||
prev := r.Bands[i-1]
|
||||
if prev.Max == nil {
|
||||
return r, invalidRules("only the last band may leave max out")
|
||||
}
|
||||
switch {
|
||||
case *b.Min <= *prev.Max:
|
||||
return r, invalidRules("band %d overlaps band %d", i+1, i)
|
||||
case *b.Min > *prev.Max+1:
|
||||
return r, invalidRules("scores %d to %d are in no band", *prev.Max+1, *b.Min-1)
|
||||
}
|
||||
}
|
||||
return r, nil
|
||||
}
|
||||
|
||||
func (s scoreBasedReward) Validate(rules json.RawMessage) error {
|
||||
_, err := s.parse(rules)
|
||||
return err
|
||||
}
|
||||
|
||||
func (s scoreBasedReward) Calculate(rules json.RawMessage, result SessionResult, _ RewardRNG) (int64, map[string]any, error) {
|
||||
r, err := s.parse(rules)
|
||||
if err != nil {
|
||||
return 0, nil, err
|
||||
}
|
||||
if result.Score == nil {
|
||||
return 0, nil, unusableResult("a score is required")
|
||||
}
|
||||
score := *result.Score
|
||||
for i, b := range r.Bands {
|
||||
if score >= *b.Min && (b.Max == nil || score <= *b.Max) {
|
||||
return *b.Amount, map[string]any{"reward_type": constants.GameRewardTypeScoreBased, "score": score, "band": i + 1}, nil
|
||||
}
|
||||
}
|
||||
return 0, nil, unusableResult("score %d is in no band", score)
|
||||
}
|
||||
|
||||
func (s scoreBasedReward) Scale(rules json.RawMessage, multiplier int64) (json.RawMessage, error) {
|
||||
r, err := s.parse(rules)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, b := range r.Bands {
|
||||
if err := scaleRewardAmounts(multiplier, b.Amount); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return marshalRules(r)
|
||||
}
|
||||
|
||||
// OUTCOME_BASED: {"outcomes": {"PERFECT": 20, "GOOD": 10, "FAIL": 0}}.
|
||||
type outcomeBasedReward struct{}
|
||||
|
||||
type outcomeRules struct {
|
||||
Outcomes map[string]int64 `json:"outcomes"`
|
||||
}
|
||||
|
||||
func (outcomeBasedReward) parse(rules json.RawMessage) (outcomeRules, error) {
|
||||
var r outcomeRules
|
||||
if err := decodeRules(rules, &r); err != nil {
|
||||
return r, err
|
||||
}
|
||||
if len(r.Outcomes) == 0 {
|
||||
return r, invalidRules("at least one outcome is required")
|
||||
}
|
||||
for outcome, amount := range r.Outcomes {
|
||||
if strings.TrimSpace(outcome) == "" {
|
||||
return r, invalidRules("an outcome needs a name")
|
||||
}
|
||||
if amount < 0 {
|
||||
return r, invalidRules("outcome %s amount must be 0 or more", outcome)
|
||||
}
|
||||
}
|
||||
return r, nil
|
||||
}
|
||||
|
||||
func (o outcomeBasedReward) Validate(rules json.RawMessage) error {
|
||||
_, err := o.parse(rules)
|
||||
return err
|
||||
}
|
||||
|
||||
func (o outcomeBasedReward) Calculate(rules json.RawMessage, result SessionResult, _ RewardRNG) (int64, map[string]any, error) {
|
||||
r, err := o.parse(rules)
|
||||
if err != nil {
|
||||
return 0, nil, err
|
||||
}
|
||||
if result.Outcome == nil {
|
||||
return 0, nil, unusableResult("an outcome is required")
|
||||
}
|
||||
amount, ok := r.Outcomes[*result.Outcome]
|
||||
if !ok {
|
||||
return 0, nil, unusableResult("unknown outcome %q", *result.Outcome)
|
||||
}
|
||||
return amount, map[string]any{"reward_type": constants.GameRewardTypeOutcomeBased, "outcome": *result.Outcome}, nil
|
||||
}
|
||||
|
||||
func (o outcomeBasedReward) Scale(rules json.RawMessage, multiplier int64) (json.RawMessage, error) {
|
||||
r, err := o.parse(rules)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for outcome, amount := range r.Outcomes {
|
||||
scaled, err := scaleRewardAmount(amount, multiplier)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
r.Outcomes[outcome] = scaled
|
||||
}
|
||||
return marshalRules(r)
|
||||
}
|
||||
|
||||
// PROBABILITY: {"table": [{"weight": 1, "amount": 1000}, {"weight": 999, "amount": 0}]}.
|
||||
// Weights are whole numbers, so no check depends on floating point (§8). The draw is
|
||||
// kept in the detail for audit. An entry may carry a label, such as a spin wheel's
|
||||
// segment ("Zonk", "Jackpot"); the customer sees the entries and the one drawn, never
|
||||
// the weights.
|
||||
type probabilityReward struct{}
|
||||
|
||||
// probabilityLabelLimit bounds a label's length.
|
||||
const probabilityLabelLimit = 100
|
||||
|
||||
type probabilityEntry struct {
|
||||
Weight *int64 `json:"weight"`
|
||||
Amount *int64 `json:"amount"`
|
||||
Label *string `json:"label,omitempty"`
|
||||
}
|
||||
|
||||
type probabilityRules struct {
|
||||
Table []probabilityEntry `json:"table"`
|
||||
}
|
||||
|
||||
func (probabilityReward) parse(rules json.RawMessage) (probabilityRules, int64, error) {
|
||||
var r probabilityRules
|
||||
if err := decodeRules(rules, &r); err != nil {
|
||||
return r, 0, err
|
||||
}
|
||||
if len(r.Table) == 0 {
|
||||
return r, 0, invalidRules("at least one entry is required")
|
||||
}
|
||||
var total int64
|
||||
for i, e := range r.Table {
|
||||
if e.Weight == nil || e.Amount == nil {
|
||||
return r, 0, invalidRules("entry %d needs weight and amount", i+1)
|
||||
}
|
||||
if *e.Weight < 1 {
|
||||
return r, 0, invalidRules("entry %d weight must be at least 1", i+1)
|
||||
}
|
||||
if *e.Amount < 0 {
|
||||
return r, 0, invalidRules("entry %d amount must be 0 or more", i+1)
|
||||
}
|
||||
if e.Label != nil && (strings.TrimSpace(*e.Label) == "" || len(*e.Label) > probabilityLabelLimit) {
|
||||
return r, 0, invalidRules("entry %d label must not be empty, at most %d characters", i+1, probabilityLabelLimit)
|
||||
}
|
||||
total += *e.Weight
|
||||
if total > rewardWeightLimit {
|
||||
return r, 0, invalidRules("the weights add up to more than %d", rewardWeightLimit)
|
||||
}
|
||||
}
|
||||
return r, total, nil
|
||||
}
|
||||
|
||||
func (p probabilityReward) Validate(rules json.RawMessage) error {
|
||||
_, _, err := p.parse(rules)
|
||||
return err
|
||||
}
|
||||
|
||||
func (p probabilityReward) Calculate(rules json.RawMessage, _ SessionResult, rng RewardRNG) (int64, map[string]any, error) {
|
||||
r, total, err := p.parse(rules)
|
||||
if err != nil {
|
||||
return 0, nil, err
|
||||
}
|
||||
roll, err := rng.Int63n(total)
|
||||
if err != nil {
|
||||
return 0, nil, fmt.Errorf("failed to draw a reward: %w", err)
|
||||
}
|
||||
cumulative := int64(0)
|
||||
for i, e := range r.Table {
|
||||
cumulative += *e.Weight
|
||||
if roll < cumulative {
|
||||
detail := map[string]any{
|
||||
"reward_type": constants.GameRewardTypeProbability, "roll": roll, "total_weight": total, "entry": i + 1,
|
||||
}
|
||||
if e.Label != nil {
|
||||
detail["label"] = *e.Label
|
||||
}
|
||||
return *e.Amount, detail, nil
|
||||
}
|
||||
}
|
||||
return 0, nil, fmt.Errorf("draw %d is outside the total weight %d", roll, total)
|
||||
}
|
||||
|
||||
// Scale changes the prizes, not their odds.
|
||||
func (p probabilityReward) Scale(rules json.RawMessage, multiplier int64) (json.RawMessage, error) {
|
||||
r, _, err := p.parse(rules)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, e := range r.Table {
|
||||
if err := scaleRewardAmounts(multiplier, e.Amount); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return marshalRules(r)
|
||||
}
|
||||
|
||||
// probabilityPrizes lists the entries of PROBABILITY rules as the customer sees them:
|
||||
// in order, without their weights.
|
||||
func probabilityPrizes(rules json.RawMessage) ([]models.GamePrize, error) {
|
||||
r, _, err := probabilityReward{}.parse(rules)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
prizes := make([]models.GamePrize, 0, len(r.Table))
|
||||
for i, e := range r.Table {
|
||||
prizes = append(prizes, models.GamePrize{Entry: i + 1, Label: e.Label, Amount: *e.Amount})
|
||||
}
|
||||
return prizes, nil
|
||||
}
|
||||
|
||||
// drawnPrize is the entry a PROBABILITY reward drew, read back from its detail; nil
|
||||
// for another type or when nothing was drawn.
|
||||
func drawnPrize(rewardType string, base int64, detail map[string]any) *models.GamePrize {
|
||||
if rewardType != constants.GameRewardTypeProbability {
|
||||
return nil
|
||||
}
|
||||
// A number read back from JSON is a float64; one just drawn is an int.
|
||||
var entry int
|
||||
switch v := detail["entry"].(type) {
|
||||
case int:
|
||||
entry = v
|
||||
case float64:
|
||||
entry = int(v)
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
prize := &models.GamePrize{Entry: entry, Amount: base}
|
||||
if label, ok := detail["label"].(string); ok {
|
||||
prize.Label = &label
|
||||
}
|
||||
return prize
|
||||
}
|
||||
@@ -0,0 +1,229 @@
|
||||
package processor
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"math"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"apskel-pos-be/internal/constants"
|
||||
"apskel-pos-be/internal/models"
|
||||
)
|
||||
|
||||
// fixedRNG returns the given draws in turn.
|
||||
type fixedRNG struct{ draws []int64 }
|
||||
|
||||
func (r *fixedRNG) Int63n(n int64) (int64, error) {
|
||||
v := r.draws[0]
|
||||
r.draws = r.draws[1:]
|
||||
return v % n, nil
|
||||
}
|
||||
|
||||
func calculate(t *testing.T, rewardType, rules string, result SessionResult, rng RewardRNG) (int64, map[string]any, error) {
|
||||
t.Helper()
|
||||
c, err := RewardCalculatorFor(rewardType)
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, c.Validate(json.RawMessage(rules)), "the example rules are valid")
|
||||
return c.Calculate(json.RawMessage(rules), result, rng)
|
||||
}
|
||||
|
||||
// The examples of docs/enakgame-prd.md §12.
|
||||
func TestRewardCalculator_PRDExamples(t *testing.T) {
|
||||
t.Run("FIXED", func(t *testing.T) {
|
||||
base, _, err := calculate(t, constants.GameRewardTypeFixed, `{"amount": 5}`, SessionResult{}, nil)
|
||||
require.NoError(t, err)
|
||||
assert.EqualValues(t, 5, base)
|
||||
})
|
||||
|
||||
t.Run("SCORE_BASED", func(t *testing.T) {
|
||||
rules := `{"bands": [
|
||||
{"min": 0, "max": 100, "amount": 1},
|
||||
{"min": 101, "max": 500, "amount": 5},
|
||||
{"min": 501, "max": 1000, "amount": 10},
|
||||
{"min": 1001, "amount": 20}]}`
|
||||
for score, want := range map[int64]int64{0: 1, 100: 1, 101: 5, 500: 5, 501: 10, 1000: 10, 1001: 20, 99999: 20} {
|
||||
score := score
|
||||
base, detail, err := calculate(t, constants.GameRewardTypeScoreBased, rules, SessionResult{Score: &score}, nil)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, want, base, "score %d", score)
|
||||
assert.Equal(t, score, detail["score"])
|
||||
}
|
||||
negative := int64(-1)
|
||||
_, _, err := calculate(t, constants.GameRewardTypeScoreBased, rules, SessionResult{Score: &negative}, nil)
|
||||
assert.ErrorIs(t, err, ErrRewardResultUnusable)
|
||||
_, _, err = calculate(t, constants.GameRewardTypeScoreBased, rules, SessionResult{}, nil)
|
||||
assert.ErrorIs(t, err, ErrRewardResultUnusable, "no score")
|
||||
capped := `{"bands": [{"min": 0, "max": 10, "amount": 1}]}`
|
||||
over := int64(11)
|
||||
_, _, err = calculate(t, constants.GameRewardTypeScoreBased, capped, SessionResult{Score: &over}, nil)
|
||||
assert.ErrorIs(t, err, ErrRewardResultUnusable, "above the last band's max")
|
||||
})
|
||||
|
||||
t.Run("OUTCOME_BASED", func(t *testing.T) {
|
||||
rules := `{"outcomes": {"PERFECT": 20, "GOOD": 10, "NORMAL": 5, "FAIL": 0}}`
|
||||
for outcome, want := range map[string]int64{"PERFECT": 20, "GOOD": 10, "NORMAL": 5, "FAIL": 0} {
|
||||
outcome := outcome
|
||||
base, detail, err := calculate(t, constants.GameRewardTypeOutcomeBased, rules, SessionResult{Outcome: &outcome}, nil)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, want, base, outcome)
|
||||
assert.Equal(t, outcome, detail["outcome"])
|
||||
}
|
||||
unknown := "LEGENDARY"
|
||||
_, _, err := calculate(t, constants.GameRewardTypeOutcomeBased, rules, SessionResult{Outcome: &unknown}, nil)
|
||||
assert.ErrorIs(t, err, ErrRewardResultUnusable)
|
||||
})
|
||||
|
||||
t.Run("PROBABILITY", func(t *testing.T) {
|
||||
// 0.1% 1000, 1% 100, 10% 10, 88.9% 0, as whole weights out of 1000.
|
||||
rules := `{"table": [{"weight": 1, "amount": 1000}, {"weight": 10, "amount": 100}, {"weight": 100, "amount": 10}, {"weight": 889, "amount": 0}]}`
|
||||
for roll, want := range map[int64]int64{0: 1000, 1: 100, 10: 100, 11: 10, 110: 10, 111: 0, 999: 0} {
|
||||
base, detail, err := calculate(t, constants.GameRewardTypeProbability, rules, SessionResult{}, &fixedRNG{draws: []int64{roll}})
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, want, base, "roll %d", roll)
|
||||
assert.Equal(t, roll, detail["roll"], "the draw is kept for audit")
|
||||
assert.EqualValues(t, 1000, detail["total_weight"])
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestRewardCalculator_ProbabilityDistribution(t *testing.T) {
|
||||
rules := json.RawMessage(`{"table": [{"weight": 1, "amount": 1000}, {"weight": 10, "amount": 100}, {"weight": 100, "amount": 10}, {"weight": 889, "amount": 0}]}`)
|
||||
c, err := RewardCalculatorFor(constants.GameRewardTypeProbability)
|
||||
require.NoError(t, err)
|
||||
|
||||
const draws = 100_000
|
||||
counts := map[int64]int{}
|
||||
for i := 0; i < draws; i++ {
|
||||
base, _, err := c.Calculate(rules, SessionResult{}, CryptoRewardRNG{})
|
||||
require.NoError(t, err)
|
||||
counts[base]++
|
||||
}
|
||||
// Within five standard deviations of the expected share: a correct table fails
|
||||
// this about once in a few million runs.
|
||||
for amount, p := range map[int64]float64{1000: 0.001, 100: 0.01, 10: 0.1, 0: 0.889} {
|
||||
got := float64(counts[amount]) / draws
|
||||
tolerance := 5 * math.Sqrt(p*(1-p)/draws)
|
||||
assert.InDelta(t, p, got, tolerance, "amount %d", amount)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRewardCalculator_RejectsInvalidRules(t *testing.T) {
|
||||
for name, tc := range map[string]struct{ rewardType, rules string }{
|
||||
"unknown type": {"TIERED", `{}`},
|
||||
"not JSON": {constants.GameRewardTypeFixed, `{amount: 5}`},
|
||||
"unknown field": {constants.GameRewardTypeFixed, `{"amount": 5, "amonut": 6}`},
|
||||
"trailing data": {constants.GameRewardTypeFixed, `{"amount": 5} {}`},
|
||||
"FIXED without amount": {constants.GameRewardTypeFixed, `{}`},
|
||||
"FIXED negative": {constants.GameRewardTypeFixed, `{"amount": -1}`},
|
||||
"FIXED fraction": {constants.GameRewardTypeFixed, `{"amount": 1.5}`},
|
||||
"no bands": {constants.GameRewardTypeScoreBased, `{"bands": []}`},
|
||||
"bands not from 0": {constants.GameRewardTypeScoreBased, `{"bands": [{"min": 1, "amount": 1}]}`},
|
||||
"bands overlap": {constants.GameRewardTypeScoreBased, `{"bands": [{"min": 0, "max": 100, "amount": 1}, {"min": 100, "amount": 2}]}`},
|
||||
"bands leave a gap": {constants.GameRewardTypeScoreBased, `{"bands": [{"min": 0, "max": 100, "amount": 1}, {"min": 102, "amount": 2}]}`},
|
||||
"open band not last": {constants.GameRewardTypeScoreBased, `{"bands": [{"min": 0, "amount": 1}, {"min": 101, "amount": 2}]}`},
|
||||
"band max below min": {constants.GameRewardTypeScoreBased, `{"bands": [{"min": 0, "max": -1, "amount": 1}]}`},
|
||||
"band out of order": {constants.GameRewardTypeScoreBased, `{"bands": [{"min": 0, "max": 100, "amount": 1}, {"min": 501, "amount": 3}, {"min": 101, "max": 500, "amount": 2}]}`},
|
||||
"band without amount": {constants.GameRewardTypeScoreBased, `{"bands": [{"min": 0}]}`},
|
||||
"band negative amount": {constants.GameRewardTypeScoreBased, `{"bands": [{"min": 0, "amount": -2}]}`},
|
||||
"no outcomes": {constants.GameRewardTypeOutcomeBased, `{"outcomes": {}}`},
|
||||
"blank outcome": {constants.GameRewardTypeOutcomeBased, `{"outcomes": {" ": 1}}`},
|
||||
"negative outcome": {constants.GameRewardTypeOutcomeBased, `{"outcomes": {"WIN": -1}}`},
|
||||
"empty table": {constants.GameRewardTypeProbability, `{"table": []}`},
|
||||
"zero weight": {constants.GameRewardTypeProbability, `{"table": [{"weight": 0, "amount": 1}, {"weight": 1, "amount": 0}]}`},
|
||||
"negative weight": {constants.GameRewardTypeProbability, `{"table": [{"weight": -1, "amount": 1}, {"weight": 2, "amount": 0}]}`},
|
||||
"percent weight": {constants.GameRewardTypeProbability, `{"table": [{"weight": 0.1, "amount": 1000}]}`},
|
||||
"entry without weight": {constants.GameRewardTypeProbability, `{"table": [{"amount": 1}]}`},
|
||||
"negative probability pay": {constants.GameRewardTypeProbability, `{"table": [{"weight": 1, "amount": -1}]}`},
|
||||
"weights overflow": {constants.GameRewardTypeProbability, `{"table": [{"weight": 9000000000000000000, "amount": 1}, {"weight": 9000000000000000000, "amount": 0}]}`},
|
||||
} {
|
||||
c, err := RewardCalculatorFor(tc.rewardType)
|
||||
if err == nil {
|
||||
err = c.Validate(json.RawMessage(tc.rules))
|
||||
}
|
||||
assert.ErrorIs(t, err, ErrInvalidRewardRules, name)
|
||||
}
|
||||
}
|
||||
|
||||
// EG-902: the Budget Controller scales amounts, rounded down, and nothing else.
|
||||
func TestRewardCalculator_Scale(t *testing.T) {
|
||||
for name, tc := range map[string]struct {
|
||||
rewardType, rules string
|
||||
multiplier int64
|
||||
want string
|
||||
}{
|
||||
"FIXED ×0.9": {constants.GameRewardTypeFixed, `{"amount": 10}`, 9_000, `{"amount":9}`},
|
||||
"FIXED rounds": {constants.GameRewardTypeFixed, `{"amount": 5}`, 9_000, `{"amount":4}`},
|
||||
"FIXED to zero": {constants.GameRewardTypeFixed, `{"amount": 1}`, 9_000, `{"amount":0}`},
|
||||
"FIXED ×1.1": {constants.GameRewardTypeFixed, `{"amount": 10}`, 11_000, `{"amount":11}`},
|
||||
"FIXED ×1": {constants.GameRewardTypeFixed, `{"amount": 7}`, 10_000, `{"amount":7}`},
|
||||
"SCORE_BASED": {constants.GameRewardTypeScoreBased, `{"bands": [{"min": 0, "max": 100, "amount": 1}, {"min": 101, "amount": 20}]}`, 8_100, `{"bands":[{"min":0,"max":100,"amount":0},{"min":101,"amount":16}]}`},
|
||||
"OUTCOME_BASED": {constants.GameRewardTypeOutcomeBased, `{"outcomes": {"PERFECT": 20, "GOOD": 10, "FAIL": 0}}`, 9_000, `{"outcomes":{"FAIL":0,"GOOD":9,"PERFECT":18}}`},
|
||||
"PROBABILITY": {constants.GameRewardTypeProbability, `{"table": [{"weight": 1, "amount": 1000}, {"weight": 999, "amount": 0}]}`, 8_500, `{"table":[{"weight":1,"amount":850},{"weight":999,"amount":0}]}`},
|
||||
} {
|
||||
c, err := RewardCalculatorFor(tc.rewardType)
|
||||
require.NoError(t, err)
|
||||
scaled, err := c.Scale(json.RawMessage(tc.rules), tc.multiplier)
|
||||
require.NoError(t, err, name)
|
||||
assert.JSONEq(t, tc.want, string(scaled), name)
|
||||
assert.NoError(t, c.Validate(scaled), "%s: scaled rules stay valid", name)
|
||||
}
|
||||
|
||||
c, _ := RewardCalculatorFor(constants.GameRewardTypeFixed)
|
||||
_, err := c.Scale(json.RawMessage(`{"amount": 9223372036854775807}`), 15_000)
|
||||
assert.ErrorIs(t, err, ErrInvalidRewardRules, "overflow is refused, not wrapped")
|
||||
_, err = c.Scale(json.RawMessage(`{"amount": -1}`), 9_000)
|
||||
assert.ErrorIs(t, err, ErrInvalidRewardRules)
|
||||
|
||||
v, err := scaleRewardAmount(math.MaxInt64/15_000, 15_000)
|
||||
require.NoError(t, err)
|
||||
assert.EqualValues(t, math.MaxInt64/15_000*15_000/10_000, v)
|
||||
}
|
||||
|
||||
// EG-1001: a spin wheel is a PROBABILITY game whose entries carry labels.
|
||||
func TestRewardCalculator_SpinPrizes(t *testing.T) {
|
||||
rules := json.RawMessage(`{"table": [
|
||||
{"weight": 50, "amount": 0, "label": "Zonk"},
|
||||
{"weight": 45, "amount": 5, "label": "5 Coin"},
|
||||
{"weight": 5, "amount": 50}]}`)
|
||||
c, err := RewardCalculatorFor(constants.GameRewardTypeProbability)
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, c.Validate(rules))
|
||||
|
||||
prizes, err := probabilityPrizes(rules)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, []models.GamePrize{
|
||||
{Entry: 1, Label: ptr("Zonk"), Amount: 0}, {Entry: 2, Label: ptr("5 Coin"), Amount: 5}, {Entry: 3, Amount: 50},
|
||||
}, prizes, "no weights")
|
||||
|
||||
base, detail, err := c.Calculate(rules, SessionResult{}, &fixedRNG{draws: []int64{60}})
|
||||
require.NoError(t, err)
|
||||
assert.EqualValues(t, 5, base)
|
||||
assert.Equal(t, &models.GamePrize{Entry: 2, Label: ptr("5 Coin"), Amount: 5}, drawnPrize(constants.GameRewardTypeProbability, base, detail))
|
||||
|
||||
// As read back from reward_breakdown.
|
||||
stored, err := json.Marshal(detail)
|
||||
require.NoError(t, err)
|
||||
var back map[string]any
|
||||
require.NoError(t, json.Unmarshal(stored, &back))
|
||||
assert.Equal(t, &models.GamePrize{Entry: 2, Label: ptr("5 Coin"), Amount: 5}, drawnPrize(constants.GameRewardTypeProbability, base, back))
|
||||
|
||||
_, detail, err = c.Calculate(rules, SessionResult{}, &fixedRNG{draws: []int64{99}})
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, &models.GamePrize{Entry: 3, Amount: 50}, drawnPrize(constants.GameRewardTypeProbability, 50, detail), "no label")
|
||||
assert.Nil(t, drawnPrize(constants.GameRewardTypeFixed, 5, map[string]any{"reward_type": "FIXED"}))
|
||||
assert.Nil(t, drawnPrize(constants.GameRewardTypeProbability, 0, nil), "rejected: nothing drawn")
|
||||
|
||||
scaled, err := c.Scale(rules, 9_000)
|
||||
require.NoError(t, err)
|
||||
assert.Contains(t, string(scaled), `"label":"Zonk"`, "scaling keeps the labels")
|
||||
|
||||
for name, bad := range map[string]string{
|
||||
"empty label": `{"table": [{"weight": 1, "amount": 1, "label": " "}]}`,
|
||||
"label too long": `{"table": [{"weight": 1, "amount": 1, "label": "` + strings.Repeat("x", 101) + `"}]}`,
|
||||
} {
|
||||
assert.ErrorIs(t, c.Validate(json.RawMessage(bad)), ErrInvalidRewardRules, name)
|
||||
}
|
||||
}
|
||||
@@ -1,149 +0,0 @@
|
||||
package processor
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"apskel-pos-be/internal/contract"
|
||||
"apskel-pos-be/internal/entities"
|
||||
"apskel-pos-be/internal/mappers"
|
||||
"apskel-pos-be/internal/models"
|
||||
"apskel-pos-be/internal/repository"
|
||||
)
|
||||
|
||||
type RewardProcessor interface {
|
||||
CreateReward(ctx context.Context, req *contract.CreateRewardRequest) (*models.RewardResponse, error)
|
||||
GetReward(ctx context.Context, id string) (*models.RewardResponse, error)
|
||||
ListRewards(ctx context.Context, req *contract.ListRewardsRequest) (*models.ListRewardsResponse, error)
|
||||
UpdateReward(ctx context.Context, req *contract.UpdateRewardRequest) (*models.RewardResponse, error)
|
||||
DeleteReward(ctx context.Context, id string) error
|
||||
UpdateRewardStock(ctx context.Context, id string, newStock int) error
|
||||
GetRewardsByType(ctx context.Context, rewardType string) ([]models.RewardResponse, error)
|
||||
}
|
||||
|
||||
type rewardProcessor struct {
|
||||
rewardRepo repository.RewardRepository
|
||||
}
|
||||
|
||||
func NewRewardProcessor(rewardRepo repository.RewardRepository) RewardProcessor {
|
||||
return &rewardProcessor{
|
||||
rewardRepo: rewardRepo,
|
||||
}
|
||||
}
|
||||
|
||||
func (p *rewardProcessor) CreateReward(ctx context.Context, req *contract.CreateRewardRequest) (*models.RewardResponse, error) {
|
||||
// Convert request to entity
|
||||
entity := mappers.ToRewardEntity(req)
|
||||
if entity == nil {
|
||||
return nil, fmt.Errorf("invalid request data")
|
||||
}
|
||||
|
||||
// Create in repository
|
||||
if err := p.rewardRepo.Create(ctx, entity); err != nil {
|
||||
return nil, fmt.Errorf("failed to create reward: %w", err)
|
||||
}
|
||||
|
||||
// Convert entity to response
|
||||
response := mappers.ToRewardResponse(entity)
|
||||
return response, nil
|
||||
}
|
||||
|
||||
func (p *rewardProcessor) GetReward(ctx context.Context, id string) (*models.RewardResponse, error) {
|
||||
// Get from repository
|
||||
entity, err := p.rewardRepo.GetByID(ctx, id)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to get reward: %w", err)
|
||||
}
|
||||
|
||||
if entity == nil {
|
||||
return nil, fmt.Errorf("reward not found")
|
||||
}
|
||||
|
||||
// Convert entity to response
|
||||
response := mappers.ToRewardResponse(entity)
|
||||
return response, nil
|
||||
}
|
||||
|
||||
func (p *rewardProcessor) ListRewards(ctx context.Context, req *contract.ListRewardsRequest) (*models.ListRewardsResponse, error) {
|
||||
// Convert request to entity request
|
||||
entityReq := &entities.ListRewardsRequest{
|
||||
Page: req.Page,
|
||||
Limit: req.Limit,
|
||||
Search: req.Search,
|
||||
RewardType: req.RewardType,
|
||||
MinPoints: req.MinPoints,
|
||||
MaxPoints: req.MaxPoints,
|
||||
HasStock: req.HasStock,
|
||||
}
|
||||
|
||||
// Get from repository
|
||||
entities, total, err := p.rewardRepo.List(ctx, entityReq)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to list rewards: %w", err)
|
||||
}
|
||||
|
||||
// Convert entities to response
|
||||
rewards := mappers.ToRewardResponseSlice(entities)
|
||||
|
||||
response := &models.ListRewardsResponse{
|
||||
Rewards: rewards,
|
||||
Total: total,
|
||||
Page: req.Page,
|
||||
Limit: req.Limit,
|
||||
}
|
||||
|
||||
return response, nil
|
||||
}
|
||||
|
||||
func (p *rewardProcessor) UpdateReward(ctx context.Context, req *contract.UpdateRewardRequest) (*models.RewardResponse, error) {
|
||||
// Convert request to entity
|
||||
entity := mappers.ToRewardEntityFromUpdate(req)
|
||||
if entity == nil {
|
||||
return nil, fmt.Errorf("invalid request data")
|
||||
}
|
||||
|
||||
// Update in repository
|
||||
if err := p.rewardRepo.Update(ctx, entity); err != nil {
|
||||
return nil, fmt.Errorf("failed to update reward: %w", err)
|
||||
}
|
||||
|
||||
// Get updated entity
|
||||
updatedEntity, err := p.rewardRepo.GetByID(ctx, req.ID.String())
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to get updated reward: %w", err)
|
||||
}
|
||||
|
||||
// Convert entity to response
|
||||
response := mappers.ToRewardResponse(updatedEntity)
|
||||
return response, nil
|
||||
}
|
||||
|
||||
func (p *rewardProcessor) DeleteReward(ctx context.Context, id string) error {
|
||||
// Delete from repository
|
||||
if err := p.rewardRepo.Delete(ctx, id); err != nil {
|
||||
return fmt.Errorf("failed to delete reward: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *rewardProcessor) UpdateRewardStock(ctx context.Context, id string, newStock int) error {
|
||||
// Update stock in repository
|
||||
if err := p.rewardRepo.UpdateStock(ctx, id, newStock); err != nil {
|
||||
return fmt.Errorf("failed to update reward stock: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *rewardProcessor) GetRewardsByType(ctx context.Context, rewardType string) ([]models.RewardResponse, error) {
|
||||
// Get from repository
|
||||
entities, err := p.rewardRepo.GetByRewardType(ctx, entities.RewardType(rewardType))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to get rewards by type: %w", err)
|
||||
}
|
||||
|
||||
// Convert entities to response
|
||||
rewards := mappers.ToRewardResponseSlice(entities)
|
||||
return rewards, nil
|
||||
}
|
||||
@@ -0,0 +1,422 @@
|
||||
package processor
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/csv"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"apskel-pos-be/internal/constants"
|
||||
"apskel-pos-be/internal/entities"
|
||||
"apskel-pos-be/internal/models"
|
||||
"apskel-pos-be/internal/repository"
|
||||
)
|
||||
|
||||
const (
|
||||
// voucherCodeImportLimit caps the lines of one import.
|
||||
voucherCodeImportLimit = 50_000
|
||||
// voucherDuplicateReportLimit caps the duplicate codes an import lists back.
|
||||
voucherDuplicateReportLimit = 100
|
||||
)
|
||||
|
||||
// VoucherAdminProcessor manages an organization's EnakGame vouchers and their code
|
||||
// pools (docs/rfc-enakgame.md §5.7, §11). Every change is audited in its transaction.
|
||||
type VoucherAdminProcessor struct {
|
||||
vouchers repository.VoucherRepository
|
||||
audit *AuditLogger
|
||||
tx TxRunner
|
||||
}
|
||||
|
||||
func NewVoucherAdminProcessor(vouchers repository.VoucherRepository, audit *AuditLogger, tx TxRunner) *VoucherAdminProcessor {
|
||||
return &VoucherAdminProcessor{vouchers: vouchers, audit: audit, tx: tx}
|
||||
}
|
||||
|
||||
func (p *VoucherAdminProcessor) record(ctx context.Context, organizationID, actor, id uuid.UUID, action string, before, after any, reason *string) error {
|
||||
return p.audit.Record(ctx, AuditEntry{
|
||||
OrganizationID: organizationID, ActorType: constants.AuditActorUser, ActorID: &actor,
|
||||
EntityType: constants.AuditEntityVoucher, EntityID: id, Action: action,
|
||||
Before: before, After: after, Reason: reason, Source: constants.AuditSourceAdminAPI,
|
||||
})
|
||||
}
|
||||
|
||||
// VoucherInputFrom is a voucher's current values as an input, for a change that only
|
||||
// sends the fields it changes.
|
||||
func VoucherInputFrom(v *models.Voucher) models.VoucherInput {
|
||||
return models.VoucherInput{
|
||||
Name: v.Name, Description: v.Description, ImageURL: v.ImageURL, VoucherType: v.VoucherType,
|
||||
FaceValue: v.FaceValue, PointCost: v.PointCost, BusinessCost: v.BusinessCost, StockMode: v.StockMode,
|
||||
Stock: v.Stock, Provider: v.Provider, ProviderRef: v.ProviderRef, MaxPerCustomer: v.MaxPerCustomer,
|
||||
ValidFrom: v.ValidFrom, ValidUntil: v.ValidUntil, Terms: v.Terms, Status: v.Status,
|
||||
}
|
||||
}
|
||||
|
||||
func (p *VoucherAdminProcessor) CreateVoucher(ctx context.Context, organizationID, actor uuid.UUID, in models.VoucherInput) (*models.Voucher, error) {
|
||||
if in.Status == "" {
|
||||
in.Status = constants.VoucherStatusDraft
|
||||
}
|
||||
in.Status = strings.ToUpper(strings.TrimSpace(in.Status))
|
||||
switch in.Status {
|
||||
case constants.VoucherStatusDraft, constants.VoucherStatusActive, constants.VoucherStatusInactive:
|
||||
default:
|
||||
return nil, enakGameRejected("a new voucher must be DRAFT, ACTIVE or INACTIVE")
|
||||
}
|
||||
voucher := &entities.Voucher{OrganizationID: organizationID, Status: in.Status}
|
||||
if err := applyVoucherInput(voucher, in); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
err := p.tx.WithTransaction(ctx, func(ctx context.Context) error {
|
||||
if err := p.vouchers.CreateVoucher(ctx, voucher); err != nil {
|
||||
return err
|
||||
}
|
||||
return p.record(ctx, organizationID, actor, voucher.ID, "CREATED", nil, voucherModel(voucher), nil)
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return voucherModel(voucher), nil
|
||||
}
|
||||
|
||||
func (p *VoucherAdminProcessor) GetVoucher(ctx context.Context, organizationID, id uuid.UUID) (*models.Voucher, error) {
|
||||
voucher, err := p.vouchers.GetVoucher(ctx, organizationID, id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return voucherModel(voucher), nil
|
||||
}
|
||||
|
||||
// ListVouchers returns a page of vouchers. ARCHIVED ones are left out unless asked
|
||||
// for by status.
|
||||
func (p *VoucherAdminProcessor) ListVouchers(ctx context.Context, organizationID uuid.UUID, q models.VoucherListQuery) (*models.PaginatedResponse[models.Voucher], error) {
|
||||
page, limit := enakGamePage(q.Page, q.Limit)
|
||||
statuses := []string{constants.VoucherStatusDraft, constants.VoucherStatusActive, constants.VoucherStatusInactive}
|
||||
if q.Status != "" {
|
||||
status := strings.ToUpper(strings.TrimSpace(q.Status))
|
||||
if !isVoucherStatus(status) {
|
||||
return nil, enakGameRejected("unknown status %q", q.Status)
|
||||
}
|
||||
statuses = []string{status}
|
||||
}
|
||||
vouchers, total, err := p.vouchers.ListVouchers(ctx, repository.VoucherFilter{
|
||||
OrganizationID: organizationID, Statuses: statuses, Search: strings.TrimSpace(q.Search),
|
||||
Offset: (page - 1) * limit, Limit: limit,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items := make([]models.Voucher, 0, len(vouchers))
|
||||
for i := range vouchers {
|
||||
items = append(items, *voucherModel(&vouchers[i]))
|
||||
}
|
||||
return &models.PaginatedResponse[models.Voucher]{Data: items, Pagination: enakGamePagination(page, limit, total)}, nil
|
||||
}
|
||||
|
||||
// UpdateVoucher changes everything but the stock mode and the status. Redemptions
|
||||
// already made keep the numbers they froze.
|
||||
func (p *VoucherAdminProcessor) UpdateVoucher(ctx context.Context, organizationID, actor, id uuid.UUID, in models.VoucherInput) (*models.Voucher, error) {
|
||||
var after *models.Voucher
|
||||
err := p.tx.WithTransaction(ctx, func(ctx context.Context) error {
|
||||
voucher, err := p.vouchers.LockVoucher(ctx, organizationID, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if voucher.Status == constants.VoucherStatusArchived {
|
||||
return enakGameRejected("an archived voucher cannot change")
|
||||
}
|
||||
if !strings.EqualFold(strings.TrimSpace(in.StockMode), voucher.StockMode) {
|
||||
return enakGameRejected("the stock mode of a voucher cannot change")
|
||||
}
|
||||
before := voucherModel(voucher)
|
||||
if err := applyVoucherInput(voucher, in); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := p.vouchers.UpdateVoucher(ctx, voucher); err != nil {
|
||||
return err
|
||||
}
|
||||
saved, err := p.vouchers.GetVoucher(ctx, organizationID, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
after = voucherModel(saved)
|
||||
return p.record(ctx, organizationID, actor, id, "UPDATED", before, after, nil)
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return after, nil
|
||||
}
|
||||
|
||||
// SetVoucherStatus moves a voucher between DRAFT, ACTIVE and INACTIVE, or archives it
|
||||
// for good.
|
||||
func (p *VoucherAdminProcessor) SetVoucherStatus(ctx context.Context, organizationID, actor, id uuid.UUID, in models.VoucherStatusInput) (*models.Voucher, error) {
|
||||
status := strings.ToUpper(strings.TrimSpace(in.Status))
|
||||
if !isVoucherStatus(status) {
|
||||
return nil, enakGameRejected("status must be DRAFT, ACTIVE, INACTIVE or ARCHIVED")
|
||||
}
|
||||
if err := validateReason(in.Reason); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
err := p.tx.WithTransaction(ctx, func(ctx context.Context) error {
|
||||
voucher, err := p.vouchers.LockVoucher(ctx, organizationID, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if voucher.Status == status {
|
||||
return nil
|
||||
}
|
||||
if voucher.Status == constants.VoucherStatusArchived {
|
||||
return enakGameRejected("an archived voucher cannot change")
|
||||
}
|
||||
if err := p.vouchers.SetVoucherStatus(ctx, organizationID, id, status); err != nil {
|
||||
return err
|
||||
}
|
||||
return p.record(ctx, organizationID, actor, id, "STATUS_CHANGED",
|
||||
map[string]string{"status": voucher.Status}, map[string]string{"status": status}, in.Reason)
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return p.GetVoucher(ctx, organizationID, id)
|
||||
}
|
||||
|
||||
// ImportCodes adds codes from a CSV to a CODE_POOL voucher. Each line holds a code and,
|
||||
// optionally, when it expires (YYYY-MM-DD, the end of that day in Asia/Jakarta, or
|
||||
// RFC 3339); a first line "code" is a header. A code already in the pool or repeated in
|
||||
// the file is skipped and listed back, so importing the same file twice adds nothing
|
||||
// the second time. A line that cannot be read is skipped and reported.
|
||||
func (p *VoucherAdminProcessor) ImportCodes(ctx context.Context, organizationID, actor, voucherID uuid.UUID, data []byte) (*models.VoucherCodeImportResult, error) {
|
||||
codes, invalid, repeated, err := parseVoucherCodes(data)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
result := &models.VoucherCodeImportResult{Duplicates: []string{}, Invalid: invalid}
|
||||
err = p.tx.WithTransaction(ctx, func(ctx context.Context) error {
|
||||
voucher, err := p.vouchers.LockVoucher(ctx, organizationID, voucherID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if voucher.StockMode != constants.VoucherStockCodePool {
|
||||
return enakGameRejected("only a CODE_POOL voucher holds codes")
|
||||
}
|
||||
if voucher.Status == constants.VoucherStatusArchived {
|
||||
return enakGameRejected("an archived voucher cannot change")
|
||||
}
|
||||
added, err := p.vouchers.ImportCodes(ctx, voucherID, codes)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
addedSet := make(map[string]bool, len(added))
|
||||
for _, code := range added {
|
||||
addedSet[code] = true
|
||||
}
|
||||
duplicates := repeated
|
||||
for _, c := range codes {
|
||||
if !addedSet[c.Code] {
|
||||
duplicates = append(duplicates, c.Code)
|
||||
}
|
||||
}
|
||||
result.Imported = len(added)
|
||||
result.DuplicateCount = len(duplicates)
|
||||
if len(duplicates) > voucherDuplicateReportLimit {
|
||||
duplicates = duplicates[:voucherDuplicateReportLimit]
|
||||
}
|
||||
result.Duplicates = append(result.Duplicates, duplicates...)
|
||||
return p.record(ctx, organizationID, actor, voucherID, "CODES_IMPORTED", nil, map[string]int{
|
||||
"imported": result.Imported, "duplicates": result.DuplicateCount, "invalid": len(result.Invalid),
|
||||
}, nil)
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// Codes returns how many of a pool's codes are in each status and a page of them.
|
||||
func (p *VoucherAdminProcessor) Codes(ctx context.Context, organizationID, voucherID uuid.UUID, q models.VoucherCodeListQuery) (*models.VoucherCodes, error) {
|
||||
if _, err := p.vouchers.GetVoucher(ctx, organizationID, voucherID); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
status := strings.ToUpper(strings.TrimSpace(q.Status))
|
||||
switch status {
|
||||
case "", constants.VoucherCodeAvailable, constants.VoucherCodeReserved, constants.VoucherCodeRedeemed,
|
||||
constants.VoucherCodeExpired, constants.VoucherCodeCancelled:
|
||||
default:
|
||||
return nil, enakGameRejected("unknown code status %q", q.Status)
|
||||
}
|
||||
counts, err := p.vouchers.CountCodes(ctx, voucherID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
page, limit := enakGamePage(q.Page, q.Limit)
|
||||
codes, total, err := p.vouchers.ListCodes(ctx, voucherID, status, (page-1)*limit, limit)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items := make([]models.VoucherCode, 0, len(codes))
|
||||
for _, c := range codes {
|
||||
items = append(items, models.VoucherCode{ID: c.ID, Code: c.Code, Status: c.Status, RedemptionID: c.RedemptionID, ExpiresAt: c.ExpiresAt, CreatedAt: c.CreatedAt})
|
||||
}
|
||||
return &models.VoucherCodes{
|
||||
Counts: counts,
|
||||
Codes: models.PaginatedResponse[models.VoucherCode]{Data: items, Pagination: enakGamePagination(page, limit, total)},
|
||||
}, nil
|
||||
}
|
||||
|
||||
// ExpireCodes moves every available code past its expiry to EXPIRED, a batch at a
|
||||
// time, and returns how many (§12).
|
||||
func (p *VoucherAdminProcessor) ExpireCodes(ctx context.Context, now time.Time) (int64, error) {
|
||||
const batch = 500
|
||||
var expired int64
|
||||
for {
|
||||
n, err := p.vouchers.ExpireCodes(ctx, now, batch)
|
||||
expired += n
|
||||
if err != nil || n < batch {
|
||||
return expired, err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// parseVoucherCodes reads codes from a CSV. It returns the codes, the lines it could
|
||||
// not read, and the codes repeated within the file.
|
||||
func parseVoucherCodes(data []byte) ([]repository.VoucherCodeImport, []models.VoucherCodeImportProblem, []string, error) {
|
||||
reader := csv.NewReader(bytes.NewReader(data))
|
||||
reader.FieldsPerRecord = -1
|
||||
reader.TrimLeadingSpace = true
|
||||
var codes []repository.VoucherCodeImport
|
||||
invalid := []models.VoucherCodeImportProblem{}
|
||||
var repeated []string
|
||||
seen := map[string]bool{}
|
||||
for line := 1; ; line++ {
|
||||
record, err := reader.Read()
|
||||
if errors.Is(err, io.EOF) {
|
||||
break
|
||||
}
|
||||
if err != nil {
|
||||
invalid = append(invalid, models.VoucherCodeImportProblem{Line: line, Reason: err.Error()})
|
||||
continue
|
||||
}
|
||||
if line > voucherCodeImportLimit {
|
||||
return nil, nil, nil, enakGameRejected("an import takes at most %d lines", voucherCodeImportLimit)
|
||||
}
|
||||
code := strings.TrimSpace(record[0])
|
||||
if line == 1 && strings.EqualFold(code, "code") {
|
||||
continue
|
||||
}
|
||||
if code == "" {
|
||||
continue
|
||||
}
|
||||
if len(code) > 255 {
|
||||
invalid = append(invalid, models.VoucherCodeImportProblem{Line: line, Reason: "the code is longer than 255 characters"})
|
||||
continue
|
||||
}
|
||||
var expiresAt *time.Time
|
||||
if len(record) > 1 && strings.TrimSpace(record[1]) != "" {
|
||||
t, err := parseCodeExpiry(strings.TrimSpace(record[1]))
|
||||
if err != nil {
|
||||
invalid = append(invalid, models.VoucherCodeImportProblem{Line: line, Reason: err.Error()})
|
||||
continue
|
||||
}
|
||||
expiresAt = &t
|
||||
}
|
||||
if seen[code] {
|
||||
repeated = append(repeated, code)
|
||||
continue
|
||||
}
|
||||
seen[code] = true
|
||||
codes = append(codes, repository.VoucherCodeImport{Code: code, ExpiresAt: expiresAt})
|
||||
}
|
||||
if len(codes) == 0 && len(invalid) == 0 {
|
||||
return nil, nil, nil, enakGameRejected("the file holds no codes")
|
||||
}
|
||||
return codes, invalid, repeated, nil
|
||||
}
|
||||
|
||||
func parseCodeExpiry(raw string) (time.Time, error) {
|
||||
if day, err := time.ParseInLocation("2006-01-02", raw, walletDisplayLocation); err == nil {
|
||||
return *endOfWalletDay(day), nil
|
||||
}
|
||||
if t, err := time.Parse(time.RFC3339, raw); err == nil {
|
||||
return t, nil
|
||||
}
|
||||
return time.Time{}, fmt.Errorf("expiry %q is not a date like 2026-12-31", raw)
|
||||
}
|
||||
|
||||
func isVoucherStatus(s string) bool {
|
||||
switch s {
|
||||
case constants.VoucherStatusDraft, constants.VoucherStatusActive, constants.VoucherStatusInactive, constants.VoucherStatusArchived:
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// applyVoucherInput checks an input and copies it onto the voucher, leaving its
|
||||
// organization, stock mode (once set) and status alone.
|
||||
func applyVoucherInput(v *entities.Voucher, in models.VoucherInput) error {
|
||||
name := strings.TrimSpace(in.Name)
|
||||
voucherType := strings.ToUpper(strings.TrimSpace(in.VoucherType))
|
||||
stockMode := strings.ToUpper(strings.TrimSpace(in.StockMode))
|
||||
switch {
|
||||
case name == "" || len(name) > 255:
|
||||
return enakGameRejected("name is required, at most 255 characters")
|
||||
case voucherType != constants.VoucherTypeFixedValue && voucherType != constants.VoucherTypePercentage &&
|
||||
voucherType != constants.VoucherTypeFreeItem && voucherType != constants.VoucherTypeMerchantBenefit:
|
||||
return enakGameRejected("voucher_type must be FIXED_VALUE, PERCENTAGE, FREE_ITEM or MERCHANT_BENEFIT")
|
||||
case in.FaceValue <= 0:
|
||||
return enakGameRejected("face_value must be more than 0")
|
||||
case in.PointCost <= 0:
|
||||
return enakGameRejected("point_cost must be more than 0")
|
||||
case in.BusinessCost != nil && *in.BusinessCost < 0:
|
||||
return enakGameRejected("business_cost must be 0 or more")
|
||||
case stockMode != constants.VoucherStockStatic && stockMode != constants.VoucherStockCodePool && stockMode != constants.VoucherStockExternal:
|
||||
return enakGameRejected("stock_mode must be STATIC, CODE_POOL or EXTERNAL")
|
||||
case (stockMode == constants.VoucherStockStatic) != (in.Stock != nil):
|
||||
return enakGameRejected("stock is required for a STATIC voucher and only for one")
|
||||
case in.Stock != nil && *in.Stock < 0:
|
||||
return enakGameRejected("stock must be 0 or more")
|
||||
case (stockMode == constants.VoucherStockExternal) != (in.Provider != nil && strings.TrimSpace(*in.Provider) != ""):
|
||||
return enakGameRejected("provider is required for an EXTERNAL voucher and only for one")
|
||||
case in.Provider != nil && len(*in.Provider) > 50:
|
||||
return enakGameRejected("provider must be at most 50 characters")
|
||||
case in.ProviderRef != nil && len(*in.ProviderRef) > 255:
|
||||
return enakGameRejected("provider_ref must be at most 255 characters")
|
||||
case in.MaxPerCustomer != nil && *in.MaxPerCustomer < 1:
|
||||
return enakGameRejected("max_per_customer must be at least 1, or left out for no limit")
|
||||
case in.ValidFrom != nil && in.ValidUntil != nil && !in.ValidUntil.After(*in.ValidFrom):
|
||||
return enakGameRejected("valid_until must be after valid_from")
|
||||
case in.ImageURL != nil && len(*in.ImageURL) > 500:
|
||||
return enakGameRejected("image_url must be at most 500 characters")
|
||||
}
|
||||
terms := entities.JSONDocument(`{}`)
|
||||
if len(bytes.TrimSpace(in.Terms)) > 0 && string(bytes.TrimSpace(in.Terms)) != "null" {
|
||||
var object map[string]any
|
||||
if err := json.Unmarshal(in.Terms, &object); err != nil {
|
||||
return enakGameRejected("terms must be a JSON object")
|
||||
}
|
||||
var compact bytes.Buffer
|
||||
if err := json.Compact(&compact, in.Terms); err != nil {
|
||||
return enakGameRejected("terms must be a JSON object")
|
||||
}
|
||||
terms = entities.JSONDocument(compact.Bytes())
|
||||
}
|
||||
v.Name, v.Description, v.ImageURL, v.VoucherType = name, in.Description, in.ImageURL, voucherType
|
||||
v.FaceValue, v.PointCost, v.BusinessCost, v.StockMode = in.FaceValue, in.PointCost, in.BusinessCost, stockMode
|
||||
v.Stock, v.Provider, v.ProviderRef, v.MaxPerCustomer = in.Stock, in.Provider, in.ProviderRef, in.MaxPerCustomer
|
||||
v.ValidFrom, v.ValidUntil, v.Terms = in.ValidFrom, in.ValidUntil, terms
|
||||
return nil
|
||||
}
|
||||
|
||||
func voucherModel(v *entities.Voucher) *models.Voucher {
|
||||
return &models.Voucher{
|
||||
ID: v.ID, Name: v.Name, Description: v.Description, ImageURL: v.ImageURL, VoucherType: v.VoucherType,
|
||||
FaceValue: v.FaceValue, PointCost: v.PointCost, BusinessCost: v.BusinessCost, StockMode: v.StockMode,
|
||||
Stock: v.Stock, Provider: v.Provider, ProviderRef: v.ProviderRef, MaxPerCustomer: v.MaxPerCustomer,
|
||||
ValidFrom: v.ValidFrom, ValidUntil: v.ValidUntil, Terms: json.RawMessage(v.Terms), Status: v.Status,
|
||||
CreatedAt: v.CreatedAt, UpdatedAt: v.UpdatedAt,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package processor
|
||||
|
||||
import (
|
||||
"math/big"
|
||||
|
||||
"apskel-pos-be/internal/repository"
|
||||
)
|
||||
|
||||
// VoucherCostPart is the share of a redemption's face value one source of its
|
||||
// EnakPoint accounts for (docs/rfc-enakgame.md §7.6).
|
||||
type VoucherCostPart struct {
|
||||
repository.RedemptionPointSource
|
||||
Cost int64
|
||||
}
|
||||
|
||||
// SplitVoucherCost divides faceValue over the sources in proportion to their
|
||||
// EnakPoint: floor(face_value × points / total points) each, with what rounding left
|
||||
// over going to the largest part (the first of equals), so the parts add up to
|
||||
// face_value exactly. Products are computed without overflow.
|
||||
func SplitVoucherCost(faceValue int64, sources []repository.RedemptionPointSource) []VoucherCostPart {
|
||||
parts := make([]VoucherCostPart, 0, len(sources))
|
||||
var totalPoints int64
|
||||
for _, s := range sources {
|
||||
totalPoints += s.Points
|
||||
}
|
||||
if totalPoints <= 0 {
|
||||
return parts
|
||||
}
|
||||
face, total := big.NewInt(faceValue), big.NewInt(totalPoints)
|
||||
var assigned int64
|
||||
largest := 0
|
||||
for i, s := range sources {
|
||||
share := new(big.Int).Mul(face, big.NewInt(s.Points))
|
||||
share.Quo(share, total)
|
||||
parts = append(parts, VoucherCostPart{RedemptionPointSource: s, Cost: share.Int64()})
|
||||
assigned += share.Int64()
|
||||
if s.Points > sources[largest].Points {
|
||||
largest = i
|
||||
}
|
||||
}
|
||||
parts[largest].Cost += faceValue - assigned
|
||||
return parts
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
package processor
|
||||
|
||||
import (
|
||||
"math/rand"
|
||||
"testing"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/stretchr/testify/assert"
|
||||
|
||||
"apskel-pos-be/internal/constants"
|
||||
"apskel-pos-be/internal/repository"
|
||||
)
|
||||
|
||||
func TestSplitVoucherCost(t *testing.T) {
|
||||
october := uuid.New()
|
||||
// RFC §7.6: Rp10.000 voucher for 8.000 EnakPoint, 6.000 from an EnakGame reward
|
||||
// and 2.000 from shopping.
|
||||
parts := SplitVoucherCost(10_000, []repository.RedemptionPointSource{
|
||||
{Points: 2_000, SourceType: constants.WalletTxTypeEarn},
|
||||
{Points: 6_000, SourceType: constants.WalletTxTypeGameReward, BudgetID: &october},
|
||||
})
|
||||
assert.EqualValues(t, 2_500, parts[0].Cost)
|
||||
assert.EqualValues(t, 7_500, parts[1].Cost)
|
||||
|
||||
// Not evenly divisible: the remainder goes to the largest part, the first of equals.
|
||||
parts = SplitVoucherCost(10_000, []repository.RedemptionPointSource{{Points: 3}, {Points: 3}, {Points: 3}})
|
||||
assert.Equal(t, []int64{3_334, 3_333, 3_333}, []int64{parts[0].Cost, parts[1].Cost, parts[2].Cost})
|
||||
parts = SplitVoucherCost(100, []repository.RedemptionPointSource{{Points: 1}, {Points: 5}, {Points: 1}})
|
||||
assert.Equal(t, []int64{14, 72, 14}, []int64{parts[0].Cost, parts[1].Cost, parts[2].Cost})
|
||||
|
||||
// No overflow on large numbers.
|
||||
parts = SplitVoucherCost(9_000_000_000_000, []repository.RedemptionPointSource{{Points: 3_000_000_000_000}, {Points: 6_000_000_000_000}})
|
||||
assert.Equal(t, []int64{3_000_000_000_000, 6_000_000_000_000}, []int64{parts[0].Cost, parts[1].Cost})
|
||||
|
||||
assert.Empty(t, SplitVoucherCost(10, nil))
|
||||
|
||||
// Whatever the numbers, the parts add up to the face value and none is negative.
|
||||
rng := rand.New(rand.NewSource(7))
|
||||
for i := 0; i < 2_000; i++ {
|
||||
face := rng.Int63n(1_000_000) + 1
|
||||
sources := make([]repository.RedemptionPointSource, rng.Intn(5)+1)
|
||||
for j := range sources {
|
||||
sources[j].Points = rng.Int63n(10_000) + 1
|
||||
}
|
||||
var sum int64
|
||||
for _, p := range SplitVoucherCost(face, sources) {
|
||||
assert.GreaterOrEqual(t, p.Cost, int64(0))
|
||||
sum += p.Cost
|
||||
}
|
||||
assert.Equal(t, face, sum)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,477 @@
|
||||
package processor
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
|
||||
"apskel-pos-be/internal/constants"
|
||||
"apskel-pos-be/internal/entities"
|
||||
"apskel-pos-be/internal/models"
|
||||
"apskel-pos-be/internal/repository"
|
||||
)
|
||||
|
||||
// EnakGame vouchers and redemptions against Postgres (docs/rfc-enakgame.md §7.4, §7.6).
|
||||
// Needs TEST_DATABASE_URL; see internal/repository/wallet_repository_test.go.
|
||||
|
||||
func (e *enakGameEnv) voucher(org uuid.UUID, in models.VoucherInput) *models.Voucher {
|
||||
e.t.Helper()
|
||||
if in.Name == "" {
|
||||
in.Name = "Voucher"
|
||||
}
|
||||
if in.VoucherType == "" {
|
||||
in.VoucherType = constants.VoucherTypeFixedValue
|
||||
}
|
||||
if in.Status == "" {
|
||||
in.Status = constants.VoucherStatusActive
|
||||
}
|
||||
v, err := e.vouchers.CreateVoucher(e.ctx(), org, e.manager, in)
|
||||
require.NoError(e.t, err)
|
||||
return v
|
||||
}
|
||||
|
||||
func (e *enakGameEnv) staticVoucher(stock, faceValue, pointCost int64) *models.Voucher {
|
||||
return e.voucher(e.orgA, models.VoucherInput{FaceValue: faceValue, PointCost: pointCost, StockMode: constants.VoucherStockStatic, Stock: &stock})
|
||||
}
|
||||
|
||||
// points gives a customer EnakPoint that did not come from EnakGame.
|
||||
func (e *enakGameEnv) points(customer uuid.UUID, txType string, amount int64) {
|
||||
e.t.Helper()
|
||||
entry := WalletEntry{
|
||||
CustomerID: customer, Currency: constants.WalletCurrencyPoint, Type: txType, Amount: amount,
|
||||
ReferenceID: uuid.New(), Description: txType,
|
||||
}
|
||||
switch txType {
|
||||
case constants.WalletTxTypeEarn:
|
||||
entry.ReferenceType, entry.OutletID = constants.WalletRefTypeOrder, ptr(uuid.New())
|
||||
default:
|
||||
entry.ReferenceType, entry.CreatedByUser, entry.Reason = constants.WalletRefTypeUser, &e.manager, ptr("test")
|
||||
}
|
||||
require.NoError(e.t, e.txm.WithTransaction(e.ctx(), func(ctx context.Context) error {
|
||||
_, err := e.wallet.Credit(ctx, WalletCreditInput{WalletEntry: entry})
|
||||
return err
|
||||
}))
|
||||
}
|
||||
|
||||
// rewardCoins plays a FIXED game of org A paying amount and returns the global budget
|
||||
// that paid it.
|
||||
func (e *enakGameEnv) rewardCoins(customer uuid.UUID, amount int64) uuid.UUID {
|
||||
e.t.Helper()
|
||||
slug := fmt.Sprintf("pay-%d-%s", amount, uuid.NewString()[:8])
|
||||
game := e.gameWith(slug, entities.GameResultRules{}, constants.GameRewardTypeFixed, fmt.Sprintf(`{"amount": %d}`, amount), 0)
|
||||
e.coins(customer, 2, nil)
|
||||
started, err := e.sessions.Start(e.ctx(), customer, game.ID, slug)
|
||||
require.NoError(e.t, err)
|
||||
out, err := e.sessions.Complete(e.ctx(), customer, started.SessionID, models.GameSessionCompleteInput{})
|
||||
require.NoError(e.t, err)
|
||||
require.EqualValues(e.t, amount, out.RewardTotal)
|
||||
var budget string
|
||||
require.NoError(e.t, e.db.Raw(`SELECT budget_id::text FROM game_session_rewards WHERE session_id = ?`, started.SessionID).Scan(&budget).Error)
|
||||
return uuid.MustParse(budget)
|
||||
}
|
||||
|
||||
func (e *enakGameEnv) exchangeCoins(customer uuid.UUID, coins int64) {
|
||||
e.t.Helper()
|
||||
_, err := e.exchange.Exchange(e.ctx(), customer, coins, testPin, uuid.NewString(), models.CustomerPinRequestInfo{})
|
||||
require.NoError(e.t, err)
|
||||
}
|
||||
|
||||
func (e *enakGameEnv) pointBalance(customer uuid.UUID) int64 {
|
||||
e.t.Helper()
|
||||
var balance int64
|
||||
require.NoError(e.t, e.db.Raw(`SELECT COALESCE((SELECT point_balance FROM customer_wallets WHERE customer_id = ?), 0)`, customer).Scan(&balance).Error)
|
||||
return balance
|
||||
}
|
||||
|
||||
func (e *enakGameEnv) redeemVoucher(customer, voucherID uuid.UUID, key string) (*models.VoucherRedeemResult, error) {
|
||||
return e.redeem.Redeem(e.ctx(), customer, voucherID, testPin, key, models.CustomerPinRequestInfo{})
|
||||
}
|
||||
|
||||
type costRow struct {
|
||||
BudgetID *string
|
||||
SourceType string
|
||||
Points int64
|
||||
Cost int64
|
||||
}
|
||||
|
||||
func (e *enakGameEnv) costs(redemptionID uuid.UUID) []costRow {
|
||||
e.t.Helper()
|
||||
var rows []costRow
|
||||
require.NoError(e.t, e.db.Raw(`SELECT budget_id::text AS budget_id, source_type, points, cost FROM voucher_redemption_costs
|
||||
WHERE redemption_id = ? ORDER BY cost DESC`, redemptionID).Scan(&rows).Error)
|
||||
return rows
|
||||
}
|
||||
|
||||
// EG-502
|
||||
func TestVoucherAdmin(t *testing.T) {
|
||||
e := newEnakGameEnv(t)
|
||||
ctx := e.ctx()
|
||||
|
||||
for name, in := range map[string]models.VoucherInput{
|
||||
"no name": {VoucherType: "FIXED_VALUE", FaceValue: 1, PointCost: 1, StockMode: "STATIC", Stock: ptr(int64(1))},
|
||||
"unknown type": {Name: "v", VoucherType: "CASHBACK", FaceValue: 1, PointCost: 1, StockMode: "STATIC", Stock: ptr(int64(1))},
|
||||
"no face value": {Name: "v", VoucherType: "FIXED_VALUE", PointCost: 1, StockMode: "STATIC", Stock: ptr(int64(1))},
|
||||
"no point cost": {Name: "v", VoucherType: "FIXED_VALUE", FaceValue: 1, StockMode: "STATIC", Stock: ptr(int64(1))},
|
||||
"static no stock": {Name: "v", VoucherType: "FIXED_VALUE", FaceValue: 1, PointCost: 1, StockMode: "STATIC"},
|
||||
"pool with stock": {Name: "v", VoucherType: "FIXED_VALUE", FaceValue: 1, PointCost: 1, StockMode: "CODE_POOL", Stock: ptr(int64(1))},
|
||||
"external no provdr": {Name: "v", VoucherType: "FIXED_VALUE", FaceValue: 1, PointCost: 1, StockMode: "EXTERNAL"},
|
||||
"max per customer 0": {Name: "v", VoucherType: "FIXED_VALUE", FaceValue: 1, PointCost: 1, StockMode: "CODE_POOL", MaxPerCustomer: ptr(0)},
|
||||
"ends before it ends": {Name: "v", VoucherType: "FIXED_VALUE", FaceValue: 1, PointCost: 1, StockMode: "CODE_POOL", ValidFrom: ptr(e.now), ValidUntil: ptr(e.now)},
|
||||
"terms not an object": {Name: "v", VoucherType: "FIXED_VALUE", FaceValue: 1, PointCost: 1, StockMode: "CODE_POOL", Terms: json.RawMessage(`[1]`)},
|
||||
"archived on create": {Name: "v", VoucherType: "FIXED_VALUE", FaceValue: 1, PointCost: 1, StockMode: "CODE_POOL", Status: "ARCHIVED"},
|
||||
} {
|
||||
_, err := e.vouchers.CreateVoucher(ctx, e.orgA, e.manager, in)
|
||||
assert.ErrorIs(t, err, ErrEnakGameRejected, name)
|
||||
}
|
||||
|
||||
pool := e.voucher(e.orgA, models.VoucherInput{Name: "Kopi", FaceValue: 20_000, PointCost: 15_000, StockMode: "code_pool",
|
||||
Terms: json.RawMessage(`{"outlet": "semua"}`), Status: "DRAFT"})
|
||||
assert.Equal(t, constants.VoucherStockCodePool, pool.StockMode)
|
||||
assert.JSONEq(t, `{"outlet": "semua"}`, string(pool.Terms))
|
||||
|
||||
// Importing the same file twice adds nothing the second time.
|
||||
csv := []byte("code,expires_at\nKOPI-1,2030-12-31\nKOPI-2\nKOPI-2\n,\nKOPI-3,31/12/2030\nKOPI-4\n")
|
||||
result, err := e.vouchers.ImportCodes(ctx, e.orgA, e.manager, pool.ID, csv)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, 3, result.Imported)
|
||||
assert.Equal(t, []string{"KOPI-2"}, result.Duplicates, "repeated in the file")
|
||||
require.Len(t, result.Invalid, 1)
|
||||
assert.Equal(t, 6, result.Invalid[0].Line)
|
||||
result, err = e.vouchers.ImportCodes(ctx, e.orgA, e.manager, pool.ID, csv)
|
||||
require.NoError(t, err)
|
||||
assert.Zero(t, result.Imported)
|
||||
assert.Equal(t, 4, result.DuplicateCount)
|
||||
codes, err := e.vouchers.Codes(ctx, e.orgA, pool.ID, models.VoucherCodeListQuery{})
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, map[string]int64{"AVAILABLE": 3}, codes.Counts)
|
||||
require.Len(t, codes.Codes.Data, 3)
|
||||
var expiring *time.Time
|
||||
for _, c := range codes.Codes.Data {
|
||||
if c.Code == "KOPI-1" {
|
||||
expiring = c.ExpiresAt
|
||||
}
|
||||
}
|
||||
require.NotNil(t, expiring)
|
||||
assert.Equal(t, "2030-12-31 23:59:59", expiring.In(walletDisplayLocation).Format("2006-01-02 15:04:05"), "the end of that day in Jakarta")
|
||||
|
||||
static := e.staticVoucher(5, 10_000, 8_000)
|
||||
_, err = e.vouchers.ImportCodes(ctx, e.orgA, e.manager, static.ID, csv)
|
||||
assert.ErrorIs(t, err, ErrEnakGameRejected, "a STATIC voucher holds no codes")
|
||||
_, err = e.vouchers.ImportCodes(ctx, e.orgB, e.manager, pool.ID, csv)
|
||||
assert.ErrorIs(t, err, repository.ErrVoucherNotFound, "another organization's voucher")
|
||||
_, err = e.vouchers.GetVoucher(ctx, e.orgB, pool.ID)
|
||||
assert.ErrorIs(t, err, repository.ErrVoucherNotFound)
|
||||
|
||||
in := VoucherInputFrom(static)
|
||||
in.Stock, in.PointCost = ptr(int64(9)), 7_500
|
||||
updated, err := e.vouchers.UpdateVoucher(ctx, e.orgA, e.manager, static.ID, in)
|
||||
require.NoError(t, err)
|
||||
assert.EqualValues(t, 9, *updated.Stock)
|
||||
in.StockMode = constants.VoucherStockCodePool
|
||||
_, err = e.vouchers.UpdateVoucher(ctx, e.orgA, e.manager, static.ID, in)
|
||||
assert.ErrorIs(t, err, ErrEnakGameRejected, "the stock mode stays")
|
||||
|
||||
_, err = e.vouchers.SetVoucherStatus(ctx, e.orgA, e.manager, static.ID, models.VoucherStatusInput{Status: "ARCHIVED"})
|
||||
require.NoError(t, err)
|
||||
_, err = e.vouchers.UpdateVoucher(ctx, e.orgA, e.manager, static.ID, VoucherInputFrom(updated))
|
||||
assert.ErrorIs(t, err, ErrEnakGameRejected)
|
||||
list, err := e.vouchers.ListVouchers(ctx, e.orgA, models.VoucherListQuery{})
|
||||
require.NoError(t, err)
|
||||
assert.Len(t, list.Data, 1, "archived left out")
|
||||
assert.Equal(t, []string{"CREATED", "UPDATED", "STATUS_CHANGED"}, e.auditActions(constants.AuditEntityVoucher, static.ID))
|
||||
assert.Equal(t, []string{"CREATED", "CODES_IMPORTED", "CODES_IMPORTED"}, e.auditActions(constants.AuditEntityVoucher, pool.ID))
|
||||
}
|
||||
|
||||
// EG-504
|
||||
func TestVoucherRedemption(t *testing.T) {
|
||||
e := newEnakGameEnv(t)
|
||||
ctx := e.ctx()
|
||||
e.points(e.alice, constants.WalletTxTypeAdjustment, 100_000)
|
||||
e.points(e.bob, constants.WalletTxTypeAdjustment, 100_000)
|
||||
|
||||
t.Run("STATIC: the last one goes to exactly one of two customers", func(t *testing.T) {
|
||||
last := e.staticVoucher(1, 10_000, 8_000)
|
||||
var wg sync.WaitGroup
|
||||
results := make([]error, 2)
|
||||
for i, customer := range []uuid.UUID{e.alice, e.bob} {
|
||||
i, customer := i, customer
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
_, results[i] = e.redeemVoucher(customer, last.ID, "last")
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
won := 0
|
||||
for _, err := range results {
|
||||
if err == nil {
|
||||
won++
|
||||
} else {
|
||||
assert.ErrorIs(t, err, ErrVoucherRedemptionRejected)
|
||||
}
|
||||
}
|
||||
assert.Equal(t, 1, won)
|
||||
assert.Equal(t, int64(1), e.count(`SELECT COUNT(*) FROM voucher_redemptions WHERE voucher_id = ?`, last.ID))
|
||||
assert.EqualValues(t, 200_000-8_000, e.pointBalance(e.alice)+e.pointBalance(e.bob), "only the winner paid")
|
||||
assert.Zero(t, e.count(`SELECT stock FROM vouchers WHERE id = ?`, last.ID))
|
||||
})
|
||||
|
||||
t.Run("CODE_POOL: redemptions at once get different codes", func(t *testing.T) {
|
||||
pool := e.voucher(e.orgA, models.VoucherInput{FaceValue: 5_000, PointCost: 1_000, StockMode: constants.VoucherStockCodePool})
|
||||
_, err := e.vouchers.ImportCodes(ctx, e.orgA, e.manager, pool.ID, []byte("A1\nA2\nA3\nA4\nA5\nA6"))
|
||||
require.NoError(t, err)
|
||||
var wg sync.WaitGroup
|
||||
var mu sync.Mutex
|
||||
got := map[string]int{}
|
||||
for i := 0; i < 6; i++ {
|
||||
customer := []uuid.UUID{e.alice, e.bob}[i%2]
|
||||
key := fmt.Sprintf("pool-%d", i)
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
res, err := e.redeemVoucher(customer, pool.ID, key)
|
||||
if assert.NoError(t, err) {
|
||||
mu.Lock()
|
||||
got[*res.Code]++
|
||||
mu.Unlock()
|
||||
}
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
assert.Len(t, got, 6, "six different codes")
|
||||
for code, n := range got {
|
||||
assert.Equal(t, 1, n, code)
|
||||
}
|
||||
_, err = e.redeemVoucher(e.alice, pool.ID, "pool-empty")
|
||||
assert.ErrorIs(t, err, ErrVoucherRedemptionRejected, "the pool is empty")
|
||||
})
|
||||
|
||||
t.Run("the same key twice: one debit, one code", func(t *testing.T) {
|
||||
pool := e.voucher(e.orgA, models.VoucherInput{FaceValue: 5_000, PointCost: 1_000, StockMode: constants.VoucherStockCodePool})
|
||||
_, err := e.vouchers.ImportCodes(ctx, e.orgA, e.manager, pool.ID, []byte("B1\nB2"))
|
||||
require.NoError(t, err)
|
||||
before := e.pointBalance(e.alice)
|
||||
first, err := e.redeemVoucher(e.alice, pool.ID, "twice")
|
||||
require.NoError(t, err)
|
||||
assert.False(t, first.Replayed)
|
||||
require.NotNil(t, first.Code)
|
||||
assert.EqualValues(t, before-1_000, first.PointBalance)
|
||||
// The voucher is turned off meanwhile; the retry still gets its code.
|
||||
_, err = e.vouchers.SetVoucherStatus(ctx, e.orgA, e.manager, pool.ID, models.VoucherStatusInput{Status: "INACTIVE"})
|
||||
require.NoError(t, err)
|
||||
second, err := e.redeemVoucher(e.alice, pool.ID, "twice")
|
||||
require.NoError(t, err)
|
||||
assert.True(t, second.Replayed)
|
||||
assert.Equal(t, first.ID, second.ID)
|
||||
assert.Equal(t, *first.Code, *second.Code)
|
||||
assert.EqualValues(t, before-1_000, e.pointBalance(e.alice))
|
||||
assert.Equal(t, int64(1), e.count(`SELECT COUNT(*) FROM wallet_transactions WHERE customer_id = ? AND type = 'REWARD_REDEEM' AND reference_id = ?`, e.alice, first.ID))
|
||||
_, err = e.redeemVoucher(e.alice, uuid.New(), "twice")
|
||||
assert.ErrorIs(t, err, ErrVoucherRedemptionRejected, "the key redeemed another voucher")
|
||||
})
|
||||
|
||||
t.Run("refusals record nothing", func(t *testing.T) {
|
||||
pricey := e.staticVoucher(5, 10_000, 1_000_000)
|
||||
limited := e.voucher(e.orgA, models.VoucherInput{FaceValue: 1_000, PointCost: 10, StockMode: "STATIC", Stock: ptr(int64(5)), MaxPerCustomer: ptr(1)})
|
||||
later := e.voucher(e.orgA, models.VoucherInput{FaceValue: 1_000, PointCost: 10, StockMode: "STATIC", Stock: ptr(int64(5)), ValidFrom: ptr(e.now.Add(time.Hour))})
|
||||
ended := e.voucher(e.orgA, models.VoucherInput{FaceValue: 1_000, PointCost: 10, StockMode: "STATIC", Stock: ptr(int64(5)), ValidUntil: ptr(e.now.Add(-time.Second))})
|
||||
draft := e.voucher(e.orgA, models.VoucherInput{FaceValue: 1_000, PointCost: 10, StockMode: "STATIC", Stock: ptr(int64(5)), Status: "DRAFT"})
|
||||
external := e.voucher(e.orgA, models.VoucherInput{FaceValue: 1_000, PointCost: 10, StockMode: "EXTERNAL", Provider: ptr("no-adapter")})
|
||||
theirs := e.voucher(e.orgB, models.VoucherInput{FaceValue: 1_000, PointCost: 10, StockMode: "STATIC", Stock: ptr(int64(5))})
|
||||
_, err := e.redeemVoucher(e.bob, limited.ID, "limit-1")
|
||||
require.NoError(t, err)
|
||||
|
||||
count := func() int64 {
|
||||
return e.count(`SELECT COUNT(*) FROM voucher_redemptions WHERE organization_id IN (?, ?)`, e.orgA, e.orgB) +
|
||||
e.count(`SELECT COUNT(*) FROM wallet_transactions WHERE type = 'REWARD_REDEEM' AND organization_id IN (?, ?)`, e.orgA, e.orgB)
|
||||
}
|
||||
before, balance := count(), e.pointBalance(e.bob)
|
||||
for name, tc := range map[string]struct {
|
||||
voucher uuid.UUID
|
||||
pin string
|
||||
want error
|
||||
}{
|
||||
"not enough EnakPoint": {pricey.ID, testPin, ErrVoucherRedemptionRejected},
|
||||
"max per customer": {limited.ID, testPin, ErrVoucherRedemptionRejected},
|
||||
"not started": {later.ID, testPin, ErrVoucherRedemptionRejected},
|
||||
"ended": {ended.ID, testPin, ErrVoucherRedemptionRejected},
|
||||
"draft": {draft.ID, testPin, ErrVoucherRedemptionRejected},
|
||||
"external, no adapter": {external.ID, testPin, ErrVoucherRedemptionRejected},
|
||||
"another org": {theirs.ID, testPin, repository.ErrVoucherNotFound},
|
||||
"wrong PIN": {limited.ID, "000000", nil},
|
||||
} {
|
||||
if name == "wrong PIN" {
|
||||
// limited is used up for Bob; Alice has it free, so only the PIN stands in the way.
|
||||
_, err := e.redeem.Redeem(ctx, e.alice, tc.voucher, tc.pin, "pin", models.CustomerPinRequestInfo{})
|
||||
var pinErr *PinError
|
||||
assert.ErrorAs(t, err, &pinErr, name)
|
||||
continue
|
||||
}
|
||||
_, err := e.redeem.Redeem(ctx, e.bob, tc.voucher, tc.pin, "refused-"+name, models.CustomerPinRequestInfo{})
|
||||
assert.ErrorIs(t, err, tc.want, name)
|
||||
}
|
||||
assert.Equal(t, before, count(), "no redemption, no ledger row")
|
||||
assert.Equal(t, balance, e.pointBalance(e.bob))
|
||||
assert.EqualValues(t, 5, e.count(`SELECT stock FROM vouchers WHERE id = ?`, pricey.ID), "the stock taken for a refused redemption is back")
|
||||
assert.Zero(t, e.count(`SELECT pin_failed_attempts FROM customers WHERE id = ?`, e.bob), "a refusal before the PIN costs no attempt")
|
||||
})
|
||||
}
|
||||
|
||||
// EG-505
|
||||
func TestVoucherRedemption_CostAttribution(t *testing.T) {
|
||||
e := newEnakGameEnv(t)
|
||||
voucher := e.staticVoucher(100, 10_000, 8_000)
|
||||
|
||||
t.Run("GAME_REWARD → exchange → redeem", func(t *testing.T) {
|
||||
budget := e.rewardCoins(e.alice, 8_000)
|
||||
e.exchangeCoins(e.alice, 8_000)
|
||||
res, err := e.redeemVoucher(e.alice, voucher.ID, "chain-1")
|
||||
require.NoError(t, err)
|
||||
b := budget.String()
|
||||
assert.Equal(t, []costRow{{BudgetID: &b, SourceType: "GAME_REWARD", Points: 8_000, Cost: 10_000}}, e.costs(res.ID))
|
||||
})
|
||||
|
||||
t.Run("GAME_REWARD → transfer → exchange → redeem", func(t *testing.T) {
|
||||
budget := e.rewardCoins(e.alice, 8_000)
|
||||
// Alice sends the reward to Bob, who exchanges and redeems it.
|
||||
require.NoError(t, e.txm.WithTransaction(e.ctx(), func(ctx context.Context) error {
|
||||
require.NoError(t, e.wallet.LockWallets(ctx, e.alice, e.bob))
|
||||
group, outID, inID := uuid.New(), uuid.New(), uuid.New()
|
||||
out, err := e.wallet.Debit(ctx, WalletDebitInput{WalletEntry: WalletEntry{
|
||||
TransactionID: outID, CustomerID: e.alice, Currency: constants.WalletCurrencyCoin, Type: constants.WalletTxTypeTransferOut,
|
||||
Amount: 8_000, ReferenceType: constants.WalletRefTypeWalletTx, ReferenceID: inID, GroupID: &group,
|
||||
CounterpartyCustomerID: &e.bob, Description: "ke Bob",
|
||||
}})
|
||||
require.NoError(t, err)
|
||||
_, err = e.wallet.Credit(ctx, WalletCreditInput{
|
||||
WalletEntry: WalletEntry{
|
||||
TransactionID: inID, CustomerID: e.bob, Currency: constants.WalletCurrencyCoin, Type: constants.WalletTxTypeTransferIn,
|
||||
Amount: 8_000, ReferenceType: constants.WalletRefTypeWalletTx, ReferenceID: outID, GroupID: &group,
|
||||
CounterpartyCustomerID: &e.alice, Description: "dari Alice",
|
||||
},
|
||||
Lots: out.CarryOver(),
|
||||
})
|
||||
return err
|
||||
}))
|
||||
e.exchangeCoins(e.bob, 8_000)
|
||||
res, err := e.redeemVoucher(e.bob, voucher.ID, "chain-2")
|
||||
require.NoError(t, err)
|
||||
b := budget.String()
|
||||
assert.Equal(t, []costRow{{BudgetID: &b, SourceType: "GAME_REWARD", Points: 8_000, Cost: 10_000}}, e.costs(res.ID))
|
||||
})
|
||||
|
||||
t.Run("GAME_REWARD + EARN: only the reward counts against the budget", func(t *testing.T) {
|
||||
// RFC §7.6: Rp10.000 for 8.000 EnakPoint, 6.000 from EnakGame and 2.000 from
|
||||
// shopping: Rp7.500 to the budget, Rp2.500 to none.
|
||||
dina := e.newCustomer(e.orgA)
|
||||
budget := e.rewardCoins(dina, 6_000)
|
||||
e.exchangeCoins(dina, 6_000)
|
||||
e.points(dina, constants.WalletTxTypeEarn, 2_000)
|
||||
res, err := e.redeemVoucher(dina, voucher.ID, "mixed")
|
||||
require.NoError(t, err)
|
||||
b := budget.String()
|
||||
assert.Equal(t, []costRow{
|
||||
{BudgetID: &b, SourceType: "GAME_REWARD", Points: 6_000, Cost: 7_500},
|
||||
{BudgetID: nil, SourceType: "EARN", Points: 2_000, Cost: 2_500},
|
||||
}, e.costs(res.ID))
|
||||
var recognized time.Time
|
||||
require.NoError(t, e.db.Raw(`SELECT recognized_at FROM voucher_redemption_costs WHERE redemption_id = ? LIMIT 1`, res.ID).Scan(&recognized).Error)
|
||||
assert.WithinDuration(t, *res.CompletedAt, recognized, time.Millisecond, "recognized when the redemption completed")
|
||||
})
|
||||
|
||||
t.Run("the costs add up to the face value when they do not divide evenly", func(t *testing.T) {
|
||||
odd := e.staticVoucher(10, 1_000, 3)
|
||||
eko := e.newCustomer(e.orgA)
|
||||
budget := e.rewardCoins(eko, 1)
|
||||
e.exchangeCoins(eko, 1)
|
||||
e.points(eko, constants.WalletTxTypeEarn, 1)
|
||||
e.points(eko, constants.WalletTxTypeAdjustment, 1)
|
||||
res, err := e.redeemVoucher(eko, odd.ID, "odd")
|
||||
require.NoError(t, err)
|
||||
// 1.000 over three equal parts: 333 each, the rupiah left over to the first of
|
||||
// equals, in source order.
|
||||
b := budget.String()
|
||||
assert.ElementsMatch(t, []costRow{
|
||||
{BudgetID: nil, SourceType: "ADJUSTMENT", Points: 1, Cost: 334},
|
||||
{BudgetID: nil, SourceType: "EARN", Points: 1, Cost: 333},
|
||||
{BudgetID: &b, SourceType: "GAME_REWARD", Points: 1, Cost: 333},
|
||||
}, e.costs(res.ID))
|
||||
})
|
||||
}
|
||||
|
||||
// newCustomer adds a customer with the test PIN to org.
|
||||
func (e *enakGameEnv) newCustomer(org uuid.UUID) uuid.UUID {
|
||||
e.t.Helper()
|
||||
id := uuid.New()
|
||||
hash, err := bcrypt.GenerateFromPassword([]byte(testPin), bcrypt.MinCost)
|
||||
require.NoError(e.t, err)
|
||||
require.NoError(e.t, e.db.Exec(`INSERT INTO customers (id, organization_id, name, pin_hash, pin_set_at) VALUES (?, ?, 'extra', ?, NOW())`, id, org, string(hash)).Error)
|
||||
return id
|
||||
}
|
||||
|
||||
// EG-506, EG-507
|
||||
func TestVoucherCatalogRedemptionsAndExpiry(t *testing.T) {
|
||||
e := newEnakGameEnv(t)
|
||||
ctx := e.ctx()
|
||||
e.points(e.alice, constants.WalletTxTypeAdjustment, 10_000)
|
||||
|
||||
static := e.voucher(e.orgA, models.VoucherInput{Name: "A Static", FaceValue: 10_000, PointCost: 100, StockMode: "STATIC", Stock: ptr(int64(3))})
|
||||
pool := e.voucher(e.orgA, models.VoucherInput{Name: "B Pool", FaceValue: 5_000, PointCost: 200, StockMode: "CODE_POOL"})
|
||||
_, err := e.vouchers.ImportCodes(ctx, e.orgA, e.manager, pool.ID, []byte("P1\nP2\nP3,2020-01-01"))
|
||||
require.NoError(t, err)
|
||||
e.voucher(e.orgA, models.VoucherInput{Name: "Draft", FaceValue: 1, PointCost: 1, StockMode: "STATIC", Stock: ptr(int64(1)), Status: "DRAFT"})
|
||||
e.voucher(e.orgA, models.VoucherInput{Name: "External", FaceValue: 1, PointCost: 1, StockMode: "EXTERNAL", Provider: ptr("no-adapter")})
|
||||
e.voucher(e.orgA, models.VoucherInput{Name: "Ended", FaceValue: 1, PointCost: 1, StockMode: "STATIC", Stock: ptr(int64(1)), ValidUntil: ptr(e.now.Add(-time.Hour))})
|
||||
e.voucher(e.orgB, models.VoucherInput{Name: "Theirs", FaceValue: 1, PointCost: 1, StockMode: "STATIC", Stock: ptr(int64(1))})
|
||||
|
||||
catalog, err := e.redeem.Catalog(ctx, e.alice)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, catalog, 2, "only ACTIVE vouchers of the organization within their dates that can be redeemed now")
|
||||
byName := map[string]models.CustomerVoucher{}
|
||||
for _, v := range catalog {
|
||||
byName[v.Name] = v
|
||||
}
|
||||
assert.EqualValues(t, 3, *byName["A Static"].Available)
|
||||
assert.EqualValues(t, 2, *byName["B Pool"].Available, "the expired code is not available")
|
||||
raw, err := json.Marshal(catalog)
|
||||
require.NoError(t, err)
|
||||
for _, internal := range []string{"business_cost", "provider", "stock_mode", "REDEEMED", "EXPIRED", "counts"} {
|
||||
assert.NotContains(t, string(raw), internal)
|
||||
}
|
||||
|
||||
_, err = e.redeemVoucher(e.alice, static.ID, "s1")
|
||||
require.NoError(t, err)
|
||||
got, err := e.redeemVoucher(e.alice, pool.ID, "p1")
|
||||
require.NoError(t, err)
|
||||
list, err := e.redeem.ListRedemptions(ctx, e.alice, 1, 10)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, list.Data, 2)
|
||||
assert.Equal(t, got.ID, list.Data[0].ID, "newest first")
|
||||
assert.Equal(t, *got.Code, *list.Data[0].Code)
|
||||
assert.Contains(t, []string{"P1", "P2"}, *got.Code, "never the expired P3")
|
||||
assert.Equal(t, "B Pool", list.Data[0].VoucherName)
|
||||
assert.Nil(t, list.Data[1].Code, "a STATIC voucher has no code")
|
||||
other, err := e.redeem.ListRedemptions(ctx, e.bob, 1, 10)
|
||||
require.NoError(t, err)
|
||||
assert.Empty(t, other.Data)
|
||||
|
||||
// The expiry job moves the expired code out of AVAILABLE, once.
|
||||
expired, err := e.vouchers.ExpireCodes(ctx, e.now)
|
||||
require.NoError(t, err)
|
||||
assert.GreaterOrEqual(t, expired, int64(1))
|
||||
codes, err := e.vouchers.Codes(ctx, e.orgA, pool.ID, models.VoucherCodeListQuery{})
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, map[string]int64{"AVAILABLE": 1, "REDEEMED": 1, "EXPIRED": 1}, codes.Counts)
|
||||
expired, err = e.vouchers.ExpireCodes(ctx, e.now)
|
||||
require.NoError(t, err)
|
||||
assert.Zero(t, e.count(`SELECT COUNT(*) FROM voucher_codes WHERE voucher_id = ? AND status = 'AVAILABLE' AND expires_at <= NOW()`, pool.ID))
|
||||
_ = expired
|
||||
}
|
||||
@@ -0,0 +1,214 @@
|
||||
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")
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
package processor
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
var (
|
||||
// ErrVoucherProviderRejected is what an adapter wraps when the provider definitely
|
||||
// will not issue the voucher: out of stock, the product retired, the request
|
||||
// refused. The redemption fails and the EnakPoint go back.
|
||||
ErrVoucherProviderRejected = errors.New("voucher provider refused")
|
||||
// ErrVoucherProviderNotFound is what an adapter's Lookup wraps when the provider
|
||||
// has no record of the redemption: the issue request never reached it.
|
||||
ErrVoucherProviderNotFound = errors.New("voucher provider has no such redemption")
|
||||
)
|
||||
|
||||
// VoucherIssueRequest is one redemption of an EXTERNAL voucher sent to its provider.
|
||||
type VoucherIssueRequest struct {
|
||||
// The provider's idempotency key: asking twice for the same redemption must give
|
||||
// the same voucher, never a second one (docs/rfc-enakgame.md §7.5).
|
||||
RedemptionID uuid.UUID
|
||||
// The provider's own reference of the product, from vouchers.provider_ref.
|
||||
ProviderRef *string
|
||||
VoucherID uuid.UUID
|
||||
FaceValue int64
|
||||
CustomerID uuid.UUID
|
||||
}
|
||||
|
||||
// VoucherIssue is what a provider handed out.
|
||||
type VoucherIssue struct {
|
||||
Code string
|
||||
// The provider's reference of this issue, for support and reconciliation.
|
||||
Ref string
|
||||
}
|
||||
|
||||
// VoucherProvider issues EXTERNAL vouchers (EG-801). Adapters classify every outcome
|
||||
// through the error they return:
|
||||
//
|
||||
// - nil: issued.
|
||||
// - wrapping ErrVoucherProviderRejected: definitely not issued, and never will be.
|
||||
// - wrapping ErrVoucherProviderNotFound (Lookup only): the provider never got it.
|
||||
// - anything else, a timeout above all: unknown. The redemption stays PENDING and
|
||||
// the recovery job asks again.
|
||||
type VoucherProvider interface {
|
||||
Issue(ctx context.Context, req VoucherIssueRequest) (*VoucherIssue, error)
|
||||
Lookup(ctx context.Context, req VoucherIssueRequest) (*VoucherIssue, error)
|
||||
}
|
||||
|
||||
// VoucherProviders are the adapters by the name vouchers.provider holds.
|
||||
type VoucherProviders map[string]VoucherProvider
|
||||
|
||||
// voucherIssueOutcome is how one call to a provider ended.
|
||||
type voucherIssueOutcome int
|
||||
|
||||
const (
|
||||
voucherIssued voucherIssueOutcome = iota
|
||||
voucherRejected
|
||||
voucherUnknown
|
||||
voucherNotFound
|
||||
)
|
||||
|
||||
func classifyVoucherIssue(issue *VoucherIssue, err error) voucherIssueOutcome {
|
||||
switch {
|
||||
case err == nil && issue != nil && issue.Code != "":
|
||||
return voucherIssued
|
||||
case errors.Is(err, ErrVoucherProviderRejected):
|
||||
return voucherRejected
|
||||
case errors.Is(err, ErrVoucherProviderNotFound):
|
||||
return voucherNotFound
|
||||
}
|
||||
// An error of any other kind, or a success without a code, settles nothing.
|
||||
return voucherUnknown
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package processor
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestClassifyVoucherIssue(t *testing.T) {
|
||||
issued := &VoucherIssue{Code: "ABC"}
|
||||
for name, tc := range map[string]struct {
|
||||
issue *VoucherIssue
|
||||
err error
|
||||
want voucherIssueOutcome
|
||||
}{
|
||||
"issued": {issued, nil, voucherIssued},
|
||||
"issued without code": {&VoucherIssue{}, nil, voucherUnknown},
|
||||
"no issue, no error": {nil, nil, voucherUnknown},
|
||||
"refused": {nil, fmt.Errorf("acme: %w: sold out", ErrVoucherProviderRejected), voucherRejected},
|
||||
"never got it": {nil, fmt.Errorf("acme: %w", ErrVoucherProviderNotFound), voucherNotFound},
|
||||
"timeout": {nil, context.DeadlineExceeded, voucherUnknown},
|
||||
"server error": {nil, errors.New("acme: 502 bad gateway"), voucherUnknown},
|
||||
"code with odd error": {issued, errors.New("acme: partial response"), voucherUnknown},
|
||||
"refused despite code": {issued, ErrVoucherProviderRejected, voucherRejected},
|
||||
} {
|
||||
assert.Equal(t, tc.want, classifyVoucherIssue(tc.issue, tc.err), name)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,196 @@
|
||||
package processor
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"apskel-pos-be/internal/constants"
|
||||
"apskel-pos-be/internal/entities"
|
||||
"apskel-pos-be/internal/logger"
|
||||
)
|
||||
|
||||
const (
|
||||
// voucherProviderTimeout bounds one call to a provider. A call that runs out is an
|
||||
// unknown outcome, settled later by the recovery job.
|
||||
voucherProviderTimeout = 10 * time.Second
|
||||
// voucherRecoveryAfter is how long a PENDING redemption waits before the recovery
|
||||
// job asks its provider again.
|
||||
voucherRecoveryAfter = 2 * time.Minute
|
||||
// voucherMaxAttempts is how many calls a redemption gets before the job gives up,
|
||||
// refunds it and marks it FAILED.
|
||||
voucherMaxAttempts = 10
|
||||
// voucherRecoveryBatch is how many PENDING redemptions one run of the job claims.
|
||||
voucherRecoveryBatch = 50
|
||||
)
|
||||
|
||||
// issueExternal asks an EXTERNAL voucher's provider for the voucher of a PENDING
|
||||
// redemption, outside any transaction, and settles the redemption with the answer
|
||||
// (docs/rfc-enakgame.md §7.5). With lookup, it first asks whether the provider already
|
||||
// issued it, and only asks to issue when the provider never got the request.
|
||||
//
|
||||
// The call does not stop when the customer's request does: an answer the provider
|
||||
// gave must not be thrown away.
|
||||
func (p *VoucherRedemptionProcessor) issueExternal(ctx context.Context, r *entities.VoucherRedemption, v *entities.Voucher, lookup bool) (*entities.VoucherRedemption, error) {
|
||||
provider, ok := p.providerOf(v)
|
||||
var issue *VoucherIssue
|
||||
var err error
|
||||
if ok {
|
||||
req := VoucherIssueRequest{RedemptionID: r.ID, ProviderRef: v.ProviderRef, VoucherID: v.ID, FaceValue: r.FaceValue, CustomerID: r.CustomerID}
|
||||
callCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), voucherProviderTimeout)
|
||||
if lookup {
|
||||
issue, err = provider.Lookup(callCtx, req)
|
||||
}
|
||||
if !lookup || classifyVoucherIssue(issue, err) == voucherNotFound {
|
||||
issue, err = provider.Issue(callCtx, req)
|
||||
}
|
||||
cancel()
|
||||
} else {
|
||||
err = fmt.Errorf("no adapter for provider %q", providerName(v))
|
||||
}
|
||||
outcome := classifyVoucherIssue(issue, err)
|
||||
if outcome == voucherUnknown || outcome == voucherNotFound {
|
||||
logger.FromContext(ctx).WithError(err).Warn("Voucher provider gave no answer; the redemption stays PENDING")
|
||||
}
|
||||
return p.settleExternal(ctx, r.ID, outcome, issue, err)
|
||||
}
|
||||
|
||||
// settleExternal applies a provider's answer to a redemption that is still PENDING,
|
||||
// under its customer's wallet lock: COMPLETED with the voucher and its cost split, or
|
||||
// FAILED with its EnakPoint refunded. An unknown answer leaves it PENDING, until it
|
||||
// has had voucherMaxAttempts calls; then it is refunded too. A redemption no longer
|
||||
// PENDING is left as it is, so settling twice refunds nothing twice.
|
||||
func (p *VoucherRedemptionProcessor) settleExternal(ctx context.Context, id uuid.UUID, outcome voucherIssueOutcome, issue *VoucherIssue, callErr error) (*entities.VoucherRedemption, error) {
|
||||
var settled *entities.VoucherRedemption
|
||||
err := p.tx.WithTransaction(ctx, func(ctx context.Context) error {
|
||||
r, err := p.redemptions.GetRedemption(ctx, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := p.wallet.LockWallet(ctx, r.CustomerID); err != nil {
|
||||
return err
|
||||
}
|
||||
if r, err = p.redemptions.GetRedemption(ctx, id); err != nil {
|
||||
return err
|
||||
}
|
||||
settled = r
|
||||
if r.Status != constants.VoucherRedemptionPending {
|
||||
return nil
|
||||
}
|
||||
now := p.now()
|
||||
switch outcome {
|
||||
case voucherIssued:
|
||||
code, ref := issue.Code, issue.Ref
|
||||
var refPtr *string
|
||||
if ref != "" {
|
||||
refPtr = &ref
|
||||
}
|
||||
moved, err := p.redemptions.MarkCompleted(ctx, r.ID, &code, refPtr, now)
|
||||
if err != nil || !moved {
|
||||
return err
|
||||
}
|
||||
r.Status, r.ExternalCode, r.ExternalRef, r.CompletedAt = constants.VoucherRedemptionCompleted, &code, refPtr, &now
|
||||
return p.recordCost(ctx, r)
|
||||
case voucherRejected:
|
||||
return p.refundExternal(ctx, r, "the provider refused: "+callErr.Error())
|
||||
}
|
||||
attempts, err := p.redemptions.TouchPending(ctx, r.ID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
r.Attempts = attempts
|
||||
if attempts >= voucherMaxAttempts {
|
||||
return p.refundExternal(ctx, r, fmt.Sprintf("the provider did not confirm the voucher after %d attempts", attempts))
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return settled, nil
|
||||
}
|
||||
|
||||
// refundExternal gives back the EnakPoint of a redemption that will not complete and
|
||||
// marks it FAILED (§7.5). The refund keeps the expiry of the lots the debit drew from,
|
||||
// with at least seven days left (§6.3).
|
||||
func (p *VoucherRedemptionProcessor) refundExternal(ctx context.Context, r *entities.VoucherRedemption, reason string) error {
|
||||
lots, err := p.wallet.RefundLots(ctx, r.DebitTransactionID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
debitID := r.DebitTransactionID
|
||||
refund, err := p.wallet.Credit(ctx, WalletCreditInput{
|
||||
WalletEntry: WalletEntry{
|
||||
CustomerID: r.CustomerID,
|
||||
Currency: constants.WalletCurrencyPoint,
|
||||
Type: constants.WalletTxTypeRewardRedeemRefund,
|
||||
Amount: r.PointCost,
|
||||
ReferenceType: constants.WalletRefTypeRewardRedemption,
|
||||
ReferenceID: r.ID,
|
||||
ReversesTransactionID: &debitID,
|
||||
Description: "Pengembalian EnakPoint voucher",
|
||||
Metadata: entities.Metadata{"voucher_id": r.VoucherID.String(), "reason": reason},
|
||||
IdempotencyKey: "redeem-refund:" + r.ID.String(),
|
||||
},
|
||||
Lots: lots,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
moved, err := p.redemptions.MarkFailed(ctx, r.ID, refund.Transaction.ID, reason)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !moved {
|
||||
return errors.New("voucher redemption left PENDING during its refund")
|
||||
}
|
||||
r.Status, r.RefundTransactionID, r.FailureReason = constants.VoucherRedemptionFailed, &refund.Transaction.ID, &reason
|
||||
return nil
|
||||
}
|
||||
|
||||
// RecoverPending is the recovery job (§7.5 step 4): it asks the provider again about
|
||||
// every redemption PENDING for longer than voucherRecoveryAfter, and settles it. It
|
||||
// returns how many it completed and how many it failed.
|
||||
func (p *VoucherRedemptionProcessor) RecoverPending(ctx context.Context) (completed, failed int, err error) {
|
||||
claimed, err := p.redemptions.ClaimStalePending(ctx, p.now().Add(-voucherRecoveryAfter), voucherRecoveryBatch)
|
||||
if err != nil {
|
||||
return 0, 0, err
|
||||
}
|
||||
var failures []error
|
||||
for i := range claimed {
|
||||
r := &claimed[i]
|
||||
v, err := p.vouchers.GetVoucher(ctx, r.OrganizationID, r.VoucherID)
|
||||
if err == nil {
|
||||
r, err = p.issueExternal(ctx, r, v, true)
|
||||
}
|
||||
if err != nil {
|
||||
failures = append(failures, fmt.Errorf("redemption %s: %w", claimed[i].ID, err))
|
||||
continue
|
||||
}
|
||||
switch r.Status {
|
||||
case constants.VoucherRedemptionCompleted:
|
||||
completed++
|
||||
case constants.VoucherRedemptionFailed:
|
||||
failed++
|
||||
}
|
||||
}
|
||||
return completed, failed, errors.Join(failures...)
|
||||
}
|
||||
|
||||
func (p *VoucherRedemptionProcessor) providerOf(v *entities.Voucher) (VoucherProvider, bool) {
|
||||
if v.Provider == nil {
|
||||
return nil, false
|
||||
}
|
||||
provider, ok := p.providers[*v.Provider]
|
||||
return provider, ok
|
||||
}
|
||||
|
||||
func providerName(v *entities.Voucher) string {
|
||||
if v.Provider == nil {
|
||||
return ""
|
||||
}
|
||||
return *v.Provider
|
||||
}
|
||||
@@ -0,0 +1,343 @@
|
||||
package processor
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"apskel-pos-be/internal/constants"
|
||||
"apskel-pos-be/internal/entities"
|
||||
"apskel-pos-be/internal/models"
|
||||
"apskel-pos-be/internal/repository"
|
||||
)
|
||||
|
||||
// ErrVoucherRedemptionRejected wraps every reason a customer cannot redeem a voucher:
|
||||
// the key, the voucher's status or dates, the stock, the per-customer limit, the
|
||||
// EnakPoint balance. The message says which.
|
||||
var ErrVoucherRedemptionRejected = errors.New("voucher redemption refused")
|
||||
|
||||
// catalogStockModes are the vouchers the catalog lists. An EXTERNAL one is listed only
|
||||
// when its provider has an adapter.
|
||||
var catalogStockModes = []string{constants.VoucherStockStatic, constants.VoucherStockCodePool, constants.VoucherStockExternal}
|
||||
|
||||
func redemptionRejected(format string, args ...any) error {
|
||||
return fmt.Errorf("%w: %s", ErrVoucherRedemptionRejected, fmt.Sprintf(format, args...))
|
||||
}
|
||||
|
||||
// VoucherRedemptionProcessor redeems EnakPoint for vouchers and records what each
|
||||
// redemption cost each budget (docs/rfc-enakgame.md §7.4, §7.6, D5).
|
||||
type VoucherRedemptionProcessor struct {
|
||||
customers gameCustomerReader
|
||||
vouchers repository.VoucherRepository
|
||||
redemptions repository.VoucherRedemptionRepository
|
||||
pins pinVerifier
|
||||
spendable spendableReader
|
||||
wallet *WalletProcessor
|
||||
providers VoucherProviders
|
||||
tx TxRunner
|
||||
now func() time.Time
|
||||
}
|
||||
|
||||
func NewVoucherRedemptionProcessor(customers gameCustomerReader, vouchers repository.VoucherRepository, redemptions repository.VoucherRedemptionRepository,
|
||||
pins pinVerifier, spendable spendableReader, wallet *WalletProcessor, providers VoucherProviders, tx TxRunner) *VoucherRedemptionProcessor {
|
||||
return &VoucherRedemptionProcessor{
|
||||
customers: customers, vouchers: vouchers, redemptions: redemptions, pins: pins, spendable: spendable,
|
||||
wallet: wallet, providers: providers, tx: tx, now: time.Now,
|
||||
}
|
||||
}
|
||||
|
||||
// Redeem takes a voucher's point cost in EnakPoint and hands out the voucher, in one
|
||||
// transaction (§7.4): the stock, the code, the debit, the redemption and its cost
|
||||
// split all commit together or not at all. The PIN approves it (K8).
|
||||
//
|
||||
// An EXTERNAL voucher comes from its provider, which is never called inside a
|
||||
// transaction (§7.5): the redemption is written PENDING with its debit first, the
|
||||
// provider is asked, and its answer completes it, fails and refunds it, or, when
|
||||
// there is no answer, leaves it PENDING for the recovery job.
|
||||
//
|
||||
// idempotencyKey is the client's Idempotency-Key: a retry with the same key returns
|
||||
// the first redemption, with its code, and takes nothing more.
|
||||
func (p *VoucherRedemptionProcessor) Redeem(ctx context.Context, customerID, voucherID uuid.UUID, pin, idempotencyKey string, info models.CustomerPinRequestInfo) (*models.VoucherRedeemResult, error) {
|
||||
key := strings.TrimSpace(idempotencyKey)
|
||||
if key == "" {
|
||||
return nil, redemptionRejected("the Idempotency-Key header is required")
|
||||
}
|
||||
if len(key) > gameSessionKeyLimit {
|
||||
return nil, redemptionRejected("the Idempotency-Key header must be at most %d characters", gameSessionKeyLimit)
|
||||
}
|
||||
customer, err := p.customers.GetCustomer(ctx, customerID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// A retry is answered before anything else is checked: the voucher may have run
|
||||
// out or ended since, but this redemption went through.
|
||||
if previous, err := p.redemptions.GetByKey(ctx, customerID, key); err != nil || previous != nil {
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return p.replay(ctx, previous, voucherID)
|
||||
}
|
||||
if !customer.IsActive {
|
||||
return nil, redemptionRejected("the customer is not active")
|
||||
}
|
||||
voucher, err := p.vouchers.GetVoucher(ctx, customer.OrganizationID, voucherID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// Refuse what cannot work before the PIN is checked, so it costs no attempt.
|
||||
if err := p.redeemable(voucher, p.now()); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := p.pins.VerifyPin(ctx, customerID, pin, PinActionRedeem, info); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var redemption *entities.VoucherRedemption
|
||||
var code *entities.VoucherCode
|
||||
replayed := false
|
||||
err = p.tx.WithTransaction(ctx, func(ctx context.Context) error {
|
||||
if err := p.wallet.LockWallet(ctx, customerID); err != nil {
|
||||
return err
|
||||
}
|
||||
// Under the lock, a request sent twice at once finds the first one here.
|
||||
previous, err := p.redemptions.GetByKey(ctx, customerID, key)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if previous != nil {
|
||||
redemption, replayed = previous, true
|
||||
return nil
|
||||
}
|
||||
if voucher, err = p.vouchers.GetVoucher(ctx, customer.OrganizationID, voucherID); err != nil {
|
||||
return err
|
||||
}
|
||||
now := p.now()
|
||||
if err := p.redeemable(voucher, now); err != nil {
|
||||
return err
|
||||
}
|
||||
if voucher.MaxPerCustomer != nil {
|
||||
// Counted under the wallet lock, so the customer's own redemptions at the
|
||||
// same time see each other.
|
||||
count, err := p.redemptions.CountForCustomer(ctx, customerID, voucher.ID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if count >= int64(*voucher.MaxPerCustomer) {
|
||||
return redemptionRejected("this voucher can be redeemed at most %d times per customer", *voucher.MaxPerCustomer)
|
||||
}
|
||||
}
|
||||
|
||||
redemptionID := uuid.New()
|
||||
switch voucher.StockMode {
|
||||
case constants.VoucherStockStatic:
|
||||
taken, err := p.vouchers.TakeStock(ctx, voucher.ID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !taken {
|
||||
return redemptionRejected("the voucher is out of stock")
|
||||
}
|
||||
case constants.VoucherStockCodePool:
|
||||
if code, err = p.vouchers.ClaimCode(ctx, voucher.ID, redemptionID, now); err != nil {
|
||||
return err
|
||||
}
|
||||
if code == nil {
|
||||
return redemptionRejected("the voucher is out of stock")
|
||||
}
|
||||
}
|
||||
external := voucher.StockMode == constants.VoucherStockExternal
|
||||
|
||||
debit, err := p.wallet.Debit(ctx, WalletDebitInput{WalletEntry: WalletEntry{
|
||||
CustomerID: customerID,
|
||||
Currency: constants.WalletCurrencyPoint,
|
||||
Type: constants.WalletTxTypeRewardRedeem,
|
||||
Amount: voucher.PointCost,
|
||||
ReferenceType: constants.WalletRefTypeRewardRedemption,
|
||||
ReferenceID: redemptionID,
|
||||
Description: truncateDescription("Tukar voucher " + voucher.Name),
|
||||
Metadata: entities.Metadata{"voucher_id": voucher.ID.String(), "face_value": voucher.FaceValue},
|
||||
IdempotencyKey: "redeem:" + redemptionID.String(),
|
||||
}})
|
||||
if errors.Is(err, repository.ErrWalletInsufficientBalance) {
|
||||
return redemptionRejected("not enough EnakPoint")
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
redemption = &entities.VoucherRedemption{
|
||||
ID: redemptionID,
|
||||
OrganizationID: customer.OrganizationID,
|
||||
CustomerID: customerID,
|
||||
VoucherID: voucher.ID,
|
||||
IdempotencyKey: key,
|
||||
Status: constants.VoucherRedemptionCompleted,
|
||||
FaceValue: voucher.FaceValue,
|
||||
PointCost: voucher.PointCost,
|
||||
DebitTransactionID: debit.Transaction.ID,
|
||||
CompletedAt: &now,
|
||||
}
|
||||
if external {
|
||||
// Its cost is split once the provider has issued it.
|
||||
redemption.Status, redemption.CompletedAt = constants.VoucherRedemptionPending, nil
|
||||
}
|
||||
if code != nil {
|
||||
redemption.VoucherCodeID = &code.ID
|
||||
}
|
||||
if err := p.redemptions.CreateRedemption(ctx, redemption); err != nil {
|
||||
return err
|
||||
}
|
||||
if external {
|
||||
return nil
|
||||
}
|
||||
return p.recordCost(ctx, redemption)
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if replayed {
|
||||
return p.replay(ctx, redemption, voucherID)
|
||||
}
|
||||
if redemption.Status == constants.VoucherRedemptionPending {
|
||||
if redemption, err = p.issueExternal(ctx, redemption, voucher, false); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return p.result(ctx, redemption, voucher, code, false)
|
||||
}
|
||||
|
||||
// recordCost splits a completed redemption's face value over where its EnakPoint
|
||||
// came from and freezes the split (§7.6). Only the part from EnakGame rewards names
|
||||
// a budget; the rest is kept for reporting.
|
||||
func (p *VoucherRedemptionProcessor) recordCost(ctx context.Context, redemption *entities.VoucherRedemption) error {
|
||||
sources, err := p.redemptions.PointSources(ctx, redemption.DebitTransactionID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var traced int64
|
||||
for _, s := range sources {
|
||||
traced += s.Points
|
||||
}
|
||||
if traced != redemption.PointCost {
|
||||
return fmt.Errorf("redemption %s: traced %d EnakPoint back to their source, not %d", redemption.ID, traced, redemption.PointCost)
|
||||
}
|
||||
parts := SplitVoucherCost(redemption.FaceValue, sources)
|
||||
costs := make([]entities.VoucherRedemptionCost, 0, len(parts))
|
||||
for _, part := range parts {
|
||||
costs = append(costs, entities.VoucherRedemptionCost{
|
||||
RedemptionID: redemption.ID, BudgetID: part.BudgetID, SourceType: part.SourceType,
|
||||
Points: part.Points, Cost: part.Cost, RecognizedAt: *redemption.CompletedAt,
|
||||
})
|
||||
}
|
||||
return p.redemptions.CreateCosts(ctx, costs)
|
||||
}
|
||||
|
||||
// replay answers a retry with the redemption it repeats.
|
||||
func (p *VoucherRedemptionProcessor) replay(ctx context.Context, redemption *entities.VoucherRedemption, voucherID uuid.UUID) (*models.VoucherRedeemResult, error) {
|
||||
if redemption.VoucherID != voucherID {
|
||||
return nil, redemptionRejected("this Idempotency-Key was already used to redeem another voucher")
|
||||
}
|
||||
voucher, err := p.vouchers.GetVoucher(ctx, redemption.OrganizationID, redemption.VoucherID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var code *entities.VoucherCode
|
||||
if redemption.VoucherCodeID != nil {
|
||||
if code, err = p.vouchers.GetCode(ctx, *redemption.VoucherCodeID); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return p.result(ctx, redemption, voucher, code, true)
|
||||
}
|
||||
|
||||
func (p *VoucherRedemptionProcessor) result(ctx context.Context, r *entities.VoucherRedemption, v *entities.Voucher, code *entities.VoucherCode, replayed bool) (*models.VoucherRedeemResult, error) {
|
||||
balances, err := p.spendable.SpendableBalances(ctx, r.CustomerID, p.now())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
item := repository.CustomerRedemption{VoucherRedemption: *r, VoucherName: v.Name, VoucherImageURL: v.ImageURL, VoucherType: v.VoucherType, Code: r.ExternalCode}
|
||||
if code != nil {
|
||||
c := code.Code
|
||||
item.Code, item.CodeExpiresAt = &c, code.ExpiresAt
|
||||
}
|
||||
return &models.VoucherRedeemResult{
|
||||
CustomerVoucherRedemption: customerRedemptionModel(item),
|
||||
PointBalance: balances[constants.WalletCurrencyPoint],
|
||||
Replayed: replayed,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Catalog returns the vouchers the customer can redeem now, with how many are left.
|
||||
func (p *VoucherRedemptionProcessor) Catalog(ctx context.Context, customerID uuid.UUID) ([]models.CustomerVoucher, error) {
|
||||
customer, err := p.customers.GetCustomer(ctx, customerID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
vouchers, err := p.vouchers.ListCatalog(ctx, customer.OrganizationID, p.now(), catalogStockModes)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out := make([]models.CustomerVoucher, 0, len(vouchers))
|
||||
for _, v := range vouchers {
|
||||
if v.StockMode == constants.VoucherStockExternal {
|
||||
if _, ok := p.providerOf(&v.Voucher); !ok {
|
||||
continue
|
||||
}
|
||||
}
|
||||
out = append(out, models.CustomerVoucher{
|
||||
ID: v.ID, Name: v.Name, Description: v.Description, ImageURL: v.ImageURL, VoucherType: v.VoucherType,
|
||||
FaceValue: v.FaceValue, PointCost: v.PointCost, MaxPerCustomer: v.MaxPerCustomer, ValidUntil: v.ValidUntil,
|
||||
Terms: []byte(v.Terms), Available: v.Available,
|
||||
})
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// ListRedemptions returns a page of the customer's redemptions, newest first, with
|
||||
// their codes.
|
||||
func (p *VoucherRedemptionProcessor) ListRedemptions(ctx context.Context, customerID uuid.UUID, page, limit int) (*models.PaginatedResponse[models.CustomerVoucherRedemption], error) {
|
||||
page, limit = enakGamePage(page, limit)
|
||||
rows, total, err := p.redemptions.ListCustomerRedemptions(ctx, customerID, (page-1)*limit, limit)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items := make([]models.CustomerVoucherRedemption, 0, len(rows))
|
||||
for _, row := range rows {
|
||||
items = append(items, customerRedemptionModel(row))
|
||||
}
|
||||
return &models.PaginatedResponse[models.CustomerVoucherRedemption]{Data: items, Pagination: enakGamePagination(page, limit, total)}, nil
|
||||
}
|
||||
|
||||
// redeemable says why a voucher cannot be redeemed now, or nil.
|
||||
func (p *VoucherRedemptionProcessor) redeemable(v *entities.Voucher, now time.Time) error {
|
||||
if v.StockMode == constants.VoucherStockExternal {
|
||||
if _, ok := p.providerOf(v); !ok {
|
||||
return redemptionRejected("the voucher is not available yet")
|
||||
}
|
||||
}
|
||||
return redeemableNow(v, now)
|
||||
}
|
||||
|
||||
func redeemableNow(v *entities.Voucher, now time.Time) error {
|
||||
switch {
|
||||
case v.Status != constants.VoucherStatusActive:
|
||||
return redemptionRejected("the voucher is not available")
|
||||
case v.ValidFrom != nil && now.Before(*v.ValidFrom):
|
||||
return redemptionRejected("the voucher cannot be redeemed yet")
|
||||
case v.ValidUntil != nil && !now.Before(*v.ValidUntil):
|
||||
return redemptionRejected("the voucher has ended")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func customerRedemptionModel(r repository.CustomerRedemption) models.CustomerVoucherRedemption {
|
||||
return models.CustomerVoucherRedemption{
|
||||
ID: r.ID, VoucherID: r.VoucherID, VoucherName: r.VoucherName, VoucherImageURL: r.VoucherImageURL,
|
||||
VoucherType: r.VoucherType, Status: r.Status, FaceValue: r.FaceValue, PointCost: r.PointCost,
|
||||
Code: r.Code, CodeExpiresAt: r.CodeExpiresAt, CompletedAt: r.CompletedAt, CreatedAt: r.CreatedAt,
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user