Compare commits
12
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
117e3529aa | ||
|
|
b59b7b4ddd | ||
|
|
fbe7e97dc7 | ||
|
|
b372821b23 | ||
|
|
d3e3ea6b08 | ||
|
|
79226bd891 | ||
|
|
306eabb1d9 | ||
|
|
f16a5da951 | ||
|
|
a24d5f0561 | ||
|
|
c1ec6a3dfd | ||
|
|
8bf2fe5585 | ||
|
|
a3cb7dd5fd |
@@ -41,6 +41,11 @@ Semua endpoint EnakPoint (`POINT`, bisa bayar order) dan EnakCoin (`COIN`, untuk
|
||||
| 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
|
||||
|
||||
@@ -318,13 +323,13 @@ Pada kedua `PUT` setting, field yang tidak dikirim tetap memakai nilai sekarang;
|
||||
|
||||
```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": { "enabled": true, "earn_mode": "PER_AMOUNT", "earn_per_amount": 100, "earn_value": 1, "earn_percent": 1, "min_order_amount": 0, "max_per_order": null },
|
||||
"coin": { "enabled": true, "earn_mode": "PER_AMOUNT", "earn_per_amount": 25000, "earn_value": 1, "earn_percent": 1, "min_order_amount": 0, "max_per_order": null },
|
||||
"point_payment": { "accept_payment": true, "min_payment_points": 1, "max_payment_percent": 100 }
|
||||
}
|
||||
```
|
||||
|
||||
Response menambahkan `outlet_id`, `point_value`, `point_cashback_percent` (default di atas = 1%), dan `changes` pada PUT. Validasi: `earn_per_amount > 0`, `earn_value ≥ 0`, `max_payment_percent` 0–100.
|
||||
Response menambahkan `outlet_id`, `point_value`, `point_cashback_percent` (default di atas = 1%), dan `changes` pada PUT. `earn_mode` adalah `PER_AMOUNT` (setiap `earn_per_amount` rupiah mendapat `earn_value`) atau `PERCENTAGE` (`earn_percent` persen dari basis). Validasi: `earn_per_amount > 0`, `earn_value ≥ 0`, `earn_percent` 0–100 dengan maks. 2 angka desimal, `max_payment_percent` 0–100.
|
||||
|
||||
### /marketing/loyalty-settings
|
||||
|
||||
|
||||
@@ -32,8 +32,8 @@ Tiap outlet mengatur sendiri berapa EnakPoint dan EnakCoin yang didapat dari ord
|
||||
|
||||
```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": { "enabled": true, "earn_mode": "PER_AMOUNT", "earn_per_amount": 100, "earn_value": 1, "earn_percent": 1, "min_order_amount": 0, "max_per_order": null },
|
||||
"coin": { "enabled": true, "earn_mode": "PER_AMOUNT", "earn_per_amount": 25000, "earn_value": 1, "earn_percent": 1, "min_order_amount": 0, "max_per_order": null },
|
||||
"point_payment": { "accept_payment": true, "min_payment_points": 1, "max_payment_percent": 100 }
|
||||
}
|
||||
```
|
||||
@@ -41,15 +41,19 @@ Tiap outlet mengatur sendiri berapa EnakPoint dan EnakCoin yang didapat dari ord
|
||||
| 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 |
|
||||
| `earn_mode` | Cara hitung: per nominal / persentase | pilihan `PER_AMOUNT` / `PERCENTAGE` | `PER_AMOUNT` | salah satu dari keduanya |
|
||||
| `earn_per_amount` | Setiap belanja Rp … (mode `PER_AMOUNT`) | Rp | 100 (point), 25.000 (coin) | > 0 |
|
||||
| `earn_value` | … mendapat (mode `PER_AMOUNT`) | angka | 1 | ≥ 0 |
|
||||
| `earn_percent` | … % dari belanja (mode `PERCENTAGE`) | %, boleh desimal | 1 | 0–100, maks. 2 angka desimal |
|
||||
| `min_order_amount` | Minimal belanja | Rp | 0 | ≥ 0 |
|
||||
| `max_per_order` | Maksimal per order | angka, boleh kosong | kosong = tanpa batas | ≥ 0 |
|
||||
| `point_payment.accept_payment` | Terima pembayaran EnakPoint | toggle | mati | – |
|
||||
| `min_payment_points` | Minimal EnakPoint per pembayaran | angka | 1 | ≥ 1 |
|
||||
| `max_payment_percent` | Maksimal porsi order dibayar EnakPoint | % | 100 | 0–100 |
|
||||
|
||||
**Cashback efektif.** Response membawa `point_cashback_percent` dan `point_value`. Tampilkan persentase di samping field earning EnakPoint, mis. "setara cashback 1%", dan hitung ulang di sisi klien saat owner mengetik: `earn_value × point_value ÷ earn_per_amount × 100`. Tujuannya agar owner tidak salah membaca skala (1 per Rp 100 bukan 1 per Rp 1).
|
||||
**Cashback efektif.** Response membawa `point_cashback_percent` dan `point_value`. Tampilkan persentase di samping field earning EnakPoint, mis. "setara cashback 1%", dan hitung ulang di sisi klien saat owner mengetik: `earn_value × point_value ÷ earn_per_amount × 100`, atau pada mode `PERCENTAGE`: `earn_percent × point_value`. Tujuannya agar owner tidak salah membaca skala (1 per Rp 100 bukan 1 per Rp 1).
|
||||
|
||||
**Mode earning.** Tampilkan hanya field mode yang dipilih (`earn_per_amount` + `earn_value`, atau `earn_percent`). Field mode lain tetap tersimpan di server, jadi tidak perlu dikosongkan saat owner berpindah mode. Pada mode `PERCENTAGE` jumlah yang didapat adalah `floor(basis × earn_percent ÷ 100)`, mis. 2,5% dari Rp 87.500 = 2.187 EnakPoint.
|
||||
|
||||
**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.
|
||||
|
||||
|
||||
@@ -516,15 +516,16 @@ Semua endpoint di bagian ini butuh login user dengan role Admin atau Manager.
|
||||
|
||||
```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": { "enabled": true, "earn_mode": "PER_AMOUNT", "earn_per_amount": 100, "earn_value": 1, "earn_percent": 1, "min_order_amount": 0, "max_per_order": null },
|
||||
"coin": { "enabled": true, "earn_mode": "PER_AMOUNT", "earn_per_amount": 25000, "earn_value": 1, "earn_percent": 1, "min_order_amount": 0, "max_per_order": null },
|
||||
"point_payment": { "accept_payment": true, "min_payment_points": 1, "max_payment_percent": 100 }
|
||||
}
|
||||
```
|
||||
|
||||
Field yang tidak dikirim di `PUT` tetap memakai nilai sekarang. Response menambahkan
|
||||
`point_value` organisasi dan `point_cashback_percent`
|
||||
(`earn_value × point_value / earn_per_amount × 100`). **Tampilkan persentase ini di
|
||||
(`earn_value × point_value / earn_per_amount × 100`, atau `earn_percent × point_value`
|
||||
pada `earn_mode` `PERCENTAGE`). **Tampilkan persentase ini di
|
||||
samping setting** supaya owner tidak salah membaca skala: default di atas setara
|
||||
cashback 1%.
|
||||
|
||||
|
||||
@@ -0,0 +1,289 @@
|
||||
# Migrasi profit sharing
|
||||
|
||||
4 Oktober 2026
|
||||
|
||||
## Ringkasan
|
||||
|
||||
Ada tiga perubahan di backend:
|
||||
|
||||
1. **Parent category bisa ditandai bukan team.** Kategori punya field baru `is_team`. Parent category dengan `is_team: false` tidak bisa dipilih sebagai team di purchase order dan cash advance, dan tidak ikut laporan profit sharing.
|
||||
2. **Endpoint laporan pindah path.** `/api/v1/analytics/parent-categories` menjadi `/api/v1/analytics/profit-sharing`.
|
||||
3. **Pembagian revenue tinggal dua porsi.** Porsi purchase (60%) dihapus. Revenue sekarang dibagi ke owner (SDL) dan team, dengan porsi team = 100% − fee owner.
|
||||
|
||||
Nomor 2 dan 3 adalah breaking change. Setelah backend baru dirilis, client yang masih memanggil path lama mendapat 404, dan `limit_purchase` serta `percentages.purchase` tidak ada lagi di response. Karena itu client harus diupdate lebih dulu, lihat [Urutan rilis](#database-dan-urutan-rilis).
|
||||
|
||||
Yang perlu bertindak, di dashboard maupun app mobile, mana pun yang punya layarnya:
|
||||
|
||||
- **Form kategori**: tambah toggle team untuk parent category.
|
||||
- **Laporan profit sharing**: ganti path, hapus porsi purchase, tampilkan dua porsi.
|
||||
- **Form purchase order dan cash advance**: picker team tidak perlu diubah, tapi form edit perlu menyesuaikan, lihat [Purchase order dan cash advance](#purchase-order-dan-cash-advance).
|
||||
|
||||
## Kategori: field `is_team`
|
||||
|
||||
### Response
|
||||
|
||||
Semua response kategori membawa `is_team` (boolean, tidak pernah `null`): `POST /api/v1/categories`, `PUT /api/v1/categories/:id`, `GET /api/v1/categories`, dan `GET /api/v1/categories/:id`.
|
||||
|
||||
```json
|
||||
{
|
||||
"id": "<uuid>",
|
||||
"name": "Merchandise",
|
||||
"parent_id": null,
|
||||
"owner_fee_percent": null,
|
||||
"is_team": false
|
||||
}
|
||||
```
|
||||
|
||||
### Request
|
||||
|
||||
`POST /api/v1/categories` dan `PUT /api/v1/categories/:id` menerima `is_team`.
|
||||
|
||||
```json
|
||||
{
|
||||
"name": "Merchandise",
|
||||
"is_team": false
|
||||
}
|
||||
```
|
||||
|
||||
| Request | `is_team` yang dikirim | Hasil |
|
||||
| --- | --- | --- |
|
||||
| Create | tidak dikirim | `true` |
|
||||
| Create | `false` | `false` |
|
||||
| Update | tidak dikirim atau `null` | tidak berubah |
|
||||
| Update | `true` atau `false` | diganti |
|
||||
|
||||
Update yang hanya berisi `is_team` diterima.
|
||||
|
||||
Aturan nilainya:
|
||||
|
||||
- `is_team` hanya berpengaruh di parent category, yaitu kategori dengan `parent_id: null`. Di sub-category nilainya disimpan tapi tidak dipakai, jadi tampilkan toggle hanya untuk parent category.
|
||||
- Semua kategori yang sudah ada sebelum rilis bernilai `true`. Tidak ada yang berubah sampai admin mematikannya.
|
||||
- Flag dibaca saat request, bukan saat transaksi. Kalau parent category dimatikan, penjualannya di periode lampau juga hilang dari laporan profit sharing. Kalau dinyalakan lagi, semuanya muncul kembali.
|
||||
|
||||
### Efek `is_team: false`
|
||||
|
||||
| Endpoint | Efek |
|
||||
| --- | --- |
|
||||
| `GET /api/v1/purchase-orders/teams`, `GET /api/v1/cash-advances/teams` | Kategori tidak muncul. Pusat tetap ada. |
|
||||
| Create dan update purchase order dan cash advance | `team_scope: "category"` dengan `team_category_id` kategori ini ditolak. |
|
||||
| `GET /api/v1/analytics/profit-sharing` | Kategori tidak muncul di `data`, dan revenue-nya tidak dihitung di `budget`. |
|
||||
| `GET /api/v1/analytics/profit-sharing/:parent_category_id` | Ditolak. |
|
||||
|
||||
Data yang sudah ada tidak diubah. Purchase order dan cash advance yang sudah tercatat ke kategori itu tetap menyimpan team-nya. Laporan purchasing (`GET /api/v1/analytics/purchasing`) masih menampilkannya di `team_data`, dan filter `team=<category_id>` tetap bisa dipakai.
|
||||
|
||||
Laporan lain yang tidak menyaring `is_team`, misalnya `GET /api/v1/analytics/categories`, tetap menampilkan penjualan kategori itu.
|
||||
|
||||
## Purchase order dan cash advance
|
||||
|
||||
Picker team sudah mengambil dari `GET /api/v1/purchase-orders/teams` dan `GET /api/v1/cash-advances/teams`, jadi kategori non-team otomatis tidak muncul tanpa perubahan di client.
|
||||
|
||||
Yang perlu diubah ada di form edit. Purchase order atau cash advance lama bisa tercatat ke kategori yang sekarang sudah non-team. Kalau form edit mengirim ulang `team_scope` dan `team_category_id` yang sama, request ditolak, walaupun user tidak mengubah team-nya.
|
||||
|
||||
1. Kirim `team_scope` dan `team_category_id` hanya kalau user mengganti team. Kalau `team_scope` tidak dikirim, team yang tersimpan tidak berubah.
|
||||
2. Kalau team yang tersimpan tidak ada di daftar `/teams`, tampilkan namanya dari field `team` di response apa adanya, dan jangan memilihkan team lain secara otomatis.
|
||||
|
||||
Contoh error saat team ditolak, dengan HTTP status 500:
|
||||
|
||||
```json
|
||||
{
|
||||
"success": false,
|
||||
"data": null,
|
||||
"errors": [
|
||||
{
|
||||
"code": "900",
|
||||
"entity": "purchase_order_service",
|
||||
"cause": "category Merchandise is not a team"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
Untuk cash advance, `entity` bernilai `cash_advance_service`. Cocokkan dengan teks `is not a team` di `cause` kalau perlu menampilkan pesan khusus.
|
||||
|
||||
## Laporan profit sharing
|
||||
|
||||
### Path baru
|
||||
|
||||
| Lama | Baru |
|
||||
| --- | --- |
|
||||
| `GET /api/v1/analytics/parent-categories` | `GET /api/v1/analytics/profit-sharing` |
|
||||
| `GET /api/v1/analytics/parent-categories/:parent_category_id` | `GET /api/v1/analytics/profit-sharing/:parent_category_id` |
|
||||
|
||||
Query parameter dan role tidak berubah:
|
||||
|
||||
- `date_from` dan `date_to` wajib, dengan format `DD-MM-YYYY`, misalnya `28-09-2026`.
|
||||
- `outlet_id` opsional.
|
||||
- Hanya bisa diakses superadmin, admin, manager, owner, dan purchasing.
|
||||
|
||||
Path lama sudah tidak ada dan mengembalikan 404.
|
||||
|
||||
### Pembagian revenue
|
||||
|
||||
Revenue tiap parent category yang team dibagi dua:
|
||||
|
||||
- **SDL (fee owner)** = revenue × `owner_fee_percent` / 100. Default-nya 20%, dan bisa diganti per parent category lewat `owner_fee_percent` di kategori.
|
||||
- **Team** = revenue − SDL.
|
||||
|
||||
Contoh dengan tiga parent category dalam satu minggu:
|
||||
|
||||
| Parent category | `is_team` | Fee owner | Revenue | SDL | Team |
|
||||
| --- | --- | --- | --- | --- | --- |
|
||||
| Food | `true` | 20% (default) | 1.000.000 | 200.000 | 800.000 |
|
||||
| Drink | `true` | 35% | 2.000.000 | 700.000 | 1.300.000 |
|
||||
| Merchandise | `false` | - | 500.000 | tidak dihitung | tidak dihitung |
|
||||
| **Budget minggu ini** | | | **3.000.000** | **900.000** | **2.100.000** |
|
||||
|
||||
### Perubahan field
|
||||
|
||||
| Field | Sebelum | Sesudah |
|
||||
| --- | --- | --- |
|
||||
| `data[]` | semua parent category | hanya parent category team |
|
||||
| `budget.percentages.purchase` | `60` | dihapus |
|
||||
| `budget.percentages.owner` | `20`, atau fee parent itu di endpoint detail | tidak berubah |
|
||||
| `budget.percentages.team` | `20` | `100 − owner`: `80` di list, `100 − fee parent` di detail |
|
||||
| `limit_purchase` di `budget.total`, `budget.weekly[]`, `budget.monthly[]` | 60% revenue | dihapus |
|
||||
| `limit_team` di tempat yang sama | 20% revenue | `revenue − sdl` |
|
||||
| `revenue` dan `sdl` di `budget` | semua parent category | hanya parent category team |
|
||||
|
||||
Di endpoint list, `budget.percentages` selalu berisi default `20` dan `80`, walaupun ada parent dengan fee berbeda. Angka `sdl` dan `limit_team` dihitung per parent dengan fee masing-masing, jadi `limit_team / revenue` bisa tidak persis 80%. Tampilkan angka rupiah dari response, jangan dihitung ulang dari persentase.
|
||||
|
||||
Baris di `data[]` membawa `sdl` tapi tidak membawa porsi team. Kalau porsi team per parent perlu ditampilkan, hitung dari `total_revenue − sdl`.
|
||||
|
||||
Contoh response list, dipotong:
|
||||
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"data": {
|
||||
"date_from": "2026-09-28T00:00:00+07:00",
|
||||
"date_to": "2026-10-04T23:59:59.999999999+07:00",
|
||||
"data": [
|
||||
{
|
||||
"parent_category_id": "<uuid>",
|
||||
"parent_category_name": "Drink",
|
||||
"owner_fee_percent": 35,
|
||||
"sdl": 700000,
|
||||
"total_revenue": 2000000
|
||||
},
|
||||
{
|
||||
"parent_category_id": "<uuid>",
|
||||
"parent_category_name": "Food",
|
||||
"owner_fee_percent": 20,
|
||||
"sdl": 200000,
|
||||
"total_revenue": 1000000
|
||||
}
|
||||
],
|
||||
"budget": {
|
||||
"percentages": { "owner": 20, "team": 80 },
|
||||
"cut_off_from": "2026-09-28T00:00:00+07:00",
|
||||
"cut_off_to": "2026-10-04T23:59:59.999999999+07:00",
|
||||
"total": {
|
||||
"period_start": "2026-09-28T00:00:00+07:00",
|
||||
"period_end": "2026-10-04T23:59:59.999999999+07:00",
|
||||
"revenue": 3000000,
|
||||
"order_count": 4,
|
||||
"sdl": 900000,
|
||||
"limit_team": 2100000
|
||||
},
|
||||
"weekly": [
|
||||
{
|
||||
"period_start": "2026-09-28T00:00:00+07:00",
|
||||
"period_end": "2026-10-04T23:59:59.999999999+07:00",
|
||||
"revenue": 3000000,
|
||||
"order_count": 4,
|
||||
"sdl": 900000,
|
||||
"limit_team": 2100000
|
||||
}
|
||||
],
|
||||
"monthly": [
|
||||
{
|
||||
"month": "2026-09",
|
||||
"week_count": 1,
|
||||
"period_start": "2026-09-28T00:00:00+07:00",
|
||||
"period_end": "2026-10-04T23:59:59.999999999+07:00",
|
||||
"revenue": 3000000,
|
||||
"order_count": 4,
|
||||
"sdl": 900000,
|
||||
"limit_team": 2100000
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"errors": null
|
||||
}
|
||||
```
|
||||
|
||||
Di endpoint detail, `budget` bentuknya sama, tapi `percentages` memakai fee parent itu, misalnya `{ "owner": 35, "team": 65 }` untuk Drink.
|
||||
|
||||
### Detail kategori non-team
|
||||
|
||||
Detail untuk parent category non-team ditolak dengan HTTP status 500:
|
||||
|
||||
```json
|
||||
{
|
||||
"success": false,
|
||||
"data": null,
|
||||
"errors": [
|
||||
{
|
||||
"code": "internal_error",
|
||||
"entity": "AnalyticsHandler::GetParentCategoryAnalyticsDetail",
|
||||
"cause": "failed to get parent category analytics detail: failed to get parent category analytics detail: category Merchandise is not a team"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
Ini bisa terjadi kalau user membuka link lama atau bookmark ke parent yang baru dimatikan. Cocokkan dengan teks `is not a team` di `cause`, lalu arahkan user kembali ke list.
|
||||
|
||||
## Migrasi client
|
||||
|
||||
### Laporan profit sharing
|
||||
|
||||
1. Ganti path ke `/api/v1/analytics/profit-sharing`. Selama backend lama masih jalan, path baru mengembalikan 404. Kalau dapat 404, panggil path lama `/api/v1/analytics/parent-categories`, supaya client baru bisa dirilis sebelum backend.
|
||||
2. Hapus tampilan limit purchase dan persentase purchase. Jangan menganggap `limit_purchase` atau `percentages.purchase` selalu ada.
|
||||
3. Tampilkan dua porsi dengan label "SDL / Fee owner" dan "Team", ambil angkanya dari `sdl` dan `limit_team`.
|
||||
4. Kalau detail ditolak dengan `is not a team`, arahkan kembali ke list.
|
||||
|
||||
Selama fallback ke backend lama, `limit_team` masih berisi 20% revenue. Angkanya baru jadi `revenue − sdl` setelah backend baru dirilis.
|
||||
|
||||
### Form kategori
|
||||
|
||||
1. Tambah toggle `is_team` untuk parent category, misalnya berlabel "Ikut profit sharing (team)". Untuk kategori baru, toggle menyala secara default.
|
||||
2. Saat membuka form edit, isi toggle dari `is_team`. Selama backend lama masih jalan, field ini tidak ada di response, jadi anggap `true`.
|
||||
3. Saat admin mematikan toggle, tampilkan konfirmasi bahwa kategori itu tidak akan muncul di pilihan team dan di laporan profit sharing, termasuk untuk periode lampau.
|
||||
4. Di daftar kategori, beri penanda untuk parent category dengan `is_team: false`.
|
||||
|
||||
Backend lama mengabaikan `is_team` di request, jadi toggle bisa dirilis lebih dulu, tapi belum berpengaruh sampai backend baru jalan. Pengecualiannya update yang hanya berisi `is_team`: backend lama menolaknya dengan error code `303` dan pesan `at least one field must be provided for update`. Selama masa transisi, kirim `is_team` bersama field form lainnya.
|
||||
|
||||
## Database dan urutan rilis
|
||||
|
||||
Migration `000101_add_is_team_to_categories` menambah kolom `categories.is_team` (`BOOLEAN NOT NULL DEFAULT TRUE`). Semua kategori yang ada otomatis bernilai `true`. Migration ini hanya menambah kolom, jadi backend lama tetap jalan normal setelahnya.
|
||||
|
||||
Urutan rilis:
|
||||
|
||||
1. Rilis client baru: path profit sharing dengan fallback ke path lama, tanpa porsi purchase, dan dengan toggle `is_team`. Untuk app mobile, pastikan versi baru sudah dipakai sebagian besar user sebelum langkah 3, karena versi lama yang memanggil `/parent-categories` mendapat 404 setelah itu.
|
||||
2. Jalankan migration `000101`.
|
||||
3. Deploy backend baru.
|
||||
4. Hapus fallback path lama di client.
|
||||
5. Admin mematikan `is_team` di parent category yang bukan team.
|
||||
|
||||
Rollback: deploy backend lama, lalu jalankan down migration yang menghapus kolom `is_team`. Client dengan fallback tetap jalan di backend lama. Nilai `is_team` yang sudah diatur admin hilang saat kolom dihapus.
|
||||
|
||||
## Checklist
|
||||
|
||||
- [ ] Client baru (fallback path, tanpa porsi purchase, toggle `is_team`) dirilis
|
||||
- [ ] Migration `000101` dan backend baru dirilis di staging
|
||||
- [ ] Uji: parent category yang dimatikan hilang dari `/purchase-orders/teams` dan `/cash-advances/teams`
|
||||
- [ ] Uji: purchase order dan cash advance baru dengan kategori itu ditolak, dan edit purchase order lama tanpa mengganti team tetap berhasil
|
||||
- [ ] Uji: kategori itu hilang dari `/analytics/profit-sharing`, dan detailnya ditolak
|
||||
- [ ] Uji: `limit_team = revenue − sdl`, dan `sdl` mengikuti fee masing-masing parent
|
||||
- [ ] Migration `000101` dan backend baru dirilis di production
|
||||
- [ ] Fallback path lama di client dihapus
|
||||
|
||||
## FAQ
|
||||
|
||||
**Kenapa porsi team jadi 100% − fee owner, bukan tetap 20%?** Porsi purchase sudah tidak ada, jadi seluruh revenue dibagi dua. Owner mengambil fee-nya, dan sisanya untuk team. Kalau fee owner sebuah parent dinaikkan, porsi team parent itu turun sebesar yang sama.
|
||||
|
||||
**Apakah sub-category bisa dijadikan non-team sendiri?** Tidak. Team dan profit sharing dihitung per parent category, jadi semua sub-category ikut status parent-nya.
|
||||
|
||||
**Bagaimana dengan kategori top-level yang tidak punya sub-category?** Kategori itu tetap parent category, jadi `is_team` berlaku untuknya.
|
||||
@@ -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.
|
||||
+19
-5
@@ -197,20 +197,28 @@ Disimpan di `outlet_settings` (key–value, sudah ada).
|
||||
| Key | Tipe | Default | Arti |
|
||||
|---|---|---|---|
|
||||
| `loyalty.point.enabled` | bool | `false` | Outlet memberi EnakPoint |
|
||||
| `loyalty.point.earn_per_amount` | int (Rp) | `100` | Setiap kelipatan nominal ini… |
|
||||
| `loyalty.point.earn_mode` | `PER_AMOUNT` / `PERCENTAGE` | `PER_AMOUNT` | Cara menghitung earning |
|
||||
| `loyalty.point.earn_per_amount` | int (Rp) | `100` | `PER_AMOUNT`: setiap kelipatan nominal ini… |
|
||||
| `loyalty.point.earn_value` | int | `1` | …mendapat sekian EnakPoint |
|
||||
| `loyalty.point.earn_percent` | desimal (0–100, maks. 2 angka desimal) | `1` | `PERCENTAGE`: sekian persen dari basis menjadi EnakPoint |
|
||||
| `loyalty.point.min_order_amount` | int (Rp) | `0` | Basis minimal agar dapat EnakPoint |
|
||||
| `loyalty.point.max_per_order` | int, nullable | kosong | Batas atas EnakPoint per order |
|
||||
| `loyalty.coin.enabled` | bool | `false` | Outlet memberi EnakCoin |
|
||||
| `loyalty.coin.earn_mode` | `PER_AMOUNT` / `PERCENTAGE` | `PER_AMOUNT` | |
|
||||
| `loyalty.coin.earn_per_amount` | int (Rp) | `25000` | |
|
||||
| `loyalty.coin.earn_value` | int | `1` | |
|
||||
| `loyalty.coin.earn_percent` | desimal (0–100, maks. 2 angka desimal) | `1` | |
|
||||
| `loyalty.coin.min_order_amount` | int (Rp) | `0` | |
|
||||
| `loyalty.coin.max_per_order` | int, nullable | kosong | |
|
||||
|
||||
Dengan nilai EnakPoint default Rp 1, default earning 1 EnakPoint per Rp 100 setara
|
||||
**cashback 1%**. Dashboard selalu menampilkan persentase cashback efektif di samping
|
||||
setting ini: `earn_value × nilai EnakPoint / earn_per_amount`. Tujuannya supaya owner
|
||||
tidak salah mengira skala.
|
||||
setting ini: `earn_value × nilai EnakPoint / earn_per_amount`, atau pada mode
|
||||
`PERCENTAGE`: `earn_percent × nilai EnakPoint`. Tujuannya supaya owner tidak salah
|
||||
mengira skala.
|
||||
|
||||
Setting mode yang sedang tidak dipakai tetap tersimpan, sehingga berpindah mode tidak
|
||||
menghapus nilai mode sebelumnya.
|
||||
|
||||
**Pembayaran EnakPoint.** Hanya ada untuk EnakPoint, tidak ada padanannya untuk
|
||||
EnakCoin.
|
||||
@@ -226,7 +234,8 @@ EnakCoin.
|
||||
```
|
||||
basis = subtotal − discount_amount − dibayar_dengan_enakpoint
|
||||
jumlah = 0 jika basis < min_order_amount
|
||||
jumlah = floor(basis / earn_per_amount) × earn_value
|
||||
jumlah = floor(basis / earn_per_amount) × earn_value mode PER_AMOUNT
|
||||
jumlah = floor(basis × earn_percent / 100) mode PERCENTAGE
|
||||
jumlah = min(jumlah, max_per_order) jika max_per_order diisi
|
||||
```
|
||||
|
||||
@@ -240,7 +249,12 @@ jumlah = min(jumlah, max_per_order) jika max_per_order diisi
|
||||
EnakPoint** dan **3 EnakCoin**. Jika Rp 20.000 dari order itu dibayar dengan EnakPoint,
|
||||
basisnya menjadi Rp 67.500, sehingga customer mendapat 675 EnakPoint dan 2 EnakCoin.
|
||||
|
||||
Validasi: `earn_per_amount > 0`, `earn_value ≥ 0`, `min_order_amount ≥ 0`,
|
||||
Pada mode `PERCENTAGE`, `earn_percent` adalah persen dari basis yang menjadi
|
||||
**jumlah** EnakPoint/EnakCoin (bukan nilai rupiahnya): 2,5% dari basis Rp 87.500
|
||||
menghasilkan 2.187 EnakPoint.
|
||||
|
||||
Validasi: `earn_per_amount > 0`, `earn_value ≥ 0`, `0 ≤ earn_percent ≤ 100` dengan
|
||||
paling banyak dua angka desimal, `min_order_amount ≥ 0`,
|
||||
`max_per_order ≥ 0`, `0 ≤ max_payment_percent ≤ 100`. Hanya role Admin/Manager yang
|
||||
bisa mengubah.
|
||||
|
||||
|
||||
@@ -165,6 +165,8 @@ func (a *App) Initialize(cfg *config.Config) error {
|
||||
services.customerOrderPaymentService,
|
||||
services.customerWalletService,
|
||||
services.customerDeviceService,
|
||||
services.customerOutletService,
|
||||
services.customerOrderService,
|
||||
a.redisClient,
|
||||
)
|
||||
|
||||
@@ -403,6 +405,8 @@ type processors struct {
|
||||
walletTransferProcessor *processor.WalletTransferProcessor
|
||||
walletTraceProcessor *processor.WalletTraceProcessor
|
||||
customerDeviceProcessor *processor.CustomerDeviceProcessor
|
||||
customerOutletProcessor *processor.CustomerOutletProcessor
|
||||
customerOrderProcessor *processor.CustomerOrderProcessor
|
||||
}
|
||||
|
||||
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,
|
||||
walletTraceProcessor: processor.NewWalletTraceProcessor(repository.NewWalletTraceRepository(a.db)),
|
||||
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),
|
||||
}
|
||||
}
|
||||
@@ -534,6 +540,8 @@ type services struct {
|
||||
customerOrderPaymentService *service.CustomerOrderPaymentServiceImpl
|
||||
customerWalletService *service.CustomerWalletServiceImpl
|
||||
customerDeviceService *service.CustomerDeviceServiceImpl
|
||||
customerOutletService *service.CustomerOutletServiceImpl
|
||||
customerOrderService *service.CustomerOrderServiceImpl
|
||||
}
|
||||
|
||||
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),
|
||||
customerWalletService: service.NewCustomerWalletService(processors.walletExchangeProcessor, processors.walletTransferProcessor),
|
||||
customerDeviceService: service.NewCustomerDeviceService(processors.customerDeviceProcessor),
|
||||
customerOutletService: service.NewCustomerOutletService(processors.customerOutletProcessor),
|
||||
customerOrderService: service.NewCustomerOrderService(processors.customerOrderProcessor),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,9 +1,6 @@
|
||||
package constants
|
||||
|
||||
// Budget allocation of revenue used by the parent category cut-off report.
|
||||
// The three shares are expected to add up to 100.
|
||||
const (
|
||||
BudgetLimitPurchasePercent = 60.0
|
||||
BudgetLimitOwnerPercent = 20.0
|
||||
BudgetLimitTeamPercent = 20.0
|
||||
)
|
||||
// Revenue split used by the profit sharing report: the owner takes its fee as SDL and
|
||||
// the team takes the rest. BudgetLimitOwnerPercent is only the default: a parent
|
||||
// category can override it with categories.owner_fee_percent.
|
||||
const BudgetLimitOwnerPercent = 20.0
|
||||
|
||||
@@ -7,12 +7,16 @@ package constants
|
||||
// Per outlet (F1): what an order earns, and whether EnakPoint can pay.
|
||||
const (
|
||||
LoyaltyPointEnabledKey = "loyalty.point.enabled"
|
||||
LoyaltyPointEarnModeKey = "loyalty.point.earn_mode"
|
||||
LoyaltyPointEarnPercentKey = "loyalty.point.earn_percent"
|
||||
LoyaltyPointEarnPerAmountKey = "loyalty.point.earn_per_amount"
|
||||
LoyaltyPointEarnValueKey = "loyalty.point.earn_value"
|
||||
LoyaltyPointMinOrderAmountKey = "loyalty.point.min_order_amount"
|
||||
LoyaltyPointMaxPerOrderKey = "loyalty.point.max_per_order"
|
||||
|
||||
LoyaltyCoinEnabledKey = "loyalty.coin.enabled"
|
||||
LoyaltyCoinEarnModeKey = "loyalty.coin.earn_mode"
|
||||
LoyaltyCoinEarnPercentKey = "loyalty.coin.earn_percent"
|
||||
LoyaltyCoinEarnPerAmountKey = "loyalty.coin.earn_per_amount"
|
||||
LoyaltyCoinEarnValueKey = "loyalty.coin.earn_value"
|
||||
LoyaltyCoinMinOrderAmountKey = "loyalty.coin.min_order_amount"
|
||||
@@ -47,6 +51,14 @@ const (
|
||||
LoyaltyExpiryGraceMonthsSuffix = "expiry_grace_months"
|
||||
)
|
||||
|
||||
// Modes of loyalty.{point,coin}.earn_mode.
|
||||
const (
|
||||
// earn_value for every earn_per_amount rupiah of the basis.
|
||||
LoyaltyEarnModePerAmount = "PER_AMOUNT"
|
||||
// earn_percent percent of the basis.
|
||||
LoyaltyEarnModePercentage = "PERCENTAGE"
|
||||
)
|
||||
|
||||
// Units of loyalty.{point,coin}.expiry_unit.
|
||||
const (
|
||||
LoyaltyExpiryUnitDay = "DAY"
|
||||
@@ -66,6 +78,8 @@ const (
|
||||
LoyaltyPointEarnPerAmountDefault = int64(100)
|
||||
LoyaltyCoinEarnPerAmountDefault = int64(25000)
|
||||
LoyaltyEarnValueDefault = int64(1)
|
||||
LoyaltyEarnModeDefault = LoyaltyEarnModePerAmount
|
||||
LoyaltyEarnPercentDefault = float64(1)
|
||||
|
||||
LoyaltyMinPaymentPointsDefault = int64(1)
|
||||
LoyaltyMaxPaymentPercentDefault = int64(100)
|
||||
|
||||
@@ -266,16 +266,27 @@ type ProductAnalyticsPerParentCategoryResponse struct {
|
||||
}
|
||||
|
||||
type ProductAnalyticsPerParentCategoryData struct {
|
||||
ParentCategoryID uuid.UUID `json:"parent_category_id"`
|
||||
ParentCategoryName string `json:"parent_category_name"`
|
||||
TotalRevenue float64 `json:"total_revenue"`
|
||||
TotalQuantity int64 `json:"total_quantity"`
|
||||
CategoryCount int64 `json:"category_count"`
|
||||
ProductCount int64 `json:"product_count"`
|
||||
OrderCount int64 `json:"order_count"`
|
||||
TotalStandardHpp float64 `json:"total_standard_hpp"`
|
||||
TotalFifoHpp float64 `json:"total_fifo_hpp"`
|
||||
TotalMovingAverageHpp float64 `json:"total_moving_average_hpp"`
|
||||
ParentCategoryID uuid.UUID `json:"parent_category_id"`
|
||||
ParentCategoryName string `json:"parent_category_name"`
|
||||
OwnerFeePercent float64 `json:"owner_fee_percent"`
|
||||
SDL float64 `json:"sdl"`
|
||||
TotalRevenue float64 `json:"total_revenue"`
|
||||
TotalQuantity int64 `json:"total_quantity"`
|
||||
CategoryCount int64 `json:"category_count"`
|
||||
ProductCount int64 `json:"product_count"`
|
||||
OrderCount int64 `json:"order_count"`
|
||||
TotalStandardHpp float64 `json:"total_standard_hpp"`
|
||||
TotalFifoHpp float64 `json:"total_fifo_hpp"`
|
||||
TotalMovingAverageHpp float64 `json:"total_moving_average_hpp"`
|
||||
TopProduct *ParentCategoryTopProduct `json:"top_product"`
|
||||
}
|
||||
|
||||
// ParentCategoryTopProduct is the best-selling product of a parent category by revenue.
|
||||
type ParentCategoryTopProduct struct {
|
||||
ProductID uuid.UUID `json:"product_id"`
|
||||
ProductName string `json:"product_name"`
|
||||
QuantitySold int64 `json:"quantity_sold"`
|
||||
Revenue float64 `json:"revenue"`
|
||||
}
|
||||
|
||||
// ParentCategoryAnalyticsDetailRequest represents the request for the drill-down of one parent category
|
||||
@@ -302,19 +313,25 @@ type ParentCategoryAnalyticsDetailResponse struct {
|
||||
}
|
||||
|
||||
type ParentCategoryAnalyticsDetailSummary struct {
|
||||
TotalRevenue float64 `json:"total_revenue"`
|
||||
TotalQuantity int64 `json:"total_quantity"`
|
||||
CategoryCount int64 `json:"category_count"`
|
||||
ProductCount int64 `json:"product_count"`
|
||||
OrderCount int64 `json:"order_count"`
|
||||
TotalStandardHpp float64 `json:"total_standard_hpp"`
|
||||
TotalFifoHpp float64 `json:"total_fifo_hpp"`
|
||||
TotalMovingAverageHpp float64 `json:"total_moving_average_hpp"`
|
||||
OwnerFeePercent float64 `json:"owner_fee_percent"`
|
||||
SDL float64 `json:"sdl"`
|
||||
TotalRevenue float64 `json:"total_revenue"`
|
||||
TotalQuantity int64 `json:"total_quantity"`
|
||||
CategoryCount int64 `json:"category_count"`
|
||||
ProductCount int64 `json:"product_count"`
|
||||
OrderCount int64 `json:"order_count"`
|
||||
TotalStandardHpp float64 `json:"total_standard_hpp"`
|
||||
TotalFifoHpp float64 `json:"total_fifo_hpp"`
|
||||
TotalMovingAverageHpp float64 `json:"total_moving_average_hpp"`
|
||||
TopProduct *ParentCategoryTopProduct `json:"top_product"`
|
||||
}
|
||||
|
||||
type ParentCategoryAnalyticsDetailData struct {
|
||||
CategoryID uuid.UUID `json:"category_id"`
|
||||
CategoryName string `json:"category_name"`
|
||||
OwnerFeePercent float64 `json:"owner_fee_percent"`
|
||||
SDL float64 `json:"sdl"`
|
||||
TopProduct *ParentCategoryTopProduct `json:"top_product"`
|
||||
TotalRevenue float64 `json:"total_revenue"`
|
||||
TotalQuantity int64 `json:"total_quantity"`
|
||||
ProductCount int64 `json:"product_count"`
|
||||
@@ -355,19 +372,17 @@ type BudgetCutOff struct {
|
||||
}
|
||||
|
||||
type BudgetPercentages struct {
|
||||
Purchase float64 `json:"purchase"`
|
||||
Owner float64 `json:"owner"`
|
||||
Team float64 `json:"team"`
|
||||
Owner float64 `json:"owner"`
|
||||
Team float64 `json:"team"`
|
||||
}
|
||||
|
||||
type BudgetPeriod struct {
|
||||
PeriodStart time.Time `json:"period_start"`
|
||||
PeriodEnd time.Time `json:"period_end"`
|
||||
Revenue float64 `json:"revenue"`
|
||||
OrderCount int64 `json:"order_count"`
|
||||
LimitPurchase float64 `json:"limit_purchase"`
|
||||
LimitOwner float64 `json:"limit_owner"`
|
||||
LimitTeam float64 `json:"limit_team"`
|
||||
PeriodStart time.Time `json:"period_start"`
|
||||
PeriodEnd time.Time `json:"period_end"`
|
||||
Revenue float64 `json:"revenue"`
|
||||
OrderCount int64 `json:"order_count"`
|
||||
SDL float64 `json:"sdl"`
|
||||
LimitTeam float64 `json:"limit_team"`
|
||||
}
|
||||
|
||||
type BudgetMonthPeriod struct {
|
||||
|
||||
@@ -1,29 +1,81 @@
|
||||
package contract
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
type CreateCategoryRequest struct {
|
||||
Name string `json:"name" validate:"required,min=1,max=255"`
|
||||
Description *string `json:"description,omitempty"`
|
||||
BusinessType *string `json:"business_type,omitempty"`
|
||||
OutletID *uuid.UUID `json:"outlet_id,omitempty"`
|
||||
ParentID *uuid.UUID `json:"parent_id,omitempty"`
|
||||
Order *int `json:"order,omitempty"`
|
||||
Metadata map[string]interface{} `json:"metadata,omitempty"`
|
||||
Name string `json:"name" validate:"required,min=1,max=255"`
|
||||
Description *string `json:"description,omitempty"`
|
||||
BusinessType *string `json:"business_type,omitempty"`
|
||||
OutletID *uuid.UUID `json:"outlet_id,omitempty"`
|
||||
ParentID *uuid.UUID `json:"parent_id,omitempty"`
|
||||
Order *int `json:"order,omitempty"`
|
||||
OwnerFeePercent *float64 `json:"owner_fee_percent,omitempty"`
|
||||
IsTeam *bool `json:"is_team,omitempty"`
|
||||
Metadata map[string]interface{} `json:"metadata,omitempty"`
|
||||
}
|
||||
|
||||
type UpdateCategoryRequest struct {
|
||||
Name *string `json:"name,omitempty" validate:"omitempty,min=1,max=255"`
|
||||
Description *string `json:"description,omitempty"`
|
||||
BusinessType *string `json:"business_type,omitempty"`
|
||||
OutletID *uuid.UUID `json:"outlet_id,omitempty"`
|
||||
ParentID *uuid.UUID `json:"parent_id,omitempty"`
|
||||
Order *int `json:"order,omitempty"`
|
||||
Metadata map[string]interface{} `json:"metadata,omitempty"`
|
||||
Name *string `json:"name,omitempty" validate:"omitempty,min=1,max=255"`
|
||||
Description *string `json:"description,omitempty"`
|
||||
BusinessType *string `json:"business_type,omitempty"`
|
||||
OutletID *uuid.UUID `json:"outlet_id,omitempty"`
|
||||
ParentID *uuid.UUID `json:"parent_id,omitempty"`
|
||||
Order *int `json:"order,omitempty"`
|
||||
OwnerFeePercent *float64 `json:"owner_fee_percent,omitempty"`
|
||||
IsTeam *bool `json:"is_team,omitempty"`
|
||||
Metadata map[string]interface{} `json:"metadata,omitempty"`
|
||||
|
||||
// Set when the field is sent as null (or "" for parent_id), which asks for the
|
||||
// value to be removed. A field that is left out stays unchanged.
|
||||
ClearParentID bool `json:"-"`
|
||||
ClearOwnerFeePercent bool `json:"-"`
|
||||
}
|
||||
|
||||
// UnmarshalJSON tells an explicit null apart from a field that was left out, so a
|
||||
// category can be detached from its parent and an owner fee override can be removed.
|
||||
func (r *UpdateCategoryRequest) UnmarshalJSON(data []byte) error {
|
||||
var raw map[string]json.RawMessage
|
||||
if err := json.Unmarshal(data, &raw); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
isEmpty := func(key string, allowEmptyString bool) bool {
|
||||
value, ok := raw[key]
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
value = bytes.TrimSpace(value)
|
||||
return bytes.Equal(value, []byte("null")) || (allowEmptyString && bytes.Equal(value, []byte(`""`)))
|
||||
}
|
||||
|
||||
clearParentID := isEmpty("parent_id", true)
|
||||
clearOwnerFeePercent := isEmpty("owner_fee_percent", false)
|
||||
if clearParentID {
|
||||
// An empty string is not a valid UUID, so keep it away from the decoder
|
||||
delete(raw, "parent_id")
|
||||
cleaned, err := json.Marshal(raw)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
data = cleaned
|
||||
}
|
||||
|
||||
type plain UpdateCategoryRequest
|
||||
var decoded plain
|
||||
if err := json.Unmarshal(data, &decoded); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
*r = UpdateCategoryRequest(decoded)
|
||||
r.ClearParentID = clearParentID
|
||||
r.ClearOwnerFeePercent = clearOwnerFeePercent
|
||||
return nil
|
||||
}
|
||||
|
||||
type ListCategoriesRequest struct {
|
||||
@@ -39,18 +91,20 @@ type ListCategoriesRequest struct {
|
||||
|
||||
// Category Response DTOs
|
||||
type CategoryResponse struct {
|
||||
ID uuid.UUID `json:"id"`
|
||||
OrganizationID uuid.UUID `json:"organization_id"`
|
||||
OutletID *uuid.UUID `json:"outlet_id"`
|
||||
ParentID *uuid.UUID `json:"parent_id,omitempty"`
|
||||
ParentName *string `json:"parent_name,omitempty"`
|
||||
Name string `json:"name"`
|
||||
Description *string `json:"description"`
|
||||
BusinessType string `json:"business_type"`
|
||||
Order int `json:"order"`
|
||||
Metadata map[string]interface{} `json:"metadata"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
ID uuid.UUID `json:"id"`
|
||||
OrganizationID uuid.UUID `json:"organization_id"`
|
||||
OutletID *uuid.UUID `json:"outlet_id"`
|
||||
ParentID *uuid.UUID `json:"parent_id,omitempty"`
|
||||
ParentName *string `json:"parent_name,omitempty"`
|
||||
Name string `json:"name"`
|
||||
Description *string `json:"description"`
|
||||
BusinessType string `json:"business_type"`
|
||||
Order int `json:"order"`
|
||||
OwnerFeePercent *float64 `json:"owner_fee_percent"`
|
||||
IsTeam bool `json:"is_team"`
|
||||
Metadata map[string]interface{} `json:"metadata"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
type ListCategoriesResponse struct {
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
package contract
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"testing"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestUpdateCategoryRequestTellsNullFromOmitted(t *testing.T) {
|
||||
parentID := uuid.New()
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
body string
|
||||
wantParentID *uuid.UUID
|
||||
wantClear bool
|
||||
wantClearFee bool
|
||||
wantFee *float64
|
||||
wantNameIsSet bool
|
||||
}{
|
||||
{name: "omitted leaves parent unchanged", body: `{"name":"Food"}`, wantNameIsSet: true},
|
||||
{name: "null detaches the parent", body: `{"parent_id":null}`, wantClear: true},
|
||||
{name: "empty string detaches the parent", body: `{"name":"Food","parent_id":""}`, wantClear: true, wantNameIsSet: true},
|
||||
{name: "uuid sets the parent", body: `{"parent_id":"` + parentID.String() + `"}`, wantParentID: &parentID},
|
||||
{name: "null removes the owner fee override", body: `{"owner_fee_percent":null}`, wantClearFee: true},
|
||||
{name: "number sets the owner fee", body: `{"owner_fee_percent":35}`, wantFee: func() *float64 { v := 35.0; return &v }()},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
var req UpdateCategoryRequest
|
||||
require.NoError(t, json.Unmarshal([]byte(tt.body), &req))
|
||||
|
||||
require.Equal(t, tt.wantParentID, req.ParentID)
|
||||
require.Equal(t, tt.wantClear, req.ClearParentID)
|
||||
require.Equal(t, tt.wantClearFee, req.ClearOwnerFeePercent)
|
||||
require.Equal(t, tt.wantFee, req.OwnerFeePercent)
|
||||
require.Equal(t, tt.wantNameIsSet, req.Name != nil)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestUpdateCategoryRequestRejectsInvalidParentID(t *testing.T) {
|
||||
var req UpdateCategoryRequest
|
||||
require.Error(t, json.Unmarshal([]byte(`{"parent_id":"not-a-uuid"}`), &req))
|
||||
}
|
||||
@@ -16,6 +16,10 @@ type RegisterStartRequest struct {
|
||||
PhoneNumber string `json:"phone_number" binding:"required"`
|
||||
Name string `json:"name" 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 {
|
||||
|
||||
@@ -143,16 +143,29 @@ type ProductAnalyticsPerCategory struct {
|
||||
// ProductAnalyticsPerParentCategory rolls the per-category figures up to the
|
||||
// top-level category. A category without a parent is its own group.
|
||||
type ProductAnalyticsPerParentCategory struct {
|
||||
ParentCategoryID uuid.UUID `json:"parent_category_id"`
|
||||
ParentCategoryName string `json:"parent_category_name"`
|
||||
TotalRevenue float64 `json:"total_revenue"`
|
||||
TotalQuantity int64 `json:"total_quantity"`
|
||||
CategoryCount int64 `json:"category_count"`
|
||||
ProductCount int64 `json:"product_count"`
|
||||
OrderCount int64 `json:"order_count"`
|
||||
TotalStandardHpp float64 `json:"total_standard_hpp"`
|
||||
TotalFifoHpp float64 `json:"total_fifo_hpp"`
|
||||
TotalMovingAverageHpp float64 `json:"total_moving_average_hpp"`
|
||||
ParentCategoryID uuid.UUID `json:"parent_category_id"`
|
||||
ParentCategoryName string `json:"parent_category_name"`
|
||||
// OwnerFeePercent is the owner share of this group's revenue, already resolved to the default
|
||||
OwnerFeePercent float64 `json:"owner_fee_percent"`
|
||||
TotalRevenue float64 `json:"total_revenue"`
|
||||
TotalQuantity int64 `json:"total_quantity"`
|
||||
CategoryCount int64 `json:"category_count"`
|
||||
ProductCount int64 `json:"product_count"`
|
||||
OrderCount int64 `json:"order_count"`
|
||||
TotalStandardHpp float64 `json:"total_standard_hpp"`
|
||||
TotalFifoHpp float64 `json:"total_fifo_hpp"`
|
||||
TotalMovingAverageHpp float64 `json:"total_moving_average_hpp"`
|
||||
// TopProduct is filled by a separate query, so it is not a scanned column
|
||||
TopProduct *ParentCategoryTopProduct `gorm:"-" json:"top_product"`
|
||||
}
|
||||
|
||||
// ParentCategoryTopProduct is the best-selling product of a parent category by revenue.
|
||||
type ParentCategoryTopProduct struct {
|
||||
ParentCategoryID uuid.UUID `json:"parent_category_id"`
|
||||
ProductID uuid.UUID `json:"product_id"`
|
||||
ProductName string `json:"product_name"`
|
||||
QuantitySold int64 `json:"quantity_sold"`
|
||||
Revenue float64 `json:"revenue"`
|
||||
}
|
||||
|
||||
// ParentCategoryAnalyticsDetail is the drill-down for a single parent category:
|
||||
@@ -171,6 +184,8 @@ type BudgetCutOffWeek struct {
|
||||
WeekStart time.Time `json:"week_start"`
|
||||
Revenue float64 `json:"revenue"`
|
||||
OrderCount int64 `json:"order_count"`
|
||||
// SDL is summed per parent category, each at its own owner fee percent
|
||||
SDL float64 `json:"sdl"`
|
||||
}
|
||||
|
||||
// DashboardOverview represents dashboard overview data
|
||||
|
||||
@@ -41,8 +41,14 @@ type Category struct {
|
||||
Order int `gorm:"default:0" json:"order"`
|
||||
BusinessType string `gorm:"size:50;default:'restaurant'" json:"business_type"`
|
||||
Metadata Metadata `gorm:"type:jsonb;default:'{}'" json:"metadata"`
|
||||
CreatedAt time.Time `gorm:"autoCreateTime" json:"created_at"`
|
||||
UpdatedAt time.Time `gorm:"autoUpdateTime" json:"updated_at"`
|
||||
// OwnerFeePercent overrides the owner's share in the parent category budget report; nil uses the default
|
||||
OwnerFeePercent *float64 `gorm:"type:numeric(5,2)" json:"owner_fee_percent"`
|
||||
// IsTeam marks a parent category as a team in the revenue split. It has no gorm
|
||||
// default on purpose: GORM would turn an explicit false into the default on insert,
|
||||
// so callers creating a category set it themselves.
|
||||
IsTeam bool `gorm:"not null" json:"is_team"`
|
||||
CreatedAt time.Time `gorm:"autoCreateTime" json:"created_at"`
|
||||
UpdatedAt time.Time `gorm:"autoUpdateTime" json:"updated_at"`
|
||||
|
||||
Organization Organization `gorm:"foreignKey:OrganizationID" json:"organization,omitempty"`
|
||||
Products []Product `gorm:"foreignKey:CategoryID" json:"products,omitempty"`
|
||||
|
||||
@@ -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")
|
||||
}
|
||||
@@ -91,8 +91,8 @@ func TestOutletLoyaltySettingsEndpoints_AgainstPostgres(t *testing.T) {
|
||||
status, body := call(http.MethodGet, "/manager"+path, "")
|
||||
require.Equal(t, http.StatusOK, status, body)
|
||||
got := data(body)
|
||||
assert.Equal(t, map[string]any{"enabled": false, "earn_per_amount": float64(100), "earn_value": float64(1), "min_order_amount": float64(0), "max_per_order": nil}, got["point"])
|
||||
assert.Equal(t, map[string]any{"enabled": false, "earn_per_amount": float64(25000), "earn_value": float64(1), "min_order_amount": float64(0), "max_per_order": nil}, got["coin"])
|
||||
assert.Equal(t, map[string]any{"enabled": false, "earn_mode": "PER_AMOUNT", "earn_per_amount": float64(100), "earn_value": float64(1), "earn_percent": float64(1), "min_order_amount": float64(0), "max_per_order": nil}, got["point"])
|
||||
assert.Equal(t, map[string]any{"enabled": false, "earn_mode": "PER_AMOUNT", "earn_per_amount": float64(25000), "earn_value": float64(1), "earn_percent": float64(1), "min_order_amount": float64(0), "max_per_order": nil}, got["coin"])
|
||||
assert.Equal(t, map[string]any{"accept_payment": false, "min_payment_points": float64(1), "max_payment_percent": float64(100)}, got["point_payment"])
|
||||
assert.EqualValues(t, 1, got["point_value"])
|
||||
assert.EqualValues(t, 1, got["point_cashback_percent"])
|
||||
@@ -135,6 +135,8 @@ func TestOutletLoyaltySettingsEndpoints_AgainstPostgres(t *testing.T) {
|
||||
for name, bad := range map[string]string{
|
||||
"earn_per_amount 0": `{"point": {"earn_per_amount": 0}}`,
|
||||
"negative earn_value": `{"coin": {"earn_value": -1}}`,
|
||||
"earn mode unknown": `{"point": {"earn_mode": "PERCENT"}}`,
|
||||
"earn_percent over 100": `{"coin": {"earn_percent": 101}}`,
|
||||
"negative min_order": `{"point": {"min_order_amount": -5}}`,
|
||||
"negative max_per_order": `{"point": {"max_per_order": -1}}`,
|
||||
"payment percent over 100": `{"point_payment": {"max_payment_percent": 101}}`,
|
||||
|
||||
@@ -58,15 +58,23 @@ func CreateCategoryRequestToEntity(req *models.CreateCategoryRequest) *entities.
|
||||
metadata["image_url"] = *req.ImageURL
|
||||
}
|
||||
|
||||
// A category is a team unless the request says otherwise
|
||||
isTeam := true
|
||||
if req.IsTeam != nil {
|
||||
isTeam = *req.IsTeam
|
||||
}
|
||||
|
||||
return &entities.Category{
|
||||
OrganizationID: req.OrganizationID,
|
||||
OutletID: req.OutletID,
|
||||
ParentID: req.ParentID,
|
||||
Name: req.Name,
|
||||
Description: req.Description,
|
||||
Order: req.Order,
|
||||
BusinessType: "restaurant",
|
||||
Metadata: metadata,
|
||||
OrganizationID: req.OrganizationID,
|
||||
OutletID: req.OutletID,
|
||||
ParentID: req.ParentID,
|
||||
Name: req.Name,
|
||||
Description: req.Description,
|
||||
Order: req.Order,
|
||||
OwnerFeePercent: req.OwnerFeePercent,
|
||||
IsTeam: isTeam,
|
||||
BusinessType: "restaurant",
|
||||
Metadata: metadata,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -94,18 +102,20 @@ func CategoryEntityToResponse(entity *entities.Category) *models.CategoryRespons
|
||||
}
|
||||
|
||||
return &models.CategoryResponse{
|
||||
ID: entity.ID,
|
||||
OrganizationID: entity.OrganizationID,
|
||||
OutletID: entity.OutletID,
|
||||
ParentID: entity.ParentID,
|
||||
ParentName: parentName,
|
||||
Name: entity.Name,
|
||||
Description: entity.Description,
|
||||
ImageURL: imageURL,
|
||||
Order: entity.Order,
|
||||
IsActive: true,
|
||||
CreatedAt: entity.CreatedAt,
|
||||
UpdatedAt: entity.UpdatedAt,
|
||||
ID: entity.ID,
|
||||
OrganizationID: entity.OrganizationID,
|
||||
OutletID: entity.OutletID,
|
||||
ParentID: entity.ParentID,
|
||||
ParentName: parentName,
|
||||
Name: entity.Name,
|
||||
Description: entity.Description,
|
||||
ImageURL: imageURL,
|
||||
Order: entity.Order,
|
||||
OwnerFeePercent: entity.OwnerFeePercent,
|
||||
IsTeam: entity.IsTeam,
|
||||
IsActive: true,
|
||||
CreatedAt: entity.CreatedAt,
|
||||
UpdatedAt: entity.UpdatedAt,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -134,11 +144,25 @@ func UpdateCategoryEntityFromRequest(entity *entities.Category, req *models.Upda
|
||||
entity.Order = *req.Order
|
||||
}
|
||||
|
||||
if req.ClearOwnerFeePercent {
|
||||
entity.OwnerFeePercent = nil
|
||||
} else if req.OwnerFeePercent != nil {
|
||||
entity.OwnerFeePercent = req.OwnerFeePercent
|
||||
}
|
||||
|
||||
if req.IsTeam != nil {
|
||||
entity.IsTeam = *req.IsTeam
|
||||
}
|
||||
|
||||
if req.OutletID != nil {
|
||||
entity.OutletID = req.OutletID
|
||||
}
|
||||
|
||||
if req.ParentID != nil {
|
||||
if req.ClearParentID {
|
||||
// Drop the preloaded parent too, so the response stops reporting it
|
||||
entity.ParentID = nil
|
||||
entity.Parent = nil
|
||||
} else if req.ParentID != nil {
|
||||
entity.ParentID = req.ParentID
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
package mappers
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"apskel-pos-be/internal/models"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestCreateCategoryRequestToEntityDefaultsToTeam(t *testing.T) {
|
||||
notTeam := false
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
isTeam *bool
|
||||
want bool
|
||||
}{
|
||||
{name: "omitted is a team", isTeam: nil, want: true},
|
||||
{name: "false is not a team", isTeam: ¬Team, want: false},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
entity := CreateCategoryRequestToEntity(&models.CreateCategoryRequest{
|
||||
OrganizationID: uuid.New(),
|
||||
Name: "Merchandise",
|
||||
IsTeam: tt.isTeam,
|
||||
})
|
||||
require.Equal(t, tt.want, entity.IsTeam)
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -82,7 +82,7 @@ func (m *AuthMiddleware) RequireRole(allowedRoles ...string) gin.HandlerFunc {
|
||||
}
|
||||
|
||||
func (m *AuthMiddleware) RequireAdminOrManager() gin.HandlerFunc {
|
||||
return m.RequireRole("superadmin", "admin", "manager", "owner", "purchasing")
|
||||
return m.RequireRole("superadmin", "admin", "manager", "owner", "purchasing")
|
||||
}
|
||||
|
||||
// RequireLoyaltyManager guards what moves or prices EnakPoint and EnakCoin: loyalty
|
||||
|
||||
@@ -306,16 +306,27 @@ type ProductAnalyticsPerParentCategoryResponse struct {
|
||||
}
|
||||
|
||||
type ProductAnalyticsPerParentCategoryData struct {
|
||||
ParentCategoryID uuid.UUID `json:"parent_category_id"`
|
||||
ParentCategoryName string `json:"parent_category_name"`
|
||||
TotalRevenue float64 `json:"total_revenue"`
|
||||
TotalQuantity int64 `json:"total_quantity"`
|
||||
CategoryCount int64 `json:"category_count"`
|
||||
ProductCount int64 `json:"product_count"`
|
||||
OrderCount int64 `json:"order_count"`
|
||||
TotalStandardHpp float64 `json:"total_standard_hpp"`
|
||||
TotalFifoHpp float64 `json:"total_fifo_hpp"`
|
||||
TotalMovingAverageHpp float64 `json:"total_moving_average_hpp"`
|
||||
ParentCategoryID uuid.UUID `json:"parent_category_id"`
|
||||
ParentCategoryName string `json:"parent_category_name"`
|
||||
OwnerFeePercent float64 `json:"owner_fee_percent"`
|
||||
SDL float64 `json:"sdl"`
|
||||
TotalRevenue float64 `json:"total_revenue"`
|
||||
TotalQuantity int64 `json:"total_quantity"`
|
||||
CategoryCount int64 `json:"category_count"`
|
||||
ProductCount int64 `json:"product_count"`
|
||||
OrderCount int64 `json:"order_count"`
|
||||
TotalStandardHpp float64 `json:"total_standard_hpp"`
|
||||
TotalFifoHpp float64 `json:"total_fifo_hpp"`
|
||||
TotalMovingAverageHpp float64 `json:"total_moving_average_hpp"`
|
||||
TopProduct *ParentCategoryTopProduct `json:"top_product"`
|
||||
}
|
||||
|
||||
// ParentCategoryTopProduct is the best-selling product of a parent category by revenue.
|
||||
type ParentCategoryTopProduct struct {
|
||||
ProductID uuid.UUID `json:"product_id"`
|
||||
ProductName string `json:"product_name"`
|
||||
QuantitySold int64 `json:"quantity_sold"`
|
||||
Revenue float64 `json:"revenue"`
|
||||
}
|
||||
|
||||
// ParentCategoryAnalyticsDetailRequest represents the request for the drill-down of one parent category
|
||||
@@ -342,19 +353,25 @@ type ParentCategoryAnalyticsDetailResponse struct {
|
||||
}
|
||||
|
||||
type ParentCategoryAnalyticsDetailSummary struct {
|
||||
TotalRevenue float64 `json:"total_revenue"`
|
||||
TotalQuantity int64 `json:"total_quantity"`
|
||||
CategoryCount int64 `json:"category_count"`
|
||||
ProductCount int64 `json:"product_count"`
|
||||
OrderCount int64 `json:"order_count"`
|
||||
TotalStandardHpp float64 `json:"total_standard_hpp"`
|
||||
TotalFifoHpp float64 `json:"total_fifo_hpp"`
|
||||
TotalMovingAverageHpp float64 `json:"total_moving_average_hpp"`
|
||||
OwnerFeePercent float64 `json:"owner_fee_percent"`
|
||||
SDL float64 `json:"sdl"`
|
||||
TotalRevenue float64 `json:"total_revenue"`
|
||||
TotalQuantity int64 `json:"total_quantity"`
|
||||
CategoryCount int64 `json:"category_count"`
|
||||
ProductCount int64 `json:"product_count"`
|
||||
OrderCount int64 `json:"order_count"`
|
||||
TotalStandardHpp float64 `json:"total_standard_hpp"`
|
||||
TotalFifoHpp float64 `json:"total_fifo_hpp"`
|
||||
TotalMovingAverageHpp float64 `json:"total_moving_average_hpp"`
|
||||
TopProduct *ParentCategoryTopProduct `json:"top_product"`
|
||||
}
|
||||
|
||||
type ParentCategoryAnalyticsDetailData struct {
|
||||
CategoryID uuid.UUID `json:"category_id"`
|
||||
CategoryName string `json:"category_name"`
|
||||
OwnerFeePercent float64 `json:"owner_fee_percent"`
|
||||
SDL float64 `json:"sdl"`
|
||||
TopProduct *ParentCategoryTopProduct `json:"top_product"`
|
||||
TotalRevenue float64 `json:"total_revenue"`
|
||||
TotalQuantity int64 `json:"total_quantity"`
|
||||
ProductCount int64 `json:"product_count"`
|
||||
@@ -395,19 +412,17 @@ type BudgetCutOff struct {
|
||||
}
|
||||
|
||||
type BudgetPercentages struct {
|
||||
Purchase float64 `json:"purchase"`
|
||||
Owner float64 `json:"owner"`
|
||||
Team float64 `json:"team"`
|
||||
Owner float64 `json:"owner"`
|
||||
Team float64 `json:"team"`
|
||||
}
|
||||
|
||||
type BudgetPeriod struct {
|
||||
PeriodStart time.Time `json:"period_start"`
|
||||
PeriodEnd time.Time `json:"period_end"`
|
||||
Revenue float64 `json:"revenue"`
|
||||
OrderCount int64 `json:"order_count"`
|
||||
LimitPurchase float64 `json:"limit_purchase"`
|
||||
LimitOwner float64 `json:"limit_owner"`
|
||||
LimitTeam float64 `json:"limit_team"`
|
||||
PeriodStart time.Time `json:"period_start"`
|
||||
PeriodEnd time.Time `json:"period_end"`
|
||||
Revenue float64 `json:"revenue"`
|
||||
OrderCount int64 `json:"order_count"`
|
||||
SDL float64 `json:"sdl"`
|
||||
LimitTeam float64 `json:"limit_team"`
|
||||
}
|
||||
|
||||
type BudgetMonthPeriod struct {
|
||||
|
||||
+37
-26
@@ -20,36 +20,47 @@ type Category struct {
|
||||
}
|
||||
|
||||
type CreateCategoryRequest struct {
|
||||
OrganizationID uuid.UUID `validate:"required"`
|
||||
OutletID *uuid.UUID
|
||||
ParentID *uuid.UUID
|
||||
Name string `validate:"required,min=1,max=255"`
|
||||
Description *string `validate:"omitempty,max=1000"`
|
||||
ImageURL *string `validate:"omitempty,url"`
|
||||
Order int `validate:"min=0"`
|
||||
OrganizationID uuid.UUID `validate:"required"`
|
||||
OutletID *uuid.UUID
|
||||
ParentID *uuid.UUID
|
||||
Name string `validate:"required,min=1,max=255"`
|
||||
Description *string `validate:"omitempty,max=1000"`
|
||||
ImageURL *string `validate:"omitempty,url"`
|
||||
Order int `validate:"min=0"`
|
||||
OwnerFeePercent *float64 `validate:"omitempty,min=0,max=100"`
|
||||
// IsTeam defaults to true when left out
|
||||
IsTeam *bool
|
||||
}
|
||||
|
||||
type UpdateCategoryRequest struct {
|
||||
Name *string `validate:"omitempty,min=1,max=255"`
|
||||
Description *string `validate:"omitempty,max=1000"`
|
||||
ImageURL *string `validate:"omitempty,url"`
|
||||
OutletID *uuid.UUID
|
||||
ParentID *uuid.UUID
|
||||
Order *int `validate:"omitempty,min=0"`
|
||||
IsActive *bool
|
||||
Name *string `validate:"omitempty,min=1,max=255"`
|
||||
Description *string `validate:"omitempty,max=1000"`
|
||||
ImageURL *string `validate:"omitempty,url"`
|
||||
OutletID *uuid.UUID
|
||||
ParentID *uuid.UUID
|
||||
Order *int `validate:"omitempty,min=0"`
|
||||
OwnerFeePercent *float64 `validate:"omitempty,min=0,max=100"`
|
||||
IsTeam *bool
|
||||
IsActive *bool
|
||||
|
||||
// Clear flags remove the value; a nil pointer above only means "leave unchanged"
|
||||
ClearParentID bool
|
||||
ClearOwnerFeePercent bool
|
||||
}
|
||||
|
||||
type CategoryResponse struct {
|
||||
ID uuid.UUID
|
||||
OrganizationID uuid.UUID
|
||||
OutletID *uuid.UUID
|
||||
ParentID *uuid.UUID
|
||||
ParentName *string
|
||||
Name string
|
||||
Description *string
|
||||
ImageURL *string
|
||||
Order int
|
||||
IsActive bool
|
||||
CreatedAt time.Time
|
||||
UpdatedAt time.Time
|
||||
ID uuid.UUID
|
||||
OrganizationID uuid.UUID
|
||||
OutletID *uuid.UUID
|
||||
ParentID *uuid.UUID
|
||||
ParentName *string
|
||||
Name string
|
||||
Description *string
|
||||
ImageURL *string
|
||||
Order int
|
||||
OwnerFeePercent *float64
|
||||
IsTeam bool
|
||||
IsActive bool
|
||||
CreatedAt time.Time
|
||||
UpdatedAt time.Time
|
||||
}
|
||||
|
||||
@@ -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"`
|
||||
}
|
||||
+29
-10
@@ -5,6 +5,8 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"apskel-pos-be/internal/constants"
|
||||
)
|
||||
|
||||
// OutletLoyaltySettings are an outlet's loyalty settings (docs/prd-point-coin.md F1).
|
||||
@@ -15,15 +17,23 @@ type OutletLoyaltySettings struct {
|
||||
PointPayment LoyaltyPointPaymentSettings `json:"point_payment"`
|
||||
}
|
||||
|
||||
// LoyaltyEarnSettings is how much of one currency an order earns:
|
||||
// floor(basis / EarnPerAmount) × EarnValue, nothing below MinOrderAmount, and at most
|
||||
// MaxPerOrder when set.
|
||||
// LoyaltyEarnSettings is how much of one currency an order earns, nothing below
|
||||
// MinOrderAmount, and at most MaxPerOrder when set:
|
||||
//
|
||||
// - PER_AMOUNT: floor(basis / EarnPerAmount) × EarnValue;
|
||||
// - PERCENTAGE: floor(basis × EarnPercent / 100).
|
||||
//
|
||||
// The settings of the mode not in use are kept, so switching back restores them.
|
||||
type LoyaltyEarnSettings struct {
|
||||
Enabled bool `json:"enabled"`
|
||||
EarnPerAmount int64 `json:"earn_per_amount"`
|
||||
EarnValue int64 `json:"earn_value"`
|
||||
MinOrderAmount int64 `json:"min_order_amount"`
|
||||
MaxPerOrder *int64 `json:"max_per_order"`
|
||||
Enabled bool `json:"enabled"`
|
||||
// PER_AMOUNT or PERCENTAGE.
|
||||
EarnMode string `json:"earn_mode"`
|
||||
EarnPerAmount int64 `json:"earn_per_amount"`
|
||||
EarnValue int64 `json:"earn_value"`
|
||||
// PERCENTAGE: percent of the basis earned, 0–100 with at most two decimals.
|
||||
EarnPercent float64 `json:"earn_percent"`
|
||||
MinOrderAmount int64 `json:"min_order_amount"`
|
||||
MaxPerOrder *int64 `json:"max_per_order"`
|
||||
}
|
||||
|
||||
type LoyaltyPointPaymentSettings struct {
|
||||
@@ -102,8 +112,8 @@ type OutletLoyaltySettingsView struct {
|
||||
// The organization's rupiah value of one EnakPoint, which the cashback depends on.
|
||||
PointValue int64 `json:"point_value"`
|
||||
// Effective EnakPoint cashback in percent: earn_value × point_value /
|
||||
// earn_per_amount × 100. Shown next to the setting so an owner cannot misread the
|
||||
// scale (F1).
|
||||
// earn_per_amount × 100, or earn_percent × point_value in PERCENTAGE mode. Shown
|
||||
// next to the setting so an owner cannot misread the scale (F1).
|
||||
PointCashbackPercent float64 `json:"point_cashback_percent"`
|
||||
// Set on PUT: the keys that changed.
|
||||
Changes []LoyaltySettingChange `json:"changes,omitempty"`
|
||||
@@ -168,6 +178,15 @@ type LoyaltySettingsImpact struct {
|
||||
CoinRupiahAfter int64 `json:"coin_rupiah_after"`
|
||||
}
|
||||
|
||||
// CashbackPercent is the rupiah value of what an order earns as a percentage of its
|
||||
// basis, in the mode the settings are in, rounded to two decimals.
|
||||
func (s LoyaltyEarnSettings) CashbackPercent(pointValue int64) float64 {
|
||||
if s.EarnMode == constants.LoyaltyEarnModePercentage {
|
||||
return math.Round(s.EarnPercent*float64(pointValue)*100) / 100
|
||||
}
|
||||
return LoyaltyCashbackPercent(s.EarnValue, pointValue, s.EarnPerAmount)
|
||||
}
|
||||
|
||||
// NewLoyaltySettingsImpact computes the impact of moving from one organization setting
|
||||
// to another on the balances in circulation.
|
||||
func NewLoyaltySettingsImpact(points, coins int64, before, after OrganizationLoyaltySettings) LoyaltySettingsImpact {
|
||||
|
||||
@@ -14,6 +14,14 @@ func TestLoyaltyCashbackPercent(t *testing.T) {
|
||||
assert.Equal(t, 0.0, LoyaltyCashbackPercent(1, 1, 0))
|
||||
}
|
||||
|
||||
func TestLoyaltyEarnSettings_CashbackPercent(t *testing.T) {
|
||||
s := LoyaltyEarnSettings{EarnMode: "PER_AMOUNT", EarnPerAmount: 100, EarnValue: 1, EarnPercent: 2.5}
|
||||
assert.Equal(t, 1.0, s.CashbackPercent(1))
|
||||
s.EarnMode = "PERCENTAGE"
|
||||
assert.Equal(t, 2.5, s.CashbackPercent(1))
|
||||
assert.Equal(t, 250.0, s.CashbackPercent(100), "each point earned is worth point_value rupiah")
|
||||
}
|
||||
|
||||
func TestNewLoyaltySettingsImpact(t *testing.T) {
|
||||
before := OrganizationLoyaltySettings{PointValue: 1, Exchange: LoyaltyExchangeSettings{CoinAmount: 1, PointAmount: 1}}
|
||||
after := OrganizationLoyaltySettings{PointValue: 100, Exchange: LoyaltyExchangeSettings{CoinAmount: 10, PointAmount: 1}}
|
||||
|
||||
@@ -413,9 +413,22 @@ func (p *AnalyticsProcessorImpl) GetProductAnalyticsPerParentCategory(ctx contex
|
||||
// Transform data
|
||||
var resultData []models.ProductAnalyticsPerParentCategoryData
|
||||
for _, data := range analyticsData {
|
||||
var topProduct *models.ParentCategoryTopProduct
|
||||
if data.TopProduct != nil {
|
||||
topProduct = &models.ParentCategoryTopProduct{
|
||||
ProductID: data.TopProduct.ProductID,
|
||||
ProductName: data.TopProduct.ProductName,
|
||||
QuantitySold: data.TopProduct.QuantitySold,
|
||||
Revenue: data.TopProduct.Revenue,
|
||||
}
|
||||
}
|
||||
|
||||
resultData = append(resultData, models.ProductAnalyticsPerParentCategoryData{
|
||||
TopProduct: topProduct,
|
||||
ParentCategoryID: data.ParentCategoryID,
|
||||
ParentCategoryName: data.ParentCategoryName,
|
||||
OwnerFeePercent: data.OwnerFeePercent,
|
||||
SDL: data.TotalRevenue * data.OwnerFeePercent / 100,
|
||||
TotalRevenue: data.TotalRevenue,
|
||||
TotalQuantity: data.TotalQuantity,
|
||||
CategoryCount: data.CategoryCount,
|
||||
@@ -456,7 +469,9 @@ func (p *AnalyticsProcessorImpl) GetParentCategoryAnalyticsDetail(ctx context.Co
|
||||
|
||||
// Bucket the product rows by the category they belong to
|
||||
productsByCategory := make(map[uuid.UUID][]models.ParentCategoryAnalyticsProductData)
|
||||
productRowsByCategory := make(map[uuid.UUID][]*entities.ProductAnalytics)
|
||||
for _, product := range detail.Products {
|
||||
productRowsByCategory[product.CategoryID] = append(productRowsByCategory[product.CategoryID], product)
|
||||
productsByCategory[product.CategoryID] = append(productsByCategory[product.CategoryID], models.ParentCategoryAnalyticsProductData{
|
||||
ProductID: product.ProductID,
|
||||
ProductName: product.ProductName,
|
||||
@@ -476,6 +491,12 @@ func (p *AnalyticsProcessorImpl) GetParentCategoryAnalyticsDetail(ctx context.Co
|
||||
})
|
||||
}
|
||||
|
||||
// Sub-categories take the owner fee of the parent category they sit under
|
||||
var ownerFeePercent float64
|
||||
if detail.Summary != nil {
|
||||
ownerFeePercent = detail.Summary.OwnerFeePercent
|
||||
}
|
||||
|
||||
categories := make([]models.ParentCategoryAnalyticsDetailData, 0, len(detail.Categories))
|
||||
for _, category := range detail.Categories {
|
||||
products := productsByCategory[category.CategoryID]
|
||||
@@ -486,6 +507,9 @@ func (p *AnalyticsProcessorImpl) GetParentCategoryAnalyticsDetail(ctx context.Co
|
||||
categories = append(categories, models.ParentCategoryAnalyticsDetailData{
|
||||
CategoryID: category.CategoryID,
|
||||
CategoryName: category.CategoryName,
|
||||
OwnerFeePercent: ownerFeePercent,
|
||||
SDL: category.TotalRevenue * ownerFeePercent / 100,
|
||||
TopProduct: topProductByRevenue(productRowsByCategory[category.CategoryID]),
|
||||
TotalRevenue: category.TotalRevenue,
|
||||
TotalQuantity: category.TotalQuantity,
|
||||
ProductCount: category.ProductCount,
|
||||
@@ -500,6 +524,9 @@ func (p *AnalyticsProcessorImpl) GetParentCategoryAnalyticsDetail(ctx context.Co
|
||||
summary := models.ParentCategoryAnalyticsDetailSummary{}
|
||||
if detail.Summary != nil {
|
||||
summary = models.ParentCategoryAnalyticsDetailSummary{
|
||||
TopProduct: topProductByRevenue(detail.Products),
|
||||
OwnerFeePercent: detail.Summary.OwnerFeePercent,
|
||||
SDL: detail.Summary.TotalRevenue * detail.Summary.OwnerFeePercent / 100,
|
||||
TotalRevenue: detail.Summary.TotalRevenue,
|
||||
TotalQuantity: detail.Summary.TotalQuantity,
|
||||
CategoryCount: detail.Summary.CategoryCount,
|
||||
@@ -515,6 +542,11 @@ func (p *AnalyticsProcessorImpl) GetParentCategoryAnalyticsDetail(ctx context.Co
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// The block covers a single parent category, so it reports that category's own fee
|
||||
if detail.Summary != nil {
|
||||
budget.Percentages.Owner = detail.Summary.OwnerFeePercent
|
||||
budget.Percentages.Team = 100 - detail.Summary.OwnerFeePercent
|
||||
}
|
||||
|
||||
return &models.ParentCategoryAnalyticsDetailResponse{
|
||||
OrganizationID: req.OrganizationID,
|
||||
@@ -530,6 +562,30 @@ func (p *AnalyticsProcessorImpl) GetParentCategoryAnalyticsDetail(ctx context.Co
|
||||
}, nil
|
||||
}
|
||||
|
||||
// topProductByRevenue picks the best-selling product of a parent category. A product
|
||||
// can span several rows (one per outlet price), so the rows are added up per product
|
||||
// first. Ties keep the product that was seen first.
|
||||
func topProductByRevenue(products []*entities.ProductAnalytics) *models.ParentCategoryTopProduct {
|
||||
totals := make(map[uuid.UUID]*models.ParentCategoryTopProduct)
|
||||
for _, product := range products {
|
||||
total, ok := totals[product.ProductID]
|
||||
if !ok {
|
||||
total = &models.ParentCategoryTopProduct{ProductID: product.ProductID, ProductName: product.ProductName}
|
||||
totals[product.ProductID] = total
|
||||
}
|
||||
total.QuantitySold += product.QuantitySold
|
||||
total.Revenue += product.Revenue
|
||||
}
|
||||
|
||||
var top *models.ParentCategoryTopProduct
|
||||
for _, product := range products {
|
||||
if total := totals[product.ProductID]; top == nil || total.Revenue > top.Revenue {
|
||||
top = total
|
||||
}
|
||||
}
|
||||
return top
|
||||
}
|
||||
|
||||
// startOfWeek returns the Monday 00:00 of the week containing t, in t's own location.
|
||||
func startOfWeek(t time.Time) time.Time {
|
||||
daysSinceMonday := (int(t.Weekday()) + 6) % 7
|
||||
@@ -542,16 +598,17 @@ func endOfWeek(t time.Time) time.Time {
|
||||
return startOfWeek(t).AddDate(0, 0, 7).Add(-time.Nanosecond)
|
||||
}
|
||||
|
||||
// newBudgetPeriod splits a period's revenue into the spending limits.
|
||||
func newBudgetPeriod(start, end time.Time, revenue float64, orderCount int64) models.BudgetPeriod {
|
||||
// newBudgetPeriod splits a period's revenue between the owner and the team. The owner
|
||||
// share is passed in because a parent category can carry its own owner fee percent,
|
||||
// and the team takes whatever the owner does not.
|
||||
func newBudgetPeriod(start, end time.Time, revenue, sdl float64, orderCount int64) models.BudgetPeriod {
|
||||
return models.BudgetPeriod{
|
||||
PeriodStart: start,
|
||||
PeriodEnd: end,
|
||||
Revenue: revenue,
|
||||
OrderCount: orderCount,
|
||||
LimitPurchase: revenue * constants.BudgetLimitPurchasePercent / 100,
|
||||
LimitOwner: revenue * constants.BudgetLimitOwnerPercent / 100,
|
||||
LimitTeam: revenue * constants.BudgetLimitTeamPercent / 100,
|
||||
PeriodStart: start,
|
||||
PeriodEnd: end,
|
||||
Revenue: revenue,
|
||||
OrderCount: orderCount,
|
||||
SDL: sdl,
|
||||
LimitTeam: revenue - sdl,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -565,9 +622,8 @@ func (p *AnalyticsProcessorImpl) buildBudgetCutOff(ctx context.Context, organiza
|
||||
|
||||
budget := models.BudgetCutOff{
|
||||
Percentages: models.BudgetPercentages{
|
||||
Purchase: constants.BudgetLimitPurchasePercent,
|
||||
Owner: constants.BudgetLimitOwnerPercent,
|
||||
Team: constants.BudgetLimitTeamPercent,
|
||||
Owner: constants.BudgetLimitOwnerPercent,
|
||||
Team: 100 - constants.BudgetLimitOwnerPercent,
|
||||
},
|
||||
CutOffFrom: cutOffFrom,
|
||||
CutOffTo: cutOffTo,
|
||||
@@ -588,22 +644,24 @@ func (p *AnalyticsProcessorImpl) buildBudgetCutOff(ctx context.Context, organiza
|
||||
|
||||
var (
|
||||
totalRevenue float64
|
||||
totalSDL float64
|
||||
totalOrders int64
|
||||
monthOrder []string
|
||||
monthAccumulator = map[string]*models.BudgetMonthPeriod{}
|
||||
)
|
||||
|
||||
for week := cutOffFrom; !week.After(cutOffTo); week = week.AddDate(0, 0, 7) {
|
||||
var revenue float64
|
||||
var revenue, sdl float64
|
||||
var orderCount int64
|
||||
if row, ok := rowsByWeek[week.Format("2006-01-02")]; ok {
|
||||
revenue, orderCount = row.Revenue, row.OrderCount
|
||||
revenue, sdl, orderCount = row.Revenue, row.SDL, row.OrderCount
|
||||
}
|
||||
|
||||
period := newBudgetPeriod(week, endOfWeek(week), revenue, orderCount)
|
||||
period := newBudgetPeriod(week, endOfWeek(week), revenue, sdl, orderCount)
|
||||
budget.Weekly = append(budget.Weekly, period)
|
||||
|
||||
totalRevenue += revenue
|
||||
totalSDL += sdl
|
||||
totalOrders += orderCount
|
||||
|
||||
// A week belongs to the month of its Monday, so every week is counted once
|
||||
@@ -618,6 +676,7 @@ func (p *AnalyticsProcessorImpl) buildBudgetCutOff(ctx context.Context, organiza
|
||||
month.WeekCount++
|
||||
month.PeriodEnd = period.PeriodEnd
|
||||
month.Revenue += revenue
|
||||
month.SDL += sdl
|
||||
month.OrderCount += orderCount
|
||||
}
|
||||
|
||||
@@ -626,11 +685,11 @@ func (p *AnalyticsProcessorImpl) buildBudgetCutOff(ctx context.Context, organiza
|
||||
budget.Monthly = append(budget.Monthly, models.BudgetMonthPeriod{
|
||||
Month: month.Month,
|
||||
WeekCount: month.WeekCount,
|
||||
BudgetPeriod: newBudgetPeriod(month.PeriodStart, month.PeriodEnd, month.Revenue, month.OrderCount),
|
||||
BudgetPeriod: newBudgetPeriod(month.PeriodStart, month.PeriodEnd, month.Revenue, month.SDL, month.OrderCount),
|
||||
})
|
||||
}
|
||||
|
||||
budget.Total = newBudgetPeriod(cutOffFrom, cutOffTo, totalRevenue, totalOrders)
|
||||
budget.Total = newBudgetPeriod(cutOffFrom, cutOffTo, totalRevenue, totalSDL, totalOrders)
|
||||
|
||||
return budget, nil
|
||||
}
|
||||
|
||||
@@ -18,6 +18,7 @@ type analyticsRepositoryStub struct {
|
||||
purchasingResult *entities.PurchasingAnalytics
|
||||
purchasingTeam *entities.PurchaseTeamFilter
|
||||
budgetCutOffWeeks []*entities.BudgetCutOffWeek
|
||||
parentCategories []*entities.ProductAnalyticsPerParentCategory
|
||||
profitLossResult *entities.ProfitLossAnalytics
|
||||
exclusiveSummaryResults []*entities.ExclusiveSummaryAnalytics
|
||||
bankBalances []entities.ExclusiveSummaryBankBalance
|
||||
@@ -49,8 +50,8 @@ func (analyticsRepositoryStub) GetProductAnalyticsPerCategory(context.Context, u
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (analyticsRepositoryStub) GetProductAnalyticsPerParentCategory(context.Context, uuid.UUID, *uuid.UUID, time.Time, time.Time) ([]*entities.ProductAnalyticsPerParentCategory, error) {
|
||||
return nil, nil
|
||||
func (s analyticsRepositoryStub) GetProductAnalyticsPerParentCategory(context.Context, uuid.UUID, *uuid.UUID, time.Time, time.Time) ([]*entities.ProductAnalyticsPerParentCategory, error) {
|
||||
return s.parentCategories, nil
|
||||
}
|
||||
|
||||
func (analyticsRepositoryStub) GetParentCategoryAnalyticsDetail(context.Context, uuid.UUID, *uuid.UUID, uuid.UUID, time.Time, time.Time) (*entities.ParentCategoryAnalyticsDetail, error) {
|
||||
@@ -604,3 +605,61 @@ func TestPaymentMethodAnalytics_EnakPointIsNotCashIn(t *testing.T) {
|
||||
assert.Zero(t, byType["point"].Percentage)
|
||||
assert.Equal(t, int64(30000), byType["point"].PointsUsed)
|
||||
}
|
||||
|
||||
// A parent category with its own owner fee percent moves the owner limit away from the
|
||||
// default share, and the team limit shrinks by the same amount.
|
||||
func TestAnalyticsProcessorParentCategoryUsesOwnerFeePercent(t *testing.T) {
|
||||
monday := time.Date(2026, 9, 28, 0, 0, 0, 0, time.UTC)
|
||||
processor := NewAnalyticsProcessorImpl(&analyticsRepositoryStub{
|
||||
parentCategories: []*entities.ProductAnalyticsPerParentCategory{
|
||||
{ParentCategoryName: "Food", OwnerFeePercent: constants.BudgetLimitOwnerPercent, TotalRevenue: 1000},
|
||||
{ParentCategoryName: "Drink", OwnerFeePercent: 35, TotalRevenue: 2000},
|
||||
},
|
||||
budgetCutOffWeeks: []*entities.BudgetCutOffWeek{
|
||||
// 1000 at the default 20% plus 2000 at 35%
|
||||
{WeekStart: monday, Revenue: 3000, OrderCount: 4, SDL: 900},
|
||||
},
|
||||
}, expenseRepositoryStub{})
|
||||
|
||||
result, err := processor.GetProductAnalyticsPerParentCategory(context.Background(), &models.ProductAnalyticsPerParentCategoryRequest{
|
||||
OrganizationID: uuid.New(),
|
||||
DateFrom: monday,
|
||||
DateTo: monday.AddDate(0, 0, 6),
|
||||
})
|
||||
|
||||
require.NoError(t, err)
|
||||
require.Len(t, result.Data, 2)
|
||||
require.Equal(t, float64(20), result.Data[0].OwnerFeePercent)
|
||||
require.Equal(t, float64(200), result.Data[0].SDL)
|
||||
require.Equal(t, float64(35), result.Data[1].OwnerFeePercent)
|
||||
require.Equal(t, float64(700), result.Data[1].SDL)
|
||||
|
||||
require.Len(t, result.Budget.Weekly, 1)
|
||||
require.Equal(t, float64(900), result.Budget.Weekly[0].SDL)
|
||||
require.Equal(t, float64(2100), result.Budget.Weekly[0].LimitTeam)
|
||||
require.Equal(t, float64(20), result.Budget.Percentages.Owner)
|
||||
require.Equal(t, float64(80), result.Budget.Percentages.Team)
|
||||
require.Len(t, result.Budget.Monthly, 1)
|
||||
require.Equal(t, float64(900), result.Budget.Monthly[0].SDL)
|
||||
require.Equal(t, float64(900), result.Budget.Total.SDL)
|
||||
}
|
||||
|
||||
// A product sold at several outlet prices comes back as several rows, which must be
|
||||
// added up before the best seller is picked.
|
||||
func TestTopProductByRevenueAddsUpRowsOfTheSameProduct(t *testing.T) {
|
||||
split, single := uuid.New(), uuid.New()
|
||||
|
||||
top := topProductByRevenue([]*entities.ProductAnalytics{
|
||||
{ProductID: single, ProductName: "Es Teh", QuantitySold: 5, Revenue: 500},
|
||||
{ProductID: split, ProductName: "Nasi Goreng", QuantitySold: 2, Revenue: 300},
|
||||
{ProductID: split, ProductName: "Nasi Goreng", QuantitySold: 2, Revenue: 300},
|
||||
})
|
||||
|
||||
require.NotNil(t, top)
|
||||
require.Equal(t, split, top.ProductID)
|
||||
require.Equal(t, "Nasi Goreng", top.ProductName)
|
||||
require.Equal(t, int64(4), top.QuantitySold)
|
||||
require.Equal(t, float64(600), top.Revenue)
|
||||
|
||||
require.Nil(t, topProductByRevenue(nil))
|
||||
}
|
||||
|
||||
@@ -85,7 +85,7 @@ func TestBuildBudgetCutOffAppliesLimits(t *testing.T) {
|
||||
weekStart := time.Date(2026, 8, 3, 0, 0, 0, 0, loc)
|
||||
|
||||
stub := &analyticsRepositoryStub{budgetCutOffWeeks: []*entities.BudgetCutOffWeek{
|
||||
{WeekStart: weekStart, Revenue: 10_000_000, OrderCount: 120},
|
||||
{WeekStart: weekStart, Revenue: 10_000_000, OrderCount: 120, SDL: 2_500_000},
|
||||
}}
|
||||
processor := &AnalyticsProcessorImpl{analyticsRepo: stub}
|
||||
|
||||
@@ -93,16 +93,17 @@ func TestBuildBudgetCutOffAppliesLimits(t *testing.T) {
|
||||
require.NoError(t, err)
|
||||
require.Len(t, budget.Weekly, 1)
|
||||
|
||||
// 60 / 20 / 20 of the week's revenue
|
||||
// The owner limit is whatever the repository summed from each parent category's
|
||||
// own fee percent, and the team takes the rest of the week's revenue
|
||||
week := budget.Weekly[0]
|
||||
require.Equal(t, float64(6_000_000), week.LimitPurchase)
|
||||
require.Equal(t, float64(2_000_000), week.LimitOwner)
|
||||
require.Equal(t, float64(2_000_000), week.LimitTeam)
|
||||
require.Equal(t, float64(2_500_000), week.SDL)
|
||||
require.Equal(t, float64(7_500_000), week.LimitTeam)
|
||||
require.Equal(t, int64(120), week.OrderCount)
|
||||
|
||||
// Totals mirror the single week
|
||||
require.Equal(t, week.Revenue, budget.Total.Revenue)
|
||||
require.Equal(t, week.LimitPurchase, budget.Total.LimitPurchase)
|
||||
require.Equal(t, week.SDL, budget.Total.SDL)
|
||||
require.Equal(t, week.LimitTeam, budget.Total.LimitTeam)
|
||||
}
|
||||
|
||||
func TestBuildBudgetCutOffAccumulatesMonthlyFromWeeks(t *testing.T) {
|
||||
@@ -110,8 +111,8 @@ func TestBuildBudgetCutOffAccumulatesMonthlyFromWeeks(t *testing.T) {
|
||||
first := time.Date(2026, 8, 3, 0, 0, 0, 0, loc)
|
||||
|
||||
stub := &analyticsRepositoryStub{budgetCutOffWeeks: []*entities.BudgetCutOffWeek{
|
||||
{WeekStart: first, Revenue: 10_000_000, OrderCount: 100},
|
||||
{WeekStart: first.AddDate(0, 0, 7), Revenue: 5_000_000, OrderCount: 60},
|
||||
{WeekStart: first, Revenue: 10_000_000, OrderCount: 100, SDL: 2_000_000},
|
||||
{WeekStart: first.AddDate(0, 0, 7), Revenue: 5_000_000, OrderCount: 60, SDL: 1_000_000},
|
||||
}}
|
||||
processor := &AnalyticsProcessorImpl{analyticsRepo: stub}
|
||||
|
||||
@@ -125,9 +126,10 @@ func TestBuildBudgetCutOffAccumulatesMonthlyFromWeeks(t *testing.T) {
|
||||
require.Equal(t, float64(15_000_000), month.Revenue)
|
||||
require.Equal(t, int64(160), month.OrderCount)
|
||||
|
||||
// The month limit is the accumulation of its weeks
|
||||
require.Equal(t, float64(9_000_000), month.LimitPurchase)
|
||||
require.Equal(t, budget.Weekly[0].LimitPurchase+budget.Weekly[1].LimitPurchase, month.LimitPurchase)
|
||||
// The month limits are the accumulation of its weeks
|
||||
require.Equal(t, float64(3_000_000), month.SDL)
|
||||
require.Equal(t, float64(12_000_000), month.LimitTeam)
|
||||
require.Equal(t, budget.Weekly[0].LimitTeam+budget.Weekly[1].LimitTeam, month.LimitTeam)
|
||||
}
|
||||
|
||||
func TestBuildBudgetCutOffEmitsWeeksWithoutSales(t *testing.T) {
|
||||
@@ -145,7 +147,7 @@ func TestBuildBudgetCutOffEmitsWeeksWithoutSales(t *testing.T) {
|
||||
|
||||
require.Len(t, budget.Weekly, 3)
|
||||
require.Zero(t, budget.Weekly[0].Revenue)
|
||||
require.Zero(t, budget.Weekly[0].LimitPurchase)
|
||||
require.Zero(t, budget.Weekly[0].LimitTeam)
|
||||
require.Zero(t, budget.Weekly[1].Revenue)
|
||||
require.Equal(t, float64(4_000_000), budget.Weekly[2].Revenue)
|
||||
require.Equal(t, float64(4_000_000), budget.Total.Revenue)
|
||||
|
||||
@@ -3,6 +3,7 @@ package processor
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"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")
|
||||
}
|
||||
|
||||
// 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
|
||||
registrationToken := uuid.New().String()
|
||||
|
||||
@@ -156,6 +164,7 @@ func (p *customerAuthProcessor) StartRegistration(ctx context.Context, req *cont
|
||||
"registration_token": registrationToken,
|
||||
"name": req.Name,
|
||||
"birth_date": req.BirthDate,
|
||||
"organization_id": organizationID.String(),
|
||||
"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)
|
||||
}
|
||||
|
||||
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{
|
||||
OrganizationID: defaultOrgID,
|
||||
OrganizationID: organizationID,
|
||||
Name: name,
|
||||
PhoneNumber: &otpSession.PhoneNumber,
|
||||
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
|
||||
|
||||
// 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)
|
||||
}
|
||||
@@ -3,6 +3,7 @@ package processor
|
||||
import (
|
||||
"math"
|
||||
|
||||
"apskel-pos-be/internal/constants"
|
||||
"apskel-pos-be/internal/entities"
|
||||
"apskel-pos-be/internal/models"
|
||||
)
|
||||
@@ -36,6 +37,10 @@ func (r EarningResult) Metadata(line EarningLine) entities.Metadata {
|
||||
"min_order_amount": line.Settings.MinOrderAmount,
|
||||
"capped": line.Capped,
|
||||
}
|
||||
if line.Settings.EarnMode == constants.LoyaltyEarnModePercentage {
|
||||
m["earn_mode"] = line.Settings.EarnMode
|
||||
m["earn_percent"] = line.Settings.EarnPercent
|
||||
}
|
||||
if line.Settings.MaxPerOrder != nil {
|
||||
m["max_per_order"] = *line.Settings.MaxPerOrder
|
||||
}
|
||||
@@ -46,7 +51,8 @@ func (r EarningResult) Metadata(line EarningLine) entities.Metadata {
|
||||
//
|
||||
// basis = subtotal − discount_amount − paid with EnakPoint
|
||||
// amount = 0 if basis < min_order_amount
|
||||
// amount = floor(basis / earn_per_amount) × earn_value
|
||||
// amount = floor(basis / earn_per_amount) × earn_value in PER_AMOUNT mode
|
||||
// amount = floor(basis × earn_percent / 100) in PERCENTAGE mode
|
||||
// amount = min(amount, max_per_order) if max_per_order is set
|
||||
//
|
||||
// The part paid with EnakPoint earns nothing (Q10). Money is handled in whole cents so
|
||||
@@ -66,13 +72,23 @@ func CalculateEarning(order *entities.Order, pointPaidAmount float64, settings m
|
||||
|
||||
func earnLine(basisCents int64, s models.LoyaltyEarnSettings) EarningLine {
|
||||
line := EarningLine{Settings: s}
|
||||
if !s.Enabled || s.EarnPerAmount <= 0 || s.EarnValue <= 0 {
|
||||
if !s.Enabled || basisCents < s.MinOrderAmount*100 {
|
||||
return line
|
||||
}
|
||||
if basisCents < s.MinOrderAmount*100 {
|
||||
return line
|
||||
if s.EarnMode == constants.LoyaltyEarnModePercentage {
|
||||
// The percent has at most two decimals, so in hundredths it is whole and the
|
||||
// product stays in integers: cents × hundredths / (100 × 100 × 100).
|
||||
hundredths := int64(math.Round(s.EarnPercent * 100))
|
||||
if hundredths <= 0 {
|
||||
return line
|
||||
}
|
||||
line.Amount = basisCents * hundredths / 1_000_000
|
||||
} else {
|
||||
if s.EarnPerAmount <= 0 || s.EarnValue <= 0 {
|
||||
return line
|
||||
}
|
||||
line.Amount = basisCents / (s.EarnPerAmount * 100) * s.EarnValue
|
||||
}
|
||||
line.Amount = basisCents / (s.EarnPerAmount * 100) * s.EarnValue
|
||||
if s.MaxPerOrder != nil && line.Amount > *s.MaxPerOrder {
|
||||
line.Amount = *s.MaxPerOrder
|
||||
line.Capped = true
|
||||
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
|
||||
"apskel-pos-be/internal/constants"
|
||||
"apskel-pos-be/internal/entities"
|
||||
"apskel-pos-be/internal/models"
|
||||
)
|
||||
@@ -113,6 +114,44 @@ func TestCalculateEarning_EdgeCases(t *testing.T) {
|
||||
assert.Equal(t, int64(0), CalculateEarning(&entities.Order{Subtotal: 87500}, 0, s).Point.Amount)
|
||||
}
|
||||
|
||||
func TestCalculateEarning_Percentage(t *testing.T) {
|
||||
s := prdEarningSettings()
|
||||
s.Point.EarnMode = constants.LoyaltyEarnModePercentage
|
||||
s.Point.EarnPercent = 1
|
||||
|
||||
// 1% of the basis; the per-amount settings are ignored, and coin keeps its own mode.
|
||||
got := CalculateEarning(&entities.Order{Subtotal: 97500, DiscountAmount: 10000}, 0, s)
|
||||
assert.Equal(t, int64(875), got.Point.Amount)
|
||||
assert.Equal(t, int64(3), got.Coin.Amount)
|
||||
// The part paid with EnakPoint earns nothing in this mode either.
|
||||
assert.Equal(t, int64(675), CalculateEarning(&entities.Order{Subtotal: 97500, DiscountAmount: 10000}, 20000, s).Point.Amount)
|
||||
|
||||
// Decimals, and floor, not round: 2.5% of 87.500 is 2187.5.
|
||||
s.Point.EarnPercent = 2.5
|
||||
assert.Equal(t, int64(2187), CalculateEarning(&entities.Order{Subtotal: 87500}, 0, s).Point.Amount)
|
||||
s.Point.EarnPercent = 0.01
|
||||
assert.Equal(t, int64(8), CalculateEarning(&entities.Order{Subtotal: 87599.99}, 0, s).Point.Amount)
|
||||
|
||||
// The minimum and the cap apply as in the other mode.
|
||||
s.Point.EarnPercent = 10
|
||||
s.Point.MinOrderAmount = 50000
|
||||
max := int64(6000)
|
||||
s.Point.MaxPerOrder = &max
|
||||
assert.Equal(t, int64(0), CalculateEarning(&entities.Order{Subtotal: 49999}, 0, s).Point.Amount)
|
||||
assert.Equal(t, int64(5000), CalculateEarning(&entities.Order{Subtotal: 50000}, 0, s).Point.Amount)
|
||||
got = CalculateEarning(&entities.Order{Subtotal: 87500}, 0, s)
|
||||
assert.Equal(t, int64(6000), got.Point.Amount)
|
||||
assert.True(t, got.Point.Capped)
|
||||
|
||||
// The mode and percent are frozen on the ledger row.
|
||||
assert.Equal(t, constants.LoyaltyEarnModePercentage, got.Metadata(got.Point)["earn_mode"])
|
||||
assert.Equal(t, 10.0, got.Metadata(got.Point)["earn_percent"])
|
||||
|
||||
// A zero percent earns nothing even when enabled.
|
||||
s.Point.EarnPercent = 0
|
||||
assert.Equal(t, int64(0), CalculateEarning(&entities.Order{Subtotal: 87500}, 0, s).Point.Amount)
|
||||
}
|
||||
|
||||
func TestCalculateEarning_MetadataSnapshot(t *testing.T) {
|
||||
got := CalculateEarning(&entities.Order{Subtotal: 87500}, 0, prdEarningSettings())
|
||||
assert.Equal(t, entities.Metadata{
|
||||
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"math"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
@@ -240,14 +241,20 @@ func loyaltySettingChangeModel(row entities.LoyaltySettingChange) models.Loyalty
|
||||
func outletLoyaltyFields(s *models.OutletLoyaltySettings) []loyaltyField {
|
||||
return []loyaltyField{
|
||||
boolLoyaltyField(constants.LoyaltyPointEnabledKey, &s.Point.Enabled, false),
|
||||
enumLoyaltyField(constants.LoyaltyPointEarnModeKey, &s.Point.EarnMode, constants.LoyaltyEarnModeDefault,
|
||||
constants.LoyaltyEarnModePerAmount, constants.LoyaltyEarnModePercentage),
|
||||
intLoyaltyField(constants.LoyaltyPointEarnPerAmountKey, &s.Point.EarnPerAmount, constants.LoyaltyPointEarnPerAmountDefault, 1, noLoyaltyMax),
|
||||
intLoyaltyField(constants.LoyaltyPointEarnValueKey, &s.Point.EarnValue, constants.LoyaltyEarnValueDefault, 0, noLoyaltyMax),
|
||||
percentLoyaltyField(constants.LoyaltyPointEarnPercentKey, &s.Point.EarnPercent, constants.LoyaltyEarnPercentDefault),
|
||||
intLoyaltyField(constants.LoyaltyPointMinOrderAmountKey, &s.Point.MinOrderAmount, 0, 0, noLoyaltyMax),
|
||||
optionalIntLoyaltyField(constants.LoyaltyPointMaxPerOrderKey, &s.Point.MaxPerOrder, 0),
|
||||
|
||||
boolLoyaltyField(constants.LoyaltyCoinEnabledKey, &s.Coin.Enabled, false),
|
||||
enumLoyaltyField(constants.LoyaltyCoinEarnModeKey, &s.Coin.EarnMode, constants.LoyaltyEarnModeDefault,
|
||||
constants.LoyaltyEarnModePerAmount, constants.LoyaltyEarnModePercentage),
|
||||
intLoyaltyField(constants.LoyaltyCoinEarnPerAmountKey, &s.Coin.EarnPerAmount, constants.LoyaltyCoinEarnPerAmountDefault, 1, noLoyaltyMax),
|
||||
intLoyaltyField(constants.LoyaltyCoinEarnValueKey, &s.Coin.EarnValue, constants.LoyaltyEarnValueDefault, 0, noLoyaltyMax),
|
||||
percentLoyaltyField(constants.LoyaltyCoinEarnPercentKey, &s.Coin.EarnPercent, constants.LoyaltyEarnPercentDefault),
|
||||
intLoyaltyField(constants.LoyaltyCoinMinOrderAmountKey, &s.Coin.MinOrderAmount, 0, 0, noLoyaltyMax),
|
||||
optionalIntLoyaltyField(constants.LoyaltyCoinMaxPerOrderKey, &s.Coin.MaxPerOrder, 0),
|
||||
|
||||
@@ -329,6 +336,35 @@ func intLoyaltyField(key string, v *int64, def, min, max int64) loyaltyField {
|
||||
}
|
||||
}
|
||||
|
||||
// percentLoyaltyField is a percentage from 0 to 100 with at most two decimals, so it
|
||||
// is whole in hundredths and calculations with it stay in integers.
|
||||
func percentLoyaltyField(key string, v *float64, def float64) loyaltyField {
|
||||
check := func(n float64) error {
|
||||
// The negated form also rejects NaN.
|
||||
if !(n >= 0 && n <= 100) {
|
||||
return fmt.Errorf("%w: %s must be between 0 and 100", ErrInvalidLoyaltySettings, key)
|
||||
}
|
||||
if math.Abs(n*100-math.Round(n*100)) > 1e-6 {
|
||||
return fmt.Errorf("%w: %s must have at most two decimals", ErrInvalidLoyaltySettings, key)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
return loyaltyField{
|
||||
key: key,
|
||||
parse: func(raw string) bool {
|
||||
n, err := strconv.ParseFloat(strings.TrimSpace(raw), 64)
|
||||
if err != nil || check(n) != nil {
|
||||
return false
|
||||
}
|
||||
*v = n
|
||||
return true
|
||||
},
|
||||
reset: func() { *v = def },
|
||||
validate: func() error { return check(*v) },
|
||||
format: func() *string { s := strconv.FormatFloat(*v, 'f', -1, 64); return &s },
|
||||
}
|
||||
}
|
||||
|
||||
// optionalIntLoyaltyField is a limit that may be unset, meaning no limit.
|
||||
func optionalIntLoyaltyField(key string, v **int64, min int64) loyaltyField {
|
||||
return loyaltyField{
|
||||
|
||||
@@ -107,8 +107,8 @@ func TestLoyaltySettings_OutletWithoutSettingsGetsEveryDefault(t *testing.T) {
|
||||
s, err := p.Outlet(context.Background(), uuid.New())
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, models.OutletLoyaltySettings{
|
||||
Point: models.LoyaltyEarnSettings{Enabled: false, EarnPerAmount: 100, EarnValue: 1, MinOrderAmount: 0, MaxPerOrder: nil},
|
||||
Coin: models.LoyaltyEarnSettings{Enabled: false, EarnPerAmount: 25000, EarnValue: 1, MinOrderAmount: 0, MaxPerOrder: nil},
|
||||
Point: models.LoyaltyEarnSettings{Enabled: false, EarnMode: "PER_AMOUNT", EarnPerAmount: 100, EarnValue: 1, EarnPercent: 1, MinOrderAmount: 0, MaxPerOrder: nil},
|
||||
Coin: models.LoyaltyEarnSettings{Enabled: false, EarnMode: "PER_AMOUNT", EarnPerAmount: 25000, EarnValue: 1, EarnPercent: 1, MinOrderAmount: 0, MaxPerOrder: nil},
|
||||
PointPayment: models.LoyaltyPointPaymentSettings{AcceptPayment: false, MinPaymentPoints: 1, MaxPaymentPercent: 100},
|
||||
}, *s)
|
||||
}
|
||||
@@ -290,6 +290,10 @@ func TestLoyaltySettings_UpdateRejectsInvalidValues(t *testing.T) {
|
||||
for name, mutate := range map[string]func(*models.OutletLoyaltySettings){
|
||||
"earn_per_amount 0": func(s *models.OutletLoyaltySettings) { s.Point.EarnPerAmount = 0 },
|
||||
"negative earn_value": func(s *models.OutletLoyaltySettings) { s.Coin.EarnValue = -1 },
|
||||
"earn mode unknown": func(s *models.OutletLoyaltySettings) { s.Point.EarnMode = "PERCENT" },
|
||||
"negative earn_percent": func(s *models.OutletLoyaltySettings) { s.Point.EarnPercent = -1 },
|
||||
"earn_percent over 100": func(s *models.OutletLoyaltySettings) { s.Coin.EarnPercent = 100.5 },
|
||||
"earn_percent 3 decimals": func(s *models.OutletLoyaltySettings) { s.Point.EarnPercent = 1.125 },
|
||||
"negative min_order": func(s *models.OutletLoyaltySettings) { s.Point.MinOrderAmount = -1 },
|
||||
"negative max_per_order": func(s *models.OutletLoyaltySettings) { s.Coin.MaxPerOrder = ptr(int64(-1)) },
|
||||
"payment percent over 100": func(s *models.OutletLoyaltySettings) { s.PointPayment.MaxPaymentPercent = 101 },
|
||||
|
||||
@@ -11,12 +11,13 @@ import (
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// Teams are the parent product categories, plus Pusat for spending that belongs to
|
||||
// no single team. Both purchase orders and cash advances are charged to one, so the rules
|
||||
// for picking and storing a team live here rather than in either processor.
|
||||
// Teams are the parent product categories flagged is_team, plus Pusat for spending
|
||||
// that belongs to no single team. Both purchase orders and cash advances are charged to
|
||||
// one, so the rules for picking and storing a team live here rather than in either
|
||||
// processor.
|
||||
|
||||
// listTeams returns the teams money can be charged to: the parent categories of the
|
||||
// outlet in scope, followed by Pusat. Pusat has no category row, so it is appended
|
||||
// listTeams returns the teams money can be charged to: the team parent categories of
|
||||
// the outlet in scope, followed by Pusat. Pusat has no category row, so it is appended
|
||||
// here rather than read from the database.
|
||||
func listTeams(ctx context.Context, categoryRepo CategoryRepository, organizationID uuid.UUID, outletID *uuid.UUID) (*models.ListPurchaseTeamsResponse, error) {
|
||||
categories, err := categoryRepo.ListParentCategories(ctx, organizationID, outletID)
|
||||
@@ -26,6 +27,9 @@ func listTeams(ctx context.Context, categoryRepo CategoryRepository, organizatio
|
||||
|
||||
teams := make([]models.PurchaseTeam, 0, len(categories)+1)
|
||||
for _, category := range categories {
|
||||
if !category.IsTeam {
|
||||
continue
|
||||
}
|
||||
categoryID := category.ID
|
||||
teams = append(teams, models.PurchaseTeam{
|
||||
Scope: constants.PurchaseTeamScopeCategory,
|
||||
@@ -75,6 +79,9 @@ func resolveTeamSelection(ctx context.Context, categoryRepo CategoryRepository,
|
||||
if category.ParentID != nil {
|
||||
return nil, nil, fmt.Errorf("team must be a parent category")
|
||||
}
|
||||
if !category.IsTeam {
|
||||
return nil, nil, fmt.Errorf("category %s is not a team", category.Name)
|
||||
}
|
||||
// Categories without an outlet are shared, so only an outlet-specific
|
||||
// category has to match the outlet the record is booked against.
|
||||
if category.OutletID != nil && outletID != nil && *category.OutletID != *outletID {
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
package processor
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"apskel-pos-be/internal/constants"
|
||||
"apskel-pos-be/internal/entities"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// teamCategoryRepositoryStub serves the two lookups the team rules make. The embedded
|
||||
// interface is left nil, so any other call panics and shows up in the test.
|
||||
type teamCategoryRepositoryStub struct {
|
||||
CategoryRepository
|
||||
categories []*entities.Category
|
||||
}
|
||||
|
||||
func (s *teamCategoryRepositoryStub) ListParentCategories(ctx context.Context, organizationID uuid.UUID, outletID *uuid.UUID) ([]*entities.Category, error) {
|
||||
return s.categories, nil
|
||||
}
|
||||
|
||||
func (s *teamCategoryRepositoryStub) GetByID(ctx context.Context, id uuid.UUID) (*entities.Category, error) {
|
||||
for _, category := range s.categories {
|
||||
if category.ID == id {
|
||||
return category, nil
|
||||
}
|
||||
}
|
||||
return nil, errors.New("record not found")
|
||||
}
|
||||
|
||||
func TestListTeamsSkipsParentCategoriesThatAreNotTeams(t *testing.T) {
|
||||
organizationID := uuid.New()
|
||||
food := &entities.Category{ID: uuid.New(), OrganizationID: organizationID, Name: "Food", IsTeam: true}
|
||||
merch := &entities.Category{ID: uuid.New(), OrganizationID: organizationID, Name: "Merchandise", IsTeam: false}
|
||||
repo := &teamCategoryRepositoryStub{categories: []*entities.Category{food, merch}}
|
||||
|
||||
result, err := listTeams(context.Background(), repo, organizationID, nil)
|
||||
require.NoError(t, err)
|
||||
|
||||
require.Len(t, result.Teams, 2)
|
||||
require.Equal(t, "Food", result.Teams[0].Name)
|
||||
require.Equal(t, &food.ID, result.Teams[0].CategoryID)
|
||||
require.Equal(t, constants.PurchaseTeamCentralName, result.Teams[1].Name)
|
||||
}
|
||||
|
||||
func TestResolveTeamSelectionRejectsParentCategoryThatIsNotATeam(t *testing.T) {
|
||||
organizationID := uuid.New()
|
||||
food := &entities.Category{ID: uuid.New(), OrganizationID: organizationID, Name: "Food", IsTeam: true}
|
||||
merch := &entities.Category{ID: uuid.New(), OrganizationID: organizationID, Name: "Merchandise", IsTeam: false}
|
||||
repo := &teamCategoryRepositoryStub{categories: []*entities.Category{food, merch}}
|
||||
scope := constants.PurchaseTeamScopeCategory
|
||||
|
||||
resolvedScope, resolvedID, err := resolveTeamSelection(context.Background(), repo, organizationID, nil, &scope, &food.ID)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, constants.PurchaseTeamScopeCategory, *resolvedScope)
|
||||
require.Equal(t, food.ID, *resolvedID)
|
||||
|
||||
_, _, err = resolveTeamSelection(context.Background(), repo, organizationID, nil, &scope, &merch.ID)
|
||||
require.EqualError(t, err, "category Merchandise is not a team")
|
||||
}
|
||||
@@ -600,6 +600,7 @@ func (r *AnalyticsRepositoryImpl) GetProductAnalyticsPerParentCategory(ctx conte
|
||||
Select(`
|
||||
pc.id as parent_category_id,
|
||||
pc.name as parent_category_name,
|
||||
COALESCE(pc.owner_fee_percent, ?) as owner_fee_percent,
|
||||
COALESCE(SUM(CASE WHEN oi.is_fully_refunded = false THEN oi.total_price - COALESCE(oi.refund_amount, 0) ELSE 0 END), 0) as total_revenue,
|
||||
COALESCE(SUM(CASE WHEN oi.is_fully_refunded = false THEN oi.quantity - COALESCE(oi.refund_quantity, 0) ELSE 0 END), 0) as total_quantity,
|
||||
COUNT(DISTINCT c.id) as category_count,
|
||||
@@ -608,11 +609,13 @@ func (r *AnalyticsRepositoryImpl) GetProductAnalyticsPerParentCategory(ctx conte
|
||||
COALESCE(SUM(CASE WHEN oi.is_fully_refunded = false THEN COALESCE(shpp.hpp_per_unit, p.cost, 0) * `+billableQtyNet+` ELSE 0 END), 0) as total_standard_hpp,
|
||||
COALESCE(SUM(CASE WHEN oi.is_fully_refunded = false THEN oi.total_cost * ((oi.quantity - COALESCE(oi.refund_quantity, 0))::float / NULLIF(oi.quantity, 0)) ELSE 0 END), 0) as total_fifo_hpp,
|
||||
COALESCE(SUM(CASE WHEN oi.is_fully_refunded = false THEN COALESCE(mahpp.hpp_per_unit, p.cost, 0) * `+billableQtyNet+` ELSE 0 END), 0) as total_moving_average_hpp
|
||||
`).
|
||||
`, constants.BudgetLimitOwnerPercent).
|
||||
Joins("JOIN products p ON oi.product_id = p.id").
|
||||
Joins("JOIN categories c ON p.category_id = c.id").
|
||||
// Categories without a parent roll up to themselves, so top-level categories still appear
|
||||
Joins("JOIN categories pc ON pc.id = COALESCE(c.parent_id, c.id)").
|
||||
// Profit sharing only covers the parent categories that are teams
|
||||
Where("pc.is_team = ?", true).
|
||||
Joins("JOIN orders o ON oi.order_id = o.id").
|
||||
Joins("LEFT JOIN (SELECT pr.product_id, SUM(pr.quantity * (1 + COALESCE(pr.waste_percentage, 0)/100.0) * i.cost) as hpp_per_unit FROM product_recipes pr JOIN ingredients i ON pr.ingredient_id = i.id GROUP BY pr.product_id) shpp ON shpp.product_id = p.id").
|
||||
Joins("LEFT JOIN (?) mahpp ON mahpp.product_id = p.id",
|
||||
@@ -640,11 +643,57 @@ func (r *AnalyticsRepositoryImpl) GetProductAnalyticsPerParentCategory(ctx conte
|
||||
query = r.resolveOutletID(query, outletID, "o.outlet_id")
|
||||
|
||||
err := query.
|
||||
Group("pc.id, pc.name").
|
||||
Group("pc.id, pc.name, pc.owner_fee_percent").
|
||||
Order("pc.name ASC").
|
||||
Scan(&results).Error
|
||||
if err != nil || len(results) == 0 {
|
||||
return results, err
|
||||
}
|
||||
|
||||
return results, err
|
||||
// Best-selling product of each parent category. DISTINCT ON keeps the first row per
|
||||
// parent category, which the ordering makes the one with the highest revenue.
|
||||
var topProducts []*entities.ParentCategoryTopProduct
|
||||
topQuery := r.db.WithContext(ctx).
|
||||
Table("order_items oi").
|
||||
Select(`
|
||||
DISTINCT ON (pc.id)
|
||||
pc.id as parent_category_id,
|
||||
p.id as product_id,
|
||||
p.name as product_name,
|
||||
COALESCE(SUM(CASE WHEN oi.is_fully_refunded = false THEN oi.quantity - COALESCE(oi.refund_quantity, 0) ELSE 0 END), 0) as quantity_sold,
|
||||
COALESCE(SUM(CASE WHEN oi.is_fully_refunded = false THEN oi.total_price - COALESCE(oi.refund_amount, 0) ELSE 0 END), 0) as revenue
|
||||
`).
|
||||
Joins("JOIN products p ON oi.product_id = p.id").
|
||||
Joins("JOIN categories c ON p.category_id = c.id").
|
||||
Joins("JOIN categories pc ON pc.id = COALESCE(c.parent_id, c.id)").
|
||||
Joins("JOIN orders o ON oi.order_id = o.id").
|
||||
Where("pc.is_team = ?", true).
|
||||
Where("o.organization_id = ?", organizationID).
|
||||
Where("o.is_void = ?", false).
|
||||
Where("o.is_refund = ?", false).
|
||||
Where("o.payment_status = ?", entities.PaymentStatusCompleted).
|
||||
Where("oi.status != ?", entities.OrderItemStatusCancelled).
|
||||
Where("o.created_at >= ? AND o.created_at <= ?", dateFrom, dateTo)
|
||||
|
||||
topQuery = r.resolveOutletID(topQuery, outletID, "o.outlet_id")
|
||||
|
||||
err = topQuery.
|
||||
Group("pc.id, p.id, p.name").
|
||||
Order("pc.id, COALESCE(SUM(CASE WHEN oi.is_fully_refunded = false THEN oi.total_price - COALESCE(oi.refund_amount, 0) ELSE 0 END), 0) DESC, p.name ASC").
|
||||
Scan(&topProducts).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
topByParent := make(map[uuid.UUID]*entities.ParentCategoryTopProduct, len(topProducts))
|
||||
for _, product := range topProducts {
|
||||
topByParent[product.ParentCategoryID] = product
|
||||
}
|
||||
for _, result := range results {
|
||||
result.TopProduct = topByParent[result.ParentCategoryID]
|
||||
}
|
||||
|
||||
return results, nil
|
||||
}
|
||||
|
||||
// movingAverageHppSubquery builds the per-product moving-average HPP lookup shared by
|
||||
@@ -691,12 +740,14 @@ func (r *AnalyticsRepositoryImpl) GetParentCategoryAnalyticsDetail(ctx context.C
|
||||
// Resolve the category first so the endpoint still identifies the category when it
|
||||
// has no sales in the requested range, and rejects ids from another organization.
|
||||
var parent struct {
|
||||
ID uuid.UUID
|
||||
Name string
|
||||
ID uuid.UUID
|
||||
Name string
|
||||
IsTeam bool
|
||||
OwnerFeePercent float64
|
||||
}
|
||||
if err := r.db.WithContext(ctx).
|
||||
Table("categories").
|
||||
Select("id, name").
|
||||
Select("id, name, is_team, COALESCE(owner_fee_percent, ?) as owner_fee_percent", constants.BudgetLimitOwnerPercent).
|
||||
Where("id = ? AND organization_id = ?", parentCategoryID, organizationID).
|
||||
Scan(&parent).Error; err != nil {
|
||||
return nil, err
|
||||
@@ -704,6 +755,9 @@ func (r *AnalyticsRepositoryImpl) GetParentCategoryAnalyticsDetail(ctx context.C
|
||||
if parent.ID == uuid.Nil {
|
||||
return nil, fmt.Errorf("category not found")
|
||||
}
|
||||
if !parent.IsTeam {
|
||||
return nil, fmt.Errorf("category %s is not a team", parent.Name)
|
||||
}
|
||||
|
||||
detail := &entities.ParentCategoryAnalyticsDetail{
|
||||
ParentCategoryID: parent.ID,
|
||||
@@ -732,6 +786,7 @@ func (r *AnalyticsRepositoryImpl) GetParentCategoryAnalyticsDetail(ctx context.C
|
||||
}
|
||||
summary.ParentCategoryID = parent.ID
|
||||
summary.ParentCategoryName = parent.Name
|
||||
summary.OwnerFeePercent = parent.OwnerFeePercent
|
||||
detail.Summary = summary
|
||||
|
||||
// Sub-category rows.
|
||||
@@ -801,7 +856,8 @@ func (r *AnalyticsRepositoryImpl) GetParentCategoryAnalyticsDetail(ctx context.C
|
||||
// GetBudgetCutOffWeekly buckets revenue and cost of goods sold into Monday-to-Sunday
|
||||
// weeks. DATE_TRUNC('week') is ISO, so the buckets start on Monday, and the connection
|
||||
// runs with TimeZone=Asia/Jakarta so the boundaries land on local midnight.
|
||||
// A nil parentCategoryID covers every category in scope.
|
||||
// A nil parentCategoryID covers every team in scope; parent categories that are not a
|
||||
// team stay out of the split.
|
||||
func (r *AnalyticsRepositoryImpl) GetBudgetCutOffWeekly(ctx context.Context, organizationID uuid.UUID, outletID *uuid.UUID, parentCategoryID *uuid.UUID, cutOffFrom, cutOffTo time.Time) ([]*entities.BudgetCutOffWeek, error) {
|
||||
var results []*entities.BudgetCutOffWeek
|
||||
|
||||
@@ -810,13 +866,18 @@ func (r *AnalyticsRepositoryImpl) GetBudgetCutOffWeekly(ctx context.Context, org
|
||||
Select(`
|
||||
DATE_TRUNC('week', o.created_at) as week_start,
|
||||
COALESCE(SUM(CASE WHEN oi.is_fully_refunded = false THEN oi.total_price - COALESCE(oi.refund_amount, 0) ELSE 0 END), 0) as revenue,
|
||||
COALESCE(SUM((CASE WHEN oi.is_fully_refunded = false THEN oi.total_price - COALESCE(oi.refund_amount, 0) ELSE 0 END) * COALESCE(pc.owner_fee_percent, ?) / 100.0), 0) as sdl,
|
||||
COUNT(DISTINCT oi.order_id) as order_count
|
||||
`).
|
||||
`, constants.BudgetLimitOwnerPercent).
|
||||
// products and categories are joined to keep the scope identical to the report
|
||||
// the block is attached to, even when no parent category filter is applied
|
||||
Joins("JOIN products p ON oi.product_id = p.id").
|
||||
Joins("JOIN categories c ON p.category_id = c.id").
|
||||
// The owner fee lives on the parent category; a category without a parent is its own group
|
||||
Joins("JOIN categories pc ON pc.id = COALESCE(c.parent_id, c.id)").
|
||||
Joins("JOIN orders o ON oi.order_id = o.id").
|
||||
// Only teams take part in the revenue split
|
||||
Where("pc.is_team = ?", true).
|
||||
Where("o.organization_id = ?", organizationID).
|
||||
Where("o.is_void = ?", false).
|
||||
Where("o.is_refund = ?", false).
|
||||
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
|
||||
"apskel-pos-be/internal/entities"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
@@ -16,6 +17,10 @@ type CustomerAuthRepository interface {
|
||||
UpdateCustomer(ctx context.Context, customer *entities.Customer) error
|
||||
CheckPhoneNumberExists(ctx context.Context, phoneNumber string) (bool, 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 {
|
||||
@@ -78,3 +83,21 @@ func (r *customerAuthRepository) SetCustomerPassword(ctx context.Context, custom
|
||||
}
|
||||
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
|
||||
customerWalletHandler *handler.CustomerWalletHandler
|
||||
customerDeviceHandler *handler.CustomerDeviceHandler
|
||||
authMiddleware *middleware.AuthMiddleware
|
||||
customerOutletHandler *handler.CustomerOutletHandler
|
||||
customerOrderHandler *handler.CustomerOrderHandler
|
||||
authMiddleware *middleware.AuthMiddleware
|
||||
customerAuthMiddleware *middleware.CustomerAuthMiddleware
|
||||
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{
|
||||
config: cfg,
|
||||
@@ -119,6 +121,8 @@ func NewRouter(cfg *config.Config, healthHandler *handler.HealthHandler, authSer
|
||||
customerOrderPaymentHandler: handler.NewCustomerOrderPaymentHandler(customerOrderPaymentService),
|
||||
customerWalletHandler: handler.NewCustomerWalletHandler(customerWalletService),
|
||||
customerDeviceHandler: handler.NewCustomerDeviceHandler(customerDeviceService),
|
||||
customerOutletHandler: handler.NewCustomerOutletHandler(customerOutletService),
|
||||
customerOrderHandler: handler.NewCustomerOrderHandler(customerOrderService),
|
||||
redisClient: redisClient,
|
||||
}
|
||||
}
|
||||
@@ -179,6 +183,9 @@ func (r *Router) addAppRoutes(rg *gin.Engine) {
|
||||
customer.POST("/wallet/transfer", r.customerWalletHandler.Transfer)
|
||||
customer.PUT("/devices", r.customerDeviceHandler.Register)
|
||||
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)
|
||||
// PIN that approves moving EnakPoint and EnakCoin (docs/prd-point-coin.md F11)
|
||||
customer.GET("/pin/status", r.customerPinHandler.Status)
|
||||
@@ -367,8 +374,8 @@ func (r *Router) addAppRoutes(rg *gin.Engine) {
|
||||
analytics.GET("/purchasing", r.analyticsHandler.GetPurchasingAnalytics)
|
||||
analytics.GET("/products", r.analyticsHandler.GetProductAnalytics)
|
||||
analytics.GET("/categories", r.analyticsHandler.GetProductAnalyticsPerCategory)
|
||||
analytics.GET("/parent-categories", r.analyticsHandler.GetProductAnalyticsPerParentCategory)
|
||||
analytics.GET("/parent-categories/:parent_category_id", r.analyticsHandler.GetParentCategoryAnalyticsDetail)
|
||||
analytics.GET("/profit-sharing", r.analyticsHandler.GetProductAnalyticsPerParentCategory)
|
||||
analytics.GET("/profit-sharing/:parent_category_id", r.analyticsHandler.GetParentCategoryAnalyticsDetail)
|
||||
analytics.GET("/dashboard", r.analyticsHandler.GetDashboardAnalytics)
|
||||
analytics.GET("/profit-loss", r.analyticsHandler.GetProfitLossAnalytics)
|
||||
analytics.GET("/exclusive-summary/period", r.analyticsHandler.GetExclusiveSummaryPeriod)
|
||||
|
||||
@@ -44,6 +44,9 @@ func TestAllRoutesRegister(t *testing.T) {
|
||||
"POST /api/v1/customer/wallet/transfer",
|
||||
"PUT /api/v1/customer/devices",
|
||||
"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",
|
||||
"POST /api/v1/customer/orders/:id/pay-with-points",
|
||||
"GET /api/v1/customer/pin/status",
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
@@ -111,7 +111,7 @@ func (s *LoyaltySettingsServiceImpl) outletView(ctx context.Context, organizatio
|
||||
OutletID: outletID,
|
||||
OutletLoyaltySettings: settings,
|
||||
PointValue: pointValue,
|
||||
PointCashbackPercent: models.LoyaltyCashbackPercent(settings.Point.EarnValue, pointValue, settings.Point.EarnPerAmount),
|
||||
PointCashbackPercent: settings.Point.CashbackPercent(pointValue),
|
||||
Changes: changes,
|
||||
}, nil
|
||||
}
|
||||
|
||||
@@ -224,23 +224,23 @@ func getPLPctByID(rows []models.ProfitLossSummaryRow, id string) float64 {
|
||||
|
||||
// profitLossReportData holds data for the profit/loss PDF template
|
||||
type profitLossReportData struct {
|
||||
OrganizationName string
|
||||
MonthName string
|
||||
ReportDate string
|
||||
ReportDateUpper string
|
||||
TotalPenjualan string
|
||||
TotalBiaya string
|
||||
LabaRugi string
|
||||
LabaRugiClass string
|
||||
LabaRugiValueClass string
|
||||
LabaRugiMtd string
|
||||
LabaRugiMtdClass string
|
||||
OrganizationName string
|
||||
MonthName string
|
||||
ReportDate string
|
||||
ReportDateUpper string
|
||||
TotalPenjualan string
|
||||
TotalBiaya string
|
||||
LabaRugi string
|
||||
LabaRugiClass string
|
||||
LabaRugiValueClass string
|
||||
LabaRugiMtd string
|
||||
LabaRugiMtdClass string
|
||||
LabaRugiMtdValueClass string
|
||||
MainSummary []profitLossSummaryRowView
|
||||
PurchasingItems []profitLossPurchasingItem
|
||||
PurchasingTotal string
|
||||
GeneratedBy string
|
||||
PrintTime string
|
||||
MainSummary []profitLossSummaryRowView
|
||||
PurchasingItems []profitLossPurchasingItem
|
||||
PurchasingTotal string
|
||||
GeneratedBy string
|
||||
PrintTime string
|
||||
}
|
||||
|
||||
type profitLossSummaryRowView struct {
|
||||
|
||||
@@ -405,6 +405,9 @@ func ProductAnalyticsPerParentCategoryModelToContract(resp *models.ProductAnalyt
|
||||
data = append(data, contract.ProductAnalyticsPerParentCategoryData{
|
||||
ParentCategoryID: item.ParentCategoryID,
|
||||
ParentCategoryName: item.ParentCategoryName,
|
||||
OwnerFeePercent: item.OwnerFeePercent,
|
||||
TopProduct: parentCategoryTopProductModelToContract(item.TopProduct),
|
||||
SDL: item.SDL,
|
||||
TotalRevenue: item.TotalRevenue,
|
||||
TotalQuantity: item.TotalQuantity,
|
||||
CategoryCount: item.CategoryCount,
|
||||
@@ -427,16 +430,28 @@ func ProductAnalyticsPerParentCategoryModelToContract(resp *models.ProductAnalyt
|
||||
}
|
||||
}
|
||||
|
||||
// parentCategoryTopProductModelToContract converts the top product of a parent category to contract
|
||||
func parentCategoryTopProductModelToContract(product *models.ParentCategoryTopProduct) *contract.ParentCategoryTopProduct {
|
||||
if product == nil {
|
||||
return nil
|
||||
}
|
||||
return &contract.ParentCategoryTopProduct{
|
||||
ProductID: product.ProductID,
|
||||
ProductName: product.ProductName,
|
||||
QuantitySold: product.QuantitySold,
|
||||
Revenue: product.Revenue,
|
||||
}
|
||||
}
|
||||
|
||||
// budgetPeriodModelToContract converts one budget period to contract
|
||||
func budgetPeriodModelToContract(period models.BudgetPeriod) contract.BudgetPeriod {
|
||||
return contract.BudgetPeriod{
|
||||
PeriodStart: period.PeriodStart,
|
||||
PeriodEnd: period.PeriodEnd,
|
||||
Revenue: period.Revenue,
|
||||
OrderCount: period.OrderCount,
|
||||
LimitPurchase: period.LimitPurchase,
|
||||
LimitOwner: period.LimitOwner,
|
||||
LimitTeam: period.LimitTeam,
|
||||
PeriodStart: period.PeriodStart,
|
||||
PeriodEnd: period.PeriodEnd,
|
||||
Revenue: period.Revenue,
|
||||
OrderCount: period.OrderCount,
|
||||
SDL: period.SDL,
|
||||
LimitTeam: period.LimitTeam,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -458,9 +473,8 @@ func BudgetCutOffModelToContract(budget models.BudgetCutOff) contract.BudgetCutO
|
||||
|
||||
return contract.BudgetCutOff{
|
||||
Percentages: contract.BudgetPercentages{
|
||||
Purchase: budget.Percentages.Purchase,
|
||||
Owner: budget.Percentages.Owner,
|
||||
Team: budget.Percentages.Team,
|
||||
Owner: budget.Percentages.Owner,
|
||||
Team: budget.Percentages.Team,
|
||||
},
|
||||
CutOffFrom: budget.CutOffFrom,
|
||||
CutOffTo: budget.CutOffTo,
|
||||
@@ -528,6 +542,9 @@ func ParentCategoryAnalyticsDetailModelToContract(resp *models.ParentCategoryAna
|
||||
categories = append(categories, contract.ParentCategoryAnalyticsDetailData{
|
||||
CategoryID: category.CategoryID,
|
||||
CategoryName: category.CategoryName,
|
||||
OwnerFeePercent: category.OwnerFeePercent,
|
||||
SDL: category.SDL,
|
||||
TopProduct: parentCategoryTopProductModelToContract(category.TopProduct),
|
||||
TotalRevenue: category.TotalRevenue,
|
||||
TotalQuantity: category.TotalQuantity,
|
||||
ProductCount: category.ProductCount,
|
||||
@@ -548,6 +565,9 @@ func ParentCategoryAnalyticsDetailModelToContract(resp *models.ParentCategoryAna
|
||||
ParentCategoryID: resp.ParentCategoryID,
|
||||
ParentCategoryName: resp.ParentCategoryName,
|
||||
Summary: contract.ParentCategoryAnalyticsDetailSummary{
|
||||
OwnerFeePercent: resp.Summary.OwnerFeePercent,
|
||||
TopProduct: parentCategoryTopProductModelToContract(resp.Summary.TopProduct),
|
||||
SDL: resp.Summary.SDL,
|
||||
TotalRevenue: resp.Summary.TotalRevenue,
|
||||
TotalQuantity: resp.Summary.TotalQuantity,
|
||||
CategoryCount: resp.Summary.CategoryCount,
|
||||
|
||||
@@ -12,25 +12,32 @@ func CreateCategoryRequestToModel(apctx *appcontext.ContextInfo, req *contract.C
|
||||
order = *req.Order
|
||||
}
|
||||
return &models.CreateCategoryRequest{
|
||||
OrganizationID: apctx.OrganizationID,
|
||||
OutletID: req.OutletID,
|
||||
ParentID: req.ParentID,
|
||||
Name: req.Name,
|
||||
Description: req.Description,
|
||||
ImageURL: nil,
|
||||
Order: order,
|
||||
OrganizationID: apctx.OrganizationID,
|
||||
OutletID: req.OutletID,
|
||||
ParentID: req.ParentID,
|
||||
Name: req.Name,
|
||||
Description: req.Description,
|
||||
ImageURL: nil,
|
||||
Order: order,
|
||||
OwnerFeePercent: req.OwnerFeePercent,
|
||||
IsTeam: req.IsTeam,
|
||||
}
|
||||
}
|
||||
|
||||
func UpdateCategoryRequestToModel(req *contract.UpdateCategoryRequest) *models.UpdateCategoryRequest {
|
||||
return &models.UpdateCategoryRequest{
|
||||
Name: req.Name,
|
||||
Description: req.Description,
|
||||
ImageURL: nil,
|
||||
OutletID: req.OutletID,
|
||||
ParentID: req.ParentID,
|
||||
Order: req.Order,
|
||||
IsActive: nil,
|
||||
Name: req.Name,
|
||||
Description: req.Description,
|
||||
ImageURL: nil,
|
||||
OutletID: req.OutletID,
|
||||
ParentID: req.ParentID,
|
||||
Order: req.Order,
|
||||
OwnerFeePercent: req.OwnerFeePercent,
|
||||
IsTeam: req.IsTeam,
|
||||
IsActive: nil,
|
||||
|
||||
ClearParentID: req.ClearParentID,
|
||||
ClearOwnerFeePercent: req.ClearOwnerFeePercent,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -40,18 +47,20 @@ func CategoryModelResponseToResponse(cat *models.CategoryResponse) *contract.Cat
|
||||
}
|
||||
|
||||
return &contract.CategoryResponse{
|
||||
ID: cat.ID,
|
||||
OrganizationID: cat.OrganizationID,
|
||||
OutletID: cat.OutletID,
|
||||
ParentID: cat.ParentID,
|
||||
ParentName: cat.ParentName,
|
||||
Name: cat.Name,
|
||||
Description: cat.Description,
|
||||
BusinessType: "restaurant",
|
||||
Order: cat.Order,
|
||||
Metadata: map[string]interface{}{},
|
||||
CreatedAt: cat.CreatedAt,
|
||||
UpdatedAt: cat.UpdatedAt,
|
||||
ID: cat.ID,
|
||||
OrganizationID: cat.OrganizationID,
|
||||
OutletID: cat.OutletID,
|
||||
ParentID: cat.ParentID,
|
||||
ParentName: cat.ParentName,
|
||||
Name: cat.Name,
|
||||
Description: cat.Description,
|
||||
BusinessType: "restaurant",
|
||||
Order: cat.Order,
|
||||
OwnerFeePercent: cat.OwnerFeePercent,
|
||||
IsTeam: cat.IsTeam,
|
||||
Metadata: map[string]interface{}{},
|
||||
CreatedAt: cat.CreatedAt,
|
||||
UpdatedAt: cat.UpdatedAt,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -37,6 +37,10 @@ func (v *CategoryValidatorImpl) ValidateCreateCategoryRequest(req *contract.Crea
|
||||
return errors.New("description cannot exceed 1000 characters"), constants.MalformedFieldErrorCode
|
||||
}
|
||||
|
||||
if req.OwnerFeePercent != nil && (*req.OwnerFeePercent < 0 || *req.OwnerFeePercent > 100) {
|
||||
return errors.New("owner_fee_percent must be between 0 and 100"), constants.MalformedFieldErrorCode
|
||||
}
|
||||
|
||||
if req.BusinessType != nil && strings.TrimSpace(*req.BusinessType) != "" {
|
||||
validBusinessTypes := map[string]bool{
|
||||
"restaurant": true,
|
||||
@@ -59,7 +63,7 @@ func (v *CategoryValidatorImpl) ValidateUpdateCategoryRequest(req *contract.Upda
|
||||
}
|
||||
|
||||
// At least one field should be provided for update
|
||||
if req.Name == nil && req.Description == nil && req.BusinessType == nil && req.ParentID == nil && req.Metadata == nil {
|
||||
if req.Name == nil && req.Description == nil && req.BusinessType == nil && req.ParentID == nil && req.Metadata == nil && req.OwnerFeePercent == nil && req.IsTeam == nil && req.Order == nil && req.OutletID == nil && !req.ClearParentID && !req.ClearOwnerFeePercent {
|
||||
return errors.New("at least one field must be provided for update"), constants.MissingFieldErrorCode
|
||||
}
|
||||
|
||||
@@ -76,6 +80,10 @@ func (v *CategoryValidatorImpl) ValidateUpdateCategoryRequest(req *contract.Upda
|
||||
return errors.New("description cannot exceed 1000 characters"), constants.MalformedFieldErrorCode
|
||||
}
|
||||
|
||||
if req.OwnerFeePercent != nil && (*req.OwnerFeePercent < 0 || *req.OwnerFeePercent > 100) {
|
||||
return errors.New("owner_fee_percent must be between 0 and 100"), constants.MalformedFieldErrorCode
|
||||
}
|
||||
|
||||
if req.BusinessType != nil && strings.TrimSpace(*req.BusinessType) != "" {
|
||||
validBusinessTypes := map[string]bool{
|
||||
"restaurant": true,
|
||||
|
||||
@@ -5,6 +5,8 @@ import (
|
||||
"regexp"
|
||||
"strings"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"apskel-pos-be/internal/constants"
|
||||
"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
|
||||
}
|
||||
|
||||
// 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
|
||||
if strings.TrimSpace(req.BirthDate) == "" {
|
||||
return errors.New("birth date is required"), constants.ValidationErrorCode
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
ALTER TABLE categories DROP COLUMN owner_fee_percent;
|
||||
@@ -0,0 +1,4 @@
|
||||
-- The owner's share of revenue in the parent category budget report. NULL keeps the
|
||||
-- default share, so only the parent categories with a different fee carry a value.
|
||||
ALTER TABLE categories ADD COLUMN owner_fee_percent NUMERIC(5,2)
|
||||
CONSTRAINT chk_categories_owner_fee_percent CHECK (owner_fee_percent >= 0 AND owner_fee_percent <= 100);
|
||||
@@ -0,0 +1 @@
|
||||
ALTER TABLE categories DROP COLUMN is_team;
|
||||
@@ -0,0 +1,4 @@
|
||||
-- Whether a parent category is a team: it can be charged with purchases and cash
|
||||
-- advances, and its revenue takes part in the parent category budget split. Every
|
||||
-- existing category stays a team, since that is how parent categories were treated.
|
||||
ALTER TABLE categories ADD COLUMN is_team BOOLEAN NOT NULL DEFAULT TRUE;
|
||||
Reference in New Issue
Block a user