Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions app/stores/__tests__/creditStore.performance.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { useCreditStore } from '../creditStore';

describe('credit store performance', () => {
it('processes 100 credit applications within the local budget', () => {
useCreditStore.setState({
accounts: {},
nextId: 0,
wallets: {},
nextWalletId: 0,
walletTransactionIds: {},
now: () => 1_000,
});
const store = useCreditStore.getState();
const startedAt = performance.now();

for (let index = 0; index < 100; index += 1) {
store.issueCredit(`subscriber-${index}`, 100, 'benchmark');
store.applyCredit(`subscriber-${index}`, `subscription-${index}`, 50);
}

expect(performance.now() - startedAt).toBeLessThan(1_500);
});
});
66 changes: 65 additions & 1 deletion app/stores/__tests__/creditStore.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,14 @@ import { useCreditStore } from '../creditStore';

let clock = 1000;
const reset = () =>
useCreditStore.setState({ accounts: {}, nextId: 0, now: () => clock });
useCreditStore.setState({
accounts: {},
nextId: 0,
wallets: {},
nextWalletId: 0,
walletTransactionIds: {},
now: () => clock,
});

beforeEach(() => {
clock = 1000;
Expand Down Expand Up @@ -66,4 +73,61 @@ describe('useCreditStore', () => {
clock = 1200;
expect(s().getBalance('alice')).toBe(0);
});

it('manages wallet deposits, withdrawals, and charge drawdowns', () => {
const walletId = s().createWallet('alice', 'sub_1', 'USD');
expect(s().deposit('alice', walletId, 1000)).toMatchObject({
walletId,
balance: 1000,
transactionId: 0,
});
expect(s().drawdown('alice', walletId, 250)).toMatchObject({
balance: 750,
transactionId: 1,
});
expect(s().withdraw('alice', walletId, 100)).toMatchObject({
balance: 650,
transactionId: 2,
});
expect(s().getWallet(walletId)).toMatchObject({
balance: 650,
totalDeposited: 1000,
totalDrawn: 250,
totalWithdrawn: 100,
transactions: [
{ id: 0, kind: 'deposit', amount: 1000, balanceAfter: 1000 },
{ id: 1, kind: 'drawdown', amount: 250, balanceAfter: 750 },
{ id: 2, kind: 'withdraw', amount: 100, balanceAfter: 650 },
],
});
});

it('rejects unauthorized and overdrawn wallet operations', () => {
const walletId = s().createWallet('alice', 'sub_1', 'USD');
s().deposit('alice', walletId, 100);
expect(s().drawdown('alice', walletId, 101)).toBeUndefined();
expect(s().withdraw('bob', walletId, 1)).toBeUndefined();
});

it('does not expose mutable account or wallet state', () => {
s().issueCredit('alice', 100, 'promo');
const account = s().getAccount('alice');
account.lots[0].remaining = 0;
expect(s().getBalance('alice')).toBe(100);

const walletId = s().createWallet('alice', 'sub_1', 'USD');
const wallet = s().getWallet(walletId);
if (wallet) wallet.balance = 99;
expect(s().getWallet(walletId)?.balance).toBe(0);
});

it('retains only the bounded recent transaction history', () => {
for (let index = 0; index < 130; index += 1) {
s().issueCredit('alice', 1, `grant-${index}`);
}
const history = s().getAccount('alice').transactions;
expect(history).toHaveLength(128);
expect(history[0].reason).toBe('grant-2');
expect(history[127].reason).toBe('grant-129');
});
});
165 changes: 157 additions & 8 deletions app/stores/creditStore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,40 @@ export interface CreditApplied {
balanceAfter: number;
}

export interface PrepaymentWallet {
id: number;
subscriber: string;
subscriptionId: string;
currency: string;
balance: number;
totalDeposited: number;
totalWithdrawn: number;
totalDrawn: number;
transactions: PrepaymentTransaction[];
createdAt: number;
updatedAt: number;
}

export type PrepaymentTxKind = 'deposit' | 'withdraw' | 'drawdown';

export interface PrepaymentTransaction {
id: number;
kind: PrepaymentTxKind;
amount: number;
balanceAfter: number;
timestamp: number;
}

export interface PrepaymentSnapshot {
walletId: number;
balance: number;
transactionId: number;
}

const MAX_HISTORY = 128;

