Compare commits
16
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
053d6a4243 | ||
|
|
2c9753fae7 | ||
|
|
3ebc09f818 | ||
|
|
117e3529aa | ||
|
|
b59b7b4ddd | ||
|
|
fbe7e97dc7 | ||
|
|
b372821b23 | ||
|
|
d3e3ea6b08 | ||
|
|
b0ef226af1 | ||
|
|
79226bd891 | ||
|
|
306eabb1d9 | ||
|
|
892575202b | ||
|
|
c9654a387a | ||
|
|
e94eb2c26d | ||
|
|
e8b31035f7 | ||
|
|
100e006218 |
+1
-1
@@ -15,6 +15,6 @@ COPY --from=build /out/app /app
|
|||||||
ENV TZ=Asia/Jakarta
|
ENV TZ=Asia/Jakarta
|
||||||
EXPOSE 4000
|
EXPOSE 4000
|
||||||
HEALTHCHECK --interval=30s --timeout=10s --start-period=30s --retries=3 \
|
HEALTHCHECK --interval=30s --timeout=10s --start-period=30s --retries=3 \
|
||||||
CMD curl -fsS http://localhost:3300/health || exit 1
|
CMD curl -fsS http://localhost:4000/health || exit 1
|
||||||
USER appuser
|
USER appuser
|
||||||
ENTRYPOINT ["/app"]
|
ENTRYPOINT ["/app"]
|
||||||
|
|||||||
+34
-95
@@ -2,7 +2,9 @@
|
|||||||
|
|
||||||
30 Sep 2026
|
30 Sep 2026
|
||||||
|
|
||||||
Semua endpoint EnakPoint (`POINT`, bisa bayar order) dan EnakCoin (`COIN`, untuk game dan ditukar ke EnakPoint) ada di bawah base URL `/api/v1`, memakai satu format response, dan semua jumlah berupa bilangan bulat.
|
Semua endpoint EnakPoint (`POINT`, hanya untuk ditukar ke voucher) dan EnakCoin (`COIN`, untuk game dan ditukar ke EnakPoint) ada di bawah base URL `/api/v1`, memakai satu format response, dan semua jumlah berupa bilangan bulat.
|
||||||
|
|
||||||
|
> **Perubahan 7 Okt 2026:** bayar order dengan EnakPoint sudah dihapus, karena EnakPoint sekarang hanya bisa ditukar ke voucher: tidak bisa dipakai sebagai alat bayar dan tidak bisa dicairkan ([`enakgame-prd.md`](./enakgame-prd.md) §3.2). Endpoint dan field yang ikut dihapus ada di Referensi → Endpoint dan field yang dihapus.
|
||||||
|
|
||||||
## Konvensi umum
|
## Konvensi umum
|
||||||
|
|
||||||
@@ -28,7 +30,7 @@ Semua endpoint EnakPoint (`POINT`, bisa bayar order) dan EnakCoin (`COIN`, untuk
|
|||||||
|
|
||||||
**Error PIN** membawa `data` yang tidak `null`: `{"code": "PIN_INVALID", "remaining_attempts": 3}`, `{"code": "PIN_LOCKED", "locked_until": "…"}`, atau `{"code": "TRANSFER_BLOCKED", "transfer_blocked_until": "…"}`. Endpoint yang menerima `pin` bisa mengembalikan salah satunya. PIN selalu dikirim sebagai string 6 digit.
|
**Error PIN** membawa `data` yang tidak `null`: `{"code": "PIN_INVALID", "remaining_attempts": 3}`, `{"code": "PIN_LOCKED", "locked_until": "…"}`, atau `{"code": "TRANSFER_BLOCKED", "transfer_blocked_until": "…"}`. Endpoint yang menerima `pin` bisa mengembalikan salah satunya. PIN selalu dikirim sebagai string 6 digit.
|
||||||
|
|
||||||
**Idempotency.** Exchange dan transfer wajib header `Idempotency-Key` (maks. 50 karakter, `X-Idempotency-Key` juga diterima): satu key per percobaan, dan key yang sama dipakai ulang saat retry. Retry mengembalikan hasil pertama dengan `replayed: true`. `POST /payments` wajib `X-Idempotency-Key` seperti pembayaran lain.
|
**Idempotency.** Exchange dan transfer wajib header `Idempotency-Key` (maks. 50 karakter, `X-Idempotency-Key` juga diterima): satu key per percobaan, dan key yang sama dipakai ulang saat retry. Retry mengembalikan hasil pertama dengan `replayed: true`.
|
||||||
|
|
||||||
**Waktu.** Tanggal kedaluwarsa dan filter tanggal memakai WIB. Saldo berlaku sampai 23:59:59 WIB pada tanggal kedaluwarsanya.
|
**Waktu.** Tanggal kedaluwarsa dan filter tanggal memakai WIB. Saldo berlaku sampai 23:59:59 WIB pada tanggal kedaluwarsanya.
|
||||||
|
|
||||||
@@ -41,9 +43,9 @@ Semua endpoint EnakPoint (`POINT`, bisa bayar order) dan EnakCoin (`COIN`, untuk
|
|||||||
| GET | `/customer/wallet/expiring` | Saldo yang akan kedaluwarsa, per currency dan tanggal |
|
| GET | `/customer/wallet/expiring` | Saldo yang akan kedaluwarsa, per currency dan tanggal |
|
||||||
| PUT | `/customer/devices` | Daftarkan token FCM device |
|
| PUT | `/customer/devices` | Daftarkan token FCM device |
|
||||||
| DELETE | `/customer/devices/:device_id` | Hapus device saat logout |
|
| DELETE | `/customer/devices/:device_id` | Hapus device saat logout |
|
||||||
| GET | `/customer/outlets` | Outlet aktif di organisasi customer, dengan `accepts_point_payment`, `earns_points`, `earns_coins` |
|
| GET | `/customer/outlets` | Outlet aktif di organisasi customer, dengan `earns_points`, `earns_coins` |
|
||||||
| GET | `/customer/orders` | Riwayat order customer (`page`, `limit`), dengan `points_earned` / `coins_earned` |
|
| GET | `/customer/orders` | Riwayat order customer (`page`, `limit`), dengan `points_earned` / `coins_earned` |
|
||||||
| GET | `/customer/orders/:id` | Detail order: item, pembayaran, EnakPoint yang dipakai; order customer lain → `404` |
|
| GET | `/customer/orders/:id` | Detail order: item, pembayaran, EnakPoint/EnakCoin yang didapat; order customer lain → `404` |
|
||||||
|
|
||||||
Registrasi (`POST /customer-auth/register/start`) menerima `organization_id` opsional: bila tidak dikirim dan hanya ada satu organisasi, customer masuk ke organisasi itu. Contoh request dan response lengkap untuk outlet dan order ada di [`mobile-customer-enakpoint.md`](./mobile-customer-enakpoint.md) §4.4–§4.5.
|
Registrasi (`POST /customer-auth/register/start`) menerima `organization_id` opsional: bila tidak dikirim dan hanya ada satu organisasi, customer masuk ke organisasi itu. Contoh request dan response lengkap untuk outlet dan order ada di [`mobile-customer-enakpoint.md`](./mobile-customer-enakpoint.md) §4.4–§4.5.
|
||||||
|
|
||||||
@@ -74,7 +76,7 @@ Registrasi (`POST /customer-auth/register/start`) menerima `organization_id` ops
|
|||||||
| `page` | int | Default 1 |
|
| `page` | int | Default 1 |
|
||||||
| `limit` | int | 1–100, default 20 |
|
| `limit` | int | 1–100, default 20 |
|
||||||
| `currency` | `POINT` \| `COIN` | Opsional |
|
| `currency` | `POINT` \| `COIN` | Opsional |
|
||||||
| `type` | string | Satu tipe atau beberapa dipisah koma, mis. `EARN,PAYMENT` |
|
| `type` | string | Satu tipe atau beberapa dipisah koma, mis. `EARN,TRANSFER_IN` |
|
||||||
| `from`, `to` | `YYYY-MM-DD` | Tanggal WIB, inklusif |
|
| `from`, `to` | `YYYY-MM-DD` | Tanggal WIB, inklusif |
|
||||||
|
|
||||||
```json
|
```json
|
||||||
@@ -125,7 +127,7 @@ Panggil setelah login dan setiap kali FCM memberi token baru. `device_id` dan `f
|
|||||||
|
|
||||||
## Customer app: PIN
|
## Customer app: PIN
|
||||||
|
|
||||||
PIN 6 digit wajib untuk bayar, kode bayar, exchange, dan transfer; minta customer membuatnya saat pertama kali melakukan aksi itu.
|
PIN 6 digit wajib untuk exchange dan transfer; minta customer membuatnya saat pertama kali melakukan aksi itu.
|
||||||
|
|
||||||
| Method | Path | Body | Response |
|
| Method | Path | Body | Response |
|
||||||
| --- | --- | --- | --- |
|
| --- | --- | --- | --- |
|
||||||
@@ -136,37 +138,21 @@ PIN 6 digit wajib untuk bayar, kode bayar, exchange, dan transfer; minta custome
|
|||||||
| POST | `/customer/pin/reset` | `{ "otp_token", "otp_code", "pin", "confirm_pin" }` | Status PIN |
|
| POST | `/customer/pin/reset` | `{ "otp_token", "otp_code", "pin", "confirm_pin" }` | Status PIN |
|
||||||
|
|
||||||
1. **Buat PIN:** minta OTP dengan `purpose: "pin_setup"` (dikirim lewat WhatsApp), lalu `POST /customer/pin` dengan `otp_token` dari response OTP dan kode yang diterima customer.
|
1. **Buat PIN:** minta OTP dengan `purpose: "pin_setup"` (dikirim lewat WhatsApp), lalu `POST /customer/pin` dengan `otp_token` dari response OTP dan kode yang diterima customer.
|
||||||
2. **Lupa PIN:** minta OTP dengan `purpose: "pin_reset"`, lalu `POST /customer/pin/reset`. Reset membuka kunci PIN, tapi transfer keluar ditahan 24 jam; pembayaran dan exchange tetap bisa.
|
2. **Lupa PIN:** minta OTP dengan `purpose: "pin_reset"`, lalu `POST /customer/pin/reset`. Reset membuka kunci PIN, tapi transfer keluar ditahan 24 jam; exchange tetap bisa.
|
||||||
3. **Ganti PIN:** `PUT /customer/pin` dengan PIN lama.
|
3. **Ganti PIN:** `PUT /customer/pin` dengan PIN lama.
|
||||||
|
|
||||||
PIN baru ditolak `304` bila bukan 6 digit, konfirmasinya beda, semua digit sama (`111111`), berurutan (`123456`, `654321`), atau sama dengan tanggal lahir (`DDMMYY` / `YYMMDD`). OTP yang diminta terlalu cepat dijawab `429`. Penanganan `PIN_INVALID`, `PIN_LOCKED`, dan `TRANSFER_BLOCKED` ada di Konvensi umum.
|
PIN baru ditolak `304` bila bukan 6 digit, konfirmasinya beda, semua digit sama (`111111`), berurutan (`123456`, `654321`), atau sama dengan tanggal lahir (`DDMMYY` / `YYMMDD`). OTP yang diminta terlalu cepat dijawab `429`. Penanganan `PIN_INVALID`, `PIN_LOCKED`, dan `TRANSFER_BLOCKED` ada di Konvensi umum.
|
||||||
|
|
||||||
## Customer app: bayar, exchange, transfer, game
|
## Customer app: exchange, transfer, game
|
||||||
|
|
||||||
| Method | Path | PIN | Idempotency-Key |
|
| Method | Path | PIN | Idempotency-Key |
|
||||||
| --- | --- | --- | --- |
|
| --- | --- | --- | --- |
|
||||||
| POST | `/customer/wallet/payment-code` | Ya | – |
|
|
||||||
| POST | `/customer/orders/:id/pay-with-points` | Ya | – |
|
|
||||||
| GET | `/customer/wallet/exchange/preview?coins=` | – | – |
|
| GET | `/customer/wallet/exchange/preview?coins=` | – | – |
|
||||||
| POST | `/customer/wallet/exchange` | Ya | Wajib |
|
| POST | `/customer/wallet/exchange` | Ya | Wajib |
|
||||||
| GET | `/customer/wallet/transfer/recipient?phone=` | – | – |
|
| GET | `/customer/wallet/transfer/recipient?phone=` | – | – |
|
||||||
| POST | `/customer/wallet/transfer` | Ya | Wajib |
|
| POST | `/customer/wallet/transfer` | Ya | Wajib |
|
||||||
| POST | `/customer/spin` | – | – |
|
| POST | `/customer/spin` | – | – |
|
||||||
|
|
||||||
### POST /customer/wallet/payment-code
|
|
||||||
|
|
||||||
Body `{ "pin": "482913" }`. Response:
|
|
||||||
|
|
||||||
```json
|
|
||||||
{ "code": "482913", "qr_payload": "enakpoint:482913", "expires_at": "2026-09-30T05:02:00Z" }
|
|
||||||
```
|
|
||||||
|
|
||||||
Tampilkan `code` sebagai angka dan `qr_payload` sebagai QR untuk kasir. Berlaku 2 menit, sekali pakai, hanya untuk customer ini; kode baru membatalkan kode lama.
|
|
||||||
|
|
||||||
### POST /customer/orders/:id/pay-with-points
|
|
||||||
|
|
||||||
Body `{ "points": 12500, "pin": "482913" }`. Hanya untuk order milik customer yang login (order lain `404`). Response sama dengan pembayaran POS (bagian POS). Batas dan aturan penolakan juga sama.
|
|
||||||
|
|
||||||
### GET /customer/wallet/exchange/preview?coins=30
|
### GET /customer/wallet/exchange/preview?coins=30
|
||||||
|
|
||||||
```json
|
```json
|
||||||
@@ -238,69 +224,9 @@ Body `{ "spin_id": "<id game>" }`. Memotong EnakCoin sebesar `metadata.coin_cost
|
|||||||
|
|
||||||
EnakCoin kurang, game nonaktif, atau hadiah baru saja habis → `304`, tidak ada EnakCoin yang terpotong.
|
EnakCoin kurang, game nonaktif, atau hadiah baru saja habis → `304`, tidak ada EnakCoin yang terpotong.
|
||||||
|
|
||||||
## POS: pembayaran EnakPoint
|
## POS: earning, void, dan refund
|
||||||
|
|
||||||
Kasir memakai endpoint pembayaran yang sudah ada dengan payment method bertipe `point`, disetujui customer lewat kode bayar dari aplikasinya; PIN tidak pernah diketik di perangkat kasir.
|
EnakPoint bukan payment method: tidak ada lagi tipe `point`, dan `POST /payments` memakai `amount` seperti pembayaran lain. Response order membawa `points_earned` dan `coins_earned` untuk struk. Saat order di-void atau direfund, EnakPoint dan EnakCoin yang didapat dari order itu ikut ditarik (`EARN_REVERSAL`); bila saldo sudah terpakai, ditarik sebanyak yang ada dan refund tetap jalan.
|
||||||
|
|
||||||
| Method | Path | Keterangan |
|
|
||||||
| --- | --- | --- |
|
|
||||||
| GET | `/orders/:id/point-payment/preview` | Batas pembayaran EnakPoint untuk order ini |
|
|
||||||
| POST | `/payments` | Bayar dengan method EnakPoint (`points` + `payment_code`) |
|
|
||||||
| POST | `/payments/:id/refund` | Refund pembayaran EnakPoint, kembali sebagai EnakPoint |
|
|
||||||
|
|
||||||
1. Customer membuat kode di aplikasi (`POST /customer/wallet/payment-code`) dan menunjukkan angka atau QR-nya.
|
|
||||||
2. POS memanggil preview untuk tombol "pakai maksimal".
|
|
||||||
3. POS memanggil `POST /payments` dengan kode tersebut. Sisa tagihan dibayar dengan method lain seperti biasa.
|
|
||||||
|
|
||||||
### GET /orders/:id/point-payment/preview
|
|
||||||
|
|
||||||
```json
|
|
||||||
{
|
|
||||||
"order_id": "…",
|
|
||||||
"customer_id": "…",
|
|
||||||
"eligible": true,
|
|
||||||
"point_balance": 12500,
|
|
||||||
"point_value": 1,
|
|
||||||
"remaining_amount": 87500,
|
|
||||||
"min_payment_points": 1,
|
|
||||||
"max_payment_percent": 100,
|
|
||||||
"max_points": 12500,
|
|
||||||
"max_amount": 12500
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
Bila `eligible: false`, `reason` menjelaskan kenapa (order walk-in, outlet tidak menerima EnakPoint, saldo di bawah minimal, dst.). Batas yang dipakai:
|
|
||||||
|
|
||||||
```
|
|
||||||
batas_rupiah = min(sisa_tagihan, total × max_payment_percent / 100 − sudah_dibayar_EnakPoint)
|
|
||||||
maks_point = min(saldo, floor(batas_rupiah / point_value))
|
|
||||||
```
|
|
||||||
|
|
||||||
### POST /payments
|
|
||||||
|
|
||||||
Header `X-Idempotency-Key` wajib.
|
|
||||||
|
|
||||||
```json
|
|
||||||
{
|
|
||||||
"order_id": "…",
|
|
||||||
"payment_method_id": "<id method EnakPoint>",
|
|
||||||
"points": 12500,
|
|
||||||
"payment_code": "482913"
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
- `amount` tidak perlu dikirim; backend menghitung `points × point_value` dan tidak pernah melebihi sisa tagihan (tidak ada kembalian).
|
|
||||||
- `payment_code` boleh angka yang diketik atau hasil scan QR apa adanya (`enakpoint:482913`).
|
|
||||||
- Response pembayaran membawa `points_used` dan `point_value` untuk struk; response order membawa `points_earned` dan `coins_earned`.
|
|
||||||
- Ditolak `304` bila: order tanpa customer atau walk-in, customer nonaktif, outlet tidak menerima EnakPoint, `points` di luar batas, kode salah/kedaluwarsa/sudah dipakai/milik customer lain, atau method EnakPoint dipakai sebagai split. Kode terpakai begitu diterima; bila pembayaran lalu ditolak, minta kode baru.
|
|
||||||
- Method EnakPoint dibuat otomatis per organisasi, tidak bisa dihapus atau diubah tipenya, dan tidak muncul di daftar method `?outlet_id=` bila outlet tidak menerima EnakPoint.
|
|
||||||
|
|
||||||
### Void dan refund
|
|
||||||
|
|
||||||
- **Void order:** semua EnakPoint yang dipakai kembali sebagai EnakPoint.
|
|
||||||
- **`POST /payments/:id/refund` pada pembayaran EnakPoint:** kembali `floor(rupiah_direfund / point_value_saat_bayar)`; sisa di bawah 1 EnakPoint hangus.
|
|
||||||
- **Refund order ke tunai/method lain** hanya sebesar bagian non-EnakPoint; mencoba merefund bagian EnakPoint secara tunai ditolak `304`.
|
|
||||||
- EnakPoint yang kembali memakai tanggal kedaluwarsa asal, minimal 7 hari sejak refund. Earning order ikut ditarik; bila saldo sudah terpakai, ditarik sebanyak yang ada dan refund tetap jalan.
|
|
||||||
|
|
||||||
## Dashboard
|
## Dashboard
|
||||||
|
|
||||||
@@ -308,7 +234,7 @@ Semua endpoint dashboard butuh role Admin atau Manager, dan semuanya dibatasi ke
|
|||||||
|
|
||||||
| Method | Path | Keterangan |
|
| Method | Path | Keterangan |
|
||||||
| --- | --- | --- |
|
| --- | --- | --- |
|
||||||
| GET, PUT | `/outlets/:outlet_id/loyalty-settings` | Earning dan penerimaan EnakPoint per outlet |
|
| GET, PUT | `/outlets/:outlet_id/loyalty-settings` | Earning EnakPoint dan EnakCoin per outlet |
|
||||||
| GET, PUT | `/marketing/loyalty-settings` | Nilai EnakPoint, kurs, transfer, kedaluwarsa (`?dry_run=true` untuk preview) |
|
| GET, PUT | `/marketing/loyalty-settings` | Nilai EnakPoint, kurs, transfer, kedaluwarsa (`?dry_run=true` untuk preview) |
|
||||||
| GET | `/marketing/loyalty-settings/history` | Riwayat perubahan setting (`page`, `limit`, `outlet_id`) |
|
| GET | `/marketing/loyalty-settings/history` | Riwayat perubahan setting (`page`, `limit`, `outlet_id`) |
|
||||||
| GET | `/marketing/customers/:id/wallet` | Saldo, lot aktif, riwayat dengan nama asli |
|
| GET | `/marketing/customers/:id/wallet` | Saldo, lot aktif, riwayat dengan nama asli |
|
||||||
@@ -323,13 +249,12 @@ Pada kedua `PUT` setting, field yang tidak dikirim tetap memakai nilai sekarang;
|
|||||||
|
|
||||||
```json
|
```json
|
||||||
{
|
{
|
||||||
"point": { "enabled": true, "earn_per_amount": 100, "earn_value": 1, "min_order_amount": 0, "max_per_order": null },
|
"point": { "enabled": true, "earn_mode": "PER_AMOUNT", "earn_per_amount": 100, "earn_value": 1, "earn_percent": 1, "min_order_amount": 0, "max_per_order": null },
|
||||||
"coin": { "enabled": true, "earn_per_amount": 25000, "earn_value": 1, "min_order_amount": 0, "max_per_order": null },
|
"coin": { "enabled": true, "earn_mode": "PER_AMOUNT", "earn_per_amount": 25000, "earn_value": 1, "earn_percent": 1, "min_order_amount": 0, "max_per_order": null }
|
||||||
"point_payment": { "accept_payment": true, "min_payment_points": 1, "max_payment_percent": 100 }
|
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
Response menambahkan `outlet_id`, `point_value`, `point_cashback_percent` (default di atas = 1%), dan `changes` pada PUT. Validasi: `earn_per_amount > 0`, `earn_value ≥ 0`, `max_payment_percent` 0–100.
|
Response menambahkan `outlet_id`, `point_value`, `point_cashback_percent` (default di atas = 1%), dan `changes` pada PUT. `earn_mode` adalah `PER_AMOUNT` (setiap `earn_per_amount` rupiah mendapat `earn_value`) atau `PERCENTAGE` (`earn_percent` persen dari basis). Validasi: `earn_per_amount > 0`, `earn_value ≥ 0`, `earn_percent` 0–100 dengan maks. 2 angka desimal. Objek `point_payment` sudah dihapus; `PUT` yang masih mengirimnya ditolak `310` (field tidak dikenal).
|
||||||
|
|
||||||
### /marketing/loyalty-settings
|
### /marketing/loyalty-settings
|
||||||
|
|
||||||
@@ -380,7 +305,7 @@ Response menambahkan:
|
|||||||
|
|
||||||
```json
|
```json
|
||||||
{
|
{
|
||||||
"transaction": { "id": "…", "customer": { "id": "…", "name": "Budi Santoso" }, "type": "PAYMENT", "amount": -30, "…": "…" },
|
"transaction": { "id": "…", "customer": { "id": "…", "name": "Budi Santoso" }, "type": "TRANSFER_OUT", "amount": -30, "…": "…" },
|
||||||
"lots": [
|
"lots": [
|
||||||
{
|
{
|
||||||
"amount": 30,
|
"amount": 30,
|
||||||
@@ -393,7 +318,7 @@ Response menambahkan:
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
Pengurangan menampilkan lot yang dipakai; penambahan menampilkan lot yang dibuat. Tiap `chain` mundur lewat transfer, exchange, atau refund sampai lot pertama dari `EARN`, `ADJUSTMENT`, atau `MIGRATION`.
|
Pengurangan menampilkan lot yang dipakai; penambahan menampilkan lot yang dibuat. Tiap `chain` mundur lewat transfer atau exchange sampai lot pertama dari `EARN`, `ADJUSTMENT`, atau `MIGRATION`.
|
||||||
|
|
||||||
### PIN customer
|
### PIN customer
|
||||||
|
|
||||||
@@ -407,8 +332,6 @@ Pengurangan menampilkan lot yang dipakai; penambahan menampilkan lot yang dibuat
|
|||||||
| --- | --- | --- | --- |
|
| --- | --- | --- | --- |
|
||||||
| `EARN` | + | Didapat dari order lunas | `ORDER` |
|
| `EARN` | + | Didapat dari order lunas | `ORDER` |
|
||||||
| `EARN_REVERSAL` | − | Ditarik karena order di-void/refund | `ORDER` |
|
| `EARN_REVERSAL` | − | Ditarik karena order di-void/refund | `ORDER` |
|
||||||
| `PAYMENT` | − | Membayar order (EnakPoint saja) | `PAYMENT` |
|
|
||||||
| `PAYMENT_REFUND` | + | Kembali karena pembayaran di-void/refund | `PAYMENT` |
|
|
||||||
| `EXCHANGE_OUT` | − | EnakCoin ditukar | `WALLET_TX` (baris `EXCHANGE_IN`) |
|
| `EXCHANGE_OUT` | − | EnakCoin ditukar | `WALLET_TX` (baris `EXCHANGE_IN`) |
|
||||||
| `EXCHANGE_IN` | + | EnakPoint hasil tukar | `WALLET_TX` (baris `EXCHANGE_OUT`) |
|
| `EXCHANGE_IN` | + | EnakPoint hasil tukar | `WALLET_TX` (baris `EXCHANGE_OUT`) |
|
||||||
| `TRANSFER_OUT` | − | Dikirim ke customer lain | `WALLET_TX` (baris `TRANSFER_IN`) |
|
| `TRANSFER_OUT` | − | Dikirim ke customer lain | `WALLET_TX` (baris `TRANSFER_IN`) |
|
||||||
@@ -438,4 +361,20 @@ Masih jalan dan membaca wallet, tapi akan dihapus setelah semua versi aplikasi p
|
|||||||
| `GET /customer/points` | `GET /customer/wallet` → `point_balance` |
|
| `GET /customer/points` | `GET /customer/wallet` → `point_balance` |
|
||||||
| `total_points`, `points_history`, `last_updated` di `/customer/wallet` | `point_balance`, `recent_transactions` |
|
| `total_points`, `points_history`, `last_updated` di `/customer/wallet` | `point_balance`, `recent_transactions` |
|
||||||
|
|
||||||
|
### Endpoint dan field yang dihapus
|
||||||
|
|
||||||
|
Bayar dengan EnakPoint dihapus pada 7 Okt 2026 karena EnakPoint sekarang hanya untuk voucher ([`enakgame-prd.md`](./enakgame-prd.md) §3.2). Tidak ada penggantinya; jangan dipanggil lagi.
|
||||||
|
|
||||||
|
| Dihapus | Catatan |
|
||||||
|
| --- | --- |
|
||||||
|
| `POST /customer/wallet/payment-code` | Kode bayar untuk kasir |
|
||||||
|
| `POST /customer/orders/:id/pay-with-points` | Bayar order dari app / self-order |
|
||||||
|
| `GET /orders/:id/point-payment/preview` | Batas pembayaran EnakPoint di POS |
|
||||||
|
| Payment method tipe `point`; field `points` dan `payment_code` di `POST /payments` | `amount` kembali wajib seperti pembayaran lain |
|
||||||
|
| `points_used`, `point_value` di response pembayaran dan di `payments` pada `GET /customer/orders/:id` | – |
|
||||||
|
| `accepts_point_payment` di `GET /customer/outlets` | – |
|
||||||
|
| `point_payment` (`accept_payment`, `min_payment_points`, `max_payment_percent`) di `/outlets/:outlet_id/loyalty-settings` | `PUT` yang masih mengirimnya ditolak `310` |
|
||||||
|
| `summary.point_amount`, `summary.points_used`, `summary.total_with_points`, serta `points_used` dan `counts_as_cash_in` per baris di analytics payment method | `summary.total_amount` kembali total semua method; persentase dihitung dari total itu |
|
||||||
|
| Tipe mutasi `PAYMENT` dan `PAYMENT_REFUND` | Tidak ditulis lagi |
|
||||||
|
|
||||||
Panduan alur lengkap per tim ada di [`integration-enakpoint.md`](./integration-enakpoint.md).
|
Panduan alur lengkap per tim ada di [`integration-enakpoint.md`](./integration-enakpoint.md).
|
||||||
|
|||||||
@@ -4,6 +4,8 @@
|
|||||||
|
|
||||||
Backoffice perlu tujuh layar untuk mengelola program loyalitas: setting per outlet, setting per organisasi (termasuk kedaluwarsa), wallet customer, telusuri mutasi, PIN customer, riwayat setting, dan biaya main game.
|
Backoffice perlu tujuh layar untuk mengelola program loyalitas: setting per outlet, setting per organisasi (termasuk kedaluwarsa), wallet customer, telusuri mutasi, PIN customer, riwayat setting, dan biaya main game.
|
||||||
|
|
||||||
|
> **Perubahan 7 Okt 2026:** bayar dengan EnakPoint sudah dihapus karena EnakPoint sekarang hanya bisa ditukar ke voucher, tidak bisa dipakai sebagai alat bayar dan tidak bisa dicairkan ([`enakgame-prd.md`](./enakgame-prd.md) §3.2). Akibatnya setting outlet tidak lagi punya `point_payment`, method "EnakPoint" (tipe `point`) tidak ada lagi di Payment Method, dan laporan per payment method tidak lagi membawa `point_amount`, `points_used`, `total_with_points`, atau `counts_as_cash_in`; `summary.total_amount` kembali total semua method.
|
||||||
|
|
||||||
## Layar yang perlu dibuat
|
## Layar yang perlu dibuat
|
||||||
|
|
||||||
Semua endpoint di bawah base URL `/api/v1`, butuh login user dengan role Admin atau Manager, dan otomatis dibatasi ke organisasi user tersebut. Data customer atau outlet organisasi lain dijawab `404`.
|
Semua endpoint di bawah base URL `/api/v1`, butuh login user dengan role Admin atau Manager, dan otomatis dibatasi ke organisasi user tersebut. Data customer atau outlet organisasi lain dijawab `404`.
|
||||||
@@ -20,40 +22,40 @@ Semua endpoint di bawah base URL `/api/v1`, butuh login user dengan role Admin a
|
|||||||
|
|
||||||
Penempatan menu di atas adalah usulan; sesuaikan dengan struktur backoffice yang ada.
|
Penempatan menu di atas adalah usulan; sesuaikan dengan struktur backoffice yang ada.
|
||||||
|
|
||||||
**Istilah di layar.** EnakPoint (`POINT`) adalah saldo yang bisa membayar order; EnakCoin (`COIN`) untuk main game dan bisa ditukar ke EnakPoint. Nilai rupiah EnakPoint selalu ditulis "setara potongan Rp …", tidak pernah "saldo Rp …", karena saldo tidak bisa dicairkan.
|
**Istilah di layar.** EnakPoint (`POINT`) adalah saldo yang hanya bisa ditukar ke voucher, bukan alat bayar; EnakCoin (`COIN`) untuk main game dan bisa ditukar ke EnakPoint. Nilai rupiah EnakPoint selalu ditulis "setara potongan Rp …", tidak pernah "saldo Rp …", karena saldo tidak bisa dicairkan.
|
||||||
|
|
||||||
**Format response.** Sukses `{ "success": true, "data": … }`; gagal `{ "success": false, "errors": [{ "code", "entity", "cause" }] }`. Tampilkan `cause` sebagai pesan (lihat bagian Pesan error).
|
**Format response.** Sukses `{ "success": true, "data": … }`; gagal `{ "success": false, "errors": [{ "code", "entity", "cause" }] }`. Tampilkan `cause` sebagai pesan (lihat bagian Pesan error).
|
||||||
|
|
||||||
## Setting loyalitas outlet
|
## Setting loyalitas outlet
|
||||||
|
|
||||||
Tiap outlet mengatur sendiri berapa EnakPoint dan EnakCoin yang didapat dari order, dan apakah outlet menerima pembayaran EnakPoint. Semua nilai default mati sampai owner menyalakannya.
|
Tiap outlet mengatur sendiri berapa EnakPoint dan EnakCoin yang didapat dari order. Semua nilai default mati sampai owner menyalakannya.
|
||||||
|
|
||||||
`GET /outlets/:outlet_id/loyalty-settings` → isi form. `PUT` ke path yang sama dengan objek yang sama untuk menyimpan; field yang tidak dikirim tetap, field tak dikenal ditolak.
|
`GET /outlets/:outlet_id/loyalty-settings` → isi form. `PUT` ke path yang sama dengan objek yang sama untuk menyimpan; field yang tidak dikirim tetap, field tak dikenal ditolak (termasuk `point_payment` yang sudah dihapus).
|
||||||
|
|
||||||
```json
|
```json
|
||||||
{
|
{
|
||||||
"point": { "enabled": true, "earn_per_amount": 100, "earn_value": 1, "min_order_amount": 0, "max_per_order": null },
|
"point": { "enabled": true, "earn_mode": "PER_AMOUNT", "earn_per_amount": 100, "earn_value": 1, "earn_percent": 1, "min_order_amount": 0, "max_per_order": null },
|
||||||
"coin": { "enabled": true, "earn_per_amount": 25000, "earn_value": 1, "min_order_amount": 0, "max_per_order": null },
|
"coin": { "enabled": true, "earn_mode": "PER_AMOUNT", "earn_per_amount": 25000, "earn_value": 1, "earn_percent": 1, "min_order_amount": 0, "max_per_order": null }
|
||||||
"point_payment": { "accept_payment": true, "min_payment_points": 1, "max_payment_percent": 100 }
|
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
| Field | Label usulan | Tipe | Default | Validasi |
|
| Field | Label usulan | Tipe | Default | Validasi |
|
||||||
| --- | --- | --- | --- | --- |
|
| --- | --- | --- | --- | --- |
|
||||||
| `point.enabled` / `coin.enabled` | Beri EnakPoint / EnakCoin | toggle | mati | – |
|
| `point.enabled` / `coin.enabled` | Beri EnakPoint / EnakCoin | toggle | mati | – |
|
||||||
| `earn_per_amount` | Setiap belanja Rp … | Rp | 100 (point), 25.000 (coin) | > 0 |
|
| `earn_mode` | Cara hitung: per nominal / persentase | pilihan `PER_AMOUNT` / `PERCENTAGE` | `PER_AMOUNT` | salah satu dari keduanya |
|
||||||
| `earn_value` | … mendapat | angka | 1 | ≥ 0 |
|
| `earn_per_amount` | Setiap belanja Rp … (mode `PER_AMOUNT`) | Rp | 100 (point), 25.000 (coin) | > 0 |
|
||||||
|
| `earn_value` | … mendapat (mode `PER_AMOUNT`) | angka | 1 | ≥ 0 |
|
||||||
|
| `earn_percent` | … % dari belanja (mode `PERCENTAGE`) | %, boleh desimal | 1 | 0–100, maks. 2 angka desimal |
|
||||||
| `min_order_amount` | Minimal belanja | Rp | 0 | ≥ 0 |
|
| `min_order_amount` | Minimal belanja | Rp | 0 | ≥ 0 |
|
||||||
| `max_per_order` | Maksimal per order | angka, boleh kosong | kosong = tanpa batas | ≥ 0 |
|
| `max_per_order` | Maksimal per order | angka, boleh kosong | kosong = tanpa batas | ≥ 0 |
|
||||||
| `point_payment.accept_payment` | Terima pembayaran EnakPoint | toggle | mati | – |
|
|
||||||
| `min_payment_points` | Minimal EnakPoint per pembayaran | angka | 1 | ≥ 1 |
|
|
||||||
| `max_payment_percent` | Maksimal porsi order dibayar EnakPoint | % | 100 | 0–100 |
|
|
||||||
|
|
||||||
**Cashback efektif.** Response membawa `point_cashback_percent` dan `point_value`. Tampilkan persentase di samping field earning EnakPoint, mis. "setara cashback 1%", dan hitung ulang di sisi klien saat owner mengetik: `earn_value × point_value ÷ earn_per_amount × 100`. Tujuannya agar owner tidak salah membaca skala (1 per Rp 100 bukan 1 per Rp 1).
|
**Cashback efektif.** Response membawa `point_cashback_percent` dan `point_value`. Tampilkan persentase di samping field earning EnakPoint, mis. "setara cashback 1%", dan hitung ulang di sisi klien saat owner mengetik: `earn_value × point_value ÷ earn_per_amount × 100`, atau pada mode `PERCENTAGE`: `earn_percent × point_value`. Tujuannya agar owner tidak salah membaca skala (1 per Rp 100 bukan 1 per Rp 1).
|
||||||
|
|
||||||
**Contoh di bawah form.** "Belanja Rp 87.500 mendapat 875 EnakPoint dan 3 EnakCoin." Earning dihitung dari subtotal setelah diskon, sebelum pajak, dan bagian yang dibayar EnakPoint tidak ikut dihitung.
|
**Mode earning.** Tampilkan hanya field mode yang dipilih (`earn_per_amount` + `earn_value`, atau `earn_percent`). Field mode lain tetap tersimpan di server, jadi tidak perlu dikosongkan saat owner berpindah mode. Pada mode `PERCENTAGE` jumlah yang didapat adalah `floor(basis × earn_percent ÷ 100)`, mis. 2,5% dari Rp 87.500 = 2.187 EnakPoint.
|
||||||
|
|
||||||
Setelah `PUT`, response membawa `changes` (key yang berubah); tampilkan toast singkat, mis. "2 pengaturan disimpan". Mematikan `accept_payment` langsung menyembunyikan method EnakPoint di kasir outlet itu.
|
**Contoh di bawah form.** "Belanja Rp 87.500 mendapat 875 EnakPoint dan 3 EnakCoin." Earning dihitung dari subtotal setelah diskon, sebelum pajak.
|
||||||
|
|
||||||
|
Setelah `PUT`, response membawa `changes` (key yang berubah); tampilkan toast singkat, mis. "2 pengaturan disimpan".
|
||||||
|
|
||||||
## Setting loyalitas organisasi
|
## Setting loyalitas organisasi
|
||||||
|
|
||||||
@@ -98,7 +100,7 @@ Nilai rupiah EnakPoint, kurs exchange, batas transfer, dan kedaluwarsa berlaku s
|
|||||||
| `coins_as_points_before` → `coins_as_points_after` | Bila semua ditukar: … EnakPoint → … EnakPoint |
|
| `coins_as_points_before` → `coins_as_points_after` | Bila semua ditukar: … EnakPoint → … EnakPoint |
|
||||||
| `coin_rupiah_before` → `coin_rupiah_after` | Setara potongan Rp … → Rp … |
|
| `coin_rupiah_before` → `coin_rupiah_after` | Setara potongan Rp … → Rp … |
|
||||||
|
|
||||||
Contoh kalimat: "Menaikkan nilai EnakPoint dari Rp 1 ke Rp 2 membuat 1.250.000 EnakPoint yang beredar setara potongan Rp 2.500.000 (sebelumnya Rp 1.250.000)." Perubahan hanya berlaku ke depan: pembayaran, refund, dan exchange yang sudah terjadi memakai nilai saat itu.
|
Contoh kalimat: "Menaikkan nilai EnakPoint dari Rp 1 ke Rp 2 membuat 1.250.000 EnakPoint yang beredar setara potongan Rp 2.500.000 (sebelumnya Rp 1.250.000)." Perubahan hanya berlaku ke depan: exchange yang sudah terjadi memakai kurs saat itu.
|
||||||
|
|
||||||
## Pengaturan kedaluwarsa
|
## Pengaturan kedaluwarsa
|
||||||
|
|
||||||
@@ -155,7 +157,7 @@ Tab Wallet di detail customer dipakai untuk menangani komplain: melihat saldo da
|
|||||||
|
|
||||||
### Saldo, lot, dan riwayat
|
### Saldo, lot, dan riwayat
|
||||||
|
|
||||||
`GET /marketing/customers/:id/wallet?page=1&limit=20¤cy=POINT&type=PAYMENT,EARN&from=2026-09-01&to=2026-09-30` (semua query opsional, sama seperti riwayat di aplikasi customer)
|
`GET /marketing/customers/:id/wallet?page=1&limit=20¤cy=POINT&type=TRANSFER_OUT,EARN&from=2026-09-01&to=2026-09-30` (semua query opsional, sama seperti riwayat di aplikasi customer)
|
||||||
|
|
||||||
```json
|
```json
|
||||||
{
|
{
|
||||||
@@ -185,7 +187,7 @@ Tab Wallet di detail customer dipakai untuk menangani komplain: melihat saldo da
|
|||||||
|
|
||||||
- **Saldo:** tampilkan `spendable_*` sebagai saldo utama. `point_balance` / `coin_balance` bisa sedikit lebih besar selama ada lot yang sudah lewat tanggal tapi belum diproses job kedaluwarsa (paling lama sekitar 15 menit).
|
- **Saldo:** tampilkan `spendable_*` sebagai saldo utama. `point_balance` / `coin_balance` bisa sedikit lebih besar selama ada lot yang sudah lewat tanggal tapi belum diproses job kedaluwarsa (paling lama sekitar 15 menit).
|
||||||
- **Lot:** tabel paket saldo yang masih berisi, urut dari yang paling cepat kedaluwarsa. Beri tanda untuk `expired: true`.
|
- **Lot:** tabel paket saldo yang masih berisi, urut dari yang paling cepat kedaluwarsa. Beri tanda untuk `expired: true`.
|
||||||
- **Riwayat:** sama dengan riwayat customer, ditambah nama asli yang disamarkan untuk customer: `counterparty` (lawan transfer), `created_by` (admin pelaku adjustment atau kasir penerima pembayaran), `outlet`, `reason`, dan `metadata` (kurs, nilai EnakPoint yang dibekukan, shortfall).
|
- **Riwayat:** sama dengan riwayat customer, ditambah nama asli yang disamarkan untuk customer: `counterparty` (lawan transfer), `created_by` (admin pelaku adjustment), `outlet`, `reason`, dan `metadata` (kurs, rumus earning, shortfall).
|
||||||
|
|
||||||
### Adjustment manual
|
### Adjustment manual
|
||||||
|
|
||||||
@@ -210,7 +212,7 @@ Dari baris riwayat mana pun, tombol Telusuri memanggil `GET /marketing/wallet-tr
|
|||||||
|
|
||||||
```json
|
```json
|
||||||
{
|
{
|
||||||
"transaction": { "id": "…", "customer": { "id": "…", "name": "Budi Santoso" }, "currency": "POINT", "type": "PAYMENT", "amount": -30, "description": "Bayar #ORD-0456 di Outlet Kemang (Rp 30)", "reference_type": "PAYMENT", "reference_id": "…", "created_at": "…" },
|
"transaction": { "id": "…", "customer": { "id": "…", "name": "Budi Santoso" }, "currency": "POINT", "type": "TRANSFER_OUT", "amount": -30, "description": "Transfer ke Ri*** (08**-****-9012)", "reference_type": "WALLET_TX", "reference_id": "…", "created_at": "…" },
|
||||||
"lots": [
|
"lots": [
|
||||||
{
|
{
|
||||||
"amount": 30,
|
"amount": 30,
|
||||||
@@ -225,7 +227,7 @@ Dari baris riwayat mana pun, tombol Telusuri memanggil `GET /marketing/wallet-tr
|
|||||||
|
|
||||||
Tampilkan tiap `lots[]` sebagai rantai dari atas ke bawah: jumlah yang lewat lot itu, lalu setiap langkah `chain` dengan pemilik, tipe, dan deskripsinya. Langkah terakhir selalu `EARN`, `ADJUSTMENT`, atau `MIGRATION`; bila `reference_type` = `ORDER`, jadikan tautan ke detail order. Mutasi keluar menampilkan lot yang dipakai; mutasi masuk menampilkan lot yang dibuatnya.
|
Tampilkan tiap `lots[]` sebagai rantai dari atas ke bawah: jumlah yang lewat lot itu, lalu setiap langkah `chain` dengan pemilik, tipe, dan deskripsinya. Langkah terakhir selalu `EARN`, `ADJUSTMENT`, atau `MIGRATION`; bila `reference_type` = `ORDER`, jadikan tautan ke detail order. Mutasi keluar menampilkan lot yang dipakai; mutasi masuk menampilkan lot yang dibuatnya.
|
||||||
|
|
||||||
## PIN, riwayat setting, game, dan method EnakPoint
|
## PIN, riwayat setting, dan game
|
||||||
|
|
||||||
### PIN & keamanan customer
|
### PIN & keamanan customer
|
||||||
|
|
||||||
@@ -266,22 +268,12 @@ Admin tidak bisa membuat, mengganti, atau melihat PIN customer; satu-satunya aks
|
|||||||
|
|
||||||
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. 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.
|
||||||
|
|
||||||
### Method pembayaran EnakPoint
|
|
||||||
|
|
||||||
Method "EnakPoint" (tipe `point`) dibuat otomatis untuk setiap organisasi. Di layar Payment Method (`/payment-methods`):
|
|
||||||
|
|
||||||
- Tampilkan sebagai method sistem: tombol hapus dan pilihan ubah tipe disembunyikan; backend menolaknya (`304`). Nama boleh diganti.
|
|
||||||
- Tipe `point` tidak ditawarkan saat membuat method baru.
|
|
||||||
- Kasir hanya melihatnya di outlet yang menyalakan "Terima pembayaran EnakPoint".
|
|
||||||
|
|
||||||
Di laporan per payment method, EnakPoint tampil terpisah dan **tidak** dihitung sebagai kas masuk.
|
|
||||||
|
|
||||||
## Pesan error dan checklist
|
## Pesan error dan checklist
|
||||||
|
|
||||||
| `code` | HTTP | Kapan terjadi di backoffice | Yang ditampilkan |
|
| `code` | HTTP | Kapan terjadi di backoffice | Yang ditampilkan |
|
||||||
| --- | --- | --- | --- |
|
| --- | --- | --- | --- |
|
||||||
| `303`, `310` | 400 | Body tidak valid, field tak dikenal di `PUT` setting, UUID salah | Pesan umum "Data tidak valid" + `cause` untuk developer |
|
| `303`, `310` | 400 | Body tidak valid, field tak dikenal di `PUT` setting, UUID salah | Pesan umum "Data tidak valid" + `cause` untuk developer |
|
||||||
| `304` | 400 | Nilai di luar batas, adjustment melebihi saldo, alasan kosong, hapus/ubah method EnakPoint | `cause` di dekat field atau di toast |
|
| `304` | 400 | Nilai di luar batas, adjustment melebihi saldo, alasan kosong | `cause` di dekat field atau di toast |
|
||||||
| `404` | 404 | Customer, outlet, atau mutasi bukan milik organisasi ini | "Data tidak ditemukan" |
|
| `404` | 404 | Customer, outlet, atau mutasi bukan milik organisasi ini | "Data tidak ditemukan" |
|
||||||
| `900` | 500 | Kesalahan server | "Terjadi kesalahan, coba lagi" |
|
| `900` | 500 | Kesalahan server | "Terjadi kesalahan, coba lagi" |
|
||||||
|
|
||||||
@@ -298,8 +290,7 @@ Pesan `cause` saat ini berbahasa Inggris, mis. `invalid loyalty settings: loyalt
|
|||||||
- [ ] Adjustment mewajibkan alasan dan mengirim `idempotency_key`.
|
- [ ] Adjustment mewajibkan alasan dan mengirim `idempotency_key`.
|
||||||
- [ ] Tombol Telusuri ada di setiap baris riwayat.
|
- [ ] Tombol Telusuri ada di setiap baris riwayat.
|
||||||
- [ ] Hapus PIN mewajibkan alasan; tab Keamanan menampilkan log.
|
- [ ] Hapus PIN mewajibkan alasan; tab Keamanan menampilkan log.
|
||||||
- [ ] Method EnakPoint tampil sebagai method sistem.
|
|
||||||
- [ ] Form game punya input `coin_cost`.
|
- [ ] Form game punya input `coin_cost`.
|
||||||
- [ ] Semua nilai rupiah EnakPoint ditulis "setara potongan Rp …".
|
- [ ] Semua nilai rupiah EnakPoint ditulis "setara potongan Rp …".
|
||||||
|
|
||||||
Pembayaran EnakPoint belum boleh dirilis ke outlet sebelum tinjauan keuangan (N2) dan legal (N3) selesai, dan transfer menunggu tinjauan legal (N3). Layar backoffice boleh disiapkan lebih dulu.
|
Transfer belum boleh dirilis sebelum tinjauan legal (N3) selesai. Layar backoffice boleh disiapkan lebih dulu.
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
+57
-140
@@ -6,6 +6,12 @@ lama tetap jalan sebagai alias (lihat §8)
|
|||||||
Panduan untuk memakai saldo loyalitas dari sisi klien. Alasan di balik setiap aturan
|
Panduan untuk memakai saldo loyalitas dari sisi klien. Alasan di balik setiap aturan
|
||||||
ada di [`prd-point-coin.md`](./prd-point-coin.md).
|
ada di [`prd-point-coin.md`](./prd-point-coin.md).
|
||||||
|
|
||||||
|
> **Perubahan 7 Okt 2026:** bayar order dengan EnakPoint sudah dihapus (migrasi
|
||||||
|
> `000102`). EnakPoint sekarang hanya bisa ditukar ke voucher, tidak bisa dipakai
|
||||||
|
> sebagai alat bayar dan tidak bisa dicairkan
|
||||||
|
> ([`enakgame-prd.md`](./enakgame-prd.md) §3.2). Endpoint dan field yang ikut dihapus
|
||||||
|
> ada di §8.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 1. Konsep inti
|
## 1. Konsep inti
|
||||||
@@ -13,21 +19,21 @@ ada di [`prd-point-coin.md`](./prd-point-coin.md).
|
|||||||
| | EnakPoint (`POINT`) | EnakCoin (`COIN`) |
|
| | EnakPoint (`POINT`) | EnakCoin (`COIN`) |
|
||||||
|---|---|---|
|
|---|---|---|
|
||||||
| Didapat dari | Order lunas (per outlet), adjustment admin, exchange | Order lunas (per outlet), adjustment admin |
|
| Didapat dari | Order lunas (per outlet), adjustment admin, exchange | Order lunas (per outlet), adjustment admin |
|
||||||
| Dipakai untuk | **Membayar order** | **Main game**, ditukar ke EnakPoint |
|
| Dipakai untuk | **Ditukar ke voucher** (tidak bisa membayar order) | **Main game**, ditukar ke EnakPoint |
|
||||||
| Bisa ditransfer | Ya | Ya |
|
| Bisa ditransfer | Ya | Ya |
|
||||||
| Bisa kedaluwarsa | Ya, bila diaktifkan owner | Ya, bila diaktifkan owner |
|
| Bisa kedaluwarsa | Ya, bila diaktifkan owner | Ya, bila diaktifkan owner |
|
||||||
|
|
||||||
Aturan yang berlaku di seluruh dokumen ini:
|
Aturan yang berlaku di seluruh dokumen ini:
|
||||||
|
|
||||||
1. **Semua jumlah bilangan bulat.** Tidak ada "setengah EnakPoint".
|
1. **Semua jumlah bilangan bulat.** Tidak ada "setengah EnakPoint".
|
||||||
2. **Saldo tidak pernah jadi uang.** Tidak ada pencairan, tidak ada kembalian, dan
|
2. **Saldo tidak pernah jadi uang.** Tidak ada pencairan, dan EnakPoint tidak bisa
|
||||||
bagian order yang dibayar EnakPoint hanya bisa kembali sebagai EnakPoint. Tampilkan
|
dipakai membayar order. Tampilkan nilai rupiahnya sebagai **"setara potongan
|
||||||
nilai rupiahnya sebagai **"setara potongan Rp …"**, bukan "saldo Rp …".
|
Rp …"**, bukan "saldo Rp …".
|
||||||
3. **Semua aksi customer yang memindahkan saldo butuh PIN 6 digit** (§3): bayar,
|
3. **Semua aksi customer yang memindahkan saldo butuh PIN 6 digit** (§3): exchange
|
||||||
buat kode bayar, exchange, transfer. Main game tidak butuh PIN.
|
dan transfer. Main game tidak butuh PIN.
|
||||||
4. **Wallet milik customer di satu organisasi.** Saldo berlaku di semua outlet
|
4. **Wallet milik customer di satu organisasi.** Saldo berlaku di semua outlet
|
||||||
organisasi itu. Nilai rupiah EnakPoint, kurs exchange, batas transfer, dan
|
organisasi itu. Nilai rupiah EnakPoint, kurs exchange, batas transfer, dan
|
||||||
kedaluwarsa diatur per organisasi; earning dan penerimaan pembayaran per outlet.
|
kedaluwarsa diatur per organisasi; earning per outlet.
|
||||||
5. **Setiap mutasi tercatat** di riwayat beserta asal atau tujuannya, dan tidak pernah
|
5. **Setiap mutasi tercatat** di riwayat beserta asal atau tujuannya, dan tidak pernah
|
||||||
dihapus. Koreksi muncul sebagai baris baru.
|
dihapus. Koreksi muncul sebagai baris baru.
|
||||||
|
|
||||||
@@ -91,7 +97,7 @@ Semua endpoint customer memakai header `Authorization: Bearer <token customer>`.
|
|||||||
|
|
||||||
### 2.2 Riwayat
|
### 2.2 Riwayat
|
||||||
|
|
||||||
`GET /api/v1/customer/wallet/transactions?page=1&limit=20¤cy=POINT&type=EARN,PAYMENT&from=2026-09-01&to=2026-09-30`
|
`GET /api/v1/customer/wallet/transactions?page=1&limit=20¤cy=POINT&type=EARN,TRANSFER_IN&from=2026-09-01&to=2026-09-30`
|
||||||
|
|
||||||
Semua query opsional. `limit` 1–100 (default 20). `type` boleh beberapa, dipisah koma.
|
Semua query opsional. `limit` 1–100 (default 20). `type` boleh beberapa, dipisah koma.
|
||||||
`from` / `to` tanggal WIB, inklusif.
|
`from` / `to` tanggal WIB, inklusif.
|
||||||
@@ -119,8 +125,8 @@ Semua query opsional. `limit` 1–100 (default 20). `type` boleh beberapa, dipis
|
|||||||
|
|
||||||
- `amount` bertanda: positif menambah saldo, negatif mengurangi.
|
- `amount` bertanda: positif menambah saldo, negatif mengurangi.
|
||||||
- Penambahan punya `source`, pengurangan punya `destination`. Keduanya berbentuk
|
- Penambahan punya `source`, pengurangan punya `destination`. Keduanya berbentuk
|
||||||
`{ type, id }` dan menunjuk hal yang bisa dibuka di detail (order, pembayaran, game
|
`{ type, id }` dan menunjuk hal yang bisa dibuka di detail (order, game play,
|
||||||
play, dst.).
|
dst.).
|
||||||
- `description` sudah siap tampil dan tidak berubah walau nama outlet atau customer
|
- `description` sudah siap tampil dan tidak berubah walau nama outlet atau customer
|
||||||
berubah belakangan. Nama lawan transfer sudah disamarkan.
|
berubah belakangan. Nama lawan transfer sudah disamarkan.
|
||||||
- Dua baris exchange atau transfer berbagi `group_id` yang sama.
|
- Dua baris exchange atau transfer berbagi `group_id` yang sama.
|
||||||
@@ -129,8 +135,6 @@ Semua query opsional. `limit` 1–100 (default 20). `type` boleh beberapa, dipis
|
|||||||
|---|---|---|---|
|
|---|---|---|---|
|
||||||
| `EARN` | + | Didapat dari order lunas | `ORDER` |
|
| `EARN` | + | Didapat dari order lunas | `ORDER` |
|
||||||
| `EARN_REVERSAL` | − | Ditarik karena order di-void/refund | `ORDER` |
|
| `EARN_REVERSAL` | − | Ditarik karena order di-void/refund | `ORDER` |
|
||||||
| `PAYMENT` | − | Membayar order | `PAYMENT` |
|
|
||||||
| `PAYMENT_REFUND` | + | Kembali karena pembayaran di-void/refund | `PAYMENT` |
|
|
||||||
| `EXCHANGE_OUT` / `EXCHANGE_IN` | − / + | Tukar EnakCoin ke EnakPoint | `WALLET_TX` (baris pasangannya) |
|
| `EXCHANGE_OUT` / `EXCHANGE_IN` | − / + | Tukar EnakCoin ke EnakPoint | `WALLET_TX` (baris pasangannya) |
|
||||||
| `TRANSFER_OUT` / `TRANSFER_IN` | − / + | Transfer antar customer | `WALLET_TX` (baris pasangannya) |
|
| `TRANSFER_OUT` / `TRANSFER_IN` | − / + | Transfer antar customer | `WALLET_TX` (baris pasangannya) |
|
||||||
| `GAME_SPEND` | − | Main game | `GAME_PLAY` |
|
| `GAME_SPEND` | − | Main game | `GAME_PLAY` |
|
||||||
@@ -219,7 +223,7 @@ menghasilkan `429`.
|
|||||||
- **Lupa PIN:** minta OTP dengan `purpose: "pin_reset"`, lalu
|
- **Lupa PIN:** minta OTP dengan `purpose: "pin_reset"`, lalu
|
||||||
`POST /api/v1/customer/pin/reset` dengan body yang sama seperti §3.2. Reset juga
|
`POST /api/v1/customer/pin/reset` dengan body yang sama seperti §3.2. Reset juga
|
||||||
membuka PIN yang terkunci. Setelah reset, **transfer keluar ditahan 24 jam**;
|
membuka PIN yang terkunci. Setelah reset, **transfer keluar ditahan 24 jam**;
|
||||||
pembayaran dan exchange tetap bisa.
|
exchange tetap bisa.
|
||||||
|
|
||||||
### 3.4 Menangani error PIN
|
### 3.4 Menangani error PIN
|
||||||
|
|
||||||
@@ -247,123 +251,19 @@ reinstall atau ganti HP.
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 4. Membayar dengan EnakPoint
|
## 4. Earning, void, dan refund
|
||||||
|
|
||||||
Ada dua jalur. Keduanya memakai logika perhitungan yang sama.
|
EnakPoint bukan payment method: tidak ada payment method bertipe `point`, dan
|
||||||
|
`POST /api/v1/payments` memakai `amount` seperti pembayaran lain. Kode bayar,
|
||||||
### 4.1 Batas pembayaran
|
bayar dari aplikasi, dan preview pembayaran EnakPoint sudah dihapus (§8).
|
||||||
|
|
||||||
EnakPoint maksimal yang bisa dipakai untuk satu order:
|
|
||||||
|
|
||||||
```
|
|
||||||
batas_rupiah = min(sisa_tagihan, total_order × max_payment_percent / 100 − yang_sudah_dibayar_EnakPoint)
|
|
||||||
maks_point = min(saldo_customer, floor(batas_rupiah / point_value))
|
|
||||||
```
|
|
||||||
|
|
||||||
Ditambah minimal `min_payment_points` per pembayaran. Nominal rupiah pembayaran selalu
|
|
||||||
`points × point_value` dan **tidak pernah melebihi sisa tagihan**, jadi tidak ada
|
|
||||||
kembalian. Sisa tagihan dibayar dengan method lain seperti biasa (split).
|
|
||||||
|
|
||||||
### 4.2 POS — kode bayar dari aplikasi customer
|
|
||||||
|
|
||||||
PIN **tidak pernah** diketik di perangkat kasir. Customer menyetujui di HP-nya sendiri:
|
|
||||||
|
|
||||||
1. **Customer app:** `POST /api/v1/customer/wallet/payment-code` dengan `{ "pin": "482913" }`.
|
|
||||||
|
|
||||||
```json
|
|
||||||
{ "code": "482913", "qr_payload": "enakpoint:482913", "expires_at": "2026-09-30T05:02:00Z" }
|
|
||||||
```
|
|
||||||
|
|
||||||
Tampilkan `code` sebagai angka dan `qr_payload` sebagai QR. Kode berlaku **2 menit**,
|
|
||||||
sekali pakai, dan hanya untuk customer itu. Membuat kode baru membatalkan kode lama.
|
|
||||||
|
|
||||||
2. **POS:** tampilkan batas untuk tombol "pakai maksimal":
|
|
||||||
|
|
||||||
`GET /api/v1/orders/:id/point-payment/preview`
|
|
||||||
|
|
||||||
```json
|
|
||||||
{
|
|
||||||
"order_id": "…",
|
|
||||||
"customer_id": "…",
|
|
||||||
"eligible": true,
|
|
||||||
"point_balance": 12500,
|
|
||||||
"point_value": 1,
|
|
||||||
"remaining_amount": 87500,
|
|
||||||
"min_payment_points": 1,
|
|
||||||
"max_payment_percent": 100,
|
|
||||||
"max_points": 12500,
|
|
||||||
"max_amount": 12500
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
Bila `eligible: false`, `reason` menjelaskan kenapa (order walk-in, outlet tidak
|
|
||||||
menerima EnakPoint, saldo di bawah minimal, dst.).
|
|
||||||
|
|
||||||
3. **POS:** bayar lewat endpoint pembayaran yang sudah ada, dengan payment method
|
|
||||||
bertipe `point`:
|
|
||||||
|
|
||||||
`POST /api/v1/payments` (header `X-Idempotency-Key` wajib seperti pembayaran lain)
|
|
||||||
|
|
||||||
```json
|
|
||||||
{
|
|
||||||
"order_id": "…",
|
|
||||||
"payment_method_id": "<id method EnakPoint>",
|
|
||||||
"points": 12500,
|
|
||||||
"payment_code": "482913"
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
`amount` tidak perlu dikirim; backend menghitungnya. `payment_code` boleh berupa
|
|
||||||
angka yang diketik kasir atau hasil scan QR apa adanya (`enakpoint:482913`).
|
|
||||||
|
|
||||||
Response pembayaran membawa `points_used` dan `point_value` untuk struk, misalnya
|
|
||||||
"EnakPoint: 12.500 (Rp 12.500)". Jika pembayaran ini melunasi order, order menjadi
|
|
||||||
`completed`; jika belum, sisanya dibayar dengan method lain.
|
|
||||||
|
|
||||||
Pembayaran ditolak (`304`, `cause` menjelaskan) bila: order tanpa customer atau
|
|
||||||
customer walk-in, customer nonaktif, outlet tidak menerima EnakPoint, `points` di luar
|
|
||||||
batas §4.1, kode salah/kedaluwarsa/sudah dipakai/milik customer lain, atau method
|
|
||||||
EnakPoint dipakai sebagai split (bayar bagian EnakPoint sebagai pembayaran tersendiri,
|
|
||||||
lalu split sisanya seperti biasa). Kode bayar dipakai habis begitu diterima, sebelum
|
|
||||||
batas dicek ulang; bila pembayaran lalu ditolak (misalnya saldo berubah), minta
|
|
||||||
customer membuat kode baru.
|
|
||||||
|
|
||||||
**Method EnakPoint** dibuat otomatis untuk setiap organisasi dan tidak bisa dihapus
|
|
||||||
atau diubah tipenya (namanya boleh diganti). Daftar payment method yang dikirim
|
|
||||||
`?outlet_id=` tidak menampilkannya bila outlet itu tidak menerima EnakPoint.
|
|
||||||
|
|
||||||
### 4.3 Customer app / self-order — bayar order sendiri
|
|
||||||
|
|
||||||
`POST /api/v1/customer/orders/:id/pay-with-points`
|
|
||||||
|
|
||||||
```json
|
|
||||||
{ "points": 12500, "pin": "482913" }
|
|
||||||
```
|
|
||||||
|
|
||||||
Hanya untuk order milik customer yang login; order lain dijawab `404`. Response sama
|
|
||||||
dengan response pembayaran di §4.2.
|
|
||||||
|
|
||||||
### 4.4 Void dan refund
|
|
||||||
|
|
||||||
- **Void order:** semua EnakPoint yang dipakai kembali ke customer sebagai EnakPoint.
|
|
||||||
- **Refund pembayaran EnakPoint** (`POST /api/v1/payments/:id/refund` pada pembayaran
|
|
||||||
EnakPoint): yang kembali `floor(rupiah_direfund / point_value_saat_bayar)`. Perubahan
|
|
||||||
nilai EnakPoint setelah pembayaran tidak mengubah jumlah yang kembali; sisa di bawah
|
|
||||||
1 EnakPoint hangus.
|
|
||||||
- **Refund order ke tunai / method lain** hanya boleh sebesar bagian yang dibayar
|
|
||||||
dengan method lain. Bagian EnakPoint harus direfund lewat pembayaran EnakPoint-nya
|
|
||||||
sendiri; mencoba lewat tunai dijawab `304`.
|
|
||||||
- EnakPoint yang kembali mengikuti tanggal kedaluwarsa asalnya, tapi minimal 7 hari
|
|
||||||
sejak refund.
|
|
||||||
- EnakPoint dan EnakCoin yang didapat dari order ikut ditarik saat void/refund. Bila
|
|
||||||
saldo customer sudah terpakai, yang ditarik sebanyak yang ada; refund tidak pernah
|
|
||||||
diblokir karena ini.
|
|
||||||
|
|
||||||
### 4.5 Earning di layar order dan struk
|
|
||||||
|
|
||||||
Response order membawa `points_earned` dan `coins_earned` (0 bila order tidak
|
Response order membawa `points_earned` dan `coins_earned` (0 bila order tidak
|
||||||
menghasilkan apa-apa). Earning dihitung dari `subtotal − discount − bagian yang
|
menghasilkan apa-apa). Earning dihitung dari `subtotal − discount`, sebelum pajak, dan
|
||||||
dibayar EnakPoint`, sebelum pajak, dan diberikan saat order lunas.
|
diberikan saat order lunas.
|
||||||
|
|
||||||
|
EnakPoint dan EnakCoin yang didapat dari order ikut ditarik saat void/refund. Bila
|
||||||
|
saldo customer sudah terpakai, yang ditarik sebanyak yang ada; refund tidak pernah
|
||||||
|
diblokir karena ini.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -504,6 +404,24 @@ Semua yang bernama token sudah dihapus: `GET /customer/tokens`, `total_tokens`,
|
|||||||
`tokens_history`, `token_used`, `tokens_remaining`, dan nilai `TOKENS` di campaign. Pakai
|
`tokens_history`, `token_used`, `tokens_remaining`, dan nilai `TOKENS` di campaign. Pakai
|
||||||
`coin_balance`, `coins_used`, `coins_remaining`, dan `COINS`.
|
`coin_balance`, `coins_used`, `coins_remaining`, dan `COINS`.
|
||||||
|
|
||||||
|
Bayar dengan EnakPoint juga sudah dihapus (7 Okt 2026, migrasi `000102`) karena
|
||||||
|
EnakPoint sekarang hanya untuk voucher ([`enakgame-prd.md`](./enakgame-prd.md) §3.2).
|
||||||
|
Tidak ada penggantinya:
|
||||||
|
|
||||||
|
- Endpoint `POST /customer/wallet/payment-code`, `POST /customer/orders/:id/pay-with-points`,
|
||||||
|
dan `GET /orders/:id/point-payment/preview`.
|
||||||
|
- Payment method tipe `point`, serta field `points` dan `payment_code` di
|
||||||
|
`POST /payments`; `amount` kembali wajib seperti pembayaran lain.
|
||||||
|
- `points_used` dan `point_value` di response pembayaran dan di `payments` pada
|
||||||
|
`GET /customer/orders/:id`; `accepts_point_payment` di `GET /customer/outlets`.
|
||||||
|
- Objek `point_payment` (`accept_payment`, `min_payment_points`,
|
||||||
|
`max_payment_percent`) di setting outlet (§9.1).
|
||||||
|
- Di analytics payment method: `point_amount`, `points_used`, `total_with_points` di
|
||||||
|
`summary`, serta `points_used` dan `counts_as_cash_in` per baris.
|
||||||
|
`summary.total_amount` kembali total semua method, dan persentase dihitung dari total
|
||||||
|
itu.
|
||||||
|
- Tipe mutasi `PAYMENT` dan `PAYMENT_REFUND` tidak ditulis lagi.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 9. Dashboard
|
## 9. Dashboard
|
||||||
@@ -516,15 +434,16 @@ Semua endpoint di bagian ini butuh login user dengan role Admin atau Manager.
|
|||||||
|
|
||||||
```json
|
```json
|
||||||
{
|
{
|
||||||
"point": { "enabled": true, "earn_per_amount": 100, "earn_value": 1, "min_order_amount": 0, "max_per_order": null },
|
"point": { "enabled": true, "earn_mode": "PER_AMOUNT", "earn_per_amount": 100, "earn_value": 1, "earn_percent": 1, "min_order_amount": 0, "max_per_order": null },
|
||||||
"coin": { "enabled": true, "earn_per_amount": 25000, "earn_value": 1, "min_order_amount": 0, "max_per_order": null },
|
"coin": { "enabled": true, "earn_mode": "PER_AMOUNT", "earn_per_amount": 25000, "earn_value": 1, "earn_percent": 1, "min_order_amount": 0, "max_per_order": null }
|
||||||
"point_payment": { "accept_payment": true, "min_payment_points": 1, "max_payment_percent": 100 }
|
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
Field yang tidak dikirim di `PUT` tetap memakai nilai sekarang. Response menambahkan
|
Field yang tidak dikirim di `PUT` tetap memakai nilai sekarang. `PUT` yang masih
|
||||||
|
mengirim `point_payment` ditolak `310` (field tidak dikenal). Response menambahkan
|
||||||
`point_value` organisasi dan `point_cashback_percent`
|
`point_value` organisasi dan `point_cashback_percent`
|
||||||
(`earn_value × point_value / earn_per_amount × 100`). **Tampilkan persentase ini di
|
(`earn_value × point_value / earn_per_amount × 100`, atau `earn_percent × point_value`
|
||||||
|
pada `earn_mode` `PERCENTAGE`). **Tampilkan persentase ini di
|
||||||
samping setting** supaya owner tidak salah membaca skala: default di atas setara
|
samping setting** supaya owner tidak salah membaca skala: default di atas setara
|
||||||
cashback 1%.
|
cashback 1%.
|
||||||
|
|
||||||
@@ -596,10 +515,10 @@ Riwayat perubahan: `GET /api/v1/marketing/loyalty-settings/history?page=1&limit=
|
|||||||
Adjustment tidak disertai pembayaran uang, jadi jangan pakai alasan "pencairan".
|
Adjustment tidak disertai pembayaran uang, jadi jangan pakai alasan "pencairan".
|
||||||
|
|
||||||
- `GET /api/v1/marketing/wallet-transactions/:id/trace` — telusuri satu mutasi per
|
- `GET /api/v1/marketing/wallet-transactions/:id/trace` — telusuri satu mutasi per
|
||||||
butir: lot mana yang dipakai atau dibuat, lalu rantai asalnya lewat transfer,
|
butir: lot mana yang dipakai atau dibuat, lalu rantai asalnya lewat transfer atau
|
||||||
exchange, atau refund sampai ke earning/adjustment/migrasi pertama. Contoh: dari
|
exchange sampai ke earning/adjustment/migrasi pertama. Contoh: dari transfer keluar
|
||||||
pembayaran B bisa terlihat bahwa EnakPoint-nya berasal dari order #ORD-1 milik A
|
B bisa terlihat bahwa EnakPoint-nya berasal dari order #ORD-1 milik A yang
|
||||||
yang mentransfer ke B.
|
mentransfer ke B.
|
||||||
|
|
||||||
### 9.4 PIN customer
|
### 9.4 PIN customer
|
||||||
|
|
||||||
@@ -623,10 +542,8 @@ Riwayat perubahan: `GET /api/v1/marketing/loyalty-settings/history?page=1&limit=
|
|||||||
- [ ] Baca `coins_used` / `coins_remaining` dan `/customer/wallet`, bukan field lama.
|
- [ ] Baca `coins_used` / `coins_remaining` dan `/customer/wallet`, bukan field lama.
|
||||||
|
|
||||||
**POS**
|
**POS**
|
||||||
- [ ] Scan QR atau ketik kode bayar, jangan pernah meminta PIN customer di layar kasir.
|
- [ ] Cetak `points_earned` dan `coins_earned` di struk.
|
||||||
- [ ] Pakai `point-payment/preview` untuk tombol "pakai maksimal".
|
- [ ] Jangan menampilkan EnakPoint sebagai payment method (§4).
|
||||||
- [ ] Cetak `points_used`, `points_earned`, dan `coins_earned` di struk.
|
|
||||||
- [ ] Refund bagian EnakPoint lewat pembayaran EnakPoint-nya, bukan tunai.
|
|
||||||
|
|
||||||
**Dashboard**
|
**Dashboard**
|
||||||
- [ ] Tampilkan `point_cashback_percent`, `impact`, `expiry_preview`, dan
|
- [ ] Tampilkan `point_cashback_percent`, `impact`, `expiry_preview`, dan
|
||||||
|
|||||||
@@ -0,0 +1,143 @@
|
|||||||
|
# Migrasi printer_type ke printer_types
|
||||||
|
|
||||||
|
1 Oktober 2026
|
||||||
|
|
||||||
|
## Ringkasan
|
||||||
|
|
||||||
|
`printer_type` (string) dihapus dan diganti `printer_types` (array string), sehingga satu produk bisa dicetak ke lebih dari satu printer. Contohnya "Paket Makan Minum" dengan `["kitchen", "bar"]` tercetak di kitchen dan bar sekaligus.
|
||||||
|
|
||||||
|
Ini breaking change. Setelah backend baru dirilis, client yang masih membaca `printer_type` tidak menerima printer apa pun. Karena itu app POS dan dashboard harus diupdate lebih dulu, lihat [Urutan rilis](#database-dan-urutan-rilis).
|
||||||
|
|
||||||
|
Yang perlu bertindak:
|
||||||
|
|
||||||
|
- **App POS**: baca `printer_types` dan cetak tiap item ke semua printer di dalamnya.
|
||||||
|
- **Dashboard admin**: ganti pilihan printer di form produk jadi multi-select yang mengirim `printer_types`.
|
||||||
|
|
||||||
|
## Perubahan response
|
||||||
|
|
||||||
|
`printer_type` hilang dari semua response dan digantikan `printer_types`, yang nilainya selalu array dan tidak pernah `null`.
|
||||||
|
|
||||||
|
| Endpoint | Letak field |
|
||||||
|
| --- | --- |
|
||||||
|
| `POST /api/v1/products`, `PUT /api/v1/products/:id`, `GET /api/v1/products`, `GET /api/v1/products/all`, `GET /api/v1/products/:id` | objek produk |
|
||||||
|
| `POST /api/v1/orders`, `GET /api/v1/orders`, `GET /api/v1/orders/:id`, `PUT /api/v1/orders/:id` | `order_items[]` |
|
||||||
|
| `POST /api/v1/orders/:id/add-items` | `added_items[]` dan `updated_order.order_items[]` |
|
||||||
|
| `POST /api/v1/self-order/orders`, `GET /api/v1/self-order/orders/:session_id` | `order_items[]` |
|
||||||
|
| `/api/v1/product-recipes` (semua yang mengembalikan recipe) | `product` |
|
||||||
|
| `/api/v1/inventory` | `product`, selalu `[]` karena produk di sini hanya berisi id dan nama |
|
||||||
|
|
||||||
|
Contoh satu item di `order_items[]`:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"product_name": "Paket Makan Minum",
|
||||||
|
"printer_types": ["kitchen", "bar"],
|
||||||
|
"print_to_checker": true
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Aturan nilainya:
|
||||||
|
|
||||||
|
- `printer_types: []` artinya produk tidak dicetak ke printer mana pun.
|
||||||
|
- Urutan printer sesuai yang disimpan admin, tanpa duplikat.
|
||||||
|
- Void, refund, payment, split bill, dan set customer tidak membawa data printer, sama seperti sebelumnya.
|
||||||
|
|
||||||
|
## Perubahan request produk
|
||||||
|
|
||||||
|
`POST /api/v1/products` dan `PUT /api/v1/products/:id` menerima `printer_types` sebagai pengganti `printer_type`. Kalau `printer_type` masih dikirim, field itu diabaikan tanpa error.
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"name": "Paket Makan Minum",
|
||||||
|
"category_id": "<uuid>",
|
||||||
|
"price": 25000,
|
||||||
|
"printer_types": ["kitchen", "bar"]
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
| Request | `printer_types` yang dikirim | Hasil |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| Create | tidak dikirim | `["kitchen"]` |
|
||||||
|
| Create | `["kitchen", "bar"]` | `["kitchen", "bar"]` |
|
||||||
|
| Create | `[]` atau hanya string kosong | `["kitchen"]` |
|
||||||
|
| Update | tidak dikirim | tidak berubah |
|
||||||
|
| Update | `["bar"]` | `["bar"]`, seluruh daftar diganti |
|
||||||
|
| Update | `[]` | `[]`, produk tidak dicetak ke mana pun |
|
||||||
|
|
||||||
|
Sebelum disimpan, spasi di awal dan akhir tiap entri dibuang, lalu entri kosong dan duplikat dihapus. Urutan dipertahankan.
|
||||||
|
|
||||||
|
Tiap entri maksimal 50 karakter. Kalau lebih, request ditolak dengan error code `310` dan pesan `each printer_types entry cannot exceed 50 characters`.
|
||||||
|
|
||||||
|
## Migrasi app POS
|
||||||
|
|
||||||
|
App POS harus mengirim tiap item ke semua printer di `printer_types`, sehingga satu item bisa muncul di lebih dari satu tiket.
|
||||||
|
|
||||||
|
1. Ganti `printer_type` dengan `printer_types` (list string) di model order item dan produk.
|
||||||
|
2. Selama backend lama masih jalan, `printer_types` belum ada di response. Pakai `[printer_type]` kalau `printer_types` tidak ada, supaya app baru bisa dirilis sebelum backend.
|
||||||
|
3. Saat mencetak, kelompokkan item per printer dengan mengulang setiap entri `printer_types` milik item.
|
||||||
|
4. Item dengan `printer_types: []` tidak dicetak ke printer station mana pun.
|
||||||
|
5. `print_to_checker` tidak berubah dan tetap diperlakukan terpisah.
|
||||||
|
6. Untuk tambahan pesanan dari `POST /api/v1/orders/:id/add-items`, cetak dari `added_items[]`.
|
||||||
|
|
||||||
|
```text
|
||||||
|
tiket = {}
|
||||||
|
untuk setiap item di order_items:
|
||||||
|
printers = item.printer_types ?? [item.printer_type] // fallback hanya untuk backend lama
|
||||||
|
untuk setiap printer di printers:
|
||||||
|
tiket[printer].tambah(item)
|
||||||
|
untuk setiap (printer, items) di tiket:
|
||||||
|
cetak items ke printer
|
||||||
|
```
|
||||||
|
|
||||||
|
Perbaikan di `added_items[]`: sebelumnya field ini selalu berisi `product_name` dan printer kosong, serta `print_to_checker: true`. Sekarang isinya lengkap seperti item di `updated_order.order_items[]`, dengan urutan sesuai request. Kalau app selama ini mengakali dengan mencari item baru di `updated_order`, cara itu bisa diganti dengan `added_items[]` langsung.
|
||||||
|
|
||||||
|
## Migrasi dashboard
|
||||||
|
|
||||||
|
Form produk di dashboard harus memakai multi-select printer dan selalu mengirim daftar lengkapnya lewat `printer_types`.
|
||||||
|
|
||||||
|
1. Ganti dropdown printer tunggal dengan multi-select, misalnya checkbox, berisi pilihan printer yang sama.
|
||||||
|
2. Saat membuka form edit, isi pilihan dari `printer_types`. Selama backend lama masih jalan, pakai `[printer_type]` kalau `printer_types` tidak ada.
|
||||||
|
3. Saat menyimpan, kirim `printer_types` berisi semua printer yang dipilih.
|
||||||
|
4. Selama backend lama masih jalan, kirim juga `printer_type` berisi printer pertama. Backend lama hanya membaca `printer_type`, dan backend baru mengabaikannya.
|
||||||
|
5. Di daftar produk, tampilkan semua printer dari `printer_types`.
|
||||||
|
|
||||||
|
Backend tidak membatasi nilai printer. Nilainya harus sama persis dengan nama printer yang dikenal app POS, termasuk huruf besar dan kecilnya.
|
||||||
|
|
||||||
|
Create dengan `printer_types: []` tetap menghasilkan `["kitchen"]`. Produk tanpa printer dibuat dulu, lalu di-update dengan `printer_types: []`.
|
||||||
|
|
||||||
|
## Database dan urutan rilis
|
||||||
|
|
||||||
|
Migration `000099_add_printer_types_to_products` menambah kolom `products.printer_types` (JSONB, `NOT NULL`, default `["kitchen"]`), mengisinya dari `printer_type`, lalu menghapus kolom `printer_type` beserta index-nya.
|
||||||
|
|
||||||
|
- Produk dengan `printer_type` berisi nilai menjadi `[printer_type]`.
|
||||||
|
- Produk dengan `printer_type` `NULL` atau kosong menjadi `[]`.
|
||||||
|
|
||||||
|
Urutan rilis:
|
||||||
|
|
||||||
|
1. Rilis app POS baru, yang membaca `printer_types` dengan fallback ke `printer_type`, ke semua outlet.
|
||||||
|
2. Rilis dashboard baru, yang mengirim `printer_types` dan `printer_type`.
|
||||||
|
3. Jalankan migration `000099` tepat sebelum deploy backend baru. Di antara keduanya, backend lama gagal menyimpan produk karena kolom `printer_type` sudah tidak ada.
|
||||||
|
4. Setelah backend baru jalan, dashboard boleh berhenti mengirim `printer_type`, dan fallback di app POS boleh dihapus.
|
||||||
|
5. Atur produk multi-printer, misalnya "Paket Makan Minum" ke `["kitchen", "bar"]`.
|
||||||
|
|
||||||
|
Outlet yang masih memakai app POS lama setelah langkah 3 tidak menerima printer untuk semua item. Pastikan langkah 1 sudah selesai di semua outlet.
|
||||||
|
|
||||||
|
Rollback: jalankan down migration dan deploy backend lama bersamaan. Down migration membuat ulang kolom `printer_type` berisi printer pertama, lalu menghapus `printer_types`, jadi yang hilang hanya printer tambahan.
|
||||||
|
|
||||||
|
## Checklist
|
||||||
|
|
||||||
|
- [ ] App POS baru (dengan fallback) terpasang di semua outlet
|
||||||
|
- [ ] Dashboard baru mengirim `printer_types` dan `printer_type`
|
||||||
|
- [ ] Migration `000099` dan backend baru dirilis di staging
|
||||||
|
- [ ] Uji "Paket Makan Minum" dengan `["kitchen", "bar"]` tercetak di dua printer, saat order baru dan saat tambah pesanan
|
||||||
|
- [ ] Migration `000099` dan backend baru dirilis di production
|
||||||
|
- [ ] Dashboard berhenti mengirim `printer_type`
|
||||||
|
- [ ] Fallback `printer_type` di app POS dihapus
|
||||||
|
|
||||||
|
## FAQ
|
||||||
|
|
||||||
|
**Kenapa `printer_type` dihapus, bukan dipertahankan?** Supaya hanya ada satu sumber data printer. Dua field yang menyimpan hal yang sama bisa saling berbeda.
|
||||||
|
|
||||||
|
**Apakah kitchen dan bar menerima tiket yang sama?** Ya. Keduanya mencetak "Paket Makan Minum" lengkap dengan varian dan modifier-nya. Memecah isi paket per station butuh fitur bundle, yang di luar rilis ini.
|
||||||
|
|
||||||
|
**Apakah nilai printer dibatasi?** Tidak. Nilainya string bebas sampai 50 karakter, dan harus sama dengan nama printer di app POS.
|
||||||
@@ -0,0 +1,289 @@
|
|||||||
|
# Migrasi profit sharing
|
||||||
|
|
||||||
|
4 Oktober 2026
|
||||||
|
|
||||||
|
## Ringkasan
|
||||||
|
|
||||||
|
Ada tiga perubahan di backend:
|
||||||
|
|
||||||
|
1. **Parent category bisa ditandai bukan team.** Kategori punya field baru `is_team`. Parent category dengan `is_team: false` tidak bisa dipilih sebagai team di purchase order dan cash advance, dan tidak ikut laporan profit sharing.
|
||||||
|
2. **Endpoint laporan pindah path.** `/api/v1/analytics/parent-categories` menjadi `/api/v1/analytics/profit-sharing`.
|
||||||
|
3. **Pembagian revenue tinggal dua porsi.** Porsi purchase (60%) dihapus. Revenue sekarang dibagi ke owner (SDL) dan team, dengan porsi team = 100% − fee owner.
|
||||||
|
|
||||||
|
Nomor 2 dan 3 adalah breaking change. Setelah backend baru dirilis, client yang masih memanggil path lama mendapat 404, dan `limit_purchase` serta `percentages.purchase` tidak ada lagi di response. Karena itu client harus diupdate lebih dulu, lihat [Urutan rilis](#database-dan-urutan-rilis).
|
||||||
|
|
||||||
|
Yang perlu bertindak, di dashboard maupun app mobile, mana pun yang punya layarnya:
|
||||||
|
|
||||||
|
- **Form kategori**: tambah toggle team untuk parent category.
|
||||||
|
- **Laporan profit sharing**: ganti path, hapus porsi purchase, tampilkan dua porsi.
|
||||||
|
- **Form purchase order dan cash advance**: picker team tidak perlu diubah, tapi form edit perlu menyesuaikan, lihat [Purchase order dan cash advance](#purchase-order-dan-cash-advance).
|
||||||
|
|
||||||
|
## Kategori: field `is_team`
|
||||||
|
|
||||||
|
### Response
|
||||||
|
|
||||||
|
Semua response kategori membawa `is_team` (boolean, tidak pernah `null`): `POST /api/v1/categories`, `PUT /api/v1/categories/:id`, `GET /api/v1/categories`, dan `GET /api/v1/categories/:id`.
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"id": "<uuid>",
|
||||||
|
"name": "Merchandise",
|
||||||
|
"parent_id": null,
|
||||||
|
"owner_fee_percent": null,
|
||||||
|
"is_team": false
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Request
|
||||||
|
|
||||||
|
`POST /api/v1/categories` dan `PUT /api/v1/categories/:id` menerima `is_team`.
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"name": "Merchandise",
|
||||||
|
"is_team": false
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
| Request | `is_team` yang dikirim | Hasil |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| Create | tidak dikirim | `true` |
|
||||||
|
| Create | `false` | `false` |
|
||||||
|
| Update | tidak dikirim atau `null` | tidak berubah |
|
||||||
|
| Update | `true` atau `false` | diganti |
|
||||||
|
|
||||||
|
Update yang hanya berisi `is_team` diterima.
|
||||||
|
|
||||||
|
Aturan nilainya:
|
||||||
|
|
||||||
|
- `is_team` hanya berpengaruh di parent category, yaitu kategori dengan `parent_id: null`. Di sub-category nilainya disimpan tapi tidak dipakai, jadi tampilkan toggle hanya untuk parent category.
|
||||||
|
- Semua kategori yang sudah ada sebelum rilis bernilai `true`. Tidak ada yang berubah sampai admin mematikannya.
|
||||||
|
- Flag dibaca saat request, bukan saat transaksi. Kalau parent category dimatikan, penjualannya di periode lampau juga hilang dari laporan profit sharing. Kalau dinyalakan lagi, semuanya muncul kembali.
|
||||||
|
|
||||||
|
### Efek `is_team: false`
|
||||||
|
|
||||||
|
| Endpoint | Efek |
|
||||||
|
| --- | --- |
|
||||||
|
| `GET /api/v1/purchase-orders/teams`, `GET /api/v1/cash-advances/teams` | Kategori tidak muncul. Pusat tetap ada. |
|
||||||
|
| Create dan update purchase order dan cash advance | `team_scope: "category"` dengan `team_category_id` kategori ini ditolak. |
|
||||||
|
| `GET /api/v1/analytics/profit-sharing` | Kategori tidak muncul di `data`, dan revenue-nya tidak dihitung di `budget`. |
|
||||||
|
| `GET /api/v1/analytics/profit-sharing/:parent_category_id` | Ditolak. |
|
||||||
|
|
||||||
|
Data yang sudah ada tidak diubah. Purchase order dan cash advance yang sudah tercatat ke kategori itu tetap menyimpan team-nya. Laporan purchasing (`GET /api/v1/analytics/purchasing`) masih menampilkannya di `team_data`, dan filter `team=<category_id>` tetap bisa dipakai.
|
||||||
|
|
||||||
|
Laporan lain yang tidak menyaring `is_team`, misalnya `GET /api/v1/analytics/categories`, tetap menampilkan penjualan kategori itu.
|
||||||
|
|
||||||
|
## Purchase order dan cash advance
|
||||||
|
|
||||||
|
Picker team sudah mengambil dari `GET /api/v1/purchase-orders/teams` dan `GET /api/v1/cash-advances/teams`, jadi kategori non-team otomatis tidak muncul tanpa perubahan di client.
|
||||||
|
|
||||||
|
Yang perlu diubah ada di form edit. Purchase order atau cash advance lama bisa tercatat ke kategori yang sekarang sudah non-team. Kalau form edit mengirim ulang `team_scope` dan `team_category_id` yang sama, request ditolak, walaupun user tidak mengubah team-nya.
|
||||||
|
|
||||||
|
1. Kirim `team_scope` dan `team_category_id` hanya kalau user mengganti team. Kalau `team_scope` tidak dikirim, team yang tersimpan tidak berubah.
|
||||||
|
2. Kalau team yang tersimpan tidak ada di daftar `/teams`, tampilkan namanya dari field `team` di response apa adanya, dan jangan memilihkan team lain secara otomatis.
|
||||||
|
|
||||||
|
Contoh error saat team ditolak, dengan HTTP status 500:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"success": false,
|
||||||
|
"data": null,
|
||||||
|
"errors": [
|
||||||
|
{
|
||||||
|
"code": "900",
|
||||||
|
"entity": "purchase_order_service",
|
||||||
|
"cause": "category Merchandise is not a team"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Untuk cash advance, `entity` bernilai `cash_advance_service`. Cocokkan dengan teks `is not a team` di `cause` kalau perlu menampilkan pesan khusus.
|
||||||
|
|
||||||
|
## Laporan profit sharing
|
||||||
|
|
||||||
|
### Path baru
|
||||||
|
|
||||||
|
| Lama | Baru |
|
||||||
|
| --- | --- |
|
||||||
|
| `GET /api/v1/analytics/parent-categories` | `GET /api/v1/analytics/profit-sharing` |
|
||||||
|
| `GET /api/v1/analytics/parent-categories/:parent_category_id` | `GET /api/v1/analytics/profit-sharing/:parent_category_id` |
|
||||||
|
|
||||||
|
Query parameter dan role tidak berubah:
|
||||||
|
|
||||||
|
- `date_from` dan `date_to` wajib, dengan format `DD-MM-YYYY`, misalnya `28-09-2026`.
|
||||||
|
- `outlet_id` opsional.
|
||||||
|
- Hanya bisa diakses superadmin, admin, manager, owner, dan purchasing.
|
||||||
|
|
||||||
|
Path lama sudah tidak ada dan mengembalikan 404.
|
||||||
|
|
||||||
|
### Pembagian revenue
|
||||||
|
|
||||||
|
Revenue tiap parent category yang team dibagi dua:
|
||||||
|
|
||||||
|
- **SDL (fee owner)** = revenue × `owner_fee_percent` / 100. Default-nya 20%, dan bisa diganti per parent category lewat `owner_fee_percent` di kategori.
|
||||||
|
- **Team** = revenue − SDL.
|
||||||
|
|
||||||
|
Contoh dengan tiga parent category dalam satu minggu:
|
||||||
|
|
||||||
|
| Parent category | `is_team` | Fee owner | Revenue | SDL | Team |
|
||||||
|
| --- | --- | --- | --- | --- | --- |
|
||||||
|
| Food | `true` | 20% (default) | 1.000.000 | 200.000 | 800.000 |
|
||||||
|
| Drink | `true` | 35% | 2.000.000 | 700.000 | 1.300.000 |
|
||||||
|
| Merchandise | `false` | - | 500.000 | tidak dihitung | tidak dihitung |
|
||||||
|
| **Budget minggu ini** | | | **3.000.000** | **900.000** | **2.100.000** |
|
||||||
|
|
||||||
|
### Perubahan field
|
||||||
|
|
||||||
|
| Field | Sebelum | Sesudah |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| `data[]` | semua parent category | hanya parent category team |
|
||||||
|
| `budget.percentages.purchase` | `60` | dihapus |
|
||||||
|
| `budget.percentages.owner` | `20`, atau fee parent itu di endpoint detail | tidak berubah |
|
||||||
|
| `budget.percentages.team` | `20` | `100 − owner`: `80` di list, `100 − fee parent` di detail |
|
||||||
|
| `limit_purchase` di `budget.total`, `budget.weekly[]`, `budget.monthly[]` | 60% revenue | dihapus |
|
||||||
|
| `limit_team` di tempat yang sama | 20% revenue | `revenue − sdl` |
|
||||||
|
| `revenue` dan `sdl` di `budget` | semua parent category | hanya parent category team |
|
||||||
|
|
||||||
|
Di endpoint list, `budget.percentages` selalu berisi default `20` dan `80`, walaupun ada parent dengan fee berbeda. Angka `sdl` dan `limit_team` dihitung per parent dengan fee masing-masing, jadi `limit_team / revenue` bisa tidak persis 80%. Tampilkan angka rupiah dari response, jangan dihitung ulang dari persentase.
|
||||||
|
|
||||||
|
Baris di `data[]` membawa `sdl` tapi tidak membawa porsi team. Kalau porsi team per parent perlu ditampilkan, hitung dari `total_revenue − sdl`.
|
||||||
|
|
||||||
|
Contoh response list, dipotong:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"success": true,
|
||||||
|
"data": {
|
||||||
|
"date_from": "2026-09-28T00:00:00+07:00",
|
||||||
|
"date_to": "2026-10-04T23:59:59.999999999+07:00",
|
||||||
|
"data": [
|
||||||
|
{
|
||||||
|
"parent_category_id": "<uuid>",
|
||||||
|
"parent_category_name": "Drink",
|
||||||
|
"owner_fee_percent": 35,
|
||||||
|
"sdl": 700000,
|
||||||
|
"total_revenue": 2000000
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"parent_category_id": "<uuid>",
|
||||||
|
"parent_category_name": "Food",
|
||||||
|
"owner_fee_percent": 20,
|
||||||
|
"sdl": 200000,
|
||||||
|
"total_revenue": 1000000
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"budget": {
|
||||||
|
"percentages": { "owner": 20, "team": 80 },
|
||||||
|
"cut_off_from": "2026-09-28T00:00:00+07:00",
|
||||||
|
"cut_off_to": "2026-10-04T23:59:59.999999999+07:00",
|
||||||
|
"total": {
|
||||||
|
"period_start": "2026-09-28T00:00:00+07:00",
|
||||||
|
"period_end": "2026-10-04T23:59:59.999999999+07:00",
|
||||||
|
"revenue": 3000000,
|
||||||
|
"order_count": 4,
|
||||||
|
"sdl": 900000,
|
||||||
|
"limit_team": 2100000
|
||||||
|
},
|
||||||
|
"weekly": [
|
||||||
|
{
|
||||||
|
"period_start": "2026-09-28T00:00:00+07:00",
|
||||||
|
"period_end": "2026-10-04T23:59:59.999999999+07:00",
|
||||||
|
"revenue": 3000000,
|
||||||
|
"order_count": 4,
|
||||||
|
"sdl": 900000,
|
||||||
|
"limit_team": 2100000
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"monthly": [
|
||||||
|
{
|
||||||
|
"month": "2026-09",
|
||||||
|
"week_count": 1,
|
||||||
|
"period_start": "2026-09-28T00:00:00+07:00",
|
||||||
|
"period_end": "2026-10-04T23:59:59.999999999+07:00",
|
||||||
|
"revenue": 3000000,
|
||||||
|
"order_count": 4,
|
||||||
|
"sdl": 900000,
|
||||||
|
"limit_team": 2100000
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"errors": null
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Di endpoint detail, `budget` bentuknya sama, tapi `percentages` memakai fee parent itu, misalnya `{ "owner": 35, "team": 65 }` untuk Drink.
|
||||||
|
|
||||||
|
### Detail kategori non-team
|
||||||
|
|
||||||
|
Detail untuk parent category non-team ditolak dengan HTTP status 500:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"success": false,
|
||||||
|
"data": null,
|
||||||
|
"errors": [
|
||||||
|
{
|
||||||
|
"code": "internal_error",
|
||||||
|
"entity": "AnalyticsHandler::GetParentCategoryAnalyticsDetail",
|
||||||
|
"cause": "failed to get parent category analytics detail: failed to get parent category analytics detail: category Merchandise is not a team"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Ini bisa terjadi kalau user membuka link lama atau bookmark ke parent yang baru dimatikan. Cocokkan dengan teks `is not a team` di `cause`, lalu arahkan user kembali ke list.
|
||||||
|
|
||||||
|
## Migrasi client
|
||||||
|
|
||||||
|
### Laporan profit sharing
|
||||||
|
|
||||||
|
1. Ganti path ke `/api/v1/analytics/profit-sharing`. Selama backend lama masih jalan, path baru mengembalikan 404. Kalau dapat 404, panggil path lama `/api/v1/analytics/parent-categories`, supaya client baru bisa dirilis sebelum backend.
|
||||||
|
2. Hapus tampilan limit purchase dan persentase purchase. Jangan menganggap `limit_purchase` atau `percentages.purchase` selalu ada.
|
||||||
|
3. Tampilkan dua porsi dengan label "SDL / Fee owner" dan "Team", ambil angkanya dari `sdl` dan `limit_team`.
|
||||||
|
4. Kalau detail ditolak dengan `is not a team`, arahkan kembali ke list.
|
||||||
|
|
||||||
|
Selama fallback ke backend lama, `limit_team` masih berisi 20% revenue. Angkanya baru jadi `revenue − sdl` setelah backend baru dirilis.
|
||||||
|
|
||||||
|
### Form kategori
|
||||||
|
|
||||||
|
1. Tambah toggle `is_team` untuk parent category, misalnya berlabel "Ikut profit sharing (team)". Untuk kategori baru, toggle menyala secara default.
|
||||||
|
2. Saat membuka form edit, isi toggle dari `is_team`. Selama backend lama masih jalan, field ini tidak ada di response, jadi anggap `true`.
|
||||||
|
3. Saat admin mematikan toggle, tampilkan konfirmasi bahwa kategori itu tidak akan muncul di pilihan team dan di laporan profit sharing, termasuk untuk periode lampau.
|
||||||
|
4. Di daftar kategori, beri penanda untuk parent category dengan `is_team: false`.
|
||||||
|
|
||||||
|
Backend lama mengabaikan `is_team` di request, jadi toggle bisa dirilis lebih dulu, tapi belum berpengaruh sampai backend baru jalan. Pengecualiannya update yang hanya berisi `is_team`: backend lama menolaknya dengan error code `303` dan pesan `at least one field must be provided for update`. Selama masa transisi, kirim `is_team` bersama field form lainnya.
|
||||||
|
|
||||||
|
## Database dan urutan rilis
|
||||||
|
|
||||||
|
Migration `000101_add_is_team_to_categories` menambah kolom `categories.is_team` (`BOOLEAN NOT NULL DEFAULT TRUE`). Semua kategori yang ada otomatis bernilai `true`. Migration ini hanya menambah kolom, jadi backend lama tetap jalan normal setelahnya.
|
||||||
|
|
||||||
|
Urutan rilis:
|
||||||
|
|
||||||
|
1. Rilis client baru: path profit sharing dengan fallback ke path lama, tanpa porsi purchase, dan dengan toggle `is_team`. Untuk app mobile, pastikan versi baru sudah dipakai sebagian besar user sebelum langkah 3, karena versi lama yang memanggil `/parent-categories` mendapat 404 setelah itu.
|
||||||
|
2. Jalankan migration `000101`.
|
||||||
|
3. Deploy backend baru.
|
||||||
|
4. Hapus fallback path lama di client.
|
||||||
|
5. Admin mematikan `is_team` di parent category yang bukan team.
|
||||||
|
|
||||||
|
Rollback: deploy backend lama, lalu jalankan down migration yang menghapus kolom `is_team`. Client dengan fallback tetap jalan di backend lama. Nilai `is_team` yang sudah diatur admin hilang saat kolom dihapus.
|
||||||
|
|
||||||
|
## Checklist
|
||||||
|
|
||||||
|
- [ ] Client baru (fallback path, tanpa porsi purchase, toggle `is_team`) dirilis
|
||||||
|
- [ ] Migration `000101` dan backend baru dirilis di staging
|
||||||
|
- [ ] Uji: parent category yang dimatikan hilang dari `/purchase-orders/teams` dan `/cash-advances/teams`
|
||||||
|
- [ ] Uji: purchase order dan cash advance baru dengan kategori itu ditolak, dan edit purchase order lama tanpa mengganti team tetap berhasil
|
||||||
|
- [ ] Uji: kategori itu hilang dari `/analytics/profit-sharing`, dan detailnya ditolak
|
||||||
|
- [ ] Uji: `limit_team = revenue − sdl`, dan `sdl` mengikuti fee masing-masing parent
|
||||||
|
- [ ] Migration `000101` dan backend baru dirilis di production
|
||||||
|
- [ ] Fallback path lama di client dihapus
|
||||||
|
|
||||||
|
## FAQ
|
||||||
|
|
||||||
|
**Kenapa porsi team jadi 100% − fee owner, bukan tetap 20%?** Porsi purchase sudah tidak ada, jadi seluruh revenue dibagi dua. Owner mengambil fee-nya, dan sisanya untuk team. Kalau fee owner sebuah parent dinaikkan, porsi team parent itu turun sebesar yang sama.
|
||||||
|
|
||||||
|
**Apakah sub-category bisa dijadikan non-team sendiri?** Tidak. Team dan profit sharing dihitung per parent category, jadi semua sub-category ikut status parent-nya.
|
||||||
|
|
||||||
|
**Bagaimana dengan kategori top-level yang tidak punya sub-category?** Kategori itu tetap parent category, jadi `is_team` berlaku untuknya.
|
||||||
@@ -12,20 +12,26 @@ aturan yang tidak tertulis di sini; kalau ada yang kurang jelas, tanyakan dulu.
|
|||||||
| | EnakPoint (`POINT`) | EnakCoin (`COIN`) |
|
| | EnakPoint (`POINT`) | EnakCoin (`COIN`) |
|
||||||
|---|---|---|
|
|---|---|---|
|
||||||
| Didapat dari | Belanja (order lunas), koreksi admin, tukar EnakCoin | Belanja, koreksi admin |
|
| Didapat dari | Belanja (order lunas), koreksi admin, tukar EnakCoin | Belanja, koreksi admin |
|
||||||
| Dipakai untuk | **Membayar order** | **Main game**, ditukar ke EnakPoint |
|
| Dipakai untuk | **Ditukar ke voucher** (tidak bisa membayar order) | **Main game**, ditukar ke EnakPoint |
|
||||||
| Bisa dikirim ke customer lain | Ya | Ya |
|
| Bisa dikirim ke customer lain | Ya | Ya |
|
||||||
| Bisa kedaluwarsa | Ya, bila owner mengaktifkan | Ya, bila owner mengaktifkan |
|
| Bisa kedaluwarsa | Ya, bila owner mengaktifkan | Ya, bila owner mengaktifkan |
|
||||||
|
|
||||||
Tidak ada lagi "token". Semua yang dulu token sekarang EnakCoin, dan endpoint serta
|
Tidak ada lagi "token". Semua yang dulu token sekarang EnakCoin, dan endpoint serta
|
||||||
field bernama token sudah dihapus dari API.
|
field bernama token sudah dihapus dari API.
|
||||||
|
|
||||||
|
> **Perubahan 7 Okt 2026:** bayar dengan EnakPoint (kode bayar di kasir, bayar order
|
||||||
|
> dari app) sudah dihapus dari backend. EnakPoint sekarang hanya bisa ditukar ke
|
||||||
|
> voucher, tidak bisa dipakai sebagai alat bayar dan tidak bisa dicairkan
|
||||||
|
> ([`enakgame-prd.md`](./enakgame-prd.md) §3.2). Jangan membangun layar bayar atau kode
|
||||||
|
> bayar; endpoint dan field yang dihapus ada di §9.
|
||||||
|
|
||||||
### Aturan yang wajib dipatuhi di UI
|
### Aturan yang wajib dipatuhi di UI
|
||||||
|
|
||||||
1. **Semua jumlah bilangan bulat.** Tidak ada desimal pada EnakPoint atau EnakCoin.
|
1. **Semua jumlah bilangan bulat.** Tidak ada desimal pada EnakPoint atau EnakCoin.
|
||||||
2. **Saldo bukan uang.** Nilai rupiah EnakPoint selalu ditulis **"setara potongan
|
2. **Saldo bukan uang.** Nilai rupiah EnakPoint selalu ditulis **"setara potongan
|
||||||
Rp …"**, tidak pernah "saldo Rp …" atau "uang". Tidak ada fitur tarik tunai.
|
Rp …"**, tidak pernah "saldo Rp …" atau "uang". Tidak ada fitur tarik tunai, dan
|
||||||
3. **PIN 6 digit wajib** untuk: membuat kode bayar, tukar
|
EnakPoint tidak bisa dipakai membayar.
|
||||||
EnakCoin, dan transfer. **Main game tidak butuh PIN.** Melihat saldo dan riwayat
|
3. **PIN 6 digit wajib** untuk: tukar EnakCoin dan transfer. **Main game tidak butuh PIN.** Melihat saldo dan riwayat
|
||||||
tidak butuh PIN.
|
tidak butuh PIN.
|
||||||
4. **PIN terpisah dari password login** dan selalu dikirim sebagai **string** (supaya
|
4. **PIN terpisah dari password login** dan selalu dikirim sebagai **string** (supaya
|
||||||
nol di depan tidak hilang). Jangan pernah menyimpan PIN di perangkat, log, atau
|
nol di depan tidak hilang). Jangan pernah menyimpan PIN di perangkat, log, atau
|
||||||
@@ -107,7 +113,6 @@ Endpoint **tukar** dan **transfer** wajib header `Idempotency-Key` (string unik,
|
|||||||
| Saldo akan kedaluwarsa | `GET /customer/wallet/expiring` | – |
|
| Saldo akan kedaluwarsa | `GET /customer/wallet/expiring` | – |
|
||||||
| Daftar outlet | `GET /customer/outlets` | – |
|
| Daftar outlet | `GET /customer/outlets` | – |
|
||||||
| Riwayat order + detail | `GET /customer/orders`, `GET /customer/orders/:id` | – |
|
| Riwayat order + detail | `GET /customer/orders`, `GET /customer/orders/:id` | – |
|
||||||
| Kode bayar (angka + QR) | `POST /customer/wallet/payment-code` | Ya |
|
|
||||||
| Tukar EnakCoin | `GET …/exchange/preview`, `POST /customer/wallet/exchange` | Ya |
|
| Tukar EnakCoin | `GET …/exchange/preview`, `POST /customer/wallet/exchange` | Ya |
|
||||||
| Transfer | `GET …/transfer/recipient`, `POST /customer/wallet/transfer` | Ya |
|
| Transfer | `GET …/transfer/recipient`, `POST /customer/wallet/transfer` | Ya |
|
||||||
| PIN (buat, ganti, lupa) | `/customer/pin/*` | – |
|
| PIN (buat, ganti, lupa) | `/customer/pin/*` | – |
|
||||||
@@ -141,7 +146,7 @@ Tampilkan:
|
|||||||
- Bila `nearest_expiring.point` / `.coin` tidak `null`: banner "{amount} EnakPoint akan
|
- Bila `nearest_expiring.point` / `.coin` tidak `null`: banner "{amount} EnakPoint akan
|
||||||
kedaluwarsa pada {date}" yang membuka layar §4.3.
|
kedaluwarsa pada {date}" yang membuka layar §4.3.
|
||||||
- 5 mutasi terakhir dari `recent_transactions`, dengan tautan "Lihat semua" ke §4.2.
|
- 5 mutasi terakhir dari `recent_transactions`, dengan tautan "Lihat semua" ke §4.2.
|
||||||
- Tombol aksi: Bayar di kasir (§7.1), Tukar EnakCoin (§8.1), Transfer (§8.2), Main game (§9).
|
- Tombol aksi: Tukar EnakCoin (§7.1), Transfer (§7.2), Main game (§8).
|
||||||
|
|
||||||
Muat ulang beranda setelah setiap transaksi dan saat menerima push (§5).
|
Muat ulang beranda setelah setiap transaksi dan saat menerima push (§5).
|
||||||
|
|
||||||
@@ -157,7 +162,7 @@ Query (semua opsional):
|
|||||||
| `page` | `1` | Mulai dari 1 |
|
| `page` | `1` | Mulai dari 1 |
|
||||||
| `limit` | `20` | 1–100, default 20 |
|
| `limit` | `20` | 1–100, default 20 |
|
||||||
| `currency` | `POINT` | `POINT` atau `COIN`; untuk tab EnakPoint / EnakCoin |
|
| `currency` | `POINT` | `POINT` atau `COIN`; untuk tab EnakPoint / EnakCoin |
|
||||||
| `type` | `EARN,PAYMENT` | Satu atau beberapa tipe dipisah koma, untuk filter |
|
| `type` | `EARN,TRANSFER_IN` | Satu atau beberapa tipe dipisah koma, untuk filter |
|
||||||
| `from`, `to` | `2026-09-01` | Tanggal WIB, inklusif |
|
| `from`, `to` | `2026-09-01` | Tanggal WIB, inklusif |
|
||||||
|
|
||||||
```json
|
```json
|
||||||
@@ -196,8 +201,6 @@ Label tipe:
|
|||||||
|---|---|---|
|
|---|---|---|
|
||||||
| `EARN` | Dari belanja | + |
|
| `EARN` | Dari belanja | + |
|
||||||
| `EARN_REVERSAL` | Dibatalkan (order di-void/refund) | − |
|
| `EARN_REVERSAL` | Dibatalkan (order di-void/refund) | − |
|
||||||
| `PAYMENT` | Bayar pesanan | − |
|
|
||||||
| `PAYMENT_REFUND` | Pengembalian pembayaran | + |
|
|
||||||
| `EXCHANGE_OUT` | Ditukar ke EnakPoint | − |
|
| `EXCHANGE_OUT` | Ditukar ke EnakPoint | − |
|
||||||
| `EXCHANGE_IN` | Hasil tukar EnakCoin | + |
|
| `EXCHANGE_IN` | Hasil tukar EnakCoin | + |
|
||||||
| `TRANSFER_OUT` | Transfer keluar | − |
|
| `TRANSFER_OUT` | Transfer keluar | − |
|
||||||
@@ -235,7 +238,6 @@ berdasarkan nama.
|
|||||||
"id": "…",
|
"id": "…",
|
||||||
"name": "Gokuna Kemang",
|
"name": "Gokuna Kemang",
|
||||||
"address": "Jl. Kemang Raya 10",
|
"address": "Jl. Kemang Raya 10",
|
||||||
"accepts_point_payment": true,
|
|
||||||
"earns_points": true,
|
"earns_points": true,
|
||||||
"earns_coins": false
|
"earns_coins": false
|
||||||
}
|
}
|
||||||
@@ -243,8 +245,6 @@ berdasarkan nama.
|
|||||||
```
|
```
|
||||||
|
|
||||||
- `address` bisa `null`.
|
- `address` bisa `null`.
|
||||||
- `accepts_point_payment`: kasir di outlet ini menerima pembayaran EnakPoint. Pakai
|
|
||||||
untuk label "Bisa bayar pakai EnakPoint".
|
|
||||||
- `earns_points` / `earns_coins`: belanja di outlet ini memberi EnakPoint / EnakCoin.
|
- `earns_points` / `earns_coins`: belanja di outlet ini memberi EnakPoint / EnakCoin.
|
||||||
- Belum ada telepon, koordinat, atau jam buka; data itu belum disimpan di backend.
|
- Belum ada telepon, koordinat, atau jam buka; data itu belum disimpan di backend.
|
||||||
|
|
||||||
@@ -318,8 +318,7 @@ hanya masuk ke sini bila kasir mengaitkannya ke customer.
|
|||||||
}
|
}
|
||||||
],
|
],
|
||||||
"payments": [
|
"payments": [
|
||||||
{ "id": "…", "method_name": "EnakPoint", "method_type": "point", "amount": 12500, "status": "completed", "refund_amount": 0, "points_used": 12500, "point_value": 1, "created_at": "…" },
|
{ "id": "…", "method_name": "Cash", "method_type": "cash", "amount": 99000, "status": "completed", "refund_amount": 0, "created_at": "…" }
|
||||||
{ "id": "…", "method_name": "Cash", "method_type": "cash", "amount": 86500, "status": "completed", "refund_amount": 0, "created_at": "…" }
|
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
@@ -327,7 +326,6 @@ hanya masuk ke sini bila kasir mengaitkannya ke customer.
|
|||||||
- Order customer lain atau yang tidak ada → `404`.
|
- Order customer lain atau yang tidak ada → `404`.
|
||||||
- `points_earned` / `coins_earned`: yang didapat dari order ini; 0 bila tidak ada.
|
- `points_earned` / `coins_earned`: yang didapat dari order ini; 0 bila tidak ada.
|
||||||
- Item timbangan membawa `weight` dan `unit_name`; tampilkan "1 × 4,2 ons".
|
- Item timbangan membawa `weight` dan `unit_name`; tampilkan "1 × 4,2 ons".
|
||||||
- Pembayaran EnakPoint membawa `points_used`; tampilkan "EnakPoint 12.500 (Rp 12.500)".
|
|
||||||
- Order yang `is_void` atau `is_refund` tetap tampil, beri label "Dibatalkan" /
|
- Order yang `is_void` atau `is_refund` tetap tampil, beri label "Dibatalkan" /
|
||||||
"Direfund".
|
"Direfund".
|
||||||
|
|
||||||
@@ -405,7 +403,7 @@ Minta OTP lagi terlalu cepat → `429`: tampilkan hitung mundur.
|
|||||||
2. `POST /customer/pin/reset` dengan `{ "otp_token", "otp_code", "pin", "confirm_pin" }`.
|
2. `POST /customer/pin/reset` dengan `{ "otp_token", "otp_code", "pin", "confirm_pin" }`.
|
||||||
|
|
||||||
Reset juga membuka PIN yang terkunci. Setelah reset, **transfer keluar ditahan 24 jam**;
|
Reset juga membuka PIN yang terkunci. Setelah reset, **transfer keluar ditahan 24 jam**;
|
||||||
bayar dan tukar tetap bisa. Beri tahu customer hal ini di layar sukses.
|
tukar tetap bisa. Beri tahu customer hal ini di layar sukses.
|
||||||
|
|
||||||
### 6.5 Menangani error PIN
|
### 6.5 Menangani error PIN
|
||||||
|
|
||||||
@@ -428,41 +426,9 @@ ditolak. Penghitung ada di server, jadi jangan membuat penghitung sendiri di app
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 7. Membayar dengan EnakPoint
|
## 7. Tukar dan transfer
|
||||||
|
|
||||||
App customer tidak membuat atau membayar order; order hanya bisa dilihat (§4.5).
|
### 7.1 Tukar EnakCoin → EnakPoint
|
||||||
EnakPoint hanya dipakai membayar di kasir, lewat kode bayar dari app. Jangan membangun
|
|
||||||
layar checkout atau memanggil `POST /customer/orders/:id/pay-with-points`.
|
|
||||||
|
|
||||||
### 7.1 Di kasir — kode bayar
|
|
||||||
|
|
||||||
Customer tidak pernah mengetik PIN di mesin kasir. Alurnya:
|
|
||||||
|
|
||||||
1. Customer membuka "Bayar di kasir" dan memasukkan PIN.
|
|
||||||
2. `POST /api/v1/customer/wallet/payment-code` dengan `{ "pin": "482913" }`:
|
|
||||||
|
|
||||||
```json
|
|
||||||
{ "code": "482913", "qr_payload": "enakpoint:482913", "expires_at": "2026-09-30T05:02:00Z" }
|
|
||||||
```
|
|
||||||
|
|
||||||
3. Tampilkan `code` besar (angka) **dan** QR dari `qr_payload` (string apa adanya).
|
|
||||||
4. Tampilkan hitung mundur ke `expires_at` (2 menit). Setelah habis, sembunyikan kode
|
|
||||||
dan tampilkan tombol "Buat kode baru".
|
|
||||||
5. Kasir memindai/mengetik kode dan memilih jumlah EnakPoint. App tidak menerima
|
|
||||||
callback; setelah customer kembali ke beranda, muat ulang saldo.
|
|
||||||
|
|
||||||
Kode sekali pakai. Membuat kode baru membatalkan kode lama.
|
|
||||||
|
|
||||||
### 7.2 Refund
|
|
||||||
|
|
||||||
Bila order yang dibayar EnakPoint dibatalkan atau direfund, EnakPoint kembali sebagai
|
|
||||||
EnakPoint (tidak pernah tunai) dan muncul di riwayat sebagai `PAYMENT_REFUND`.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 8. Tukar dan transfer
|
|
||||||
|
|
||||||
### 8.1 Tukar EnakCoin → EnakPoint
|
|
||||||
|
|
||||||
1. Customer mengetik jumlah EnakCoin. Panggil preview (debounce saat mengetik):
|
1. Customer mengetik jumlah EnakCoin. Panggil preview (debounce saat mengetik):
|
||||||
|
|
||||||
@@ -503,7 +469,7 @@ EnakPoint (tidak pernah tunai) dan muncul di riwayat sebagai `PAYMENT_REFUND`.
|
|||||||
3. Layar sukses: saldo baru, dan bila `lots[].expires_at` ada, "EnakPoint ini berlaku
|
3. Layar sukses: saldo baru, dan bila `lots[].expires_at` ada, "EnakPoint ini berlaku
|
||||||
sampai {tanggal}".
|
sampai {tanggal}".
|
||||||
|
|
||||||
### 8.2 Transfer
|
### 7.2 Transfer
|
||||||
|
|
||||||
1. Pilih mata uang (EnakPoint / EnakCoin), isi nomor HP penerima dan jumlah.
|
1. Pilih mata uang (EnakPoint / EnakCoin), isi nomor HP penerima dan jumlah.
|
||||||
2. Cek penerima:
|
2. Cek penerima:
|
||||||
@@ -556,7 +522,7 @@ Penerima mendapat push `WALLET_TRANSFER_IN`.
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 9. Game (memakai EnakCoin)
|
## 8. Game (memakai EnakCoin)
|
||||||
|
|
||||||
`POST /api/v1/customer/spin` dengan `{ "spin_id": "<id game>" }`. Tanpa PIN.
|
`POST /api/v1/customer/spin` dengan `{ "spin_id": "<id game>" }`. Tanpa PIN.
|
||||||
|
|
||||||
@@ -577,7 +543,7 @@ Penerima mendapat push `WALLET_TRANSFER_IN`.
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 10. Yang sudah dihapus / deprecated
|
## 9. Yang sudah dihapus / deprecated
|
||||||
|
|
||||||
Sudah **dihapus** dari API (jangan dipanggil, akan error / tidak ada):
|
Sudah **dihapus** dari API (jangan dipanggil, akan error / tidak ada):
|
||||||
|
|
||||||
@@ -586,6 +552,12 @@ Sudah **dihapus** dari API (jangan dipanggil, akan error / tidak ada):
|
|||||||
| `GET /customer/tokens` | `GET /customer/wallet` → `coin_balance` |
|
| `GET /customer/tokens` | `GET /customer/wallet` → `coin_balance` |
|
||||||
| `total_tokens`, `tokens_history` | `coin_balance`, `GET /customer/wallet/transactions?currency=COIN` |
|
| `total_tokens`, `tokens_history` | `coin_balance`, `GET /customer/wallet/transactions?currency=COIN` |
|
||||||
| `token_used`, `tokens_remaining` di response game | `coins_used`, `coins_remaining` |
|
| `token_used`, `tokens_remaining` di response game | `coins_used`, `coins_remaining` |
|
||||||
|
| `POST /customer/wallet/payment-code` | Tidak ada; EnakPoint tidak bisa untuk bayar |
|
||||||
|
| `POST /customer/orders/:id/pay-with-points` | Tidak ada; EnakPoint tidak bisa untuk bayar |
|
||||||
|
| `GET /orders/:id/point-payment/preview` (POS) | Tidak ada; EnakPoint tidak bisa untuk bayar |
|
||||||
|
| `accepts_point_payment` di `GET /customer/outlets` | – |
|
||||||
|
| `points_used`, `point_value` di `payments` pada `GET /customer/orders/:id` | – |
|
||||||
|
| Tipe mutasi `PAYMENT`, `PAYMENT_REFUND` di riwayat | Tidak ditulis lagi |
|
||||||
|
|
||||||
Masih ada tapi **deprecated** (akan dihapus, jangan dipakai di kode baru):
|
Masih ada tapi **deprecated** (akan dihapus, jangan dipakai di kode baru):
|
||||||
|
|
||||||
@@ -596,7 +568,7 @@ Masih ada tapi **deprecated** (akan dihapus, jangan dipakai di kode baru):
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 11. Checklist selesai
|
## 10. Checklist selesai
|
||||||
|
|
||||||
- [ ] Beranda menampilkan saldo EnakPoint ("setara potongan Rp …"), EnakCoin, dan banner kedaluwarsa terdekat.
|
- [ ] Beranda menampilkan saldo EnakPoint ("setara potongan Rp …"), EnakCoin, dan banner kedaluwarsa terdekat.
|
||||||
- [ ] Riwayat dengan tab per mata uang, filter tipe/tanggal, infinite scroll, label tipe sesuai §4.2.
|
- [ ] Riwayat dengan tab per mata uang, filter tipe/tanggal, infinite scroll, label tipe sesuai §4.2.
|
||||||
@@ -605,10 +577,9 @@ Masih ada tapi **deprecated** (akan dihapus, jangan dipakai di kode baru):
|
|||||||
- [ ] Penanganan tap untuk keempat tipe push.
|
- [ ] Penanganan tap untuk keempat tipe push.
|
||||||
- [ ] PIN diminta hanya saat aksi yang membutuhkan; alur buat, ganti, dan lupa PIN lewat OTP.
|
- [ ] PIN diminta hanya saat aksi yang membutuhkan; alur buat, ganti, dan lupa PIN lewat OTP.
|
||||||
- [ ] Keempat error PIN ditangani di semua layar yang meminta PIN.
|
- [ ] Keempat error PIN ditangani di semua layar yang meminta PIN.
|
||||||
- [ ] Kode bayar: angka + QR, hitung mundur 2 menit, tombol buat ulang.
|
|
||||||
- [ ] Tukar dengan preview, kelipatan kurs, konfirmasi, `Idempotency-Key`, retry dengan key sama.
|
- [ ] Tukar dengan preview, kelipatan kurs, konfirmasi, `Idempotency-Key`, retry dengan key sama.
|
||||||
- [ ] Transfer dengan cek penerima tersamar, konfirmasi, `Idempotency-Key`, retry dengan key sama.
|
- [ ] Transfer dengan cek penerima tersamar, konfirmasi, `Idempotency-Key`, retry dengan key sama.
|
||||||
- [ ] Game memakai `coins_used` / `coins_remaining` dan menampilkan biaya per game.
|
- [ ] Game memakai `coins_used` / `coins_remaining` dan menampilkan biaya per game.
|
||||||
- [ ] Riwayat order dengan pagination dan layar detail (item, pembayaran, EnakPoint/EnakCoin yang didapat).
|
- [ ] Riwayat order dengan pagination dan layar detail (item, pembayaran, EnakPoint/EnakCoin yang didapat).
|
||||||
- [ ] Tidak ada pemakaian endpoint atau field di §10.
|
- [ ] Tidak ada pemakaian endpoint atau field di §9.
|
||||||
- [ ] PIN tidak pernah disimpan, di-log, atau dikirim ke analytics.
|
- [ ] PIN tidak pernah disimpan, di-log, atau dikirim ke analytics.
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,981 @@
|
|||||||
|
# RFC: EnakGame — Game Session, Reward, Voucher & Budget
|
||||||
|
|
||||||
|
**Status:** Draft
|
||||||
|
**Tanggal:** 2026-10-07
|
||||||
|
**PRD:** [enakgame-prd.md](enakgame-prd.md)
|
||||||
|
**Scope:** Game catalog, game session + entry cost + refund, Reward Engine, Economy Guard,
|
||||||
|
voucher & redemption, budget & Budget Controller (recommendation mode), audit
|
||||||
|
**Out of scope:** Mission, leaderboard, reward `TIERED`, Budget Controller automatic mode
|
||||||
|
(lihat §16)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. Ringkasan
|
||||||
|
|
||||||
|
EnakGame dibangun **di atas wallet EnakPoint/EnakCoin yang sudah ada**
|
||||||
|
([prd-point-coin.md](prd-point-coin.md)), bukan sebagai sistem saldo baru. Ledger, lot,
|
||||||
|
kedaluwarsa, idempotency, exchange Coin → Point, dan PIN sudah tersedia dan sudah
|
||||||
|
teruji. Yang dibangun baru:
|
||||||
|
|
||||||
|
| Komponen PRD | Kondisi sekarang | Rencana |
|
||||||
|
|---|---|---|
|
||||||
|
| Game Management (§9) | `games` ada, tanpa `organization_id`, tanpa status/slug/URL | **Extend** `games` |
|
||||||
|
| Game Session (§10) | Tidak ada. `game_plays` adalah main-instan tanpa session | **Baru**: `game_sessions` |
|
||||||
|
| Entry cost (§10.1) | Ada (`GAME_SPEND`, `metadata.coin_cost`) tapi tanpa idempotency | **Reuse** `GAME_SPEND`, ref baru `GAME_SESSION` |
|
||||||
|
| Refund entry cost (§10.2) | Tidak ada | **Baru**: tipe ledger `GAME_SPEND_REFUND` + job |
|
||||||
|
| Reward Engine (§11–13) | Tidak ada. Hadiah spin tidak memberi apa pun | **Baru**: `game_reward_configs` (versioned) |
|
||||||
|
| Event / campaign (§14–16) | Tidak ada. `campaigns` ada tapi tidak pernah dieksekusi | **Baru**: `game_events`, masing-masing dengan budget sendiri |
|
||||||
|
| Economy Guard & Limits (§17, §35) | Tidak ada | **Baru**: counter harian + settings organisasi |
|
||||||
|
| Coin Wallet & Ledger (§18–20) | **Ada lengkap** | **Reuse**, tambah 3 tipe ledger |
|
||||||
|
| Coin → Point, expiry | **Ada** (F4, F12) | **Reuse** tanpa perubahan |
|
||||||
|
| Voucher & Redemption (§21–28) | `rewards` ada tanpa org, tanpa redemption, tanpa kode | **Baru**: `vouchers`, `voucher_codes`, `voucher_redemptions` |
|
||||||
|
| Budget & Controller (§5–8, §29–34) | Tidak ada | **Baru**: `game_budgets` + atribusi cost per lot |
|
||||||
|
| Audit Log (§37) | Tidak ada yang generik | **Baru**: `audit_logs` |
|
||||||
|
|
||||||
|
Keputusan paling penting ada di §3, terutama **D5**: realized cost voucher diatribusikan ke
|
||||||
|
budget dengan menelusuri lot Point yang dipakai sampai ke asalnya.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. Kondisi Sekarang
|
||||||
|
|
||||||
|
Temuan yang memengaruhi desain:
|
||||||
|
|
||||||
|
1. **Tabel game, reward, campaign, dan tier tidak punya `organization_id`.** Semua query
|
||||||
|
membaca semua tenant. Tabel wallet (`000090`) sudah punya.
|
||||||
|
2. **Main game sekarang tidak punya session.** `GamePlayProcessor.PlayGame`
|
||||||
|
(`processor/game_play_processor.go:141`) memotong Coin, memilih hadiah, dan mencatat
|
||||||
|
`game_plays` dalam satu request.
|
||||||
|
3. **Hadiah game tidak memberi apa pun.** Prize hanya tercatat sebagai
|
||||||
|
`game_plays.prize_id` dan teks deskripsi ledger. Tidak ada kredit Coin/Point, tidak ada
|
||||||
|
voucher.
|
||||||
|
4. **`GAME_SPEND` tanpa idempotency key** (`game_play_processor.go:186`). Tombol main yang
|
||||||
|
ditekan dua kali memotong Coin dua kali.
|
||||||
|
5. **Tidak ada alur penukaran.** Tipe ledger `REWARD_REDEEM` dan ref
|
||||||
|
`REWARD_REDEMPTION` sudah ada di `walletTypeRules` dan CHECK database, tapi belum pernah
|
||||||
|
dipakai.
|
||||||
|
6. **Wallet sudah mendukung semua kebutuhan dasar:** `Credit` / `Debit` dengan lock per
|
||||||
|
customer, lot FIFO berdasarkan kedaluwarsa, `idempotency_key` UNIQUE dengan replay,
|
||||||
|
`origin_lot_id` untuk menelusuri asal saldo, `RefundExpiry` untuk refund.
|
||||||
|
7. **Tidak ada scheduler library.** Semua job adalah goroutine `time.NewTicker` di
|
||||||
|
`app/app.go`, aman multi-instance lewat lock wallet dan idempotency key.
|
||||||
|
8. **`TxManager.WithTransaction` tidak me-reuse transaksi di context.** Pemanggilan
|
||||||
|
bersarang membuka transaksi baru yang independen.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. Keputusan Inti
|
||||||
|
|
||||||
|
**D1 — EnakGame memakai wallet yang sudah ada.**
|
||||||
|
Entry cost, reward, refund, dan redemption semuanya lewat `WalletProcessor.Credit` /
|
||||||
|
`Debit`. Tidak ada tabel saldo baru. Konsekuensinya, aturan K5 (setiap mutasi punya asal
|
||||||
|
dan tujuan), K6 (bilangan bulat), dan K9 (lot FIFO) otomatis berlaku untuk EnakGame.
|
||||||
|
|
||||||
|
**D2 — `games` di-extend, game lama diarsipkan, `game_plays` tidak dipakai EnakGame.**
|
||||||
|
`games` sudah dibaca customer app. Kolom yang kurang ditambahkan (§5.1). Session baru masuk
|
||||||
|
ke `game_sessions`. Game lama (spin, ferris wheel) **dihapus dari sisi produk** dan spin
|
||||||
|
dibangun ulang sebagai game EnakGame. Secara data, baris lama diarsipkan, bukan di-`DELETE`
|
||||||
|
(§14).
|
||||||
|
|
||||||
|
**D3 — Coin dipotong saat session dibuat, dalam satu transaksi.**
|
||||||
|
Sesuai PRD §10.1. Idempotency key dari header `Idempotency-Key`, mengikuti pola exchange.
|
||||||
|
|
||||||
|
**D4 — Session punya state machine yang ditegakkan dengan UPDATE bersyarat.**
|
||||||
|
`STARTED → COMPLETED | REFUNDED | EXPIRED`. Setiap transisi adalah
|
||||||
|
`UPDATE ... WHERE id = ? AND status = 'STARTED'`. Complete dan refund tidak mungkin
|
||||||
|
sama-sama berhasil untuk satu session, karena hanya satu yang mendapat baris ter-update.
|
||||||
|
|
||||||
|
**D5 — Realized cost diatribusikan ke budget lewat lot.**
|
||||||
|
Point yang dipakai menukar voucher ditelusuri lewat `wallet_lot_allocations` →
|
||||||
|
`wallet_lots.origin_lot_id` sampai ke lot pertama. Lot pertama menunjuk mutasi asalnya:
|
||||||
|
`GAME_REWARD` (EnakGame, dengan budget yang tercatat), atau `EARN` / `ADJUSTMENT` /
|
||||||
|
`MIGRATION` (bukan dari game). Hasilnya dibekukan per redemption di
|
||||||
|
`voucher_redemption_costs`.
|
||||||
|
|
||||||
|
**Hanya bagian yang berasal dari `GAME_REWARD` yang dihitung ke budget.** Point dari
|
||||||
|
belanja (`EARN`) dan sumber lain tetap dicatat atribusinya (dengan `budget_id` kosong)
|
||||||
|
untuk reporting, tetapi tidak mengurangi budget mana pun.
|
||||||
|
|
||||||
|
Alasannya: Point bersifat fungible. Customer bisa memegang Point dari belanja, dari
|
||||||
|
exchange Coin hasil game, dan dari transfer sekaligus. Tanpa penelusuran lot, sistem tidak
|
||||||
|
bisa tahu berapa bagian voucher yang benar-benar dibiayai budget EnakGame atau budget
|
||||||
|
event tertentu. Lot sudah menyimpan jejak ini sejak PRD point-coin (Q9), jadi tidak ada
|
||||||
|
perubahan struktur wallet.
|
||||||
|
|
||||||
|
**D6 — Reward per budget dicatat sebagai baris ledger terpisah.**
|
||||||
|
Satu session bisa menghasilkan reward dari budget global (reward normal) dan dari budget
|
||||||
|
event (tambahan dari multiplier/bonus event). Masing-masing menjadi satu baris
|
||||||
|
`GAME_REWARD` dengan lot sendiri, dan `game_session_rewards` mencatat budget tiap baris.
|
||||||
|
Ini yang membuat D5 bisa membedakan budget global dan event tanpa menambah kolom di
|
||||||
|
`wallet_lots`.
|
||||||
|
|
||||||
|
Dalam RFC ini **event = campaign**: istilah yang sama untuk hal yang sama.
|
||||||
|
|
||||||
|
**D7 — Reward configuration immutable.**
|
||||||
|
Baris `game_reward_configs` tidak pernah di-UPDATE kecuali kolom `status`. Perubahan
|
||||||
|
reward = baris baru dengan `version + 1`. Session menyimpan `reward_config_id` saat
|
||||||
|
**Start Game**, sehingga perubahan config tidak memengaruhi session yang sedang berjalan.
|
||||||
|
|
||||||
|
**D8 — Semua tabel baru punya `organization_id`.**
|
||||||
|
Satu organisasi = satu ekonomi EnakGame (budget, limit, voucher, game). Org customer dibaca
|
||||||
|
dari tabel `customers` seperti flow wallet sekarang, karena JWT customer tidak membawa org.
|
||||||
|
Game, voucher, dan event milik org lain ditolak.
|
||||||
|
|
||||||
|
**D9 — Budget Controller v1 hanya recommendation mode.**
|
||||||
|
Sesuai default PRD §33. Automatic mode di luar scope RFC ini.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. Prinsip
|
||||||
|
|
||||||
|
**P1 — Backend satu-satunya penentu reward.** Client hanya mengirim `score`, `outcome`, dan
|
||||||
|
data hasil. Request yang membawa angka reward diabaikan.
|
||||||
|
|
||||||
|
**P2 — Setiap mutasi uang punya idempotency key deterministik.** Diturunkan dari id
|
||||||
|
session/redemption, bukan dari waktu. Retry selalu menghasilkan key yang sama.
|
||||||
|
|
||||||
|
**P3 — Snapshot, bukan join.** Entry cost, reward config, face value voucher, dan point cost
|
||||||
|
dibekukan di baris transaksi saat terjadi, sama seperti `unit_price` di `order_items`.
|
||||||
|
|
||||||
|
**P4 — Lock wallet customer selalu diambil lebih dulu.** Semua alur (start, complete,
|
||||||
|
refund, redeem) mengunci `customer_wallets` sebelum menyentuh tabel lain, supaya urutan
|
||||||
|
lock konsisten dan tidak deadlock.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. Model Data
|
||||||
|
|
||||||
|
Semua migrasi mengikuti golang-migrate di `migrations/`, nomor lanjut dari `000101`.
|
||||||
|
|
||||||
|
### 5.1 `games` (extend)
|
||||||
|
|
||||||
|
```sql
|
||||||
|
ALTER TABLE games
|
||||||
|
ADD COLUMN organization_id UUID,
|
||||||
|
ADD COLUMN slug VARCHAR(100),
|
||||||
|
ADD COLUMN description TEXT,
|
||||||
|
ADD COLUMN thumbnail_url VARCHAR(500),
|
||||||
|
ADD COLUMN game_url VARCHAR(500),
|
||||||
|
ADD COLUMN version VARCHAR(50),
|
||||||
|
ADD COLUMN status VARCHAR(20) NOT NULL DEFAULT 'ACTIVE'
|
||||||
|
CHECK (status IN ('DRAFT', 'ACTIVE', 'INACTIVE', 'ARCHIVED')),
|
||||||
|
ADD COLUMN entry_cost BIGINT,
|
||||||
|
ADD COLUMN session_ttl_seconds INT NOT NULL DEFAULT 600
|
||||||
|
CHECK (session_ttl_seconds > 0),
|
||||||
|
-- Batas validasi hasil: max_score, min_duration_seconds, max_score_per_second, outcome
|
||||||
|
-- yang valid. Dibaca Result Validator (§7.2).
|
||||||
|
ADD COLUMN result_rules JSONB NOT NULL DEFAULT '{}';
|
||||||
|
|
||||||
|
-- Game lama dihapus dari produk: diarsipkan, tidak di-DELETE (§14).
|
||||||
|
UPDATE games SET status = 'ARCHIVED', is_active = FALSE,
|
||||||
|
entry_cost = COALESCE((metadata->>'coin_cost')::bigint, 1);
|
||||||
|
|
||||||
|
ALTER TABLE games
|
||||||
|
ALTER COLUMN entry_cost SET NOT NULL,
|
||||||
|
ADD CONSTRAINT chk_games_entry_cost CHECK (entry_cost >= 1), -- PRD §10.1: tidak ada game gratis
|
||||||
|
-- Semua game EnakGame wajib punya org dan slug. Hanya arsip lama yang boleh kosong.
|
||||||
|
ADD CONSTRAINT chk_games_enakgame_identity CHECK (
|
||||||
|
status = 'ARCHIVED' OR (organization_id IS NOT NULL AND slug IS NOT NULL));
|
||||||
|
|
||||||
|
CREATE UNIQUE INDEX uq_games_org_slug ON games(organization_id, slug) WHERE slug IS NOT NULL;
|
||||||
|
CREATE INDEX idx_games_org_status ON games(organization_id, status);
|
||||||
|
```
|
||||||
|
|
||||||
|
**Catatan:**
|
||||||
|
|
||||||
|
- Baris lama tidak punya org, sehingga tidak bisa dijadikan game EnakGame. Mereka
|
||||||
|
diarsipkan dan tidak pernah tampil di endpoint EnakGame. Game baru (termasuk spin yang
|
||||||
|
dibangun ulang) dibuat sebagai baris baru dengan org.
|
||||||
|
- `is_active` tidak dipakai EnakGame dan dihapus bersama alur lama (§14). EnakGame hanya
|
||||||
|
membaca `status`.
|
||||||
|
|
||||||
|
### 5.2 `game_reward_configs`
|
||||||
|
|
||||||
|
```sql
|
||||||
|
CREATE TABLE game_reward_configs (
|
||||||
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
organization_id UUID NOT NULL,
|
||||||
|
game_id UUID NOT NULL REFERENCES games(id) ON DELETE RESTRICT,
|
||||||
|
version INT NOT NULL,
|
||||||
|
reward_type VARCHAR(30) NOT NULL
|
||||||
|
CHECK (reward_type IN ('FIXED', 'SCORE_BASED', 'OUTCOME_BASED', 'PROBABILITY')),
|
||||||
|
rules JSONB NOT NULL, -- bentuk per tipe di §8
|
||||||
|
max_reward BIGINT NOT NULL CHECK (max_reward >= 0),
|
||||||
|
status VARCHAR(20) NOT NULL DEFAULT 'DRAFT'
|
||||||
|
CHECK (status IN ('DRAFT', 'ACTIVE', 'RETIRED')),
|
||||||
|
effective_at TIMESTAMPTZ,
|
||||||
|
created_by UUID NOT NULL,
|
||||||
|
reason VARCHAR(255),
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
|
||||||
|
UNIQUE (game_id, version)
|
||||||
|
);
|
||||||
|
|
||||||
|
-- Satu config aktif per game.
|
||||||
|
CREATE UNIQUE INDEX uq_game_reward_configs_active
|
||||||
|
ON game_reward_configs(game_id) WHERE status = 'ACTIVE';
|
||||||
|
```
|
||||||
|
|
||||||
|
`MULTIPLIER` tidak menjadi `reward_type` karena di PRD ia adalah modifier di atas base
|
||||||
|
reward, bukan cara menghitung base. Multiplier dan bonus hidup di `game_events` (§5.5).
|
||||||
|
|
||||||
|
### 5.3 `game_sessions`
|
||||||
|
|
||||||
|
```sql
|
||||||
|
CREATE TABLE game_sessions (
|
||||||
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
organization_id UUID NOT NULL,
|
||||||
|
customer_id UUID NOT NULL REFERENCES customers(id) ON DELETE RESTRICT,
|
||||||
|
game_id UUID NOT NULL REFERENCES games(id) ON DELETE RESTRICT,
|
||||||
|
reward_config_id UUID NOT NULL REFERENCES game_reward_configs(id), -- snapshot (D7)
|
||||||
|
entry_cost BIGINT NOT NULL CHECK (entry_cost >= 1), -- snapshot (P3)
|
||||||
|
|
||||||
|
status VARCHAR(20) NOT NULL DEFAULT 'STARTED'
|
||||||
|
CHECK (status IN ('STARTED', 'COMPLETED', 'REFUNDED', 'EXPIRED')),
|
||||||
|
started_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
expires_at TIMESTAMPTZ NOT NULL,
|
||||||
|
ended_at TIMESTAMPTZ,
|
||||||
|
|
||||||
|
-- Hasil dari client (P1: hanya data, tanpa angka reward).
|
||||||
|
result JSONB,
|
||||||
|
-- Validasi & perhitungan: base, modifier event, cap guard, alasan penolakan, roll RNG.
|
||||||
|
reward_breakdown JSONB,
|
||||||
|
reward_total BIGINT NOT NULL DEFAULT 0 CHECK (reward_total >= 0),
|
||||||
|
flagged BOOLEAN NOT NULL DEFAULT FALSE,
|
||||||
|
|
||||||
|
spend_transaction_id UUID NOT NULL REFERENCES wallet_transactions(id),
|
||||||
|
refund_transaction_id UUID REFERENCES wallet_transactions(id),
|
||||||
|
refund_reason VARCHAR(30)
|
||||||
|
CHECK (refund_reason IN ('SYSTEM_ERROR', 'GAME_DEACTIVATED')),
|
||||||
|
-- Diisi saat complete gagal karena error sistem (5xx), di transaksi terpisah (§7.3).
|
||||||
|
completion_failed_at TIMESTAMPTZ,
|
||||||
|
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
|
||||||
|
CONSTRAINT chk_game_sessions_refund CHECK (
|
||||||
|
(status = 'REFUNDED') = (refund_transaction_id IS NOT NULL AND refund_reason IS NOT NULL))
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX idx_game_sessions_customer ON game_sessions(customer_id, started_at DESC);
|
||||||
|
CREATE INDEX idx_game_sessions_open ON game_sessions(expires_at) WHERE status = 'STARTED';
|
||||||
|
CREATE INDEX idx_game_sessions_game_open ON game_sessions(game_id) WHERE status = 'STARTED';
|
||||||
|
```
|
||||||
|
|
||||||
|
`balance_before` yang diminta PRD §19 tidak perlu kolom: `balance_after - amount` di
|
||||||
|
`wallet_transactions` sudah memberikannya.
|
||||||
|
|
||||||
|
### 5.4 `game_session_rewards`
|
||||||
|
|
||||||
|
```sql
|
||||||
|
-- Satu baris per budget yang membiayai reward session (D6).
|
||||||
|
CREATE TABLE game_session_rewards (
|
||||||
|
session_id UUID NOT NULL REFERENCES game_sessions(id),
|
||||||
|
budget_id UUID NOT NULL REFERENCES game_budgets(id),
|
||||||
|
amount BIGINT NOT NULL CHECK (amount > 0),
|
||||||
|
wallet_transaction_id UUID NOT NULL UNIQUE REFERENCES wallet_transactions(id),
|
||||||
|
PRIMARY KEY (session_id, budget_id)
|
||||||
|
);
|
||||||
|
```
|
||||||
|
|
||||||
|
### 5.5 `game_events` dan `game_event_games`
|
||||||
|
|
||||||
|
```sql
|
||||||
|
CREATE TABLE game_events (
|
||||||
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
organization_id UUID NOT NULL,
|
||||||
|
name VARCHAR(255) NOT NULL,
|
||||||
|
slug VARCHAR(100) NOT NULL,
|
||||||
|
description TEXT,
|
||||||
|
banner_url VARCHAR(500),
|
||||||
|
start_at TIMESTAMPTZ NOT NULL,
|
||||||
|
end_at TIMESTAMPTZ NOT NULL,
|
||||||
|
timezone VARCHAR(50) NOT NULL DEFAULT 'Asia/Jakarta',
|
||||||
|
status VARCHAR(20) NOT NULL DEFAULT 'DRAFT'
|
||||||
|
CHECK (status IN ('DRAFT', 'ACTIVE', 'ENDED', 'CANCELLED')),
|
||||||
|
priority INT NOT NULL DEFAULT 0,
|
||||||
|
multiplier NUMERIC(5,2) CHECK (multiplier IS NULL OR multiplier > 0),
|
||||||
|
bonus BIGINT CHECK (bonus IS NULL OR bonus > 0),
|
||||||
|
-- Budget event sendiri, terpisah dari global (§5.6). Membiayai tambahan reward
|
||||||
|
-- dari multiplier dan bonus event ini.
|
||||||
|
budget_id UUID NOT NULL REFERENCES game_budgets(id),
|
||||||
|
reward_limit BIGINT, -- PRD §35 Event Limit
|
||||||
|
user_daily_limit BIGINT,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
|
||||||
|
UNIQUE (organization_id, slug),
|
||||||
|
CHECK (end_at > start_at)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE game_event_games (
|
||||||
|
event_id UUID NOT NULL REFERENCES game_events(id) ON DELETE CASCADE,
|
||||||
|
game_id UUID NOT NULL REFERENCES games(id) ON DELETE RESTRICT,
|
||||||
|
PRIMARY KEY (event_id, game_id)
|
||||||
|
);
|
||||||
|
```
|
||||||
|
|
||||||
|
Event adalah campaign dalam arti PRD §7: setiap event punya budget sendiri. Base reward
|
||||||
|
tetap dibiayai budget global. Hanya selisih yang ditambahkan event (multiplier + bonus)
|
||||||
|
yang dibiayai budget event. Budget event harus ber-`scope = 'EVENT'`, ditegakkan di
|
||||||
|
processor.
|
||||||
|
|
||||||
|
### 5.6 `game_budgets`
|
||||||
|
|
||||||
|
```sql
|
||||||
|
CREATE TABLE game_budgets (
|
||||||
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
organization_id UUID NOT NULL,
|
||||||
|
scope VARCHAR(20) NOT NULL CHECK (scope IN ('GLOBAL', 'EVENT')),
|
||||||
|
name VARCHAR(255) NOT NULL,
|
||||||
|
period_start DATE NOT NULL,
|
||||||
|
period_end DATE NOT NULL,
|
||||||
|
amount BIGINT NOT NULL CHECK (amount > 0), -- rupiah
|
||||||
|
-- {"warning": 70, "critical": 90} dalam persen utilisasi/forecast (PRD §8, §32).
|
||||||
|
thresholds JSONB NOT NULL DEFAULT '{}',
|
||||||
|
exhaustion_policy VARCHAR(30), -- PRD §34, menunggu keputusan
|
||||||
|
created_by UUID NOT NULL,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
|
||||||
|
CHECK (period_end >= period_start)
|
||||||
|
);
|
||||||
|
|
||||||
|
-- Budget global tidak boleh tumpang tindih di satu org: satu baris per periode.
|
||||||
|
CREATE UNIQUE INDEX uq_game_budgets_global_period
|
||||||
|
ON game_budgets(organization_id, period_start) WHERE scope = 'GLOBAL';
|
||||||
|
```
|
||||||
|
|
||||||
|
- **Global** default bulanan (PRD §5.2): `period_start` tanggal 1, `period_end` akhir bulan.
|
||||||
|
Periode lain bisa di-configure dengan mengisi rentang sendiri.
|
||||||
|
- **Event** periodenya rentang event. Realized cost dihitung ke budget event **kapan pun
|
||||||
|
Point-nya ditukar**, termasuk setelah event berakhir, karena biaya itu lahir dari reward
|
||||||
|
event tersebut.
|
||||||
|
|
||||||
|
### 5.7 Voucher
|
||||||
|
|
||||||
|
```sql
|
||||||
|
CREATE TABLE vouchers (
|
||||||
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
organization_id UUID NOT NULL,
|
||||||
|
name VARCHAR(255) NOT NULL,
|
||||||
|
description TEXT,
|
||||||
|
image_url VARCHAR(500),
|
||||||
|
voucher_type VARCHAR(30) NOT NULL
|
||||||
|
CHECK (voucher_type IN ('FIXED_VALUE', 'PERCENTAGE', 'FREE_ITEM', 'MERCHANT_BENEFIT')),
|
||||||
|
face_value BIGINT NOT NULL CHECK (face_value > 0), -- rupiah, dasar realized cost
|
||||||
|
point_cost BIGINT NOT NULL CHECK (point_cost > 0), -- boleh beda dari face_value (PRD §22)
|
||||||
|
business_cost BIGINT, -- reporting saja, bukan budget
|
||||||
|
stock_mode VARCHAR(20) NOT NULL
|
||||||
|
CHECK (stock_mode IN ('STATIC', 'CODE_POOL', 'EXTERNAL')),
|
||||||
|
stock BIGINT CHECK (stock IS NULL OR stock >= 0), -- hanya STATIC
|
||||||
|
provider VARCHAR(50), -- hanya EXTERNAL
|
||||||
|
provider_ref VARCHAR(255),
|
||||||
|
max_per_customer INT,
|
||||||
|
valid_from TIMESTAMPTZ,
|
||||||
|
valid_until TIMESTAMPTZ,
|
||||||
|
terms JSONB NOT NULL DEFAULT '{}',
|
||||||
|
status VARCHAR(20) NOT NULL DEFAULT 'DRAFT'
|
||||||
|
CHECK (status IN ('DRAFT', 'ACTIVE', 'INACTIVE', 'ARCHIVED')),
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
|
||||||
|
CHECK ((stock_mode = 'STATIC') = (stock IS NOT NULL)),
|
||||||
|
CHECK ((stock_mode = 'EXTERNAL') = (provider IS NOT NULL))
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE voucher_codes (
|
||||||
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
voucher_id UUID NOT NULL REFERENCES vouchers(id) ON DELETE RESTRICT,
|
||||||
|
code VARCHAR(255) NOT NULL,
|
||||||
|
status VARCHAR(20) NOT NULL DEFAULT 'AVAILABLE'
|
||||||
|
CHECK (status IN ('AVAILABLE', 'RESERVED', 'REDEEMED', 'EXPIRED', 'CANCELLED')),
|
||||||
|
redemption_id UUID,
|
||||||
|
expires_at TIMESTAMPTZ,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
|
||||||
|
UNIQUE (voucher_id, code),
|
||||||
|
CHECK ((status IN ('RESERVED', 'REDEEMED')) = (redemption_id IS NOT NULL))
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX idx_voucher_codes_available ON voucher_codes(voucher_id, created_at)
|
||||||
|
WHERE status = 'AVAILABLE';
|
||||||
|
|
||||||
|
CREATE TABLE voucher_redemptions (
|
||||||
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
organization_id UUID NOT NULL,
|
||||||
|
customer_id UUID NOT NULL REFERENCES customers(id) ON DELETE RESTRICT,
|
||||||
|
voucher_id UUID NOT NULL REFERENCES vouchers(id),
|
||||||
|
idempotency_key VARCHAR(100) NOT NULL,
|
||||||
|
status VARCHAR(20) NOT NULL
|
||||||
|
CHECK (status IN ('PENDING', 'COMPLETED', 'FAILED')),
|
||||||
|
-- Snapshot (P3).
|
||||||
|
face_value BIGINT NOT NULL,
|
||||||
|
point_cost BIGINT NOT NULL,
|
||||||
|
voucher_code_id UUID REFERENCES voucher_codes(id),
|
||||||
|
external_code VARCHAR(255),
|
||||||
|
external_ref VARCHAR(255),
|
||||||
|
debit_transaction_id UUID NOT NULL REFERENCES wallet_transactions(id),
|
||||||
|
refund_transaction_id UUID REFERENCES wallet_transactions(id),
|
||||||
|
failure_reason VARCHAR(255),
|
||||||
|
attempts INT NOT NULL DEFAULT 0,
|
||||||
|
completed_at TIMESTAMPTZ,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
|
||||||
|
UNIQUE (customer_id, idempotency_key),
|
||||||
|
CHECK ((status = 'FAILED') = (refund_transaction_id IS NOT NULL))
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX idx_voucher_redemptions_pending ON voucher_redemptions(updated_at)
|
||||||
|
WHERE status = 'PENDING';
|
||||||
|
|
||||||
|
-- Atribusi realized cost per budget, dibekukan saat redemption COMPLETED (D5).
|
||||||
|
CREATE TABLE voucher_redemption_costs (
|
||||||
|
redemption_id UUID NOT NULL REFERENCES voucher_redemptions(id),
|
||||||
|
-- NULL = Point yang bukan berasal dari EnakGame (EARN, ADJUSTMENT, MIGRATION).
|
||||||
|
budget_id UUID REFERENCES game_budgets(id),
|
||||||
|
source_type VARCHAR(30) NOT NULL, -- tipe ledger lot asal
|
||||||
|
points BIGINT NOT NULL CHECK (points > 0),
|
||||||
|
cost BIGINT NOT NULL CHECK (cost >= 0), -- rupiah, bagian dari face_value
|
||||||
|
recognized_at TIMESTAMPTZ NOT NULL, -- = completed_at, dasar periode budget
|
||||||
|
UNIQUE (redemption_id, budget_id, source_type)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX idx_voucher_redemption_costs_budget
|
||||||
|
ON voucher_redemption_costs(budget_id, recognized_at);
|
||||||
|
```
|
||||||
|
|
||||||
|
### 5.8 Counter Economy Guard
|
||||||
|
|
||||||
|
```sql
|
||||||
|
-- Jumlah reward yang sudah diterbitkan per cakupan per hari (Asia/Jakarta).
|
||||||
|
CREATE TABLE game_reward_counters (
|
||||||
|
organization_id UUID NOT NULL,
|
||||||
|
scope_type VARCHAR(20) NOT NULL CHECK (scope_type IN ('USER', 'GAME', 'EVENT', 'GLOBAL')),
|
||||||
|
scope_id UUID NOT NULL, -- customer / game / event / organization
|
||||||
|
day DATE NOT NULL,
|
||||||
|
amount BIGINT NOT NULL DEFAULT 0 CHECK (amount >= 0),
|
||||||
|
PRIMARY KEY (organization_id, scope_type, scope_id, day)
|
||||||
|
);
|
||||||
|
```
|
||||||
|
|
||||||
|
`EVENT` memakai `day = '0001-01-01'` untuk limit seumur event (PRD §35 Event Limit) dan
|
||||||
|
tanggal sebenarnya untuk `game_events.user_daily_limit`.
|
||||||
|
|
||||||
|
### 5.9 `audit_logs`
|
||||||
|
|
||||||
|
```sql
|
||||||
|
CREATE TABLE audit_logs (
|
||||||
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
organization_id UUID NOT NULL,
|
||||||
|
actor_type VARCHAR(20) NOT NULL CHECK (actor_type IN ('USER', 'SYSTEM')),
|
||||||
|
actor_id UUID,
|
||||||
|
entity_type VARCHAR(50) NOT NULL,
|
||||||
|
entity_id UUID NOT NULL,
|
||||||
|
action VARCHAR(50) NOT NULL,
|
||||||
|
before JSONB,
|
||||||
|
after JSONB,
|
||||||
|
reason VARCHAR(255),
|
||||||
|
source VARCHAR(50) NOT NULL, -- 'admin_api', 'budget_controller', 'session_job', ...
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX idx_audit_logs_entity ON audit_logs(entity_type, entity_id, created_at DESC);
|
||||||
|
```
|
||||||
|
|
||||||
|
### 5.10 Pengaturan organisasi
|
||||||
|
|
||||||
|
Limit global dan per user disimpan di `organization_settings` (key-value, `000091`),
|
||||||
|
dikelola lewat pola `LoyaltySettingsProcessor`: field descriptor dengan default dan
|
||||||
|
min/max, advisory lock, dan riwayat otomatis di `loyalty_setting_changes`. Audit perubahan
|
||||||
|
setting gratis didapat dari situ.
|
||||||
|
|
||||||
|
| Key | Tipe | Default | Arti |
|
||||||
|
|---|---|---|---|
|
||||||
|
| `enakgame.limit.user_daily` | int ≥ 0 | 0 (tanpa batas) | Coin maksimal yang didapat satu customer per hari |
|
||||||
|
| `enakgame.limit.global_daily` | int ≥ 0 | 0 | Coin maksimal yang diterbitkan seluruh org per hari |
|
||||||
|
|
||||||
|
Perilaku saat limit terlampaui tidak di-configure: reward selalu **dipotong ke sisa limit**
|
||||||
|
(§9).
|
||||||
|
|
||||||
|
Limit per game (`Game Daily Limit`) disimpan di `games.result_rules` agar ikut di-configure
|
||||||
|
per game.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 6. Ledger
|
||||||
|
|
||||||
|
### 6.1 Tipe baru dan perubahan
|
||||||
|
|
||||||
|
| Tipe | Currency | Arah | Ref | Wajib tambahan | Idempotency key | Status |
|
||||||
|
|---|---|---|---|---|---|---|
|
||||||
|
| `GAME_SPEND` | COIN | keluar | `GAME_PLAY` (lama) **atau `GAME_SESSION`** | – | `game-entry:{customer}:{key}` | ref baru |
|
||||||
|
| `GAME_SPEND_REFUND` | COIN | masuk | `GAME_SESSION` | `reverses_transaction_id` | `game-refund:{session}` | **baru** |
|
||||||
|
| `GAME_REWARD` | COIN | masuk | `GAME_SESSION` | – | `game-reward:{session}:{budget}` | **baru** |
|
||||||
|
| `REWARD_REDEEM` | POINT | keluar | `REWARD_REDEMPTION` → `voucher_redemptions.id` | – | `redeem:{redemption}` | sudah ada, mulai dipakai |
|
||||||
|
| `REWARD_REDEEM_REFUND` | POINT | masuk | `REWARD_REDEMPTION` | `reverses_transaction_id` | `redeem-refund:{redemption}` | **baru** |
|
||||||
|
|
||||||
|
Pemetaan ke konsep PRD §19: `EARNED` = `GAME_REWARD`, `SPENT` = `GAME_SPEND` /
|
||||||
|
`REWARD_REDEEM`, `REFUND` = `GAME_SPEND_REFUND` / `REWARD_REDEEM_REFUND`, `EXPIRED` =
|
||||||
|
`EXPIRE`, `CONVERSION` = `EXCHANGE_OUT` + `EXCHANGE_IN`. `BONUS` dari event tetap
|
||||||
|
`GAME_REWARD`, dibedakan lewat budget dan `reward_breakdown`.
|
||||||
|
|
||||||
|
### 6.2 Perubahan yang harus dilakukan bersamaan
|
||||||
|
|
||||||
|
Menambah tipe berarti mengubah **dua tempat** yang harus sinkron:
|
||||||
|
|
||||||
|
1. `walletTypeRules` di `processor/wallet_processor.go:487`, plus konstanta di
|
||||||
|
`constants/wallet.go` (`WalletRefTypeGameSession`).
|
||||||
|
2. CHECK di `wallet_transactions` (drop + create ulang):
|
||||||
|
- `chk_wallet_transactions_point_only_types` + `REWARD_REDEEM_REFUND`
|
||||||
|
- `chk_wallet_transactions_coin_only_types` + `GAME_SPEND_REFUND`, `GAME_REWARD`
|
||||||
|
- `chk_wallet_transactions_reversal_source` + `GAME_SPEND_REFUND`, `REWARD_REDEEM_REFUND`
|
||||||
|
|
||||||
|
Reconciliation job (`service/wallet_reconciliation_job.go`) harus diperiksa: invariant
|
||||||
|
yang menghitung per tipe perlu mengenali tipe baru.
|
||||||
|
|
||||||
|
### 6.3 Lot
|
||||||
|
|
||||||
|
| Mutasi | Lot yang dibuat |
|
||||||
|
|---|---|
|
||||||
|
| `GAME_REWARD` | Satu lot, `expires_at = ComputeExpiry(CoinExpiry, now)`, tanpa `origin_lot_id` (lot akar) |
|
||||||
|
| `GAME_SPEND_REFUND` | Satu lot per alokasi `GAME_SPEND` asal: `expires_at = RefundExpiry(lot.expires_at, now)`, `origin_lot_id = lot asal`. Sama persis dengan pola `PAYMENT_REFUND` (`point_payment_refund.go`) |
|
||||||
|
| `REWARD_REDEEM_REFUND` | Sama dengan `GAME_SPEND_REFUND`, untuk Point |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 7. Alur
|
||||||
|
|
||||||
|
### 7.1 Start Game
|
||||||
|
|
||||||
|
```
|
||||||
|
POST /customer/enakgame/sessions { game_id } Idempotency-Key: <≤50 char>
|
||||||
|
```
|
||||||
|
|
||||||
|
Satu transaksi:
|
||||||
|
|
||||||
|
1. Baca customer → `organization_id`. Tolak bila game bukan milik org tersebut atau
|
||||||
|
`status <> 'ACTIVE'`.
|
||||||
|
2. Baca reward config `ACTIVE` untuk game. Tolak bila tidak ada.
|
||||||
|
3. Pastikan ada budget global untuk periode berjalan. Tolak bila belum diatur, karena
|
||||||
|
reward yang nanti diterbitkan wajib menunjuk budget (D6).
|
||||||
|
4. `LockWallet(customer)`.
|
||||||
|
5. `FindTransaction("game-entry:{customer}:{key}")`. Bila ada → kembalikan session yang
|
||||||
|
menunjuknya (replay, tidak memotong lagi).
|
||||||
|
6. Buat `session_id` baru. `Debit` COIN `GAME_SPEND`, ref `GAME_SESSION → session_id`,
|
||||||
|
amount `games.entry_cost`. Saldo kurang → `ErrWalletInsufficientBalance` → tolak tanpa
|
||||||
|
apa pun tercatat.
|
||||||
|
7. Insert `game_sessions` dengan `entry_cost`, `reward_config_id`,
|
||||||
|
`expires_at = now + session_ttl_seconds`, `spend_transaction_id`.
|
||||||
|
|
||||||
|
Response: `session_id`, `expires_at`, `entry_cost`, `coin_balance`.
|
||||||
|
|
||||||
|
### 7.2 Complete Game
|
||||||
|
|
||||||
|
```
|
||||||
|
POST /customer/enakgame/sessions/:id/complete { score?, outcome?, data? }
|
||||||
|
```
|
||||||
|
|
||||||
|
Satu transaksi:
|
||||||
|
|
||||||
|
1. `LockWallet(customer)`.
|
||||||
|
2. Baca session. Bila `customer_id` beda → 404. Bila status sudah `COMPLETED` → kembalikan
|
||||||
|
hasil yang tersimpan (idempotent, PRD §20). Bila `REFUNDED` / `EXPIRED` → tolak.
|
||||||
|
3. Bila `now > expires_at` → tolak (session dibiarkan untuk job, §7.3).
|
||||||
|
4. Bila game sudah tidak `ACTIVE` → **refund** (`GAME_DEACTIVATED`) di transaksi ini, lalu
|
||||||
|
kembalikan response "game dinonaktifkan, Coin dikembalikan".
|
||||||
|
5. **Result Validator** (`games.result_rules`): durasi minimal sejak `started_at`, skor
|
||||||
|
maksimum, skor per detik, outcome yang dikenal. Gagal → reward 0, `flagged = true`,
|
||||||
|
alasan di `reward_breakdown`. Session tetap `COMPLETED`, tidak ada refund.
|
||||||
|
6. **Reward Engine** (§8): hitung base dari config snapshot.
|
||||||
|
7. **Event modifier**: event `ACTIVE` yang mencakup game, `start_at ≤ now < end_at`.
|
||||||
|
Hasilnya daftar komponen `{budget_id, amount}`.
|
||||||
|
8. **Economy Guard** (§9): naikkan counter dengan UPDATE bersyarat, potong komponen yang
|
||||||
|
melewati limit.
|
||||||
|
9. `UPDATE game_sessions SET status='COMPLETED' ... WHERE id=? AND status='STARTED'`.
|
||||||
|
0 baris → session baru saja di-refund job → rollback, kembalikan status terbaru.
|
||||||
|
10. Untuk tiap komponen > 0: `Credit` COIN `GAME_REWARD` dengan key
|
||||||
|
`game-reward:{session}:{budget}`, lalu insert `game_session_rewards`.
|
||||||
|
|
||||||
|
Response: `reward_total`, rincian yang aman ditampilkan (base, bonus event), `coin_balance`.
|
||||||
|
|
||||||
|
### 7.3 Refund otomatis & kedaluwarsa session
|
||||||
|
|
||||||
|
PRD §10.2: refund otomatis untuk **system error** dan **game dinonaktifkan**; session yang
|
||||||
|
ditinggal user tidak di-refund.
|
||||||
|
|
||||||
|
**Mendefinisikan "system error".** Backend hanya bisa membedakan dua hal ini bila ada jejak.
|
||||||
|
Aturannya:
|
||||||
|
|
||||||
|
- Bila complete (§7.2) gagal dengan error non-bisnis (DB error, panic, timeout → HTTP 5xx),
|
||||||
|
handler menulis `completion_failed_at = now()` di **transaksi terpisah**
|
||||||
|
(`DetachTransaction`, karena transaksi utama sudah rollback).
|
||||||
|
- Error validasi (4xx) dan error yang terjadi di client (Phaser crash, koneksi putus
|
||||||
|
sebelum request sampai) **tidak** meninggalkan jejak, sehingga diperlakukan sebagai
|
||||||
|
ditinggal user dan tidak di-refund (diputuskan).
|
||||||
|
|
||||||
|
**`GameSessionJob`** (ticker, pola `WalletExpiryJob`, per batch, satu transaksi per
|
||||||
|
session):
|
||||||
|
|
||||||
|
| Kondisi session `STARTED` | Aksi |
|
||||||
|
|---|---|
|
||||||
|
| Game tidak lagi `ACTIVE` | Refund `GAME_DEACTIVATED` segera, tanpa menunggu kedaluwarsa |
|
||||||
|
| Lewat `expires_at` dan `completion_failed_at IS NOT NULL` | Refund `SYSTEM_ERROR` |
|
||||||
|
| Lewat `expires_at`, tanpa jejak gagal | `EXPIRED`, tanpa refund |
|
||||||
|
|
||||||
|
Langkah refund: `LockWallet` → `UPDATE ... SET status='REFUNDED' WHERE status='STARTED'`
|
||||||
|
(0 baris = sudah diselesaikan pihak lain, lewati) → `Credit` COIN `GAME_SPEND_REFUND`
|
||||||
|
dengan `reverses_transaction_id = spend_transaction_id`, lot sesuai §6.3, key
|
||||||
|
`game-refund:{session}` → isi `refund_transaction_id`, `refund_reason` → `audit_logs`
|
||||||
|
dengan `actor_type = SYSTEM`.
|
||||||
|
|
||||||
|
Saat admin mengubah game ke `INACTIVE`, handler tidak perlu menyapu session. Job berikutnya
|
||||||
|
menanganinya, dan complete di §7.2 langkah 4 menangani yang lebih cepat.
|
||||||
|
|
||||||
|
### 7.4 Redemption voucher internal (`STATIC`, `CODE_POOL`)
|
||||||
|
|
||||||
|
```
|
||||||
|
POST /customer/enakgame/vouchers/:id/redeem { pin } Idempotency-Key: <≤50 char>
|
||||||
|
```
|
||||||
|
|
||||||
|
Satu transaksi, sehingga state `RESERVED` tidak diperlukan:
|
||||||
|
|
||||||
|
1. Validasi voucher `ACTIVE`, dalam masa berlaku, org sama.
|
||||||
|
2. `VerifyPin(..., PinActionRedeem)` — aksi PIN baru, konsisten dengan K8 (PIN untuk setiap
|
||||||
|
pemakaian saldo). Batas salah 5 kali / kunci 30 menit yang sudah ada ikut berlaku.
|
||||||
|
3. `LockWallet(customer)`.
|
||||||
|
4. Cari `voucher_redemptions (customer_id, idempotency_key)`. Ada → kembalikan (replay).
|
||||||
|
5. Cek `max_per_customer` dari `COUNT(*)` redemption `COMPLETED` / `PENDING`.
|
||||||
|
6. Ambil stok:
|
||||||
|
- `STATIC`: `UPDATE vouchers SET stock = stock - 1 WHERE id = ? AND stock > 0`.
|
||||||
|
- `CODE_POOL`: `SELECT ... FROM voucher_codes WHERE voucher_id = ? AND status = 'AVAILABLE'
|
||||||
|
ORDER BY created_at LIMIT 1 FOR UPDATE SKIP LOCKED`, lalu set `REDEEMED`.
|
||||||
|
- Habis → tolak, tidak ada yang tercatat.
|
||||||
|
7. `Debit` POINT `REWARD_REDEEM` sebesar `point_cost`, key `redeem:{redemption}`.
|
||||||
|
8. Insert `voucher_redemptions` `COMPLETED` dengan snapshot `face_value`, `point_cost`.
|
||||||
|
9. **Atribusi cost** (§7.6) → insert `voucher_redemption_costs`.
|
||||||
|
|
||||||
|
### 7.5 Redemption voucher eksternal (`EXTERNAL`)
|
||||||
|
|
||||||
|
Panggilan ke provider tidak boleh berada di dalam transaksi database, jadi alurnya dua
|
||||||
|
tahap dengan pemulihan:
|
||||||
|
|
||||||
|
1. **Transaksi 1:** langkah 1–5 dan 7 di §7.4, lalu insert redemption `PENDING`. Point sudah
|
||||||
|
terpotong.
|
||||||
|
2. **Panggil provider** dengan `redemption_id` sebagai idempotency key provider.
|
||||||
|
3. **Transaksi 2**, tergantung hasil:
|
||||||
|
- Sukses → simpan `external_code` / `external_ref`, `COMPLETED`, atribusi cost (§7.6).
|
||||||
|
- Gagal pasti (provider menolak) → `Credit` POINT `REWARD_REDEEM_REFUND`, `FAILED`.
|
||||||
|
- Timeout / tidak jelas → biarkan `PENDING`, response "sedang diproses".
|
||||||
|
4. **`VoucherRedemptionRecoveryJob`** mengambil `PENDING` yang sudah lewat N menit, bertanya
|
||||||
|
ke provider (atau mengulang dengan key yang sama), lalu menjalankan transaksi 2. Setelah
|
||||||
|
batas percobaan, refund dan `FAILED`.
|
||||||
|
|
||||||
|
Dengan ini syarat PRD §26 terpenuhi: tidak ada keadaan "Point terpotong, voucher tidak
|
||||||
|
datang" yang tidak dipulihkan.
|
||||||
|
|
||||||
|
### 7.6 Atribusi realized cost
|
||||||
|
|
||||||
|
Dijalankan di dalam transaksi redemption, setelah debit `REWARD_REDEEM`:
|
||||||
|
|
||||||
|
```sql
|
||||||
|
WITH RECURSIVE chain AS (
|
||||||
|
SELECT a.lot_id AS spent_lot, a.amount AS points, l.origin_lot_id, l.source_transaction_id
|
||||||
|
FROM wallet_lot_allocations a
|
||||||
|
JOIN wallet_lots l ON l.id = a.lot_id
|
||||||
|
WHERE a.transaction_id = :redeem_tx
|
||||||
|
UNION ALL
|
||||||
|
SELECT c.spent_lot, c.points, p.origin_lot_id, p.source_transaction_id
|
||||||
|
FROM chain c
|
||||||
|
JOIN wallet_lots p ON p.id = c.origin_lot_id
|
||||||
|
)
|
||||||
|
SELECT c.points, t.type AS source_type, gsr.budget_id
|
||||||
|
FROM chain c
|
||||||
|
JOIN wallet_transactions t ON t.id = c.source_transaction_id
|
||||||
|
LEFT JOIN game_session_rewards gsr ON gsr.wallet_transaction_id = t.id
|
||||||
|
WHERE c.origin_lot_id IS NULL; -- lot akar
|
||||||
|
```
|
||||||
|
|
||||||
|
Rantai lot akar Point bisa melewati `EXCHANGE_IN` → lot Coin → `TRANSFER_IN` → ... sampai
|
||||||
|
`GAME_REWARD` (EnakGame) atau `EARN` / `ADJUSTMENT` / `MIGRATION` (bukan EnakGame).
|
||||||
|
`exchangeLots` dan transfer sudah mengisi `origin_lot_id`, jadi query ini bekerja dengan
|
||||||
|
data yang sudah ada.
|
||||||
|
|
||||||
|
Hasil dikelompokkan per `(budget_id, source_type)`, lalu `face_value` dibagi
|
||||||
|
proporsional terhadap Point:
|
||||||
|
|
||||||
|
```
|
||||||
|
cost_i = face_value × points_i / point_cost (dibulatkan; selisih pembulatan
|
||||||
|
diberikan ke bagian terbesar, sehingga
|
||||||
|
Σ cost_i = face_value persis)
|
||||||
|
```
|
||||||
|
|
||||||
|
Contoh: voucher face value Rp10.000, point cost 8.000. Point yang dipakai: 6.000 dari
|
||||||
|
`GAME_REWARD` (budget global Oktober), 2.000 dari `EARN`.
|
||||||
|
|
||||||
|
| budget_id | source_type | points | cost |
|
||||||
|
|---|---|---|---|
|
||||||
|
| global-2026-10 | `GAME_REWARD` | 6.000 | 7.500 |
|
||||||
|
| NULL | `EARN` | 2.000 | 2.500 |
|
||||||
|
|
||||||
|
Hanya Rp7.500 yang mengurangi budget global Oktober. Rp2.500 dari Point belanja tetap
|
||||||
|
tercatat untuk reporting Finance, tetapi tidak dihitung ke budget mana pun (D5).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 8. Reward Engine
|
||||||
|
|
||||||
|
Satu interface, satu implementasi per tipe:
|
||||||
|
|
||||||
|
```go
|
||||||
|
type RewardCalculator interface {
|
||||||
|
Validate(rules json.RawMessage) error // saat config dibuat
|
||||||
|
Calculate(rules json.RawMessage, result SessionResult, rng RNG) (base int64, detail map[string]any, err error)
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
| Tipe | `rules` | Catatan |
|
||||||
|
|---|---|---|
|
||||||
|
| `FIXED` | `{"amount": 5}` | |
|
||||||
|
| `SCORE_BASED` | `{"bands": [{"min": 0, "max": 100, "amount": 1}, {"min": 101, "amount": 20}]}` | Band tidak boleh tumpang tindih atau berlubang; band terakhir boleh tanpa `max` |
|
||||||
|
| `OUTCOME_BASED` | `{"outcomes": {"PERFECT": 20, "GOOD": 10, "NORMAL": 5, "FAIL": 0}}` | Outcome di luar daftar → ditolak Result Validator |
|
||||||
|
| `PROBABILITY` | `{"table": [{"weight": 1, "amount": 1000}, {"weight": 10, "amount": 100}, {"weight": 889, "amount": 0}]}` | Bobot bilangan bulat, bukan persen desimal, supaya validasi "total = 100%" tidak bergantung float |
|
||||||
|
|
||||||
|
**PROBABILITY memakai `crypto/rand`**, bukan `math/rand` yang di-seed ulang dengan waktu
|
||||||
|
seperti `selectPrizeByWeight` sekarang. Angka acak yang ditarik disimpan di
|
||||||
|
`reward_breakdown` untuk audit. Hasil diundi saat **complete**, bukan saat start, supaya
|
||||||
|
client tidak bisa mengetahui hasil lalu meninggalkan session.
|
||||||
|
|
||||||
|
**Modifier event** (urutan tetap): `base × multiplier` → `+ bonus` → cap `max_reward` config.
|
||||||
|
Aturan tumpuk antar event mengikuti default PRD §16 (multiplier terkontrol, bonus dihitung
|
||||||
|
terpisah, cap selalu berlaku) sampai diputuskan (§19.2 #2).
|
||||||
|
|
||||||
|
**Pembulatan:** semua hasil perkalian **dibulatkan ke bawah** ke Coin utuh, mengikuti K6 di
|
||||||
|
PRD point-coin. Ini usulan untuk menutup Open Decision PRD §43 #1.
|
||||||
|
|
||||||
|
`TIERED` di luar scope: tabel `tiers` belum terhubung ke customer, dan aturan tier dibahas
|
||||||
|
di PRD terpisah (point-coin Q8).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 9. Economy Guard & Limits
|
||||||
|
|
||||||
|
Pemeriksaan di §7.2 langkah 8, untuk setiap komponen reward:
|
||||||
|
|
||||||
|
1. Session valid, belum rewarded, user & game cocok — sudah dijamin §7.2 langkah 2–4 dan 9.
|
||||||
|
2. Untuk tiap limit yang berlaku (`USER` harian, `GAME` harian, `EVENT` total & per user,
|
||||||
|
`GLOBAL` harian):
|
||||||
|
|
||||||
|
```sql
|
||||||
|
INSERT INTO game_reward_counters (...) VALUES (..., 0) ON CONFLICT DO NOTHING;
|
||||||
|
UPDATE game_reward_counters SET amount = amount + :x
|
||||||
|
WHERE ... AND amount + :x <= :limit
|
||||||
|
RETURNING amount;
|
||||||
|
```
|
||||||
|
|
||||||
|
0 baris → limit terlampaui → `x` diturunkan ke sisa limit dan diulang. Sisa 0 berarti
|
||||||
|
komponen menjadi 0. Batas yang memotong dicatat di `reward_breakdown`, supaya customer
|
||||||
|
bisa diberi tahu kenapa reward-nya lebih kecil.
|
||||||
|
3. Status budget (§10) `EXHAUSTED` → terapkan `exhaustion_policy` (§19.2 #3).
|
||||||
|
|
||||||
|
Counter `USER` aman karena wallet customer sudah dikunci. Counter `GAME` / `GLOBAL` adalah
|
||||||
|
baris panas yang dikunci singkat oleh setiap complete di org tersebut. Untuk volume awal
|
||||||
|
ini dapat diterima. Lihat risiko di §17.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 10. Budget & Budget Controller v1
|
||||||
|
|
||||||
|
**Metrik per budget** (PRD §8), dihitung on-read dari tabel yang ada, tanpa tabel agregat:
|
||||||
|
|
||||||
|
| Metrik | Sumber |
|
||||||
|
|---|---|
|
||||||
|
| Realized cost | `SUM(voucher_redemption_costs.cost)` untuk `budget_id`, `recognized_at` dalam periode (global) / tanpa batas waktu (event) |
|
||||||
|
| Coin issued | `SUM(game_session_rewards.amount)` untuk `budget_id` |
|
||||||
|
| Remaining | `amount − realized` |
|
||||||
|
| Utilization | `realized / amount` |
|
||||||
|
| Forecast | `realized + rata-rata realized harian 7 hari terakhir × sisa hari` |
|
||||||
|
| Exposure | Sisa Coin/Point beredar yang berasal dari budget ini (via lot), sebagai batas atas biaya yang masih bisa datang |
|
||||||
|
| Status | Bandingkan utilization dan forecast dengan `thresholds` → `HEALTHY` / `WARNING` / `CRITICAL` / `EXHAUSTED` |
|
||||||
|
|
||||||
|
**Rekomendasi** (recommendation mode, D9): bila forecast > budget, hitung multiplier yang
|
||||||
|
membuat forecast = budget, lalu batasi dengan step maksimum dan min/max multiplier (PRD
|
||||||
|
§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.
|
||||||
|
|
||||||
|
`GET` metrik cukup cepat untuk dashboard selama index di §5.7 ada. Bila nanti lambat,
|
||||||
|
tambahkan snapshot harian, bukan cache yang di-invalidate.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 11. API
|
||||||
|
|
||||||
|
### Customer (`/api/v1/customer/enakgame`, `ValidateCustomerToken`)
|
||||||
|
|
||||||
|
| Method | Path | Catatan |
|
||||||
|
|---|---|---|
|
||||||
|
| `GET` | `/games` | Game `ACTIVE` milik org customer, dengan `entry_cost` dan event aktif |
|
||||||
|
| `POST` | `/sessions` | §7.1. Wajib `Idempotency-Key` |
|
||||||
|
| `POST` | `/sessions/:id/complete` | §7.2. Idempotent tanpa header |
|
||||||
|
| `GET` | `/sessions/:id` | Status dan hasil |
|
||||||
|
| `GET` | `/sessions` | Riwayat main |
|
||||||
|
| `GET` | `/vouchers` | Katalog `ACTIVE` + stok tersedia |
|
||||||
|
| `POST` | `/vouchers/:id/redeem` | §7.4 / §7.5. Wajib `Idempotency-Key` + PIN |
|
||||||
|
| `GET` | `/redemptions` | Voucher milik customer, termasuk kode |
|
||||||
|
|
||||||
|
Prefix `/enakgame` dipakai karena `/customer/games` sudah dipakai alur spin lama.
|
||||||
|
|
||||||
|
### Admin (`/api/v1/marketing/enakgame`, `RequireAdminOrManager`)
|
||||||
|
|
||||||
|
| Resource | Endpoint |
|
||||||
|
|---|---|
|
||||||
|
| 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` |
|
||||||
|
| Vouchers | CRUD, `POST /:id/codes` (impor CSV), `GET /:id/codes` |
|
||||||
|
| Redemptions | `GET` list, `GET /:id` dengan atribusi cost |
|
||||||
|
| Sessions | `GET` list + filter `flagged` |
|
||||||
|
| Settings | Lewat endpoint loyalty settings yang ada, dengan key baru (§5.10) |
|
||||||
|
|
||||||
|
Perubahan budget, voucher, dan reward config memerlukan `RequireLoyaltyManager`, sama
|
||||||
|
seperti adjustment saldo.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 12. Background Jobs
|
||||||
|
|
||||||
|
Semua mengikuti pola goroutine + `time.NewTicker` di `app/app.go`, satu transaksi per item,
|
||||||
|
aman dijalankan di beberapa instance karena setiap item dikunci lewat UPDATE bersyarat.
|
||||||
|
|
||||||
|
| Job | Interval | Tugas |
|
||||||
|
|---|---|---|
|
||||||
|
| `GameSessionJob` | 1 menit | §7.3: refund / expire session `STARTED` |
|
||||||
|
| `VoucherRedemptionRecoveryJob` | 1 menit | §7.5: selesaikan `PENDING` eksternal |
|
||||||
|
| `VoucherCodeExpiryJob` | 1 jam | `AVAILABLE → EXPIRED` untuk kode lewat `expires_at` |
|
||||||
|
| `GameBudgetPeriodJob` | 1 hari | Membuat baris budget global bulan berikutnya dari bulan berjalan, bila belum ada |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 13. Audit
|
||||||
|
|
||||||
|
`audit_logs` diisi untuk semua perubahan yang disebut PRD §37: reward config (buat,
|
||||||
|
aktifkan, pensiunkan), event, budget, voucher (termasuk impor kode), status game, refund
|
||||||
|
otomatis, dan penerimaan rekomendasi Budget Controller. Ditulis di transaksi yang sama
|
||||||
|
dengan perubahannya, sehingga tidak ada perubahan tanpa jejak.
|
||||||
|
|
||||||
|
Pengaturan limit sudah ter-audit lewat `loyalty_setting_changes` (§5.10). Adjustment saldo
|
||||||
|
sudah ter-audit lewat ledger `ADJUSTMENT`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 14. Legacy & Migrasi
|
||||||
|
|
||||||
|
| Bagian lama | Nasib |
|
||||||
|
|---|---|
|
||||||
|
| Baris `games` lama | Diarsipkan (`status = 'ARCHIVED'`), **tidak di-`DELETE`**. FK `game_plays.game_id` adalah `ON DELETE CASCADE`: menghapus game ikut menghapus `game_plays`, padahal ledger `GAME_SPEND` lama menunjuk ke sana lewat `reference_id`. Jejak asal-tujuan saldo (K5) akan putus |
|
||||||
|
| `POST /customer/spin`, `GET /customer/games`, `GET /customer/ferris-wheel` | Dihapus. Spin dibangun ulang sebagai game EnakGame dengan config `PROBABILITY` dan reward Coin |
|
||||||
|
| `game_prizes`, `game_plays` | Dibekukan (read-only). Data tetap disimpan untuk riwayat ledger `GAME_PLAY`. Kode processor/handler/route-nya dihapus |
|
||||||
|
| `rewards` | Diganti `vouchers`. Tidak punya org, tidak punya redemption, tidak dipakai flow mana pun, dan tidak punya data produksi (dikonfirmasi), sehingga tidak ada migrasi data |
|
||||||
|
| `campaigns`, `campaign_rules` | Tidak dipakai EnakGame. Campaign EnakGame adalah `game_events` |
|
||||||
|
| Bayar order dengan EnakPoint | **Dimatikan sebelum EnakGame rilis** (PRD §3.2). Belum ada order yang dibayar dengan Point, jadi tidak ada data yang dimigrasi. Yang dilepas: route point payment, `payment_methods` tipe `point` beserta trigger pembuatnya (`000094`), dan setting `loyalty.point.accept_payment`. Dikerjakan sebagai task terpisah |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 15. Temuan Sampingan
|
||||||
|
|
||||||
|
Ditemukan saat memetakan code. Tidak memblokir RFC ini, tapi sebagian berdampak ke uang:
|
||||||
|
|
||||||
|
1. **Double charge di `/customer/spin`.** `GAME_SPEND` di `PlayGame` tanpa idempotency key.
|
||||||
|
2. **`/customer/spin` menerima game id mana pun**, tanpa cek tipe dan tanpa cek org
|
||||||
|
(`spin_game_service.go:27`). Customer org A bisa memainkan game org B.
|
||||||
|
|
||||||
|
Nomor 1 dan 2 hilang sendiri saat alur lama dihapus (§14). Bila penghapusannya tidak
|
||||||
|
segera, endpoint lama sebaiknya dimatikan lebih dulu daripada ditambal.
|
||||||
|
3. **RNG hadiah** di-seed ulang dengan `UnixNano` setiap panggilan (`game_play_processor.go:287`).
|
||||||
|
4. **`threshold` dan `fallback_prize_id`** di `game_prizes` tidak pernah dipakai.
|
||||||
|
5. **`GET /customer/ferris-wheel`** mengembalikan `First()` dari game SPIN aktif tanpa urutan,
|
||||||
|
sehingga game yang dikembalikan tidak pasti.
|
||||||
|
6. **`rewards`**: create menolak tipe `BALANCE`, update menerimanya, database tidak punya
|
||||||
|
CHECK.
|
||||||
|
7. **`campaigns`**: `GetActiveCampaigns` mengikat string `"now()"` sebagai parameter tanggal
|
||||||
|
(`campaign_repository.go:114`). Belum diverifikasi apakah Postgres menerimanya.
|
||||||
|
8. **`tiers.name` UNIQUE global**, bukan per org.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 16. Di Luar Scope
|
||||||
|
|
||||||
|
- **Mission** (PRD §3.1, §19). PRD belum mendefinisikan aturannya.
|
||||||
|
- **Leaderboard** (PRD §15).
|
||||||
|
- **Reward `TIERED`** (§8).
|
||||||
|
- **Budget Controller automatic mode** (D9).
|
||||||
|
- **Hosting dan build Phaser.** RFC ini hanya mendefinisikan API yang dipanggil game.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 17. Urutan Implementasi
|
||||||
|
|
||||||
|
1. **Matikan bayar dengan EnakPoint** (§14). Independen, bisa paralel.
|
||||||
|
2. **Migrasi skema**, dengan urutan mengikuti foreign key: extend `games`,
|
||||||
|
`game_budgets`, `game_reward_configs`, `game_sessions`, `game_session_rewards`,
|
||||||
|
`audit_logs`; tipe ledger baru + CHECK (§6.2).
|
||||||
|
3. **Session + entry cost** (§7.1) dan **refund + `GameSessionJob`** (§7.3).
|
||||||
|
4. **Reward Engine** `FIXED`, `SCORE_BASED`, `OUTCOME_BASED`, `PROBABILITY` + Result
|
||||||
|
Validator + complete (§7.2, §8).
|
||||||
|
5. **Economy Guard + limits** (§9, §5.10).
|
||||||
|
6. **Voucher internal + redemption + atribusi cost** (§7.4, §7.6).
|
||||||
|
7. **Budget metrics + status** (§10).
|
||||||
|
8. **Events / campaign** dengan budget sendiri (§5.5).
|
||||||
|
9. **Voucher eksternal + recovery job** (§7.5). Butuh provider pertama yang konkret.
|
||||||
|
10. **Rekomendasi Budget Controller + analytics** (§10, PRD §36).
|
||||||
|
11. **Spin dibangun ulang sebagai game EnakGame**, lalu hapus kode alur lama dan arsipkan
|
||||||
|
datanya (§14). Endpoint lama bisa dimatikan lebih awal, kapan pun.
|
||||||
|
|
||||||
|
Langkah 2–4 sudah membuat game bisa dimainkan end-to-end dengan Coin. Langkah 6 membuat
|
||||||
|
Point bisa ditukar. Langkah 7 membuat Finance bisa melihat biaya.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 18. Risiko
|
||||||
|
|
||||||
|
| Risiko | Dampak | Mitigasi |
|
||||||
|
|---|---|---|
|
||||||
|
| Satu dari dua tempat aturan ledger (§6.2) terlewat | Mutasi ditolak di produksi, atau lolos tanpa validasi | Test per tipe di `wallet_processor_test.go` + test DB yang benar-benar insert ke `wallet_transactions` |
|
||||||
|
| Farming lewat banyak akun + transfer Coin | Limit harian per user dilewati, karena Coin hasil game boleh ditransfer (diputuskan) | Setting transfer yang ada (`Transfer.DailyLimit`, `MaxPerTransaction`); pantau `GAME_REWARD` yang langsung diikuti `TRANSFER_OUT` di analytics |
|
||||||
|
| Counter `GLOBAL` / `GAME` jadi bottleneck | Complete melambat saat ramai | Diukur dulu. Bila perlu, pecah counter per shard dan jumlahkan saat cek |
|
||||||
|
| Rantai `origin_lot_id` panjang | Query atribusi lambat | Rantai praktis pendek (reward → exchange → transfer). Bila perlu, tambah kolom `root_lot_id` di `wallet_lots` |
|
||||||
|
| Provider eksternal tidak idempotent | Voucher terbit dua kali saat recovery | Syarat integrasi: provider wajib menerima idempotency key; bila tidak, recovery hanya boleh *query*, tidak boleh mengulang |
|
||||||
|
| Client mengirim skor palsu | Coin terbit tanpa main | Result Validator (§7.2) + `flagged`; reward tidak pernah dari client (P1) |
|
||||||
|
| Game lama di-`DELETE` alih-alih diarsipkan | `game_plays` ikut terhapus (CASCADE), ledger `GAME_SPEND` lama kehilangan tujuan | Migrasi §5.1 mengarsipkan; `chk_games_enakgame_identity` mencegah arsip lama tampil sebagai game EnakGame |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 19. Keputusan & Pertanyaan Terbuka
|
||||||
|
|
||||||
|
### 19.1 Sudah Diputuskan (2026-10-07)
|
||||||
|
|
||||||
|
| # | Pertanyaan | Keputusan | Tercermin di |
|
||||||
|
|---|---|---|---|
|
||||||
|
| Q1 | Point dari belanja (`EARN`) yang ditukar voucher masuk budget EnakGame? | **Tidak.** Hanya Point yang berasal dari `GAME_REWARD` | D5, §7.6 |
|
||||||
|
| Q2 | Campaign itu apa? | **Campaign = event.** Setiap event punya budget sendiri | D6, §5.5, §5.6 |
|
||||||
|
| Q3 | Spin dan game lama? | **Dibangun ulang** sebagai game EnakGame | §14, §17 |
|
||||||
|
| Q4 | Baris `games` lama? | **Dihapus dari produk** (diarsipkan secara data, lihat §14) | §5.1, §14 |
|
||||||
|
| Q5 | Reward melewati limit? | **Dipotong ke sisa limit** | §9 |
|
||||||
|
| Q6 | Coin hasil game boleh ditransfer? | **Boleh** | §18 |
|
||||||
|
| Q7 | PIN untuk redemption voucher? | **Ya** | §7.4 |
|
||||||
|
| Q8 | Definisi "system error" untuk refund? | **Hanya error yang tercatat di server** (5xx saat complete). Crash di client = ditinggal user | §7.3 |
|
||||||
|
|
||||||
|
### 19.2 Masih Terbuka
|
||||||
|
|
||||||
|
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.**
|
||||||
|
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
|
||||||
|
7 (budget status) dirilis.
|
||||||
@@ -0,0 +1,503 @@
|
|||||||
|
# Task Breakdown: EnakGame
|
||||||
|
|
||||||
|
**Sumber:** [RFC EnakGame](rfc-enakgame.md), [PRD EnakGame](enakgame-prd.md)
|
||||||
|
**Tanggal:** 2026-10-07
|
||||||
|
|
||||||
|
Setiap task menyebut bagian RFC yang dikerjakan, lapisan kode yang disentuh, task yang
|
||||||
|
harus selesai lebih dulu, dan kriteria selesai. Ukuran: **S** ≤ 1 hari, **M** 2–3 hari,
|
||||||
|
**L** 4–5 hari.
|
||||||
|
|
||||||
|
Konvensi kode mengikuti yang sudah ada: `migrations/` (lanjut dari `000101`),
|
||||||
|
`entities` → `repository` → `processor` → `service` → `handler` / `validator` →
|
||||||
|
`router`, dan wiring di `internal/app/app.go`. Repository **selalu** memakai
|
||||||
|
`DBFromContext`. Semua mutasi saldo **hanya** lewat `WalletProcessor`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Ringkasan
|
||||||
|
|
||||||
|
| Fase | Task | Terblokir oleh |
|
||||||
|
|---|---|---|
|
||||||
|
| 0. Matikan bayar dengan EnakPoint | EG-001 – EG-002 | – |
|
||||||
|
| 1. Fondasi | EG-101 – EG-106 | – |
|
||||||
|
| 2. Admin game & session | EG-201 – EG-206 | – |
|
||||||
|
| 3. Reward Engine & complete | EG-301 – EG-303 | Pembulatan (RFC §19.2 #1) sebelum **rilis** |
|
||||||
|
| 4. Economy Guard | EG-401 – EG-402 | – |
|
||||||
|
| 5. Voucher & redemption | EG-501 – EG-507 | – |
|
||||||
|
| 6. Budget metrics | EG-601 – EG-602 | Exhaustion policy & threshold (#3, #4) sebelum **rilis** |
|
||||||
|
| 7. Event / campaign | EG-701 – EG-704 | Event stacking (#2) sebelum **rilis** |
|
||||||
|
| 8. Voucher eksternal | EG-801 – EG-803 | Provider pertama yang konkret sebelum **dikerjakan** |
|
||||||
|
| 9. Budget Controller & analytics | EG-901 – EG-903 | Threshold (#4) sebelum **dikerjakan** |
|
||||||
|
| 10. Spin & bersih-bersih | EG-1001 – EG-1003 | – |
|
||||||
|
|
||||||
|
Fase 0 independen dan bisa jalan paralel dengan semua fase lain, tetapi **harus selesai
|
||||||
|
sebelum EnakGame rilis** (PRD §3.2).
|
||||||
|
|
||||||
|
Fase 1–3 membuat game bisa dimainkan end-to-end dengan Coin. Fase 5 membuat Point bisa
|
||||||
|
ditukar. Fase 6 membuat Finance bisa melihat biaya.
|
||||||
|
|
||||||
|
```
|
||||||
|
Fase 0 EG-001 ── EG-002
|
||||||
|
|
||||||
|
Fondasi EG-101 ── EG-102 ── EG-105
|
||||||
|
EG-103, EG-104, EG-106, EG-301 (independen)
|
||||||
|
|
||||||
|
Game EG-104 + EG-105 ─────────────────── EG-201, EG-203
|
||||||
|
EG-104 + EG-105 + EG-301 ────────── EG-202
|
||||||
|
EG-103 + EG-201 + EG-202 + EG-203 ─ EG-204 ── EG-205
|
||||||
|
EG-204 + EG-205 + EG-301 + EG-302 ─ EG-303
|
||||||
|
EG-106 ── EG-401
|
||||||
|
EG-303 + EG-401 ─────────────────── EG-402
|
||||||
|
|
||||||
|
Voucher EG-501 ── EG-502
|
||||||
|
EG-103 + EG-502 + EG-503 ────────── EG-504
|
||||||
|
EG-303 + EG-504 ─────────────────── EG-505 ── EG-601 ─┬─ EG-602
|
||||||
|
└─ EG-901 ── EG-902
|
||||||
|
EG-504 ── EG-801
|
||||||
|
EG-505 + EG-801 ─────────────────── EG-802 ── EG-803
|
||||||
|
|
||||||
|
Event EG-102 ── EG-701
|
||||||
|
EG-203 + EG-701 ─────────────────── EG-702
|
||||||
|
EG-402 + EG-702 ─────────────────── EG-703
|
||||||
|
|
||||||
|
Akhir EG-402 ── EG-1001 ── EG-1002 ── EG-1003
|
||||||
|
```
|
||||||
|
|
||||||
|
Task kecil yang tidak digambar: EG-206, EG-302 (setelah EG-105), EG-506 (EG-504), EG-507
|
||||||
|
(EG-501), EG-704 (EG-206 + EG-702), EG-903 (EG-303 + EG-505).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Fase 0 — Matikan Bayar dengan EnakPoint
|
||||||
|
|
||||||
|
PRD §3.2: Point hanya bisa ditukar ke voucher. Belum ada order yang dibayar dengan Point,
|
||||||
|
jadi tidak ada data yang dimigrasi.
|
||||||
|
|
||||||
|
### EG-001 · Tutup semua jalur pembayaran EnakPoint · M
|
||||||
|
- **RFC:** §14
|
||||||
|
- **Kerjakan:**
|
||||||
|
- Sudah dikonfirmasi belum ada pembayaran dengan EnakPoint di production (2026-10-07).
|
||||||
|
- Migrasi: drop trigger yang membuat payment method `point` untuk organisasi baru
|
||||||
|
(`000094`), lalu nonaktifkan / hapus baris `payment_methods` tipe `point`.
|
||||||
|
- Tolak pembayaran bertipe `point` di jalur POS (`order_handler`, `order_processor`,
|
||||||
|
`payment_method_processor`) dan customer app (`customer_order_payment_service`).
|
||||||
|
- Hapus route `GET /orders/:id/point-payment/preview` dan
|
||||||
|
`POST /customer/wallet/payment-code`.
|
||||||
|
- Hapus `PAYMENT` dan `PAYMENT_REFUND` dari `walletTypeRules`, supaya engine menolak
|
||||||
|
keduanya. CHECK database dibiarkan.
|
||||||
|
- Hapus setting `loyalty.point.accept_payment` dari descriptor
|
||||||
|
`LoyaltySettingsProcessor` dan dari response outlet customer.
|
||||||
|
- **Selesai jika:** pembayaran order dengan method `point` ditolak di POS dan customer app,
|
||||||
|
outlet baru tidak lagi mendapat payment method EnakPoint, dan test yang ada diperbarui.
|
||||||
|
- **Bergantung pada:** –
|
||||||
|
|
||||||
|
### EG-002 · Hapus kode point payment · S
|
||||||
|
- **Kerjakan:** hapus `PointPaymentProcessor`, `point_payment_refund.go`,
|
||||||
|
`PointPaymentRepository`, `PointPaymentService`, `PointPaymentHandler`, wiring di
|
||||||
|
`app.go` / `router.go`, dan test-nya (`point_payment_db_test.go`,
|
||||||
|
`point_payment_method_db_test.go`). Pindahkan dulu helper yang ternyata dipakai di
|
||||||
|
tempat lain (mis. pola pembuatan lot refund, yang dipakai ulang di EG-205).
|
||||||
|
- **Selesai jika:** `go build ./...` dan seluruh test lulus, dan
|
||||||
|
`grep -rn "PointPayment" internal/` kosong.
|
||||||
|
- **Bergantung pada:** EG-001
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Fase 1 — Fondasi
|
||||||
|
|
||||||
|
### EG-101 · Migrasi extend `games` + arsipkan game lama · S
|
||||||
|
- **RFC:** §5.1, §14
|
||||||
|
- **Kerjakan:** migrasi up & down persis seperti §5.1. Semua baris lama menjadi
|
||||||
|
`ARCHIVED`. **Tidak ada `DELETE`** (FK `game_plays` CASCADE).
|
||||||
|
- **Selesai jika:**
|
||||||
|
- Up/down bersih di database kosong dan di salinan staging.
|
||||||
|
- Jumlah baris `game_plays` sebelum = sesudah.
|
||||||
|
- Ditolak database: game `ACTIVE` tanpa `organization_id` atau `slug`;
|
||||||
|
`entry_cost = 0`; dua game dengan slug sama di satu org.
|
||||||
|
- **Bergantung pada:** –
|
||||||
|
|
||||||
|
### EG-102 · Migrasi budget, reward config, session · M
|
||||||
|
- **RFC:** §5.2, §5.3, §5.4, §5.6
|
||||||
|
- **Kerjakan:** `game_budgets`, `game_reward_configs`, `game_sessions`,
|
||||||
|
`game_session_rewards`, dalam urutan foreign key.
|
||||||
|
- **Selesai jika:** up/down bersih. Ditolak database: dua config `ACTIVE` untuk satu game;
|
||||||
|
session `REFUNDED` tanpa `refund_transaction_id`; dua budget `GLOBAL` dengan
|
||||||
|
`period_start` sama di satu org; `game_session_rewards` dengan
|
||||||
|
`wallet_transaction_id` yang sama dua kali.
|
||||||
|
- **Bergantung pada:** EG-101
|
||||||
|
|
||||||
|
### EG-103 · Tipe ledger baru · M
|
||||||
|
- **RFC:** §6
|
||||||
|
- **Kerjakan:**
|
||||||
|
- Konstanta `GAME_SPEND_REFUND`, `GAME_REWARD`, `REWARD_REDEEM_REFUND`, ref
|
||||||
|
`GAME_SESSION` di `constants/wallet.go`.
|
||||||
|
- `walletTypeRules`: tambah tiga tipe, dan izinkan ref `GAME_SESSION` pada
|
||||||
|
`GAME_SPEND`.
|
||||||
|
- Migrasi: drop + create ulang tiga CHECK di `wallet_transactions` (§6.2).
|
||||||
|
- Periksa invariant di `wallet_reconciliation_repository.go` terhadap tipe baru.
|
||||||
|
- **Selesai jika:** test validasi di `wallet_processor_test.go` per tipe baru (currency
|
||||||
|
salah, ref salah, reversal tanpa `reverses_transaction_id` → ditolak), dan test DB yang
|
||||||
|
benar-benar insert ke `wallet_transactions` untuk setiap tipe (lolos engine **dan**
|
||||||
|
CHECK).
|
||||||
|
- **Bergantung pada:** –
|
||||||
|
|
||||||
|
### EG-104 · `audit_logs` + helper · S
|
||||||
|
- **RFC:** §5.9, §13
|
||||||
|
- **Kerjakan:** migrasi, entity, dan `AuditLogger.Record(ctx, entry)` yang menulis lewat
|
||||||
|
`DBFromContext`, sehingga audit ikut commit/rollback bersama perubahannya.
|
||||||
|
- **Selesai jika:** perubahan yang di-rollback tidak meninggalkan baris audit.
|
||||||
|
- **Bergantung pada:** –
|
||||||
|
|
||||||
|
### EG-105 · Entities & repository EnakGame · M
|
||||||
|
- **RFC:** §5.1–§5.6
|
||||||
|
- **Kerjakan:** entities dan repository untuk kolom baru `games`, `game_reward_configs`,
|
||||||
|
`game_sessions`, `game_session_rewards`, `game_budgets`. Transisi status session
|
||||||
|
sebagai `UPDATE ... WHERE status = 'STARTED'` yang mengembalikan jumlah baris
|
||||||
|
ter-update (D4). Semua query game/budget memfilter `organization_id`.
|
||||||
|
- **Selesai jika:** test repository: dua transisi bersamaan pada session yang sama, hanya
|
||||||
|
satu yang mendapat 1 baris.
|
||||||
|
- **Bergantung pada:** EG-101, EG-102
|
||||||
|
|
||||||
|
### EG-106 · Setting limit EnakGame · S
|
||||||
|
- **RFC:** §5.10
|
||||||
|
- **Kerjakan:** key `enakgame.limit.user_daily` dan `enakgame.limit.global_daily` sebagai
|
||||||
|
field descriptor di `LoyaltySettingsProcessor` (default 0 = tanpa batas, min 0).
|
||||||
|
- **Selesai jika:** setting terbaca dengan default, bisa diubah lewat endpoint loyalty
|
||||||
|
settings yang ada, dan perubahan tercatat di `loyalty_setting_changes`.
|
||||||
|
- **Bergantung pada:** –
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Fase 2 — Admin Game & Session
|
||||||
|
|
||||||
|
### EG-201 · Admin game CRUD · M
|
||||||
|
- **RFC:** §11 (admin)
|
||||||
|
- **Kerjakan:** `/marketing/enakgame/games` CRUD + `PUT /:id/status`, org dari user admin.
|
||||||
|
Validasi `slug`, `entry_cost ≥ 1`, `result_rules`. Game `ARCHIVED` tidak bisa diubah.
|
||||||
|
Perubahan status masuk `audit_logs`.
|
||||||
|
- **Selesai jika:** admin org A tidak bisa melihat atau mengubah game org B; game lama
|
||||||
|
(arsip) tidak muncul.
|
||||||
|
- **Bergantung pada:** EG-104, EG-105
|
||||||
|
|
||||||
|
### EG-202 · Admin reward config versioning · M
|
||||||
|
- **RFC:** §5.2, D7
|
||||||
|
- **Kerjakan:** `POST /games/:id/reward-configs` (versi baru, `rules` divalidasi
|
||||||
|
`RewardCalculator.Validate`), `POST /reward-configs/:id/activate` (dalam satu transaksi:
|
||||||
|
config lama → `RETIRED`, yang baru → `ACTIVE`), `GET` daftar versi. Tidak ada endpoint
|
||||||
|
update atau delete. Wajib `RequireLoyaltyManager`. Semua aksi masuk `audit_logs`.
|
||||||
|
- **Selesai jika:** config yang sudah dipakai session tidak bisa diubah lewat jalur apa
|
||||||
|
pun; aktivasi bersamaan dua versi berakhir dengan tepat satu `ACTIVE`.
|
||||||
|
- **Bergantung pada:** EG-104, EG-105, EG-301
|
||||||
|
|
||||||
|
### EG-203 · Admin budget + `GameBudgetPeriodJob` · M
|
||||||
|
- **RFC:** §5.6, §12
|
||||||
|
- **Kerjakan:** CRUD `/marketing/enakgame/budgets` (scope `GLOBAL` / `EVENT`), wajib
|
||||||
|
`RequireLoyaltyManager`, audit. Job harian yang membuat budget global bulan berikutnya
|
||||||
|
dari bulan berjalan bila belum ada.
|
||||||
|
- **Selesai jika:** job aman dijalankan berulang (unique index mencegah duplikat), dan
|
||||||
|
perubahan `amount` tercatat sebelum/sesudah di audit.
|
||||||
|
- **Bergantung pada:** EG-104, EG-105
|
||||||
|
|
||||||
|
### EG-204 · Start Game · M
|
||||||
|
- **RFC:** §7.1
|
||||||
|
- **Kerjakan:** `POST /customer/enakgame/sessions` dengan `Idempotency-Key` wajib (≤ 50
|
||||||
|
karakter, pola `customer_wallet_handler.go`). Langkah persis §7.1.
|
||||||
|
- **Selesai jika:** test untuk:
|
||||||
|
- Key yang sama dua kali → satu debit, session yang sama dikembalikan.
|
||||||
|
- Coin kurang → ditolak, tidak ada ledger maupun session.
|
||||||
|
- Game org lain, game tidak `ACTIVE`, tanpa config aktif, tanpa budget global → ditolak.
|
||||||
|
- `entry_cost` dan `reward_config_id` tersimpan sebagai snapshot: mengubah game setelah
|
||||||
|
start tidak mengubah session.
|
||||||
|
- **Bergantung pada:** EG-103, EG-105, EG-201, EG-202, EG-203
|
||||||
|
|
||||||
|
### EG-205 · Refund otomatis + `GameSessionJob` · M
|
||||||
|
- **RFC:** §7.3, §6.3
|
||||||
|
- **Kerjakan:**
|
||||||
|
- `RefundSession(ctx, sessionID, reason)`: lock wallet → transisi bersyarat ke
|
||||||
|
`REFUNDED` → `Credit` `GAME_SPEND_REFUND` dengan lot per alokasi asal
|
||||||
|
(`RefundExpiry`, `origin_lot_id`) → audit `SYSTEM`.
|
||||||
|
- Job tiap 1 menit, per batch, satu transaksi per session, sesuai tabel §7.3.
|
||||||
|
- Wiring start/stop di `app.go` seperti `WalletExpiryJob`.
|
||||||
|
- **Selesai jika:** test untuk:
|
||||||
|
- Game dinonaktifkan → session `STARTED` di-refund tanpa menunggu kedaluwarsa.
|
||||||
|
- Expired dengan `completion_failed_at` → refund. Expired tanpa → `EXPIRED`, saldo tetap.
|
||||||
|
- Lot refund punya `origin_lot_id` ke lot asal dan `expires_at` minimal 7 hari.
|
||||||
|
- Complete dan refund bersamaan pada session yang sama → tepat satu yang berhasil.
|
||||||
|
- Job dijalankan dua kali → tidak ada refund ganda.
|
||||||
|
- **Bergantung pada:** EG-204
|
||||||
|
|
||||||
|
### EG-206 · Customer: daftar game & riwayat session · S
|
||||||
|
- **RFC:** §11 (customer)
|
||||||
|
- **Kerjakan:** `GET /customer/enakgame/games`, `GET /sessions`, `GET /sessions/:id`. Hanya
|
||||||
|
game `ACTIVE` milik org customer. Rincian internal (`reward_breakdown` lengkap, angka
|
||||||
|
RNG) tidak ditampilkan.
|
||||||
|
- **Bergantung pada:** EG-105
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Fase 3 — Reward Engine & Complete
|
||||||
|
|
||||||
|
### EG-301 · `RewardCalculator` + empat tipe · M
|
||||||
|
- **RFC:** §8
|
||||||
|
- **Kerjakan:** interface `Validate` / `Calculate`, implementasi `FIXED`, `SCORE_BASED`,
|
||||||
|
`OUTCOME_BASED`, `PROBABILITY`. RNG lewat interface yang diisi `crypto/rand` di
|
||||||
|
production dan RNG tetap di test. Pembulatan ke bawah.
|
||||||
|
- **Selesai jika:** unit test: contoh tabel PRD §12 untuk setiap tipe; band skor
|
||||||
|
tumpang tindih / berlubang ditolak `Validate`; bobot `PROBABILITY` nol atau negatif
|
||||||
|
ditolak; distribusi `PROBABILITY` pada 100.000 undian berada dalam toleransi bobotnya.
|
||||||
|
- **Bergantung pada:** –
|
||||||
|
|
||||||
|
### EG-302 · Result Validator · S
|
||||||
|
- **RFC:** §7.2 langkah 5
|
||||||
|
- **Kerjakan:** validasi `result` terhadap `games.result_rules`: durasi minimal, skor
|
||||||
|
maksimum, skor per detik, outcome yang dikenal. Mengembalikan alasan, bukan error.
|
||||||
|
- **Selesai jika:** unit test per aturan, termasuk game tanpa `result_rules` (semua lolos).
|
||||||
|
- **Bergantung pada:** EG-105
|
||||||
|
|
||||||
|
### EG-303 · Complete Game · L
|
||||||
|
- **RFC:** §7.2, §7.3 (bagian `completion_failed_at`)
|
||||||
|
- **Kerjakan:**
|
||||||
|
- `POST /customer/enakgame/sessions/:id/complete`, langkah §7.2 dengan base reward dari
|
||||||
|
budget global saja. Event menyusul di EG-703, guard di EG-402.
|
||||||
|
- Satu baris `GAME_REWARD` + `game_session_rewards` per budget, key
|
||||||
|
`game-reward:{session}:{budget}`. Lot dengan `ComputeExpiry(CoinExpiry)`.
|
||||||
|
- Game tidak `ACTIVE` saat complete → `RefundSession(GAME_DEACTIVATED)`.
|
||||||
|
- Error non-bisnis → tulis `completion_failed_at` di transaksi terpisah
|
||||||
|
(`DetachTransaction`), lalu kembalikan 5xx.
|
||||||
|
- **Selesai jika:** test untuk:
|
||||||
|
- Complete dua kali → satu reward, response kedua sama dengan yang pertama.
|
||||||
|
- Hasil tidak valid → reward 0, `flagged`, session `COMPLETED`, tanpa refund.
|
||||||
|
- Session milik customer lain → 404. Session expired → ditolak.
|
||||||
|
- Error yang disuntikkan setelah kredit → rollback total, `completion_failed_at` terisi.
|
||||||
|
- Request yang membawa field `reward` diabaikan (P1).
|
||||||
|
- **Bergantung pada:** EG-204, EG-205, EG-301, EG-302
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Fase 4 — Economy Guard
|
||||||
|
|
||||||
|
### EG-401 · Counter reward + increment bersyarat · M
|
||||||
|
- **RFC:** §5.8, §9
|
||||||
|
- **Kerjakan:** migrasi `game_reward_counters`; repository `Consume(scope, id, day, x,
|
||||||
|
limit)` yang mengembalikan jumlah yang **benar-benar** diterima (dipotong ke sisa
|
||||||
|
limit, 0 bila habis). Hari dihitung di Asia/Jakarta.
|
||||||
|
- **Selesai jika:** test DB: 20 goroutine menambah counter yang sama dengan limit 100 →
|
||||||
|
total tepat 100, tidak pernah lewat.
|
||||||
|
- **Bergantung pada:** EG-106
|
||||||
|
|
||||||
|
### EG-402 · Guard di complete · S
|
||||||
|
- **RFC:** §9
|
||||||
|
- **Kerjakan:** panggil `Consume` untuk `USER` dan `GLOBAL` harian (dari setting) dan
|
||||||
|
`GAME` harian (dari `result_rules`) sebelum kredit. Batas yang memotong dicatat di
|
||||||
|
`reward_breakdown` dan dikembalikan di response.
|
||||||
|
- **Selesai jika:** reward 30 dengan sisa limit user 10 → kredit 10, breakdown menyebut
|
||||||
|
limit user. Sisa 0 → session `COMPLETED` dengan reward 0.
|
||||||
|
- **Bergantung pada:** EG-303, EG-401
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Fase 5 — Voucher & Redemption
|
||||||
|
|
||||||
|
### EG-501 · Migrasi voucher · M
|
||||||
|
- **RFC:** §5.7
|
||||||
|
- **Kerjakan:** `vouchers`, `voucher_codes`, `voucher_redemptions`,
|
||||||
|
`voucher_redemption_costs`.
|
||||||
|
- **Selesai jika:** up/down bersih. Ditolak database: voucher `STATIC` tanpa `stock`;
|
||||||
|
`EXTERNAL` tanpa `provider`; kode `REDEEMED` tanpa `redemption_id`; dua redemption dengan
|
||||||
|
`(customer_id, idempotency_key)` yang sama.
|
||||||
|
- **Bergantung pada:** –
|
||||||
|
|
||||||
|
### EG-502 · Admin voucher + impor kode · M
|
||||||
|
- **RFC:** §11 (admin)
|
||||||
|
- **Kerjakan:** CRUD `/marketing/enakgame/vouchers`, `POST /:id/codes` (CSV, kode duplikat
|
||||||
|
dilewati dan dilaporkan), `GET /:id/codes` dengan jumlah per status. `RequireLoyaltyManager`
|
||||||
|
dan audit.
|
||||||
|
- **Selesai jika:** impor CSV yang sama dua kali tidak menggandakan kode.
|
||||||
|
- **Bergantung pada:** EG-104, EG-501
|
||||||
|
|
||||||
|
### EG-503 · Aksi PIN `REDEEM` · S
|
||||||
|
- **RFC:** §7.4 langkah 2
|
||||||
|
- **Kerjakan:** `PinActionRedeem` di `customer_pin_processor.go`, ikut aturan kunci yang
|
||||||
|
ada (5 salah, 30 menit).
|
||||||
|
- **Bergantung pada:** –
|
||||||
|
|
||||||
|
### EG-504 · Redemption internal · L
|
||||||
|
- **RFC:** §7.4
|
||||||
|
- **Kerjakan:** `POST /customer/enakgame/vouchers/:id/redeem` untuk `STATIC` dan
|
||||||
|
`CODE_POOL`, satu transaksi, langkah persis §7.4. Debit `REWARD_REDEEM` dengan key
|
||||||
|
`redeem:{redemption}`.
|
||||||
|
- **Selesai jika:** test untuk:
|
||||||
|
- Stok tersisa 1, dua customer menukar bersamaan → tepat satu berhasil.
|
||||||
|
- `CODE_POOL`: dua redemption bersamaan mendapat kode berbeda (`SKIP LOCKED`).
|
||||||
|
- Key yang sama dua kali → satu debit, satu kode.
|
||||||
|
- Point kurang, PIN salah, `max_per_customer` tercapai, voucher di luar masa berlaku →
|
||||||
|
ditolak tanpa apa pun tercatat.
|
||||||
|
- **Bergantung pada:** EG-103, EG-501, EG-502, EG-503
|
||||||
|
|
||||||
|
### EG-505 · Atribusi realized cost · M
|
||||||
|
- **RFC:** §7.6, D5
|
||||||
|
- **Kerjakan:** query rekursif §7.6 di dalam transaksi redemption, pembagian
|
||||||
|
`face_value` proporsional dengan sisa pembulatan ke bagian terbesar, insert
|
||||||
|
`voucher_redemption_costs`.
|
||||||
|
- **Selesai jika:** test DB untuk rantai: `GAME_REWARD` → exchange → redeem;
|
||||||
|
`GAME_REWARD` → transfer → exchange → redeem; campuran `GAME_REWARD` + `EARN` (contoh
|
||||||
|
§7.6: Rp7.500 ke budget, Rp2.500 tanpa budget); `Σ cost = face_value` untuk kombinasi
|
||||||
|
angka yang tidak habis dibagi.
|
||||||
|
- **Bergantung pada:** EG-303, EG-504
|
||||||
|
|
||||||
|
### EG-506 · Customer: katalog & voucher saya · S
|
||||||
|
- **RFC:** §11 (customer)
|
||||||
|
- **Kerjakan:** `GET /customer/enakgame/vouchers` (stok tersedia, tanpa membocorkan
|
||||||
|
jumlah kode per status) dan `GET /redemptions` (dengan kode voucher).
|
||||||
|
- **Bergantung pada:** EG-504
|
||||||
|
|
||||||
|
### EG-507 · `VoucherCodeExpiryJob` · S
|
||||||
|
- **RFC:** §12
|
||||||
|
- **Kerjakan:** `AVAILABLE → EXPIRED` untuk kode lewat `expires_at`, per batch.
|
||||||
|
- **Bergantung pada:** EG-501
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Fase 6 — Budget Metrics
|
||||||
|
|
||||||
|
### EG-601 · Perhitungan metrik & status budget · M
|
||||||
|
- **RFC:** §10
|
||||||
|
- **Kerjakan:** realized cost, Coin issued, remaining, utilization, forecast, exposure,
|
||||||
|
dan status per budget. Global dibatasi periode; event tanpa batas waktu. Threshold dari
|
||||||
|
`game_budgets.thresholds`.
|
||||||
|
- **Selesai jika:** test dengan data tetap menghasilkan angka contoh PRD §30 (budget
|
||||||
|
Rp100M, realized Rp60M, sisa 10 hari); Point dari `EARN` tidak ikut dihitung.
|
||||||
|
- **Bergantung pada:** EG-505
|
||||||
|
|
||||||
|
### EG-602 · Endpoint metrik budget · S
|
||||||
|
- **Kerjakan:** `GET /marketing/enakgame/budgets/:id/metrics`.
|
||||||
|
- **Bergantung pada:** EG-601
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Fase 7 — Event / Campaign
|
||||||
|
|
||||||
|
### EG-701 · Migrasi event · S
|
||||||
|
- **RFC:** §5.5
|
||||||
|
- **Kerjakan:** `game_events`, `game_event_games`.
|
||||||
|
- **Selesai jika:** up/down bersih; event tanpa `budget_id` atau dengan
|
||||||
|
`end_at ≤ start_at` ditolak.
|
||||||
|
- **Bergantung pada:** EG-102
|
||||||
|
|
||||||
|
### EG-702 · Admin event · M
|
||||||
|
- **RFC:** §5.5, §11
|
||||||
|
- **Kerjakan:** CRUD + status. Budget yang dipasang harus milik org yang sama dan ber-scope
|
||||||
|
`EVENT`. Audit.
|
||||||
|
- **Bergantung pada:** EG-203, EG-701
|
||||||
|
|
||||||
|
### EG-703 · Modifier event di complete · M
|
||||||
|
- **RFC:** §7.2 langkah 7, §8 (modifier), D6
|
||||||
|
- **Kerjakan:** cari event aktif untuk game, hitung tambahan dari multiplier dan bonus,
|
||||||
|
pisahkan menjadi komponen per budget, terapkan `reward_limit` dan `user_daily_limit`
|
||||||
|
event lewat counter `EVENT`, cap `max_reward`. Aturan tumpuk mengikuti default PRD §16.
|
||||||
|
- **Selesai jika:** contoh PRD §7 (10 Coin + Ramadan 2x) menghasilkan dua baris
|
||||||
|
`GAME_REWARD`: 10 ke budget global, 10 ke budget event; event di luar jam aktif tidak
|
||||||
|
berpengaruh.
|
||||||
|
- **Bergantung pada:** EG-402, EG-702
|
||||||
|
|
||||||
|
### EG-704 · Event di daftar game customer · S
|
||||||
|
- **Kerjakan:** `GET /customer/enakgame/games` menyertakan event aktif per game (nama,
|
||||||
|
banner, multiplier/bonus, berakhir kapan).
|
||||||
|
- **Bergantung pada:** EG-206, EG-702
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Fase 8 — Voucher Eksternal
|
||||||
|
|
||||||
|
Terblokir sampai provider pertama ditentukan: API-nya menentukan bentuk adapter dan
|
||||||
|
apakah provider menerima idempotency key (RFC §18).
|
||||||
|
|
||||||
|
### EG-801 · Interface provider + adapter pertama · M
|
||||||
|
- **Kerjakan:** `VoucherProvider` (`Issue(ctx, redemptionID, voucher)`,
|
||||||
|
`Lookup(ctx, redemptionID)`), adapter provider pertama, dan klasifikasi hasil: sukses,
|
||||||
|
gagal pasti, tidak jelas.
|
||||||
|
- **Bergantung pada:** EG-504
|
||||||
|
|
||||||
|
### EG-802 · Redemption dua tahap · M
|
||||||
|
- **RFC:** §7.5
|
||||||
|
- **Kerjakan:** jalur `EXTERNAL` di endpoint redeem: transaksi 1 (`PENDING` + debit),
|
||||||
|
panggil provider di luar transaksi, transaksi 2 (`COMPLETED` + atribusi, atau `FAILED` +
|
||||||
|
`REWARD_REDEEM_REFUND`).
|
||||||
|
- **Selesai jika:** test dengan provider palsu untuk ketiga hasil; timeout meninggalkan
|
||||||
|
`PENDING` dengan Point terpotong dan response "sedang diproses".
|
||||||
|
- **Bergantung pada:** EG-505, EG-801
|
||||||
|
|
||||||
|
### EG-803 · `VoucherRedemptionRecoveryJob` · M
|
||||||
|
- **RFC:** §7.5 langkah 4, §12
|
||||||
|
- **Kerjakan:** ambil `PENDING` lewat N menit, `Lookup` ke provider, selesaikan transaksi 2.
|
||||||
|
Setelah batas percobaan → refund + `FAILED`.
|
||||||
|
- **Selesai jika:** tidak ada redemption yang tertinggal `PENDING` melewati batas
|
||||||
|
percobaan; job berjalan dua kali tidak merefund dua kali.
|
||||||
|
- **Bergantung pada:** EG-802
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Fase 9 — Budget Controller & Analytics
|
||||||
|
|
||||||
|
### EG-901 · Rekomendasi multiplier · M
|
||||||
|
- **RFC:** §10 (rekomendasi), PRD §30–§31
|
||||||
|
- **Kerjakan:** hitung multiplier yang membuat forecast = budget, dibatasi step maksimum dan
|
||||||
|
min/max multiplier. `GET /budgets/:id/recommendation`.
|
||||||
|
- **Bergantung pada:** EG-601
|
||||||
|
|
||||||
|
### EG-902 · Terima rekomendasi · S
|
||||||
|
- **Kerjakan:** admin menerima rekomendasi → reward config versi baru dibuat dari config
|
||||||
|
aktif dengan angka yang disesuaikan, tercatat di audit dengan `source = budget_controller`.
|
||||||
|
- **Bergantung pada:** EG-202, EG-901
|
||||||
|
|
||||||
|
### EG-903 · Analytics · M
|
||||||
|
- **RFC:** PRD §36
|
||||||
|
- **Kerjakan:** endpoint dashboard game (plays, completed, rata-rata skor & reward, Coin
|
||||||
|
issued, entry cost dibayar, Coin di-refund) dan economy (Coin generated / spent /
|
||||||
|
expired / outstanding, Point redeemed), per org dan rentang tanggal.
|
||||||
|
- **Bergantung pada:** EG-303, EG-505
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Fase 10 — Spin & Bersih-bersih
|
||||||
|
|
||||||
|
### EG-1001 · Spin sebagai game EnakGame · S
|
||||||
|
- **RFC:** §14
|
||||||
|
- **Kerjakan:** seeder / langkah admin untuk game spin baru dengan config `PROBABILITY` dan
|
||||||
|
reward Coin. Client Phaser di luar repo ini.
|
||||||
|
- **Selesai jika:** spin bisa dimainkan lewat `/customer/enakgame/sessions` end-to-end.
|
||||||
|
- **Bergantung pada:** EG-402
|
||||||
|
|
||||||
|
### EG-1002 · Hapus alur game lama · M
|
||||||
|
- **RFC:** §14, §15
|
||||||
|
- **Kerjakan:** hapus route `POST /customer/spin`, `GET /customer/games`,
|
||||||
|
`GET /customer/ferris-wheel`, admin `/marketing/games`, `/marketing/game-prizes`, dan
|
||||||
|
`/marketing/rewards`, beserta handler, service, processor, dan test-nya
|
||||||
|
(`GamePlayProcessor`, `SpinGameService`, dan seterusnya). **Tabel `games`,
|
||||||
|
`game_prizes`, `game_plays` tetap ada** untuk riwayat ledger.
|
||||||
|
- **Selesai jika:** build dan test lulus; aplikasi customer sudah tidak memanggil endpoint
|
||||||
|
lama (konfirmasi tim aplikasi).
|
||||||
|
- **Bergantung pada:** EG-1001. Tabel `rewards` tidak punya data produksi (dikonfirmasi
|
||||||
|
2026-10-07), jadi tidak ada yang dipindah ke `vouchers`.
|
||||||
|
- **Catatan:** endpoint customer lama boleh dimatikan **lebih awal**, kapan pun, untuk
|
||||||
|
menutup temuan RFC §15 nomor 1 dan 2.
|
||||||
|
|
||||||
|
### EG-1003 · Bersihkan kolom lama `games` · S
|
||||||
|
- **Kerjakan:** drop `games.is_active` dan berhenti membaca `metadata.coin_cost`.
|
||||||
|
- **Bergantung pada:** EG-1002
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Yang Bisa Dimulai Sekarang
|
||||||
|
|
||||||
|
Bisa dikerjakan paralel tanpa menunggu apa pun:
|
||||||
|
|
||||||
|
- **EG-001** (matikan bayar dengan EnakPoint) → **EG-002**
|
||||||
|
- **EG-101** → **EG-102** → **EG-105** (skema & repository)
|
||||||
|
- **EG-103** (tipe ledger)
|
||||||
|
- **EG-104** (audit), **EG-106** (setting limit)
|
||||||
|
- **EG-301** (Reward Engine, kode murni tanpa database)
|
||||||
|
- **EG-501**, **EG-503** (fondasi voucher)
|
||||||
|
|
||||||
|
Jalur kritis: **EG-105 → EG-204 → EG-303 → EG-402**. Hampir semua fase setelahnya
|
||||||
|
menunggu complete game selesai.
|
||||||
@@ -0,0 +1,445 @@
|
|||||||
|
# Task Breakdown: EnakPoint & EnakCoin
|
||||||
|
|
||||||
|
**Sumber:** [PRD EnakPoint & EnakCoin](prd-point-coin.md)
|
||||||
|
**Tanggal:** 2026-09-29
|
||||||
|
|
||||||
|
> **Catatan 2026-10-07:** fase 3 (Pembayaran EnakPoint) dihapus sesuai
|
||||||
|
> [`enakgame-prd.md`](./enakgame-prd.md) §3.2: EnakPoint hanya bisa ditukar ke voucher,
|
||||||
|
> bukan alat bayar. Payment method EnakPoint, kode bayar, bayar di kasir & app, refund
|
||||||
|
> EnakPoint, dan EnakPoint di laporan (PC-303 – PC-308) sudah dihapus dari backend
|
||||||
|
> (migrasi `000102`). PIN customer (PC-301) dan pengaturan loyalitas organisasi (PC-302)
|
||||||
|
> tetap dipakai. Sisa dokumen ini dibiarkan sebagai riwayat.
|
||||||
|
|
||||||
|
Setiap task menyebut bagian PRD yang dikerjakan, lapisan kode yang disentuh, task yang
|
||||||
|
harus selesai lebih dulu, dan kriteria selesai. Ukuran: **S** ≤ 1 hari, **M** 2–3 hari,
|
||||||
|
**L** 4–5 hari.
|
||||||
|
|
||||||
|
Konvensi kode mengikuti yang sudah ada: `migrations/` (lanjut dari `000089`),
|
||||||
|
`entities` → `repository` → `processor` → `service` → `handler` / `validator` →
|
||||||
|
`router`, dan wiring di `internal/app/app.go`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Ringkasan
|
||||||
|
|
||||||
|
| Fase | Task | Terblokir oleh catatan PRD |
|
||||||
|
|---|---|---|
|
||||||
|
| 1. Fondasi | PC-101 – PC-109 | – |
|
||||||
|
| 2. Earning | PC-201 – PC-205 | – |
|
||||||
|
| 3. Pembayaran EnakPoint | PC-301 – PC-308 | N2 (keuangan), N3 (legal) sebelum **rilis** |
|
||||||
|
| 4. Pergerakan saldo | PC-401 – PC-404 | N3 (legal) sebelum **rilis** |
|
||||||
|
| 5. Kedaluwarsa | PC-501 – PC-504 | N4 (model kedaluwarsa) sebelum **dikerjakan** |
|
||||||
|
| 6. Bersih-bersih | PC-601 – PC-602 | – |
|
||||||
|
|
||||||
|
Catatan N2 dan N3 hanya memblokir **rilis** fase 3–4, bukan pengerjaannya. N4
|
||||||
|
memblokir pengerjaan fase 5, karena rumus kedaluwarsanya belum ditentukan.
|
||||||
|
|
||||||
|
```
|
||||||
|
PC-101 ─┬─ PC-103 ── PC-104 ─┬─ PC-105 ── PC-106
|
||||||
|
│ ├─ PC-107
|
||||||
|
│ ├─ PC-108
|
||||||
|
│ ├─ PC-203 ── PC-204 ── PC-205
|
||||||
|
│ ├─ PC-305 ── PC-306 / PC-307
|
||||||
|
│ ├─ PC-401 / PC-402 / PC-403 / PC-404
|
||||||
|
│ └─ PC-502 ── PC-503
|
||||||
|
PC-102 ── PC-109 ─┬─ PC-201 ── PC-202 ── PC-203
|
||||||
|
└─ PC-302
|
||||||
|
PC-301 ── PC-304 ── PC-305
|
||||||
|
PC-303 ── PC-305
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Fase 1 — Fondasi
|
||||||
|
|
||||||
|
Semua fase lain bergantung pada fase ini. **PC-104 (wallet engine) adalah inti.** Tidak
|
||||||
|
ada kode lain yang boleh mengubah saldo tanpa lewat engine ini.
|
||||||
|
|
||||||
|
### PC-101 · Migrasi tabel wallet, ledger, dan lot · M
|
||||||
|
- **PRD:** §8 (`customer_wallets`, `wallet_transactions`, `wallet_lots`,
|
||||||
|
`wallet_lot_allocations`), K5, K9
|
||||||
|
- **Kerjakan:** migrasi `000090_create_wallet_tables` (up & down) dengan semua
|
||||||
|
`CHECK` constraint dan index persis seperti di §8.
|
||||||
|
- **Selesai jika:**
|
||||||
|
- Up dan down berjalan bersih di database kosong dan di salinan staging.
|
||||||
|
- Uji constraint langsung di SQL, masing-masing harus ditolak:
|
||||||
|
`PAYMENT` bercurrency `COIN`; `TRANSFER_IN` tanpa `counterparty_customer_id`;
|
||||||
|
`EARN_REVERSAL` tanpa `reverses_transaction_id`; `ADJUSTMENT` tanpa `reason`;
|
||||||
|
`EXPIRE` dengan `reference_type` selain `LOT`; saldo negatif; lot dengan
|
||||||
|
`remaining_amount > original_amount`.
|
||||||
|
- **Bergantung pada:** –
|
||||||
|
|
||||||
|
### PC-102 · Migrasi pengaturan organisasi dan riwayat perubahan setting · S
|
||||||
|
- **PRD:** F2, `loyalty_setting_changes` di §8
|
||||||
|
- **Kerjakan:** tabel `organization_settings` (key–value, pola sama dengan
|
||||||
|
`outlet_settings`, `UNIQUE(organization_id, key)`) dan `loyalty_setting_changes`.
|
||||||
|
Saat ini belum ada tempat menyimpan setting per organisasi.
|
||||||
|
- **Selesai jika:** up/down bersih.
|
||||||
|
- **Bergantung pada:** –
|
||||||
|
|
||||||
|
### PC-103 · Entities dan repository wallet · M
|
||||||
|
- **PRD:** §7.1–§7.4
|
||||||
|
- **Kerjakan:**
|
||||||
|
- Entities untuk empat tabel PC-101.
|
||||||
|
- Repository yang **selalu** memakai `DBFromContext` (berbeda dari repository
|
||||||
|
gamification yang sekarang memakai `r.db` langsung).
|
||||||
|
- `LockWallet(ctx, customerID)` dengan `SELECT … FOR UPDATE`. Membuat baris wallet
|
||||||
|
jika belum ada (`INSERT … ON CONFLICT DO NOTHING`, lalu lock).
|
||||||
|
- `LockWallets(ctx, a, b)` yang selalu mengunci berurutan berdasarkan `customer_id`.
|
||||||
|
- Update saldo bersyarat yang **mengembalikan error jika 0 baris ter-update**.
|
||||||
|
- Query lot aktif sesuai urutan K9: `expires_at NULLS LAST, created_at`.
|
||||||
|
- **Selesai jika:** test repository menunjukkan update bersyarat gagal saat saldo
|
||||||
|
kurang, dan dua goroutine yang mengunci wallet yang sama berjalan bergantian.
|
||||||
|
- **Bergantung pada:** PC-101
|
||||||
|
|
||||||
|
### PC-104 · Wallet engine (credit / debit / lot / idempotensi) · L
|
||||||
|
- **PRD:** K5, K6, K9, §7, §8.1
|
||||||
|
- **Kerjakan:** processor `WalletProcessor` sebagai **satu-satunya pintu** perubahan
|
||||||
|
saldo:
|
||||||
|
- `Credit(ctx, CreditInput)`: menulis ledger, membuat lot (dengan `expires_at` dan
|
||||||
|
`origin_lot_id` dari input), dan menambah saldo.
|
||||||
|
- `Debit(ctx, DebitInput)`: mengambil dari lot sesuai urutan K9 (atau dari lot
|
||||||
|
tertentu lebih dulu, untuk reversal di F10), menulis alokasi dan ledger, lalu
|
||||||
|
mengurangi saldo. Mengembalikan daftar alokasi, supaya transfer/exchange bisa
|
||||||
|
membuat lot penerima dengan `expires_at` yang sama.
|
||||||
|
- `DebitUpTo`: mengambil sebanyak yang tersedia, untuk reversal dengan shortfall
|
||||||
|
(F10, Q3).
|
||||||
|
- Idempotensi: jika `idempotency_key` sudah ada, kembalikan hasil pertama tanpa
|
||||||
|
mutasi baru.
|
||||||
|
- Validasi di level kode untuk aturan §8.1 (tipe ↔ currency ↔ referensi wajib),
|
||||||
|
sebagai lapisan kedua di atas constraint database.
|
||||||
|
- Semua method mewajibkan caller sudah berada di dalam transaksi dan wallet sudah
|
||||||
|
dikunci.
|
||||||
|
- **Selesai jika:** unit test mencakup debit yang melewati beberapa lot, urutan lot
|
||||||
|
dengan dan tanpa `expires_at`, debit melebihi saldo (ditolak), `DebitUpTo` dengan
|
||||||
|
shortfall, idempotency key ganda, dan saldo = `SUM(ledger)` = `SUM(lot.remaining)`
|
||||||
|
setelah setiap skenario.
|
||||||
|
- **Bergantung pada:** PC-103
|
||||||
|
|
||||||
|
### PC-105 · Migrasi data Point & Token lama · M
|
||||||
|
- **PRD:** §10, Q6
|
||||||
|
- **Kerjakan:** migrasi data (atau command satu kali) yang:
|
||||||
|
- Membuat wallet dari `customer_points` dan penjumlahan semua jenis
|
||||||
|
`customer_tokens`.
|
||||||
|
- Menulis ledger `MIGRATION` dan lot tanpa `expires_at` per customer per currency,
|
||||||
|
dengan rincian per jenis token di `metadata`.
|
||||||
|
- Mengganti `TOKENS` menjadi `COINS` di `campaigns.type` dan
|
||||||
|
`campaign_rules.reward_type`.
|
||||||
|
- **Selesai jika:** jumlah total Point dan Token sebelum = jumlah total saldo wallet
|
||||||
|
sesudah (diuji pada salinan data staging), dan migrasi aman dijalankan dua kali
|
||||||
|
(tidak menggandakan).
|
||||||
|
- **Bergantung pada:** PC-104
|
||||||
|
|
||||||
|
### PC-106 · Endpoint saldo & riwayat customer · M
|
||||||
|
- **PRD:** F6, §9 (customer app)
|
||||||
|
- **Kerjakan:** `GET /customer/wallet` dan `GET /customer/wallet/transactions`
|
||||||
|
(pagination, filter currency/tipe/tanggal). Ganti isi `/customer/points` dan
|
||||||
|
`/customer/tokens` menjadi alias yang membaca `customer_wallets`. Hapus pemakaian
|
||||||
|
`customer_points_repository` untuk saldo.
|
||||||
|
- **Selesai jika:** response menampilkan asal/tujuan setiap mutasi sesuai §8.1, dan
|
||||||
|
aplikasi lama yang memanggil `/points` / `/tokens` tetap mendapat angka yang benar.
|
||||||
|
- **Bergantung pada:** PC-105
|
||||||
|
|
||||||
|
### PC-107 · Wallet customer dan adjustment di dashboard · M
|
||||||
|
- **PRD:** F7
|
||||||
|
- **Kerjakan:** `GET /marketing/customers/:id/wallet` (saldo, lot aktif, mutasi) dan
|
||||||
|
`POST /marketing/customers/:id/wallet/adjust` (alasan wajib, tidak boleh membuat saldo
|
||||||
|
negatif, tercatat `created_by_user`).
|
||||||
|
- **Selesai jika:** adjustment muncul di riwayat customer dengan nama admin dan alasan.
|
||||||
|
Adjustment yang melebihi saldo ditolak.
|
||||||
|
- **Bergantung pada:** PC-104
|
||||||
|
|
||||||
|
### PC-108 · Job rekonsiliasi · S
|
||||||
|
- **PRD:** §7.5
|
||||||
|
- **Kerjakan:** query dan job terjadwal yang memeriksa semua invarian §7.5 dan
|
||||||
|
melaporkan selisih ke log dan notifikasi admin.
|
||||||
|
- **Selesai jika:** job menemukan selisih yang sengaja dibuat di data test, dan diam
|
||||||
|
saat data konsisten.
|
||||||
|
- **Bergantung pada:** PC-104
|
||||||
|
|
||||||
|
### PC-109 · Pembaca setting loyalitas dan riwayat perubahan · M
|
||||||
|
- **PRD:** F1, F2 (bagian mekanisme, bukan UI), §8 `loyalty_setting_changes`
|
||||||
|
- **Kerjakan:** service yang membaca setting outlet dan organisasi dengan nilai default
|
||||||
|
PRD bila key belum diisi, mengembalikan struct bertipe (bukan string mentah), dan
|
||||||
|
menulis `loyalty_setting_changes` setiap kali setting loyalitas diubah.
|
||||||
|
- **Selesai jika:** outlet tanpa setting mendapat semua default PRD, dan setiap
|
||||||
|
perubahan tercatat nilai lama, nilai baru, dan pelakunya.
|
||||||
|
- **Bergantung pada:** PC-102
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Fase 2 — Earning
|
||||||
|
|
||||||
|
### PC-201 · API pengaturan loyalitas outlet · M
|
||||||
|
- **PRD:** F1
|
||||||
|
- **Kerjakan:** `GET/PUT /outlets/:id/loyalty-settings` dengan validasi F1. Response
|
||||||
|
menyertakan **persentase cashback efektif** (`earn_value × nilai EnakPoint /
|
||||||
|
earn_per_amount`).
|
||||||
|
- **Selesai jika:** validasi menolak nilai di luar batas, dan hanya Admin/Manager yang
|
||||||
|
bisa mengubah.
|
||||||
|
- **Bergantung pada:** PC-109
|
||||||
|
|
||||||
|
### PC-202 · Kalkulator earning · S
|
||||||
|
- **PRD:** F1 (rumus), Q1, Q10
|
||||||
|
- **Kerjakan:** fungsi murni `CalculateEarning(order, pointPaidAmount, settings)` yang
|
||||||
|
mengembalikan Point, Coin, basis, dan snapshot setting.
|
||||||
|
- **Selesai jika:** unit test mencakup contoh di PRD (Rp 87.500 → 875 Point, 3 Coin;
|
||||||
|
dengan Rp 20.000 dibayar EnakPoint → 675 Point, 2 Coin), basis di bawah minimum,
|
||||||
|
`max_per_order`, setting nonaktif, dan pajak tidak ikut dihitung.
|
||||||
|
- **Bergantung pada:** PC-201
|
||||||
|
|
||||||
|
### PC-203 · Earning saat order lunas · L
|
||||||
|
- **PRD:** F3
|
||||||
|
- **Kerjakan:**
|
||||||
|
- **Satukan titik "order menjadi lunas".** Saat ini `payment_status = completed`
|
||||||
|
di-set di empat tempat: `OrderProcessorImpl.UpdateOrder`,
|
||||||
|
`OrderProcessorImpl.updateOrderStatus`, dan dua tempat di `split_bill_processor.go`.
|
||||||
|
Buat satu hook `onOrderPaid(orderID)` yang dipanggil dari keempatnya.
|
||||||
|
- Hook menjalankan earning **setelah** transaksi pembayaran commit, sehingga
|
||||||
|
kegagalan earning tidak menggagalkan pembayaran.
|
||||||
|
- Idempotency key `earn:{order_id}:{currency}`.
|
||||||
|
- Lewati order tanpa customer, customer default, atau customer nonaktif.
|
||||||
|
- **Jaring pengaman:** job yang mencari order lunas beberapa hari terakhir yang belum
|
||||||
|
punya `EARN` (dan seharusnya punya), lalu menjalankan ulang earning.
|
||||||
|
- **Selesai jika:** test untuk pembayaran penuh, split bill (lunas di pembayaran
|
||||||
|
terakhir), self-order, dan pemanggilan ganda (hasilnya tetap satu earning). Earning
|
||||||
|
yang sengaja digagalkan tidak menggagalkan pembayaran dan terambil oleh job.
|
||||||
|
- **Bergantung pada:** PC-104, PC-202
|
||||||
|
|
||||||
|
### PC-204 · Reversal earning saat void / refund · M
|
||||||
|
- **PRD:** F10, Q3
|
||||||
|
- **Kerjakan:** panggil reversal dari `VoidOrder`, `RefundOrder`, dan `RefundPayment`.
|
||||||
|
Ambil pertama dari lot `EARN` order tersebut, lalu lot lain. Gunakan `DebitUpTo` dan
|
||||||
|
catat `shortfall`. Refund tidak pernah diblokir.
|
||||||
|
- **Selesai jika:** test untuk void penuh, refund sebagian (proporsional, akumulasi tidak
|
||||||
|
melebihi earning), dan saldo yang sudah terpakai (shortfall tercatat, saldo 0).
|
||||||
|
- **Bergantung pada:** PC-203
|
||||||
|
|
||||||
|
### PC-205 · Tampilkan earning di order dan struk · S
|
||||||
|
- **PRD:** F3
|
||||||
|
- **Kerjakan:** tambah `points_earned` dan `coins_earned` ke response order dan data
|
||||||
|
struk.
|
||||||
|
- **Selesai jika:** nilai sama dengan baris `EARN` di ledger, dan bernilai 0 untuk order
|
||||||
|
tanpa earning.
|
||||||
|
- **Bergantung pada:** PC-203
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Fase 3 — Pembayaran EnakPoint
|
||||||
|
|
||||||
|
> Boleh dikerjakan sekarang. **Tidak boleh dirilis** sebelum catatan N2 (keuangan) dan
|
||||||
|
> N3 (legal) ditutup.
|
||||||
|
|
||||||
|
### PC-301 · PIN customer · L
|
||||||
|
- **PRD:** K8, F11, Q16, Q17
|
||||||
|
- **Kerjakan:**
|
||||||
|
- Migrasi kolom PIN di `customers` dan tabel `customer_security_events`.
|
||||||
|
- Purpose OTP baru `pin_setup` dan `pin_reset` di `OtpProcessor`.
|
||||||
|
- Endpoint `/customer/pin/*` (status, OTP, buat, ganti, reset).
|
||||||
|
- Hash bcrypt, tolak PIN lemah (digit sama, berurutan, tanggal lahir).
|
||||||
|
- Kunci 30 menit setelah 5 kali salah, dengan penghitung di database.
|
||||||
|
- Tahan transfer keluar 24 jam setelah reset.
|
||||||
|
- `VerifyPin(ctx, customerID, pin)` untuk dipakai task lain, dengan error
|
||||||
|
`PIN_NOT_SET`, `PIN_INVALID`, `PIN_LOCKED`, `TRANSFER_BLOCKED`.
|
||||||
|
- Hapus PIN oleh admin: `DELETE /marketing/customers/:id/pin`, dan
|
||||||
|
`GET /marketing/customers/:id/security-events`.
|
||||||
|
- PIN tidak pernah muncul di log (termasuk log request body).
|
||||||
|
- **Selesai jika:** test untuk semua aturan di atas, termasuk 5 kali salah lalu PIN
|
||||||
|
benar tetap ditolak selama terkunci, dan reset OTP membuka kunci.
|
||||||
|
- **Bergantung pada:** –
|
||||||
|
|
||||||
|
### PC-302 · API pengaturan loyalitas organisasi · S
|
||||||
|
- **PRD:** F2
|
||||||
|
- **Kerjakan:** `GET/PUT /marketing/loyalty-settings` untuk nilai EnakPoint, kurs
|
||||||
|
exchange, dan batas transfer, serta `GET /marketing/loyalty-settings/history`.
|
||||||
|
Sebelum menyimpan perubahan nilai EnakPoint atau kurs, response preview menampilkan
|
||||||
|
total saldo beredar dan nilai rupiahnya sebelum/sesudah.
|
||||||
|
- **Selesai jika:** perubahan tercatat di riwayat, dan transaksi lama tetap memakai nilai
|
||||||
|
yang dibekukan.
|
||||||
|
- **Bergantung pada:** PC-109
|
||||||
|
|
||||||
|
### PC-303 · Payment method EnakPoint · M
|
||||||
|
- **PRD:** F9 (payment method), §8 (perubahan `payments`), §10.5
|
||||||
|
- **Kerjakan:**
|
||||||
|
- Tambah tipe `point` ke `PaymentMethodType` dan validator (`oneof=cash card
|
||||||
|
digital_wallet point`).
|
||||||
|
- Migrasi kolom `points_used` dan `point_value` di `payments`.
|
||||||
|
- Buat payment method sistem "EnakPoint" untuk setiap organisasi yang sudah ada, dan
|
||||||
|
otomatis untuk organisasi baru.
|
||||||
|
- Tolak hapus / ubah tipe method sistem.
|
||||||
|
- Sembunyikan method ini di kasir jika outlet tidak mengaktifkan `accept_payment`.
|
||||||
|
- **Selesai jika:** setiap organisasi punya tepat satu method EnakPoint yang tidak bisa
|
||||||
|
dihapus.
|
||||||
|
- **Bergantung pada:** –
|
||||||
|
|
||||||
|
### PC-304 · Kode bayar sekali pakai · M
|
||||||
|
- **PRD:** F9 (persetujuan customer), K8
|
||||||
|
- **Kerjakan:** `POST /customer/wallet/payment-code` (butuh PIN) menghasilkan kode 6
|
||||||
|
digit dan QR yang berlaku 2 menit, disimpan di Redis dengan TTL dan diambil
|
||||||
|
sekali-pakai (`GETDEL`). Kode terikat ke `customer_id`.
|
||||||
|
- **Selesai jika:** kode kedaluwarsa, kode yang sudah dipakai, dan kode milik customer
|
||||||
|
lain semuanya ditolak.
|
||||||
|
- **Bergantung pada:** PC-301
|
||||||
|
|
||||||
|
### PC-305 · Bayar EnakPoint di kasir · L
|
||||||
|
- **PRD:** F9 (perhitungan, pencatatan), K7
|
||||||
|
- **Kerjakan:**
|
||||||
|
- `GET /orders/:id/point-payment/preview`.
|
||||||
|
- Cabang method `point` di `CreatePayment`: validasi kode bayar, cocokkan customer
|
||||||
|
order, hitung `maks_point`, lalu lakukan langkah 1–6 F9 dalam **satu transaksi**
|
||||||
|
bersama pembuatan baris `payments`.
|
||||||
|
- Idempotency `payment:{payment_id}`.
|
||||||
|
- Tolak jika `nominal_rupiah > remaining_amount` (tidak ada kembalian).
|
||||||
|
- **Selesai jika:** test untuk pembayaran penuh, sebagian + tunai (split), batas
|
||||||
|
`max_payment_percent`, order walk-in (ditolak), kode salah (ditolak), dan dua
|
||||||
|
pembayaran bersamaan untuk customer yang sama (saldo tidak terpakai dua kali).
|
||||||
|
Earning (PC-203) menghitung basis tanpa bagian EnakPoint.
|
||||||
|
- **Bergantung pada:** PC-104, PC-303, PC-304
|
||||||
|
|
||||||
|
### PC-306 · Bayar EnakPoint dari app / self-order · M
|
||||||
|
- **PRD:** F9
|
||||||
|
- **Kerjakan:** `POST /customer/orders/:id/pay-with-points` (butuh PIN, hanya untuk
|
||||||
|
order milik customer itu sendiri), memakai logika yang sama dengan PC-305.
|
||||||
|
- **Selesai jika:** customer tidak bisa membayar order milik customer lain.
|
||||||
|
- **Bergantung pada:** PC-305
|
||||||
|
|
||||||
|
### PC-307 · Refund pembayaran EnakPoint · M
|
||||||
|
- **PRD:** F9 (void/refund), K7, Q13
|
||||||
|
- **Kerjakan:** `PAYMENT_REFUND` di jalur void dan refund memakai `point_value` yang
|
||||||
|
dibekukan, dengan pembulatan ke bawah. Kembalikan ke lot dengan `expires_at` asal
|
||||||
|
(aturan perpanjangan 7 hari mengikuti N4, jadi untuk sekarang cukup pakai tanggal
|
||||||
|
asal). **Tolak** permintaan refund bagian EnakPoint lewat method lain.
|
||||||
|
- **Selesai jika:** test untuk void penuh, refund sebagian, perubahan nilai EnakPoint di
|
||||||
|
antara bayar dan refund (jumlah EnakPoint yang kembali tetap sama), dan percobaan
|
||||||
|
refund tunai atas pembayaran EnakPoint (ditolak).
|
||||||
|
- **Bergantung pada:** PC-305
|
||||||
|
|
||||||
|
### PC-308 · EnakPoint di laporan · S
|
||||||
|
- **PRD:** F9 (laporan)
|
||||||
|
- **Kerjakan:** laporan per payment method menampilkan EnakPoint terpisah dan tidak
|
||||||
|
menghitungnya sebagai kas masuk. Cek laporan analytics yang menjumlahkan pembayaran.
|
||||||
|
- **Selesai jika:** total kas masuk di laporan tidak berubah saat sebagian order dibayar
|
||||||
|
EnakPoint. Perlakuan akuntansi lanjutan menunggu N2.
|
||||||
|
- **Bergantung pada:** PC-305
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Fase 4 — Pergerakan Saldo
|
||||||
|
|
||||||
|
> Boleh dikerjakan sekarang. Transfer (PC-402) **tidak boleh dirilis** sebelum N3
|
||||||
|
> (legal) ditutup.
|
||||||
|
|
||||||
|
### PC-401 · Exchange EnakCoin → EnakPoint · M
|
||||||
|
- **PRD:** F4, K3
|
||||||
|
- **Kerjakan:** `GET /customer/wallet/exchange/preview` dan
|
||||||
|
`POST /customer/wallet/exchange` (butuh PIN, `Idempotency-Key`). Jumlah harus
|
||||||
|
kelipatan `coin_amount`. Kurs dibekukan di metadata. Lot EnakPoint kedaluwarsa pada
|
||||||
|
`min(lot EnakCoin asal, sekarang + masa berlaku EnakPoint)`.
|
||||||
|
- **Selesai jika:** test untuk kurs default 1:1, kurs 10:3, jumlah bukan kelipatan
|
||||||
|
(ditolak), dan `expires_at` lot hasil exchange tidak pernah lebih lama dari lot asal.
|
||||||
|
- **Bergantung pada:** PC-104, PC-301, PC-302
|
||||||
|
|
||||||
|
### PC-402 · Transfer antar customer · L
|
||||||
|
- **PRD:** F5, Q4, Q16
|
||||||
|
- **Kerjakan:** `GET /customer/wallet/transfer/recipient` (nama disamarkan) dan
|
||||||
|
`POST /customer/wallet/transfer` (butuh PIN, `Idempotency-Key`). Kunci dua wallet
|
||||||
|
berurutan, cek batas organisasi (per transaksi dan harian), cek
|
||||||
|
`transfer_blocked_until`. Lot penerima mewarisi `expires_at` dan `origin_lot_id` dari
|
||||||
|
lot pengirim. Kirim notifikasi push ke penerima.
|
||||||
|
- **Selesai jika:** test untuk transfer ke diri sendiri / customer lain organisasi /
|
||||||
|
customer default (semua ditolak), batas harian, transfer dua arah bersamaan (tidak
|
||||||
|
deadlock), dan `expires_at` di penerima sama persis dengan pengirim.
|
||||||
|
- **Bergantung pada:** PC-104, PC-301, PC-302
|
||||||
|
|
||||||
|
### PC-403 · Semua game memakai EnakCoin · M
|
||||||
|
- **PRD:** F8, K1
|
||||||
|
- **Kerjakan:**
|
||||||
|
- `GamePlayProcessor.PlayGame` memotong EnakCoin lewat wallet engine sesuai
|
||||||
|
`games.metadata.coin_cost`.
|
||||||
|
- Seluruh permainan dalam satu transaksi: ubah repository game, game play, dan game
|
||||||
|
prize ke `DBFromContext`. Gagal mengurangi stok hadiah membatalkan permainan (saat
|
||||||
|
ini hanya di-`Printf`), dan rollback manual `AddTokens` dihapus.
|
||||||
|
- Rename `game_plays.token_used` menjadi `coins_used`.
|
||||||
|
- **Selesai jika:** test untuk saldo kurang (ditolak, tidak ada `game_plays` yang
|
||||||
|
tercatat), stok hadiah gagal (semua dibatalkan), dan `GAME_SPEND` menunjuk
|
||||||
|
`game_plays.id`.
|
||||||
|
- **Bergantung pada:** PC-104
|
||||||
|
|
||||||
|
### PC-404 · Telusuri per butir di dashboard · S
|
||||||
|
- **PRD:** F7, §8.1 (per butir)
|
||||||
|
- **Kerjakan:** `GET /marketing/wallet-transactions/:id/trace` yang mengembalikan
|
||||||
|
alokasi lot dan rantai `origin_lot_id` sampai ke lot pertama.
|
||||||
|
- **Selesai jika:** contoh di §8 (A transfer 120 ke B, B bayar 30) menelusuri ke order
|
||||||
|
#ORD-1 milik A.
|
||||||
|
- **Bergantung pada:** PC-402
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Fase 5 — Kedaluwarsa
|
||||||
|
|
||||||
|
> **Jangan dikerjakan sebelum catatan N4 (model kedaluwarsa) diputuskan.** Struktur lot
|
||||||
|
> sudah ada sejak PC-101, jadi yang tersisa hanya rumus, job, dan tampilan.
|
||||||
|
|
||||||
|
### PC-501 · Setting kedaluwarsa · M
|
||||||
|
- **PRD:** F12 (pengaturan), N4
|
||||||
|
- **Kerjakan:** key setting sesuai model yang dipilih di N4, dengan validasi dan preview
|
||||||
|
"saldo yang didapat hari ini kedaluwarsa pada …".
|
||||||
|
- **Bergantung pada:** PC-302, **N4**
|
||||||
|
|
||||||
|
### PC-502 · Hitung `expires_at` saat lot dibuat · M
|
||||||
|
- **PRD:** F12 (tabel kedaluwarsa per lot), N4
|
||||||
|
- **Kerjakan:** satu fungsi `ComputeExpiry(currency, receivedAt, settings)` yang dipakai
|
||||||
|
oleh `EARN` dan `ADJUSTMENT`, serta aturan aktivasi pertama untuk lot lama (termasuk
|
||||||
|
lot `MIGRATION`).
|
||||||
|
- **Bergantung pada:** PC-104, PC-501
|
||||||
|
|
||||||
|
### PC-503 · Job kedaluwarsa · M
|
||||||
|
- **PRD:** F12 (proses kedaluwarsa)
|
||||||
|
- **Kerjakan:** job per jam yang memproses lot lewat tanggal dengan `EXPIRE`
|
||||||
|
(idempotency `expire:{lot_id}`) di bawah lock wallet.
|
||||||
|
- **Jangan menyalin pola `OmsetMilestoneScheduler`.** Scheduler itu menyimpan state di
|
||||||
|
memori, dan menurut komentarnya sendiri bisa mengirim ulang notifikasi setelah
|
||||||
|
restart. Job ini harus aman dijalankan di banyak instance sekaligus: pilih lot
|
||||||
|
dengan `FOR UPDATE SKIP LOCKED`, dan andalkan idempotency key.
|
||||||
|
- **Selesai jika:** dua instance yang berjalan bersamaan tidak menghanguskan lot yang
|
||||||
|
sama dua kali, dan tidak ada lot yang lewat tanggal lebih dari 1 jam tanpa diproses.
|
||||||
|
- **Bergantung pada:** PC-502
|
||||||
|
|
||||||
|
### PC-504 · Pengingat dan tampilan saldo yang akan kedaluwarsa · M
|
||||||
|
- **PRD:** F6 (`/wallet/expiring`), F12 (pengingat)
|
||||||
|
- **Kerjakan:** endpoint `GET /customer/wallet/expiring`, field saldo kedaluwarsa
|
||||||
|
terdekat di `/wallet`, dan notifikasi pengingat yang dikelompokkan per tanggal.
|
||||||
|
Jadwal pengingat mengikuti N4.
|
||||||
|
- **Bergantung pada:** PC-503
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Fase 6 — Bersih-bersih
|
||||||
|
|
||||||
|
### PC-601 · Hapus tabel dan kode lama · S
|
||||||
|
- **PRD:** §10.7
|
||||||
|
- **Kerjakan:** satu rilis setelah PC-105 berjalan di production, drop
|
||||||
|
`customer_points` dan `customer_tokens`. Hapus `CustomerPointsProcessor` dan
|
||||||
|
`CustomerTokensProcessor` beserta stub `not implemented`, rute yang di-comment di
|
||||||
|
`router.go`, dan alias `/customer/points` / `/customer/tokens` setelah aplikasi
|
||||||
|
diperbarui.
|
||||||
|
- **Bergantung pada:** PC-106, PC-403, dan konfirmasi bahwa aplikasi sudah tidak
|
||||||
|
memanggil endpoint lama.
|
||||||
|
|
||||||
|
### PC-602 · Dokumentasi integrasi · S
|
||||||
|
- **Kerjakan:** panduan integrasi untuk tim aplikasi dan POS (seperti
|
||||||
|
`integration-weight-based-products.md`): endpoint, kode error PIN, alur kode bayar, dan
|
||||||
|
contoh request/response.
|
||||||
|
- **Bergantung pada:** PC-305, PC-402
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Yang Bisa Dimulai Sekarang
|
||||||
|
|
||||||
|
Bisa dikerjakan paralel tanpa menunggu apa pun:
|
||||||
|
- **PC-101** (migrasi wallet) → langsung lanjut **PC-103**, lalu **PC-104**
|
||||||
|
- **PC-102** (setting organisasi) → **PC-109**
|
||||||
|
- **PC-301** (PIN customer)
|
||||||
|
- **PC-303** (payment method EnakPoint)
|
||||||
|
|
||||||
|
PC-104 adalah jalur kritis: hampir semua task lain menunggunya.
|
||||||
@@ -76,7 +76,6 @@ require (
|
|||||||
github.com/subosito/gotenv v1.4.2 // indirect
|
github.com/subosito/gotenv v1.4.2 // indirect
|
||||||
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
|
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
|
||||||
github.com/ugorji/go/codec v1.2.12 // indirect
|
github.com/ugorji/go/codec v1.2.12 // indirect
|
||||||
github.com/yuin/gopher-lua v1.1.1 // indirect
|
|
||||||
github.com/zeebo/errs v1.4.0 // indirect
|
github.com/zeebo/errs v1.4.0 // indirect
|
||||||
go.opentelemetry.io/auto/sdk v1.1.0 // indirect
|
go.opentelemetry.io/auto/sdk v1.1.0 // indirect
|
||||||
go.opentelemetry.io/contrib/detectors/gcp v1.35.0 // indirect
|
go.opentelemetry.io/contrib/detectors/gcp v1.35.0 // indirect
|
||||||
@@ -108,7 +107,6 @@ require (
|
|||||||
|
|
||||||
require (
|
require (
|
||||||
firebase.google.com/go/v4 v4.19.0
|
firebase.google.com/go/v4 v4.19.0
|
||||||
github.com/alicebob/miniredis/v2 v2.39.0
|
|
||||||
github.com/aws/aws-sdk-go v1.55.7
|
github.com/aws/aws-sdk-go v1.55.7
|
||||||
github.com/boombuler/barcode v1.1.0
|
github.com/boombuler/barcode v1.1.0
|
||||||
github.com/golang-jwt/jwt/v5 v5.2.3
|
github.com/golang-jwt/jwt/v5 v5.2.3
|
||||||
|
|||||||
@@ -74,8 +74,6 @@ github.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/resourcemapp
|
|||||||
github.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/resourcemapping v0.51.0/go.mod h1:otE2jQekW/PqXk1Awf5lmfokJx4uwuqcj1ab5SpGeW0=
|
github.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/resourcemapping v0.51.0/go.mod h1:otE2jQekW/PqXk1Awf5lmfokJx4uwuqcj1ab5SpGeW0=
|
||||||
github.com/MicahParks/keyfunc v1.9.0 h1:lhKd5xrFHLNOWrDc4Tyb/Q1AJ4LCzQ48GVJyVIID3+o=
|
github.com/MicahParks/keyfunc v1.9.0 h1:lhKd5xrFHLNOWrDc4Tyb/Q1AJ4LCzQ48GVJyVIID3+o=
|
||||||
github.com/MicahParks/keyfunc v1.9.0/go.mod h1:IdnCilugA0O/99dW+/MkvlyrsX8+L8+x95xuVNtM5jw=
|
github.com/MicahParks/keyfunc v1.9.0/go.mod h1:IdnCilugA0O/99dW+/MkvlyrsX8+L8+x95xuVNtM5jw=
|
||||||
github.com/alicebob/miniredis/v2 v2.39.0 h1:M7WbmV5BmV56L8KTG0rw6vEQ+woTOghpDgin2xv4A0g=
|
|
||||||
github.com/alicebob/miniredis/v2 v2.39.0/go.mod h1:TcL7YfarKPGDAthEtl5NBeHZfeUQj6OXMm/+iu5cLMM=
|
|
||||||
github.com/aws/aws-sdk-go v1.55.7 h1:UJrkFq7es5CShfBwlWAC8DA077vp8PyVbQd3lqLiztE=
|
github.com/aws/aws-sdk-go v1.55.7 h1:UJrkFq7es5CShfBwlWAC8DA077vp8PyVbQd3lqLiztE=
|
||||||
github.com/aws/aws-sdk-go v1.55.7/go.mod h1:eRwEWoyTWFMVYVQzKMNHWP5/RV4xIUGMQfXQHfHkpNU=
|
github.com/aws/aws-sdk-go v1.55.7/go.mod h1:eRwEWoyTWFMVYVQzKMNHWP5/RV4xIUGMQfXQHfHkpNU=
|
||||||
github.com/benbjohnson/clock v1.1.0 h1:Q92kusRqC1XV2MjkWETPvjJVqKetz1OzxZB7mHJLju8=
|
github.com/benbjohnson/clock v1.1.0 h1:Q92kusRqC1XV2MjkWETPvjJVqKetz1OzxZB7mHJLju8=
|
||||||
@@ -351,8 +349,6 @@ github.com/yuin/goldmark v1.1.32/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9de
|
|||||||
github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
|
github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
|
||||||
github.com/yuin/goldmark v1.3.5/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k=
|
github.com/yuin/goldmark v1.3.5/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k=
|
||||||
github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
|
github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
|
||||||
github.com/yuin/gopher-lua v1.1.1 h1:kYKnWBjvbNP4XLT3+bPEwAXJx262OhaHDWDVOPjL46M=
|
|
||||||
github.com/yuin/gopher-lua v1.1.1/go.mod h1:GBR0iDaNXjAgGg9zfCvksxSRnQx76gclCIb7kdAd1Pw=
|
|
||||||
github.com/zeebo/errs v1.4.0 h1:XNdoD/RRMKP7HD0UhJnIzUy74ISdGGxURlYG8HSWSfM=
|
github.com/zeebo/errs v1.4.0 h1:XNdoD/RRMKP7HD0UhJnIzUy74ISdGGxURlYG8HSWSfM=
|
||||||
github.com/zeebo/errs v1.4.0/go.mod h1:sgbWHsvVuTPHcqJJGQ1WhI5KbWlHYz+2+2C/LSEtCw4=
|
github.com/zeebo/errs v1.4.0/go.mod h1:sgbWHsvVuTPHcqJJGQ1WhI5KbWlHYz+2+2C/LSEtCw4=
|
||||||
github.com/zeebo/xxh3 v1.1.0 h1:s7DLGDK45Dyfg7++yxI0khrfwq9661w9EN78eP/UZVs=
|
github.com/zeebo/xxh3 v1.1.0 h1:s7DLGDK45Dyfg7++yxI0khrfwq9661w9EN78eP/UZVs=
|
||||||
|
|||||||
+2
-16
@@ -161,8 +161,6 @@ func (a *App) Initialize(cfg *config.Config) error {
|
|||||||
validators.walletValidator,
|
validators.walletValidator,
|
||||||
services.loyaltySettingsService,
|
services.loyaltySettingsService,
|
||||||
services.customerPinService,
|
services.customerPinService,
|
||||||
services.pointPaymentService,
|
|
||||||
services.customerOrderPaymentService,
|
|
||||||
services.customerWalletService,
|
services.customerWalletService,
|
||||||
services.customerDeviceService,
|
services.customerDeviceService,
|
||||||
services.customerOutletService,
|
services.customerOutletService,
|
||||||
@@ -399,8 +397,6 @@ type processors struct {
|
|||||||
loyaltySettingsProcessor *processor.LoyaltySettingsProcessor
|
loyaltySettingsProcessor *processor.LoyaltySettingsProcessor
|
||||||
earningProcessor *processor.EarningProcessor
|
earningProcessor *processor.EarningProcessor
|
||||||
customerPinProcessor *processor.CustomerPinProcessor
|
customerPinProcessor *processor.CustomerPinProcessor
|
||||||
paymentCodeProcessor *processor.PaymentCodeProcessor
|
|
||||||
pointPaymentProcessor *processor.PointPaymentProcessor
|
|
||||||
walletExchangeProcessor *processor.WalletExchangeProcessor
|
walletExchangeProcessor *processor.WalletExchangeProcessor
|
||||||
walletTransferProcessor *processor.WalletTransferProcessor
|
walletTransferProcessor *processor.WalletTransferProcessor
|
||||||
walletTraceProcessor *processor.WalletTraceProcessor
|
walletTraceProcessor *processor.WalletTraceProcessor
|
||||||
@@ -418,7 +414,6 @@ func (a *App) initProcessors(cfg *config.Config, repos *repositories) *processor
|
|||||||
otpProcessor := processor.NewOtpProcessor(fonnteClient, repos.otpRepo)
|
otpProcessor := processor.NewOtpProcessor(fonnteClient, repos.otpRepo)
|
||||||
// Customer PIN (docs/prd-point-coin.md F11)
|
// Customer PIN (docs/prd-point-coin.md F11)
|
||||||
customerPinProcessor := processor.NewCustomerPinProcessor(repository.NewCustomerPinRepository(a.db), otpProcessor, customerDeviceProcessor)
|
customerPinProcessor := processor.NewCustomerPinProcessor(repository.NewCustomerPinRepository(a.db), otpProcessor, customerDeviceProcessor)
|
||||||
paymentCodeProcessor := processor.NewPaymentCodeProcessor(repository.NewPaymentCodeRepository(a.redisClient), customerPinProcessor)
|
|
||||||
inventoryMovementService := service.NewInventoryMovementService(repos.inventoryMovementRepo, repos.ingredientRepo)
|
inventoryMovementService := service.NewInventoryMovementService(repos.inventoryMovementRepo, repos.ingredientRepo)
|
||||||
|
|
||||||
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)
|
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)
|
||||||
@@ -426,9 +421,6 @@ func (a *App) initProcessors(cfg *config.Config, repos *repositories) *processor
|
|||||||
// Earn EnakPoint and EnakCoin when an order becomes fully paid (docs/prd-point-coin.md F3)
|
// 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)
|
earningProcessor := processor.NewEarningProcessor(repository.NewEarningRepository(a.db), loyaltySettingsProcessor, processor.NewWalletProcessor(repos.walletRepo), repos.txManager)
|
||||||
orderProcessor.SetLoyalty(earningProcessor)
|
orderProcessor.SetLoyalty(earningProcessor)
|
||||||
// Pay orders with EnakPoint, approved by the customer's one-time code (docs/prd-point-coin.md F9)
|
|
||||||
pointPaymentProcessor := processor.NewPointPaymentProcessor(repository.NewPointPaymentRepository(a.db), loyaltySettingsProcessor, repos.walletQueryRepo, processor.NewWalletProcessor(repos.walletRepo), repos.txManager)
|
|
||||||
orderProcessor.SetPointPayments(pointPaymentProcessor, paymentCodeProcessor, customerPinProcessor)
|
|
||||||
// Exchange EnakCoin into EnakPoint, approved by the customer's PIN (docs/prd-point-coin.md F4)
|
// Exchange EnakCoin into EnakPoint, approved by the customer's PIN (docs/prd-point-coin.md F4)
|
||||||
walletExchangeProcessor := processor.NewWalletExchangeProcessor(repository.NewWalletMoveRepository(a.db), loyaltySettingsProcessor, repos.walletQueryRepo, customerPinProcessor, processor.NewWalletProcessor(repos.walletRepo), repos.txManager)
|
walletExchangeProcessor := processor.NewWalletExchangeProcessor(repository.NewWalletMoveRepository(a.db), loyaltySettingsProcessor, repos.walletQueryRepo, customerPinProcessor, processor.NewWalletProcessor(repos.walletRepo), repos.txManager)
|
||||||
// Send EnakPoint or EnakCoin to another customer; the recipient gets a push through FCM (docs/prd-point-coin.md F5)
|
// Send EnakPoint or EnakCoin to another customer; the recipient gets a push through FCM (docs/prd-point-coin.md F5)
|
||||||
@@ -444,7 +436,7 @@ func (a *App) initProcessors(cfg *config.Config, repos *repositories) *processor
|
|||||||
productVariantProcessor: processor.NewProductVariantProcessorImpl(repos.productVariantRepo, repos.productRepo),
|
productVariantProcessor: processor.NewProductVariantProcessorImpl(repos.productVariantRepo, repos.productRepo),
|
||||||
inventoryProcessor: processor.NewInventoryProcessorImpl(repos.inventoryRepo, repos.productRepo, repos.outletRepo, repos.ingredientRepo, repos.inventoryMovementRepo),
|
inventoryProcessor: processor.NewInventoryProcessorImpl(repos.inventoryRepo, repos.productRepo, repos.outletRepo, repos.ingredientRepo, repos.inventoryMovementRepo),
|
||||||
orderProcessor: orderProcessor,
|
orderProcessor: orderProcessor,
|
||||||
paymentMethodProcessor: processor.NewPaymentMethodProcessorImpl(repos.paymentMethodRepo, loyaltySettingsProcessor),
|
paymentMethodProcessor: processor.NewPaymentMethodProcessorImpl(repos.paymentMethodRepo),
|
||||||
fileProcessor: processor.NewFileProcessorImpl(repos.fileRepo, fileClient),
|
fileProcessor: processor.NewFileProcessorImpl(repos.fileRepo, fileClient),
|
||||||
customerProcessor: processor.NewCustomerProcessor(repos.customerRepo),
|
customerProcessor: processor.NewCustomerProcessor(repos.customerRepo),
|
||||||
analyticsProcessor: processor.NewAnalyticsProcessorImpl(repos.analyticsRepo, repos.expenseRepo),
|
analyticsProcessor: processor.NewAnalyticsProcessorImpl(repos.analyticsRepo, repos.expenseRepo),
|
||||||
@@ -482,8 +474,6 @@ func (a *App) initProcessors(cfg *config.Config, repos *repositories) *processor
|
|||||||
loyaltySettingsProcessor: loyaltySettingsProcessor,
|
loyaltySettingsProcessor: loyaltySettingsProcessor,
|
||||||
earningProcessor: earningProcessor,
|
earningProcessor: earningProcessor,
|
||||||
customerPinProcessor: customerPinProcessor,
|
customerPinProcessor: customerPinProcessor,
|
||||||
paymentCodeProcessor: paymentCodeProcessor,
|
|
||||||
pointPaymentProcessor: pointPaymentProcessor,
|
|
||||||
walletExchangeProcessor: walletExchangeProcessor,
|
walletExchangeProcessor: walletExchangeProcessor,
|
||||||
walletTransferProcessor: walletTransferProcessor,
|
walletTransferProcessor: walletTransferProcessor,
|
||||||
walletTraceProcessor: processor.NewWalletTraceProcessor(repository.NewWalletTraceRepository(a.db)),
|
walletTraceProcessor: processor.NewWalletTraceProcessor(repository.NewWalletTraceRepository(a.db)),
|
||||||
@@ -536,8 +526,6 @@ type services struct {
|
|||||||
walletAdminService *service.WalletAdminServiceImpl
|
walletAdminService *service.WalletAdminServiceImpl
|
||||||
loyaltySettingsService *service.LoyaltySettingsServiceImpl
|
loyaltySettingsService *service.LoyaltySettingsServiceImpl
|
||||||
customerPinService *service.CustomerPinServiceImpl
|
customerPinService *service.CustomerPinServiceImpl
|
||||||
pointPaymentService *service.PointPaymentServiceImpl
|
|
||||||
customerOrderPaymentService *service.CustomerOrderPaymentServiceImpl
|
|
||||||
customerWalletService *service.CustomerWalletServiceImpl
|
customerWalletService *service.CustomerWalletServiceImpl
|
||||||
customerDeviceService *service.CustomerDeviceServiceImpl
|
customerDeviceService *service.CustomerDeviceServiceImpl
|
||||||
customerOutletService *service.CustomerOutletServiceImpl
|
customerOutletService *service.CustomerOutletServiceImpl
|
||||||
@@ -625,9 +613,7 @@ func (a *App) initServices(processors *processors, repos *repositories, cfg *con
|
|||||||
cashAdvanceService: service.NewCashAdvanceService(processors.cashAdvanceProcessor),
|
cashAdvanceService: service.NewCashAdvanceService(processors.cashAdvanceProcessor),
|
||||||
walletAdminService: service.NewWalletAdminService(processors.walletAdminProcessor, processors.walletTraceProcessor),
|
walletAdminService: service.NewWalletAdminService(processors.walletAdminProcessor, processors.walletTraceProcessor),
|
||||||
loyaltySettingsService: service.NewLoyaltySettingsService(processors.loyaltySettingsProcessor, repos.walletQueryRepo),
|
loyaltySettingsService: service.NewLoyaltySettingsService(processors.loyaltySettingsProcessor, repos.walletQueryRepo),
|
||||||
customerPinService: service.NewCustomerPinService(processors.customerPinProcessor, processors.paymentCodeProcessor),
|
customerPinService: service.NewCustomerPinService(processors.customerPinProcessor),
|
||||||
pointPaymentService: service.NewPointPaymentService(processors.pointPaymentProcessor),
|
|
||||||
customerOrderPaymentService: service.NewCustomerOrderPaymentService(processors.orderProcessor),
|
|
||||||
customerWalletService: service.NewCustomerWalletService(processors.walletExchangeProcessor, processors.walletTransferProcessor),
|
customerWalletService: service.NewCustomerWalletService(processors.walletExchangeProcessor, processors.walletTransferProcessor),
|
||||||
customerDeviceService: service.NewCustomerDeviceService(processors.customerDeviceProcessor),
|
customerDeviceService: service.NewCustomerDeviceService(processors.customerDeviceProcessor),
|
||||||
customerOutletService: service.NewCustomerOutletService(processors.customerOutletProcessor),
|
customerOutletService: service.NewCustomerOutletService(processors.customerOutletProcessor),
|
||||||
|
|||||||
@@ -1,9 +1,6 @@
|
|||||||
package constants
|
package constants
|
||||||
|
|
||||||
// Budget allocation of revenue used by the parent category cut-off report.
|
// Revenue split used by the profit sharing report: the owner takes its fee as SDL and
|
||||||
// The three shares are expected to add up to 100.
|
// the team takes the rest. BudgetLimitOwnerPercent is only the default: a parent
|
||||||
const (
|
// category can override it with categories.owner_fee_percent.
|
||||||
BudgetLimitPurchasePercent = 60.0
|
const BudgetLimitOwnerPercent = 20.0
|
||||||
BudgetLimitOwnerPercent = 20.0
|
|
||||||
BudgetLimitTeamPercent = 20.0
|
|
||||||
)
|
|
||||||
|
|||||||
@@ -4,23 +4,23 @@ package constants
|
|||||||
// outlet_settings and organization keys in organization_settings. A key that was
|
// outlet_settings and organization keys in organization_settings. A key that was
|
||||||
// never set takes the default in the PRD.
|
// never set takes the default in the PRD.
|
||||||
|
|
||||||
// Per outlet (F1): what an order earns, and whether EnakPoint can pay.
|
// Per outlet (F1): what an order earns.
|
||||||
const (
|
const (
|
||||||
LoyaltyPointEnabledKey = "loyalty.point.enabled"
|
LoyaltyPointEnabledKey = "loyalty.point.enabled"
|
||||||
|
LoyaltyPointEarnModeKey = "loyalty.point.earn_mode"
|
||||||
|
LoyaltyPointEarnPercentKey = "loyalty.point.earn_percent"
|
||||||
LoyaltyPointEarnPerAmountKey = "loyalty.point.earn_per_amount"
|
LoyaltyPointEarnPerAmountKey = "loyalty.point.earn_per_amount"
|
||||||
LoyaltyPointEarnValueKey = "loyalty.point.earn_value"
|
LoyaltyPointEarnValueKey = "loyalty.point.earn_value"
|
||||||
LoyaltyPointMinOrderAmountKey = "loyalty.point.min_order_amount"
|
LoyaltyPointMinOrderAmountKey = "loyalty.point.min_order_amount"
|
||||||
LoyaltyPointMaxPerOrderKey = "loyalty.point.max_per_order"
|
LoyaltyPointMaxPerOrderKey = "loyalty.point.max_per_order"
|
||||||
|
|
||||||
LoyaltyCoinEnabledKey = "loyalty.coin.enabled"
|
LoyaltyCoinEnabledKey = "loyalty.coin.enabled"
|
||||||
|
LoyaltyCoinEarnModeKey = "loyalty.coin.earn_mode"
|
||||||
|
LoyaltyCoinEarnPercentKey = "loyalty.coin.earn_percent"
|
||||||
LoyaltyCoinEarnPerAmountKey = "loyalty.coin.earn_per_amount"
|
LoyaltyCoinEarnPerAmountKey = "loyalty.coin.earn_per_amount"
|
||||||
LoyaltyCoinEarnValueKey = "loyalty.coin.earn_value"
|
LoyaltyCoinEarnValueKey = "loyalty.coin.earn_value"
|
||||||
LoyaltyCoinMinOrderAmountKey = "loyalty.coin.min_order_amount"
|
LoyaltyCoinMinOrderAmountKey = "loyalty.coin.min_order_amount"
|
||||||
LoyaltyCoinMaxPerOrderKey = "loyalty.coin.max_per_order"
|
LoyaltyCoinMaxPerOrderKey = "loyalty.coin.max_per_order"
|
||||||
|
|
||||||
LoyaltyPointAcceptPaymentKey = "loyalty.point.accept_payment"
|
|
||||||
LoyaltyPointMinPaymentPointsKey = "loyalty.point.min_payment_points"
|
|
||||||
LoyaltyPointMaxPaymentPercentKey = "loyalty.point.max_payment_percent"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
// Per organization (F2, F12): the value of EnakPoint, the exchange rate, transfers and
|
// Per organization (F2, F12): the value of EnakPoint, the exchange rate, transfers and
|
||||||
@@ -47,6 +47,14 @@ const (
|
|||||||
LoyaltyExpiryGraceMonthsSuffix = "expiry_grace_months"
|
LoyaltyExpiryGraceMonthsSuffix = "expiry_grace_months"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// Modes of loyalty.{point,coin}.earn_mode.
|
||||||
|
const (
|
||||||
|
// earn_value for every earn_per_amount rupiah of the basis.
|
||||||
|
LoyaltyEarnModePerAmount = "PER_AMOUNT"
|
||||||
|
// earn_percent percent of the basis.
|
||||||
|
LoyaltyEarnModePercentage = "PERCENTAGE"
|
||||||
|
)
|
||||||
|
|
||||||
// Units of loyalty.{point,coin}.expiry_unit.
|
// Units of loyalty.{point,coin}.expiry_unit.
|
||||||
const (
|
const (
|
||||||
LoyaltyExpiryUnitDay = "DAY"
|
LoyaltyExpiryUnitDay = "DAY"
|
||||||
@@ -66,9 +74,8 @@ const (
|
|||||||
LoyaltyPointEarnPerAmountDefault = int64(100)
|
LoyaltyPointEarnPerAmountDefault = int64(100)
|
||||||
LoyaltyCoinEarnPerAmountDefault = int64(25000)
|
LoyaltyCoinEarnPerAmountDefault = int64(25000)
|
||||||
LoyaltyEarnValueDefault = int64(1)
|
LoyaltyEarnValueDefault = int64(1)
|
||||||
|
LoyaltyEarnModeDefault = LoyaltyEarnModePerAmount
|
||||||
LoyaltyMinPaymentPointsDefault = int64(1)
|
LoyaltyEarnPercentDefault = float64(1)
|
||||||
LoyaltyMaxPaymentPercentDefault = int64(100)
|
|
||||||
|
|
||||||
LoyaltyPointValueDefault = int64(1)
|
LoyaltyPointValueDefault = int64(1)
|
||||||
LoyaltyExchangeAmountDefault = int64(1)
|
LoyaltyExchangeAmountDefault = int64(1)
|
||||||
|
|||||||
@@ -8,9 +8,6 @@ const (
|
|||||||
PaymentMethodTypeDigitalWallet PaymentMethodType = "digital_wallet"
|
PaymentMethodTypeDigitalWallet PaymentMethodType = "digital_wallet"
|
||||||
PaymentMethodTypeQR PaymentMethodType = "qr"
|
PaymentMethodTypeQR PaymentMethodType = "qr"
|
||||||
PaymentMethodTypeEDC PaymentMethodType = "edc"
|
PaymentMethodTypeEDC PaymentMethodType = "edc"
|
||||||
// Paying with EnakPoint (docs/prd-point-coin.md F9). Not accepted as a payment method
|
|
||||||
// type until that phase ships.
|
|
||||||
PaymentMethodTypePoint PaymentMethodType = "point"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
type PaymentStatus string
|
type PaymentStatus string
|
||||||
|
|||||||
@@ -16,8 +16,6 @@ func IsValidWalletCurrency(currency string) bool {
|
|||||||
const (
|
const (
|
||||||
WalletTxTypeEarn = "EARN"
|
WalletTxTypeEarn = "EARN"
|
||||||
WalletTxTypeEarnReversal = "EARN_REVERSAL"
|
WalletTxTypeEarnReversal = "EARN_REVERSAL"
|
||||||
WalletTxTypePayment = "PAYMENT"
|
|
||||||
WalletTxTypePaymentRefund = "PAYMENT_REFUND"
|
|
||||||
WalletTxTypeExchangeOut = "EXCHANGE_OUT"
|
WalletTxTypeExchangeOut = "EXCHANGE_OUT"
|
||||||
WalletTxTypeExchangeIn = "EXCHANGE_IN"
|
WalletTxTypeExchangeIn = "EXCHANGE_IN"
|
||||||
WalletTxTypeTransferOut = "TRANSFER_OUT"
|
WalletTxTypeTransferOut = "TRANSFER_OUT"
|
||||||
@@ -33,7 +31,6 @@ const (
|
|||||||
// credit, or where it went for a debit.
|
// credit, or where it went for a debit.
|
||||||
const (
|
const (
|
||||||
WalletRefTypeOrder = "ORDER"
|
WalletRefTypeOrder = "ORDER"
|
||||||
WalletRefTypePayment = "PAYMENT"
|
|
||||||
WalletRefTypeWalletTx = "WALLET_TX"
|
WalletRefTypeWalletTx = "WALLET_TX"
|
||||||
WalletRefTypeGamePlay = "GAME_PLAY"
|
WalletRefTypeGamePlay = "GAME_PLAY"
|
||||||
WalletRefTypeLot = "LOT"
|
WalletRefTypeLot = "LOT"
|
||||||
|
|||||||
@@ -28,11 +28,7 @@ type PaymentMethodAnalyticsResponse struct {
|
|||||||
|
|
||||||
// PaymentMethodSummary represents the summary of payment method analytics
|
// PaymentMethodSummary represents the summary of payment method analytics
|
||||||
type PaymentMethodSummary struct {
|
type PaymentMethodSummary struct {
|
||||||
// Money actually received; EnakPoint is reported apart (docs/prd-point-coin.md F9).
|
|
||||||
TotalAmount float64 `json:"total_amount"`
|
TotalAmount float64 `json:"total_amount"`
|
||||||
PointAmount float64 `json:"point_amount"`
|
|
||||||
PointsUsed int64 `json:"points_used"`
|
|
||||||
TotalWithPoints float64 `json:"total_with_points"`
|
|
||||||
TotalOrders int64 `json:"total_orders"`
|
TotalOrders int64 `json:"total_orders"`
|
||||||
TotalPayments int64 `json:"total_payments"`
|
TotalPayments int64 `json:"total_payments"`
|
||||||
AverageOrderValue float64 `json:"average_order_value"`
|
AverageOrderValue float64 `json:"average_order_value"`
|
||||||
@@ -46,8 +42,6 @@ type PaymentMethodAnalyticsData struct {
|
|||||||
OrderCount int64 `json:"order_count"`
|
OrderCount int64 `json:"order_count"`
|
||||||
PaymentCount int64 `json:"payment_count"`
|
PaymentCount int64 `json:"payment_count"`
|
||||||
Percentage float64 `json:"percentage"`
|
Percentage float64 `json:"percentage"`
|
||||||
PointsUsed int64 `json:"points_used"`
|
|
||||||
CountsAsCashIn bool `json:"counts_as_cash_in"`
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type SalesAnalyticsRequest struct {
|
type SalesAnalyticsRequest struct {
|
||||||
@@ -268,6 +262,8 @@ type ProductAnalyticsPerParentCategoryResponse struct {
|
|||||||
type ProductAnalyticsPerParentCategoryData struct {
|
type ProductAnalyticsPerParentCategoryData struct {
|
||||||
ParentCategoryID uuid.UUID `json:"parent_category_id"`
|
ParentCategoryID uuid.UUID `json:"parent_category_id"`
|
||||||
ParentCategoryName string `json:"parent_category_name"`
|
ParentCategoryName string `json:"parent_category_name"`
|
||||||
|
OwnerFeePercent float64 `json:"owner_fee_percent"`
|
||||||
|
SDL float64 `json:"sdl"`
|
||||||
TotalRevenue float64 `json:"total_revenue"`
|
TotalRevenue float64 `json:"total_revenue"`
|
||||||
TotalQuantity int64 `json:"total_quantity"`
|
TotalQuantity int64 `json:"total_quantity"`
|
||||||
CategoryCount int64 `json:"category_count"`
|
CategoryCount int64 `json:"category_count"`
|
||||||
@@ -276,6 +272,15 @@ type ProductAnalyticsPerParentCategoryData struct {
|
|||||||
TotalStandardHpp float64 `json:"total_standard_hpp"`
|
TotalStandardHpp float64 `json:"total_standard_hpp"`
|
||||||
TotalFifoHpp float64 `json:"total_fifo_hpp"`
|
TotalFifoHpp float64 `json:"total_fifo_hpp"`
|
||||||
TotalMovingAverageHpp float64 `json:"total_moving_average_hpp"`
|
TotalMovingAverageHpp float64 `json:"total_moving_average_hpp"`
|
||||||
|
TopProduct *ParentCategoryTopProduct `json:"top_product"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// ParentCategoryTopProduct is the best-selling product of a parent category by revenue.
|
||||||
|
type ParentCategoryTopProduct struct {
|
||||||
|
ProductID uuid.UUID `json:"product_id"`
|
||||||
|
ProductName string `json:"product_name"`
|
||||||
|
QuantitySold int64 `json:"quantity_sold"`
|
||||||
|
Revenue float64 `json:"revenue"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// ParentCategoryAnalyticsDetailRequest represents the request for the drill-down of one parent category
|
// ParentCategoryAnalyticsDetailRequest represents the request for the drill-down of one parent category
|
||||||
@@ -302,6 +307,8 @@ type ParentCategoryAnalyticsDetailResponse struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type ParentCategoryAnalyticsDetailSummary struct {
|
type ParentCategoryAnalyticsDetailSummary struct {
|
||||||
|
OwnerFeePercent float64 `json:"owner_fee_percent"`
|
||||||
|
SDL float64 `json:"sdl"`
|
||||||
TotalRevenue float64 `json:"total_revenue"`
|
TotalRevenue float64 `json:"total_revenue"`
|
||||||
TotalQuantity int64 `json:"total_quantity"`
|
TotalQuantity int64 `json:"total_quantity"`
|
||||||
CategoryCount int64 `json:"category_count"`
|
CategoryCount int64 `json:"category_count"`
|
||||||
@@ -310,11 +317,15 @@ type ParentCategoryAnalyticsDetailSummary struct {
|
|||||||
TotalStandardHpp float64 `json:"total_standard_hpp"`
|
TotalStandardHpp float64 `json:"total_standard_hpp"`
|
||||||
TotalFifoHpp float64 `json:"total_fifo_hpp"`
|
TotalFifoHpp float64 `json:"total_fifo_hpp"`
|
||||||
TotalMovingAverageHpp float64 `json:"total_moving_average_hpp"`
|
TotalMovingAverageHpp float64 `json:"total_moving_average_hpp"`
|
||||||
|
TopProduct *ParentCategoryTopProduct `json:"top_product"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type ParentCategoryAnalyticsDetailData struct {
|
type ParentCategoryAnalyticsDetailData struct {
|
||||||
CategoryID uuid.UUID `json:"category_id"`
|
CategoryID uuid.UUID `json:"category_id"`
|
||||||
CategoryName string `json:"category_name"`
|
CategoryName string `json:"category_name"`
|
||||||
|
OwnerFeePercent float64 `json:"owner_fee_percent"`
|
||||||
|
SDL float64 `json:"sdl"`
|
||||||
|
TopProduct *ParentCategoryTopProduct `json:"top_product"`
|
||||||
TotalRevenue float64 `json:"total_revenue"`
|
TotalRevenue float64 `json:"total_revenue"`
|
||||||
TotalQuantity int64 `json:"total_quantity"`
|
TotalQuantity int64 `json:"total_quantity"`
|
||||||
ProductCount int64 `json:"product_count"`
|
ProductCount int64 `json:"product_count"`
|
||||||
@@ -355,7 +366,6 @@ type BudgetCutOff struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type BudgetPercentages struct {
|
type BudgetPercentages struct {
|
||||||
Purchase float64 `json:"purchase"`
|
|
||||||
Owner float64 `json:"owner"`
|
Owner float64 `json:"owner"`
|
||||||
Team float64 `json:"team"`
|
Team float64 `json:"team"`
|
||||||
}
|
}
|
||||||
@@ -365,8 +375,7 @@ type BudgetPeriod struct {
|
|||||||
PeriodEnd time.Time `json:"period_end"`
|
PeriodEnd time.Time `json:"period_end"`
|
||||||
Revenue float64 `json:"revenue"`
|
Revenue float64 `json:"revenue"`
|
||||||
OrderCount int64 `json:"order_count"`
|
OrderCount int64 `json:"order_count"`
|
||||||
LimitPurchase float64 `json:"limit_purchase"`
|
SDL float64 `json:"sdl"`
|
||||||
LimitOwner float64 `json:"limit_owner"`
|
|
||||||
LimitTeam float64 `json:"limit_team"`
|
LimitTeam float64 `json:"limit_team"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,8 @@
|
|||||||
package contract
|
package contract
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"bytes"
|
||||||
|
"encoding/json"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/google/uuid"
|
"github.com/google/uuid"
|
||||||
@@ -13,6 +15,8 @@ type CreateCategoryRequest struct {
|
|||||||
OutletID *uuid.UUID `json:"outlet_id,omitempty"`
|
OutletID *uuid.UUID `json:"outlet_id,omitempty"`
|
||||||
ParentID *uuid.UUID `json:"parent_id,omitempty"`
|
ParentID *uuid.UUID `json:"parent_id,omitempty"`
|
||||||
Order *int `json:"order,omitempty"`
|
Order *int `json:"order,omitempty"`
|
||||||
|
OwnerFeePercent *float64 `json:"owner_fee_percent,omitempty"`
|
||||||
|
IsTeam *bool `json:"is_team,omitempty"`
|
||||||
Metadata map[string]interface{} `json:"metadata,omitempty"`
|
Metadata map[string]interface{} `json:"metadata,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -23,7 +27,55 @@ type UpdateCategoryRequest struct {
|
|||||||
OutletID *uuid.UUID `json:"outlet_id,omitempty"`
|
OutletID *uuid.UUID `json:"outlet_id,omitempty"`
|
||||||
ParentID *uuid.UUID `json:"parent_id,omitempty"`
|
ParentID *uuid.UUID `json:"parent_id,omitempty"`
|
||||||
Order *int `json:"order,omitempty"`
|
Order *int `json:"order,omitempty"`
|
||||||
|
OwnerFeePercent *float64 `json:"owner_fee_percent,omitempty"`
|
||||||
|
IsTeam *bool `json:"is_team,omitempty"`
|
||||||
Metadata map[string]interface{} `json:"metadata,omitempty"`
|
Metadata map[string]interface{} `json:"metadata,omitempty"`
|
||||||
|
|
||||||
|
// Set when the field is sent as null (or "" for parent_id), which asks for the
|
||||||
|
// value to be removed. A field that is left out stays unchanged.
|
||||||
|
ClearParentID bool `json:"-"`
|
||||||
|
ClearOwnerFeePercent bool `json:"-"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// UnmarshalJSON tells an explicit null apart from a field that was left out, so a
|
||||||
|
// category can be detached from its parent and an owner fee override can be removed.
|
||||||
|
func (r *UpdateCategoryRequest) UnmarshalJSON(data []byte) error {
|
||||||
|
var raw map[string]json.RawMessage
|
||||||
|
if err := json.Unmarshal(data, &raw); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
isEmpty := func(key string, allowEmptyString bool) bool {
|
||||||
|
value, ok := raw[key]
|
||||||
|
if !ok {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
value = bytes.TrimSpace(value)
|
||||||
|
return bytes.Equal(value, []byte("null")) || (allowEmptyString && bytes.Equal(value, []byte(`""`)))
|
||||||
|
}
|
||||||
|
|
||||||
|
clearParentID := isEmpty("parent_id", true)
|
||||||
|
clearOwnerFeePercent := isEmpty("owner_fee_percent", false)
|
||||||
|
if clearParentID {
|
||||||
|
// An empty string is not a valid UUID, so keep it away from the decoder
|
||||||
|
delete(raw, "parent_id")
|
||||||
|
cleaned, err := json.Marshal(raw)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
data = cleaned
|
||||||
|
}
|
||||||
|
|
||||||
|
type plain UpdateCategoryRequest
|
||||||
|
var decoded plain
|
||||||
|
if err := json.Unmarshal(data, &decoded); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
*r = UpdateCategoryRequest(decoded)
|
||||||
|
r.ClearParentID = clearParentID
|
||||||
|
r.ClearOwnerFeePercent = clearOwnerFeePercent
|
||||||
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
type ListCategoriesRequest struct {
|
type ListCategoriesRequest struct {
|
||||||
@@ -48,6 +100,8 @@ type CategoryResponse struct {
|
|||||||
Description *string `json:"description"`
|
Description *string `json:"description"`
|
||||||
BusinessType string `json:"business_type"`
|
BusinessType string `json:"business_type"`
|
||||||
Order int `json:"order"`
|
Order int `json:"order"`
|
||||||
|
OwnerFeePercent *float64 `json:"owner_fee_percent"`
|
||||||
|
IsTeam bool `json:"is_team"`
|
||||||
Metadata map[string]interface{} `json:"metadata"`
|
Metadata map[string]interface{} `json:"metadata"`
|
||||||
CreatedAt time.Time `json:"created_at"`
|
CreatedAt time.Time `json:"created_at"`
|
||||||
UpdatedAt time.Time `json:"updated_at"`
|
UpdatedAt time.Time `json:"updated_at"`
|
||||||
|
|||||||
@@ -0,0 +1,48 @@
|
|||||||
|
package contract
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
"github.com/stretchr/testify/require"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestUpdateCategoryRequestTellsNullFromOmitted(t *testing.T) {
|
||||||
|
parentID := uuid.New()
|
||||||
|
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
body string
|
||||||
|
wantParentID *uuid.UUID
|
||||||
|
wantClear bool
|
||||||
|
wantClearFee bool
|
||||||
|
wantFee *float64
|
||||||
|
wantNameIsSet bool
|
||||||
|
}{
|
||||||
|
{name: "omitted leaves parent unchanged", body: `{"name":"Food"}`, wantNameIsSet: true},
|
||||||
|
{name: "null detaches the parent", body: `{"parent_id":null}`, wantClear: true},
|
||||||
|
{name: "empty string detaches the parent", body: `{"name":"Food","parent_id":""}`, wantClear: true, wantNameIsSet: true},
|
||||||
|
{name: "uuid sets the parent", body: `{"parent_id":"` + parentID.String() + `"}`, wantParentID: &parentID},
|
||||||
|
{name: "null removes the owner fee override", body: `{"owner_fee_percent":null}`, wantClearFee: true},
|
||||||
|
{name: "number sets the owner fee", body: `{"owner_fee_percent":35}`, wantFee: func() *float64 { v := 35.0; return &v }()},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, tt := range tests {
|
||||||
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
|
var req UpdateCategoryRequest
|
||||||
|
require.NoError(t, json.Unmarshal([]byte(tt.body), &req))
|
||||||
|
|
||||||
|
require.Equal(t, tt.wantParentID, req.ParentID)
|
||||||
|
require.Equal(t, tt.wantClear, req.ClearParentID)
|
||||||
|
require.Equal(t, tt.wantClearFee, req.ClearOwnerFeePercent)
|
||||||
|
require.Equal(t, tt.wantFee, req.OwnerFeePercent)
|
||||||
|
require.Equal(t, tt.wantNameIsSet, req.Name != nil)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestUpdateCategoryRequestRejectsInvalidParentID(t *testing.T) {
|
||||||
|
var req UpdateCategoryRequest
|
||||||
|
require.Error(t, json.Unmarshal([]byte(`{"parent_id":"not-a-uuid"}`), &req))
|
||||||
|
}
|
||||||
@@ -26,14 +26,3 @@ type ResetCustomerPinRequest = CreateCustomerPinRequest
|
|||||||
type RemoveCustomerPinRequest struct {
|
type RemoveCustomerPinRequest struct {
|
||||||
Reason string `json:"reason" binding:"required"`
|
Reason string `json:"reason" binding:"required"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// IssuePaymentCodeRequest is POST /customer/wallet/payment-code.
|
|
||||||
type IssuePaymentCodeRequest struct {
|
|
||||||
Pin string `json:"pin" binding:"required"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// PayWithPointsRequest is POST /customer/orders/:id/pay-with-points.
|
|
||||||
type PayWithPointsRequest struct {
|
|
||||||
Points int64 `json:"points" binding:"required,min=1"`
|
|
||||||
Pin string `json:"pin" binding:"required"`
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -121,7 +121,7 @@ type OrderItemResponse struct {
|
|||||||
Status string `json:"status"`
|
Status string `json:"status"`
|
||||||
CreatedAt time.Time `json:"created_at"`
|
CreatedAt time.Time `json:"created_at"`
|
||||||
UpdatedAt time.Time `json:"updated_at"`
|
UpdatedAt time.Time `json:"updated_at"`
|
||||||
PrinterType string `json:"printer_type"`
|
PrinterTypes []string `json:"printer_types"`
|
||||||
PrintToChecker bool `json:"print_to_checker"`
|
PrintToChecker bool `json:"print_to_checker"`
|
||||||
PaidQuantity int `json:"paid_quantity"`
|
PaidQuantity int `json:"paid_quantity"`
|
||||||
}
|
}
|
||||||
@@ -188,11 +188,7 @@ type SetOrderCustomerResponse struct {
|
|||||||
type CreatePaymentRequest struct {
|
type CreatePaymentRequest struct {
|
||||||
OrderID uuid.UUID `json:"order_id" validate:"required"`
|
OrderID uuid.UUID `json:"order_id" validate:"required"`
|
||||||
PaymentMethodID uuid.UUID `json:"payment_method_id" validate:"required"`
|
PaymentMethodID uuid.UUID `json:"payment_method_id" validate:"required"`
|
||||||
// For the EnakPoint method: how many to use and the code the customer shows. The
|
Amount float64 `json:"amount" validate:"required,min=0"`
|
||||||
// amount is then computed from them.
|
|
||||||
Points *int64 `json:"points,omitempty"`
|
|
||||||
PaymentCode *string `json:"payment_code,omitempty"`
|
|
||||||
Amount float64 `json:"amount" validate:"min=0"`
|
|
||||||
TransactionID *string `json:"transaction_id,omitempty" validate:"omitempty"`
|
TransactionID *string `json:"transaction_id,omitempty" validate:"omitempty"`
|
||||||
SplitNumber int `json:"split_number,omitempty" validate:"omitempty,min=1"`
|
SplitNumber int `json:"split_number,omitempty" validate:"omitempty,min=1"`
|
||||||
SplitTotal int `json:"split_total,omitempty" validate:"omitempty,min=1"`
|
SplitTotal int `json:"split_total,omitempty" validate:"omitempty,min=1"`
|
||||||
@@ -221,10 +217,6 @@ type PaymentResponse struct {
|
|||||||
SplitType *string `json:"split_type,omitempty"`
|
SplitType *string `json:"split_type,omitempty"`
|
||||||
SplitDescription *string `json:"split_description,omitempty"`
|
SplitDescription *string `json:"split_description,omitempty"`
|
||||||
RefundAmount float64 `json:"refund_amount"`
|
RefundAmount float64 `json:"refund_amount"`
|
||||||
// Set for a payment with EnakPoint, for "EnakPoint: 50.000 (Rp 50.000)" on the
|
|
||||||
// receipt (docs/prd-point-coin.md F9).
|
|
||||||
PointsUsed *int64 `json:"points_used,omitempty"`
|
|
||||||
PointValue *float64 `json:"point_value,omitempty"`
|
|
||||||
RefundReason *string `json:"refund_reason,omitempty"`
|
RefundReason *string `json:"refund_reason,omitempty"`
|
||||||
RefundedAt *time.Time `json:"refunded_at,omitempty"`
|
RefundedAt *time.Time `json:"refunded_at,omitempty"`
|
||||||
RefundedBy *uuid.UUID `json:"refunded_by,omitempty"`
|
RefundedBy *uuid.UUID `json:"refunded_by,omitempty"`
|
||||||
|
|||||||
@@ -18,7 +18,7 @@ type CreatePaymentMethodRequest struct {
|
|||||||
|
|
||||||
type UpdatePaymentMethodRequest struct {
|
type UpdatePaymentMethodRequest struct {
|
||||||
Name *string `json:"name,omitempty" validate:"omitempty,min=1,max=100"`
|
Name *string `json:"name,omitempty" validate:"omitempty,min=1,max=100"`
|
||||||
Type *string `json:"type,omitempty" validate:"omitempty,oneof=cash card digital_wallet qr edc point"`
|
Type *string `json:"type,omitempty" validate:"omitempty,oneof=cash card digital_wallet qr edc"`
|
||||||
Processor *string `json:"processor,omitempty" validate:"omitempty,max=100"`
|
Processor *string `json:"processor,omitempty" validate:"omitempty,max=100"`
|
||||||
Configuration map[string]interface{} `json:"configuration,omitempty"`
|
Configuration map[string]interface{} `json:"configuration,omitempty"`
|
||||||
IsActive *bool `json:"is_active,omitempty"`
|
IsActive *bool `json:"is_active,omitempty"`
|
||||||
@@ -38,9 +38,7 @@ type PaymentMethodResponse struct {
|
|||||||
|
|
||||||
type ListPaymentMethodsRequest struct {
|
type ListPaymentMethodsRequest struct {
|
||||||
OrganizationID *uuid.UUID `json:"organization_id,omitempty"`
|
OrganizationID *uuid.UUID `json:"organization_id,omitempty"`
|
||||||
// When set, EnakPoint is left out unless the outlet accepts it (F9).
|
Type *string `json:"type,omitempty" validate:"omitempty,oneof=cash card digital_wallet qr edc"`
|
||||||
OutletID *uuid.UUID `json:"outlet_id,omitempty"`
|
|
||||||
Type *string `json:"type,omitempty" validate:"omitempty,oneof=cash card digital_wallet qr edc point"`
|
|
||||||
IsActive *bool `json:"is_active,omitempty"`
|
IsActive *bool `json:"is_active,omitempty"`
|
||||||
Search string `json:"search,omitempty"`
|
Search string `json:"search,omitempty"`
|
||||||
Page int `json:"page" validate:"min=1"`
|
Page int `json:"page" validate:"min=1"`
|
||||||
|
|||||||
@@ -16,7 +16,7 @@ type CreateProductRequest struct {
|
|||||||
Cost *float64 `json:"cost,omitempty" validate:"omitempty,min=0"`
|
Cost *float64 `json:"cost,omitempty" validate:"omitempty,min=0"`
|
||||||
BusinessType *string `json:"business_type,omitempty"`
|
BusinessType *string `json:"business_type,omitempty"`
|
||||||
ImageURL *string `json:"image_url,omitempty" validate:"omitempty,max=500"`
|
ImageURL *string `json:"image_url,omitempty" validate:"omitempty,max=500"`
|
||||||
PrinterType *string `json:"printer_type,omitempty" validate:"omitempty,max=50"`
|
PrinterTypes []string `json:"printer_types,omitempty" validate:"omitempty,dive,max=50"`
|
||||||
PrintToChecker *bool `json:"print_to_checker,omitempty"`
|
PrintToChecker *bool `json:"print_to_checker,omitempty"`
|
||||||
UnitID *uuid.UUID `json:"unit_id,omitempty"`
|
UnitID *uuid.UUID `json:"unit_id,omitempty"`
|
||||||
SellBy *string `json:"sell_by,omitempty" validate:"omitempty,oneof=unit weight"`
|
SellBy *string `json:"sell_by,omitempty" validate:"omitempty,oneof=unit weight"`
|
||||||
@@ -38,7 +38,7 @@ type UpdateProductRequest struct {
|
|||||||
Cost *float64 `json:"cost,omitempty" validate:"omitempty,min=0"`
|
Cost *float64 `json:"cost,omitempty" validate:"omitempty,min=0"`
|
||||||
BusinessType *string `json:"business_type,omitempty"`
|
BusinessType *string `json:"business_type,omitempty"`
|
||||||
ImageURL *string `json:"image_url,omitempty" validate:"omitempty,max=500"`
|
ImageURL *string `json:"image_url,omitempty" validate:"omitempty,max=500"`
|
||||||
PrinterType *string `json:"printer_type,omitempty" validate:"omitempty,max=50"`
|
PrinterTypes []string `json:"printer_types,omitempty" validate:"omitempty,dive,max=50"` // Replaces the whole list when sent
|
||||||
PrintToChecker *bool `json:"print_to_checker,omitempty"`
|
PrintToChecker *bool `json:"print_to_checker,omitempty"`
|
||||||
UnitID *uuid.UUID `json:"unit_id,omitempty"`
|
UnitID *uuid.UUID `json:"unit_id,omitempty"`
|
||||||
SellBy *string `json:"sell_by,omitempty" validate:"omitempty,oneof=unit weight"`
|
SellBy *string `json:"sell_by,omitempty" validate:"omitempty,oneof=unit weight"`
|
||||||
@@ -76,7 +76,7 @@ type ProductResponse struct {
|
|||||||
Cost float64 `json:"cost"`
|
Cost float64 `json:"cost"`
|
||||||
BusinessType string `json:"business_type"`
|
BusinessType string `json:"business_type"`
|
||||||
ImageURL *string `json:"image_url"`
|
ImageURL *string `json:"image_url"`
|
||||||
PrinterType string `json:"printer_type"`
|
PrinterTypes []string `json:"printer_types"`
|
||||||
UnitID *uuid.UUID `json:"unit_id,omitempty"`
|
UnitID *uuid.UUID `json:"unit_id,omitempty"`
|
||||||
SellBy string `json:"sell_by"`
|
SellBy string `json:"sell_by"`
|
||||||
PrintToChecker bool `json:"print_to_checker"`
|
PrintToChecker bool `json:"print_to_checker"`
|
||||||
|
|||||||
@@ -14,8 +14,6 @@ type PaymentMethodAnalytics struct {
|
|||||||
TotalAmount float64 `json:"total_amount"`
|
TotalAmount float64 `json:"total_amount"`
|
||||||
OrderCount int64 `json:"order_count"`
|
OrderCount int64 `json:"order_count"`
|
||||||
PaymentCount int64 `json:"payment_count"`
|
PaymentCount int64 `json:"payment_count"`
|
||||||
// EnakPoint used, for the EnakPoint method.
|
|
||||||
PointsUsed int64 `json:"points_used"`
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// SalesAnalytics represents sales analytics data
|
// SalesAnalytics represents sales analytics data
|
||||||
@@ -145,6 +143,8 @@ type ProductAnalyticsPerCategory struct {
|
|||||||
type ProductAnalyticsPerParentCategory struct {
|
type ProductAnalyticsPerParentCategory struct {
|
||||||
ParentCategoryID uuid.UUID `json:"parent_category_id"`
|
ParentCategoryID uuid.UUID `json:"parent_category_id"`
|
||||||
ParentCategoryName string `json:"parent_category_name"`
|
ParentCategoryName string `json:"parent_category_name"`
|
||||||
|
// OwnerFeePercent is the owner share of this group's revenue, already resolved to the default
|
||||||
|
OwnerFeePercent float64 `json:"owner_fee_percent"`
|
||||||
TotalRevenue float64 `json:"total_revenue"`
|
TotalRevenue float64 `json:"total_revenue"`
|
||||||
TotalQuantity int64 `json:"total_quantity"`
|
TotalQuantity int64 `json:"total_quantity"`
|
||||||
CategoryCount int64 `json:"category_count"`
|
CategoryCount int64 `json:"category_count"`
|
||||||
@@ -153,6 +153,17 @@ type ProductAnalyticsPerParentCategory struct {
|
|||||||
TotalStandardHpp float64 `json:"total_standard_hpp"`
|
TotalStandardHpp float64 `json:"total_standard_hpp"`
|
||||||
TotalFifoHpp float64 `json:"total_fifo_hpp"`
|
TotalFifoHpp float64 `json:"total_fifo_hpp"`
|
||||||
TotalMovingAverageHpp float64 `json:"total_moving_average_hpp"`
|
TotalMovingAverageHpp float64 `json:"total_moving_average_hpp"`
|
||||||
|
// TopProduct is filled by a separate query, so it is not a scanned column
|
||||||
|
TopProduct *ParentCategoryTopProduct `gorm:"-" json:"top_product"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// ParentCategoryTopProduct is the best-selling product of a parent category by revenue.
|
||||||
|
type ParentCategoryTopProduct struct {
|
||||||
|
ParentCategoryID uuid.UUID `json:"parent_category_id"`
|
||||||
|
ProductID uuid.UUID `json:"product_id"`
|
||||||
|
ProductName string `json:"product_name"`
|
||||||
|
QuantitySold int64 `json:"quantity_sold"`
|
||||||
|
Revenue float64 `json:"revenue"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// ParentCategoryAnalyticsDetail is the drill-down for a single parent category:
|
// ParentCategoryAnalyticsDetail is the drill-down for a single parent category:
|
||||||
@@ -171,6 +182,8 @@ type BudgetCutOffWeek struct {
|
|||||||
WeekStart time.Time `json:"week_start"`
|
WeekStart time.Time `json:"week_start"`
|
||||||
Revenue float64 `json:"revenue"`
|
Revenue float64 `json:"revenue"`
|
||||||
OrderCount int64 `json:"order_count"`
|
OrderCount int64 `json:"order_count"`
|
||||||
|
// SDL is summed per parent category, each at its own owner fee percent
|
||||||
|
SDL float64 `json:"sdl"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// DashboardOverview represents dashboard overview data
|
// DashboardOverview represents dashboard overview data
|
||||||
|
|||||||
@@ -41,6 +41,12 @@ type Category struct {
|
|||||||
Order int `gorm:"default:0" json:"order"`
|
Order int `gorm:"default:0" json:"order"`
|
||||||
BusinessType string `gorm:"size:50;default:'restaurant'" json:"business_type"`
|
BusinessType string `gorm:"size:50;default:'restaurant'" json:"business_type"`
|
||||||
Metadata Metadata `gorm:"type:jsonb;default:'{}'" json:"metadata"`
|
Metadata Metadata `gorm:"type:jsonb;default:'{}'" json:"metadata"`
|
||||||
|
// OwnerFeePercent overrides the owner's share in the parent category budget report; nil uses the default
|
||||||
|
OwnerFeePercent *float64 `gorm:"type:numeric(5,2)" json:"owner_fee_percent"`
|
||||||
|
// IsTeam marks a parent category as a team in the revenue split. It has no gorm
|
||||||
|
// default on purpose: GORM would turn an explicit false into the default on insert,
|
||||||
|
// so callers creating a category set it themselves.
|
||||||
|
IsTeam bool `gorm:"not null" json:"is_team"`
|
||||||
CreatedAt time.Time `gorm:"autoCreateTime" json:"created_at"`
|
CreatedAt time.Time `gorm:"autoCreateTime" json:"created_at"`
|
||||||
UpdatedAt time.Time `gorm:"autoUpdateTime" json:"updated_at"`
|
UpdatedAt time.Time `gorm:"autoUpdateTime" json:"updated_at"`
|
||||||
|
|
||||||
|
|||||||
@@ -13,16 +13,13 @@ const (
|
|||||||
PaymentMethodTypeCash PaymentMethodType = "cash"
|
PaymentMethodTypeCash PaymentMethodType = "cash"
|
||||||
PaymentMethodTypeCard PaymentMethodType = "card"
|
PaymentMethodTypeCard PaymentMethodType = "card"
|
||||||
PaymentMethodTypeDigitalWallet PaymentMethodType = "digital_wallet"
|
PaymentMethodTypeDigitalWallet PaymentMethodType = "digital_wallet"
|
||||||
// The system method for paying with EnakPoint (docs/prd-point-coin.md F9). One per
|
|
||||||
// organization; it cannot be created, deleted or retyped through the API.
|
|
||||||
PaymentMethodTypePoint PaymentMethodType = "point"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
type PaymentMethod struct {
|
type PaymentMethod struct {
|
||||||
ID uuid.UUID `gorm:"type:uuid;primary_key;default:gen_random_uuid()" json:"id"`
|
ID uuid.UUID `gorm:"type:uuid;primary_key;default:gen_random_uuid()" json:"id"`
|
||||||
OrganizationID uuid.UUID `gorm:"type:uuid;not null;index" json:"organization_id" validate:"required"`
|
OrganizationID uuid.UUID `gorm:"type:uuid;not null;index" json:"organization_id" validate:"required"`
|
||||||
Name string `gorm:"not null;size:100" json:"name" validate:"required,min=1,max=100"`
|
Name string `gorm:"not null;size:100" json:"name" validate:"required,min=1,max=100"`
|
||||||
Type PaymentMethodType `gorm:"not null;size:50" json:"type" validate:"required,oneof=cash card digital_wallet point"`
|
Type PaymentMethodType `gorm:"not null;size:50" json:"type" validate:"required,oneof=cash card digital_wallet"`
|
||||||
Processor *string `gorm:"size:100" json:"processor"`
|
Processor *string `gorm:"size:100" json:"processor"`
|
||||||
Configuration Metadata `gorm:"type:jsonb;default:'{}'" json:"configuration"`
|
Configuration Metadata `gorm:"type:jsonb;default:'{}'" json:"configuration"`
|
||||||
IsActive bool `gorm:"default:true" json:"is_active"`
|
IsActive bool `gorm:"default:true" json:"is_active"`
|
||||||
@@ -72,10 +69,6 @@ type Payment struct {
|
|||||||
SplitType *SplitType `gorm:"size:20" json:"split_type,omitempty"`
|
SplitType *SplitType `gorm:"size:20" json:"split_type,omitempty"`
|
||||||
SplitDescription *string `gorm:"size:255" json:"split_description,omitempty"`
|
SplitDescription *string `gorm:"size:255" json:"split_description,omitempty"`
|
||||||
RefundAmount float64 `gorm:"type:decimal(10,2);default:0.00" json:"refund_amount"`
|
RefundAmount float64 `gorm:"type:decimal(10,2);default:0.00" json:"refund_amount"`
|
||||||
// Set only for a payment with EnakPoint: how many were used, and the rupiah value of
|
|
||||||
// one then, frozen so a refund returns exactly what was used.
|
|
||||||
PointsUsed *int64 `json:"points_used,omitempty"`
|
|
||||||
PointValue *float64 `gorm:"type:decimal(10,2)" json:"point_value,omitempty"`
|
|
||||||
RefundReason *string `gorm:"size:255" json:"refund_reason,omitempty"`
|
RefundReason *string `gorm:"size:255" json:"refund_reason,omitempty"`
|
||||||
RefundedAt *time.Time `gorm:"" json:"refunded_at,omitempty"`
|
RefundedAt *time.Time `gorm:"" json:"refunded_at,omitempty"`
|
||||||
RefundedBy *uuid.UUID `gorm:"type:uuid" json:"refunded_by,omitempty"`
|
RefundedBy *uuid.UUID `gorm:"type:uuid" json:"refunded_by,omitempty"`
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
package entities
|
package entities
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/google/uuid"
|
"github.com/google/uuid"
|
||||||
@@ -18,7 +19,9 @@ type Product struct {
|
|||||||
Cost float64 `gorm:"type:decimal(10,2);default:0.00" json:"cost" validate:"min=0"`
|
Cost float64 `gorm:"type:decimal(10,2);default:0.00" json:"cost" validate:"min=0"`
|
||||||
BusinessType string `gorm:"size:50;default:'restaurant'" json:"business_type"`
|
BusinessType string `gorm:"size:50;default:'restaurant'" json:"business_type"`
|
||||||
ImageURL *string `gorm:"size:500" json:"image_url"`
|
ImageURL *string `gorm:"size:500" json:"image_url"`
|
||||||
PrinterType string `gorm:"size:50;default:'kitchen'" json:"printer_type"`
|
// PrinterTypes are the stations the product is printed at. Set them through
|
||||||
|
// SetPrinterTypes.
|
||||||
|
PrinterTypes StringSlice `gorm:"type:jsonb;not null;default:'[\"kitchen\"]'" json:"printer_types"`
|
||||||
UnitID *uuid.UUID `gorm:"type:uuid;index" json:"unit_id"`
|
UnitID *uuid.UUID `gorm:"type:uuid;index" json:"unit_id"`
|
||||||
SellBy string `gorm:"size:20;default:'unit'" json:"sell_by"`
|
SellBy string `gorm:"size:20;default:'unit'" json:"sell_by"`
|
||||||
HasIngredients bool `gorm:"default:false" json:"has_ingredients"`
|
HasIngredients bool `gorm:"default:false" json:"has_ingredients"`
|
||||||
@@ -48,6 +51,32 @@ func (Product) TableName() string {
|
|||||||
return "products"
|
return "products"
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// SetPrinterTypes records the stations the product is printed at, in order, dropping
|
||||||
|
// blanks and repeats.
|
||||||
|
func (p *Product) SetPrinterTypes(printerTypes []string) {
|
||||||
|
cleaned := StringSlice{}
|
||||||
|
seen := make(map[string]bool, len(printerTypes))
|
||||||
|
for _, printerType := range printerTypes {
|
||||||
|
printerType = strings.TrimSpace(printerType)
|
||||||
|
if printerType == "" || seen[printerType] {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
seen[printerType] = true
|
||||||
|
cleaned = append(cleaned, printerType)
|
||||||
|
}
|
||||||
|
|
||||||
|
p.PrinterTypes = cleaned
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetPrinterTypes returns the stations the product is printed at, never nil, so a
|
||||||
|
// response always carries a list. A product that was not loaded has none.
|
||||||
|
func (p *Product) GetPrinterTypes() []string {
|
||||||
|
if p.PrinterTypes == nil {
|
||||||
|
return []string{}
|
||||||
|
}
|
||||||
|
return []string(p.PrinterTypes)
|
||||||
|
}
|
||||||
|
|
||||||
type ProductVariant struct {
|
type ProductVariant struct {
|
||||||
ID uuid.UUID `gorm:"type:uuid;primary_key;default:gen_random_uuid()" json:"id"`
|
ID uuid.UUID `gorm:"type:uuid;primary_key;default:gen_random_uuid()" json:"id"`
|
||||||
ProductID uuid.UUID `gorm:"type:uuid;not null;index" json:"product_id" validate:"required"`
|
ProductID uuid.UUID `gorm:"type:uuid;not null;index" json:"product_id" validate:"required"`
|
||||||
|
|||||||
@@ -1,35 +0,0 @@
|
|||||||
package handler
|
|
||||||
|
|
||||||
import (
|
|
||||||
"github.com/gin-gonic/gin"
|
|
||||||
|
|
||||||
"apskel-pos-be/internal/contract"
|
|
||||||
"apskel-pos-be/internal/service"
|
|
||||||
"apskel-pos-be/internal/util"
|
|
||||||
)
|
|
||||||
|
|
||||||
// CustomerOrderPaymentHandler serves POST /customer/orders/:id/pay-with-points
|
|
||||||
// (docs/prd-point-coin.md F9). The body holds the PIN, so it is never logged.
|
|
||||||
type CustomerOrderPaymentHandler struct {
|
|
||||||
payments service.CustomerOrderPaymentService
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewCustomerOrderPaymentHandler(payments service.CustomerOrderPaymentService) *CustomerOrderPaymentHandler {
|
|
||||||
return &CustomerOrderPaymentHandler{payments: payments}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *CustomerOrderPaymentHandler) PayWithPoints(c *gin.Context) {
|
|
||||||
customerID, ok := customerIDFromGin(c, "CustomerOrderPaymentHandler::PayWithPoints")
|
|
||||||
if !ok {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
orderID, ok := parseUUIDParam(c, "id", "CustomerOrderPaymentHandler::PayWithPoints")
|
|
||||||
if !ok {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
var req contract.PayWithPointsRequest
|
|
||||||
if !bindPinRequest(c, &req, "CustomerOrderPaymentHandler::PayWithPoints") {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
util.HandleResponse(c.Writer, c.Request, h.payments.PayWithPoints(c.Request.Context(), customerID, orderID, &req, pinRequestInfo(c)), "CustomerOrderPaymentHandler::PayWithPoints")
|
|
||||||
}
|
|
||||||
@@ -136,16 +136,3 @@ func customerIDFromGin(c *gin.Context, method string) (uuid.UUID, bool) {
|
|||||||
func pinRequestInfo(c *gin.Context) models.CustomerPinRequestInfo {
|
func pinRequestInfo(c *gin.Context) models.CustomerPinRequestInfo {
|
||||||
return models.CustomerPinRequestInfo{IPAddress: c.ClientIP(), UserAgent: c.Request.UserAgent()}
|
return models.CustomerPinRequestInfo{IPAddress: c.ClientIP(), UserAgent: c.Request.UserAgent()}
|
||||||
}
|
}
|
||||||
|
|
||||||
// IssuePaymentCode is POST /customer/wallet/payment-code.
|
|
||||||
func (h *CustomerPinHandler) IssuePaymentCode(c *gin.Context) {
|
|
||||||
customerID, ok := customerIDFromGin(c, "CustomerPinHandler::IssuePaymentCode")
|
|
||||||
if !ok {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
var req contract.IssuePaymentCodeRequest
|
|
||||||
if !bindPinRequest(c, &req, "CustomerPinHandler::IssuePaymentCode") {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
util.HandleResponse(c.Writer, c.Request, h.pinService.IssuePaymentCode(c.Request.Context(), customerID, &req, pinRequestInfo(c)), "CustomerPinHandler::IssuePaymentCode")
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -82,9 +82,9 @@ func TestCustomerWalletEndpoints_AgainstPostgres(t *testing.T) {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
if _, err := wallet.Debit(ctx, processor.WalletDebitInput{WalletEntry: processor.WalletEntry{
|
if _, err := wallet.Debit(ctx, processor.WalletDebitInput{WalletEntry: processor.WalletEntry{
|
||||||
CustomerID: customer, Currency: constants.WalletCurrencyPoint, Type: constants.WalletTxTypePayment,
|
CustomerID: customer, Currency: constants.WalletCurrencyPoint, Type: constants.WalletTxTypeRewardRedeem,
|
||||||
Amount: 50, ReferenceType: constants.WalletRefTypePayment, ReferenceID: payment, OutletID: &outlet,
|
Amount: 50, ReferenceType: constants.WalletRefTypeRewardRedemption, ReferenceID: payment, OutletID: &outlet,
|
||||||
Description: "Bayar #ORD-2"}}); err != nil {
|
Description: "Tukar voucher"}}); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
_, err := wallet.Credit(ctx, processor.WalletCreditInput{
|
_, err := wallet.Credit(ctx, processor.WalletCreditInput{
|
||||||
@@ -162,7 +162,7 @@ func TestCustomerWalletEndpoints_AgainstPostgres(t *testing.T) {
|
|||||||
assert.Contains(t, tx, "source", tx["type"])
|
assert.Contains(t, tx, "source", tx["type"])
|
||||||
assert.NotContains(t, tx, "destination")
|
assert.NotContains(t, tx, "destination")
|
||||||
} else {
|
} else {
|
||||||
assert.Equal(t, map[string]any{"type": "PAYMENT", "id": payment.String()}, tx["destination"])
|
assert.Equal(t, map[string]any{"type": "REWARD_REDEMPTION", "id": payment.String()}, tx["destination"])
|
||||||
assert.NotContains(t, tx, "source")
|
assert.NotContains(t, tx, "source")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -91,9 +91,9 @@ func TestOutletLoyaltySettingsEndpoints_AgainstPostgres(t *testing.T) {
|
|||||||
status, body := call(http.MethodGet, "/manager"+path, "")
|
status, body := call(http.MethodGet, "/manager"+path, "")
|
||||||
require.Equal(t, http.StatusOK, status, body)
|
require.Equal(t, http.StatusOK, status, body)
|
||||||
got := data(body)
|
got := data(body)
|
||||||
assert.Equal(t, map[string]any{"enabled": false, "earn_per_amount": float64(100), "earn_value": float64(1), "min_order_amount": float64(0), "max_per_order": nil}, got["point"])
|
assert.Equal(t, map[string]any{"enabled": false, "earn_mode": "PER_AMOUNT", "earn_per_amount": float64(100), "earn_value": float64(1), "earn_percent": float64(1), "min_order_amount": float64(0), "max_per_order": nil}, got["point"])
|
||||||
assert.Equal(t, map[string]any{"enabled": false, "earn_per_amount": float64(25000), "earn_value": float64(1), "min_order_amount": float64(0), "max_per_order": nil}, got["coin"])
|
assert.Equal(t, map[string]any{"enabled": false, "earn_mode": "PER_AMOUNT", "earn_per_amount": float64(25000), "earn_value": float64(1), "earn_percent": float64(1), "min_order_amount": float64(0), "max_per_order": nil}, got["coin"])
|
||||||
assert.Equal(t, map[string]any{"accept_payment": false, "min_payment_points": float64(1), "max_payment_percent": float64(100)}, got["point_payment"])
|
assert.NotContains(t, got, "point_payment", "EnakPoint cannot pay (docs/enakgame-prd.md §3.2)")
|
||||||
assert.EqualValues(t, 1, got["point_value"])
|
assert.EqualValues(t, 1, got["point_value"])
|
||||||
assert.EqualValues(t, 1, got["point_cashback_percent"])
|
assert.EqualValues(t, 1, got["point_cashback_percent"])
|
||||||
|
|
||||||
@@ -135,9 +135,11 @@ func TestOutletLoyaltySettingsEndpoints_AgainstPostgres(t *testing.T) {
|
|||||||
for name, bad := range map[string]string{
|
for name, bad := range map[string]string{
|
||||||
"earn_per_amount 0": `{"point": {"earn_per_amount": 0}}`,
|
"earn_per_amount 0": `{"point": {"earn_per_amount": 0}}`,
|
||||||
"negative earn_value": `{"coin": {"earn_value": -1}}`,
|
"negative earn_value": `{"coin": {"earn_value": -1}}`,
|
||||||
|
"earn mode unknown": `{"point": {"earn_mode": "PERCENT"}}`,
|
||||||
|
"earn_percent over 100": `{"coin": {"earn_percent": 101}}`,
|
||||||
"negative min_order": `{"point": {"min_order_amount": -5}}`,
|
"negative min_order": `{"point": {"min_order_amount": -5}}`,
|
||||||
"negative max_per_order": `{"point": {"max_per_order": -1}}`,
|
"negative max_per_order": `{"point": {"max_per_order": -1}}`,
|
||||||
"payment percent over 100": `{"point_payment": {"max_payment_percent": 101}}`,
|
"point_payment removed": `{"point_payment": {"accept_payment": true}}`,
|
||||||
"unknown field": `{"point": {"earn_per_amout": 50}}`,
|
"unknown field": `{"point": {"earn_per_amout": 50}}`,
|
||||||
"wrong type": `{"point": {"enabled": "yes"}}`,
|
"wrong type": `{"point": {"enabled": "yes"}}`,
|
||||||
"not json": `enabled=true`,
|
"not json": `enabled=true`,
|
||||||
|
|||||||
@@ -1,11 +1,8 @@
|
|||||||
package handler
|
package handler
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"errors"
|
|
||||||
|
|
||||||
"apskel-pos-be/internal/appcontext"
|
"apskel-pos-be/internal/appcontext"
|
||||||
"apskel-pos-be/internal/contract"
|
"apskel-pos-be/internal/contract"
|
||||||
"apskel-pos-be/internal/processor"
|
|
||||||
"apskel-pos-be/internal/service"
|
"apskel-pos-be/internal/service"
|
||||||
"apskel-pos-be/internal/transformer"
|
"apskel-pos-be/internal/transformer"
|
||||||
"apskel-pos-be/internal/util"
|
"apskel-pos-be/internal/util"
|
||||||
@@ -205,11 +202,6 @@ func (h *OrderHandler) RefundOrder(c *gin.Context) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if err := h.orderService.RefundOrder(ctx, id, modelReq, userID); err != nil {
|
if err := h.orderService.RefundOrder(ctx, id, modelReq, userID); err != nil {
|
||||||
// Refusing to hand EnakPoint back as cash is a bad request, not a server fault.
|
|
||||||
if errors.Is(err, processor.ErrPointPaymentRejected) {
|
|
||||||
util.HandleResponse(c.Writer, c.Request, service.PointPaymentErrorResponse(err), "OrderHandler::RefundOrder")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{contract.NewResponseError("internal_error", "OrderHandler::RefundOrder", err.Error())}), "OrderHandler::RefundOrder")
|
util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{contract.NewResponseError("internal_error", "OrderHandler::RefundOrder", err.Error())}), "OrderHandler::RefundOrder")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -233,11 +225,6 @@ func (h *OrderHandler) CreatePayment(c *gin.Context) {
|
|||||||
|
|
||||||
response, err := h.orderService.CreatePayment(c.Request.Context(), modelReq)
|
response, err := h.orderService.CreatePayment(c.Request.Context(), modelReq)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
// A refused EnakPoint payment is the cashier's or customer's to fix, not a server fault.
|
|
||||||
if errors.Is(err, processor.ErrPointPaymentRejected) {
|
|
||||||
util.HandleResponse(c.Writer, c.Request, service.PointPaymentErrorResponse(err), "OrderHandler::CreatePayment")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{contract.NewResponseError("internal_error", "OrderHandler::CreatePayment", err.Error())}), "OrderHandler::CreatePayment")
|
util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{contract.NewResponseError("internal_error", "OrderHandler::CreatePayment", err.Error())}), "OrderHandler::CreatePayment")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -113,16 +113,6 @@ func (h *PaymentMethodHandler) ListPaymentMethods(c *gin.Context) {
|
|||||||
|
|
||||||
req.OrganizationID = &contextInfo.OrganizationID
|
req.OrganizationID = &contextInfo.OrganizationID
|
||||||
|
|
||||||
// At the cashier, EnakPoint is listed only where the outlet accepts it (F9).
|
|
||||||
if outletStr := c.Query("outlet_id"); outletStr != "" {
|
|
||||||
if outletID, err := uuid.Parse(outletStr); err == nil {
|
|
||||||
req.OutletID = &outletID
|
|
||||||
}
|
|
||||||
} else if contextInfo.OutletID != uuid.Nil {
|
|
||||||
outletID := contextInfo.OutletID
|
|
||||||
req.OutletID = &outletID
|
|
||||||
}
|
|
||||||
|
|
||||||
if isActiveStr := c.Query("is_active"); isActiveStr != "" {
|
if isActiveStr := c.Query("is_active"); isActiveStr != "" {
|
||||||
if isActive, err := strconv.ParseBool(isActiveStr); err == nil {
|
if isActive, err := strconv.ParseBool(isActiveStr); err == nil {
|
||||||
req.IsActive = &isActive
|
req.IsActive = &isActive
|
||||||
|
|||||||
@@ -1,28 +0,0 @@
|
|||||||
package handler
|
|
||||||
|
|
||||||
import (
|
|
||||||
"github.com/gin-gonic/gin"
|
|
||||||
|
|
||||||
"apskel-pos-be/internal/appcontext"
|
|
||||||
"apskel-pos-be/internal/service"
|
|
||||||
"apskel-pos-be/internal/util"
|
|
||||||
)
|
|
||||||
|
|
||||||
// PointPaymentHandler serves GET /orders/:id/point-payment/preview
|
|
||||||
// (docs/prd-point-coin.md F9).
|
|
||||||
type PointPaymentHandler struct {
|
|
||||||
pointPaymentService service.PointPaymentService
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewPointPaymentHandler(pointPaymentService service.PointPaymentService) *PointPaymentHandler {
|
|
||||||
return &PointPaymentHandler{pointPaymentService: pointPaymentService}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *PointPaymentHandler) Preview(c *gin.Context) {
|
|
||||||
orderID, ok := parseUUIDParam(c, "id", "PointPaymentHandler::Preview")
|
|
||||||
if !ok {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
ctx := c.Request.Context()
|
|
||||||
util.HandleResponse(c.Writer, c.Request, h.pointPaymentService.Preview(ctx, appcontext.FromGinContext(ctx), orderID), "PointPaymentHandler::Preview")
|
|
||||||
}
|
|
||||||
@@ -58,6 +58,12 @@ func CreateCategoryRequestToEntity(req *models.CreateCategoryRequest) *entities.
|
|||||||
metadata["image_url"] = *req.ImageURL
|
metadata["image_url"] = *req.ImageURL
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// A category is a team unless the request says otherwise
|
||||||
|
isTeam := true
|
||||||
|
if req.IsTeam != nil {
|
||||||
|
isTeam = *req.IsTeam
|
||||||
|
}
|
||||||
|
|
||||||
return &entities.Category{
|
return &entities.Category{
|
||||||
OrganizationID: req.OrganizationID,
|
OrganizationID: req.OrganizationID,
|
||||||
OutletID: req.OutletID,
|
OutletID: req.OutletID,
|
||||||
@@ -65,6 +71,8 @@ func CreateCategoryRequestToEntity(req *models.CreateCategoryRequest) *entities.
|
|||||||
Name: req.Name,
|
Name: req.Name,
|
||||||
Description: req.Description,
|
Description: req.Description,
|
||||||
Order: req.Order,
|
Order: req.Order,
|
||||||
|
OwnerFeePercent: req.OwnerFeePercent,
|
||||||
|
IsTeam: isTeam,
|
||||||
BusinessType: "restaurant",
|
BusinessType: "restaurant",
|
||||||
Metadata: metadata,
|
Metadata: metadata,
|
||||||
}
|
}
|
||||||
@@ -103,6 +111,8 @@ func CategoryEntityToResponse(entity *entities.Category) *models.CategoryRespons
|
|||||||
Description: entity.Description,
|
Description: entity.Description,
|
||||||
ImageURL: imageURL,
|
ImageURL: imageURL,
|
||||||
Order: entity.Order,
|
Order: entity.Order,
|
||||||
|
OwnerFeePercent: entity.OwnerFeePercent,
|
||||||
|
IsTeam: entity.IsTeam,
|
||||||
IsActive: true,
|
IsActive: true,
|
||||||
CreatedAt: entity.CreatedAt,
|
CreatedAt: entity.CreatedAt,
|
||||||
UpdatedAt: entity.UpdatedAt,
|
UpdatedAt: entity.UpdatedAt,
|
||||||
@@ -134,11 +144,25 @@ func UpdateCategoryEntityFromRequest(entity *entities.Category, req *models.Upda
|
|||||||
entity.Order = *req.Order
|
entity.Order = *req.Order
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if req.ClearOwnerFeePercent {
|
||||||
|
entity.OwnerFeePercent = nil
|
||||||
|
} else if req.OwnerFeePercent != nil {
|
||||||
|
entity.OwnerFeePercent = req.OwnerFeePercent
|
||||||
|
}
|
||||||
|
|
||||||
|
if req.IsTeam != nil {
|
||||||
|
entity.IsTeam = *req.IsTeam
|
||||||
|
}
|
||||||
|
|
||||||
if req.OutletID != nil {
|
if req.OutletID != nil {
|
||||||
entity.OutletID = req.OutletID
|
entity.OutletID = req.OutletID
|
||||||
}
|
}
|
||||||
|
|
||||||
if req.ParentID != nil {
|
if req.ClearParentID {
|
||||||
|
// Drop the preloaded parent too, so the response stops reporting it
|
||||||
|
entity.ParentID = nil
|
||||||
|
entity.Parent = nil
|
||||||
|
} else if req.ParentID != nil {
|
||||||
entity.ParentID = req.ParentID
|
entity.ParentID = req.ParentID
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,34 @@
|
|||||||
|
package mappers
|
||||||
|
|
||||||
|
import (
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"apskel-pos-be/internal/models"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
"github.com/stretchr/testify/require"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestCreateCategoryRequestToEntityDefaultsToTeam(t *testing.T) {
|
||||||
|
notTeam := false
|
||||||
|
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
isTeam *bool
|
||||||
|
want bool
|
||||||
|
}{
|
||||||
|
{name: "omitted is a team", isTeam: nil, want: true},
|
||||||
|
{name: "false is not a team", isTeam: ¬Team, want: false},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, tt := range tests {
|
||||||
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
|
entity := CreateCategoryRequestToEntity(&models.CreateCategoryRequest{
|
||||||
|
OrganizationID: uuid.New(),
|
||||||
|
Name: "Merchandise",
|
||||||
|
IsTeam: tt.isTeam,
|
||||||
|
})
|
||||||
|
require.Equal(t, tt.want, entity.IsTeam)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -149,7 +149,7 @@ func OrderItemEntityToResponse(item *entities.OrderItem, outletID uuid.UUID) *mo
|
|||||||
Status: constants.OrderItemStatus(item.Status),
|
Status: constants.OrderItemStatus(item.Status),
|
||||||
CreatedAt: item.CreatedAt,
|
CreatedAt: item.CreatedAt,
|
||||||
UpdatedAt: item.UpdatedAt,
|
UpdatedAt: item.UpdatedAt,
|
||||||
PrinterType: item.Product.PrinterType,
|
PrinterTypes: item.Product.GetPrinterTypes(),
|
||||||
PrintToChecker: printToChecker,
|
PrintToChecker: printToChecker,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -189,8 +189,6 @@ func PaymentEntityToResponse(payment *entities.Payment) *models.PaymentResponse
|
|||||||
SplitType: (*string)(payment.SplitType),
|
SplitType: (*string)(payment.SplitType),
|
||||||
SplitDescription: payment.SplitDescription,
|
SplitDescription: payment.SplitDescription,
|
||||||
RefundAmount: payment.RefundAmount,
|
RefundAmount: payment.RefundAmount,
|
||||||
PointsUsed: payment.PointsUsed,
|
|
||||||
PointValue: payment.PointValue,
|
|
||||||
RefundReason: payment.RefundReason,
|
RefundReason: payment.RefundReason,
|
||||||
RefundedAt: payment.RefundedAt,
|
RefundedAt: payment.RefundedAt,
|
||||||
RefundedBy: payment.RefundedBy,
|
RefundedBy: payment.RefundedBy,
|
||||||
|
|||||||
@@ -134,7 +134,6 @@ func ListPaymentMethodsContractToModel(req *contract.ListPaymentMethodsRequest)
|
|||||||
|
|
||||||
return &models.ListPaymentMethodsRequest{
|
return &models.ListPaymentMethodsRequest{
|
||||||
OrganizationID: req.OrganizationID,
|
OrganizationID: req.OrganizationID,
|
||||||
OutletID: req.OutletID,
|
|
||||||
Type: paymentMethodType,
|
Type: paymentMethodType,
|
||||||
IsActive: req.IsActive,
|
IsActive: req.IsActive,
|
||||||
Search: req.Search,
|
Search: req.Search,
|
||||||
|
|||||||
@@ -24,7 +24,7 @@ func ProductEntityToModel(entity *entities.Product) *models.Product {
|
|||||||
Cost: entity.Cost,
|
Cost: entity.Cost,
|
||||||
BusinessType: constants.BusinessType(entity.BusinessType),
|
BusinessType: constants.BusinessType(entity.BusinessType),
|
||||||
ImageURL: entity.ImageURL,
|
ImageURL: entity.ImageURL,
|
||||||
PrinterType: entity.PrinterType,
|
PrinterTypes: entity.GetPrinterTypes(),
|
||||||
UnitID: entity.UnitID,
|
UnitID: entity.UnitID,
|
||||||
SellBy: entity.SellBy,
|
SellBy: entity.SellBy,
|
||||||
HasIngredients: entity.HasIngredients,
|
HasIngredients: entity.HasIngredients,
|
||||||
@@ -51,7 +51,7 @@ func ProductModelToEntity(model *models.Product) *entities.Product {
|
|||||||
Cost: model.Cost,
|
Cost: model.Cost,
|
||||||
BusinessType: string(model.BusinessType),
|
BusinessType: string(model.BusinessType),
|
||||||
ImageURL: model.ImageURL,
|
ImageURL: model.ImageURL,
|
||||||
PrinterType: model.PrinterType,
|
PrinterTypes: entities.StringSlice(model.PrinterTypes),
|
||||||
UnitID: model.UnitID,
|
UnitID: model.UnitID,
|
||||||
SellBy: model.SellBy,
|
SellBy: model.SellBy,
|
||||||
HasIngredients: model.HasIngredients,
|
HasIngredients: model.HasIngredients,
|
||||||
@@ -77,11 +77,6 @@ func CreateProductRequestToEntity(req *models.CreateProductRequest) *entities.Pr
|
|||||||
businessType = string(req.BusinessType)
|
businessType = string(req.BusinessType)
|
||||||
}
|
}
|
||||||
|
|
||||||
printerType := "kitchen"
|
|
||||||
if req.PrinterType != nil && *req.PrinterType != "" {
|
|
||||||
printerType = *req.PrinterType
|
|
||||||
}
|
|
||||||
|
|
||||||
sellBy := constants.SellByUnit
|
sellBy := constants.SellByUnit
|
||||||
if constants.IsValidSellBy(req.SellBy) {
|
if constants.IsValidSellBy(req.SellBy) {
|
||||||
sellBy = req.SellBy
|
sellBy = req.SellBy
|
||||||
@@ -92,7 +87,7 @@ func CreateProductRequestToEntity(req *models.CreateProductRequest) *entities.Pr
|
|||||||
metadata = entities.Metadata(req.Metadata)
|
metadata = entities.Metadata(req.Metadata)
|
||||||
}
|
}
|
||||||
|
|
||||||
return &entities.Product{
|
product := &entities.Product{
|
||||||
OrganizationID: req.OrganizationID,
|
OrganizationID: req.OrganizationID,
|
||||||
CategoryID: req.CategoryID,
|
CategoryID: req.CategoryID,
|
||||||
SKU: req.SKU,
|
SKU: req.SKU,
|
||||||
@@ -102,12 +97,18 @@ func CreateProductRequestToEntity(req *models.CreateProductRequest) *entities.Pr
|
|||||||
Cost: cost,
|
Cost: cost,
|
||||||
BusinessType: businessType,
|
BusinessType: businessType,
|
||||||
ImageURL: req.ImageURL,
|
ImageURL: req.ImageURL,
|
||||||
PrinterType: printerType,
|
|
||||||
UnitID: req.UnitID,
|
UnitID: req.UnitID,
|
||||||
SellBy: sellBy,
|
SellBy: sellBy,
|
||||||
Metadata: metadata,
|
Metadata: metadata,
|
||||||
IsActive: true, // Default to active
|
IsActive: true, // Default to active
|
||||||
}
|
}
|
||||||
|
|
||||||
|
product.SetPrinterTypes(req.PrinterTypes)
|
||||||
|
if len(product.PrinterTypes) == 0 {
|
||||||
|
product.SetPrinterTypes([]string{"kitchen"})
|
||||||
|
}
|
||||||
|
|
||||||
|
return product
|
||||||
}
|
}
|
||||||
|
|
||||||
func ProductEntityToResponse(entity *entities.Product) *models.ProductResponse {
|
func ProductEntityToResponse(entity *entities.Product) *models.ProductResponse {
|
||||||
@@ -152,7 +153,7 @@ func ProductEntityToResponse(entity *entities.Product) *models.ProductResponse {
|
|||||||
Cost: entity.Cost,
|
Cost: entity.Cost,
|
||||||
BusinessType: constants.BusinessType(entity.BusinessType),
|
BusinessType: constants.BusinessType(entity.BusinessType),
|
||||||
ImageURL: entity.ImageURL,
|
ImageURL: entity.ImageURL,
|
||||||
PrinterType: entity.PrinterType,
|
PrinterTypes: entity.GetPrinterTypes(),
|
||||||
UnitID: entity.UnitID,
|
UnitID: entity.UnitID,
|
||||||
SellBy: entity.SellBy,
|
SellBy: entity.SellBy,
|
||||||
Metadata: map[string]interface{}(entity.Metadata),
|
Metadata: map[string]interface{}(entity.Metadata),
|
||||||
@@ -196,8 +197,8 @@ func UpdateProductEntityFromRequest(entity *entities.Product, req *models.Update
|
|||||||
entity.ImageURL = req.ImageURL
|
entity.ImageURL = req.ImageURL
|
||||||
}
|
}
|
||||||
|
|
||||||
if req.PrinterType != nil {
|
if req.PrinterTypes != nil {
|
||||||
entity.PrinterType = *req.PrinterType
|
entity.SetPrinterTypes(req.PrinterTypes)
|
||||||
}
|
}
|
||||||
|
|
||||||
if req.UnitID != nil {
|
if req.UnitID != nil {
|
||||||
|
|||||||
@@ -0,0 +1,102 @@
|
|||||||
|
package mappers
|
||||||
|
|
||||||
|
import (
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"apskel-pos-be/internal/entities"
|
||||||
|
"apskel-pos-be/internal/models"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
"github.com/stretchr/testify/assert"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestCreateProductRequestToEntityPrinterTypes(t *testing.T) {
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
printerTypes []string
|
||||||
|
want []string
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
name: "nothing sent prints in the kitchen",
|
||||||
|
want: []string{"kitchen"},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "a meal-and-drink package prints in the kitchen and the bar",
|
||||||
|
printerTypes: []string{"kitchen", "bar"},
|
||||||
|
want: []string{"kitchen", "bar"},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "blanks and repeats are dropped",
|
||||||
|
printerTypes: []string{" kitchen ", "", "kitchen", "bar"},
|
||||||
|
want: []string{"kitchen", "bar"},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "a list of only blanks falls back to the kitchen",
|
||||||
|
printerTypes: []string{" ", ""},
|
||||||
|
want: []string{"kitchen"},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, tt := range tests {
|
||||||
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
|
product := CreateProductRequestToEntity(&models.CreateProductRequest{
|
||||||
|
OrganizationID: uuid.New(),
|
||||||
|
CategoryID: uuid.New(),
|
||||||
|
Name: "Paket Makan Minum",
|
||||||
|
PrinterTypes: tt.printerTypes,
|
||||||
|
})
|
||||||
|
|
||||||
|
assert.Equal(t, entities.StringSlice(tt.want), product.PrinterTypes)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestUpdateProductEntityFromRequestPrinterTypes(t *testing.T) {
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
printerTypes []string
|
||||||
|
want []string
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
name: "a save that does not send printers keeps them",
|
||||||
|
want: []string{"kitchen", "bar"},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "printer_types replaces the whole list",
|
||||||
|
printerTypes: []string{"bar"},
|
||||||
|
want: []string{"bar"},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "an empty printer_types prints nowhere",
|
||||||
|
printerTypes: []string{},
|
||||||
|
want: []string{},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, tt := range tests {
|
||||||
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
|
product := &entities.Product{}
|
||||||
|
product.SetPrinterTypes([]string{"kitchen", "bar"})
|
||||||
|
|
||||||
|
UpdateProductEntityFromRequest(product, &models.UpdateProductRequest{PrinterTypes: tt.printerTypes})
|
||||||
|
|
||||||
|
assert.Equal(t, entities.StringSlice(tt.want), product.PrinterTypes)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestOrderItemEntityToResponsePrinterTypes(t *testing.T) {
|
||||||
|
product := entities.Product{ID: uuid.New(), Name: "Paket Makan Minum"}
|
||||||
|
product.SetPrinterTypes([]string{"kitchen", "bar"})
|
||||||
|
|
||||||
|
response := OrderItemEntityToResponse(&entities.OrderItem{ProductID: product.ID, Product: product}, uuid.New())
|
||||||
|
|
||||||
|
assert.Equal(t, []string{"kitchen", "bar"}, response.PrinterTypes)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestProductEntityToResponseAlwaysHasAList(t *testing.T) {
|
||||||
|
// The POS reads printer_types as a list, so a product without one sends [] not null.
|
||||||
|
response := ProductEntityToResponse(&entities.Product{})
|
||||||
|
|
||||||
|
assert.Equal(t, []string{}, response.PrinterTypes)
|
||||||
|
}
|
||||||
@@ -33,14 +33,7 @@ type PaymentMethodAnalyticsResponse struct {
|
|||||||
|
|
||||||
// PaymentMethodSummary represents the summary of payment method analytics
|
// PaymentMethodSummary represents the summary of payment method analytics
|
||||||
type PaymentMethodSummary struct {
|
type PaymentMethodSummary struct {
|
||||||
// Money actually received. EnakPoint is not money in (docs/prd-point-coin.md F9,
|
|
||||||
// K7) and is reported apart; its accounting treatment waits on note N2.
|
|
||||||
TotalAmount float64 `json:"total_amount"`
|
TotalAmount float64 `json:"total_amount"`
|
||||||
// Rupiah paid with EnakPoint, and how many EnakPoint that was.
|
|
||||||
PointAmount float64 `json:"point_amount"`
|
|
||||||
PointsUsed int64 `json:"points_used"`
|
|
||||||
// TotalAmount plus PointAmount: the value of the orders paid.
|
|
||||||
TotalWithPoints float64 `json:"total_with_points"`
|
|
||||||
TotalOrders int64 `json:"total_orders"`
|
TotalOrders int64 `json:"total_orders"`
|
||||||
TotalPayments int64 `json:"total_payments"`
|
TotalPayments int64 `json:"total_payments"`
|
||||||
AverageOrderValue float64 `json:"average_order_value"`
|
AverageOrderValue float64 `json:"average_order_value"`
|
||||||
@@ -54,11 +47,7 @@ type PaymentMethodAnalyticsData struct {
|
|||||||
TotalAmount float64 `json:"total_amount"`
|
TotalAmount float64 `json:"total_amount"`
|
||||||
OrderCount int64 `json:"order_count"`
|
OrderCount int64 `json:"order_count"`
|
||||||
PaymentCount int64 `json:"payment_count"`
|
PaymentCount int64 `json:"payment_count"`
|
||||||
// Share of the money received; 0 for EnakPoint, which is not money in.
|
|
||||||
Percentage float64 `json:"percentage"`
|
Percentage float64 `json:"percentage"`
|
||||||
PointsUsed int64 `json:"points_used"`
|
|
||||||
// False for EnakPoint.
|
|
||||||
CountsAsCashIn bool `json:"counts_as_cash_in"`
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// SalesAnalyticsRequest represents the request for sales analytics
|
// SalesAnalyticsRequest represents the request for sales analytics
|
||||||
@@ -308,6 +297,8 @@ type ProductAnalyticsPerParentCategoryResponse struct {
|
|||||||
type ProductAnalyticsPerParentCategoryData struct {
|
type ProductAnalyticsPerParentCategoryData struct {
|
||||||
ParentCategoryID uuid.UUID `json:"parent_category_id"`
|
ParentCategoryID uuid.UUID `json:"parent_category_id"`
|
||||||
ParentCategoryName string `json:"parent_category_name"`
|
ParentCategoryName string `json:"parent_category_name"`
|
||||||
|
OwnerFeePercent float64 `json:"owner_fee_percent"`
|
||||||
|
SDL float64 `json:"sdl"`
|
||||||
TotalRevenue float64 `json:"total_revenue"`
|
TotalRevenue float64 `json:"total_revenue"`
|
||||||
TotalQuantity int64 `json:"total_quantity"`
|
TotalQuantity int64 `json:"total_quantity"`
|
||||||
CategoryCount int64 `json:"category_count"`
|
CategoryCount int64 `json:"category_count"`
|
||||||
@@ -316,6 +307,15 @@ type ProductAnalyticsPerParentCategoryData struct {
|
|||||||
TotalStandardHpp float64 `json:"total_standard_hpp"`
|
TotalStandardHpp float64 `json:"total_standard_hpp"`
|
||||||
TotalFifoHpp float64 `json:"total_fifo_hpp"`
|
TotalFifoHpp float64 `json:"total_fifo_hpp"`
|
||||||
TotalMovingAverageHpp float64 `json:"total_moving_average_hpp"`
|
TotalMovingAverageHpp float64 `json:"total_moving_average_hpp"`
|
||||||
|
TopProduct *ParentCategoryTopProduct `json:"top_product"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// ParentCategoryTopProduct is the best-selling product of a parent category by revenue.
|
||||||
|
type ParentCategoryTopProduct struct {
|
||||||
|
ProductID uuid.UUID `json:"product_id"`
|
||||||
|
ProductName string `json:"product_name"`
|
||||||
|
QuantitySold int64 `json:"quantity_sold"`
|
||||||
|
Revenue float64 `json:"revenue"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// ParentCategoryAnalyticsDetailRequest represents the request for the drill-down of one parent category
|
// ParentCategoryAnalyticsDetailRequest represents the request for the drill-down of one parent category
|
||||||
@@ -342,6 +342,8 @@ type ParentCategoryAnalyticsDetailResponse struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type ParentCategoryAnalyticsDetailSummary struct {
|
type ParentCategoryAnalyticsDetailSummary struct {
|
||||||
|
OwnerFeePercent float64 `json:"owner_fee_percent"`
|
||||||
|
SDL float64 `json:"sdl"`
|
||||||
TotalRevenue float64 `json:"total_revenue"`
|
TotalRevenue float64 `json:"total_revenue"`
|
||||||
TotalQuantity int64 `json:"total_quantity"`
|
TotalQuantity int64 `json:"total_quantity"`
|
||||||
CategoryCount int64 `json:"category_count"`
|
CategoryCount int64 `json:"category_count"`
|
||||||
@@ -350,11 +352,15 @@ type ParentCategoryAnalyticsDetailSummary struct {
|
|||||||
TotalStandardHpp float64 `json:"total_standard_hpp"`
|
TotalStandardHpp float64 `json:"total_standard_hpp"`
|
||||||
TotalFifoHpp float64 `json:"total_fifo_hpp"`
|
TotalFifoHpp float64 `json:"total_fifo_hpp"`
|
||||||
TotalMovingAverageHpp float64 `json:"total_moving_average_hpp"`
|
TotalMovingAverageHpp float64 `json:"total_moving_average_hpp"`
|
||||||
|
TopProduct *ParentCategoryTopProduct `json:"top_product"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type ParentCategoryAnalyticsDetailData struct {
|
type ParentCategoryAnalyticsDetailData struct {
|
||||||
CategoryID uuid.UUID `json:"category_id"`
|
CategoryID uuid.UUID `json:"category_id"`
|
||||||
CategoryName string `json:"category_name"`
|
CategoryName string `json:"category_name"`
|
||||||
|
OwnerFeePercent float64 `json:"owner_fee_percent"`
|
||||||
|
SDL float64 `json:"sdl"`
|
||||||
|
TopProduct *ParentCategoryTopProduct `json:"top_product"`
|
||||||
TotalRevenue float64 `json:"total_revenue"`
|
TotalRevenue float64 `json:"total_revenue"`
|
||||||
TotalQuantity int64 `json:"total_quantity"`
|
TotalQuantity int64 `json:"total_quantity"`
|
||||||
ProductCount int64 `json:"product_count"`
|
ProductCount int64 `json:"product_count"`
|
||||||
@@ -395,7 +401,6 @@ type BudgetCutOff struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type BudgetPercentages struct {
|
type BudgetPercentages struct {
|
||||||
Purchase float64 `json:"purchase"`
|
|
||||||
Owner float64 `json:"owner"`
|
Owner float64 `json:"owner"`
|
||||||
Team float64 `json:"team"`
|
Team float64 `json:"team"`
|
||||||
}
|
}
|
||||||
@@ -405,8 +410,7 @@ type BudgetPeriod struct {
|
|||||||
PeriodEnd time.Time `json:"period_end"`
|
PeriodEnd time.Time `json:"period_end"`
|
||||||
Revenue float64 `json:"revenue"`
|
Revenue float64 `json:"revenue"`
|
||||||
OrderCount int64 `json:"order_count"`
|
OrderCount int64 `json:"order_count"`
|
||||||
LimitPurchase float64 `json:"limit_purchase"`
|
SDL float64 `json:"sdl"`
|
||||||
LimitOwner float64 `json:"limit_owner"`
|
|
||||||
LimitTeam float64 `json:"limit_team"`
|
LimitTeam float64 `json:"limit_team"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -27,6 +27,9 @@ type CreateCategoryRequest struct {
|
|||||||
Description *string `validate:"omitempty,max=1000"`
|
Description *string `validate:"omitempty,max=1000"`
|
||||||
ImageURL *string `validate:"omitempty,url"`
|
ImageURL *string `validate:"omitempty,url"`
|
||||||
Order int `validate:"min=0"`
|
Order int `validate:"min=0"`
|
||||||
|
OwnerFeePercent *float64 `validate:"omitempty,min=0,max=100"`
|
||||||
|
// IsTeam defaults to true when left out
|
||||||
|
IsTeam *bool
|
||||||
}
|
}
|
||||||
|
|
||||||
type UpdateCategoryRequest struct {
|
type UpdateCategoryRequest struct {
|
||||||
@@ -36,7 +39,13 @@ type UpdateCategoryRequest struct {
|
|||||||
OutletID *uuid.UUID
|
OutletID *uuid.UUID
|
||||||
ParentID *uuid.UUID
|
ParentID *uuid.UUID
|
||||||
Order *int `validate:"omitempty,min=0"`
|
Order *int `validate:"omitempty,min=0"`
|
||||||
|
OwnerFeePercent *float64 `validate:"omitempty,min=0,max=100"`
|
||||||
|
IsTeam *bool
|
||||||
IsActive *bool
|
IsActive *bool
|
||||||
|
|
||||||
|
// Clear flags remove the value; a nil pointer above only means "leave unchanged"
|
||||||
|
ClearParentID bool
|
||||||
|
ClearOwnerFeePercent bool
|
||||||
}
|
}
|
||||||
|
|
||||||
type CategoryResponse struct {
|
type CategoryResponse struct {
|
||||||
@@ -49,6 +58,8 @@ type CategoryResponse struct {
|
|||||||
Description *string
|
Description *string
|
||||||
ImageURL *string
|
ImageURL *string
|
||||||
Order int
|
Order int
|
||||||
|
OwnerFeePercent *float64
|
||||||
|
IsTeam bool
|
||||||
IsActive bool
|
IsActive bool
|
||||||
CreatedAt time.Time
|
CreatedAt time.Time
|
||||||
UpdatedAt time.Time
|
UpdatedAt time.Time
|
||||||
|
|||||||
@@ -61,9 +61,6 @@ type CustomerOrderPayment struct {
|
|||||||
Amount float64 `json:"amount"`
|
Amount float64 `json:"amount"`
|
||||||
Status string `json:"status"`
|
Status string `json:"status"`
|
||||||
RefundAmount float64 `json:"refund_amount"`
|
RefundAmount float64 `json:"refund_amount"`
|
||||||
// Set for a payment with EnakPoint.
|
|
||||||
PointsUsed *int64 `json:"points_used,omitempty"`
|
|
||||||
PointValue *float64 `json:"point_value,omitempty"`
|
|
||||||
CreatedAt time.Time `json:"created_at"`
|
CreatedAt time.Time `json:"created_at"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -8,8 +8,6 @@ type CustomerOutlet struct {
|
|||||||
ID uuid.UUID `json:"id"`
|
ID uuid.UUID `json:"id"`
|
||||||
Name string `json:"name"`
|
Name string `json:"name"`
|
||||||
Address *string `json:"address"`
|
Address *string `json:"address"`
|
||||||
// The cashier accepts EnakPoint as payment here.
|
|
||||||
AcceptsPointPayment bool `json:"accepts_point_payment"`
|
|
||||||
// Orders here earn EnakPoint / EnakCoin.
|
// Orders here earn EnakPoint / EnakCoin.
|
||||||
EarnsPoints bool `json:"earns_points"`
|
EarnsPoints bool `json:"earns_points"`
|
||||||
EarnsCoins bool `json:"earns_coins"`
|
EarnsCoins bool `json:"earns_coins"`
|
||||||
|
|||||||
@@ -37,11 +37,3 @@ type CustomerPinRequestInfo struct {
|
|||||||
IPAddress string
|
IPAddress string
|
||||||
UserAgent string
|
UserAgent string
|
||||||
}
|
}
|
||||||
|
|
||||||
// PaymentCode is what POST /customer/wallet/payment-code returns: a one-time code the
|
|
||||||
// customer shows the cashier, as digits or as a QR of QRPayload.
|
|
||||||
type PaymentCode struct {
|
|
||||||
Code string `json:"code"`
|
|
||||||
QRPayload string `json:"qr_payload"`
|
|
||||||
ExpiresAt time.Time `json:"expires_at"`
|
|
||||||
}
|
|
||||||
|
|||||||
+24
-14
@@ -5,34 +5,35 @@ import (
|
|||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/google/uuid"
|
"github.com/google/uuid"
|
||||||
|
|
||||||
|
"apskel-pos-be/internal/constants"
|
||||||
)
|
)
|
||||||
|
|
||||||
// OutletLoyaltySettings are an outlet's loyalty settings (docs/prd-point-coin.md F1).
|
// OutletLoyaltySettings are an outlet's loyalty settings (docs/prd-point-coin.md F1).
|
||||||
type OutletLoyaltySettings struct {
|
type OutletLoyaltySettings struct {
|
||||||
Point LoyaltyEarnSettings `json:"point"`
|
Point LoyaltyEarnSettings `json:"point"`
|
||||||
Coin LoyaltyEarnSettings `json:"coin"`
|
Coin LoyaltyEarnSettings `json:"coin"`
|
||||||
// Paying with EnakPoint. EnakCoin cannot pay, so it has no counterpart.
|
|
||||||
PointPayment LoyaltyPointPaymentSettings `json:"point_payment"`
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// LoyaltyEarnSettings is how much of one currency an order earns:
|
// LoyaltyEarnSettings is how much of one currency an order earns, nothing below
|
||||||
// floor(basis / EarnPerAmount) × EarnValue, nothing below MinOrderAmount, and at most
|
// MinOrderAmount, and at most MaxPerOrder when set:
|
||||||
// MaxPerOrder when set.
|
//
|
||||||
|
// - PER_AMOUNT: floor(basis / EarnPerAmount) × EarnValue;
|
||||||
|
// - PERCENTAGE: floor(basis × EarnPercent / 100).
|
||||||
|
//
|
||||||
|
// The settings of the mode not in use are kept, so switching back restores them.
|
||||||
type LoyaltyEarnSettings struct {
|
type LoyaltyEarnSettings struct {
|
||||||
Enabled bool `json:"enabled"`
|
Enabled bool `json:"enabled"`
|
||||||
|
// PER_AMOUNT or PERCENTAGE.
|
||||||
|
EarnMode string `json:"earn_mode"`
|
||||||
EarnPerAmount int64 `json:"earn_per_amount"`
|
EarnPerAmount int64 `json:"earn_per_amount"`
|
||||||
EarnValue int64 `json:"earn_value"`
|
EarnValue int64 `json:"earn_value"`
|
||||||
|
// PERCENTAGE: percent of the basis earned, 0–100 with at most two decimals.
|
||||||
|
EarnPercent float64 `json:"earn_percent"`
|
||||||
MinOrderAmount int64 `json:"min_order_amount"`
|
MinOrderAmount int64 `json:"min_order_amount"`
|
||||||
MaxPerOrder *int64 `json:"max_per_order"`
|
MaxPerOrder *int64 `json:"max_per_order"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type LoyaltyPointPaymentSettings struct {
|
|
||||||
AcceptPayment bool `json:"accept_payment"`
|
|
||||||
MinPaymentPoints int64 `json:"min_payment_points"`
|
|
||||||
// Largest share of the order total, 0–100, that EnakPoint may pay.
|
|
||||||
MaxPaymentPercent int64 `json:"max_payment_percent"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// OrganizationLoyaltySettings are the loyalty settings shared by every outlet of an
|
// OrganizationLoyaltySettings are the loyalty settings shared by every outlet of an
|
||||||
// organization (docs/prd-point-coin.md F2, F12).
|
// organization (docs/prd-point-coin.md F2, F12).
|
||||||
type OrganizationLoyaltySettings struct {
|
type OrganizationLoyaltySettings struct {
|
||||||
@@ -102,8 +103,8 @@ type OutletLoyaltySettingsView struct {
|
|||||||
// The organization's rupiah value of one EnakPoint, which the cashback depends on.
|
// The organization's rupiah value of one EnakPoint, which the cashback depends on.
|
||||||
PointValue int64 `json:"point_value"`
|
PointValue int64 `json:"point_value"`
|
||||||
// Effective EnakPoint cashback in percent: earn_value × point_value /
|
// Effective EnakPoint cashback in percent: earn_value × point_value /
|
||||||
// earn_per_amount × 100. Shown next to the setting so an owner cannot misread the
|
// earn_per_amount × 100, or earn_percent × point_value in PERCENTAGE mode. Shown
|
||||||
// scale (F1).
|
// next to the setting so an owner cannot misread the scale (F1).
|
||||||
PointCashbackPercent float64 `json:"point_cashback_percent"`
|
PointCashbackPercent float64 `json:"point_cashback_percent"`
|
||||||
// Set on PUT: the keys that changed.
|
// Set on PUT: the keys that changed.
|
||||||
Changes []LoyaltySettingChange `json:"changes,omitempty"`
|
Changes []LoyaltySettingChange `json:"changes,omitempty"`
|
||||||
@@ -168,6 +169,15 @@ type LoyaltySettingsImpact struct {
|
|||||||
CoinRupiahAfter int64 `json:"coin_rupiah_after"`
|
CoinRupiahAfter int64 `json:"coin_rupiah_after"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// CashbackPercent is the rupiah value of what an order earns as a percentage of its
|
||||||
|
// basis, in the mode the settings are in, rounded to two decimals.
|
||||||
|
func (s LoyaltyEarnSettings) CashbackPercent(pointValue int64) float64 {
|
||||||
|
if s.EarnMode == constants.LoyaltyEarnModePercentage {
|
||||||
|
return math.Round(s.EarnPercent*float64(pointValue)*100) / 100
|
||||||
|
}
|
||||||
|
return LoyaltyCashbackPercent(s.EarnValue, pointValue, s.EarnPerAmount)
|
||||||
|
}
|
||||||
|
|
||||||
// NewLoyaltySettingsImpact computes the impact of moving from one organization setting
|
// NewLoyaltySettingsImpact computes the impact of moving from one organization setting
|
||||||
// to another on the balances in circulation.
|
// to another on the balances in circulation.
|
||||||
func NewLoyaltySettingsImpact(points, coins int64, before, after OrganizationLoyaltySettings) LoyaltySettingsImpact {
|
func NewLoyaltySettingsImpact(points, coins int64, before, after OrganizationLoyaltySettings) LoyaltySettingsImpact {
|
||||||
|
|||||||
@@ -14,6 +14,14 @@ func TestLoyaltyCashbackPercent(t *testing.T) {
|
|||||||
assert.Equal(t, 0.0, LoyaltyCashbackPercent(1, 1, 0))
|
assert.Equal(t, 0.0, LoyaltyCashbackPercent(1, 1, 0))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestLoyaltyEarnSettings_CashbackPercent(t *testing.T) {
|
||||||
|
s := LoyaltyEarnSettings{EarnMode: "PER_AMOUNT", EarnPerAmount: 100, EarnValue: 1, EarnPercent: 2.5}
|
||||||
|
assert.Equal(t, 1.0, s.CashbackPercent(1))
|
||||||
|
s.EarnMode = "PERCENTAGE"
|
||||||
|
assert.Equal(t, 2.5, s.CashbackPercent(1))
|
||||||
|
assert.Equal(t, 250.0, s.CashbackPercent(100), "each point earned is worth point_value rupiah")
|
||||||
|
}
|
||||||
|
|
||||||
func TestNewLoyaltySettingsImpact(t *testing.T) {
|
func TestNewLoyaltySettingsImpact(t *testing.T) {
|
||||||
before := OrganizationLoyaltySettings{PointValue: 1, Exchange: LoyaltyExchangeSettings{CoinAmount: 1, PointAmount: 1}}
|
before := OrganizationLoyaltySettings{PointValue: 1, Exchange: LoyaltyExchangeSettings{CoinAmount: 1, PointAmount: 1}}
|
||||||
after := OrganizationLoyaltySettings{PointValue: 100, Exchange: LoyaltyExchangeSettings{CoinAmount: 10, PointAmount: 1}}
|
after := OrganizationLoyaltySettings{PointValue: 100, Exchange: LoyaltyExchangeSettings{CoinAmount: 10, PointAmount: 1}}
|
||||||
|
|||||||
@@ -218,7 +218,7 @@ type OrderItemResponse struct {
|
|||||||
Status constants.OrderItemStatus
|
Status constants.OrderItemStatus
|
||||||
CreatedAt time.Time
|
CreatedAt time.Time
|
||||||
UpdatedAt time.Time
|
UpdatedAt time.Time
|
||||||
PrinterType string
|
PrinterTypes []string
|
||||||
PrintToChecker bool
|
PrintToChecker bool
|
||||||
PaidQuantity int
|
PaidQuantity int
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -30,8 +30,6 @@ type Payment struct {
|
|||||||
type CreatePaymentRequest struct {
|
type CreatePaymentRequest struct {
|
||||||
OrderID uuid.UUID `validate:"required"`
|
OrderID uuid.UUID `validate:"required"`
|
||||||
PaymentMethodID uuid.UUID `validate:"required"`
|
PaymentMethodID uuid.UUID `validate:"required"`
|
||||||
Points *int64
|
|
||||||
PaymentCode *string
|
|
||||||
Amount float64 `validate:"required,min=0"`
|
Amount float64 `validate:"required,min=0"`
|
||||||
TransactionID *string `validate:"omitempty"`
|
TransactionID *string `validate:"omitempty"`
|
||||||
SplitNumber int `validate:"omitempty,min=1"`
|
SplitNumber int `validate:"omitempty,min=1"`
|
||||||
@@ -62,9 +60,6 @@ type PaymentResponse struct {
|
|||||||
SplitType *string
|
SplitType *string
|
||||||
SplitDescription *string
|
SplitDescription *string
|
||||||
RefundAmount float64
|
RefundAmount float64
|
||||||
// Set for a payment with EnakPoint.
|
|
||||||
PointsUsed *int64
|
|
||||||
PointValue *float64
|
|
||||||
RefundReason *string
|
RefundReason *string
|
||||||
RefundedAt *time.Time
|
RefundedAt *time.Time
|
||||||
RefundedBy *uuid.UUID
|
RefundedBy *uuid.UUID
|
||||||
|
|||||||
@@ -51,8 +51,6 @@ type PaymentMethodResponse struct {
|
|||||||
|
|
||||||
type ListPaymentMethodsRequest struct {
|
type ListPaymentMethodsRequest struct {
|
||||||
OrganizationID *uuid.UUID
|
OrganizationID *uuid.UUID
|
||||||
// When set, EnakPoint is left out unless the outlet accepts it (F9).
|
|
||||||
OutletID *uuid.UUID
|
|
||||||
Type *constants.PaymentMethodType
|
Type *constants.PaymentMethodType
|
||||||
IsActive *bool
|
IsActive *bool
|
||||||
Search string
|
Search string
|
||||||
|
|||||||
@@ -18,7 +18,7 @@ type Product struct {
|
|||||||
Cost float64
|
Cost float64
|
||||||
BusinessType constants.BusinessType
|
BusinessType constants.BusinessType
|
||||||
ImageURL *string
|
ImageURL *string
|
||||||
PrinterType string
|
PrinterTypes []string
|
||||||
SellBy string
|
SellBy string
|
||||||
UnitID *uuid.UUID
|
UnitID *uuid.UUID
|
||||||
HasIngredients bool
|
HasIngredients bool
|
||||||
@@ -50,7 +50,7 @@ type CreateProductRequest struct {
|
|||||||
Cost float64 `validate:"min=0"`
|
Cost float64 `validate:"min=0"`
|
||||||
BusinessType constants.BusinessType `validate:"required"`
|
BusinessType constants.BusinessType `validate:"required"`
|
||||||
ImageURL *string `validate:"omitempty,max=500"`
|
ImageURL *string `validate:"omitempty,max=500"`
|
||||||
PrinterType *string `validate:"omitempty,max=50"`
|
PrinterTypes []string `validate:"omitempty,dive,max=50"`
|
||||||
PrintToChecker *bool `validate:"omitempty"`
|
PrintToChecker *bool `validate:"omitempty"`
|
||||||
UnitID *uuid.UUID `validate:"omitempty"`
|
UnitID *uuid.UUID `validate:"omitempty"`
|
||||||
SellBy string `validate:"omitempty,oneof=unit weight"`
|
SellBy string `validate:"omitempty,oneof=unit weight"`
|
||||||
@@ -72,7 +72,7 @@ type UpdateProductRequest struct {
|
|||||||
Price *float64 `validate:"omitempty,min=0"`
|
Price *float64 `validate:"omitempty,min=0"`
|
||||||
Cost *float64 `validate:"omitempty,min=0"`
|
Cost *float64 `validate:"omitempty,min=0"`
|
||||||
ImageURL *string `validate:"omitempty,max=500"`
|
ImageURL *string `validate:"omitempty,max=500"`
|
||||||
PrinterType *string `validate:"omitempty,max=50"`
|
PrinterTypes []string `validate:"omitempty,dive,max=50"` // Replaces the whole list when not nil
|
||||||
PrintToChecker *bool `validate:"omitempty"`
|
PrintToChecker *bool `validate:"omitempty"`
|
||||||
UnitID *uuid.UUID `validate:"omitempty"`
|
UnitID *uuid.UUID `validate:"omitempty"`
|
||||||
SellBy *string `validate:"omitempty,oneof=unit weight"`
|
SellBy *string `validate:"omitempty,oneof=unit weight"`
|
||||||
@@ -112,7 +112,7 @@ type ProductResponse struct {
|
|||||||
Cost float64
|
Cost float64
|
||||||
BusinessType constants.BusinessType
|
BusinessType constants.BusinessType
|
||||||
ImageURL *string
|
ImageURL *string
|
||||||
PrinterType string
|
PrinterTypes []string
|
||||||
SellBy string
|
SellBy string
|
||||||
PrintToChecker bool
|
PrintToChecker bool
|
||||||
UnitID *uuid.UUID
|
UnitID *uuid.UUID
|
||||||
|
|||||||
@@ -139,25 +139,6 @@ type AdminWalletAdjustmentResult struct {
|
|||||||
Replayed bool `json:"replayed"`
|
Replayed bool `json:"replayed"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// PointPaymentPreview is GET /orders/:id/point-payment/preview (docs/prd-point-coin.md
|
|
||||||
// F9): whether the order can be paid with EnakPoint and at most how much, for the
|
|
||||||
// cashier's "use maximum" button.
|
|
||||||
type PointPaymentPreview struct {
|
|
||||||
OrderID uuid.UUID `json:"order_id"`
|
|
||||||
CustomerID *uuid.UUID `json:"customer_id"`
|
|
||||||
Eligible bool `json:"eligible"`
|
|
||||||
// Why not, when not eligible.
|
|
||||||
Reason string `json:"reason,omitempty"`
|
|
||||||
PointBalance int64 `json:"point_balance"`
|
|
||||||
PointValue int64 `json:"point_value"`
|
|
||||||
RemainingAmount float64 `json:"remaining_amount"`
|
|
||||||
MinPaymentPoints int64 `json:"min_payment_points"`
|
|
||||||
MaxPaymentPercent int64 `json:"max_payment_percent"`
|
|
||||||
MaxPoints int64 `json:"max_points"`
|
|
||||||
// Rupiah covered by MaxPoints.
|
|
||||||
MaxAmount int64 `json:"max_amount"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// CustomerWalletExpiringList is GET /customer/wallet/expiring (docs/prd-point-coin.md
|
// CustomerWalletExpiringList is GET /customer/wallet/expiring (docs/prd-point-coin.md
|
||||||
// F6): everything that will expire, per currency and day, soonest first.
|
// F6): everything that will expire, per currency and day, soonest first.
|
||||||
type CustomerWalletExpiringList struct {
|
type CustomerWalletExpiringList struct {
|
||||||
|
|||||||
@@ -63,37 +63,27 @@ func (p *AnalyticsProcessorImpl) GetPaymentMethodAnalytics(ctx context.Context,
|
|||||||
return nil, fmt.Errorf("failed to get payment method analytics: %w", err)
|
return nil, fmt.Errorf("failed to get payment method analytics: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
// EnakPoint is not money in (docs/prd-point-coin.md F9, K7): it is listed as its own
|
var totalAmount float64
|
||||||
// method but left out of the money received and of the shares. How it is booked
|
|
||||||
// waits on note N2.
|
|
||||||
var cashAmount, pointAmount float64
|
|
||||||
var pointsUsed int64
|
|
||||||
var totalOrders int64
|
var totalOrders int64
|
||||||
var totalPayments int64
|
var totalPayments int64
|
||||||
|
|
||||||
for _, data := range analyticsData {
|
for _, data := range analyticsData {
|
||||||
if data.PaymentMethodType == string(constants.PaymentMethodTypePoint) {
|
totalAmount += data.TotalAmount
|
||||||
pointAmount += data.TotalAmount
|
|
||||||
pointsUsed += data.PointsUsed
|
|
||||||
} else {
|
|
||||||
cashAmount += data.TotalAmount
|
|
||||||
}
|
|
||||||
totalOrders += data.OrderCount
|
totalOrders += data.OrderCount
|
||||||
totalPayments += data.PaymentCount
|
totalPayments += data.PaymentCount
|
||||||
}
|
}
|
||||||
|
|
||||||
// The value of an order includes what EnakPoint paid, so the average does too.
|
|
||||||
var averageOrderValue float64
|
var averageOrderValue float64
|
||||||
if totalOrders > 0 {
|
if totalOrders > 0 {
|
||||||
averageOrderValue = (cashAmount + pointAmount) / float64(totalOrders)
|
averageOrderValue = totalAmount / float64(totalOrders)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Calculate percentages
|
||||||
var resultData []models.PaymentMethodAnalyticsData
|
var resultData []models.PaymentMethodAnalyticsData
|
||||||
for _, data := range analyticsData {
|
for _, data := range analyticsData {
|
||||||
cashIn := data.PaymentMethodType != string(constants.PaymentMethodTypePoint)
|
|
||||||
var percentage float64
|
var percentage float64
|
||||||
if cashIn && cashAmount > 0 {
|
if totalAmount > 0 {
|
||||||
percentage = (data.TotalAmount / cashAmount) * 100
|
percentage = (data.TotalAmount / totalAmount) * 100
|
||||||
}
|
}
|
||||||
|
|
||||||
resultData = append(resultData, models.PaymentMethodAnalyticsData{
|
resultData = append(resultData, models.PaymentMethodAnalyticsData{
|
||||||
@@ -104,16 +94,11 @@ func (p *AnalyticsProcessorImpl) GetPaymentMethodAnalytics(ctx context.Context,
|
|||||||
OrderCount: data.OrderCount,
|
OrderCount: data.OrderCount,
|
||||||
PaymentCount: data.PaymentCount,
|
PaymentCount: data.PaymentCount,
|
||||||
Percentage: percentage,
|
Percentage: percentage,
|
||||||
PointsUsed: data.PointsUsed,
|
|
||||||
CountsAsCashIn: cashIn,
|
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
summary := models.PaymentMethodSummary{
|
summary := models.PaymentMethodSummary{
|
||||||
TotalAmount: cashAmount,
|
TotalAmount: totalAmount,
|
||||||
PointAmount: pointAmount,
|
|
||||||
PointsUsed: pointsUsed,
|
|
||||||
TotalWithPoints: cashAmount + pointAmount,
|
|
||||||
TotalOrders: totalOrders,
|
TotalOrders: totalOrders,
|
||||||
TotalPayments: totalPayments,
|
TotalPayments: totalPayments,
|
||||||
AverageOrderValue: averageOrderValue,
|
AverageOrderValue: averageOrderValue,
|
||||||
@@ -413,9 +398,22 @@ func (p *AnalyticsProcessorImpl) GetProductAnalyticsPerParentCategory(ctx contex
|
|||||||
// Transform data
|
// Transform data
|
||||||
var resultData []models.ProductAnalyticsPerParentCategoryData
|
var resultData []models.ProductAnalyticsPerParentCategoryData
|
||||||
for _, data := range analyticsData {
|
for _, data := range analyticsData {
|
||||||
|
var topProduct *models.ParentCategoryTopProduct
|
||||||
|
if data.TopProduct != nil {
|
||||||
|
topProduct = &models.ParentCategoryTopProduct{
|
||||||
|
ProductID: data.TopProduct.ProductID,
|
||||||
|
ProductName: data.TopProduct.ProductName,
|
||||||
|
QuantitySold: data.TopProduct.QuantitySold,
|
||||||
|
Revenue: data.TopProduct.Revenue,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
resultData = append(resultData, models.ProductAnalyticsPerParentCategoryData{
|
resultData = append(resultData, models.ProductAnalyticsPerParentCategoryData{
|
||||||
|
TopProduct: topProduct,
|
||||||
ParentCategoryID: data.ParentCategoryID,
|
ParentCategoryID: data.ParentCategoryID,
|
||||||
ParentCategoryName: data.ParentCategoryName,
|
ParentCategoryName: data.ParentCategoryName,
|
||||||
|
OwnerFeePercent: data.OwnerFeePercent,
|
||||||
|
SDL: data.TotalRevenue * data.OwnerFeePercent / 100,
|
||||||
TotalRevenue: data.TotalRevenue,
|
TotalRevenue: data.TotalRevenue,
|
||||||
TotalQuantity: data.TotalQuantity,
|
TotalQuantity: data.TotalQuantity,
|
||||||
CategoryCount: data.CategoryCount,
|
CategoryCount: data.CategoryCount,
|
||||||
@@ -456,7 +454,9 @@ func (p *AnalyticsProcessorImpl) GetParentCategoryAnalyticsDetail(ctx context.Co
|
|||||||
|
|
||||||
// Bucket the product rows by the category they belong to
|
// Bucket the product rows by the category they belong to
|
||||||
productsByCategory := make(map[uuid.UUID][]models.ParentCategoryAnalyticsProductData)
|
productsByCategory := make(map[uuid.UUID][]models.ParentCategoryAnalyticsProductData)
|
||||||
|
productRowsByCategory := make(map[uuid.UUID][]*entities.ProductAnalytics)
|
||||||
for _, product := range detail.Products {
|
for _, product := range detail.Products {
|
||||||
|
productRowsByCategory[product.CategoryID] = append(productRowsByCategory[product.CategoryID], product)
|
||||||
productsByCategory[product.CategoryID] = append(productsByCategory[product.CategoryID], models.ParentCategoryAnalyticsProductData{
|
productsByCategory[product.CategoryID] = append(productsByCategory[product.CategoryID], models.ParentCategoryAnalyticsProductData{
|
||||||
ProductID: product.ProductID,
|
ProductID: product.ProductID,
|
||||||
ProductName: product.ProductName,
|
ProductName: product.ProductName,
|
||||||
@@ -476,6 +476,12 @@ func (p *AnalyticsProcessorImpl) GetParentCategoryAnalyticsDetail(ctx context.Co
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Sub-categories take the owner fee of the parent category they sit under
|
||||||
|
var ownerFeePercent float64
|
||||||
|
if detail.Summary != nil {
|
||||||
|
ownerFeePercent = detail.Summary.OwnerFeePercent
|
||||||
|
}
|
||||||
|
|
||||||
categories := make([]models.ParentCategoryAnalyticsDetailData, 0, len(detail.Categories))
|
categories := make([]models.ParentCategoryAnalyticsDetailData, 0, len(detail.Categories))
|
||||||
for _, category := range detail.Categories {
|
for _, category := range detail.Categories {
|
||||||
products := productsByCategory[category.CategoryID]
|
products := productsByCategory[category.CategoryID]
|
||||||
@@ -486,6 +492,9 @@ func (p *AnalyticsProcessorImpl) GetParentCategoryAnalyticsDetail(ctx context.Co
|
|||||||
categories = append(categories, models.ParentCategoryAnalyticsDetailData{
|
categories = append(categories, models.ParentCategoryAnalyticsDetailData{
|
||||||
CategoryID: category.CategoryID,
|
CategoryID: category.CategoryID,
|
||||||
CategoryName: category.CategoryName,
|
CategoryName: category.CategoryName,
|
||||||
|
OwnerFeePercent: ownerFeePercent,
|
||||||
|
SDL: category.TotalRevenue * ownerFeePercent / 100,
|
||||||
|
TopProduct: topProductByRevenue(productRowsByCategory[category.CategoryID]),
|
||||||
TotalRevenue: category.TotalRevenue,
|
TotalRevenue: category.TotalRevenue,
|
||||||
TotalQuantity: category.TotalQuantity,
|
TotalQuantity: category.TotalQuantity,
|
||||||
ProductCount: category.ProductCount,
|
ProductCount: category.ProductCount,
|
||||||
@@ -500,6 +509,9 @@ func (p *AnalyticsProcessorImpl) GetParentCategoryAnalyticsDetail(ctx context.Co
|
|||||||
summary := models.ParentCategoryAnalyticsDetailSummary{}
|
summary := models.ParentCategoryAnalyticsDetailSummary{}
|
||||||
if detail.Summary != nil {
|
if detail.Summary != nil {
|
||||||
summary = models.ParentCategoryAnalyticsDetailSummary{
|
summary = models.ParentCategoryAnalyticsDetailSummary{
|
||||||
|
TopProduct: topProductByRevenue(detail.Products),
|
||||||
|
OwnerFeePercent: detail.Summary.OwnerFeePercent,
|
||||||
|
SDL: detail.Summary.TotalRevenue * detail.Summary.OwnerFeePercent / 100,
|
||||||
TotalRevenue: detail.Summary.TotalRevenue,
|
TotalRevenue: detail.Summary.TotalRevenue,
|
||||||
TotalQuantity: detail.Summary.TotalQuantity,
|
TotalQuantity: detail.Summary.TotalQuantity,
|
||||||
CategoryCount: detail.Summary.CategoryCount,
|
CategoryCount: detail.Summary.CategoryCount,
|
||||||
@@ -515,6 +527,11 @@ func (p *AnalyticsProcessorImpl) GetParentCategoryAnalyticsDetail(ctx context.Co
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
// The block covers a single parent category, so it reports that category's own fee
|
||||||
|
if detail.Summary != nil {
|
||||||
|
budget.Percentages.Owner = detail.Summary.OwnerFeePercent
|
||||||
|
budget.Percentages.Team = 100 - detail.Summary.OwnerFeePercent
|
||||||
|
}
|
||||||
|
|
||||||
return &models.ParentCategoryAnalyticsDetailResponse{
|
return &models.ParentCategoryAnalyticsDetailResponse{
|
||||||
OrganizationID: req.OrganizationID,
|
OrganizationID: req.OrganizationID,
|
||||||
@@ -530,6 +547,30 @@ func (p *AnalyticsProcessorImpl) GetParentCategoryAnalyticsDetail(ctx context.Co
|
|||||||
}, nil
|
}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// topProductByRevenue picks the best-selling product of a parent category. A product
|
||||||
|
// can span several rows (one per outlet price), so the rows are added up per product
|
||||||
|
// first. Ties keep the product that was seen first.
|
||||||
|
func topProductByRevenue(products []*entities.ProductAnalytics) *models.ParentCategoryTopProduct {
|
||||||
|
totals := make(map[uuid.UUID]*models.ParentCategoryTopProduct)
|
||||||
|
for _, product := range products {
|
||||||
|
total, ok := totals[product.ProductID]
|
||||||
|
if !ok {
|
||||||
|
total = &models.ParentCategoryTopProduct{ProductID: product.ProductID, ProductName: product.ProductName}
|
||||||
|
totals[product.ProductID] = total
|
||||||
|
}
|
||||||
|
total.QuantitySold += product.QuantitySold
|
||||||
|
total.Revenue += product.Revenue
|
||||||
|
}
|
||||||
|
|
||||||
|
var top *models.ParentCategoryTopProduct
|
||||||
|
for _, product := range products {
|
||||||
|
if total := totals[product.ProductID]; top == nil || total.Revenue > top.Revenue {
|
||||||
|
top = total
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return top
|
||||||
|
}
|
||||||
|
|
||||||
// startOfWeek returns the Monday 00:00 of the week containing t, in t's own location.
|
// startOfWeek returns the Monday 00:00 of the week containing t, in t's own location.
|
||||||
func startOfWeek(t time.Time) time.Time {
|
func startOfWeek(t time.Time) time.Time {
|
||||||
daysSinceMonday := (int(t.Weekday()) + 6) % 7
|
daysSinceMonday := (int(t.Weekday()) + 6) % 7
|
||||||
@@ -542,16 +583,17 @@ func endOfWeek(t time.Time) time.Time {
|
|||||||
return startOfWeek(t).AddDate(0, 0, 7).Add(-time.Nanosecond)
|
return startOfWeek(t).AddDate(0, 0, 7).Add(-time.Nanosecond)
|
||||||
}
|
}
|
||||||
|
|
||||||
// newBudgetPeriod splits a period's revenue into the spending limits.
|
// newBudgetPeriod splits a period's revenue between the owner and the team. The owner
|
||||||
func newBudgetPeriod(start, end time.Time, revenue float64, orderCount int64) models.BudgetPeriod {
|
// share is passed in because a parent category can carry its own owner fee percent,
|
||||||
|
// and the team takes whatever the owner does not.
|
||||||
|
func newBudgetPeriod(start, end time.Time, revenue, sdl float64, orderCount int64) models.BudgetPeriod {
|
||||||
return models.BudgetPeriod{
|
return models.BudgetPeriod{
|
||||||
PeriodStart: start,
|
PeriodStart: start,
|
||||||
PeriodEnd: end,
|
PeriodEnd: end,
|
||||||
Revenue: revenue,
|
Revenue: revenue,
|
||||||
OrderCount: orderCount,
|
OrderCount: orderCount,
|
||||||
LimitPurchase: revenue * constants.BudgetLimitPurchasePercent / 100,
|
SDL: sdl,
|
||||||
LimitOwner: revenue * constants.BudgetLimitOwnerPercent / 100,
|
LimitTeam: revenue - sdl,
|
||||||
LimitTeam: revenue * constants.BudgetLimitTeamPercent / 100,
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -565,9 +607,8 @@ func (p *AnalyticsProcessorImpl) buildBudgetCutOff(ctx context.Context, organiza
|
|||||||
|
|
||||||
budget := models.BudgetCutOff{
|
budget := models.BudgetCutOff{
|
||||||
Percentages: models.BudgetPercentages{
|
Percentages: models.BudgetPercentages{
|
||||||
Purchase: constants.BudgetLimitPurchasePercent,
|
|
||||||
Owner: constants.BudgetLimitOwnerPercent,
|
Owner: constants.BudgetLimitOwnerPercent,
|
||||||
Team: constants.BudgetLimitTeamPercent,
|
Team: 100 - constants.BudgetLimitOwnerPercent,
|
||||||
},
|
},
|
||||||
CutOffFrom: cutOffFrom,
|
CutOffFrom: cutOffFrom,
|
||||||
CutOffTo: cutOffTo,
|
CutOffTo: cutOffTo,
|
||||||
@@ -588,22 +629,24 @@ func (p *AnalyticsProcessorImpl) buildBudgetCutOff(ctx context.Context, organiza
|
|||||||
|
|
||||||
var (
|
var (
|
||||||
totalRevenue float64
|
totalRevenue float64
|
||||||
|
totalSDL float64
|
||||||
totalOrders int64
|
totalOrders int64
|
||||||
monthOrder []string
|
monthOrder []string
|
||||||
monthAccumulator = map[string]*models.BudgetMonthPeriod{}
|
monthAccumulator = map[string]*models.BudgetMonthPeriod{}
|
||||||
)
|
)
|
||||||
|
|
||||||
for week := cutOffFrom; !week.After(cutOffTo); week = week.AddDate(0, 0, 7) {
|
for week := cutOffFrom; !week.After(cutOffTo); week = week.AddDate(0, 0, 7) {
|
||||||
var revenue float64
|
var revenue, sdl float64
|
||||||
var orderCount int64
|
var orderCount int64
|
||||||
if row, ok := rowsByWeek[week.Format("2006-01-02")]; ok {
|
if row, ok := rowsByWeek[week.Format("2006-01-02")]; ok {
|
||||||
revenue, orderCount = row.Revenue, row.OrderCount
|
revenue, sdl, orderCount = row.Revenue, row.SDL, row.OrderCount
|
||||||
}
|
}
|
||||||
|
|
||||||
period := newBudgetPeriod(week, endOfWeek(week), revenue, orderCount)
|
period := newBudgetPeriod(week, endOfWeek(week), revenue, sdl, orderCount)
|
||||||
budget.Weekly = append(budget.Weekly, period)
|
budget.Weekly = append(budget.Weekly, period)
|
||||||
|
|
||||||
totalRevenue += revenue
|
totalRevenue += revenue
|
||||||
|
totalSDL += sdl
|
||||||
totalOrders += orderCount
|
totalOrders += orderCount
|
||||||
|
|
||||||
// A week belongs to the month of its Monday, so every week is counted once
|
// A week belongs to the month of its Monday, so every week is counted once
|
||||||
@@ -618,6 +661,7 @@ func (p *AnalyticsProcessorImpl) buildBudgetCutOff(ctx context.Context, organiza
|
|||||||
month.WeekCount++
|
month.WeekCount++
|
||||||
month.PeriodEnd = period.PeriodEnd
|
month.PeriodEnd = period.PeriodEnd
|
||||||
month.Revenue += revenue
|
month.Revenue += revenue
|
||||||
|
month.SDL += sdl
|
||||||
month.OrderCount += orderCount
|
month.OrderCount += orderCount
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -626,11 +670,11 @@ func (p *AnalyticsProcessorImpl) buildBudgetCutOff(ctx context.Context, organiza
|
|||||||
budget.Monthly = append(budget.Monthly, models.BudgetMonthPeriod{
|
budget.Monthly = append(budget.Monthly, models.BudgetMonthPeriod{
|
||||||
Month: month.Month,
|
Month: month.Month,
|
||||||
WeekCount: month.WeekCount,
|
WeekCount: month.WeekCount,
|
||||||
BudgetPeriod: newBudgetPeriod(month.PeriodStart, month.PeriodEnd, month.Revenue, month.OrderCount),
|
BudgetPeriod: newBudgetPeriod(month.PeriodStart, month.PeriodEnd, month.Revenue, month.SDL, month.OrderCount),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
budget.Total = newBudgetPeriod(cutOffFrom, cutOffTo, totalRevenue, totalOrders)
|
budget.Total = newBudgetPeriod(cutOffFrom, cutOffTo, totalRevenue, totalSDL, totalOrders)
|
||||||
|
|
||||||
return budget, nil
|
return budget, nil
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -10,7 +10,6 @@ import (
|
|||||||
"apskel-pos-be/internal/models"
|
"apskel-pos-be/internal/models"
|
||||||
|
|
||||||
"github.com/google/uuid"
|
"github.com/google/uuid"
|
||||||
"github.com/stretchr/testify/assert"
|
|
||||||
"github.com/stretchr/testify/require"
|
"github.com/stretchr/testify/require"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -18,6 +17,7 @@ type analyticsRepositoryStub struct {
|
|||||||
purchasingResult *entities.PurchasingAnalytics
|
purchasingResult *entities.PurchasingAnalytics
|
||||||
purchasingTeam *entities.PurchaseTeamFilter
|
purchasingTeam *entities.PurchaseTeamFilter
|
||||||
budgetCutOffWeeks []*entities.BudgetCutOffWeek
|
budgetCutOffWeeks []*entities.BudgetCutOffWeek
|
||||||
|
parentCategories []*entities.ProductAnalyticsPerParentCategory
|
||||||
profitLossResult *entities.ProfitLossAnalytics
|
profitLossResult *entities.ProfitLossAnalytics
|
||||||
exclusiveSummaryResults []*entities.ExclusiveSummaryAnalytics
|
exclusiveSummaryResults []*entities.ExclusiveSummaryAnalytics
|
||||||
bankBalances []entities.ExclusiveSummaryBankBalance
|
bankBalances []entities.ExclusiveSummaryBankBalance
|
||||||
@@ -49,8 +49,8 @@ func (analyticsRepositoryStub) GetProductAnalyticsPerCategory(context.Context, u
|
|||||||
return nil, nil
|
return nil, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (analyticsRepositoryStub) GetProductAnalyticsPerParentCategory(context.Context, uuid.UUID, *uuid.UUID, time.Time, time.Time) ([]*entities.ProductAnalyticsPerParentCategory, error) {
|
func (s analyticsRepositoryStub) GetProductAnalyticsPerParentCategory(context.Context, uuid.UUID, *uuid.UUID, time.Time, time.Time) ([]*entities.ProductAnalyticsPerParentCategory, error) {
|
||||||
return nil, nil
|
return s.parentCategories, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (analyticsRepositoryStub) GetParentCategoryAnalyticsDetail(context.Context, uuid.UUID, *uuid.UUID, uuid.UUID, time.Time, time.Time) (*entities.ParentCategoryAnalyticsDetail, error) {
|
func (analyticsRepositoryStub) GetParentCategoryAnalyticsDetail(context.Context, uuid.UUID, *uuid.UUID, uuid.UUID, time.Time, time.Time) (*entities.ParentCategoryAnalyticsDetail, error) {
|
||||||
@@ -573,34 +573,60 @@ func TestAnalyticsProcessorGetExclusiveSummaryMTDBuildsMonthToDateBreakdown(t *t
|
|||||||
require.Len(t, result.DailyTransactions, 2)
|
require.Len(t, result.DailyTransactions, 2)
|
||||||
}
|
}
|
||||||
|
|
||||||
// EnakPoint is listed as its own method but is not money in (F9, K7).
|
// A parent category with its own owner fee percent moves the owner limit away from the
|
||||||
func TestPaymentMethodAnalytics_EnakPointIsNotCashIn(t *testing.T) {
|
// default share, and the team limit shrinks by the same amount.
|
||||||
repo := &analyticsRepositoryStub{paymentMethods: []*entities.PaymentMethodAnalytics{
|
func TestAnalyticsProcessorParentCategoryUsesOwnerFeePercent(t *testing.T) {
|
||||||
{PaymentMethodName: "Tunai", PaymentMethodType: "cash", TotalAmount: 70000, OrderCount: 2, PaymentCount: 2},
|
monday := time.Date(2026, 9, 28, 0, 0, 0, 0, time.UTC)
|
||||||
{PaymentMethodName: "Kartu", PaymentMethodType: "card", TotalAmount: 20000, OrderCount: 1, PaymentCount: 1},
|
processor := NewAnalyticsProcessorImpl(&analyticsRepositoryStub{
|
||||||
{PaymentMethodName: "EnakPoint", PaymentMethodType: "point", TotalAmount: 30000, OrderCount: 1, PaymentCount: 1, PointsUsed: 30000},
|
parentCategories: []*entities.ProductAnalyticsPerParentCategory{
|
||||||
}}
|
{ParentCategoryName: "Food", OwnerFeePercent: constants.BudgetLimitOwnerPercent, TotalRevenue: 1000},
|
||||||
p := NewAnalyticsProcessorImpl(repo, nil)
|
{ParentCategoryName: "Drink", OwnerFeePercent: 35, TotalRevenue: 2000},
|
||||||
|
},
|
||||||
|
budgetCutOffWeeks: []*entities.BudgetCutOffWeek{
|
||||||
|
// 1000 at the default 20% plus 2000 at 35%
|
||||||
|
{WeekStart: monday, Revenue: 3000, OrderCount: 4, SDL: 900},
|
||||||
|
},
|
||||||
|
}, expenseRepositoryStub{})
|
||||||
|
|
||||||
got, err := p.GetPaymentMethodAnalytics(context.Background(), &models.PaymentMethodAnalyticsRequest{
|
result, err := processor.GetProductAnalyticsPerParentCategory(context.Background(), &models.ProductAnalyticsPerParentCategoryRequest{
|
||||||
OrganizationID: uuid.New(), DateFrom: time.Now().Add(-time.Hour), DateTo: time.Now(),
|
OrganizationID: uuid.New(),
|
||||||
|
DateFrom: monday,
|
||||||
|
DateTo: monday.AddDate(0, 0, 6),
|
||||||
})
|
})
|
||||||
require.NoError(t, err)
|
|
||||||
assert.Equal(t, 90000.0, got.Summary.TotalAmount, "money in leaves EnakPoint out")
|
|
||||||
assert.Equal(t, 30000.0, got.Summary.PointAmount)
|
|
||||||
assert.Equal(t, int64(30000), got.Summary.PointsUsed)
|
|
||||||
assert.Equal(t, 120000.0, got.Summary.TotalWithPoints)
|
|
||||||
assert.Equal(t, int64(4), got.Summary.TotalOrders)
|
|
||||||
assert.Equal(t, 30000.0, got.Summary.AverageOrderValue, "the value of an order includes what EnakPoint paid")
|
|
||||||
|
|
||||||
byType := map[string]models.PaymentMethodAnalyticsData{}
|
require.NoError(t, err)
|
||||||
for _, d := range got.Data {
|
require.Len(t, result.Data, 2)
|
||||||
byType[d.PaymentMethodType] = d
|
require.Equal(t, float64(20), result.Data[0].OwnerFeePercent)
|
||||||
|
require.Equal(t, float64(200), result.Data[0].SDL)
|
||||||
|
require.Equal(t, float64(35), result.Data[1].OwnerFeePercent)
|
||||||
|
require.Equal(t, float64(700), result.Data[1].SDL)
|
||||||
|
|
||||||
|
require.Len(t, result.Budget.Weekly, 1)
|
||||||
|
require.Equal(t, float64(900), result.Budget.Weekly[0].SDL)
|
||||||
|
require.Equal(t, float64(2100), result.Budget.Weekly[0].LimitTeam)
|
||||||
|
require.Equal(t, float64(20), result.Budget.Percentages.Owner)
|
||||||
|
require.Equal(t, float64(80), result.Budget.Percentages.Team)
|
||||||
|
require.Len(t, result.Budget.Monthly, 1)
|
||||||
|
require.Equal(t, float64(900), result.Budget.Monthly[0].SDL)
|
||||||
|
require.Equal(t, float64(900), result.Budget.Total.SDL)
|
||||||
}
|
}
|
||||||
assert.True(t, byType["cash"].CountsAsCashIn)
|
|
||||||
assert.False(t, byType["point"].CountsAsCashIn)
|
// A product sold at several outlet prices comes back as several rows, which must be
|
||||||
assert.InDelta(t, 77.78, byType["cash"].Percentage, 0.01, "shares are of the money received")
|
// added up before the best seller is picked.
|
||||||
assert.InDelta(t, 22.22, byType["card"].Percentage, 0.01)
|
func TestTopProductByRevenueAddsUpRowsOfTheSameProduct(t *testing.T) {
|
||||||
assert.Zero(t, byType["point"].Percentage)
|
split, single := uuid.New(), uuid.New()
|
||||||
assert.Equal(t, int64(30000), byType["point"].PointsUsed)
|
|
||||||
|
top := topProductByRevenue([]*entities.ProductAnalytics{
|
||||||
|
{ProductID: single, ProductName: "Es Teh", QuantitySold: 5, Revenue: 500},
|
||||||
|
{ProductID: split, ProductName: "Nasi Goreng", QuantitySold: 2, Revenue: 300},
|
||||||
|
{ProductID: split, ProductName: "Nasi Goreng", QuantitySold: 2, Revenue: 300},
|
||||||
|
})
|
||||||
|
|
||||||
|
require.NotNil(t, top)
|
||||||
|
require.Equal(t, split, top.ProductID)
|
||||||
|
require.Equal(t, "Nasi Goreng", top.ProductName)
|
||||||
|
require.Equal(t, int64(4), top.QuantitySold)
|
||||||
|
require.Equal(t, float64(600), top.Revenue)
|
||||||
|
|
||||||
|
require.Nil(t, topProductByRevenue(nil))
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -85,7 +85,7 @@ func TestBuildBudgetCutOffAppliesLimits(t *testing.T) {
|
|||||||
weekStart := time.Date(2026, 8, 3, 0, 0, 0, 0, loc)
|
weekStart := time.Date(2026, 8, 3, 0, 0, 0, 0, loc)
|
||||||
|
|
||||||
stub := &analyticsRepositoryStub{budgetCutOffWeeks: []*entities.BudgetCutOffWeek{
|
stub := &analyticsRepositoryStub{budgetCutOffWeeks: []*entities.BudgetCutOffWeek{
|
||||||
{WeekStart: weekStart, Revenue: 10_000_000, OrderCount: 120},
|
{WeekStart: weekStart, Revenue: 10_000_000, OrderCount: 120, SDL: 2_500_000},
|
||||||
}}
|
}}
|
||||||
processor := &AnalyticsProcessorImpl{analyticsRepo: stub}
|
processor := &AnalyticsProcessorImpl{analyticsRepo: stub}
|
||||||
|
|
||||||
@@ -93,16 +93,17 @@ func TestBuildBudgetCutOffAppliesLimits(t *testing.T) {
|
|||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
require.Len(t, budget.Weekly, 1)
|
require.Len(t, budget.Weekly, 1)
|
||||||
|
|
||||||
// 60 / 20 / 20 of the week's revenue
|
// The owner limit is whatever the repository summed from each parent category's
|
||||||
|
// own fee percent, and the team takes the rest of the week's revenue
|
||||||
week := budget.Weekly[0]
|
week := budget.Weekly[0]
|
||||||
require.Equal(t, float64(6_000_000), week.LimitPurchase)
|
require.Equal(t, float64(2_500_000), week.SDL)
|
||||||
require.Equal(t, float64(2_000_000), week.LimitOwner)
|
require.Equal(t, float64(7_500_000), week.LimitTeam)
|
||||||
require.Equal(t, float64(2_000_000), week.LimitTeam)
|
|
||||||
require.Equal(t, int64(120), week.OrderCount)
|
require.Equal(t, int64(120), week.OrderCount)
|
||||||
|
|
||||||
// Totals mirror the single week
|
// Totals mirror the single week
|
||||||
require.Equal(t, week.Revenue, budget.Total.Revenue)
|
require.Equal(t, week.Revenue, budget.Total.Revenue)
|
||||||
require.Equal(t, week.LimitPurchase, budget.Total.LimitPurchase)
|
require.Equal(t, week.SDL, budget.Total.SDL)
|
||||||
|
require.Equal(t, week.LimitTeam, budget.Total.LimitTeam)
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestBuildBudgetCutOffAccumulatesMonthlyFromWeeks(t *testing.T) {
|
func TestBuildBudgetCutOffAccumulatesMonthlyFromWeeks(t *testing.T) {
|
||||||
@@ -110,8 +111,8 @@ func TestBuildBudgetCutOffAccumulatesMonthlyFromWeeks(t *testing.T) {
|
|||||||
first := time.Date(2026, 8, 3, 0, 0, 0, 0, loc)
|
first := time.Date(2026, 8, 3, 0, 0, 0, 0, loc)
|
||||||
|
|
||||||
stub := &analyticsRepositoryStub{budgetCutOffWeeks: []*entities.BudgetCutOffWeek{
|
stub := &analyticsRepositoryStub{budgetCutOffWeeks: []*entities.BudgetCutOffWeek{
|
||||||
{WeekStart: first, Revenue: 10_000_000, OrderCount: 100},
|
{WeekStart: first, Revenue: 10_000_000, OrderCount: 100, SDL: 2_000_000},
|
||||||
{WeekStart: first.AddDate(0, 0, 7), Revenue: 5_000_000, OrderCount: 60},
|
{WeekStart: first.AddDate(0, 0, 7), Revenue: 5_000_000, OrderCount: 60, SDL: 1_000_000},
|
||||||
}}
|
}}
|
||||||
processor := &AnalyticsProcessorImpl{analyticsRepo: stub}
|
processor := &AnalyticsProcessorImpl{analyticsRepo: stub}
|
||||||
|
|
||||||
@@ -125,9 +126,10 @@ func TestBuildBudgetCutOffAccumulatesMonthlyFromWeeks(t *testing.T) {
|
|||||||
require.Equal(t, float64(15_000_000), month.Revenue)
|
require.Equal(t, float64(15_000_000), month.Revenue)
|
||||||
require.Equal(t, int64(160), month.OrderCount)
|
require.Equal(t, int64(160), month.OrderCount)
|
||||||
|
|
||||||
// The month limit is the accumulation of its weeks
|
// The month limits are the accumulation of its weeks
|
||||||
require.Equal(t, float64(9_000_000), month.LimitPurchase)
|
require.Equal(t, float64(3_000_000), month.SDL)
|
||||||
require.Equal(t, budget.Weekly[0].LimitPurchase+budget.Weekly[1].LimitPurchase, month.LimitPurchase)
|
require.Equal(t, float64(12_000_000), month.LimitTeam)
|
||||||
|
require.Equal(t, budget.Weekly[0].LimitTeam+budget.Weekly[1].LimitTeam, month.LimitTeam)
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestBuildBudgetCutOffEmitsWeeksWithoutSales(t *testing.T) {
|
func TestBuildBudgetCutOffEmitsWeeksWithoutSales(t *testing.T) {
|
||||||
@@ -145,7 +147,7 @@ func TestBuildBudgetCutOffEmitsWeeksWithoutSales(t *testing.T) {
|
|||||||
|
|
||||||
require.Len(t, budget.Weekly, 3)
|
require.Len(t, budget.Weekly, 3)
|
||||||
require.Zero(t, budget.Weekly[0].Revenue)
|
require.Zero(t, budget.Weekly[0].Revenue)
|
||||||
require.Zero(t, budget.Weekly[0].LimitPurchase)
|
require.Zero(t, budget.Weekly[0].LimitTeam)
|
||||||
require.Zero(t, budget.Weekly[1].Revenue)
|
require.Zero(t, budget.Weekly[1].Revenue)
|
||||||
require.Equal(t, float64(4_000_000), budget.Weekly[2].Revenue)
|
require.Equal(t, float64(4_000_000), budget.Weekly[2].Revenue)
|
||||||
require.Equal(t, float64(4_000_000), budget.Total.Revenue)
|
require.Equal(t, float64(4_000_000), budget.Total.Revenue)
|
||||||
|
|||||||
@@ -129,8 +129,6 @@ func (p *CustomerOrderProcessor) Detail(ctx context.Context, customerID, orderID
|
|||||||
Amount: pay.Amount,
|
Amount: pay.Amount,
|
||||||
Status: pay.Status,
|
Status: pay.Status,
|
||||||
RefundAmount: pay.RefundAmount,
|
RefundAmount: pay.RefundAmount,
|
||||||
PointsUsed: pay.PointsUsed,
|
|
||||||
PointValue: pay.PointValue,
|
|
||||||
CreatedAt: pay.CreatedAt,
|
CreatedAt: pay.CreatedAt,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -110,7 +110,6 @@ func TestCustomerOrders_DetailHasItemsPaymentsAndEarning(t *testing.T) {
|
|||||||
repo, customer, mine, _ := newCustomerOrderTest()
|
repo, customer, mine, _ := newCustomerOrderTest()
|
||||||
variant, unit := "Large", "ons"
|
variant, unit := "Large", "ons"
|
||||||
weight := 4.2
|
weight := 4.2
|
||||||
points, value := int64(12500), 1.0
|
|
||||||
repo.items = map[uuid.UUID][]repository.CustomerOrderItemRow{
|
repo.items = map[uuid.UUID][]repository.CustomerOrderItemRow{
|
||||||
mine: {
|
mine: {
|
||||||
{ProductName: "Kopi Susu", VariantName: &variant, Quantity: 2, UnitPrice: 25000, TotalPrice: 50000, Status: "completed"},
|
{ProductName: "Kopi Susu", VariantName: &variant, Quantity: 2, UnitPrice: 25000, TotalPrice: 50000, Status: "completed"},
|
||||||
@@ -119,7 +118,7 @@ func TestCustomerOrders_DetailHasItemsPaymentsAndEarning(t *testing.T) {
|
|||||||
}
|
}
|
||||||
repo.payments = map[uuid.UUID][]repository.CustomerOrderPaymentRow{
|
repo.payments = map[uuid.UUID][]repository.CustomerOrderPaymentRow{
|
||||||
mine: {
|
mine: {
|
||||||
{MethodName: "EnakPoint", MethodType: "point", Amount: 12500, Status: "completed", PointsUsed: &points, PointValue: &value},
|
{MethodName: "Card", MethodType: "card", Amount: 12500, Status: "completed"},
|
||||||
{MethodName: "Cash", MethodType: "cash", Amount: 86500, Status: "completed"},
|
{MethodName: "Cash", MethodType: "cash", Amount: 86500, Status: "completed"},
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
@@ -135,7 +134,8 @@ func TestCustomerOrders_DetailHasItemsPaymentsAndEarning(t *testing.T) {
|
|||||||
assert.Equal(t, []map[string]interface{}{}, got.Items[0].Modifiers, "no modifiers is an empty list, not null")
|
assert.Equal(t, []map[string]interface{}{}, got.Items[0].Modifiers, "no modifiers is an empty list, not null")
|
||||||
assert.Equal(t, 4.2, *got.Items[1].Weight)
|
assert.Equal(t, 4.2, *got.Items[1].Weight)
|
||||||
require.Len(t, got.Payments, 2)
|
require.Len(t, got.Payments, 2)
|
||||||
assert.Equal(t, int64(12500), *got.Payments[0].PointsUsed)
|
assert.Equal(t, "Card", got.Payments[0].MethodName)
|
||||||
|
assert.Equal(t, float64(12500), got.Payments[0].Amount)
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestCustomerOrders_AnotherCustomersOrderIsNotFound(t *testing.T) {
|
func TestCustomerOrders_AnotherCustomersOrderIsNotFound(t *testing.T) {
|
||||||
|
|||||||
@@ -40,7 +40,6 @@ func (p *CustomerOutletProcessor) List(ctx context.Context, customerID uuid.UUID
|
|||||||
ID: o.ID,
|
ID: o.ID,
|
||||||
Name: o.Name,
|
Name: o.Name,
|
||||||
Address: o.Address,
|
Address: o.Address,
|
||||||
AcceptsPointPayment: settings.PointPayment.AcceptPayment,
|
|
||||||
EarnsPoints: settings.Point.Enabled,
|
EarnsPoints: settings.Point.Enabled,
|
||||||
EarnsCoins: settings.Coin.Enabled,
|
EarnsCoins: settings.Coin.Enabled,
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -48,17 +48,14 @@ func TestCustomerOutlets_ListsTheCustomersOrganizationWithLoyaltyFlags(t *testin
|
|||||||
},
|
},
|
||||||
}
|
}
|
||||||
settings := outletSettingsFake{
|
settings := outletSettingsFake{
|
||||||
kemang: {
|
kemang: {Point: models.LoyaltyEarnSettings{Enabled: true}},
|
||||||
Point: models.LoyaltyEarnSettings{Enabled: true},
|
|
||||||
PointPayment: models.LoyaltyPointPaymentSettings{AcceptPayment: true},
|
|
||||||
},
|
|
||||||
}
|
}
|
||||||
|
|
||||||
got, err := NewCustomerOutletProcessor(repo, settings).List(context.Background(), customer)
|
got, err := NewCustomerOutletProcessor(repo, settings).List(context.Background(), customer)
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
assert.Equal(t, []models.CustomerOutlet{
|
assert.Equal(t, []models.CustomerOutlet{
|
||||||
{ID: blokm, Name: "Blok M"},
|
{ID: blokm, Name: "Blok M"},
|
||||||
{ID: kemang, Name: "Kemang", Address: &addr, AcceptsPointPayment: true, EarnsPoints: true},
|
{ID: kemang, Name: "Kemang", Address: &addr, EarnsPoints: true},
|
||||||
}, got)
|
}, got)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -47,6 +47,10 @@ const (
|
|||||||
PinActionTransfer PinAction = "TRANSFER"
|
PinActionTransfer PinAction = "TRANSFER"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
type pinVerifier interface {
|
||||||
|
VerifyPin(ctx context.Context, customerID uuid.UUID, pin string, action PinAction, info models.CustomerPinRequestInfo) error
|
||||||
|
}
|
||||||
|
|
||||||
// Codes of PinError, which the apps tell apart (docs/prd-point-coin.md §9).
|
// Codes of PinError, which the apps tell apart (docs/prd-point-coin.md §9).
|
||||||
const (
|
const (
|
||||||
PinErrNotSet = "PIN_NOT_SET"
|
PinErrNotSet = "PIN_NOT_SET"
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ package processor
|
|||||||
import (
|
import (
|
||||||
"math"
|
"math"
|
||||||
|
|
||||||
|
"apskel-pos-be/internal/constants"
|
||||||
"apskel-pos-be/internal/entities"
|
"apskel-pos-be/internal/entities"
|
||||||
"apskel-pos-be/internal/models"
|
"apskel-pos-be/internal/models"
|
||||||
)
|
)
|
||||||
@@ -20,7 +21,7 @@ type EarningLine struct {
|
|||||||
|
|
||||||
// EarningResult is what an order earns.
|
// EarningResult is what an order earns.
|
||||||
type EarningResult struct {
|
type EarningResult struct {
|
||||||
// subtotal − discount − the part paid with EnakPoint, in rupiah, never negative.
|
// subtotal − discount, in rupiah, never negative.
|
||||||
// Tax and anything else added on top of the subtotal are not part of it (Q1).
|
// Tax and anything else added on top of the subtotal are not part of it (Q1).
|
||||||
Basis float64
|
Basis float64
|
||||||
Point EarningLine
|
Point EarningLine
|
||||||
@@ -36,6 +37,10 @@ func (r EarningResult) Metadata(line EarningLine) entities.Metadata {
|
|||||||
"min_order_amount": line.Settings.MinOrderAmount,
|
"min_order_amount": line.Settings.MinOrderAmount,
|
||||||
"capped": line.Capped,
|
"capped": line.Capped,
|
||||||
}
|
}
|
||||||
|
if line.Settings.EarnMode == constants.LoyaltyEarnModePercentage {
|
||||||
|
m["earn_mode"] = line.Settings.EarnMode
|
||||||
|
m["earn_percent"] = line.Settings.EarnPercent
|
||||||
|
}
|
||||||
if line.Settings.MaxPerOrder != nil {
|
if line.Settings.MaxPerOrder != nil {
|
||||||
m["max_per_order"] = *line.Settings.MaxPerOrder
|
m["max_per_order"] = *line.Settings.MaxPerOrder
|
||||||
}
|
}
|
||||||
@@ -44,16 +49,16 @@ func (r EarningResult) Metadata(line EarningLine) entities.Metadata {
|
|||||||
|
|
||||||
// CalculateEarning applies the earning formula of docs/prd-point-coin.md F1:
|
// CalculateEarning applies the earning formula of docs/prd-point-coin.md F1:
|
||||||
//
|
//
|
||||||
// basis = subtotal − discount_amount − paid with EnakPoint
|
// basis = subtotal − discount_amount
|
||||||
// amount = 0 if basis < min_order_amount
|
// amount = 0 if basis < min_order_amount
|
||||||
// amount = floor(basis / earn_per_amount) × earn_value
|
// amount = floor(basis / earn_per_amount) × earn_value in PER_AMOUNT mode
|
||||||
|
// amount = floor(basis × earn_percent / 100) in PERCENTAGE mode
|
||||||
// amount = min(amount, max_per_order) if max_per_order is set
|
// amount = min(amount, max_per_order) if max_per_order is set
|
||||||
//
|
//
|
||||||
// The part paid with EnakPoint earns nothing (Q10). Money is handled in whole cents so
|
// Money is handled in whole cents so floor never lands one short on a value like
|
||||||
// floor never lands one short on a value like 87500.00 that float64 cannot hold
|
// 87500.00 that float64 cannot hold exactly. It has no side effects.
|
||||||
// exactly. It has no side effects.
|
func CalculateEarning(order *entities.Order, settings models.OutletLoyaltySettings) EarningResult {
|
||||||
func CalculateEarning(order *entities.Order, pointPaidAmount float64, settings models.OutletLoyaltySettings) EarningResult {
|
basisCents := toCents(order.Subtotal) - toCents(order.DiscountAmount)
|
||||||
basisCents := toCents(order.Subtotal) - toCents(order.DiscountAmount) - toCents(pointPaidAmount)
|
|
||||||
if basisCents < 0 {
|
if basisCents < 0 {
|
||||||
basisCents = 0
|
basisCents = 0
|
||||||
}
|
}
|
||||||
@@ -66,13 +71,23 @@ func CalculateEarning(order *entities.Order, pointPaidAmount float64, settings m
|
|||||||
|
|
||||||
func earnLine(basisCents int64, s models.LoyaltyEarnSettings) EarningLine {
|
func earnLine(basisCents int64, s models.LoyaltyEarnSettings) EarningLine {
|
||||||
line := EarningLine{Settings: s}
|
line := EarningLine{Settings: s}
|
||||||
if !s.Enabled || s.EarnPerAmount <= 0 || s.EarnValue <= 0 {
|
if !s.Enabled || basisCents < s.MinOrderAmount*100 {
|
||||||
return line
|
return line
|
||||||
}
|
}
|
||||||
if basisCents < s.MinOrderAmount*100 {
|
if s.EarnMode == constants.LoyaltyEarnModePercentage {
|
||||||
|
// The percent has at most two decimals, so in hundredths it is whole and the
|
||||||
|
// product stays in integers: cents × hundredths / (100 × 100 × 100).
|
||||||
|
hundredths := int64(math.Round(s.EarnPercent * 100))
|
||||||
|
if hundredths <= 0 {
|
||||||
|
return line
|
||||||
|
}
|
||||||
|
line.Amount = basisCents * hundredths / 1_000_000
|
||||||
|
} else {
|
||||||
|
if s.EarnPerAmount <= 0 || s.EarnValue <= 0 {
|
||||||
return line
|
return line
|
||||||
}
|
}
|
||||||
line.Amount = basisCents / (s.EarnPerAmount * 100) * s.EarnValue
|
line.Amount = basisCents / (s.EarnPerAmount * 100) * s.EarnValue
|
||||||
|
}
|
||||||
if s.MaxPerOrder != nil && line.Amount > *s.MaxPerOrder {
|
if s.MaxPerOrder != nil && line.Amount > *s.MaxPerOrder {
|
||||||
line.Amount = *s.MaxPerOrder
|
line.Amount = *s.MaxPerOrder
|
||||||
line.Capped = true
|
line.Capped = true
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import (
|
|||||||
|
|
||||||
"github.com/stretchr/testify/assert"
|
"github.com/stretchr/testify/assert"
|
||||||
|
|
||||||
|
"apskel-pos-be/internal/constants"
|
||||||
"apskel-pos-be/internal/entities"
|
"apskel-pos-be/internal/entities"
|
||||||
"apskel-pos-be/internal/models"
|
"apskel-pos-be/internal/models"
|
||||||
)
|
)
|
||||||
@@ -21,35 +22,29 @@ func TestCalculateEarning_PRDExample(t *testing.T) {
|
|||||||
// Subtotal after discount Rp 87.500, paid in full in cash.
|
// Subtotal after discount Rp 87.500, paid in full in cash.
|
||||||
order := &entities.Order{Subtotal: 97500, DiscountAmount: 10000, TaxAmount: 9625, TotalAmount: 97125}
|
order := &entities.Order{Subtotal: 97500, DiscountAmount: 10000, TaxAmount: 9625, TotalAmount: 97125}
|
||||||
|
|
||||||
got := CalculateEarning(order, 0, prdEarningSettings())
|
got := CalculateEarning(order, prdEarningSettings())
|
||||||
assert.Equal(t, 87500.0, got.Basis)
|
assert.Equal(t, 87500.0, got.Basis)
|
||||||
assert.Equal(t, int64(875), got.Point.Amount)
|
assert.Equal(t, int64(875), got.Point.Amount)
|
||||||
assert.Equal(t, int64(3), got.Coin.Amount)
|
assert.Equal(t, int64(3), got.Coin.Amount)
|
||||||
|
|
||||||
// Rp 20.000 of it paid with EnakPoint earns nothing.
|
|
||||||
got = CalculateEarning(order, 20000, prdEarningSettings())
|
|
||||||
assert.Equal(t, 67500.0, got.Basis)
|
|
||||||
assert.Equal(t, int64(675), got.Point.Amount)
|
|
||||||
assert.Equal(t, int64(2), got.Coin.Amount)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestCalculateEarning_TaxIsNotPartOfTheBasis(t *testing.T) {
|
func TestCalculateEarning_TaxIsNotPartOfTheBasis(t *testing.T) {
|
||||||
withoutTax := &entities.Order{Subtotal: 50000}
|
withoutTax := &entities.Order{Subtotal: 50000}
|
||||||
withTax := &entities.Order{Subtotal: 50000, TaxAmount: 5500, TotalAmount: 55500}
|
withTax := &entities.Order{Subtotal: 50000, TaxAmount: 5500, TotalAmount: 55500}
|
||||||
assert.Equal(t, CalculateEarning(withoutTax, 0, prdEarningSettings()), CalculateEarning(withTax, 0, prdEarningSettings()))
|
assert.Equal(t, CalculateEarning(withoutTax, prdEarningSettings()), CalculateEarning(withTax, prdEarningSettings()))
|
||||||
assert.Equal(t, int64(500), CalculateEarning(withTax, 0, prdEarningSettings()).Point.Amount)
|
assert.Equal(t, int64(500), CalculateEarning(withTax, prdEarningSettings()).Point.Amount)
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestCalculateEarning_BelowMinimum(t *testing.T) {
|
func TestCalculateEarning_BelowMinimum(t *testing.T) {
|
||||||
s := prdEarningSettings()
|
s := prdEarningSettings()
|
||||||
s.Point.MinOrderAmount = 50000
|
s.Point.MinOrderAmount = 50000
|
||||||
|
|
||||||
assert.Equal(t, int64(0), CalculateEarning(&entities.Order{Subtotal: 49999}, 0, s).Point.Amount)
|
assert.Equal(t, int64(0), CalculateEarning(&entities.Order{Subtotal: 49999}, s).Point.Amount)
|
||||||
assert.Equal(t, int64(500), CalculateEarning(&entities.Order{Subtotal: 50000}, 0, s).Point.Amount, "the minimum itself earns")
|
assert.Equal(t, int64(500), CalculateEarning(&entities.Order{Subtotal: 50000}, s).Point.Amount, "the minimum itself earns")
|
||||||
// The minimum applies to the basis, after discount and EnakPoint.
|
// The minimum applies to the basis, after discount.
|
||||||
assert.Equal(t, int64(0), CalculateEarning(&entities.Order{Subtotal: 60000}, 15000, s).Point.Amount)
|
assert.Equal(t, int64(0), CalculateEarning(&entities.Order{Subtotal: 60000, DiscountAmount: 15000}, s).Point.Amount)
|
||||||
// Coin has its own minimum.
|
// Coin has its own minimum.
|
||||||
assert.Equal(t, int64(1), CalculateEarning(&entities.Order{Subtotal: 49999}, 0, s).Coin.Amount)
|
assert.Equal(t, int64(1), CalculateEarning(&entities.Order{Subtotal: 49999}, s).Coin.Amount)
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestCalculateEarning_MaxPerOrder(t *testing.T) {
|
func TestCalculateEarning_MaxPerOrder(t *testing.T) {
|
||||||
@@ -57,36 +52,36 @@ func TestCalculateEarning_MaxPerOrder(t *testing.T) {
|
|||||||
max := int64(300)
|
max := int64(300)
|
||||||
s.Point.MaxPerOrder = &max
|
s.Point.MaxPerOrder = &max
|
||||||
|
|
||||||
got := CalculateEarning(&entities.Order{Subtotal: 87500}, 0, s)
|
got := CalculateEarning(&entities.Order{Subtotal: 87500}, s)
|
||||||
assert.Equal(t, int64(300), got.Point.Amount)
|
assert.Equal(t, int64(300), got.Point.Amount)
|
||||||
assert.True(t, got.Point.Capped)
|
assert.True(t, got.Point.Capped)
|
||||||
assert.Equal(t, int64(300), got.Metadata(got.Point)["max_per_order"])
|
assert.Equal(t, int64(300), got.Metadata(got.Point)["max_per_order"])
|
||||||
|
|
||||||
got = CalculateEarning(&entities.Order{Subtotal: 20000}, 0, s)
|
got = CalculateEarning(&entities.Order{Subtotal: 20000}, s)
|
||||||
assert.Equal(t, int64(200), got.Point.Amount)
|
assert.Equal(t, int64(200), got.Point.Amount)
|
||||||
assert.False(t, got.Point.Capped)
|
assert.False(t, got.Point.Capped)
|
||||||
|
|
||||||
zero := int64(0)
|
zero := int64(0)
|
||||||
s.Point.MaxPerOrder = &zero
|
s.Point.MaxPerOrder = &zero
|
||||||
assert.Equal(t, int64(0), CalculateEarning(&entities.Order{Subtotal: 87500}, 0, s).Point.Amount)
|
assert.Equal(t, int64(0), CalculateEarning(&entities.Order{Subtotal: 87500}, s).Point.Amount)
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestCalculateEarning_DisabledEarnsNothing(t *testing.T) {
|
func TestCalculateEarning_DisabledEarnsNothing(t *testing.T) {
|
||||||
s := prdEarningSettings()
|
s := prdEarningSettings()
|
||||||
s.Point.Enabled = false
|
s.Point.Enabled = false
|
||||||
got := CalculateEarning(&entities.Order{Subtotal: 87500}, 0, s)
|
got := CalculateEarning(&entities.Order{Subtotal: 87500}, s)
|
||||||
assert.Equal(t, int64(0), got.Point.Amount)
|
assert.Equal(t, int64(0), got.Point.Amount)
|
||||||
assert.Equal(t, int64(3), got.Coin.Amount, "each currency is switched on its own")
|
assert.Equal(t, int64(3), got.Coin.Amount, "each currency is switched on its own")
|
||||||
|
|
||||||
s.Coin.Enabled = false
|
s.Coin.Enabled = false
|
||||||
got = CalculateEarning(&entities.Order{Subtotal: 87500}, 0, s)
|
got = CalculateEarning(&entities.Order{Subtotal: 87500}, s)
|
||||||
assert.Equal(t, int64(0), got.Coin.Amount)
|
assert.Equal(t, int64(0), got.Coin.Amount)
|
||||||
assert.Equal(t, 87500.0, got.Basis, "the basis is still reported")
|
assert.Equal(t, 87500.0, got.Basis, "the basis is still reported")
|
||||||
|
|
||||||
// The defaults of an outlet that never set anything earn nothing.
|
// The defaults of an outlet that never set anything earn nothing.
|
||||||
var defaults models.OutletLoyaltySettings
|
var defaults models.OutletLoyaltySettings
|
||||||
loadLoyaltyFields(outletLoyaltyFields(&defaults), nil, "test")
|
loadLoyaltyFields(outletLoyaltyFields(&defaults), nil, "test")
|
||||||
got = CalculateEarning(&entities.Order{Subtotal: 87500}, 0, defaults)
|
got = CalculateEarning(&entities.Order{Subtotal: 87500}, defaults)
|
||||||
assert.Equal(t, int64(0), got.Point.Amount)
|
assert.Equal(t, int64(0), got.Point.Amount)
|
||||||
assert.Equal(t, int64(0), got.Coin.Amount)
|
assert.Equal(t, int64(0), got.Coin.Amount)
|
||||||
}
|
}
|
||||||
@@ -95,26 +90,62 @@ func TestCalculateEarning_EdgeCases(t *testing.T) {
|
|||||||
s := prdEarningSettings()
|
s := prdEarningSettings()
|
||||||
|
|
||||||
// floor, not round.
|
// floor, not round.
|
||||||
assert.Equal(t, int64(875), CalculateEarning(&entities.Order{Subtotal: 87599.99}, 0, s).Point.Amount)
|
assert.Equal(t, int64(875), CalculateEarning(&entities.Order{Subtotal: 87599.99}, s).Point.Amount)
|
||||||
// Values float64 cannot hold exactly do not lose a point: computed in float64 this
|
// Values float64 cannot hold exactly do not lose a point: computed in float64 this
|
||||||
// basis divides to 4956.999…, which a naive floor turns into 4956.
|
// basis divides to 4956.999…, which a naive floor turns into 4956.
|
||||||
per250 := prdEarningSettings()
|
per250 := prdEarningSettings()
|
||||||
per250.Point.EarnPerAmount = 250
|
per250.Point.EarnPerAmount = 250
|
||||||
assert.Equal(t, int64(4957), CalculateEarning(&entities.Order{Subtotal: 1240155.48, DiscountAmount: 749.11}, 156.37, per250).Point.Amount)
|
assert.Equal(t, int64(4957), CalculateEarning(&entities.Order{Subtotal: 1240155.48, DiscountAmount: 905.48}, per250).Point.Amount)
|
||||||
// Paying more with EnakPoint than the basis leaves nothing, never a negative amount.
|
// A discount larger than the subtotal leaves nothing, never a negative amount.
|
||||||
got := CalculateEarning(&entities.Order{Subtotal: 10000}, 15000, s)
|
got := CalculateEarning(&entities.Order{Subtotal: 10000, DiscountAmount: 15000}, s)
|
||||||
assert.Equal(t, 0.0, got.Basis)
|
assert.Equal(t, 0.0, got.Basis)
|
||||||
assert.Equal(t, int64(0), got.Point.Amount)
|
assert.Equal(t, int64(0), got.Point.Amount)
|
||||||
// earn_value multiplies.
|
// earn_value multiplies.
|
||||||
s.Point.EarnValue = 5
|
s.Point.EarnValue = 5
|
||||||
assert.Equal(t, int64(4375), CalculateEarning(&entities.Order{Subtotal: 87500}, 0, s).Point.Amount)
|
assert.Equal(t, int64(4375), CalculateEarning(&entities.Order{Subtotal: 87500}, s).Point.Amount)
|
||||||
// A zero earn_value earns nothing even when enabled.
|
// A zero earn_value earns nothing even when enabled.
|
||||||
s.Point.EarnValue = 0
|
s.Point.EarnValue = 0
|
||||||
assert.Equal(t, int64(0), CalculateEarning(&entities.Order{Subtotal: 87500}, 0, s).Point.Amount)
|
assert.Equal(t, int64(0), CalculateEarning(&entities.Order{Subtotal: 87500}, s).Point.Amount)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCalculateEarning_Percentage(t *testing.T) {
|
||||||
|
s := prdEarningSettings()
|
||||||
|
s.Point.EarnMode = constants.LoyaltyEarnModePercentage
|
||||||
|
s.Point.EarnPercent = 1
|
||||||
|
|
||||||
|
// 1% of the basis; the per-amount settings are ignored, and coin keeps its own mode.
|
||||||
|
got := CalculateEarning(&entities.Order{Subtotal: 97500, DiscountAmount: 10000}, s)
|
||||||
|
assert.Equal(t, int64(875), got.Point.Amount)
|
||||||
|
assert.Equal(t, int64(3), got.Coin.Amount)
|
||||||
|
|
||||||
|
// Decimals, and floor, not round: 2.5% of 87.500 is 2187.5.
|
||||||
|
s.Point.EarnPercent = 2.5
|
||||||
|
assert.Equal(t, int64(2187), CalculateEarning(&entities.Order{Subtotal: 87500}, s).Point.Amount)
|
||||||
|
s.Point.EarnPercent = 0.01
|
||||||
|
assert.Equal(t, int64(8), CalculateEarning(&entities.Order{Subtotal: 87599.99}, s).Point.Amount)
|
||||||
|
|
||||||
|
// The minimum and the cap apply as in the other mode.
|
||||||
|
s.Point.EarnPercent = 10
|
||||||
|
s.Point.MinOrderAmount = 50000
|
||||||
|
max := int64(6000)
|
||||||
|
s.Point.MaxPerOrder = &max
|
||||||
|
assert.Equal(t, int64(0), CalculateEarning(&entities.Order{Subtotal: 49999}, s).Point.Amount)
|
||||||
|
assert.Equal(t, int64(5000), CalculateEarning(&entities.Order{Subtotal: 50000}, s).Point.Amount)
|
||||||
|
got = CalculateEarning(&entities.Order{Subtotal: 87500}, s)
|
||||||
|
assert.Equal(t, int64(6000), got.Point.Amount)
|
||||||
|
assert.True(t, got.Point.Capped)
|
||||||
|
|
||||||
|
// The mode and percent are frozen on the ledger row.
|
||||||
|
assert.Equal(t, constants.LoyaltyEarnModePercentage, got.Metadata(got.Point)["earn_mode"])
|
||||||
|
assert.Equal(t, 10.0, got.Metadata(got.Point)["earn_percent"])
|
||||||
|
|
||||||
|
// A zero percent earns nothing even when enabled.
|
||||||
|
s.Point.EarnPercent = 0
|
||||||
|
assert.Equal(t, int64(0), CalculateEarning(&entities.Order{Subtotal: 87500}, s).Point.Amount)
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestCalculateEarning_MetadataSnapshot(t *testing.T) {
|
func TestCalculateEarning_MetadataSnapshot(t *testing.T) {
|
||||||
got := CalculateEarning(&entities.Order{Subtotal: 87500}, 0, prdEarningSettings())
|
got := CalculateEarning(&entities.Order{Subtotal: 87500}, prdEarningSettings())
|
||||||
assert.Equal(t, entities.Metadata{
|
assert.Equal(t, entities.Metadata{
|
||||||
"basis": 87500.0, "earn_per_amount": int64(100), "earn_value": int64(1), "min_order_amount": int64(0), "capped": false,
|
"basis": 87500.0, "earn_per_amount": int64(100), "earn_value": int64(1), "min_order_amount": int64(0), "capped": false,
|
||||||
}, got.Metadata(got.Point))
|
}, got.Metadata(got.Point))
|
||||||
|
|||||||
@@ -86,11 +86,7 @@ func (p *EarningProcessor) EarnForOrder(ctx context.Context, orderID uuid.UUID)
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
pointPaid, err := p.orders.PointPaidAmount(ctx, orderID)
|
result := CalculateEarning(&entities.Order{Subtotal: order.Subtotal, DiscountAmount: order.DiscountAmount}, *settings)
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
result := CalculateEarning(&entities.Order{Subtotal: order.Subtotal, DiscountAmount: order.DiscountAmount}, pointPaid, *settings)
|
|
||||||
if result.Point.Amount == 0 && result.Coin.Amount == 0 {
|
if result.Point.Amount == 0 && result.Coin.Amount == 0 {
|
||||||
return &EarningOutcome{Skipped: EarningSkipNothingToEarn}, nil
|
return &EarningOutcome{Skipped: EarningSkipNothingToEarn}, nil
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -140,8 +140,8 @@ func TestEarningReversal_AgainstPostgres(t *testing.T) {
|
|||||||
spent := paidOrder(spender)
|
spent := paidOrder(spender)
|
||||||
committed(t, txm, func(ctx context.Context) (*WalletResult, error) {
|
committed(t, txm, func(ctx context.Context) (*WalletResult, error) {
|
||||||
return wallet.Debit(ctx, WalletDebitInput{WalletEntry: WalletEntry{
|
return wallet.Debit(ctx, WalletDebitInput{WalletEntry: WalletEntry{
|
||||||
CustomerID: spender, Currency: constants.WalletCurrencyPoint, Type: constants.WalletTxTypePayment,
|
CustomerID: spender, Currency: constants.WalletCurrencyPoint, Type: constants.WalletTxTypeRewardRedeem,
|
||||||
Amount: 800, ReferenceType: constants.WalletRefTypePayment, ReferenceID: uuid.New(), OutletID: &outlet,
|
Amount: 800, ReferenceType: constants.WalletRefTypeRewardRedemption, ReferenceID: uuid.New(), OutletID: &outlet,
|
||||||
Description: "Bayar"}})
|
Description: "Bayar"}})
|
||||||
})
|
})
|
||||||
exec(`UPDATE orders SET is_void = true WHERE id = ?`, spent)
|
exec(`UPDATE orders SET is_void = true WHERE id = ?`, spent)
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"math"
|
||||||
"strconv"
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
@@ -240,20 +241,22 @@ func loyaltySettingChangeModel(row entities.LoyaltySettingChange) models.Loyalty
|
|||||||
func outletLoyaltyFields(s *models.OutletLoyaltySettings) []loyaltyField {
|
func outletLoyaltyFields(s *models.OutletLoyaltySettings) []loyaltyField {
|
||||||
return []loyaltyField{
|
return []loyaltyField{
|
||||||
boolLoyaltyField(constants.LoyaltyPointEnabledKey, &s.Point.Enabled, false),
|
boolLoyaltyField(constants.LoyaltyPointEnabledKey, &s.Point.Enabled, false),
|
||||||
|
enumLoyaltyField(constants.LoyaltyPointEarnModeKey, &s.Point.EarnMode, constants.LoyaltyEarnModeDefault,
|
||||||
|
constants.LoyaltyEarnModePerAmount, constants.LoyaltyEarnModePercentage),
|
||||||
intLoyaltyField(constants.LoyaltyPointEarnPerAmountKey, &s.Point.EarnPerAmount, constants.LoyaltyPointEarnPerAmountDefault, 1, noLoyaltyMax),
|
intLoyaltyField(constants.LoyaltyPointEarnPerAmountKey, &s.Point.EarnPerAmount, constants.LoyaltyPointEarnPerAmountDefault, 1, noLoyaltyMax),
|
||||||
intLoyaltyField(constants.LoyaltyPointEarnValueKey, &s.Point.EarnValue, constants.LoyaltyEarnValueDefault, 0, noLoyaltyMax),
|
intLoyaltyField(constants.LoyaltyPointEarnValueKey, &s.Point.EarnValue, constants.LoyaltyEarnValueDefault, 0, noLoyaltyMax),
|
||||||
|
percentLoyaltyField(constants.LoyaltyPointEarnPercentKey, &s.Point.EarnPercent, constants.LoyaltyEarnPercentDefault),
|
||||||
intLoyaltyField(constants.LoyaltyPointMinOrderAmountKey, &s.Point.MinOrderAmount, 0, 0, noLoyaltyMax),
|
intLoyaltyField(constants.LoyaltyPointMinOrderAmountKey, &s.Point.MinOrderAmount, 0, 0, noLoyaltyMax),
|
||||||
optionalIntLoyaltyField(constants.LoyaltyPointMaxPerOrderKey, &s.Point.MaxPerOrder, 0),
|
optionalIntLoyaltyField(constants.LoyaltyPointMaxPerOrderKey, &s.Point.MaxPerOrder, 0),
|
||||||
|
|
||||||
boolLoyaltyField(constants.LoyaltyCoinEnabledKey, &s.Coin.Enabled, false),
|
boolLoyaltyField(constants.LoyaltyCoinEnabledKey, &s.Coin.Enabled, false),
|
||||||
|
enumLoyaltyField(constants.LoyaltyCoinEarnModeKey, &s.Coin.EarnMode, constants.LoyaltyEarnModeDefault,
|
||||||
|
constants.LoyaltyEarnModePerAmount, constants.LoyaltyEarnModePercentage),
|
||||||
intLoyaltyField(constants.LoyaltyCoinEarnPerAmountKey, &s.Coin.EarnPerAmount, constants.LoyaltyCoinEarnPerAmountDefault, 1, noLoyaltyMax),
|
intLoyaltyField(constants.LoyaltyCoinEarnPerAmountKey, &s.Coin.EarnPerAmount, constants.LoyaltyCoinEarnPerAmountDefault, 1, noLoyaltyMax),
|
||||||
intLoyaltyField(constants.LoyaltyCoinEarnValueKey, &s.Coin.EarnValue, constants.LoyaltyEarnValueDefault, 0, noLoyaltyMax),
|
intLoyaltyField(constants.LoyaltyCoinEarnValueKey, &s.Coin.EarnValue, constants.LoyaltyEarnValueDefault, 0, noLoyaltyMax),
|
||||||
|
percentLoyaltyField(constants.LoyaltyCoinEarnPercentKey, &s.Coin.EarnPercent, constants.LoyaltyEarnPercentDefault),
|
||||||
intLoyaltyField(constants.LoyaltyCoinMinOrderAmountKey, &s.Coin.MinOrderAmount, 0, 0, noLoyaltyMax),
|
intLoyaltyField(constants.LoyaltyCoinMinOrderAmountKey, &s.Coin.MinOrderAmount, 0, 0, noLoyaltyMax),
|
||||||
optionalIntLoyaltyField(constants.LoyaltyCoinMaxPerOrderKey, &s.Coin.MaxPerOrder, 0),
|
optionalIntLoyaltyField(constants.LoyaltyCoinMaxPerOrderKey, &s.Coin.MaxPerOrder, 0),
|
||||||
|
|
||||||
boolLoyaltyField(constants.LoyaltyPointAcceptPaymentKey, &s.PointPayment.AcceptPayment, false),
|
|
||||||
intLoyaltyField(constants.LoyaltyPointMinPaymentPointsKey, &s.PointPayment.MinPaymentPoints, constants.LoyaltyMinPaymentPointsDefault, 1, noLoyaltyMax),
|
|
||||||
intLoyaltyField(constants.LoyaltyPointMaxPaymentPercentKey, &s.PointPayment.MaxPaymentPercent, constants.LoyaltyMaxPaymentPercentDefault, 0, 100),
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -329,6 +332,35 @@ func intLoyaltyField(key string, v *int64, def, min, max int64) loyaltyField {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// percentLoyaltyField is a percentage from 0 to 100 with at most two decimals, so it
|
||||||
|
// is whole in hundredths and calculations with it stay in integers.
|
||||||
|
func percentLoyaltyField(key string, v *float64, def float64) loyaltyField {
|
||||||
|
check := func(n float64) error {
|
||||||
|
// The negated form also rejects NaN.
|
||||||
|
if !(n >= 0 && n <= 100) {
|
||||||
|
return fmt.Errorf("%w: %s must be between 0 and 100", ErrInvalidLoyaltySettings, key)
|
||||||
|
}
|
||||||
|
if math.Abs(n*100-math.Round(n*100)) > 1e-6 {
|
||||||
|
return fmt.Errorf("%w: %s must have at most two decimals", ErrInvalidLoyaltySettings, key)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return loyaltyField{
|
||||||
|
key: key,
|
||||||
|
parse: func(raw string) bool {
|
||||||
|
n, err := strconv.ParseFloat(strings.TrimSpace(raw), 64)
|
||||||
|
if err != nil || check(n) != nil {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
*v = n
|
||||||
|
return true
|
||||||
|
},
|
||||||
|
reset: func() { *v = def },
|
||||||
|
validate: func() error { return check(*v) },
|
||||||
|
format: func() *string { s := strconv.FormatFloat(*v, 'f', -1, 64); return &s },
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// optionalIntLoyaltyField is a limit that may be unset, meaning no limit.
|
// optionalIntLoyaltyField is a limit that may be unset, meaning no limit.
|
||||||
func optionalIntLoyaltyField(key string, v **int64, min int64) loyaltyField {
|
func optionalIntLoyaltyField(key string, v **int64, min int64) loyaltyField {
|
||||||
return loyaltyField{
|
return loyaltyField{
|
||||||
|
|||||||
@@ -107,9 +107,8 @@ func TestLoyaltySettings_OutletWithoutSettingsGetsEveryDefault(t *testing.T) {
|
|||||||
s, err := p.Outlet(context.Background(), uuid.New())
|
s, err := p.Outlet(context.Background(), uuid.New())
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
assert.Equal(t, models.OutletLoyaltySettings{
|
assert.Equal(t, models.OutletLoyaltySettings{
|
||||||
Point: models.LoyaltyEarnSettings{Enabled: false, EarnPerAmount: 100, EarnValue: 1, MinOrderAmount: 0, MaxPerOrder: nil},
|
Point: models.LoyaltyEarnSettings{Enabled: false, EarnMode: "PER_AMOUNT", EarnPerAmount: 100, EarnValue: 1, EarnPercent: 1, MinOrderAmount: 0, MaxPerOrder: nil},
|
||||||
Coin: models.LoyaltyEarnSettings{Enabled: false, EarnPerAmount: 25000, EarnValue: 1, MinOrderAmount: 0, MaxPerOrder: nil},
|
Coin: models.LoyaltyEarnSettings{Enabled: false, EarnMode: "PER_AMOUNT", EarnPerAmount: 25000, EarnValue: 1, EarnPercent: 1, MinOrderAmount: 0, MaxPerOrder: nil},
|
||||||
PointPayment: models.LoyaltyPointPaymentSettings{AcceptPayment: false, MinPaymentPoints: 1, MaxPaymentPercent: 100},
|
|
||||||
}, *s)
|
}, *s)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -133,7 +132,6 @@ func TestLoyaltySettings_StoredValuesAreTyped(t *testing.T) {
|
|||||||
constants.LoyaltyPointEnabledKey: "true",
|
constants.LoyaltyPointEnabledKey: "true",
|
||||||
constants.LoyaltyPointEarnPerAmountKey: " 1000 ",
|
constants.LoyaltyPointEarnPerAmountKey: " 1000 ",
|
||||||
constants.LoyaltyPointMaxPerOrderKey: "500",
|
constants.LoyaltyPointMaxPerOrderKey: "500",
|
||||||
constants.LoyaltyPointMaxPaymentPercentKey: "50",
|
|
||||||
"loyalty.unknown": "ignored",
|
"loyalty.unknown": "ignored",
|
||||||
},
|
},
|
||||||
orgValues: map[string]string{
|
orgValues: map[string]string{
|
||||||
@@ -151,7 +149,6 @@ func TestLoyaltySettings_StoredValuesAreTyped(t *testing.T) {
|
|||||||
assert.True(t, outlet.Point.Enabled)
|
assert.True(t, outlet.Point.Enabled)
|
||||||
assert.Equal(t, int64(1000), outlet.Point.EarnPerAmount)
|
assert.Equal(t, int64(1000), outlet.Point.EarnPerAmount)
|
||||||
assert.Equal(t, int64(500), *outlet.Point.MaxPerOrder)
|
assert.Equal(t, int64(500), *outlet.Point.MaxPerOrder)
|
||||||
assert.Equal(t, int64(50), outlet.PointPayment.MaxPaymentPercent)
|
|
||||||
|
|
||||||
org, err := p.Organization(context.Background(), uuid.New())
|
org, err := p.Organization(context.Background(), uuid.New())
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
@@ -172,7 +169,6 @@ func TestLoyaltySettings_UnusableStoredValuesFallBackToDefault(t *testing.T) {
|
|||||||
constants.LoyaltyPointEarnPerAmountKey: "0",
|
constants.LoyaltyPointEarnPerAmountKey: "0",
|
||||||
constants.LoyaltyCoinEarnValueKey: "-1",
|
constants.LoyaltyCoinEarnValueKey: "-1",
|
||||||
constants.LoyaltyPointMaxPerOrderKey: "abc",
|
constants.LoyaltyPointMaxPerOrderKey: "abc",
|
||||||
constants.LoyaltyPointMaxPaymentPercentKey: "150",
|
|
||||||
},
|
},
|
||||||
orgValues: map[string]string{
|
orgValues: map[string]string{
|
||||||
constants.LoyaltyPointValueKey: "0",
|
constants.LoyaltyPointValueKey: "0",
|
||||||
@@ -188,7 +184,6 @@ func TestLoyaltySettings_UnusableStoredValuesFallBackToDefault(t *testing.T) {
|
|||||||
assert.Equal(t, int64(100), outlet.Point.EarnPerAmount)
|
assert.Equal(t, int64(100), outlet.Point.EarnPerAmount)
|
||||||
assert.Equal(t, int64(1), outlet.Coin.EarnValue)
|
assert.Equal(t, int64(1), outlet.Coin.EarnValue)
|
||||||
assert.Nil(t, outlet.Point.MaxPerOrder)
|
assert.Nil(t, outlet.Point.MaxPerOrder)
|
||||||
assert.Equal(t, int64(100), outlet.PointPayment.MaxPaymentPercent)
|
|
||||||
|
|
||||||
for name, raw := range map[string]string{"not set": "", "garbage": "abc", "zero": "0", "negative": "-5"} {
|
for name, raw := range map[string]string{"not set": "", "garbage": "abc", "zero": "0", "negative": "-5"} {
|
||||||
repo.orgValues = map[string]string{}
|
repo.orgValues = map[string]string{}
|
||||||
@@ -290,11 +285,12 @@ func TestLoyaltySettings_UpdateRejectsInvalidValues(t *testing.T) {
|
|||||||
for name, mutate := range map[string]func(*models.OutletLoyaltySettings){
|
for name, mutate := range map[string]func(*models.OutletLoyaltySettings){
|
||||||
"earn_per_amount 0": func(s *models.OutletLoyaltySettings) { s.Point.EarnPerAmount = 0 },
|
"earn_per_amount 0": func(s *models.OutletLoyaltySettings) { s.Point.EarnPerAmount = 0 },
|
||||||
"negative earn_value": func(s *models.OutletLoyaltySettings) { s.Coin.EarnValue = -1 },
|
"negative earn_value": func(s *models.OutletLoyaltySettings) { s.Coin.EarnValue = -1 },
|
||||||
|
"earn mode unknown": func(s *models.OutletLoyaltySettings) { s.Point.EarnMode = "PERCENT" },
|
||||||
|
"negative earn_percent": func(s *models.OutletLoyaltySettings) { s.Point.EarnPercent = -1 },
|
||||||
|
"earn_percent over 100": func(s *models.OutletLoyaltySettings) { s.Coin.EarnPercent = 100.5 },
|
||||||
|
"earn_percent 3 decimals": func(s *models.OutletLoyaltySettings) { s.Point.EarnPercent = 1.125 },
|
||||||
"negative min_order": func(s *models.OutletLoyaltySettings) { s.Point.MinOrderAmount = -1 },
|
"negative min_order": func(s *models.OutletLoyaltySettings) { s.Point.MinOrderAmount = -1 },
|
||||||
"negative max_per_order": func(s *models.OutletLoyaltySettings) { s.Coin.MaxPerOrder = ptr(int64(-1)) },
|
"negative max_per_order": func(s *models.OutletLoyaltySettings) { s.Coin.MaxPerOrder = ptr(int64(-1)) },
|
||||||
"payment percent over 100": func(s *models.OutletLoyaltySettings) { s.PointPayment.MaxPaymentPercent = 101 },
|
|
||||||
"negative payment percent": func(s *models.OutletLoyaltySettings) { s.PointPayment.MaxPaymentPercent = -1 },
|
|
||||||
"min payment points 0": func(s *models.OutletLoyaltySettings) { s.PointPayment.MinPaymentPoints = 0 },
|
|
||||||
} {
|
} {
|
||||||
s, err := p.Outlet(ctx, outlet)
|
s, err := p.Outlet(ctx, outlet)
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
|
|||||||
@@ -0,0 +1,46 @@
|
|||||||
|
package processor
|
||||||
|
|
||||||
|
import (
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"apskel-pos-be/internal/entities"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
"github.com/stretchr/testify/assert"
|
||||||
|
"github.com/stretchr/testify/require"
|
||||||
|
)
|
||||||
|
|
||||||
|
// The items AddToOrder creates have no product loaded, so their responses used to go out
|
||||||
|
// without a name or a printer, and the POS could not print them.
|
||||||
|
func TestAddedItemsFromOrderUsesTheReloadedProduct(t *testing.T) {
|
||||||
|
outletID := uuid.New()
|
||||||
|
|
||||||
|
paket := entities.Product{ID: uuid.New(), Name: "Paket Makan Minum"}
|
||||||
|
paket.SetPrinterTypes([]string{"kitchen", "bar"})
|
||||||
|
paket.ProductOutletPrices = []entities.ProductOutletPrice{{OutletID: outletID, PrintToChecker: false}}
|
||||||
|
esTeh := entities.Product{ID: uuid.New(), Name: "Es Teh"}
|
||||||
|
esTeh.SetPrinterTypes([]string{"bar"})
|
||||||
|
|
||||||
|
existing := entities.OrderItem{ID: uuid.New(), ProductID: esTeh.ID, Product: esTeh}
|
||||||
|
addedPaket := &entities.OrderItem{ID: uuid.New(), ProductID: paket.ID}
|
||||||
|
addedEsTeh := &entities.OrderItem{ID: uuid.New(), ProductID: esTeh.ID}
|
||||||
|
|
||||||
|
order := &entities.Order{
|
||||||
|
OutletID: outletID,
|
||||||
|
OrderItems: []entities.OrderItem{
|
||||||
|
existing,
|
||||||
|
{ID: addedEsTeh.ID, ProductID: esTeh.ID, Product: esTeh},
|
||||||
|
{ID: addedPaket.ID, ProductID: paket.ID, Product: paket},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
responses := addedItemsFromOrder([]*entities.OrderItem{addedPaket, addedEsTeh}, order)
|
||||||
|
|
||||||
|
require.Len(t, responses, 2, "only the added items, not the ones already on the order")
|
||||||
|
assert.Equal(t, addedPaket.ID, responses[0].ID, "in the order they were requested")
|
||||||
|
assert.Equal(t, "Paket Makan Minum", responses[0].ProductName)
|
||||||
|
assert.Equal(t, []string{"kitchen", "bar"}, responses[0].PrinterTypes)
|
||||||
|
assert.False(t, responses[0].PrintToChecker, "the outlet's print_to_checker is loaded too")
|
||||||
|
assert.Equal(t, addedEsTeh.ID, responses[1].ID)
|
||||||
|
assert.Equal(t, []string{"bar"}, responses[1].PrinterTypes)
|
||||||
|
}
|
||||||
@@ -5,7 +5,6 @@ import (
|
|||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
|
||||||
"apskel-pos-be/internal/appcontext"
|
|
||||||
"apskel-pos-be/internal/constants"
|
"apskel-pos-be/internal/constants"
|
||||||
"apskel-pos-be/internal/entities"
|
"apskel-pos-be/internal/entities"
|
||||||
"apskel-pos-be/internal/logger"
|
"apskel-pos-be/internal/logger"
|
||||||
@@ -21,9 +20,6 @@ type OrderProcessor interface {
|
|||||||
CreateOrder(ctx context.Context, req *models.CreateOrderRequest, organizationID uuid.UUID) (*models.OrderResponse, error)
|
CreateOrder(ctx context.Context, req *models.CreateOrderRequest, organizationID uuid.UUID) (*models.OrderResponse, error)
|
||||||
AddToOrder(ctx context.Context, orderID uuid.UUID, req *models.AddToOrderRequest) (*models.AddToOrderResponse, error)
|
AddToOrder(ctx context.Context, orderID uuid.UUID, req *models.AddToOrderRequest) (*models.AddToOrderResponse, error)
|
||||||
UpdateOrder(ctx context.Context, id uuid.UUID, req *models.UpdateOrderRequest) (*models.OrderResponse, error)
|
UpdateOrder(ctx context.Context, id uuid.UUID, req *models.UpdateOrderRequest) (*models.OrderResponse, error)
|
||||||
// PayWithPointsInApp pays the customer's own order with EnakPoint from the app or a
|
|
||||||
// self-order, approved by their PIN (docs/prd-point-coin.md F9).
|
|
||||||
PayWithPointsInApp(ctx context.Context, customerID, orderID uuid.UUID, points int64, pin string, info models.CustomerPinRequestInfo) (*models.PaymentResponse, error)
|
|
||||||
GetOrderByID(ctx context.Context, id uuid.UUID) (*models.OrderResponse, error)
|
GetOrderByID(ctx context.Context, id uuid.UUID) (*models.OrderResponse, error)
|
||||||
ListOrders(ctx context.Context, req *models.ListOrdersRequest) (*models.ListOrdersResponse, error)
|
ListOrders(ctx context.Context, req *models.ListOrdersRequest) (*models.ListOrdersResponse, error)
|
||||||
VoidOrder(ctx context.Context, req *models.VoidOrderRequest, voidedBy uuid.UUID) error
|
VoidOrder(ctx context.Context, req *models.VoidOrderRequest, voidedBy uuid.UUID) error
|
||||||
@@ -115,9 +111,6 @@ type OrderProcessorImpl struct {
|
|||||||
inventoryMovementService InventoryMovementService
|
inventoryMovementService InventoryMovementService
|
||||||
productOutletPriceRepo repository.ProductOutletPriceRepository
|
productOutletPriceRepo repository.ProductOutletPriceRepository
|
||||||
loyalty OrderLoyalty
|
loyalty OrderLoyalty
|
||||||
pointPayments *PointPaymentProcessor
|
|
||||||
paymentCodes paymentCodeRedeemer
|
|
||||||
pins pinVerifier
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// OrderLoyalty is what the order flow tells and asks the loyalty program
|
// OrderLoyalty is what the order flow tells and asks the loyalty program
|
||||||
@@ -144,58 +137,6 @@ func (p *OrderProcessorImpl) SetLoyalty(loyalty OrderLoyalty) {
|
|||||||
p.loyalty = loyalty
|
p.loyalty = loyalty
|
||||||
}
|
}
|
||||||
|
|
||||||
type paymentCodeRedeemer interface {
|
|
||||||
Redeem(ctx context.Context, code string, customerID uuid.UUID) error
|
|
||||||
}
|
|
||||||
|
|
||||||
// SetPointPayments enables paying with the EnakPoint method. CreatePayment hands such
|
|
||||||
// payments to pointPayments approved by the code the customer shows at the cashier,
|
|
||||||
// and PayWithPointsInApp approved by the customer's PIN (F9).
|
|
||||||
func (p *OrderProcessorImpl) SetPointPayments(pointPayments *PointPaymentProcessor, codes paymentCodeRedeemer, pins pinVerifier) {
|
|
||||||
p.pointPayments = pointPayments
|
|
||||||
p.paymentCodes = codes
|
|
||||||
p.pins = pins
|
|
||||||
}
|
|
||||||
|
|
||||||
// createPointPayment is CreatePayment for the EnakPoint method. It never uses the
|
|
||||||
// generic payment path, which would record the payment without taking any balance.
|
|
||||||
func (p *OrderProcessorImpl) createPointPayment(ctx context.Context, req *models.CreatePaymentRequest) (*models.PaymentResponse, error) {
|
|
||||||
if p.pointPayments == nil || p.paymentCodes == nil {
|
|
||||||
return nil, fmt.Errorf("%w: paying with EnakPoint is not available", ErrPointPaymentRejected)
|
|
||||||
}
|
|
||||||
if req.Points == nil || req.PaymentCode == nil || *req.PaymentCode == "" {
|
|
||||||
return nil, fmt.Errorf("%w: points and the customer's payment code are required", ErrPointPaymentRejected)
|
|
||||||
}
|
|
||||||
var cashier *uuid.UUID
|
|
||||||
if id := appcontext.FromContext(ctx).UserID; id != uuid.Nil {
|
|
||||||
cashier = &id
|
|
||||||
}
|
|
||||||
code := *req.PaymentCode
|
|
||||||
result, err := p.pointPayments.Pay(ctx, PointPaymentInput{
|
|
||||||
OrderID: req.OrderID,
|
|
||||||
PaymentMethodID: req.PaymentMethodID,
|
|
||||||
Points: *req.Points,
|
|
||||||
CashierID: cashier,
|
|
||||||
Authorize: func(ctx context.Context, customerID uuid.UUID) error {
|
|
||||||
if err := p.paymentCodes.Redeem(ctx, code, customerID); err != nil {
|
|
||||||
return fmt.Errorf("%w: %v", ErrPointPaymentRejected, err)
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
},
|
|
||||||
})
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
if result.Completed {
|
|
||||||
p.onOrderPaid(ctx, req.OrderID)
|
|
||||||
}
|
|
||||||
payment, err := p.paymentRepo.GetByID(ctx, result.Payment.ID)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("failed to retrieve created payment: %w", err)
|
|
||||||
}
|
|
||||||
return mappers.PaymentEntityToResponse(payment), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// onOrderPaid is the single place every path that completes an order's payment goes
|
// onOrderPaid is the single place every path that completes an order's payment goes
|
||||||
// through: UpdateOrder, CreatePayment and both kinds of split bill. It must be called
|
// through: UpdateOrder, CreatePayment and both kinds of split bill. It must be called
|
||||||
// after the payment has committed. The hook runs detached from the caller's
|
// after the payment has committed. The hook runs detached from the caller's
|
||||||
@@ -213,12 +154,6 @@ func (p *OrderProcessorImpl) onOrderPaid(ctx context.Context, orderID uuid.UUID)
|
|||||||
// never block or fail the void or refund.
|
// never block or fail the void or refund.
|
||||||
func (p *OrderProcessorImpl) onOrderRefunded(ctx context.Context, orderID uuid.UUID) {
|
func (p *OrderProcessorImpl) onOrderRefunded(ctx context.Context, orderID uuid.UUID) {
|
||||||
ctx = repository.DetachTransaction(context.WithoutCancel(ctx))
|
ctx = repository.DetachTransaction(context.WithoutCancel(ctx))
|
||||||
// EnakPoint paid on the order comes back first: the customer is owed it (F9).
|
|
||||||
if p.pointPayments != nil {
|
|
||||||
if _, err := p.pointPayments.RefundForOrder(ctx, orderID); err != nil {
|
|
||||||
logger.FromContext(ctx).WithError(err).Error("OrderProcessorImpl::onOrderRefunded -> failed to return EnakPoint; calling it again is safe")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if p.loyalty != nil {
|
if p.loyalty != nil {
|
||||||
p.loyalty.OnOrderRefunded(ctx, orderID)
|
p.loyalty.OnOrderRefunded(ctx, orderID)
|
||||||
}
|
}
|
||||||
@@ -316,6 +251,18 @@ func resolveLineQuantity(product *entities.Product, quantity int, weight *float6
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (p *OrderProcessorImpl) CreateOrder(ctx context.Context, req *models.CreateOrderRequest, organizationID uuid.UUID) (*models.OrderResponse, error) {
|
func (p *OrderProcessorImpl) CreateOrder(ctx context.Context, req *models.CreateOrderRequest, organizationID uuid.UUID) (*models.OrderResponse, error) {
|
||||||
|
// The order's customer earns EnakPoint and EnakCoin once it is paid, so it must be
|
||||||
|
// one of the organization's own; orders.customer_id has no foreign key to catch it.
|
||||||
|
customerID := req.CustomerID
|
||||||
|
if customerID != nil && *customerID == uuid.Nil {
|
||||||
|
customerID = nil
|
||||||
|
}
|
||||||
|
if customerID != nil {
|
||||||
|
if _, err := p.customerRepo.GetByIDAndOrganization(ctx, *customerID, organizationID); err != nil {
|
||||||
|
return nil, fmt.Errorf("customer not found or does not belong to the organization: %w", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
orderNumber, err := p.orderRepo.GetNextOrderNumber(ctx, organizationID, req.OutletID)
|
orderNumber, err := p.orderRepo.GetNextOrderNumber(ctx, organizationID, req.OutletID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("failed to generate order number: %w", err)
|
return nil, fmt.Errorf("failed to generate order number: %w", err)
|
||||||
@@ -401,7 +348,7 @@ func (p *OrderProcessorImpl) CreateOrder(ctx context.Context, req *models.Create
|
|||||||
OrganizationID: organizationID,
|
OrganizationID: organizationID,
|
||||||
OutletID: req.OutletID,
|
OutletID: req.OutletID,
|
||||||
UserID: req.UserID,
|
UserID: req.UserID,
|
||||||
CustomerID: req.CustomerID,
|
CustomerID: customerID,
|
||||||
OrderNumber: orderNumber,
|
OrderNumber: orderNumber,
|
||||||
TableNumber: req.TableNumber,
|
TableNumber: req.TableNumber,
|
||||||
OrderType: entities.OrderType(req.OrderType),
|
OrderType: entities.OrderType(req.OrderType),
|
||||||
@@ -556,16 +503,10 @@ func (p *OrderProcessorImpl) AddToOrder(ctx context.Context, orderID uuid.UUID,
|
|||||||
return nil, fmt.Errorf("failed to update order: %w", err)
|
return nil, fmt.Errorf("failed to update order: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
var addedItemResponses []models.OrderItemResponse
|
|
||||||
for _, orderItem := range addedOrderItems {
|
for _, orderItem := range addedOrderItems {
|
||||||
if err := p.orderItemRepo.Create(ctx, orderItem); err != nil {
|
if err := p.orderItemRepo.Create(ctx, orderItem); err != nil {
|
||||||
return nil, fmt.Errorf("failed to create order item: %w", err)
|
return nil, fmt.Errorf("failed to create order item: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
itemResponse := mappers.OrderItemEntityToResponse(orderItem, order.OutletID)
|
|
||||||
if itemResponse != nil {
|
|
||||||
addedItemResponses = append(addedItemResponses, *itemResponse)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
orderWithRelations, err := p.orderRepo.GetWithRelations(ctx, orderID)
|
orderWithRelations, err := p.orderRepo.GetWithRelations(ctx, orderID)
|
||||||
@@ -573,6 +514,10 @@ func (p *OrderProcessorImpl) AddToOrder(ctx context.Context, orderID uuid.UUID,
|
|||||||
return nil, fmt.Errorf("failed to retrieve updated order: %w", err)
|
return nil, fmt.Errorf("failed to retrieve updated order: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// The items just created carry no product, so take them from the reloaded order: the
|
||||||
|
// POS prints added items from this response and needs their name and printers.
|
||||||
|
addedItemResponses := addedItemsFromOrder(addedOrderItems, orderWithRelations)
|
||||||
|
|
||||||
updatedOrderResponse := mappers.OrderEntityToResponse(orderWithRelations)
|
updatedOrderResponse := mappers.OrderEntityToResponse(orderWithRelations)
|
||||||
p.attachEarnings(ctx, updatedOrderResponse)
|
p.attachEarnings(ctx, updatedOrderResponse)
|
||||||
|
|
||||||
@@ -584,6 +529,26 @@ func (p *OrderProcessorImpl) AddToOrder(ctx context.Context, orderID uuid.UUID,
|
|||||||
}, nil
|
}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// addedItemsFromOrder maps the added items in the order they were requested, using their
|
||||||
|
// copies in the reloaded order, which have the product and its outlet prices loaded.
|
||||||
|
func addedItemsFromOrder(added []*entities.OrderItem, order *entities.Order) []models.OrderItemResponse {
|
||||||
|
reloaded := make(map[uuid.UUID]*entities.OrderItem, len(order.OrderItems))
|
||||||
|
for i := range order.OrderItems {
|
||||||
|
reloaded[order.OrderItems[i].ID] = &order.OrderItems[i]
|
||||||
|
}
|
||||||
|
|
||||||
|
var responses []models.OrderItemResponse
|
||||||
|
for _, item := range added {
|
||||||
|
if loaded, ok := reloaded[item.ID]; ok {
|
||||||
|
item = loaded
|
||||||
|
}
|
||||||
|
if response := mappers.OrderItemEntityToResponse(item, order.OutletID); response != nil {
|
||||||
|
responses = append(responses, *response)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return responses
|
||||||
|
}
|
||||||
|
|
||||||
func (p *OrderProcessorImpl) UpdateOrder(ctx context.Context, id uuid.UUID, req *models.UpdateOrderRequest) (*models.OrderResponse, error) {
|
func (p *OrderProcessorImpl) UpdateOrder(ctx context.Context, id uuid.UUID, req *models.UpdateOrderRequest) (*models.OrderResponse, error) {
|
||||||
// Get existing order
|
// Get existing order
|
||||||
order, err := p.orderRepo.GetByID(ctx, id)
|
order, err := p.orderRepo.GetByID(ctx, id)
|
||||||
@@ -866,18 +831,6 @@ func (p *OrderProcessorImpl) RefundOrder(ctx context.Context, id uuid.UUID, req
|
|||||||
reason = *req.Reason
|
reason = *req.Reason
|
||||||
}
|
}
|
||||||
|
|
||||||
// An order refund is handed back in cash or another method, so it cannot cover what
|
|
||||||
// was paid with EnakPoint (K7). Checked before anything is written.
|
|
||||||
if p.pointPayments != nil {
|
|
||||||
planned, err := p.plannedOrderRefund(ctx, id, req)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
if err := p.pointPayments.EnsureOrderRefundAllowed(ctx, id, planned); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Process refund based on request type
|
// Process refund based on request type
|
||||||
if req.RefundAmount != nil {
|
if req.RefundAmount != nil {
|
||||||
// Full or partial refund by amount
|
// Full or partial refund by amount
|
||||||
@@ -969,13 +922,10 @@ func (p *OrderProcessorImpl) CreatePayment(ctx context.Context, req *models.Crea
|
|||||||
return nil, fmt.Errorf("order is already fully paid")
|
return nil, fmt.Errorf("order is already fully paid")
|
||||||
}
|
}
|
||||||
|
|
||||||
method, err := p.paymentMethodRepo.GetByID(ctx, req.PaymentMethodID)
|
_, err = p.paymentMethodRepo.GetByID(ctx, req.PaymentMethodID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("payment method not found: %w", err)
|
return nil, fmt.Errorf("payment method not found: %w", err)
|
||||||
}
|
}
|
||||||
if method.Type == entities.PaymentMethodTypePoint {
|
|
||||||
return p.createPointPayment(ctx, req)
|
|
||||||
}
|
|
||||||
|
|
||||||
totalPaid, err := p.paymentRepo.GetTotalPaidByOrderID(ctx, req.OrderID)
|
totalPaid, err := p.paymentRepo.GetTotalPaidByOrderID(ctx, req.OrderID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -1360,11 +1310,6 @@ func (p *OrderProcessorImpl) SplitBill(ctx context.Context, req *models.SplitBil
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("payment method not found: %w", err)
|
return nil, fmt.Errorf("payment method not found: %w", err)
|
||||||
}
|
}
|
||||||
// Splitting with EnakPoint would record a payment without taking any balance; an
|
|
||||||
// EnakPoint part goes through CreatePayment and the rest is split as usual (F9).
|
|
||||||
if payment.Type == entities.PaymentMethodTypePoint {
|
|
||||||
return nil, fmt.Errorf("%w: pay the EnakPoint part as its own payment, not as a split", ErrPointPaymentRejected)
|
|
||||||
}
|
|
||||||
|
|
||||||
customer := &entities.Customer{}
|
customer := &entities.Customer{}
|
||||||
if req.CustomerID != uuid.Nil {
|
if req.CustomerID != uuid.Nil {
|
||||||
@@ -1811,71 +1756,3 @@ func (p *OrderProcessorImpl) prepareRefundedIngredientRecipeItem(ctx context.Con
|
|||||||
func stringPtr(s string) *string {
|
func stringPtr(s string) *string {
|
||||||
return &s
|
return &s
|
||||||
}
|
}
|
||||||
|
|
||||||
// PayWithPointsInApp pays an order with EnakPoint on the customer's own request, in the
|
|
||||||
// app or a self-order. The session alone is not enough: the customer's PIN approves
|
|
||||||
// it (K8). An order that is not the customer's own is reported as not found, so the
|
|
||||||
// endpoint does not reveal other customers' orders.
|
|
||||||
func (p *OrderProcessorImpl) PayWithPointsInApp(ctx context.Context, customerID, orderID uuid.UUID, points int64, pin string, info models.CustomerPinRequestInfo) (*models.PaymentResponse, error) {
|
|
||||||
if p.pointPayments == nil || p.pins == nil {
|
|
||||||
return nil, fmt.Errorf("%w: paying with EnakPoint is not available", ErrPointPaymentRejected)
|
|
||||||
}
|
|
||||||
organizationID, owner, err := p.pointPayments.OrderOwner(ctx, orderID)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
if owner == nil || *owner != customerID {
|
|
||||||
return nil, repository.ErrPointPaymentOrderNotFound
|
|
||||||
}
|
|
||||||
methodID, err := p.pointPayments.PointMethodID(ctx, organizationID)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
result, err := p.pointPayments.Pay(ctx, PointPaymentInput{
|
|
||||||
OrderID: orderID,
|
|
||||||
PaymentMethodID: methodID,
|
|
||||||
Points: points,
|
|
||||||
Authorize: func(ctx context.Context, customerID uuid.UUID) error {
|
|
||||||
return p.pins.VerifyPin(ctx, customerID, pin, PinActionPay, info)
|
|
||||||
},
|
|
||||||
})
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
if result.Completed {
|
|
||||||
p.onOrderPaid(ctx, orderID)
|
|
||||||
}
|
|
||||||
payment, err := p.paymentRepo.GetByID(ctx, result.Payment.ID)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("failed to retrieve created payment: %w", err)
|
|
||||||
}
|
|
||||||
return mappers.PaymentEntityToResponse(payment), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// plannedOrderRefund is the total RefundOrder is about to hand back, computed the same
|
|
||||||
// way it will be, without writing anything.
|
|
||||||
func (p *OrderProcessorImpl) plannedOrderRefund(ctx context.Context, orderID uuid.UUID, req *models.RefundOrderRequest) (float64, error) {
|
|
||||||
if req.RefundAmount != nil {
|
|
||||||
return *req.RefundAmount, nil
|
|
||||||
}
|
|
||||||
var total float64
|
|
||||||
for _, itemRefund := range req.OrderItems {
|
|
||||||
if itemRefund.RefundAmount != nil {
|
|
||||||
total += *itemRefund.RefundAmount
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
orderItem, err := p.orderItemRepo.GetByID(ctx, itemRefund.OrderItemID)
|
|
||||||
if err != nil {
|
|
||||||
return 0, fmt.Errorf("order item not found: %w", err)
|
|
||||||
}
|
|
||||||
if orderItem.OrderID != orderID {
|
|
||||||
return 0, fmt.Errorf("order item does not belong to this order")
|
|
||||||
}
|
|
||||||
quantity := itemRefund.RefundQuantity
|
|
||||||
if quantity == 0 {
|
|
||||||
quantity = orderItem.Quantity
|
|
||||||
}
|
|
||||||
total += entities.RoundMoney(orderItem.BillableQuantityFor(quantity) * orderItem.UnitPrice)
|
|
||||||
}
|
|
||||||
return total, nil
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -1,101 +0,0 @@
|
|||||||
package processor
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"crypto/rand"
|
|
||||||
"errors"
|
|
||||||
"fmt"
|
|
||||||
"math/big"
|
|
||||||
"strings"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/google/uuid"
|
|
||||||
|
|
||||||
"apskel-pos-be/internal/models"
|
|
||||||
"apskel-pos-be/internal/repository"
|
|
||||||
)
|
|
||||||
|
|
||||||
const (
|
|
||||||
paymentCodeDigits = 6
|
|
||||||
paymentCodeTTL = 2 * time.Minute
|
|
||||||
paymentCodeAttempts = 5
|
|
||||||
// PaymentCodeQRPrefix marks a scanned QR as an EnakPoint payment code.
|
|
||||||
PaymentCodeQRPrefix = "enakpoint:"
|
|
||||||
)
|
|
||||||
|
|
||||||
// ErrPaymentCodeInvalid means the code was never issued, has expired, has been used,
|
|
||||||
// or belongs to another customer.
|
|
||||||
var ErrPaymentCodeInvalid = errors.New("payment code is invalid or expired")
|
|
||||||
|
|
||||||
type pinVerifier interface {
|
|
||||||
VerifyPin(ctx context.Context, customerID uuid.UUID, pin string, action PinAction, info models.CustomerPinRequestInfo) error
|
|
||||||
}
|
|
||||||
|
|
||||||
// PaymentCodeProcessor issues and redeems the one-time codes that let a cashier take a
|
|
||||||
// customer's EnakPoint (docs/prd-point-coin.md F9, K8). The customer approves with
|
|
||||||
// their PIN on their own phone and shows the code; the PIN is never typed on the
|
|
||||||
// cashier's device.
|
|
||||||
type PaymentCodeProcessor struct {
|
|
||||||
codes repository.PaymentCodeRepository
|
|
||||||
pins pinVerifier
|
|
||||||
now func() time.Time
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewPaymentCodeProcessor(codes repository.PaymentCodeRepository, pins pinVerifier) *PaymentCodeProcessor {
|
|
||||||
return &PaymentCodeProcessor{codes: codes, pins: pins, now: time.Now}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Issue checks the customer's PIN and returns a fresh 6-digit code, valid for two
|
|
||||||
// minutes and bound to the customer. A new code retires the previous one.
|
|
||||||
func (p *PaymentCodeProcessor) Issue(ctx context.Context, customerID uuid.UUID, pin string, info models.CustomerPinRequestInfo) (*models.PaymentCode, error) {
|
|
||||||
if err := p.pins.VerifyPin(ctx, customerID, pin, PinActionPay, info); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
for attempt := 0; attempt < paymentCodeAttempts; attempt++ {
|
|
||||||
code, err := randomDigits(paymentCodeDigits)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
err = p.codes.Save(ctx, code, customerID, paymentCodeTTL)
|
|
||||||
if errors.Is(err, repository.ErrPaymentCodeTaken) {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
return &models.PaymentCode{
|
|
||||||
Code: code,
|
|
||||||
QRPayload: PaymentCodeQRPrefix + code,
|
|
||||||
ExpiresAt: p.now().Add(paymentCodeTTL),
|
|
||||||
}, nil
|
|
||||||
}
|
|
||||||
return nil, fmt.Errorf("could not draw a free payment code after %d attempts", paymentCodeAttempts)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Redeem uses a code up for a payment by the given customer. It accepts the code as
|
|
||||||
// typed or as scanned from the QR. Every failure is ErrPaymentCodeInvalid.
|
|
||||||
func (p *PaymentCodeProcessor) Redeem(ctx context.Context, code string, customerID uuid.UUID) error {
|
|
||||||
code = strings.TrimPrefix(strings.TrimSpace(code), PaymentCodeQRPrefix)
|
|
||||||
if len(code) != paymentCodeDigits {
|
|
||||||
return ErrPaymentCodeInvalid
|
|
||||||
}
|
|
||||||
err := p.codes.Consume(ctx, code, customerID)
|
|
||||||
if errors.Is(err, repository.ErrPaymentCodeNotFound) || errors.Is(err, repository.ErrPaymentCodeWrongCustomer) {
|
|
||||||
return ErrPaymentCodeInvalid
|
|
||||||
}
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
// randomDigits draws n decimal digits from a cryptographic source, so codes cannot be
|
|
||||||
// predicted.
|
|
||||||
func randomDigits(n int) (string, error) {
|
|
||||||
var b strings.Builder
|
|
||||||
for i := 0; i < n; i++ {
|
|
||||||
d, err := rand.Int(rand.Reader, big.NewInt(10))
|
|
||||||
if err != nil {
|
|
||||||
return "", fmt.Errorf("failed to draw a payment code: %w", err)
|
|
||||||
}
|
|
||||||
b.WriteByte(byte('0' + d.Int64()))
|
|
||||||
}
|
|
||||||
return b.String(), nil
|
|
||||||
}
|
|
||||||
@@ -1,136 +0,0 @@
|
|||||||
package processor
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"sync"
|
|
||||||
"sync/atomic"
|
|
||||||
"testing"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/alicebob/miniredis/v2"
|
|
||||||
"github.com/google/uuid"
|
|
||||||
"github.com/redis/go-redis/v9"
|
|
||||||
"github.com/stretchr/testify/assert"
|
|
||||||
"github.com/stretchr/testify/require"
|
|
||||||
|
|
||||||
"apskel-pos-be/internal/models"
|
|
||||||
"apskel-pos-be/internal/repository"
|
|
||||||
)
|
|
||||||
|
|
||||||
type pinVerifierFake struct{ good string }
|
|
||||||
|
|
||||||
func (f pinVerifierFake) VerifyPin(_ context.Context, _ uuid.UUID, pin string, action PinAction, _ models.CustomerPinRequestInfo) error {
|
|
||||||
if action != PinActionPay {
|
|
||||||
return &PinError{Code: "UNEXPECTED_ACTION"}
|
|
||||||
}
|
|
||||||
if pin != f.good {
|
|
||||||
return &PinError{Code: PinErrInvalid, RemainingAttempts: 4}
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func newPaymentCodeTest(t *testing.T) (*PaymentCodeProcessor, *miniredis.Miniredis) {
|
|
||||||
t.Helper()
|
|
||||||
mr := miniredis.RunT(t)
|
|
||||||
client := redis.NewClient(&redis.Options{Addr: mr.Addr()})
|
|
||||||
t.Cleanup(func() { client.Close() })
|
|
||||||
return NewPaymentCodeProcessor(repository.NewPaymentCodeRepository(client), pinVerifierFake{good: "482913"}), mr
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestPaymentCode_IssueNeedsThePin(t *testing.T) {
|
|
||||||
p, mr := newPaymentCodeTest(t)
|
|
||||||
_, err := p.Issue(context.Background(), uuid.New(), "000000", models.CustomerPinRequestInfo{})
|
|
||||||
var pe *PinError
|
|
||||||
require.ErrorAs(t, err, &pe)
|
|
||||||
assert.Equal(t, PinErrInvalid, pe.Code)
|
|
||||||
assert.Empty(t, mr.Keys(), "nothing is issued without the PIN")
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestPaymentCode_Lifecycle(t *testing.T) {
|
|
||||||
p, mr := newPaymentCodeTest(t)
|
|
||||||
ctx := context.Background()
|
|
||||||
customer, other := uuid.New(), uuid.New()
|
|
||||||
|
|
||||||
code, err := p.Issue(ctx, customer, "482913", models.CustomerPinRequestInfo{})
|
|
||||||
require.NoError(t, err)
|
|
||||||
assert.Len(t, code.Code, 6)
|
|
||||||
assert.Equal(t, "enakpoint:"+code.Code, code.QRPayload)
|
|
||||||
assert.WithinDuration(t, time.Now().Add(2*time.Minute), code.ExpiresAt, 2*time.Second)
|
|
||||||
assert.InDelta(t, 120, mr.TTL("wallet:paycode:"+code.Code).Seconds(), 1, "Redis expires it by itself")
|
|
||||||
|
|
||||||
// A code of another customer is refused, and stays usable by its owner.
|
|
||||||
assert.ErrorIs(t, p.Redeem(ctx, code.Code, other), ErrPaymentCodeInvalid)
|
|
||||||
// Scanned from the QR it works; used once, it is gone.
|
|
||||||
require.NoError(t, p.Redeem(ctx, code.QRPayload, customer))
|
|
||||||
assert.ErrorIs(t, p.Redeem(ctx, code.Code, customer), ErrPaymentCodeInvalid)
|
|
||||||
|
|
||||||
// An expired code is refused.
|
|
||||||
late, err := p.Issue(ctx, customer, "482913", models.CustomerPinRequestInfo{})
|
|
||||||
require.NoError(t, err)
|
|
||||||
mr.FastForward(2*time.Minute + time.Second)
|
|
||||||
assert.ErrorIs(t, p.Redeem(ctx, late.Code, customer), ErrPaymentCodeInvalid)
|
|
||||||
|
|
||||||
// A new code retires the previous one.
|
|
||||||
first, err := p.Issue(ctx, customer, "482913", models.CustomerPinRequestInfo{})
|
|
||||||
require.NoError(t, err)
|
|
||||||
second, err := p.Issue(ctx, customer, "482913", models.CustomerPinRequestInfo{})
|
|
||||||
require.NoError(t, err)
|
|
||||||
if first.Code != second.Code {
|
|
||||||
assert.ErrorIs(t, p.Redeem(ctx, first.Code, customer), ErrPaymentCodeInvalid)
|
|
||||||
}
|
|
||||||
require.NoError(t, p.Redeem(ctx, second.Code, customer))
|
|
||||||
|
|
||||||
// Garbage is refused without touching Redis.
|
|
||||||
for _, bad := range []string{"", "12345", "1234567", "enakpoint:"} {
|
|
||||||
assert.ErrorIs(t, p.Redeem(ctx, bad, customer), ErrPaymentCodeInvalid, bad)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Two cashiers scanning the same code at once: exactly one gets it.
|
|
||||||
func TestPaymentCode_UsedOnceUnderRace(t *testing.T) {
|
|
||||||
p, _ := newPaymentCodeTest(t)
|
|
||||||
ctx := context.Background()
|
|
||||||
customer := uuid.New()
|
|
||||||
code, err := p.Issue(ctx, customer, "482913", models.CustomerPinRequestInfo{})
|
|
||||||
require.NoError(t, err)
|
|
||||||
|
|
||||||
var wins int32
|
|
||||||
var wg sync.WaitGroup
|
|
||||||
for i := 0; i < 20; i++ {
|
|
||||||
wg.Add(1)
|
|
||||||
go func() {
|
|
||||||
defer wg.Done()
|
|
||||||
if p.Redeem(ctx, code.Code, customer) == nil {
|
|
||||||
atomic.AddInt32(&wins, 1)
|
|
||||||
}
|
|
||||||
}()
|
|
||||||
}
|
|
||||||
wg.Wait()
|
|
||||||
assert.Equal(t, int32(1), wins)
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestPaymentCode_SaveRefusesALiveCode(t *testing.T) {
|
|
||||||
mr := miniredis.RunT(t)
|
|
||||||
client := redis.NewClient(&redis.Options{Addr: mr.Addr()})
|
|
||||||
defer client.Close()
|
|
||||||
repo := repository.NewPaymentCodeRepository(client)
|
|
||||||
ctx := context.Background()
|
|
||||||
|
|
||||||
require.NoError(t, repo.Save(ctx, "123456", uuid.New(), time.Minute))
|
|
||||||
assert.ErrorIs(t, repo.Save(ctx, "123456", uuid.New(), time.Minute), repository.ErrPaymentCodeTaken,
|
|
||||||
"a live code is never handed to a second customer")
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestRandomDigits(t *testing.T) {
|
|
||||||
seen := map[string]bool{}
|
|
||||||
for i := 0; i < 200; i++ {
|
|
||||||
d, err := randomDigits(6)
|
|
||||||
require.NoError(t, err)
|
|
||||||
require.Len(t, d, 6)
|
|
||||||
for _, r := range d {
|
|
||||||
require.True(t, r >= '0' && r <= '9')
|
|
||||||
}
|
|
||||||
seen[d] = true
|
|
||||||
}
|
|
||||||
assert.Greater(t, len(seen), 190, "codes do not repeat")
|
|
||||||
}
|
|
||||||
@@ -1,10 +1,7 @@
|
|||||||
package processor
|
package processor
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"apskel-pos-be/internal/constants"
|
|
||||||
"apskel-pos-be/internal/entities"
|
|
||||||
"context"
|
"context"
|
||||||
"errors"
|
|
||||||
"fmt"
|
"fmt"
|
||||||
|
|
||||||
"apskel-pos-be/internal/mappers"
|
"apskel-pos-be/internal/mappers"
|
||||||
@@ -23,26 +20,17 @@ type PaymentMethodProcessor interface {
|
|||||||
GetActivePaymentMethodsByOrganization(ctx context.Context, organizationID uuid.UUID) ([]models.PaymentMethodResponse, error)
|
GetActivePaymentMethodsByOrganization(ctx context.Context, organizationID uuid.UUID) ([]models.PaymentMethodResponse, error)
|
||||||
}
|
}
|
||||||
|
|
||||||
// ErrSystemPaymentMethod means an attempt to create, delete or retype the EnakPoint
|
|
||||||
// method, which the system owns (docs/prd-point-coin.md F9).
|
|
||||||
var ErrSystemPaymentMethod = errors.New("the EnakPoint payment method is managed by the system: it cannot be created, deleted or change type")
|
|
||||||
|
|
||||||
type PaymentMethodProcessorImpl struct {
|
type PaymentMethodProcessorImpl struct {
|
||||||
paymentMethodRepo repository.PaymentMethodRepository
|
paymentMethodRepo repository.PaymentMethodRepository
|
||||||
outletSettings outletSettingsReader
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewPaymentMethodProcessorImpl(paymentMethodRepo repository.PaymentMethodRepository, outletSettings outletSettingsReader) *PaymentMethodProcessorImpl {
|
func NewPaymentMethodProcessorImpl(paymentMethodRepo repository.PaymentMethodRepository) *PaymentMethodProcessorImpl {
|
||||||
return &PaymentMethodProcessorImpl{
|
return &PaymentMethodProcessorImpl{
|
||||||
paymentMethodRepo: paymentMethodRepo,
|
paymentMethodRepo: paymentMethodRepo,
|
||||||
outletSettings: outletSettings,
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (p *PaymentMethodProcessorImpl) CreatePaymentMethod(ctx context.Context, req *models.CreatePaymentMethodRequest) (*models.PaymentMethodResponse, error) {
|
func (p *PaymentMethodProcessorImpl) CreatePaymentMethod(ctx context.Context, req *models.CreatePaymentMethodRequest) (*models.PaymentMethodResponse, error) {
|
||||||
if req.Type == constants.PaymentMethodTypePoint {
|
|
||||||
return nil, ErrSystemPaymentMethod
|
|
||||||
}
|
|
||||||
exists, err := p.paymentMethodRepo.ExistsByName(ctx, req.OrganizationID, req.Name, nil)
|
exists, err := p.paymentMethodRepo.ExistsByName(ctx, req.OrganizationID, req.Name, nil)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("failed to check payment method name uniqueness: %w", err)
|
return nil, fmt.Errorf("failed to check payment method name uniqueness: %w", err)
|
||||||
@@ -89,17 +77,6 @@ func (p *PaymentMethodProcessorImpl) ListPaymentMethods(ctx context.Context, req
|
|||||||
if req.Search != "" {
|
if req.Search != "" {
|
||||||
filters["search"] = req.Search
|
filters["search"] = req.Search
|
||||||
}
|
}
|
||||||
// At the cashier EnakPoint only shows where the outlet accepts it (F9). Filtered in
|
|
||||||
// the query so paging stays right.
|
|
||||||
if req.OutletID != nil && p.outletSettings != nil {
|
|
||||||
settings, err := p.outletSettings.Outlet(ctx, *req.OutletID)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("failed to read outlet loyalty settings: %w", err)
|
|
||||||
}
|
|
||||||
if !settings.PointPayment.AcceptPayment {
|
|
||||||
filters["exclude_type"] = string(constants.PaymentMethodTypePoint)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
offset := (req.Page - 1) * req.Limit
|
offset := (req.Page - 1) * req.Limit
|
||||||
|
|
||||||
@@ -139,15 +116,6 @@ func (p *PaymentMethodProcessorImpl) UpdatePaymentMethod(ctx context.Context, id
|
|||||||
return nil, fmt.Errorf("payment method not found: %w", err)
|
return nil, fmt.Errorf("payment method not found: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
// The EnakPoint method keeps its type, and no other method can become one.
|
|
||||||
if req.Type != nil {
|
|
||||||
wasPoint := existingPaymentMethod.Type == entities.PaymentMethodTypePoint
|
|
||||||
isPoint := *req.Type == constants.PaymentMethodTypePoint
|
|
||||||
if wasPoint != isPoint {
|
|
||||||
return nil, ErrSystemPaymentMethod
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Check name uniqueness if name is being updated
|
// Check name uniqueness if name is being updated
|
||||||
if req.Name != nil && *req.Name != existingPaymentMethod.Name {
|
if req.Name != nil && *req.Name != existingPaymentMethod.Name {
|
||||||
exists, err := p.paymentMethodRepo.ExistsByName(ctx, existingPaymentMethod.OrganizationID, *req.Name, &id)
|
exists, err := p.paymentMethodRepo.ExistsByName(ctx, existingPaymentMethod.OrganizationID, *req.Name, &id)
|
||||||
@@ -179,13 +147,10 @@ func (p *PaymentMethodProcessorImpl) UpdatePaymentMethod(ctx context.Context, id
|
|||||||
|
|
||||||
func (p *PaymentMethodProcessorImpl) DeletePaymentMethod(ctx context.Context, id uuid.UUID) error {
|
func (p *PaymentMethodProcessorImpl) DeletePaymentMethod(ctx context.Context, id uuid.UUID) error {
|
||||||
// Check if payment method exists
|
// Check if payment method exists
|
||||||
existing, err := p.paymentMethodRepo.GetByID(ctx, id)
|
_, err := p.paymentMethodRepo.GetByID(ctx, id)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("payment method not found: %w", err)
|
return fmt.Errorf("payment method not found: %w", err)
|
||||||
}
|
}
|
||||||
if existing.Type == entities.PaymentMethodTypePoint {
|
|
||||||
return ErrSystemPaymentMethod
|
|
||||||
}
|
|
||||||
|
|
||||||
// TODO: Check if payment method is being used in any payments
|
// TODO: Check if payment method is being used in any payments
|
||||||
// For now, allow deletion
|
// For now, allow deletion
|
||||||
|
|||||||
@@ -1,401 +0,0 @@
|
|||||||
package processor
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"os"
|
|
||||||
"sync"
|
|
||||||
"testing"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/alicebob/miniredis/v2"
|
|
||||||
"github.com/google/uuid"
|
|
||||||
"github.com/redis/go-redis/v9"
|
|
||||||
"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/appcontext"
|
|
||||||
"apskel-pos-be/internal/constants"
|
|
||||||
"apskel-pos-be/internal/models"
|
|
||||||
"apskel-pos-be/internal/repository"
|
|
||||||
)
|
|
||||||
|
|
||||||
// pointPaymentEnv is an order flow wired as in the app, against Postgres and a
|
|
||||||
// miniredis for payment codes.
|
|
||||||
type pointPaymentEnv struct {
|
|
||||||
t *testing.T
|
|
||||||
db *gorm.DB
|
|
||||||
orders *OrderProcessorImpl
|
|
||||||
payments *PointPaymentProcessor
|
|
||||||
codes *PaymentCodeProcessor
|
|
||||||
org uuid.UUID
|
|
||||||
cashier uuid.UUID
|
|
||||||
outlet uuid.UUID
|
|
||||||
point uuid.UUID
|
|
||||||
cash uuid.UUID
|
|
||||||
walkIn uuid.UUID
|
|
||||||
ctx context.Context
|
|
||||||
}
|
|
||||||
|
|
||||||
func newPointPaymentEnv(t *testing.T) *pointPaymentEnv {
|
|
||||||
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 := &pointPaymentEnv{t: t, db: db, org: uuid.New(), cashier: uuid.New(), outlet: uuid.New(), cash: uuid.New()}
|
|
||||||
e.exec(`INSERT INTO organizations (id, name, plan_type) VALUES (?, 'point pay test', 'basic')`, e.org)
|
|
||||||
e.exec(`INSERT INTO users (id, organization_id, name, email, password_hash, role) VALUES (?, ?, 'Kasir', ?, 'x', 'cashier')`, e.cashier, e.org, e.cashier.String()+"@t")
|
|
||||||
e.exec(`INSERT INTO outlets (id, organization_id, name) VALUES (?, ?, 'Kemang')`, e.outlet, e.org)
|
|
||||||
e.exec(`INSERT INTO payment_methods (id, organization_id, name, type) VALUES (?, ?, 'Tunai', 'cash')`, e.cash, e.org)
|
|
||||||
var ids []string
|
|
||||||
require.NoError(t, db.Raw(`SELECT id::text FROM payment_methods WHERE organization_id = ? AND type = 'point'`, e.org).Scan(&ids).Error)
|
|
||||||
require.Len(t, ids, 1)
|
|
||||||
e.point = uuid.MustParse(ids[0])
|
|
||||||
require.NoError(t, db.Raw(`SELECT id::text FROM customers WHERE organization_id = ? AND is_default`, e.org).Scan(&ids).Error)
|
|
||||||
e.walkIn = uuid.MustParse(ids[0])
|
|
||||||
t.Cleanup(func() {
|
|
||||||
db.Exec(`DELETE FROM wallet_lot_allocations WHERE lot_id IN (SELECT id FROM wallet_lots WHERE organization_id = ?)`, e.org)
|
|
||||||
db.Exec(`DELETE FROM wallet_lots WHERE organization_id = ?`, e.org)
|
|
||||||
db.Exec(`DELETE FROM wallet_transactions WHERE organization_id = ?`, e.org)
|
|
||||||
db.Exec(`DELETE FROM customer_wallets WHERE organization_id = ?`, e.org)
|
|
||||||
db.Exec(`DELETE FROM payments WHERE order_id IN (SELECT id FROM orders WHERE organization_id = ?)`, e.org)
|
|
||||||
db.Exec(`DELETE FROM orders WHERE organization_id = ?`, e.org)
|
|
||||||
db.Exec(`DELETE FROM loyalty_setting_changes WHERE organization_id = ?`, e.org)
|
|
||||||
db.Exec(`DELETE FROM outlet_settings WHERE outlet_id = ?`, e.outlet)
|
|
||||||
db.Exec(`DELETE FROM payment_methods WHERE organization_id = ?`, e.org)
|
|
||||||
db.Exec(`DELETE FROM customers WHERE organization_id = ?`, e.org)
|
|
||||||
db.Exec(`DELETE FROM outlets WHERE id = ?`, e.outlet)
|
|
||||||
db.Exec(`DELETE FROM users WHERE id = ?`, e.cashier)
|
|
||||||
db.Exec(`DELETE FROM organizations WHERE id = ?`, e.org)
|
|
||||||
})
|
|
||||||
|
|
||||||
txm := repository.NewTxManager(db)
|
|
||||||
settings := NewLoyaltySettingsProcessor(repository.NewLoyaltySettingsRepository(db), txm)
|
|
||||||
wallet := NewWalletProcessor(repository.NewWalletRepository(db))
|
|
||||||
e.payments = NewPointPaymentProcessor(repository.NewPointPaymentRepository(db), settings, repository.NewWalletQueryRepository(db), wallet, txm)
|
|
||||||
mr := miniredis.RunT(t)
|
|
||||||
client := redis.NewClient(&redis.Options{Addr: mr.Addr()})
|
|
||||||
t.Cleanup(func() { client.Close() })
|
|
||||||
e.codes = NewPaymentCodeProcessor(repository.NewPaymentCodeRepository(client), pinVerifierFake{good: "482913"})
|
|
||||||
|
|
||||||
e.orders = &OrderProcessorImpl{
|
|
||||||
orderRepo: repository.NewOrderRepositoryImpl(db),
|
|
||||||
orderItemRepo: repository.NewOrderItemRepositoryImpl(db),
|
|
||||||
paymentRepo: repository.NewPaymentRepositoryImpl(db),
|
|
||||||
paymentMethodRepo: repository.NewPaymentMethodRepositoryImpl(db),
|
|
||||||
splitBillProcessor: nil,
|
|
||||||
txManager: txm,
|
|
||||||
}
|
|
||||||
e.orders.SetLoyalty(NewEarningProcessor(repository.NewEarningRepository(db), settings, wallet, txm))
|
|
||||||
e.orders.SetPointPayments(e.payments, e.codes, pinVerifierFake{good: "482913"})
|
|
||||||
|
|
||||||
// The outlet earns 1 EnakPoint per Rp 100 and accepts EnakPoint.
|
|
||||||
s, err := settings.Outlet(context.Background(), e.outlet)
|
|
||||||
require.NoError(t, err)
|
|
||||||
s.Point.Enabled = true
|
|
||||||
s.PointPayment.AcceptPayment = true
|
|
||||||
_, err = settings.UpdateOutlet(context.Background(), e.org, e.outlet, e.cashier, *s)
|
|
||||||
require.NoError(t, err)
|
|
||||||
|
|
||||||
e.ctx = context.WithValue(context.Background(), appcontext.UserIDKey, e.cashier.String())
|
|
||||||
return e
|
|
||||||
}
|
|
||||||
|
|
||||||
func (e *pointPaymentEnv) exec(q string, args ...any) {
|
|
||||||
e.t.Helper()
|
|
||||||
require.NoError(e.t, e.db.Exec(q, args...).Error)
|
|
||||||
}
|
|
||||||
|
|
||||||
// customerWith creates a customer holding the given EnakPoint.
|
|
||||||
func (e *pointPaymentEnv) customerWith(points int64) uuid.UUID {
|
|
||||||
e.t.Helper()
|
|
||||||
id := uuid.New()
|
|
||||||
e.exec(`INSERT INTO customers (id, organization_id, name) VALUES (?, ?, 'c')`, id, e.org)
|
|
||||||
if points > 0 {
|
|
||||||
require.NoError(e.t, repository.NewTxManager(e.db).WithTransaction(context.Background(), func(ctx context.Context) error {
|
|
||||||
_, err := NewWalletProcessor(repository.NewWalletRepository(e.db)).Credit(ctx, WalletCreditInput{WalletEntry: WalletEntry{
|
|
||||||
CustomerID: id, Currency: constants.WalletCurrencyPoint, Type: constants.WalletTxTypeMigration, Amount: points,
|
|
||||||
ReferenceType: constants.WalletRefTypeLegacyPoints, ReferenceID: uuid.New(), Description: "Saldo awal"}})
|
|
||||||
return err
|
|
||||||
}))
|
|
||||||
}
|
|
||||||
return id
|
|
||||||
}
|
|
||||||
|
|
||||||
func (e *pointPaymentEnv) order(customer uuid.UUID, subtotal float64) uuid.UUID {
|
|
||||||
e.t.Helper()
|
|
||||||
id := uuid.New()
|
|
||||||
e.exec(`INSERT INTO orders (id, organization_id, outlet_id, user_id, customer_id, order_number, order_type,
|
|
||||||
subtotal, tax_amount, total_amount, remaining_amount, payment_status)
|
|
||||||
VALUES (?, ?, ?, ?, ?, ?, 'dine_in', ?, 0, ?, ?, 'pending')`,
|
|
||||||
id, e.org, e.outlet, e.cashier, customer, "PP-"+id.String()[:8], subtotal, subtotal, subtotal)
|
|
||||||
return id
|
|
||||||
}
|
|
||||||
|
|
||||||
func (e *pointPaymentEnv) code(customer uuid.UUID) string {
|
|
||||||
e.t.Helper()
|
|
||||||
c, err := e.codes.Issue(context.Background(), customer, "482913", models.CustomerPinRequestInfo{})
|
|
||||||
require.NoError(e.t, err)
|
|
||||||
return c.Code
|
|
||||||
}
|
|
||||||
|
|
||||||
func (e *pointPaymentEnv) payPoints(order uuid.UUID, points int64, code string) (*models.PaymentResponse, error) {
|
|
||||||
return e.orders.CreatePayment(e.ctx, &models.CreatePaymentRequest{OrderID: order, PaymentMethodID: e.point, Points: &points, PaymentCode: &code})
|
|
||||||
}
|
|
||||||
|
|
||||||
func (e *pointPaymentEnv) balance(customer uuid.UUID) int64 {
|
|
||||||
e.t.Helper()
|
|
||||||
var b int64
|
|
||||||
require.NoError(e.t, e.db.Raw(`SELECT COALESCE(SUM(point_balance), 0) FROM customer_wallets WHERE customer_id = ?`, customer).Scan(&b).Error)
|
|
||||||
return b
|
|
||||||
}
|
|
||||||
|
|
||||||
func (e *pointPaymentEnv) orderState(order uuid.UUID) (status string, remaining float64) {
|
|
||||||
e.t.Helper()
|
|
||||||
var row struct {
|
|
||||||
PaymentStatus string
|
|
||||||
RemainingAmount float64
|
|
||||||
}
|
|
||||||
require.NoError(e.t, e.db.Raw(`SELECT payment_status, remaining_amount FROM orders WHERE id = ?`, order).Scan(&row).Error)
|
|
||||||
return row.PaymentStatus, row.RemainingAmount
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestPointPayment_FullPayment(t *testing.T) {
|
|
||||||
e := newPointPaymentEnv(t)
|
|
||||||
customer := e.customerWith(100000)
|
|
||||||
order := e.order(customer, 50000)
|
|
||||||
|
|
||||||
payment, err := e.payPoints(order, 50000, e.code(customer))
|
|
||||||
require.NoError(t, err)
|
|
||||||
assert.Equal(t, 50000.0, payment.Amount)
|
|
||||||
require.NotNil(t, payment.PointsUsed)
|
|
||||||
assert.Equal(t, int64(50000), *payment.PointsUsed)
|
|
||||||
assert.Equal(t, 1.0, *payment.PointValue, "the value is frozen on the payment")
|
|
||||||
status, remaining := e.orderState(order)
|
|
||||||
assert.Equal(t, "completed", status)
|
|
||||||
assert.Zero(t, remaining)
|
|
||||||
assert.Equal(t, int64(50000), e.balance(customer))
|
|
||||||
|
|
||||||
var ledger struct {
|
|
||||||
Amount int64
|
|
||||||
ReferenceType string
|
|
||||||
ReferenceID string
|
|
||||||
OutletID string
|
|
||||||
CreatedByUser string
|
|
||||||
}
|
|
||||||
require.NoError(t, e.db.Raw(`SELECT amount, reference_type, reference_id::text AS reference_id, outlet_id::text AS outlet_id,
|
|
||||||
created_by_user::text AS created_by_user FROM wallet_transactions WHERE customer_id = ? AND type = 'PAYMENT'`, customer).Scan(&ledger).Error)
|
|
||||||
assert.Equal(t, int64(-50000), ledger.Amount)
|
|
||||||
assert.Equal(t, "PAYMENT", ledger.ReferenceType)
|
|
||||||
assert.Equal(t, payment.ID.String(), ledger.ReferenceID)
|
|
||||||
assert.Equal(t, e.outlet.String(), ledger.OutletID)
|
|
||||||
assert.Equal(t, e.cashier.String(), ledger.CreatedByUser, "the cashier who took it")
|
|
||||||
|
|
||||||
// Paid entirely with EnakPoint, so nothing earns (Q10).
|
|
||||||
var earned int64
|
|
||||||
require.NoError(t, e.db.Raw(`SELECT COUNT(*) FROM wallet_transactions WHERE reference_id = ? AND type = 'EARN'`, order).Scan(&earned).Error)
|
|
||||||
assert.Zero(t, earned)
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestPointPayment_PartialThenCash(t *testing.T) {
|
|
||||||
e := newPointPaymentEnv(t)
|
|
||||||
customer := e.customerWith(100000)
|
|
||||||
order := e.order(customer, 87500)
|
|
||||||
|
|
||||||
_, err := e.payPoints(order, 20000, e.code(customer))
|
|
||||||
require.NoError(t, err)
|
|
||||||
status, remaining := e.orderState(order)
|
|
||||||
assert.Equal(t, "partial", status)
|
|
||||||
assert.Equal(t, 67500.0, remaining)
|
|
||||||
|
|
||||||
// The rest in cash settles it; earning counts only the part not paid with
|
|
||||||
// EnakPoint: floor(67.500 / 100) = 675.
|
|
||||||
_, err = e.orders.CreatePayment(e.ctx, &models.CreatePaymentRequest{OrderID: order, PaymentMethodID: e.cash, Amount: 67500})
|
|
||||||
require.NoError(t, err)
|
|
||||||
status, _ = e.orderState(order)
|
|
||||||
assert.Equal(t, "completed", status)
|
|
||||||
var earned int64
|
|
||||||
require.NoError(t, e.db.Raw(`SELECT COALESCE(SUM(amount), 0) FROM wallet_transactions WHERE reference_id = ? AND type = 'EARN'`, order).Scan(&earned).Error)
|
|
||||||
assert.Equal(t, int64(675), earned)
|
|
||||||
assert.Equal(t, int64(100000-20000+675), e.balance(customer))
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestPointPayment_PercentCap(t *testing.T) {
|
|
||||||
e := newPointPaymentEnv(t)
|
|
||||||
settings := NewLoyaltySettingsProcessor(repository.NewLoyaltySettingsRepository(e.db), repository.NewTxManager(e.db))
|
|
||||||
s, err := settings.Outlet(context.Background(), e.outlet)
|
|
||||||
require.NoError(t, err)
|
|
||||||
s.PointPayment.MaxPaymentPercent = 50
|
|
||||||
_, err = settings.UpdateOutlet(context.Background(), e.org, e.outlet, e.cashier, *s)
|
|
||||||
require.NoError(t, err)
|
|
||||||
|
|
||||||
customer := e.customerWith(100000)
|
|
||||||
order := e.order(customer, 100000)
|
|
||||||
|
|
||||||
preview, err := e.payments.Preview(context.Background(), e.org, order)
|
|
||||||
require.NoError(t, err)
|
|
||||||
assert.True(t, preview.Eligible)
|
|
||||||
assert.Equal(t, int64(50000), preview.MaxPoints)
|
|
||||||
assert.Equal(t, int64(100000), preview.PointBalance)
|
|
||||||
|
|
||||||
_, err = e.payPoints(order, 50001, e.code(customer))
|
|
||||||
assert.ErrorIs(t, err, ErrPointPaymentRejected)
|
|
||||||
_, err = e.payPoints(order, 30000, e.code(customer))
|
|
||||||
require.NoError(t, err)
|
|
||||||
_, err = e.payPoints(order, 20001, e.code(customer))
|
|
||||||
assert.ErrorIs(t, err, ErrPointPaymentRejected, "earlier EnakPoint counts toward the cap")
|
|
||||||
_, err = e.payPoints(order, 20000, e.code(customer))
|
|
||||||
require.NoError(t, err)
|
|
||||||
assert.Equal(t, int64(50000), e.balance(customer))
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestPointPayment_Refusals(t *testing.T) {
|
|
||||||
e := newPointPaymentEnv(t)
|
|
||||||
customer := e.customerWith(100000)
|
|
||||||
other := e.customerWith(100000)
|
|
||||||
|
|
||||||
// A walk-in order cannot be paid with EnakPoint.
|
|
||||||
walkInOrder := e.order(e.walkIn, 10000)
|
|
||||||
preview, err := e.payments.Preview(context.Background(), e.org, walkInOrder)
|
|
||||||
require.NoError(t, err)
|
|
||||||
assert.False(t, preview.Eligible)
|
|
||||||
assert.Contains(t, preview.Reason, "walk-in")
|
|
||||||
_, err = e.payPoints(walkInOrder, 1000, "123456")
|
|
||||||
assert.ErrorIs(t, err, ErrPointPaymentRejected)
|
|
||||||
|
|
||||||
order := e.order(customer, 10000)
|
|
||||||
_, err = e.payPoints(order, 1000, "000000")
|
|
||||||
assert.ErrorIs(t, err, ErrPointPaymentRejected, "a wrong code")
|
|
||||||
_, err = e.payPoints(order, 1000, e.code(other))
|
|
||||||
assert.ErrorIs(t, err, ErrPointPaymentRejected, "another customer's code")
|
|
||||||
missing := int64(1000)
|
|
||||||
_, err = e.orders.CreatePayment(e.ctx, &models.CreatePaymentRequest{OrderID: order, PaymentMethodID: e.point, Points: &missing})
|
|
||||||
assert.ErrorIs(t, err, ErrPointPaymentRejected, "no code at all")
|
|
||||||
|
|
||||||
code := e.code(customer)
|
|
||||||
_, err = e.payPoints(order, 1000, code)
|
|
||||||
require.NoError(t, err)
|
|
||||||
_, err = e.payPoints(order, 1000, code)
|
|
||||||
assert.ErrorIs(t, err, ErrPointPaymentRejected, "a code is used once, so a double tap takes once")
|
|
||||||
_, err = e.payPoints(order, 9001, e.code(customer))
|
|
||||||
assert.ErrorIs(t, err, ErrPointPaymentRejected, "no change is given: not more than what is left")
|
|
||||||
|
|
||||||
// Splitting with the EnakPoint method would skip the balance, so it is refused.
|
|
||||||
e.orders.splitBillProcessor = splitFake{}
|
|
||||||
_, err = e.orders.SplitBill(e.ctx, &models.SplitBillRequest{OrderID: order, PaymentMethodID: e.point, Type: "AMOUNT", Amount: 1000})
|
|
||||||
assert.ErrorIs(t, err, ErrPointPaymentRejected)
|
|
||||||
|
|
||||||
assert.Equal(t, int64(99000), e.balance(customer), "only the one payment took anything")
|
|
||||||
assert.Equal(t, int64(100000), e.balance(other))
|
|
||||||
}
|
|
||||||
|
|
||||||
// Two payments for the same customer at once, on two orders: the balance is taken
|
|
||||||
// once, never twice. Authorization is taken as given so only the balance decides.
|
|
||||||
func TestPointPayment_ConcurrentForOneCustomer(t *testing.T) {
|
|
||||||
e := newPointPaymentEnv(t)
|
|
||||||
customer := e.customerWith(30000)
|
|
||||||
orders := []uuid.UUID{e.order(customer, 20000), e.order(customer, 20000)}
|
|
||||||
|
|
||||||
var wg sync.WaitGroup
|
|
||||||
results := make([]error, len(orders))
|
|
||||||
for i, order := range orders {
|
|
||||||
wg.Add(1)
|
|
||||||
go func(i int, order uuid.UUID) {
|
|
||||||
defer wg.Done()
|
|
||||||
_, results[i] = e.payments.Pay(e.ctx, PointPaymentInput{
|
|
||||||
OrderID: order, PaymentMethodID: e.point, Points: 20000,
|
|
||||||
Authorize: func(context.Context, uuid.UUID) error { return nil },
|
|
||||||
})
|
|
||||||
}(i, order)
|
|
||||||
}
|
|
||||||
wg.Wait()
|
|
||||||
|
|
||||||
succeeded := 0
|
|
||||||
for _, err := range results {
|
|
||||||
if err == nil {
|
|
||||||
succeeded++
|
|
||||||
} else {
|
|
||||||
assert.ErrorIs(t, err, ErrPointPaymentRejected)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
assert.Equal(t, 1, succeeded, "30.000 EnakPoint pays one 20.000 order, not two")
|
|
||||||
assert.Equal(t, int64(10000), e.balance(customer))
|
|
||||||
|
|
||||||
// And the wallet still reconciles.
|
|
||||||
found, err := repository.NewWalletReconciliationRepository(e.db).FindDiscrepancies(context.Background(), 1000)
|
|
||||||
require.NoError(t, err)
|
|
||||||
for _, d := range found {
|
|
||||||
assert.NotEqual(t, customer, d.CustomerID, d.Check)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestPointPayment_InApp(t *testing.T) {
|
|
||||||
e := newPointPaymentEnv(t)
|
|
||||||
owner := e.customerWith(100000)
|
|
||||||
stranger := e.customerWith(100000)
|
|
||||||
order := e.order(owner, 60000)
|
|
||||||
info := models.CustomerPinRequestInfo{}
|
|
||||||
|
|
||||||
// Another customer cannot pay it, and is not told it exists.
|
|
||||||
_, err := e.orders.PayWithPointsInApp(e.ctx, stranger, order, 1000, "482913", info)
|
|
||||||
assert.ErrorIs(t, err, repository.ErrPointPaymentOrderNotFound)
|
|
||||||
_, err = e.orders.PayWithPointsInApp(e.ctx, owner, uuid.New(), 1000, "482913", info)
|
|
||||||
assert.ErrorIs(t, err, repository.ErrPointPaymentOrderNotFound)
|
|
||||||
|
|
||||||
// The session alone is not enough: a wrong PIN takes nothing.
|
|
||||||
_, err = e.orders.PayWithPointsInApp(e.ctx, owner, order, 1000, "000000", info)
|
|
||||||
var pe *PinError
|
|
||||||
require.ErrorAs(t, err, &pe)
|
|
||||||
assert.Equal(t, PinErrInvalid, pe.Code)
|
|
||||||
assert.Equal(t, int64(100000), e.balance(owner))
|
|
||||||
|
|
||||||
// The owner pays part, then the rest, with the same rules as at the cashier.
|
|
||||||
payment, err := e.orders.PayWithPointsInApp(e.ctx, owner, order, 10000, "482913", info)
|
|
||||||
require.NoError(t, err)
|
|
||||||
assert.Equal(t, int64(10000), *payment.PointsUsed)
|
|
||||||
status, remaining := e.orderState(order)
|
|
||||||
assert.Equal(t, "partial", status)
|
|
||||||
assert.Equal(t, 50000.0, remaining)
|
|
||||||
|
|
||||||
_, err = e.orders.PayWithPointsInApp(e.ctx, owner, order, 50001, "482913", info)
|
|
||||||
assert.ErrorIs(t, err, ErrPointPaymentRejected, "not more than what is left")
|
|
||||||
_, err = e.orders.PayWithPointsInApp(e.ctx, owner, order, 50000, "482913", info)
|
|
||||||
require.NoError(t, err)
|
|
||||||
status, _ = e.orderState(order)
|
|
||||||
assert.Equal(t, "completed", status)
|
|
||||||
assert.Equal(t, int64(40000), e.balance(owner))
|
|
||||||
assert.Equal(t, int64(100000), e.balance(stranger))
|
|
||||||
|
|
||||||
var createdBy *string
|
|
||||||
require.NoError(t, e.db.Raw(`SELECT created_by_user::text FROM wallet_transactions WHERE customer_id = ? AND type = 'PAYMENT' LIMIT 1`, owner).Scan(&createdBy).Error)
|
|
||||||
assert.Nil(t, createdBy, "no cashier took an in-app payment")
|
|
||||||
}
|
|
||||||
|
|
||||||
// The payment method report counts only money actually received as money in; the
|
|
||||||
// EnakPoint part is listed apart (F9).
|
|
||||||
func TestPointPayment_ReportKeepsEnakPointOutOfCashIn(t *testing.T) {
|
|
||||||
e := newPointPaymentEnv(t)
|
|
||||||
customer := e.customerWith(100000)
|
|
||||||
order := e.order(customer, 87500)
|
|
||||||
_, err := e.payPoints(order, 20000, e.code(customer))
|
|
||||||
require.NoError(t, err)
|
|
||||||
_, err = e.orders.CreatePayment(e.ctx, &models.CreatePaymentRequest{OrderID: order, PaymentMethodID: e.cash, Amount: 67500})
|
|
||||||
require.NoError(t, err)
|
|
||||||
|
|
||||||
report, err := NewAnalyticsProcessorImpl(repository.NewAnalyticsRepositoryImpl(e.db), nil).GetPaymentMethodAnalytics(context.Background(),
|
|
||||||
&models.PaymentMethodAnalyticsRequest{OrganizationID: e.org, DateFrom: time.Now().Add(-time.Hour), DateTo: time.Now().Add(time.Hour)})
|
|
||||||
require.NoError(t, err)
|
|
||||||
assert.Equal(t, 67500.0, report.Summary.TotalAmount, "money in is the cash, not the order total")
|
|
||||||
assert.Equal(t, 20000.0, report.Summary.PointAmount)
|
|
||||||
assert.Equal(t, int64(20000), report.Summary.PointsUsed)
|
|
||||||
assert.Equal(t, 87500.0, report.Summary.TotalWithPoints)
|
|
||||||
require.Len(t, report.Data, 2)
|
|
||||||
for _, d := range report.Data {
|
|
||||||
assert.Equal(t, d.PaymentMethodType != "point", d.CountsAsCashIn, d.PaymentMethodName)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,118 +0,0 @@
|
|||||||
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/models"
|
|
||||||
"apskel-pos-be/internal/repository"
|
|
||||||
)
|
|
||||||
|
|
||||||
// Needs TEST_DATABASE_URL pointing at a migrated database; see
|
|
||||||
// internal/repository/wallet_repository_test.go.
|
|
||||||
func TestPointPaymentMethod_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)
|
|
||||||
ctx := context.Background()
|
|
||||||
|
|
||||||
org, user, accepting, refusing := uuid.New(), uuid.New(), uuid.New(), uuid.New()
|
|
||||||
exec := func(q string, args ...any) error { return db.Exec(q, args...).Error }
|
|
||||||
require.NoError(t, exec(`INSERT INTO organizations (id, name, plan_type) VALUES (?, 'pm test', 'basic')`, org))
|
|
||||||
require.NoError(t, exec(`INSERT INTO outlets (id, organization_id, name) VALUES (?, ?, 'Terima'), (?, ?, 'Tolak')`, accepting, org, refusing, org))
|
|
||||||
t.Cleanup(func() {
|
|
||||||
db.Exec(`DELETE FROM loyalty_setting_changes WHERE organization_id = ?`, org)
|
|
||||||
db.Exec(`DELETE FROM outlet_settings WHERE outlet_id IN ?`, []uuid.UUID{accepting, refusing})
|
|
||||||
db.Exec(`DELETE FROM outlets WHERE id IN ?`, []uuid.UUID{accepting, refusing})
|
|
||||||
db.Exec(`DELETE FROM payment_methods WHERE organization_id = ?`, org)
|
|
||||||
db.Exec(`DELETE FROM organizations WHERE id = ?`, org)
|
|
||||||
})
|
|
||||||
|
|
||||||
// A new organization gets exactly one EnakPoint method from the trigger.
|
|
||||||
var methods []struct {
|
|
||||||
ID string
|
|
||||||
Name string
|
|
||||||
Type string
|
|
||||||
}
|
|
||||||
require.NoError(t, db.Raw(`SELECT id::text AS id, name, type FROM payment_methods WHERE organization_id = ?`, org).Scan(&methods).Error)
|
|
||||||
require.Len(t, methods, 1)
|
|
||||||
assert.Equal(t, "EnakPoint", methods[0].Name)
|
|
||||||
assert.Equal(t, "point", methods[0].Type)
|
|
||||||
pointID := uuid.MustParse(methods[0].ID)
|
|
||||||
|
|
||||||
// The database refuses a second one.
|
|
||||||
assert.Error(t, exec(`INSERT INTO payment_methods (organization_id, name, type) VALUES (?, 'EnakPoint 2', 'point')`, org))
|
|
||||||
|
|
||||||
txm := repository.NewTxManager(db)
|
|
||||||
settings := NewLoyaltySettingsProcessor(repository.NewLoyaltySettingsRepository(db), txm)
|
|
||||||
s, err := settings.Outlet(ctx, accepting)
|
|
||||||
require.NoError(t, err)
|
|
||||||
s.PointPayment.AcceptPayment = true
|
|
||||||
_, err = settings.UpdateOutlet(ctx, org, accepting, user, *s)
|
|
||||||
require.NoError(t, err)
|
|
||||||
|
|
||||||
p := NewPaymentMethodProcessorImpl(repository.NewPaymentMethodRepositoryImpl(db), settings)
|
|
||||||
cash, err := p.CreatePaymentMethod(ctx, &models.CreatePaymentMethodRequest{OrganizationID: org, Name: "Tunai", Type: constants.PaymentMethodTypeCash, IsActive: ptr(true)})
|
|
||||||
require.NoError(t, err)
|
|
||||||
|
|
||||||
// The API cannot make, retype or delete an EnakPoint method.
|
|
||||||
_, err = p.CreatePaymentMethod(ctx, &models.CreatePaymentMethodRequest{OrganizationID: org, Name: "Poin Lain", Type: constants.PaymentMethodTypePoint, IsActive: ptr(true)})
|
|
||||||
assert.ErrorIs(t, err, ErrSystemPaymentMethod)
|
|
||||||
toCash := constants.PaymentMethodTypeCash
|
|
||||||
_, err = p.UpdatePaymentMethod(ctx, pointID, &models.UpdatePaymentMethodRequest{Type: &toCash})
|
|
||||||
assert.ErrorIs(t, err, ErrSystemPaymentMethod)
|
|
||||||
toPoint := constants.PaymentMethodTypePoint
|
|
||||||
_, err = p.UpdatePaymentMethod(ctx, cash.ID, &models.UpdatePaymentMethodRequest{Type: &toPoint})
|
|
||||||
assert.ErrorIs(t, err, ErrSystemPaymentMethod)
|
|
||||||
assert.ErrorIs(t, p.DeletePaymentMethod(ctx, pointID), ErrSystemPaymentMethod)
|
|
||||||
|
|
||||||
// Renaming it is fine; its type stays.
|
|
||||||
name := "Bayar pakai EnakPoint"
|
|
||||||
renamed, err := p.UpdatePaymentMethod(ctx, pointID, &models.UpdatePaymentMethodRequest{Name: &name, Type: &toPoint})
|
|
||||||
require.NoError(t, err)
|
|
||||||
assert.Equal(t, name, renamed.Name)
|
|
||||||
|
|
||||||
// At the cashier it shows only where the outlet accepts EnakPoint.
|
|
||||||
types := func(outlet *uuid.UUID) []constants.PaymentMethodType {
|
|
||||||
t.Helper()
|
|
||||||
list, err := p.ListPaymentMethods(ctx, &models.ListPaymentMethodsRequest{OrganizationID: &org, OutletID: outlet, Page: 1, Limit: 50})
|
|
||||||
require.NoError(t, err)
|
|
||||||
var out []constants.PaymentMethodType
|
|
||||||
for _, m := range list.PaymentMethods {
|
|
||||||
out = append(out, m.Type)
|
|
||||||
}
|
|
||||||
assert.Equal(t, len(out), list.TotalCount, "the count matches what is listed")
|
|
||||||
return out
|
|
||||||
}
|
|
||||||
assert.ElementsMatch(t, []constants.PaymentMethodType{"cash", "point"}, types(&accepting))
|
|
||||||
assert.ElementsMatch(t, []constants.PaymentMethodType{"cash"}, types(&refusing))
|
|
||||||
assert.ElementsMatch(t, []constants.PaymentMethodType{"cash", "point"}, types(nil), "the dashboard, without an outlet, sees it")
|
|
||||||
|
|
||||||
// A payment either records both points_used and point_value, or neither.
|
|
||||||
var orderID uuid.UUID
|
|
||||||
require.NoError(t, exec(`INSERT INTO users (id, organization_id, name, email, password_hash, role) VALUES (?, ?, 'K', ?, 'x', 'cashier')`, user, org, user.String()+"@t"))
|
|
||||||
orderID = uuid.New()
|
|
||||||
require.NoError(t, exec(`INSERT INTO orders (id, organization_id, outlet_id, user_id, order_number, order_type, subtotal, tax_amount, total_amount)
|
|
||||||
VALUES (?, ?, ?, ?, ?, 'dine_in', 1000, 0, 1000)`, orderID, org, accepting, user, "PM-"+orderID.String()[:8]))
|
|
||||||
t.Cleanup(func() {
|
|
||||||
db.Exec(`DELETE FROM payments WHERE order_id = ?`, orderID)
|
|
||||||
db.Exec(`DELETE FROM orders WHERE id = ?`, orderID)
|
|
||||||
db.Exec(`DELETE FROM users WHERE id = ?`, user)
|
|
||||||
})
|
|
||||||
assert.Error(t, exec(`INSERT INTO payments (order_id, payment_method_id, amount, points_used) VALUES (?, ?, 1000, 1000)`, orderID, pointID))
|
|
||||||
assert.Error(t, exec(`INSERT INTO payments (order_id, payment_method_id, amount, points_used, point_value) VALUES (?, ?, 1000, 0, 1)`, orderID, pointID))
|
|
||||||
assert.NoError(t, exec(`INSERT INTO payments (order_id, payment_method_id, amount, points_used, point_value) VALUES (?, ?, 1000, 1000, 1)`, orderID, pointID))
|
|
||||||
assert.NoError(t, exec(`INSERT INTO payments (order_id, payment_method_id, amount) VALUES (?, ?, 1000)`, orderID, cash.ID))
|
|
||||||
}
|
|
||||||
@@ -1,336 +0,0 @@
|
|||||||
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/models"
|
|
||||||
"apskel-pos-be/internal/repository"
|
|
||||||
)
|
|
||||||
|
|
||||||
// ErrPointPaymentRejected wraps every reason a payment with EnakPoint is refused: the
|
|
||||||
// order, the customer, the outlet or the amount. The message says which.
|
|
||||||
var ErrPointPaymentRejected = errors.New("EnakPoint payment refused")
|
|
||||||
|
|
||||||
type pointPaymentSettings interface {
|
|
||||||
Outlet(ctx context.Context, outletID uuid.UUID) (*models.OutletLoyaltySettings, error)
|
|
||||||
PointValue(ctx context.Context, organizationID uuid.UUID) (int64, error)
|
|
||||||
}
|
|
||||||
|
|
||||||
type spendableReader interface {
|
|
||||||
SpendableBalances(ctx context.Context, customerID uuid.UUID, asOf time.Time) (map[string]int64, error)
|
|
||||||
}
|
|
||||||
|
|
||||||
// PointPaymentInput is one payment of an order with EnakPoint.
|
|
||||||
type PointPaymentInput struct {
|
|
||||||
OrderID uuid.UUID
|
|
||||||
PaymentMethodID uuid.UUID
|
|
||||||
Points int64
|
|
||||||
// The cashier taking the payment at the POS; nil when the customer pays in the app.
|
|
||||||
CashierID *uuid.UUID
|
|
||||||
// Authorize proves the customer agreed, before anything is taken: at the POS it
|
|
||||||
// redeems the payment code, in the app it checks the PIN (K8).
|
|
||||||
Authorize func(ctx context.Context, customerID uuid.UUID) error
|
|
||||||
}
|
|
||||||
|
|
||||||
// PointPaymentResult is the payment made and where it left the order.
|
|
||||||
type PointPaymentResult struct {
|
|
||||||
Payment *entities.Payment
|
|
||||||
// True when this payment settled the order.
|
|
||||||
Completed bool
|
|
||||||
// Rupiah still to pay with another method.
|
|
||||||
Remaining float64
|
|
||||||
}
|
|
||||||
|
|
||||||
// pointPaymentLimits applies the formula of docs/prd-point-coin.md F9, in cents:
|
|
||||||
//
|
|
||||||
// cap = min(remaining, total × max_payment_percent / 100 − already paid with EnakPoint)
|
|
||||||
// max_points = min(balance, floor(cap / point_value))
|
|
||||||
type pointPaymentLimits struct {
|
|
||||||
RemainingCents int64
|
|
||||||
CapCents int64
|
|
||||||
MaxPoints int64
|
|
||||||
}
|
|
||||||
|
|
||||||
func computePointPaymentLimits(total, totalPaid, paidWithPoints float64, maxPercent, pointValue, balance int64) pointPaymentLimits {
|
|
||||||
remaining := toCents(total) - toCents(totalPaid)
|
|
||||||
if remaining < 0 {
|
|
||||||
remaining = 0
|
|
||||||
}
|
|
||||||
byPercent := toCents(total)*maxPercent/100 - toCents(paidWithPoints)
|
|
||||||
capCents := min(remaining, byPercent)
|
|
||||||
if capCents < 0 {
|
|
||||||
capCents = 0
|
|
||||||
}
|
|
||||||
maxPoints := int64(0)
|
|
||||||
if pointValue > 0 {
|
|
||||||
maxPoints = min(balance, capCents/(pointValue*100))
|
|
||||||
}
|
|
||||||
if maxPoints < 0 {
|
|
||||||
maxPoints = 0
|
|
||||||
}
|
|
||||||
return pointPaymentLimits{RemainingCents: remaining, CapCents: capCents, MaxPoints: maxPoints}
|
|
||||||
}
|
|
||||||
|
|
||||||
// PointPaymentProcessor pays orders with EnakPoint (docs/prd-point-coin.md F9).
|
|
||||||
type PointPaymentProcessor struct {
|
|
||||||
repo repository.PointPaymentRepository
|
|
||||||
settings pointPaymentSettings
|
|
||||||
spendable spendableReader
|
|
||||||
wallet *WalletProcessor
|
|
||||||
tx TxRunner
|
|
||||||
now func() time.Time
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewPointPaymentProcessor(repo repository.PointPaymentRepository, settings pointPaymentSettings, spendable spendableReader, wallet *WalletProcessor, tx TxRunner) *PointPaymentProcessor {
|
|
||||||
return &PointPaymentProcessor{repo: repo, settings: settings, spendable: spendable, wallet: wallet, tx: tx, now: time.Now}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Preview is GET /orders/:id/point-payment/preview: whether the order can be paid with
|
|
||||||
// EnakPoint, and at most how much.
|
|
||||||
func (p *PointPaymentProcessor) Preview(ctx context.Context, organizationID, orderID uuid.UUID) (*models.PointPaymentPreview, error) {
|
|
||||||
order, err := p.repo.GetOrder(ctx, orderID, false)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
if order.OrganizationID != organizationID {
|
|
||||||
return nil, repository.ErrPointPaymentOrderNotFound
|
|
||||||
}
|
|
||||||
preview := &models.PointPaymentPreview{OrderID: orderID, CustomerID: order.CustomerID}
|
|
||||||
settings, err := p.settings.Outlet(ctx, order.OutletID)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
value, err := p.settings.PointValue(ctx, order.OrganizationID)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
preview.PointValue = value
|
|
||||||
preview.MinPaymentPoints = settings.PointPayment.MinPaymentPoints
|
|
||||||
preview.MaxPaymentPercent = settings.PointPayment.MaxPaymentPercent
|
|
||||||
|
|
||||||
if reason := pointPaymentOrderProblem(order, settings); reason != "" {
|
|
||||||
preview.Reason = reason
|
|
||||||
return preview, nil
|
|
||||||
}
|
|
||||||
limits, balance, err := p.limits(ctx, order, settings, value)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
preview.PointBalance = balance
|
|
||||||
preview.RemainingAmount = float64(limits.RemainingCents) / 100
|
|
||||||
preview.MaxPoints = limits.MaxPoints
|
|
||||||
preview.MaxAmount = limits.MaxPoints * value
|
|
||||||
if limits.MaxPoints < settings.PointPayment.MinPaymentPoints {
|
|
||||||
preview.Reason = "the customer cannot pay the minimum of EnakPoint on this order"
|
|
||||||
return preview, nil
|
|
||||||
}
|
|
||||||
preview.Eligible = true
|
|
||||||
return preview, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// Pay takes EnakPoint from the order's customer and records the payment. The payment
|
|
||||||
// row, the ledger PAYMENT row, the balance and the order change in one transaction
|
|
||||||
// with the order row and the wallet locked (F9 steps 1–6).
|
|
||||||
func (p *PointPaymentProcessor) Pay(ctx context.Context, in PointPaymentInput) (*PointPaymentResult, error) {
|
|
||||||
reject := func(format string, args ...any) error {
|
|
||||||
return fmt.Errorf("%w: %s", ErrPointPaymentRejected, fmt.Sprintf(format, args...))
|
|
||||||
}
|
|
||||||
if in.Points <= 0 {
|
|
||||||
return nil, reject("the number of EnakPoint must be positive")
|
|
||||||
}
|
|
||||||
order, err := p.repo.GetOrder(ctx, in.OrderID, false)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
methodOrg, methodType, err := p.repo.GetPaymentMethod(ctx, in.PaymentMethodID)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
if methodType != string(constants.PaymentMethodTypePoint) || methodOrg != order.OrganizationID {
|
|
||||||
return nil, reject("the payment method is not this organization's EnakPoint method")
|
|
||||||
}
|
|
||||||
settings, err := p.settings.Outlet(ctx, order.OutletID)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
if reason := pointPaymentOrderProblem(order, settings); reason != "" {
|
|
||||||
return nil, reject("%s", reason)
|
|
||||||
}
|
|
||||||
if in.Points < settings.PointPayment.MinPaymentPoints {
|
|
||||||
return nil, reject("at least %d EnakPoint must be used", settings.PointPayment.MinPaymentPoints)
|
|
||||||
}
|
|
||||||
customerID := *order.CustomerID
|
|
||||||
|
|
||||||
// The customer agrees before anything is taken. A code is used up here even if the
|
|
||||||
// payment then fails, and the customer shows a new one.
|
|
||||||
if in.Authorize == nil {
|
|
||||||
return nil, reject("the customer has not approved the payment")
|
|
||||||
}
|
|
||||||
if err := in.Authorize(ctx, customerID); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
result := &PointPaymentResult{}
|
|
||||||
err = p.tx.WithTransaction(ctx, func(ctx context.Context) error {
|
|
||||||
// Lock the order, then the wallet, and read everything again: another payment
|
|
||||||
// may have landed since the checks above.
|
|
||||||
order, err := p.repo.GetOrder(ctx, in.OrderID, true)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
if reason := pointPaymentOrderProblem(order, settings); reason != "" {
|
|
||||||
return reject("%s", reason)
|
|
||||||
}
|
|
||||||
if err := p.wallet.LockWallet(ctx, customerID); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
value, err := p.settings.PointValue(ctx, order.OrganizationID)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
limits, _, err := p.limits(ctx, order, settings, value)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
if in.Points > limits.MaxPoints {
|
|
||||||
return reject("at most %d EnakPoint can pay this order now", limits.MaxPoints)
|
|
||||||
}
|
|
||||||
amountCents := in.Points * value * 100
|
|
||||||
// No change is ever given for EnakPoint (K7); the limits already keep it
|
|
||||||
// within what is left, this only guards that.
|
|
||||||
if amountCents > limits.RemainingCents {
|
|
||||||
return reject("EnakPoint cannot pay more than what is left on the order")
|
|
||||||
}
|
|
||||||
|
|
||||||
pointsUsed := in.Points
|
|
||||||
frozenValue := float64(value)
|
|
||||||
payment := &entities.Payment{
|
|
||||||
ID: uuid.New(),
|
|
||||||
OrderID: order.ID,
|
|
||||||
PaymentMethodID: in.PaymentMethodID,
|
|
||||||
Amount: float64(amountCents) / 100,
|
|
||||||
Status: entities.PaymentTransactionStatusCompleted,
|
|
||||||
PointsUsed: &pointsUsed,
|
|
||||||
PointValue: &frozenValue,
|
|
||||||
Metadata: entities.Metadata{"points_used": pointsUsed, "point_value": value},
|
|
||||||
}
|
|
||||||
if err := p.repo.InsertPayment(ctx, payment); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
outletID := order.OutletID
|
|
||||||
if _, err := p.wallet.Debit(ctx, WalletDebitInput{WalletEntry: WalletEntry{
|
|
||||||
CustomerID: customerID,
|
|
||||||
Currency: constants.WalletCurrencyPoint,
|
|
||||||
Type: constants.WalletTxTypePayment,
|
|
||||||
Amount: in.Points,
|
|
||||||
ReferenceType: constants.WalletRefTypePayment,
|
|
||||||
ReferenceID: payment.ID,
|
|
||||||
OutletID: &outletID,
|
|
||||||
CreatedByUser: in.CashierID,
|
|
||||||
Description: pointPaymentDescription(order, amountCents),
|
|
||||||
Metadata: entities.Metadata{"point_value": value, "amount": payment.Amount},
|
|
||||||
IdempotencyKey: "payment:" + payment.ID.String(),
|
|
||||||
}}); err != nil {
|
|
||||||
if errors.Is(err, repository.ErrWalletInsufficientBalance) {
|
|
||||||
return reject("the customer does not have enough EnakPoint")
|
|
||||||
}
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
remainingCents := limits.RemainingCents - amountCents
|
|
||||||
completed := remainingCents == 0
|
|
||||||
if err := p.repo.UpdateOrderAfterPayment(ctx, order.ID, float64(remainingCents)/100, completed); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
result.Payment = payment
|
|
||||||
result.Completed = completed
|
|
||||||
result.Remaining = float64(remainingCents) / 100
|
|
||||||
return nil
|
|
||||||
})
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
return result, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (p *PointPaymentProcessor) limits(ctx context.Context, order *repository.PointPaymentOrder, settings *models.OutletLoyaltySettings, value int64) (pointPaymentLimits, int64, error) {
|
|
||||||
totalPaid, err := p.repo.TotalPaid(ctx, order.ID)
|
|
||||||
if err != nil {
|
|
||||||
return pointPaymentLimits{}, 0, err
|
|
||||||
}
|
|
||||||
paidWithPoints, err := p.repo.PaidWithPoints(ctx, order.ID)
|
|
||||||
if err != nil {
|
|
||||||
return pointPaymentLimits{}, 0, err
|
|
||||||
}
|
|
||||||
balances, err := p.spendable.SpendableBalances(ctx, *order.CustomerID, p.now())
|
|
||||||
if err != nil {
|
|
||||||
return pointPaymentLimits{}, 0, err
|
|
||||||
}
|
|
||||||
balance := balances[constants.WalletCurrencyPoint]
|
|
||||||
return computePointPaymentLimits(order.TotalAmount, totalPaid, paidWithPoints, settings.PointPayment.MaxPaymentPercent, value, balance), balance, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// pointPaymentOrderProblem says why an order cannot be paid with EnakPoint at all, or
|
|
||||||
// "" when it can.
|
|
||||||
func pointPaymentOrderProblem(order *repository.PointPaymentOrder, settings *models.OutletLoyaltySettings) string {
|
|
||||||
switch {
|
|
||||||
case order.IsVoid:
|
|
||||||
return "the order is void"
|
|
||||||
case order.PaymentStatus == string(entities.PaymentStatusCompleted):
|
|
||||||
return "the order is already paid"
|
|
||||||
case !settings.PointPayment.AcceptPayment:
|
|
||||||
return "this outlet does not accept EnakPoint"
|
|
||||||
case order.CustomerID == nil || order.CustomerIsDefault == nil:
|
|
||||||
return "the order has no customer"
|
|
||||||
case *order.CustomerIsDefault:
|
|
||||||
return "a walk-in order cannot be paid with EnakPoint"
|
|
||||||
case order.CustomerIsActive == nil || !*order.CustomerIsActive:
|
|
||||||
return "the customer is not active"
|
|
||||||
}
|
|
||||||
return ""
|
|
||||||
}
|
|
||||||
|
|
||||||
func pointPaymentDescription(order *repository.PointPaymentOrder, amountCents int64) string {
|
|
||||||
description := "Bayar #" + order.OrderNumber
|
|
||||||
if order.OutletName != "" {
|
|
||||||
description += " di " + order.OutletName
|
|
||||||
}
|
|
||||||
description += " (Rp " + formatRupiah(amountCents/100) + ")"
|
|
||||||
return truncateRunes(description, walletDescriptionLimit)
|
|
||||||
}
|
|
||||||
|
|
||||||
// formatRupiah writes 50000 as 50.000.
|
|
||||||
func formatRupiah(n int64) string {
|
|
||||||
s := fmt.Sprintf("%d", n)
|
|
||||||
out := make([]byte, 0, len(s)+len(s)/3)
|
|
||||||
for i, c := range []byte(s) {
|
|
||||||
if i > 0 && (len(s)-i)%3 == 0 {
|
|
||||||
out = append(out, '.')
|
|
||||||
}
|
|
||||||
out = append(out, c)
|
|
||||||
}
|
|
||||||
return string(out)
|
|
||||||
}
|
|
||||||
|
|
||||||
// PointMethodID returns the organization's EnakPoint payment method.
|
|
||||||
func (p *PointPaymentProcessor) PointMethodID(ctx context.Context, organizationID uuid.UUID) (uuid.UUID, error) {
|
|
||||||
return p.repo.PointMethodID(ctx, organizationID)
|
|
||||||
}
|
|
||||||
|
|
||||||
// OrderOwner returns the organization and customer of an order, for checking that a
|
|
||||||
// customer pays only their own order.
|
|
||||||
func (p *PointPaymentProcessor) OrderOwner(ctx context.Context, orderID uuid.UUID) (organizationID uuid.UUID, customerID *uuid.UUID, err error) {
|
|
||||||
order, err := p.repo.GetOrder(ctx, orderID, false)
|
|
||||||
if err != nil {
|
|
||||||
return uuid.Nil, nil, err
|
|
||||||
}
|
|
||||||
return order.OrganizationID, order.CustomerID, nil
|
|
||||||
}
|
|
||||||
@@ -1,39 +0,0 @@
|
|||||||
package processor
|
|
||||||
|
|
||||||
import (
|
|
||||||
"testing"
|
|
||||||
|
|
||||||
"github.com/stretchr/testify/assert"
|
|
||||||
)
|
|
||||||
|
|
||||||
func TestComputePointPaymentLimits(t *testing.T) {
|
|
||||||
for name, c := range map[string]struct {
|
|
||||||
total, paid, paidWithPoints float64
|
|
||||||
percent, value, balance int64
|
|
||||||
wantRemaining, wantMax int64
|
|
||||||
}{
|
|
||||||
// The F9 example: Rp 87.550 left, 50.000 EnakPoint, 100%, Rp 1 a point.
|
|
||||||
"PRD example": {87550, 0, 0, 100, 1, 50000, 8755000, 50000},
|
|
||||||
"balance covers it all": {87550, 0, 0, 100, 1, 100000, 8755000, 87550},
|
|
||||||
"part already paid": {100000, 30000, 0, 100, 1, 100000, 7000000, 70000},
|
|
||||||
"capped by percent": {100000, 0, 0, 50, 1, 100000, 10000000, 50000},
|
|
||||||
"percent counts EnakPoint already used": {100000, 20000, 20000, 50, 1, 100000, 8000000, 30000},
|
|
||||||
"percent cap already used": {100000, 50000, 50000, 50, 1, 100000, 5000000, 0},
|
|
||||||
"point worth more than Rp 1": {87550, 0, 0, 100, 100, 1000, 8755000, 875},
|
|
||||||
"nothing left": {50000, 50000, 0, 100, 1, 100000, 0, 0},
|
|
||||||
"overpaid": {50000, 60000, 0, 100, 1, 100000, 0, 0},
|
|
||||||
"no balance": {50000, 0, 0, 100, 1, 0, 5000000, 0},
|
|
||||||
"cents left over": {10000.50, 0, 0, 100, 1, 100000, 1000050, 10000},
|
|
||||||
} {
|
|
||||||
got := computePointPaymentLimits(c.total, c.paid, c.paidWithPoints, c.percent, c.value, c.balance)
|
|
||||||
assert.Equal(t, c.wantRemaining, got.RemainingCents, name)
|
|
||||||
assert.Equal(t, c.wantMax, got.MaxPoints, name)
|
|
||||||
assert.LessOrEqual(t, got.MaxPoints*c.value*100, got.RemainingCents, "%s: never more than what is left", name)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestFormatRupiah(t *testing.T) {
|
|
||||||
for n, want := range map[int64]string{0: "0", 999: "999", 1000: "1.000", 50000: "50.000", 1234567: "1.234.567"} {
|
|
||||||
assert.Equal(t, want, formatRupiah(n))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,157 +0,0 @@
|
|||||||
package processor
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"fmt"
|
|
||||||
|
|
||||||
"github.com/google/uuid"
|
|
||||||
|
|
||||||
"apskel-pos-be/internal/constants"
|
|
||||||
"apskel-pos-be/internal/entities"
|
|
||||||
"apskel-pos-be/internal/repository"
|
|
||||||
)
|
|
||||||
|
|
||||||
// RefundForOrder gives EnakPoint back for the order's EnakPoint payments, as far as the
|
|
||||||
// order has been voided or those payments refunded (docs/prd-point-coin.md F9, K7):
|
|
||||||
//
|
|
||||||
// - void: every EnakPoint used on the order;
|
|
||||||
// - a refunded EnakPoint payment: floor(refunded rupiah / the frozen point value),
|
|
||||||
// so a later change of the point value does not change how many come back, and a
|
|
||||||
// rupiah remainder below one EnakPoint is lost (Q13).
|
|
||||||
//
|
|
||||||
// Never more than the payment used, and only what has not come back yet, so it can be
|
|
||||||
// called again safely. Returned EnakPoint go back into lots with the expiry of the lots
|
|
||||||
// they were taken from, but at least seven days from the refund (note N4, decided). It
|
|
||||||
// returns how many came back in total.
|
|
||||||
func (p *PointPaymentProcessor) RefundForOrder(ctx context.Context, orderID uuid.UUID) (int64, error) {
|
|
||||||
order, err := p.repo.GetOrder(ctx, orderID, false)
|
|
||||||
if err != nil {
|
|
||||||
return 0, err
|
|
||||||
}
|
|
||||||
payments, err := p.repo.ListPointPayments(ctx, orderID)
|
|
||||||
if err != nil {
|
|
||||||
return 0, err
|
|
||||||
}
|
|
||||||
|
|
||||||
var returned int64
|
|
||||||
for _, payment := range payments {
|
|
||||||
if payment.LedgerID == nil || payment.CustomerID == nil {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
target := pointRefundTarget(order.IsVoid, payment)
|
|
||||||
if target == 0 {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
var n int64
|
|
||||||
err := p.tx.WithTransaction(ctx, func(ctx context.Context) error {
|
|
||||||
if err := p.wallet.LockWallet(ctx, *payment.CustomerID); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
allocations, err := p.repo.PaymentAllocations(ctx, *payment.LedgerID)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
refunded, err := p.repo.RefundedByOriginLot(ctx, *payment.LedgerID)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
var already int64
|
|
||||||
for _, amount := range refunded {
|
|
||||||
already += amount
|
|
||||||
}
|
|
||||||
toReturn := target - already
|
|
||||||
if toReturn <= 0 {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// Fill the lots the payment took from, each up to what it gave.
|
|
||||||
var lots []WalletLotInput
|
|
||||||
left := toReturn
|
|
||||||
for _, a := range allocations {
|
|
||||||
if left == 0 {
|
|
||||||
break
|
|
||||||
}
|
|
||||||
room := a.Amount - refunded[a.LotID]
|
|
||||||
if room <= 0 {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
take := min(room, left)
|
|
||||||
left -= take
|
|
||||||
lotID := a.LotID
|
|
||||||
lots = append(lots, WalletLotInput{Amount: take, ExpiresAt: RefundExpiry(a.ExpiresAt, p.now()), OriginLotID: &lotID})
|
|
||||||
}
|
|
||||||
toReturn -= left
|
|
||||||
|
|
||||||
ledgerID := *payment.LedgerID
|
|
||||||
if _, err := p.wallet.Credit(ctx, WalletCreditInput{
|
|
||||||
WalletEntry: WalletEntry{
|
|
||||||
CustomerID: *payment.CustomerID,
|
|
||||||
Currency: constants.WalletCurrencyPoint,
|
|
||||||
Type: constants.WalletTxTypePaymentRefund,
|
|
||||||
Amount: toReturn,
|
|
||||||
ReferenceType: constants.WalletRefTypePayment,
|
|
||||||
ReferenceID: payment.PaymentID,
|
|
||||||
ReversesTransactionID: &ledgerID,
|
|
||||||
OutletID: payment.OutletID,
|
|
||||||
Description: pointRefundDescription(order),
|
|
||||||
Metadata: entities.Metadata{"point_value": payment.PointValue, "target": target, "void": order.IsVoid},
|
|
||||||
IdempotencyKey: fmt.Sprintf("payment-refund:%s:%d", payment.PaymentID, target),
|
|
||||||
},
|
|
||||||
Lots: lots,
|
|
||||||
}); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
n = toReturn
|
|
||||||
return nil
|
|
||||||
})
|
|
||||||
if err != nil {
|
|
||||||
return returned, fmt.Errorf("refunding EnakPoint payment %s: %w", payment.PaymentID, err)
|
|
||||||
}
|
|
||||||
returned += n
|
|
||||||
}
|
|
||||||
return returned, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// EnsureOrderRefundAllowed refuses an order-level refund that would hand back, in cash
|
|
||||||
// or another method, what was paid with EnakPoint (K7). The EnakPoint part is refunded
|
|
||||||
// through its own payment, and comes back as EnakPoint.
|
|
||||||
func (p *PointPaymentProcessor) EnsureOrderRefundAllowed(ctx context.Context, orderID uuid.UUID, amount float64) error {
|
|
||||||
refundable, err := p.repo.RefundableByOtherMethods(ctx, orderID)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
paidWithPoints, err := p.repo.PaidWithPoints(ctx, orderID)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
if paidWithPoints == 0 {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
if toCents(amount) > toCents(refundable) {
|
|
||||||
return fmt.Errorf("%w: at most Rp %s can be refunded this way; the part paid with EnakPoint is refunded through its EnakPoint payment and returns as EnakPoint",
|
|
||||||
ErrPointPaymentRejected, formatRupiah(toCents(refundable)/100))
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func pointRefundTarget(orderVoid bool, payment repository.PointPaymentRow) int64 {
|
|
||||||
if orderVoid {
|
|
||||||
return payment.PointsUsed
|
|
||||||
}
|
|
||||||
if payment.Status != string(entities.PaymentTransactionStatusRefunded) {
|
|
||||||
return 0
|
|
||||||
}
|
|
||||||
valueCents := toCents(payment.PointValue)
|
|
||||||
if valueCents <= 0 {
|
|
||||||
return 0
|
|
||||||
}
|
|
||||||
return min(payment.PointsUsed, toCents(payment.RefundAmount)/valueCents)
|
|
||||||
}
|
|
||||||
|
|
||||||
func pointRefundDescription(order *repository.PointPaymentOrder) string {
|
|
||||||
description := "Pengembalian #" + order.OrderNumber
|
|
||||||
if order.OutletName != "" {
|
|
||||||
description += " di " + order.OutletName
|
|
||||||
}
|
|
||||||
return truncateRunes(description, walletDescriptionLimit)
|
|
||||||
}
|
|
||||||
@@ -1,151 +0,0 @@
|
|||||||
package processor
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"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"
|
|
||||||
)
|
|
||||||
|
|
||||||
func (e *pointPaymentEnv) sum(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
|
|
||||||
}
|
|
||||||
|
|
||||||
func (e *pointPaymentEnv) returned(order uuid.UUID) int64 {
|
|
||||||
return e.sum(`SELECT COALESCE(SUM(t.amount), 0) FROM wallet_transactions t
|
|
||||||
JOIN payments p ON p.id = t.reference_id
|
|
||||||
WHERE p.order_id = ? AND t.type = 'PAYMENT_REFUND'`, order)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (e *pointPaymentEnv) assertReconciled(customers ...uuid.UUID) {
|
|
||||||
e.t.Helper()
|
|
||||||
found, err := repository.NewWalletReconciliationRepository(e.db).FindDiscrepancies(context.Background(), 1000)
|
|
||||||
require.NoError(e.t, err)
|
|
||||||
for _, d := range found {
|
|
||||||
for _, c := range customers {
|
|
||||||
assert.NotEqual(e.t, c, d.CustomerID, d.Check)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestPointRefund_VoidReturnsEverythingToItsExpiry(t *testing.T) {
|
|
||||||
e := newPointPaymentEnv(t)
|
|
||||||
customer := e.customerWith(0)
|
|
||||||
expires := time.Now().Add(30 * 24 * time.Hour).Truncate(time.Second)
|
|
||||||
require.NoError(t, repository.NewTxManager(e.db).WithTransaction(context.Background(), func(ctx context.Context) error {
|
|
||||||
_, err := NewWalletProcessor(repository.NewWalletRepository(e.db)).Credit(ctx, WalletCreditInput{
|
|
||||||
WalletEntry: WalletEntry{CustomerID: customer, Currency: constants.WalletCurrencyPoint, Type: constants.WalletTxTypeMigration,
|
|
||||||
Amount: 40000, ReferenceType: constants.WalletRefTypeLegacyPoints, ReferenceID: uuid.New(), Description: "Saldo awal"},
|
|
||||||
Lots: []WalletLotInput{{Amount: 40000, ExpiresAt: &expires}},
|
|
||||||
})
|
|
||||||
return err
|
|
||||||
}))
|
|
||||||
|
|
||||||
// Part of the order paid with EnakPoint, then the order is voided.
|
|
||||||
order := e.order(customer, 50000)
|
|
||||||
_, err := e.payPoints(order, 30000, e.code(customer))
|
|
||||||
require.NoError(t, err)
|
|
||||||
assert.Equal(t, int64(10000), e.balance(customer))
|
|
||||||
require.NoError(t, e.orders.VoidOrder(e.ctx, &models.VoidOrderRequest{OrderID: order, Type: "ALL", Reason: "batal"}, e.cashier))
|
|
||||||
|
|
||||||
assert.Equal(t, int64(30000), e.returned(order))
|
|
||||||
assert.Equal(t, int64(40000), e.balance(customer))
|
|
||||||
var expiry time.Time
|
|
||||||
require.NoError(t, e.db.Raw(`SELECT l.expires_at FROM wallet_lots l JOIN wallet_transactions t ON t.id = l.source_transaction_id
|
|
||||||
WHERE t.customer_id = ? AND t.type = 'PAYMENT_REFUND'`, customer).Scan(&expiry).Error)
|
|
||||||
assert.WithinDuration(t, expires, expiry, time.Second, "returned EnakPoint keep the expiry they had")
|
|
||||||
|
|
||||||
// Calling it again returns nothing more.
|
|
||||||
e.orders.onOrderRefunded(e.ctx, order)
|
|
||||||
assert.Equal(t, int64(30000), e.returned(order))
|
|
||||||
e.assertReconciled(customer)
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestPointRefund_PartialRefundFloors(t *testing.T) {
|
|
||||||
e := newPointPaymentEnv(t)
|
|
||||||
customer := e.customerWith(100000)
|
|
||||||
order := e.order(customer, 50000)
|
|
||||||
payment, err := e.payPoints(order, 50000, e.code(customer))
|
|
||||||
require.NoError(t, err)
|
|
||||||
|
|
||||||
// Rp 12.345,67 back at Rp 1 a point: 12.345 EnakPoint; the 67 sen are lost (Q13).
|
|
||||||
require.NoError(t, e.orders.RefundPayment(e.ctx, payment.ID, 12345.67, "sebagian", e.cashier))
|
|
||||||
assert.Equal(t, int64(12345), e.returned(order))
|
|
||||||
assert.Equal(t, int64(50000+12345), e.balance(customer))
|
|
||||||
e.assertReconciled(customer)
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestPointRefund_UsesTheFrozenValue(t *testing.T) {
|
|
||||||
e := newPointPaymentEnv(t)
|
|
||||||
settings := NewLoyaltySettingsProcessor(repository.NewLoyaltySettingsRepository(e.db), repository.NewTxManager(e.db))
|
|
||||||
setValue := func(v int64) {
|
|
||||||
s, err := settings.Organization(context.Background(), e.org)
|
|
||||||
require.NoError(t, err)
|
|
||||||
s.PointValue = v
|
|
||||||
_, _, err = settings.UpdateOrganization(context.Background(), e.org, e.cashier, *s)
|
|
||||||
require.NoError(t, err)
|
|
||||||
}
|
|
||||||
setValue(100)
|
|
||||||
|
|
||||||
customer := e.customerWith(1000)
|
|
||||||
order := e.order(customer, 50000)
|
|
||||||
payment, err := e.payPoints(order, 500, e.code(customer))
|
|
||||||
require.NoError(t, err)
|
|
||||||
assert.Equal(t, 50000.0, payment.Amount, "500 × Rp 100")
|
|
||||||
|
|
||||||
// The value changes before the refund; the customer still gets back what they used.
|
|
||||||
setValue(250)
|
|
||||||
require.NoError(t, e.orders.RefundPayment(e.ctx, payment.ID, 50000, "semua", e.cashier))
|
|
||||||
assert.Equal(t, int64(500), e.returned(order), "50.000 / the frozen Rp 100, not the new Rp 250")
|
|
||||||
assert.Equal(t, int64(1000), e.balance(customer))
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestPointRefund_NoCashForTheEnakPointPart(t *testing.T) {
|
|
||||||
e := newPointPaymentEnv(t)
|
|
||||||
customer := e.customerWith(100000)
|
|
||||||
order := e.order(customer, 50000)
|
|
||||||
_, err := e.payPoints(order, 20000, e.code(customer))
|
|
||||||
require.NoError(t, err)
|
|
||||||
_, err = e.orders.CreatePayment(e.ctx, &models.CreatePaymentRequest{OrderID: order, PaymentMethodID: e.cash, Amount: 30000})
|
|
||||||
require.NoError(t, err)
|
|
||||||
|
|
||||||
amount := 40000.0
|
|
||||||
err = e.orders.RefundOrder(e.ctx, order, &models.RefundOrderRequest{RefundAmount: &amount}, e.cashier)
|
|
||||||
assert.ErrorIs(t, err, ErrPointPaymentRejected, "Rp 40.000 in cash would include EnakPoint")
|
|
||||||
var refunded float64
|
|
||||||
require.NoError(t, e.db.Raw(`SELECT refund_amount FROM orders WHERE id = ?`, order).Scan(&refunded).Error)
|
|
||||||
assert.Zero(t, refunded, "nothing was written")
|
|
||||||
|
|
||||||
amount = 30000
|
|
||||||
require.NoError(t, e.orders.RefundOrder(e.ctx, order, &models.RefundOrderRequest{RefundAmount: &amount}, e.cashier), "the cash part can be refunded")
|
|
||||||
assert.Zero(t, e.returned(order), "and no EnakPoint came back for it")
|
|
||||||
}
|
|
||||||
|
|
||||||
// Giving back the EnakPoint part does not take earning back: that part never earned.
|
|
||||||
func TestPointRefund_DoesNotReverseEarning(t *testing.T) {
|
|
||||||
e := newPointPaymentEnv(t)
|
|
||||||
customer := e.customerWith(100000)
|
|
||||||
order := e.order(customer, 87500)
|
|
||||||
pointPayment, err := e.payPoints(order, 20000, e.code(customer))
|
|
||||||
require.NoError(t, err)
|
|
||||||
_, err = e.orders.CreatePayment(e.ctx, &models.CreatePaymentRequest{OrderID: order, PaymentMethodID: e.cash, Amount: 67500})
|
|
||||||
require.NoError(t, err)
|
|
||||||
earned := e.sum(`SELECT COALESCE(SUM(amount), 0) FROM wallet_transactions WHERE reference_id = ? AND type = 'EARN'`, order)
|
|
||||||
require.Equal(t, int64(675), earned)
|
|
||||||
|
|
||||||
require.NoError(t, e.orders.RefundPayment(e.ctx, pointPayment.ID, 20000, "kembali", e.cashier))
|
|
||||||
assert.Equal(t, int64(20000), e.returned(order))
|
|
||||||
reversed := e.sum(`SELECT COALESCE(SUM(-amount), 0) FROM wallet_transactions WHERE reference_id = ? AND type = 'EARN_REVERSAL'`, order)
|
|
||||||
assert.Zero(t, reversed, "the EnakPoint part never earned, so giving it back takes nothing")
|
|
||||||
e.assertReconciled(customer)
|
|
||||||
}
|
|
||||||
@@ -199,7 +199,7 @@ func (p *ProductRecipeProcessorImpl) entityToResponse(entity *entities.ProductRe
|
|||||||
Cost: entity.Product.Cost,
|
Cost: entity.Product.Cost,
|
||||||
BusinessType: string(entity.Product.BusinessType),
|
BusinessType: string(entity.Product.BusinessType),
|
||||||
ImageURL: entity.Product.ImageURL,
|
ImageURL: entity.Product.ImageURL,
|
||||||
PrinterType: entity.Product.PrinterType,
|
PrinterTypes: entity.Product.GetPrinterTypes(),
|
||||||
Metadata: entity.Product.Metadata,
|
Metadata: entity.Product.Metadata,
|
||||||
IsActive: entity.Product.IsActive,
|
IsActive: entity.Product.IsActive,
|
||||||
CreatedAt: entity.Product.CreatedAt,
|
CreatedAt: entity.Product.CreatedAt,
|
||||||
|
|||||||
@@ -11,12 +11,13 @@ import (
|
|||||||
"github.com/google/uuid"
|
"github.com/google/uuid"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Teams are the parent product categories, plus Pusat for spending that belongs to
|
// Teams are the parent product categories flagged is_team, plus Pusat for spending
|
||||||
// no single team. Both purchase orders and cash advances are charged to one, so the rules
|
// that belongs to no single team. Both purchase orders and cash advances are charged to
|
||||||
// for picking and storing a team live here rather than in either processor.
|
// one, so the rules for picking and storing a team live here rather than in either
|
||||||
|
// processor.
|
||||||
|
|
||||||
// listTeams returns the teams money can be charged to: the parent categories of the
|
// listTeams returns the teams money can be charged to: the team parent categories of
|
||||||
// outlet in scope, followed by Pusat. Pusat has no category row, so it is appended
|
// the outlet in scope, followed by Pusat. Pusat has no category row, so it is appended
|
||||||
// here rather than read from the database.
|
// here rather than read from the database.
|
||||||
func listTeams(ctx context.Context, categoryRepo CategoryRepository, organizationID uuid.UUID, outletID *uuid.UUID) (*models.ListPurchaseTeamsResponse, error) {
|
func listTeams(ctx context.Context, categoryRepo CategoryRepository, organizationID uuid.UUID, outletID *uuid.UUID) (*models.ListPurchaseTeamsResponse, error) {
|
||||||
categories, err := categoryRepo.ListParentCategories(ctx, organizationID, outletID)
|
categories, err := categoryRepo.ListParentCategories(ctx, organizationID, outletID)
|
||||||
@@ -26,6 +27,9 @@ func listTeams(ctx context.Context, categoryRepo CategoryRepository, organizatio
|
|||||||
|
|
||||||
teams := make([]models.PurchaseTeam, 0, len(categories)+1)
|
teams := make([]models.PurchaseTeam, 0, len(categories)+1)
|
||||||
for _, category := range categories {
|
for _, category := range categories {
|
||||||
|
if !category.IsTeam {
|
||||||
|
continue
|
||||||
|
}
|
||||||
categoryID := category.ID
|
categoryID := category.ID
|
||||||
teams = append(teams, models.PurchaseTeam{
|
teams = append(teams, models.PurchaseTeam{
|
||||||
Scope: constants.PurchaseTeamScopeCategory,
|
Scope: constants.PurchaseTeamScopeCategory,
|
||||||
@@ -75,6 +79,9 @@ func resolveTeamSelection(ctx context.Context, categoryRepo CategoryRepository,
|
|||||||
if category.ParentID != nil {
|
if category.ParentID != nil {
|
||||||
return nil, nil, fmt.Errorf("team must be a parent category")
|
return nil, nil, fmt.Errorf("team must be a parent category")
|
||||||
}
|
}
|
||||||
|
if !category.IsTeam {
|
||||||
|
return nil, nil, fmt.Errorf("category %s is not a team", category.Name)
|
||||||
|
}
|
||||||
// Categories without an outlet are shared, so only an outlet-specific
|
// Categories without an outlet are shared, so only an outlet-specific
|
||||||
// category has to match the outlet the record is booked against.
|
// category has to match the outlet the record is booked against.
|
||||||
if category.OutletID != nil && outletID != nil && *category.OutletID != *outletID {
|
if category.OutletID != nil && outletID != nil && *category.OutletID != *outletID {
|
||||||
|
|||||||
@@ -0,0 +1,64 @@
|
|||||||
|
package processor
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"apskel-pos-be/internal/constants"
|
||||||
|
"apskel-pos-be/internal/entities"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
"github.com/stretchr/testify/require"
|
||||||
|
)
|
||||||
|
|
||||||
|
// teamCategoryRepositoryStub serves the two lookups the team rules make. The embedded
|
||||||
|
// interface is left nil, so any other call panics and shows up in the test.
|
||||||
|
type teamCategoryRepositoryStub struct {
|
||||||
|
CategoryRepository
|
||||||
|
categories []*entities.Category
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *teamCategoryRepositoryStub) ListParentCategories(ctx context.Context, organizationID uuid.UUID, outletID *uuid.UUID) ([]*entities.Category, error) {
|
||||||
|
return s.categories, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *teamCategoryRepositoryStub) GetByID(ctx context.Context, id uuid.UUID) (*entities.Category, error) {
|
||||||
|
for _, category := range s.categories {
|
||||||
|
if category.ID == id {
|
||||||
|
return category, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil, errors.New("record not found")
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestListTeamsSkipsParentCategoriesThatAreNotTeams(t *testing.T) {
|
||||||
|
organizationID := uuid.New()
|
||||||
|
food := &entities.Category{ID: uuid.New(), OrganizationID: organizationID, Name: "Food", IsTeam: true}
|
||||||
|
merch := &entities.Category{ID: uuid.New(), OrganizationID: organizationID, Name: "Merchandise", IsTeam: false}
|
||||||
|
repo := &teamCategoryRepositoryStub{categories: []*entities.Category{food, merch}}
|
||||||
|
|
||||||
|
result, err := listTeams(context.Background(), repo, organizationID, nil)
|
||||||
|
require.NoError(t, err)
|
||||||
|
|
||||||
|
require.Len(t, result.Teams, 2)
|
||||||
|
require.Equal(t, "Food", result.Teams[0].Name)
|
||||||
|
require.Equal(t, &food.ID, result.Teams[0].CategoryID)
|
||||||
|
require.Equal(t, constants.PurchaseTeamCentralName, result.Teams[1].Name)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestResolveTeamSelectionRejectsParentCategoryThatIsNotATeam(t *testing.T) {
|
||||||
|
organizationID := uuid.New()
|
||||||
|
food := &entities.Category{ID: uuid.New(), OrganizationID: organizationID, Name: "Food", IsTeam: true}
|
||||||
|
merch := &entities.Category{ID: uuid.New(), OrganizationID: organizationID, Name: "Merchandise", IsTeam: false}
|
||||||
|
repo := &teamCategoryRepositoryStub{categories: []*entities.Category{food, merch}}
|
||||||
|
scope := constants.PurchaseTeamScopeCategory
|
||||||
|
|
||||||
|
resolvedScope, resolvedID, err := resolveTeamSelection(context.Background(), repo, organizationID, nil, &scope, &food.ID)
|
||||||
|
require.NoError(t, err)
|
||||||
|
require.Equal(t, constants.PurchaseTeamScopeCategory, *resolvedScope)
|
||||||
|
require.Equal(t, food.ID, *resolvedID)
|
||||||
|
|
||||||
|
_, _, err = resolveTeamSelection(context.Background(), repo, organizationID, nil, &scope, &merch.ID)
|
||||||
|
require.EqualError(t, err, "category Merchandise is not a team")
|
||||||
|
}
|
||||||
@@ -28,6 +28,10 @@ type organizationSettingsReader interface {
|
|||||||
Organization(ctx context.Context, organizationID uuid.UUID) (*models.OrganizationLoyaltySettings, error)
|
Organization(ctx context.Context, organizationID uuid.UUID) (*models.OrganizationLoyaltySettings, error)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type spendableReader interface {
|
||||||
|
SpendableBalances(ctx context.Context, customerID uuid.UUID, asOf time.Time) (map[string]int64, error)
|
||||||
|
}
|
||||||
|
|
||||||
// WalletExchangeProcessor exchanges EnakCoin into EnakPoint (docs/prd-point-coin.md
|
// WalletExchangeProcessor exchanges EnakCoin into EnakPoint (docs/prd-point-coin.md
|
||||||
// F4, K3). It is one way only; nothing turns EnakPoint back into EnakCoin.
|
// F4, K3). It is one way only; nothing turns EnakPoint back into EnakCoin.
|
||||||
type WalletExchangeProcessor struct {
|
type WalletExchangeProcessor struct {
|
||||||
|
|||||||
@@ -63,7 +63,7 @@ func TestWalletExpiry_ExpiresWhatIsDueAndTellsTheCustomer(t *testing.T) {
|
|||||||
e.credit(t, earn(a, 30, nil)) // never
|
e.credit(t, earn(a, 30, nil)) // never
|
||||||
e.earnCoins(t, a, 4, e.at(-time.Minute))
|
e.earnCoins(t, a, 4, e.at(-time.Minute))
|
||||||
// A payment already used part of the first lot; only the rest expires.
|
// A payment already used part of the first lot; only the rest expires.
|
||||||
_, err := e.p.Debit(e.ctx, WalletDebitInput{WalletEntry: pay(a, 20).WalletEntry, PreferredLotIDs: []uuid.UUID{due.Lots[0].ID}})
|
_, err := e.p.Debit(e.ctx, WalletDebitInput{WalletEntry: redeem(a, 20).WalletEntry, PreferredLotIDs: []uuid.UUID{due.Lots[0].ID}})
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
|
|
||||||
notifier := ¬ifierFake{}
|
notifier := ¬ifierFake{}
|
||||||
|
|||||||
@@ -180,7 +180,7 @@ func TestWalletTrace_AgainstPostgres(t *testing.T) {
|
|||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
var payment *WalletResult
|
var payment *WalletResult
|
||||||
require.NoError(t, txm.WithTransaction(context.Background(), func(ctx context.Context) error {
|
require.NoError(t, txm.WithTransaction(context.Background(), func(ctx context.Context) error {
|
||||||
payment, err = wallet.Debit(ctx, pay(b, 30))
|
payment, err = wallet.Debit(ctx, redeem(b, 30))
|
||||||
return err
|
return err
|
||||||
}))
|
}))
|
||||||
|
|
||||||
|
|||||||
@@ -485,8 +485,6 @@ type walletTypeRule struct {
|
|||||||
var walletTypeRules = map[string]walletTypeRule{
|
var walletTypeRules = map[string]walletTypeRule{
|
||||||
constants.WalletTxTypeEarn: {credit: true, referenceTypes: []string{constants.WalletRefTypeOrder}, needsOutlet: true},
|
constants.WalletTxTypeEarn: {credit: true, referenceTypes: []string{constants.WalletRefTypeOrder}, needsOutlet: true},
|
||||||
constants.WalletTxTypeEarnReversal: {debit: true, referenceTypes: []string{constants.WalletRefTypeOrder}, needsOutlet: true, needsReverses: true},
|
constants.WalletTxTypeEarnReversal: {debit: true, referenceTypes: []string{constants.WalletRefTypeOrder}, needsOutlet: true, needsReverses: true},
|
||||||
constants.WalletTxTypePayment: {debit: true, currency: constants.WalletCurrencyPoint, referenceTypes: []string{constants.WalletRefTypePayment}, needsOutlet: true},
|
|
||||||
constants.WalletTxTypePaymentRefund: {credit: true, currency: constants.WalletCurrencyPoint, referenceTypes: []string{constants.WalletRefTypePayment}, needsOutlet: true, needsReverses: true},
|
|
||||||
constants.WalletTxTypeExchangeOut: {debit: true, currency: constants.WalletCurrencyCoin, referenceTypes: []string{constants.WalletRefTypeWalletTx}, needsGroup: true},
|
constants.WalletTxTypeExchangeOut: {debit: true, currency: constants.WalletCurrencyCoin, referenceTypes: []string{constants.WalletRefTypeWalletTx}, needsGroup: true},
|
||||||
constants.WalletTxTypeExchangeIn: {credit: true, currency: constants.WalletCurrencyPoint, referenceTypes: []string{constants.WalletRefTypeWalletTx}, needsGroup: true},
|
constants.WalletTxTypeExchangeIn: {credit: true, currency: constants.WalletCurrencyPoint, referenceTypes: []string{constants.WalletRefTypeWalletTx}, needsGroup: true},
|
||||||
constants.WalletTxTypeTransferOut: {debit: true, referenceTypes: []string{constants.WalletRefTypeWalletTx}, needsGroup: true, needsCounter: true},
|
constants.WalletTxTypeTransferOut: {debit: true, referenceTypes: []string{constants.WalletRefTypeWalletTx}, needsGroup: true, needsCounter: true},
|
||||||
|
|||||||
@@ -106,7 +106,7 @@ func TestWalletProcessor_AgainstPostgres(t *testing.T) {
|
|||||||
|
|
||||||
// Overdraw fails and rolls back cleanly.
|
// Overdraw fails and rolls back cleanly.
|
||||||
err = txm.WithTransaction(context.Background(), func(ctx context.Context) error {
|
err = txm.WithTransaction(context.Background(), func(ctx context.Context) error {
|
||||||
_, err := p.Debit(ctx, pay(b, 121))
|
_, err := p.Debit(ctx, redeem(b, 121))
|
||||||
return err
|
return err
|
||||||
})
|
})
|
||||||
assert.ErrorIs(t, err, repository.ErrWalletInsufficientBalance)
|
assert.ErrorIs(t, err, repository.ErrWalletInsufficientBalance)
|
||||||
|
|||||||
@@ -300,16 +300,16 @@ func earn(customerID uuid.UUID, amount int64, expiresAt *time.Time) WalletCredit
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func pay(customerID uuid.UUID, amount int64) WalletDebitInput {
|
func redeem(customerID uuid.UUID, amount int64) WalletDebitInput {
|
||||||
return WalletDebitInput{WalletEntry: WalletEntry{
|
return WalletDebitInput{WalletEntry: WalletEntry{
|
||||||
CustomerID: customerID,
|
CustomerID: customerID,
|
||||||
Currency: constants.WalletCurrencyPoint,
|
Currency: constants.WalletCurrencyPoint,
|
||||||
Type: constants.WalletTxTypePayment,
|
Type: constants.WalletTxTypeRewardRedeem,
|
||||||
Amount: amount,
|
Amount: amount,
|
||||||
ReferenceType: constants.WalletRefTypePayment,
|
ReferenceType: constants.WalletRefTypeRewardRedemption,
|
||||||
ReferenceID: uuid.New(),
|
ReferenceID: uuid.New(),
|
||||||
OutletID: ptr(uuid.New()),
|
OutletID: ptr(uuid.New()),
|
||||||
Description: "Bayar",
|
Description: "Tukar voucher",
|
||||||
}}
|
}}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -385,7 +385,7 @@ func TestWalletProcessor_DebitAcrossSeveralLots(t *testing.T) {
|
|||||||
second := e.credit(t, earn(c, 50, e.at(2*time.Hour))).Lots[0]
|
second := e.credit(t, earn(c, 50, e.at(2*time.Hour))).Lots[0]
|
||||||
third := e.credit(t, earn(c, 40, e.at(3*time.Hour))).Lots[0]
|
third := e.credit(t, earn(c, 40, e.at(3*time.Hour))).Lots[0]
|
||||||
|
|
||||||
res, err := e.p.Debit(e.ctx, pay(c, 70))
|
res, err := e.p.Debit(e.ctx, redeem(c, 70))
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
|
|
||||||
assert.Equal(t, int64(-70), res.Transaction.Amount)
|
assert.Equal(t, int64(-70), res.Transaction.Amount)
|
||||||
@@ -415,7 +415,7 @@ func TestWalletProcessor_DebitFollowsLotOrder(t *testing.T) {
|
|||||||
|
|
||||||
var order []uuid.UUID
|
var order []uuid.UUID
|
||||||
for i := 0; i < 4; i++ {
|
for i := 0; i < 4; i++ {
|
||||||
res, err := e.p.Debit(e.ctx, pay(c, 10))
|
res, err := e.p.Debit(e.ctx, redeem(c, 10))
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
require.Len(t, res.Allocations, 1)
|
require.Len(t, res.Allocations, 1)
|
||||||
order = append(order, res.Allocations[0].LotID)
|
order = append(order, res.Allocations[0].LotID)
|
||||||
@@ -425,7 +425,7 @@ func TestWalletProcessor_DebitFollowsLotOrder(t *testing.T) {
|
|||||||
// The expired lot still counts in the balance until the expiry job removes it,
|
// The expired lot still counts in the balance until the expiry job removes it,
|
||||||
// but it cannot be spent (§7.3).
|
// but it cannot be spent (§7.3).
|
||||||
assert.Equal(t, int64(10), e.balance(t, c))
|
assert.Equal(t, int64(10), e.balance(t, c))
|
||||||
_, err := e.p.Debit(e.ctx, pay(c, 10))
|
_, err := e.p.Debit(e.ctx, redeem(c, 10))
|
||||||
assert.ErrorIs(t, err, repository.ErrWalletInsufficientBalance)
|
assert.ErrorIs(t, err, repository.ErrWalletInsufficientBalance)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -434,14 +434,14 @@ func TestWalletProcessor_DebitOverBalanceChangesNothing(t *testing.T) {
|
|||||||
c := e.customer()
|
c := e.customer()
|
||||||
e.credit(t, earn(c, 50, nil))
|
e.credit(t, earn(c, 50, nil))
|
||||||
|
|
||||||
_, err := e.p.Debit(e.ctx, pay(c, 51))
|
_, err := e.p.Debit(e.ctx, redeem(c, 51))
|
||||||
assert.ErrorIs(t, err, repository.ErrWalletInsufficientBalance)
|
assert.ErrorIs(t, err, repository.ErrWalletInsufficientBalance)
|
||||||
assert.Equal(t, int64(50), e.balance(t, c))
|
assert.Equal(t, int64(50), e.balance(t, c))
|
||||||
assert.Len(t, e.repo.transactions, 1)
|
assert.Len(t, e.repo.transactions, 1)
|
||||||
assert.Empty(t, e.repo.allocations)
|
assert.Empty(t, e.repo.allocations)
|
||||||
|
|
||||||
// A customer who never had a wallet has nothing to spend.
|
// A customer who never had a wallet has nothing to spend.
|
||||||
_, err = e.p.Debit(e.ctx, pay(e.customer(), 1))
|
_, err = e.p.Debit(e.ctx, redeem(e.customer(), 1))
|
||||||
assert.ErrorIs(t, err, repository.ErrWalletInsufficientBalance)
|
assert.ErrorIs(t, err, repository.ErrWalletInsufficientBalance)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -467,7 +467,7 @@ func TestWalletProcessor_DebitUpToWithShortfall(t *testing.T) {
|
|||||||
e := newWalletTestEnv(t)
|
e := newWalletTestEnv(t)
|
||||||
c := e.customer()
|
c := e.customer()
|
||||||
earned := e.credit(t, earn(c, 100, nil))
|
earned := e.credit(t, earn(c, 100, nil))
|
||||||
_, err := e.p.Debit(e.ctx, pay(c, 70))
|
_, err := e.p.Debit(e.ctx, redeem(c, 70))
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
|
|
||||||
res, err := e.p.DebitUpTo(e.ctx, reversal(c, 100, earned))
|
res, err := e.p.DebitUpTo(e.ctx, reversal(c, 100, earned))
|
||||||
@@ -510,7 +510,7 @@ func TestWalletProcessor_DebitRejectsSomeoneElsesLot(t *testing.T) {
|
|||||||
e.credit(t, earn(a, 10, nil))
|
e.credit(t, earn(a, 10, nil))
|
||||||
other := e.credit(t, earn(b, 10, nil))
|
other := e.credit(t, earn(b, 10, nil))
|
||||||
|
|
||||||
in := pay(a, 5)
|
in := redeem(a, 5)
|
||||||
in.PreferredLotIDs = []uuid.UUID{other.Lots[0].ID}
|
in.PreferredLotIDs = []uuid.UUID{other.Lots[0].ID}
|
||||||
_, err := e.p.Debit(e.ctx, in)
|
_, err := e.p.Debit(e.ctx, in)
|
||||||
assert.ErrorIs(t, err, ErrWalletInvalidEntry)
|
assert.ErrorIs(t, err, ErrWalletInvalidEntry)
|
||||||
@@ -567,7 +567,7 @@ func TestWalletProcessor_IdempotentDebit(t *testing.T) {
|
|||||||
c := e.customer()
|
c := e.customer()
|
||||||
e.credit(t, earn(c, 30, e.at(time.Hour)))
|
e.credit(t, earn(c, 30, e.at(time.Hour)))
|
||||||
e.credit(t, earn(c, 30, nil))
|
e.credit(t, earn(c, 30, nil))
|
||||||
in := pay(c, 40)
|
in := redeem(c, 40)
|
||||||
in.IdempotencyKey = "pay:1"
|
in.IdempotencyKey = "pay:1"
|
||||||
|
|
||||||
first, err := e.p.Debit(e.ctx, in)
|
first, err := e.p.Debit(e.ctx, in)
|
||||||
@@ -585,7 +585,7 @@ func TestWalletProcessor_IdempotentDebitUpToKeepsShortfall(t *testing.T) {
|
|||||||
e := newWalletTestEnv(t)
|
e := newWalletTestEnv(t)
|
||||||
c := e.customer()
|
c := e.customer()
|
||||||
earned := e.credit(t, earn(c, 100, nil))
|
earned := e.credit(t, earn(c, 100, nil))
|
||||||
_, err := e.p.Debit(e.ctx, pay(c, 60))
|
_, err := e.p.Debit(e.ctx, redeem(c, 60))
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
in := reversal(c, 100, earned)
|
in := reversal(c, 100, earned)
|
||||||
in.IdempotencyKey = "reverse:order-1"
|
in.IdempotencyKey = "reverse:order-1"
|
||||||
@@ -614,7 +614,7 @@ func TestWalletProcessor_IdempotencyKeyReusedForAnotherOperation(t *testing.T) {
|
|||||||
_, err := e.p.Credit(e.ctx, other)
|
_, err := e.p.Credit(e.ctx, other)
|
||||||
assert.ErrorIs(t, err, ErrWalletIdempotencyConflict)
|
assert.ErrorIs(t, err, ErrWalletIdempotencyConflict)
|
||||||
|
|
||||||
debit := pay(c, 100)
|
debit := redeem(c, 100)
|
||||||
debit.IdempotencyKey = "k"
|
debit.IdempotencyKey = "k"
|
||||||
_, err = e.p.Debit(e.ctx, debit)
|
_, err = e.p.Debit(e.ctx, debit)
|
||||||
assert.ErrorIs(t, err, ErrWalletIdempotencyConflict)
|
assert.ErrorIs(t, err, ErrWalletIdempotencyConflict)
|
||||||
@@ -673,8 +673,8 @@ func TestWalletProcessor_RejectsEntriesThatBreakTheTypeRules(t *testing.T) {
|
|||||||
credits := map[string]func(*WalletCreditInput){
|
credits := map[string]func(*WalletCreditInput){
|
||||||
"unknown type": func(in *WalletCreditInput) { in.Type = "BONUS" },
|
"unknown type": func(in *WalletCreditInput) { in.Type = "BONUS" },
|
||||||
"debit-only type as credit": func(in *WalletCreditInput) {
|
"debit-only type as credit": func(in *WalletCreditInput) {
|
||||||
in.Type = constants.WalletTxTypePayment
|
in.Type = constants.WalletTxTypeRewardRedeem
|
||||||
in.ReferenceType = constants.WalletRefTypePayment
|
in.ReferenceType = constants.WalletRefTypeRewardRedemption
|
||||||
},
|
},
|
||||||
"unknown currency": func(in *WalletCreditInput) { in.Currency = "GOLD" },
|
"unknown currency": func(in *WalletCreditInput) { in.Currency = "GOLD" },
|
||||||
"zero amount": func(in *WalletCreditInput) { in.Amount = 0; in.Lots = nil },
|
"zero amount": func(in *WalletCreditInput) { in.Amount = 0; in.Lots = nil },
|
||||||
@@ -701,10 +701,6 @@ func TestWalletProcessor_RejectsEntriesThatBreakTheTypeRules(t *testing.T) {
|
|||||||
in.ReferenceType = constants.WalletRefTypeWalletTx
|
in.ReferenceType = constants.WalletRefTypeWalletTx
|
||||||
in.CounterpartyCustomerID = ptr(uuid.New())
|
in.CounterpartyCustomerID = ptr(uuid.New())
|
||||||
},
|
},
|
||||||
"PAYMENT_REFUND without source": func(in *WalletCreditInput) {
|
|
||||||
in.Type = constants.WalletTxTypePaymentRefund
|
|
||||||
in.ReferenceType = constants.WalletRefTypePayment
|
|
||||||
},
|
|
||||||
"ADJUSTMENT without reason": func(in *WalletCreditInput) {
|
"ADJUSTMENT without reason": func(in *WalletCreditInput) {
|
||||||
in.Type = constants.WalletTxTypeAdjustment
|
in.Type = constants.WalletTxTypeAdjustment
|
||||||
in.ReferenceType = constants.WalletRefTypeUser
|
in.ReferenceType = constants.WalletRefTypeUser
|
||||||
@@ -744,7 +740,7 @@ func TestWalletProcessor_RejectsEntriesThatBreakTheTypeRules(t *testing.T) {
|
|||||||
in.Type = constants.WalletTxTypeMigration
|
in.Type = constants.WalletTxTypeMigration
|
||||||
in.ReferenceType = constants.WalletRefTypeLegacyPoints
|
in.ReferenceType = constants.WalletRefTypeLegacyPoints
|
||||||
},
|
},
|
||||||
"PAYMENT in COIN": func(in *WalletDebitInput) { in.Currency = constants.WalletCurrencyCoin },
|
"REWARD_REDEEM in COIN": func(in *WalletDebitInput) { in.Currency = constants.WalletCurrencyCoin },
|
||||||
"GAME_SPEND in POINT": func(in *WalletDebitInput) {
|
"GAME_SPEND in POINT": func(in *WalletDebitInput) {
|
||||||
in.Type = constants.WalletTxTypeGameSpend
|
in.Type = constants.WalletTxTypeGameSpend
|
||||||
in.ReferenceType = constants.WalletRefTypeGamePlay
|
in.ReferenceType = constants.WalletRefTypeGamePlay
|
||||||
@@ -772,7 +768,7 @@ func TestWalletProcessor_RejectsEntriesThatBreakTheTypeRules(t *testing.T) {
|
|||||||
e := newWalletTestEnv(t)
|
e := newWalletTestEnv(t)
|
||||||
e.repo.customers[c] = e.org
|
e.repo.customers[c] = e.org
|
||||||
e.credit(t, earn(c, 100, nil))
|
e.credit(t, earn(c, 100, nil))
|
||||||
in := pay(c, 10)
|
in := redeem(c, 10)
|
||||||
mutate(&in)
|
mutate(&in)
|
||||||
_, err := e.p.Debit(e.ctx, in)
|
_, err := e.p.Debit(e.ctx, in)
|
||||||
assert.ErrorIs(t, err, ErrWalletInvalidEntry)
|
assert.ErrorIs(t, err, ErrWalletInvalidEntry)
|
||||||
|
|||||||
@@ -87,8 +87,8 @@ func TestWalletQueryProcessor_SummaryShowsWhereEachRowCameFromOrWent(t *testing.
|
|||||||
{Currency: constants.WalletCurrencyPoint, Date: "2026-07-01", Amount: 100},
|
{Currency: constants.WalletCurrencyPoint, Date: "2026-07-01", Amount: 100},
|
||||||
},
|
},
|
||||||
transactions: []entities.WalletTransaction{
|
transactions: []entities.WalletTransaction{
|
||||||
{ID: payID, Currency: constants.WalletCurrencyPoint, Type: constants.WalletTxTypePayment, Amount: -50, BalanceAfter: 250,
|
{ID: payID, Currency: constants.WalletCurrencyPoint, Type: constants.WalletTxTypeRewardRedeem, Amount: -50, BalanceAfter: 250,
|
||||||
ReferenceType: constants.WalletRefTypePayment, ReferenceID: payment, Description: "Bayar #ORD-1", CreatedAt: created.Add(time.Hour),
|
ReferenceType: constants.WalletRefTypeRewardRedemption, ReferenceID: payment, Description: "Tukar voucher", CreatedAt: created.Add(time.Hour),
|
||||||
CounterpartyCustomerID: ptr(uuid.New()), Metadata: entities.Metadata{"point_value": 100}},
|
CounterpartyCustomerID: ptr(uuid.New()), Metadata: entities.Metadata{"point_value": 100}},
|
||||||
{ID: earnID, Currency: constants.WalletCurrencyPoint, Type: constants.WalletTxTypeEarn, Amount: 300, BalanceAfter: 300,
|
{ID: earnID, Currency: constants.WalletCurrencyPoint, Type: constants.WalletTxTypeEarn, Amount: 300, BalanceAfter: 300,
|
||||||
ReferenceType: constants.WalletRefTypeOrder, ReferenceID: order, Description: "Belanja #ORD-1", CreatedAt: created},
|
ReferenceType: constants.WalletRefTypeOrder, ReferenceID: order, Description: "Belanja #ORD-1", CreatedAt: created},
|
||||||
@@ -112,7 +112,7 @@ func TestWalletQueryProcessor_SummaryShowsWhereEachRowCameFromOrWent(t *testing.
|
|||||||
|
|
||||||
require.Len(t, data.RecentTransactions, 2)
|
require.Len(t, data.RecentTransactions, 2)
|
||||||
pay, earn := data.RecentTransactions[0], data.RecentTransactions[1]
|
pay, earn := data.RecentTransactions[0], data.RecentTransactions[1]
|
||||||
assert.Equal(t, &models.CustomerWalletTransactionRef{Type: constants.WalletRefTypePayment, ID: payment}, pay.Destination)
|
assert.Equal(t, &models.CustomerWalletTransactionRef{Type: constants.WalletRefTypeRewardRedemption, ID: payment}, pay.Destination)
|
||||||
assert.Nil(t, pay.Source)
|
assert.Nil(t, pay.Source)
|
||||||
assert.Empty(t, pay.Lots)
|
assert.Empty(t, pay.Lots)
|
||||||
assert.Equal(t, &models.CustomerWalletTransactionRef{Type: constants.WalletRefTypeOrder, ID: order}, earn.Source)
|
assert.Equal(t, &models.CustomerWalletTransactionRef{Type: constants.WalletRefTypeOrder, ID: order}, earn.Source)
|
||||||
@@ -124,7 +124,7 @@ func TestWalletQueryProcessor_SummaryShowsWhereEachRowCameFromOrWent(t *testing.
|
|||||||
assert.Equal(t, int64(250), data.TotalPoints)
|
assert.Equal(t, int64(250), data.TotalPoints)
|
||||||
require.Len(t, data.PointsHistory, 2)
|
require.Len(t, data.PointsHistory, 2)
|
||||||
assert.Equal(t, int64(-50), data.PointsHistory[0].Points)
|
assert.Equal(t, int64(-50), data.PointsHistory[0].Points)
|
||||||
assert.Equal(t, constants.WalletTxTypePayment, data.PointsHistory[0].Type)
|
assert.Equal(t, constants.WalletTxTypeRewardRedeem, data.PointsHistory[0].Type)
|
||||||
assert.Equal(t, created.Add(time.Hour), data.LastUpdated)
|
assert.Equal(t, created.Add(time.Hour), data.LastUpdated)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -181,7 +181,7 @@ func TestWalletQueryProcessor_TransactionsQuery(t *testing.T) {
|
|||||||
|
|
||||||
repo := &walletQueryRepoFake{org: uuid.New(), total: 45}
|
repo := &walletQueryRepoFake{org: uuid.New(), total: 45}
|
||||||
page, err := newWalletQueryTest(repo, orgSettingsFake{}).Transactions(context.Background(), customer, models.ListCustomerWalletTransactionsQuery{
|
page, err := newWalletQueryTest(repo, orgSettingsFake{}).Transactions(context.Background(), customer, models.ListCustomerWalletTransactionsQuery{
|
||||||
Page: 3, Limit: 10, Currency: "point", Type: "earn, PAYMENT", From: "2026-05-01", To: "2026-05-31",
|
Page: 3, Limit: 10, Currency: "point", Type: "earn, REWARD_REDEEM", From: "2026-05-01", To: "2026-05-31",
|
||||||
})
|
})
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
assert.Equal(t, models.Pagination{Page: 3, Limit: 10, Total: 45, TotalPages: 5}, page.Pagination)
|
assert.Equal(t, models.Pagination{Page: 3, Limit: 10, Total: 45, TotalPages: 5}, page.Pagination)
|
||||||
@@ -192,7 +192,7 @@ func TestWalletQueryProcessor_TransactionsQuery(t *testing.T) {
|
|||||||
assert.Equal(t, 20, f.Offset)
|
assert.Equal(t, 20, f.Offset)
|
||||||
assert.Equal(t, 10, f.Limit)
|
assert.Equal(t, 10, f.Limit)
|
||||||
assert.Equal(t, constants.WalletCurrencyPoint, f.Currency)
|
assert.Equal(t, constants.WalletCurrencyPoint, f.Currency)
|
||||||
assert.Equal(t, []string{constants.WalletTxTypeEarn, constants.WalletTxTypePayment}, f.Types)
|
assert.Equal(t, []string{constants.WalletTxTypeEarn, constants.WalletTxTypeRewardRedeem}, f.Types)
|
||||||
assert.True(t, f.From.Equal(time.Date(2026, 5, 1, 0, 0, 0, 0, jakarta)))
|
assert.True(t, f.From.Equal(time.Date(2026, 5, 1, 0, 0, 0, 0, jakarta)))
|
||||||
assert.True(t, f.To.Equal(time.Date(2026, 6, 1, 0, 0, 0, 0, jakarta)), "to covers the whole last day")
|
assert.True(t, f.To.Equal(time.Date(2026, 6, 1, 0, 0, 0, 0, jakarta)), "to covers the whole last day")
|
||||||
|
|
||||||
|
|||||||
@@ -82,8 +82,8 @@ func findRow(t *testing.T, e *walletMoveEnv, customerID uuid.UUID, txType string
|
|||||||
}
|
}
|
||||||
|
|
||||||
// The example of §8: A has 100 from #ORD-1 and 50 from #ORD-2, sends 120 to B, and B
|
// The example of §8: A has 100 from #ORD-1 and 50 from #ORD-2, sends 120 to B, and B
|
||||||
// pays 30. Tracing B's payment leads to A's order #ORD-1.
|
// redeems 30. Tracing B's redemption leads to A's order #ORD-1.
|
||||||
func TestWalletTrace_PaymentLeadsBackToTheSendersOrder(t *testing.T) {
|
func TestWalletTrace_RedemptionLeadsBackToTheSendersOrder(t *testing.T) {
|
||||||
e := newWalletMoveEnv(t)
|
e := newWalletMoveEnv(t)
|
||||||
a := e.member("Anita", "081200005678")
|
a := e.member("Anita", "081200005678")
|
||||||
b := e.member("Budi Santoso", "081234561234")
|
b := e.member("Budi Santoso", "081234561234")
|
||||||
@@ -95,14 +95,14 @@ func TestWalletTrace_PaymentLeadsBackToTheSendersOrder(t *testing.T) {
|
|||||||
e.credit(t, ord2)
|
e.credit(t, ord2)
|
||||||
_, err := e.transfers(nil).Transfer(e.ctx, a, sendPoints(120, "081234561234"), "482913", "key-1", models.CustomerPinRequestInfo{})
|
_, err := e.transfers(nil).Transfer(e.ctx, a, sendPoints(120, "081234561234"), "482913", "key-1", models.CustomerPinRequestInfo{})
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
payment, err := e.p.Debit(e.ctx, pay(b, 30))
|
payment, err := e.p.Debit(e.ctx, redeem(b, 30))
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
|
|
||||||
p := NewWalletTraceProcessor(walletTraceRepoFake{e})
|
p := NewWalletTraceProcessor(walletTraceRepoFake{e})
|
||||||
trace, err := p.Trace(e.ctx, e.org, payment.Transaction.ID)
|
trace, err := p.Trace(e.ctx, e.org, payment.Transaction.ID)
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
|
|
||||||
assert.Equal(t, constants.WalletTxTypePayment, trace.Transaction.Type)
|
assert.Equal(t, constants.WalletTxTypeRewardRedeem, trace.Transaction.Type)
|
||||||
assert.Equal(t, "Budi Santoso", trace.Transaction.Customer.Name)
|
assert.Equal(t, "Budi Santoso", trace.Transaction.Customer.Name)
|
||||||
require.Len(t, trace.Lots, 1)
|
require.Len(t, trace.Lots, 1)
|
||||||
assert.Equal(t, int64(30), trace.Lots[0].Amount)
|
assert.Equal(t, int64(30), trace.Lots[0].Amount)
|
||||||
|
|||||||
@@ -99,8 +99,7 @@ func (r *AnalyticsRepositoryImpl) GetPaymentMethodAnalytics(ctx context.Context,
|
|||||||
pm.type as payment_method_type,
|
pm.type as payment_method_type,
|
||||||
COALESCE(SUM(p.amount), 0) as total_amount,
|
COALESCE(SUM(p.amount), 0) as total_amount,
|
||||||
COUNT(DISTINCT p.order_id) as order_count,
|
COUNT(DISTINCT p.order_id) as order_count,
|
||||||
COUNT(p.id) as payment_count,
|
COUNT(p.id) as payment_count
|
||||||
COALESCE(SUM(p.points_used), 0) as points_used
|
|
||||||
`).
|
`).
|
||||||
Joins("JOIN payment_methods pm ON p.payment_method_id = pm.id").
|
Joins("JOIN payment_methods pm ON p.payment_method_id = pm.id").
|
||||||
Joins("JOIN orders o ON p.order_id = o.id").
|
Joins("JOIN orders o ON p.order_id = o.id").
|
||||||
@@ -600,6 +599,7 @@ func (r *AnalyticsRepositoryImpl) GetProductAnalyticsPerParentCategory(ctx conte
|
|||||||
Select(`
|
Select(`
|
||||||
pc.id as parent_category_id,
|
pc.id as parent_category_id,
|
||||||
pc.name as parent_category_name,
|
pc.name as parent_category_name,
|
||||||
|
COALESCE(pc.owner_fee_percent, ?) as owner_fee_percent,
|
||||||
COALESCE(SUM(CASE WHEN oi.is_fully_refunded = false THEN oi.total_price - COALESCE(oi.refund_amount, 0) ELSE 0 END), 0) as total_revenue,
|
COALESCE(SUM(CASE WHEN oi.is_fully_refunded = false THEN oi.total_price - COALESCE(oi.refund_amount, 0) ELSE 0 END), 0) as total_revenue,
|
||||||
COALESCE(SUM(CASE WHEN oi.is_fully_refunded = false THEN oi.quantity - COALESCE(oi.refund_quantity, 0) ELSE 0 END), 0) as total_quantity,
|
COALESCE(SUM(CASE WHEN oi.is_fully_refunded = false THEN oi.quantity - COALESCE(oi.refund_quantity, 0) ELSE 0 END), 0) as total_quantity,
|
||||||
COUNT(DISTINCT c.id) as category_count,
|
COUNT(DISTINCT c.id) as category_count,
|
||||||
@@ -608,11 +608,13 @@ func (r *AnalyticsRepositoryImpl) GetProductAnalyticsPerParentCategory(ctx conte
|
|||||||
COALESCE(SUM(CASE WHEN oi.is_fully_refunded = false THEN COALESCE(shpp.hpp_per_unit, p.cost, 0) * `+billableQtyNet+` ELSE 0 END), 0) as total_standard_hpp,
|
COALESCE(SUM(CASE WHEN oi.is_fully_refunded = false THEN COALESCE(shpp.hpp_per_unit, p.cost, 0) * `+billableQtyNet+` ELSE 0 END), 0) as total_standard_hpp,
|
||||||
COALESCE(SUM(CASE WHEN oi.is_fully_refunded = false THEN oi.total_cost * ((oi.quantity - COALESCE(oi.refund_quantity, 0))::float / NULLIF(oi.quantity, 0)) ELSE 0 END), 0) as total_fifo_hpp,
|
COALESCE(SUM(CASE WHEN oi.is_fully_refunded = false THEN oi.total_cost * ((oi.quantity - COALESCE(oi.refund_quantity, 0))::float / NULLIF(oi.quantity, 0)) ELSE 0 END), 0) as total_fifo_hpp,
|
||||||
COALESCE(SUM(CASE WHEN oi.is_fully_refunded = false THEN COALESCE(mahpp.hpp_per_unit, p.cost, 0) * `+billableQtyNet+` ELSE 0 END), 0) as total_moving_average_hpp
|
COALESCE(SUM(CASE WHEN oi.is_fully_refunded = false THEN COALESCE(mahpp.hpp_per_unit, p.cost, 0) * `+billableQtyNet+` ELSE 0 END), 0) as total_moving_average_hpp
|
||||||
`).
|
`, constants.BudgetLimitOwnerPercent).
|
||||||
Joins("JOIN products p ON oi.product_id = p.id").
|
Joins("JOIN products p ON oi.product_id = p.id").
|
||||||
Joins("JOIN categories c ON p.category_id = c.id").
|
Joins("JOIN categories c ON p.category_id = c.id").
|
||||||
// Categories without a parent roll up to themselves, so top-level categories still appear
|
// Categories without a parent roll up to themselves, so top-level categories still appear
|
||||||
Joins("JOIN categories pc ON pc.id = COALESCE(c.parent_id, c.id)").
|
Joins("JOIN categories pc ON pc.id = COALESCE(c.parent_id, c.id)").
|
||||||
|
// Profit sharing only covers the parent categories that are teams
|
||||||
|
Where("pc.is_team = ?", true).
|
||||||
Joins("JOIN orders o ON oi.order_id = o.id").
|
Joins("JOIN orders o ON oi.order_id = o.id").
|
||||||
Joins("LEFT JOIN (SELECT pr.product_id, SUM(pr.quantity * (1 + COALESCE(pr.waste_percentage, 0)/100.0) * i.cost) as hpp_per_unit FROM product_recipes pr JOIN ingredients i ON pr.ingredient_id = i.id GROUP BY pr.product_id) shpp ON shpp.product_id = p.id").
|
Joins("LEFT JOIN (SELECT pr.product_id, SUM(pr.quantity * (1 + COALESCE(pr.waste_percentage, 0)/100.0) * i.cost) as hpp_per_unit FROM product_recipes pr JOIN ingredients i ON pr.ingredient_id = i.id GROUP BY pr.product_id) shpp ON shpp.product_id = p.id").
|
||||||
Joins("LEFT JOIN (?) mahpp ON mahpp.product_id = p.id",
|
Joins("LEFT JOIN (?) mahpp ON mahpp.product_id = p.id",
|
||||||
@@ -640,13 +642,59 @@ func (r *AnalyticsRepositoryImpl) GetProductAnalyticsPerParentCategory(ctx conte
|
|||||||
query = r.resolveOutletID(query, outletID, "o.outlet_id")
|
query = r.resolveOutletID(query, outletID, "o.outlet_id")
|
||||||
|
|
||||||
err := query.
|
err := query.
|
||||||
Group("pc.id, pc.name").
|
Group("pc.id, pc.name, pc.owner_fee_percent").
|
||||||
Order("pc.name ASC").
|
Order("pc.name ASC").
|
||||||
Scan(&results).Error
|
Scan(&results).Error
|
||||||
|
if err != nil || len(results) == 0 {
|
||||||
return results, err
|
return results, err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Best-selling product of each parent category. DISTINCT ON keeps the first row per
|
||||||
|
// parent category, which the ordering makes the one with the highest revenue.
|
||||||
|
var topProducts []*entities.ParentCategoryTopProduct
|
||||||
|
topQuery := r.db.WithContext(ctx).
|
||||||
|
Table("order_items oi").
|
||||||
|
Select(`
|
||||||
|
DISTINCT ON (pc.id)
|
||||||
|
pc.id as parent_category_id,
|
||||||
|
p.id as product_id,
|
||||||
|
p.name as product_name,
|
||||||
|
COALESCE(SUM(CASE WHEN oi.is_fully_refunded = false THEN oi.quantity - COALESCE(oi.refund_quantity, 0) ELSE 0 END), 0) as quantity_sold,
|
||||||
|
COALESCE(SUM(CASE WHEN oi.is_fully_refunded = false THEN oi.total_price - COALESCE(oi.refund_amount, 0) ELSE 0 END), 0) as revenue
|
||||||
|
`).
|
||||||
|
Joins("JOIN products p ON oi.product_id = p.id").
|
||||||
|
Joins("JOIN categories c ON p.category_id = c.id").
|
||||||
|
Joins("JOIN categories pc ON pc.id = COALESCE(c.parent_id, c.id)").
|
||||||
|
Joins("JOIN orders o ON oi.order_id = o.id").
|
||||||
|
Where("pc.is_team = ?", true).
|
||||||
|
Where("o.organization_id = ?", organizationID).
|
||||||
|
Where("o.is_void = ?", false).
|
||||||
|
Where("o.is_refund = ?", false).
|
||||||
|
Where("o.payment_status = ?", entities.PaymentStatusCompleted).
|
||||||
|
Where("oi.status != ?", entities.OrderItemStatusCancelled).
|
||||||
|
Where("o.created_at >= ? AND o.created_at <= ?", dateFrom, dateTo)
|
||||||
|
|
||||||
|
topQuery = r.resolveOutletID(topQuery, outletID, "o.outlet_id")
|
||||||
|
|
||||||
|
err = topQuery.
|
||||||
|
Group("pc.id, p.id, p.name").
|
||||||
|
Order("pc.id, COALESCE(SUM(CASE WHEN oi.is_fully_refunded = false THEN oi.total_price - COALESCE(oi.refund_amount, 0) ELSE 0 END), 0) DESC, p.name ASC").
|
||||||
|
Scan(&topProducts).Error
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
topByParent := make(map[uuid.UUID]*entities.ParentCategoryTopProduct, len(topProducts))
|
||||||
|
for _, product := range topProducts {
|
||||||
|
topByParent[product.ParentCategoryID] = product
|
||||||
|
}
|
||||||
|
for _, result := range results {
|
||||||
|
result.TopProduct = topByParent[result.ParentCategoryID]
|
||||||
|
}
|
||||||
|
|
||||||
|
return results, nil
|
||||||
|
}
|
||||||
|
|
||||||
// movingAverageHppSubquery builds the per-product moving-average HPP lookup shared by
|
// movingAverageHppSubquery builds the per-product moving-average HPP lookup shared by
|
||||||
// the parent category detail queries.
|
// the parent category detail queries.
|
||||||
func (r *AnalyticsRepositoryImpl) movingAverageHppSubquery(organizationID uuid.UUID, dateTo time.Time) *gorm.DB {
|
func (r *AnalyticsRepositoryImpl) movingAverageHppSubquery(organizationID uuid.UUID, dateTo time.Time) *gorm.DB {
|
||||||
@@ -693,10 +741,12 @@ func (r *AnalyticsRepositoryImpl) GetParentCategoryAnalyticsDetail(ctx context.C
|
|||||||
var parent struct {
|
var parent struct {
|
||||||
ID uuid.UUID
|
ID uuid.UUID
|
||||||
Name string
|
Name string
|
||||||
|
IsTeam bool
|
||||||
|
OwnerFeePercent float64
|
||||||
}
|
}
|
||||||
if err := r.db.WithContext(ctx).
|
if err := r.db.WithContext(ctx).
|
||||||
Table("categories").
|
Table("categories").
|
||||||
Select("id, name").
|
Select("id, name, is_team, COALESCE(owner_fee_percent, ?) as owner_fee_percent", constants.BudgetLimitOwnerPercent).
|
||||||
Where("id = ? AND organization_id = ?", parentCategoryID, organizationID).
|
Where("id = ? AND organization_id = ?", parentCategoryID, organizationID).
|
||||||
Scan(&parent).Error; err != nil {
|
Scan(&parent).Error; err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
@@ -704,6 +754,9 @@ func (r *AnalyticsRepositoryImpl) GetParentCategoryAnalyticsDetail(ctx context.C
|
|||||||
if parent.ID == uuid.Nil {
|
if parent.ID == uuid.Nil {
|
||||||
return nil, fmt.Errorf("category not found")
|
return nil, fmt.Errorf("category not found")
|
||||||
}
|
}
|
||||||
|
if !parent.IsTeam {
|
||||||
|
return nil, fmt.Errorf("category %s is not a team", parent.Name)
|
||||||
|
}
|
||||||
|
|
||||||
detail := &entities.ParentCategoryAnalyticsDetail{
|
detail := &entities.ParentCategoryAnalyticsDetail{
|
||||||
ParentCategoryID: parent.ID,
|
ParentCategoryID: parent.ID,
|
||||||
@@ -732,6 +785,7 @@ func (r *AnalyticsRepositoryImpl) GetParentCategoryAnalyticsDetail(ctx context.C
|
|||||||
}
|
}
|
||||||
summary.ParentCategoryID = parent.ID
|
summary.ParentCategoryID = parent.ID
|
||||||
summary.ParentCategoryName = parent.Name
|
summary.ParentCategoryName = parent.Name
|
||||||
|
summary.OwnerFeePercent = parent.OwnerFeePercent
|
||||||
detail.Summary = summary
|
detail.Summary = summary
|
||||||
|
|
||||||
// Sub-category rows.
|
// Sub-category rows.
|
||||||
@@ -801,7 +855,8 @@ func (r *AnalyticsRepositoryImpl) GetParentCategoryAnalyticsDetail(ctx context.C
|
|||||||
// GetBudgetCutOffWeekly buckets revenue and cost of goods sold into Monday-to-Sunday
|
// GetBudgetCutOffWeekly buckets revenue and cost of goods sold into Monday-to-Sunday
|
||||||
// weeks. DATE_TRUNC('week') is ISO, so the buckets start on Monday, and the connection
|
// weeks. DATE_TRUNC('week') is ISO, so the buckets start on Monday, and the connection
|
||||||
// runs with TimeZone=Asia/Jakarta so the boundaries land on local midnight.
|
// runs with TimeZone=Asia/Jakarta so the boundaries land on local midnight.
|
||||||
// A nil parentCategoryID covers every category in scope.
|
// A nil parentCategoryID covers every team in scope; parent categories that are not a
|
||||||
|
// team stay out of the split.
|
||||||
func (r *AnalyticsRepositoryImpl) GetBudgetCutOffWeekly(ctx context.Context, organizationID uuid.UUID, outletID *uuid.UUID, parentCategoryID *uuid.UUID, cutOffFrom, cutOffTo time.Time) ([]*entities.BudgetCutOffWeek, error) {
|
func (r *AnalyticsRepositoryImpl) GetBudgetCutOffWeekly(ctx context.Context, organizationID uuid.UUID, outletID *uuid.UUID, parentCategoryID *uuid.UUID, cutOffFrom, cutOffTo time.Time) ([]*entities.BudgetCutOffWeek, error) {
|
||||||
var results []*entities.BudgetCutOffWeek
|
var results []*entities.BudgetCutOffWeek
|
||||||
|
|
||||||
@@ -810,13 +865,18 @@ func (r *AnalyticsRepositoryImpl) GetBudgetCutOffWeekly(ctx context.Context, org
|
|||||||
Select(`
|
Select(`
|
||||||
DATE_TRUNC('week', o.created_at) as week_start,
|
DATE_TRUNC('week', o.created_at) as week_start,
|
||||||
COALESCE(SUM(CASE WHEN oi.is_fully_refunded = false THEN oi.total_price - COALESCE(oi.refund_amount, 0) ELSE 0 END), 0) as revenue,
|
COALESCE(SUM(CASE WHEN oi.is_fully_refunded = false THEN oi.total_price - COALESCE(oi.refund_amount, 0) ELSE 0 END), 0) as revenue,
|
||||||
|
COALESCE(SUM((CASE WHEN oi.is_fully_refunded = false THEN oi.total_price - COALESCE(oi.refund_amount, 0) ELSE 0 END) * COALESCE(pc.owner_fee_percent, ?) / 100.0), 0) as sdl,
|
||||||
COUNT(DISTINCT oi.order_id) as order_count
|
COUNT(DISTINCT oi.order_id) as order_count
|
||||||
`).
|
`, constants.BudgetLimitOwnerPercent).
|
||||||
// products and categories are joined to keep the scope identical to the report
|
// products and categories are joined to keep the scope identical to the report
|
||||||
// the block is attached to, even when no parent category filter is applied
|
// the block is attached to, even when no parent category filter is applied
|
||||||
Joins("JOIN products p ON oi.product_id = p.id").
|
Joins("JOIN products p ON oi.product_id = p.id").
|
||||||
Joins("JOIN categories c ON p.category_id = c.id").
|
Joins("JOIN categories c ON p.category_id = c.id").
|
||||||
|
// The owner fee lives on the parent category; a category without a parent is its own group
|
||||||
|
Joins("JOIN categories pc ON pc.id = COALESCE(c.parent_id, c.id)").
|
||||||
Joins("JOIN orders o ON oi.order_id = o.id").
|
Joins("JOIN orders o ON oi.order_id = o.id").
|
||||||
|
// Only teams take part in the revenue split
|
||||||
|
Where("pc.is_team = ?", true).
|
||||||
Where("o.organization_id = ?", organizationID).
|
Where("o.organization_id = ?", organizationID).
|
||||||
Where("o.is_void = ?", false).
|
Where("o.is_void = ?", false).
|
||||||
Where("o.is_refund = ?", false).
|
Where("o.is_refund = ?", false).
|
||||||
|
|||||||
@@ -62,8 +62,6 @@ type CustomerOrderPaymentRow struct {
|
|||||||
Amount float64
|
Amount float64
|
||||||
Status string
|
Status string
|
||||||
RefundAmount float64
|
RefundAmount float64
|
||||||
PointsUsed *int64
|
|
||||||
PointValue *float64
|
|
||||||
CreatedAt time.Time
|
CreatedAt time.Time
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -145,7 +143,7 @@ func (r *customerOrderRepository) ListPayments(ctx context.Context, orderID uuid
|
|||||||
var rows []CustomerOrderPaymentRow
|
var rows []CustomerOrderPaymentRow
|
||||||
err := DBFromContext(ctx, r.db).WithContext(ctx).Raw(`
|
err := DBFromContext(ctx, r.db).WithContext(ctx).Raw(`
|
||||||
SELECT pay.id, COALESCE(pm.name, '') AS method_name, COALESCE(pm.type, '') AS method_type,
|
SELECT pay.id, COALESCE(pm.name, '') AS method_name, COALESCE(pm.type, '') AS method_type,
|
||||||
pay.amount, pay.status, pay.refund_amount, pay.points_used, pay.point_value, pay.created_at
|
pay.amount, pay.status, pay.refund_amount, pay.created_at
|
||||||
FROM payments pay
|
FROM payments pay
|
||||||
LEFT JOIN payment_methods pm ON pm.id = pay.payment_method_id
|
LEFT JOIN payment_methods pm ON pm.id = pay.payment_method_id
|
||||||
WHERE pay.order_id = ?
|
WHERE pay.order_id = ?
|
||||||
|
|||||||
@@ -44,9 +44,6 @@ type EarningCursor struct {
|
|||||||
// EarningRepository reads orders for loyalty earning (docs/prd-point-coin.md F3).
|
// EarningRepository reads orders for loyalty earning (docs/prd-point-coin.md F3).
|
||||||
type EarningRepository interface {
|
type EarningRepository interface {
|
||||||
GetOrderForEarning(ctx context.Context, orderID uuid.UUID) (*EarningOrder, error)
|
GetOrderForEarning(ctx context.Context, orderID uuid.UUID) (*EarningOrder, error)
|
||||||
// PointPaidAmount is the rupiah part of the order paid with EnakPoint, which earns
|
|
||||||
// nothing (Q10). Zero until EnakPoint payment exists (phase 3).
|
|
||||||
PointPaidAmount(ctx context.Context, orderID uuid.UUID) (float64, error)
|
|
||||||
// ListPaidOrdersWithoutEarning pages, oldest first, through orders updated since
|
// ListPaidOrdersWithoutEarning pages, oldest first, through orders updated since
|
||||||
// the given time that are paid, not void, have an eligible customer, belong to an
|
// the given time that are paid, not void, have an eligible customer, belong to an
|
||||||
// outlet that earns something, and have no EARN row yet. Pass the previous page's
|
// outlet that earns something, and have no EARN row yet. Pass the previous page's
|
||||||
@@ -92,13 +89,7 @@ func (r *earningRepository) GetOrderForEarning(ctx context.Context, orderID uuid
|
|||||||
SELECT o.id::text AS id, o.organization_id::text AS organization_id, o.outlet_id::text AS outlet_id,
|
SELECT o.id::text AS id, o.organization_id::text AS organization_id, o.outlet_id::text AS outlet_id,
|
||||||
o.order_number, COALESCE(ou.name, '') AS outlet_name, o.customer_id::text AS customer_id,
|
o.order_number, COALESCE(ou.name, '') AS outlet_name, o.customer_id::text AS customer_id,
|
||||||
o.subtotal, COALESCE(o.discount_amount, 0) AS discount_amount, o.payment_status,
|
o.subtotal, COALESCE(o.discount_amount, 0) AS discount_amount, o.payment_status,
|
||||||
COALESCE(o.is_void, false) AS is_void,
|
COALESCE(o.is_void, false) AS is_void, COALESCE(o.refund_amount, 0) AS refund_amount,
|
||||||
-- Refunds of EnakPoint payments are left out: that part never earned (Q10),
|
|
||||||
-- so giving it back must not take earning back.
|
|
||||||
COALESCE(o.refund_amount, 0) - COALESCE((
|
|
||||||
SELECT SUM(COALESCE(p.refund_amount, 0)) FROM payments p
|
|
||||||
JOIN payment_methods pm ON pm.id = p.payment_method_id
|
|
||||||
WHERE p.order_id = o.id AND pm.type = 'point'), 0) AS refund_amount,
|
|
||||||
c.is_default AS customer_is_default, c.is_active AS customer_is_active
|
c.is_default AS customer_is_default, c.is_active AS customer_is_active
|
||||||
FROM orders o
|
FROM orders o
|
||||||
LEFT JOIN outlets ou ON ou.id = o.outlet_id
|
LEFT JOIN outlets ou ON ou.id = o.outlet_id
|
||||||
@@ -134,21 +125,6 @@ func (r *earningRepository) GetOrderForEarning(ctx context.Context, orderID uuid
|
|||||||
return order, nil
|
return order, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r *earningRepository) PointPaidAmount(ctx context.Context, orderID uuid.UUID) (float64, error) {
|
|
||||||
var total float64
|
|
||||||
err := DBFromContext(ctx, r.db).WithContext(ctx).Raw(`
|
|
||||||
SELECT COALESCE(SUM(p.amount), 0)
|
|
||||||
FROM payments p
|
|
||||||
JOIN payment_methods pm ON pm.id = p.payment_method_id
|
|
||||||
WHERE p.order_id = ? AND pm.type = ? AND p.status = ?`,
|
|
||||||
orderID, constants.PaymentMethodTypePoint, entities.PaymentTransactionStatusCompleted).
|
|
||||||
Scan(&total).Error
|
|
||||||
if err != nil {
|
|
||||||
return 0, fmt.Errorf("failed to sum EnakPoint payments: %w", err)
|
|
||||||
}
|
|
||||||
return total, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *earningRepository) ListPaidOrdersWithoutEarning(ctx context.Context, since time.Time, after *EarningCursor, limit int) ([]EarningCursor, error) {
|
func (r *earningRepository) ListPaidOrdersWithoutEarning(ctx context.Context, since time.Time, after *EarningCursor, limit int) ([]EarningCursor, error) {
|
||||||
cursorAt, cursorID := since, uuid.Nil
|
cursorAt, cursorID := since, uuid.Nil
|
||||||
if after != nil {
|
if after != nil {
|
||||||
|
|||||||
@@ -58,7 +58,6 @@ func TestLoyaltySettings_AgainstPostgres(t *testing.T) {
|
|||||||
assert.Equal(t, int64(100), settings.Point.EarnPerAmount)
|
assert.Equal(t, int64(100), settings.Point.EarnPerAmount)
|
||||||
assert.Equal(t, int64(25000), settings.Coin.EarnPerAmount)
|
assert.Equal(t, int64(25000), settings.Coin.EarnPerAmount)
|
||||||
assert.Nil(t, settings.Point.MaxPerOrder)
|
assert.Nil(t, settings.Point.MaxPerOrder)
|
||||||
assert.Equal(t, int64(100), settings.PointPayment.MaxPaymentPercent)
|
|
||||||
|
|
||||||
// Change three keys.
|
// Change three keys.
|
||||||
settings.Point.Enabled = true
|
settings.Point.Enabled = true
|
||||||
|
|||||||
@@ -1,103 +0,0 @@
|
|||||||
package repository
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"errors"
|
|
||||||
"fmt"
|
|
||||||
"strings"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/google/uuid"
|
|
||||||
"github.com/redis/go-redis/v9"
|
|
||||||
)
|
|
||||||
|
|
||||||
var (
|
|
||||||
// ErrPaymentCodeTaken means the code is already live for someone; draw another.
|
|
||||||
ErrPaymentCodeTaken = errors.New("payment code already in use")
|
|
||||||
// ErrPaymentCodeNotFound means the code does not exist: never issued, expired, or
|
|
||||||
// already used.
|
|
||||||
ErrPaymentCodeNotFound = errors.New("payment code not found")
|
|
||||||
// ErrPaymentCodeWrongCustomer means the code belongs to another customer.
|
|
||||||
ErrPaymentCodeWrongCustomer = errors.New("payment code belongs to another customer")
|
|
||||||
)
|
|
||||||
|
|
||||||
// PaymentCodeRepository keeps one-time EnakPoint payment codes in Redis
|
|
||||||
// (docs/prd-point-coin.md F9). A code expires by TTL and is removed when used.
|
|
||||||
type PaymentCodeRepository interface {
|
|
||||||
// Save stores a code for a customer for ttl, and retires the customer's previous
|
|
||||||
// code so only the newest one works. ErrPaymentCodeTaken if the code is live.
|
|
||||||
Save(ctx context.Context, code string, customerID uuid.UUID, ttl time.Duration) error
|
|
||||||
// Consume uses a code up if it belongs to the customer. A code of another customer
|
|
||||||
// is left in place, so a cashier scanning it against the wrong order does not burn
|
|
||||||
// it for its owner.
|
|
||||||
Consume(ctx context.Context, code string, customerID uuid.UUID) error
|
|
||||||
}
|
|
||||||
|
|
||||||
type paymentCodeRepository struct {
|
|
||||||
client *redis.Client
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewPaymentCodeRepository(client *redis.Client) PaymentCodeRepository {
|
|
||||||
return &paymentCodeRepository{client: client}
|
|
||||||
}
|
|
||||||
|
|
||||||
func paymentCodeKey(code string) string { return "wallet:paycode:" + code }
|
|
||||||
|
|
||||||
func paymentCodeCustomerKey(customerID uuid.UUID) string {
|
|
||||||
return "wallet:paycode:customer:" + customerID.String()
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *paymentCodeRepository) Save(ctx context.Context, code string, customerID uuid.UUID, ttl time.Duration) error {
|
|
||||||
ok, err := r.client.SetNX(ctx, paymentCodeKey(code), customerID.String(), ttl).Result()
|
|
||||||
if err != nil {
|
|
||||||
return fmt.Errorf("failed to store payment code: %w", err)
|
|
||||||
}
|
|
||||||
if !ok {
|
|
||||||
return ErrPaymentCodeTaken
|
|
||||||
}
|
|
||||||
previous, err := r.client.GetSet(ctx, paymentCodeCustomerKey(customerID), code).Result()
|
|
||||||
if err != nil && !errors.Is(err, redis.Nil) {
|
|
||||||
return fmt.Errorf("failed to track payment code: %w", err)
|
|
||||||
}
|
|
||||||
r.client.Expire(ctx, paymentCodeCustomerKey(customerID), ttl)
|
|
||||||
if previous != "" && previous != code {
|
|
||||||
// Only if it is still that customer's: the number may have been reissued.
|
|
||||||
if err := r.compareAndDelete(ctx, previous, customerID); err != nil && !errors.Is(err, ErrPaymentCodeNotFound) && !errors.Is(err, ErrPaymentCodeWrongCustomer) {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// consumeScript deletes a code only if it belongs to the given customer, in one step.
|
|
||||||
// Returns 1 when used up, 0 when missing, -1 when it belongs to someone else.
|
|
||||||
var consumeScript = redis.NewScript(`
|
|
||||||
local owner = redis.call('GET', KEYS[1])
|
|
||||||
if not owner then return 0 end
|
|
||||||
if owner ~= ARGV[1] then return -1 end
|
|
||||||
redis.call('DEL', KEYS[1])
|
|
||||||
return 1
|
|
||||||
`)
|
|
||||||
|
|
||||||
func (r *paymentCodeRepository) Consume(ctx context.Context, code string, customerID uuid.UUID) error {
|
|
||||||
code = strings.TrimSpace(code)
|
|
||||||
if code == "" {
|
|
||||||
return ErrPaymentCodeNotFound
|
|
||||||
}
|
|
||||||
return r.compareAndDelete(ctx, code, customerID)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *paymentCodeRepository) compareAndDelete(ctx context.Context, code string, customerID uuid.UUID) error {
|
|
||||||
result, err := consumeScript.Run(ctx, r.client, []string{paymentCodeKey(code)}, customerID.String()).Int()
|
|
||||||
if err != nil {
|
|
||||||
return fmt.Errorf("failed to use payment code: %w", err)
|
|
||||||
}
|
|
||||||
switch result {
|
|
||||||
case 1:
|
|
||||||
return nil
|
|
||||||
case -1:
|
|
||||||
return ErrPaymentCodeWrongCustomer
|
|
||||||
default:
|
|
||||||
return ErrPaymentCodeNotFound
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -75,8 +75,6 @@ func (r *PaymentMethodRepositoryImpl) List(ctx context.Context, filters map[stri
|
|||||||
case "search":
|
case "search":
|
||||||
searchValue := "%" + value.(string) + "%"
|
searchValue := "%" + value.(string) + "%"
|
||||||
query = query.Where("name ILIKE ? OR processor ILIKE ?", searchValue, searchValue)
|
query = query.Where("name ILIKE ? OR processor ILIKE ?", searchValue, searchValue)
|
||||||
case "exclude_type":
|
|
||||||
query = query.Where("type <> ?", value)
|
|
||||||
default:
|
default:
|
||||||
query = query.Where(key+" = ?", value)
|
query = query.Where(key+" = ?", value)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,339 +0,0 @@
|
|||||||
package repository
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"errors"
|
|
||||||
"fmt"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/google/uuid"
|
|
||||||
"gorm.io/gorm"
|
|
||||||
|
|
||||||
"apskel-pos-be/internal/constants"
|
|
||||||
"apskel-pos-be/internal/entities"
|
|
||||||
)
|
|
||||||
|
|
||||||
// ErrPointPaymentOrderNotFound means the order does not exist.
|
|
||||||
var ErrPointPaymentOrderNotFound = errors.New("point payment: order not found")
|
|
||||||
|
|
||||||
// PointPaymentOrder is what paying with EnakPoint needs to know about an order.
|
|
||||||
type PointPaymentOrder struct {
|
|
||||||
ID uuid.UUID
|
|
||||||
OrganizationID uuid.UUID
|
|
||||||
OutletID uuid.UUID
|
|
||||||
OrderNumber string
|
|
||||||
OutletName string
|
|
||||||
CustomerID *uuid.UUID
|
|
||||||
TotalAmount float64
|
|
||||||
PaymentStatus string
|
|
||||||
IsVoid bool
|
|
||||||
CustomerIsDefault *bool
|
|
||||||
CustomerIsActive *bool
|
|
||||||
}
|
|
||||||
|
|
||||||
// PointPaymentRepository reads and writes what paying an order with EnakPoint touches
|
|
||||||
// (docs/prd-point-coin.md F9). Unlike the order and payment repositories, every method
|
|
||||||
// joins the caller's transaction, since the payment row, the balance and the order
|
|
||||||
// must change together.
|
|
||||||
type PointPaymentRepository interface {
|
|
||||||
// GetOrder reads the order; with lock it also locks the order row for the rest of
|
|
||||||
// the transaction, so two payments of the same order queue up.
|
|
||||||
GetOrder(ctx context.Context, orderID uuid.UUID, lock bool) (*PointPaymentOrder, error)
|
|
||||||
// GetPaymentMethod returns a method's organization and type.
|
|
||||||
GetPaymentMethod(ctx context.Context, methodID uuid.UUID) (organizationID uuid.UUID, methodType string, err error)
|
|
||||||
// TotalPaid sums the order's completed payments, as the rest of the order flow does.
|
|
||||||
TotalPaid(ctx context.Context, orderID uuid.UUID) (float64, error)
|
|
||||||
// PaidWithPoints sums the rupiah of the order's completed EnakPoint payments.
|
|
||||||
PaidWithPoints(ctx context.Context, orderID uuid.UUID) (float64, error)
|
|
||||||
// PointMethodID returns the organization's EnakPoint payment method.
|
|
||||||
PointMethodID(ctx context.Context, organizationID uuid.UUID) (uuid.UUID, error)
|
|
||||||
InsertPayment(ctx context.Context, payment *entities.Payment) error
|
|
||||||
// UpdateOrderAfterPayment stores what is left to pay and marks the order paid when
|
|
||||||
// nothing is.
|
|
||||||
UpdateOrderAfterPayment(ctx context.Context, orderID uuid.UUID, remaining float64, completed bool) error
|
|
||||||
|
|
||||||
// ListPointPayments returns the order's EnakPoint payments with their PAYMENT rows.
|
|
||||||
ListPointPayments(ctx context.Context, orderID uuid.UUID) ([]PointPaymentRow, error)
|
|
||||||
// PaymentAllocations returns the lots a PAYMENT row took from, longest-lasting first.
|
|
||||||
PaymentAllocations(ctx context.Context, ledgerID uuid.UUID) ([]PointPaymentAllocation, error)
|
|
||||||
// RefundedByOriginLot sums, per original lot, what PAYMENT_REFUND rows have already
|
|
||||||
// returned for a PAYMENT row.
|
|
||||||
RefundedByOriginLot(ctx context.Context, ledgerID uuid.UUID) (map[uuid.UUID]int64, error)
|
|
||||||
// RefundableByOtherMethods is what the order's non-EnakPoint payments can still give
|
|
||||||
// back: paid minus already refunded.
|
|
||||||
RefundableByOtherMethods(ctx context.Context, orderID uuid.UUID) (float64, error)
|
|
||||||
}
|
|
||||||
|
|
||||||
type pointPaymentRepository struct {
|
|
||||||
db *gorm.DB
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewPointPaymentRepository(db *gorm.DB) PointPaymentRepository {
|
|
||||||
return &pointPaymentRepository{db: db}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *pointPaymentRepository) GetOrder(ctx context.Context, orderID uuid.UUID, lock bool) (*PointPaymentOrder, error) {
|
|
||||||
lockClause := ""
|
|
||||||
if lock {
|
|
||||||
lockClause = "FOR UPDATE OF o"
|
|
||||||
}
|
|
||||||
var rows []struct {
|
|
||||||
ID string
|
|
||||||
OrganizationID string
|
|
||||||
OutletID string
|
|
||||||
OrderNumber string
|
|
||||||
OutletName string
|
|
||||||
CustomerID *string
|
|
||||||
TotalAmount float64
|
|
||||||
PaymentStatus string
|
|
||||||
IsVoid bool
|
|
||||||
CustomerIsDefault *bool
|
|
||||||
CustomerIsActive *bool
|
|
||||||
}
|
|
||||||
err := DBFromContext(ctx, r.db).WithContext(ctx).Raw(`
|
|
||||||
SELECT o.id::text AS id, o.organization_id::text AS organization_id, o.outlet_id::text AS outlet_id,
|
|
||||||
o.order_number, COALESCE(ou.name, '') AS outlet_name, o.customer_id::text AS customer_id,
|
|
||||||
o.total_amount, o.payment_status, COALESCE(o.is_void, false) AS is_void,
|
|
||||||
c.is_default AS customer_is_default, c.is_active AS customer_is_active
|
|
||||||
FROM orders o
|
|
||||||
LEFT JOIN outlets ou ON ou.id = o.outlet_id
|
|
||||||
LEFT JOIN customers c ON c.id = o.customer_id
|
|
||||||
WHERE o.id = ?
|
|
||||||
`+lockClause, orderID).Scan(&rows).Error
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("failed to read order: %w", err)
|
|
||||||
}
|
|
||||||
if len(rows) == 0 {
|
|
||||||
return nil, ErrPointPaymentOrderNotFound
|
|
||||||
}
|
|
||||||
row := rows[0]
|
|
||||||
order := &PointPaymentOrder{
|
|
||||||
OrderNumber: row.OrderNumber,
|
|
||||||
OutletName: row.OutletName,
|
|
||||||
TotalAmount: row.TotalAmount,
|
|
||||||
PaymentStatus: row.PaymentStatus,
|
|
||||||
IsVoid: row.IsVoid,
|
|
||||||
CustomerIsDefault: row.CustomerIsDefault,
|
|
||||||
CustomerIsActive: row.CustomerIsActive,
|
|
||||||
}
|
|
||||||
order.ID, _ = uuid.Parse(row.ID)
|
|
||||||
order.OrganizationID, _ = uuid.Parse(row.OrganizationID)
|
|
||||||
order.OutletID, _ = uuid.Parse(row.OutletID)
|
|
||||||
if row.CustomerID != nil {
|
|
||||||
if id, err := uuid.Parse(*row.CustomerID); err == nil {
|
|
||||||
order.CustomerID = &id
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return order, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *pointPaymentRepository) GetPaymentMethod(ctx context.Context, methodID uuid.UUID) (uuid.UUID, string, error) {
|
|
||||||
var rows []struct {
|
|
||||||
OrganizationID string
|
|
||||||
Type string
|
|
||||||
}
|
|
||||||
err := DBFromContext(ctx, r.db).WithContext(ctx).Raw(`
|
|
||||||
SELECT organization_id::text AS organization_id, type FROM payment_methods WHERE id = ?`, methodID).Scan(&rows).Error
|
|
||||||
if err != nil {
|
|
||||||
return uuid.Nil, "", fmt.Errorf("failed to read payment method: %w", err)
|
|
||||||
}
|
|
||||||
if len(rows) == 0 {
|
|
||||||
return uuid.Nil, "", fmt.Errorf("payment method not found")
|
|
||||||
}
|
|
||||||
org, _ := uuid.Parse(rows[0].OrganizationID)
|
|
||||||
return org, rows[0].Type, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *pointPaymentRepository) TotalPaid(ctx context.Context, orderID uuid.UUID) (float64, error) {
|
|
||||||
var total float64
|
|
||||||
err := DBFromContext(ctx, r.db).WithContext(ctx).Raw(`
|
|
||||||
SELECT COALESCE(SUM(amount), 0) FROM payments WHERE order_id = ? AND status = ?`,
|
|
||||||
orderID, entities.PaymentTransactionStatusCompleted).Scan(&total).Error
|
|
||||||
if err != nil {
|
|
||||||
return 0, fmt.Errorf("failed to sum payments: %w", err)
|
|
||||||
}
|
|
||||||
return total, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *pointPaymentRepository) PaidWithPoints(ctx context.Context, orderID uuid.UUID) (float64, error) {
|
|
||||||
var total float64
|
|
||||||
err := DBFromContext(ctx, r.db).WithContext(ctx).Raw(`
|
|
||||||
SELECT COALESCE(SUM(p.amount), 0) FROM payments p
|
|
||||||
JOIN payment_methods pm ON pm.id = p.payment_method_id
|
|
||||||
WHERE p.order_id = ? AND p.status = ? AND pm.type = ?`,
|
|
||||||
orderID, entities.PaymentTransactionStatusCompleted, constants.PaymentMethodTypePoint).Scan(&total).Error
|
|
||||||
if err != nil {
|
|
||||||
return 0, fmt.Errorf("failed to sum EnakPoint payments: %w", err)
|
|
||||||
}
|
|
||||||
return total, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *pointPaymentRepository) InsertPayment(ctx context.Context, payment *entities.Payment) error {
|
|
||||||
if err := DBFromContext(ctx, r.db).WithContext(ctx).Create(payment).Error; err != nil {
|
|
||||||
return fmt.Errorf("failed to create payment: %w", err)
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *pointPaymentRepository) UpdateOrderAfterPayment(ctx context.Context, orderID uuid.UUID, remaining float64, completed bool) error {
|
|
||||||
paymentStatus := entities.PaymentStatusPartial
|
|
||||||
if completed {
|
|
||||||
paymentStatus = entities.PaymentStatusCompleted
|
|
||||||
}
|
|
||||||
err := DBFromContext(ctx, r.db).WithContext(ctx).Exec(`
|
|
||||||
UPDATE orders SET remaining_amount = ?, payment_status = ?,
|
|
||||||
status = CASE WHEN ? THEN ? ELSE status END, updated_at = NOW()
|
|
||||||
WHERE id = ?`,
|
|
||||||
remaining, paymentStatus, completed, entities.OrderStatusCompleted, orderID).Error
|
|
||||||
if err != nil {
|
|
||||||
return fmt.Errorf("failed to update order after payment: %w", err)
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *pointPaymentRepository) PointMethodID(ctx context.Context, organizationID uuid.UUID) (uuid.UUID, error) {
|
|
||||||
var ids []string
|
|
||||||
err := DBFromContext(ctx, r.db).WithContext(ctx).
|
|
||||||
Table("payment_methods").
|
|
||||||
Where("organization_id = ? AND type = ?", organizationID, constants.PaymentMethodTypePoint).
|
|
||||||
Limit(1).
|
|
||||||
Pluck("id::text", &ids).Error
|
|
||||||
if err != nil {
|
|
||||||
return uuid.Nil, fmt.Errorf("failed to find the EnakPoint payment method: %w", err)
|
|
||||||
}
|
|
||||||
if len(ids) == 0 {
|
|
||||||
return uuid.Nil, fmt.Errorf("the organization has no EnakPoint payment method")
|
|
||||||
}
|
|
||||||
return uuid.Parse(ids[0])
|
|
||||||
}
|
|
||||||
|
|
||||||
// PointPaymentRow is one EnakPoint payment of an order, for refunding it.
|
|
||||||
type PointPaymentRow struct {
|
|
||||||
PaymentID uuid.UUID
|
|
||||||
Status string
|
|
||||||
PointsUsed int64
|
|
||||||
PointValue float64
|
|
||||||
RefundAmount float64
|
|
||||||
// The PAYMENT ledger row that took the balance; nil if none was written.
|
|
||||||
LedgerID *uuid.UUID
|
|
||||||
CustomerID *uuid.UUID
|
|
||||||
OutletID *uuid.UUID
|
|
||||||
}
|
|
||||||
|
|
||||||
// PointPaymentAllocation is how much a PAYMENT took from one lot, with that lot's
|
|
||||||
// expiry, so a refund can return it to the same expiry.
|
|
||||||
type PointPaymentAllocation struct {
|
|
||||||
LotID uuid.UUID
|
|
||||||
Amount int64
|
|
||||||
ExpiresAt *time.Time
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *pointPaymentRepository) ListPointPayments(ctx context.Context, orderID uuid.UUID) ([]PointPaymentRow, error) {
|
|
||||||
var rows []struct {
|
|
||||||
PaymentID string
|
|
||||||
Status string
|
|
||||||
PointsUsed int64
|
|
||||||
PointValue float64
|
|
||||||
RefundAmount float64
|
|
||||||
LedgerID *string
|
|
||||||
CustomerID *string
|
|
||||||
OutletID *string
|
|
||||||
}
|
|
||||||
err := DBFromContext(ctx, r.db).WithContext(ctx).Raw(`
|
|
||||||
SELECT p.id::text AS payment_id, p.status, p.points_used, p.point_value,
|
|
||||||
COALESCE(p.refund_amount, 0) AS refund_amount,
|
|
||||||
t.id::text AS ledger_id, t.customer_id::text AS customer_id, t.outlet_id::text AS outlet_id
|
|
||||||
FROM payments p
|
|
||||||
JOIN payment_methods pm ON pm.id = p.payment_method_id
|
|
||||||
LEFT JOIN wallet_transactions t ON t.reference_type = ? AND t.reference_id = p.id AND t.type = ?
|
|
||||||
WHERE p.order_id = ? AND pm.type = ? AND p.points_used IS NOT NULL
|
|
||||||
ORDER BY p.created_at, p.id`,
|
|
||||||
constants.WalletRefTypePayment, constants.WalletTxTypePayment, orderID, constants.PaymentMethodTypePoint).
|
|
||||||
Scan(&rows).Error
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("failed to list EnakPoint payments: %w", err)
|
|
||||||
}
|
|
||||||
out := make([]PointPaymentRow, 0, len(rows))
|
|
||||||
for _, row := range rows {
|
|
||||||
p := PointPaymentRow{Status: row.Status, PointsUsed: row.PointsUsed, PointValue: row.PointValue, RefundAmount: row.RefundAmount}
|
|
||||||
p.PaymentID, _ = uuid.Parse(row.PaymentID)
|
|
||||||
p.LedgerID = parseOptionalUUID(row.LedgerID)
|
|
||||||
p.CustomerID = parseOptionalUUID(row.CustomerID)
|
|
||||||
p.OutletID = parseOptionalUUID(row.OutletID)
|
|
||||||
out = append(out, p)
|
|
||||||
}
|
|
||||||
return out, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *pointPaymentRepository) PaymentAllocations(ctx context.Context, ledgerID uuid.UUID) ([]PointPaymentAllocation, error) {
|
|
||||||
var rows []struct {
|
|
||||||
LotID string
|
|
||||||
Amount int64
|
|
||||||
ExpiresAt *time.Time
|
|
||||||
}
|
|
||||||
// Longest-lasting first: a partial refund gives back the balance that keeps longest.
|
|
||||||
err := DBFromContext(ctx, r.db).WithContext(ctx).Raw(`
|
|
||||||
SELECT a.lot_id::text AS lot_id, a.amount, l.expires_at
|
|
||||||
FROM wallet_lot_allocations a JOIN wallet_lots l ON l.id = a.lot_id
|
|
||||||
WHERE a.transaction_id = ?
|
|
||||||
ORDER BY l.expires_at DESC NULLS FIRST, l.created_at DESC, l.id`, ledgerID).Scan(&rows).Error
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("failed to list payment allocations: %w", err)
|
|
||||||
}
|
|
||||||
out := make([]PointPaymentAllocation, 0, len(rows))
|
|
||||||
for _, row := range rows {
|
|
||||||
id, err := uuid.Parse(row.LotID)
|
|
||||||
if err != nil {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
out = append(out, PointPaymentAllocation{LotID: id, Amount: row.Amount, ExpiresAt: row.ExpiresAt})
|
|
||||||
}
|
|
||||||
return out, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *pointPaymentRepository) RefundedByOriginLot(ctx context.Context, ledgerID uuid.UUID) (map[uuid.UUID]int64, error) {
|
|
||||||
var rows []struct {
|
|
||||||
OriginLotID string
|
|
||||||
Amount int64
|
|
||||||
}
|
|
||||||
err := DBFromContext(ctx, r.db).WithContext(ctx).Raw(`
|
|
||||||
SELECT l.origin_lot_id::text AS origin_lot_id, SUM(l.original_amount) AS amount
|
|
||||||
FROM wallet_transactions t JOIN wallet_lots l ON l.source_transaction_id = t.id
|
|
||||||
WHERE t.reverses_transaction_id = ? AND t.type = ? AND l.origin_lot_id IS NOT NULL
|
|
||||||
GROUP BY l.origin_lot_id`, ledgerID, constants.WalletTxTypePaymentRefund).Scan(&rows).Error
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("failed to sum payment refunds: %w", err)
|
|
||||||
}
|
|
||||||
out := make(map[uuid.UUID]int64, len(rows))
|
|
||||||
for _, row := range rows {
|
|
||||||
if id, err := uuid.Parse(row.OriginLotID); err == nil {
|
|
||||||
out[id] = row.Amount
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return out, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *pointPaymentRepository) RefundableByOtherMethods(ctx context.Context, orderID uuid.UUID) (float64, error) {
|
|
||||||
var total float64
|
|
||||||
err := DBFromContext(ctx, r.db).WithContext(ctx).Raw(`
|
|
||||||
SELECT COALESCE(SUM(p.amount - COALESCE(p.refund_amount, 0)), 0)
|
|
||||||
FROM payments p JOIN payment_methods pm ON pm.id = p.payment_method_id
|
|
||||||
WHERE p.order_id = ? AND pm.type <> ? AND p.status IN (?, ?)`,
|
|
||||||
orderID, constants.PaymentMethodTypePoint,
|
|
||||||
entities.PaymentTransactionStatusCompleted, entities.PaymentTransactionStatusRefunded).Scan(&total).Error
|
|
||||||
if err != nil {
|
|
||||||
return 0, fmt.Errorf("failed to sum refundable payments: %w", err)
|
|
||||||
}
|
|
||||||
return total, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func parseOptionalUUID(s *string) *uuid.UUID {
|
|
||||||
if s == nil {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
id, err := uuid.Parse(*s)
|
|
||||||
if err != nil {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
return &id
|
|
||||||
}
|
|
||||||
@@ -39,7 +39,7 @@ func (r *ProductIngredientRepository) Create(ctx context.Context, productIngredi
|
|||||||
func (r *ProductIngredientRepository) GetByID(ctx context.Context, id, organizationID uuid.UUID) (*entities.ProductIngredient, error) {
|
func (r *ProductIngredientRepository) GetByID(ctx context.Context, id, organizationID uuid.UUID) (*entities.ProductIngredient, error) {
|
||||||
query := `
|
query := `
|
||||||
SELECT pi.id, pi.organization_id, pi.outlet_id, pi.product_id, pi.ingredient_id, pi.quantity, pi.created_at, pi.updated_at,
|
SELECT pi.id, pi.organization_id, pi.outlet_id, pi.product_id, pi.ingredient_id, pi.quantity, pi.created_at, pi.updated_at,
|
||||||
p.id, p.organization_id, p.category_id, p.sku, p.name, p.description, p.price, p.cost, p.business_type, p.image_url, p.printer_type, p.unit_id, p.has_ingredients, p.metadata, p.is_active, p.created_at, p.updated_at,
|
p.id, p.organization_id, p.category_id, p.sku, p.name, p.description, p.price, p.cost, p.business_type, p.image_url, p.printer_types, p.unit_id, p.has_ingredients, p.metadata, p.is_active, p.created_at, p.updated_at,
|
||||||
i.id, i.organization_id, i.outlet_id, i.name, i.unit_id, i.cost, i.stock, i.is_semi_finished, i.is_active, i.metadata, i.created_at, i.updated_at
|
i.id, i.organization_id, i.outlet_id, i.name, i.unit_id, i.cost, i.stock, i.is_semi_finished, i.is_active, i.metadata, i.created_at, i.updated_at
|
||||||
FROM product_ingredients pi
|
FROM product_ingredients pi
|
||||||
LEFT JOIN products p ON pi.product_id = p.id
|
LEFT JOIN products p ON pi.product_id = p.id
|
||||||
@@ -70,7 +70,7 @@ func (r *ProductIngredientRepository) GetByID(ctx context.Context, id, organizat
|
|||||||
&product.Cost,
|
&product.Cost,
|
||||||
&product.BusinessType,
|
&product.BusinessType,
|
||||||
&product.ImageURL,
|
&product.ImageURL,
|
||||||
&product.PrinterType,
|
&product.PrinterTypes,
|
||||||
&product.UnitID,
|
&product.UnitID,
|
||||||
&product.HasIngredients,
|
&product.HasIngredients,
|
||||||
&product.Metadata,
|
&product.Metadata,
|
||||||
@@ -103,7 +103,7 @@ func (r *ProductIngredientRepository) GetByID(ctx context.Context, id, organizat
|
|||||||
func (r *ProductIngredientRepository) GetByProductID(ctx context.Context, productID, organizationID uuid.UUID) ([]*entities.ProductIngredient, error) {
|
func (r *ProductIngredientRepository) GetByProductID(ctx context.Context, productID, organizationID uuid.UUID) ([]*entities.ProductIngredient, error) {
|
||||||
query := `
|
query := `
|
||||||
SELECT pi.id, pi.organization_id, pi.outlet_id, pi.product_id, pi.ingredient_id, pi.quantity, pi.created_at, pi.updated_at,
|
SELECT pi.id, pi.organization_id, pi.outlet_id, pi.product_id, pi.ingredient_id, pi.quantity, pi.created_at, pi.updated_at,
|
||||||
p.id, p.organization_id, p.category_id, p.sku, p.name, p.description, p.price, p.cost, p.business_type, p.image_url, p.printer_type, p.unit_id, p.has_ingredients, p.metadata, p.is_active, p.created_at, p.updated_at,
|
p.id, p.organization_id, p.category_id, p.sku, p.name, p.description, p.price, p.cost, p.business_type, p.image_url, p.printer_types, p.unit_id, p.has_ingredients, p.metadata, p.is_active, p.created_at, p.updated_at,
|
||||||
i.id, i.organization_id, i.outlet_id, i.name, i.unit_id, i.cost, i.stock, i.is_semi_finished, i.is_active, i.metadata, i.created_at, i.updated_at
|
i.id, i.organization_id, i.outlet_id, i.name, i.unit_id, i.cost, i.stock, i.is_semi_finished, i.is_active, i.metadata, i.created_at, i.updated_at
|
||||||
FROM product_ingredients pi
|
FROM product_ingredients pi
|
||||||
LEFT JOIN products p ON pi.product_id = p.id
|
LEFT JOIN products p ON pi.product_id = p.id
|
||||||
@@ -143,7 +143,7 @@ func (r *ProductIngredientRepository) GetByProductID(ctx context.Context, produc
|
|||||||
&product.Cost,
|
&product.Cost,
|
||||||
&product.BusinessType,
|
&product.BusinessType,
|
||||||
&product.ImageURL,
|
&product.ImageURL,
|
||||||
&product.PrinterType,
|
&product.PrinterTypes,
|
||||||
&product.UnitID,
|
&product.UnitID,
|
||||||
&product.HasIngredients,
|
&product.HasIngredients,
|
||||||
&product.Metadata,
|
&product.Metadata,
|
||||||
@@ -178,7 +178,7 @@ func (r *ProductIngredientRepository) GetByProductID(ctx context.Context, produc
|
|||||||
func (r *ProductIngredientRepository) GetByIngredientID(ctx context.Context, ingredientID, organizationID uuid.UUID) ([]*entities.ProductIngredient, error) {
|
func (r *ProductIngredientRepository) GetByIngredientID(ctx context.Context, ingredientID, organizationID uuid.UUID) ([]*entities.ProductIngredient, error) {
|
||||||
query := `
|
query := `
|
||||||
SELECT pi.id, pi.organization_id, pi.outlet_id, pi.product_id, pi.ingredient_id, pi.quantity, pi.created_at, pi.updated_at,
|
SELECT pi.id, pi.organization_id, pi.outlet_id, pi.product_id, pi.ingredient_id, pi.quantity, pi.created_at, pi.updated_at,
|
||||||
p.id, p.organization_id, p.category_id, p.sku, p.name, p.description, p.price, p.cost, p.business_type, p.image_url, p.printer_type, p.unit_id, p.has_ingredients, p.metadata, p.is_active, p.created_at, p.updated_at,
|
p.id, p.organization_id, p.category_id, p.sku, p.name, p.description, p.price, p.cost, p.business_type, p.image_url, p.printer_types, p.unit_id, p.has_ingredients, p.metadata, p.is_active, p.created_at, p.updated_at,
|
||||||
i.id, i.organization_id, i.outlet_id, i.name, i.unit_id, i.cost, i.stock, i.is_semi_finished, i.is_active, i.metadata, i.created_at, i.updated_at
|
i.id, i.organization_id, i.outlet_id, i.name, i.unit_id, i.cost, i.stock, i.is_semi_finished, i.is_active, i.metadata, i.created_at, i.updated_at
|
||||||
FROM product_ingredients pi
|
FROM product_ingredients pi
|
||||||
LEFT JOIN products p ON pi.product_id = p.id
|
LEFT JOIN products p ON pi.product_id = p.id
|
||||||
@@ -218,7 +218,7 @@ func (r *ProductIngredientRepository) GetByIngredientID(ctx context.Context, ing
|
|||||||
&product.Cost,
|
&product.Cost,
|
||||||
&product.BusinessType,
|
&product.BusinessType,
|
||||||
&product.ImageURL,
|
&product.ImageURL,
|
||||||
&product.PrinterType,
|
&product.PrinterTypes,
|
||||||
&product.UnitID,
|
&product.UnitID,
|
||||||
&product.HasIngredients,
|
&product.HasIngredients,
|
||||||
&product.Metadata,
|
&product.Metadata,
|
||||||
|
|||||||
@@ -0,0 +1,48 @@
|
|||||||
|
package repository
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
"github.com/stretchr/testify/assert"
|
||||||
|
"github.com/stretchr/testify/require"
|
||||||
|
|
||||||
|
"apskel-pos-be/internal/entities"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Needs TEST_DATABASE_URL pointing at a migrated database; see walletTestDB.
|
||||||
|
func TestProductPrinterTypes_AgainstPostgres(t *testing.T) {
|
||||||
|
db := walletTestDB(t)
|
||||||
|
ctx := context.Background()
|
||||||
|
|
||||||
|
org, category := uuid.New(), uuid.New()
|
||||||
|
require.NoError(t, db.Exec(`INSERT INTO organizations (id, name, plan_type) VALUES (?, 'printer test', 'basic')`, org).Error)
|
||||||
|
require.NoError(t, db.Exec(`INSERT INTO categories (id, organization_id, name) VALUES (?, ?, 'Paket')`, category, org).Error)
|
||||||
|
t.Cleanup(func() {
|
||||||
|
db.Exec(`DELETE FROM products WHERE organization_id = ?`, org)
|
||||||
|
db.Exec(`DELETE FROM categories WHERE id = ?`, category)
|
||||||
|
db.Exec(`DELETE FROM organizations WHERE id = ?`, org)
|
||||||
|
})
|
||||||
|
|
||||||
|
repo := NewProductRepositoryImpl(db)
|
||||||
|
product := &entities.Product{OrganizationID: org, CategoryID: category, Name: "Paket Makan Minum", Price: 25000}
|
||||||
|
product.SetPrinterTypes([]string{"kitchen", "bar"})
|
||||||
|
require.NoError(t, repo.Create(ctx, product))
|
||||||
|
|
||||||
|
stored, err := repo.GetByID(ctx, product.ID)
|
||||||
|
require.NoError(t, err)
|
||||||
|
assert.Equal(t, entities.StringSlice{"kitchen", "bar"}, stored.PrinterTypes)
|
||||||
|
|
||||||
|
stored.SetPrinterTypes([]string{"bar"})
|
||||||
|
require.NoError(t, repo.Update(ctx, stored))
|
||||||
|
|
||||||
|
var printerTypes string
|
||||||
|
require.NoError(t, db.Raw(`SELECT printer_types::text FROM products WHERE id = ?`, product.ID).Scan(&printerTypes).Error)
|
||||||
|
assert.Equal(t, `["bar"]`, printerTypes)
|
||||||
|
|
||||||
|
// The old single column is gone.
|
||||||
|
var columns int64
|
||||||
|
require.NoError(t, db.Raw(`SELECT COUNT(*) FROM information_schema.columns WHERE table_name = 'products' AND column_name = 'printer_type'`).Scan(&columns).Error)
|
||||||
|
assert.Zero(t, columns)
|
||||||
|
}
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user