export type Brand = 'Visa' | 'Mastercard' | 'American Express' | 'Discover';
export type PaymentMethod =
| { id: string; kind: 'card'; brand: Brand; last4: string; expires: string; holder: string; default: boolean }
| { id: string; kind: 'bank'; type: 'checking' | 'savings'; last4: string; holder: string; default: boolean }
| { id: string; kind: 'invoice'; company: string; email: string; terms: number; po: string; status: 'review' | 'active'; default: boolean };
export const digits = (s: string) => s.replace(/\D/g, '');
export const brandOf = (number: string): Brand | null => {
const n = digits(number);
if (/^4/.test(n)) return 'Visa';
if (/^3[47]/.test(n)) return 'American Express';
if (/^(5[1-5]|2(2[2-9][1-9]|[3-6]\d\d|7[01]\d|720))/.test(n)) return 'Mastercard';
if (/^(6011|65|64[4-9])/.test(n)) return 'Discover';
return null;
};
export const luhn = (number: string) => {
const n = digits(number);
let sum = 0;
for (let i = 0; i < n.length; i++) {
let d = Number(n[n.length - 1 - i]);
if (i % 2 === 1) d = d * 2 > 9 ? d * 2 - 9 : d * 2;
sum += d;
}
return n.length > 0 && sum % 10 === 0;
};
// American Express groups 4-6-5; the others group in fours.
export const formatCard = (number: string) => {
const n = digits(number).slice(0, brandOf(number) === 'American Express' ? 15 : 19);
if (brandOf(n) === 'American Express') return [n.slice(0, 4), n.slice(4, 10), n.slice(10)].filter(Boolean).join(' ');
return n.replace(/(.{4})/g, '$1 ').trim();
};
export const cardProblem = (number: string, expiry: string, cvc: string, now: Date) => {
const n = digits(number);
const brand = brandOf(n);
if (!brand) return 'We take Visa, Mastercard, American Express and Discover.';
if (n.length !== (brand === 'American Express' ? 15 : 16) || !luhn(n)) return 'That card number is not valid. Check the digits.';
const m = /^(\d{2})\s*\/\s*(\d{2})$/.exec(expiry.trim());
const month = Number(m?.[1]);
if (!m || month < 1 || month > 12) return 'Enter the expiry as MM/YY.';
const year = 2000 + Number(m[2]);
if (year < now.getUTCFullYear() || (year === now.getUTCFullYear() && month < now.getUTCMonth() + 1)) return 'That card has expired.';
if (digits(cvc).length !== (brand === 'American Express' ? 4 : 3)) return `Enter the ${brand === 'American Express' ? '4' : '3'}-digit security code.`;
return null;
};
// ABA checksum: weights 3, 7, 1 repeating across the nine digits.
export const routingValid = (routing: string) => {
const r = digits(routing);
if (r.length !== 9) return false;
const w = [3, 7, 1];
return [...r].reduce((sum, d, i) => sum + Number(d) * (w[i % 3] ?? 0), 0) % 10 === 0;
};
export const describe = (m: PaymentMethod) =>
m.kind === 'card'
? `${m.brand} ending ${m.last4}`
: m.kind === 'bank'
? `${m.type === 'checking' ? 'Checking' : 'Savings'} account ending ${m.last4}`
: `Invoice to ${m.company}, net ${m.terms}`;