const isPositiveAmount = (amount: number): boolean => Number.isFinite(amount) && amount > 0;

const isExpired = (lot: CreditLot, now: number): boolean =>
lot.expiresAt !== undefined && lot.expiresAt <= now;

Expand All @@ -58,6 +92,9 @@ const availableOf = (account: AccountCredit, now: number): number =>
interface CreditStoreState {
accounts: Record<string, AccountCredit>;
nextId: number;
wallets: Record<number, PrepaymentWallet>;
nextWalletId: number;
walletTransactionIds: Record<number, number>;
now: () => number;

issueCredit: (subscriber: string, amount: number, reason: string, expiresAt?: number) => void;
Expand All @@ -67,6 +104,11 @@ interface CreditStoreState {
expireCredits: (subscriber: string) => number;
getBalance: (subscriber: string) => number;
getAccount: (subscriber: string) => AccountCredit;
createWallet: (subscriber: string, subscriptionId: string, currency: string) => number;
getWallet: (walletId: number) => PrepaymentWallet | undefined;
deposit: (subscriber: string, walletId: number, amount: number) => PrepaymentSnapshot | undefined;
withdraw: (subscriber: string, walletId: number, amount: number) => PrepaymentSnapshot | undefined;
drawdown: (subscriber: string, walletId: number, amount: number) => PrepaymentSnapshot | undefined;
}

const blankAccount = (subscriber: string): AccountCredit => ({
Expand Down Expand Up @@ -103,7 +145,7 @@ export const useCreditStore = create<CreditStoreState>()(
acc.transactions = [
...acc.transactions,
{ id: nextId(), kind, amount, timestamp: get().now(), reason, counterparty },
];
].slice(-MAX_HISTORY);
};

const realizeExpiry = (acc: AccountCredit, now: number): number => {
Expand Down Expand Up @@ -135,17 +177,47 @@ export const useCreditStore = create<CreditStoreState>()(

const cloneAccount = (acc: AccountCredit): AccountCredit => ({
...acc,
lots: [...acc.lots],
transactions: [...acc.transactions],
lots: acc.lots.map((lot) => ({ ...lot })),
transactions: acc.transactions.map((transaction) => ({ ...transaction })),
});

const nextWalletTransactionId = (walletId: number): number => {
const id = get().walletTransactionIds[walletId] ?? 0;
set((state) => ({
walletTransactionIds: { ...state.walletTransactionIds, [walletId]: id + 1 },
}));
return id;
};

const recordWalletTransaction = (
wallet: PrepaymentWallet,
kind: PrepaymentTxKind,
amount: number
): PrepaymentSnapshot => {
const transactionId = nextWalletTransactionId(wallet.id);
wallet.transactions = [
...wallet.transactions,
{
id: transactionId,
kind,
amount,
balanceAfter: wallet.balance,
timestamp: get().now(),
},
].slice(-MAX_HISTORY);
return { walletId: wallet.id, balance: wallet.balance, transactionId };
};

return {
accounts: {},
nextId: 0,
wallets: {},
nextWalletId: 0,
walletTransactionIds: {},
now: () => Math.floor(Date.now() / 1000),

issueCredit: (subscriber, amount, reason, expiresAt) => {
if (amount <= 0) return;
if (!isPositiveAmount(amount)) return;
const now = get().now();
const acc = cloneAccount(account(subscriber));
realizeExpiry(acc, now);
Expand All @@ -169,7 +241,8 @@ export const useCreditStore = create<CreditStoreState>()(
const now = get().now();
const acc = cloneAccount(account(subscriber));
realizeExpiry(acc, now);
const applied = consume(acc, now, Math.max(0, amountDue));
const due = Number.isFinite(amountDue) ? Math.max(0, amountDue) : 0;
const applied = consume(acc, now, due);
if (applied > 0) {
acc.balance -= applied;
record(acc, 'apply', -applied, 'charge_application');
Expand All @@ -178,13 +251,13 @@ export const useCreditStore = create<CreditStoreState>()(
return {
subscriptionId,
applied,
remainingDue: amountDue - applied,
remainingDue: due - applied,
balanceAfter: acc.balance,
};
},

transferCredit: (from, to, amount, reason) => {
if (amount <= 0 || from === to) return false;
if (!isPositiveAmount(amount) || from === to) return false;
const now = get().now();
const sender = cloneAccount(account(from));
realizeExpiry(sender, now);
Expand Down Expand Up @@ -216,7 +289,80 @@ export const useCreditStore = create<CreditStoreState>()(
},

getBalance: (subscriber) => availableOf(account(subscriber), get().now()),
getAccount: (subscriber) => account(subscriber),
getAccount: (subscriber) => cloneAccount(account(subscriber)),

createWallet: (subscriber, subscriptionId, currency) => {
const id = get().nextWalletId;
const now = get().now();
const wallet: PrepaymentWallet = {
id,
subscriber,
subscriptionId,
currency,
balance: 0,
totalDeposited: 0,
totalWithdrawn: 0,
totalDrawn: 0,
transactions: [],
createdAt: now,
updatedAt: now,
};
set((state) => ({
wallets: { ...state.wallets, [id]: wallet },
nextWalletId: id + 1,
}));
return id;
},

getWallet: (walletId) => {
const wallet = get().wallets[walletId];
return wallet ? { ...wallet } : undefined;
},

deposit: (subscriber, walletId, amount) => {
if (!isPositiveAmount(amount)) return undefined;
const wallet = get().wallets[walletId];
if (!wallet || wallet.subscriber !== subscriber) return undefined;
const updated = {
...wallet,
balance: wallet.balance + amount,
totalDeposited: wallet.totalDeposited + amount,
updatedAt: get().now(),
};
const snapshot = recordWalletTransaction(updated, 'deposit', amount);
set((state) => ({ wallets: { ...state.wallets, [walletId]: updated } }));
return snapshot;
},

withdraw: (subscriber, walletId, amount) => {
if (!isPositiveAmount(amount)) return undefined;
const wallet = get().wallets[walletId];
if (!wallet || wallet.subscriber !== subscriber || wallet.balance < amount) return undefined;
const updated = {
...wallet,
balance: wallet.balance - amount,
totalWithdrawn: wallet.totalWithdrawn + amount,
updatedAt: get().now(),
};
const snapshot = recordWalletTransaction(updated, 'withdraw', amount);
set((state) => ({ wallets: { ...state.wallets, [walletId]: updated } }));
return snapshot;
},

drawdown: (subscriber, walletId, amount) => {
if (!isPositiveAmount(amount)) return undefined;
const wallet = get().wallets[walletId];
if (!wallet || wallet.subscriber !== subscriber || wallet.balance < amount) return undefined;
const updated = {
...wallet,
balance: wallet.balance - amount,
totalDrawn: wallet.totalDrawn + amount,
updatedAt: get().now(),
};
const snapshot = recordWalletTransaction(updated, 'drawdown', amount);
set((state) => ({ wallets: { ...state.wallets, [walletId]: updated } }));
return snapshot;
},
};
},
{
Expand All @@ -225,6 +371,9 @@ export const useCreditStore = create<CreditStoreState>()(
partialize: (state) => ({
accounts: state.accounts,
nextId: state.nextId,
wallets: state.wallets,
nextWalletId: state.nextWalletId,
walletTransactionIds: state.walletTransactionIds,
}),
}
)
Expand Down
30 changes: 30 additions & 0 deletions app/tests/integration/credit-wallet.integration.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import { useCreditStore } from '../../stores/creditStore';

describe('credit wallet integration', () => {
beforeEach(() => {
useCreditStore.setState({
accounts: {},
nextId: 0,
wallets: {},
nextWalletId: 0,
walletTransactionIds: {},
now: () => 1_000,
});
});

it('keeps wallet balance, receipts, and account credit independent', () => {
const store = useCreditStore.getState();
const walletId = store.createWallet('alice', 'sub_1', 'USD');

store.issueCredit('alice', 500, 'refund');
const deposit = store.deposit('alice', walletId, 1_000);
const drawdown = store.drawdown('alice', walletId, 250);
const applied = store.applyCredit('alice', 'sub_1', 200);

expect(deposit?.balance).toBe(1_000);
expect(drawdown?.balance).toBe(750);
expect(applied).toMatchObject({ applied: 200, remainingDue: 0, balanceAfter: 300 });
expect(useCreditStore.getState().getWallet(walletId)?.transactions).toHaveLength(2);
expect(useCreditStore.getState().getBalance('alice')).toBe(300);
});
});
Loading