From c6062c4bb90bfddf9e88d3070f9515babdbbbeaf Mon Sep 17 00:00:00 2001 From: efrilm Date: Wed, 30 Sep 2026 15:31:11 +0700 Subject: [PATCH 1/5] Reapply "feat(loyalty): EnakPoint & EnakCoin" (#32) This reverts commit 4e24f9bbb0e6313ddc6a00a95b53c0071cba877d. --- Makefile | 8 + cmd/wallet-migrate/main.go | 73 ++ docs/api-enakpoint.md | 439 ++++++++++ docs/backoffice-enakpoint.md | 305 +++++++ docs/integration-enakpoint.md | 635 ++++++++++++++ go.mod | 2 + go.sum | 4 + internal/app/app.go | 150 +++- internal/constants/error.go | 26 +- internal/constants/loyalty.go | 86 ++ internal/constants/payment.go | 3 + internal/constants/wallet.go | 44 + internal/contract/analytics_contract.go | 6 + internal/contract/campaign_contract.go | 10 +- internal/contract/customer_device_contract.go | 11 + internal/contract/customer_pin_contract.go | 39 + internal/contract/customer_points_contract.go | 58 -- internal/contract/customer_tokens_contract.go | 52 -- internal/contract/game_play_contract.go | 25 +- internal/contract/order_contract.go | 44 +- internal/contract/payment_method_contract.go | 14 +- internal/contract/spin_game_contract.go | 8 +- internal/contract/wallet_contract.go | 31 + internal/entities/analytics.go | 20 +- internal/entities/campaign.go | 25 +- internal/entities/campaign_test.go | 18 + internal/entities/entities.go | 6 + internal/entities/game_play.go | 2 +- internal/entities/loyalty_setting_change.go | 34 + internal/entities/payment.go | 21 +- internal/entities/wallet.go | 113 +++ internal/handler/customer_device_handler.go | 45 + .../handler/customer_order_payment_handler.go | 35 + internal/handler/customer_pin_handler.go | 151 ++++ internal/handler/customer_points_handler.go | 82 +- internal/handler/customer_wallet_db_test.go | 218 +++++ internal/handler/customer_wallet_handler.go | 92 ++ internal/handler/gamification_handler.go | 471 ----------- internal/handler/loyalty_settings_db_test.go | 169 ++++ internal/handler/loyalty_settings_handler.go | 117 +++ .../handler/loyalty_settings_org_db_test.go | 180 ++++ internal/handler/order_handler.go | 13 + internal/handler/payment_method_handler.go | 10 + internal/handler/point_payment_handler.go | 28 + internal/handler/spin_game_handler.go | 11 +- internal/handler/wallet_admin_db_test.go | 203 +++++ internal/handler/wallet_admin_handler.go | 99 +++ internal/mappers/campaign_mapper.go | 8 +- internal/mappers/customer_points_mapper.go | 46 - internal/mappers/customer_tokens_mapper.go | 48 -- internal/mappers/game_play_mapper.go | 4 +- internal/mappers/order_mapper.go | 2 + internal/mappers/payment_method_mapper.go | 1 + internal/mappers/spin_game_mapper.go | 6 +- internal/middleware/auth_middleware.go | 8 + internal/models/analytics.go | 27 +- internal/models/campaign.go | 10 +- internal/models/customer_pin.go | 47 ++ internal/models/customer_points.go | 71 +- internal/models/customer_tokens.go | 44 - internal/models/game_play.go | 14 +- internal/models/loyalty.go | 193 +++++ internal/models/loyalty_test.go | 32 + internal/models/order.go | 3 + internal/models/payment.go | 9 +- internal/models/payment_method.go | 12 +- internal/models/spin_game.go | 6 +- internal/models/wallet.go | 166 ++++ internal/models/wallet_move.go | 73 ++ internal/models/wallet_trace.go | 46 + internal/processor/analytics_processor.go | 29 +- .../processor/analytics_processor_test.go | 38 +- internal/processor/campaign_processor.go | 8 +- .../processor/customer_device_processor.go | 77 ++ .../customer_device_processor_test.go | 136 +++ internal/processor/customer_pin_processor.go | 471 +++++++++++ .../customer_pin_processor_db_test.go | 257 ++++++ .../processor/customer_pin_processor_test.go | 107 +++ .../processor/customer_points_processor.go | 219 ++--- .../processor/customer_tokens_processor.go | 198 ----- internal/processor/earning_calculator.go | 85 ++ internal/processor/earning_calculator_test.go | 121 +++ internal/processor/earning_processor.go | 217 +++++ .../processor/earning_processor_db_test.go | 233 ++++++ internal/processor/earning_reversal.go | 167 ++++ .../processor/earning_reversal_db_test.go | 206 +++++ internal/processor/earning_reversal_test.go | 25 + internal/processor/game_play_processor.go | 244 ++++-- .../processor/game_play_processor_db_test.go | 69 ++ .../processor/game_play_processor_test.go | 245 ++++++ internal/processor/loyalty_expiry.go | 170 ++++ internal/processor/loyalty_expiry_test.go | 115 +++ .../processor/loyalty_settings_processor.go | 530 ++++++++++++ .../loyalty_settings_processor_test.go | 385 +++++++++ internal/processor/order_paid_hook_test.go | 272 ++++++ internal/processor/order_processor.go | 255 +++++- internal/processor/otp_processor.go | 4 + internal/processor/payment_code_processor.go | 101 +++ .../processor/payment_code_processor_test.go | 136 +++ .../processor/payment_method_processor.go | 39 +- internal/processor/point_payment_db_test.go | 401 +++++++++ .../processor/point_payment_method_db_test.go | 118 +++ internal/processor/point_payment_processor.go | 336 ++++++++ .../processor/point_payment_processor_test.go | 39 + internal/processor/point_payment_refund.go | 157 ++++ internal/processor/point_refund_db_test.go | 151 ++++ internal/processor/wallet_admin_processor.go | 223 +++++ .../processor/wallet_exchange_processor.go | 289 +++++++ .../wallet_exchange_processor_test.go | 354 ++++++++ internal/processor/wallet_expiry_processor.go | 196 +++++ .../processor/wallet_expiry_processor_test.go | 244 ++++++ .../processor/wallet_migration_processor.go | 184 ++++ .../wallet_migration_processor_db_test.go | 167 ++++ internal/processor/wallet_move_db_test.go | 237 ++++++ internal/processor/wallet_processor.go | 583 +++++++++++++ .../processor/wallet_processor_db_test.go | 142 ++++ internal/processor/wallet_processor_test.go | 788 ++++++++++++++++++ internal/processor/wallet_query_processor.go | 336 ++++++++ .../processor/wallet_query_processor_test.go | 266 ++++++ internal/processor/wallet_trace_processor.go | 180 ++++ .../processor/wallet_trace_processor_test.go | 161 ++++ .../processor/wallet_transfer_processor.go | 307 +++++++ .../wallet_transfer_processor_test.go | 243 ++++++ internal/repository/analytics_repository.go | 19 +- .../repository/customer_device_repository.go | 84 ++ .../repository/customer_pin_repository.go | 220 +++++ .../repository/customer_points_repository.go | 97 --- .../repository/customer_tokens_repository.go | 131 --- internal/repository/earning_repository.go | 275 ++++++ internal/repository/game_play_repository.go | 14 +- internal/repository/game_prize_repository.go | 31 +- internal/repository/game_repository.go | 16 +- .../repository/loyalty_settings_repository.go | 219 +++++ .../loyalty_settings_repository_test.go | 149 ++++ .../repository/payment_code_repository.go | 103 +++ .../repository/payment_method_repository.go | 2 + .../repository/point_payment_repository.go | 339 ++++++++ internal/repository/tx_manager.go | 7 + .../repository/wallet_admin_repository.go | 126 +++ .../repository/wallet_expiry_repository.go | 118 +++ .../repository/wallet_migration_repository.go | 134 +++ internal/repository/wallet_move_repository.go | 82 ++ .../repository/wallet_query_repository.go | 202 +++++ .../wallet_reconciliation_repository.go | 160 ++++ .../wallet_reconciliation_repository_test.go | 141 ++++ internal/repository/wallet_repository.go | 295 +++++++ internal/repository/wallet_repository_test.go | 353 ++++++++ .../repository/wallet_trace_repository.go | 109 +++ internal/router/router.go | 79 +- internal/router/router_test.go | 59 ++ internal/service/campaign_service.go | 14 +- internal/service/customer_device_service.go | 58 ++ .../service/customer_order_payment_service.go | 34 + internal/service/customer_pin_service.go | 140 ++++ internal/service/customer_pin_service_test.go | 50 ++ internal/service/customer_points_service.go | 16 + internal/service/customer_wallet_service.go | 91 ++ internal/service/earning_backfill_job.go | 74 ++ internal/service/earning_backfill_job_test.go | 46 + internal/service/gamification_service.go | 174 +--- internal/service/loyalty_settings_service.go | 224 +++++ internal/service/order_service.go | 3 +- internal/service/order_service_table_test.go | 8 + internal/service/payment_method_service.go | 17 +- internal/service/point_payment_service.go | 55 ++ internal/service/spin_game_service.go | 36 +- internal/service/wallet_admin_service.go | 82 ++ internal/service/wallet_expiry_job.go | 77 ++ internal/service/wallet_reconciliation_job.go | 212 +++++ .../service/wallet_reconciliation_job_test.go | 110 +++ internal/transformer/analytics_transformer.go | 7 + .../transformer/gamification_transformer.go | 134 +-- internal/transformer/order_transformer.go | 6 + .../transformer/order_transformer_test.go | 14 + internal/validator/campaign_validator.go | 16 +- internal/validator/gamification_validator.go | 168 +--- .../validator/payment_method_validator.go | 1 + internal/validator/wallet_validator.go | 66 ++ internal/validator/wallet_validator_test.go | 43 + .../000090_create_wallet_tables.down.sql | 4 + migrations/000090_create_wallet_tables.up.sql | 131 +++ ...0091_create_organization_settings.down.sql | 2 + ...000091_create_organization_settings.up.sql | 35 + ...2_rename_campaign_tokens_to_coins.down.sql | 5 + ...092_rename_campaign_tokens_to_coins.up.sql | 7 + migrations/000093_add_customer_pin.down.sql | 9 + migrations/000093_add_customer_pin.up.sql | 32 + .../000094_add_point_payment_method.down.sql | 16 + .../000094_add_point_payment_method.up.sql | 45 + ...me_plays_token_used_to_coins_used.down.sql | 2 + ...game_plays_token_used_to_coins_used.up.sql | 4 + .../000096_create_customer_devices.down.sql | 1 + .../000096_create_customer_devices.up.sql | 17 + ...97_create_wallet_expiry_reminders.down.sql | 1 + ...0097_create_wallet_expiry_reminders.up.sql | 11 + 195 files changed, 20058 insertions(+), 2177 deletions(-) create mode 100644 cmd/wallet-migrate/main.go create mode 100644 docs/api-enakpoint.md create mode 100644 docs/backoffice-enakpoint.md create mode 100644 docs/integration-enakpoint.md create mode 100644 internal/constants/loyalty.go create mode 100644 internal/constants/wallet.go create mode 100644 internal/contract/customer_device_contract.go create mode 100644 internal/contract/customer_pin_contract.go delete mode 100644 internal/contract/customer_tokens_contract.go create mode 100644 internal/contract/wallet_contract.go create mode 100644 internal/entities/campaign_test.go create mode 100644 internal/entities/loyalty_setting_change.go create mode 100644 internal/entities/wallet.go create mode 100644 internal/handler/customer_device_handler.go create mode 100644 internal/handler/customer_order_payment_handler.go create mode 100644 internal/handler/customer_pin_handler.go create mode 100644 internal/handler/customer_wallet_db_test.go create mode 100644 internal/handler/customer_wallet_handler.go create mode 100644 internal/handler/loyalty_settings_db_test.go create mode 100644 internal/handler/loyalty_settings_handler.go create mode 100644 internal/handler/loyalty_settings_org_db_test.go create mode 100644 internal/handler/point_payment_handler.go create mode 100644 internal/handler/wallet_admin_db_test.go create mode 100644 internal/handler/wallet_admin_handler.go delete mode 100644 internal/mappers/customer_points_mapper.go delete mode 100644 internal/mappers/customer_tokens_mapper.go create mode 100644 internal/models/customer_pin.go delete mode 100644 internal/models/customer_tokens.go create mode 100644 internal/models/loyalty.go create mode 100644 internal/models/loyalty_test.go create mode 100644 internal/models/wallet.go create mode 100644 internal/models/wallet_move.go create mode 100644 internal/models/wallet_trace.go create mode 100644 internal/processor/customer_device_processor.go create mode 100644 internal/processor/customer_device_processor_test.go create mode 100644 internal/processor/customer_pin_processor.go create mode 100644 internal/processor/customer_pin_processor_db_test.go create mode 100644 internal/processor/customer_pin_processor_test.go delete mode 100644 internal/processor/customer_tokens_processor.go create mode 100644 internal/processor/earning_calculator.go create mode 100644 internal/processor/earning_calculator_test.go create mode 100644 internal/processor/earning_processor.go create mode 100644 internal/processor/earning_processor_db_test.go create mode 100644 internal/processor/earning_reversal.go create mode 100644 internal/processor/earning_reversal_db_test.go create mode 100644 internal/processor/earning_reversal_test.go create mode 100644 internal/processor/game_play_processor_db_test.go create mode 100644 internal/processor/game_play_processor_test.go create mode 100644 internal/processor/loyalty_expiry.go create mode 100644 internal/processor/loyalty_expiry_test.go create mode 100644 internal/processor/loyalty_settings_processor.go create mode 100644 internal/processor/loyalty_settings_processor_test.go create mode 100644 internal/processor/order_paid_hook_test.go create mode 100644 internal/processor/payment_code_processor.go create mode 100644 internal/processor/payment_code_processor_test.go create mode 100644 internal/processor/point_payment_db_test.go create mode 100644 internal/processor/point_payment_method_db_test.go create mode 100644 internal/processor/point_payment_processor.go create mode 100644 internal/processor/point_payment_processor_test.go create mode 100644 internal/processor/point_payment_refund.go create mode 100644 internal/processor/point_refund_db_test.go create mode 100644 internal/processor/wallet_admin_processor.go create mode 100644 internal/processor/wallet_exchange_processor.go create mode 100644 internal/processor/wallet_exchange_processor_test.go create mode 100644 internal/processor/wallet_expiry_processor.go create mode 100644 internal/processor/wallet_expiry_processor_test.go create mode 100644 internal/processor/wallet_migration_processor.go create mode 100644 internal/processor/wallet_migration_processor_db_test.go create mode 100644 internal/processor/wallet_move_db_test.go create mode 100644 internal/processor/wallet_processor.go create mode 100644 internal/processor/wallet_processor_db_test.go create mode 100644 internal/processor/wallet_processor_test.go create mode 100644 internal/processor/wallet_query_processor.go create mode 100644 internal/processor/wallet_query_processor_test.go create mode 100644 internal/processor/wallet_trace_processor.go create mode 100644 internal/processor/wallet_trace_processor_test.go create mode 100644 internal/processor/wallet_transfer_processor.go create mode 100644 internal/processor/wallet_transfer_processor_test.go create mode 100644 internal/repository/customer_device_repository.go create mode 100644 internal/repository/customer_pin_repository.go delete mode 100644 internal/repository/customer_points_repository.go delete mode 100644 internal/repository/customer_tokens_repository.go create mode 100644 internal/repository/earning_repository.go create mode 100644 internal/repository/loyalty_settings_repository.go create mode 100644 internal/repository/loyalty_settings_repository_test.go create mode 100644 internal/repository/payment_code_repository.go create mode 100644 internal/repository/point_payment_repository.go create mode 100644 internal/repository/wallet_admin_repository.go create mode 100644 internal/repository/wallet_expiry_repository.go create mode 100644 internal/repository/wallet_migration_repository.go create mode 100644 internal/repository/wallet_move_repository.go create mode 100644 internal/repository/wallet_query_repository.go create mode 100644 internal/repository/wallet_reconciliation_repository.go create mode 100644 internal/repository/wallet_reconciliation_repository_test.go create mode 100644 internal/repository/wallet_repository.go create mode 100644 internal/repository/wallet_repository_test.go create mode 100644 internal/repository/wallet_trace_repository.go create mode 100644 internal/router/router_test.go create mode 100644 internal/service/customer_device_service.go create mode 100644 internal/service/customer_order_payment_service.go create mode 100644 internal/service/customer_pin_service.go create mode 100644 internal/service/customer_pin_service_test.go create mode 100644 internal/service/customer_wallet_service.go create mode 100644 internal/service/earning_backfill_job.go create mode 100644 internal/service/earning_backfill_job_test.go create mode 100644 internal/service/loyalty_settings_service.go create mode 100644 internal/service/point_payment_service.go create mode 100644 internal/service/wallet_admin_service.go create mode 100644 internal/service/wallet_expiry_job.go create mode 100644 internal/service/wallet_reconciliation_job.go create mode 100644 internal/service/wallet_reconciliation_job_test.go create mode 100644 internal/validator/wallet_validator.go create mode 100644 internal/validator/wallet_validator_test.go create mode 100644 migrations/000090_create_wallet_tables.down.sql create mode 100644 migrations/000090_create_wallet_tables.up.sql create mode 100644 migrations/000091_create_organization_settings.down.sql create mode 100644 migrations/000091_create_organization_settings.up.sql create mode 100644 migrations/000092_rename_campaign_tokens_to_coins.down.sql create mode 100644 migrations/000092_rename_campaign_tokens_to_coins.up.sql create mode 100644 migrations/000093_add_customer_pin.down.sql create mode 100644 migrations/000093_add_customer_pin.up.sql create mode 100644 migrations/000094_add_point_payment_method.down.sql create mode 100644 migrations/000094_add_point_payment_method.up.sql create mode 100644 migrations/000095_rename_game_plays_token_used_to_coins_used.down.sql create mode 100644 migrations/000095_rename_game_plays_token_used_to_coins_used.up.sql create mode 100644 migrations/000096_create_customer_devices.down.sql create mode 100644 migrations/000096_create_customer_devices.up.sql create mode 100644 migrations/000097_create_wallet_expiry_reminders.down.sql create mode 100644 migrations/000097_create_wallet_expiry_reminders.up.sql diff --git a/Makefile b/Makefile index 6b79f01..48f2b97 100644 --- a/Makefile +++ b/Makefile @@ -42,6 +42,7 @@ help: @echo " migration-up Up migrations" @echo " migration-up ENV=production Up migrations (production DB)" @echo " migration-down Down last migration" + @echo " wallet-migrate args=-dry-run Move legacy points/tokens into the wallet" @echo @echo " docker-up Up docker services" @echo " docker-down Down docker services" @@ -105,6 +106,13 @@ migration-down: migration-force: @migrate -database $(DB_URL) -path ./migrations force $(version) +# Move customer_points / customer_tokens into the wallet. Safe to run again. +# Pass args=-dry-run to only report. + +.SILENT: wallet-migrate +wallet-migrate: + ENV_MODE=$(ENV) go run ./cmd/wallet-migrate $(args) + .SILENT: seeder-create seeder-create: @migrate create -ext sql -dir ./seeders -seq $(name) diff --git a/cmd/wallet-migrate/main.go b/cmd/wallet-migrate/main.go new file mode 100644 index 0000000..7cd2652 --- /dev/null +++ b/cmd/wallet-migrate/main.go @@ -0,0 +1,73 @@ +// Command wallet-migrate moves customer_points and customer_tokens balances into the +// EnakPoint & EnakCoin wallet (docs/prd-point-coin.md §10). Safe to run more than once: +// each run credits only what earlier runs have not. +// +// ENV_MODE=staging go run ./cmd/wallet-migrate -dry-run +// ENV_MODE=staging go run ./cmd/wallet-migrate +// +// It exits non-zero when the legacy totals and the migrated totals disagree. +package main + +import ( + "context" + "flag" + "fmt" + "log" + "os" + + "apskel-pos-be/config" + "apskel-pos-be/internal/db" + "apskel-pos-be/internal/processor" + "apskel-pos-be/internal/repository" +) + +func main() { + dryRun := flag.Bool("dry-run", false, "report what would be credited without writing anything") + batchSize := flag.Int("batch", 500, "customers read per batch") + flag.Parse() + + cfg := config.LoadConfig() + pg, err := db.NewPostgres(cfg.Database) + if err != nil { + log.Fatal(err) + } + + migrator := processor.NewWalletMigrationProcessor( + repository.NewWalletMigrationRepository(pg), + processor.NewWalletProcessor(repository.NewWalletRepository(pg)), + repository.NewTxManager(pg), + ) + report, err := migrator.Run(context.Background(), *dryRun, *batchSize) + if err != nil { + log.Fatalf("wallet migration failed: %v", err) + } + + verb := "credited" + if report.DryRun { + verb = "would credit" + } + t := report.Totals + fmt.Printf("customers scanned: %d\n", report.CustomersScanned) + fmt.Printf("EnakPoint: %s %d in %d rows\n", verb, report.PointsCredited, report.PointCredits) + fmt.Printf("EnakCoin: %s %d in %d rows\n", verb, report.CoinsCredited, report.CoinCredits) + fmt.Printf("\n%-10s %15s %15s %15s\n", "", "legacy", "migrated", "wallet balance") + fmt.Printf("%-10s %15d %15d %15d\n", "EnakPoint", t.LegacyPoints, t.MigratedPoints, t.WalletPoints) + fmt.Printf("%-10s %15d %15d %15d\n", "EnakCoin", t.LegacyCoins, t.MigratedCoins, t.WalletCoins) + + if len(report.Discrepancies) > 0 { + fmt.Printf("\n%d balances shrank in the legacy tables after they were migrated.\n", len(report.Discrepancies)) + fmt.Println("They were left as they are in the wallet; correct them with an adjustment if needed:") + for _, d := range report.Discrepancies { + fmt.Printf(" customer %s %s: legacy %d, migrated %d\n", d.CustomerID, d.Currency, d.Legacy, d.Migrated) + } + } + + if report.DryRun { + return + } + if !report.Balanced() { + fmt.Println("\nNOT BALANCED: legacy and migrated totals differ") + os.Exit(1) + } + fmt.Println("\nbalanced: legacy totals = migrated totals") +} diff --git a/docs/api-enakpoint.md b/docs/api-enakpoint.md new file mode 100644 index 0000000..8bd3837 --- /dev/null +++ b/docs/api-enakpoint.md @@ -0,0 +1,439 @@ +# API EnakPoint & EnakCoin + +30 Sep 2026 + +Semua endpoint EnakPoint (`POINT`, bisa bayar order) dan EnakCoin (`COIN`, untuk game dan ditukar ke EnakPoint) ada di bawah base URL `/api/v1`, memakai satu format response, dan semua jumlah berupa bilangan bulat. + +## Konvensi umum + +| Klien | Autentikasi | Prefix | +| --- | --- | --- | +| Customer app / self-order | `Authorization: Bearer ` | `/api/v1/customer` | +| POS | Token user (kasir/manager) | `/api/v1` | +| Dashboard | Token user, role Admin atau Manager | `/api/v1/marketing`, `/api/v1/outlets` | + +**Format response.** Sukses: `{"success": true, "data": {…}, "errors": null}`. Gagal: `{"success": false, "data": null, "errors": [{"code": "304", "entity": "wallet_service", "cause": "…"}]}`. Tampilkan `cause` sebagai alasan penolakan. + +| `code` | HTTP | Arti | +| --- | --- | --- | +| `303`, `310` | 400 | Body atau parameter tidak lengkap / salah format | +| `304` | 400 | Ditolak aturan bisnis (saldo kurang, di luar batas, dst.) | +| `404` | 404 | Tidak ditemukan, juga untuk data milik customer atau organisasi lain | +| `429` | 429 | OTP diminta ulang terlalu cepat | +| `PIN_NOT_SET` | 403 | Customer belum membuat PIN | +| `PIN_INVALID` | 400 | PIN salah | +| `PIN_LOCKED` | 423 | PIN terkunci 30 menit setelah 5 kali salah | +| `TRANSFER_BLOCKED` | 403 | Transfer ditahan 24 jam setelah reset PIN | +| `900` | 500 | Kesalahan server | + +**Error PIN** membawa `data` yang tidak `null`: `{"code": "PIN_INVALID", "remaining_attempts": 3}`, `{"code": "PIN_LOCKED", "locked_until": "…"}`, atau `{"code": "TRANSFER_BLOCKED", "transfer_blocked_until": "…"}`. Endpoint yang menerima `pin` bisa mengembalikan salah satunya. PIN selalu dikirim sebagai string 6 digit. + +**Idempotency.** Exchange dan transfer wajib header `Idempotency-Key` (maks. 50 karakter, `X-Idempotency-Key` juga diterima): satu key per percobaan, dan key yang sama dipakai ulang saat retry. Retry mengembalikan hasil pertama dengan `replayed: true`. `POST /payments` wajib `X-Idempotency-Key` seperti pembayaran lain. + +**Waktu.** Tanggal kedaluwarsa dan filter tanggal memakai WIB. Saldo berlaku sampai 23:59:59 WIB pada tanggal kedaluwarsanya. + +## Customer app: saldo & riwayat + +| Method | Path | Keterangan | +| --- | --- | --- | +| GET | `/customer/wallet` | Saldo, nilai rupiah, kedaluwarsa terdekat, 5 mutasi terakhir | +| GET | `/customer/wallet/transactions` | Riwayat mutasi, dengan pagination dan filter | +| GET | `/customer/wallet/expiring` | Saldo yang akan kedaluwarsa, per currency dan tanggal | +| PUT | `/customer/devices` | Daftarkan token FCM device | +| DELETE | `/customer/devices/:device_id` | Hapus device saat logout | + +### GET /customer/wallet + +```json +{ + "point_balance": 12500, + "coin_balance": 8, + "point_value": 1, + "point_discount_value": 12500, + "nearest_expiring": { + "point": { "amount": 150, "date": "2026-12-31" }, + "coin": null + }, + "recent_transactions": [ "… sama seperti item riwayat …" ] +} +``` + +- `point_balance` / `coin_balance` = saldo yang bisa dipakai sekarang. +- `point_discount_value` = `point_balance × point_value`; tampilkan sebagai "setara potongan Rp …", bukan saldo uang. +- `nearest_expiring.point` / `.coin` bernilai `null` bila tidak ada yang akan kedaluwarsa. + +### GET /customer/wallet/transactions + +| Query | Tipe | Keterangan | +| --- | --- | --- | +| `page` | int | Default 1 | +| `limit` | int | 1–100, default 20 | +| `currency` | `POINT` \| `COIN` | Opsional | +| `type` | string | Satu tipe atau beberapa dipisah koma, mis. `EARN,PAYMENT` | +| `from`, `to` | `YYYY-MM-DD` | Tanggal WIB, inklusif | + +```json +{ + "data": [ + { + "id": "…", + "currency": "POINT", + "type": "EARN", + "amount": 875, + "balance_after": 12500, + "description": "Belanja #ORD-0123 di Outlet Kemang", + "source": { "type": "ORDER", "id": "…" }, + "outlet_id": "…", + "group_id": null, + "expires_at": "2026-12-31T23:59:59+07:00", + "lots": [{ "amount": 875, "remaining": 875, "expires_at": "2026-12-31T23:59:59+07:00" }], + "created_at": "2026-09-30T12:01:00Z" + } + ], + "pagination": { "page": 1, "limit": 20, "total_count": 42, "total_pages": 3 } +} +``` + +`amount` bertanda (+ menambah, − mengurangi). Penambahan membawa `source`, pengurangan membawa `destination`, keduanya `{ type, id }`. Dua baris exchange atau transfer berbagi `group_id`. Daftar tipe ada di bagian Referensi. + +### GET /customer/wallet/expiring + +```json +{ + "point": [ + { "amount": 150, "date": "2026-10-31" }, + { "amount": 200, "date": "2026-12-31" } + ], + "coin": [] +} +``` + +Terurut dari tanggal terdekat. Daftar kosong berarti tidak ada yang akan kedaluwarsa. + +### PUT /customer/devices + +```json +{ "device_id": "a1b2c3", "fcm_token": "…", "platform": "android", "app_version": "2.4.0" } +``` + +Panggil setelah login dan setiap kali FCM memberi token baru. `device_id` dan `fcm_token` wajib; `platform` = `android` | `ios` | `web`. Satu token hanya milik satu customer: customer lain yang mendaftarkan token yang sama mengambil alih HP itu. Response: `{ "device_id": "a1b2c3" }`. + +## Customer app: PIN + +PIN 6 digit wajib untuk bayar, kode bayar, exchange, dan transfer; minta customer membuatnya saat pertama kali melakukan aksi itu. + +| Method | Path | Body | Response | +| --- | --- | --- | --- | +| GET | `/customer/pin/status` | – | `{ "has_pin", "locked_until", "transfer_blocked_until" }` | +| POST | `/customer/pin/otp` | `{ "purpose": "pin_setup" }` atau `"pin_reset"` | `{ "purpose", "otp_token", "expires_at" }` | +| POST | `/customer/pin` | `{ "otp_token", "otp_code", "pin", "confirm_pin" }` | Status PIN | +| PUT | `/customer/pin` | `{ "old_pin", "pin", "confirm_pin" }` | Status PIN | +| POST | `/customer/pin/reset` | `{ "otp_token", "otp_code", "pin", "confirm_pin" }` | Status PIN | + +1. **Buat PIN:** minta OTP dengan `purpose: "pin_setup"` (dikirim lewat WhatsApp), lalu `POST /customer/pin` dengan `otp_token` dari response OTP dan kode yang diterima customer. +2. **Lupa PIN:** minta OTP dengan `purpose: "pin_reset"`, lalu `POST /customer/pin/reset`. Reset membuka kunci PIN, tapi transfer keluar ditahan 24 jam; pembayaran dan exchange tetap bisa. +3. **Ganti PIN:** `PUT /customer/pin` dengan PIN lama. + +PIN baru ditolak `304` bila bukan 6 digit, konfirmasinya beda, semua digit sama (`111111`), berurutan (`123456`, `654321`), atau sama dengan tanggal lahir (`DDMMYY` / `YYMMDD`). OTP yang diminta terlalu cepat dijawab `429`. Penanganan `PIN_INVALID`, `PIN_LOCKED`, dan `TRANSFER_BLOCKED` ada di Konvensi umum. + +## Customer app: bayar, exchange, transfer, game + +| Method | Path | PIN | Idempotency-Key | +| --- | --- | --- | --- | +| POST | `/customer/wallet/payment-code` | Ya | – | +| POST | `/customer/orders/:id/pay-with-points` | Ya | – | +| GET | `/customer/wallet/exchange/preview?coins=` | – | – | +| POST | `/customer/wallet/exchange` | Ya | Wajib | +| GET | `/customer/wallet/transfer/recipient?phone=` | – | – | +| POST | `/customer/wallet/transfer` | Ya | Wajib | +| POST | `/customer/spin` | – | – | + +### POST /customer/wallet/payment-code + +Body `{ "pin": "482913" }`. Response: + +```json +{ "code": "482913", "qr_payload": "enakpoint:482913", "expires_at": "2026-09-30T05:02:00Z" } +``` + +Tampilkan `code` sebagai angka dan `qr_payload` sebagai QR untuk kasir. Berlaku 2 menit, sekali pakai, hanya untuk customer ini; kode baru membatalkan kode lama. + +### POST /customer/orders/:id/pay-with-points + +Body `{ "points": 12500, "pin": "482913" }`. Hanya untuk order milik customer yang login (order lain `404`). Response sama dengan pembayaran POS (bagian POS). Batas dan aturan penolakan juga sama. + +### GET /customer/wallet/exchange/preview?coins=30 + +```json +{ "coin_amount": 10, "point_amount": 3, "coin_balance": 35, "coins": 30, "points": 9, "valid": true } +``` + +Kurs: `coin_amount` EnakCoin = `point_amount` EnakPoint (default 1 : 1). Bila `valid: false`, tampilkan `reason`. + +### POST /customer/wallet/exchange + +Body `{ "coins": 30, "pin": "482913" }`. Response: + +```json +{ + "group_id": "…", + "coins": 30, + "points": 9, + "coin_amount": 10, + "point_amount": 3, + "lots": [{ "amount": 9, "expires_at": "2026-12-31T23:59:59+07:00" }], + "coin_balance": 5, + "point_balance": 9, + "replayed": false +} +``` + +`coins` harus kelipatan `coin_amount`; jumlah yang salah ditolak `304` sebelum PIN dicek. Exchange tidak bisa dibatalkan. EnakPoint hasil tukar tidak bisa hidup lebih lama dari EnakCoin asalnya (lihat `lots`). + +### GET /customer/wallet/transfer/recipient?phone=081234561234 + +```json +{ "name": "Bu*** Sa***", "phone_number": "08**-****-1234" } +``` + +Nomor di luar organisasi atau tidak terdaftar → `404`. Diri sendiri, customer walk-in, atau nonaktif → `304`. + +### POST /customer/wallet/transfer + +Body `{ "currency": "POINT", "amount": 120, "recipient_phone": "081234561234", "pin": "482913" }`. Response: + +```json +{ + "group_id": "…", + "currency": "POINT", + "amount": 120, + "recipient": { "name": "Bu*** Sa***", "phone_number": "08**-****-1234" }, + "lots": [ + { "amount": 100, "expires_at": "2026-12-31T23:59:59+07:00" }, + { "amount": 20, "expires_at": null } + ], + "balance": 30, + "replayed": false +} +``` + +`currency` = `POINT` atau `COIN`. Batas organisasi (transfer aktif, minimal, maksimal per transaksi, batas harian per currency yang reset tengah malam WIB) ditolak `304` sebelum PIN dicek. Transfer final. Saldo membawa tanggal kedaluwarsa aslinya ke penerima (`lots`), dan penerima mendapat push `WALLET_TRANSFER_IN`. + +### POST /customer/spin + +Body `{ "spin_id": "" }`. Memotong EnakCoin sebesar `metadata.coin_cost` game itu (default 1). + +```json +{ + "game_play": { "id": "…", "game_id": "…", "coins_used": 1, "created_at": "…" }, + "prize_won": { "id": "…", "name": "Voucher 10rb" }, + "coins_remaining": 7 +} +``` + +EnakCoin kurang, game nonaktif, atau hadiah baru saja habis → `304`, tidak ada EnakCoin yang terpotong. + +## POS: pembayaran EnakPoint + +Kasir memakai endpoint pembayaran yang sudah ada dengan payment method bertipe `point`, disetujui customer lewat kode bayar dari aplikasinya; PIN tidak pernah diketik di perangkat kasir. + +| Method | Path | Keterangan | +| --- | --- | --- | +| GET | `/orders/:id/point-payment/preview` | Batas pembayaran EnakPoint untuk order ini | +| POST | `/payments` | Bayar dengan method EnakPoint (`points` + `payment_code`) | +| POST | `/payments/:id/refund` | Refund pembayaran EnakPoint, kembali sebagai EnakPoint | + +1. Customer membuat kode di aplikasi (`POST /customer/wallet/payment-code`) dan menunjukkan angka atau QR-nya. +2. POS memanggil preview untuk tombol "pakai maksimal". +3. POS memanggil `POST /payments` dengan kode tersebut. Sisa tagihan dibayar dengan method lain seperti biasa. + +### GET /orders/:id/point-payment/preview + +```json +{ + "order_id": "…", + "customer_id": "…", + "eligible": true, + "point_balance": 12500, + "point_value": 1, + "remaining_amount": 87500, + "min_payment_points": 1, + "max_payment_percent": 100, + "max_points": 12500, + "max_amount": 12500 +} +``` + +Bila `eligible: false`, `reason` menjelaskan kenapa (order walk-in, outlet tidak menerima EnakPoint, saldo di bawah minimal, dst.). Batas yang dipakai: + +``` +batas_rupiah = min(sisa_tagihan, total × max_payment_percent / 100 − sudah_dibayar_EnakPoint) +maks_point = min(saldo, floor(batas_rupiah / point_value)) +``` + +### POST /payments + +Header `X-Idempotency-Key` wajib. + +```json +{ + "order_id": "…", + "payment_method_id": "", + "points": 12500, + "payment_code": "482913" +} +``` + +- `amount` tidak perlu dikirim; backend menghitung `points × point_value` dan tidak pernah melebihi sisa tagihan (tidak ada kembalian). +- `payment_code` boleh angka yang diketik atau hasil scan QR apa adanya (`enakpoint:482913`). +- Response pembayaran membawa `points_used` dan `point_value` untuk struk; response order membawa `points_earned` dan `coins_earned`. +- Ditolak `304` bila: order tanpa customer atau walk-in, customer nonaktif, outlet tidak menerima EnakPoint, `points` di luar batas, kode salah/kedaluwarsa/sudah dipakai/milik customer lain, atau method EnakPoint dipakai sebagai split. Kode terpakai begitu diterima; bila pembayaran lalu ditolak, minta kode baru. +- Method EnakPoint dibuat otomatis per organisasi, tidak bisa dihapus atau diubah tipenya, dan tidak muncul di daftar method `?outlet_id=` bila outlet tidak menerima EnakPoint. + +### Void dan refund + +- **Void order:** semua EnakPoint yang dipakai kembali sebagai EnakPoint. +- **`POST /payments/:id/refund` pada pembayaran EnakPoint:** kembali `floor(rupiah_direfund / point_value_saat_bayar)`; sisa di bawah 1 EnakPoint hangus. +- **Refund order ke tunai/method lain** hanya sebesar bagian non-EnakPoint; mencoba merefund bagian EnakPoint secara tunai ditolak `304`. +- EnakPoint yang kembali memakai tanggal kedaluwarsa asal, minimal 7 hari sejak refund. Earning order ikut ditarik; bila saldo sudah terpakai, ditarik sebanyak yang ada dan refund tetap jalan. + +## Dashboard + +Semua endpoint dashboard butuh role Admin atau Manager, dan semuanya dibatasi ke organisasi user yang login. Rincian layar ada di [`backoffice-enakpoint.md`](./backoffice-enakpoint.md). + +| Method | Path | Keterangan | +| --- | --- | --- | +| GET, PUT | `/outlets/:outlet_id/loyalty-settings` | Earning dan penerimaan EnakPoint per outlet | +| GET, PUT | `/marketing/loyalty-settings` | Nilai EnakPoint, kurs, transfer, kedaluwarsa (`?dry_run=true` untuk preview) | +| GET | `/marketing/loyalty-settings/history` | Riwayat perubahan setting (`page`, `limit`, `outlet_id`) | +| GET | `/marketing/customers/:id/wallet` | Saldo, lot aktif, riwayat dengan nama asli | +| POST | `/marketing/customers/:id/wallet/adjust` | Koreksi saldo manual | +| GET | `/marketing/wallet-transactions/:id/trace` | Telusuri asal saldo per butir | +| DELETE | `/marketing/customers/:id/pin` | Hapus PIN customer | +| GET | `/marketing/customers/:id/security-events` | Log keamanan PIN (`page`, `limit`) | + +Pada kedua `PUT` setting, field yang tidak dikirim tetap memakai nilai sekarang; field yang tidak dikenal ditolak. + +### /outlets/:outlet_id/loyalty-settings + +```json +{ + "point": { "enabled": true, "earn_per_amount": 100, "earn_value": 1, "min_order_amount": 0, "max_per_order": null }, + "coin": { "enabled": true, "earn_per_amount": 25000, "earn_value": 1, "min_order_amount": 0, "max_per_order": null }, + "point_payment": { "accept_payment": true, "min_payment_points": 1, "max_payment_percent": 100 } +} +``` + +Response menambahkan `outlet_id`, `point_value`, `point_cashback_percent` (default di atas = 1%), dan `changes` pada PUT. Validasi: `earn_per_amount > 0`, `earn_value ≥ 0`, `max_payment_percent` 0–100. + +### /marketing/loyalty-settings + +```json +{ + "point_value": 1, + "exchange": { "coin_amount": 1, "point_amount": 1 }, + "transfer": { "enabled": true, "min_amount": 1, "max_per_transaction": null, "daily_limit": null }, + "point_expiry": { + "enabled": false, + "mode": "FIXED_DATE", + "fixed_dates": ["12-31"], + "grace_months": 3, + "period": 12, + "unit": "MONTH", + "end_of_month": false, + "reminder_days": 7 + }, + "coin_expiry": { "…": "sama dengan point_expiry" } +} +``` + +| Field kedaluwarsa | Dipakai mode | Nilai | +| --- | --- | --- | +| `mode` | – | `FIXED_DATE` (hangus di tanggal tetap tiap tahun) atau `ROLLING` (umur sejak didapat) | +| `fixed_dates` | `FIXED_DATE` | `MM-DD`, boleh lebih dari satu; `02-29` ditolak | +| `grace_months` | `FIXED_DATE` | 0–24; saldo yang didapat kurang dari ini sebelum tanggal hangus ikut ke tanggal berikutnya | +| `period`, `unit` | `ROLLING` | ≥ 1, `DAY` atau `MONTH` | +| `end_of_month` | `ROLLING` | Dibulatkan ke akhir bulan | +| `reminder_days` | keduanya | Hari sebelum hangus untuk pengingat; 0 = tanpa pengingat | + +Response menambahkan: + +- `impact`: saldo beredar dan nilai rupiahnya sebelum/sesudah perubahan `point_value` atau kurs. +- `expiry_preview`: `{ "point", "coin" }`, kapan saldo yang didapat sekarang kedaluwarsa (`null` = tidak). +- `expiry_activations`: bila perubahan ini menyalakan kedaluwarsa pertama kali, `[{ "currency", "lots", "amount", "expires_at" }]` saldo lama yang ikut diberi tanggal. +- `changes` dan `dry_run`. + +### POST /marketing/customers/:id/wallet/adjust + +```json +{ "currency": "POINT", "amount": -500, "reason": "Komplain #45", "idempotency_key": "adj-45" } +``` + +`amount` bertanda dan tidak boleh 0; `reason` wajib. Pengurangan yang melebihi saldo ditolak `304`. Response: `{ "transaction", "spendable_point_balance", "spendable_coin_balance", "replayed" }`. + +### GET /marketing/wallet-transactions/:id/trace + +```json +{ + "transaction": { "id": "…", "customer": { "id": "…", "name": "Budi Santoso" }, "type": "PAYMENT", "amount": -30, "…": "…" }, + "lots": [ + { + "amount": 30, + "chain": [ + { "lot": { "id": "…", "expires_at": "…" }, "source": { "type": "TRANSFER_IN", "customer": { "name": "Budi Santoso" } } }, + { "lot": { "id": "…", "origin_lot_id": null }, "source": { "type": "EARN", "reference_type": "ORDER", "description": "Belanja #ORD-1", "customer": { "name": "Anita" } } } + ] + } + ] +} +``` + +Pengurangan menampilkan lot yang dipakai; penambahan menampilkan lot yang dibuat. Tiap `chain` mundur lewat transfer, exchange, atau refund sampai lot pertama dari `EARN`, `ADJUSTMENT`, atau `MIGRATION`. + +### PIN customer + +`DELETE /marketing/customers/:id/pin` dengan `{ "reason": "…" }` memaksa customer membuat PIN baru lewat OTP; admin tidak bisa membuat, mengganti, atau melihat PIN. `security-events` mengembalikan `PIN_SET`, `PIN_CHANGED`, `PIN_RESET`, `PIN_FAILED`, `PIN_LOCKED`, `PIN_REMOVED_BY_ADMIN` beserta waktu, IP, dan perangkat. + +## Referensi + +### Tipe mutasi (`type`) + +| `type` | Arah | Arti | `source` / `destination` | +| --- | --- | --- | --- | +| `EARN` | + | Didapat dari order lunas | `ORDER` | +| `EARN_REVERSAL` | − | Ditarik karena order di-void/refund | `ORDER` | +| `PAYMENT` | − | Membayar order (EnakPoint saja) | `PAYMENT` | +| `PAYMENT_REFUND` | + | Kembali karena pembayaran di-void/refund | `PAYMENT` | +| `EXCHANGE_OUT` | − | EnakCoin ditukar | `WALLET_TX` (baris `EXCHANGE_IN`) | +| `EXCHANGE_IN` | + | EnakPoint hasil tukar | `WALLET_TX` (baris `EXCHANGE_OUT`) | +| `TRANSFER_OUT` | − | Dikirim ke customer lain | `WALLET_TX` (baris `TRANSFER_IN`) | +| `TRANSFER_IN` | + | Diterima dari customer lain | `WALLET_TX` (baris `TRANSFER_OUT`) | +| `GAME_SPEND` | − | Main game (EnakCoin saja) | `GAME_PLAY` | +| `EXPIRE` | − | Hangus karena kedaluwarsa | `LOT` | +| `ADJUSTMENT` | + / − | Koreksi admin | `USER` | +| `MIGRATION` | + | Saldo dari sistem lama | `LEGACY_POINTS` / `LEGACY_TOKENS` | + +### Notifikasi push (FCM) + +Semua nilai `data` berupa string. Push hanya sampai ke device yang terdaftar lewat `PUT /customer/devices`. + +| `data.type` | Kapan | Isi `data` lainnya | +| --- | --- | --- | +| `WALLET_TRANSFER_IN` | Menerima transfer | `transaction_id`, `group_id`, `currency`, `amount` | +| `WALLET_EXPIRING` | `reminder_days` hari sebelum hangus, sekali per tanggal | `currency`, `amount`, `expiry_date` | +| `WALLET_EXPIRED` | Saldo baru saja hangus | `currency`, `amount` | +| `PIN_LOCKED` | PIN terkunci setelah 5 kali salah | `locked_until` (RFC3339, UTC) | + +### Endpoint dan field deprecated + +Masih jalan dan membaca wallet, tapi akan dihapus setelah semua versi aplikasi pindah. + +| Lama | Pengganti | +| --- | --- | +| `GET /customer/points` | `GET /customer/wallet` → `point_balance` | +| `GET /customer/tokens` | `GET /customer/wallet` → `coin_balance` | +| `total_points`, `total_tokens`, `points_history`, `tokens_history`, `last_updated` di `/customer/wallet` | `point_balance`, `coin_balance`, `recent_transactions` | +| `token_used`, `tokens_remaining` di response game | `coins_used`, `coins_remaining` | +| `sort_by=token_used` di daftar game play | `sort_by=coins_used` | + +Panduan alur lengkap per tim ada di [`integration-enakpoint.md`](./integration-enakpoint.md). diff --git a/docs/backoffice-enakpoint.md b/docs/backoffice-enakpoint.md new file mode 100644 index 0000000..599eb34 --- /dev/null +++ b/docs/backoffice-enakpoint.md @@ -0,0 +1,305 @@ +# Backoffice EnakPoint & EnakCoin + +30 Sep 2026 + +Backoffice perlu tujuh layar untuk mengelola program loyalitas: setting per outlet, setting per organisasi (termasuk kedaluwarsa), wallet customer, telusuri mutasi, PIN customer, riwayat setting, dan biaya main game. + +## Layar yang perlu dibuat + +Semua endpoint di bawah base URL `/api/v1`, butuh login user dengan role Admin atau Manager, dan otomatis dibatasi ke organisasi user tersebut. Data customer atau outlet organisasi lain dijawab `404`. + +| Layar | Endpoint | Tempat di menu | +| --- | --- | --- | +| Setting loyalitas outlet | `GET` / `PUT /outlets/:outlet_id/loyalty-settings` | Outlet → detail outlet → tab Loyalitas | +| Setting loyalitas organisasi | `GET` / `PUT /marketing/loyalty-settings` (+ `?dry_run=true`) | Marketing → Loyalitas → Pengaturan | +| Riwayat perubahan setting | `GET /marketing/loyalty-settings/history` | Marketing → Loyalitas → Riwayat | +| Wallet customer | `GET /marketing/customers/:id/wallet`, `POST …/wallet/adjust` | Customer → detail customer → tab Wallet | +| Telusuri mutasi | `GET /marketing/wallet-transactions/:id/trace` | Dibuka dari baris riwayat wallet | +| PIN & keamanan customer | `DELETE /marketing/customers/:id/pin`, `GET …/security-events` | Customer → detail customer → tab Keamanan | +| Biaya main game | `PUT` game yang sudah ada, `metadata.coin_cost` | Marketing → Game → edit game | + +Penempatan menu di atas adalah usulan; sesuaikan dengan struktur backoffice yang ada. + +**Istilah di layar.** EnakPoint (`POINT`) adalah saldo yang bisa membayar order; EnakCoin (`COIN`) untuk main game dan bisa ditukar ke EnakPoint. Nilai rupiah EnakPoint selalu ditulis "setara potongan Rp …", tidak pernah "saldo Rp …", karena saldo tidak bisa dicairkan. + +**Format response.** Sukses `{ "success": true, "data": … }`; gagal `{ "success": false, "errors": [{ "code", "entity", "cause" }] }`. Tampilkan `cause` sebagai pesan (lihat bagian Pesan error). + +## Setting loyalitas outlet + +Tiap outlet mengatur sendiri berapa EnakPoint dan EnakCoin yang didapat dari order, dan apakah outlet menerima pembayaran EnakPoint. Semua nilai default mati sampai owner menyalakannya. + +`GET /outlets/:outlet_id/loyalty-settings` → isi form. `PUT` ke path yang sama dengan objek yang sama untuk menyimpan; field yang tidak dikirim tetap, field tak dikenal ditolak. + +```json +{ + "point": { "enabled": true, "earn_per_amount": 100, "earn_value": 1, "min_order_amount": 0, "max_per_order": null }, + "coin": { "enabled": true, "earn_per_amount": 25000, "earn_value": 1, "min_order_amount": 0, "max_per_order": null }, + "point_payment": { "accept_payment": true, "min_payment_points": 1, "max_payment_percent": 100 } +} +``` + +| Field | Label usulan | Tipe | Default | Validasi | +| --- | --- | --- | --- | --- | +| `point.enabled` / `coin.enabled` | Beri EnakPoint / EnakCoin | toggle | mati | – | +| `earn_per_amount` | Setiap belanja Rp … | Rp | 100 (point), 25.000 (coin) | > 0 | +| `earn_value` | … mendapat | angka | 1 | ≥ 0 | +| `min_order_amount` | Minimal belanja | Rp | 0 | ≥ 0 | +| `max_per_order` | Maksimal per order | angka, boleh kosong | kosong = tanpa batas | ≥ 0 | +| `point_payment.accept_payment` | Terima pembayaran EnakPoint | toggle | mati | – | +| `min_payment_points` | Minimal EnakPoint per pembayaran | angka | 1 | ≥ 1 | +| `max_payment_percent` | Maksimal porsi order dibayar EnakPoint | % | 100 | 0–100 | + +**Cashback efektif.** Response membawa `point_cashback_percent` dan `point_value`. Tampilkan persentase di samping field earning EnakPoint, mis. "setara cashback 1%", dan hitung ulang di sisi klien saat owner mengetik: `earn_value × point_value ÷ earn_per_amount × 100`. Tujuannya agar owner tidak salah membaca skala (1 per Rp 100 bukan 1 per Rp 1). + +**Contoh di bawah form.** "Belanja Rp 87.500 mendapat 875 EnakPoint dan 3 EnakCoin." Earning dihitung dari subtotal setelah diskon, sebelum pajak, dan bagian yang dibayar EnakPoint tidak ikut dihitung. + +Setelah `PUT`, response membawa `changes` (key yang berubah); tampilkan toast singkat, mis. "2 pengaturan disimpan". Mematikan `accept_payment` langsung menyembunyikan method EnakPoint di kasir outlet itu. + +## Setting loyalitas organisasi + +Nilai rupiah EnakPoint, kurs exchange, batas transfer, dan kedaluwarsa berlaku sama untuk semua outlet, jadi diatur sekali per organisasi. Mengubah nilai EnakPoint atau kurs langsung mengubah daya beli semua saldo customer, jadi layar ini wajib menampilkan dampaknya sebelum disimpan. + +```json +{ + "point_value": 1, + "exchange": { "coin_amount": 1, "point_amount": 1 }, + "transfer": { "enabled": true, "min_amount": 1, "max_per_transaction": null, "daily_limit": null }, + "point_expiry": { "…": "lihat bagian kedaluwarsa" }, + "coin_expiry": { "…": "lihat bagian kedaluwarsa" } +} +``` + +| Field | Label usulan | Default | Validasi | +| --- | --- | --- | --- | +| `point_value` | Nilai 1 EnakPoint (Rp) | 1 | ≥ 1 | +| `exchange.coin_amount` : `exchange.point_amount` | Kurs tukar: … EnakCoin = … EnakPoint | 1 : 1 | keduanya ≥ 1 | +| `transfer.enabled` | Izinkan transfer antar customer | aktif | – | +| `transfer.min_amount` | Minimal per transfer | 1 | ≥ 1 | +| `transfer.max_per_transaction` | Maksimal per transfer | kosong = tanpa batas | ≥ 1 | +| `transfer.daily_limit` | Batas harian per customer | kosong = tanpa batas | ≥ 1, dihitung per currency, reset tengah malam WIB | + +### Alur simpan + +1. Owner mengubah form. +2. Tombol Simpan memanggil `PUT /marketing/loyalty-settings?dry_run=true` dengan objek yang diubah. Tidak ada yang tersimpan. +3. Bila `changes` kosong, beri tahu "tidak ada perubahan" dan berhenti. +4. Tampilkan dialog konfirmasi berisi `changes`, `impact` (bila `point_value` atau kurs berubah), dan `expiry_activations` (bila ada, lihat bagian kedaluwarsa). +5. Konfirmasi memanggil `PUT` yang sama tanpa `dry_run`. + +### Dialog dampak + +`impact` berisi saldo beredar organisasi dan nilainya sebelum/sesudah: + +| Field `impact` | Tampilkan sebagai | +| --- | --- | +| `outstanding_points` | EnakPoint beredar | +| `point_rupiah_before` → `point_rupiah_after` | Setara potongan Rp … → Rp … | +| `outstanding_coins` | EnakCoin beredar | +| `coins_as_points_before` → `coins_as_points_after` | Bila semua ditukar: … EnakPoint → … EnakPoint | +| `coin_rupiah_before` → `coin_rupiah_after` | Setara potongan Rp … → Rp … | + +Contoh kalimat: "Menaikkan nilai EnakPoint dari Rp 1 ke Rp 2 membuat 1.250.000 EnakPoint yang beredar setara potongan Rp 2.500.000 (sebelumnya Rp 1.250.000)." Perubahan hanya berlaku ke depan: pembayaran, refund, dan exchange yang sudah terjadi memakai nilai saat itu. + +## Pengaturan kedaluwarsa + +Kedaluwarsa diatur terpisah untuk EnakPoint (`point_expiry`) dan EnakCoin (`coin_expiry`) dengan salah satu dari dua model; defaultnya mati, dan bila dinyalakan defaultnya hangus setiap 31 Desember. + +```json +"point_expiry": { + "enabled": true, + "mode": "FIXED_DATE", + "fixed_dates": ["12-31"], + "grace_months": 3, + "period": 12, + "unit": "MONTH", + "end_of_month": false, + "reminder_days": 7 +} +``` + +| Field | Tampil saat | Label usulan | Validasi | +| --- | --- | --- | --- | +| `enabled` | selalu | Saldo bisa kedaluwarsa | – | +| `mode` | aktif | Model: Tanggal tetap / Sejak didapat | `FIXED_DATE` atau `ROLLING` | +| `fixed_dates` | `FIXED_DATE` | Tanggal hangus setiap tahun | minimal satu, format `MM-DD`, `02-29` ditolak | +| `grace_months` | `FIXED_DATE` | Periode tanggung (bulan) | 0–24, default 3 | +| `period` + `unit` | `ROLLING` | Berlaku selama … hari/bulan | period ≥ 1, `DAY` atau `MONTH` | +| `end_of_month` | `ROLLING` | Bulatkan ke akhir bulan | – | +| `reminder_days` | aktif | Ingatkan customer … hari sebelumnya | ≥ 0, 0 = tanpa pengingat | + +**Tanggal tetap (`FIXED_DATE`).** Semua saldo hangus di tanggal yang sama, mis. 31 Desember, atau 30 Juni dan 31 Desember untuk dua kali setahun. Saldo yang didapat kurang dari `grace_months` sebelum tanggal itu ikut ke tanggal berikutnya, jadi saldo yang didapat 1 Oktober dengan tanggung 3 bulan hangus 31 Desember tahun depan. Untuk input `fixed_dates`, pakai pemilih tanggal+bulan tanpa tahun. + +**Sejak didapat (`ROLLING`).** Tiap saldo berlaku `period` hari atau bulan sejak masuk, mis. 12 bulan. Dengan `end_of_month`, saldo yang didapat 14 Maret 2026 hangus 31 Maret 2027. + +**Preview.** Response `GET`, `PUT`, dan dry run membawa `expiry_preview.point` dan `.coin`: kapan saldo yang didapat sekarang akan kedaluwarsa (`null` = tidak). Tampilkan di bawah form: "EnakPoint yang didapat hari ini kedaluwarsa pada 31 Des 2026." Karena dihitung dari nilai yang dikirim, dry run bisa dipakai untuk memperbarui preview saat owner mengubah pilihan. + +**Menyalakan pertama kali.** Saldo lama yang belum punya tanggal ikut diberi tanggal, dengan masa berlaku penuh: tanggal hangus kedua berikutnya (`FIXED_DATE`) atau satu periode sejak hari ini (`ROLLING`). Dry run mengembalikan `expiry_activations`; tampilkan di dialog konfirmasi dengan kalimat tegas, mis. "1.250.000 EnakPoint milik customer yang ada sekarang akan kedaluwarsa pada 31 Des 2027. Tindakan ini tidak bisa dibatalkan dengan mematikan kedaluwarsa." + +| Field `expiry_activations[]` | Arti | +| --- | --- | +| `currency` | `POINT` atau `COIN` | +| `lots` | Jumlah paket saldo yang diberi tanggal | +| `amount` | Total saldo yang diberi tanggal | +| `expires_at` | Tanggal kedaluwarsanya | + +**Aturan lain yang perlu dijelaskan di layar:** + +- Mengubah model atau masa berlaku hanya berlaku untuk saldo yang masuk setelahnya. +- Mematikan kedaluwarsa tidak membatalkan tanggal yang sudah terjadwal. +- Saldo yang ditransfer atau ditukar membawa tanggal kedaluwarsa aslinya. +- Saldo hangus tanpa kompensasi apa pun. Customer mendapat pengingat push `reminder_days` hari sebelumnya dan notifikasi saat hangus. + +## Wallet customer + +Tab Wallet di detail customer dipakai untuk menangani komplain: melihat saldo dan asal-usulnya, mengoreksi saldo, dan menelusuri satu mutasi sampai ke order asalnya. + +### Saldo, lot, dan riwayat + +`GET /marketing/customers/:id/wallet?page=1&limit=20¤cy=POINT&type=PAYMENT,EARN&from=2026-09-01&to=2026-09-30` (semua query opsional, sama seperti riwayat di aplikasi customer) + +```json +{ + "customer": { "id": "…", "name": "Budi Santoso", "phone": "081234561234" }, + "point_balance": 12650, + "coin_balance": 8, + "spendable_point_balance": 12500, + "spendable_coin_balance": 8, + "lots": [ + { "id": "…", "currency": "POINT", "original_amount": 875, "remaining_amount": 875, "expires_at": "2026-12-31T23:59:59+07:00", "expired": false, "source_transaction_id": "…", "origin_lot_id": null, "created_at": "…" } + ], + "transactions": { + "data": [ + { + "id": "…", "currency": "POINT", "type": "TRANSFER_OUT", "amount": -120, "balance_after": 12650, + "description": "Transfer ke An*** (08**-****-5678)", + "destination": { "type": "WALLET_TX", "id": "…" }, + "counterparty": { "id": "…", "name": "Anita Rahma" }, + "created_by": null, "outlet": null, "reason": null, "metadata": {}, + "created_at": "…" + } + ], + "pagination": { "page": 1, "limit": 20, "total_count": 42, "total_pages": 3 } + } +} +``` + +- **Saldo:** tampilkan `spendable_*` sebagai saldo utama. `point_balance` / `coin_balance` bisa sedikit lebih besar selama ada lot yang sudah lewat tanggal tapi belum diproses job kedaluwarsa (paling lama sekitar 15 menit). +- **Lot:** tabel paket saldo yang masih berisi, urut dari yang paling cepat kedaluwarsa. Beri tanda untuk `expired: true`. +- **Riwayat:** sama dengan riwayat customer, ditambah nama asli yang disamarkan untuk customer: `counterparty` (lawan transfer), `created_by` (admin pelaku adjustment atau kasir penerima pembayaran), `outlet`, `reason`, dan `metadata` (kurs, nilai EnakPoint yang dibekukan, shortfall). + +### Adjustment manual + +`POST /marketing/customers/:id/wallet/adjust` + +```json +{ "currency": "POINT", "amount": -500, "reason": "Komplain #45", "idempotency_key": "adj-7f3c" } +``` + +| Field | Aturan | +| --- | --- | +| `currency` | `POINT` atau `COIN` | +| `amount` | Bertanda, tidak boleh 0. Positif menambah, negatif mengurangi | +| `reason` | Wajib; tampil di riwayat customer sebagai "Koreksi oleh admin: …" | +| `idempotency_key` | Opsional tapi disarankan: buat satu nilai saat dialog dibuka, supaya klik ganda tidak mengoreksi dua kali | + +Pengurangan yang melebihi saldo yang bisa dipakai ditolak `304`. Adjustment tambah mengikuti aturan kedaluwarsa organisasi. Response: `{ "transaction", "spendable_point_balance", "spendable_coin_balance", "replayed" }`. Beri catatan di dialog bahwa adjustment tidak disertai pembayaran uang, sehingga alasan tidak boleh "pencairan". + +### Telusuri mutasi + +Dari baris riwayat mana pun, tombol Telusuri memanggil `GET /marketing/wallet-transactions/:id/trace`. + +```json +{ + "transaction": { "id": "…", "customer": { "id": "…", "name": "Budi Santoso" }, "currency": "POINT", "type": "PAYMENT", "amount": -30, "description": "Bayar #ORD-0456 di Outlet Kemang (Rp 30)", "reference_type": "PAYMENT", "reference_id": "…", "created_at": "…" }, + "lots": [ + { + "amount": 30, + "chain": [ + { "lot": { "id": "…", "expires_at": "…", "origin_lot_id": "…" }, "source": { "type": "TRANSFER_IN", "customer": { "name": "Budi Santoso" }, "description": "Transfer dari An*** (08**-****-5678)" } }, + { "lot": { "id": "…", "origin_lot_id": null }, "source": { "type": "EARN", "customer": { "name": "Anita Rahma" }, "reference_type": "ORDER", "reference_id": "…", "description": "Belanja #ORD-1 di Outlet Kemang" } } + ] + } + ] +} +``` + +Tampilkan tiap `lots[]` sebagai rantai dari atas ke bawah: jumlah yang lewat lot itu, lalu setiap langkah `chain` dengan pemilik, tipe, dan deskripsinya. Langkah terakhir selalu `EARN`, `ADJUSTMENT`, atau `MIGRATION`; bila `reference_type` = `ORDER`, jadikan tautan ke detail order. Mutasi keluar menampilkan lot yang dipakai; mutasi masuk menampilkan lot yang dibuatnya. + +## PIN, riwayat setting, game, dan method EnakPoint + +### PIN & keamanan customer + +Admin tidak bisa membuat, mengganti, atau melihat PIN customer; satu-satunya aksi adalah menghapusnya, misalnya bila customer kehilangan akses, sehingga customer harus membuat PIN baru lewat OTP di aplikasi. + +- `DELETE /marketing/customers/:id/pin` dengan body `{ "reason": "Customer ganti nomor HP" }`. `reason` wajib. Tampilkan dialog konfirmasi dengan input alasan. +- `GET /marketing/customers/:id/security-events?page=1&limit=20` untuk tab Keamanan: + +```json +{ + "data": [ + { "id": "…", "event": "PIN_LOCKED", "actor_user": null, "reason": null, "ip_address": "103.10.0.7", "user_agent": "EnakApp/2.4 (Android 14)", "created_at": "…" } + ], + "pagination": { "page": 1, "limit": 20, "total_count": 5, "total_pages": 1 } +} +``` + +| `event` | Label usulan | +| --- | --- | +| `PIN_SET` | PIN dibuat | +| `PIN_CHANGED` | PIN diganti | +| `PIN_RESET` | PIN direset lewat OTP (transfer ditahan 24 jam) | +| `PIN_FAILED` | PIN salah dimasukkan | +| `PIN_LOCKED` | PIN terkunci 30 menit | +| `PIN_REMOVED_BY_ADMIN` | PIN dihapus admin (`actor_user`, `reason` terisi) | + +### Riwayat perubahan setting + +`GET /marketing/loyalty-settings/history?page=1&limit=20` untuk setting organisasi; tambah `&outlet_id=…` untuk riwayat satu outlet. + +```json +{ "id": "…", "organization_id": "…", "outlet_id": null, "key": "loyalty.point.value", "old_value": "1", "new_value": "2", "changed_by": "…", "created_at": "…" } +``` + +`old_value` `null` berarti sebelumnya masih nilai default. Tampilkan `key` dengan label yang sama seperti di form (mis. `loyalty.point.value` → "Nilai 1 EnakPoint"), dan `changed_by` sebagai nama user. + +### Biaya main game + +Semua game (spin, raffle, minigame) memakai EnakCoin yang sama. Biaya per main diisi di `metadata.coin_cost` saat membuat atau mengedit game (`/marketing/games`): bilangan bulat ≥ 1, default 1 bila kosong. Nilai pecahan, 0, atau teks membuat game tidak bisa dimainkan. Karena `metadata` dikirim utuh, pertahankan key metadata lain saat menyimpan. Hadiah game juga bernilai rupiah secara tidak langsung, karena EnakCoin bisa ditukar ke EnakPoint. + +### Method pembayaran EnakPoint + +Method "EnakPoint" (tipe `point`) dibuat otomatis untuk setiap organisasi. Di layar Payment Method (`/payment-methods`): + +- Tampilkan sebagai method sistem: tombol hapus dan pilihan ubah tipe disembunyikan; backend menolaknya (`304`). Nama boleh diganti. +- Tipe `point` tidak ditawarkan saat membuat method baru. +- Kasir hanya melihatnya di outlet yang menyalakan "Terima pembayaran EnakPoint". + +Di laporan per payment method, EnakPoint tampil terpisah dan **tidak** dihitung sebagai kas masuk. + +## Pesan error dan checklist + +| `code` | HTTP | Kapan terjadi di backoffice | Yang ditampilkan | +| --- | --- | --- | --- | +| `303`, `310` | 400 | Body tidak valid, field tak dikenal di `PUT` setting, UUID salah | Pesan umum "Data tidak valid" + `cause` untuk developer | +| `304` | 400 | Nilai di luar batas, adjustment melebihi saldo, alasan kosong, hapus/ubah method EnakPoint | `cause` di dekat field atau di toast | +| `404` | 404 | Customer, outlet, atau mutasi bukan milik organisasi ini | "Data tidak ditemukan" | +| `900` | 500 | Kesalahan server | "Terjadi kesalahan, coba lagi" | + +Pesan `cause` saat ini berbahasa Inggris, mis. `invalid loyalty settings: loyalty.point.earn_per_amount must be at least 1`. Untuk validasi form, lebih baik cek batasnya di sisi klien (tabel di tiap bagian) dan tampilkan `cause` hanya sebagai cadangan. + +### Checklist rilis + +- [ ] Form setting outlet menampilkan cashback efektif dan contoh earning. +- [ ] Setting organisasi selalu lewat dry run dan dialog konfirmasi sebelum disimpan. +- [ ] Dialog konfirmasi menampilkan `impact` saat nilai EnakPoint atau kurs berubah. +- [ ] Dialog konfirmasi menampilkan `expiry_activations` saat kedaluwarsa dinyalakan pertama kali. +- [ ] Preview "yang didapat hari ini kedaluwarsa pada …" tampil di bawah pengaturan kedaluwarsa. +- [ ] Wallet customer menampilkan saldo yang bisa dipakai, lot, dan riwayat dengan nama asli. +- [ ] Adjustment mewajibkan alasan dan mengirim `idempotency_key`. +- [ ] Tombol Telusuri ada di setiap baris riwayat. +- [ ] Hapus PIN mewajibkan alasan; tab Keamanan menampilkan log. +- [ ] Method EnakPoint tampil sebagai method sistem. +- [ ] Form game punya input `coin_cost`. +- [ ] Semua nilai rupiah EnakPoint ditulis "setara potongan Rp …". + +Pembayaran EnakPoint belum boleh dirilis ke outlet sebelum tinjauan keuangan (N2) dan legal (N3) selesai, dan transfer menunggu tinjauan legal (N3). Layar backoffice boleh disiapkan lebih dulu. diff --git a/docs/integration-enakpoint.md b/docs/integration-enakpoint.md new file mode 100644 index 0000000..1b5e816 --- /dev/null +++ b/docs/integration-enakpoint.md @@ -0,0 +1,635 @@ +# Integrasi EnakPoint & EnakCoin — Customer App, POS & Dashboard + +**Migrasi:** `000090`–`000097` · **Base URL:** `/api/v1` · **Kompatibilitas:** endpoint +lama tetap jalan sebagai alias (lihat §8) + +Panduan untuk memakai saldo loyalitas dari sisi klien. Alasan di balik setiap aturan +ada di [`prd-point-coin.md`](./prd-point-coin.md). + +--- + +## 1. Konsep inti + +| | EnakPoint (`POINT`) | EnakCoin (`COIN`) | +|---|---|---| +| Didapat dari | Order lunas (per outlet), adjustment admin, exchange | Order lunas (per outlet), adjustment admin | +| Dipakai untuk | **Membayar order** | **Main game**, ditukar ke EnakPoint | +| Bisa ditransfer | Ya | Ya | +| Bisa kedaluwarsa | Ya, bila diaktifkan owner | Ya, bila diaktifkan owner | + +Aturan yang berlaku di seluruh dokumen ini: + +1. **Semua jumlah bilangan bulat.** Tidak ada "setengah EnakPoint". +2. **Saldo tidak pernah jadi uang.** Tidak ada pencairan, tidak ada kembalian, dan + bagian order yang dibayar EnakPoint hanya bisa kembali sebagai EnakPoint. Tampilkan + nilai rupiahnya sebagai **"setara potongan Rp …"**, bukan "saldo Rp …". +3. **Semua aksi customer yang memindahkan saldo butuh PIN 6 digit** (§3): bayar, + buat kode bayar, exchange, transfer. Main game tidak butuh PIN. +4. **Wallet milik customer di satu organisasi.** Saldo berlaku di semua outlet + organisasi itu. Nilai rupiah EnakPoint, kurs exchange, batas transfer, dan + kedaluwarsa diatur per organisasi; earning dan penerimaan pembayaran per outlet. +5. **Setiap mutasi tercatat** di riwayat beserta asal atau tujuannya, dan tidak pernah + dihapus. Koreksi muncul sebagai baris baru. + +### Format response + +Semua endpoint memakai amplop yang sama: + +```json +{ "success": true, "data": { … }, "errors": null } +``` + +```json +{ + "success": false, + "data": null, + "errors": [{ "code": "304", "entity": "wallet_service", "cause": "wallet move refused: not enough EnakCoin" }] +} +``` + +| `code` | HTTP | Arti | +|---|---|---| +| `303`, `310` | 400 | Body atau parameter tidak lengkap / salah format | +| `304` | 400 | Permintaan ditolak aturan bisnis; `cause` menjelaskan alasannya | +| `404` | 404 | Tidak ditemukan (juga dipakai untuk data milik customer/organisasi lain) | +| `429` | 429 | Terlalu cepat meminta ulang (OTP) | +| `PIN_NOT_SET` | 403 | Customer belum membuat PIN | +| `PIN_INVALID` | 400 | PIN salah | +| `PIN_LOCKED` | 423 | PIN terkunci | +| `TRANSFER_BLOCKED` | 403 | Transfer ditahan setelah reset PIN | +| `900` | 500 | Kesalahan server | + +--- + +## 2. Customer app — saldo & riwayat + +Semua endpoint customer memakai header `Authorization: Bearer `. + +### 2.1 Saldo + +`GET /api/v1/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": [ … ] +} +``` + +- `point_balance` dan `coin_balance` adalah saldo yang **bisa dipakai sekarang**. +- `point_discount_value` = `point_balance × point_value`. Tampilkan sebagai + "setara potongan Rp 12.500". +- `nearest_expiring` bernilai `null` per currency bila tidak ada yang akan kedaluwarsa. +- `recent_transactions` berisi 5 mutasi terakhir dengan bentuk yang sama seperti §2.2. + +### 2.2 Riwayat + +`GET /api/v1/customer/wallet/transactions?page=1&limit=20¤cy=POINT&type=EARN,PAYMENT&from=2026-09-01&to=2026-09-30` + +Semua query opsional. `limit` 1–100 (default 20). `type` boleh beberapa, dipisah koma. +`from` / `to` 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": "…", + "expires_at": "2026-12-31T23:59:59+07:00", + "lots": [{ "amount": 875, "remaining": 875, "expires_at": "2026-12-31T23:59:59+07:00" }], + "created_at": "2026-09-30T12:01:00Z" + } + ], + "pagination": { "page": 1, "limit": 20, "total_count": 42, "total_pages": 3 } +} +``` + +- `amount` bertanda: positif menambah saldo, negatif mengurangi. +- Penambahan punya `source`, pengurangan punya `destination`. Keduanya berbentuk + `{ type, id }` dan menunjuk hal yang bisa dibuka di detail (order, pembayaran, game + play, dst.). +- `description` sudah siap tampil dan tidak berubah walau nama outlet atau customer + berubah belakangan. Nama lawan transfer sudah disamarkan. +- Dua baris exchange atau transfer berbagi `group_id` yang sama. + +| `type` | Arah | Arti | `source` / `destination` | +|---|---|---|---| +| `EARN` | + | Didapat dari order lunas | `ORDER` | +| `EARN_REVERSAL` | − | Ditarik karena order di-void/refund | `ORDER` | +| `PAYMENT` | − | Membayar order | `PAYMENT` | +| `PAYMENT_REFUND` | + | Kembali karena pembayaran di-void/refund | `PAYMENT` | +| `EXCHANGE_OUT` / `EXCHANGE_IN` | − / + | Tukar EnakCoin ke EnakPoint | `WALLET_TX` (baris pasangannya) | +| `TRANSFER_OUT` / `TRANSFER_IN` | − / + | Transfer antar customer | `WALLET_TX` (baris pasangannya) | +| `GAME_SPEND` | − | Main game | `GAME_PLAY` | +| `EXPIRE` | − | Hangus karena kedaluwarsa | `LOT` | +| `ADJUSTMENT` | + / − | Koreksi oleh admin | `USER` | +| `MIGRATION` | + | Saldo dari sistem lama | `LEGACY_POINTS` / `LEGACY_TOKENS` | + +### 2.3 Yang akan kedaluwarsa + +`GET /api/v1/customer/wallet/expiring` + +```json +{ + "point": [ + { "amount": 150, "date": "2026-10-31" }, + { "amount": 200, "date": "2026-12-31" } + ], + "coin": [] +} +``` + +Dikelompokkan per tanggal (WIB), paling dekat lebih dulu. Saldo bisa dipakai sampai +akhir hari tanggal itu. Daftar kosong berarti tidak ada yang akan kedaluwarsa. + +### 2.4 Notifikasi push (FCM) + +Aplikasi mendaftarkan token FCM-nya **setelah login dan setiap kali FCM memberi token +baru**: + +`PUT /api/v1/customer/devices` + +```json +{ "device_id": "a1b2c3", "fcm_token": "…", "platform": "android", "app_version": "2.4.0" } +``` + +`platform`: `android`, `ios`, atau `web` (opsional). Saat logout, panggil +`DELETE /api/v1/customer/devices/:device_id` supaya HP itu tidak lagi menerima +notifikasi customer tersebut. Satu token hanya milik satu customer: bila customer lain +login di HP yang sama dan mendaftarkan token yang sama, customer sebelumnya otomatis +tidak menerima notifikasi di HP itu lagi. + +Push yang dikirim, dibedakan lewat `data.type`: + +| `data.type` | Kapan | Isi `data` lainnya | +|---|---|---| +| `WALLET_TRANSFER_IN` | Menerima transfer | `transaction_id`, `group_id`, `currency`, `amount` | +| `WALLET_EXPIRING` | `reminder_days` hari sebelum saldo kedaluwarsa, sekali per tanggal | `currency`, `amount`, `expiry_date` | +| `WALLET_EXPIRED` | Saldo baru saja hangus | `currency`, `amount` | +| `PIN_LOCKED` | PIN terkunci setelah 5 kali salah | `locked_until` (RFC3339, UTC) | + +Semua nilai di `data` berupa string, sesuai aturan FCM. + +--- + +## 3. Customer app — PIN + +PIN 6 digit, terpisah dari password login, dikirim sebagai **string** supaya angka nol +di depan tidak hilang. PIN tidak pernah dikembalikan di response. + +### 3.1 Cek status + +`GET /api/v1/customer/pin/status` + +```json +{ "has_pin": true, "locked_until": null, "transfer_blocked_until": null } +``` + +Minta customer membuat PIN saat pertama kali ia melakukan aksi yang butuh PIN +(`has_pin: false`), bukan saat registrasi. + +### 3.2 Membuat PIN pertama kali + +1. `POST /api/v1/customer/pin/otp` dengan `{ "purpose": "pin_setup" }`. OTP dikirim ke + nomor customer lewat WhatsApp. Response: `{ "purpose", "otp_token", "expires_at" }`. +2. `POST /api/v1/customer/pin` dengan + `{ "otp_token": "…", "otp_code": "123456", "pin": "482913", "confirm_pin": "482913" }`. + +PIN ditolak (`304`) bila bukan 6 digit, konfirmasinya beda, semua digit sama +(`111111`), berurutan (`123456`, `654321`), atau sama dengan tanggal lahir +(`DDMMYY` / `YYMMDD`). Tampilkan `cause` apa adanya. Meminta OTP terlalu cepat +menghasilkan `429`. + +### 3.3 Mengganti dan mereset PIN + +- **Ganti:** `PUT /api/v1/customer/pin` dengan `{ "old_pin", "pin", "confirm_pin" }`. +- **Lupa PIN:** minta OTP dengan `purpose: "pin_reset"`, lalu + `POST /api/v1/customer/pin/reset` dengan body yang sama seperti §3.2. Reset juga + membuka PIN yang terkunci. Setelah reset, **transfer keluar ditahan 24 jam**; + pembayaran dan exchange tetap bisa. + +### 3.4 Menangani error PIN + +Setiap endpoint yang menerima `pin` bisa mengembalikan error PIN. Pada error ini `data` +**tidak** `null`: + +```json +{ + "success": false, + "data": { "code": "PIN_INVALID", "remaining_attempts": 3 }, + "errors": [{ "code": "PIN_INVALID", "entity": "customer_pin_service", "cause": "wrong PIN, 3 attempts left" }] +} +``` + +| `data.code` | Field tambahan | Yang ditampilkan aplikasi | +|---|---|---| +| `PIN_NOT_SET` | – | Arahkan ke pembuatan PIN (§3.2) | +| `PIN_INVALID` | `remaining_attempts` | "PIN salah, sisa 3 percobaan" | +| `PIN_LOCKED` | `locked_until` | "PIN terkunci sampai 14:30", tawarkan reset PIN | +| `TRANSFER_BLOCKED` | `transfer_blocked_until` | "Transfer bisa dilakukan lagi pada …" | + +Lima kali salah berturut-turut mengunci PIN selama 30 menit. Selama terkunci, PIN yang +benar pun ditolak. Penghitung disimpan di server, jadi tidak bisa diakali dengan +reinstall atau ganti HP. + +--- + +## 4. Membayar dengan EnakPoint + +Ada dua jalur. Keduanya memakai logika perhitungan yang sama. + +### 4.1 Batas pembayaran + +EnakPoint maksimal yang bisa dipakai untuk satu order: + +``` +batas_rupiah = min(sisa_tagihan, total_order × max_payment_percent / 100 − yang_sudah_dibayar_EnakPoint) +maks_point = min(saldo_customer, floor(batas_rupiah / point_value)) +``` + +Ditambah minimal `min_payment_points` per pembayaran. Nominal rupiah pembayaran selalu +`points × point_value` dan **tidak pernah melebihi sisa tagihan**, jadi tidak ada +kembalian. Sisa tagihan dibayar dengan method lain seperti biasa (split). + +### 4.2 POS — kode bayar dari aplikasi customer + +PIN **tidak pernah** diketik di perangkat kasir. Customer menyetujui di HP-nya sendiri: + +1. **Customer app:** `POST /api/v1/customer/wallet/payment-code` dengan `{ "pin": "482913" }`. + + ```json + { "code": "482913", "qr_payload": "enakpoint:482913", "expires_at": "2026-09-30T05:02:00Z" } + ``` + + Tampilkan `code` sebagai angka dan `qr_payload` sebagai QR. Kode berlaku **2 menit**, + sekali pakai, dan hanya untuk customer itu. Membuat kode baru membatalkan kode lama. + +2. **POS:** tampilkan batas untuk tombol "pakai maksimal": + + `GET /api/v1/orders/:id/point-payment/preview` + + ```json + { + "order_id": "…", + "customer_id": "…", + "eligible": true, + "point_balance": 12500, + "point_value": 1, + "remaining_amount": 87500, + "min_payment_points": 1, + "max_payment_percent": 100, + "max_points": 12500, + "max_amount": 12500 + } + ``` + + Bila `eligible: false`, `reason` menjelaskan kenapa (order walk-in, outlet tidak + menerima EnakPoint, saldo di bawah minimal, dst.). + +3. **POS:** bayar lewat endpoint pembayaran yang sudah ada, dengan payment method + bertipe `point`: + + `POST /api/v1/payments` (header `X-Idempotency-Key` wajib seperti pembayaran lain) + + ```json + { + "order_id": "…", + "payment_method_id": "", + "points": 12500, + "payment_code": "482913" + } + ``` + + `amount` tidak perlu dikirim; backend menghitungnya. `payment_code` boleh berupa + angka yang diketik kasir atau hasil scan QR apa adanya (`enakpoint:482913`). + +Response pembayaran membawa `points_used` dan `point_value` untuk struk, misalnya +"EnakPoint: 12.500 (Rp 12.500)". Jika pembayaran ini melunasi order, order menjadi +`completed`; jika belum, sisanya dibayar dengan method lain. + +Pembayaran ditolak (`304`, `cause` menjelaskan) bila: order tanpa customer atau +customer walk-in, customer nonaktif, outlet tidak menerima EnakPoint, `points` di luar +batas §4.1, kode salah/kedaluwarsa/sudah dipakai/milik customer lain, atau method +EnakPoint dipakai sebagai split (bayar bagian EnakPoint sebagai pembayaran tersendiri, +lalu split sisanya seperti biasa). Kode bayar dipakai habis begitu diterima, sebelum +batas dicek ulang; bila pembayaran lalu ditolak (misalnya saldo berubah), minta +customer membuat kode baru. + +**Method EnakPoint** dibuat otomatis untuk setiap organisasi dan tidak bisa dihapus +atau diubah tipenya (namanya boleh diganti). Daftar payment method yang dikirim +`?outlet_id=` tidak menampilkannya bila outlet itu tidak menerima EnakPoint. + +### 4.3 Customer app / self-order — bayar order sendiri + +`POST /api/v1/customer/orders/:id/pay-with-points` + +```json +{ "points": 12500, "pin": "482913" } +``` + +Hanya untuk order milik customer yang login; order lain dijawab `404`. Response sama +dengan response pembayaran di §4.2. + +### 4.4 Void dan refund + +- **Void order:** semua EnakPoint yang dipakai kembali ke customer sebagai EnakPoint. +- **Refund pembayaran EnakPoint** (`POST /api/v1/payments/:id/refund` pada pembayaran + EnakPoint): yang kembali `floor(rupiah_direfund / point_value_saat_bayar)`. Perubahan + nilai EnakPoint setelah pembayaran tidak mengubah jumlah yang kembali; sisa di bawah + 1 EnakPoint hangus. +- **Refund order ke tunai / method lain** hanya boleh sebesar bagian yang dibayar + dengan method lain. Bagian EnakPoint harus direfund lewat pembayaran EnakPoint-nya + sendiri; mencoba lewat tunai dijawab `304`. +- EnakPoint yang kembali mengikuti tanggal kedaluwarsa asalnya, tapi minimal 7 hari + sejak refund. +- EnakPoint dan EnakCoin yang didapat dari order ikut ditarik saat void/refund. Bila + saldo customer sudah terpakai, yang ditarik sebanyak yang ada; refund tidak pernah + diblokir karena ini. + +### 4.5 Earning di layar order dan struk + +Response order membawa `points_earned` dan `coins_earned` (0 bila order tidak +menghasilkan apa-apa). Earning dihitung dari `subtotal − discount − bagian yang +dibayar EnakPoint`, sebelum pajak, dan diberikan saat order lunas. + +--- + +## 5. Exchange EnakCoin → EnakPoint + +Kurs per organisasi: `coin_amount` EnakCoin = `point_amount` EnakPoint (default 1 : 1). + +1. **Preview** sebelum minta PIN: + + `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 } + ``` + + Bila `valid: false`, tampilkan `reason` (misalnya harus kelipatan `coin_amount`, + atau EnakCoin tidak cukup). + +2. **Tukar:** + + `POST /api/v1/customer/wallet/exchange` dengan header **`Idempotency-Key`** (wajib, + maks. 50 karakter, satu key per percobaan tukar) + + ```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 + } + ``` + +- Jumlah EnakCoin harus kelipatan `coin_amount`. Kesalahan jumlah ditolak **sebelum** + PIN dicek, jadi tidak memakan jatah percobaan PIN. +- Exchange tidak bisa dibatalkan; tampilkan konfirmasi. +- Kirim ulang dengan `Idempotency-Key` yang sama bila koneksi putus: hasil pertama + dikembalikan dengan `replayed: true` tanpa menukar lagi, dengan kurs saat itu. + `Idempotency-Key` yang sama untuk jumlah berbeda ditolak. +- EnakPoint hasil tukar tidak bisa hidup lebih lama dari EnakCoin asalnya (`lots` + menunjukkan tanggalnya). + +--- + +## 6. Transfer ke customer lain + +1. **Cek penerima** sebelum konfirmasi: + + `GET /api/v1/customer/wallet/transfer/recipient?phone=081234561234` + + ```json + { "name": "Bu*** Sa***", "phone_number": "08**-****-1234" } + ``` + + Nomor yang tidak terdaftar di organisasi yang sama dijawab `404`. Diri sendiri, + customer walk-in, atau customer nonaktif dijawab `304`. + +2. **Kirim:** + + `POST /api/v1/customer/wallet/transfer` dengan header **`Idempotency-Key`** (wajib) + + ```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 + } + ``` + +- `currency`: `POINT` atau `COIN`, satu jenis per transfer. +- Batas dari organisasi: transfer bisa dimatikan, ada minimal, maksimal per + transaksi, dan batas harian per currency (reset tengah malam WIB). Pelanggaran batas + ditolak `304` sebelum PIN dicek. +- Transfer final dan tidak bisa dibatalkan customer. +- Saldo yang dikirim membawa tanggal kedaluwarsa aslinya ke penerima (`lots`). + Tampilkan ini ke pengirim. +- Penerima mendapat push `WALLET_TRANSFER_IN` (§2.4). +- Retry dengan `Idempotency-Key` yang sama mengembalikan hasil pertama + (`replayed: true`) dan tidak dihitung dua kali terhadap batas harian. + +--- + +## 7. Game + +`POST /api/v1/customer/spin` dengan `{ "spin_id": "" }`. Tanpa PIN. + +Setiap game memotong EnakCoin sebesar `metadata.coin_cost` game itu (default 1). +Response: + +```json +{ + "game_play": { "id": "…", "game_id": "…", "coins_used": 1, "token_used": 1, "created_at": "…" }, + "prize_won": { "id": "…", "name": "Voucher 10rb", … }, + "coins_remaining": 7, + "tokens_remaining": 7 +} +``` + +EnakCoin kurang, game nonaktif, atau hadiah baru saja habis dijawab `304`; tidak ada +EnakCoin yang terpotong. Baca `coins_used` dan `coins_remaining`; `token_used` dan +`tokens_remaining` hanya salinan untuk versi aplikasi lama. + +Di dashboard, `metadata.coin_cost` diisi per game dengan bilangan bulat ≥ 1. + +--- + +## 8. Endpoint lama (deprecated) + +Masih jalan dan membaca saldo wallet, tapi akan dihapus setelah semua versi aplikasi +pindah. Aplikasi baru jangan memakainya. + +| Lama | Ganti dengan | +|---|---| +| `GET /customer/points` | `GET /customer/wallet` (`point_balance`) | +| `GET /customer/tokens` | `GET /customer/wallet` (`coin_balance`) | +| `total_points`, `total_tokens`, `points_history`, `tokens_history`, `last_updated` di `/customer/wallet` | `point_balance`, `coin_balance`, `recent_transactions` | +| `token_used`, `tokens_remaining` di respons game | `coins_used`, `coins_remaining` | +| `sort_by=token_used` di daftar game play | `sort_by=coins_used` | + +Beri tahu tim backend setelah aplikasi yang beredar tidak lagi memakai kolom kiri, +supaya alias dan tabel lama (`customer_points`, `customer_tokens`) bisa dihapus. + +--- + +## 9. Dashboard + +Semua endpoint di bagian ini butuh login user dengan role Admin atau Manager. + +### 9.1 Pengaturan per outlet + +`GET` / `PUT /api/v1/outlets/:outlet_id/loyalty-settings` + +```json +{ + "point": { "enabled": true, "earn_per_amount": 100, "earn_value": 1, "min_order_amount": 0, "max_per_order": null }, + "coin": { "enabled": true, "earn_per_amount": 25000, "earn_value": 1, "min_order_amount": 0, "max_per_order": null }, + "point_payment": { "accept_payment": true, "min_payment_points": 1, "max_payment_percent": 100 } +} +``` + +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 +samping setting** supaya owner tidak salah membaca skala: default di atas setara +cashback 1%. + +### 9.2 Pengaturan organisasi + +`GET` / `PUT /api/v1/marketing/loyalty-settings` (tambah `?dry_run=true` untuk preview +tanpa menyimpan) + +```json +{ + "point_value": 1, + "exchange": { "coin_amount": 1, "point_amount": 1 }, + "transfer": { "enabled": true, "min_amount": 1, "max_per_transaction": null, "daily_limit": null }, + "point_expiry": { + "enabled": false, + "mode": "FIXED_DATE", + "fixed_dates": ["12-31"], + "grace_months": 3, + "period": 12, + "unit": "MONTH", + "end_of_month": false, + "reminder_days": 7 + }, + "coin_expiry": { … sama … } +} +``` + +Field yang tidak dikirim di `PUT` tetap memakai nilai sekarang. Response menambahkan: + +- `impact`: total saldo beredar dan nilai rupiahnya **sebelum dan sesudah** perubahan + `point_value` atau kurs. Tampilkan sebagai peringatan sebelum owner menyimpan. +- `expiry_preview`: `{ "point": …, "coin": … }`, kapan saldo yang didapat hari ini + akan kedaluwarsa (`null` bila tidak kedaluwarsa). Tampilkan sebagai "EnakPoint yang + didapat hari ini kedaluwarsa pada 31 Des 2026". +- `expiry_activations`: bila perubahan ini **menyalakan** kedaluwarsa untuk pertama + kali, berapa saldo lama yang ikut diberi tanggal (`lots`, `amount`) dan tanggalnya + (`expires_at`). Selalu minta konfirmasi dengan `dry_run=true` dulu. +- `changes`: key yang berubah. + +**Kedaluwarsa** diatur per currency dengan salah satu model: + +| `mode` | Cara kerja | Field yang dipakai | +|---|---|---| +| `FIXED_DATE` (default) | Semua saldo hangus di tanggal tetap setiap tahun. Saldo yang didapat kurang dari `grace_months` sebelum tanggal itu ikut ke tanggal berikutnya | `fixed_dates` (format `MM-DD`, boleh lebih dari satu, `02-29` ditolak), `grace_months` (0–24) | +| `ROLLING` | Tiap saldo berlaku sekian lama sejak didapat | `period`, `unit` (`DAY` / `MONTH`), `end_of_month` | + +- `reminder_days` berlaku untuk keduanya: customer diingatkan sekian hari sebelum + hangus (0 = tanpa pengingat). +- Mengubah pengaturan hanya berlaku untuk saldo yang masuk setelahnya. +- Menyalakan kedaluwarsa pertama kali memberi saldo lama masa berlaku penuh: tanggal + hangus kedua berikutnya (`FIXED_DATE`) atau satu periode penuh (`ROLLING`). +- Mematikan kedaluwarsa tidak membatalkan tanggal yang sudah terjadwal. + +Riwayat perubahan: `GET /api/v1/marketing/loyalty-settings/history?page=1&limit=20` +(tambah `outlet_id=` untuk setting outlet). + +### 9.3 Wallet customer + +- `GET /api/v1/marketing/customers/:id/wallet` — saldo buku dan saldo yang bisa + dipakai, semua lot yang masih berisi, dan riwayat dengan nama asli (lawan transfer, + admin, kasir, outlet). Query riwayat sama seperti §2.2. +- `POST /api/v1/marketing/customers/:id/wallet/adjust` + + ```json + { "currency": "POINT", "amount": -500, "reason": "Komplain #45", "idempotency_key": "adj-45" } + ``` + + `amount` bertanda. `reason` wajib. Pengurangan yang melebihi saldo ditolak. + Adjustment tidak disertai pembayaran uang, jadi jangan pakai alasan "pencairan". + +- `GET /api/v1/marketing/wallet-transactions/:id/trace` — telusuri satu mutasi per + butir: lot mana yang dipakai atau dibuat, lalu rantai asalnya lewat transfer, + exchange, atau refund sampai ke earning/adjustment/migrasi pertama. Contoh: dari + pembayaran B bisa terlihat bahwa EnakPoint-nya berasal dari order #ORD-1 milik A + yang mentransfer ke B. + +### 9.4 PIN customer + +- `DELETE /api/v1/marketing/customers/:id/pin` dengan `{ "reason": "…" }` — hapus PIN + bila customer kehilangan akses. Customer lalu membuat PIN baru lewat OTP. Admin + **tidak bisa** membuat, mengganti, atau melihat PIN. +- `GET /api/v1/marketing/customers/:id/security-events?page=1&limit=20` — log keamanan: + `PIN_SET`, `PIN_CHANGED`, `PIN_RESET`, `PIN_FAILED`, `PIN_LOCKED`, + `PIN_REMOVED_BY_ADMIN`, beserta waktu, IP, dan perangkat. + +--- + +## 10. Checklist integrasi + +**Customer app** +- [ ] Daftarkan token FCM setelah login dan saat token berganti; hapus saat logout. +- [ ] Tangani empat kode error PIN (§3.4) di semua layar yang meminta PIN. +- [ ] Kirim `Idempotency-Key` baru untuk setiap exchange dan transfer, dan pakai ulang + key yang sama saat retry. +- [ ] Tampilkan nilai rupiah sebagai "setara potongan", bukan saldo uang. +- [ ] Baca `coins_used` / `coins_remaining` dan `/customer/wallet`, bukan field lama. + +**POS** +- [ ] Scan QR atau ketik kode bayar, jangan pernah meminta PIN customer di layar kasir. +- [ ] Pakai `point-payment/preview` untuk tombol "pakai maksimal". +- [ ] Cetak `points_used`, `points_earned`, dan `coins_earned` di struk. +- [ ] Refund bagian EnakPoint lewat pembayaran EnakPoint-nya, bukan tunai. + +**Dashboard** +- [ ] Tampilkan `point_cashback_percent`, `impact`, `expiry_preview`, dan + `expiry_activations` sebelum owner menyimpan setting. +- [ ] Isi `metadata.coin_cost` untuk setiap game. diff --git a/go.mod b/go.mod index fa0aba6..f58d285 100644 --- a/go.mod +++ b/go.mod @@ -76,6 +76,7 @@ require ( github.com/subosito/gotenv v1.4.2 // indirect github.com/twitchyliquid64/golang-asm v0.15.1 // indirect github.com/ugorji/go/codec v1.2.12 // indirect + github.com/yuin/gopher-lua v1.1.1 // indirect github.com/zeebo/errs v1.4.0 // indirect go.opentelemetry.io/auto/sdk v1.1.0 // indirect go.opentelemetry.io/contrib/detectors/gcp v1.35.0 // indirect @@ -107,6 +108,7 @@ require ( require ( firebase.google.com/go/v4 v4.19.0 + github.com/alicebob/miniredis/v2 v2.39.0 github.com/aws/aws-sdk-go v1.55.7 github.com/boombuler/barcode v1.1.0 github.com/golang-jwt/jwt/v5 v5.2.3 diff --git a/go.sum b/go.sum index 3f6c466..b178a33 100644 --- a/go.sum +++ b/go.sum @@ -74,6 +74,8 @@ github.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/resourcemapp github.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/resourcemapping v0.51.0/go.mod h1:otE2jQekW/PqXk1Awf5lmfokJx4uwuqcj1ab5SpGeW0= github.com/MicahParks/keyfunc v1.9.0 h1:lhKd5xrFHLNOWrDc4Tyb/Q1AJ4LCzQ48GVJyVIID3+o= github.com/MicahParks/keyfunc v1.9.0/go.mod h1:IdnCilugA0O/99dW+/MkvlyrsX8+L8+x95xuVNtM5jw= +github.com/alicebob/miniredis/v2 v2.39.0 h1:M7WbmV5BmV56L8KTG0rw6vEQ+woTOghpDgin2xv4A0g= +github.com/alicebob/miniredis/v2 v2.39.0/go.mod h1:TcL7YfarKPGDAthEtl5NBeHZfeUQj6OXMm/+iu5cLMM= github.com/aws/aws-sdk-go v1.55.7 h1:UJrkFq7es5CShfBwlWAC8DA077vp8PyVbQd3lqLiztE= github.com/aws/aws-sdk-go v1.55.7/go.mod h1:eRwEWoyTWFMVYVQzKMNHWP5/RV4xIUGMQfXQHfHkpNU= github.com/benbjohnson/clock v1.1.0 h1:Q92kusRqC1XV2MjkWETPvjJVqKetz1OzxZB7mHJLju8= @@ -349,6 +351,8 @@ github.com/yuin/goldmark v1.1.32/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9de github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/yuin/goldmark v1.3.5/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k= github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= +github.com/yuin/gopher-lua v1.1.1 h1:kYKnWBjvbNP4XLT3+bPEwAXJx262OhaHDWDVOPjL46M= +github.com/yuin/gopher-lua v1.1.1/go.mod h1:GBR0iDaNXjAgGg9zfCvksxSRnQx76gclCIb7kdAd1Pw= github.com/zeebo/errs v1.4.0 h1:XNdoD/RRMKP7HD0UhJnIzUy74ISdGGxURlYG8HSWSfM= github.com/zeebo/errs v1.4.0/go.mod h1:sgbWHsvVuTPHcqJJGQ1WhI5KbWlHYz+2+2C/LSEtCw4= github.com/zeebo/xxh3 v1.1.0 h1:s7DLGDK45Dyfg7++yxI0khrfwq9661w9EN78eP/UZVs= diff --git a/internal/app/app.go b/internal/app/app.go index ace698f..0e04b7e 100644 --- a/internal/app/app.go +++ b/internal/app/app.go @@ -31,6 +31,9 @@ type App struct { router *router.Router shutdown chan os.Signal omsetScheduler *service.OmsetMilestoneScheduler + walletRecon *service.WalletReconciliationJob + earningRetry *service.EarningBackfillJob + walletExpiry *service.WalletExpiryJob } func NewApp(db *gorm.DB, redisClient *redis.Client) *App { @@ -53,6 +56,18 @@ func (a *App) Initialize(cfg *config.Config) error { processors.notificationProcessor, ) + // Checks that wallet balances, ledger and lots agree (docs/prd-point-coin.md §7.5) + a.walletRecon = service.NewWalletReconciliationJob( + repository.NewWalletReconciliationRepository(a.db), + repos.userRepo, + processors.notificationProcessor, + ) + // Earns for paid orders whose earning failed at payment time (docs/prd-point-coin.md F3) + a.earningRetry = service.NewEarningBackfillJob(processors.earningProcessor) + // Expires balances whose time is up and reminds customers before (docs/prd-point-coin.md F12) + a.walletExpiry = service.NewWalletExpiryJob(processor.NewWalletExpiryProcessor( + repository.NewWalletExpiryRepository(a.db), processors.loyaltySettingsProcessor, processor.NewWalletProcessor(repos.walletRepo), repos.txManager, processors.customerDeviceProcessor)) + services := a.initServices(processors, repos, cfg) validators := a.initValidators() middleware := a.initMiddleware(services, cfg) @@ -142,6 +157,14 @@ func (a *App) Initialize(cfg *config.Config) error { validators.expenseValidator, services.cashAdvanceService, validators.cashAdvanceValidator, + services.walletAdminService, + validators.walletValidator, + services.loyaltySettingsService, + services.customerPinService, + services.pointPaymentService, + services.customerOrderPaymentService, + services.customerWalletService, + services.customerDeviceService, a.redisClient, ) @@ -153,6 +176,15 @@ func (a *App) Start(port string) error { if a.omsetScheduler != nil { a.omsetScheduler.Start(5 * time.Minute) } + if a.walletRecon != nil { + a.walletRecon.Start(6 * time.Hour) + } + if a.earningRetry != nil { + a.earningRetry.Start(30 * time.Minute) + } + if a.walletExpiry != nil { + a.walletExpiry.Start(15 * time.Minute) + } engine := a.router.Init() @@ -192,6 +224,15 @@ func (a *App) Shutdown() { if a.omsetScheduler != nil { a.omsetScheduler.Stop() } + if a.walletRecon != nil { + a.walletRecon.Stop() + } + if a.earningRetry != nil { + a.earningRetry.Stop() + } + if a.walletExpiry != nil { + a.walletExpiry.Stop() + } close(a.shutdown) } @@ -226,7 +267,6 @@ type repositories struct { chartOfAccountRepo *repository.ChartOfAccountRepositoryImpl accountRepo *repository.AccountRepositoryImpl orderIngredientTransactionRepo *repository.OrderIngredientTransactionRepositoryImpl - customerTokensRepo *repository.CustomerTokensRepository tierRepo *repository.TierRepository gameRepo *repository.GameRepository gamePrizeRepo *repository.GamePrizeRepository @@ -236,7 +276,6 @@ type repositories struct { campaignRepo repository.CampaignRepository campaignRuleRepo repository.CampaignRuleRepository customerAuthRepo repository.CustomerAuthRepository - customerPointsRepo repository.CustomerPointsRepository otpRepo repository.OtpRepository sessionRepo repository.SessionRepository txManager *repository.TxManager @@ -247,6 +286,9 @@ type repositories struct { productOutletPriceRepo *repository.ProductOutletPriceRepositoryImpl expenseRepo *repository.ExpenseRepositoryImpl cashAdvanceRepo *repository.CashAdvanceRepositoryImpl + walletRepo repository.WalletRepository + walletQueryRepo repository.WalletQueryRepository + loyaltySettingsRepo repository.LoyaltySettingsRepository } func (a *App) initRepositories() *repositories { @@ -281,7 +323,6 @@ func (a *App) initRepositories() *repositories { chartOfAccountRepo: repository.NewChartOfAccountRepositoryImpl(a.db), accountRepo: repository.NewAccountRepositoryImpl(a.db), orderIngredientTransactionRepo: repository.NewOrderIngredientTransactionRepositoryImpl(a.db).(*repository.OrderIngredientTransactionRepositoryImpl), - customerTokensRepo: repository.NewCustomerTokensRepository(a.db), tierRepo: repository.NewTierRepository(a.db), gameRepo: repository.NewGameRepository(a.db), gamePrizeRepo: repository.NewGamePrizeRepository(a.db), @@ -291,7 +332,6 @@ func (a *App) initRepositories() *repositories { campaignRepo: repository.NewCampaignRepository(a.db), campaignRuleRepo: repository.NewCampaignRuleRepository(a.db), customerAuthRepo: repository.NewCustomerAuthRepository(a.db), - customerPointsRepo: repository.NewCustomerPointsRepository(a.db), otpRepo: repository.NewOtpRepository(a.db), sessionRepo: repository.NewSessionRepository(a.redisClient), txManager: repository.NewTxManager(a.db), @@ -302,6 +342,9 @@ func (a *App) initRepositories() *repositories { productOutletPriceRepo: repository.NewProductOutletPriceRepositoryImpl(a.db), expenseRepo: repository.NewExpenseRepositoryImpl(a.db), cashAdvanceRepo: repository.NewCashAdvanceRepositoryImpl(a.db), + walletRepo: repository.NewWalletRepository(a.db), + walletQueryRepo: repository.NewWalletQueryRepository(a.db), + loyaltySettingsRepo: repository.NewLoyaltySettingsRepository(a.db), } } @@ -331,7 +374,6 @@ type processors struct { chartOfAccountProcessor *processor.ChartOfAccountProcessorImpl accountProcessor *processor.AccountProcessorImpl orderIngredientTransactionProcessor *processor.OrderIngredientTransactionProcessorImpl - customerTokensProcessor *processor.CustomerTokensProcessor tierProcessor *processor.TierProcessor gameProcessor *processor.GameProcessor gamePrizeProcessor *processor.GamePrizeProcessor @@ -350,14 +392,44 @@ type processors struct { productOutletPriceProcessor processor.ProductOutletPriceProcessor expenseProcessor *processor.ExpenseProcessorImpl cashAdvanceProcessor *processor.CashAdvanceProcessorImpl + walletProcessor *processor.WalletProcessor + walletAdminProcessor *processor.WalletAdminProcessor + loyaltySettingsProcessor *processor.LoyaltySettingsProcessor + earningProcessor *processor.EarningProcessor + customerPinProcessor *processor.CustomerPinProcessor + paymentCodeProcessor *processor.PaymentCodeProcessor + pointPaymentProcessor *processor.PointPaymentProcessor + walletExchangeProcessor *processor.WalletExchangeProcessor + walletTransferProcessor *processor.WalletTransferProcessor + walletTraceProcessor *processor.WalletTraceProcessor + customerDeviceProcessor *processor.CustomerDeviceProcessor } func (a *App) initProcessors(cfg *config.Config, repos *repositories) *processors { fileClient := client.NewFileClient(cfg.S3Config) + fcmClient := buildFCMClient(cfg) + // Devices of the customer app, for pushes through FCM + customerDeviceProcessor := processor.NewCustomerDeviceProcessor(repository.NewCustomerDeviceRepository(a.db), fcmClient) fonnteClient := client.NewFonnteClient(cfg.GetFonnte()) otpProcessor := processor.NewOtpProcessor(fonnteClient, repos.otpRepo) + // Customer PIN (docs/prd-point-coin.md F11) + customerPinProcessor := processor.NewCustomerPinProcessor(repository.NewCustomerPinRepository(a.db), otpProcessor, customerDeviceProcessor) + paymentCodeProcessor := processor.NewPaymentCodeProcessor(repository.NewPaymentCodeRepository(a.redisClient), customerPinProcessor) inventoryMovementService := service.NewInventoryMovementService(repos.inventoryMovementRepo, repos.ingredientRepo) + orderProcessor := processor.NewOrderProcessorImpl(repos.orderRepo, repos.orderItemRepo, repos.paymentRepo, repos.paymentOrderItemRepo, repos.productRepo, repos.paymentMethodRepo, repos.inventoryRepo, repos.inventoryMovementRepo, repos.productVariantRepo, repos.outletRepo, repos.customerRepo, repos.txManager, repos.productRecipeRepo, repos.ingredientRepo, inventoryMovementService, repos.productOutletPriceRepo) + loyaltySettingsProcessor := processor.NewLoyaltySettingsProcessor(repos.loyaltySettingsRepo, repos.txManager) + // Earn EnakPoint and EnakCoin when an order becomes fully paid (docs/prd-point-coin.md F3) + earningProcessor := processor.NewEarningProcessor(repository.NewEarningRepository(a.db), loyaltySettingsProcessor, processor.NewWalletProcessor(repos.walletRepo), repos.txManager) + orderProcessor.SetLoyalty(earningProcessor) + // Pay orders with EnakPoint, approved by the customer's one-time code (docs/prd-point-coin.md F9) + pointPaymentProcessor := processor.NewPointPaymentProcessor(repository.NewPointPaymentRepository(a.db), loyaltySettingsProcessor, repos.walletQueryRepo, processor.NewWalletProcessor(repos.walletRepo), repos.txManager) + orderProcessor.SetPointPayments(pointPaymentProcessor, paymentCodeProcessor, customerPinProcessor) + // Exchange EnakCoin into EnakPoint, approved by the customer's PIN (docs/prd-point-coin.md F4) + walletExchangeProcessor := processor.NewWalletExchangeProcessor(repository.NewWalletMoveRepository(a.db), loyaltySettingsProcessor, repos.walletQueryRepo, customerPinProcessor, processor.NewWalletProcessor(repos.walletRepo), repos.txManager) + // Send EnakPoint or EnakCoin to another customer; the recipient gets a push through FCM (docs/prd-point-coin.md F5) + walletTransferProcessor := processor.NewWalletTransferProcessor(repository.NewWalletMoveRepository(a.db), loyaltySettingsProcessor, repos.walletQueryRepo, customerPinProcessor, processor.NewWalletProcessor(repos.walletRepo), repos.txManager, customerDeviceProcessor) + return &processors{ userProcessor: processor.NewUserProcessor(repos.userRepo, repos.organizationRepo, repos.outletRepo), organizationProcessor: processor.NewOrganizationProcessorImpl(repos.organizationRepo, repos.outletRepo, repos.userRepo), @@ -367,8 +439,8 @@ func (a *App) initProcessors(cfg *config.Config, repos *repositories) *processor productProcessor: processor.NewProductProcessorImpl(repos.productRepo, repos.categoryRepo, repos.productVariantRepo, repos.inventoryRepo, repos.outletRepo, repos.productOutletPriceRepo), productVariantProcessor: processor.NewProductVariantProcessorImpl(repos.productVariantRepo, repos.productRepo), inventoryProcessor: processor.NewInventoryProcessorImpl(repos.inventoryRepo, repos.productRepo, repos.outletRepo, repos.ingredientRepo, repos.inventoryMovementRepo), - orderProcessor: processor.NewOrderProcessorImpl(repos.orderRepo, repos.orderItemRepo, repos.paymentRepo, repos.paymentOrderItemRepo, repos.productRepo, repos.paymentMethodRepo, repos.inventoryRepo, repos.inventoryMovementRepo, repos.productVariantRepo, repos.outletRepo, repos.customerRepo, repos.txManager, repos.productRecipeRepo, repos.ingredientRepo, inventoryMovementService, repos.productOutletPriceRepo), - paymentMethodProcessor: processor.NewPaymentMethodProcessorImpl(repos.paymentMethodRepo), + orderProcessor: orderProcessor, + paymentMethodProcessor: processor.NewPaymentMethodProcessorImpl(repos.paymentMethodRepo, loyaltySettingsProcessor), fileProcessor: processor.NewFileProcessorImpl(repos.fileRepo, fileClient), customerProcessor: processor.NewCustomerProcessor(repos.customerRepo), analyticsProcessor: processor.NewAnalyticsProcessorImpl(repos.analyticsRepo, repos.expenseRepo), @@ -384,25 +456,35 @@ func (a *App) initProcessors(cfg *config.Config, repos *repositories) *processor chartOfAccountProcessor: processor.NewChartOfAccountProcessorImpl(repos.chartOfAccountRepo, repos.chartOfAccountTypeRepo), accountProcessor: processor.NewAccountProcessorImpl(repos.accountRepo, repos.chartOfAccountRepo), orderIngredientTransactionProcessor: processor.NewOrderIngredientTransactionProcessorImpl(repos.orderIngredientTransactionRepo, repos.productRecipeRepo, repos.ingredientRepo, repos.unitRepo).(*processor.OrderIngredientTransactionProcessorImpl), - customerTokensProcessor: processor.NewCustomerTokensProcessor(repos.customerTokensRepo), tierProcessor: processor.NewTierProcessor(repos.tierRepo), gameProcessor: processor.NewGameProcessor(repos.gameRepo), gamePrizeProcessor: processor.NewGamePrizeProcessor(repos.gamePrizeRepo), - gamePlayProcessor: processor.NewGamePlayProcessor(repos.gamePlayRepo, repos.gameRepo, repos.gamePrizeRepo, repos.customerTokensRepo, repos.customerPointsRepo), + gamePlayProcessor: processor.NewGamePlayProcessor(repos.gamePlayRepo, repos.gameRepo, repos.gamePrizeRepo, processor.NewWalletProcessor(repos.walletRepo), repos.walletQueryRepo, repos.txManager), omsetTrackerProcessor: processor.NewOmsetTrackerProcessor(repos.omsetTrackerRepo), rewardProcessor: processor.NewRewardProcessor(repos.rewardRepo), campaignProcessor: processor.NewCampaignProcessor(repos.campaignRepo), campaignRuleProcessor: processor.NewCampaignRuleProcessor(repos.campaignRuleRepo), customerAuthProcessor: processor.NewCustomerAuthProcessor(repos.customerAuthRepo, otpProcessor, repos.otpRepo, cfg.GetCustomerJWTSecret(), cfg.GetCustomerJWTExpiresTTL()), - customerPointsProcessor: processor.NewCustomerPointsProcessor(repos.customerPointsRepo, repos.gameRepo), + customerPointsProcessor: processor.NewCustomerPointsProcessor(processor.NewWalletQueryProcessor(repos.walletQueryRepo, processor.NewLoyaltySettingsProcessor(repos.loyaltySettingsRepo, repos.txManager)), repos.gameRepo), otpProcessor: otpProcessor, fileClient: fileClient, inventoryMovementService: inventoryMovementService, userDeviceProcessor: processor.NewUserDeviceProcessorImpl(repos.userDeviceRepo), - notificationProcessor: buildNotificationProcessor(cfg, repos), + notificationProcessor: buildNotificationProcessor(repos, fcmClient), productOutletPriceProcessor: processor.NewProductOutletPriceProcessorImpl(repos.productOutletPriceRepo, repos.productRepo, repos.outletRepo), expenseProcessor: processor.NewExpenseProcessorImpl(repos.expenseRepo, repos.purchaseCategoryRepo, repos.cashAdvanceRepo), cashAdvanceProcessor: processor.NewCashAdvanceProcessorImpl(repos.cashAdvanceRepo, repos.categoryRepo), + walletProcessor: processor.NewWalletProcessor(repos.walletRepo), + loyaltySettingsProcessor: loyaltySettingsProcessor, + earningProcessor: earningProcessor, + customerPinProcessor: customerPinProcessor, + paymentCodeProcessor: paymentCodeProcessor, + pointPaymentProcessor: pointPaymentProcessor, + walletExchangeProcessor: walletExchangeProcessor, + walletTransferProcessor: walletTransferProcessor, + walletTraceProcessor: processor.NewWalletTraceProcessor(repository.NewWalletTraceRepository(a.db)), + customerDeviceProcessor: customerDeviceProcessor, + walletAdminProcessor: processor.NewWalletAdminProcessor(repository.NewWalletAdminRepository(a.db), repos.walletQueryRepo, processor.NewWalletProcessor(repos.walletRepo), loyaltySettingsProcessor, repos.txManager), } } @@ -445,6 +527,13 @@ type services struct { productOutletPriceService service.ProductOutletPriceService expenseService *service.ExpenseServiceImpl cashAdvanceService *service.CashAdvanceServiceImpl + walletAdminService *service.WalletAdminServiceImpl + loyaltySettingsService *service.LoyaltySettingsServiceImpl + customerPinService *service.CustomerPinServiceImpl + pointPaymentService *service.PointPaymentServiceImpl + customerOrderPaymentService *service.CustomerOrderPaymentServiceImpl + customerWalletService *service.CustomerWalletServiceImpl + customerDeviceService *service.CustomerDeviceServiceImpl } func (a *App) initServices(processors *processors, repos *repositories, cfg *config.Config) *services { @@ -475,12 +564,12 @@ func (a *App) initServices(processors *processors, repos *repositories, cfg *con chartOfAccountService := service.NewChartOfAccountService(processors.chartOfAccountProcessor) accountService := service.NewAccountService(processors.accountProcessor) orderIngredientTransactionService := service.NewOrderIngredientTransactionService(processors.orderIngredientTransactionProcessor, repos.txManager) - gamificationService := service.NewGamificationService(processors.customerPointsProcessor, processors.customerTokensProcessor, processors.tierProcessor, processors.gameProcessor, processors.gamePrizeProcessor, processors.gamePlayProcessor, processors.omsetTrackerProcessor) + gamificationService := service.NewGamificationService(processors.tierProcessor, processors.gameProcessor, processors.gamePrizeProcessor, processors.gamePlayProcessor, processors.omsetTrackerProcessor) rewardService := service.NewRewardService(processors.rewardProcessor) campaignService := service.NewCampaignService(processors.campaignProcessor, processors.campaignRuleProcessor) customerAuthService := service.NewCustomerAuthService(processors.customerAuthProcessor) customerPointsService := service.NewCustomerPointsService(processors.customerPointsProcessor) - spinGameService := service.NewSpinGameService(processors.gamePlayProcessor, repos.txManager) + spinGameService := service.NewSpinGameService(processors.gamePlayProcessor) userDeviceService := service.NewUserDeviceService(processors.userDeviceProcessor) notificationService := service.NewNotificationService(processors.notificationProcessor) @@ -526,6 +615,13 @@ func (a *App) initServices(processors *processors, repos *repositories, cfg *con productOutletPriceService: service.NewProductOutletPriceService(processors.productOutletPriceProcessor), expenseService: service.NewExpenseService(processors.expenseProcessor), cashAdvanceService: service.NewCashAdvanceService(processors.cashAdvanceProcessor), + walletAdminService: service.NewWalletAdminService(processors.walletAdminProcessor, processors.walletTraceProcessor), + loyaltySettingsService: service.NewLoyaltySettingsService(processors.loyaltySettingsProcessor, repos.walletQueryRepo), + customerPinService: service.NewCustomerPinService(processors.customerPinProcessor, processors.paymentCodeProcessor), + pointPaymentService: service.NewPointPaymentService(processors.pointPaymentProcessor), + customerOrderPaymentService: service.NewCustomerOrderPaymentService(processors.orderProcessor), + customerWalletService: service.NewCustomerWalletService(processors.walletExchangeProcessor, processors.walletTransferProcessor), + customerDeviceService: service.NewCustomerDeviceService(processors.customerDeviceProcessor), } } @@ -571,6 +667,7 @@ type validators struct { productOutletPriceValidator *validator.ProductOutletPriceValidatorImpl expenseValidator *validator.ExpenseValidatorImpl cashAdvanceValidator *validator.CashAdvanceValidatorImpl + walletValidator *validator.WalletValidatorImpl } func (a *App) initValidators() *validators { @@ -604,22 +701,27 @@ func (a *App) initValidators() *validators { productOutletPriceValidator: validator.NewProductOutletPriceValidator(), expenseValidator: validator.NewExpenseValidator(), cashAdvanceValidator: validator.NewCashAdvanceValidator(), + walletValidator: validator.NewWalletValidator(), } } +// buildFCMClient connects to FCM, or returns nil when it is not configured or fails to +// start. FCM failing is non-fatal: pushes are skipped and notifications are still +// persisted. +func buildFCMClient(cfg *config.Config) client.FCMClient { + if cfg.FCM.CredentialsFile == "" { + return nil + } + fcmClient, err := client.NewFCMClient(&cfg.FCM) + if err != nil { + return nil + } + return fcmClient +} + // buildNotificationProcessor creates the notification processor with FCM integration. // If FCM is not configured, it returns a processor with a nil FCM client (FCM dispatch will be skipped). -func buildNotificationProcessor(cfg *config.Config, repos *repositories) *processor.NotificationProcessorImpl { - var fcmClient client.FCMClient - if cfg.FCM.CredentialsFile != "" { - var err error - fcmClient, err = client.NewFCMClient(&cfg.FCM) - if err != nil { - // FCM init failure is non-fatal; notifications will still be persisted. - fcmClient = nil - } - } - +func buildNotificationProcessor(repos *repositories, fcmClient client.FCMClient) *processor.NotificationProcessorImpl { return processor.NewNotificationProcessor( repos.notificationRepo, repos.notificationReceiverRepo, diff --git a/internal/constants/error.go b/internal/constants/error.go index c2cd49b..d0967fc 100644 --- a/internal/constants/error.go +++ b/internal/constants/error.go @@ -12,6 +12,12 @@ const ( ValidationErrorCode = "304" InvalidFieldErrorCode = "305" NotFoundErrorCode = "404" + // PIN outcomes the customer app tells apart (docs/prd-point-coin.md §9). + PinNotSetErrorCode = "PIN_NOT_SET" + PinInvalidErrorCode = "PIN_INVALID" + PinLockedErrorCode = "PIN_LOCKED" + TransferBlockedErrorCode = "TRANSFER_BLOCKED" + TooManyRequestsErrorCode = "429" ) const ( @@ -63,15 +69,23 @@ const ( ProductOutletPriceServiceEntity = "product_outlet_price_service" ExpenseServiceEntity = "expense_service" CashAdvanceServiceEntity = "cash_advance_service" + WalletServiceEntity = "wallet_service" + LoyaltySettingsServiceEntity = "loyalty_settings_service" + CustomerPinServiceEntity = "customer_pin_service" ) var HttpErrorMap = map[string]int{ - InternalServerErrorCode: http.StatusInternalServerError, - MissingFieldErrorCode: http.StatusBadRequest, - MalformedFieldErrorCode: http.StatusBadRequest, - ValidationErrorCode: http.StatusBadRequest, - InvalidFieldErrorCode: http.StatusBadRequest, - NotFoundErrorCode: http.StatusNotFound, + InternalServerErrorCode: http.StatusInternalServerError, + MissingFieldErrorCode: http.StatusBadRequest, + MalformedFieldErrorCode: http.StatusBadRequest, + ValidationErrorCode: http.StatusBadRequest, + InvalidFieldErrorCode: http.StatusBadRequest, + NotFoundErrorCode: http.StatusNotFound, + PinNotSetErrorCode: http.StatusForbidden, + PinInvalidErrorCode: http.StatusBadRequest, + PinLockedErrorCode: http.StatusLocked, + TransferBlockedErrorCode: http.StatusForbidden, + TooManyRequestsErrorCode: http.StatusTooManyRequests, } // Error messages diff --git a/internal/constants/loyalty.go b/internal/constants/loyalty.go new file mode 100644 index 0000000..6721edf --- /dev/null +++ b/internal/constants/loyalty.go @@ -0,0 +1,86 @@ +package constants + +// Loyalty setting keys (docs/prd-point-coin.md F1, F2, F12). Outlet keys live in +// outlet_settings and organization keys in organization_settings. A key that was +// never set takes the default in the PRD. + +// Per outlet (F1): what an order earns, and whether EnakPoint can pay. +const ( + LoyaltyPointEnabledKey = "loyalty.point.enabled" + 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" + LoyaltyCoinEarnPerAmountKey = "loyalty.coin.earn_per_amount" + LoyaltyCoinEarnValueKey = "loyalty.coin.earn_value" + LoyaltyCoinMinOrderAmountKey = "loyalty.coin.min_order_amount" + LoyaltyCoinMaxPerOrderKey = "loyalty.coin.max_per_order" + + LoyaltyPointAcceptPaymentKey = "loyalty.point.accept_payment" + LoyaltyPointMinPaymentPointsKey = "loyalty.point.min_payment_points" + LoyaltyPointMaxPaymentPercentKey = "loyalty.point.max_payment_percent" +) + +// Per organization (F2, F12): the value of EnakPoint, the exchange rate, transfers and +// expiry, which must be the same in every outlet. +const ( + LoyaltyPointValueKey = "loyalty.point.value" + + LoyaltyExchangeCoinAmountKey = "loyalty.exchange.coin_amount" + LoyaltyExchangePointAmountKey = "loyalty.exchange.point_amount" + + LoyaltyTransferEnabledKey = "loyalty.transfer.enabled" + LoyaltyTransferMinAmountKey = "loyalty.transfer.min_amount" + LoyaltyTransferMaxPerTransactionKey = "loyalty.transfer.max_per_transaction" + LoyaltyTransferDailyLimitKey = "loyalty.transfer.daily_limit" + + // Suffixes after "loyalty.point." or "loyalty.coin.". + LoyaltyExpiryEnabledSuffix = "expiry_enabled" + LoyaltyExpiryPeriodSuffix = "expiry_period" + LoyaltyExpiryUnitSuffix = "expiry_unit" + LoyaltyExpiryEndOfMonthSuffix = "expiry_end_of_month" + LoyaltyExpiryReminderDaysSuffix = "expiry_reminder_days" + LoyaltyExpiryModeSuffix = "expiry_mode" + LoyaltyExpiryFixedDatesSuffix = "expiry_fixed_dates" + LoyaltyExpiryGraceMonthsSuffix = "expiry_grace_months" +) + +// Units of loyalty.{point,coin}.expiry_unit. +const ( + LoyaltyExpiryUnitDay = "DAY" + LoyaltyExpiryUnitMonth = "MONTH" +) + +// Modes of loyalty.{point,coin}.expiry_mode (note N4, decided: both are supported). +const ( + // Every balance expires on the same fixed dates of the year, such as 31 Dec. + LoyaltyExpiryModeFixedDate = "FIXED_DATE" + // Every balance lasts a period from when it was received. + LoyaltyExpiryModeRolling = "ROLLING" +) + +// Defaults from the PRD. +const ( + LoyaltyPointEarnPerAmountDefault = int64(100) + LoyaltyCoinEarnPerAmountDefault = int64(25000) + LoyaltyEarnValueDefault = int64(1) + + LoyaltyMinPaymentPointsDefault = int64(1) + LoyaltyMaxPaymentPercentDefault = int64(100) + + LoyaltyPointValueDefault = int64(1) + LoyaltyExchangeAmountDefault = int64(1) + + LoyaltyTransferEnabledDefault = true + LoyaltyTransferMinAmountDefault = int64(1) + + LoyaltyExpiryPeriodDefault = int64(12) + LoyaltyExpiryUnitDefault = LoyaltyExpiryUnitMonth + LoyaltyExpiryReminderDaysDefault = int64(7) + LoyaltyExpiryModeDefault = LoyaltyExpiryModeFixedDate + // Once a year on 31 December, as MM-DD. + LoyaltyExpiryFixedDatesDefault = "12-31" + LoyaltyExpiryGraceMonthsDefault = int64(3) +) diff --git a/internal/constants/payment.go b/internal/constants/payment.go index a95330e..75138db 100644 --- a/internal/constants/payment.go +++ b/internal/constants/payment.go @@ -8,6 +8,9 @@ const ( PaymentMethodTypeDigitalWallet PaymentMethodType = "digital_wallet" PaymentMethodTypeQR PaymentMethodType = "qr" PaymentMethodTypeEDC PaymentMethodType = "edc" + // Paying with EnakPoint (docs/prd-point-coin.md F9). Not accepted as a payment method + // type until that phase ships. + PaymentMethodTypePoint PaymentMethodType = "point" ) type PaymentStatus string diff --git a/internal/constants/wallet.go b/internal/constants/wallet.go new file mode 100644 index 0000000..2892fdd --- /dev/null +++ b/internal/constants/wallet.go @@ -0,0 +1,44 @@ +package constants + +// The two balances a customer wallet holds (docs/prd-point-coin.md). EnakPoint pays +// for orders; EnakCoin is spent on games and can be exchanged into EnakPoint. +const ( + WalletCurrencyPoint = "POINT" + WalletCurrencyCoin = "COIN" +) + +func IsValidWalletCurrency(currency string) bool { + return currency == WalletCurrencyPoint || currency == WalletCurrencyCoin +} + +// Ledger row types. §8.1 of the PRD lists, per type, which currency it may use, which +// way it moves the balance, and which reference it must carry. +const ( + WalletTxTypeEarn = "EARN" + WalletTxTypeEarnReversal = "EARN_REVERSAL" + WalletTxTypePayment = "PAYMENT" + WalletTxTypePaymentRefund = "PAYMENT_REFUND" + WalletTxTypeExchangeOut = "EXCHANGE_OUT" + WalletTxTypeExchangeIn = "EXCHANGE_IN" + WalletTxTypeTransferOut = "TRANSFER_OUT" + WalletTxTypeTransferIn = "TRANSFER_IN" + WalletTxTypeGameSpend = "GAME_SPEND" + WalletTxTypeExpire = "EXPIRE" + WalletTxTypeAdjustment = "ADJUSTMENT" + WalletTxTypeMigration = "MIGRATION" + WalletTxTypeRewardRedeem = "REWARD_REDEEM" +) + +// What a ledger row's reference_id points at: where the value came from for a +// credit, or where it went for a debit. +const ( + WalletRefTypeOrder = "ORDER" + WalletRefTypePayment = "PAYMENT" + WalletRefTypeWalletTx = "WALLET_TX" + WalletRefTypeGamePlay = "GAME_PLAY" + WalletRefTypeLot = "LOT" + WalletRefTypeUser = "USER" + WalletRefTypeLegacyPoints = "LEGACY_POINTS" + WalletRefTypeLegacyTokens = "LEGACY_TOKENS" + WalletRefTypeRewardRedemption = "REWARD_REDEMPTION" +) diff --git a/internal/contract/analytics_contract.go b/internal/contract/analytics_contract.go index 1d2045f..3b48206 100644 --- a/internal/contract/analytics_contract.go +++ b/internal/contract/analytics_contract.go @@ -28,7 +28,11 @@ type PaymentMethodAnalyticsResponse struct { // PaymentMethodSummary represents the summary of payment method analytics type PaymentMethodSummary struct { + // Money actually received; EnakPoint is reported apart (docs/prd-point-coin.md F9). TotalAmount float64 `json:"total_amount"` + PointAmount float64 `json:"point_amount"` + PointsUsed int64 `json:"points_used"` + TotalWithPoints float64 `json:"total_with_points"` TotalOrders int64 `json:"total_orders"` TotalPayments int64 `json:"total_payments"` AverageOrderValue float64 `json:"average_order_value"` @@ -42,6 +46,8 @@ type PaymentMethodAnalyticsData struct { OrderCount int64 `json:"order_count"` PaymentCount int64 `json:"payment_count"` Percentage float64 `json:"percentage"` + PointsUsed int64 `json:"points_used"` + CountsAsCashIn bool `json:"counts_as_cash_in"` } type SalesAnalyticsRequest struct { diff --git a/internal/contract/campaign_contract.go b/internal/contract/campaign_contract.go index bb5e479..f19d4a2 100644 --- a/internal/contract/campaign_contract.go +++ b/internal/contract/campaign_contract.go @@ -12,7 +12,7 @@ import ( type CreateCampaignRequest struct { Name string `json:"name" binding:"required,min=1,max=150"` Description *string `json:"description,omitempty"` - Type string `json:"type" binding:"required,oneof=REWARD POINTS TOKENS MIXED"` + Type string `json:"type" binding:"required,oneof=REWARD POINTS COINS TOKENS MIXED"` StartDate time.Time `json:"start_date" binding:"required"` EndDate time.Time `json:"end_date" binding:"required"` IsActive bool `json:"is_active"` @@ -25,7 +25,7 @@ type UpdateCampaignRequest struct { ID uuid.UUID `json:"id" binding:"required"` Name string `json:"name" binding:"required,min=1,max=150"` Description *string `json:"description,omitempty"` - Type string `json:"type" binding:"required,oneof=REWARD POINTS TOKENS MIXED"` + Type string `json:"type" binding:"required,oneof=REWARD POINTS COINS TOKENS MIXED"` StartDate time.Time `json:"start_date" binding:"required"` EndDate time.Time `json:"end_date" binding:"required"` IsActive bool `json:"is_active"` @@ -58,7 +58,7 @@ type CreateCampaignRuleRequest struct { CampaignID uuid.UUID `json:"campaign_id" binding:"required"` RuleType string `json:"rule_type" binding:"required,oneof=TIER SPEND PRODUCT CATEGORY DAY LOCATION"` ConditionValue *string `json:"condition_value,omitempty"` - RewardType string `json:"reward_type" binding:"required,oneof=POINTS TOKENS REWARD"` + RewardType string `json:"reward_type" binding:"required,oneof=POINTS COINS TOKENS REWARD"` RewardValue *int64 `json:"reward_value,omitempty"` RewardSubtype *string `json:"reward_subtype,omitempty"` RewardRefID *uuid.UUID `json:"reward_ref_id,omitempty"` @@ -70,7 +70,7 @@ type UpdateCampaignRuleRequest struct { CampaignID uuid.UUID `json:"campaign_id" binding:"required"` RuleType string `json:"rule_type" binding:"required,oneof=TIER SPEND PRODUCT CATEGORY DAY LOCATION"` ConditionValue *string `json:"condition_value,omitempty"` - RewardType string `json:"reward_type" binding:"required,oneof=POINTS TOKENS REWARD"` + RewardType string `json:"reward_type" binding:"required,oneof=POINTS COINS TOKENS REWARD"` RewardValue *int64 `json:"reward_value,omitempty"` RewardSubtype *string `json:"reward_subtype,omitempty"` RewardRefID *uuid.UUID `json:"reward_ref_id,omitempty"` @@ -142,7 +142,7 @@ type ListCampaignRulesResponse struct { type CampaignRuleStruct struct { RuleType string `json:"rule_type" binding:"required,oneof=TIER SPEND PRODUCT CATEGORY DAY LOCATION"` ConditionValue *string `json:"condition_value,omitempty"` - RewardType string `json:"reward_type" binding:"required,oneof=POINTS TOKENS REWARD"` + RewardType string `json:"reward_type" binding:"required,oneof=POINTS COINS TOKENS REWARD"` RewardValue *int64 `json:"reward_value,omitempty"` RewardSubtype *string `json:"reward_subtype,omitempty"` RewardRefID *uuid.UUID `json:"reward_ref_id,omitempty"` diff --git a/internal/contract/customer_device_contract.go b/internal/contract/customer_device_contract.go new file mode 100644 index 0000000..f304af0 --- /dev/null +++ b/internal/contract/customer_device_contract.go @@ -0,0 +1,11 @@ +package contract + +// RegisterCustomerDeviceRequest is PUT /customer/devices: the FCM token the customer +// app got for this device. Send it after login and whenever FCM refreshes the token. +type RegisterCustomerDeviceRequest struct { + DeviceID string `json:"device_id" binding:"required"` + FCMToken string `json:"fcm_token" binding:"required"` + // android, ios or web. + Platform *string `json:"platform"` + AppVersion *string `json:"app_version"` +} diff --git a/internal/contract/customer_pin_contract.go b/internal/contract/customer_pin_contract.go new file mode 100644 index 0000000..cb550cc --- /dev/null +++ b/internal/contract/customer_pin_contract.go @@ -0,0 +1,39 @@ +package contract + +// Requests of /customer/pin and /marketing/customers/:id/pin (docs/prd-point-coin.md +// F11). PINs are strings so a leading zero is kept. + +type RequestPinOtpRequest struct { + // pin_setup or pin_reset. + Purpose string `json:"purpose" binding:"required"` +} + +type CreateCustomerPinRequest struct { + OtpToken string `json:"otp_token" binding:"required"` + OtpCode string `json:"otp_code" binding:"required"` + Pin string `json:"pin" binding:"required"` + ConfirmPin string `json:"confirm_pin" binding:"required"` +} + +type ChangeCustomerPinRequest struct { + OldPin string `json:"old_pin" binding:"required"` + Pin string `json:"pin" binding:"required"` + ConfirmPin string `json:"confirm_pin" binding:"required"` +} + +type ResetCustomerPinRequest = CreateCustomerPinRequest + +type RemoveCustomerPinRequest struct { + Reason string `json:"reason" binding:"required"` +} + +// IssuePaymentCodeRequest is POST /customer/wallet/payment-code. +type IssuePaymentCodeRequest struct { + Pin string `json:"pin" binding:"required"` +} + +// PayWithPointsRequest is POST /customer/orders/:id/pay-with-points. +type PayWithPointsRequest struct { + Points int64 `json:"points" binding:"required,min=1"` + Pin string `json:"pin" binding:"required"` +} diff --git a/internal/contract/customer_points_contract.go b/internal/contract/customer_points_contract.go index d7cd65a..591758c 100644 --- a/internal/contract/customer_points_contract.go +++ b/internal/contract/customer_points_contract.go @@ -2,66 +2,8 @@ package contract import ( "time" - - "github.com/google/uuid" ) -// Existing gamification contracts -type CreateCustomerPointsRequest struct { - CustomerID uuid.UUID `json:"customer_id" validate:"required"` - Balance int64 `json:"balance" validate:"min=0"` -} - -type UpdateCustomerPointsRequest struct { - Balance int64 `json:"balance" validate:"min=0"` -} - -type AddCustomerPointsRequest struct { - Points int64 `json:"points" validate:"required,min=1"` -} - -type DeductCustomerPointsRequest struct { - Points int64 `json:"points" validate:"required,min=1"` -} - -type CustomerPointsResponse struct { - ID uuid.UUID `json:"id"` - CustomerID uuid.UUID `json:"customer_id"` - Balance int64 `json:"balance"` - Customer *CustomerResponse `json:"customer,omitempty"` - CreatedAt time.Time `json:"created_at"` - UpdatedAt time.Time `json:"updated_at"` -} - -type ListCustomerPointsRequest struct { - Page int `json:"page" validate:"min=1"` - Limit int `json:"limit" validate:"min=1,max=100"` - Search string `json:"search"` - SortBy string `json:"sort_by" validate:"omitempty,oneof=balance created_at updated_at"` - SortOrder string `json:"sort_order" validate:"omitempty,oneof=asc desc"` -} - -type PaginatedCustomerPointsResponse struct { - Data []CustomerPointsResponse `json:"data"` - TotalCount int `json:"total_count"` - Page int `json:"page"` - Limit int `json:"limit"` - TotalPages int `json:"total_pages"` -} - -// New customer API contracts -type GetCustomerPointsRequest struct { - // No additional fields needed - customer ID comes from JWT token -} - -type GetCustomerTokensRequest struct { - // No additional fields needed - customer ID comes from JWT token -} - -type GetCustomerWalletRequest struct { - // No additional fields needed - customer ID comes from JWT token -} - // Response Contracts type GetCustomerPointsResponse struct { Status string `json:"status"` diff --git a/internal/contract/customer_tokens_contract.go b/internal/contract/customer_tokens_contract.go deleted file mode 100644 index 21d90c6..0000000 --- a/internal/contract/customer_tokens_contract.go +++ /dev/null @@ -1,52 +0,0 @@ -package contract - -import ( - "time" - - "github.com/google/uuid" -) - -type CreateCustomerTokensRequest struct { - CustomerID uuid.UUID `json:"customer_id" validate:"required"` - TokenType string `json:"token_type" validate:"required,oneof=SPIN RAFFLE MINIGAME"` - Balance int64 `json:"balance" validate:"min=0"` -} - -type UpdateCustomerTokensRequest struct { - Balance int64 `json:"balance" validate:"min=0"` -} - -type AddCustomerTokensRequest struct { - Tokens int64 `json:"tokens" validate:"required,min=1"` -} - -type DeductCustomerTokensRequest struct { - Tokens int64 `json:"tokens" validate:"required,min=1"` -} - -type CustomerTokensResponse struct { - ID uuid.UUID `json:"id"` - CustomerID uuid.UUID `json:"customer_id"` - TokenType string `json:"token_type"` - Balance int64 `json:"balance"` - Customer *CustomerResponse `json:"customer,omitempty"` - CreatedAt time.Time `json:"created_at"` - UpdatedAt time.Time `json:"updated_at"` -} - -type ListCustomerTokensRequest struct { - Page int `json:"page" validate:"min=1"` - Limit int `json:"limit" validate:"min=1,max=100"` - Search string `json:"search"` - TokenType string `json:"token_type" validate:"omitempty,oneof=SPIN RAFFLE MINIGAME"` - SortBy string `json:"sort_by" validate:"omitempty,oneof=balance token_type created_at updated_at"` - SortOrder string `json:"sort_order" validate:"omitempty,oneof=asc desc"` -} - -type PaginatedCustomerTokensResponse struct { - Data []CustomerTokensResponse `json:"data"` - TotalCount int `json:"total_count"` - Page int `json:"page"` - Limit int `json:"limit"` - TotalPages int `json:"total_pages"` -} diff --git a/internal/contract/game_play_contract.go b/internal/contract/game_play_contract.go index 57ab50d..b32ad4f 100644 --- a/internal/contract/game_play_contract.go +++ b/internal/contract/game_play_contract.go @@ -9,15 +9,17 @@ import ( type CreateGamePlayRequest struct { GameID uuid.UUID `json:"game_id" validate:"required"` CustomerID uuid.UUID `json:"customer_id" validate:"required"` - TokenUsed int `json:"token_used" validate:"min=0"` + CoinsUsed int `json:"coins_used" validate:"min=0"` RandomSeed *string `json:"random_seed,omitempty"` } type GamePlayResponse struct { - ID uuid.UUID `json:"id"` - GameID uuid.UUID `json:"game_id"` - CustomerID uuid.UUID `json:"customer_id"` - PrizeID *uuid.UUID `json:"prize_id,omitempty"` + ID uuid.UUID `json:"id"` + GameID uuid.UUID `json:"game_id"` + CustomerID uuid.UUID `json:"customer_id"` + PrizeID *uuid.UUID `json:"prize_id,omitempty"` + CoinsUsed int `json:"coins_used"` + // Deprecated: the same as CoinsUsed, kept until the apps read coins_used. TokenUsed int `json:"token_used"` RandomSeed *string `json:"random_seed,omitempty"` CreatedAt time.Time `json:"created_at"` @@ -33,7 +35,7 @@ type ListGamePlaysRequest struct { GameID *uuid.UUID `json:"game_id"` CustomerID *uuid.UUID `json:"customer_id"` PrizeID *uuid.UUID `json:"prize_id"` - SortBy string `json:"sort_by" validate:"omitempty,oneof=created_at token_used"` + SortBy string `json:"sort_by" validate:"omitempty,oneof=created_at coins_used token_used"` SortOrder string `json:"sort_order" validate:"omitempty,oneof=asc desc"` } @@ -45,14 +47,17 @@ type PaginatedGamePlaysResponse struct { TotalPages int `json:"total_pages"` } +// PlayGameRequest plays a game for a customer. What it costs is the game's +// metadata.coin_cost (docs/prd-point-coin.md F8), never the caller's choice. type PlayGameRequest struct { GameID uuid.UUID `json:"game_id" validate:"required"` CustomerID uuid.UUID `json:"customer_id" validate:"required"` - TokenUsed int `json:"token_used" validate:"min=0"` } type PlayGameResponse struct { - GamePlay GamePlayResponse `json:"game_play"` - PrizeWon *GamePrizeResponse `json:"prize_won,omitempty"` - TokensRemaining int64 `json:"tokens_remaining"` + GamePlay GamePlayResponse `json:"game_play"` + PrizeWon *GamePrizeResponse `json:"prize_won,omitempty"` + CoinsRemaining int64 `json:"coins_remaining"` + // Deprecated: the same as CoinsRemaining, kept until the apps read coins_remaining. + TokensRemaining int64 `json:"tokens_remaining"` } diff --git a/internal/contract/order_contract.go b/internal/contract/order_contract.go index 80ea44f..4ce5f20 100644 --- a/internal/contract/order_contract.go +++ b/internal/contract/order_contract.go @@ -92,6 +92,10 @@ type OrderResponse struct { TotalPaid float64 `json:"total_paid"` PaymentCount int `json:"payment_count"` SplitType *string `json:"split_type,omitempty"` + // EnakPoint and EnakCoin the order earned, for the order screen and the receipt + // (docs/prd-point-coin.md F3). Zero when it earned nothing. + PointsEarned int64 `json:"points_earned"` + CoinsEarned int64 `json:"coins_earned"` } type OrderItemResponse struct { @@ -182,9 +186,13 @@ type SetOrderCustomerResponse struct { } type CreatePaymentRequest struct { - OrderID uuid.UUID `json:"order_id" validate:"required"` - PaymentMethodID uuid.UUID `json:"payment_method_id" validate:"required"` - Amount float64 `json:"amount" validate:"required,min=0"` + OrderID uuid.UUID `json:"order_id" validate:"required"` + PaymentMethodID uuid.UUID `json:"payment_method_id" validate:"required"` + // For the EnakPoint method: how many to use and the code the customer shows. The + // amount is then computed from them. + Points *int64 `json:"points,omitempty"` + PaymentCode *string `json:"payment_code,omitempty"` + Amount float64 `json:"amount" validate:"min=0"` TransactionID *string `json:"transaction_id,omitempty" validate:"omitempty"` SplitNumber int `json:"split_number,omitempty" validate:"omitempty,min=1"` SplitTotal int `json:"split_total,omitempty" validate:"omitempty,min=1"` @@ -200,19 +208,23 @@ type CreatePaymentOrderItemRequest struct { } type PaymentResponse struct { - ID uuid.UUID `json:"id"` - OrderID uuid.UUID `json:"order_id"` - PaymentMethodID uuid.UUID `json:"payment_method_id"` - PaymentMethodName string `json:"payment_method_name"` - PaymentMethodType string `json:"payment_method_type"` - Amount float64 `json:"amount"` - Status string `json:"status"` - TransactionID *string `json:"transaction_id,omitempty"` - SplitNumber int `json:"split_number"` - SplitTotal int `json:"split_total"` - SplitType *string `json:"split_type,omitempty"` - SplitDescription *string `json:"split_description,omitempty"` - RefundAmount float64 `json:"refund_amount"` + ID uuid.UUID `json:"id"` + OrderID uuid.UUID `json:"order_id"` + PaymentMethodID uuid.UUID `json:"payment_method_id"` + PaymentMethodName string `json:"payment_method_name"` + PaymentMethodType string `json:"payment_method_type"` + Amount float64 `json:"amount"` + Status string `json:"status"` + TransactionID *string `json:"transaction_id,omitempty"` + SplitNumber int `json:"split_number"` + SplitTotal int `json:"split_total"` + SplitType *string `json:"split_type,omitempty"` + SplitDescription *string `json:"split_description,omitempty"` + RefundAmount float64 `json:"refund_amount"` + // Set for a payment with EnakPoint, for "EnakPoint: 50.000 (Rp 50.000)" on the + // receipt (docs/prd-point-coin.md F9). + PointsUsed *int64 `json:"points_used,omitempty"` + PointValue *float64 `json:"point_value,omitempty"` RefundReason *string `json:"refund_reason,omitempty"` RefundedAt *time.Time `json:"refunded_at,omitempty"` RefundedBy *uuid.UUID `json:"refunded_by,omitempty"` diff --git a/internal/contract/payment_method_contract.go b/internal/contract/payment_method_contract.go index 9153b7a..e7e2155 100644 --- a/internal/contract/payment_method_contract.go +++ b/internal/contract/payment_method_contract.go @@ -18,7 +18,7 @@ type CreatePaymentMethodRequest struct { type UpdatePaymentMethodRequest struct { Name *string `json:"name,omitempty" validate:"omitempty,min=1,max=100"` - Type *string `json:"type,omitempty" validate:"omitempty,oneof=cash card digital_wallet qr edc"` + Type *string `json:"type,omitempty" validate:"omitempty,oneof=cash card digital_wallet qr edc point"` Processor *string `json:"processor,omitempty" validate:"omitempty,max=100"` Configuration map[string]interface{} `json:"configuration,omitempty"` IsActive *bool `json:"is_active,omitempty"` @@ -38,11 +38,13 @@ type PaymentMethodResponse struct { type ListPaymentMethodsRequest struct { OrganizationID *uuid.UUID `json:"organization_id,omitempty"` - Type *string `json:"type,omitempty" validate:"omitempty,oneof=cash card digital_wallet qr edc"` - IsActive *bool `json:"is_active,omitempty"` - Search string `json:"search,omitempty"` - Page int `json:"page" validate:"min=1"` - Limit int `json:"limit" validate:"min=1,max=100"` + // When set, EnakPoint is left out unless the outlet accepts it (F9). + OutletID *uuid.UUID `json:"outlet_id,omitempty"` + Type *string `json:"type,omitempty" validate:"omitempty,oneof=cash card digital_wallet qr edc point"` + IsActive *bool `json:"is_active,omitempty"` + Search string `json:"search,omitempty"` + Page int `json:"page" validate:"min=1"` + Limit int `json:"limit" validate:"min=1,max=100"` } type ListPaymentMethodsResponse struct { diff --git a/internal/contract/spin_game_contract.go b/internal/contract/spin_game_contract.go index e41dc41..67b50b7 100644 --- a/internal/contract/spin_game_contract.go +++ b/internal/contract/spin_game_contract.go @@ -14,7 +14,9 @@ type SpinGameResponse struct { // SpinGameResponseData contains the game play result type SpinGameResponseData struct { - GamePlay GamePlayResponse `json:"game_play"` - PrizeWon *CustomerGamePrizeResponse `json:"prize_won,omitempty"` - TokensRemaining int64 `json:"tokens_remaining"` + GamePlay GamePlayResponse `json:"game_play"` + PrizeWon *CustomerGamePrizeResponse `json:"prize_won,omitempty"` + CoinsRemaining int64 `json:"coins_remaining"` + // Deprecated: the same as CoinsRemaining, kept until the apps read coins_remaining. + TokensRemaining int64 `json:"tokens_remaining"` } diff --git a/internal/contract/wallet_contract.go b/internal/contract/wallet_contract.go new file mode 100644 index 0000000..d261a95 --- /dev/null +++ b/internal/contract/wallet_contract.go @@ -0,0 +1,31 @@ +package contract + +// AdjustCustomerWalletRequest is POST /marketing/customers/:id/wallet/adjust +// (docs/prd-point-coin.md F7). +type AdjustCustomerWalletRequest struct { + // POINT or COIN. + Currency string `json:"currency"` + // Signed: positive adds to the balance, negative takes from it. Never zero. + Amount int64 `json:"amount"` + Reason string `json:"reason"` + // Optional. Sending the same key again returns the first result instead of + // adjusting twice, so a retried request is safe. + IdempotencyKey string `json:"idempotency_key"` +} + +// ExchangeCoinsRequest is POST /customer/wallet/exchange (docs/prd-point-coin.md F4). +// The Idempotency-Key header is required. +type ExchangeCoinsRequest struct { + Coins int64 `json:"coins" binding:"required,min=1"` + Pin string `json:"pin" binding:"required"` +} + +// TransferWalletRequest is POST /customer/wallet/transfer (docs/prd-point-coin.md F5). +// The Idempotency-Key header is required. +type TransferWalletRequest struct { + // POINT or COIN. + Currency string `json:"currency" binding:"required"` + Amount int64 `json:"amount" binding:"required,min=1"` + RecipientPhone string `json:"recipient_phone" binding:"required"` + Pin string `json:"pin" binding:"required"` +} diff --git a/internal/entities/analytics.go b/internal/entities/analytics.go index 87b9644..8446e86 100644 --- a/internal/entities/analytics.go +++ b/internal/entities/analytics.go @@ -14,6 +14,8 @@ type PaymentMethodAnalytics struct { TotalAmount float64 `json:"total_amount"` OrderCount int64 `json:"order_count"` PaymentCount int64 `json:"payment_count"` + // EnakPoint used, for the EnakPoint method. + PointsUsed int64 `json:"points_used"` } // SalesAnalytics represents sales analytics data @@ -173,15 +175,15 @@ type BudgetCutOffWeek struct { // DashboardOverview represents dashboard overview data type DashboardOverview struct { - TotalSales float64 `json:"total_sales"` - TotalOrders int64 `json:"total_orders"` - AverageOrderValue float64 `json:"average_order_value"` - TotalCustomers int64 `json:"total_customers"` - VoidedOrders int64 `json:"voided_orders"` - RefundedOrders int64 `json:"refunded_orders"` - TotalItemSold int64 `json:"total_item_sold"` - TotalLowStock int64 `json:"total_low_stock"` - TotalProductActive int64 `json:"total_product_active"` + TotalSales float64 `json:"total_sales"` + TotalOrders int64 `json:"total_orders"` + AverageOrderValue float64 `json:"average_order_value"` + TotalCustomers int64 `json:"total_customers"` + VoidedOrders int64 `json:"voided_orders"` + RefundedOrders int64 `json:"refunded_orders"` + TotalItemSold int64 `json:"total_item_sold"` + TotalLowStock int64 `json:"total_low_stock"` + TotalProductActive int64 `json:"total_product_active"` } type ProfitLossAnalytics struct { diff --git a/internal/entities/campaign.go b/internal/entities/campaign.go index bf76ac5..5eabd76 100644 --- a/internal/entities/campaign.go +++ b/internal/entities/campaign.go @@ -12,10 +12,31 @@ type CampaignType string const ( CampaignTypeReward CampaignType = "REWARD" CampaignTypePoints CampaignType = "POINTS" - CampaignTypeTokens CampaignType = "TOKENS" + CampaignTypeCoins CampaignType = "COINS" CampaignTypeMixed CampaignType = "MIXED" ) +// legacyCampaignTokens is what COINS was called before tokens became EnakCoin +// (docs/prd-point-coin.md §10). Requests may still send it; it is stored as COINS. +const legacyCampaignTokens = "TOKENS" + +// NormalizeCampaignType maps the legacy TOKENS to COINS and leaves anything else as is. +func NormalizeCampaignType(t string) CampaignType { + if t == legacyCampaignTokens { + return CampaignTypeCoins + } + return CampaignType(t) +} + +// NormalizeCampaignRewardType maps the legacy TOKENS to COINS and leaves anything +// else as is. +func NormalizeCampaignRewardType(t string) CampaignRewardType { + if t == legacyCampaignTokens { + return CampaignRewardTypeCoins + } + return CampaignRewardType(t) +} + type RuleType string const ( @@ -31,7 +52,7 @@ type CampaignRewardType string const ( CampaignRewardTypePoints CampaignRewardType = "POINTS" - CampaignRewardTypeTokens CampaignRewardType = "TOKENS" + CampaignRewardTypeCoins CampaignRewardType = "COINS" CampaignRewardTypeReward CampaignRewardType = "REWARD" ) diff --git a/internal/entities/campaign_test.go b/internal/entities/campaign_test.go new file mode 100644 index 0000000..5dd1cd0 --- /dev/null +++ b/internal/entities/campaign_test.go @@ -0,0 +1,18 @@ +package entities + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestNormalizeCampaignTypesMapsLegacyTokensToCoins(t *testing.T) { + assert.Equal(t, CampaignTypeCoins, NormalizeCampaignType("TOKENS")) + assert.Equal(t, CampaignTypeCoins, NormalizeCampaignType("COINS")) + assert.Equal(t, CampaignTypePoints, NormalizeCampaignType("POINTS")) + assert.Equal(t, CampaignType(""), NormalizeCampaignType(""), "an empty filter stays empty") + + assert.Equal(t, CampaignRewardTypeCoins, NormalizeCampaignRewardType("TOKENS")) + assert.Equal(t, CampaignRewardTypeReward, NormalizeCampaignRewardType("REWARD")) + assert.Equal(t, CampaignRewardType(""), NormalizeCampaignRewardType("")) +} diff --git a/internal/entities/entities.go b/internal/entities/entities.go index a5d6973..8ee2e10 100644 --- a/internal/entities/entities.go +++ b/internal/entities/entities.go @@ -44,6 +44,12 @@ func GetAllEntities() []interface{} { &ProductOutletPrice{}, &Expense{}, &CashAdvance{}, + // Wallet entities + &CustomerWallet{}, + &WalletTransaction{}, + &WalletLot{}, + &WalletLotAllocation{}, + &LoyaltySettingChange{}, } } diff --git a/internal/entities/game_play.go b/internal/entities/game_play.go index 5ef61f6..026ca95 100644 --- a/internal/entities/game_play.go +++ b/internal/entities/game_play.go @@ -12,7 +12,7 @@ type GamePlay struct { GameID uuid.UUID `gorm:"type:uuid;not null;index" json:"game_id" validate:"required"` CustomerID uuid.UUID `gorm:"type:uuid;not null;index" json:"customer_id" validate:"required"` PrizeID *uuid.UUID `gorm:"type:uuid" json:"prize_id,omitempty"` - TokenUsed int `gorm:"default:0" json:"token_used" validate:"min=0"` + CoinsUsed int `gorm:"column:coins_used;default:0" json:"coins_used" validate:"min=0"` RandomSeed *string `gorm:"type:varchar(255)" json:"random_seed,omitempty"` CreatedAt time.Time `gorm:"autoCreateTime" json:"created_at"` diff --git a/internal/entities/loyalty_setting_change.go b/internal/entities/loyalty_setting_change.go new file mode 100644 index 0000000..db5e8f2 --- /dev/null +++ b/internal/entities/loyalty_setting_change.go @@ -0,0 +1,34 @@ +package entities + +import ( + "time" + + "github.com/google/uuid" + "gorm.io/gorm" +) + +// LoyaltySettingChange records one change to a loyalty setting: which key, from what, +// to what, by whom (docs/prd-point-coin.md F2). Append-only. +type LoyaltySettingChange struct { + ID uuid.UUID `gorm:"type:uuid;primary_key;default:gen_random_uuid()" json:"id"` + OrganizationID uuid.UUID `gorm:"type:uuid;not null" json:"organization_id"` + // Nil for an organization setting. + OutletID *uuid.UUID `gorm:"type:uuid" json:"outlet_id"` + Key string `gorm:"not null;size:100" json:"key"` + // Nil when the key had no stored value, or has none any more. + OldValue *string `gorm:"type:text" json:"old_value"` + NewValue *string `gorm:"type:text" json:"new_value"` + ChangedBy uuid.UUID `gorm:"type:uuid;not null" json:"changed_by"` + CreatedAt time.Time `gorm:"autoCreateTime" json:"created_at"` +} + +func (c *LoyaltySettingChange) BeforeCreate(tx *gorm.DB) error { + if c.ID == uuid.Nil { + c.ID = uuid.New() + } + return nil +} + +func (LoyaltySettingChange) TableName() string { + return "loyalty_setting_changes" +} diff --git a/internal/entities/payment.go b/internal/entities/payment.go index 1e7ea29..f1bf058 100644 --- a/internal/entities/payment.go +++ b/internal/entities/payment.go @@ -13,13 +13,16 @@ const ( PaymentMethodTypeCash PaymentMethodType = "cash" PaymentMethodTypeCard PaymentMethodType = "card" PaymentMethodTypeDigitalWallet PaymentMethodType = "digital_wallet" + // The system method for paying with EnakPoint (docs/prd-point-coin.md F9). One per + // organization; it cannot be created, deleted or retyped through the API. + PaymentMethodTypePoint PaymentMethodType = "point" ) type PaymentMethod struct { ID uuid.UUID `gorm:"type:uuid;primary_key;default:gen_random_uuid()" json:"id"` OrganizationID uuid.UUID `gorm:"type:uuid;not null;index" json:"organization_id" validate:"required"` Name string `gorm:"not null;size:100" json:"name" validate:"required,min=1,max=100"` - Type PaymentMethodType `gorm:"not null;size:50" json:"type" validate:"required,oneof=cash card digital_wallet"` + Type PaymentMethodType `gorm:"not null;size:50" json:"type" validate:"required,oneof=cash card digital_wallet point"` Processor *string `gorm:"size:100" json:"processor"` Configuration Metadata `gorm:"type:jsonb;default:'{}'" json:"configuration"` IsActive bool `gorm:"default:true" json:"is_active"` @@ -69,12 +72,16 @@ type Payment struct { SplitType *SplitType `gorm:"size:20" json:"split_type,omitempty"` SplitDescription *string `gorm:"size:255" json:"split_description,omitempty"` RefundAmount float64 `gorm:"type:decimal(10,2);default:0.00" json:"refund_amount"` - RefundReason *string `gorm:"size:255" json:"refund_reason,omitempty"` - RefundedAt *time.Time `gorm:"" json:"refunded_at,omitempty"` - RefundedBy *uuid.UUID `gorm:"type:uuid" json:"refunded_by,omitempty"` - Metadata Metadata `gorm:"type:jsonb;default:'{}'" json:"metadata"` - CreatedAt time.Time `gorm:"autoCreateTime" json:"created_at"` - UpdatedAt time.Time `gorm:"autoUpdateTime" json:"updated_at"` + // Set only for a payment with EnakPoint: how many were used, and the rupiah value of + // one then, frozen so a refund returns exactly what was used. + PointsUsed *int64 `json:"points_used,omitempty"` + PointValue *float64 `gorm:"type:decimal(10,2)" json:"point_value,omitempty"` + RefundReason *string `gorm:"size:255" json:"refund_reason,omitempty"` + RefundedAt *time.Time `gorm:"" json:"refunded_at,omitempty"` + RefundedBy *uuid.UUID `gorm:"type:uuid" json:"refunded_by,omitempty"` + Metadata Metadata `gorm:"type:jsonb;default:'{}'" json:"metadata"` + CreatedAt time.Time `gorm:"autoCreateTime" json:"created_at"` + UpdatedAt time.Time `gorm:"autoUpdateTime" json:"updated_at"` Order Order `gorm:"foreignKey:OrderID" json:"order,omitempty"` PaymentMethod PaymentMethod `gorm:"foreignKey:PaymentMethodID" json:"payment_method,omitempty"` diff --git a/internal/entities/wallet.go b/internal/entities/wallet.go new file mode 100644 index 0000000..7b78cb2 --- /dev/null +++ b/internal/entities/wallet.go @@ -0,0 +1,113 @@ +package entities + +import ( + "time" + + "github.com/google/uuid" + "gorm.io/gorm" +) + +// CustomerWallet holds a customer's EnakPoint and EnakCoin balances. The row is also +// the lock every wallet operation for the customer takes first, so concurrent +// operations on one customer queue up instead of spending the same balance twice. +// +// Balances are never written directly: they only move together with a ledger row, and +// only through the wallet processor. +type CustomerWallet struct { + CustomerID uuid.UUID `gorm:"type:uuid;primary_key" json:"customer_id"` + OrganizationID uuid.UUID `gorm:"type:uuid;not null" json:"organization_id"` + PointBalance int64 `gorm:"not null;default:0" json:"point_balance"` + CoinBalance int64 `gorm:"not null;default:0" json:"coin_balance"` + CreatedAt time.Time `gorm:"autoCreateTime" json:"created_at"` + UpdatedAt time.Time `gorm:"autoUpdateTime" json:"updated_at"` +} + +func (CustomerWallet) TableName() string { + return "customer_wallets" +} + +// WalletTransaction is one ledger row. The ledger is append-only: a correction is a +// new row pointing at the one it corrects, never an update. +type WalletTransaction struct { + ID uuid.UUID `gorm:"type:uuid;primary_key;default:gen_random_uuid()" json:"id"` + OrganizationID uuid.UUID `gorm:"type:uuid;not null" json:"organization_id"` + CustomerID uuid.UUID `gorm:"type:uuid;not null" json:"customer_id"` + Currency string `gorm:"not null;size:10" json:"currency"` + Type string `gorm:"not null;size:30" json:"type"` + // Signed: positive credits the wallet, negative debits it. + Amount int64 `gorm:"not null" json:"amount"` + BalanceAfter int64 `gorm:"not null" json:"balance_after"` + GroupID *uuid.UUID `gorm:"type:uuid" json:"group_id"` + + // Where the value came from (credit) or went to (debit). + ReferenceType string `gorm:"not null;size:30" json:"reference_type"` + ReferenceID uuid.UUID `gorm:"type:uuid;not null" json:"reference_id"` + + CounterpartyCustomerID *uuid.UUID `gorm:"type:uuid" json:"counterparty_customer_id"` + ReversesTransactionID *uuid.UUID `gorm:"type:uuid" json:"reverses_transaction_id"` + OutletID *uuid.UUID `gorm:"type:uuid" json:"outlet_id"` + CreatedByUser *uuid.UUID `gorm:"type:uuid" json:"created_by_user"` + Reason *string `gorm:"size:255" json:"reason"` + + // Frozen at creation, so later renames do not rewrite history. + Description string `gorm:"not null;size:255" json:"description"` + Metadata Metadata `gorm:"type:jsonb;default:'{}'" json:"metadata"` + IdempotencyKey *string `gorm:"size:100;unique" json:"idempotency_key"` + CreatedAt time.Time `gorm:"autoCreateTime" json:"created_at"` +} + +func (t *WalletTransaction) BeforeCreate(tx *gorm.DB) error { + if t.ID == uuid.Nil { + t.ID = uuid.New() + } + // A nil map would be stored as JSON null rather than an empty object. + if t.Metadata == nil { + t.Metadata = Metadata{} + } + return nil +} + +func (WalletTransaction) TableName() string { + return "wallet_transactions" +} + +// WalletLot is one credited piece of balance with its own expiry (K9). Debits draw from +// the lots that expire soonest. A lot created by a transfer, exchange or refund carries +// the expiry of the lot it came from and points back at it through OriginLotID. +type WalletLot struct { + ID uuid.UUID `gorm:"type:uuid;primary_key;default:gen_random_uuid()" json:"id"` + OrganizationID uuid.UUID `gorm:"type:uuid;not null" json:"organization_id"` + CustomerID uuid.UUID `gorm:"type:uuid;not null" json:"customer_id"` + Currency string `gorm:"not null;size:10" json:"currency"` + SourceTransactionID uuid.UUID `gorm:"type:uuid;not null" json:"source_transaction_id"` + OriginLotID *uuid.UUID `gorm:"type:uuid" json:"origin_lot_id"` + OriginalAmount int64 `gorm:"not null" json:"original_amount"` + // A cache of OriginalAmount minus the lot's allocations, and the only wallet column + // that is ever updated. + RemainingAmount int64 `gorm:"not null" json:"remaining_amount"` + // Nil means the lot never expires. + ExpiresAt *time.Time `json:"expires_at"` + CreatedAt time.Time `gorm:"autoCreateTime" json:"created_at"` +} + +func (l *WalletLot) BeforeCreate(tx *gorm.DB) error { + if l.ID == uuid.Nil { + l.ID = uuid.New() + } + return nil +} + +func (WalletLot) TableName() string { + return "wallet_lots" +} + +// WalletLotAllocation records how much a debit ledger row drew from one lot. +type WalletLotAllocation struct { + TransactionID uuid.UUID `gorm:"type:uuid;primary_key" json:"transaction_id"` + LotID uuid.UUID `gorm:"type:uuid;primary_key" json:"lot_id"` + Amount int64 `gorm:"not null" json:"amount"` +} + +func (WalletLotAllocation) TableName() string { + return "wallet_lot_allocations" +} diff --git a/internal/handler/customer_device_handler.go b/internal/handler/customer_device_handler.go new file mode 100644 index 0000000..da03f32 --- /dev/null +++ b/internal/handler/customer_device_handler.go @@ -0,0 +1,45 @@ +package handler + +import ( + "github.com/gin-gonic/gin" + + "apskel-pos-be/internal/constants" + "apskel-pos-be/internal/contract" + "apskel-pos-be/internal/service" + "apskel-pos-be/internal/util" +) + +// CustomerDeviceHandler serves /customer/devices, where the customer app registers +// the FCM token of each device it runs on. +type CustomerDeviceHandler struct { + devices service.CustomerDeviceService +} + +func NewCustomerDeviceHandler(devices service.CustomerDeviceService) *CustomerDeviceHandler { + return &CustomerDeviceHandler{devices: devices} +} + +// Register is PUT /customer/devices. +func (h *CustomerDeviceHandler) Register(c *gin.Context) { + customerID, ok := customerIDFromGin(c, "CustomerDeviceHandler::Register") + if !ok { + return + } + var req contract.RegisterCustomerDeviceRequest + if err := c.ShouldBindJSON(&req); err != nil { + util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{ + contract.NewResponseError(constants.MissingFieldErrorCode, constants.RequestEntity, "device_id and fcm_token are required"), + }), "CustomerDeviceHandler::Register") + return + } + util.HandleResponse(c.Writer, c.Request, h.devices.Register(c.Request.Context(), customerID, &req), "CustomerDeviceHandler::Register") +} + +// Unregister is DELETE /customer/devices/:device_id, for logout. +func (h *CustomerDeviceHandler) Unregister(c *gin.Context) { + customerID, ok := customerIDFromGin(c, "CustomerDeviceHandler::Unregister") + if !ok { + return + } + util.HandleResponse(c.Writer, c.Request, h.devices.Unregister(c.Request.Context(), customerID, c.Param("device_id")), "CustomerDeviceHandler::Unregister") +} diff --git a/internal/handler/customer_order_payment_handler.go b/internal/handler/customer_order_payment_handler.go new file mode 100644 index 0000000..29f7071 --- /dev/null +++ b/internal/handler/customer_order_payment_handler.go @@ -0,0 +1,35 @@ +package handler + +import ( + "github.com/gin-gonic/gin" + + "apskel-pos-be/internal/contract" + "apskel-pos-be/internal/service" + "apskel-pos-be/internal/util" +) + +// CustomerOrderPaymentHandler serves POST /customer/orders/:id/pay-with-points +// (docs/prd-point-coin.md F9). The body holds the PIN, so it is never logged. +type CustomerOrderPaymentHandler struct { + payments service.CustomerOrderPaymentService +} + +func NewCustomerOrderPaymentHandler(payments service.CustomerOrderPaymentService) *CustomerOrderPaymentHandler { + return &CustomerOrderPaymentHandler{payments: payments} +} + +func (h *CustomerOrderPaymentHandler) PayWithPoints(c *gin.Context) { + customerID, ok := customerIDFromGin(c, "CustomerOrderPaymentHandler::PayWithPoints") + if !ok { + return + } + orderID, ok := parseUUIDParam(c, "id", "CustomerOrderPaymentHandler::PayWithPoints") + if !ok { + return + } + var req contract.PayWithPointsRequest + if !bindPinRequest(c, &req, "CustomerOrderPaymentHandler::PayWithPoints") { + return + } + util.HandleResponse(c.Writer, c.Request, h.payments.PayWithPoints(c.Request.Context(), customerID, orderID, &req, pinRequestInfo(c)), "CustomerOrderPaymentHandler::PayWithPoints") +} diff --git a/internal/handler/customer_pin_handler.go b/internal/handler/customer_pin_handler.go new file mode 100644 index 0000000..c0f9185 --- /dev/null +++ b/internal/handler/customer_pin_handler.go @@ -0,0 +1,151 @@ +package handler + +import ( + "strconv" + + "github.com/gin-gonic/gin" + "github.com/google/uuid" + + "apskel-pos-be/internal/appcontext" + "apskel-pos-be/internal/constants" + "apskel-pos-be/internal/contract" + "apskel-pos-be/internal/models" + "apskel-pos-be/internal/service" + "apskel-pos-be/internal/util" +) + +// CustomerPinHandler serves /customer/pin and the dashboard's PIN endpoints +// (docs/prd-point-coin.md F11). Request bodies hold PINs, so nothing here logs a body, +// and binding errors are reported without the values sent. +type CustomerPinHandler struct { + pinService service.CustomerPinService +} + +func NewCustomerPinHandler(pinService service.CustomerPinService) *CustomerPinHandler { + return &CustomerPinHandler{pinService: pinService} +} + +func (h *CustomerPinHandler) Status(c *gin.Context) { + customerID, ok := customerIDFromGin(c, "CustomerPinHandler::Status") + if !ok { + return + } + util.HandleResponse(c.Writer, c.Request, h.pinService.Status(c.Request.Context(), customerID), "CustomerPinHandler::Status") +} + +func (h *CustomerPinHandler) RequestOtp(c *gin.Context) { + customerID, ok := customerIDFromGin(c, "CustomerPinHandler::RequestOtp") + if !ok { + return + } + var req contract.RequestPinOtpRequest + if !bindPinRequest(c, &req, "CustomerPinHandler::RequestOtp") { + return + } + util.HandleResponse(c.Writer, c.Request, h.pinService.RequestOtp(c.Request.Context(), customerID, &req), "CustomerPinHandler::RequestOtp") +} + +func (h *CustomerPinHandler) CreatePin(c *gin.Context) { + customerID, ok := customerIDFromGin(c, "CustomerPinHandler::CreatePin") + if !ok { + return + } + var req contract.CreateCustomerPinRequest + if !bindPinRequest(c, &req, "CustomerPinHandler::CreatePin") { + return + } + util.HandleResponse(c.Writer, c.Request, h.pinService.CreatePin(c.Request.Context(), customerID, &req, pinRequestInfo(c)), "CustomerPinHandler::CreatePin") +} + +func (h *CustomerPinHandler) ChangePin(c *gin.Context) { + customerID, ok := customerIDFromGin(c, "CustomerPinHandler::ChangePin") + if !ok { + return + } + var req contract.ChangeCustomerPinRequest + if !bindPinRequest(c, &req, "CustomerPinHandler::ChangePin") { + return + } + util.HandleResponse(c.Writer, c.Request, h.pinService.ChangePin(c.Request.Context(), customerID, &req, pinRequestInfo(c)), "CustomerPinHandler::ChangePin") +} + +func (h *CustomerPinHandler) ResetPin(c *gin.Context) { + customerID, ok := customerIDFromGin(c, "CustomerPinHandler::ResetPin") + if !ok { + return + } + var req contract.ResetCustomerPinRequest + if !bindPinRequest(c, &req, "CustomerPinHandler::ResetPin") { + return + } + util.HandleResponse(c.Writer, c.Request, h.pinService.ResetPin(c.Request.Context(), customerID, &req, pinRequestInfo(c)), "CustomerPinHandler::ResetPin") +} + +// RemovePin is DELETE /marketing/customers/:id/pin. +func (h *CustomerPinHandler) RemovePin(c *gin.Context) { + customerID, ok := parseUUIDParam(c, "id", "CustomerPinHandler::RemovePin") + if !ok { + return + } + var req contract.RemoveCustomerPinRequest + if !bindPinRequest(c, &req, "CustomerPinHandler::RemovePin") { + return + } + ctx := c.Request.Context() + util.HandleResponse(c.Writer, c.Request, h.pinService.RemovePin(ctx, appcontext.FromGinContext(ctx), customerID, &req, pinRequestInfo(c)), "CustomerPinHandler::RemovePin") +} + +// ListSecurityEvents is GET /marketing/customers/:id/security-events. +func (h *CustomerPinHandler) ListSecurityEvents(c *gin.Context) { + customerID, ok := parseUUIDParam(c, "id", "CustomerPinHandler::ListSecurityEvents") + if !ok { + return + } + page, _ := strconv.Atoi(c.DefaultQuery("page", "1")) + limit, _ := strconv.Atoi(c.DefaultQuery("limit", "20")) + ctx := c.Request.Context() + util.HandleResponse(c.Writer, c.Request, h.pinService.ListSecurityEvents(ctx, appcontext.FromGinContext(ctx), customerID, page, limit), "CustomerPinHandler::ListSecurityEvents") +} + +// bindPinRequest binds a JSON body. The error it reports names what is wrong, never the +// values, since those can be PINs. +func bindPinRequest(c *gin.Context, req interface{}, method string) bool { + if err := c.ShouldBindJSON(req); err != nil { + util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{ + contract.NewResponseError(constants.MissingFieldErrorCode, constants.RequestEntity, "invalid request body: required fields are missing or have the wrong type"), + }), method) + return false + } + return true +} + +// customerIDFromGin reads the customer set by CustomerAuthMiddleware. +func customerIDFromGin(c *gin.Context, method string) (uuid.UUID, bool) { + raw, _ := c.Get("customer_id") + s, _ := raw.(string) + id, err := uuid.Parse(s) + if err != nil { + util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{ + contract.NewResponseError(constants.ValidationErrorCode, constants.AuthHandlerEntity, "Customer ID not found"), + }), method) + return uuid.Nil, false + } + return id, true +} + +func pinRequestInfo(c *gin.Context) models.CustomerPinRequestInfo { + return models.CustomerPinRequestInfo{IPAddress: c.ClientIP(), UserAgent: c.Request.UserAgent()} +} + +// IssuePaymentCode is POST /customer/wallet/payment-code. +func (h *CustomerPinHandler) IssuePaymentCode(c *gin.Context) { + customerID, ok := customerIDFromGin(c, "CustomerPinHandler::IssuePaymentCode") + if !ok { + return + } + var req contract.IssuePaymentCodeRequest + if !bindPinRequest(c, &req, "CustomerPinHandler::IssuePaymentCode") { + return + } + util.HandleResponse(c.Writer, c.Request, h.pinService.IssuePaymentCode(c.Request.Context(), customerID, &req, pinRequestInfo(c)), "CustomerPinHandler::IssuePaymentCode") +} diff --git a/internal/handler/customer_points_handler.go b/internal/handler/customer_points_handler.go index 8e98a26..0df8ff2 100644 --- a/internal/handler/customer_points_handler.go +++ b/internal/handler/customer_points_handler.go @@ -1,9 +1,14 @@ package handler import ( + "errors" + "apskel-pos-be/internal/constants" "apskel-pos-be/internal/contract" "apskel-pos-be/internal/logger" + "apskel-pos-be/internal/models" + "apskel-pos-be/internal/processor" + "apskel-pos-be/internal/repository" "apskel-pos-be/internal/service" "apskel-pos-be/internal/util" @@ -46,7 +51,7 @@ func (h *CustomerPointsHandler) GetCustomerPoints(c *gin.Context) { if err != nil { logger.FromContext(ctx).WithError(err).Error("CustomerPointsHandler::GetCustomerPoints -> service call failed") util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{ - contract.NewResponseError(constants.InternalServerErrorCode, constants.RequestEntity, err.Error()), + contract.NewResponseError(walletErrorCode(err), constants.RequestEntity, err.Error()), }), "CustomerPointsHandler::GetCustomerPoints") return } @@ -80,7 +85,7 @@ func (h *CustomerPointsHandler) GetCustomerTokens(c *gin.Context) { if err != nil { logger.FromContext(ctx).WithError(err).Error("CustomerPointsHandler::GetCustomerTokens -> service call failed") util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{ - contract.NewResponseError(constants.InternalServerErrorCode, constants.RequestEntity, err.Error()), + contract.NewResponseError(walletErrorCode(err), constants.RequestEntity, err.Error()), }), "CustomerPointsHandler::GetCustomerTokens") return } @@ -114,7 +119,7 @@ func (h *CustomerPointsHandler) GetCustomerWallet(c *gin.Context) { if err != nil { logger.FromContext(ctx).WithError(err).Error("CustomerPointsHandler::GetCustomerWallet -> service call failed") util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{ - contract.NewResponseError(constants.InternalServerErrorCode, constants.RequestEntity, err.Error()), + contract.NewResponseError(walletErrorCode(err), constants.RequestEntity, err.Error()), }), "CustomerPointsHandler::GetCustomerWallet") return } @@ -151,3 +156,74 @@ func (h *CustomerPointsHandler) GetFerrisWheelGame(c *gin.Context) { util.HandleResponse(c.Writer, c.Request, contract.BuildSuccessResponse(response), "CustomerPointsHandler::GetFerrisWheelGame") } + +// GetCustomerWalletTransactions is GET /customer/wallet/transactions: the ledger, newest +// first, filterable by currency, type and date (docs/prd-point-coin.md F6). +func (h *CustomerPointsHandler) GetCustomerWalletTransactions(c *gin.Context) { + ctx := c.Request.Context() + + customerID, ok := c.Get("customer_id") + customerIDStr, isString := customerID.(string) + if !ok || !isString { + logger.FromContext(ctx).Error("Customer ID not found in context") + util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{ + contract.NewResponseError(constants.ValidationErrorCode, constants.AuthHandlerEntity, "Customer ID not found"), + }), "CustomerPointsHandler::GetCustomerWalletTransactions") + return + } + + var query models.ListCustomerWalletTransactionsQuery + if err := c.ShouldBindQuery(&query); err != nil { + util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{ + contract.NewResponseError(constants.MalformedFieldErrorCode, constants.RequestEntity, err.Error()), + }), "CustomerPointsHandler::GetCustomerWalletTransactions") + return + } + + response, err := h.customerPointsService.GetCustomerWalletTransactions(ctx, customerIDStr, query) + if err != nil { + logger.FromContext(ctx).WithError(err).Error("CustomerPointsHandler::GetCustomerWalletTransactions -> service call failed") + util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{ + contract.NewResponseError(walletErrorCode(err), constants.RequestEntity, err.Error()), + }), "CustomerPointsHandler::GetCustomerWalletTransactions") + return + } + + util.HandleResponse(c.Writer, c.Request, contract.BuildSuccessResponse(response), "CustomerPointsHandler::GetCustomerWalletTransactions") +} + +// walletErrorCode tells a bad request apart from a server failure on the wallet +// endpoints. +func walletErrorCode(err error) string { + switch { + case errors.Is(err, processor.ErrInvalidWalletQuery): + return constants.ValidationErrorCode + case errors.Is(err, repository.ErrWalletNotFound): + return constants.NotFoundErrorCode + default: + return constants.InternalServerErrorCode + } +} + +// GetCustomerWalletExpiring is GET /customer/wallet/expiring: what will expire, per +// currency and day (docs/prd-point-coin.md F6). +func (h *CustomerPointsHandler) GetCustomerWalletExpiring(c *gin.Context) { + ctx := c.Request.Context() + customerID, ok := c.Get("customer_id") + customerIDStr, isString := customerID.(string) + if !ok || !isString { + util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{ + contract.NewResponseError(constants.ValidationErrorCode, constants.AuthHandlerEntity, "Customer ID not found"), + }), "CustomerPointsHandler::GetCustomerWalletExpiring") + return + } + response, err := h.customerPointsService.GetCustomerWalletExpiring(ctx, customerIDStr) + if err != nil { + logger.FromContext(ctx).WithError(err).Error("CustomerPointsHandler::GetCustomerWalletExpiring -> service call failed") + util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{ + contract.NewResponseError(walletErrorCode(err), constants.RequestEntity, err.Error()), + }), "CustomerPointsHandler::GetCustomerWalletExpiring") + return + } + util.HandleResponse(c.Writer, c.Request, contract.BuildSuccessResponse(response), "CustomerPointsHandler::GetCustomerWalletExpiring") +} diff --git a/internal/handler/customer_wallet_db_test.go b/internal/handler/customer_wallet_db_test.go new file mode 100644 index 0000000..d9e2467 --- /dev/null +++ b/internal/handler/customer_wallet_db_test.go @@ -0,0 +1,218 @@ +package handler + +import ( + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "os" + "testing" + "time" + + "github.com/gin-gonic/gin" + "github.com/google/uuid" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "gorm.io/driver/postgres" + "gorm.io/gorm" + "gorm.io/gorm/logger" + + "apskel-pos-be/internal/constants" + applogger "apskel-pos-be/internal/logger" + "apskel-pos-be/internal/processor" + "apskel-pos-be/internal/repository" + "apskel-pos-be/internal/service" +) + +// Drives the customer wallet endpoints over HTTP down to Postgres, to show the app +// gets the right numbers from the new endpoints and from the old /points, /tokens +// and /wallet shapes. Needs TEST_DATABASE_URL pointing at a migrated database; see +// internal/repository/wallet_repository_test.go. +func TestCustomerWalletEndpoints_AgainstPostgres(t *testing.T) { + dsn := os.Getenv("TEST_DATABASE_URL") + if dsn == "" { + t.Skip("TEST_DATABASE_URL not set") + } + applogger.Setup("fatal", "json") // the handlers log their errors; the server sets this up at startup + db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{Logger: logger.Default.LogMode(logger.Silent)}) + require.NoError(t, err) + + org, customer, other := uuid.New(), uuid.New(), uuid.New() + customers := []uuid.UUID{customer, other} + exec := func(q string, args ...any) { + t.Helper() + require.NoError(t, db.Exec(q, args...).Error) + } + exec(`INSERT INTO organizations (id, name, plan_type) VALUES (?, 'wallet api test', 'basic')`, org) + exec(`INSERT INTO customers (id, organization_id, name) VALUES (?, ?, 'A'), (?, ?, 'B')`, customer, org, other, org) + exec(`INSERT INTO organization_settings (organization_id, key, value) VALUES (?, ?, '100')`, org, constants.LoyaltyPointValueKey) + t.Cleanup(func() { + db.Exec(`DELETE FROM wallet_lot_allocations WHERE lot_id IN (SELECT id FROM wallet_lots WHERE customer_id IN ?)`, customers) + db.Exec(`DELETE FROM wallet_lots WHERE customer_id IN ?`, customers) + db.Exec(`DELETE FROM wallet_transactions WHERE customer_id IN ?`, customers) + db.Exec(`DELETE FROM customer_wallets WHERE customer_id IN ?`, customers) + db.Exec(`DELETE FROM customers WHERE id IN ?`, customers) + db.Exec(`DELETE FROM organization_settings WHERE organization_id = ?`, org) + db.Exec(`DELETE FROM organizations WHERE id = ?`, org) + }) + + // Balance: 300 earned in two lots that expire on the same Jakarta day but on + // different UTC days, 8 coins, 50 paid, and 20 in a lot that has expired but + // that the expiry job has not processed. + wallet := processor.NewWalletProcessor(repository.NewWalletRepository(db)) + txm := repository.NewTxManager(db) + next := time.Now().Year() + 1 + lateNightUTC := time.Date(next, 7, 1, 17, 30, 0, 0, time.UTC) // 2 July 00:30 WIB + afternoonUTC := time.Date(next, 7, 2, 10, 0, 0, 0, time.UTC) // 2 July 17:00 WIB + expired := time.Now().Add(-time.Hour) + outlet, order, payment := uuid.New(), uuid.New(), uuid.New() + require.NoError(t, txm.WithTransaction(context.Background(), func(ctx context.Context) error { + if _, err := wallet.Credit(ctx, processor.WalletCreditInput{ + WalletEntry: processor.WalletEntry{CustomerID: customer, Currency: constants.WalletCurrencyPoint, + Type: constants.WalletTxTypeEarn, Amount: 300, ReferenceType: constants.WalletRefTypeOrder, + ReferenceID: order, OutletID: &outlet, Description: "Belanja #ORD-1"}, + Lots: []processor.WalletLotInput{{Amount: 200, ExpiresAt: &afternoonUTC}, {Amount: 100, ExpiresAt: &lateNightUTC}}, + }); err != nil { + return err + } + if _, err := wallet.Credit(ctx, processor.WalletCreditInput{WalletEntry: processor.WalletEntry{ + CustomerID: customer, Currency: constants.WalletCurrencyCoin, Type: constants.WalletTxTypeMigration, + Amount: 8, ReferenceType: constants.WalletRefTypeLegacyTokens, ReferenceID: customer, + Description: "Saldo awal dari sistem lama"}}); err != nil { + return err + } + if _, err := wallet.Debit(ctx, processor.WalletDebitInput{WalletEntry: processor.WalletEntry{ + CustomerID: customer, Currency: constants.WalletCurrencyPoint, Type: constants.WalletTxTypePayment, + Amount: 50, ReferenceType: constants.WalletRefTypePayment, ReferenceID: payment, OutletID: &outlet, + Description: "Bayar #ORD-2"}}); err != nil { + return err + } + _, err := wallet.Credit(ctx, processor.WalletCreditInput{ + WalletEntry: processor.WalletEntry{CustomerID: customer, Currency: constants.WalletCurrencyPoint, + Type: constants.WalletTxTypeEarn, Amount: 20, ReferenceType: constants.WalletRefTypeOrder, + ReferenceID: uuid.New(), OutletID: &outlet, Description: "Belanja #ORD-0"}, + Lots: []processor.WalletLotInput{{Amount: 20, ExpiresAt: &expired}}, + }) + return err + })) + + h := NewCustomerPointsHandler(service.NewCustomerPointsService(processor.NewCustomerPointsProcessor( + processor.NewWalletQueryProcessor(repository.NewWalletQueryRepository(db), processor.NewLoyaltySettingsProcessor(repository.NewLoyaltySettingsRepository(db), repository.NewTxManager(db))), + nil, + ))) + gin.SetMode(gin.TestMode) + router := gin.New() + as := func(id uuid.UUID) gin.HandlerFunc { + return func(c *gin.Context) { c.Set("customer_id", id.String()) } + } + for _, who := range []struct { + prefix string + id uuid.UUID + }{{"/a", customer}, {"/b", other}, {"/gone", uuid.New()}} { + g := router.Group(who.prefix, as(who.id)) + g.GET("/points", h.GetCustomerPoints) + g.GET("/tokens", h.GetCustomerTokens) + g.GET("/wallet", h.GetCustomerWallet) + g.GET("/wallet/transactions", h.GetCustomerWalletTransactions) + } + get := func(path string) (int, map[string]any) { + t.Helper() + rec := httptest.NewRecorder() + router.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, path, nil)) + var body map[string]any + require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &body), rec.Body.String()) + return rec.Code, body + } + // The balance endpoints wrap their data in {status, message, data}. + inner := func(body map[string]any) map[string]any { + return body["data"].(map[string]any)["data"].(map[string]any) + } + + // Old app: /points and /tokens keep their shape and show the spendable balance. + status, body := get("/a/points") + require.Equal(t, http.StatusOK, status, body) + assert.EqualValues(t, 250, inner(body)["total_points"], "300 - 50; the expired 20 is not spendable") + assert.Len(t, inner(body)["points_history"], 3) + + status, body = get("/a/tokens") + require.Equal(t, http.StatusOK, status, body) + assert.EqualValues(t, 8, inner(body)["total_tokens"]) + + // /wallet: new fields, with the old ones still there. + status, body = get("/a/wallet") + require.Equal(t, http.StatusOK, status, body) + w := inner(body) + assert.EqualValues(t, 250, w["point_balance"]) + assert.EqualValues(t, 8, w["coin_balance"]) + assert.EqualValues(t, 100, w["point_value"]) + assert.EqualValues(t, 25000, w["point_discount_value"]) + nearest := w["nearest_expiring"].(map[string]any) + // The payment took 50 from the lot expiring first, leaving 50 + 200. + assert.Equal(t, map[string]any{"amount": float64(250), "date": time.Date(next, 7, 2, 0, 0, 0, 0, time.UTC).Format("2006-01-02")}, + nearest["point"], "both lots fall on 2 July in Jakarta although they are on different UTC days") + assert.Nil(t, nearest["coin"]) + for _, legacy := range []string{"total_points", "total_tokens", "points_history", "tokens_history", "last_updated"} { + assert.Contains(t, w, legacy) + } + assert.EqualValues(t, 250, w["total_points"]) + + recent := w["recent_transactions"].([]any) + require.Len(t, recent, 4) + for _, raw := range recent { + tx := raw.(map[string]any) + assert.NotContains(t, tx, "counterparty_customer_id") + assert.NotContains(t, tx, "metadata") + if tx["amount"].(float64) > 0 { + assert.Contains(t, tx, "source", tx["type"]) + assert.NotContains(t, tx, "destination") + } else { + assert.Equal(t, map[string]any{"type": "PAYMENT", "id": payment.String()}, tx["destination"]) + assert.NotContains(t, tx, "source") + } + } + + // History with filters. + status, body = get("/a/wallet/transactions?currency=POINT&type=EARN&limit=1&page=2") + require.Equal(t, http.StatusOK, status, body) + page := body["data"].(map[string]any) + assert.Equal(t, map[string]any{"page": float64(2), "limit": float64(1), "total_count": float64(2), "total_pages": float64(2)}, page["pagination"]) + rows := page["data"].([]any) + require.Len(t, rows, 1) + first := rows[0].(map[string]any) + assert.Equal(t, "Belanja #ORD-1", first["description"], "newest first, so page 2 is the older earning") + assert.Equal(t, map[string]any{"type": "ORDER", "id": order.String()}, first["source"]) + assert.Equal(t, lateNightUTC.Format(time.RFC3339), parseTime(t, first["expires_at"]).UTC().Format(time.RFC3339)) + assert.Len(t, first["lots"], 2) + + today := time.Now().In(time.FixedZone("WIB", 7*3600)).Format("2006-01-02") + status, body = get("/a/wallet/transactions?from=" + today + "&to=" + today + "&type=PAYMENT,MIGRATION") + require.Equal(t, http.StatusOK, status, body) + assert.EqualValues(t, 2, body["data"].(map[string]any)["pagination"].(map[string]any)["total_count"]) + + status, _ = get("/a/wallet/transactions?currency=GOLD") + assert.Equal(t, http.StatusBadRequest, status) + status, _ = get("/a/wallet/transactions?limit=abc") + assert.Equal(t, http.StatusBadRequest, status) + + // A customer who has never had a wallet sees zeros, not an error. + status, body = get("/b/wallet") + require.Equal(t, http.StatusOK, status, body) + assert.EqualValues(t, 0, inner(body)["point_balance"]) + assert.Equal(t, []any{}, inner(body)["recent_transactions"]) + status, body = get("/b/wallet/transactions") + require.Equal(t, http.StatusOK, status, body) + assert.Equal(t, []any{}, body["data"].(map[string]any)["data"]) + + // A token for a customer that no longer exists. + status, _ = get("/gone/wallet") + assert.Equal(t, http.StatusNotFound, status) +} + +func parseTime(t *testing.T, v any) time.Time { + t.Helper() + s, ok := v.(string) + require.True(t, ok, "expected a time string, got %v", v) + parsed, err := time.Parse(time.RFC3339Nano, s) + require.NoError(t, err) + return parsed +} diff --git a/internal/handler/customer_wallet_handler.go b/internal/handler/customer_wallet_handler.go new file mode 100644 index 0000000..90aed18 --- /dev/null +++ b/internal/handler/customer_wallet_handler.go @@ -0,0 +1,92 @@ +package handler + +import ( + "strconv" + "strings" + + "github.com/gin-gonic/gin" + + "apskel-pos-be/internal/constants" + "apskel-pos-be/internal/contract" + "apskel-pos-be/internal/service" + "apskel-pos-be/internal/util" +) + +// The header exchanges and transfers require (docs/prd-point-coin.md F4, F5), and the +// X- form the rest of the API uses, which is accepted too. +const ( + idempotencyKeyHeader = "Idempotency-Key" + legacyIdempotencyKeyHeader = "X-Idempotency-Key" +) + +// CustomerWalletHandler serves what the customer app does with its own wallet. Bodies +// hold the PIN, so they are never logged. +type CustomerWalletHandler struct { + wallets service.CustomerWalletService +} + +func NewCustomerWalletHandler(wallets service.CustomerWalletService) *CustomerWalletHandler { + return &CustomerWalletHandler{wallets: wallets} +} + +// PreviewExchange is GET /customer/wallet/exchange/preview?coins=. +func (h *CustomerWalletHandler) PreviewExchange(c *gin.Context) { + customerID, ok := customerIDFromGin(c, "CustomerWalletHandler::PreviewExchange") + if !ok { + return + } + var coins int64 + if raw := c.Query("coins"); raw != "" { + var err error + coins, err = strconv.ParseInt(raw, 10, 64) + if err != nil { + util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{ + contract.NewResponseError(constants.MalformedFieldErrorCode, constants.RequestEntity, "coins must be a whole number"), + }), "CustomerWalletHandler::PreviewExchange") + return + } + } + util.HandleResponse(c.Writer, c.Request, h.wallets.PreviewExchange(c.Request.Context(), customerID, coins), "CustomerWalletHandler::PreviewExchange") +} + +// Exchange is POST /customer/wallet/exchange. +func (h *CustomerWalletHandler) Exchange(c *gin.Context) { + customerID, ok := customerIDFromGin(c, "CustomerWalletHandler::Exchange") + if !ok { + return + } + var req contract.ExchangeCoinsRequest + if !bindPinRequest(c, &req, "CustomerWalletHandler::Exchange") { + return + } + util.HandleResponse(c.Writer, c.Request, h.wallets.Exchange(c.Request.Context(), customerID, &req, idempotencyKey(c), pinRequestInfo(c)), "CustomerWalletHandler::Exchange") +} + +func idempotencyKey(c *gin.Context) string { + if key := strings.TrimSpace(c.GetHeader(idempotencyKeyHeader)); key != "" { + return key + } + return strings.TrimSpace(c.GetHeader(legacyIdempotencyKeyHeader)) +} + +// TransferRecipient is GET /customer/wallet/transfer/recipient?phone=. +func (h *CustomerWalletHandler) TransferRecipient(c *gin.Context) { + customerID, ok := customerIDFromGin(c, "CustomerWalletHandler::TransferRecipient") + if !ok { + return + } + util.HandleResponse(c.Writer, c.Request, h.wallets.TransferRecipient(c.Request.Context(), customerID, c.Query("phone")), "CustomerWalletHandler::TransferRecipient") +} + +// Transfer is POST /customer/wallet/transfer. +func (h *CustomerWalletHandler) Transfer(c *gin.Context) { + customerID, ok := customerIDFromGin(c, "CustomerWalletHandler::Transfer") + if !ok { + return + } + var req contract.TransferWalletRequest + if !bindPinRequest(c, &req, "CustomerWalletHandler::Transfer") { + return + } + util.HandleResponse(c.Writer, c.Request, h.wallets.Transfer(c.Request.Context(), customerID, &req, idempotencyKey(c), pinRequestInfo(c)), "CustomerWalletHandler::Transfer") +} diff --git a/internal/handler/gamification_handler.go b/internal/handler/gamification_handler.go index 4344a35..4c3c606 100644 --- a/internal/handler/gamification_handler.go +++ b/internal/handler/gamification_handler.go @@ -9,7 +9,6 @@ import ( "apskel-pos-be/internal/validator" "github.com/gin-gonic/gin" - "github.com/google/uuid" ) type GamificationHandler struct { @@ -27,239 +26,6 @@ func NewGamificationHandler( } } -// Customer Points Handlers -func (h *GamificationHandler) CreateCustomerPoints(c *gin.Context) { - ctx := c.Request.Context() - - var req contract.CreateCustomerPointsRequest - if err := c.ShouldBindJSON(&req); err != nil { - logger.FromContext(c.Request.Context()).WithError(err).Error("GamificationHandler::CreateCustomerPoints -> request binding failed") - validationResponseError := contract.NewResponseError(constants.MissingFieldErrorCode, constants.RequestEntity, err.Error()) - util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{validationResponseError}), "GamificationHandler::CreateCustomerPoints") - return - } - - validationError, validationErrorCode := h.gamificationValidator.ValidateCreateCustomerPointsRequest(&req) - if validationError != nil { - logger.FromContext(c.Request.Context()).WithError(validationError).Error("GamificationHandler::CreateCustomerPoints -> request validation failed") - validationResponseError := contract.NewResponseError(validationErrorCode, constants.RequestEntity, validationError.Error()) - util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{validationResponseError}), "GamificationHandler::CreateCustomerPoints") - return - } - - response, err := h.gamificationService.CreateCustomerPoints(ctx, &req) - if err != nil { - logger.FromContext(c.Request.Context()).WithError(err).Error("GamificationHandler::CreateCustomerPoints -> service call failed") - util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{contract.NewResponseError(constants.InternalServerErrorCode, constants.CustomerPointsEntity, err.Error())}), "GamificationHandler::CreateCustomerPoints") - return - } - - util.HandleResponse(c.Writer, c.Request, contract.BuildSuccessResponse(response), "GamificationHandler::CreateCustomerPoints") -} - -func (h *GamificationHandler) GetCustomerPoints(c *gin.Context) { - ctx := c.Request.Context() - - idStr := c.Param("id") - id, err := uuid.Parse(idStr) - if err != nil { - logger.FromContext(c.Request.Context()).WithError(err).Error("GamificationHandler::GetCustomerPoints -> invalid ID") - validationResponseError := contract.NewResponseError(constants.InvalidFieldErrorCode, constants.CustomerPointsEntity, "Invalid ID format") - util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{validationResponseError}), "GamificationHandler::GetCustomerPoints") - return - } - - response, err := h.gamificationService.GetCustomerPoints(ctx, id) - if err != nil { - logger.FromContext(c.Request.Context()).WithError(err).Error("GamificationHandler::GetCustomerPoints -> service call failed") - util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{contract.NewResponseError(constants.InternalServerErrorCode, constants.CustomerPointsEntity, err.Error())}), "GamificationHandler::GetCustomerPoints") - return - } - - util.HandleResponse(c.Writer, c.Request, contract.BuildSuccessResponse(response), "GamificationHandler::GetCustomerPoints") -} - -func (h *GamificationHandler) GetCustomerPointsByCustomerID(c *gin.Context) { - ctx := c.Request.Context() - customerIDStr := c.Param("customer_id") - customerID, err := uuid.Parse(customerIDStr) - if err != nil { - logger.FromContext(c.Request.Context()).WithError(err).Error("GamificationHandler::GetCustomerPointsByCustomerID -> invalid customer ID") - validationResponseError := contract.NewResponseError(constants.InvalidFieldErrorCode, constants.CustomerPointsEntity, "Invalid customer ID format") - util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{validationResponseError}), "GamificationHandler::GetCustomerPointsByCustomerID") - return - } - - response, err := h.gamificationService.GetCustomerPointsByCustomerID(ctx, customerID) - if err != nil { - logger.FromContext(c.Request.Context()).WithError(err).Error("GamificationHandler::GetCustomerPointsByCustomerID -> service call failed") - util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{contract.NewResponseError(constants.InternalServerErrorCode, constants.CustomerPointsEntity, err.Error())}), "GamificationHandler::GetCustomerPointsByCustomerID") - return - } - - util.HandleResponse(c.Writer, c.Request, contract.BuildSuccessResponse(response), "GamificationHandler::GetCustomerPointsByCustomerID") -} - -func (h *GamificationHandler) ListCustomerPoints(c *gin.Context) { - ctx := c.Request.Context() - var req contract.ListCustomerPointsRequest - if err := c.ShouldBindQuery(&req); err != nil { - logger.FromContext(c.Request.Context()).WithError(err).Error("GamificationHandler::ListCustomerPoints -> request binding failed") - validationResponseError := contract.NewResponseError(constants.MissingFieldErrorCode, constants.RequestEntity, err.Error()) - util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{validationResponseError}), "GamificationHandler::ListCustomerPoints") - return - } - - validationError, validationErrorCode := h.gamificationValidator.ValidateListCustomerPointsRequest(&req) - if validationError != nil { - logger.FromContext(c.Request.Context()).WithError(validationError).Error("GamificationHandler::ListCustomerPoints -> request validation failed") - validationResponseError := contract.NewResponseError(validationErrorCode, constants.RequestEntity, validationError.Error()) - util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{validationResponseError}), "GamificationHandler::ListCustomerPoints") - return - } - - response, err := h.gamificationService.ListCustomerPoints(ctx, &req) - if err != nil { - logger.FromContext(c.Request.Context()).WithError(err).Error("GamificationHandler::ListCustomerPoints -> service call failed") - util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{contract.NewResponseError(constants.InternalServerErrorCode, constants.CustomerPointsEntity, err.Error())}), "GamificationHandler::ListCustomerPoints") - return - } - - util.HandleResponse(c.Writer, c.Request, contract.BuildSuccessResponse(response), "GamificationHandler::ListCustomerPoints") -} - -func (h *GamificationHandler) UpdateCustomerPoints(c *gin.Context) { - ctx := c.Request.Context() - idStr := c.Param("id") - id, err := uuid.Parse(idStr) - if err != nil { - logger.FromContext(c.Request.Context()).WithError(err).Error("GamificationHandler::UpdateCustomerPoints -> invalid ID") - validationResponseError := contract.NewResponseError(constants.InvalidFieldErrorCode, constants.CustomerPointsEntity, "Invalid ID format") - util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{validationResponseError}), "GamificationHandler::UpdateCustomerPoints") - return - } - - var req contract.UpdateCustomerPointsRequest - if err := c.ShouldBindJSON(&req); err != nil { - logger.FromContext(c.Request.Context()).WithError(err).Error("GamificationHandler::UpdateCustomerPoints -> request binding failed") - validationResponseError := contract.NewResponseError(constants.MissingFieldErrorCode, constants.RequestEntity, err.Error()) - util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{validationResponseError}), "GamificationHandler::UpdateCustomerPoints") - return - } - - validationError, validationErrorCode := h.gamificationValidator.ValidateUpdateCustomerPointsRequest(&req) - if validationError != nil { - logger.FromContext(c.Request.Context()).WithError(validationError).Error("GamificationHandler::UpdateCustomerPoints -> request validation failed") - validationResponseError := contract.NewResponseError(validationErrorCode, constants.RequestEntity, validationError.Error()) - util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{validationResponseError}), "GamificationHandler::UpdateCustomerPoints") - return - } - - response, err := h.gamificationService.UpdateCustomerPoints(ctx, id, &req) - if err != nil { - logger.FromContext(c.Request.Context()).WithError(err).Error("GamificationHandler::UpdateCustomerPoints -> service call failed") - util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{contract.NewResponseError(constants.InternalServerErrorCode, constants.CustomerPointsEntity, err.Error())}), "GamificationHandler::UpdateCustomerPoints") - return - } - - util.HandleResponse(c.Writer, c.Request, contract.BuildSuccessResponse(response), "GamificationHandler::UpdateCustomerPoints") -} - -func (h *GamificationHandler) DeleteCustomerPoints(c *gin.Context) { - ctx := c.Request.Context() - idStr := c.Param("id") - id, err := uuid.Parse(idStr) - if err != nil { - logger.FromContext(c.Request.Context()).WithError(err).Error("GamificationHandler::DeleteCustomerPoints -> invalid ID") - validationResponseError := contract.NewResponseError(constants.InvalidFieldErrorCode, constants.CustomerPointsEntity, "Invalid ID format") - util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{validationResponseError}), "GamificationHandler::DeleteCustomerPoints") - return - } - - err = h.gamificationService.DeleteCustomerPoints(ctx, id) - if err != nil { - logger.FromContext(c.Request.Context()).WithError(err).Error("GamificationHandler::DeleteCustomerPoints -> service call failed") - util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{contract.NewResponseError(constants.InternalServerErrorCode, constants.CustomerPointsEntity, err.Error())}), "GamificationHandler::DeleteCustomerPoints") - return - } - - util.HandleResponse(c.Writer, c.Request, contract.BuildSuccessResponse(nil), "GamificationHandler::DeleteCustomerPoints") -} - -func (h *GamificationHandler) AddCustomerPoints(c *gin.Context) { - ctx := c.Request.Context() - customerIDStr := c.Param("customer_id") - customerID, err := uuid.Parse(customerIDStr) - if err != nil { - logger.FromContext(c.Request.Context()).WithError(err).Error("GamificationHandler::AddCustomerPoints -> invalid customer ID") - validationResponseError := contract.NewResponseError(constants.InvalidFieldErrorCode, constants.CustomerPointsEntity, "Invalid customer ID format") - util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{validationResponseError}), "GamificationHandler::AddCustomerPoints") - return - } - - var req contract.AddCustomerPointsRequest - if err := c.ShouldBindJSON(&req); err != nil { - logger.FromContext(c.Request.Context()).WithError(err).Error("GamificationHandler::AddCustomerPoints -> request binding failed") - validationResponseError := contract.NewResponseError(constants.MissingFieldErrorCode, constants.RequestEntity, err.Error()) - util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{validationResponseError}), "GamificationHandler::AddCustomerPoints") - return - } - - validationError, validationErrorCode := h.gamificationValidator.ValidateAddCustomerPointsRequest(&req) - if validationError != nil { - logger.FromContext(c.Request.Context()).WithError(validationError).Error("GamificationHandler::AddCustomerPoints -> request validation failed") - validationResponseError := contract.NewResponseError(validationErrorCode, constants.RequestEntity, validationError.Error()) - util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{validationResponseError}), "GamificationHandler::AddCustomerPoints") - return - } - - response, err := h.gamificationService.AddCustomerPoints(ctx, customerID, &req) - if err != nil { - logger.FromContext(c.Request.Context()).WithError(err).Error("GamificationHandler::AddCustomerPoints -> service call failed") - util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{contract.NewResponseError(constants.InternalServerErrorCode, constants.CustomerPointsEntity, err.Error())}), "GamificationHandler::AddCustomerPoints") - return - } - - util.HandleResponse(c.Writer, c.Request, contract.BuildSuccessResponse(response), "GamificationHandler::AddCustomerPoints") -} - -func (h *GamificationHandler) DeductCustomerPoints(c *gin.Context) { - ctx := c.Request.Context() - customerIDStr := c.Param("customer_id") - customerID, err := uuid.Parse(customerIDStr) - if err != nil { - logger.FromContext(c.Request.Context()).WithError(err).Error("GamificationHandler::DeductCustomerPoints -> invalid customer ID") - validationResponseError := contract.NewResponseError(constants.InvalidFieldErrorCode, constants.CustomerPointsEntity, "Invalid customer ID format") - util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{validationResponseError}), "GamificationHandler::DeductCustomerPoints") - return - } - - var req contract.DeductCustomerPointsRequest - if err := c.ShouldBindJSON(&req); err != nil { - logger.FromContext(c.Request.Context()).WithError(err).Error("GamificationHandler::DeductCustomerPoints -> request binding failed") - validationResponseError := contract.NewResponseError(constants.MissingFieldErrorCode, constants.RequestEntity, err.Error()) - util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{validationResponseError}), "GamificationHandler::DeductCustomerPoints") - return - } - - validationError, validationErrorCode := h.gamificationValidator.ValidateDeductCustomerPointsRequest(&req) - if validationError != nil { - logger.FromContext(c.Request.Context()).WithError(validationError).Error("GamificationHandler::DeductCustomerPoints -> request validation failed") - validationResponseError := contract.NewResponseError(validationErrorCode, constants.RequestEntity, validationError.Error()) - util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{validationResponseError}), "GamificationHandler::DeductCustomerPoints") - return - } - - response, err := h.gamificationService.DeductCustomerPoints(ctx, customerID, &req) - if err != nil { - logger.FromContext(c.Request.Context()).WithError(err).Error("GamificationHandler::DeductCustomerPoints -> service call failed") - util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{contract.NewResponseError(constants.InternalServerErrorCode, constants.CustomerPointsEntity, err.Error())}), "GamificationHandler::DeductCustomerPoints") - return - } - - util.HandleResponse(c.Writer, c.Request, contract.BuildSuccessResponse(response), "GamificationHandler::DeductCustomerPoints") -} - // Play Game Handler func (h *GamificationHandler) PlayGame(c *gin.Context) { ctx := c.Request.Context() @@ -288,240 +54,3 @@ func (h *GamificationHandler) PlayGame(c *gin.Context) { util.HandleResponse(c.Writer, c.Request, contract.BuildSuccessResponse(response), "GamificationHandler::PlayGame") } - -// Additional handler methods for other gamification features -func (h *GamificationHandler) CreateCustomerTokens(c *gin.Context) { - ctx := c.Request.Context() - var req contract.CreateCustomerTokensRequest - if err := c.ShouldBindJSON(&req); err != nil { - logger.FromContext(c.Request.Context()).WithError(err).Error("GamificationHandler::CreateCustomerTokens -> request binding failed") - validationResponseError := contract.NewResponseError(constants.MissingFieldErrorCode, constants.RequestEntity, err.Error()) - util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{validationResponseError}), "GamificationHandler::CreateCustomerTokens") - return - } - - validationError, validationErrorCode := h.gamificationValidator.ValidateCreateCustomerTokensRequest(&req) - if validationError != nil { - logger.FromContext(c.Request.Context()).WithError(validationError).Error("GamificationHandler::CreateCustomerTokens -> request validation failed") - validationResponseError := contract.NewResponseError(validationErrorCode, constants.RequestEntity, validationError.Error()) - util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{validationResponseError}), "GamificationHandler::CreateCustomerTokens") - return - } - - response, err := h.gamificationService.CreateCustomerTokens(ctx, &req) - if err != nil { - logger.FromContext(c.Request.Context()).WithError(err).Error("GamificationHandler::CreateCustomerTokens -> service call failed") - util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{contract.NewResponseError(constants.InternalServerErrorCode, constants.CustomerTokensEntity, err.Error())}), "GamificationHandler::CreateCustomerTokens") - return - } - - util.HandleResponse(c.Writer, c.Request, contract.BuildSuccessResponse(response), "GamificationHandler::CreateCustomerTokens") -} - -func (h *GamificationHandler) GetCustomerTokens(c *gin.Context) { - ctx := c.Request.Context() - idStr := c.Param("id") - id, err := uuid.Parse(idStr) - if err != nil { - logger.FromContext(c.Request.Context()).WithError(err).Error("GamificationHandler::GetCustomerTokens -> invalid ID") - validationResponseError := contract.NewResponseError(constants.InvalidFieldErrorCode, constants.CustomerTokensEntity, "Invalid ID format") - util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{validationResponseError}), "GamificationHandler::GetCustomerTokens") - return - } - - response, err := h.gamificationService.GetCustomerTokens(ctx, id) - if err != nil { - logger.FromContext(c.Request.Context()).WithError(err).Error("GamificationHandler::GetCustomerTokens -> service call failed") - util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{contract.NewResponseError(constants.InternalServerErrorCode, constants.CustomerTokensEntity, err.Error())}), "GamificationHandler::GetCustomerTokens") - return - } - - util.HandleResponse(c.Writer, c.Request, contract.BuildSuccessResponse(response), "GamificationHandler::GetCustomerTokens") -} - -func (h *GamificationHandler) GetCustomerTokensByCustomerIDAndType(c *gin.Context) { - ctx := c.Request.Context() - customerIDStr := c.Param("customer_id") - customerID, err := uuid.Parse(customerIDStr) - if err != nil { - logger.FromContext(c.Request.Context()).WithError(err).Error("GamificationHandler::GetCustomerTokensByCustomerIDAndType -> invalid customer ID") - validationResponseError := contract.NewResponseError(constants.InvalidFieldErrorCode, constants.CustomerTokensEntity, "Invalid customer ID format") - util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{validationResponseError}), "GamificationHandler::GetCustomerTokensByCustomerIDAndType") - return - } - - tokenType := c.Param("token_type") - - response, err := h.gamificationService.GetCustomerTokensByCustomerIDAndType(ctx, customerID, tokenType) - if err != nil { - logger.FromContext(c.Request.Context()).WithError(err).Error("GamificationHandler::GetCustomerTokensByCustomerIDAndType -> service call failed") - util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{contract.NewResponseError(constants.InternalServerErrorCode, constants.CustomerTokensEntity, err.Error())}), "GamificationHandler::GetCustomerTokensByCustomerIDAndType") - return - } - - util.HandleResponse(c.Writer, c.Request, contract.BuildSuccessResponse(response), "GamificationHandler::GetCustomerTokensByCustomerIDAndType") -} - -func (h *GamificationHandler) ListCustomerTokens(c *gin.Context) { - ctx := c.Request.Context() - var req contract.ListCustomerTokensRequest - if err := c.ShouldBindQuery(&req); err != nil { - logger.FromContext(c.Request.Context()).WithError(err).Error("GamificationHandler::ListCustomerTokens -> request binding failed") - validationResponseError := contract.NewResponseError(constants.MissingFieldErrorCode, constants.RequestEntity, err.Error()) - util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{validationResponseError}), "GamificationHandler::ListCustomerTokens") - return - } - - validationError, validationErrorCode := h.gamificationValidator.ValidateListCustomerTokensRequest(&req) - if validationError != nil { - logger.FromContext(c.Request.Context()).WithError(validationError).Error("GamificationHandler::ListCustomerTokens -> request validation failed") - validationResponseError := contract.NewResponseError(validationErrorCode, constants.RequestEntity, validationError.Error()) - util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{validationResponseError}), "GamificationHandler::ListCustomerTokens") - return - } - - response, err := h.gamificationService.ListCustomerTokens(ctx, &req) - if err != nil { - logger.FromContext(c.Request.Context()).WithError(err).Error("GamificationHandler::ListCustomerTokens -> service call failed") - util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{contract.NewResponseError(constants.InternalServerErrorCode, constants.CustomerTokensEntity, err.Error())}), "GamificationHandler::ListCustomerTokens") - return - } - - util.HandleResponse(c.Writer, c.Request, contract.BuildSuccessResponse(response), "GamificationHandler::ListCustomerTokens") -} - -func (h *GamificationHandler) UpdateCustomerTokens(c *gin.Context) { - ctx := c.Request.Context() - idStr := c.Param("id") - id, err := uuid.Parse(idStr) - if err != nil { - logger.FromContext(c.Request.Context()).WithError(err).Error("GamificationHandler::UpdateCustomerTokens -> invalid ID") - validationResponseError := contract.NewResponseError(constants.InvalidFieldErrorCode, constants.CustomerTokensEntity, "Invalid ID format") - util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{validationResponseError}), "GamificationHandler::UpdateCustomerTokens") - return - } - - var req contract.UpdateCustomerTokensRequest - if err := c.ShouldBindJSON(&req); err != nil { - logger.FromContext(c.Request.Context()).WithError(err).Error("GamificationHandler::UpdateCustomerTokens -> request binding failed") - validationResponseError := contract.NewResponseError(constants.MissingFieldErrorCode, constants.RequestEntity, err.Error()) - util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{validationResponseError}), "GamificationHandler::UpdateCustomerTokens") - return - } - - validationError, validationErrorCode := h.gamificationValidator.ValidateUpdateCustomerTokensRequest(&req) - if validationError != nil { - logger.FromContext(c.Request.Context()).WithError(validationError).Error("GamificationHandler::UpdateCustomerTokens -> request validation failed") - validationResponseError := contract.NewResponseError(validationErrorCode, constants.RequestEntity, validationError.Error()) - util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{validationResponseError}), "GamificationHandler::UpdateCustomerTokens") - return - } - - response, err := h.gamificationService.UpdateCustomerTokens(ctx, id, &req) - if err != nil { - logger.FromContext(c.Request.Context()).WithError(err).Error("GamificationHandler::UpdateCustomerTokens -> service call failed") - util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{contract.NewResponseError(constants.InternalServerErrorCode, constants.CustomerTokensEntity, err.Error())}), "GamificationHandler::UpdateCustomerTokens") - return - } - - util.HandleResponse(c.Writer, c.Request, contract.BuildSuccessResponse(response), "GamificationHandler::UpdateCustomerTokens") -} - -func (h *GamificationHandler) DeleteCustomerTokens(c *gin.Context) { - ctx := c.Request.Context() - idStr := c.Param("id") - id, err := uuid.Parse(idStr) - if err != nil { - logger.FromContext(c.Request.Context()).WithError(err).Error("GamificationHandler::DeleteCustomerTokens -> invalid ID") - validationResponseError := contract.NewResponseError(constants.InvalidFieldErrorCode, constants.CustomerTokensEntity, "Invalid ID format") - util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{validationResponseError}), "GamificationHandler::DeleteCustomerTokens") - return - } - - err = h.gamificationService.DeleteCustomerTokens(ctx, id) - if err != nil { - logger.FromContext(c.Request.Context()).WithError(err).Error("GamificationHandler::DeleteCustomerTokens -> service call failed") - util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{contract.NewResponseError(constants.InternalServerErrorCode, constants.CustomerTokensEntity, err.Error())}), "GamificationHandler::DeleteCustomerTokens") - return - } - - util.HandleResponse(c.Writer, c.Request, contract.BuildSuccessResponse(nil), "GamificationHandler::DeleteCustomerTokens") -} - -func (h *GamificationHandler) AddCustomerTokens(c *gin.Context) { - ctx := c.Request.Context() - customerIDStr := c.Param("customer_id") - customerID, err := uuid.Parse(customerIDStr) - if err != nil { - logger.FromContext(c.Request.Context()).WithError(err).Error("GamificationHandler::AddCustomerTokens -> invalid customer ID") - validationResponseError := contract.NewResponseError(constants.InvalidFieldErrorCode, constants.CustomerTokensEntity, "Invalid customer ID format") - util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{validationResponseError}), "GamificationHandler::AddCustomerTokens") - return - } - - tokenType := c.Param("token_type") - - var req contract.AddCustomerTokensRequest - if err := c.ShouldBindJSON(&req); err != nil { - logger.FromContext(c.Request.Context()).WithError(err).Error("GamificationHandler::AddCustomerTokens -> request binding failed") - validationResponseError := contract.NewResponseError(constants.MissingFieldErrorCode, constants.RequestEntity, err.Error()) - util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{validationResponseError}), "GamificationHandler::AddCustomerTokens") - return - } - - validationError, validationErrorCode := h.gamificationValidator.ValidateAddCustomerTokensRequest(&req) - if validationError != nil { - logger.FromContext(c.Request.Context()).WithError(validationError).Error("GamificationHandler::AddCustomerTokens -> request validation failed") - validationResponseError := contract.NewResponseError(validationErrorCode, constants.RequestEntity, validationError.Error()) - util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{validationResponseError}), "GamificationHandler::AddCustomerTokens") - return - } - - response, err := h.gamificationService.AddCustomerTokens(ctx, customerID, tokenType, &req) - if err != nil { - logger.FromContext(c.Request.Context()).WithError(err).Error("GamificationHandler::AddCustomerTokens -> service call failed") - util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{contract.NewResponseError(constants.InternalServerErrorCode, constants.CustomerTokensEntity, err.Error())}), "GamificationHandler::AddCustomerTokens") - return - } - - util.HandleResponse(c.Writer, c.Request, contract.BuildSuccessResponse(response), "GamificationHandler::AddCustomerTokens") -} - -func (h *GamificationHandler) DeductCustomerTokens(c *gin.Context) { - ctx := c.Request.Context() - customerIDStr := c.Param("customer_id") - customerID, err := uuid.Parse(customerIDStr) - if err != nil { - logger.FromContext(c.Request.Context()).WithError(err).Error("GamificationHandler::DeductCustomerTokens -> invalid customer ID") - validationResponseError := contract.NewResponseError(constants.InvalidFieldErrorCode, constants.CustomerTokensEntity, "Invalid customer ID format") - util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{validationResponseError}), "GamificationHandler::DeductCustomerTokens") - return - } - - tokenType := c.Param("token_type") - - var req contract.DeductCustomerTokensRequest - if err := c.ShouldBindJSON(&req); err != nil { - logger.FromContext(c.Request.Context()).WithError(err).Error("GamificationHandler::DeductCustomerTokens -> request binding failed") - validationResponseError := contract.NewResponseError(constants.MissingFieldErrorCode, constants.RequestEntity, err.Error()) - util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{validationResponseError}), "GamificationHandler::DeductCustomerTokens") - return - } - - validationError, validationErrorCode := h.gamificationValidator.ValidateDeductCustomerTokensRequest(&req) - if validationError != nil { - logger.FromContext(c.Request.Context()).WithError(validationError).Error("GamificationHandler::DeductCustomerTokens -> request validation failed") - validationResponseError := contract.NewResponseError(validationErrorCode, constants.RequestEntity, validationError.Error()) - util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{validationResponseError}), "GamificationHandler::DeductCustomerTokens") - return - } - - response, err := h.gamificationService.DeductCustomerTokens(ctx, customerID, tokenType, &req) - if err != nil { - logger.FromContext(c.Request.Context()).WithError(err).Error("GamificationHandler::DeductCustomerTokens -> service call failed") - util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{contract.NewResponseError(constants.InternalServerErrorCode, constants.CustomerTokensEntity, err.Error())}), "GamificationHandler::DeductCustomerTokens") - return - } - - util.HandleResponse(c.Writer, c.Request, contract.BuildSuccessResponse(response), "GamificationHandler::DeductCustomerTokens") -} diff --git a/internal/handler/loyalty_settings_db_test.go b/internal/handler/loyalty_settings_db_test.go new file mode 100644 index 0000000..c427002 --- /dev/null +++ b/internal/handler/loyalty_settings_db_test.go @@ -0,0 +1,169 @@ +package handler + +import ( + "bytes" + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "os" + "testing" + + "github.com/gin-gonic/gin" + "github.com/google/uuid" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "gorm.io/driver/postgres" + "gorm.io/gorm" + "gorm.io/gorm/logger" + + "apskel-pos-be/internal/appcontext" + applogger "apskel-pos-be/internal/logger" + "apskel-pos-be/internal/middleware" + "apskel-pos-be/internal/processor" + "apskel-pos-be/internal/repository" + "apskel-pos-be/internal/service" +) + +// Drives GET/PUT /outlets/:id/loyalty-settings over HTTP down to Postgres. Needs +// TEST_DATABASE_URL pointing at a migrated database; see +// internal/repository/wallet_repository_test.go. +func TestOutletLoyaltySettingsEndpoints_AgainstPostgres(t *testing.T) { + dsn := os.Getenv("TEST_DATABASE_URL") + if dsn == "" { + t.Skip("TEST_DATABASE_URL not set") + } + applogger.Setup("fatal", "json") + db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{Logger: logger.Default.LogMode(logger.Silent)}) + require.NoError(t, err) + + org, otherOrg, outlet, admin := uuid.New(), uuid.New(), uuid.New(), uuid.New() + exec := func(q string, args ...any) { + t.Helper() + require.NoError(t, db.Exec(q, args...).Error) + } + exec(`INSERT INTO organizations (id, name, plan_type) VALUES (?, 'A', 'basic'), (?, 'B', 'basic')`, org, otherOrg) + exec(`INSERT INTO outlets (id, organization_id, name) VALUES (?, ?, 'Kemang')`, outlet, org) + t.Cleanup(func() { + db.Exec(`DELETE FROM loyalty_setting_changes WHERE organization_id IN ?`, []uuid.UUID{org, otherOrg}) + db.Exec(`DELETE FROM outlet_settings WHERE outlet_id = ?`, outlet) + db.Exec(`DELETE FROM organization_settings WHERE organization_id = ?`, org) + db.Exec(`DELETE FROM outlets WHERE id = ?`, outlet) + db.Exec(`DELETE FROM organizations WHERE id IN ?`, []uuid.UUID{org, otherOrg}) + }) + + settings := processor.NewLoyaltySettingsProcessor(repository.NewLoyaltySettingsRepository(db), repository.NewTxManager(db)) + h := NewLoyaltySettingsHandler(service.NewLoyaltySettingsService(settings, repository.NewWalletQueryRepository(db))) + auth := middleware.NewAuthMiddleware(nil) + + gin.SetMode(gin.TestMode) + router := gin.New() + as := func(orgID uuid.UUID, role string) gin.HandlerFunc { + return func(c *gin.Context) { + ctx := context.WithValue(c.Request.Context(), appcontext.OrganizationIDKey, orgID.String()) + ctx = context.WithValue(ctx, appcontext.UserIDKey, admin.String()) + ctx = context.WithValue(ctx, appcontext.UserRoleKey, role) + c.Request = c.Request.WithContext(ctx) + } + } + for prefix, who := range map[string]struct { + org uuid.UUID + role string + }{"/manager": {org, "manager"}, "/purchasing": {org, "purchasing"}, "/other": {otherOrg, "admin"}} { + g := router.Group(prefix, as(who.org, who.role)) + g.GET("/outlets/:outlet_id/loyalty-settings", h.GetOutletSettings) + g.PUT("/outlets/:outlet_id/loyalty-settings", auth.RequireLoyaltyManager(), h.UpdateOutletSettings) + } + call := func(method, path string, body string) (int, map[string]any) { + t.Helper() + req := httptest.NewRequest(method, path, bytes.NewBufferString(body)) + req.Header.Set("Content-Type", "application/json") + rec := httptest.NewRecorder() + router.ServeHTTP(rec, req) + var out map[string]any + require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &out), rec.Body.String()) + return rec.Code, out + } + path := "/outlets/" + outlet.String() + "/loyalty-settings" + data := func(body map[string]any) map[string]any { return body["data"].(map[string]any) } + + // An outlet without settings shows every default and 1% cashback. + 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{"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"]) + + // A partial update keeps everything it does not mention. + status, body = call(http.MethodPut, "/manager"+path, `{"point": {"enabled": true, "earn_per_amount": 1000}, "coin": {"max_per_order": 3}}`) + require.Equal(t, http.StatusOK, status, body) + got = data(body) + assert.Equal(t, true, got["point"].(map[string]any)["enabled"]) + assert.EqualValues(t, 1000, got["point"].(map[string]any)["earn_per_amount"]) + assert.EqualValues(t, 1, got["point"].(map[string]any)["earn_value"], "untouched") + assert.EqualValues(t, 25000, got["coin"].(map[string]any)["earn_per_amount"], "untouched") + assert.EqualValues(t, 3, got["coin"].(map[string]any)["max_per_order"]) + assert.EqualValues(t, 0.1, got["point_cashback_percent"], "1 point per Rp 1.000 at Rp 1 a point") + assert.Len(t, got["changes"], 3) + + // The cashback follows the organization's point value. + orgSettings, err := settings.Organization(context.Background(), org) + require.NoError(t, err) + orgSettings.PointValue = 5 + _, _, err = settings.UpdateOrganization(context.Background(), org, admin, *orgSettings) + require.NoError(t, err) + status, body = call(http.MethodGet, "/manager"+path, "") + require.Equal(t, http.StatusOK, status, body) + assert.EqualValues(t, 0.5, data(body)["point_cashback_percent"]) + + // Sending back what GET returned changes nothing. + echo, err := json.Marshal(data(body)) + require.NoError(t, err) + status, body = call(http.MethodPut, "/manager"+path, string(echo)) + require.Equal(t, http.StatusOK, status, body) + assert.Empty(t, data(body)["changes"]) + + // null clears a limit. + status, body = call(http.MethodPut, "/manager"+path, `{"coin": {"max_per_order": null}}`) + require.Equal(t, http.StatusOK, status, body) + assert.Nil(t, data(body)["coin"].(map[string]any)["max_per_order"]) + + // Values out of bounds, unknown fields and bad JSON are refused and change nothing. + for name, bad := range map[string]string{ + "earn_per_amount 0": `{"point": {"earn_per_amount": 0}}`, + "negative earn_value": `{"coin": {"earn_value": -1}}`, + "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}}`, + "unknown field": `{"point": {"earn_per_amout": 50}}`, + "wrong type": `{"point": {"enabled": "yes"}}`, + "not json": `enabled=true`, + } { + status, _ = call(http.MethodPut, "/manager"+path, bad) + assert.Equal(t, http.StatusBadRequest, status, name) + } + status, body = call(http.MethodGet, "/manager"+path, "") + require.Equal(t, http.StatusOK, status, body) + assert.EqualValues(t, 1000, data(body)["point"].(map[string]any)["earn_per_amount"]) + + // Purchasing staff can read but not change; another organization sees nothing. + status, _ = call(http.MethodPut, "/purchasing"+path, `{"point": {"enabled": false}}`) + assert.Equal(t, http.StatusForbidden, status) + status, _ = call(http.MethodGet, "/other"+path, "") + assert.Equal(t, http.StatusNotFound, status) + status, _ = call(http.MethodPut, "/other"+path, `{"point": {"enabled": false}}`) + assert.Equal(t, http.StatusNotFound, status) + status, _ = call(http.MethodGet, "/manager/outlets/not-a-uuid/loyalty-settings", "") + assert.Equal(t, http.StatusBadRequest, status) + + // Every change is in the history with who made it. + history, err := settings.ListChanges(context.Background(), org, &outlet, 1, 100) + require.NoError(t, err) + assert.EqualValues(t, 4, history.Pagination.Total, "three keys, then the limit cleared") + for _, c := range history.Data { + assert.Equal(t, admin, c.ChangedBy) + } +} diff --git a/internal/handler/loyalty_settings_handler.go b/internal/handler/loyalty_settings_handler.go new file mode 100644 index 0000000..ea73cb9 --- /dev/null +++ b/internal/handler/loyalty_settings_handler.go @@ -0,0 +1,117 @@ +package handler + +import ( + "io" + "strconv" + + "github.com/gin-gonic/gin" + "github.com/google/uuid" + + "apskel-pos-be/internal/appcontext" + "apskel-pos-be/internal/constants" + "apskel-pos-be/internal/contract" + "apskel-pos-be/internal/logger" + "apskel-pos-be/internal/service" + "apskel-pos-be/internal/util" +) + +// loyaltySettingsBodyLimit caps a settings body; a real one is well under 2 KB. +const loyaltySettingsBodyLimit = 64 << 10 + +// LoyaltySettingsHandler serves the loyalty settings (docs/prd-point-coin.md F1, F2). +type LoyaltySettingsHandler struct { + loyaltySettingsService service.LoyaltySettingsService +} + +func NewLoyaltySettingsHandler(loyaltySettingsService service.LoyaltySettingsService) *LoyaltySettingsHandler { + return &LoyaltySettingsHandler{loyaltySettingsService: loyaltySettingsService} +} + +func (h *LoyaltySettingsHandler) GetOutletSettings(c *gin.Context) { + ctx := c.Request.Context() + outletID, ok := parseUUIDParam(c, "outlet_id", "LoyaltySettingsHandler::GetOutletSettings") + if !ok { + return + } + response := h.loyaltySettingsService.GetOutletSettings(ctx, appcontext.FromGinContext(ctx), outletID) + if response.HasErrors() { + logger.FromContext(ctx).WithError(response.GetErrors()[0]).Error("LoyaltySettingsHandler::GetOutletSettings -> service call failed") + } + util.HandleResponse(c.Writer, c.Request, response, "LoyaltySettingsHandler::GetOutletSettings") +} + +func (h *LoyaltySettingsHandler) UpdateOutletSettings(c *gin.Context) { + ctx := c.Request.Context() + outletID, ok := parseUUIDParam(c, "outlet_id", "LoyaltySettingsHandler::UpdateOutletSettings") + if !ok { + return + } + body, err := io.ReadAll(io.LimitReader(c.Request.Body, loyaltySettingsBodyLimit)) + if err != nil { + util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{ + contract.NewResponseError(constants.MalformedFieldErrorCode, constants.RequestEntity, "unable to read request body"), + }), "LoyaltySettingsHandler::UpdateOutletSettings") + return + } + response := h.loyaltySettingsService.UpdateOutletSettings(ctx, appcontext.FromGinContext(ctx), outletID, body) + if response.HasErrors() { + logger.FromContext(ctx).WithError(response.GetErrors()[0]).Error("LoyaltySettingsHandler::UpdateOutletSettings -> service call failed") + } + util.HandleResponse(c.Writer, c.Request, response, "LoyaltySettingsHandler::UpdateOutletSettings") +} + +// parseUUIDParam reads a UUID path parameter, answering 400 itself when it is not one. +func parseUUIDParam(c *gin.Context, name, method string) (uuid.UUID, bool) { + id, err := uuid.Parse(c.Param(name)) + if err != nil { + util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{ + contract.NewResponseError(constants.MalformedFieldErrorCode, constants.RequestEntity, "Invalid "+name), + }), method) + return uuid.Nil, false + } + return id, true +} + +func (h *LoyaltySettingsHandler) GetOrganizationSettings(c *gin.Context) { + ctx := c.Request.Context() + util.HandleResponse(c.Writer, c.Request, h.loyaltySettingsService.GetOrganizationSettings(ctx, appcontext.FromGinContext(ctx)), "LoyaltySettingsHandler::GetOrganizationSettings") +} + +// UpdateOrganizationSettings is PUT /marketing/loyalty-settings. With ?dry_run=true it +// saves nothing and returns what would change and what the balances in circulation +// would be worth, for the warning the dashboard shows before saving (F2). +func (h *LoyaltySettingsHandler) UpdateOrganizationSettings(c *gin.Context) { + ctx := c.Request.Context() + body, err := io.ReadAll(io.LimitReader(c.Request.Body, loyaltySettingsBodyLimit)) + if err != nil { + util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{ + contract.NewResponseError(constants.MalformedFieldErrorCode, constants.RequestEntity, "unable to read request body"), + }), "LoyaltySettingsHandler::UpdateOrganizationSettings") + return + } + response := h.loyaltySettingsService.UpdateOrganizationSettings(ctx, appcontext.FromGinContext(ctx), body, c.Query("dry_run") == "true") + if response.HasErrors() { + logger.FromContext(ctx).WithError(response.GetErrors()[0]).Error("LoyaltySettingsHandler::UpdateOrganizationSettings -> service call failed") + } + util.HandleResponse(c.Writer, c.Request, response, "LoyaltySettingsHandler::UpdateOrganizationSettings") +} + +// ListHistory is GET /marketing/loyalty-settings/history, optionally for one outlet +// (?outlet_id=). +func (h *LoyaltySettingsHandler) ListHistory(c *gin.Context) { + ctx := c.Request.Context() + var outletID *uuid.UUID + if raw := c.Query("outlet_id"); raw != "" { + id, err := uuid.Parse(raw) + if err != nil { + util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{ + contract.NewResponseError(constants.MalformedFieldErrorCode, constants.RequestEntity, "Invalid outlet_id"), + }), "LoyaltySettingsHandler::ListHistory") + return + } + outletID = &id + } + page, _ := strconv.Atoi(c.DefaultQuery("page", "1")) + limit, _ := strconv.Atoi(c.DefaultQuery("limit", "20")) + util.HandleResponse(c.Writer, c.Request, h.loyaltySettingsService.ListHistory(ctx, appcontext.FromGinContext(ctx), outletID, page, limit), "LoyaltySettingsHandler::ListHistory") +} diff --git a/internal/handler/loyalty_settings_org_db_test.go b/internal/handler/loyalty_settings_org_db_test.go new file mode 100644 index 0000000..6b455d5 --- /dev/null +++ b/internal/handler/loyalty_settings_org_db_test.go @@ -0,0 +1,180 @@ +package handler + +import ( + "bytes" + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "os" + "testing" + + "github.com/gin-gonic/gin" + "github.com/google/uuid" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "gorm.io/driver/postgres" + "gorm.io/gorm" + "gorm.io/gorm/logger" + + "apskel-pos-be/internal/appcontext" + applogger "apskel-pos-be/internal/logger" + "apskel-pos-be/internal/middleware" + "apskel-pos-be/internal/processor" + "apskel-pos-be/internal/repository" + "apskel-pos-be/internal/service" +) + +// Drives GET/PUT /marketing/loyalty-settings and its history over HTTP down to +// Postgres. Needs TEST_DATABASE_URL pointing at a migrated database; see +// internal/repository/wallet_repository_test.go. +func TestOrganizationLoyaltySettingsEndpoints_AgainstPostgres(t *testing.T) { + dsn := os.Getenv("TEST_DATABASE_URL") + if dsn == "" { + t.Skip("TEST_DATABASE_URL not set") + } + applogger.Setup("fatal", "json") + db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{Logger: logger.Default.LogMode(logger.Silent)}) + require.NoError(t, err) + + org, admin, customer := uuid.New(), uuid.New(), uuid.New() + exec := func(q string, args ...any) { + t.Helper() + require.NoError(t, db.Exec(q, args...).Error) + } + exec(`INSERT INTO organizations (id, name, plan_type) VALUES (?, 'A', 'basic')`, org) + exec(`INSERT INTO customers (id, organization_id, name) VALUES (?, ?, 'Budi')`, customer, org) + t.Cleanup(func() { + db.Exec(`DELETE FROM wallet_lots WHERE customer_id = ?`, customer) + db.Exec(`DELETE FROM wallet_transactions WHERE customer_id = ?`, customer) + db.Exec(`DELETE FROM customer_wallets WHERE customer_id = ?`, customer) + db.Exec(`DELETE FROM loyalty_setting_changes WHERE organization_id = ?`, org) + db.Exec(`DELETE FROM organization_settings WHERE organization_id = ?`, org) + db.Exec(`DELETE FROM customers WHERE id = ?`, customer) + db.Exec(`DELETE FROM organizations WHERE id = ?`, org) + }) + + // Balances in circulation: 50.000 EnakPoint and 105 EnakCoin. + txm := repository.NewTxManager(db) + wallet := processor.NewWalletProcessor(repository.NewWalletRepository(db)) + for _, c := range []struct { + currency, ref string + amount int64 + }{{"POINT", "LEGACY_POINTS", 50000}, {"COIN", "LEGACY_TOKENS", 105}} { + require.NoError(t, txm.WithTransaction(context.Background(), func(ctx context.Context) error { + _, err := wallet.Credit(ctx, processor.WalletCreditInput{WalletEntry: processor.WalletEntry{ + CustomerID: customer, Currency: c.currency, Type: "MIGRATION", Amount: c.amount, + ReferenceType: c.ref, ReferenceID: uuid.New(), Description: "Saldo awal", + Metadata: map[string]interface{}{"frozen": true}}}) + return err + })) + } + + settings := processor.NewLoyaltySettingsProcessor(repository.NewLoyaltySettingsRepository(db), txm) + h := NewLoyaltySettingsHandler(service.NewLoyaltySettingsService(settings, repository.NewWalletQueryRepository(db))) + auth := middleware.NewAuthMiddleware(nil) + gin.SetMode(gin.TestMode) + router := gin.New() + for prefix, role := range map[string]string{"/manager": "manager", "/purchasing": "purchasing"} { + role := role + g := router.Group(prefix, func(c *gin.Context) { + ctx := context.WithValue(c.Request.Context(), appcontext.OrganizationIDKey, org.String()) + ctx = context.WithValue(ctx, appcontext.UserIDKey, admin.String()) + ctx = context.WithValue(ctx, appcontext.UserRoleKey, role) + c.Request = c.Request.WithContext(ctx) + }) + g.GET("/loyalty-settings", h.GetOrganizationSettings) + g.PUT("/loyalty-settings", auth.RequireLoyaltyManager(), h.UpdateOrganizationSettings) + g.GET("/loyalty-settings/history", h.ListHistory) + } + call := func(method, path, body string) (int, map[string]any) { + t.Helper() + req := httptest.NewRequest(method, path, bytes.NewBufferString(body)) + rec := httptest.NewRecorder() + router.ServeHTTP(rec, req) + var out map[string]any + require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &out), rec.Body.String()) + return rec.Code, out + } + data := func(body map[string]any) map[string]any { return body["data"].(map[string]any) } + + status, body := call(http.MethodGet, "/manager/loyalty-settings", "") + require.Equal(t, http.StatusOK, status, body) + got := data(body) + assert.EqualValues(t, 1, got["point_value"]) + assert.Equal(t, map[string]any{"coin_amount": float64(1), "point_amount": float64(1)}, got["exchange"]) + assert.Equal(t, true, got["transfer"].(map[string]any)["enabled"]) + assert.Equal(t, "MONTH", got["point_expiry"].(map[string]any)["unit"]) + impact := got["impact"].(map[string]any) + assert.EqualValues(t, 50000, impact["outstanding_points"]) + assert.EqualValues(t, impact["point_rupiah_before"], impact["point_rupiah_after"]) + + // A dry run shows what the balances in circulation would be worth, and saves nothing. + change := `{"point_value": 100, "exchange": {"coin_amount": 10, "point_amount": 1}}` + status, body = call(http.MethodPut, "/manager/loyalty-settings?dry_run=true", change) + require.Equal(t, http.StatusOK, status, body) + got = data(body) + assert.Equal(t, true, got["dry_run"]) + impact = got["impact"].(map[string]any) + assert.EqualValues(t, 50000, impact["point_rupiah_before"]) + assert.EqualValues(t, 5000000, impact["point_rupiah_after"]) + assert.EqualValues(t, 105, impact["coins_as_points_before"]) + assert.EqualValues(t, 10, impact["coins_as_points_after"]) + assert.Len(t, got["changes"], 2) + status, body = call(http.MethodGet, "/manager/loyalty-settings", "") + require.Equal(t, http.StatusOK, status, body) + assert.EqualValues(t, 1, data(body)["point_value"], "a dry run saves nothing") + status, body = call(http.MethodGet, "/manager/loyalty-settings/history", "") + require.Equal(t, http.StatusOK, status, body) + assert.EqualValues(t, 0, data(body)["pagination"].(map[string]any)["total_count"]) + + // Saving records every change with who made it. + status, body = call(http.MethodPut, "/manager/loyalty-settings", change) + require.Equal(t, http.StatusOK, status, body) + assert.Equal(t, false, data(body)["dry_run"]) + assert.EqualValues(t, 100, data(body)["point_value"]) + status, body = call(http.MethodGet, "/manager/loyalty-settings/history", "") + require.Equal(t, http.StatusOK, status, body) + history := data(body)["data"].([]any) + require.Len(t, history, 2) + var keys []string + for _, raw := range history { + row := raw.(map[string]any) + keys = append(keys, row["key"].(string)) + assert.Equal(t, admin.String(), row["changed_by"]) + assert.Nil(t, row["old_value"], "was on its default") + assert.Nil(t, row["outlet_id"]) + } + assert.ElementsMatch(t, []string{"loyalty.point.value", "loyalty.exchange.coin_amount"}, keys) + + // Nothing already written changes: balances and ledger rows keep their numbers. + var rows []struct { + Amount int64 + Metadata string + } + require.NoError(t, db.Raw(`SELECT amount, metadata::text AS metadata FROM wallet_transactions WHERE customer_id = ? ORDER BY currency`, customer).Scan(&rows).Error) + require.Len(t, rows, 2) + assert.Equal(t, int64(105), rows[0].Amount) + assert.Equal(t, int64(50000), rows[1].Amount) + for _, r := range rows { + assert.Contains(t, r.Metadata, `"frozen": true`) + } + + // Out of bounds, unknown fields and the wrong role are refused. + for name, bad := range map[string]string{ + "point value 0": `{"point_value": 0}`, + "exchange 0": `{"exchange": {"coin_amount": 0}}`, + "expiry unit YEAR": `{"coin_expiry": {"unit": "YEAR"}}`, + "unknown field": `{"point_valeu": 5}`, + } { + status, _ = call(http.MethodPut, "/manager/loyalty-settings", bad) + assert.Equal(t, http.StatusBadRequest, status, name) + status, _ = call(http.MethodPut, "/manager/loyalty-settings?dry_run=true", bad) + assert.Equal(t, http.StatusBadRequest, status, name+" (dry run)") + } + status, _ = call(http.MethodPut, "/purchasing/loyalty-settings", `{"point_value": 5}`) + assert.Equal(t, http.StatusForbidden, status) + status, body = call(http.MethodGet, "/manager/loyalty-settings", "") + require.Equal(t, http.StatusOK, status, body) + assert.EqualValues(t, 100, data(body)["point_value"]) +} diff --git a/internal/handler/order_handler.go b/internal/handler/order_handler.go index fa3971b..df26367 100644 --- a/internal/handler/order_handler.go +++ b/internal/handler/order_handler.go @@ -1,8 +1,11 @@ package handler import ( + "errors" + "apskel-pos-be/internal/appcontext" "apskel-pos-be/internal/contract" + "apskel-pos-be/internal/processor" "apskel-pos-be/internal/service" "apskel-pos-be/internal/transformer" "apskel-pos-be/internal/util" @@ -202,6 +205,11 @@ func (h *OrderHandler) RefundOrder(c *gin.Context) { } if err := h.orderService.RefundOrder(ctx, id, modelReq, userID); err != nil { + // Refusing to hand EnakPoint back as cash is a bad request, not a server fault. + if errors.Is(err, processor.ErrPointPaymentRejected) { + util.HandleResponse(c.Writer, c.Request, service.PointPaymentErrorResponse(err), "OrderHandler::RefundOrder") + return + } util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{contract.NewResponseError("internal_error", "OrderHandler::RefundOrder", err.Error())}), "OrderHandler::RefundOrder") return } @@ -225,6 +233,11 @@ func (h *OrderHandler) CreatePayment(c *gin.Context) { response, err := h.orderService.CreatePayment(c.Request.Context(), modelReq) if err != nil { + // A refused EnakPoint payment is the cashier's or customer's to fix, not a server fault. + if errors.Is(err, processor.ErrPointPaymentRejected) { + util.HandleResponse(c.Writer, c.Request, service.PointPaymentErrorResponse(err), "OrderHandler::CreatePayment") + return + } util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{contract.NewResponseError("internal_error", "OrderHandler::CreatePayment", err.Error())}), "OrderHandler::CreatePayment") return } diff --git a/internal/handler/payment_method_handler.go b/internal/handler/payment_method_handler.go index 49a914a..290d0df 100644 --- a/internal/handler/payment_method_handler.go +++ b/internal/handler/payment_method_handler.go @@ -113,6 +113,16 @@ func (h *PaymentMethodHandler) ListPaymentMethods(c *gin.Context) { req.OrganizationID = &contextInfo.OrganizationID + // At the cashier, EnakPoint is listed only where the outlet accepts it (F9). + if outletStr := c.Query("outlet_id"); outletStr != "" { + if outletID, err := uuid.Parse(outletStr); err == nil { + req.OutletID = &outletID + } + } else if contextInfo.OutletID != uuid.Nil { + outletID := contextInfo.OutletID + req.OutletID = &outletID + } + if isActiveStr := c.Query("is_active"); isActiveStr != "" { if isActive, err := strconv.ParseBool(isActiveStr); err == nil { req.IsActive = &isActive diff --git a/internal/handler/point_payment_handler.go b/internal/handler/point_payment_handler.go new file mode 100644 index 0000000..3c1f3e2 --- /dev/null +++ b/internal/handler/point_payment_handler.go @@ -0,0 +1,28 @@ +package handler + +import ( + "github.com/gin-gonic/gin" + + "apskel-pos-be/internal/appcontext" + "apskel-pos-be/internal/service" + "apskel-pos-be/internal/util" +) + +// PointPaymentHandler serves GET /orders/:id/point-payment/preview +// (docs/prd-point-coin.md F9). +type PointPaymentHandler struct { + pointPaymentService service.PointPaymentService +} + +func NewPointPaymentHandler(pointPaymentService service.PointPaymentService) *PointPaymentHandler { + return &PointPaymentHandler{pointPaymentService: pointPaymentService} +} + +func (h *PointPaymentHandler) Preview(c *gin.Context) { + orderID, ok := parseUUIDParam(c, "id", "PointPaymentHandler::Preview") + if !ok { + return + } + ctx := c.Request.Context() + util.HandleResponse(c.Writer, c.Request, h.pointPaymentService.Preview(ctx, appcontext.FromGinContext(ctx), orderID), "PointPaymentHandler::Preview") +} diff --git a/internal/handler/spin_game_handler.go b/internal/handler/spin_game_handler.go index 3b218cb..b7c033d 100644 --- a/internal/handler/spin_game_handler.go +++ b/internal/handler/spin_game_handler.go @@ -1,10 +1,13 @@ package handler import ( + "errors" + "apskel-pos-be/internal/constants" "apskel-pos-be/internal/contract" "apskel-pos-be/internal/mappers" "apskel-pos-be/internal/models" + "apskel-pos-be/internal/processor" "apskel-pos-be/internal/service" "apskel-pos-be/internal/util" @@ -49,8 +52,14 @@ func (h *SpinGameHandler) PlaySpinGame(c *gin.Context) { // Play the spin game response, err := h.spinGameService.PlaySpinGame(c.Request.Context(), customerID.(string), modelReq) if err != nil { + // Not enough EnakCoin, an inactive game or a prize that just ran out is the + // customer's to fix, not a server failure. + code := constants.InternalServerErrorCode + if errors.Is(err, processor.ErrGamePlayRefused) { + code = constants.ValidationErrorCode + } util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{ - contract.NewResponseError(constants.InternalServerErrorCode, constants.SpinGameHandlerEntity, err.Error()), + contract.NewResponseError(code, constants.SpinGameHandlerEntity, err.Error()), }), "SpinGameHandler::PlaySpinGame") return } diff --git a/internal/handler/wallet_admin_db_test.go b/internal/handler/wallet_admin_db_test.go new file mode 100644 index 0000000..7c4de20 --- /dev/null +++ b/internal/handler/wallet_admin_db_test.go @@ -0,0 +1,203 @@ +package handler + +import ( + "bytes" + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "os" + "testing" + + "github.com/gin-gonic/gin" + "github.com/google/uuid" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "gorm.io/driver/postgres" + "gorm.io/gorm" + "gorm.io/gorm/logger" + + "apskel-pos-be/internal/appcontext" + "apskel-pos-be/internal/constants" + applogger "apskel-pos-be/internal/logger" + "apskel-pos-be/internal/processor" + "apskel-pos-be/internal/repository" + "apskel-pos-be/internal/service" + "apskel-pos-be/internal/validator" +) + +// Drives the dashboard wallet endpoints over HTTP down to Postgres. Needs +// TEST_DATABASE_URL pointing at a migrated database; see +// internal/repository/wallet_repository_test.go. +func TestWalletAdminEndpoints_AgainstPostgres(t *testing.T) { + dsn := os.Getenv("TEST_DATABASE_URL") + if dsn == "" { + t.Skip("TEST_DATABASE_URL not set") + } + applogger.Setup("fatal", "json") + db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{Logger: logger.Default.LogMode(logger.Silent)}) + require.NoError(t, err) + + orgA, orgB := uuid.New(), uuid.New() + adminA, adminB := uuid.New(), uuid.New() + customer := uuid.New() + exec := func(q string, args ...any) { + t.Helper() + require.NoError(t, db.Exec(q, args...).Error) + } + exec(`INSERT INTO organizations (id, name, plan_type) VALUES (?, 'A', 'basic'), (?, 'B', 'basic')`, orgA, orgB) + exec(`INSERT INTO users (id, organization_id, name, email, password_hash, role) VALUES + (?, ?, 'Admin Satu', ?, 'x', 'admin'), (?, ?, 'Admin Lain', ?, 'x', 'admin')`, + adminA, orgA, adminA.String()+"@test", adminB, orgB, adminB.String()+"@test") + exec(`INSERT INTO customers (id, organization_id, name, phone_number) VALUES (?, ?, 'Budi Santoso', '081234567890')`, customer, orgA) + t.Cleanup(func() { + db.Exec(`DELETE FROM wallet_lot_allocations WHERE lot_id IN (SELECT id FROM wallet_lots WHERE customer_id = ?)`, customer) + db.Exec(`DELETE FROM wallet_lots WHERE customer_id = ?`, customer) + db.Exec(`DELETE FROM wallet_transactions WHERE customer_id = ?`, customer) + db.Exec(`DELETE FROM customer_wallets WHERE customer_id = ?`, customer) + db.Exec(`DELETE FROM customers WHERE id = ?`, customer) + db.Exec(`DELETE FROM users WHERE id IN ?`, []uuid.UUID{adminA, adminB}) + db.Exec(`DELETE FROM organizations WHERE id IN ?`, []uuid.UUID{orgA, orgB}) + }) + + walletRepo := repository.NewWalletRepository(db) + queryRepo := repository.NewWalletQueryRepository(db) + txm := repository.NewTxManager(db) + wallet := processor.NewWalletProcessor(walletRepo) + require.NoError(t, txm.WithTransaction(context.Background(), func(ctx context.Context) error { + outlet := uuid.New() + _, err := wallet.Credit(ctx, processor.WalletCreditInput{WalletEntry: processor.WalletEntry{ + CustomerID: customer, Currency: constants.WalletCurrencyPoint, Type: constants.WalletTxTypeEarn, + Amount: 100, ReferenceType: constants.WalletRefTypeOrder, ReferenceID: uuid.New(), OutletID: &outlet, + Description: "Belanja #ORD-1"}}) + return err + })) + + h := NewWalletAdminHandler( + service.NewWalletAdminService(processor.NewWalletAdminProcessor(repository.NewWalletAdminRepository(db), queryRepo, wallet, processor.NewLoyaltySettingsProcessor(repository.NewLoyaltySettingsRepository(db), txm), txm), processor.NewWalletTraceProcessor(repository.NewWalletTraceRepository(db))), + validator.NewWalletValidator(), + ) + gin.SetMode(gin.TestMode) + router := gin.New() + as := func(org, user uuid.UUID) gin.HandlerFunc { + return func(c *gin.Context) { + ctx := context.WithValue(c.Request.Context(), appcontext.OrganizationIDKey, org.String()) + ctx = context.WithValue(ctx, appcontext.UserIDKey, user.String()) + c.Request = c.Request.WithContext(ctx) + } + } + for prefix, who := range map[string][2]uuid.UUID{"/a": {orgA, adminA}, "/b": {orgB, adminB}} { + g := router.Group(prefix, as(who[0], who[1])) + g.GET("/customers/:id/wallet", h.GetCustomerWallet) + g.POST("/customers/:id/wallet/adjust", h.AdjustCustomerWallet) + } + call := func(method, path string, body any) (int, map[string]any) { + t.Helper() + var buf bytes.Buffer + if body != nil { + require.NoError(t, json.NewEncoder(&buf).Encode(body)) + } + req := httptest.NewRequest(method, path, &buf) + req.Header.Set("Content-Type", "application/json") + rec := httptest.NewRecorder() + router.ServeHTTP(rec, req) + var out map[string]any + require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &out), rec.Body.String()) + return rec.Code, out + } + adjust := func(prefix string, body map[string]any) (int, map[string]any) { + return call(http.MethodPost, prefix+"/customers/"+customer.String()+"/wallet/adjust", body) + } + spendable := func() float64 { + t.Helper() + status, body := call(http.MethodGet, "/a/customers/"+customer.String()+"/wallet", nil) + require.Equal(t, http.StatusOK, status, body) + return body["data"].(map[string]any)["spendable_point_balance"].(float64) + } + + // Add 50. + status, body := adjust("/a", map[string]any{"currency": "point", "amount": 50, "reason": "komplain #45"}) + require.Equal(t, http.StatusOK, status, body) + tx := body["data"].(map[string]any)["transaction"].(map[string]any) + assert.Equal(t, "ADJUSTMENT", tx["type"]) + assert.EqualValues(t, 50, tx["amount"]) + assert.Equal(t, "komplain #45", tx["reason"]) + assert.Equal(t, "Koreksi oleh admin: komplain #45", tx["description"]) + assert.Equal(t, map[string]any{"id": adminA.String(), "name": "Admin Satu"}, tx["created_by"]) + assert.Equal(t, map[string]any{"type": "USER", "id": adminA.String()}, tx["source"]) + assert.EqualValues(t, 150, body["data"].(map[string]any)["spendable_point_balance"]) + + // Taking more than the customer can spend is refused and changes nothing. + status, body = adjust("/a", map[string]any{"currency": "POINT", "amount": -151, "reason": "salah input"}) + assert.Equal(t, http.StatusBadRequest, status, body) + assert.Equal(t, float64(150), spendable()) + + // Taking away, retried with the same key, happens once. + for i, wantReplayed := range []bool{false, true} { + status, body = adjust("/a", map[string]any{"currency": "POINT", "amount": -30, "reason": "salah input", "idempotency_key": "req-1"}) + require.Equal(t, http.StatusOK, status, body) + assert.Equal(t, wantReplayed, body["data"].(map[string]any)["replayed"], "call %d", i+1) + } + assert.Equal(t, float64(120), spendable()) + + // Bad requests. + for name, req := range map[string]map[string]any{ + "cash-out": {"currency": "POINT", "amount": -10, "reason": "pencairan saldo"}, + "zero amount": {"currency": "POINT", "amount": 0, "reason": "x"}, + "no reason": {"currency": "POINT", "amount": 10}, + "bad currency": {"currency": "GOLD", "amount": 10, "reason": "x"}, + } { + status, _ = adjust("/a", req) + assert.Equal(t, http.StatusBadRequest, status, name) + } + status, _ = call(http.MethodPost, "/a/customers/not-a-uuid/wallet/adjust", map[string]any{"currency": "POINT", "amount": 1, "reason": "x"}) + assert.Equal(t, http.StatusBadRequest, status) + assert.Equal(t, float64(120), spendable()) + + // Another organization's admin cannot see or touch this customer. + status, _ = call(http.MethodGet, "/b/customers/"+customer.String()+"/wallet", nil) + assert.Equal(t, http.StatusNotFound, status) + status, _ = adjust("/b", map[string]any{"currency": "POINT", "amount": 1000, "reason": "x"}) + assert.Equal(t, http.StatusNotFound, status) + assert.Equal(t, float64(120), spendable()) + + // The dashboard view. + status, body = call(http.MethodGet, "/a/customers/"+customer.String()+"/wallet?type=ADJUSTMENT", nil) + require.Equal(t, http.StatusOK, status, body) + w := body["data"].(map[string]any) + assert.Equal(t, map[string]any{"id": customer.String(), "name": "Budi Santoso", "phone": "081234567890"}, w["customer"]) + assert.EqualValues(t, 120, w["point_balance"]) + assert.EqualValues(t, 120, w["spendable_point_balance"]) + lots := w["lots"].([]any) + var lotTotal float64 + for _, l := range lots { + lotTotal += l.(map[string]any)["remaining_amount"].(float64) + } + assert.Equal(t, float64(120), lotTotal) + + rows := w["transactions"].(map[string]any)["data"].([]any) + require.Len(t, rows, 2, "the two adjustments, newest first") + newest := rows[0].(map[string]any) + assert.EqualValues(t, -30, newest["amount"]) + assert.Equal(t, "salah input", newest["reason"]) + assert.Equal(t, map[string]any{"id": adminA.String(), "name": "Admin Satu"}, newest["created_by"]) + assert.Equal(t, map[string]any{"type": "USER", "id": adminA.String()}, newest["destination"]) + + // The customer's own history shows the adjustment too, with the reason in the + // description and without the admin's identity fields. + customerView := NewCustomerPointsHandler(service.NewCustomerPointsService(processor.NewCustomerPointsProcessor( + processor.NewWalletQueryProcessor(queryRepo, processor.NewLoyaltySettingsProcessor(repository.NewLoyaltySettingsRepository(db), repository.NewTxManager(db))), nil))) + crouter := gin.New() + crouter.GET("/wallet/transactions", func(c *gin.Context) { c.Set("customer_id", customer.String()) }, customerView.GetCustomerWalletTransactions) + rec := httptest.NewRecorder() + crouter.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/wallet/transactions?type=ADJUSTMENT", nil)) + require.Equal(t, http.StatusOK, rec.Code, rec.Body.String()) + var cbody map[string]any + require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &cbody)) + crows := cbody["data"].(map[string]any)["data"].([]any) + require.Len(t, crows, 2) + first := crows[0].(map[string]any) + assert.Equal(t, "Koreksi oleh admin: salah input", first["description"]) + assert.NotContains(t, first, "created_by") + assert.NotContains(t, first, "reason") +} diff --git a/internal/handler/wallet_admin_handler.go b/internal/handler/wallet_admin_handler.go new file mode 100644 index 0000000..648cbb5 --- /dev/null +++ b/internal/handler/wallet_admin_handler.go @@ -0,0 +1,99 @@ +package handler + +import ( + "github.com/gin-gonic/gin" + "github.com/google/uuid" + + "apskel-pos-be/internal/appcontext" + "apskel-pos-be/internal/constants" + "apskel-pos-be/internal/contract" + "apskel-pos-be/internal/logger" + "apskel-pos-be/internal/models" + "apskel-pos-be/internal/service" + "apskel-pos-be/internal/util" + "apskel-pos-be/internal/validator" +) + +// WalletAdminHandler serves /marketing/customers/:id/wallet (docs/prd-point-coin.md F7). +type WalletAdminHandler struct { + walletAdminService service.WalletAdminService + walletValidator validator.WalletValidator +} + +func NewWalletAdminHandler(walletAdminService service.WalletAdminService, walletValidator validator.WalletValidator) *WalletAdminHandler { + return &WalletAdminHandler{walletAdminService: walletAdminService, walletValidator: walletValidator} +} + +func (h *WalletAdminHandler) GetCustomerWallet(c *gin.Context) { + ctx := c.Request.Context() + contextInfo := appcontext.FromGinContext(ctx) + + customerID, err := uuid.Parse(c.Param("id")) + if err != nil { + util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{ + contract.NewResponseError(constants.MalformedFieldErrorCode, constants.RequestEntity, "Invalid customer ID"), + }), "WalletAdminHandler::GetCustomerWallet") + return + } + + var query models.ListCustomerWalletTransactionsQuery + if err := c.ShouldBindQuery(&query); err != nil { + util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{ + contract.NewResponseError(constants.MalformedFieldErrorCode, constants.RequestEntity, err.Error()), + }), "WalletAdminHandler::GetCustomerWallet") + return + } + + response := h.walletAdminService.GetCustomerWallet(ctx, contextInfo, customerID, query) + if response.HasErrors() { + logger.FromContext(ctx).WithError(response.GetErrors()[0]).Error("WalletAdminHandler::GetCustomerWallet -> service call failed") + } + util.HandleResponse(c.Writer, c.Request, response, "WalletAdminHandler::GetCustomerWallet") +} + +func (h *WalletAdminHandler) AdjustCustomerWallet(c *gin.Context) { + ctx := c.Request.Context() + contextInfo := appcontext.FromGinContext(ctx) + + customerID, err := uuid.Parse(c.Param("id")) + if err != nil { + util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{ + contract.NewResponseError(constants.MalformedFieldErrorCode, constants.RequestEntity, "Invalid customer ID"), + }), "WalletAdminHandler::AdjustCustomerWallet") + return + } + + var req contract.AdjustCustomerWalletRequest + if err := c.ShouldBindJSON(&req); err != nil { + util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{ + contract.NewResponseError(constants.MissingFieldErrorCode, constants.RequestEntity, err.Error()), + }), "WalletAdminHandler::AdjustCustomerWallet") + return + } + if validationError, code := h.walletValidator.ValidateAdjustRequest(&req); validationError != nil { + util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{ + contract.NewResponseError(code, constants.RequestEntity, validationError.Error()), + }), "WalletAdminHandler::AdjustCustomerWallet") + return + } + + response := h.walletAdminService.AdjustCustomerWallet(ctx, contextInfo, customerID, &req) + if response.HasErrors() { + logger.FromContext(ctx).WithError(response.GetErrors()[0]).Error("WalletAdminHandler::AdjustCustomerWallet -> service call failed") + } + util.HandleResponse(c.Writer, c.Request, response, "WalletAdminHandler::AdjustCustomerWallet") +} + +// TraceTransaction is GET /marketing/wallet-transactions/:id/trace. +func (h *WalletAdminHandler) TraceTransaction(c *gin.Context) { + ctx := c.Request.Context() + transactionID, ok := parseUUIDParam(c, "id", "WalletAdminHandler::TraceTransaction") + if !ok { + return + } + response := h.walletAdminService.TraceTransaction(ctx, appcontext.FromGinContext(ctx), transactionID) + if response.HasErrors() { + logger.FromContext(ctx).WithError(response.GetErrors()[0]).Error("WalletAdminHandler::TraceTransaction -> service call failed") + } + util.HandleResponse(c.Writer, c.Request, response, "WalletAdminHandler::TraceTransaction") +} diff --git a/internal/mappers/campaign_mapper.go b/internal/mappers/campaign_mapper.go index f662108..ffd2940 100644 --- a/internal/mappers/campaign_mapper.go +++ b/internal/mappers/campaign_mapper.go @@ -71,7 +71,7 @@ func ToCampaignEntity(request *contract.CreateCampaignRequest) *entities.Campaig return &entities.Campaign{ Name: request.Name, Description: request.Description, - Type: entities.CampaignType(request.Type), + Type: entities.NormalizeCampaignType(request.Type), StartDate: request.StartDate, EndDate: request.EndDate, IsActive: request.IsActive, @@ -91,7 +91,7 @@ func ToCampaignEntityFromUpdate(request *contract.UpdateCampaignRequest) *entiti ID: request.ID, Name: request.Name, Description: request.Description, - Type: entities.CampaignType(request.Type), + Type: entities.NormalizeCampaignType(request.Type), StartDate: request.StartDate, EndDate: request.EndDate, IsActive: request.IsActive, @@ -118,7 +118,7 @@ func ToCampaignRuleEntity(request *contract.CampaignRuleStruct, campaignID uuid. CampaignID: campaignID, RuleType: entities.RuleType(request.RuleType), ConditionValue: request.ConditionValue, - RewardType: entities.CampaignRewardType(request.RewardType), + RewardType: entities.NormalizeCampaignRewardType(request.RewardType), RewardValue: request.RewardValue, RewardSubtype: rewardSubtype, RewardRefID: request.RewardRefID, @@ -142,7 +142,7 @@ func ToCampaignRuleEntityFromUpdate(request *contract.CampaignRuleStruct, campai CampaignID: campaignID, RuleType: entities.RuleType(request.RuleType), ConditionValue: request.ConditionValue, - RewardType: entities.CampaignRewardType(request.RewardType), + RewardType: entities.NormalizeCampaignRewardType(request.RewardType), RewardValue: request.RewardValue, RewardSubtype: rewardSubtype, RewardRefID: request.RewardRefID, diff --git a/internal/mappers/customer_points_mapper.go b/internal/mappers/customer_points_mapper.go deleted file mode 100644 index 0cf67ba..0000000 --- a/internal/mappers/customer_points_mapper.go +++ /dev/null @@ -1,46 +0,0 @@ -package mappers - -import ( - "apskel-pos-be/internal/entities" - "apskel-pos-be/internal/models" -) - -// ToCustomerPointsResponse converts a customer points entity to a customer points response -func ToCustomerPointsResponse(customerPoints *entities.CustomerPoints) *models.CustomerPointsResponse { - if customerPoints == nil { - return nil - } - - return &models.CustomerPointsResponse{ - ID: customerPoints.ID, - CustomerID: customerPoints.CustomerID, - Balance: customerPoints.Balance, - Customer: ToCustomerResponse(&customerPoints.Customer), - CreatedAt: customerPoints.CreatedAt, - UpdatedAt: customerPoints.UpdatedAt, - } -} - -// ToCustomerPointsResponses converts a slice of customer points entities to customer points responses -func ToCustomerPointsResponses(customerPoints []entities.CustomerPoints) []models.CustomerPointsResponse { - responses := make([]models.CustomerPointsResponse, len(customerPoints)) - for i, cp := range customerPoints { - responses[i] = *ToCustomerPointsResponse(&cp) - } - return responses -} - -// ToCustomerPointsEntity converts a create customer points request to a customer points entity -func ToCustomerPointsEntity(req *models.CreateCustomerPointsRequest) *entities.CustomerPoints { - return &entities.CustomerPoints{ - CustomerID: req.CustomerID, - Balance: req.Balance, - } -} - -// UpdateCustomerPointsEntity updates a customer points entity with update request data -func UpdateCustomerPointsEntity(customerPoints *entities.CustomerPoints, req *models.UpdateCustomerPointsRequest) { - if req.Balance >= 0 { - customerPoints.Balance = req.Balance - } -} diff --git a/internal/mappers/customer_tokens_mapper.go b/internal/mappers/customer_tokens_mapper.go deleted file mode 100644 index e88cfed..0000000 --- a/internal/mappers/customer_tokens_mapper.go +++ /dev/null @@ -1,48 +0,0 @@ -package mappers - -import ( - "apskel-pos-be/internal/entities" - "apskel-pos-be/internal/models" -) - -// ToCustomerTokensResponse converts a customer tokens entity to a customer tokens response -func ToCustomerTokensResponse(customerTokens *entities.CustomerTokens) *models.CustomerTokensResponse { - if customerTokens == nil { - return nil - } - - return &models.CustomerTokensResponse{ - ID: customerTokens.ID, - CustomerID: customerTokens.CustomerID, - TokenType: string(customerTokens.TokenType), - Balance: customerTokens.Balance, - Customer: ToCustomerResponse(&customerTokens.Customer), - CreatedAt: customerTokens.CreatedAt, - UpdatedAt: customerTokens.UpdatedAt, - } -} - -// ToCustomerTokensResponses converts a slice of customer tokens entities to customer tokens responses -func ToCustomerTokensResponses(customerTokens []entities.CustomerTokens) []models.CustomerTokensResponse { - responses := make([]models.CustomerTokensResponse, len(customerTokens)) - for i, ct := range customerTokens { - responses[i] = *ToCustomerTokensResponse(&ct) - } - return responses -} - -// ToCustomerTokensEntity converts a create customer tokens request to a customer tokens entity -func ToCustomerTokensEntity(req *models.CreateCustomerTokensRequest) *entities.CustomerTokens { - return &entities.CustomerTokens{ - CustomerID: req.CustomerID, - TokenType: entities.TokenType(req.TokenType), - Balance: req.Balance, - } -} - -// UpdateCustomerTokensEntity updates a customer tokens entity with update request data -func UpdateCustomerTokensEntity(customerTokens *entities.CustomerTokens, req *models.UpdateCustomerTokensRequest) { - if req.Balance >= 0 { - customerTokens.Balance = req.Balance - } -} diff --git a/internal/mappers/game_play_mapper.go b/internal/mappers/game_play_mapper.go index cf88268..659ca51 100644 --- a/internal/mappers/game_play_mapper.go +++ b/internal/mappers/game_play_mapper.go @@ -16,7 +16,7 @@ func ToGamePlayResponse(gamePlay *entities.GamePlay) *models.GamePlayResponse { GameID: gamePlay.GameID, CustomerID: gamePlay.CustomerID, PrizeID: gamePlay.PrizeID, - TokenUsed: gamePlay.TokenUsed, + CoinsUsed: gamePlay.CoinsUsed, RandomSeed: gamePlay.RandomSeed, CreatedAt: gamePlay.CreatedAt, Game: ToGameResponse(&gamePlay.Game), @@ -48,7 +48,7 @@ func ToGamePlayEntity(req *models.CreateGamePlayRequest) *entities.GamePlay { return &entities.GamePlay{ GameID: req.GameID, CustomerID: req.CustomerID, - TokenUsed: req.TokenUsed, + CoinsUsed: req.CoinsUsed, RandomSeed: req.RandomSeed, } } diff --git a/internal/mappers/order_mapper.go b/internal/mappers/order_mapper.go index 5f68ce2..8a12404 100644 --- a/internal/mappers/order_mapper.go +++ b/internal/mappers/order_mapper.go @@ -189,6 +189,8 @@ func PaymentEntityToResponse(payment *entities.Payment) *models.PaymentResponse SplitType: (*string)(payment.SplitType), SplitDescription: payment.SplitDescription, RefundAmount: payment.RefundAmount, + PointsUsed: payment.PointsUsed, + PointValue: payment.PointValue, RefundReason: payment.RefundReason, RefundedAt: payment.RefundedAt, RefundedBy: payment.RefundedBy, diff --git a/internal/mappers/payment_method_mapper.go b/internal/mappers/payment_method_mapper.go index 651e721..526acac 100644 --- a/internal/mappers/payment_method_mapper.go +++ b/internal/mappers/payment_method_mapper.go @@ -134,6 +134,7 @@ func ListPaymentMethodsContractToModel(req *contract.ListPaymentMethodsRequest) return &models.ListPaymentMethodsRequest{ OrganizationID: req.OrganizationID, + OutletID: req.OutletID, Type: paymentMethodType, IsActive: req.IsActive, Search: req.Search, diff --git a/internal/mappers/spin_game_mapper.go b/internal/mappers/spin_game_mapper.go index be5b882..dd4b184 100644 --- a/internal/mappers/spin_game_mapper.go +++ b/internal/mappers/spin_game_mapper.go @@ -38,7 +38,8 @@ func SpinGameResponseDataModelToContract(data *models.SpinGameResponseData) *con return &contract.SpinGameResponseData{ GamePlay: GamePlayResponseModelToContract(&data.GamePlay), PrizeWon: CustomerGamePrizeResponseModelToContract(data.PrizeWon), - TokensRemaining: data.TokensRemaining, + CoinsRemaining: data.CoinsRemaining, + TokensRemaining: data.CoinsRemaining, } } @@ -53,7 +54,8 @@ func GamePlayResponseModelToContract(resp *models.GamePlayResponse) contract.Gam GameID: resp.GameID, CustomerID: resp.CustomerID, PrizeID: resp.PrizeID, - TokenUsed: resp.TokenUsed, + CoinsUsed: resp.CoinsUsed, + TokenUsed: resp.CoinsUsed, RandomSeed: resp.RandomSeed, CreatedAt: resp.CreatedAt, Game: nil, // Optional field - can be populated separately if needed diff --git a/internal/middleware/auth_middleware.go b/internal/middleware/auth_middleware.go index ad42527..9bfc7a8 100644 --- a/internal/middleware/auth_middleware.go +++ b/internal/middleware/auth_middleware.go @@ -85,6 +85,14 @@ func (m *AuthMiddleware) RequireAdminOrManager() gin.HandlerFunc { return m.RequireRole("superadmin", "admin", "manager", "owner", "purchasing") } +// RequireLoyaltyManager guards what moves or prices EnakPoint and EnakCoin: loyalty +// settings and manual wallet adjustments (docs/prd-point-coin.md F1, F2, F7). Only +// admins and managers may do these; unlike RequireAdminOrManager it does not let the +// purchasing role through. +func (m *AuthMiddleware) RequireLoyaltyManager() gin.HandlerFunc { + return m.RequireRole("superadmin", "admin", "manager", "owner") +} + func (m *AuthMiddleware) RequireAdminOrManagerOrPurchasing() gin.HandlerFunc { return m.RequireRole("superadmin", "admin", "manager", "owner", "purchasing") } diff --git a/internal/models/analytics.go b/internal/models/analytics.go index 109a65b..141dac2 100644 --- a/internal/models/analytics.go +++ b/internal/models/analytics.go @@ -33,7 +33,14 @@ type PaymentMethodAnalyticsResponse struct { // PaymentMethodSummary represents the summary of payment method analytics type PaymentMethodSummary struct { - TotalAmount float64 `json:"total_amount"` + // Money actually received. EnakPoint is not money in (docs/prd-point-coin.md F9, + // K7) and is reported apart; its accounting treatment waits on note N2. + TotalAmount float64 `json:"total_amount"` + // Rupiah paid with EnakPoint, and how many EnakPoint that was. + PointAmount float64 `json:"point_amount"` + PointsUsed int64 `json:"points_used"` + // TotalAmount plus PointAmount: the value of the orders paid. + TotalWithPoints float64 `json:"total_with_points"` TotalOrders int64 `json:"total_orders"` TotalPayments int64 `json:"total_payments"` AverageOrderValue float64 `json:"average_order_value"` @@ -47,7 +54,11 @@ type PaymentMethodAnalyticsData struct { TotalAmount float64 `json:"total_amount"` OrderCount int64 `json:"order_count"` PaymentCount int64 `json:"payment_count"` - Percentage float64 `json:"percentage"` + // Share of the money received; 0 for EnakPoint, which is not money in. + Percentage float64 `json:"percentage"` + PointsUsed int64 `json:"points_used"` + // False for EnakPoint. + CountsAsCashIn bool `json:"counts_as_cash_in"` } // SalesAnalyticsRequest represents the request for sales analytics @@ -464,12 +475,12 @@ type ProfitLossAnalyticsResponse struct { } type ProfitLossPurchasing struct { - TodayTotal float64 `json:"today_total"` - MtdTotal float64 `json:"mtd_total"` - TodayRawMaterial float64 `json:"today_raw_material"` - MtdRawMaterial float64 `json:"mtd_raw_material"` - TodayExpense float64 `json:"today_expense"` - MtdExpense float64 `json:"mtd_expense"` + TodayTotal float64 `json:"today_total"` + MtdTotal float64 `json:"mtd_total"` + TodayRawMaterial float64 `json:"today_raw_material"` + MtdRawMaterial float64 `json:"mtd_raw_material"` + TodayExpense float64 `json:"today_expense"` + MtdExpense float64 `json:"mtd_expense"` Items []ProfitLossPurchasingItem `json:"items"` } diff --git a/internal/models/campaign.go b/internal/models/campaign.go index 9c65dc6..9720694 100644 --- a/internal/models/campaign.go +++ b/internal/models/campaign.go @@ -11,7 +11,7 @@ import ( type CreateCampaignRequest struct { Name string `json:"name" binding:"required,min=1,max=150"` Description *string `json:"description,omitempty"` - Type string `json:"type" binding:"required,oneof=REWARD POINTS TOKENS MIXED"` + Type string `json:"type" binding:"required,oneof=REWARD POINTS COINS TOKENS MIXED"` StartDate time.Time `json:"start_date" binding:"required"` EndDate time.Time `json:"end_date" binding:"required"` IsActive bool `json:"is_active"` @@ -25,7 +25,7 @@ type UpdateCampaignRequest struct { ID uuid.UUID `json:"id" binding:"required"` Name string `json:"name" binding:"required,min=1,max=150"` Description *string `json:"description,omitempty"` - Type string `json:"type" binding:"required,oneof=REWARD POINTS TOKENS MIXED"` + Type string `json:"type" binding:"required,oneof=REWARD POINTS COINS TOKENS MIXED"` StartDate time.Time `json:"start_date" binding:"required"` EndDate time.Time `json:"end_date" binding:"required"` IsActive bool `json:"is_active"` @@ -88,7 +88,7 @@ type CreateCampaignRuleRequest struct { CampaignID uuid.UUID `json:"campaign_id" binding:"required"` RuleType string `json:"rule_type" binding:"required,oneof=TIER SPEND PRODUCT CATEGORY DAY LOCATION"` ConditionValue *string `json:"condition_value,omitempty"` - RewardType string `json:"reward_type" binding:"required,oneof=POINTS TOKENS REWARD"` + RewardType string `json:"reward_type" binding:"required,oneof=POINTS COINS TOKENS REWARD"` RewardValue *int64 `json:"reward_value,omitempty"` RewardSubtype *string `json:"reward_subtype,omitempty"` RewardRefID *uuid.UUID `json:"reward_ref_id,omitempty"` @@ -100,7 +100,7 @@ type UpdateCampaignRuleRequest struct { CampaignID uuid.UUID `json:"campaign_id" binding:"required"` RuleType string `json:"rule_type" binding:"required,oneof=TIER SPEND PRODUCT CATEGORY DAY LOCATION"` ConditionValue *string `json:"condition_value,omitempty"` - RewardType string `json:"reward_type" binding:"required,oneof=POINTS TOKENS REWARD"` + RewardType string `json:"reward_type" binding:"required,oneof=POINTS COINS TOKENS REWARD"` RewardValue *int64 `json:"reward_value,omitempty"` RewardSubtype *string `json:"reward_subtype,omitempty"` RewardRefID *uuid.UUID `json:"reward_ref_id,omitempty"` @@ -126,7 +126,7 @@ type ListCampaignRulesResponse struct { type CampaignRuleStruct struct { RuleType string `json:"rule_type" binding:"required,oneof=TIER SPEND PRODUCT CATEGORY DAY LOCATION"` ConditionValue *string `json:"condition_value,omitempty"` - RewardType string `json:"reward_type" binding:"required,oneof=POINTS TOKENS REWARD"` + RewardType string `json:"reward_type" binding:"required,oneof=POINTS COINS TOKENS REWARD"` RewardValue *int64 `json:"reward_value,omitempty"` RewardSubtype *string `json:"reward_subtype,omitempty"` RewardRefID *uuid.UUID `json:"reward_ref_id,omitempty"` diff --git a/internal/models/customer_pin.go b/internal/models/customer_pin.go new file mode 100644 index 0000000..6b3616c --- /dev/null +++ b/internal/models/customer_pin.go @@ -0,0 +1,47 @@ +package models + +import ( + "time" + + "github.com/google/uuid" +) + +// CustomerPinStatus is GET /customer/pin/status. +type CustomerPinStatus struct { + HasPin bool `json:"has_pin"` + LockedUntil *time.Time `json:"locked_until"` + TransferBlockedUntil *time.Time `json:"transfer_blocked_until"` +} + +// CustomerPinOtp is what POST /customer/pin/otp returns: the token to send back with +// the code the customer received. +type CustomerPinOtp struct { + Purpose string `json:"purpose"` + OtpToken string `json:"otp_token"` + ExpiresAt time.Time `json:"expires_at"` +} + +// CustomerSecurityEventView is one row of GET /marketing/customers/:id/security-events. +type CustomerSecurityEventView struct { + ID uuid.UUID `json:"id"` + Event string `json:"event"` + ActorUser *uuid.UUID `json:"actor_user,omitempty"` + Reason *string `json:"reason,omitempty"` + IPAddress *string `json:"ip_address,omitempty"` + UserAgent *string `json:"user_agent,omitempty"` + CreatedAt time.Time `json:"created_at"` +} + +// CustomerPinRequestInfo is where a PIN request came from, for the security log. +type CustomerPinRequestInfo struct { + IPAddress string + UserAgent string +} + +// PaymentCode is what POST /customer/wallet/payment-code returns: a one-time code the +// customer shows the cashier, as digits or as a QR of QRPayload. +type PaymentCode struct { + Code string `json:"code"` + QRPayload string `json:"qr_payload"` + ExpiresAt time.Time `json:"expires_at"` +} diff --git a/internal/models/customer_points.go b/internal/models/customer_points.go index cfe9b45..9e1c84f 100644 --- a/internal/models/customer_points.go +++ b/internal/models/customer_points.go @@ -2,66 +2,8 @@ package models import ( "time" - - "github.com/google/uuid" ) -// Existing gamification models -type CreateCustomerPointsRequest struct { - CustomerID uuid.UUID `json:"customer_id" validate:"required"` - Balance int64 `json:"balance" validate:"min=0"` -} - -type UpdateCustomerPointsRequest struct { - Balance int64 `json:"balance" validate:"min=0"` -} - -type AddCustomerPointsRequest struct { - Balance int64 `json:"balance" validate:"required,min=1"` -} - -type DeductCustomerPointsRequest struct { - Balance int64 `json:"balance" validate:"required,min=1"` -} - -type CustomerPointsResponse struct { - ID uuid.UUID `json:"id"` - CustomerID uuid.UUID `json:"customer_id"` - Balance int64 `json:"balance"` - Customer *CustomerResponse `json:"customer,omitempty"` - CreatedAt time.Time `json:"created_at"` - UpdatedAt time.Time `json:"updated_at"` -} - -type ListCustomerPointsQuery struct { - Page int `json:"page" validate:"min=1"` - Limit int `json:"limit" validate:"min=1,max=100"` - Search string `json:"search"` - SortBy string `json:"sort_by" validate:"omitempty,oneof=balance created_at updated_at"` - SortOrder string `json:"sort_order" validate:"omitempty,oneof=asc desc"` -} - -type PaginatedCustomerPointsResponse struct { - Data []CustomerPointsResponse `json:"data"` - TotalCount int `json:"total_count"` - Page int `json:"page"` - Limit int `json:"limit"` - TotalPages int `json:"total_pages"` -} - -// New customer API models -type GetCustomerPointsRequest struct { - // No additional fields needed - customer ID comes from JWT token -} - -type GetCustomerTokensRequest struct { - // No additional fields needed - customer ID comes from JWT token -} - -type GetCustomerWalletRequest struct { - // No additional fields needed - customer ID comes from JWT token -} - // Response Models type GetCustomerPointsResponse struct { Status string `json:"status"` @@ -109,7 +51,20 @@ type GetCustomerWalletResponse struct { Data *GetCustomerWalletResponseData `json:"data,omitempty"` } +// GetCustomerWalletResponseData is GET /customer/wallet (docs/prd-point-coin.md F6). type GetCustomerWalletResponseData struct { + // Balances the customer can spend now. + PointBalance int64 `json:"point_balance"` + CoinBalance int64 `json:"coin_balance"` + // Rupiah value of one EnakPoint, and of the whole point balance. EnakPoint only + // ever pays for orders, so the app shows this as "setara potongan Rp …" (K7). + PointValue int64 `json:"point_value"` + PointDiscountValue int64 `json:"point_discount_value"` + NearestExpiring CustomerWalletNearestExpiring `json:"nearest_expiring"` + RecentTransactions []CustomerWalletTransaction `json:"recent_transactions"` + + // Deprecated: the shape of this endpoint before the wallet, kept for app versions + // that still read it. Filled from the wallet like the fields above. TotalPoints int64 `json:"total_points"` TotalTokens int64 `json:"total_tokens"` PointsHistory []PointsHistoryItem `json:"points_history,omitempty"` diff --git a/internal/models/customer_tokens.go b/internal/models/customer_tokens.go deleted file mode 100644 index 7ee4455..0000000 --- a/internal/models/customer_tokens.go +++ /dev/null @@ -1,44 +0,0 @@ -package models - -import ( - "time" - - "github.com/google/uuid" -) - -type CreateCustomerTokensRequest struct { - CustomerID uuid.UUID `json:"customer_id" validate:"required"` - TokenType string `json:"token_type" validate:"required,oneof=SPIN RAFFLE MINIGAME"` - Balance int64 `json:"balance" validate:"min=0"` -} - -type UpdateCustomerTokensRequest struct { - Balance int64 `json:"balance" validate:"min=0"` -} - -type AddCustomerTokensRequest struct { - Tokens int64 `json:"tokens" validate:"required,min=1"` -} - -type DeductCustomerTokensRequest struct { - Tokens int64 `json:"tokens" validate:"required,min=1"` -} - -type CustomerTokensResponse struct { - ID uuid.UUID `json:"id"` - CustomerID uuid.UUID `json:"customer_id"` - TokenType string `json:"token_type"` - Balance int64 `json:"balance"` - Customer *CustomerResponse `json:"customer,omitempty"` - CreatedAt time.Time `json:"created_at"` - UpdatedAt time.Time `json:"updated_at"` -} - -type ListCustomerTokensQuery struct { - Page int `query:"page" validate:"min=1"` - Limit int `query:"limit" validate:"min=1,max=100"` - Search string `query:"search"` - TokenType string `query:"token_type" validate:"omitempty,oneof=SPIN RAFFLE MINIGAME"` - SortBy string `query:"sort_by" validate:"omitempty,oneof=balance token_type created_at updated_at"` - SortOrder string `query:"sort_order" validate:"omitempty,oneof=asc desc"` -} diff --git a/internal/models/game_play.go b/internal/models/game_play.go index 342c2c9..f2378b3 100644 --- a/internal/models/game_play.go +++ b/internal/models/game_play.go @@ -9,7 +9,7 @@ import ( type CreateGamePlayRequest struct { GameID uuid.UUID `json:"game_id" validate:"required"` CustomerID uuid.UUID `json:"customer_id" validate:"required"` - TokenUsed int `json:"token_used" validate:"min=0"` + CoinsUsed int `json:"coins_used" validate:"min=0"` RandomSeed *string `json:"random_seed,omitempty"` } @@ -18,7 +18,7 @@ type GamePlayResponse struct { GameID uuid.UUID `json:"game_id"` CustomerID uuid.UUID `json:"customer_id"` PrizeID *uuid.UUID `json:"prize_id,omitempty"` - TokenUsed int `json:"token_used"` + CoinsUsed int `json:"coins_used"` RandomSeed *string `json:"random_seed,omitempty"` CreatedAt time.Time `json:"created_at"` Game *GameResponse `json:"game,omitempty"` @@ -33,18 +33,18 @@ type ListGamePlaysQuery struct { GameID *uuid.UUID `query:"game_id"` CustomerID *uuid.UUID `query:"customer_id"` PrizeID *uuid.UUID `query:"prize_id"` - SortBy string `query:"sort_by" validate:"omitempty,oneof=created_at token_used"` + SortBy string `query:"sort_by" validate:"omitempty,oneof=created_at coins_used token_used"` SortOrder string `query:"sort_order" validate:"omitempty,oneof=asc desc"` } +// PlayGameRequest plays a game for a customer, at the game's metadata.coin_cost. type PlayGameRequest struct { GameID uuid.UUID `json:"game_id" validate:"required"` CustomerID uuid.UUID `json:"customer_id" validate:"required"` - TokenUsed int `json:"token_used" validate:"min=0"` } type PlayGameResponse struct { - GamePlay GamePlayResponse `json:"game_play"` - PrizeWon *GamePrizeResponse `json:"prize_won,omitempty"` - TokensRemaining int64 `json:"tokens_remaining"` + GamePlay GamePlayResponse `json:"game_play"` + PrizeWon *GamePrizeResponse `json:"prize_won,omitempty"` + CoinsRemaining int64 `json:"coins_remaining"` } diff --git a/internal/models/loyalty.go b/internal/models/loyalty.go new file mode 100644 index 0000000..3a0f8b1 --- /dev/null +++ b/internal/models/loyalty.go @@ -0,0 +1,193 @@ +package models + +import ( + "math" + "time" + + "github.com/google/uuid" +) + +// OutletLoyaltySettings are an outlet's loyalty settings (docs/prd-point-coin.md F1). +type OutletLoyaltySettings struct { + Point LoyaltyEarnSettings `json:"point"` + Coin LoyaltyEarnSettings `json:"coin"` + // Paying with EnakPoint. EnakCoin cannot pay, so it has no counterpart. + PointPayment LoyaltyPointPaymentSettings `json:"point_payment"` +} + +// LoyaltyEarnSettings is how much of one currency an order earns: +// floor(basis / EarnPerAmount) × EarnValue, nothing below MinOrderAmount, and at most +// MaxPerOrder when set. +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"` +} + +type LoyaltyPointPaymentSettings struct { + AcceptPayment bool `json:"accept_payment"` + MinPaymentPoints int64 `json:"min_payment_points"` + // Largest share of the order total, 0–100, that EnakPoint may pay. + MaxPaymentPercent int64 `json:"max_payment_percent"` +} + +// OrganizationLoyaltySettings are the loyalty settings shared by every outlet of an +// organization (docs/prd-point-coin.md F2, F12). +type OrganizationLoyaltySettings struct { + // Rupiah value of one EnakPoint when paying. + PointValue int64 `json:"point_value"` + // CoinAmount EnakCoin exchange into PointAmount EnakPoint. + Exchange LoyaltyExchangeSettings `json:"exchange"` + Transfer LoyaltyTransferSettings `json:"transfer"` + PointExpiry LoyaltyExpirySettings `json:"point_expiry"` + CoinExpiry LoyaltyExpirySettings `json:"coin_expiry"` +} + +type LoyaltyExchangeSettings struct { + CoinAmount int64 `json:"coin_amount"` + PointAmount int64 `json:"point_amount"` +} + +type LoyaltyTransferSettings struct { + Enabled bool `json:"enabled"` + MinAmount int64 `json:"min_amount"` + MaxPerTransaction *int64 `json:"max_per_transaction"` + DailyLimit *int64 `json:"daily_limit"` +} + +// LoyaltyExpirySettings is when one currency expires once received (F12). Both +// models of note N4 are supported, and the owner picks one: +// +// - FIXED_DATE: everything expires on the next of FixedDates falling on or after +// the day received + GraceMonths, so a balance received just before a date moves +// on to the one after. +// - ROLLING: everything lasts Period Units from the day received, to the end of +// that month when EndOfMonth is set. +type LoyaltyExpirySettings struct { + Enabled bool `json:"enabled"` + // FIXED_DATE or ROLLING. + Mode string `json:"mode"` + // FIXED_DATE: the days of the year balances expire on, as MM-DD, sorted. + FixedDates []string `json:"fixed_dates"` + // FIXED_DATE: how many months a balance lasts at least before a fixed date takes it. + GraceMonths int64 `json:"grace_months"` + // ROLLING: how long a balance lasts. + Period int64 `json:"period"` + // ROLLING: DAY or MONTH. + Unit string `json:"unit"` + EndOfMonth bool `json:"end_of_month"` + // Days before expiry the customer is reminded; 0 for no reminder. + ReminderDays int64 `json:"reminder_days"` +} + +// LoyaltySettingChange is one row of the loyalty settings history. +type LoyaltySettingChange struct { + ID uuid.UUID `json:"id"` + OrganizationID uuid.UUID `json:"organization_id"` + OutletID *uuid.UUID `json:"outlet_id"` + Key string `json:"key"` + // Nil when the key had no stored value, that is it was on its default. + OldValue *string `json:"old_value"` + NewValue *string `json:"new_value"` + ChangedBy uuid.UUID `json:"changed_by"` + CreatedAt time.Time `json:"created_at"` +} + +// OutletLoyaltySettingsView is GET and PUT /outlets/:id/loyalty-settings. +type OutletLoyaltySettingsView struct { + OutletID uuid.UUID `json:"outlet_id"` + OutletLoyaltySettings + // 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). + PointCashbackPercent float64 `json:"point_cashback_percent"` + // Set on PUT: the keys that changed. + Changes []LoyaltySettingChange `json:"changes,omitempty"` +} + +// LoyaltyCashbackPercent is earnValue × pointValue / earnPerAmount as a percentage, +// rounded to two decimals. +func LoyaltyCashbackPercent(earnValue, pointValue, earnPerAmount int64) float64 { + if earnPerAmount <= 0 { + return 0 + } + return math.Round(float64(earnValue)*float64(pointValue)*10000/float64(earnPerAmount)) / 100 +} + +// OrganizationLoyaltySettingsView is GET and PUT /marketing/loyalty-settings. +type OrganizationLoyaltySettingsView struct { + OrganizationLoyaltySettings + // What the balances in circulation are worth, before and after the change. + Impact LoyaltySettingsImpact `json:"impact"` + // When a balance received now would expire under these settings (F12). + ExpiryPreview LoyaltyExpiryPreview `json:"expiry_preview"` + // The currencies this change turns expiry on for, and the balances affected. + ExpiryActivations []LoyaltyExpiryActivation `json:"expiry_activations"` + // On PUT, the keys that changed; on a dry run, the keys that would. + Changes []LoyaltySettingChange `json:"changes"` + // True when nothing was saved. + DryRun bool `json:"dry_run"` +} + +// LoyaltyExpiryActivation is expiry being turned on for a currency: the balances that +// had no expiry and the expiry they get (F12). On a dry run nothing is dated yet. +type LoyaltyExpiryActivation struct { + Currency string `json:"currency"` + Lots int64 `json:"lots"` + Amount int64 `json:"amount"` + ExpiresAt time.Time `json:"expires_at"` +} + +// LoyaltyExpiryPreview is what the dashboard shows next to the expiry settings: "the +// EnakPoint received today expire on …". Nil means they never expire. +type LoyaltyExpiryPreview struct { + Point *time.Time `json:"point"` + Coin *time.Time `json:"coin"` +} + +// LoyaltySettingsImpact shows how a change of point value or exchange rate changes what +// the balances in circulation are worth (F2). Before and after are equal when neither +// changes. +type LoyaltySettingsImpact struct { + OutstandingPoints int64 `json:"outstanding_points"` + OutstandingCoins int64 `json:"outstanding_coins"` + + PointValueBefore int64 `json:"point_value_before"` + PointValueAfter int64 `json:"point_value_after"` + PointRupiahBefore int64 `json:"point_rupiah_before"` + PointRupiahAfter int64 `json:"point_rupiah_after"` + + // The coins in circulation exchanged at the rate, in EnakPoint and in rupiah. + CoinsAsPointsBefore int64 `json:"coins_as_points_before"` + CoinsAsPointsAfter int64 `json:"coins_as_points_after"` + CoinRupiahBefore int64 `json:"coin_rupiah_before"` + CoinRupiahAfter int64 `json:"coin_rupiah_after"` +} + +// 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 { + asPoints := func(s OrganizationLoyaltySettings) int64 { + if s.Exchange.CoinAmount <= 0 { + return 0 + } + return coins * s.Exchange.PointAmount / s.Exchange.CoinAmount + } + impact := LoyaltySettingsImpact{ + OutstandingPoints: points, + OutstandingCoins: coins, + PointValueBefore: before.PointValue, + PointValueAfter: after.PointValue, + PointRupiahBefore: points * before.PointValue, + PointRupiahAfter: points * after.PointValue, + CoinsAsPointsBefore: asPoints(before), + CoinsAsPointsAfter: asPoints(after), + } + impact.CoinRupiahBefore = impact.CoinsAsPointsBefore * before.PointValue + impact.CoinRupiahAfter = impact.CoinsAsPointsAfter * after.PointValue + return impact +} diff --git a/internal/models/loyalty_test.go b/internal/models/loyalty_test.go new file mode 100644 index 0000000..2fc48e5 --- /dev/null +++ b/internal/models/loyalty_test.go @@ -0,0 +1,32 @@ +package models + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestLoyaltyCashbackPercent(t *testing.T) { + assert.Equal(t, 1.0, LoyaltyCashbackPercent(1, 1, 100)) + assert.Equal(t, 0.1, LoyaltyCashbackPercent(1, 1, 1000)) + assert.Equal(t, 0.33, LoyaltyCashbackPercent(1, 1, 300), "rounded to two decimals") + assert.Equal(t, 0.67, LoyaltyCashbackPercent(2, 1, 300), "rounded, not cut") + assert.Equal(t, 0.0, LoyaltyCashbackPercent(1, 1, 0)) +} + +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}} + + got := NewLoyaltySettingsImpact(50000, 105, before, after) + assert.Equal(t, LoyaltySettingsImpact{ + OutstandingPoints: 50000, OutstandingCoins: 105, + PointValueBefore: 1, PointValueAfter: 100, + PointRupiahBefore: 50000, PointRupiahAfter: 5000000, + CoinsAsPointsBefore: 105, CoinsAsPointsAfter: 10, // floor(105 / 10) + CoinRupiahBefore: 105, CoinRupiahAfter: 1000, + }, got) + + same := NewLoyaltySettingsImpact(10, 10, before, before) + assert.Equal(t, same.PointRupiahBefore, same.PointRupiahAfter) +} diff --git a/internal/models/order.go b/internal/models/order.go index d18e2a9..d15278f 100644 --- a/internal/models/order.go +++ b/internal/models/order.go @@ -182,6 +182,9 @@ type OrderResponse struct { TotalPaid float64 PaymentCount int SplitType *string + // What the order earned (docs/prd-point-coin.md F3), from its EARN rows. + PointsEarned int64 + CoinsEarned int64 } type OrderItemResponse struct { diff --git a/internal/models/payment.go b/internal/models/payment.go index bf35894..1269b9e 100644 --- a/internal/models/payment.go +++ b/internal/models/payment.go @@ -28,8 +28,10 @@ type Payment struct { } type CreatePaymentRequest struct { - OrderID uuid.UUID `validate:"required"` - PaymentMethodID uuid.UUID `validate:"required"` + OrderID uuid.UUID `validate:"required"` + PaymentMethodID uuid.UUID `validate:"required"` + Points *int64 + PaymentCode *string Amount float64 `validate:"required,min=0"` TransactionID *string `validate:"omitempty"` SplitNumber int `validate:"omitempty,min=1"` @@ -60,6 +62,9 @@ type PaymentResponse struct { SplitType *string SplitDescription *string RefundAmount float64 + // Set for a payment with EnakPoint. + PointsUsed *int64 + PointValue *float64 RefundReason *string RefundedAt *time.Time RefundedBy *uuid.UUID diff --git a/internal/models/payment_method.go b/internal/models/payment_method.go index 398586d..b7ea272 100644 --- a/internal/models/payment_method.go +++ b/internal/models/payment_method.go @@ -51,11 +51,13 @@ type PaymentMethodResponse struct { type ListPaymentMethodsRequest struct { OrganizationID *uuid.UUID - Type *constants.PaymentMethodType - IsActive *bool - Search string - Page int `validate:"min=1"` - Limit int `validate:"min=1,max=100"` + // When set, EnakPoint is left out unless the outlet accepts it (F9). + OutletID *uuid.UUID + Type *constants.PaymentMethodType + IsActive *bool + Search string + Page int `validate:"min=1"` + Limit int `validate:"min=1,max=100"` } type ListPaymentMethodsResponse struct { diff --git a/internal/models/spin_game.go b/internal/models/spin_game.go index ae66946..a384b7a 100644 --- a/internal/models/spin_game.go +++ b/internal/models/spin_game.go @@ -20,9 +20,9 @@ type SpinGameResponse struct { // SpinGameResponseData contains the game play result type SpinGameResponseData struct { - GamePlay GamePlayResponse `json:"game_play"` - PrizeWon *CustomerGamePrizeResponse `json:"prize_won,omitempty"` - TokensRemaining int64 `json:"tokens_remaining"` + GamePlay GamePlayResponse `json:"game_play"` + PrizeWon *CustomerGamePrizeResponse `json:"prize_won,omitempty"` + CoinsRemaining int64 `json:"coins_remaining"` } // SpinGamePrizeResponse represents a prize won in the spin game diff --git a/internal/models/wallet.go b/internal/models/wallet.go new file mode 100644 index 0000000..9412444 --- /dev/null +++ b/internal/models/wallet.go @@ -0,0 +1,166 @@ +package models + +import ( + "time" + + "github.com/google/uuid" +) + +// CustomerWalletTransaction is one ledger row as the customer app shows it +// (docs/prd-point-coin.md F6). +type CustomerWalletTransaction struct { + ID uuid.UUID `json:"id"` + Currency string `json:"currency"` + Type string `json:"type"` + // Signed: positive added to the balance, negative taken from it. + Amount int64 `json:"amount"` + BalanceAfter int64 `json:"balance_after"` + Description string `json:"description"` + // Where the value came from, set on additions. + Source *CustomerWalletTransactionRef `json:"source,omitempty"` + // Where the value went, set on deductions. + Destination *CustomerWalletTransactionRef `json:"destination,omitempty"` + OutletID *uuid.UUID `json:"outlet_id,omitempty"` + ReversesTransactionID *uuid.UUID `json:"reverses_transaction_id,omitempty"` + // Shared by the two rows of an exchange or a transfer. + GroupID *uuid.UUID `json:"group_id,omitempty"` + // Additions only: the earliest expiry among the lots it created, nil when none of + // them expire, and the lots themselves. + ExpiresAt *time.Time `json:"expires_at,omitempty"` + Lots []CustomerWalletLot `json:"lots,omitempty"` + CreatedAt time.Time `json:"created_at"` +} + +// CustomerWalletTransactionRef points at what a ledger row came from or went to, as +// listed in §8.1: ORDER, PAYMENT, WALLET_TX, GAME_PLAY, LOT, USER and so on. +type CustomerWalletTransactionRef struct { + Type string `json:"type"` + ID uuid.UUID `json:"id"` +} + +type CustomerWalletLot struct { + Amount int64 `json:"amount"` + Remaining int64 `json:"remaining"` + ExpiresAt *time.Time `json:"expires_at"` +} + +// CustomerWalletExpiring is how much expires on one day. +type CustomerWalletExpiring struct { + Amount int64 `json:"amount"` + // YYYY-MM-DD, Asia/Jakarta. + Date string `json:"date"` +} + +// CustomerWalletNearestExpiring is the next day each currency loses balance, nil when +// nothing is due to expire. +type CustomerWalletNearestExpiring struct { + Point *CustomerWalletExpiring `json:"point"` + Coin *CustomerWalletExpiring `json:"coin"` +} + +// ListCustomerWalletTransactionsQuery is GET /customer/wallet/transactions. +type ListCustomerWalletTransactionsQuery struct { + Page int `form:"page"` + Limit int `form:"limit"` + Currency string `form:"currency"` + // One type, or several separated by commas. + Type string `form:"type"` + // Inclusive calendar dates, YYYY-MM-DD, Asia/Jakarta. + From string `form:"from"` + To string `form:"to"` +} + +// AdminCustomerWallet is GET /marketing/customers/:id/wallet (docs/prd-point-coin.md +// F7). Unlike the customer's own view it shows the raw balances next to the spendable +// ones, every lot that still holds something, and the real names behind each row. +type AdminCustomerWallet struct { + Customer AdminWalletCustomer `json:"customer"` + // Balances as the ledger has them. + PointBalance int64 `json:"point_balance"` + CoinBalance int64 `json:"coin_balance"` + // What can be spent now. Lower than the ledger balance only while lots that have + // expired wait for the expiry job. + SpendablePointBalance int64 `json:"spendable_point_balance"` + SpendableCoinBalance int64 `json:"spendable_coin_balance"` + Lots []AdminWalletLot `json:"lots"` + Transactions PaginatedResponse[AdminWalletTransaction] `json:"transactions"` +} + +type AdminWalletCustomer struct { + ID uuid.UUID `json:"id"` + Name string `json:"name"` + Phone *string `json:"phone,omitempty"` +} + +type AdminWalletLot struct { + ID uuid.UUID `json:"id"` + Currency string `json:"currency"` + OriginalAmount int64 `json:"original_amount"` + RemainingAmount int64 `json:"remaining_amount"` + ExpiresAt *time.Time `json:"expires_at"` + Expired bool `json:"expired"` + SourceTransactionID uuid.UUID `json:"source_transaction_id"` + OriginLotID *uuid.UUID `json:"origin_lot_id,omitempty"` + CreatedAt time.Time `json:"created_at"` +} + +// AdminWalletTransaction is a ledger row with the names the customer does not see: +// the real counterparty of a transfer, the admin behind an adjustment, the cashier who +// took a payment, and the outlet. +type AdminWalletTransaction struct { + CustomerWalletTransaction + Counterparty *AdminWalletNamedRef `json:"counterparty,omitempty"` + CreatedBy *AdminWalletNamedRef `json:"created_by,omitempty"` + Outlet *AdminWalletNamedRef `json:"outlet,omitempty"` + Reason *string `json:"reason,omitempty"` + Metadata map[string]any `json:"metadata,omitempty"` +} + +type AdminWalletNamedRef struct { + ID uuid.UUID `json:"id"` + Name string `json:"name"` +} + +// WalletAdjustment is a manual correction by an admin. +type WalletAdjustment struct { + Currency string + // Signed: positive adds, negative takes away. + Amount int64 + Reason string + IdempotencyKey string +} + +// AdminWalletAdjustmentResult is what POST /marketing/customers/:id/wallet/adjust returns. +type AdminWalletAdjustmentResult struct { + Transaction AdminWalletTransaction `json:"transaction"` + SpendablePointBalance int64 `json:"spendable_point_balance"` + SpendableCoinBalance int64 `json:"spendable_coin_balance"` + // True when the idempotency key had been used before and nothing changed. + Replayed bool `json:"replayed"` +} + +// PointPaymentPreview is GET /orders/:id/point-payment/preview (docs/prd-point-coin.md +// F9): whether the order can be paid with EnakPoint and at most how much, for the +// cashier's "use maximum" button. +type PointPaymentPreview struct { + OrderID uuid.UUID `json:"order_id"` + CustomerID *uuid.UUID `json:"customer_id"` + Eligible bool `json:"eligible"` + // Why not, when not eligible. + Reason string `json:"reason,omitempty"` + PointBalance int64 `json:"point_balance"` + PointValue int64 `json:"point_value"` + RemainingAmount float64 `json:"remaining_amount"` + MinPaymentPoints int64 `json:"min_payment_points"` + MaxPaymentPercent int64 `json:"max_payment_percent"` + MaxPoints int64 `json:"max_points"` + // Rupiah covered by MaxPoints. + MaxAmount int64 `json:"max_amount"` +} + +// CustomerWalletExpiringList is GET /customer/wallet/expiring (docs/prd-point-coin.md +// F6): everything that will expire, per currency and day, soonest first. +type CustomerWalletExpiringList struct { + Point []CustomerWalletExpiring `json:"point"` + Coin []CustomerWalletExpiring `json:"coin"` +} diff --git a/internal/models/wallet_move.go b/internal/models/wallet_move.go new file mode 100644 index 0000000..d348cf4 --- /dev/null +++ b/internal/models/wallet_move.go @@ -0,0 +1,73 @@ +package models + +import ( + "time" + + "github.com/google/uuid" +) + +// WalletExchangePreview is GET /customer/wallet/exchange/preview +// (docs/prd-point-coin.md F4): the rate, and what exchanging Coins would give. +type WalletExchangePreview struct { + // The rate: CoinAmount EnakCoin exchange into PointAmount EnakPoint. + CoinAmount int64 `json:"coin_amount"` + PointAmount int64 `json:"point_amount"` + CoinBalance int64 `json:"coin_balance"` + Coins int64 `json:"coins"` + Points int64 `json:"points"` + // Whether Coins can be exchanged now, and why not when it cannot. + Valid bool `json:"valid"` + Reason string `json:"reason,omitempty"` +} + +// WalletMovedLot is part of what an exchange or a transfer delivered, with the +// expiry it carried over from the lot it came from (K9). +type WalletMovedLot struct { + Amount int64 `json:"amount"` + // Nil when it never expires. + ExpiresAt *time.Time `json:"expires_at"` +} + +// WalletExchangeResult is POST /customer/wallet/exchange. +type WalletExchangeResult struct { + GroupID uuid.UUID `json:"group_id"` + Coins int64 `json:"coins"` + Points int64 `json:"points"` + CoinAmount int64 `json:"coin_amount"` + PointAmount int64 `json:"point_amount"` + // The EnakPoint received, split by expiry. + Lots []WalletMovedLot `json:"lots"` + CoinBalance int64 `json:"coin_balance"` + PointBalance int64 `json:"point_balance"` + // True when this was a retry of an exchange already made; nothing moved again. + Replayed bool `json:"replayed"` +} + +// WalletTransferRecipient is GET /customer/wallet/transfer/recipient: who a phone +// number belongs to, masked, so the sender can check before confirming (F5). +type WalletTransferRecipient struct { + Name string `json:"name"` + PhoneNumber string `json:"phone_number"` +} + +// WalletTransfer is what a customer asks to send (F5). +type WalletTransfer struct { + // POINT or COIN. + Currency string + Amount int64 + RecipientPhone string +} + +// WalletTransferResult is POST /customer/wallet/transfer. +type WalletTransferResult struct { + GroupID uuid.UUID `json:"group_id"` + Currency string `json:"currency"` + Amount int64 `json:"amount"` + Recipient WalletTransferRecipient `json:"recipient"` + // What the recipient received, split by the expiry it carried over. + Lots []WalletMovedLot `json:"lots"` + // The sender's balance in the currency sent. + Balance int64 `json:"balance"` + // True when this was a retry of a transfer already made; nothing moved again. + Replayed bool `json:"replayed"` +} diff --git a/internal/models/wallet_trace.go b/internal/models/wallet_trace.go new file mode 100644 index 0000000..809d7c9 --- /dev/null +++ b/internal/models/wallet_trace.go @@ -0,0 +1,46 @@ +package models + +import ( + "time" + + "github.com/google/uuid" +) + +// AdminWalletTrace is GET /marketing/wallet-transactions/:id/trace +// (docs/prd-point-coin.md F7, §8.1): the lots a ledger row took from or created, and +// where each of them came from, lot by lot, back to the lot that first brought the +// balance into a wallet. It follows balance across transfers, exchanges and refunds. +type AdminWalletTrace struct { + Transaction AdminWalletTraceRow `json:"transaction"` + // One per lot the row took from (a debit) or created (a credit). + Lots []AdminWalletTraceLot `json:"lots"` +} + +// AdminWalletTraceLot is how much of a row went through one lot, and that lot's chain. +type AdminWalletTraceLot struct { + Amount int64 `json:"amount"` + // The lot itself first, then the lot it was carried over from, and so on. The + // last step is the lot an EARN, ADJUSTMENT or MIGRATION created. + Chain []AdminWalletTraceStep `json:"chain"` +} + +// AdminWalletTraceStep is one lot on a chain and the row that created it. +type AdminWalletTraceStep struct { + Lot AdminWalletLot `json:"lot"` + Source AdminWalletTraceRow `json:"source"` +} + +// AdminWalletTraceRow is a ledger row as a trace shows it, with the real name of the +// customer it belongs to. +type AdminWalletTraceRow struct { + ID uuid.UUID `json:"id"` + Customer AdminWalletNamedRef `json:"customer"` + Currency string `json:"currency"` + Type string `json:"type"` + Amount int64 `json:"amount"` + Description string `json:"description"` + ReferenceType string `json:"reference_type"` + ReferenceID uuid.UUID `json:"reference_id"` + OutletID *uuid.UUID `json:"outlet_id,omitempty"` + CreatedAt time.Time `json:"created_at"` +} diff --git a/internal/processor/analytics_processor.go b/internal/processor/analytics_processor.go index 1297e90..9764551 100644 --- a/internal/processor/analytics_processor.go +++ b/internal/processor/analytics_processor.go @@ -63,27 +63,37 @@ func (p *AnalyticsProcessorImpl) GetPaymentMethodAnalytics(ctx context.Context, return nil, fmt.Errorf("failed to get payment method analytics: %w", err) } - var totalAmount float64 + // EnakPoint is not money in (docs/prd-point-coin.md F9, K7): it is listed as its own + // method but left out of the money received and of the shares. How it is booked + // waits on note N2. + var cashAmount, pointAmount float64 + var pointsUsed int64 var totalOrders int64 var totalPayments int64 for _, data := range analyticsData { - totalAmount += data.TotalAmount + if data.PaymentMethodType == string(constants.PaymentMethodTypePoint) { + pointAmount += data.TotalAmount + pointsUsed += data.PointsUsed + } else { + cashAmount += data.TotalAmount + } totalOrders += data.OrderCount totalPayments += data.PaymentCount } + // The value of an order includes what EnakPoint paid, so the average does too. var averageOrderValue float64 if totalOrders > 0 { - averageOrderValue = totalAmount / float64(totalOrders) + averageOrderValue = (cashAmount + pointAmount) / float64(totalOrders) } - // Calculate percentages var resultData []models.PaymentMethodAnalyticsData for _, data := range analyticsData { + cashIn := data.PaymentMethodType != string(constants.PaymentMethodTypePoint) var percentage float64 - if totalAmount > 0 { - percentage = (data.TotalAmount / totalAmount) * 100 + if cashIn && cashAmount > 0 { + percentage = (data.TotalAmount / cashAmount) * 100 } resultData = append(resultData, models.PaymentMethodAnalyticsData{ @@ -94,11 +104,16 @@ func (p *AnalyticsProcessorImpl) GetPaymentMethodAnalytics(ctx context.Context, OrderCount: data.OrderCount, PaymentCount: data.PaymentCount, Percentage: percentage, + PointsUsed: data.PointsUsed, + CountsAsCashIn: cashIn, }) } summary := models.PaymentMethodSummary{ - TotalAmount: totalAmount, + TotalAmount: cashAmount, + PointAmount: pointAmount, + PointsUsed: pointsUsed, + TotalWithPoints: cashAmount + pointAmount, TotalOrders: totalOrders, TotalPayments: totalPayments, AverageOrderValue: averageOrderValue, diff --git a/internal/processor/analytics_processor_test.go b/internal/processor/analytics_processor_test.go index 7ae2d0e..33f9f79 100644 --- a/internal/processor/analytics_processor_test.go +++ b/internal/processor/analytics_processor_test.go @@ -10,6 +10,7 @@ import ( "apskel-pos-be/internal/models" "github.com/google/uuid" + "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) @@ -24,10 +25,11 @@ type analyticsRepositoryStub struct { exclusiveSummaryCalls int exclusiveSummaryFrom []time.Time exclusiveSummaryTo []time.Time + paymentMethods []*entities.PaymentMethodAnalytics } -func (analyticsRepositoryStub) GetPaymentMethodAnalytics(context.Context, uuid.UUID, *uuid.UUID, time.Time, time.Time) ([]*entities.PaymentMethodAnalytics, error) { - return nil, nil +func (s analyticsRepositoryStub) GetPaymentMethodAnalytics(context.Context, uuid.UUID, *uuid.UUID, time.Time, time.Time) ([]*entities.PaymentMethodAnalytics, error) { + return s.paymentMethods, nil } func (analyticsRepositoryStub) GetSalesAnalytics(context.Context, uuid.UUID, *uuid.UUID, time.Time, time.Time, string) ([]*entities.SalesAnalytics, error) { @@ -570,3 +572,35 @@ func TestAnalyticsProcessorGetExclusiveSummaryMTDBuildsMonthToDateBreakdown(t *t require.Len(t, result.DailySummary, 1) require.Len(t, result.DailyTransactions, 2) } + +// EnakPoint is listed as its own method but is not money in (F9, K7). +func TestPaymentMethodAnalytics_EnakPointIsNotCashIn(t *testing.T) { + repo := &analyticsRepositoryStub{paymentMethods: []*entities.PaymentMethodAnalytics{ + {PaymentMethodName: "Tunai", PaymentMethodType: "cash", TotalAmount: 70000, OrderCount: 2, PaymentCount: 2}, + {PaymentMethodName: "Kartu", PaymentMethodType: "card", TotalAmount: 20000, OrderCount: 1, PaymentCount: 1}, + {PaymentMethodName: "EnakPoint", PaymentMethodType: "point", TotalAmount: 30000, OrderCount: 1, PaymentCount: 1, PointsUsed: 30000}, + }} + p := NewAnalyticsProcessorImpl(repo, nil) + + got, err := p.GetPaymentMethodAnalytics(context.Background(), &models.PaymentMethodAnalyticsRequest{ + OrganizationID: uuid.New(), DateFrom: time.Now().Add(-time.Hour), DateTo: time.Now(), + }) + require.NoError(t, err) + assert.Equal(t, 90000.0, got.Summary.TotalAmount, "money in leaves EnakPoint out") + assert.Equal(t, 30000.0, got.Summary.PointAmount) + assert.Equal(t, int64(30000), got.Summary.PointsUsed) + assert.Equal(t, 120000.0, got.Summary.TotalWithPoints) + assert.Equal(t, int64(4), got.Summary.TotalOrders) + assert.Equal(t, 30000.0, got.Summary.AverageOrderValue, "the value of an order includes what EnakPoint paid") + + byType := map[string]models.PaymentMethodAnalyticsData{} + for _, d := range got.Data { + byType[d.PaymentMethodType] = d + } + assert.True(t, byType["cash"].CountsAsCashIn) + assert.False(t, byType["point"].CountsAsCashIn) + assert.InDelta(t, 77.78, byType["cash"].Percentage, 0.01, "shares are of the money received") + assert.InDelta(t, 22.22, byType["card"].Percentage, 0.01) + assert.Zero(t, byType["point"].Percentage) + assert.Equal(t, int64(30000), byType["point"].PointsUsed) +} diff --git a/internal/processor/campaign_processor.go b/internal/processor/campaign_processor.go index 2823a26..57f2c8f 100644 --- a/internal/processor/campaign_processor.go +++ b/internal/processor/campaign_processor.go @@ -70,7 +70,7 @@ func (p *campaignProcessor) ListCampaigns(ctx context.Context, req *contract.Lis Page: req.Page, Limit: req.Limit, Search: req.Search, - Type: req.Type, + Type: string(entities.NormalizeCampaignType(req.Type)), IsActive: req.IsActive, ShowOnApp: req.ShowOnApp, StartDate: req.StartDate, @@ -178,7 +178,7 @@ func (p *campaignRuleProcessor) CreateCampaignRule(ctx context.Context, req *con CampaignID: req.CampaignID, RuleType: entities.RuleType(req.RuleType), ConditionValue: req.ConditionValue, - RewardType: entities.CampaignRewardType(req.RewardType), + RewardType: entities.NormalizeCampaignRewardType(req.RewardType), RewardValue: req.RewardValue, RewardSubtype: (*entities.RewardSubtype)(req.RewardSubtype), RewardRefID: req.RewardRefID, @@ -218,7 +218,7 @@ func (p *campaignRuleProcessor) ListCampaignRules(ctx context.Context, req *cont Limit: req.Limit, CampaignID: req.CampaignID, RuleType: req.RuleType, - RewardType: req.RewardType, + RewardType: string(entities.NormalizeCampaignRewardType(req.RewardType)), } // Get from repository @@ -247,7 +247,7 @@ func (p *campaignRuleProcessor) UpdateCampaignRule(ctx context.Context, req *con CampaignID: req.CampaignID, RuleType: entities.RuleType(req.RuleType), ConditionValue: req.ConditionValue, - RewardType: entities.CampaignRewardType(req.RewardType), + RewardType: entities.NormalizeCampaignRewardType(req.RewardType), RewardValue: req.RewardValue, RewardSubtype: (*entities.RewardSubtype)(req.RewardSubtype), RewardRefID: req.RewardRefID, diff --git a/internal/processor/customer_device_processor.go b/internal/processor/customer_device_processor.go new file mode 100644 index 0000000..419c2f4 --- /dev/null +++ b/internal/processor/customer_device_processor.go @@ -0,0 +1,77 @@ +package processor + +import ( + "context" + "errors" + "fmt" + "strings" + "time" + + "github.com/google/uuid" + + "apskel-pos-be/internal/logger" + "apskel-pos-be/internal/repository" +) + +// ErrInvalidCustomerDevice wraps every rejection of a device registration. +var ErrInvalidCustomerDevice = errors.New("invalid customer device") + +type customerPushSender interface { + SendMulticastNotification(ctx context.Context, tokens []string, title string, body string, data map[string]string) error +} + +// CustomerDeviceProcessor keeps the customer app's FCM tokens and sends push +// notifications to a customer's devices. +type CustomerDeviceProcessor struct { + repo repository.CustomerDeviceRepository + // Nil when FCM is not configured; notifications are then skipped. + fcm customerPushSender + now func() time.Time +} + +func NewCustomerDeviceProcessor(repo repository.CustomerDeviceRepository, fcm customerPushSender) *CustomerDeviceProcessor { + return &CustomerDeviceProcessor{repo: repo, fcm: fcm, now: time.Now} +} + +// Register saves the FCM token the app got for this device. The app calls it after +// login and whenever FCM gives it a new token. +func (p *CustomerDeviceProcessor) Register(ctx context.Context, device repository.CustomerDevice) error { + device.DeviceID = strings.TrimSpace(device.DeviceID) + device.FCMToken = strings.TrimSpace(device.FCMToken) + switch { + case device.DeviceID == "" || len(device.DeviceID) > 255: + return fmt.Errorf("%w: device_id is required, at most 255 characters", ErrInvalidCustomerDevice) + case device.FCMToken == "" || len(device.FCMToken) > 512: + return fmt.Errorf("%w: fcm_token is required, at most 512 characters", ErrInvalidCustomerDevice) + } + if device.Platform != nil { + platform := strings.ToLower(strings.TrimSpace(*device.Platform)) + if platform != "android" && platform != "ios" && platform != "web" { + return fmt.Errorf("%w: platform must be android, ios or web", ErrInvalidCustomerDevice) + } + device.Platform = &platform + } + return p.repo.Register(ctx, device, p.now()) +} + +// Unregister forgets a device, so it stops getting the customer's notifications. +func (p *CustomerDeviceProcessor) Unregister(ctx context.Context, customerID uuid.UUID, deviceID string) error { + return p.repo.Unregister(ctx, customerID, strings.TrimSpace(deviceID)) +} + +// Notify pushes a notification to every device of the customer through FCM. A +// customer without a registered device gets nothing, which is not an error. +func (p *CustomerDeviceProcessor) Notify(ctx context.Context, customerID uuid.UUID, title, body string, data map[string]string) error { + if p.fcm == nil { + logger.NonContext.Info(fmt.Sprintf("FCM is not configured; not notifying customer %s", customerID)) + return nil + } + tokens, err := p.repo.ListTokens(ctx, customerID) + if err != nil { + return err + } + if len(tokens) == 0 { + return nil + } + return p.fcm.SendMulticastNotification(ctx, tokens, title, body, data) +} diff --git a/internal/processor/customer_device_processor_test.go b/internal/processor/customer_device_processor_test.go new file mode 100644 index 0000000..d8c3156 --- /dev/null +++ b/internal/processor/customer_device_processor_test.go @@ -0,0 +1,136 @@ +package processor + +import ( + "context" + "errors" + "testing" + "time" + + "github.com/google/uuid" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "apskel-pos-be/internal/repository" +) + +// customerDeviceRepoFake keeps devices the way the table does: one row per customer +// and device, and a token belongs to one row only. +type customerDeviceRepoFake struct{ devices []repository.CustomerDevice } + +func (f *customerDeviceRepoFake) Register(_ context.Context, d repository.CustomerDevice, _ time.Time) error { + kept := f.devices[:0] + for _, existing := range f.devices { + sameRow := existing.CustomerID == d.CustomerID && existing.DeviceID == d.DeviceID + if !sameRow && existing.FCMToken != d.FCMToken { + kept = append(kept, existing) + } + } + f.devices = append(kept, d) + return nil +} + +func (f *customerDeviceRepoFake) Unregister(_ context.Context, customerID uuid.UUID, deviceID string) error { + kept := f.devices[:0] + for _, d := range f.devices { + if d.CustomerID != customerID || d.DeviceID != deviceID { + kept = append(kept, d) + } + } + f.devices = kept + return nil +} + +func (f *customerDeviceRepoFake) ListTokens(_ context.Context, customerID uuid.UUID) ([]string, error) { + var tokens []string + for _, d := range f.devices { + if d.CustomerID == customerID { + tokens = append(tokens, d.FCMToken) + } + } + return tokens, nil +} + +type fcmFake struct { + tokens [][]string + title string + body string + data map[string]string + err error +} + +func (f *fcmFake) SendMulticastNotification(_ context.Context, tokens []string, title, body string, data map[string]string) error { + f.tokens = append(f.tokens, tokens) + f.title, f.body, f.data = title, body, data + return f.err +} + +func TestCustomerDevice_NotifiesEveryDeviceOfTheCustomer(t *testing.T) { + repo, fcm := &customerDeviceRepoFake{}, &fcmFake{} + p := NewCustomerDeviceProcessor(repo, fcm) + ctx := context.Background() + budi, anita := uuid.New(), uuid.New() + + require.NoError(t, p.Register(ctx, repository.CustomerDevice{CustomerID: budi, DeviceID: "phone", FCMToken: "t1", Platform: ptr("Android")})) + require.NoError(t, p.Register(ctx, repository.CustomerDevice{CustomerID: budi, DeviceID: "tablet", FCMToken: "t2"})) + // A refreshed token replaces the old one of the same device. + require.NoError(t, p.Register(ctx, repository.CustomerDevice{CustomerID: budi, DeviceID: "phone", FCMToken: "t1b"})) + require.NoError(t, p.Register(ctx, repository.CustomerDevice{CustomerID: anita, DeviceID: "phone", FCMToken: "t3"})) + + require.NoError(t, p.Notify(ctx, budi, "EnakPoint masuk", "Kamu menerima 10 EnakPoint", map[string]string{"type": "X"})) + assert.Equal(t, [][]string{{"t2", "t1b"}}, fcm.tokens) + assert.Equal(t, "EnakPoint masuk", fcm.title) + assert.Equal(t, map[string]string{"type": "X"}, fcm.data) +} + +func TestCustomerDevice_TokenMovesToWhoeverLogsInOnThePhone(t *testing.T) { + repo, fcm := &customerDeviceRepoFake{}, &fcmFake{} + p := NewCustomerDeviceProcessor(repo, fcm) + ctx := context.Background() + budi, anita := uuid.New(), uuid.New() + + require.NoError(t, p.Register(ctx, repository.CustomerDevice{CustomerID: budi, DeviceID: "phone", FCMToken: "shared"})) + require.NoError(t, p.Register(ctx, repository.CustomerDevice{CustomerID: anita, DeviceID: "phone", FCMToken: "shared"})) + + // Budi's notifications no longer reach the phone Anita is now logged in on. + require.NoError(t, p.Notify(ctx, budi, "t", "b", nil)) + require.NoError(t, p.Notify(ctx, anita, "t", "b", nil)) + assert.Equal(t, [][]string{{"shared"}}, fcm.tokens) +} + +func TestCustomerDevice_NothingToSend(t *testing.T) { + repo, fcm := &customerDeviceRepoFake{}, &fcmFake{} + ctx := context.Background() + customer := uuid.New() + + // No device registered, or logged out: nothing is sent and nothing fails. + require.NoError(t, NewCustomerDeviceProcessor(repo, fcm).Notify(ctx, customer, "t", "b", nil)) + require.NoError(t, NewCustomerDeviceProcessor(repo, fcm).Register(ctx, repository.CustomerDevice{CustomerID: customer, DeviceID: "phone", FCMToken: "t1"})) + require.NoError(t, NewCustomerDeviceProcessor(repo, fcm).Unregister(ctx, customer, "phone")) + require.NoError(t, NewCustomerDeviceProcessor(repo, fcm).Notify(ctx, customer, "t", "b", nil)) + assert.Empty(t, fcm.tokens) + + // FCM not configured. + require.NoError(t, NewCustomerDeviceProcessor(repo, nil).Notify(ctx, customer, "t", "b", nil)) +} + +func TestCustomerDevice_FCMFailureIsReported(t *testing.T) { + repo, fcm := &customerDeviceRepoFake{}, &fcmFake{err: errors.New("unavailable")} + p := NewCustomerDeviceProcessor(repo, fcm) + ctx := context.Background() + customer := uuid.New() + require.NoError(t, p.Register(ctx, repository.CustomerDevice{CustomerID: customer, DeviceID: "phone", FCMToken: "t1"})) + + assert.Error(t, p.Notify(ctx, customer, "t", "b", nil)) +} + +func TestCustomerDevice_RejectsIncompleteRegistrations(t *testing.T) { + p := NewCustomerDeviceProcessor(&customerDeviceRepoFake{}, nil) + ctx := context.Background() + for name, d := range map[string]repository.CustomerDevice{ + "no device": {FCMToken: "t"}, + "no token": {DeviceID: "phone", FCMToken: " "}, + "bad platform": {DeviceID: "phone", FCMToken: "t", Platform: ptr("symbian")}, + } { + assert.ErrorIs(t, p.Register(ctx, d), ErrInvalidCustomerDevice, name) + } +} diff --git a/internal/processor/customer_pin_processor.go b/internal/processor/customer_pin_processor.go new file mode 100644 index 0000000..0de4f19 --- /dev/null +++ b/internal/processor/customer_pin_processor.go @@ -0,0 +1,471 @@ +package processor + +import ( + "context" + "errors" + "fmt" + "strings" + "time" + + "github.com/google/uuid" + "golang.org/x/crypto/bcrypt" + + "apskel-pos-be/internal/entities" + "apskel-pos-be/internal/logger" + "apskel-pos-be/internal/models" + "apskel-pos-be/internal/repository" +) + +// PIN rules (docs/prd-point-coin.md F11, Q16, Q17). +const ( + pinLength = 6 + pinMaxAttempts = 5 + pinLockDuration = 30 * time.Minute + pinTransferHold = 24 * time.Hour + pinSecurityReasonN = 255 + + PinOtpPurposeSetup = "pin_setup" + PinOtpPurposeReset = "pin_reset" +) + +// Security log events. +const ( + PinEventSet = "PIN_SET" + PinEventChanged = "PIN_CHANGED" + PinEventReset = "PIN_RESET" + PinEventFailed = "PIN_FAILED" + PinEventLocked = "PIN_LOCKED" + PinEventRemovedByAdmin = "PIN_REMOVED_BY_ADMIN" +) + +// What a PIN approves. Only a transfer is held after a reset. +type PinAction string + +const ( + PinActionPay PinAction = "PAY" + PinActionExchange PinAction = "EXCHANGE" + PinActionTransfer PinAction = "TRANSFER" +) + +// Codes of PinError, which the apps tell apart (docs/prd-point-coin.md §9). +const ( + PinErrNotSet = "PIN_NOT_SET" + PinErrInvalid = "PIN_INVALID" + PinErrLocked = "PIN_LOCKED" + PinErrTransferBlocked = "TRANSFER_BLOCKED" +) + +// PinError is why a PIN did not approve an action. +type PinError struct { + Code string + // Set for PIN_INVALID: attempts left before the PIN locks. + RemainingAttempts int + // Set for PIN_LOCKED and TRANSFER_BLOCKED. + Until *time.Time +} + +func (e *PinError) Error() string { + switch e.Code { + case PinErrNotSet: + return "PIN has not been set" + case PinErrInvalid: + return fmt.Sprintf("wrong PIN, %d attempts left", e.RemainingAttempts) + case PinErrLocked: + return fmt.Sprintf("PIN is locked until %s", e.Until.Format(time.RFC3339)) + case PinErrTransferBlocked: + return fmt.Sprintf("transfers are on hold after a PIN reset until %s", e.Until.Format(time.RFC3339)) + } + return e.Code +} + +var ( + // ErrInvalidPinInput wraps a PIN that is malformed, weak, or not confirmed. The + // message never contains the PIN. + ErrInvalidPinInput = errors.New("invalid PIN") + // ErrPinAlreadySet means a first PIN was requested for a customer who has one. + ErrPinAlreadySet = errors.New("PIN has already been set") + // ErrPinOtpInvalid means the OTP was wrong, expired, used, for another purpose, or + // sent to another number. + ErrPinOtpInvalid = errors.New("invalid or expired OTP") + // ErrPinOtpTooSoon means an OTP was requested again too quickly. + ErrPinOtpTooSoon = errors.New("an OTP was sent recently; wait before asking again") + // ErrPinNoPhone means the customer has no phone number to send an OTP to. + ErrPinNoPhone = errors.New("customer has no phone number") +) + +type pinOtpSender interface { + CanResendOtp(ctx context.Context, phoneNumber string, purpose string) (bool, int, error) + CreateOtpSession(ctx context.Context, phoneNumber string, purpose string) (*entities.OtpSession, error) + SendOtpViaWhatsApp(phoneNumber string, otpCode string, purpose string) error + ValidateOtpSession(ctx context.Context, token string, code string) (*entities.OtpSession, error) +} + +// NotificationTypePinLocked is the data type of the push a customer gets when their +// PIN locks, so the app can offer the PIN reset. +const NotificationTypePinLocked = "PIN_LOCKED" + +// CustomerPinProcessor manages customer PINs (docs/prd-point-coin.md F11). Every flow +// that moves balance on the customer's request calls VerifyPin first (K8). +type CustomerPinProcessor struct { + repo repository.CustomerPinRepository + otp pinOtpSender + notifier customerNotifier + now func() time.Time + cost int +} + +func NewCustomerPinProcessor(repo repository.CustomerPinRepository, otp pinOtpSender, notifier customerNotifier) *CustomerPinProcessor { + return &CustomerPinProcessor{repo: repo, otp: otp, notifier: notifier, now: time.Now, cost: bcrypt.DefaultCost} +} + +func (p *CustomerPinProcessor) Status(ctx context.Context, customerID uuid.UUID) (*models.CustomerPinStatus, error) { + state, err := p.repo.GetState(ctx, customerID) + if err != nil { + return nil, err + } + now := p.now() + status := &models.CustomerPinStatus{HasPin: state.PinHash != nil} + if state.LockedUntil != nil && state.LockedUntil.After(now) { + status.LockedUntil = state.LockedUntil + } + if state.TransferBlockedUntil != nil && state.TransferBlockedUntil.After(now) { + status.TransferBlockedUntil = state.TransferBlockedUntil + } + return status, nil +} + +// RequestOtp sends an OTP to the customer's own phone number, for creating a first PIN +// (pin_setup) or resetting a forgotten one (pin_reset). +func (p *CustomerPinProcessor) RequestOtp(ctx context.Context, customerID uuid.UUID, purpose string) (*models.CustomerPinOtp, error) { + state, err := p.repo.GetState(ctx, customerID) + if err != nil { + return nil, err + } + switch purpose { + case PinOtpPurposeSetup: + if state.PinHash != nil { + return nil, ErrPinAlreadySet + } + case PinOtpPurposeReset: + if state.PinHash == nil { + return nil, &PinError{Code: PinErrNotSet} + } + default: + return nil, fmt.Errorf("%w: purpose must be %s or %s", ErrInvalidPinInput, PinOtpPurposeSetup, PinOtpPurposeReset) + } + if state.PhoneNumber == nil || *state.PhoneNumber == "" { + return nil, ErrPinNoPhone + } + + canSend, _, err := p.otp.CanResendOtp(ctx, *state.PhoneNumber, purpose) + if err != nil { + return nil, err + } + if !canSend { + return nil, ErrPinOtpTooSoon + } + session, err := p.otp.CreateOtpSession(ctx, *state.PhoneNumber, purpose) + if err != nil { + return nil, err + } + if err := p.otp.SendOtpViaWhatsApp(*state.PhoneNumber, session.Code, purpose); err != nil { + return nil, err + } + return &models.CustomerPinOtp{Purpose: purpose, OtpToken: session.Token, ExpiresAt: session.ExpiresAt}, nil +} + +// CreatePin sets a customer's first PIN, approved by an OTP to their phone so it is set +// by the owner of the number and not by whoever holds a logged-in phone. +func (p *CustomerPinProcessor) CreatePin(ctx context.Context, customerID uuid.UUID, otpToken, otpCode, pin, confirmPin string, info models.CustomerPinRequestInfo) error { + state, err := p.repo.GetState(ctx, customerID) + if err != nil { + return err + } + if state.PinHash != nil { + return ErrPinAlreadySet + } + // Check the PIN before spending the OTP, so a weak PIN does not cost a new code. + if err := checkNewPin(pin, confirmPin, state.BirthDate); err != nil { + return err + } + if err := p.checkOtp(ctx, state, otpToken, otpCode, PinOtpPurposeSetup); err != nil { + return err + } + hash, err := p.hash(pin) + if err != nil { + return err + } + if err := p.repo.SetPin(ctx, customerID, hash, nil); err != nil { + return err + } + p.logEvent(ctx, customerID, PinEventSet, nil, nil, info) + return nil +} + +// ChangePin replaces the PIN after checking the old one, which counts toward the lock +// like any other attempt. A transfer hold from an earlier reset stays. +func (p *CustomerPinProcessor) ChangePin(ctx context.Context, customerID uuid.UUID, oldPin, pin, confirmPin string, info models.CustomerPinRequestInfo) error { + state, err := p.repo.GetState(ctx, customerID) + if err != nil { + return err + } + if err := checkNewPin(pin, confirmPin, state.BirthDate); err != nil { + return err + } + if err := p.verify(ctx, state, oldPin, PinActionPay, info); err != nil { + return err + } + hash, err := p.hash(pin) + if err != nil { + return err + } + if err := p.repo.SetPin(ctx, customerID, hash, p.activeHold(state)); err != nil { + return err + } + p.logEvent(ctx, customerID, PinEventChanged, nil, nil, info) + return nil +} + +// ResetPin sets a new PIN for a customer who forgot theirs, approved by an OTP. It also +// lifts a lock, and holds outgoing transfers for 24 hours in case the phone number was +// taken over (Q16). +func (p *CustomerPinProcessor) ResetPin(ctx context.Context, customerID uuid.UUID, otpToken, otpCode, pin, confirmPin string, info models.CustomerPinRequestInfo) error { + state, err := p.repo.GetState(ctx, customerID) + if err != nil { + return err + } + if state.PinHash == nil { + return &PinError{Code: PinErrNotSet} + } + if err := checkNewPin(pin, confirmPin, state.BirthDate); err != nil { + return err + } + if err := p.checkOtp(ctx, state, otpToken, otpCode, PinOtpPurposeReset); err != nil { + return err + } + hash, err := p.hash(pin) + if err != nil { + return err + } + hold := p.now().Add(pinTransferHold) + if err := p.repo.SetPin(ctx, customerID, hash, &hold); err != nil { + return err + } + p.logEvent(ctx, customerID, PinEventReset, nil, nil, info) + return nil +} + +// VerifyPin checks the PIN before an action that moves balance. It returns a *PinError +// with the code the apps act on: PIN_NOT_SET, PIN_INVALID (with the attempts left), +// PIN_LOCKED or TRANSFER_BLOCKED (with until when). +func (p *CustomerPinProcessor) VerifyPin(ctx context.Context, customerID uuid.UUID, pin string, action PinAction, info models.CustomerPinRequestInfo) error { + state, err := p.repo.GetState(ctx, customerID) + if err != nil { + return err + } + return p.verify(ctx, state, pin, action, info) +} + +func (p *CustomerPinProcessor) verify(ctx context.Context, state *repository.CustomerPinState, pin string, action PinAction, info models.CustomerPinRequestInfo) error { + if state.PinHash == nil { + return &PinError{Code: PinErrNotSet} + } + now := p.now() + // A locked PIN is refused before it is compared, even when it is right. + if state.LockedUntil != nil && state.LockedUntil.After(now) { + until := *state.LockedUntil + return &PinError{Code: PinErrLocked, Until: &until} + } + // A held transfer is refused before the PIN is compared, so it costs no attempt. + if action == PinActionTransfer && state.TransferBlockedUntil != nil && state.TransferBlockedUntil.After(now) { + until := *state.TransferBlockedUntil + return &PinError{Code: PinErrTransferBlocked, Until: &until} + } + + if bcrypt.CompareHashAndPassword([]byte(*state.PinHash), []byte(pin)) != nil { + attempts, lockedUntil, err := p.repo.RecordFailure(ctx, state.CustomerID, pinMaxAttempts, now, now.Add(pinLockDuration)) + if err != nil { + return err + } + p.logEvent(ctx, state.CustomerID, PinEventFailed, nil, nil, info) + if lockedUntil != nil && lockedUntil.After(now) { + // Only the attempt that reached the limit logs the lock and tells the + // customer; attempts racing it just see the lock. + if attempts == pinMaxAttempts { + p.logEvent(ctx, state.CustomerID, PinEventLocked, nil, nil, info) + p.alertLocked(ctx, state, *lockedUntil) + } + return &PinError{Code: PinErrLocked, Until: lockedUntil} + } + return &PinError{Code: PinErrInvalid, RemainingAttempts: pinMaxAttempts - attempts} + } + if state.FailedAttempts > 0 || state.LockedUntil != nil { + if err := p.repo.ClearFailures(ctx, state.CustomerID); err != nil { + return err + } + } + return nil +} + +// RemovePinByAdmin deletes a customer's PIN, for example when they lost access to it, +// so they have to create a new one through OTP. Admins can never set or read a PIN. +func (p *CustomerPinProcessor) RemovePinByAdmin(ctx context.Context, organizationID, customerID, adminID uuid.UUID, reason string, info models.CustomerPinRequestInfo) error { + reason = strings.TrimSpace(reason) + if reason == "" { + return fmt.Errorf("%w: a reason is required", ErrInvalidPinInput) + } + if adminID == uuid.Nil { + return fmt.Errorf("%w: the admin is unknown", ErrInvalidPinInput) + } + state, err := p.repo.GetState(ctx, customerID) + if err != nil { + return err + } + if state.OrganizationID != organizationID { + return repository.ErrPinCustomerNotFound + } + if state.PinHash == nil { + return &PinError{Code: PinErrNotSet} + } + if err := p.repo.RemovePin(ctx, customerID); err != nil { + return err + } + reason = truncateRunes(reason, pinSecurityReasonN) + p.logEvent(ctx, customerID, PinEventRemovedByAdmin, &adminID, &reason, info) + return nil +} + +// ListEvents returns a page of a customer's PIN security log for the dashboard. +func (p *CustomerPinProcessor) ListEvents(ctx context.Context, organizationID, customerID uuid.UUID, page, limit int) (*models.PaginatedResponse[models.CustomerSecurityEventView], error) { + state, err := p.repo.GetState(ctx, customerID) + if err != nil { + return nil, err + } + if state.OrganizationID != organizationID { + return nil, repository.ErrPinCustomerNotFound + } + if page < 1 { + page = 1 + } + if limit < 1 || limit > 100 { + limit = 20 + } + rows, total, err := p.repo.ListEvents(ctx, customerID, (page-1)*limit, limit) + if err != nil { + return nil, err + } + events := make([]models.CustomerSecurityEventView, 0, len(rows)) + for _, e := range rows { + events = append(events, models.CustomerSecurityEventView{ + ID: e.ID, Event: e.Event, ActorUser: e.ActorUser, Reason: e.Reason, + IPAddress: e.IPAddress, UserAgent: e.UserAgent, CreatedAt: e.CreatedAt, + }) + } + return &models.PaginatedResponse[models.CustomerSecurityEventView]{ + Data: events, + Pagination: models.Pagination{ + Page: page, Limit: limit, Total: total, TotalPages: int((total + int64(limit) - 1) / int64(limit)), + }, + }, nil +} + +// checkOtp validates an OTP and that it was issued for this purpose to this customer's +// own phone number. Without those checks an OTP from the login flow, or one sent to +// another number, could approve a PIN change. +func (p *CustomerPinProcessor) checkOtp(ctx context.Context, state *repository.CustomerPinState, token, code, purpose string) error { + if token == "" || code == "" || state.PhoneNumber == nil { + return ErrPinOtpInvalid + } + session, err := p.otp.ValidateOtpSession(ctx, token, code) + if err != nil || session == nil { + return ErrPinOtpInvalid + } + if session.Purpose != purpose || session.PhoneNumber != *state.PhoneNumber { + return ErrPinOtpInvalid + } + return nil +} + +func (p *CustomerPinProcessor) hash(pin string) (string, error) { + hash, err := bcrypt.GenerateFromPassword([]byte(pin), p.cost) + if err != nil { + return "", fmt.Errorf("failed to hash PIN: %w", err) + } + return string(hash), nil +} + +func (p *CustomerPinProcessor) activeHold(state *repository.CustomerPinState) *time.Time { + if state.TransferBlockedUntil != nil && state.TransferBlockedUntil.After(p.now()) { + return state.TransferBlockedUntil + } + return nil +} + +// logEvent records a security event. The log is best effort: failing to write it must +// not undo what the customer just did, so a failure is logged instead. +func (p *CustomerPinProcessor) logEvent(ctx context.Context, customerID uuid.UUID, event string, actor *uuid.UUID, reason *string, info models.CustomerPinRequestInfo) { + e := repository.CustomerSecurityEvent{CustomerID: customerID, Event: event, ActorUser: actor, Reason: reason} + if info.IPAddress != "" { + ip := truncateRunes(info.IPAddress, 45) + e.IPAddress = &ip + } + if info.UserAgent != "" { + ua := truncateRunes(info.UserAgent, 255) + e.UserAgent = &ua + } + if err := p.repo.InsertEvent(ctx, e); err != nil { + logger.NonContext.Error(fmt.Sprintf("Could not record %s for customer %s", event, customerID), err) + } +} + +// alertLocked pushes the lock to the customer's app through FCM (F11). It is best +// effort: the lock stands whether or not the push goes out. +func (p *CustomerPinProcessor) alertLocked(ctx context.Context, state *repository.CustomerPinState, until time.Time) { + if p.notifier == nil { + return + } + body := fmt.Sprintf("PIN EnakPoint kamu terkunci sampai %s karena salah dimasukkan %d kali. Jika ini bukan kamu, segera reset PIN lewat aplikasi.", + until.In(walletDisplayLocation).Format("02 Jan 2006 15:04 WIB"), pinMaxAttempts) + data := map[string]string{ + "type": NotificationTypePinLocked, + "locked_until": until.UTC().Format(time.RFC3339), + } + if err := p.notifier.Notify(ctx, state.CustomerID, "PIN terkunci", body, data); err != nil { + logger.NonContext.Error(fmt.Sprintf("Could not tell customer %s their PIN is locked", state.CustomerID), err) + } +} + +// checkNewPin rejects a PIN that is not 6 digits, does not match its confirmation, or +// is easy to guess: one digit repeated, a run up or down, or the birth date as DDMMYY +// or YYMMDD. +func checkNewPin(pin, confirm string, birthDate *time.Time) error { + if len(pin) != pinLength { + return fmt.Errorf("%w: a PIN is %d digits", ErrInvalidPinInput, pinLength) + } + for _, r := range pin { + if r < '0' || r > '9' { + return fmt.Errorf("%w: a PIN is digits only", ErrInvalidPinInput) + } + } + if pin != confirm { + return fmt.Errorf("%w: the PIN and its confirmation differ", ErrInvalidPinInput) + } + same, up, down := true, true, true + for i := 1; i < len(pin); i++ { + d := int(pin[i]) - int(pin[i-1]) + same = same && d == 0 + up = up && d == 1 + down = down && d == -1 + } + if same || up || down { + return fmt.Errorf("%w: the PIN is too easy to guess", ErrInvalidPinInput) + } + if birthDate != nil { + for _, layout := range []string{"020106", "060102"} { + if pin == birthDate.Format(layout) { + return fmt.Errorf("%w: the PIN must not be your birth date", ErrInvalidPinInput) + } + } + } + return nil +} diff --git a/internal/processor/customer_pin_processor_db_test.go b/internal/processor/customer_pin_processor_db_test.go new file mode 100644 index 0000000..ca0e8d0 --- /dev/null +++ b/internal/processor/customer_pin_processor_db_test.go @@ -0,0 +1,257 @@ +package processor + +import ( + "context" + "errors" + "os" + "strings" + "sync" + "testing" + "time" + + "github.com/google/uuid" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "golang.org/x/crypto/bcrypt" + "gorm.io/driver/postgres" + "gorm.io/gorm" + "gorm.io/gorm/logger" + + "apskel-pos-be/internal/entities" + "apskel-pos-be/internal/models" + "apskel-pos-be/internal/repository" +) + +// otpFake keeps OTP sessions in memory with the checks the real one makes. +type otpFake struct { + mu sync.Mutex + sessions map[string]*entities.OtpSession + sent []string +} + +func (f *otpFake) CanResendOtp(context.Context, string, string) (bool, int, error) { + return true, 0, nil +} + +func (f *otpFake) CreateOtpSession(_ context.Context, phone, purpose string) (*entities.OtpSession, error) { + f.mu.Lock() + defer f.mu.Unlock() + s := &entities.OtpSession{Token: uuid.NewString(), Code: "246810", PhoneNumber: phone, Purpose: purpose, ExpiresAt: time.Now().Add(5 * time.Minute)} + f.sessions[s.Token] = s + return s, nil +} + +func (f *otpFake) SendOtpViaWhatsApp(phone, code, purpose string) error { + f.sent = append(f.sent, purpose) + return nil +} + +func (f *otpFake) ValidateOtpSession(_ context.Context, token, code string) (*entities.OtpSession, error) { + f.mu.Lock() + defer f.mu.Unlock() + s := f.sessions[token] + if s == nil || s.IsUsed || s.Code != code { + return nil, errors.New("invalid OTP") + } + s.IsUsed = true + return s, nil +} + +// issue creates a session as if it had been sent, for any purpose and number. +func (f *otpFake) issue(phone, purpose string) *entities.OtpSession { + s, _ := f.CreateOtpSession(context.Background(), phone, purpose) + return s +} + +type alerterFake struct { + mu sync.Mutex + messages []string +} + +func (f *alerterFake) Notify(_ context.Context, _ uuid.UUID, _, body string, _ map[string]string) error { + f.mu.Lock() + defer f.mu.Unlock() + f.messages = append(f.messages, body) + return nil +} + +// Needs TEST_DATABASE_URL pointing at a migrated database; see +// internal/repository/wallet_repository_test.go. +func TestCustomerPin_AgainstPostgres(t *testing.T) { + dsn := os.Getenv("TEST_DATABASE_URL") + if dsn == "" { + t.Skip("TEST_DATABASE_URL not set") + } + db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{Logger: logger.Default.LogMode(logger.Silent)}) + require.NoError(t, err) + ctx := context.Background() + + org, otherOrg, customer, admin := uuid.New(), uuid.New(), uuid.New(), uuid.New() + phone := "0812" + customer.String()[:8] + exec := func(q string, args ...any) { + t.Helper() + require.NoError(t, db.Exec(q, args...).Error) + } + exec(`INSERT INTO organizations (id, name, plan_type) VALUES (?, 'pin test', 'basic'), (?, 'other', 'basic')`, org, otherOrg) + exec(`INSERT INTO customers (id, organization_id, name, phone_number, birth_date) VALUES (?, ?, 'Budi', ?, '1990-03-14')`, customer, org, phone) + t.Cleanup(func() { + db.Exec(`DELETE FROM customer_security_events WHERE customer_id = ?`, customer) + db.Exec(`DELETE FROM customers WHERE id = ?`, customer) + db.Exec(`DELETE FROM organizations WHERE id IN ?`, []uuid.UUID{org, otherOrg}) + }) + + otp := &otpFake{sessions: map[string]*entities.OtpSession{}} + alerts := &alerterFake{} + p := NewCustomerPinProcessor(repository.NewCustomerPinRepository(db), otp, alerts) + p.cost = bcrypt.MinCost + clock := time.Now() + var clockMu sync.Mutex + p.now = func() time.Time { clockMu.Lock(); defer clockMu.Unlock(); return clock } + advance := func(d time.Duration) { clockMu.Lock(); clock = clock.Add(d); clockMu.Unlock() } + info := models.CustomerPinRequestInfo{IPAddress: "10.0.0.7", UserAgent: "EnakApp/2.0"} + const pin, newPin, resetPin = "482913", "572039", "613408" + + pinErr := func(err error) *PinError { + t.Helper() + var pe *PinError + require.True(t, errors.As(err, &pe), "want a PinError, got %v", err) + for _, secret := range []string{pin, newPin, resetPin} { + assert.NotContains(t, err.Error(), secret, "an error must never contain a PIN") + } + return pe + } + events := func() []string { + t.Helper() + var out []string + require.NoError(t, db.Raw(`SELECT event FROM customer_security_events WHERE customer_id = ? ORDER BY created_at, id`, customer).Scan(&out).Error) + return out + } + + // No PIN yet: nothing can be approved. + status, err := p.Status(ctx, customer) + require.NoError(t, err) + assert.False(t, status.HasPin) + assert.Equal(t, PinErrNotSet, pinErr(p.VerifyPin(ctx, customer, pin, PinActionPay, info)).Code) + + // Creating the first PIN takes an OTP sent to the customer's own number, for this + // purpose. + sent, err := p.RequestOtp(ctx, customer, PinOtpPurposeSetup) + require.NoError(t, err) + assert.Equal(t, []string{PinOtpPurposeSetup}, otp.sent) + + loginOtp := otp.issue(phone, "login") + assert.ErrorIs(t, p.CreatePin(ctx, customer, loginOtp.Token, loginOtp.Code, pin, pin, info), ErrPinOtpInvalid, "an OTP for another purpose") + strangerOtp := otp.issue("0899999999", PinOtpPurposeSetup) + assert.ErrorIs(t, p.CreatePin(ctx, customer, strangerOtp.Token, strangerOtp.Code, pin, pin, info), ErrPinOtpInvalid, "an OTP sent to another number") + assert.ErrorIs(t, p.CreatePin(ctx, customer, sent.OtpToken, "000000", pin, pin, info), ErrPinOtpInvalid, "a wrong code") + + // A weak PIN is refused before the OTP is used, so the same OTP still works after. + assert.ErrorIs(t, p.CreatePin(ctx, customer, sent.OtpToken, "246810", "123456", "123456", info), ErrInvalidPinInput) + assert.ErrorIs(t, p.CreatePin(ctx, customer, sent.OtpToken, "246810", "140390", "140390", info), ErrInvalidPinInput, "birth date") + require.NoError(t, p.CreatePin(ctx, customer, sent.OtpToken, "246810", pin, pin, info)) + assert.ErrorIs(t, p.CreatePin(ctx, customer, sent.OtpToken, "246810", pin, pin, info), ErrPinAlreadySet) + + var stored string + require.NoError(t, db.Raw(`SELECT pin_hash FROM customers WHERE id = ?`, customer).Scan(&stored).Error) + assert.NotContains(t, stored, pin, "only a hash is stored") + assert.True(t, strings.HasPrefix(stored, "$2"), "bcrypt") + + require.NoError(t, p.VerifyPin(ctx, customer, pin, PinActionPay, info)) + + // Four wrong attempts count down; the fifth locks for 30 minutes. + for left := 4; left >= 1; left-- { + pe := pinErr(p.VerifyPin(ctx, customer, "000001", PinActionPay, info)) + assert.Equal(t, PinErrInvalid, pe.Code) + assert.Equal(t, left, pe.RemainingAttempts) + } + pe := pinErr(p.VerifyPin(ctx, customer, "000001", PinActionPay, info)) + assert.Equal(t, PinErrLocked, pe.Code) + assert.WithinDuration(t, clock.Add(30*time.Minute), *pe.Until, time.Second) + assert.Len(t, alerts.messages, 1, "the customer is told the PIN locked") + + // While locked even the right PIN is refused. + pe = pinErr(p.VerifyPin(ctx, customer, pin, PinActionPay, info)) + assert.Equal(t, PinErrLocked, pe.Code) + status, err = p.Status(ctx, customer) + require.NoError(t, err) + assert.NotNil(t, status.LockedUntil) + + // Once the lock runs out a wrong PIN starts a new series of five. + advance(31 * time.Minute) + pe = pinErr(p.VerifyPin(ctx, customer, "000001", PinActionPay, info)) + assert.Equal(t, PinErrInvalid, pe.Code) + assert.Equal(t, 4, pe.RemainingAttempts) + // The right PIN resets the count. + require.NoError(t, p.VerifyPin(ctx, customer, pin, PinActionPay, info)) + pe = pinErr(p.VerifyPin(ctx, customer, "000001", PinActionPay, info)) + assert.Equal(t, 4, pe.RemainingAttempts) + require.NoError(t, p.VerifyPin(ctx, customer, pin, PinActionPay, info)) + + // Wrong attempts made at once all count: none slips past the lock. + var wg sync.WaitGroup + for i := 0; i < 8; i++ { + wg.Add(1) + go func() { defer wg.Done(); _ = p.VerifyPin(ctx, customer, "000001", PinActionPay, info) }() + } + wg.Wait() + pe = pinErr(p.VerifyPin(ctx, customer, pin, PinActionPay, info)) + assert.Equal(t, PinErrLocked, pe.Code) + + // Resetting through OTP lifts the lock and holds transfers for 24 hours. + _, err = p.RequestOtp(ctx, customer, PinOtpPurposeReset) + require.NoError(t, err) + setupOtp := otp.issue(phone, PinOtpPurposeSetup) + assert.ErrorIs(t, p.ResetPin(ctx, customer, setupOtp.Token, setupOtp.Code, resetPin, resetPin, info), ErrPinOtpInvalid, "a setup OTP cannot reset") + resetOtp := otp.issue(phone, PinOtpPurposeReset) + require.NoError(t, p.ResetPin(ctx, customer, resetOtp.Token, resetOtp.Code, resetPin, resetPin, info)) + status, err = p.Status(ctx, customer) + require.NoError(t, err) + assert.Nil(t, status.LockedUntil, "the lock is lifted") + require.NotNil(t, status.TransferBlockedUntil) + assert.WithinDuration(t, clock.Add(24*time.Hour), *status.TransferBlockedUntil, time.Second) + + require.NoError(t, p.VerifyPin(ctx, customer, resetPin, PinActionPay, info), "paying still works") + require.NoError(t, p.VerifyPin(ctx, customer, resetPin, PinActionExchange, info), "exchanging still works") + pe = pinErr(p.VerifyPin(ctx, customer, resetPin, PinActionTransfer, info)) + assert.Equal(t, PinErrTransferBlocked, pe.Code) + var failed int + require.NoError(t, db.Raw(`SELECT pin_failed_attempts FROM customers WHERE id = ?`, customer).Scan(&failed).Error) + assert.Zero(t, failed, "a held transfer costs no attempt") + + // Changing the PIN needs the old one and keeps the transfer hold. + assert.Equal(t, PinErrInvalid, pinErr(p.ChangePin(ctx, customer, "000001", newPin, newPin, info)).Code) + require.NoError(t, p.ChangePin(ctx, customer, resetPin, newPin, newPin, info)) + require.NoError(t, p.VerifyPin(ctx, customer, newPin, PinActionPay, info)) + assert.Equal(t, PinErrTransferBlocked, pinErr(p.VerifyPin(ctx, customer, newPin, PinActionTransfer, info)).Code) + advance(25 * time.Hour) + require.NoError(t, p.VerifyPin(ctx, customer, newPin, PinActionTransfer, info), "the hold ends after 24 hours") + + // An admin can remove the PIN, only in their own organization and with a reason. + assert.ErrorIs(t, p.RemovePinByAdmin(ctx, otherOrg, customer, admin, "hilang HP", info), repository.ErrPinCustomerNotFound) + assert.ErrorIs(t, p.RemovePinByAdmin(ctx, org, customer, admin, " ", info), ErrInvalidPinInput) + require.NoError(t, p.RemovePinByAdmin(ctx, org, customer, admin, "hilang HP", info)) + status, err = p.Status(ctx, customer) + require.NoError(t, err) + assert.False(t, status.HasPin) + assert.Equal(t, PinErrNotSet, pinErr(p.VerifyPin(ctx, customer, newPin, PinActionPay, info)).Code) + + // Every event is in the security log, with where it came from. + got := events() + for _, want := range []string{PinEventSet, PinEventFailed, PinEventLocked, PinEventReset, PinEventChanged, PinEventRemovedByAdmin} { + assert.Contains(t, got, want) + } + page, err := p.ListEvents(ctx, org, customer, 1, 100) + require.NoError(t, err) + assert.EqualValues(t, len(got), page.Pagination.Total) + removed := page.Data[0] + assert.Equal(t, PinEventRemovedByAdmin, removed.Event) + assert.Equal(t, &admin, removed.ActorUser) + assert.Equal(t, "hilang HP", *removed.Reason) + assert.Equal(t, "10.0.0.7", *removed.IPAddress) + _, err = p.ListEvents(ctx, otherOrg, customer, 1, 10) + assert.ErrorIs(t, err, repository.ErrPinCustomerNotFound) + + var locked int + require.NoError(t, db.Raw(`SELECT COUNT(*) FROM customer_security_events WHERE customer_id = ? AND event = ?`, customer, PinEventLocked).Scan(&locked).Error) + assert.Equal(t, locked, len(alerts.messages), "one alert per lock") +} diff --git a/internal/processor/customer_pin_processor_test.go b/internal/processor/customer_pin_processor_test.go new file mode 100644 index 0000000..f99a593 --- /dev/null +++ b/internal/processor/customer_pin_processor_test.go @@ -0,0 +1,107 @@ +package processor + +import ( + "context" + "testing" + "time" + + "github.com/google/uuid" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "golang.org/x/crypto/bcrypt" + + "apskel-pos-be/internal/models" + "apskel-pos-be/internal/repository" +) + +func TestCheckNewPin(t *testing.T) { + birth := time.Date(1990, 3, 14, 0, 0, 0, 0, time.UTC) + + for _, ok := range []string{"482913", "019283", "135790", "112233"} { + assert.NoError(t, checkNewPin(ok, ok, &birth), ok) + } + for name, c := range map[string][2]string{ + "too short": {"12345", "12345"}, + "too long": {"1234567", "1234567"}, + "not digits": {"12a456", "12a456"}, + "confirmation": {"482913", "482914"}, + "one digit": {"111111", "111111"}, + "zeros": {"000000", "000000"}, + "run up": {"123456", "123456"}, + "run up from 4": {"456789", "456789"}, + "run down": {"654321", "654321"}, + "run down from 9": {"987654", "987654"}, + "birth date DDMMYY": {"140390", "140390"}, + "birth date YYMMDD": {"900314", "900314"}, + } { + err := checkNewPin(c[0], c[1], &birth) + assert.ErrorIs(t, err, ErrInvalidPinInput, name) + assert.NotContains(t, err.Error(), c[0], "%s: the message must not echo the PIN", name) + } + // Without a birth date only the other rules apply. + assert.NoError(t, checkNewPin("140390", "140390", nil)) +} + +// pinRepoFake holds one customer's PIN state, with the lock rules of RecordFailure. +type pinRepoFake struct { + repository.CustomerPinRepository + state repository.CustomerPinState +} + +func (f *pinRepoFake) GetState(context.Context, uuid.UUID) (*repository.CustomerPinState, error) { + s := f.state + return &s, nil +} + +func (f *pinRepoFake) RecordFailure(_ context.Context, _ uuid.UUID, maxAttempts int, now, lockUntil time.Time) (int, *time.Time, error) { + if f.state.LockedUntil != nil && !f.state.LockedUntil.After(now) { + f.state.FailedAttempts, f.state.LockedUntil = 1, nil + } else { + f.state.FailedAttempts++ + if f.state.FailedAttempts >= maxAttempts { + f.state.LockedUntil = &lockUntil + } + } + return f.state.FailedAttempts, f.state.LockedUntil, nil +} + +func (f *pinRepoFake) ClearFailures(context.Context, uuid.UUID) error { + f.state.FailedAttempts, f.state.LockedUntil = 0, nil + return nil +} + +func (f *pinRepoFake) InsertEvent(context.Context, repository.CustomerSecurityEvent) error { + return nil +} + +func TestCustomerPin_LockIsPushedThroughFCM(t *testing.T) { + customer := uuid.New() + hash, err := bcrypt.GenerateFromPassword([]byte("482913"), bcrypt.MinCost) + require.NoError(t, err) + h := string(hash) + repo := &pinRepoFake{state: repository.CustomerPinState{CustomerID: customer, PinHash: &h}} + notifier := ¬ifierFake{} + p := NewCustomerPinProcessor(repo, nil, notifier) + now := time.Date(2026, 9, 30, 3, 0, 0, 0, time.UTC) + p.now = func() time.Time { return now } + ctx := context.Background() + + for i := 0; i < 4; i++ { + _ = p.VerifyPin(ctx, customer, "000000", PinActionPay, models.CustomerPinRequestInfo{}) + } + assert.Empty(t, notifier.pushes[customer], "no push before the PIN locks") + + err = p.VerifyPin(ctx, customer, "000000", PinActionPay, models.CustomerPinRequestInfo{}) + var pinErr *PinError + require.ErrorAs(t, err, &pinErr) + assert.Equal(t, PinErrLocked, pinErr.Code) + + // Attempts while locked do not push again. + _ = p.VerifyPin(ctx, customer, "482913", PinActionPay, models.CustomerPinRequestInfo{}) + + require.Len(t, notifier.pushes[customer], 1) + push := notifier.pushes[customer][0] + assert.Equal(t, "PIN terkunci", push.title) + assert.Equal(t, "PIN EnakPoint kamu terkunci sampai 30 Sep 2026 10:30 WIB karena salah dimasukkan 5 kali. Jika ini bukan kamu, segera reset PIN lewat aplikasi.", push.body) + assert.Equal(t, map[string]string{"type": NotificationTypePinLocked, "locked_until": "2026-09-30T03:30:00Z"}, push.data) +} diff --git a/internal/processor/customer_points_processor.go b/internal/processor/customer_points_processor.go index d65ef2b..a5a96aa 100644 --- a/internal/processor/customer_points_processor.go +++ b/internal/processor/customer_points_processor.go @@ -3,7 +3,6 @@ package processor import ( "context" "fmt" - "time" "apskel-pos-be/internal/models" "apskel-pos-be/internal/repository" @@ -12,217 +11,85 @@ import ( ) type CustomerPointsProcessor struct { - customerPointsRepo repository.CustomerPointsRepository - gameRepo *repository.GameRepository + walletQuery *WalletQueryProcessor + gameRepo *repository.GameRepository } -func NewCustomerPointsProcessor(customerPointsRepo repository.CustomerPointsRepository, gameRepo *repository.GameRepository) *CustomerPointsProcessor { +func NewCustomerPointsProcessor(walletQuery *WalletQueryProcessor, gameRepo *repository.GameRepository) *CustomerPointsProcessor { return &CustomerPointsProcessor{ - customerPointsRepo: customerPointsRepo, - gameRepo: gameRepo, + walletQuery: walletQuery, + gameRepo: gameRepo, } } -// Existing gamification methods - placeholder implementations -func (p *CustomerPointsProcessor) CreateCustomerPoints(ctx context.Context, req *models.CreateCustomerPointsRequest) (*models.CustomerPointsResponse, error) { - // TODO: Implement this method - return nil, fmt.Errorf("not implemented") -} - -func (p *CustomerPointsProcessor) GetCustomerPoints(ctx context.Context, id uuid.UUID) (*models.CustomerPointsResponse, error) { - // TODO: Implement this method - return nil, fmt.Errorf("not implemented") -} - -func (p *CustomerPointsProcessor) GetCustomerPointsByCustomerID(ctx context.Context, customerID uuid.UUID) (*models.CustomerPointsResponse, error) { - // TODO: Implement this method - return nil, fmt.Errorf("not implemented") -} - -func (p *CustomerPointsProcessor) ListCustomerPoints(ctx context.Context, query *models.ListCustomerPointsQuery) (*models.PaginatedCustomerPointsResponse, error) { - // Return empty paginated response for now - return &models.PaginatedCustomerPointsResponse{ - Data: []models.CustomerPointsResponse{}, - TotalCount: 0, - Page: 1, - Limit: 10, - TotalPages: 0, - }, nil -} - -func (p *CustomerPointsProcessor) UpdateCustomerPoints(ctx context.Context, id uuid.UUID, req *models.UpdateCustomerPointsRequest) (*models.CustomerPointsResponse, error) { - // TODO: Implement this method - return nil, fmt.Errorf("not implemented") -} - -func (p *CustomerPointsProcessor) DeleteCustomerPoints(ctx context.Context, id uuid.UUID) error { - // TODO: Implement this method - return fmt.Errorf("not implemented") -} - -func (p *CustomerPointsProcessor) AddPoints(ctx context.Context, customerID uuid.UUID, points int64) (*models.CustomerPointsResponse, error) { - // TODO: Implement this method - return nil, fmt.Errorf("not implemented") -} - -func (p *CustomerPointsProcessor) DeductPoints(ctx context.Context, customerID uuid.UUID, points int64) (*models.CustomerPointsResponse, error) { - // TODO: Implement this method - return nil, fmt.Errorf("not implemented") -} +// The three endpoints below are the customer app's balance screens. They read the +// EnakPoint & EnakCoin wallet; customer_points and customer_tokens are no longer used +// for balances (docs/prd-point-coin.md §9). func (p *CustomerPointsProcessor) GetCustomerTotalPointsAPI(ctx context.Context, customerID string) (*models.GetCustomerPointsResponse, error) { - // Get total points - totalPoints, err := p.customerPointsRepo.GetCustomerTotalPoints(ctx, customerID) + id, err := parseWalletCustomerID(customerID) if err != nil { - return nil, fmt.Errorf("failed to get customer total points: %w", err) + return nil, err } - - // Get points history (last 10 records) - pointsHistory, err := p.customerPointsRepo.GetCustomerPointsHistory(ctx, customerID, 10) + data, err := p.walletQuery.LegacyPoints(ctx, id) if err != nil { - return nil, fmt.Errorf("failed to get customer points history: %w", err) + return nil, fmt.Errorf("failed to get customer points: %w", err) } - - // Convert to response format - var historyItems []models.PointsHistoryItem - - for _, point := range pointsHistory { - historyItems = append(historyItems, models.PointsHistoryItem{ - ID: point.ID.String(), - Points: point.Balance, - Type: "BALANCE", - Description: "Points balance", - CreatedAt: point.CreatedAt, - }) - } - - var lastUpdated time.Time - if len(pointsHistory) > 0 { - lastUpdated = pointsHistory[0].CreatedAt - } - return &models.GetCustomerPointsResponse{ Status: "SUCCESS", Message: "Customer points retrieved successfully.", - Data: &models.GetCustomerPointsResponseData{ - TotalPoints: totalPoints, - PointsHistory: historyItems, - LastUpdated: lastUpdated, - }, + Data: data, }, nil } func (p *CustomerPointsProcessor) GetCustomerTotalTokensAPI(ctx context.Context, customerID string) (*models.GetCustomerTokensResponse, error) { - // Get total tokens - totalTokens, err := p.customerPointsRepo.GetCustomerTotalTokens(ctx, customerID) + id, err := parseWalletCustomerID(customerID) if err != nil { - return nil, fmt.Errorf("failed to get customer total tokens: %w", err) + return nil, err } - - // Get tokens history (last 10 records) - tokensHistory, err := p.customerPointsRepo.GetCustomerTokensHistory(ctx, customerID, 10) + data, err := p.walletQuery.LegacyTokens(ctx, id) if err != nil { - return nil, fmt.Errorf("failed to get customer tokens history: %w", err) + return nil, fmt.Errorf("failed to get customer tokens: %w", err) } - - // Convert to response format - var historyItems []models.TokensHistoryItem - - for _, token := range tokensHistory { - historyItems = append(historyItems, models.TokensHistoryItem{ - ID: token.ID.String(), - Tokens: token.Balance, - Type: string(token.TokenType), - Description: "Tokens balance", - CreatedAt: token.CreatedAt, - }) - } - - var lastUpdated time.Time - if len(tokensHistory) > 0 { - lastUpdated = tokensHistory[0].CreatedAt - } - return &models.GetCustomerTokensResponse{ Status: "SUCCESS", Message: "Customer tokens retrieved successfully.", - Data: &models.GetCustomerTokensResponseData{ - TotalTokens: totalTokens, - TokensHistory: historyItems, - LastUpdated: lastUpdated, - }, + Data: data, }, nil } func (p *CustomerPointsProcessor) GetCustomerWalletAPI(ctx context.Context, customerID string) (*models.GetCustomerWalletResponse, error) { - // Get total points - totalPoints, err := p.customerPointsRepo.GetCustomerTotalPoints(ctx, customerID) + id, err := parseWalletCustomerID(customerID) if err != nil { - return nil, fmt.Errorf("failed to get customer total points: %w", err) + return nil, err } - - // Get total tokens - totalTokens, err := p.customerPointsRepo.GetCustomerTotalTokens(ctx, customerID) + data, err := p.walletQuery.Summary(ctx, id) if err != nil { - return nil, fmt.Errorf("failed to get customer total tokens: %w", err) + return nil, fmt.Errorf("failed to get customer wallet: %w", err) } - - // Get points history (last 5 records) - pointsHistory, err := p.customerPointsRepo.GetCustomerPointsHistory(ctx, customerID, 5) - if err != nil { - return nil, fmt.Errorf("failed to get customer points history: %w", err) - } - - // Get tokens history (last 5 records) - tokensHistory, err := p.customerPointsRepo.GetCustomerTokensHistory(ctx, customerID, 5) - if err != nil { - return nil, fmt.Errorf("failed to get customer tokens history: %w", err) - } - - // Convert to response format - var pointsHistoryItems []models.PointsHistoryItem - var tokensHistoryItems []models.TokensHistoryItem - var lastUpdated time.Time - - for _, point := range pointsHistory { - pointsHistoryItems = append(pointsHistoryItems, models.PointsHistoryItem{ - ID: point.ID.String(), - Points: point.Balance, - Type: "BALANCE", - Description: "Points balance", - CreatedAt: point.CreatedAt, - }) - if point.CreatedAt.After(lastUpdated) { - lastUpdated = point.CreatedAt - } - } - - for _, token := range tokensHistory { - tokensHistoryItems = append(tokensHistoryItems, models.TokensHistoryItem{ - ID: token.ID.String(), - Tokens: token.Balance, - Type: string(token.TokenType), - Description: "Tokens balance", - CreatedAt: token.CreatedAt, - }) - if token.CreatedAt.After(lastUpdated) { - lastUpdated = token.CreatedAt - } - } - return &models.GetCustomerWalletResponse{ Status: "SUCCESS", Message: "Customer wallet retrieved successfully.", - Data: &models.GetCustomerWalletResponseData{ - TotalPoints: totalPoints, - TotalTokens: totalTokens, - PointsHistory: pointsHistoryItems, - TokensHistory: tokensHistoryItems, - LastUpdated: lastUpdated, - }, + Data: data, }, nil } +func (p *CustomerPointsProcessor) GetCustomerWalletTransactionsAPI(ctx context.Context, customerID string, query models.ListCustomerWalletTransactionsQuery) (*models.PaginatedResponse[models.CustomerWalletTransaction], error) { + id, err := parseWalletCustomerID(customerID) + if err != nil { + return nil, err + } + return p.walletQuery.Transactions(ctx, id, query) +} + +func parseWalletCustomerID(customerID string) (uuid.UUID, error) { + id, err := uuid.Parse(customerID) + if err != nil { + return uuid.Nil, fmt.Errorf("%w: invalid customer id", ErrInvalidWalletQuery) + } + return id, nil +} + // GetCustomerGamesAPI gets active SPIN games for customers func (p *CustomerPointsProcessor) GetCustomerGamesAPI(ctx context.Context) (*models.GetCustomerGamesResponse, error) { // Get active SPIN games @@ -310,3 +177,11 @@ func (p *CustomerPointsProcessor) GetFerrisWheelGameAPI(ctx context.Context) (*m }, }, nil } + +func (p *CustomerPointsProcessor) GetCustomerWalletExpiringAPI(ctx context.Context, customerID string) (*models.CustomerWalletExpiringList, error) { + id, err := parseWalletCustomerID(customerID) + if err != nil { + return nil, err + } + return p.walletQuery.Expiring(ctx, id) +} diff --git a/internal/processor/customer_tokens_processor.go b/internal/processor/customer_tokens_processor.go deleted file mode 100644 index f66e693..0000000 --- a/internal/processor/customer_tokens_processor.go +++ /dev/null @@ -1,198 +0,0 @@ -package processor - -import ( - "apskel-pos-be/internal/entities" - "apskel-pos-be/internal/mappers" - "apskel-pos-be/internal/models" - "apskel-pos-be/internal/repository" - "context" - "errors" - "fmt" - - "github.com/google/uuid" -) - -type CustomerTokensProcessor struct { - customerTokensRepo *repository.CustomerTokensRepository -} - -func NewCustomerTokensProcessor(customerTokensRepo *repository.CustomerTokensRepository) *CustomerTokensProcessor { - return &CustomerTokensProcessor{ - customerTokensRepo: customerTokensRepo, - } -} - -// CreateCustomerTokens creates a new customer tokens record -func (p *CustomerTokensProcessor) CreateCustomerTokens(ctx context.Context, req *models.CreateCustomerTokensRequest) (*models.CustomerTokensResponse, error) { - // Convert request to entity - customerTokens := mappers.ToCustomerTokensEntity(req) - - // Create customer tokens - err := p.customerTokensRepo.Create(ctx, customerTokens) - if err != nil { - return nil, fmt.Errorf("failed to create customer tokens: %w", err) - } - - return mappers.ToCustomerTokensResponse(customerTokens), nil -} - -// GetCustomerTokens retrieves customer tokens by ID -func (p *CustomerTokensProcessor) GetCustomerTokens(ctx context.Context, id uuid.UUID) (*models.CustomerTokensResponse, error) { - customerTokens, err := p.customerTokensRepo.GetByID(ctx, id) - if err != nil { - return nil, fmt.Errorf("customer tokens not found: %w", err) - } - - return mappers.ToCustomerTokensResponse(customerTokens), nil -} - -// GetCustomerTokensByCustomerIDAndType retrieves customer tokens by customer ID and token type -func (p *CustomerTokensProcessor) GetCustomerTokensByCustomerIDAndType(ctx context.Context, customerID uuid.UUID, tokenType string) (*models.CustomerTokensResponse, error) { - customerTokens, err := p.customerTokensRepo.EnsureCustomerTokens(ctx, customerID, entities.TokenType(tokenType)) - if err != nil { - return nil, fmt.Errorf("failed to get customer tokens: %w", err) - } - - return mappers.ToCustomerTokensResponse(customerTokens), nil -} - -// ListCustomerTokens retrieves customer tokens with pagination and filtering -func (p *CustomerTokensProcessor) ListCustomerTokens(ctx context.Context, query *models.ListCustomerTokensQuery) (*models.PaginatedResponse[models.CustomerTokensResponse], error) { - // Set default values - if query.Page <= 0 { - query.Page = 1 - } - if query.Limit <= 0 { - query.Limit = 10 - } - if query.Limit > 100 { - query.Limit = 100 - } - - offset := (query.Page - 1) * query.Limit - - // Get customer tokens from repository - customerTokens, total, err := p.customerTokensRepo.List( - ctx, - offset, - query.Limit, - query.Search, - query.TokenType, - query.SortBy, - query.SortOrder, - ) - if err != nil { - return nil, fmt.Errorf("failed to list customer tokens: %w", err) - } - - // Convert to responses - responses := mappers.ToCustomerTokensResponses(customerTokens) - - // Calculate pagination info - totalPages := int((total + int64(query.Limit) - 1) / int64(query.Limit)) - - return &models.PaginatedResponse[models.CustomerTokensResponse]{ - Data: responses, - Pagination: models.Pagination{ - Page: query.Page, - Limit: query.Limit, - Total: total, - TotalPages: totalPages, - }, - }, nil -} - -// UpdateCustomerTokens updates an existing customer tokens record -func (p *CustomerTokensProcessor) UpdateCustomerTokens(ctx context.Context, id uuid.UUID, req *models.UpdateCustomerTokensRequest) (*models.CustomerTokensResponse, error) { - // Get existing customer tokens - customerTokens, err := p.customerTokensRepo.GetByID(ctx, id) - if err != nil { - return nil, fmt.Errorf("customer tokens not found: %w", err) - } - - // Update customer tokens fields - mappers.UpdateCustomerTokensEntity(customerTokens, req) - - // Save updated customer tokens - err = p.customerTokensRepo.Update(ctx, customerTokens) - if err != nil { - return nil, fmt.Errorf("failed to update customer tokens: %w", err) - } - - return mappers.ToCustomerTokensResponse(customerTokens), nil -} - -// DeleteCustomerTokens deletes a customer tokens record -func (p *CustomerTokensProcessor) DeleteCustomerTokens(ctx context.Context, id uuid.UUID) error { - // Get existing customer tokens - _, err := p.customerTokensRepo.GetByID(ctx, id) - if err != nil { - return fmt.Errorf("customer tokens not found: %w", err) - } - - // Delete customer tokens - err = p.customerTokensRepo.Delete(ctx, id) - if err != nil { - return fmt.Errorf("failed to delete customer tokens: %w", err) - } - - return nil -} - -// AddTokens adds tokens to a customer's balance -func (p *CustomerTokensProcessor) AddTokens(ctx context.Context, customerID uuid.UUID, tokenType string, tokens int64) (*models.CustomerTokensResponse, error) { - if tokens <= 0 { - return nil, errors.New("tokens must be greater than 0") - } - - // Ensure customer tokens record exists - _, err := p.customerTokensRepo.EnsureCustomerTokens(ctx, customerID, entities.TokenType(tokenType)) - if err != nil { - return nil, fmt.Errorf("failed to ensure customer tokens: %w", err) - } - - // Add tokens - err = p.customerTokensRepo.AddTokens(ctx, customerID, entities.TokenType(tokenType), tokens) - if err != nil { - return nil, fmt.Errorf("failed to add tokens: %w", err) - } - - // Get updated customer tokens - customerTokens, err := p.customerTokensRepo.GetByCustomerIDAndType(ctx, customerID, entities.TokenType(tokenType)) - if err != nil { - return nil, fmt.Errorf("failed to get updated customer tokens: %w", err) - } - - return mappers.ToCustomerTokensResponse(customerTokens), nil -} - -// DeductTokens deducts tokens from a customer's balance -func (p *CustomerTokensProcessor) DeductTokens(ctx context.Context, customerID uuid.UUID, tokenType string, tokens int64) (*models.CustomerTokensResponse, error) { - if tokens <= 0 { - return nil, errors.New("tokens must be greater than 0") - } - - // Get current customer tokens - customerTokens, err := p.customerTokensRepo.GetByCustomerIDAndType(ctx, customerID, entities.TokenType(tokenType)) - if err != nil { - return nil, fmt.Errorf("customer tokens not found: %w", err) - } - - if customerTokens.Balance < tokens { - return nil, errors.New("insufficient tokens balance") - } - - // Deduct tokens - err = p.customerTokensRepo.DeductTokens(ctx, customerID, entities.TokenType(tokenType), tokens) - if err != nil { - return nil, fmt.Errorf("failed to deduct tokens: %w", err) - } - - // Get updated customer tokens - updatedCustomerTokens, err := p.customerTokensRepo.GetByCustomerIDAndType(ctx, customerID, entities.TokenType(tokenType)) - if err != nil { - return nil, fmt.Errorf("failed to get updated customer tokens: %w", err) - } - - return mappers.ToCustomerTokensResponse(updatedCustomerTokens), nil -} diff --git a/internal/processor/earning_calculator.go b/internal/processor/earning_calculator.go new file mode 100644 index 0000000..28825c4 --- /dev/null +++ b/internal/processor/earning_calculator.go @@ -0,0 +1,85 @@ +package processor + +import ( + "math" + + "apskel-pos-be/internal/entities" + "apskel-pos-be/internal/models" +) + +// EarningLine is what an order earns in one currency, and the settings that produced +// it. The settings are kept so the ledger row can freeze them: a later change of +// setting must not change what an earning meant, and a reversal is computed with the +// same numbers (docs/prd-point-coin.md F3). +type EarningLine struct { + Amount int64 + Settings models.LoyaltyEarnSettings + // True when max_per_order cut the amount down. + Capped bool +} + +// EarningResult is what an order earns. +type EarningResult struct { + // subtotal − discount − the part paid with EnakPoint, in rupiah, never negative. + // Tax and anything else added on top of the subtotal are not part of it (Q1). + Basis float64 + Point EarningLine + Coin EarningLine +} + +// Metadata is the snapshot stored on the currency's EARN ledger row. +func (r EarningResult) Metadata(line EarningLine) entities.Metadata { + m := entities.Metadata{ + "basis": r.Basis, + "earn_per_amount": line.Settings.EarnPerAmount, + "earn_value": line.Settings.EarnValue, + "min_order_amount": line.Settings.MinOrderAmount, + "capped": line.Capped, + } + if line.Settings.MaxPerOrder != nil { + m["max_per_order"] = *line.Settings.MaxPerOrder + } + return m +} + +// CalculateEarning applies the earning formula of docs/prd-point-coin.md F1: +// +// basis = subtotal − discount_amount − paid with EnakPoint +// amount = 0 if basis < min_order_amount +// amount = floor(basis / earn_per_amount) × earn_value +// 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 +// floor never lands one short on a value like 87500.00 that float64 cannot hold +// exactly. It has no side effects. +func CalculateEarning(order *entities.Order, pointPaidAmount float64, settings models.OutletLoyaltySettings) EarningResult { + basisCents := toCents(order.Subtotal) - toCents(order.DiscountAmount) - toCents(pointPaidAmount) + if basisCents < 0 { + basisCents = 0 + } + return EarningResult{ + Basis: float64(basisCents) / 100, + Point: earnLine(basisCents, settings.Point), + Coin: earnLine(basisCents, settings.Coin), + } +} + +func earnLine(basisCents int64, s models.LoyaltyEarnSettings) EarningLine { + line := EarningLine{Settings: s} + if !s.Enabled || s.EarnPerAmount <= 0 || s.EarnValue <= 0 { + return line + } + if basisCents < s.MinOrderAmount*100 { + return line + } + line.Amount = basisCents / (s.EarnPerAmount * 100) * s.EarnValue + if s.MaxPerOrder != nil && line.Amount > *s.MaxPerOrder { + line.Amount = *s.MaxPerOrder + line.Capped = true + } + return line +} + +func toCents(rupiah float64) int64 { + return int64(math.Round(rupiah * 100)) +} diff --git a/internal/processor/earning_calculator_test.go b/internal/processor/earning_calculator_test.go new file mode 100644 index 0000000..b49efab --- /dev/null +++ b/internal/processor/earning_calculator_test.go @@ -0,0 +1,121 @@ +package processor + +import ( + "testing" + + "github.com/stretchr/testify/assert" + + "apskel-pos-be/internal/entities" + "apskel-pos-be/internal/models" +) + +// 1 EnakPoint per Rp 100 and 1 EnakCoin per Rp 25.000, as in the F1 example. +func prdEarningSettings() models.OutletLoyaltySettings { + return models.OutletLoyaltySettings{ + Point: models.LoyaltyEarnSettings{Enabled: true, EarnPerAmount: 100, EarnValue: 1}, + Coin: models.LoyaltyEarnSettings{Enabled: true, EarnPerAmount: 25000, EarnValue: 1}, + } +} + +func TestCalculateEarning_PRDExample(t *testing.T) { + // Subtotal after discount Rp 87.500, paid in full in cash. + order := &entities.Order{Subtotal: 97500, DiscountAmount: 10000, TaxAmount: 9625, TotalAmount: 97125} + + got := CalculateEarning(order, 0, prdEarningSettings()) + assert.Equal(t, 87500.0, got.Basis) + assert.Equal(t, int64(875), got.Point.Amount) + assert.Equal(t, int64(3), got.Coin.Amount) + + // Rp 20.000 of it paid with EnakPoint earns nothing. + got = CalculateEarning(order, 20000, prdEarningSettings()) + assert.Equal(t, 67500.0, got.Basis) + assert.Equal(t, int64(675), got.Point.Amount) + assert.Equal(t, int64(2), got.Coin.Amount) +} + +func TestCalculateEarning_TaxIsNotPartOfTheBasis(t *testing.T) { + withoutTax := &entities.Order{Subtotal: 50000} + withTax := &entities.Order{Subtotal: 50000, TaxAmount: 5500, TotalAmount: 55500} + assert.Equal(t, CalculateEarning(withoutTax, 0, prdEarningSettings()), CalculateEarning(withTax, 0, prdEarningSettings())) + assert.Equal(t, int64(500), CalculateEarning(withTax, 0, prdEarningSettings()).Point.Amount) +} + +func TestCalculateEarning_BelowMinimum(t *testing.T) { + s := prdEarningSettings() + s.Point.MinOrderAmount = 50000 + + assert.Equal(t, int64(0), CalculateEarning(&entities.Order{Subtotal: 49999}, 0, s).Point.Amount) + assert.Equal(t, int64(500), CalculateEarning(&entities.Order{Subtotal: 50000}, 0, s).Point.Amount, "the minimum itself earns") + // The minimum applies to the basis, after discount and EnakPoint. + assert.Equal(t, int64(0), CalculateEarning(&entities.Order{Subtotal: 60000}, 15000, s).Point.Amount) + // Coin has its own minimum. + assert.Equal(t, int64(1), CalculateEarning(&entities.Order{Subtotal: 49999}, 0, s).Coin.Amount) +} + +func TestCalculateEarning_MaxPerOrder(t *testing.T) { + s := prdEarningSettings() + max := int64(300) + s.Point.MaxPerOrder = &max + + got := CalculateEarning(&entities.Order{Subtotal: 87500}, 0, s) + assert.Equal(t, int64(300), got.Point.Amount) + assert.True(t, got.Point.Capped) + assert.Equal(t, int64(300), got.Metadata(got.Point)["max_per_order"]) + + got = CalculateEarning(&entities.Order{Subtotal: 20000}, 0, s) + assert.Equal(t, int64(200), got.Point.Amount) + assert.False(t, got.Point.Capped) + + zero := int64(0) + s.Point.MaxPerOrder = &zero + assert.Equal(t, int64(0), CalculateEarning(&entities.Order{Subtotal: 87500}, 0, s).Point.Amount) +} + +func TestCalculateEarning_DisabledEarnsNothing(t *testing.T) { + s := prdEarningSettings() + s.Point.Enabled = false + got := CalculateEarning(&entities.Order{Subtotal: 87500}, 0, s) + assert.Equal(t, int64(0), got.Point.Amount) + assert.Equal(t, int64(3), got.Coin.Amount, "each currency is switched on its own") + + s.Coin.Enabled = false + got = CalculateEarning(&entities.Order{Subtotal: 87500}, 0, s) + assert.Equal(t, int64(0), got.Coin.Amount) + assert.Equal(t, 87500.0, got.Basis, "the basis is still reported") + + // The defaults of an outlet that never set anything earn nothing. + var defaults models.OutletLoyaltySettings + loadLoyaltyFields(outletLoyaltyFields(&defaults), nil, "test") + got = CalculateEarning(&entities.Order{Subtotal: 87500}, 0, defaults) + assert.Equal(t, int64(0), got.Point.Amount) + assert.Equal(t, int64(0), got.Coin.Amount) +} + +func TestCalculateEarning_EdgeCases(t *testing.T) { + s := prdEarningSettings() + + // floor, not round. + assert.Equal(t, int64(875), CalculateEarning(&entities.Order{Subtotal: 87599.99}, 0, s).Point.Amount) + // Values float64 cannot hold exactly do not lose a point: computed in float64 this + // basis divides to 4956.999…, which a naive floor turns into 4956. + per250 := prdEarningSettings() + per250.Point.EarnPerAmount = 250 + assert.Equal(t, int64(4957), CalculateEarning(&entities.Order{Subtotal: 1240155.48, DiscountAmount: 749.11}, 156.37, per250).Point.Amount) + // Paying more with EnakPoint than the basis leaves nothing, never a negative amount. + got := CalculateEarning(&entities.Order{Subtotal: 10000}, 15000, s) + assert.Equal(t, 0.0, got.Basis) + assert.Equal(t, int64(0), got.Point.Amount) + // earn_value multiplies. + s.Point.EarnValue = 5 + assert.Equal(t, int64(4375), CalculateEarning(&entities.Order{Subtotal: 87500}, 0, s).Point.Amount) + // A zero earn_value earns nothing even when enabled. + s.Point.EarnValue = 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{ + "basis": 87500.0, "earn_per_amount": int64(100), "earn_value": int64(1), "min_order_amount": int64(0), "capped": false, + }, got.Metadata(got.Point)) +} diff --git a/internal/processor/earning_processor.go b/internal/processor/earning_processor.go new file mode 100644 index 0000000..b820ea1 --- /dev/null +++ b/internal/processor/earning_processor.go @@ -0,0 +1,217 @@ +package processor + +import ( + "context" + "fmt" + "time" + + "github.com/google/uuid" + + "apskel-pos-be/internal/constants" + "apskel-pos-be/internal/entities" + "apskel-pos-be/internal/logger" + "apskel-pos-be/internal/models" + "apskel-pos-be/internal/repository" +) + +// Why an order earned nothing. +const ( + EarningSkipNotPaid = "NOT_PAID" + EarningSkipVoid = "VOID" + EarningSkipNoCustomer = "NO_CUSTOMER" + EarningSkipDefaultCustomer = "DEFAULT_CUSTOMER" + EarningSkipInactiveCustomer = "INACTIVE_CUSTOMER" + EarningSkipNothingToEarn = "NOTHING_TO_EARN" +) + +// EarningOutcome is what earning did for one order. +type EarningOutcome struct { + Points int64 + Coins int64 + // Set when the order earned nothing, to say why. + Skipped string +} + +type outletSettingsReader interface { + Outlet(ctx context.Context, outletID uuid.UUID) (*models.OutletLoyaltySettings, error) +} + +// earningSettingsReader gives the outlet's earning settings and the organization's +// expiry. LoyaltySettingsProcessor is one. +type earningSettingsReader interface { + outletSettingsReader + organizationSettingsReader +} + +// EarningProcessor credits EnakPoint and EnakCoin for paid orders +// (docs/prd-point-coin.md F3). +type EarningProcessor struct { + orders repository.EarningRepository + settings earningSettingsReader + now func() time.Time + wallet *WalletProcessor + tx TxRunner +} + +func NewEarningProcessor(orders repository.EarningRepository, settings earningSettingsReader, wallet *WalletProcessor, tx TxRunner) *EarningProcessor { + return &EarningProcessor{orders: orders, settings: settings, wallet: wallet, tx: tx, now: time.Now} +} + +// OnOrderPaid is called once an order has become fully paid and the payment has +// committed. It never fails the caller: a failed earning is logged and picked up later +// by EarnMissing, and the idempotency keys make that retry safe. +func (p *EarningProcessor) OnOrderPaid(ctx context.Context, orderID uuid.UUID) { + defer func() { + if r := recover(); r != nil { + logger.NonContext.Error(fmt.Sprintf("Earning for order %s panicked; it will be retried", orderID), fmt.Errorf("%v", r)) + } + }() + if _, err := p.EarnForOrder(ctx, orderID); err != nil { + logger.NonContext.Error(fmt.Sprintf("Earning for order %s failed; it will be retried", orderID), err) + } +} + +// EarnForOrder credits what a paid order earns. Calling it again for the same order +// credits nothing more. +func (p *EarningProcessor) EarnForOrder(ctx context.Context, orderID uuid.UUID) (*EarningOutcome, error) { + order, err := p.orders.GetOrderForEarning(ctx, orderID) + if err != nil { + return nil, err + } + if skip := earningSkipReason(order); skip != "" { + return &EarningOutcome{Skipped: skip}, nil + } + + settings, err := p.settings.Outlet(ctx, order.OutletID) + if err != nil { + return nil, err + } + pointPaid, err := p.orders.PointPaidAmount(ctx, orderID) + if err != nil { + return nil, err + } + result := CalculateEarning(&entities.Order{Subtotal: order.Subtotal, DiscountAmount: order.DiscountAmount}, pointPaid, *settings) + if result.Point.Amount == 0 && result.Coin.Amount == 0 { + return &EarningOutcome{Skipped: EarningSkipNothingToEarn}, nil + } + + orgSettings, err := p.settings.Organization(ctx, order.OrganizationID) + if err != nil { + return nil, err + } + receivedAt := p.now() + + outcome := &EarningOutcome{} + err = p.tx.WithTransaction(ctx, func(ctx context.Context) error { + for _, c := range []struct { + currency string + line EarningLine + total *int64 + }{ + {constants.WalletCurrencyPoint, result.Point, &outcome.Points}, + {constants.WalletCurrencyCoin, result.Coin, &outcome.Coins}, + } { + if c.line.Amount == 0 { + continue + } + outletID := order.OutletID + res, err := p.wallet.Credit(ctx, WalletCreditInput{ + WalletEntry: WalletEntry{ + CustomerID: *order.CustomerID, + Currency: c.currency, + Type: constants.WalletTxTypeEarn, + Amount: c.line.Amount, + ReferenceType: constants.WalletRefTypeOrder, + ReferenceID: order.ID, + OutletID: &outletID, + Description: earningDescription(order), + Metadata: result.Metadata(c.line), + IdempotencyKey: fmt.Sprintf("earn:%s:%s", order.ID, c.currency), + }, + Lots: []WalletLotInput{{ + Amount: c.line.Amount, + ExpiresAt: ComputeExpiry(ExpirySettings(orgSettings, c.currency), receivedAt), + }}, + }) + if err != nil { + return fmt.Errorf("crediting %s: %w", c.currency, err) + } + *c.total = res.Transaction.Amount + } + return nil + }) + if err != nil { + return nil, err + } + return outcome, nil +} + +// EarnMissing is the safety net behind OnOrderPaid: it looks for orders paid since the +// given time that should have earned and have no EARN row, and earns for them. It +// returns how many orders it looked at and how many now earned. One order failing does +// not stop the others. +func (p *EarningProcessor) EarnMissing(ctx context.Context, since time.Time, maxOrders int) (checked, earned int, err error) { + const page = 200 + var after *repository.EarningCursor + for checked < maxOrders { + batch, err := p.orders.ListPaidOrdersWithoutEarning(ctx, since, after, page) + if err != nil { + return checked, earned, err + } + if len(batch) == 0 { + break + } + for _, candidate := range batch { + checked++ + outcome, err := p.EarnForOrder(ctx, candidate.ID) + if err != nil { + logger.NonContext.Error(fmt.Sprintf("Earning retry for order %s failed", candidate.ID), err) + continue + } + if outcome.Skipped == "" { + earned++ + } + } + last := batch[len(batch)-1] + after = &last + } + return checked, earned, nil +} + +func earningSkipReason(order *repository.EarningOrder) string { + switch { + case order.PaymentStatus != string(entities.PaymentStatusCompleted): + return EarningSkipNotPaid + case order.IsVoid: + return EarningSkipVoid + case order.CustomerID == nil || order.CustomerIsDefault == nil: + return EarningSkipNoCustomer + case *order.CustomerIsDefault: + return EarningSkipDefaultCustomer + case order.CustomerIsActive == nil || !*order.CustomerIsActive: + return EarningSkipInactiveCustomer + } + return "" +} + +func earningDescription(order *repository.EarningOrder) string { + description := "Belanja #" + order.OrderNumber + if order.OutletName != "" { + description += " di " + order.OutletName + } + return truncateRunes(description, walletDescriptionLimit) +} + +// EarnedByOrders returns what each order earned, as written in its EARN rows, for the +// order screen and the receipt (F3). Orders that earned nothing are absent. +func (p *EarningProcessor) EarnedByOrders(ctx context.Context, orderIDs []uuid.UUID) (map[uuid.UUID]OrderEarned, error) { + rows, err := p.orders.EarnedByOrders(ctx, orderIDs) + if err != nil { + return nil, err + } + out := make(map[uuid.UUID]OrderEarned, len(rows)) + for id, byCurrency := range rows { + out[id] = OrderEarned{Points: byCurrency[constants.WalletCurrencyPoint], Coins: byCurrency[constants.WalletCurrencyCoin]} + } + return out, nil +} diff --git a/internal/processor/earning_processor_db_test.go b/internal/processor/earning_processor_db_test.go new file mode 100644 index 0000000..7fad218 --- /dev/null +++ b/internal/processor/earning_processor_db_test.go @@ -0,0 +1,233 @@ +package processor + +import ( + "context" + "errors" + "os" + "sync" + "testing" + "time" + + "github.com/google/uuid" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "gorm.io/driver/postgres" + "gorm.io/gorm" + "gorm.io/gorm/logger" + + "apskel-pos-be/internal/models" + "apskel-pos-be/internal/repository" +) + +// failingSettings fails for the outlet settings until healed, to stand in for the +// database being unreachable right after a payment. +type failingSettings struct { + real earningSettingsReader + mu sync.Mutex + fail bool +} + +func (f *failingSettings) Outlet(ctx context.Context, outletID uuid.UUID) (*models.OutletLoyaltySettings, error) { + f.mu.Lock() + fail := f.fail + f.mu.Unlock() + if fail { + return nil, errors.New("connection refused") + } + return f.real.Outlet(ctx, outletID) +} + +// Needs TEST_DATABASE_URL pointing at a migrated database; see +// internal/repository/wallet_repository_test.go. +func TestEarningProcessor_AgainstPostgres(t *testing.T) { + dsn := os.Getenv("TEST_DATABASE_URL") + if dsn == "" { + t.Skip("TEST_DATABASE_URL not set") + } + db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{Logger: logger.Default.LogMode(logger.Silent)}) + require.NoError(t, err) + ctx := context.Background() + + org, user := uuid.New(), uuid.New() + earningOutlet, quietOutlet := uuid.New(), uuid.New() + regular, inactive := uuid.New(), uuid.New() + var walkIn uuid.UUID + var customers []uuid.UUID + exec := func(q string, args ...any) { + t.Helper() + require.NoError(t, db.Exec(q, args...).Error) + } + exec(`INSERT INTO organizations (id, name, plan_type) VALUES (?, 'earning test', 'basic')`, org) + exec(`INSERT INTO users (id, organization_id, name, email, password_hash, role) VALUES (?, ?, 'Kasir', ?, 'x', 'cashier')`, user, org, user.String()+"@test") + exec(`INSERT INTO outlets (id, organization_id, name) VALUES (?, ?, 'Kemang'), (?, ?, 'Tanpa Poin')`, earningOutlet, org, quietOutlet, org) + exec(`INSERT INTO customers (id, organization_id, name, is_default, is_active) VALUES + (?, ?, 'Budi', false, true), (?, ?, 'Nonaktif', false, false)`, regular, org, inactive, org) + // Creating the organization created its walk-in customer (trigger_create_default_customer). + var walkInID string + require.NoError(t, db.Raw(`SELECT id::text FROM customers WHERE organization_id = ? AND is_default`, org).Scan(&walkInID).Error) + walkIn = uuid.MustParse(walkInID) + customers = []uuid.UUID{regular, walkIn, inactive} + t.Cleanup(func() { + db.Exec(`DELETE FROM wallet_lot_allocations WHERE lot_id IN (SELECT id FROM wallet_lots WHERE customer_id IN ?)`, customers) + db.Exec(`DELETE FROM wallet_lots WHERE customer_id IN ?`, customers) + db.Exec(`DELETE FROM wallet_transactions WHERE customer_id IN ?`, customers) + db.Exec(`DELETE FROM customer_wallets WHERE customer_id IN ?`, customers) + db.Exec(`DELETE FROM orders WHERE organization_id = ?`, org) + db.Exec(`DELETE FROM loyalty_setting_changes WHERE organization_id = ?`, org) + db.Exec(`DELETE FROM outlet_settings WHERE outlet_id IN ?`, []uuid.UUID{earningOutlet, quietOutlet}) + db.Exec(`DELETE FROM customers WHERE id IN ?`, customers) + db.Exec(`DELETE FROM outlets WHERE id IN ?`, []uuid.UUID{earningOutlet, quietOutlet}) + db.Exec(`DELETE FROM users WHERE id = ?`, user) + db.Exec(`DELETE FROM organizations WHERE id = ?`, org) + }) + + txm := repository.NewTxManager(db) + settingsProcessor := NewLoyaltySettingsProcessor(repository.NewLoyaltySettingsRepository(db), txm) + outletSettings, err := settingsProcessor.Outlet(ctx, earningOutlet) + require.NoError(t, err) + outletSettings.Point.Enabled = true + outletSettings.Coin.Enabled = true + _, err = settingsProcessor.UpdateOutlet(ctx, org, earningOutlet, user, *outletSettings) + require.NoError(t, err) + + settings := &failingSettings{real: settingsProcessor} + earning := NewEarningProcessor(repository.NewEarningRepository(db), settings, NewWalletProcessor(repository.NewWalletRepository(db)), txm) + + orderNo := 0 + newOrder := func(outlet uuid.UUID, customer *uuid.UUID, paymentStatus string, isVoid bool, subtotal, discount float64) uuid.UUID { + t.Helper() + orderNo++ + id := uuid.New() + exec(`INSERT INTO orders (id, organization_id, outlet_id, user_id, customer_id, order_number, order_type, + subtotal, discount_amount, tax_amount, total_amount, payment_status, is_void) + VALUES (?, ?, ?, ?, ?, ?, 'dine_in', ?, ?, 0, ?, ?, ?)`, + id, org, outlet, user, customer, id.String()[:8]+"-"+string(rune('A'+orderNo)), subtotal, discount, subtotal-discount, paymentStatus, isVoid) + return id + } + earnRows := func(orderID uuid.UUID) map[string]int64 { + t.Helper() + var rows []struct { + Currency string + Amount int64 + } + require.NoError(t, db.Raw(`SELECT currency, amount FROM wallet_transactions WHERE reference_id = ? AND type = 'EARN'`, orderID).Scan(&rows).Error) + out := map[string]int64{} + for _, r := range rows { + out[r.Currency] += r.Amount + } + return out + } + + // Paid in full: the PRD example, 875 EnakPoint and 3 EnakCoin. + paid := newOrder(earningOutlet, ®ular, "completed", false, 97500, 10000) + earning.OnOrderPaid(ctx, paid) + assert.Equal(t, map[string]int64{"POINT": 875, "COIN": 3}, earnRows(paid)) + + var row struct { + Description string + Metadata string + OutletID string + } + require.NoError(t, db.Raw(`SELECT description, metadata::text AS metadata, outlet_id::text AS outlet_id FROM wallet_transactions + WHERE reference_id = ? AND currency = 'POINT'`, paid).Scan(&row).Error) + assert.Contains(t, row.Description, "di Kemang") + assert.Contains(t, row.Metadata, `"earn_per_amount": 100`, "the settings used are frozen on the row") + assert.Contains(t, row.Metadata, `"basis": 87500`) + assert.Equal(t, earningOutlet.String(), row.OutletID) + + // Called again, and five times at once, it is still one earning. + var wg sync.WaitGroup + for i := 0; i < 5; i++ { + wg.Add(1) + go func() { defer wg.Done(); earning.OnOrderPaid(ctx, paid) }() + } + wg.Wait() + outcome, err := earning.EarnForOrder(ctx, paid) + require.NoError(t, err) + assert.Equal(t, int64(875), outcome.Points, "a repeat reports the first earning") + assert.Equal(t, map[string]int64{"POINT": 875, "COIN": 3}, earnRows(paid)) + + // A self-order goes through the same payment path and the same rules. + selfOrder := newOrder(earningOutlet, ®ular, "completed", false, 25000, 0) + earning.OnOrderPaid(ctx, selfOrder) + assert.Equal(t, map[string]int64{"POINT": 250, "COIN": 1}, earnRows(selfOrder)) + + // A split bill earns once, on the payment that settles it: while partial, nothing. + split := newOrder(earningOutlet, ®ular, "partial", false, 60000, 0) + earning.OnOrderPaid(ctx, split) + assert.Empty(t, earnRows(split)) + exec(`UPDATE orders SET payment_status = 'completed' WHERE id = ?`, split) + earning.OnOrderPaid(ctx, split) + assert.Equal(t, map[string]int64{"POINT": 600, "COIN": 2}, earnRows(split)) + + // Orders that must not earn. + for name, c := range map[string]struct { + id uuid.UUID + skip string + }{ + "walk-in customer": {newOrder(earningOutlet, &walkIn, "completed", false, 50000, 0), EarningSkipDefaultCustomer}, + "inactive customer": {newOrder(earningOutlet, &inactive, "completed", false, 50000, 0), EarningSkipInactiveCustomer}, + "no customer": {newOrder(earningOutlet, nil, "completed", false, 50000, 0), EarningSkipNoCustomer}, + "void": {newOrder(earningOutlet, ®ular, "completed", true, 50000, 0), EarningSkipVoid}, + "unpaid": {newOrder(earningOutlet, ®ular, "pending", false, 50000, 0), EarningSkipNotPaid}, + "outlet not earning": {newOrder(quietOutlet, ®ular, "completed", false, 50000, 0), EarningSkipNothingToEarn}, + } { + outcome, err := earning.EarnForOrder(ctx, c.id) + require.NoError(t, err, name) + assert.Equal(t, c.skip, outcome.Skipped, name) + assert.Empty(t, earnRows(c.id), name) + } + + // An earning that fails does not surface to the payment, and the job picks it up. + settings.mu.Lock() + settings.fail = true + settings.mu.Unlock() + missed := newOrder(earningOutlet, ®ular, "completed", false, 40000, 0) + assert.NotPanics(t, func() { earning.OnOrderPaid(ctx, missed) }) + assert.Empty(t, earnRows(missed)) + + settings.mu.Lock() + settings.fail = false + settings.mu.Unlock() + since := time.Now().Add(-time.Hour) + checked, earned, err := earning.EarnMissing(ctx, since, 1000) + require.NoError(t, err) + assert.GreaterOrEqual(t, earned, 1) + assert.GreaterOrEqual(t, checked, earned) + assert.Equal(t, map[string]int64{"POINT": 400, "COIN": 1}, earnRows(missed)) + + // The job only looks at orders that could earn and have not. + candidates, err := repository.NewEarningRepository(db).ListPaidOrdersWithoutEarning(ctx, since, nil, 1000) + require.NoError(t, err) + var ours []uuid.UUID + for _, c := range candidates { + var n int64 + db.Raw(`SELECT COUNT(*) FROM orders WHERE id = ? AND organization_id = ?`, c.ID, org).Scan(&n) + if n > 0 { + ours = append(ours, c.ID) + } + } + assert.Empty(t, ours, "every eligible order of ours has earned; walk-in, inactive, void, unpaid and non-earning outlets are never candidates") + + // A second run finds nothing more to do for these orders. + _, _, err = earning.EarnMissing(ctx, since, 1000) + require.NoError(t, err) + assert.Equal(t, map[string]int64{"POINT": 400, "COIN": 1}, earnRows(missed)) + + // What the order screen and receipt show is what the ledger has. + shown, err := earning.EarnedByOrders(ctx, []uuid.UUID{paid, split, missed, uuid.New()}) + require.NoError(t, err) + assert.Equal(t, OrderEarned{Points: 875, Coins: 3}, shown[paid]) + assert.Equal(t, OrderEarned{Points: 600, Coins: 2}, shown[split]) + assert.Equal(t, OrderEarned{Points: 400, Coins: 1}, shown[missed]) + assert.Len(t, shown, 3, "an order without earning is absent, so it shows 0") + + balance := struct{ PointBalance, CoinBalance int64 }{} + require.NoError(t, db.Raw(`SELECT point_balance, coin_balance FROM customer_wallets WHERE customer_id = ?`, regular).Scan(&balance).Error) + assert.Equal(t, int64(875+250+600+400), balance.PointBalance) + assert.Equal(t, int64(3+1+2+1), balance.CoinBalance) +} + +func (f *failingSettings) Organization(ctx context.Context, organizationID uuid.UUID) (*models.OrganizationLoyaltySettings, error) { + return f.real.Organization(ctx, organizationID) +} diff --git a/internal/processor/earning_reversal.go b/internal/processor/earning_reversal.go new file mode 100644 index 0000000..e0dc1dd --- /dev/null +++ b/internal/processor/earning_reversal.go @@ -0,0 +1,167 @@ +package processor + +import ( + "context" + "fmt" + + "github.com/google/uuid" + + "apskel-pos-be/internal/constants" + "apskel-pos-be/internal/entities" + "apskel-pos-be/internal/logger" + "apskel-pos-be/internal/repository" +) + +// ReversalOutcome is what a reversal took back, and what it could not. +type ReversalOutcome struct { + Points int64 + Coins int64 + PointShortfall int64 + CoinShortfall int64 +} + +// OnOrderRefunded is called after an order was voided or (partly) refunded and that +// has committed. It never fails the caller: a refund is never blocked by the loyalty +// balance (Q3), so errors are logged. +func (p *EarningProcessor) OnOrderRefunded(ctx context.Context, orderID uuid.UUID) { + defer func() { + if r := recover(); r != nil { + logger.NonContext.Error(fmt.Sprintf("Earning reversal for order %s panicked", orderID), fmt.Errorf("%v", r)) + } + }() + if _, err := p.ReverseForOrder(ctx, orderID); err != nil { + logger.NonContext.Error(fmt.Sprintf("Earning reversal for order %s failed", orderID), err) + } +} + +// ReverseForOrder takes back what an order earned, as far as it has been voided or +// refunded (docs/prd-point-coin.md F10): +// +// - void: everything the order earned; +// - refund: floor(earned × refunded / basis), never more than was earned, with the +// refunded amount being the order's cumulative refund. +// +// Only the part not asked back yet is taken, so calling it again, or after each of +// several partial refunds, never takes more than the order earned. It draws from the +// lots the EARN created first, then from the others in K9 order, and takes what the +// balance has when it is short, recording the rest as shortfall (Q3). +func (p *EarningProcessor) ReverseForOrder(ctx context.Context, orderID uuid.UUID) (*ReversalOutcome, error) { + order, err := p.orders.GetOrderForEarning(ctx, orderID) + if err != nil { + return nil, err + } + earns, err := p.orders.ListEarnTransactions(ctx, orderID) + if err != nil { + return nil, err + } + outcome := &ReversalOutcome{} + if len(earns) == 0 { + return outcome, nil + } + + err = p.tx.WithTransaction(ctx, func(ctx context.Context) error { + for _, earn := range earns { + target := earningReversalTarget(order, earn) + requested, err := p.orders.ReversalRequested(ctx, earn.ID) + if err != nil { + return err + } + amount := target - requested + if amount <= 0 { + continue + } + lots, err := p.orders.LotIDsCreatedBy(ctx, earn.ID) + if err != nil { + return err + } + + reason := "REFUND" + if order.IsVoid { + reason = "VOID" + } + earnID := earn.ID + res, err := p.wallet.DebitUpTo(ctx, WalletDebitInput{ + WalletEntry: WalletEntry{ + CustomerID: earn.CustomerID, + Currency: earn.Currency, + Type: constants.WalletTxTypeEarnReversal, + Amount: amount, + ReferenceType: constants.WalletRefTypeOrder, + ReferenceID: order.ID, + ReversesTransactionID: &earnID, + OutletID: earn.OutletID, + Description: earningReversalDescription(order), + Metadata: entities.Metadata{ + "reason": reason, + "refund_amount": order.RefundAmount, + "target": target, + }, + // The target only grows with each refund, so each refund gets its own + // key while a retry of the same one replays. + IdempotencyKey: fmt.Sprintf("reverse:%s:%d", earn.ID, target), + }, + PreferredLotIDs: lots, + }) + if err != nil { + return fmt.Errorf("reversing %s: %w", earn.Currency, err) + } + + var taken int64 + if res.Transaction != nil { + taken = -res.Transaction.Amount + } else { + // Nothing to take: the ledger has no row to carry the shortfall. + logger.NonContext.WarnWithFields("Earning reversal found an empty balance; the whole amount is shortfall", map[string]interface{}{ + "order_id": order.ID.String(), "customer_id": earn.CustomerID.String(), + "currency": earn.Currency, "shortfall": res.Shortfall, + }, nil) + } + switch earn.Currency { + case constants.WalletCurrencyPoint: + outcome.Points += taken + outcome.PointShortfall += res.Shortfall + case constants.WalletCurrencyCoin: + outcome.Coins += taken + outcome.CoinShortfall += res.Shortfall + } + } + return nil + }) + if err != nil { + return nil, err + } + return outcome, nil +} + +// earningReversalTarget is how much of an EARN row should have been taken back in +// total, given the order's void flag and cumulative refund. It works in cents like +// CalculateEarning, with the basis frozen on the EARN row. +func earningReversalTarget(order *repository.EarningOrder, earn entities.WalletTransaction) int64 { + earned := earn.Amount + if order.IsVoid { + return earned + } + refundCents := toCents(order.RefundAmount) + if refundCents <= 0 { + return 0 + } + basis, _ := earn.Metadata["basis"].(float64) + basisCents := toCents(basis) + // A refund can include tax, which the basis does not, so it can reach past it. + if basisCents <= 0 || refundCents >= basisCents { + return earned + } + return earned * refundCents / basisCents +} + +func earningReversalDescription(order *repository.EarningOrder) string { + verb := "Refund" + if order.IsVoid { + verb = "Batal" + } + description := verb + " #" + order.OrderNumber + if order.OutletName != "" { + description += " di " + order.OutletName + } + return truncateRunes(description, walletDescriptionLimit) +} diff --git a/internal/processor/earning_reversal_db_test.go b/internal/processor/earning_reversal_db_test.go new file mode 100644 index 0000000..d17dd8e --- /dev/null +++ b/internal/processor/earning_reversal_db_test.go @@ -0,0 +1,206 @@ +package processor + +import ( + "context" + "os" + "testing" + + "github.com/google/uuid" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "gorm.io/driver/postgres" + "gorm.io/gorm" + "gorm.io/gorm/logger" + + "apskel-pos-be/internal/constants" + "apskel-pos-be/internal/repository" +) + +// Needs TEST_DATABASE_URL pointing at a migrated database; see +// internal/repository/wallet_repository_test.go. +func TestEarningReversal_AgainstPostgres(t *testing.T) { + dsn := os.Getenv("TEST_DATABASE_URL") + if dsn == "" { + t.Skip("TEST_DATABASE_URL not set") + } + db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{Logger: logger.Default.LogMode(logger.Silent)}) + require.NoError(t, err) + ctx := context.Background() + + org, user, outlet := uuid.New(), uuid.New(), uuid.New() + voider, refunder, spender, loyal := uuid.New(), uuid.New(), uuid.New(), uuid.New() + customers := []uuid.UUID{voider, refunder, spender, loyal} + exec := func(q string, args ...any) { + t.Helper() + require.NoError(t, db.Exec(q, args...).Error) + } + exec(`INSERT INTO organizations (id, name, plan_type) VALUES (?, 'reversal test', 'basic')`, org) + exec(`INSERT INTO users (id, organization_id, name, email, password_hash, role) VALUES (?, ?, 'Kasir', ?, 'x', 'cashier')`, user, org, user.String()+"@test") + exec(`INSERT INTO outlets (id, organization_id, name) VALUES (?, ?, 'Kemang')`, outlet, org) + for _, c := range customers { + exec(`INSERT INTO customers (id, organization_id, name) VALUES (?, ?, 'c')`, c, org) + } + t.Cleanup(func() { + db.Exec(`DELETE FROM wallet_lot_allocations WHERE lot_id IN (SELECT id FROM wallet_lots WHERE customer_id IN ?)`, customers) + db.Exec(`DELETE FROM wallet_lots WHERE customer_id IN ?`, customers) + db.Exec(`DELETE FROM wallet_transactions WHERE customer_id IN ?`, customers) + db.Exec(`DELETE FROM customer_wallets WHERE customer_id IN ?`, customers) + db.Exec(`DELETE FROM orders WHERE organization_id = ?`, org) + db.Exec(`DELETE FROM loyalty_setting_changes WHERE organization_id = ?`, org) + db.Exec(`DELETE FROM outlet_settings WHERE outlet_id = ?`, outlet) + db.Exec(`DELETE FROM customers WHERE id IN ?`, customers) + db.Exec(`DELETE FROM outlets WHERE id = ?`, outlet) + db.Exec(`DELETE FROM users WHERE id = ?`, user) + db.Exec(`DELETE FROM organizations WHERE id = ?`, org) + }) + + txm := repository.NewTxManager(db) + settings := NewLoyaltySettingsProcessor(repository.NewLoyaltySettingsRepository(db), txm) + s, err := settings.Outlet(ctx, outlet) + require.NoError(t, err) + s.Point.Enabled, s.Coin.Enabled = true, true + _, err = settings.UpdateOutlet(ctx, org, outlet, user, *s) + require.NoError(t, err) + wallet := NewWalletProcessor(repository.NewWalletRepository(db)) + earning := NewEarningProcessor(repository.NewEarningRepository(db), settings, wallet, txm) + + // Each order is the PRD example: basis Rp 87.500, 875 EnakPoint and 3 EnakCoin. + paidOrder := func(customer uuid.UUID) uuid.UUID { + t.Helper() + id := uuid.New() + exec(`INSERT INTO orders (id, organization_id, outlet_id, user_id, customer_id, order_number, order_type, + subtotal, discount_amount, tax_amount, total_amount, payment_status) + VALUES (?, ?, ?, ?, ?, ?, 'dine_in', 97500, 10000, 8750, 96250, 'completed')`, + id, org, outlet, user, customer, "ORD-"+id.String()[:8]) + outcome, err := earning.EarnForOrder(ctx, id) + require.NoError(t, err) + require.Equal(t, int64(875), outcome.Points) + return id + } + balance := func(customer uuid.UUID) (points, coins int64) { + t.Helper() + var b struct{ PointBalance, CoinBalance int64 } + require.NoError(t, db.Raw(`SELECT point_balance, coin_balance FROM customer_wallets WHERE customer_id = ?`, customer).Scan(&b).Error) + return b.PointBalance, b.CoinBalance + } + reversed := func(order uuid.UUID, currency string) int64 { + t.Helper() + var total int64 + require.NoError(t, db.Raw(`SELECT COALESCE(SUM(-amount), 0) FROM wallet_transactions + WHERE reference_id = ? AND type = 'EARN_REVERSAL' AND currency = ?`, order, currency).Scan(&total).Error) + return total + } + + // Void: everything comes back. + voided := paidOrder(voider) + exec(`UPDATE orders SET is_void = true WHERE id = ?`, voided) + earning.OnOrderRefunded(ctx, voided) + assert.Equal(t, int64(875), reversed(voided, "POINT")) + assert.Equal(t, int64(3), reversed(voided, "COIN")) + p, c := balance(voider) + assert.Equal(t, [2]int64{0, 0}, [2]int64{p, c}) + + var rev struct { + ReversesTransactionID string + Description string + } + require.NoError(t, db.Raw(`SELECT reverses_transaction_id::text AS reverses_transaction_id, description FROM wallet_transactions + WHERE reference_id = ? AND type = 'EARN_REVERSAL' AND currency = 'POINT'`, voided).Scan(&rev).Error) + var earnID string + require.NoError(t, db.Raw(`SELECT id::text FROM wallet_transactions WHERE reference_id = ? AND type = 'EARN' AND currency = 'POINT'`, voided).Scan(&earnID).Error) + assert.Equal(t, earnID, rev.ReversesTransactionID, "the reversal points at the EARN it reverses") + assert.Contains(t, rev.Description, "Batal #ORD-") + + // Repeating it takes nothing more. + earning.OnOrderRefunded(ctx, voided) + assert.Equal(t, int64(875), reversed(voided, "POINT")) + + // Partial refunds are proportional and add up to at most what was earned. + refunded := paidOrder(refunder) + for _, step := range []struct { + refundAmount float64 + wantTotal int64 + }{ + {20000, 200}, // floor(875 × 20000 / 87500) + {20000, 200}, // same refund again: nothing more + {50000, 500}, // cumulative refund grew + {96250, 875}, // the whole total, tax included, cannot exceed the earning + {96250, 875}, + } { + exec(`UPDATE orders SET refund_amount = ? WHERE id = ?`, step.refundAmount, refunded) + outcome, err := earning.ReverseForOrder(ctx, refunded) + require.NoError(t, err) + assert.Zero(t, outcome.PointShortfall) + assert.Equal(t, step.wantTotal, reversed(refunded, "POINT"), "after a refund of %.0f", step.refundAmount) + } + assert.Equal(t, int64(3), reversed(refunded, "COIN")) + + // Balance already spent: what is left is taken, the rest recorded as shortfall, + // and the refund is not blocked. + spent := paidOrder(spender) + committed(t, txm, func(ctx context.Context) (*WalletResult, error) { + return wallet.Debit(ctx, WalletDebitInput{WalletEntry: WalletEntry{ + CustomerID: spender, Currency: constants.WalletCurrencyPoint, Type: constants.WalletTxTypePayment, + Amount: 800, ReferenceType: constants.WalletRefTypePayment, ReferenceID: uuid.New(), OutletID: &outlet, + Description: "Bayar"}}) + }) + exec(`UPDATE orders SET is_void = true WHERE id = ?`, spent) + outcome, err := earning.ReverseForOrder(ctx, spent) + require.NoError(t, err) + assert.Equal(t, int64(75), outcome.Points) + assert.Equal(t, int64(800), outcome.PointShortfall) + p, _ = balance(spender) + assert.Equal(t, int64(0), p, "never negative") + var metadata string + require.NoError(t, db.Raw(`SELECT metadata::text FROM wallet_transactions WHERE reference_id = ? AND type = 'EARN_REVERSAL' AND currency = 'POINT'`, spent).Scan(&metadata).Error) + assert.Contains(t, metadata, `"shortfall": 800`) + assert.Contains(t, metadata, `"requested_amount": 875`) + // Asked back in full already, shortfall included: a repeat takes nothing. + outcome, err = earning.ReverseForOrder(ctx, spent) + require.NoError(t, err) + assert.Zero(t, outcome.Points) + + // The EARN's own lots are drawn first, even when an older lot would come first. + older := committed(t, txm, func(ctx context.Context) (*WalletResult, error) { + return wallet.Credit(ctx, WalletCreditInput{WalletEntry: WalletEntry{ + CustomerID: loyal, Currency: constants.WalletCurrencyPoint, Type: constants.WalletTxTypeMigration, + Amount: 500, ReferenceType: constants.WalletRefTypeLegacyPoints, ReferenceID: uuid.New(), Description: "Saldo awal"}}) + }) + loyalOrder := paidOrder(loyal) + exec(`UPDATE orders SET refund_amount = 20000 WHERE id = ?`, loyalOrder) + _, err = earning.ReverseForOrder(ctx, loyalOrder) + require.NoError(t, err) + var fromOlder int64 + require.NoError(t, db.Raw(`SELECT COALESCE(SUM(a.amount), 0) FROM wallet_lot_allocations a + JOIN wallet_transactions t ON t.id = a.transaction_id + WHERE t.reference_id = ? AND t.type = 'EARN_REVERSAL' AND a.lot_id = ?`, loyalOrder, older.Lots[0].ID).Scan(&fromOlder).Error) + assert.Zero(t, fromOlder, "the older lot is untouched") + assert.Equal(t, int64(200), reversed(loyalOrder, "POINT")) + + // An order that never earned has nothing to reverse. + outcome, err = earning.ReverseForOrder(ctx, uuid.New()) + assert.ErrorIs(t, err, repository.ErrEarningOrderNotFound) + assert.Nil(t, outcome) + + // Every reversal kept balances, ledger and lots in step (§7.5). + found, err := repository.NewWalletReconciliationRepository(db).FindDiscrepancies(ctx, 1000) + require.NoError(t, err) + for _, d := range found { + for _, c := range customers { + assert.NotEqual(t, c, d.CustomerID, "discrepancy %s for one of our customers", d.Check) + } + } +} + +// committed runs fn in a transaction that commits before it returns, for engine calls +// made directly from a test. +func committed[T any](t *testing.T, txm *repository.TxManager, fn func(ctx context.Context) (T, error)) T { + t.Helper() + var out T + require.NoError(t, txm.WithTransaction(context.Background(), func(ctx context.Context) error { + var err error + out, err = fn(ctx) + return err + })) + return out +} diff --git a/internal/processor/earning_reversal_test.go b/internal/processor/earning_reversal_test.go new file mode 100644 index 0000000..760fae4 --- /dev/null +++ b/internal/processor/earning_reversal_test.go @@ -0,0 +1,25 @@ +package processor + +import ( + "testing" + + "github.com/stretchr/testify/assert" + + "apskel-pos-be/internal/entities" + "apskel-pos-be/internal/repository" +) + +func TestEarningReversalTarget(t *testing.T) { + earn := entities.WalletTransaction{Amount: 875, Metadata: entities.Metadata{"basis": 87500.0}} + target := func(order repository.EarningOrder) int64 { return earningReversalTarget(&order, earn) } + + assert.Equal(t, int64(0), target(repository.EarningOrder{}), "nothing refunded, nothing to take") + assert.Equal(t, int64(875), target(repository.EarningOrder{IsVoid: true}), "void takes everything") + assert.Equal(t, int64(200), target(repository.EarningOrder{RefundAmount: 20000}), "floor(875 × 20000 / 87500)") + assert.Equal(t, int64(299), target(repository.EarningOrder{RefundAmount: 29999.99}), "floor, not round") + assert.Equal(t, int64(875), target(repository.EarningOrder{RefundAmount: 87500})) + assert.Equal(t, int64(875), target(repository.EarningOrder{RefundAmount: 96250}), "a refund including tax cannot take more than was earned") + + noBasis := entities.WalletTransaction{Amount: 10, Metadata: entities.Metadata{}} + assert.Equal(t, int64(10), earningReversalTarget(&repository.EarningOrder{RefundAmount: 1}, noBasis), "without a basis any refund takes it all") +} diff --git a/internal/processor/game_play_processor.go b/internal/processor/game_play_processor.go index 4a77282..15e3337 100644 --- a/internal/processor/game_play_processor.go +++ b/internal/processor/game_play_processor.go @@ -1,6 +1,7 @@ package processor import ( + "apskel-pos-be/internal/constants" "apskel-pos-be/internal/entities" "apskel-pos-be/internal/mappers" "apskel-pos-be/internal/models" @@ -8,33 +9,55 @@ import ( "context" "errors" "fmt" + "math" "math/rand" "time" "github.com/google/uuid" ) +// ErrGamePlayRefused wraps every reason a customer cannot play right now: the game, +// its prizes or their EnakCoin. The message says which. +var ErrGamePlayRefused = errors.New("game cannot be played") + +const ( + gameCoinCostKey = "coin_cost" + defaultGameCoinCost = 1 +) + +type gameReader interface { + GetByID(ctx context.Context, id uuid.UUID) (*entities.Game, error) +} + +type gamePrizeStock interface { + GetAvailablePrizes(ctx context.Context, gameID uuid.UUID) ([]entities.GamePrize, error) + DecreaseStock(ctx context.Context, id uuid.UUID, amount int) error +} + type GamePlayProcessor struct { - gamePlayRepo repository.GamePlayRepository - gameRepo *repository.GameRepository - gamePrizeRepo *repository.GamePrizeRepository - customerTokensRepo *repository.CustomerTokensRepository - customerPointsRepo repository.CustomerPointsRepository + gamePlayRepo repository.GamePlayRepository + gameRepo gameReader + gamePrizeRepo gamePrizeStock + wallet *WalletProcessor + spendable spendableReader + tx TxRunner } func NewGamePlayProcessor( gamePlayRepo repository.GamePlayRepository, - gameRepo *repository.GameRepository, - gamePrizeRepo *repository.GamePrizeRepository, - customerTokensRepo *repository.CustomerTokensRepository, - customerPointsRepo repository.CustomerPointsRepository, + gameRepo gameReader, + gamePrizeRepo gamePrizeStock, + wallet *WalletProcessor, + spendable spendableReader, + tx TxRunner, ) *GamePlayProcessor { return &GamePlayProcessor{ - gamePlayRepo: gamePlayRepo, - gameRepo: gameRepo, - gamePrizeRepo: gamePrizeRepo, - customerTokensRepo: customerTokensRepo, - customerPointsRepo: customerPointsRepo, + gamePlayRepo: gamePlayRepo, + gameRepo: gameRepo, + gamePrizeRepo: gamePrizeRepo, + wallet: wallet, + spendable: spendable, + tx: tx, } } @@ -76,6 +99,10 @@ func (p *GamePlayProcessor) ListGamePlays(ctx context.Context, query *models.Lis } offset := (query.Page - 1) * query.Limit + // The column was renamed; the old name still sorts the same way. + if query.SortBy == "token_used" { + query.SortBy = "coins_used" + } // Get game plays from repository gamePlays, total, err := p.gamePlayRepo.List( @@ -110,101 +137,140 @@ func (p *GamePlayProcessor) ListGamePlays(ctx context.Context, query *models.Lis }, nil } -// PlayGame handles the game playing logic +// PlayGame plays a game for a customer, paid with EnakCoin (docs/prd-point-coin.md +// F8, K1). Every kind of game spends the same EnakCoin, at the game's +// metadata.coin_cost. Taking the EnakCoin (GAME_SPEND), recording the play and taking +// the prize from stock happen in one transaction, so a play that cannot be completed, +// for instance because the prize just ran out, takes nothing and records nothing. func (p *GamePlayProcessor) PlayGame(ctx context.Context, req *models.PlayGameRequest) (*models.PlayGameResponse, error) { - // Verify game exists and is active + refuse := func(format string, args ...any) error { + return fmt.Errorf("%w: %s", ErrGamePlayRefused, fmt.Sprintf(format, args...)) + } game, err := p.gameRepo.GetByID(ctx, req.GameID) if err != nil { return nil, fmt.Errorf("game not found: %w", err) } - if !game.IsActive { - return nil, errors.New("game is not active") + return nil, refuse("game is not active") } - - // Convert GameType to TokenType - tokenType := entities.TokenType(game.Type) - - // Check if customer has enough tokens - customerTokens, err := p.customerTokensRepo.GetByCustomerIDAndType(ctx, req.CustomerID, tokenType) + cost, err := gameCoinCost(game.Metadata) if err != nil { - return nil, fmt.Errorf("customer tokens not found: %w", err) + return nil, refuse("%s", err.Error()) } - if customerTokens.Balance < int64(req.TokenUsed) { - return nil, errors.New("insufficient tokens") - } - - // Deduct tokens - err = p.customerTokensRepo.DeductTokens(ctx, req.CustomerID, tokenType, int64(req.TokenUsed)) - if err != nil { - return nil, fmt.Errorf("failed to deduct tokens: %w", err) - } - - // Get available prizes - availablePrizes, err := p.gamePrizeRepo.GetAvailablePrizes(ctx, req.GameID) - if err != nil { - return nil, fmt.Errorf("failed to get available prizes: %w", err) - } - - if len(availablePrizes) == 0 { - return nil, errors.New("no prizes available") - } - - // Convert entities to models for prize selection - prizeResponses := make([]models.GamePrizeResponse, len(availablePrizes)) - for i, prize := range availablePrizes { - prizeResponses[i] = *mappers.ToGamePrizeResponse(&prize) - } - - // Select prize based on weight - selectedPrize := p.selectPrizeByWeight(prizeResponses) - - // Generate random seed for audit - randomSeed := fmt.Sprintf("%d", time.Now().UnixNano()) - - // Create game play record - gamePlay := &models.CreateGamePlayRequest{ - GameID: req.GameID, - CustomerID: req.CustomerID, - TokenUsed: req.TokenUsed, - RandomSeed: &randomSeed, - } - - gamePlayEntity := mappers.ToGamePlayEntity(gamePlay) - if selectedPrize != nil { - gamePlayEntity.PrizeID = &selectedPrize.ID - } - - err = p.gamePlayRepo.Create(ctx, gamePlayEntity) - if err != nil { - // Rollback token deduction - p.customerTokensRepo.AddTokens(ctx, req.CustomerID, tokenType, int64(req.TokenUsed)) - return nil, fmt.Errorf("failed to create game play: %w", err) - } - - // Decrease prize stock if prize was won - if selectedPrize != nil { - err = p.gamePrizeRepo.DecreaseStock(ctx, selectedPrize.ID, 1) + var gamePlay *entities.GamePlay + var selectedPrize *models.GamePrizeResponse + err = p.tx.WithTransaction(ctx, func(ctx context.Context) error { + availablePrizes, err := p.gamePrizeRepo.GetAvailablePrizes(ctx, req.GameID) if err != nil { - // Log error but don't fail the transaction - fmt.Printf("Warning: failed to decrease prize stock: %v\n", err) + return fmt.Errorf("failed to get available prizes: %w", err) } - } + if len(availablePrizes) == 0 { + return refuse("no prizes available") + } + prizeResponses := make([]models.GamePrizeResponse, len(availablePrizes)) + for i, prize := range availablePrizes { + prizeResponses[i] = *mappers.ToGamePrizeResponse(&prize) + } + selectedPrize = p.selectPrizeByWeight(prizeResponses) - // Get updated token balance - updatedTokens, err := p.customerTokensRepo.GetByCustomerIDAndType(ctx, req.CustomerID, tokenType) + // Random seed kept for audit. + randomSeed := fmt.Sprintf("%d", time.Now().UnixNano()) + gamePlay = &entities.GamePlay{ + ID: uuid.New(), + GameID: req.GameID, + CustomerID: req.CustomerID, + CoinsUsed: int(cost), + RandomSeed: &randomSeed, + } + if selectedPrize != nil { + gamePlay.PrizeID = &selectedPrize.ID + } + + // The EnakCoin go first: the debit locks the wallet, so plays by the same + // customer at the same time queue up instead of spending the same balance. + _, err = p.wallet.Debit(ctx, WalletDebitInput{WalletEntry: WalletEntry{ + CustomerID: req.CustomerID, + Currency: constants.WalletCurrencyCoin, + Type: constants.WalletTxTypeGameSpend, + Amount: cost, + ReferenceType: constants.WalletRefTypeGamePlay, + ReferenceID: gamePlay.ID, + Description: gameSpendDescription(game.Name, selectedPrize), + Metadata: entities.Metadata{"game_id": game.ID.String(), "coin_cost": cost}, + }}) + if errors.Is(err, repository.ErrWalletInsufficientBalance) { + return refuse("not enough EnakCoin: this game costs %d", cost) + } + if err != nil { + return err + } + if err := p.gamePlayRepo.Create(ctx, gamePlay); err != nil { + return err + } + if selectedPrize != nil { + err := p.gamePrizeRepo.DecreaseStock(ctx, selectedPrize.ID, 1) + if errors.Is(err, repository.ErrGamePrizeOutOfStock) { + return refuse("the prize just ran out, please play again") + } + if err != nil { + return err + } + } + return nil + }) if err != nil { - return nil, fmt.Errorf("failed to get updated token balance: %w", err) + return nil, err } + balances, err := p.spendable.SpendableBalances(ctx, req.CustomerID, time.Now()) + if err != nil { + return nil, err + } return &models.PlayGameResponse{ - GamePlay: *mappers.ToGamePlayResponse(gamePlayEntity), - PrizeWon: selectedPrize, - TokensRemaining: updatedTokens.Balance, + GamePlay: *mappers.ToGamePlayResponse(gamePlay), + PrizeWon: selectedPrize, + CoinsRemaining: balances[constants.WalletCurrencyCoin], }, nil } +// gameCoinCost is what one play of a game costs, from games.metadata.coin_cost: a +// whole number of EnakCoin, 1 when it is not set (F8). +func gameCoinCost(metadata entities.Metadata) (int64, error) { + raw, ok := metadata[gameCoinCostKey] + if !ok || raw == nil { + return defaultGameCoinCost, nil + } + var cost int64 + switch v := raw.(type) { + case float64: + if v != math.Trunc(v) { + return 0, fmt.Errorf("the game's coin_cost %v is not a whole number", v) + } + cost = int64(v) + case int: + cost = int64(v) + case int64: + cost = v + default: + return 0, fmt.Errorf("the game's coin_cost %v is not a number", raw) + } + if cost < 1 { + return 0, fmt.Errorf("the game's coin_cost must be at least 1, got %d", cost) + } + return cost, nil +} + +// gameSpendDescription is what the customer's history shows for a play, frozen when it +// happens (§8.1): "Main Spin Wheel: dapat Voucher 10rb". +func gameSpendDescription(gameName string, prize *models.GamePrizeResponse) string { + description := "Main " + gameName + if prize != nil { + description += ": dapat " + prize.Name + } + return truncateRunes(description, walletDescriptionLimit) +} + // selectPrizeByWeight selects a prize based on weight distribution func (p *GamePlayProcessor) selectPrizeByWeight(prizes []models.GamePrizeResponse) *models.GamePrizeResponse { if len(prizes) == 0 { diff --git a/internal/processor/game_play_processor_db_test.go b/internal/processor/game_play_processor_db_test.go new file mode 100644 index 0000000..ef1cb6d --- /dev/null +++ b/internal/processor/game_play_processor_db_test.go @@ -0,0 +1,69 @@ +package processor + +import ( + "context" + "testing" + + "github.com/google/uuid" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "apskel-pos-be/internal/constants" + "apskel-pos-be/internal/models" + "apskel-pos-be/internal/repository" +) + +// Plays against Postgres, so the game repositories really join the transaction: a +// refused play leaves no game_plays row and no GAME_SPEND. +func TestPlayGame_AgainstPostgres(t *testing.T) { + db, _, player, _ := walletMoveDB(t) + gameID, prizeID := uuid.New(), uuid.New() + require.NoError(t, db.Exec(`INSERT INTO games (id, name, type, metadata) VALUES (?, 'Raffle', 'RAFFLE', '{"coin_cost": 2}')`, gameID).Error) + require.NoError(t, db.Exec(`INSERT INTO game_prizes (id, game_id, name, weight, stock) VALUES (?, ?, 'Tumbler', 1, 1)`, prizeID, gameID).Error) + t.Cleanup(func() { + db.Exec(`DELETE FROM wallet_lot_allocations WHERE transaction_id IN (SELECT id FROM wallet_transactions WHERE customer_id = ?)`, player) + db.Exec(`DELETE FROM game_plays WHERE game_id = ?`, gameID) + db.Exec(`DELETE FROM game_prizes WHERE game_id = ?`, gameID) + db.Exec(`DELETE FROM games WHERE id = ?`, gameID) + }) + + wallet := NewWalletProcessor(repository.NewWalletRepository(db)) + txm := repository.NewTxManager(db) + require.NoError(t, txm.WithTransaction(context.Background(), func(ctx context.Context) error { + in := earn(player, 3, nil) + in.Currency = constants.WalletCurrencyCoin + _, err := wallet.Credit(ctx, in) + return err + })) + p := NewGamePlayProcessor(repository.NewGamePlayRepository(db), repository.NewGameRepository(db), repository.NewGamePrizeRepository(db), + wallet, repository.NewWalletQueryRepository(db), txm) + play := func() (*models.PlayGameResponse, error) { + return p.PlayGame(context.Background(), &models.PlayGameRequest{GameID: gameID, CustomerID: player}) + } + + res, err := play() + require.NoError(t, err) + assert.Equal(t, int64(1), res.CoinsRemaining) + assert.Equal(t, 2, res.GamePlay.CoinsUsed) + + var spend struct { + ReferenceID uuid.UUID + Amount int64 + } + require.NoError(t, db.Raw(`SELECT reference_id, amount FROM wallet_transactions WHERE customer_id = ? AND type = 'GAME_SPEND'`, player).Scan(&spend).Error) + assert.Equal(t, res.GamePlay.ID, spend.ReferenceID) + assert.Equal(t, int64(-2), spend.Amount) + + // The only prize is gone, then the EnakCoin are too short: neither play leaves a row. + _, err = play() + assert.ErrorIs(t, err, ErrGamePlayRefused) + require.NoError(t, db.Exec(`UPDATE game_prizes SET stock = 5 WHERE id = ?`, prizeID).Error) + _, err = play() + assert.ErrorIs(t, err, ErrGamePlayRefused) + + var plays, spends int64 + require.NoError(t, db.Raw(`SELECT COUNT(*) FROM game_plays WHERE game_id = ? AND coins_used = 2`, gameID).Scan(&plays).Error) + require.NoError(t, db.Raw(`SELECT COUNT(*) FROM wallet_transactions WHERE customer_id = ? AND type = 'GAME_SPEND'`, player).Scan(&spends).Error) + assert.Equal(t, int64(1), plays) + assert.Equal(t, int64(1), spends) +} diff --git a/internal/processor/game_play_processor_test.go b/internal/processor/game_play_processor_test.go new file mode 100644 index 0000000..6a43670 --- /dev/null +++ b/internal/processor/game_play_processor_test.go @@ -0,0 +1,245 @@ +package processor + +import ( + "context" + "errors" + "testing" + + "github.com/google/uuid" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "apskel-pos-be/internal/constants" + "apskel-pos-be/internal/entities" + "apskel-pos-be/internal/models" + "apskel-pos-be/internal/repository" +) + +// snapshot saves everything the fake wallet holds and returns what puts it back, so +// a test transaction can roll back like a real one. +func (f *walletRepoFake) snapshot() func() { + wallets := make(map[uuid.UUID]*entities.CustomerWallet, len(f.wallets)) + for id, w := range f.wallets { + c := *w + wallets[id] = &c + } + transactions := make([]*entities.WalletTransaction, len(f.transactions)) + for i, t := range f.transactions { + c := *t + transactions[i] = &c + } + lots := make([]*entities.WalletLot, len(f.lots)) + for i, l := range f.lots { + c := *l + lots[i] = &c + } + allocations := append([]entities.WalletLotAllocation(nil), f.allocations...) + return func() { + f.wallets, f.transactions, f.lots, f.allocations = wallets, transactions, lots, allocations + } +} + +// rollbackTx runs fn in place and, when it fails, puts back what each save saved. +type rollbackTx struct{ saves []func() func() } + +func (r rollbackTx) WithTransaction(ctx context.Context, fn func(ctx context.Context) error) error { + restores := make([]func(), 0, len(r.saves)) + for _, save := range r.saves { + restores = append(restores, save()) + } + err := fn(ctx) + if err != nil { + for _, restore := range restores { + restore() + } + } + return err +} + +type gameFake struct{ games map[uuid.UUID]*entities.Game } + +func (f gameFake) GetByID(_ context.Context, id uuid.UUID) (*entities.Game, error) { + g, ok := f.games[id] + if !ok { + return nil, errors.New("record not found") + } + return g, nil +} + +type prizeStockFake struct { + prizes []entities.GamePrize + stockErr error +} + +func (f *prizeStockFake) GetAvailablePrizes(_ context.Context, gameID uuid.UUID) ([]entities.GamePrize, error) { + var out []entities.GamePrize + for _, p := range f.prizes { + if p.GameID == gameID && p.Stock > 0 { + out = append(out, p) + } + } + return out, nil +} + +func (f *prizeStockFake) DecreaseStock(_ context.Context, id uuid.UUID, amount int) error { + if f.stockErr != nil { + return f.stockErr + } + for i := range f.prizes { + if f.prizes[i].ID == id { + if f.prizes[i].Stock < amount { + return repository.ErrGamePrizeOutOfStock + } + f.prizes[i].Stock -= amount + return nil + } + } + return repository.ErrGamePrizeOutOfStock +} + +func (f *prizeStockFake) snapshot() func() { + prizes := append([]entities.GamePrize(nil), f.prizes...) + return func() { f.prizes = prizes } +} + +// gamePlayRepoFake records plays; the other methods of the interface are not used. +type gamePlayRepoFake struct { + repository.GamePlayRepository + plays []entities.GamePlay +} + +func (f *gamePlayRepoFake) Create(_ context.Context, gp *entities.GamePlay) error { + f.plays = append(f.plays, *gp) + return nil +} + +func (f *gamePlayRepoFake) snapshot() func() { + plays := append([]entities.GamePlay(nil), f.plays...) + return func() { f.plays = plays } +} + +type gameTestEnv struct { + *walletMoveEnv + game *entities.Game + prize entities.GamePrize + stock *prizeStockFake + plays *gamePlayRepoFake + player uuid.UUID + p *GamePlayProcessor +} + +func newGameTestEnv(t *testing.T, metadata entities.Metadata) *gameTestEnv { + e := &gameTestEnv{walletMoveEnv: newWalletMoveEnv(t)} + e.game = &entities.Game{ID: uuid.New(), Name: "Spin Wheel", Type: entities.GameTypeSpin, IsActive: true, Metadata: metadata} + e.prize = entities.GamePrize{ID: uuid.New(), GameID: e.game.ID, Name: "Voucher 10rb", Weight: 1, Stock: 5} + e.stock = &prizeStockFake{prizes: []entities.GamePrize{e.prize}} + e.plays = &gamePlayRepoFake{} + e.player = e.member("Budi", "081234561234") + tx := rollbackTx{saves: []func() func(){e.repo.snapshot, e.stock.snapshot, e.plays.snapshot}} + e.p = NewGamePlayProcessor(e.plays, gameFake{games: map[uuid.UUID]*entities.Game{e.game.ID: e.game}}, e.stock, e.walletTestEnv.p, e, tx) + return e +} + +func (e *gameTestEnv) play() (*models.PlayGameResponse, error) { + return e.p.PlayGame(e.ctx, &models.PlayGameRequest{GameID: e.game.ID, CustomerID: e.player}) +} + +func TestPlayGame_SpendsTheGamesCoinCost(t *testing.T) { + // coin_cost comes back from JSONB as a float64. + e := newGameTestEnv(t, entities.Metadata{"coin_cost": float64(3)}) + e.earnCoins(t, e.player, 10, nil) + + res, err := e.play() + require.NoError(t, err) + + assert.Equal(t, int64(7), res.CoinsRemaining) + require.NotNil(t, res.PrizeWon) + assert.Equal(t, e.prize.ID, res.PrizeWon.ID) + require.Len(t, e.plays.plays, 1) + play := e.plays.plays[0] + assert.Equal(t, 3, play.CoinsUsed) + assert.Equal(t, e.prize.ID, *play.PrizeID) + assert.Equal(t, 4, e.stock.prizes[0].Stock) + + spend := e.repo.transactions[len(e.repo.transactions)-1] + assert.Equal(t, constants.WalletTxTypeGameSpend, spend.Type) + assert.Equal(t, constants.WalletCurrencyCoin, spend.Currency) + assert.Equal(t, int64(-3), spend.Amount) + assert.Equal(t, constants.WalletRefTypeGamePlay, spend.ReferenceType) + assert.Equal(t, play.ID, spend.ReferenceID, "GAME_SPEND points at the game play") + assert.Equal(t, "Main Spin Wheel: dapat Voucher 10rb", spend.Description) +} + +func TestPlayGame_CostsOneCoinByDefault(t *testing.T) { + e := newGameTestEnv(t, entities.Metadata{}) + e.earnCoins(t, e.player, 2, nil) + + res, err := e.play() + require.NoError(t, err) + assert.Equal(t, int64(1), res.CoinsRemaining) + assert.Equal(t, 1, e.plays.plays[0].CoinsUsed) +} + +func TestPlayGame_NotEnoughCoinsRecordsNothing(t *testing.T) { + e := newGameTestEnv(t, entities.Metadata{"coin_cost": float64(3)}) + e.earnCoins(t, e.player, 2, nil) + + _, err := e.play() + assert.ErrorIs(t, err, ErrGamePlayRefused) + assert.Empty(t, e.plays.plays) + assert.Equal(t, 5, e.stock.prizes[0].Stock) + assert.Equal(t, int64(2), e.coinBalance(t, e.player)) +} + +func TestPlayGame_PrizeStockFailureCancelsThePlay(t *testing.T) { + e := newGameTestEnv(t, entities.Metadata{}) + e.earnCoins(t, e.player, 5, nil) + rows := len(e.repo.transactions) + + // Another play took the last one between reading the prizes and taking it. + e.stock.stockErr = repository.ErrGamePrizeOutOfStock + _, err := e.play() + assert.ErrorIs(t, err, ErrGamePlayRefused) + + // Anything else going wrong with the stock cancels it too. + e.stock.stockErr = errors.New("connection reset") + _, err = e.play() + assert.Error(t, err) + + assert.Empty(t, e.plays.plays) + assert.Len(t, e.repo.transactions, rows, "no GAME_SPEND is left behind") + assert.Equal(t, int64(5), e.coinBalance(t, e.player)) +} + +func TestPlayGame_RefusesWhatCannotBePlayed(t *testing.T) { + for name, metadata := range map[string]entities.Metadata{ + "zero": {"coin_cost": float64(0)}, + "fraction": {"coin_cost": 1.5}, + "not number": {"coin_cost": "2"}, + } { + t.Run(name, func(t *testing.T) { + e := newGameTestEnv(t, metadata) + e.earnCoins(t, e.player, 5, nil) + _, err := e.play() + assert.ErrorIs(t, err, ErrGamePlayRefused) + assert.Equal(t, int64(5), e.coinBalance(t, e.player)) + }) + } + + t.Run("inactive", func(t *testing.T) { + e := newGameTestEnv(t, entities.Metadata{}) + e.earnCoins(t, e.player, 5, nil) + e.game.IsActive = false + _, err := e.play() + assert.ErrorIs(t, err, ErrGamePlayRefused) + }) + + t.Run("no prizes left", func(t *testing.T) { + e := newGameTestEnv(t, entities.Metadata{}) + e.earnCoins(t, e.player, 5, nil) + e.stock.prizes[0].Stock = 0 + _, err := e.play() + assert.ErrorIs(t, err, ErrGamePlayRefused) + assert.Equal(t, int64(5), e.coinBalance(t, e.player)) + }) +} diff --git a/internal/processor/loyalty_expiry.go b/internal/processor/loyalty_expiry.go new file mode 100644 index 0000000..cf05322 --- /dev/null +++ b/internal/processor/loyalty_expiry.go @@ -0,0 +1,170 @@ +package processor + +import ( + "errors" + "fmt" + "sort" + "strings" + "time" + + "apskel-pos-be/internal/constants" + "apskel-pos-be/internal/models" +) + +// Expiry rules of docs/prd-point-coin.md F12, with the model of note N4 decided: both +// FIXED_DATE and ROLLING are supported and the owner picks one per currency. +// +// A lot expires at the last second of its expiry day in the customer's time zone, so +// "expires on 31 Dec" means it can still be spent all of 31 Dec, and the day the apps +// group it under is that day. + +const ( + // A longer grace would push a balance past a whole cycle of fixed dates. + loyaltyExpiryMaxGraceMonths = 24 + // A refund gives the EnakPoint back at least this long, even when the lot they + // came from has expired or is about to (note N4, decided). + refundMinimumValidity = 7 * 24 * time.Hour +) + +// ExpirySettings picks the settings of one currency. +func ExpirySettings(s *models.OrganizationLoyaltySettings, currency string) models.LoyaltyExpirySettings { + if currency == constants.WalletCurrencyCoin { + return s.CoinExpiry + } + return s.PointExpiry +} + +// ComputeExpiry is when a balance received at receivedAt expires, or nil when it never +// does because expiry is off. It is the expiry of every lot that is not carried over +// from another one: EARN, ADJUSTMENT and, capped by its origin, EXCHANGE_IN. +func ComputeExpiry(s models.LoyaltyExpirySettings, receivedAt time.Time) *time.Time { + if !s.Enabled { + return nil + } + day := walletDay(receivedAt) + if s.Mode == constants.LoyaltyExpiryModeRolling { + if s.Unit == constants.LoyaltyExpiryUnitDay { + day = day.AddDate(0, 0, int(s.Period)) + } else { + day = addMonthsClamped(day, int(s.Period)) + } + if s.EndOfMonth { + day = lastDayOfMonth(day) + } + return endOfWalletDay(day) + } + return endOfWalletDay(fixedDateOnOrAfter(s.FixedDates, addMonthsClamped(day, int(s.GraceMonths)))) +} + +// ActivationExpiry is the expiry given to the balances that already exist, without an +// expiry, when expiry is turned on (note N4, decided): a full period from activation +// when ROLLING, the second fixed date after activation when FIXED_DATE. Either way no +// customer loses a balance soon after the rule is announced. +func ActivationExpiry(s models.LoyaltyExpirySettings, at time.Time) *time.Time { + if s.Mode == constants.LoyaltyExpiryModeRolling { + s.Enabled = true + return ComputeExpiry(s, at) + } + first := fixedDateOnOrAfter(s.FixedDates, walletDay(at)) + return endOfWalletDay(fixedDateOnOrAfter(s.FixedDates, first.AddDate(0, 0, 1))) +} + +// RefundExpiry is the expiry of EnakPoint given back by a refund: that of the lot they +// came from, but at least seven days from now (note N4, decided). A lot that never +// expires stays so. +func RefundExpiry(origin *time.Time, now time.Time) *time.Time { + if origin == nil { + return nil + } + minimum := endOfWalletDay(walletDay(now.Add(refundMinimumValidity))) + if origin.Before(*minimum) { + return minimum + } + return origin +} + +// EarlierExpiry is the sooner of two expiries, where nil means never. +func EarlierExpiry(a, b *time.Time) *time.Time { + switch { + case a == nil: + return b + case b == nil: + return a + case b.Before(*a): + return b + } + return a +} + +// normalizeDaysOfYear checks days written as MM-DD and returns them sorted without +// duplicates. 29 February is refused, as it does not come every year. +func normalizeDaysOfYear(days []string) ([]string, error) { + seen := map[string]bool{} + var out []string + for _, d := range days { + d = strings.TrimSpace(d) + if d == "" { + continue + } + parsed, err := time.Parse("01-02", d) + if err != nil || parsed.Format("01-02") != d { + return nil, fmt.Errorf("has %q, which is not a day of the year written as MM-DD", d) + } + if d == "02-29" { + return nil, errors.New("cannot use 02-29, which is not in every year") + } + if !seen[d] { + seen[d] = true + out = append(out, d) + } + } + if len(out) == 0 { + return nil, errors.New("must list at least one day of the year, as MM-DD") + } + sort.Strings(out) + return out, nil +} + +// fixedDateOnOrAfter is the first of the days of the year that falls on or after day. +func fixedDateOnOrAfter(days []string, day time.Time) time.Time { + days, err := normalizeDaysOfYear(days) + if err != nil { + days = []string{constants.LoyaltyExpiryFixedDatesDefault} + } + for year := day.Year(); ; year++ { + for _, d := range days { + parsed, _ := time.Parse("01-02", d) + candidate := time.Date(year, parsed.Month(), parsed.Day(), 0, 0, 0, 0, walletDisplayLocation) + if !candidate.Before(day) { + return candidate + } + } + } +} + +// walletDay is the calendar day of t in the customer's time zone, at midnight. +func walletDay(t time.Time) time.Time { + local := t.In(walletDisplayLocation) + return time.Date(local.Year(), local.Month(), local.Day(), 0, 0, 0, 0, walletDisplayLocation) +} + +func endOfWalletDay(day time.Time) *time.Time { + end := time.Date(day.Year(), day.Month(), day.Day(), 23, 59, 59, 0, walletDisplayLocation) + return &end +} + +// addMonthsClamped adds months, keeping to the last day of a shorter month: 31 Jan +// plus one month is 28 or 29 Feb, not 3 Mar. +func addMonthsClamped(day time.Time, months int) time.Time { + first := time.Date(day.Year(), day.Month(), 1, 0, 0, 0, 0, day.Location()).AddDate(0, months, 0) + last := lastDayOfMonth(first).Day() + d := day.Day() + if d > last { + d = last + } + return time.Date(first.Year(), first.Month(), d, 0, 0, 0, 0, day.Location()) +} + +func lastDayOfMonth(day time.Time) time.Time { + return time.Date(day.Year(), day.Month()+1, 0, 0, 0, 0, 0, day.Location()) +} diff --git a/internal/processor/loyalty_expiry_test.go b/internal/processor/loyalty_expiry_test.go new file mode 100644 index 0000000..c112f30 --- /dev/null +++ b/internal/processor/loyalty_expiry_test.go @@ -0,0 +1,115 @@ +package processor + +import ( + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "apskel-pos-be/internal/models" +) + +// wib is a moment in the customer's time zone. +func wib(year int, month time.Month, day, hour, minute int) time.Time { + return time.Date(year, month, day, hour, minute, 0, 0, walletDisplayLocation) +} + +// expiryDay is the day a lot expires on, as the apps show it. +func expiryDay(t *testing.T, at *time.Time) string { + t.Helper() + require.NotNil(t, at) + local := at.In(walletDisplayLocation) + assert.Equal(t, "23:59:59", local.Format("15:04:05"), "a lot lasts to the end of its day") + return local.Format("2006-01-02") +} + +func fixedDate(dates ...string) models.LoyaltyExpirySettings { + return models.LoyaltyExpirySettings{Enabled: true, Mode: "FIXED_DATE", FixedDates: dates, GraceMonths: 3} +} + +func rolling(period int64, unit string, endOfMonth bool) models.LoyaltyExpirySettings { + return models.LoyaltyExpirySettings{Enabled: true, Mode: "ROLLING", Period: period, Unit: unit, EndOfMonth: endOfMonth} +} + +func TestComputeExpiry_OffNeverExpires(t *testing.T) { + s := fixedDate("12-31") + s.Enabled = false + assert.Nil(t, ComputeExpiry(s, wib(2026, 5, 1, 10, 0))) +} + +func TestComputeExpiry_FixedDateWithGrace(t *testing.T) { + yearly := fixedDate("12-31") + for received, want := range map[time.Time]string{ + wib(2026, 1, 15, 9, 0): "2026-12-31", + wib(2026, 9, 30, 23, 0): "2026-12-31", // 30 Dec + nothing: still this year + wib(2026, 10, 1, 0, 30): "2027-12-31", // within 3 months of 31 Dec: next year + wib(2026, 12, 31, 8, 0): "2027-12-31", + } { + assert.Equal(t, want, expiryDay(t, ComputeExpiry(yearly, received)), received.String()) + } + + twice := fixedDate("12-31", "06-30") + assert.Equal(t, "2026-06-30", expiryDay(t, ComputeExpiry(twice, wib(2026, 3, 1, 12, 0)))) + assert.Equal(t, "2026-12-31", expiryDay(t, ComputeExpiry(twice, wib(2026, 4, 1, 12, 0)))) + assert.Equal(t, "2027-06-30", expiryDay(t, ComputeExpiry(twice, wib(2026, 10, 1, 12, 0)))) + + noGrace := fixedDate("12-31") + noGrace.GraceMonths = 0 + assert.Equal(t, "2026-12-31", expiryDay(t, ComputeExpiry(noGrace, wib(2026, 12, 31, 22, 0)))) +} + +// The day received is the customer's day: 20:00 UTC on 31 Mar is already 1 Apr in WIB. +func TestComputeExpiry_UsesTheCustomersDay(t *testing.T) { + received := time.Date(2026, 3, 31, 20, 0, 0, 0, time.UTC) + assert.Equal(t, "2026-04-11", expiryDay(t, ComputeExpiry(rolling(10, "DAY", false), received))) +} + +func TestComputeExpiry_Rolling(t *testing.T) { + assert.Equal(t, "2027-03-14", expiryDay(t, ComputeExpiry(rolling(12, "MONTH", false), wib(2026, 3, 14, 10, 0)))) + assert.Equal(t, "2027-03-31", expiryDay(t, ComputeExpiry(rolling(12, "MONTH", true), wib(2026, 3, 14, 10, 0)))) + assert.Equal(t, "2026-03-24", expiryDay(t, ComputeExpiry(rolling(10, "DAY", false), wib(2026, 3, 14, 10, 0)))) + // A month that is shorter keeps to its last day. + assert.Equal(t, "2026-02-28", expiryDay(t, ComputeExpiry(rolling(1, "MONTH", false), wib(2026, 1, 31, 10, 0)))) +} + +func TestActivationExpiry(t *testing.T) { + // FIXED_DATE: the second fixed date after activation, so nobody loses a balance + // weeks after the rule is announced. + assert.Equal(t, "2027-12-31", expiryDay(t, ActivationExpiry(fixedDate("12-31"), wib(2026, 11, 20, 10, 0)))) + assert.Equal(t, "2027-12-31", expiryDay(t, ActivationExpiry(fixedDate("12-31"), wib(2026, 12, 31, 10, 0)))) + assert.Equal(t, "2027-06-30", expiryDay(t, ActivationExpiry(fixedDate("06-30", "12-31"), wib(2026, 11, 20, 10, 0)))) + // ROLLING: a full period from activation. + assert.Equal(t, "2027-11-20", expiryDay(t, ActivationExpiry(rolling(12, "MONTH", false), wib(2026, 11, 20, 10, 0)))) +} + +func TestRefundExpiry(t *testing.T) { + now := wib(2026, 6, 1, 10, 0) + later := wib(2026, 12, 31, 23, 59) + soon := wib(2026, 6, 3, 23, 59) + past := wib(2026, 5, 1, 23, 59) + + assert.Nil(t, RefundExpiry(nil, now)) + assert.Equal(t, &later, RefundExpiry(&later, now)) + assert.Equal(t, "2026-06-08", expiryDay(t, RefundExpiry(&soon, now))) + assert.Equal(t, "2026-06-08", expiryDay(t, RefundExpiry(&past, now))) +} + +func TestEarlierExpiry(t *testing.T) { + a, b := wib(2026, 1, 1, 0, 0), wib(2026, 2, 1, 0, 0) + assert.Equal(t, &a, EarlierExpiry(&a, &b)) + assert.Equal(t, &a, EarlierExpiry(&b, &a)) + assert.Equal(t, &a, EarlierExpiry(nil, &a)) + assert.Equal(t, &a, EarlierExpiry(&a, nil)) + assert.Nil(t, EarlierExpiry(nil, nil)) +} + +func TestNormalizeDaysOfYear(t *testing.T) { + days, err := normalizeDaysOfYear([]string{" 12-31", "06-30", "12-31", ""}) + require.NoError(t, err) + assert.Equal(t, []string{"06-30", "12-31"}, days) + for _, bad := range [][]string{{}, {"13-01"}, {"12-32"}, {"1-31"}, {"02-29"}, {"31-12"}} { + _, err := normalizeDaysOfYear(bad) + assert.Error(t, err, bad) + } +} diff --git a/internal/processor/loyalty_settings_processor.go b/internal/processor/loyalty_settings_processor.go new file mode 100644 index 0000000..2b78e45 --- /dev/null +++ b/internal/processor/loyalty_settings_processor.go @@ -0,0 +1,530 @@ +package processor + +import ( + "context" + "errors" + "fmt" + "strconv" + "strings" + "time" + + "github.com/google/uuid" + + "apskel-pos-be/internal/constants" + "apskel-pos-be/internal/entities" + "apskel-pos-be/internal/logger" + "apskel-pos-be/internal/models" + "apskel-pos-be/internal/repository" +) + +// ErrInvalidLoyaltySettings wraps every rejection of a setting that breaks the rules in +// docs/prd-point-coin.md F1, F2 and F12. +var ErrInvalidLoyaltySettings = errors.New("invalid loyalty settings") + +// LoyaltySettingsProcessor reads and writes the loyalty settings of outlets (F1) and +// organizations (F2, F12). Reads always return every setting, with the PRD default for +// a key that was never set, so callers never handle a missing value. Every write +// records what changed in loyalty_setting_changes. +type LoyaltySettingsProcessor struct { + repo repository.LoyaltySettingsRepository + tx TxRunner + now func() time.Time +} + +func NewLoyaltySettingsProcessor(repo repository.LoyaltySettingsRepository, tx TxRunner) *LoyaltySettingsProcessor { + return &LoyaltySettingsProcessor{repo: repo, tx: tx, now: time.Now} +} + +// Outlet returns an outlet's settings. +func (p *LoyaltySettingsProcessor) Outlet(ctx context.Context, outletID uuid.UUID) (*models.OutletLoyaltySettings, error) { + raw, err := p.repo.GetOutletValues(ctx, outletID) + if err != nil { + return nil, err + } + var s models.OutletLoyaltySettings + loadLoyaltyFields(outletLoyaltyFields(&s), raw, "outlet "+outletID.String()) + return &s, nil +} + +// OutletForOrganization returns an outlet's settings for the dashboard, and +// repository.ErrLoyaltyOutletNotFound unless the outlet belongs to the organization. +func (p *LoyaltySettingsProcessor) OutletForOrganization(ctx context.Context, organizationID, outletID uuid.UUID) (*models.OutletLoyaltySettings, error) { + owner, err := p.repo.OutletOrganizationID(ctx, outletID) + if err != nil { + return nil, err + } + if owner != organizationID { + return nil, repository.ErrLoyaltyOutletNotFound + } + return p.Outlet(ctx, outletID) +} + +// Organization returns an organization's settings. +func (p *LoyaltySettingsProcessor) Organization(ctx context.Context, organizationID uuid.UUID) (*models.OrganizationLoyaltySettings, error) { + raw, err := p.repo.GetOrganizationValues(ctx, organizationID) + if err != nil { + return nil, err + } + var s models.OrganizationLoyaltySettings + loadLoyaltyFields(organizationLoyaltyFields(&s), raw, "organization "+organizationID.String()) + return &s, nil +} + +// PointValue is the rupiah value of one EnakPoint in an organization. +func (p *LoyaltySettingsProcessor) PointValue(ctx context.Context, organizationID uuid.UUID) (int64, error) { + s, err := p.Organization(ctx, organizationID) + if err != nil { + return 0, err + } + return s.PointValue, nil +} + +// UpdateOutlet replaces an outlet's settings and returns what changed. The outlet must +// belong to the organization; otherwise repository.ErrLoyaltyOutletNotFound. +func (p *LoyaltySettingsProcessor) UpdateOutlet(ctx context.Context, organizationID, outletID, changedBy uuid.UUID, settings models.OutletLoyaltySettings) ([]models.LoyaltySettingChange, error) { + if err := validateLoyaltyFields(outletLoyaltyFields(&settings)); err != nil { + return nil, err + } + var changes []models.LoyaltySettingChange + err := p.tx.WithTransaction(ctx, func(ctx context.Context) error { + owner, err := p.repo.OutletOrganizationID(ctx, outletID) + if err != nil { + return err + } + if owner != organizationID { + return repository.ErrLoyaltyOutletNotFound + } + if err := p.repo.LockScope(ctx, outletID); err != nil { + return err + } + raw, err := p.repo.GetOutletValues(ctx, outletID) + if err != nil { + return err + } + var current models.OutletLoyaltySettings + loadLoyaltyFields(outletLoyaltyFields(¤t), raw, "outlet "+outletID.String()) + + changes, err = p.apply(ctx, organizationID, &outletID, changedBy, raw, + outletLoyaltyFields(¤t), outletLoyaltyFields(&settings), + func(key string, value *string) error { return p.repo.SetOutletValue(ctx, outletID, key, value) }) + return err + }) + return changes, err +} + +// UpdateOrganization replaces an organization's settings and returns what changed. +// +// Turning expiry on for a currency for the first time also gives every existing lot +// without an expiry the activation expiry (F12, note N4), and the result lists them. +func (p *LoyaltySettingsProcessor) UpdateOrganization(ctx context.Context, organizationID, changedBy uuid.UUID, settings models.OrganizationLoyaltySettings) ([]models.LoyaltySettingChange, []models.LoyaltyExpiryActivation, error) { + if err := validateLoyaltyFields(organizationLoyaltyFields(&settings)); err != nil { + return nil, nil, err + } + var changes []models.LoyaltySettingChange + var activations []models.LoyaltyExpiryActivation + err := p.tx.WithTransaction(ctx, func(ctx context.Context) error { + if err := p.repo.LockScope(ctx, organizationID); err != nil { + return err + } + raw, err := p.repo.GetOrganizationValues(ctx, organizationID) + if err != nil { + return err + } + var current models.OrganizationLoyaltySettings + loadLoyaltyFields(organizationLoyaltyFields(¤t), raw, "organization "+organizationID.String()) + + changes, err = p.apply(ctx, organizationID, nil, changedBy, raw, + organizationLoyaltyFields(¤t), organizationLoyaltyFields(&settings), + func(key string, value *string) error { + return p.repo.SetOrganizationValue(ctx, organizationID, key, value) + }) + if err != nil { + return err + } + activations, err = p.expiryActivations(ctx, organizationID, current, settings, true) + return err + }) + if err != nil { + return nil, nil, err + } + return changes, activations, nil +} + +// expiryActivations lists the currencies whose expiry these settings turn on, with the +// balances that have no expiry yet and the expiry they get: a full period from now +// (note N4, decided). With apply, it dates those lots. +func (p *LoyaltySettingsProcessor) expiryActivations(ctx context.Context, organizationID uuid.UUID, before, after models.OrganizationLoyaltySettings, apply bool) ([]models.LoyaltyExpiryActivation, error) { + activations := []models.LoyaltyExpiryActivation{} + for _, currency := range []string{constants.WalletCurrencyPoint, constants.WalletCurrencyCoin} { + was, will := ExpirySettings(&before, currency), ExpirySettings(&after, currency) + if was.Enabled || !will.Enabled { + continue + } + expiresAt := *ActivationExpiry(will, p.now()) + var lots, amount int64 + var err error + if apply { + lots, amount, err = p.repo.DateUndatedLots(ctx, organizationID, currency, expiresAt) + } else { + lots, amount, err = p.repo.UndatedBalance(ctx, organizationID, currency) + } + if err != nil { + return nil, err + } + activations = append(activations, models.LoyaltyExpiryActivation{Currency: currency, Lots: lots, Amount: amount, ExpiresAt: expiresAt}) + } + return activations, nil +} + +// apply stores every field whose effective value changes and records it. A key left +// on its default and not changed is not written, so the history only shows real +// changes. current and next list the same keys in the same order. +func (p *LoyaltySettingsProcessor) apply(ctx context.Context, organizationID uuid.UUID, outletID *uuid.UUID, changedBy uuid.UUID, raw map[string]string, current, next []loyaltyField, store func(key string, value *string) error) ([]models.LoyaltySettingChange, error) { + rows := diffLoyaltyFields(organizationID, outletID, changedBy, raw, current, next) + for _, row := range rows { + if err := store(row.Key, row.NewValue); err != nil { + return nil, err + } + } + if err := p.repo.InsertChanges(ctx, rows); err != nil { + return nil, err + } + changes := make([]models.LoyaltySettingChange, 0, len(rows)) + for _, row := range rows { + changes = append(changes, loyaltySettingChangeModel(row)) + } + return changes, nil +} + +// ListChanges returns a page of an organization's settings history, newest first. +// A nil outlet lists the whole organization, outlets included. +func (p *LoyaltySettingsProcessor) ListChanges(ctx context.Context, organizationID uuid.UUID, outletID *uuid.UUID, page, limit int) (*models.PaginatedResponse[models.LoyaltySettingChange], error) { + if page < 1 { + page = 1 + } + if limit < 1 || limit > 100 { + limit = 20 + } + rows, total, err := p.repo.ListChanges(ctx, repository.LoyaltySettingChangeFilter{ + OrganizationID: organizationID, OutletID: outletID, Offset: (page - 1) * limit, Limit: limit, + }) + if err != nil { + return nil, err + } + items := make([]models.LoyaltySettingChange, 0, len(rows)) + for _, row := range rows { + items = append(items, loyaltySettingChangeModel(row)) + } + return &models.PaginatedResponse[models.LoyaltySettingChange]{ + Data: items, + Pagination: models.Pagination{ + Page: page, Limit: limit, Total: total, TotalPages: int((total + int64(limit) - 1) / int64(limit)), + }, + }, nil +} + +func loyaltySettingChangeModel(row entities.LoyaltySettingChange) models.LoyaltySettingChange { + return models.LoyaltySettingChange{ + ID: row.ID, + OrganizationID: row.OrganizationID, + OutletID: row.OutletID, + Key: row.Key, + OldValue: row.OldValue, + NewValue: row.NewValue, + ChangedBy: row.ChangedBy, + CreatedAt: row.CreatedAt, + } +} + +// outletLoyaltyFields describes every outlet key (F1), bound to s. +func outletLoyaltyFields(s *models.OutletLoyaltySettings) []loyaltyField { + return []loyaltyField{ + boolLoyaltyField(constants.LoyaltyPointEnabledKey, &s.Point.Enabled, false), + intLoyaltyField(constants.LoyaltyPointEarnPerAmountKey, &s.Point.EarnPerAmount, constants.LoyaltyPointEarnPerAmountDefault, 1, noLoyaltyMax), + intLoyaltyField(constants.LoyaltyPointEarnValueKey, &s.Point.EarnValue, constants.LoyaltyEarnValueDefault, 0, noLoyaltyMax), + intLoyaltyField(constants.LoyaltyPointMinOrderAmountKey, &s.Point.MinOrderAmount, 0, 0, noLoyaltyMax), + optionalIntLoyaltyField(constants.LoyaltyPointMaxPerOrderKey, &s.Point.MaxPerOrder, 0), + + boolLoyaltyField(constants.LoyaltyCoinEnabledKey, &s.Coin.Enabled, false), + intLoyaltyField(constants.LoyaltyCoinEarnPerAmountKey, &s.Coin.EarnPerAmount, constants.LoyaltyCoinEarnPerAmountDefault, 1, noLoyaltyMax), + intLoyaltyField(constants.LoyaltyCoinEarnValueKey, &s.Coin.EarnValue, constants.LoyaltyEarnValueDefault, 0, noLoyaltyMax), + intLoyaltyField(constants.LoyaltyCoinMinOrderAmountKey, &s.Coin.MinOrderAmount, 0, 0, noLoyaltyMax), + optionalIntLoyaltyField(constants.LoyaltyCoinMaxPerOrderKey, &s.Coin.MaxPerOrder, 0), + + boolLoyaltyField(constants.LoyaltyPointAcceptPaymentKey, &s.PointPayment.AcceptPayment, false), + intLoyaltyField(constants.LoyaltyPointMinPaymentPointsKey, &s.PointPayment.MinPaymentPoints, constants.LoyaltyMinPaymentPointsDefault, 1, noLoyaltyMax), + intLoyaltyField(constants.LoyaltyPointMaxPaymentPercentKey, &s.PointPayment.MaxPaymentPercent, constants.LoyaltyMaxPaymentPercentDefault, 0, 100), + } +} + +// organizationLoyaltyFields describes every organization key (F2, F12), bound to s. +func organizationLoyaltyFields(s *models.OrganizationLoyaltySettings) []loyaltyField { + fields := []loyaltyField{ + intLoyaltyField(constants.LoyaltyPointValueKey, &s.PointValue, constants.LoyaltyPointValueDefault, 1, noLoyaltyMax), + intLoyaltyField(constants.LoyaltyExchangeCoinAmountKey, &s.Exchange.CoinAmount, constants.LoyaltyExchangeAmountDefault, 1, noLoyaltyMax), + intLoyaltyField(constants.LoyaltyExchangePointAmountKey, &s.Exchange.PointAmount, constants.LoyaltyExchangeAmountDefault, 1, noLoyaltyMax), + boolLoyaltyField(constants.LoyaltyTransferEnabledKey, &s.Transfer.Enabled, constants.LoyaltyTransferEnabledDefault), + intLoyaltyField(constants.LoyaltyTransferMinAmountKey, &s.Transfer.MinAmount, constants.LoyaltyTransferMinAmountDefault, 1, noLoyaltyMax), + optionalIntLoyaltyField(constants.LoyaltyTransferMaxPerTransactionKey, &s.Transfer.MaxPerTransaction, 1), + optionalIntLoyaltyField(constants.LoyaltyTransferDailyLimitKey, &s.Transfer.DailyLimit, 1), + } + fields = append(fields, expiryLoyaltyFields("loyalty.point.", &s.PointExpiry)...) + return append(fields, expiryLoyaltyFields("loyalty.coin.", &s.CoinExpiry)...) +} + +func expiryLoyaltyFields(prefix string, s *models.LoyaltyExpirySettings) []loyaltyField { + return []loyaltyField{ + boolLoyaltyField(prefix+constants.LoyaltyExpiryEnabledSuffix, &s.Enabled, false), + enumLoyaltyField(prefix+constants.LoyaltyExpiryModeSuffix, &s.Mode, constants.LoyaltyExpiryModeDefault, + constants.LoyaltyExpiryModeFixedDate, constants.LoyaltyExpiryModeRolling), + dayOfYearListLoyaltyField(prefix+constants.LoyaltyExpiryFixedDatesSuffix, &s.FixedDates, constants.LoyaltyExpiryFixedDatesDefault), + intLoyaltyField(prefix+constants.LoyaltyExpiryGraceMonthsSuffix, &s.GraceMonths, constants.LoyaltyExpiryGraceMonthsDefault, 0, loyaltyExpiryMaxGraceMonths), + intLoyaltyField(prefix+constants.LoyaltyExpiryPeriodSuffix, &s.Period, constants.LoyaltyExpiryPeriodDefault, 1, noLoyaltyMax), + enumLoyaltyField(prefix+constants.LoyaltyExpiryUnitSuffix, &s.Unit, constants.LoyaltyExpiryUnitDefault, + constants.LoyaltyExpiryUnitDay, constants.LoyaltyExpiryUnitMonth), + boolLoyaltyField(prefix+constants.LoyaltyExpiryEndOfMonthSuffix, &s.EndOfMonth, false), + intLoyaltyField(prefix+constants.LoyaltyExpiryReminderDaysSuffix, &s.ReminderDays, constants.LoyaltyExpiryReminderDaysDefault, 0, noLoyaltyMax), + } +} + +// loyaltyField is one setting key bound to the struct field that holds it. The same +// description drives reading (parse or default), validating, and writing (format). +type loyaltyField struct { + key string + // parse sets the field from a stored value, or reports it unusable. + parse func(raw string) bool + // reset sets the field to its default. + reset func() + // validate checks the field's current value. + validate func() error + // format is the field's current value as stored; nil means no stored value. + format func() *string +} + +const noLoyaltyMax = int64(-1) + +func intLoyaltyField(key string, v *int64, def, min, max int64) loyaltyField { + check := func(n int64) error { + if n < min { + return fmt.Errorf("%w: %s must be at least %d", ErrInvalidLoyaltySettings, key, min) + } + if max != noLoyaltyMax && n > max { + return fmt.Errorf("%w: %s must be at most %d", ErrInvalidLoyaltySettings, key, max) + } + return nil + } + return loyaltyField{ + key: key, + parse: func(raw string) bool { + n, err := strconv.ParseInt(strings.TrimSpace(raw), 10, 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.FormatInt(*v, 10); return &s }, + } +} + +// optionalIntLoyaltyField is a limit that may be unset, meaning no limit. +func optionalIntLoyaltyField(key string, v **int64, min int64) loyaltyField { + return loyaltyField{ + key: key, + parse: func(raw string) bool { + n, err := strconv.ParseInt(strings.TrimSpace(raw), 10, 64) + if err != nil || n < min { + return false + } + *v = &n + return true + }, + reset: func() { *v = nil }, + validate: func() error { + if *v != nil && **v < min { + return fmt.Errorf("%w: %s must be at least %d, or empty for no limit", ErrInvalidLoyaltySettings, key, min) + } + return nil + }, + format: func() *string { + if *v == nil { + return nil + } + s := strconv.FormatInt(**v, 10) + return &s + }, + } +} + +func boolLoyaltyField(key string, v *bool, def bool) loyaltyField { + return loyaltyField{ + key: key, + parse: func(raw string) bool { + b, err := strconv.ParseBool(strings.TrimSpace(raw)) + if err != nil { + return false + } + *v = b + return true + }, + reset: func() { *v = def }, + validate: func() error { return nil }, + format: func() *string { s := strconv.FormatBool(*v); return &s }, + } +} + +func enumLoyaltyField(key string, v *string, def string, allowed ...string) loyaltyField { + valid := func(s string) bool { + for _, a := range allowed { + if s == a { + return true + } + } + return false + } + return loyaltyField{ + key: key, + parse: func(raw string) bool { + s := strings.ToUpper(strings.TrimSpace(raw)) + if !valid(s) { + return false + } + *v = s + return true + }, + reset: func() { *v = def }, + validate: func() error { + if !valid(*v) { + return fmt.Errorf("%w: %s must be one of %s", ErrInvalidLoyaltySettings, key, strings.Join(allowed, ", ")) + } + return nil + }, + format: func() *string { s := *v; return &s }, + } +} + +// dayOfYearListLoyaltyField is a non-empty set of days of the year, stored as sorted +// MM-DD values joined by commas, such as "06-30,12-31". +func dayOfYearListLoyaltyField(key string, v *[]string, def string) loyaltyField { + normalize := func(days []string) ([]string, error) { + out, err := normalizeDaysOfYear(days) + if err != nil { + return nil, fmt.Errorf("%w: %s %v", ErrInvalidLoyaltySettings, key, err) + } + return out, nil + } + return loyaltyField{ + key: key, + parse: func(raw string) bool { + days, err := normalize(strings.Split(raw, ",")) + if err != nil { + return false + } + *v = days + return true + }, + reset: func() { *v, _ = normalizeDaysOfYear(strings.Split(def, ",")) }, + validate: func() error { + days, err := normalize(*v) + if err != nil { + return err + } + *v = days + return nil + }, + format: func() *string { + days, err := normalizeDaysOfYear(*v) + if err != nil { + days = *v + } + s := strings.Join(days, ",") + return &s + }, + } +} + +// loadLoyaltyFields fills each field from its stored value, or its default when there +// is none. A stored value that cannot be used also falls back to the default, so a bad +// row can never reach a calculation, and it is logged so it gets fixed. +func loadLoyaltyFields(fields []loyaltyField, raw map[string]string, scope string) { + for _, f := range fields { + f.reset() + value, ok := raw[f.key] + if !ok { + continue + } + if !f.parse(value) { + f.reset() + logger.NonContext.Warnf("Loyalty setting %s of %s has an unusable value %q; using the default", f.key, scope, value) + } + } +} + +func validateLoyaltyFields(fields []loyaltyField) error { + for _, f := range fields { + if err := f.validate(); err != nil { + return err + } + } + return nil +} + +func equalOptionalStrings(a, b *string) bool { + if a == nil || b == nil { + return a == nil && b == nil + } + return *a == *b +} + +// diffLoyaltyFields lists the keys whose effective value differs between current and +// next, with the stored old value (nil when the key was on its default). current and +// next list the same keys in the same order. +func diffLoyaltyFields(organizationID uuid.UUID, outletID *uuid.UUID, changedBy uuid.UUID, raw map[string]string, current, next []loyaltyField) []entities.LoyaltySettingChange { + var rows []entities.LoyaltySettingChange + for i, field := range next { + newValue := field.format() + if equalOptionalStrings(current[i].format(), newValue) { + continue + } + var oldValue *string + if v, ok := raw[field.key]; ok { + oldValue = &v + } + rows = append(rows, entities.LoyaltySettingChange{ + OrganizationID: organizationID, + OutletID: outletID, + Key: field.key, + OldValue: oldValue, + NewValue: newValue, + ChangedBy: changedBy, + }) + } + return rows +} + +// PreviewOrganization validates new organization settings and lists what saving them +// would change, and which balances turning expiry on would date, without writing +// anything. +func (p *LoyaltySettingsProcessor) PreviewOrganization(ctx context.Context, organizationID uuid.UUID, settings models.OrganizationLoyaltySettings) ([]models.LoyaltySettingChange, []models.LoyaltyExpiryActivation, error) { + if err := validateLoyaltyFields(organizationLoyaltyFields(&settings)); err != nil { + return nil, nil, err + } + raw, err := p.repo.GetOrganizationValues(ctx, organizationID) + if err != nil { + return nil, nil, err + } + var current models.OrganizationLoyaltySettings + loadLoyaltyFields(organizationLoyaltyFields(¤t), raw, "organization "+organizationID.String()) + rows := diffLoyaltyFields(organizationID, nil, uuid.Nil, raw, organizationLoyaltyFields(¤t), organizationLoyaltyFields(&settings)) + changes := make([]models.LoyaltySettingChange, 0, len(rows)) + for _, row := range rows { + changes = append(changes, loyaltySettingChangeModel(row)) + } + activations, err := p.expiryActivations(ctx, organizationID, current, settings, false) + if err != nil { + return nil, nil, err + } + return changes, activations, nil +} diff --git a/internal/processor/loyalty_settings_processor_test.go b/internal/processor/loyalty_settings_processor_test.go new file mode 100644 index 0000000..ecbdb1e --- /dev/null +++ b/internal/processor/loyalty_settings_processor_test.go @@ -0,0 +1,385 @@ +package processor + +import ( + "context" + "os" + "testing" + "time" + + "github.com/google/uuid" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "apskel-pos-be/internal/constants" + "apskel-pos-be/internal/entities" + "apskel-pos-be/internal/logger" + "apskel-pos-be/internal/models" + "apskel-pos-be/internal/repository" +) + +func TestMain(m *testing.M) { + // Some processors log; the server sets the logger up at startup. + logger.Setup("fatal", "json") + os.Exit(m.Run()) +} + +// loyaltyRepoFake keeps settings in maps. It does not check for a transaction. +type loyaltyRepoFake struct { + outletOrg map[uuid.UUID]uuid.UUID + outletValues map[string]string + orgValues map[string]string + changes []entities.LoyaltySettingChange + locks []uuid.UUID + // Lots without an expiry per currency: how many and what they hold. + undated map[string][2]int64 + dated map[string]time.Time +} + +func (f *loyaltyRepoFake) GetOutletValues(context.Context, uuid.UUID) (map[string]string, error) { + return copyStringMap(f.outletValues), nil +} + +func (f *loyaltyRepoFake) GetOrganizationValues(context.Context, uuid.UUID) (map[string]string, error) { + return copyStringMap(f.orgValues), nil +} + +func (f *loyaltyRepoFake) OutletOrganizationID(_ context.Context, outletID uuid.UUID) (uuid.UUID, error) { + org, ok := f.outletOrg[outletID] + if !ok { + return uuid.Nil, repository.ErrLoyaltyOutletNotFound + } + return org, nil +} + +func (f *loyaltyRepoFake) LockScope(_ context.Context, id uuid.UUID) error { + f.locks = append(f.locks, id) + return nil +} + +func (f *loyaltyRepoFake) SetOutletValue(_ context.Context, _ uuid.UUID, key string, value *string) error { + f.outletValues = setOptional(f.outletValues, key, value) + return nil +} + +func (f *loyaltyRepoFake) SetOrganizationValue(_ context.Context, _ uuid.UUID, key string, value *string) error { + f.orgValues = setOptional(f.orgValues, key, value) + return nil +} + +func (f *loyaltyRepoFake) InsertChanges(_ context.Context, changes []entities.LoyaltySettingChange) error { + f.changes = append(f.changes, changes...) + return nil +} + +func (f *loyaltyRepoFake) ListChanges(context.Context, repository.LoyaltySettingChangeFilter) ([]entities.LoyaltySettingChange, int64, error) { + return f.changes, int64(len(f.changes)), nil +} + +func copyStringMap(m map[string]string) map[string]string { + out := make(map[string]string, len(m)) + for k, v := range m { + out[k] = v + } + return out +} + +func setOptional(m map[string]string, key string, value *string) map[string]string { + if m == nil { + m = map[string]string{} + } + if value == nil { + delete(m, key) + } else { + m[key] = *value + } + return m +} + +// txRunnerFake runs fn in place. +type txRunnerFake struct{} + +func (txRunnerFake) WithTransaction(ctx context.Context, fn func(ctx context.Context) error) error { + return fn(ctx) +} + +func TestLoyaltySettings_OutletWithoutSettingsGetsEveryDefault(t *testing.T) { + p := NewLoyaltySettingsProcessor(&loyaltyRepoFake{}, txRunnerFake{}) + 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}, + PointPayment: models.LoyaltyPointPaymentSettings{AcceptPayment: false, MinPaymentPoints: 1, MaxPaymentPercent: 100}, + }, *s) +} + +func TestLoyaltySettings_OrganizationWithoutSettingsGetsEveryDefault(t *testing.T) { + p := NewLoyaltySettingsProcessor(&loyaltyRepoFake{}, txRunnerFake{}) + s, err := p.Organization(context.Background(), uuid.New()) + require.NoError(t, err) + expiry := models.LoyaltyExpirySettings{Enabled: false, Mode: "FIXED_DATE", FixedDates: []string{"12-31"}, GraceMonths: 3, Period: 12, Unit: "MONTH", EndOfMonth: false, ReminderDays: 7} + assert.Equal(t, models.OrganizationLoyaltySettings{ + PointValue: 1, + Exchange: models.LoyaltyExchangeSettings{CoinAmount: 1, PointAmount: 1}, + Transfer: models.LoyaltyTransferSettings{Enabled: true, MinAmount: 1}, + PointExpiry: expiry, + CoinExpiry: expiry, + }, *s) +} + +func TestLoyaltySettings_StoredValuesAreTyped(t *testing.T) { + repo := &loyaltyRepoFake{ + outletValues: map[string]string{ + constants.LoyaltyPointEnabledKey: "true", + constants.LoyaltyPointEarnPerAmountKey: " 1000 ", + constants.LoyaltyPointMaxPerOrderKey: "500", + constants.LoyaltyPointMaxPaymentPercentKey: "50", + "loyalty.unknown": "ignored", + }, + orgValues: map[string]string{ + constants.LoyaltyPointValueKey: "100", + constants.LoyaltyTransferDailyLimitKey: "10000", + "loyalty.coin.expiry_unit": "day", + "loyalty.point.expiry_fixed_dates": "12-31, 06-30,12-31", + "loyalty.coin.expiry_mode": "rolling", + }, + } + p := NewLoyaltySettingsProcessor(repo, txRunnerFake{}) + + outlet, err := p.Outlet(context.Background(), uuid.New()) + require.NoError(t, err) + assert.True(t, outlet.Point.Enabled) + assert.Equal(t, int64(1000), outlet.Point.EarnPerAmount) + assert.Equal(t, int64(500), *outlet.Point.MaxPerOrder) + assert.Equal(t, int64(50), outlet.PointPayment.MaxPaymentPercent) + + org, err := p.Organization(context.Background(), uuid.New()) + require.NoError(t, err) + assert.Equal(t, int64(100), org.PointValue) + assert.Equal(t, int64(10000), *org.Transfer.DailyLimit) + assert.Equal(t, "DAY", org.CoinExpiry.Unit) + assert.Equal(t, "MONTH", org.PointExpiry.Unit) + assert.Equal(t, []string{"06-30", "12-31"}, org.PointExpiry.FixedDates) + assert.Equal(t, "ROLLING", org.CoinExpiry.Mode) + assert.Equal(t, "FIXED_DATE", org.PointExpiry.Mode) +} + +// A bad row must never reach a calculation: earn_per_amount 0 would divide by zero. +func TestLoyaltySettings_UnusableStoredValuesFallBackToDefault(t *testing.T) { + repo := &loyaltyRepoFake{ + outletValues: map[string]string{ + constants.LoyaltyPointEnabledKey: "yes please", + constants.LoyaltyPointEarnPerAmountKey: "0", + constants.LoyaltyCoinEarnValueKey: "-1", + constants.LoyaltyPointMaxPerOrderKey: "abc", + constants.LoyaltyPointMaxPaymentPercentKey: "150", + }, + orgValues: map[string]string{ + constants.LoyaltyPointValueKey: "0", + "loyalty.point.expiry_unit": "YEAR", + "loyalty.point.expiry_period": "", + }, + } + p := NewLoyaltySettingsProcessor(repo, txRunnerFake{}) + + outlet, err := p.Outlet(context.Background(), uuid.New()) + require.NoError(t, err) + assert.False(t, outlet.Point.Enabled) + assert.Equal(t, int64(100), outlet.Point.EarnPerAmount) + assert.Equal(t, int64(1), outlet.Coin.EarnValue) + assert.Nil(t, outlet.Point.MaxPerOrder) + assert.Equal(t, int64(100), outlet.PointPayment.MaxPaymentPercent) + + for name, raw := range map[string]string{"not set": "", "garbage": "abc", "zero": "0", "negative": "-5"} { + repo.orgValues = map[string]string{} + if raw != "" { + repo.orgValues[constants.LoyaltyPointValueKey] = raw + } + value, err := p.PointValue(context.Background(), uuid.New()) + require.NoError(t, err) + assert.Equal(t, constants.LoyaltyPointValueDefault, value, name) + } +} + +func TestLoyaltySettings_UpdateRecordsOnlyRealChanges(t *testing.T) { + org, outlet, admin := uuid.New(), uuid.New(), uuid.New() + repo := &loyaltyRepoFake{ + outletOrg: map[uuid.UUID]uuid.UUID{outlet: org}, + outletValues: map[string]string{constants.LoyaltyPointEarnPerAmountKey: "200"}, + } + p := NewLoyaltySettingsProcessor(repo, txRunnerFake{}) + ctx := context.Background() + + settings, err := p.Outlet(ctx, outlet) + require.NoError(t, err) + settings.Point.Enabled = true // default false -> true + settings.Point.EarnPerAmount = 100 // stored 200 -> 100 (the default, but set explicitly) + settings.Point.MaxPerOrder = ptr(int64(0)) // unset -> 0 + // Everything else stays on its default. + + changes, err := p.UpdateOutlet(ctx, org, outlet, admin, *settings) + require.NoError(t, err) + byKey := map[string]models.LoyaltySettingChange{} + for _, c := range changes { + byKey[c.Key] = c + assert.Equal(t, admin, c.ChangedBy) + assert.Equal(t, org, c.OrganizationID) + assert.Equal(t, &outlet, c.OutletID) + } + require.Len(t, byKey, 3, "only the three keys that changed") + assert.Nil(t, byKey[constants.LoyaltyPointEnabledKey].OldValue, "was on its default") + assert.Equal(t, "true", *byKey[constants.LoyaltyPointEnabledKey].NewValue) + assert.Equal(t, "200", *byKey[constants.LoyaltyPointEarnPerAmountKey].OldValue) + assert.Equal(t, "100", *byKey[constants.LoyaltyPointEarnPerAmountKey].NewValue) + assert.Equal(t, "0", *byKey[constants.LoyaltyPointMaxPerOrderKey].NewValue) + assert.Len(t, repo.changes, 3) + assert.Equal(t, []uuid.UUID{outlet}, repo.locks) + + after, err := p.Outlet(ctx, outlet) + require.NoError(t, err) + assert.Equal(t, *settings, *after) + + // Saving the same settings again changes nothing and records nothing. + changes, err = p.UpdateOutlet(ctx, org, outlet, admin, *after) + require.NoError(t, err) + assert.Empty(t, changes) + assert.Len(t, repo.changes, 3) + + // Clearing a limit removes the stored value, recorded as a change to nothing. + after.Point.MaxPerOrder = nil + changes, err = p.UpdateOutlet(ctx, org, outlet, admin, *after) + require.NoError(t, err) + require.Len(t, changes, 1) + assert.Equal(t, "0", *changes[0].OldValue) + assert.Nil(t, changes[0].NewValue) + assert.NotContains(t, repo.outletValues, constants.LoyaltyPointMaxPerOrderKey) +} + +func TestLoyaltySettings_UpdateOrganization(t *testing.T) { + org, admin := uuid.New(), uuid.New() + repo := &loyaltyRepoFake{} + p := NewLoyaltySettingsProcessor(repo, txRunnerFake{}) + ctx := context.Background() + + settings, err := p.Organization(ctx, org) + require.NoError(t, err) + settings.PointValue = 100 + settings.CoinExpiry.Enabled = true + settings.CoinExpiry.Unit = constants.LoyaltyExpiryUnitDay + + changes, _, err := p.UpdateOrganization(ctx, org, admin, *settings) + require.NoError(t, err) + keys := []string{} + for _, c := range changes { + keys = append(keys, c.Key) + assert.Nil(t, c.OutletID, "organization settings have no outlet") + } + assert.ElementsMatch(t, []string{constants.LoyaltyPointValueKey, "loyalty.coin.expiry_enabled", "loyalty.coin.expiry_unit"}, keys) + + value, err := p.PointValue(ctx, org) + require.NoError(t, err) + assert.Equal(t, int64(100), value) +} + +func TestLoyaltySettings_UpdateRejectsInvalidValues(t *testing.T) { + org, outlet := uuid.New(), uuid.New() + repo := &loyaltyRepoFake{outletOrg: map[uuid.UUID]uuid.UUID{outlet: org}} + p := NewLoyaltySettingsProcessor(repo, txRunnerFake{}) + ctx := context.Background() + + 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 }, + "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 }, + "negative payment percent": func(s *models.OutletLoyaltySettings) { s.PointPayment.MaxPaymentPercent = -1 }, + "min payment points 0": func(s *models.OutletLoyaltySettings) { s.PointPayment.MinPaymentPoints = 0 }, + } { + s, err := p.Outlet(ctx, outlet) + require.NoError(t, err) + mutate(s) + _, err = p.UpdateOutlet(ctx, org, outlet, uuid.New(), *s) + assert.ErrorIs(t, err, ErrInvalidLoyaltySettings, name) + } + + for name, mutate := range map[string]func(*models.OrganizationLoyaltySettings){ + "point value 0": func(s *models.OrganizationLoyaltySettings) { s.PointValue = 0 }, + "exchange coin amount 0": func(s *models.OrganizationLoyaltySettings) { s.Exchange.CoinAmount = 0 }, + "transfer min 0": func(s *models.OrganizationLoyaltySettings) { s.Transfer.MinAmount = 0 }, + "daily limit 0": func(s *models.OrganizationLoyaltySettings) { s.Transfer.DailyLimit = ptr(int64(0)) }, + "expiry period 0": func(s *models.OrganizationLoyaltySettings) { s.PointExpiry.Period = 0 }, + "expiry unit YEAR": func(s *models.OrganizationLoyaltySettings) { s.CoinExpiry.Unit = "YEAR" }, + "negative reminder days": func(s *models.OrganizationLoyaltySettings) { s.CoinExpiry.ReminderDays = -1 }, + "expiry mode YEARLY": func(s *models.OrganizationLoyaltySettings) { s.PointExpiry.Mode = "YEARLY" }, + "no fixed dates": func(s *models.OrganizationLoyaltySettings) { s.PointExpiry.FixedDates = nil }, + "fixed date 13-01": func(s *models.OrganizationLoyaltySettings) { s.PointExpiry.FixedDates = []string{"13-01"} }, + "fixed date 02-29": func(s *models.OrganizationLoyaltySettings) { s.CoinExpiry.FixedDates = []string{"02-29"} }, + "negative grace": func(s *models.OrganizationLoyaltySettings) { s.CoinExpiry.GraceMonths = -1 }, + } { + s, err := p.Organization(ctx, org) + require.NoError(t, err) + mutate(s) + _, _, err = p.UpdateOrganization(ctx, org, uuid.New(), *s) + assert.ErrorIs(t, err, ErrInvalidLoyaltySettings, name) + } + assert.Empty(t, repo.changes, "nothing is written when a value is invalid") + assert.Empty(t, repo.locks, "invalid input is rejected before touching the database") + + // An outlet of another organization. + s, err := p.Outlet(ctx, outlet) + require.NoError(t, err) + _, err = p.UpdateOutlet(ctx, uuid.New(), outlet, uuid.New(), *s) + assert.ErrorIs(t, err, repository.ErrLoyaltyOutletNotFound) + _, err = p.UpdateOutlet(ctx, org, uuid.New(), uuid.New(), *s) + assert.ErrorIs(t, err, repository.ErrLoyaltyOutletNotFound) +} + +func (f *loyaltyRepoFake) UndatedBalance(_ context.Context, _ uuid.UUID, currency string) (int64, int64, error) { + u := f.undated[currency] + return u[0], u[1], nil +} + +func (f *loyaltyRepoFake) DateUndatedLots(_ context.Context, _ uuid.UUID, currency string, expiresAt time.Time) (int64, int64, error) { + u := f.undated[currency] + if f.dated == nil { + f.dated = map[string]time.Time{} + } + f.dated[currency] = expiresAt + delete(f.undated, currency) + return u[0], u[1], nil +} + +// Turning expiry on dates the balances that had none, a full cycle away; a dry run +// only counts them, and saving again dates nothing more. +func TestLoyaltySettings_TurningExpiryOnDatesExistingBalances(t *testing.T) { + org, admin := uuid.New(), uuid.New() + repo := &loyaltyRepoFake{undated: map[string][2]int64{"POINT": {3, 1500}, "COIN": {2, 40}}} + p := NewLoyaltySettingsProcessor(repo, txRunnerFake{}) + p.now = func() time.Time { return time.Date(2026, 11, 20, 3, 0, 0, 0, time.UTC) } + ctx := context.Background() + + settings, err := p.Organization(ctx, org) + require.NoError(t, err) + settings.PointExpiry.Enabled = true + + _, preview, err := p.PreviewOrganization(ctx, org, *settings) + require.NoError(t, err) + require.Len(t, preview, 1) + assert.Equal(t, "POINT", preview[0].Currency) + assert.Equal(t, int64(1500), preview[0].Amount) + assert.Empty(t, repo.dated, "a dry run dates nothing") + + _, activations, err := p.UpdateOrganization(ctx, org, admin, *settings) + require.NoError(t, err) + require.Len(t, activations, 1) + assert.Equal(t, int64(3), activations[0].Lots) + // Default FIXED_DATE on 31 Dec: the second one after 20 Nov 2026. + assert.Equal(t, "2027-12-31", activations[0].ExpiresAt.In(walletDisplayLocation).Format("2006-01-02")) + assert.Equal(t, activations[0].ExpiresAt, repo.dated["POINT"]) + assert.NotContains(t, repo.dated, "COIN", "EnakCoin expiry stays off") + + _, again, err := p.UpdateOrganization(ctx, org, admin, *settings) + require.NoError(t, err) + assert.Empty(t, again, "already on: nothing is activated twice") +} diff --git a/internal/processor/order_paid_hook_test.go b/internal/processor/order_paid_hook_test.go new file mode 100644 index 0000000..bed9ef9 --- /dev/null +++ b/internal/processor/order_paid_hook_test.go @@ -0,0 +1,272 @@ +package processor + +import ( + "context" + "testing" + + "github.com/google/uuid" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "apskel-pos-be/internal/entities" + "apskel-pos-be/internal/models" + "apskel-pos-be/internal/repository" +) + +// These fakes embed the interface they stand for and implement only what the paths +// under test call; anything else would panic, which would show a path doing more than +// expected. +type hookOrderRepo struct { + OrderRepository + order *entities.Order + statusUpdates int + hookCallsAtPay int // hook calls seen when the status was written + hook *orderPaidHookFake +} + +func (r *hookOrderRepo) GetByID(context.Context, uuid.UUID) (*entities.Order, error) { + o := *r.order + return &o, nil +} + +func (r *hookOrderRepo) GetWithRelations(context.Context, uuid.UUID) (*entities.Order, error) { + o := *r.order + return &o, nil +} + +func (r *hookOrderRepo) UpdateStatusSuccess(_ context.Context, _ uuid.UUID, status entities.OrderStatus, payment entities.PaymentStatus) error { + r.statusUpdates++ + r.hookCallsAtPay = len(r.hook.calls) + r.order.Status, r.order.PaymentStatus = status, payment + return nil +} + +type hookPaymentRepo struct { + PaymentRepository + created []*entities.Payment +} + +func (r *hookPaymentRepo) GetTotalPaidByOrderID(context.Context, uuid.UUID) (float64, error) { + return 0, nil +} + +func (r *hookPaymentRepo) Create(_ context.Context, p *entities.Payment) error { + p.ID = uuid.New() + r.created = append(r.created, p) + return nil +} + +func (r *hookPaymentRepo) GetByID(_ context.Context, id uuid.UUID) (*entities.Payment, error) { + for _, p := range r.created { + if p.ID == id { + return p, nil + } + } + return nil, nil +} + +func (r *hookPaymentRepo) GetByOrderID(context.Context, uuid.UUID) ([]*entities.Payment, error) { + return r.created, nil +} + +type hookPaymentMethodRepo struct{} + +func (hookPaymentMethodRepo) GetByID(_ context.Context, id uuid.UUID) (*entities.PaymentMethod, error) { + return &entities.PaymentMethod{ID: id}, nil +} + +type hookOrderItemRepo struct{ OrderItemRepository } + +func (hookOrderItemRepo) GetByOrderID(context.Context, uuid.UUID) ([]*entities.OrderItem, error) { + return nil, nil +} + +// splitFake settles the order on the payment that covers what is left, as the real +// split bill processor does. +type splitFake struct{ settle bool } + +func (f splitFake) split(order *entities.Order) (*models.SplitBillResponse, error) { + if f.settle { + order.PaymentStatus = entities.PaymentStatusCompleted + } else { + order.PaymentStatus = entities.PaymentStatusPartial + } + return &models.SplitBillResponse{OrderID: order.ID}, nil +} + +func (f splitFake) SplitByAmount(_ context.Context, _ *models.SplitBillRequest, order *entities.Order, _ *entities.PaymentMethod, _ *entities.Customer) (*models.SplitBillResponse, error) { + return f.split(order) +} + +func (f splitFake) SplitByItem(_ context.Context, _ *models.SplitBillRequest, order *entities.Order, _ *entities.PaymentMethod, _ *entities.Customer) (*models.SplitBillResponse, error) { + return f.split(order) +} + +type orderPaidHookFake struct { + calls []uuid.UUID + ctxs []context.Context + refunded []uuid.UUID + earned map[uuid.UUID]OrderEarned +} + +func (h *orderPaidHookFake) OnOrderPaid(ctx context.Context, orderID uuid.UUID) { + h.calls = append(h.calls, orderID) + h.ctxs = append(h.ctxs, ctx) +} + +func (h *orderPaidHookFake) OnOrderRefunded(_ context.Context, orderID uuid.UUID) { + h.refunded = append(h.refunded, orderID) +} + +func (h *orderPaidHookFake) EarnedByOrders(context.Context, []uuid.UUID) (map[uuid.UUID]OrderEarned, error) { + return h.earned, nil +} + +func newHookedOrderProcessor(split SplitBillProcessor) (*OrderProcessorImpl, *hookOrderRepo, *orderPaidHookFake) { + hook := &orderPaidHookFake{} + orders := &hookOrderRepo{ + order: &entities.Order{ID: uuid.New(), OrganizationID: uuid.New(), OutletID: uuid.New(), TotalAmount: 100000, PaymentStatus: entities.PaymentStatusPending}, + hook: hook, + } + p := &OrderProcessorImpl{ + orderRepo: orders, + orderItemRepo: hookOrderItemRepo{}, + paymentRepo: &hookPaymentRepo{}, + paymentMethodRepo: hookPaymentMethodRepo{}, + splitBillProcessor: split, + txManager: repository.NewTxManager(nil), + } + p.SetLoyalty(hook) + return p, orders, hook +} + +func TestOrderPaidHook_CreatePayment(t *testing.T) { + p, orders, hook := newHookedOrderProcessor(nil) + ctx, cancel := context.WithCancel(context.Background()) + + _, err := p.CreatePayment(ctx, &models.CreatePaymentRequest{OrderID: orders.order.ID, PaymentMethodID: uuid.New(), Amount: 100000}) + require.NoError(t, err) + assert.Equal(t, []uuid.UUID{orders.order.ID}, hook.calls) + assert.Zero(t, orders.hookCallsAtPay, "the hook runs after the payment, not inside its transaction") + + // The hook's context outlives the request. + cancel() + assert.NoError(t, hook.ctxs[0].Err()) +} + +func TestOrderPaidHook_UpdateOrder(t *testing.T) { + p, orders, hook := newHookedOrderProcessor(nil) + _, err := p.UpdateOrder(context.Background(), orders.order.ID, &models.UpdateOrderRequest{}) + require.NoError(t, err) + assert.Equal(t, []uuid.UUID{orders.order.ID}, hook.calls) + assert.Equal(t, 1, orders.statusUpdates) + assert.Zero(t, orders.hookCallsAtPay) +} + +func TestOrderPaidHook_SplitBillOnlyOnTheSettlingPayment(t *testing.T) { + for _, splitType := range []string{"AMOUNT", "ITEM"} { + t.Run(splitType, func(t *testing.T) { + req := &models.SplitBillRequest{Type: splitType, PaymentMethodID: uuid.New()} + + p, orders, hook := newHookedOrderProcessor(splitFake{settle: false}) + req.OrderID = orders.order.ID + _, err := p.SplitBill(context.Background(), req) + require.NoError(t, err) + assert.Empty(t, hook.calls, "a partial split payment does not make the order paid") + + p, orders, hook = newHookedOrderProcessor(splitFake{settle: true}) + req.OrderID = orders.order.ID + _, err = p.SplitBill(context.Background(), req) + require.NoError(t, err) + assert.Equal(t, []uuid.UUID{orders.order.ID}, hook.calls) + }) + } +} + +func TestOrderPaidHook_NoHookIsFine(t *testing.T) { + p, orders, _ := newHookedOrderProcessor(nil) + p.SetLoyalty(nil) + _, err := p.UpdateOrder(context.Background(), orders.order.ID, &models.UpdateOrderRequest{}) + assert.NoError(t, err) +} + +func (r *hookOrderRepo) VoidOrderWithStatus(_ context.Context, _ uuid.UUID, status entities.OrderStatus, _ string, _ uuid.UUID) error { + r.order.Status, r.order.IsVoid = status, true + return nil +} + +func (r *hookOrderRepo) Update(_ context.Context, o *entities.Order) error { + r.order.RefundAmount = o.RefundAmount + return nil +} + +func (r *hookOrderRepo) RefundOrder(context.Context, uuid.UUID, string, uuid.UUID) error { + r.order.IsRefund = true + return nil +} + +func (r *hookPaymentRepo) RefundPayment(_ context.Context, id uuid.UUID, amount float64, _ string, _ uuid.UUID) error { + for _, p := range r.created { + if p.ID == id { + p.RefundAmount = amount + } + } + return nil +} + +func TestOrderRefundedHook(t *testing.T) { + t.Run("void", func(t *testing.T) { + p, orders, hook := newHookedOrderProcessor(nil) + require.NoError(t, p.VoidOrder(context.Background(), &models.VoidOrderRequest{OrderID: orders.order.ID, Type: "ALL", Reason: "salah input"}, uuid.New())) + assert.Equal(t, []uuid.UUID{orders.order.ID}, hook.refunded) + }) + + t.Run("refund order", func(t *testing.T) { + p, orders, hook := newHookedOrderProcessor(nil) + orders.order.PaymentStatus = entities.PaymentStatusCompleted + amount := 25000.0 + require.NoError(t, p.RefundOrder(context.Background(), orders.order.ID, &models.RefundOrderRequest{RefundAmount: &amount}, uuid.New())) + assert.Equal(t, []uuid.UUID{orders.order.ID}, hook.refunded) + }) + + t.Run("refund payment", func(t *testing.T) { + p, orders, hook := newHookedOrderProcessor(nil) + payments := p.paymentRepo.(*hookPaymentRepo) + payment := &entities.Payment{ID: uuid.New(), OrderID: orders.order.ID, Amount: 50000, Status: entities.PaymentTransactionStatusCompleted} + payments.created = append(payments.created, payment) + require.NoError(t, p.RefundPayment(context.Background(), payment.ID, 20000, "kembali", uuid.New())) + assert.Equal(t, []uuid.UUID{orders.order.ID}, hook.refunded) + + // A refund that fails does not run the hook. + assert.Error(t, p.RefundPayment(context.Background(), payment.ID, 60000, "terlalu besar", uuid.New())) + assert.Len(t, hook.refunded, 1) + }) +} + +func (r *hookOrderRepo) List(context.Context, map[string]interface{}, int, int) ([]*entities.Order, int64, error) { + o := *r.order + other := entities.Order{ID: uuid.New()} + return []*entities.Order{&o, &other}, 2, nil +} + +func TestOrderResponsesCarryEarnings(t *testing.T) { + p, orders, hook := newHookedOrderProcessor(nil) + hook.earned = map[uuid.UUID]OrderEarned{orders.order.ID: {Points: 875, Coins: 3}} + + got, err := p.GetOrderByID(context.Background(), orders.order.ID) + require.NoError(t, err) + assert.Equal(t, int64(875), got.PointsEarned) + assert.Equal(t, int64(3), got.CoinsEarned) + + list, err := p.ListOrders(context.Background(), &models.ListOrdersRequest{Page: 1, Limit: 10}) + require.NoError(t, err) + require.Len(t, list.Orders, 2) + assert.Equal(t, int64(875), list.Orders[0].PointsEarned) + assert.Equal(t, int64(0), list.Orders[1].PointsEarned, "an order that earned nothing shows 0") + + // Without the loyalty program the fields stay at 0. + p.SetLoyalty(nil) + got, err = p.GetOrderByID(context.Background(), orders.order.ID) + require.NoError(t, err) + assert.Equal(t, int64(0), got.PointsEarned) +} diff --git a/internal/processor/order_processor.go b/internal/processor/order_processor.go index 3e14e23..bea796c 100644 --- a/internal/processor/order_processor.go +++ b/internal/processor/order_processor.go @@ -5,8 +5,10 @@ import ( "errors" "fmt" + "apskel-pos-be/internal/appcontext" "apskel-pos-be/internal/constants" "apskel-pos-be/internal/entities" + "apskel-pos-be/internal/logger" "apskel-pos-be/internal/mappers" "apskel-pos-be/internal/models" "apskel-pos-be/internal/repository" @@ -19,6 +21,9 @@ type OrderProcessor interface { CreateOrder(ctx context.Context, req *models.CreateOrderRequest, organizationID uuid.UUID) (*models.OrderResponse, error) AddToOrder(ctx context.Context, orderID uuid.UUID, req *models.AddToOrderRequest) (*models.AddToOrderResponse, error) UpdateOrder(ctx context.Context, id uuid.UUID, req *models.UpdateOrderRequest) (*models.OrderResponse, error) + // PayWithPointsInApp pays the customer's own order with EnakPoint from the app or a + // self-order, approved by their PIN (docs/prd-point-coin.md F9). + PayWithPointsInApp(ctx context.Context, customerID, orderID uuid.UUID, points int64, pin string, info models.CustomerPinRequestInfo) (*models.PaymentResponse, error) GetOrderByID(ctx context.Context, id uuid.UUID) (*models.OrderResponse, error) ListOrders(ctx context.Context, req *models.ListOrdersRequest) (*models.ListOrdersResponse, error) VoidOrder(ctx context.Context, req *models.VoidOrderRequest, voidedBy uuid.UUID) error @@ -109,6 +114,139 @@ type OrderProcessorImpl struct { ingredientRepo IngredientRepository inventoryMovementService InventoryMovementService productOutletPriceRepo repository.ProductOutletPriceRepository + loyalty OrderLoyalty + pointPayments *PointPaymentProcessor + paymentCodes paymentCodeRedeemer + pins pinVerifier +} + +// OrderLoyalty is what the order flow tells and asks the loyalty program +// (docs/prd-point-coin.md F3, F10). EarningProcessor is one. +type OrderLoyalty interface { + // OnOrderPaid runs once an order has just become fully paid and the payment has + // committed. + OnOrderPaid(ctx context.Context, orderID uuid.UUID) + // OnOrderRefunded runs once an order has been voided or (partly) refunded and that + // has committed. + OnOrderRefunded(ctx context.Context, orderID uuid.UUID) + // EarnedByOrders returns what each order earned. + EarnedByOrders(ctx context.Context, orderIDs []uuid.UUID) (map[uuid.UUID]OrderEarned, error) +} + +// OrderEarned is what one order earned, as written in its EARN rows. +type OrderEarned struct { + Points int64 + Coins int64 +} + +// SetLoyalty connects the order flow to the loyalty program. +func (p *OrderProcessorImpl) SetLoyalty(loyalty OrderLoyalty) { + p.loyalty = loyalty +} + +type paymentCodeRedeemer interface { + Redeem(ctx context.Context, code string, customerID uuid.UUID) error +} + +// SetPointPayments enables paying with the EnakPoint method. CreatePayment hands such +// payments to pointPayments approved by the code the customer shows at the cashier, +// and PayWithPointsInApp approved by the customer's PIN (F9). +func (p *OrderProcessorImpl) SetPointPayments(pointPayments *PointPaymentProcessor, codes paymentCodeRedeemer, pins pinVerifier) { + p.pointPayments = pointPayments + p.paymentCodes = codes + p.pins = pins +} + +// createPointPayment is CreatePayment for the EnakPoint method. It never uses the +// generic payment path, which would record the payment without taking any balance. +func (p *OrderProcessorImpl) createPointPayment(ctx context.Context, req *models.CreatePaymentRequest) (*models.PaymentResponse, error) { + if p.pointPayments == nil || p.paymentCodes == nil { + return nil, fmt.Errorf("%w: paying with EnakPoint is not available", ErrPointPaymentRejected) + } + if req.Points == nil || req.PaymentCode == nil || *req.PaymentCode == "" { + return nil, fmt.Errorf("%w: points and the customer's payment code are required", ErrPointPaymentRejected) + } + var cashier *uuid.UUID + if id := appcontext.FromContext(ctx).UserID; id != uuid.Nil { + cashier = &id + } + code := *req.PaymentCode + result, err := p.pointPayments.Pay(ctx, PointPaymentInput{ + OrderID: req.OrderID, + PaymentMethodID: req.PaymentMethodID, + Points: *req.Points, + CashierID: cashier, + Authorize: func(ctx context.Context, customerID uuid.UUID) error { + if err := p.paymentCodes.Redeem(ctx, code, customerID); err != nil { + return fmt.Errorf("%w: %v", ErrPointPaymentRejected, err) + } + return nil + }, + }) + if err != nil { + return nil, err + } + if result.Completed { + p.onOrderPaid(ctx, req.OrderID) + } + payment, err := p.paymentRepo.GetByID(ctx, result.Payment.ID) + if err != nil { + return nil, fmt.Errorf("failed to retrieve created payment: %w", err) + } + return mappers.PaymentEntityToResponse(payment), nil +} + +// onOrderPaid is the single place every path that completes an order's payment goes +// through: UpdateOrder, CreatePayment and both kinds of split bill. It must be called +// after the payment has committed. The hook runs detached from the caller's +// transaction and from the request being cancelled, and anything it does cannot fail +// the payment. +func (p *OrderProcessorImpl) onOrderPaid(ctx context.Context, orderID uuid.UUID) { + if p.loyalty == nil { + return + } + p.loyalty.OnOrderPaid(repository.DetachTransaction(context.WithoutCancel(ctx)), orderID) +} + +// onOrderRefunded is called at the end of VoidOrder, RefundOrder and RefundPayment, +// after their writes have committed, with the same guarantees as onOrderPaid: it can +// never block or fail the void or refund. +func (p *OrderProcessorImpl) onOrderRefunded(ctx context.Context, orderID uuid.UUID) { + ctx = repository.DetachTransaction(context.WithoutCancel(ctx)) + // EnakPoint paid on the order comes back first: the customer is owed it (F9). + if p.pointPayments != nil { + if _, err := p.pointPayments.RefundForOrder(ctx, orderID); err != nil { + logger.FromContext(ctx).WithError(err).Error("OrderProcessorImpl::onOrderRefunded -> failed to return EnakPoint; calling it again is safe") + } + } + if p.loyalty != nil { + p.loyalty.OnOrderRefunded(ctx, orderID) + } +} + +// attachEarnings fills points_earned and coins_earned (F3). A failure is logged and +// leaves them at zero rather than failing the order read. +func (p *OrderProcessorImpl) attachEarnings(ctx context.Context, responses ...*models.OrderResponse) { + if p.loyalty == nil || len(responses) == 0 { + return + } + ids := make([]uuid.UUID, 0, len(responses)) + for _, r := range responses { + if r != nil { + ids = append(ids, r.ID) + } + } + earned, err := p.loyalty.EarnedByOrders(repository.DetachTransaction(ctx), ids) + if err != nil { + logger.FromContext(ctx).WithError(err).Error("OrderProcessorImpl::attachEarnings -> failed to read earnings") + return + } + for _, r := range responses { + if r != nil { + e := earned[r.ID] + r.PointsEarned, r.CoinsEarned = e.Points, e.Coins + } + } } func NewOrderProcessorImpl( @@ -297,6 +435,7 @@ func (p *OrderProcessorImpl) CreateOrder(ctx context.Context, req *models.Create } response := mappers.OrderEntityToResponse(orderWithRelations) + p.attachEarnings(ctx, response) return response, nil } @@ -435,6 +574,7 @@ func (p *OrderProcessorImpl) AddToOrder(ctx context.Context, orderID uuid.UUID, } updatedOrderResponse := mappers.OrderEntityToResponse(orderWithRelations) + p.attachEarnings(ctx, updatedOrderResponse) return &models.AddToOrderResponse{ OrderID: orderID, @@ -494,6 +634,7 @@ func (p *OrderProcessorImpl) UpdateOrder(ctx context.Context, id uuid.UUID, req if err := p.orderRepo.UpdateStatusSuccess(ctx, order.ID, order.Status, order.PaymentStatus); err != nil { return nil, fmt.Errorf("failed to update order: %w", err) } + p.onOrderPaid(ctx, order.ID) orderWithRelations, err := p.orderRepo.GetWithRelations(ctx, id) if err != nil { @@ -501,6 +642,7 @@ func (p *OrderProcessorImpl) UpdateOrder(ctx context.Context, id uuid.UUID, req } response := mappers.OrderEntityToResponse(orderWithRelations) + p.attachEarnings(ctx, response) return response, nil } @@ -511,6 +653,7 @@ func (p *OrderProcessorImpl) GetOrderByID(ctx context.Context, id uuid.UUID) (*m } response := mappers.OrderEntityToResponse(order) + p.attachEarnings(ctx, response) return response, nil } @@ -572,6 +715,11 @@ func (p *OrderProcessorImpl) ListOrders(ctx context.Context, req *models.ListOrd } } } + listed := make([]*models.OrderResponse, len(orderResponses)) + for i := range orderResponses { + listed[i] = &orderResponses[i] + } + p.attachEarnings(ctx, listed...) totalPages := int(total) / req.Limit if int(total)%req.Limit > 0 { @@ -692,6 +840,10 @@ func (p *OrderProcessorImpl) VoidOrder(ctx context.Context, req *models.VoidOrde return fmt.Errorf("invalid void type: must be 'ALL' or 'ITEM'") } + // VoidOrder refuses fully paid orders today, so there is usually nothing to take + // back; this keeps a void correct if that rule changes. The order repository writes + // outside the caller's transaction, so the void is already committed here. + p.onOrderRefunded(ctx, req.OrderID) return nil } @@ -714,6 +866,18 @@ func (p *OrderProcessorImpl) RefundOrder(ctx context.Context, id uuid.UUID, req reason = *req.Reason } + // An order refund is handed back in cash or another method, so it cannot cover what + // was paid with EnakPoint (K7). Checked before anything is written. + if p.pointPayments != nil { + planned, err := p.plannedOrderRefund(ctx, id, req) + if err != nil { + return err + } + if err := p.pointPayments.EnsureOrderRefundAllowed(ctx, id, planned); err != nil { + return err + } + } + // Process refund based on request type if req.RefundAmount != nil { // Full or partial refund by amount @@ -787,6 +951,7 @@ func (p *OrderProcessorImpl) RefundOrder(ctx context.Context, id uuid.UUID, req } } + p.onOrderRefunded(ctx, id) return nil } @@ -804,10 +969,13 @@ func (p *OrderProcessorImpl) CreatePayment(ctx context.Context, req *models.Crea return nil, fmt.Errorf("order is already fully paid") } - _, err = p.paymentMethodRepo.GetByID(ctx, req.PaymentMethodID) + method, err := p.paymentMethodRepo.GetByID(ctx, req.PaymentMethodID) if err != nil { return nil, fmt.Errorf("payment method not found: %w", err) } + if method.Type == entities.PaymentMethodTypePoint { + return p.createPointPayment(ctx, req) + } totalPaid, err := p.paymentRepo.GetTotalPaidByOrderID(ctx, req.OrderID) if err != nil { @@ -818,6 +986,8 @@ func (p *OrderProcessorImpl) CreatePayment(ctx context.Context, req *models.Crea if err != nil { return nil, err } + // Not from updateOrderStatus: that runs inside the payment's transaction. + p.onOrderPaid(ctx, req.OrderID) paymentWithRelations, err := p.paymentRepo.GetByID(ctx, payment.ID) if err != nil { @@ -842,7 +1012,11 @@ func (p *OrderProcessorImpl) RefundPayment(ctx context.Context, paymentID uuid.U return fmt.Errorf("refund amount cannot exceed payment amount") } - return p.RefundPaymentWithInventoryMovement(ctx, paymentID, refundAmount, reason, refundedBy, payment) + if err := p.RefundPaymentWithInventoryMovement(ctx, paymentID, refundAmount, reason, refundedBy, payment); err != nil { + return err + } + p.onOrderRefunded(ctx, payment.OrderID) + return nil } func (p *OrderProcessorImpl) CreatePaymentWithInventoryMovement(ctx context.Context, req *models.CreatePaymentRequest, order *entities.Order, totalPaid float64) (*entities.Payment, error) { @@ -1186,6 +1360,11 @@ func (p *OrderProcessorImpl) SplitBill(ctx context.Context, req *models.SplitBil if err != nil { return nil, fmt.Errorf("payment method not found: %w", err) } + // Splitting with EnakPoint would record a payment without taking any balance; an + // EnakPoint part goes through CreatePayment and the rest is split as usual (F9). + if payment.Type == entities.PaymentMethodTypePoint { + return nil, fmt.Errorf("%w: pay the EnakPoint part as its own payment, not as a split", ErrPointPaymentRejected) + } customer := &entities.Customer{} if req.CustomerID != uuid.Nil { @@ -1207,6 +1386,10 @@ func (p *OrderProcessorImpl) SplitBill(ctx context.Context, req *models.SplitBil if err != nil { return nil, err } + // Both split paths mark the order paid on the payment that settles it. + if order.PaymentStatus == entities.PaymentStatusCompleted { + p.onOrderPaid(ctx, order.ID) + } return response, nil } @@ -1628,3 +1811,71 @@ func (p *OrderProcessorImpl) prepareRefundedIngredientRecipeItem(ctx context.Con func stringPtr(s string) *string { return &s } + +// PayWithPointsInApp pays an order with EnakPoint on the customer's own request, in the +// app or a self-order. The session alone is not enough: the customer's PIN approves +// it (K8). An order that is not the customer's own is reported as not found, so the +// endpoint does not reveal other customers' orders. +func (p *OrderProcessorImpl) PayWithPointsInApp(ctx context.Context, customerID, orderID uuid.UUID, points int64, pin string, info models.CustomerPinRequestInfo) (*models.PaymentResponse, error) { + if p.pointPayments == nil || p.pins == nil { + return nil, fmt.Errorf("%w: paying with EnakPoint is not available", ErrPointPaymentRejected) + } + organizationID, owner, err := p.pointPayments.OrderOwner(ctx, orderID) + if err != nil { + return nil, err + } + if owner == nil || *owner != customerID { + return nil, repository.ErrPointPaymentOrderNotFound + } + methodID, err := p.pointPayments.PointMethodID(ctx, organizationID) + if err != nil { + return nil, err + } + result, err := p.pointPayments.Pay(ctx, PointPaymentInput{ + OrderID: orderID, + PaymentMethodID: methodID, + Points: points, + Authorize: func(ctx context.Context, customerID uuid.UUID) error { + return p.pins.VerifyPin(ctx, customerID, pin, PinActionPay, info) + }, + }) + if err != nil { + return nil, err + } + if result.Completed { + p.onOrderPaid(ctx, orderID) + } + payment, err := p.paymentRepo.GetByID(ctx, result.Payment.ID) + if err != nil { + return nil, fmt.Errorf("failed to retrieve created payment: %w", err) + } + return mappers.PaymentEntityToResponse(payment), nil +} + +// plannedOrderRefund is the total RefundOrder is about to hand back, computed the same +// way it will be, without writing anything. +func (p *OrderProcessorImpl) plannedOrderRefund(ctx context.Context, orderID uuid.UUID, req *models.RefundOrderRequest) (float64, error) { + if req.RefundAmount != nil { + return *req.RefundAmount, nil + } + var total float64 + for _, itemRefund := range req.OrderItems { + if itemRefund.RefundAmount != nil { + total += *itemRefund.RefundAmount + continue + } + orderItem, err := p.orderItemRepo.GetByID(ctx, itemRefund.OrderItemID) + if err != nil { + return 0, fmt.Errorf("order item not found: %w", err) + } + if orderItem.OrderID != orderID { + return 0, fmt.Errorf("order item does not belong to this order") + } + quantity := itemRefund.RefundQuantity + if quantity == 0 { + quantity = orderItem.Quantity + } + total += entities.RoundMoney(orderItem.BillableQuantityFor(quantity) * orderItem.UnitPrice) + } + return total, nil +} diff --git a/internal/processor/otp_processor.go b/internal/processor/otp_processor.go index f0616ed..28013aa 100644 --- a/internal/processor/otp_processor.go +++ b/internal/processor/otp_processor.go @@ -133,6 +133,10 @@ func (p *otpProcessor) SendOtpViaWhatsApp(phoneNumber string, otpCode string, pu switch purpose { case "login": message = fmt.Sprintf("Kode OTP untuk login kamu adalah %s. Berlaku 5 menit.", otpCode) + case "pin_setup": + message = fmt.Sprintf("Kode OTP untuk membuat PIN EnakPoint kamu adalah %s. Berlaku 5 menit. Jangan berikan kode ini kepada siapa pun, termasuk kasir.", otpCode) + case "pin_reset": + message = fmt.Sprintf("Kode OTP untuk reset PIN EnakPoint kamu adalah %s. Berlaku 5 menit. Jangan berikan kode ini kepada siapa pun. Setelah reset, transfer ditahan 24 jam.", otpCode) case "registration": message = fmt.Sprintf("Kode OTP untuk registrasi kamu adalah %s. Berlaku 5 menit.", otpCode) default: diff --git a/internal/processor/payment_code_processor.go b/internal/processor/payment_code_processor.go new file mode 100644 index 0000000..7c7038c --- /dev/null +++ b/internal/processor/payment_code_processor.go @@ -0,0 +1,101 @@ +package processor + +import ( + "context" + "crypto/rand" + "errors" + "fmt" + "math/big" + "strings" + "time" + + "github.com/google/uuid" + + "apskel-pos-be/internal/models" + "apskel-pos-be/internal/repository" +) + +const ( + paymentCodeDigits = 6 + paymentCodeTTL = 2 * time.Minute + paymentCodeAttempts = 5 + // PaymentCodeQRPrefix marks a scanned QR as an EnakPoint payment code. + PaymentCodeQRPrefix = "enakpoint:" +) + +// ErrPaymentCodeInvalid means the code was never issued, has expired, has been used, +// or belongs to another customer. +var ErrPaymentCodeInvalid = errors.New("payment code is invalid or expired") + +type pinVerifier interface { + VerifyPin(ctx context.Context, customerID uuid.UUID, pin string, action PinAction, info models.CustomerPinRequestInfo) error +} + +// PaymentCodeProcessor issues and redeems the one-time codes that let a cashier take a +// customer's EnakPoint (docs/prd-point-coin.md F9, K8). The customer approves with +// their PIN on their own phone and shows the code; the PIN is never typed on the +// cashier's device. +type PaymentCodeProcessor struct { + codes repository.PaymentCodeRepository + pins pinVerifier + now func() time.Time +} + +func NewPaymentCodeProcessor(codes repository.PaymentCodeRepository, pins pinVerifier) *PaymentCodeProcessor { + return &PaymentCodeProcessor{codes: codes, pins: pins, now: time.Now} +} + +// Issue checks the customer's PIN and returns a fresh 6-digit code, valid for two +// minutes and bound to the customer. A new code retires the previous one. +func (p *PaymentCodeProcessor) Issue(ctx context.Context, customerID uuid.UUID, pin string, info models.CustomerPinRequestInfo) (*models.PaymentCode, error) { + if err := p.pins.VerifyPin(ctx, customerID, pin, PinActionPay, info); err != nil { + return nil, err + } + for attempt := 0; attempt < paymentCodeAttempts; attempt++ { + code, err := randomDigits(paymentCodeDigits) + if err != nil { + return nil, err + } + err = p.codes.Save(ctx, code, customerID, paymentCodeTTL) + if errors.Is(err, repository.ErrPaymentCodeTaken) { + continue + } + if err != nil { + return nil, err + } + return &models.PaymentCode{ + Code: code, + QRPayload: PaymentCodeQRPrefix + code, + ExpiresAt: p.now().Add(paymentCodeTTL), + }, nil + } + return nil, fmt.Errorf("could not draw a free payment code after %d attempts", paymentCodeAttempts) +} + +// Redeem uses a code up for a payment by the given customer. It accepts the code as +// typed or as scanned from the QR. Every failure is ErrPaymentCodeInvalid. +func (p *PaymentCodeProcessor) Redeem(ctx context.Context, code string, customerID uuid.UUID) error { + code = strings.TrimPrefix(strings.TrimSpace(code), PaymentCodeQRPrefix) + if len(code) != paymentCodeDigits { + return ErrPaymentCodeInvalid + } + err := p.codes.Consume(ctx, code, customerID) + if errors.Is(err, repository.ErrPaymentCodeNotFound) || errors.Is(err, repository.ErrPaymentCodeWrongCustomer) { + return ErrPaymentCodeInvalid + } + return err +} + +// randomDigits draws n decimal digits from a cryptographic source, so codes cannot be +// predicted. +func randomDigits(n int) (string, error) { + var b strings.Builder + for i := 0; i < n; i++ { + d, err := rand.Int(rand.Reader, big.NewInt(10)) + if err != nil { + return "", fmt.Errorf("failed to draw a payment code: %w", err) + } + b.WriteByte(byte('0' + d.Int64())) + } + return b.String(), nil +} diff --git a/internal/processor/payment_code_processor_test.go b/internal/processor/payment_code_processor_test.go new file mode 100644 index 0000000..bb134d7 --- /dev/null +++ b/internal/processor/payment_code_processor_test.go @@ -0,0 +1,136 @@ +package processor + +import ( + "context" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/alicebob/miniredis/v2" + "github.com/google/uuid" + "github.com/redis/go-redis/v9" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "apskel-pos-be/internal/models" + "apskel-pos-be/internal/repository" +) + +type pinVerifierFake struct{ good string } + +func (f pinVerifierFake) VerifyPin(_ context.Context, _ uuid.UUID, pin string, action PinAction, _ models.CustomerPinRequestInfo) error { + if action != PinActionPay { + return &PinError{Code: "UNEXPECTED_ACTION"} + } + if pin != f.good { + return &PinError{Code: PinErrInvalid, RemainingAttempts: 4} + } + return nil +} + +func newPaymentCodeTest(t *testing.T) (*PaymentCodeProcessor, *miniredis.Miniredis) { + t.Helper() + mr := miniredis.RunT(t) + client := redis.NewClient(&redis.Options{Addr: mr.Addr()}) + t.Cleanup(func() { client.Close() }) + return NewPaymentCodeProcessor(repository.NewPaymentCodeRepository(client), pinVerifierFake{good: "482913"}), mr +} + +func TestPaymentCode_IssueNeedsThePin(t *testing.T) { + p, mr := newPaymentCodeTest(t) + _, err := p.Issue(context.Background(), uuid.New(), "000000", models.CustomerPinRequestInfo{}) + var pe *PinError + require.ErrorAs(t, err, &pe) + assert.Equal(t, PinErrInvalid, pe.Code) + assert.Empty(t, mr.Keys(), "nothing is issued without the PIN") +} + +func TestPaymentCode_Lifecycle(t *testing.T) { + p, mr := newPaymentCodeTest(t) + ctx := context.Background() + customer, other := uuid.New(), uuid.New() + + code, err := p.Issue(ctx, customer, "482913", models.CustomerPinRequestInfo{}) + require.NoError(t, err) + assert.Len(t, code.Code, 6) + assert.Equal(t, "enakpoint:"+code.Code, code.QRPayload) + assert.WithinDuration(t, time.Now().Add(2*time.Minute), code.ExpiresAt, 2*time.Second) + assert.InDelta(t, 120, mr.TTL("wallet:paycode:"+code.Code).Seconds(), 1, "Redis expires it by itself") + + // A code of another customer is refused, and stays usable by its owner. + assert.ErrorIs(t, p.Redeem(ctx, code.Code, other), ErrPaymentCodeInvalid) + // Scanned from the QR it works; used once, it is gone. + require.NoError(t, p.Redeem(ctx, code.QRPayload, customer)) + assert.ErrorIs(t, p.Redeem(ctx, code.Code, customer), ErrPaymentCodeInvalid) + + // An expired code is refused. + late, err := p.Issue(ctx, customer, "482913", models.CustomerPinRequestInfo{}) + require.NoError(t, err) + mr.FastForward(2*time.Minute + time.Second) + assert.ErrorIs(t, p.Redeem(ctx, late.Code, customer), ErrPaymentCodeInvalid) + + // A new code retires the previous one. + first, err := p.Issue(ctx, customer, "482913", models.CustomerPinRequestInfo{}) + require.NoError(t, err) + second, err := p.Issue(ctx, customer, "482913", models.CustomerPinRequestInfo{}) + require.NoError(t, err) + if first.Code != second.Code { + assert.ErrorIs(t, p.Redeem(ctx, first.Code, customer), ErrPaymentCodeInvalid) + } + require.NoError(t, p.Redeem(ctx, second.Code, customer)) + + // Garbage is refused without touching Redis. + for _, bad := range []string{"", "12345", "1234567", "enakpoint:"} { + assert.ErrorIs(t, p.Redeem(ctx, bad, customer), ErrPaymentCodeInvalid, bad) + } +} + +// Two cashiers scanning the same code at once: exactly one gets it. +func TestPaymentCode_UsedOnceUnderRace(t *testing.T) { + p, _ := newPaymentCodeTest(t) + ctx := context.Background() + customer := uuid.New() + code, err := p.Issue(ctx, customer, "482913", models.CustomerPinRequestInfo{}) + require.NoError(t, err) + + var wins int32 + var wg sync.WaitGroup + for i := 0; i < 20; i++ { + wg.Add(1) + go func() { + defer wg.Done() + if p.Redeem(ctx, code.Code, customer) == nil { + atomic.AddInt32(&wins, 1) + } + }() + } + wg.Wait() + assert.Equal(t, int32(1), wins) +} + +func TestPaymentCode_SaveRefusesALiveCode(t *testing.T) { + mr := miniredis.RunT(t) + client := redis.NewClient(&redis.Options{Addr: mr.Addr()}) + defer client.Close() + repo := repository.NewPaymentCodeRepository(client) + ctx := context.Background() + + require.NoError(t, repo.Save(ctx, "123456", uuid.New(), time.Minute)) + assert.ErrorIs(t, repo.Save(ctx, "123456", uuid.New(), time.Minute), repository.ErrPaymentCodeTaken, + "a live code is never handed to a second customer") +} + +func TestRandomDigits(t *testing.T) { + seen := map[string]bool{} + for i := 0; i < 200; i++ { + d, err := randomDigits(6) + require.NoError(t, err) + require.Len(t, d, 6) + for _, r := range d { + require.True(t, r >= '0' && r <= '9') + } + seen[d] = true + } + assert.Greater(t, len(seen), 190, "codes do not repeat") +} diff --git a/internal/processor/payment_method_processor.go b/internal/processor/payment_method_processor.go index 952ab86..bd0b240 100644 --- a/internal/processor/payment_method_processor.go +++ b/internal/processor/payment_method_processor.go @@ -1,7 +1,10 @@ package processor import ( + "apskel-pos-be/internal/constants" + "apskel-pos-be/internal/entities" "context" + "errors" "fmt" "apskel-pos-be/internal/mappers" @@ -20,17 +23,26 @@ type PaymentMethodProcessor interface { GetActivePaymentMethodsByOrganization(ctx context.Context, organizationID uuid.UUID) ([]models.PaymentMethodResponse, error) } +// ErrSystemPaymentMethod means an attempt to create, delete or retype the EnakPoint +// method, which the system owns (docs/prd-point-coin.md F9). +var ErrSystemPaymentMethod = errors.New("the EnakPoint payment method is managed by the system: it cannot be created, deleted or change type") + type PaymentMethodProcessorImpl struct { paymentMethodRepo repository.PaymentMethodRepository + outletSettings outletSettingsReader } -func NewPaymentMethodProcessorImpl(paymentMethodRepo repository.PaymentMethodRepository) *PaymentMethodProcessorImpl { +func NewPaymentMethodProcessorImpl(paymentMethodRepo repository.PaymentMethodRepository, outletSettings outletSettingsReader) *PaymentMethodProcessorImpl { return &PaymentMethodProcessorImpl{ paymentMethodRepo: paymentMethodRepo, + outletSettings: outletSettings, } } func (p *PaymentMethodProcessorImpl) CreatePaymentMethod(ctx context.Context, req *models.CreatePaymentMethodRequest) (*models.PaymentMethodResponse, error) { + if req.Type == constants.PaymentMethodTypePoint { + return nil, ErrSystemPaymentMethod + } exists, err := p.paymentMethodRepo.ExistsByName(ctx, req.OrganizationID, req.Name, nil) if err != nil { return nil, fmt.Errorf("failed to check payment method name uniqueness: %w", err) @@ -77,6 +89,17 @@ func (p *PaymentMethodProcessorImpl) ListPaymentMethods(ctx context.Context, req if req.Search != "" { filters["search"] = req.Search } + // At the cashier EnakPoint only shows where the outlet accepts it (F9). Filtered in + // the query so paging stays right. + if req.OutletID != nil && p.outletSettings != nil { + settings, err := p.outletSettings.Outlet(ctx, *req.OutletID) + if err != nil { + return nil, fmt.Errorf("failed to read outlet loyalty settings: %w", err) + } + if !settings.PointPayment.AcceptPayment { + filters["exclude_type"] = string(constants.PaymentMethodTypePoint) + } + } offset := (req.Page - 1) * req.Limit @@ -116,6 +139,15 @@ func (p *PaymentMethodProcessorImpl) UpdatePaymentMethod(ctx context.Context, id return nil, fmt.Errorf("payment method not found: %w", err) } + // The EnakPoint method keeps its type, and no other method can become one. + if req.Type != nil { + wasPoint := existingPaymentMethod.Type == entities.PaymentMethodTypePoint + isPoint := *req.Type == constants.PaymentMethodTypePoint + if wasPoint != isPoint { + return nil, ErrSystemPaymentMethod + } + } + // Check name uniqueness if name is being updated if req.Name != nil && *req.Name != existingPaymentMethod.Name { exists, err := p.paymentMethodRepo.ExistsByName(ctx, existingPaymentMethod.OrganizationID, *req.Name, &id) @@ -147,10 +179,13 @@ func (p *PaymentMethodProcessorImpl) UpdatePaymentMethod(ctx context.Context, id func (p *PaymentMethodProcessorImpl) DeletePaymentMethod(ctx context.Context, id uuid.UUID) error { // Check if payment method exists - _, err := p.paymentMethodRepo.GetByID(ctx, id) + existing, err := p.paymentMethodRepo.GetByID(ctx, id) if err != nil { return fmt.Errorf("payment method not found: %w", err) } + if existing.Type == entities.PaymentMethodTypePoint { + return ErrSystemPaymentMethod + } // TODO: Check if payment method is being used in any payments // For now, allow deletion diff --git a/internal/processor/point_payment_db_test.go b/internal/processor/point_payment_db_test.go new file mode 100644 index 0000000..3ab8c2f --- /dev/null +++ b/internal/processor/point_payment_db_test.go @@ -0,0 +1,401 @@ +package processor + +import ( + "context" + "os" + "sync" + "testing" + "time" + + "github.com/alicebob/miniredis/v2" + "github.com/google/uuid" + "github.com/redis/go-redis/v9" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "gorm.io/driver/postgres" + "gorm.io/gorm" + "gorm.io/gorm/logger" + + "apskel-pos-be/internal/appcontext" + "apskel-pos-be/internal/constants" + "apskel-pos-be/internal/models" + "apskel-pos-be/internal/repository" +) + +// pointPaymentEnv is an order flow wired as in the app, against Postgres and a +// miniredis for payment codes. +type pointPaymentEnv struct { + t *testing.T + db *gorm.DB + orders *OrderProcessorImpl + payments *PointPaymentProcessor + codes *PaymentCodeProcessor + org uuid.UUID + cashier uuid.UUID + outlet uuid.UUID + point uuid.UUID + cash uuid.UUID + walkIn uuid.UUID + ctx context.Context +} + +func newPointPaymentEnv(t *testing.T) *pointPaymentEnv { + t.Helper() + dsn := os.Getenv("TEST_DATABASE_URL") + if dsn == "" { + t.Skip("TEST_DATABASE_URL not set") + } + db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{Logger: logger.Default.LogMode(logger.Silent)}) + require.NoError(t, err) + e := &pointPaymentEnv{t: t, db: db, org: uuid.New(), cashier: uuid.New(), outlet: uuid.New(), cash: uuid.New()} + e.exec(`INSERT INTO organizations (id, name, plan_type) VALUES (?, 'point pay test', 'basic')`, e.org) + e.exec(`INSERT INTO users (id, organization_id, name, email, password_hash, role) VALUES (?, ?, 'Kasir', ?, 'x', 'cashier')`, e.cashier, e.org, e.cashier.String()+"@t") + e.exec(`INSERT INTO outlets (id, organization_id, name) VALUES (?, ?, 'Kemang')`, e.outlet, e.org) + e.exec(`INSERT INTO payment_methods (id, organization_id, name, type) VALUES (?, ?, 'Tunai', 'cash')`, e.cash, e.org) + var ids []string + require.NoError(t, db.Raw(`SELECT id::text FROM payment_methods WHERE organization_id = ? AND type = 'point'`, e.org).Scan(&ids).Error) + require.Len(t, ids, 1) + e.point = uuid.MustParse(ids[0]) + require.NoError(t, db.Raw(`SELECT id::text FROM customers WHERE organization_id = ? AND is_default`, e.org).Scan(&ids).Error) + e.walkIn = uuid.MustParse(ids[0]) + t.Cleanup(func() { + db.Exec(`DELETE FROM wallet_lot_allocations WHERE lot_id IN (SELECT id FROM wallet_lots WHERE organization_id = ?)`, e.org) + db.Exec(`DELETE FROM wallet_lots WHERE organization_id = ?`, e.org) + db.Exec(`DELETE FROM wallet_transactions WHERE organization_id = ?`, e.org) + db.Exec(`DELETE FROM customer_wallets WHERE organization_id = ?`, e.org) + db.Exec(`DELETE FROM payments WHERE order_id IN (SELECT id FROM orders WHERE organization_id = ?)`, e.org) + db.Exec(`DELETE FROM orders WHERE organization_id = ?`, e.org) + db.Exec(`DELETE FROM loyalty_setting_changes WHERE organization_id = ?`, e.org) + db.Exec(`DELETE FROM outlet_settings WHERE outlet_id = ?`, e.outlet) + db.Exec(`DELETE FROM payment_methods WHERE organization_id = ?`, e.org) + db.Exec(`DELETE FROM customers WHERE organization_id = ?`, e.org) + db.Exec(`DELETE FROM outlets WHERE id = ?`, e.outlet) + db.Exec(`DELETE FROM users WHERE id = ?`, e.cashier) + db.Exec(`DELETE FROM organizations WHERE id = ?`, e.org) + }) + + txm := repository.NewTxManager(db) + settings := NewLoyaltySettingsProcessor(repository.NewLoyaltySettingsRepository(db), txm) + wallet := NewWalletProcessor(repository.NewWalletRepository(db)) + e.payments = NewPointPaymentProcessor(repository.NewPointPaymentRepository(db), settings, repository.NewWalletQueryRepository(db), wallet, txm) + mr := miniredis.RunT(t) + client := redis.NewClient(&redis.Options{Addr: mr.Addr()}) + t.Cleanup(func() { client.Close() }) + e.codes = NewPaymentCodeProcessor(repository.NewPaymentCodeRepository(client), pinVerifierFake{good: "482913"}) + + e.orders = &OrderProcessorImpl{ + orderRepo: repository.NewOrderRepositoryImpl(db), + orderItemRepo: repository.NewOrderItemRepositoryImpl(db), + paymentRepo: repository.NewPaymentRepositoryImpl(db), + paymentMethodRepo: repository.NewPaymentMethodRepositoryImpl(db), + splitBillProcessor: nil, + txManager: txm, + } + e.orders.SetLoyalty(NewEarningProcessor(repository.NewEarningRepository(db), settings, wallet, txm)) + e.orders.SetPointPayments(e.payments, e.codes, pinVerifierFake{good: "482913"}) + + // The outlet earns 1 EnakPoint per Rp 100 and accepts EnakPoint. + s, err := settings.Outlet(context.Background(), e.outlet) + require.NoError(t, err) + s.Point.Enabled = true + s.PointPayment.AcceptPayment = true + _, err = settings.UpdateOutlet(context.Background(), e.org, e.outlet, e.cashier, *s) + require.NoError(t, err) + + e.ctx = context.WithValue(context.Background(), appcontext.UserIDKey, e.cashier.String()) + return e +} + +func (e *pointPaymentEnv) exec(q string, args ...any) { + e.t.Helper() + require.NoError(e.t, e.db.Exec(q, args...).Error) +} + +// customerWith creates a customer holding the given EnakPoint. +func (e *pointPaymentEnv) customerWith(points int64) uuid.UUID { + e.t.Helper() + id := uuid.New() + e.exec(`INSERT INTO customers (id, organization_id, name) VALUES (?, ?, 'c')`, id, e.org) + if points > 0 { + require.NoError(e.t, repository.NewTxManager(e.db).WithTransaction(context.Background(), func(ctx context.Context) error { + _, err := NewWalletProcessor(repository.NewWalletRepository(e.db)).Credit(ctx, WalletCreditInput{WalletEntry: WalletEntry{ + CustomerID: id, Currency: constants.WalletCurrencyPoint, Type: constants.WalletTxTypeMigration, Amount: points, + ReferenceType: constants.WalletRefTypeLegacyPoints, ReferenceID: uuid.New(), Description: "Saldo awal"}}) + return err + })) + } + return id +} + +func (e *pointPaymentEnv) order(customer uuid.UUID, subtotal float64) uuid.UUID { + e.t.Helper() + id := uuid.New() + e.exec(`INSERT INTO orders (id, organization_id, outlet_id, user_id, customer_id, order_number, order_type, + subtotal, tax_amount, total_amount, remaining_amount, payment_status) + VALUES (?, ?, ?, ?, ?, ?, 'dine_in', ?, 0, ?, ?, 'pending')`, + id, e.org, e.outlet, e.cashier, customer, "PP-"+id.String()[:8], subtotal, subtotal, subtotal) + return id +} + +func (e *pointPaymentEnv) code(customer uuid.UUID) string { + e.t.Helper() + c, err := e.codes.Issue(context.Background(), customer, "482913", models.CustomerPinRequestInfo{}) + require.NoError(e.t, err) + return c.Code +} + +func (e *pointPaymentEnv) payPoints(order uuid.UUID, points int64, code string) (*models.PaymentResponse, error) { + return e.orders.CreatePayment(e.ctx, &models.CreatePaymentRequest{OrderID: order, PaymentMethodID: e.point, Points: &points, PaymentCode: &code}) +} + +func (e *pointPaymentEnv) balance(customer uuid.UUID) int64 { + e.t.Helper() + var b int64 + require.NoError(e.t, e.db.Raw(`SELECT COALESCE(SUM(point_balance), 0) FROM customer_wallets WHERE customer_id = ?`, customer).Scan(&b).Error) + return b +} + +func (e *pointPaymentEnv) orderState(order uuid.UUID) (status string, remaining float64) { + e.t.Helper() + var row struct { + PaymentStatus string + RemainingAmount float64 + } + require.NoError(e.t, e.db.Raw(`SELECT payment_status, remaining_amount FROM orders WHERE id = ?`, order).Scan(&row).Error) + return row.PaymentStatus, row.RemainingAmount +} + +func TestPointPayment_FullPayment(t *testing.T) { + e := newPointPaymentEnv(t) + customer := e.customerWith(100000) + order := e.order(customer, 50000) + + payment, err := e.payPoints(order, 50000, e.code(customer)) + require.NoError(t, err) + assert.Equal(t, 50000.0, payment.Amount) + require.NotNil(t, payment.PointsUsed) + assert.Equal(t, int64(50000), *payment.PointsUsed) + assert.Equal(t, 1.0, *payment.PointValue, "the value is frozen on the payment") + status, remaining := e.orderState(order) + assert.Equal(t, "completed", status) + assert.Zero(t, remaining) + assert.Equal(t, int64(50000), e.balance(customer)) + + var ledger struct { + Amount int64 + ReferenceType string + ReferenceID string + OutletID string + CreatedByUser string + } + require.NoError(t, e.db.Raw(`SELECT amount, reference_type, reference_id::text AS reference_id, outlet_id::text AS outlet_id, + created_by_user::text AS created_by_user FROM wallet_transactions WHERE customer_id = ? AND type = 'PAYMENT'`, customer).Scan(&ledger).Error) + assert.Equal(t, int64(-50000), ledger.Amount) + assert.Equal(t, "PAYMENT", ledger.ReferenceType) + assert.Equal(t, payment.ID.String(), ledger.ReferenceID) + assert.Equal(t, e.outlet.String(), ledger.OutletID) + assert.Equal(t, e.cashier.String(), ledger.CreatedByUser, "the cashier who took it") + + // Paid entirely with EnakPoint, so nothing earns (Q10). + var earned int64 + require.NoError(t, e.db.Raw(`SELECT COUNT(*) FROM wallet_transactions WHERE reference_id = ? AND type = 'EARN'`, order).Scan(&earned).Error) + assert.Zero(t, earned) +} + +func TestPointPayment_PartialThenCash(t *testing.T) { + e := newPointPaymentEnv(t) + customer := e.customerWith(100000) + order := e.order(customer, 87500) + + _, err := e.payPoints(order, 20000, e.code(customer)) + require.NoError(t, err) + status, remaining := e.orderState(order) + assert.Equal(t, "partial", status) + assert.Equal(t, 67500.0, remaining) + + // The rest in cash settles it; earning counts only the part not paid with + // EnakPoint: floor(67.500 / 100) = 675. + _, err = e.orders.CreatePayment(e.ctx, &models.CreatePaymentRequest{OrderID: order, PaymentMethodID: e.cash, Amount: 67500}) + require.NoError(t, err) + status, _ = e.orderState(order) + assert.Equal(t, "completed", status) + var earned int64 + require.NoError(t, e.db.Raw(`SELECT COALESCE(SUM(amount), 0) FROM wallet_transactions WHERE reference_id = ? AND type = 'EARN'`, order).Scan(&earned).Error) + assert.Equal(t, int64(675), earned) + assert.Equal(t, int64(100000-20000+675), e.balance(customer)) +} + +func TestPointPayment_PercentCap(t *testing.T) { + e := newPointPaymentEnv(t) + settings := NewLoyaltySettingsProcessor(repository.NewLoyaltySettingsRepository(e.db), repository.NewTxManager(e.db)) + s, err := settings.Outlet(context.Background(), e.outlet) + require.NoError(t, err) + s.PointPayment.MaxPaymentPercent = 50 + _, err = settings.UpdateOutlet(context.Background(), e.org, e.outlet, e.cashier, *s) + require.NoError(t, err) + + customer := e.customerWith(100000) + order := e.order(customer, 100000) + + preview, err := e.payments.Preview(context.Background(), e.org, order) + require.NoError(t, err) + assert.True(t, preview.Eligible) + assert.Equal(t, int64(50000), preview.MaxPoints) + assert.Equal(t, int64(100000), preview.PointBalance) + + _, err = e.payPoints(order, 50001, e.code(customer)) + assert.ErrorIs(t, err, ErrPointPaymentRejected) + _, err = e.payPoints(order, 30000, e.code(customer)) + require.NoError(t, err) + _, err = e.payPoints(order, 20001, e.code(customer)) + assert.ErrorIs(t, err, ErrPointPaymentRejected, "earlier EnakPoint counts toward the cap") + _, err = e.payPoints(order, 20000, e.code(customer)) + require.NoError(t, err) + assert.Equal(t, int64(50000), e.balance(customer)) +} + +func TestPointPayment_Refusals(t *testing.T) { + e := newPointPaymentEnv(t) + customer := e.customerWith(100000) + other := e.customerWith(100000) + + // A walk-in order cannot be paid with EnakPoint. + walkInOrder := e.order(e.walkIn, 10000) + preview, err := e.payments.Preview(context.Background(), e.org, walkInOrder) + require.NoError(t, err) + assert.False(t, preview.Eligible) + assert.Contains(t, preview.Reason, "walk-in") + _, err = e.payPoints(walkInOrder, 1000, "123456") + assert.ErrorIs(t, err, ErrPointPaymentRejected) + + order := e.order(customer, 10000) + _, err = e.payPoints(order, 1000, "000000") + assert.ErrorIs(t, err, ErrPointPaymentRejected, "a wrong code") + _, err = e.payPoints(order, 1000, e.code(other)) + assert.ErrorIs(t, err, ErrPointPaymentRejected, "another customer's code") + missing := int64(1000) + _, err = e.orders.CreatePayment(e.ctx, &models.CreatePaymentRequest{OrderID: order, PaymentMethodID: e.point, Points: &missing}) + assert.ErrorIs(t, err, ErrPointPaymentRejected, "no code at all") + + code := e.code(customer) + _, err = e.payPoints(order, 1000, code) + require.NoError(t, err) + _, err = e.payPoints(order, 1000, code) + assert.ErrorIs(t, err, ErrPointPaymentRejected, "a code is used once, so a double tap takes once") + _, err = e.payPoints(order, 9001, e.code(customer)) + assert.ErrorIs(t, err, ErrPointPaymentRejected, "no change is given: not more than what is left") + + // Splitting with the EnakPoint method would skip the balance, so it is refused. + e.orders.splitBillProcessor = splitFake{} + _, err = e.orders.SplitBill(e.ctx, &models.SplitBillRequest{OrderID: order, PaymentMethodID: e.point, Type: "AMOUNT", Amount: 1000}) + assert.ErrorIs(t, err, ErrPointPaymentRejected) + + assert.Equal(t, int64(99000), e.balance(customer), "only the one payment took anything") + assert.Equal(t, int64(100000), e.balance(other)) +} + +// Two payments for the same customer at once, on two orders: the balance is taken +// once, never twice. Authorization is taken as given so only the balance decides. +func TestPointPayment_ConcurrentForOneCustomer(t *testing.T) { + e := newPointPaymentEnv(t) + customer := e.customerWith(30000) + orders := []uuid.UUID{e.order(customer, 20000), e.order(customer, 20000)} + + var wg sync.WaitGroup + results := make([]error, len(orders)) + for i, order := range orders { + wg.Add(1) + go func(i int, order uuid.UUID) { + defer wg.Done() + _, results[i] = e.payments.Pay(e.ctx, PointPaymentInput{ + OrderID: order, PaymentMethodID: e.point, Points: 20000, + Authorize: func(context.Context, uuid.UUID) error { return nil }, + }) + }(i, order) + } + wg.Wait() + + succeeded := 0 + for _, err := range results { + if err == nil { + succeeded++ + } else { + assert.ErrorIs(t, err, ErrPointPaymentRejected) + } + } + assert.Equal(t, 1, succeeded, "30.000 EnakPoint pays one 20.000 order, not two") + assert.Equal(t, int64(10000), e.balance(customer)) + + // And the wallet still reconciles. + found, err := repository.NewWalletReconciliationRepository(e.db).FindDiscrepancies(context.Background(), 1000) + require.NoError(t, err) + for _, d := range found { + assert.NotEqual(t, customer, d.CustomerID, d.Check) + } +} + +func TestPointPayment_InApp(t *testing.T) { + e := newPointPaymentEnv(t) + owner := e.customerWith(100000) + stranger := e.customerWith(100000) + order := e.order(owner, 60000) + info := models.CustomerPinRequestInfo{} + + // Another customer cannot pay it, and is not told it exists. + _, err := e.orders.PayWithPointsInApp(e.ctx, stranger, order, 1000, "482913", info) + assert.ErrorIs(t, err, repository.ErrPointPaymentOrderNotFound) + _, err = e.orders.PayWithPointsInApp(e.ctx, owner, uuid.New(), 1000, "482913", info) + assert.ErrorIs(t, err, repository.ErrPointPaymentOrderNotFound) + + // The session alone is not enough: a wrong PIN takes nothing. + _, err = e.orders.PayWithPointsInApp(e.ctx, owner, order, 1000, "000000", info) + var pe *PinError + require.ErrorAs(t, err, &pe) + assert.Equal(t, PinErrInvalid, pe.Code) + assert.Equal(t, int64(100000), e.balance(owner)) + + // The owner pays part, then the rest, with the same rules as at the cashier. + payment, err := e.orders.PayWithPointsInApp(e.ctx, owner, order, 10000, "482913", info) + require.NoError(t, err) + assert.Equal(t, int64(10000), *payment.PointsUsed) + status, remaining := e.orderState(order) + assert.Equal(t, "partial", status) + assert.Equal(t, 50000.0, remaining) + + _, err = e.orders.PayWithPointsInApp(e.ctx, owner, order, 50001, "482913", info) + assert.ErrorIs(t, err, ErrPointPaymentRejected, "not more than what is left") + _, err = e.orders.PayWithPointsInApp(e.ctx, owner, order, 50000, "482913", info) + require.NoError(t, err) + status, _ = e.orderState(order) + assert.Equal(t, "completed", status) + assert.Equal(t, int64(40000), e.balance(owner)) + assert.Equal(t, int64(100000), e.balance(stranger)) + + var createdBy *string + require.NoError(t, e.db.Raw(`SELECT created_by_user::text FROM wallet_transactions WHERE customer_id = ? AND type = 'PAYMENT' LIMIT 1`, owner).Scan(&createdBy).Error) + assert.Nil(t, createdBy, "no cashier took an in-app payment") +} + +// The payment method report counts only money actually received as money in; the +// EnakPoint part is listed apart (F9). +func TestPointPayment_ReportKeepsEnakPointOutOfCashIn(t *testing.T) { + e := newPointPaymentEnv(t) + customer := e.customerWith(100000) + order := e.order(customer, 87500) + _, err := e.payPoints(order, 20000, e.code(customer)) + require.NoError(t, err) + _, err = e.orders.CreatePayment(e.ctx, &models.CreatePaymentRequest{OrderID: order, PaymentMethodID: e.cash, Amount: 67500}) + require.NoError(t, err) + + report, err := NewAnalyticsProcessorImpl(repository.NewAnalyticsRepositoryImpl(e.db), nil).GetPaymentMethodAnalytics(context.Background(), + &models.PaymentMethodAnalyticsRequest{OrganizationID: e.org, DateFrom: time.Now().Add(-time.Hour), DateTo: time.Now().Add(time.Hour)}) + require.NoError(t, err) + assert.Equal(t, 67500.0, report.Summary.TotalAmount, "money in is the cash, not the order total") + assert.Equal(t, 20000.0, report.Summary.PointAmount) + assert.Equal(t, int64(20000), report.Summary.PointsUsed) + assert.Equal(t, 87500.0, report.Summary.TotalWithPoints) + require.Len(t, report.Data, 2) + for _, d := range report.Data { + assert.Equal(t, d.PaymentMethodType != "point", d.CountsAsCashIn, d.PaymentMethodName) + } +} diff --git a/internal/processor/point_payment_method_db_test.go b/internal/processor/point_payment_method_db_test.go new file mode 100644 index 0000000..eb912ed --- /dev/null +++ b/internal/processor/point_payment_method_db_test.go @@ -0,0 +1,118 @@ +package processor + +import ( + "context" + "os" + "testing" + + "github.com/google/uuid" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "gorm.io/driver/postgres" + "gorm.io/gorm" + "gorm.io/gorm/logger" + + "apskel-pos-be/internal/constants" + "apskel-pos-be/internal/models" + "apskel-pos-be/internal/repository" +) + +// Needs TEST_DATABASE_URL pointing at a migrated database; see +// internal/repository/wallet_repository_test.go. +func TestPointPaymentMethod_AgainstPostgres(t *testing.T) { + dsn := os.Getenv("TEST_DATABASE_URL") + if dsn == "" { + t.Skip("TEST_DATABASE_URL not set") + } + db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{Logger: logger.Default.LogMode(logger.Silent)}) + require.NoError(t, err) + ctx := context.Background() + + org, user, accepting, refusing := uuid.New(), uuid.New(), uuid.New(), uuid.New() + exec := func(q string, args ...any) error { return db.Exec(q, args...).Error } + require.NoError(t, exec(`INSERT INTO organizations (id, name, plan_type) VALUES (?, 'pm test', 'basic')`, org)) + require.NoError(t, exec(`INSERT INTO outlets (id, organization_id, name) VALUES (?, ?, 'Terima'), (?, ?, 'Tolak')`, accepting, org, refusing, org)) + t.Cleanup(func() { + db.Exec(`DELETE FROM loyalty_setting_changes WHERE organization_id = ?`, org) + db.Exec(`DELETE FROM outlet_settings WHERE outlet_id IN ?`, []uuid.UUID{accepting, refusing}) + db.Exec(`DELETE FROM outlets WHERE id IN ?`, []uuid.UUID{accepting, refusing}) + db.Exec(`DELETE FROM payment_methods WHERE organization_id = ?`, org) + db.Exec(`DELETE FROM organizations WHERE id = ?`, org) + }) + + // A new organization gets exactly one EnakPoint method from the trigger. + var methods []struct { + ID string + Name string + Type string + } + require.NoError(t, db.Raw(`SELECT id::text AS id, name, type FROM payment_methods WHERE organization_id = ?`, org).Scan(&methods).Error) + require.Len(t, methods, 1) + assert.Equal(t, "EnakPoint", methods[0].Name) + assert.Equal(t, "point", methods[0].Type) + pointID := uuid.MustParse(methods[0].ID) + + // The database refuses a second one. + assert.Error(t, exec(`INSERT INTO payment_methods (organization_id, name, type) VALUES (?, 'EnakPoint 2', 'point')`, org)) + + txm := repository.NewTxManager(db) + settings := NewLoyaltySettingsProcessor(repository.NewLoyaltySettingsRepository(db), txm) + s, err := settings.Outlet(ctx, accepting) + require.NoError(t, err) + s.PointPayment.AcceptPayment = true + _, err = settings.UpdateOutlet(ctx, org, accepting, user, *s) + require.NoError(t, err) + + p := NewPaymentMethodProcessorImpl(repository.NewPaymentMethodRepositoryImpl(db), settings) + cash, err := p.CreatePaymentMethod(ctx, &models.CreatePaymentMethodRequest{OrganizationID: org, Name: "Tunai", Type: constants.PaymentMethodTypeCash, IsActive: ptr(true)}) + require.NoError(t, err) + + // The API cannot make, retype or delete an EnakPoint method. + _, err = p.CreatePaymentMethod(ctx, &models.CreatePaymentMethodRequest{OrganizationID: org, Name: "Poin Lain", Type: constants.PaymentMethodTypePoint, IsActive: ptr(true)}) + assert.ErrorIs(t, err, ErrSystemPaymentMethod) + toCash := constants.PaymentMethodTypeCash + _, err = p.UpdatePaymentMethod(ctx, pointID, &models.UpdatePaymentMethodRequest{Type: &toCash}) + assert.ErrorIs(t, err, ErrSystemPaymentMethod) + toPoint := constants.PaymentMethodTypePoint + _, err = p.UpdatePaymentMethod(ctx, cash.ID, &models.UpdatePaymentMethodRequest{Type: &toPoint}) + assert.ErrorIs(t, err, ErrSystemPaymentMethod) + assert.ErrorIs(t, p.DeletePaymentMethod(ctx, pointID), ErrSystemPaymentMethod) + + // Renaming it is fine; its type stays. + name := "Bayar pakai EnakPoint" + renamed, err := p.UpdatePaymentMethod(ctx, pointID, &models.UpdatePaymentMethodRequest{Name: &name, Type: &toPoint}) + require.NoError(t, err) + assert.Equal(t, name, renamed.Name) + + // At the cashier it shows only where the outlet accepts EnakPoint. + types := func(outlet *uuid.UUID) []constants.PaymentMethodType { + t.Helper() + list, err := p.ListPaymentMethods(ctx, &models.ListPaymentMethodsRequest{OrganizationID: &org, OutletID: outlet, Page: 1, Limit: 50}) + require.NoError(t, err) + var out []constants.PaymentMethodType + for _, m := range list.PaymentMethods { + out = append(out, m.Type) + } + assert.Equal(t, len(out), list.TotalCount, "the count matches what is listed") + return out + } + assert.ElementsMatch(t, []constants.PaymentMethodType{"cash", "point"}, types(&accepting)) + assert.ElementsMatch(t, []constants.PaymentMethodType{"cash"}, types(&refusing)) + assert.ElementsMatch(t, []constants.PaymentMethodType{"cash", "point"}, types(nil), "the dashboard, without an outlet, sees it") + + // A payment either records both points_used and point_value, or neither. + var orderID uuid.UUID + require.NoError(t, exec(`INSERT INTO users (id, organization_id, name, email, password_hash, role) VALUES (?, ?, 'K', ?, 'x', 'cashier')`, user, org, user.String()+"@t")) + orderID = uuid.New() + require.NoError(t, exec(`INSERT INTO orders (id, organization_id, outlet_id, user_id, order_number, order_type, subtotal, tax_amount, total_amount) + VALUES (?, ?, ?, ?, ?, 'dine_in', 1000, 0, 1000)`, orderID, org, accepting, user, "PM-"+orderID.String()[:8])) + t.Cleanup(func() { + db.Exec(`DELETE FROM payments WHERE order_id = ?`, orderID) + db.Exec(`DELETE FROM orders WHERE id = ?`, orderID) + db.Exec(`DELETE FROM users WHERE id = ?`, user) + }) + assert.Error(t, exec(`INSERT INTO payments (order_id, payment_method_id, amount, points_used) VALUES (?, ?, 1000, 1000)`, orderID, pointID)) + assert.Error(t, exec(`INSERT INTO payments (order_id, payment_method_id, amount, points_used, point_value) VALUES (?, ?, 1000, 0, 1)`, orderID, pointID)) + assert.NoError(t, exec(`INSERT INTO payments (order_id, payment_method_id, amount, points_used, point_value) VALUES (?, ?, 1000, 1000, 1)`, orderID, pointID)) + assert.NoError(t, exec(`INSERT INTO payments (order_id, payment_method_id, amount) VALUES (?, ?, 1000)`, orderID, cash.ID)) +} diff --git a/internal/processor/point_payment_processor.go b/internal/processor/point_payment_processor.go new file mode 100644 index 0000000..0e989cd --- /dev/null +++ b/internal/processor/point_payment_processor.go @@ -0,0 +1,336 @@ +package processor + +import ( + "context" + "errors" + "fmt" + "time" + + "github.com/google/uuid" + + "apskel-pos-be/internal/constants" + "apskel-pos-be/internal/entities" + "apskel-pos-be/internal/models" + "apskel-pos-be/internal/repository" +) + +// ErrPointPaymentRejected wraps every reason a payment with EnakPoint is refused: the +// order, the customer, the outlet or the amount. The message says which. +var ErrPointPaymentRejected = errors.New("EnakPoint payment refused") + +type pointPaymentSettings interface { + Outlet(ctx context.Context, outletID uuid.UUID) (*models.OutletLoyaltySettings, error) + PointValue(ctx context.Context, organizationID uuid.UUID) (int64, error) +} + +type spendableReader interface { + SpendableBalances(ctx context.Context, customerID uuid.UUID, asOf time.Time) (map[string]int64, error) +} + +// PointPaymentInput is one payment of an order with EnakPoint. +type PointPaymentInput struct { + OrderID uuid.UUID + PaymentMethodID uuid.UUID + Points int64 + // The cashier taking the payment at the POS; nil when the customer pays in the app. + CashierID *uuid.UUID + // Authorize proves the customer agreed, before anything is taken: at the POS it + // redeems the payment code, in the app it checks the PIN (K8). + Authorize func(ctx context.Context, customerID uuid.UUID) error +} + +// PointPaymentResult is the payment made and where it left the order. +type PointPaymentResult struct { + Payment *entities.Payment + // True when this payment settled the order. + Completed bool + // Rupiah still to pay with another method. + Remaining float64 +} + +// pointPaymentLimits applies the formula of docs/prd-point-coin.md F9, in cents: +// +// cap = min(remaining, total × max_payment_percent / 100 − already paid with EnakPoint) +// max_points = min(balance, floor(cap / point_value)) +type pointPaymentLimits struct { + RemainingCents int64 + CapCents int64 + MaxPoints int64 +} + +func computePointPaymentLimits(total, totalPaid, paidWithPoints float64, maxPercent, pointValue, balance int64) pointPaymentLimits { + remaining := toCents(total) - toCents(totalPaid) + if remaining < 0 { + remaining = 0 + } + byPercent := toCents(total)*maxPercent/100 - toCents(paidWithPoints) + capCents := min(remaining, byPercent) + if capCents < 0 { + capCents = 0 + } + maxPoints := int64(0) + if pointValue > 0 { + maxPoints = min(balance, capCents/(pointValue*100)) + } + if maxPoints < 0 { + maxPoints = 0 + } + return pointPaymentLimits{RemainingCents: remaining, CapCents: capCents, MaxPoints: maxPoints} +} + +// PointPaymentProcessor pays orders with EnakPoint (docs/prd-point-coin.md F9). +type PointPaymentProcessor struct { + repo repository.PointPaymentRepository + settings pointPaymentSettings + spendable spendableReader + wallet *WalletProcessor + tx TxRunner + now func() time.Time +} + +func NewPointPaymentProcessor(repo repository.PointPaymentRepository, settings pointPaymentSettings, spendable spendableReader, wallet *WalletProcessor, tx TxRunner) *PointPaymentProcessor { + return &PointPaymentProcessor{repo: repo, settings: settings, spendable: spendable, wallet: wallet, tx: tx, now: time.Now} +} + +// Preview is GET /orders/:id/point-payment/preview: whether the order can be paid with +// EnakPoint, and at most how much. +func (p *PointPaymentProcessor) Preview(ctx context.Context, organizationID, orderID uuid.UUID) (*models.PointPaymentPreview, error) { + order, err := p.repo.GetOrder(ctx, orderID, false) + if err != nil { + return nil, err + } + if order.OrganizationID != organizationID { + return nil, repository.ErrPointPaymentOrderNotFound + } + preview := &models.PointPaymentPreview{OrderID: orderID, CustomerID: order.CustomerID} + settings, err := p.settings.Outlet(ctx, order.OutletID) + if err != nil { + return nil, err + } + value, err := p.settings.PointValue(ctx, order.OrganizationID) + if err != nil { + return nil, err + } + preview.PointValue = value + preview.MinPaymentPoints = settings.PointPayment.MinPaymentPoints + preview.MaxPaymentPercent = settings.PointPayment.MaxPaymentPercent + + if reason := pointPaymentOrderProblem(order, settings); reason != "" { + preview.Reason = reason + return preview, nil + } + limits, balance, err := p.limits(ctx, order, settings, value) + if err != nil { + return nil, err + } + preview.PointBalance = balance + preview.RemainingAmount = float64(limits.RemainingCents) / 100 + preview.MaxPoints = limits.MaxPoints + preview.MaxAmount = limits.MaxPoints * value + if limits.MaxPoints < settings.PointPayment.MinPaymentPoints { + preview.Reason = "the customer cannot pay the minimum of EnakPoint on this order" + return preview, nil + } + preview.Eligible = true + return preview, nil +} + +// Pay takes EnakPoint from the order's customer and records the payment. The payment +// row, the ledger PAYMENT row, the balance and the order change in one transaction +// with the order row and the wallet locked (F9 steps 1–6). +func (p *PointPaymentProcessor) Pay(ctx context.Context, in PointPaymentInput) (*PointPaymentResult, error) { + reject := func(format string, args ...any) error { + return fmt.Errorf("%w: %s", ErrPointPaymentRejected, fmt.Sprintf(format, args...)) + } + if in.Points <= 0 { + return nil, reject("the number of EnakPoint must be positive") + } + order, err := p.repo.GetOrder(ctx, in.OrderID, false) + if err != nil { + return nil, err + } + methodOrg, methodType, err := p.repo.GetPaymentMethod(ctx, in.PaymentMethodID) + if err != nil { + return nil, err + } + if methodType != string(constants.PaymentMethodTypePoint) || methodOrg != order.OrganizationID { + return nil, reject("the payment method is not this organization's EnakPoint method") + } + settings, err := p.settings.Outlet(ctx, order.OutletID) + if err != nil { + return nil, err + } + if reason := pointPaymentOrderProblem(order, settings); reason != "" { + return nil, reject("%s", reason) + } + if in.Points < settings.PointPayment.MinPaymentPoints { + return nil, reject("at least %d EnakPoint must be used", settings.PointPayment.MinPaymentPoints) + } + customerID := *order.CustomerID + + // The customer agrees before anything is taken. A code is used up here even if the + // payment then fails, and the customer shows a new one. + if in.Authorize == nil { + return nil, reject("the customer has not approved the payment") + } + if err := in.Authorize(ctx, customerID); err != nil { + return nil, err + } + + result := &PointPaymentResult{} + err = p.tx.WithTransaction(ctx, func(ctx context.Context) error { + // Lock the order, then the wallet, and read everything again: another payment + // may have landed since the checks above. + order, err := p.repo.GetOrder(ctx, in.OrderID, true) + if err != nil { + return err + } + if reason := pointPaymentOrderProblem(order, settings); reason != "" { + return reject("%s", reason) + } + if err := p.wallet.LockWallet(ctx, customerID); err != nil { + return err + } + value, err := p.settings.PointValue(ctx, order.OrganizationID) + if err != nil { + return err + } + limits, _, err := p.limits(ctx, order, settings, value) + if err != nil { + return err + } + if in.Points > limits.MaxPoints { + return reject("at most %d EnakPoint can pay this order now", limits.MaxPoints) + } + amountCents := in.Points * value * 100 + // No change is ever given for EnakPoint (K7); the limits already keep it + // within what is left, this only guards that. + if amountCents > limits.RemainingCents { + return reject("EnakPoint cannot pay more than what is left on the order") + } + + pointsUsed := in.Points + frozenValue := float64(value) + payment := &entities.Payment{ + ID: uuid.New(), + OrderID: order.ID, + PaymentMethodID: in.PaymentMethodID, + Amount: float64(amountCents) / 100, + Status: entities.PaymentTransactionStatusCompleted, + PointsUsed: &pointsUsed, + PointValue: &frozenValue, + Metadata: entities.Metadata{"points_used": pointsUsed, "point_value": value}, + } + if err := p.repo.InsertPayment(ctx, payment); err != nil { + return err + } + + outletID := order.OutletID + if _, err := p.wallet.Debit(ctx, WalletDebitInput{WalletEntry: WalletEntry{ + CustomerID: customerID, + Currency: constants.WalletCurrencyPoint, + Type: constants.WalletTxTypePayment, + Amount: in.Points, + ReferenceType: constants.WalletRefTypePayment, + ReferenceID: payment.ID, + OutletID: &outletID, + CreatedByUser: in.CashierID, + Description: pointPaymentDescription(order, amountCents), + Metadata: entities.Metadata{"point_value": value, "amount": payment.Amount}, + IdempotencyKey: "payment:" + payment.ID.String(), + }}); err != nil { + if errors.Is(err, repository.ErrWalletInsufficientBalance) { + return reject("the customer does not have enough EnakPoint") + } + return err + } + + remainingCents := limits.RemainingCents - amountCents + completed := remainingCents == 0 + if err := p.repo.UpdateOrderAfterPayment(ctx, order.ID, float64(remainingCents)/100, completed); err != nil { + return err + } + result.Payment = payment + result.Completed = completed + result.Remaining = float64(remainingCents) / 100 + return nil + }) + if err != nil { + return nil, err + } + return result, nil +} + +func (p *PointPaymentProcessor) limits(ctx context.Context, order *repository.PointPaymentOrder, settings *models.OutletLoyaltySettings, value int64) (pointPaymentLimits, int64, error) { + totalPaid, err := p.repo.TotalPaid(ctx, order.ID) + if err != nil { + return pointPaymentLimits{}, 0, err + } + paidWithPoints, err := p.repo.PaidWithPoints(ctx, order.ID) + if err != nil { + return pointPaymentLimits{}, 0, err + } + balances, err := p.spendable.SpendableBalances(ctx, *order.CustomerID, p.now()) + if err != nil { + return pointPaymentLimits{}, 0, err + } + balance := balances[constants.WalletCurrencyPoint] + return computePointPaymentLimits(order.TotalAmount, totalPaid, paidWithPoints, settings.PointPayment.MaxPaymentPercent, value, balance), balance, nil +} + +// pointPaymentOrderProblem says why an order cannot be paid with EnakPoint at all, or +// "" when it can. +func pointPaymentOrderProblem(order *repository.PointPaymentOrder, settings *models.OutletLoyaltySettings) string { + switch { + case order.IsVoid: + return "the order is void" + case order.PaymentStatus == string(entities.PaymentStatusCompleted): + return "the order is already paid" + case !settings.PointPayment.AcceptPayment: + return "this outlet does not accept EnakPoint" + case order.CustomerID == nil || order.CustomerIsDefault == nil: + return "the order has no customer" + case *order.CustomerIsDefault: + return "a walk-in order cannot be paid with EnakPoint" + case order.CustomerIsActive == nil || !*order.CustomerIsActive: + return "the customer is not active" + } + return "" +} + +func pointPaymentDescription(order *repository.PointPaymentOrder, amountCents int64) string { + description := "Bayar #" + order.OrderNumber + if order.OutletName != "" { + description += " di " + order.OutletName + } + description += " (Rp " + formatRupiah(amountCents/100) + ")" + return truncateRunes(description, walletDescriptionLimit) +} + +// formatRupiah writes 50000 as 50.000. +func formatRupiah(n int64) string { + s := fmt.Sprintf("%d", n) + out := make([]byte, 0, len(s)+len(s)/3) + for i, c := range []byte(s) { + if i > 0 && (len(s)-i)%3 == 0 { + out = append(out, '.') + } + out = append(out, c) + } + return string(out) +} + +// PointMethodID returns the organization's EnakPoint payment method. +func (p *PointPaymentProcessor) PointMethodID(ctx context.Context, organizationID uuid.UUID) (uuid.UUID, error) { + return p.repo.PointMethodID(ctx, organizationID) +} + +// OrderOwner returns the organization and customer of an order, for checking that a +// customer pays only their own order. +func (p *PointPaymentProcessor) OrderOwner(ctx context.Context, orderID uuid.UUID) (organizationID uuid.UUID, customerID *uuid.UUID, err error) { + order, err := p.repo.GetOrder(ctx, orderID, false) + if err != nil { + return uuid.Nil, nil, err + } + return order.OrganizationID, order.CustomerID, nil +} diff --git a/internal/processor/point_payment_processor_test.go b/internal/processor/point_payment_processor_test.go new file mode 100644 index 0000000..4b879c3 --- /dev/null +++ b/internal/processor/point_payment_processor_test.go @@ -0,0 +1,39 @@ +package processor + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestComputePointPaymentLimits(t *testing.T) { + for name, c := range map[string]struct { + total, paid, paidWithPoints float64 + percent, value, balance int64 + wantRemaining, wantMax int64 + }{ + // The F9 example: Rp 87.550 left, 50.000 EnakPoint, 100%, Rp 1 a point. + "PRD example": {87550, 0, 0, 100, 1, 50000, 8755000, 50000}, + "balance covers it all": {87550, 0, 0, 100, 1, 100000, 8755000, 87550}, + "part already paid": {100000, 30000, 0, 100, 1, 100000, 7000000, 70000}, + "capped by percent": {100000, 0, 0, 50, 1, 100000, 10000000, 50000}, + "percent counts EnakPoint already used": {100000, 20000, 20000, 50, 1, 100000, 8000000, 30000}, + "percent cap already used": {100000, 50000, 50000, 50, 1, 100000, 5000000, 0}, + "point worth more than Rp 1": {87550, 0, 0, 100, 100, 1000, 8755000, 875}, + "nothing left": {50000, 50000, 0, 100, 1, 100000, 0, 0}, + "overpaid": {50000, 60000, 0, 100, 1, 100000, 0, 0}, + "no balance": {50000, 0, 0, 100, 1, 0, 5000000, 0}, + "cents left over": {10000.50, 0, 0, 100, 1, 100000, 1000050, 10000}, + } { + got := computePointPaymentLimits(c.total, c.paid, c.paidWithPoints, c.percent, c.value, c.balance) + assert.Equal(t, c.wantRemaining, got.RemainingCents, name) + assert.Equal(t, c.wantMax, got.MaxPoints, name) + assert.LessOrEqual(t, got.MaxPoints*c.value*100, got.RemainingCents, "%s: never more than what is left", name) + } +} + +func TestFormatRupiah(t *testing.T) { + for n, want := range map[int64]string{0: "0", 999: "999", 1000: "1.000", 50000: "50.000", 1234567: "1.234.567"} { + assert.Equal(t, want, formatRupiah(n)) + } +} diff --git a/internal/processor/point_payment_refund.go b/internal/processor/point_payment_refund.go new file mode 100644 index 0000000..9b6397a --- /dev/null +++ b/internal/processor/point_payment_refund.go @@ -0,0 +1,157 @@ +package processor + +import ( + "context" + "fmt" + + "github.com/google/uuid" + + "apskel-pos-be/internal/constants" + "apskel-pos-be/internal/entities" + "apskel-pos-be/internal/repository" +) + +// RefundForOrder gives EnakPoint back for the order's EnakPoint payments, as far as the +// order has been voided or those payments refunded (docs/prd-point-coin.md F9, K7): +// +// - void: every EnakPoint used on the order; +// - a refunded EnakPoint payment: floor(refunded rupiah / the frozen point value), +// so a later change of the point value does not change how many come back, and a +// rupiah remainder below one EnakPoint is lost (Q13). +// +// Never more than the payment used, and only what has not come back yet, so it can be +// called again safely. Returned EnakPoint go back into lots with the expiry of the lots +// they were taken from, but at least seven days from the refund (note N4, decided). It +// returns how many came back in total. +func (p *PointPaymentProcessor) RefundForOrder(ctx context.Context, orderID uuid.UUID) (int64, error) { + order, err := p.repo.GetOrder(ctx, orderID, false) + if err != nil { + return 0, err + } + payments, err := p.repo.ListPointPayments(ctx, orderID) + if err != nil { + return 0, err + } + + var returned int64 + for _, payment := range payments { + if payment.LedgerID == nil || payment.CustomerID == nil { + continue + } + target := pointRefundTarget(order.IsVoid, payment) + if target == 0 { + continue + } + var n int64 + err := p.tx.WithTransaction(ctx, func(ctx context.Context) error { + if err := p.wallet.LockWallet(ctx, *payment.CustomerID); err != nil { + return err + } + allocations, err := p.repo.PaymentAllocations(ctx, *payment.LedgerID) + if err != nil { + return err + } + refunded, err := p.repo.RefundedByOriginLot(ctx, *payment.LedgerID) + if err != nil { + return err + } + var already int64 + for _, amount := range refunded { + already += amount + } + toReturn := target - already + if toReturn <= 0 { + return nil + } + + // Fill the lots the payment took from, each up to what it gave. + var lots []WalletLotInput + left := toReturn + for _, a := range allocations { + if left == 0 { + break + } + room := a.Amount - refunded[a.LotID] + if room <= 0 { + continue + } + take := min(room, left) + left -= take + lotID := a.LotID + lots = append(lots, WalletLotInput{Amount: take, ExpiresAt: RefundExpiry(a.ExpiresAt, p.now()), OriginLotID: &lotID}) + } + toReturn -= left + + ledgerID := *payment.LedgerID + if _, err := p.wallet.Credit(ctx, WalletCreditInput{ + WalletEntry: WalletEntry{ + CustomerID: *payment.CustomerID, + Currency: constants.WalletCurrencyPoint, + Type: constants.WalletTxTypePaymentRefund, + Amount: toReturn, + ReferenceType: constants.WalletRefTypePayment, + ReferenceID: payment.PaymentID, + ReversesTransactionID: &ledgerID, + OutletID: payment.OutletID, + Description: pointRefundDescription(order), + Metadata: entities.Metadata{"point_value": payment.PointValue, "target": target, "void": order.IsVoid}, + IdempotencyKey: fmt.Sprintf("payment-refund:%s:%d", payment.PaymentID, target), + }, + Lots: lots, + }); err != nil { + return err + } + n = toReturn + return nil + }) + if err != nil { + return returned, fmt.Errorf("refunding EnakPoint payment %s: %w", payment.PaymentID, err) + } + returned += n + } + return returned, nil +} + +// EnsureOrderRefundAllowed refuses an order-level refund that would hand back, in cash +// or another method, what was paid with EnakPoint (K7). The EnakPoint part is refunded +// through its own payment, and comes back as EnakPoint. +func (p *PointPaymentProcessor) EnsureOrderRefundAllowed(ctx context.Context, orderID uuid.UUID, amount float64) error { + refundable, err := p.repo.RefundableByOtherMethods(ctx, orderID) + if err != nil { + return err + } + paidWithPoints, err := p.repo.PaidWithPoints(ctx, orderID) + if err != nil { + return err + } + if paidWithPoints == 0 { + return nil + } + if toCents(amount) > toCents(refundable) { + return fmt.Errorf("%w: at most Rp %s can be refunded this way; the part paid with EnakPoint is refunded through its EnakPoint payment and returns as EnakPoint", + ErrPointPaymentRejected, formatRupiah(toCents(refundable)/100)) + } + return nil +} + +func pointRefundTarget(orderVoid bool, payment repository.PointPaymentRow) int64 { + if orderVoid { + return payment.PointsUsed + } + if payment.Status != string(entities.PaymentTransactionStatusRefunded) { + return 0 + } + valueCents := toCents(payment.PointValue) + if valueCents <= 0 { + return 0 + } + return min(payment.PointsUsed, toCents(payment.RefundAmount)/valueCents) +} + +func pointRefundDescription(order *repository.PointPaymentOrder) string { + description := "Pengembalian #" + order.OrderNumber + if order.OutletName != "" { + description += " di " + order.OutletName + } + return truncateRunes(description, walletDescriptionLimit) +} diff --git a/internal/processor/point_refund_db_test.go b/internal/processor/point_refund_db_test.go new file mode 100644 index 0000000..55a5e59 --- /dev/null +++ b/internal/processor/point_refund_db_test.go @@ -0,0 +1,151 @@ +package processor + +import ( + "context" + "testing" + "time" + + "github.com/google/uuid" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "apskel-pos-be/internal/constants" + "apskel-pos-be/internal/models" + "apskel-pos-be/internal/repository" +) + +func (e *pointPaymentEnv) sum(query string, args ...any) int64 { + e.t.Helper() + var n int64 + require.NoError(e.t, e.db.Raw(query, args...).Scan(&n).Error) + return n +} + +func (e *pointPaymentEnv) returned(order uuid.UUID) int64 { + return e.sum(`SELECT COALESCE(SUM(t.amount), 0) FROM wallet_transactions t + JOIN payments p ON p.id = t.reference_id + WHERE p.order_id = ? AND t.type = 'PAYMENT_REFUND'`, order) +} + +func (e *pointPaymentEnv) assertReconciled(customers ...uuid.UUID) { + e.t.Helper() + found, err := repository.NewWalletReconciliationRepository(e.db).FindDiscrepancies(context.Background(), 1000) + require.NoError(e.t, err) + for _, d := range found { + for _, c := range customers { + assert.NotEqual(e.t, c, d.CustomerID, d.Check) + } + } +} + +func TestPointRefund_VoidReturnsEverythingToItsExpiry(t *testing.T) { + e := newPointPaymentEnv(t) + customer := e.customerWith(0) + expires := time.Now().Add(30 * 24 * time.Hour).Truncate(time.Second) + require.NoError(t, repository.NewTxManager(e.db).WithTransaction(context.Background(), func(ctx context.Context) error { + _, err := NewWalletProcessor(repository.NewWalletRepository(e.db)).Credit(ctx, WalletCreditInput{ + WalletEntry: WalletEntry{CustomerID: customer, Currency: constants.WalletCurrencyPoint, Type: constants.WalletTxTypeMigration, + Amount: 40000, ReferenceType: constants.WalletRefTypeLegacyPoints, ReferenceID: uuid.New(), Description: "Saldo awal"}, + Lots: []WalletLotInput{{Amount: 40000, ExpiresAt: &expires}}, + }) + return err + })) + + // Part of the order paid with EnakPoint, then the order is voided. + order := e.order(customer, 50000) + _, err := e.payPoints(order, 30000, e.code(customer)) + require.NoError(t, err) + assert.Equal(t, int64(10000), e.balance(customer)) + require.NoError(t, e.orders.VoidOrder(e.ctx, &models.VoidOrderRequest{OrderID: order, Type: "ALL", Reason: "batal"}, e.cashier)) + + assert.Equal(t, int64(30000), e.returned(order)) + assert.Equal(t, int64(40000), e.balance(customer)) + var expiry time.Time + require.NoError(t, e.db.Raw(`SELECT l.expires_at FROM wallet_lots l JOIN wallet_transactions t ON t.id = l.source_transaction_id + WHERE t.customer_id = ? AND t.type = 'PAYMENT_REFUND'`, customer).Scan(&expiry).Error) + assert.WithinDuration(t, expires, expiry, time.Second, "returned EnakPoint keep the expiry they had") + + // Calling it again returns nothing more. + e.orders.onOrderRefunded(e.ctx, order) + assert.Equal(t, int64(30000), e.returned(order)) + e.assertReconciled(customer) +} + +func TestPointRefund_PartialRefundFloors(t *testing.T) { + e := newPointPaymentEnv(t) + customer := e.customerWith(100000) + order := e.order(customer, 50000) + payment, err := e.payPoints(order, 50000, e.code(customer)) + require.NoError(t, err) + + // Rp 12.345,67 back at Rp 1 a point: 12.345 EnakPoint; the 67 sen are lost (Q13). + require.NoError(t, e.orders.RefundPayment(e.ctx, payment.ID, 12345.67, "sebagian", e.cashier)) + assert.Equal(t, int64(12345), e.returned(order)) + assert.Equal(t, int64(50000+12345), e.balance(customer)) + e.assertReconciled(customer) +} + +func TestPointRefund_UsesTheFrozenValue(t *testing.T) { + e := newPointPaymentEnv(t) + settings := NewLoyaltySettingsProcessor(repository.NewLoyaltySettingsRepository(e.db), repository.NewTxManager(e.db)) + setValue := func(v int64) { + s, err := settings.Organization(context.Background(), e.org) + require.NoError(t, err) + s.PointValue = v + _, _, err = settings.UpdateOrganization(context.Background(), e.org, e.cashier, *s) + require.NoError(t, err) + } + setValue(100) + + customer := e.customerWith(1000) + order := e.order(customer, 50000) + payment, err := e.payPoints(order, 500, e.code(customer)) + require.NoError(t, err) + assert.Equal(t, 50000.0, payment.Amount, "500 × Rp 100") + + // The value changes before the refund; the customer still gets back what they used. + setValue(250) + require.NoError(t, e.orders.RefundPayment(e.ctx, payment.ID, 50000, "semua", e.cashier)) + assert.Equal(t, int64(500), e.returned(order), "50.000 / the frozen Rp 100, not the new Rp 250") + assert.Equal(t, int64(1000), e.balance(customer)) +} + +func TestPointRefund_NoCashForTheEnakPointPart(t *testing.T) { + e := newPointPaymentEnv(t) + customer := e.customerWith(100000) + order := e.order(customer, 50000) + _, err := e.payPoints(order, 20000, e.code(customer)) + require.NoError(t, err) + _, err = e.orders.CreatePayment(e.ctx, &models.CreatePaymentRequest{OrderID: order, PaymentMethodID: e.cash, Amount: 30000}) + require.NoError(t, err) + + amount := 40000.0 + err = e.orders.RefundOrder(e.ctx, order, &models.RefundOrderRequest{RefundAmount: &amount}, e.cashier) + assert.ErrorIs(t, err, ErrPointPaymentRejected, "Rp 40.000 in cash would include EnakPoint") + var refunded float64 + require.NoError(t, e.db.Raw(`SELECT refund_amount FROM orders WHERE id = ?`, order).Scan(&refunded).Error) + assert.Zero(t, refunded, "nothing was written") + + amount = 30000 + require.NoError(t, e.orders.RefundOrder(e.ctx, order, &models.RefundOrderRequest{RefundAmount: &amount}, e.cashier), "the cash part can be refunded") + assert.Zero(t, e.returned(order), "and no EnakPoint came back for it") +} + +// Giving back the EnakPoint part does not take earning back: that part never earned. +func TestPointRefund_DoesNotReverseEarning(t *testing.T) { + e := newPointPaymentEnv(t) + customer := e.customerWith(100000) + order := e.order(customer, 87500) + pointPayment, err := e.payPoints(order, 20000, e.code(customer)) + require.NoError(t, err) + _, err = e.orders.CreatePayment(e.ctx, &models.CreatePaymentRequest{OrderID: order, PaymentMethodID: e.cash, Amount: 67500}) + require.NoError(t, err) + earned := e.sum(`SELECT COALESCE(SUM(amount), 0) FROM wallet_transactions WHERE reference_id = ? AND type = 'EARN'`, order) + require.Equal(t, int64(675), earned) + + require.NoError(t, e.orders.RefundPayment(e.ctx, pointPayment.ID, 20000, "kembali", e.cashier)) + assert.Equal(t, int64(20000), e.returned(order)) + reversed := e.sum(`SELECT COALESCE(SUM(-amount), 0) FROM wallet_transactions WHERE reference_id = ? AND type = 'EARN_REVERSAL'`, order) + assert.Zero(t, reversed, "the EnakPoint part never earned, so giving it back takes nothing") + e.assertReconciled(customer) +} diff --git a/internal/processor/wallet_admin_processor.go b/internal/processor/wallet_admin_processor.go new file mode 100644 index 0000000..3909a35 --- /dev/null +++ b/internal/processor/wallet_admin_processor.go @@ -0,0 +1,223 @@ +package processor + +import ( + "context" + "fmt" + "strings" + "time" + "unicode/utf8" + + "github.com/google/uuid" + + "apskel-pos-be/internal/constants" + "apskel-pos-be/internal/entities" + "apskel-pos-be/internal/models" + "apskel-pos-be/internal/repository" +) + +// walletDescriptionLimit is the size of wallet_transactions.description. +const walletDescriptionLimit = 255 + +// WalletAdminProcessor serves the dashboard's view of one customer's wallet and the +// manual adjustments an admin makes to it (docs/prd-point-coin.md F7). +type WalletAdminProcessor struct { + admin repository.WalletAdminRepository + query repository.WalletQueryRepository + wallet *WalletProcessor + settings organizationSettingsReader + tx TxRunner + now func() time.Time +} + +func NewWalletAdminProcessor(admin repository.WalletAdminRepository, query repository.WalletQueryRepository, wallet *WalletProcessor, settings organizationSettingsReader, tx TxRunner) *WalletAdminProcessor { + return &WalletAdminProcessor{admin: admin, query: query, wallet: wallet, settings: settings, tx: tx, now: time.Now} +} + +// GetCustomerWallet returns the customer's balances, lots and a page of history. +// A customer outside the organization is reported as not found. +func (p *WalletAdminProcessor) GetCustomerWallet(ctx context.Context, organizationID, customerID uuid.UUID, query models.ListCustomerWalletTransactionsQuery) (*models.AdminCustomerWallet, error) { + filter, page, err := walletTransactionFilter(customerID, query) + if err != nil { + return nil, err + } + customer, err := p.admin.GetCustomer(ctx, organizationID, customerID) + if err != nil { + return nil, err + } + now := p.now() + + result := &models.AdminCustomerWallet{ + Customer: models.AdminWalletCustomer{ID: customer.ID, Name: customer.Name, Phone: customer.Phone}, + Lots: []models.AdminWalletLot{}, + } + wallet, err := p.admin.GetWallet(ctx, customerID) + if err != nil { + return nil, err + } + if wallet != nil { + result.PointBalance = wallet.PointBalance + result.CoinBalance = wallet.CoinBalance + } + spendable, err := p.query.SpendableBalances(ctx, customerID, now) + if err != nil { + return nil, err + } + result.SpendablePointBalance = spendable[constants.WalletCurrencyPoint] + result.SpendableCoinBalance = spendable[constants.WalletCurrencyCoin] + + lots, err := p.admin.ListLotsWithBalance(ctx, customerID) + if err != nil { + return nil, err + } + for _, lot := range lots { + result.Lots = append(result.Lots, adminWalletLot(lot, now)) + } + + rows, total, err := p.query.ListTransactions(ctx, filter) + if err != nil { + return nil, err + } + transactions, err := p.adminTransactions(ctx, rows) + if err != nil { + return nil, err + } + result.Transactions = models.PaginatedResponse[models.AdminWalletTransaction]{ + Data: transactions, + Pagination: models.Pagination{ + Page: page, + Limit: filter.Limit, + Total: total, + TotalPages: int((total + int64(filter.Limit) - 1) / int64(filter.Limit)), + }, + } + return result, nil +} + +// Adjust adds to or takes from a customer's balance by hand. It is recorded as an +// ADJUSTMENT pointing at the admin, with the reason. Taking more than the customer +// can spend is refused with repository.ErrWalletInsufficientBalance. +func (p *WalletAdminProcessor) Adjust(ctx context.Context, organizationID, adminID, customerID uuid.UUID, in models.WalletAdjustment) (*models.AdminWalletAdjustmentResult, error) { + reason := strings.TrimSpace(in.Reason) + if adminID == uuid.Nil { + return nil, fmt.Errorf("%w: the admin making the adjustment is unknown", ErrWalletInvalidEntry) + } + if in.Amount == 0 { + return nil, fmt.Errorf("%w: amount must not be zero", ErrWalletInvalidEntry) + } + + entry := WalletEntry{ + CustomerID: customerID, + Currency: in.Currency, + Type: constants.WalletTxTypeAdjustment, + Amount: abs(in.Amount), + ReferenceType: constants.WalletRefTypeUser, + ReferenceID: adminID, + CreatedByUser: &adminID, + Reason: &reason, + Description: truncateRunes("Koreksi oleh admin: "+reason, walletDescriptionLimit), + } + if in.IdempotencyKey != "" { + // Scoped to the customer so a key chosen by the dashboard cannot collide with + // the keys other flows use. + entry.IdempotencyKey = fmt.Sprintf("adjust:%s:%s", customerID, in.IdempotencyKey) + } + + var res *WalletResult + err := p.tx.WithTransaction(ctx, func(ctx context.Context) error { + if _, err := p.admin.GetCustomer(ctx, organizationID, customerID); err != nil { + return err + } + if in.Amount < 0 { + var err error + res, err = p.wallet.Debit(ctx, WalletDebitInput{WalletEntry: entry}) + return err + } + // An adjustment that adds is a new balance, and expires like one (F7, F12). + settings, err := p.settings.Organization(ctx, organizationID) + if err != nil { + return err + } + res, err = p.wallet.Credit(ctx, WalletCreditInput{ + WalletEntry: entry, + Lots: []WalletLotInput{{Amount: entry.Amount, ExpiresAt: ComputeExpiry(ExpirySettings(settings, in.Currency), p.now())}}, + }) + return err + }) + if err != nil { + return nil, err + } + + transactions, err := p.adminTransactions(ctx, []entities.WalletTransaction{*res.Transaction}) + if err != nil { + return nil, err + } + spendable, err := p.query.SpendableBalances(ctx, customerID, p.now()) + if err != nil { + return nil, err + } + return &models.AdminWalletAdjustmentResult{ + Transaction: transactions[0], + SpendablePointBalance: spendable[constants.WalletCurrencyPoint], + SpendableCoinBalance: spendable[constants.WalletCurrencyCoin], + Replayed: res.Replayed, + }, nil +} + +// adminTransactions adds, to what the customer sees, the names behind each row. +func (p *WalletAdminProcessor) adminTransactions(ctx context.Context, rows []entities.WalletTransaction) ([]models.AdminWalletTransaction, error) { + base, err := buildWalletTransactions(ctx, p.query, rows) + if err != nil { + return nil, err + } + + var customerIDs, userIDs, outletIDs []uuid.UUID + for _, row := range rows { + if row.CounterpartyCustomerID != nil { + customerIDs = append(customerIDs, *row.CounterpartyCustomerID) + } + if row.CreatedByUser != nil { + userIDs = append(userIDs, *row.CreatedByUser) + } + if row.OutletID != nil { + outletIDs = append(outletIDs, *row.OutletID) + } + } + customers, err := p.admin.CustomerNames(ctx, customerIDs) + if err != nil { + return nil, err + } + users, err := p.admin.UserNames(ctx, userIDs) + if err != nil { + return nil, err + } + outlets, err := p.admin.OutletNames(ctx, outletIDs) + if err != nil { + return nil, err + } + named := func(id *uuid.UUID, names map[uuid.UUID]string) *models.AdminWalletNamedRef { + if id == nil { + return nil + } + return &models.AdminWalletNamedRef{ID: *id, Name: names[*id]} + } + + out := make([]models.AdminWalletTransaction, 0, len(rows)) + for i, row := range rows { + out = append(out, models.AdminWalletTransaction{ + CustomerWalletTransaction: base[i], + Counterparty: named(row.CounterpartyCustomerID, customers), + CreatedBy: named(row.CreatedByUser, users), + Outlet: named(row.OutletID, outlets), + Reason: row.Reason, + Metadata: row.Metadata, + }) + } + return out, nil +} + +func truncateRunes(s string, limit int) string { + if utf8.RuneCountInString(s) <= limit { + return s + } + return string([]rune(s)[:limit]) +} diff --git a/internal/processor/wallet_exchange_processor.go b/internal/processor/wallet_exchange_processor.go new file mode 100644 index 0000000..71552a1 --- /dev/null +++ b/internal/processor/wallet_exchange_processor.go @@ -0,0 +1,289 @@ +package processor + +import ( + "context" + "errors" + "fmt" + "strings" + "time" + + "github.com/google/uuid" + + "apskel-pos-be/internal/constants" + "apskel-pos-be/internal/entities" + "apskel-pos-be/internal/models" + "apskel-pos-be/internal/repository" +) + +// ErrWalletMoveRejected wraps every reason an exchange or a transfer is refused on +// the customer's side: the amount, the limits, the recipient or the balance. The +// message says which. +var ErrWalletMoveRejected = errors.New("wallet move refused") + +// walletMoveKeyLimit keeps a client's Idempotency-Key short enough to fit, with the +// prefix that scopes it to the customer, in wallet_transactions.idempotency_key. +const walletMoveKeyLimit = 50 + +type organizationSettingsReader interface { + Organization(ctx context.Context, organizationID uuid.UUID) (*models.OrganizationLoyaltySettings, error) +} + +// WalletExchangeProcessor exchanges EnakCoin into EnakPoint (docs/prd-point-coin.md +// F4, K3). It is one way only; nothing turns EnakPoint back into EnakCoin. +type WalletExchangeProcessor struct { + customers repository.WalletMoveRepository + settings organizationSettingsReader + spendable spendableReader + pins pinVerifier + wallet *WalletProcessor + tx TxRunner + now func() time.Time +} + +func NewWalletExchangeProcessor(customers repository.WalletMoveRepository, settings organizationSettingsReader, spendable spendableReader, pins pinVerifier, wallet *WalletProcessor, tx TxRunner) *WalletExchangeProcessor { + return &WalletExchangeProcessor{customers: customers, settings: settings, spendable: spendable, pins: pins, wallet: wallet, tx: tx, now: time.Now} +} + +// Preview is GET /customer/wallet/exchange/preview: the organization's rate and what +// exchanging coins would give, so the app can show it before asking for the PIN. +func (p *WalletExchangeProcessor) Preview(ctx context.Context, customerID uuid.UUID, coins int64) (*models.WalletExchangePreview, error) { + customer, err := p.customers.GetCustomer(ctx, customerID) + if err != nil { + return nil, err + } + settings, err := p.settings.Organization(ctx, customer.OrganizationID) + if err != nil { + return nil, err + } + balances, err := p.spendable.SpendableBalances(ctx, customerID, p.now()) + if err != nil { + return nil, err + } + rate := settings.Exchange + preview := &models.WalletExchangePreview{ + CoinAmount: rate.CoinAmount, + PointAmount: rate.PointAmount, + CoinBalance: balances[constants.WalletCurrencyCoin], + Coins: coins, + } + if reason := exchangeProblem(customer, rate, coins); reason != "" { + preview.Reason = reason + return preview, nil + } + preview.Points = exchangePoints(coins, rate) + if coins > preview.CoinBalance { + preview.Reason = "not enough EnakCoin" + return preview, nil + } + preview.Valid = true + return preview, nil +} + +// Exchange takes coins EnakCoin and gives the EnakPoint they are worth at the +// organization's rate, in one transaction. The two ledger rows share a group and +// point at each other, and both freeze the rate. Each EnakPoint lot keeps the expiry +// of the EnakCoin lot it came from, so exchanging cannot extend a balance's life +// (K9). The PIN approves it (K8). +// +// idempotencyKey is the client's Idempotency-Key: a retry with the same key returns +// the first exchange, at the rate it was made, without moving anything again. +func (p *WalletExchangeProcessor) Exchange(ctx context.Context, customerID uuid.UUID, coins int64, pin, idempotencyKey string, info models.CustomerPinRequestInfo) (*models.WalletExchangeResult, error) { + key, err := walletMoveKey(idempotencyKey) + if err != nil { + return nil, err + } + customer, err := p.customers.GetCustomer(ctx, customerID) + if err != nil { + return nil, err + } + settings, err := p.settings.Organization(ctx, customer.OrganizationID) + if err != nil { + return nil, err + } + // Refuse a malformed request before the PIN is checked, so a typo in the amount + // costs the customer no PIN attempt. + if reason := exchangeProblem(customer, settings.Exchange, coins); reason != "" { + return nil, fmt.Errorf("%w: %s", ErrWalletMoveRejected, reason) + } + if err := p.pins.VerifyPin(ctx, customerID, pin, PinActionExchange, info); err != nil { + return nil, err + } + + outKey := fmt.Sprintf("exchange:%s:%s:out", customerID, key) + inKey := fmt.Sprintf("exchange:%s:%s:in", customerID, key) + result := &models.WalletExchangeResult{Coins: coins} + err = p.tx.WithTransaction(ctx, func(ctx context.Context) error { + if err := p.wallet.LockWallet(ctx, customerID); err != nil { + return err + } + rate := settings.Exchange + groupID, outID, inID := uuid.New(), uuid.New(), uuid.New() + previous, err := p.wallet.FindTransaction(ctx, outKey) + if err != nil { + return err + } + if previous != nil && previous.GroupID != nil { + // A retry: repeat it with the ids and the rate the first attempt froze, so + // both rows replay even if the rate has changed since. + outID, inID, groupID = previous.ID, previous.ReferenceID, *previous.GroupID + rate = frozenExchangeRate(previous.Metadata, rate) + } + points := exchangePoints(coins, rate) + metadata := entities.Metadata{ + "coins": coins, + "points": points, + "coin_amount": rate.CoinAmount, + "point_amount": rate.PointAmount, + } + + out, err := p.wallet.Debit(ctx, WalletDebitInput{WalletEntry: WalletEntry{ + TransactionID: outID, + CustomerID: customerID, + Currency: constants.WalletCurrencyCoin, + Type: constants.WalletTxTypeExchangeOut, + Amount: coins, + ReferenceType: constants.WalletRefTypeWalletTx, + ReferenceID: inID, + GroupID: &groupID, + Description: fmt.Sprintf("Tukar %d EnakCoin ke EnakPoint", coins), + Metadata: metadata, + IdempotencyKey: outKey, + }}) + if errors.Is(err, repository.ErrWalletInsufficientBalance) { + return fmt.Errorf("%w: not enough EnakCoin", ErrWalletMoveRejected) + } + if err != nil { + return err + } + in, err := p.wallet.Credit(ctx, WalletCreditInput{ + WalletEntry: WalletEntry{ + TransactionID: inID, + CustomerID: customerID, + Currency: constants.WalletCurrencyPoint, + Type: constants.WalletTxTypeExchangeIn, + Amount: points, + ReferenceType: constants.WalletRefTypeWalletTx, + ReferenceID: outID, + GroupID: &groupID, + Description: fmt.Sprintf("Dari tukar %d EnakCoin", coins), + Metadata: metadata, + IdempotencyKey: inKey, + }, + Lots: exchangeLots(out.Allocations, rate, ComputeExpiry(settings.PointExpiry, p.now())), + }) + if err != nil { + return err + } + + result.GroupID = groupID + result.Points = points + result.CoinAmount = rate.CoinAmount + result.PointAmount = rate.PointAmount + result.Lots = movedLots(in.Lots) + result.Replayed = out.Replayed + return nil + }) + if err != nil { + return nil, err + } + + balances, err := p.spendable.SpendableBalances(ctx, customerID, p.now()) + if err != nil { + return nil, err + } + result.CoinBalance = balances[constants.WalletCurrencyCoin] + result.PointBalance = balances[constants.WalletCurrencyPoint] + return result, nil +} + +// exchangeProblem says why coins cannot be exchanged, or "" when they can as far as +// the request goes. The balance is checked under the wallet lock. +func exchangeProblem(customer *repository.WalletMoveCustomer, rate models.LoyaltyExchangeSettings, coins int64) string { + switch { + case !customer.IsActive: + return "the customer is not active" + case coins <= 0: + return "the number of EnakCoin must be positive" + case rate.CoinAmount <= 0 || rate.PointAmount <= 0: + return "exchange is not available" + case coins%rate.CoinAmount != 0: + // Otherwise part of the EnakCoin would be lost to rounding (F4). + return fmt.Sprintf("EnakCoin are exchanged in multiples of %d", rate.CoinAmount) + } + return "" +} + +// exchangePoints is (coins / coin_amount) × point_amount, for coins that are a +// multiple of coin_amount. +func exchangePoints(coins int64, rate models.LoyaltyExchangeSettings) int64 { + return coins / rate.CoinAmount * rate.PointAmount +} + +// exchangeLots splits the EnakPoint of an exchange over the EnakCoin lots it took, +// so each part keeps the expiry of its lot and points back at it (K9). The share of +// a lot is the difference of floor(coins so far × point_amount / coin_amount) before +// and after it, which adds up exactly because the total is a multiple of +// coin_amount. A lot too small to earn a whole EnakPoint on its own gives none. +// +// Each part expires at the sooner of its EnakCoin lot's expiry and pointExpiry, when an +// EnakPoint received now would expire (F4); nil means never. +func exchangeLots(allocations []WalletAllocation, rate models.LoyaltyExchangeSettings, pointExpiry *time.Time) []WalletLotInput { + var lots []WalletLotInput + var coinsSoFar int64 + for _, a := range allocations { + before := coinsSoFar * rate.PointAmount / rate.CoinAmount + coinsSoFar += a.Amount + points := coinsSoFar*rate.PointAmount/rate.CoinAmount - before + if points == 0 { + continue + } + lotID := a.LotID + lots = append(lots, WalletLotInput{Amount: points, ExpiresAt: EarlierExpiry(a.ExpiresAt, pointExpiry), OriginLotID: &lotID}) + } + return lots +} + +// frozenExchangeRate reads the rate an exchange was made at from its ledger row. +func frozenExchangeRate(metadata entities.Metadata, fallback models.LoyaltyExchangeSettings) models.LoyaltyExchangeSettings { + coinAmount, ok1 := metadataInt(metadata, "coin_amount") + pointAmount, ok2 := metadataInt(metadata, "point_amount") + if !ok1 || !ok2 || coinAmount <= 0 || pointAmount <= 0 { + return fallback + } + return models.LoyaltyExchangeSettings{CoinAmount: coinAmount, PointAmount: pointAmount} +} + +// metadataInt reads a whole number from metadata that may have been through JSONB, +// which gives numbers back as float64. +func metadataInt(metadata entities.Metadata, key string) (int64, bool) { + switch v := metadata[key].(type) { + case float64: + return int64(v), true + case int64: + return v, true + case int: + return int64(v), true + } + return 0, false +} + +func movedLots(lots []entities.WalletLot) []models.WalletMovedLot { + out := make([]models.WalletMovedLot, 0, len(lots)) + for _, lot := range lots { + out = append(out, models.WalletMovedLot{Amount: lot.OriginalAmount, ExpiresAt: lot.ExpiresAt}) + } + return out +} + +// walletMoveKey checks the client's Idempotency-Key, which exchanges and transfers +// require (F4, F5). +func walletMoveKey(key string) (string, error) { + key = strings.TrimSpace(key) + if key == "" { + return "", fmt.Errorf("%w: the Idempotency-Key header is required", ErrWalletMoveRejected) + } + if len(key) > walletMoveKeyLimit { + return "", fmt.Errorf("%w: the Idempotency-Key header must be at most %d characters", ErrWalletMoveRejected, walletMoveKeyLimit) + } + return key, nil +} diff --git a/internal/processor/wallet_exchange_processor_test.go b/internal/processor/wallet_exchange_processor_test.go new file mode 100644 index 0000000..a6d64c5 --- /dev/null +++ b/internal/processor/wallet_exchange_processor_test.go @@ -0,0 +1,354 @@ +package processor + +import ( + "context" + "errors" + "testing" + "time" + + "github.com/google/uuid" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "apskel-pos-be/internal/constants" + "apskel-pos-be/internal/entities" + "apskel-pos-be/internal/models" + "apskel-pos-be/internal/repository" +) + +// walletMoveEnv runs exchanges and transfers on the in-memory wallet, so every test +// also checks the §7.5 invariants when it ends. +type walletMoveEnv struct { + *walletTestEnv + customers *walletMoveRepoFake + settings *models.OrganizationLoyaltySettings + pins *movePinFake +} + +func newWalletMoveEnv(t *testing.T) *walletMoveEnv { + e := &walletMoveEnv{ + walletTestEnv: newWalletTestEnv(t), + customers: &walletMoveRepoFake{byID: map[uuid.UUID]*repository.WalletMoveCustomer{}}, + settings: &models.OrganizationLoyaltySettings{ + PointValue: 1, + Exchange: models.LoyaltyExchangeSettings{CoinAmount: 1, PointAmount: 1}, + Transfer: models.LoyaltyTransferSettings{Enabled: true, MinAmount: 1}, + }, + pins: &movePinFake{good: "482913"}, + } + e.customers.ledger = e.repo + // Ledger rows are stamped from now on, so "today" is the day of e.now. + e.repo.clock = e.now + return e +} + +// member adds an active customer of the organization. +func (e *walletMoveEnv) member(name, phone string) uuid.UUID { + id := e.customer() + e.customers.byID[id] = &repository.WalletMoveCustomer{ + ID: id, OrganizationID: e.org, Name: name, PhoneNumber: &phone, IsActive: true, + } + return id +} + +func (e *walletMoveEnv) exchanges() *WalletExchangeProcessor { + p := NewWalletExchangeProcessor(e.customers, e, e, e.pins, e.p, txRunnerFake{}) + p.now = func() time.Time { return e.now } + return p +} + +func (e *walletMoveEnv) transfers(notifier customerNotifier) *WalletTransferProcessor { + p := NewWalletTransferProcessor(e.customers, e, e, e.pins, e.p, txRunnerFake{}, notifier) + p.now = func() time.Time { return e.now } + return p +} + +func (e *walletMoveEnv) Organization(context.Context, uuid.UUID) (*models.OrganizationLoyaltySettings, error) { + s := *e.settings + return &s, nil +} + +// SpendableBalances sums the unexpired lots, as the real query does. +func (e *walletMoveEnv) SpendableBalances(_ context.Context, customerID uuid.UUID, asOf time.Time) (map[string]int64, error) { + out := map[string]int64{} + for _, lot := range e.repo.lots { + if lot.CustomerID == customerID && (lot.ExpiresAt == nil || lot.ExpiresAt.After(asOf)) { + out[lot.Currency] += lot.RemainingAmount + } + } + return out, nil +} + +// earnCoins gives a customer an EnakCoin lot. +func (e *walletMoveEnv) earnCoins(t *testing.T, customerID uuid.UUID, amount int64, expiresAt *time.Time) *WalletResult { + t.Helper() + in := earn(customerID, amount, expiresAt) + in.Currency = constants.WalletCurrencyCoin + return e.credit(t, in) +} + +func (e *walletMoveEnv) coinBalance(t *testing.T, customerID uuid.UUID) int64 { + t.Helper() + w, err := e.repo.GetWallet(e.ctx, customerID) + require.NoError(t, err) + return w.CoinBalance +} + +type walletMoveRepoFake struct { + byID map[uuid.UUID]*repository.WalletMoveCustomer + ledger *walletRepoFake +} + +func (f *walletMoveRepoFake) GetCustomer(_ context.Context, id uuid.UUID) (*repository.WalletMoveCustomer, error) { + c, ok := f.byID[id] + if !ok { + return nil, repository.ErrWalletNotFound + } + copied := *c + return &copied, nil +} + +func (f *walletMoveRepoFake) FindCustomerByPhone(ctx context.Context, phone string) (*repository.WalletMoveCustomer, error) { + for id, c := range f.byID { + if c.PhoneNumber != nil && *c.PhoneNumber == phone { + return f.GetCustomer(ctx, id) + } + } + return nil, repository.ErrWalletNotFound +} + +func (f *walletMoveRepoFake) TransferredOutSince(_ context.Context, customerID uuid.UUID, currency string, since time.Time) (int64, error) { + var total int64 + for _, tx := range f.ledger.transactions { + if tx.CustomerID == customerID && tx.Currency == currency && tx.Type == constants.WalletTxTypeTransferOut && !tx.CreatedAt.Before(since) { + total -= tx.Amount + } + } + return total, nil +} + +// movePinFake accepts one PIN and records the actions it was asked to approve. +type movePinFake struct { + good string + err error + actions []PinAction +} + +func (f *movePinFake) VerifyPin(_ context.Context, _ uuid.UUID, pin string, action PinAction, _ models.CustomerPinRequestInfo) error { + f.actions = append(f.actions, action) + if f.err != nil { + return f.err + } + if pin != f.good { + return &PinError{Code: PinErrInvalid, RemainingAttempts: 4} + } + return nil +} + +func TestWalletExchange_DefaultRateIsOneToOne(t *testing.T) { + e := newWalletMoveEnv(t) + c := e.member("Budi Santoso", "081234561234") + e.earnCoins(t, c, 50, nil) + + res, err := e.exchanges().Exchange(e.ctx, c, 50, "482913", "key-1", models.CustomerPinRequestInfo{}) + require.NoError(t, err) + + assert.Equal(t, int64(50), res.Points) + assert.Equal(t, int64(0), res.CoinBalance) + assert.Equal(t, int64(50), res.PointBalance) + assert.Equal(t, []PinAction{PinActionExchange}, e.pins.actions) + + out, in := e.repo.transactions[1], e.repo.transactions[2] + assert.Equal(t, constants.WalletTxTypeExchangeOut, out.Type) + assert.Equal(t, constants.WalletCurrencyCoin, out.Currency) + assert.Equal(t, int64(-50), out.Amount) + assert.Equal(t, constants.WalletTxTypeExchangeIn, in.Type) + assert.Equal(t, constants.WalletCurrencyPoint, in.Currency) + assert.Equal(t, int64(50), in.Amount) + // The pair shares a group and each row points at the other (§8.1). + assert.Equal(t, *out.GroupID, *in.GroupID) + assert.Equal(t, res.GroupID, *out.GroupID) + assert.Equal(t, in.ID, out.ReferenceID) + assert.Equal(t, out.ID, in.ReferenceID) + assert.Equal(t, "Tukar 50 EnakCoin ke EnakPoint", out.Description) + assert.Equal(t, "Dari tukar 50 EnakCoin", in.Description) + // Both rows freeze the rate. + for _, row := range []*entities.WalletTransaction{out, in} { + assert.Equal(t, int64(1), row.Metadata["coin_amount"]) + assert.Equal(t, int64(1), row.Metadata["point_amount"]) + } +} + +func TestWalletExchange_TenCoinsForThreePoints(t *testing.T) { + e := newWalletMoveEnv(t) + e.settings.Exchange = models.LoyaltyExchangeSettings{CoinAmount: 10, PointAmount: 3} + c := e.member("Budi", "081234561234") + e.earnCoins(t, c, 35, nil) + + preview, err := e.exchanges().Preview(e.ctx, c, 30) + require.NoError(t, err) + assert.True(t, preview.Valid) + assert.Equal(t, int64(9), preview.Points) + assert.Equal(t, int64(35), preview.CoinBalance) + + res, err := e.exchanges().Exchange(e.ctx, c, 30, "482913", "key-1", models.CustomerPinRequestInfo{}) + require.NoError(t, err) + assert.Equal(t, int64(9), res.Points) + assert.Equal(t, int64(5), res.CoinBalance) + assert.Equal(t, int64(9), res.PointBalance) +} + +func TestWalletExchange_RefusesAmountsThatAreNotAMultiple(t *testing.T) { + e := newWalletMoveEnv(t) + e.settings.Exchange = models.LoyaltyExchangeSettings{CoinAmount: 10, PointAmount: 3} + c := e.member("Budi", "081234561234") + e.earnCoins(t, c, 50, nil) + + preview, err := e.exchanges().Preview(e.ctx, c, 25) + require.NoError(t, err) + assert.False(t, preview.Valid) + assert.Contains(t, preview.Reason, "multiples of 10") + + _, err = e.exchanges().Exchange(e.ctx, c, 25, "482913", "key-1", models.CustomerPinRequestInfo{}) + assert.ErrorIs(t, err, ErrWalletMoveRejected) + // Refused before the PIN, so a typo costs no attempt. + assert.Empty(t, e.pins.actions) + assert.Equal(t, int64(50), e.coinBalance(t, c)) + + _, err = e.exchanges().Exchange(e.ctx, c, 0, "482913", "key-2", models.CustomerPinRequestInfo{}) + assert.ErrorIs(t, err, ErrWalletMoveRejected) +} + +func TestWalletExchange_NeverOutlivesTheCoinLot(t *testing.T) { + e := newWalletMoveEnv(t) + e.settings.Exchange = models.LoyaltyExchangeSettings{CoinAmount: 10, PointAmount: 3} + c := e.member("Budi", "081234561234") + soon, later := e.at(24*time.Hour), e.at(48*time.Hour) + first := e.earnCoins(t, c, 15, soon) + second := e.earnCoins(t, c, 15, later) + third := e.earnCoins(t, c, 10, nil) + + // 40 EnakCoin take 15 from the lot expiring soonest, 15 from the next and 10 from + // the one that never expires, giving 12 EnakPoint split 4 + 5 + 3. + res, err := e.exchanges().Exchange(e.ctx, c, 40, "482913", "key-1", models.CustomerPinRequestInfo{}) + require.NoError(t, err) + require.Len(t, res.Lots, 3) + assert.Equal(t, models.WalletMovedLot{Amount: 4, ExpiresAt: soon}, res.Lots[0]) + assert.Equal(t, models.WalletMovedLot{Amount: 5, ExpiresAt: later}, res.Lots[1]) + assert.Equal(t, models.WalletMovedLot{Amount: 3}, res.Lots[2]) + + origins := map[uuid.UUID]*time.Time{} + for _, lot := range e.repo.lots { + if lot.Currency == constants.WalletCurrencyPoint { + require.NotNil(t, lot.OriginLotID) + origins[*lot.OriginLotID] = lot.ExpiresAt + } + } + assert.Equal(t, map[uuid.UUID]*time.Time{ + first.Lots[0].ID: soon, second.Lots[0].ID: later, third.Lots[0].ID: nil, + }, origins) + for _, lot := range e.repo.lots { + if lot.Currency != constants.WalletCurrencyPoint || lot.OriginLotID == nil { + continue + } + for _, coinLot := range e.repo.lots { + if coinLot.ID == *lot.OriginLotID && coinLot.ExpiresAt != nil { + require.NotNil(t, lot.ExpiresAt, "a lot that expires cannot become one that does not") + assert.False(t, lot.ExpiresAt.After(*coinLot.ExpiresAt)) + } + } + } +} + +func TestWalletExchange_LotTooSmallForAWholePointGivesNone(t *testing.T) { + e := newWalletMoveEnv(t) + e.settings.Exchange = models.LoyaltyExchangeSettings{CoinAmount: 10, PointAmount: 1} + c := e.member("Budi", "081234561234") + e.earnCoins(t, c, 5, e.at(time.Hour)) + e.earnCoins(t, c, 5, nil) + + // Neither lot is worth a whole EnakPoint alone; the one that completes the 10 + // carries it. + res, err := e.exchanges().Exchange(e.ctx, c, 10, "482913", "key-1", models.CustomerPinRequestInfo{}) + require.NoError(t, err) + assert.Equal(t, []models.WalletMovedLot{{Amount: 1}}, res.Lots) +} + +func TestWalletExchange_NotEnoughCoins(t *testing.T) { + e := newWalletMoveEnv(t) + c := e.member("Budi", "081234561234") + e.earnCoins(t, c, 5, nil) + + preview, err := e.exchanges().Preview(e.ctx, c, 6) + require.NoError(t, err) + assert.False(t, preview.Valid) + + _, err = e.exchanges().Exchange(e.ctx, c, 6, "482913", "key-1", models.CustomerPinRequestInfo{}) + assert.ErrorIs(t, err, ErrWalletMoveRejected) + assert.Equal(t, int64(5), e.coinBalance(t, c)) +} + +func TestWalletExchange_WrongPinMovesNothing(t *testing.T) { + e := newWalletMoveEnv(t) + c := e.member("Budi", "081234561234") + e.earnCoins(t, c, 5, nil) + + _, err := e.exchanges().Exchange(e.ctx, c, 5, "000000", "key-1", models.CustomerPinRequestInfo{}) + var pinErr *PinError + require.True(t, errors.As(err, &pinErr)) + assert.Equal(t, PinErrInvalid, pinErr.Code) + assert.Equal(t, int64(5), e.coinBalance(t, c)) +} + +func TestWalletExchange_RetryReturnsTheFirstExchangeAtItsRate(t *testing.T) { + e := newWalletMoveEnv(t) + c := e.member("Budi", "081234561234") + e.earnCoins(t, c, 100, nil) + + first, err := e.exchanges().Exchange(e.ctx, c, 40, "482913", "key-1", models.CustomerPinRequestInfo{}) + require.NoError(t, err) + // The rate changes before the retry arrives; the retry still gets the first result. + e.settings.Exchange = models.LoyaltyExchangeSettings{CoinAmount: 1, PointAmount: 2} + again, err := e.exchanges().Exchange(e.ctx, c, 40, "482913", "key-1", models.CustomerPinRequestInfo{}) + require.NoError(t, err) + + assert.True(t, again.Replayed) + assert.Equal(t, first.GroupID, again.GroupID) + assert.Equal(t, int64(40), again.Points) + assert.Equal(t, int64(60), e.coinBalance(t, c)) + assert.Len(t, e.repo.transactions, 3) + + // The same key for a different amount is not a retry. + _, err = e.exchanges().Exchange(e.ctx, c, 20, "482913", "key-1", models.CustomerPinRequestInfo{}) + assert.ErrorIs(t, err, ErrWalletIdempotencyConflict) +} + +func TestWalletExchange_RequiresAnIdempotencyKey(t *testing.T) { + e := newWalletMoveEnv(t) + c := e.member("Budi", "081234561234") + e.earnCoins(t, c, 5, nil) + + _, err := e.exchanges().Exchange(e.ctx, c, 5, "482913", " ", models.CustomerPinRequestInfo{}) + assert.ErrorIs(t, err, ErrWalletMoveRejected) + assert.Empty(t, e.pins.actions) +} + +// F4: EnakPoint from an exchange expire at the sooner of the EnakCoin lot's expiry and +// when EnakPoint received now would expire. +func TestWalletExchange_CappedByThePointExpiry(t *testing.T) { + e := newWalletMoveEnv(t) + e.now = wib(2026, 6, 1, 10, 0) + e.settings.PointExpiry = rolling(30, "DAY", false) + c := e.member("Budi", "081234561234") + soon, later := e.at(24*time.Hour), e.at(90*24*time.Hour) + e.earnCoins(t, c, 10, soon) + e.earnCoins(t, c, 10, later) + e.earnCoins(t, c, 10, nil) + + res, err := e.exchanges().Exchange(e.ctx, c, 30, "482913", "key-1", models.CustomerPinRequestInfo{}) + require.NoError(t, err) + require.Len(t, res.Lots, 3) + assert.Equal(t, soon, res.Lots[0].ExpiresAt, "the EnakCoin lot expires first") + assert.Equal(t, "2026-07-01", expiryDay(t, res.Lots[1].ExpiresAt), "30 days of EnakPoint come first") + assert.Equal(t, "2026-07-01", expiryDay(t, res.Lots[2].ExpiresAt), "a lot that never expired gets the EnakPoint expiry") +} diff --git a/internal/processor/wallet_expiry_processor.go b/internal/processor/wallet_expiry_processor.go new file mode 100644 index 0000000..b322362 --- /dev/null +++ b/internal/processor/wallet_expiry_processor.go @@ -0,0 +1,196 @@ +package processor + +import ( + "context" + "fmt" + "strconv" + "time" + + "github.com/google/uuid" + + "apskel-pos-be/internal/constants" + "apskel-pos-be/internal/logger" + "apskel-pos-be/internal/repository" +) + +const ( + // Lots expired per query; a run keeps going until nothing is due. + walletExpiryBatchSize = 500 + // Batches per run at most, so one run cannot run away. + walletExpiryMaxBatches = 40 +) + +// NotificationTypeWalletExpired is the data type of the push a customer gets when +// part of their balance expires. +const NotificationTypeWalletExpired = "WALLET_EXPIRED" + +// NotificationTypeWalletExpiring is the data type of the reminder a customer gets +// before part of their balance expires. +const NotificationTypeWalletExpiring = "WALLET_EXPIRING" + +// WalletExpiryProcessor takes what is left in lots whose expiry has passed +// (docs/prd-point-coin.md F12, PC-503). It is safe to run on several instances at +// once: every lot is expired under its wallet's lock with the key expire:{lot_id}. +type WalletExpiryProcessor struct { + repo repository.WalletExpiryRepository + settings organizationSettingsReader + wallet *WalletProcessor + tx TxRunner + notifier customerNotifier + now func() time.Time +} + +func NewWalletExpiryProcessor(repo repository.WalletExpiryRepository, settings organizationSettingsReader, wallet *WalletProcessor, tx TxRunner, notifier customerNotifier) *WalletExpiryProcessor { + return &WalletExpiryProcessor{repo: repo, settings: settings, wallet: wallet, tx: tx, notifier: notifier, now: time.Now} +} + +type walletExpiredKey struct { + customerID uuid.UUID + currency string +} + +// ExpireDue expires every lot due now and tells each customer how much of each +// currency they lost, in one push per currency. It returns how many lots it expired. +// A lot that fails is logged and left for the next run; it does not stop the others. +func (p *WalletExpiryProcessor) ExpireDue(ctx context.Context) (int, error) { + asOf := p.now() + expired := map[walletExpiredKey]int64{} + count := 0 + for batch := 0; batch < walletExpiryMaxBatches; batch++ { + due, err := p.repo.ListDueLots(ctx, asOf, walletExpiryBatchSize) + if err != nil { + p.notify(ctx, expired) + return count, err + } + progressed := false + for _, lot := range due { + var res *WalletResult + err := p.tx.WithTransaction(ctx, func(ctx context.Context) error { + var err error + res, err = p.wallet.ExpireLot(ctx, lot.ID, func(amount int64) string { + return expiryDescription(amount, lot.Currency, lot.SourceDescription) + }, asOf) + return err + }) + if err != nil { + logger.NonContext.Error(fmt.Sprintf("Could not expire wallet lot %s; it will be retried", lot.ID), err) + continue + } + if res == nil || res.Transaction == nil || res.Replayed { + // Another run got there first, or a payment used it up. + continue + } + progressed = true + count++ + expired[walletExpiredKey{lot.CustomerID, lot.Currency}] += -res.Transaction.Amount + } + // A short batch was the last; a batch that moved nothing would only come back + // the same, whether failing or taken by another instance. + if len(due) < walletExpiryBatchSize || !progressed { + break + } + } + p.notify(ctx, expired) + return count, nil +} + +// notify is best effort: the balance has already expired. +func (p *WalletExpiryProcessor) notify(ctx context.Context, expired map[walletExpiredKey]int64) { + if p.notifier == nil { + return + } + for key, amount := range expired { + name := walletCurrencyName(key.currency) + data := map[string]string{ + "type": NotificationTypeWalletExpired, + "currency": key.currency, + "amount": strconv.FormatInt(amount, 10), + } + body := fmt.Sprintf("%d %s kamu sudah kedaluwarsa.", amount, name) + if err := p.notifier.Notify(ctx, key.customerID, name+" kedaluwarsa", body, data); err != nil { + logger.NonContext.Error(fmt.Sprintf("Could not tell customer %s about expired %s", key.customerID, name), err) + } + } +} + +// expiryDescription is the EXPIRE row's frozen description (§8.1): +// "Kedaluwarsa: 150 EnakPoint dari Belanja #ORD-0098". +func expiryDescription(amount int64, currency, sourceDescription string) string { + description := fmt.Sprintf("Kedaluwarsa: %d %s", amount, walletCurrencyName(currency)) + if sourceDescription != "" { + description += " dari " + sourceDescription + } + return truncateRunes(description, walletDescriptionLimit) +} + +// SendReminders tells customers, reminder_days before, how much of their balance +// expires on a day (F12): one push per customer, currency and expiry day, however many +// lots make it up. A reminder is recorded before it is sent, so another instance or a +// later run never sends it again; a push that then fails is logged and not retried. +// It returns how many reminders it sent. +func (p *WalletExpiryProcessor) SendReminders(ctx context.Context) (int, error) { + now := p.now() + organizations, err := p.repo.OrganizationsWithUpcomingExpiry(ctx, now) + if err != nil { + return 0, err + } + sent := 0 + for _, organizationID := range organizations { + settings, err := p.settings.Organization(ctx, organizationID) + if err != nil { + logger.NonContext.Error(fmt.Sprintf("Could not read the expiry settings of organization %s; its reminders wait for the next run", organizationID), err) + continue + } + for _, currency := range []string{constants.WalletCurrencyPoint, constants.WalletCurrencyCoin} { + days := ExpirySettings(settings, currency).ReminderDays + if days <= 0 { + continue + } + until := endOfWalletDay(walletDay(now).AddDate(0, 0, int(days))) + upcoming, err := p.repo.UpcomingUnreminded(ctx, organizationID, currency, now, *until) + if err != nil { + return sent, err + } + for _, u := range upcoming { + first, err := p.repo.MarkReminded(ctx, u, currency) + if err != nil { + return sent, err + } + if !first { + continue + } + sent++ + p.remind(ctx, u, currency) + } + } + } + return sent, nil +} + +func (p *WalletExpiryProcessor) remind(ctx context.Context, u repository.UpcomingExpiry, currency string) { + if p.notifier == nil { + return + } + name := walletCurrencyName(currency) + body := fmt.Sprintf("%d %s akan kedaluwarsa pada %s. Pakai sebelum hangus.", u.Amount, name, formatWalletDate(u.Date)) + data := map[string]string{ + "type": NotificationTypeWalletExpiring, + "currency": currency, + "amount": strconv.FormatInt(u.Amount, 10), + "expiry_date": u.Date, + } + if err := p.notifier.Notify(ctx, u.CustomerID, name+" akan kedaluwarsa", body, data); err != nil { + logger.NonContext.Error(fmt.Sprintf("Could not remind customer %s of expiring %s", u.CustomerID, name), err) + } +} + +var walletMonthNames = [...]string{"Jan", "Feb", "Mar", "Apr", "Mei", "Jun", "Jul", "Agu", "Sep", "Okt", "Nov", "Des"} + +// formatWalletDate writes a YYYY-MM-DD date the way the apps do: "31 Okt 2026". +func formatWalletDate(date string) string { + d, err := time.Parse("2006-01-02", date) + if err != nil { + return date + } + return fmt.Sprintf("%d %s %d", d.Day(), walletMonthNames[d.Month()-1], d.Year()) +} diff --git a/internal/processor/wallet_expiry_processor_test.go b/internal/processor/wallet_expiry_processor_test.go new file mode 100644 index 0000000..d5bbbe8 --- /dev/null +++ b/internal/processor/wallet_expiry_processor_test.go @@ -0,0 +1,244 @@ +package processor + +import ( + "context" + "sort" + "testing" + "time" + + "github.com/google/uuid" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "apskel-pos-be/internal/constants" + "apskel-pos-be/internal/entities" + "apskel-pos-be/internal/repository" +) + +// walletExpiryRepoFake lists the fake wallet's due lots the way the query does, plus +// any extra lots a test wants listed. +type walletExpiryRepoFake struct { + wallet *walletRepoFake + extra []repository.DueLot + // customer/currency/date of the reminders recorded. + reminded map[string]bool +} + +func (f *walletExpiryRepoFake) ListDueLots(_ context.Context, asOf time.Time, limit int) ([]repository.DueLot, error) { + descriptions := map[uuid.UUID]string{} + for _, tx := range f.wallet.transactions { + descriptions[tx.ID] = tx.Description + } + due := append([]repository.DueLot(nil), f.extra...) + for _, lot := range f.wallet.lots { + if lot.RemainingAmount > 0 && lot.ExpiresAt != nil && !lot.ExpiresAt.After(asOf) { + due = append(due, repository.DueLot{ + ID: lot.ID, CustomerID: lot.CustomerID, Currency: lot.Currency, Remaining: lot.RemainingAmount, + ExpiresAt: *lot.ExpiresAt, SourceDescription: descriptions[lot.SourceTransactionID], + }) + } + } + sort.SliceStable(due, func(i, j int) bool { return due[i].ExpiresAt.Before(due[j].ExpiresAt) }) + if len(due) > limit { + due = due[:limit] + } + return due, nil +} + +func (e *walletMoveEnv) expiry(notifier customerNotifier) (*WalletExpiryProcessor, *walletExpiryRepoFake) { + repo := &walletExpiryRepoFake{wallet: e.repo} + p := NewWalletExpiryProcessor(repo, e, e.p, txRunnerFake{}, notifier) + p.now = func() time.Time { return e.now } + return p, repo +} + +func TestWalletExpiry_ExpiresWhatIsDueAndTellsTheCustomer(t *testing.T) { + e := newWalletMoveEnv(t) + a := e.member("Anita", "081200005678") + ord := earn(a, 150, e.at(-time.Hour)) + ord.Description = "Belanja #ORD-0098" + due := e.credit(t, ord) + e.credit(t, earn(a, 50, e.at(-2*time.Hour))) + e.credit(t, earn(a, 70, e.at(time.Hour))) // not yet + e.credit(t, earn(a, 30, nil)) // never + e.earnCoins(t, a, 4, e.at(-time.Minute)) + // A payment already used part of the first lot; only the rest expires. + _, err := e.p.Debit(e.ctx, WalletDebitInput{WalletEntry: pay(a, 20).WalletEntry, PreferredLotIDs: []uuid.UUID{due.Lots[0].ID}}) + require.NoError(t, err) + + notifier := ¬ifierFake{} + p, _ := e.expiry(notifier) + count, err := p.ExpireDue(e.ctx) + require.NoError(t, err) + + assert.Equal(t, 3, count) + assert.Equal(t, int64(100), e.balance(t, a), "70 not due yet + 30 that never expires") + assert.Equal(t, int64(0), e.coinBalance(t, a)) + + var expire *entities.WalletTransaction + for _, tx := range e.repo.transactions { + if tx.Type == constants.WalletTxTypeExpire && tx.ReferenceID == due.Lots[0].ID { + expire = tx + } + } + require.NotNil(t, expire) + assert.Equal(t, int64(-130), expire.Amount) + assert.Equal(t, "Kedaluwarsa: 130 EnakPoint dari Belanja #ORD-0098", expire.Description) + assert.Equal(t, constants.WalletRefTypeLot, expire.ReferenceType) + assert.Equal(t, "expire:"+due.Lots[0].ID.String(), *expire.IdempotencyKey) + + // One push per currency, with the total. + pushes := notifier.pushes[a] + require.Len(t, pushes, 2) + byCurrency := map[string]pushFake{} + for _, p := range pushes { + byCurrency[p.data["currency"]] = p + } + assert.Equal(t, "EnakPoint kedaluwarsa", byCurrency["POINT"].title) + assert.Equal(t, "180 EnakPoint kamu sudah kedaluwarsa.", byCurrency["POINT"].body) + assert.Equal(t, NotificationTypeWalletExpired, byCurrency["POINT"].data["type"]) + assert.Equal(t, "4", byCurrency["COIN"].data["amount"]) +} + +func TestWalletExpiry_RunningAgainExpiresNothingMore(t *testing.T) { + e := newWalletMoveEnv(t) + a := e.member("Anita", "081200005678") + e.credit(t, earn(a, 150, e.at(-time.Hour))) + notifier := ¬ifierFake{} + + // Two instances, one after the other. + first, _ := e.expiry(notifier) + second, _ := e.expiry(notifier) + n1, err := first.ExpireDue(e.ctx) + require.NoError(t, err) + n2, err := second.ExpireDue(e.ctx) + require.NoError(t, err) + + assert.Equal(t, 1, n1) + assert.Equal(t, 0, n2) + assert.Len(t, notifier.pushes[a], 1) + var expires int + for _, tx := range e.repo.transactions { + if tx.Type == constants.WalletTxTypeExpire { + expires++ + } + } + assert.Equal(t, 1, expires) +} + +func TestWalletExpiry_OneFailingLotDoesNotStopTheOthers(t *testing.T) { + e := newWalletMoveEnv(t) + a := e.member("Anita", "081200005678") + e.credit(t, earn(a, 150, e.at(-time.Hour))) + p, repo := e.expiry(nil) + // A lot listed that ExpireLot cannot find. + repo.extra = []repository.DueLot{{ID: uuid.New(), CustomerID: a, Currency: "POINT", Remaining: 5, ExpiresAt: e.now.Add(-3 * time.Hour)}} + + count, err := p.ExpireDue(e.ctx) + require.NoError(t, err) + assert.Equal(t, 1, count) + assert.Equal(t, int64(0), e.balance(t, a)) +} + +func TestWalletExpiry_NothingDue(t *testing.T) { + e := newWalletMoveEnv(t) + a := e.member("Anita", "081200005678") + e.credit(t, earn(a, 150, e.at(time.Hour))) + notifier := ¬ifierFake{} + p, _ := e.expiry(notifier) + + count, err := p.ExpireDue(e.ctx) + require.NoError(t, err) + assert.Zero(t, count) + assert.Empty(t, notifier.pushes) +} + +func (f *walletExpiryRepoFake) OrganizationsWithUpcomingExpiry(_ context.Context, asOf time.Time) ([]uuid.UUID, error) { + seen := map[uuid.UUID]bool{} + var out []uuid.UUID + for _, lot := range f.wallet.lots { + if lot.RemainingAmount > 0 && lot.ExpiresAt != nil && lot.ExpiresAt.After(asOf) && !seen[lot.OrganizationID] { + seen[lot.OrganizationID] = true + out = append(out, lot.OrganizationID) + } + } + return out, nil +} + +func (f *walletExpiryRepoFake) UpcomingUnreminded(_ context.Context, organizationID uuid.UUID, currency string, asOf, until time.Time) ([]repository.UpcomingExpiry, error) { + sums := map[[2]string]int64{} + var order [][2]string + for _, lot := range f.wallet.lots { + if lot.OrganizationID != organizationID || lot.Currency != currency || lot.RemainingAmount == 0 || + lot.ExpiresAt == nil || !lot.ExpiresAt.After(asOf) || lot.ExpiresAt.After(until) { + continue + } + key := [2]string{lot.CustomerID.String(), lot.ExpiresAt.In(walletDisplayLocation).Format("2006-01-02")} + if f.reminded[key[0]+"/"+currency+"/"+key[1]] { + continue + } + if _, ok := sums[key]; !ok { + order = append(order, key) + } + sums[key] += lot.RemainingAmount + } + var out []repository.UpcomingExpiry + for _, key := range order { + out = append(out, repository.UpcomingExpiry{CustomerID: uuid.MustParse(key[0]), Date: key[1], Amount: sums[key]}) + } + return out, nil +} + +func (f *walletExpiryRepoFake) MarkReminded(_ context.Context, u repository.UpcomingExpiry, currency string) (bool, error) { + if f.reminded == nil { + f.reminded = map[string]bool{} + } + key := u.CustomerID.String() + "/" + currency + "/" + u.Date + if f.reminded[key] { + return false, nil + } + f.reminded[key] = true + return true, nil +} + +func TestWalletExpiry_RemindsOncePerDayBeforeExpiry(t *testing.T) { + e := newWalletMoveEnv(t) + e.now = wib(2026, 10, 25, 9, 0) + e.settings.PointExpiry.ReminderDays = 7 + e.settings.CoinExpiry.ReminderDays = 0 // no reminders for EnakCoin + a := e.member("Anita", "081200005678") + oct31 := wib(2026, 10, 31, 23, 59) + nov30 := wib(2026, 11, 30, 23, 59) + e.credit(t, earn(a, 100, &oct31)) + e.credit(t, earn(a, 50, &oct31)) + e.credit(t, earn(a, 70, &nov30)) // too far off yet + e.earnCoins(t, a, 5, &oct31) + notifier := ¬ifierFake{} + p, _ := e.expiry(notifier) + + sent, err := p.SendReminders(e.ctx) + require.NoError(t, err) + assert.Equal(t, 1, sent) + require.Len(t, notifier.pushes[a], 1) + push := notifier.pushes[a][0] + assert.Equal(t, "EnakPoint akan kedaluwarsa", push.title) + assert.Equal(t, "150 EnakPoint akan kedaluwarsa pada 31 Okt 2026. Pakai sebelum hangus.", push.body) + assert.Equal(t, map[string]string{"type": NotificationTypeWalletExpiring, "currency": "POINT", "amount": "150", "expiry_date": "2026-10-31"}, push.data) + + // The next run, on this instance or another, sends nothing again. + again, err := p.SendReminders(e.ctx) + require.NoError(t, err) + assert.Zero(t, again) + + // Once 30 Nov comes within seven days, it gets its own reminder. + e.now = wib(2026, 11, 23, 9, 0) + sent, err = p.SendReminders(e.ctx) + require.NoError(t, err) + assert.Equal(t, 1, sent) + assert.Equal(t, "70", notifier.pushes[a][1].data["amount"]) +} + +func TestFormatWalletDate(t *testing.T) { + assert.Equal(t, "31 Okt 2026", formatWalletDate("2026-10-31")) + assert.Equal(t, "1 Mei 2027", formatWalletDate("2027-05-01")) +} diff --git a/internal/processor/wallet_migration_processor.go b/internal/processor/wallet_migration_processor.go new file mode 100644 index 0000000..16aaef6 --- /dev/null +++ b/internal/processor/wallet_migration_processor.go @@ -0,0 +1,184 @@ +package processor + +import ( + "context" + "fmt" + + "github.com/google/uuid" + + "apskel-pos-be/internal/constants" + "apskel-pos-be/internal/entities" + "apskel-pos-be/internal/repository" +) + +// TxRunner runs fn inside a database transaction. repository.TxManager is one. +type TxRunner interface { + WithTransaction(ctx context.Context, fn func(ctx context.Context) error) error +} + +// WalletMigrationDiscrepancy is a customer whose legacy balance is now lower than +// what was already migrated: the old code spent from it after the migration ran. +// The wallet is left alone, because only an admin adjustment can take balance away. +type WalletMigrationDiscrepancy struct { + CustomerID uuid.UUID + Currency string + Legacy int64 + Migrated int64 +} + +type WalletMigrationReport struct { + DryRun bool + CustomersScanned int + // Ledger rows written (or, on a dry run, that would be written) and their sum. + PointCredits int + PointsCredited int64 + CoinCredits int + CoinsCredited int64 + Discrepancies []WalletMigrationDiscrepancy + // Taken after the run. On a dry run they show the state before it. + Totals *repository.WalletMigrationTotals +} + +// Balanced reports whether everything in the legacy tables is now in the wallet. +func (r *WalletMigrationReport) Balanced() bool { + return len(r.Discrepancies) == 0 && r.Totals != nil && + r.Totals.LegacyPoints == r.Totals.MigratedPoints && + r.Totals.LegacyCoins == r.Totals.MigratedCoins +} + +// WalletMigrationProcessor moves the balances in customer_points and customer_tokens +// into the wallet (docs/prd-point-coin.md §10, PC-105). Each customer gets a MIGRATION +// ledger row and a non-expiring lot per currency, through WalletProcessor like any +// other credit, so the wallet reconciles from the first row. +// +// It credits the difference between the legacy balance and what earlier runs already +// migrated, so running it again never doubles a balance, and a run after the old code +// kept writing to the legacy tables picks up only what was added since. +type WalletMigrationProcessor struct { + repo repository.WalletMigrationRepository + wallet *WalletProcessor + tx TxRunner +} + +func NewWalletMigrationProcessor(repo repository.WalletMigrationRepository, wallet *WalletProcessor, tx TxRunner) *WalletMigrationProcessor { + return &WalletMigrationProcessor{repo: repo, wallet: wallet, tx: tx} +} + +// Run migrates every customer with a legacy balance, one transaction per customer. +// With dryRun it only reports what it would credit. +func (p *WalletMigrationProcessor) Run(ctx context.Context, dryRun bool, batchSize int) (*WalletMigrationReport, error) { + if batchSize <= 0 { + batchSize = 500 + } + report := &WalletMigrationReport{DryRun: dryRun} + + after := uuid.Nil + for { + ids, err := p.repo.ListLegacyCustomers(ctx, after, batchSize) + if err != nil { + return nil, err + } + if len(ids) == 0 { + break + } + for _, id := range ids { + if dryRun { + err = p.migrateCustomer(ctx, id, true, report) + } else { + err = p.tx.WithTransaction(ctx, func(ctx context.Context) error { + return p.migrateCustomer(ctx, id, false, report) + }) + } + if err != nil { + return nil, fmt.Errorf("customer %s: %w", id, err) + } + report.CustomersScanned++ + } + after = ids[len(ids)-1] + } + + totals, err := p.repo.Totals(ctx) + if err != nil { + return nil, err + } + report.Totals = totals + return report, nil +} + +func (p *WalletMigrationProcessor) migrateCustomer(ctx context.Context, customerID uuid.UUID, dryRun bool, report *WalletMigrationReport) error { + // Lock before reading what was migrated, so two runs at once cannot both see the + // same gap and fill it twice. + if !dryRun { + if err := p.wallet.LockWallet(ctx, customerID); err != nil { + return err + } + } + legacy, err := p.repo.GetLegacyBalance(ctx, customerID) + if err != nil { + return err + } + + // Points come from the single customer_points row. Tokens come from several rows, + // one per type, so the ledger row points at the customer and lists the rows. + pointsRef := customerID + if legacy.PointsRowID != nil { + pointsRef = *legacy.PointsRowID + } + tokens := make([]map[string]any, 0, len(legacy.Tokens)) + for _, t := range legacy.Tokens { + tokens = append(tokens, map[string]any{"id": t.ID, "token_type": string(t.TokenType), "balance": t.Balance}) + } + + for _, c := range []struct { + currency, refType string + refID uuid.UUID + legacy int64 + metadata entities.Metadata + credits *int + credited *int64 + }{ + {constants.WalletCurrencyPoint, constants.WalletRefTypeLegacyPoints, pointsRef, legacy.Points, + entities.Metadata{}, &report.PointCredits, &report.PointsCredited}, + {constants.WalletCurrencyCoin, constants.WalletRefTypeLegacyTokens, customerID, legacy.Coins(), + entities.Metadata{"legacy_tokens": tokens}, &report.CoinCredits, &report.CoinsCredited}, + } { + migrated, err := p.repo.SumMigrated(ctx, customerID, c.currency) + if err != nil { + return err + } + delta := c.legacy - migrated + if delta < 0 { + report.Discrepancies = append(report.Discrepancies, WalletMigrationDiscrepancy{ + CustomerID: customerID, Currency: c.currency, Legacy: c.legacy, Migrated: migrated, + }) + continue + } + if delta == 0 { + continue + } + + if !dryRun { + c.metadata["legacy_balance"] = c.legacy + c.metadata["previously_migrated"] = migrated + _, err = p.wallet.Credit(ctx, WalletCreditInput{WalletEntry: WalletEntry{ + CustomerID: customerID, + Currency: c.currency, + Type: constants.WalletTxTypeMigration, + Amount: delta, + ReferenceType: c.refType, + ReferenceID: c.refID, + Description: "Saldo awal dari sistem lama", + Metadata: c.metadata, + // The legacy total in the key lets a later run top up a balance that + // grew, while a retry of the same run is still recognised. + IdempotencyKey: fmt.Sprintf("migration:%s:%s:%d", c.currency, customerID, c.legacy), + }}) + if err != nil { + return err + } + } + *c.credits++ + *c.credited += delta + } + return nil +} diff --git a/internal/processor/wallet_migration_processor_db_test.go b/internal/processor/wallet_migration_processor_db_test.go new file mode 100644 index 0000000..c0c3f3d --- /dev/null +++ b/internal/processor/wallet_migration_processor_db_test.go @@ -0,0 +1,167 @@ +package processor + +import ( + "context" + "os" + "testing" + + "github.com/google/uuid" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "gorm.io/driver/postgres" + "gorm.io/gorm" + "gorm.io/gorm/logger" + + "apskel-pos-be/internal/constants" + "apskel-pos-be/internal/repository" +) + +// Needs TEST_DATABASE_URL pointing at a migrated database; see +// internal/repository/wallet_repository_test.go. Other packages' tests may use the +// same database at the same time, so everything here is scoped to its own customers. +func TestWalletMigrationProcessor_AgainstPostgres(t *testing.T) { + dsn := os.Getenv("TEST_DATABASE_URL") + if dsn == "" { + t.Skip("TEST_DATABASE_URL not set") + } + db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{Logger: logger.Default.LogMode(logger.Silent)}) + require.NoError(t, err) + ctx := context.Background() + + org := uuid.New() + full, tokensOnly, pointsOnly, none := uuid.New(), uuid.New(), uuid.New(), uuid.New() + customers := []uuid.UUID{full, tokensOnly, pointsOnly, none} + exec := func(q string, args ...any) { + t.Helper() + require.NoError(t, db.Exec(q, args...).Error) + } + exec(`INSERT INTO organizations (id, name, plan_type) VALUES (?, 'migration test', 'basic')`, org) + for _, c := range customers { + exec(`INSERT INTO customers (id, organization_id, name) VALUES (?, ?, 'migration test')`, c, org) + } + t.Cleanup(func() { + db.Exec(`DELETE FROM wallet_lot_allocations WHERE lot_id IN (SELECT id FROM wallet_lots WHERE customer_id IN ?)`, customers) + db.Exec(`DELETE FROM wallet_lots WHERE customer_id IN ?`, customers) + db.Exec(`DELETE FROM wallet_transactions WHERE customer_id IN ?`, customers) + db.Exec(`DELETE FROM customer_wallets WHERE customer_id IN ?`, customers) + db.Exec(`DELETE FROM customers WHERE id IN ?`, customers) + db.Exec(`DELETE FROM organizations WHERE id = ?`, org) + }) + + // The example from §10: SPIN 5 + RAFFLE 2 + MINIGAME 1 = 8 EnakCoin. + exec(`INSERT INTO customer_points (customer_id, balance) VALUES (?, 100), (?, 0), (?, 40)`, full, tokensOnly, pointsOnly) + exec(`INSERT INTO customer_tokens (customer_id, token_type, balance) VALUES + (?, 'SPIN', 5), (?, 'RAFFLE', 2), (?, 'MINIGAME', 1), (?, 'SPIN', 3)`, full, full, full, tokensOnly) + + migrator := NewWalletMigrationProcessor( + repository.NewWalletMigrationRepository(db), + NewWalletProcessor(repository.NewWalletRepository(db)), + repository.NewTxManager(db), + ) + + type balance struct{ Point, Coin int64 } + balances := func() map[uuid.UUID]balance { + t.Helper() + var rows []struct { + CustomerID uuid.UUID + PointBalance, CoinBalance int64 + } + require.NoError(t, db.Raw(`SELECT customer_id, point_balance, coin_balance FROM customer_wallets WHERE customer_id IN ?`, customers).Scan(&rows).Error) + out := map[uuid.UUID]balance{} + for _, r := range rows { + out[r.CustomerID] = balance{r.PointBalance, r.CoinBalance} + } + return out + } + countRows := func() int64 { + t.Helper() + var n int64 + require.NoError(t, db.Raw(`SELECT COUNT(*) FROM wallet_transactions WHERE customer_id IN ?`, customers).Scan(&n).Error) + return n + } + + // A dry run reports and writes nothing, not even the wallets. + report, err := migrator.Run(ctx, true, 2) + require.NoError(t, err) + assert.GreaterOrEqual(t, report.PointsCredited, int64(140)) + assert.GreaterOrEqual(t, report.CoinsCredited, int64(11)) + assert.Empty(t, balances()) + assert.Zero(t, countRows()) + + // The real run. A batch of 2 makes it page through the customers. + _, err = migrator.Run(ctx, false, 2) + require.NoError(t, err) + assert.Equal(t, map[uuid.UUID]balance{ + full: {Point: 100, Coin: 8}, + tokensOnly: {Point: 0, Coin: 3}, + pointsOnly: {Point: 40, Coin: 0}, + }, balances(), "a customer without legacy rows gets no wallet") + assert.Equal(t, int64(4), countRows(), "one row per customer per currency with a balance") + + var coinRow struct { + ReferenceType string + ReferenceID uuid.UUID + Metadata string + } + require.NoError(t, db.Raw(`SELECT reference_type, reference_id, metadata::text AS metadata FROM wallet_transactions + WHERE customer_id = ? AND currency = 'COIN'`, full).Scan(&coinRow).Error) + assert.Equal(t, constants.WalletRefTypeLegacyTokens, coinRow.ReferenceType) + assert.Equal(t, full, coinRow.ReferenceID) + for _, part := range []string{`"token_type": "SPIN"`, `"token_type": "RAFFLE"`, `"token_type": "MINIGAME"`, `"legacy_balance": 8`} { + assert.Contains(t, coinRow.Metadata, part) + } + + var pointRef, pointsRowID string + require.NoError(t, db.Raw(`SELECT reference_id::text FROM wallet_transactions WHERE customer_id = ? AND currency = 'POINT'`, full).Scan(&pointRef).Error) + require.NoError(t, db.Raw(`SELECT id::text FROM customer_points WHERE customer_id = ?`, full).Scan(&pointsRowID).Error) + assert.NotEmpty(t, pointRef) + assert.Equal(t, pointsRowID, pointRef, "points row points at the customer_points row") + + var expiring int64 + require.NoError(t, db.Raw(`SELECT COUNT(*) FROM wallet_lots WHERE customer_id IN ? AND expires_at IS NOT NULL`, customers).Scan(&expiring).Error) + assert.Zero(t, expiring, "migrated lots never expire") + + // Running again changes nothing. + report, err = migrator.Run(ctx, false, 2) + require.NoError(t, err) + assert.Equal(t, int64(4), countRows()) + assert.Empty(t, discrepanciesFor(report, customers)) + + // The old code kept writing: one balance grew, one shrank. Only the growth is + // migrated; the shrink is reported and left alone. + exec(`UPDATE customer_tokens SET balance = 9 WHERE customer_id = ? AND token_type = 'SPIN'`, full) + exec(`UPDATE customer_points SET balance = 30 WHERE customer_id = ?`, pointsOnly) + report, err = migrator.Run(ctx, false, 2) + require.NoError(t, err) + assert.Equal(t, balance{Point: 100, Coin: 12}, balances()[full]) + assert.Equal(t, balance{Point: 40, Coin: 0}, balances()[pointsOnly]) + assert.Equal(t, []WalletMigrationDiscrepancy{{CustomerID: pointsOnly, Currency: constants.WalletCurrencyPoint, Legacy: 30, Migrated: 40}}, + discrepanciesFor(report, customers)) + assert.Equal(t, int64(5), countRows()) + + // §7.5 for these customers. + var broken int64 + require.NoError(t, db.Raw(` + SELECT COUNT(*) FROM customer_wallets w + WHERE w.customer_id IN ? AND ( + w.point_balance <> (SELECT COALESCE(SUM(amount), 0) FROM wallet_transactions t WHERE t.customer_id = w.customer_id AND t.currency = 'POINT') + OR w.coin_balance <> (SELECT COALESCE(SUM(amount), 0) FROM wallet_transactions t WHERE t.customer_id = w.customer_id AND t.currency = 'COIN') + OR w.point_balance <> (SELECT COALESCE(SUM(remaining_amount), 0) FROM wallet_lots l WHERE l.customer_id = w.customer_id AND l.currency = 'POINT') + OR w.coin_balance <> (SELECT COALESCE(SUM(remaining_amount), 0) FROM wallet_lots l WHERE l.customer_id = w.customer_id AND l.currency = 'COIN'))`, + customers).Scan(&broken).Error) + assert.Zero(t, broken) +} + +func discrepanciesFor(report *WalletMigrationReport, customers []uuid.UUID) []WalletMigrationDiscrepancy { + mine := map[uuid.UUID]bool{} + for _, c := range customers { + mine[c] = true + } + var out []WalletMigrationDiscrepancy + for _, d := range report.Discrepancies { + if mine[d.CustomerID] { + out = append(out, d) + } + } + return out +} diff --git a/internal/processor/wallet_move_db_test.go b/internal/processor/wallet_move_db_test.go new file mode 100644 index 0000000..0808d2f --- /dev/null +++ b/internal/processor/wallet_move_db_test.go @@ -0,0 +1,237 @@ +package processor + +import ( + "context" + "fmt" + "os" + "sync" + "testing" + "time" + + "github.com/google/uuid" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "gorm.io/driver/postgres" + "gorm.io/gorm" + "gorm.io/gorm/logger" + + "apskel-pos-be/internal/constants" + "apskel-pos-be/internal/models" + "apskel-pos-be/internal/repository" +) + +// fixedOrganizationSettings serves the same organization settings to every caller. +type fixedOrganizationSettings struct { + s models.OrganizationLoyaltySettings +} + +func (f fixedOrganizationSettings) Organization(context.Context, uuid.UUID) (*models.OrganizationLoyaltySettings, error) { + s := f.s + return &s, nil +} + +// walletMoveDB opens TEST_DATABASE_URL and creates an organization with two customers, +// removed again when the test ends. See internal/repository/wallet_repository_test.go. +func walletMoveDB(t *testing.T) (db *gorm.DB, org, a, b uuid.UUID) { + t.Helper() + dsn := os.Getenv("TEST_DATABASE_URL") + if dsn == "" { + t.Skip("TEST_DATABASE_URL not set") + } + db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{Logger: logger.Default.LogMode(logger.Silent)}) + require.NoError(t, err) + + org, a, b = uuid.New(), uuid.New(), uuid.New() + phoneA, phoneB := "08"+a.String()[:10], "08"+b.String()[:10] + require.NoError(t, db.Exec(`INSERT INTO organizations (id, name, plan_type) VALUES (?, 'wallet move test', 'basic')`, org).Error) + require.NoError(t, db.Exec(`INSERT INTO customers (id, organization_id, name, phone_number) VALUES (?, ?, 'Anita', ?), (?, ?, 'Budi Santoso', ?)`, + a, org, phoneA, b, org, phoneB).Error) + customers := []uuid.UUID{a, b} + t.Cleanup(func() { + db.Exec(`DELETE FROM wallet_lot_allocations WHERE lot_id IN (SELECT id FROM wallet_lots WHERE customer_id IN ?)`, customers) + db.Exec(`DELETE FROM wallet_lots WHERE customer_id IN ? AND origin_lot_id IS NOT NULL`, customers) + db.Exec(`DELETE FROM wallet_lots WHERE customer_id IN ?`, customers) + db.Exec(`DELETE FROM wallet_transactions WHERE customer_id IN ?`, customers) + db.Exec(`DELETE FROM customer_wallets WHERE customer_id IN ?`, customers) + db.Exec(`DELETE FROM customers WHERE id IN ?`, customers) + db.Exec(`DELETE FROM organizations WHERE id = ?`, org) + }) + return db, org, a, b +} + +func TestWalletExchange_AgainstPostgres(t *testing.T) { + db, _, a, _ := walletMoveDB(t) + wallet := NewWalletProcessor(repository.NewWalletRepository(db)) + txm := repository.NewTxManager(db) + settings := fixedOrganizationSettings{models.OrganizationLoyaltySettings{ + Exchange: models.LoyaltyExchangeSettings{CoinAmount: 10, PointAmount: 3}, + }} + p := NewWalletExchangeProcessor(repository.NewWalletMoveRepository(db), settings, repository.NewWalletQueryRepository(db), + &movePinFake{good: "482913"}, wallet, txm) + + expiry := time.Now().Add(24 * time.Hour).Truncate(time.Second) + require.NoError(t, txm.WithTransaction(context.Background(), func(ctx context.Context) error { + in := earn(a, 30, &expiry) + in.Currency = constants.WalletCurrencyCoin + _, err := wallet.Credit(ctx, in) + return err + })) + + res, err := p.Exchange(context.Background(), a, 20, "482913", "db-key", models.CustomerPinRequestInfo{}) + require.NoError(t, err) + assert.Equal(t, int64(6), res.Points) + assert.Equal(t, int64(10), res.CoinBalance) + assert.Equal(t, int64(6), res.PointBalance) + require.Len(t, res.Lots, 1) + require.NotNil(t, res.Lots[0].ExpiresAt) + assert.True(t, res.Lots[0].ExpiresAt.Equal(expiry)) + + // The retry reads the frozen rate back out of JSONB and replays. + again, err := p.Exchange(context.Background(), a, 20, "482913", "db-key", models.CustomerPinRequestInfo{}) + require.NoError(t, err) + assert.True(t, again.Replayed) + assert.Equal(t, int64(6), again.Points) + + var rows int64 + require.NoError(t, db.Raw(`SELECT COUNT(*) FROM wallet_transactions WHERE group_id = ?`, res.GroupID).Scan(&rows).Error) + assert.Equal(t, int64(2), rows) +} + +// Transfers in both directions at once must not deadlock: both lock the two wallets +// in customer_id order. Every one of them lands, and the totals still reconcile. +func TestWalletTransfer_BothWaysAtOnceAgainstPostgres(t *testing.T) { + db, _, a, b := walletMoveDB(t) + wallet := NewWalletProcessor(repository.NewWalletRepository(db)) + txm := repository.NewTxManager(db) + moves := repository.NewWalletMoveRepository(db) + settings := fixedOrganizationSettings{models.OrganizationLoyaltySettings{ + Transfer: models.LoyaltyTransferSettings{Enabled: true, MinAmount: 1}, + }} + p := NewWalletTransferProcessor(moves, settings, repository.NewWalletQueryRepository(db), &movePinFake{good: "482913"}, wallet, txm, nil) + + expiry := time.Now().Add(24 * time.Hour).Truncate(time.Second) + require.NoError(t, txm.WithTransaction(context.Background(), func(ctx context.Context) error { + if _, err := wallet.Credit(ctx, earn(a, 100, &expiry)); err != nil { + return err + } + _, err := wallet.Credit(ctx, earn(b, 100, nil)) + return err + })) + phone := func(id uuid.UUID) string { return "08" + id.String()[:10] } + + const rounds = 10 + errs := make(chan error, 2*rounds) + var wg sync.WaitGroup + for i := 0; i < rounds; i++ { + for _, pair := range [][2]uuid.UUID{{a, b}, {b, a}} { + wg.Add(1) + go func(from, to uuid.UUID, i int) { + defer wg.Done() + _, err := p.Transfer(context.Background(), from, sendPoints(1, phone(to)), "482913", fmt.Sprintf("race-%d", i), models.CustomerPinRequestInfo{}) + errs <- err + }(pair[0], pair[1], i) + } + } + wg.Wait() + close(errs) + for err := range errs { + assert.NoError(t, err) + } + + var balances []int64 + require.NoError(t, db.Raw(`SELECT point_balance FROM customer_wallets WHERE customer_id IN ? ORDER BY point_balance`, []uuid.UUID{a, b}).Scan(&balances).Error) + assert.Equal(t, []int64{100, 100}, balances) + + // B's lots that came from A keep A's expiry to the second. + var mismatched int64 + require.NoError(t, db.Raw(` + SELECT COUNT(*) FROM wallet_lots l JOIN wallet_lots o ON o.id = l.origin_lot_id + WHERE l.customer_id = ? AND o.customer_id = ? AND l.expires_at IS DISTINCT FROM o.expires_at`, b, a).Scan(&mismatched).Error) + assert.Zero(t, mismatched) + + require.NoError(t, txm.WithTransaction(context.Background(), func(ctx context.Context) error { + sent, err := moves.TransferredOutSince(ctx, a, constants.WalletCurrencyPoint, startOfWalletDay(time.Now())) + assert.Equal(t, int64(rounds), sent) + return err + })) +} + +// The example of §8 against Postgres: B's payment of 30 traces back to A's #ORD-1. +func TestWalletTrace_AgainstPostgres(t *testing.T) { + db, org, a, b := walletMoveDB(t) + wallet := NewWalletProcessor(repository.NewWalletRepository(db)) + txm := repository.NewTxManager(db) + settings := fixedOrganizationSettings{models.OrganizationLoyaltySettings{ + Transfer: models.LoyaltyTransferSettings{Enabled: true, MinAmount: 1}, + }} + transfers := NewWalletTransferProcessor(repository.NewWalletMoveRepository(db), settings, repository.NewWalletQueryRepository(db), &movePinFake{good: "482913"}, wallet, txm, nil) + + dec, jan := time.Now().Add(30*24*time.Hour), time.Now().Add(60*24*time.Hour) + ord1 := earn(a, 100, &dec) + ord1.Description = "Belanja #ORD-1" + require.NoError(t, txm.WithTransaction(context.Background(), func(ctx context.Context) error { + if _, err := wallet.Credit(ctx, ord1); err != nil { + return err + } + _, err := wallet.Credit(ctx, earn(a, 50, &jan)) + return err + })) + _, err := transfers.Transfer(context.Background(), a, sendPoints(120, "08"+b.String()[:10]), "482913", "trace", models.CustomerPinRequestInfo{}) + require.NoError(t, err) + var payment *WalletResult + require.NoError(t, txm.WithTransaction(context.Background(), func(ctx context.Context) error { + payment, err = wallet.Debit(ctx, pay(b, 30)) + return err + })) + + trace, err := NewWalletTraceProcessor(repository.NewWalletTraceRepository(db)).Trace(context.Background(), org, payment.Transaction.ID) + require.NoError(t, err) + require.Len(t, trace.Lots, 1) + chain := trace.Lots[0].Chain + require.Len(t, chain, 2) + assert.Equal(t, constants.WalletTxTypeTransferIn, chain[0].Source.Type) + assert.Equal(t, "Anita", chain[1].Source.Customer.Name) + assert.Equal(t, ord1.ReferenceID, chain[1].Source.ReferenceID) + + _, err = NewWalletTraceProcessor(repository.NewWalletTraceRepository(db)).Trace(context.Background(), uuid.New(), payment.Transaction.ID) + assert.ErrorIs(t, err, repository.ErrWalletTransactionNotFound) +} + +// Two instances of the expiry job at once expire each lot exactly once (PC-503). +func TestWalletExpiry_TwoInstancesAgainstPostgres(t *testing.T) { + db, _, a, b := walletMoveDB(t) + wallet := NewWalletProcessor(repository.NewWalletRepository(db)) + txm := repository.NewTxManager(db) + past := time.Now().Add(-time.Hour) + require.NoError(t, txm.WithTransaction(context.Background(), func(ctx context.Context) error { + for i := 0; i < 5; i++ { + for _, c := range []uuid.UUID{a, b} { + if _, err := wallet.Credit(ctx, earn(c, 10, &past)); err != nil { + return err + } + } + } + return nil + })) + + var wg sync.WaitGroup + counts := make([]int, 2) + for i := range counts { + wg.Add(1) + go func(i int) { + defer wg.Done() + p := NewWalletExpiryProcessor(repository.NewWalletExpiryRepository(db), fixedOrganizationSettings{}, wallet, txm, nil) + n, err := p.ExpireDue(context.Background()) + assert.NoError(t, err) + counts[i] = n + }(i) + } + wg.Wait() + assert.Equal(t, 10, counts[0]+counts[1], "every lot once, between them") + + var expires, left int64 + require.NoError(t, db.Raw(`SELECT COUNT(*) FROM wallet_transactions WHERE customer_id IN ? AND type = 'EXPIRE'`, []uuid.UUID{a, b}).Scan(&expires).Error) + require.NoError(t, db.Raw(`SELECT COALESCE(SUM(point_balance), 0) FROM customer_wallets WHERE customer_id IN ?`, []uuid.UUID{a, b}).Scan(&left).Error) + assert.Equal(t, int64(10), expires) + assert.Zero(t, left) +} diff --git a/internal/processor/wallet_processor.go b/internal/processor/wallet_processor.go new file mode 100644 index 0000000..17bb8de --- /dev/null +++ b/internal/processor/wallet_processor.go @@ -0,0 +1,583 @@ +package processor + +import ( + "context" + "errors" + "fmt" + "strings" + "time" + + "github.com/google/uuid" + + "apskel-pos-be/internal/constants" + "apskel-pos-be/internal/entities" + "apskel-pos-be/internal/repository" +) + +var ( + // ErrWalletInvalidEntry wraps every rejection of an entry that breaks the rules in + // docs/prd-point-coin.md §8.1. The database enforces most of them too; checking + // here first gives callers a readable error instead of a constraint name. + ErrWalletInvalidEntry = errors.New("wallet: invalid entry") + // ErrWalletIdempotencyConflict means an idempotency key was reused for a different + // operation. Retrying the same operation with the same key is not a conflict. + ErrWalletIdempotencyConflict = errors.New("wallet: idempotency key already used for a different operation") +) + +// WalletEntry is what every ledger row needs, whichever way it moves the balance. +// Which of the optional fields a type requires is listed in §8.1. +type WalletEntry struct { + // Optional. Set it when another row must reference this one before it exists, as + // the two rows of an exchange or a transfer do. + TransactionID uuid.UUID + + CustomerID uuid.UUID + Currency string + Type string + // Always positive: Credit adds it, Debit takes it away. + Amount int64 + + ReferenceType string + ReferenceID uuid.UUID + + GroupID *uuid.UUID + CounterpartyCustomerID *uuid.UUID + ReversesTransactionID *uuid.UUID + OutletID *uuid.UUID + CreatedByUser *uuid.UUID + Reason *string + + Description string + Metadata entities.Metadata + // Optional. A retry with the same key returns the first result without moving + // anything again. + IdempotencyKey string +} + +// WalletLotInput is one lot a credit creates. +type WalletLotInput struct { + Amount int64 + // Nil means the lot never expires. + ExpiresAt *time.Time + // The lot this one was carried over from, for transfers, exchanges and refunds. + OriginLotID *uuid.UUID +} + +type WalletCreditInput struct { + WalletEntry + // How the credit is split into lots. Their amounts must add up to Amount. Leave + // empty for a single lot that never expires. + Lots []WalletLotInput +} + +type WalletDebitInput struct { + WalletEntry + // Lots to draw from first, in this order, before falling back to the K9 order. + // A reversal names the lots its EARN created (F10), and the expiry job names the + // lot that expired. These lots are used even if they have already expired. + PreferredLotIDs []uuid.UUID +} + +// WalletAllocation is how much a debit took from one lot. It carries the lot's +// expiry, so a transfer or exchange can give the receiving lot the same expiry (K9). +type WalletAllocation struct { + LotID uuid.UUID + Amount int64 + ExpiresAt *time.Time +} + +type WalletResult struct { + // Nil only when DebitUpTo found nothing to take. + Transaction *entities.WalletTransaction + // The lots a credit created. + Lots []entities.WalletLot + // The lots a debit drew from, in the order they were used. + Allocations []WalletAllocation + // What DebitUpTo could not take because the balance ran out. + Shortfall int64 + // True when the idempotency key had already been used and nothing moved. + Replayed bool +} + +// CarryOver turns a debit's allocations into lots for the receiving side of a +// transfer or exchange. Each lot keeps the expiry of the lot it came from and points +// back at it, so a balance cannot be kept alive by moving it around (K9). +func (r *WalletResult) CarryOver() []WalletLotInput { + lots := make([]WalletLotInput, 0, len(r.Allocations)) + for _, a := range r.Allocations { + lotID := a.LotID + lots = append(lots, WalletLotInput{Amount: a.Amount, ExpiresAt: a.ExpiresAt, OriginLotID: &lotID}) + } + return lots +} + +// WalletProcessor is the only code allowed to change a wallet balance. Every change +// writes the balance, the ledger row and the lots or allocations together, which is +// what keeps SUM(ledger) = balance = SUM(lot remaining) (§7.5). +// +// Every method must run inside a transaction from TxManager, and the repository +// refuses otherwise. Each method locks the customer's wallet itself, so a single-wallet +// caller needs nothing more. A caller touching two wallets, such as a transfer, must +// call LockWallets first so the locks are always taken in the same order. +type WalletProcessor struct { + repo repository.WalletRepository + now func() time.Time +} + +func NewWalletProcessor(repo repository.WalletRepository) *WalletProcessor { + return &WalletProcessor{repo: repo, now: time.Now} +} + +// LockWallet locks one customer's wallet, creating it if needed. Credit and Debit do +// this themselves; call it when something must be read under the lock first. +func (p *WalletProcessor) LockWallet(ctx context.Context, customerID uuid.UUID) error { + _, err := p.repo.LockWallet(ctx, customerID) + return err +} + +// LockWallets locks two customers' wallets in a fixed order. Call it before touching +// both wallets in one transaction. +func (p *WalletProcessor) LockWallets(ctx context.Context, a, b uuid.UUID) error { + _, _, err := p.repo.LockWallets(ctx, a, b) + return err +} + +// FindTransaction returns the row written under an idempotency key, or nil when the +// key is new. Read it under the wallet lock: a flow that writes several rows uses it +// to recognise a retry before checking limits the first attempt already counts in. +func (p *WalletProcessor) FindTransaction(ctx context.Context, idempotencyKey string) (*entities.WalletTransaction, error) { + return p.repo.GetTransactionByIdempotencyKey(ctx, idempotencyKey) +} + +// ExpireLot takes what is left in a lot whose expiry has passed at asOf, as an EXPIRE +// row pointing at the lot (F12). It locks the wallet before reading the lot again, so +// it never races a payment for the same balance, and the key expire:{lot_id} makes a +// second run, on this instance or another, take nothing more. describe gives the +// row's description for the amount taken. It returns nil when +// there is nothing to take: the lot is empty, not due, or already expired. +func (p *WalletProcessor) ExpireLot(ctx context.Context, lotID uuid.UUID, describe func(amount int64) string, asOf time.Time) (*WalletResult, error) { + lot, err := p.getLot(ctx, lotID) + if err != nil { + return nil, err + } + if _, err := p.repo.LockWallet(ctx, lot.CustomerID); err != nil { + return nil, err + } + // Read again under the lock: a payment may have used it up meanwhile. + if lot, err = p.getLot(ctx, lotID); err != nil { + return nil, err + } + if lot.RemainingAmount == 0 || lot.ExpiresAt == nil || lot.ExpiresAt.After(asOf) { + return nil, nil + } + return p.Debit(ctx, WalletDebitInput{ + WalletEntry: WalletEntry{ + CustomerID: lot.CustomerID, + Currency: lot.Currency, + Type: constants.WalletTxTypeExpire, + Amount: lot.RemainingAmount, + ReferenceType: constants.WalletRefTypeLot, + ReferenceID: lot.ID, + Description: describe(lot.RemainingAmount), + Metadata: entities.Metadata{"expires_at": lot.ExpiresAt.UTC().Format(time.RFC3339)}, + IdempotencyKey: "expire:" + lot.ID.String(), + }, + // Exactly what the lot holds, from the lot itself, even though it has expired. + PreferredLotIDs: []uuid.UUID{lot.ID}, + }) +} + +func (p *WalletProcessor) getLot(ctx context.Context, lotID uuid.UUID) (*entities.WalletLot, error) { + lots, err := p.repo.GetLotsByIDs(ctx, []uuid.UUID{lotID}) + if err != nil { + return nil, err + } + if len(lots) == 0 { + return nil, fmt.Errorf("%w: lot %s does not exist", ErrWalletInvalidEntry, lotID) + } + return &lots[0], nil +} + +// Credit adds Amount to the wallet and creates its lots. +func (p *WalletProcessor) Credit(ctx context.Context, in WalletCreditInput) (*WalletResult, error) { + if err := validateWalletEntry(&in.WalletEntry, true); err != nil { + return nil, err + } + lots := in.Lots + if len(lots) == 0 { + lots = []WalletLotInput{{Amount: in.Amount}} + } + var total int64 + for _, lot := range lots { + if lot.Amount <= 0 { + return nil, fmt.Errorf("%w: lot amount must be positive, got %d", ErrWalletInvalidEntry, lot.Amount) + } + total += lot.Amount + } + if total != in.Amount { + return nil, fmt.Errorf("%w: lots add up to %d, not %d", ErrWalletInvalidEntry, total, in.Amount) + } + + wallet, err := p.repo.LockWallet(ctx, in.CustomerID) + if err != nil { + return nil, err + } + if replay, err := p.replay(ctx, &in.WalletEntry, true, true); replay != nil || err != nil { + return replay, err + } + + balance, err := p.repo.AddBalance(ctx, in.CustomerID, in.Currency, in.Amount) + if err != nil { + return nil, err + } + walletTx := newWalletTransaction(wallet, &in.WalletEntry, in.Amount, balance, nil) + if err := p.repo.CreateTransaction(ctx, walletTx); err != nil { + return nil, fmt.Errorf("failed to create wallet transaction: %w", err) + } + + result := &WalletResult{Transaction: walletTx} + for _, lotIn := range lots { + lot := entities.WalletLot{ + OrganizationID: wallet.OrganizationID, + CustomerID: in.CustomerID, + Currency: in.Currency, + SourceTransactionID: walletTx.ID, + OriginLotID: lotIn.OriginLotID, + OriginalAmount: lotIn.Amount, + RemainingAmount: lotIn.Amount, + ExpiresAt: lotIn.ExpiresAt, + } + if err := p.repo.CreateLot(ctx, &lot); err != nil { + return nil, fmt.Errorf("failed to create wallet lot: %w", err) + } + result.Lots = append(result.Lots, lot) + } + return result, nil +} + +// Debit takes exactly Amount from the wallet, or nothing at all with +// repository.ErrWalletInsufficientBalance if the usable balance is short. +func (p *WalletProcessor) Debit(ctx context.Context, in WalletDebitInput) (*WalletResult, error) { + return p.debit(ctx, in, false) +} + +// DebitUpTo takes as much of Amount as the wallet has and reports the rest as +// Shortfall. It is for reversing earnings the customer has already spent (F10, Q3). +// When there is nothing to take, no ledger row is written and Transaction is nil; +// such a call leaves no trace, so a retry with the same key takes whatever the +// balance holds by then. +func (p *WalletProcessor) DebitUpTo(ctx context.Context, in WalletDebitInput) (*WalletResult, error) { + return p.debit(ctx, in, true) +} + +func (p *WalletProcessor) debit(ctx context.Context, in WalletDebitInput, upTo bool) (*WalletResult, error) { + if err := validateWalletEntry(&in.WalletEntry, false); err != nil { + return nil, err + } + wallet, err := p.repo.LockWallet(ctx, in.CustomerID) + if err != nil { + return nil, err + } + // DebitUpTo may have taken less than asked, so the amount cannot be compared. + if replay, err := p.replay(ctx, &in.WalletEntry, false, !upTo); replay != nil || err != nil { + return replay, err + } + + lots, err := p.spendableLots(ctx, &in) + if err != nil { + return nil, err + } + + var available int64 + for _, lot := range lots { + available += lot.RemainingAmount + } + take := in.Amount + if available < take { + if !upTo { + return nil, repository.ErrWalletInsufficientBalance + } + take = available + } + result := &WalletResult{Shortfall: in.Amount - take} + if take == 0 { + return result, nil + } + + var metadata entities.Metadata + if upTo { + metadata = entities.Metadata{"requested_amount": in.Amount, "shortfall": result.Shortfall} + } + + balance, err := p.repo.AddBalance(ctx, in.CustomerID, in.Currency, -take) + if err != nil { + return nil, err + } + walletTx := newWalletTransaction(wallet, &in.WalletEntry, -take, balance, metadata) + if err := p.repo.CreateTransaction(ctx, walletTx); err != nil { + return nil, fmt.Errorf("failed to create wallet transaction: %w", err) + } + result.Transaction = walletTx + + var allocations []entities.WalletLotAllocation + remaining := take + for _, lot := range lots { + if remaining == 0 { + break + } + amount := min(lot.RemainingAmount, remaining) + remaining -= amount + if err := p.repo.ConsumeLot(ctx, lot.ID, amount); err != nil { + return nil, err + } + allocations = append(allocations, entities.WalletLotAllocation{TransactionID: walletTx.ID, LotID: lot.ID, Amount: amount}) + result.Allocations = append(result.Allocations, WalletAllocation{LotID: lot.ID, Amount: amount, ExpiresAt: lot.ExpiresAt}) + } + if err := p.repo.CreateAllocations(ctx, allocations); err != nil { + return nil, fmt.Errorf("failed to create wallet lot allocations: %w", err) + } + return result, nil +} + +// spendableLots returns the lots a debit may draw from, in the order it draws: the +// preferred lots first, then the unexpired lots in K9 order. +func (p *WalletProcessor) spendableLots(ctx context.Context, in *WalletDebitInput) ([]entities.WalletLot, error) { + var lots []entities.WalletLot + preferred := make(map[uuid.UUID]bool, len(in.PreferredLotIDs)) + + if len(in.PreferredLotIDs) > 0 { + found, err := p.repo.GetLotsByIDs(ctx, in.PreferredLotIDs) + if err != nil { + return nil, err + } + byID := make(map[uuid.UUID]entities.WalletLot, len(found)) + for _, lot := range found { + byID[lot.ID] = lot + } + for _, id := range in.PreferredLotIDs { + lot, ok := byID[id] + if !ok || lot.CustomerID != in.CustomerID || lot.Currency != in.Currency { + return nil, fmt.Errorf("%w: lot %s is not a %s lot of this customer", ErrWalletInvalidEntry, id, in.Currency) + } + if preferred[id] { + continue + } + preferred[id] = true + if lot.RemainingAmount > 0 { + lots = append(lots, lot) + } + } + } + + active, err := p.repo.ListActiveLots(ctx, in.CustomerID, in.Currency, p.now()) + if err != nil { + return nil, err + } + for _, lot := range active { + if !preferred[lot.ID] { + lots = append(lots, lot) + } + } + return lots, nil +} + +// replay returns the first result for an idempotency key that has already been used, +// or nil when the key is new. It runs after the wallet lock, so a concurrent request +// with the same key has either committed its row or not started. +func (p *WalletProcessor) replay(ctx context.Context, in *WalletEntry, credit, compareAmount bool) (*WalletResult, error) { + if in.IdempotencyKey == "" { + return nil, nil + } + walletTx, err := p.repo.GetTransactionByIdempotencyKey(ctx, in.IdempotencyKey) + if err != nil || walletTx == nil { + return nil, err + } + + sameDirection := (walletTx.Amount > 0) == credit + sameAmount := !compareAmount || abs(walletTx.Amount) == in.Amount + if walletTx.CustomerID != in.CustomerID || walletTx.Currency != in.Currency || + walletTx.Type != in.Type || !sameDirection || !sameAmount { + return nil, ErrWalletIdempotencyConflict + } + + result := &WalletResult{Transaction: walletTx, Replayed: true} + if credit { + result.Lots, err = p.repo.ListLotsBySourceTransaction(ctx, walletTx.ID) + return result, err + } + + // JSON numbers come back from JSONB as float64. + switch shortfall := walletTx.Metadata["shortfall"].(type) { + case float64: + result.Shortfall = int64(shortfall) + case int64: + result.Shortfall = shortfall + } + allocations, err := p.repo.ListAllocationsByTransaction(ctx, walletTx.ID) + if err != nil { + return nil, err + } + ids := make([]uuid.UUID, 0, len(allocations)) + for _, a := range allocations { + ids = append(ids, a.LotID) + } + lots, err := p.repo.GetLotsByIDs(ctx, ids) + if err != nil { + return nil, err + } + expiry := make(map[uuid.UUID]*time.Time, len(lots)) + for _, lot := range lots { + expiry[lot.ID] = lot.ExpiresAt + } + for _, a := range allocations { + result.Allocations = append(result.Allocations, WalletAllocation{LotID: a.LotID, Amount: a.Amount, ExpiresAt: expiry[a.LotID]}) + } + return result, nil +} + +func newWalletTransaction(wallet *entities.CustomerWallet, in *WalletEntry, amount, balance int64, extra entities.Metadata) *entities.WalletTransaction { + metadata := entities.Metadata{} + for k, v := range in.Metadata { + metadata[k] = v + } + for k, v := range extra { + metadata[k] = v + } + var key *string + if in.IdempotencyKey != "" { + k := in.IdempotencyKey + key = &k + } + return &entities.WalletTransaction{ + ID: in.TransactionID, + OrganizationID: wallet.OrganizationID, + CustomerID: in.CustomerID, + Currency: in.Currency, + Type: in.Type, + Amount: amount, + BalanceAfter: balance, + GroupID: in.GroupID, + ReferenceType: in.ReferenceType, + ReferenceID: in.ReferenceID, + CounterpartyCustomerID: in.CounterpartyCustomerID, + ReversesTransactionID: in.ReversesTransactionID, + OutletID: in.OutletID, + CreatedByUser: in.CreatedByUser, + Reason: in.Reason, + Description: in.Description, + Metadata: metadata, + IdempotencyKey: key, + } +} + +// walletTypeRule is one row of §8.1. +type walletTypeRule struct { + credit, debit bool + currency string // empty: either currency + referenceTypes []string + needsOutlet bool + needsReverses bool + needsGroup bool + needsCounter bool + needsActor bool +} + +var walletTypeRules = map[string]walletTypeRule{ + constants.WalletTxTypeEarn: {credit: true, referenceTypes: []string{constants.WalletRefTypeOrder}, needsOutlet: true}, + constants.WalletTxTypeEarnReversal: {debit: true, referenceTypes: []string{constants.WalletRefTypeOrder}, needsOutlet: true, needsReverses: true}, + constants.WalletTxTypePayment: {debit: true, currency: constants.WalletCurrencyPoint, referenceTypes: []string{constants.WalletRefTypePayment}, needsOutlet: true}, + constants.WalletTxTypePaymentRefund: {credit: true, currency: constants.WalletCurrencyPoint, referenceTypes: []string{constants.WalletRefTypePayment}, needsOutlet: true, needsReverses: true}, + constants.WalletTxTypeExchangeOut: {debit: true, currency: constants.WalletCurrencyCoin, referenceTypes: []string{constants.WalletRefTypeWalletTx}, needsGroup: true}, + constants.WalletTxTypeExchangeIn: {credit: true, currency: constants.WalletCurrencyPoint, referenceTypes: []string{constants.WalletRefTypeWalletTx}, needsGroup: true}, + constants.WalletTxTypeTransferOut: {debit: true, referenceTypes: []string{constants.WalletRefTypeWalletTx}, needsGroup: true, needsCounter: true}, + constants.WalletTxTypeTransferIn: {credit: true, referenceTypes: []string{constants.WalletRefTypeWalletTx}, needsGroup: true, needsCounter: true}, + constants.WalletTxTypeGameSpend: {debit: true, currency: constants.WalletCurrencyCoin, referenceTypes: []string{constants.WalletRefTypeGamePlay}}, + constants.WalletTxTypeExpire: {debit: true, referenceTypes: []string{constants.WalletRefTypeLot}}, + constants.WalletTxTypeAdjustment: {credit: true, debit: true, referenceTypes: []string{constants.WalletRefTypeUser}, needsActor: true}, + constants.WalletTxTypeMigration: {credit: true, referenceTypes: []string{constants.WalletRefTypeLegacyPoints, constants.WalletRefTypeLegacyTokens}}, + constants.WalletTxTypeRewardRedeem: {debit: true, currency: constants.WalletCurrencyPoint, referenceTypes: []string{constants.WalletRefTypeRewardRedemption}}, +} + +func validateWalletEntry(in *WalletEntry, credit bool) error { + invalid := func(format string, args ...any) error { + return fmt.Errorf("%w: %s", ErrWalletInvalidEntry, fmt.Sprintf(format, args...)) + } + + rule, ok := walletTypeRules[in.Type] + if !ok { + return invalid("unknown type %q", in.Type) + } + if credit && !rule.credit { + return invalid("%s cannot add to a balance", in.Type) + } + if !credit && !rule.debit { + return invalid("%s cannot take from a balance", in.Type) + } + if in.CustomerID == uuid.Nil { + return invalid("customer is required") + } + if !constants.IsValidWalletCurrency(in.Currency) { + return invalid("unknown currency %q", in.Currency) + } + if rule.currency != "" && in.Currency != rule.currency { + return invalid("%s must be in %s", in.Type, rule.currency) + } + if in.Amount <= 0 { + return invalid("amount must be positive, got %d", in.Amount) + } + if !containsString(rule.referenceTypes, in.ReferenceType) { + return invalid("%s must reference %s, got %q", in.Type, strings.Join(rule.referenceTypes, " or "), in.ReferenceType) + } + if in.ReferenceID == uuid.Nil { + return invalid("reference id is required") + } + if strings.TrimSpace(in.Description) == "" { + return invalid("description is required") + } + if rule.needsOutlet && isNilID(in.OutletID) { + return invalid("%s requires an outlet", in.Type) + } + if rule.needsReverses && isNilID(in.ReversesTransactionID) { + return invalid("%s requires the transaction it reverses", in.Type) + } + if rule.needsGroup && isNilID(in.GroupID) { + return invalid("%s requires a group id", in.Type) + } + if rule.needsCounter { + if isNilID(in.CounterpartyCustomerID) { + return invalid("%s requires a counterparty", in.Type) + } + if *in.CounterpartyCustomerID == in.CustomerID { + return invalid("%s cannot go to the same customer", in.Type) + } + } + if rule.needsActor { + if isNilID(in.CreatedByUser) { + return invalid("%s requires the admin who made it", in.Type) + } + if in.Reason == nil || strings.TrimSpace(*in.Reason) == "" { + return invalid("%s requires a reason", in.Type) + } + } + return nil +} + +func isNilID(id *uuid.UUID) bool { + return id == nil || *id == uuid.Nil +} + +func containsString(values []string, v string) bool { + for _, value := range values { + if value == v { + return true + } + } + return false +} + +func abs(v int64) int64 { + if v < 0 { + return -v + } + return v +} diff --git a/internal/processor/wallet_processor_db_test.go b/internal/processor/wallet_processor_db_test.go new file mode 100644 index 0000000..d3aa795 --- /dev/null +++ b/internal/processor/wallet_processor_db_test.go @@ -0,0 +1,142 @@ +package processor + +import ( + "context" + "os" + "testing" + "time" + + "github.com/google/uuid" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "gorm.io/driver/postgres" + "gorm.io/gorm" + "gorm.io/gorm/logger" + + "apskel-pos-be/internal/constants" + "apskel-pos-be/internal/repository" +) + +// Runs the engine against Postgres, to show the rows it writes pass the database +// constraints and reconcile the way §7.5 requires. Needs TEST_DATABASE_URL pointing +// at a migrated database; see internal/repository/wallet_repository_test.go. +func TestWalletProcessor_AgainstPostgres(t *testing.T) { + dsn := os.Getenv("TEST_DATABASE_URL") + if dsn == "" { + t.Skip("TEST_DATABASE_URL not set") + } + db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{Logger: logger.Default.LogMode(logger.Silent)}) + require.NoError(t, err) + + org, a, b := uuid.New(), uuid.New(), uuid.New() + require.NoError(t, db.Exec(`INSERT INTO organizations (id, name, plan_type) VALUES (?, 'wallet test', 'basic')`, org).Error) + require.NoError(t, db.Exec(`INSERT INTO customers (id, organization_id, name) VALUES (?, ?, 'A'), (?, ?, 'B')`, a, org, b, org).Error) + customers := []uuid.UUID{a, b} + t.Cleanup(func() { + db.Exec(`DELETE FROM wallet_lot_allocations WHERE lot_id IN (SELECT id FROM wallet_lots WHERE customer_id IN ?)`, customers) + db.Exec(`DELETE FROM wallet_lots WHERE customer_id IN ?`, customers) + db.Exec(`DELETE FROM wallet_transactions WHERE customer_id IN ?`, customers) + db.Exec(`DELETE FROM customer_wallets WHERE customer_id IN ?`, customers) + db.Exec(`DELETE FROM customers WHERE id IN ?`, customers) + db.Exec(`DELETE FROM organizations WHERE id = ?`, org) + }) + + p := NewWalletProcessor(repository.NewWalletRepository(db)) + txm := repository.NewTxManager(db) + now := time.Now() + inTx := func(fn func(ctx context.Context) error) { + t.Helper() + require.NoError(t, txm.WithTransaction(context.Background(), fn)) + } + + // Without a transaction nothing moves. + _, err = p.Credit(context.Background(), earn(a, 10, nil)) + assert.ErrorIs(t, err, repository.ErrWalletTxRequired) + + var earned *WalletResult + inTx(func(ctx context.Context) error { + soon := now.Add(time.Hour) + earned, err = p.Credit(ctx, earn(a, 100, &soon)) + require.NoError(t, err) + _, err = p.Credit(ctx, earn(a, 50, nil)) + return err + }) + + // Transfer 120 from A to B, spanning both of A's lots. + inTx(func(ctx context.Context) error { + require.NoError(t, p.LockWallets(ctx, a, b)) + group, outID, inID := uuid.New(), uuid.New(), uuid.New() + out, err := p.Debit(ctx, WalletDebitInput{WalletEntry: WalletEntry{ + TransactionID: outID, CustomerID: a, Currency: constants.WalletCurrencyPoint, + Type: constants.WalletTxTypeTransferOut, Amount: 120, + ReferenceType: constants.WalletRefTypeWalletTx, ReferenceID: inID, + GroupID: &group, CounterpartyCustomerID: &b, Description: "Transfer ke B", + }}) + require.NoError(t, err) + _, err = p.Credit(ctx, WalletCreditInput{ + WalletEntry: WalletEntry{ + TransactionID: inID, CustomerID: b, Currency: constants.WalletCurrencyPoint, + Type: constants.WalletTxTypeTransferIn, Amount: 120, + ReferenceType: constants.WalletRefTypeWalletTx, ReferenceID: outID, + GroupID: &group, CounterpartyCustomerID: &a, Description: "Transfer dari A", + }, + Lots: out.CarryOver(), + }) + return err + }) + + // Reversing the 100 earned leaves A 30 short. The retry reads the shortfall back + // out of JSONB and takes nothing more. + rev := reversal(a, 100, earned) + rev.IdempotencyKey = "reverse:" + earned.Transaction.ID.String() + var first, second *WalletResult + inTx(func(ctx context.Context) error { + first, err = p.DebitUpTo(ctx, rev) + return err + }) + inTx(func(ctx context.Context) error { + second, err = p.DebitUpTo(ctx, rev) + return err + }) + assert.Equal(t, int64(-30), first.Transaction.Amount) + assert.Equal(t, int64(70), first.Shortfall) + assert.True(t, second.Replayed) + assert.Equal(t, int64(70), second.Shortfall) + assert.Equal(t, first.Transaction.ID, second.Transaction.ID) + + // Overdraw fails and rolls back cleanly. + err = txm.WithTransaction(context.Background(), func(ctx context.Context) error { + _, err := p.Debit(ctx, pay(b, 121)) + return err + }) + assert.ErrorIs(t, err, repository.ErrWalletInsufficientBalance) + + var balances []struct { + CustomerID uuid.UUID + PointBalance int64 + } + require.NoError(t, db.Raw(`SELECT customer_id, point_balance FROM customer_wallets WHERE customer_id IN ?`, customers).Scan(&balances).Error) + got := map[uuid.UUID]int64{} + for _, row := range balances { + got[row.CustomerID] = row.PointBalance + } + assert.Equal(t, map[uuid.UUID]int64{a: 0, b: 120}, got) + + // §7.5, straight from the tables. + var broken []string + require.NoError(t, db.Raw(` + SELECT 'wallet ' || w.customer_id FROM customer_wallets w + WHERE w.customer_id IN ? AND ( + w.point_balance <> (SELECT COALESCE(SUM(amount), 0) FROM wallet_transactions t WHERE t.customer_id = w.customer_id AND t.currency = 'POINT') + OR w.point_balance <> (SELECT COALESCE(SUM(remaining_amount), 0) FROM wallet_lots l WHERE l.customer_id = w.customer_id AND l.currency = 'POINT')) + UNION ALL + SELECT 'lot ' || l.id FROM wallet_lots l + WHERE l.customer_id IN ? AND l.original_amount - l.remaining_amount + <> (SELECT COALESCE(SUM(amount), 0) FROM wallet_lot_allocations a WHERE a.lot_id = l.id) + UNION ALL + SELECT 'debit ' || t.id FROM wallet_transactions t + WHERE t.customer_id IN ? AND t.amount < 0 + AND -t.amount <> (SELECT COALESCE(SUM(amount), 0) FROM wallet_lot_allocations a WHERE a.transaction_id = t.id)`, + customers, customers, customers).Scan(&broken).Error) + assert.Empty(t, broken) +} diff --git a/internal/processor/wallet_processor_test.go b/internal/processor/wallet_processor_test.go new file mode 100644 index 0000000..810dfd7 --- /dev/null +++ b/internal/processor/wallet_processor_test.go @@ -0,0 +1,788 @@ +package processor + +import ( + "context" + "errors" + "sort" + "testing" + "time" + + "github.com/google/uuid" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "apskel-pos-be/internal/constants" + "apskel-pos-be/internal/entities" + "apskel-pos-be/internal/repository" +) + +// walletRepoFake is an in-memory WalletRepository with the same conditional-update +// semantics as the real one. Locks are only counted: these tests are single-threaded, +// and the locking itself is covered by the repository tests against Postgres. +type walletRepoFake struct { + customers map[uuid.UUID]uuid.UUID // customer -> organization + wallets map[uuid.UUID]*entities.CustomerWallet + transactions []*entities.WalletTransaction + lots []*entities.WalletLot + allocations []entities.WalletLotAllocation + locks map[uuid.UUID]int + clock time.Time +} + +func newWalletRepoFake() *walletRepoFake { + return &walletRepoFake{ + customers: map[uuid.UUID]uuid.UUID{}, + wallets: map[uuid.UUID]*entities.CustomerWallet{}, + locks: map[uuid.UUID]int{}, + clock: time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC), + } +} + +func (f *walletRepoFake) tick() time.Time { + f.clock = f.clock.Add(time.Second) + return f.clock +} + +func (f *walletRepoFake) LockWallet(_ context.Context, customerID uuid.UUID) (*entities.CustomerWallet, error) { + org, ok := f.customers[customerID] + if !ok { + return nil, repository.ErrWalletNotFound + } + if f.wallets[customerID] == nil { + f.wallets[customerID] = &entities.CustomerWallet{CustomerID: customerID, OrganizationID: org} + } + f.locks[customerID]++ + w := *f.wallets[customerID] + return &w, nil +} + +func (f *walletRepoFake) LockWallets(ctx context.Context, a, b uuid.UUID) (*entities.CustomerWallet, *entities.CustomerWallet, error) { + wa, err := f.LockWallet(ctx, a) + if err != nil { + return nil, nil, err + } + wb, err := f.LockWallet(ctx, b) + return wa, wb, err +} + +func (f *walletRepoFake) AddBalance(_ context.Context, customerID uuid.UUID, currency string, delta int64) (int64, error) { + w := f.wallets[customerID] + if w == nil { + return 0, repository.ErrWalletNotFound + } + balance := &w.PointBalance + if currency == constants.WalletCurrencyCoin { + balance = &w.CoinBalance + } + if *balance+delta < 0 { + return 0, repository.ErrWalletInsufficientBalance + } + *balance += delta + return *balance, nil +} + +func (f *walletRepoFake) GetWallet(_ context.Context, customerID uuid.UUID) (*entities.CustomerWallet, error) { + w := f.wallets[customerID] + if w == nil { + return nil, errors.New("not found") + } + c := *w + return &c, nil +} + +func (f *walletRepoFake) CreateTransaction(_ context.Context, tx *entities.WalletTransaction) error { + if tx.IdempotencyKey != nil { + for _, t := range f.transactions { + if t.IdempotencyKey != nil && *t.IdempotencyKey == *tx.IdempotencyKey { + return errors.New("duplicate idempotency key") + } + } + } + if tx.ID == uuid.Nil { + tx.ID = uuid.New() + } + tx.CreatedAt = f.tick() + c := *tx + f.transactions = append(f.transactions, &c) + return nil +} + +func (f *walletRepoFake) GetTransactionByIdempotencyKey(_ context.Context, key string) (*entities.WalletTransaction, error) { + for _, t := range f.transactions { + if t.IdempotencyKey != nil && *t.IdempotencyKey == key { + c := *t + return &c, nil + } + } + return nil, nil +} + +func (f *walletRepoFake) CreateLot(_ context.Context, lot *entities.WalletLot) error { + if lot.ID == uuid.Nil { + lot.ID = uuid.New() + } + lot.CreatedAt = f.tick() + c := *lot + f.lots = append(f.lots, &c) + return nil +} + +func (f *walletRepoFake) GetLotsByIDs(_ context.Context, ids []uuid.UUID) ([]entities.WalletLot, error) { + var out []entities.WalletLot + for _, lot := range f.lots { + for _, id := range ids { + if lot.ID == id { + out = append(out, *lot) + break + } + } + } + return out, nil +} + +func (f *walletRepoFake) ListLotsBySourceTransaction(_ context.Context, txID uuid.UUID) ([]entities.WalletLot, error) { + var out []entities.WalletLot + for _, lot := range f.lots { + if lot.SourceTransactionID == txID { + out = append(out, *lot) + } + } + return out, nil +} + +func (f *walletRepoFake) ListActiveLots(_ context.Context, customerID uuid.UUID, currency string, asOf time.Time) ([]entities.WalletLot, error) { + var out []entities.WalletLot + for _, lot := range f.lots { + if lot.CustomerID == customerID && lot.Currency == currency && lot.RemainingAmount > 0 && + (lot.ExpiresAt == nil || lot.ExpiresAt.After(asOf)) { + out = append(out, *lot) + } + } + sort.SliceStable(out, func(i, j int) bool { + a, b := out[i], out[j] + switch { + case a.ExpiresAt == nil && b.ExpiresAt != nil: + return false + case a.ExpiresAt != nil && b.ExpiresAt == nil: + return true + case a.ExpiresAt != nil && !a.ExpiresAt.Equal(*b.ExpiresAt): + return a.ExpiresAt.Before(*b.ExpiresAt) + } + return a.CreatedAt.Before(b.CreatedAt) + }) + return out, nil +} + +func (f *walletRepoFake) ConsumeLot(_ context.Context, lotID uuid.UUID, amount int64) error { + for _, lot := range f.lots { + if lot.ID == lotID { + if lot.RemainingAmount < amount { + return repository.ErrWalletLotInsufficient + } + lot.RemainingAmount -= amount + return nil + } + } + return repository.ErrWalletLotInsufficient +} + +func (f *walletRepoFake) CreateAllocations(_ context.Context, allocations []entities.WalletLotAllocation) error { + f.allocations = append(f.allocations, allocations...) + return nil +} + +func (f *walletRepoFake) ListAllocationsByTransaction(_ context.Context, txID uuid.UUID) ([]entities.WalletLotAllocation, error) { + var out []entities.WalletLotAllocation + for _, a := range f.allocations { + if a.TransactionID == txID { + out = append(out, a) + } + } + return out, nil +} + +// assertInvariants checks the reconciliation rules of §7.5 over everything the fake +// holds. +func (f *walletRepoFake) assertInvariants(t *testing.T) { + t.Helper() + allocatedFromLot := map[uuid.UUID]int64{} + allocatedByTx := map[uuid.UUID]int64{} + for _, a := range f.allocations { + allocatedFromLot[a.LotID] += a.Amount + allocatedByTx[a.TransactionID] += a.Amount + } + createdByTx := map[uuid.UUID]int64{} + for _, lot := range f.lots { + createdByTx[lot.SourceTransactionID] += lot.OriginalAmount + assert.Equal(t, lot.OriginalAmount-allocatedFromLot[lot.ID], lot.RemainingAmount, "lot %s: original - allocations = remaining", lot.ID) + } + for _, tx := range f.transactions { + if tx.Amount > 0 { + assert.Equal(t, tx.Amount, createdByTx[tx.ID], "credit %s: lots add up to the amount", tx.Type) + assert.Zero(t, allocatedByTx[tx.ID], "credit %s has no allocations", tx.Type) + } else { + assert.Equal(t, -tx.Amount, allocatedByTx[tx.ID], "debit %s: allocations add up to the amount", tx.Type) + assert.Zero(t, createdByTx[tx.ID], "debit %s creates no lots", tx.Type) + } + } + for customerID, w := range f.wallets { + for currency, balance := range map[string]int64{ + constants.WalletCurrencyPoint: w.PointBalance, + constants.WalletCurrencyCoin: w.CoinBalance, + } { + var ledger, lots, last int64 + for _, tx := range f.transactions { + if tx.CustomerID == customerID && tx.Currency == currency { + ledger += tx.Amount + last = tx.BalanceAfter + } + } + for _, lot := range f.lots { + if lot.CustomerID == customerID && lot.Currency == currency { + lots += lot.RemainingAmount + } + } + assert.Equal(t, balance, ledger, "%s balance = SUM(ledger)", currency) + assert.Equal(t, balance, lots, "%s balance = SUM(lot remaining)", currency) + assert.Equal(t, balance, last, "%s balance = last balance_after", currency) + } + } +} + +type walletTestEnv struct { + repo *walletRepoFake + p *WalletProcessor + now time.Time + org uuid.UUID + ctx context.Context +} + +func newWalletTestEnv(t *testing.T) *walletTestEnv { + repo := newWalletRepoFake() + env := &walletTestEnv{ + repo: repo, + p: NewWalletProcessor(repo), + now: time.Date(2026, 6, 1, 12, 0, 0, 0, time.UTC), + org: uuid.New(), + ctx: context.Background(), + } + env.p.now = func() time.Time { return env.now } + t.Cleanup(func() { repo.assertInvariants(t) }) + return env +} + +func (e *walletTestEnv) customer() uuid.UUID { + id := uuid.New() + e.repo.customers[id] = e.org + return id +} + +func (e *walletTestEnv) at(d time.Duration) *time.Time { + v := e.now.Add(d) + return &v +} + +func ptr[T any](v T) *T { return &v } + +func earn(customerID uuid.UUID, amount int64, expiresAt *time.Time) WalletCreditInput { + return WalletCreditInput{ + WalletEntry: WalletEntry{ + CustomerID: customerID, + Currency: constants.WalletCurrencyPoint, + Type: constants.WalletTxTypeEarn, + Amount: amount, + ReferenceType: constants.WalletRefTypeOrder, + ReferenceID: uuid.New(), + OutletID: ptr(uuid.New()), + Description: "Belanja", + }, + Lots: []WalletLotInput{{Amount: amount, ExpiresAt: expiresAt}}, + } +} + +func pay(customerID uuid.UUID, amount int64) WalletDebitInput { + return WalletDebitInput{WalletEntry: WalletEntry{ + CustomerID: customerID, + Currency: constants.WalletCurrencyPoint, + Type: constants.WalletTxTypePayment, + Amount: amount, + ReferenceType: constants.WalletRefTypePayment, + ReferenceID: uuid.New(), + OutletID: ptr(uuid.New()), + Description: "Bayar", + }} +} + +func (e *walletTestEnv) credit(t *testing.T, in WalletCreditInput) *WalletResult { + t.Helper() + res, err := e.p.Credit(e.ctx, in) + require.NoError(t, err) + return res +} + +func (e *walletTestEnv) balance(t *testing.T, customerID uuid.UUID) int64 { + t.Helper() + w, err := e.repo.GetWallet(e.ctx, customerID) + require.NoError(t, err) + return w.PointBalance +} + +func allocationsOf(res *WalletResult) map[uuid.UUID]int64 { + out := map[uuid.UUID]int64{} + for _, a := range res.Allocations { + out[a.LotID] = a.Amount + } + return out +} + +func TestWalletProcessor_CreditCreatesLedgerRowAndLot(t *testing.T) { + e := newWalletTestEnv(t) + c := e.customer() + + res := e.credit(t, earn(c, 100, e.at(24*time.Hour))) + + assert.Equal(t, int64(100), res.Transaction.Amount) + assert.Equal(t, int64(100), res.Transaction.BalanceAfter) + assert.Equal(t, e.org, res.Transaction.OrganizationID, "organization comes from the wallet") + require.Len(t, res.Lots, 1) + assert.Equal(t, res.Transaction.ID, res.Lots[0].SourceTransactionID) + assert.Equal(t, e.at(24*time.Hour), res.Lots[0].ExpiresAt) + assert.Equal(t, int64(100), e.balance(t, c)) + assert.Equal(t, 1, e.repo.locks[c], "credit locks the wallet itself") +} + +func TestWalletProcessor_CreditWithoutLotsMakesOneNonExpiringLot(t *testing.T) { + e := newWalletTestEnv(t) + c := e.customer() + in := earn(c, 40, nil) + in.Lots = nil + + res := e.credit(t, in) + require.Len(t, res.Lots, 1) + assert.Equal(t, int64(40), res.Lots[0].OriginalAmount) + assert.Nil(t, res.Lots[0].ExpiresAt) +} + +func TestWalletProcessor_CreditRejectsLotsThatDoNotAddUp(t *testing.T) { + e := newWalletTestEnv(t) + c := e.customer() + in := earn(c, 100, nil) + in.Lots = []WalletLotInput{{Amount: 60}, {Amount: 30}} + + _, err := e.p.Credit(e.ctx, in) + assert.ErrorIs(t, err, ErrWalletInvalidEntry) + + in.Lots = []WalletLotInput{{Amount: 100}, {Amount: 0}} + _, err = e.p.Credit(e.ctx, in) + assert.ErrorIs(t, err, ErrWalletInvalidEntry) + assert.Empty(t, e.repo.transactions) +} + +func TestWalletProcessor_DebitAcrossSeveralLots(t *testing.T) { + e := newWalletTestEnv(t) + c := e.customer() + first := e.credit(t, earn(c, 30, e.at(1*time.Hour))).Lots[0] + second := e.credit(t, earn(c, 50, e.at(2*time.Hour))).Lots[0] + third := e.credit(t, earn(c, 40, e.at(3*time.Hour))).Lots[0] + + res, err := e.p.Debit(e.ctx, pay(c, 70)) + require.NoError(t, err) + + assert.Equal(t, int64(-70), res.Transaction.Amount) + assert.Equal(t, int64(50), res.Transaction.BalanceAfter) + assert.Equal(t, map[uuid.UUID]int64{first.ID: 30, second.ID: 40}, allocationsOf(res)) + assert.Equal(t, first.ID, res.Allocations[0].LotID, "allocations are reported in the order used") + assert.Equal(t, e.at(1*time.Hour), res.Allocations[0].ExpiresAt) + + lots, _ := e.repo.GetLotsByIDs(e.ctx, []uuid.UUID{first.ID, second.ID, third.ID}) + remaining := map[uuid.UUID]int64{} + for _, l := range lots { + remaining[l.ID] = l.RemainingAmount + } + assert.Equal(t, map[uuid.UUID]int64{first.ID: 0, second.ID: 10, third.ID: 40}, remaining) +} + +// K9: soonest expiry first, lots without an expiry last and oldest first among them, +// expired lots never. +func TestWalletProcessor_DebitFollowsLotOrder(t *testing.T) { + e := newWalletTestEnv(t) + c := e.customer() + neverOld := e.credit(t, earn(c, 10, nil)).Lots[0] + late := e.credit(t, earn(c, 10, e.at(48*time.Hour))).Lots[0] + soon := e.credit(t, earn(c, 10, e.at(1*time.Hour))).Lots[0] + neverNew := e.credit(t, earn(c, 10, nil)).Lots[0] + e.credit(t, earn(c, 10, e.at(-1*time.Hour))) // already expired + + var order []uuid.UUID + for i := 0; i < 4; i++ { + res, err := e.p.Debit(e.ctx, pay(c, 10)) + require.NoError(t, err) + require.Len(t, res.Allocations, 1) + order = append(order, res.Allocations[0].LotID) + } + assert.Equal(t, []uuid.UUID{soon.ID, late.ID, neverOld.ID, neverNew.ID}, order) + + // The expired lot still counts in the balance until the expiry job removes it, + // but it cannot be spent (§7.3). + assert.Equal(t, int64(10), e.balance(t, c)) + _, err := e.p.Debit(e.ctx, pay(c, 10)) + assert.ErrorIs(t, err, repository.ErrWalletInsufficientBalance) +} + +func TestWalletProcessor_DebitOverBalanceChangesNothing(t *testing.T) { + e := newWalletTestEnv(t) + c := e.customer() + e.credit(t, earn(c, 50, nil)) + + _, err := e.p.Debit(e.ctx, pay(c, 51)) + assert.ErrorIs(t, err, repository.ErrWalletInsufficientBalance) + assert.Equal(t, int64(50), e.balance(t, c)) + assert.Len(t, e.repo.transactions, 1) + assert.Empty(t, e.repo.allocations) + + // A customer who never had a wallet has nothing to spend. + _, err = e.p.Debit(e.ctx, pay(e.customer(), 1)) + assert.ErrorIs(t, err, repository.ErrWalletInsufficientBalance) +} + +func reversal(customerID uuid.UUID, amount int64, earnRes *WalletResult) WalletDebitInput { + in := WalletDebitInput{WalletEntry: WalletEntry{ + CustomerID: customerID, + Currency: constants.WalletCurrencyPoint, + Type: constants.WalletTxTypeEarnReversal, + Amount: amount, + ReferenceType: constants.WalletRefTypeOrder, + ReferenceID: earnRes.Transaction.ReferenceID, + ReversesTransactionID: &earnRes.Transaction.ID, + OutletID: earnRes.Transaction.OutletID, + Description: "Batal", + }} + for _, lot := range earnRes.Lots { + in.PreferredLotIDs = append(in.PreferredLotIDs, lot.ID) + } + return in +} + +func TestWalletProcessor_DebitUpToWithShortfall(t *testing.T) { + e := newWalletTestEnv(t) + c := e.customer() + earned := e.credit(t, earn(c, 100, nil)) + _, err := e.p.Debit(e.ctx, pay(c, 70)) + require.NoError(t, err) + + res, err := e.p.DebitUpTo(e.ctx, reversal(c, 100, earned)) + require.NoError(t, err) + assert.Equal(t, int64(-30), res.Transaction.Amount) + assert.Equal(t, int64(70), res.Shortfall) + assert.Equal(t, int64(100), res.Transaction.Metadata["requested_amount"]) + assert.Equal(t, int64(70), res.Transaction.Metadata["shortfall"]) + assert.Equal(t, int64(0), e.balance(t, c)) + + // Nothing left: no ledger row, the whole amount is shortfall. + in := reversal(c, 5, earned) + res, err = e.p.DebitUpTo(e.ctx, in) + require.NoError(t, err) + assert.Nil(t, res.Transaction) + assert.Equal(t, int64(5), res.Shortfall) + assert.Len(t, e.repo.transactions, 3) +} + +// A reversal draws from the lots its EARN created first (F10), even when an older lot +// would come first in K9 order, and even when that lot has expired. +func TestWalletProcessor_DebitDrawsPreferredLotsFirst(t *testing.T) { + e := newWalletTestEnv(t) + c := e.customer() + older := e.credit(t, earn(c, 50, e.at(1*time.Hour))).Lots[0] + earned := e.credit(t, earn(c, 20, e.at(-1*time.Hour))) + + res, err := e.p.Debit(e.ctx, reversal(c, 30, earned)) + require.NoError(t, err) + require.Len(t, res.Allocations, 2) + assert.Equal(t, earned.Lots[0].ID, res.Allocations[0].LotID) + assert.Equal(t, int64(20), res.Allocations[0].Amount) + assert.Equal(t, older.ID, res.Allocations[1].LotID) + assert.Equal(t, int64(10), res.Allocations[1].Amount) +} + +func TestWalletProcessor_DebitRejectsSomeoneElsesLot(t *testing.T) { + e := newWalletTestEnv(t) + a, b := e.customer(), e.customer() + e.credit(t, earn(a, 10, nil)) + other := e.credit(t, earn(b, 10, nil)) + + in := pay(a, 5) + in.PreferredLotIDs = []uuid.UUID{other.Lots[0].ID} + _, err := e.p.Debit(e.ctx, in) + assert.ErrorIs(t, err, ErrWalletInvalidEntry) + + in.PreferredLotIDs = []uuid.UUID{uuid.New()} + _, err = e.p.Debit(e.ctx, in) + assert.ErrorIs(t, err, ErrWalletInvalidEntry) +} + +func TestWalletProcessor_ExpireDrawsTheExpiredLot(t *testing.T) { + e := newWalletTestEnv(t) + c := e.customer() + e.credit(t, earn(c, 10, nil)) + expired := e.credit(t, earn(c, 25, e.at(-1*time.Hour))).Lots[0] + + res, err := e.p.Debit(e.ctx, WalletDebitInput{ + WalletEntry: WalletEntry{ + CustomerID: c, + Currency: constants.WalletCurrencyPoint, + Type: constants.WalletTxTypeExpire, + Amount: expired.RemainingAmount, + ReferenceType: constants.WalletRefTypeLot, + ReferenceID: expired.ID, + Description: "Kedaluwarsa", + IdempotencyKey: "expire:" + expired.ID.String(), + }, + PreferredLotIDs: []uuid.UUID{expired.ID}, + }) + require.NoError(t, err) + assert.Equal(t, map[uuid.UUID]int64{expired.ID: 25}, allocationsOf(res)) + assert.Equal(t, int64(10), e.balance(t, c)) +} + +func TestWalletProcessor_IdempotentCredit(t *testing.T) { + e := newWalletTestEnv(t) + c := e.customer() + in := earn(c, 100, nil) + in.IdempotencyKey = "earn:order-1" + + first := e.credit(t, in) + in.ReferenceID = first.Transaction.ReferenceID + second := e.credit(t, in) + + assert.True(t, second.Replayed) + assert.False(t, first.Replayed) + assert.Equal(t, first.Transaction.ID, second.Transaction.ID) + assert.Equal(t, first.Lots[0].ID, second.Lots[0].ID) + assert.Equal(t, int64(100), e.balance(t, c)) + assert.Len(t, e.repo.transactions, 1) +} + +func TestWalletProcessor_IdempotentDebit(t *testing.T) { + e := newWalletTestEnv(t) + c := e.customer() + e.credit(t, earn(c, 30, e.at(time.Hour))) + e.credit(t, earn(c, 30, nil)) + in := pay(c, 40) + in.IdempotencyKey = "pay:1" + + first, err := e.p.Debit(e.ctx, in) + require.NoError(t, err) + second, err := e.p.Debit(e.ctx, in) + require.NoError(t, err) + + assert.True(t, second.Replayed) + assert.Equal(t, first.Transaction.ID, second.Transaction.ID) + assert.ElementsMatch(t, first.Allocations, second.Allocations) + assert.Equal(t, int64(20), e.balance(t, c)) +} + +func TestWalletProcessor_IdempotentDebitUpToKeepsShortfall(t *testing.T) { + e := newWalletTestEnv(t) + c := e.customer() + earned := e.credit(t, earn(c, 100, nil)) + _, err := e.p.Debit(e.ctx, pay(c, 60)) + require.NoError(t, err) + in := reversal(c, 100, earned) + in.IdempotencyKey = "reverse:order-1" + + first, err := e.p.DebitUpTo(e.ctx, in) + require.NoError(t, err) + e.credit(t, earn(c, 500, nil)) // new balance must not be taken by the retry + second, err := e.p.DebitUpTo(e.ctx, in) + require.NoError(t, err) + + assert.True(t, second.Replayed) + assert.Equal(t, first.Transaction.ID, second.Transaction.ID) + assert.Equal(t, int64(60), second.Shortfall) + assert.Equal(t, int64(500), e.balance(t, c)) +} + +func TestWalletProcessor_IdempotencyKeyReusedForAnotherOperation(t *testing.T) { + e := newWalletTestEnv(t) + c := e.customer() + in := earn(c, 100, nil) + in.IdempotencyKey = "k" + e.credit(t, in) + + other := earn(c, 99, nil) + other.IdempotencyKey = "k" + _, err := e.p.Credit(e.ctx, other) + assert.ErrorIs(t, err, ErrWalletIdempotencyConflict) + + debit := pay(c, 100) + debit.IdempotencyKey = "k" + _, err = e.p.Debit(e.ctx, debit) + assert.ErrorIs(t, err, ErrWalletIdempotencyConflict) + + otherCustomer := earn(e.customer(), 100, nil) + otherCustomer.IdempotencyKey = "k" + _, err = e.p.Credit(e.ctx, otherCustomer) + assert.ErrorIs(t, err, ErrWalletIdempotencyConflict) +} + +// A transfer debits the sender and credits the receiver with lots that keep the +// sender's expiry (K9), following the example in §8. +func TestWalletProcessor_TransferCarriesExpiry(t *testing.T) { + e := newWalletTestEnv(t) + a, b := e.customer(), e.customer() + dec := e.credit(t, earn(a, 100, e.at(30*24*time.Hour))).Lots[0] + jan := e.credit(t, earn(a, 50, e.at(60*24*time.Hour))).Lots[0] + + require.NoError(t, e.p.LockWallets(e.ctx, a, b)) + group, outID, inID := uuid.New(), uuid.New(), uuid.New() + out, err := e.p.Debit(e.ctx, WalletDebitInput{WalletEntry: WalletEntry{ + TransactionID: outID, CustomerID: a, Currency: constants.WalletCurrencyPoint, + Type: constants.WalletTxTypeTransferOut, Amount: 120, + ReferenceType: constants.WalletRefTypeWalletTx, ReferenceID: inID, + GroupID: &group, CounterpartyCustomerID: &b, Description: "Transfer ke B", + }}) + require.NoError(t, err) + received, err := e.p.Credit(e.ctx, WalletCreditInput{ + WalletEntry: WalletEntry{ + TransactionID: inID, CustomerID: b, Currency: constants.WalletCurrencyPoint, + Type: constants.WalletTxTypeTransferIn, Amount: 120, + ReferenceType: constants.WalletRefTypeWalletTx, ReferenceID: outID, + GroupID: &group, CounterpartyCustomerID: &a, Description: "Transfer dari A", + }, + Lots: out.CarryOver(), + }) + require.NoError(t, err) + + assert.Equal(t, outID, out.Transaction.ID) + assert.Equal(t, inID, received.Transaction.ID) + require.Len(t, received.Lots, 2) + assert.Equal(t, int64(100), received.Lots[0].OriginalAmount) + assert.Equal(t, dec.ExpiresAt, received.Lots[0].ExpiresAt) + assert.Equal(t, &dec.ID, received.Lots[0].OriginLotID) + assert.Equal(t, int64(20), received.Lots[1].OriginalAmount) + assert.Equal(t, jan.ExpiresAt, received.Lots[1].ExpiresAt) + assert.Equal(t, &jan.ID, received.Lots[1].OriginLotID) + assert.Equal(t, int64(30), e.balance(t, a)) + assert.Equal(t, int64(120), e.balance(t, b)) +} + +func TestWalletProcessor_RejectsEntriesThatBreakTheTypeRules(t *testing.T) { + c := uuid.New() + outlet := ptr(uuid.New()) + + credits := map[string]func(*WalletCreditInput){ + "unknown type": func(in *WalletCreditInput) { in.Type = "BONUS" }, + "debit-only type as credit": func(in *WalletCreditInput) { + in.Type = constants.WalletTxTypePayment + in.ReferenceType = constants.WalletRefTypePayment + }, + "unknown currency": func(in *WalletCreditInput) { in.Currency = "GOLD" }, + "zero amount": func(in *WalletCreditInput) { in.Amount = 0; in.Lots = nil }, + "negative amount": func(in *WalletCreditInput) { in.Amount = -5; in.Lots = nil }, + "wrong reference type": func(in *WalletCreditInput) { in.ReferenceType = constants.WalletRefTypeUser }, + "missing reference id": func(in *WalletCreditInput) { in.ReferenceID = uuid.Nil }, + "missing description": func(in *WalletCreditInput) { in.Description = " " }, + "EARN without outlet": func(in *WalletCreditInput) { in.OutletID = nil }, + "missing customer": func(in *WalletCreditInput) { in.CustomerID = uuid.Nil }, + "EXCHANGE_IN in COIN": func(in *WalletCreditInput) { + in.Type = constants.WalletTxTypeExchangeIn + in.Currency = constants.WalletCurrencyCoin + in.ReferenceType = constants.WalletRefTypeWalletTx + in.GroupID = ptr(uuid.New()) + }, + "TRANSFER_IN to self": func(in *WalletCreditInput) { + in.Type = constants.WalletTxTypeTransferIn + in.ReferenceType = constants.WalletRefTypeWalletTx + in.GroupID = ptr(uuid.New()) + in.CounterpartyCustomerID = &in.CustomerID + }, + "TRANSFER_IN without group": func(in *WalletCreditInput) { + in.Type = constants.WalletTxTypeTransferIn + in.ReferenceType = constants.WalletRefTypeWalletTx + in.CounterpartyCustomerID = ptr(uuid.New()) + }, + "PAYMENT_REFUND without source": func(in *WalletCreditInput) { + in.Type = constants.WalletTxTypePaymentRefund + in.ReferenceType = constants.WalletRefTypePayment + }, + "ADJUSTMENT without reason": func(in *WalletCreditInput) { + in.Type = constants.WalletTxTypeAdjustment + in.ReferenceType = constants.WalletRefTypeUser + in.CreatedByUser = ptr(uuid.New()) + }, + "ADJUSTMENT blank reason": func(in *WalletCreditInput) { + in.Type = constants.WalletTxTypeAdjustment + in.ReferenceType = constants.WalletRefTypeUser + in.CreatedByUser = ptr(uuid.New()) + in.Reason = ptr(" ") + }, + "ADJUSTMENT without admin": func(in *WalletCreditInput) { + in.Type = constants.WalletTxTypeAdjustment + in.ReferenceType = constants.WalletRefTypeUser + in.Reason = ptr("komplain") + }, + "MIGRATION wrong reference": func(in *WalletCreditInput) { + in.Type = constants.WalletTxTypeMigration + in.ReferenceType = constants.WalletRefTypeOrder + }, + } + for name, mutate := range credits { + t.Run("credit/"+name, func(t *testing.T) { + e := newWalletTestEnv(t) + e.repo.customers[c] = e.org + in := earn(c, 10, nil) + in.OutletID = outlet + mutate(&in) + _, err := e.p.Credit(e.ctx, in) + assert.ErrorIs(t, err, ErrWalletInvalidEntry) + assert.Empty(t, e.repo.transactions) + }) + } + + debits := map[string]func(*WalletDebitInput){ + "credit-only type as debit": func(in *WalletDebitInput) { + in.Type = constants.WalletTxTypeMigration + in.ReferenceType = constants.WalletRefTypeLegacyPoints + }, + "PAYMENT in COIN": func(in *WalletDebitInput) { in.Currency = constants.WalletCurrencyCoin }, + "GAME_SPEND in POINT": func(in *WalletDebitInput) { + in.Type = constants.WalletTxTypeGameSpend + in.ReferenceType = constants.WalletRefTypeGamePlay + }, + "EXPIRE not pointing at a lot": func(in *WalletDebitInput) { + in.Type = constants.WalletTxTypeExpire + in.ReferenceType = constants.WalletRefTypeOrder + }, + "EARN_REVERSAL without source": func(in *WalletDebitInput) { + in.Type = constants.WalletTxTypeEarnReversal + in.ReferenceType = constants.WalletRefTypeOrder + }, + "TRANSFER_OUT without counterparty": func(in *WalletDebitInput) { + in.Type = constants.WalletTxTypeTransferOut + in.ReferenceType = constants.WalletRefTypeWalletTx + in.GroupID = ptr(uuid.New()) + }, + "REWARD_REDEEM wrong reference": func(in *WalletDebitInput) { + in.Type = constants.WalletTxTypeRewardRedeem + in.ReferenceType = constants.WalletRefTypeOrder + }, + } + for name, mutate := range debits { + t.Run("debit/"+name, func(t *testing.T) { + e := newWalletTestEnv(t) + e.repo.customers[c] = e.org + e.credit(t, earn(c, 100, nil)) + in := pay(c, 10) + mutate(&in) + _, err := e.p.Debit(e.ctx, in) + assert.ErrorIs(t, err, ErrWalletInvalidEntry) + assert.Len(t, e.repo.transactions, 1) + }) + } +} + +func TestWalletProcessor_UnknownCustomer(t *testing.T) { + e := newWalletTestEnv(t) + _, err := e.p.Credit(e.ctx, earn(uuid.New(), 10, nil)) + assert.ErrorIs(t, err, repository.ErrWalletNotFound) +} diff --git a/internal/processor/wallet_query_processor.go b/internal/processor/wallet_query_processor.go new file mode 100644 index 0000000..3a83fb6 --- /dev/null +++ b/internal/processor/wallet_query_processor.go @@ -0,0 +1,336 @@ +package processor + +import ( + "context" + "errors" + "fmt" + "strings" + "time" + + "github.com/google/uuid" + + "apskel-pos-be/internal/constants" + "apskel-pos-be/internal/entities" + "apskel-pos-be/internal/models" + "apskel-pos-be/internal/repository" +) + +// ErrInvalidWalletQuery wraps every rejection of a malformed history query, so the +// handler can answer with a validation error rather than a server error. +var ErrInvalidWalletQuery = errors.New("invalid wallet query") + +const ( + walletRecentTransactions = 5 + walletLegacyHistorySize = 10 + walletTransactionsPageLimit = 20 + walletTransactionsMaxLimit = 100 +) + +// walletDisplayLocation is where the customer's calendar days start and end, for +// date filters. Same zone as the database connection and the expiry grouping. +var walletDisplayLocation = func() *time.Location { + loc, err := time.LoadLocation("Asia/Jakarta") + if err != nil { + return time.FixedZone("WIB", 7*60*60) + } + return loc +}() + +// WalletQueryProcessor answers what the customer app shows about a wallet: balances, +// history and upcoming expiry (docs/prd-point-coin.md F6). It only reads. +type WalletQueryProcessor struct { + repo repository.WalletQueryRepository + settings pointValueReader + now func() time.Time +} + +// pointValueReader gives the rupiah value of one EnakPoint in an organization. +// LoyaltySettingsProcessor is one. +type pointValueReader interface { + PointValue(ctx context.Context, organizationID uuid.UUID) (int64, error) +} + +func NewWalletQueryProcessor(repo repository.WalletQueryRepository, settings pointValueReader) *WalletQueryProcessor { + return &WalletQueryProcessor{repo: repo, settings: settings, now: time.Now} +} + +// Summary is GET /customer/wallet. A customer who has never had a wallet gets zeros. +func (p *WalletQueryProcessor) Summary(ctx context.Context, customerID uuid.UUID) (*models.GetCustomerWalletResponseData, error) { + organizationID, err := p.repo.GetCustomerOrganizationID(ctx, customerID) + if err != nil { + return nil, err + } + now := p.now() + + balances, err := p.repo.SpendableBalances(ctx, customerID, now) + if err != nil { + return nil, err + } + pointValue, err := p.settings.PointValue(ctx, organizationID) + if err != nil { + return nil, err + } + expiring, err := p.repo.NearestExpiring(ctx, customerID, now) + if err != nil { + return nil, err + } + recent, err := p.recent(ctx, customerID, "", walletRecentTransactions) + if err != nil { + return nil, err + } + points, err := p.legacyPoints(ctx, customerID, balances) + if err != nil { + return nil, err + } + tokens, err := p.legacyTokens(ctx, customerID, balances) + if err != nil { + return nil, err + } + + data := &models.GetCustomerWalletResponseData{ + PointBalance: balances[constants.WalletCurrencyPoint], + CoinBalance: balances[constants.WalletCurrencyCoin], + PointValue: pointValue, + PointDiscountValue: balances[constants.WalletCurrencyPoint] * pointValue, + RecentTransactions: recent, + TotalPoints: points.TotalPoints, + TotalTokens: tokens.TotalTokens, + PointsHistory: points.PointsHistory, + TokensHistory: tokens.TokensHistory, + LastUpdated: points.LastUpdated, + } + if tokens.LastUpdated.After(data.LastUpdated) { + data.LastUpdated = tokens.LastUpdated + } + for _, e := range expiring { + entry := &models.CustomerWalletExpiring{Amount: e.Amount, Date: e.Date} + switch e.Currency { + case constants.WalletCurrencyPoint: + data.NearestExpiring.Point = entry + case constants.WalletCurrencyCoin: + data.NearestExpiring.Coin = entry + } + } + return data, nil +} + +// Transactions is GET /customer/wallet/transactions. +func (p *WalletQueryProcessor) Transactions(ctx context.Context, customerID uuid.UUID, query models.ListCustomerWalletTransactionsQuery) (*models.PaginatedResponse[models.CustomerWalletTransaction], error) { + filter, page, err := walletTransactionFilter(customerID, query) + if err != nil { + return nil, err + } + rows, total, err := p.repo.ListTransactions(ctx, filter) + if err != nil { + return nil, err + } + items, err := p.toTransactions(ctx, rows) + if err != nil { + return nil, err + } + totalPages := int((total + int64(filter.Limit) - 1) / int64(filter.Limit)) + return &models.PaginatedResponse[models.CustomerWalletTransaction]{ + Data: items, + Pagination: models.Pagination{Page: page, Limit: filter.Limit, Total: total, TotalPages: totalPages}, + }, nil +} + +// LegacyPoints is the pre-wallet GET /customer/points, now read from the wallet. +func (p *WalletQueryProcessor) LegacyPoints(ctx context.Context, customerID uuid.UUID) (*models.GetCustomerPointsResponseData, error) { + balances, err := p.repo.SpendableBalances(ctx, customerID, p.now()) + if err != nil { + return nil, err + } + return p.legacyPoints(ctx, customerID, balances) +} + +func (p *WalletQueryProcessor) legacyPoints(ctx context.Context, customerID uuid.UUID, balances map[string]int64) (*models.GetCustomerPointsResponseData, error) { + recent, err := p.recent(ctx, customerID, constants.WalletCurrencyPoint, walletLegacyHistorySize) + if err != nil { + return nil, err + } + data := &models.GetCustomerPointsResponseData{TotalPoints: balances[constants.WalletCurrencyPoint]} + for _, tx := range recent { + data.PointsHistory = append(data.PointsHistory, models.PointsHistoryItem{ + ID: tx.ID.String(), Points: tx.Amount, Type: tx.Type, Description: tx.Description, CreatedAt: tx.CreatedAt, + }) + } + if len(recent) > 0 { + data.LastUpdated = recent[0].CreatedAt + } + return data, nil +} + +// LegacyTokens is the pre-wallet GET /customer/tokens. Tokens are EnakCoin now. +func (p *WalletQueryProcessor) LegacyTokens(ctx context.Context, customerID uuid.UUID) (*models.GetCustomerTokensResponseData, error) { + balances, err := p.repo.SpendableBalances(ctx, customerID, p.now()) + if err != nil { + return nil, err + } + return p.legacyTokens(ctx, customerID, balances) +} + +func (p *WalletQueryProcessor) legacyTokens(ctx context.Context, customerID uuid.UUID, balances map[string]int64) (*models.GetCustomerTokensResponseData, error) { + recent, err := p.recent(ctx, customerID, constants.WalletCurrencyCoin, walletLegacyHistorySize) + if err != nil { + return nil, err + } + data := &models.GetCustomerTokensResponseData{TotalTokens: balances[constants.WalletCurrencyCoin]} + for _, tx := range recent { + data.TokensHistory = append(data.TokensHistory, models.TokensHistoryItem{ + ID: tx.ID.String(), Tokens: tx.Amount, Type: tx.Type, Description: tx.Description, CreatedAt: tx.CreatedAt, + }) + } + if len(recent) > 0 { + data.LastUpdated = recent[0].CreatedAt + } + return data, nil +} + +func (p *WalletQueryProcessor) recent(ctx context.Context, customerID uuid.UUID, currency string, limit int) ([]models.CustomerWalletTransaction, error) { + rows, _, err := p.repo.ListTransactions(ctx, repository.WalletTransactionFilter{ + CustomerID: customerID, Currency: currency, Limit: limit, + }) + if err != nil { + return nil, err + } + return p.toTransactions(ctx, rows) +} + +func (p *WalletQueryProcessor) toTransactions(ctx context.Context, rows []entities.WalletTransaction) ([]models.CustomerWalletTransaction, error) { + return buildWalletTransactions(ctx, p.repo, rows) +} + +// buildWalletTransactions turns ledger rows into what the apps show, in the same +// order: where each row came from or went to, and the lots each credit created. +func buildWalletTransactions(ctx context.Context, repo repository.WalletQueryRepository, rows []entities.WalletTransaction) ([]models.CustomerWalletTransaction, error) { + var credits []uuid.UUID + for _, row := range rows { + if row.Amount > 0 { + credits = append(credits, row.ID) + } + } + lots, err := repo.ListLotsBySourceTransactions(ctx, credits) + if err != nil { + return nil, err + } + lotsByTx := make(map[uuid.UUID][]entities.WalletLot, len(credits)) + for _, lot := range lots { + lotsByTx[lot.SourceTransactionID] = append(lotsByTx[lot.SourceTransactionID], lot) + } + + items := make([]models.CustomerWalletTransaction, 0, len(rows)) + for _, row := range rows { + ref := &models.CustomerWalletTransactionRef{Type: row.ReferenceType, ID: row.ReferenceID} + item := models.CustomerWalletTransaction{ + ID: row.ID, + Currency: row.Currency, + Type: row.Type, + Amount: row.Amount, + BalanceAfter: row.BalanceAfter, + Description: row.Description, + OutletID: row.OutletID, + ReversesTransactionID: row.ReversesTransactionID, + GroupID: row.GroupID, + CreatedAt: row.CreatedAt, + } + // The counterparty's id, the admin and the metadata are left out on purpose: + // the customer sees the masked name in the description (§8.1). + if row.Amount > 0 { + item.Source = ref + for _, lot := range lotsByTx[row.ID] { + item.Lots = append(item.Lots, models.CustomerWalletLot{ + Amount: lot.OriginalAmount, Remaining: lot.RemainingAmount, ExpiresAt: lot.ExpiresAt, + }) + if lot.ExpiresAt != nil && (item.ExpiresAt == nil || lot.ExpiresAt.Before(*item.ExpiresAt)) { + item.ExpiresAt = lot.ExpiresAt + } + } + } else { + item.Destination = ref + } + items = append(items, item) + } + return items, nil +} + +func walletTransactionFilter(customerID uuid.UUID, q models.ListCustomerWalletTransactionsQuery) (repository.WalletTransactionFilter, int, error) { + invalid := func(format string, args ...any) error { + return fmt.Errorf("%w: %s", ErrInvalidWalletQuery, fmt.Sprintf(format, args...)) + } + filter := repository.WalletTransactionFilter{CustomerID: customerID} + + page := q.Page + if page == 0 { + page = 1 + } + if page < 1 { + return filter, 0, invalid("page must be at least 1") + } + filter.Limit = q.Limit + if filter.Limit == 0 { + filter.Limit = walletTransactionsPageLimit + } + if filter.Limit < 1 || filter.Limit > walletTransactionsMaxLimit { + return filter, 0, invalid("limit must be between 1 and %d", walletTransactionsMaxLimit) + } + filter.Offset = (page - 1) * filter.Limit + + if q.Currency != "" { + currency := strings.ToUpper(q.Currency) + if !constants.IsValidWalletCurrency(currency) { + return filter, 0, invalid("currency must be POINT or COIN") + } + filter.Currency = currency + } + for _, t := range strings.Split(q.Type, ",") { + t = strings.ToUpper(strings.TrimSpace(t)) + if t == "" { + continue + } + if _, ok := walletTypeRules[t]; !ok { + return filter, 0, invalid("unknown type %q", t) + } + filter.Types = append(filter.Types, t) + } + + if q.From != "" { + from, err := time.ParseInLocation("2006-01-02", q.From, walletDisplayLocation) + if err != nil { + return filter, 0, invalid("from must be a date like 2026-01-31") + } + filter.From = &from + } + if q.To != "" { + to, err := time.ParseInLocation("2006-01-02", q.To, walletDisplayLocation) + if err != nil { + return filter, 0, invalid("to must be a date like 2026-01-31") + } + // To is inclusive for the customer, exclusive in the query. + end := to.AddDate(0, 0, 1) + filter.To = &end + } + if filter.From != nil && filter.To != nil && !filter.From.Before(*filter.To) { + return filter, 0, invalid("from must not be after to") + } + return filter, page, nil +} + +// Expiring is GET /customer/wallet/expiring: what will expire, grouped by day (F6). +func (p *WalletQueryProcessor) Expiring(ctx context.Context, customerID uuid.UUID) (*models.CustomerWalletExpiringList, error) { + rows, err := p.repo.ExpiringByDay(ctx, customerID, p.now()) + if err != nil { + return nil, err + } + list := &models.CustomerWalletExpiringList{Point: []models.CustomerWalletExpiring{}, Coin: []models.CustomerWalletExpiring{}} + for _, row := range rows { + item := models.CustomerWalletExpiring{Amount: row.Amount, Date: row.Date} + switch row.Currency { + case constants.WalletCurrencyPoint: + list.Point = append(list.Point, item) + case constants.WalletCurrencyCoin: + list.Coin = append(list.Coin, item) + } + } + return list, nil +} diff --git a/internal/processor/wallet_query_processor_test.go b/internal/processor/wallet_query_processor_test.go new file mode 100644 index 0000000..bf6def7 --- /dev/null +++ b/internal/processor/wallet_query_processor_test.go @@ -0,0 +1,266 @@ +package processor + +import ( + "context" + "testing" + "time" + + "github.com/google/uuid" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "apskel-pos-be/internal/constants" + "apskel-pos-be/internal/entities" + "apskel-pos-be/internal/models" + "apskel-pos-be/internal/repository" +) + +type walletQueryRepoFake struct { + org uuid.UUID + spendable map[string]int64 + expiring []repository.WalletExpiringAmount + transactions []entities.WalletTransaction + total int64 + lots []entities.WalletLot + filters []repository.WalletTransactionFilter +} + +func (f *walletQueryRepoFake) GetCustomerOrganizationID(context.Context, uuid.UUID) (uuid.UUID, error) { + if f.org == uuid.Nil { + return uuid.Nil, repository.ErrWalletNotFound + } + return f.org, nil +} + +func (f *walletQueryRepoFake) SpendableBalances(context.Context, uuid.UUID, time.Time) (map[string]int64, error) { + return f.spendable, nil +} + +func (f *walletQueryRepoFake) NearestExpiring(context.Context, uuid.UUID, time.Time) ([]repository.WalletExpiringAmount, error) { + return f.expiring, nil +} + +func (f *walletQueryRepoFake) ListTransactions(_ context.Context, filter repository.WalletTransactionFilter) ([]entities.WalletTransaction, int64, error) { + f.filters = append(f.filters, filter) + var out []entities.WalletTransaction + for _, tx := range f.transactions { + if filter.Currency == "" || tx.Currency == filter.Currency { + out = append(out, tx) + } + } + if len(out) > filter.Limit { + out = out[:filter.Limit] + } + return out, f.total, nil +} + +func (f *walletQueryRepoFake) ListLotsBySourceTransactions(_ context.Context, ids []uuid.UUID) ([]entities.WalletLot, error) { + var out []entities.WalletLot + for _, lot := range f.lots { + for _, id := range ids { + if lot.SourceTransactionID == id { + out = append(out, lot) + } + } + } + return out, nil +} + +type orgSettingsFake map[string]string + +func newWalletQueryTest(repo *walletQueryRepoFake, settings orgSettingsFake) *WalletQueryProcessor { + p := NewWalletQueryProcessor(repo, NewLoyaltySettingsProcessor(&loyaltyRepoFake{orgValues: settings}, txRunnerFake{})) + p.now = func() time.Time { return time.Date(2026, 6, 1, 12, 0, 0, 0, time.UTC) } + return p +} + +func TestWalletQueryProcessor_SummaryShowsWhereEachRowCameFromOrWent(t *testing.T) { + order, payment := uuid.New(), uuid.New() + earnID, payID := uuid.New(), uuid.New() + soon := time.Date(2026, 7, 1, 0, 0, 0, 0, time.UTC) + later := time.Date(2026, 9, 1, 0, 0, 0, 0, time.UTC) + created := time.Date(2026, 5, 1, 0, 0, 0, 0, time.UTC) + repo := &walletQueryRepoFake{ + org: uuid.New(), + spendable: map[string]int64{constants.WalletCurrencyPoint: 250, constants.WalletCurrencyCoin: 8}, + expiring: []repository.WalletExpiringAmount{ + {Currency: constants.WalletCurrencyPoint, Date: "2026-07-01", Amount: 100}, + }, + transactions: []entities.WalletTransaction{ + {ID: payID, Currency: constants.WalletCurrencyPoint, Type: constants.WalletTxTypePayment, Amount: -50, BalanceAfter: 250, + ReferenceType: constants.WalletRefTypePayment, ReferenceID: payment, Description: "Bayar #ORD-1", CreatedAt: created.Add(time.Hour), + CounterpartyCustomerID: ptr(uuid.New()), Metadata: entities.Metadata{"point_value": 100}}, + {ID: earnID, Currency: constants.WalletCurrencyPoint, Type: constants.WalletTxTypeEarn, Amount: 300, BalanceAfter: 300, + ReferenceType: constants.WalletRefTypeOrder, ReferenceID: order, Description: "Belanja #ORD-1", CreatedAt: created}, + }, + lots: []entities.WalletLot{ + {SourceTransactionID: earnID, OriginalAmount: 200, RemainingAmount: 150, ExpiresAt: &later}, + {SourceTransactionID: earnID, OriginalAmount: 100, RemainingAmount: 100, ExpiresAt: &soon}, + }, + } + p := newWalletQueryTest(repo, orgSettingsFake{constants.LoyaltyPointValueKey: "100"}) + + data, err := p.Summary(context.Background(), uuid.New()) + require.NoError(t, err) + + assert.Equal(t, int64(250), data.PointBalance) + assert.Equal(t, int64(8), data.CoinBalance) + assert.Equal(t, int64(100), data.PointValue) + assert.Equal(t, int64(25000), data.PointDiscountValue) + assert.Equal(t, &models.CustomerWalletExpiring{Amount: 100, Date: "2026-07-01"}, data.NearestExpiring.Point) + assert.Nil(t, data.NearestExpiring.Coin) + + require.Len(t, data.RecentTransactions, 2) + pay, earn := data.RecentTransactions[0], data.RecentTransactions[1] + assert.Equal(t, &models.CustomerWalletTransactionRef{Type: constants.WalletRefTypePayment, ID: payment}, pay.Destination) + assert.Nil(t, pay.Source) + assert.Empty(t, pay.Lots) + assert.Equal(t, &models.CustomerWalletTransactionRef{Type: constants.WalletRefTypeOrder, ID: order}, earn.Source) + assert.Nil(t, earn.Destination) + assert.Equal(t, &soon, earn.ExpiresAt, "earliest expiry among the lots the credit created") + assert.Len(t, earn.Lots, 2) + + // The pre-wallet fields are still filled, from the wallet. + assert.Equal(t, int64(250), data.TotalPoints) + assert.Equal(t, int64(8), data.TotalTokens) + require.Len(t, data.PointsHistory, 2) + assert.Equal(t, int64(-50), data.PointsHistory[0].Points) + assert.Equal(t, constants.WalletTxTypePayment, data.PointsHistory[0].Type) + assert.Equal(t, created.Add(time.Hour), data.LastUpdated) +} + +func TestWalletQueryProcessor_PointValueFallsBackToDefault(t *testing.T) { + for name, settings := range map[string]orgSettingsFake{ + "not set": {}, + "garbage": {constants.LoyaltyPointValueKey: "abc"}, + "zero": {constants.LoyaltyPointValueKey: "0"}, + "negative": {constants.LoyaltyPointValueKey: "-5"}, + } { + t.Run(name, func(t *testing.T) { + repo := &walletQueryRepoFake{org: uuid.New(), spendable: map[string]int64{constants.WalletCurrencyPoint: 40}} + data, err := newWalletQueryTest(repo, settings).Summary(context.Background(), uuid.New()) + require.NoError(t, err) + assert.Equal(t, constants.LoyaltyPointValueDefault, data.PointValue) + assert.Equal(t, int64(40), data.PointDiscountValue) + }) + } +} + +func TestWalletQueryProcessor_SummaryForCustomerWithoutWallet(t *testing.T) { + repo := &walletQueryRepoFake{org: uuid.New(), spendable: map[string]int64{}} + data, err := newWalletQueryTest(repo, orgSettingsFake{}).Summary(context.Background(), uuid.New()) + require.NoError(t, err) + assert.Zero(t, data.PointBalance) + assert.Zero(t, data.CoinBalance) + assert.NotNil(t, data.RecentTransactions, "an empty list, not null, for the app") + + _, err = newWalletQueryTest(&walletQueryRepoFake{}, orgSettingsFake{}).Summary(context.Background(), uuid.New()) + assert.ErrorIs(t, err, repository.ErrWalletNotFound) +} + +func TestWalletQueryProcessor_LegacyEndpointsSplitByCurrency(t *testing.T) { + repo := &walletQueryRepoFake{ + org: uuid.New(), + spendable: map[string]int64{constants.WalletCurrencyPoint: 100, constants.WalletCurrencyCoin: 8}, + transactions: []entities.WalletTransaction{ + {ID: uuid.New(), Currency: constants.WalletCurrencyCoin, Type: constants.WalletTxTypeMigration, Amount: 8}, + {ID: uuid.New(), Currency: constants.WalletCurrencyPoint, Type: constants.WalletTxTypeMigration, Amount: 100}, + }, + } + p := newWalletQueryTest(repo, orgSettingsFake{}) + + points, err := p.LegacyPoints(context.Background(), uuid.New()) + require.NoError(t, err) + assert.Equal(t, int64(100), points.TotalPoints) + require.Len(t, points.PointsHistory, 1) + assert.Equal(t, int64(100), points.PointsHistory[0].Points) + + tokens, err := p.LegacyTokens(context.Background(), uuid.New()) + require.NoError(t, err) + assert.Equal(t, int64(8), tokens.TotalTokens) + require.Len(t, tokens.TokensHistory, 1) + assert.Equal(t, int64(8), tokens.TokensHistory[0].Tokens) +} + +func TestWalletQueryProcessor_TransactionsQuery(t *testing.T) { + customer := uuid.New() + jakarta := walletDisplayLocation + + repo := &walletQueryRepoFake{org: uuid.New(), total: 45} + page, err := newWalletQueryTest(repo, orgSettingsFake{}).Transactions(context.Background(), customer, models.ListCustomerWalletTransactionsQuery{ + Page: 3, Limit: 10, Currency: "point", Type: "earn, PAYMENT", From: "2026-05-01", To: "2026-05-31", + }) + require.NoError(t, err) + assert.Equal(t, models.Pagination{Page: 3, Limit: 10, Total: 45, TotalPages: 5}, page.Pagination) + assert.NotNil(t, page.Data) + + f := repo.filters[0] + assert.Equal(t, customer, f.CustomerID) + assert.Equal(t, 20, f.Offset) + assert.Equal(t, 10, f.Limit) + assert.Equal(t, constants.WalletCurrencyPoint, f.Currency) + assert.Equal(t, []string{constants.WalletTxTypeEarn, constants.WalletTxTypePayment}, f.Types) + assert.True(t, f.From.Equal(time.Date(2026, 5, 1, 0, 0, 0, 0, jakarta))) + assert.True(t, f.To.Equal(time.Date(2026, 6, 1, 0, 0, 0, 0, jakarta)), "to covers the whole last day") + + // Defaults. + repo = &walletQueryRepoFake{org: uuid.New()} + page, err = newWalletQueryTest(repo, orgSettingsFake{}).Transactions(context.Background(), customer, models.ListCustomerWalletTransactionsQuery{}) + require.NoError(t, err) + assert.Equal(t, 1, page.Pagination.Page) + assert.Equal(t, walletTransactionsPageLimit, repo.filters[0].Limit) + assert.Zero(t, repo.filters[0].Offset) + assert.Nil(t, repo.filters[0].From) + assert.Empty(t, repo.filters[0].Types) +} + +func TestWalletQueryProcessor_RejectsBadQueries(t *testing.T) { + for name, q := range map[string]models.ListCustomerWalletTransactionsQuery{ + "negative page": {Page: -1}, + "limit too big": {Limit: walletTransactionsMaxLimit + 1}, + "negative limit": {Limit: -1}, + "unknown currency": {Currency: "GOLD"}, + "unknown type": {Type: "EARN,BONUS"}, + "bad from": {From: "01-05-2026"}, + "bad to": {To: "2026-13-01"}, + "from after to": {From: "2026-06-02", To: "2026-06-01"}, + } { + t.Run(name, func(t *testing.T) { + repo := &walletQueryRepoFake{org: uuid.New()} + _, err := newWalletQueryTest(repo, orgSettingsFake{}).Transactions(context.Background(), uuid.New(), q) + assert.ErrorIs(t, err, ErrInvalidWalletQuery) + assert.Empty(t, repo.filters, "nothing is queried") + }) + } + + // A single day is a valid range. + repo := &walletQueryRepoFake{org: uuid.New()} + _, err := newWalletQueryTest(repo, orgSettingsFake{}).Transactions(context.Background(), uuid.New(), + models.ListCustomerWalletTransactionsQuery{From: "2026-06-01", To: "2026-06-01"}) + assert.NoError(t, err) +} + +func (f *walletQueryRepoFake) OrganizationOutstanding(context.Context, uuid.UUID) (int64, int64, error) { + return 0, 0, nil +} + +func (f *walletQueryRepoFake) ExpiringByDay(context.Context, uuid.UUID, time.Time) ([]repository.WalletExpiringAmount, error) { + return f.expiring, nil +} + +func TestWalletQueryProcessor_ExpiringGroupsByCurrencyAndDay(t *testing.T) { + repo := &walletQueryRepoFake{org: uuid.New(), expiring: []repository.WalletExpiringAmount{ + {Currency: "POINT", Date: "2026-10-31", Amount: 150}, + {Currency: "COIN", Date: "2026-10-31", Amount: 4}, + {Currency: "POINT", Date: "2026-12-31", Amount: 200}, + }} + got, err := newWalletQueryTest(repo, nil).Expiring(context.Background(), uuid.New()) + require.NoError(t, err) + assert.Equal(t, []models.CustomerWalletExpiring{{Amount: 150, Date: "2026-10-31"}, {Amount: 200, Date: "2026-12-31"}}, got.Point) + assert.Equal(t, []models.CustomerWalletExpiring{{Amount: 4, Date: "2026-10-31"}}, got.Coin) + + empty, err := newWalletQueryTest(&walletQueryRepoFake{org: uuid.New()}, nil).Expiring(context.Background(), uuid.New()) + require.NoError(t, err) + assert.NotNil(t, empty.Point, "an empty list, not null") + assert.NotNil(t, empty.Coin) +} diff --git a/internal/processor/wallet_trace_processor.go b/internal/processor/wallet_trace_processor.go new file mode 100644 index 0000000..dc37e60 --- /dev/null +++ b/internal/processor/wallet_trace_processor.go @@ -0,0 +1,180 @@ +package processor + +import ( + "context" + "time" + + "github.com/google/uuid" + + "apskel-pos-be/internal/entities" + "apskel-pos-be/internal/models" + "apskel-pos-be/internal/repository" +) + +// walletTraceMaxDepth bounds how far back a chain is followed. Every step is a +// transfer, exchange or refund of the step before, so real chains are short; the +// bound only guards against a loop in bad data. +const walletTraceMaxDepth = 100 + +// WalletTraceProcessor traces a ledger row lot by lot for the dashboard +// (docs/prd-point-coin.md F7, §8.1). It only reads. +type WalletTraceProcessor struct { + repo repository.WalletTraceRepository + now func() time.Time +} + +func NewWalletTraceProcessor(repo repository.WalletTraceRepository) *WalletTraceProcessor { + return &WalletTraceProcessor{repo: repo, now: time.Now} +} + +type walletTraceStart struct { + lotID uuid.UUID + amount int64 +} + +// Trace follows a row of the organization's ledger: a debit through the lots it took +// from, a credit through the lots it created, and each lot back through origin_lot_id +// to the lot that first brought the balance in. A row of another organization is +// repository.ErrWalletTransactionNotFound. +func (p *WalletTraceProcessor) Trace(ctx context.Context, organizationID, transactionID uuid.UUID) (*models.AdminWalletTrace, error) { + row, err := p.repo.GetTransaction(ctx, organizationID, transactionID) + if err != nil { + return nil, err + } + + var starts []walletTraceStart + if row.Amount < 0 { + allocations, err := p.repo.ListAllocations(ctx, row.ID) + if err != nil { + return nil, err + } + for _, a := range allocations { + starts = append(starts, walletTraceStart{lotID: a.LotID, amount: a.Amount}) + } + } else { + created, err := p.repo.ListLotsBySource(ctx, row.ID) + if err != nil { + return nil, err + } + for _, lot := range created { + starts = append(starts, walletTraceStart{lotID: lot.ID, amount: lot.OriginalAmount}) + } + } + + lots, err := p.loadChains(ctx, starts) + if err != nil { + return nil, err + } + + sourceIDs := make([]uuid.UUID, 0, len(lots)) + customerIDs := []uuid.UUID{row.CustomerID} + for _, lot := range lots { + sourceIDs = append(sourceIDs, lot.SourceTransactionID) + customerIDs = append(customerIDs, lot.CustomerID) + } + sourceRows, err := p.repo.GetTransactions(ctx, uniqueIDs(sourceIDs)) + if err != nil { + return nil, err + } + sources := make(map[uuid.UUID]entities.WalletTransaction, len(sourceRows)) + for _, s := range sourceRows { + sources[s.ID] = s + } + names, err := p.repo.CustomerNames(ctx, uniqueIDs(customerIDs)) + if err != nil { + return nil, err + } + + now := p.now() + trace := &models.AdminWalletTrace{ + Transaction: walletTraceRow(*row, names), + Lots: make([]models.AdminWalletTraceLot, 0, len(starts)), + } + for _, start := range starts { + item := models.AdminWalletTraceLot{Amount: start.amount, Chain: []models.AdminWalletTraceStep{}} + visited := map[uuid.UUID]bool{} + for id := &start.lotID; id != nil && !visited[*id]; { + lot, ok := lots[*id] + if !ok { + break + } + visited[*id] = true + item.Chain = append(item.Chain, models.AdminWalletTraceStep{ + Lot: adminWalletLot(lot, now), + Source: walletTraceRow(sources[lot.SourceTransactionID], names), + }) + id = lot.OriginLotID + } + trace.Lots = append(trace.Lots, item) + } + return trace, nil +} + +// loadChains loads the starting lots and every lot they were carried over from, one +// generation at a time. +func (p *WalletTraceProcessor) loadChains(ctx context.Context, starts []walletTraceStart) (map[uuid.UUID]entities.WalletLot, error) { + lots := map[uuid.UUID]entities.WalletLot{} + pending := make([]uuid.UUID, 0, len(starts)) + for _, s := range starts { + pending = append(pending, s.lotID) + } + for depth := 0; len(pending) > 0 && depth < walletTraceMaxDepth; depth++ { + found, err := p.repo.GetLots(ctx, uniqueIDs(pending)) + if err != nil { + return nil, err + } + pending = pending[:0] + for _, lot := range found { + lots[lot.ID] = lot + } + for _, lot := range found { + if lot.OriginLotID != nil { + if _, seen := lots[*lot.OriginLotID]; !seen { + pending = append(pending, *lot.OriginLotID) + } + } + } + } + return lots, nil +} + +func walletTraceRow(row entities.WalletTransaction, names map[uuid.UUID]string) models.AdminWalletTraceRow { + return models.AdminWalletTraceRow{ + ID: row.ID, + Customer: models.AdminWalletNamedRef{ID: row.CustomerID, Name: names[row.CustomerID]}, + Currency: row.Currency, + Type: row.Type, + Amount: row.Amount, + Description: row.Description, + ReferenceType: row.ReferenceType, + ReferenceID: row.ReferenceID, + OutletID: row.OutletID, + CreatedAt: row.CreatedAt, + } +} + +func adminWalletLot(lot entities.WalletLot, now time.Time) models.AdminWalletLot { + return models.AdminWalletLot{ + ID: lot.ID, + Currency: lot.Currency, + OriginalAmount: lot.OriginalAmount, + RemainingAmount: lot.RemainingAmount, + ExpiresAt: lot.ExpiresAt, + Expired: lot.ExpiresAt != nil && !lot.ExpiresAt.After(now), + SourceTransactionID: lot.SourceTransactionID, + OriginLotID: lot.OriginLotID, + CreatedAt: lot.CreatedAt, + } +} + +func uniqueIDs(ids []uuid.UUID) []uuid.UUID { + seen := make(map[uuid.UUID]bool, len(ids)) + out := make([]uuid.UUID, 0, len(ids)) + for _, id := range ids { + if !seen[id] { + seen[id] = true + out = append(out, id) + } + } + return out +} diff --git a/internal/processor/wallet_trace_processor_test.go b/internal/processor/wallet_trace_processor_test.go new file mode 100644 index 0000000..2a0aa01 --- /dev/null +++ b/internal/processor/wallet_trace_processor_test.go @@ -0,0 +1,161 @@ +package processor + +import ( + "context" + "testing" + "time" + + "github.com/google/uuid" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "apskel-pos-be/internal/constants" + "apskel-pos-be/internal/entities" + "apskel-pos-be/internal/models" + "apskel-pos-be/internal/repository" +) + +// walletTraceRepoFake reads the fake wallet the way the trace repository reads the +// tables. +type walletTraceRepoFake struct{ e *walletMoveEnv } + +func (f walletTraceRepoFake) GetTransaction(_ context.Context, organizationID, id uuid.UUID) (*entities.WalletTransaction, error) { + for _, tx := range f.e.repo.transactions { + if tx.ID == id && tx.OrganizationID == organizationID { + c := *tx + return &c, nil + } + } + return nil, repository.ErrWalletTransactionNotFound +} + +func (f walletTraceRepoFake) GetTransactions(_ context.Context, ids []uuid.UUID) ([]entities.WalletTransaction, error) { + var out []entities.WalletTransaction + for _, tx := range f.e.repo.transactions { + if containsID(ids, tx.ID) { + out = append(out, *tx) + } + } + return out, nil +} + +func (f walletTraceRepoFake) ListAllocations(ctx context.Context, id uuid.UUID) ([]entities.WalletLotAllocation, error) { + return f.e.repo.ListAllocationsByTransaction(ctx, id) +} + +func (f walletTraceRepoFake) ListLotsBySource(ctx context.Context, id uuid.UUID) ([]entities.WalletLot, error) { + return f.e.repo.ListLotsBySourceTransaction(ctx, id) +} + +func (f walletTraceRepoFake) GetLots(ctx context.Context, ids []uuid.UUID) ([]entities.WalletLot, error) { + return f.e.repo.GetLotsByIDs(ctx, ids) +} + +func (f walletTraceRepoFake) CustomerNames(_ context.Context, ids []uuid.UUID) (map[uuid.UUID]string, error) { + names := map[uuid.UUID]string{} + for _, id := range ids { + if c, ok := f.e.customers.byID[id]; ok { + names[id] = c.Name + } + } + return names, nil +} + +func containsID(ids []uuid.UUID, id uuid.UUID) bool { + for _, v := range ids { + if v == id { + return true + } + } + return false +} + +func findRow(t *testing.T, e *walletMoveEnv, customerID uuid.UUID, txType string) *entities.WalletTransaction { + t.Helper() + for _, tx := range e.repo.transactions { + if tx.CustomerID == customerID && tx.Type == txType { + return tx + } + } + t.Fatalf("no %s row for %s", txType, customerID) + return nil +} + +// The example of §8: A has 100 from #ORD-1 and 50 from #ORD-2, sends 120 to B, and B +// pays 30. Tracing B's payment leads to A's order #ORD-1. +func TestWalletTrace_PaymentLeadsBackToTheSendersOrder(t *testing.T) { + e := newWalletMoveEnv(t) + a := e.member("Anita", "081200005678") + b := e.member("Budi Santoso", "081234561234") + ord1 := earn(a, 100, e.at(30*24*time.Hour)) + ord1.Description = "Belanja #ORD-1" + ord2 := earn(a, 50, e.at(60*24*time.Hour)) + ord2.Description = "Belanja #ORD-2" + e.credit(t, ord1) + e.credit(t, ord2) + _, err := e.transfers(nil).Transfer(e.ctx, a, sendPoints(120, "081234561234"), "482913", "key-1", models.CustomerPinRequestInfo{}) + require.NoError(t, err) + payment, err := e.p.Debit(e.ctx, pay(b, 30)) + require.NoError(t, err) + + p := NewWalletTraceProcessor(walletTraceRepoFake{e}) + trace, err := p.Trace(e.ctx, e.org, payment.Transaction.ID) + require.NoError(t, err) + + assert.Equal(t, constants.WalletTxTypePayment, trace.Transaction.Type) + assert.Equal(t, "Budi Santoso", trace.Transaction.Customer.Name) + require.Len(t, trace.Lots, 1) + assert.Equal(t, int64(30), trace.Lots[0].Amount) + chain := trace.Lots[0].Chain + require.Len(t, chain, 2) + assert.Equal(t, constants.WalletTxTypeTransferIn, chain[0].Source.Type) + assert.Equal(t, b, chain[0].Source.Customer.ID) + assert.Equal(t, constants.WalletTxTypeEarn, chain[1].Source.Type) + assert.Equal(t, "Anita", chain[1].Source.Customer.Name) + assert.Equal(t, "Belanja #ORD-1", chain[1].Source.Description) + assert.Equal(t, constants.WalletRefTypeOrder, chain[1].Source.ReferenceType) + assert.Equal(t, ord1.ReferenceID, chain[1].Source.ReferenceID) + assert.Nil(t, chain[1].Lot.OriginLotID, "the chain ends at the lot the order created") + assert.Equal(t, *chain[0].Lot.OriginLotID, chain[1].Lot.ID) +} + +func TestWalletTrace_DebitAndCreditOfATransfer(t *testing.T) { + e := newWalletMoveEnv(t) + a := e.member("Anita", "081200005678") + b := e.member("Budi", "081234561234") + e.credit(t, earn(a, 100, e.at(time.Hour))) + e.credit(t, earn(a, 50, nil)) + _, err := e.transfers(nil).Transfer(e.ctx, a, sendPoints(120, "081234561234"), "482913", "key-1", models.CustomerPinRequestInfo{}) + require.NoError(t, err) + p := NewWalletTraceProcessor(walletTraceRepoFake{e}) + + // The sending side took from both of A's lots, which were A's own earnings. + out, err := p.Trace(e.ctx, e.org, findRow(t, e, a, constants.WalletTxTypeTransferOut).ID) + require.NoError(t, err) + require.Len(t, out.Lots, 2) + assert.Equal(t, []int64{100, 20}, []int64{out.Lots[0].Amount, out.Lots[1].Amount}) + for _, lot := range out.Lots { + require.Len(t, lot.Chain, 1) + assert.Equal(t, constants.WalletTxTypeEarn, lot.Chain[0].Source.Type) + } + + // The receiving side created two lots, each carried over from one of A's. + in, err := p.Trace(e.ctx, e.org, findRow(t, e, b, constants.WalletTxTypeTransferIn).ID) + require.NoError(t, err) + require.Len(t, in.Lots, 2) + for _, lot := range in.Lots { + require.Len(t, lot.Chain, 2) + assert.Equal(t, b, lot.Chain[0].Source.Customer.ID) + assert.Equal(t, a, lot.Chain[1].Source.Customer.ID) + assert.Equal(t, lot.Chain[1].Lot.ExpiresAt, lot.Chain[0].Lot.ExpiresAt) + } +} + +func TestWalletTrace_OtherOrganizationsRowsAreNotFound(t *testing.T) { + e := newWalletMoveEnv(t) + a := e.member("Anita", "081200005678") + res := e.credit(t, earn(a, 10, nil)) + + _, err := NewWalletTraceProcessor(walletTraceRepoFake{e}).Trace(e.ctx, uuid.New(), res.Transaction.ID) + assert.ErrorIs(t, err, repository.ErrWalletTransactionNotFound) +} diff --git a/internal/processor/wallet_transfer_processor.go b/internal/processor/wallet_transfer_processor.go new file mode 100644 index 0000000..6c2d7c1 --- /dev/null +++ b/internal/processor/wallet_transfer_processor.go @@ -0,0 +1,307 @@ +package processor + +import ( + "context" + "errors" + "fmt" + "strconv" + "strings" + "time" + "unicode/utf8" + + "github.com/google/uuid" + + "apskel-pos-be/internal/constants" + "apskel-pos-be/internal/logger" + "apskel-pos-be/internal/models" + "apskel-pos-be/internal/repository" +) + +// ErrWalletRecipientNotFound means no customer of the sender's organization has the +// phone number. A customer of another organization is reported the same way, so the +// check does not reveal who uses the app elsewhere. +var ErrWalletRecipientNotFound = errors.New("no customer of this organization has that phone number") + +// customerNotifier pushes a notification to a customer's app through FCM. +// CustomerDeviceProcessor is one. +type customerNotifier interface { + Notify(ctx context.Context, customerID uuid.UUID, title, body string, data map[string]string) error +} + +// NotificationTypeWalletTransferIn is the data type of the push a transfer recipient +// gets, so the app can open the transaction. +const NotificationTypeWalletTransferIn = "WALLET_TRANSFER_IN" + +// WalletTransferProcessor sends EnakPoint or EnakCoin from one customer to another in +// the same organization (docs/prd-point-coin.md F5). +type WalletTransferProcessor struct { + customers repository.WalletMoveRepository + settings organizationSettingsReader + spendable spendableReader + pins pinVerifier + wallet *WalletProcessor + tx TxRunner + notifier customerNotifier + now func() time.Time +} + +func NewWalletTransferProcessor(customers repository.WalletMoveRepository, settings organizationSettingsReader, spendable spendableReader, pins pinVerifier, wallet *WalletProcessor, tx TxRunner, notifier customerNotifier) *WalletTransferProcessor { + return &WalletTransferProcessor{customers: customers, settings: settings, spendable: spendable, pins: pins, wallet: wallet, tx: tx, notifier: notifier, now: time.Now} +} + +// Recipient is GET /customer/wallet/transfer/recipient: the masked name and number +// of the customer a phone number belongs to, if the sender may send to them. +func (p *WalletTransferProcessor) Recipient(ctx context.Context, senderID uuid.UUID, phoneNumber string) (*models.WalletTransferRecipient, error) { + sender, err := p.customers.GetCustomer(ctx, senderID) + if err != nil { + return nil, err + } + recipient, err := p.recipient(ctx, sender, phoneNumber) + if err != nil { + return nil, err + } + return maskedRecipient(recipient), nil +} + +// Transfer sends in.Amount of in.Currency to the customer with in.RecipientPhone, +// approved by the sender's PIN (K8), and tells the recipient. +// +// Both wallets are locked in customer_id order, so two transfers in opposite +// directions cannot deadlock. TRANSFER_OUT takes from the sender's lots in K9 order, +// and TRANSFER_IN gives the recipient lots with exactly the same expiries, pointing +// back at the sender's lots, so sending a balance back and forth cannot extend it. +// The two rows share a group and name each other's customer. +// +// idempotencyKey is the client's Idempotency-Key: a retry with the same key returns +// the first transfer without moving anything again or counting against the limits. +func (p *WalletTransferProcessor) Transfer(ctx context.Context, senderID uuid.UUID, in models.WalletTransfer, pin, idempotencyKey string, info models.CustomerPinRequestInfo) (*models.WalletTransferResult, error) { + reject := func(format string, args ...any) error { + return fmt.Errorf("%w: %s", ErrWalletMoveRejected, fmt.Sprintf(format, args...)) + } + key, err := walletMoveKey(idempotencyKey) + if err != nil { + return nil, err + } + currency := strings.ToUpper(strings.TrimSpace(in.Currency)) + if !constants.IsValidWalletCurrency(currency) { + return nil, reject("currency must be POINT or COIN") + } + if in.Amount <= 0 { + return nil, reject("the amount must be positive") + } + sender, err := p.customers.GetCustomer(ctx, senderID) + if err != nil { + return nil, err + } + if !sender.IsActive { + return nil, reject("the customer is not active") + } + settings, err := p.settings.Organization(ctx, sender.OrganizationID) + if err != nil { + return nil, err + } + limits := settings.Transfer + switch { + case !limits.Enabled: + return nil, reject("transfers are turned off") + case in.Amount < limits.MinAmount: + return nil, reject("at least %d can be sent at a time", limits.MinAmount) + case limits.MaxPerTransaction != nil && in.Amount > *limits.MaxPerTransaction: + return nil, reject("at most %d can be sent at a time", *limits.MaxPerTransaction) + } + recipient, err := p.recipient(ctx, sender, in.RecipientPhone) + if err != nil { + return nil, err + } + // Everything the request alone can get wrong is refused above, before the PIN, so + // it costs no attempt. The PIN also refuses a transfer held after a PIN reset. + if err := p.pins.VerifyPin(ctx, senderID, pin, PinActionTransfer, info); err != nil { + return nil, err + } + + to, from := maskedRecipient(recipient), maskedRecipient(sender) + outKey := fmt.Sprintf("transfer:%s:%s:out", senderID, key) + inKey := fmt.Sprintf("transfer:%s:%s:in", senderID, key) + result := &models.WalletTransferResult{Currency: currency, Amount: in.Amount, Recipient: *to} + var receivedID uuid.UUID + err = p.tx.WithTransaction(ctx, func(ctx context.Context) error { + if err := p.wallet.LockWallets(ctx, senderID, recipient.ID); err != nil { + return err + } + groupID, outID, inID := uuid.New(), uuid.New(), uuid.New() + previous, err := p.wallet.FindTransaction(ctx, outKey) + if err != nil { + return err + } + if previous != nil { + // A retry: it replays below, so it must not count against the daily limit + // it is already part of. + if previous.CounterpartyCustomerID == nil || *previous.CounterpartyCustomerID != recipient.ID || previous.GroupID == nil { + return ErrWalletIdempotencyConflict + } + outID, inID, groupID = previous.ID, previous.ReferenceID, *previous.GroupID + } else if limits.DailyLimit != nil { + sent, err := p.customers.TransferredOutSince(ctx, senderID, currency, startOfWalletDay(p.now())) + if err != nil { + return err + } + if sent+in.Amount > *limits.DailyLimit { + return reject("at most %d can be sent per day; %d is left today", *limits.DailyLimit, max(*limits.DailyLimit-sent, 0)) + } + } + + out, err := p.wallet.Debit(ctx, WalletDebitInput{WalletEntry: WalletEntry{ + TransactionID: outID, + CustomerID: senderID, + Currency: currency, + Type: constants.WalletTxTypeTransferOut, + Amount: in.Amount, + ReferenceType: constants.WalletRefTypeWalletTx, + ReferenceID: inID, + GroupID: &groupID, + CounterpartyCustomerID: &recipient.ID, + Description: truncateRunes(fmt.Sprintf("Transfer ke %s (%s)", to.Name, to.PhoneNumber), walletDescriptionLimit), + IdempotencyKey: outKey, + }}) + if errors.Is(err, repository.ErrWalletInsufficientBalance) { + return reject("not enough %s", walletCurrencyName(currency)) + } + if err != nil { + return err + } + received, err := p.wallet.Credit(ctx, WalletCreditInput{ + WalletEntry: WalletEntry{ + TransactionID: inID, + CustomerID: recipient.ID, + Currency: currency, + Type: constants.WalletTxTypeTransferIn, + Amount: in.Amount, + ReferenceType: constants.WalletRefTypeWalletTx, + ReferenceID: outID, + GroupID: &groupID, + CounterpartyCustomerID: &senderID, + Description: truncateRunes(fmt.Sprintf("Transfer dari %s (%s)", from.Name, from.PhoneNumber), walletDescriptionLimit), + IdempotencyKey: inKey, + }, + Lots: out.CarryOver(), + }) + if err != nil { + return err + } + result.GroupID = groupID + result.Lots = movedLots(received.Lots) + result.Replayed = out.Replayed + receivedID = received.Transaction.ID + return nil + }) + if err != nil { + return nil, err + } + + if !result.Replayed { + p.tellRecipient(ctx, recipient.ID, from, currency, in.Amount, receivedID, result.GroupID) + } + balances, err := p.spendable.SpendableBalances(ctx, senderID, p.now()) + if err != nil { + return nil, err + } + result.Balance = balances[currency] + return result, nil +} + +// recipient finds who a phone number belongs to and checks the sender may send to +// them: an active customer of the same organization, not the walk-in customer, and +// not the sender. +func (p *WalletTransferProcessor) recipient(ctx context.Context, sender *repository.WalletMoveCustomer, phoneNumber string) (*repository.WalletMoveCustomer, error) { + phoneNumber = strings.TrimSpace(phoneNumber) + if phoneNumber == "" { + return nil, fmt.Errorf("%w: the recipient's phone number is required", ErrWalletMoveRejected) + } + recipient, err := p.customers.FindCustomerByPhone(ctx, phoneNumber) + if errors.Is(err, repository.ErrWalletNotFound) { + return nil, ErrWalletRecipientNotFound + } + if err != nil { + return nil, err + } + switch { + case recipient.OrganizationID != sender.OrganizationID: + return nil, ErrWalletRecipientNotFound + case recipient.ID == sender.ID: + return nil, fmt.Errorf("%w: you cannot send to yourself", ErrWalletMoveRejected) + case recipient.IsDefault || !recipient.IsActive: + return nil, fmt.Errorf("%w: this customer cannot receive transfers", ErrWalletMoveRejected) + } + return recipient, nil +} + +// tellRecipient pushes the transfer to the recipient's app (F5). It is best effort: +// the transfer has already happened, so a failure to send is only logged. +func (p *WalletTransferProcessor) tellRecipient(ctx context.Context, recipientID uuid.UUID, sender *models.WalletTransferRecipient, currency string, amount int64, transactionID, groupID uuid.UUID) { + if p.notifier == nil { + return + } + name := walletCurrencyName(currency) + title := name + " masuk" + body := fmt.Sprintf("Kamu menerima %d %s dari %s (%s).", amount, name, sender.Name, sender.PhoneNumber) + data := map[string]string{ + "type": NotificationTypeWalletTransferIn, + "transaction_id": transactionID.String(), + "group_id": groupID.String(), + "currency": currency, + "amount": strconv.FormatInt(amount, 10), + } + if err := p.notifier.Notify(ctx, recipientID, title, body, data); err != nil { + logger.NonContext.Error(fmt.Sprintf("Could not tell customer %s about a transfer", recipientID), err) + } +} + +func maskedRecipient(c *repository.WalletMoveCustomer) *models.WalletTransferRecipient { + phone := "" + if c.PhoneNumber != nil { + phone = maskPhoneNumber(*c.PhoneNumber) + } + return &models.WalletTransferRecipient{Name: maskName(c.Name), PhoneNumber: phone} +} + +// maskName keeps the first two letters of each word, "Budi Santoso" → "Bu*** Sa***", +// and one letter of a word that short, so the sender can recognise the recipient +// without the app revealing their name (F5, §8.1). +func maskName(name string) string { + words := strings.Fields(name) + if len(words) == 0 { + return "***" + } + for i, w := range words { + keep := 2 + if utf8.RuneCountInString(w) <= 2 { + keep = 1 + } + words[i] = string([]rune(w)[:keep]) + "***" + } + return strings.Join(words, " ") +} + +// maskPhoneNumber keeps the first two and the last four digits: +// "081234561234" → "08**-****-1234". +func maskPhoneNumber(phone string) string { + runes := []rune(strings.TrimSpace(phone)) + if len(runes) < 8 { + return "****" + } + return string(runes[:2]) + "**-****-" + string(runes[len(runes)-4:]) +} + +func walletCurrencyName(currency string) string { + if currency == constants.WalletCurrencyCoin { + return "EnakCoin" + } + return "EnakPoint" +} + +// startOfWalletDay is midnight of t's day in the customer's time zone, where the +// daily transfer limit starts over. +func startOfWalletDay(t time.Time) time.Time { + local := t.In(walletDisplayLocation) + return time.Date(local.Year(), local.Month(), local.Day(), 0, 0, 0, 0, walletDisplayLocation) +} diff --git a/internal/processor/wallet_transfer_processor_test.go b/internal/processor/wallet_transfer_processor_test.go new file mode 100644 index 0000000..090ca88 --- /dev/null +++ b/internal/processor/wallet_transfer_processor_test.go @@ -0,0 +1,243 @@ +package processor + +import ( + "context" + "errors" + "testing" + "time" + + "github.com/google/uuid" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "apskel-pos-be/internal/constants" + "apskel-pos-be/internal/models" + "apskel-pos-be/internal/repository" +) + +type pushFake struct { + title, body string + data map[string]string +} + +// notifierFake records the pushes each customer would get. +type notifierFake struct{ pushes map[uuid.UUID][]pushFake } + +func (f *notifierFake) Notify(_ context.Context, customerID uuid.UUID, title, body string, data map[string]string) error { + if f.pushes == nil { + f.pushes = map[uuid.UUID][]pushFake{} + } + f.pushes[customerID] = append(f.pushes[customerID], pushFake{title: title, body: body, data: data}) + return nil +} + +func sendPoints(amount int64, phone string) models.WalletTransfer { + return models.WalletTransfer{Currency: constants.WalletCurrencyPoint, Amount: amount, RecipientPhone: phone} +} + +func TestWalletTransfer_MovesBalanceWithItsExpiry(t *testing.T) { + e := newWalletMoveEnv(t) + a := e.member("Anita", "081200005678") + b := e.member("Budi Santoso", "081234561234") + dec, jan := e.at(30*24*time.Hour), e.at(60*24*time.Hour) + first := e.credit(t, earn(a, 100, dec)) + second := e.credit(t, earn(a, 50, jan)) + notifier := ¬ifierFake{} + + // The example in §8: A sends 120, 100 from the lot expiring first and 20 from the next. + res, err := e.transfers(notifier).Transfer(e.ctx, a, sendPoints(120, "081234561234"), "482913", "key-1", models.CustomerPinRequestInfo{}) + require.NoError(t, err) + + assert.Equal(t, int64(30), res.Balance) + assert.Equal(t, models.WalletTransferRecipient{Name: "Bu*** Sa***", PhoneNumber: "08**-****-1234"}, res.Recipient) + assert.Equal(t, []models.WalletMovedLot{{Amount: 100, ExpiresAt: dec}, {Amount: 20, ExpiresAt: jan}}, res.Lots) + assert.Equal(t, int64(120), e.balance(t, b)) + assert.Equal(t, []PinAction{PinActionTransfer}, e.pins.actions) + + var bLots []uuid.UUID + for _, lot := range e.repo.lots { + if lot.CustomerID == b { + require.NotNil(t, lot.OriginLotID) + bLots = append(bLots, *lot.OriginLotID) + for _, origin := range e.repo.lots { + if origin.ID == *lot.OriginLotID { + assert.Equal(t, origin.ExpiresAt, lot.ExpiresAt, "the recipient's lot expires exactly when the sender's did") + } + } + } + } + assert.Equal(t, []uuid.UUID{first.Lots[0].ID, second.Lots[0].ID}, bLots) + + out, in := e.repo.transactions[2], e.repo.transactions[3] + assert.Equal(t, constants.WalletTxTypeTransferOut, out.Type) + assert.Equal(t, b, *out.CounterpartyCustomerID) + assert.Equal(t, in.ID, out.ReferenceID) + assert.Equal(t, "Transfer ke Bu*** Sa*** (08**-****-1234)", out.Description) + assert.Equal(t, constants.WalletTxTypeTransferIn, in.Type) + assert.Equal(t, a, *in.CounterpartyCustomerID) + assert.Equal(t, out.ID, in.ReferenceID) + assert.Equal(t, *out.GroupID, *in.GroupID) + assert.Equal(t, "Transfer dari An*** (08**-****-5678)", in.Description) + assert.GreaterOrEqual(t, e.repo.locks[a], 1) + assert.GreaterOrEqual(t, e.repo.locks[b], 1) + + assert.Equal(t, []pushFake{{ + title: "EnakPoint masuk", + body: "Kamu menerima 120 EnakPoint dari An*** (08**-****-5678).", + data: map[string]string{ + "type": NotificationTypeWalletTransferIn, + "transaction_id": in.ID.String(), + "group_id": in.GroupID.String(), + "currency": constants.WalletCurrencyPoint, + "amount": "120", + }, + }}, notifier.pushes[b]) + assert.Empty(t, notifier.pushes[a], "the sender gets no push") +} + +func TestWalletTransfer_Coins(t *testing.T) { + e := newWalletMoveEnv(t) + a := e.member("Anita", "081200005678") + b := e.member("Budi", "081234561234") + e.earnCoins(t, a, 10, nil) + + _, err := e.transfers(nil).Transfer(e.ctx, a, models.WalletTransfer{Currency: "coin", Amount: 4, RecipientPhone: "081234561234"}, "482913", "key-1", models.CustomerPinRequestInfo{}) + require.NoError(t, err) + assert.Equal(t, int64(6), e.coinBalance(t, a)) + assert.Equal(t, int64(4), e.coinBalance(t, b)) +} + +func TestWalletTransfer_RefusesRecipientsItMayNotSendTo(t *testing.T) { + e := newWalletMoveEnv(t) + a := e.member("Anita", "081200005678") + e.credit(t, earn(a, 100, nil)) + + walkIn := e.member("Walk-in", "081100000000") + e.customers.byID[walkIn].IsDefault = true + inactive := e.member("Old", "081100000001") + e.customers.byID[inactive].IsActive = false + elsewhere := e.member("Other Org", "081100000002") + e.customers.byID[elsewhere].OrganizationID = uuid.New() + + for phone, want := range map[string]error{ + "081200005678": ErrWalletMoveRejected, // herself + "081100000000": ErrWalletMoveRejected, // the walk-in customer + "081100000001": ErrWalletMoveRejected, // inactive + "081100000002": ErrWalletRecipientNotFound, // another organization looks like nobody + "081999999999": ErrWalletRecipientNotFound, + "": ErrWalletMoveRejected, + } { + _, err := e.transfers(nil).Recipient(e.ctx, a, phone) + assert.ErrorIs(t, err, want, phone) + _, err = e.transfers(nil).Transfer(e.ctx, a, sendPoints(10, phone), "482913", "key-"+phone, models.CustomerPinRequestInfo{}) + assert.ErrorIs(t, err, want, phone) + } + assert.Empty(t, e.pins.actions, "refused before the PIN") + assert.Equal(t, int64(100), e.balance(t, a)) +} + +func TestWalletTransfer_RecipientIsMasked(t *testing.T) { + e := newWalletMoveEnv(t) + a := e.member("Anita", "081200005678") + e.member("Budi Santoso", "081234561234") + + got, err := e.transfers(nil).Recipient(e.ctx, a, " 081234561234 ") + require.NoError(t, err) + assert.Equal(t, &models.WalletTransferRecipient{Name: "Bu*** Sa***", PhoneNumber: "08**-****-1234"}, got) +} + +func TestWalletTransfer_OrganizationLimits(t *testing.T) { + e := newWalletMoveEnv(t) + a := e.member("Anita", "081200005678") + e.member("Budi", "081234561234") + e.credit(t, earn(a, 1000, nil)) + e.settings.Transfer = models.LoyaltyTransferSettings{Enabled: true, MinAmount: 10, MaxPerTransaction: ptr(int64(300)), DailyLimit: ptr(int64(500))} + send := func(amount int64, key string) error { + _, err := e.transfers(nil).Transfer(e.ctx, a, sendPoints(amount, "081234561234"), "482913", key, models.CustomerPinRequestInfo{}) + return err + } + + assert.ErrorIs(t, send(9, "below-min"), ErrWalletMoveRejected) + assert.ErrorIs(t, send(301, "above-max"), ErrWalletMoveRejected) + require.NoError(t, send(300, "k1")) + require.NoError(t, send(200, "k2")) + // The daily limit is used up; a retry of a transfer already made still replays. + assert.ErrorIs(t, send(10, "k3"), ErrWalletMoveRejected) + require.NoError(t, send(200, "k2")) + + // It starts over the next day in the customer's time zone. + e.now = startOfWalletDay(e.now).AddDate(0, 0, 1).Add(time.Minute) + e.repo.clock = e.now + require.NoError(t, send(10, "k4")) + assert.Equal(t, int64(490), e.balance(t, a)) + + e.settings.Transfer.Enabled = false + assert.ErrorIs(t, send(10, "k5"), ErrWalletMoveRejected) +} + +func TestWalletTransfer_HeldAfterPinReset(t *testing.T) { + e := newWalletMoveEnv(t) + a := e.member("Anita", "081200005678") + e.member("Budi", "081234561234") + e.credit(t, earn(a, 100, nil)) + until := e.now.Add(time.Hour) + e.pins.err = &PinError{Code: PinErrTransferBlocked, Until: &until} + + _, err := e.transfers(nil).Transfer(e.ctx, a, sendPoints(10, "081234561234"), "482913", "key-1", models.CustomerPinRequestInfo{}) + var pinErr *PinError + require.True(t, errors.As(err, &pinErr)) + assert.Equal(t, PinErrTransferBlocked, pinErr.Code) + assert.Equal(t, int64(100), e.balance(t, a)) +} + +func TestWalletTransfer_NotEnoughBalance(t *testing.T) { + e := newWalletMoveEnv(t) + a := e.member("Anita", "081200005678") + b := e.member("Budi", "081234561234") + e.credit(t, earn(a, 100, nil)) + // An expired lot cannot be sent even before the expiry job takes it. + e.credit(t, earn(a, 50, e.at(-time.Hour))) + + _, err := e.transfers(nil).Transfer(e.ctx, a, sendPoints(120, "081234561234"), "482913", "key-1", models.CustomerPinRequestInfo{}) + assert.ErrorIs(t, err, ErrWalletMoveRejected) + assert.Equal(t, int64(0), e.balance(t, b)) +} + +func TestWalletTransfer_RetryMovesNothingAndTellsNobodyAgain(t *testing.T) { + e := newWalletMoveEnv(t) + a := e.member("Anita", "081200005678") + b := e.member("Budi", "081234561234") + e.member("Citra", "081255550000") + e.credit(t, earn(a, 100, nil)) + notifier := ¬ifierFake{} + + first, err := e.transfers(notifier).Transfer(e.ctx, a, sendPoints(40, "081234561234"), "482913", "key-1", models.CustomerPinRequestInfo{}) + require.NoError(t, err) + again, err := e.transfers(notifier).Transfer(e.ctx, a, sendPoints(40, "081234561234"), "482913", "key-1", models.CustomerPinRequestInfo{}) + require.NoError(t, err) + + assert.True(t, again.Replayed) + assert.Equal(t, first.GroupID, again.GroupID) + assert.Equal(t, int64(40), e.balance(t, b)) + assert.Len(t, notifier.pushes[b], 1) + + // The same key to someone else is not a retry. + _, err = e.transfers(notifier).Transfer(e.ctx, a, sendPoints(40, "081255550000"), "482913", "key-1", models.CustomerPinRequestInfo{}) + assert.ErrorIs(t, err, ErrWalletIdempotencyConflict) +} + +func TestWalletTransfer_UnknownSender(t *testing.T) { + e := newWalletMoveEnv(t) + _, err := e.transfers(nil).Transfer(e.ctx, uuid.New(), sendPoints(1, "081234561234"), "482913", "key-1", models.CustomerPinRequestInfo{}) + assert.ErrorIs(t, err, repository.ErrWalletNotFound) +} + +func TestMaskName(t *testing.T) { + assert.Equal(t, "Bu*** Sa***", maskName("Budi Santoso")) + assert.Equal(t, "An***", maskName("Anita")) + assert.Equal(t, "A*** Ra***", maskName("Al Rahman")) + assert.Equal(t, "***", maskName(" ")) + assert.Equal(t, "08**-****-1234", maskPhoneNumber("081234561234")) + assert.Equal(t, "+6**-****-1234", maskPhoneNumber("+6281234561234")) + assert.Equal(t, "****", maskPhoneNumber("12345")) +} diff --git a/internal/repository/analytics_repository.go b/internal/repository/analytics_repository.go index 1696973..a4fddcb 100644 --- a/internal/repository/analytics_repository.go +++ b/internal/repository/analytics_repository.go @@ -99,7 +99,8 @@ func (r *AnalyticsRepositoryImpl) GetPaymentMethodAnalytics(ctx context.Context, pm.type as payment_method_type, COALESCE(SUM(p.amount), 0) as total_amount, COUNT(DISTINCT p.order_id) as order_count, - COUNT(p.id) as payment_count + COUNT(p.id) as payment_count, + COALESCE(SUM(p.points_used), 0) as points_used `). Joins("JOIN payment_methods pm ON p.payment_method_id = pm.id"). Joins("JOIN orders o ON p.order_id = o.id"). @@ -478,7 +479,7 @@ func (r *AnalyticsRepositoryImpl) GetProductAnalytics(ctx context.Context, organ COALESCE(SUM(oi.weight), 0) as weight_sold, COALESCE(SUM(oi.total_price), 0) as revenue, CASE - WHEN SUM(` + billableQty + `) > 0 THEN COALESCE(SUM(oi.total_price), 0) / SUM(` + billableQty + `) + WHEN SUM(`+billableQty+`) > 0 THEN COALESCE(SUM(oi.total_price), 0) / SUM(`+billableQty+`) ELSE 0 END as average_price, COUNT(DISTINCT oi.order_id) as order_count, @@ -493,14 +494,14 @@ func (r *AnalyticsRepositoryImpl) GetProductAnalytics(ctx context.Context, organ FROM product_recipes pr JOIN ingredients i ON pr.ingredient_id = i.id WHERE pr.product_id = p.id - ), p.cost, 0) * COALESCE(SUM(` + billableQty + `), 0) as standard_hpp_total, + ), p.cost, 0) * COALESCE(SUM(`+billableQty+`), 0) as standard_hpp_total, CASE - WHEN SUM(` + billableQty + `) > 0 THEN COALESCE(SUM(oi.total_cost), 0) / SUM(` + billableQty + `) + WHEN SUM(`+billableQty+`) > 0 THEN COALESCE(SUM(oi.total_cost), 0) / SUM(`+billableQty+`) ELSE 0 END as fifo_hpp_per_unit, COALESCE(SUM(oi.total_cost), 0) as fifo_hpp_total, COALESCE(mahpp.hpp_per_unit, p.cost, 0) as moving_average_hpp_per_unit, - COALESCE(mahpp.hpp_per_unit, p.cost, 0) * COALESCE(SUM(` + billableQty + `), 0) as moving_average_hpp_total + COALESCE(mahpp.hpp_per_unit, p.cost, 0) * COALESCE(SUM(`+billableQty+`), 0) as moving_average_hpp_total `). Joins("JOIN products p ON oi.product_id = p.id"). Joins("JOIN categories c ON p.category_id = c.id"). @@ -551,9 +552,9 @@ func (r *AnalyticsRepositoryImpl) GetProductAnalyticsPerCategory(ctx context.Con 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 p.id) as product_count, COUNT(DISTINCT oi.order_id) as order_count, - COALESCE(SUM(CASE WHEN oi.is_fully_refunded = false THEN COALESCE(shpp.hpp_per_unit, p.cost, 0) * ` + billableQtyNet + ` ELSE 0 END), 0) as total_standard_hpp, + COALESCE(SUM(CASE WHEN oi.is_fully_refunded = false THEN COALESCE(shpp.hpp_per_unit, p.cost, 0) * `+billableQtyNet+` ELSE 0 END), 0) as total_standard_hpp, COALESCE(SUM(CASE WHEN oi.is_fully_refunded = false THEN oi.total_cost * ((oi.quantity - COALESCE(oi.refund_quantity, 0))::float / NULLIF(oi.quantity, 0)) ELSE 0 END), 0) as total_fifo_hpp, - COALESCE(SUM(CASE WHEN oi.is_fully_refunded = false THEN COALESCE(mahpp.hpp_per_unit, p.cost, 0) * ` + billableQtyNet + ` ELSE 0 END), 0) as total_moving_average_hpp + COALESCE(SUM(CASE WHEN oi.is_fully_refunded = false THEN COALESCE(mahpp.hpp_per_unit, p.cost, 0) * `+billableQtyNet+` ELSE 0 END), 0) as total_moving_average_hpp `). Joins("JOIN products p ON oi.product_id = p.id"). Joins("JOIN categories c ON p.category_id = c.id"). @@ -604,9 +605,9 @@ func (r *AnalyticsRepositoryImpl) GetProductAnalyticsPerParentCategory(ctx conte COUNT(DISTINCT c.id) as category_count, COUNT(DISTINCT p.id) as product_count, COUNT(DISTINCT oi.order_id) as order_count, - COALESCE(SUM(CASE WHEN oi.is_fully_refunded = false THEN COALESCE(shpp.hpp_per_unit, p.cost, 0) * ` + billableQtyNet + ` ELSE 0 END), 0) as total_standard_hpp, + COALESCE(SUM(CASE WHEN oi.is_fully_refunded = false THEN COALESCE(shpp.hpp_per_unit, p.cost, 0) * `+billableQtyNet+` ELSE 0 END), 0) as total_standard_hpp, COALESCE(SUM(CASE WHEN oi.is_fully_refunded = false THEN oi.total_cost * ((oi.quantity - COALESCE(oi.refund_quantity, 0))::float / NULLIF(oi.quantity, 0)) ELSE 0 END), 0) as total_fifo_hpp, - COALESCE(SUM(CASE WHEN oi.is_fully_refunded = false THEN COALESCE(mahpp.hpp_per_unit, p.cost, 0) * ` + billableQtyNet + ` ELSE 0 END), 0) as total_moving_average_hpp + COALESCE(SUM(CASE WHEN oi.is_fully_refunded = false THEN COALESCE(mahpp.hpp_per_unit, p.cost, 0) * `+billableQtyNet+` ELSE 0 END), 0) as total_moving_average_hpp `). Joins("JOIN products p ON oi.product_id = p.id"). Joins("JOIN categories c ON p.category_id = c.id"). diff --git a/internal/repository/customer_device_repository.go b/internal/repository/customer_device_repository.go new file mode 100644 index 0000000..5c38807 --- /dev/null +++ b/internal/repository/customer_device_repository.go @@ -0,0 +1,84 @@ +package repository + +import ( + "context" + "fmt" + "time" + + "github.com/google/uuid" + "gorm.io/gorm" +) + +// CustomerDevice is one install of the customer app that can receive push +// notifications. +type CustomerDevice struct { + CustomerID uuid.UUID + DeviceID string + Platform *string + FCMToken string + AppVersion *string +} + +// CustomerDeviceRepository keeps the FCM tokens of the customer app. +type CustomerDeviceRepository interface { + // Register saves the device's current token. A token is only ever one customer's: + // registering it takes it away from whoever had it before on that phone, so they + // stop getting this customer's notifications. + Register(ctx context.Context, device CustomerDevice, now time.Time) error + // Unregister forgets a device, for instance on logout. An unknown device is not an error. + Unregister(ctx context.Context, customerID uuid.UUID, deviceID string) error + ListTokens(ctx context.Context, customerID uuid.UUID) ([]string, error) +} + +type customerDeviceRepository struct { + db *gorm.DB +} + +func NewCustomerDeviceRepository(db *gorm.DB) CustomerDeviceRepository { + return &customerDeviceRepository{db: db} +} + +func (r *customerDeviceRepository) Register(ctx context.Context, d CustomerDevice, now time.Time) error { + return DBFromContext(ctx, r.db).WithContext(ctx).Transaction(func(tx *gorm.DB) error { + err := tx.Exec(`DELETE FROM customer_devices WHERE fcm_token = ? AND NOT (customer_id = ? AND device_id = ?)`, + d.FCMToken, d.CustomerID, d.DeviceID).Error + if err != nil { + return fmt.Errorf("failed to release FCM token: %w", err) + } + err = tx.Exec(`INSERT INTO customer_devices (customer_id, device_id, platform, fcm_token, app_version, last_active_at) + VALUES (?, ?, ?, ?, ?, ?) + ON CONFLICT (customer_id, device_id) DO UPDATE SET + platform = EXCLUDED.platform, + fcm_token = EXCLUDED.fcm_token, + app_version = EXCLUDED.app_version, + last_active_at = EXCLUDED.last_active_at, + updated_at = NOW()`, + d.CustomerID, d.DeviceID, d.Platform, d.FCMToken, d.AppVersion, now).Error + if err != nil { + return fmt.Errorf("failed to register customer device: %w", err) + } + return nil + }) +} + +func (r *customerDeviceRepository) Unregister(ctx context.Context, customerID uuid.UUID, deviceID string) error { + err := DBFromContext(ctx, r.db).WithContext(ctx). + Exec(`DELETE FROM customer_devices WHERE customer_id = ? AND device_id = ?`, customerID, deviceID).Error + if err != nil { + return fmt.Errorf("failed to unregister customer device: %w", err) + } + return nil +} + +func (r *customerDeviceRepository) ListTokens(ctx context.Context, customerID uuid.UUID) ([]string, error) { + var tokens []string + err := DBFromContext(ctx, r.db).WithContext(ctx). + Table("customer_devices"). + Where("customer_id = ? AND fcm_token <> ''", customerID). + Order("last_active_at DESC NULLS LAST"). + Pluck("fcm_token", &tokens).Error + if err != nil { + return nil, fmt.Errorf("failed to list customer FCM tokens: %w", err) + } + return tokens, nil +} diff --git a/internal/repository/customer_pin_repository.go b/internal/repository/customer_pin_repository.go new file mode 100644 index 0000000..6c38ab3 --- /dev/null +++ b/internal/repository/customer_pin_repository.go @@ -0,0 +1,220 @@ +package repository + +import ( + "context" + "errors" + "fmt" + "time" + + "github.com/google/uuid" + "gorm.io/gorm" +) + +// ErrPinCustomerNotFound means the customer does not exist. +var ErrPinCustomerNotFound = errors.New("pin: customer not found") + +// CustomerPinState is a customer's PIN and what guards it. It lives in the customers +// table but is read and written only here, never through the Customer entity, so the +// hash cannot end up in a customer response. +type CustomerPinState struct { + CustomerID uuid.UUID + OrganizationID uuid.UUID + PhoneNumber *string + BirthDate *time.Time + PinHash *string + PinSetAt *time.Time + FailedAttempts int + LockedUntil *time.Time + TransferBlockedUntil *time.Time +} + +// CustomerSecurityEvent is one row of the PIN security log. +type CustomerSecurityEvent struct { + ID uuid.UUID + CustomerID uuid.UUID + Event string + ActorUser *uuid.UUID + Reason *string + IPAddress *string + UserAgent *string + CreatedAt time.Time +} + +// CustomerPinRepository stores customer PINs and their security log +// (docs/prd-point-coin.md F11). +type CustomerPinRepository interface { + GetState(ctx context.Context, customerID uuid.UUID) (*CustomerPinState, error) + // SetPin stores a new PIN hash, clears the failure counter and any lock, and sets + // or clears the transfer hold. + SetPin(ctx context.Context, customerID uuid.UUID, hash string, transferBlockedUntil *time.Time) error + // RemovePin deletes the PIN, so the customer has to create a new one through OTP. + RemovePin(ctx context.Context, customerID uuid.UUID) error + // RecordFailure adds one wrong attempt in a single statement, so wrong attempts + // made at the same time all count. A lock that has already run out starts the + // count again. When the count reaches maxAttempts the PIN is locked until + // lockUntil. It returns the count and lock after the update. + RecordFailure(ctx context.Context, customerID uuid.UUID, maxAttempts int, now, lockUntil time.Time) (int, *time.Time, error) + ClearFailures(ctx context.Context, customerID uuid.UUID) error + + InsertEvent(ctx context.Context, event CustomerSecurityEvent) error + // ListEvents returns a page of the customer's log, newest first, and the total. + ListEvents(ctx context.Context, customerID uuid.UUID, offset, limit int) ([]CustomerSecurityEvent, int64, error) +} + +type customerPinRepository struct { + db *gorm.DB +} + +func NewCustomerPinRepository(db *gorm.DB) CustomerPinRepository { + return &customerPinRepository{db: db} +} + +func (r *customerPinRepository) GetState(ctx context.Context, customerID uuid.UUID) (*CustomerPinState, error) { + var rows []struct { + CustomerID string + OrganizationID string + PhoneNumber *string + BirthDate *time.Time + PinHash *string + PinSetAt *time.Time + PinFailedAttempts int + PinLockedUntil *time.Time + TransferBlockedUntil *time.Time + } + err := DBFromContext(ctx, r.db).WithContext(ctx).Raw(` + SELECT id::text AS customer_id, organization_id::text AS organization_id, + COALESCE(phone_number, phone) AS phone_number, birth_date, + pin_hash, pin_set_at, pin_failed_attempts, pin_locked_until, transfer_blocked_until + FROM customers WHERE id = ? LIMIT 1`, customerID).Scan(&rows).Error + if err != nil { + return nil, fmt.Errorf("failed to read customer PIN: %w", err) + } + if len(rows) == 0 { + return nil, ErrPinCustomerNotFound + } + row := rows[0] + state := &CustomerPinState{ + PhoneNumber: row.PhoneNumber, + BirthDate: row.BirthDate, + PinHash: row.PinHash, + PinSetAt: row.PinSetAt, + FailedAttempts: row.PinFailedAttempts, + LockedUntil: row.PinLockedUntil, + TransferBlockedUntil: row.TransferBlockedUntil, + } + state.CustomerID, _ = uuid.Parse(row.CustomerID) + state.OrganizationID, _ = uuid.Parse(row.OrganizationID) + return state, nil +} + +func (r *customerPinRepository) SetPin(ctx context.Context, customerID uuid.UUID, hash string, transferBlockedUntil *time.Time) error { + result := DBFromContext(ctx, r.db).WithContext(ctx).Exec(` + UPDATE customers SET pin_hash = ?, pin_set_at = NOW(), pin_failed_attempts = 0, + pin_locked_until = NULL, transfer_blocked_until = ?, updated_at = NOW() + WHERE id = ?`, hash, transferBlockedUntil, customerID) + if result.Error != nil { + return fmt.Errorf("failed to store customer PIN: %w", result.Error) + } + if result.RowsAffected == 0 { + return ErrPinCustomerNotFound + } + return nil +} + +func (r *customerPinRepository) RemovePin(ctx context.Context, customerID uuid.UUID) error { + result := DBFromContext(ctx, r.db).WithContext(ctx).Exec(` + UPDATE customers SET pin_hash = NULL, pin_set_at = NULL, pin_failed_attempts = 0, + pin_locked_until = NULL, updated_at = NOW() + WHERE id = ?`, customerID) + if result.Error != nil { + return fmt.Errorf("failed to remove customer PIN: %w", result.Error) + } + if result.RowsAffected == 0 { + return ErrPinCustomerNotFound + } + return nil +} + +func (r *customerPinRepository) RecordFailure(ctx context.Context, customerID uuid.UUID, maxAttempts int, now, lockUntil time.Time) (int, *time.Time, error) { + var rows []struct { + PinFailedAttempts int + PinLockedUntil *time.Time + } + // When an earlier lock has run out, this attempt is the first of a new series. + err := DBFromContext(ctx, r.db).WithContext(ctx).Raw(` + UPDATE customers SET + pin_failed_attempts = CASE + WHEN pin_locked_until IS NOT NULL AND pin_locked_until <= @now THEN 1 + ELSE pin_failed_attempts + 1 END, + pin_locked_until = CASE + WHEN pin_locked_until IS NOT NULL AND pin_locked_until <= @now THEN NULL + WHEN pin_failed_attempts + 1 >= @max THEN @lock + ELSE pin_locked_until END + WHERE id = @id + RETURNING pin_failed_attempts, pin_locked_until`, + map[string]interface{}{"now": now, "max": maxAttempts, "lock": lockUntil, "id": customerID}). + Scan(&rows).Error + if err != nil { + return 0, nil, fmt.Errorf("failed to record a wrong PIN: %w", err) + } + if len(rows) == 0 { + return 0, nil, ErrPinCustomerNotFound + } + return rows[0].PinFailedAttempts, rows[0].PinLockedUntil, nil +} + +func (r *customerPinRepository) ClearFailures(ctx context.Context, customerID uuid.UUID) error { + return DBFromContext(ctx, r.db).WithContext(ctx).Exec(` + UPDATE customers SET pin_failed_attempts = 0, pin_locked_until = NULL + WHERE id = ? AND (pin_failed_attempts <> 0 OR pin_locked_until IS NOT NULL)`, customerID).Error +} + +func (r *customerPinRepository) InsertEvent(ctx context.Context, event CustomerSecurityEvent) error { + err := DBFromContext(ctx, r.db).WithContext(ctx).Exec(` + INSERT INTO customer_security_events (customer_id, event, actor_user, reason, ip_address, user_agent) + VALUES (?, ?, ?, ?, ?, ?)`, + event.CustomerID, event.Event, event.ActorUser, event.Reason, event.IPAddress, event.UserAgent).Error + if err != nil { + return fmt.Errorf("failed to record security event: %w", err) + } + return nil +} + +func (r *customerPinRepository) ListEvents(ctx context.Context, customerID uuid.UUID, offset, limit int) ([]CustomerSecurityEvent, int64, error) { + db := DBFromContext(ctx, r.db).WithContext(ctx) + var total int64 + if err := db.Table("customer_security_events").Where("customer_id = ?", customerID).Count(&total).Error; err != nil { + return nil, 0, fmt.Errorf("failed to count security events: %w", err) + } + var rows []struct { + ID string + CustomerID string + Event string + ActorUser *string + Reason *string + IPAddress *string + UserAgent *string + CreatedAt time.Time + } + err := db.Raw(` + SELECT id::text AS id, customer_id::text AS customer_id, event, actor_user::text AS actor_user, + reason, ip_address, user_agent, created_at + FROM customer_security_events WHERE customer_id = ? + ORDER BY created_at DESC, id DESC OFFSET ? LIMIT ?`, customerID, offset, limit).Scan(&rows).Error + if err != nil { + return nil, 0, fmt.Errorf("failed to list security events: %w", err) + } + events := make([]CustomerSecurityEvent, 0, len(rows)) + for _, row := range rows { + e := CustomerSecurityEvent{Event: row.Event, Reason: row.Reason, IPAddress: row.IPAddress, UserAgent: row.UserAgent, CreatedAt: row.CreatedAt} + e.ID, _ = uuid.Parse(row.ID) + e.CustomerID, _ = uuid.Parse(row.CustomerID) + if row.ActorUser != nil { + if id, err := uuid.Parse(*row.ActorUser); err == nil { + e.ActorUser = &id + } + } + events = append(events, e) + } + return events, total, nil +} diff --git a/internal/repository/customer_points_repository.go b/internal/repository/customer_points_repository.go deleted file mode 100644 index 6ee1677..0000000 --- a/internal/repository/customer_points_repository.go +++ /dev/null @@ -1,97 +0,0 @@ -package repository - -import ( - "context" - "fmt" - - "apskel-pos-be/internal/entities" - - "gorm.io/gorm" -) - -type CustomerPointsRepository interface { - GetCustomerTotalPoints(ctx context.Context, customerID string) (int64, error) - GetCustomerTotalTokens(ctx context.Context, customerID string) (int64, error) - GetCustomerPointsHistory(ctx context.Context, customerID string, limit int) ([]entities.CustomerPoints, error) - GetCustomerTokensHistory(ctx context.Context, customerID string, limit int) ([]entities.CustomerTokens, error) -} - -type customerPointsRepository struct { - db *gorm.DB -} - -func NewCustomerPointsRepository(db *gorm.DB) CustomerPointsRepository { - return &customerPointsRepository{ - db: db, - } -} - -func (r *customerPointsRepository) GetCustomerTotalPoints(ctx context.Context, customerID string) (int64, error) { - var totalPoints int64 - - err := r.db.WithContext(ctx). - Model(&entities.CustomerPoints{}). - Where("customer_id = ?", customerID). - Select("COALESCE(SUM(balance), 0)"). - Scan(&totalPoints).Error - - if err != nil { - return 0, fmt.Errorf("failed to get customer total points: %w", err) - } - - return totalPoints, nil -} - -func (r *customerPointsRepository) GetCustomerTotalTokens(ctx context.Context, customerID string) (int64, error) { - var totalTokens int64 - - err := r.db.WithContext(ctx). - Model(&entities.CustomerTokens{}). - Where("customer_id = ?", customerID). - Select("COALESCE(SUM(balance), 0)"). - Scan(&totalTokens).Error - - if err != nil { - return 0, fmt.Errorf("failed to get customer total tokens: %w", err) - } - - return totalTokens, nil -} - -func (r *customerPointsRepository) GetCustomerPointsHistory(ctx context.Context, customerID string, limit int) ([]entities.CustomerPoints, error) { - var pointsHistory []entities.CustomerPoints - - query := r.db.WithContext(ctx). - Where("customer_id = ?", customerID). - Order("created_at DESC") - - if limit > 0 { - query = query.Limit(limit) - } - - err := query.Find(&pointsHistory).Error - if err != nil { - return nil, fmt.Errorf("failed to get customer points history: %w", err) - } - - return pointsHistory, nil -} - -func (r *customerPointsRepository) GetCustomerTokensHistory(ctx context.Context, customerID string, limit int) ([]entities.CustomerTokens, error) { - var tokensHistory []entities.CustomerTokens - - query := r.db.WithContext(ctx). - Where("customer_id = ?", customerID). - Order("created_at DESC") - - if limit > 0 { - query = query.Limit(limit) - } - - err := query.Find(&tokensHistory).Error - if err != nil { - return nil, fmt.Errorf("failed to get customer tokens history: %w", err) - } - - return tokensHistory, nil -} diff --git a/internal/repository/customer_tokens_repository.go b/internal/repository/customer_tokens_repository.go deleted file mode 100644 index de29903..0000000 --- a/internal/repository/customer_tokens_repository.go +++ /dev/null @@ -1,131 +0,0 @@ -package repository - -import ( - "apskel-pos-be/internal/entities" - "context" - "fmt" - - "github.com/google/uuid" - "gorm.io/gorm" -) - -type CustomerTokensRepository struct { - db *gorm.DB -} - -func NewCustomerTokensRepository(db *gorm.DB) *CustomerTokensRepository { - return &CustomerTokensRepository{db: db} -} - -func (r *CustomerTokensRepository) Create(ctx context.Context, customerTokens *entities.CustomerTokens) error { - return r.db.WithContext(ctx).Create(customerTokens).Error -} - -func (r *CustomerTokensRepository) GetByID(ctx context.Context, id uuid.UUID) (*entities.CustomerTokens, error) { - var customerTokens entities.CustomerTokens - err := r.db.WithContext(ctx).Preload("Customer").Where("id = ?", id).First(&customerTokens).Error - if err != nil { - return nil, err - } - return &customerTokens, nil -} - -func (r *CustomerTokensRepository) GetByCustomerIDAndType(ctx context.Context, customerID uuid.UUID, tokenType entities.TokenType) (*entities.CustomerTokens, error) { - var customerTokens entities.CustomerTokens - err := r.db.WithContext(ctx).Preload("Customer").Where("customer_id = ? AND token_type = ?", customerID, tokenType).First(&customerTokens).Error - if err != nil { - return nil, err - } - return &customerTokens, nil -} - -func (r *CustomerTokensRepository) GetByCustomerID(ctx context.Context, customerID uuid.UUID) ([]entities.CustomerTokens, error) { - var customerTokens []entities.CustomerTokens - err := r.db.WithContext(ctx).Preload("Customer").Where("customer_id = ?", customerID).Find(&customerTokens).Error - if err != nil { - return nil, err - } - return customerTokens, nil -} - -func (r *CustomerTokensRepository) List(ctx context.Context, offset, limit int, search, tokenType string, sortBy, sortOrder string) ([]entities.CustomerTokens, int64, error) { - var customerTokens []entities.CustomerTokens - var total int64 - - query := r.db.WithContext(ctx).Preload("Customer") - - if search != "" { - searchTerm := "%" + search + "%" - query = query.Joins("JOIN customers ON customer_tokens.customer_id = customers.id"). - Where("customers.name ILIKE ? OR customers.email ILIKE ?", searchTerm, searchTerm) - } - - if tokenType != "" { - query = query.Where("token_type = ?", tokenType) - } - - if err := query.Model(&entities.CustomerTokens{}).Count(&total).Error; err != nil { - return nil, 0, err - } - - if sortBy != "" { - if sortOrder == "" { - sortOrder = "asc" - } - query = query.Order(fmt.Sprintf("customer_tokens.%s %s", sortBy, sortOrder)) - } else { - query = query.Order("customer_tokens.created_at DESC") - } - - err := query.Offset(offset).Limit(limit).Find(&customerTokens).Error - if err != nil { - return nil, 0, err - } - - return customerTokens, total, nil -} - -func (r *CustomerTokensRepository) Update(ctx context.Context, customerTokens *entities.CustomerTokens) error { - return r.db.WithContext(ctx).Save(customerTokens).Error -} - -func (r *CustomerTokensRepository) Delete(ctx context.Context, id uuid.UUID) error { - return r.db.WithContext(ctx).Delete(&entities.CustomerTokens{}, id).Error -} - -func (r *CustomerTokensRepository) AddTokens(ctx context.Context, customerID uuid.UUID, tokenType entities.TokenType, tokens int64) error { - return r.db.WithContext(ctx).Model(&entities.CustomerTokens{}). - Where("customer_id = ? AND token_type = ?", customerID, tokenType). - Update("balance", gorm.Expr("balance + ?", tokens)).Error -} - -func (r *CustomerTokensRepository) DeductTokens(ctx context.Context, customerID uuid.UUID, tokenType entities.TokenType, tokens int64) error { - return r.db.WithContext(ctx).Model(&entities.CustomerTokens{}). - Where("customer_id = ? AND token_type = ? AND balance >= ?", customerID, tokenType, tokens). - Update("balance", gorm.Expr("balance - ?", tokens)).Error -} - -func (r *CustomerTokensRepository) EnsureCustomerTokens(ctx context.Context, customerID uuid.UUID, tokenType entities.TokenType) (*entities.CustomerTokens, error) { - customerTokens, err := r.GetByCustomerIDAndType(ctx, customerID, tokenType) - if err == nil { - return customerTokens, nil - } - - if err != gorm.ErrRecordNotFound { - return nil, err - } - - // Create new customer tokens record - newCustomerTokens := &entities.CustomerTokens{ - CustomerID: customerID, - TokenType: tokenType, - Balance: 0, - } - - err = r.Create(ctx, newCustomerTokens) - if err != nil { - return nil, err - } - - return newCustomerTokens, nil -} diff --git a/internal/repository/earning_repository.go b/internal/repository/earning_repository.go new file mode 100644 index 0000000..81d3711 --- /dev/null +++ b/internal/repository/earning_repository.go @@ -0,0 +1,275 @@ +package repository + +import ( + "context" + "errors" + "fmt" + "time" + + "github.com/google/uuid" + "gorm.io/gorm" + + "apskel-pos-be/internal/constants" + "apskel-pos-be/internal/entities" +) + +// ErrEarningOrderNotFound means the order does not exist. +var ErrEarningOrderNotFound = errors.New("earning: order not found") + +// EarningOrder is what earning needs to know about an order. +type EarningOrder struct { + ID uuid.UUID + OrganizationID uuid.UUID + OutletID uuid.UUID + OrderNumber string + OutletName string + CustomerID *uuid.UUID + Subtotal float64 + DiscountAmount float64 + PaymentStatus string + IsVoid bool + // Cumulative rupiah refunded so far. + RefundAmount float64 + // Nil when the order has no customer, or the customer row is gone. + CustomerIsDefault *bool + CustomerIsActive *bool +} + +// EarningCursor pages through orders by (updated_at, id). +type EarningCursor struct { + UpdatedAt time.Time + ID uuid.UUID +} + +// EarningRepository reads orders for loyalty earning (docs/prd-point-coin.md F3). +type EarningRepository interface { + GetOrderForEarning(ctx context.Context, orderID uuid.UUID) (*EarningOrder, error) + // PointPaidAmount is the rupiah part of the order paid with EnakPoint, which earns + // nothing (Q10). Zero until EnakPoint payment exists (phase 3). + PointPaidAmount(ctx context.Context, orderID uuid.UUID) (float64, error) + // ListPaidOrdersWithoutEarning pages, oldest first, through orders updated since + // the given time that are paid, not void, have an eligible customer, belong to an + // outlet that earns something, and have no EARN row yet. Pass the previous page's + // last cursor to continue; nil starts at the beginning. + ListPaidOrdersWithoutEarning(ctx context.Context, since time.Time, after *EarningCursor, limit int) ([]EarningCursor, error) + // ListEarnTransactions returns the EARN rows written for an order. + ListEarnTransactions(ctx context.Context, orderID uuid.UUID) ([]entities.WalletTransaction, error) + // ReversalRequested is how much has been asked back from an EARN row so far: what + // was taken plus any shortfall. + ReversalRequested(ctx context.Context, earnTransactionID uuid.UUID) (int64, error) + // LotIDsCreatedBy returns the lots a credit created. + LotIDsCreatedBy(ctx context.Context, transactionID uuid.UUID) ([]uuid.UUID, error) + // EarnedByOrders sums the EARN rows of each order per currency, as + // map[order]map[currency]amount. Orders that earned nothing are absent. + EarnedByOrders(ctx context.Context, orderIDs []uuid.UUID) (map[uuid.UUID]map[string]int64, error) +} + +type earningRepository struct { + db *gorm.DB +} + +func NewEarningRepository(db *gorm.DB) EarningRepository { + return &earningRepository{db: db} +} + +func (r *earningRepository) GetOrderForEarning(ctx context.Context, orderID uuid.UUID) (*EarningOrder, error) { + var rows []struct { + ID string + OrganizationID string + OutletID string + OrderNumber string + OutletName string + CustomerID *string + Subtotal float64 + DiscountAmount float64 + PaymentStatus string + IsVoid bool + RefundAmount float64 + CustomerIsDefault *bool + CustomerIsActive *bool + } + err := DBFromContext(ctx, r.db).WithContext(ctx).Raw(` + SELECT o.id::text AS id, o.organization_id::text AS organization_id, o.outlet_id::text AS outlet_id, + o.order_number, COALESCE(ou.name, '') AS outlet_name, o.customer_id::text AS customer_id, + o.subtotal, COALESCE(o.discount_amount, 0) AS discount_amount, o.payment_status, + COALESCE(o.is_void, false) AS is_void, + -- Refunds of EnakPoint payments are left out: that part never earned (Q10), + -- so giving it back must not take earning back. + COALESCE(o.refund_amount, 0) - COALESCE(( + SELECT SUM(COALESCE(p.refund_amount, 0)) FROM payments p + JOIN payment_methods pm ON pm.id = p.payment_method_id + WHERE p.order_id = o.id AND pm.type = 'point'), 0) AS refund_amount, + c.is_default AS customer_is_default, c.is_active AS customer_is_active + FROM orders o + LEFT JOIN outlets ou ON ou.id = o.outlet_id + LEFT JOIN customers c ON c.id = o.customer_id + WHERE o.id = ? + LIMIT 1`, orderID).Scan(&rows).Error + if err != nil { + return nil, fmt.Errorf("failed to get order for earning: %w", err) + } + if len(rows) == 0 { + return nil, ErrEarningOrderNotFound + } + row := rows[0] + order := &EarningOrder{ + OrderNumber: row.OrderNumber, + OutletName: row.OutletName, + Subtotal: row.Subtotal, + DiscountAmount: row.DiscountAmount, + PaymentStatus: row.PaymentStatus, + IsVoid: row.IsVoid, + RefundAmount: row.RefundAmount, + CustomerIsDefault: row.CustomerIsDefault, + CustomerIsActive: row.CustomerIsActive, + } + order.ID, _ = uuid.Parse(row.ID) + order.OrganizationID, _ = uuid.Parse(row.OrganizationID) + order.OutletID, _ = uuid.Parse(row.OutletID) + if row.CustomerID != nil { + if id, err := uuid.Parse(*row.CustomerID); err == nil { + order.CustomerID = &id + } + } + return order, nil +} + +func (r *earningRepository) PointPaidAmount(ctx context.Context, orderID uuid.UUID) (float64, error) { + var total float64 + err := DBFromContext(ctx, r.db).WithContext(ctx).Raw(` + SELECT COALESCE(SUM(p.amount), 0) + FROM payments p + JOIN payment_methods pm ON pm.id = p.payment_method_id + WHERE p.order_id = ? AND pm.type = ? AND p.status = ?`, + orderID, constants.PaymentMethodTypePoint, entities.PaymentTransactionStatusCompleted). + Scan(&total).Error + if err != nil { + return 0, fmt.Errorf("failed to sum EnakPoint payments: %w", err) + } + return total, nil +} + +func (r *earningRepository) ListPaidOrdersWithoutEarning(ctx context.Context, since time.Time, after *EarningCursor, limit int) ([]EarningCursor, error) { + cursorAt, cursorID := since, uuid.Nil + if after != nil { + cursorAt, cursorID = after.UpdatedAt, after.ID + } + var rows []struct { + ID string + UpdatedAt time.Time + } + // An outlet that has neither currency switched on can never earn, so its orders are + // not candidates; otherwise every order of such an outlet would be rescanned on + // every run. + err := DBFromContext(ctx, r.db).WithContext(ctx).Raw(` + SELECT o.id::text AS id, o.updated_at + FROM orders o + JOIN customers c ON c.id = o.customer_id + WHERE o.payment_status = ? + AND COALESCE(o.is_void, false) = false + AND c.is_default = false AND c.is_active = true + AND o.updated_at >= ? + AND (o.updated_at, o.id) > (?, ?) + AND EXISTS ( + SELECT 1 FROM outlet_settings s + WHERE s.outlet_id = o.outlet_id + AND s.key IN (?, ?) + AND lower(trim(s.value)) IN ('true', 't', '1') + ) + AND NOT EXISTS ( + SELECT 1 FROM wallet_transactions t + WHERE t.reference_type = ? AND t.reference_id = o.id AND t.type = ? + ) + ORDER BY o.updated_at, o.id + LIMIT ?`, + entities.PaymentStatusCompleted, since, cursorAt, cursorID, + constants.LoyaltyPointEnabledKey, constants.LoyaltyCoinEnabledKey, + constants.WalletRefTypeOrder, constants.WalletTxTypeEarn, limit). + Scan(&rows).Error + if err != nil { + return nil, fmt.Errorf("failed to list paid orders without earning: %w", err) + } + out := make([]EarningCursor, 0, len(rows)) + for _, row := range rows { + if id, err := uuid.Parse(row.ID); err == nil { + out = append(out, EarningCursor{UpdatedAt: row.UpdatedAt, ID: id}) + } + } + return out, nil +} + +func (r *earningRepository) ListEarnTransactions(ctx context.Context, orderID uuid.UUID) ([]entities.WalletTransaction, error) { + var rows []entities.WalletTransaction + err := DBFromContext(ctx, r.db).WithContext(ctx). + Where("reference_type = ? AND reference_id = ? AND type = ?", constants.WalletRefTypeOrder, orderID, constants.WalletTxTypeEarn). + Order("currency"). + Find(&rows).Error + if err != nil { + return nil, fmt.Errorf("failed to list EARN rows: %w", err) + } + return rows, nil +} + +func (r *earningRepository) ReversalRequested(ctx context.Context, earnTransactionID uuid.UUID) (int64, error) { + var total int64 + err := DBFromContext(ctx, r.db).WithContext(ctx).Raw(` + SELECT COALESCE(SUM(COALESCE((metadata->>'requested_amount')::bigint, -amount)), 0) + FROM wallet_transactions + WHERE reverses_transaction_id = ? AND type = ?`, + earnTransactionID, constants.WalletTxTypeEarnReversal).Scan(&total).Error + if err != nil { + return 0, fmt.Errorf("failed to sum earning reversals: %w", err) + } + return total, nil +} + +func (r *earningRepository) LotIDsCreatedBy(ctx context.Context, transactionID uuid.UUID) ([]uuid.UUID, error) { + var ids []string + err := DBFromContext(ctx, r.db).WithContext(ctx). + Table("wallet_lots"). + Where("source_transaction_id = ?", transactionID). + Order("expires_at NULLS LAST, created_at, id"). + Pluck("id::text", &ids).Error + if err != nil { + return nil, fmt.Errorf("failed to list lots of a credit: %w", err) + } + out := make([]uuid.UUID, 0, len(ids)) + for _, s := range ids { + if id, err := uuid.Parse(s); err == nil { + out = append(out, id) + } + } + return out, nil +} + +func (r *earningRepository) EarnedByOrders(ctx context.Context, orderIDs []uuid.UUID) (map[uuid.UUID]map[string]int64, error) { + earned := map[uuid.UUID]map[string]int64{} + if len(orderIDs) == 0 { + return earned, nil + } + var rows []struct { + OrderID string + Currency string + Amount int64 + } + err := DBFromContext(ctx, r.db).WithContext(ctx).Raw(` + SELECT reference_id::text AS order_id, currency, SUM(amount) AS amount + FROM wallet_transactions + WHERE reference_type = ? AND type = ? AND reference_id IN ? + GROUP BY reference_id, currency`, + constants.WalletRefTypeOrder, constants.WalletTxTypeEarn, orderIDs).Scan(&rows).Error + if err != nil { + return nil, fmt.Errorf("failed to sum earnings of orders: %w", err) + } + for _, row := range rows { + id, err := uuid.Parse(row.OrderID) + if err != nil { + continue + } + if earned[id] == nil { + earned[id] = map[string]int64{} + } + earned[id][row.Currency] = row.Amount + } + return earned, nil +} diff --git a/internal/repository/game_play_repository.go b/internal/repository/game_play_repository.go index b3ffb2c..48c8d01 100644 --- a/internal/repository/game_play_repository.go +++ b/internal/repository/game_play_repository.go @@ -31,7 +31,7 @@ func NewGamePlayRepository(db *gorm.DB) GamePlayRepository { } func (r *gamePlayRepository) Create(ctx context.Context, gamePlay *entities.GamePlay) error { - if err := r.db.WithContext(ctx).Create(gamePlay).Error; err != nil { + if err := DBFromContext(ctx, r.db).WithContext(ctx).Create(gamePlay).Error; err != nil { return fmt.Errorf("failed to create game play: %w", err) } return nil @@ -39,7 +39,7 @@ func (r *gamePlayRepository) Create(ctx context.Context, gamePlay *entities.Game func (r *gamePlayRepository) GetByID(ctx context.Context, id uuid.UUID) (*entities.GamePlay, error) { var gamePlay entities.GamePlay - err := r.db.WithContext(ctx). + err := DBFromContext(ctx, r.db).WithContext(ctx). Preload("Game"). Preload("Customer"). Preload("Prize"). @@ -57,7 +57,7 @@ func (r *gamePlayRepository) List(ctx context.Context, offset, limit int, search var gamePlays []*entities.GamePlay var total int64 - query := r.db.WithContext(ctx).Model(&entities.GamePlay{}) + query := DBFromContext(ctx, r.db).WithContext(ctx).Model(&entities.GamePlay{}) // Apply filters if search != "" { @@ -107,7 +107,7 @@ func (r *gamePlayRepository) List(ctx context.Context, offset, limit int, search func (r *gamePlayRepository) GetByCustomerID(ctx context.Context, customerID uuid.UUID, limit int) ([]*entities.GamePlay, error) { var gamePlays []*entities.GamePlay - query := r.db.WithContext(ctx). + query := DBFromContext(ctx, r.db).WithContext(ctx). Where("customer_id = ?", customerID). Preload("Game"). Preload("Prize"). @@ -127,7 +127,7 @@ func (r *gamePlayRepository) GetByCustomerID(ctx context.Context, customerID uui func (r *gamePlayRepository) GetByGameID(ctx context.Context, gameID uuid.UUID, limit int) ([]*entities.GamePlay, error) { var gamePlays []*entities.GamePlay - query := r.db.WithContext(ctx). + query := DBFromContext(ctx, r.db).WithContext(ctx). Where("game_id = ?", gameID). Preload("Customer"). Preload("Prize"). @@ -147,7 +147,7 @@ func (r *gamePlayRepository) GetByGameID(ctx context.Context, gameID uuid.UUID, func (r *gamePlayRepository) CountByCustomerID(ctx context.Context, customerID uuid.UUID) (int64, error) { var count int64 - err := r.db.WithContext(ctx). + err := DBFromContext(ctx, r.db).WithContext(ctx). Model(&entities.GamePlay{}). Where("customer_id = ?", customerID). Count(&count).Error @@ -159,7 +159,7 @@ func (r *gamePlayRepository) CountByCustomerID(ctx context.Context, customerID u func (r *gamePlayRepository) CountByGameID(ctx context.Context, gameID uuid.UUID) (int64, error) { var count int64 - err := r.db.WithContext(ctx). + err := DBFromContext(ctx, r.db).WithContext(ctx). Model(&entities.GamePlay{}). Where("game_id = ?", gameID). Count(&count).Error diff --git a/internal/repository/game_prize_repository.go b/internal/repository/game_prize_repository.go index 243bf73..2b2f13c 100644 --- a/internal/repository/game_prize_repository.go +++ b/internal/repository/game_prize_repository.go @@ -3,12 +3,16 @@ package repository import ( "apskel-pos-be/internal/entities" "context" + "errors" "fmt" "github.com/google/uuid" "gorm.io/gorm" ) +// ErrGamePrizeOutOfStock means a prize had less stock than was taken from it. +var ErrGamePrizeOutOfStock = errors.New("game prize is out of stock") + type GamePrizeRepository struct { db *gorm.DB } @@ -18,12 +22,12 @@ func NewGamePrizeRepository(db *gorm.DB) *GamePrizeRepository { } func (r *GamePrizeRepository) Create(ctx context.Context, gamePrize *entities.GamePrize) error { - return r.db.WithContext(ctx).Create(gamePrize).Error + return DBFromContext(ctx, r.db).WithContext(ctx).Create(gamePrize).Error } func (r *GamePrizeRepository) GetByID(ctx context.Context, id uuid.UUID) (*entities.GamePrize, error) { var gamePrize entities.GamePrize - err := r.db.WithContext(ctx).Preload("Game").Preload("FallbackPrize").Where("id = ?", id).First(&gamePrize).Error + err := DBFromContext(ctx, r.db).WithContext(ctx).Preload("Game").Preload("FallbackPrize").Where("id = ?", id).First(&gamePrize).Error if err != nil { return nil, err } @@ -32,7 +36,7 @@ func (r *GamePrizeRepository) GetByID(ctx context.Context, id uuid.UUID) (*entit func (r *GamePrizeRepository) GetByGameID(ctx context.Context, gameID uuid.UUID) ([]entities.GamePrize, error) { var gamePrizes []entities.GamePrize - err := r.db.WithContext(ctx).Preload("Game").Preload("FallbackPrize").Where("game_id = ?", gameID).Find(&gamePrizes).Error + err := DBFromContext(ctx, r.db).WithContext(ctx).Preload("Game").Preload("FallbackPrize").Where("game_id = ?", gameID).Find(&gamePrizes).Error if err != nil { return nil, err } @@ -43,7 +47,7 @@ func (r *GamePrizeRepository) List(ctx context.Context, offset, limit int, searc var gamePrizes []entities.GamePrize var total int64 - query := r.db.WithContext(ctx).Preload("Game").Preload("FallbackPrize") + query := DBFromContext(ctx, r.db).WithContext(ctx).Preload("Game").Preload("FallbackPrize") if search != "" { searchTerm := "%" + search + "%" @@ -76,22 +80,31 @@ func (r *GamePrizeRepository) List(ctx context.Context, offset, limit int, searc } func (r *GamePrizeRepository) Update(ctx context.Context, gamePrize *entities.GamePrize) error { - return r.db.WithContext(ctx).Save(gamePrize).Error + return DBFromContext(ctx, r.db).WithContext(ctx).Save(gamePrize).Error } func (r *GamePrizeRepository) Delete(ctx context.Context, id uuid.UUID) error { - return r.db.WithContext(ctx).Delete(&entities.GamePrize{}, id).Error + return DBFromContext(ctx, r.db).WithContext(ctx).Delete(&entities.GamePrize{}, id).Error } +// DecreaseStock takes amount from a prize's stock. When less than amount is left it +// changes nothing and returns ErrGamePrizeOutOfStock. func (r *GamePrizeRepository) DecreaseStock(ctx context.Context, id uuid.UUID, amount int) error { - return r.db.WithContext(ctx).Model(&entities.GamePrize{}). + res := DBFromContext(ctx, r.db).WithContext(ctx).Model(&entities.GamePrize{}). Where("id = ? AND stock >= ?", id, amount). - Update("stock", gorm.Expr("stock - ?", amount)).Error + Update("stock", gorm.Expr("stock - ?", amount)) + if res.Error != nil { + return fmt.Errorf("failed to decrease prize stock: %w", res.Error) + } + if res.RowsAffected == 0 { + return ErrGamePrizeOutOfStock + } + return nil } func (r *GamePrizeRepository) GetAvailablePrizes(ctx context.Context, gameID uuid.UUID) ([]entities.GamePrize, error) { var gamePrizes []entities.GamePrize - err := r.db.WithContext(ctx).Preload("Game").Preload("FallbackPrize"). + err := DBFromContext(ctx, r.db).WithContext(ctx).Preload("Game").Preload("FallbackPrize"). Where("game_id = ? AND stock > 0", gameID). Order("weight DESC"). Find(&gamePrizes).Error diff --git a/internal/repository/game_repository.go b/internal/repository/game_repository.go index 4d41f18..22d281a 100644 --- a/internal/repository/game_repository.go +++ b/internal/repository/game_repository.go @@ -18,12 +18,12 @@ func NewGameRepository(db *gorm.DB) *GameRepository { } func (r *GameRepository) Create(ctx context.Context, game *entities.Game) error { - return r.db.WithContext(ctx).Create(game).Error + return DBFromContext(ctx, r.db).WithContext(ctx).Create(game).Error } func (r *GameRepository) GetByID(ctx context.Context, id uuid.UUID) (*entities.Game, error) { var game entities.Game - err := r.db.WithContext(ctx).Preload("Prizes").Where("id = ?", id).First(&game).Error + err := DBFromContext(ctx, r.db).WithContext(ctx).Preload("Prizes").Where("id = ?", id).First(&game).Error if err != nil { return nil, err } @@ -34,7 +34,7 @@ func (r *GameRepository) List(ctx context.Context, offset, limit int, search, ga var games []entities.Game var total int64 - query := r.db.WithContext(ctx).Preload("Prizes") + query := DBFromContext(ctx, r.db).WithContext(ctx).Preload("Prizes") if search != "" { searchTerm := "%" + search + "%" @@ -71,16 +71,16 @@ func (r *GameRepository) List(ctx context.Context, offset, limit int, search, ga } func (r *GameRepository) Update(ctx context.Context, game *entities.Game) error { - return r.db.WithContext(ctx).Save(game).Error + return DBFromContext(ctx, r.db).WithContext(ctx).Save(game).Error } func (r *GameRepository) Delete(ctx context.Context, id uuid.UUID) error { - return r.db.WithContext(ctx).Delete(&entities.Game{}, id).Error + return DBFromContext(ctx, r.db).WithContext(ctx).Delete(&entities.Game{}, id).Error } func (r *GameRepository) GetActiveGames(ctx context.Context) ([]entities.Game, error) { var games []entities.Game - err := r.db.WithContext(ctx).Preload("Prizes").Where("is_active = ?", true).Find(&games).Error + err := DBFromContext(ctx, r.db).WithContext(ctx).Preload("Prizes").Where("is_active = ?", true).Find(&games).Error if err != nil { return nil, err } @@ -89,7 +89,7 @@ func (r *GameRepository) GetActiveGames(ctx context.Context) ([]entities.Game, e func (r *GameRepository) GetActiveSpinGames(ctx context.Context) ([]entities.Game, error) { var games []entities.Game - err := r.db.WithContext(ctx). + err := DBFromContext(ctx, r.db).WithContext(ctx). Preload("Prizes"). Where("is_active = ? AND type = ?", true, entities.GameTypeSpin). Find(&games).Error @@ -101,7 +101,7 @@ func (r *GameRepository) GetActiveSpinGames(ctx context.Context) ([]entities.Gam func (r *GameRepository) GetFerrisWheelGame(ctx context.Context) (*entities.Game, error) { var game entities.Game - err := r.db.WithContext(ctx). + err := DBFromContext(ctx, r.db).WithContext(ctx). Preload("Prizes"). Where("is_active = ? AND type = ?", true, "SPIN"). First(&game).Error diff --git a/internal/repository/loyalty_settings_repository.go b/internal/repository/loyalty_settings_repository.go new file mode 100644 index 0000000..757634f --- /dev/null +++ b/internal/repository/loyalty_settings_repository.go @@ -0,0 +1,219 @@ +package repository + +import ( + "context" + "errors" + "fmt" + "time" + + "github.com/google/uuid" + "gorm.io/gorm" + + "apskel-pos-be/internal/entities" +) + +// ErrLoyaltyOutletNotFound means the outlet does not exist or belongs to another +// organization. +var ErrLoyaltyOutletNotFound = errors.New("loyalty settings: outlet not found") + +// LoyaltySettingChangeFilter narrows the loyalty settings history. +type LoyaltySettingChangeFilter struct { + OrganizationID uuid.UUID + // Nil for the whole organization, outlets included. + OutletID *uuid.UUID + Offset int + Limit int +} + +// LoyaltySettingsRepository stores the raw loyalty settings (the loyalty.* keys of +// outlet_settings and organization_settings) and their history +// (docs/prd-point-coin.md F1, F2). The loyalty settings processor turns them into +// typed values and is the only writer. +type LoyaltySettingsRepository interface { + // GetOutletValues returns the stored loyalty keys of an outlet. A key with no row, + // or a NULL value, is absent. + GetOutletValues(ctx context.Context, outletID uuid.UUID) (map[string]string, error) + GetOrganizationValues(ctx context.Context, organizationID uuid.UUID) (map[string]string, error) + // OutletOrganizationID returns ErrLoyaltyOutletNotFound for an unknown outlet. + OutletOrganizationID(ctx context.Context, outletID uuid.UUID) (uuid.UUID, error) + + // LockScope serializes writers of one outlet's or one organization's settings + // until the transaction ends, so two saves at once cannot both compute their + // changes from the same old values. + LockScope(ctx context.Context, scopeID uuid.UUID) error + // SetOutletValue stores a value, or removes the key when value is nil so it falls + // back to its default. + SetOutletValue(ctx context.Context, outletID uuid.UUID, key string, value *string) error + SetOrganizationValue(ctx context.Context, organizationID uuid.UUID, key string, value *string) error + InsertChanges(ctx context.Context, changes []entities.LoyaltySettingChange) error + // ListChanges returns a page of history, newest first, and the total count. + ListChanges(ctx context.Context, filter LoyaltySettingChangeFilter) ([]entities.LoyaltySettingChange, int64, error) + + // UndatedBalance counts an organization's lots of one currency that still hold + // something and have no expiry, and what they hold. + UndatedBalance(ctx context.Context, organizationID uuid.UUID, currency string) (lots, amount int64, err error) + // DateUndatedLots gives those lots an expiry, when expiry is turned on (F12). + DateUndatedLots(ctx context.Context, organizationID uuid.UUID, currency string, expiresAt time.Time) (lots, amount int64, err error) +} + +type loyaltySettingsRepository struct { + db *gorm.DB +} + +func NewLoyaltySettingsRepository(db *gorm.DB) LoyaltySettingsRepository { + return &loyaltySettingsRepository{db: db} +} + +// requireTx returns the caller's transaction. Writes must run in one, together with +// the history rows they produce. +func (r *loyaltySettingsRepository) requireTx(ctx context.Context) (*gorm.DB, error) { + if tx, ok := ctx.Value(txKey).(*gorm.DB); ok && tx != nil { + return tx.WithContext(ctx), nil + } + return nil, errors.New("loyalty settings: write must run inside a transaction") +} + +func (r *loyaltySettingsRepository) values(ctx context.Context, table, scopeColumn string, scopeID uuid.UUID) (map[string]string, error) { + var rows []struct { + Key string + Value string + } + err := DBFromContext(ctx, r.db).WithContext(ctx). + Table(table). + Select("key, value"). + Where(scopeColumn+" = ? AND key LIKE 'loyalty.%' AND value IS NOT NULL", scopeID). + Scan(&rows).Error + if err != nil { + return nil, fmt.Errorf("failed to read %s: %w", table, err) + } + values := make(map[string]string, len(rows)) + for _, row := range rows { + values[row.Key] = row.Value + } + return values, nil +} + +func (r *loyaltySettingsRepository) GetOutletValues(ctx context.Context, outletID uuid.UUID) (map[string]string, error) { + return r.values(ctx, "outlet_settings", "outlet_id", outletID) +} + +func (r *loyaltySettingsRepository) GetOrganizationValues(ctx context.Context, organizationID uuid.UUID) (map[string]string, error) { + return r.values(ctx, "organization_settings", "organization_id", organizationID) +} + +func (r *loyaltySettingsRepository) OutletOrganizationID(ctx context.Context, outletID uuid.UUID) (uuid.UUID, error) { + var ids []string + err := DBFromContext(ctx, r.db).WithContext(ctx). + Table("outlets"). + Where("id = ?", outletID). + Limit(1). + Pluck("organization_id::text", &ids).Error + if err != nil { + return uuid.Nil, fmt.Errorf("failed to get outlet organization: %w", err) + } + if len(ids) == 0 { + return uuid.Nil, ErrLoyaltyOutletNotFound + } + return uuid.Parse(ids[0]) +} + +func (r *loyaltySettingsRepository) LockScope(ctx context.Context, scopeID uuid.UUID) error { + db, err := r.requireTx(ctx) + if err != nil { + return err + } + return db.Exec(`SELECT pg_advisory_xact_lock(hashtextextended(?, 0))`, "loyalty-settings:"+scopeID.String()).Error +} + +func (r *loyaltySettingsRepository) SetOutletValue(ctx context.Context, outletID uuid.UUID, key string, value *string) error { + return r.setValue(ctx, "outlet_settings", "outlet_id", outletID, key, value) +} + +func (r *loyaltySettingsRepository) SetOrganizationValue(ctx context.Context, organizationID uuid.UUID, key string, value *string) error { + return r.setValue(ctx, "organization_settings", "organization_id", organizationID, key, value) +} + +// setValue upserts or deletes one key. table and scopeColumn are never user input. +func (r *loyaltySettingsRepository) setValue(ctx context.Context, table, scopeColumn string, scopeID uuid.UUID, key string, value *string) error { + db, err := r.requireTx(ctx) + if err != nil { + return err + } + if value == nil { + err = db.Exec(`DELETE FROM `+table+` WHERE `+scopeColumn+` = ? AND key = ?`, scopeID, key).Error + } else { + err = db.Exec(`INSERT INTO `+table+` (`+scopeColumn+`, key, value) VALUES (?, ?, ?) + ON CONFLICT (`+scopeColumn+`, key) DO UPDATE SET value = EXCLUDED.value, updated_at = NOW()`, + scopeID, key, *value).Error + } + if err != nil { + return fmt.Errorf("failed to store %s in %s: %w", key, table, err) + } + return nil +} + +func (r *loyaltySettingsRepository) InsertChanges(ctx context.Context, changes []entities.LoyaltySettingChange) error { + if len(changes) == 0 { + return nil + } + db, err := r.requireTx(ctx) + if err != nil { + return err + } + return db.Create(&changes).Error +} + +func (r *loyaltySettingsRepository) ListChanges(ctx context.Context, filter LoyaltySettingChangeFilter) ([]entities.LoyaltySettingChange, int64, error) { + query := DBFromContext(ctx, r.db).WithContext(ctx). + Model(&entities.LoyaltySettingChange{}). + Where("organization_id = ?", filter.OrganizationID) + if filter.OutletID != nil { + query = query.Where("outlet_id = ?", *filter.OutletID) + } + var total int64 + if err := query.Count(&total).Error; err != nil { + return nil, 0, fmt.Errorf("failed to count loyalty setting changes: %w", err) + } + var changes []entities.LoyaltySettingChange + err := query.Order("created_at DESC, id").Offset(filter.Offset).Limit(filter.Limit).Find(&changes).Error + if err != nil { + return nil, 0, fmt.Errorf("failed to list loyalty setting changes: %w", err) + } + return changes, total, nil +} + +func (r *loyaltySettingsRepository) UndatedBalance(ctx context.Context, organizationID uuid.UUID, currency string) (int64, int64, error) { + var row struct{ Lots, Amount int64 } + err := DBFromContext(ctx, r.db).WithContext(ctx).Raw(` + SELECT COUNT(*) AS lots, COALESCE(SUM(remaining_amount), 0) AS amount + FROM wallet_lots + WHERE organization_id = ? AND currency = ? AND expires_at IS NULL AND remaining_amount > 0`, + organizationID, currency).Scan(&row).Error + if err != nil { + return 0, 0, fmt.Errorf("failed to sum undated wallet lots: %w", err) + } + return row.Lots, row.Amount, nil +} + +func (r *loyaltySettingsRepository) DateUndatedLots(ctx context.Context, organizationID uuid.UUID, currency string, expiresAt time.Time) (int64, int64, error) { + db, err := r.requireTx(ctx) + if err != nil { + return 0, 0, err + } + var rows []struct{ RemainingAmount int64 } + // Only lots that still hold something: an empty lot never expires anything, and + // leaving it undated keeps the history as it was. + err = db.Raw(` + UPDATE wallet_lots SET expires_at = ? + WHERE organization_id = ? AND currency = ? AND expires_at IS NULL AND remaining_amount > 0 + RETURNING remaining_amount`, + expiresAt, organizationID, currency).Scan(&rows).Error + if err != nil { + return 0, 0, fmt.Errorf("failed to date wallet lots: %w", err) + } + var amount int64 + for _, row := range rows { + amount += row.RemainingAmount + } + return int64(len(rows)), amount, nil +} diff --git a/internal/repository/loyalty_settings_repository_test.go b/internal/repository/loyalty_settings_repository_test.go new file mode 100644 index 0000000..233c66d --- /dev/null +++ b/internal/repository/loyalty_settings_repository_test.go @@ -0,0 +1,149 @@ +package repository_test + +import ( + "context" + "os" + "testing" + "time" + + "github.com/google/uuid" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "gorm.io/driver/postgres" + "gorm.io/gorm" + "gorm.io/gorm/logger" + + "apskel-pos-be/internal/constants" + applogger "apskel-pos-be/internal/logger" + "apskel-pos-be/internal/processor" + "apskel-pos-be/internal/repository" +) + +// Reads and writes loyalty settings through the processor against Postgres. Needs +// TEST_DATABASE_URL pointing at a migrated database; see wallet_repository_test.go. +func TestLoyaltySettings_AgainstPostgres(t *testing.T) { + dsn := os.Getenv("TEST_DATABASE_URL") + if dsn == "" { + t.Skip("TEST_DATABASE_URL not set") + } + applogger.Setup("fatal", "json") + db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{Logger: logger.Default.LogMode(logger.Silent)}) + require.NoError(t, err) + ctx := context.Background() + + org, otherOrg, outlet, admin := uuid.New(), uuid.New(), uuid.New(), uuid.New() + exec := func(q string, args ...any) { + t.Helper() + require.NoError(t, db.Exec(q, args...).Error) + } + exec(`INSERT INTO organizations (id, name, plan_type) VALUES (?, 'loyalty test', 'basic'), (?, 'other', 'basic')`, org, otherOrg) + exec(`INSERT INTO outlets (id, organization_id, name) VALUES (?, ?, 'Kemang')`, outlet, org) + // A setting that is not a loyalty setting must be left alone. + exec(`INSERT INTO outlet_settings (outlet_id, key, value) VALUES (?, 'receipt.footer', 'Terima kasih')`, outlet) + t.Cleanup(func() { + db.Exec(`DELETE FROM loyalty_setting_changes WHERE organization_id IN ?`, []uuid.UUID{org, otherOrg}) + db.Exec(`DELETE FROM outlet_settings WHERE outlet_id = ?`, outlet) + db.Exec(`DELETE FROM organization_settings WHERE organization_id IN ?`, []uuid.UUID{org, otherOrg}) + db.Exec(`DELETE FROM outlets WHERE id = ?`, outlet) + db.Exec(`DELETE FROM organizations WHERE id IN ?`, []uuid.UUID{org, otherOrg}) + }) + + repo := repository.NewLoyaltySettingsRepository(db) + p := processor.NewLoyaltySettingsProcessor(repo, repository.NewTxManager(db)) + + // No settings: every PRD default. + settings, err := p.Outlet(ctx, outlet) + require.NoError(t, err) + assert.False(t, settings.Point.Enabled) + assert.Equal(t, int64(100), settings.Point.EarnPerAmount) + assert.Equal(t, int64(25000), settings.Coin.EarnPerAmount) + assert.Nil(t, settings.Point.MaxPerOrder) + assert.Equal(t, int64(100), settings.PointPayment.MaxPaymentPercent) + + // Change three keys. + settings.Point.Enabled = true + settings.Point.EarnPerAmount = 1000 + settings.Coin.MaxPerOrder = ptrInt64(5) + changes, err := p.UpdateOutlet(ctx, org, outlet, admin, *settings) + require.NoError(t, err) + assert.Len(t, changes, 3) + + var stored []struct{ Key, Value string } + require.NoError(t, db.Raw(`SELECT key, value FROM outlet_settings WHERE outlet_id = ? ORDER BY key`, outlet).Scan(&stored).Error) + assert.Equal(t, []struct{ Key, Value string }{ + {constants.LoyaltyCoinMaxPerOrderKey, "5"}, + {constants.LoyaltyPointEarnPerAmountKey, "1000"}, + {constants.LoyaltyPointEnabledKey, "true"}, + {"receipt.footer", "Terima kasih"}, + }, stored, "only the changed keys are stored, next to the untouched non-loyalty key") + + history, err := p.ListChanges(ctx, org, &outlet, 1, 20) + require.NoError(t, err) + require.Len(t, history.Data, 3) + for _, c := range history.Data { + assert.Equal(t, admin, c.ChangedBy) + assert.Nil(t, c.OldValue, "%s was on its default", c.Key) + assert.NotNil(t, c.NewValue) + } + + // A second change records the old value. + settings.Point.EarnPerAmount = 500 + changes, err = p.UpdateOutlet(ctx, org, outlet, admin, *settings) + require.NoError(t, err) + require.Len(t, changes, 1) + assert.Equal(t, "1000", *changes[0].OldValue) + assert.Equal(t, "500", *changes[0].NewValue) + + // Another organization cannot change this outlet. + _, err = p.UpdateOutlet(ctx, otherOrg, outlet, admin, *settings) + assert.ErrorIs(t, err, repository.ErrLoyaltyOutletNotFound) + + // Writing outside a transaction is refused. + assert.Error(t, repo.SetOutletValue(ctx, outlet, constants.LoyaltyPointEnabledKey, nil)) + + // A save must wait while another save of the same organization holds the lock, so + // two admins saving at once cannot both compute their change from the same old + // value. Hold the lock in another transaction and check the save blocks until it + // is released. + txm := repository.NewTxManager(db) + holding, release, holderDone := make(chan struct{}), make(chan struct{}), make(chan error, 1) + go func() { + holderDone <- txm.WithTransaction(ctx, func(ctx context.Context) error { + if err := repo.LockScope(ctx, org); err != nil { + return err + } + close(holding) + <-release + return nil + }) + }() + <-holding + + orgSettings, err := p.Organization(ctx, org) + require.NoError(t, err) + orgSettings.PointValue = 200 + saved := make(chan error, 1) + go func() { + _, _, err := p.UpdateOrganization(ctx, org, admin, *orgSettings) + saved <- err + }() + select { + case err := <-saved: + t.Fatalf("the save finished while another transaction held the lock (err: %v)", err) + case <-time.After(300 * time.Millisecond): + } + close(release) + require.NoError(t, <-holderDone) + require.NoError(t, <-saved) + + value, err := p.PointValue(ctx, org) + require.NoError(t, err) + assert.Equal(t, int64(200), value) + + // The whole organization's history includes the outlet's changes. + all, err := p.ListChanges(ctx, org, nil, 1, 100) + require.NoError(t, err) + assert.EqualValues(t, 5, all.Pagination.Total, "four outlet changes and one organization change") +} + +func ptrInt64(v int64) *int64 { return &v } diff --git a/internal/repository/payment_code_repository.go b/internal/repository/payment_code_repository.go new file mode 100644 index 0000000..f76fc5b --- /dev/null +++ b/internal/repository/payment_code_repository.go @@ -0,0 +1,103 @@ +package repository + +import ( + "context" + "errors" + "fmt" + "strings" + "time" + + "github.com/google/uuid" + "github.com/redis/go-redis/v9" +) + +var ( + // ErrPaymentCodeTaken means the code is already live for someone; draw another. + ErrPaymentCodeTaken = errors.New("payment code already in use") + // ErrPaymentCodeNotFound means the code does not exist: never issued, expired, or + // already used. + ErrPaymentCodeNotFound = errors.New("payment code not found") + // ErrPaymentCodeWrongCustomer means the code belongs to another customer. + ErrPaymentCodeWrongCustomer = errors.New("payment code belongs to another customer") +) + +// PaymentCodeRepository keeps one-time EnakPoint payment codes in Redis +// (docs/prd-point-coin.md F9). A code expires by TTL and is removed when used. +type PaymentCodeRepository interface { + // Save stores a code for a customer for ttl, and retires the customer's previous + // code so only the newest one works. ErrPaymentCodeTaken if the code is live. + Save(ctx context.Context, code string, customerID uuid.UUID, ttl time.Duration) error + // Consume uses a code up if it belongs to the customer. A code of another customer + // is left in place, so a cashier scanning it against the wrong order does not burn + // it for its owner. + Consume(ctx context.Context, code string, customerID uuid.UUID) error +} + +type paymentCodeRepository struct { + client *redis.Client +} + +func NewPaymentCodeRepository(client *redis.Client) PaymentCodeRepository { + return &paymentCodeRepository{client: client} +} + +func paymentCodeKey(code string) string { return "wallet:paycode:" + code } + +func paymentCodeCustomerKey(customerID uuid.UUID) string { + return "wallet:paycode:customer:" + customerID.String() +} + +func (r *paymentCodeRepository) Save(ctx context.Context, code string, customerID uuid.UUID, ttl time.Duration) error { + ok, err := r.client.SetNX(ctx, paymentCodeKey(code), customerID.String(), ttl).Result() + if err != nil { + return fmt.Errorf("failed to store payment code: %w", err) + } + if !ok { + return ErrPaymentCodeTaken + } + previous, err := r.client.GetSet(ctx, paymentCodeCustomerKey(customerID), code).Result() + if err != nil && !errors.Is(err, redis.Nil) { + return fmt.Errorf("failed to track payment code: %w", err) + } + r.client.Expire(ctx, paymentCodeCustomerKey(customerID), ttl) + if previous != "" && previous != code { + // Only if it is still that customer's: the number may have been reissued. + if err := r.compareAndDelete(ctx, previous, customerID); err != nil && !errors.Is(err, ErrPaymentCodeNotFound) && !errors.Is(err, ErrPaymentCodeWrongCustomer) { + return err + } + } + return nil +} + +// consumeScript deletes a code only if it belongs to the given customer, in one step. +// Returns 1 when used up, 0 when missing, -1 when it belongs to someone else. +var consumeScript = redis.NewScript(` +local owner = redis.call('GET', KEYS[1]) +if not owner then return 0 end +if owner ~= ARGV[1] then return -1 end +redis.call('DEL', KEYS[1]) +return 1 +`) + +func (r *paymentCodeRepository) Consume(ctx context.Context, code string, customerID uuid.UUID) error { + code = strings.TrimSpace(code) + if code == "" { + return ErrPaymentCodeNotFound + } + return r.compareAndDelete(ctx, code, customerID) +} + +func (r *paymentCodeRepository) compareAndDelete(ctx context.Context, code string, customerID uuid.UUID) error { + result, err := consumeScript.Run(ctx, r.client, []string{paymentCodeKey(code)}, customerID.String()).Int() + if err != nil { + return fmt.Errorf("failed to use payment code: %w", err) + } + switch result { + case 1: + return nil + case -1: + return ErrPaymentCodeWrongCustomer + default: + return ErrPaymentCodeNotFound + } +} diff --git a/internal/repository/payment_method_repository.go b/internal/repository/payment_method_repository.go index 41977b7..7a9cd18 100644 --- a/internal/repository/payment_method_repository.go +++ b/internal/repository/payment_method_repository.go @@ -75,6 +75,8 @@ func (r *PaymentMethodRepositoryImpl) List(ctx context.Context, filters map[stri case "search": searchValue := "%" + value.(string) + "%" query = query.Where("name ILIKE ? OR processor ILIKE ?", searchValue, searchValue) + case "exclude_type": + query = query.Where("type <> ?", value) default: query = query.Where(key+" = ?", value) } diff --git a/internal/repository/point_payment_repository.go b/internal/repository/point_payment_repository.go new file mode 100644 index 0000000..43508bf --- /dev/null +++ b/internal/repository/point_payment_repository.go @@ -0,0 +1,339 @@ +package repository + +import ( + "context" + "errors" + "fmt" + "time" + + "github.com/google/uuid" + "gorm.io/gorm" + + "apskel-pos-be/internal/constants" + "apskel-pos-be/internal/entities" +) + +// ErrPointPaymentOrderNotFound means the order does not exist. +var ErrPointPaymentOrderNotFound = errors.New("point payment: order not found") + +// PointPaymentOrder is what paying with EnakPoint needs to know about an order. +type PointPaymentOrder struct { + ID uuid.UUID + OrganizationID uuid.UUID + OutletID uuid.UUID + OrderNumber string + OutletName string + CustomerID *uuid.UUID + TotalAmount float64 + PaymentStatus string + IsVoid bool + CustomerIsDefault *bool + CustomerIsActive *bool +} + +// PointPaymentRepository reads and writes what paying an order with EnakPoint touches +// (docs/prd-point-coin.md F9). Unlike the order and payment repositories, every method +// joins the caller's transaction, since the payment row, the balance and the order +// must change together. +type PointPaymentRepository interface { + // GetOrder reads the order; with lock it also locks the order row for the rest of + // the transaction, so two payments of the same order queue up. + GetOrder(ctx context.Context, orderID uuid.UUID, lock bool) (*PointPaymentOrder, error) + // GetPaymentMethod returns a method's organization and type. + GetPaymentMethod(ctx context.Context, methodID uuid.UUID) (organizationID uuid.UUID, methodType string, err error) + // TotalPaid sums the order's completed payments, as the rest of the order flow does. + TotalPaid(ctx context.Context, orderID uuid.UUID) (float64, error) + // PaidWithPoints sums the rupiah of the order's completed EnakPoint payments. + PaidWithPoints(ctx context.Context, orderID uuid.UUID) (float64, error) + // PointMethodID returns the organization's EnakPoint payment method. + PointMethodID(ctx context.Context, organizationID uuid.UUID) (uuid.UUID, error) + InsertPayment(ctx context.Context, payment *entities.Payment) error + // UpdateOrderAfterPayment stores what is left to pay and marks the order paid when + // nothing is. + UpdateOrderAfterPayment(ctx context.Context, orderID uuid.UUID, remaining float64, completed bool) error + + // ListPointPayments returns the order's EnakPoint payments with their PAYMENT rows. + ListPointPayments(ctx context.Context, orderID uuid.UUID) ([]PointPaymentRow, error) + // PaymentAllocations returns the lots a PAYMENT row took from, longest-lasting first. + PaymentAllocations(ctx context.Context, ledgerID uuid.UUID) ([]PointPaymentAllocation, error) + // RefundedByOriginLot sums, per original lot, what PAYMENT_REFUND rows have already + // returned for a PAYMENT row. + RefundedByOriginLot(ctx context.Context, ledgerID uuid.UUID) (map[uuid.UUID]int64, error) + // RefundableByOtherMethods is what the order's non-EnakPoint payments can still give + // back: paid minus already refunded. + RefundableByOtherMethods(ctx context.Context, orderID uuid.UUID) (float64, error) +} + +type pointPaymentRepository struct { + db *gorm.DB +} + +func NewPointPaymentRepository(db *gorm.DB) PointPaymentRepository { + return &pointPaymentRepository{db: db} +} + +func (r *pointPaymentRepository) GetOrder(ctx context.Context, orderID uuid.UUID, lock bool) (*PointPaymentOrder, error) { + lockClause := "" + if lock { + lockClause = "FOR UPDATE OF o" + } + var rows []struct { + ID string + OrganizationID string + OutletID string + OrderNumber string + OutletName string + CustomerID *string + TotalAmount float64 + PaymentStatus string + IsVoid bool + CustomerIsDefault *bool + CustomerIsActive *bool + } + err := DBFromContext(ctx, r.db).WithContext(ctx).Raw(` + SELECT o.id::text AS id, o.organization_id::text AS organization_id, o.outlet_id::text AS outlet_id, + o.order_number, COALESCE(ou.name, '') AS outlet_name, o.customer_id::text AS customer_id, + o.total_amount, o.payment_status, COALESCE(o.is_void, false) AS is_void, + c.is_default AS customer_is_default, c.is_active AS customer_is_active + FROM orders o + LEFT JOIN outlets ou ON ou.id = o.outlet_id + LEFT JOIN customers c ON c.id = o.customer_id + WHERE o.id = ? + `+lockClause, orderID).Scan(&rows).Error + if err != nil { + return nil, fmt.Errorf("failed to read order: %w", err) + } + if len(rows) == 0 { + return nil, ErrPointPaymentOrderNotFound + } + row := rows[0] + order := &PointPaymentOrder{ + OrderNumber: row.OrderNumber, + OutletName: row.OutletName, + TotalAmount: row.TotalAmount, + PaymentStatus: row.PaymentStatus, + IsVoid: row.IsVoid, + CustomerIsDefault: row.CustomerIsDefault, + CustomerIsActive: row.CustomerIsActive, + } + order.ID, _ = uuid.Parse(row.ID) + order.OrganizationID, _ = uuid.Parse(row.OrganizationID) + order.OutletID, _ = uuid.Parse(row.OutletID) + if row.CustomerID != nil { + if id, err := uuid.Parse(*row.CustomerID); err == nil { + order.CustomerID = &id + } + } + return order, nil +} + +func (r *pointPaymentRepository) GetPaymentMethod(ctx context.Context, methodID uuid.UUID) (uuid.UUID, string, error) { + var rows []struct { + OrganizationID string + Type string + } + err := DBFromContext(ctx, r.db).WithContext(ctx).Raw(` + SELECT organization_id::text AS organization_id, type FROM payment_methods WHERE id = ?`, methodID).Scan(&rows).Error + if err != nil { + return uuid.Nil, "", fmt.Errorf("failed to read payment method: %w", err) + } + if len(rows) == 0 { + return uuid.Nil, "", fmt.Errorf("payment method not found") + } + org, _ := uuid.Parse(rows[0].OrganizationID) + return org, rows[0].Type, nil +} + +func (r *pointPaymentRepository) TotalPaid(ctx context.Context, orderID uuid.UUID) (float64, error) { + var total float64 + err := DBFromContext(ctx, r.db).WithContext(ctx).Raw(` + SELECT COALESCE(SUM(amount), 0) FROM payments WHERE order_id = ? AND status = ?`, + orderID, entities.PaymentTransactionStatusCompleted).Scan(&total).Error + if err != nil { + return 0, fmt.Errorf("failed to sum payments: %w", err) + } + return total, nil +} + +func (r *pointPaymentRepository) PaidWithPoints(ctx context.Context, orderID uuid.UUID) (float64, error) { + var total float64 + err := DBFromContext(ctx, r.db).WithContext(ctx).Raw(` + SELECT COALESCE(SUM(p.amount), 0) FROM payments p + JOIN payment_methods pm ON pm.id = p.payment_method_id + WHERE p.order_id = ? AND p.status = ? AND pm.type = ?`, + orderID, entities.PaymentTransactionStatusCompleted, constants.PaymentMethodTypePoint).Scan(&total).Error + if err != nil { + return 0, fmt.Errorf("failed to sum EnakPoint payments: %w", err) + } + return total, nil +} + +func (r *pointPaymentRepository) InsertPayment(ctx context.Context, payment *entities.Payment) error { + if err := DBFromContext(ctx, r.db).WithContext(ctx).Create(payment).Error; err != nil { + return fmt.Errorf("failed to create payment: %w", err) + } + return nil +} + +func (r *pointPaymentRepository) UpdateOrderAfterPayment(ctx context.Context, orderID uuid.UUID, remaining float64, completed bool) error { + paymentStatus := entities.PaymentStatusPartial + if completed { + paymentStatus = entities.PaymentStatusCompleted + } + err := DBFromContext(ctx, r.db).WithContext(ctx).Exec(` + UPDATE orders SET remaining_amount = ?, payment_status = ?, + status = CASE WHEN ? THEN ? ELSE status END, updated_at = NOW() + WHERE id = ?`, + remaining, paymentStatus, completed, entities.OrderStatusCompleted, orderID).Error + if err != nil { + return fmt.Errorf("failed to update order after payment: %w", err) + } + return nil +} + +func (r *pointPaymentRepository) PointMethodID(ctx context.Context, organizationID uuid.UUID) (uuid.UUID, error) { + var ids []string + err := DBFromContext(ctx, r.db).WithContext(ctx). + Table("payment_methods"). + Where("organization_id = ? AND type = ?", organizationID, constants.PaymentMethodTypePoint). + Limit(1). + Pluck("id::text", &ids).Error + if err != nil { + return uuid.Nil, fmt.Errorf("failed to find the EnakPoint payment method: %w", err) + } + if len(ids) == 0 { + return uuid.Nil, fmt.Errorf("the organization has no EnakPoint payment method") + } + return uuid.Parse(ids[0]) +} + +// PointPaymentRow is one EnakPoint payment of an order, for refunding it. +type PointPaymentRow struct { + PaymentID uuid.UUID + Status string + PointsUsed int64 + PointValue float64 + RefundAmount float64 + // The PAYMENT ledger row that took the balance; nil if none was written. + LedgerID *uuid.UUID + CustomerID *uuid.UUID + OutletID *uuid.UUID +} + +// PointPaymentAllocation is how much a PAYMENT took from one lot, with that lot's +// expiry, so a refund can return it to the same expiry. +type PointPaymentAllocation struct { + LotID uuid.UUID + Amount int64 + ExpiresAt *time.Time +} + +func (r *pointPaymentRepository) ListPointPayments(ctx context.Context, orderID uuid.UUID) ([]PointPaymentRow, error) { + var rows []struct { + PaymentID string + Status string + PointsUsed int64 + PointValue float64 + RefundAmount float64 + LedgerID *string + CustomerID *string + OutletID *string + } + err := DBFromContext(ctx, r.db).WithContext(ctx).Raw(` + SELECT p.id::text AS payment_id, p.status, p.points_used, p.point_value, + COALESCE(p.refund_amount, 0) AS refund_amount, + t.id::text AS ledger_id, t.customer_id::text AS customer_id, t.outlet_id::text AS outlet_id + FROM payments p + JOIN payment_methods pm ON pm.id = p.payment_method_id + LEFT JOIN wallet_transactions t ON t.reference_type = ? AND t.reference_id = p.id AND t.type = ? + WHERE p.order_id = ? AND pm.type = ? AND p.points_used IS NOT NULL + ORDER BY p.created_at, p.id`, + constants.WalletRefTypePayment, constants.WalletTxTypePayment, orderID, constants.PaymentMethodTypePoint). + Scan(&rows).Error + if err != nil { + return nil, fmt.Errorf("failed to list EnakPoint payments: %w", err) + } + out := make([]PointPaymentRow, 0, len(rows)) + for _, row := range rows { + p := PointPaymentRow{Status: row.Status, PointsUsed: row.PointsUsed, PointValue: row.PointValue, RefundAmount: row.RefundAmount} + p.PaymentID, _ = uuid.Parse(row.PaymentID) + p.LedgerID = parseOptionalUUID(row.LedgerID) + p.CustomerID = parseOptionalUUID(row.CustomerID) + p.OutletID = parseOptionalUUID(row.OutletID) + out = append(out, p) + } + return out, nil +} + +func (r *pointPaymentRepository) PaymentAllocations(ctx context.Context, ledgerID uuid.UUID) ([]PointPaymentAllocation, error) { + var rows []struct { + LotID string + Amount int64 + ExpiresAt *time.Time + } + // Longest-lasting first: a partial refund gives back the balance that keeps longest. + err := DBFromContext(ctx, r.db).WithContext(ctx).Raw(` + SELECT a.lot_id::text AS lot_id, a.amount, l.expires_at + FROM wallet_lot_allocations a JOIN wallet_lots l ON l.id = a.lot_id + WHERE a.transaction_id = ? + ORDER BY l.expires_at DESC NULLS FIRST, l.created_at DESC, l.id`, ledgerID).Scan(&rows).Error + if err != nil { + return nil, fmt.Errorf("failed to list payment allocations: %w", err) + } + out := make([]PointPaymentAllocation, 0, len(rows)) + for _, row := range rows { + id, err := uuid.Parse(row.LotID) + if err != nil { + continue + } + out = append(out, PointPaymentAllocation{LotID: id, Amount: row.Amount, ExpiresAt: row.ExpiresAt}) + } + return out, nil +} + +func (r *pointPaymentRepository) RefundedByOriginLot(ctx context.Context, ledgerID uuid.UUID) (map[uuid.UUID]int64, error) { + var rows []struct { + OriginLotID string + Amount int64 + } + err := DBFromContext(ctx, r.db).WithContext(ctx).Raw(` + SELECT l.origin_lot_id::text AS origin_lot_id, SUM(l.original_amount) AS amount + FROM wallet_transactions t JOIN wallet_lots l ON l.source_transaction_id = t.id + WHERE t.reverses_transaction_id = ? AND t.type = ? AND l.origin_lot_id IS NOT NULL + GROUP BY l.origin_lot_id`, ledgerID, constants.WalletTxTypePaymentRefund).Scan(&rows).Error + if err != nil { + return nil, fmt.Errorf("failed to sum payment refunds: %w", err) + } + out := make(map[uuid.UUID]int64, len(rows)) + for _, row := range rows { + if id, err := uuid.Parse(row.OriginLotID); err == nil { + out[id] = row.Amount + } + } + return out, nil +} + +func (r *pointPaymentRepository) RefundableByOtherMethods(ctx context.Context, orderID uuid.UUID) (float64, error) { + var total float64 + err := DBFromContext(ctx, r.db).WithContext(ctx).Raw(` + SELECT COALESCE(SUM(p.amount - COALESCE(p.refund_amount, 0)), 0) + FROM payments p JOIN payment_methods pm ON pm.id = p.payment_method_id + WHERE p.order_id = ? AND pm.type <> ? AND p.status IN (?, ?)`, + orderID, constants.PaymentMethodTypePoint, + entities.PaymentTransactionStatusCompleted, entities.PaymentTransactionStatusRefunded).Scan(&total).Error + if err != nil { + return 0, fmt.Errorf("failed to sum refundable payments: %w", err) + } + return total, nil +} + +func parseOptionalUUID(s *string) *uuid.UUID { + if s == nil { + return nil + } + id, err := uuid.Parse(*s) + if err != nil { + return nil + } + return &id +} diff --git a/internal/repository/tx_manager.go b/internal/repository/tx_manager.go index ee9a3f8..33760c2 100644 --- a/internal/repository/tx_manager.go +++ b/internal/repository/tx_manager.go @@ -50,3 +50,10 @@ func (m *TxManager) WithTransactionOptions(ctx context.Context, opts *sql.TxOpti return fn(ctxTx) }, opts) } + +// DetachTransaction returns ctx without the caller's transaction, so work started from +// it (such as loyalty earning after a payment) reads committed data and commits on its +// own, whatever happens to the caller's transaction. +func DetachTransaction(ctx context.Context) context.Context { + return context.WithValue(ctx, txKey, (*gorm.DB)(nil)) +} diff --git a/internal/repository/wallet_admin_repository.go b/internal/repository/wallet_admin_repository.go new file mode 100644 index 0000000..f3035c2 --- /dev/null +++ b/internal/repository/wallet_admin_repository.go @@ -0,0 +1,126 @@ +package repository + +import ( + "context" + "fmt" + + "github.com/google/uuid" + "gorm.io/gorm" + + "apskel-pos-be/internal/entities" +) + +// WalletCustomer is the customer a dashboard wallet screen is about. +type WalletCustomer struct { + ID uuid.UUID + Name string + Phone *string +} + +// WalletAdminRepository serves what the dashboard adds on top of the customer's own +// wallet view (docs/prd-point-coin.md F7): the raw balances, every lot with balance, +// and the real names behind a ledger row. Nothing here changes a balance. +type WalletAdminRepository interface { + // GetCustomer returns ErrWalletNotFound unless the customer exists and belongs to + // the organization, so one organization can never read another's customers. + GetCustomer(ctx context.Context, organizationID, customerID uuid.UUID) (*WalletCustomer, error) + // GetWallet returns nil, nil for a customer who has never had a wallet. + GetWallet(ctx context.Context, customerID uuid.UUID) (*entities.CustomerWallet, error) + // ListLotsWithBalance returns every lot that still holds something, expired or + // not, in K9 spending order. + ListLotsWithBalance(ctx context.Context, customerID uuid.UUID) ([]entities.WalletLot, error) + CustomerNames(ctx context.Context, ids []uuid.UUID) (map[uuid.UUID]string, error) + UserNames(ctx context.Context, ids []uuid.UUID) (map[uuid.UUID]string, error) + OutletNames(ctx context.Context, ids []uuid.UUID) (map[uuid.UUID]string, error) +} + +type walletAdminRepository struct { + db *gorm.DB +} + +func NewWalletAdminRepository(db *gorm.DB) WalletAdminRepository { + return &walletAdminRepository{db: db} +} + +func (r *walletAdminRepository) GetCustomer(ctx context.Context, organizationID, customerID uuid.UUID) (*WalletCustomer, error) { + var customers []WalletCustomer + err := DBFromContext(ctx, r.db).WithContext(ctx). + Table("customers"). + Select("id, name, COALESCE(phone_number, phone) AS phone"). + Where("id = ? AND organization_id = ?", customerID, organizationID). + Limit(1). + Scan(&customers).Error + if err != nil { + return nil, fmt.Errorf("failed to get customer: %w", err) + } + if len(customers) == 0 { + return nil, ErrWalletNotFound + } + return &customers[0], nil +} + +func (r *walletAdminRepository) GetWallet(ctx context.Context, customerID uuid.UUID) (*entities.CustomerWallet, error) { + var wallets []entities.CustomerWallet + err := DBFromContext(ctx, r.db).WithContext(ctx). + Where("customer_id = ?", customerID). + Limit(1). + Find(&wallets).Error + if err != nil { + return nil, fmt.Errorf("failed to get customer wallet: %w", err) + } + if len(wallets) == 0 { + return nil, nil + } + return &wallets[0], nil +} + +func (r *walletAdminRepository) ListLotsWithBalance(ctx context.Context, customerID uuid.UUID) ([]entities.WalletLot, error) { + var lots []entities.WalletLot + err := DBFromContext(ctx, r.db).WithContext(ctx). + Where("customer_id = ? AND remaining_amount > 0", customerID). + Order("currency, expires_at NULLS LAST, created_at, id"). + Find(&lots).Error + if err != nil { + return nil, fmt.Errorf("failed to list wallet lots: %w", err) + } + return lots, nil +} + +func (r *walletAdminRepository) CustomerNames(ctx context.Context, ids []uuid.UUID) (map[uuid.UUID]string, error) { + return r.names(ctx, "customers", ids) +} + +func (r *walletAdminRepository) UserNames(ctx context.Context, ids []uuid.UUID) (map[uuid.UUID]string, error) { + return r.names(ctx, "users", ids) +} + +func (r *walletAdminRepository) OutletNames(ctx context.Context, ids []uuid.UUID) (map[uuid.UUID]string, error) { + return r.names(ctx, "outlets", ids) +} + +// names looks up the name column of a table by id. The table name is never taken +// from user input. +func (r *walletAdminRepository) names(ctx context.Context, table string, ids []uuid.UUID) (map[uuid.UUID]string, error) { + names := make(map[uuid.UUID]string, len(ids)) + if len(ids) == 0 { + return names, nil + } + var rows []struct { + ID string + Name string + } + err := DBFromContext(ctx, r.db).WithContext(ctx). + Table(table). + Select("id::text AS id, name"). + Where("id IN ?", ids). + Scan(&rows).Error + if err != nil { + return nil, fmt.Errorf("failed to look up %s names: %w", table, err) + } + for _, row := range rows { + if id, err := uuid.Parse(row.ID); err == nil { + names[id] = row.Name + } + } + return names, nil +} diff --git a/internal/repository/wallet_expiry_repository.go b/internal/repository/wallet_expiry_repository.go new file mode 100644 index 0000000..c7e0b99 --- /dev/null +++ b/internal/repository/wallet_expiry_repository.go @@ -0,0 +1,118 @@ +package repository + +import ( + "context" + "fmt" + "time" + + "github.com/google/uuid" + "gorm.io/gorm" +) + +// DueLot is a lot whose expiry has passed and that still holds something. +type DueLot struct { + ID uuid.UUID + CustomerID uuid.UUID + Currency string + Remaining int64 + ExpiresAt time.Time + // The description of the row that created the lot, for the EXPIRE row's. + SourceDescription string +} + +// UpcomingExpiry is how much of a customer's balance expires on one day. +type UpcomingExpiry struct { + CustomerID uuid.UUID + // A calendar date in walletDisplayTimeZone, formatted YYYY-MM-DD. + Date string + Amount int64 +} + +// WalletExpiryRepository finds what the expiry job has to do (docs/prd-point-coin.md +// F12). Balances only change through WalletProcessor. +type WalletExpiryRepository interface { + // ListDueLots returns up to limit lots due at asOf, the longest overdue first. It + // takes no lock: locking a lot before its wallet would deadlock against payments, + // which lock the wallet first. WalletProcessor.ExpireLot locks and reads again. + ListDueLots(ctx context.Context, asOf time.Time, limit int) ([]DueLot, error) + + // OrganizationsWithUpcomingExpiry lists the organizations that have balance + // expiring after asOf. + OrganizationsWithUpcomingExpiry(ctx context.Context, asOf time.Time) ([]uuid.UUID, error) + // UpcomingUnreminded sums, per customer and expiry day, the balance of one currency + // of an organization expiring after asOf and up to until, leaving out the days the + // customer has already been reminded of. + UpcomingUnreminded(ctx context.Context, organizationID uuid.UUID, currency string, asOf, until time.Time) ([]UpcomingExpiry, error) + // MarkReminded records a reminder, and reports false when it was already recorded, + // by this run or another. + MarkReminded(ctx context.Context, reminder UpcomingExpiry, currency string) (bool, error) +} + +type walletExpiryRepository struct { + db *gorm.DB +} + +func NewWalletExpiryRepository(db *gorm.DB) WalletExpiryRepository { + return &walletExpiryRepository{db: db} +} + +func (r *walletExpiryRepository) ListDueLots(ctx context.Context, asOf time.Time, limit int) ([]DueLot, error) { + var lots []DueLot + err := DBFromContext(ctx, r.db).WithContext(ctx).Raw(` + SELECT l.id, l.customer_id, l.currency, l.remaining_amount AS remaining, l.expires_at, + t.description AS source_description + FROM wallet_lots l + JOIN wallet_transactions t ON t.id = l.source_transaction_id + WHERE l.remaining_amount > 0 AND l.expires_at <= ? + ORDER BY l.expires_at, l.id + LIMIT ?`, asOf, limit).Scan(&lots).Error + if err != nil { + return nil, fmt.Errorf("failed to list due wallet lots: %w", err) + } + return lots, nil +} + +func (r *walletExpiryRepository) OrganizationsWithUpcomingExpiry(ctx context.Context, asOf time.Time) ([]uuid.UUID, error) { + var ids []uuid.UUID + err := DBFromContext(ctx, r.db).WithContext(ctx).Raw(` + SELECT DISTINCT organization_id FROM wallet_lots + WHERE remaining_amount > 0 AND expires_at > ?`, asOf).Scan(&ids).Error + if err != nil { + return nil, fmt.Errorf("failed to list organizations with expiring balances: %w", err) + } + return ids, nil +} + +func (r *walletExpiryRepository) UpcomingUnreminded(ctx context.Context, organizationID uuid.UUID, currency string, asOf, until time.Time) ([]UpcomingExpiry, error) { + var rows []UpcomingExpiry + err := DBFromContext(ctx, r.db).WithContext(ctx).Raw(` + WITH by_day AS ( + SELECT customer_id, (expires_at AT TIME ZONE ?)::date AS day, SUM(remaining_amount) AS amount + FROM wallet_lots + WHERE organization_id = ? AND currency = ? AND remaining_amount > 0 + AND expires_at > ? AND expires_at <= ? + GROUP BY customer_id, day + ) + SELECT d.customer_id, to_char(d.day, 'YYYY-MM-DD') AS date, d.amount + FROM by_day d + LEFT JOIN wallet_expiry_reminders w + ON w.customer_id = d.customer_id AND w.currency = ? AND w.expiry_date = d.day + WHERE w.customer_id IS NULL + ORDER BY d.day, d.customer_id`, + walletDisplayTimeZone, organizationID, currency, asOf, until, currency).Scan(&rows).Error + if err != nil { + return nil, fmt.Errorf("failed to list upcoming expiry: %w", err) + } + return rows, nil +} + +func (r *walletExpiryRepository) MarkReminded(ctx context.Context, reminder UpcomingExpiry, currency string) (bool, error) { + res := DBFromContext(ctx, r.db).WithContext(ctx).Exec(` + INSERT INTO wallet_expiry_reminders (customer_id, currency, expiry_date, amount) + VALUES (?, ?, ?::date, ?) + ON CONFLICT DO NOTHING`, reminder.CustomerID, currency, reminder.Date, reminder.Amount) + if res.Error != nil { + return false, fmt.Errorf("failed to record expiry reminder: %w", res.Error) + } + return res.RowsAffected == 1, nil +} diff --git a/internal/repository/wallet_migration_repository.go b/internal/repository/wallet_migration_repository.go new file mode 100644 index 0000000..cfef523 --- /dev/null +++ b/internal/repository/wallet_migration_repository.go @@ -0,0 +1,134 @@ +package repository + +import ( + "context" + "fmt" + + "github.com/google/uuid" + "gorm.io/gorm" + + "apskel-pos-be/internal/constants" + "apskel-pos-be/internal/entities" +) + +// LegacyBalance is what one customer holds in customer_points and customer_tokens, +// the tables the wallet replaces (docs/prd-point-coin.md §10). +type LegacyBalance struct { + CustomerID uuid.UUID + // Nil when the customer has no customer_points row. + PointsRowID *uuid.UUID + Points int64 + Tokens []entities.CustomerTokens +} + +// Coins is the sum of every token type: all of them become EnakCoin (Q6). +func (b LegacyBalance) Coins() int64 { + var total int64 + for _, t := range b.Tokens { + total += t.Balance + } + return total +} + +// WalletMigrationTotals compares the legacy tables with what has been migrated. +type WalletMigrationTotals struct { + LegacyPoints int64 + LegacyCoins int64 + MigratedPoints int64 + MigratedCoins int64 + WalletPoints int64 + WalletCoins int64 +} + +// WalletMigrationRepository reads the legacy balances for the one-time move into the +// wallet. The writes go through the wallet processor like any other credit. +type WalletMigrationRepository interface { + // ListLegacyCustomers returns, in id order, up to limit customers after the given + // id that have a row in customer_points or customer_tokens. + ListLegacyCustomers(ctx context.Context, after uuid.UUID, limit int) ([]uuid.UUID, error) + GetLegacyBalance(ctx context.Context, customerID uuid.UUID) (*LegacyBalance, error) + // SumMigrated returns how much has already been credited to the customer by + // MIGRATION ledger rows in the currency. + SumMigrated(ctx context.Context, customerID uuid.UUID, currency string) (int64, error) + Totals(ctx context.Context) (*WalletMigrationTotals, error) +} + +type walletMigrationRepository struct { + db *gorm.DB +} + +func NewWalletMigrationRepository(db *gorm.DB) WalletMigrationRepository { + return &walletMigrationRepository{db: db} +} + +func (r *walletMigrationRepository) ListLegacyCustomers(ctx context.Context, after uuid.UUID, limit int) ([]uuid.UUID, error) { + var ids []uuid.UUID + err := DBFromContext(ctx, r.db).WithContext(ctx).Raw(` + SELECT customer_id FROM ( + SELECT customer_id FROM customer_points + UNION + SELECT customer_id FROM customer_tokens + ) legacy + WHERE customer_id > ? + ORDER BY customer_id + LIMIT ?`, after, limit). + Scan(&ids).Error + if err != nil { + return nil, fmt.Errorf("failed to list legacy customers: %w", err) + } + return ids, nil +} + +func (r *walletMigrationRepository) GetLegacyBalance(ctx context.Context, customerID uuid.UUID) (*LegacyBalance, error) { + db := DBFromContext(ctx, r.db).WithContext(ctx) + balance := &LegacyBalance{CustomerID: customerID} + + // Find rather than First: many customers have tokens but no points row, and First + // would log each of them as a "record not found" error. + var points []entities.CustomerPoints + if err := db.Where("customer_id = ?", customerID).Limit(1).Find(&points).Error; err != nil { + return nil, fmt.Errorf("failed to get legacy points: %w", err) + } + if len(points) > 0 { + balance.PointsRowID = &points[0].ID + balance.Points = points[0].Balance + } + + err := db.Where("customer_id = ?", customerID).Order("token_type").Find(&balance.Tokens).Error + if err != nil { + return nil, fmt.Errorf("failed to get legacy tokens: %w", err) + } + return balance, nil +} + +func (r *walletMigrationRepository) SumMigrated(ctx context.Context, customerID uuid.UUID, currency string) (int64, error) { + var total int64 + err := DBFromContext(ctx, r.db).WithContext(ctx). + Model(&entities.WalletTransaction{}). + Where("customer_id = ? AND currency = ? AND type = ?", customerID, currency, constants.WalletTxTypeMigration). + Select("COALESCE(SUM(amount), 0)"). + Scan(&total).Error + if err != nil { + return 0, fmt.Errorf("failed to sum migrated balance: %w", err) + } + return total, nil +} + +func (r *walletMigrationRepository) Totals(ctx context.Context) (*WalletMigrationTotals, error) { + var totals WalletMigrationTotals + err := DBFromContext(ctx, r.db).WithContext(ctx).Raw(` + SELECT + (SELECT COALESCE(SUM(balance), 0) FROM customer_points) AS legacy_points, + (SELECT COALESCE(SUM(balance), 0) FROM customer_tokens) AS legacy_coins, + (SELECT COALESCE(SUM(amount), 0) FROM wallet_transactions WHERE type = ? AND currency = ?) AS migrated_points, + (SELECT COALESCE(SUM(amount), 0) FROM wallet_transactions WHERE type = ? AND currency = ?) AS migrated_coins, + (SELECT COALESCE(SUM(point_balance), 0) FROM customer_wallets) AS wallet_points, + (SELECT COALESCE(SUM(coin_balance), 0) FROM customer_wallets) AS wallet_coins`, + constants.WalletTxTypeMigration, constants.WalletCurrencyPoint, + constants.WalletTxTypeMigration, constants.WalletCurrencyCoin). + Scan(&totals).Error + if err != nil { + return nil, fmt.Errorf("failed to compute wallet migration totals: %w", err) + } + return &totals, nil +} diff --git a/internal/repository/wallet_move_repository.go b/internal/repository/wallet_move_repository.go new file mode 100644 index 0000000..d8cbb70 --- /dev/null +++ b/internal/repository/wallet_move_repository.go @@ -0,0 +1,82 @@ +package repository + +import ( + "context" + "errors" + "fmt" + "time" + + "github.com/google/uuid" + "gorm.io/gorm" + + "apskel-pos-be/internal/constants" +) + +// WalletMoveCustomer is a customer on either side of an exchange or a transfer. +type WalletMoveCustomer struct { + ID uuid.UUID + OrganizationID uuid.UUID + Name string + PhoneNumber *string + IsDefault bool + IsActive bool +} + +// WalletMoveRepository reads what exchanges and transfers check before moving a +// balance (docs/prd-point-coin.md F4, F5). The balance itself only moves through +// WalletProcessor. +type WalletMoveRepository interface { + // GetCustomer returns ErrWalletNotFound when the customer does not exist. + GetCustomer(ctx context.Context, customerID uuid.UUID) (*WalletMoveCustomer, error) + // FindCustomerByPhone returns ErrWalletNotFound when no customer has the number. + // Phone numbers are unique across organizations, so there is at most one. + FindCustomerByPhone(ctx context.Context, phoneNumber string) (*WalletMoveCustomer, error) + // TransferredOutSince sums what a customer has sent in one currency since a time. + // Call it under the sender's wallet lock, so transfers at the same time count. + TransferredOutSince(ctx context.Context, customerID uuid.UUID, currency string, since time.Time) (int64, error) +} + +type walletMoveRepository struct { + db *gorm.DB +} + +func NewWalletMoveRepository(db *gorm.DB) WalletMoveRepository { + return &walletMoveRepository{db: db} +} + +func (r *walletMoveRepository) GetCustomer(ctx context.Context, customerID uuid.UUID) (*WalletMoveCustomer, error) { + return r.customer(ctx, "id = ?", customerID) +} + +func (r *walletMoveRepository) FindCustomerByPhone(ctx context.Context, phoneNumber string) (*WalletMoveCustomer, error) { + return r.customer(ctx, "phone_number = ?", phoneNumber) +} + +func (r *walletMoveRepository) TransferredOutSince(ctx context.Context, customerID uuid.UUID, currency string, since time.Time) (int64, error) { + var total int64 + err := DBFromContext(ctx, r.db).WithContext(ctx). + Table("wallet_transactions"). + Select("COALESCE(SUM(-amount), 0)"). + Where("customer_id = ? AND currency = ? AND type = ? AND created_at >= ?", customerID, currency, constants.WalletTxTypeTransferOut, since). + Scan(&total).Error + if err != nil { + return 0, fmt.Errorf("failed to sum transfers: %w", err) + } + return total, nil +} + +func (r *walletMoveRepository) customer(ctx context.Context, where string, arg interface{}) (*WalletMoveCustomer, error) { + var c WalletMoveCustomer + err := DBFromContext(ctx, r.db).WithContext(ctx). + Table("customers"). + Select("id, organization_id, name, phone_number, is_default, is_active"). + Where(where, arg). + Take(&c).Error + if err != nil { + if errors.Is(err, gorm.ErrRecordNotFound) { + return nil, ErrWalletNotFound + } + return nil, fmt.Errorf("failed to get customer: %w", err) + } + return &c, nil +} diff --git a/internal/repository/wallet_query_repository.go b/internal/repository/wallet_query_repository.go new file mode 100644 index 0000000..ecd446f --- /dev/null +++ b/internal/repository/wallet_query_repository.go @@ -0,0 +1,202 @@ +package repository + +import ( + "context" + "fmt" + "time" + + "github.com/google/uuid" + "gorm.io/gorm" + + "apskel-pos-be/internal/entities" +) + +// walletDisplayTimeZone is the zone expiry dates are grouped in for display, the same +// one the database connection uses (config.Database.DSN). +const walletDisplayTimeZone = "Asia/Jakarta" + +// WalletTransactionFilter narrows a customer's ledger. Zero values mean no filter. +type WalletTransactionFilter struct { + CustomerID uuid.UUID + Currency string + Types []string + // From is inclusive and To is exclusive. + From *time.Time + To *time.Time + Offset int + Limit int +} + +// WalletExpiringAmount is how much of one currency expires on one day. +type WalletExpiringAmount struct { + Currency string + // A calendar date in walletDisplayTimeZone, formatted YYYY-MM-DD. + Date string + Amount int64 +} + +// WalletQueryRepository serves the read side of the wallet: balances, history and +// upcoming expiry for display. Nothing here changes a balance. +type WalletQueryRepository interface { + // GetCustomerOrganizationID returns ErrWalletNotFound when the customer does not exist. + GetCustomerOrganizationID(ctx context.Context, customerID uuid.UUID) (uuid.UUID, error) + // SpendableBalances sums, per currency, the lots that still have balance and have + // not expired at asOf. It differs from the wallet balance only for lots that have + // expired but that the expiry job has not processed yet. + SpendableBalances(ctx context.Context, customerID uuid.UUID, asOf time.Time) (map[string]int64, error) + // NearestExpiring returns, per currency, the earliest day after asOf on which some + // balance expires, and how much expires that day. + NearestExpiring(ctx context.Context, customerID uuid.UUID, asOf time.Time) ([]WalletExpiringAmount, error) + // ExpiringByDay returns, per currency and day, everything that expires after asOf, + // soonest first. + ExpiringByDay(ctx context.Context, customerID uuid.UUID, asOf time.Time) ([]WalletExpiringAmount, error) + // ListTransactions returns a page of the ledger, newest first, and the total count. + ListTransactions(ctx context.Context, filter WalletTransactionFilter) ([]entities.WalletTransaction, int64, error) + // OrganizationOutstanding sums every wallet balance of an organization. + OrganizationOutstanding(ctx context.Context, organizationID uuid.UUID) (points, coins int64, err error) + // ListLotsBySourceTransactions returns the lots created by the given credits. + ListLotsBySourceTransactions(ctx context.Context, transactionIDs []uuid.UUID) ([]entities.WalletLot, error) +} + +type walletQueryRepository struct { + db *gorm.DB +} + +func NewWalletQueryRepository(db *gorm.DB) WalletQueryRepository { + return &walletQueryRepository{db: db} +} + +func (r *walletQueryRepository) GetCustomerOrganizationID(ctx context.Context, customerID uuid.UUID) (uuid.UUID, error) { + var ids []string + err := DBFromContext(ctx, r.db).WithContext(ctx). + Table("customers"). + Where("id = ?", customerID). + Limit(1). + Pluck("organization_id::text", &ids).Error + if err != nil { + return uuid.Nil, fmt.Errorf("failed to get customer organization: %w", err) + } + if len(ids) == 0 { + return uuid.Nil, ErrWalletNotFound + } + return uuid.Parse(ids[0]) +} + +func (r *walletQueryRepository) SpendableBalances(ctx context.Context, customerID uuid.UUID, asOf time.Time) (map[string]int64, error) { + var rows []struct { + Currency string + Amount int64 + } + err := DBFromContext(ctx, r.db).WithContext(ctx). + Model(&entities.WalletLot{}). + Select("currency, SUM(remaining_amount) AS amount"). + Where("customer_id = ? AND remaining_amount > 0", customerID). + Where("(expires_at IS NULL OR expires_at > ?)", asOf). + Group("currency"). + Scan(&rows).Error + if err != nil { + return nil, fmt.Errorf("failed to sum spendable wallet balance: %w", err) + } + balances := make(map[string]int64, len(rows)) + for _, row := range rows { + balances[row.Currency] = row.Amount + } + return balances, nil +} + +func (r *walletQueryRepository) NearestExpiring(ctx context.Context, customerID uuid.UUID, asOf time.Time) ([]WalletExpiringAmount, error) { + var rows []WalletExpiringAmount + err := DBFromContext(ctx, r.db).WithContext(ctx).Raw(` + WITH by_day AS ( + SELECT currency, + (expires_at AT TIME ZONE ?)::date AS day, + SUM(remaining_amount) AS amount + FROM wallet_lots + WHERE customer_id = ? AND remaining_amount > 0 AND expires_at > ? + GROUP BY currency, day + ) + SELECT DISTINCT ON (currency) currency, to_char(day, 'YYYY-MM-DD') AS date, amount + FROM by_day + ORDER BY currency, day`, walletDisplayTimeZone, customerID, asOf). + Scan(&rows).Error + if err != nil { + return nil, fmt.Errorf("failed to get nearest expiring wallet balance: %w", err) + } + return rows, nil +} + +func (r *walletQueryRepository) ListTransactions(ctx context.Context, filter WalletTransactionFilter) ([]entities.WalletTransaction, int64, error) { + query := DBFromContext(ctx, r.db).WithContext(ctx). + Model(&entities.WalletTransaction{}). + Where("customer_id = ?", filter.CustomerID) + if filter.Currency != "" { + query = query.Where("currency = ?", filter.Currency) + } + if len(filter.Types) > 0 { + query = query.Where("type IN ?", filter.Types) + } + if filter.From != nil { + query = query.Where("created_at >= ?", *filter.From) + } + if filter.To != nil { + query = query.Where("created_at < ?", *filter.To) + } + + var total int64 + if err := query.Count(&total).Error; err != nil { + return nil, 0, fmt.Errorf("failed to count wallet transactions: %w", err) + } + + var transactions []entities.WalletTransaction + err := query. + Order("created_at DESC, id DESC"). + Offset(filter.Offset). + Limit(filter.Limit). + Find(&transactions).Error + if err != nil { + return nil, 0, fmt.Errorf("failed to list wallet transactions: %w", err) + } + return transactions, total, nil +} + +func (r *walletQueryRepository) ListLotsBySourceTransactions(ctx context.Context, transactionIDs []uuid.UUID) ([]entities.WalletLot, error) { + var lots []entities.WalletLot + if len(transactionIDs) == 0 { + return lots, nil + } + err := DBFromContext(ctx, r.db).WithContext(ctx). + Where("source_transaction_id IN ?", transactionIDs). + Order("expires_at NULLS LAST, created_at, id"). + Find(&lots).Error + if err != nil { + return nil, fmt.Errorf("failed to list wallet lots: %w", err) + } + return lots, nil +} + +func (r *walletQueryRepository) OrganizationOutstanding(ctx context.Context, organizationID uuid.UUID) (int64, int64, error) { + var totals struct{ Points, Coins int64 } + err := DBFromContext(ctx, r.db).WithContext(ctx).Raw(` + SELECT COALESCE(SUM(point_balance), 0) AS points, COALESCE(SUM(coin_balance), 0) AS coins + FROM customer_wallets WHERE organization_id = ?`, organizationID).Scan(&totals).Error + if err != nil { + return 0, 0, fmt.Errorf("failed to sum outstanding balances: %w", err) + } + return totals.Points, totals.Coins, nil +} + +func (r *walletQueryRepository) ExpiringByDay(ctx context.Context, customerID uuid.UUID, asOf time.Time) ([]WalletExpiringAmount, error) { + var rows []WalletExpiringAmount + err := DBFromContext(ctx, r.db).WithContext(ctx).Raw(` + SELECT currency, to_char((expires_at AT TIME ZONE ?)::date, 'YYYY-MM-DD') AS date, + SUM(remaining_amount) AS amount + FROM wallet_lots + WHERE customer_id = ? AND remaining_amount > 0 AND expires_at > ? + GROUP BY currency, date + ORDER BY date, currency`, walletDisplayTimeZone, customerID, asOf). + Scan(&rows).Error + if err != nil { + return nil, fmt.Errorf("failed to list expiring wallet balance: %w", err) + } + return rows, nil +} diff --git a/internal/repository/wallet_reconciliation_repository.go b/internal/repository/wallet_reconciliation_repository.go new file mode 100644 index 0000000..af41535 --- /dev/null +++ b/internal/repository/wallet_reconciliation_repository.go @@ -0,0 +1,160 @@ +package repository + +import ( + "context" + "fmt" + + "github.com/google/uuid" + "gorm.io/gorm" +) + +// The reconciliation checks of docs/prd-point-coin.md §7.5. +const ( + // Wallet balance = SUM(amount) of the customer's ledger rows, per currency. + WalletCheckBalanceVsLedger = "BALANCE_VS_LEDGER" + // Wallet balance = SUM(remaining_amount) of the customer's lots, per currency. + WalletCheckBalanceVsLots = "BALANCE_VS_LOTS" + // For every lot: original_amount - SUM(allocations) = remaining_amount. + WalletCheckLotVsAllocations = "LOT_VS_ALLOCATIONS" + // For every deduction: SUM(allocations) = |amount|. + WalletCheckDebitVsAllocations = "DEBIT_VS_ALLOCATIONS" + // For every addition: SUM(original_amount) of the lots it created = amount. Not + // listed in §7.5, but the engine keeps it and the other checks rely on it. + WalletCheckCreditVsLots = "CREDIT_VS_LOTS" +) + +// WalletDiscrepancy is one place where the wallet tables disagree with each other. +type WalletDiscrepancy struct { + Check string + OrganizationID uuid.UUID + CustomerID uuid.UUID + Currency string + // The lot or ledger row the check is about. Nil for the per-wallet checks. + ObjectID *uuid.UUID + Expected int64 + Actual int64 +} + +// WalletReconciliationRepository runs the §7.5 checks across every wallet. +type WalletReconciliationRepository interface { + // FindDiscrepancies returns every discrepancy, at most limit per check, so one + // systematic bug cannot produce an unbounded report. + FindDiscrepancies(ctx context.Context, limit int) ([]WalletDiscrepancy, error) +} + +type walletReconciliationRepository struct { + db *gorm.DB +} + +func NewWalletReconciliationRepository(db *gorm.DB) WalletReconciliationRepository { + return &walletReconciliationRepository{db: db} +} + +// Each query returns check, organization_id, customer_id, currency, object_id, +// expected and actual. Aggregates are joined rather than correlated, so each check is +// a handful of scans however many customers there are. +var walletReconciliationQueries = []struct { + check string + sql string +}{ + {WalletCheckBalanceVsLedger, ` + WITH ledger AS ( + SELECT customer_id, currency, MAX(organization_id::text) AS organization_id, SUM(amount) AS total + FROM wallet_transactions GROUP BY customer_id, currency + ), balances AS ( + SELECT customer_id, organization_id::text AS organization_id, 'POINT' AS currency, point_balance AS balance FROM customer_wallets + UNION ALL + SELECT customer_id, organization_id::text, 'COIN', coin_balance FROM customer_wallets + ) + SELECT COALESCE(b.organization_id, l.organization_id) AS organization_id, + COALESCE(b.customer_id, l.customer_id)::text AS customer_id, + COALESCE(b.currency, l.currency) AS currency, + NULL AS object_id, + COALESCE(l.total, 0) AS expected, + COALESCE(b.balance, 0) AS actual + FROM balances b + FULL JOIN ledger l ON l.customer_id = b.customer_id AND l.currency = b.currency + WHERE COALESCE(b.balance, 0) <> COALESCE(l.total, 0) + LIMIT ?`}, + {WalletCheckBalanceVsLots, ` + WITH lots AS ( + SELECT customer_id, currency, MAX(organization_id::text) AS organization_id, SUM(remaining_amount) AS total + FROM wallet_lots GROUP BY customer_id, currency + ), balances AS ( + SELECT customer_id, organization_id::text AS organization_id, 'POINT' AS currency, point_balance AS balance FROM customer_wallets + UNION ALL + SELECT customer_id, organization_id::text, 'COIN', coin_balance FROM customer_wallets + ) + SELECT COALESCE(b.organization_id, l.organization_id) AS organization_id, + COALESCE(b.customer_id, l.customer_id)::text AS customer_id, + COALESCE(b.currency, l.currency) AS currency, + NULL AS object_id, + COALESCE(l.total, 0) AS expected, + COALESCE(b.balance, 0) AS actual + FROM balances b + FULL JOIN lots l ON l.customer_id = b.customer_id AND l.currency = b.currency + WHERE COALESCE(b.balance, 0) <> COALESCE(l.total, 0) + LIMIT ?`}, + {WalletCheckLotVsAllocations, ` + SELECT l.organization_id::text AS organization_id, l.customer_id::text AS customer_id, l.currency, + l.id::text AS object_id, + l.original_amount - COALESCE(a.total, 0) AS expected, + l.remaining_amount AS actual + FROM wallet_lots l + LEFT JOIN (SELECT lot_id, SUM(amount) AS total FROM wallet_lot_allocations GROUP BY lot_id) a ON a.lot_id = l.id + WHERE l.original_amount - COALESCE(a.total, 0) <> l.remaining_amount + LIMIT ?`}, + {WalletCheckDebitVsAllocations, ` + SELECT t.organization_id::text AS organization_id, t.customer_id::text AS customer_id, t.currency, + t.id::text AS object_id, + -t.amount AS expected, + COALESCE(a.total, 0) AS actual + FROM wallet_transactions t + LEFT JOIN (SELECT transaction_id, SUM(amount) AS total FROM wallet_lot_allocations GROUP BY transaction_id) a ON a.transaction_id = t.id + WHERE t.amount < 0 AND -t.amount <> COALESCE(a.total, 0) + LIMIT ?`}, + {WalletCheckCreditVsLots, ` + SELECT t.organization_id::text AS organization_id, t.customer_id::text AS customer_id, t.currency, + t.id::text AS object_id, + t.amount AS expected, + COALESCE(l.total, 0) AS actual + FROM wallet_transactions t + LEFT JOIN (SELECT source_transaction_id, SUM(original_amount) AS total FROM wallet_lots GROUP BY source_transaction_id) l ON l.source_transaction_id = t.id + WHERE t.amount > 0 AND t.amount <> COALESCE(l.total, 0) + LIMIT ?`}, +} + +func (r *walletReconciliationRepository) FindDiscrepancies(ctx context.Context, limit int) ([]WalletDiscrepancy, error) { + db := DBFromContext(ctx, r.db).WithContext(ctx) + var found []WalletDiscrepancy + for _, q := range walletReconciliationQueries { + var rows []struct { + OrganizationID string + CustomerID string + Currency string + ObjectID *string + Expected int64 + Actual int64 + } + if err := db.Raw(q.sql, limit).Scan(&rows).Error; err != nil { + return nil, fmt.Errorf("wallet reconciliation check %s failed: %w", q.check, err) + } + for _, row := range rows { + d := WalletDiscrepancy{ + Check: q.check, + Currency: row.Currency, + Expected: row.Expected, + Actual: row.Actual, + } + d.OrganizationID, _ = uuid.Parse(row.OrganizationID) + d.CustomerID, _ = uuid.Parse(row.CustomerID) + if row.ObjectID != nil { + if id, err := uuid.Parse(*row.ObjectID); err == nil { + d.ObjectID = &id + } + } + found = append(found, d) + } + } + return found, nil +} diff --git a/internal/repository/wallet_reconciliation_repository_test.go b/internal/repository/wallet_reconciliation_repository_test.go new file mode 100644 index 0000000..4b530f4 --- /dev/null +++ b/internal/repository/wallet_reconciliation_repository_test.go @@ -0,0 +1,141 @@ +package repository_test + +import ( + "context" + "os" + "sort" + "testing" + + "github.com/google/uuid" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "gorm.io/driver/postgres" + "gorm.io/gorm" + "gorm.io/gorm/logger" + + "apskel-pos-be/internal/constants" + "apskel-pos-be/internal/processor" + "apskel-pos-be/internal/repository" +) + +// Builds consistent wallets through the engine, checks the reconciliation is silent, +// then breaks each §7.5 invariant for a different customer and checks each break is +// found by the right checks and nothing else is. Needs TEST_DATABASE_URL pointing at +// a migrated database; see wallet_repository_test.go. +func TestWalletReconciliation_AgainstPostgres(t *testing.T) { + dsn := os.Getenv("TEST_DATABASE_URL") + if dsn == "" { + t.Skip("TEST_DATABASE_URL not set") + } + db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{Logger: logger.Default.LogMode(logger.Silent)}) + require.NoError(t, err) + ctx := context.Background() + + org := uuid.New() + names := []string{"clean", "balance", "lot", "allocation", "credit"} + customers := map[string]uuid.UUID{} + var ids []uuid.UUID + require.NoError(t, db.Exec(`INSERT INTO organizations (id, name, plan_type) VALUES (?, 'recon test', 'basic')`, org).Error) + for _, n := range names { + customers[n] = uuid.New() + ids = append(ids, customers[n]) + require.NoError(t, db.Exec(`INSERT INTO customers (id, organization_id, name) VALUES (?, ?, ?)`, customers[n], org, n).Error) + } + t.Cleanup(func() { + db.Exec(`DELETE FROM wallet_lot_allocations WHERE lot_id IN (SELECT id FROM wallet_lots WHERE customer_id IN ?)`, ids) + db.Exec(`DELETE FROM wallet_lot_allocations WHERE transaction_id IN (SELECT id FROM wallet_transactions WHERE customer_id IN ?)`, ids) + db.Exec(`DELETE FROM wallet_lots WHERE customer_id IN ?`, ids) + db.Exec(`DELETE FROM wallet_transactions WHERE customer_id IN ?`, ids) + db.Exec(`DELETE FROM customer_wallets WHERE customer_id IN ?`, ids) + db.Exec(`DELETE FROM customers WHERE id IN ?`, ids) + db.Exec(`DELETE FROM organizations WHERE id = ?`, org) + }) + + // Every customer: +100 in two lots, +30 coins, -70 points across both lots. + wallet := processor.NewWalletProcessor(repository.NewWalletRepository(db)) + txm := repository.NewTxManager(db) + for _, id := range ids { + require.NoError(t, txm.WithTransaction(ctx, func(ctx context.Context) error { + if _, err := wallet.Credit(ctx, processor.WalletCreditInput{ + WalletEntry: processor.WalletEntry{CustomerID: id, Currency: constants.WalletCurrencyPoint, + Type: constants.WalletTxTypeMigration, Amount: 100, ReferenceType: constants.WalletRefTypeLegacyPoints, + ReferenceID: uuid.New(), Description: "Saldo awal"}, + Lots: []processor.WalletLotInput{{Amount: 60}, {Amount: 40}}, + }); err != nil { + return err + } + if _, err := wallet.Credit(ctx, processor.WalletCreditInput{WalletEntry: processor.WalletEntry{ + CustomerID: id, Currency: constants.WalletCurrencyCoin, Type: constants.WalletTxTypeMigration, + Amount: 30, ReferenceType: constants.WalletRefTypeLegacyTokens, ReferenceID: id, Description: "Saldo awal"}}); err != nil { + return err + } + outlet := uuid.New() + _, err := wallet.Debit(ctx, processor.WalletDebitInput{WalletEntry: processor.WalletEntry{ + CustomerID: id, Currency: constants.WalletCurrencyPoint, Type: constants.WalletTxTypePayment, + Amount: 70, ReferenceType: constants.WalletRefTypePayment, ReferenceID: uuid.New(), OutletID: &outlet, + Description: "Bayar"}}) + return err + })) + } + + recon := repository.NewWalletReconciliationRepository(db) + // Other packages' tests may share the database, so only these customers count. + checksByCustomer := func() map[string][]string { + t.Helper() + found, err := recon.FindDiscrepancies(ctx, 1000) + require.NoError(t, err) + byName := map[uuid.UUID]string{} + for n, id := range customers { + byName[id] = n + } + out := map[string][]string{} + for _, d := range found { + if n, ok := byName[d.CustomerID]; ok { + assert.Equal(t, org, d.OrganizationID) + out[n] = append(out[n], d.Check) + } + } + for n := range out { + sort.Strings(out[n]) + } + return out + } + + assert.Empty(t, checksByCustomer(), "consistent data reports nothing") + + exec := func(q string, args ...any) { + t.Helper() + require.NoError(t, db.Exec(q, args...).Error) + } + // A balance moved without a ledger row or a lot. + exec(`UPDATE customer_wallets SET point_balance = point_balance + 5 WHERE customer_id = ?`, customers["balance"]) + // A lot's remainder changed without an allocation. + exec(`UPDATE wallet_lots SET remaining_amount = remaining_amount - 1 + WHERE id = (SELECT id FROM wallet_lots WHERE customer_id = ? AND remaining_amount > 0 LIMIT 1)`, customers["lot"]) + // An allocation lost. + exec(`DELETE FROM wallet_lot_allocations WHERE (transaction_id, lot_id) IN ( + SELECT a.transaction_id, a.lot_id FROM wallet_lot_allocations a + JOIN wallet_transactions t ON t.id = a.transaction_id WHERE t.customer_id = ? LIMIT 1)`, customers["allocation"]) + // A credit whose lot was never written, with the balance moved to match the ledger. + exec(`INSERT INTO wallet_transactions (organization_id, customer_id, currency, type, amount, balance_after, reference_type, reference_id, description) + VALUES (?, ?, 'COIN', 'MIGRATION', 10, 40, 'LEGACY_TOKENS', ?, 'x')`, org, customers["credit"], customers["credit"]) + exec(`UPDATE customer_wallets SET coin_balance = coin_balance + 10 WHERE customer_id = ?`, customers["credit"]) + + assert.Equal(t, map[string][]string{ + "balance": {repository.WalletCheckBalanceVsLedger, repository.WalletCheckBalanceVsLots}, + "lot": {repository.WalletCheckBalanceVsLots, repository.WalletCheckLotVsAllocations}, + "allocation": {repository.WalletCheckDebitVsAllocations, repository.WalletCheckLotVsAllocations}, + "credit": {repository.WalletCheckBalanceVsLots, repository.WalletCheckCreditVsLots}, + }, checksByCustomer(), "each break is found by exactly the checks it violates, and the clean customer by none") + + // The per-check limit caps the report. + found, err := recon.FindDiscrepancies(ctx, 1) + require.NoError(t, err) + perCheck := map[string]int{} + for _, d := range found { + perCheck[d.Check]++ + } + for check, n := range perCheck { + assert.LessOrEqual(t, n, 1, check) + } +} diff --git a/internal/repository/wallet_repository.go b/internal/repository/wallet_repository.go new file mode 100644 index 0000000..be3763b --- /dev/null +++ b/internal/repository/wallet_repository.go @@ -0,0 +1,295 @@ +package repository + +import ( + "context" + "errors" + "fmt" + "sort" + "time" + + "github.com/google/uuid" + "gorm.io/gorm" + "gorm.io/gorm/clause" + + "apskel-pos-be/internal/constants" + "apskel-pos-be/internal/entities" +) + +var ( + // ErrWalletTxRequired is returned by every write and lock when the context carries + // no transaction from TxManager. Outside a transaction a lock is released as soon as + // it is taken, and a balance could move without its ledger row. + ErrWalletTxRequired = errors.New("wallet: operation must run inside a transaction") + // ErrWalletNotFound means the customer does not exist, so no wallet could be made. + ErrWalletNotFound = errors.New("wallet: customer not found") + // ErrWalletInsufficientBalance means a conditional update matched no row because + // the balance would have gone negative. + ErrWalletInsufficientBalance = errors.New("wallet: insufficient balance") + // ErrWalletLotInsufficient means a lot had less remaining than was taken from it. + ErrWalletLotInsufficient = errors.New("wallet: lot has insufficient remaining amount") +) + +// WalletRepository reads and writes the wallet tables (docs/prd-point-coin.md §7, §8). +// Only the wallet processor should call its write methods: it is the one place that +// keeps balances, ledger rows and lots in step. +// +// Unlike the gamification repositories, every method goes through DBFromContext so it +// joins the caller's transaction. Writes and locks refuse to run without one. +type WalletRepository interface { + // LockWallet locks the customer's wallet row for the rest of the transaction, + // creating the row first if the customer has none yet. + LockWallet(ctx context.Context, customerID uuid.UUID) (*entities.CustomerWallet, error) + // LockWallets locks two wallets, always in customer_id order so that two transfers + // in opposite directions cannot deadlock. The results come back in argument order. + LockWallets(ctx context.Context, a, b uuid.UUID) (*entities.CustomerWallet, *entities.CustomerWallet, error) + // AddBalance moves one balance by delta and returns the new balance. A debit that + // would make it negative changes nothing and returns ErrWalletInsufficientBalance. + AddBalance(ctx context.Context, customerID uuid.UUID, currency string, delta int64) (int64, error) + GetWallet(ctx context.Context, customerID uuid.UUID) (*entities.CustomerWallet, error) + + CreateTransaction(ctx context.Context, walletTx *entities.WalletTransaction) error + // GetTransactionByIdempotencyKey returns nil, nil when no row has the key. + GetTransactionByIdempotencyKey(ctx context.Context, key string) (*entities.WalletTransaction, error) + + CreateLot(ctx context.Context, lot *entities.WalletLot) error + // GetLotsByIDs returns the lots with the given ids, expired or not, in no + // particular order. Ids that match no lot are left out. + GetLotsByIDs(ctx context.Context, ids []uuid.UUID) ([]entities.WalletLot, error) + // ListLotsBySourceTransaction returns the lots a credit created, oldest first. + ListLotsBySourceTransaction(ctx context.Context, transactionID uuid.UUID) ([]entities.WalletLot, error) + // ListActiveLots returns the lots that still have balance and have not expired at + // asOf, in the order they are spent (K9): soonest expiry first, lots without an + // expiry last, oldest first within the same expiry. + ListActiveLots(ctx context.Context, customerID uuid.UUID, currency string, asOf time.Time) ([]entities.WalletLot, error) + // ConsumeLot takes amount from a lot's remaining amount. Taking more than remains + // changes nothing and returns ErrWalletLotInsufficient. + ConsumeLot(ctx context.Context, lotID uuid.UUID, amount int64) error + + CreateAllocations(ctx context.Context, allocations []entities.WalletLotAllocation) error + ListAllocationsByTransaction(ctx context.Context, transactionID uuid.UUID) ([]entities.WalletLotAllocation, error) +} + +type walletRepository struct { + db *gorm.DB +} + +func NewWalletRepository(db *gorm.DB) WalletRepository { + return &walletRepository{db: db} +} + +// txDB returns the caller's transaction, or ErrWalletTxRequired if there is none. +func (r *walletRepository) txDB(ctx context.Context) (*gorm.DB, error) { + if tx, ok := ctx.Value(txKey).(*gorm.DB); ok && tx != nil { + return tx.WithContext(ctx), nil + } + return nil, ErrWalletTxRequired +} + +func (r *walletRepository) LockWallet(ctx context.Context, customerID uuid.UUID) (*entities.CustomerWallet, error) { + db, err := r.txDB(ctx) + if err != nil { + return nil, err + } + + // The wallet takes its organization from the customer, so the two cannot disagree. + // ON CONFLICT covers two first operations racing to create the same wallet. + err = db.Exec(`INSERT INTO customer_wallets (customer_id, organization_id) + SELECT id, organization_id FROM customers WHERE id = ? + ON CONFLICT (customer_id) DO NOTHING`, customerID).Error + if err != nil { + return nil, fmt.Errorf("failed to create customer wallet: %w", err) + } + + var wallet entities.CustomerWallet + err = db.Clauses(clause.Locking{Strength: "UPDATE"}). + Where("customer_id = ?", customerID). + First(&wallet).Error + if err != nil { + if errors.Is(err, gorm.ErrRecordNotFound) { + return nil, ErrWalletNotFound + } + return nil, fmt.Errorf("failed to lock customer wallet: %w", err) + } + return &wallet, nil +} + +func (r *walletRepository) LockWallets(ctx context.Context, a, b uuid.UUID) (*entities.CustomerWallet, *entities.CustomerWallet, error) { + if a == b { + return nil, nil, errors.New("wallet: cannot lock the same wallet twice") + } + + ids := []uuid.UUID{a, b} + sort.Slice(ids, func(i, j int) bool { return ids[i].String() < ids[j].String() }) + + locked := make(map[uuid.UUID]*entities.CustomerWallet, 2) + for _, id := range ids { + wallet, err := r.LockWallet(ctx, id) + if err != nil { + return nil, nil, err + } + locked[id] = wallet + } + return locked[a], locked[b], nil +} + +func (r *walletRepository) AddBalance(ctx context.Context, customerID uuid.UUID, currency string, delta int64) (int64, error) { + db, err := r.txDB(ctx) + if err != nil { + return 0, err + } + + var column string + switch currency { + case constants.WalletCurrencyPoint: + column = "point_balance" + case constants.WalletCurrencyCoin: + column = "coin_balance" + default: + return 0, fmt.Errorf("wallet: unknown currency %q", currency) + } + + // The WHERE clause makes an overdraft match no row instead of tripping the CHECK, + // so the caller gets a clean error and the transaction stays usable. + var balances []int64 + err = db.Raw(`UPDATE customer_wallets + SET `+column+` = `+column+` + ?, updated_at = NOW() + WHERE customer_id = ? AND `+column+` + ? >= 0 + RETURNING `+column, delta, customerID, delta). + Scan(&balances).Error + if err != nil { + return 0, fmt.Errorf("failed to update wallet balance: %w", err) + } + if len(balances) == 0 { + if delta >= 0 { + return 0, ErrWalletNotFound + } + return 0, ErrWalletInsufficientBalance + } + return balances[0], nil +} + +func (r *walletRepository) GetWallet(ctx context.Context, customerID uuid.UUID) (*entities.CustomerWallet, error) { + var wallet entities.CustomerWallet + err := DBFromContext(ctx, r.db).WithContext(ctx). + Where("customer_id = ?", customerID). + First(&wallet).Error + if err != nil { + return nil, err + } + return &wallet, nil +} + +func (r *walletRepository) CreateTransaction(ctx context.Context, walletTx *entities.WalletTransaction) error { + db, err := r.txDB(ctx) + if err != nil { + return err + } + return db.Create(walletTx).Error +} + +func (r *walletRepository) GetTransactionByIdempotencyKey(ctx context.Context, key string) (*entities.WalletTransaction, error) { + // Find rather than First: a new key is the normal case, and First would log every + // one of them as a "record not found" error. + var walletTxs []entities.WalletTransaction + err := DBFromContext(ctx, r.db).WithContext(ctx). + Where("idempotency_key = ?", key). + Limit(1). + Find(&walletTxs).Error + if err != nil { + return nil, fmt.Errorf("failed to get wallet transaction by idempotency key: %w", err) + } + if len(walletTxs) == 0 { + return nil, nil + } + return &walletTxs[0], nil +} + +func (r *walletRepository) CreateLot(ctx context.Context, lot *entities.WalletLot) error { + db, err := r.txDB(ctx) + if err != nil { + return err + } + return db.Create(lot).Error +} + +func (r *walletRepository) GetLotsByIDs(ctx context.Context, ids []uuid.UUID) ([]entities.WalletLot, error) { + var lots []entities.WalletLot + if len(ids) == 0 { + return lots, nil + } + err := DBFromContext(ctx, r.db).WithContext(ctx). + Where("id IN ?", ids). + Find(&lots).Error + if err != nil { + return nil, fmt.Errorf("failed to get wallet lots: %w", err) + } + return lots, nil +} + +func (r *walletRepository) ListLotsBySourceTransaction(ctx context.Context, transactionID uuid.UUID) ([]entities.WalletLot, error) { + var lots []entities.WalletLot + err := DBFromContext(ctx, r.db).WithContext(ctx). + Where("source_transaction_id = ?", transactionID). + Order("created_at, id"). + Find(&lots).Error + if err != nil { + return nil, fmt.Errorf("failed to list wallet lots by source transaction: %w", err) + } + return lots, nil +} + +func (r *walletRepository) ListActiveLots(ctx context.Context, customerID uuid.UUID, currency string, asOf time.Time) ([]entities.WalletLot, error) { + var lots []entities.WalletLot + // Filter and order match idx_wallet_lots_consume. + err := DBFromContext(ctx, r.db).WithContext(ctx). + Where("customer_id = ? AND currency = ? AND remaining_amount > 0", customerID, currency). + Where("(expires_at IS NULL OR expires_at > ?)", asOf). + Order("expires_at NULLS LAST, created_at, id"). + Find(&lots).Error + if err != nil { + return nil, fmt.Errorf("failed to list active wallet lots: %w", err) + } + return lots, nil +} + +func (r *walletRepository) ConsumeLot(ctx context.Context, lotID uuid.UUID, amount int64) error { + if amount <= 0 { + return fmt.Errorf("wallet: lot consumption must be positive, got %d", amount) + } + db, err := r.txDB(ctx) + if err != nil { + return err + } + + result := db.Exec(`UPDATE wallet_lots SET remaining_amount = remaining_amount - ? + WHERE id = ? AND remaining_amount >= ?`, amount, lotID, amount) + if result.Error != nil { + return fmt.Errorf("failed to consume wallet lot: %w", result.Error) + } + if result.RowsAffected == 0 { + return ErrWalletLotInsufficient + } + return nil +} + +func (r *walletRepository) CreateAllocations(ctx context.Context, allocations []entities.WalletLotAllocation) error { + if len(allocations) == 0 { + return nil + } + db, err := r.txDB(ctx) + if err != nil { + return err + } + return db.Create(&allocations).Error +} + +func (r *walletRepository) ListAllocationsByTransaction(ctx context.Context, transactionID uuid.UUID) ([]entities.WalletLotAllocation, error) { + var allocations []entities.WalletLotAllocation + err := DBFromContext(ctx, r.db).WithContext(ctx). + Where("transaction_id = ?", transactionID). + Find(&allocations).Error + if err != nil { + return nil, fmt.Errorf("failed to list wallet lot allocations: %w", err) + } + return allocations, nil +} diff --git a/internal/repository/wallet_repository_test.go b/internal/repository/wallet_repository_test.go new file mode 100644 index 0000000..bfbdd30 --- /dev/null +++ b/internal/repository/wallet_repository_test.go @@ -0,0 +1,353 @@ +package repository + +import ( + "context" + "errors" + "os" + "sync" + "testing" + "time" + + "github.com/google/uuid" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "gorm.io/driver/postgres" + "gorm.io/gorm" + "gorm.io/gorm/logger" + + "apskel-pos-be/internal/constants" + "apskel-pos-be/internal/entities" +) + +// These tests need a real Postgres, because what they check (row locks and +// conditional updates) only exists there. Point TEST_DATABASE_URL at a database with +// all migrations applied, e.g. +// +// TEST_DATABASE_URL=postgres://user:pass@localhost:5432/pos_test?sslmode=disable go test ./internal/repository/ -run Wallet +// +// Each test creates its own organization and customers and removes them afterwards. +func walletTestDB(t *testing.T) *gorm.DB { + t.Helper() + dsn := os.Getenv("TEST_DATABASE_URL") + if dsn == "" { + t.Skip("TEST_DATABASE_URL not set") + } + db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{Logger: logger.Default.LogMode(logger.Silent)}) + require.NoError(t, err) + return db +} + +type walletFixture struct { + db *gorm.DB + repo WalletRepository + txm *TxManager + orgID uuid.UUID + customers []uuid.UUID +} + +func newWalletFixture(t *testing.T, customerCount int) *walletFixture { + t.Helper() + db := walletTestDB(t) + f := &walletFixture{db: db, repo: NewWalletRepository(db), txm: NewTxManager(db), orgID: uuid.New()} + + require.NoError(t, db.Exec(`INSERT INTO organizations (id, name, plan_type) VALUES (?, 'wallet test', 'basic')`, f.orgID).Error) + for i := 0; i < customerCount; i++ { + id := uuid.New() + require.NoError(t, db.Exec(`INSERT INTO customers (id, organization_id, name) VALUES (?, ?, 'wallet test')`, id, f.orgID).Error) + f.customers = append(f.customers, id) + } + + t.Cleanup(func() { + for _, q := range []string{ + `DELETE FROM wallet_lot_allocations WHERE lot_id IN (SELECT id FROM wallet_lots WHERE customer_id IN ?)`, + `DELETE FROM wallet_lots WHERE customer_id IN ?`, + `DELETE FROM wallet_transactions WHERE customer_id IN ?`, + `DELETE FROM customer_wallets WHERE customer_id IN ?`, + `DELETE FROM customers WHERE id IN ?`, + } { + db.Exec(q, f.customers) + } + db.Exec(`DELETE FROM organizations WHERE id = ?`, f.orgID) + }) + return f +} + +// inTx runs fn in a transaction and fails the test on error. +func (f *walletFixture) inTx(t *testing.T, fn func(ctx context.Context) error) { + t.Helper() + require.NoError(t, f.txm.WithTransaction(context.Background(), fn)) +} + +// credit writes a ledger row and a lot and moves the balance, the minimum the +// database accepts for a credit. +func (f *walletFixture) credit(t *testing.T, ctx context.Context, customerID uuid.UUID, amount int64, expiresAt *time.Time) *entities.WalletLot { + t.Helper() + balance, err := f.repo.AddBalance(ctx, customerID, constants.WalletCurrencyPoint, amount) + require.NoError(t, err) + walletTx := &entities.WalletTransaction{ + OrganizationID: f.orgID, + CustomerID: customerID, + Currency: constants.WalletCurrencyPoint, + Type: constants.WalletTxTypeMigration, + Amount: amount, + BalanceAfter: balance, + ReferenceType: constants.WalletRefTypeLegacyPoints, + ReferenceID: uuid.New(), + Description: "test", + } + require.NoError(t, f.repo.CreateTransaction(ctx, walletTx)) + lot := &entities.WalletLot{ + OrganizationID: f.orgID, + CustomerID: customerID, + Currency: constants.WalletCurrencyPoint, + SourceTransactionID: walletTx.ID, + OriginalAmount: amount, + RemainingAmount: amount, + ExpiresAt: expiresAt, + } + require.NoError(t, f.repo.CreateLot(ctx, lot)) + return lot +} + +func TestWalletRepository_WritesRequireTransaction(t *testing.T) { + f := newWalletFixture(t, 1) + ctx := context.Background() + + _, err := f.repo.LockWallet(ctx, f.customers[0]) + assert.ErrorIs(t, err, ErrWalletTxRequired) + _, err = f.repo.AddBalance(ctx, f.customers[0], constants.WalletCurrencyPoint, 10) + assert.ErrorIs(t, err, ErrWalletTxRequired) + assert.ErrorIs(t, f.repo.ConsumeLot(ctx, uuid.New(), 1), ErrWalletTxRequired) + assert.ErrorIs(t, f.repo.CreateTransaction(ctx, &entities.WalletTransaction{}), ErrWalletTxRequired) + assert.ErrorIs(t, f.repo.CreateLot(ctx, &entities.WalletLot{}), ErrWalletTxRequired) +} + +func TestWalletRepository_LockWalletCreatesWallet(t *testing.T) { + f := newWalletFixture(t, 1) + + f.inTx(t, func(ctx context.Context) error { + wallet, err := f.repo.LockWallet(ctx, f.customers[0]) + require.NoError(t, err) + assert.Equal(t, f.orgID, wallet.OrganizationID, "organization comes from the customer") + assert.Zero(t, wallet.PointBalance) + assert.Zero(t, wallet.CoinBalance) + + // Locking again in the same transaction finds the same row. + again, err := f.repo.LockWallet(ctx, f.customers[0]) + require.NoError(t, err) + assert.Equal(t, wallet.CustomerID, again.CustomerID) + return nil + }) + + f.inTx(t, func(ctx context.Context) error { + _, err := f.repo.LockWallet(ctx, uuid.New()) + assert.ErrorIs(t, err, ErrWalletNotFound) + return nil + }) +} + +func TestWalletRepository_AddBalanceRejectsOverdraft(t *testing.T) { + f := newWalletFixture(t, 1) + customerID := f.customers[0] + + f.inTx(t, func(ctx context.Context) error { + _, err := f.repo.LockWallet(ctx, customerID) + require.NoError(t, err) + + balance, err := f.repo.AddBalance(ctx, customerID, constants.WalletCurrencyPoint, 5) + require.NoError(t, err) + assert.Equal(t, int64(5), balance) + + _, err = f.repo.AddBalance(ctx, customerID, constants.WalletCurrencyPoint, -6) + assert.ErrorIs(t, err, ErrWalletInsufficientBalance) + + // Coin is a separate balance: point balance does not cover it. + _, err = f.repo.AddBalance(ctx, customerID, constants.WalletCurrencyCoin, -1) + assert.ErrorIs(t, err, ErrWalletInsufficientBalance) + + // The failed update left the transaction usable and the balance untouched. + balance, err = f.repo.AddBalance(ctx, customerID, constants.WalletCurrencyPoint, -5) + require.NoError(t, err) + assert.Equal(t, int64(0), balance) + return nil + }) + + wallet, err := f.repo.GetWallet(context.Background(), customerID) + require.NoError(t, err) + assert.Equal(t, int64(0), wallet.PointBalance) + assert.Equal(t, int64(0), wallet.CoinBalance) +} + +func TestWalletRepository_AddBalanceWithoutWallet(t *testing.T) { + f := newWalletFixture(t, 1) + + f.inTx(t, func(ctx context.Context) error { + _, err := f.repo.AddBalance(ctx, f.customers[0], constants.WalletCurrencyPoint, 5) + assert.ErrorIs(t, err, ErrWalletNotFound) + _, err = f.repo.AddBalance(ctx, f.customers[0], "GOLD", 5) + assert.Error(t, err) + return nil + }) +} + +func TestWalletRepository_ConsumeLotRejectsOverdraw(t *testing.T) { + f := newWalletFixture(t, 1) + customerID := f.customers[0] + + f.inTx(t, func(ctx context.Context) error { + _, err := f.repo.LockWallet(ctx, customerID) + require.NoError(t, err) + lot := f.credit(t, ctx, customerID, 10, nil) + + require.NoError(t, f.repo.ConsumeLot(ctx, lot.ID, 4)) + assert.ErrorIs(t, f.repo.ConsumeLot(ctx, lot.ID, 7), ErrWalletLotInsufficient) + require.NoError(t, f.repo.ConsumeLot(ctx, lot.ID, 6)) + assert.ErrorIs(t, f.repo.ConsumeLot(ctx, lot.ID, 1), ErrWalletLotInsufficient) + assert.Error(t, f.repo.ConsumeLot(ctx, lot.ID, 0)) + return nil + }) +} + +// Two goroutines lock the same wallet and do a read-modify-write with a pause in +// between. Without the lock both would read 0 and the result would be 1. +func TestWalletRepository_LockWalletSerializes(t *testing.T) { + f := newWalletFixture(t, 1) + customerID := f.customers[0] + + // Create the wallet up front. Otherwise the second goroutine's INSERT ... ON + // CONFLICT waits on the first one's uncommitted insert, which serializes them + // even without FOR UPDATE and the test would prove nothing about the lock. + f.inTx(t, func(ctx context.Context) error { + _, err := f.repo.LockWallet(ctx, customerID) + return err + }) + + type window struct{ locked, released time.Time } + windows := make([]window, 2) + var wg sync.WaitGroup + errs := make(chan error, 2) + + for i := 0; i < 2; i++ { + wg.Add(1) + go func(i int) { + defer wg.Done() + errs <- f.txm.WithTransaction(context.Background(), func(ctx context.Context) error { + wallet, err := f.repo.LockWallet(ctx, customerID) + if err != nil { + return err + } + windows[i].locked = time.Now() + time.Sleep(300 * time.Millisecond) + db := DBFromContext(ctx, f.db) + if err := db.Exec(`UPDATE customer_wallets SET point_balance = ? WHERE customer_id = ?`, + wallet.PointBalance+1, customerID).Error; err != nil { + return err + } + windows[i].released = time.Now() + return nil + }) + }(i) + } + wg.Wait() + close(errs) + for err := range errs { + require.NoError(t, err) + } + + wallet, err := f.repo.GetWallet(context.Background(), customerID) + require.NoError(t, err) + assert.Equal(t, int64(2), wallet.PointBalance, "second transaction must see the first one's write") + + first, second := windows[0], windows[1] + if second.locked.Before(first.locked) { + first, second = second, first + } + assert.False(t, second.locked.Before(first.released), "second lock was taken while the first was held") +} + +// Transfers in opposite directions lock the same pair of wallets. Because LockWallets +// always locks in customer_id order, they queue instead of deadlocking. +func TestWalletRepository_LockWalletsOppositeOrderDoesNotDeadlock(t *testing.T) { + f := newWalletFixture(t, 2) + a, b := f.customers[0], f.customers[1] + // Existing wallets, for the same reason as in LockWalletSerializes. + f.inTx(t, func(ctx context.Context) error { + _, _, err := f.repo.LockWallets(ctx, a, b) + return err + }) + + var wg sync.WaitGroup + errs := make(chan error, 20) + for i := 0; i < 10; i++ { + for _, pair := range [][2]uuid.UUID{{a, b}, {b, a}} { + wg.Add(1) + go func(first, second uuid.UUID) { + defer wg.Done() + errs <- f.txm.WithTransaction(context.Background(), func(ctx context.Context) error { + w1, w2, err := f.repo.LockWallets(ctx, first, second) + if err != nil { + return err + } + if w1.CustomerID != first || w2.CustomerID != second { + return errors.New("wallets returned out of argument order") + } + time.Sleep(20 * time.Millisecond) + return nil + }) + }(pair[0], pair[1]) + } + } + wg.Wait() + close(errs) + for err := range errs { + require.NoError(t, err) + } + + f.inTx(t, func(ctx context.Context) error { + _, _, err := f.repo.LockWallets(ctx, a, a) + assert.Error(t, err) + return nil + }) +} + +func TestWalletRepository_ListActiveLotsOrder(t *testing.T) { + f := newWalletFixture(t, 1) + customerID := f.customers[0] + now := time.Now() + at := func(d time.Duration) *time.Time { v := now.Add(d); return &v } + + create := func(expiresAt *time.Time) *entities.WalletLot { + var lot *entities.WalletLot + f.inTx(t, func(ctx context.Context) error { + _, err := f.repo.LockWallet(ctx, customerID) + require.NoError(t, err) + lot = f.credit(t, ctx, customerID, 10, expiresAt) + return nil + }) + return lot + } + neverOld := create(nil) + late := create(at(48 * time.Hour)) + soon := create(at(time.Hour)) + neverNew := create(nil) + expired := create(at(-time.Hour)) + empty := create(at(30 * time.Minute)) + f.inTx(t, func(ctx context.Context) error { + return f.repo.ConsumeLot(ctx, empty.ID, 10) + }) + + lots, err := f.repo.ListActiveLots(context.Background(), customerID, constants.WalletCurrencyPoint, now) + require.NoError(t, err) + + var got []uuid.UUID + for _, lot := range lots { + got = append(got, lot.ID) + } + assert.Equal(t, []uuid.UUID{soon.ID, late.ID, neverOld.ID, neverNew.ID}, got, + "soonest expiry first, no expiry last and oldest first, expired and empty lots left out") + assert.NotContains(t, got, expired.ID) + + coinLots, err := f.repo.ListActiveLots(context.Background(), customerID, constants.WalletCurrencyCoin, now) + require.NoError(t, err) + assert.Empty(t, coinLots) +} diff --git a/internal/repository/wallet_trace_repository.go b/internal/repository/wallet_trace_repository.go new file mode 100644 index 0000000..aad7677 --- /dev/null +++ b/internal/repository/wallet_trace_repository.go @@ -0,0 +1,109 @@ +package repository + +import ( + "context" + "errors" + "fmt" + + "github.com/google/uuid" + "gorm.io/gorm" + + "apskel-pos-be/internal/entities" +) + +// ErrWalletTransactionNotFound means the ledger row does not exist or belongs to +// another organization. +var ErrWalletTransactionNotFound = errors.New("wallet: transaction not found") + +// WalletTraceRepository reads what tracing a ledger row lot by lot needs +// (docs/prd-point-coin.md F7, §8.1). Nothing here changes a balance. +type WalletTraceRepository interface { + // GetTransaction returns ErrWalletTransactionNotFound unless the row belongs to + // the organization. + GetTransaction(ctx context.Context, organizationID, id uuid.UUID) (*entities.WalletTransaction, error) + GetTransactions(ctx context.Context, ids []uuid.UUID) ([]entities.WalletTransaction, error) + // ListAllocations returns what a debit took from each lot, in the order it took. + ListAllocations(ctx context.Context, transactionID uuid.UUID) ([]entities.WalletLotAllocation, error) + // ListLotsBySource returns the lots a credit created, oldest first. + ListLotsBySource(ctx context.Context, transactionID uuid.UUID) ([]entities.WalletLot, error) + GetLots(ctx context.Context, ids []uuid.UUID) ([]entities.WalletLot, error) + CustomerNames(ctx context.Context, ids []uuid.UUID) (map[uuid.UUID]string, error) +} + +type walletTraceRepository struct { + db *gorm.DB + names *walletAdminRepository +} + +func NewWalletTraceRepository(db *gorm.DB) WalletTraceRepository { + return &walletTraceRepository{db: db, names: &walletAdminRepository{db: db}} +} + +func (r *walletTraceRepository) GetTransaction(ctx context.Context, organizationID, id uuid.UUID) (*entities.WalletTransaction, error) { + var rows []entities.WalletTransaction + err := DBFromContext(ctx, r.db).WithContext(ctx). + Where("id = ? AND organization_id = ?", id, organizationID). + Limit(1). + Find(&rows).Error + if err != nil { + return nil, fmt.Errorf("failed to get wallet transaction: %w", err) + } + if len(rows) == 0 { + return nil, ErrWalletTransactionNotFound + } + return &rows[0], nil +} + +func (r *walletTraceRepository) GetTransactions(ctx context.Context, ids []uuid.UUID) ([]entities.WalletTransaction, error) { + var rows []entities.WalletTransaction + if len(ids) == 0 { + return rows, nil + } + if err := DBFromContext(ctx, r.db).WithContext(ctx).Where("id IN ?", ids).Find(&rows).Error; err != nil { + return nil, fmt.Errorf("failed to get wallet transactions: %w", err) + } + return rows, nil +} + +func (r *walletTraceRepository) ListAllocations(ctx context.Context, transactionID uuid.UUID) ([]entities.WalletLotAllocation, error) { + var rows []entities.WalletLotAllocation + // A debit draws in K9 order, so the lots' order is the order it took from them. + err := DBFromContext(ctx, r.db).WithContext(ctx). + Table("wallet_lot_allocations a"). + Select("a.*"). + Joins("JOIN wallet_lots l ON l.id = a.lot_id"). + Where("a.transaction_id = ?", transactionID). + Order("l.expires_at NULLS LAST, l.created_at, l.id"). + Scan(&rows).Error + if err != nil { + return nil, fmt.Errorf("failed to list wallet lot allocations: %w", err) + } + return rows, nil +} + +func (r *walletTraceRepository) ListLotsBySource(ctx context.Context, transactionID uuid.UUID) ([]entities.WalletLot, error) { + var lots []entities.WalletLot + err := DBFromContext(ctx, r.db).WithContext(ctx). + Where("source_transaction_id = ?", transactionID). + Order("created_at, id"). + Find(&lots).Error + if err != nil { + return nil, fmt.Errorf("failed to list wallet lots: %w", err) + } + return lots, nil +} + +func (r *walletTraceRepository) GetLots(ctx context.Context, ids []uuid.UUID) ([]entities.WalletLot, error) { + var lots []entities.WalletLot + if len(ids) == 0 { + return lots, nil + } + if err := DBFromContext(ctx, r.db).WithContext(ctx).Where("id IN ?", ids).Find(&lots).Error; err != nil { + return nil, fmt.Errorf("failed to get wallet lots: %w", err) + } + return lots, nil +} + +func (r *walletTraceRepository) CustomerNames(ctx context.Context, ids []uuid.UUID) (map[uuid.UUID]string, error) { + return r.names.CustomerNames(ctx, ids) +} diff --git a/internal/router/router.go b/internal/router/router.go index 6da7d3f..a06e26e 100644 --- a/internal/router/router.go +++ b/internal/router/router.go @@ -54,12 +54,19 @@ type Router struct { productOutletPriceHandler *handler.ProductOutletPriceHandler expenseHandler *handler.ExpenseHandler cashAdvanceHandler *handler.CashAdvanceHandler - authMiddleware *middleware.AuthMiddleware + walletAdminHandler *handler.WalletAdminHandler + loyaltySettingsHandler *handler.LoyaltySettingsHandler + customerPinHandler *handler.CustomerPinHandler + pointPaymentHandler *handler.PointPaymentHandler + customerOrderPaymentHandler *handler.CustomerOrderPaymentHandler + customerWalletHandler *handler.CustomerWalletHandler + customerDeviceHandler *handler.CustomerDeviceHandler + 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, 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, redisClient *redis.Client) *Router { return &Router{ config: cfg, @@ -105,6 +112,13 @@ func NewRouter(cfg *config.Config, healthHandler *handler.HealthHandler, authSer productOutletPriceHandler: handler.NewProductOutletPriceHandler(productOutletPriceService, productOutletPriceValidator), expenseHandler: handler.NewExpenseHandler(expenseService, expenseValidator), cashAdvanceHandler: handler.NewCashAdvanceHandler(cashAdvanceService, cashAdvanceValidator), + walletAdminHandler: handler.NewWalletAdminHandler(walletAdminService, walletValidator), + loyaltySettingsHandler: handler.NewLoyaltySettingsHandler(loyaltySettingsService), + customerPinHandler: handler.NewCustomerPinHandler(customerPinService), + pointPaymentHandler: handler.NewPointPaymentHandler(pointPaymentService), + customerOrderPaymentHandler: handler.NewCustomerOrderPaymentHandler(customerOrderPaymentService), + customerWalletHandler: handler.NewCustomerWalletHandler(customerWalletService), + customerDeviceHandler: handler.NewCustomerDeviceHandler(customerDeviceService), redisClient: redisClient, } } @@ -157,6 +171,22 @@ func (r *Router) addAppRoutes(rg *gin.Engine) { customer.GET("/points", r.customerPointsHandler.GetCustomerPoints) customer.GET("/tokens", r.customerPointsHandler.GetCustomerTokens) customer.GET("/wallet", r.customerPointsHandler.GetCustomerWallet) + customer.GET("/wallet/transactions", r.customerPointsHandler.GetCustomerWalletTransactions) + customer.GET("/wallet/expiring", r.customerPointsHandler.GetCustomerWalletExpiring) + customer.POST("/wallet/payment-code", r.customerPinHandler.IssuePaymentCode) + customer.GET("/wallet/exchange/preview", r.customerWalletHandler.PreviewExchange) + customer.POST("/wallet/exchange", r.customerWalletHandler.Exchange) + customer.GET("/wallet/transfer/recipient", r.customerWalletHandler.TransferRecipient) + customer.POST("/wallet/transfer", r.customerWalletHandler.Transfer) + customer.PUT("/devices", r.customerDeviceHandler.Register) + customer.DELETE("/devices/:device_id", r.customerDeviceHandler.Unregister) + 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) + customer.POST("/pin/otp", r.customerPinHandler.RequestOtp) + customer.POST("/pin", r.customerPinHandler.CreatePin) + customer.PUT("/pin", r.customerPinHandler.ChangePin) + customer.POST("/pin/reset", r.customerPinHandler.ResetPin) customer.GET("/games", r.customerPointsHandler.GetCustomerGames) customer.GET("/ferris-wheel", r.customerPointsHandler.GetFerrisWheelGame) customer.POST("/spin", r.spinGameHandler.PlaySpinGame) @@ -280,6 +310,7 @@ func (r *Router) addAppRoutes(rg *gin.Engine) { { orders.GET("", r.orderHandler.ListOrders) orders.GET("/:id", r.orderHandler.GetOrderByID) + orders.GET("/:id/point-payment/preview", r.pointPaymentHandler.Preview) orders.POST("", r.orderHandler.CreateOrder) orders.POST("/:id/add-items", middleware.IdempotencyMiddleware(r.redisClient), r.orderHandler.AddToOrder) orders.PUT("/:id", r.orderHandler.UpdateOrder) @@ -511,31 +542,6 @@ func (r *Router) addAppRoutes(rg *gin.Engine) { gamification := protected.Group("/marketing") gamification.Use(r.authMiddleware.RequireAdminOrManager()) { - //customerPoints := gamification.Group("/customer-points") - //{ - // customerPoints.POST("", r.gamificationHandler.CreateCustomerPoints) - // customerPoints.GET("", r.gamificationHandler.ListCustomerPoints) - // customerPoints.GET("/:id", r.gamificationHandler.GetCustomerPoints) - // customerPoints.PUT("/:id", r.gamificationHandler.UpdateCustomerPoints) - // customerPoints.DELETE("/:id", r.gamificationHandler.DeleteCustomerPoints) - // customerPoints.GET("/customer/:customer_id", r.gamificationHandler.GetCustomerPointsByCustomerID) - // customerPoints.POST("/customer/:customer_id/add", r.gamificationHandler.AddCustomerPoints) - // customerPoints.POST("/customer/:customer_id/deduct", r.gamificationHandler.DeductCustomerPoints) - //} - - // Customer Tokens - //customerTokens := gamification.Group("/customer-tokens") - //{ - // customerTokens.POST("", r.gamificationHandler.CreateCustomerTokens) - // customerTokens.GET("", r.gamificationHandler.ListCustomerTokens) - // customerTokens.GET("/:id", r.gamificationHandler.GetCustomerTokens) - // customerTokens.PUT("/:id", r.gamificationHandler.UpdateCustomerTokens) - // customerTokens.DELETE("/:id", r.gamificationHandler.DeleteCustomerTokens) - // customerTokens.GET("/customer/:customer_id/type/:token_type", r.gamificationHandler.GetCustomerTokensByCustomerIDAndType) - // customerTokens.POST("/customer/:customer_id/type/:token_type/add", r.gamificationHandler.AddCustomerTokens) - // customerTokens.POST("/customer/:customer_id/type/:token_type/deduct", r.gamificationHandler.DeductCustomerTokens) - //} - // Tiers tiers := gamification.Group("/tiers") { @@ -614,6 +620,22 @@ func (r *Router) addAppRoutes(rg *gin.Engine) { } // Campaign Rules + // EnakPoint & EnakCoin settings of the organization (docs/prd-point-coin.md F2) + gamification.GET("/loyalty-settings", r.loyaltySettingsHandler.GetOrganizationSettings) + gamification.PUT("/loyalty-settings", r.authMiddleware.RequireLoyaltyManager(), r.loyaltySettingsHandler.UpdateOrganizationSettings) + gamification.GET("/loyalty-settings/history", r.loyaltySettingsHandler.ListHistory) + + // EnakPoint & EnakCoin wallet of one customer (docs/prd-point-coin.md F7) + marketingCustomers := gamification.Group("/customers") + { + marketingCustomers.GET("/:id/wallet", r.walletAdminHandler.GetCustomerWallet) + marketingCustomers.POST("/:id/wallet/adjust", r.authMiddleware.RequireLoyaltyManager(), r.walletAdminHandler.AdjustCustomerWallet) + marketingCustomers.DELETE("/:id/pin", r.authMiddleware.RequireLoyaltyManager(), r.customerPinHandler.RemovePin) + marketingCustomers.GET("/:id/security-events", r.customerPinHandler.ListSecurityEvents) + } + // Trace one ledger row lot by lot back to where its balance came from (F7, §8.1) + gamification.GET("/wallet-transactions/:id/trace", r.walletAdminHandler.TraceTransaction) + campaignRules := gamification.Group("/campaign-rules") { campaignRules.POST("", r.campaignHandler.CreateCampaignRule) @@ -634,6 +656,9 @@ func (r *Router) addAppRoutes(rg *gin.Engine) { outlets.PUT("/detail/:id", r.outletHandler.UpdateOutlet) outlets.GET("/printer-setting/:outlet_id", r.outletSettingHandler.GetPrinterSettings) outlets.PUT("/printer-setting/:outlet_id", r.outletSettingHandler.UpdatePrinterSettings) + // EnakPoint & EnakCoin settings of the outlet (docs/prd-point-coin.md F1) + outlets.GET("/:outlet_id/loyalty-settings", r.loyaltySettingsHandler.GetOutletSettings) + outlets.PUT("/:outlet_id/loyalty-settings", r.authMiddleware.RequireLoyaltyManager(), r.loyaltySettingsHandler.UpdateOutletSettings) outlets.GET("/:outlet_id/tables/available", r.tableHandler.GetAvailableTables) outlets.GET("/:outlet_id/tables/occupied", r.tableHandler.GetOccupiedTables) // Reports diff --git a/internal/router/router_test.go b/internal/router/router_test.go new file mode 100644 index 0000000..40db753 --- /dev/null +++ b/internal/router/router_test.go @@ -0,0 +1,59 @@ +package router + +import ( + "testing" + + "github.com/stretchr/testify/assert" + + "apskel-pos-be/config" + "apskel-pos-be/internal/middleware" +) + +// Gin panics at startup when two routes disagree on a path parameter's name at the +// same position (say /outlets/:id/x next to /outlets/:outlet_id/y). Registering every +// route here catches that in a test instead of on deploy. Handlers are nil: nothing is +// served, only registered. +func TestAllRoutesRegister(t *testing.T) { + r := &Router{ + config: &config.Config{}, + authMiddleware: middleware.NewAuthMiddleware(nil), + customerAuthMiddleware: middleware.NewCustomerAuthMiddleware("test"), + } + engine := r.Init() + + registered := map[string]bool{} + for _, route := range engine.Routes() { + registered[route.Method+" "+route.Path] = true + } + for _, want := range []string{ + "GET /api/v1/customer/wallet", + "GET /api/v1/customer/wallet/transactions", + "GET /api/v1/customer/wallet/expiring", + "GET /api/v1/marketing/customers/:id/wallet", + "POST /api/v1/marketing/customers/:id/wallet/adjust", + "GET /api/v1/marketing/wallet-transactions/:id/trace", + "GET /api/v1/outlets/:outlet_id/loyalty-settings", + "PUT /api/v1/outlets/:outlet_id/loyalty-settings", + "GET /api/v1/marketing/loyalty-settings", + "PUT /api/v1/marketing/loyalty-settings", + "GET /api/v1/marketing/loyalty-settings/history", + "POST /api/v1/customer/wallet/payment-code", + "GET /api/v1/customer/wallet/exchange/preview", + "POST /api/v1/customer/wallet/exchange", + "GET /api/v1/customer/wallet/transfer/recipient", + "POST /api/v1/customer/wallet/transfer", + "PUT /api/v1/customer/devices", + "DELETE /api/v1/customer/devices/:device_id", + "GET /api/v1/orders/:id/point-payment/preview", + "POST /api/v1/customer/orders/:id/pay-with-points", + "GET /api/v1/customer/pin/status", + "POST /api/v1/customer/pin/otp", + "POST /api/v1/customer/pin", + "PUT /api/v1/customer/pin", + "POST /api/v1/customer/pin/reset", + "DELETE /api/v1/marketing/customers/:id/pin", + "GET /api/v1/marketing/customers/:id/security-events", + } { + assert.True(t, registered[want], want) + } +} diff --git a/internal/service/campaign_service.go b/internal/service/campaign_service.go index 95a671a..bc42ba2 100644 --- a/internal/service/campaign_service.go +++ b/internal/service/campaign_service.go @@ -177,7 +177,7 @@ func (s *campaignService) CreateCampaignRule(ctx context.Context, req *contract. } // Validate reward value based on reward type - if req.RewardType == "POINTS" || req.RewardType == "TOKENS" { + if req.RewardType == "POINTS" || req.RewardType == "COINS" || req.RewardType == "TOKENS" { if req.RewardValue == nil || *req.RewardValue <= 0 { return nil, fmt.Errorf("reward value must be positive for %s type", req.RewardType) } @@ -247,7 +247,7 @@ func (s *campaignService) UpdateCampaignRule(ctx context.Context, req *contract. } // Validate reward value based on reward type - if req.RewardType == "POINTS" || req.RewardType == "TOKENS" { + if req.RewardType == "POINTS" || req.RewardType == "COINS" || req.RewardType == "TOKENS" { if req.RewardValue == nil || *req.RewardValue <= 0 { return nil, fmt.Errorf("reward value must be positive for %s type", req.RewardType) } @@ -295,13 +295,13 @@ func (s *campaignService) GetCampaignRulesByCampaignID(ctx context.Context, camp } func (s *campaignService) validateCampaignType(campaignType string) error { - validTypes := []string{"REWARD", "POINTS", "TOKENS", "MIXED"} + validTypes := []string{"REWARD", "POINTS", "COINS", "TOKENS", "MIXED"} for _, validType := range validTypes { if campaignType == validType { return nil } } - return fmt.Errorf("invalid campaign type: %s. Valid types are: REWARD, POINTS, TOKENS, MIXED", campaignType) + return fmt.Errorf("invalid campaign type: %s. Valid types are: REWARD, POINTS, COINS, MIXED", campaignType) } func (s *campaignService) validateDateRange(startDate, endDate time.Time) error { @@ -335,7 +335,7 @@ func (s *campaignService) validateCampaignRules(rules []contract.CampaignRuleStr } // Validate reward value based on reward type - if rule.RewardType == "POINTS" || rule.RewardType == "TOKENS" { + if rule.RewardType == "POINTS" || rule.RewardType == "COINS" || rule.RewardType == "TOKENS" { if rule.RewardValue == nil || *rule.RewardValue <= 0 { return fmt.Errorf("reward value must be positive for %s type in rule %d", rule.RewardType, i+1) } @@ -365,11 +365,11 @@ func (s *campaignService) validateRuleType(ruleType string) error { } func (s *campaignService) validateRewardType(rewardType string) error { - validTypes := []string{"POINTS", "TOKENS", "REWARD"} + validTypes := []string{"POINTS", "COINS", "TOKENS", "REWARD"} for _, validType := range validTypes { if rewardType == validType { return nil } } - return fmt.Errorf("invalid reward type: %s. Valid types are: POINTS, TOKENS, REWARD", rewardType) + return fmt.Errorf("invalid reward type: %s. Valid types are: POINTS, COINS, REWARD", rewardType) } diff --git a/internal/service/customer_device_service.go b/internal/service/customer_device_service.go new file mode 100644 index 0000000..157d93b --- /dev/null +++ b/internal/service/customer_device_service.go @@ -0,0 +1,58 @@ +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" +) + +// CustomerDeviceService registers the customer app's devices for push notifications. +type CustomerDeviceService interface { + Register(ctx context.Context, customerID uuid.UUID, req *contract.RegisterCustomerDeviceRequest) *contract.Response + Unregister(ctx context.Context, customerID uuid.UUID, deviceID string) *contract.Response +} + +type CustomerDeviceServiceImpl struct { + devices *processor.CustomerDeviceProcessor +} + +func NewCustomerDeviceService(devices *processor.CustomerDeviceProcessor) *CustomerDeviceServiceImpl { + return &CustomerDeviceServiceImpl{devices: devices} +} + +func (s *CustomerDeviceServiceImpl) Register(ctx context.Context, customerID uuid.UUID, req *contract.RegisterCustomerDeviceRequest) *contract.Response { + err := s.devices.Register(ctx, repository.CustomerDevice{ + CustomerID: customerID, + DeviceID: req.DeviceID, + FCMToken: req.FCMToken, + Platform: req.Platform, + AppVersion: req.AppVersion, + }) + if err != nil { + return customerDeviceErrorResponse(err) + } + return contract.BuildSuccessResponse(map[string]interface{}{"device_id": req.DeviceID}) +} + +func (s *CustomerDeviceServiceImpl) Unregister(ctx context.Context, customerID uuid.UUID, deviceID string) *contract.Response { + if err := s.devices.Unregister(ctx, customerID, deviceID); err != nil { + return customerDeviceErrorResponse(err) + } + return contract.BuildSuccessResponse(map[string]interface{}{"device_id": deviceID}) +} + +func customerDeviceErrorResponse(err error) *contract.Response { + code := constants.InternalServerErrorCode + if errors.Is(err, processor.ErrInvalidCustomerDevice) { + code = constants.ValidationErrorCode + } + return contract.BuildErrorResponse([]*contract.ResponseError{ + contract.NewResponseError(code, constants.RequestEntity, err.Error()), + }) +} diff --git a/internal/service/customer_order_payment_service.go b/internal/service/customer_order_payment_service.go new file mode 100644 index 0000000..b7e57c4 --- /dev/null +++ b/internal/service/customer_order_payment_service.go @@ -0,0 +1,34 @@ +package service + +import ( + "context" + + "github.com/google/uuid" + + "apskel-pos-be/internal/contract" + "apskel-pos-be/internal/models" + "apskel-pos-be/internal/processor" + "apskel-pos-be/internal/transformer" +) + +// CustomerOrderPaymentService lets customers pay their own orders with EnakPoint in the +// app or a self-order (docs/prd-point-coin.md F9). +type CustomerOrderPaymentService interface { + PayWithPoints(ctx context.Context, customerID, orderID uuid.UUID, req *contract.PayWithPointsRequest, info models.CustomerPinRequestInfo) *contract.Response +} + +type CustomerOrderPaymentServiceImpl struct { + orders processor.OrderProcessor +} + +func NewCustomerOrderPaymentService(orders processor.OrderProcessor) *CustomerOrderPaymentServiceImpl { + return &CustomerOrderPaymentServiceImpl{orders: orders} +} + +func (s *CustomerOrderPaymentServiceImpl) PayWithPoints(ctx context.Context, customerID, orderID uuid.UUID, req *contract.PayWithPointsRequest, info models.CustomerPinRequestInfo) *contract.Response { + payment, err := s.orders.PayWithPointsInApp(ctx, customerID, orderID, req.Points, req.Pin, info) + if err != nil { + return PointPaymentErrorResponse(err) + } + return contract.BuildSuccessResponse(transformer.PaymentModelToContract(payment)) +} diff --git a/internal/service/customer_pin_service.go b/internal/service/customer_pin_service.go new file mode 100644 index 0000000..9fdc5b4 --- /dev/null +++ b/internal/service/customer_pin_service.go @@ -0,0 +1,140 @@ +package service + +import ( + "context" + "errors" + + "github.com/google/uuid" + + "apskel-pos-be/internal/appcontext" + "apskel-pos-be/internal/constants" + "apskel-pos-be/internal/contract" + "apskel-pos-be/internal/models" + "apskel-pos-be/internal/processor" + "apskel-pos-be/internal/repository" +) + +// CustomerPinService serves the customer's PIN (docs/prd-point-coin.md F11) and the +// dashboard's view of it. +type CustomerPinService interface { + Status(ctx context.Context, customerID uuid.UUID) *contract.Response + RequestOtp(ctx context.Context, customerID uuid.UUID, req *contract.RequestPinOtpRequest) *contract.Response + CreatePin(ctx context.Context, customerID uuid.UUID, req *contract.CreateCustomerPinRequest, info models.CustomerPinRequestInfo) *contract.Response + ChangePin(ctx context.Context, customerID uuid.UUID, req *contract.ChangeCustomerPinRequest, info models.CustomerPinRequestInfo) *contract.Response + ResetPin(ctx context.Context, customerID uuid.UUID, req *contract.ResetCustomerPinRequest, info models.CustomerPinRequestInfo) *contract.Response + + RemovePin(ctx context.Context, apctx *appcontext.ContextInfo, customerID uuid.UUID, req *contract.RemoveCustomerPinRequest, info models.CustomerPinRequestInfo) *contract.Response + ListSecurityEvents(ctx context.Context, apctx *appcontext.ContextInfo, customerID uuid.UUID, page, limit int) *contract.Response + + // IssuePaymentCode checks the PIN and returns a one-time code for the cashier (F9). + IssuePaymentCode(ctx context.Context, customerID uuid.UUID, req *contract.IssuePaymentCodeRequest, info models.CustomerPinRequestInfo) *contract.Response +} + +type CustomerPinServiceImpl struct { + pins *processor.CustomerPinProcessor + codes *processor.PaymentCodeProcessor +} + +func NewCustomerPinService(pins *processor.CustomerPinProcessor, codes *processor.PaymentCodeProcessor) *CustomerPinServiceImpl { + return &CustomerPinServiceImpl{pins: pins, codes: codes} +} + +func (s *CustomerPinServiceImpl) Status(ctx context.Context, customerID uuid.UUID) *contract.Response { + status, err := s.pins.Status(ctx, customerID) + if err != nil { + return PinErrorResponse(err) + } + return contract.BuildSuccessResponse(status) +} + +func (s *CustomerPinServiceImpl) RequestOtp(ctx context.Context, customerID uuid.UUID, req *contract.RequestPinOtpRequest) *contract.Response { + otp, err := s.pins.RequestOtp(ctx, customerID, req.Purpose) + if err != nil { + return PinErrorResponse(err) + } + return contract.BuildSuccessResponse(otp) +} + +func (s *CustomerPinServiceImpl) CreatePin(ctx context.Context, customerID uuid.UUID, req *contract.CreateCustomerPinRequest, info models.CustomerPinRequestInfo) *contract.Response { + if err := s.pins.CreatePin(ctx, customerID, req.OtpToken, req.OtpCode, req.Pin, req.ConfirmPin, info); err != nil { + return PinErrorResponse(err) + } + return s.Status(ctx, customerID) +} + +func (s *CustomerPinServiceImpl) ChangePin(ctx context.Context, customerID uuid.UUID, req *contract.ChangeCustomerPinRequest, info models.CustomerPinRequestInfo) *contract.Response { + if err := s.pins.ChangePin(ctx, customerID, req.OldPin, req.Pin, req.ConfirmPin, info); err != nil { + return PinErrorResponse(err) + } + return s.Status(ctx, customerID) +} + +func (s *CustomerPinServiceImpl) ResetPin(ctx context.Context, customerID uuid.UUID, req *contract.ResetCustomerPinRequest, info models.CustomerPinRequestInfo) *contract.Response { + if err := s.pins.ResetPin(ctx, customerID, req.OtpToken, req.OtpCode, req.Pin, req.ConfirmPin, info); err != nil { + return PinErrorResponse(err) + } + return s.Status(ctx, customerID) +} + +func (s *CustomerPinServiceImpl) RemovePin(ctx context.Context, apctx *appcontext.ContextInfo, customerID uuid.UUID, req *contract.RemoveCustomerPinRequest, info models.CustomerPinRequestInfo) *contract.Response { + if err := s.pins.RemovePinByAdmin(ctx, apctx.OrganizationID, customerID, apctx.UserID, req.Reason, info); err != nil { + return PinErrorResponse(err) + } + return contract.BuildSuccessResponse(map[string]interface{}{"message": "PIN removed; the customer has to create a new one"}) +} + +func (s *CustomerPinServiceImpl) ListSecurityEvents(ctx context.Context, apctx *appcontext.ContextInfo, customerID uuid.UUID, page, limit int) *contract.Response { + events, err := s.pins.ListEvents(ctx, apctx.OrganizationID, customerID, page, limit) + if err != nil { + return PinErrorResponse(err) + } + return contract.BuildSuccessResponse(events) +} + +// PinErrorResponse turns an error from a PIN-guarded action into a response the apps +// can act on. A *processor.PinError keeps its code (PIN_NOT_SET, PIN_INVALID, +// PIN_LOCKED, TRANSFER_BLOCKED) and puts the attempts left or the time it lifts in the +// response data. Other errors map to a validation or server error. +func PinErrorResponse(err error) *contract.Response { + var pinErr *processor.PinError + if errors.As(err, &pinErr) { + data := map[string]interface{}{"code": pinErr.Code} + switch pinErr.Code { + case processor.PinErrInvalid: + data["remaining_attempts"] = pinErr.RemainingAttempts + case processor.PinErrLocked: + data["locked_until"] = pinErr.Until + case processor.PinErrTransferBlocked: + data["transfer_blocked_until"] = pinErr.Until + } + return &contract.Response{ + Success: false, + Data: data, + Errors: []*contract.ResponseError{contract.NewResponseError(pinErr.Code, constants.CustomerPinServiceEntity, pinErr.Error())}, + } + } + + code := constants.InternalServerErrorCode + switch { + case errors.Is(err, repository.ErrPinCustomerNotFound): + code = constants.NotFoundErrorCode + case errors.Is(err, processor.ErrPinOtpTooSoon): + code = constants.TooManyRequestsErrorCode + case errors.Is(err, processor.ErrInvalidPinInput), + errors.Is(err, processor.ErrPinAlreadySet), + errors.Is(err, processor.ErrPinOtpInvalid), + errors.Is(err, processor.ErrPinNoPhone): + code = constants.ValidationErrorCode + } + return contract.BuildErrorResponse([]*contract.ResponseError{ + contract.NewResponseError(code, constants.CustomerPinServiceEntity, err.Error()), + }) +} + +func (s *CustomerPinServiceImpl) IssuePaymentCode(ctx context.Context, customerID uuid.UUID, req *contract.IssuePaymentCodeRequest, info models.CustomerPinRequestInfo) *contract.Response { + code, err := s.codes.Issue(ctx, customerID, req.Pin, info) + if err != nil { + return PinErrorResponse(err) + } + return contract.BuildSuccessResponse(code) +} diff --git a/internal/service/customer_pin_service_test.go b/internal/service/customer_pin_service_test.go new file mode 100644 index 0000000..d59a69f --- /dev/null +++ b/internal/service/customer_pin_service_test.go @@ -0,0 +1,50 @@ +package service + +import ( + "fmt" + "net/http" + "testing" + "time" + + "github.com/stretchr/testify/assert" + + "apskel-pos-be/internal/processor" + "apskel-pos-be/internal/repository" + "apskel-pos-be/internal/util" +) + +func TestPinErrorResponse(t *testing.T) { + until := time.Date(2026, 9, 30, 12, 30, 0, 0, time.UTC) + for name, c := range map[string]struct { + err error + code string + status int + data map[string]interface{} + }{ + "not set": {&processor.PinError{Code: processor.PinErrNotSet}, "PIN_NOT_SET", http.StatusForbidden, map[string]interface{}{"code": "PIN_NOT_SET"}}, + "invalid": {fmt.Errorf("pay: %w", &processor.PinError{Code: processor.PinErrInvalid, RemainingAttempts: 2}), "PIN_INVALID", http.StatusBadRequest, map[string]interface{}{"code": "PIN_INVALID", "remaining_attempts": 2}}, + "locked": {&processor.PinError{Code: processor.PinErrLocked, Until: &until}, "PIN_LOCKED", http.StatusLocked, map[string]interface{}{"code": "PIN_LOCKED", "locked_until": &until}}, + "transfer": {&processor.PinError{Code: processor.PinErrTransferBlocked, Until: &until}, "TRANSFER_BLOCKED", http.StatusForbidden, map[string]interface{}{"code": "TRANSFER_BLOCKED", "transfer_blocked_until": &until}}, + } { + resp := PinErrorResponse(c.err) + assert.False(t, resp.Success, name) + assert.Equal(t, c.code, resp.Errors[0].Code, name) + assert.Equal(t, c.status, util.MapErrorCodeToHttpStatus(resp.Errors[0].Code), name) + assert.Equal(t, c.data, resp.Data, name) + } + + for name, c := range map[string]struct { + err error + status int + }{ + "weak PIN": {fmt.Errorf("%w: too easy", processor.ErrInvalidPinInput), http.StatusBadRequest}, + "bad OTP": {processor.ErrPinOtpInvalid, http.StatusBadRequest}, + "already set": {processor.ErrPinAlreadySet, http.StatusBadRequest}, + "too soon": {processor.ErrPinOtpTooSoon, http.StatusTooManyRequests}, + "no customer": {repository.ErrPinCustomerNotFound, http.StatusNotFound}, + "anything else": {fmt.Errorf("db down"), http.StatusInternalServerError}, + } { + resp := PinErrorResponse(c.err) + assert.Equal(t, c.status, util.MapErrorCodeToHttpStatus(resp.Errors[0].Code), name) + } +} diff --git a/internal/service/customer_points_service.go b/internal/service/customer_points_service.go index 20b473d..6e85854 100644 --- a/internal/service/customer_points_service.go +++ b/internal/service/customer_points_service.go @@ -12,6 +12,8 @@ type CustomerPointsService interface { GetCustomerPoints(ctx context.Context, customerID string) (*models.GetCustomerPointsResponse, error) GetCustomerTokens(ctx context.Context, customerID string) (*models.GetCustomerTokensResponse, error) GetCustomerWallet(ctx context.Context, customerID string) (*models.GetCustomerWalletResponse, error) + GetCustomerWalletTransactions(ctx context.Context, customerID string, query models.ListCustomerWalletTransactionsQuery) (*models.PaginatedResponse[models.CustomerWalletTransaction], error) + GetCustomerWalletExpiring(ctx context.Context, customerID string) (*models.CustomerWalletExpiringList, error) GetCustomerGames(ctx context.Context) (*models.GetCustomerGamesResponse, error) GetFerrisWheelGame(ctx context.Context) (*models.GetFerrisWheelGameResponse, error) } @@ -82,3 +84,17 @@ func (s *customerPointsService) GetFerrisWheelGame(ctx context.Context) (*models return response, nil } + +func (s *customerPointsService) GetCustomerWalletTransactions(ctx context.Context, customerID string, query models.ListCustomerWalletTransactionsQuery) (*models.PaginatedResponse[models.CustomerWalletTransaction], error) { + if customerID == "" { + return nil, fmt.Errorf("customer ID is required") + } + return s.customerPointsProcessor.GetCustomerWalletTransactionsAPI(ctx, customerID, query) +} + +func (s *customerPointsService) GetCustomerWalletExpiring(ctx context.Context, customerID string) (*models.CustomerWalletExpiringList, error) { + if customerID == "" { + return nil, fmt.Errorf("customer ID is required") + } + return s.customerPointsProcessor.GetCustomerWalletExpiringAPI(ctx, customerID) +} diff --git a/internal/service/customer_wallet_service.go b/internal/service/customer_wallet_service.go new file mode 100644 index 0000000..897a32e --- /dev/null +++ b/internal/service/customer_wallet_service.go @@ -0,0 +1,91 @@ +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" +) + +// CustomerWalletService moves balance on the customer's own request: exchanging +// EnakCoin into EnakPoint and sending either to another customer +// (docs/prd-point-coin.md F4, F5). +type CustomerWalletService interface { + PreviewExchange(ctx context.Context, customerID uuid.UUID, coins int64) *contract.Response + Exchange(ctx context.Context, customerID uuid.UUID, req *contract.ExchangeCoinsRequest, idempotencyKey string, info models.CustomerPinRequestInfo) *contract.Response + TransferRecipient(ctx context.Context, customerID uuid.UUID, phoneNumber string) *contract.Response + Transfer(ctx context.Context, customerID uuid.UUID, req *contract.TransferWalletRequest, idempotencyKey string, info models.CustomerPinRequestInfo) *contract.Response +} + +type CustomerWalletServiceImpl struct { + exchanges *processor.WalletExchangeProcessor + transfers *processor.WalletTransferProcessor +} + +func NewCustomerWalletService(exchanges *processor.WalletExchangeProcessor, transfers *processor.WalletTransferProcessor) *CustomerWalletServiceImpl { + return &CustomerWalletServiceImpl{exchanges: exchanges, transfers: transfers} +} + +func (s *CustomerWalletServiceImpl) TransferRecipient(ctx context.Context, customerID uuid.UUID, phoneNumber string) *contract.Response { + recipient, err := s.transfers.Recipient(ctx, customerID, phoneNumber) + if err != nil { + return walletMoveErrorResponse(err) + } + return contract.BuildSuccessResponse(recipient) +} + +func (s *CustomerWalletServiceImpl) Transfer(ctx context.Context, customerID uuid.UUID, req *contract.TransferWalletRequest, idempotencyKey string, info models.CustomerPinRequestInfo) *contract.Response { + result, err := s.transfers.Transfer(ctx, customerID, models.WalletTransfer{ + Currency: req.Currency, + Amount: req.Amount, + RecipientPhone: req.RecipientPhone, + }, req.Pin, idempotencyKey, info) + if err != nil { + return walletMoveErrorResponse(err) + } + return contract.BuildSuccessResponse(result) +} + +func (s *CustomerWalletServiceImpl) PreviewExchange(ctx context.Context, customerID uuid.UUID, coins int64) *contract.Response { + preview, err := s.exchanges.Preview(ctx, customerID, coins) + if err != nil { + return walletMoveErrorResponse(err) + } + return contract.BuildSuccessResponse(preview) +} + +func (s *CustomerWalletServiceImpl) Exchange(ctx context.Context, customerID uuid.UUID, req *contract.ExchangeCoinsRequest, idempotencyKey string, info models.CustomerPinRequestInfo) *contract.Response { + result, err := s.exchanges.Exchange(ctx, customerID, req.Coins, req.Pin, idempotencyKey, info) + if err != nil { + return walletMoveErrorResponse(err) + } + return contract.BuildSuccessResponse(result) +} + +// walletMoveErrorResponse keeps the PIN codes the apps act on, and tells a refused +// request apart from a server failure. +func walletMoveErrorResponse(err error) *contract.Response { + var pinErr *processor.PinError + if errors.As(err, &pinErr) { + return PinErrorResponse(err) + } + code := constants.InternalServerErrorCode + switch { + case errors.Is(err, repository.ErrWalletNotFound), + errors.Is(err, processor.ErrWalletRecipientNotFound): + code = constants.NotFoundErrorCode + case errors.Is(err, processor.ErrWalletMoveRejected), + errors.Is(err, processor.ErrWalletIdempotencyConflict), + errors.Is(err, processor.ErrWalletInvalidEntry): + code = constants.ValidationErrorCode + } + return contract.BuildErrorResponse([]*contract.ResponseError{ + contract.NewResponseError(code, constants.WalletServiceEntity, err.Error()), + }) +} diff --git a/internal/service/earning_backfill_job.go b/internal/service/earning_backfill_job.go new file mode 100644 index 0000000..131434c --- /dev/null +++ b/internal/service/earning_backfill_job.go @@ -0,0 +1,74 @@ +package service + +import ( + "context" + "sync" + "time" + + "apskel-pos-be/internal/logger" +) + +const ( + defaultEarningBackfillInterval = 30 * time.Minute + // How far back to look for paid orders that never earned. + earningBackfillWindow = 72 * time.Hour + // Orders looked at per run at most, so one run cannot run away. + earningBackfillMaxOrders = 5000 +) + +type missingEarner interface { + EarnMissing(ctx context.Context, since time.Time, maxOrders int) (checked, earned int, err error) +} + +// EarningBackfillJob is the safety net behind earning at payment time +// (docs/prd-point-coin.md F3, PC-203). Every run it earns for orders paid in the last +// few days that should have earned and did not, for example because the database was +// briefly unreachable right after the payment committed. +type EarningBackfillJob struct { + earner missingEarner + now func() time.Time + stopCh chan struct{} + stopOnce sync.Once +} + +func NewEarningBackfillJob(earner missingEarner) *EarningBackfillJob { + return &EarningBackfillJob{earner: earner, now: time.Now, stopCh: make(chan struct{})} +} + +func (j *EarningBackfillJob) Start(interval time.Duration) { + if interval <= 0 { + interval = defaultEarningBackfillInterval + } + go func() { + j.RunOnce(context.Background()) + ticker := time.NewTicker(interval) + defer ticker.Stop() + for { + select { + case <-ticker.C: + j.RunOnce(context.Background()) + case <-j.stopCh: + return + } + } + }() + logger.NonContext.Infof("Earning backfill job started (interval: %s)", interval) +} + +func (j *EarningBackfillJob) Stop() { + j.stopOnce.Do(func() { close(j.stopCh) }) +} + +// RunOnce earns for every missed order in the window and reports how many it fixed. +// It is quiet when nothing was missed. +func (j *EarningBackfillJob) RunOnce(ctx context.Context) int { + checked, earned, err := j.earner.EarnMissing(ctx, j.now().Add(-earningBackfillWindow), earningBackfillMaxOrders) + if err != nil { + logger.NonContext.Error("Earning backfill failed to run", err) + } + if earned > 0 { + logger.NonContext.WarnWithFields("Earning backfill credited orders that had missed their earning", + map[string]interface{}{"checked": checked, "earned": earned}, nil) + } + return earned +} diff --git a/internal/service/earning_backfill_job_test.go b/internal/service/earning_backfill_job_test.go new file mode 100644 index 0000000..31146b5 --- /dev/null +++ b/internal/service/earning_backfill_job_test.go @@ -0,0 +1,46 @@ +package service + +import ( + "context" + "errors" + "testing" + "time" + + "github.com/stretchr/testify/assert" + + "apskel-pos-be/internal/logger" +) + +type missingEarnerFake struct { + since time.Time + max int + earned int + err error + calls int +} + +func (f *missingEarnerFake) EarnMissing(_ context.Context, since time.Time, maxOrders int) (int, int, error) { + f.calls++ + f.since, f.max = since, maxOrders + return f.earned * 2, f.earned, f.err +} + +func TestEarningBackfillJob(t *testing.T) { + logger.Setup("fatal", "json") + now := time.Date(2026, 9, 30, 12, 0, 0, 0, time.UTC) + earner := &missingEarnerFake{earned: 3} + job := NewEarningBackfillJob(earner) + job.now = func() time.Time { return now } + + assert.Equal(t, 3, job.RunOnce(context.Background())) + assert.Equal(t, now.Add(-72*time.Hour), earner.since, "looks back three days") + assert.Equal(t, earningBackfillMaxOrders, earner.max) + + // A failing run is logged, not fatal. + earner.earned, earner.err = 0, errors.New("db down") + assert.Equal(t, 0, job.RunOnce(context.Background())) + + job.Start(time.Hour) + job.Stop() + job.Stop() +} diff --git a/internal/service/gamification_service.go b/internal/service/gamification_service.go index 6b5b22c..7096fe1 100644 --- a/internal/service/gamification_service.go +++ b/internal/service/gamification_service.go @@ -11,26 +11,6 @@ import ( ) type GamificationService interface { - // Customer Points - CreateCustomerPoints(ctx context.Context, req *contract.CreateCustomerPointsRequest) (*contract.CustomerPointsResponse, error) - GetCustomerPoints(ctx context.Context, id uuid.UUID) (*contract.CustomerPointsResponse, error) - GetCustomerPointsByCustomerID(ctx context.Context, customerID uuid.UUID) (*contract.CustomerPointsResponse, error) - ListCustomerPoints(ctx context.Context, query *contract.ListCustomerPointsRequest) (*contract.PaginatedCustomerPointsResponse, error) - UpdateCustomerPoints(ctx context.Context, id uuid.UUID, req *contract.UpdateCustomerPointsRequest) (*contract.CustomerPointsResponse, error) - DeleteCustomerPoints(ctx context.Context, id uuid.UUID) error - AddCustomerPoints(ctx context.Context, customerID uuid.UUID, req *contract.AddCustomerPointsRequest) (*contract.CustomerPointsResponse, error) - DeductCustomerPoints(ctx context.Context, customerID uuid.UUID, req *contract.DeductCustomerPointsRequest) (*contract.CustomerPointsResponse, error) - - // Customer Tokens - CreateCustomerTokens(ctx context.Context, req *contract.CreateCustomerTokensRequest) (*contract.CustomerTokensResponse, error) - GetCustomerTokens(ctx context.Context, id uuid.UUID) (*contract.CustomerTokensResponse, error) - GetCustomerTokensByCustomerIDAndType(ctx context.Context, customerID uuid.UUID, tokenType string) (*contract.CustomerTokensResponse, error) - ListCustomerTokens(ctx context.Context, query *contract.ListCustomerTokensRequest) (*contract.PaginatedCustomerTokensResponse, error) - UpdateCustomerTokens(ctx context.Context, id uuid.UUID, req *contract.UpdateCustomerTokensRequest) (*contract.CustomerTokensResponse, error) - DeleteCustomerTokens(ctx context.Context, id uuid.UUID) error - AddCustomerTokens(ctx context.Context, customerID uuid.UUID, tokenType string, req *contract.AddCustomerTokensRequest) (*contract.CustomerTokensResponse, error) - DeductCustomerTokens(ctx context.Context, customerID uuid.UUID, tokenType string, req *contract.DeductCustomerTokensRequest) (*contract.CustomerTokensResponse, error) - // Tiers CreateTier(ctx context.Context, req *contract.CreateTierRequest) (*contract.TierResponse, error) GetTier(ctx context.Context, id uuid.UUID) (*contract.TierResponse, error) @@ -72,18 +52,14 @@ type GamificationService interface { } type GamificationServiceImpl struct { - customerPointsProcessor *processor.CustomerPointsProcessor - customerTokensProcessor *processor.CustomerTokensProcessor - tierProcessor *processor.TierProcessor - gameProcessor *processor.GameProcessor - gamePrizeProcessor *processor.GamePrizeProcessor - gamePlayProcessor *processor.GamePlayProcessor - omsetTrackerProcessor *processor.OmsetTrackerProcessor + tierProcessor *processor.TierProcessor + gameProcessor *processor.GameProcessor + gamePrizeProcessor *processor.GamePrizeProcessor + gamePlayProcessor *processor.GamePlayProcessor + omsetTrackerProcessor *processor.OmsetTrackerProcessor } func NewGamificationService( - customerPointsProcessor *processor.CustomerPointsProcessor, - customerTokensProcessor *processor.CustomerTokensProcessor, tierProcessor *processor.TierProcessor, gameProcessor *processor.GameProcessor, gamePrizeProcessor *processor.GamePrizeProcessor, @@ -91,144 +67,14 @@ func NewGamificationService( omsetTrackerProcessor *processor.OmsetTrackerProcessor, ) *GamificationServiceImpl { return &GamificationServiceImpl{ - customerPointsProcessor: customerPointsProcessor, - customerTokensProcessor: customerTokensProcessor, - tierProcessor: tierProcessor, - gameProcessor: gameProcessor, - gamePrizeProcessor: gamePrizeProcessor, - gamePlayProcessor: gamePlayProcessor, - omsetTrackerProcessor: omsetTrackerProcessor, + tierProcessor: tierProcessor, + gameProcessor: gameProcessor, + gamePrizeProcessor: gamePrizeProcessor, + gamePlayProcessor: gamePlayProcessor, + omsetTrackerProcessor: omsetTrackerProcessor, } } -// Customer Points Service Methods -func (s *GamificationServiceImpl) CreateCustomerPoints(ctx context.Context, req *contract.CreateCustomerPointsRequest) (*contract.CustomerPointsResponse, error) { - modelReq := transformer.CreateCustomerPointsRequestToModel(req) - response, err := s.customerPointsProcessor.CreateCustomerPoints(ctx, modelReq) - if err != nil { - return nil, err - } - return transformer.CustomerPointsModelToResponse(response), nil -} - -func (s *GamificationServiceImpl) GetCustomerPoints(ctx context.Context, id uuid.UUID) (*contract.CustomerPointsResponse, error) { - response, err := s.customerPointsProcessor.GetCustomerPoints(ctx, id) - if err != nil { - return nil, err - } - return transformer.CustomerPointsModelToResponse(response), nil -} - -func (s *GamificationServiceImpl) GetCustomerPointsByCustomerID(ctx context.Context, customerID uuid.UUID) (*contract.CustomerPointsResponse, error) { - response, err := s.customerPointsProcessor.GetCustomerPointsByCustomerID(ctx, customerID) - if err != nil { - return nil, err - } - return transformer.CustomerPointsModelToResponse(response), nil -} - -func (s *GamificationServiceImpl) ListCustomerPoints(ctx context.Context, query *contract.ListCustomerPointsRequest) (*contract.PaginatedCustomerPointsResponse, error) { - modelQuery := transformer.ListCustomerPointsRequestToModel(query) - response, err := s.customerPointsProcessor.ListCustomerPoints(ctx, modelQuery) - if err != nil { - return nil, err - } - return transformer.PaginatedCustomerPointsResponseToContract(response), nil -} - -func (s *GamificationServiceImpl) UpdateCustomerPoints(ctx context.Context, id uuid.UUID, req *contract.UpdateCustomerPointsRequest) (*contract.CustomerPointsResponse, error) { - modelReq := transformer.UpdateCustomerPointsRequestToModel(req) - response, err := s.customerPointsProcessor.UpdateCustomerPoints(ctx, id, modelReq) - if err != nil { - return nil, err - } - return transformer.CustomerPointsModelToResponse(response), nil -} - -func (s *GamificationServiceImpl) DeleteCustomerPoints(ctx context.Context, id uuid.UUID) error { - return s.customerPointsProcessor.DeleteCustomerPoints(ctx, id) -} - -func (s *GamificationServiceImpl) AddCustomerPoints(ctx context.Context, customerID uuid.UUID, req *contract.AddCustomerPointsRequest) (*contract.CustomerPointsResponse, error) { - response, err := s.customerPointsProcessor.AddPoints(ctx, customerID, req.Points) - if err != nil { - return nil, err - } - return transformer.CustomerPointsModelToResponse(response), nil -} - -func (s *GamificationServiceImpl) DeductCustomerPoints(ctx context.Context, customerID uuid.UUID, req *contract.DeductCustomerPointsRequest) (*contract.CustomerPointsResponse, error) { - response, err := s.customerPointsProcessor.DeductPoints(ctx, customerID, req.Points) - if err != nil { - return nil, err - } - return transformer.CustomerPointsModelToResponse(response), nil -} - -// Customer Tokens Service Methods -func (s *GamificationServiceImpl) CreateCustomerTokens(ctx context.Context, req *contract.CreateCustomerTokensRequest) (*contract.CustomerTokensResponse, error) { - modelReq := transformer.CreateCustomerTokensRequestToModel(req) - response, err := s.customerTokensProcessor.CreateCustomerTokens(ctx, modelReq) - if err != nil { - return nil, err - } - return transformer.CustomerTokensModelToResponse(response), nil -} - -func (s *GamificationServiceImpl) GetCustomerTokens(ctx context.Context, id uuid.UUID) (*contract.CustomerTokensResponse, error) { - response, err := s.customerTokensProcessor.GetCustomerTokens(ctx, id) - if err != nil { - return nil, err - } - return transformer.CustomerTokensModelToResponse(response), nil -} - -func (s *GamificationServiceImpl) GetCustomerTokensByCustomerIDAndType(ctx context.Context, customerID uuid.UUID, tokenType string) (*contract.CustomerTokensResponse, error) { - response, err := s.customerTokensProcessor.GetCustomerTokensByCustomerIDAndType(ctx, customerID, tokenType) - if err != nil { - return nil, err - } - return transformer.CustomerTokensModelToResponse(response), nil -} - -func (s *GamificationServiceImpl) ListCustomerTokens(ctx context.Context, query *contract.ListCustomerTokensRequest) (*contract.PaginatedCustomerTokensResponse, error) { - modelQuery := transformer.ListCustomerTokensRequestToModel(query) - response, err := s.customerTokensProcessor.ListCustomerTokens(ctx, modelQuery) - if err != nil { - return nil, err - } - return transformer.PaginatedCustomerTokensResponseToContract(response), nil -} - -func (s *GamificationServiceImpl) UpdateCustomerTokens(ctx context.Context, id uuid.UUID, req *contract.UpdateCustomerTokensRequest) (*contract.CustomerTokensResponse, error) { - modelReq := transformer.UpdateCustomerTokensRequestToModel(req) - response, err := s.customerTokensProcessor.UpdateCustomerTokens(ctx, id, modelReq) - if err != nil { - return nil, err - } - return transformer.CustomerTokensModelToResponse(response), nil -} - -func (s *GamificationServiceImpl) DeleteCustomerTokens(ctx context.Context, id uuid.UUID) error { - return s.customerTokensProcessor.DeleteCustomerTokens(ctx, id) -} - -func (s *GamificationServiceImpl) AddCustomerTokens(ctx context.Context, customerID uuid.UUID, tokenType string, req *contract.AddCustomerTokensRequest) (*contract.CustomerTokensResponse, error) { - response, err := s.customerTokensProcessor.AddTokens(ctx, customerID, tokenType, req.Tokens) - if err != nil { - return nil, err - } - return transformer.CustomerTokensModelToResponse(response), nil -} - -func (s *GamificationServiceImpl) DeductCustomerTokens(ctx context.Context, customerID uuid.UUID, tokenType string, req *contract.DeductCustomerTokensRequest) (*contract.CustomerTokensResponse, error) { - response, err := s.customerTokensProcessor.DeductTokens(ctx, customerID, tokenType, req.Tokens) - if err != nil { - return nil, err - } - return transformer.CustomerTokensModelToResponse(response), nil -} - // Tier Service Methods func (s *GamificationServiceImpl) CreateTier(ctx context.Context, req *contract.CreateTierRequest) (*contract.TierResponse, error) { modelReq := transformer.CreateTierRequestToModel(req) diff --git a/internal/service/loyalty_settings_service.go b/internal/service/loyalty_settings_service.go new file mode 100644 index 0000000..1d81921 --- /dev/null +++ b/internal/service/loyalty_settings_service.go @@ -0,0 +1,224 @@ +package service + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "time" + + "github.com/google/uuid" + + "apskel-pos-be/internal/appcontext" + "apskel-pos-be/internal/constants" + "apskel-pos-be/internal/contract" + "apskel-pos-be/internal/models" + "apskel-pos-be/internal/processor" + "apskel-pos-be/internal/repository" +) + +// LoyaltySettingsService is the dashboard's access to loyalty settings +// (docs/prd-point-coin.md F1, F2). Every call is scoped to the caller's organization. +type LoyaltySettingsService interface { + GetOutletSettings(ctx context.Context, apctx *appcontext.ContextInfo, outletID uuid.UUID) *contract.Response + // UpdateOutletSettings applies a JSON body on top of the current settings: fields + // left out keep their value, and null clears an optional limit. + UpdateOutletSettings(ctx context.Context, apctx *appcontext.ContextInfo, outletID uuid.UUID, body []byte) *contract.Response + + GetOrganizationSettings(ctx context.Context, apctx *appcontext.ContextInfo) *contract.Response + // UpdateOrganizationSettings applies a JSON body like UpdateOutletSettings. With + // dryRun it only validates and reports what would change and its impact. + UpdateOrganizationSettings(ctx context.Context, apctx *appcontext.ContextInfo, body []byte, dryRun bool) *contract.Response + // ListHistory returns the settings history of the organization, or of one outlet. + ListHistory(ctx context.Context, apctx *appcontext.ContextInfo, outletID *uuid.UUID, page, limit int) *contract.Response +} + +type outstandingBalanceReader interface { + OrganizationOutstanding(ctx context.Context, organizationID uuid.UUID) (points, coins int64, err error) +} + +type LoyaltySettingsServiceImpl struct { + settings *processor.LoyaltySettingsProcessor + outstanding outstandingBalanceReader +} + +func NewLoyaltySettingsService(settings *processor.LoyaltySettingsProcessor, outstanding outstandingBalanceReader) *LoyaltySettingsServiceImpl { + return &LoyaltySettingsServiceImpl{settings: settings, outstanding: outstanding} +} + +func (s *LoyaltySettingsServiceImpl) GetOutletSettings(ctx context.Context, apctx *appcontext.ContextInfo, outletID uuid.UUID) *contract.Response { + current, err := s.settings.OutletForOrganization(ctx, apctx.OrganizationID, outletID) + if err != nil { + return loyaltyErrorResponse(err) + } + view, err := s.outletView(ctx, apctx.OrganizationID, outletID, *current, nil) + if err != nil { + return loyaltyErrorResponse(err) + } + return contract.BuildSuccessResponse(view) +} + +// outletSettingsInput is what PUT accepts: the settings, plus the read-only fields of +// the GET response so a client can send back what it received. Those are ignored. +type outletSettingsInput struct { + *models.OutletLoyaltySettings + OutletID json.RawMessage `json:"outlet_id"` + PointValue json.RawMessage `json:"point_value"` + PointCashbackPercent json.RawMessage `json:"point_cashback_percent"` + Changes json.RawMessage `json:"changes"` +} + +func (s *LoyaltySettingsServiceImpl) UpdateOutletSettings(ctx context.Context, apctx *appcontext.ContextInfo, outletID uuid.UUID, body []byte) *contract.Response { + current, err := s.settings.OutletForOrganization(ctx, apctx.OrganizationID, outletID) + if err != nil { + return loyaltyErrorResponse(err) + } + + next := *current + decoder := json.NewDecoder(bytes.NewReader(body)) + decoder.DisallowUnknownFields() + if err := decoder.Decode(&outletSettingsInput{OutletLoyaltySettings: &next}); err != nil { + return contract.BuildErrorResponse([]*contract.ResponseError{ + contract.NewResponseError(constants.MalformedFieldErrorCode, constants.LoyaltySettingsServiceEntity, fmt.Sprintf("invalid request body: %v", err)), + }) + } + + changes, err := s.settings.UpdateOutlet(ctx, apctx.OrganizationID, outletID, apctx.UserID, next) + if err != nil { + return loyaltyErrorResponse(err) + } + saved, err := s.settings.Outlet(ctx, outletID) + if err != nil { + return loyaltyErrorResponse(err) + } + view, err := s.outletView(ctx, apctx.OrganizationID, outletID, *saved, changes) + if err != nil { + return loyaltyErrorResponse(err) + } + return contract.BuildSuccessResponse(view) +} + +func (s *LoyaltySettingsServiceImpl) outletView(ctx context.Context, organizationID, outletID uuid.UUID, settings models.OutletLoyaltySettings, changes []models.LoyaltySettingChange) (*models.OutletLoyaltySettingsView, error) { + pointValue, err := s.settings.PointValue(ctx, organizationID) + if err != nil { + return nil, err + } + if changes == nil { + changes = []models.LoyaltySettingChange{} + } + return &models.OutletLoyaltySettingsView{ + OutletID: outletID, + OutletLoyaltySettings: settings, + PointValue: pointValue, + PointCashbackPercent: models.LoyaltyCashbackPercent(settings.Point.EarnValue, pointValue, settings.Point.EarnPerAmount), + Changes: changes, + }, nil +} + +func loyaltyErrorResponse(err error) *contract.Response { + code, message := constants.InternalServerErrorCode, err.Error() + switch { + case errors.Is(err, repository.ErrLoyaltyOutletNotFound): + code, message = constants.NotFoundErrorCode, "outlet not found" + case errors.Is(err, processor.ErrInvalidLoyaltySettings): + code = constants.ValidationErrorCode + } + return contract.BuildErrorResponse([]*contract.ResponseError{ + contract.NewResponseError(code, constants.LoyaltySettingsServiceEntity, message), + }) +} + +func (s *LoyaltySettingsServiceImpl) GetOrganizationSettings(ctx context.Context, apctx *appcontext.ContextInfo) *contract.Response { + current, err := s.settings.Organization(ctx, apctx.OrganizationID) + if err != nil { + return loyaltyErrorResponse(err) + } + view, err := s.organizationView(ctx, apctx.OrganizationID, *current, *current, nil, nil, false) + if err != nil { + return loyaltyErrorResponse(err) + } + return contract.BuildSuccessResponse(view) +} + +// organizationSettingsInput is what PUT accepts: the settings plus the read-only fields +// of the GET response, which are ignored. +type organizationSettingsInput struct { + *models.OrganizationLoyaltySettings + Impact json.RawMessage `json:"impact"` + ExpiryPreview json.RawMessage `json:"expiry_preview"` + ExpiryActivations json.RawMessage `json:"expiry_activations"` + Changes json.RawMessage `json:"changes"` + DryRun json.RawMessage `json:"dry_run"` +} + +func (s *LoyaltySettingsServiceImpl) UpdateOrganizationSettings(ctx context.Context, apctx *appcontext.ContextInfo, body []byte, dryRun bool) *contract.Response { + current, err := s.settings.Organization(ctx, apctx.OrganizationID) + if err != nil { + return loyaltyErrorResponse(err) + } + next := *current + decoder := json.NewDecoder(bytes.NewReader(body)) + decoder.DisallowUnknownFields() + if err := decoder.Decode(&organizationSettingsInput{OrganizationLoyaltySettings: &next}); err != nil { + return contract.BuildErrorResponse([]*contract.ResponseError{ + contract.NewResponseError(constants.MalformedFieldErrorCode, constants.LoyaltySettingsServiceEntity, fmt.Sprintf("invalid request body: %v", err)), + }) + } + + var changes []models.LoyaltySettingChange + var activations []models.LoyaltyExpiryActivation + if dryRun { + changes, activations, err = s.settings.PreviewOrganization(ctx, apctx.OrganizationID, next) + } else { + changes, activations, err = s.settings.UpdateOrganization(ctx, apctx.OrganizationID, apctx.UserID, next) + } + if err != nil { + return loyaltyErrorResponse(err) + } + after := next + if !dryRun { + saved, err := s.settings.Organization(ctx, apctx.OrganizationID) + if err != nil { + return loyaltyErrorResponse(err) + } + after = *saved + } + view, err := s.organizationView(ctx, apctx.OrganizationID, *current, after, changes, activations, dryRun) + if err != nil { + return loyaltyErrorResponse(err) + } + return contract.BuildSuccessResponse(view) +} + +func (s *LoyaltySettingsServiceImpl) ListHistory(ctx context.Context, apctx *appcontext.ContextInfo, outletID *uuid.UUID, page, limit int) *contract.Response { + history, err := s.settings.ListChanges(ctx, apctx.OrganizationID, outletID, page, limit) + if err != nil { + return loyaltyErrorResponse(err) + } + return contract.BuildSuccessResponse(history) +} + +func (s *LoyaltySettingsServiceImpl) organizationView(ctx context.Context, organizationID uuid.UUID, before, after models.OrganizationLoyaltySettings, changes []models.LoyaltySettingChange, activations []models.LoyaltyExpiryActivation, dryRun bool) (*models.OrganizationLoyaltySettingsView, error) { + now := time.Now() + points, coins, err := s.outstanding.OrganizationOutstanding(ctx, organizationID) + if err != nil { + return nil, err + } + if activations == nil { + activations = []models.LoyaltyExpiryActivation{} + } + if changes == nil { + changes = []models.LoyaltySettingChange{} + } + return &models.OrganizationLoyaltySettingsView{ + OrganizationLoyaltySettings: after, + Impact: models.NewLoyaltySettingsImpact(points, coins, before, after), + ExpiryPreview: models.LoyaltyExpiryPreview{ + Point: processor.ComputeExpiry(after.PointExpiry, now), + Coin: processor.ComputeExpiry(after.CoinExpiry, now), + }, + Changes: changes, + DryRun: dryRun, + }, nil +} diff --git a/internal/service/order_service.go b/internal/service/order_service.go index d7e450c..626fb24 100644 --- a/internal/service/order_service.go +++ b/internal/service/order_service.go @@ -557,7 +557,8 @@ func (s *OrderServiceImpl) validateCreatePaymentRequest(req *models.CreatePaymen return fmt.Errorf("payment method ID is required") } - if req.Amount <= 0 { + // A payment with EnakPoint gives points instead; its amount is computed from them. + if req.Points == nil && req.Amount <= 0 { return fmt.Errorf("payment amount must be greater than zero") } diff --git a/internal/service/order_service_table_test.go b/internal/service/order_service_table_test.go index 66fd43b..adbc497 100644 --- a/internal/service/order_service_table_test.go +++ b/internal/service/order_service_table_test.go @@ -42,6 +42,14 @@ func (m *MockOrderProcessor) UpdateOrder(ctx context.Context, id uuid.UUID, req return args.Get(0).(*models.OrderResponse), args.Error(1) } +func (m *MockOrderProcessor) PayWithPointsInApp(ctx context.Context, customerID, orderID uuid.UUID, points int64, pin string, info models.CustomerPinRequestInfo) (*models.PaymentResponse, error) { + args := m.Called(ctx, customerID, orderID, points, pin, info) + if args.Get(0) == nil { + return nil, args.Error(1) + } + return args.Get(0).(*models.PaymentResponse), args.Error(1) +} + func (m *MockOrderProcessor) GetOrderByID(ctx context.Context, id uuid.UUID) (*models.OrderResponse, error) { args := m.Called(ctx, id) if args.Get(0) == nil { diff --git a/internal/service/payment_method_service.go b/internal/service/payment_method_service.go index d0ecd7d..fa1198f 100644 --- a/internal/service/payment_method_service.go +++ b/internal/service/payment_method_service.go @@ -2,8 +2,10 @@ package service import ( "context" + "errors" "apskel-pos-be/internal/appcontext" + "apskel-pos-be/internal/constants" "apskel-pos-be/internal/contract" "apskel-pos-be/internal/mappers" "apskel-pos-be/internal/processor" @@ -39,7 +41,7 @@ func (s *PaymentMethodServiceImpl) CreatePaymentMethod(ctx context.Context, cont response, err := s.paymentMethodProcessor.CreatePaymentMethod(ctx, modelReq) if err != nil { return contract.BuildErrorResponse([]*contract.ResponseError{ - contract.NewResponseError("PAYMENT_METHOD_CREATE_ERROR", "payment_method", err.Error()), + contract.NewResponseError(paymentMethodErrorCode(err, "PAYMENT_METHOD_CREATE_ERROR"), "payment_method", err.Error()), }) } @@ -84,7 +86,7 @@ func (s *PaymentMethodServiceImpl) UpdatePaymentMethod(ctx context.Context, id u response, err := s.paymentMethodProcessor.UpdatePaymentMethod(ctx, id, modelReq) if err != nil { return contract.BuildErrorResponse([]*contract.ResponseError{ - contract.NewResponseError("PAYMENT_METHOD_UPDATE_ERROR", "payment_method", err.Error()), + contract.NewResponseError(paymentMethodErrorCode(err, "PAYMENT_METHOD_UPDATE_ERROR"), "payment_method", err.Error()), }) } @@ -97,7 +99,7 @@ func (s *PaymentMethodServiceImpl) DeletePaymentMethod(ctx context.Context, id u err := s.paymentMethodProcessor.DeletePaymentMethod(ctx, id) if err != nil { return contract.BuildErrorResponse([]*contract.ResponseError{ - contract.NewResponseError("PAYMENT_METHOD_DELETE_ERROR", "payment_method", err.Error()), + contract.NewResponseError(paymentMethodErrorCode(err, "PAYMENT_METHOD_DELETE_ERROR"), "payment_method", err.Error()), }) } @@ -123,3 +125,12 @@ func (s *PaymentMethodServiceImpl) GetActivePaymentMethodsByOrganization(ctx con return contract.BuildSuccessResponse(contractResponses) } + +// paymentMethodErrorCode answers a request to create, delete or retype the EnakPoint +// method as a bad request instead of a server error. +func paymentMethodErrorCode(err error, fallback string) string { + if errors.Is(err, processor.ErrSystemPaymentMethod) { + return constants.ValidationErrorCode + } + return fallback +} diff --git a/internal/service/point_payment_service.go b/internal/service/point_payment_service.go new file mode 100644 index 0000000..a0c609e --- /dev/null +++ b/internal/service/point_payment_service.go @@ -0,0 +1,55 @@ +package service + +import ( + "context" + "errors" + + "github.com/google/uuid" + + "apskel-pos-be/internal/appcontext" + "apskel-pos-be/internal/constants" + "apskel-pos-be/internal/contract" + "apskel-pos-be/internal/processor" + "apskel-pos-be/internal/repository" +) + +// PointPaymentService serves what the cashier needs before taking EnakPoint +// (docs/prd-point-coin.md F9). +type PointPaymentService interface { + Preview(ctx context.Context, apctx *appcontext.ContextInfo, orderID uuid.UUID) *contract.Response +} + +type PointPaymentServiceImpl struct { + payments *processor.PointPaymentProcessor +} + +func NewPointPaymentService(payments *processor.PointPaymentProcessor) *PointPaymentServiceImpl { + return &PointPaymentServiceImpl{payments: payments} +} + +func (s *PointPaymentServiceImpl) Preview(ctx context.Context, apctx *appcontext.ContextInfo, orderID uuid.UUID) *contract.Response { + preview, err := s.payments.Preview(ctx, apctx.OrganizationID, orderID) + if err != nil { + return PointPaymentErrorResponse(err) + } + return contract.BuildSuccessResponse(preview) +} + +// PointPaymentErrorResponse answers a refused EnakPoint payment as a bad request, PIN +// problems with their own codes, and anything else as a server error. +func PointPaymentErrorResponse(err error) *contract.Response { + var pinErr *processor.PinError + if errors.As(err, &pinErr) { + return PinErrorResponse(err) + } + code := constants.InternalServerErrorCode + switch { + case errors.Is(err, repository.ErrPointPaymentOrderNotFound): + code = constants.NotFoundErrorCode + case errors.Is(err, processor.ErrPointPaymentRejected): + code = constants.ValidationErrorCode + } + return contract.BuildErrorResponse([]*contract.ResponseError{ + contract.NewResponseError(code, constants.WalletServiceEntity, err.Error()), + }) +} diff --git a/internal/service/spin_game_service.go b/internal/service/spin_game_service.go index dcfd93e..42390c2 100644 --- a/internal/service/spin_game_service.go +++ b/internal/service/spin_game_service.go @@ -6,7 +6,6 @@ import ( "apskel-pos-be/internal/models" "apskel-pos-be/internal/processor" - "apskel-pos-be/internal/repository" "github.com/google/uuid" ) @@ -17,13 +16,11 @@ type SpinGameService interface { type spinGameService struct { gamePlayProcessor *processor.GamePlayProcessor - txManager *repository.TxManager } -func NewSpinGameService(gamePlayProcessor *processor.GamePlayProcessor, txManager *repository.TxManager) SpinGameService { +func NewSpinGameService(gamePlayProcessor *processor.GamePlayProcessor) SpinGameService { return &spinGameService{ gamePlayProcessor: gamePlayProcessor, - txManager: txManager, } } @@ -45,28 +42,13 @@ func (s *spinGameService) PlaySpinGame(ctx context.Context, customerID string, r return nil, fmt.Errorf("invalid customer ID format: %w", err) } - // Use transaction to ensure consistency - var playResponse *models.PlayGameResponse - err = s.txManager.WithTransaction(ctx, func(txCtx context.Context) error { - // Create play game request - playGameReq := &models.PlayGameRequest{ - GameID: spinID, - CustomerID: customerUUID, - TokenUsed: 1, // Default to 1 token per spin - } - - // Play the game within transaction - var playErr error - playResponse, playErr = s.gamePlayProcessor.PlayGame(txCtx, playGameReq) - if playErr != nil { - return fmt.Errorf("failed to play spin game: %w", playErr) - } - - return nil + // PlayGame runs its own transaction and charges the game's coin_cost in EnakCoin. + playResponse, err := s.gamePlayProcessor.PlayGame(ctx, &models.PlayGameRequest{ + GameID: spinID, + CustomerID: customerUUID, }) - if err != nil { - return nil, err + return nil, fmt.Errorf("failed to play spin game: %w", err) } // Convert prize to customer-facing format @@ -88,9 +70,9 @@ func (s *spinGameService) PlaySpinGame(ctx context.Context, customerID string, r Status: "SUCCESS", Message: "Spin game completed successfully.", Data: &models.SpinGameResponseData{ - GamePlay: playResponse.GamePlay, - PrizeWon: customerPrize, - TokensRemaining: playResponse.TokensRemaining, + GamePlay: playResponse.GamePlay, + PrizeWon: customerPrize, + CoinsRemaining: playResponse.CoinsRemaining, }, } diff --git a/internal/service/wallet_admin_service.go b/internal/service/wallet_admin_service.go new file mode 100644 index 0000000..c29580d --- /dev/null +++ b/internal/service/wallet_admin_service.go @@ -0,0 +1,82 @@ +package service + +import ( + "context" + "errors" + + "github.com/google/uuid" + + "apskel-pos-be/internal/appcontext" + "apskel-pos-be/internal/constants" + "apskel-pos-be/internal/contract" + "apskel-pos-be/internal/models" + "apskel-pos-be/internal/processor" + "apskel-pos-be/internal/repository" +) + +// WalletAdminService is the dashboard's access to a customer's wallet +// (docs/prd-point-coin.md F7). Every call is scoped to the caller's organization. +type WalletAdminService interface { + GetCustomerWallet(ctx context.Context, apctx *appcontext.ContextInfo, customerID uuid.UUID, query models.ListCustomerWalletTransactionsQuery) *contract.Response + AdjustCustomerWallet(ctx context.Context, apctx *appcontext.ContextInfo, customerID uuid.UUID, req *contract.AdjustCustomerWalletRequest) *contract.Response + // TraceTransaction follows a ledger row lot by lot back to where its balance came from. + TraceTransaction(ctx context.Context, apctx *appcontext.ContextInfo, transactionID uuid.UUID) *contract.Response +} + +type WalletAdminServiceImpl struct { + walletAdminProcessor *processor.WalletAdminProcessor + walletTraceProcessor *processor.WalletTraceProcessor +} + +func NewWalletAdminService(walletAdminProcessor *processor.WalletAdminProcessor, walletTraceProcessor *processor.WalletTraceProcessor) *WalletAdminServiceImpl { + return &WalletAdminServiceImpl{walletAdminProcessor: walletAdminProcessor, walletTraceProcessor: walletTraceProcessor} +} + +func (s *WalletAdminServiceImpl) TraceTransaction(ctx context.Context, apctx *appcontext.ContextInfo, transactionID uuid.UUID) *contract.Response { + trace, err := s.walletTraceProcessor.Trace(ctx, apctx.OrganizationID, transactionID) + if err != nil { + return walletErrorResponse(err) + } + return contract.BuildSuccessResponse(trace) +} + +func (s *WalletAdminServiceImpl) GetCustomerWallet(ctx context.Context, apctx *appcontext.ContextInfo, customerID uuid.UUID, query models.ListCustomerWalletTransactionsQuery) *contract.Response { + wallet, err := s.walletAdminProcessor.GetCustomerWallet(ctx, apctx.OrganizationID, customerID, query) + if err != nil { + return walletErrorResponse(err) + } + return contract.BuildSuccessResponse(wallet) +} + +func (s *WalletAdminServiceImpl) AdjustCustomerWallet(ctx context.Context, apctx *appcontext.ContextInfo, customerID uuid.UUID, req *contract.AdjustCustomerWalletRequest) *contract.Response { + result, err := s.walletAdminProcessor.Adjust(ctx, apctx.OrganizationID, apctx.UserID, customerID, models.WalletAdjustment{ + Currency: req.Currency, + Amount: req.Amount, + Reason: req.Reason, + IdempotencyKey: req.IdempotencyKey, + }) + if err != nil { + return walletErrorResponse(err) + } + return contract.BuildSuccessResponse(result) +} + +// walletErrorResponse tells the dashboard's mistakes apart from server failures. +func walletErrorResponse(err error) *contract.Response { + code, message := constants.InternalServerErrorCode, err.Error() + switch { + case errors.Is(err, repository.ErrWalletNotFound): + code, message = constants.NotFoundErrorCode, "customer not found" + case errors.Is(err, repository.ErrWalletTransactionNotFound): + code, message = constants.NotFoundErrorCode, "wallet transaction not found" + case errors.Is(err, repository.ErrWalletInsufficientBalance): + code, message = constants.ValidationErrorCode, "the adjustment would take more than the customer can spend" + case errors.Is(err, processor.ErrInvalidWalletQuery), + errors.Is(err, processor.ErrWalletInvalidEntry), + errors.Is(err, processor.ErrWalletIdempotencyConflict): + code = constants.ValidationErrorCode + } + return contract.BuildErrorResponse([]*contract.ResponseError{ + contract.NewResponseError(code, constants.WalletServiceEntity, message), + }) +} diff --git a/internal/service/wallet_expiry_job.go b/internal/service/wallet_expiry_job.go new file mode 100644 index 0000000..f2a83c0 --- /dev/null +++ b/internal/service/wallet_expiry_job.go @@ -0,0 +1,77 @@ +package service + +import ( + "context" + "sync" + "time" + + "apskel-pos-be/internal/logger" +) + +// Lots expire at the end of their day, so running every quarter of an hour keeps any +// lot from staying past its expiry for more than about that long (PC-503). +const defaultWalletExpiryInterval = 15 * time.Minute + +type walletExpiryWork interface { + ExpireDue(ctx context.Context) (int, error) + SendReminders(ctx context.Context) (int, error) +} + +// WalletExpiryJob expires the balances whose time is up and reminds customers of what +// is about to (docs/prd-point-coin.md F12, PC-503, PC-504). +// Unlike OmsetMilestoneScheduler it keeps no state in memory: several instances can +// run it at once, and a restart repeats nothing, because every lot is expired under +// its wallet's lock with an idempotency key. +type WalletExpiryJob struct { + expirer walletExpiryWork + stopCh chan struct{} + stopOnce sync.Once +} + +func NewWalletExpiryJob(expirer walletExpiryWork) *WalletExpiryJob { + return &WalletExpiryJob{expirer: expirer, stopCh: make(chan struct{})} +} + +func (j *WalletExpiryJob) Start(interval time.Duration) { + if interval <= 0 { + interval = defaultWalletExpiryInterval + } + go func() { + j.RunOnce(context.Background()) + ticker := time.NewTicker(interval) + defer ticker.Stop() + for { + select { + case <-ticker.C: + j.RunOnce(context.Background()) + case <-j.stopCh: + return + } + } + }() + logger.NonContext.Infof("Wallet expiry job started (interval: %s)", interval) +} + +func (j *WalletExpiryJob) Stop() { + j.stopOnce.Do(func() { close(j.stopCh) }) +} + +// RunOnce expires what is due, sends the reminders that are due, and returns how many +// lots it expired. +func (j *WalletExpiryJob) RunOnce(ctx context.Context) int { + expired, err := j.expirer.ExpireDue(ctx) + if err != nil { + logger.NonContext.Error("Wallet expiry failed to run", err) + } + if expired > 0 { + logger.NonContext.Infof("Wallet expiry expired %d lots", expired) + } + reminded, err := j.expirer.SendReminders(ctx) + if err != nil { + logger.NonContext.Error("Wallet expiry reminders failed to run", err) + } + if reminded > 0 { + logger.NonContext.Infof("Wallet expiry sent %d reminders", reminded) + } + return expired +} diff --git a/internal/service/wallet_reconciliation_job.go b/internal/service/wallet_reconciliation_job.go new file mode 100644 index 0000000..2b9aebd --- /dev/null +++ b/internal/service/wallet_reconciliation_job.go @@ -0,0 +1,212 @@ +package service + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "fmt" + "sort" + "sync" + "time" + + "github.com/google/uuid" + + "apskel-pos-be/internal/entities" + "apskel-pos-be/internal/logger" + "apskel-pos-be/internal/models" + "apskel-pos-be/internal/repository" +) + +const ( + defaultWalletReconciliationInterval = 6 * time.Hour + // Per check, so one systematic bug cannot flood the log or the notification. + walletReconciliationLimit = 50 +) + +type walletDiscrepancyFinder interface { + FindDiscrepancies(ctx context.Context, limit int) ([]repository.WalletDiscrepancy, error) +} + +type organizationUserLister interface { + GetByOrganizationID(ctx context.Context, organizationID uuid.UUID) ([]*entities.User, error) +} + +type notificationSender interface { + Send(ctx context.Context, req *models.SendNotificationRequest) (*models.NotificationResponse, error) +} + +// WalletReconciliationJob periodically runs the §7.5 checks of +// docs/prd-point-coin.md over every wallet (PC-108). It is silent while the data is +// consistent. When it finds a discrepancy it logs each one and notifies the admins, +// owners and managers of the organization concerned. +// +// An organization is notified again only when its set of discrepancies changes, so an +// unfixed problem does not page the same people every run. That memory is in-process: +// a restart notifies once more, and each running instance keeps its own. +type WalletReconciliationJob struct { + finder walletDiscrepancyFinder + users organizationUserLister + notifier notificationSender + + mu sync.Mutex + notified map[uuid.UUID]string // organization -> fingerprint last notified + stopCh chan struct{} + stopOnce sync.Once +} + +func NewWalletReconciliationJob(finder walletDiscrepancyFinder, users organizationUserLister, notifier notificationSender) *WalletReconciliationJob { + return &WalletReconciliationJob{ + finder: finder, + users: users, + notifier: notifier, + notified: make(map[uuid.UUID]string), + stopCh: make(chan struct{}), + } +} + +// Start runs the checks once now and then every interval, in the background. +func (j *WalletReconciliationJob) Start(interval time.Duration) { + if interval <= 0 { + interval = defaultWalletReconciliationInterval + } + go func() { + j.runLogged() + ticker := time.NewTicker(interval) + defer ticker.Stop() + for { + select { + case <-ticker.C: + j.runLogged() + case <-j.stopCh: + return + } + } + }() + logger.NonContext.Infof("Wallet reconciliation job started (interval: %s)", interval) +} + +func (j *WalletReconciliationJob) Stop() { + j.stopOnce.Do(func() { close(j.stopCh) }) +} + +func (j *WalletReconciliationJob) runLogged() { + if _, err := j.RunOnce(context.Background()); err != nil { + logger.NonContext.Error("Wallet reconciliation failed to run", err) + } +} + +// RunOnce runs every check, reports what it finds, and returns it. +func (j *WalletReconciliationJob) RunOnce(ctx context.Context) ([]repository.WalletDiscrepancy, error) { + found, err := j.finder.FindDiscrepancies(ctx, walletReconciliationLimit) + if err != nil { + return nil, err + } + + byOrg := make(map[uuid.UUID][]repository.WalletDiscrepancy) + for _, d := range found { + fields := map[string]interface{}{ + "check": d.Check, + "organization_id": d.OrganizationID.String(), + "customer_id": d.CustomerID.String(), + "currency": d.Currency, + "expected": d.Expected, + "actual": d.Actual, + } + if d.ObjectID != nil { + fields["object_id"] = d.ObjectID.String() + } + logger.NonContext.WarnWithFields("Wallet reconciliation found a discrepancy", fields, nil) + byOrg[d.OrganizationID] = append(byOrg[d.OrganizationID], d) + } + + j.mu.Lock() + defer j.mu.Unlock() + // Organizations that are clean again are forgotten, so a later problem notifies. + for org := range j.notified { + if _, still := byOrg[org]; !still { + delete(j.notified, org) + } + } + for org, discrepancies := range byOrg { + fingerprint := walletDiscrepancyFingerprint(discrepancies) + if j.notified[org] == fingerprint { + continue + } + if err := j.notify(ctx, org, discrepancies); err != nil { + logger.NonContext.Error(fmt.Sprintf("Wallet reconciliation could not notify organization %s", org), err) + continue + } + j.notified[org] = fingerprint + } + return found, nil +} + +func (j *WalletReconciliationJob) notify(ctx context.Context, organizationID uuid.UUID, discrepancies []repository.WalletDiscrepancy) error { + if organizationID == uuid.Nil { + return fmt.Errorf("discrepancy without an organization") + } + users, err := j.users.GetByOrganizationID(ctx, organizationID) + if err != nil { + return err + } + var receivers []uuid.UUID + for _, u := range users { + switch u.Role { + case entities.RoleAdmin, entities.RoleOwner, entities.RoleManager: + receivers = append(receivers, u.ID) + } + } + if len(receivers) == 0 { + return nil + } + + perCheck := map[string]int{} + customers := map[string]bool{} + for _, d := range discrepancies { + perCheck[d.Check]++ + customers[d.CustomerID.String()] = true + } + customerIDs := make([]string, 0, len(customers)) + for id := range customers { + customerIDs = append(customerIDs, id) + } + sort.Strings(customerIDs) + + _, err = j.notifier.Send(ctx, &models.SendNotificationRequest{ + Title: "Selisih saldo EnakPoint/EnakCoin terdeteksi", + Body: fmt.Sprintf("Pemeriksaan rutin menemukan %d selisih pada saldo %d customer. Saldo belum dikoreksi otomatis; tim teknis perlu memeriksanya.", + len(discrepancies), len(customerIDs)), + Type: "system", + Category: "wallet_reconciliation", + Priority: entities.NotificationPriorityHigh, + NotifiableType: "organization", + NotifiableID: &organizationID, + ReceiverIDs: receivers, + Data: map[string]interface{}{ + "organization_id": organizationID.String(), + "discrepancies": len(discrepancies), + "per_check": perCheck, + "customer_ids": customerIDs, + }, + }) + return err +} + +// walletDiscrepancyFingerprint identifies a set of discrepancies regardless of order. +func walletDiscrepancyFingerprint(discrepancies []repository.WalletDiscrepancy) string { + keys := make([]string, 0, len(discrepancies)) + for _, d := range discrepancies { + object := "" + if d.ObjectID != nil { + object = d.ObjectID.String() + } + keys = append(keys, fmt.Sprintf("%s|%s|%s|%s|%d|%d", d.Check, d.CustomerID, d.Currency, object, d.Expected, d.Actual)) + } + sort.Strings(keys) + h := sha256.New() + for _, k := range keys { + h.Write([]byte(k)) + h.Write([]byte{'\n'}) + } + return hex.EncodeToString(h.Sum(nil)) +} diff --git a/internal/service/wallet_reconciliation_job_test.go b/internal/service/wallet_reconciliation_job_test.go new file mode 100644 index 0000000..c12c8e6 --- /dev/null +++ b/internal/service/wallet_reconciliation_job_test.go @@ -0,0 +1,110 @@ +package service + +import ( + "context" + "testing" + + "github.com/google/uuid" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "apskel-pos-be/internal/entities" + "apskel-pos-be/internal/logger" + "apskel-pos-be/internal/models" + "apskel-pos-be/internal/repository" +) + +type discrepancyFinderFake struct { + found []repository.WalletDiscrepancy +} + +func (f *discrepancyFinderFake) FindDiscrepancies(context.Context, int) ([]repository.WalletDiscrepancy, error) { + return f.found, nil +} + +type orgUsersFake map[uuid.UUID][]*entities.User + +func (f orgUsersFake) GetByOrganizationID(_ context.Context, org uuid.UUID) ([]*entities.User, error) { + return f[org], nil +} + +type notifierFake struct { + sent []*models.SendNotificationRequest +} + +func (f *notifierFake) Send(_ context.Context, req *models.SendNotificationRequest) (*models.NotificationResponse, error) { + f.sent = append(f.sent, req) + return &models.NotificationResponse{}, nil +} + +func TestWalletReconciliationJob(t *testing.T) { + logger.Setup("fatal", "json") + org := uuid.New() + admin, owner, manager, cashier := uuid.New(), uuid.New(), uuid.New(), uuid.New() + users := orgUsersFake{org: { + {ID: admin, Role: entities.RoleAdmin}, + {ID: owner, Role: entities.RoleOwner}, + {ID: manager, Role: entities.RoleManager}, + {ID: cashier, Role: entities.RoleCashier}, + }} + finder := &discrepancyFinderFake{} + notifier := ¬ifierFake{} + job := NewWalletReconciliationJob(finder, users, notifier) + ctx := context.Background() + + // Consistent data: nothing reported. + found, err := job.RunOnce(ctx) + require.NoError(t, err) + assert.Empty(t, found) + assert.Empty(t, notifier.sent) + + // A discrepancy notifies the organization's admins, owners and managers. + customer := uuid.New() + lot := uuid.New() + finder.found = []repository.WalletDiscrepancy{ + {Check: repository.WalletCheckBalanceVsLots, OrganizationID: org, CustomerID: customer, Currency: "POINT", Expected: 100, Actual: 105}, + {Check: repository.WalletCheckLotVsAllocations, OrganizationID: org, CustomerID: customer, Currency: "POINT", ObjectID: &lot, Expected: 50, Actual: 55}, + } + found, err = job.RunOnce(ctx) + require.NoError(t, err) + assert.Len(t, found, 2) + require.Len(t, notifier.sent, 1) + sent := notifier.sent[0] + assert.ElementsMatch(t, []uuid.UUID{admin, owner, manager}, sent.ReceiverIDs, "cashiers are not told") + assert.Equal(t, &org, sent.NotifiableID) + assert.Equal(t, 2, sent.Data["discrepancies"]) + assert.Equal(t, []string{customer.String()}, sent.Data["customer_ids"]) + assert.Equal(t, entities.NotificationPriorityHigh, sent.Priority) + + // The same problem, still unfixed and in a different order, does not notify again. + finder.found = []repository.WalletDiscrepancy{finder.found[1], finder.found[0]} + _, err = job.RunOnce(ctx) + require.NoError(t, err) + assert.Len(t, notifier.sent, 1) + + // A changed problem does. + finder.found = finder.found[:1] + _, err = job.RunOnce(ctx) + require.NoError(t, err) + assert.Len(t, notifier.sent, 2) + + // Once clean the organization is forgotten, so the same problem coming back + // notifies again. + previous := finder.found + finder.found = nil + _, err = job.RunOnce(ctx) + require.NoError(t, err) + assert.Len(t, notifier.sent, 2) + finder.found = previous + _, err = job.RunOnce(ctx) + require.NoError(t, err) + assert.Len(t, notifier.sent, 3) +} + +func TestWalletReconciliationJobStartStop(t *testing.T) { + logger.Setup("fatal", "json") + job := NewWalletReconciliationJob(&discrepancyFinderFake{}, orgUsersFake{}, ¬ifierFake{}) + job.Start(0) + job.Stop() + job.Stop() // stopping twice is harmless +} diff --git a/internal/transformer/analytics_transformer.go b/internal/transformer/analytics_transformer.go index 8590c18..a6267cc 100644 --- a/internal/transformer/analytics_transformer.go +++ b/internal/transformer/analytics_transformer.go @@ -60,6 +60,8 @@ func PaymentMethodAnalyticsModelToContract(resp *models.PaymentMethodAnalyticsRe OrderCount: item.OrderCount, PaymentCount: item.PaymentCount, Percentage: item.Percentage, + PointsUsed: item.PointsUsed, + CountsAsCashIn: item.CountsAsCashIn, }) } @@ -72,6 +74,9 @@ func PaymentMethodAnalyticsModelToContract(resp *models.PaymentMethodAnalyticsRe GroupBy: resp.GroupBy, Summary: contract.PaymentMethodSummary{ TotalAmount: resp.Summary.TotalAmount, + PointAmount: resp.Summary.PointAmount, + PointsUsed: resp.Summary.PointsUsed, + TotalWithPoints: resp.Summary.TotalWithPoints, TotalOrders: resp.Summary.TotalOrders, TotalPayments: resp.Summary.TotalPayments, AverageOrderValue: resp.Summary.AverageOrderValue, @@ -617,6 +622,8 @@ func DashboardAnalyticsModelToContract(resp *models.DashboardAnalyticsResponse) OrderCount: item.OrderCount, PaymentCount: item.PaymentCount, Percentage: item.Percentage, + PointsUsed: item.PointsUsed, + CountsAsCashIn: item.CountsAsCashIn, }) } diff --git a/internal/transformer/gamification_transformer.go b/internal/transformer/gamification_transformer.go index b7a2b70..0b66a63 100644 --- a/internal/transformer/gamification_transformer.go +++ b/internal/transformer/gamification_transformer.go @@ -5,131 +5,6 @@ import ( "apskel-pos-be/internal/models" ) -// Customer Points Transformers -func CreateCustomerPointsRequestToModel(req *contract.CreateCustomerPointsRequest) *models.CreateCustomerPointsRequest { - return &models.CreateCustomerPointsRequest{ - CustomerID: req.CustomerID, - Balance: req.Balance, - } -} - -func UpdateCustomerPointsRequestToModel(req *contract.UpdateCustomerPointsRequest) *models.UpdateCustomerPointsRequest { - return &models.UpdateCustomerPointsRequest{ - Balance: req.Balance, - } -} - -func ListCustomerPointsRequestToModel(req *contract.ListCustomerPointsRequest) *models.ListCustomerPointsQuery { - return &models.ListCustomerPointsQuery{ - Page: req.Page, - Limit: req.Limit, - Search: req.Search, - SortBy: req.SortBy, - SortOrder: req.SortOrder, - } -} - -func CustomerPointsModelToResponse(model *models.CustomerPointsResponse) *contract.CustomerPointsResponse { - if model == nil { - return nil - } - - var customer *contract.CustomerResponse - if model.Customer != nil { - customer = CustomerModelToResponse(model.Customer) - } - - return &contract.CustomerPointsResponse{ - ID: model.ID, - CustomerID: model.CustomerID, - Balance: model.Balance, - Customer: customer, - CreatedAt: model.CreatedAt, - UpdatedAt: model.UpdatedAt, - } -} - -func PaginatedCustomerPointsResponseToContract(model *models.PaginatedCustomerPointsResponse) *contract.PaginatedCustomerPointsResponse { - if model == nil { - return nil - } - - responses := make([]contract.CustomerPointsResponse, len(model.Data)) - for i, item := range model.Data { - responses[i] = *CustomerPointsModelToResponse(&item) - } - - return &contract.PaginatedCustomerPointsResponse{ - Data: responses, - TotalCount: model.TotalCount, - Page: model.Page, - Limit: model.Limit, - TotalPages: model.TotalPages, - } -} - -// Customer Tokens Transformers -func CreateCustomerTokensRequestToModel(req *contract.CreateCustomerTokensRequest) *models.CreateCustomerTokensRequest { - return &models.CreateCustomerTokensRequest{ - CustomerID: req.CustomerID, - TokenType: req.TokenType, - Balance: req.Balance, - } -} - -func UpdateCustomerTokensRequestToModel(req *contract.UpdateCustomerTokensRequest) *models.UpdateCustomerTokensRequest { - return &models.UpdateCustomerTokensRequest{ - Balance: req.Balance, - } -} - -func ListCustomerTokensRequestToModel(req *contract.ListCustomerTokensRequest) *models.ListCustomerTokensQuery { - return &models.ListCustomerTokensQuery{ - Page: req.Page, - Limit: req.Limit, - Search: req.Search, - TokenType: req.TokenType, - SortBy: req.SortBy, - SortOrder: req.SortOrder, - } -} - -func CustomerTokensModelToResponse(model *models.CustomerTokensResponse) *contract.CustomerTokensResponse { - if model == nil { - return nil - } - - var customer *contract.CustomerResponse - if model.Customer != nil { - customer = CustomerModelToResponse(model.Customer) - } - - return &contract.CustomerTokensResponse{ - ID: model.ID, - CustomerID: model.CustomerID, - TokenType: model.TokenType, - Balance: model.Balance, - Customer: customer, - CreatedAt: model.CreatedAt, - UpdatedAt: model.UpdatedAt, - } -} - -func PaginatedCustomerTokensResponseToContract(model *models.PaginatedResponse[models.CustomerTokensResponse]) *contract.PaginatedCustomerTokensResponse { - responses := make([]contract.CustomerTokensResponse, len(model.Data)) - for i, item := range model.Data { - responses[i] = *CustomerTokensModelToResponse(&item) - } - - return &contract.PaginatedCustomerTokensResponse{ - Data: responses, - TotalCount: int(model.Pagination.Total), - Page: model.Pagination.Page, - Limit: model.Pagination.Limit, - TotalPages: model.Pagination.TotalPages, - } -} - // Tier Transformers func CreateTierRequestToModel(req *contract.CreateTierRequest) *models.CreateTierRequest { return &models.CreateTierRequest{ @@ -350,7 +225,7 @@ func CreateGamePlayRequestToModel(req *contract.CreateGamePlayRequest) *models.C return &models.CreateGamePlayRequest{ GameID: req.GameID, CustomerID: req.CustomerID, - TokenUsed: req.TokenUsed, + CoinsUsed: req.CoinsUsed, RandomSeed: req.RandomSeed, } } @@ -359,7 +234,6 @@ func PlayGameRequestToModel(req *contract.PlayGameRequest) *models.PlayGameReque return &models.PlayGameRequest{ GameID: req.GameID, CustomerID: req.CustomerID, - TokenUsed: req.TokenUsed, } } @@ -401,7 +275,8 @@ func GamePlayModelToResponse(model *models.GamePlayResponse) *contract.GamePlayR GameID: model.GameID, CustomerID: model.CustomerID, PrizeID: model.PrizeID, - TokenUsed: model.TokenUsed, + CoinsUsed: model.CoinsUsed, + TokenUsed: model.CoinsUsed, RandomSeed: model.RandomSeed, CreatedAt: model.CreatedAt, Game: game, @@ -433,7 +308,8 @@ func PlayGameModelToResponse(model *models.PlayGameResponse) *contract.PlayGameR return &contract.PlayGameResponse{ GamePlay: gamePlayValue, PrizeWon: prizeWon, - TokensRemaining: model.TokensRemaining, + CoinsRemaining: model.CoinsRemaining, + TokensRemaining: model.CoinsRemaining, } } diff --git a/internal/transformer/order_transformer.go b/internal/transformer/order_transformer.go index b297cef..5bd19ba 100644 --- a/internal/transformer/order_transformer.go +++ b/internal/transformer/order_transformer.go @@ -161,6 +161,8 @@ func OrderModelToContract(resp *models.OrderResponse) *contract.OrderResponse { TotalPaid: resp.TotalPaid, PaymentCount: resp.PaymentCount, SplitType: resp.SplitType, + PointsEarned: resp.PointsEarned, + CoinsEarned: resp.CoinsEarned, } } @@ -322,6 +324,8 @@ func CreatePaymentContractToModel(req *contract.CreatePaymentRequest) *models.Cr return &models.CreatePaymentRequest{ OrderID: req.OrderID, PaymentMethodID: req.PaymentMethodID, + Points: req.Points, + PaymentCode: req.PaymentCode, Amount: req.Amount, TransactionID: req.TransactionID, SplitNumber: req.SplitNumber, @@ -363,6 +367,8 @@ func PaymentModelToContract(resp *models.PaymentResponse) *contract.PaymentRespo SplitType: resp.SplitType, SplitDescription: resp.SplitDescription, RefundAmount: resp.RefundAmount, + PointsUsed: resp.PointsUsed, + PointValue: resp.PointValue, RefundReason: resp.RefundReason, RefundedAt: resp.RefundedAt, RefundedBy: resp.RefundedBy, diff --git a/internal/transformer/order_transformer_test.go b/internal/transformer/order_transformer_test.go index c3067a0..5c55afd 100644 --- a/internal/transformer/order_transformer_test.go +++ b/internal/transformer/order_transformer_test.go @@ -1,11 +1,14 @@ package transformer import ( + "encoding/json" "testing" "apskel-pos-be/internal/contract" + "apskel-pos-be/internal/models" "github.com/google/uuid" + "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) @@ -46,3 +49,14 @@ func TestAddToOrderContractToModelCarriesWeight(t *testing.T) { require.NotNil(t, result.OrderItems[0].Weight) require.Equal(t, weight, *result.OrderItems[0].Weight) } + +func TestOrderModelToContractCarriesEarnings(t *testing.T) { + got := OrderModelToContract(&models.OrderResponse{PointsEarned: 875, CoinsEarned: 3}) + assert.Equal(t, int64(875), got.PointsEarned) + assert.Equal(t, int64(3), got.CoinsEarned) + + body, err := json.Marshal(OrderModelToContract(&models.OrderResponse{})) + assert.NoError(t, err) + assert.Contains(t, string(body), `"points_earned":0`, "present as 0 when nothing was earned") + assert.Contains(t, string(body), `"coins_earned":0`) +} diff --git a/internal/validator/campaign_validator.go b/internal/validator/campaign_validator.go index d46bae7..8618fc8 100644 --- a/internal/validator/campaign_validator.go +++ b/internal/validator/campaign_validator.go @@ -43,7 +43,7 @@ func (v *CampaignValidatorImpl) ValidateCreateCampaignRequest(req *contract.Crea // Validate campaign type if !v.isValidCampaignType(req.Type) { - return errors.New("invalid campaign type. Valid types are: REWARD, POINTS, TOKENS, MIXED"), constants.ValidationErrorCode + return errors.New("invalid campaign type. Valid types are: REWARD, POINTS, COINS, MIXED"), constants.ValidationErrorCode } // Validate date range @@ -79,7 +79,7 @@ func (v *CampaignValidatorImpl) ValidateUpdateCampaignRequest(req *contract.Upda // Validate campaign type if !v.isValidCampaignType(req.Type) { - return errors.New("invalid campaign type. Valid types are: REWARD, POINTS, TOKENS, MIXED"), constants.ValidationErrorCode + return errors.New("invalid campaign type. Valid types are: REWARD, POINTS, COINS, MIXED"), constants.ValidationErrorCode } // Validate date range @@ -113,7 +113,7 @@ func (v *CampaignValidatorImpl) ValidateListCampaignsRequest(req *contract.ListC // Validate campaign type filter if provided if req.Type != "" && !v.isValidCampaignType(req.Type) { - return errors.New("invalid campaign type filter. Valid types are: REWARD, POINTS, TOKENS, MIXED"), constants.ValidationErrorCode + return errors.New("invalid campaign type filter. Valid types are: REWARD, POINTS, COINS, MIXED"), constants.ValidationErrorCode } return nil, "" @@ -223,7 +223,7 @@ func (v *CampaignValidatorImpl) ValidateListCampaignRulesRequest(req *contract.L // Validate reward type filter if provided if req.RewardType != "" && !v.isValidRewardType(req.RewardType) { - return errors.New("invalid reward type filter. Valid types are: POINTS, TOKENS, REWARD"), constants.ValidationErrorCode + return errors.New("invalid reward type filter. Valid types are: POINTS, COINS, REWARD"), constants.ValidationErrorCode } return nil, "" @@ -254,7 +254,7 @@ func (v *CampaignValidatorImpl) ValidateDeleteCampaignRuleRequest(req *contract. } func (v *CampaignValidatorImpl) isValidCampaignType(campaignType string) bool { - validTypes := []string{"REWARD", "POINTS", "TOKENS", "MIXED"} + validTypes := []string{"REWARD", "POINTS", "COINS", "TOKENS", "MIXED"} return contains(validTypes, campaignType) } @@ -264,7 +264,7 @@ func (v *CampaignValidatorImpl) isValidRuleType(ruleType string) bool { } func (v *CampaignValidatorImpl) isValidRewardType(rewardType string) bool { - validTypes := []string{"POINTS", "TOKENS", "REWARD"} + validTypes := []string{"POINTS", "COINS", "TOKENS", "REWARD"} return contains(validTypes, rewardType) } @@ -293,11 +293,11 @@ func (v *CampaignValidatorImpl) validateCampaignRule(rule *contract.CampaignRule // Validate reward type if !v.isValidRewardType(rule.RewardType) { - return errors.New("invalid reward type in rule " + string(rune(ruleNumber)) + ". Valid types are: POINTS, TOKENS, REWARD") + return errors.New("invalid reward type in rule " + string(rune(ruleNumber)) + ". Valid types are: POINTS, COINS, REWARD") } // Validate reward value based on reward type - if rule.RewardType == "POINTS" || rule.RewardType == "TOKENS" { + if rule.RewardType == "POINTS" || rule.RewardType == "COINS" || rule.RewardType == "TOKENS" { if rule.RewardValue == nil || *rule.RewardValue <= 0 { return errors.New("reward value must be positive for " + rule.RewardType + " type in rule " + string(rune(ruleNumber))) } diff --git a/internal/validator/gamification_validator.go b/internal/validator/gamification_validator.go index c65a001..e0fc023 100644 --- a/internal/validator/gamification_validator.go +++ b/internal/validator/gamification_validator.go @@ -9,20 +9,6 @@ import ( ) type GamificationValidator interface { - // Customer Points - ValidateCreateCustomerPointsRequest(req *contract.CreateCustomerPointsRequest) (error, string) - ValidateUpdateCustomerPointsRequest(req *contract.UpdateCustomerPointsRequest) (error, string) - ValidateListCustomerPointsRequest(req *contract.ListCustomerPointsRequest) (error, string) - ValidateAddCustomerPointsRequest(req *contract.AddCustomerPointsRequest) (error, string) - ValidateDeductCustomerPointsRequest(req *contract.DeductCustomerPointsRequest) (error, string) - - // Customer Tokens - ValidateCreateCustomerTokensRequest(req *contract.CreateCustomerTokensRequest) (error, string) - ValidateUpdateCustomerTokensRequest(req *contract.UpdateCustomerTokensRequest) (error, string) - ValidateListCustomerTokensRequest(req *contract.ListCustomerTokensRequest) (error, string) - ValidateAddCustomerTokensRequest(req *contract.AddCustomerTokensRequest) (error, string) - ValidateDeductCustomerTokensRequest(req *contract.DeductCustomerTokensRequest) (error, string) - // Tiers ValidateCreateTierRequest(req *contract.CreateTierRequest) (error, string) ValidateUpdateTierRequest(req *contract.UpdateTierRequest) (error, string) @@ -60,152 +46,6 @@ func NewGamificationValidator() *GamificationValidatorImpl { } } -// Customer Points Validators -func (v *GamificationValidatorImpl) ValidateCreateCustomerPointsRequest(req *contract.CreateCustomerPointsRequest) (error, string) { - if err := v.validate.Struct(req); err != nil { - return err, "VALIDATION_ERROR" - } - - if req.Balance < 0 { - return errors.New("balance cannot be negative"), "INVALID_BALANCE" - } - - return nil, "" -} - -func (v *GamificationValidatorImpl) ValidateUpdateCustomerPointsRequest(req *contract.UpdateCustomerPointsRequest) (error, string) { - if err := v.validate.Struct(req); err != nil { - return err, "VALIDATION_ERROR" - } - - if req.Balance < 0 { - return errors.New("balance cannot be negative"), "INVALID_BALANCE" - } - - return nil, "" -} - -func (v *GamificationValidatorImpl) ValidateListCustomerPointsRequest(req *contract.ListCustomerPointsRequest) (error, string) { - if err := v.validate.Struct(req); err != nil { - return err, "VALIDATION_ERROR" - } - - if req.Page <= 0 { - req.Page = 1 - } - if req.Limit <= 0 { - req.Limit = 10 - } - if req.Limit > 100 { - req.Limit = 100 - } - - return nil, "" -} - -func (v *GamificationValidatorImpl) ValidateAddCustomerPointsRequest(req *contract.AddCustomerPointsRequest) (error, string) { - if err := v.validate.Struct(req); err != nil { - return err, "VALIDATION_ERROR" - } - - if req.Points <= 0 { - return errors.New("points must be greater than 0"), "INVALID_POINTS" - } - - return nil, "" -} - -func (v *GamificationValidatorImpl) ValidateDeductCustomerPointsRequest(req *contract.DeductCustomerPointsRequest) (error, string) { - if err := v.validate.Struct(req); err != nil { - return err, "VALIDATION_ERROR" - } - - if req.Points <= 0 { - return errors.New("points must be greater than 0"), "INVALID_POINTS" - } - - return nil, "" -} - -// Customer Tokens Validators -func (v *GamificationValidatorImpl) ValidateCreateCustomerTokensRequest(req *contract.CreateCustomerTokensRequest) (error, string) { - if err := v.validate.Struct(req); err != nil { - return err, "VALIDATION_ERROR" - } - - if req.Balance < 0 { - return errors.New("balance cannot be negative"), "INVALID_BALANCE" - } - - validTokenTypes := []string{"SPIN", "RAFFLE", "MINIGAME"} - if !contains(validTokenTypes, req.TokenType) { - return errors.New("invalid token type"), "INVALID_TOKEN_TYPE" - } - - return nil, "" -} - -func (v *GamificationValidatorImpl) ValidateUpdateCustomerTokensRequest(req *contract.UpdateCustomerTokensRequest) (error, string) { - if err := v.validate.Struct(req); err != nil { - return err, "VALIDATION_ERROR" - } - - if req.Balance < 0 { - return errors.New("balance cannot be negative"), "INVALID_BALANCE" - } - - return nil, "" -} - -func (v *GamificationValidatorImpl) ValidateListCustomerTokensRequest(req *contract.ListCustomerTokensRequest) (error, string) { - if err := v.validate.Struct(req); err != nil { - return err, "VALIDATION_ERROR" - } - - if req.Page <= 0 { - req.Page = 1 - } - if req.Limit <= 0 { - req.Limit = 10 - } - if req.Limit > 100 { - req.Limit = 100 - } - - if req.TokenType != "" { - validTokenTypes := []string{"SPIN", "RAFFLE", "MINIGAME"} - if !contains(validTokenTypes, req.TokenType) { - return errors.New("invalid token type"), "INVALID_TOKEN_TYPE" - } - } - - return nil, "" -} - -func (v *GamificationValidatorImpl) ValidateAddCustomerTokensRequest(req *contract.AddCustomerTokensRequest) (error, string) { - if err := v.validate.Struct(req); err != nil { - return err, "VALIDATION_ERROR" - } - - if req.Tokens <= 0 { - return errors.New("tokens must be greater than 0"), "INVALID_TOKENS" - } - - return nil, "" -} - -func (v *GamificationValidatorImpl) ValidateDeductCustomerTokensRequest(req *contract.DeductCustomerTokensRequest) (error, string) { - if err := v.validate.Struct(req); err != nil { - return err, "VALIDATION_ERROR" - } - - if req.Tokens <= 0 { - return errors.New("tokens must be greater than 0"), "INVALID_TOKENS" - } - - return nil, "" -} - // Tier Validators func (v *GamificationValidatorImpl) ValidateCreateTierRequest(req *contract.CreateTierRequest) (error, string) { if err := v.validate.Struct(req); err != nil { @@ -436,8 +276,8 @@ func (v *GamificationValidatorImpl) ValidateCreateGamePlayRequest(req *contract. return err, "VALIDATION_ERROR" } - if req.TokenUsed < 0 { - return errors.New("token used cannot be negative"), "INVALID_TOKEN_USED" + if req.CoinsUsed < 0 { + return errors.New("coins used cannot be negative"), "INVALID_COINS_USED" } return nil, "" @@ -466,10 +306,6 @@ func (v *GamificationValidatorImpl) ValidatePlayGameRequest(req *contract.PlayGa return err, "VALIDATION_ERROR" } - if req.TokenUsed < 0 { - return errors.New("token used cannot be negative"), "INVALID_TOKEN_USED" - } - return nil, "" } diff --git a/internal/validator/payment_method_validator.go b/internal/validator/payment_method_validator.go index 8173abf..62d70e3 100644 --- a/internal/validator/payment_method_validator.go +++ b/internal/validator/payment_method_validator.go @@ -95,6 +95,7 @@ func (v *PaymentMethodValidatorImpl) isValidPaymentMethodType(paymentMethodType string(constants.PaymentMethodTypeDigitalWallet), string(constants.PaymentMethodTypeQR), string(constants.PaymentMethodTypeEDC), + string(constants.PaymentMethodTypePoint), } for _, validType := range validTypes { diff --git a/internal/validator/wallet_validator.go b/internal/validator/wallet_validator.go new file mode 100644 index 0000000..862d137 --- /dev/null +++ b/internal/validator/wallet_validator.go @@ -0,0 +1,66 @@ +package validator + +import ( + "errors" + "strings" + "unicode/utf8" + + "apskel-pos-be/internal/constants" + "apskel-pos-be/internal/contract" +) + +// walletAdjustmentReasonLimit is the size of wallet_transactions.reason. +const walletAdjustmentReasonLimit = 255 + +// walletCashOutWords are reasons that describe turning balance into money. EnakPoint +// and EnakCoin can never be cashed out, and an adjustment must not be used to record +// that it happened (docs/prd-point-coin.md K7). Words like "tunai" are left out on +// purpose: "paid in cash but the points never arrived" is a legitimate reason. +var walletCashOutWords = []string{"pencairan", "cairkan", "cash out", "cashout", "withdraw"} + +type WalletValidator interface { + ValidateAdjustRequest(req *contract.AdjustCustomerWalletRequest) (error, string) +} + +type WalletValidatorImpl struct{} + +func NewWalletValidator() *WalletValidatorImpl { + return &WalletValidatorImpl{} +} + +func (v *WalletValidatorImpl) ValidateAdjustRequest(req *contract.AdjustCustomerWalletRequest) (error, string) { + if req == nil { + return errors.New("request body is required"), constants.MissingFieldErrorCode + } + + req.Currency = strings.ToUpper(strings.TrimSpace(req.Currency)) + if req.Currency == "" { + return errors.New("currency is required"), constants.MissingFieldErrorCode + } + if !constants.IsValidWalletCurrency(req.Currency) { + return errors.New("currency must be POINT or COIN"), constants.MalformedFieldErrorCode + } + + if req.Amount == 0 { + return errors.New("amount must not be zero: use a positive amount to add and a negative one to take away"), constants.ValidationErrorCode + } + + req.Reason = strings.TrimSpace(req.Reason) + if req.Reason == "" { + return errors.New("reason is required"), constants.MissingFieldErrorCode + } + if utf8.RuneCountInString(req.Reason) > walletAdjustmentReasonLimit { + return errors.New("reason must be at most 255 characters"), constants.MalformedFieldErrorCode + } + lower := strings.ToLower(req.Reason) + for _, word := range walletCashOutWords { + if strings.Contains(lower, word) { + return errors.New("EnakPoint and EnakCoin cannot be cashed out, so an adjustment cannot be for a cash-out"), constants.ValidationErrorCode + } + } + + if len(req.IdempotencyKey) > 50 { + return errors.New("idempotency_key must be at most 50 characters"), constants.MalformedFieldErrorCode + } + return nil, "" +} diff --git a/internal/validator/wallet_validator_test.go b/internal/validator/wallet_validator_test.go new file mode 100644 index 0000000..b765d87 --- /dev/null +++ b/internal/validator/wallet_validator_test.go @@ -0,0 +1,43 @@ +package validator + +import ( + "strings" + "testing" + + "github.com/stretchr/testify/assert" + + "apskel-pos-be/internal/constants" + "apskel-pos-be/internal/contract" +) + +func TestWalletValidator_AdjustRequest(t *testing.T) { + v := NewWalletValidator() + + ok := &contract.AdjustCustomerWalletRequest{Currency: " point ", Amount: -25, Reason: " komplain #45 "} + err, _ := v.ValidateAdjustRequest(ok) + assert.NoError(t, err) + assert.Equal(t, constants.WalletCurrencyPoint, ok.Currency, "currency is normalised") + assert.Equal(t, "komplain #45", ok.Reason, "reason is trimmed") + + legit := &contract.AdjustCustomerWalletRequest{Currency: "COIN", Amount: 5, Reason: "Bayar tunai tapi poin tidak masuk"} + err, _ = v.ValidateAdjustRequest(legit) + assert.NoError(t, err, "mentioning a cash payment is not a cash-out") + + for name, req := range map[string]*contract.AdjustCustomerWalletRequest{ + "nil": nil, + "no currency": {Amount: 5, Reason: "x"}, + "unknown currency": {Currency: "GOLD", Amount: 5, Reason: "x"}, + "zero amount": {Currency: "POINT", Amount: 0, Reason: "x"}, + "no reason": {Currency: "POINT", Amount: 5, Reason: " "}, + "reason too long": {Currency: "POINT", Amount: 5, Reason: strings.Repeat("a", 256)}, + "cash-out reason": {Currency: "POINT", Amount: -500, Reason: "Pencairan saldo ke rekening"}, + "cash-out, English": {Currency: "POINT", Amount: -500, Reason: "customer asked to cash out"}, + "long key": {Currency: "POINT", Amount: 5, Reason: "x", IdempotencyKey: strings.Repeat("k", 51)}, + } { + t.Run(name, func(t *testing.T) { + err, code := v.ValidateAdjustRequest(req) + assert.Error(t, err) + assert.NotEmpty(t, code) + }) + } +} diff --git a/migrations/000090_create_wallet_tables.down.sql b/migrations/000090_create_wallet_tables.down.sql new file mode 100644 index 0000000..2369658 --- /dev/null +++ b/migrations/000090_create_wallet_tables.down.sql @@ -0,0 +1,4 @@ +DROP TABLE IF EXISTS wallet_lot_allocations; +DROP TABLE IF EXISTS wallet_lots; +DROP TABLE IF EXISTS wallet_transactions; +DROP TABLE IF EXISTS customer_wallets; diff --git a/migrations/000090_create_wallet_tables.up.sql b/migrations/000090_create_wallet_tables.up.sql new file mode 100644 index 0000000..4dcee08 --- /dev/null +++ b/migrations/000090_create_wallet_tables.up.sql @@ -0,0 +1,131 @@ +-- EnakPoint & EnakCoin wallet (docs/prd-point-coin.md §8). Replaces customer_points +-- and customer_tokens; the old tables stay until their data is migrated (PC-105). +-- +-- Balances are only ever changed together with a ledger row, in one transaction, and +-- every ledger row must name where the value came from or went to (K5). The CHECKs +-- below enforce that at the database so a bug in the application cannot skip it. + +-- One row per customer. Besides holding the balances, this row is the lock every +-- wallet operation for the customer takes first (SELECT ... FOR UPDATE), so +-- concurrent operations on the same customer queue up instead of spending twice. +CREATE TABLE customer_wallets ( + customer_id UUID PRIMARY KEY REFERENCES customers(id) ON DELETE RESTRICT, + organization_id UUID NOT NULL REFERENCES organizations(id), + point_balance BIGINT NOT NULL DEFAULT 0, + coin_balance BIGINT NOT NULL DEFAULT 0, + created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(), + updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(), + + CONSTRAINT chk_customer_wallets_point_balance CHECK (point_balance >= 0), + CONSTRAINT chk_customer_wallets_coin_balance CHECK (coin_balance >= 0) +); + +-- The ledger. Append-only: rows are never updated or deleted, a correction is a new +-- row (EARN_REVERSAL, PAYMENT_REFUND or ADJUSTMENT) pointing at the one it corrects. +-- ON DELETE RESTRICT on customers means a customer with history can only be +-- deactivated, not hard-deleted. +CREATE TABLE wallet_transactions ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + organization_id UUID NOT NULL, + customer_id UUID NOT NULL REFERENCES customers(id) ON DELETE RESTRICT, + currency VARCHAR(10) NOT NULL, + type VARCHAR(30) NOT NULL, + -- Signed: positive credits the wallet, negative debits it. + amount BIGINT NOT NULL, + balance_after BIGINT NOT NULL, + -- Ties the two rows of an exchange or a transfer together. + group_id UUID, + + -- Where the value came from (amount > 0) or went to (amount < 0). Required for + -- every type; §8.1 lists which reference_type each type uses. + reference_type VARCHAR(30) NOT NULL, + reference_id UUID NOT NULL, + + counterparty_customer_id UUID REFERENCES customers(id), + reverses_transaction_id UUID REFERENCES wallet_transactions(id), + outlet_id UUID, + -- The admin for ADJUSTMENT, the cashier for PAYMENT / PAYMENT_REFUND via POS. + created_by_user UUID, + reason VARCHAR(255), + + -- Display text frozen at creation, so a later rename of an outlet or a customer + -- does not rewrite history (same idea as the price snapshot on order_items). + description VARCHAR(255) NOT NULL, + -- Snapshot of whatever was used to compute the row: settings, point value, + -- exchange rate, reversal shortfall. + metadata JSONB DEFAULT '{}', + idempotency_key VARCHAR(100) UNIQUE, + created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(), + + CONSTRAINT chk_wallet_transactions_currency CHECK (currency IN ('POINT', 'COIN')), + CONSTRAINT chk_wallet_transactions_amount CHECK (amount <> 0), + + -- Only EnakPoint can pay (K2); spending on games and exchanging out are EnakCoin only. + CONSTRAINT chk_wallet_transactions_point_only_types CHECK ( + type NOT IN ('PAYMENT', 'PAYMENT_REFUND', 'EXCHANGE_IN', 'REWARD_REDEEM') + OR currency = 'POINT'), + CONSTRAINT chk_wallet_transactions_coin_only_types CHECK ( + type NOT IN ('EXCHANGE_OUT', 'GAME_SPEND') OR currency = 'COIN'), + + CONSTRAINT chk_wallet_transactions_transfer_counterparty CHECK ( + type NOT IN ('TRANSFER_IN', 'TRANSFER_OUT') OR counterparty_customer_id IS NOT NULL), + CONSTRAINT chk_wallet_transactions_reversal_source CHECK ( + type NOT IN ('EARN_REVERSAL', 'PAYMENT_REFUND') OR reverses_transaction_id IS NOT NULL), + CONSTRAINT chk_wallet_transactions_adjustment_actor CHECK ( + type <> 'ADJUSTMENT' OR (created_by_user IS NOT NULL AND reason IS NOT NULL)), + CONSTRAINT chk_wallet_transactions_expire_lot CHECK ( + type <> 'EXPIRE' OR reference_type = 'LOT') +); + +CREATE INDEX idx_wallet_transactions_customer_id_created_at ON wallet_transactions(customer_id, created_at DESC); +CREATE INDEX idx_wallet_transactions_reference ON wallet_transactions(reference_type, reference_id); +CREATE INDEX idx_wallet_transactions_group_id ON wallet_transactions(group_id); +CREATE INDEX idx_wallet_transactions_counterparty_customer_id ON wallet_transactions(counterparty_customer_id); +CREATE INDEX idx_wallet_transactions_reverses_transaction_id ON wallet_transactions(reverses_transaction_id); + +-- Balance kept per lot (K9). Every credit creates one or more lots with their own +-- expiry, and every debit draws from the lots that expire soonest. A transfer, +-- exchange or refund carries the expiry of the lot it came from and points back at it +-- through origin_lot_id, so each unit can be traced to the EARN, ADJUSTMENT or +-- MIGRATION that first created it. +CREATE TABLE wallet_lots ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + organization_id UUID NOT NULL, + customer_id UUID NOT NULL REFERENCES customers(id) ON DELETE RESTRICT, + currency VARCHAR(10) NOT NULL, + -- The incoming ledger row that created this lot. + source_transaction_id UUID NOT NULL REFERENCES wallet_transactions(id), + origin_lot_id UUID REFERENCES wallet_lots(id), + original_amount BIGINT NOT NULL, + -- The only column in the wallet tables that is ever updated. It is a cached + -- original_amount - SUM(wallet_lot_allocations.amount), kept for fast spending, + -- and the reconciliation job (§7.5) checks it against the allocations. + remaining_amount BIGINT NOT NULL, + -- NULL means the lot never expires. + expires_at TIMESTAMP WITH TIME ZONE, + created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(), + + CONSTRAINT chk_wallet_lots_currency CHECK (currency IN ('POINT', 'COIN')), + CONSTRAINT chk_wallet_lots_original_amount CHECK (original_amount > 0), + CONSTRAINT chk_wallet_lots_remaining_amount CHECK ( + remaining_amount >= 0 AND remaining_amount <= original_amount) +); + +-- Spending order (K9): soonest expiry first, lots without an expiry last. +CREATE INDEX idx_wallet_lots_consume ON wallet_lots(customer_id, currency, expires_at NULLS LAST, created_at) + WHERE remaining_amount > 0; +CREATE INDEX idx_wallet_lots_expiry ON wallet_lots(expires_at) WHERE remaining_amount > 0; + +-- Which lots each outgoing ledger row drew from, and how much from each. +CREATE TABLE wallet_lot_allocations ( + transaction_id UUID NOT NULL REFERENCES wallet_transactions(id), + lot_id UUID NOT NULL REFERENCES wallet_lots(id), + amount BIGINT NOT NULL, + + PRIMARY KEY (transaction_id, lot_id), + CONSTRAINT chk_wallet_lot_allocations_amount CHECK (amount > 0) +); + +-- Not in §8: the primary key cannot serve lookups by lot, which the reconciliation +-- job needs to sum each lot's allocations. +CREATE INDEX idx_wallet_lot_allocations_lot_id ON wallet_lot_allocations(lot_id); diff --git a/migrations/000091_create_organization_settings.down.sql b/migrations/000091_create_organization_settings.down.sql new file mode 100644 index 0000000..62d6a91 --- /dev/null +++ b/migrations/000091_create_organization_settings.down.sql @@ -0,0 +1,2 @@ +DROP TABLE IF EXISTS loyalty_setting_changes; +DROP TABLE IF EXISTS organization_settings; diff --git a/migrations/000091_create_organization_settings.up.sql b/migrations/000091_create_organization_settings.up.sql new file mode 100644 index 0000000..06e9ed1 --- /dev/null +++ b/migrations/000091_create_organization_settings.up.sql @@ -0,0 +1,35 @@ +-- Settings that must be the same in every outlet of an organization, starting with the +-- loyalty ones (docs/prd-point-coin.md F2, F12): point value, exchange rate, transfer +-- limits and expiry. Same key-value shape as outlet_settings. +CREATE TABLE organization_settings ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + organization_id UUID NOT NULL REFERENCES organizations(id) ON DELETE CASCADE, + key VARCHAR(255) NOT NULL, + value TEXT, + created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(), + updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(), + UNIQUE(organization_id, key) +); + +-- The unique constraint leads with organization_id, so it also serves the plain +-- per-organization lookups and there is no separate index on that column. + +-- Who changed which loyalty setting, from what, to what (F2). Covers both the +-- organization settings above and the per-outlet loyalty keys in outlet_settings. +-- Append-only. Values are stored as text, the same as in the settings tables. +CREATE TABLE loyalty_setting_changes ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + organization_id UUID NOT NULL, + -- NULL for an organization setting. + outlet_id UUID, + key VARCHAR(100) NOT NULL, + -- NULL when the key had no stored value yet (it was on its default). + old_value TEXT, + new_value TEXT, + changed_by UUID NOT NULL, + created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW() +); + +CREATE INDEX idx_loyalty_setting_changes_organization_id_created_at ON loyalty_setting_changes(organization_id, created_at DESC); +CREATE INDEX idx_loyalty_setting_changes_outlet_id_created_at ON loyalty_setting_changes(outlet_id, created_at DESC) + WHERE outlet_id IS NOT NULL; diff --git a/migrations/000092_rename_campaign_tokens_to_coins.down.sql b/migrations/000092_rename_campaign_tokens_to_coins.down.sql new file mode 100644 index 0000000..06a8ab1 --- /dev/null +++ b/migrations/000092_rename_campaign_tokens_to_coins.down.sql @@ -0,0 +1,5 @@ +UPDATE campaigns SET type = 'TOKENS' WHERE type = 'COINS'; +UPDATE campaign_rules SET reward_type = 'TOKENS' WHERE reward_type = 'COINS'; + +COMMENT ON COLUMN campaigns.type IS 'Type of campaign: REWARD, POINTS, TOKENS, MIXED'; +COMMENT ON COLUMN campaign_rules.reward_type IS 'Type of reward: POINTS, TOKENS, REWARD'; diff --git a/migrations/000092_rename_campaign_tokens_to_coins.up.sql b/migrations/000092_rename_campaign_tokens_to_coins.up.sql new file mode 100644 index 0000000..8ccf3fc --- /dev/null +++ b/migrations/000092_rename_campaign_tokens_to_coins.up.sql @@ -0,0 +1,7 @@ +-- Tokens become EnakCoin (docs/prd-point-coin.md §10). Campaigns that handed out +-- tokens now hand out coins; the API still accepts TOKENS and stores it as COINS. +UPDATE campaigns SET type = 'COINS' WHERE type = 'TOKENS'; +UPDATE campaign_rules SET reward_type = 'COINS' WHERE reward_type = 'TOKENS'; + +COMMENT ON COLUMN campaigns.type IS 'Type of campaign: REWARD, POINTS, COINS, MIXED'; +COMMENT ON COLUMN campaign_rules.reward_type IS 'Type of reward: POINTS, COINS, REWARD'; diff --git a/migrations/000093_add_customer_pin.down.sql b/migrations/000093_add_customer_pin.down.sql new file mode 100644 index 0000000..95edae3 --- /dev/null +++ b/migrations/000093_add_customer_pin.down.sql @@ -0,0 +1,9 @@ +DROP TABLE IF EXISTS customer_security_events; + +ALTER TABLE customers + DROP CONSTRAINT IF EXISTS chk_customers_pin_failed_attempts, + DROP COLUMN IF EXISTS transfer_blocked_until, + DROP COLUMN IF EXISTS pin_locked_until, + DROP COLUMN IF EXISTS pin_failed_attempts, + DROP COLUMN IF EXISTS pin_set_at, + DROP COLUMN IF EXISTS pin_hash; diff --git a/migrations/000093_add_customer_pin.up.sql b/migrations/000093_add_customer_pin.up.sql new file mode 100644 index 0000000..12e722b --- /dev/null +++ b/migrations/000093_add_customer_pin.up.sql @@ -0,0 +1,32 @@ +-- Customer PIN (docs/prd-point-coin.md F11, K8). A 6-digit PIN, separate from the +-- login password, approves everything that moves EnakPoint or EnakCoin on the +-- customer's request. Only its bcrypt hash is stored. +ALTER TABLE customers + ADD COLUMN pin_hash VARCHAR(255), + ADD COLUMN pin_set_at TIMESTAMP WITH TIME ZONE, + -- Kept in the database, not a cache, so it cannot be dodged by waiting for a cache + -- to expire or by hitting another server (Q17). + ADD COLUMN pin_failed_attempts INT NOT NULL DEFAULT 0, + ADD COLUMN pin_locked_until TIMESTAMP WITH TIME ZONE, + -- Outgoing transfers are held for 24 hours after a PIN reset (Q16). + ADD COLUMN transfer_blocked_until TIMESTAMP WITH TIME ZONE, + ADD CONSTRAINT chk_customers_pin_failed_attempts CHECK (pin_failed_attempts >= 0); + +-- Security log of PIN events. Not a balance movement, so not in wallet_transactions. +CREATE TABLE customer_security_events ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + customer_id UUID NOT NULL REFERENCES customers(id) ON DELETE RESTRICT, + -- PIN_SET, PIN_CHANGED, PIN_RESET, PIN_FAILED, PIN_LOCKED, PIN_REMOVED_BY_ADMIN + event VARCHAR(30) NOT NULL, + -- The admin, for PIN_REMOVED_BY_ADMIN. + actor_user UUID, + reason VARCHAR(255), + ip_address VARCHAR(45), + user_agent VARCHAR(255), + created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(), + + CONSTRAINT chk_customer_security_events_admin CHECK ( + event <> 'PIN_REMOVED_BY_ADMIN' OR (actor_user IS NOT NULL AND reason IS NOT NULL)) +); + +CREATE INDEX idx_customer_security_events_customer_id_created_at ON customer_security_events(customer_id, created_at DESC); diff --git a/migrations/000094_add_point_payment_method.down.sql b/migrations/000094_add_point_payment_method.down.sql new file mode 100644 index 0000000..dd86218 --- /dev/null +++ b/migrations/000094_add_point_payment_method.down.sql @@ -0,0 +1,16 @@ +ALTER TABLE payments + DROP CONSTRAINT IF EXISTS chk_payments_point_pair, + DROP COLUMN IF EXISTS point_value, + DROP COLUMN IF EXISTS points_used; + +DROP TRIGGER IF EXISTS trigger_create_point_payment_method ON organizations; +DROP FUNCTION IF EXISTS create_point_payment_method(); + +-- Fails if an EnakPoint method has been used by a payment, which is the point: those +-- payments would lose their method. +DELETE FROM payment_methods WHERE type = 'point'; +DROP INDEX IF EXISTS uq_payment_methods_point_per_organization; + +ALTER TABLE payment_methods DROP CONSTRAINT IF EXISTS payment_methods_type_check; +ALTER TABLE payment_methods ADD CONSTRAINT payment_methods_type_check + CHECK (type IN ('cash', 'card', 'digital_wallet')); diff --git a/migrations/000094_add_point_payment_method.up.sql b/migrations/000094_add_point_payment_method.up.sql new file mode 100644 index 0000000..e39899e --- /dev/null +++ b/migrations/000094_add_point_payment_method.up.sql @@ -0,0 +1,45 @@ +-- Paying with EnakPoint (docs/prd-point-coin.md F9, §8, §10.5). + +-- A new payment method type. Every organization has exactly one method of it, made by +-- the system, which cannot be deleted or change type. +ALTER TABLE payment_methods DROP CONSTRAINT IF EXISTS payment_methods_type_check; +ALTER TABLE payment_methods ADD CONSTRAINT payment_methods_type_check + CHECK (type IN ('cash', 'card', 'digital_wallet', 'point')); + +CREATE UNIQUE INDEX uq_payment_methods_point_per_organization ON payment_methods(organization_id) + WHERE type = 'point'; + +INSERT INTO payment_methods (organization_id, name, type, is_active) +SELECT id, 'EnakPoint', 'point', TRUE FROM organizations +ON CONFLICT (organization_id) WHERE type = 'point' DO NOTHING; + +-- New organizations get theirs the same way they get their walk-in customer, whatever +-- code path creates them. +CREATE OR REPLACE FUNCTION create_point_payment_method() +RETURNS TRIGGER AS $$ +BEGIN + INSERT INTO payment_methods (organization_id, name, type, is_active) + VALUES (NEW.id, 'EnakPoint', 'point', TRUE) + ON CONFLICT (organization_id) WHERE type = 'point' DO NOTHING; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER trigger_create_point_payment_method + AFTER INSERT ON organizations + FOR EACH ROW + EXECUTE FUNCTION create_point_payment_method(); + +-- A payment made with EnakPoint records how many were used and the rupiah value of one +-- at that moment. The value is frozen so a refund returns exactly the EnakPoint used, +-- whatever the value is by then. +-- +-- Written so it never evaluates to NULL: the form in the PRD, (both NULL) OR (both +-- > 0), is NULL for points_used = 1000 with point_value NULL, and a CHECK only rejects +-- FALSE, so a payment could lose its frozen value. +ALTER TABLE payments + ADD COLUMN points_used BIGINT, + ADD COLUMN point_value DECIMAL(10,2), + ADD CONSTRAINT chk_payments_point_pair CHECK ( + (points_used IS NULL) = (point_value IS NULL) + AND (points_used IS NULL OR (points_used > 0 AND point_value > 0))); diff --git a/migrations/000095_rename_game_plays_token_used_to_coins_used.down.sql b/migrations/000095_rename_game_plays_token_used_to_coins_used.down.sql new file mode 100644 index 0000000..fb9fb88 --- /dev/null +++ b/migrations/000095_rename_game_plays_token_used_to_coins_used.down.sql @@ -0,0 +1,2 @@ +ALTER TABLE game_plays RENAME CONSTRAINT chk_game_plays_coins_used_non_negative TO chk_game_plays_token_used_non_negative; +ALTER TABLE game_plays RENAME COLUMN coins_used TO token_used; diff --git a/migrations/000095_rename_game_plays_token_used_to_coins_used.up.sql b/migrations/000095_rename_game_plays_token_used_to_coins_used.up.sql new file mode 100644 index 0000000..d59c7e1 --- /dev/null +++ b/migrations/000095_rename_game_plays_token_used_to_coins_used.up.sql @@ -0,0 +1,4 @@ +-- Every game now costs EnakCoin (docs/prd-point-coin.md F8, K1), so what a play used +-- is a number of EnakCoin. +ALTER TABLE game_plays RENAME COLUMN token_used TO coins_used; +ALTER TABLE game_plays RENAME CONSTRAINT chk_game_plays_token_used_non_negative TO chk_game_plays_coins_used_non_negative; diff --git a/migrations/000096_create_customer_devices.down.sql b/migrations/000096_create_customer_devices.down.sql new file mode 100644 index 0000000..b541b49 --- /dev/null +++ b/migrations/000096_create_customer_devices.down.sql @@ -0,0 +1 @@ +DROP TABLE IF EXISTS customer_devices; diff --git a/migrations/000096_create_customer_devices.up.sql b/migrations/000096_create_customer_devices.up.sql new file mode 100644 index 0000000..c8f9d0d --- /dev/null +++ b/migrations/000096_create_customer_devices.up.sql @@ -0,0 +1,17 @@ +-- Devices of the customer app, so customers can get push notifications through FCM +-- (docs/prd-point-coin.md F5: the recipient of a transfer is notified). user_devices +-- only holds staff devices. +CREATE TABLE customer_devices ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + customer_id UUID NOT NULL REFERENCES customers(id) ON DELETE CASCADE, + device_id VARCHAR(255) NOT NULL, + platform VARCHAR(50) CHECK (platform IN ('android', 'ios', 'web')), + fcm_token VARCHAR(512) NOT NULL, + app_version VARCHAR(50), + last_active_at TIMESTAMP WITH TIME ZONE, + created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(), + updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW() +); + +CREATE UNIQUE INDEX idx_customer_devices_customer_device ON customer_devices(customer_id, device_id); +CREATE INDEX idx_customer_devices_fcm_token ON customer_devices(fcm_token); diff --git a/migrations/000097_create_wallet_expiry_reminders.down.sql b/migrations/000097_create_wallet_expiry_reminders.down.sql new file mode 100644 index 0000000..a154829 --- /dev/null +++ b/migrations/000097_create_wallet_expiry_reminders.down.sql @@ -0,0 +1 @@ +DROP TABLE IF EXISTS wallet_expiry_reminders; diff --git a/migrations/000097_create_wallet_expiry_reminders.up.sql b/migrations/000097_create_wallet_expiry_reminders.up.sql new file mode 100644 index 0000000..74e500e --- /dev/null +++ b/migrations/000097_create_wallet_expiry_reminders.up.sql @@ -0,0 +1,11 @@ +-- Which expiry reminders have gone out (docs/prd-point-coin.md F12): one per +-- customer, currency and expiry day. The row is written before the push is sent, so +-- several instances of the job, or a restart, never remind twice. +CREATE TABLE wallet_expiry_reminders ( + customer_id UUID NOT NULL REFERENCES customers(id) ON DELETE CASCADE, + currency VARCHAR(10) NOT NULL CHECK (currency IN ('POINT','COIN')), + expiry_date DATE NOT NULL, + amount BIGINT NOT NULL, + created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(), + PRIMARY KEY (customer_id, currency, expiry_date) +); From 9b21af8892f3a6a13600d31b00c0667bfcbc911e Mon Sep 17 00:00:00 2001 From: efrilm Date: Wed, 30 Sep 2026 15:32:25 +0700 Subject: [PATCH 2/5] fix(deploy): require explicit environment and isolate containers per env Deploying staging from a folder checked out on main replaced the production container, because the environment was inferred from the current branch and both environments shared the container name "apskel-pos". - Environment is now a required argument (staging|production) - Refuse to deploy when the branch doesn't match, HEAD is detached, or the tree is dirty - Container name per environment; the legacy "apskel-pos" container is only removed by production deploys - Abort if the port is held by another environment's container - Confirmation prompt for production (--yes to skip) - Fast-forward-only pull from origin/ - Keep the previous image and roll back automatically when the new container is not healthy; --rollback for manual rollback Co-Authored-By: Claude Opus 5.5 --- deployment.sh | 169 ++++++++++++++++++++++++++++++++++++++++++-------- 1 file changed, 142 insertions(+), 27 deletions(-) diff --git a/deployment.sh b/deployment.sh index f1fb342..7586274 100644 --- a/deployment.sh +++ b/deployment.sh @@ -1,62 +1,177 @@ #!/bin/bash set -euo pipefail +# Usage: +# ./deployment.sh staging deploy staging (branch staging, port 4001) +# ./deployment.sh production deploy production (branch main, port 4000) +# ./deployment.sh production --rollback kembali ke image sebelum deploy terakhir +# Tambahkan --yes untuk melewati konfirmasi production. + APP_NAME="apskel-pos" +LEGACY_CONTAINER="apskel-pos" # nama lama sebelum nama container memakai environment -# ─── Deteksi environment dari branch aktif ─────────────────────────────────── -CURRENT_BRANCH=$(git rev-parse --abbrev-ref HEAD) +usage() { + echo "Usage: $0 [--rollback] [--yes]" + exit 1 +} -case "$CURRENT_BRANCH" in - main) - ENV_MODE="production" +fail() { + echo "❌ $*" + exit 1 +} + +# ─── Argumen ────────────────────────────────────────────────────────────────── +ENV_MODE="${1:-}" +shift || true + +ROLLBACK=false +ASSUME_YES=false +for arg in "$@"; do + case "$arg" in + --rollback) ROLLBACK=true ;; + --yes|-y) ASSUME_YES=true ;; + *) usage ;; + esac +done + +# Environment wajib disebut eksplisit, tidak lagi ditebak dari branch aktif +case "$ENV_MODE" in + production) + EXPECTED_BRANCH="main" PORT="4000" ;; staging) - ENV_MODE="staging" + EXPECTED_BRANCH="staging" PORT="4001" ;; *) - echo "❌ Branch '$CURRENT_BRANCH' tidak dikenali untuk deployment." - echo " Gunakan branch 'main' (production) atau 'staging' (staging)." - exit 1 + usage ;; esac -CONTAINER_NAME="$APP_NAME" +CONTAINER_NAME="$APP_NAME-$ENV_MODE" IMAGE_NAME="$APP_NAME:$ENV_MODE" +PREVIOUS_IMAGE="$APP_NAME:$ENV_MODE-previous" +CONFIG_FILE="infra/$ENV_MODE.yaml" + +# ─── Validasi repo ──────────────────────────────────────────────────────────── +CURRENT_BRANCH=$(git rev-parse --abbrev-ref HEAD) + +if [ "$CURRENT_BRANCH" = "HEAD" ]; then + fail "Repo sedang detached HEAD. Jalankan 'git checkout $EXPECTED_BRANCH' dulu." +fi + +if [ "$CURRENT_BRANCH" != "$EXPECTED_BRANCH" ]; then + fail "Deploy $ENV_MODE harus dari branch '$EXPECTED_BRANCH', folder ini di branch '$CURRENT_BRANCH'. + Pakai folder terpisah per environment, jangan pindah branch di folder yang sedang dipakai container lain." +fi + +if [ -n "$(git status --porcelain --untracked-files=no)" ]; then + fail "Ada perubahan yang belum di-commit di folder ini. Bersihkan dulu sebelum deploy." +fi + +[ -f "$CONFIG_FILE" ] || fail "Config file '$CONFIG_FILE' tidak ditemukan." + +# ─── Pastikan port tidak dipakai container environment lain ────────────────── +OTHER_ON_PORT=$(docker ps --filter "publish=$PORT" --format '{{.Names}}' \ + | grep -vx "$CONTAINER_NAME" \ + | { if [ "$ENV_MODE" = "production" ]; then grep -vx "$LEGACY_CONTAINER"; else cat; fi; } \ + || true) +if [ -n "$OTHER_ON_PORT" ]; then + fail "Port $PORT sedang dipakai container lain: $OTHER_ON_PORT" +fi echo "📦 Environment : $ENV_MODE" echo "🌿 Branch : $CURRENT_BRANCH" echo "🐳 Container : $CONTAINER_NAME" echo "🔌 Port : $PORT" +echo "📁 Folder : $(pwd)" +[ "$ROLLBACK" = true ] && echo "⏪ Mode : ROLLBACK ke $PREVIOUS_IMAGE" echo "" -# ─── Pastikan config file ada ───────────────────────────────────────────────── -CONFIG_FILE="infra/$ENV_MODE.yaml" -if [ ! -f "$CONFIG_FILE" ]; then - echo "❌ Config file '$CONFIG_FILE' tidak ditemukan." - exit 1 +# ─── Konfirmasi production ──────────────────────────────────────────────────── +if [ "$ENV_MODE" = "production" ] && [ "$ASSUME_YES" != true ]; then + read -r -p "⚠️ Ini PRODUCTION. Ketik 'production' untuk lanjut: " CONFIRM + [ "$CONFIRM" = "production" ] || fail "Dibatalkan." fi -echo "🔄 Pulling latest code..." -git pull +run_container() { + local image="$1" + + echo "🛑 Stopping and removing old container..." + docker rm -f "$CONTAINER_NAME" 2>/dev/null || true + # Container production lama masih bernama 'apskel-pos'; staging tidak boleh menyentuhnya + if [ "$ENV_MODE" = "production" ]; then + docker rm -f "$LEGACY_CONTAINER" 2>/dev/null || true + fi + + echo "🚀 Running container from $image..." + docker run -d --name "$CONTAINER_NAME" \ + --restart unless-stopped \ + -p "$PORT:4000" \ + -e TZ=Asia/Jakarta \ + -e ENV_MODE="$ENV_MODE" \ + -v "$(pwd)/infra":/infra:ro \ + -v "$(pwd)/templates":/templates:ro \ + "$image" >/dev/null +} + +wait_healthy() { + echo "🩺 Waiting for healthcheck..." + for _ in $(seq 1 36); do + local status + status=$(docker inspect -f '{{if .State.Health}}{{.State.Health.Status}}{{else}}{{.State.Status}}{{end}}' "$CONTAINER_NAME" 2>/dev/null || echo "missing") + case "$status" in + healthy) return 0 ;; + unhealthy|exited|dead|missing) return 1 ;; + esac + sleep 5 + done + return 1 +} + +# ─── Rollback ───────────────────────────────────────────────────────────────── +if [ "$ROLLBACK" = true ]; then + docker image inspect "$PREVIOUS_IMAGE" >/dev/null 2>&1 || fail "Image '$PREVIOUS_IMAGE' tidak ada, tidak bisa rollback." + run_container "$PREVIOUS_IMAGE" + wait_healthy || fail "Container hasil rollback tidak healthy. Cek: docker logs $CONTAINER_NAME" + docker tag "$PREVIOUS_IMAGE" "$IMAGE_NAME" + echo "✅ Rollback $ENV_MODE complete." + exit 0 +fi + +# ─── Deploy ─────────────────────────────────────────────────────────────────── +echo "🔄 Pulling latest code (origin/$EXPECTED_BRANCH)..." +git fetch origin "$EXPECTED_BRANCH" +git merge --ff-only "origin/$EXPECTED_BRANCH" +echo " Commit: $(git log -1 --format='%h %s')" + +# Simpan image yang sedang jalan untuk rollback +if docker image inspect "$IMAGE_NAME" >/dev/null 2>&1; then + docker tag "$IMAGE_NAME" "$PREVIOUS_IMAGE" +fi echo "🐳 Building Docker image ($ENV_MODE)..." docker build --target production -t "$IMAGE_NAME" . -echo "🛑 Stopping and removing old container..." -docker rm -f "$CONTAINER_NAME" 2>/dev/null || true +run_container "$IMAGE_NAME" -echo "🚀 Running new container..." -docker run -d --name "$CONTAINER_NAME" \ - -p "$PORT:4000" \ - -e TZ=Asia/Jakarta \ - -e ENV_MODE="$ENV_MODE" \ - -v "$(pwd)/infra":/infra:ro \ - -v "$(pwd)/templates":/templates:ro \ - "$IMAGE_NAME" +if ! wait_healthy; then + echo "❌ Container baru tidak healthy. Log terakhir:" + docker logs --tail 50 "$CONTAINER_NAME" || true + if docker image inspect "$PREVIOUS_IMAGE" >/dev/null 2>&1; then + echo "⏪ Rolling back ke $PREVIOUS_IMAGE..." + run_container "$PREVIOUS_IMAGE" + wait_healthy || fail "Rollback juga tidak healthy. Cek manual: docker logs $CONTAINER_NAME" + # Jangan biarkan image rusak jadi 'previous' di deploy berikutnya + docker tag "$PREVIOUS_IMAGE" "$IMAGE_NAME" + fail "Deploy gagal, $ENV_MODE sudah dikembalikan ke image sebelumnya." + fi + fail "Deploy gagal dan tidak ada image sebelumnya untuk rollback." +fi echo "" echo "✅ Deployment $ENV_MODE complete." echo " Container : $CONTAINER_NAME" echo " Port : $PORT" +echo " Rollback : $0 $ENV_MODE --rollback" From c988a79d3b947393dc6ec359888a37546456eb2f Mon Sep 17 00:00:00 2001 From: efrilm Date: Wed, 30 Sep 2026 16:55:27 +0700 Subject: [PATCH 3/5] refactor(loyalty): remove what is left of tokens Tokens are EnakCoin and no app uses the token names any more, so their compatibility layer goes: - GET /customer/tokens and its handler, service, processor and response types. - total_tokens and tokens_history on GET /customer/wallet; last_updated now comes from the most recent row of either currency. - token_used and tokens_remaining on game and spin responses, and sort_by=token_used on the game play list. - TOKENS as a campaign type and reward type, with the mapping to COINS: migration 000092 already renamed the stored values. The customer_tokens table and its entity stay, as cmd/wallet-migrate still reads them, and LEGACY_TOKENS stays as the reference of the MIGRATION rows it wrote. The docs list the removed names and their replacements. Co-Authored-By: Claude Opus 5.5 --- docs/api-enakpoint.md | 7 +--- docs/integration-enakpoint.md | 19 +++++----- internal/constants/error.go | 1 - internal/contract/campaign_contract.go | 10 ++--- internal/contract/customer_points_contract.go | 22 ----------- internal/contract/game_play_contract.go | 16 +++----- internal/contract/spin_game_contract.go | 2 - internal/entities/campaign.go | 21 ----------- internal/entities/campaign_test.go | 18 --------- internal/handler/customer_points_handler.go | 34 ----------------- internal/handler/customer_wallet_db_test.go | 12 ++---- internal/mappers/campaign_mapper.go | 8 ++-- internal/mappers/spin_game_mapper.go | 8 ++-- internal/models/campaign.go | 10 ++--- internal/models/customer_points.go | 22 ----------- internal/models/game_play.go | 2 +- internal/processor/campaign_processor.go | 8 ++-- .../processor/customer_points_processor.go | 18 +-------- internal/processor/game_play_processor.go | 4 -- internal/processor/wallet_query_processor.go | 37 +------------------ .../processor/wallet_query_processor_test.go | 7 ---- internal/router/router.go | 1 - internal/service/campaign_service.go | 10 ++--- internal/service/customer_points_service.go | 14 ------- .../transformer/gamification_transformer.go | 8 ++-- internal/validator/campaign_validator.go | 6 +-- 26 files changed, 57 insertions(+), 268 deletions(-) delete mode 100644 internal/entities/campaign_test.go diff --git a/docs/api-enakpoint.md b/docs/api-enakpoint.md index 8bd3837..1aeb01b 100644 --- a/docs/api-enakpoint.md +++ b/docs/api-enakpoint.md @@ -426,14 +426,11 @@ Semua nilai `data` berupa string. Push hanya sampai ke device yang terdaftar lew ### Endpoint dan field deprecated -Masih jalan dan membaca wallet, tapi akan dihapus setelah semua versi aplikasi pindah. +Masih jalan dan membaca wallet, tapi akan dihapus setelah semua versi aplikasi pindah. Semua yang bernama token (`/customer/tokens`, `total_tokens`, `tokens_history`, `token_used`, `tokens_remaining`, campaign `TOKENS`) sudah dihapus; pakai `coin_balance`, `coins_used`, `coins_remaining`, dan `COINS`. | Lama | Pengganti | | --- | --- | | `GET /customer/points` | `GET /customer/wallet` → `point_balance` | -| `GET /customer/tokens` | `GET /customer/wallet` → `coin_balance` | -| `total_points`, `total_tokens`, `points_history`, `tokens_history`, `last_updated` di `/customer/wallet` | `point_balance`, `coin_balance`, `recent_transactions` | -| `token_used`, `tokens_remaining` di response game | `coins_used`, `coins_remaining` | -| `sort_by=token_used` di daftar game play | `sort_by=coins_used` | +| `total_points`, `points_history`, `last_updated` di `/customer/wallet` | `point_balance`, `recent_transactions` | Panduan alur lengkap per tim ada di [`integration-enakpoint.md`](./integration-enakpoint.md). diff --git a/docs/integration-enakpoint.md b/docs/integration-enakpoint.md index 1b5e816..58b459a 100644 --- a/docs/integration-enakpoint.md +++ b/docs/integration-enakpoint.md @@ -474,16 +474,14 @@ Response: ```json { - "game_play": { "id": "…", "game_id": "…", "coins_used": 1, "token_used": 1, "created_at": "…" }, + "game_play": { "id": "…", "game_id": "…", "coins_used": 1, "created_at": "…" }, "prize_won": { "id": "…", "name": "Voucher 10rb", … }, - "coins_remaining": 7, - "tokens_remaining": 7 + "coins_remaining": 7 } ``` EnakCoin kurang, game nonaktif, atau hadiah baru saja habis dijawab `304`; tidak ada -EnakCoin yang terpotong. Baca `coins_used` dan `coins_remaining`; `token_used` dan -`tokens_remaining` hanya salinan untuk versi aplikasi lama. +EnakCoin yang terpotong. Di dashboard, `metadata.coin_cost` diisi per game dengan bilangan bulat ≥ 1. @@ -497,13 +495,14 @@ pindah. Aplikasi baru jangan memakainya. | Lama | Ganti dengan | |---|---| | `GET /customer/points` | `GET /customer/wallet` (`point_balance`) | -| `GET /customer/tokens` | `GET /customer/wallet` (`coin_balance`) | -| `total_points`, `total_tokens`, `points_history`, `tokens_history`, `last_updated` di `/customer/wallet` | `point_balance`, `coin_balance`, `recent_transactions` | -| `token_used`, `tokens_remaining` di respons game | `coins_used`, `coins_remaining` | -| `sort_by=token_used` di daftar game play | `sort_by=coins_used` | +| `total_points`, `points_history`, `last_updated` di `/customer/wallet` | `point_balance`, `recent_transactions` | Beri tahu tim backend setelah aplikasi yang beredar tidak lagi memakai kolom kiri, -supaya alias dan tabel lama (`customer_points`, `customer_tokens`) bisa dihapus. +supaya alias ini bisa dihapus. + +Semua yang bernama token sudah dihapus: `GET /customer/tokens`, `total_tokens`, +`tokens_history`, `token_used`, `tokens_remaining`, dan nilai `TOKENS` di campaign. Pakai +`coin_balance`, `coins_used`, `coins_remaining`, dan `COINS`. --- diff --git a/internal/constants/error.go b/internal/constants/error.go index d0967fc..e0ed8a6 100644 --- a/internal/constants/error.go +++ b/internal/constants/error.go @@ -52,7 +52,6 @@ const ( TableEntity = "table" // Gamification entities CustomerPointsEntity = "customer_points" - CustomerTokensEntity = "customer_tokens" TierEntity = "tier" GameEntity = "game" GamePrizeEntity = "game_prize" diff --git a/internal/contract/campaign_contract.go b/internal/contract/campaign_contract.go index f19d4a2..a62c078 100644 --- a/internal/contract/campaign_contract.go +++ b/internal/contract/campaign_contract.go @@ -12,7 +12,7 @@ import ( type CreateCampaignRequest struct { Name string `json:"name" binding:"required,min=1,max=150"` Description *string `json:"description,omitempty"` - Type string `json:"type" binding:"required,oneof=REWARD POINTS COINS TOKENS MIXED"` + Type string `json:"type" binding:"required,oneof=REWARD POINTS COINS MIXED"` StartDate time.Time `json:"start_date" binding:"required"` EndDate time.Time `json:"end_date" binding:"required"` IsActive bool `json:"is_active"` @@ -25,7 +25,7 @@ type UpdateCampaignRequest struct { ID uuid.UUID `json:"id" binding:"required"` Name string `json:"name" binding:"required,min=1,max=150"` Description *string `json:"description,omitempty"` - Type string `json:"type" binding:"required,oneof=REWARD POINTS COINS TOKENS MIXED"` + Type string `json:"type" binding:"required,oneof=REWARD POINTS COINS MIXED"` StartDate time.Time `json:"start_date" binding:"required"` EndDate time.Time `json:"end_date" binding:"required"` IsActive bool `json:"is_active"` @@ -58,7 +58,7 @@ type CreateCampaignRuleRequest struct { CampaignID uuid.UUID `json:"campaign_id" binding:"required"` RuleType string `json:"rule_type" binding:"required,oneof=TIER SPEND PRODUCT CATEGORY DAY LOCATION"` ConditionValue *string `json:"condition_value,omitempty"` - RewardType string `json:"reward_type" binding:"required,oneof=POINTS COINS TOKENS REWARD"` + RewardType string `json:"reward_type" binding:"required,oneof=POINTS COINS REWARD"` RewardValue *int64 `json:"reward_value,omitempty"` RewardSubtype *string `json:"reward_subtype,omitempty"` RewardRefID *uuid.UUID `json:"reward_ref_id,omitempty"` @@ -70,7 +70,7 @@ type UpdateCampaignRuleRequest struct { CampaignID uuid.UUID `json:"campaign_id" binding:"required"` RuleType string `json:"rule_type" binding:"required,oneof=TIER SPEND PRODUCT CATEGORY DAY LOCATION"` ConditionValue *string `json:"condition_value,omitempty"` - RewardType string `json:"reward_type" binding:"required,oneof=POINTS COINS TOKENS REWARD"` + RewardType string `json:"reward_type" binding:"required,oneof=POINTS COINS REWARD"` RewardValue *int64 `json:"reward_value,omitempty"` RewardSubtype *string `json:"reward_subtype,omitempty"` RewardRefID *uuid.UUID `json:"reward_ref_id,omitempty"` @@ -142,7 +142,7 @@ type ListCampaignRulesResponse struct { type CampaignRuleStruct struct { RuleType string `json:"rule_type" binding:"required,oneof=TIER SPEND PRODUCT CATEGORY DAY LOCATION"` ConditionValue *string `json:"condition_value,omitempty"` - RewardType string `json:"reward_type" binding:"required,oneof=POINTS COINS TOKENS REWARD"` + RewardType string `json:"reward_type" binding:"required,oneof=POINTS COINS REWARD"` RewardValue *int64 `json:"reward_value,omitempty"` RewardSubtype *string `json:"reward_subtype,omitempty"` RewardRefID *uuid.UUID `json:"reward_ref_id,omitempty"` diff --git a/internal/contract/customer_points_contract.go b/internal/contract/customer_points_contract.go index 591758c..29d4b12 100644 --- a/internal/contract/customer_points_contract.go +++ b/internal/contract/customer_points_contract.go @@ -25,26 +25,6 @@ type PointsHistoryItem struct { CreatedAt time.Time `json:"created_at"` } -type GetCustomerTokensResponse struct { - Status string `json:"status"` - Message string `json:"message"` - Data *GetCustomerTokensResponseData `json:"data,omitempty"` -} - -type GetCustomerTokensResponseData struct { - TotalTokens int64 `json:"total_tokens"` - TokensHistory []TokensHistoryItem `json:"tokens_history,omitempty"` - LastUpdated time.Time `json:"last_updated"` -} - -type TokensHistoryItem struct { - ID string `json:"id"` - Tokens int64 `json:"tokens"` - Type string `json:"type"` // EARNED, REDEEMED, EXPIRED - Description string `json:"description"` - CreatedAt time.Time `json:"created_at"` -} - type GetCustomerWalletResponse struct { Status string `json:"status"` Message string `json:"message"` @@ -53,8 +33,6 @@ type GetCustomerWalletResponse struct { type GetCustomerWalletResponseData struct { TotalPoints int64 `json:"total_points"` - TotalTokens int64 `json:"total_tokens"` PointsHistory []PointsHistoryItem `json:"points_history,omitempty"` - TokensHistory []TokensHistoryItem `json:"tokens_history,omitempty"` LastUpdated time.Time `json:"last_updated"` } diff --git a/internal/contract/game_play_contract.go b/internal/contract/game_play_contract.go index b32ad4f..a7454e9 100644 --- a/internal/contract/game_play_contract.go +++ b/internal/contract/game_play_contract.go @@ -14,13 +14,11 @@ type CreateGamePlayRequest struct { } type GamePlayResponse struct { - ID uuid.UUID `json:"id"` - GameID uuid.UUID `json:"game_id"` - CustomerID uuid.UUID `json:"customer_id"` - PrizeID *uuid.UUID `json:"prize_id,omitempty"` - CoinsUsed int `json:"coins_used"` - // Deprecated: the same as CoinsUsed, kept until the apps read coins_used. - TokenUsed int `json:"token_used"` + ID uuid.UUID `json:"id"` + GameID uuid.UUID `json:"game_id"` + CustomerID uuid.UUID `json:"customer_id"` + PrizeID *uuid.UUID `json:"prize_id,omitempty"` + CoinsUsed int `json:"coins_used"` RandomSeed *string `json:"random_seed,omitempty"` CreatedAt time.Time `json:"created_at"` Game *GameResponse `json:"game,omitempty"` @@ -35,7 +33,7 @@ type ListGamePlaysRequest struct { GameID *uuid.UUID `json:"game_id"` CustomerID *uuid.UUID `json:"customer_id"` PrizeID *uuid.UUID `json:"prize_id"` - SortBy string `json:"sort_by" validate:"omitempty,oneof=created_at coins_used token_used"` + SortBy string `json:"sort_by" validate:"omitempty,oneof=created_at coins_used"` SortOrder string `json:"sort_order" validate:"omitempty,oneof=asc desc"` } @@ -58,6 +56,4 @@ type PlayGameResponse struct { GamePlay GamePlayResponse `json:"game_play"` PrizeWon *GamePrizeResponse `json:"prize_won,omitempty"` CoinsRemaining int64 `json:"coins_remaining"` - // Deprecated: the same as CoinsRemaining, kept until the apps read coins_remaining. - TokensRemaining int64 `json:"tokens_remaining"` } diff --git a/internal/contract/spin_game_contract.go b/internal/contract/spin_game_contract.go index 67b50b7..b234f2b 100644 --- a/internal/contract/spin_game_contract.go +++ b/internal/contract/spin_game_contract.go @@ -17,6 +17,4 @@ type SpinGameResponseData struct { GamePlay GamePlayResponse `json:"game_play"` PrizeWon *CustomerGamePrizeResponse `json:"prize_won,omitempty"` CoinsRemaining int64 `json:"coins_remaining"` - // Deprecated: the same as CoinsRemaining, kept until the apps read coins_remaining. - TokensRemaining int64 `json:"tokens_remaining"` } diff --git a/internal/entities/campaign.go b/internal/entities/campaign.go index 5eabd76..1e5aac0 100644 --- a/internal/entities/campaign.go +++ b/internal/entities/campaign.go @@ -16,27 +16,6 @@ const ( CampaignTypeMixed CampaignType = "MIXED" ) -// legacyCampaignTokens is what COINS was called before tokens became EnakCoin -// (docs/prd-point-coin.md §10). Requests may still send it; it is stored as COINS. -const legacyCampaignTokens = "TOKENS" - -// NormalizeCampaignType maps the legacy TOKENS to COINS and leaves anything else as is. -func NormalizeCampaignType(t string) CampaignType { - if t == legacyCampaignTokens { - return CampaignTypeCoins - } - return CampaignType(t) -} - -// NormalizeCampaignRewardType maps the legacy TOKENS to COINS and leaves anything -// else as is. -func NormalizeCampaignRewardType(t string) CampaignRewardType { - if t == legacyCampaignTokens { - return CampaignRewardTypeCoins - } - return CampaignRewardType(t) -} - type RuleType string const ( diff --git a/internal/entities/campaign_test.go b/internal/entities/campaign_test.go deleted file mode 100644 index 5dd1cd0..0000000 --- a/internal/entities/campaign_test.go +++ /dev/null @@ -1,18 +0,0 @@ -package entities - -import ( - "testing" - - "github.com/stretchr/testify/assert" -) - -func TestNormalizeCampaignTypesMapsLegacyTokensToCoins(t *testing.T) { - assert.Equal(t, CampaignTypeCoins, NormalizeCampaignType("TOKENS")) - assert.Equal(t, CampaignTypeCoins, NormalizeCampaignType("COINS")) - assert.Equal(t, CampaignTypePoints, NormalizeCampaignType("POINTS")) - assert.Equal(t, CampaignType(""), NormalizeCampaignType(""), "an empty filter stays empty") - - assert.Equal(t, CampaignRewardTypeCoins, NormalizeCampaignRewardType("TOKENS")) - assert.Equal(t, CampaignRewardTypeReward, NormalizeCampaignRewardType("REWARD")) - assert.Equal(t, CampaignRewardType(""), NormalizeCampaignRewardType("")) -} diff --git a/internal/handler/customer_points_handler.go b/internal/handler/customer_points_handler.go index 0df8ff2..8875d79 100644 --- a/internal/handler/customer_points_handler.go +++ b/internal/handler/customer_points_handler.go @@ -59,40 +59,6 @@ func (h *CustomerPointsHandler) GetCustomerPoints(c *gin.Context) { util.HandleResponse(c.Writer, c.Request, contract.BuildSuccessResponse(response), "CustomerPointsHandler::GetCustomerPoints") } -func (h *CustomerPointsHandler) GetCustomerTokens(c *gin.Context) { - ctx := c.Request.Context() - - // Get customer ID from context (set by middleware) - customerID, exists := c.Get("customer_id") - if !exists { - logger.FromContext(ctx).Error("Customer ID not found in context") - util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{ - contract.NewResponseError(constants.ValidationErrorCode, constants.AuthHandlerEntity, "Customer ID not found"), - }), "CustomerPointsHandler::GetCustomerTokens") - return - } - - customerIDStr, ok := customerID.(string) - if !ok { - logger.FromContext(ctx).Error("Invalid customer ID type in context") - util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{ - contract.NewResponseError(constants.ValidationErrorCode, constants.AuthHandlerEntity, "Invalid customer ID"), - }), "CustomerPointsHandler::GetCustomerTokens") - return - } - - response, err := h.customerPointsService.GetCustomerTokens(ctx, customerIDStr) - if err != nil { - logger.FromContext(ctx).WithError(err).Error("CustomerPointsHandler::GetCustomerTokens -> service call failed") - util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{ - contract.NewResponseError(walletErrorCode(err), constants.RequestEntity, err.Error()), - }), "CustomerPointsHandler::GetCustomerTokens") - return - } - - util.HandleResponse(c.Writer, c.Request, contract.BuildSuccessResponse(response), "CustomerPointsHandler::GetCustomerTokens") -} - func (h *CustomerPointsHandler) GetCustomerWallet(c *gin.Context) { ctx := c.Request.Context() diff --git a/internal/handler/customer_wallet_db_test.go b/internal/handler/customer_wallet_db_test.go index d9e2467..6cc88d6 100644 --- a/internal/handler/customer_wallet_db_test.go +++ b/internal/handler/customer_wallet_db_test.go @@ -25,7 +25,7 @@ import ( ) // Drives the customer wallet endpoints over HTTP down to Postgres, to show the app -// gets the right numbers from the new endpoints and from the old /points, /tokens +// gets the right numbers from the new endpoints and from the old /points // and /wallet shapes. Needs TEST_DATABASE_URL pointing at a migrated database; see // internal/repository/wallet_repository_test.go. func TestCustomerWalletEndpoints_AgainstPostgres(t *testing.T) { @@ -111,7 +111,6 @@ func TestCustomerWalletEndpoints_AgainstPostgres(t *testing.T) { }{{"/a", customer}, {"/b", other}, {"/gone", uuid.New()}} { g := router.Group(who.prefix, as(who.id)) g.GET("/points", h.GetCustomerPoints) - g.GET("/tokens", h.GetCustomerTokens) g.GET("/wallet", h.GetCustomerWallet) g.GET("/wallet/transactions", h.GetCustomerWalletTransactions) } @@ -128,16 +127,12 @@ func TestCustomerWalletEndpoints_AgainstPostgres(t *testing.T) { return body["data"].(map[string]any)["data"].(map[string]any) } - // Old app: /points and /tokens keep their shape and show the spendable balance. + // Old app: /points keeps its shape and shows the spendable balance. status, body := get("/a/points") require.Equal(t, http.StatusOK, status, body) assert.EqualValues(t, 250, inner(body)["total_points"], "300 - 50; the expired 20 is not spendable") assert.Len(t, inner(body)["points_history"], 3) - status, body = get("/a/tokens") - require.Equal(t, http.StatusOK, status, body) - assert.EqualValues(t, 8, inner(body)["total_tokens"]) - // /wallet: new fields, with the old ones still there. status, body = get("/a/wallet") require.Equal(t, http.StatusOK, status, body) @@ -151,9 +146,10 @@ func TestCustomerWalletEndpoints_AgainstPostgres(t *testing.T) { assert.Equal(t, map[string]any{"amount": float64(250), "date": time.Date(next, 7, 2, 0, 0, 0, 0, time.UTC).Format("2006-01-02")}, nearest["point"], "both lots fall on 2 July in Jakarta although they are on different UTC days") assert.Nil(t, nearest["coin"]) - for _, legacy := range []string{"total_points", "total_tokens", "points_history", "tokens_history", "last_updated"} { + for _, legacy := range []string{"total_points", "points_history", "last_updated"} { assert.Contains(t, w, legacy) } + assert.NotContains(t, w, "total_tokens", "tokens are gone; EnakCoin is coin_balance") assert.EqualValues(t, 250, w["total_points"]) recent := w["recent_transactions"].([]any) diff --git a/internal/mappers/campaign_mapper.go b/internal/mappers/campaign_mapper.go index ffd2940..f662108 100644 --- a/internal/mappers/campaign_mapper.go +++ b/internal/mappers/campaign_mapper.go @@ -71,7 +71,7 @@ func ToCampaignEntity(request *contract.CreateCampaignRequest) *entities.Campaig return &entities.Campaign{ Name: request.Name, Description: request.Description, - Type: entities.NormalizeCampaignType(request.Type), + Type: entities.CampaignType(request.Type), StartDate: request.StartDate, EndDate: request.EndDate, IsActive: request.IsActive, @@ -91,7 +91,7 @@ func ToCampaignEntityFromUpdate(request *contract.UpdateCampaignRequest) *entiti ID: request.ID, Name: request.Name, Description: request.Description, - Type: entities.NormalizeCampaignType(request.Type), + Type: entities.CampaignType(request.Type), StartDate: request.StartDate, EndDate: request.EndDate, IsActive: request.IsActive, @@ -118,7 +118,7 @@ func ToCampaignRuleEntity(request *contract.CampaignRuleStruct, campaignID uuid. CampaignID: campaignID, RuleType: entities.RuleType(request.RuleType), ConditionValue: request.ConditionValue, - RewardType: entities.NormalizeCampaignRewardType(request.RewardType), + RewardType: entities.CampaignRewardType(request.RewardType), RewardValue: request.RewardValue, RewardSubtype: rewardSubtype, RewardRefID: request.RewardRefID, @@ -142,7 +142,7 @@ func ToCampaignRuleEntityFromUpdate(request *contract.CampaignRuleStruct, campai CampaignID: campaignID, RuleType: entities.RuleType(request.RuleType), ConditionValue: request.ConditionValue, - RewardType: entities.NormalizeCampaignRewardType(request.RewardType), + RewardType: entities.CampaignRewardType(request.RewardType), RewardValue: request.RewardValue, RewardSubtype: rewardSubtype, RewardRefID: request.RewardRefID, diff --git a/internal/mappers/spin_game_mapper.go b/internal/mappers/spin_game_mapper.go index dd4b184..b38be64 100644 --- a/internal/mappers/spin_game_mapper.go +++ b/internal/mappers/spin_game_mapper.go @@ -36,10 +36,9 @@ func SpinGameResponseDataModelToContract(data *models.SpinGameResponseData) *con } return &contract.SpinGameResponseData{ - GamePlay: GamePlayResponseModelToContract(&data.GamePlay), - PrizeWon: CustomerGamePrizeResponseModelToContract(data.PrizeWon), - CoinsRemaining: data.CoinsRemaining, - TokensRemaining: data.CoinsRemaining, + GamePlay: GamePlayResponseModelToContract(&data.GamePlay), + PrizeWon: CustomerGamePrizeResponseModelToContract(data.PrizeWon), + CoinsRemaining: data.CoinsRemaining, } } @@ -55,7 +54,6 @@ func GamePlayResponseModelToContract(resp *models.GamePlayResponse) contract.Gam CustomerID: resp.CustomerID, PrizeID: resp.PrizeID, CoinsUsed: resp.CoinsUsed, - TokenUsed: resp.CoinsUsed, RandomSeed: resp.RandomSeed, CreatedAt: resp.CreatedAt, Game: nil, // Optional field - can be populated separately if needed diff --git a/internal/models/campaign.go b/internal/models/campaign.go index 9720694..2b14007 100644 --- a/internal/models/campaign.go +++ b/internal/models/campaign.go @@ -11,7 +11,7 @@ import ( type CreateCampaignRequest struct { Name string `json:"name" binding:"required,min=1,max=150"` Description *string `json:"description,omitempty"` - Type string `json:"type" binding:"required,oneof=REWARD POINTS COINS TOKENS MIXED"` + Type string `json:"type" binding:"required,oneof=REWARD POINTS COINS MIXED"` StartDate time.Time `json:"start_date" binding:"required"` EndDate time.Time `json:"end_date" binding:"required"` IsActive bool `json:"is_active"` @@ -25,7 +25,7 @@ type UpdateCampaignRequest struct { ID uuid.UUID `json:"id" binding:"required"` Name string `json:"name" binding:"required,min=1,max=150"` Description *string `json:"description,omitempty"` - Type string `json:"type" binding:"required,oneof=REWARD POINTS COINS TOKENS MIXED"` + Type string `json:"type" binding:"required,oneof=REWARD POINTS COINS MIXED"` StartDate time.Time `json:"start_date" binding:"required"` EndDate time.Time `json:"end_date" binding:"required"` IsActive bool `json:"is_active"` @@ -88,7 +88,7 @@ type CreateCampaignRuleRequest struct { CampaignID uuid.UUID `json:"campaign_id" binding:"required"` RuleType string `json:"rule_type" binding:"required,oneof=TIER SPEND PRODUCT CATEGORY DAY LOCATION"` ConditionValue *string `json:"condition_value,omitempty"` - RewardType string `json:"reward_type" binding:"required,oneof=POINTS COINS TOKENS REWARD"` + RewardType string `json:"reward_type" binding:"required,oneof=POINTS COINS REWARD"` RewardValue *int64 `json:"reward_value,omitempty"` RewardSubtype *string `json:"reward_subtype,omitempty"` RewardRefID *uuid.UUID `json:"reward_ref_id,omitempty"` @@ -100,7 +100,7 @@ type UpdateCampaignRuleRequest struct { CampaignID uuid.UUID `json:"campaign_id" binding:"required"` RuleType string `json:"rule_type" binding:"required,oneof=TIER SPEND PRODUCT CATEGORY DAY LOCATION"` ConditionValue *string `json:"condition_value,omitempty"` - RewardType string `json:"reward_type" binding:"required,oneof=POINTS COINS TOKENS REWARD"` + RewardType string `json:"reward_type" binding:"required,oneof=POINTS COINS REWARD"` RewardValue *int64 `json:"reward_value,omitempty"` RewardSubtype *string `json:"reward_subtype,omitempty"` RewardRefID *uuid.UUID `json:"reward_ref_id,omitempty"` @@ -126,7 +126,7 @@ type ListCampaignRulesResponse struct { type CampaignRuleStruct struct { RuleType string `json:"rule_type" binding:"required,oneof=TIER SPEND PRODUCT CATEGORY DAY LOCATION"` ConditionValue *string `json:"condition_value,omitempty"` - RewardType string `json:"reward_type" binding:"required,oneof=POINTS COINS TOKENS REWARD"` + RewardType string `json:"reward_type" binding:"required,oneof=POINTS COINS REWARD"` RewardValue *int64 `json:"reward_value,omitempty"` RewardSubtype *string `json:"reward_subtype,omitempty"` RewardRefID *uuid.UUID `json:"reward_ref_id,omitempty"` diff --git a/internal/models/customer_points.go b/internal/models/customer_points.go index 9e1c84f..75e7916 100644 --- a/internal/models/customer_points.go +++ b/internal/models/customer_points.go @@ -25,26 +25,6 @@ type PointsHistoryItem struct { CreatedAt time.Time `json:"created_at"` } -type GetCustomerTokensResponse struct { - Status string `json:"status"` - Message string `json:"message"` - Data *GetCustomerTokensResponseData `json:"data,omitempty"` -} - -type GetCustomerTokensResponseData struct { - TotalTokens int64 `json:"total_tokens"` - TokensHistory []TokensHistoryItem `json:"tokens_history,omitempty"` - LastUpdated time.Time `json:"last_updated"` -} - -type TokensHistoryItem struct { - ID string `json:"id"` - Tokens int64 `json:"tokens"` - Type string `json:"type"` // EARNED, REDEEMED, EXPIRED - Description string `json:"description"` - CreatedAt time.Time `json:"created_at"` -} - type GetCustomerWalletResponse struct { Status string `json:"status"` Message string `json:"message"` @@ -66,8 +46,6 @@ type GetCustomerWalletResponseData struct { // Deprecated: the shape of this endpoint before the wallet, kept for app versions // that still read it. Filled from the wallet like the fields above. TotalPoints int64 `json:"total_points"` - TotalTokens int64 `json:"total_tokens"` PointsHistory []PointsHistoryItem `json:"points_history,omitempty"` - TokensHistory []TokensHistoryItem `json:"tokens_history,omitempty"` LastUpdated time.Time `json:"last_updated"` } diff --git a/internal/models/game_play.go b/internal/models/game_play.go index f2378b3..db62ce3 100644 --- a/internal/models/game_play.go +++ b/internal/models/game_play.go @@ -33,7 +33,7 @@ type ListGamePlaysQuery struct { GameID *uuid.UUID `query:"game_id"` CustomerID *uuid.UUID `query:"customer_id"` PrizeID *uuid.UUID `query:"prize_id"` - SortBy string `query:"sort_by" validate:"omitempty,oneof=created_at coins_used token_used"` + SortBy string `query:"sort_by" validate:"omitempty,oneof=created_at coins_used"` SortOrder string `query:"sort_order" validate:"omitempty,oneof=asc desc"` } diff --git a/internal/processor/campaign_processor.go b/internal/processor/campaign_processor.go index 57f2c8f..2823a26 100644 --- a/internal/processor/campaign_processor.go +++ b/internal/processor/campaign_processor.go @@ -70,7 +70,7 @@ func (p *campaignProcessor) ListCampaigns(ctx context.Context, req *contract.Lis Page: req.Page, Limit: req.Limit, Search: req.Search, - Type: string(entities.NormalizeCampaignType(req.Type)), + Type: req.Type, IsActive: req.IsActive, ShowOnApp: req.ShowOnApp, StartDate: req.StartDate, @@ -178,7 +178,7 @@ func (p *campaignRuleProcessor) CreateCampaignRule(ctx context.Context, req *con CampaignID: req.CampaignID, RuleType: entities.RuleType(req.RuleType), ConditionValue: req.ConditionValue, - RewardType: entities.NormalizeCampaignRewardType(req.RewardType), + RewardType: entities.CampaignRewardType(req.RewardType), RewardValue: req.RewardValue, RewardSubtype: (*entities.RewardSubtype)(req.RewardSubtype), RewardRefID: req.RewardRefID, @@ -218,7 +218,7 @@ func (p *campaignRuleProcessor) ListCampaignRules(ctx context.Context, req *cont Limit: req.Limit, CampaignID: req.CampaignID, RuleType: req.RuleType, - RewardType: string(entities.NormalizeCampaignRewardType(req.RewardType)), + RewardType: req.RewardType, } // Get from repository @@ -247,7 +247,7 @@ func (p *campaignRuleProcessor) UpdateCampaignRule(ctx context.Context, req *con CampaignID: req.CampaignID, RuleType: entities.RuleType(req.RuleType), ConditionValue: req.ConditionValue, - RewardType: entities.NormalizeCampaignRewardType(req.RewardType), + RewardType: entities.CampaignRewardType(req.RewardType), RewardValue: req.RewardValue, RewardSubtype: (*entities.RewardSubtype)(req.RewardSubtype), RewardRefID: req.RewardRefID, diff --git a/internal/processor/customer_points_processor.go b/internal/processor/customer_points_processor.go index a5a96aa..6e6095e 100644 --- a/internal/processor/customer_points_processor.go +++ b/internal/processor/customer_points_processor.go @@ -22,7 +22,7 @@ func NewCustomerPointsProcessor(walletQuery *WalletQueryProcessor, gameRepo *rep } } -// The three endpoints below are the customer app's balance screens. They read the +// The endpoints below are the customer app's balance screens. They read the // EnakPoint & EnakCoin wallet; customer_points and customer_tokens are no longer used // for balances (docs/prd-point-coin.md §9). @@ -42,22 +42,6 @@ func (p *CustomerPointsProcessor) GetCustomerTotalPointsAPI(ctx context.Context, }, nil } -func (p *CustomerPointsProcessor) GetCustomerTotalTokensAPI(ctx context.Context, customerID string) (*models.GetCustomerTokensResponse, error) { - id, err := parseWalletCustomerID(customerID) - if err != nil { - return nil, err - } - data, err := p.walletQuery.LegacyTokens(ctx, id) - if err != nil { - return nil, fmt.Errorf("failed to get customer tokens: %w", err) - } - return &models.GetCustomerTokensResponse{ - Status: "SUCCESS", - Message: "Customer tokens retrieved successfully.", - Data: data, - }, nil -} - func (p *CustomerPointsProcessor) GetCustomerWalletAPI(ctx context.Context, customerID string) (*models.GetCustomerWalletResponse, error) { id, err := parseWalletCustomerID(customerID) if err != nil { diff --git a/internal/processor/game_play_processor.go b/internal/processor/game_play_processor.go index 15e3337..e6fef4f 100644 --- a/internal/processor/game_play_processor.go +++ b/internal/processor/game_play_processor.go @@ -99,10 +99,6 @@ func (p *GamePlayProcessor) ListGamePlays(ctx context.Context, query *models.Lis } offset := (query.Page - 1) * query.Limit - // The column was renamed; the old name still sorts the same way. - if query.SortBy == "token_used" { - query.SortBy = "coins_used" - } // Get game plays from repository gamePlays, total, err := p.gamePlayRepo.List( diff --git a/internal/processor/wallet_query_processor.go b/internal/processor/wallet_query_processor.go index 3a83fb6..7812191 100644 --- a/internal/processor/wallet_query_processor.go +++ b/internal/processor/wallet_query_processor.go @@ -82,10 +82,6 @@ func (p *WalletQueryProcessor) Summary(ctx context.Context, customerID uuid.UUID if err != nil { return nil, err } - tokens, err := p.legacyTokens(ctx, customerID, balances) - if err != nil { - return nil, err - } data := &models.GetCustomerWalletResponseData{ PointBalance: balances[constants.WalletCurrencyPoint], @@ -94,13 +90,10 @@ func (p *WalletQueryProcessor) Summary(ctx context.Context, customerID uuid.UUID PointDiscountValue: balances[constants.WalletCurrencyPoint] * pointValue, RecentTransactions: recent, TotalPoints: points.TotalPoints, - TotalTokens: tokens.TotalTokens, PointsHistory: points.PointsHistory, - TokensHistory: tokens.TokensHistory, - LastUpdated: points.LastUpdated, } - if tokens.LastUpdated.After(data.LastUpdated) { - data.LastUpdated = tokens.LastUpdated + if len(recent) > 0 { + data.LastUpdated = recent[0].CreatedAt } for _, e := range expiring { entry := &models.CustomerWalletExpiring{Amount: e.Amount, Date: e.Date} @@ -161,32 +154,6 @@ func (p *WalletQueryProcessor) legacyPoints(ctx context.Context, customerID uuid return data, nil } -// LegacyTokens is the pre-wallet GET /customer/tokens. Tokens are EnakCoin now. -func (p *WalletQueryProcessor) LegacyTokens(ctx context.Context, customerID uuid.UUID) (*models.GetCustomerTokensResponseData, error) { - balances, err := p.repo.SpendableBalances(ctx, customerID, p.now()) - if err != nil { - return nil, err - } - return p.legacyTokens(ctx, customerID, balances) -} - -func (p *WalletQueryProcessor) legacyTokens(ctx context.Context, customerID uuid.UUID, balances map[string]int64) (*models.GetCustomerTokensResponseData, error) { - recent, err := p.recent(ctx, customerID, constants.WalletCurrencyCoin, walletLegacyHistorySize) - if err != nil { - return nil, err - } - data := &models.GetCustomerTokensResponseData{TotalTokens: balances[constants.WalletCurrencyCoin]} - for _, tx := range recent { - data.TokensHistory = append(data.TokensHistory, models.TokensHistoryItem{ - ID: tx.ID.String(), Tokens: tx.Amount, Type: tx.Type, Description: tx.Description, CreatedAt: tx.CreatedAt, - }) - } - if len(recent) > 0 { - data.LastUpdated = recent[0].CreatedAt - } - return data, nil -} - func (p *WalletQueryProcessor) recent(ctx context.Context, customerID uuid.UUID, currency string, limit int) ([]models.CustomerWalletTransaction, error) { rows, _, err := p.repo.ListTransactions(ctx, repository.WalletTransactionFilter{ CustomerID: customerID, Currency: currency, Limit: limit, diff --git a/internal/processor/wallet_query_processor_test.go b/internal/processor/wallet_query_processor_test.go index bf6def7..bc24cf2 100644 --- a/internal/processor/wallet_query_processor_test.go +++ b/internal/processor/wallet_query_processor_test.go @@ -122,7 +122,6 @@ func TestWalletQueryProcessor_SummaryShowsWhereEachRowCameFromOrWent(t *testing. // The pre-wallet fields are still filled, from the wallet. assert.Equal(t, int64(250), data.TotalPoints) - assert.Equal(t, int64(8), data.TotalTokens) require.Len(t, data.PointsHistory, 2) assert.Equal(t, int64(-50), data.PointsHistory[0].Points) assert.Equal(t, constants.WalletTxTypePayment, data.PointsHistory[0].Type) @@ -174,12 +173,6 @@ func TestWalletQueryProcessor_LegacyEndpointsSplitByCurrency(t *testing.T) { assert.Equal(t, int64(100), points.TotalPoints) require.Len(t, points.PointsHistory, 1) assert.Equal(t, int64(100), points.PointsHistory[0].Points) - - tokens, err := p.LegacyTokens(context.Background(), uuid.New()) - require.NoError(t, err) - assert.Equal(t, int64(8), tokens.TotalTokens) - require.Len(t, tokens.TokensHistory, 1) - assert.Equal(t, int64(8), tokens.TokensHistory[0].Tokens) } func TestWalletQueryProcessor_TransactionsQuery(t *testing.T) { diff --git a/internal/router/router.go b/internal/router/router.go index a06e26e..f72a8c5 100644 --- a/internal/router/router.go +++ b/internal/router/router.go @@ -169,7 +169,6 @@ func (r *Router) addAppRoutes(rg *gin.Engine) { customer.Use(r.customerAuthMiddleware.ValidateCustomerToken()) { customer.GET("/points", r.customerPointsHandler.GetCustomerPoints) - customer.GET("/tokens", r.customerPointsHandler.GetCustomerTokens) customer.GET("/wallet", r.customerPointsHandler.GetCustomerWallet) customer.GET("/wallet/transactions", r.customerPointsHandler.GetCustomerWalletTransactions) customer.GET("/wallet/expiring", r.customerPointsHandler.GetCustomerWalletExpiring) diff --git a/internal/service/campaign_service.go b/internal/service/campaign_service.go index bc42ba2..5e76fda 100644 --- a/internal/service/campaign_service.go +++ b/internal/service/campaign_service.go @@ -177,7 +177,7 @@ func (s *campaignService) CreateCampaignRule(ctx context.Context, req *contract. } // Validate reward value based on reward type - if req.RewardType == "POINTS" || req.RewardType == "COINS" || req.RewardType == "TOKENS" { + if req.RewardType == "POINTS" || req.RewardType == "COINS" { if req.RewardValue == nil || *req.RewardValue <= 0 { return nil, fmt.Errorf("reward value must be positive for %s type", req.RewardType) } @@ -247,7 +247,7 @@ func (s *campaignService) UpdateCampaignRule(ctx context.Context, req *contract. } // Validate reward value based on reward type - if req.RewardType == "POINTS" || req.RewardType == "COINS" || req.RewardType == "TOKENS" { + if req.RewardType == "POINTS" || req.RewardType == "COINS" { if req.RewardValue == nil || *req.RewardValue <= 0 { return nil, fmt.Errorf("reward value must be positive for %s type", req.RewardType) } @@ -295,7 +295,7 @@ func (s *campaignService) GetCampaignRulesByCampaignID(ctx context.Context, camp } func (s *campaignService) validateCampaignType(campaignType string) error { - validTypes := []string{"REWARD", "POINTS", "COINS", "TOKENS", "MIXED"} + validTypes := []string{"REWARD", "POINTS", "COINS", "MIXED"} for _, validType := range validTypes { if campaignType == validType { return nil @@ -335,7 +335,7 @@ func (s *campaignService) validateCampaignRules(rules []contract.CampaignRuleStr } // Validate reward value based on reward type - if rule.RewardType == "POINTS" || rule.RewardType == "COINS" || rule.RewardType == "TOKENS" { + if rule.RewardType == "POINTS" || rule.RewardType == "COINS" { if rule.RewardValue == nil || *rule.RewardValue <= 0 { return fmt.Errorf("reward value must be positive for %s type in rule %d", rule.RewardType, i+1) } @@ -365,7 +365,7 @@ func (s *campaignService) validateRuleType(ruleType string) error { } func (s *campaignService) validateRewardType(rewardType string) error { - validTypes := []string{"POINTS", "COINS", "TOKENS", "REWARD"} + validTypes := []string{"POINTS", "COINS", "REWARD"} for _, validType := range validTypes { if rewardType == validType { return nil diff --git a/internal/service/customer_points_service.go b/internal/service/customer_points_service.go index 6e85854..33c0728 100644 --- a/internal/service/customer_points_service.go +++ b/internal/service/customer_points_service.go @@ -10,7 +10,6 @@ import ( type CustomerPointsService interface { GetCustomerPoints(ctx context.Context, customerID string) (*models.GetCustomerPointsResponse, error) - GetCustomerTokens(ctx context.Context, customerID string) (*models.GetCustomerTokensResponse, error) GetCustomerWallet(ctx context.Context, customerID string) (*models.GetCustomerWalletResponse, error) GetCustomerWalletTransactions(ctx context.Context, customerID string, query models.ListCustomerWalletTransactionsQuery) (*models.PaginatedResponse[models.CustomerWalletTransaction], error) GetCustomerWalletExpiring(ctx context.Context, customerID string) (*models.CustomerWalletExpiringList, error) @@ -41,19 +40,6 @@ func (s *customerPointsService) GetCustomerPoints(ctx context.Context, customerI return response, nil } -func (s *customerPointsService) GetCustomerTokens(ctx context.Context, customerID string) (*models.GetCustomerTokensResponse, error) { - if customerID == "" { - return nil, fmt.Errorf("customer ID is required") - } - - response, err := s.customerPointsProcessor.GetCustomerTotalTokensAPI(ctx, customerID) - if err != nil { - return nil, fmt.Errorf("failed to get customer tokens: %w", err) - } - - return response, nil -} - func (s *customerPointsService) GetCustomerWallet(ctx context.Context, customerID string) (*models.GetCustomerWalletResponse, error) { if customerID == "" { return nil, fmt.Errorf("customer ID is required") diff --git a/internal/transformer/gamification_transformer.go b/internal/transformer/gamification_transformer.go index 0b66a63..8c17e3c 100644 --- a/internal/transformer/gamification_transformer.go +++ b/internal/transformer/gamification_transformer.go @@ -276,7 +276,6 @@ func GamePlayModelToResponse(model *models.GamePlayResponse) *contract.GamePlayR CustomerID: model.CustomerID, PrizeID: model.PrizeID, CoinsUsed: model.CoinsUsed, - TokenUsed: model.CoinsUsed, RandomSeed: model.RandomSeed, CreatedAt: model.CreatedAt, Game: game, @@ -306,10 +305,9 @@ func PlayGameModelToResponse(model *models.PlayGameResponse) *contract.PlayGameR } return &contract.PlayGameResponse{ - GamePlay: gamePlayValue, - PrizeWon: prizeWon, - CoinsRemaining: model.CoinsRemaining, - TokensRemaining: model.CoinsRemaining, + GamePlay: gamePlayValue, + PrizeWon: prizeWon, + CoinsRemaining: model.CoinsRemaining, } } diff --git a/internal/validator/campaign_validator.go b/internal/validator/campaign_validator.go index 8618fc8..fedcf77 100644 --- a/internal/validator/campaign_validator.go +++ b/internal/validator/campaign_validator.go @@ -254,7 +254,7 @@ func (v *CampaignValidatorImpl) ValidateDeleteCampaignRuleRequest(req *contract. } func (v *CampaignValidatorImpl) isValidCampaignType(campaignType string) bool { - validTypes := []string{"REWARD", "POINTS", "COINS", "TOKENS", "MIXED"} + validTypes := []string{"REWARD", "POINTS", "COINS", "MIXED"} return contains(validTypes, campaignType) } @@ -264,7 +264,7 @@ func (v *CampaignValidatorImpl) isValidRuleType(ruleType string) bool { } func (v *CampaignValidatorImpl) isValidRewardType(rewardType string) bool { - validTypes := []string{"POINTS", "COINS", "TOKENS", "REWARD"} + validTypes := []string{"POINTS", "COINS", "REWARD"} return contains(validTypes, rewardType) } @@ -297,7 +297,7 @@ func (v *CampaignValidatorImpl) validateCampaignRule(rule *contract.CampaignRule } // Validate reward value based on reward type - if rule.RewardType == "POINTS" || rule.RewardType == "COINS" || rule.RewardType == "TOKENS" { + if rule.RewardType == "POINTS" || rule.RewardType == "COINS" { if rule.RewardValue == nil || *rule.RewardValue <= 0 { return errors.New("reward value must be positive for " + rule.RewardType + " type in rule " + string(rune(ruleNumber))) } From 35fe5703fd9ef72ab717b0719adf17a8818b0675 Mon Sep 17 00:00:00 2001 From: efrilm Date: Wed, 30 Sep 2026 17:05:42 +0700 Subject: [PATCH 4/5] fix(loyalty): keep tokens removed after merging staging Merging staging brought back, through its own re-apply of #32, the TOKENS campaign mapping, its test and the token_used sort fallback that c988a79 had removed, because those hunks did not conflict. This restores the five files to c988a79. Co-Authored-By: Claude Opus 5.5 --- internal/entities/campaign.go | 21 --------------------- internal/entities/campaign_test.go | 18 ------------------ internal/mappers/campaign_mapper.go | 8 ++++---- internal/processor/campaign_processor.go | 8 ++++---- internal/processor/game_play_processor.go | 4 ---- 5 files changed, 8 insertions(+), 51 deletions(-) delete mode 100644 internal/entities/campaign_test.go diff --git a/internal/entities/campaign.go b/internal/entities/campaign.go index 5eabd76..1e5aac0 100644 --- a/internal/entities/campaign.go +++ b/internal/entities/campaign.go @@ -16,27 +16,6 @@ const ( CampaignTypeMixed CampaignType = "MIXED" ) -// legacyCampaignTokens is what COINS was called before tokens became EnakCoin -// (docs/prd-point-coin.md §10). Requests may still send it; it is stored as COINS. -const legacyCampaignTokens = "TOKENS" - -// NormalizeCampaignType maps the legacy TOKENS to COINS and leaves anything else as is. -func NormalizeCampaignType(t string) CampaignType { - if t == legacyCampaignTokens { - return CampaignTypeCoins - } - return CampaignType(t) -} - -// NormalizeCampaignRewardType maps the legacy TOKENS to COINS and leaves anything -// else as is. -func NormalizeCampaignRewardType(t string) CampaignRewardType { - if t == legacyCampaignTokens { - return CampaignRewardTypeCoins - } - return CampaignRewardType(t) -} - type RuleType string const ( diff --git a/internal/entities/campaign_test.go b/internal/entities/campaign_test.go deleted file mode 100644 index 5dd1cd0..0000000 --- a/internal/entities/campaign_test.go +++ /dev/null @@ -1,18 +0,0 @@ -package entities - -import ( - "testing" - - "github.com/stretchr/testify/assert" -) - -func TestNormalizeCampaignTypesMapsLegacyTokensToCoins(t *testing.T) { - assert.Equal(t, CampaignTypeCoins, NormalizeCampaignType("TOKENS")) - assert.Equal(t, CampaignTypeCoins, NormalizeCampaignType("COINS")) - assert.Equal(t, CampaignTypePoints, NormalizeCampaignType("POINTS")) - assert.Equal(t, CampaignType(""), NormalizeCampaignType(""), "an empty filter stays empty") - - assert.Equal(t, CampaignRewardTypeCoins, NormalizeCampaignRewardType("TOKENS")) - assert.Equal(t, CampaignRewardTypeReward, NormalizeCampaignRewardType("REWARD")) - assert.Equal(t, CampaignRewardType(""), NormalizeCampaignRewardType("")) -} diff --git a/internal/mappers/campaign_mapper.go b/internal/mappers/campaign_mapper.go index ffd2940..f662108 100644 --- a/internal/mappers/campaign_mapper.go +++ b/internal/mappers/campaign_mapper.go @@ -71,7 +71,7 @@ func ToCampaignEntity(request *contract.CreateCampaignRequest) *entities.Campaig return &entities.Campaign{ Name: request.Name, Description: request.Description, - Type: entities.NormalizeCampaignType(request.Type), + Type: entities.CampaignType(request.Type), StartDate: request.StartDate, EndDate: request.EndDate, IsActive: request.IsActive, @@ -91,7 +91,7 @@ func ToCampaignEntityFromUpdate(request *contract.UpdateCampaignRequest) *entiti ID: request.ID, Name: request.Name, Description: request.Description, - Type: entities.NormalizeCampaignType(request.Type), + Type: entities.CampaignType(request.Type), StartDate: request.StartDate, EndDate: request.EndDate, IsActive: request.IsActive, @@ -118,7 +118,7 @@ func ToCampaignRuleEntity(request *contract.CampaignRuleStruct, campaignID uuid. CampaignID: campaignID, RuleType: entities.RuleType(request.RuleType), ConditionValue: request.ConditionValue, - RewardType: entities.NormalizeCampaignRewardType(request.RewardType), + RewardType: entities.CampaignRewardType(request.RewardType), RewardValue: request.RewardValue, RewardSubtype: rewardSubtype, RewardRefID: request.RewardRefID, @@ -142,7 +142,7 @@ func ToCampaignRuleEntityFromUpdate(request *contract.CampaignRuleStruct, campai CampaignID: campaignID, RuleType: entities.RuleType(request.RuleType), ConditionValue: request.ConditionValue, - RewardType: entities.NormalizeCampaignRewardType(request.RewardType), + RewardType: entities.CampaignRewardType(request.RewardType), RewardValue: request.RewardValue, RewardSubtype: rewardSubtype, RewardRefID: request.RewardRefID, diff --git a/internal/processor/campaign_processor.go b/internal/processor/campaign_processor.go index 57f2c8f..2823a26 100644 --- a/internal/processor/campaign_processor.go +++ b/internal/processor/campaign_processor.go @@ -70,7 +70,7 @@ func (p *campaignProcessor) ListCampaigns(ctx context.Context, req *contract.Lis Page: req.Page, Limit: req.Limit, Search: req.Search, - Type: string(entities.NormalizeCampaignType(req.Type)), + Type: req.Type, IsActive: req.IsActive, ShowOnApp: req.ShowOnApp, StartDate: req.StartDate, @@ -178,7 +178,7 @@ func (p *campaignRuleProcessor) CreateCampaignRule(ctx context.Context, req *con CampaignID: req.CampaignID, RuleType: entities.RuleType(req.RuleType), ConditionValue: req.ConditionValue, - RewardType: entities.NormalizeCampaignRewardType(req.RewardType), + RewardType: entities.CampaignRewardType(req.RewardType), RewardValue: req.RewardValue, RewardSubtype: (*entities.RewardSubtype)(req.RewardSubtype), RewardRefID: req.RewardRefID, @@ -218,7 +218,7 @@ func (p *campaignRuleProcessor) ListCampaignRules(ctx context.Context, req *cont Limit: req.Limit, CampaignID: req.CampaignID, RuleType: req.RuleType, - RewardType: string(entities.NormalizeCampaignRewardType(req.RewardType)), + RewardType: req.RewardType, } // Get from repository @@ -247,7 +247,7 @@ func (p *campaignRuleProcessor) UpdateCampaignRule(ctx context.Context, req *con CampaignID: req.CampaignID, RuleType: entities.RuleType(req.RuleType), ConditionValue: req.ConditionValue, - RewardType: entities.NormalizeCampaignRewardType(req.RewardType), + RewardType: entities.CampaignRewardType(req.RewardType), RewardValue: req.RewardValue, RewardSubtype: (*entities.RewardSubtype)(req.RewardSubtype), RewardRefID: req.RewardRefID, diff --git a/internal/processor/game_play_processor.go b/internal/processor/game_play_processor.go index 15e3337..e6fef4f 100644 --- a/internal/processor/game_play_processor.go +++ b/internal/processor/game_play_processor.go @@ -99,10 +99,6 @@ func (p *GamePlayProcessor) ListGamePlays(ctx context.Context, query *models.Lis } offset := (query.Page - 1) * query.Limit - // The column was renamed; the old name still sorts the same way. - if query.SortBy == "token_used" { - query.SortBy = "coins_used" - } // Get game plays from repository gamePlays, total, err := p.gamePlayRepo.List( From 100e006218a85d038461e81f0eaf3953121629d5 Mon Sep 17 00:00:00 2001 From: efrilm Date: Wed, 30 Sep 2026 22:35:20 +0700 Subject: [PATCH 5/5] fix(docker): healthcheck the port the app listens on The HEALTHCHECK curled localhost:3300/health, but the app listens on 4000 (server.port in infra/*.yaml, EXPOSE 4000). The check always failed, so deployment.sh waited on 'Waiting for healthcheck...', found the container unhealthy and rolled back to an image with the same broken check. Co-Authored-By: Claude Opus 5.5 --- Dockerfile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Dockerfile b/Dockerfile index bdbd381..128cda3 100644 --- a/Dockerfile +++ b/Dockerfile @@ -15,6 +15,6 @@ COPY --from=build /out/app /app ENV TZ=Asia/Jakarta EXPOSE 4000 HEALTHCHECK --interval=30s --timeout=10s --start-period=30s --retries=3 \ - CMD curl -fsS http://localhost:3300/health || exit 1 + CMD curl -fsS http://localhost:4000/health || exit 1 USER appuser ENTRYPOINT ["/app"]