package processor import ( "context" "fmt" "sync" "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" ) // fakeVoucherProvider stands in for a provider. issueMode says what Issue does: // "ok" issues, "reject" refuses, "lost" issues but the answer never arrives, "down" // never gets the request. lookupMode "down" makes Lookup fail as well. type fakeVoucherProvider struct { mu sync.Mutex issueMode string lookupMode string issued map[uuid.UUID]*VoucherIssue issueCalls int } func (f *fakeVoucherProvider) set(issue, lookup string) { f.mu.Lock() defer f.mu.Unlock() f.issueMode, f.lookupMode = issue, lookup } func (f *fakeVoucherProvider) Issue(_ context.Context, req VoucherIssueRequest) (*VoucherIssue, error) { f.mu.Lock() defer f.mu.Unlock() f.issueCalls++ switch f.issueMode { case "reject": return nil, fmt.Errorf("%w: sold out", ErrVoucherProviderRejected) case "down": return nil, context.DeadlineExceeded } issue, ok := f.issued[req.RedemptionID] if !ok { // The redemption id is the provider's idempotency key. issue = &VoucherIssue{Code: fmt.Sprintf("EXT-%d", len(f.issued)+1), Ref: "ref-" + req.RedemptionID.String()[:8]} f.issued[req.RedemptionID] = issue } if f.issueMode == "lost" { return nil, context.DeadlineExceeded } return issue, nil } func (f *fakeVoucherProvider) Lookup(_ context.Context, req VoucherIssueRequest) (*VoucherIssue, error) { f.mu.Lock() defer f.mu.Unlock() if f.lookupMode == "down" { return nil, context.DeadlineExceeded } if issue, ok := f.issued[req.RedemptionID]; ok { return issue, nil } return nil, ErrVoucherProviderNotFound } func (e *enakGameEnv) redemptionStatus(id uuid.UUID) (string, *string, int) { e.t.Helper() var row struct { Status string ExternalCode *string Attempts int } require.NoError(e.t, e.db.Raw(`SELECT status, external_code, attempts FROM voucher_redemptions WHERE id = ?`, id).Scan(&row).Error) return row.Status, row.ExternalCode, row.Attempts } // EG-801, EG-802, EG-803 func TestVoucherRedemption_External(t *testing.T) { e := newEnakGameEnv(t) ctx := e.ctx() external := e.voucher(e.orgA, models.VoucherInput{Name: "Pulsa", FaceValue: 10_000, PointCost: 1_000, StockMode: "EXTERNAL", Provider: ptr("acme"), ProviderRef: ptr("PULSA-10K")}) e.points(e.alice, constants.WalletTxTypeAdjustment, 100_000) refunds := func(id uuid.UUID) int64 { return e.count(`SELECT COUNT(*) FROM wallet_transactions WHERE type = 'REWARD_REDEEM_REFUND' AND reference_id = ?`, id) } // The job works across organizations and other tests may share the database, so // each step checks its own redemption, not the job's totals. recover := func() { t.Helper() _, _, err := e.redeem.RecoverPending(ctx) require.NoError(t, err) } catalog, err := e.redeem.Catalog(ctx, e.alice) require.NoError(t, err) require.Len(t, catalog, 1, "listed: its provider has an adapter") assert.Nil(t, catalog[0].Available) t.Run("issued at once", func(t *testing.T) { e.provider.set("ok", "ok") before := e.pointBalance(e.alice) res, err := e.redeemVoucher(e.alice, external.ID, "ok") require.NoError(t, err) assert.Equal(t, constants.VoucherRedemptionCompleted, res.Status) require.NotNil(t, res.Code) assert.Contains(t, *res.Code, "EXT-") assert.EqualValues(t, before-1_000, res.PointBalance) assert.Len(t, e.costs(res.ID), 1, "the cost is split once issued") }) t.Run("refused: FAILED and the EnakPoint back", func(t *testing.T) { e.provider.set("reject", "ok") before := e.pointBalance(e.alice) res, err := e.redeemVoucher(e.alice, external.ID, "reject") require.NoError(t, err) assert.Equal(t, constants.VoucherRedemptionFailed, res.Status) assert.Nil(t, res.Code) assert.EqualValues(t, before, res.PointBalance) assert.Equal(t, int64(1), refunds(res.ID)) assert.Empty(t, e.costs(res.ID)) var reason string require.NoError(t, e.db.Raw(`SELECT failure_reason FROM voucher_redemptions WHERE id = ?`, res.ID).Scan(&reason).Error) assert.Contains(t, reason, "sold out") // The refund lot points back at the lot the EnakPoint came from. assert.Equal(t, int64(1), e.count(`SELECT COUNT(*) FROM wallet_lots l JOIN wallet_transactions t ON t.id = l.source_transaction_id WHERE t.type = 'REWARD_REDEEM_REFUND' AND t.reference_id = ? AND l.origin_lot_id IS NOT NULL`, res.ID)) }) t.Run("answer lost: PENDING, then the job finds it issued", func(t *testing.T) { e.provider.set("lost", "ok") before := e.pointBalance(e.alice) res, err := e.redeemVoucher(e.alice, external.ID, "lost") require.NoError(t, err) assert.Equal(t, constants.VoucherRedemptionPending, res.Status, "being processed") assert.Nil(t, res.Code) assert.EqualValues(t, before-1_000, e.pointBalance(e.alice), "the EnakPoint stay taken meanwhile") calls := e.provider.issueCalls again, err := e.redeemVoucher(e.alice, external.ID, "lost") require.NoError(t, err) assert.True(t, again.Replayed) assert.Equal(t, constants.VoucherRedemptionPending, again.Status) assert.Equal(t, calls, e.provider.issueCalls, "a retry does not call the provider") recover() status, _, _ := e.redemptionStatus(res.ID) assert.Equal(t, constants.VoucherRedemptionPending, status, "too fresh for the job") e.now = e.now.Add(3 * time.Minute) recover() status, code, _ := e.redemptionStatus(res.ID) assert.Equal(t, constants.VoucherRedemptionCompleted, status) assert.Equal(t, *e.provider.issued[res.ID], VoucherIssue{Code: *code, Ref: e.provider.issued[res.ID].Ref}, "the code the provider issued the first time") assert.Equal(t, calls, e.provider.issueCalls, "found by lookup, not issued again") assert.Len(t, e.costs(res.ID), 1) e.now = e.now.Add(3 * time.Minute) recover() assert.Len(t, e.costs(res.ID), 1, "settled once") }) t.Run("never reached: the job issues it", func(t *testing.T) { e.provider.set("down", "ok") res, err := e.redeemVoucher(e.alice, external.ID, "down") require.NoError(t, err) assert.Equal(t, constants.VoucherRedemptionPending, res.Status) e.provider.set("ok", "ok") e.now = e.now.Add(3 * time.Minute) recover() status, code, _ := e.redemptionStatus(res.ID) assert.Equal(t, constants.VoucherRedemptionCompleted, status) assert.NotNil(t, code) list, err := e.redeem.ListRedemptions(ctx, e.alice, 1, 1) require.NoError(t, err) assert.Equal(t, code, list.Data[0].Code, "the customer sees the provider's code") }) t.Run("no answer at all: refunded once after the last attempt", func(t *testing.T) { e.provider.set("down", "down") before := e.pointBalance(e.alice) res, err := e.redeemVoucher(e.alice, external.ID, "silent") require.NoError(t, err) for attempt := 2; attempt < voucherMaxAttempts; attempt++ { e.now = e.now.Add(3 * time.Minute) recover() status, _, _ := e.redemptionStatus(res.ID) assert.Equal(t, constants.VoucherRedemptionPending, status, "attempt %d", attempt) } status, _, attempts := e.redemptionStatus(res.ID) assert.Equal(t, constants.VoucherRedemptionPending, status) assert.Equal(t, voucherMaxAttempts-1, attempts) // Two instances run the last attempt at once: one refund. e.now = e.now.Add(3 * time.Minute) var wg sync.WaitGroup for i := 0; i < 2; i++ { wg.Add(1) go func() { defer wg.Done() _, _, err := e.redeem.RecoverPending(ctx) assert.NoError(t, err) }() } wg.Wait() status, _, _ = e.redemptionStatus(res.ID) assert.Equal(t, constants.VoucherRedemptionFailed, status) assert.Equal(t, int64(1), refunds(res.ID)) assert.EqualValues(t, before, e.pointBalance(e.alice)) e.now = e.now.Add(3 * time.Minute) recover() assert.Equal(t, int64(1), refunds(res.ID), "running again refunds nothing more") }) }