Reapply "feat(loyalty): EnakPoint & EnakCoin" (#32)

This reverts commit 4e24f9bbb0.
This commit is contained in:
efrilm
2026-09-30 15:31:44 +07:00
parent 4e24f9bbb0
commit 582dc75543
195 changed files with 20058 additions and 2177 deletions
+22 -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,
+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)
}
+47 -172
View File
@@ -3,7 +3,6 @@ package processor
import (
"context"
"fmt"
"time"
"apskel-pos-be/internal/models"
"apskel-pos-be/internal/repository"
@@ -12,217 +11,85 @@ import (
)
type CustomerPointsProcessor struct {
customerPointsRepo repository.CustomerPointsRepository
gameRepo *repository.GameRepository
walletQuery *WalletQueryProcessor
gameRepo *repository.GameRepository
}
func NewCustomerPointsProcessor(customerPointsRepo repository.CustomerPointsRepository, gameRepo *repository.GameRepository) *CustomerPointsProcessor {
func NewCustomerPointsProcessor(walletQuery *WalletQueryProcessor, gameRepo *repository.GameRepository) *CustomerPointsProcessor {
return &CustomerPointsProcessor{
customerPointsRepo: customerPointsRepo,
gameRepo: gameRepo,
walletQuery: walletQuery,
gameRepo: gameRepo,
}
}
// Existing gamification methods - placeholder implementations
func (p *CustomerPointsProcessor) CreateCustomerPoints(ctx context.Context, req *models.CreateCustomerPointsRequest) (*models.CustomerPointsResponse, error) {
// TODO: Implement this method
return nil, fmt.Errorf("not implemented")
}
func (p *CustomerPointsProcessor) GetCustomerPoints(ctx context.Context, id uuid.UUID) (*models.CustomerPointsResponse, error) {
// TODO: Implement this method
return nil, fmt.Errorf("not implemented")
}
func (p *CustomerPointsProcessor) GetCustomerPointsByCustomerID(ctx context.Context, customerID uuid.UUID) (*models.CustomerPointsResponse, error) {
// TODO: Implement this method
return nil, fmt.Errorf("not implemented")
}
func (p *CustomerPointsProcessor) ListCustomerPoints(ctx context.Context, query *models.ListCustomerPointsQuery) (*models.PaginatedCustomerPointsResponse, error) {
// Return empty paginated response for now
return &models.PaginatedCustomerPointsResponse{
Data: []models.CustomerPointsResponse{},
TotalCount: 0,
Page: 1,
Limit: 10,
TotalPages: 0,
}, nil
}
func (p *CustomerPointsProcessor) UpdateCustomerPoints(ctx context.Context, id uuid.UUID, req *models.UpdateCustomerPointsRequest) (*models.CustomerPointsResponse, error) {
// TODO: Implement this method
return nil, fmt.Errorf("not implemented")
}
func (p *CustomerPointsProcessor) DeleteCustomerPoints(ctx context.Context, id uuid.UUID) error {
// TODO: Implement this method
return fmt.Errorf("not implemented")
}
func (p *CustomerPointsProcessor) AddPoints(ctx context.Context, customerID uuid.UUID, points int64) (*models.CustomerPointsResponse, error) {
// TODO: Implement this method
return nil, fmt.Errorf("not implemented")
}
func (p *CustomerPointsProcessor) DeductPoints(ctx context.Context, customerID uuid.UUID, points int64) (*models.CustomerPointsResponse, error) {
// TODO: Implement this method
return nil, fmt.Errorf("not implemented")
}
// The three endpoints below are the customer app's balance screens. They read the
// EnakPoint & EnakCoin wallet; customer_points and customer_tokens are no longer used
// for balances (docs/prd-point-coin.md §9).
func (p *CustomerPointsProcessor) GetCustomerTotalPointsAPI(ctx context.Context, customerID string) (*models.GetCustomerPointsResponse, error) {
// Get total points
totalPoints, err := p.customerPointsRepo.GetCustomerTotalPoints(ctx, customerID)
id, err := parseWalletCustomerID(customerID)
if err != nil {
return nil, fmt.Errorf("failed to get customer total points: %w", err)
return nil, err
}
// Get points history (last 10 records)
pointsHistory, err := p.customerPointsRepo.GetCustomerPointsHistory(ctx, customerID, 10)
data, err := p.walletQuery.LegacyPoints(ctx, id)
if err != nil {
return nil, fmt.Errorf("failed to get customer points history: %w", err)
return nil, fmt.Errorf("failed to get customer points: %w", err)
}
// Convert to response format
var historyItems []models.PointsHistoryItem
for _, point := range pointsHistory {
historyItems = append(historyItems, models.PointsHistoryItem{
ID: point.ID.String(),
Points: point.Balance,
Type: "BALANCE",
Description: "Points balance",
CreatedAt: point.CreatedAt,
})
}
var lastUpdated time.Time
if len(pointsHistory) > 0 {
lastUpdated = pointsHistory[0].CreatedAt
}
return &models.GetCustomerPointsResponse{
Status: "SUCCESS",
Message: "Customer points retrieved successfully.",
Data: &models.GetCustomerPointsResponseData{
TotalPoints: totalPoints,
PointsHistory: historyItems,
LastUpdated: lastUpdated,
},
Data: data,
}, nil
}
func (p *CustomerPointsProcessor) GetCustomerTotalTokensAPI(ctx context.Context, customerID string) (*models.GetCustomerTokensResponse, error) {
// Get total tokens
totalTokens, err := p.customerPointsRepo.GetCustomerTotalTokens(ctx, customerID)
id, err := parseWalletCustomerID(customerID)
if err != nil {
return nil, fmt.Errorf("failed to get customer total tokens: %w", err)
return nil, err
}
// Get tokens history (last 10 records)
tokensHistory, err := p.customerPointsRepo.GetCustomerTokensHistory(ctx, customerID, 10)
data, err := p.walletQuery.LegacyTokens(ctx, id)
if err != nil {
return nil, fmt.Errorf("failed to get customer tokens history: %w", err)
return nil, fmt.Errorf("failed to get customer tokens: %w", err)
}
// Convert to response format
var historyItems []models.TokensHistoryItem
for _, token := range tokensHistory {
historyItems = append(historyItems, models.TokensHistoryItem{
ID: token.ID.String(),
Tokens: token.Balance,
Type: string(token.TokenType),
Description: "Tokens balance",
CreatedAt: token.CreatedAt,
})
}
var lastUpdated time.Time
if len(tokensHistory) > 0 {
lastUpdated = tokensHistory[0].CreatedAt
}
return &models.GetCustomerTokensResponse{
Status: "SUCCESS",
Message: "Customer tokens retrieved successfully.",
Data: &models.GetCustomerTokensResponseData{
TotalTokens: totalTokens,
TokensHistory: historyItems,
LastUpdated: lastUpdated,
},
Data: data,
}, nil
}
func (p *CustomerPointsProcessor) GetCustomerWalletAPI(ctx context.Context, customerID string) (*models.GetCustomerWalletResponse, error) {
// Get total points
totalPoints, err := p.customerPointsRepo.GetCustomerTotalPoints(ctx, customerID)
id, err := parseWalletCustomerID(customerID)
if err != nil {
return nil, fmt.Errorf("failed to get customer total points: %w", err)
return nil, err
}
// Get total tokens
totalTokens, err := p.customerPointsRepo.GetCustomerTotalTokens(ctx, customerID)
data, err := p.walletQuery.Summary(ctx, id)
if err != nil {
return nil, fmt.Errorf("failed to get customer total tokens: %w", err)
return nil, fmt.Errorf("failed to get customer wallet: %w", err)
}
// Get points history (last 5 records)
pointsHistory, err := p.customerPointsRepo.GetCustomerPointsHistory(ctx, customerID, 5)
if err != nil {
return nil, fmt.Errorf("failed to get customer points history: %w", err)
}
// Get tokens history (last 5 records)
tokensHistory, err := p.customerPointsRepo.GetCustomerTokensHistory(ctx, customerID, 5)
if err != nil {
return nil, fmt.Errorf("failed to get customer tokens history: %w", err)
}
// Convert to response format
var pointsHistoryItems []models.PointsHistoryItem
var tokensHistoryItems []models.TokensHistoryItem
var lastUpdated time.Time
for _, point := range pointsHistory {
pointsHistoryItems = append(pointsHistoryItems, models.PointsHistoryItem{
ID: point.ID.String(),
Points: point.Balance,
Type: "BALANCE",
Description: "Points balance",
CreatedAt: point.CreatedAt,
})
if point.CreatedAt.After(lastUpdated) {
lastUpdated = point.CreatedAt
}
}
for _, token := range tokensHistory {
tokensHistoryItems = append(tokensHistoryItems, models.TokensHistoryItem{
ID: token.ID.String(),
Tokens: token.Balance,
Type: string(token.TokenType),
Description: "Tokens balance",
CreatedAt: token.CreatedAt,
})
if token.CreatedAt.After(lastUpdated) {
lastUpdated = token.CreatedAt
}
}
return &models.GetCustomerWalletResponse{
Status: "SUCCESS",
Message: "Customer wallet retrieved successfully.",
Data: &models.GetCustomerWalletResponseData{
TotalPoints: totalPoints,
TotalTokens: totalTokens,
PointsHistory: pointsHistoryItems,
TokensHistory: tokensHistoryItems,
LastUpdated: lastUpdated,
},
Data: data,
}, nil
}
func (p *CustomerPointsProcessor) GetCustomerWalletTransactionsAPI(ctx context.Context, customerID string, query models.ListCustomerWalletTransactionsQuery) (*models.PaginatedResponse[models.CustomerWalletTransaction], error) {
id, err := parseWalletCustomerID(customerID)
if err != nil {
return nil, err
}
return p.walletQuery.Transactions(ctx, id, query)
}
func parseWalletCustomerID(customerID string) (uuid.UUID, error) {
id, err := uuid.Parse(customerID)
if err != nil {
return uuid.Nil, fmt.Errorf("%w: invalid customer id", ErrInvalidWalletQuery)
}
return id, nil
}
// GetCustomerGamesAPI gets active SPIN games for customers
func (p *CustomerPointsProcessor) GetCustomerGamesAPI(ctx context.Context) (*models.GetCustomerGamesResponse, error) {
// Get active SPIN games
@@ -310,3 +177,11 @@ func (p *CustomerPointsProcessor) GetFerrisWheelGameAPI(ctx context.Context) (*m
},
}, nil
}
func (p *CustomerPointsProcessor) GetCustomerWalletExpiringAPI(ctx context.Context, customerID string) (*models.CustomerWalletExpiringList, error) {
id, err := parseWalletCustomerID(customerID)
if err != nil {
return nil, err
}
return p.walletQuery.Expiring(ctx, id)
}
@@ -1,198 +0,0 @@
package processor
import (
"apskel-pos-be/internal/entities"
"apskel-pos-be/internal/mappers"
"apskel-pos-be/internal/models"
"apskel-pos-be/internal/repository"
"context"
"errors"
"fmt"
"github.com/google/uuid"
)
type CustomerTokensProcessor struct {
customerTokensRepo *repository.CustomerTokensRepository
}
func NewCustomerTokensProcessor(customerTokensRepo *repository.CustomerTokensRepository) *CustomerTokensProcessor {
return &CustomerTokensProcessor{
customerTokensRepo: customerTokensRepo,
}
}
// CreateCustomerTokens creates a new customer tokens record
func (p *CustomerTokensProcessor) CreateCustomerTokens(ctx context.Context, req *models.CreateCustomerTokensRequest) (*models.CustomerTokensResponse, error) {
// Convert request to entity
customerTokens := mappers.ToCustomerTokensEntity(req)
// Create customer tokens
err := p.customerTokensRepo.Create(ctx, customerTokens)
if err != nil {
return nil, fmt.Errorf("failed to create customer tokens: %w", err)
}
return mappers.ToCustomerTokensResponse(customerTokens), nil
}
// GetCustomerTokens retrieves customer tokens by ID
func (p *CustomerTokensProcessor) GetCustomerTokens(ctx context.Context, id uuid.UUID) (*models.CustomerTokensResponse, error) {
customerTokens, err := p.customerTokensRepo.GetByID(ctx, id)
if err != nil {
return nil, fmt.Errorf("customer tokens not found: %w", err)
}
return mappers.ToCustomerTokensResponse(customerTokens), nil
}
// GetCustomerTokensByCustomerIDAndType retrieves customer tokens by customer ID and token type
func (p *CustomerTokensProcessor) GetCustomerTokensByCustomerIDAndType(ctx context.Context, customerID uuid.UUID, tokenType string) (*models.CustomerTokensResponse, error) {
customerTokens, err := p.customerTokensRepo.EnsureCustomerTokens(ctx, customerID, entities.TokenType(tokenType))
if err != nil {
return nil, fmt.Errorf("failed to get customer tokens: %w", err)
}
return mappers.ToCustomerTokensResponse(customerTokens), nil
}
// ListCustomerTokens retrieves customer tokens with pagination and filtering
func (p *CustomerTokensProcessor) ListCustomerTokens(ctx context.Context, query *models.ListCustomerTokensQuery) (*models.PaginatedResponse[models.CustomerTokensResponse], error) {
// Set default values
if query.Page <= 0 {
query.Page = 1
}
if query.Limit <= 0 {
query.Limit = 10
}
if query.Limit > 100 {
query.Limit = 100
}
offset := (query.Page - 1) * query.Limit
// Get customer tokens from repository
customerTokens, total, err := p.customerTokensRepo.List(
ctx,
offset,
query.Limit,
query.Search,
query.TokenType,
query.SortBy,
query.SortOrder,
)
if err != nil {
return nil, fmt.Errorf("failed to list customer tokens: %w", err)
}
// Convert to responses
responses := mappers.ToCustomerTokensResponses(customerTokens)
// Calculate pagination info
totalPages := int((total + int64(query.Limit) - 1) / int64(query.Limit))
return &models.PaginatedResponse[models.CustomerTokensResponse]{
Data: responses,
Pagination: models.Pagination{
Page: query.Page,
Limit: query.Limit,
Total: total,
TotalPages: totalPages,
},
}, nil
}
// UpdateCustomerTokens updates an existing customer tokens record
func (p *CustomerTokensProcessor) UpdateCustomerTokens(ctx context.Context, id uuid.UUID, req *models.UpdateCustomerTokensRequest) (*models.CustomerTokensResponse, error) {
// Get existing customer tokens
customerTokens, err := p.customerTokensRepo.GetByID(ctx, id)
if err != nil {
return nil, fmt.Errorf("customer tokens not found: %w", err)
}
// Update customer tokens fields
mappers.UpdateCustomerTokensEntity(customerTokens, req)
// Save updated customer tokens
err = p.customerTokensRepo.Update(ctx, customerTokens)
if err != nil {
return nil, fmt.Errorf("failed to update customer tokens: %w", err)
}
return mappers.ToCustomerTokensResponse(customerTokens), nil
}
// DeleteCustomerTokens deletes a customer tokens record
func (p *CustomerTokensProcessor) DeleteCustomerTokens(ctx context.Context, id uuid.UUID) error {
// Get existing customer tokens
_, err := p.customerTokensRepo.GetByID(ctx, id)
if err != nil {
return fmt.Errorf("customer tokens not found: %w", err)
}
// Delete customer tokens
err = p.customerTokensRepo.Delete(ctx, id)
if err != nil {
return fmt.Errorf("failed to delete customer tokens: %w", err)
}
return nil
}
// AddTokens adds tokens to a customer's balance
func (p *CustomerTokensProcessor) AddTokens(ctx context.Context, customerID uuid.UUID, tokenType string, tokens int64) (*models.CustomerTokensResponse, error) {
if tokens <= 0 {
return nil, errors.New("tokens must be greater than 0")
}
// Ensure customer tokens record exists
_, err := p.customerTokensRepo.EnsureCustomerTokens(ctx, customerID, entities.TokenType(tokenType))
if err != nil {
return nil, fmt.Errorf("failed to ensure customer tokens: %w", err)
}
// Add tokens
err = p.customerTokensRepo.AddTokens(ctx, customerID, entities.TokenType(tokenType), tokens)
if err != nil {
return nil, fmt.Errorf("failed to add tokens: %w", err)
}
// Get updated customer tokens
customerTokens, err := p.customerTokensRepo.GetByCustomerIDAndType(ctx, customerID, entities.TokenType(tokenType))
if err != nil {
return nil, fmt.Errorf("failed to get updated customer tokens: %w", err)
}
return mappers.ToCustomerTokensResponse(customerTokens), nil
}
// DeductTokens deducts tokens from a customer's balance
func (p *CustomerTokensProcessor) DeductTokens(ctx context.Context, customerID uuid.UUID, tokenType string, tokens int64) (*models.CustomerTokensResponse, error) {
if tokens <= 0 {
return nil, errors.New("tokens must be greater than 0")
}
// Get current customer tokens
customerTokens, err := p.customerTokensRepo.GetByCustomerIDAndType(ctx, customerID, entities.TokenType(tokenType))
if err != nil {
return nil, fmt.Errorf("customer tokens not found: %w", err)
}
if customerTokens.Balance < tokens {
return nil, errors.New("insufficient tokens balance")
}
// Deduct tokens
err = p.customerTokensRepo.DeductTokens(ctx, customerID, entities.TokenType(tokenType), tokens)
if err != nil {
return nil, fmt.Errorf("failed to deduct tokens: %w", err)
}
// Get updated customer tokens
updatedCustomerTokens, err := p.customerTokensRepo.GetByCustomerIDAndType(ctx, customerID, entities.TokenType(tokenType))
if err != nil {
return nil, fmt.Errorf("failed to get updated customer tokens: %w", err)
}
return mappers.ToCustomerTokensResponse(updatedCustomerTokens), nil
}
+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))
}
+217
View File
@@ -0,0 +1,217 @@
package processor
import (
"context"
"fmt"
"time"
"github.com/google/uuid"
"apskel-pos-be/internal/constants"
"apskel-pos-be/internal/entities"
"apskel-pos-be/internal/logger"
"apskel-pos-be/internal/models"
"apskel-pos-be/internal/repository"
)
// Why an order earned nothing.
const (
EarningSkipNotPaid = "NOT_PAID"
EarningSkipVoid = "VOID"
EarningSkipNoCustomer = "NO_CUSTOMER"
EarningSkipDefaultCustomer = "DEFAULT_CUSTOMER"
EarningSkipInactiveCustomer = "INACTIVE_CUSTOMER"
EarningSkipNothingToEarn = "NOTHING_TO_EARN"
)
// EarningOutcome is what earning did for one order.
type EarningOutcome struct {
Points int64
Coins int64
// Set when the order earned nothing, to say why.
Skipped string
}
type outletSettingsReader interface {
Outlet(ctx context.Context, outletID uuid.UUID) (*models.OutletLoyaltySettings, error)
}
// earningSettingsReader gives the outlet's earning settings and the organization's
// expiry. LoyaltySettingsProcessor is one.
type earningSettingsReader interface {
outletSettingsReader
organizationSettingsReader
}
// EarningProcessor credits EnakPoint and EnakCoin for paid orders
// (docs/prd-point-coin.md F3).
type EarningProcessor struct {
orders repository.EarningRepository
settings earningSettingsReader
now func() time.Time
wallet *WalletProcessor
tx TxRunner
}
func NewEarningProcessor(orders repository.EarningRepository, settings earningSettingsReader, wallet *WalletProcessor, tx TxRunner) *EarningProcessor {
return &EarningProcessor{orders: orders, settings: settings, wallet: wallet, tx: tx, now: time.Now}
}
// OnOrderPaid is called once an order has become fully paid and the payment has
// committed. It never fails the caller: a failed earning is logged and picked up later
// by EarnMissing, and the idempotency keys make that retry safe.
func (p *EarningProcessor) OnOrderPaid(ctx context.Context, orderID uuid.UUID) {
defer func() {
if r := recover(); r != nil {
logger.NonContext.Error(fmt.Sprintf("Earning for order %s panicked; it will be retried", orderID), fmt.Errorf("%v", r))
}
}()
if _, err := p.EarnForOrder(ctx, orderID); err != nil {
logger.NonContext.Error(fmt.Sprintf("Earning for order %s failed; it will be retried", orderID), err)
}
}
// EarnForOrder credits what a paid order earns. Calling it again for the same order
// credits nothing more.
func (p *EarningProcessor) EarnForOrder(ctx context.Context, orderID uuid.UUID) (*EarningOutcome, error) {
order, err := p.orders.GetOrderForEarning(ctx, orderID)
if err != nil {
return nil, err
}
if skip := earningSkipReason(order); skip != "" {
return &EarningOutcome{Skipped: skip}, nil
}
settings, err := p.settings.Outlet(ctx, order.OutletID)
if err != nil {
return nil, err
}
pointPaid, err := p.orders.PointPaidAmount(ctx, orderID)
if err != nil {
return nil, err
}
result := CalculateEarning(&entities.Order{Subtotal: order.Subtotal, DiscountAmount: order.DiscountAmount}, pointPaid, *settings)
if result.Point.Amount == 0 && result.Coin.Amount == 0 {
return &EarningOutcome{Skipped: EarningSkipNothingToEarn}, nil
}
orgSettings, err := p.settings.Organization(ctx, order.OrganizationID)
if err != nil {
return nil, err
}
receivedAt := p.now()
outcome := &EarningOutcome{}
err = p.tx.WithTransaction(ctx, func(ctx context.Context) error {
for _, c := range []struct {
currency string
line EarningLine
total *int64
}{
{constants.WalletCurrencyPoint, result.Point, &outcome.Points},
{constants.WalletCurrencyCoin, result.Coin, &outcome.Coins},
} {
if c.line.Amount == 0 {
continue
}
outletID := order.OutletID
res, err := p.wallet.Credit(ctx, WalletCreditInput{
WalletEntry: WalletEntry{
CustomerID: *order.CustomerID,
Currency: c.currency,
Type: constants.WalletTxTypeEarn,
Amount: c.line.Amount,
ReferenceType: constants.WalletRefTypeOrder,
ReferenceID: order.ID,
OutletID: &outletID,
Description: earningDescription(order),
Metadata: result.Metadata(c.line),
IdempotencyKey: fmt.Sprintf("earn:%s:%s", order.ID, c.currency),
},
Lots: []WalletLotInput{{
Amount: c.line.Amount,
ExpiresAt: ComputeExpiry(ExpirySettings(orgSettings, c.currency), receivedAt),
}},
})
if err != nil {
return fmt.Errorf("crediting %s: %w", c.currency, err)
}
*c.total = res.Transaction.Amount
}
return nil
})
if err != nil {
return nil, err
}
return outcome, nil
}
// EarnMissing is the safety net behind OnOrderPaid: it looks for orders paid since the
// given time that should have earned and have no EARN row, and earns for them. It
// returns how many orders it looked at and how many now earned. One order failing does
// not stop the others.
func (p *EarningProcessor) EarnMissing(ctx context.Context, since time.Time, maxOrders int) (checked, earned int, err error) {
const page = 200
var after *repository.EarningCursor
for checked < maxOrders {
batch, err := p.orders.ListPaidOrdersWithoutEarning(ctx, since, after, page)
if err != nil {
return checked, earned, err
}
if len(batch) == 0 {
break
}
for _, candidate := range batch {
checked++
outcome, err := p.EarnForOrder(ctx, candidate.ID)
if err != nil {
logger.NonContext.Error(fmt.Sprintf("Earning retry for order %s failed", candidate.ID), err)
continue
}
if outcome.Skipped == "" {
earned++
}
}
last := batch[len(batch)-1]
after = &last
}
return checked, earned, nil
}
func earningSkipReason(order *repository.EarningOrder) string {
switch {
case order.PaymentStatus != string(entities.PaymentStatusCompleted):
return EarningSkipNotPaid
case order.IsVoid:
return EarningSkipVoid
case order.CustomerID == nil || order.CustomerIsDefault == nil:
return EarningSkipNoCustomer
case *order.CustomerIsDefault:
return EarningSkipDefaultCustomer
case order.CustomerIsActive == nil || !*order.CustomerIsActive:
return EarningSkipInactiveCustomer
}
return ""
}
func earningDescription(order *repository.EarningOrder) string {
description := "Belanja #" + order.OrderNumber
if order.OutletName != "" {
description += " di " + order.OutletName
}
return truncateRunes(description, walletDescriptionLimit)
}
// EarnedByOrders returns what each order earned, as written in its EARN rows, for the
// order screen and the receipt (F3). Orders that earned nothing are absent.
func (p *EarningProcessor) EarnedByOrders(ctx context.Context, orderIDs []uuid.UUID) (map[uuid.UUID]OrderEarned, error) {
rows, err := p.orders.EarnedByOrders(ctx, orderIDs)
if err != nil {
return nil, err
}
out := make(map[uuid.UUID]OrderEarned, len(rows))
for id, byCurrency := range rows {
out[id] = OrderEarned{Points: byCurrency[constants.WalletCurrencyPoint], Coins: byCurrency[constants.WalletCurrencyCoin]}
}
return out, nil
}
@@ -0,0 +1,233 @@
package processor
import (
"context"
"errors"
"os"
"sync"
"testing"
"time"
"github.com/google/uuid"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"gorm.io/driver/postgres"
"gorm.io/gorm"
"gorm.io/gorm/logger"
"apskel-pos-be/internal/models"
"apskel-pos-be/internal/repository"
)
// failingSettings fails for the outlet settings until healed, to stand in for the
// database being unreachable right after a payment.
type failingSettings struct {
real earningSettingsReader
mu sync.Mutex
fail bool
}
func (f *failingSettings) Outlet(ctx context.Context, outletID uuid.UUID) (*models.OutletLoyaltySettings, error) {
f.mu.Lock()
fail := f.fail
f.mu.Unlock()
if fail {
return nil, errors.New("connection refused")
}
return f.real.Outlet(ctx, outletID)
}
// Needs TEST_DATABASE_URL pointing at a migrated database; see
// internal/repository/wallet_repository_test.go.
func TestEarningProcessor_AgainstPostgres(t *testing.T) {
dsn := os.Getenv("TEST_DATABASE_URL")
if dsn == "" {
t.Skip("TEST_DATABASE_URL not set")
}
db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{Logger: logger.Default.LogMode(logger.Silent)})
require.NoError(t, err)
ctx := context.Background()
org, user := uuid.New(), uuid.New()
earningOutlet, quietOutlet := uuid.New(), uuid.New()
regular, inactive := uuid.New(), uuid.New()
var walkIn uuid.UUID
var customers []uuid.UUID
exec := func(q string, args ...any) {
t.Helper()
require.NoError(t, db.Exec(q, args...).Error)
}
exec(`INSERT INTO organizations (id, name, plan_type) VALUES (?, 'earning test', 'basic')`, org)
exec(`INSERT INTO users (id, organization_id, name, email, password_hash, role) VALUES (?, ?, 'Kasir', ?, 'x', 'cashier')`, user, org, user.String()+"@test")
exec(`INSERT INTO outlets (id, organization_id, name) VALUES (?, ?, 'Kemang'), (?, ?, 'Tanpa Poin')`, earningOutlet, org, quietOutlet, org)
exec(`INSERT INTO customers (id, organization_id, name, is_default, is_active) VALUES
(?, ?, 'Budi', false, true), (?, ?, 'Nonaktif', false, false)`, regular, org, inactive, org)
// Creating the organization created its walk-in customer (trigger_create_default_customer).
var walkInID string
require.NoError(t, db.Raw(`SELECT id::text FROM customers WHERE organization_id = ? AND is_default`, org).Scan(&walkInID).Error)
walkIn = uuid.MustParse(walkInID)
customers = []uuid.UUID{regular, walkIn, inactive}
t.Cleanup(func() {
db.Exec(`DELETE FROM wallet_lot_allocations WHERE lot_id IN (SELECT id FROM wallet_lots WHERE customer_id IN ?)`, customers)
db.Exec(`DELETE FROM wallet_lots WHERE customer_id IN ?`, customers)
db.Exec(`DELETE FROM wallet_transactions WHERE customer_id IN ?`, customers)
db.Exec(`DELETE FROM customer_wallets WHERE customer_id IN ?`, customers)
db.Exec(`DELETE FROM orders WHERE organization_id = ?`, org)
db.Exec(`DELETE FROM loyalty_setting_changes WHERE organization_id = ?`, org)
db.Exec(`DELETE FROM outlet_settings WHERE outlet_id IN ?`, []uuid.UUID{earningOutlet, quietOutlet})
db.Exec(`DELETE FROM customers WHERE id IN ?`, customers)
db.Exec(`DELETE FROM outlets WHERE id IN ?`, []uuid.UUID{earningOutlet, quietOutlet})
db.Exec(`DELETE FROM users WHERE id = ?`, user)
db.Exec(`DELETE FROM organizations WHERE id = ?`, org)
})
txm := repository.NewTxManager(db)
settingsProcessor := NewLoyaltySettingsProcessor(repository.NewLoyaltySettingsRepository(db), txm)
outletSettings, err := settingsProcessor.Outlet(ctx, earningOutlet)
require.NoError(t, err)
outletSettings.Point.Enabled = true
outletSettings.Coin.Enabled = true
_, err = settingsProcessor.UpdateOutlet(ctx, org, earningOutlet, user, *outletSettings)
require.NoError(t, err)
settings := &failingSettings{real: settingsProcessor}
earning := NewEarningProcessor(repository.NewEarningRepository(db), settings, NewWalletProcessor(repository.NewWalletRepository(db)), txm)
orderNo := 0
newOrder := func(outlet uuid.UUID, customer *uuid.UUID, paymentStatus string, isVoid bool, subtotal, discount float64) uuid.UUID {
t.Helper()
orderNo++
id := uuid.New()
exec(`INSERT INTO orders (id, organization_id, outlet_id, user_id, customer_id, order_number, order_type,
subtotal, discount_amount, tax_amount, total_amount, payment_status, is_void)
VALUES (?, ?, ?, ?, ?, ?, 'dine_in', ?, ?, 0, ?, ?, ?)`,
id, org, outlet, user, customer, id.String()[:8]+"-"+string(rune('A'+orderNo)), subtotal, discount, subtotal-discount, paymentStatus, isVoid)
return id
}
earnRows := func(orderID uuid.UUID) map[string]int64 {
t.Helper()
var rows []struct {
Currency string
Amount int64
}
require.NoError(t, db.Raw(`SELECT currency, amount FROM wallet_transactions WHERE reference_id = ? AND type = 'EARN'`, orderID).Scan(&rows).Error)
out := map[string]int64{}
for _, r := range rows {
out[r.Currency] += r.Amount
}
return out
}
// Paid in full: the PRD example, 875 EnakPoint and 3 EnakCoin.
paid := newOrder(earningOutlet, &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)
}
func (f *failingSettings) Organization(ctx context.Context, organizationID uuid.UUID) (*models.OrganizationLoyaltySettings, error) {
return f.real.Organization(ctx, organizationID)
}
+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))
})
}
+170
View File
@@ -0,0 +1,170 @@
package processor
import (
"errors"
"fmt"
"sort"
"strings"
"time"
"apskel-pos-be/internal/constants"
"apskel-pos-be/internal/models"
)
// Expiry rules of docs/prd-point-coin.md F12, with the model of note N4 decided: both
// FIXED_DATE and ROLLING are supported and the owner picks one per currency.
//
// A lot expires at the last second of its expiry day in the customer's time zone, so
// "expires on 31 Dec" means it can still be spent all of 31 Dec, and the day the apps
// group it under is that day.
const (
// A longer grace would push a balance past a whole cycle of fixed dates.
loyaltyExpiryMaxGraceMonths = 24
// A refund gives the EnakPoint back at least this long, even when the lot they
// came from has expired or is about to (note N4, decided).
refundMinimumValidity = 7 * 24 * time.Hour
)
// ExpirySettings picks the settings of one currency.
func ExpirySettings(s *models.OrganizationLoyaltySettings, currency string) models.LoyaltyExpirySettings {
if currency == constants.WalletCurrencyCoin {
return s.CoinExpiry
}
return s.PointExpiry
}
// ComputeExpiry is when a balance received at receivedAt expires, or nil when it never
// does because expiry is off. It is the expiry of every lot that is not carried over
// from another one: EARN, ADJUSTMENT and, capped by its origin, EXCHANGE_IN.
func ComputeExpiry(s models.LoyaltyExpirySettings, receivedAt time.Time) *time.Time {
if !s.Enabled {
return nil
}
day := walletDay(receivedAt)
if s.Mode == constants.LoyaltyExpiryModeRolling {
if s.Unit == constants.LoyaltyExpiryUnitDay {
day = day.AddDate(0, 0, int(s.Period))
} else {
day = addMonthsClamped(day, int(s.Period))
}
if s.EndOfMonth {
day = lastDayOfMonth(day)
}
return endOfWalletDay(day)
}
return endOfWalletDay(fixedDateOnOrAfter(s.FixedDates, addMonthsClamped(day, int(s.GraceMonths))))
}
// ActivationExpiry is the expiry given to the balances that already exist, without an
// expiry, when expiry is turned on (note N4, decided): a full period from activation
// when ROLLING, the second fixed date after activation when FIXED_DATE. Either way no
// customer loses a balance soon after the rule is announced.
func ActivationExpiry(s models.LoyaltyExpirySettings, at time.Time) *time.Time {
if s.Mode == constants.LoyaltyExpiryModeRolling {
s.Enabled = true
return ComputeExpiry(s, at)
}
first := fixedDateOnOrAfter(s.FixedDates, walletDay(at))
return endOfWalletDay(fixedDateOnOrAfter(s.FixedDates, first.AddDate(0, 0, 1)))
}
// RefundExpiry is the expiry of EnakPoint given back by a refund: that of the lot they
// came from, but at least seven days from now (note N4, decided). A lot that never
// expires stays so.
func RefundExpiry(origin *time.Time, now time.Time) *time.Time {
if origin == nil {
return nil
}
minimum := endOfWalletDay(walletDay(now.Add(refundMinimumValidity)))
if origin.Before(*minimum) {
return minimum
}
return origin
}
// EarlierExpiry is the sooner of two expiries, where nil means never.
func EarlierExpiry(a, b *time.Time) *time.Time {
switch {
case a == nil:
return b
case b == nil:
return a
case b.Before(*a):
return b
}
return a
}
// normalizeDaysOfYear checks days written as MM-DD and returns them sorted without
// duplicates. 29 February is refused, as it does not come every year.
func normalizeDaysOfYear(days []string) ([]string, error) {
seen := map[string]bool{}
var out []string
for _, d := range days {
d = strings.TrimSpace(d)
if d == "" {
continue
}
parsed, err := time.Parse("01-02", d)
if err != nil || parsed.Format("01-02") != d {
return nil, fmt.Errorf("has %q, which is not a day of the year written as MM-DD", d)
}
if d == "02-29" {
return nil, errors.New("cannot use 02-29, which is not in every year")
}
if !seen[d] {
seen[d] = true
out = append(out, d)
}
}
if len(out) == 0 {
return nil, errors.New("must list at least one day of the year, as MM-DD")
}
sort.Strings(out)
return out, nil
}
// fixedDateOnOrAfter is the first of the days of the year that falls on or after day.
func fixedDateOnOrAfter(days []string, day time.Time) time.Time {
days, err := normalizeDaysOfYear(days)
if err != nil {
days = []string{constants.LoyaltyExpiryFixedDatesDefault}
}
for year := day.Year(); ; year++ {
for _, d := range days {
parsed, _ := time.Parse("01-02", d)
candidate := time.Date(year, parsed.Month(), parsed.Day(), 0, 0, 0, 0, walletDisplayLocation)
if !candidate.Before(day) {
return candidate
}
}
}
}
// walletDay is the calendar day of t in the customer's time zone, at midnight.
func walletDay(t time.Time) time.Time {
local := t.In(walletDisplayLocation)
return time.Date(local.Year(), local.Month(), local.Day(), 0, 0, 0, 0, walletDisplayLocation)
}
func endOfWalletDay(day time.Time) *time.Time {
end := time.Date(day.Year(), day.Month(), day.Day(), 23, 59, 59, 0, walletDisplayLocation)
return &end
}
// addMonthsClamped adds months, keeping to the last day of a shorter month: 31 Jan
// plus one month is 28 or 29 Feb, not 3 Mar.
func addMonthsClamped(day time.Time, months int) time.Time {
first := time.Date(day.Year(), day.Month(), 1, 0, 0, 0, 0, day.Location()).AddDate(0, months, 0)
last := lastDayOfMonth(first).Day()
d := day.Day()
if d > last {
d = last
}
return time.Date(first.Year(), first.Month(), d, 0, 0, 0, 0, day.Location())
}
func lastDayOfMonth(day time.Time) time.Time {
return time.Date(day.Year(), day.Month()+1, 0, 0, 0, 0, 0, day.Location())
}
+115
View File
@@ -0,0 +1,115 @@
package processor
import (
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"apskel-pos-be/internal/models"
)
// wib is a moment in the customer's time zone.
func wib(year int, month time.Month, day, hour, minute int) time.Time {
return time.Date(year, month, day, hour, minute, 0, 0, walletDisplayLocation)
}
// expiryDay is the day a lot expires on, as the apps show it.
func expiryDay(t *testing.T, at *time.Time) string {
t.Helper()
require.NotNil(t, at)
local := at.In(walletDisplayLocation)
assert.Equal(t, "23:59:59", local.Format("15:04:05"), "a lot lasts to the end of its day")
return local.Format("2006-01-02")
}
func fixedDate(dates ...string) models.LoyaltyExpirySettings {
return models.LoyaltyExpirySettings{Enabled: true, Mode: "FIXED_DATE", FixedDates: dates, GraceMonths: 3}
}
func rolling(period int64, unit string, endOfMonth bool) models.LoyaltyExpirySettings {
return models.LoyaltyExpirySettings{Enabled: true, Mode: "ROLLING", Period: period, Unit: unit, EndOfMonth: endOfMonth}
}
func TestComputeExpiry_OffNeverExpires(t *testing.T) {
s := fixedDate("12-31")
s.Enabled = false
assert.Nil(t, ComputeExpiry(s, wib(2026, 5, 1, 10, 0)))
}
func TestComputeExpiry_FixedDateWithGrace(t *testing.T) {
yearly := fixedDate("12-31")
for received, want := range map[time.Time]string{
wib(2026, 1, 15, 9, 0): "2026-12-31",
wib(2026, 9, 30, 23, 0): "2026-12-31", // 30 Dec + nothing: still this year
wib(2026, 10, 1, 0, 30): "2027-12-31", // within 3 months of 31 Dec: next year
wib(2026, 12, 31, 8, 0): "2027-12-31",
} {
assert.Equal(t, want, expiryDay(t, ComputeExpiry(yearly, received)), received.String())
}
twice := fixedDate("12-31", "06-30")
assert.Equal(t, "2026-06-30", expiryDay(t, ComputeExpiry(twice, wib(2026, 3, 1, 12, 0))))
assert.Equal(t, "2026-12-31", expiryDay(t, ComputeExpiry(twice, wib(2026, 4, 1, 12, 0))))
assert.Equal(t, "2027-06-30", expiryDay(t, ComputeExpiry(twice, wib(2026, 10, 1, 12, 0))))
noGrace := fixedDate("12-31")
noGrace.GraceMonths = 0
assert.Equal(t, "2026-12-31", expiryDay(t, ComputeExpiry(noGrace, wib(2026, 12, 31, 22, 0))))
}
// The day received is the customer's day: 20:00 UTC on 31 Mar is already 1 Apr in WIB.
func TestComputeExpiry_UsesTheCustomersDay(t *testing.T) {
received := time.Date(2026, 3, 31, 20, 0, 0, 0, time.UTC)
assert.Equal(t, "2026-04-11", expiryDay(t, ComputeExpiry(rolling(10, "DAY", false), received)))
}
func TestComputeExpiry_Rolling(t *testing.T) {
assert.Equal(t, "2027-03-14", expiryDay(t, ComputeExpiry(rolling(12, "MONTH", false), wib(2026, 3, 14, 10, 0))))
assert.Equal(t, "2027-03-31", expiryDay(t, ComputeExpiry(rolling(12, "MONTH", true), wib(2026, 3, 14, 10, 0))))
assert.Equal(t, "2026-03-24", expiryDay(t, ComputeExpiry(rolling(10, "DAY", false), wib(2026, 3, 14, 10, 0))))
// A month that is shorter keeps to its last day.
assert.Equal(t, "2026-02-28", expiryDay(t, ComputeExpiry(rolling(1, "MONTH", false), wib(2026, 1, 31, 10, 0))))
}
func TestActivationExpiry(t *testing.T) {
// FIXED_DATE: the second fixed date after activation, so nobody loses a balance
// weeks after the rule is announced.
assert.Equal(t, "2027-12-31", expiryDay(t, ActivationExpiry(fixedDate("12-31"), wib(2026, 11, 20, 10, 0))))
assert.Equal(t, "2027-12-31", expiryDay(t, ActivationExpiry(fixedDate("12-31"), wib(2026, 12, 31, 10, 0))))
assert.Equal(t, "2027-06-30", expiryDay(t, ActivationExpiry(fixedDate("06-30", "12-31"), wib(2026, 11, 20, 10, 0))))
// ROLLING: a full period from activation.
assert.Equal(t, "2027-11-20", expiryDay(t, ActivationExpiry(rolling(12, "MONTH", false), wib(2026, 11, 20, 10, 0))))
}
func TestRefundExpiry(t *testing.T) {
now := wib(2026, 6, 1, 10, 0)
later := wib(2026, 12, 31, 23, 59)
soon := wib(2026, 6, 3, 23, 59)
past := wib(2026, 5, 1, 23, 59)
assert.Nil(t, RefundExpiry(nil, now))
assert.Equal(t, &later, RefundExpiry(&later, now))
assert.Equal(t, "2026-06-08", expiryDay(t, RefundExpiry(&soon, now)))
assert.Equal(t, "2026-06-08", expiryDay(t, RefundExpiry(&past, now)))
}
func TestEarlierExpiry(t *testing.T) {
a, b := wib(2026, 1, 1, 0, 0), wib(2026, 2, 1, 0, 0)
assert.Equal(t, &a, EarlierExpiry(&a, &b))
assert.Equal(t, &a, EarlierExpiry(&b, &a))
assert.Equal(t, &a, EarlierExpiry(nil, &a))
assert.Equal(t, &a, EarlierExpiry(&a, nil))
assert.Nil(t, EarlierExpiry(nil, nil))
}
func TestNormalizeDaysOfYear(t *testing.T) {
days, err := normalizeDaysOfYear([]string{" 12-31", "06-30", "12-31", ""})
require.NoError(t, err)
assert.Equal(t, []string{"06-30", "12-31"}, days)
for _, bad := range [][]string{{}, {"13-01"}, {"12-32"}, {"1-31"}, {"02-29"}, {"31-12"}} {
_, err := normalizeDaysOfYear(bad)
assert.Error(t, err, bad)
}
}
@@ -0,0 +1,530 @@
package processor
import (
"context"
"errors"
"fmt"
"strconv"
"strings"
"time"
"github.com/google/uuid"
"apskel-pos-be/internal/constants"
"apskel-pos-be/internal/entities"
"apskel-pos-be/internal/logger"
"apskel-pos-be/internal/models"
"apskel-pos-be/internal/repository"
)
// ErrInvalidLoyaltySettings wraps every rejection of a setting that breaks the rules in
// docs/prd-point-coin.md F1, F2 and F12.
var ErrInvalidLoyaltySettings = errors.New("invalid loyalty settings")
// LoyaltySettingsProcessor reads and writes the loyalty settings of outlets (F1) and
// organizations (F2, F12). Reads always return every setting, with the PRD default for
// a key that was never set, so callers never handle a missing value. Every write
// records what changed in loyalty_setting_changes.
type LoyaltySettingsProcessor struct {
repo repository.LoyaltySettingsRepository
tx TxRunner
now func() time.Time
}
func NewLoyaltySettingsProcessor(repo repository.LoyaltySettingsRepository, tx TxRunner) *LoyaltySettingsProcessor {
return &LoyaltySettingsProcessor{repo: repo, tx: tx, now: time.Now}
}
// Outlet returns an outlet's settings.
func (p *LoyaltySettingsProcessor) Outlet(ctx context.Context, outletID uuid.UUID) (*models.OutletLoyaltySettings, error) {
raw, err := p.repo.GetOutletValues(ctx, outletID)
if err != nil {
return nil, err
}
var s models.OutletLoyaltySettings
loadLoyaltyFields(outletLoyaltyFields(&s), raw, "outlet "+outletID.String())
return &s, nil
}
// OutletForOrganization returns an outlet's settings for the dashboard, and
// repository.ErrLoyaltyOutletNotFound unless the outlet belongs to the organization.
func (p *LoyaltySettingsProcessor) OutletForOrganization(ctx context.Context, organizationID, outletID uuid.UUID) (*models.OutletLoyaltySettings, error) {
owner, err := p.repo.OutletOrganizationID(ctx, outletID)
if err != nil {
return nil, err
}
if owner != organizationID {
return nil, repository.ErrLoyaltyOutletNotFound
}
return p.Outlet(ctx, outletID)
}
// Organization returns an organization's settings.
func (p *LoyaltySettingsProcessor) Organization(ctx context.Context, organizationID uuid.UUID) (*models.OrganizationLoyaltySettings, error) {
raw, err := p.repo.GetOrganizationValues(ctx, organizationID)
if err != nil {
return nil, err
}
var s models.OrganizationLoyaltySettings
loadLoyaltyFields(organizationLoyaltyFields(&s), raw, "organization "+organizationID.String())
return &s, nil
}
// PointValue is the rupiah value of one EnakPoint in an organization.
func (p *LoyaltySettingsProcessor) PointValue(ctx context.Context, organizationID uuid.UUID) (int64, error) {
s, err := p.Organization(ctx, organizationID)
if err != nil {
return 0, err
}
return s.PointValue, nil
}
// UpdateOutlet replaces an outlet's settings and returns what changed. The outlet must
// belong to the organization; otherwise repository.ErrLoyaltyOutletNotFound.
func (p *LoyaltySettingsProcessor) UpdateOutlet(ctx context.Context, organizationID, outletID, changedBy uuid.UUID, settings models.OutletLoyaltySettings) ([]models.LoyaltySettingChange, error) {
if err := validateLoyaltyFields(outletLoyaltyFields(&settings)); err != nil {
return nil, err
}
var changes []models.LoyaltySettingChange
err := p.tx.WithTransaction(ctx, func(ctx context.Context) error {
owner, err := p.repo.OutletOrganizationID(ctx, outletID)
if err != nil {
return err
}
if owner != organizationID {
return repository.ErrLoyaltyOutletNotFound
}
if err := p.repo.LockScope(ctx, outletID); err != nil {
return err
}
raw, err := p.repo.GetOutletValues(ctx, outletID)
if err != nil {
return err
}
var current models.OutletLoyaltySettings
loadLoyaltyFields(outletLoyaltyFields(&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.
//
// Turning expiry on for a currency for the first time also gives every existing lot
// without an expiry the activation expiry (F12, note N4), and the result lists them.
func (p *LoyaltySettingsProcessor) UpdateOrganization(ctx context.Context, organizationID, changedBy uuid.UUID, settings models.OrganizationLoyaltySettings) ([]models.LoyaltySettingChange, []models.LoyaltyExpiryActivation, error) {
if err := validateLoyaltyFields(organizationLoyaltyFields(&settings)); err != nil {
return nil, nil, err
}
var changes []models.LoyaltySettingChange
var activations []models.LoyaltyExpiryActivation
err := p.tx.WithTransaction(ctx, func(ctx context.Context) error {
if err := p.repo.LockScope(ctx, organizationID); err != nil {
return err
}
raw, err := p.repo.GetOrganizationValues(ctx, organizationID)
if err != nil {
return err
}
var current models.OrganizationLoyaltySettings
loadLoyaltyFields(organizationLoyaltyFields(&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)
})
if err != nil {
return err
}
activations, err = p.expiryActivations(ctx, organizationID, current, settings, true)
return err
})
if err != nil {
return nil, nil, err
}
return changes, activations, nil
}
// expiryActivations lists the currencies whose expiry these settings turn on, with the
// balances that have no expiry yet and the expiry they get: a full period from now
// (note N4, decided). With apply, it dates those lots.
func (p *LoyaltySettingsProcessor) expiryActivations(ctx context.Context, organizationID uuid.UUID, before, after models.OrganizationLoyaltySettings, apply bool) ([]models.LoyaltyExpiryActivation, error) {
activations := []models.LoyaltyExpiryActivation{}
for _, currency := range []string{constants.WalletCurrencyPoint, constants.WalletCurrencyCoin} {
was, will := ExpirySettings(&before, currency), ExpirySettings(&after, currency)
if was.Enabled || !will.Enabled {
continue
}
expiresAt := *ActivationExpiry(will, p.now())
var lots, amount int64
var err error
if apply {
lots, amount, err = p.repo.DateUndatedLots(ctx, organizationID, currency, expiresAt)
} else {
lots, amount, err = p.repo.UndatedBalance(ctx, organizationID, currency)
}
if err != nil {
return nil, err
}
activations = append(activations, models.LoyaltyExpiryActivation{Currency: currency, Lots: lots, Amount: amount, ExpiresAt: expiresAt})
}
return activations, nil
}
// apply stores every field whose effective value changes and records it. A key left
// on its default and not changed is not written, so the history only shows real
// changes. current and next list the same keys in the same order.
func (p *LoyaltySettingsProcessor) apply(ctx context.Context, organizationID uuid.UUID, outletID *uuid.UUID, changedBy uuid.UUID, raw map[string]string, current, next []loyaltyField, store func(key string, value *string) error) ([]models.LoyaltySettingChange, error) {
rows := diffLoyaltyFields(organizationID, outletID, changedBy, raw, current, next)
for _, row := range rows {
if err := store(row.Key, row.NewValue); err != nil {
return nil, err
}
}
if err := p.repo.InsertChanges(ctx, rows); err != nil {
return nil, err
}
changes := make([]models.LoyaltySettingChange, 0, len(rows))
for _, row := range rows {
changes = append(changes, loyaltySettingChangeModel(row))
}
return changes, nil
}
// ListChanges returns a page of an organization's settings history, newest first.
// A nil outlet lists the whole organization, outlets included.
func (p *LoyaltySettingsProcessor) ListChanges(ctx context.Context, organizationID uuid.UUID, outletID *uuid.UUID, page, limit int) (*models.PaginatedResponse[models.LoyaltySettingChange], error) {
if page < 1 {
page = 1
}
if limit < 1 || limit > 100 {
limit = 20
}
rows, total, err := p.repo.ListChanges(ctx, repository.LoyaltySettingChangeFilter{
OrganizationID: organizationID, OutletID: outletID, Offset: (page - 1) * limit, Limit: limit,
})
if err != nil {
return nil, err
}
items := make([]models.LoyaltySettingChange, 0, len(rows))
for _, row := range rows {
items = append(items, loyaltySettingChangeModel(row))
}
return &models.PaginatedResponse[models.LoyaltySettingChange]{
Data: items,
Pagination: models.Pagination{
Page: page, Limit: limit, Total: total, TotalPages: int((total + int64(limit) - 1) / int64(limit)),
},
}, nil
}
func loyaltySettingChangeModel(row entities.LoyaltySettingChange) models.LoyaltySettingChange {
return models.LoyaltySettingChange{
ID: row.ID,
OrganizationID: row.OrganizationID,
OutletID: row.OutletID,
Key: row.Key,
OldValue: row.OldValue,
NewValue: row.NewValue,
ChangedBy: row.ChangedBy,
CreatedAt: row.CreatedAt,
}
}
// outletLoyaltyFields describes every outlet key (F1), bound to s.
func outletLoyaltyFields(s *models.OutletLoyaltySettings) []loyaltyField {
return []loyaltyField{
boolLoyaltyField(constants.LoyaltyPointEnabledKey, &s.Point.Enabled, false),
intLoyaltyField(constants.LoyaltyPointEarnPerAmountKey, &s.Point.EarnPerAmount, constants.LoyaltyPointEarnPerAmountDefault, 1, noLoyaltyMax),
intLoyaltyField(constants.LoyaltyPointEarnValueKey, &s.Point.EarnValue, constants.LoyaltyEarnValueDefault, 0, noLoyaltyMax),
intLoyaltyField(constants.LoyaltyPointMinOrderAmountKey, &s.Point.MinOrderAmount, 0, 0, noLoyaltyMax),
optionalIntLoyaltyField(constants.LoyaltyPointMaxPerOrderKey, &s.Point.MaxPerOrder, 0),
boolLoyaltyField(constants.LoyaltyCoinEnabledKey, &s.Coin.Enabled, false),
intLoyaltyField(constants.LoyaltyCoinEarnPerAmountKey, &s.Coin.EarnPerAmount, constants.LoyaltyCoinEarnPerAmountDefault, 1, noLoyaltyMax),
intLoyaltyField(constants.LoyaltyCoinEarnValueKey, &s.Coin.EarnValue, constants.LoyaltyEarnValueDefault, 0, noLoyaltyMax),
intLoyaltyField(constants.LoyaltyCoinMinOrderAmountKey, &s.Coin.MinOrderAmount, 0, 0, noLoyaltyMax),
optionalIntLoyaltyField(constants.LoyaltyCoinMaxPerOrderKey, &s.Coin.MaxPerOrder, 0),
boolLoyaltyField(constants.LoyaltyPointAcceptPaymentKey, &s.PointPayment.AcceptPayment, false),
intLoyaltyField(constants.LoyaltyPointMinPaymentPointsKey, &s.PointPayment.MinPaymentPoints, constants.LoyaltyMinPaymentPointsDefault, 1, noLoyaltyMax),
intLoyaltyField(constants.LoyaltyPointMaxPaymentPercentKey, &s.PointPayment.MaxPaymentPercent, constants.LoyaltyMaxPaymentPercentDefault, 0, 100),
}
}
// organizationLoyaltyFields describes every organization key (F2, F12), bound to s.
func organizationLoyaltyFields(s *models.OrganizationLoyaltySettings) []loyaltyField {
fields := []loyaltyField{
intLoyaltyField(constants.LoyaltyPointValueKey, &s.PointValue, constants.LoyaltyPointValueDefault, 1, noLoyaltyMax),
intLoyaltyField(constants.LoyaltyExchangeCoinAmountKey, &s.Exchange.CoinAmount, constants.LoyaltyExchangeAmountDefault, 1, noLoyaltyMax),
intLoyaltyField(constants.LoyaltyExchangePointAmountKey, &s.Exchange.PointAmount, constants.LoyaltyExchangeAmountDefault, 1, noLoyaltyMax),
boolLoyaltyField(constants.LoyaltyTransferEnabledKey, &s.Transfer.Enabled, constants.LoyaltyTransferEnabledDefault),
intLoyaltyField(constants.LoyaltyTransferMinAmountKey, &s.Transfer.MinAmount, constants.LoyaltyTransferMinAmountDefault, 1, noLoyaltyMax),
optionalIntLoyaltyField(constants.LoyaltyTransferMaxPerTransactionKey, &s.Transfer.MaxPerTransaction, 1),
optionalIntLoyaltyField(constants.LoyaltyTransferDailyLimitKey, &s.Transfer.DailyLimit, 1),
}
fields = append(fields, expiryLoyaltyFields("loyalty.point.", &s.PointExpiry)...)
return append(fields, expiryLoyaltyFields("loyalty.coin.", &s.CoinExpiry)...)
}
func expiryLoyaltyFields(prefix string, s *models.LoyaltyExpirySettings) []loyaltyField {
return []loyaltyField{
boolLoyaltyField(prefix+constants.LoyaltyExpiryEnabledSuffix, &s.Enabled, false),
enumLoyaltyField(prefix+constants.LoyaltyExpiryModeSuffix, &s.Mode, constants.LoyaltyExpiryModeDefault,
constants.LoyaltyExpiryModeFixedDate, constants.LoyaltyExpiryModeRolling),
dayOfYearListLoyaltyField(prefix+constants.LoyaltyExpiryFixedDatesSuffix, &s.FixedDates, constants.LoyaltyExpiryFixedDatesDefault),
intLoyaltyField(prefix+constants.LoyaltyExpiryGraceMonthsSuffix, &s.GraceMonths, constants.LoyaltyExpiryGraceMonthsDefault, 0, loyaltyExpiryMaxGraceMonths),
intLoyaltyField(prefix+constants.LoyaltyExpiryPeriodSuffix, &s.Period, constants.LoyaltyExpiryPeriodDefault, 1, noLoyaltyMax),
enumLoyaltyField(prefix+constants.LoyaltyExpiryUnitSuffix, &s.Unit, constants.LoyaltyExpiryUnitDefault,
constants.LoyaltyExpiryUnitDay, constants.LoyaltyExpiryUnitMonth),
boolLoyaltyField(prefix+constants.LoyaltyExpiryEndOfMonthSuffix, &s.EndOfMonth, false),
intLoyaltyField(prefix+constants.LoyaltyExpiryReminderDaysSuffix, &s.ReminderDays, constants.LoyaltyExpiryReminderDaysDefault, 0, noLoyaltyMax),
}
}
// loyaltyField is one setting key bound to the struct field that holds it. The same
// description drives reading (parse or default), validating, and writing (format).
type loyaltyField struct {
key string
// parse sets the field from a stored value, or reports it unusable.
parse func(raw string) bool
// reset sets the field to its default.
reset func()
// validate checks the field's current value.
validate func() error
// format is the field's current value as stored; nil means no stored value.
format func() *string
}
const noLoyaltyMax = int64(-1)
func intLoyaltyField(key string, v *int64, def, min, max int64) loyaltyField {
check := func(n int64) error {
if n < min {
return fmt.Errorf("%w: %s must be at least %d", ErrInvalidLoyaltySettings, key, min)
}
if max != noLoyaltyMax && n > max {
return fmt.Errorf("%w: %s must be at most %d", ErrInvalidLoyaltySettings, key, max)
}
return nil
}
return loyaltyField{
key: key,
parse: func(raw string) bool {
n, err := strconv.ParseInt(strings.TrimSpace(raw), 10, 64)
if err != nil || check(n) != nil {
return false
}
*v = n
return true
},
reset: func() { *v = def },
validate: func() error { return check(*v) },
format: func() *string { s := strconv.FormatInt(*v, 10); return &s },
}
}
// optionalIntLoyaltyField is a limit that may be unset, meaning no limit.
func optionalIntLoyaltyField(key string, v **int64, min int64) loyaltyField {
return loyaltyField{
key: key,
parse: func(raw string) bool {
n, err := strconv.ParseInt(strings.TrimSpace(raw), 10, 64)
if err != nil || n < min {
return false
}
*v = &n
return true
},
reset: func() { *v = nil },
validate: func() error {
if *v != nil && **v < min {
return fmt.Errorf("%w: %s must be at least %d, or empty for no limit", ErrInvalidLoyaltySettings, key, min)
}
return nil
},
format: func() *string {
if *v == nil {
return nil
}
s := strconv.FormatInt(**v, 10)
return &s
},
}
}
func boolLoyaltyField(key string, v *bool, def bool) loyaltyField {
return loyaltyField{
key: key,
parse: func(raw string) bool {
b, err := strconv.ParseBool(strings.TrimSpace(raw))
if err != nil {
return false
}
*v = b
return true
},
reset: func() { *v = def },
validate: func() error { return nil },
format: func() *string { s := strconv.FormatBool(*v); return &s },
}
}
func enumLoyaltyField(key string, v *string, def string, allowed ...string) loyaltyField {
valid := func(s string) bool {
for _, a := range allowed {
if s == a {
return true
}
}
return false
}
return loyaltyField{
key: key,
parse: func(raw string) bool {
s := strings.ToUpper(strings.TrimSpace(raw))
if !valid(s) {
return false
}
*v = s
return true
},
reset: func() { *v = def },
validate: func() error {
if !valid(*v) {
return fmt.Errorf("%w: %s must be one of %s", ErrInvalidLoyaltySettings, key, strings.Join(allowed, ", "))
}
return nil
},
format: func() *string { s := *v; return &s },
}
}
// dayOfYearListLoyaltyField is a non-empty set of days of the year, stored as sorted
// MM-DD values joined by commas, such as "06-30,12-31".
func dayOfYearListLoyaltyField(key string, v *[]string, def string) loyaltyField {
normalize := func(days []string) ([]string, error) {
out, err := normalizeDaysOfYear(days)
if err != nil {
return nil, fmt.Errorf("%w: %s %v", ErrInvalidLoyaltySettings, key, err)
}
return out, nil
}
return loyaltyField{
key: key,
parse: func(raw string) bool {
days, err := normalize(strings.Split(raw, ","))
if err != nil {
return false
}
*v = days
return true
},
reset: func() { *v, _ = normalizeDaysOfYear(strings.Split(def, ",")) },
validate: func() error {
days, err := normalize(*v)
if err != nil {
return err
}
*v = days
return nil
},
format: func() *string {
days, err := normalizeDaysOfYear(*v)
if err != nil {
days = *v
}
s := strings.Join(days, ",")
return &s
},
}
}
// loadLoyaltyFields fills each field from its stored value, or its default when there
// is none. A stored value that cannot be used also falls back to the default, so a bad
// row can never reach a calculation, and it is logged so it gets fixed.
func loadLoyaltyFields(fields []loyaltyField, raw map[string]string, scope string) {
for _, f := range fields {
f.reset()
value, ok := raw[f.key]
if !ok {
continue
}
if !f.parse(value) {
f.reset()
logger.NonContext.Warnf("Loyalty setting %s of %s has an unusable value %q; using the default", f.key, scope, value)
}
}
}
func validateLoyaltyFields(fields []loyaltyField) error {
for _, f := range fields {
if err := f.validate(); err != nil {
return err
}
}
return nil
}
func equalOptionalStrings(a, b *string) bool {
if a == nil || b == nil {
return a == nil && b == nil
}
return *a == *b
}
// diffLoyaltyFields lists the keys whose effective value differs between current and
// next, with the stored old value (nil when the key was on its default). current and
// next list the same keys in the same order.
func diffLoyaltyFields(organizationID uuid.UUID, outletID *uuid.UUID, changedBy uuid.UUID, raw map[string]string, current, next []loyaltyField) []entities.LoyaltySettingChange {
var rows []entities.LoyaltySettingChange
for i, field := range next {
newValue := field.format()
if equalOptionalStrings(current[i].format(), newValue) {
continue
}
var oldValue *string
if v, ok := raw[field.key]; ok {
oldValue = &v
}
rows = append(rows, entities.LoyaltySettingChange{
OrganizationID: organizationID,
OutletID: outletID,
Key: field.key,
OldValue: oldValue,
NewValue: newValue,
ChangedBy: changedBy,
})
}
return rows
}
// PreviewOrganization validates new organization settings and lists what saving them
// would change, and which balances turning expiry on would date, without writing
// anything.
func (p *LoyaltySettingsProcessor) PreviewOrganization(ctx context.Context, organizationID uuid.UUID, settings models.OrganizationLoyaltySettings) ([]models.LoyaltySettingChange, []models.LoyaltyExpiryActivation, error) {
if err := validateLoyaltyFields(organizationLoyaltyFields(&settings)); err != nil {
return nil, nil, err
}
raw, err := p.repo.GetOrganizationValues(ctx, organizationID)
if err != nil {
return nil, nil, err
}
var current models.OrganizationLoyaltySettings
loadLoyaltyFields(organizationLoyaltyFields(&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))
}
activations, err := p.expiryActivations(ctx, organizationID, current, settings, false)
if err != nil {
return nil, nil, err
}
return changes, activations, nil
}
@@ -0,0 +1,385 @@
package processor
import (
"context"
"os"
"testing"
"time"
"github.com/google/uuid"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"apskel-pos-be/internal/constants"
"apskel-pos-be/internal/entities"
"apskel-pos-be/internal/logger"
"apskel-pos-be/internal/models"
"apskel-pos-be/internal/repository"
)
func TestMain(m *testing.M) {
// Some processors log; the server sets the logger up at startup.
logger.Setup("fatal", "json")
os.Exit(m.Run())
}
// loyaltyRepoFake keeps settings in maps. It does not check for a transaction.
type loyaltyRepoFake struct {
outletOrg map[uuid.UUID]uuid.UUID
outletValues map[string]string
orgValues map[string]string
changes []entities.LoyaltySettingChange
locks []uuid.UUID
// Lots without an expiry per currency: how many and what they hold.
undated map[string][2]int64
dated map[string]time.Time
}
func (f *loyaltyRepoFake) GetOutletValues(context.Context, uuid.UUID) (map[string]string, error) {
return copyStringMap(f.outletValues), nil
}
func (f *loyaltyRepoFake) GetOrganizationValues(context.Context, uuid.UUID) (map[string]string, error) {
return copyStringMap(f.orgValues), nil
}
func (f *loyaltyRepoFake) OutletOrganizationID(_ context.Context, outletID uuid.UUID) (uuid.UUID, error) {
org, ok := f.outletOrg[outletID]
if !ok {
return uuid.Nil, repository.ErrLoyaltyOutletNotFound
}
return org, nil
}
func (f *loyaltyRepoFake) LockScope(_ context.Context, id uuid.UUID) error {
f.locks = append(f.locks, id)
return nil
}
func (f *loyaltyRepoFake) SetOutletValue(_ context.Context, _ uuid.UUID, key string, value *string) error {
f.outletValues = setOptional(f.outletValues, key, value)
return nil
}
func (f *loyaltyRepoFake) SetOrganizationValue(_ context.Context, _ uuid.UUID, key string, value *string) error {
f.orgValues = setOptional(f.orgValues, key, value)
return nil
}
func (f *loyaltyRepoFake) InsertChanges(_ context.Context, changes []entities.LoyaltySettingChange) error {
f.changes = append(f.changes, changes...)
return nil
}
func (f *loyaltyRepoFake) ListChanges(context.Context, repository.LoyaltySettingChangeFilter) ([]entities.LoyaltySettingChange, int64, error) {
return f.changes, int64(len(f.changes)), nil
}
func copyStringMap(m map[string]string) map[string]string {
out := make(map[string]string, len(m))
for k, v := range m {
out[k] = v
}
return out
}
func setOptional(m map[string]string, key string, value *string) map[string]string {
if m == nil {
m = map[string]string{}
}
if value == nil {
delete(m, key)
} else {
m[key] = *value
}
return m
}
// txRunnerFake runs fn in place.
type txRunnerFake struct{}
func (txRunnerFake) WithTransaction(ctx context.Context, fn func(ctx context.Context) error) error {
return fn(ctx)
}
func TestLoyaltySettings_OutletWithoutSettingsGetsEveryDefault(t *testing.T) {
p := NewLoyaltySettingsProcessor(&loyaltyRepoFake{}, txRunnerFake{})
s, err := p.Outlet(context.Background(), uuid.New())
require.NoError(t, err)
assert.Equal(t, models.OutletLoyaltySettings{
Point: models.LoyaltyEarnSettings{Enabled: false, EarnPerAmount: 100, EarnValue: 1, MinOrderAmount: 0, MaxPerOrder: nil},
Coin: models.LoyaltyEarnSettings{Enabled: false, EarnPerAmount: 25000, EarnValue: 1, MinOrderAmount: 0, MaxPerOrder: nil},
PointPayment: models.LoyaltyPointPaymentSettings{AcceptPayment: false, MinPaymentPoints: 1, MaxPaymentPercent: 100},
}, *s)
}
func TestLoyaltySettings_OrganizationWithoutSettingsGetsEveryDefault(t *testing.T) {
p := NewLoyaltySettingsProcessor(&loyaltyRepoFake{}, txRunnerFake{})
s, err := p.Organization(context.Background(), uuid.New())
require.NoError(t, err)
expiry := models.LoyaltyExpirySettings{Enabled: false, Mode: "FIXED_DATE", FixedDates: []string{"12-31"}, GraceMonths: 3, Period: 12, Unit: "MONTH", EndOfMonth: false, ReminderDays: 7}
assert.Equal(t, models.OrganizationLoyaltySettings{
PointValue: 1,
Exchange: models.LoyaltyExchangeSettings{CoinAmount: 1, PointAmount: 1},
Transfer: models.LoyaltyTransferSettings{Enabled: true, MinAmount: 1},
PointExpiry: expiry,
CoinExpiry: expiry,
}, *s)
}
func TestLoyaltySettings_StoredValuesAreTyped(t *testing.T) {
repo := &loyaltyRepoFake{
outletValues: map[string]string{
constants.LoyaltyPointEnabledKey: "true",
constants.LoyaltyPointEarnPerAmountKey: " 1000 ",
constants.LoyaltyPointMaxPerOrderKey: "500",
constants.LoyaltyPointMaxPaymentPercentKey: "50",
"loyalty.unknown": "ignored",
},
orgValues: map[string]string{
constants.LoyaltyPointValueKey: "100",
constants.LoyaltyTransferDailyLimitKey: "10000",
"loyalty.coin.expiry_unit": "day",
"loyalty.point.expiry_fixed_dates": "12-31, 06-30,12-31",
"loyalty.coin.expiry_mode": "rolling",
},
}
p := NewLoyaltySettingsProcessor(repo, txRunnerFake{})
outlet, err := p.Outlet(context.Background(), uuid.New())
require.NoError(t, err)
assert.True(t, outlet.Point.Enabled)
assert.Equal(t, int64(1000), outlet.Point.EarnPerAmount)
assert.Equal(t, int64(500), *outlet.Point.MaxPerOrder)
assert.Equal(t, int64(50), outlet.PointPayment.MaxPaymentPercent)
org, err := p.Organization(context.Background(), uuid.New())
require.NoError(t, err)
assert.Equal(t, int64(100), org.PointValue)
assert.Equal(t, int64(10000), *org.Transfer.DailyLimit)
assert.Equal(t, "DAY", org.CoinExpiry.Unit)
assert.Equal(t, "MONTH", org.PointExpiry.Unit)
assert.Equal(t, []string{"06-30", "12-31"}, org.PointExpiry.FixedDates)
assert.Equal(t, "ROLLING", org.CoinExpiry.Mode)
assert.Equal(t, "FIXED_DATE", org.PointExpiry.Mode)
}
// A bad row must never reach a calculation: earn_per_amount 0 would divide by zero.
func TestLoyaltySettings_UnusableStoredValuesFallBackToDefault(t *testing.T) {
repo := &loyaltyRepoFake{
outletValues: map[string]string{
constants.LoyaltyPointEnabledKey: "yes please",
constants.LoyaltyPointEarnPerAmountKey: "0",
constants.LoyaltyCoinEarnValueKey: "-1",
constants.LoyaltyPointMaxPerOrderKey: "abc",
constants.LoyaltyPointMaxPaymentPercentKey: "150",
},
orgValues: map[string]string{
constants.LoyaltyPointValueKey: "0",
"loyalty.point.expiry_unit": "YEAR",
"loyalty.point.expiry_period": "",
},
}
p := NewLoyaltySettingsProcessor(repo, txRunnerFake{})
outlet, err := p.Outlet(context.Background(), uuid.New())
require.NoError(t, err)
assert.False(t, outlet.Point.Enabled)
assert.Equal(t, int64(100), outlet.Point.EarnPerAmount)
assert.Equal(t, int64(1), outlet.Coin.EarnValue)
assert.Nil(t, outlet.Point.MaxPerOrder)
assert.Equal(t, int64(100), outlet.PointPayment.MaxPaymentPercent)
for name, raw := range map[string]string{"not set": "", "garbage": "abc", "zero": "0", "negative": "-5"} {
repo.orgValues = map[string]string{}
if raw != "" {
repo.orgValues[constants.LoyaltyPointValueKey] = raw
}
value, err := p.PointValue(context.Background(), uuid.New())
require.NoError(t, err)
assert.Equal(t, constants.LoyaltyPointValueDefault, value, name)
}
}
func TestLoyaltySettings_UpdateRecordsOnlyRealChanges(t *testing.T) {
org, outlet, admin := uuid.New(), uuid.New(), uuid.New()
repo := &loyaltyRepoFake{
outletOrg: map[uuid.UUID]uuid.UUID{outlet: org},
outletValues: map[string]string{constants.LoyaltyPointEarnPerAmountKey: "200"},
}
p := NewLoyaltySettingsProcessor(repo, txRunnerFake{})
ctx := context.Background()
settings, err := p.Outlet(ctx, outlet)
require.NoError(t, err)
settings.Point.Enabled = true // default false -> true
settings.Point.EarnPerAmount = 100 // stored 200 -> 100 (the default, but set explicitly)
settings.Point.MaxPerOrder = ptr(int64(0)) // unset -> 0
// Everything else stays on its default.
changes, err := p.UpdateOutlet(ctx, org, outlet, admin, *settings)
require.NoError(t, err)
byKey := map[string]models.LoyaltySettingChange{}
for _, c := range changes {
byKey[c.Key] = c
assert.Equal(t, admin, c.ChangedBy)
assert.Equal(t, org, c.OrganizationID)
assert.Equal(t, &outlet, c.OutletID)
}
require.Len(t, byKey, 3, "only the three keys that changed")
assert.Nil(t, byKey[constants.LoyaltyPointEnabledKey].OldValue, "was on its default")
assert.Equal(t, "true", *byKey[constants.LoyaltyPointEnabledKey].NewValue)
assert.Equal(t, "200", *byKey[constants.LoyaltyPointEarnPerAmountKey].OldValue)
assert.Equal(t, "100", *byKey[constants.LoyaltyPointEarnPerAmountKey].NewValue)
assert.Equal(t, "0", *byKey[constants.LoyaltyPointMaxPerOrderKey].NewValue)
assert.Len(t, repo.changes, 3)
assert.Equal(t, []uuid.UUID{outlet}, repo.locks)
after, err := p.Outlet(ctx, outlet)
require.NoError(t, err)
assert.Equal(t, *settings, *after)
// Saving the same settings again changes nothing and records nothing.
changes, err = p.UpdateOutlet(ctx, org, outlet, admin, *after)
require.NoError(t, err)
assert.Empty(t, changes)
assert.Len(t, repo.changes, 3)
// Clearing a limit removes the stored value, recorded as a change to nothing.
after.Point.MaxPerOrder = nil
changes, err = p.UpdateOutlet(ctx, org, outlet, admin, *after)
require.NoError(t, err)
require.Len(t, changes, 1)
assert.Equal(t, "0", *changes[0].OldValue)
assert.Nil(t, changes[0].NewValue)
assert.NotContains(t, repo.outletValues, constants.LoyaltyPointMaxPerOrderKey)
}
func TestLoyaltySettings_UpdateOrganization(t *testing.T) {
org, admin := uuid.New(), uuid.New()
repo := &loyaltyRepoFake{}
p := NewLoyaltySettingsProcessor(repo, txRunnerFake{})
ctx := context.Background()
settings, err := p.Organization(ctx, org)
require.NoError(t, err)
settings.PointValue = 100
settings.CoinExpiry.Enabled = true
settings.CoinExpiry.Unit = constants.LoyaltyExpiryUnitDay
changes, _, err := p.UpdateOrganization(ctx, org, admin, *settings)
require.NoError(t, err)
keys := []string{}
for _, c := range changes {
keys = append(keys, c.Key)
assert.Nil(t, c.OutletID, "organization settings have no outlet")
}
assert.ElementsMatch(t, []string{constants.LoyaltyPointValueKey, "loyalty.coin.expiry_enabled", "loyalty.coin.expiry_unit"}, keys)
value, err := p.PointValue(ctx, org)
require.NoError(t, err)
assert.Equal(t, int64(100), value)
}
func TestLoyaltySettings_UpdateRejectsInvalidValues(t *testing.T) {
org, outlet := uuid.New(), uuid.New()
repo := &loyaltyRepoFake{outletOrg: map[uuid.UUID]uuid.UUID{outlet: org}}
p := NewLoyaltySettingsProcessor(repo, txRunnerFake{})
ctx := context.Background()
for name, mutate := range map[string]func(*models.OutletLoyaltySettings){
"earn_per_amount 0": func(s *models.OutletLoyaltySettings) { s.Point.EarnPerAmount = 0 },
"negative earn_value": func(s *models.OutletLoyaltySettings) { s.Coin.EarnValue = -1 },
"negative min_order": func(s *models.OutletLoyaltySettings) { s.Point.MinOrderAmount = -1 },
"negative max_per_order": func(s *models.OutletLoyaltySettings) { s.Coin.MaxPerOrder = ptr(int64(-1)) },
"payment percent over 100": func(s *models.OutletLoyaltySettings) { s.PointPayment.MaxPaymentPercent = 101 },
"negative payment percent": func(s *models.OutletLoyaltySettings) { s.PointPayment.MaxPaymentPercent = -1 },
"min payment points 0": func(s *models.OutletLoyaltySettings) { s.PointPayment.MinPaymentPoints = 0 },
} {
s, err := p.Outlet(ctx, outlet)
require.NoError(t, err)
mutate(s)
_, err = p.UpdateOutlet(ctx, org, outlet, uuid.New(), *s)
assert.ErrorIs(t, err, ErrInvalidLoyaltySettings, name)
}
for name, mutate := range map[string]func(*models.OrganizationLoyaltySettings){
"point value 0": func(s *models.OrganizationLoyaltySettings) { s.PointValue = 0 },
"exchange coin amount 0": func(s *models.OrganizationLoyaltySettings) { s.Exchange.CoinAmount = 0 },
"transfer min 0": func(s *models.OrganizationLoyaltySettings) { s.Transfer.MinAmount = 0 },
"daily limit 0": func(s *models.OrganizationLoyaltySettings) { s.Transfer.DailyLimit = ptr(int64(0)) },
"expiry period 0": func(s *models.OrganizationLoyaltySettings) { s.PointExpiry.Period = 0 },
"expiry unit YEAR": func(s *models.OrganizationLoyaltySettings) { s.CoinExpiry.Unit = "YEAR" },
"negative reminder days": func(s *models.OrganizationLoyaltySettings) { s.CoinExpiry.ReminderDays = -1 },
"expiry mode YEARLY": func(s *models.OrganizationLoyaltySettings) { s.PointExpiry.Mode = "YEARLY" },
"no fixed dates": func(s *models.OrganizationLoyaltySettings) { s.PointExpiry.FixedDates = nil },
"fixed date 13-01": func(s *models.OrganizationLoyaltySettings) { s.PointExpiry.FixedDates = []string{"13-01"} },
"fixed date 02-29": func(s *models.OrganizationLoyaltySettings) { s.CoinExpiry.FixedDates = []string{"02-29"} },
"negative grace": func(s *models.OrganizationLoyaltySettings) { s.CoinExpiry.GraceMonths = -1 },
} {
s, err := p.Organization(ctx, org)
require.NoError(t, err)
mutate(s)
_, _, err = p.UpdateOrganization(ctx, org, uuid.New(), *s)
assert.ErrorIs(t, err, ErrInvalidLoyaltySettings, name)
}
assert.Empty(t, repo.changes, "nothing is written when a value is invalid")
assert.Empty(t, repo.locks, "invalid input is rejected before touching the database")
// An outlet of another organization.
s, err := p.Outlet(ctx, outlet)
require.NoError(t, err)
_, err = p.UpdateOutlet(ctx, uuid.New(), outlet, uuid.New(), *s)
assert.ErrorIs(t, err, repository.ErrLoyaltyOutletNotFound)
_, err = p.UpdateOutlet(ctx, org, uuid.New(), uuid.New(), *s)
assert.ErrorIs(t, err, repository.ErrLoyaltyOutletNotFound)
}
func (f *loyaltyRepoFake) UndatedBalance(_ context.Context, _ uuid.UUID, currency string) (int64, int64, error) {
u := f.undated[currency]
return u[0], u[1], nil
}
func (f *loyaltyRepoFake) DateUndatedLots(_ context.Context, _ uuid.UUID, currency string, expiresAt time.Time) (int64, int64, error) {
u := f.undated[currency]
if f.dated == nil {
f.dated = map[string]time.Time{}
}
f.dated[currency] = expiresAt
delete(f.undated, currency)
return u[0], u[1], nil
}
// Turning expiry on dates the balances that had none, a full cycle away; a dry run
// only counts them, and saving again dates nothing more.
func TestLoyaltySettings_TurningExpiryOnDatesExistingBalances(t *testing.T) {
org, admin := uuid.New(), uuid.New()
repo := &loyaltyRepoFake{undated: map[string][2]int64{"POINT": {3, 1500}, "COIN": {2, 40}}}
p := NewLoyaltySettingsProcessor(repo, txRunnerFake{})
p.now = func() time.Time { return time.Date(2026, 11, 20, 3, 0, 0, 0, time.UTC) }
ctx := context.Background()
settings, err := p.Organization(ctx, org)
require.NoError(t, err)
settings.PointExpiry.Enabled = true
_, preview, err := p.PreviewOrganization(ctx, org, *settings)
require.NoError(t, err)
require.Len(t, preview, 1)
assert.Equal(t, "POINT", preview[0].Currency)
assert.Equal(t, int64(1500), preview[0].Amount)
assert.Empty(t, repo.dated, "a dry run dates nothing")
_, activations, err := p.UpdateOrganization(ctx, org, admin, *settings)
require.NoError(t, err)
require.Len(t, activations, 1)
assert.Equal(t, int64(3), activations[0].Lots)
// Default FIXED_DATE on 31 Dec: the second one after 20 Nov 2026.
assert.Equal(t, "2027-12-31", activations[0].ExpiresAt.In(walletDisplayLocation).Format("2006-01-02"))
assert.Equal(t, activations[0].ExpiresAt, repo.dated["POINT"])
assert.NotContains(t, repo.dated, "COIN", "EnakCoin expiry stays off")
_, again, err := p.UpdateOrganization(ctx, org, admin, *settings)
require.NoError(t, err)
assert.Empty(t, again, "already on: nothing is activated twice")
}
+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)
}
+253 -2
View File
@@ -5,8 +5,10 @@ import (
"errors"
"fmt"
"apskel-pos-be/internal/appcontext"
"apskel-pos-be/internal/constants"
"apskel-pos-be/internal/entities"
"apskel-pos-be/internal/logger"
"apskel-pos-be/internal/mappers"
"apskel-pos-be/internal/models"
"apskel-pos-be/internal/repository"
@@ -19,6 +21,9 @@ type OrderProcessor interface {
CreateOrder(ctx context.Context, req *models.CreateOrderRequest, organizationID uuid.UUID) (*models.OrderResponse, error)
AddToOrder(ctx context.Context, orderID uuid.UUID, req *models.AddToOrderRequest) (*models.AddToOrderResponse, error)
UpdateOrder(ctx context.Context, id uuid.UUID, req *models.UpdateOrderRequest) (*models.OrderResponse, error)
// PayWithPointsInApp pays the customer's own order with EnakPoint from the app or a
// self-order, approved by their PIN (docs/prd-point-coin.md F9).
PayWithPointsInApp(ctx context.Context, customerID, orderID uuid.UUID, points int64, pin string, info models.CustomerPinRequestInfo) (*models.PaymentResponse, error)
GetOrderByID(ctx context.Context, id uuid.UUID) (*models.OrderResponse, error)
ListOrders(ctx context.Context, req *models.ListOrdersRequest) (*models.ListOrdersResponse, error)
VoidOrder(ctx context.Context, req *models.VoidOrderRequest, voidedBy uuid.UUID) error
@@ -109,6 +114,139 @@ type OrderProcessorImpl struct {
ingredientRepo IngredientRepository
inventoryMovementService InventoryMovementService
productOutletPriceRepo repository.ProductOutletPriceRepository
loyalty OrderLoyalty
pointPayments *PointPaymentProcessor
paymentCodes paymentCodeRedeemer
pins pinVerifier
}
// OrderLoyalty is what the order flow tells and asks the loyalty program
// (docs/prd-point-coin.md F3, F10). EarningProcessor is one.
type OrderLoyalty interface {
// OnOrderPaid runs once an order has just become fully paid and the payment has
// committed.
OnOrderPaid(ctx context.Context, orderID uuid.UUID)
// OnOrderRefunded runs once an order has been voided or (partly) refunded and that
// has committed.
OnOrderRefunded(ctx context.Context, orderID uuid.UUID)
// EarnedByOrders returns what each order earned.
EarnedByOrders(ctx context.Context, orderIDs []uuid.UUID) (map[uuid.UUID]OrderEarned, error)
}
// OrderEarned is what one order earned, as written in its EARN rows.
type OrderEarned struct {
Points int64
Coins int64
}
// SetLoyalty connects the order flow to the loyalty program.
func (p *OrderProcessorImpl) SetLoyalty(loyalty OrderLoyalty) {
p.loyalty = loyalty
}
type paymentCodeRedeemer interface {
Redeem(ctx context.Context, code string, customerID uuid.UUID) error
}
// SetPointPayments enables paying with the EnakPoint method. CreatePayment hands such
// payments to pointPayments approved by the code the customer shows at the cashier,
// and PayWithPointsInApp approved by the customer's PIN (F9).
func (p *OrderProcessorImpl) SetPointPayments(pointPayments *PointPaymentProcessor, codes paymentCodeRedeemer, pins pinVerifier) {
p.pointPayments = pointPayments
p.paymentCodes = codes
p.pins = pins
}
// createPointPayment is CreatePayment for the EnakPoint method. It never uses the
// generic payment path, which would record the payment without taking any balance.
func (p *OrderProcessorImpl) createPointPayment(ctx context.Context, req *models.CreatePaymentRequest) (*models.PaymentResponse, error) {
if p.pointPayments == nil || p.paymentCodes == nil {
return nil, fmt.Errorf("%w: paying with EnakPoint is not available", ErrPointPaymentRejected)
}
if req.Points == nil || req.PaymentCode == nil || *req.PaymentCode == "" {
return nil, fmt.Errorf("%w: points and the customer's payment code are required", ErrPointPaymentRejected)
}
var cashier *uuid.UUID
if id := appcontext.FromContext(ctx).UserID; id != uuid.Nil {
cashier = &id
}
code := *req.PaymentCode
result, err := p.pointPayments.Pay(ctx, PointPaymentInput{
OrderID: req.OrderID,
PaymentMethodID: req.PaymentMethodID,
Points: *req.Points,
CashierID: cashier,
Authorize: func(ctx context.Context, customerID uuid.UUID) error {
if err := p.paymentCodes.Redeem(ctx, code, customerID); err != nil {
return fmt.Errorf("%w: %v", ErrPointPaymentRejected, err)
}
return nil
},
})
if err != nil {
return nil, err
}
if result.Completed {
p.onOrderPaid(ctx, req.OrderID)
}
payment, err := p.paymentRepo.GetByID(ctx, result.Payment.ID)
if err != nil {
return nil, fmt.Errorf("failed to retrieve created payment: %w", err)
}
return mappers.PaymentEntityToResponse(payment), nil
}
// onOrderPaid is the single place every path that completes an order's payment goes
// through: UpdateOrder, CreatePayment and both kinds of split bill. It must be called
// after the payment has committed. The hook runs detached from the caller's
// transaction and from the request being cancelled, and anything it does cannot fail
// the payment.
func (p *OrderProcessorImpl) onOrderPaid(ctx context.Context, orderID uuid.UUID) {
if p.loyalty == nil {
return
}
p.loyalty.OnOrderPaid(repository.DetachTransaction(context.WithoutCancel(ctx)), orderID)
}
// onOrderRefunded is called at the end of VoidOrder, RefundOrder and RefundPayment,
// after their writes have committed, with the same guarantees as onOrderPaid: it can
// never block or fail the void or refund.
func (p *OrderProcessorImpl) onOrderRefunded(ctx context.Context, orderID uuid.UUID) {
ctx = repository.DetachTransaction(context.WithoutCancel(ctx))
// EnakPoint paid on the order comes back first: the customer is owed it (F9).
if p.pointPayments != nil {
if _, err := p.pointPayments.RefundForOrder(ctx, orderID); err != nil {
logger.FromContext(ctx).WithError(err).Error("OrderProcessorImpl::onOrderRefunded -> failed to return EnakPoint; calling it again is safe")
}
}
if p.loyalty != nil {
p.loyalty.OnOrderRefunded(ctx, orderID)
}
}
// attachEarnings fills points_earned and coins_earned (F3). A failure is logged and
// leaves them at zero rather than failing the order read.
func (p *OrderProcessorImpl) attachEarnings(ctx context.Context, responses ...*models.OrderResponse) {
if p.loyalty == nil || len(responses) == 0 {
return
}
ids := make([]uuid.UUID, 0, len(responses))
for _, r := range responses {
if r != nil {
ids = append(ids, r.ID)
}
}
earned, err := p.loyalty.EarnedByOrders(repository.DetachTransaction(ctx), ids)
if err != nil {
logger.FromContext(ctx).WithError(err).Error("OrderProcessorImpl::attachEarnings -> failed to read earnings")
return
}
for _, r := range responses {
if r != nil {
e := earned[r.ID]
r.PointsEarned, r.CoinsEarned = e.Points, e.Coins
}
}
}
func NewOrderProcessorImpl(
@@ -297,6 +435,7 @@ func (p *OrderProcessorImpl) CreateOrder(ctx context.Context, req *models.Create
}
response := mappers.OrderEntityToResponse(orderWithRelations)
p.attachEarnings(ctx, response)
return response, nil
}
@@ -435,6 +574,7 @@ func (p *OrderProcessorImpl) AddToOrder(ctx context.Context, orderID uuid.UUID,
}
updatedOrderResponse := mappers.OrderEntityToResponse(orderWithRelations)
p.attachEarnings(ctx, updatedOrderResponse)
return &models.AddToOrderResponse{
OrderID: orderID,
@@ -494,6 +634,7 @@ func (p *OrderProcessorImpl) UpdateOrder(ctx context.Context, id uuid.UUID, req
if err := p.orderRepo.UpdateStatusSuccess(ctx, order.ID, order.Status, order.PaymentStatus); err != nil {
return nil, fmt.Errorf("failed to update order: %w", err)
}
p.onOrderPaid(ctx, order.ID)
orderWithRelations, err := p.orderRepo.GetWithRelations(ctx, id)
if err != nil {
@@ -501,6 +642,7 @@ func (p *OrderProcessorImpl) UpdateOrder(ctx context.Context, id uuid.UUID, req
}
response := mappers.OrderEntityToResponse(orderWithRelations)
p.attachEarnings(ctx, response)
return response, nil
}
@@ -511,6 +653,7 @@ func (p *OrderProcessorImpl) GetOrderByID(ctx context.Context, id uuid.UUID) (*m
}
response := mappers.OrderEntityToResponse(order)
p.attachEarnings(ctx, response)
return response, nil
}
@@ -572,6 +715,11 @@ func (p *OrderProcessorImpl) ListOrders(ctx context.Context, req *models.ListOrd
}
}
}
listed := make([]*models.OrderResponse, len(orderResponses))
for i := range orderResponses {
listed[i] = &orderResponses[i]
}
p.attachEarnings(ctx, listed...)
totalPages := int(total) / req.Limit
if int(total)%req.Limit > 0 {
@@ -692,6 +840,10 @@ func (p *OrderProcessorImpl) VoidOrder(ctx context.Context, req *models.VoidOrde
return fmt.Errorf("invalid void type: must be 'ALL' or 'ITEM'")
}
// VoidOrder refuses fully paid orders today, so there is usually nothing to take
// back; this keeps a void correct if that rule changes. The order repository writes
// outside the caller's transaction, so the void is already committed here.
p.onOrderRefunded(ctx, req.OrderID)
return nil
}
@@ -714,6 +866,18 @@ func (p *OrderProcessorImpl) RefundOrder(ctx context.Context, id uuid.UUID, req
reason = *req.Reason
}
// An order refund is handed back in cash or another method, so it cannot cover what
// was paid with EnakPoint (K7). Checked before anything is written.
if p.pointPayments != nil {
planned, err := p.plannedOrderRefund(ctx, id, req)
if err != nil {
return err
}
if err := p.pointPayments.EnsureOrderRefundAllowed(ctx, id, planned); err != nil {
return err
}
}
// Process refund based on request type
if req.RefundAmount != nil {
// Full or partial refund by amount
@@ -787,6 +951,7 @@ func (p *OrderProcessorImpl) RefundOrder(ctx context.Context, id uuid.UUID, req
}
}
p.onOrderRefunded(ctx, id)
return nil
}
@@ -804,10 +969,13 @@ func (p *OrderProcessorImpl) CreatePayment(ctx context.Context, req *models.Crea
return nil, fmt.Errorf("order is already fully paid")
}
_, err = p.paymentMethodRepo.GetByID(ctx, req.PaymentMethodID)
method, err := p.paymentMethodRepo.GetByID(ctx, req.PaymentMethodID)
if err != nil {
return nil, fmt.Errorf("payment method not found: %w", err)
}
if method.Type == entities.PaymentMethodTypePoint {
return p.createPointPayment(ctx, req)
}
totalPaid, err := p.paymentRepo.GetTotalPaidByOrderID(ctx, req.OrderID)
if err != nil {
@@ -818,6 +986,8 @@ func (p *OrderProcessorImpl) CreatePayment(ctx context.Context, req *models.Crea
if err != nil {
return nil, err
}
// Not from updateOrderStatus: that runs inside the payment's transaction.
p.onOrderPaid(ctx, req.OrderID)
paymentWithRelations, err := p.paymentRepo.GetByID(ctx, payment.ID)
if err != nil {
@@ -842,7 +1012,11 @@ func (p *OrderProcessorImpl) RefundPayment(ctx context.Context, paymentID uuid.U
return fmt.Errorf("refund amount cannot exceed payment amount")
}
return p.RefundPaymentWithInventoryMovement(ctx, paymentID, refundAmount, reason, refundedBy, payment)
if err := p.RefundPaymentWithInventoryMovement(ctx, paymentID, refundAmount, reason, refundedBy, payment); err != nil {
return err
}
p.onOrderRefunded(ctx, payment.OrderID)
return nil
}
func (p *OrderProcessorImpl) CreatePaymentWithInventoryMovement(ctx context.Context, req *models.CreatePaymentRequest, order *entities.Order, totalPaid float64) (*entities.Payment, error) {
@@ -1186,6 +1360,11 @@ func (p *OrderProcessorImpl) SplitBill(ctx context.Context, req *models.SplitBil
if err != nil {
return nil, fmt.Errorf("payment method not found: %w", err)
}
// Splitting with EnakPoint would record a payment without taking any balance; an
// EnakPoint part goes through CreatePayment and the rest is split as usual (F9).
if payment.Type == entities.PaymentMethodTypePoint {
return nil, fmt.Errorf("%w: pay the EnakPoint part as its own payment, not as a split", ErrPointPaymentRejected)
}
customer := &entities.Customer{}
if req.CustomerID != uuid.Nil {
@@ -1207,6 +1386,10 @@ func (p *OrderProcessorImpl) SplitBill(ctx context.Context, req *models.SplitBil
if err != nil {
return nil, err
}
// Both split paths mark the order paid on the payment that settles it.
if order.PaymentStatus == entities.PaymentStatusCompleted {
p.onOrderPaid(ctx, order.ID)
}
return response, nil
}
@@ -1628,3 +1811,71 @@ func (p *OrderProcessorImpl) prepareRefundedIngredientRecipeItem(ctx context.Con
func stringPtr(s string) *string {
return &s
}
// PayWithPointsInApp pays an order with EnakPoint on the customer's own request, in the
// app or a self-order. The session alone is not enough: the customer's PIN approves
// it (K8). An order that is not the customer's own is reported as not found, so the
// endpoint does not reveal other customers' orders.
func (p *OrderProcessorImpl) PayWithPointsInApp(ctx context.Context, customerID, orderID uuid.UUID, points int64, pin string, info models.CustomerPinRequestInfo) (*models.PaymentResponse, error) {
if p.pointPayments == nil || p.pins == nil {
return nil, fmt.Errorf("%w: paying with EnakPoint is not available", ErrPointPaymentRejected)
}
organizationID, owner, err := p.pointPayments.OrderOwner(ctx, orderID)
if err != nil {
return nil, err
}
if owner == nil || *owner != customerID {
return nil, repository.ErrPointPaymentOrderNotFound
}
methodID, err := p.pointPayments.PointMethodID(ctx, organizationID)
if err != nil {
return nil, err
}
result, err := p.pointPayments.Pay(ctx, PointPaymentInput{
OrderID: orderID,
PaymentMethodID: methodID,
Points: points,
Authorize: func(ctx context.Context, customerID uuid.UUID) error {
return p.pins.VerifyPin(ctx, customerID, pin, PinActionPay, info)
},
})
if err != nil {
return nil, err
}
if result.Completed {
p.onOrderPaid(ctx, orderID)
}
payment, err := p.paymentRepo.GetByID(ctx, result.Payment.ID)
if err != nil {
return nil, fmt.Errorf("failed to retrieve created payment: %w", err)
}
return mappers.PaymentEntityToResponse(payment), nil
}
// plannedOrderRefund is the total RefundOrder is about to hand back, computed the same
// way it will be, without writing anything.
func (p *OrderProcessorImpl) plannedOrderRefund(ctx context.Context, orderID uuid.UUID, req *models.RefundOrderRequest) (float64, error) {
if req.RefundAmount != nil {
return *req.RefundAmount, nil
}
var total float64
for _, itemRefund := range req.OrderItems {
if itemRefund.RefundAmount != nil {
total += *itemRefund.RefundAmount
continue
}
orderItem, err := p.orderItemRepo.GetByID(ctx, itemRefund.OrderItemID)
if err != nil {
return 0, fmt.Errorf("order item not found: %w", err)
}
if orderItem.OrderID != orderID {
return 0, fmt.Errorf("order item does not belong to this order")
}
quantity := itemRefund.RefundQuantity
if quantity == 0 {
quantity = orderItem.Quantity
}
total += entities.RoundMoney(orderItem.BillableQuantityFor(quantity) * orderItem.UnitPrice)
}
return total, nil
}
+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
+401
View File
@@ -0,0 +1,401 @@
package processor
import (
"context"
"os"
"sync"
"testing"
"time"
"github.com/alicebob/miniredis/v2"
"github.com/google/uuid"
"github.com/redis/go-redis/v9"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"gorm.io/driver/postgres"
"gorm.io/gorm"
"gorm.io/gorm/logger"
"apskel-pos-be/internal/appcontext"
"apskel-pos-be/internal/constants"
"apskel-pos-be/internal/models"
"apskel-pos-be/internal/repository"
)
// pointPaymentEnv is an order flow wired as in the app, against Postgres and a
// miniredis for payment codes.
type pointPaymentEnv struct {
t *testing.T
db *gorm.DB
orders *OrderProcessorImpl
payments *PointPaymentProcessor
codes *PaymentCodeProcessor
org uuid.UUID
cashier uuid.UUID
outlet uuid.UUID
point uuid.UUID
cash uuid.UUID
walkIn uuid.UUID
ctx context.Context
}
func newPointPaymentEnv(t *testing.T) *pointPaymentEnv {
t.Helper()
dsn := os.Getenv("TEST_DATABASE_URL")
if dsn == "" {
t.Skip("TEST_DATABASE_URL not set")
}
db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{Logger: logger.Default.LogMode(logger.Silent)})
require.NoError(t, err)
e := &pointPaymentEnv{t: t, db: db, org: uuid.New(), cashier: uuid.New(), outlet: uuid.New(), cash: uuid.New()}
e.exec(`INSERT INTO organizations (id, name, plan_type) VALUES (?, 'point pay test', 'basic')`, e.org)
e.exec(`INSERT INTO users (id, organization_id, name, email, password_hash, role) VALUES (?, ?, 'Kasir', ?, 'x', 'cashier')`, e.cashier, e.org, e.cashier.String()+"@t")
e.exec(`INSERT INTO outlets (id, organization_id, name) VALUES (?, ?, 'Kemang')`, e.outlet, e.org)
e.exec(`INSERT INTO payment_methods (id, organization_id, name, type) VALUES (?, ?, 'Tunai', 'cash')`, e.cash, e.org)
var ids []string
require.NoError(t, db.Raw(`SELECT id::text FROM payment_methods WHERE organization_id = ? AND type = 'point'`, e.org).Scan(&ids).Error)
require.Len(t, ids, 1)
e.point = uuid.MustParse(ids[0])
require.NoError(t, db.Raw(`SELECT id::text FROM customers WHERE organization_id = ? AND is_default`, e.org).Scan(&ids).Error)
e.walkIn = uuid.MustParse(ids[0])
t.Cleanup(func() {
db.Exec(`DELETE FROM wallet_lot_allocations WHERE lot_id IN (SELECT id FROM wallet_lots WHERE organization_id = ?)`, e.org)
db.Exec(`DELETE FROM wallet_lots WHERE organization_id = ?`, e.org)
db.Exec(`DELETE FROM wallet_transactions WHERE organization_id = ?`, e.org)
db.Exec(`DELETE FROM customer_wallets WHERE organization_id = ?`, e.org)
db.Exec(`DELETE FROM payments WHERE order_id IN (SELECT id FROM orders WHERE organization_id = ?)`, e.org)
db.Exec(`DELETE FROM orders WHERE organization_id = ?`, e.org)
db.Exec(`DELETE FROM loyalty_setting_changes WHERE organization_id = ?`, e.org)
db.Exec(`DELETE FROM outlet_settings WHERE outlet_id = ?`, e.outlet)
db.Exec(`DELETE FROM payment_methods WHERE organization_id = ?`, e.org)
db.Exec(`DELETE FROM customers WHERE organization_id = ?`, e.org)
db.Exec(`DELETE FROM outlets WHERE id = ?`, e.outlet)
db.Exec(`DELETE FROM users WHERE id = ?`, e.cashier)
db.Exec(`DELETE FROM organizations WHERE id = ?`, e.org)
})
txm := repository.NewTxManager(db)
settings := NewLoyaltySettingsProcessor(repository.NewLoyaltySettingsRepository(db), txm)
wallet := NewWalletProcessor(repository.NewWalletRepository(db))
e.payments = NewPointPaymentProcessor(repository.NewPointPaymentRepository(db), settings, repository.NewWalletQueryRepository(db), wallet, txm)
mr := miniredis.RunT(t)
client := redis.NewClient(&redis.Options{Addr: mr.Addr()})
t.Cleanup(func() { client.Close() })
e.codes = NewPaymentCodeProcessor(repository.NewPaymentCodeRepository(client), pinVerifierFake{good: "482913"})
e.orders = &OrderProcessorImpl{
orderRepo: repository.NewOrderRepositoryImpl(db),
orderItemRepo: repository.NewOrderItemRepositoryImpl(db),
paymentRepo: repository.NewPaymentRepositoryImpl(db),
paymentMethodRepo: repository.NewPaymentMethodRepositoryImpl(db),
splitBillProcessor: nil,
txManager: txm,
}
e.orders.SetLoyalty(NewEarningProcessor(repository.NewEarningRepository(db), settings, wallet, txm))
e.orders.SetPointPayments(e.payments, e.codes, pinVerifierFake{good: "482913"})
// The outlet earns 1 EnakPoint per Rp 100 and accepts EnakPoint.
s, err := settings.Outlet(context.Background(), e.outlet)
require.NoError(t, err)
s.Point.Enabled = true
s.PointPayment.AcceptPayment = true
_, err = settings.UpdateOutlet(context.Background(), e.org, e.outlet, e.cashier, *s)
require.NoError(t, err)
e.ctx = context.WithValue(context.Background(), appcontext.UserIDKey, e.cashier.String())
return e
}
func (e *pointPaymentEnv) exec(q string, args ...any) {
e.t.Helper()
require.NoError(e.t, e.db.Exec(q, args...).Error)
}
// customerWith creates a customer holding the given EnakPoint.
func (e *pointPaymentEnv) customerWith(points int64) uuid.UUID {
e.t.Helper()
id := uuid.New()
e.exec(`INSERT INTO customers (id, organization_id, name) VALUES (?, ?, 'c')`, id, e.org)
if points > 0 {
require.NoError(e.t, repository.NewTxManager(e.db).WithTransaction(context.Background(), func(ctx context.Context) error {
_, err := NewWalletProcessor(repository.NewWalletRepository(e.db)).Credit(ctx, WalletCreditInput{WalletEntry: WalletEntry{
CustomerID: id, Currency: constants.WalletCurrencyPoint, Type: constants.WalletTxTypeMigration, Amount: points,
ReferenceType: constants.WalletRefTypeLegacyPoints, ReferenceID: uuid.New(), Description: "Saldo awal"}})
return err
}))
}
return id
}
func (e *pointPaymentEnv) order(customer uuid.UUID, subtotal float64) uuid.UUID {
e.t.Helper()
id := uuid.New()
e.exec(`INSERT INTO orders (id, organization_id, outlet_id, user_id, customer_id, order_number, order_type,
subtotal, tax_amount, total_amount, remaining_amount, payment_status)
VALUES (?, ?, ?, ?, ?, ?, 'dine_in', ?, 0, ?, ?, 'pending')`,
id, e.org, e.outlet, e.cashier, customer, "PP-"+id.String()[:8], subtotal, subtotal, subtotal)
return id
}
func (e *pointPaymentEnv) code(customer uuid.UUID) string {
e.t.Helper()
c, err := e.codes.Issue(context.Background(), customer, "482913", models.CustomerPinRequestInfo{})
require.NoError(e.t, err)
return c.Code
}
func (e *pointPaymentEnv) payPoints(order uuid.UUID, points int64, code string) (*models.PaymentResponse, error) {
return e.orders.CreatePayment(e.ctx, &models.CreatePaymentRequest{OrderID: order, PaymentMethodID: e.point, Points: &points, PaymentCode: &code})
}
func (e *pointPaymentEnv) balance(customer uuid.UUID) int64 {
e.t.Helper()
var b int64
require.NoError(e.t, e.db.Raw(`SELECT COALESCE(SUM(point_balance), 0) FROM customer_wallets WHERE customer_id = ?`, customer).Scan(&b).Error)
return b
}
func (e *pointPaymentEnv) orderState(order uuid.UUID) (status string, remaining float64) {
e.t.Helper()
var row struct {
PaymentStatus string
RemainingAmount float64
}
require.NoError(e.t, e.db.Raw(`SELECT payment_status, remaining_amount FROM orders WHERE id = ?`, order).Scan(&row).Error)
return row.PaymentStatus, row.RemainingAmount
}
func TestPointPayment_FullPayment(t *testing.T) {
e := newPointPaymentEnv(t)
customer := e.customerWith(100000)
order := e.order(customer, 50000)
payment, err := e.payPoints(order, 50000, e.code(customer))
require.NoError(t, err)
assert.Equal(t, 50000.0, payment.Amount)
require.NotNil(t, payment.PointsUsed)
assert.Equal(t, int64(50000), *payment.PointsUsed)
assert.Equal(t, 1.0, *payment.PointValue, "the value is frozen on the payment")
status, remaining := e.orderState(order)
assert.Equal(t, "completed", status)
assert.Zero(t, remaining)
assert.Equal(t, int64(50000), e.balance(customer))
var ledger struct {
Amount int64
ReferenceType string
ReferenceID string
OutletID string
CreatedByUser string
}
require.NoError(t, e.db.Raw(`SELECT amount, reference_type, reference_id::text AS reference_id, outlet_id::text AS outlet_id,
created_by_user::text AS created_by_user FROM wallet_transactions WHERE customer_id = ? AND type = 'PAYMENT'`, customer).Scan(&ledger).Error)
assert.Equal(t, int64(-50000), ledger.Amount)
assert.Equal(t, "PAYMENT", ledger.ReferenceType)
assert.Equal(t, payment.ID.String(), ledger.ReferenceID)
assert.Equal(t, e.outlet.String(), ledger.OutletID)
assert.Equal(t, e.cashier.String(), ledger.CreatedByUser, "the cashier who took it")
// Paid entirely with EnakPoint, so nothing earns (Q10).
var earned int64
require.NoError(t, e.db.Raw(`SELECT COUNT(*) FROM wallet_transactions WHERE reference_id = ? AND type = 'EARN'`, order).Scan(&earned).Error)
assert.Zero(t, earned)
}
func TestPointPayment_PartialThenCash(t *testing.T) {
e := newPointPaymentEnv(t)
customer := e.customerWith(100000)
order := e.order(customer, 87500)
_, err := e.payPoints(order, 20000, e.code(customer))
require.NoError(t, err)
status, remaining := e.orderState(order)
assert.Equal(t, "partial", status)
assert.Equal(t, 67500.0, remaining)
// The rest in cash settles it; earning counts only the part not paid with
// EnakPoint: floor(67.500 / 100) = 675.
_, err = e.orders.CreatePayment(e.ctx, &models.CreatePaymentRequest{OrderID: order, PaymentMethodID: e.cash, Amount: 67500})
require.NoError(t, err)
status, _ = e.orderState(order)
assert.Equal(t, "completed", status)
var earned int64
require.NoError(t, e.db.Raw(`SELECT COALESCE(SUM(amount), 0) FROM wallet_transactions WHERE reference_id = ? AND type = 'EARN'`, order).Scan(&earned).Error)
assert.Equal(t, int64(675), earned)
assert.Equal(t, int64(100000-20000+675), e.balance(customer))
}
func TestPointPayment_PercentCap(t *testing.T) {
e := newPointPaymentEnv(t)
settings := NewLoyaltySettingsProcessor(repository.NewLoyaltySettingsRepository(e.db), repository.NewTxManager(e.db))
s, err := settings.Outlet(context.Background(), e.outlet)
require.NoError(t, err)
s.PointPayment.MaxPaymentPercent = 50
_, err = settings.UpdateOutlet(context.Background(), e.org, e.outlet, e.cashier, *s)
require.NoError(t, err)
customer := e.customerWith(100000)
order := e.order(customer, 100000)
preview, err := e.payments.Preview(context.Background(), e.org, order)
require.NoError(t, err)
assert.True(t, preview.Eligible)
assert.Equal(t, int64(50000), preview.MaxPoints)
assert.Equal(t, int64(100000), preview.PointBalance)
_, err = e.payPoints(order, 50001, e.code(customer))
assert.ErrorIs(t, err, ErrPointPaymentRejected)
_, err = e.payPoints(order, 30000, e.code(customer))
require.NoError(t, err)
_, err = e.payPoints(order, 20001, e.code(customer))
assert.ErrorIs(t, err, ErrPointPaymentRejected, "earlier EnakPoint counts toward the cap")
_, err = e.payPoints(order, 20000, e.code(customer))
require.NoError(t, err)
assert.Equal(t, int64(50000), e.balance(customer))
}
func TestPointPayment_Refusals(t *testing.T) {
e := newPointPaymentEnv(t)
customer := e.customerWith(100000)
other := e.customerWith(100000)
// A walk-in order cannot be paid with EnakPoint.
walkInOrder := e.order(e.walkIn, 10000)
preview, err := e.payments.Preview(context.Background(), e.org, walkInOrder)
require.NoError(t, err)
assert.False(t, preview.Eligible)
assert.Contains(t, preview.Reason, "walk-in")
_, err = e.payPoints(walkInOrder, 1000, "123456")
assert.ErrorIs(t, err, ErrPointPaymentRejected)
order := e.order(customer, 10000)
_, err = e.payPoints(order, 1000, "000000")
assert.ErrorIs(t, err, ErrPointPaymentRejected, "a wrong code")
_, err = e.payPoints(order, 1000, e.code(other))
assert.ErrorIs(t, err, ErrPointPaymentRejected, "another customer's code")
missing := int64(1000)
_, err = e.orders.CreatePayment(e.ctx, &models.CreatePaymentRequest{OrderID: order, PaymentMethodID: e.point, Points: &missing})
assert.ErrorIs(t, err, ErrPointPaymentRejected, "no code at all")
code := e.code(customer)
_, err = e.payPoints(order, 1000, code)
require.NoError(t, err)
_, err = e.payPoints(order, 1000, code)
assert.ErrorIs(t, err, ErrPointPaymentRejected, "a code is used once, so a double tap takes once")
_, err = e.payPoints(order, 9001, e.code(customer))
assert.ErrorIs(t, err, ErrPointPaymentRejected, "no change is given: not more than what is left")
// Splitting with the EnakPoint method would skip the balance, so it is refused.
e.orders.splitBillProcessor = splitFake{}
_, err = e.orders.SplitBill(e.ctx, &models.SplitBillRequest{OrderID: order, PaymentMethodID: e.point, Type: "AMOUNT", Amount: 1000})
assert.ErrorIs(t, err, ErrPointPaymentRejected)
assert.Equal(t, int64(99000), e.balance(customer), "only the one payment took anything")
assert.Equal(t, int64(100000), e.balance(other))
}
// Two payments for the same customer at once, on two orders: the balance is taken
// once, never twice. Authorization is taken as given so only the balance decides.
func TestPointPayment_ConcurrentForOneCustomer(t *testing.T) {
e := newPointPaymentEnv(t)
customer := e.customerWith(30000)
orders := []uuid.UUID{e.order(customer, 20000), e.order(customer, 20000)}
var wg sync.WaitGroup
results := make([]error, len(orders))
for i, order := range orders {
wg.Add(1)
go func(i int, order uuid.UUID) {
defer wg.Done()
_, results[i] = e.payments.Pay(e.ctx, PointPaymentInput{
OrderID: order, PaymentMethodID: e.point, Points: 20000,
Authorize: func(context.Context, uuid.UUID) error { return nil },
})
}(i, order)
}
wg.Wait()
succeeded := 0
for _, err := range results {
if err == nil {
succeeded++
} else {
assert.ErrorIs(t, err, ErrPointPaymentRejected)
}
}
assert.Equal(t, 1, succeeded, "30.000 EnakPoint pays one 20.000 order, not two")
assert.Equal(t, int64(10000), e.balance(customer))
// And the wallet still reconciles.
found, err := repository.NewWalletReconciliationRepository(e.db).FindDiscrepancies(context.Background(), 1000)
require.NoError(t, err)
for _, d := range found {
assert.NotEqual(t, customer, d.CustomerID, d.Check)
}
}
func TestPointPayment_InApp(t *testing.T) {
e := newPointPaymentEnv(t)
owner := e.customerWith(100000)
stranger := e.customerWith(100000)
order := e.order(owner, 60000)
info := models.CustomerPinRequestInfo{}
// Another customer cannot pay it, and is not told it exists.
_, err := e.orders.PayWithPointsInApp(e.ctx, stranger, order, 1000, "482913", info)
assert.ErrorIs(t, err, repository.ErrPointPaymentOrderNotFound)
_, err = e.orders.PayWithPointsInApp(e.ctx, owner, uuid.New(), 1000, "482913", info)
assert.ErrorIs(t, err, repository.ErrPointPaymentOrderNotFound)
// The session alone is not enough: a wrong PIN takes nothing.
_, err = e.orders.PayWithPointsInApp(e.ctx, owner, order, 1000, "000000", info)
var pe *PinError
require.ErrorAs(t, err, &pe)
assert.Equal(t, PinErrInvalid, pe.Code)
assert.Equal(t, int64(100000), e.balance(owner))
// The owner pays part, then the rest, with the same rules as at the cashier.
payment, err := e.orders.PayWithPointsInApp(e.ctx, owner, order, 10000, "482913", info)
require.NoError(t, err)
assert.Equal(t, int64(10000), *payment.PointsUsed)
status, remaining := e.orderState(order)
assert.Equal(t, "partial", status)
assert.Equal(t, 50000.0, remaining)
_, err = e.orders.PayWithPointsInApp(e.ctx, owner, order, 50001, "482913", info)
assert.ErrorIs(t, err, ErrPointPaymentRejected, "not more than what is left")
_, err = e.orders.PayWithPointsInApp(e.ctx, owner, order, 50000, "482913", info)
require.NoError(t, err)
status, _ = e.orderState(order)
assert.Equal(t, "completed", status)
assert.Equal(t, int64(40000), e.balance(owner))
assert.Equal(t, int64(100000), e.balance(stranger))
var createdBy *string
require.NoError(t, e.db.Raw(`SELECT created_by_user::text FROM wallet_transactions WHERE customer_id = ? AND type = 'PAYMENT' LIMIT 1`, owner).Scan(&createdBy).Error)
assert.Nil(t, createdBy, "no cashier took an in-app payment")
}
// The payment method report counts only money actually received as money in; the
// EnakPoint part is listed apart (F9).
func TestPointPayment_ReportKeepsEnakPointOutOfCashIn(t *testing.T) {
e := newPointPaymentEnv(t)
customer := e.customerWith(100000)
order := e.order(customer, 87500)
_, err := e.payPoints(order, 20000, e.code(customer))
require.NoError(t, err)
_, err = e.orders.CreatePayment(e.ctx, &models.CreatePaymentRequest{OrderID: order, PaymentMethodID: e.cash, Amount: 67500})
require.NoError(t, err)
report, err := NewAnalyticsProcessorImpl(repository.NewAnalyticsRepositoryImpl(e.db), nil).GetPaymentMethodAnalytics(context.Background(),
&models.PaymentMethodAnalyticsRequest{OrganizationID: e.org, DateFrom: time.Now().Add(-time.Hour), DateTo: time.Now().Add(time.Hour)})
require.NoError(t, err)
assert.Equal(t, 67500.0, report.Summary.TotalAmount, "money in is the cash, not the order total")
assert.Equal(t, 20000.0, report.Summary.PointAmount)
assert.Equal(t, int64(20000), report.Summary.PointsUsed)
assert.Equal(t, 87500.0, report.Summary.TotalWithPoints)
require.Len(t, report.Data, 2)
for _, d := range report.Data {
assert.Equal(t, d.PaymentMethodType != "point", d.CountsAsCashIn, d.PaymentMethodName)
}
}
@@ -0,0 +1,118 @@
package processor
import (
"context"
"os"
"testing"
"github.com/google/uuid"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"gorm.io/driver/postgres"
"gorm.io/gorm"
"gorm.io/gorm/logger"
"apskel-pos-be/internal/constants"
"apskel-pos-be/internal/models"
"apskel-pos-be/internal/repository"
)
// Needs TEST_DATABASE_URL pointing at a migrated database; see
// internal/repository/wallet_repository_test.go.
func TestPointPaymentMethod_AgainstPostgres(t *testing.T) {
dsn := os.Getenv("TEST_DATABASE_URL")
if dsn == "" {
t.Skip("TEST_DATABASE_URL not set")
}
db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{Logger: logger.Default.LogMode(logger.Silent)})
require.NoError(t, err)
ctx := context.Background()
org, user, accepting, refusing := uuid.New(), uuid.New(), uuid.New(), uuid.New()
exec := func(q string, args ...any) error { return db.Exec(q, args...).Error }
require.NoError(t, exec(`INSERT INTO organizations (id, name, plan_type) VALUES (?, 'pm test', 'basic')`, org))
require.NoError(t, exec(`INSERT INTO outlets (id, organization_id, name) VALUES (?, ?, 'Terima'), (?, ?, 'Tolak')`, accepting, org, refusing, org))
t.Cleanup(func() {
db.Exec(`DELETE FROM loyalty_setting_changes WHERE organization_id = ?`, org)
db.Exec(`DELETE FROM outlet_settings WHERE outlet_id IN ?`, []uuid.UUID{accepting, refusing})
db.Exec(`DELETE FROM outlets WHERE id IN ?`, []uuid.UUID{accepting, refusing})
db.Exec(`DELETE FROM payment_methods WHERE organization_id = ?`, org)
db.Exec(`DELETE FROM organizations WHERE id = ?`, org)
})
// A new organization gets exactly one EnakPoint method from the trigger.
var methods []struct {
ID string
Name string
Type string
}
require.NoError(t, db.Raw(`SELECT id::text AS id, name, type FROM payment_methods WHERE organization_id = ?`, org).Scan(&methods).Error)
require.Len(t, methods, 1)
assert.Equal(t, "EnakPoint", methods[0].Name)
assert.Equal(t, "point", methods[0].Type)
pointID := uuid.MustParse(methods[0].ID)
// The database refuses a second one.
assert.Error(t, exec(`INSERT INTO payment_methods (organization_id, name, type) VALUES (?, 'EnakPoint 2', 'point')`, org))
txm := repository.NewTxManager(db)
settings := NewLoyaltySettingsProcessor(repository.NewLoyaltySettingsRepository(db), txm)
s, err := settings.Outlet(ctx, accepting)
require.NoError(t, err)
s.PointPayment.AcceptPayment = true
_, err = settings.UpdateOutlet(ctx, org, accepting, user, *s)
require.NoError(t, err)
p := NewPaymentMethodProcessorImpl(repository.NewPaymentMethodRepositoryImpl(db), settings)
cash, err := p.CreatePaymentMethod(ctx, &models.CreatePaymentMethodRequest{OrganizationID: org, Name: "Tunai", Type: constants.PaymentMethodTypeCash, IsActive: ptr(true)})
require.NoError(t, err)
// The API cannot make, retype or delete an EnakPoint method.
_, err = p.CreatePaymentMethod(ctx, &models.CreatePaymentMethodRequest{OrganizationID: org, Name: "Poin Lain", Type: constants.PaymentMethodTypePoint, IsActive: ptr(true)})
assert.ErrorIs(t, err, ErrSystemPaymentMethod)
toCash := constants.PaymentMethodTypeCash
_, err = p.UpdatePaymentMethod(ctx, pointID, &models.UpdatePaymentMethodRequest{Type: &toCash})
assert.ErrorIs(t, err, ErrSystemPaymentMethod)
toPoint := constants.PaymentMethodTypePoint
_, err = p.UpdatePaymentMethod(ctx, cash.ID, &models.UpdatePaymentMethodRequest{Type: &toPoint})
assert.ErrorIs(t, err, ErrSystemPaymentMethod)
assert.ErrorIs(t, p.DeletePaymentMethod(ctx, pointID), ErrSystemPaymentMethod)
// Renaming it is fine; its type stays.
name := "Bayar pakai EnakPoint"
renamed, err := p.UpdatePaymentMethod(ctx, pointID, &models.UpdatePaymentMethodRequest{Name: &name, Type: &toPoint})
require.NoError(t, err)
assert.Equal(t, name, renamed.Name)
// At the cashier it shows only where the outlet accepts EnakPoint.
types := func(outlet *uuid.UUID) []constants.PaymentMethodType {
t.Helper()
list, err := p.ListPaymentMethods(ctx, &models.ListPaymentMethodsRequest{OrganizationID: &org, OutletID: outlet, Page: 1, Limit: 50})
require.NoError(t, err)
var out []constants.PaymentMethodType
for _, m := range list.PaymentMethods {
out = append(out, m.Type)
}
assert.Equal(t, len(out), list.TotalCount, "the count matches what is listed")
return out
}
assert.ElementsMatch(t, []constants.PaymentMethodType{"cash", "point"}, types(&accepting))
assert.ElementsMatch(t, []constants.PaymentMethodType{"cash"}, types(&refusing))
assert.ElementsMatch(t, []constants.PaymentMethodType{"cash", "point"}, types(nil), "the dashboard, without an outlet, sees it")
// A payment either records both points_used and point_value, or neither.
var orderID uuid.UUID
require.NoError(t, exec(`INSERT INTO users (id, organization_id, name, email, password_hash, role) VALUES (?, ?, 'K', ?, 'x', 'cashier')`, user, org, user.String()+"@t"))
orderID = uuid.New()
require.NoError(t, exec(`INSERT INTO orders (id, organization_id, outlet_id, user_id, order_number, order_type, subtotal, tax_amount, total_amount)
VALUES (?, ?, ?, ?, ?, 'dine_in', 1000, 0, 1000)`, orderID, org, accepting, user, "PM-"+orderID.String()[:8]))
t.Cleanup(func() {
db.Exec(`DELETE FROM payments WHERE order_id = ?`, orderID)
db.Exec(`DELETE FROM orders WHERE id = ?`, orderID)
db.Exec(`DELETE FROM users WHERE id = ?`, user)
})
assert.Error(t, exec(`INSERT INTO payments (order_id, payment_method_id, amount, points_used) VALUES (?, ?, 1000, 1000)`, orderID, pointID))
assert.Error(t, exec(`INSERT INTO payments (order_id, payment_method_id, amount, points_used, point_value) VALUES (?, ?, 1000, 0, 1)`, orderID, pointID))
assert.NoError(t, exec(`INSERT INTO payments (order_id, payment_method_id, amount, points_used, point_value) VALUES (?, ?, 1000, 1000, 1)`, orderID, pointID))
assert.NoError(t, exec(`INSERT INTO payments (order_id, payment_method_id, amount) VALUES (?, ?, 1000)`, orderID, cash.ID))
}
@@ -0,0 +1,336 @@
package processor
import (
"context"
"errors"
"fmt"
"time"
"github.com/google/uuid"
"apskel-pos-be/internal/constants"
"apskel-pos-be/internal/entities"
"apskel-pos-be/internal/models"
"apskel-pos-be/internal/repository"
)
// ErrPointPaymentRejected wraps every reason a payment with EnakPoint is refused: the
// order, the customer, the outlet or the amount. The message says which.
var ErrPointPaymentRejected = errors.New("EnakPoint payment refused")
type pointPaymentSettings interface {
Outlet(ctx context.Context, outletID uuid.UUID) (*models.OutletLoyaltySettings, error)
PointValue(ctx context.Context, organizationID uuid.UUID) (int64, error)
}
type spendableReader interface {
SpendableBalances(ctx context.Context, customerID uuid.UUID, asOf time.Time) (map[string]int64, error)
}
// PointPaymentInput is one payment of an order with EnakPoint.
type PointPaymentInput struct {
OrderID uuid.UUID
PaymentMethodID uuid.UUID
Points int64
// The cashier taking the payment at the POS; nil when the customer pays in the app.
CashierID *uuid.UUID
// Authorize proves the customer agreed, before anything is taken: at the POS it
// redeems the payment code, in the app it checks the PIN (K8).
Authorize func(ctx context.Context, customerID uuid.UUID) error
}
// PointPaymentResult is the payment made and where it left the order.
type PointPaymentResult struct {
Payment *entities.Payment
// True when this payment settled the order.
Completed bool
// Rupiah still to pay with another method.
Remaining float64
}
// pointPaymentLimits applies the formula of docs/prd-point-coin.md F9, in cents:
//
// cap = min(remaining, total × max_payment_percent / 100 − already paid with EnakPoint)
// max_points = min(balance, floor(cap / point_value))
type pointPaymentLimits struct {
RemainingCents int64
CapCents int64
MaxPoints int64
}
func computePointPaymentLimits(total, totalPaid, paidWithPoints float64, maxPercent, pointValue, balance int64) pointPaymentLimits {
remaining := toCents(total) - toCents(totalPaid)
if remaining < 0 {
remaining = 0
}
byPercent := toCents(total)*maxPercent/100 - toCents(paidWithPoints)
capCents := min(remaining, byPercent)
if capCents < 0 {
capCents = 0
}
maxPoints := int64(0)
if pointValue > 0 {
maxPoints = min(balance, capCents/(pointValue*100))
}
if maxPoints < 0 {
maxPoints = 0
}
return pointPaymentLimits{RemainingCents: remaining, CapCents: capCents, MaxPoints: maxPoints}
}
// PointPaymentProcessor pays orders with EnakPoint (docs/prd-point-coin.md F9).
type PointPaymentProcessor struct {
repo repository.PointPaymentRepository
settings pointPaymentSettings
spendable spendableReader
wallet *WalletProcessor
tx TxRunner
now func() time.Time
}
func NewPointPaymentProcessor(repo repository.PointPaymentRepository, settings pointPaymentSettings, spendable spendableReader, wallet *WalletProcessor, tx TxRunner) *PointPaymentProcessor {
return &PointPaymentProcessor{repo: repo, settings: settings, spendable: spendable, wallet: wallet, tx: tx, now: time.Now}
}
// Preview is GET /orders/:id/point-payment/preview: whether the order can be paid with
// EnakPoint, and at most how much.
func (p *PointPaymentProcessor) Preview(ctx context.Context, organizationID, orderID uuid.UUID) (*models.PointPaymentPreview, error) {
order, err := p.repo.GetOrder(ctx, orderID, false)
if err != nil {
return nil, err
}
if order.OrganizationID != organizationID {
return nil, repository.ErrPointPaymentOrderNotFound
}
preview := &models.PointPaymentPreview{OrderID: orderID, CustomerID: order.CustomerID}
settings, err := p.settings.Outlet(ctx, order.OutletID)
if err != nil {
return nil, err
}
value, err := p.settings.PointValue(ctx, order.OrganizationID)
if err != nil {
return nil, err
}
preview.PointValue = value
preview.MinPaymentPoints = settings.PointPayment.MinPaymentPoints
preview.MaxPaymentPercent = settings.PointPayment.MaxPaymentPercent
if reason := pointPaymentOrderProblem(order, settings); reason != "" {
preview.Reason = reason
return preview, nil
}
limits, balance, err := p.limits(ctx, order, settings, value)
if err != nil {
return nil, err
}
preview.PointBalance = balance
preview.RemainingAmount = float64(limits.RemainingCents) / 100
preview.MaxPoints = limits.MaxPoints
preview.MaxAmount = limits.MaxPoints * value
if limits.MaxPoints < settings.PointPayment.MinPaymentPoints {
preview.Reason = "the customer cannot pay the minimum of EnakPoint on this order"
return preview, nil
}
preview.Eligible = true
return preview, nil
}
// Pay takes EnakPoint from the order's customer and records the payment. The payment
// row, the ledger PAYMENT row, the balance and the order change in one transaction
// with the order row and the wallet locked (F9 steps 1–6).
func (p *PointPaymentProcessor) Pay(ctx context.Context, in PointPaymentInput) (*PointPaymentResult, error) {
reject := func(format string, args ...any) error {
return fmt.Errorf("%w: %s", ErrPointPaymentRejected, fmt.Sprintf(format, args...))
}
if in.Points <= 0 {
return nil, reject("the number of EnakPoint must be positive")
}
order, err := p.repo.GetOrder(ctx, in.OrderID, false)
if err != nil {
return nil, err
}
methodOrg, methodType, err := p.repo.GetPaymentMethod(ctx, in.PaymentMethodID)
if err != nil {
return nil, err
}
if methodType != string(constants.PaymentMethodTypePoint) || methodOrg != order.OrganizationID {
return nil, reject("the payment method is not this organization's EnakPoint method")
}
settings, err := p.settings.Outlet(ctx, order.OutletID)
if err != nil {
return nil, err
}
if reason := pointPaymentOrderProblem(order, settings); reason != "" {
return nil, reject("%s", reason)
}
if in.Points < settings.PointPayment.MinPaymentPoints {
return nil, reject("at least %d EnakPoint must be used", settings.PointPayment.MinPaymentPoints)
}
customerID := *order.CustomerID
// The customer agrees before anything is taken. A code is used up here even if the
// payment then fails, and the customer shows a new one.
if in.Authorize == nil {
return nil, reject("the customer has not approved the payment")
}
if err := in.Authorize(ctx, customerID); err != nil {
return nil, err
}
result := &PointPaymentResult{}
err = p.tx.WithTransaction(ctx, func(ctx context.Context) error {
// Lock the order, then the wallet, and read everything again: another payment
// may have landed since the checks above.
order, err := p.repo.GetOrder(ctx, in.OrderID, true)
if err != nil {
return err
}
if reason := pointPaymentOrderProblem(order, settings); reason != "" {
return reject("%s", reason)
}
if err := p.wallet.LockWallet(ctx, customerID); err != nil {
return err
}
value, err := p.settings.PointValue(ctx, order.OrganizationID)
if err != nil {
return err
}
limits, _, err := p.limits(ctx, order, settings, value)
if err != nil {
return err
}
if in.Points > limits.MaxPoints {
return reject("at most %d EnakPoint can pay this order now", limits.MaxPoints)
}
amountCents := in.Points * value * 100
// No change is ever given for EnakPoint (K7); the limits already keep it
// within what is left, this only guards that.
if amountCents > limits.RemainingCents {
return reject("EnakPoint cannot pay more than what is left on the order")
}
pointsUsed := in.Points
frozenValue := float64(value)
payment := &entities.Payment{
ID: uuid.New(),
OrderID: order.ID,
PaymentMethodID: in.PaymentMethodID,
Amount: float64(amountCents) / 100,
Status: entities.PaymentTransactionStatusCompleted,
PointsUsed: &pointsUsed,
PointValue: &frozenValue,
Metadata: entities.Metadata{"points_used": pointsUsed, "point_value": value},
}
if err := p.repo.InsertPayment(ctx, payment); err != nil {
return err
}
outletID := order.OutletID
if _, err := p.wallet.Debit(ctx, WalletDebitInput{WalletEntry: WalletEntry{
CustomerID: customerID,
Currency: constants.WalletCurrencyPoint,
Type: constants.WalletTxTypePayment,
Amount: in.Points,
ReferenceType: constants.WalletRefTypePayment,
ReferenceID: payment.ID,
OutletID: &outletID,
CreatedByUser: in.CashierID,
Description: pointPaymentDescription(order, amountCents),
Metadata: entities.Metadata{"point_value": value, "amount": payment.Amount},
IdempotencyKey: "payment:" + payment.ID.String(),
}}); err != nil {
if errors.Is(err, repository.ErrWalletInsufficientBalance) {
return reject("the customer does not have enough EnakPoint")
}
return err
}
remainingCents := limits.RemainingCents - amountCents
completed := remainingCents == 0
if err := p.repo.UpdateOrderAfterPayment(ctx, order.ID, float64(remainingCents)/100, completed); err != nil {
return err
}
result.Payment = payment
result.Completed = completed
result.Remaining = float64(remainingCents) / 100
return nil
})
if err != nil {
return nil, err
}
return result, nil
}
func (p *PointPaymentProcessor) limits(ctx context.Context, order *repository.PointPaymentOrder, settings *models.OutletLoyaltySettings, value int64) (pointPaymentLimits, int64, error) {
totalPaid, err := p.repo.TotalPaid(ctx, order.ID)
if err != nil {
return pointPaymentLimits{}, 0, err
}
paidWithPoints, err := p.repo.PaidWithPoints(ctx, order.ID)
if err != nil {
return pointPaymentLimits{}, 0, err
}
balances, err := p.spendable.SpendableBalances(ctx, *order.CustomerID, p.now())
if err != nil {
return pointPaymentLimits{}, 0, err
}
balance := balances[constants.WalletCurrencyPoint]
return computePointPaymentLimits(order.TotalAmount, totalPaid, paidWithPoints, settings.PointPayment.MaxPaymentPercent, value, balance), balance, nil
}
// pointPaymentOrderProblem says why an order cannot be paid with EnakPoint at all, or
// "" when it can.
func pointPaymentOrderProblem(order *repository.PointPaymentOrder, settings *models.OutletLoyaltySettings) string {
switch {
case order.IsVoid:
return "the order is void"
case order.PaymentStatus == string(entities.PaymentStatusCompleted):
return "the order is already paid"
case !settings.PointPayment.AcceptPayment:
return "this outlet does not accept EnakPoint"
case order.CustomerID == nil || order.CustomerIsDefault == nil:
return "the order has no customer"
case *order.CustomerIsDefault:
return "a walk-in order cannot be paid with EnakPoint"
case order.CustomerIsActive == nil || !*order.CustomerIsActive:
return "the customer is not active"
}
return ""
}
func pointPaymentDescription(order *repository.PointPaymentOrder, amountCents int64) string {
description := "Bayar #" + order.OrderNumber
if order.OutletName != "" {
description += " di " + order.OutletName
}
description += " (Rp " + formatRupiah(amountCents/100) + ")"
return truncateRunes(description, walletDescriptionLimit)
}
// formatRupiah writes 50000 as 50.000.
func formatRupiah(n int64) string {
s := fmt.Sprintf("%d", n)
out := make([]byte, 0, len(s)+len(s)/3)
for i, c := range []byte(s) {
if i > 0 && (len(s)-i)%3 == 0 {
out = append(out, '.')
}
out = append(out, c)
}
return string(out)
}
// PointMethodID returns the organization's EnakPoint payment method.
func (p *PointPaymentProcessor) PointMethodID(ctx context.Context, organizationID uuid.UUID) (uuid.UUID, error) {
return p.repo.PointMethodID(ctx, organizationID)
}
// OrderOwner returns the organization and customer of an order, for checking that a
// customer pays only their own order.
func (p *PointPaymentProcessor) OrderOwner(ctx context.Context, orderID uuid.UUID) (organizationID uuid.UUID, customerID *uuid.UUID, err error) {
order, err := p.repo.GetOrder(ctx, orderID, false)
if err != nil {
return uuid.Nil, nil, err
}
return order.OrganizationID, order.CustomerID, nil
}
@@ -0,0 +1,39 @@
package processor
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestComputePointPaymentLimits(t *testing.T) {
for name, c := range map[string]struct {
total, paid, paidWithPoints float64
percent, value, balance int64
wantRemaining, wantMax int64
}{
// The F9 example: Rp 87.550 left, 50.000 EnakPoint, 100%, Rp 1 a point.
"PRD example": {87550, 0, 0, 100, 1, 50000, 8755000, 50000},
"balance covers it all": {87550, 0, 0, 100, 1, 100000, 8755000, 87550},
"part already paid": {100000, 30000, 0, 100, 1, 100000, 7000000, 70000},
"capped by percent": {100000, 0, 0, 50, 1, 100000, 10000000, 50000},
"percent counts EnakPoint already used": {100000, 20000, 20000, 50, 1, 100000, 8000000, 30000},
"percent cap already used": {100000, 50000, 50000, 50, 1, 100000, 5000000, 0},
"point worth more than Rp 1": {87550, 0, 0, 100, 100, 1000, 8755000, 875},
"nothing left": {50000, 50000, 0, 100, 1, 100000, 0, 0},
"overpaid": {50000, 60000, 0, 100, 1, 100000, 0, 0},
"no balance": {50000, 0, 0, 100, 1, 0, 5000000, 0},
"cents left over": {10000.50, 0, 0, 100, 1, 100000, 1000050, 10000},
} {
got := computePointPaymentLimits(c.total, c.paid, c.paidWithPoints, c.percent, c.value, c.balance)
assert.Equal(t, c.wantRemaining, got.RemainingCents, name)
assert.Equal(t, c.wantMax, got.MaxPoints, name)
assert.LessOrEqual(t, got.MaxPoints*c.value*100, got.RemainingCents, "%s: never more than what is left", name)
}
}
func TestFormatRupiah(t *testing.T) {
for n, want := range map[int64]string{0: "0", 999: "999", 1000: "1.000", 50000: "50.000", 1234567: "1.234.567"} {
assert.Equal(t, want, formatRupiah(n))
}
}
+157
View File
@@ -0,0 +1,157 @@
package processor
import (
"context"
"fmt"
"github.com/google/uuid"
"apskel-pos-be/internal/constants"
"apskel-pos-be/internal/entities"
"apskel-pos-be/internal/repository"
)
// RefundForOrder gives EnakPoint back for the order's EnakPoint payments, as far as the
// order has been voided or those payments refunded (docs/prd-point-coin.md F9, K7):
//
// - void: every EnakPoint used on the order;
// - a refunded EnakPoint payment: floor(refunded rupiah / the frozen point value),
// so a later change of the point value does not change how many come back, and a
// rupiah remainder below one EnakPoint is lost (Q13).
//
// Never more than the payment used, and only what has not come back yet, so it can be
// called again safely. Returned EnakPoint go back into lots with the expiry of the lots
// they were taken from, but at least seven days from the refund (note N4, decided). It
// returns how many came back in total.
func (p *PointPaymentProcessor) RefundForOrder(ctx context.Context, orderID uuid.UUID) (int64, error) {
order, err := p.repo.GetOrder(ctx, orderID, false)
if err != nil {
return 0, err
}
payments, err := p.repo.ListPointPayments(ctx, orderID)
if err != nil {
return 0, err
}
var returned int64
for _, payment := range payments {
if payment.LedgerID == nil || payment.CustomerID == nil {
continue
}
target := pointRefundTarget(order.IsVoid, payment)
if target == 0 {
continue
}
var n int64
err := p.tx.WithTransaction(ctx, func(ctx context.Context) error {
if err := p.wallet.LockWallet(ctx, *payment.CustomerID); err != nil {
return err
}
allocations, err := p.repo.PaymentAllocations(ctx, *payment.LedgerID)
if err != nil {
return err
}
refunded, err := p.repo.RefundedByOriginLot(ctx, *payment.LedgerID)
if err != nil {
return err
}
var already int64
for _, amount := range refunded {
already += amount
}
toReturn := target - already
if toReturn <= 0 {
return nil
}
// Fill the lots the payment took from, each up to what it gave.
var lots []WalletLotInput
left := toReturn
for _, a := range allocations {
if left == 0 {
break
}
room := a.Amount - refunded[a.LotID]
if room <= 0 {
continue
}
take := min(room, left)
left -= take
lotID := a.LotID
lots = append(lots, WalletLotInput{Amount: take, ExpiresAt: RefundExpiry(a.ExpiresAt, p.now()), OriginLotID: &lotID})
}
toReturn -= left
ledgerID := *payment.LedgerID
if _, err := p.wallet.Credit(ctx, WalletCreditInput{
WalletEntry: WalletEntry{
CustomerID: *payment.CustomerID,
Currency: constants.WalletCurrencyPoint,
Type: constants.WalletTxTypePaymentRefund,
Amount: toReturn,
ReferenceType: constants.WalletRefTypePayment,
ReferenceID: payment.PaymentID,
ReversesTransactionID: &ledgerID,
OutletID: payment.OutletID,
Description: pointRefundDescription(order),
Metadata: entities.Metadata{"point_value": payment.PointValue, "target": target, "void": order.IsVoid},
IdempotencyKey: fmt.Sprintf("payment-refund:%s:%d", payment.PaymentID, target),
},
Lots: lots,
}); err != nil {
return err
}
n = toReturn
return nil
})
if err != nil {
return returned, fmt.Errorf("refunding EnakPoint payment %s: %w", payment.PaymentID, err)
}
returned += n
}
return returned, nil
}
// EnsureOrderRefundAllowed refuses an order-level refund that would hand back, in cash
// or another method, what was paid with EnakPoint (K7). The EnakPoint part is refunded
// through its own payment, and comes back as EnakPoint.
func (p *PointPaymentProcessor) EnsureOrderRefundAllowed(ctx context.Context, orderID uuid.UUID, amount float64) error {
refundable, err := p.repo.RefundableByOtherMethods(ctx, orderID)
if err != nil {
return err
}
paidWithPoints, err := p.repo.PaidWithPoints(ctx, orderID)
if err != nil {
return err
}
if paidWithPoints == 0 {
return nil
}
if toCents(amount) > toCents(refundable) {
return fmt.Errorf("%w: at most Rp %s can be refunded this way; the part paid with EnakPoint is refunded through its EnakPoint payment and returns as EnakPoint",
ErrPointPaymentRejected, formatRupiah(toCents(refundable)/100))
}
return nil
}
func pointRefundTarget(orderVoid bool, payment repository.PointPaymentRow) int64 {
if orderVoid {
return payment.PointsUsed
}
if payment.Status != string(entities.PaymentTransactionStatusRefunded) {
return 0
}
valueCents := toCents(payment.PointValue)
if valueCents <= 0 {
return 0
}
return min(payment.PointsUsed, toCents(payment.RefundAmount)/valueCents)
}
func pointRefundDescription(order *repository.PointPaymentOrder) string {
description := "Pengembalian #" + order.OrderNumber
if order.OutletName != "" {
description += " di " + order.OutletName
}
return truncateRunes(description, walletDescriptionLimit)
}
+151
View File
@@ -0,0 +1,151 @@
package processor
import (
"context"
"testing"
"time"
"github.com/google/uuid"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"apskel-pos-be/internal/constants"
"apskel-pos-be/internal/models"
"apskel-pos-be/internal/repository"
)
func (e *pointPaymentEnv) sum(query string, args ...any) int64 {
e.t.Helper()
var n int64
require.NoError(e.t, e.db.Raw(query, args...).Scan(&n).Error)
return n
}
func (e *pointPaymentEnv) returned(order uuid.UUID) int64 {
return e.sum(`SELECT COALESCE(SUM(t.amount), 0) FROM wallet_transactions t
JOIN payments p ON p.id = t.reference_id
WHERE p.order_id = ? AND t.type = 'PAYMENT_REFUND'`, order)
}
func (e *pointPaymentEnv) assertReconciled(customers ...uuid.UUID) {
e.t.Helper()
found, err := repository.NewWalletReconciliationRepository(e.db).FindDiscrepancies(context.Background(), 1000)
require.NoError(e.t, err)
for _, d := range found {
for _, c := range customers {
assert.NotEqual(e.t, c, d.CustomerID, d.Check)
}
}
}
func TestPointRefund_VoidReturnsEverythingToItsExpiry(t *testing.T) {
e := newPointPaymentEnv(t)
customer := e.customerWith(0)
expires := time.Now().Add(30 * 24 * time.Hour).Truncate(time.Second)
require.NoError(t, repository.NewTxManager(e.db).WithTransaction(context.Background(), func(ctx context.Context) error {
_, err := NewWalletProcessor(repository.NewWalletRepository(e.db)).Credit(ctx, WalletCreditInput{
WalletEntry: WalletEntry{CustomerID: customer, Currency: constants.WalletCurrencyPoint, Type: constants.WalletTxTypeMigration,
Amount: 40000, ReferenceType: constants.WalletRefTypeLegacyPoints, ReferenceID: uuid.New(), Description: "Saldo awal"},
Lots: []WalletLotInput{{Amount: 40000, ExpiresAt: &expires}},
})
return err
}))
// Part of the order paid with EnakPoint, then the order is voided.
order := e.order(customer, 50000)
_, err := e.payPoints(order, 30000, e.code(customer))
require.NoError(t, err)
assert.Equal(t, int64(10000), e.balance(customer))
require.NoError(t, e.orders.VoidOrder(e.ctx, &models.VoidOrderRequest{OrderID: order, Type: "ALL", Reason: "batal"}, e.cashier))
assert.Equal(t, int64(30000), e.returned(order))
assert.Equal(t, int64(40000), e.balance(customer))
var expiry time.Time
require.NoError(t, e.db.Raw(`SELECT l.expires_at FROM wallet_lots l JOIN wallet_transactions t ON t.id = l.source_transaction_id
WHERE t.customer_id = ? AND t.type = 'PAYMENT_REFUND'`, customer).Scan(&expiry).Error)
assert.WithinDuration(t, expires, expiry, time.Second, "returned EnakPoint keep the expiry they had")
// Calling it again returns nothing more.
e.orders.onOrderRefunded(e.ctx, order)
assert.Equal(t, int64(30000), e.returned(order))
e.assertReconciled(customer)
}
func TestPointRefund_PartialRefundFloors(t *testing.T) {
e := newPointPaymentEnv(t)
customer := e.customerWith(100000)
order := e.order(customer, 50000)
payment, err := e.payPoints(order, 50000, e.code(customer))
require.NoError(t, err)
// Rp 12.345,67 back at Rp 1 a point: 12.345 EnakPoint; the 67 sen are lost (Q13).
require.NoError(t, e.orders.RefundPayment(e.ctx, payment.ID, 12345.67, "sebagian", e.cashier))
assert.Equal(t, int64(12345), e.returned(order))
assert.Equal(t, int64(50000+12345), e.balance(customer))
e.assertReconciled(customer)
}
func TestPointRefund_UsesTheFrozenValue(t *testing.T) {
e := newPointPaymentEnv(t)
settings := NewLoyaltySettingsProcessor(repository.NewLoyaltySettingsRepository(e.db), repository.NewTxManager(e.db))
setValue := func(v int64) {
s, err := settings.Organization(context.Background(), e.org)
require.NoError(t, err)
s.PointValue = v
_, _, err = settings.UpdateOrganization(context.Background(), e.org, e.cashier, *s)
require.NoError(t, err)
}
setValue(100)
customer := e.customerWith(1000)
order := e.order(customer, 50000)
payment, err := e.payPoints(order, 500, e.code(customer))
require.NoError(t, err)
assert.Equal(t, 50000.0, payment.Amount, "500 × Rp 100")
// The value changes before the refund; the customer still gets back what they used.
setValue(250)
require.NoError(t, e.orders.RefundPayment(e.ctx, payment.ID, 50000, "semua", e.cashier))
assert.Equal(t, int64(500), e.returned(order), "50.000 / the frozen Rp 100, not the new Rp 250")
assert.Equal(t, int64(1000), e.balance(customer))
}
func TestPointRefund_NoCashForTheEnakPointPart(t *testing.T) {
e := newPointPaymentEnv(t)
customer := e.customerWith(100000)
order := e.order(customer, 50000)
_, err := e.payPoints(order, 20000, e.code(customer))
require.NoError(t, err)
_, err = e.orders.CreatePayment(e.ctx, &models.CreatePaymentRequest{OrderID: order, PaymentMethodID: e.cash, Amount: 30000})
require.NoError(t, err)
amount := 40000.0
err = e.orders.RefundOrder(e.ctx, order, &models.RefundOrderRequest{RefundAmount: &amount}, e.cashier)
assert.ErrorIs(t, err, ErrPointPaymentRejected, "Rp 40.000 in cash would include EnakPoint")
var refunded float64
require.NoError(t, e.db.Raw(`SELECT refund_amount FROM orders WHERE id = ?`, order).Scan(&refunded).Error)
assert.Zero(t, refunded, "nothing was written")
amount = 30000
require.NoError(t, e.orders.RefundOrder(e.ctx, order, &models.RefundOrderRequest{RefundAmount: &amount}, e.cashier), "the cash part can be refunded")
assert.Zero(t, e.returned(order), "and no EnakPoint came back for it")
}
// Giving back the EnakPoint part does not take earning back: that part never earned.
func TestPointRefund_DoesNotReverseEarning(t *testing.T) {
e := newPointPaymentEnv(t)
customer := e.customerWith(100000)
order := e.order(customer, 87500)
pointPayment, err := e.payPoints(order, 20000, e.code(customer))
require.NoError(t, err)
_, err = e.orders.CreatePayment(e.ctx, &models.CreatePaymentRequest{OrderID: order, PaymentMethodID: e.cash, Amount: 67500})
require.NoError(t, err)
earned := e.sum(`SELECT COALESCE(SUM(amount), 0) FROM wallet_transactions WHERE reference_id = ? AND type = 'EARN'`, order)
require.Equal(t, int64(675), earned)
require.NoError(t, e.orders.RefundPayment(e.ctx, pointPayment.ID, 20000, "kembali", e.cashier))
assert.Equal(t, int64(20000), e.returned(order))
reversed := e.sum(`SELECT COALESCE(SUM(-amount), 0) FROM wallet_transactions WHERE reference_id = ? AND type = 'EARN_REVERSAL'`, order)
assert.Zero(t, reversed, "the EnakPoint part never earned, so giving it back takes nothing")
e.assertReconciled(customer)
}
@@ -0,0 +1,223 @@
package processor
import (
"context"
"fmt"
"strings"
"time"
"unicode/utf8"
"github.com/google/uuid"
"apskel-pos-be/internal/constants"
"apskel-pos-be/internal/entities"
"apskel-pos-be/internal/models"
"apskel-pos-be/internal/repository"
)
// walletDescriptionLimit is the size of wallet_transactions.description.
const walletDescriptionLimit = 255
// WalletAdminProcessor serves the dashboard's view of one customer's wallet and the
// manual adjustments an admin makes to it (docs/prd-point-coin.md F7).
type WalletAdminProcessor struct {
admin repository.WalletAdminRepository
query repository.WalletQueryRepository
wallet *WalletProcessor
settings organizationSettingsReader
tx TxRunner
now func() time.Time
}
func NewWalletAdminProcessor(admin repository.WalletAdminRepository, query repository.WalletQueryRepository, wallet *WalletProcessor, settings organizationSettingsReader, tx TxRunner) *WalletAdminProcessor {
return &WalletAdminProcessor{admin: admin, query: query, wallet: wallet, settings: settings, tx: tx, now: time.Now}
}
// GetCustomerWallet returns the customer's balances, lots and a page of history.
// A customer outside the organization is reported as not found.
func (p *WalletAdminProcessor) GetCustomerWallet(ctx context.Context, organizationID, customerID uuid.UUID, query models.ListCustomerWalletTransactionsQuery) (*models.AdminCustomerWallet, error) {
filter, page, err := walletTransactionFilter(customerID, query)
if err != nil {
return nil, err
}
customer, err := p.admin.GetCustomer(ctx, organizationID, customerID)
if err != nil {
return nil, err
}
now := p.now()
result := &models.AdminCustomerWallet{
Customer: models.AdminWalletCustomer{ID: customer.ID, Name: customer.Name, Phone: customer.Phone},
Lots: []models.AdminWalletLot{},
}
wallet, err := p.admin.GetWallet(ctx, customerID)
if err != nil {
return nil, err
}
if wallet != nil {
result.PointBalance = wallet.PointBalance
result.CoinBalance = wallet.CoinBalance
}
spendable, err := p.query.SpendableBalances(ctx, customerID, now)
if err != nil {
return nil, err
}
result.SpendablePointBalance = spendable[constants.WalletCurrencyPoint]
result.SpendableCoinBalance = spendable[constants.WalletCurrencyCoin]
lots, err := p.admin.ListLotsWithBalance(ctx, customerID)
if err != nil {
return nil, err
}
for _, lot := range lots {
result.Lots = append(result.Lots, adminWalletLot(lot, now))
}
rows, total, err := p.query.ListTransactions(ctx, filter)
if err != nil {
return nil, err
}
transactions, err := p.adminTransactions(ctx, rows)
if err != nil {
return nil, err
}
result.Transactions = models.PaginatedResponse[models.AdminWalletTransaction]{
Data: transactions,
Pagination: models.Pagination{
Page: page,
Limit: filter.Limit,
Total: total,
TotalPages: int((total + int64(filter.Limit) - 1) / int64(filter.Limit)),
},
}
return result, nil
}
// Adjust adds to or takes from a customer's balance by hand. It is recorded as an
// ADJUSTMENT pointing at the admin, with the reason. Taking more than the customer
// can spend is refused with repository.ErrWalletInsufficientBalance.
func (p *WalletAdminProcessor) Adjust(ctx context.Context, organizationID, adminID, customerID uuid.UUID, in models.WalletAdjustment) (*models.AdminWalletAdjustmentResult, error) {
reason := strings.TrimSpace(in.Reason)
if adminID == uuid.Nil {
return nil, fmt.Errorf("%w: the admin making the adjustment is unknown", ErrWalletInvalidEntry)
}
if in.Amount == 0 {
return nil, fmt.Errorf("%w: amount must not be zero", ErrWalletInvalidEntry)
}
entry := WalletEntry{
CustomerID: customerID,
Currency: in.Currency,
Type: constants.WalletTxTypeAdjustment,
Amount: abs(in.Amount),
ReferenceType: constants.WalletRefTypeUser,
ReferenceID: adminID,
CreatedByUser: &adminID,
Reason: &reason,
Description: truncateRunes("Koreksi oleh admin: "+reason, walletDescriptionLimit),
}
if in.IdempotencyKey != "" {
// Scoped to the customer so a key chosen by the dashboard cannot collide with
// the keys other flows use.
entry.IdempotencyKey = fmt.Sprintf("adjust:%s:%s", customerID, in.IdempotencyKey)
}
var res *WalletResult
err := p.tx.WithTransaction(ctx, func(ctx context.Context) error {
if _, err := p.admin.GetCustomer(ctx, organizationID, customerID); err != nil {
return err
}
if in.Amount < 0 {
var err error
res, err = p.wallet.Debit(ctx, WalletDebitInput{WalletEntry: entry})
return err
}
// An adjustment that adds is a new balance, and expires like one (F7, F12).
settings, err := p.settings.Organization(ctx, organizationID)
if err != nil {
return err
}
res, err = p.wallet.Credit(ctx, WalletCreditInput{
WalletEntry: entry,
Lots: []WalletLotInput{{Amount: entry.Amount, ExpiresAt: ComputeExpiry(ExpirySettings(settings, in.Currency), p.now())}},
})
return err
})
if err != nil {
return nil, err
}
transactions, err := p.adminTransactions(ctx, []entities.WalletTransaction{*res.Transaction})
if err != nil {
return nil, err
}
spendable, err := p.query.SpendableBalances(ctx, customerID, p.now())
if err != nil {
return nil, err
}
return &models.AdminWalletAdjustmentResult{
Transaction: transactions[0],
SpendablePointBalance: spendable[constants.WalletCurrencyPoint],
SpendableCoinBalance: spendable[constants.WalletCurrencyCoin],
Replayed: res.Replayed,
}, nil
}
// adminTransactions adds, to what the customer sees, the names behind each row.
func (p *WalletAdminProcessor) adminTransactions(ctx context.Context, rows []entities.WalletTransaction) ([]models.AdminWalletTransaction, error) {
base, err := buildWalletTransactions(ctx, p.query, rows)
if err != nil {
return nil, err
}
var customerIDs, userIDs, outletIDs []uuid.UUID
for _, row := range rows {
if row.CounterpartyCustomerID != nil {
customerIDs = append(customerIDs, *row.CounterpartyCustomerID)
}
if row.CreatedByUser != nil {
userIDs = append(userIDs, *row.CreatedByUser)
}
if row.OutletID != nil {
outletIDs = append(outletIDs, *row.OutletID)
}
}
customers, err := p.admin.CustomerNames(ctx, customerIDs)
if err != nil {
return nil, err
}
users, err := p.admin.UserNames(ctx, userIDs)
if err != nil {
return nil, err
}
outlets, err := p.admin.OutletNames(ctx, outletIDs)
if err != nil {
return nil, err
}
named := func(id *uuid.UUID, names map[uuid.UUID]string) *models.AdminWalletNamedRef {
if id == nil {
return nil
}
return &models.AdminWalletNamedRef{ID: *id, Name: names[*id]}
}
out := make([]models.AdminWalletTransaction, 0, len(rows))
for i, row := range rows {
out = append(out, models.AdminWalletTransaction{
CustomerWalletTransaction: base[i],
Counterparty: named(row.CounterpartyCustomerID, customers),
CreatedBy: named(row.CreatedByUser, users),
Outlet: named(row.OutletID, outlets),
Reason: row.Reason,
Metadata: row.Metadata,
})
}
return out, nil
}
func truncateRunes(s string, limit int) string {
if utf8.RuneCountInString(s) <= limit {
return s
}
return string([]rune(s)[:limit])
}
@@ -0,0 +1,289 @@
package processor
import (
"context"
"errors"
"fmt"
"strings"
"time"
"github.com/google/uuid"
"apskel-pos-be/internal/constants"
"apskel-pos-be/internal/entities"
"apskel-pos-be/internal/models"
"apskel-pos-be/internal/repository"
)
// ErrWalletMoveRejected wraps every reason an exchange or a transfer is refused on
// the customer's side: the amount, the limits, the recipient or the balance. The
// message says which.
var ErrWalletMoveRejected = errors.New("wallet move refused")
// walletMoveKeyLimit keeps a client's Idempotency-Key short enough to fit, with the
// prefix that scopes it to the customer, in wallet_transactions.idempotency_key.
const walletMoveKeyLimit = 50
type organizationSettingsReader interface {
Organization(ctx context.Context, organizationID uuid.UUID) (*models.OrganizationLoyaltySettings, error)
}
// WalletExchangeProcessor exchanges EnakCoin into EnakPoint (docs/prd-point-coin.md
// F4, K3). It is one way only; nothing turns EnakPoint back into EnakCoin.
type WalletExchangeProcessor struct {
customers repository.WalletMoveRepository
settings organizationSettingsReader
spendable spendableReader
pins pinVerifier
wallet *WalletProcessor
tx TxRunner
now func() time.Time
}
func NewWalletExchangeProcessor(customers repository.WalletMoveRepository, settings organizationSettingsReader, spendable spendableReader, pins pinVerifier, wallet *WalletProcessor, tx TxRunner) *WalletExchangeProcessor {
return &WalletExchangeProcessor{customers: customers, settings: settings, spendable: spendable, pins: pins, wallet: wallet, tx: tx, now: time.Now}
}
// Preview is GET /customer/wallet/exchange/preview: the organization's rate and what
// exchanging coins would give, so the app can show it before asking for the PIN.
func (p *WalletExchangeProcessor) Preview(ctx context.Context, customerID uuid.UUID, coins int64) (*models.WalletExchangePreview, error) {
customer, err := p.customers.GetCustomer(ctx, customerID)
if err != nil {
return nil, err
}
settings, err := p.settings.Organization(ctx, customer.OrganizationID)
if err != nil {
return nil, err
}
balances, err := p.spendable.SpendableBalances(ctx, customerID, p.now())
if err != nil {
return nil, err
}
rate := settings.Exchange
preview := &models.WalletExchangePreview{
CoinAmount: rate.CoinAmount,
PointAmount: rate.PointAmount,
CoinBalance: balances[constants.WalletCurrencyCoin],
Coins: coins,
}
if reason := exchangeProblem(customer, rate, coins); reason != "" {
preview.Reason = reason
return preview, nil
}
preview.Points = exchangePoints(coins, rate)
if coins > preview.CoinBalance {
preview.Reason = "not enough EnakCoin"
return preview, nil
}
preview.Valid = true
return preview, nil
}
// Exchange takes coins EnakCoin and gives the EnakPoint they are worth at the
// organization's rate, in one transaction. The two ledger rows share a group and
// point at each other, and both freeze the rate. Each EnakPoint lot keeps the expiry
// of the EnakCoin lot it came from, so exchanging cannot extend a balance's life
// (K9). The PIN approves it (K8).
//
// idempotencyKey is the client's Idempotency-Key: a retry with the same key returns
// the first exchange, at the rate it was made, without moving anything again.
func (p *WalletExchangeProcessor) Exchange(ctx context.Context, customerID uuid.UUID, coins int64, pin, idempotencyKey string, info models.CustomerPinRequestInfo) (*models.WalletExchangeResult, error) {
key, err := walletMoveKey(idempotencyKey)
if err != nil {
return nil, err
}
customer, err := p.customers.GetCustomer(ctx, customerID)
if err != nil {
return nil, err
}
settings, err := p.settings.Organization(ctx, customer.OrganizationID)
if err != nil {
return nil, err
}
// Refuse a malformed request before the PIN is checked, so a typo in the amount
// costs the customer no PIN attempt.
if reason := exchangeProblem(customer, settings.Exchange, coins); reason != "" {
return nil, fmt.Errorf("%w: %s", ErrWalletMoveRejected, reason)
}
if err := p.pins.VerifyPin(ctx, customerID, pin, PinActionExchange, info); err != nil {
return nil, err
}
outKey := fmt.Sprintf("exchange:%s:%s:out", customerID, key)
inKey := fmt.Sprintf("exchange:%s:%s:in", customerID, key)
result := &models.WalletExchangeResult{Coins: coins}
err = p.tx.WithTransaction(ctx, func(ctx context.Context) error {
if err := p.wallet.LockWallet(ctx, customerID); err != nil {
return err
}
rate := settings.Exchange
groupID, outID, inID := uuid.New(), uuid.New(), uuid.New()
previous, err := p.wallet.FindTransaction(ctx, outKey)
if err != nil {
return err
}
if previous != nil && previous.GroupID != nil {
// A retry: repeat it with the ids and the rate the first attempt froze, so
// both rows replay even if the rate has changed since.
outID, inID, groupID = previous.ID, previous.ReferenceID, *previous.GroupID
rate = frozenExchangeRate(previous.Metadata, rate)
}
points := exchangePoints(coins, rate)
metadata := entities.Metadata{
"coins": coins,
"points": points,
"coin_amount": rate.CoinAmount,
"point_amount": rate.PointAmount,
}
out, err := p.wallet.Debit(ctx, WalletDebitInput{WalletEntry: WalletEntry{
TransactionID: outID,
CustomerID: customerID,
Currency: constants.WalletCurrencyCoin,
Type: constants.WalletTxTypeExchangeOut,
Amount: coins,
ReferenceType: constants.WalletRefTypeWalletTx,
ReferenceID: inID,
GroupID: &groupID,
Description: fmt.Sprintf("Tukar %d EnakCoin ke EnakPoint", coins),
Metadata: metadata,
IdempotencyKey: outKey,
}})
if errors.Is(err, repository.ErrWalletInsufficientBalance) {
return fmt.Errorf("%w: not enough EnakCoin", ErrWalletMoveRejected)
}
if err != nil {
return err
}
in, err := p.wallet.Credit(ctx, WalletCreditInput{
WalletEntry: WalletEntry{
TransactionID: inID,
CustomerID: customerID,
Currency: constants.WalletCurrencyPoint,
Type: constants.WalletTxTypeExchangeIn,
Amount: points,
ReferenceType: constants.WalletRefTypeWalletTx,
ReferenceID: outID,
GroupID: &groupID,
Description: fmt.Sprintf("Dari tukar %d EnakCoin", coins),
Metadata: metadata,
IdempotencyKey: inKey,
},
Lots: exchangeLots(out.Allocations, rate, ComputeExpiry(settings.PointExpiry, p.now())),
})
if err != nil {
return err
}
result.GroupID = groupID
result.Points = points
result.CoinAmount = rate.CoinAmount
result.PointAmount = rate.PointAmount
result.Lots = movedLots(in.Lots)
result.Replayed = out.Replayed
return nil
})
if err != nil {
return nil, err
}
balances, err := p.spendable.SpendableBalances(ctx, customerID, p.now())
if err != nil {
return nil, err
}
result.CoinBalance = balances[constants.WalletCurrencyCoin]
result.PointBalance = balances[constants.WalletCurrencyPoint]
return result, nil
}
// exchangeProblem says why coins cannot be exchanged, or "" when they can as far as
// the request goes. The balance is checked under the wallet lock.
func exchangeProblem(customer *repository.WalletMoveCustomer, rate models.LoyaltyExchangeSettings, coins int64) string {
switch {
case !customer.IsActive:
return "the customer is not active"
case coins <= 0:
return "the number of EnakCoin must be positive"
case rate.CoinAmount <= 0 || rate.PointAmount <= 0:
return "exchange is not available"
case coins%rate.CoinAmount != 0:
// Otherwise part of the EnakCoin would be lost to rounding (F4).
return fmt.Sprintf("EnakCoin are exchanged in multiples of %d", rate.CoinAmount)
}
return ""
}
// exchangePoints is (coins / coin_amount) × point_amount, for coins that are a
// multiple of coin_amount.
func exchangePoints(coins int64, rate models.LoyaltyExchangeSettings) int64 {
return coins / rate.CoinAmount * rate.PointAmount
}
// exchangeLots splits the EnakPoint of an exchange over the EnakCoin lots it took,
// so each part keeps the expiry of its lot and points back at it (K9). The share of
// a lot is the difference of floor(coins so far × point_amount / coin_amount) before
// and after it, which adds up exactly because the total is a multiple of
// coin_amount. A lot too small to earn a whole EnakPoint on its own gives none.
//
// Each part expires at the sooner of its EnakCoin lot's expiry and pointExpiry, when an
// EnakPoint received now would expire (F4); nil means never.
func exchangeLots(allocations []WalletAllocation, rate models.LoyaltyExchangeSettings, pointExpiry *time.Time) []WalletLotInput {
var lots []WalletLotInput
var coinsSoFar int64
for _, a := range allocations {
before := coinsSoFar * rate.PointAmount / rate.CoinAmount
coinsSoFar += a.Amount
points := coinsSoFar*rate.PointAmount/rate.CoinAmount - before
if points == 0 {
continue
}
lotID := a.LotID
lots = append(lots, WalletLotInput{Amount: points, ExpiresAt: EarlierExpiry(a.ExpiresAt, pointExpiry), OriginLotID: &lotID})
}
return lots
}
// frozenExchangeRate reads the rate an exchange was made at from its ledger row.
func frozenExchangeRate(metadata entities.Metadata, fallback models.LoyaltyExchangeSettings) models.LoyaltyExchangeSettings {
coinAmount, ok1 := metadataInt(metadata, "coin_amount")
pointAmount, ok2 := metadataInt(metadata, "point_amount")
if !ok1 || !ok2 || coinAmount <= 0 || pointAmount <= 0 {
return fallback
}
return models.LoyaltyExchangeSettings{CoinAmount: coinAmount, PointAmount: pointAmount}
}
// metadataInt reads a whole number from metadata that may have been through JSONB,
// which gives numbers back as float64.
func metadataInt(metadata entities.Metadata, key string) (int64, bool) {
switch v := metadata[key].(type) {
case float64:
return int64(v), true
case int64:
return v, true
case int:
return int64(v), true
}
return 0, false
}
func movedLots(lots []entities.WalletLot) []models.WalletMovedLot {
out := make([]models.WalletMovedLot, 0, len(lots))
for _, lot := range lots {
out = append(out, models.WalletMovedLot{Amount: lot.OriginalAmount, ExpiresAt: lot.ExpiresAt})
}
return out
}
// walletMoveKey checks the client's Idempotency-Key, which exchanges and transfers
// require (F4, F5).
func walletMoveKey(key string) (string, error) {
key = strings.TrimSpace(key)
if key == "" {
return "", fmt.Errorf("%w: the Idempotency-Key header is required", ErrWalletMoveRejected)
}
if len(key) > walletMoveKeyLimit {
return "", fmt.Errorf("%w: the Idempotency-Key header must be at most %d characters", ErrWalletMoveRejected, walletMoveKeyLimit)
}
return key, nil
}
@@ -0,0 +1,354 @@
package processor
import (
"context"
"errors"
"testing"
"time"
"github.com/google/uuid"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"apskel-pos-be/internal/constants"
"apskel-pos-be/internal/entities"
"apskel-pos-be/internal/models"
"apskel-pos-be/internal/repository"
)
// walletMoveEnv runs exchanges and transfers on the in-memory wallet, so every test
// also checks the §7.5 invariants when it ends.
type walletMoveEnv struct {
*walletTestEnv
customers *walletMoveRepoFake
settings *models.OrganizationLoyaltySettings
pins *movePinFake
}
func newWalletMoveEnv(t *testing.T) *walletMoveEnv {
e := &walletMoveEnv{
walletTestEnv: newWalletTestEnv(t),
customers: &walletMoveRepoFake{byID: map[uuid.UUID]*repository.WalletMoveCustomer{}},
settings: &models.OrganizationLoyaltySettings{
PointValue: 1,
Exchange: models.LoyaltyExchangeSettings{CoinAmount: 1, PointAmount: 1},
Transfer: models.LoyaltyTransferSettings{Enabled: true, MinAmount: 1},
},
pins: &movePinFake{good: "482913"},
}
e.customers.ledger = e.repo
// Ledger rows are stamped from now on, so "today" is the day of e.now.
e.repo.clock = e.now
return e
}
// member adds an active customer of the organization.
func (e *walletMoveEnv) member(name, phone string) uuid.UUID {
id := e.customer()
e.customers.byID[id] = &repository.WalletMoveCustomer{
ID: id, OrganizationID: e.org, Name: name, PhoneNumber: &phone, IsActive: true,
}
return id
}
func (e *walletMoveEnv) exchanges() *WalletExchangeProcessor {
p := NewWalletExchangeProcessor(e.customers, e, e, e.pins, e.p, txRunnerFake{})
p.now = func() time.Time { return e.now }
return p
}
func (e *walletMoveEnv) transfers(notifier customerNotifier) *WalletTransferProcessor {
p := NewWalletTransferProcessor(e.customers, e, e, e.pins, e.p, txRunnerFake{}, notifier)
p.now = func() time.Time { return e.now }
return p
}
func (e *walletMoveEnv) Organization(context.Context, uuid.UUID) (*models.OrganizationLoyaltySettings, error) {
s := *e.settings
return &s, nil
}
// SpendableBalances sums the unexpired lots, as the real query does.
func (e *walletMoveEnv) SpendableBalances(_ context.Context, customerID uuid.UUID, asOf time.Time) (map[string]int64, error) {
out := map[string]int64{}
for _, lot := range e.repo.lots {
if lot.CustomerID == customerID && (lot.ExpiresAt == nil || lot.ExpiresAt.After(asOf)) {
out[lot.Currency] += lot.RemainingAmount
}
}
return out, nil
}
// earnCoins gives a customer an EnakCoin lot.
func (e *walletMoveEnv) earnCoins(t *testing.T, customerID uuid.UUID, amount int64, expiresAt *time.Time) *WalletResult {
t.Helper()
in := earn(customerID, amount, expiresAt)
in.Currency = constants.WalletCurrencyCoin
return e.credit(t, in)
}
func (e *walletMoveEnv) coinBalance(t *testing.T, customerID uuid.UUID) int64 {
t.Helper()
w, err := e.repo.GetWallet(e.ctx, customerID)
require.NoError(t, err)
return w.CoinBalance
}
type walletMoveRepoFake struct {
byID map[uuid.UUID]*repository.WalletMoveCustomer
ledger *walletRepoFake
}
func (f *walletMoveRepoFake) GetCustomer(_ context.Context, id uuid.UUID) (*repository.WalletMoveCustomer, error) {
c, ok := f.byID[id]
if !ok {
return nil, repository.ErrWalletNotFound
}
copied := *c
return &copied, nil
}
func (f *walletMoveRepoFake) FindCustomerByPhone(ctx context.Context, phone string) (*repository.WalletMoveCustomer, error) {
for id, c := range f.byID {
if c.PhoneNumber != nil && *c.PhoneNumber == phone {
return f.GetCustomer(ctx, id)
}
}
return nil, repository.ErrWalletNotFound
}
func (f *walletMoveRepoFake) TransferredOutSince(_ context.Context, customerID uuid.UUID, currency string, since time.Time) (int64, error) {
var total int64
for _, tx := range f.ledger.transactions {
if tx.CustomerID == customerID && tx.Currency == currency && tx.Type == constants.WalletTxTypeTransferOut && !tx.CreatedAt.Before(since) {
total -= tx.Amount
}
}
return total, nil
}
// movePinFake accepts one PIN and records the actions it was asked to approve.
type movePinFake struct {
good string
err error
actions []PinAction
}
func (f *movePinFake) VerifyPin(_ context.Context, _ uuid.UUID, pin string, action PinAction, _ models.CustomerPinRequestInfo) error {
f.actions = append(f.actions, action)
if f.err != nil {
return f.err
}
if pin != f.good {
return &PinError{Code: PinErrInvalid, RemainingAttempts: 4}
}
return nil
}
func TestWalletExchange_DefaultRateIsOneToOne(t *testing.T) {
e := newWalletMoveEnv(t)
c := e.member("Budi Santoso", "081234561234")
e.earnCoins(t, c, 50, nil)
res, err := e.exchanges().Exchange(e.ctx, c, 50, "482913", "key-1", models.CustomerPinRequestInfo{})
require.NoError(t, err)
assert.Equal(t, int64(50), res.Points)
assert.Equal(t, int64(0), res.CoinBalance)
assert.Equal(t, int64(50), res.PointBalance)
assert.Equal(t, []PinAction{PinActionExchange}, e.pins.actions)
out, in := e.repo.transactions[1], e.repo.transactions[2]
assert.Equal(t, constants.WalletTxTypeExchangeOut, out.Type)
assert.Equal(t, constants.WalletCurrencyCoin, out.Currency)
assert.Equal(t, int64(-50), out.Amount)
assert.Equal(t, constants.WalletTxTypeExchangeIn, in.Type)
assert.Equal(t, constants.WalletCurrencyPoint, in.Currency)
assert.Equal(t, int64(50), in.Amount)
// The pair shares a group and each row points at the other (§8.1).
assert.Equal(t, *out.GroupID, *in.GroupID)
assert.Equal(t, res.GroupID, *out.GroupID)
assert.Equal(t, in.ID, out.ReferenceID)
assert.Equal(t, out.ID, in.ReferenceID)
assert.Equal(t, "Tukar 50 EnakCoin ke EnakPoint", out.Description)
assert.Equal(t, "Dari tukar 50 EnakCoin", in.Description)
// Both rows freeze the rate.
for _, row := range []*entities.WalletTransaction{out, in} {
assert.Equal(t, int64(1), row.Metadata["coin_amount"])
assert.Equal(t, int64(1), row.Metadata["point_amount"])
}
}
func TestWalletExchange_TenCoinsForThreePoints(t *testing.T) {
e := newWalletMoveEnv(t)
e.settings.Exchange = models.LoyaltyExchangeSettings{CoinAmount: 10, PointAmount: 3}
c := e.member("Budi", "081234561234")
e.earnCoins(t, c, 35, nil)
preview, err := e.exchanges().Preview(e.ctx, c, 30)
require.NoError(t, err)
assert.True(t, preview.Valid)
assert.Equal(t, int64(9), preview.Points)
assert.Equal(t, int64(35), preview.CoinBalance)
res, err := e.exchanges().Exchange(e.ctx, c, 30, "482913", "key-1", models.CustomerPinRequestInfo{})
require.NoError(t, err)
assert.Equal(t, int64(9), res.Points)
assert.Equal(t, int64(5), res.CoinBalance)
assert.Equal(t, int64(9), res.PointBalance)
}
func TestWalletExchange_RefusesAmountsThatAreNotAMultiple(t *testing.T) {
e := newWalletMoveEnv(t)
e.settings.Exchange = models.LoyaltyExchangeSettings{CoinAmount: 10, PointAmount: 3}
c := e.member("Budi", "081234561234")
e.earnCoins(t, c, 50, nil)
preview, err := e.exchanges().Preview(e.ctx, c, 25)
require.NoError(t, err)
assert.False(t, preview.Valid)
assert.Contains(t, preview.Reason, "multiples of 10")
_, err = e.exchanges().Exchange(e.ctx, c, 25, "482913", "key-1", models.CustomerPinRequestInfo{})
assert.ErrorIs(t, err, ErrWalletMoveRejected)
// Refused before the PIN, so a typo costs no attempt.
assert.Empty(t, e.pins.actions)
assert.Equal(t, int64(50), e.coinBalance(t, c))
_, err = e.exchanges().Exchange(e.ctx, c, 0, "482913", "key-2", models.CustomerPinRequestInfo{})
assert.ErrorIs(t, err, ErrWalletMoveRejected)
}
func TestWalletExchange_NeverOutlivesTheCoinLot(t *testing.T) {
e := newWalletMoveEnv(t)
e.settings.Exchange = models.LoyaltyExchangeSettings{CoinAmount: 10, PointAmount: 3}
c := e.member("Budi", "081234561234")
soon, later := e.at(24*time.Hour), e.at(48*time.Hour)
first := e.earnCoins(t, c, 15, soon)
second := e.earnCoins(t, c, 15, later)
third := e.earnCoins(t, c, 10, nil)
// 40 EnakCoin take 15 from the lot expiring soonest, 15 from the next and 10 from
// the one that never expires, giving 12 EnakPoint split 4 + 5 + 3.
res, err := e.exchanges().Exchange(e.ctx, c, 40, "482913", "key-1", models.CustomerPinRequestInfo{})
require.NoError(t, err)
require.Len(t, res.Lots, 3)
assert.Equal(t, models.WalletMovedLot{Amount: 4, ExpiresAt: soon}, res.Lots[0])
assert.Equal(t, models.WalletMovedLot{Amount: 5, ExpiresAt: later}, res.Lots[1])
assert.Equal(t, models.WalletMovedLot{Amount: 3}, res.Lots[2])
origins := map[uuid.UUID]*time.Time{}
for _, lot := range e.repo.lots {
if lot.Currency == constants.WalletCurrencyPoint {
require.NotNil(t, lot.OriginLotID)
origins[*lot.OriginLotID] = lot.ExpiresAt
}
}
assert.Equal(t, map[uuid.UUID]*time.Time{
first.Lots[0].ID: soon, second.Lots[0].ID: later, third.Lots[0].ID: nil,
}, origins)
for _, lot := range e.repo.lots {
if lot.Currency != constants.WalletCurrencyPoint || lot.OriginLotID == nil {
continue
}
for _, coinLot := range e.repo.lots {
if coinLot.ID == *lot.OriginLotID && coinLot.ExpiresAt != nil {
require.NotNil(t, lot.ExpiresAt, "a lot that expires cannot become one that does not")
assert.False(t, lot.ExpiresAt.After(*coinLot.ExpiresAt))
}
}
}
}
func TestWalletExchange_LotTooSmallForAWholePointGivesNone(t *testing.T) {
e := newWalletMoveEnv(t)
e.settings.Exchange = models.LoyaltyExchangeSettings{CoinAmount: 10, PointAmount: 1}
c := e.member("Budi", "081234561234")
e.earnCoins(t, c, 5, e.at(time.Hour))
e.earnCoins(t, c, 5, nil)
// Neither lot is worth a whole EnakPoint alone; the one that completes the 10
// carries it.
res, err := e.exchanges().Exchange(e.ctx, c, 10, "482913", "key-1", models.CustomerPinRequestInfo{})
require.NoError(t, err)
assert.Equal(t, []models.WalletMovedLot{{Amount: 1}}, res.Lots)
}
func TestWalletExchange_NotEnoughCoins(t *testing.T) {
e := newWalletMoveEnv(t)
c := e.member("Budi", "081234561234")
e.earnCoins(t, c, 5, nil)
preview, err := e.exchanges().Preview(e.ctx, c, 6)
require.NoError(t, err)
assert.False(t, preview.Valid)
_, err = e.exchanges().Exchange(e.ctx, c, 6, "482913", "key-1", models.CustomerPinRequestInfo{})
assert.ErrorIs(t, err, ErrWalletMoveRejected)
assert.Equal(t, int64(5), e.coinBalance(t, c))
}
func TestWalletExchange_WrongPinMovesNothing(t *testing.T) {
e := newWalletMoveEnv(t)
c := e.member("Budi", "081234561234")
e.earnCoins(t, c, 5, nil)
_, err := e.exchanges().Exchange(e.ctx, c, 5, "000000", "key-1", models.CustomerPinRequestInfo{})
var pinErr *PinError
require.True(t, errors.As(err, &pinErr))
assert.Equal(t, PinErrInvalid, pinErr.Code)
assert.Equal(t, int64(5), e.coinBalance(t, c))
}
func TestWalletExchange_RetryReturnsTheFirstExchangeAtItsRate(t *testing.T) {
e := newWalletMoveEnv(t)
c := e.member("Budi", "081234561234")
e.earnCoins(t, c, 100, nil)
first, err := e.exchanges().Exchange(e.ctx, c, 40, "482913", "key-1", models.CustomerPinRequestInfo{})
require.NoError(t, err)
// The rate changes before the retry arrives; the retry still gets the first result.
e.settings.Exchange = models.LoyaltyExchangeSettings{CoinAmount: 1, PointAmount: 2}
again, err := e.exchanges().Exchange(e.ctx, c, 40, "482913", "key-1", models.CustomerPinRequestInfo{})
require.NoError(t, err)
assert.True(t, again.Replayed)
assert.Equal(t, first.GroupID, again.GroupID)
assert.Equal(t, int64(40), again.Points)
assert.Equal(t, int64(60), e.coinBalance(t, c))
assert.Len(t, e.repo.transactions, 3)
// The same key for a different amount is not a retry.
_, err = e.exchanges().Exchange(e.ctx, c, 20, "482913", "key-1", models.CustomerPinRequestInfo{})
assert.ErrorIs(t, err, ErrWalletIdempotencyConflict)
}
func TestWalletExchange_RequiresAnIdempotencyKey(t *testing.T) {
e := newWalletMoveEnv(t)
c := e.member("Budi", "081234561234")
e.earnCoins(t, c, 5, nil)
_, err := e.exchanges().Exchange(e.ctx, c, 5, "482913", " ", models.CustomerPinRequestInfo{})
assert.ErrorIs(t, err, ErrWalletMoveRejected)
assert.Empty(t, e.pins.actions)
}
// F4: EnakPoint from an exchange expire at the sooner of the EnakCoin lot's expiry and
// when EnakPoint received now would expire.
func TestWalletExchange_CappedByThePointExpiry(t *testing.T) {
e := newWalletMoveEnv(t)
e.now = wib(2026, 6, 1, 10, 0)
e.settings.PointExpiry = rolling(30, "DAY", false)
c := e.member("Budi", "081234561234")
soon, later := e.at(24*time.Hour), e.at(90*24*time.Hour)
e.earnCoins(t, c, 10, soon)
e.earnCoins(t, c, 10, later)
e.earnCoins(t, c, 10, nil)
res, err := e.exchanges().Exchange(e.ctx, c, 30, "482913", "key-1", models.CustomerPinRequestInfo{})
require.NoError(t, err)
require.Len(t, res.Lots, 3)
assert.Equal(t, soon, res.Lots[0].ExpiresAt, "the EnakCoin lot expires first")
assert.Equal(t, "2026-07-01", expiryDay(t, res.Lots[1].ExpiresAt), "30 days of EnakPoint come first")
assert.Equal(t, "2026-07-01", expiryDay(t, res.Lots[2].ExpiresAt), "a lot that never expired gets the EnakPoint expiry")
}
@@ -0,0 +1,196 @@
package processor
import (
"context"
"fmt"
"strconv"
"time"
"github.com/google/uuid"
"apskel-pos-be/internal/constants"
"apskel-pos-be/internal/logger"
"apskel-pos-be/internal/repository"
)
const (
// Lots expired per query; a run keeps going until nothing is due.
walletExpiryBatchSize = 500
// Batches per run at most, so one run cannot run away.
walletExpiryMaxBatches = 40
)
// NotificationTypeWalletExpired is the data type of the push a customer gets when
// part of their balance expires.
const NotificationTypeWalletExpired = "WALLET_EXPIRED"
// NotificationTypeWalletExpiring is the data type of the reminder a customer gets
// before part of their balance expires.
const NotificationTypeWalletExpiring = "WALLET_EXPIRING"
// WalletExpiryProcessor takes what is left in lots whose expiry has passed
// (docs/prd-point-coin.md F12, PC-503). It is safe to run on several instances at
// once: every lot is expired under its wallet's lock with the key expire:{lot_id}.
type WalletExpiryProcessor struct {
repo repository.WalletExpiryRepository
settings organizationSettingsReader
wallet *WalletProcessor
tx TxRunner
notifier customerNotifier
now func() time.Time
}
func NewWalletExpiryProcessor(repo repository.WalletExpiryRepository, settings organizationSettingsReader, wallet *WalletProcessor, tx TxRunner, notifier customerNotifier) *WalletExpiryProcessor {
return &WalletExpiryProcessor{repo: repo, settings: settings, wallet: wallet, tx: tx, notifier: notifier, now: time.Now}
}
type walletExpiredKey struct {
customerID uuid.UUID
currency string
}
// ExpireDue expires every lot due now and tells each customer how much of each
// currency they lost, in one push per currency. It returns how many lots it expired.
// A lot that fails is logged and left for the next run; it does not stop the others.
func (p *WalletExpiryProcessor) ExpireDue(ctx context.Context) (int, error) {
asOf := p.now()
expired := map[walletExpiredKey]int64{}
count := 0
for batch := 0; batch < walletExpiryMaxBatches; batch++ {
due, err := p.repo.ListDueLots(ctx, asOf, walletExpiryBatchSize)
if err != nil {
p.notify(ctx, expired)
return count, err
}
progressed := false
for _, lot := range due {
var res *WalletResult
err := p.tx.WithTransaction(ctx, func(ctx context.Context) error {
var err error
res, err = p.wallet.ExpireLot(ctx, lot.ID, func(amount int64) string {
return expiryDescription(amount, lot.Currency, lot.SourceDescription)
}, asOf)
return err
})
if err != nil {
logger.NonContext.Error(fmt.Sprintf("Could not expire wallet lot %s; it will be retried", lot.ID), err)
continue
}
if res == nil || res.Transaction == nil || res.Replayed {
// Another run got there first, or a payment used it up.
continue
}
progressed = true
count++
expired[walletExpiredKey{lot.CustomerID, lot.Currency}] += -res.Transaction.Amount
}
// A short batch was the last; a batch that moved nothing would only come back
// the same, whether failing or taken by another instance.
if len(due) < walletExpiryBatchSize || !progressed {
break
}
}
p.notify(ctx, expired)
return count, nil
}
// notify is best effort: the balance has already expired.
func (p *WalletExpiryProcessor) notify(ctx context.Context, expired map[walletExpiredKey]int64) {
if p.notifier == nil {
return
}
for key, amount := range expired {
name := walletCurrencyName(key.currency)
data := map[string]string{
"type": NotificationTypeWalletExpired,
"currency": key.currency,
"amount": strconv.FormatInt(amount, 10),
}
body := fmt.Sprintf("%d %s kamu sudah kedaluwarsa.", amount, name)
if err := p.notifier.Notify(ctx, key.customerID, name+" kedaluwarsa", body, data); err != nil {
logger.NonContext.Error(fmt.Sprintf("Could not tell customer %s about expired %s", key.customerID, name), err)
}
}
}
// expiryDescription is the EXPIRE row's frozen description (§8.1):
// "Kedaluwarsa: 150 EnakPoint dari Belanja #ORD-0098".
func expiryDescription(amount int64, currency, sourceDescription string) string {
description := fmt.Sprintf("Kedaluwarsa: %d %s", amount, walletCurrencyName(currency))
if sourceDescription != "" {
description += " dari " + sourceDescription
}
return truncateRunes(description, walletDescriptionLimit)
}
// SendReminders tells customers, reminder_days before, how much of their balance
// expires on a day (F12): one push per customer, currency and expiry day, however many
// lots make it up. A reminder is recorded before it is sent, so another instance or a
// later run never sends it again; a push that then fails is logged and not retried.
// It returns how many reminders it sent.
func (p *WalletExpiryProcessor) SendReminders(ctx context.Context) (int, error) {
now := p.now()
organizations, err := p.repo.OrganizationsWithUpcomingExpiry(ctx, now)
if err != nil {
return 0, err
}
sent := 0
for _, organizationID := range organizations {
settings, err := p.settings.Organization(ctx, organizationID)
if err != nil {
logger.NonContext.Error(fmt.Sprintf("Could not read the expiry settings of organization %s; its reminders wait for the next run", organizationID), err)
continue
}
for _, currency := range []string{constants.WalletCurrencyPoint, constants.WalletCurrencyCoin} {
days := ExpirySettings(settings, currency).ReminderDays
if days <= 0 {
continue
}
until := endOfWalletDay(walletDay(now).AddDate(0, 0, int(days)))
upcoming, err := p.repo.UpcomingUnreminded(ctx, organizationID, currency, now, *until)
if err != nil {
return sent, err
}
for _, u := range upcoming {
first, err := p.repo.MarkReminded(ctx, u, currency)
if err != nil {
return sent, err
}
if !first {
continue
}
sent++
p.remind(ctx, u, currency)
}
}
}
return sent, nil
}
func (p *WalletExpiryProcessor) remind(ctx context.Context, u repository.UpcomingExpiry, currency string) {
if p.notifier == nil {
return
}
name := walletCurrencyName(currency)
body := fmt.Sprintf("%d %s akan kedaluwarsa pada %s. Pakai sebelum hangus.", u.Amount, name, formatWalletDate(u.Date))
data := map[string]string{
"type": NotificationTypeWalletExpiring,
"currency": currency,
"amount": strconv.FormatInt(u.Amount, 10),
"expiry_date": u.Date,
}
if err := p.notifier.Notify(ctx, u.CustomerID, name+" akan kedaluwarsa", body, data); err != nil {
logger.NonContext.Error(fmt.Sprintf("Could not remind customer %s of expiring %s", u.CustomerID, name), err)
}
}
var walletMonthNames = [...]string{"Jan", "Feb", "Mar", "Apr", "Mei", "Jun", "Jul", "Agu", "Sep", "Okt", "Nov", "Des"}
// formatWalletDate writes a YYYY-MM-DD date the way the apps do: "31 Okt 2026".
func formatWalletDate(date string) string {
d, err := time.Parse("2006-01-02", date)
if err != nil {
return date
}
return fmt.Sprintf("%d %s %d", d.Day(), walletMonthNames[d.Month()-1], d.Year())
}
@@ -0,0 +1,244 @@
package processor
import (
"context"
"sort"
"testing"
"time"
"github.com/google/uuid"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"apskel-pos-be/internal/constants"
"apskel-pos-be/internal/entities"
"apskel-pos-be/internal/repository"
)
// walletExpiryRepoFake lists the fake wallet's due lots the way the query does, plus
// any extra lots a test wants listed.
type walletExpiryRepoFake struct {
wallet *walletRepoFake
extra []repository.DueLot
// customer/currency/date of the reminders recorded.
reminded map[string]bool
}
func (f *walletExpiryRepoFake) ListDueLots(_ context.Context, asOf time.Time, limit int) ([]repository.DueLot, error) {
descriptions := map[uuid.UUID]string{}
for _, tx := range f.wallet.transactions {
descriptions[tx.ID] = tx.Description
}
due := append([]repository.DueLot(nil), f.extra...)
for _, lot := range f.wallet.lots {
if lot.RemainingAmount > 0 && lot.ExpiresAt != nil && !lot.ExpiresAt.After(asOf) {
due = append(due, repository.DueLot{
ID: lot.ID, CustomerID: lot.CustomerID, Currency: lot.Currency, Remaining: lot.RemainingAmount,
ExpiresAt: *lot.ExpiresAt, SourceDescription: descriptions[lot.SourceTransactionID],
})
}
}
sort.SliceStable(due, func(i, j int) bool { return due[i].ExpiresAt.Before(due[j].ExpiresAt) })
if len(due) > limit {
due = due[:limit]
}
return due, nil
}
func (e *walletMoveEnv) expiry(notifier customerNotifier) (*WalletExpiryProcessor, *walletExpiryRepoFake) {
repo := &walletExpiryRepoFake{wallet: e.repo}
p := NewWalletExpiryProcessor(repo, e, e.p, txRunnerFake{}, notifier)
p.now = func() time.Time { return e.now }
return p, repo
}
func TestWalletExpiry_ExpiresWhatIsDueAndTellsTheCustomer(t *testing.T) {
e := newWalletMoveEnv(t)
a := e.member("Anita", "081200005678")
ord := earn(a, 150, e.at(-time.Hour))
ord.Description = "Belanja #ORD-0098"
due := e.credit(t, ord)
e.credit(t, earn(a, 50, e.at(-2*time.Hour)))
e.credit(t, earn(a, 70, e.at(time.Hour))) // not yet
e.credit(t, earn(a, 30, nil)) // never
e.earnCoins(t, a, 4, e.at(-time.Minute))
// A payment already used part of the first lot; only the rest expires.
_, err := e.p.Debit(e.ctx, WalletDebitInput{WalletEntry: pay(a, 20).WalletEntry, PreferredLotIDs: []uuid.UUID{due.Lots[0].ID}})
require.NoError(t, err)
notifier := &notifierFake{}
p, _ := e.expiry(notifier)
count, err := p.ExpireDue(e.ctx)
require.NoError(t, err)
assert.Equal(t, 3, count)
assert.Equal(t, int64(100), e.balance(t, a), "70 not due yet + 30 that never expires")
assert.Equal(t, int64(0), e.coinBalance(t, a))
var expire *entities.WalletTransaction
for _, tx := range e.repo.transactions {
if tx.Type == constants.WalletTxTypeExpire && tx.ReferenceID == due.Lots[0].ID {
expire = tx
}
}
require.NotNil(t, expire)
assert.Equal(t, int64(-130), expire.Amount)
assert.Equal(t, "Kedaluwarsa: 130 EnakPoint dari Belanja #ORD-0098", expire.Description)
assert.Equal(t, constants.WalletRefTypeLot, expire.ReferenceType)
assert.Equal(t, "expire:"+due.Lots[0].ID.String(), *expire.IdempotencyKey)
// One push per currency, with the total.
pushes := notifier.pushes[a]
require.Len(t, pushes, 2)
byCurrency := map[string]pushFake{}
for _, p := range pushes {
byCurrency[p.data["currency"]] = p
}
assert.Equal(t, "EnakPoint kedaluwarsa", byCurrency["POINT"].title)
assert.Equal(t, "180 EnakPoint kamu sudah kedaluwarsa.", byCurrency["POINT"].body)
assert.Equal(t, NotificationTypeWalletExpired, byCurrency["POINT"].data["type"])
assert.Equal(t, "4", byCurrency["COIN"].data["amount"])
}
func TestWalletExpiry_RunningAgainExpiresNothingMore(t *testing.T) {
e := newWalletMoveEnv(t)
a := e.member("Anita", "081200005678")
e.credit(t, earn(a, 150, e.at(-time.Hour)))
notifier := &notifierFake{}
// Two instances, one after the other.
first, _ := e.expiry(notifier)
second, _ := e.expiry(notifier)
n1, err := first.ExpireDue(e.ctx)
require.NoError(t, err)
n2, err := second.ExpireDue(e.ctx)
require.NoError(t, err)
assert.Equal(t, 1, n1)
assert.Equal(t, 0, n2)
assert.Len(t, notifier.pushes[a], 1)
var expires int
for _, tx := range e.repo.transactions {
if tx.Type == constants.WalletTxTypeExpire {
expires++
}
}
assert.Equal(t, 1, expires)
}
func TestWalletExpiry_OneFailingLotDoesNotStopTheOthers(t *testing.T) {
e := newWalletMoveEnv(t)
a := e.member("Anita", "081200005678")
e.credit(t, earn(a, 150, e.at(-time.Hour)))
p, repo := e.expiry(nil)
// A lot listed that ExpireLot cannot find.
repo.extra = []repository.DueLot{{ID: uuid.New(), CustomerID: a, Currency: "POINT", Remaining: 5, ExpiresAt: e.now.Add(-3 * time.Hour)}}
count, err := p.ExpireDue(e.ctx)
require.NoError(t, err)
assert.Equal(t, 1, count)
assert.Equal(t, int64(0), e.balance(t, a))
}
func TestWalletExpiry_NothingDue(t *testing.T) {
e := newWalletMoveEnv(t)
a := e.member("Anita", "081200005678")
e.credit(t, earn(a, 150, e.at(time.Hour)))
notifier := &notifierFake{}
p, _ := e.expiry(notifier)
count, err := p.ExpireDue(e.ctx)
require.NoError(t, err)
assert.Zero(t, count)
assert.Empty(t, notifier.pushes)
}
func (f *walletExpiryRepoFake) OrganizationsWithUpcomingExpiry(_ context.Context, asOf time.Time) ([]uuid.UUID, error) {
seen := map[uuid.UUID]bool{}
var out []uuid.UUID
for _, lot := range f.wallet.lots {
if lot.RemainingAmount > 0 && lot.ExpiresAt != nil && lot.ExpiresAt.After(asOf) && !seen[lot.OrganizationID] {
seen[lot.OrganizationID] = true
out = append(out, lot.OrganizationID)
}
}
return out, nil
}
func (f *walletExpiryRepoFake) UpcomingUnreminded(_ context.Context, organizationID uuid.UUID, currency string, asOf, until time.Time) ([]repository.UpcomingExpiry, error) {
sums := map[[2]string]int64{}
var order [][2]string
for _, lot := range f.wallet.lots {
if lot.OrganizationID != organizationID || lot.Currency != currency || lot.RemainingAmount == 0 ||
lot.ExpiresAt == nil || !lot.ExpiresAt.After(asOf) || lot.ExpiresAt.After(until) {
continue
}
key := [2]string{lot.CustomerID.String(), lot.ExpiresAt.In(walletDisplayLocation).Format("2006-01-02")}
if f.reminded[key[0]+"/"+currency+"/"+key[1]] {
continue
}
if _, ok := sums[key]; !ok {
order = append(order, key)
}
sums[key] += lot.RemainingAmount
}
var out []repository.UpcomingExpiry
for _, key := range order {
out = append(out, repository.UpcomingExpiry{CustomerID: uuid.MustParse(key[0]), Date: key[1], Amount: sums[key]})
}
return out, nil
}
func (f *walletExpiryRepoFake) MarkReminded(_ context.Context, u repository.UpcomingExpiry, currency string) (bool, error) {
if f.reminded == nil {
f.reminded = map[string]bool{}
}
key := u.CustomerID.String() + "/" + currency + "/" + u.Date
if f.reminded[key] {
return false, nil
}
f.reminded[key] = true
return true, nil
}
func TestWalletExpiry_RemindsOncePerDayBeforeExpiry(t *testing.T) {
e := newWalletMoveEnv(t)
e.now = wib(2026, 10, 25, 9, 0)
e.settings.PointExpiry.ReminderDays = 7
e.settings.CoinExpiry.ReminderDays = 0 // no reminders for EnakCoin
a := e.member("Anita", "081200005678")
oct31 := wib(2026, 10, 31, 23, 59)
nov30 := wib(2026, 11, 30, 23, 59)
e.credit(t, earn(a, 100, &oct31))
e.credit(t, earn(a, 50, &oct31))
e.credit(t, earn(a, 70, &nov30)) // too far off yet
e.earnCoins(t, a, 5, &oct31)
notifier := &notifierFake{}
p, _ := e.expiry(notifier)
sent, err := p.SendReminders(e.ctx)
require.NoError(t, err)
assert.Equal(t, 1, sent)
require.Len(t, notifier.pushes[a], 1)
push := notifier.pushes[a][0]
assert.Equal(t, "EnakPoint akan kedaluwarsa", push.title)
assert.Equal(t, "150 EnakPoint akan kedaluwarsa pada 31 Okt 2026. Pakai sebelum hangus.", push.body)
assert.Equal(t, map[string]string{"type": NotificationTypeWalletExpiring, "currency": "POINT", "amount": "150", "expiry_date": "2026-10-31"}, push.data)
// The next run, on this instance or another, sends nothing again.
again, err := p.SendReminders(e.ctx)
require.NoError(t, err)
assert.Zero(t, again)
// Once 30 Nov comes within seven days, it gets its own reminder.
e.now = wib(2026, 11, 23, 9, 0)
sent, err = p.SendReminders(e.ctx)
require.NoError(t, err)
assert.Equal(t, 1, sent)
assert.Equal(t, "70", notifier.pushes[a][1].data["amount"])
}
func TestFormatWalletDate(t *testing.T) {
assert.Equal(t, "31 Okt 2026", formatWalletDate("2026-10-31"))
assert.Equal(t, "1 Mei 2027", formatWalletDate("2027-05-01"))
}
@@ -0,0 +1,184 @@
package processor
import (
"context"
"fmt"
"github.com/google/uuid"
"apskel-pos-be/internal/constants"
"apskel-pos-be/internal/entities"
"apskel-pos-be/internal/repository"
)
// TxRunner runs fn inside a database transaction. repository.TxManager is one.
type TxRunner interface {
WithTransaction(ctx context.Context, fn func(ctx context.Context) error) error
}
// WalletMigrationDiscrepancy is a customer whose legacy balance is now lower than
// what was already migrated: the old code spent from it after the migration ran.
// The wallet is left alone, because only an admin adjustment can take balance away.
type WalletMigrationDiscrepancy struct {
CustomerID uuid.UUID
Currency string
Legacy int64
Migrated int64
}
type WalletMigrationReport struct {
DryRun bool
CustomersScanned int
// Ledger rows written (or, on a dry run, that would be written) and their sum.
PointCredits int
PointsCredited int64
CoinCredits int
CoinsCredited int64
Discrepancies []WalletMigrationDiscrepancy
// Taken after the run. On a dry run they show the state before it.
Totals *repository.WalletMigrationTotals
}
// Balanced reports whether everything in the legacy tables is now in the wallet.
func (r *WalletMigrationReport) Balanced() bool {
return len(r.Discrepancies) == 0 && r.Totals != nil &&
r.Totals.LegacyPoints == r.Totals.MigratedPoints &&
r.Totals.LegacyCoins == r.Totals.MigratedCoins
}
// WalletMigrationProcessor moves the balances in customer_points and customer_tokens
// into the wallet (docs/prd-point-coin.md §10, PC-105). Each customer gets a MIGRATION
// ledger row and a non-expiring lot per currency, through WalletProcessor like any
// other credit, so the wallet reconciles from the first row.
//
// It credits the difference between the legacy balance and what earlier runs already
// migrated, so running it again never doubles a balance, and a run after the old code
// kept writing to the legacy tables picks up only what was added since.
type WalletMigrationProcessor struct {
repo repository.WalletMigrationRepository
wallet *WalletProcessor
tx TxRunner
}
func NewWalletMigrationProcessor(repo repository.WalletMigrationRepository, wallet *WalletProcessor, tx TxRunner) *WalletMigrationProcessor {
return &WalletMigrationProcessor{repo: repo, wallet: wallet, tx: tx}
}
// Run migrates every customer with a legacy balance, one transaction per customer.
// With dryRun it only reports what it would credit.
func (p *WalletMigrationProcessor) Run(ctx context.Context, dryRun bool, batchSize int) (*WalletMigrationReport, error) {
if batchSize <= 0 {
batchSize = 500
}
report := &WalletMigrationReport{DryRun: dryRun}
after := uuid.Nil
for {
ids, err := p.repo.ListLegacyCustomers(ctx, after, batchSize)
if err != nil {
return nil, err
}
if len(ids) == 0 {
break
}
for _, id := range ids {
if dryRun {
err = p.migrateCustomer(ctx, id, true, report)
} else {
err = p.tx.WithTransaction(ctx, func(ctx context.Context) error {
return p.migrateCustomer(ctx, id, false, report)
})
}
if err != nil {
return nil, fmt.Errorf("customer %s: %w", id, err)
}
report.CustomersScanned++
}
after = ids[len(ids)-1]
}
totals, err := p.repo.Totals(ctx)
if err != nil {
return nil, err
}
report.Totals = totals
return report, nil
}
func (p *WalletMigrationProcessor) migrateCustomer(ctx context.Context, customerID uuid.UUID, dryRun bool, report *WalletMigrationReport) error {
// Lock before reading what was migrated, so two runs at once cannot both see the
// same gap and fill it twice.
if !dryRun {
if err := p.wallet.LockWallet(ctx, customerID); err != nil {
return err
}
}
legacy, err := p.repo.GetLegacyBalance(ctx, customerID)
if err != nil {
return err
}
// Points come from the single customer_points row. Tokens come from several rows,
// one per type, so the ledger row points at the customer and lists the rows.
pointsRef := customerID
if legacy.PointsRowID != nil {
pointsRef = *legacy.PointsRowID
}
tokens := make([]map[string]any, 0, len(legacy.Tokens))
for _, t := range legacy.Tokens {
tokens = append(tokens, map[string]any{"id": t.ID, "token_type": string(t.TokenType), "balance": t.Balance})
}
for _, c := range []struct {
currency, refType string
refID uuid.UUID
legacy int64
metadata entities.Metadata
credits *int
credited *int64
}{
{constants.WalletCurrencyPoint, constants.WalletRefTypeLegacyPoints, pointsRef, legacy.Points,
entities.Metadata{}, &report.PointCredits, &report.PointsCredited},
{constants.WalletCurrencyCoin, constants.WalletRefTypeLegacyTokens, customerID, legacy.Coins(),
entities.Metadata{"legacy_tokens": tokens}, &report.CoinCredits, &report.CoinsCredited},
} {
migrated, err := p.repo.SumMigrated(ctx, customerID, c.currency)
if err != nil {
return err
}
delta := c.legacy - migrated
if delta < 0 {
report.Discrepancies = append(report.Discrepancies, WalletMigrationDiscrepancy{
CustomerID: customerID, Currency: c.currency, Legacy: c.legacy, Migrated: migrated,
})
continue
}
if delta == 0 {
continue
}
if !dryRun {
c.metadata["legacy_balance"] = c.legacy
c.metadata["previously_migrated"] = migrated
_, err = p.wallet.Credit(ctx, WalletCreditInput{WalletEntry: WalletEntry{
CustomerID: customerID,
Currency: c.currency,
Type: constants.WalletTxTypeMigration,
Amount: delta,
ReferenceType: c.refType,
ReferenceID: c.refID,
Description: "Saldo awal dari sistem lama",
Metadata: c.metadata,
// The legacy total in the key lets a later run top up a balance that
// grew, while a retry of the same run is still recognised.
IdempotencyKey: fmt.Sprintf("migration:%s:%s:%d", c.currency, customerID, c.legacy),
}})
if err != nil {
return err
}
}
*c.credits++
*c.credited += delta
}
return nil
}
@@ -0,0 +1,167 @@
package processor
import (
"context"
"os"
"testing"
"github.com/google/uuid"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"gorm.io/driver/postgres"
"gorm.io/gorm"
"gorm.io/gorm/logger"
"apskel-pos-be/internal/constants"
"apskel-pos-be/internal/repository"
)
// Needs TEST_DATABASE_URL pointing at a migrated database; see
// internal/repository/wallet_repository_test.go. Other packages' tests may use the
// same database at the same time, so everything here is scoped to its own customers.
func TestWalletMigrationProcessor_AgainstPostgres(t *testing.T) {
dsn := os.Getenv("TEST_DATABASE_URL")
if dsn == "" {
t.Skip("TEST_DATABASE_URL not set")
}
db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{Logger: logger.Default.LogMode(logger.Silent)})
require.NoError(t, err)
ctx := context.Background()
org := uuid.New()
full, tokensOnly, pointsOnly, none := uuid.New(), uuid.New(), uuid.New(), uuid.New()
customers := []uuid.UUID{full, tokensOnly, pointsOnly, none}
exec := func(q string, args ...any) {
t.Helper()
require.NoError(t, db.Exec(q, args...).Error)
}
exec(`INSERT INTO organizations (id, name, plan_type) VALUES (?, 'migration test', 'basic')`, org)
for _, c := range customers {
exec(`INSERT INTO customers (id, organization_id, name) VALUES (?, ?, 'migration test')`, c, org)
}
t.Cleanup(func() {
db.Exec(`DELETE FROM wallet_lot_allocations WHERE lot_id IN (SELECT id FROM wallet_lots WHERE customer_id IN ?)`, customers)
db.Exec(`DELETE FROM wallet_lots WHERE customer_id IN ?`, customers)
db.Exec(`DELETE FROM wallet_transactions WHERE customer_id IN ?`, customers)
db.Exec(`DELETE FROM customer_wallets WHERE customer_id IN ?`, customers)
db.Exec(`DELETE FROM customers WHERE id IN ?`, customers)
db.Exec(`DELETE FROM organizations WHERE id = ?`, org)
})
// The example from §10: SPIN 5 + RAFFLE 2 + MINIGAME 1 = 8 EnakCoin.
exec(`INSERT INTO customer_points (customer_id, balance) VALUES (?, 100), (?, 0), (?, 40)`, full, tokensOnly, pointsOnly)
exec(`INSERT INTO customer_tokens (customer_id, token_type, balance) VALUES
(?, 'SPIN', 5), (?, 'RAFFLE', 2), (?, 'MINIGAME', 1), (?, 'SPIN', 3)`, full, full, full, tokensOnly)
migrator := NewWalletMigrationProcessor(
repository.NewWalletMigrationRepository(db),
NewWalletProcessor(repository.NewWalletRepository(db)),
repository.NewTxManager(db),
)
type balance struct{ Point, Coin int64 }
balances := func() map[uuid.UUID]balance {
t.Helper()
var rows []struct {
CustomerID uuid.UUID
PointBalance, CoinBalance int64
}
require.NoError(t, db.Raw(`SELECT customer_id, point_balance, coin_balance FROM customer_wallets WHERE customer_id IN ?`, customers).Scan(&rows).Error)
out := map[uuid.UUID]balance{}
for _, r := range rows {
out[r.CustomerID] = balance{r.PointBalance, r.CoinBalance}
}
return out
}
countRows := func() int64 {
t.Helper()
var n int64
require.NoError(t, db.Raw(`SELECT COUNT(*) FROM wallet_transactions WHERE customer_id IN ?`, customers).Scan(&n).Error)
return n
}
// A dry run reports and writes nothing, not even the wallets.
report, err := migrator.Run(ctx, true, 2)
require.NoError(t, err)
assert.GreaterOrEqual(t, report.PointsCredited, int64(140))
assert.GreaterOrEqual(t, report.CoinsCredited, int64(11))
assert.Empty(t, balances())
assert.Zero(t, countRows())
// The real run. A batch of 2 makes it page through the customers.
_, err = migrator.Run(ctx, false, 2)
require.NoError(t, err)
assert.Equal(t, map[uuid.UUID]balance{
full: {Point: 100, Coin: 8},
tokensOnly: {Point: 0, Coin: 3},
pointsOnly: {Point: 40, Coin: 0},
}, balances(), "a customer without legacy rows gets no wallet")
assert.Equal(t, int64(4), countRows(), "one row per customer per currency with a balance")
var coinRow struct {
ReferenceType string
ReferenceID uuid.UUID
Metadata string
}
require.NoError(t, db.Raw(`SELECT reference_type, reference_id, metadata::text AS metadata FROM wallet_transactions
WHERE customer_id = ? AND currency = 'COIN'`, full).Scan(&coinRow).Error)
assert.Equal(t, constants.WalletRefTypeLegacyTokens, coinRow.ReferenceType)
assert.Equal(t, full, coinRow.ReferenceID)
for _, part := range []string{`"token_type": "SPIN"`, `"token_type": "RAFFLE"`, `"token_type": "MINIGAME"`, `"legacy_balance": 8`} {
assert.Contains(t, coinRow.Metadata, part)
}
var pointRef, pointsRowID string
require.NoError(t, db.Raw(`SELECT reference_id::text FROM wallet_transactions WHERE customer_id = ? AND currency = 'POINT'`, full).Scan(&pointRef).Error)
require.NoError(t, db.Raw(`SELECT id::text FROM customer_points WHERE customer_id = ?`, full).Scan(&pointsRowID).Error)
assert.NotEmpty(t, pointRef)
assert.Equal(t, pointsRowID, pointRef, "points row points at the customer_points row")
var expiring int64
require.NoError(t, db.Raw(`SELECT COUNT(*) FROM wallet_lots WHERE customer_id IN ? AND expires_at IS NOT NULL`, customers).Scan(&expiring).Error)
assert.Zero(t, expiring, "migrated lots never expire")
// Running again changes nothing.
report, err = migrator.Run(ctx, false, 2)
require.NoError(t, err)
assert.Equal(t, int64(4), countRows())
assert.Empty(t, discrepanciesFor(report, customers))
// The old code kept writing: one balance grew, one shrank. Only the growth is
// migrated; the shrink is reported and left alone.
exec(`UPDATE customer_tokens SET balance = 9 WHERE customer_id = ? AND token_type = 'SPIN'`, full)
exec(`UPDATE customer_points SET balance = 30 WHERE customer_id = ?`, pointsOnly)
report, err = migrator.Run(ctx, false, 2)
require.NoError(t, err)
assert.Equal(t, balance{Point: 100, Coin: 12}, balances()[full])
assert.Equal(t, balance{Point: 40, Coin: 0}, balances()[pointsOnly])
assert.Equal(t, []WalletMigrationDiscrepancy{{CustomerID: pointsOnly, Currency: constants.WalletCurrencyPoint, Legacy: 30, Migrated: 40}},
discrepanciesFor(report, customers))
assert.Equal(t, int64(5), countRows())
// §7.5 for these customers.
var broken int64
require.NoError(t, db.Raw(`
SELECT COUNT(*) FROM customer_wallets w
WHERE w.customer_id IN ? AND (
w.point_balance <> (SELECT COALESCE(SUM(amount), 0) FROM wallet_transactions t WHERE t.customer_id = w.customer_id AND t.currency = 'POINT')
OR w.coin_balance <> (SELECT COALESCE(SUM(amount), 0) FROM wallet_transactions t WHERE t.customer_id = w.customer_id AND t.currency = 'COIN')
OR w.point_balance <> (SELECT COALESCE(SUM(remaining_amount), 0) FROM wallet_lots l WHERE l.customer_id = w.customer_id AND l.currency = 'POINT')
OR w.coin_balance <> (SELECT COALESCE(SUM(remaining_amount), 0) FROM wallet_lots l WHERE l.customer_id = w.customer_id AND l.currency = 'COIN'))`,
customers).Scan(&broken).Error)
assert.Zero(t, broken)
}
func discrepanciesFor(report *WalletMigrationReport, customers []uuid.UUID) []WalletMigrationDiscrepancy {
mine := map[uuid.UUID]bool{}
for _, c := range customers {
mine[c] = true
}
var out []WalletMigrationDiscrepancy
for _, d := range report.Discrepancies {
if mine[d.CustomerID] {
out = append(out, d)
}
}
return out
}
+237
View File
@@ -0,0 +1,237 @@
package processor
import (
"context"
"fmt"
"os"
"sync"
"testing"
"time"
"github.com/google/uuid"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"gorm.io/driver/postgres"
"gorm.io/gorm"
"gorm.io/gorm/logger"
"apskel-pos-be/internal/constants"
"apskel-pos-be/internal/models"
"apskel-pos-be/internal/repository"
)
// fixedOrganizationSettings serves the same organization settings to every caller.
type fixedOrganizationSettings struct {
s models.OrganizationLoyaltySettings
}
func (f fixedOrganizationSettings) Organization(context.Context, uuid.UUID) (*models.OrganizationLoyaltySettings, error) {
s := f.s
return &s, nil
}
// walletMoveDB opens TEST_DATABASE_URL and creates an organization with two customers,
// removed again when the test ends. See internal/repository/wallet_repository_test.go.
func walletMoveDB(t *testing.T) (db *gorm.DB, org, a, b uuid.UUID) {
t.Helper()
dsn := os.Getenv("TEST_DATABASE_URL")
if dsn == "" {
t.Skip("TEST_DATABASE_URL not set")
}
db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{Logger: logger.Default.LogMode(logger.Silent)})
require.NoError(t, err)
org, a, b = uuid.New(), uuid.New(), uuid.New()
phoneA, phoneB := "08"+a.String()[:10], "08"+b.String()[:10]
require.NoError(t, db.Exec(`INSERT INTO organizations (id, name, plan_type) VALUES (?, 'wallet move test', 'basic')`, org).Error)
require.NoError(t, db.Exec(`INSERT INTO customers (id, organization_id, name, phone_number) VALUES (?, ?, 'Anita', ?), (?, ?, 'Budi Santoso', ?)`,
a, org, phoneA, b, org, phoneB).Error)
customers := []uuid.UUID{a, b}
t.Cleanup(func() {
db.Exec(`DELETE FROM wallet_lot_allocations WHERE lot_id IN (SELECT id FROM wallet_lots WHERE customer_id IN ?)`, customers)
db.Exec(`DELETE FROM wallet_lots WHERE customer_id IN ? AND origin_lot_id IS NOT NULL`, customers)
db.Exec(`DELETE FROM wallet_lots WHERE customer_id IN ?`, customers)
db.Exec(`DELETE FROM wallet_transactions WHERE customer_id IN ?`, customers)
db.Exec(`DELETE FROM customer_wallets WHERE customer_id IN ?`, customers)
db.Exec(`DELETE FROM customers WHERE id IN ?`, customers)
db.Exec(`DELETE FROM organizations WHERE id = ?`, org)
})
return db, org, a, b
}
func TestWalletExchange_AgainstPostgres(t *testing.T) {
db, _, a, _ := walletMoveDB(t)
wallet := NewWalletProcessor(repository.NewWalletRepository(db))
txm := repository.NewTxManager(db)
settings := fixedOrganizationSettings{models.OrganizationLoyaltySettings{
Exchange: models.LoyaltyExchangeSettings{CoinAmount: 10, PointAmount: 3},
}}
p := NewWalletExchangeProcessor(repository.NewWalletMoveRepository(db), settings, repository.NewWalletQueryRepository(db),
&movePinFake{good: "482913"}, wallet, txm)
expiry := time.Now().Add(24 * time.Hour).Truncate(time.Second)
require.NoError(t, txm.WithTransaction(context.Background(), func(ctx context.Context) error {
in := earn(a, 30, &expiry)
in.Currency = constants.WalletCurrencyCoin
_, err := wallet.Credit(ctx, in)
return err
}))
res, err := p.Exchange(context.Background(), a, 20, "482913", "db-key", models.CustomerPinRequestInfo{})
require.NoError(t, err)
assert.Equal(t, int64(6), res.Points)
assert.Equal(t, int64(10), res.CoinBalance)
assert.Equal(t, int64(6), res.PointBalance)
require.Len(t, res.Lots, 1)
require.NotNil(t, res.Lots[0].ExpiresAt)
assert.True(t, res.Lots[0].ExpiresAt.Equal(expiry))
// The retry reads the frozen rate back out of JSONB and replays.
again, err := p.Exchange(context.Background(), a, 20, "482913", "db-key", models.CustomerPinRequestInfo{})
require.NoError(t, err)
assert.True(t, again.Replayed)
assert.Equal(t, int64(6), again.Points)
var rows int64
require.NoError(t, db.Raw(`SELECT COUNT(*) FROM wallet_transactions WHERE group_id = ?`, res.GroupID).Scan(&rows).Error)
assert.Equal(t, int64(2), rows)
}
// Transfers in both directions at once must not deadlock: both lock the two wallets
// in customer_id order. Every one of them lands, and the totals still reconcile.
func TestWalletTransfer_BothWaysAtOnceAgainstPostgres(t *testing.T) {
db, _, a, b := walletMoveDB(t)
wallet := NewWalletProcessor(repository.NewWalletRepository(db))
txm := repository.NewTxManager(db)
moves := repository.NewWalletMoveRepository(db)
settings := fixedOrganizationSettings{models.OrganizationLoyaltySettings{
Transfer: models.LoyaltyTransferSettings{Enabled: true, MinAmount: 1},
}}
p := NewWalletTransferProcessor(moves, settings, repository.NewWalletQueryRepository(db), &movePinFake{good: "482913"}, wallet, txm, nil)
expiry := time.Now().Add(24 * time.Hour).Truncate(time.Second)
require.NoError(t, txm.WithTransaction(context.Background(), func(ctx context.Context) error {
if _, err := wallet.Credit(ctx, earn(a, 100, &expiry)); err != nil {
return err
}
_, err := wallet.Credit(ctx, earn(b, 100, nil))
return err
}))
phone := func(id uuid.UUID) string { return "08" + id.String()[:10] }
const rounds = 10
errs := make(chan error, 2*rounds)
var wg sync.WaitGroup
for i := 0; i < rounds; i++ {
for _, pair := range [][2]uuid.UUID{{a, b}, {b, a}} {
wg.Add(1)
go func(from, to uuid.UUID, i int) {
defer wg.Done()
_, err := p.Transfer(context.Background(), from, sendPoints(1, phone(to)), "482913", fmt.Sprintf("race-%d", i), models.CustomerPinRequestInfo{})
errs <- err
}(pair[0], pair[1], i)
}
}
wg.Wait()
close(errs)
for err := range errs {
assert.NoError(t, err)
}
var balances []int64
require.NoError(t, db.Raw(`SELECT point_balance FROM customer_wallets WHERE customer_id IN ? ORDER BY point_balance`, []uuid.UUID{a, b}).Scan(&balances).Error)
assert.Equal(t, []int64{100, 100}, balances)
// B's lots that came from A keep A's expiry to the second.
var mismatched int64
require.NoError(t, db.Raw(`
SELECT COUNT(*) FROM wallet_lots l JOIN wallet_lots o ON o.id = l.origin_lot_id
WHERE l.customer_id = ? AND o.customer_id = ? AND l.expires_at IS DISTINCT FROM o.expires_at`, b, a).Scan(&mismatched).Error)
assert.Zero(t, mismatched)
require.NoError(t, txm.WithTransaction(context.Background(), func(ctx context.Context) error {
sent, err := moves.TransferredOutSince(ctx, a, constants.WalletCurrencyPoint, startOfWalletDay(time.Now()))
assert.Equal(t, int64(rounds), sent)
return err
}))
}
// The example of §8 against Postgres: B's payment of 30 traces back to A's #ORD-1.
func TestWalletTrace_AgainstPostgres(t *testing.T) {
db, org, a, b := walletMoveDB(t)
wallet := NewWalletProcessor(repository.NewWalletRepository(db))
txm := repository.NewTxManager(db)
settings := fixedOrganizationSettings{models.OrganizationLoyaltySettings{
Transfer: models.LoyaltyTransferSettings{Enabled: true, MinAmount: 1},
}}
transfers := NewWalletTransferProcessor(repository.NewWalletMoveRepository(db), settings, repository.NewWalletQueryRepository(db), &movePinFake{good: "482913"}, wallet, txm, nil)
dec, jan := time.Now().Add(30*24*time.Hour), time.Now().Add(60*24*time.Hour)
ord1 := earn(a, 100, &dec)
ord1.Description = "Belanja #ORD-1"
require.NoError(t, txm.WithTransaction(context.Background(), func(ctx context.Context) error {
if _, err := wallet.Credit(ctx, ord1); err != nil {
return err
}
_, err := wallet.Credit(ctx, earn(a, 50, &jan))
return err
}))
_, err := transfers.Transfer(context.Background(), a, sendPoints(120, "08"+b.String()[:10]), "482913", "trace", models.CustomerPinRequestInfo{})
require.NoError(t, err)
var payment *WalletResult
require.NoError(t, txm.WithTransaction(context.Background(), func(ctx context.Context) error {
payment, err = wallet.Debit(ctx, pay(b, 30))
return err
}))
trace, err := NewWalletTraceProcessor(repository.NewWalletTraceRepository(db)).Trace(context.Background(), org, payment.Transaction.ID)
require.NoError(t, err)
require.Len(t, trace.Lots, 1)
chain := trace.Lots[0].Chain
require.Len(t, chain, 2)
assert.Equal(t, constants.WalletTxTypeTransferIn, chain[0].Source.Type)
assert.Equal(t, "Anita", chain[1].Source.Customer.Name)
assert.Equal(t, ord1.ReferenceID, chain[1].Source.ReferenceID)
_, err = NewWalletTraceProcessor(repository.NewWalletTraceRepository(db)).Trace(context.Background(), uuid.New(), payment.Transaction.ID)
assert.ErrorIs(t, err, repository.ErrWalletTransactionNotFound)
}
// Two instances of the expiry job at once expire each lot exactly once (PC-503).
func TestWalletExpiry_TwoInstancesAgainstPostgres(t *testing.T) {
db, _, a, b := walletMoveDB(t)
wallet := NewWalletProcessor(repository.NewWalletRepository(db))
txm := repository.NewTxManager(db)
past := time.Now().Add(-time.Hour)
require.NoError(t, txm.WithTransaction(context.Background(), func(ctx context.Context) error {
for i := 0; i < 5; i++ {
for _, c := range []uuid.UUID{a, b} {
if _, err := wallet.Credit(ctx, earn(c, 10, &past)); err != nil {
return err
}
}
}
return nil
}))
var wg sync.WaitGroup
counts := make([]int, 2)
for i := range counts {
wg.Add(1)
go func(i int) {
defer wg.Done()
p := NewWalletExpiryProcessor(repository.NewWalletExpiryRepository(db), fixedOrganizationSettings{}, wallet, txm, nil)
n, err := p.ExpireDue(context.Background())
assert.NoError(t, err)
counts[i] = n
}(i)
}
wg.Wait()
assert.Equal(t, 10, counts[0]+counts[1], "every lot once, between them")
var expires, left int64
require.NoError(t, db.Raw(`SELECT COUNT(*) FROM wallet_transactions WHERE customer_id IN ? AND type = 'EXPIRE'`, []uuid.UUID{a, b}).Scan(&expires).Error)
require.NoError(t, db.Raw(`SELECT COALESCE(SUM(point_balance), 0) FROM customer_wallets WHERE customer_id IN ?`, []uuid.UUID{a, b}).Scan(&left).Error)
assert.Equal(t, int64(10), expires)
assert.Zero(t, left)
}
+583
View File
@@ -0,0 +1,583 @@
package processor
import (
"context"
"errors"
"fmt"
"strings"
"time"
"github.com/google/uuid"
"apskel-pos-be/internal/constants"
"apskel-pos-be/internal/entities"
"apskel-pos-be/internal/repository"
)
var (
// ErrWalletInvalidEntry wraps every rejection of an entry that breaks the rules in
// docs/prd-point-coin.md §8.1. The database enforces most of them too; checking
// here first gives callers a readable error instead of a constraint name.
ErrWalletInvalidEntry = errors.New("wallet: invalid entry")
// ErrWalletIdempotencyConflict means an idempotency key was reused for a different
// operation. Retrying the same operation with the same key is not a conflict.
ErrWalletIdempotencyConflict = errors.New("wallet: idempotency key already used for a different operation")
)
// WalletEntry is what every ledger row needs, whichever way it moves the balance.
// Which of the optional fields a type requires is listed in §8.1.
type WalletEntry struct {
// Optional. Set it when another row must reference this one before it exists, as
// the two rows of an exchange or a transfer do.
TransactionID uuid.UUID
CustomerID uuid.UUID
Currency string
Type string
// Always positive: Credit adds it, Debit takes it away.
Amount int64
ReferenceType string
ReferenceID uuid.UUID
GroupID *uuid.UUID
CounterpartyCustomerID *uuid.UUID
ReversesTransactionID *uuid.UUID
OutletID *uuid.UUID
CreatedByUser *uuid.UUID
Reason *string
Description string
Metadata entities.Metadata
// Optional. A retry with the same key returns the first result without moving
// anything again.
IdempotencyKey string
}
// WalletLotInput is one lot a credit creates.
type WalletLotInput struct {
Amount int64
// Nil means the lot never expires.
ExpiresAt *time.Time
// The lot this one was carried over from, for transfers, exchanges and refunds.
OriginLotID *uuid.UUID
}
type WalletCreditInput struct {
WalletEntry
// How the credit is split into lots. Their amounts must add up to Amount. Leave
// empty for a single lot that never expires.
Lots []WalletLotInput
}
type WalletDebitInput struct {
WalletEntry
// Lots to draw from first, in this order, before falling back to the K9 order.
// A reversal names the lots its EARN created (F10), and the expiry job names the
// lot that expired. These lots are used even if they have already expired.
PreferredLotIDs []uuid.UUID
}
// WalletAllocation is how much a debit took from one lot. It carries the lot's
// expiry, so a transfer or exchange can give the receiving lot the same expiry (K9).
type WalletAllocation struct {
LotID uuid.UUID
Amount int64
ExpiresAt *time.Time
}
type WalletResult struct {
// Nil only when DebitUpTo found nothing to take.
Transaction *entities.WalletTransaction
// The lots a credit created.
Lots []entities.WalletLot
// The lots a debit drew from, in the order they were used.
Allocations []WalletAllocation
// What DebitUpTo could not take because the balance ran out.
Shortfall int64
// True when the idempotency key had already been used and nothing moved.
Replayed bool
}
// CarryOver turns a debit's allocations into lots for the receiving side of a
// transfer or exchange. Each lot keeps the expiry of the lot it came from and points
// back at it, so a balance cannot be kept alive by moving it around (K9).
func (r *WalletResult) CarryOver() []WalletLotInput {
lots := make([]WalletLotInput, 0, len(r.Allocations))
for _, a := range r.Allocations {
lotID := a.LotID
lots = append(lots, WalletLotInput{Amount: a.Amount, ExpiresAt: a.ExpiresAt, OriginLotID: &lotID})
}
return lots
}
// WalletProcessor is the only code allowed to change a wallet balance. Every change
// writes the balance, the ledger row and the lots or allocations together, which is
// what keeps SUM(ledger) = balance = SUM(lot remaining) (§7.5).
//
// Every method must run inside a transaction from TxManager, and the repository
// refuses otherwise. Each method locks the customer's wallet itself, so a single-wallet
// caller needs nothing more. A caller touching two wallets, such as a transfer, must
// call LockWallets first so the locks are always taken in the same order.
type WalletProcessor struct {
repo repository.WalletRepository
now func() time.Time
}
func NewWalletProcessor(repo repository.WalletRepository) *WalletProcessor {
return &WalletProcessor{repo: repo, now: time.Now}
}
// LockWallet locks one customer's wallet, creating it if needed. Credit and Debit do
// this themselves; call it when something must be read under the lock first.
func (p *WalletProcessor) LockWallet(ctx context.Context, customerID uuid.UUID) error {
_, err := p.repo.LockWallet(ctx, customerID)
return err
}
// LockWallets locks two customers' wallets in a fixed order. Call it before touching
// both wallets in one transaction.
func (p *WalletProcessor) LockWallets(ctx context.Context, a, b uuid.UUID) error {
_, _, err := p.repo.LockWallets(ctx, a, b)
return err
}
// FindTransaction returns the row written under an idempotency key, or nil when the
// key is new. Read it under the wallet lock: a flow that writes several rows uses it
// to recognise a retry before checking limits the first attempt already counts in.
func (p *WalletProcessor) FindTransaction(ctx context.Context, idempotencyKey string) (*entities.WalletTransaction, error) {
return p.repo.GetTransactionByIdempotencyKey(ctx, idempotencyKey)
}
// ExpireLot takes what is left in a lot whose expiry has passed at asOf, as an EXPIRE
// row pointing at the lot (F12). It locks the wallet before reading the lot again, so
// it never races a payment for the same balance, and the key expire:{lot_id} makes a
// second run, on this instance or another, take nothing more. describe gives the
// row's description for the amount taken. It returns nil when
// there is nothing to take: the lot is empty, not due, or already expired.
func (p *WalletProcessor) ExpireLot(ctx context.Context, lotID uuid.UUID, describe func(amount int64) string, asOf time.Time) (*WalletResult, error) {
lot, err := p.getLot(ctx, lotID)
if err != nil {
return nil, err
}
if _, err := p.repo.LockWallet(ctx, lot.CustomerID); err != nil {
return nil, err
}
// Read again under the lock: a payment may have used it up meanwhile.
if lot, err = p.getLot(ctx, lotID); err != nil {
return nil, err
}
if lot.RemainingAmount == 0 || lot.ExpiresAt == nil || lot.ExpiresAt.After(asOf) {
return nil, nil
}
return p.Debit(ctx, WalletDebitInput{
WalletEntry: WalletEntry{
CustomerID: lot.CustomerID,
Currency: lot.Currency,
Type: constants.WalletTxTypeExpire,
Amount: lot.RemainingAmount,
ReferenceType: constants.WalletRefTypeLot,
ReferenceID: lot.ID,
Description: describe(lot.RemainingAmount),
Metadata: entities.Metadata{"expires_at": lot.ExpiresAt.UTC().Format(time.RFC3339)},
IdempotencyKey: "expire:" + lot.ID.String(),
},
// Exactly what the lot holds, from the lot itself, even though it has expired.
PreferredLotIDs: []uuid.UUID{lot.ID},
})
}
func (p *WalletProcessor) getLot(ctx context.Context, lotID uuid.UUID) (*entities.WalletLot, error) {
lots, err := p.repo.GetLotsByIDs(ctx, []uuid.UUID{lotID})
if err != nil {
return nil, err
}
if len(lots) == 0 {
return nil, fmt.Errorf("%w: lot %s does not exist", ErrWalletInvalidEntry, lotID)
}
return &lots[0], nil
}
// Credit adds Amount to the wallet and creates its lots.
func (p *WalletProcessor) Credit(ctx context.Context, in WalletCreditInput) (*WalletResult, error) {
if err := validateWalletEntry(&in.WalletEntry, true); err != nil {
return nil, err
}
lots := in.Lots
if len(lots) == 0 {
lots = []WalletLotInput{{Amount: in.Amount}}
}
var total int64
for _, lot := range lots {
if lot.Amount <= 0 {
return nil, fmt.Errorf("%w: lot amount must be positive, got %d", ErrWalletInvalidEntry, lot.Amount)
}
total += lot.Amount
}
if total != in.Amount {
return nil, fmt.Errorf("%w: lots add up to %d, not %d", ErrWalletInvalidEntry, total, in.Amount)
}
wallet, err := p.repo.LockWallet(ctx, in.CustomerID)
if err != nil {
return nil, err
}
if replay, err := p.replay(ctx, &in.WalletEntry, true, true); replay != nil || err != nil {
return replay, err
}
balance, err := p.repo.AddBalance(ctx, in.CustomerID, in.Currency, in.Amount)
if err != nil {
return nil, err
}
walletTx := newWalletTransaction(wallet, &in.WalletEntry, in.Amount, balance, nil)
if err := p.repo.CreateTransaction(ctx, walletTx); err != nil {
return nil, fmt.Errorf("failed to create wallet transaction: %w", err)
}
result := &WalletResult{Transaction: walletTx}
for _, lotIn := range lots {
lot := entities.WalletLot{
OrganizationID: wallet.OrganizationID,
CustomerID: in.CustomerID,
Currency: in.Currency,
SourceTransactionID: walletTx.ID,
OriginLotID: lotIn.OriginLotID,
OriginalAmount: lotIn.Amount,
RemainingAmount: lotIn.Amount,
ExpiresAt: lotIn.ExpiresAt,
}
if err := p.repo.CreateLot(ctx, &lot); err != nil {
return nil, fmt.Errorf("failed to create wallet lot: %w", err)
}
result.Lots = append(result.Lots, lot)
}
return result, nil
}
// Debit takes exactly Amount from the wallet, or nothing at all with
// repository.ErrWalletInsufficientBalance if the usable balance is short.
func (p *WalletProcessor) Debit(ctx context.Context, in WalletDebitInput) (*WalletResult, error) {
return p.debit(ctx, in, false)
}
// DebitUpTo takes as much of Amount as the wallet has and reports the rest as
// Shortfall. It is for reversing earnings the customer has already spent (F10, Q3).
// When there is nothing to take, no ledger row is written and Transaction is nil;
// such a call leaves no trace, so a retry with the same key takes whatever the
// balance holds by then.
func (p *WalletProcessor) DebitUpTo(ctx context.Context, in WalletDebitInput) (*WalletResult, error) {
return p.debit(ctx, in, true)
}
func (p *WalletProcessor) debit(ctx context.Context, in WalletDebitInput, upTo bool) (*WalletResult, error) {
if err := validateWalletEntry(&in.WalletEntry, false); err != nil {
return nil, err
}
wallet, err := p.repo.LockWallet(ctx, in.CustomerID)
if err != nil {
return nil, err
}
// DebitUpTo may have taken less than asked, so the amount cannot be compared.
if replay, err := p.replay(ctx, &in.WalletEntry, false, !upTo); replay != nil || err != nil {
return replay, err
}
lots, err := p.spendableLots(ctx, &in)
if err != nil {
return nil, err
}
var available int64
for _, lot := range lots {
available += lot.RemainingAmount
}
take := in.Amount
if available < take {
if !upTo {
return nil, repository.ErrWalletInsufficientBalance
}
take = available
}
result := &WalletResult{Shortfall: in.Amount - take}
if take == 0 {
return result, nil
}
var metadata entities.Metadata
if upTo {
metadata = entities.Metadata{"requested_amount": in.Amount, "shortfall": result.Shortfall}
}
balance, err := p.repo.AddBalance(ctx, in.CustomerID, in.Currency, -take)
if err != nil {
return nil, err
}
walletTx := newWalletTransaction(wallet, &in.WalletEntry, -take, balance, metadata)
if err := p.repo.CreateTransaction(ctx, walletTx); err != nil {
return nil, fmt.Errorf("failed to create wallet transaction: %w", err)
}
result.Transaction = walletTx
var allocations []entities.WalletLotAllocation
remaining := take
for _, lot := range lots {
if remaining == 0 {
break
}
amount := min(lot.RemainingAmount, remaining)
remaining -= amount
if err := p.repo.ConsumeLot(ctx, lot.ID, amount); err != nil {
return nil, err
}
allocations = append(allocations, entities.WalletLotAllocation{TransactionID: walletTx.ID, LotID: lot.ID, Amount: amount})
result.Allocations = append(result.Allocations, WalletAllocation{LotID: lot.ID, Amount: amount, ExpiresAt: lot.ExpiresAt})
}
if err := p.repo.CreateAllocations(ctx, allocations); err != nil {
return nil, fmt.Errorf("failed to create wallet lot allocations: %w", err)
}
return result, nil
}
// spendableLots returns the lots a debit may draw from, in the order it draws: the
// preferred lots first, then the unexpired lots in K9 order.
func (p *WalletProcessor) spendableLots(ctx context.Context, in *WalletDebitInput) ([]entities.WalletLot, error) {
var lots []entities.WalletLot
preferred := make(map[uuid.UUID]bool, len(in.PreferredLotIDs))
if len(in.PreferredLotIDs) > 0 {
found, err := p.repo.GetLotsByIDs(ctx, in.PreferredLotIDs)
if err != nil {
return nil, err
}
byID := make(map[uuid.UUID]entities.WalletLot, len(found))
for _, lot := range found {
byID[lot.ID] = lot
}
for _, id := range in.PreferredLotIDs {
lot, ok := byID[id]
if !ok || lot.CustomerID != in.CustomerID || lot.Currency != in.Currency {
return nil, fmt.Errorf("%w: lot %s is not a %s lot of this customer", ErrWalletInvalidEntry, id, in.Currency)
}
if preferred[id] {
continue
}
preferred[id] = true
if lot.RemainingAmount > 0 {
lots = append(lots, lot)
}
}
}
active, err := p.repo.ListActiveLots(ctx, in.CustomerID, in.Currency, p.now())
if err != nil {
return nil, err
}
for _, lot := range active {
if !preferred[lot.ID] {
lots = append(lots, lot)
}
}
return lots, nil
}
// replay returns the first result for an idempotency key that has already been used,
// or nil when the key is new. It runs after the wallet lock, so a concurrent request
// with the same key has either committed its row or not started.
func (p *WalletProcessor) replay(ctx context.Context, in *WalletEntry, credit, compareAmount bool) (*WalletResult, error) {
if in.IdempotencyKey == "" {
return nil, nil
}
walletTx, err := p.repo.GetTransactionByIdempotencyKey(ctx, in.IdempotencyKey)
if err != nil || walletTx == nil {
return nil, err
}
sameDirection := (walletTx.Amount > 0) == credit
sameAmount := !compareAmount || abs(walletTx.Amount) == in.Amount
if walletTx.CustomerID != in.CustomerID || walletTx.Currency != in.Currency ||
walletTx.Type != in.Type || !sameDirection || !sameAmount {
return nil, ErrWalletIdempotencyConflict
}
result := &WalletResult{Transaction: walletTx, Replayed: true}
if credit {
result.Lots, err = p.repo.ListLotsBySourceTransaction(ctx, walletTx.ID)
return result, err
}
// JSON numbers come back from JSONB as float64.
switch shortfall := walletTx.Metadata["shortfall"].(type) {
case float64:
result.Shortfall = int64(shortfall)
case int64:
result.Shortfall = shortfall
}
allocations, err := p.repo.ListAllocationsByTransaction(ctx, walletTx.ID)
if err != nil {
return nil, err
}
ids := make([]uuid.UUID, 0, len(allocations))
for _, a := range allocations {
ids = append(ids, a.LotID)
}
lots, err := p.repo.GetLotsByIDs(ctx, ids)
if err != nil {
return nil, err
}
expiry := make(map[uuid.UUID]*time.Time, len(lots))
for _, lot := range lots {
expiry[lot.ID] = lot.ExpiresAt
}
for _, a := range allocations {
result.Allocations = append(result.Allocations, WalletAllocation{LotID: a.LotID, Amount: a.Amount, ExpiresAt: expiry[a.LotID]})
}
return result, nil
}
func newWalletTransaction(wallet *entities.CustomerWallet, in *WalletEntry, amount, balance int64, extra entities.Metadata) *entities.WalletTransaction {
metadata := entities.Metadata{}
for k, v := range in.Metadata {
metadata[k] = v
}
for k, v := range extra {
metadata[k] = v
}
var key *string
if in.IdempotencyKey != "" {
k := in.IdempotencyKey
key = &k
}
return &entities.WalletTransaction{
ID: in.TransactionID,
OrganizationID: wallet.OrganizationID,
CustomerID: in.CustomerID,
Currency: in.Currency,
Type: in.Type,
Amount: amount,
BalanceAfter: balance,
GroupID: in.GroupID,
ReferenceType: in.ReferenceType,
ReferenceID: in.ReferenceID,
CounterpartyCustomerID: in.CounterpartyCustomerID,
ReversesTransactionID: in.ReversesTransactionID,
OutletID: in.OutletID,
CreatedByUser: in.CreatedByUser,
Reason: in.Reason,
Description: in.Description,
Metadata: metadata,
IdempotencyKey: key,
}
}
// walletTypeRule is one row of §8.1.
type walletTypeRule struct {
credit, debit bool
currency string // empty: either currency
referenceTypes []string
needsOutlet bool
needsReverses bool
needsGroup bool
needsCounter bool
needsActor bool
}
var walletTypeRules = map[string]walletTypeRule{
constants.WalletTxTypeEarn: {credit: true, referenceTypes: []string{constants.WalletRefTypeOrder}, needsOutlet: true},
constants.WalletTxTypeEarnReversal: {debit: true, referenceTypes: []string{constants.WalletRefTypeOrder}, needsOutlet: true, needsReverses: true},
constants.WalletTxTypePayment: {debit: true, currency: constants.WalletCurrencyPoint, referenceTypes: []string{constants.WalletRefTypePayment}, needsOutlet: true},
constants.WalletTxTypePaymentRefund: {credit: true, currency: constants.WalletCurrencyPoint, referenceTypes: []string{constants.WalletRefTypePayment}, needsOutlet: true, needsReverses: true},
constants.WalletTxTypeExchangeOut: {debit: true, currency: constants.WalletCurrencyCoin, referenceTypes: []string{constants.WalletRefTypeWalletTx}, needsGroup: true},
constants.WalletTxTypeExchangeIn: {credit: true, currency: constants.WalletCurrencyPoint, referenceTypes: []string{constants.WalletRefTypeWalletTx}, needsGroup: true},
constants.WalletTxTypeTransferOut: {debit: true, referenceTypes: []string{constants.WalletRefTypeWalletTx}, needsGroup: true, needsCounter: true},
constants.WalletTxTypeTransferIn: {credit: true, referenceTypes: []string{constants.WalletRefTypeWalletTx}, needsGroup: true, needsCounter: true},
constants.WalletTxTypeGameSpend: {debit: true, currency: constants.WalletCurrencyCoin, referenceTypes: []string{constants.WalletRefTypeGamePlay}},
constants.WalletTxTypeExpire: {debit: true, referenceTypes: []string{constants.WalletRefTypeLot}},
constants.WalletTxTypeAdjustment: {credit: true, debit: true, referenceTypes: []string{constants.WalletRefTypeUser}, needsActor: true},
constants.WalletTxTypeMigration: {credit: true, referenceTypes: []string{constants.WalletRefTypeLegacyPoints, constants.WalletRefTypeLegacyTokens}},
constants.WalletTxTypeRewardRedeem: {debit: true, currency: constants.WalletCurrencyPoint, referenceTypes: []string{constants.WalletRefTypeRewardRedemption}},
}
func validateWalletEntry(in *WalletEntry, credit bool) error {
invalid := func(format string, args ...any) error {
return fmt.Errorf("%w: %s", ErrWalletInvalidEntry, fmt.Sprintf(format, args...))
}
rule, ok := walletTypeRules[in.Type]
if !ok {
return invalid("unknown type %q", in.Type)
}
if credit && !rule.credit {
return invalid("%s cannot add to a balance", in.Type)
}
if !credit && !rule.debit {
return invalid("%s cannot take from a balance", in.Type)
}
if in.CustomerID == uuid.Nil {
return invalid("customer is required")
}
if !constants.IsValidWalletCurrency(in.Currency) {
return invalid("unknown currency %q", in.Currency)
}
if rule.currency != "" && in.Currency != rule.currency {
return invalid("%s must be in %s", in.Type, rule.currency)
}
if in.Amount <= 0 {
return invalid("amount must be positive, got %d", in.Amount)
}
if !containsString(rule.referenceTypes, in.ReferenceType) {
return invalid("%s must reference %s, got %q", in.Type, strings.Join(rule.referenceTypes, " or "), in.ReferenceType)
}
if in.ReferenceID == uuid.Nil {
return invalid("reference id is required")
}
if strings.TrimSpace(in.Description) == "" {
return invalid("description is required")
}
if rule.needsOutlet && isNilID(in.OutletID) {
return invalid("%s requires an outlet", in.Type)
}
if rule.needsReverses && isNilID(in.ReversesTransactionID) {
return invalid("%s requires the transaction it reverses", in.Type)
}
if rule.needsGroup && isNilID(in.GroupID) {
return invalid("%s requires a group id", in.Type)
}
if rule.needsCounter {
if isNilID(in.CounterpartyCustomerID) {
return invalid("%s requires a counterparty", in.Type)
}
if *in.CounterpartyCustomerID == in.CustomerID {
return invalid("%s cannot go to the same customer", in.Type)
}
}
if rule.needsActor {
if isNilID(in.CreatedByUser) {
return invalid("%s requires the admin who made it", in.Type)
}
if in.Reason == nil || strings.TrimSpace(*in.Reason) == "" {
return invalid("%s requires a reason", in.Type)
}
}
return nil
}
func isNilID(id *uuid.UUID) bool {
return id == nil || *id == uuid.Nil
}
func containsString(values []string, v string) bool {
for _, value := range values {
if value == v {
return true
}
}
return false
}
func abs(v int64) int64 {
if v < 0 {
return -v
}
return v
}
@@ -0,0 +1,142 @@
package processor
import (
"context"
"os"
"testing"
"time"
"github.com/google/uuid"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"gorm.io/driver/postgres"
"gorm.io/gorm"
"gorm.io/gorm/logger"
"apskel-pos-be/internal/constants"
"apskel-pos-be/internal/repository"
)
// Runs the engine against Postgres, to show the rows it writes pass the database
// constraints and reconcile the way §7.5 requires. Needs TEST_DATABASE_URL pointing
// at a migrated database; see internal/repository/wallet_repository_test.go.
func TestWalletProcessor_AgainstPostgres(t *testing.T) {
dsn := os.Getenv("TEST_DATABASE_URL")
if dsn == "" {
t.Skip("TEST_DATABASE_URL not set")
}
db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{Logger: logger.Default.LogMode(logger.Silent)})
require.NoError(t, err)
org, a, b := uuid.New(), uuid.New(), uuid.New()
require.NoError(t, db.Exec(`INSERT INTO organizations (id, name, plan_type) VALUES (?, 'wallet test', 'basic')`, org).Error)
require.NoError(t, db.Exec(`INSERT INTO customers (id, organization_id, name) VALUES (?, ?, 'A'), (?, ?, 'B')`, a, org, b, org).Error)
customers := []uuid.UUID{a, b}
t.Cleanup(func() {
db.Exec(`DELETE FROM wallet_lot_allocations WHERE lot_id IN (SELECT id FROM wallet_lots WHERE customer_id IN ?)`, customers)
db.Exec(`DELETE FROM wallet_lots WHERE customer_id IN ?`, customers)
db.Exec(`DELETE FROM wallet_transactions WHERE customer_id IN ?`, customers)
db.Exec(`DELETE FROM customer_wallets WHERE customer_id IN ?`, customers)
db.Exec(`DELETE FROM customers WHERE id IN ?`, customers)
db.Exec(`DELETE FROM organizations WHERE id = ?`, org)
})
p := NewWalletProcessor(repository.NewWalletRepository(db))
txm := repository.NewTxManager(db)
now := time.Now()
inTx := func(fn func(ctx context.Context) error) {
t.Helper()
require.NoError(t, txm.WithTransaction(context.Background(), fn))
}
// Without a transaction nothing moves.
_, err = p.Credit(context.Background(), earn(a, 10, nil))
assert.ErrorIs(t, err, repository.ErrWalletTxRequired)
var earned *WalletResult
inTx(func(ctx context.Context) error {
soon := now.Add(time.Hour)
earned, err = p.Credit(ctx, earn(a, 100, &soon))
require.NoError(t, err)
_, err = p.Credit(ctx, earn(a, 50, nil))
return err
})
// Transfer 120 from A to B, spanning both of A's lots.
inTx(func(ctx context.Context) error {
require.NoError(t, p.LockWallets(ctx, a, b))
group, outID, inID := uuid.New(), uuid.New(), uuid.New()
out, err := p.Debit(ctx, WalletDebitInput{WalletEntry: WalletEntry{
TransactionID: outID, CustomerID: a, Currency: constants.WalletCurrencyPoint,
Type: constants.WalletTxTypeTransferOut, Amount: 120,
ReferenceType: constants.WalletRefTypeWalletTx, ReferenceID: inID,
GroupID: &group, CounterpartyCustomerID: &b, Description: "Transfer ke B",
}})
require.NoError(t, err)
_, err = p.Credit(ctx, WalletCreditInput{
WalletEntry: WalletEntry{
TransactionID: inID, CustomerID: b, Currency: constants.WalletCurrencyPoint,
Type: constants.WalletTxTypeTransferIn, Amount: 120,
ReferenceType: constants.WalletRefTypeWalletTx, ReferenceID: outID,
GroupID: &group, CounterpartyCustomerID: &a, Description: "Transfer dari A",
},
Lots: out.CarryOver(),
})
return err
})
// Reversing the 100 earned leaves A 30 short. The retry reads the shortfall back
// out of JSONB and takes nothing more.
rev := reversal(a, 100, earned)
rev.IdempotencyKey = "reverse:" + earned.Transaction.ID.String()
var first, second *WalletResult
inTx(func(ctx context.Context) error {
first, err = p.DebitUpTo(ctx, rev)
return err
})
inTx(func(ctx context.Context) error {
second, err = p.DebitUpTo(ctx, rev)
return err
})
assert.Equal(t, int64(-30), first.Transaction.Amount)
assert.Equal(t, int64(70), first.Shortfall)
assert.True(t, second.Replayed)
assert.Equal(t, int64(70), second.Shortfall)
assert.Equal(t, first.Transaction.ID, second.Transaction.ID)
// Overdraw fails and rolls back cleanly.
err = txm.WithTransaction(context.Background(), func(ctx context.Context) error {
_, err := p.Debit(ctx, pay(b, 121))
return err
})
assert.ErrorIs(t, err, repository.ErrWalletInsufficientBalance)
var balances []struct {
CustomerID uuid.UUID
PointBalance int64
}
require.NoError(t, db.Raw(`SELECT customer_id, point_balance FROM customer_wallets WHERE customer_id IN ?`, customers).Scan(&balances).Error)
got := map[uuid.UUID]int64{}
for _, row := range balances {
got[row.CustomerID] = row.PointBalance
}
assert.Equal(t, map[uuid.UUID]int64{a: 0, b: 120}, got)
// §7.5, straight from the tables.
var broken []string
require.NoError(t, db.Raw(`
SELECT 'wallet ' || w.customer_id FROM customer_wallets w
WHERE w.customer_id IN ? AND (
w.point_balance <> (SELECT COALESCE(SUM(amount), 0) FROM wallet_transactions t WHERE t.customer_id = w.customer_id AND t.currency = 'POINT')
OR w.point_balance <> (SELECT COALESCE(SUM(remaining_amount), 0) FROM wallet_lots l WHERE l.customer_id = w.customer_id AND l.currency = 'POINT'))
UNION ALL
SELECT 'lot ' || l.id FROM wallet_lots l
WHERE l.customer_id IN ? AND l.original_amount - l.remaining_amount
<> (SELECT COALESCE(SUM(amount), 0) FROM wallet_lot_allocations a WHERE a.lot_id = l.id)
UNION ALL
SELECT 'debit ' || t.id FROM wallet_transactions t
WHERE t.customer_id IN ? AND t.amount < 0
AND -t.amount <> (SELECT COALESCE(SUM(amount), 0) FROM wallet_lot_allocations a WHERE a.transaction_id = t.id)`,
customers, customers, customers).Scan(&broken).Error)
assert.Empty(t, broken)
}
+788
View File
@@ -0,0 +1,788 @@
package processor
import (
"context"
"errors"
"sort"
"testing"
"time"
"github.com/google/uuid"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"apskel-pos-be/internal/constants"
"apskel-pos-be/internal/entities"
"apskel-pos-be/internal/repository"
)
// walletRepoFake is an in-memory WalletRepository with the same conditional-update
// semantics as the real one. Locks are only counted: these tests are single-threaded,
// and the locking itself is covered by the repository tests against Postgres.
type walletRepoFake struct {
customers map[uuid.UUID]uuid.UUID // customer -> organization
wallets map[uuid.UUID]*entities.CustomerWallet
transactions []*entities.WalletTransaction
lots []*entities.WalletLot
allocations []entities.WalletLotAllocation
locks map[uuid.UUID]int
clock time.Time
}
func newWalletRepoFake() *walletRepoFake {
return &walletRepoFake{
customers: map[uuid.UUID]uuid.UUID{},
wallets: map[uuid.UUID]*entities.CustomerWallet{},
locks: map[uuid.UUID]int{},
clock: time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC),
}
}
func (f *walletRepoFake) tick() time.Time {
f.clock = f.clock.Add(time.Second)
return f.clock
}
func (f *walletRepoFake) LockWallet(_ context.Context, customerID uuid.UUID) (*entities.CustomerWallet, error) {
org, ok := f.customers[customerID]
if !ok {
return nil, repository.ErrWalletNotFound
}
if f.wallets[customerID] == nil {
f.wallets[customerID] = &entities.CustomerWallet{CustomerID: customerID, OrganizationID: org}
}
f.locks[customerID]++
w := *f.wallets[customerID]
return &w, nil
}
func (f *walletRepoFake) LockWallets(ctx context.Context, a, b uuid.UUID) (*entities.CustomerWallet, *entities.CustomerWallet, error) {
wa, err := f.LockWallet(ctx, a)
if err != nil {
return nil, nil, err
}
wb, err := f.LockWallet(ctx, b)
return wa, wb, err
}
func (f *walletRepoFake) AddBalance(_ context.Context, customerID uuid.UUID, currency string, delta int64) (int64, error) {
w := f.wallets[customerID]
if w == nil {
return 0, repository.ErrWalletNotFound
}
balance := &w.PointBalance
if currency == constants.WalletCurrencyCoin {
balance = &w.CoinBalance
}
if *balance+delta < 0 {
return 0, repository.ErrWalletInsufficientBalance
}
*balance += delta
return *balance, nil
}
func (f *walletRepoFake) GetWallet(_ context.Context, customerID uuid.UUID) (*entities.CustomerWallet, error) {
w := f.wallets[customerID]
if w == nil {
return nil, errors.New("not found")
}
c := *w
return &c, nil
}
func (f *walletRepoFake) CreateTransaction(_ context.Context, tx *entities.WalletTransaction) error {
if tx.IdempotencyKey != nil {
for _, t := range f.transactions {
if t.IdempotencyKey != nil && *t.IdempotencyKey == *tx.IdempotencyKey {
return errors.New("duplicate idempotency key")
}
}
}
if tx.ID == uuid.Nil {
tx.ID = uuid.New()
}
tx.CreatedAt = f.tick()
c := *tx
f.transactions = append(f.transactions, &c)
return nil
}
func (f *walletRepoFake) GetTransactionByIdempotencyKey(_ context.Context, key string) (*entities.WalletTransaction, error) {
for _, t := range f.transactions {
if t.IdempotencyKey != nil && *t.IdempotencyKey == key {
c := *t
return &c, nil
}
}
return nil, nil
}
func (f *walletRepoFake) CreateLot(_ context.Context, lot *entities.WalletLot) error {
if lot.ID == uuid.Nil {
lot.ID = uuid.New()
}
lot.CreatedAt = f.tick()
c := *lot
f.lots = append(f.lots, &c)
return nil
}
func (f *walletRepoFake) GetLotsByIDs(_ context.Context, ids []uuid.UUID) ([]entities.WalletLot, error) {
var out []entities.WalletLot
for _, lot := range f.lots {
for _, id := range ids {
if lot.ID == id {
out = append(out, *lot)
break
}
}
}
return out, nil
}
func (f *walletRepoFake) ListLotsBySourceTransaction(_ context.Context, txID uuid.UUID) ([]entities.WalletLot, error) {
var out []entities.WalletLot
for _, lot := range f.lots {
if lot.SourceTransactionID == txID {
out = append(out, *lot)
}
}
return out, nil
}
func (f *walletRepoFake) ListActiveLots(_ context.Context, customerID uuid.UUID, currency string, asOf time.Time) ([]entities.WalletLot, error) {
var out []entities.WalletLot
for _, lot := range f.lots {
if lot.CustomerID == customerID && lot.Currency == currency && lot.RemainingAmount > 0 &&
(lot.ExpiresAt == nil || lot.ExpiresAt.After(asOf)) {
out = append(out, *lot)
}
}
sort.SliceStable(out, func(i, j int) bool {
a, b := out[i], out[j]
switch {
case a.ExpiresAt == nil && b.ExpiresAt != nil:
return false
case a.ExpiresAt != nil && b.ExpiresAt == nil:
return true
case a.ExpiresAt != nil && !a.ExpiresAt.Equal(*b.ExpiresAt):
return a.ExpiresAt.Before(*b.ExpiresAt)
}
return a.CreatedAt.Before(b.CreatedAt)
})
return out, nil
}
func (f *walletRepoFake) ConsumeLot(_ context.Context, lotID uuid.UUID, amount int64) error {
for _, lot := range f.lots {
if lot.ID == lotID {
if lot.RemainingAmount < amount {
return repository.ErrWalletLotInsufficient
}
lot.RemainingAmount -= amount
return nil
}
}
return repository.ErrWalletLotInsufficient
}
func (f *walletRepoFake) CreateAllocations(_ context.Context, allocations []entities.WalletLotAllocation) error {
f.allocations = append(f.allocations, allocations...)
return nil
}
func (f *walletRepoFake) ListAllocationsByTransaction(_ context.Context, txID uuid.UUID) ([]entities.WalletLotAllocation, error) {
var out []entities.WalletLotAllocation
for _, a := range f.allocations {
if a.TransactionID == txID {
out = append(out, a)
}
}
return out, nil
}
// assertInvariants checks the reconciliation rules of §7.5 over everything the fake
// holds.
func (f *walletRepoFake) assertInvariants(t *testing.T) {
t.Helper()
allocatedFromLot := map[uuid.UUID]int64{}
allocatedByTx := map[uuid.UUID]int64{}
for _, a := range f.allocations {
allocatedFromLot[a.LotID] += a.Amount
allocatedByTx[a.TransactionID] += a.Amount
}
createdByTx := map[uuid.UUID]int64{}
for _, lot := range f.lots {
createdByTx[lot.SourceTransactionID] += lot.OriginalAmount
assert.Equal(t, lot.OriginalAmount-allocatedFromLot[lot.ID], lot.RemainingAmount, "lot %s: original - allocations = remaining", lot.ID)
}
for _, tx := range f.transactions {
if tx.Amount > 0 {
assert.Equal(t, tx.Amount, createdByTx[tx.ID], "credit %s: lots add up to the amount", tx.Type)
assert.Zero(t, allocatedByTx[tx.ID], "credit %s has no allocations", tx.Type)
} else {
assert.Equal(t, -tx.Amount, allocatedByTx[tx.ID], "debit %s: allocations add up to the amount", tx.Type)
assert.Zero(t, createdByTx[tx.ID], "debit %s creates no lots", tx.Type)
}
}
for customerID, w := range f.wallets {
for currency, balance := range map[string]int64{
constants.WalletCurrencyPoint: w.PointBalance,
constants.WalletCurrencyCoin: w.CoinBalance,
} {
var ledger, lots, last int64
for _, tx := range f.transactions {
if tx.CustomerID == customerID && tx.Currency == currency {
ledger += tx.Amount
last = tx.BalanceAfter
}
}
for _, lot := range f.lots {
if lot.CustomerID == customerID && lot.Currency == currency {
lots += lot.RemainingAmount
}
}
assert.Equal(t, balance, ledger, "%s balance = SUM(ledger)", currency)
assert.Equal(t, balance, lots, "%s balance = SUM(lot remaining)", currency)
assert.Equal(t, balance, last, "%s balance = last balance_after", currency)
}
}
}
type walletTestEnv struct {
repo *walletRepoFake
p *WalletProcessor
now time.Time
org uuid.UUID
ctx context.Context
}
func newWalletTestEnv(t *testing.T) *walletTestEnv {
repo := newWalletRepoFake()
env := &walletTestEnv{
repo: repo,
p: NewWalletProcessor(repo),
now: time.Date(2026, 6, 1, 12, 0, 0, 0, time.UTC),
org: uuid.New(),
ctx: context.Background(),
}
env.p.now = func() time.Time { return env.now }
t.Cleanup(func() { repo.assertInvariants(t) })
return env
}
func (e *walletTestEnv) customer() uuid.UUID {
id := uuid.New()
e.repo.customers[id] = e.org
return id
}
func (e *walletTestEnv) at(d time.Duration) *time.Time {
v := e.now.Add(d)
return &v
}
func ptr[T any](v T) *T { return &v }
func earn(customerID uuid.UUID, amount int64, expiresAt *time.Time) WalletCreditInput {
return WalletCreditInput{
WalletEntry: WalletEntry{
CustomerID: customerID,
Currency: constants.WalletCurrencyPoint,
Type: constants.WalletTxTypeEarn,
Amount: amount,
ReferenceType: constants.WalletRefTypeOrder,
ReferenceID: uuid.New(),
OutletID: ptr(uuid.New()),
Description: "Belanja",
},
Lots: []WalletLotInput{{Amount: amount, ExpiresAt: expiresAt}},
}
}
func pay(customerID uuid.UUID, amount int64) WalletDebitInput {
return WalletDebitInput{WalletEntry: WalletEntry{
CustomerID: customerID,
Currency: constants.WalletCurrencyPoint,
Type: constants.WalletTxTypePayment,
Amount: amount,
ReferenceType: constants.WalletRefTypePayment,
ReferenceID: uuid.New(),
OutletID: ptr(uuid.New()),
Description: "Bayar",
}}
}
func (e *walletTestEnv) credit(t *testing.T, in WalletCreditInput) *WalletResult {
t.Helper()
res, err := e.p.Credit(e.ctx, in)
require.NoError(t, err)
return res
}
func (e *walletTestEnv) balance(t *testing.T, customerID uuid.UUID) int64 {
t.Helper()
w, err := e.repo.GetWallet(e.ctx, customerID)
require.NoError(t, err)
return w.PointBalance
}
func allocationsOf(res *WalletResult) map[uuid.UUID]int64 {
out := map[uuid.UUID]int64{}
for _, a := range res.Allocations {
out[a.LotID] = a.Amount
}
return out
}
func TestWalletProcessor_CreditCreatesLedgerRowAndLot(t *testing.T) {
e := newWalletTestEnv(t)
c := e.customer()
res := e.credit(t, earn(c, 100, e.at(24*time.Hour)))
assert.Equal(t, int64(100), res.Transaction.Amount)
assert.Equal(t, int64(100), res.Transaction.BalanceAfter)
assert.Equal(t, e.org, res.Transaction.OrganizationID, "organization comes from the wallet")
require.Len(t, res.Lots, 1)
assert.Equal(t, res.Transaction.ID, res.Lots[0].SourceTransactionID)
assert.Equal(t, e.at(24*time.Hour), res.Lots[0].ExpiresAt)
assert.Equal(t, int64(100), e.balance(t, c))
assert.Equal(t, 1, e.repo.locks[c], "credit locks the wallet itself")
}
func TestWalletProcessor_CreditWithoutLotsMakesOneNonExpiringLot(t *testing.T) {
e := newWalletTestEnv(t)
c := e.customer()
in := earn(c, 40, nil)
in.Lots = nil
res := e.credit(t, in)
require.Len(t, res.Lots, 1)
assert.Equal(t, int64(40), res.Lots[0].OriginalAmount)
assert.Nil(t, res.Lots[0].ExpiresAt)
}
func TestWalletProcessor_CreditRejectsLotsThatDoNotAddUp(t *testing.T) {
e := newWalletTestEnv(t)
c := e.customer()
in := earn(c, 100, nil)
in.Lots = []WalletLotInput{{Amount: 60}, {Amount: 30}}
_, err := e.p.Credit(e.ctx, in)
assert.ErrorIs(t, err, ErrWalletInvalidEntry)
in.Lots = []WalletLotInput{{Amount: 100}, {Amount: 0}}
_, err = e.p.Credit(e.ctx, in)
assert.ErrorIs(t, err, ErrWalletInvalidEntry)
assert.Empty(t, e.repo.transactions)
}
func TestWalletProcessor_DebitAcrossSeveralLots(t *testing.T) {
e := newWalletTestEnv(t)
c := e.customer()
first := e.credit(t, earn(c, 30, e.at(1*time.Hour))).Lots[0]
second := e.credit(t, earn(c, 50, e.at(2*time.Hour))).Lots[0]
third := e.credit(t, earn(c, 40, e.at(3*time.Hour))).Lots[0]
res, err := e.p.Debit(e.ctx, pay(c, 70))
require.NoError(t, err)
assert.Equal(t, int64(-70), res.Transaction.Amount)
assert.Equal(t, int64(50), res.Transaction.BalanceAfter)
assert.Equal(t, map[uuid.UUID]int64{first.ID: 30, second.ID: 40}, allocationsOf(res))
assert.Equal(t, first.ID, res.Allocations[0].LotID, "allocations are reported in the order used")
assert.Equal(t, e.at(1*time.Hour), res.Allocations[0].ExpiresAt)
lots, _ := e.repo.GetLotsByIDs(e.ctx, []uuid.UUID{first.ID, second.ID, third.ID})
remaining := map[uuid.UUID]int64{}
for _, l := range lots {
remaining[l.ID] = l.RemainingAmount
}
assert.Equal(t, map[uuid.UUID]int64{first.ID: 0, second.ID: 10, third.ID: 40}, remaining)
}
// K9: soonest expiry first, lots without an expiry last and oldest first among them,
// expired lots never.
func TestWalletProcessor_DebitFollowsLotOrder(t *testing.T) {
e := newWalletTestEnv(t)
c := e.customer()
neverOld := e.credit(t, earn(c, 10, nil)).Lots[0]
late := e.credit(t, earn(c, 10, e.at(48*time.Hour))).Lots[0]
soon := e.credit(t, earn(c, 10, e.at(1*time.Hour))).Lots[0]
neverNew := e.credit(t, earn(c, 10, nil)).Lots[0]
e.credit(t, earn(c, 10, e.at(-1*time.Hour))) // already expired
var order []uuid.UUID
for i := 0; i < 4; i++ {
res, err := e.p.Debit(e.ctx, pay(c, 10))
require.NoError(t, err)
require.Len(t, res.Allocations, 1)
order = append(order, res.Allocations[0].LotID)
}
assert.Equal(t, []uuid.UUID{soon.ID, late.ID, neverOld.ID, neverNew.ID}, order)
// The expired lot still counts in the balance until the expiry job removes it,
// but it cannot be spent (§7.3).
assert.Equal(t, int64(10), e.balance(t, c))
_, err := e.p.Debit(e.ctx, pay(c, 10))
assert.ErrorIs(t, err, repository.ErrWalletInsufficientBalance)
}
func TestWalletProcessor_DebitOverBalanceChangesNothing(t *testing.T) {
e := newWalletTestEnv(t)
c := e.customer()
e.credit(t, earn(c, 50, nil))
_, err := e.p.Debit(e.ctx, pay(c, 51))
assert.ErrorIs(t, err, repository.ErrWalletInsufficientBalance)
assert.Equal(t, int64(50), e.balance(t, c))
assert.Len(t, e.repo.transactions, 1)
assert.Empty(t, e.repo.allocations)
// A customer who never had a wallet has nothing to spend.
_, err = e.p.Debit(e.ctx, pay(e.customer(), 1))
assert.ErrorIs(t, err, repository.ErrWalletInsufficientBalance)
}
func reversal(customerID uuid.UUID, amount int64, earnRes *WalletResult) WalletDebitInput {
in := WalletDebitInput{WalletEntry: WalletEntry{
CustomerID: customerID,
Currency: constants.WalletCurrencyPoint,
Type: constants.WalletTxTypeEarnReversal,
Amount: amount,
ReferenceType: constants.WalletRefTypeOrder,
ReferenceID: earnRes.Transaction.ReferenceID,
ReversesTransactionID: &earnRes.Transaction.ID,
OutletID: earnRes.Transaction.OutletID,
Description: "Batal",
}}
for _, lot := range earnRes.Lots {
in.PreferredLotIDs = append(in.PreferredLotIDs, lot.ID)
}
return in
}
func TestWalletProcessor_DebitUpToWithShortfall(t *testing.T) {
e := newWalletTestEnv(t)
c := e.customer()
earned := e.credit(t, earn(c, 100, nil))
_, err := e.p.Debit(e.ctx, pay(c, 70))
require.NoError(t, err)
res, err := e.p.DebitUpTo(e.ctx, reversal(c, 100, earned))
require.NoError(t, err)
assert.Equal(t, int64(-30), res.Transaction.Amount)
assert.Equal(t, int64(70), res.Shortfall)
assert.Equal(t, int64(100), res.Transaction.Metadata["requested_amount"])
assert.Equal(t, int64(70), res.Transaction.Metadata["shortfall"])
assert.Equal(t, int64(0), e.balance(t, c))
// Nothing left: no ledger row, the whole amount is shortfall.
in := reversal(c, 5, earned)
res, err = e.p.DebitUpTo(e.ctx, in)
require.NoError(t, err)
assert.Nil(t, res.Transaction)
assert.Equal(t, int64(5), res.Shortfall)
assert.Len(t, e.repo.transactions, 3)
}
// A reversal draws from the lots its EARN created first (F10), even when an older lot
// would come first in K9 order, and even when that lot has expired.
func TestWalletProcessor_DebitDrawsPreferredLotsFirst(t *testing.T) {
e := newWalletTestEnv(t)
c := e.customer()
older := e.credit(t, earn(c, 50, e.at(1*time.Hour))).Lots[0]
earned := e.credit(t, earn(c, 20, e.at(-1*time.Hour)))
res, err := e.p.Debit(e.ctx, reversal(c, 30, earned))
require.NoError(t, err)
require.Len(t, res.Allocations, 2)
assert.Equal(t, earned.Lots[0].ID, res.Allocations[0].LotID)
assert.Equal(t, int64(20), res.Allocations[0].Amount)
assert.Equal(t, older.ID, res.Allocations[1].LotID)
assert.Equal(t, int64(10), res.Allocations[1].Amount)
}
func TestWalletProcessor_DebitRejectsSomeoneElsesLot(t *testing.T) {
e := newWalletTestEnv(t)
a, b := e.customer(), e.customer()
e.credit(t, earn(a, 10, nil))
other := e.credit(t, earn(b, 10, nil))
in := pay(a, 5)
in.PreferredLotIDs = []uuid.UUID{other.Lots[0].ID}
_, err := e.p.Debit(e.ctx, in)
assert.ErrorIs(t, err, ErrWalletInvalidEntry)
in.PreferredLotIDs = []uuid.UUID{uuid.New()}
_, err = e.p.Debit(e.ctx, in)
assert.ErrorIs(t, err, ErrWalletInvalidEntry)
}
func TestWalletProcessor_ExpireDrawsTheExpiredLot(t *testing.T) {
e := newWalletTestEnv(t)
c := e.customer()
e.credit(t, earn(c, 10, nil))
expired := e.credit(t, earn(c, 25, e.at(-1*time.Hour))).Lots[0]
res, err := e.p.Debit(e.ctx, WalletDebitInput{
WalletEntry: WalletEntry{
CustomerID: c,
Currency: constants.WalletCurrencyPoint,
Type: constants.WalletTxTypeExpire,
Amount: expired.RemainingAmount,
ReferenceType: constants.WalletRefTypeLot,
ReferenceID: expired.ID,
Description: "Kedaluwarsa",
IdempotencyKey: "expire:" + expired.ID.String(),
},
PreferredLotIDs: []uuid.UUID{expired.ID},
})
require.NoError(t, err)
assert.Equal(t, map[uuid.UUID]int64{expired.ID: 25}, allocationsOf(res))
assert.Equal(t, int64(10), e.balance(t, c))
}
func TestWalletProcessor_IdempotentCredit(t *testing.T) {
e := newWalletTestEnv(t)
c := e.customer()
in := earn(c, 100, nil)
in.IdempotencyKey = "earn:order-1"
first := e.credit(t, in)
in.ReferenceID = first.Transaction.ReferenceID
second := e.credit(t, in)
assert.True(t, second.Replayed)
assert.False(t, first.Replayed)
assert.Equal(t, first.Transaction.ID, second.Transaction.ID)
assert.Equal(t, first.Lots[0].ID, second.Lots[0].ID)
assert.Equal(t, int64(100), e.balance(t, c))
assert.Len(t, e.repo.transactions, 1)
}
func TestWalletProcessor_IdempotentDebit(t *testing.T) {
e := newWalletTestEnv(t)
c := e.customer()
e.credit(t, earn(c, 30, e.at(time.Hour)))
e.credit(t, earn(c, 30, nil))
in := pay(c, 40)
in.IdempotencyKey = "pay:1"
first, err := e.p.Debit(e.ctx, in)
require.NoError(t, err)
second, err := e.p.Debit(e.ctx, in)
require.NoError(t, err)
assert.True(t, second.Replayed)
assert.Equal(t, first.Transaction.ID, second.Transaction.ID)
assert.ElementsMatch(t, first.Allocations, second.Allocations)
assert.Equal(t, int64(20), e.balance(t, c))
}
func TestWalletProcessor_IdempotentDebitUpToKeepsShortfall(t *testing.T) {
e := newWalletTestEnv(t)
c := e.customer()
earned := e.credit(t, earn(c, 100, nil))
_, err := e.p.Debit(e.ctx, pay(c, 60))
require.NoError(t, err)
in := reversal(c, 100, earned)
in.IdempotencyKey = "reverse:order-1"
first, err := e.p.DebitUpTo(e.ctx, in)
require.NoError(t, err)
e.credit(t, earn(c, 500, nil)) // new balance must not be taken by the retry
second, err := e.p.DebitUpTo(e.ctx, in)
require.NoError(t, err)
assert.True(t, second.Replayed)
assert.Equal(t, first.Transaction.ID, second.Transaction.ID)
assert.Equal(t, int64(60), second.Shortfall)
assert.Equal(t, int64(500), e.balance(t, c))
}
func TestWalletProcessor_IdempotencyKeyReusedForAnotherOperation(t *testing.T) {
e := newWalletTestEnv(t)
c := e.customer()
in := earn(c, 100, nil)
in.IdempotencyKey = "k"
e.credit(t, in)
other := earn(c, 99, nil)
other.IdempotencyKey = "k"
_, err := e.p.Credit(e.ctx, other)
assert.ErrorIs(t, err, ErrWalletIdempotencyConflict)
debit := pay(c, 100)
debit.IdempotencyKey = "k"
_, err = e.p.Debit(e.ctx, debit)
assert.ErrorIs(t, err, ErrWalletIdempotencyConflict)
otherCustomer := earn(e.customer(), 100, nil)
otherCustomer.IdempotencyKey = "k"
_, err = e.p.Credit(e.ctx, otherCustomer)
assert.ErrorIs(t, err, ErrWalletIdempotencyConflict)
}
// A transfer debits the sender and credits the receiver with lots that keep the
// sender's expiry (K9), following the example in §8.
func TestWalletProcessor_TransferCarriesExpiry(t *testing.T) {
e := newWalletTestEnv(t)
a, b := e.customer(), e.customer()
dec := e.credit(t, earn(a, 100, e.at(30*24*time.Hour))).Lots[0]
jan := e.credit(t, earn(a, 50, e.at(60*24*time.Hour))).Lots[0]
require.NoError(t, e.p.LockWallets(e.ctx, a, b))
group, outID, inID := uuid.New(), uuid.New(), uuid.New()
out, err := e.p.Debit(e.ctx, WalletDebitInput{WalletEntry: WalletEntry{
TransactionID: outID, CustomerID: a, Currency: constants.WalletCurrencyPoint,
Type: constants.WalletTxTypeTransferOut, Amount: 120,
ReferenceType: constants.WalletRefTypeWalletTx, ReferenceID: inID,
GroupID: &group, CounterpartyCustomerID: &b, Description: "Transfer ke B",
}})
require.NoError(t, err)
received, err := e.p.Credit(e.ctx, WalletCreditInput{
WalletEntry: WalletEntry{
TransactionID: inID, CustomerID: b, Currency: constants.WalletCurrencyPoint,
Type: constants.WalletTxTypeTransferIn, Amount: 120,
ReferenceType: constants.WalletRefTypeWalletTx, ReferenceID: outID,
GroupID: &group, CounterpartyCustomerID: &a, Description: "Transfer dari A",
},
Lots: out.CarryOver(),
})
require.NoError(t, err)
assert.Equal(t, outID, out.Transaction.ID)
assert.Equal(t, inID, received.Transaction.ID)
require.Len(t, received.Lots, 2)
assert.Equal(t, int64(100), received.Lots[0].OriginalAmount)
assert.Equal(t, dec.ExpiresAt, received.Lots[0].ExpiresAt)
assert.Equal(t, &dec.ID, received.Lots[0].OriginLotID)
assert.Equal(t, int64(20), received.Lots[1].OriginalAmount)
assert.Equal(t, jan.ExpiresAt, received.Lots[1].ExpiresAt)
assert.Equal(t, &jan.ID, received.Lots[1].OriginLotID)
assert.Equal(t, int64(30), e.balance(t, a))
assert.Equal(t, int64(120), e.balance(t, b))
}
func TestWalletProcessor_RejectsEntriesThatBreakTheTypeRules(t *testing.T) {
c := uuid.New()
outlet := ptr(uuid.New())
credits := map[string]func(*WalletCreditInput){
"unknown type": func(in *WalletCreditInput) { in.Type = "BONUS" },
"debit-only type as credit": func(in *WalletCreditInput) {
in.Type = constants.WalletTxTypePayment
in.ReferenceType = constants.WalletRefTypePayment
},
"unknown currency": func(in *WalletCreditInput) { in.Currency = "GOLD" },
"zero amount": func(in *WalletCreditInput) { in.Amount = 0; in.Lots = nil },
"negative amount": func(in *WalletCreditInput) { in.Amount = -5; in.Lots = nil },
"wrong reference type": func(in *WalletCreditInput) { in.ReferenceType = constants.WalletRefTypeUser },
"missing reference id": func(in *WalletCreditInput) { in.ReferenceID = uuid.Nil },
"missing description": func(in *WalletCreditInput) { in.Description = " " },
"EARN without outlet": func(in *WalletCreditInput) { in.OutletID = nil },
"missing customer": func(in *WalletCreditInput) { in.CustomerID = uuid.Nil },
"EXCHANGE_IN in COIN": func(in *WalletCreditInput) {
in.Type = constants.WalletTxTypeExchangeIn
in.Currency = constants.WalletCurrencyCoin
in.ReferenceType = constants.WalletRefTypeWalletTx
in.GroupID = ptr(uuid.New())
},
"TRANSFER_IN to self": func(in *WalletCreditInput) {
in.Type = constants.WalletTxTypeTransferIn
in.ReferenceType = constants.WalletRefTypeWalletTx
in.GroupID = ptr(uuid.New())
in.CounterpartyCustomerID = &in.CustomerID
},
"TRANSFER_IN without group": func(in *WalletCreditInput) {
in.Type = constants.WalletTxTypeTransferIn
in.ReferenceType = constants.WalletRefTypeWalletTx
in.CounterpartyCustomerID = ptr(uuid.New())
},
"PAYMENT_REFUND without source": func(in *WalletCreditInput) {
in.Type = constants.WalletTxTypePaymentRefund
in.ReferenceType = constants.WalletRefTypePayment
},
"ADJUSTMENT without reason": func(in *WalletCreditInput) {
in.Type = constants.WalletTxTypeAdjustment
in.ReferenceType = constants.WalletRefTypeUser
in.CreatedByUser = ptr(uuid.New())
},
"ADJUSTMENT blank reason": func(in *WalletCreditInput) {
in.Type = constants.WalletTxTypeAdjustment
in.ReferenceType = constants.WalletRefTypeUser
in.CreatedByUser = ptr(uuid.New())
in.Reason = ptr(" ")
},
"ADJUSTMENT without admin": func(in *WalletCreditInput) {
in.Type = constants.WalletTxTypeAdjustment
in.ReferenceType = constants.WalletRefTypeUser
in.Reason = ptr("komplain")
},
"MIGRATION wrong reference": func(in *WalletCreditInput) {
in.Type = constants.WalletTxTypeMigration
in.ReferenceType = constants.WalletRefTypeOrder
},
}
for name, mutate := range credits {
t.Run("credit/"+name, func(t *testing.T) {
e := newWalletTestEnv(t)
e.repo.customers[c] = e.org
in := earn(c, 10, nil)
in.OutletID = outlet
mutate(&in)
_, err := e.p.Credit(e.ctx, in)
assert.ErrorIs(t, err, ErrWalletInvalidEntry)
assert.Empty(t, e.repo.transactions)
})
}
debits := map[string]func(*WalletDebitInput){
"credit-only type as debit": func(in *WalletDebitInput) {
in.Type = constants.WalletTxTypeMigration
in.ReferenceType = constants.WalletRefTypeLegacyPoints
},
"PAYMENT in COIN": func(in *WalletDebitInput) { in.Currency = constants.WalletCurrencyCoin },
"GAME_SPEND in POINT": func(in *WalletDebitInput) {
in.Type = constants.WalletTxTypeGameSpend
in.ReferenceType = constants.WalletRefTypeGamePlay
},
"EXPIRE not pointing at a lot": func(in *WalletDebitInput) {
in.Type = constants.WalletTxTypeExpire
in.ReferenceType = constants.WalletRefTypeOrder
},
"EARN_REVERSAL without source": func(in *WalletDebitInput) {
in.Type = constants.WalletTxTypeEarnReversal
in.ReferenceType = constants.WalletRefTypeOrder
},
"TRANSFER_OUT without counterparty": func(in *WalletDebitInput) {
in.Type = constants.WalletTxTypeTransferOut
in.ReferenceType = constants.WalletRefTypeWalletTx
in.GroupID = ptr(uuid.New())
},
"REWARD_REDEEM wrong reference": func(in *WalletDebitInput) {
in.Type = constants.WalletTxTypeRewardRedeem
in.ReferenceType = constants.WalletRefTypeOrder
},
}
for name, mutate := range debits {
t.Run("debit/"+name, func(t *testing.T) {
e := newWalletTestEnv(t)
e.repo.customers[c] = e.org
e.credit(t, earn(c, 100, nil))
in := pay(c, 10)
mutate(&in)
_, err := e.p.Debit(e.ctx, in)
assert.ErrorIs(t, err, ErrWalletInvalidEntry)
assert.Len(t, e.repo.transactions, 1)
})
}
}
func TestWalletProcessor_UnknownCustomer(t *testing.T) {
e := newWalletTestEnv(t)
_, err := e.p.Credit(e.ctx, earn(uuid.New(), 10, nil))
assert.ErrorIs(t, err, repository.ErrWalletNotFound)
}
@@ -0,0 +1,336 @@
package processor
import (
"context"
"errors"
"fmt"
"strings"
"time"
"github.com/google/uuid"
"apskel-pos-be/internal/constants"
"apskel-pos-be/internal/entities"
"apskel-pos-be/internal/models"
"apskel-pos-be/internal/repository"
)
// ErrInvalidWalletQuery wraps every rejection of a malformed history query, so the
// handler can answer with a validation error rather than a server error.
var ErrInvalidWalletQuery = errors.New("invalid wallet query")
const (
walletRecentTransactions = 5
walletLegacyHistorySize = 10
walletTransactionsPageLimit = 20
walletTransactionsMaxLimit = 100
)
// walletDisplayLocation is where the customer's calendar days start and end, for
// date filters. Same zone as the database connection and the expiry grouping.
var walletDisplayLocation = func() *time.Location {
loc, err := time.LoadLocation("Asia/Jakarta")
if err != nil {
return time.FixedZone("WIB", 7*60*60)
}
return loc
}()
// WalletQueryProcessor answers what the customer app shows about a wallet: balances,
// history and upcoming expiry (docs/prd-point-coin.md F6). It only reads.
type WalletQueryProcessor struct {
repo repository.WalletQueryRepository
settings pointValueReader
now func() time.Time
}
// pointValueReader gives the rupiah value of one EnakPoint in an organization.
// LoyaltySettingsProcessor is one.
type pointValueReader interface {
PointValue(ctx context.Context, organizationID uuid.UUID) (int64, error)
}
func NewWalletQueryProcessor(repo repository.WalletQueryRepository, settings pointValueReader) *WalletQueryProcessor {
return &WalletQueryProcessor{repo: repo, settings: settings, now: time.Now}
}
// Summary is GET /customer/wallet. A customer who has never had a wallet gets zeros.
func (p *WalletQueryProcessor) Summary(ctx context.Context, customerID uuid.UUID) (*models.GetCustomerWalletResponseData, error) {
organizationID, err := p.repo.GetCustomerOrganizationID(ctx, customerID)
if err != nil {
return nil, err
}
now := p.now()
balances, err := p.repo.SpendableBalances(ctx, customerID, now)
if err != nil {
return nil, err
}
pointValue, err := p.settings.PointValue(ctx, organizationID)
if err != nil {
return nil, err
}
expiring, err := p.repo.NearestExpiring(ctx, customerID, now)
if err != nil {
return nil, err
}
recent, err := p.recent(ctx, customerID, "", walletRecentTransactions)
if err != nil {
return nil, err
}
points, err := p.legacyPoints(ctx, customerID, balances)
if err != nil {
return nil, err
}
tokens, err := p.legacyTokens(ctx, customerID, balances)
if err != nil {
return nil, err
}
data := &models.GetCustomerWalletResponseData{
PointBalance: balances[constants.WalletCurrencyPoint],
CoinBalance: balances[constants.WalletCurrencyCoin],
PointValue: pointValue,
PointDiscountValue: balances[constants.WalletCurrencyPoint] * pointValue,
RecentTransactions: recent,
TotalPoints: points.TotalPoints,
TotalTokens: tokens.TotalTokens,
PointsHistory: points.PointsHistory,
TokensHistory: tokens.TokensHistory,
LastUpdated: points.LastUpdated,
}
if tokens.LastUpdated.After(data.LastUpdated) {
data.LastUpdated = tokens.LastUpdated
}
for _, e := range expiring {
entry := &models.CustomerWalletExpiring{Amount: e.Amount, Date: e.Date}
switch e.Currency {
case constants.WalletCurrencyPoint:
data.NearestExpiring.Point = entry
case constants.WalletCurrencyCoin:
data.NearestExpiring.Coin = entry
}
}
return data, nil
}
// Transactions is GET /customer/wallet/transactions.
func (p *WalletQueryProcessor) Transactions(ctx context.Context, customerID uuid.UUID, query models.ListCustomerWalletTransactionsQuery) (*models.PaginatedResponse[models.CustomerWalletTransaction], error) {
filter, page, err := walletTransactionFilter(customerID, query)
if err != nil {
return nil, err
}
rows, total, err := p.repo.ListTransactions(ctx, filter)
if err != nil {
return nil, err
}
items, err := p.toTransactions(ctx, rows)
if err != nil {
return nil, err
}
totalPages := int((total + int64(filter.Limit) - 1) / int64(filter.Limit))
return &models.PaginatedResponse[models.CustomerWalletTransaction]{
Data: items,
Pagination: models.Pagination{Page: page, Limit: filter.Limit, Total: total, TotalPages: totalPages},
}, nil
}
// LegacyPoints is the pre-wallet GET /customer/points, now read from the wallet.
func (p *WalletQueryProcessor) LegacyPoints(ctx context.Context, customerID uuid.UUID) (*models.GetCustomerPointsResponseData, error) {
balances, err := p.repo.SpendableBalances(ctx, customerID, p.now())
if err != nil {
return nil, err
}
return p.legacyPoints(ctx, customerID, balances)
}
func (p *WalletQueryProcessor) legacyPoints(ctx context.Context, customerID uuid.UUID, balances map[string]int64) (*models.GetCustomerPointsResponseData, error) {
recent, err := p.recent(ctx, customerID, constants.WalletCurrencyPoint, walletLegacyHistorySize)
if err != nil {
return nil, err
}
data := &models.GetCustomerPointsResponseData{TotalPoints: balances[constants.WalletCurrencyPoint]}
for _, tx := range recent {
data.PointsHistory = append(data.PointsHistory, models.PointsHistoryItem{
ID: tx.ID.String(), Points: tx.Amount, Type: tx.Type, Description: tx.Description, CreatedAt: tx.CreatedAt,
})
}
if len(recent) > 0 {
data.LastUpdated = recent[0].CreatedAt
}
return data, nil
}
// LegacyTokens is the pre-wallet GET /customer/tokens. Tokens are EnakCoin now.
func (p *WalletQueryProcessor) LegacyTokens(ctx context.Context, customerID uuid.UUID) (*models.GetCustomerTokensResponseData, error) {
balances, err := p.repo.SpendableBalances(ctx, customerID, p.now())
if err != nil {
return nil, err
}
return p.legacyTokens(ctx, customerID, balances)
}
func (p *WalletQueryProcessor) legacyTokens(ctx context.Context, customerID uuid.UUID, balances map[string]int64) (*models.GetCustomerTokensResponseData, error) {
recent, err := p.recent(ctx, customerID, constants.WalletCurrencyCoin, walletLegacyHistorySize)
if err != nil {
return nil, err
}
data := &models.GetCustomerTokensResponseData{TotalTokens: balances[constants.WalletCurrencyCoin]}
for _, tx := range recent {
data.TokensHistory = append(data.TokensHistory, models.TokensHistoryItem{
ID: tx.ID.String(), Tokens: tx.Amount, Type: tx.Type, Description: tx.Description, CreatedAt: tx.CreatedAt,
})
}
if len(recent) > 0 {
data.LastUpdated = recent[0].CreatedAt
}
return data, nil
}
func (p *WalletQueryProcessor) recent(ctx context.Context, customerID uuid.UUID, currency string, limit int) ([]models.CustomerWalletTransaction, error) {
rows, _, err := p.repo.ListTransactions(ctx, repository.WalletTransactionFilter{
CustomerID: customerID, Currency: currency, Limit: limit,
})
if err != nil {
return nil, err
}
return p.toTransactions(ctx, rows)
}
func (p *WalletQueryProcessor) toTransactions(ctx context.Context, rows []entities.WalletTransaction) ([]models.CustomerWalletTransaction, error) {
return buildWalletTransactions(ctx, p.repo, rows)
}
// buildWalletTransactions turns ledger rows into what the apps show, in the same
// order: where each row came from or went to, and the lots each credit created.
func buildWalletTransactions(ctx context.Context, repo repository.WalletQueryRepository, rows []entities.WalletTransaction) ([]models.CustomerWalletTransaction, error) {
var credits []uuid.UUID
for _, row := range rows {
if row.Amount > 0 {
credits = append(credits, row.ID)
}
}
lots, err := repo.ListLotsBySourceTransactions(ctx, credits)
if err != nil {
return nil, err
}
lotsByTx := make(map[uuid.UUID][]entities.WalletLot, len(credits))
for _, lot := range lots {
lotsByTx[lot.SourceTransactionID] = append(lotsByTx[lot.SourceTransactionID], lot)
}
items := make([]models.CustomerWalletTransaction, 0, len(rows))
for _, row := range rows {
ref := &models.CustomerWalletTransactionRef{Type: row.ReferenceType, ID: row.ReferenceID}
item := models.CustomerWalletTransaction{
ID: row.ID,
Currency: row.Currency,
Type: row.Type,
Amount: row.Amount,
BalanceAfter: row.BalanceAfter,
Description: row.Description,
OutletID: row.OutletID,
ReversesTransactionID: row.ReversesTransactionID,
GroupID: row.GroupID,
CreatedAt: row.CreatedAt,
}
// The counterparty's id, the admin and the metadata are left out on purpose:
// the customer sees the masked name in the description (§8.1).
if row.Amount > 0 {
item.Source = ref
for _, lot := range lotsByTx[row.ID] {
item.Lots = append(item.Lots, models.CustomerWalletLot{
Amount: lot.OriginalAmount, Remaining: lot.RemainingAmount, ExpiresAt: lot.ExpiresAt,
})
if lot.ExpiresAt != nil && (item.ExpiresAt == nil || lot.ExpiresAt.Before(*item.ExpiresAt)) {
item.ExpiresAt = lot.ExpiresAt
}
}
} else {
item.Destination = ref
}
items = append(items, item)
}
return items, nil
}
func walletTransactionFilter(customerID uuid.UUID, q models.ListCustomerWalletTransactionsQuery) (repository.WalletTransactionFilter, int, error) {
invalid := func(format string, args ...any) error {
return fmt.Errorf("%w: %s", ErrInvalidWalletQuery, fmt.Sprintf(format, args...))
}
filter := repository.WalletTransactionFilter{CustomerID: customerID}
page := q.Page
if page == 0 {
page = 1
}
if page < 1 {
return filter, 0, invalid("page must be at least 1")
}
filter.Limit = q.Limit
if filter.Limit == 0 {
filter.Limit = walletTransactionsPageLimit
}
if filter.Limit < 1 || filter.Limit > walletTransactionsMaxLimit {
return filter, 0, invalid("limit must be between 1 and %d", walletTransactionsMaxLimit)
}
filter.Offset = (page - 1) * filter.Limit
if q.Currency != "" {
currency := strings.ToUpper(q.Currency)
if !constants.IsValidWalletCurrency(currency) {
return filter, 0, invalid("currency must be POINT or COIN")
}
filter.Currency = currency
}
for _, t := range strings.Split(q.Type, ",") {
t = strings.ToUpper(strings.TrimSpace(t))
if t == "" {
continue
}
if _, ok := walletTypeRules[t]; !ok {
return filter, 0, invalid("unknown type %q", t)
}
filter.Types = append(filter.Types, t)
}
if q.From != "" {
from, err := time.ParseInLocation("2006-01-02", q.From, walletDisplayLocation)
if err != nil {
return filter, 0, invalid("from must be a date like 2026-01-31")
}
filter.From = &from
}
if q.To != "" {
to, err := time.ParseInLocation("2006-01-02", q.To, walletDisplayLocation)
if err != nil {
return filter, 0, invalid("to must be a date like 2026-01-31")
}
// To is inclusive for the customer, exclusive in the query.
end := to.AddDate(0, 0, 1)
filter.To = &end
}
if filter.From != nil && filter.To != nil && !filter.From.Before(*filter.To) {
return filter, 0, invalid("from must not be after to")
}
return filter, page, nil
}
// Expiring is GET /customer/wallet/expiring: what will expire, grouped by day (F6).
func (p *WalletQueryProcessor) Expiring(ctx context.Context, customerID uuid.UUID) (*models.CustomerWalletExpiringList, error) {
rows, err := p.repo.ExpiringByDay(ctx, customerID, p.now())
if err != nil {
return nil, err
}
list := &models.CustomerWalletExpiringList{Point: []models.CustomerWalletExpiring{}, Coin: []models.CustomerWalletExpiring{}}
for _, row := range rows {
item := models.CustomerWalletExpiring{Amount: row.Amount, Date: row.Date}
switch row.Currency {
case constants.WalletCurrencyPoint:
list.Point = append(list.Point, item)
case constants.WalletCurrencyCoin:
list.Coin = append(list.Coin, item)
}
}
return list, nil
}
@@ -0,0 +1,266 @@
package processor
import (
"context"
"testing"
"time"
"github.com/google/uuid"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"apskel-pos-be/internal/constants"
"apskel-pos-be/internal/entities"
"apskel-pos-be/internal/models"
"apskel-pos-be/internal/repository"
)
type walletQueryRepoFake struct {
org uuid.UUID
spendable map[string]int64
expiring []repository.WalletExpiringAmount
transactions []entities.WalletTransaction
total int64
lots []entities.WalletLot
filters []repository.WalletTransactionFilter
}
func (f *walletQueryRepoFake) GetCustomerOrganizationID(context.Context, uuid.UUID) (uuid.UUID, error) {
if f.org == uuid.Nil {
return uuid.Nil, repository.ErrWalletNotFound
}
return f.org, nil
}
func (f *walletQueryRepoFake) SpendableBalances(context.Context, uuid.UUID, time.Time) (map[string]int64, error) {
return f.spendable, nil
}
func (f *walletQueryRepoFake) NearestExpiring(context.Context, uuid.UUID, time.Time) ([]repository.WalletExpiringAmount, error) {
return f.expiring, nil
}
func (f *walletQueryRepoFake) ListTransactions(_ context.Context, filter repository.WalletTransactionFilter) ([]entities.WalletTransaction, int64, error) {
f.filters = append(f.filters, filter)
var out []entities.WalletTransaction
for _, tx := range f.transactions {
if filter.Currency == "" || tx.Currency == filter.Currency {
out = append(out, tx)
}
}
if len(out) > filter.Limit {
out = out[:filter.Limit]
}
return out, f.total, nil
}
func (f *walletQueryRepoFake) ListLotsBySourceTransactions(_ context.Context, ids []uuid.UUID) ([]entities.WalletLot, error) {
var out []entities.WalletLot
for _, lot := range f.lots {
for _, id := range ids {
if lot.SourceTransactionID == id {
out = append(out, lot)
}
}
}
return out, nil
}
type orgSettingsFake map[string]string
func newWalletQueryTest(repo *walletQueryRepoFake, settings orgSettingsFake) *WalletQueryProcessor {
p := NewWalletQueryProcessor(repo, NewLoyaltySettingsProcessor(&loyaltyRepoFake{orgValues: settings}, txRunnerFake{}))
p.now = func() time.Time { return time.Date(2026, 6, 1, 12, 0, 0, 0, time.UTC) }
return p
}
func TestWalletQueryProcessor_SummaryShowsWhereEachRowCameFromOrWent(t *testing.T) {
order, payment := uuid.New(), uuid.New()
earnID, payID := uuid.New(), uuid.New()
soon := time.Date(2026, 7, 1, 0, 0, 0, 0, time.UTC)
later := time.Date(2026, 9, 1, 0, 0, 0, 0, time.UTC)
created := time.Date(2026, 5, 1, 0, 0, 0, 0, time.UTC)
repo := &walletQueryRepoFake{
org: uuid.New(),
spendable: map[string]int64{constants.WalletCurrencyPoint: 250, constants.WalletCurrencyCoin: 8},
expiring: []repository.WalletExpiringAmount{
{Currency: constants.WalletCurrencyPoint, Date: "2026-07-01", Amount: 100},
},
transactions: []entities.WalletTransaction{
{ID: payID, Currency: constants.WalletCurrencyPoint, Type: constants.WalletTxTypePayment, Amount: -50, BalanceAfter: 250,
ReferenceType: constants.WalletRefTypePayment, ReferenceID: payment, Description: "Bayar #ORD-1", CreatedAt: created.Add(time.Hour),
CounterpartyCustomerID: ptr(uuid.New()), Metadata: entities.Metadata{"point_value": 100}},
{ID: earnID, Currency: constants.WalletCurrencyPoint, Type: constants.WalletTxTypeEarn, Amount: 300, BalanceAfter: 300,
ReferenceType: constants.WalletRefTypeOrder, ReferenceID: order, Description: "Belanja #ORD-1", CreatedAt: created},
},
lots: []entities.WalletLot{
{SourceTransactionID: earnID, OriginalAmount: 200, RemainingAmount: 150, ExpiresAt: &later},
{SourceTransactionID: earnID, OriginalAmount: 100, RemainingAmount: 100, ExpiresAt: &soon},
},
}
p := newWalletQueryTest(repo, orgSettingsFake{constants.LoyaltyPointValueKey: "100"})
data, err := p.Summary(context.Background(), uuid.New())
require.NoError(t, err)
assert.Equal(t, int64(250), data.PointBalance)
assert.Equal(t, int64(8), data.CoinBalance)
assert.Equal(t, int64(100), data.PointValue)
assert.Equal(t, int64(25000), data.PointDiscountValue)
assert.Equal(t, &models.CustomerWalletExpiring{Amount: 100, Date: "2026-07-01"}, data.NearestExpiring.Point)
assert.Nil(t, data.NearestExpiring.Coin)
require.Len(t, data.RecentTransactions, 2)
pay, earn := data.RecentTransactions[0], data.RecentTransactions[1]
assert.Equal(t, &models.CustomerWalletTransactionRef{Type: constants.WalletRefTypePayment, ID: payment}, pay.Destination)
assert.Nil(t, pay.Source)
assert.Empty(t, pay.Lots)
assert.Equal(t, &models.CustomerWalletTransactionRef{Type: constants.WalletRefTypeOrder, ID: order}, earn.Source)
assert.Nil(t, earn.Destination)
assert.Equal(t, &soon, earn.ExpiresAt, "earliest expiry among the lots the credit created")
assert.Len(t, earn.Lots, 2)
// The pre-wallet fields are still filled, from the wallet.
assert.Equal(t, int64(250), data.TotalPoints)
assert.Equal(t, int64(8), data.TotalTokens)
require.Len(t, data.PointsHistory, 2)
assert.Equal(t, int64(-50), data.PointsHistory[0].Points)
assert.Equal(t, constants.WalletTxTypePayment, data.PointsHistory[0].Type)
assert.Equal(t, created.Add(time.Hour), data.LastUpdated)
}
func TestWalletQueryProcessor_PointValueFallsBackToDefault(t *testing.T) {
for name, settings := range map[string]orgSettingsFake{
"not set": {},
"garbage": {constants.LoyaltyPointValueKey: "abc"},
"zero": {constants.LoyaltyPointValueKey: "0"},
"negative": {constants.LoyaltyPointValueKey: "-5"},
} {
t.Run(name, func(t *testing.T) {
repo := &walletQueryRepoFake{org: uuid.New(), spendable: map[string]int64{constants.WalletCurrencyPoint: 40}}
data, err := newWalletQueryTest(repo, settings).Summary(context.Background(), uuid.New())
require.NoError(t, err)
assert.Equal(t, constants.LoyaltyPointValueDefault, data.PointValue)
assert.Equal(t, int64(40), data.PointDiscountValue)
})
}
}
func TestWalletQueryProcessor_SummaryForCustomerWithoutWallet(t *testing.T) {
repo := &walletQueryRepoFake{org: uuid.New(), spendable: map[string]int64{}}
data, err := newWalletQueryTest(repo, orgSettingsFake{}).Summary(context.Background(), uuid.New())
require.NoError(t, err)
assert.Zero(t, data.PointBalance)
assert.Zero(t, data.CoinBalance)
assert.NotNil(t, data.RecentTransactions, "an empty list, not null, for the app")
_, err = newWalletQueryTest(&walletQueryRepoFake{}, orgSettingsFake{}).Summary(context.Background(), uuid.New())
assert.ErrorIs(t, err, repository.ErrWalletNotFound)
}
func TestWalletQueryProcessor_LegacyEndpointsSplitByCurrency(t *testing.T) {
repo := &walletQueryRepoFake{
org: uuid.New(),
spendable: map[string]int64{constants.WalletCurrencyPoint: 100, constants.WalletCurrencyCoin: 8},
transactions: []entities.WalletTransaction{
{ID: uuid.New(), Currency: constants.WalletCurrencyCoin, Type: constants.WalletTxTypeMigration, Amount: 8},
{ID: uuid.New(), Currency: constants.WalletCurrencyPoint, Type: constants.WalletTxTypeMigration, Amount: 100},
},
}
p := newWalletQueryTest(repo, orgSettingsFake{})
points, err := p.LegacyPoints(context.Background(), uuid.New())
require.NoError(t, err)
assert.Equal(t, int64(100), points.TotalPoints)
require.Len(t, points.PointsHistory, 1)
assert.Equal(t, int64(100), points.PointsHistory[0].Points)
tokens, err := p.LegacyTokens(context.Background(), uuid.New())
require.NoError(t, err)
assert.Equal(t, int64(8), tokens.TotalTokens)
require.Len(t, tokens.TokensHistory, 1)
assert.Equal(t, int64(8), tokens.TokensHistory[0].Tokens)
}
func TestWalletQueryProcessor_TransactionsQuery(t *testing.T) {
customer := uuid.New()
jakarta := walletDisplayLocation
repo := &walletQueryRepoFake{org: uuid.New(), total: 45}
page, err := newWalletQueryTest(repo, orgSettingsFake{}).Transactions(context.Background(), customer, models.ListCustomerWalletTransactionsQuery{
Page: 3, Limit: 10, Currency: "point", Type: "earn, PAYMENT", From: "2026-05-01", To: "2026-05-31",
})
require.NoError(t, err)
assert.Equal(t, models.Pagination{Page: 3, Limit: 10, Total: 45, TotalPages: 5}, page.Pagination)
assert.NotNil(t, page.Data)
f := repo.filters[0]
assert.Equal(t, customer, f.CustomerID)
assert.Equal(t, 20, f.Offset)
assert.Equal(t, 10, f.Limit)
assert.Equal(t, constants.WalletCurrencyPoint, f.Currency)
assert.Equal(t, []string{constants.WalletTxTypeEarn, constants.WalletTxTypePayment}, f.Types)
assert.True(t, f.From.Equal(time.Date(2026, 5, 1, 0, 0, 0, 0, jakarta)))
assert.True(t, f.To.Equal(time.Date(2026, 6, 1, 0, 0, 0, 0, jakarta)), "to covers the whole last day")
// Defaults.
repo = &walletQueryRepoFake{org: uuid.New()}
page, err = newWalletQueryTest(repo, orgSettingsFake{}).Transactions(context.Background(), customer, models.ListCustomerWalletTransactionsQuery{})
require.NoError(t, err)
assert.Equal(t, 1, page.Pagination.Page)
assert.Equal(t, walletTransactionsPageLimit, repo.filters[0].Limit)
assert.Zero(t, repo.filters[0].Offset)
assert.Nil(t, repo.filters[0].From)
assert.Empty(t, repo.filters[0].Types)
}
func TestWalletQueryProcessor_RejectsBadQueries(t *testing.T) {
for name, q := range map[string]models.ListCustomerWalletTransactionsQuery{
"negative page": {Page: -1},
"limit too big": {Limit: walletTransactionsMaxLimit + 1},
"negative limit": {Limit: -1},
"unknown currency": {Currency: "GOLD"},
"unknown type": {Type: "EARN,BONUS"},
"bad from": {From: "01-05-2026"},
"bad to": {To: "2026-13-01"},
"from after to": {From: "2026-06-02", To: "2026-06-01"},
} {
t.Run(name, func(t *testing.T) {
repo := &walletQueryRepoFake{org: uuid.New()}
_, err := newWalletQueryTest(repo, orgSettingsFake{}).Transactions(context.Background(), uuid.New(), q)
assert.ErrorIs(t, err, ErrInvalidWalletQuery)
assert.Empty(t, repo.filters, "nothing is queried")
})
}
// A single day is a valid range.
repo := &walletQueryRepoFake{org: uuid.New()}
_, err := newWalletQueryTest(repo, orgSettingsFake{}).Transactions(context.Background(), uuid.New(),
models.ListCustomerWalletTransactionsQuery{From: "2026-06-01", To: "2026-06-01"})
assert.NoError(t, err)
}
func (f *walletQueryRepoFake) OrganizationOutstanding(context.Context, uuid.UUID) (int64, int64, error) {
return 0, 0, nil
}
func (f *walletQueryRepoFake) ExpiringByDay(context.Context, uuid.UUID, time.Time) ([]repository.WalletExpiringAmount, error) {
return f.expiring, nil
}
func TestWalletQueryProcessor_ExpiringGroupsByCurrencyAndDay(t *testing.T) {
repo := &walletQueryRepoFake{org: uuid.New(), expiring: []repository.WalletExpiringAmount{
{Currency: "POINT", Date: "2026-10-31", Amount: 150},
{Currency: "COIN", Date: "2026-10-31", Amount: 4},
{Currency: "POINT", Date: "2026-12-31", Amount: 200},
}}
got, err := newWalletQueryTest(repo, nil).Expiring(context.Background(), uuid.New())
require.NoError(t, err)
assert.Equal(t, []models.CustomerWalletExpiring{{Amount: 150, Date: "2026-10-31"}, {Amount: 200, Date: "2026-12-31"}}, got.Point)
assert.Equal(t, []models.CustomerWalletExpiring{{Amount: 4, Date: "2026-10-31"}}, got.Coin)
empty, err := newWalletQueryTest(&walletQueryRepoFake{org: uuid.New()}, nil).Expiring(context.Background(), uuid.New())
require.NoError(t, err)
assert.NotNil(t, empty.Point, "an empty list, not null")
assert.NotNil(t, empty.Coin)
}
@@ -0,0 +1,180 @@
package processor
import (
"context"
"time"
"github.com/google/uuid"
"apskel-pos-be/internal/entities"
"apskel-pos-be/internal/models"
"apskel-pos-be/internal/repository"
)
// walletTraceMaxDepth bounds how far back a chain is followed. Every step is a
// transfer, exchange or refund of the step before, so real chains are short; the
// bound only guards against a loop in bad data.
const walletTraceMaxDepth = 100
// WalletTraceProcessor traces a ledger row lot by lot for the dashboard
// (docs/prd-point-coin.md F7, §8.1). It only reads.
type WalletTraceProcessor struct {
repo repository.WalletTraceRepository
now func() time.Time
}
func NewWalletTraceProcessor(repo repository.WalletTraceRepository) *WalletTraceProcessor {
return &WalletTraceProcessor{repo: repo, now: time.Now}
}
type walletTraceStart struct {
lotID uuid.UUID
amount int64
}
// Trace follows a row of the organization's ledger: a debit through the lots it took
// from, a credit through the lots it created, and each lot back through origin_lot_id
// to the lot that first brought the balance in. A row of another organization is
// repository.ErrWalletTransactionNotFound.
func (p *WalletTraceProcessor) Trace(ctx context.Context, organizationID, transactionID uuid.UUID) (*models.AdminWalletTrace, error) {
row, err := p.repo.GetTransaction(ctx, organizationID, transactionID)
if err != nil {
return nil, err
}
var starts []walletTraceStart
if row.Amount < 0 {
allocations, err := p.repo.ListAllocations(ctx, row.ID)
if err != nil {
return nil, err
}
for _, a := range allocations {
starts = append(starts, walletTraceStart{lotID: a.LotID, amount: a.Amount})
}
} else {
created, err := p.repo.ListLotsBySource(ctx, row.ID)
if err != nil {
return nil, err
}
for _, lot := range created {
starts = append(starts, walletTraceStart{lotID: lot.ID, amount: lot.OriginalAmount})
}
}
lots, err := p.loadChains(ctx, starts)
if err != nil {
return nil, err
}
sourceIDs := make([]uuid.UUID, 0, len(lots))
customerIDs := []uuid.UUID{row.CustomerID}
for _, lot := range lots {
sourceIDs = append(sourceIDs, lot.SourceTransactionID)
customerIDs = append(customerIDs, lot.CustomerID)
}
sourceRows, err := p.repo.GetTransactions(ctx, uniqueIDs(sourceIDs))
if err != nil {
return nil, err
}
sources := make(map[uuid.UUID]entities.WalletTransaction, len(sourceRows))
for _, s := range sourceRows {
sources[s.ID] = s
}
names, err := p.repo.CustomerNames(ctx, uniqueIDs(customerIDs))
if err != nil {
return nil, err
}
now := p.now()
trace := &models.AdminWalletTrace{
Transaction: walletTraceRow(*row, names),
Lots: make([]models.AdminWalletTraceLot, 0, len(starts)),
}
for _, start := range starts {
item := models.AdminWalletTraceLot{Amount: start.amount, Chain: []models.AdminWalletTraceStep{}}
visited := map[uuid.UUID]bool{}
for id := &start.lotID; id != nil && !visited[*id]; {
lot, ok := lots[*id]
if !ok {
break
}
visited[*id] = true
item.Chain = append(item.Chain, models.AdminWalletTraceStep{
Lot: adminWalletLot(lot, now),
Source: walletTraceRow(sources[lot.SourceTransactionID], names),
})
id = lot.OriginLotID
}
trace.Lots = append(trace.Lots, item)
}
return trace, nil
}
// loadChains loads the starting lots and every lot they were carried over from, one
// generation at a time.
func (p *WalletTraceProcessor) loadChains(ctx context.Context, starts []walletTraceStart) (map[uuid.UUID]entities.WalletLot, error) {
lots := map[uuid.UUID]entities.WalletLot{}
pending := make([]uuid.UUID, 0, len(starts))
for _, s := range starts {
pending = append(pending, s.lotID)
}
for depth := 0; len(pending) > 0 && depth < walletTraceMaxDepth; depth++ {
found, err := p.repo.GetLots(ctx, uniqueIDs(pending))
if err != nil {
return nil, err
}
pending = pending[:0]
for _, lot := range found {
lots[lot.ID] = lot
}
for _, lot := range found {
if lot.OriginLotID != nil {
if _, seen := lots[*lot.OriginLotID]; !seen {
pending = append(pending, *lot.OriginLotID)
}
}
}
}
return lots, nil
}
func walletTraceRow(row entities.WalletTransaction, names map[uuid.UUID]string) models.AdminWalletTraceRow {
return models.AdminWalletTraceRow{
ID: row.ID,
Customer: models.AdminWalletNamedRef{ID: row.CustomerID, Name: names[row.CustomerID]},
Currency: row.Currency,
Type: row.Type,
Amount: row.Amount,
Description: row.Description,
ReferenceType: row.ReferenceType,
ReferenceID: row.ReferenceID,
OutletID: row.OutletID,
CreatedAt: row.CreatedAt,
}
}
func adminWalletLot(lot entities.WalletLot, now time.Time) models.AdminWalletLot {
return models.AdminWalletLot{
ID: lot.ID,
Currency: lot.Currency,
OriginalAmount: lot.OriginalAmount,
RemainingAmount: lot.RemainingAmount,
ExpiresAt: lot.ExpiresAt,
Expired: lot.ExpiresAt != nil && !lot.ExpiresAt.After(now),
SourceTransactionID: lot.SourceTransactionID,
OriginLotID: lot.OriginLotID,
CreatedAt: lot.CreatedAt,
}
}
func uniqueIDs(ids []uuid.UUID) []uuid.UUID {
seen := make(map[uuid.UUID]bool, len(ids))
out := make([]uuid.UUID, 0, len(ids))
for _, id := range ids {
if !seen[id] {
seen[id] = true
out = append(out, id)
}
}
return out
}
@@ -0,0 +1,161 @@
package processor
import (
"context"
"testing"
"time"
"github.com/google/uuid"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"apskel-pos-be/internal/constants"
"apskel-pos-be/internal/entities"
"apskel-pos-be/internal/models"
"apskel-pos-be/internal/repository"
)
// walletTraceRepoFake reads the fake wallet the way the trace repository reads the
// tables.
type walletTraceRepoFake struct{ e *walletMoveEnv }
func (f walletTraceRepoFake) GetTransaction(_ context.Context, organizationID, id uuid.UUID) (*entities.WalletTransaction, error) {
for _, tx := range f.e.repo.transactions {
if tx.ID == id && tx.OrganizationID == organizationID {
c := *tx
return &c, nil
}
}
return nil, repository.ErrWalletTransactionNotFound
}
func (f walletTraceRepoFake) GetTransactions(_ context.Context, ids []uuid.UUID) ([]entities.WalletTransaction, error) {
var out []entities.WalletTransaction
for _, tx := range f.e.repo.transactions {
if containsID(ids, tx.ID) {
out = append(out, *tx)
}
}
return out, nil
}
func (f walletTraceRepoFake) ListAllocations(ctx context.Context, id uuid.UUID) ([]entities.WalletLotAllocation, error) {
return f.e.repo.ListAllocationsByTransaction(ctx, id)
}
func (f walletTraceRepoFake) ListLotsBySource(ctx context.Context, id uuid.UUID) ([]entities.WalletLot, error) {
return f.e.repo.ListLotsBySourceTransaction(ctx, id)
}
func (f walletTraceRepoFake) GetLots(ctx context.Context, ids []uuid.UUID) ([]entities.WalletLot, error) {
return f.e.repo.GetLotsByIDs(ctx, ids)
}
func (f walletTraceRepoFake) CustomerNames(_ context.Context, ids []uuid.UUID) (map[uuid.UUID]string, error) {
names := map[uuid.UUID]string{}
for _, id := range ids {
if c, ok := f.e.customers.byID[id]; ok {
names[id] = c.Name
}
}
return names, nil
}
func containsID(ids []uuid.UUID, id uuid.UUID) bool {
for _, v := range ids {
if v == id {
return true
}
}
return false
}
func findRow(t *testing.T, e *walletMoveEnv, customerID uuid.UUID, txType string) *entities.WalletTransaction {
t.Helper()
for _, tx := range e.repo.transactions {
if tx.CustomerID == customerID && tx.Type == txType {
return tx
}
}
t.Fatalf("no %s row for %s", txType, customerID)
return nil
}
// The example of §8: A has 100 from #ORD-1 and 50 from #ORD-2, sends 120 to B, and B
// pays 30. Tracing B's payment leads to A's order #ORD-1.
func TestWalletTrace_PaymentLeadsBackToTheSendersOrder(t *testing.T) {
e := newWalletMoveEnv(t)
a := e.member("Anita", "081200005678")
b := e.member("Budi Santoso", "081234561234")
ord1 := earn(a, 100, e.at(30*24*time.Hour))
ord1.Description = "Belanja #ORD-1"
ord2 := earn(a, 50, e.at(60*24*time.Hour))
ord2.Description = "Belanja #ORD-2"
e.credit(t, ord1)
e.credit(t, ord2)
_, err := e.transfers(nil).Transfer(e.ctx, a, sendPoints(120, "081234561234"), "482913", "key-1", models.CustomerPinRequestInfo{})
require.NoError(t, err)
payment, err := e.p.Debit(e.ctx, pay(b, 30))
require.NoError(t, err)
p := NewWalletTraceProcessor(walletTraceRepoFake{e})
trace, err := p.Trace(e.ctx, e.org, payment.Transaction.ID)
require.NoError(t, err)
assert.Equal(t, constants.WalletTxTypePayment, trace.Transaction.Type)
assert.Equal(t, "Budi Santoso", trace.Transaction.Customer.Name)
require.Len(t, trace.Lots, 1)
assert.Equal(t, int64(30), trace.Lots[0].Amount)
chain := trace.Lots[0].Chain
require.Len(t, chain, 2)
assert.Equal(t, constants.WalletTxTypeTransferIn, chain[0].Source.Type)
assert.Equal(t, b, chain[0].Source.Customer.ID)
assert.Equal(t, constants.WalletTxTypeEarn, chain[1].Source.Type)
assert.Equal(t, "Anita", chain[1].Source.Customer.Name)
assert.Equal(t, "Belanja #ORD-1", chain[1].Source.Description)
assert.Equal(t, constants.WalletRefTypeOrder, chain[1].Source.ReferenceType)
assert.Equal(t, ord1.ReferenceID, chain[1].Source.ReferenceID)
assert.Nil(t, chain[1].Lot.OriginLotID, "the chain ends at the lot the order created")
assert.Equal(t, *chain[0].Lot.OriginLotID, chain[1].Lot.ID)
}
func TestWalletTrace_DebitAndCreditOfATransfer(t *testing.T) {
e := newWalletMoveEnv(t)
a := e.member("Anita", "081200005678")
b := e.member("Budi", "081234561234")
e.credit(t, earn(a, 100, e.at(time.Hour)))
e.credit(t, earn(a, 50, nil))
_, err := e.transfers(nil).Transfer(e.ctx, a, sendPoints(120, "081234561234"), "482913", "key-1", models.CustomerPinRequestInfo{})
require.NoError(t, err)
p := NewWalletTraceProcessor(walletTraceRepoFake{e})
// The sending side took from both of A's lots, which were A's own earnings.
out, err := p.Trace(e.ctx, e.org, findRow(t, e, a, constants.WalletTxTypeTransferOut).ID)
require.NoError(t, err)
require.Len(t, out.Lots, 2)
assert.Equal(t, []int64{100, 20}, []int64{out.Lots[0].Amount, out.Lots[1].Amount})
for _, lot := range out.Lots {
require.Len(t, lot.Chain, 1)
assert.Equal(t, constants.WalletTxTypeEarn, lot.Chain[0].Source.Type)
}
// The receiving side created two lots, each carried over from one of A's.
in, err := p.Trace(e.ctx, e.org, findRow(t, e, b, constants.WalletTxTypeTransferIn).ID)
require.NoError(t, err)
require.Len(t, in.Lots, 2)
for _, lot := range in.Lots {
require.Len(t, lot.Chain, 2)
assert.Equal(t, b, lot.Chain[0].Source.Customer.ID)
assert.Equal(t, a, lot.Chain[1].Source.Customer.ID)
assert.Equal(t, lot.Chain[1].Lot.ExpiresAt, lot.Chain[0].Lot.ExpiresAt)
}
}
func TestWalletTrace_OtherOrganizationsRowsAreNotFound(t *testing.T) {
e := newWalletMoveEnv(t)
a := e.member("Anita", "081200005678")
res := e.credit(t, earn(a, 10, nil))
_, err := NewWalletTraceProcessor(walletTraceRepoFake{e}).Trace(e.ctx, uuid.New(), res.Transaction.ID)
assert.ErrorIs(t, err, repository.ErrWalletTransactionNotFound)
}
@@ -0,0 +1,307 @@
package processor
import (
"context"
"errors"
"fmt"
"strconv"
"strings"
"time"
"unicode/utf8"
"github.com/google/uuid"
"apskel-pos-be/internal/constants"
"apskel-pos-be/internal/logger"
"apskel-pos-be/internal/models"
"apskel-pos-be/internal/repository"
)
// ErrWalletRecipientNotFound means no customer of the sender's organization has the
// phone number. A customer of another organization is reported the same way, so the
// check does not reveal who uses the app elsewhere.
var ErrWalletRecipientNotFound = errors.New("no customer of this organization has that phone number")
// customerNotifier pushes a notification to a customer's app through FCM.
// CustomerDeviceProcessor is one.
type customerNotifier interface {
Notify(ctx context.Context, customerID uuid.UUID, title, body string, data map[string]string) error
}
// NotificationTypeWalletTransferIn is the data type of the push a transfer recipient
// gets, so the app can open the transaction.
const NotificationTypeWalletTransferIn = "WALLET_TRANSFER_IN"
// WalletTransferProcessor sends EnakPoint or EnakCoin from one customer to another in
// the same organization (docs/prd-point-coin.md F5).
type WalletTransferProcessor struct {
customers repository.WalletMoveRepository
settings organizationSettingsReader
spendable spendableReader
pins pinVerifier
wallet *WalletProcessor
tx TxRunner
notifier customerNotifier
now func() time.Time
}
func NewWalletTransferProcessor(customers repository.WalletMoveRepository, settings organizationSettingsReader, spendable spendableReader, pins pinVerifier, wallet *WalletProcessor, tx TxRunner, notifier customerNotifier) *WalletTransferProcessor {
return &WalletTransferProcessor{customers: customers, settings: settings, spendable: spendable, pins: pins, wallet: wallet, tx: tx, notifier: notifier, now: time.Now}
}
// Recipient is GET /customer/wallet/transfer/recipient: the masked name and number
// of the customer a phone number belongs to, if the sender may send to them.
func (p *WalletTransferProcessor) Recipient(ctx context.Context, senderID uuid.UUID, phoneNumber string) (*models.WalletTransferRecipient, error) {
sender, err := p.customers.GetCustomer(ctx, senderID)
if err != nil {
return nil, err
}
recipient, err := p.recipient(ctx, sender, phoneNumber)
if err != nil {
return nil, err
}
return maskedRecipient(recipient), nil
}
// Transfer sends in.Amount of in.Currency to the customer with in.RecipientPhone,
// approved by the sender's PIN (K8), and tells the recipient.
//
// Both wallets are locked in customer_id order, so two transfers in opposite
// directions cannot deadlock. TRANSFER_OUT takes from the sender's lots in K9 order,
// and TRANSFER_IN gives the recipient lots with exactly the same expiries, pointing
// back at the sender's lots, so sending a balance back and forth cannot extend it.
// The two rows share a group and name each other's customer.
//
// idempotencyKey is the client's Idempotency-Key: a retry with the same key returns
// the first transfer without moving anything again or counting against the limits.
func (p *WalletTransferProcessor) Transfer(ctx context.Context, senderID uuid.UUID, in models.WalletTransfer, pin, idempotencyKey string, info models.CustomerPinRequestInfo) (*models.WalletTransferResult, error) {
reject := func(format string, args ...any) error {
return fmt.Errorf("%w: %s", ErrWalletMoveRejected, fmt.Sprintf(format, args...))
}
key, err := walletMoveKey(idempotencyKey)
if err != nil {
return nil, err
}
currency := strings.ToUpper(strings.TrimSpace(in.Currency))
if !constants.IsValidWalletCurrency(currency) {
return nil, reject("currency must be POINT or COIN")
}
if in.Amount <= 0 {
return nil, reject("the amount must be positive")
}
sender, err := p.customers.GetCustomer(ctx, senderID)
if err != nil {
return nil, err
}
if !sender.IsActive {
return nil, reject("the customer is not active")
}
settings, err := p.settings.Organization(ctx, sender.OrganizationID)
if err != nil {
return nil, err
}
limits := settings.Transfer
switch {
case !limits.Enabled:
return nil, reject("transfers are turned off")
case in.Amount < limits.MinAmount:
return nil, reject("at least %d can be sent at a time", limits.MinAmount)
case limits.MaxPerTransaction != nil && in.Amount > *limits.MaxPerTransaction:
return nil, reject("at most %d can be sent at a time", *limits.MaxPerTransaction)
}
recipient, err := p.recipient(ctx, sender, in.RecipientPhone)
if err != nil {
return nil, err
}
// Everything the request alone can get wrong is refused above, before the PIN, so
// it costs no attempt. The PIN also refuses a transfer held after a PIN reset.
if err := p.pins.VerifyPin(ctx, senderID, pin, PinActionTransfer, info); err != nil {
return nil, err
}
to, from := maskedRecipient(recipient), maskedRecipient(sender)
outKey := fmt.Sprintf("transfer:%s:%s:out", senderID, key)
inKey := fmt.Sprintf("transfer:%s:%s:in", senderID, key)
result := &models.WalletTransferResult{Currency: currency, Amount: in.Amount, Recipient: *to}
var receivedID uuid.UUID
err = p.tx.WithTransaction(ctx, func(ctx context.Context) error {
if err := p.wallet.LockWallets(ctx, senderID, recipient.ID); err != nil {
return err
}
groupID, outID, inID := uuid.New(), uuid.New(), uuid.New()
previous, err := p.wallet.FindTransaction(ctx, outKey)
if err != nil {
return err
}
if previous != nil {
// A retry: it replays below, so it must not count against the daily limit
// it is already part of.
if previous.CounterpartyCustomerID == nil || *previous.CounterpartyCustomerID != recipient.ID || previous.GroupID == nil {
return ErrWalletIdempotencyConflict
}
outID, inID, groupID = previous.ID, previous.ReferenceID, *previous.GroupID
} else if limits.DailyLimit != nil {
sent, err := p.customers.TransferredOutSince(ctx, senderID, currency, startOfWalletDay(p.now()))
if err != nil {
return err
}
if sent+in.Amount > *limits.DailyLimit {
return reject("at most %d can be sent per day; %d is left today", *limits.DailyLimit, max(*limits.DailyLimit-sent, 0))
}
}
out, err := p.wallet.Debit(ctx, WalletDebitInput{WalletEntry: WalletEntry{
TransactionID: outID,
CustomerID: senderID,
Currency: currency,
Type: constants.WalletTxTypeTransferOut,
Amount: in.Amount,
ReferenceType: constants.WalletRefTypeWalletTx,
ReferenceID: inID,
GroupID: &groupID,
CounterpartyCustomerID: &recipient.ID,
Description: truncateRunes(fmt.Sprintf("Transfer ke %s (%s)", to.Name, to.PhoneNumber), walletDescriptionLimit),
IdempotencyKey: outKey,
}})
if errors.Is(err, repository.ErrWalletInsufficientBalance) {
return reject("not enough %s", walletCurrencyName(currency))
}
if err != nil {
return err
}
received, err := p.wallet.Credit(ctx, WalletCreditInput{
WalletEntry: WalletEntry{
TransactionID: inID,
CustomerID: recipient.ID,
Currency: currency,
Type: constants.WalletTxTypeTransferIn,
Amount: in.Amount,
ReferenceType: constants.WalletRefTypeWalletTx,
ReferenceID: outID,
GroupID: &groupID,
CounterpartyCustomerID: &senderID,
Description: truncateRunes(fmt.Sprintf("Transfer dari %s (%s)", from.Name, from.PhoneNumber), walletDescriptionLimit),
IdempotencyKey: inKey,
},
Lots: out.CarryOver(),
})
if err != nil {
return err
}
result.GroupID = groupID
result.Lots = movedLots(received.Lots)
result.Replayed = out.Replayed
receivedID = received.Transaction.ID
return nil
})
if err != nil {
return nil, err
}
if !result.Replayed {
p.tellRecipient(ctx, recipient.ID, from, currency, in.Amount, receivedID, result.GroupID)
}
balances, err := p.spendable.SpendableBalances(ctx, senderID, p.now())
if err != nil {
return nil, err
}
result.Balance = balances[currency]
return result, nil
}
// recipient finds who a phone number belongs to and checks the sender may send to
// them: an active customer of the same organization, not the walk-in customer, and
// not the sender.
func (p *WalletTransferProcessor) recipient(ctx context.Context, sender *repository.WalletMoveCustomer, phoneNumber string) (*repository.WalletMoveCustomer, error) {
phoneNumber = strings.TrimSpace(phoneNumber)
if phoneNumber == "" {
return nil, fmt.Errorf("%w: the recipient's phone number is required", ErrWalletMoveRejected)
}
recipient, err := p.customers.FindCustomerByPhone(ctx, phoneNumber)
if errors.Is(err, repository.ErrWalletNotFound) {
return nil, ErrWalletRecipientNotFound
}
if err != nil {
return nil, err
}
switch {
case recipient.OrganizationID != sender.OrganizationID:
return nil, ErrWalletRecipientNotFound
case recipient.ID == sender.ID:
return nil, fmt.Errorf("%w: you cannot send to yourself", ErrWalletMoveRejected)
case recipient.IsDefault || !recipient.IsActive:
return nil, fmt.Errorf("%w: this customer cannot receive transfers", ErrWalletMoveRejected)
}
return recipient, nil
}
// tellRecipient pushes the transfer to the recipient's app (F5). It is best effort:
// the transfer has already happened, so a failure to send is only logged.
func (p *WalletTransferProcessor) tellRecipient(ctx context.Context, recipientID uuid.UUID, sender *models.WalletTransferRecipient, currency string, amount int64, transactionID, groupID uuid.UUID) {
if p.notifier == nil {
return
}
name := walletCurrencyName(currency)
title := name + " masuk"
body := fmt.Sprintf("Kamu menerima %d %s dari %s (%s).", amount, name, sender.Name, sender.PhoneNumber)
data := map[string]string{
"type": NotificationTypeWalletTransferIn,
"transaction_id": transactionID.String(),
"group_id": groupID.String(),
"currency": currency,
"amount": strconv.FormatInt(amount, 10),
}
if err := p.notifier.Notify(ctx, recipientID, title, body, data); err != nil {
logger.NonContext.Error(fmt.Sprintf("Could not tell customer %s about a transfer", recipientID), err)
}
}
func maskedRecipient(c *repository.WalletMoveCustomer) *models.WalletTransferRecipient {
phone := ""
if c.PhoneNumber != nil {
phone = maskPhoneNumber(*c.PhoneNumber)
}
return &models.WalletTransferRecipient{Name: maskName(c.Name), PhoneNumber: phone}
}
// maskName keeps the first two letters of each word, "Budi Santoso" → "Bu*** Sa***",
// and one letter of a word that short, so the sender can recognise the recipient
// without the app revealing their name (F5, §8.1).
func maskName(name string) string {
words := strings.Fields(name)
if len(words) == 0 {
return "***"
}
for i, w := range words {
keep := 2
if utf8.RuneCountInString(w) <= 2 {
keep = 1
}
words[i] = string([]rune(w)[:keep]) + "***"
}
return strings.Join(words, " ")
}
// maskPhoneNumber keeps the first two and the last four digits:
// "081234561234" → "08**-****-1234".
func maskPhoneNumber(phone string) string {
runes := []rune(strings.TrimSpace(phone))
if len(runes) < 8 {
return "****"
}
return string(runes[:2]) + "**-****-" + string(runes[len(runes)-4:])
}
func walletCurrencyName(currency string) string {
if currency == constants.WalletCurrencyCoin {
return "EnakCoin"
}
return "EnakPoint"
}
// startOfWalletDay is midnight of t's day in the customer's time zone, where the
// daily transfer limit starts over.
func startOfWalletDay(t time.Time) time.Time {
local := t.In(walletDisplayLocation)
return time.Date(local.Year(), local.Month(), local.Day(), 0, 0, 0, 0, walletDisplayLocation)
}
@@ -0,0 +1,243 @@
package processor
import (
"context"
"errors"
"testing"
"time"
"github.com/google/uuid"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"apskel-pos-be/internal/constants"
"apskel-pos-be/internal/models"
"apskel-pos-be/internal/repository"
)
type pushFake struct {
title, body string
data map[string]string
}
// notifierFake records the pushes each customer would get.
type notifierFake struct{ pushes map[uuid.UUID][]pushFake }
func (f *notifierFake) Notify(_ context.Context, customerID uuid.UUID, title, body string, data map[string]string) error {
if f.pushes == nil {
f.pushes = map[uuid.UUID][]pushFake{}
}
f.pushes[customerID] = append(f.pushes[customerID], pushFake{title: title, body: body, data: data})
return nil
}
func sendPoints(amount int64, phone string) models.WalletTransfer {
return models.WalletTransfer{Currency: constants.WalletCurrencyPoint, Amount: amount, RecipientPhone: phone}
}
func TestWalletTransfer_MovesBalanceWithItsExpiry(t *testing.T) {
e := newWalletMoveEnv(t)
a := e.member("Anita", "081200005678")
b := e.member("Budi Santoso", "081234561234")
dec, jan := e.at(30*24*time.Hour), e.at(60*24*time.Hour)
first := e.credit(t, earn(a, 100, dec))
second := e.credit(t, earn(a, 50, jan))
notifier := &notifierFake{}
// The example in §8: A sends 120, 100 from the lot expiring first and 20 from the next.
res, err := e.transfers(notifier).Transfer(e.ctx, a, sendPoints(120, "081234561234"), "482913", "key-1", models.CustomerPinRequestInfo{})
require.NoError(t, err)
assert.Equal(t, int64(30), res.Balance)
assert.Equal(t, models.WalletTransferRecipient{Name: "Bu*** Sa***", PhoneNumber: "08**-****-1234"}, res.Recipient)
assert.Equal(t, []models.WalletMovedLot{{Amount: 100, ExpiresAt: dec}, {Amount: 20, ExpiresAt: jan}}, res.Lots)
assert.Equal(t, int64(120), e.balance(t, b))
assert.Equal(t, []PinAction{PinActionTransfer}, e.pins.actions)
var bLots []uuid.UUID
for _, lot := range e.repo.lots {
if lot.CustomerID == b {
require.NotNil(t, lot.OriginLotID)
bLots = append(bLots, *lot.OriginLotID)
for _, origin := range e.repo.lots {
if origin.ID == *lot.OriginLotID {
assert.Equal(t, origin.ExpiresAt, lot.ExpiresAt, "the recipient's lot expires exactly when the sender's did")
}
}
}
}
assert.Equal(t, []uuid.UUID{first.Lots[0].ID, second.Lots[0].ID}, bLots)
out, in := e.repo.transactions[2], e.repo.transactions[3]
assert.Equal(t, constants.WalletTxTypeTransferOut, out.Type)
assert.Equal(t, b, *out.CounterpartyCustomerID)
assert.Equal(t, in.ID, out.ReferenceID)
assert.Equal(t, "Transfer ke Bu*** Sa*** (08**-****-1234)", out.Description)
assert.Equal(t, constants.WalletTxTypeTransferIn, in.Type)
assert.Equal(t, a, *in.CounterpartyCustomerID)
assert.Equal(t, out.ID, in.ReferenceID)
assert.Equal(t, *out.GroupID, *in.GroupID)
assert.Equal(t, "Transfer dari An*** (08**-****-5678)", in.Description)
assert.GreaterOrEqual(t, e.repo.locks[a], 1)
assert.GreaterOrEqual(t, e.repo.locks[b], 1)
assert.Equal(t, []pushFake{{
title: "EnakPoint masuk",
body: "Kamu menerima 120 EnakPoint dari An*** (08**-****-5678).",
data: map[string]string{
"type": NotificationTypeWalletTransferIn,
"transaction_id": in.ID.String(),
"group_id": in.GroupID.String(),
"currency": constants.WalletCurrencyPoint,
"amount": "120",
},
}}, notifier.pushes[b])
assert.Empty(t, notifier.pushes[a], "the sender gets no push")
}
func TestWalletTransfer_Coins(t *testing.T) {
e := newWalletMoveEnv(t)
a := e.member("Anita", "081200005678")
b := e.member("Budi", "081234561234")
e.earnCoins(t, a, 10, nil)
_, err := e.transfers(nil).Transfer(e.ctx, a, models.WalletTransfer{Currency: "coin", Amount: 4, RecipientPhone: "081234561234"}, "482913", "key-1", models.CustomerPinRequestInfo{})
require.NoError(t, err)
assert.Equal(t, int64(6), e.coinBalance(t, a))
assert.Equal(t, int64(4), e.coinBalance(t, b))
}
func TestWalletTransfer_RefusesRecipientsItMayNotSendTo(t *testing.T) {
e := newWalletMoveEnv(t)
a := e.member("Anita", "081200005678")
e.credit(t, earn(a, 100, nil))
walkIn := e.member("Walk-in", "081100000000")
e.customers.byID[walkIn].IsDefault = true
inactive := e.member("Old", "081100000001")
e.customers.byID[inactive].IsActive = false
elsewhere := e.member("Other Org", "081100000002")
e.customers.byID[elsewhere].OrganizationID = uuid.New()
for phone, want := range map[string]error{
"081200005678": ErrWalletMoveRejected, // herself
"081100000000": ErrWalletMoveRejected, // the walk-in customer
"081100000001": ErrWalletMoveRejected, // inactive
"081100000002": ErrWalletRecipientNotFound, // another organization looks like nobody
"081999999999": ErrWalletRecipientNotFound,
"": ErrWalletMoveRejected,
} {
_, err := e.transfers(nil).Recipient(e.ctx, a, phone)
assert.ErrorIs(t, err, want, phone)
_, err = e.transfers(nil).Transfer(e.ctx, a, sendPoints(10, phone), "482913", "key-"+phone, models.CustomerPinRequestInfo{})
assert.ErrorIs(t, err, want, phone)
}
assert.Empty(t, e.pins.actions, "refused before the PIN")
assert.Equal(t, int64(100), e.balance(t, a))
}
func TestWalletTransfer_RecipientIsMasked(t *testing.T) {
e := newWalletMoveEnv(t)
a := e.member("Anita", "081200005678")
e.member("Budi Santoso", "081234561234")
got, err := e.transfers(nil).Recipient(e.ctx, a, " 081234561234 ")
require.NoError(t, err)
assert.Equal(t, &models.WalletTransferRecipient{Name: "Bu*** Sa***", PhoneNumber: "08**-****-1234"}, got)
}
func TestWalletTransfer_OrganizationLimits(t *testing.T) {
e := newWalletMoveEnv(t)
a := e.member("Anita", "081200005678")
e.member("Budi", "081234561234")
e.credit(t, earn(a, 1000, nil))
e.settings.Transfer = models.LoyaltyTransferSettings{Enabled: true, MinAmount: 10, MaxPerTransaction: ptr(int64(300)), DailyLimit: ptr(int64(500))}
send := func(amount int64, key string) error {
_, err := e.transfers(nil).Transfer(e.ctx, a, sendPoints(amount, "081234561234"), "482913", key, models.CustomerPinRequestInfo{})
return err
}
assert.ErrorIs(t, send(9, "below-min"), ErrWalletMoveRejected)
assert.ErrorIs(t, send(301, "above-max"), ErrWalletMoveRejected)
require.NoError(t, send(300, "k1"))
require.NoError(t, send(200, "k2"))
// The daily limit is used up; a retry of a transfer already made still replays.
assert.ErrorIs(t, send(10, "k3"), ErrWalletMoveRejected)
require.NoError(t, send(200, "k2"))
// It starts over the next day in the customer's time zone.
e.now = startOfWalletDay(e.now).AddDate(0, 0, 1).Add(time.Minute)
e.repo.clock = e.now
require.NoError(t, send(10, "k4"))
assert.Equal(t, int64(490), e.balance(t, a))
e.settings.Transfer.Enabled = false
assert.ErrorIs(t, send(10, "k5"), ErrWalletMoveRejected)
}
func TestWalletTransfer_HeldAfterPinReset(t *testing.T) {
e := newWalletMoveEnv(t)
a := e.member("Anita", "081200005678")
e.member("Budi", "081234561234")
e.credit(t, earn(a, 100, nil))
until := e.now.Add(time.Hour)
e.pins.err = &PinError{Code: PinErrTransferBlocked, Until: &until}
_, err := e.transfers(nil).Transfer(e.ctx, a, sendPoints(10, "081234561234"), "482913", "key-1", models.CustomerPinRequestInfo{})
var pinErr *PinError
require.True(t, errors.As(err, &pinErr))
assert.Equal(t, PinErrTransferBlocked, pinErr.Code)
assert.Equal(t, int64(100), e.balance(t, a))
}
func TestWalletTransfer_NotEnoughBalance(t *testing.T) {
e := newWalletMoveEnv(t)
a := e.member("Anita", "081200005678")
b := e.member("Budi", "081234561234")
e.credit(t, earn(a, 100, nil))
// An expired lot cannot be sent even before the expiry job takes it.
e.credit(t, earn(a, 50, e.at(-time.Hour)))
_, err := e.transfers(nil).Transfer(e.ctx, a, sendPoints(120, "081234561234"), "482913", "key-1", models.CustomerPinRequestInfo{})
assert.ErrorIs(t, err, ErrWalletMoveRejected)
assert.Equal(t, int64(0), e.balance(t, b))
}
func TestWalletTransfer_RetryMovesNothingAndTellsNobodyAgain(t *testing.T) {
e := newWalletMoveEnv(t)
a := e.member("Anita", "081200005678")
b := e.member("Budi", "081234561234")
e.member("Citra", "081255550000")
e.credit(t, earn(a, 100, nil))
notifier := &notifierFake{}
first, err := e.transfers(notifier).Transfer(e.ctx, a, sendPoints(40, "081234561234"), "482913", "key-1", models.CustomerPinRequestInfo{})
require.NoError(t, err)
again, err := e.transfers(notifier).Transfer(e.ctx, a, sendPoints(40, "081234561234"), "482913", "key-1", models.CustomerPinRequestInfo{})
require.NoError(t, err)
assert.True(t, again.Replayed)
assert.Equal(t, first.GroupID, again.GroupID)
assert.Equal(t, int64(40), e.balance(t, b))
assert.Len(t, notifier.pushes[b], 1)
// The same key to someone else is not a retry.
_, err = e.transfers(notifier).Transfer(e.ctx, a, sendPoints(40, "081255550000"), "482913", "key-1", models.CustomerPinRequestInfo{})
assert.ErrorIs(t, err, ErrWalletIdempotencyConflict)
}
func TestWalletTransfer_UnknownSender(t *testing.T) {
e := newWalletMoveEnv(t)
_, err := e.transfers(nil).Transfer(e.ctx, uuid.New(), sendPoints(1, "081234561234"), "482913", "key-1", models.CustomerPinRequestInfo{})
assert.ErrorIs(t, err, repository.ErrWalletNotFound)
}
func TestMaskName(t *testing.T) {
assert.Equal(t, "Bu*** Sa***", maskName("Budi Santoso"))
assert.Equal(t, "An***", maskName("Anita"))
assert.Equal(t, "A*** Ra***", maskName("Al Rahman"))
assert.Equal(t, "***", maskName(" "))
assert.Equal(t, "08**-****-1234", maskPhoneNumber("081234561234"))
assert.Equal(t, "+6**-****-1234", maskPhoneNumber("+6281234561234"))
assert.Equal(t, "****", maskPhoneNumber("12345"))
}