Compare commits

..
39 Commits
Author SHA1 Message Date
efrilmandClaude Opus 5.5 4432f0a10d feat(loyalty): push a locked PIN through FCM
A customer whose PIN locks after five wrong attempts is now told by a push
through FCM instead of WhatsApp (docs/prd-point-coin.md F11), to every
device registered at /customer/devices. The push is titled "PIN terkunci",
says until when it is locked, and carries type PIN_LOCKED and locked_until
in its data so the app can offer the PIN reset. As before, only the attempt
that reached the limit sends it, and a failure to send is logged without
affecting the lock.

OtpProcessor.SendWhatsAppMessage was only there for this alert and is
removed; OTPs still go out by WhatsApp.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 12:33:20 +07:00
efrilmandClaude Opus 5.5 bf9651e221 feat(loyalty): notify transfer recipients through FCM
The recipient of a transfer now gets a push through FCM instead of a
WhatsApp message (docs/prd-point-coin.md F5).

Customers had nowhere to keep FCM tokens: user_devices only holds staff
devices. Migration 000096 adds customer_devices, and the customer app
registers with PUT /customer/devices { device_id, fcm_token, platform,
app_version } after login and whenever FCM refreshes the token, and
unregisters with DELETE /customer/devices/:device_id on logout. A token
belongs to one customer only: registering it takes it away from whoever
had it on that phone before, so they stop getting this customer's
notifications.

The push goes to every device of the recipient after the commit, titled
"EnakPoint masuk" or "EnakCoin masuk", with type WALLET_TRANSFER_IN, the
TRANSFER_IN transaction id, the group id, the currency and the amount in
its data so the app can open it. A retried transfer sends nothing again. It
stays best effort: no device, FCM not configured or FCM failing is logged
and never undoes the transfer.

The app builds one FCM client and shares it between staff notifications
and customer pushes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 12:30:14 +07:00
efrilmandClaude Opus 5.5 8bf1d5c1a8 feat(loyalty): trace a wallet row lot by lot in the dashboard
Adds GET /marketing/wallet-transactions/:id/trace (docs/prd-point-coin.md
F7, §8.1, PC-404).

From any ledger row of the organization, the trace lists the lots a debit
took from, with how much it took from each, or the lots a credit created.
Each lot is followed back through origin_lot_id, across transfers,
exchanges and refunds, to the lot an EARN, ADJUSTMENT or MIGRATION first
created. Every step shows the lot and the row that created it, with the
real name of the customer it belongs to, so the example of §8 (A sends 120
to B, B pays 30) leads from B's payment to A's order #ORD-1.

Lots are loaded a generation at a time, and a chain stops at 100 steps or
at a lot it has already seen, which only bad data could cause. A row of
another organization answers 404.

The dashboard's wallet view now builds its lots with the same helper.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 12:25:17 +07:00
efrilmandClaude Opus 5.5 a18bb072f5 feat(loyalty): pay every game with EnakCoin
Games now spend the wallet's EnakCoin instead of the per-type tokens
(docs/prd-point-coin.md F8, K1, PC-403).

GamePlayProcessor.PlayGame charges the game's metadata.coin_cost, 1 when
it is not set; a cost that is not a whole number of at least 1 refuses the
game. In one transaction it picks the prize, takes the EnakCoin with a
GAME_SPEND row pointing at the new game_plays.id (which locks the wallet,
so a customer's plays at the same time queue up), records the play and
takes the prize from stock. The play owns its transaction, so the spin
service no longer wraps it, and the admin play endpoint is now atomic too.

The game, game prize and game play repositories go through DBFromContext
so they join that transaction. DecreaseStock now reports a prize that ran
out (ErrGamePrizeOutOfStock) instead of silently updating nothing; that,
or any other stock failure, cancels the whole play, where it used to be
only printed. The manual AddTokens rollback is gone. Not enough EnakCoin,
an inactive game or a prize that ran out answer 400 on /customer/spin
instead of 500.

game_plays.token_used is renamed coins_used (migration 000095). What a
play costs is no longer the caller's choice, so PlayGameRequest loses
token_used. Responses carry coins_used and coins_remaining; token_used and
tokens_remaining stay as deprecated copies until the apps move over, and
sort_by=token_used still sorts by coins_used.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 12:20:42 +07:00
efrilmandClaude Opus 5.5 694d65b6d8 feat(loyalty): send EnakPoint and EnakCoin to another customer
Adds GET /customer/wallet/transfer/recipient?phone= and
POST /customer/wallet/transfer (docs/prd-point-coin.md F5, Q4, Q16,
PC-402).

The recipient is found by phone number and must be an active customer of
the same organization, not the walk-in customer and not the sender. A
number of another organization answers 404 like an unknown one, so the
check does not reveal who uses the app elsewhere. The recipient check
returns the name and number masked ("Bu*** Sa***", "08**-****-1234").

The organization's transfer settings apply: transfers turned off, the
minimum, the maximum per transaction and the daily limit per currency,
which starts over at midnight WIB. Everything the request alone can get
wrong is refused before the PIN, so it costs no attempt; the PIN then
refuses a transfer held for 24 hours after a PIN reset.

Both wallets are locked in customer_id order, so transfers in opposite
directions cannot deadlock, and the daily limit is summed under the lock.
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. The rows share a group, reference each other and name
the other customer; descriptions carry only the masked name.

The Idempotency-Key header is required. A retry is recognised under the
lock before the daily limit, so it replays instead of counting twice; the
same key towards another recipient is refused.

The recipient is told by WhatsApp after the commit, as PIN locks are:
NotificationService only reaches staff devices, there is no push channel
to customers yet. A failure to send is logged, never undoes the transfer.

Transfers must not be released before note N3 (legal) is closed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 12:14:32 +07:00
efrilmandClaude Opus 5.5 ab3425070b feat(loyalty): exchange EnakCoin into EnakPoint
Adds GET /customer/wallet/exchange/preview?coins= and
POST /customer/wallet/exchange (docs/prd-point-coin.md F4, K3, PC-401).

The customer exchanges a multiple of the organization's coin_amount and
gets (coins / coin_amount) x point_amount EnakPoint, approved by their PIN
(K8). A malformed amount is refused before the PIN is checked, so it costs
no attempt. In one transaction the wallet is locked, EXCHANGE_OUT takes the
EnakCoin in K9 order and EXCHANGE_IN adds the EnakPoint; the two rows share
a group, point at each other and both freeze the rate in their metadata.

The EnakPoint are split over the EnakCoin lots they came from, each part
keeping its lot's expiry and pointing back at it, so exchanging cannot
extend a balance's life. The split takes floor(coins so far x rate) per
lot, which adds up exactly because the total is a multiple of coin_amount.
EnakPoint have no validity of their own until the expiry model is decided
(N4), so the EnakCoin lot is for now the only bound.

The Idempotency-Key header (or X-Idempotency-Key) is required. A retry
with the same key is recognised under the wallet lock and replayed with
the ids and rate the first attempt froze, even if the rate has changed
since; the same key for another amount is refused.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 12:09:53 +07:00
efrilmandClaude Opus 5.5 0b52edf84e feat(loyalty): report EnakPoint apart from money received
Keeps EnakPoint out of the money in on the payment method analytics
(docs/prd-point-coin.md F9, K7, PC-308), the one report that sums payments;
the daily transaction and profit-loss PDFs do not break payments down by
method.

summary.total_amount is now only money actually received. EnakPoint stays
listed as its own method, with points_used, and the summary adds
point_amount, points_used and total_with_points. Each method row says
whether it counts_as_cash_in, and the shares are of the money received, 0
for EnakPoint. The average order value still includes what EnakPoint paid,
since that is part of what the orders were worth. How EnakPoint is booked
waits on note N2.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 11:59:33 +07:00
efrilmandClaude Opus 5.5 d7138b8f87 feat(loyalty): refund EnakPoint payments as EnakPoint only
Adds refunds of EnakPoint payments (docs/prd-point-coin.md F9, K7, Q13,
PC-307).

After a void or refund, onOrderRefunded now returns EnakPoint before taking
earning back. For each EnakPoint payment of the order it returns everything
on a void, and floor(refunded rupiah / the frozen point_value) when the
payment itself was refunded, so a later change of the point value does not
change how many come back and a remainder below one EnakPoint is lost. It
never returns more than the payment used, and only what has not come back
yet, so repeating is safe. PAYMENT_REFUND rows point at the PAYMENT they
reverse, and the EnakPoint go back into lots with the expiry of the lots
they were taken from, longest-lasting first (the 7-day extension waits on
note N4).

RefundOrder, which hands money back in cash or another method, is now
limited to what was paid with other methods; the EnakPoint part has to be
refunded through its own payment. That answers 400.

Fixes earning reversal from PC-204: a refund of the EnakPoint part raised
orders.refund_amount and so took earning back, although that part never
earned. It is now left out of the refund the reversal uses.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 11:55:30 +07:00
efrilmandClaude Opus 5.5 43eac0ced4 feat(loyalty): pay own orders with EnakPoint from the app
Adds POST /customer/orders/:id/pay-with-points (docs/prd-point-coin.md F9,
PC-306) for the customer app and self-order. It uses the same payment path
as the cashier, approved by the customer's PIN instead of a code: the
session alone is not enough (K8), and a wrong PIN takes nothing and counts
toward the lock.

A customer can pay only their own order; any other order, and one that
does not exist, answer 404 alike, so the endpoint does not reveal other
customers' orders. The method is the organization's EnakPoint method, no
cashier is recorded, and settling the order triggers earning through the
same onOrderPaid hook as every other payment.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 11:49:49 +07:00
efrilmandClaude Opus 5.5 4b3beaed41 feat(loyalty): pay orders with EnakPoint at the cashier
Adds paying with the EnakPoint method (docs/prd-point-coin.md F9, K7,
PC-305).

POST /payments with the EnakPoint method now takes points and the
customer's payment code and goes through PointPaymentProcessor instead of
the generic path, which would record a payment without taking any balance.
After checking the order, its customer (not walk-in, active), the outlet
(accepts EnakPoint, minimum) and the method, it redeems the code, then in
one transaction locks the order row and the wallet, recomputes the F9
limits from fresh data, inserts the payment with points_used and the frozen
point_value, writes the PAYMENT ledger row (key payment:{id}, the outlet,
the cashier) and updates the order. The limits are
min(balance, floor(min(remaining, total × max_payment_percent / 100 − paid
with EnakPoint) / point_value)) in cents, so EnakPoint never pays more than
what is left and gives no change.

Unlike the generic CreatePayment, which always marks the order paid, an
EnakPoint payment leaves it partial with the right remaining amount until
it is settled, so the rest can be paid in cash. Settling it triggers
earning, whose basis leaves out the EnakPoint part. Splitting with the
EnakPoint method is refused. Refusals answer 400. The payment response
carries points_used and point_value for the receipt.

GET /orders/:id/point-payment/preview returns eligibility, balance, point
value and the maximum for the use-maximum button.

The payment and order repositories write outside transactions, so this
path uses its own repository that joins it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 11:46:31 +07:00
efrilmandClaude Opus 5.5 0c4dd72583 feat(loyalty): one-time EnakPoint payment code
Adds POST /customer/wallet/payment-code (docs/prd-point-coin.md F9, K8,
PC-304). The customer approves with their PIN on their own phone and gets a
6-digit code, as digits and as a QR payload (enakpoint:<code>) for the app
to render, valid for two minutes. The PIN is never typed at the cashier.

Codes are drawn from crypto/rand and stored in Redis with SET NX and a TTL,
bound to the customer; a new code retires the previous one. Redeeming is a
single Lua step that uses the code up only if it belongs to the order's
customer, so it stays one-time under a race, and a cashier scanning it
against the wrong order does not burn it for its owner, which a plain
GETDEL would. Expired, used, unknown and other customers' codes are all
refused alike.

Tests run against miniredis, added as a test dependency.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 11:37:20 +07:00
efrilmandClaude Opus 5.5 cf5332c281 feat(loyalty): EnakPoint payment method
Adds the system payment method for paying with EnakPoint
(docs/prd-point-coin.md F9, §8, §10.5, PC-303).

Migration 000094 allows the point type, keeps one per organization with a
partial unique index, creates it for every existing organization, and adds
a trigger that creates it for new ones, as the walk-in customer is. It adds
payments.points_used and point_value. Their CHECK is written so it can
never be NULL: the PRD form, (both NULL) OR (both > 0), is NULL for
points_used with a NULL point_value, which a CHECK lets through, so a
payment could have lost the value a refund depends on. A test caught it.

The API cannot create, delete or retype the EnakPoint method, nor turn
another method into one; that answers 400. Renaming it is allowed. The
method list takes the outlet from ?outlet_id= or the user's outlet and
leaves EnakPoint out when that outlet does not accept it, filtered in the
query so the count stays right. The organization-wide active list is
unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 11:33:25 +07:00
efrilmandClaude Opus 5.5 fe2f459b03 feat(loyalty): organization loyalty settings API
Adds GET and PUT /marketing/loyalty-settings and GET
/marketing/loyalty-settings/history (docs/prd-point-coin.md F2, PC-302).

The settings are the point value, the exchange rate, transfer limits and
the stored expiry settings. PUT merges the body like the outlet settings
and is limited to loyalty managers. Every response carries the impact of
the change on the balances in circulation: outstanding EnakPoint and
EnakCoin, their rupiah value, and the coins exchanged into points, before
and after. With ?dry_run=true nothing is saved and the response lists the
keys that would change, for the warning shown before saving.

Saving records each change in loyalty_setting_changes with who made it;
history can be filtered to one outlet. Changing the value leaves what was
already written alone. The diff behind saving and previewing is shared.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 11:26:16 +07:00
efrilmandClaude Opus 5.5 8370851ed2 feat(loyalty): customer PIN
Adds the 6-digit customer PIN that approves every action moving EnakPoint
or EnakCoin on the customer's request (docs/prd-point-coin.md K8, F11, Q16,
Q17, PC-301).

