diff --git a/app.js b/app.js index aede8be..bc23667 100644 --- a/app.js +++ b/app.js @@ -1,3 +1,4 @@ +import { createLedger } from './ledger/create-ledger.js'; import { OrderRepository } from './orders/order-repository.js'; import { CardGateway } from './payments/card-gateway.js'; import { PaymentService } from './payments/payment-service.js'; @@ -12,12 +13,13 @@ import { FinanceExport } from './finance/reconciliation.js'; export function createCommerce() { const orders = new OrderRepository(); const cardGateway = new CardGateway(); - const payments = new PaymentService(cardGateway); + const ledger = createLedger(); + const payments = new PaymentService(cardGateway, ledger); const notifications = new NotificationService(); - const refunds = new RefundService(orders, payments, new RefundPolicy(), notifications); - const checkout = new CheckoutApi(orders, refunds, payments); - const storefront = new StorefrontAccount(checkout); + const refunds = new RefundService(orders, ledger, new RefundPolicy(), notifications); + const checkout = new CheckoutApi(orders, refunds, payments, ledger); + const storefront = new StorefrontAccount(checkout, ledger); const support = new SupportConsole(refunds); const finance = new FinanceExport(orders, payments); - return { orders, cardGateway, payments, notifications, refunds, checkout, storefront, support, finance }; + return { orders, cardGateway, payments, notifications, refunds, checkout, storefront, support, finance, ledger }; } diff --git a/checkout/checkout-api.js b/checkout/checkout-api.js index b1d7efb..d5f728f 100644 --- a/checkout/checkout-api.js +++ b/checkout/checkout-api.js @@ -1,12 +1,14 @@ +import { createLedger } from '../ledger/create-ledger.js'; import { OrderRepository } from '../orders/order-repository.js'; import { RefundService } from '../refunds/refund-service.js'; import { PaymentService } from '../payments/payment-service.js'; export class CheckoutApi { - constructor(orders = new OrderRepository(), refunds = new RefundService(), payments = new PaymentService()) { + constructor(orders = new OrderRepository(), refunds = new RefundService(), payments = new PaymentService(), ledger = createLedger()) { this.orders = orders; this.refunds = refunds; this.payments = payments; + this.ledger = ledger; } requestRefund(customerId, request) { @@ -18,6 +20,6 @@ export class CheckoutApi { accountSummary(customerId) { const orders = this.orders.list().filter(order => order.customerId === customerId); const cardRefunds = orders.flatMap(order => this.payments.refundsForOrder(order)); - return { customerId, orders, cardRefunds, storeCredit: 0 }; + return { customerId, orders, cardRefunds, storeCredit: this.ledger.balance(customerId, 'EUR') }; } } diff --git a/ledger/account-repository.js b/ledger/account-repository.js new file mode 100644 index 0000000..b9e8c2d --- /dev/null +++ b/ledger/account-repository.js @@ -0,0 +1,10 @@ +export class LedgerAccountRepository { + #accounts = new Map(); + + forCustomer(customerId, currency) { + if (!customerId) throw new Error('Customer ID required'); + const key = `${customerId}:${currency}`; + if (!this.#accounts.has(key)) this.#accounts.set(key, { id: key, customerId, currency }); + return { ...this.#accounts.get(key) }; + } +} diff --git a/ledger/balance-reader.js b/ledger/balance-reader.js new file mode 100644 index 0000000..cad4f48 --- /dev/null +++ b/ledger/balance-reader.js @@ -0,0 +1,11 @@ +import { LedgerEntryRepository } from './entry-repository.js'; + +export class LedgerBalanceReader { + constructor(entries = new LedgerEntryRepository()) { this.entries = entries; } + + availableCredit(accountId) { + return this.entries.forAccount(accountId) + .filter(entry => entry.kind === 'refund-credit') + .reduce((total, entry) => total + entry.amount, 0); + } +} diff --git a/ledger/create-ledger.js b/ledger/create-ledger.js new file mode 100644 index 0000000..a9bf97a --- /dev/null +++ b/ledger/create-ledger.js @@ -0,0 +1,13 @@ +import { LedgerAccountRepository } from './account-repository.js'; +import { LedgerEntryRepository } from './entry-repository.js'; +import { LedgerBalanceReader } from './balance-reader.js'; +import { LedgerOutbox } from './outbox.js'; +import { LedgerService } from './ledger-service.js'; + +export function createLedger() { + const accounts = new LedgerAccountRepository(); + const entries = new LedgerEntryRepository(); + const balances = new LedgerBalanceReader(entries); + const outbox = new LedgerOutbox(); + return new LedgerService(accounts, entries, balances, outbox); +} diff --git a/ledger/entry-repository.js b/ledger/entry-repository.js new file mode 100644 index 0000000..922acb9 --- /dev/null +++ b/ledger/entry-repository.js @@ -0,0 +1,14 @@ +export class LedgerEntryRepository { + #entries = new Map(); + + insert(entry) { + const existing = this.#entries.get(entry.id); + if (existing && JSON.stringify(existing) !== JSON.stringify(entry)) throw new Error('Entry ID conflict'); + this.#entries.set(entry.id, { ...entry }); + return { ...entry }; + } + + forAccount(accountId) { + return [...this.#entries.values()].filter(entry => entry.accountId === accountId).map(entry => ({ ...entry })); + } +} diff --git a/ledger/ledger-service.js b/ledger/ledger-service.js new file mode 100644 index 0000000..abef9ce --- /dev/null +++ b/ledger/ledger-service.js @@ -0,0 +1,42 @@ +import { LedgerAccountRepository } from './account-repository.js'; +import { LedgerEntryRepository } from './entry-repository.js'; +import { LedgerBalanceReader } from './balance-reader.js'; +import { LedgerOutbox } from './outbox.js'; +import { assertAmount } from '../shared/money.js'; + +/** Posts commerce money events and exposes customers' available store credit. */ +export class LedgerService { + constructor(accounts = new LedgerAccountRepository(), entries = new LedgerEntryRepository(), balances = new LedgerBalanceReader(entries), outbox = new LedgerOutbox()) { + this.accounts = accounts; + this.entries = entries; + this.balances = balances; + this.outbox = outbox; + } + + creditRefund(order, amount, requestId) { + assertAmount(amount, order.currency); + const account = this.accounts.forCustomer(order.customerId, order.currency); + const entry = this.entries.insert({ + id: `ledger-${requestId}`, accountId: account.id, amount, currency: order.currency, + kind: 'refund-credit', orderId: order.id, destination: 'store-credit', + }); + this.outbox.enqueue(entry); + return entry; + } + + recordSettlement(order, requestId) { + assertAmount(order.paidAmount, order.currency); + const account = this.accounts.forCustomer(order.customerId, order.currency); + const entry = this.entries.insert({ + id: `settlement-${requestId}`, accountId: account.id, amount: order.paidAmount, + currency: order.currency, kind: 'card-settlement', orderId: order.id, + }); + this.outbox.enqueue(entry); + return entry; + } + + balance(customerId, currency) { + const account = this.accounts.forCustomer(customerId, currency); + return this.balances.availableCredit(account.id); + } +} diff --git a/ledger/outbox.js b/ledger/outbox.js new file mode 100644 index 0000000..b2449d3 --- /dev/null +++ b/ledger/outbox.js @@ -0,0 +1,11 @@ +export class LedgerOutbox { + #events = new Map(); + + enqueue(entry) { + const event = { id: `event-${entry.id}`, kind: 'ledger.entry.posted', entryId: entry.id, accountId: entry.accountId }; + this.#events.set(event.id, event); + return { ...event }; + } + + pending() { return [...this.#events.values()].map(event => ({ ...event })); } +} diff --git a/payments/payment-service.js b/payments/payment-service.js index 3ce54d7..2622bbd 100644 --- a/payments/payment-service.js +++ b/payments/payment-service.js @@ -1,7 +1,15 @@ +import { createLedger } from '../ledger/create-ledger.js'; import { CardGateway } from './card-gateway.js'; export class PaymentService { - constructor(cardGateway = new CardGateway()) { this.cardGateway = cardGateway; } + constructor(cardGateway = new CardGateway(), ledger = createLedger()) { + this.cardGateway = cardGateway; + this.ledger = ledger; + } + + recordSettlement(order, requestId) { + return this.ledger.recordSettlement(order, requestId); + } refundOriginalPayment(order, amount, requestId) { return this.cardGateway.reverseCharge({ paymentId: order.paymentId, amount, currency: order.currency, requestId }); diff --git a/refunds/refund-service.js b/refunds/refund-service.js index b30240b..ed55d2a 100644 --- a/refunds/refund-service.js +++ b/refunds/refund-service.js @@ -1,14 +1,14 @@ import { OrderRepository } from '../orders/order-repository.js'; -import { PaymentService } from '../payments/payment-service.js'; +import { createLedger } from '../ledger/create-ledger.js'; import { RefundPolicy } from './refund-policy.js'; import { NotificationService } from '../notifications/notification-service.js'; export class RefundService { #requests = new Map(); - constructor(orders = new OrderRepository(), payments = new PaymentService(), policy = new RefundPolicy(), notifications = new NotificationService()) { + constructor(orders = new OrderRepository(), ledger = createLedger(), policy = new RefundPolicy(), notifications = new NotificationService()) { this.orders = orders; - this.payments = payments; + this.ledger = ledger; this.policy = policy; this.notifications = notifications; } @@ -22,8 +22,8 @@ export class RefundService { } const order = this.orders.get(orderId); this.policy.validate(order, amount); - const paymentRefund = this.payments.refundOriginalPayment(order, amount, requestId); - const refund = { ...paymentRefund, orderId, customerId: order.customerId, status: 'completed' }; + const ledgerEntry = this.ledger.creditRefund(order, amount, requestId); + const refund = { ...ledgerEntry, orderId, customerId: order.customerId, status: 'completed' }; this.orders.recordRefund(orderId, refund); this.notifications.sendRefundReceipt(refund); this.#requests.set(requestId, refund); diff --git a/storefront/account-page.js b/storefront/account-page.js index b9bbbf0..8300adc 100644 --- a/storefront/account-page.js +++ b/storefront/account-page.js @@ -1,16 +1,20 @@ +import { createLedger } from '../ledger/create-ledger.js'; import { CheckoutApi } from '../checkout/checkout-api.js'; import { formatMoney } from '../shared/money.js'; /** Account view model consumed by the storefront UI. */ export class StorefrontAccount { - constructor(checkout = new CheckoutApi()) { this.checkout = checkout; } + constructor(checkout = new CheckoutApi(), ledger = createLedger()) { + this.checkout = checkout; + this.ledger = ledger; + } refundOrder(customerId, orderId, amount, requestId) { return this.checkout.requestRefund(customerId, { orderId, amount, requestId }); } renderBalance(customerId, currency = 'EUR') { - const summary = this.checkout.accountSummary(customerId); - return `Store credit: ${formatMoney(summary.storeCredit, currency)}`; + const availableCredit = this.ledger.balance(customerId, currency); + return `Store credit: ${formatMoney(availableCredit, currency)}`; } } diff --git a/tests/ledger.test.js b/tests/ledger.test.js new file mode 100644 index 0000000..9abdca8 --- /dev/null +++ b/tests/ledger.test.js @@ -0,0 +1,38 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { createLedger } from '../ledger/create-ledger.js'; + +const order = { id: 'order-1042', customerId: 'customer-demo', paidAmount: 12900, currency: 'EUR' }; + +test('a posted refund is immediately available as store credit', () => { + const ledger = createLedger(); + ledger.creditRefund(order, 4900, 'r-1'); + assert.equal(ledger.balance(order.customerId, 'EUR'), 4900); +}); + +test('reposting the same refund does not double the balance', () => { + const ledger = createLedger(); + ledger.creditRefund(order, 4900, 'r-1'); + ledger.creditRefund(order, 4900, 'r-1'); + assert.equal(ledger.balance(order.customerId, 'EUR'), 4900); + assert.equal(ledger.outbox.pending().length, 1); +}); + +test('settlements do not become spendable customer credit', () => { + const ledger = createLedger(); + ledger.recordSettlement(order, 's-1'); + assert.equal(ledger.balance(order.customerId, 'EUR'), 0); +}); + +test('credit is isolated by customer and currency', () => { + const ledger = createLedger(); + ledger.creditRefund(order, 4900, 'r-1'); + assert.equal(ledger.balance('another-customer', 'EUR'), 0); + assert.equal(ledger.balance(order.customerId, 'CHF'), 0); +}); + +test('conflicting ledger entry IDs are rejected', () => { + const ledger = createLedger(); + ledger.creditRefund(order, 4900, 'r-1'); + assert.throws(() => ledger.creditRefund(order, 5100, 'r-1'), /conflict/); +}); diff --git a/tests/refunds.test.js b/tests/refunds.test.js index 9346836..7b79ae5 100644 --- a/tests/refunds.test.js +++ b/tests/refunds.test.js @@ -8,12 +8,11 @@ function fixture() { return app; } -test('a refund returns money to the original card', () => { +test('an instant refund updates the account balance', () => { const app = fixture(); const result = app.storefront.refundOrder('customer-demo', 'order-1042', 4900, 'refund-demo'); - assert.equal(result.destination, 'original-card'); - assert.equal(app.cardGateway.listReversals()[0].amount, 4900); - assert.equal(app.finance.reconcile()[0].discrepancy, 0); + assert.equal(result.status, 'completed'); + assert.equal(app.ledger.balance('customer-demo', 'EUR'), 4900); }); test('a retry does not refund the card twice', () => {