feat: add manual bank card ledger
Store exact RUB balances, atomic transfers, linked refunds and versioned edits independently of T-Bank. Add migration, HTTP and durability verification.
This commit is contained in:
@@ -0,0 +1,62 @@
|
||||
export type Decimal = { value: bigint; scale: number };
|
||||
|
||||
export function decimalFromString(value: string): Decimal {
|
||||
if (!/^-?(?:0|[1-9]\d*)(?:\.\d+)?$/.test(value))
|
||||
throw new Error('Invalid decimal string');
|
||||
const negative = value.startsWith('-');
|
||||
const [whole, fraction = ''] = (negative ? value.slice(1) : value).split('.');
|
||||
return {
|
||||
value: (negative ? -1n : 1n) * BigInt(`${whole}${fraction}`),
|
||||
scale: fraction.length,
|
||||
};
|
||||
}
|
||||
|
||||
export function add(left: Decimal, right: Decimal): Decimal {
|
||||
const scale = Math.max(left.scale, right.scale);
|
||||
return {
|
||||
value:
|
||||
left.value * 10n ** BigInt(scale - left.scale) +
|
||||
right.value * 10n ** BigInt(scale - right.scale),
|
||||
scale,
|
||||
};
|
||||
}
|
||||
|
||||
export function subtract(left: Decimal, right: Decimal): Decimal {
|
||||
return add(left, { value: -right.value, scale: right.scale });
|
||||
}
|
||||
|
||||
export function multiply(left: Decimal, right: Decimal): Decimal {
|
||||
return { value: left.value * right.value, scale: left.scale + right.scale };
|
||||
}
|
||||
|
||||
export function isZero(value: Decimal): boolean {
|
||||
return value.value === 0n;
|
||||
}
|
||||
|
||||
export function compare(left: Decimal, right: Decimal): number {
|
||||
const difference = subtract(left, right).value;
|
||||
return difference === 0n ? 0 : difference > 0n ? 1 : -1;
|
||||
}
|
||||
|
||||
export function formatDecimal({ value, scale }: Decimal): string {
|
||||
if (value === 0n) return '0';
|
||||
const sign = value < 0n ? '-' : '';
|
||||
if (scale === 0) return `${sign}${value < 0n ? -value : value}`;
|
||||
const digits = (value < 0n ? -value : value)
|
||||
.toString()
|
||||
.padStart(scale + 1, '0');
|
||||
const whole = digits.slice(0, -scale) || '0';
|
||||
const fraction = digits.slice(-scale).replace(/0+$/, '');
|
||||
return `${sign}${whole}${fraction ? `.${fraction}` : ''}`;
|
||||
}
|
||||
|
||||
// Round half away from zero; callers choose presentation precision explicitly.
|
||||
export function divide(left: Decimal, right: Decimal, scale: number): Decimal {
|
||||
if (right.value === 0n) throw new Error('Division by zero');
|
||||
const numerator = left.value * 10n ** BigInt(right.scale + scale);
|
||||
const denominator = right.value * 10n ** BigInt(left.scale);
|
||||
const sign = numerator < 0n !== denominator < 0n ? -1n : 1n;
|
||||
const n = numerator < 0n ? -numerator : numerator;
|
||||
const d = denominator < 0n ? -denominator : denominator;
|
||||
return { value: sign * ((n + d / 2n) / d), scale };
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
import { ApiProperty } from '@nestjs/swagger';
|
||||
|
||||
export class MoneyDto {
|
||||
@ApiProperty()
|
||||
currency: string;
|
||||
|
||||
@ApiProperty()
|
||||
value: string;
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
import { parseRubMoney, rubMoney } from './rub-money';
|
||||
|
||||
describe('RUB money', () => {
|
||||
it.each([
|
||||
['0', 0n],
|
||||
['-100', -10000n],
|
||||
['0.01', 1n],
|
||||
['123.4', 12340n],
|
||||
['90071992547409.93', 9007199254740993n],
|
||||
['92233720368547758.07', 2n ** 63n - 1n],
|
||||
['-92233720368547758.08', -(2n ** 63n)],
|
||||
])('roundtrips %s exactly', (value, kopecks) => {
|
||||
expect(parseRubMoney({ currency: 'RUB', value })).toBe(kopecks);
|
||||
expect(rubMoney(kopecks)).toEqual({ currency: 'RUB', value });
|
||||
});
|
||||
|
||||
it.each([
|
||||
'92233720368547758.08',
|
||||
'-92233720368547758.09',
|
||||
'1.001',
|
||||
'1.000',
|
||||
'NaN',
|
||||
'Infinity',
|
||||
'1e2',
|
||||
'1,23',
|
||||
'',
|
||||
' 1',
|
||||
'1\n',
|
||||
'01',
|
||||
])('rejects invalid input %s without rounding', (value) => {
|
||||
expect(() => parseRubMoney({ currency: 'RUB', value })).toThrow();
|
||||
});
|
||||
|
||||
it('rejects other currencies and non-string values', () => {
|
||||
expect(() => parseRubMoney({ currency: 'USD', value: '1' })).toThrow();
|
||||
expect(() =>
|
||||
parseRubMoney({ currency: 'RUB', value: 1 as unknown as string }),
|
||||
).toThrow();
|
||||
});
|
||||
|
||||
it('requires positive operation amounts, including at the maximum', () => {
|
||||
for (const value of ['0', '-0.00', '-0.01'])
|
||||
expect(() => parseRubMoney({ currency: 'RUB', value }, true)).toThrow();
|
||||
expect(parseRubMoney({ currency: 'RUB', value: '0.01' }, true)).toBe(1n);
|
||||
expect(
|
||||
parseRubMoney({ currency: 'RUB', value: '92233720368547758.07' }, true),
|
||||
).toBe(2n ** 63n - 1n);
|
||||
});
|
||||
|
||||
it('formats computed sums beyond the storage range without losing precision', () => {
|
||||
expect(rubMoney(2n * (2n ** 63n - 1n))).toEqual({
|
||||
currency: 'RUB',
|
||||
value: '184467440737095516.14',
|
||||
});
|
||||
expect(rubMoney(-1n)).toEqual({ currency: 'RUB', value: '-0.01' });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,27 @@
|
||||
import { decimalFromString, formatDecimal } from './decimal';
|
||||
import { MoneyDto } from './money.dto';
|
||||
|
||||
export function parseRubMoney(money: MoneyDto, positive = false): bigint {
|
||||
if (
|
||||
money?.currency !== 'RUB' ||
|
||||
typeof money.value !== 'string' ||
|
||||
money.value !== money.value.trim()
|
||||
)
|
||||
throw new TypeError('Expected RUB money with a decimal string');
|
||||
const amount = decimalFromString(money.value);
|
||||
if (amount.scale > 2)
|
||||
throw new RangeError('RUB money supports at most two decimal places');
|
||||
const kopecks = amount.value * 10n ** BigInt(2 - amount.scale);
|
||||
if (kopecks < -(2n ** 63n) || kopecks > 2n ** 63n - 1n)
|
||||
throw new RangeError('RUB money is outside the signed 64-bit range');
|
||||
if (positive && kopecks <= 0n)
|
||||
throw new RangeError('Operation amount must be positive');
|
||||
return kopecks;
|
||||
}
|
||||
|
||||
export function rubMoney(kopecks: bigint): MoneyDto {
|
||||
return {
|
||||
currency: 'RUB',
|
||||
value: formatDecimal({ value: kopecks, scale: 2 }),
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user