Migration 000093 adds the PIN columns to customers and the
customer_security_events table. PIN data is read and written only through
CustomerPinRepository, never the Customer entity, so the hash cannot reach
a customer response. Only a bcrypt hash is stored.

- /customer/pin: status, OTP (pin_setup, pin_reset), create, change,
  reset. The OTP must be for that purpose and sent to the customer's own
  number; the existing OTP validation checks neither. A new PIN is checked
  (6 digits, confirmed, not one digit, not a run up or down, not the birth
  date as DDMMYY or YYMMDD) before the OTP is spent.
- Five wrong attempts in a row lock the PIN for 30 minutes; the counter is
  incremented in one statement so attempts at the same time all count,
  and a lock that ran out starts a new series. A locked PIN is refused even
  when right. The customer is told by WhatsApp, as there is no push channel
  to customers yet; only the attempt that reached the limit alerts.
- A reset through OTP lifts the lock and holds outgoing transfers for 24
  hours; paying and exchanging still work, and a held transfer costs no
  attempt.
- VerifyPin(ctx, customer, pin, action) for the flows that follow, with
  PIN_NOT_SET, PIN_INVALID (attempts left), PIN_LOCKED and
  TRANSFER_BLOCKED (until when), which PinErrorResponse turns into
  distinct codes and statuses.
- DELETE /marketing/customers/:id/pin (loyalty managers, reason required)
  and GET /marketing/customers/:id/security-events, scoped to the
  organization.

Every PIN event is in the security log with IP and user agent. No message
or binding error contains a PIN.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 11:20:29 +07:00
efrilmandClaude Opus 5.5 fc97c78300 feat(loyalty): show what an order earned on the order and receipt
Adds points_earned and coins_earned to the order response
(docs/prd-point-coin.md F3, PC-205). The POS prints the receipt from this
response, so the receipt gets them too.

The values are the sums of the order's EARN rows, read in one query for a
list of orders. They are filled for create, add items, update, detail and
list, and are 0 for an order that earned nothing. UpdateOrder earns before
building its response, so a payment completed there already shows the
earning. A failure to read them is logged and leaves them at 0 rather than
failing the order read. The self-order session listing reads orders
directly from the repository and still shows 0.

The two order hooks are merged into one OrderLoyalty interface (paid,
refunded, earned by orders) with a single SetLoyalty.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 10:50:37 +07:00
efrilmandClaude Opus 5.5 eb5b63677f feat(loyalty): take back earning when an order is voided or refunded
Adds earning reversal (docs/prd-point-coin.md F10, Q3, PC-204).

VoidOrder, RefundOrder and RefundPayment now end with an onOrderRefunded
hook, called once their writes have committed and, like onOrderPaid,
detached from the request so it can never block or fail the void or
refund. For RefundPayment that is after its transaction.

EarningProcessor.ReverseForOrder computes how much of each EARN row should
have come back in total: everything for a void, otherwise
floor(earned × refunded / basis) with the order's cumulative refund and
the basis frozen on the EARN row, never more than was earned (a refund
including tax can pass the basis). It takes only what has not been asked
back yet, what was taken plus any shortfall, so repeats and successive
partial refunds never add up to more than the earning. It writes an
EARN_REVERSAL pointing at the EARN with DebitUpTo, drawing from the lots
the EARN created first, and records the shortfall when the balance was
already spent.

When the balance is empty there is no ledger row to carry the shortfall;
that case is logged. VoidOrder still refuses fully paid orders, so a void
has nothing to take back today; the hook keeps it correct if that changes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 10:45:33 +07:00
efrilmandClaude Opus 5.5 78c0c11774 feat(loyalty): earn EnakPoint and EnakCoin when an order is paid
Adds earning at payment time (docs/prd-point-coin.md F3, PC-203).

An order becomes fully paid through UpdateOrder, CreatePayment and both
kinds of split bill. All of them now go through one OrderProcessorImpl
hook, onOrderPaid, called after the payment has committed; for
CreatePayment that is after its transaction, not from updateOrderStatus
inside it. The hook runs detached from the caller's transaction and from
the request being cancelled, and it runs synchronously so the order
response can show what was earned.

EarningProcessor.EarnForOrder skips orders that are not paid, are void,
have no customer, or whose customer is the walk-in customer or inactive.
It computes the earning with CalculateEarning, subtracting any part paid
with EnakPoint (none until phase 3), and credits each currency through the
wallet engine as EARN with key earn:{order_id}:{currency} and the settings
snapshot in metadata. A repeat, even concurrent, credits nothing more.
OnOrderPaid never fails the payment: errors and panics are logged.

EarningBackfillJob is the safety net: every 30 minutes it earns for orders
paid in the last three days that have no EARN row. It only looks at
outlets with earning switched on and pages by (updated_at, id), so orders
that correctly earned nothing cannot starve the ones that were missed.

Lots from earning never expire until the expiry model is decided (F12,
note N4). Adds the point payment method type constant, not yet accepted as
a payment method.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 10:40:05 +07:00
efrilmandClaude Opus 5.5 5baed18b22 feat(loyalty): earning calculator
Adds CalculateEarning (docs/prd-point-coin.md F1, Q1, Q10, PC-202), a pure
function returning, per currency, the amount an order earns and the
settings that produced it, plus the basis:

  basis  = subtotal − discount − paid with EnakPoint   (never negative)
  amount = 0 below min_order_amount, else
           floor(basis / earn_per_amount) × earn_value, capped by max_per_order

Tax and anything added on top of the subtotal are not part of the basis,
and the part paid with EnakPoint earns nothing. Money is handled in whole
cents: in float64 some baskets divide to 4956.999… and a naive floor would
lose a point, which a test reproduces. Metadata() gives the snapshot the
EARN row will freeze.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 10:31:09 +07:00
efrilmandClaude Opus 5.5 2bd53ee4a4 feat(loyalty): outlet loyalty settings API
Adds GET and PUT /outlets/:id/loyalty-settings (docs/prd-point-coin.md F1,
PC-201) on top of the typed settings processor.

The response shows every setting with its default when unset, the
organization's point value, and the effective EnakPoint cashback
(earn_value × point_value / earn_per_amount), so an owner cannot misread
the scale. PUT applies the body on top of the current settings: fields left
out keep their value, null clears an optional limit, and unknown fields are
refused so a typo cannot be ignored silently. The read-only fields of the
GET response are accepted and ignored, so a client can send back what it
received. It returns the keys that changed. Values outside the F1 bounds
answer 400, and an outlet of another organization 404.

RequireAdminOrManager also lets the purchasing role through, so loyalty
settings and the manual wallet adjustment from PC-107 now use a stricter
RequireLoyaltyManager (superadmin, admin, manager, owner).

Adds a test that registers every route, since gin panics at startup when
two routes name the same path parameter differently.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 10:28:40 +07:00
efrilmandClaude Opus 5.5 39e47ff0e6 feat(loyalty): typed loyalty settings with change history
Adds LoyaltySettingsProcessor (docs/prd-point-coin.md F1, F2, F12, PC-109).

Reading returns typed settings for an outlet (earning per currency, paying
with EnakPoint) and for an organization (point value, exchange rate,
transfers, and the expiry settings awaiting note N4). A key that was never
set takes the PRD default. A stored value that is unusable, such as an
earn_per_amount of 0 that would divide by zero, also falls back to the
default and is logged, so a bad row never reaches a calculation.

Writing takes the whole settings struct, validates every rule in the PRD
before touching the database, and stores and records in
loyalty_setting_changes only the keys whose effective value changes: old
value (NULL while it was on its default), new value, and who changed it.
Clearing a limit deletes the stored value. Each save runs in one
transaction under an advisory lock per outlet or organization, so two saves
at once cannot both compute their change from the same old value. The
outlet must belong to the caller's organization.

Every key is described once (key, default, valid range, bound field), and
reading, validating and diffing all use that description.

GET /customer/wallet now reads the point value through this processor; the
minimal organization settings repository from PC-106 is removed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 10:23:08 +07:00
efrilmandClaude Opus 5.5 040780cd2d feat(wallet): reconcile balances, ledger and lots on a schedule
Adds the reconciliation of docs/prd-point-coin.md §7.5 (PC-108). One
aggregate query per check, across every wallet:

- wallet balance = SUM(ledger), per currency, including customers with
  ledger rows but no wallet row
- wallet balance = SUM(lot remaining)
- lot original - SUM(allocations) = remaining
- SUM(allocations) = |amount| for every deduction
- lots created = amount for every addition, which the engine keeps and the
  other checks rely on

The check on payments.points_used waits for that column (PC-305).

WalletReconciliationJob runs the checks at startup and every six hours,
alongside the omset scheduler. It is silent while the data is consistent.
Each discrepancy is logged with its check, customer, object and the
expected and actual values, and the organization's admins, owners and
managers get a high-priority notification. An organization is notified
again only when its set of discrepancies changes. Nothing is corrected
automatically. At most 50 discrepancies per check are reported.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 10:13:46 +07:00
efrilmandClaude Opus 5.5 a6d5a8b056 feat(wallet): customer wallet and manual adjustments in the dashboard
Adds the dashboard side of a customer's wallet (docs/prd-point-coin.md F7,
PC-107), under /marketing for admins and managers:

- GET /marketing/customers/:id/wallet returns the customer, the ledger and
  spendable balances, every lot that still holds something (flagged when
  expired), and a page of history. Unlike the customer's own view, each row
  carries the real names behind it: the transfer counterparty, the admin or
  cashier, and the outlet, plus the reason and metadata.
- POST /marketing/customers/:id/wallet/adjust takes a signed amount and a
  required reason. It writes an ADJUSTMENT pointing at the admin through the
  wallet engine, refuses to take more than the customer can spend, and
  accepts an optional idempotency key so a retried request adjusts once.
  Reasons describing a cash-out are refused (K7).

The customer must belong to the caller's organization; otherwise both
endpoints answer 404. Positive adjustments create non-expiring lots until
the expiry model is decided (F12, note N4).

The mapping from ledger rows to what the apps show is now shared between the
customer and dashboard views.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 09:36:18 +07:00
efrilmandClaude Opus 5.5 e5db0325cc feat(wallet): serve customer balances and history from the wallet
GET /customer/wallet now reads the EnakPoint & EnakCoin wallet
(docs/prd-point-coin.md F6, PC-106): spendable point and coin balances, the
rupiah value of one EnakPoint and of the balance, the nearest day each
currency loses balance (grouped by Asia/Jakarta day), and recent ledger
rows. The fields of the pre-wallet response stay, filled from the wallet, so
app versions that read them keep working.

Adds GET /customer/wallet/transactions with pagination and filters for
currency, one or more types, and an inclusive date range. Each row shows
where the value came from (additions) or went to (deductions) as in §8.1,
and additions list their lots and earliest expiry. The counterparty id, the
admin and the metadata are left out; the description already carries the
masked name. A malformed query answers 400, a missing customer 404.

/customer/points and /customer/tokens keep their shape and now read the
wallet too, so customer_points_repository is no longer used for balances.

Balances are what the customer can spend: lots that have expired but that
the expiry job has not processed are not counted. The point value is read
from organization_settings (loyalty.point.value, default 1) through a small
repository that the typed settings reader in PC-109 will build on.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 09:15:26 +07:00
efrilmandClaude Opus 5.5 41b75810fd feat(wallet): migrate legacy points and tokens into the wallet
Adds cmd/wallet-migrate (make wallet-migrate, args=-dry-run to only report),
which moves 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, written through WalletProcessor in
one transaction per customer. EnakCoin is the sum of every token type (Q6),
with the legacy rows listed in the row's metadata.

It credits the difference between the legacy balance and what earlier runs
migrated, so running it again never doubles a balance and picks up only
what the old code added since. A legacy balance that shrank after being
migrated is reported and left alone, since only an admin adjustment may
take balance away, and the command then exits non-zero. It ends with a
legacy / migrated / wallet total per currency.

Migration 000092 renames TOKENS to COINS in campaigns.type and
campaign_rules.reward_type. The campaign API now validates COINS; it still
accepts TOKENS, including as a list filter, and stores it as COINS so older
dashboards keep working while they are updated.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 08:47:48 +07:00
efrilmandClaude Opus 5.5 6af97f5696 fix(wallet): stop logging new idempotency keys as errors
GetTransactionByIdempotencyKey used First, so every wallet operation with a
key not seen before, which is the normal case, logged a "record not found"
error. It now uses Find with a limit and returns nil when nothing matches.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 08:47:37 +07:00
efrilmandClaude Opus 5.5 2eb590caab feat(wallet): add wallet engine as the only way to change a balance
WalletProcessor writes the balance, the ledger row and the lots or
allocations together, which keeps SUM(ledger) = balance = SUM(lot
remaining) (docs/prd-point-coin.md §7.5, PC-104).

- Credit writes the ledger row and creates lots, each with its own expiry
  and origin lot.
- Debit draws from the preferred lots first (a reversal's own lots, or the
  lot being expired), then from unexpired lots in K9 order, and returns the
  allocations with their expiry so CarryOver can give the receiving side of
  a transfer or exchange the same expiry.
- DebitUpTo takes what the wallet has and reports the shortfall (F10, Q3).
- An idempotency key returns the first result; reusing it for a different
  operation is an error.
- §8.1 is checked in code from one rule table, ahead of the database
  constraints, so callers get a readable error.

Each method locks the wallet itself, after validating the input and before
checking the idempotency key, so correctness does not depend on the caller.
Operations on two wallets still call LockWallets first to keep lock order.

Unit tests run on an in-memory repository and check the §7.5 invariants
after every scenario; one more test runs the engine against Postgres when
TEST_DATABASE_URL is set.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 08:47:37 +07:00
efrilmandClaude Opus 5.5 fc5eecb68a feat(wallet): add wallet entities and repository
Entities for the four wallet tables and a WalletRepository that the wallet
processor will build on (PC-103).

