Compare commits
16
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f16a5da951 | ||
|
|
a24d5f0561 | ||
|
|
c1ec6a3dfd | ||
|
|
8bf2fe5585 | ||
|
|
a3cb7dd5fd | ||
|
|
609d434976 | ||
|
|
35fe5703fd | ||
|
|
e200923b72 | ||
|
|
c988a79d3b | ||
|
|
9b21af8892 | ||
|
|
582dc75543 | ||
|
|
c6062c4bb9 | ||
|
|
5e28b05770 | ||
|
|
4e24f9bbb0 | ||
|
|
645da3048e | ||
|
|
ae8003c1e4 |
+142
-27
@@ -1,62 +1,177 @@
|
|||||||
#!/bin/bash
|
#!/bin/bash
|
||||||
set -euo pipefail
|
set -euo pipefail
|
||||||
|
|
||||||
|
# Usage:
|
||||||
|
# ./deployment.sh staging deploy staging (branch staging, port 4001)
|
||||||
|
# ./deployment.sh production deploy production (branch main, port 4000)
|
||||||
|
# ./deployment.sh production --rollback kembali ke image sebelum deploy terakhir
|
||||||
|
# Tambahkan --yes untuk melewati konfirmasi production.
|
||||||
|
|
||||||
APP_NAME="apskel-pos"
|
APP_NAME="apskel-pos"
|
||||||
|
LEGACY_CONTAINER="apskel-pos" # nama lama sebelum nama container memakai environment
|
||||||
|
|
||||||
# ─── Deteksi environment dari branch aktif ───────────────────────────────────
|
usage() {
|
||||||
CURRENT_BRANCH=$(git rev-parse --abbrev-ref HEAD)
|
echo "Usage: $0 <staging|production> [--rollback] [--yes]"
|
||||||
|
exit 1
|
||||||
|
}
|
||||||
|
|
||||||
case "$CURRENT_BRANCH" in
|
fail() {
|
||||||
main)
|
echo "❌ $*"
|
||||||
ENV_MODE="production"
|
exit 1
|
||||||
|
}
|
||||||
|
|
||||||
|
# ─── Argumen ──────────────────────────────────────────────────────────────────
|
||||||
|
ENV_MODE="${1:-}"
|
||||||
|
shift || true
|
||||||
|
|
||||||
|
ROLLBACK=false
|
||||||
|
ASSUME_YES=false
|
||||||
|
for arg in "$@"; do
|
||||||
|
case "$arg" in
|
||||||
|
--rollback) ROLLBACK=true ;;
|
||||||
|
--yes|-y) ASSUME_YES=true ;;
|
||||||
|
*) usage ;;
|
||||||
|
esac
|
||||||
|
done
|
||||||
|
|
||||||
|
# Environment wajib disebut eksplisit, tidak lagi ditebak dari branch aktif
|
||||||
|
case "$ENV_MODE" in
|
||||||
|
production)
|
||||||
|
EXPECTED_BRANCH="main"
|
||||||
PORT="4000"
|
PORT="4000"
|
||||||
;;
|
;;
|
||||||
staging)
|
staging)
|
||||||
ENV_MODE="staging"
|
EXPECTED_BRANCH="staging"
|
||||||
PORT="4001"
|
PORT="4001"
|
||||||
;;
|
;;
|
||||||
*)
|
*)
|
||||||
echo "❌ Branch '$CURRENT_BRANCH' tidak dikenali untuk deployment."
|
usage
|
||||||
echo " Gunakan branch 'main' (production) atau 'staging' (staging)."
|
|
||||||
exit 1
|
|
||||||
;;
|
;;
|
||||||
esac
|
esac
|
||||||
|
|
||||||
CONTAINER_NAME="$APP_NAME"
|
CONTAINER_NAME="$APP_NAME-$ENV_MODE"
|
||||||
IMAGE_NAME="$APP_NAME:$ENV_MODE"
|
IMAGE_NAME="$APP_NAME:$ENV_MODE"
|
||||||
|
PREVIOUS_IMAGE="$APP_NAME:$ENV_MODE-previous"
|
||||||
|
CONFIG_FILE="infra/$ENV_MODE.yaml"
|
||||||
|
|
||||||
|
# ─── Validasi repo ────────────────────────────────────────────────────────────
|
||||||
|
CURRENT_BRANCH=$(git rev-parse --abbrev-ref HEAD)
|
||||||
|
|
||||||
|
if [ "$CURRENT_BRANCH" = "HEAD" ]; then
|
||||||
|
fail "Repo sedang detached HEAD. Jalankan 'git checkout $EXPECTED_BRANCH' dulu."
|
||||||
|
fi
|
||||||
|
|
||||||
|
if [ "$CURRENT_BRANCH" != "$EXPECTED_BRANCH" ]; then
|
||||||
|
fail "Deploy $ENV_MODE harus dari branch '$EXPECTED_BRANCH', folder ini di branch '$CURRENT_BRANCH'.
|
||||||
|
Pakai folder terpisah per environment, jangan pindah branch di folder yang sedang dipakai container lain."
|
||||||
|
fi
|
||||||
|
|
||||||
|
if [ -n "$(git status --porcelain --untracked-files=no)" ]; then
|
||||||
|
fail "Ada perubahan yang belum di-commit di folder ini. Bersihkan dulu sebelum deploy."
|
||||||
|
fi
|
||||||
|
|
||||||
|
[ -f "$CONFIG_FILE" ] || fail "Config file '$CONFIG_FILE' tidak ditemukan."
|
||||||
|
|
||||||
|
# ─── Pastikan port tidak dipakai container environment lain ──────────────────
|
||||||
|
OTHER_ON_PORT=$(docker ps --filter "publish=$PORT" --format '{{.Names}}' \
|
||||||
|
| grep -vx "$CONTAINER_NAME" \
|
||||||
|
| { if [ "$ENV_MODE" = "production" ]; then grep -vx "$LEGACY_CONTAINER"; else cat; fi; } \
|
||||||
|
|| true)
|
||||||
|
if [ -n "$OTHER_ON_PORT" ]; then
|
||||||
|
fail "Port $PORT sedang dipakai container lain: $OTHER_ON_PORT"
|
||||||
|
fi
|
||||||
|
|
||||||
echo "📦 Environment : $ENV_MODE"
|
echo "📦 Environment : $ENV_MODE"
|
||||||
echo "🌿 Branch : $CURRENT_BRANCH"
|
echo "🌿 Branch : $CURRENT_BRANCH"
|
||||||
echo "🐳 Container : $CONTAINER_NAME"
|
echo "🐳 Container : $CONTAINER_NAME"
|
||||||
echo "🔌 Port : $PORT"
|
echo "🔌 Port : $PORT"
|
||||||
|
echo "📁 Folder : $(pwd)"
|
||||||
|
[ "$ROLLBACK" = true ] && echo "⏪ Mode : ROLLBACK ke $PREVIOUS_IMAGE"
|
||||||
echo ""
|
echo ""
|
||||||
|
|
||||||
# ─── Pastikan config file ada ─────────────────────────────────────────────────
|
# ─── Konfirmasi production ────────────────────────────────────────────────────
|
||||||
CONFIG_FILE="infra/$ENV_MODE.yaml"
|
if [ "$ENV_MODE" = "production" ] && [ "$ASSUME_YES" != true ]; then
|
||||||
if [ ! -f "$CONFIG_FILE" ]; then
|
read -r -p "⚠️ Ini PRODUCTION. Ketik 'production' untuk lanjut: " CONFIRM
|
||||||
echo "❌ Config file '$CONFIG_FILE' tidak ditemukan."
|
[ "$CONFIRM" = "production" ] || fail "Dibatalkan."
|
||||||
exit 1
|
|
||||||
fi
|
fi
|
||||||
|
|
||||||
echo "🔄 Pulling latest code..."
|
run_container() {
|
||||||
git pull
|
local image="$1"
|
||||||
|
|
||||||
|
echo "🛑 Stopping and removing old container..."
|
||||||
|
docker rm -f "$CONTAINER_NAME" 2>/dev/null || true
|
||||||
|
# Container production lama masih bernama 'apskel-pos'; staging tidak boleh menyentuhnya
|
||||||
|
if [ "$ENV_MODE" = "production" ]; then
|
||||||
|
docker rm -f "$LEGACY_CONTAINER" 2>/dev/null || true
|
||||||
|
fi
|
||||||
|
|
||||||
|
echo "🚀 Running container from $image..."
|
||||||
|
docker run -d --name "$CONTAINER_NAME" \
|
||||||
|
--restart unless-stopped \
|
||||||
|
-p "$PORT:4000" \
|
||||||
|
-e TZ=Asia/Jakarta \
|
||||||
|
-e ENV_MODE="$ENV_MODE" \
|
||||||
|
-v "$(pwd)/infra":/infra:ro \
|
||||||
|
-v "$(pwd)/templates":/templates:ro \
|
||||||
|
"$image" >/dev/null
|
||||||
|
}
|
||||||
|
|
||||||
|
wait_healthy() {
|
||||||
|
echo "🩺 Waiting for healthcheck..."
|
||||||
|
for _ in $(seq 1 36); do
|
||||||
|
local status
|
||||||
|
status=$(docker inspect -f '{{if .State.Health}}{{.State.Health.Status}}{{else}}{{.State.Status}}{{end}}' "$CONTAINER_NAME" 2>/dev/null || echo "missing")
|
||||||
|
case "$status" in
|
||||||
|
healthy) return 0 ;;
|
||||||
|
unhealthy|exited|dead|missing) return 1 ;;
|
||||||
|
esac
|
||||||
|
sleep 5
|
||||||
|
done
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
|
||||||
|
# ─── Rollback ─────────────────────────────────────────────────────────────────
|
||||||
|
if [ "$ROLLBACK" = true ]; then
|
||||||
|
docker image inspect "$PREVIOUS_IMAGE" >/dev/null 2>&1 || fail "Image '$PREVIOUS_IMAGE' tidak ada, tidak bisa rollback."
|
||||||
|
run_container "$PREVIOUS_IMAGE"
|
||||||
|
wait_healthy || fail "Container hasil rollback tidak healthy. Cek: docker logs $CONTAINER_NAME"
|
||||||
|
docker tag "$PREVIOUS_IMAGE" "$IMAGE_NAME"
|
||||||
|
echo "✅ Rollback $ENV_MODE complete."
|
||||||
|
exit 0
|
||||||
|
fi
|
||||||
|
|
||||||
|
# ─── Deploy ───────────────────────────────────────────────────────────────────
|
||||||
|
echo "🔄 Pulling latest code (origin/$EXPECTED_BRANCH)..."
|
||||||
|
git fetch origin "$EXPECTED_BRANCH"
|
||||||
|
git merge --ff-only "origin/$EXPECTED_BRANCH"
|
||||||
|
echo " Commit: $(git log -1 --format='%h %s')"
|
||||||
|
|
||||||
|
# Simpan image yang sedang jalan untuk rollback
|
||||||
|
if docker image inspect "$IMAGE_NAME" >/dev/null 2>&1; then
|
||||||
|
docker tag "$IMAGE_NAME" "$PREVIOUS_IMAGE"
|
||||||
|
fi
|
||||||
|
|
||||||
echo "🐳 Building Docker image ($ENV_MODE)..."
|
echo "🐳 Building Docker image ($ENV_MODE)..."
|
||||||
docker build --target production -t "$IMAGE_NAME" .
|
docker build --target production -t "$IMAGE_NAME" .
|
||||||
|
|
||||||
echo "🛑 Stopping and removing old container..."
|
run_container "$IMAGE_NAME"
|
||||||
docker rm -f "$CONTAINER_NAME" 2>/dev/null || true
|
|
||||||
|
|
||||||
echo "🚀 Running new container..."
|
if ! wait_healthy; then
|
||||||
docker run -d --name "$CONTAINER_NAME" \
|
echo "❌ Container baru tidak healthy. Log terakhir:"
|
||||||
-p "$PORT:4000" \
|
docker logs --tail 50 "$CONTAINER_NAME" || true
|
||||||
-e TZ=Asia/Jakarta \
|
if docker image inspect "$PREVIOUS_IMAGE" >/dev/null 2>&1; then
|
||||||
-e ENV_MODE="$ENV_MODE" \
|
echo "⏪ Rolling back ke $PREVIOUS_IMAGE..."
|
||||||
-v "$(pwd)/infra":/infra:ro \
|
run_container "$PREVIOUS_IMAGE"
|
||||||
-v "$(pwd)/templates":/templates:ro \
|
wait_healthy || fail "Rollback juga tidak healthy. Cek manual: docker logs $CONTAINER_NAME"
|
||||||
"$IMAGE_NAME"
|
# Jangan biarkan image rusak jadi 'previous' di deploy berikutnya
|
||||||
|
docker tag "$PREVIOUS_IMAGE" "$IMAGE_NAME"
|
||||||
|
fail "Deploy gagal, $ENV_MODE sudah dikembalikan ke image sebelumnya."
|
||||||
|
fi
|
||||||
|
fail "Deploy gagal dan tidak ada image sebelumnya untuk rollback."
|
||||||
|
fi
|
||||||
|
|
||||||
echo ""
|
echo ""
|
||||||
echo "✅ Deployment $ENV_MODE complete."
|
echo "✅ Deployment $ENV_MODE complete."
|
||||||
echo " Container : $CONTAINER_NAME"
|
echo " Container : $CONTAINER_NAME"
|
||||||
echo " Port : $PORT"
|
echo " Port : $PORT"
|
||||||
|
echo " Rollback : $0 $ENV_MODE --rollback"
|
||||||
|
|||||||
@@ -0,0 +1,441 @@
|
|||||||
|
# API EnakPoint & EnakCoin
|
||||||
|
|
||||||
|
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.
|
||||||
|
|
||||||
|
## Konvensi umum
|
||||||
|
|
||||||
|
| Klien | Autentikasi | Prefix |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| Customer app / self-order | `Authorization: Bearer <token customer>` | `/api/v1/customer` |
|
||||||
|
| POS | Token user (kasir/manager) | `/api/v1` |
|
||||||
|
| Dashboard | Token user, role Admin atau Manager | `/api/v1/marketing`, `/api/v1/outlets` |
|
||||||
|
|
||||||
|
**Format response.** Sukses: `{"success": true, "data": {…}, "errors": null}`. Gagal: `{"success": false, "data": null, "errors": [{"code": "304", "entity": "wallet_service", "cause": "…"}]}`. Tampilkan `cause` sebagai alasan penolakan.
|
||||||
|
|
||||||
|
| `code` | HTTP | Arti |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| `303`, `310` | 400 | Body atau parameter tidak lengkap / salah format |
|
||||||
|
| `304` | 400 | Ditolak aturan bisnis (saldo kurang, di luar batas, dst.) |
|
||||||
|
| `404` | 404 | Tidak ditemukan, juga untuk data milik customer atau organisasi lain |
|
||||||
|
| `429` | 429 | OTP diminta ulang terlalu cepat |
|
||||||
|
| `PIN_NOT_SET` | 403 | Customer belum membuat PIN |
|
||||||
|
| `PIN_INVALID` | 400 | PIN salah |
|
||||||
|
| `PIN_LOCKED` | 423 | PIN terkunci 30 menit setelah 5 kali salah |
|
||||||
|
| `TRANSFER_BLOCKED` | 403 | Transfer ditahan 24 jam setelah reset PIN |
|
||||||
|
| `900` | 500 | Kesalahan server |
|
||||||
|
|
||||||
|
**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.
|
||||||
|
|
||||||
|
**Waktu.** Tanggal kedaluwarsa dan filter tanggal memakai WIB. Saldo berlaku sampai 23:59:59 WIB pada tanggal kedaluwarsanya.
|
||||||
|
|
||||||
|
## Customer app: saldo & riwayat
|
||||||
|
|
||||||
|
| Method | Path | Keterangan |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| GET | `/customer/wallet` | Saldo, nilai rupiah, kedaluwarsa terdekat, 5 mutasi terakhir |
|
||||||
|
| GET | `/customer/wallet/transactions` | Riwayat mutasi, dengan pagination dan filter |
|
||||||
|
| GET | `/customer/wallet/expiring` | Saldo yang akan kedaluwarsa, per currency dan tanggal |
|
||||||
|
| PUT | `/customer/devices` | Daftarkan token FCM device |
|
||||||
|
| 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/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` |
|
||||||
|
|
||||||
|
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.
|
||||||
|
|
||||||
|
### GET /customer/wallet
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"point_balance": 12500,
|
||||||
|
"coin_balance": 8,
|
||||||
|
"point_value": 1,
|
||||||
|
"point_discount_value": 12500,
|
||||||
|
"nearest_expiring": {
|
||||||
|
"point": { "amount": 150, "date": "2026-12-31" },
|
||||||
|
"coin": null
|
||||||
|
},
|
||||||
|
"recent_transactions": [ "… sama seperti item riwayat …" ]
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
- `point_balance` / `coin_balance` = saldo yang bisa dipakai sekarang.
|
||||||
|
- `point_discount_value` = `point_balance × point_value`; tampilkan sebagai "setara potongan Rp …", bukan saldo uang.
|
||||||
|
- `nearest_expiring.point` / `.coin` bernilai `null` bila tidak ada yang akan kedaluwarsa.
|
||||||
|
|
||||||
|
### GET /customer/wallet/transactions
|
||||||
|
|
||||||
|
| Query | Tipe | Keterangan |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| `page` | int | Default 1 |
|
||||||
|
| `limit` | int | 1–100, default 20 |
|
||||||
|
| `currency` | `POINT` \| `COIN` | Opsional |
|
||||||
|
| `type` | string | Satu tipe atau beberapa dipisah koma, mis. `EARN,PAYMENT` |
|
||||||
|
| `from`, `to` | `YYYY-MM-DD` | Tanggal WIB, inklusif |
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"data": [
|
||||||
|
{
|
||||||
|
"id": "…",
|
||||||
|
"currency": "POINT",
|
||||||
|
"type": "EARN",
|
||||||
|
"amount": 875,
|
||||||
|
"balance_after": 12500,
|
||||||
|
"description": "Belanja #ORD-0123 di Outlet Kemang",
|
||||||
|
"source": { "type": "ORDER", "id": "…" },
|
||||||
|
"outlet_id": "…",
|
||||||
|
"group_id": null,
|
||||||
|
"expires_at": "2026-12-31T23:59:59+07:00",
|
||||||
|
"lots": [{ "amount": 875, "remaining": 875, "expires_at": "2026-12-31T23:59:59+07:00" }],
|
||||||
|
"created_at": "2026-09-30T12:01:00Z"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"pagination": { "page": 1, "limit": 20, "total_count": 42, "total_pages": 3 }
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
`amount` bertanda (+ menambah, − mengurangi). Penambahan membawa `source`, pengurangan membawa `destination`, keduanya `{ type, id }`. Dua baris exchange atau transfer berbagi `group_id`. Daftar tipe ada di bagian Referensi.
|
||||||
|
|
||||||
|
### GET /customer/wallet/expiring
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"point": [
|
||||||
|
{ "amount": 150, "date": "2026-10-31" },
|
||||||
|
{ "amount": 200, "date": "2026-12-31" }
|
||||||
|
],
|
||||||
|
"coin": []
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Terurut dari tanggal terdekat. Daftar kosong berarti tidak ada yang akan kedaluwarsa.
|
||||||
|
|
||||||
|
### PUT /customer/devices
|
||||||
|
|
||||||
|
```json
|
||||||
|
{ "device_id": "a1b2c3", "fcm_token": "…", "platform": "android", "app_version": "2.4.0" }
|
||||||
|
```
|
||||||
|
|
||||||
|
Panggil setelah login dan setiap kali FCM memberi token baru. `device_id` dan `fcm_token` wajib; `platform` = `android` | `ios` | `web`. Satu token hanya milik satu customer: customer lain yang mendaftarkan token yang sama mengambil alih HP itu. Response: `{ "device_id": "a1b2c3" }`.
|
||||||
|
|
||||||
|
## Customer app: PIN
|
||||||
|
|
||||||
|
PIN 6 digit wajib untuk bayar, kode bayar, exchange, dan transfer; minta customer membuatnya saat pertama kali melakukan aksi itu.
|
||||||
|
|
||||||
|
| Method | Path | Body | Response |
|
||||||
|
| --- | --- | --- | --- |
|
||||||
|
| GET | `/customer/pin/status` | – | `{ "has_pin", "locked_until", "transfer_blocked_until" }` |
|
||||||
|
| POST | `/customer/pin/otp` | `{ "purpose": "pin_setup" }` atau `"pin_reset"` | `{ "purpose", "otp_token", "expires_at" }` |
|
||||||
|
| POST | `/customer/pin` | `{ "otp_token", "otp_code", "pin", "confirm_pin" }` | Status PIN |
|
||||||
|
| PUT | `/customer/pin` | `{ "old_pin", "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.
|
||||||
|
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.
|
||||||
|
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.
|
||||||
|
|
||||||
|
## Customer app: bayar, exchange, transfer, game
|
||||||
|
|
||||||
|
| 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=` | – | – |
|
||||||
|
| POST | `/customer/wallet/exchange` | Ya | Wajib |
|
||||||
|
| GET | `/customer/wallet/transfer/recipient?phone=` | – | – |
|
||||||
|
| POST | `/customer/wallet/transfer` | Ya | Wajib |
|
||||||
|
| 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
|
||||||
|
|
||||||
|
```json
|
||||||
|
{ "coin_amount": 10, "point_amount": 3, "coin_balance": 35, "coins": 30, "points": 9, "valid": true }
|
||||||
|
```
|
||||||
|
|
||||||
|
Kurs: `coin_amount` EnakCoin = `point_amount` EnakPoint (default 1 : 1). Bila `valid: false`, tampilkan `reason`.
|
||||||
|
|
||||||
|
### POST /customer/wallet/exchange
|
||||||
|
|
||||||
|
Body `{ "coins": 30, "pin": "482913" }`. Response:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"group_id": "…",
|
||||||
|
"coins": 30,
|
||||||
|
"points": 9,
|
||||||
|
"coin_amount": 10,
|
||||||
|
"point_amount": 3,
|
||||||
|
"lots": [{ "amount": 9, "expires_at": "2026-12-31T23:59:59+07:00" }],
|
||||||
|
"coin_balance": 5,
|
||||||
|
"point_balance": 9,
|
||||||
|
"replayed": false
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
`coins` harus kelipatan `coin_amount`; jumlah yang salah ditolak `304` sebelum PIN dicek. Exchange tidak bisa dibatalkan. EnakPoint hasil tukar tidak bisa hidup lebih lama dari EnakCoin asalnya (lihat `lots`).
|
||||||
|
|
||||||
|
### GET /customer/wallet/transfer/recipient?phone=081234561234
|
||||||
|
|
||||||
|
```json
|
||||||
|
{ "name": "Bu*** Sa***", "phone_number": "08**-****-1234" }
|
||||||
|
```
|
||||||
|
|
||||||
|
Nomor di luar organisasi atau tidak terdaftar → `404`. Diri sendiri, customer walk-in, atau nonaktif → `304`.
|
||||||
|
|
||||||
|
### POST /customer/wallet/transfer
|
||||||
|
|
||||||
|
Body `{ "currency": "POINT", "amount": 120, "recipient_phone": "081234561234", "pin": "482913" }`. Response:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"group_id": "…",
|
||||||
|
"currency": "POINT",
|
||||||
|
"amount": 120,
|
||||||
|
"recipient": { "name": "Bu*** Sa***", "phone_number": "08**-****-1234" },
|
||||||
|
"lots": [
|
||||||
|
{ "amount": 100, "expires_at": "2026-12-31T23:59:59+07:00" },
|
||||||
|
{ "amount": 20, "expires_at": null }
|
||||||
|
],
|
||||||
|
"balance": 30,
|
||||||
|
"replayed": false
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
`currency` = `POINT` atau `COIN`. Batas organisasi (transfer aktif, minimal, maksimal per transaksi, batas harian per currency yang reset tengah malam WIB) ditolak `304` sebelum PIN dicek. Transfer final. Saldo membawa tanggal kedaluwarsa aslinya ke penerima (`lots`), dan penerima mendapat push `WALLET_TRANSFER_IN`.
|
||||||
|
|
||||||
|
### POST /customer/spin
|
||||||
|
|
||||||
|
Body `{ "spin_id": "<id game>" }`. Memotong EnakCoin sebesar `metadata.coin_cost` game itu (default 1).
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"game_play": { "id": "…", "game_id": "…", "coins_used": 1, "created_at": "…" },
|
||||||
|
"prize_won": { "id": "…", "name": "Voucher 10rb" },
|
||||||
|
"coins_remaining": 7
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
EnakCoin kurang, game nonaktif, atau hadiah baru saja habis → `304`, tidak ada EnakCoin yang terpotong.
|
||||||
|
|
||||||
|
## POS: pembayaran EnakPoint
|
||||||
|
|
||||||
|
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.
|
||||||
|
|
||||||
|
| 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
|
||||||
|
|
||||||
|
Semua endpoint dashboard butuh role Admin atau Manager, dan semuanya dibatasi ke organisasi user yang login. Rincian layar ada di [`backoffice-enakpoint.md`](./backoffice-enakpoint.md).
|
||||||
|
|
||||||
|
| Method | Path | Keterangan |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| GET, PUT | `/outlets/:outlet_id/loyalty-settings` | Earning dan penerimaan EnakPoint per outlet |
|
||||||
|
| 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/customers/:id/wallet` | Saldo, lot aktif, riwayat dengan nama asli |
|
||||||
|
| POST | `/marketing/customers/:id/wallet/adjust` | Koreksi saldo manual |
|
||||||
|
| GET | `/marketing/wallet-transactions/:id/trace` | Telusuri asal saldo per butir |
|
||||||
|
| DELETE | `/marketing/customers/:id/pin` | Hapus PIN customer |
|
||||||
|
| GET | `/marketing/customers/:id/security-events` | Log keamanan PIN (`page`, `limit`) |
|
||||||
|
|
||||||
|
Pada kedua `PUT` setting, field yang tidak dikirim tetap memakai nilai sekarang; field yang tidak dikenal ditolak.
|
||||||
|
|
||||||
|
### /outlets/:outlet_id/loyalty-settings
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"point": { "enabled": true, "earn_per_amount": 100, "earn_value": 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 },
|
||||||
|
"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.
|
||||||
|
|
||||||
|
### /marketing/loyalty-settings
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"point_value": 1,
|
||||||
|
"exchange": { "coin_amount": 1, "point_amount": 1 },
|
||||||
|
"transfer": { "enabled": true, "min_amount": 1, "max_per_transaction": null, "daily_limit": null },
|
||||||
|
"point_expiry": {
|
||||||
|
"enabled": false,
|
||||||
|
"mode": "FIXED_DATE",
|
||||||
|
"fixed_dates": ["12-31"],
|
||||||
|
"grace_months": 3,
|
||||||
|
"period": 12,
|
||||||
|
"unit": "MONTH",
|
||||||
|
"end_of_month": false,
|
||||||
|
"reminder_days": 7
|
||||||
|
},
|
||||||
|
"coin_expiry": { "…": "sama dengan point_expiry" }
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
| Field kedaluwarsa | Dipakai mode | Nilai |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| `mode` | – | `FIXED_DATE` (hangus di tanggal tetap tiap tahun) atau `ROLLING` (umur sejak didapat) |
|
||||||
|
| `fixed_dates` | `FIXED_DATE` | `MM-DD`, boleh lebih dari satu; `02-29` ditolak |
|
||||||
|
| `grace_months` | `FIXED_DATE` | 0–24; saldo yang didapat kurang dari ini sebelum tanggal hangus ikut ke tanggal berikutnya |
|
||||||
|
| `period`, `unit` | `ROLLING` | ≥ 1, `DAY` atau `MONTH` |
|
||||||
|
| `end_of_month` | `ROLLING` | Dibulatkan ke akhir bulan |
|
||||||
|
| `reminder_days` | keduanya | Hari sebelum hangus untuk pengingat; 0 = tanpa pengingat |
|
||||||
|
|
||||||
|
Response menambahkan:
|
||||||
|
|
||||||
|
- `impact`: saldo beredar dan nilai rupiahnya sebelum/sesudah perubahan `point_value` atau kurs.
|
||||||
|
- `expiry_preview`: `{ "point", "coin" }`, kapan saldo yang didapat sekarang kedaluwarsa (`null` = tidak).
|
||||||
|
- `expiry_activations`: bila perubahan ini menyalakan kedaluwarsa pertama kali, `[{ "currency", "lots", "amount", "expires_at" }]` saldo lama yang ikut diberi tanggal.
|
||||||
|
- `changes` dan `dry_run`.
|
||||||
|
|
||||||
|
### POST /marketing/customers/:id/wallet/adjust
|
||||||
|
|
||||||
|
```json
|
||||||
|
{ "currency": "POINT", "amount": -500, "reason": "Komplain #45", "idempotency_key": "adj-45" }
|
||||||
|
```
|
||||||
|
|
||||||
|
`amount` bertanda dan tidak boleh 0; `reason` wajib. Pengurangan yang melebihi saldo ditolak `304`. Response: `{ "transaction", "spendable_point_balance", "spendable_coin_balance", "replayed" }`.
|
||||||
|
|
||||||
|
### GET /marketing/wallet-transactions/:id/trace
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"transaction": { "id": "…", "customer": { "id": "…", "name": "Budi Santoso" }, "type": "PAYMENT", "amount": -30, "…": "…" },
|
||||||
|
"lots": [
|
||||||
|
{
|
||||||
|
"amount": 30,
|
||||||
|
"chain": [
|
||||||
|
{ "lot": { "id": "…", "expires_at": "…" }, "source": { "type": "TRANSFER_IN", "customer": { "name": "Budi Santoso" } } },
|
||||||
|
{ "lot": { "id": "…", "origin_lot_id": null }, "source": { "type": "EARN", "reference_type": "ORDER", "description": "Belanja #ORD-1", "customer": { "name": "Anita" } } }
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
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`.
|
||||||
|
|
||||||
|
### PIN customer
|
||||||
|
|
||||||
|
`DELETE /marketing/customers/:id/pin` dengan `{ "reason": "…" }` memaksa customer membuat PIN baru lewat OTP; admin tidak bisa membuat, mengganti, atau melihat PIN. `security-events` mengembalikan `PIN_SET`, `PIN_CHANGED`, `PIN_RESET`, `PIN_FAILED`, `PIN_LOCKED`, `PIN_REMOVED_BY_ADMIN` beserta waktu, IP, dan perangkat.
|
||||||
|
|
||||||
|
## Referensi
|
||||||
|
|
||||||
|
### Tipe mutasi (`type`)
|
||||||
|
|
||||||
|
| `type` | Arah | Arti | `source` / `destination` |
|
||||||
|
| --- | --- | --- | --- |
|
||||||
|
| `EARN` | + | Didapat dari order lunas | `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_IN` | + | EnakPoint hasil tukar | `WALLET_TX` (baris `EXCHANGE_OUT`) |
|
||||||
|
| `TRANSFER_OUT` | − | Dikirim ke customer lain | `WALLET_TX` (baris `TRANSFER_IN`) |
|
||||||
|
| `TRANSFER_IN` | + | Diterima dari customer lain | `WALLET_TX` (baris `TRANSFER_OUT`) |
|
||||||
|
| `GAME_SPEND` | − | Main game (EnakCoin saja) | `GAME_PLAY` |
|
||||||
|
| `EXPIRE` | − | Hangus karena kedaluwarsa | `LOT` |
|
||||||
|
| `ADJUSTMENT` | + / − | Koreksi admin | `USER` |
|
||||||
|
| `MIGRATION` | + | Saldo dari sistem lama | `LEGACY_POINTS` / `LEGACY_TOKENS` |
|
||||||
|
|
||||||
|
### Notifikasi push (FCM)
|
||||||
|
|
||||||
|
Semua nilai `data` berupa string. Push hanya sampai ke device yang terdaftar lewat `PUT /customer/devices`.
|
||||||
|
|
||||||
|
| `data.type` | Kapan | Isi `data` lainnya |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| `WALLET_TRANSFER_IN` | Menerima transfer | `transaction_id`, `group_id`, `currency`, `amount` |
|
||||||
|
| `WALLET_EXPIRING` | `reminder_days` hari sebelum hangus, sekali per tanggal | `currency`, `amount`, `expiry_date` |
|
||||||
|
| `WALLET_EXPIRED` | Saldo baru saja hangus | `currency`, `amount` |
|
||||||
|
| `PIN_LOCKED` | PIN terkunci setelah 5 kali salah | `locked_until` (RFC3339, UTC) |
|
||||||
|
|
||||||
|
### Endpoint dan field deprecated
|
||||||
|
|
||||||
|
Masih jalan dan membaca wallet, tapi akan dihapus setelah semua versi aplikasi pindah. Semua yang bernama token (`/customer/tokens`, `total_tokens`, `tokens_history`, `token_used`, `tokens_remaining`, campaign `TOKENS`) sudah dihapus; pakai `coin_balance`, `coins_used`, `coins_remaining`, dan `COINS`.
|
||||||
|
|
||||||
|
| Lama | Pengganti |
|
||||||
|
| --- | --- |
|
||||||
|
| `GET /customer/points` | `GET /customer/wallet` → `point_balance` |
|
||||||
|
| `total_points`, `points_history`, `last_updated` di `/customer/wallet` | `point_balance`, `recent_transactions` |
|
||||||
|
|
||||||
|
Panduan alur lengkap per tim ada di [`integration-enakpoint.md`](./integration-enakpoint.md).
|
||||||
@@ -0,0 +1,305 @@
|
|||||||
|
# Backoffice EnakPoint & EnakCoin
|
||||||
|
|
||||||
|
30 Sep 2026
|
||||||
|
|
||||||
|
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.
|
||||||
|
|
||||||
|
## 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`.
|
||||||
|
|
||||||
|
| Layar | Endpoint | Tempat di menu |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| Setting loyalitas outlet | `GET` / `PUT /outlets/:outlet_id/loyalty-settings` | Outlet → detail outlet → tab Loyalitas |
|
||||||
|
| Setting loyalitas organisasi | `GET` / `PUT /marketing/loyalty-settings` (+ `?dry_run=true`) | Marketing → Loyalitas → Pengaturan |
|
||||||
|
| Riwayat perubahan setting | `GET /marketing/loyalty-settings/history` | Marketing → Loyalitas → Riwayat |
|
||||||
|
| Wallet customer | `GET /marketing/customers/:id/wallet`, `POST …/wallet/adjust` | Customer → detail customer → tab Wallet |
|
||||||
|
| Telusuri mutasi | `GET /marketing/wallet-transactions/:id/trace` | Dibuka dari baris riwayat wallet |
|
||||||
|
| PIN & keamanan customer | `DELETE /marketing/customers/:id/pin`, `GET …/security-events` | Customer → detail customer → tab Keamanan |
|
||||||
|
| Biaya main game | `PUT` game yang sudah ada, `metadata.coin_cost` | Marketing → Game → edit game |
|
||||||
|
|
||||||
|
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.
|
||||||
|
|
||||||
|
**Format response.** Sukses `{ "success": true, "data": … }`; gagal `{ "success": false, "errors": [{ "code", "entity", "cause" }] }`. Tampilkan `cause` sebagai pesan (lihat bagian Pesan error).
|
||||||
|
|
||||||
|
## 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.
|
||||||
|
|
||||||
|
`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.
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"point": { "enabled": true, "earn_per_amount": 100, "earn_value": 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 },
|
||||||
|
"point_payment": { "accept_payment": true, "min_payment_points": 1, "max_payment_percent": 100 }
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
| Field | Label usulan | Tipe | Default | Validasi |
|
||||||
|
| --- | --- | --- | --- | --- |
|
||||||
|
| `point.enabled` / `coin.enabled` | Beri EnakPoint / EnakCoin | toggle | mati | – |
|
||||||
|
| `earn_per_amount` | Setiap belanja Rp … | Rp | 100 (point), 25.000 (coin) | > 0 |
|
||||||
|
| `earn_value` | … mendapat | angka | 1 | ≥ 0 |
|
||||||
|
| `min_order_amount` | Minimal belanja | Rp | 0 | ≥ 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).
|
||||||
|
|
||||||
|
**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.
|
||||||
|
|
||||||
|
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.
|
||||||
|
|
||||||
|
## Setting loyalitas organisasi
|
||||||
|
|
||||||
|
Nilai rupiah EnakPoint, kurs exchange, batas transfer, dan kedaluwarsa berlaku sama untuk semua outlet, jadi diatur sekali per organisasi. Mengubah nilai EnakPoint atau kurs langsung mengubah daya beli semua saldo customer, jadi layar ini wajib menampilkan dampaknya sebelum disimpan.
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"point_value": 1,
|
||||||
|
"exchange": { "coin_amount": 1, "point_amount": 1 },
|
||||||
|
"transfer": { "enabled": true, "min_amount": 1, "max_per_transaction": null, "daily_limit": null },
|
||||||
|
"point_expiry": { "…": "lihat bagian kedaluwarsa" },
|
||||||
|
"coin_expiry": { "…": "lihat bagian kedaluwarsa" }
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
| Field | Label usulan | Default | Validasi |
|
||||||
|
| --- | --- | --- | --- |
|
||||||
|
| `point_value` | Nilai 1 EnakPoint (Rp) | 1 | ≥ 1 |
|
||||||
|
| `exchange.coin_amount` : `exchange.point_amount` | Kurs tukar: … EnakCoin = … EnakPoint | 1 : 1 | keduanya ≥ 1 |
|
||||||
|
| `transfer.enabled` | Izinkan transfer antar customer | aktif | – |
|
||||||
|
| `transfer.min_amount` | Minimal per transfer | 1 | ≥ 1 |
|
||||||
|
| `transfer.max_per_transaction` | Maksimal per transfer | kosong = tanpa batas | ≥ 1 |
|
||||||
|
| `transfer.daily_limit` | Batas harian per customer | kosong = tanpa batas | ≥ 1, dihitung per currency, reset tengah malam WIB |
|
||||||
|
|
||||||
|
### Alur simpan
|
||||||
|
|
||||||
|
1. Owner mengubah form.
|
||||||
|
2. Tombol Simpan memanggil `PUT /marketing/loyalty-settings?dry_run=true` dengan objek yang diubah. Tidak ada yang tersimpan.
|
||||||
|
3. Bila `changes` kosong, beri tahu "tidak ada perubahan" dan berhenti.
|
||||||
|
4. Tampilkan dialog konfirmasi berisi `changes`, `impact` (bila `point_value` atau kurs berubah), dan `expiry_activations` (bila ada, lihat bagian kedaluwarsa).
|
||||||
|
5. Konfirmasi memanggil `PUT` yang sama tanpa `dry_run`.
|
||||||
|
|
||||||
|
### Dialog dampak
|
||||||
|
|
||||||
|
`impact` berisi saldo beredar organisasi dan nilainya sebelum/sesudah:
|
||||||
|
|
||||||
|
| Field `impact` | Tampilkan sebagai |
|
||||||
|
| --- | --- |
|
||||||
|
| `outstanding_points` | EnakPoint beredar |
|
||||||
|
| `point_rupiah_before` → `point_rupiah_after` | Setara potongan Rp … → Rp … |
|
||||||
|
| `outstanding_coins` | EnakCoin beredar |
|
||||||
|
| `coins_as_points_before` → `coins_as_points_after` | Bila semua ditukar: … EnakPoint → … EnakPoint |
|
||||||
|
| `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.
|
||||||
|
|
||||||
|
## Pengaturan kedaluwarsa
|
||||||
|
|
||||||
|
Kedaluwarsa diatur terpisah untuk EnakPoint (`point_expiry`) dan EnakCoin (`coin_expiry`) dengan salah satu dari dua model; defaultnya mati, dan bila dinyalakan defaultnya hangus setiap 31 Desember.
|
||||||
|
|
||||||
|
```json
|
||||||
|
"point_expiry": {
|
||||||
|
"enabled": true,
|
||||||
|
"mode": "FIXED_DATE",
|
||||||
|
"fixed_dates": ["12-31"],
|
||||||
|
"grace_months": 3,
|
||||||
|
"period": 12,
|
||||||
|
"unit": "MONTH",
|
||||||
|
"end_of_month": false,
|
||||||
|
"reminder_days": 7
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
| Field | Tampil saat | Label usulan | Validasi |
|
||||||
|
| --- | --- | --- | --- |
|
||||||
|
| `enabled` | selalu | Saldo bisa kedaluwarsa | – |
|
||||||
|
| `mode` | aktif | Model: Tanggal tetap / Sejak didapat | `FIXED_DATE` atau `ROLLING` |
|
||||||
|
| `fixed_dates` | `FIXED_DATE` | Tanggal hangus setiap tahun | minimal satu, format `MM-DD`, `02-29` ditolak |
|
||||||
|
| `grace_months` | `FIXED_DATE` | Periode tanggung (bulan) | 0–24, default 3 |
|
||||||
|
| `period` + `unit` | `ROLLING` | Berlaku selama … hari/bulan | period ≥ 1, `DAY` atau `MONTH` |
|
||||||
|
| `end_of_month` | `ROLLING` | Bulatkan ke akhir bulan | – |
|
||||||
|
| `reminder_days` | aktif | Ingatkan customer … hari sebelumnya | ≥ 0, 0 = tanpa pengingat |
|
||||||
|
|
||||||
|
**Tanggal tetap (`FIXED_DATE`).** Semua saldo hangus di tanggal yang sama, mis. 31 Desember, atau 30 Juni dan 31 Desember untuk dua kali setahun. Saldo yang didapat kurang dari `grace_months` sebelum tanggal itu ikut ke tanggal berikutnya, jadi saldo yang didapat 1 Oktober dengan tanggung 3 bulan hangus 31 Desember tahun depan. Untuk input `fixed_dates`, pakai pemilih tanggal+bulan tanpa tahun.
|
||||||
|
|
||||||
|
**Sejak didapat (`ROLLING`).** Tiap saldo berlaku `period` hari atau bulan sejak masuk, mis. 12 bulan. Dengan `end_of_month`, saldo yang didapat 14 Maret 2026 hangus 31 Maret 2027.
|
||||||
|
|
||||||
|
**Preview.** Response `GET`, `PUT`, dan dry run membawa `expiry_preview.point` dan `.coin`: kapan saldo yang didapat sekarang akan kedaluwarsa (`null` = tidak). Tampilkan di bawah form: "EnakPoint yang didapat hari ini kedaluwarsa pada 31 Des 2026." Karena dihitung dari nilai yang dikirim, dry run bisa dipakai untuk memperbarui preview saat owner mengubah pilihan.
|
||||||
|
|
||||||
|
**Menyalakan pertama kali.** Saldo lama yang belum punya tanggal ikut diberi tanggal, dengan masa berlaku penuh: tanggal hangus kedua berikutnya (`FIXED_DATE`) atau satu periode sejak hari ini (`ROLLING`). Dry run mengembalikan `expiry_activations`; tampilkan di dialog konfirmasi dengan kalimat tegas, mis. "1.250.000 EnakPoint milik customer yang ada sekarang akan kedaluwarsa pada 31 Des 2027. Tindakan ini tidak bisa dibatalkan dengan mematikan kedaluwarsa."
|
||||||
|
|
||||||
|
| Field `expiry_activations[]` | Arti |
|
||||||
|
| --- | --- |
|
||||||
|
| `currency` | `POINT` atau `COIN` |
|
||||||
|
| `lots` | Jumlah paket saldo yang diberi tanggal |
|
||||||
|
| `amount` | Total saldo yang diberi tanggal |
|
||||||
|
| `expires_at` | Tanggal kedaluwarsanya |
|
||||||
|
|
||||||
|
**Aturan lain yang perlu dijelaskan di layar:**
|
||||||
|
|
||||||
|
- Mengubah model atau masa berlaku hanya berlaku untuk saldo yang masuk setelahnya.
|
||||||
|
- Mematikan kedaluwarsa tidak membatalkan tanggal yang sudah terjadwal.
|
||||||
|
- Saldo yang ditransfer atau ditukar membawa tanggal kedaluwarsa aslinya.
|
||||||
|
- Saldo hangus tanpa kompensasi apa pun. Customer mendapat pengingat push `reminder_days` hari sebelumnya dan notifikasi saat hangus.
|
||||||
|
|
||||||
|
## Wallet customer
|
||||||
|
|
||||||
|
Tab Wallet di detail customer dipakai untuk menangani komplain: melihat saldo dan asal-usulnya, mengoreksi saldo, dan menelusuri satu mutasi sampai ke order asalnya.
|
||||||
|
|
||||||
|
### 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)
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"customer": { "id": "…", "name": "Budi Santoso", "phone": "081234561234" },
|
||||||
|
"point_balance": 12650,
|
||||||
|
"coin_balance": 8,
|
||||||
|
"spendable_point_balance": 12500,
|
||||||
|
"spendable_coin_balance": 8,
|
||||||
|
"lots": [
|
||||||
|
{ "id": "…", "currency": "POINT", "original_amount": 875, "remaining_amount": 875, "expires_at": "2026-12-31T23:59:59+07:00", "expired": false, "source_transaction_id": "…", "origin_lot_id": null, "created_at": "…" }
|
||||||
|
],
|
||||||
|
"transactions": {
|
||||||
|
"data": [
|
||||||
|
{
|
||||||
|
"id": "…", "currency": "POINT", "type": "TRANSFER_OUT", "amount": -120, "balance_after": 12650,
|
||||||
|
"description": "Transfer ke An*** (08**-****-5678)",
|
||||||
|
"destination": { "type": "WALLET_TX", "id": "…" },
|
||||||
|
"counterparty": { "id": "…", "name": "Anita Rahma" },
|
||||||
|
"created_by": null, "outlet": null, "reason": null, "metadata": {},
|
||||||
|
"created_at": "…"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"pagination": { "page": 1, "limit": 20, "total_count": 42, "total_pages": 3 }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
- **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`.
|
||||||
|
- **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).
|
||||||
|
|
||||||
|
### Adjustment manual
|
||||||
|
|
||||||
|
`POST /marketing/customers/:id/wallet/adjust`
|
||||||
|
|
||||||
|
```json
|
||||||
|
{ "currency": "POINT", "amount": -500, "reason": "Komplain #45", "idempotency_key": "adj-7f3c" }
|
||||||
|
```
|
||||||
|
|
||||||
|
| Field | Aturan |
|
||||||
|
| --- | --- |
|
||||||
|
| `currency` | `POINT` atau `COIN` |
|
||||||
|
| `amount` | Bertanda, tidak boleh 0. Positif menambah, negatif mengurangi |
|
||||||
|
| `reason` | Wajib; tampil di riwayat customer sebagai "Koreksi oleh admin: …" |
|
||||||
|
| `idempotency_key` | Opsional tapi disarankan: buat satu nilai saat dialog dibuka, supaya klik ganda tidak mengoreksi dua kali |
|
||||||
|
|
||||||
|
Pengurangan yang melebihi saldo yang bisa dipakai ditolak `304`. Adjustment tambah mengikuti aturan kedaluwarsa organisasi. Response: `{ "transaction", "spendable_point_balance", "spendable_coin_balance", "replayed" }`. Beri catatan di dialog bahwa adjustment tidak disertai pembayaran uang, sehingga alasan tidak boleh "pencairan".
|
||||||
|
|
||||||
|
### Telusuri mutasi
|
||||||
|
|
||||||
|
Dari baris riwayat mana pun, tombol Telusuri memanggil `GET /marketing/wallet-transactions/:id/trace`.
|
||||||
|
|
||||||
|
```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": "…" },
|
||||||
|
"lots": [
|
||||||
|
{
|
||||||
|
"amount": 30,
|
||||||
|
"chain": [
|
||||||
|
{ "lot": { "id": "…", "expires_at": "…", "origin_lot_id": "…" }, "source": { "type": "TRANSFER_IN", "customer": { "name": "Budi Santoso" }, "description": "Transfer dari An*** (08**-****-5678)" } },
|
||||||
|
{ "lot": { "id": "…", "origin_lot_id": null }, "source": { "type": "EARN", "customer": { "name": "Anita Rahma" }, "reference_type": "ORDER", "reference_id": "…", "description": "Belanja #ORD-1 di Outlet Kemang" } }
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
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 & keamanan customer
|
||||||
|
|
||||||
|
Admin tidak bisa membuat, mengganti, atau melihat PIN customer; satu-satunya aksi adalah menghapusnya, misalnya bila customer kehilangan akses, sehingga customer harus membuat PIN baru lewat OTP di aplikasi.
|
||||||
|
|
||||||
|
- `DELETE /marketing/customers/:id/pin` dengan body `{ "reason": "Customer ganti nomor HP" }`. `reason` wajib. Tampilkan dialog konfirmasi dengan input alasan.
|
||||||
|
- `GET /marketing/customers/:id/security-events?page=1&limit=20` untuk tab Keamanan:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"data": [
|
||||||
|
{ "id": "…", "event": "PIN_LOCKED", "actor_user": null, "reason": null, "ip_address": "103.10.0.7", "user_agent": "EnakApp/2.4 (Android 14)", "created_at": "…" }
|
||||||
|
],
|
||||||
|
"pagination": { "page": 1, "limit": 20, "total_count": 5, "total_pages": 1 }
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
| `event` | Label usulan |
|
||||||
|
| --- | --- |
|
||||||
|
| `PIN_SET` | PIN dibuat |
|
||||||
|
| `PIN_CHANGED` | PIN diganti |
|
||||||
|
| `PIN_RESET` | PIN direset lewat OTP (transfer ditahan 24 jam) |
|
||||||
|
| `PIN_FAILED` | PIN salah dimasukkan |
|
||||||
|
| `PIN_LOCKED` | PIN terkunci 30 menit |
|
||||||
|
| `PIN_REMOVED_BY_ADMIN` | PIN dihapus admin (`actor_user`, `reason` terisi) |
|
||||||
|
|
||||||
|
### Riwayat perubahan setting
|
||||||
|
|
||||||
|
`GET /marketing/loyalty-settings/history?page=1&limit=20` untuk setting organisasi; tambah `&outlet_id=…` untuk riwayat satu outlet.
|
||||||
|
|
||||||
|
```json
|
||||||
|
{ "id": "…", "organization_id": "…", "outlet_id": null, "key": "loyalty.point.value", "old_value": "1", "new_value": "2", "changed_by": "…", "created_at": "…" }
|
||||||
|
```
|
||||||
|
|
||||||
|
`old_value` `null` berarti sebelumnya masih nilai default. Tampilkan `key` dengan label yang sama seperti di form (mis. `loyalty.point.value` → "Nilai 1 EnakPoint"), dan `changed_by` sebagai nama user.
|
||||||
|
|
||||||
|
### Biaya main game
|
||||||
|
|
||||||
|
Semua game (spin, raffle, minigame) memakai EnakCoin yang sama. Biaya per main diisi di `metadata.coin_cost` saat membuat atau mengedit game (`/marketing/games`): bilangan bulat ≥ 1, default 1 bila kosong. Nilai pecahan, 0, atau teks membuat game tidak bisa dimainkan. Karena `metadata` dikirim utuh, pertahankan key metadata lain saat menyimpan. Hadiah game juga bernilai rupiah secara tidak langsung, karena EnakCoin bisa ditukar ke EnakPoint.
|
||||||
|
|
||||||
|
### 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
|
||||||
|
|
||||||
|
| `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 |
|
||||||
|
| `304` | 400 | Nilai di luar batas, adjustment melebihi saldo, alasan kosong, hapus/ubah method EnakPoint | `cause` di dekat field atau di toast |
|
||||||
|
| `404` | 404 | Customer, outlet, atau mutasi bukan milik organisasi ini | "Data tidak ditemukan" |
|
||||||
|
| `900` | 500 | Kesalahan server | "Terjadi kesalahan, coba lagi" |
|
||||||
|
|
||||||
|
Pesan `cause` saat ini berbahasa Inggris, mis. `invalid loyalty settings: loyalty.point.earn_per_amount must be at least 1`. Untuk validasi form, lebih baik cek batasnya di sisi klien (tabel di tiap bagian) dan tampilkan `cause` hanya sebagai cadangan.
|
||||||
|
|
||||||
|
### Checklist rilis
|
||||||
|
|
||||||
|
- [ ] Form setting outlet menampilkan cashback efektif dan contoh earning.
|
||||||
|
- [ ] Setting organisasi selalu lewat dry run dan dialog konfirmasi sebelum disimpan.
|
||||||
|
- [ ] Dialog konfirmasi menampilkan `impact` saat nilai EnakPoint atau kurs berubah.
|
||||||
|
- [ ] Dialog konfirmasi menampilkan `expiry_activations` saat kedaluwarsa dinyalakan pertama kali.
|
||||||
|
- [ ] Preview "yang didapat hari ini kedaluwarsa pada …" tampil di bawah pengaturan kedaluwarsa.
|
||||||
|
- [ ] Wallet customer menampilkan saldo yang bisa dipakai, lot, dan riwayat dengan nama asli.
|
||||||
|
- [ ] Adjustment mewajibkan alasan dan mengirim `idempotency_key`.
|
||||||
|
- [ ] Tombol Telusuri ada di setiap baris riwayat.
|
||||||
|
- [ ] Hapus PIN mewajibkan alasan; tab Keamanan menampilkan log.
|
||||||
|
- [ ] Method EnakPoint tampil sebagai method sistem.
|
||||||
|
- [ ] Form game punya input `coin_cost`.
|
||||||
|
- [ ] 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.
|
||||||
@@ -474,16 +474,14 @@ Response:
|
|||||||
|
|
||||||
```json
|
```json
|
||||||
{
|
{
|
||||||
"game_play": { "id": "…", "game_id": "…", "coins_used": 1, "token_used": 1, "created_at": "…" },
|
"game_play": { "id": "…", "game_id": "…", "coins_used": 1, "created_at": "…" },
|
||||||
"prize_won": { "id": "…", "name": "Voucher 10rb", … },
|
"prize_won": { "id": "…", "name": "Voucher 10rb", … },
|
||||||
"coins_remaining": 7,
|
"coins_remaining": 7
|
||||||
"tokens_remaining": 7
|
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
EnakCoin kurang, game nonaktif, atau hadiah baru saja habis dijawab `304`; tidak ada
|
EnakCoin kurang, game nonaktif, atau hadiah baru saja habis dijawab `304`; tidak ada
|
||||||
EnakCoin yang terpotong. Baca `coins_used` dan `coins_remaining`; `token_used` dan
|
EnakCoin yang terpotong.
|
||||||
`tokens_remaining` hanya salinan untuk versi aplikasi lama.
|
|
||||||
|
|
||||||
Di dashboard, `metadata.coin_cost` diisi per game dengan bilangan bulat ≥ 1.
|
Di dashboard, `metadata.coin_cost` diisi per game dengan bilangan bulat ≥ 1.
|
||||||
|
|
||||||
@@ -497,13 +495,14 @@ pindah. Aplikasi baru jangan memakainya.
|
|||||||
| Lama | Ganti dengan |
|
| Lama | Ganti dengan |
|
||||||
|---|---|
|
|---|---|
|
||||||
| `GET /customer/points` | `GET /customer/wallet` (`point_balance`) |
|
| `GET /customer/points` | `GET /customer/wallet` (`point_balance`) |
|
||||||
| `GET /customer/tokens` | `GET /customer/wallet` (`coin_balance`) |
|
| `total_points`, `points_history`, `last_updated` di `/customer/wallet` | `point_balance`, `recent_transactions` |
|
||||||
| `total_points`, `total_tokens`, `points_history`, `tokens_history`, `last_updated` di `/customer/wallet` | `point_balance`, `coin_balance`, `recent_transactions` |
|
|
||||||
| `token_used`, `tokens_remaining` di respons game | `coins_used`, `coins_remaining` |
|
|
||||||
| `sort_by=token_used` di daftar game play | `sort_by=coins_used` |
|
|
||||||
|
|
||||||
Beri tahu tim backend setelah aplikasi yang beredar tidak lagi memakai kolom kiri,
|
Beri tahu tim backend setelah aplikasi yang beredar tidak lagi memakai kolom kiri,
|
||||||
supaya alias dan tabel lama (`customer_points`, `customer_tokens`) bisa dihapus.
|
supaya alias ini bisa dihapus.
|
||||||
|
|
||||||
|
Semua yang bernama token sudah dihapus: `GET /customer/tokens`, `total_tokens`,
|
||||||
|
`tokens_history`, `token_used`, `tokens_remaining`, dan nilai `TOKENS` di campaign. Pakai
|
||||||
|
`coin_balance`, `coins_used`, `coins_remaining`, dan `COINS`.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,614 @@
|
|||||||
|
# Prompt: fitur EnakPoint & EnakCoin di Mobile App Customer
|
||||||
|
|
||||||
|
Kamu mengerjakan aplikasi mobile untuk **customer** (bukan kasir, bukan backoffice).
|
||||||
|
Tugasmu: membangun fitur loyalitas EnakPoint & EnakCoin di aplikasi, memakai API backend
|
||||||
|
yang sudah jadi dan dijelaskan di dokumen ini. Jangan mengarang endpoint, field, atau
|
||||||
|
aturan yang tidak tertulis di sini; kalau ada yang kurang jelas, tanyakan dulu.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. Konteks bisnis
|
||||||
|
|
||||||
|
| | EnakPoint (`POINT`) | EnakCoin (`COIN`) |
|
||||||
|
|---|---|---|
|
||||||
|
| Didapat dari | Belanja (order lunas), koreksi admin, tukar EnakCoin | Belanja, koreksi admin |
|
||||||
|
| Dipakai untuk | **Membayar order** | **Main game**, ditukar ke EnakPoint |
|
||||||
|
| Bisa dikirim ke customer lain | Ya | Ya |
|
||||||
|
| Bisa kedaluwarsa | Ya, bila owner mengaktifkan | Ya, bila owner mengaktifkan |
|
||||||
|
|
||||||
|
Tidak ada lagi "token". Semua yang dulu token sekarang EnakCoin, dan endpoint serta
|
||||||
|
field bernama token sudah dihapus dari API.
|
||||||
|
|
||||||
|
### Aturan yang wajib dipatuhi di UI
|
||||||
|
|
||||||
|
1. **Semua jumlah bilangan bulat.** Tidak ada desimal pada EnakPoint atau EnakCoin.
|
||||||
|
2. **Saldo bukan uang.** Nilai rupiah EnakPoint selalu ditulis **"setara potongan
|
||||||
|
Rp …"**, tidak pernah "saldo Rp …" atau "uang". Tidak ada fitur tarik tunai.
|
||||||
|
3. **PIN 6 digit wajib** untuk: membuat kode bayar, tukar
|
||||||
|
EnakCoin, dan transfer. **Main game tidak butuh PIN.** Melihat saldo dan riwayat
|
||||||
|
tidak butuh PIN.
|
||||||
|
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
|
||||||
|
analytics.
|
||||||
|
5. **Satu akun customer = satu organisasi.** Saldo berlaku di semua outlet organisasi itu.
|
||||||
|
6. **Waktu memakai WIB.** Tanggal kedaluwarsa berarti saldo masih bisa dipakai sampai
|
||||||
|
23:59:59 WIB di tanggal itu.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. Koneksi ke API
|
||||||
|
|
||||||
|
- Base URL: `/api/v1`
|
||||||
|
- Semua endpoint customer: header `Authorization: Bearer <token login customer>`
|
||||||
|
- Semua jumlah di request dan response berupa integer.
|
||||||
|
|
||||||
|
### Registrasi customer
|
||||||
|
|
||||||
|
`POST /api/v1/customer-auth/register/start` menerima `organization_id` (opsional):
|
||||||
|
|
||||||
|
```json
|
||||||
|
{ "phone_number": "0812…", "name": "Budi", "birth_date": "2000-01-31", "organization_id": "648b96a0-1d1d-414e-baee-37e9d6317b4e" }
|
||||||
|
```
|
||||||
|
|
||||||
|
- Customer terdaftar di satu organisasi, dan saldonya berlaku di semua outlet organisasi itu.
|
||||||
|
- Bila `organization_id` tidak dikirim dan backend hanya punya satu organisasi, customer
|
||||||
|
otomatis masuk ke organisasi itu. Bila ada lebih dari satu, registrasi ditolak
|
||||||
|
("organization_id is required"), jadi sebaiknya app selalu mengirimnya dari config per
|
||||||
|
environment/brand.
|
||||||
|
- `organization_id` yang dikirim harus ada; bila tidak, registrasi ditolak sebelum OTP dikirim.
|
||||||
|
- Wallet customer baru belum punya baris sampai saldo pertama kali bergerak;
|
||||||
|
`GET /customer/wallet` tetap menjawab saldo 0.
|
||||||
|
|
||||||
|
### Format response
|
||||||
|
|
||||||
|
Sukses:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{ "success": true, "data": { … }, "errors": null }
|
||||||
|
```
|
||||||
|
|
||||||
|
Gagal:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{ "success": false, "data": null, "errors": [{ "code": "304", "entity": "wallet_service", "cause": "wallet move refused: not enough EnakCoin" }] }
|
||||||
|
```
|
||||||
|
|
||||||
|
| `errors[0].code` | HTTP | Arti | Yang dilakukan app |
|
||||||
|
|---|---|---|---|
|
||||||
|
| `303`, `310` | 400 | Request tidak lengkap / salah format | Bug di app; tampilkan pesan umum |
|
||||||
|
| `304` | 400 | Ditolak aturan bisnis | Tampilkan pesan yang ramah (lihat tiap fitur); `cause` berbahasa Inggris, jangan tampilkan mentah |
|
||||||
|
| `404` | 404 | Tidak ditemukan | Tampilkan "tidak ditemukan" |
|
||||||
|
| `429` | 429 | Minta OTP terlalu cepat | Tampilkan hitung mundur sebelum boleh minta lagi |
|
||||||
|
| `PIN_NOT_SET` | 403 | Belum punya PIN | Buka alur buat PIN (§6.2) |
|
||||||
|
| `PIN_INVALID` | 400 | PIN salah | §6.5 |
|
||||||
|
| `PIN_LOCKED` | 423 | PIN terkunci | §6.5 |
|
||||||
|
| `TRANSFER_BLOCKED` | 403 | Transfer ditahan setelah reset PIN | §6.5 |
|
||||||
|
| `900` | 500 | Error server | "Terjadi kesalahan, coba lagi" |
|
||||||
|
|
||||||
|
### Idempotency-Key
|
||||||
|
|
||||||
|
Endpoint **tukar** dan **transfer** wajib header `Idempotency-Key` (string unik, maks.
|
||||||
|
50 karakter, mis. UUID v4).
|
||||||
|
|
||||||
|
- Buat **satu key baru saat customer menekan tombol konfirmasi**.
|
||||||
|
- Bila request gagal karena jaringan/timeout, **kirim ulang dengan key yang sama**.
|
||||||
|
Server mengembalikan hasil pertama dengan `"replayed": true` dan tidak memotong saldo
|
||||||
|
dua kali.
|
||||||
|
- Jangan pakai ulang key untuk transaksi yang berbeda; server menolaknya (`304`).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. Layar yang perlu dibuat
|
||||||
|
|
||||||
|
| Layar | Endpoint utama | Butuh PIN |
|
||||||
|
|---|---|---|
|
||||||
|
| Beranda wallet | `GET /customer/wallet` | – |
|
||||||
|
| Riwayat mutasi | `GET /customer/wallet/transactions` | – |
|
||||||
|
| Saldo akan kedaluwarsa | `GET /customer/wallet/expiring` | – |
|
||||||
|
| Daftar outlet | `GET /customer/outlets` | – |
|
||||||
|
| 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 |
|
||||||
|
| Transfer | `GET …/transfer/recipient`, `POST /customer/wallet/transfer` | Ya |
|
||||||
|
| PIN (buat, ganti, lupa) | `/customer/pin/*` | – |
|
||||||
|
| Game | `POST /customer/spin` | – |
|
||||||
|
| (latar belakang) registrasi push | `PUT` / `DELETE /customer/devices` | – |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. Beranda wallet, riwayat, kedaluwarsa
|
||||||
|
|
||||||
|
### 4.1 Beranda — `GET /customer/wallet`
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"point_balance": 12500,
|
||||||
|
"coin_balance": 8,
|
||||||
|
"point_value": 1,
|
||||||
|
"point_discount_value": 12500,
|
||||||
|
"nearest_expiring": {
|
||||||
|
"point": { "amount": 150, "date": "2026-12-31" },
|
||||||
|
"coin": null
|
||||||
|
},
|
||||||
|
"recent_transactions": [ /* sama dengan item riwayat §4.2, maksimal 5 */ ]
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Tampilkan:
|
||||||
|
- Saldo EnakPoint (`point_balance`) dengan keterangan "setara potongan Rp
|
||||||
|
{point_discount_value}" (format ribuan Indonesia: `Rp 12.500`).
|
||||||
|
- Saldo EnakCoin (`coin_balance`).
|
||||||
|
- Bila `nearest_expiring.point` / `.coin` tidak `null`: banner "{amount} EnakPoint akan
|
||||||
|
kedaluwarsa pada {date}" yang membuka layar §4.3.
|
||||||
|
- 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).
|
||||||
|
|
||||||
|
Muat ulang beranda setelah setiap transaksi dan saat menerima push (§5).
|
||||||
|
|
||||||
|
Field `total_points`, `points_history`, `last_updated` di response ini **deprecated**;
|
||||||
|
jangan dipakai.
|
||||||
|
|
||||||
|
### 4.2 Riwayat — `GET /customer/wallet/transactions`
|
||||||
|
|
||||||
|
Query (semua opsional):
|
||||||
|
|
||||||
|
| Query | Contoh | Keterangan |
|
||||||
|
|---|---|---|
|
||||||
|
| `page` | `1` | Mulai dari 1 |
|
||||||
|
| `limit` | `20` | 1–100, default 20 |
|
||||||
|
| `currency` | `POINT` | `POINT` atau `COIN`; untuk tab EnakPoint / EnakCoin |
|
||||||
|
| `type` | `EARN,PAYMENT` | Satu atau beberapa tipe dipisah koma, untuk filter |
|
||||||
|
| `from`, `to` | `2026-09-01` | Tanggal WIB, inklusif |
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"data": [
|
||||||
|
{
|
||||||
|
"id": "…",
|
||||||
|
"currency": "POINT",
|
||||||
|
"type": "EARN",
|
||||||
|
"amount": 875,
|
||||||
|
"balance_after": 12500,
|
||||||
|
"description": "Belanja #ORD-0123 di Outlet Kemang",
|
||||||
|
"source": { "type": "ORDER", "id": "…" },
|
||||||
|
"outlet_id": "…",
|
||||||
|
"group_id": null,
|
||||||
|
"expires_at": "2026-12-31T23:59:59+07:00",
|
||||||
|
"lots": [{ "amount": 875, "remaining": 875, "expires_at": "2026-12-31T23:59:59+07:00" }],
|
||||||
|
"created_at": "2026-09-30T12:01:00Z"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"pagination": { "page": 1, "limit": 20, "total_count": 42, "total_pages": 3 }
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Aturan tampilan:
|
||||||
|
- `amount` bertanda: positif tampil hijau dengan `+`, negatif merah dengan `−`.
|
||||||
|
- `description` sudah siap tampil (nama lawan transfer sudah disamarkan). Tampilkan apa
|
||||||
|
adanya.
|
||||||
|
- Mutasi masuk yang punya `expires_at` menampilkan "Berlaku sampai {tanggal}".
|
||||||
|
- Infinite scroll memakai `pagination.total_pages`.
|
||||||
|
- Riwayat tidak pernah berubah atau hilang; koreksi muncul sebagai baris baru.
|
||||||
|
|
||||||
|
Label tipe:
|
||||||
|
|
||||||
|
| `type` | Label | Arah |
|
||||||
|
|---|---|---|
|
||||||
|
| `EARN` | Dari belanja | + |
|
||||||
|
| `EARN_REVERSAL` | Dibatalkan (order di-void/refund) | − |
|
||||||
|
| `PAYMENT` | Bayar pesanan | − |
|
||||||
|
| `PAYMENT_REFUND` | Pengembalian pembayaran | + |
|
||||||
|
| `EXCHANGE_OUT` | Ditukar ke EnakPoint | − |
|
||||||
|
| `EXCHANGE_IN` | Hasil tukar EnakCoin | + |
|
||||||
|
| `TRANSFER_OUT` | Transfer keluar | − |
|
||||||
|
| `TRANSFER_IN` | Transfer masuk | + |
|
||||||
|
| `GAME_SPEND` | Main game | − |
|
||||||
|
| `EXPIRE` | Kedaluwarsa | − |
|
||||||
|
| `ADJUSTMENT` | Koreksi | + / − |
|
||||||
|
| `MIGRATION` | Saldo awal | + |
|
||||||
|
|
||||||
|
### 4.3 Akan kedaluwarsa — `GET /customer/wallet/expiring`
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"point": [
|
||||||
|
{ "amount": 150, "date": "2026-10-31" },
|
||||||
|
{ "amount": 200, "date": "2026-12-31" }
|
||||||
|
],
|
||||||
|
"coin": []
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Daftar per tanggal, paling dekat di atas. Daftar kosong: tampilkan "Tidak ada saldo
|
||||||
|
yang akan kedaluwarsa". Saldo yang kedaluwarsa hangus tanpa kompensasi.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 4.4 Daftar outlet — `GET /customer/outlets`
|
||||||
|
|
||||||
|
Outlet aktif di organisasi customer, tempat saldo EnakPoint & EnakCoin berlaku. Urut
|
||||||
|
berdasarkan nama.
|
||||||
|
|
||||||
|
```json
|
||||||
|
[
|
||||||
|
{
|
||||||
|
"id": "…",
|
||||||
|
"name": "Gokuna Kemang",
|
||||||
|
"address": "Jl. Kemang Raya 10",
|
||||||
|
"accepts_point_payment": true,
|
||||||
|
"earns_points": true,
|
||||||
|
"earns_coins": false
|
||||||
|
}
|
||||||
|
]
|
||||||
|
```
|
||||||
|
|
||||||
|
- `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.
|
||||||
|
- Belum ada telepon, koordinat, atau jam buka; data itu belum disimpan di backend.
|
||||||
|
|
||||||
|
|
||||||
|
### 4.5 Riwayat order — `GET /customer/orders` dan `GET /customer/orders/:id`
|
||||||
|
|
||||||
|
Order milik customer yang login di semua outlet organisasinya, terbaru di atas. Order
|
||||||
|
hanya masuk ke sini bila kasir mengaitkannya ke customer.
|
||||||
|
|
||||||
|
`GET /api/v1/customer/orders?page=1&limit=20` (`limit` 1–100, default 20):
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"data": [
|
||||||
|
{
|
||||||
|
"id": "…",
|
||||||
|
"order_number": "ORD-0123",
|
||||||
|
"outlet_id": "…",
|
||||||
|
"outlet_name": "Gokuna 1",
|
||||||
|
"order_type": "dine_in",
|
||||||
|
"status": "completed",
|
||||||
|
"payment_status": "completed",
|
||||||
|
"total_amount": 99000,
|
||||||
|
"item_count": 2,
|
||||||
|
"is_void": false,
|
||||||
|
"is_refund": false,
|
||||||
|
"points_earned": 865,
|
||||||
|
"coins_earned": 3,
|
||||||
|
"created_at": "2026-09-30T12:01:00Z"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"pagination": { "page": 1, "limit": 20, "total_count": 42, "total_pages": 3 }
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
`GET /api/v1/customer/orders/{id}` mengembalikan field yang sama, ditambah:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"table_number": "A3",
|
||||||
|
"subtotal": 90000,
|
||||||
|
"discount_amount": 0,
|
||||||
|
"tax_amount": 9000,
|
||||||
|
"refund_amount": 0,
|
||||||
|
"items": [
|
||||||
|
{
|
||||||
|
"id": "…",
|
||||||
|
"product_id": "…",
|
||||||
|
"product_name": "Kopi Susu",
|
||||||
|
"variant_name": "Large",
|
||||||
|
"quantity": 2,
|
||||||
|
"unit_price": 25000,
|
||||||
|
"total_price": 50000,
|
||||||
|
"refund_quantity": 0,
|
||||||
|
"modifiers": [],
|
||||||
|
"status": "completed"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "…",
|
||||||
|
"product_id": "…",
|
||||||
|
"product_name": "Ikan Tude",
|
||||||
|
"variant_name": null,
|
||||||
|
"quantity": 1,
|
||||||
|
"weight": 4.2,
|
||||||
|
"unit_name": "ons",
|
||||||
|
"unit_price": 4500,
|
||||||
|
"total_price": 18900,
|
||||||
|
"refund_quantity": 0,
|
||||||
|
"modifiers": [],
|
||||||
|
"status": "completed"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"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": 86500, "status": "completed", "refund_amount": 0, "created_at": "…" }
|
||||||
|
]
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
- Order customer lain atau yang tidak ada → `404`.
|
||||||
|
- `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".
|
||||||
|
- Pembayaran EnakPoint membawa `points_used`; tampilkan "EnakPoint 12.500 (Rp 12.500)".
|
||||||
|
- Order yang `is_void` atau `is_refund` tetap tampil, beri label "Dibatalkan" /
|
||||||
|
"Direfund".
|
||||||
|
|
||||||
|
|
||||||
|
## 5. Notifikasi push (FCM)
|
||||||
|
|
||||||
|
### 5.1 Registrasi device
|
||||||
|
|
||||||
|
Setelah login berhasil **dan** setiap kali FCM memberi token baru (`onTokenRefresh`):
|
||||||
|
|
||||||
|
`PUT /api/v1/customer/devices`
|
||||||
|
|
||||||
|
```json
|
||||||
|
{ "device_id": "<id unik & stabil per instalasi>", "fcm_token": "<token FCM>", "platform": "android", "app_version": "2.4.0" }
|
||||||
|
```
|
||||||
|
|
||||||
|
- `device_id` wajib, stabil untuk satu instalasi (simpan di secure storage).
|
||||||
|
- `platform`: `android`, `ios`, atau `web`.
|
||||||
|
- Saat **logout**, panggil `DELETE /api/v1/customer/devices/{device_id}` sebelum
|
||||||
|
menghapus token login, supaya HP itu tidak lagi menerima notifikasi akun ini.
|
||||||
|
|
||||||
|
Tanpa registrasi ini, customer tidak menerima push apa pun.
|
||||||
|
|
||||||
|
### 5.2 Tipe push
|
||||||
|
|
||||||
|
Semua nilai di `data` berupa string.
|
||||||
|
|
||||||
|
| `data.type` | Kapan | Isi `data` lain | Aksi saat di-tap |
|
||||||
|
|---|---|---|---|
|
||||||
|
| `WALLET_TRANSFER_IN` | Menerima transfer | `transaction_id`, `group_id`, `currency`, `amount` | Buka riwayat, sorot transaksi itu |
|
||||||
|
| `WALLET_EXPIRING` | Beberapa hari sebelum saldo hangus | `currency`, `amount`, `expiry_date` | Buka layar kedaluwarsa (§4.3) |
|
||||||
|
| `WALLET_EXPIRED` | Saldo baru saja hangus | `currency`, `amount` | Buka riwayat |
|
||||||
|
| `PIN_LOCKED` | PIN terkunci setelah 5 kali salah | `locked_until` (RFC3339 UTC) | Buka layar lupa PIN (§6.4) |
|
||||||
|
|
||||||
|
Saat app terbuka dan menerima push wallet, muat ulang beranda.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 6. PIN
|
||||||
|
|
||||||
|
### 6.1 Kapan diminta
|
||||||
|
|
||||||
|
Jangan minta PIN saat registrasi. Minta saat customer **pertama kali** melakukan aksi
|
||||||
|
yang butuh PIN. Cek dengan:
|
||||||
|
|
||||||
|
`GET /api/v1/customer/pin/status` → `{ "has_pin": false, "locked_until": null, "transfer_blocked_until": null }`
|
||||||
|
|
||||||
|
Bila `has_pin: false`, arahkan ke alur buat PIN, lalu kembali ke aksi semula.
|
||||||
|
|
||||||
|
### 6.2 Buat PIN
|
||||||
|
|
||||||
|
1. `POST /api/v1/customer/pin/otp` dengan `{ "purpose": "pin_setup" }`.
|
||||||
|
Response: `{ "purpose": "pin_setup", "otp_token": "…", "expires_at": "…" }`.
|
||||||
|
OTP dikirim ke WhatsApp customer.
|
||||||
|
2. Customer memasukkan kode OTP, lalu PIN dua kali.
|
||||||
|
3. `POST /api/v1/customer/pin` dengan
|
||||||
|
`{ "otp_token": "…", "otp_code": "123456", "pin": "482913", "confirm_pin": "482913" }`.
|
||||||
|
Response: status PIN.
|
||||||
|
|
||||||
|
Validasi di app sebelum kirim (server juga memeriksa, jawab `304`):
|
||||||
|
- Tepat 6 digit angka, dan konfirmasi sama.
|
||||||
|
- Bukan satu digit berulang (`111111`).
|
||||||
|
- Bukan berurutan naik/turun (`123456`, `654321`).
|
||||||
|
- Bukan tanggal lahir customer (`DDMMYY` atau `YYMMDD`).
|
||||||
|
|
||||||
|
Minta OTP lagi terlalu cepat → `429`: tampilkan hitung mundur.
|
||||||
|
|
||||||
|
### 6.3 Ganti PIN
|
||||||
|
|
||||||
|
`PUT /api/v1/customer/pin` dengan `{ "old_pin": "…", "pin": "…", "confirm_pin": "…" }`.
|
||||||
|
|
||||||
|
### 6.4 Lupa PIN
|
||||||
|
|
||||||
|
1. `POST /customer/pin/otp` dengan `{ "purpose": "pin_reset" }`.
|
||||||
|
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**;
|
||||||
|
bayar dan tukar tetap bisa. Beri tahu customer hal ini di layar sukses.
|
||||||
|
|
||||||
|
### 6.5 Menangani error PIN
|
||||||
|
|
||||||
|
Semua endpoint yang menerima `pin` bisa menjawab error PIN. Pada error ini **`data`
|
||||||
|
tidak `null`**:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{ "success": false, "data": { "code": "PIN_INVALID", "remaining_attempts": 3 }, "errors": [ … ] }
|
||||||
|
```
|
||||||
|
|
||||||
|
| `data.code` | Field tambahan | Tampilan |
|
||||||
|
|---|---|---|
|
||||||
|
| `PIN_NOT_SET` | – | Buka alur buat PIN (§6.2) |
|
||||||
|
| `PIN_INVALID` | `remaining_attempts` | "PIN salah, sisa {n} percobaan." Kosongkan input PIN |
|
||||||
|
| `PIN_LOCKED` | `locked_until` | "PIN terkunci sampai {jam}." Tombol "Lupa PIN" |
|
||||||
|
| `TRANSFER_BLOCKED` | `transfer_blocked_until` | "Transfer bisa dilakukan lagi pada {waktu}." |
|
||||||
|
|
||||||
|
5 kali salah berturut-turut mengunci PIN 30 menit; selama terkunci PIN yang benar pun
|
||||||
|
ditolak. Penghitung ada di server, jadi jangan membuat penghitung sendiri di app.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 7. Membayar dengan EnakPoint
|
||||||
|
|
||||||
|
App customer tidak membuat atau membayar order; order hanya bisa dilihat (§4.5).
|
||||||
|
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):
|
||||||
|
|
||||||
|
`GET /api/v1/customer/wallet/exchange/preview?coins=30`
|
||||||
|
|
||||||
|
```json
|
||||||
|
{ "coin_amount": 10, "point_amount": 3, "coin_balance": 35, "coins": 30, "points": 9, "valid": true }
|
||||||
|
```
|
||||||
|
|
||||||
|
- Kurs: `coin_amount` EnakCoin = `point_amount` EnakPoint. Tampilkan "10 EnakCoin =
|
||||||
|
3 EnakPoint".
|
||||||
|
- Bila `valid: false`, tampilkan `reason` sebagai alasan dan nonaktifkan tombol. Jumlah
|
||||||
|
harus kelipatan `coin_amount`.
|
||||||
|
- Tampilkan "Kamu akan mendapat {points} EnakPoint".
|
||||||
|
|
||||||
|
2. Konfirmasi (tukar tidak bisa dibatalkan) → minta PIN →
|
||||||
|
|
||||||
|
`POST /api/v1/customer/wallet/exchange` + header `Idempotency-Key`
|
||||||
|
|
||||||
|
```json
|
||||||
|
{ "coins": 30, "pin": "482913" }
|
||||||
|
```
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"group_id": "…",
|
||||||
|
"coins": 30,
|
||||||
|
"points": 9,
|
||||||
|
"coin_amount": 10,
|
||||||
|
"point_amount": 3,
|
||||||
|
"lots": [{ "amount": 9, "expires_at": "2026-12-31T23:59:59+07:00" }],
|
||||||
|
"coin_balance": 5,
|
||||||
|
"point_balance": 9,
|
||||||
|
"replayed": false
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
3. Layar sukses: saldo baru, dan bila `lots[].expires_at` ada, "EnakPoint ini berlaku
|
||||||
|
sampai {tanggal}".
|
||||||
|
|
||||||
|
### 8.2 Transfer
|
||||||
|
|
||||||
|
1. Pilih mata uang (EnakPoint / EnakCoin), isi nomor HP penerima dan jumlah.
|
||||||
|
2. Cek penerima:
|
||||||
|
|
||||||
|
`GET /api/v1/customer/wallet/transfer/recipient?phone=081234561234`
|
||||||
|
|
||||||
|
```json
|
||||||
|
{ "name": "Bu*** Sa***", "phone_number": "08**-****-1234" }
|
||||||
|
```
|
||||||
|
|
||||||
|
| Hasil | Tampilan |
|
||||||
|
|---|---|
|
||||||
|
| Sukses | "Kirim ke Bu*** Sa*** (08**-****-1234)?" |
|
||||||
|
| `404` | "Nomor ini tidak terdaftar" |
|
||||||
|
| `304` | "Tidak bisa mengirim ke nomor ini" (diri sendiri, akun nonaktif) |
|
||||||
|
|
||||||
|
3. Konfirmasi (transfer final, tidak bisa dibatalkan) → minta PIN →
|
||||||
|
|
||||||
|
`POST /api/v1/customer/wallet/transfer` + header `Idempotency-Key`
|
||||||
|
|
||||||
|
```json
|
||||||
|
{ "currency": "POINT", "amount": 120, "recipient_phone": "081234561234", "pin": "482913" }
|
||||||
|
```
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"group_id": "…",
|
||||||
|
"currency": "POINT",
|
||||||
|
"amount": 120,
|
||||||
|
"recipient": { "name": "Bu*** Sa***", "phone_number": "08**-****-1234" },
|
||||||
|
"lots": [
|
||||||
|
{ "amount": 100, "expires_at": "2026-12-31T23:59:59+07:00" },
|
||||||
|
{ "amount": 20, "expires_at": null }
|
||||||
|
],
|
||||||
|
"balance": 30,
|
||||||
|
"replayed": false
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
4. Layar sukses: saldo tersisa (`balance`). Bila ada `lots[].expires_at`, tampilkan
|
||||||
|
"Saldo yang dikirim berlaku sampai {tanggal}" (tanggal kedaluwarsa ikut terbawa ke
|
||||||
|
penerima).
|
||||||
|
|
||||||
|
Penolakan `304` yang mungkin: transfer dimatikan owner, di bawah minimal, di atas
|
||||||
|
maksimal per transaksi, melewati batas harian (reset tengah malam WIB), saldo tidak
|
||||||
|
cukup. Tampilkan pesan umum "Transfer tidak bisa diproses" plus alasan yang sesuai
|
||||||
|
bila bisa dikenali. Bila kena `TRANSFER_BLOCKED`, ikuti §6.5.
|
||||||
|
|
||||||
|
Penerima mendapat push `WALLET_TRANSFER_IN`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 9. Game (memakai EnakCoin)
|
||||||
|
|
||||||
|
`POST /api/v1/customer/spin` dengan `{ "spin_id": "<id game>" }`. Tanpa PIN.
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"game_play": { "id": "…", "game_id": "…", "coins_used": 1, "created_at": "…" },
|
||||||
|
"prize_won": { "id": "…", "name": "Voucher 10rb" },
|
||||||
|
"coins_remaining": 7
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
- Setiap game punya biaya sendiri: `metadata.coin_cost` pada data game dari
|
||||||
|
`GET /api/v1/customer/games` (atau `GET /customer/ferris-wheel`), default 1 bila kosong.
|
||||||
|
Tampilkan biaya sebelum main, dan nonaktifkan tombol bila `coin_balance` kurang.
|
||||||
|
- `304`: EnakCoin kurang, game nonaktif, atau hadiah baru saja habis. Tidak ada
|
||||||
|
EnakCoin yang terpotong; tampilkan pesan dan biarkan customer mencoba lagi.
|
||||||
|
- Setelah main, perbarui saldo EnakCoin dari `coins_remaining`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 10. Yang sudah dihapus / deprecated
|
||||||
|
|
||||||
|
Sudah **dihapus** dari API (jangan dipanggil, akan error / tidak ada):
|
||||||
|
|
||||||
|
| Lama | Pengganti |
|
||||||
|
|---|---|
|
||||||
|
| `GET /customer/tokens` | `GET /customer/wallet` → `coin_balance` |
|
||||||
|
| `total_tokens`, `tokens_history` | `coin_balance`, `GET /customer/wallet/transactions?currency=COIN` |
|
||||||
|
| `token_used`, `tokens_remaining` di response game | `coins_used`, `coins_remaining` |
|
||||||
|
|
||||||
|
Masih ada tapi **deprecated** (akan dihapus, jangan dipakai di kode baru):
|
||||||
|
|
||||||
|
| Lama | Pengganti |
|
||||||
|
|---|---|
|
||||||
|
| `GET /customer/points` | `GET /customer/wallet` → `point_balance` |
|
||||||
|
| `total_points`, `points_history`, `last_updated` di `/customer/wallet` | `point_balance`, `recent_transactions` |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 11. Checklist selesai
|
||||||
|
|
||||||
|
- [ ] 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.
|
||||||
|
- [ ] Layar saldo akan kedaluwarsa.
|
||||||
|
- [ ] Registrasi device FCM setelah login dan saat token berganti; unregister saat logout.
|
||||||
|
- [ ] Penanganan tap untuk keempat tipe push.
|
||||||
|
- [ ] 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.
|
||||||
|
- [ ] Kode bayar: angka + QR, hitung mundur 2 menit, tombol buat ulang.
|
||||||
|
- [ ] Tukar dengan preview, kelipatan kurs, 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.
|
||||||
|
- [ ] Riwayat order dengan pagination dan layar detail (item, pembayaran, EnakPoint/EnakCoin yang didapat).
|
||||||
|
- [ ] Tidak ada pemakaian endpoint atau field di §10.
|
||||||
|
- [ ] PIN tidak pernah disimpan, di-log, atau dikirim ke analytics.
|
||||||
@@ -165,6 +165,8 @@ func (a *App) Initialize(cfg *config.Config) error {
|
|||||||
services.customerOrderPaymentService,
|
services.customerOrderPaymentService,
|
||||||
services.customerWalletService,
|
services.customerWalletService,
|
||||||
services.customerDeviceService,
|
services.customerDeviceService,
|
||||||
|
services.customerOutletService,
|
||||||
|
services.customerOrderService,
|
||||||
a.redisClient,
|
a.redisClient,
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -403,6 +405,8 @@ type processors struct {
|
|||||||
walletTransferProcessor *processor.WalletTransferProcessor
|
walletTransferProcessor *processor.WalletTransferProcessor
|
||||||
walletTraceProcessor *processor.WalletTraceProcessor
|
walletTraceProcessor *processor.WalletTraceProcessor
|
||||||
customerDeviceProcessor *processor.CustomerDeviceProcessor
|
customerDeviceProcessor *processor.CustomerDeviceProcessor
|
||||||
|
customerOutletProcessor *processor.CustomerOutletProcessor
|
||||||
|
customerOrderProcessor *processor.CustomerOrderProcessor
|
||||||
}
|
}
|
||||||
|
|
||||||
func (a *App) initProcessors(cfg *config.Config, repos *repositories) *processors {
|
func (a *App) initProcessors(cfg *config.Config, repos *repositories) *processors {
|
||||||
@@ -484,6 +488,8 @@ func (a *App) initProcessors(cfg *config.Config, repos *repositories) *processor
|
|||||||
walletTransferProcessor: walletTransferProcessor,
|
walletTransferProcessor: walletTransferProcessor,
|
||||||
walletTraceProcessor: processor.NewWalletTraceProcessor(repository.NewWalletTraceRepository(a.db)),
|
walletTraceProcessor: processor.NewWalletTraceProcessor(repository.NewWalletTraceRepository(a.db)),
|
||||||
customerDeviceProcessor: customerDeviceProcessor,
|
customerDeviceProcessor: customerDeviceProcessor,
|
||||||
|
customerOutletProcessor: processor.NewCustomerOutletProcessor(repository.NewCustomerOutletRepository(a.db), loyaltySettingsProcessor),
|
||||||
|
customerOrderProcessor: processor.NewCustomerOrderProcessor(repository.NewCustomerOrderRepository(a.db), earningProcessor),
|
||||||
walletAdminProcessor: processor.NewWalletAdminProcessor(repository.NewWalletAdminRepository(a.db), repos.walletQueryRepo, processor.NewWalletProcessor(repos.walletRepo), loyaltySettingsProcessor, repos.txManager),
|
walletAdminProcessor: processor.NewWalletAdminProcessor(repository.NewWalletAdminRepository(a.db), repos.walletQueryRepo, processor.NewWalletProcessor(repos.walletRepo), loyaltySettingsProcessor, repos.txManager),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -534,6 +540,8 @@ type services struct {
|
|||||||
customerOrderPaymentService *service.CustomerOrderPaymentServiceImpl
|
customerOrderPaymentService *service.CustomerOrderPaymentServiceImpl
|
||||||
customerWalletService *service.CustomerWalletServiceImpl
|
customerWalletService *service.CustomerWalletServiceImpl
|
||||||
customerDeviceService *service.CustomerDeviceServiceImpl
|
customerDeviceService *service.CustomerDeviceServiceImpl
|
||||||
|
customerOutletService *service.CustomerOutletServiceImpl
|
||||||
|
customerOrderService *service.CustomerOrderServiceImpl
|
||||||
}
|
}
|
||||||
|
|
||||||
func (a *App) initServices(processors *processors, repos *repositories, cfg *config.Config) *services {
|
func (a *App) initServices(processors *processors, repos *repositories, cfg *config.Config) *services {
|
||||||
@@ -622,6 +630,8 @@ func (a *App) initServices(processors *processors, repos *repositories, cfg *con
|
|||||||
customerOrderPaymentService: service.NewCustomerOrderPaymentService(processors.orderProcessor),
|
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),
|
||||||
|
customerOrderService: service.NewCustomerOrderService(processors.customerOrderProcessor),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -52,7 +52,6 @@ const (
|
|||||||
TableEntity = "table"
|
TableEntity = "table"
|
||||||
// Gamification entities
|
// Gamification entities
|
||||||
CustomerPointsEntity = "customer_points"
|
CustomerPointsEntity = "customer_points"
|
||||||
CustomerTokensEntity = "customer_tokens"
|
|
||||||
TierEntity = "tier"
|
TierEntity = "tier"
|
||||||
GameEntity = "game"
|
GameEntity = "game"
|
||||||
GamePrizeEntity = "game_prize"
|
GamePrizeEntity = "game_prize"
|
||||||
|
|||||||
@@ -12,7 +12,7 @@ import (
|
|||||||
type CreateCampaignRequest struct {
|
type CreateCampaignRequest struct {
|
||||||
Name string `json:"name" binding:"required,min=1,max=150"`
|
Name string `json:"name" binding:"required,min=1,max=150"`
|
||||||
Description *string `json:"description,omitempty"`
|
Description *string `json:"description,omitempty"`
|
||||||
Type string `json:"type" binding:"required,oneof=REWARD POINTS COINS TOKENS MIXED"`
|
Type string `json:"type" binding:"required,oneof=REWARD POINTS COINS MIXED"`
|
||||||
StartDate time.Time `json:"start_date" binding:"required"`
|
StartDate time.Time `json:"start_date" binding:"required"`
|
||||||
EndDate time.Time `json:"end_date" binding:"required"`
|
EndDate time.Time `json:"end_date" binding:"required"`
|
||||||
IsActive bool `json:"is_active"`
|
IsActive bool `json:"is_active"`
|
||||||
@@ -25,7 +25,7 @@ type UpdateCampaignRequest struct {
|
|||||||
ID uuid.UUID `json:"id" binding:"required"`
|
ID uuid.UUID `json:"id" binding:"required"`
|
||||||
Name string `json:"name" binding:"required,min=1,max=150"`
|
Name string `json:"name" binding:"required,min=1,max=150"`
|
||||||
Description *string `json:"description,omitempty"`
|
Description *string `json:"description,omitempty"`
|
||||||
Type string `json:"type" binding:"required,oneof=REWARD POINTS COINS TOKENS MIXED"`
|
Type string `json:"type" binding:"required,oneof=REWARD POINTS COINS MIXED"`
|
||||||
StartDate time.Time `json:"start_date" binding:"required"`
|
StartDate time.Time `json:"start_date" binding:"required"`
|
||||||
EndDate time.Time `json:"end_date" binding:"required"`
|
EndDate time.Time `json:"end_date" binding:"required"`
|
||||||
IsActive bool `json:"is_active"`
|
IsActive bool `json:"is_active"`
|
||||||
@@ -58,7 +58,7 @@ type CreateCampaignRuleRequest struct {
|
|||||||
CampaignID uuid.UUID `json:"campaign_id" binding:"required"`
|
CampaignID uuid.UUID `json:"campaign_id" binding:"required"`
|
||||||
RuleType string `json:"rule_type" binding:"required,oneof=TIER SPEND PRODUCT CATEGORY DAY LOCATION"`
|
RuleType string `json:"rule_type" binding:"required,oneof=TIER SPEND PRODUCT CATEGORY DAY LOCATION"`
|
||||||
ConditionValue *string `json:"condition_value,omitempty"`
|
ConditionValue *string `json:"condition_value,omitempty"`
|
||||||
RewardType string `json:"reward_type" binding:"required,oneof=POINTS COINS TOKENS REWARD"`
|
RewardType string `json:"reward_type" binding:"required,oneof=POINTS COINS REWARD"`
|
||||||
RewardValue *int64 `json:"reward_value,omitempty"`
|
RewardValue *int64 `json:"reward_value,omitempty"`
|
||||||
RewardSubtype *string `json:"reward_subtype,omitempty"`
|
RewardSubtype *string `json:"reward_subtype,omitempty"`
|
||||||
RewardRefID *uuid.UUID `json:"reward_ref_id,omitempty"`
|
RewardRefID *uuid.UUID `json:"reward_ref_id,omitempty"`
|
||||||
@@ -70,7 +70,7 @@ type UpdateCampaignRuleRequest struct {
|
|||||||
CampaignID uuid.UUID `json:"campaign_id" binding:"required"`
|
CampaignID uuid.UUID `json:"campaign_id" binding:"required"`
|
||||||
RuleType string `json:"rule_type" binding:"required,oneof=TIER SPEND PRODUCT CATEGORY DAY LOCATION"`
|
RuleType string `json:"rule_type" binding:"required,oneof=TIER SPEND PRODUCT CATEGORY DAY LOCATION"`
|
||||||
ConditionValue *string `json:"condition_value,omitempty"`
|
ConditionValue *string `json:"condition_value,omitempty"`
|
||||||
RewardType string `json:"reward_type" binding:"required,oneof=POINTS COINS TOKENS REWARD"`
|
RewardType string `json:"reward_type" binding:"required,oneof=POINTS COINS REWARD"`
|
||||||
RewardValue *int64 `json:"reward_value,omitempty"`
|
RewardValue *int64 `json:"reward_value,omitempty"`
|
||||||
RewardSubtype *string `json:"reward_subtype,omitempty"`
|
RewardSubtype *string `json:"reward_subtype,omitempty"`
|
||||||
RewardRefID *uuid.UUID `json:"reward_ref_id,omitempty"`
|
RewardRefID *uuid.UUID `json:"reward_ref_id,omitempty"`
|
||||||
@@ -142,7 +142,7 @@ type ListCampaignRulesResponse struct {
|
|||||||
type CampaignRuleStruct struct {
|
type CampaignRuleStruct struct {
|
||||||
RuleType string `json:"rule_type" binding:"required,oneof=TIER SPEND PRODUCT CATEGORY DAY LOCATION"`
|
RuleType string `json:"rule_type" binding:"required,oneof=TIER SPEND PRODUCT CATEGORY DAY LOCATION"`
|
||||||
ConditionValue *string `json:"condition_value,omitempty"`
|
ConditionValue *string `json:"condition_value,omitempty"`
|
||||||
RewardType string `json:"reward_type" binding:"required,oneof=POINTS COINS TOKENS REWARD"`
|
RewardType string `json:"reward_type" binding:"required,oneof=POINTS COINS REWARD"`
|
||||||
RewardValue *int64 `json:"reward_value,omitempty"`
|
RewardValue *int64 `json:"reward_value,omitempty"`
|
||||||
RewardSubtype *string `json:"reward_subtype,omitempty"`
|
RewardSubtype *string `json:"reward_subtype,omitempty"`
|
||||||
RewardRefID *uuid.UUID `json:"reward_ref_id,omitempty"`
|
RewardRefID *uuid.UUID `json:"reward_ref_id,omitempty"`
|
||||||
|
|||||||
@@ -16,6 +16,10 @@ type RegisterStartRequest struct {
|
|||||||
PhoneNumber string `json:"phone_number" binding:"required"`
|
PhoneNumber string `json:"phone_number" binding:"required"`
|
||||||
Name string `json:"name" binding:"required"`
|
Name string `json:"name" binding:"required"`
|
||||||
BirthDate string `json:"birth_date" binding:"required"`
|
BirthDate string `json:"birth_date" binding:"required"`
|
||||||
|
// The organization (brand) the customer registers with. A customer belongs to one
|
||||||
|
// organization. Optional: when it is left out and the database has exactly one
|
||||||
|
// organization, the customer joins that one.
|
||||||
|
OrganizationID string `json:"organization_id,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type RegisterVerifyOtpRequest struct {
|
type RegisterVerifyOtpRequest struct {
|
||||||
|
|||||||
@@ -25,26 +25,6 @@ type PointsHistoryItem struct {
|
|||||||
CreatedAt time.Time `json:"created_at"`
|
CreatedAt time.Time `json:"created_at"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type GetCustomerTokensResponse struct {
|
|
||||||
Status string `json:"status"`
|
|
||||||
Message string `json:"message"`
|
|
||||||
Data *GetCustomerTokensResponseData `json:"data,omitempty"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type GetCustomerTokensResponseData struct {
|
|
||||||
TotalTokens int64 `json:"total_tokens"`
|
|
||||||
TokensHistory []TokensHistoryItem `json:"tokens_history,omitempty"`
|
|
||||||
LastUpdated time.Time `json:"last_updated"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type TokensHistoryItem struct {
|
|
||||||
ID string `json:"id"`
|
|
||||||
Tokens int64 `json:"tokens"`
|
|
||||||
Type string `json:"type"` // EARNED, REDEEMED, EXPIRED
|
|
||||||
Description string `json:"description"`
|
|
||||||
CreatedAt time.Time `json:"created_at"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type GetCustomerWalletResponse struct {
|
type GetCustomerWalletResponse struct {
|
||||||
Status string `json:"status"`
|
Status string `json:"status"`
|
||||||
Message string `json:"message"`
|
Message string `json:"message"`
|
||||||
@@ -53,8 +33,6 @@ type GetCustomerWalletResponse struct {
|
|||||||
|
|
||||||
type GetCustomerWalletResponseData struct {
|
type GetCustomerWalletResponseData struct {
|
||||||
TotalPoints int64 `json:"total_points"`
|
TotalPoints int64 `json:"total_points"`
|
||||||
TotalTokens int64 `json:"total_tokens"`
|
|
||||||
PointsHistory []PointsHistoryItem `json:"points_history,omitempty"`
|
PointsHistory []PointsHistoryItem `json:"points_history,omitempty"`
|
||||||
TokensHistory []TokensHistoryItem `json:"tokens_history,omitempty"`
|
|
||||||
LastUpdated time.Time `json:"last_updated"`
|
LastUpdated time.Time `json:"last_updated"`
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -14,13 +14,11 @@ type CreateGamePlayRequest struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type GamePlayResponse struct {
|
type GamePlayResponse struct {
|
||||||
ID uuid.UUID `json:"id"`
|
ID uuid.UUID `json:"id"`
|
||||||
GameID uuid.UUID `json:"game_id"`
|
GameID uuid.UUID `json:"game_id"`
|
||||||
CustomerID uuid.UUID `json:"customer_id"`
|
CustomerID uuid.UUID `json:"customer_id"`
|
||||||
PrizeID *uuid.UUID `json:"prize_id,omitempty"`
|
PrizeID *uuid.UUID `json:"prize_id,omitempty"`
|
||||||
CoinsUsed int `json:"coins_used"`
|
CoinsUsed int `json:"coins_used"`
|
||||||
// Deprecated: the same as CoinsUsed, kept until the apps read coins_used.
|
|
||||||
TokenUsed int `json:"token_used"`
|
|
||||||
RandomSeed *string `json:"random_seed,omitempty"`
|
RandomSeed *string `json:"random_seed,omitempty"`
|
||||||
CreatedAt time.Time `json:"created_at"`
|
CreatedAt time.Time `json:"created_at"`
|
||||||
Game *GameResponse `json:"game,omitempty"`
|
Game *GameResponse `json:"game,omitempty"`
|
||||||
@@ -35,7 +33,7 @@ type ListGamePlaysRequest struct {
|
|||||||
GameID *uuid.UUID `json:"game_id"`
|
GameID *uuid.UUID `json:"game_id"`
|
||||||
CustomerID *uuid.UUID `json:"customer_id"`
|
CustomerID *uuid.UUID `json:"customer_id"`
|
||||||
PrizeID *uuid.UUID `json:"prize_id"`
|
PrizeID *uuid.UUID `json:"prize_id"`
|
||||||
SortBy string `json:"sort_by" validate:"omitempty,oneof=created_at coins_used token_used"`
|
SortBy string `json:"sort_by" validate:"omitempty,oneof=created_at coins_used"`
|
||||||
SortOrder string `json:"sort_order" validate:"omitempty,oneof=asc desc"`
|
SortOrder string `json:"sort_order" validate:"omitempty,oneof=asc desc"`
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -58,6 +56,4 @@ type PlayGameResponse struct {
|
|||||||
GamePlay GamePlayResponse `json:"game_play"`
|
GamePlay GamePlayResponse `json:"game_play"`
|
||||||
PrizeWon *GamePrizeResponse `json:"prize_won,omitempty"`
|
PrizeWon *GamePrizeResponse `json:"prize_won,omitempty"`
|
||||||
CoinsRemaining int64 `json:"coins_remaining"`
|
CoinsRemaining int64 `json:"coins_remaining"`
|
||||||
// Deprecated: the same as CoinsRemaining, kept until the apps read coins_remaining.
|
|
||||||
TokensRemaining int64 `json:"tokens_remaining"`
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -17,6 +17,4 @@ type SpinGameResponseData struct {
|
|||||||
GamePlay GamePlayResponse `json:"game_play"`
|
GamePlay GamePlayResponse `json:"game_play"`
|
||||||
PrizeWon *CustomerGamePrizeResponse `json:"prize_won,omitempty"`
|
PrizeWon *CustomerGamePrizeResponse `json:"prize_won,omitempty"`
|
||||||
CoinsRemaining int64 `json:"coins_remaining"`
|
CoinsRemaining int64 `json:"coins_remaining"`
|
||||||
// Deprecated: the same as CoinsRemaining, kept until the apps read coins_remaining.
|
|
||||||
TokensRemaining int64 `json:"tokens_remaining"`
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -16,27 +16,6 @@ const (
|
|||||||
CampaignTypeMixed CampaignType = "MIXED"
|
CampaignTypeMixed CampaignType = "MIXED"
|
||||||
)
|
)
|
||||||
|
|
||||||
// legacyCampaignTokens is what COINS was called before tokens became EnakCoin
|
|
||||||
// (docs/prd-point-coin.md §10). Requests may still send it; it is stored as COINS.
|
|
||||||
const legacyCampaignTokens = "TOKENS"
|
|
||||||
|
|
||||||
// NormalizeCampaignType maps the legacy TOKENS to COINS and leaves anything else as is.
|
|
||||||
func NormalizeCampaignType(t string) CampaignType {
|
|
||||||
if t == legacyCampaignTokens {
|
|
||||||
return CampaignTypeCoins
|
|
||||||
}
|
|
||||||
return CampaignType(t)
|
|
||||||
}
|
|
||||||
|
|
||||||
// NormalizeCampaignRewardType maps the legacy TOKENS to COINS and leaves anything
|
|
||||||
// else as is.
|
|
||||||
func NormalizeCampaignRewardType(t string) CampaignRewardType {
|
|
||||||
if t == legacyCampaignTokens {
|
|
||||||
return CampaignRewardTypeCoins
|
|
||||||
}
|
|
||||||
return CampaignRewardType(t)
|
|
||||||
}
|
|
||||||
|
|
||||||
type RuleType string
|
type RuleType string
|
||||||
|
|
||||||
const (
|
const (
|
||||||
|
|||||||
@@ -1,18 +0,0 @@
|
|||||||
package entities
|
|
||||||
|
|
||||||
import (
|
|
||||||
"testing"
|
|
||||||
|
|
||||||
"github.com/stretchr/testify/assert"
|
|
||||||
)
|
|
||||||
|
|
||||||
func TestNormalizeCampaignTypesMapsLegacyTokensToCoins(t *testing.T) {
|
|
||||||
assert.Equal(t, CampaignTypeCoins, NormalizeCampaignType("TOKENS"))
|
|
||||||
assert.Equal(t, CampaignTypeCoins, NormalizeCampaignType("COINS"))
|
|
||||||
assert.Equal(t, CampaignTypePoints, NormalizeCampaignType("POINTS"))
|
|
||||||
assert.Equal(t, CampaignType(""), NormalizeCampaignType(""), "an empty filter stays empty")
|
|
||||||
|
|
||||||
assert.Equal(t, CampaignRewardTypeCoins, NormalizeCampaignRewardType("TOKENS"))
|
|
||||||
assert.Equal(t, CampaignRewardTypeReward, NormalizeCampaignRewardType("REWARD"))
|
|
||||||
assert.Equal(t, CampaignRewardType(""), NormalizeCampaignRewardType(""))
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
package handler
|
||||||
|
|
||||||
|
import (
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
|
||||||
|
"apskel-pos-be/internal/constants"
|
||||||
|
"apskel-pos-be/internal/contract"
|
||||||
|
"apskel-pos-be/internal/models"
|
||||||
|
"apskel-pos-be/internal/service"
|
||||||
|
"apskel-pos-be/internal/util"
|
||||||
|
)
|
||||||
|
|
||||||
|
// CustomerOrderHandler serves the customer app's order history.
|
||||||
|
type CustomerOrderHandler struct {
|
||||||
|
orders service.CustomerOrderService
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewCustomerOrderHandler(orders service.CustomerOrderService) *CustomerOrderHandler {
|
||||||
|
return &CustomerOrderHandler{orders: orders}
|
||||||
|
}
|
||||||
|
|
||||||
|
// List is GET /customer/orders?page=&limit=.
|
||||||
|
func (h *CustomerOrderHandler) List(c *gin.Context) {
|
||||||
|
customerID, ok := customerIDFromGin(c, "CustomerOrderHandler::List")
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
var query models.ListCustomerOrdersQuery
|
||||||
|
if err := c.ShouldBindQuery(&query); err != nil {
|
||||||
|
util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{
|
||||||
|
contract.NewResponseError(constants.MalformedFieldErrorCode, constants.RequestEntity, "page and limit must be whole numbers"),
|
||||||
|
}), "CustomerOrderHandler::List")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
util.HandleResponse(c.Writer, c.Request, h.orders.List(c.Request.Context(), customerID, query), "CustomerOrderHandler::List")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Detail is GET /customer/orders/:id.
|
||||||
|
func (h *CustomerOrderHandler) Detail(c *gin.Context) {
|
||||||
|
customerID, ok := customerIDFromGin(c, "CustomerOrderHandler::Detail")
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
orderID, ok := parseUUIDParam(c, "id", "CustomerOrderHandler::Detail")
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
util.HandleResponse(c.Writer, c.Request, h.orders.Detail(c.Request.Context(), customerID, orderID), "CustomerOrderHandler::Detail")
|
||||||
|
}
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
package handler
|
||||||
|
|
||||||
|
import (
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
|
||||||
|
"apskel-pos-be/internal/service"
|
||||||
|
"apskel-pos-be/internal/util"
|
||||||
|
)
|
||||||
|
|
||||||
|
// CustomerOutletHandler serves GET /customer/outlets.
|
||||||
|
type CustomerOutletHandler struct {
|
||||||
|
outlets service.CustomerOutletService
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewCustomerOutletHandler(outlets service.CustomerOutletService) *CustomerOutletHandler {
|
||||||
|
return &CustomerOutletHandler{outlets: outlets}
|
||||||
|
}
|
||||||
|
|
||||||
|
// List returns the active outlets of the customer's organization.
|
||||||
|
func (h *CustomerOutletHandler) List(c *gin.Context) {
|
||||||
|
customerID, ok := customerIDFromGin(c, "CustomerOutletHandler::List")
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
util.HandleResponse(c.Writer, c.Request, h.outlets.List(c.Request.Context(), customerID), "CustomerOutletHandler::List")
|
||||||
|
}
|
||||||
@@ -59,40 +59,6 @@ func (h *CustomerPointsHandler) GetCustomerPoints(c *gin.Context) {
|
|||||||
util.HandleResponse(c.Writer, c.Request, contract.BuildSuccessResponse(response), "CustomerPointsHandler::GetCustomerPoints")
|
util.HandleResponse(c.Writer, c.Request, contract.BuildSuccessResponse(response), "CustomerPointsHandler::GetCustomerPoints")
|
||||||
}
|
}
|
||||||
|
|
||||||
func (h *CustomerPointsHandler) GetCustomerTokens(c *gin.Context) {
|
|
||||||
ctx := c.Request.Context()
|
|
||||||
|
|
||||||
// Get customer ID from context (set by middleware)
|
|
||||||
customerID, exists := c.Get("customer_id")
|
|
||||||
if !exists {
|
|
||||||
logger.FromContext(ctx).Error("Customer ID not found in context")
|
|
||||||
util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{
|
|
||||||
contract.NewResponseError(constants.ValidationErrorCode, constants.AuthHandlerEntity, "Customer ID not found"),
|
|
||||||
}), "CustomerPointsHandler::GetCustomerTokens")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
customerIDStr, ok := customerID.(string)
|
|
||||||
if !ok {
|
|
||||||
logger.FromContext(ctx).Error("Invalid customer ID type in context")
|
|
||||||
util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{
|
|
||||||
contract.NewResponseError(constants.ValidationErrorCode, constants.AuthHandlerEntity, "Invalid customer ID"),
|
|
||||||
}), "CustomerPointsHandler::GetCustomerTokens")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
response, err := h.customerPointsService.GetCustomerTokens(ctx, customerIDStr)
|
|
||||||
if err != nil {
|
|
||||||
logger.FromContext(ctx).WithError(err).Error("CustomerPointsHandler::GetCustomerTokens -> service call failed")
|
|
||||||
util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{
|
|
||||||
contract.NewResponseError(walletErrorCode(err), constants.RequestEntity, err.Error()),
|
|
||||||
}), "CustomerPointsHandler::GetCustomerTokens")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
util.HandleResponse(c.Writer, c.Request, contract.BuildSuccessResponse(response), "CustomerPointsHandler::GetCustomerTokens")
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *CustomerPointsHandler) GetCustomerWallet(c *gin.Context) {
|
func (h *CustomerPointsHandler) GetCustomerWallet(c *gin.Context) {
|
||||||
ctx := c.Request.Context()
|
ctx := c.Request.Context()
|
||||||
|
|
||||||
|
|||||||
@@ -25,7 +25,7 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
// Drives the customer wallet endpoints over HTTP down to Postgres, to show the app
|
// Drives the customer wallet endpoints over HTTP down to Postgres, to show the app
|
||||||
// gets the right numbers from the new endpoints and from the old /points, /tokens
|
// gets the right numbers from the new endpoints and from the old /points
|
||||||
// and /wallet shapes. Needs TEST_DATABASE_URL pointing at a migrated database; see
|
// and /wallet shapes. Needs TEST_DATABASE_URL pointing at a migrated database; see
|
||||||
// internal/repository/wallet_repository_test.go.
|
// internal/repository/wallet_repository_test.go.
|
||||||
func TestCustomerWalletEndpoints_AgainstPostgres(t *testing.T) {
|
func TestCustomerWalletEndpoints_AgainstPostgres(t *testing.T) {
|
||||||
@@ -111,7 +111,6 @@ func TestCustomerWalletEndpoints_AgainstPostgres(t *testing.T) {
|
|||||||
}{{"/a", customer}, {"/b", other}, {"/gone", uuid.New()}} {
|
}{{"/a", customer}, {"/b", other}, {"/gone", uuid.New()}} {
|
||||||
g := router.Group(who.prefix, as(who.id))
|
g := router.Group(who.prefix, as(who.id))
|
||||||
g.GET("/points", h.GetCustomerPoints)
|
g.GET("/points", h.GetCustomerPoints)
|
||||||
g.GET("/tokens", h.GetCustomerTokens)
|
|
||||||
g.GET("/wallet", h.GetCustomerWallet)
|
g.GET("/wallet", h.GetCustomerWallet)
|
||||||
g.GET("/wallet/transactions", h.GetCustomerWalletTransactions)
|
g.GET("/wallet/transactions", h.GetCustomerWalletTransactions)
|
||||||
}
|
}
|
||||||
@@ -128,16 +127,12 @@ func TestCustomerWalletEndpoints_AgainstPostgres(t *testing.T) {
|
|||||||
return body["data"].(map[string]any)["data"].(map[string]any)
|
return body["data"].(map[string]any)["data"].(map[string]any)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Old app: /points and /tokens keep their shape and show the spendable balance.
|
// Old app: /points keeps its shape and shows the spendable balance.
|
||||||
status, body := get("/a/points")
|
status, body := get("/a/points")
|
||||||
require.Equal(t, http.StatusOK, status, body)
|
require.Equal(t, http.StatusOK, status, body)
|
||||||
assert.EqualValues(t, 250, inner(body)["total_points"], "300 - 50; the expired 20 is not spendable")
|
assert.EqualValues(t, 250, inner(body)["total_points"], "300 - 50; the expired 20 is not spendable")
|
||||||
assert.Len(t, inner(body)["points_history"], 3)
|
assert.Len(t, inner(body)["points_history"], 3)
|
||||||
|
|
||||||
status, body = get("/a/tokens")
|
|
||||||
require.Equal(t, http.StatusOK, status, body)
|
|
||||||
assert.EqualValues(t, 8, inner(body)["total_tokens"])
|
|
||||||
|
|
||||||
// /wallet: new fields, with the old ones still there.
|
// /wallet: new fields, with the old ones still there.
|
||||||
status, body = get("/a/wallet")
|
status, body = get("/a/wallet")
|
||||||
require.Equal(t, http.StatusOK, status, body)
|
require.Equal(t, http.StatusOK, status, body)
|
||||||
@@ -151,9 +146,10 @@ func TestCustomerWalletEndpoints_AgainstPostgres(t *testing.T) {
|
|||||||
assert.Equal(t, map[string]any{"amount": float64(250), "date": time.Date(next, 7, 2, 0, 0, 0, 0, time.UTC).Format("2006-01-02")},
|
assert.Equal(t, map[string]any{"amount": float64(250), "date": time.Date(next, 7, 2, 0, 0, 0, 0, time.UTC).Format("2006-01-02")},
|
||||||
nearest["point"], "both lots fall on 2 July in Jakarta although they are on different UTC days")
|
nearest["point"], "both lots fall on 2 July in Jakarta although they are on different UTC days")
|
||||||
assert.Nil(t, nearest["coin"])
|
assert.Nil(t, nearest["coin"])
|
||||||
for _, legacy := range []string{"total_points", "total_tokens", "points_history", "tokens_history", "last_updated"} {
|
for _, legacy := range []string{"total_points", "points_history", "last_updated"} {
|
||||||
assert.Contains(t, w, legacy)
|
assert.Contains(t, w, legacy)
|
||||||
}
|
}
|
||||||
|
assert.NotContains(t, w, "total_tokens", "tokens are gone; EnakCoin is coin_balance")
|
||||||
assert.EqualValues(t, 250, w["total_points"])
|
assert.EqualValues(t, 250, w["total_points"])
|
||||||
|
|
||||||
recent := w["recent_transactions"].([]any)
|
recent := w["recent_transactions"].([]any)
|
||||||
|
|||||||
@@ -71,7 +71,7 @@ func ToCampaignEntity(request *contract.CreateCampaignRequest) *entities.Campaig
|
|||||||
return &entities.Campaign{
|
return &entities.Campaign{
|
||||||
Name: request.Name,
|
Name: request.Name,
|
||||||
Description: request.Description,
|
Description: request.Description,
|
||||||
Type: entities.NormalizeCampaignType(request.Type),
|
Type: entities.CampaignType(request.Type),
|
||||||
StartDate: request.StartDate,
|
StartDate: request.StartDate,
|
||||||
EndDate: request.EndDate,
|
EndDate: request.EndDate,
|
||||||
IsActive: request.IsActive,
|
IsActive: request.IsActive,
|
||||||
@@ -91,7 +91,7 @@ func ToCampaignEntityFromUpdate(request *contract.UpdateCampaignRequest) *entiti
|
|||||||
ID: request.ID,
|
ID: request.ID,
|
||||||
Name: request.Name,
|
Name: request.Name,
|
||||||
Description: request.Description,
|
Description: request.Description,
|
||||||
Type: entities.NormalizeCampaignType(request.Type),
|
Type: entities.CampaignType(request.Type),
|
||||||
StartDate: request.StartDate,
|
StartDate: request.StartDate,
|
||||||
EndDate: request.EndDate,
|
EndDate: request.EndDate,
|
||||||
IsActive: request.IsActive,
|
IsActive: request.IsActive,
|
||||||
@@ -118,7 +118,7 @@ func ToCampaignRuleEntity(request *contract.CampaignRuleStruct, campaignID uuid.
|
|||||||
CampaignID: campaignID,
|
CampaignID: campaignID,
|
||||||
RuleType: entities.RuleType(request.RuleType),
|
RuleType: entities.RuleType(request.RuleType),
|
||||||
ConditionValue: request.ConditionValue,
|
ConditionValue: request.ConditionValue,
|
||||||
RewardType: entities.NormalizeCampaignRewardType(request.RewardType),
|
RewardType: entities.CampaignRewardType(request.RewardType),
|
||||||
RewardValue: request.RewardValue,
|
RewardValue: request.RewardValue,
|
||||||
RewardSubtype: rewardSubtype,
|
RewardSubtype: rewardSubtype,
|
||||||
RewardRefID: request.RewardRefID,
|
RewardRefID: request.RewardRefID,
|
||||||
@@ -142,7 +142,7 @@ func ToCampaignRuleEntityFromUpdate(request *contract.CampaignRuleStruct, campai
|
|||||||
CampaignID: campaignID,
|
CampaignID: campaignID,
|
||||||
RuleType: entities.RuleType(request.RuleType),
|
RuleType: entities.RuleType(request.RuleType),
|
||||||
ConditionValue: request.ConditionValue,
|
ConditionValue: request.ConditionValue,
|
||||||
RewardType: entities.NormalizeCampaignRewardType(request.RewardType),
|
RewardType: entities.CampaignRewardType(request.RewardType),
|
||||||
RewardValue: request.RewardValue,
|
RewardValue: request.RewardValue,
|
||||||
RewardSubtype: rewardSubtype,
|
RewardSubtype: rewardSubtype,
|
||||||
RewardRefID: request.RewardRefID,
|
RewardRefID: request.RewardRefID,
|
||||||
|
|||||||
@@ -36,10 +36,9 @@ func SpinGameResponseDataModelToContract(data *models.SpinGameResponseData) *con
|
|||||||
}
|
}
|
||||||
|
|
||||||
return &contract.SpinGameResponseData{
|
return &contract.SpinGameResponseData{
|
||||||
GamePlay: GamePlayResponseModelToContract(&data.GamePlay),
|
GamePlay: GamePlayResponseModelToContract(&data.GamePlay),
|
||||||
PrizeWon: CustomerGamePrizeResponseModelToContract(data.PrizeWon),
|
PrizeWon: CustomerGamePrizeResponseModelToContract(data.PrizeWon),
|
||||||
CoinsRemaining: data.CoinsRemaining,
|
CoinsRemaining: data.CoinsRemaining,
|
||||||
TokensRemaining: data.CoinsRemaining,
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -55,7 +54,6 @@ func GamePlayResponseModelToContract(resp *models.GamePlayResponse) contract.Gam
|
|||||||
CustomerID: resp.CustomerID,
|
CustomerID: resp.CustomerID,
|
||||||
PrizeID: resp.PrizeID,
|
PrizeID: resp.PrizeID,
|
||||||
CoinsUsed: resp.CoinsUsed,
|
CoinsUsed: resp.CoinsUsed,
|
||||||
TokenUsed: resp.CoinsUsed,
|
|
||||||
RandomSeed: resp.RandomSeed,
|
RandomSeed: resp.RandomSeed,
|
||||||
CreatedAt: resp.CreatedAt,
|
CreatedAt: resp.CreatedAt,
|
||||||
Game: nil, // Optional field - can be populated separately if needed
|
Game: nil, // Optional field - can be populated separately if needed
|
||||||
|
|||||||
@@ -11,7 +11,7 @@ import (
|
|||||||
type CreateCampaignRequest struct {
|
type CreateCampaignRequest struct {
|
||||||
Name string `json:"name" binding:"required,min=1,max=150"`
|
Name string `json:"name" binding:"required,min=1,max=150"`
|
||||||
Description *string `json:"description,omitempty"`
|
Description *string `json:"description,omitempty"`
|
||||||
Type string `json:"type" binding:"required,oneof=REWARD POINTS COINS TOKENS MIXED"`
|
Type string `json:"type" binding:"required,oneof=REWARD POINTS COINS MIXED"`
|
||||||
StartDate time.Time `json:"start_date" binding:"required"`
|
StartDate time.Time `json:"start_date" binding:"required"`
|
||||||
EndDate time.Time `json:"end_date" binding:"required"`
|
EndDate time.Time `json:"end_date" binding:"required"`
|
||||||
IsActive bool `json:"is_active"`
|
IsActive bool `json:"is_active"`
|
||||||
@@ -25,7 +25,7 @@ type UpdateCampaignRequest struct {
|
|||||||
ID uuid.UUID `json:"id" binding:"required"`
|
ID uuid.UUID `json:"id" binding:"required"`
|
||||||
Name string `json:"name" binding:"required,min=1,max=150"`
|
Name string `json:"name" binding:"required,min=1,max=150"`
|
||||||
Description *string `json:"description,omitempty"`
|
Description *string `json:"description,omitempty"`
|
||||||
Type string `json:"type" binding:"required,oneof=REWARD POINTS COINS TOKENS MIXED"`
|
Type string `json:"type" binding:"required,oneof=REWARD POINTS COINS MIXED"`
|
||||||
StartDate time.Time `json:"start_date" binding:"required"`
|
StartDate time.Time `json:"start_date" binding:"required"`
|
||||||
EndDate time.Time `json:"end_date" binding:"required"`
|
EndDate time.Time `json:"end_date" binding:"required"`
|
||||||
IsActive bool `json:"is_active"`
|
IsActive bool `json:"is_active"`
|
||||||
@@ -88,7 +88,7 @@ type CreateCampaignRuleRequest struct {
|
|||||||
CampaignID uuid.UUID `json:"campaign_id" binding:"required"`
|
CampaignID uuid.UUID `json:"campaign_id" binding:"required"`
|
||||||
RuleType string `json:"rule_type" binding:"required,oneof=TIER SPEND PRODUCT CATEGORY DAY LOCATION"`
|
RuleType string `json:"rule_type" binding:"required,oneof=TIER SPEND PRODUCT CATEGORY DAY LOCATION"`
|
||||||
ConditionValue *string `json:"condition_value,omitempty"`
|
ConditionValue *string `json:"condition_value,omitempty"`
|
||||||
RewardType string `json:"reward_type" binding:"required,oneof=POINTS COINS TOKENS REWARD"`
|
RewardType string `json:"reward_type" binding:"required,oneof=POINTS COINS REWARD"`
|
||||||
RewardValue *int64 `json:"reward_value,omitempty"`
|
RewardValue *int64 `json:"reward_value,omitempty"`
|
||||||
RewardSubtype *string `json:"reward_subtype,omitempty"`
|
RewardSubtype *string `json:"reward_subtype,omitempty"`
|
||||||
RewardRefID *uuid.UUID `json:"reward_ref_id,omitempty"`
|
RewardRefID *uuid.UUID `json:"reward_ref_id,omitempty"`
|
||||||
@@ -100,7 +100,7 @@ type UpdateCampaignRuleRequest struct {
|
|||||||
CampaignID uuid.UUID `json:"campaign_id" binding:"required"`
|
CampaignID uuid.UUID `json:"campaign_id" binding:"required"`
|
||||||
RuleType string `json:"rule_type" binding:"required,oneof=TIER SPEND PRODUCT CATEGORY DAY LOCATION"`
|
RuleType string `json:"rule_type" binding:"required,oneof=TIER SPEND PRODUCT CATEGORY DAY LOCATION"`
|
||||||
ConditionValue *string `json:"condition_value,omitempty"`
|
ConditionValue *string `json:"condition_value,omitempty"`
|
||||||
RewardType string `json:"reward_type" binding:"required,oneof=POINTS COINS TOKENS REWARD"`
|
RewardType string `json:"reward_type" binding:"required,oneof=POINTS COINS REWARD"`
|
||||||
RewardValue *int64 `json:"reward_value,omitempty"`
|
RewardValue *int64 `json:"reward_value,omitempty"`
|
||||||
RewardSubtype *string `json:"reward_subtype,omitempty"`
|
RewardSubtype *string `json:"reward_subtype,omitempty"`
|
||||||
RewardRefID *uuid.UUID `json:"reward_ref_id,omitempty"`
|
RewardRefID *uuid.UUID `json:"reward_ref_id,omitempty"`
|
||||||
@@ -126,7 +126,7 @@ type ListCampaignRulesResponse struct {
|
|||||||
type CampaignRuleStruct struct {
|
type CampaignRuleStruct struct {
|
||||||
RuleType string `json:"rule_type" binding:"required,oneof=TIER SPEND PRODUCT CATEGORY DAY LOCATION"`
|
RuleType string `json:"rule_type" binding:"required,oneof=TIER SPEND PRODUCT CATEGORY DAY LOCATION"`
|
||||||
ConditionValue *string `json:"condition_value,omitempty"`
|
ConditionValue *string `json:"condition_value,omitempty"`
|
||||||
RewardType string `json:"reward_type" binding:"required,oneof=POINTS COINS TOKENS REWARD"`
|
RewardType string `json:"reward_type" binding:"required,oneof=POINTS COINS REWARD"`
|
||||||
RewardValue *int64 `json:"reward_value,omitempty"`
|
RewardValue *int64 `json:"reward_value,omitempty"`
|
||||||
RewardSubtype *string `json:"reward_subtype,omitempty"`
|
RewardSubtype *string `json:"reward_subtype,omitempty"`
|
||||||
RewardRefID *uuid.UUID `json:"reward_ref_id,omitempty"`
|
RewardRefID *uuid.UUID `json:"reward_ref_id,omitempty"`
|
||||||
|
|||||||
@@ -0,0 +1,74 @@
|
|||||||
|
package models
|
||||||
|
|
||||||
|
import (
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
)
|
||||||
|
|
||||||
|
// CustomerOrderSummary is one order in GET /customer/orders.
|
||||||
|
type CustomerOrderSummary struct {
|
||||||
|
ID uuid.UUID `json:"id"`
|
||||||
|
OrderNumber string `json:"order_number"`
|
||||||
|
OutletID uuid.UUID `json:"outlet_id"`
|
||||||
|
OutletName string `json:"outlet_name"`
|
||||||
|
OrderType string `json:"order_type"`
|
||||||
|
Status string `json:"status"`
|
||||||
|
PaymentStatus string `json:"payment_status"`
|
||||||
|
TotalAmount float64 `json:"total_amount"`
|
||||||
|
ItemCount int64 `json:"item_count"`
|
||||||
|
IsVoid bool `json:"is_void"`
|
||||||
|
IsRefund bool `json:"is_refund"`
|
||||||
|
// EnakPoint and EnakCoin the order earned; 0 when it earned nothing.
|
||||||
|
PointsEarned int64 `json:"points_earned"`
|
||||||
|
CoinsEarned int64 `json:"coins_earned"`
|
||||||
|
CreatedAt time.Time `json:"created_at"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// CustomerOrderDetail is GET /customer/orders/:id.
|
||||||
|
type CustomerOrderDetail struct {
|
||||||
|
CustomerOrderSummary
|
||||||
|
TableNumber *string `json:"table_number"`
|
||||||
|
Subtotal float64 `json:"subtotal"`
|
||||||
|
DiscountAmount float64 `json:"discount_amount"`
|
||||||
|
TaxAmount float64 `json:"tax_amount"`
|
||||||
|
RefundAmount float64 `json:"refund_amount"`
|
||||||
|
Items []CustomerOrderItem `json:"items"`
|
||||||
|
Payments []CustomerOrderPayment `json:"payments"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type CustomerOrderItem struct {
|
||||||
|
ID uuid.UUID `json:"id"`
|
||||||
|
ProductID uuid.UUID `json:"product_id"`
|
||||||
|
ProductName string `json:"product_name"`
|
||||||
|
VariantName *string `json:"variant_name"`
|
||||||
|
Quantity int `json:"quantity"`
|
||||||
|
// Set for products sold by weight, in UnitName.
|
||||||
|
Weight *float64 `json:"weight,omitempty"`
|
||||||
|
UnitName *string `json:"unit_name,omitempty"`
|
||||||
|
UnitPrice float64 `json:"unit_price"`
|
||||||
|
TotalPrice float64 `json:"total_price"`
|
||||||
|
RefundQuantity int `json:"refund_quantity"`
|
||||||
|
Modifiers []map[string]interface{} `json:"modifiers"`
|
||||||
|
Notes *string `json:"notes,omitempty"`
|
||||||
|
Status string `json:"status"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type CustomerOrderPayment struct {
|
||||||
|
ID uuid.UUID `json:"id"`
|
||||||
|
MethodName string `json:"method_name"`
|
||||||
|
MethodType string `json:"method_type"`
|
||||||
|
Amount float64 `json:"amount"`
|
||||||
|
Status string `json:"status"`
|
||||||
|
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"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// ListCustomerOrdersQuery is GET /customer/orders.
|
||||||
|
type ListCustomerOrdersQuery struct {
|
||||||
|
Page int `form:"page"`
|
||||||
|
Limit int `form:"limit"`
|
||||||
|
}
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
package models
|
||||||
|
|
||||||
|
import "github.com/google/uuid"
|
||||||
|
|
||||||
|
// CustomerOutlet is one outlet in GET /customer/outlets: where the customer can shop,
|
||||||
|
// and what the outlet does with EnakPoint and EnakCoin.
|
||||||
|
type CustomerOutlet struct {
|
||||||
|
ID uuid.UUID `json:"id"`
|
||||||
|
Name string `json:"name"`
|
||||||
|
Address *string `json:"address"`
|
||||||
|
// The cashier accepts EnakPoint as payment here.
|
||||||
|
AcceptsPointPayment bool `json:"accepts_point_payment"`
|
||||||
|
// Orders here earn EnakPoint / EnakCoin.
|
||||||
|
EarnsPoints bool `json:"earns_points"`
|
||||||
|
EarnsCoins bool `json:"earns_coins"`
|
||||||
|
}
|
||||||
@@ -25,26 +25,6 @@ type PointsHistoryItem struct {
|
|||||||
CreatedAt time.Time `json:"created_at"`
|
CreatedAt time.Time `json:"created_at"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type GetCustomerTokensResponse struct {
|
|
||||||
Status string `json:"status"`
|
|
||||||
Message string `json:"message"`
|
|
||||||
Data *GetCustomerTokensResponseData `json:"data,omitempty"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type GetCustomerTokensResponseData struct {
|
|
||||||
TotalTokens int64 `json:"total_tokens"`
|
|
||||||
TokensHistory []TokensHistoryItem `json:"tokens_history,omitempty"`
|
|
||||||
LastUpdated time.Time `json:"last_updated"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type TokensHistoryItem struct {
|
|
||||||
ID string `json:"id"`
|
|
||||||
Tokens int64 `json:"tokens"`
|
|
||||||
Type string `json:"type"` // EARNED, REDEEMED, EXPIRED
|
|
||||||
Description string `json:"description"`
|
|
||||||
CreatedAt time.Time `json:"created_at"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type GetCustomerWalletResponse struct {
|
type GetCustomerWalletResponse struct {
|
||||||
Status string `json:"status"`
|
Status string `json:"status"`
|
||||||
Message string `json:"message"`
|
Message string `json:"message"`
|
||||||
@@ -66,8 +46,6 @@ type GetCustomerWalletResponseData struct {
|
|||||||
// Deprecated: the shape of this endpoint before the wallet, kept for app versions
|
// Deprecated: the shape of this endpoint before the wallet, kept for app versions
|
||||||
// that still read it. Filled from the wallet like the fields above.
|
// that still read it. Filled from the wallet like the fields above.
|
||||||
TotalPoints int64 `json:"total_points"`
|
TotalPoints int64 `json:"total_points"`
|
||||||
TotalTokens int64 `json:"total_tokens"`
|
|
||||||
PointsHistory []PointsHistoryItem `json:"points_history,omitempty"`
|
PointsHistory []PointsHistoryItem `json:"points_history,omitempty"`
|
||||||
TokensHistory []TokensHistoryItem `json:"tokens_history,omitempty"`
|
|
||||||
LastUpdated time.Time `json:"last_updated"`
|
LastUpdated time.Time `json:"last_updated"`
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -33,7 +33,7 @@ type ListGamePlaysQuery struct {
|
|||||||
GameID *uuid.UUID `query:"game_id"`
|
GameID *uuid.UUID `query:"game_id"`
|
||||||
CustomerID *uuid.UUID `query:"customer_id"`
|
CustomerID *uuid.UUID `query:"customer_id"`
|
||||||
PrizeID *uuid.UUID `query:"prize_id"`
|
PrizeID *uuid.UUID `query:"prize_id"`
|
||||||
SortBy string `query:"sort_by" validate:"omitempty,oneof=created_at coins_used token_used"`
|
SortBy string `query:"sort_by" validate:"omitempty,oneof=created_at coins_used"`
|
||||||
SortOrder string `query:"sort_order" validate:"omitempty,oneof=asc desc"`
|
SortOrder string `query:"sort_order" validate:"omitempty,oneof=asc desc"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -70,7 +70,7 @@ func (p *campaignProcessor) ListCampaigns(ctx context.Context, req *contract.Lis
|
|||||||
Page: req.Page,
|
Page: req.Page,
|
||||||
Limit: req.Limit,
|
Limit: req.Limit,
|
||||||
Search: req.Search,
|
Search: req.Search,
|
||||||
Type: string(entities.NormalizeCampaignType(req.Type)),
|
Type: req.Type,
|
||||||
IsActive: req.IsActive,
|
IsActive: req.IsActive,
|
||||||
ShowOnApp: req.ShowOnApp,
|
ShowOnApp: req.ShowOnApp,
|
||||||
StartDate: req.StartDate,
|
StartDate: req.StartDate,
|
||||||
@@ -178,7 +178,7 @@ func (p *campaignRuleProcessor) CreateCampaignRule(ctx context.Context, req *con
|
|||||||
CampaignID: req.CampaignID,
|
CampaignID: req.CampaignID,
|
||||||
RuleType: entities.RuleType(req.RuleType),
|
RuleType: entities.RuleType(req.RuleType),
|
||||||
ConditionValue: req.ConditionValue,
|
ConditionValue: req.ConditionValue,
|
||||||
RewardType: entities.NormalizeCampaignRewardType(req.RewardType),
|
RewardType: entities.CampaignRewardType(req.RewardType),
|
||||||
RewardValue: req.RewardValue,
|
RewardValue: req.RewardValue,
|
||||||
RewardSubtype: (*entities.RewardSubtype)(req.RewardSubtype),
|
RewardSubtype: (*entities.RewardSubtype)(req.RewardSubtype),
|
||||||
RewardRefID: req.RewardRefID,
|
RewardRefID: req.RewardRefID,
|
||||||
@@ -218,7 +218,7 @@ func (p *campaignRuleProcessor) ListCampaignRules(ctx context.Context, req *cont
|
|||||||
Limit: req.Limit,
|
Limit: req.Limit,
|
||||||
CampaignID: req.CampaignID,
|
CampaignID: req.CampaignID,
|
||||||
RuleType: req.RuleType,
|
RuleType: req.RuleType,
|
||||||
RewardType: string(entities.NormalizeCampaignRewardType(req.RewardType)),
|
RewardType: req.RewardType,
|
||||||
}
|
}
|
||||||
|
|
||||||
// Get from repository
|
// Get from repository
|
||||||
@@ -247,7 +247,7 @@ func (p *campaignRuleProcessor) UpdateCampaignRule(ctx context.Context, req *con
|
|||||||
CampaignID: req.CampaignID,
|
CampaignID: req.CampaignID,
|
||||||
RuleType: entities.RuleType(req.RuleType),
|
RuleType: entities.RuleType(req.RuleType),
|
||||||
ConditionValue: req.ConditionValue,
|
ConditionValue: req.ConditionValue,
|
||||||
RewardType: entities.NormalizeCampaignRewardType(req.RewardType),
|
RewardType: entities.CampaignRewardType(req.RewardType),
|
||||||
RewardValue: req.RewardValue,
|
RewardValue: req.RewardValue,
|
||||||
RewardSubtype: (*entities.RewardSubtype)(req.RewardSubtype),
|
RewardSubtype: (*entities.RewardSubtype)(req.RewardSubtype),
|
||||||
RewardRefID: req.RewardRefID,
|
RewardRefID: req.RewardRefID,
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ package processor
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"apskel-pos-be/internal/contract"
|
"apskel-pos-be/internal/contract"
|
||||||
@@ -142,6 +143,13 @@ func (p *customerAuthProcessor) StartRegistration(ctx context.Context, req *cont
|
|||||||
return nil, fmt.Errorf("phone number already registered")
|
return nil, fmt.Errorf("phone number already registered")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Resolve the organization before an OTP is sent, rather than failing on a foreign
|
||||||
|
// key at the last step.
|
||||||
|
organizationID, err := p.registrationOrganization(ctx, req.OrganizationID)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
// Generate registration token and create OTP session
|
// Generate registration token and create OTP session
|
||||||
registrationToken := uuid.New().String()
|
registrationToken := uuid.New().String()
|
||||||
|
|
||||||
@@ -156,6 +164,7 @@ func (p *customerAuthProcessor) StartRegistration(ctx context.Context, req *cont
|
|||||||
"registration_token": registrationToken,
|
"registration_token": registrationToken,
|
||||||
"name": req.Name,
|
"name": req.Name,
|
||||||
"birth_date": req.BirthDate,
|
"birth_date": req.BirthDate,
|
||||||
|
"organization_id": organizationID.String(),
|
||||||
"step": "otp_sent",
|
"step": "otp_sent",
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -294,10 +303,14 @@ func (p *customerAuthProcessor) SetPassword(ctx context.Context, req *contract.R
|
|||||||
return nil, fmt.Errorf("invalid birth date format: %w", err)
|
return nil, fmt.Errorf("invalid birth date format: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
defaultOrgID := uuid.MustParse("87bec7c1-e274-4f66-bac5-84e632208470") // This should be configurable
|
orgIDStr, _ := otpSession.Metadata["organization_id"].(string)
|
||||||
|
organizationID, err := uuid.Parse(orgIDStr)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("invalid registration data: organization not found, start the registration again")
|
||||||
|
}
|
||||||
|
|
||||||
customer := &entities.Customer{
|
customer := &entities.Customer{
|
||||||
OrganizationID: defaultOrgID,
|
OrganizationID: organizationID,
|
||||||
Name: name,
|
Name: name,
|
||||||
PhoneNumber: &otpSession.PhoneNumber,
|
PhoneNumber: &otpSession.PhoneNumber,
|
||||||
BirthDate: &birthDate,
|
BirthDate: &birthDate,
|
||||||
@@ -438,3 +451,37 @@ func (p *customerAuthProcessor) ResendOtp(ctx context.Context, req *contract.Res
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Helper functions - OTP generation is now handled by OtpProcessor
|
// Helper functions - OTP generation is now handled by OtpProcessor
|
||||||
|
|
||||||
|
// registrationOrganization is the organization a new customer joins: the one the app
|
||||||
|
// sent, which must exist, or, when the app sent none, the only organization there is.
|
||||||
|
// With several organizations and none sent there is no way to choose, so it refuses.
|
||||||
|
func (p *customerAuthProcessor) registrationOrganization(ctx context.Context, requested string) (uuid.UUID, error) {
|
||||||
|
requested = strings.TrimSpace(requested)
|
||||||
|
if requested != "" {
|
||||||
|
id, err := uuid.Parse(requested)
|
||||||
|
if err != nil {
|
||||||
|
return uuid.Nil, fmt.Errorf("organization_id must be a valid UUID")
|
||||||
|
}
|
||||||
|
exists, err := p.customerAuthRepo.OrganizationExists(ctx, id)
|
||||||
|
if err != nil {
|
||||||
|
return uuid.Nil, err
|
||||||
|
}
|
||||||
|
if !exists {
|
||||||
|
return uuid.Nil, fmt.Errorf("organization not found")
|
||||||
|
}
|
||||||
|
return id, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
ids, err := p.customerAuthRepo.OrganizationIDs(ctx, 2)
|
||||||
|
if err != nil {
|
||||||
|
return uuid.Nil, err
|
||||||
|
}
|
||||||
|
switch len(ids) {
|
||||||
|
case 1:
|
||||||
|
return ids[0], nil
|
||||||
|
case 0:
|
||||||
|
return uuid.Nil, fmt.Errorf("no organization exists to register customers into")
|
||||||
|
default:
|
||||||
|
return uuid.Nil, fmt.Errorf("organization_id is required: there is more than one organization")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -0,0 +1,157 @@
|
|||||||
|
package processor
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
|
||||||
|
"apskel-pos-be/internal/models"
|
||||||
|
"apskel-pos-be/internal/repository"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
customerOrdersPageLimit = 20
|
||||||
|
customerOrdersMaxLimit = 100
|
||||||
|
)
|
||||||
|
|
||||||
|
type orderEarnedReader interface {
|
||||||
|
EarnedByOrders(ctx context.Context, orderIDs []uuid.UUID) (map[uuid.UUID]OrderEarned, error)
|
||||||
|
}
|
||||||
|
|
||||||
|
// CustomerOrderProcessor serves the customer app's order history: the customer's own
|
||||||
|
// orders only, without costs or staff details.
|
||||||
|
type CustomerOrderProcessor struct {
|
||||||
|
repo repository.CustomerOrderRepository
|
||||||
|
earned orderEarnedReader
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewCustomerOrderProcessor(repo repository.CustomerOrderRepository, earned orderEarnedReader) *CustomerOrderProcessor {
|
||||||
|
return &CustomerOrderProcessor{repo: repo, earned: earned}
|
||||||
|
}
|
||||||
|
|
||||||
|
// List is GET /customer/orders: the customer's orders across all outlets, newest first.
|
||||||
|
func (p *CustomerOrderProcessor) List(ctx context.Context, customerID uuid.UUID, query models.ListCustomerOrdersQuery) (*models.PaginatedResponse[models.CustomerOrderSummary], error) {
|
||||||
|
page, limit := query.Page, query.Limit
|
||||||
|
if page == 0 {
|
||||||
|
page = 1
|
||||||
|
}
|
||||||
|
if limit == 0 {
|
||||||
|
limit = customerOrdersPageLimit
|
||||||
|
}
|
||||||
|
if page < 1 || limit < 1 || limit > customerOrdersMaxLimit {
|
||||||
|
return nil, fmt.Errorf("%w: page must be at least 1 and limit between 1 and %d", ErrInvalidWalletQuery, customerOrdersMaxLimit)
|
||||||
|
}
|
||||||
|
|
||||||
|
rows, total, err := p.repo.ListOrders(ctx, customerID, (page-1)*limit, limit)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
ids := make([]uuid.UUID, 0, len(rows))
|
||||||
|
for _, r := range rows {
|
||||||
|
ids = append(ids, r.ID)
|
||||||
|
}
|
||||||
|
earned, err := p.earned.EarnedByOrders(ctx, ids)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
data := make([]models.CustomerOrderSummary, 0, len(rows))
|
||||||
|
for _, r := range rows {
|
||||||
|
data = append(data, customerOrderSummary(r, earned[r.ID]))
|
||||||
|
}
|
||||||
|
return &models.PaginatedResponse[models.CustomerOrderSummary]{
|
||||||
|
Data: data,
|
||||||
|
Pagination: models.Pagination{
|
||||||
|
Page: page,
|
||||||
|
Limit: limit,
|
||||||
|
Total: total,
|
||||||
|
TotalPages: int((total + int64(limit) - 1) / int64(limit)),
|
||||||
|
},
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Detail is GET /customer/orders/:id. Another customer's order is
|
||||||
|
// repository.ErrCustomerOrderNotFound, like one that does not exist.
|
||||||
|
func (p *CustomerOrderProcessor) Detail(ctx context.Context, customerID, orderID uuid.UUID) (*models.CustomerOrderDetail, error) {
|
||||||
|
row, err := p.repo.GetOrder(ctx, customerID, orderID)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
items, err := p.repo.ListItems(ctx, orderID)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
payments, err := p.repo.ListPayments(ctx, orderID)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
earned, err := p.earned.EarnedByOrders(ctx, []uuid.UUID{orderID})
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
detail := &models.CustomerOrderDetail{
|
||||||
|
CustomerOrderSummary: customerOrderSummary(*row, earned[orderID]),
|
||||||
|
TableNumber: row.TableNumber,
|
||||||
|
Subtotal: row.Subtotal,
|
||||||
|
DiscountAmount: row.DiscountAmount,
|
||||||
|
TaxAmount: row.TaxAmount,
|
||||||
|
RefundAmount: row.RefundAmount,
|
||||||
|
Items: make([]models.CustomerOrderItem, 0, len(items)),
|
||||||
|
Payments: make([]models.CustomerOrderPayment, 0, len(payments)),
|
||||||
|
}
|
||||||
|
for _, it := range items {
|
||||||
|
modifiers := []map[string]interface{}(it.Modifiers)
|
||||||
|
if modifiers == nil {
|
||||||
|
modifiers = []map[string]interface{}{}
|
||||||
|
}
|
||||||
|
detail.Items = append(detail.Items, models.CustomerOrderItem{
|
||||||
|
ID: it.ID,
|
||||||
|
ProductID: it.ProductID,
|
||||||
|
ProductName: it.ProductName,
|
||||||
|
VariantName: it.VariantName,
|
||||||
|
Quantity: it.Quantity,
|
||||||
|
Weight: it.Weight,
|
||||||
|
UnitName: it.UnitName,
|
||||||
|
UnitPrice: it.UnitPrice,
|
||||||
|
TotalPrice: it.TotalPrice,
|
||||||
|
RefundQuantity: it.RefundQuantity,
|
||||||
|
Modifiers: modifiers,
|
||||||
|
Notes: it.Notes,
|
||||||
|
Status: it.Status,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
for _, pay := range payments {
|
||||||
|
detail.Payments = append(detail.Payments, models.CustomerOrderPayment{
|
||||||
|
ID: pay.ID,
|
||||||
|
MethodName: pay.MethodName,
|
||||||
|
MethodType: pay.MethodType,
|
||||||
|
Amount: pay.Amount,
|
||||||
|
Status: pay.Status,
|
||||||
|
RefundAmount: pay.RefundAmount,
|
||||||
|
PointsUsed: pay.PointsUsed,
|
||||||
|
PointValue: pay.PointValue,
|
||||||
|
CreatedAt: pay.CreatedAt,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
return detail, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func customerOrderSummary(r repository.CustomerOrderRow, earned OrderEarned) models.CustomerOrderSummary {
|
||||||
|
return models.CustomerOrderSummary{
|
||||||
|
ID: r.ID,
|
||||||
|
OrderNumber: r.OrderNumber,
|
||||||
|
OutletID: r.OutletID,
|
||||||
|
OutletName: r.OutletName,
|
||||||
|
OrderType: r.OrderType,
|
||||||
|
Status: r.Status,
|
||||||
|
PaymentStatus: r.PaymentStatus,
|
||||||
|
TotalAmount: r.TotalAmount,
|
||||||
|
ItemCount: r.ItemCount,
|
||||||
|
IsVoid: r.IsVoid,
|
||||||
|
IsRefund: r.IsRefund,
|
||||||
|
PointsEarned: earned.Points,
|
||||||
|
CoinsEarned: earned.Coins,
|
||||||
|
CreatedAt: r.CreatedAt,
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,145 @@
|
|||||||
|
package processor
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
"github.com/stretchr/testify/assert"
|
||||||
|
"github.com/stretchr/testify/require"
|
||||||
|
|
||||||
|
"apskel-pos-be/internal/models"
|
||||||
|
"apskel-pos-be/internal/repository"
|
||||||
|
)
|
||||||
|
|
||||||
|
type customerOrderRepoFake struct {
|
||||||
|
owner map[uuid.UUID]uuid.UUID // order -> customer
|
||||||
|
orders []repository.CustomerOrderRow
|
||||||
|
items map[uuid.UUID][]repository.CustomerOrderItemRow
|
||||||
|
payments map[uuid.UUID][]repository.CustomerOrderPaymentRow
|
||||||
|
offset int
|
||||||
|
limit int
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *customerOrderRepoFake) ListOrders(_ context.Context, customerID uuid.UUID, offset, limit int) ([]repository.CustomerOrderRow, int64, error) {
|
||||||
|
f.offset, f.limit = offset, limit
|
||||||
|
var mine []repository.CustomerOrderRow
|
||||||
|
for _, o := range f.orders {
|
||||||
|
if f.owner[o.ID] == customerID {
|
||||||
|
mine = append(mine, o)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return mine, int64(len(mine)), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *customerOrderRepoFake) GetOrder(_ context.Context, customerID, orderID uuid.UUID) (*repository.CustomerOrderRow, error) {
|
||||||
|
for _, o := range f.orders {
|
||||||
|
if o.ID == orderID && f.owner[o.ID] == customerID {
|
||||||
|
c := o
|
||||||
|
return &c, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil, repository.ErrCustomerOrderNotFound
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *customerOrderRepoFake) ListItems(_ context.Context, orderID uuid.UUID) ([]repository.CustomerOrderItemRow, error) {
|
||||||
|
return f.items[orderID], nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *customerOrderRepoFake) ListPayments(_ context.Context, orderID uuid.UUID) ([]repository.CustomerOrderPaymentRow, error) {
|
||||||
|
return f.payments[orderID], nil
|
||||||
|
}
|
||||||
|
|
||||||
|
type earnedFake map[uuid.UUID]OrderEarned
|
||||||
|
|
||||||
|
func (f earnedFake) EarnedByOrders(_ context.Context, ids []uuid.UUID) (map[uuid.UUID]OrderEarned, error) {
|
||||||
|
out := map[uuid.UUID]OrderEarned{}
|
||||||
|
for _, id := range ids {
|
||||||
|
if e, ok := f[id]; ok {
|
||||||
|
out[id] = e
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func newCustomerOrderTest() (*customerOrderRepoFake, uuid.UUID, uuid.UUID, uuid.UUID) {
|
||||||
|
customer, other := uuid.New(), uuid.New()
|
||||||
|
mine, theirs := uuid.New(), uuid.New()
|
||||||
|
repo := &customerOrderRepoFake{
|
||||||
|
owner: map[uuid.UUID]uuid.UUID{mine: customer, theirs: other},
|
||||||
|
orders: []repository.CustomerOrderRow{
|
||||||
|
{ID: mine, OrderNumber: "ORD-1", OutletName: "Gokuna 1", Status: "completed", PaymentStatus: "completed", Subtotal: 90000, TotalAmount: 99000, ItemCount: 2, CreatedAt: time.Now()},
|
||||||
|
{ID: theirs, OrderNumber: "ORD-2"},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
return repo, customer, mine, theirs
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCustomerOrders_ListShowsOnlyTheCustomersOrdersWithEarning(t *testing.T) {
|
||||||
|
repo, customer, mine, _ := newCustomerOrderTest()
|
||||||
|
p := NewCustomerOrderProcessor(repo, earnedFake{mine: {Points: 900, Coins: 3}})
|
||||||
|
|
||||||
|
got, err := p.List(context.Background(), customer, models.ListCustomerOrdersQuery{Page: 2, Limit: 10})
|
||||||
|
require.NoError(t, err)
|
||||||
|
require.Len(t, got.Data, 1)
|
||||||
|
assert.Equal(t, "ORD-1", got.Data[0].OrderNumber)
|
||||||
|
assert.Equal(t, int64(900), got.Data[0].PointsEarned)
|
||||||
|
assert.Equal(t, int64(3), got.Data[0].CoinsEarned)
|
||||||
|
assert.Equal(t, 10, repo.offset, "page 2 of 10 skips the first 10")
|
||||||
|
assert.Equal(t, 10, repo.limit)
|
||||||
|
assert.Equal(t, 2, got.Pagination.Page)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCustomerOrders_ListDefaultsAndLimits(t *testing.T) {
|
||||||
|
repo, customer, _, _ := newCustomerOrderTest()
|
||||||
|
p := NewCustomerOrderProcessor(repo, earnedFake{})
|
||||||
|
|
||||||
|
got, err := p.List(context.Background(), customer, models.ListCustomerOrdersQuery{})
|
||||||
|
require.NoError(t, err)
|
||||||
|
assert.Equal(t, 1, got.Pagination.Page)
|
||||||
|
assert.Equal(t, 20, got.Pagination.Limit)
|
||||||
|
|
||||||
|
for _, q := range []models.ListCustomerOrdersQuery{{Page: -1}, {Limit: 101}, {Limit: -5}} {
|
||||||
|
_, err := p.List(context.Background(), customer, q)
|
||||||
|
assert.ErrorIs(t, err, ErrInvalidWalletQuery, "%+v", q)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCustomerOrders_DetailHasItemsPaymentsAndEarning(t *testing.T) {
|
||||||
|
repo, customer, mine, _ := newCustomerOrderTest()
|
||||||
|
variant, unit := "Large", "ons"
|
||||||
|
weight := 4.2
|
||||||
|
points, value := int64(12500), 1.0
|
||||||
|
repo.items = map[uuid.UUID][]repository.CustomerOrderItemRow{
|
||||||
|
mine: {
|
||||||
|
{ProductName: "Kopi Susu", VariantName: &variant, Quantity: 2, UnitPrice: 25000, TotalPrice: 50000, Status: "completed"},
|
||||||
|
{ProductName: "Ikan Tude", Quantity: 1, Weight: &weight, UnitName: &unit, UnitPrice: 4500, TotalPrice: 18900, Status: "completed"},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
repo.payments = map[uuid.UUID][]repository.CustomerOrderPaymentRow{
|
||||||
|
mine: {
|
||||||
|
{MethodName: "EnakPoint", MethodType: "point", Amount: 12500, Status: "completed", PointsUsed: &points, PointValue: &value},
|
||||||
|
{MethodName: "Cash", MethodType: "cash", Amount: 86500, Status: "completed"},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
p := NewCustomerOrderProcessor(repo, earnedFake{mine: {Points: 865}})
|
||||||
|
|
||||||
|
got, err := p.Detail(context.Background(), customer, mine)
|
||||||
|
require.NoError(t, err)
|
||||||
|
assert.Equal(t, "Gokuna 1", got.OutletName)
|
||||||
|
assert.Equal(t, float64(90000), got.Subtotal)
|
||||||
|
assert.Equal(t, int64(865), got.PointsEarned)
|
||||||
|
require.Len(t, got.Items, 2)
|
||||||
|
assert.Equal(t, "Large", *got.Items[0].VariantName)
|
||||||
|
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)
|
||||||
|
require.Len(t, got.Payments, 2)
|
||||||
|
assert.Equal(t, int64(12500), *got.Payments[0].PointsUsed)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCustomerOrders_AnotherCustomersOrderIsNotFound(t *testing.T) {
|
||||||
|
repo, customer, _, theirs := newCustomerOrderTest()
|
||||||
|
_, err := NewCustomerOrderProcessor(repo, earnedFake{}).Detail(context.Background(), customer, theirs)
|
||||||
|
assert.ErrorIs(t, err, repository.ErrCustomerOrderNotFound)
|
||||||
|
}
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
package processor
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
|
||||||
|
"apskel-pos-be/internal/models"
|
||||||
|
"apskel-pos-be/internal/repository"
|
||||||
|
)
|
||||||
|
|
||||||
|
// CustomerOutletProcessor lists the outlets the customer app shows: the active
|
||||||
|
// outlets of the customer's organization, where their wallet can be used (K4).
|
||||||
|
type CustomerOutletProcessor struct {
|
||||||
|
repo repository.CustomerOutletRepository
|
||||||
|
settings outletSettingsReader
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewCustomerOutletProcessor(repo repository.CustomerOutletRepository, settings outletSettingsReader) *CustomerOutletProcessor {
|
||||||
|
return &CustomerOutletProcessor{repo: repo, settings: settings}
|
||||||
|
}
|
||||||
|
|
||||||
|
// List is GET /customer/outlets.
|
||||||
|
func (p *CustomerOutletProcessor) List(ctx context.Context, customerID uuid.UUID) ([]models.CustomerOutlet, error) {
|
||||||
|
organizationID, err := p.repo.CustomerOrganizationID(ctx, customerID)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
outlets, err := p.repo.ListActiveOutlets(ctx, organizationID)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
list := make([]models.CustomerOutlet, 0, len(outlets))
|
||||||
|
for _, o := range outlets {
|
||||||
|
settings, err := p.settings.Outlet(ctx, o.ID)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
list = append(list, models.CustomerOutlet{
|
||||||
|
ID: o.ID,
|
||||||
|
Name: o.Name,
|
||||||
|
Address: o.Address,
|
||||||
|
AcceptsPointPayment: settings.PointPayment.AcceptPayment,
|
||||||
|
EarnsPoints: settings.Point.Enabled,
|
||||||
|
EarnsCoins: settings.Coin.Enabled,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
return list, nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,77 @@
|
|||||||
|
package processor
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
"github.com/stretchr/testify/assert"
|
||||||
|
"github.com/stretchr/testify/require"
|
||||||
|
|
||||||
|
"apskel-pos-be/internal/models"
|
||||||
|
"apskel-pos-be/internal/repository"
|
||||||
|
)
|
||||||
|
|
||||||
|
type customerOutletRepoFake struct {
|
||||||
|
orgs map[uuid.UUID]uuid.UUID
|
||||||
|
outlets map[uuid.UUID][]repository.CustomerOutlet
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f customerOutletRepoFake) CustomerOrganizationID(_ context.Context, id uuid.UUID) (uuid.UUID, error) {
|
||||||
|
org, ok := f.orgs[id]
|
||||||
|
if !ok {
|
||||||
|
return uuid.Nil, repository.ErrWalletNotFound
|
||||||
|
}
|
||||||
|
return org, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f customerOutletRepoFake) ListActiveOutlets(_ context.Context, org uuid.UUID) ([]repository.CustomerOutlet, error) {
|
||||||
|
return f.outlets[org], nil
|
||||||
|
}
|
||||||
|
|
||||||
|
type outletSettingsFake map[uuid.UUID]models.OutletLoyaltySettings
|
||||||
|
|
||||||
|
func (f outletSettingsFake) Outlet(_ context.Context, id uuid.UUID) (*models.OutletLoyaltySettings, error) {
|
||||||
|
s := f[id]
|
||||||
|
return &s, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCustomerOutlets_ListsTheCustomersOrganizationWithLoyaltyFlags(t *testing.T) {
|
||||||
|
customer, org, other := uuid.New(), uuid.New(), uuid.New()
|
||||||
|
kemang, blokm := uuid.New(), uuid.New()
|
||||||
|
addr := "Jl. Kemang Raya 10"
|
||||||
|
repo := customerOutletRepoFake{
|
||||||
|
orgs: map[uuid.UUID]uuid.UUID{customer: org},
|
||||||
|
outlets: map[uuid.UUID][]repository.CustomerOutlet{
|
||||||
|
org: {{ID: blokm, Name: "Blok M"}, {ID: kemang, Name: "Kemang", Address: &addr}},
|
||||||
|
other: {{ID: uuid.New(), Name: "Not mine"}},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
settings := outletSettingsFake{
|
||||||
|
kemang: {
|
||||||
|
Point: models.LoyaltyEarnSettings{Enabled: true},
|
||||||
|
PointPayment: models.LoyaltyPointPaymentSettings{AcceptPayment: true},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
got, err := NewCustomerOutletProcessor(repo, settings).List(context.Background(), customer)
|
||||||
|
require.NoError(t, err)
|
||||||
|
assert.Equal(t, []models.CustomerOutlet{
|
||||||
|
{ID: blokm, Name: "Blok M"},
|
||||||
|
{ID: kemang, Name: "Kemang", Address: &addr, AcceptsPointPayment: true, EarnsPoints: true},
|
||||||
|
}, got)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCustomerOutlets_UnknownCustomer(t *testing.T) {
|
||||||
|
_, err := NewCustomerOutletProcessor(customerOutletRepoFake{}, outletSettingsFake{}).List(context.Background(), uuid.New())
|
||||||
|
assert.ErrorIs(t, err, repository.ErrWalletNotFound)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCustomerOutlets_NoOutletsIsAnEmptyList(t *testing.T) {
|
||||||
|
customer := uuid.New()
|
||||||
|
repo := customerOutletRepoFake{orgs: map[uuid.UUID]uuid.UUID{customer: uuid.New()}}
|
||||||
|
got, err := NewCustomerOutletProcessor(repo, outletSettingsFake{}).List(context.Background(), customer)
|
||||||
|
require.NoError(t, err)
|
||||||
|
assert.NotNil(t, got)
|
||||||
|
assert.Empty(t, got)
|
||||||
|
}
|
||||||
@@ -22,7 +22,7 @@ func NewCustomerPointsProcessor(walletQuery *WalletQueryProcessor, gameRepo *rep
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// The three endpoints below are the customer app's balance screens. They read the
|
// The endpoints below are the customer app's balance screens. They read the
|
||||||
// EnakPoint & EnakCoin wallet; customer_points and customer_tokens are no longer used
|
// EnakPoint & EnakCoin wallet; customer_points and customer_tokens are no longer used
|
||||||
// for balances (docs/prd-point-coin.md §9).
|
// for balances (docs/prd-point-coin.md §9).
|
||||||
|
|
||||||
@@ -42,22 +42,6 @@ func (p *CustomerPointsProcessor) GetCustomerTotalPointsAPI(ctx context.Context,
|
|||||||
}, nil
|
}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (p *CustomerPointsProcessor) GetCustomerTotalTokensAPI(ctx context.Context, customerID string) (*models.GetCustomerTokensResponse, error) {
|
|
||||||
id, err := parseWalletCustomerID(customerID)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
data, err := p.walletQuery.LegacyTokens(ctx, id)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("failed to get customer tokens: %w", err)
|
|
||||||
}
|
|
||||||
return &models.GetCustomerTokensResponse{
|
|
||||||
Status: "SUCCESS",
|
|
||||||
Message: "Customer tokens retrieved successfully.",
|
|
||||||
Data: data,
|
|
||||||
}, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (p *CustomerPointsProcessor) GetCustomerWalletAPI(ctx context.Context, customerID string) (*models.GetCustomerWalletResponse, error) {
|
func (p *CustomerPointsProcessor) GetCustomerWalletAPI(ctx context.Context, customerID string) (*models.GetCustomerWalletResponse, error) {
|
||||||
id, err := parseWalletCustomerID(customerID)
|
id, err := parseWalletCustomerID(customerID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
|||||||
@@ -99,10 +99,6 @@ func (p *GamePlayProcessor) ListGamePlays(ctx context.Context, query *models.Lis
|
|||||||
}
|
}
|
||||||
|
|
||||||
offset := (query.Page - 1) * query.Limit
|
offset := (query.Page - 1) * query.Limit
|
||||||
// The column was renamed; the old name still sorts the same way.
|
|
||||||
if query.SortBy == "token_used" {
|
|
||||||
query.SortBy = "coins_used"
|
|
||||||
}
|
|
||||||
|
|
||||||
// Get game plays from repository
|
// Get game plays from repository
|
||||||
gamePlays, total, err := p.gamePlayRepo.List(
|
gamePlays, total, err := p.gamePlayRepo.List(
|
||||||
|
|||||||
@@ -82,10 +82,6 @@ func (p *WalletQueryProcessor) Summary(ctx context.Context, customerID uuid.UUID
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
tokens, err := p.legacyTokens(ctx, customerID, balances)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
data := &models.GetCustomerWalletResponseData{
|
data := &models.GetCustomerWalletResponseData{
|
||||||
PointBalance: balances[constants.WalletCurrencyPoint],
|
PointBalance: balances[constants.WalletCurrencyPoint],
|
||||||
@@ -94,13 +90,10 @@ func (p *WalletQueryProcessor) Summary(ctx context.Context, customerID uuid.UUID
|
|||||||
PointDiscountValue: balances[constants.WalletCurrencyPoint] * pointValue,
|
PointDiscountValue: balances[constants.WalletCurrencyPoint] * pointValue,
|
||||||
RecentTransactions: recent,
|
RecentTransactions: recent,
|
||||||
TotalPoints: points.TotalPoints,
|
TotalPoints: points.TotalPoints,
|
||||||
TotalTokens: tokens.TotalTokens,
|
|
||||||
PointsHistory: points.PointsHistory,
|
PointsHistory: points.PointsHistory,
|
||||||
TokensHistory: tokens.TokensHistory,
|
|
||||||
LastUpdated: points.LastUpdated,
|
|
||||||
}
|
}
|
||||||
if tokens.LastUpdated.After(data.LastUpdated) {
|
if len(recent) > 0 {
|
||||||
data.LastUpdated = tokens.LastUpdated
|
data.LastUpdated = recent[0].CreatedAt
|
||||||
}
|
}
|
||||||
for _, e := range expiring {
|
for _, e := range expiring {
|
||||||
entry := &models.CustomerWalletExpiring{Amount: e.Amount, Date: e.Date}
|
entry := &models.CustomerWalletExpiring{Amount: e.Amount, Date: e.Date}
|
||||||
@@ -161,32 +154,6 @@ func (p *WalletQueryProcessor) legacyPoints(ctx context.Context, customerID uuid
|
|||||||
return data, nil
|
return data, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// LegacyTokens is the pre-wallet GET /customer/tokens. Tokens are EnakCoin now.
|
|
||||||
func (p *WalletQueryProcessor) LegacyTokens(ctx context.Context, customerID uuid.UUID) (*models.GetCustomerTokensResponseData, error) {
|
|
||||||
balances, err := p.repo.SpendableBalances(ctx, customerID, p.now())
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
return p.legacyTokens(ctx, customerID, balances)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (p *WalletQueryProcessor) legacyTokens(ctx context.Context, customerID uuid.UUID, balances map[string]int64) (*models.GetCustomerTokensResponseData, error) {
|
|
||||||
recent, err := p.recent(ctx, customerID, constants.WalletCurrencyCoin, walletLegacyHistorySize)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
data := &models.GetCustomerTokensResponseData{TotalTokens: balances[constants.WalletCurrencyCoin]}
|
|
||||||
for _, tx := range recent {
|
|
||||||
data.TokensHistory = append(data.TokensHistory, models.TokensHistoryItem{
|
|
||||||
ID: tx.ID.String(), Tokens: tx.Amount, Type: tx.Type, Description: tx.Description, CreatedAt: tx.CreatedAt,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
if len(recent) > 0 {
|
|
||||||
data.LastUpdated = recent[0].CreatedAt
|
|
||||||
}
|
|
||||||
return data, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (p *WalletQueryProcessor) recent(ctx context.Context, customerID uuid.UUID, currency string, limit int) ([]models.CustomerWalletTransaction, error) {
|
func (p *WalletQueryProcessor) recent(ctx context.Context, customerID uuid.UUID, currency string, limit int) ([]models.CustomerWalletTransaction, error) {
|
||||||
rows, _, err := p.repo.ListTransactions(ctx, repository.WalletTransactionFilter{
|
rows, _, err := p.repo.ListTransactions(ctx, repository.WalletTransactionFilter{
|
||||||
CustomerID: customerID, Currency: currency, Limit: limit,
|
CustomerID: customerID, Currency: currency, Limit: limit,
|
||||||
|
|||||||
@@ -122,7 +122,6 @@ func TestWalletQueryProcessor_SummaryShowsWhereEachRowCameFromOrWent(t *testing.
|
|||||||
|
|
||||||
// The pre-wallet fields are still filled, from the wallet.
|
// The pre-wallet fields are still filled, from the wallet.
|
||||||
assert.Equal(t, int64(250), data.TotalPoints)
|
assert.Equal(t, int64(250), data.TotalPoints)
|
||||||
assert.Equal(t, int64(8), data.TotalTokens)
|
|
||||||
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.WalletTxTypePayment, data.PointsHistory[0].Type)
|
||||||
@@ -174,12 +173,6 @@ func TestWalletQueryProcessor_LegacyEndpointsSplitByCurrency(t *testing.T) {
|
|||||||
assert.Equal(t, int64(100), points.TotalPoints)
|
assert.Equal(t, int64(100), points.TotalPoints)
|
||||||
require.Len(t, points.PointsHistory, 1)
|
require.Len(t, points.PointsHistory, 1)
|
||||||
assert.Equal(t, int64(100), points.PointsHistory[0].Points)
|
assert.Equal(t, int64(100), points.PointsHistory[0].Points)
|
||||||
|
|
||||||
tokens, err := p.LegacyTokens(context.Background(), uuid.New())
|
|
||||||
require.NoError(t, err)
|
|
||||||
assert.Equal(t, int64(8), tokens.TotalTokens)
|
|
||||||
require.Len(t, tokens.TokensHistory, 1)
|
|
||||||
assert.Equal(t, int64(8), tokens.TokensHistory[0].Tokens)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestWalletQueryProcessor_TransactionsQuery(t *testing.T) {
|
func TestWalletQueryProcessor_TransactionsQuery(t *testing.T) {
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ import (
|
|||||||
|
|
||||||
"apskel-pos-be/internal/entities"
|
"apskel-pos-be/internal/entities"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
"gorm.io/gorm"
|
"gorm.io/gorm"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -16,6 +17,10 @@ type CustomerAuthRepository interface {
|
|||||||
UpdateCustomer(ctx context.Context, customer *entities.Customer) error
|
UpdateCustomer(ctx context.Context, customer *entities.Customer) error
|
||||||
CheckPhoneNumberExists(ctx context.Context, phoneNumber string) (bool, error)
|
CheckPhoneNumberExists(ctx context.Context, phoneNumber string) (bool, error)
|
||||||
SetCustomerPassword(ctx context.Context, customerID string, passwordHash string) error
|
SetCustomerPassword(ctx context.Context, customerID string, passwordHash string) error
|
||||||
|
// OrganizationExists reports whether an organization with this id exists.
|
||||||
|
OrganizationExists(ctx context.Context, organizationID uuid.UUID) (bool, error)
|
||||||
|
// OrganizationIDs returns up to limit organization ids.
|
||||||
|
OrganizationIDs(ctx context.Context, limit int) ([]uuid.UUID, error)
|
||||||
}
|
}
|
||||||
|
|
||||||
type customerAuthRepository struct {
|
type customerAuthRepository struct {
|
||||||
@@ -78,3 +83,21 @@ func (r *customerAuthRepository) SetCustomerPassword(ctx context.Context, custom
|
|||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (r *customerAuthRepository) OrganizationExists(ctx context.Context, organizationID uuid.UUID) (bool, error) {
|
||||||
|
var count int64
|
||||||
|
err := r.db.WithContext(ctx).Table("organizations").Where("id = ?", organizationID).Count(&count).Error
|
||||||
|
if err != nil {
|
||||||
|
return false, fmt.Errorf("failed to check organization: %w", err)
|
||||||
|
}
|
||||||
|
return count > 0, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *customerAuthRepository) OrganizationIDs(ctx context.Context, limit int) ([]uuid.UUID, error) {
|
||||||
|
var ids []uuid.UUID
|
||||||
|
err := r.db.WithContext(ctx).Table("organizations").Order("created_at").Limit(limit).Pluck("id", &ids).Error
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("failed to list organizations: %w", err)
|
||||||
|
}
|
||||||
|
return ids, nil
|
||||||
|
}
|
||||||
|
|||||||
@@ -0,0 +1,157 @@
|
|||||||
|
package repository
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
"gorm.io/gorm"
|
||||||
|
|
||||||
|
"apskel-pos-be/internal/entities"
|
||||||
|
)
|
||||||
|
|
||||||
|
// ErrCustomerOrderNotFound means the order does not exist or belongs to another
|
||||||
|
// customer; the two are not told apart.
|
||||||
|
var ErrCustomerOrderNotFound = errors.New("order not found")
|
||||||
|
|
||||||
|
// CustomerOrderRow is one order as the customer app lists it.
|
||||||
|
type CustomerOrderRow struct {
|
||||||
|
ID uuid.UUID
|
||||||
|
OrderNumber string
|
||||||
|
OutletID uuid.UUID
|
||||||
|
OutletName string
|
||||||
|
OrderType string
|
||||||
|
TableNumber *string
|
||||||
|
Status string
|
||||||
|
PaymentStatus string
|
||||||
|
Subtotal float64
|
||||||
|
DiscountAmount float64
|
||||||
|
TaxAmount float64
|
||||||
|
TotalAmount float64
|
||||||
|
RefundAmount float64
|
||||||
|
IsVoid bool
|
||||||
|
IsRefund bool
|
||||||
|
ItemCount int64
|
||||||
|
CreatedAt time.Time
|
||||||
|
}
|
||||||
|
|
||||||
|
// CustomerOrderItemRow is one line of an order, without costs.
|
||||||
|
type CustomerOrderItemRow struct {
|
||||||
|
ID uuid.UUID
|
||||||
|
ProductID uuid.UUID
|
||||||
|
ProductName string
|
||||||
|
VariantName *string
|
||||||
|
Quantity int
|
||||||
|
Weight *float64
|
||||||
|
UnitName *string
|
||||||
|
UnitPrice float64
|
||||||
|
TotalPrice float64
|
||||||
|
RefundQuantity int
|
||||||
|
Modifiers entities.Modifiers `gorm:"type:jsonb"`
|
||||||
|
Notes *string
|
||||||
|
Status string
|
||||||
|
}
|
||||||
|
|
||||||
|
// CustomerOrderPaymentRow is one payment of an order.
|
||||||
|
type CustomerOrderPaymentRow struct {
|
||||||
|
ID uuid.UUID
|
||||||
|
MethodName string
|
||||||
|
MethodType string
|
||||||
|
Amount float64
|
||||||
|
Status string
|
||||||
|
RefundAmount float64
|
||||||
|
PointsUsed *int64
|
||||||
|
PointValue *float64
|
||||||
|
CreatedAt time.Time
|
||||||
|
}
|
||||||
|
|
||||||
|
// CustomerOrderRepository reads a customer's own orders for the customer app. Every
|
||||||
|
// read is scoped to the customer, so one customer can never see another's order.
|
||||||
|
type CustomerOrderRepository interface {
|
||||||
|
// ListOrders returns a page of the customer's orders, newest first, and the total.
|
||||||
|
ListOrders(ctx context.Context, customerID uuid.UUID, offset, limit int) ([]CustomerOrderRow, int64, error)
|
||||||
|
// GetOrder returns ErrCustomerOrderNotFound unless the order is the customer's.
|
||||||
|
GetOrder(ctx context.Context, customerID, orderID uuid.UUID) (*CustomerOrderRow, error)
|
||||||
|
ListItems(ctx context.Context, orderID uuid.UUID) ([]CustomerOrderItemRow, error)
|
||||||
|
ListPayments(ctx context.Context, orderID uuid.UUID) ([]CustomerOrderPaymentRow, error)
|
||||||
|
}
|
||||||
|
|
||||||
|
type customerOrderRepository struct {
|
||||||
|
db *gorm.DB
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewCustomerOrderRepository(db *gorm.DB) CustomerOrderRepository {
|
||||||
|
return &customerOrderRepository{db: db}
|
||||||
|
}
|
||||||
|
|
||||||
|
const customerOrderColumns = `o.id, o.order_number, o.outlet_id, COALESCE(ol.name, '') AS outlet_name,
|
||||||
|
o.order_type, o.table_number, o.status, o.payment_status, o.subtotal, o.discount_amount,
|
||||||
|
o.tax_amount, o.total_amount, o.refund_amount, o.is_void, o.is_refund,
|
||||||
|
(SELECT COUNT(*) FROM order_items oi WHERE oi.order_id = o.id) AS item_count, o.created_at`
|
||||||
|
|
||||||
|
func (r *customerOrderRepository) ListOrders(ctx context.Context, customerID uuid.UUID, offset, limit int) ([]CustomerOrderRow, int64, error) {
|
||||||
|
db := DBFromContext(ctx, r.db).WithContext(ctx)
|
||||||
|
var total int64
|
||||||
|
if err := db.Table("orders").Where("customer_id = ?", customerID).Count(&total).Error; err != nil {
|
||||||
|
return nil, 0, fmt.Errorf("failed to count customer orders: %w", err)
|
||||||
|
}
|
||||||
|
var rows []CustomerOrderRow
|
||||||
|
err := db.Raw(`SELECT `+customerOrderColumns+`
|
||||||
|
FROM orders o LEFT JOIN outlets ol ON ol.id = o.outlet_id
|
||||||
|
WHERE o.customer_id = ?
|
||||||
|
ORDER BY o.created_at DESC, o.id
|
||||||
|
LIMIT ? OFFSET ?`, customerID, limit, offset).Scan(&rows).Error
|
||||||
|
if err != nil {
|
||||||
|
return nil, 0, fmt.Errorf("failed to list customer orders: %w", err)
|
||||||
|
}
|
||||||
|
return rows, total, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *customerOrderRepository) GetOrder(ctx context.Context, customerID, orderID uuid.UUID) (*CustomerOrderRow, error) {
|
||||||
|
var rows []CustomerOrderRow
|
||||||
|
err := DBFromContext(ctx, r.db).WithContext(ctx).Raw(`SELECT `+customerOrderColumns+`
|
||||||
|
FROM orders o LEFT JOIN outlets ol ON ol.id = o.outlet_id
|
||||||
|
WHERE o.id = ? AND o.customer_id = ?`, orderID, customerID).Scan(&rows).Error
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("failed to get customer order: %w", err)
|
||||||
|
}
|
||||||
|
if len(rows) == 0 {
|
||||||
|
return nil, ErrCustomerOrderNotFound
|
||||||
|
}
|
||||||
|
return &rows[0], nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *customerOrderRepository) ListItems(ctx context.Context, orderID uuid.UUID) ([]CustomerOrderItemRow, error) {
|
||||||
|
var rows []CustomerOrderItemRow
|
||||||
|
err := DBFromContext(ctx, r.db).WithContext(ctx).Raw(`
|
||||||
|
SELECT oi.id, oi.product_id, COALESCE(p.name, '') AS product_name, pv.name AS variant_name,
|
||||||
|
oi.quantity, oi.weight, COALESCE(u.abbreviation, u.name) AS unit_name,
|
||||||
|
oi.unit_price, oi.total_price, oi.refund_quantity, oi.modifiers, oi.notes, oi.status
|
||||||
|
FROM order_items oi
|
||||||
|
LEFT JOIN products p ON p.id = oi.product_id
|
||||||
|
LEFT JOIN product_variants pv ON pv.id = oi.product_variant_id
|
||||||
|
LEFT JOIN units u ON u.id = oi.unit_id
|
||||||
|
WHERE oi.order_id = ?
|
||||||
|
ORDER BY oi.created_at, oi.id`, orderID).Scan(&rows).Error
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("failed to list order items: %w", err)
|
||||||
|
}
|
||||||
|
return rows, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *customerOrderRepository) ListPayments(ctx context.Context, orderID uuid.UUID) ([]CustomerOrderPaymentRow, error) {
|
||||||
|
var rows []CustomerOrderPaymentRow
|
||||||
|
err := DBFromContext(ctx, r.db).WithContext(ctx).Raw(`
|
||||||
|
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
|
||||||
|
FROM payments pay
|
||||||
|
LEFT JOIN payment_methods pm ON pm.id = pay.payment_method_id
|
||||||
|
WHERE pay.order_id = ?
|
||||||
|
ORDER BY pay.created_at, pay.id`, orderID).Scan(&rows).Error
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("failed to list order payments: %w", err)
|
||||||
|
}
|
||||||
|
return rows, nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,60 @@
|
|||||||
|
package repository
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
"gorm.io/gorm"
|
||||||
|
)
|
||||||
|
|
||||||
|
// CustomerOutlet is what the customer app may see of an outlet.
|
||||||
|
type CustomerOutlet struct {
|
||||||
|
ID uuid.UUID
|
||||||
|
Name string
|
||||||
|
Address *string
|
||||||
|
}
|
||||||
|
|
||||||
|
// CustomerOutletRepository reads the outlets a customer can visit: the active outlets
|
||||||
|
// of their organization.
|
||||||
|
type CustomerOutletRepository interface {
|
||||||
|
// CustomerOrganizationID returns ErrWalletNotFound when the customer does not exist.
|
||||||
|
CustomerOrganizationID(ctx context.Context, customerID uuid.UUID) (uuid.UUID, error)
|
||||||
|
// ListActiveOutlets returns the organization's active outlets, by name.
|
||||||
|
ListActiveOutlets(ctx context.Context, organizationID uuid.UUID) ([]CustomerOutlet, error)
|
||||||
|
}
|
||||||
|
|
||||||
|
type customerOutletRepository struct {
|
||||||
|
db *gorm.DB
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewCustomerOutletRepository(db *gorm.DB) CustomerOutletRepository {
|
||||||
|
return &customerOutletRepository{db: db}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *customerOutletRepository) CustomerOrganizationID(ctx context.Context, customerID uuid.UUID) (uuid.UUID, error) {
|
||||||
|
var row struct{ OrganizationID uuid.UUID }
|
||||||
|
err := DBFromContext(ctx, r.db).WithContext(ctx).
|
||||||
|
Table("customers").Select("organization_id").Where("id = ?", customerID).Take(&row).Error
|
||||||
|
if err != nil {
|
||||||
|
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||||
|
return uuid.Nil, ErrWalletNotFound
|
||||||
|
}
|
||||||
|
return uuid.Nil, fmt.Errorf("failed to get customer organization: %w", err)
|
||||||
|
}
|
||||||
|
return row.OrganizationID, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *customerOutletRepository) ListActiveOutlets(ctx context.Context, organizationID uuid.UUID) ([]CustomerOutlet, error) {
|
||||||
|
var outlets []CustomerOutlet
|
||||||
|
err := DBFromContext(ctx, r.db).WithContext(ctx).
|
||||||
|
Table("outlets").Select("id, name, address").
|
||||||
|
Where("organization_id = ? AND is_active = ?", organizationID, true).
|
||||||
|
Order("name, id").
|
||||||
|
Scan(&outlets).Error
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("failed to list outlets: %w", err)
|
||||||
|
}
|
||||||
|
return outlets, nil
|
||||||
|
}
|
||||||
@@ -61,12 +61,14 @@ type Router struct {
|
|||||||
customerOrderPaymentHandler *handler.CustomerOrderPaymentHandler
|
customerOrderPaymentHandler *handler.CustomerOrderPaymentHandler
|
||||||
customerWalletHandler *handler.CustomerWalletHandler
|
customerWalletHandler *handler.CustomerWalletHandler
|
||||||
customerDeviceHandler *handler.CustomerDeviceHandler
|
customerDeviceHandler *handler.CustomerDeviceHandler
|
||||||
|
customerOutletHandler *handler.CustomerOutletHandler
|
||||||
|
customerOrderHandler *handler.CustomerOrderHandler
|
||||||
authMiddleware *middleware.AuthMiddleware
|
authMiddleware *middleware.AuthMiddleware
|
||||||
customerAuthMiddleware *middleware.CustomerAuthMiddleware
|
customerAuthMiddleware *middleware.CustomerAuthMiddleware
|
||||||
redisClient *redis.Client
|
redisClient *redis.Client
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewRouter(cfg *config.Config, healthHandler *handler.HealthHandler, authService service.AuthService, authMiddleware *middleware.AuthMiddleware, userService *service.UserServiceImpl, userValidator *validator.UserValidatorImpl, organizationService service.OrganizationService, organizationValidator validator.OrganizationValidator, outletService service.OutletService, outletValidator validator.OutletValidator, outletSettingService service.OutletSettingService, categoryService service.CategoryService, categoryValidator validator.CategoryValidator, productService service.ProductService, productValidator validator.ProductValidator, productVariantService service.ProductVariantService, productVariantValidator validator.ProductVariantValidator, inventoryService service.InventoryService, inventoryValidator validator.InventoryValidator, orderService service.OrderService, orderValidator validator.OrderValidator, fileService service.FileService, fileValidator validator.FileValidator, customerService service.CustomerService, customerValidator validator.CustomerValidator, paymentMethodService service.PaymentMethodService, paymentMethodValidator validator.PaymentMethodValidator, analyticsService *service.AnalyticsServiceImpl, reportService service.ReportService, tableService *service.TableServiceImpl, tableValidator *validator.TableValidator, unitService handler.UnitService, ingredientService handler.IngredientService, productRecipeService service.ProductRecipeService, vendorService service.VendorService, vendorValidator validator.VendorValidator, purchaseOrderService service.PurchaseOrderService, purchaseOrderValidator validator.PurchaseOrderValidator, purchaseCategoryService service.PurchaseCategoryService, purchaseCategoryValidator validator.PurchaseCategoryValidator, unitConverterService service.IngredientUnitConverterService, unitConverterValidator validator.IngredientUnitConverterValidator, chartOfAccountTypeService service.ChartOfAccountTypeService, chartOfAccountTypeValidator validator.ChartOfAccountTypeValidator, chartOfAccountService service.ChartOfAccountService, chartOfAccountValidator validator.ChartOfAccountValidator, accountService service.AccountService, accountValidator validator.AccountValidator, orderIngredientTransactionService service.OrderIngredientTransactionService, orderIngredientTransactionValidator validator.OrderIngredientTransactionValidator, gamificationService service.GamificationService, gamificationValidator validator.GamificationValidator, rewardService service.RewardService, rewardValidator validator.RewardValidator, campaignService service.CampaignService, campaignValidator validator.CampaignValidator, customerAuthService service.CustomerAuthService, customerAuthValidator validator.CustomerAuthValidator, customerPointsService service.CustomerPointsService, spinGameService service.SpinGameService, customerAuthMiddleware *middleware.CustomerAuthMiddleware, userDeviceService service.UserDeviceService, userDeviceValidator validator.UserDeviceValidator, notificationService service.NotificationService, notificationValidator validator.NotificationValidator, productOutletPriceService service.ProductOutletPriceService, productOutletPriceValidator validator.ProductOutletPriceValidator, selfOrderHandler *handler.SelfOrderHandler, expenseService *service.ExpenseServiceImpl, expenseValidator *validator.ExpenseValidatorImpl, cashAdvanceService service.CashAdvanceService, cashAdvanceValidator validator.CashAdvanceValidator, walletAdminService service.WalletAdminService, walletValidator validator.WalletValidator, loyaltySettingsService service.LoyaltySettingsService, customerPinService service.CustomerPinService, pointPaymentService service.PointPaymentService, customerOrderPaymentService service.CustomerOrderPaymentService, customerWalletService service.CustomerWalletService, customerDeviceService service.CustomerDeviceService, redisClient *redis.Client) *Router {
|
func NewRouter(cfg *config.Config, healthHandler *handler.HealthHandler, authService service.AuthService, authMiddleware *middleware.AuthMiddleware, userService *service.UserServiceImpl, userValidator *validator.UserValidatorImpl, organizationService service.OrganizationService, organizationValidator validator.OrganizationValidator, outletService service.OutletService, outletValidator validator.OutletValidator, outletSettingService service.OutletSettingService, categoryService service.CategoryService, categoryValidator validator.CategoryValidator, productService service.ProductService, productValidator validator.ProductValidator, productVariantService service.ProductVariantService, productVariantValidator validator.ProductVariantValidator, inventoryService service.InventoryService, inventoryValidator validator.InventoryValidator, orderService service.OrderService, orderValidator validator.OrderValidator, fileService service.FileService, fileValidator validator.FileValidator, customerService service.CustomerService, customerValidator validator.CustomerValidator, paymentMethodService service.PaymentMethodService, paymentMethodValidator validator.PaymentMethodValidator, analyticsService *service.AnalyticsServiceImpl, reportService service.ReportService, tableService *service.TableServiceImpl, tableValidator *validator.TableValidator, unitService handler.UnitService, ingredientService handler.IngredientService, productRecipeService service.ProductRecipeService, vendorService service.VendorService, vendorValidator validator.VendorValidator, purchaseOrderService service.PurchaseOrderService, purchaseOrderValidator validator.PurchaseOrderValidator, purchaseCategoryService service.PurchaseCategoryService, purchaseCategoryValidator validator.PurchaseCategoryValidator, unitConverterService service.IngredientUnitConverterService, unitConverterValidator validator.IngredientUnitConverterValidator, chartOfAccountTypeService service.ChartOfAccountTypeService, chartOfAccountTypeValidator validator.ChartOfAccountTypeValidator, chartOfAccountService service.ChartOfAccountService, chartOfAccountValidator validator.ChartOfAccountValidator, accountService service.AccountService, accountValidator validator.AccountValidator, orderIngredientTransactionService service.OrderIngredientTransactionService, orderIngredientTransactionValidator validator.OrderIngredientTransactionValidator, gamificationService service.GamificationService, gamificationValidator validator.GamificationValidator, rewardService service.RewardService, rewardValidator validator.RewardValidator, campaignService service.CampaignService, campaignValidator validator.CampaignValidator, customerAuthService service.CustomerAuthService, customerAuthValidator validator.CustomerAuthValidator, customerPointsService service.CustomerPointsService, spinGameService service.SpinGameService, customerAuthMiddleware *middleware.CustomerAuthMiddleware, userDeviceService service.UserDeviceService, userDeviceValidator validator.UserDeviceValidator, notificationService service.NotificationService, notificationValidator validator.NotificationValidator, productOutletPriceService service.ProductOutletPriceService, productOutletPriceValidator validator.ProductOutletPriceValidator, selfOrderHandler *handler.SelfOrderHandler, expenseService *service.ExpenseServiceImpl, expenseValidator *validator.ExpenseValidatorImpl, cashAdvanceService service.CashAdvanceService, cashAdvanceValidator validator.CashAdvanceValidator, walletAdminService service.WalletAdminService, walletValidator validator.WalletValidator, loyaltySettingsService service.LoyaltySettingsService, customerPinService service.CustomerPinService, pointPaymentService service.PointPaymentService, customerOrderPaymentService service.CustomerOrderPaymentService, customerWalletService service.CustomerWalletService, customerDeviceService service.CustomerDeviceService, customerOutletService service.CustomerOutletService, customerOrderService service.CustomerOrderService, redisClient *redis.Client) *Router {
|
||||||
|
|
||||||
return &Router{
|
return &Router{
|
||||||
config: cfg,
|
config: cfg,
|
||||||
@@ -119,6 +121,8 @@ func NewRouter(cfg *config.Config, healthHandler *handler.HealthHandler, authSer
|
|||||||
customerOrderPaymentHandler: handler.NewCustomerOrderPaymentHandler(customerOrderPaymentService),
|
customerOrderPaymentHandler: handler.NewCustomerOrderPaymentHandler(customerOrderPaymentService),
|
||||||
customerWalletHandler: handler.NewCustomerWalletHandler(customerWalletService),
|
customerWalletHandler: handler.NewCustomerWalletHandler(customerWalletService),
|
||||||
customerDeviceHandler: handler.NewCustomerDeviceHandler(customerDeviceService),
|
customerDeviceHandler: handler.NewCustomerDeviceHandler(customerDeviceService),
|
||||||
|
customerOutletHandler: handler.NewCustomerOutletHandler(customerOutletService),
|
||||||
|
customerOrderHandler: handler.NewCustomerOrderHandler(customerOrderService),
|
||||||
redisClient: redisClient,
|
redisClient: redisClient,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -169,7 +173,6 @@ func (r *Router) addAppRoutes(rg *gin.Engine) {
|
|||||||
customer.Use(r.customerAuthMiddleware.ValidateCustomerToken())
|
customer.Use(r.customerAuthMiddleware.ValidateCustomerToken())
|
||||||
{
|
{
|
||||||
customer.GET("/points", r.customerPointsHandler.GetCustomerPoints)
|
customer.GET("/points", r.customerPointsHandler.GetCustomerPoints)
|
||||||
customer.GET("/tokens", r.customerPointsHandler.GetCustomerTokens)
|
|
||||||
customer.GET("/wallet", r.customerPointsHandler.GetCustomerWallet)
|
customer.GET("/wallet", r.customerPointsHandler.GetCustomerWallet)
|
||||||
customer.GET("/wallet/transactions", r.customerPointsHandler.GetCustomerWalletTransactions)
|
customer.GET("/wallet/transactions", r.customerPointsHandler.GetCustomerWalletTransactions)
|
||||||
customer.GET("/wallet/expiring", r.customerPointsHandler.GetCustomerWalletExpiring)
|
customer.GET("/wallet/expiring", r.customerPointsHandler.GetCustomerWalletExpiring)
|
||||||
@@ -180,6 +183,9 @@ func (r *Router) addAppRoutes(rg *gin.Engine) {
|
|||||||
customer.POST("/wallet/transfer", r.customerWalletHandler.Transfer)
|
customer.POST("/wallet/transfer", r.customerWalletHandler.Transfer)
|
||||||
customer.PUT("/devices", r.customerDeviceHandler.Register)
|
customer.PUT("/devices", r.customerDeviceHandler.Register)
|
||||||
customer.DELETE("/devices/:device_id", r.customerDeviceHandler.Unregister)
|
customer.DELETE("/devices/:device_id", r.customerDeviceHandler.Unregister)
|
||||||
|
customer.GET("/outlets", r.customerOutletHandler.List)
|
||||||
|
customer.GET("/orders", r.customerOrderHandler.List)
|
||||||
|
customer.GET("/orders/:id", r.customerOrderHandler.Detail)
|
||||||
customer.POST("/orders/:id/pay-with-points", r.customerOrderPaymentHandler.PayWithPoints)
|
customer.POST("/orders/:id/pay-with-points", r.customerOrderPaymentHandler.PayWithPoints)
|
||||||
// PIN that approves moving EnakPoint and EnakCoin (docs/prd-point-coin.md F11)
|
// PIN that approves moving EnakPoint and EnakCoin (docs/prd-point-coin.md F11)
|
||||||
customer.GET("/pin/status", r.customerPinHandler.Status)
|
customer.GET("/pin/status", r.customerPinHandler.Status)
|
||||||
|
|||||||
@@ -44,6 +44,9 @@ func TestAllRoutesRegister(t *testing.T) {
|
|||||||
"POST /api/v1/customer/wallet/transfer",
|
"POST /api/v1/customer/wallet/transfer",
|
||||||
"PUT /api/v1/customer/devices",
|
"PUT /api/v1/customer/devices",
|
||||||
"DELETE /api/v1/customer/devices/:device_id",
|
"DELETE /api/v1/customer/devices/:device_id",
|
||||||
|
"GET /api/v1/customer/outlets",
|
||||||
|
"GET /api/v1/customer/orders",
|
||||||
|
"GET /api/v1/customer/orders/:id",
|
||||||
"GET /api/v1/orders/:id/point-payment/preview",
|
"GET /api/v1/orders/:id/point-payment/preview",
|
||||||
"POST /api/v1/customer/orders/:id/pay-with-points",
|
"POST /api/v1/customer/orders/:id/pay-with-points",
|
||||||
"GET /api/v1/customer/pin/status",
|
"GET /api/v1/customer/pin/status",
|
||||||
|
|||||||
@@ -177,7 +177,7 @@ func (s *campaignService) CreateCampaignRule(ctx context.Context, req *contract.
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Validate reward value based on reward type
|
// Validate reward value based on reward type
|
||||||
if req.RewardType == "POINTS" || req.RewardType == "COINS" || req.RewardType == "TOKENS" {
|
if req.RewardType == "POINTS" || req.RewardType == "COINS" {
|
||||||
if req.RewardValue == nil || *req.RewardValue <= 0 {
|
if req.RewardValue == nil || *req.RewardValue <= 0 {
|
||||||
return nil, fmt.Errorf("reward value must be positive for %s type", req.RewardType)
|
return nil, fmt.Errorf("reward value must be positive for %s type", req.RewardType)
|
||||||
}
|
}
|
||||||
@@ -247,7 +247,7 @@ func (s *campaignService) UpdateCampaignRule(ctx context.Context, req *contract.
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Validate reward value based on reward type
|
// Validate reward value based on reward type
|
||||||
if req.RewardType == "POINTS" || req.RewardType == "COINS" || req.RewardType == "TOKENS" {
|
if req.RewardType == "POINTS" || req.RewardType == "COINS" {
|
||||||
if req.RewardValue == nil || *req.RewardValue <= 0 {
|
if req.RewardValue == nil || *req.RewardValue <= 0 {
|
||||||
return nil, fmt.Errorf("reward value must be positive for %s type", req.RewardType)
|
return nil, fmt.Errorf("reward value must be positive for %s type", req.RewardType)
|
||||||
}
|
}
|
||||||
@@ -295,7 +295,7 @@ func (s *campaignService) GetCampaignRulesByCampaignID(ctx context.Context, camp
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (s *campaignService) validateCampaignType(campaignType string) error {
|
func (s *campaignService) validateCampaignType(campaignType string) error {
|
||||||
validTypes := []string{"REWARD", "POINTS", "COINS", "TOKENS", "MIXED"}
|
validTypes := []string{"REWARD", "POINTS", "COINS", "MIXED"}
|
||||||
for _, validType := range validTypes {
|
for _, validType := range validTypes {
|
||||||
if campaignType == validType {
|
if campaignType == validType {
|
||||||
return nil
|
return nil
|
||||||
@@ -335,7 +335,7 @@ func (s *campaignService) validateCampaignRules(rules []contract.CampaignRuleStr
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Validate reward value based on reward type
|
// Validate reward value based on reward type
|
||||||
if rule.RewardType == "POINTS" || rule.RewardType == "COINS" || rule.RewardType == "TOKENS" {
|
if rule.RewardType == "POINTS" || rule.RewardType == "COINS" {
|
||||||
if rule.RewardValue == nil || *rule.RewardValue <= 0 {
|
if rule.RewardValue == nil || *rule.RewardValue <= 0 {
|
||||||
return fmt.Errorf("reward value must be positive for %s type in rule %d", rule.RewardType, i+1)
|
return fmt.Errorf("reward value must be positive for %s type in rule %d", rule.RewardType, i+1)
|
||||||
}
|
}
|
||||||
@@ -365,7 +365,7 @@ func (s *campaignService) validateRuleType(ruleType string) error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (s *campaignService) validateRewardType(rewardType string) error {
|
func (s *campaignService) validateRewardType(rewardType string) error {
|
||||||
validTypes := []string{"POINTS", "COINS", "TOKENS", "REWARD"}
|
validTypes := []string{"POINTS", "COINS", "REWARD"}
|
||||||
for _, validType := range validTypes {
|
for _, validType := range validTypes {
|
||||||
if rewardType == validType {
|
if rewardType == validType {
|
||||||
return nil
|
return nil
|
||||||
|
|||||||
@@ -0,0 +1,57 @@
|
|||||||
|
package service
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
|
||||||
|
"apskel-pos-be/internal/constants"
|
||||||
|
"apskel-pos-be/internal/contract"
|
||||||
|
"apskel-pos-be/internal/models"
|
||||||
|
"apskel-pos-be/internal/processor"
|
||||||
|
"apskel-pos-be/internal/repository"
|
||||||
|
)
|
||||||
|
|
||||||
|
// CustomerOrderService serves the customer app's order history.
|
||||||
|
type CustomerOrderService interface {
|
||||||
|
List(ctx context.Context, customerID uuid.UUID, query models.ListCustomerOrdersQuery) *contract.Response
|
||||||
|
Detail(ctx context.Context, customerID, orderID uuid.UUID) *contract.Response
|
||||||
|
}
|
||||||
|
|
||||||
|
type CustomerOrderServiceImpl struct {
|
||||||
|
orders *processor.CustomerOrderProcessor
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewCustomerOrderService(orders *processor.CustomerOrderProcessor) *CustomerOrderServiceImpl {
|
||||||
|
return &CustomerOrderServiceImpl{orders: orders}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *CustomerOrderServiceImpl) List(ctx context.Context, customerID uuid.UUID, query models.ListCustomerOrdersQuery) *contract.Response {
|
||||||
|
orders, err := s.orders.List(ctx, customerID, query)
|
||||||
|
if err != nil {
|
||||||
|
return customerOrderErrorResponse(err)
|
||||||
|
}
|
||||||
|
return contract.BuildSuccessResponse(orders)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *CustomerOrderServiceImpl) Detail(ctx context.Context, customerID, orderID uuid.UUID) *contract.Response {
|
||||||
|
order, err := s.orders.Detail(ctx, customerID, orderID)
|
||||||
|
if err != nil {
|
||||||
|
return customerOrderErrorResponse(err)
|
||||||
|
}
|
||||||
|
return contract.BuildSuccessResponse(order)
|
||||||
|
}
|
||||||
|
|
||||||
|
func customerOrderErrorResponse(err error) *contract.Response {
|
||||||
|
code := constants.InternalServerErrorCode
|
||||||
|
switch {
|
||||||
|
case errors.Is(err, repository.ErrCustomerOrderNotFound):
|
||||||
|
code = constants.NotFoundErrorCode
|
||||||
|
case errors.Is(err, processor.ErrInvalidWalletQuery):
|
||||||
|
code = constants.ValidationErrorCode
|
||||||
|
}
|
||||||
|
return contract.BuildErrorResponse([]*contract.ResponseError{
|
||||||
|
contract.NewResponseError(code, constants.RequestEntity, err.Error()),
|
||||||
|
})
|
||||||
|
}
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
package service
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
|
||||||
|
"apskel-pos-be/internal/constants"
|
||||||
|
"apskel-pos-be/internal/contract"
|
||||||
|
"apskel-pos-be/internal/processor"
|
||||||
|
"apskel-pos-be/internal/repository"
|
||||||
|
)
|
||||||
|
|
||||||
|
// CustomerOutletService serves the outlets list of the customer app.
|
||||||
|
type CustomerOutletService interface {
|
||||||
|
List(ctx context.Context, customerID uuid.UUID) *contract.Response
|
||||||
|
}
|
||||||
|
|
||||||
|
type CustomerOutletServiceImpl struct {
|
||||||
|
outlets *processor.CustomerOutletProcessor
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewCustomerOutletService(outlets *processor.CustomerOutletProcessor) *CustomerOutletServiceImpl {
|
||||||
|
return &CustomerOutletServiceImpl{outlets: outlets}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *CustomerOutletServiceImpl) List(ctx context.Context, customerID uuid.UUID) *contract.Response {
|
||||||
|
outlets, err := s.outlets.List(ctx, customerID)
|
||||||
|
if err != nil {
|
||||||
|
code := constants.InternalServerErrorCode
|
||||||
|
if errors.Is(err, repository.ErrWalletNotFound) {
|
||||||
|
code = constants.NotFoundErrorCode
|
||||||
|
}
|
||||||
|
return contract.BuildErrorResponse([]*contract.ResponseError{
|
||||||
|
contract.NewResponseError(code, constants.RequestEntity, err.Error()),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
return contract.BuildSuccessResponse(outlets)
|
||||||
|
}
|
||||||
@@ -10,7 +10,6 @@ import (
|
|||||||
|
|
||||||
type CustomerPointsService interface {
|
type CustomerPointsService interface {
|
||||||
GetCustomerPoints(ctx context.Context, customerID string) (*models.GetCustomerPointsResponse, error)
|
GetCustomerPoints(ctx context.Context, customerID string) (*models.GetCustomerPointsResponse, error)
|
||||||
GetCustomerTokens(ctx context.Context, customerID string) (*models.GetCustomerTokensResponse, error)
|
|
||||||
GetCustomerWallet(ctx context.Context, customerID string) (*models.GetCustomerWalletResponse, error)
|
GetCustomerWallet(ctx context.Context, customerID string) (*models.GetCustomerWalletResponse, error)
|
||||||
GetCustomerWalletTransactions(ctx context.Context, customerID string, query models.ListCustomerWalletTransactionsQuery) (*models.PaginatedResponse[models.CustomerWalletTransaction], error)
|
GetCustomerWalletTransactions(ctx context.Context, customerID string, query models.ListCustomerWalletTransactionsQuery) (*models.PaginatedResponse[models.CustomerWalletTransaction], error)
|
||||||
GetCustomerWalletExpiring(ctx context.Context, customerID string) (*models.CustomerWalletExpiringList, error)
|
GetCustomerWalletExpiring(ctx context.Context, customerID string) (*models.CustomerWalletExpiringList, error)
|
||||||
@@ -41,19 +40,6 @@ func (s *customerPointsService) GetCustomerPoints(ctx context.Context, customerI
|
|||||||
return response, nil
|
return response, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *customerPointsService) GetCustomerTokens(ctx context.Context, customerID string) (*models.GetCustomerTokensResponse, error) {
|
|
||||||
if customerID == "" {
|
|
||||||
return nil, fmt.Errorf("customer ID is required")
|
|
||||||
}
|
|
||||||
|
|
||||||
response, err := s.customerPointsProcessor.GetCustomerTotalTokensAPI(ctx, customerID)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("failed to get customer tokens: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
return response, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *customerPointsService) GetCustomerWallet(ctx context.Context, customerID string) (*models.GetCustomerWalletResponse, error) {
|
func (s *customerPointsService) GetCustomerWallet(ctx context.Context, customerID string) (*models.GetCustomerWalletResponse, error) {
|
||||||
if customerID == "" {
|
if customerID == "" {
|
||||||
return nil, fmt.Errorf("customer ID is required")
|
return nil, fmt.Errorf("customer ID is required")
|
||||||
|
|||||||
@@ -276,7 +276,6 @@ func GamePlayModelToResponse(model *models.GamePlayResponse) *contract.GamePlayR
|
|||||||
CustomerID: model.CustomerID,
|
CustomerID: model.CustomerID,
|
||||||
PrizeID: model.PrizeID,
|
PrizeID: model.PrizeID,
|
||||||
CoinsUsed: model.CoinsUsed,
|
CoinsUsed: model.CoinsUsed,
|
||||||
TokenUsed: model.CoinsUsed,
|
|
||||||
RandomSeed: model.RandomSeed,
|
RandomSeed: model.RandomSeed,
|
||||||
CreatedAt: model.CreatedAt,
|
CreatedAt: model.CreatedAt,
|
||||||
Game: game,
|
Game: game,
|
||||||
@@ -306,10 +305,9 @@ func PlayGameModelToResponse(model *models.PlayGameResponse) *contract.PlayGameR
|
|||||||
}
|
}
|
||||||
|
|
||||||
return &contract.PlayGameResponse{
|
return &contract.PlayGameResponse{
|
||||||
GamePlay: gamePlayValue,
|
GamePlay: gamePlayValue,
|
||||||
PrizeWon: prizeWon,
|
PrizeWon: prizeWon,
|
||||||
CoinsRemaining: model.CoinsRemaining,
|
CoinsRemaining: model.CoinsRemaining,
|
||||||
TokensRemaining: model.CoinsRemaining,
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -254,7 +254,7 @@ func (v *CampaignValidatorImpl) ValidateDeleteCampaignRuleRequest(req *contract.
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (v *CampaignValidatorImpl) isValidCampaignType(campaignType string) bool {
|
func (v *CampaignValidatorImpl) isValidCampaignType(campaignType string) bool {
|
||||||
validTypes := []string{"REWARD", "POINTS", "COINS", "TOKENS", "MIXED"}
|
validTypes := []string{"REWARD", "POINTS", "COINS", "MIXED"}
|
||||||
return contains(validTypes, campaignType)
|
return contains(validTypes, campaignType)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -264,7 +264,7 @@ func (v *CampaignValidatorImpl) isValidRuleType(ruleType string) bool {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (v *CampaignValidatorImpl) isValidRewardType(rewardType string) bool {
|
func (v *CampaignValidatorImpl) isValidRewardType(rewardType string) bool {
|
||||||
validTypes := []string{"POINTS", "COINS", "TOKENS", "REWARD"}
|
validTypes := []string{"POINTS", "COINS", "REWARD"}
|
||||||
return contains(validTypes, rewardType)
|
return contains(validTypes, rewardType)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -297,7 +297,7 @@ func (v *CampaignValidatorImpl) validateCampaignRule(rule *contract.CampaignRule
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Validate reward value based on reward type
|
// Validate reward value based on reward type
|
||||||
if rule.RewardType == "POINTS" || rule.RewardType == "COINS" || rule.RewardType == "TOKENS" {
|
if rule.RewardType == "POINTS" || rule.RewardType == "COINS" {
|
||||||
if rule.RewardValue == nil || *rule.RewardValue <= 0 {
|
if rule.RewardValue == nil || *rule.RewardValue <= 0 {
|
||||||
return errors.New("reward value must be positive for " + rule.RewardType + " type in rule " + string(rune(ruleNumber)))
|
return errors.New("reward value must be positive for " + rule.RewardType + " type in rule " + string(rune(ruleNumber)))
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,6 +5,8 @@ import (
|
|||||||
"regexp"
|
"regexp"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
|
||||||
"apskel-pos-be/internal/constants"
|
"apskel-pos-be/internal/constants"
|
||||||
"apskel-pos-be/internal/contract"
|
"apskel-pos-be/internal/contract"
|
||||||
)
|
)
|
||||||
@@ -68,6 +70,13 @@ func (v *CustomerAuthValidatorImpl) ValidateRegisterStartRequest(req *contract.R
|
|||||||
return errors.New("name cannot exceed 100 characters"), constants.ValidationErrorCode
|
return errors.New("name cannot exceed 100 characters"), constants.ValidationErrorCode
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Validate organization
|
||||||
|
if orgID := strings.TrimSpace(req.OrganizationID); orgID != "" {
|
||||||
|
if _, err := uuid.Parse(orgID); err != nil {
|
||||||
|
return errors.New("organization_id must be a valid UUID"), constants.ValidationErrorCode
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// Validate birth date
|
// Validate birth date
|
||||||
if strings.TrimSpace(req.BirthDate) == "" {
|
if strings.TrimSpace(req.BirthDate) == "" {
|
||||||
return errors.New("birth date is required"), constants.ValidationErrorCode
|
return errors.New("birth date is required"), constants.ValidationErrorCode
|
||||||
|
|||||||
Reference in New Issue
Block a user