Every method goes through the caller's transaction, and writes and locks
refuse to run without one: outside a transaction a lock is released as soon
as it is taken and a balance could move without its ledger row.

- LockWallet creates the wallet on first use, taking the organization from
  the customer, then locks it with SELECT ... FOR UPDATE.
- LockWallets always locks in customer_id order so opposite transfers
  cannot deadlock.
- AddBalance and ConsumeLot are conditional updates that return an error
  when they would overdraw, instead of tripping the CHECK constraint.
- ListActiveLots returns unexpired lots with balance in K9 spending order.

The tests need a real Postgres and run only when TEST_DATABASE_URL points at
a migrated database. Both the lock and the lock ordering were checked by
removing them and watching the tests fail (lost update, deadlock detected).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 01:01:03 +07:00
efrilmandClaude Opus 5.5 b107f4ef04 feat(settings): add organization settings and loyalty setting history
Migration 000091 creates organization_settings, a key-value store per
organization shaped like outlet_settings, for the loyalty settings that must
be the same in every outlet (point value, exchange rate, transfer limits,
expiry). Until now there was nowhere to keep organization-level settings.

Also creates loyalty_setting_changes, the append-only log of who changed
which loyalty setting from what to what (PRD F2), for both organization and
outlet settings (PC-102).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 01:01:02 +07:00
efrilmandClaude Opus 5.5 84401cc708 feat(wallet): add wallet, ledger and lot tables
Migration 000090 creates customer_wallets, wallet_transactions, wallet_lots
and wallet_lot_allocations as specified in docs/prd-point-coin.md §8 (PC-101).

The CHECK constraints enforce K5 at the database: every ledger row names its
source or destination, PAYMENT and the other point-only types cannot carry
COIN, transfers need a counterparty, reversals need the row they reverse,
adjustments need an admin and a reason, and EXPIRE must point at a lot.
Balances and lot remainders cannot go negative, and a lot cannot hold more
than it was created with.

Beyond §8, adds idx_wallet_lot_allocations_lot_id: the primary key cannot
serve lookups by lot, which the reconciliation job needs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 01:01:01 +07:00
aefril f0ff59fea7 Merge pull request 'fix(analytics): cost weighed lines by weight, not row count' (#31) from feature/weight-based-products into main
Reviewed-on: https://gits.altru.id/apksel-dev/apskel-pos-backend/pulls/31
2026-09-06 18:07:46 +02:00
efrilmandClaude Opus 5 923c108690 fix(analytics): cost weighed lines by weight, not row count
A weight-based line is one weighing, so order_items.quantity is pinned to 1
while unit_price and unit_cost are per unit of weight. Analytics SQL was
multiplying and dividing per-unit rates by the raw quantity, costing a 4.2 ons
fish as a single ons: standard_hpp_total and moving_average_hpp_total came out
far too low across all four product reports, overstating gross profit, and
average_price and fifo_hpp_per_unit read per weighing while
standard_hpp_per_unit read per unit, so the three HPP figures in one row could
not be compared.

Adds billableQty and billableQtyNet as the single place that decides the
multiplier, mirroring entities.OrderItem.BillableQuantity.

quantity_sold and total_items stay as weighing counts; weight_sold already
carries the amount. revenue and fifo_hpp_total were already correct via
total_price/total_cost.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-06 23:06:31 +07:00
aefril 1edeaa0a48 Merge pull request 'fix(order): carry item weight through the contract-to-model transformer' (#30) from feature/weight-based-products into main
Reviewed-on: https://gits.altru.id/apksel-dev/apskel-pos-backend/pulls/30
2026-09-06 17:46:07 +02:00
efrilmandClaude Opus 5 f2701882dc fix(order): carry item weight through the contract-to-model transformer
CreateOrderContractToModel and AddToOrderContractToModel copied every order
item field except Weight, so a weight sent by the client never reached the
processor and every weight-based line failed with "product ... is sold by
weight and requires a weight".

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-06 22:44:55 +07:00
aefril c9311997a7 Merge pull request 'Feature/weight based products' (#29) from feature/weight-based-products into main
Reviewed-on: https://gits.altru.id/apksel-dev/apskel-pos-backend/pulls/29
2026-09-06 17:13:51 +02:00
efrilmandClaude Opus 5 ebf666c004 feat(product): require a unit for weight-based products
A product sold by weight with no unit produces order lines with nothing to
print: the receipt would read "4,2" with no idea of what. Until now nothing
stopped that — the mistake only surfaced at the cashier.

Enforce it in two places, because neither alone sees the whole picture. On
create, the validator has everything it needs. On update, the request may
omit unit_id for a product that already has one, so the check runs in the
processor against the merged product: what is rejected is the end state, a
product sold by weight with no unit.

Also fixes two things this uncovered:

The struct tags on the product contracts are decorative — this validator is
hand-written and never calls validator.Struct — so `oneof=unit weight` was
never enforced, and an unknown sell_by was silently rewritten to "unit" by
the mapper. It is now rejected with a message that names the valid values.

The update validator's "at least one field" guard did not list unit_id,
sell_by or print_to_checker, so an update carrying only one of those was
turned away as an empty request.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-06 17:29:34 +07:00
efrilmandClaude Opus 5 d3987c7114 docs(order): add weight-based product integration guide
Client-facing companion to the RFC, aimed at the POS Mobile and Backoffice
teams: endpoints and payloads for setting up a weight product, placing an
order, rendering the line, and voiding, refunding or splitting it.

Documents two gaps the teams have to work around rather than discover:
unit_id is not yet enforced when sell_by is "weight", so Backoffice must
require it in the form; and money rounds to 2 decimals rather than whole
rupiah, which is still an open decision.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-06 17:20:22 +07:00
efrilmandClaude Opus 5 992bb04816 feat(order): support weight-based products
Products like fish are sold per weighing (4.2 ons, 5.6 ons), which the
order line could not represent: quantity is INTEGER and prices are always
computed as quantity * unit_price.

Model one weighing as one order line. quantity stays INTEGER and keeps
meaning "how many items"; the measured amount goes into a new nullable
order_items.weight, and the line is priced weight * unit_price. Two
weighings of the same product are two lines, never merged into one.

Keeping quantity integral avoids float comparisons in void, refund and
split bill, where accumulated rounding error would silently misbehave —
"1.4 + 1.4 + 1.4" is not 4.2 in float64, which would leave a fully paid
split-bill item marked unpaid.

BillableQuantity() is now the single place that decides between weight
and count; every price and cost calculation goes through it. Missing one
would bill a 4.2 ons fish as a single ons — wrong money, no error.

Two database constraints back the design: a weighed line always carries a
positive weight, and its quantity is pinned to 1. The latter also makes
void all-or-nothing for weighed lines, so the row-splitting branch can
never produce a zero-weight remainder row.

Also wires product.unit_id through the API, which was previously not
settable at all, and corrects the misleading comment on the request's
unit_price field — that value has never been used; price always comes
from the database.

Design notes and the audit of every price multiplication site are in
docs/rfc-weight-based-products.md.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-06 17:14:42 +07:00
aefril 1e5573af75 Merge pull request 'feat: cash advance' (#28) from dev into main
Reviewed-on: https://gits.altru.id/apksel-dev/apskel-pos-backend/pulls/28
2026-08-13 09:39:53 +02:00
aefril b42d141927 Merge pull request 'Dev' (#27) from dev into main
Reviewed-on: https://gits.altru.id/apksel-dev/apskel-pos-backend/pulls/27
2026-08-11 17:46:43 +02:00
197 changed files with 18657 additions and 522 deletions
+8
View File
@@ -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)
+73
View File
@@ -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")
}
+279
View File
@@ -0,0 +1,279 @@
# Integrasi Produk Timbangan — POS Mobile & Backoffice
**Migrasi:** `000089` · **Base URL:** `/api/v1` · **Kompatibilitas:** mundur penuh
Panduan untuk menjual produk per timbangan (ikan, daging, buah) dari sisi klien.
Alasan di balik setiap keputusan desain ada di [`rfc-weight-based-products.md`](./rfc-weight-based-products.md).
---
## 1. Konsep inti
**Satu penimbangan = satu baris order.**
Pelanggan memesan Ikan Tude 4,2 ons, lalu memesan Ikan Tude lagi 5,6 ons. Itu **dua
baris terpisah**, karena keduanya dua ikan berbeda yang ditimbang sendiri-sendiri.
| Bukan begini | Melainkan begini |
|---|---|
| `quantity: 9.8` | `quantity: 1, weight: 4.2`<br>`quantity: 1, weight: 5.6` |
| Dua ikan hilang jejaknya, dan `quantity` bertipe integer sehingga pecahan ditolak | Tiap penimbangan berdiri sendiri, bisa di-void atau dibayar terpisah |
Empat aturan yang berlaku di seluruh dokumen ini:
1. `quantity` untuk produk timbangan **selalu 1**. Backend memaksanya, dan database
menolak nilai lain lewat constraint `chk_order_items_weight_single_line`.
2. `weight` menyimpan angka timbangan, dalam satuan produk itu sendiri (ons, kg, gram —
apa pun yang dipilih saat setup).
3. Harga baris dihitung `weight × unit_price`, bukan `quantity × unit_price`.
`unit_price` tetap berarti harga per satu satuan (per ons).
4. **Jangan pernah menggabungkan dua baris** produk timbangan menjadi satu, meski
produknya sama.
Untuk produk biasa tidak ada yang berubah: `weight` tidak dikirim, `quantity` tetap
cacah seperti sekarang.
---
## 2. Backoffice — setup produk
### 2.1 Pastikan satuannya ada
Satuan disimpan per organisasi. Buat sekali, pakai ulang untuk semua produk timbangan.
`POST /api/v1/units`
```json
{
"name": "Ons",
"abbreviation": "ons",
"is_active": true
}
```
`abbreviation` yang dipakai POS untuk mencetak `4,2 ons` di struk — isi dengan bentuk
pendek yang benar-benar ingin ditampilkan. Daftar satuan dibaca lewat `GET /api/v1/units`.
### 2.2 Buat produk sebagai produk timbangan
`POST /api/v1/products`
```json
{
"category_id": "…",
"name": "Ikan Tude",
"price": 4500,
"cost": 3000,
"sell_by": "weight",
"unit_id": "<id satuan Ons>"
}
```
| Field | Tipe | Keterangan |
|---|---|---|
| `sell_by` | `"unit"` \| `"weight"` | Opsional, default `"unit"`. Nilai lain **ditolak** dengan pesan jelas. |
| `unit_id` | UUID | **Wajib** saat `sell_by: "weight"`, ditolak backend bila kosong. Opsional untuk produk satuan. |
| `price` | number | Harga per satu satuan. Rp 4.500 per ons, bukan harga per ikan. |
Pada `PUT /api/v1/products/:id`, `unit_id` **tidak perlu dikirim ulang** bila produknya
sudah punya satuan — mengubah `sell_by` menjadi `"weight"` saja sudah cukup. Yang ditolak
adalah kondisi akhirnya: produk yang dijual per timbangan tanpa satuan.
Keduanya juga bisa diubah lewat `PUT /api/v1/products/:id` dengan bentuk yang sama, dan
ikut terbaca di setiap response produk (`GET /api/v1/products`, `/products/all`,
`/products/:id`).
### 2.3 Catatan UI
- Kunci `sell_by` **setelah produk punya transaksi**. Mengubah produk lama dari `unit`
ke `weight` tidak mengubah baris order yang sudah ada — baris lama tetap dihitung per
cacah — tapi akan membingungkan pengguna yang melihat riwayatnya.
- Saat `weight` dipilih, jadikan pemilih satuan sebagai field **wajib** di form. Backend
juga menolaknya, tapi ditangkap di form lebih baik daripada baru gagal saat simpan.
- Ubah label harga mengikuti satuan yang dipilih: *"Harga per ons"*.
- Untuk produk satuan, pemilih satuan boleh disembunyikan — `unit_id` opsional dan belum
dikonsumsi apa pun di POS.
---
## 3. POS Mobile — transaksi
### 3.1 Bentuk input mengikuti `sell_by`
| `sell_by` | Input di POS | Yang dikirim |
|---|---|---|
| `"unit"` | Stepper − / + seperti sekarang | `quantity: n`, tanpa `weight` |
| `"weight"` | Papan angka desimal, satuan dari `unit` produk | `quantity: 1` + `weight: 4.2` |
### 3.2 Mengirim order
`POST /api/v1/orders`
```json
{
"outlet_id": "…",
"user_id": "…",
"order_type": "dine_in",
"order_items": [
{ "product_id": "<ikan-tude>", "quantity": 1, "weight": 4.2 },
{ "product_id": "<ikan-tude>", "quantity": 1, "weight": 5.6 },
{ "product_id": "<nasi-goreng>", "quantity": 2 }
]
}
```
Bentuk yang sama berlaku untuk `POST /api/v1/orders/:id/add-items` dan untuk pemesanan
mandiri `POST /api/v1/self-order/orders`.
**Presisi.** Berat dibulatkan backend ke 3 desimal. Kirim `4.2` atau `4.237`; angka di
bawah `0.001` membulat ke nol dan ditolak.
**Harga.** Field `unit_price` pada request **diabaikan** — harga selalu diambil backend
dari master produk. Jangan mengirim harga hasil hitungan sendiri.
---
## 4. Menampilkan baris
Setiap `order_items[]` di response membawa empat field tambahan:
```json
{
"product_name": "Ikan Tude",
"quantity": 1,
"weight": 4.2,
"unit_id": "…",
"unit_name": "Ons",
"unit_abbreviation": "ons",
"unit_price": 4500,
"total_price": 18900
}
```
Semuanya `null` atau absen untuk produk biasa, jadi cabangkan tampilan pada `weight`:
| Kondisi | Tampilkan |
|---|---|
| `weight == null` | `2 × Rp 25.000` |
| `weight != null` | `4,2 ons × Rp 4.500` |
**Jangan menampilkan `quantity` untuk baris berbobot** — nilainya selalu 1 dan akan
terbaca seperti "satu ons". Gunakan `weight` dengan `unit_abbreviation`, dan pakai koma
desimal sesuai format Indonesia.
---
## 5. Void, refund, split bill
Baris berbobot bersifat **utuh**: dibatalkan seluruhnya atau tidak sama sekali. Karena
`quantity`-nya 1, semua endpoint cukup dikirimi `1`, dan backend menghitung nilai
rupiahnya dari `weight`.
| Aksi | Endpoint | Field untuk baris berbobot |
|---|---|---|
| Void per item | `POST /orders/void` | `items[].quantity: 1` |
| Refund per item | `POST /orders/:id/refund` | `order_items[].refund_quantity: 1` (atau kosongkan) |
| Split bill per item | `POST /orders/split-bill` | `items[].quantity: 1` = bayar baris itu penuh |
```json
{
"order_id": "…",
"reason": "Salah timbang",
"type": "ITEM",
"items": [
{ "order_item_id": "<baris 4,2 ons>", "quantity": 1 }
]
}
```
Untuk split bill, baris berbobot hanya bisa berstatus belum dibayar atau lunas — tidak
ada nilai di antaranya. Sembunyikan stepper jumlah pada baris berbobot, ganti dengan
tombol pilih baris.
**Batasan yang disengaja.** Mengembalikan *sebagian berat* — 1 ons dari baris 4,2 ons —
tidak didukung. Koreksi salah timbang ditangani dengan void baris itu lalu input ulang,
sehingga jejak auditnya tetap jujur.
---
## 6. Referensi error
Semua error mengikuti amplop standar. Pesan validasi baru muncul dengan kode `900`:
```json
{
"success": false,
"data": null,
"errors": [
{ "code": "900", "entity": "ORDER",
"cause": "product Ikan Tude is sold by weight and requires a weight" }
]
}
```
| Pesan (`cause`) | Penyebab | Perbaikan di klien |
|---|---|---|
| `… is sold by weight and requires a weight` | Produk `sell_by: "weight"` dikirim tanpa `weight` | Wajibkan input timbangan sebelum item masuk keranjang |
| `… is not sold by weight and must not carry a weight` | `weight` dikirim untuk produk satuan | Kirim `weight` hanya bila `sell_by == "weight"` |
| `weight for … must be greater than 0` | Berat nol, negatif, atau membulat ke nol | Validasi minimal `0.001` di keypad |
| `quantity for … must be at least 1` | Produk satuan dengan `quantity` ≤ 0 | Perilaku lama, tidak berubah |
Pesan menyebut **nama produk**, sehingga bisa ditampilkan apa adanya ke kasir.
### Setup produk (Backoffice)
| Pesan (`cause`) | Penyebab | Perbaikan di klien |
|---|---|---|
| `unit_id is required when sell_by is 'weight'` | Produk timbangan dibuat tanpa satuan | Wajibkan pemilih satuan saat Timbangan dipilih |
| `sell_by must be either 'unit' or 'weight'` | Nilai `sell_by` di luar dua itu | Kirim persis `"unit"` atau `"weight"` |
| `product '…' is sold by weight and requires a unit_id` | Update membuat produk jadi timbangan tanpa satuan | Kirim `unit_id` bersama perubahan `sell_by` |
---
## 7. Kompatibilitas mundur
- Semua produk lama otomatis `sell_by: "unit"`. Perilakunya identik dengan sebelumnya.
- `weight` opsional di request. Klien yang tidak mengenalnya tetap berfungsi penuh untuk
produk satuan.
- Field baru di response semuanya `omitempty` — tidak muncul untuk baris biasa, jadi
parser lama tidak terganggu.
- `quantity` tetap **integer** di seluruh API. Tidak ada field yang berubah tipe.
Yang tidak berfungsi di klien lama hanyalah menjual produk timbangan itu sendiri —
permintaannya ditolak dengan pesan jelas, bukan gagal diam-diam.
---
## 8. Batasan yang diketahui
- **Pembulatan uang ke 2 desimal.** `4,237 ons × Rp 4.500` tersimpan `Rp 19.066,50`,
bukan dibulatkan ke rupiah utuh. Bila kasir harus menerima rupiah penuh, ini perlu
diputuskan dan diubah di backend lebih dulu (`RoundMoney`, satu tempat).
- **Stok belum otomatis berkurang** saat penjualan — untuk produk timbangan maupun
produk biasa. Pengurangan stok belum tersambung di backend, jadi jangan menampilkan
sisa stok yang mengandaikan itu berjalan.
---
## 9. Checklist per tim
**Backoffice Website**
- [ ] CRUD satuan tersedia di menu master data
- [ ] Form produk punya pilihan cara jual: Satuan / Timbangan
- [ ] Pemilih satuan menjadi wajib saat Timbangan dipilih
- [ ] Label harga ikut satuan — "Harga per ons"
- [ ] `sell_by` dikunci untuk produk yang sudah bertransaksi
- [ ] Daftar produk menandai mana yang dijual per timbangan
- [ ] Laporan harian menampilkan kolom Berat
**POS Mobile**
- [ ] Menu membaca `sell_by` tiap produk
- [ ] Papan angka desimal untuk produk timbangan
- [ ] Kirim `quantity: 1` + `weight`
- [ ] Dua penimbangan menjadi dua baris, tidak digabung
- [ ] Keranjang & struk menampilkan `4,2 ons × Rp 4.500`
- [ ] Void & refund baris berbobot bersifat utuh
- [ ] Split bill: pilih baris, bukan stepper jumlah
- [ ] Pesan error validasi ditampilkan ke kasir
+362
View File
@@ -0,0 +1,362 @@
# RFC: Produk Timbangan (Weight-Based Products)
**Status:** Diimplementasikan (migrasi `000089`)
**Tanggal:** 2026-09-05, diperbarui 2026-09-06
**Scope:** Product, Order, Void/Refund, Report
**Out of scope:** Inventory / pengurangan stok otomatis (lihat §8)
---
## 1. Masalah
Sistem mengasumsikan setiap produk dijual dalam satuan diskrit. `order_items.quantity`
bertipe `INTEGER` dengan `CHECK (quantity > 0)`, dan harga dihitung
`quantity × unit_price` di seluruh jalur order, void, refund, dan split bill.
Produk seperti Ikan Tude dijual per timbangan. Pelanggan memesan Ikan Tude 4,2 ons,
lalu memesan Ikan Tude lagi 5,6 ons. Keduanya adalah **dua ikan berbeda yang ditimbang
terpisah** — bukan satu baris berisi 9,8.
Angka 4,2 itu **berat**, bukan cacah. Sistem belum punya tempat untuk menyimpannya.
> **Catatan satuan.** RFC ini tidak mengasumsikan satuan tertentu. Satuan produk
> ditentukan `products.unit_id` yang merujuk tabel `units` — bisa ons, kg, gram, atau
> apa pun yang didefinisikan organisasi. Contoh memakai **ons** karena itu kasus yang
> sedang dikerjakan; tidak ada bagian desain ini yang bergantung padanya.
---
## 2. Keputusan Inti
**Satu penimbangan = satu baris `order_items`.**
| | Baris 1 | Baris 2 |
|---|---|---|
| Ikan Tude 4,2 ons | `quantity = 1`, `weight = 4.2` | |
| Ikan Tude 5,6 ons | | `quantity = 1`, `weight = 5.6` |
`quantity` tetap `INTEGER` dan tetap berarti "berapa banyak barang". Berat masuk ke
kolom baru. Dua baris tidak pernah digabung menjadi `9.8`, karena keduanya memang dua
ikan yang berbeda.
### Kenapa bukan `quantity = 4.2`
Alternatif yang sempat dipertimbangkan adalah mengubah `quantity` menjadi
`DECIMAL(12,3)`. Model itu ditolak karena tiga alasan:
1. **Menghapus jejak barang.** `4.2` dan `5.6` yang digabung jadi `9.8` kehilangan
informasi bahwa ada dua ikan. Tidak bisa direkonstruksi.
2. **Merusak agregasi lintas produk.** `SUM(quantity)` untuk laporan
"total item terjual" akan menjumlahkan ons dengan porsi — angka tanpa arti, yang
bahkan berubah nilainya bila satuan produk diganti dari ons ke kg tanpa ada apa pun
yang berubah di dunia nyata.
3. **Membawa masalah presisi float ke seluruh sistem.** Perbandingan quantity dipakai
di void, refund, dan split bill. Dengan float, `1,4 + 1,4 + 1,4` tidak sama dengan
`4,2` — split bill "bagi rata bertiga" akan gagal menandai item lunas meski uang
sudah diterima penuh. Semua itu tidak terjadi bila `quantity` tetap integer.
Konsekuensi langsung dari keputusan ini: **tidak diperlukan helper perbandingan
epsilon.** Berat tidak pernah dibandingkan, hanya dikalikan.
---
## 3. Prinsip
**P1 — Baris transaksi adalah snapshot yang beku.**
`order_items` sudah menyimpan `unit_price` dan `unit_cost` sebagai salinan, bukan join
ke `products`. Satuan mendapat perlakuan sama: mengubah master data tidak boleh
mengubah arti transaksi yang sudah terjadi.
**P2 — Perhitungan harga baris hanya ada di satu tempat.**
Setelah RFC ini ada dua rumus (`quantity × harga` dan `weight × harga`). Tidak boleh
ada perkalian harga yang tersebar; semuanya memanggil satu fungsi.
**P3 — Harga tetap otoritas backend.**
Klien tidak pernah mengirim harga. Backend membacanya dari `products` /
`product_outlet_prices` seperti sekarang.
**P4 — Berat boleh dijumlahkan dalam satu produk, tidak boleh antar produk.**
`SUM(weight)` untuk satu produk bermakna ("terjual 47,3 ons"). Lintas produk dengan
satuan berbeda tidak bermakna.
---
## 4. Perubahan Skema
```sql
-- Products: cara jual
ALTER TABLE products
ADD COLUMN sell_by VARCHAR(20) NOT NULL DEFAULT 'unit'
CHECK (sell_by IN ('unit', 'weight'));
-- Order items: berat + snapshot satuan
ALTER TABLE order_items
ADD COLUMN weight DECIMAL(12,3),
ADD COLUMN unit_id UUID REFERENCES units(id) ON DELETE RESTRICT;
ALTER TABLE order_items
ADD CONSTRAINT chk_order_items_weight_positive
CHECK (weight IS NULL OR weight > 0),
ADD CONSTRAINT chk_order_items_weight_single_line
CHECK (weight IS NULL OR quantity = 1);
```
**Catatan:**
- `weight` **nullable**. `NULL` berarti produk satuan biasa — seluruh data lama valid
tanpa backfill, dan perilakunya tidak berubah sama sekali.
- `chk_order_items_weight_single_line` menegakkan keputusan §2 di level database:
baris berbobot selalu `quantity = 1`. Ini yang membuat `BillableQuantity()` tidak
ambigu dan membuat void otomatis bersifat utuh (§6).
- `quantity` **tidak berubah tipe**. `CHECK (quantity > 0)` yang sudah ada tetap
berlaku.
- `DECIMAL(12,3)` konsisten dengan `inventory_movements.quantity` yang sudah memakai
presisi sama.
- Tidak ada `weighed_unit`. Karena satu baris memang satu barang, "ikan curah" dan
"ikan per ekor" berperilaku identik — pembedaan itu tidak punya konsekuensi.
---
## 5. Perhitungan Harga
Satu-satunya tempat yang boleh mengalikan harga (P2):
```go
// BillableQuantity mengembalikan pengali harga untuk baris ini:
// berat bila produk dijual per timbangan, jumlah bila dijual per satuan.
// Baris berbobot dijamin quantity = 1 oleh constraint DB.
func (oi *OrderItem) BillableQuantity() float64 {
if oi.Weight != nil {
return *oi.Weight
}
return float64(oi.Quantity)
}
func (oi *OrderItem) CalculateTotalPrice() {
oi.TotalPrice = RoundMoney(oi.BillableQuantity() * oi.UnitPrice)
}
func (oi *OrderItem) CalculateTotalCost() {
oi.TotalCost = RoundMoney(oi.BillableQuantity() * oi.UnitCost)
}
```
`unit_price` tetap berarti **harga per satu satuan produk** (per ons). Tidak ada faktor
konversi yang menyelinap ke perhitungan uang.
### Titik yang harus diganti
Ini bagian paling berisiko dari RFC. Setiap perkalian harga yang terlewat akan
menghitung `1 × harga_per_ons` — ikan 4,2 ons ditagih seharga 1 ons. **Salah uang,
bukan salah tampilan**, dan tidak memicu error apa pun.
| Lokasi | Sekarang |
|---|---|
| `processor/order_processor.go:197-198` | buat order |
| `processor/order_processor.go:330-331` | tambah item ke order |
| `processor/order_processor.go:605-606` | jumlah & HPP yang di-void |
| `processor/order_processor.go:723` | jumlah refund |
| `processor/split_bill_processor.go:143` | hitung jumlah split |
| `processor/split_bill_processor.go:189` | catat pembayaran |
| `processor/split_bill_processor.go:231` | metadata pembayaran |
| `repository/order_item_repository.go:113` | jumlah void penuh |
Implementasi menemukan **lima titik tambahan** di luar daftar di atas, semuanya di jalur
inventory movement dan resep bahan yang tidak terlihat saat RFC ini ditulis:
| Lokasi | Status |
|---|---|
| `order_processor.go:1056` `createInventoryMovement` | mati (0 pemanggil), tetap diperbaiki |
| `order_processor.go:1354` `prepareProductInventoryMovement` | **hidup** |
| `order_processor.go:1420` `prepareIngredientRecipeItem` | **hidup** |
| `order_processor.go:1518` `prepareRefundProductInventoryMovement` | mati (0 pemanggil), tetap diperbaiki |
| `order_processor.go:1584` `prepareRefundedIngredientRecipeItem` | **hidup** |
Tiga yang hidup penting: tanpa perbaikan, konsumsi bahan untuk ikan 4,2 ons akan
dihitung sebagai 1 satuan resep.
### Verifikasi
```bash
grep -rn "Quantity) \* \|Quantity \* " --include=*.go internal/ \
| grep -iE "price|cost" | grep -v BillableQuantity | grep -v totalIngredientQuantity
```
Hasilnya **tidak kosong** — tersisa tujuh baris, semuanya sudah diperiksa dan aman:
- `mappers/inventory_movement_mapper.go:129` dan
`processor/inventory_movement_processor.go:69` — penyesuaian stok manual, bukan
baris order.
- `repository/order_item_repository.go:144,146,147,165,166` — cabang void sebagian,
yang baris berbobot tidak pernah jangkau karena dijaga `orderItem.IsWeighed()`.
Bila daftar ini bertambah di kemudian hari, baris barunya harus diperiksa satu per satu.
---
## 6. Void, Refund, Split Bill
**Tidak ada perubahan logika.** Ini konsekuensi menyenangkan dari `quantity` yang tetap
integer.
**Void.** `VoidOrderItem` (`repository/order_item_repository.go:104`) bercabang pada
`voidQuantity >= orderItem.Quantity`. Untuk baris berbobot, `quantity` dijamin `1` dan
`voidQuantity` minimal `1`, sehingga **selalu** masuk cabang void penuh. Cabang
pemecahan baris tidak pernah tersentuh, sehingga tidak mungkin lahir baris sisa
berbobot nol. Yang berubah hanya perhitungan `voidedAmount` di baris 113 (§5).
**Refund.** Sama — refund baris berbobot bersifat utuh. Hanya `refundAmount` di
`order_processor.go:723` yang perlu memakai `BillableQuantity()`.
**Split bill.** `payment_order_items.quantity` tetap `INTEGER`. Untuk baris berbobot
nilainya `0` atau `1` — bayar penuh atau tidak sama sekali. Seluruh perbandingan di
`split_bill_processor.go` tetap aritmatika bilangan bulat, sehingga masalah presisi
float tidak pernah muncul. Hanya perhitungan `itemAmount` (baris 143 dan 189) yang
berubah.
**Batasan yang diterima:** refund atau void **sebagian berat** (mengembalikan 1 ons
dari baris 4,2 ons) tidak didukung. Untuk barang yang sudah ditimbang dan diserahkan,
koreksi sebagian pada praktiknya berarti salah timbang — yang penanganan benarnya
adalah void baris itu lalu input ulang, bukan mengubah berat baris yang sudah tercatat.
Ini menjaga jejak audit tetap jujur.
---
## 7. Validasi & Tampilan
### 7.1 Aturan validasi
Divalidasi di processor saat membuat / menambah item, di mana produk sudah dimuat:
| `products.sell_by` | Aturan |
|---|---|
| `unit` | `weight` harus kosong. Bila dikirim → tolak. |
| `weight` | `weight` wajib ada dan `> 0`. `quantity` dipaksa `1`. |
`unit_id` di `order_items` diisi dari `products.unit_id` saat baris dibuat (P1) —
bukan dibaca lewat join saat ditampilkan.
Berat dibulatkan ke 3 desimal saat masuk, agar nilai tersimpan selalu sama dengan
nilai yang divalidasi.
### 7.2 Tampilan
`templates/daily_transaction.html:539` mencetak `{{$item.Quantity}}`. Untuk baris
berbobot ini akan menampilkan `1`, bukan `4,2 ons`. Perlu bercabang pada `weight`.
Response API menambah `weight` dan `unit` pada item, agar frontend dan struk dapat
menampilkan `4,2 ons × Rp 4.500` alih-alih `1 × Rp 4.500`.
---
## 8. Report
**Tidak ada perubahan yang wajib.** Karena `quantity` tetap integer dan tetap berarti
"berapa banyak barang":
- `SUM(oi.quantity)` sebagai `total_items` tetap bermakna dan tetap konsisten lintas
produk — 2 ikan tetap dihitung 2, bukan 9,8 ons.
- `QuantitySold` tetap `int64`. Tidak ada pemotongan pecahan.
- `average_price = SUM(total_price) / SUM(quantity)` menjadi "rata-rata harga per
ekor", yang tetap merupakan angka bermakna.
**Tambahan opsional** — melaporkan berat terjual, hanya pada laporan **per produk**
(P4):
```sql
COALESCE(SUM(oi.weight), 0) AS weight_sold
```
Tidak boleh dipakai pada agregat lintas produk, karena akan menjumlahkan satuan yang
berbeda.
---
## 9. Di Luar Scope
**Pengurangan stok otomatis.** `adjustInventoryWithTransaction`
(`order_processor.go:1177`) dan `adjustIngredientInventoryWithTransaction`
(`order_processor.go:920`) terdefinisi tetapi **tidak pernah dipanggil dari mana pun** —
sudah diverifikasi se-repo. Endpoint CRUD inventory berfungsi; pengurangan stok saat
penjualan tidak tersambung.
Konsekuensi untuk RFC ini: `inventory.quantity` yang masih `int` tidak menghalangi
apa pun.
Catatan untuk nanti bila jalur stok disambungkan:
- Stok produk timbangan harus berkurang sebesar `weight`, bukan `quantity` — kalau
tidak, menjual ikan 4,2 ons hanya mengurangi stok sebanyak 1.
- `inventory.quantity` perlu menjadi `DECIMAL(12,3)` lebih dulu. Biayanya hampir nol
sekarang (3 call site, tanpa data historis); jauh lebih mahal setelah berjalan.
- `order_processor.go:946` berisi `deltaInt := int(delta)` yang memotong pecahan.
Kode ini mati, jadi bukan kebocoran aktif — tetapi bila disambungkan tanpa
diperbaiki, konsumsi bahan di bawah 1 unit akan hilang diam-diam.
Kedua fungsi mati itu sebaiknya **dihapus atau disambungkan**, jangan dibiarkan
menggantung — komentar di dalamnya ditulis seolah-olah aktif.
---
## 10. Temuan Sampingan: `unit_price` pada request diabaikan
`CreateOrderItemRequest.UnitPrice` (`contract/order_contract.go:46`) berkomentar
*"Optional, will use database price if not provided"*. Kenyataannya field ini **tidak
pernah dipakai** — satu-satunya yang menyentuhnya adalah validasi `< 0` di
`service/order_service.go:431` dan `:474`. Processor selalu membaca harga dari
`products` / `product_outlet_prices`.
Perilaku sekarang sudah benar dan sesuai P3. Yang salah hanya komentarnya, yang
menyiratkan klien bisa mengirim harga. Sebaiknya field itu **dihapus** dari contract,
atau komentarnya dikoreksi menjadi keterangan bahwa harga selalu diambil dari database.
Dibiarkan seperti sekarang, ini mengundang frontend mengirim harga dan menyangka
berhasil, padahal diabaikan diam-diam.
---
## 11. Urutan Implementasi
1. **Migrasi skema** (§4). Aman: semua kolom nullable atau ber-default, data lama
tidak tersentuh.
2. **`BillableQuantity()` + `CalculateTotalPrice()` / `CalculateTotalCost()`** (§5).
3. **Ganti 8 titik perkalian harga** (§5) lalu jalankan dua `grep` verifikasi.
4. **Field kontrak**: `weight` pada request order & self-order, `weight` + `unit` pada
response.
5. **Validasi `sell_by`** (§7.1).
6. **Template & tampilan struk** (§7.2).
7. *(Opsional)* `weight_sold` pada laporan per produk (§8).
Langkah 1-4 membuat produk timbangan dapat dijual dengan harga yang benar. Langkah 5
mencegah data tidak konsisten masuk. Langkah 6 membuat struk terbaca benar.
---
## 12. Risiko
| Risiko | Dampak | Mitigasi |
|---|---|---|
| Satu titik perkalian harga terlewat | Ikan 4,2 ons ditagih seharga 1 ons — salah uang, tanpa error | Dua `grep` verifikasi di §5; uji satu order timbangan lewat setiap jalur (create, tambah item, void, refund, split bill) |
| `weight` dikirim untuk produk `unit` | Harga baris salah total | Validasi §7.1 + constraint DB |
| `quantity > 1` pada baris berbobot | `BillableQuantity()` ambigu | Dicegah `chk_order_items_weight_single_line` di level DB |
| Klien lama tidak mengirim `weight` | Produk timbangan ditagih 1 satuan | Validasi §7.1 menolak, bukan mendiamkan |
| Struk menampilkan `1` alih-alih `4,2 ons` | Pelanggan bingung, kasir kehilangan kepercayaan | §7.2 |
---
## 13. Pertanyaan Terbuka
1. **Pembulatan uang — diputuskan sementara, perlu konfirmasi.** `RoundMoney`
membulatkan ke **2 desimal**, mengikuti presisi kolom `decimal(10,2)` yang sudah
dipakai semua nilai uang. Jadi `4,237 ons × Rp 4.500` tersimpan `Rp 19.066,50`.
Ini pilihan paling tidak mengejutkan dan konsisten dengan data lama, tetapi **bukan**
pembulatan ke rupiah utuh. Bila kasir harus menerima uang dalam rupiah penuh (atau
kelipatan Rp 100/500), ubah `RoundMoney` di `entities/order_item.go` — satu tempat,
dan lakukan **sebelum** ada transaksi timbangan, karena setelahnya data lama dan
baru akan mengikuti aturan berbeda.
2. **Presisi input berat.** Apakah `4,237 ons` (resolusi 0,1 gram) valid, atau input
harus dibatasi ke kelipatan tertentu sesuai resolusi timbangan? Bila perlu dibatasi,
tambahkan `products.min_weight_increment`.
3. **Sumber angka timbangan** — kasir mengetik manual atau timbangan tersambung? Bila
tersambung, ada urusan tara dan pembacaan stabil yang berada di luar RFC ini.
+2
View File
@@ -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
+4
View File
@@ -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=
+115 -17
View File
@@ -31,6 +31,8 @@ type App struct {
router *router.Router
shutdown chan os.Signal
omsetScheduler *service.OmsetMilestoneScheduler
walletRecon *service.WalletReconciliationJob
earningRetry *service.EarningBackfillJob
}
func NewApp(db *gorm.DB, redisClient *redis.Client) *App {
@@ -53,6 +55,15 @@ 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)
services := a.initServices(processors, repos, cfg)
validators := a.initValidators()
middleware := a.initMiddleware(services, cfg)
@@ -142,6 +153,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 +172,12 @@ 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)
}
engine := a.router.Init()
@@ -192,6 +217,12 @@ 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()
}
close(a.shutdown)
}
@@ -247,6 +278,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 {
@@ -302,6 +336,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),
}
}
@@ -350,14 +387,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 +434,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),
@@ -388,21 +455,32 @@ func (a *App) initProcessors(cfg *config.Config, repos *repositories) *processor
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), repos.txManager),
}
}
@@ -445,6 +523,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 {
@@ -480,7 +565,7 @@ func (a *App) initServices(processors *processors, repos *repositories, cfg *con
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 +611,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 +663,7 @@ type validators struct {
productOutletPriceValidator *validator.ProductOutletPriceValidatorImpl
expenseValidator *validator.ExpenseValidatorImpl
cashAdvanceValidator *validator.CashAdvanceValidatorImpl
walletValidator *validator.WalletValidatorImpl
}
func (a *App) initValidators() *validators {
@@ -604,22 +697,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,
+20 -6
View File
@@ -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
+71
View File
@@ -0,0 +1,71 @@
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"
)
// Units of loyalty.{point,coin}.expiry_unit.
const (
LoyaltyExpiryUnitDay = "DAY"
LoyaltyExpiryUnitMonth = "MONTH"
)
// 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)
)
+3
View File
@@ -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
+17
View File
@@ -0,0 +1,17 @@
package constants
// SellBy describes how a product's quantity is expressed on an order line.
type SellBy = string
const (
// SellByUnit is the default: the line counts discrete items (2 portions, 3 bottles).
SellByUnit SellBy = "unit"
// SellByWeight means the line carries a weighed amount. One weighing is one line,
// so quantity stays 1 and the measured value lives in order_items.weight.
SellByWeight SellBy = "weight"
)
// IsValidSellBy reports whether s is a supported sell_by value.
func IsValidSellBy(s string) bool {
return s == SellByUnit || s == SellByWeight
}
+44
View File
@@ -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"
)
+8
View File
@@ -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 {
@@ -198,6 +204,7 @@ type ProductAnalyticsData struct {
CategoryName string `json:"category_name"`
CategoryOrder int `json:"category_order"`
QuantitySold int64 `json:"quantity_sold"`
WeightSold float64 `json:"weight_sold"`
Revenue float64 `json:"revenue"`
AveragePrice float64 `json:"average_price"`
OrderCount int64 `json:"order_count"`
@@ -324,6 +331,7 @@ type ParentCategoryAnalyticsProductData struct {
ProductSku string `json:"product_sku"`
ProductPrice float64 `json:"product_price"`
QuantitySold int64 `json:"quantity_sold"`
WeightSold float64 `json:"weight_sold"`
Revenue float64 `json:"revenue"`
AveragePrice float64 `json:"average_price"`
OrderCount int64 `json:"order_count"`
+5 -5
View File
@@ -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"`
@@ -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"`
}
@@ -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"`
}
+15 -10
View File
@@ -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"`
}
+63 -43
View File
@@ -40,13 +40,16 @@ type UpdateOrderRequest struct {
}
type CreateOrderItemRequest struct {
ProductID uuid.UUID `json:"product_id" validate:"required"`
ProductVariantID *uuid.UUID `json:"product_variant_id,omitempty"`
Quantity int `json:"quantity" validate:"required,min=1"`
UnitPrice *float64 `json:"unit_price,omitempty" validate:"omitempty,min=0"` // Optional, will use database price if not provided
Modifiers []map[string]interface{} `json:"modifiers,omitempty"`
Notes *string `json:"notes,omitempty" validate:"omitempty,max=500"`
Metadata map[string]interface{} `json:"metadata,omitempty"`
ProductID uuid.UUID `json:"product_id" validate:"required"`
ProductVariantID *uuid.UUID `json:"product_variant_id,omitempty"`
Quantity int `json:"quantity" validate:"required,min=1"`
// Weight is required for products with sell_by = "weight" and must be absent otherwise.
// One weighing is one line, so quantity stays 1 and the line is priced weight * unit_price.
Weight *float64 `json:"weight,omitempty" validate:"omitempty,gt=0"`
UnitPrice *float64 `json:"unit_price,omitempty" validate:"omitempty,min=0"` // Ignored: price always comes from the database
Modifiers []map[string]interface{} `json:"modifiers,omitempty"`
Notes *string `json:"notes,omitempty" validate:"omitempty,max=500"`
Metadata map[string]interface{} `json:"metadata,omitempty"`
}
type UpdateOrderItemRequest struct {
@@ -89,29 +92,38 @@ 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 {
ID uuid.UUID `json:"id"`
OrderID uuid.UUID `json:"order_id"`
ProductID uuid.UUID `json:"product_id"`
ProductName string `json:"product_name"`
ProductVariantID *uuid.UUID `json:"product_variant_id"`
ProductVariantName *string `json:"product_variant_name,omitempty"`
CategoryID *uuid.UUID `json:"category_id,omitempty"`
CategoryName *string `json:"category_name,omitempty"`
Quantity int `json:"quantity"`
UnitPrice float64 `json:"unit_price"`
TotalPrice float64 `json:"total_price"`
Modifiers []map[string]interface{} `json:"modifiers"`
Notes *string `json:"notes,omitempty"`
Metadata map[string]interface{} `json:"metadata,omitempty"`
Status string `json:"status"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
PrinterType string `json:"printer_type"`
PrintToChecker bool `json:"print_to_checker"`
PaidQuantity int `json:"paid_quantity"`
ID uuid.UUID `json:"id"`
OrderID uuid.UUID `json:"order_id"`
ProductID uuid.UUID `json:"product_id"`
ProductName string `json:"product_name"`
ProductVariantID *uuid.UUID `json:"product_variant_id"`
ProductVariantName *string `json:"product_variant_name,omitempty"`
CategoryID *uuid.UUID `json:"category_id,omitempty"`
CategoryName *string `json:"category_name,omitempty"`
Quantity int `json:"quantity"`
// Weight is set only for products sold by weight; the line is priced weight * unit_price.
Weight *float64 `json:"weight,omitempty"`
UnitID *uuid.UUID `json:"unit_id,omitempty"`
UnitName *string `json:"unit_name,omitempty"`
UnitAbbreviation *string `json:"unit_abbreviation,omitempty"`
UnitPrice float64 `json:"unit_price"`
TotalPrice float64 `json:"total_price"`
Modifiers []map[string]interface{} `json:"modifiers"`
Notes *string `json:"notes,omitempty"`
Metadata map[string]interface{} `json:"metadata,omitempty"`
Status string `json:"status"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
PrinterType string `json:"printer_type"`
PrintToChecker bool `json:"print_to_checker"`
PaidQuantity int `json:"paid_quantity"`
}
type ListOrdersQuery struct {
@@ -174,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"`
@@ -192,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"`
+8 -6
View File
@@ -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 {
+6
View File
@@ -18,6 +18,8 @@ type CreateProductRequest struct {
ImageURL *string `json:"image_url,omitempty" validate:"omitempty,max=500"`
PrinterType *string `json:"printer_type,omitempty" validate:"omitempty,max=50"`
PrintToChecker *bool `json:"print_to_checker,omitempty"`
UnitID *uuid.UUID `json:"unit_id,omitempty"`
SellBy *string `json:"sell_by,omitempty" validate:"omitempty,oneof=unit weight"`
Metadata map[string]interface{} `json:"metadata,omitempty"`
IsActive *bool `json:"is_active,omitempty"`
Variants []CreateProductVariantRequest `json:"variants,omitempty"`
@@ -38,6 +40,8 @@ type UpdateProductRequest struct {
ImageURL *string `json:"image_url,omitempty" validate:"omitempty,max=500"`
PrinterType *string `json:"printer_type,omitempty" validate:"omitempty,max=50"`
PrintToChecker *bool `json:"print_to_checker,omitempty"`
UnitID *uuid.UUID `json:"unit_id,omitempty"`
SellBy *string `json:"sell_by,omitempty" validate:"omitempty,oneof=unit weight"`
Metadata map[string]interface{} `json:"metadata,omitempty"`
IsActive *bool `json:"is_active,omitempty"`
ReorderLevel *int `json:"reorder_level,omitempty" validate:"omitempty,min=0"`
@@ -73,6 +77,8 @@ type ProductResponse struct {
BusinessType string `json:"business_type"`
ImageURL *string `json:"image_url"`
PrinterType string `json:"printer_type"`
UnitID *uuid.UUID `json:"unit_id,omitempty"`
SellBy string `json:"sell_by"`
PrintToChecker bool `json:"print_to_checker"`
Metadata map[string]interface{} `json:"metadata"`
IsActive bool `json:"is_active"`
+1
View File
@@ -58,6 +58,7 @@ type SelfOrderCreateOrderItem struct {
ProductID uuid.UUID `json:"product_id" validate:"required"`
ProductVariantID *uuid.UUID `json:"product_variant_id,omitempty"`
Quantity int `json:"quantity" validate:"required,min=1"`
Weight *float64 `json:"weight,omitempty" validate:"omitempty,gt=0"`
Notes *string `json:"notes,omitempty"`
}
+5 -3
View File
@@ -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"`
}
+31
View File
@@ -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"`
}
+12 -9
View File
@@ -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
@@ -114,6 +116,7 @@ type ProductAnalytics struct {
CategoryName string `json:"category_name"`
CategoryOrder int `json:"category_order"`
QuantitySold int64 `json:"quantity_sold"`
WeightSold float64 `json:"weight_sold"`
Revenue float64 `json:"revenue"`
AveragePrice float64 `json:"average_price"`
OrderCount int64 `json:"order_count"`
@@ -172,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 {
+23 -2
View File
@@ -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"
)
+18
View File
@@ -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(""))
}
+6
View File
@@ -44,6 +44,12 @@ func GetAllEntities() []interface{} {
&ProductOutletPrice{},
&Expense{},
&CashAdvance{},
// Wallet entities
&CustomerWallet{},
&WalletTransaction{},
&WalletLot{},
&WalletLotAllocation{},
&LoyaltySettingChange{},
}
}
+1 -1
View File
@@ -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"`
@@ -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"
}
+54 -1
View File
@@ -4,6 +4,7 @@ import (
"database/sql/driver"
"encoding/json"
"errors"
"math"
"time"
"github.com/google/uuid"
@@ -47,6 +48,8 @@ type OrderItem struct {
ProductID uuid.UUID `gorm:"type:uuid;not null;index" json:"product_id" validate:"required"`
ProductVariantID *uuid.UUID `gorm:"type:uuid;index" json:"product_variant_id"`
Quantity int `gorm:"not null" json:"quantity" validate:"required,min=1"`
Weight *float64 `gorm:"type:decimal(12,3)" json:"weight,omitempty"`
UnitID *uuid.UUID `gorm:"type:uuid;index" json:"unit_id,omitempty"`
UnitPrice float64 `gorm:"type:decimal(10,2);not null" json:"unit_price" validate:"required,min=0"`
TotalPrice float64 `gorm:"type:decimal(10,2);not null" json:"total_price" validate:"required,min=0"`
UnitCost float64 `gorm:"type:decimal(10,2);default:0.00" json:"unit_cost"`
@@ -68,6 +71,7 @@ type OrderItem struct {
Order Order `gorm:"foreignKey:OrderID" json:"order,omitempty"`
Product Product `gorm:"foreignKey:ProductID" json:"product,omitempty"`
ProductVariant *ProductVariant `gorm:"foreignKey:ProductVariantID" json:"product_variant,omitempty"`
Unit *Unit `gorm:"foreignKey:UnitID" json:"unit,omitempty"`
}
func (oi *OrderItem) BeforeCreate(tx *gorm.DB) error {
@@ -81,8 +85,57 @@ func (OrderItem) TableName() string {
return "order_items"
}
// IsWeighed reports whether this line was sold by weight rather than by count.
func (oi *OrderItem) IsWeighed() bool {
return oi.Weight != nil
}
// BillableQuantity is the multiplier for unit price and unit cost on this line:
// the weighed amount for weight-based products, the item count otherwise.
//
// This is the ONLY place that decides between the two. Every price or cost
// calculation must go through it — multiplying by Quantity directly would bill a
// 4.2 ons fish as a single ons.
//
// Weighed lines are pinned to quantity = 1 by chk_order_items_weight_single_line,
// so there is no ambiguity between counting and weighing.
func (oi *OrderItem) BillableQuantity() float64 {
if oi.Weight != nil {
return *oi.Weight
}
return float64(oi.Quantity)
}
// BillableQuantityFor is BillableQuantity for a partial action on this line, such as
// voiding or refunding `units` of it.
//
// Weighed lines are always acted on in full — quantity is 1, so any void or refund
// covers the whole weighing — hence the full weight is returned regardless of units.
func (oi *OrderItem) BillableQuantityFor(units int) float64 {
if oi.Weight != nil {
return *oi.Weight
}
return float64(units)
}
// RoundMoney rounds to the 2 decimals that every monetary column stores, so the
// value written back always matches what the database keeps.
func RoundMoney(amount float64) float64 {
return math.Round(amount*100) / 100
}
// RoundWeight rounds to the 3 decimals of order_items.weight, so a validated value
// is identical to the stored one.
func RoundWeight(weight float64) float64 {
return math.Round(weight*1000) / 1000
}
func (oi *OrderItem) CalculateTotalPrice() {
oi.TotalPrice = float64(oi.Quantity) * oi.UnitPrice
oi.TotalPrice = RoundMoney(oi.BillableQuantity() * oi.UnitPrice)
}
func (oi *OrderItem) CalculateTotalCost() {
oi.TotalCost = RoundMoney(oi.BillableQuantity() * oi.UnitCost)
}
func (oi *OrderItem) CanBeModified() bool {
+104
View File
@@ -0,0 +1,104 @@
package entities
import "testing"
func weightPtr(v float64) *float64 { return &v }
func TestBillableQuantity(t *testing.T) {
tests := []struct {
name string
item OrderItem
want float64
}{
{"unit line counts items", OrderItem{Quantity: 3}, 3},
{"weighed line uses the weight", OrderItem{Quantity: 1, Weight: weightPtr(4.2)}, 4.2},
{"weight of zero is still a weighed line", OrderItem{Quantity: 1, Weight: weightPtr(0)}, 0},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := tt.item.BillableQuantity(); got != tt.want {
t.Errorf("BillableQuantity() = %v, want %v", got, tt.want)
}
})
}
}
// A weighed line is voided or refunded whole, so the units asked for must not shrink
// the amount: refunding "1" of a 4.2 ons line refunds all 4.2 ons.
func TestBillableQuantityForIgnoresUnitsOnWeighedLines(t *testing.T) {
weighed := OrderItem{Quantity: 1, Weight: weightPtr(5.6)}
if got := weighed.BillableQuantityFor(1); got != 5.6 {
t.Errorf("weighed BillableQuantityFor(1) = %v, want 5.6", got)
}
counted := OrderItem{Quantity: 3}
if got := counted.BillableQuantityFor(2); got != 2 {
t.Errorf("unit BillableQuantityFor(2) = %v, want 2", got)
}
}
// The regression this whole feature exists to prevent: a 4.2 ons fish priced per ons
// must not be billed as a single ons.
func TestCalculateTotalPriceForWeighedLine(t *testing.T) {
item := OrderItem{Quantity: 1, Weight: weightPtr(4.2), UnitPrice: 4500, UnitCost: 3000}
item.CalculateTotalPrice()
item.CalculateTotalCost()
if item.TotalPrice != 18900 {
t.Errorf("TotalPrice = %v, want 18900", item.TotalPrice)
}
if item.TotalCost != 12600 {
t.Errorf("TotalCost = %v, want 12600", item.TotalCost)
}
}
func TestCalculateTotalPriceForUnitLine(t *testing.T) {
item := OrderItem{Quantity: 3, UnitPrice: 25000, UnitCost: 10000}
item.CalculateTotalPrice()
item.CalculateTotalCost()
if item.TotalPrice != 75000 {
t.Errorf("TotalPrice = %v, want 75000", item.TotalPrice)
}
if item.TotalCost != 30000 {
t.Errorf("TotalCost = %v, want 30000", item.TotalCost)
}
}
// Sub-rupiah residue must not survive into a decimal(10,2) column.
func TestCalculateTotalPriceRoundsToStoredPrecision(t *testing.T) {
item := OrderItem{Quantity: 1, Weight: weightPtr(4.237), UnitPrice: 4500}
item.CalculateTotalPrice()
if item.TotalPrice != 19066.5 {
t.Errorf("TotalPrice = %v, want 19066.5", item.TotalPrice)
}
}
func TestIsWeighed(t *testing.T) {
if (&OrderItem{Quantity: 1}).IsWeighed() {
t.Error("unit line reported as weighed")
}
if !(&OrderItem{Quantity: 1, Weight: weightPtr(1.5)}).IsWeighed() {
t.Error("weighed line reported as unit")
}
}
func TestRoundWeight(t *testing.T) {
tests := []struct {
in float64
want float64
}{
{4.2, 4.2},
{4.2374, 4.237},
{4.2375, 4.238},
{0.0004, 0},
}
for _, tt := range tests {
if got := RoundWeight(tt.in); got != tt.want {
t.Errorf("RoundWeight(%v) = %v, want %v", tt.in, got, tt.want)
}
}
}
+14 -7
View File
@@ -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"`
+1
View File
@@ -20,6 +20,7 @@ type Product struct {
ImageURL *string `gorm:"size:500" json:"image_url"`
PrinterType string `gorm:"size:50;default:'kitchen'" json:"printer_type"`
UnitID *uuid.UUID `gorm:"type:uuid;index" json:"unit_id"`
SellBy string `gorm:"size:20;default:'unit'" json:"sell_by"`
HasIngredients bool `gorm:"default:false" json:"has_ingredients"`
Metadata Metadata `gorm:"type:jsonb;default:'{}'" json:"metadata"`
IsActive bool `gorm:"default:true" json:"is_active"`
+113
View File
@@ -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"
}
@@ -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")
}
@@ -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")
}
+151
View File
@@ -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")
}
+56 -3
View File
@@ -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,51 @@ 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
}
}
+218
View File
@@ -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
}
@@ -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")
}
@@ -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)
}
}
@@ -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")
}
@@ -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"])
}
+13
View File
@@ -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
}
@@ -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
+28
View File
@@ -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")
}
+1
View File
@@ -344,6 +344,7 @@ func (h *SelfOrderHandler) CreateOrder(c *gin.Context) {
ProductID: item.ProductID,
ProductVariantID: item.ProductVariantID,
Quantity: item.Quantity,
Weight: item.Weight,
Notes: item.Notes,
})
}
+10 -1
View File
@@ -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
}
+203
View File
@@ -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, 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")
}
+99
View File
@@ -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")
}
+4 -4
View File
@@ -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,
+2 -2
View File
@@ -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,
}
}
+13
View File
@@ -115,12 +115,23 @@ func OrderItemEntityToResponse(item *entities.OrderItem, outletID uuid.UUID) *mo
}
}
// Unit is only meaningful for weighed lines, but carry it whenever it was captured.
var unitName, unitAbbreviation *string
if item.Unit != nil {
unitName = &item.Unit.Name
unitAbbreviation = item.Unit.Abbreviation
}
response := &models.OrderItemResponse{
ID: item.ID,
OrderID: item.OrderID,
ProductID: item.ProductID,
ProductVariantID: item.ProductVariantID,
Quantity: item.Quantity,
Weight: item.Weight,
UnitID: item.UnitID,
UnitName: unitName,
UnitAbbreviation: unitAbbreviation,
UnitPrice: item.UnitPrice,
TotalPrice: item.TotalPrice,
UnitCost: item.UnitCost,
@@ -178,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,
@@ -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,
+23
View File
@@ -25,6 +25,9 @@ func ProductEntityToModel(entity *entities.Product) *models.Product {
BusinessType: constants.BusinessType(entity.BusinessType),
ImageURL: entity.ImageURL,
PrinterType: entity.PrinterType,
UnitID: entity.UnitID,
SellBy: entity.SellBy,
HasIngredients: entity.HasIngredients,
Metadata: map[string]interface{}(entity.Metadata),
IsActive: entity.IsActive,
CreatedAt: entity.CreatedAt,
@@ -49,6 +52,9 @@ func ProductModelToEntity(model *models.Product) *entities.Product {
BusinessType: string(model.BusinessType),
ImageURL: model.ImageURL,
PrinterType: model.PrinterType,
UnitID: model.UnitID,
SellBy: model.SellBy,
HasIngredients: model.HasIngredients,
Metadata: entities.Metadata(model.Metadata),
IsActive: model.IsActive,
CreatedAt: model.CreatedAt,
@@ -76,6 +82,11 @@ func CreateProductRequestToEntity(req *models.CreateProductRequest) *entities.Pr
printerType = *req.PrinterType
}
sellBy := constants.SellByUnit
if constants.IsValidSellBy(req.SellBy) {
sellBy = req.SellBy
}
metadata := entities.Metadata{}
if req.Metadata != nil {
metadata = entities.Metadata(req.Metadata)
@@ -92,6 +103,8 @@ func CreateProductRequestToEntity(req *models.CreateProductRequest) *entities.Pr
BusinessType: businessType,
ImageURL: req.ImageURL,
PrinterType: printerType,
UnitID: req.UnitID,
SellBy: sellBy,
Metadata: metadata,
IsActive: true, // Default to active
}
@@ -140,6 +153,8 @@ func ProductEntityToResponse(entity *entities.Product) *models.ProductResponse {
BusinessType: constants.BusinessType(entity.BusinessType),
ImageURL: entity.ImageURL,
PrinterType: entity.PrinterType,
UnitID: entity.UnitID,
SellBy: entity.SellBy,
Metadata: map[string]interface{}(entity.Metadata),
IsActive: entity.IsActive,
CreatedAt: entity.CreatedAt,
@@ -185,6 +200,14 @@ func UpdateProductEntityFromRequest(entity *entities.Product, req *models.Update
entity.PrinterType = *req.PrinterType
}
if req.UnitID != nil {
entity.UnitID = req.UnitID
}
if req.SellBy != nil && constants.IsValidSellBy(*req.SellBy) {
entity.SellBy = *req.SellBy
}
if req.Metadata != nil {
if entity.Metadata == nil {
entity.Metadata = make(entities.Metadata)
+4 -2
View File
@@ -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
+8
View File
@@ -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")
}
+21 -8
View File
@@ -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
@@ -233,6 +244,7 @@ type ProductAnalyticsData struct {
CategoryName string `json:"category_name"`
CategoryOrder int `json:"category_order"`
QuantitySold int64 `json:"quantity_sold"`
WeightSold float64 `json:"weight_sold"`
Revenue float64 `json:"revenue"`
AveragePrice float64 `json:"average_price"`
OrderCount int64 `json:"order_count"`
@@ -359,6 +371,7 @@ type ParentCategoryAnalyticsProductData struct {
ProductSku string `json:"product_sku"`
ProductPrice float64 `json:"product_price"`
QuantitySold int64 `json:"quantity_sold"`
WeightSold float64 `json:"weight_sold"`
Revenue float64 `json:"revenue"`
AveragePrice float64 `json:"average_price"`
OrderCount int64 `json:"order_count"`
@@ -462,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"`
}
+5 -5
View File
@@ -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"`
+47
View File
@@ -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"`
}
+13
View File
@@ -109,7 +109,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"`
+7 -7
View File
@@ -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"`
}
+159
View File
@@ -0,0 +1,159 @@
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 how long one currency lasts once received. The expiry
// model is still open (note N4); these are only the stored settings.
type LoyaltyExpirySettings struct {
Enabled bool `json:"enabled"`
Period int64 `json:"period"`
// DAY or MONTH.
Unit string `json:"unit"`
EndOfMonth bool `json:"end_of_month"`
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"`
// 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"`
}
// 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
}
+32
View File
@@ -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)
}
+11 -1
View File
@@ -44,6 +44,8 @@ type OrderItem struct {
ProductID uuid.UUID
ProductVariantID *uuid.UUID
Quantity int
Weight *float64
UnitID *uuid.UUID
UnitPrice float64
TotalPrice float64
UnitCost float64
@@ -99,7 +101,8 @@ type CreateOrderItemRequest struct {
ProductID uuid.UUID `validate:"required"`
ProductVariantID *uuid.UUID `validate:"omitempty"`
Quantity int `validate:"required,min=1"`
UnitPrice *float64 `validate:"omitempty,min=0"` // Optional, will use database price if not provided
Weight *float64 `validate:"omitempty,gt=0"`
UnitPrice *float64 `validate:"omitempty,min=0"` // Ignored: price always comes from the database
Modifiers []map[string]interface{} `validate:"omitempty"`
Notes *string `validate:"omitempty,max=500"`
Metadata map[string]interface{} `validate:"omitempty"`
@@ -179,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 {
@@ -191,6 +197,10 @@ type OrderItemResponse struct {
CategoryID *uuid.UUID
CategoryName *string
Quantity int
Weight *float64
UnitID *uuid.UUID
UnitName *string
UnitAbbreviation *string
UnitPrice float64
TotalPrice float64
UnitCost float64
+7 -2
View File
@@ -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
+7 -5
View File
@@ -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 {
+4
View File
@@ -19,6 +19,7 @@ type Product struct {
BusinessType constants.BusinessType
ImageURL *string
PrinterType string
SellBy string
UnitID *uuid.UUID
HasIngredients bool
Metadata map[string]interface{}
@@ -52,6 +53,7 @@ type CreateProductRequest struct {
PrinterType *string `validate:"omitempty,max=50"`
PrintToChecker *bool `validate:"omitempty"`
UnitID *uuid.UUID `validate:"omitempty"`
SellBy string `validate:"omitempty,oneof=unit weight"`
HasIngredients bool `validate:"omitempty"`
Metadata map[string]interface{}
Variants []CreateProductVariantRequest `validate:"omitempty,dive"`
@@ -73,6 +75,7 @@ type UpdateProductRequest struct {
PrinterType *string `validate:"omitempty,max=50"`
PrintToChecker *bool `validate:"omitempty"`
UnitID *uuid.UUID `validate:"omitempty"`
SellBy *string `validate:"omitempty,oneof=unit weight"`
HasIngredients *bool `validate:"omitempty"`
Metadata map[string]interface{}
IsActive *bool
@@ -110,6 +113,7 @@ type ProductResponse struct {
BusinessType constants.BusinessType
ImageURL *string
PrinterType string
SellBy string
PrintToChecker bool
UnitID *uuid.UUID
HasIngredients bool
+3 -3
View File
@@ -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
+159
View File
@@ -0,0 +1,159 @@
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"`
}
+73
View File
@@ -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"`
}
+46
View File
@@ -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"`
}
+24 -7
View File
@@ -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,
@@ -322,6 +337,7 @@ func (p *AnalyticsProcessorImpl) GetProductAnalytics(ctx context.Context, req *m
CategoryName: data.CategoryName,
CategoryOrder: data.CategoryOrder,
QuantitySold: data.QuantitySold,
WeightSold: data.WeightSold,
Revenue: data.Revenue,
AveragePrice: data.AveragePrice,
OrderCount: data.OrderCount,
@@ -447,6 +463,7 @@ func (p *AnalyticsProcessorImpl) GetParentCategoryAnalyticsDetail(ctx context.Co
ProductSku: product.ProductSku,
ProductPrice: product.ProductPrice,
QuantitySold: product.QuantitySold,
WeightSold: product.WeightSold,
Revenue: product.Revenue,
AveragePrice: product.AveragePrice,
OrderCount: product.OrderCount,
+36 -2
View File
@@ -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)
}
+4 -4
View File
@@ -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,
@@ -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)
}
@@ -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)
}
}
@@ -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
}
@@ -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")
}
@@ -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 := &notifierFake{}
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)
}
+40 -126
View File
@@ -3,7 +3,6 @@ package processor
import (
"context"
"fmt"
"time"
"apskel-pos-be/internal/models"
"apskel-pos-be/internal/repository"
@@ -12,14 +11,14 @@ 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,
}
}
@@ -70,159 +69,74 @@ func (p *CustomerPointsProcessor) DeductPoints(ctx context.Context, customerID u
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
+85
View File
@@ -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))
}
@@ -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))
}
+198
View File
@@ -0,0 +1,198 @@
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)
}
// EarningProcessor credits EnakPoint and EnakCoin for paid orders
// (docs/prd-point-coin.md F3).
type EarningProcessor struct {
orders repository.EarningRepository
settings outletSettingsReader
wallet *WalletProcessor
tx TxRunner
}
func NewEarningProcessor(orders repository.EarningRepository, settings outletSettingsReader, wallet *WalletProcessor, tx TxRunner) *EarningProcessor {
return &EarningProcessor{orders: orders, settings: settings, wallet: wallet, tx: tx}
}
// 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
}
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 never expire until the expiry model is decided (F12, note N4).
}})
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
}
@@ -0,0 +1,229 @@
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 outletSettingsReader
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, &regular, "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, &regular, "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, &regular, "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, &regular, "completed", true, 50000, 0), EarningSkipVoid},
"unpaid": {newOrder(earningOutlet, &regular, "pending", false, 50000, 0), EarningSkipNotPaid},
"outlet not earning": {newOrder(quietOutlet, &regular, "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, &regular, "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)
}
+167
View File
@@ -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)
}
@@ -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
}
@@ -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")
}
+155 -89
View File
@@ -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 {
@@ -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)
}
@@ -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))
})
}
@@ -0,0 +1,442 @@
package processor
import (
"context"
"errors"
"fmt"
"strconv"
"strings"
"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
}
func NewLoyaltySettingsProcessor(repo repository.LoyaltySettingsRepository, tx TxRunner) *LoyaltySettingsProcessor {
return &LoyaltySettingsProcessor{repo: repo, tx: tx}
}
// 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(&current), raw, "outlet "+outletID.String())
changes, err = p.apply(ctx, organizationID, &outletID, changedBy, raw,
outletLoyaltyFields(&current), 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.
func (p *LoyaltySettingsProcessor) UpdateOrganization(ctx context.Context, organizationID, changedBy uuid.UUID, settings models.OrganizationLoyaltySettings) ([]models.LoyaltySettingChange, error) {
if err := validateLoyaltyFields(organizationLoyaltyFields(&settings)); err != nil {
return nil, err
}
var changes []models.LoyaltySettingChange
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(&current), raw, "organization "+organizationID.String())
changes, err = p.apply(ctx, organizationID, nil, changedBy, raw,
organizationLoyaltyFields(&current), organizationLoyaltyFields(&settings),
func(key string, value *string) error {
return p.repo.SetOrganizationValue(ctx, organizationID, key, value)
})
return err
})
return changes, err
}
// 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),
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 },
}
}
// 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, without writing anything.
func (p *LoyaltySettingsProcessor) PreviewOrganization(ctx context.Context, organizationID uuid.UUID, settings models.OrganizationLoyaltySettings) ([]models.LoyaltySettingChange, error) {
if err := validateLoyaltyFields(organizationLoyaltyFields(&settings)); err != nil {
return nil, err
}
raw, err := p.repo.GetOrganizationValues(ctx, organizationID)
if err != nil {
return nil, err
}
var current models.OrganizationLoyaltySettings
loadLoyaltyFields(organizationLoyaltyFields(&current), raw, "organization "+organizationID.String())
rows := diffLoyaltyFields(organizationID, nil, uuid.Nil, raw, organizationLoyaltyFields(&current), organizationLoyaltyFields(&settings))
changes := make([]models.LoyaltySettingChange, 0, len(rows))
for _, row := range rows {
changes = append(changes, loyaltySettingChangeModel(row))
}
return changes, nil
}
@@ -0,0 +1,322 @@
package processor
import (
"context"
"os"
"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/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
}
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, 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",
},
}
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)
}
// 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 },
} {
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)
}
+272
View File
@@ -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)
}
+314 -26
View File
@@ -5,7 +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"
@@ -18,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
@@ -108,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(
@@ -149,6 +288,33 @@ func NewOrderProcessorImpl(
}
}
// resolveLineQuantity reconciles the requested quantity and weight against how the
// product is sold, returning the values to store on the order line.
//
// For weight-based products a line is exactly one weighing, so quantity is pinned to 1
// and the weighed amount is what gets priced. This mirrors
// chk_order_items_weight_single_line in the database.
func resolveLineQuantity(product *entities.Product, quantity int, weight *float64) (int, *float64, error) {
if product.SellBy == constants.SellByWeight {
if weight == nil {
return 0, nil, fmt.Errorf("product %s is sold by weight and requires a weight", product.Name)
}
rounded := entities.RoundWeight(*weight)
if rounded <= 0 {
return 0, nil, fmt.Errorf("weight for product %s must be greater than 0", product.Name)
}
return 1, &rounded, nil
}
if weight != nil {
return 0, nil, fmt.Errorf("product %s is not sold by weight and must not carry a weight", product.Name)
}
if quantity < 1 {
return 0, nil, fmt.Errorf("quantity for product %s must be at least 1", product.Name)
}
return quantity, nil, nil
}
func (p *OrderProcessorImpl) CreateOrder(ctx context.Context, req *models.CreateOrderRequest, organizationID uuid.UUID) (*models.OrderResponse, error) {
orderNumber, err := p.orderRepo.GetNextOrderNumber(ctx, organizationID, req.OutletID)
if err != nil {
@@ -194,25 +360,29 @@ func (p *OrderProcessorImpl) CreateOrder(ctx context.Context, req *models.Create
}
}
itemTotalPrice := float64(itemReq.Quantity) * unitPrice
itemTotalCost := float64(itemReq.Quantity) * unitCost
subtotal += itemTotalPrice
totalCost += itemTotalCost
quantity, weight, err := resolveLineQuantity(product, itemReq.Quantity, itemReq.Weight)
if err != nil {
return nil, err
}
orderItem := &entities.OrderItem{
ProductID: itemReq.ProductID,
ProductVariantID: itemReq.ProductVariantID,
Quantity: itemReq.Quantity,
Quantity: quantity,
Weight: weight,
UnitID: product.UnitID,
UnitPrice: unitPrice,
TotalPrice: itemTotalPrice,
UnitCost: unitCost,
TotalCost: itemTotalCost,
Modifiers: entities.Modifiers(itemReq.Modifiers),
Notes: itemReq.Notes,
Metadata: entities.Metadata(itemReq.Metadata),
Status: entities.OrderItemStatusPending,
}
orderItem.CalculateTotalPrice()
orderItem.CalculateTotalCost()
subtotal += orderItem.TotalPrice
totalCost += orderItem.TotalCost
orderItems = append(orderItems, orderItem)
}
@@ -265,6 +435,7 @@ func (p *OrderProcessorImpl) CreateOrder(ctx context.Context, req *models.Create
}
response := mappers.OrderEntityToResponse(orderWithRelations)
p.attachEarnings(ctx, response)
return response, nil
}
@@ -327,26 +498,30 @@ func (p *OrderProcessorImpl) AddToOrder(ctx context.Context, orderID uuid.UUID,
}
}
itemTotalPrice := float64(itemReq.Quantity) * unitPrice
itemTotalCost := float64(itemReq.Quantity) * unitCost
newSubtotal += itemTotalPrice
newTotalCost += itemTotalCost
quantity, weight, err := resolveLineQuantity(product, itemReq.Quantity, itemReq.Weight)
if err != nil {
return nil, err
}
orderItem := &entities.OrderItem{
OrderID: orderID,
ProductID: itemReq.ProductID,
ProductVariantID: itemReq.ProductVariantID,
Quantity: itemReq.Quantity,
Quantity: quantity,
Weight: weight,
UnitID: product.UnitID,
UnitPrice: unitPrice,
TotalPrice: itemTotalPrice,
UnitCost: unitCost,
TotalCost: itemTotalCost,
Modifiers: entities.Modifiers(itemReq.Modifiers),
Notes: itemReq.Notes,
Metadata: entities.Metadata(itemReq.Metadata),
Status: entities.OrderItemStatusPending,
}
orderItem.CalculateTotalPrice()
orderItem.CalculateTotalCost()
newSubtotal += orderItem.TotalPrice
newTotalCost += orderItem.TotalCost
addedOrderItems = append(addedOrderItems, orderItem)
}
@@ -399,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,
@@ -458,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 {
@@ -465,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
}
@@ -475,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
}
@@ -536,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 {
@@ -602,8 +786,9 @@ func (p *OrderProcessorImpl) VoidOrder(ctx context.Context, req *models.VoidOrde
return fmt.Errorf("void quantity cannot exceed original quantity for item %d", itemVoid.OrderItemID)
}
voidedAmount := float64(itemVoid.Quantity) * orderItem.UnitPrice
voidedCost := float64(itemVoid.Quantity) * orderItem.UnitCost
billable := orderItem.BillableQuantityFor(itemVoid.Quantity)
voidedAmount := entities.RoundMoney(billable * orderItem.UnitPrice)
voidedCost := entities.RoundMoney(billable * orderItem.UnitCost)
totalVoidedAmount += voidedAmount
totalVoidedCost += voidedCost
@@ -655,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
}
@@ -677,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
@@ -720,7 +921,7 @@ func (p *OrderProcessorImpl) RefundOrder(ctx context.Context, id uuid.UUID, req
return fmt.Errorf("refund quantity cannot exceed original quantity")
}
refundAmount := float64(refundQuantity) * orderItem.UnitPrice
refundAmount := entities.RoundMoney(orderItem.BillableQuantityFor(refundQuantity) * orderItem.UnitPrice)
if itemRefund.RefundAmount != nil {
refundAmount = *itemRefund.RefundAmount
}
@@ -750,6 +951,7 @@ func (p *OrderProcessorImpl) RefundOrder(ctx context.Context, id uuid.UUID, req
}
}
p.onOrderRefunded(ctx, id)
return nil
}
@@ -767,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 {
@@ -781,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 {
@@ -805,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) {
@@ -1016,7 +1227,7 @@ func (p *OrderProcessorImpl) createInventoryMovement(ctx context.Context, item *
PreviousQuantity: float64(updatedInventory.Quantity + item.Quantity), // Add back the quantity that was subtracted
NewQuantity: float64(updatedInventory.Quantity),
UnitCost: item.UnitCost,
TotalCost: float64(item.Quantity) * item.UnitCost,
TotalCost: entities.RoundMoney(item.BillableQuantity() * item.UnitCost),
ReferenceType: func() *entities.InventoryMovementReferenceType {
t := entities.InventoryMovementReferenceTypePayment
return &t
@@ -1149,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 {
@@ -1170,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
}
@@ -1314,7 +1534,7 @@ func (p *OrderProcessorImpl) prepareProductInventoryMovement(item *entities.Orde
PreviousQuantity: float64(previousQuantity),
NewQuantity: float64(updatedInventory.Quantity),
UnitCost: item.UnitCost,
TotalCost: float64(item.Quantity) * item.UnitCost,
TotalCost: entities.RoundMoney(item.BillableQuantity() * item.UnitCost),
ReferenceType: func() *entities.InventoryMovementReferenceType {
t := entities.InventoryMovementReferenceTypePayment
return &t
@@ -1380,7 +1600,7 @@ type ingredientRecipeItem struct {
// prepareIngredientRecipeItem prepares data for a single ingredient recipe without making database calls
func (p *OrderProcessorImpl) prepareIngredientRecipeItem(ctx context.Context, recipe *entities.ProductRecipe, item *entities.OrderItem, order *entities.Order, payment *entities.Payment) (*ingredientRecipeItem, error) {
totalIngredientQuantity := recipe.Quantity * float64(item.Quantity)
totalIngredientQuantity := recipe.Quantity * item.BillableQuantity()
currentIngredient, err := p.ingredientRepo.GetByID(ctx, recipe.IngredientID, order.OrganizationID)
if err != nil {
@@ -1478,7 +1698,7 @@ func (p *OrderProcessorImpl) prepareRefundProductInventoryMovement(item *entitie
PreviousQuantity: float64(previousQuantity),
NewQuantity: float64(updatedInventory.Quantity),
UnitCost: item.UnitCost,
TotalCost: float64(refundedQuantity) * item.UnitCost,
TotalCost: entities.RoundMoney(item.BillableQuantityFor(refundedQuantity) * item.UnitCost),
ReferenceType: func() *entities.InventoryMovementReferenceType {
t := entities.InventoryMovementReferenceTypeRefund
return &t
@@ -1544,7 +1764,7 @@ func (p *OrderProcessorImpl) prepareRefundedIngredientRecipeData(ctx context.Con
// prepareRefundedIngredientRecipeItem prepares data for a single ingredient recipe restoration
func (p *OrderProcessorImpl) prepareRefundedIngredientRecipeItem(ctx context.Context, recipe *entities.ProductRecipe, item *entities.OrderItem, order *entities.Order, payment *entities.Payment, refundRatio float64, reason string, refundedBy uuid.UUID, refundAmount float64) (*ingredientRecipeItem, error) {
// Calculate total ingredient quantity needed based on order item quantity
totalIngredientQuantity := recipe.Quantity * float64(item.Quantity)
totalIngredientQuantity := recipe.Quantity * item.BillableQuantity()
// Get current ingredient details
currentIngredient, err := p.ingredientRepo.GetByID(ctx, recipe.IngredientID, order.OrganizationID)
@@ -1591,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
}
+106
View File
@@ -0,0 +1,106 @@
package processor
import (
"testing"
"apskel-pos-be/internal/constants"
"apskel-pos-be/internal/entities"
)
func fPtr(v float64) *float64 { return &v }
func TestResolveLineQuantity(t *testing.T) {
weightProduct := &entities.Product{Name: "Ikan Tude", SellBy: constants.SellByWeight}
unitProduct := &entities.Product{Name: "Nasi Goreng", SellBy: constants.SellByUnit}
tests := []struct {
name string
product *entities.Product
quantity int
weight *float64
wantQuantity int
wantWeight *float64
wantErr bool
}{
{
name: "weighed line is pinned to quantity 1",
// Mirrors chk_order_items_weight_single_line: even if a client sends 3,
// one weighing is one line.
product: weightProduct, quantity: 3, weight: fPtr(4.2),
wantQuantity: 1, wantWeight: fPtr(4.2),
},
{
name: "weight is rounded to stored precision",
product: weightProduct, quantity: 1, weight: fPtr(5.6004),
wantQuantity: 1, wantWeight: fPtr(5.6),
},
{
name: "weight product without a weight is rejected",
product: weightProduct, quantity: 1, weight: nil,
wantErr: true,
},
{
name: "weight that rounds away to zero is rejected",
product: weightProduct, quantity: 1, weight: fPtr(0.0004),
wantErr: true,
},
{
name: "unit line keeps its quantity and carries no weight",
product: unitProduct, quantity: 3, weight: nil,
wantQuantity: 3, wantWeight: nil,
},
{
name: "weight on a unit product is rejected",
// Otherwise the line would silently be priced by weight.
product: unitProduct, quantity: 1, weight: fPtr(4.2),
wantErr: true,
},
{
name: "non-positive quantity on a unit product is rejected",
product: unitProduct, quantity: 0, weight: nil,
wantErr: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
gotQty, gotWeight, err := resolveLineQuantity(tt.product, tt.quantity, tt.weight)
if tt.wantErr {
if err == nil {
t.Fatalf("expected an error, got quantity=%v weight=%v", gotQty, gotWeight)
}
return
}
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if gotQty != tt.wantQuantity {
t.Errorf("quantity = %v, want %v", gotQty, tt.wantQuantity)
}
switch {
case tt.wantWeight == nil && gotWeight != nil:
t.Errorf("weight = %v, want nil", *gotWeight)
case tt.wantWeight != nil && gotWeight == nil:
t.Errorf("weight = nil, want %v", *tt.wantWeight)
case tt.wantWeight != nil && *gotWeight != *tt.wantWeight:
t.Errorf("weight = %v, want %v", *gotWeight, *tt.wantWeight)
}
})
}
}
// A product created before this feature has sell_by defaulted to 'unit' by the
// migration, but a zero-valued struct must behave the same way.
func TestResolveLineQuantityTreatsEmptySellByAsUnit(t *testing.T) {
legacy := &entities.Product{Name: "Legacy"}
quantity, weight, err := resolveLineQuantity(legacy, 2, nil)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if quantity != 2 || weight != nil {
t.Errorf("got quantity=%v weight=%v, want quantity=2 weight=nil", quantity, weight)
}
}
+4
View File
@@ -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:
@@ -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
}
@@ -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")
}
+37 -2
View File
@@ -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

Some files were not shown because too many files have changed in this diff Show More