TypeScript
feat: add Withdrawal methods page
Vipul Kumarf1d7e963baa9
diff --git a/src/app/withdrawal-methods/page.tsx b/src/app/withdrawal-methods/page.tsxnew file mode 100644index 0000000..d2effaa--- /dev/null+++ b/src/app/withdrawal-methods/page.tsx@@ -0,0 +1,8 @@+import type { Metadata } from "next";+import { WithdrawalMethodsPage } from "@/components/pages/withdrawal-methods/withdrawal-methods-page";++export const metadata: Metadata = { title: "Withdrawal methods" };++export default function Page() {+ return <WithdrawalMethodsPage />;+}diff --git a/src/components/pages/withdrawal-methods/add-method-dialog.tsx b/src/components/pages/withdrawal-methods/add-method-dialog.tsxnew file mode 100644index 0000000..9181b0a--- /dev/null+++ b/src/components/pages/withdrawal-methods/add-method-dialog.tsx@@ -0,0 +1,222 @@+"use client";++import { useState } from "react";+import { ShieldCheckIcon } from "lucide-react";+import { toast } from "sonner";+import { Field } from "@/components/dialogs/field";+import { Button } from "@/components/ui/button";+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from "@/components/ui/dialog";+import { Input } from "@/components/ui/input";+import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";+import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";+import type { WithdrawalKind } from "@/lib/types";+import { cn } from "@/lib/utils";+import { useAppStore } from "@/stores/app-store";+import { KIND_META, KINDS, KindTile, masked, PAYOUT_CURRENCIES } from "./shared";++// Inputs that may hold account/card digits: keep browsers and password managers from saving them.+const SENSITIVE_INPUT = {+ autoComplete: "off",+ "data-1p-ignore": true,+ "data-lpignore": "true",+ "data-form-type": "other",+} as const;++const digitsOnly = (v: string) => v.replace(/\D/g, "");+const groupDigits = (v: string) => v.replace(/(\d{4})(?=\d)/g, "$1 ");++function cardBrand(digits: string): string {+ if (/^4/.test(digits)) return "Visa";+ if (/^(5[1-5]|2[2-7])/.test(digits)) return "Mastercard";+ if (/^3[47]/.test(digits)) return "Amex";+ return "Debit card";+}++export function AddMethodDialog({ open, session, onClose }: { open: boolean; session: number; onClose: () => void }) {+ return (+ <Dialog open={open} onOpenChange={(v) => !v && onClose()}>+ <DialogContent className="gap-5 p-5 sm:max-w-[520px]">+ <AddMethodForm key={session} onDone={onClose} />+ </DialogContent>+ </Dialog>+ );+}++function AddMethodForm({ onDone }: { onDone: () => void }) {+ const profile = useAppStore((s) => s.profile);+ const addWithdrawalMethod = useAppStore((s) => s.addWithdrawalMethod);+ const [kind, setKind] = useState<WithdrawalKind>("bank");+ const [holder, setHolder] = useState(profile.name);+ const [email, setEmail] = useState(profile.email);+ const [bankName, setBankName] = useState("");+ // Full numbers live only in this form's state while typing; only the last 4 digits are saved.+ const [number, setNumber] = useState("");+ const [currency, setCurrency] = useState<string>("GBP");++ const needsNumber = kind === "bank" || kind === "card";+ const minDigits = kind === "card" ? 12 : 6;+ const numberError = needsNumber && number.length > 0 && number.length < minDigits;+ const emailValid = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email.trim());++ const valid =+ kind === "bank"+ ? holder.trim() && bankName.trim() && number.length >= minDigits+ : kind === "card"+ ? holder.trim() && number.length >= minDigits+ : emailValid;++ const preview = needsNumber && number.length >= 4 ? masked(number.slice(-4)) : null;++ return (+ <form+ className="contents"+ autoComplete="off"+ onSubmit={(e) => {+ e.preventDefault();+ if (!valid) return;+ const last4 = needsNumber ? number.slice(-4) : "";+ const label =+ kind === "bank" ? bankName.trim() : kind === "card" ? cardBrand(number) : KIND_META[kind].label;+ addWithdrawalMethod({+ kind,+ label,+ holder: kind === "paypal" || kind === "wise" ? email.trim() : holder.trim(),+ last4,+ currency,+ });+ setNumber("");+ toast.success("Withdrawal method added", {+ description: [label, masked(last4), currency].filter(Boolean).join(" · "),+ });+ onDone();+ }}+ >+ <DialogHeader className="gap-1.5">+ <DialogTitle className="t-16">Add withdrawal method</DialogTitle>+ <DialogDescription className="t-14">Choose where your payouts should land.</DialogDescription>+ </DialogHeader>++ <RadioGroup+ value={kind}+ onValueChange={(v) => {+ setKind(v as WithdrawalKind);+ setNumber("");+ }}+ className="grid grid-cols-4 gap-2"+ aria-label="Method type"+ >+ {KINDS.map((k) => (+ <label+ key={k.kind}+ className={cn(+ "press relative flex cursor-pointer flex-col items-start gap-2.5 rounded-lg border p-2.5 transition-[border-color,background-color] duration-150",+ kind === k.kind ? "border-brand/50 bg-brand-tint" : "border-control bg-surface hover-fine:bg-hover",+ )}+ >+ <RadioGroupItem value={k.kind} className="absolute top-2.5 right-2.5" />+ <KindTile kind={k.kind} className="size-7 rounded-md [&_svg]:size-3.5" />+ <span className="flex flex-col gap-1">+ <span className="t-14 text-fg">{k.kind === "bank" ? "Bank" : k.label}</span>+ <span className="t-12 text-fg-2">{k.hint}</span>+ </span>+ </label>+ ))}+ </RadioGroup>++ <div className="grid gap-4">+ {kind === "paypal" || kind === "wise" ? (+ <Field+ label={`${KIND_META[kind].label} email`}+ htmlFor="wm-email"+ error={email && !emailValid ? "Enter a valid email address." : null}+ >+ <Input+ id="wm-email"+ type="email"+ required+ value={email}+ aria-invalid={!!email && !emailValid}+ onChange={(e) => setEmail(e.target.value)}+ />+ </Field>+ ) : (+ <>+ <div className={cn("grid gap-3", kind === "bank" && "grid-cols-2")}>+ <Field label={kind === "card" ? "Name on card" : "Account holder"} htmlFor="wm-holder">+ <Input id="wm-holder" required value={holder} onChange={(e) => setHolder(e.target.value)} />+ </Field>+ {kind === "bank" && (+ <Field label="Bank name" htmlFor="wm-bank">+ <Input+ id="wm-bank"+ required+ placeholder="e.g. Monzo"+ value={bankName}+ onChange={(e) => setBankName(e.target.value)}+ />+ </Field>+ )}+ </div>+ <Field+ label={kind === "card" ? "Card number" : "Account number"}+ htmlFor="wm-number"+ error={numberError ? `Enter at least ${minDigits} digits.` : null}+ hint={preview ? `Saved as ${preview}` : "Only the last 4 digits are kept."}+ >+ <Input+ id="wm-number"+ inputMode="numeric"+ placeholder={kind === "card" ? "4242 4242 4242 4242" : "00000000"}+ className="tabular-nums"+ aria-invalid={numberError}+ maxLength={kind === "card" ? 23 : 20}+ value={kind === "card" ? groupDigits(number) : number}+ onChange={(e) => setNumber(digitsOnly(e.target.value).slice(0, 19))}+ {...SENSITIVE_INPUT}+ />+ </Field>+ </>+ )}++ <Field label="Payout currency" htmlFor="wm-currency">+ <Select value={currency} onValueChange={setCurrency}>+ <SelectTrigger id="wm-currency" className="w-full">+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ {PAYOUT_CURRENCIES.map((c) => (+ <SelectItem key={c} value={c}>+ {c}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ </Field>++ <p className="t-12 flex items-start gap-2 rounded-lg border border-hairline bg-app px-3 py-2.5 leading-[1.4] text-fg-2">+ <ShieldCheckIcon className="mt-px size-3.5 shrink-0 text-icon" />+ <span>+ <span className="text-fg">Demo only — please don’t enter real details.</span> Full account and card numbers+ are never stored; this app keeps just the last 4 digits for display.+ </span>+ </p>+ </div>++ <DialogFooter className="-mx-5 -mb-5 bg-app px-5 py-3">+ <Button type="button" onClick={onDone}>+ Cancel+ </Button>+ <Button type="submit" variant="brand" disabled={!valid}>+ Add method+ </Button>+ </DialogFooter>+ </form>+ );+}diff --git a/src/components/pages/withdrawal-methods/shared.tsx b/src/components/pages/withdrawal-methods/shared.tsxnew file mode 100644index 0000000..bc575ec--- /dev/null+++ b/src/components/pages/withdrawal-methods/shared.tsx@@ -0,0 +1,45 @@+import { CreditCardIcon, GlobeIcon, LandmarkIcon, WalletIcon, type LucideIcon } from "lucide-react";+import { addDays, daysInMonth, isWeekend } from "@/lib/dates";+import { cn } from "@/lib/utils";+import type { EventColor, Holiday, WithdrawalKind } from "@/lib/types";++export const KINDS: { kind: WithdrawalKind; label: string; hint: string; icon: LucideIcon; color: EventColor }[] = [+ { kind: "bank", label: "Bank account", hint: "2–3 days", icon: LandmarkIcon, color: "blue" },+ { kind: "paypal", label: "PayPal", hint: "Instant", icon: WalletIcon, color: "purple" },+ { kind: "wise", label: "Wise", hint: "Same day", icon: GlobeIcon, color: "green" },+ { kind: "card", label: "Debit card", hint: "30 min", icon: CreditCardIcon, color: "orange" },+];++export const KIND_META = Object.fromEntries(KINDS.map((k) => [k.kind, k])) as Record<WithdrawalKind, (typeof KINDS)[number]>;++export const PAYOUT_CURRENCIES = ["GBP", "USD", "EUR", "INR"] as const;++export function KindTile({ kind, className }: { kind: WithdrawalKind; className?: string }) {+ const { icon: KindIcon, color } = KIND_META[kind];+ return (+ <span+ aria-hidden+ className={cn("flex size-9 shrink-0 items-center justify-center rounded-lg", className)}+ style={{ background: `var(--category-${color}-tint)`, color: `var(--event-${color}-fg)` }}+ >+ <KindIcon className="size-4" strokeWidth={2} />+ </span>+ );+}++export const masked = (last4: string) => (last4 ? `•••• ${last4}` : "");++/** Last weekday of the month that isn't a public holiday. */+export function lastWorkingDay(monthKey: string, holidays: Holiday[]): string {+ const off = new Set(holidays.map((h) => h.date));+ let day = monthKey.slice(0, 8) + String(daysInMonth(monthKey)).padStart(2, "0");+ while (isWeekend(day) || off.has(day)) day = addDays(day, -1);+ return day;+}++/** Next payout on or after `today`. */+export function nextPayoutDate(today: string, holidays: Holiday[]): string {+ const thisMonth = lastWorkingDay(today, holidays);+ if (thisMonth >= today) return thisMonth;+ return lastWorkingDay(addDays(today.slice(0, 8) + "01", 32), holidays);+}diff --git a/src/components/pages/withdrawal-methods/withdrawal-methods-page.tsx b/src/components/pages/withdrawal-methods/withdrawal-methods-page.tsxnew file mode 100644index 0000000..1cdd299--- /dev/null+++ b/src/components/pages/withdrawal-methods/withdrawal-methods-page.tsx@@ -0,0 +1,261 @@+"use client";++import { useMemo, useState } from "react";+import { ArrowDownToLineIcon, CalendarClockIcon, CheckIcon, PlusIcon, Trash2Icon, WalletCardsIcon } from "lucide-react";+import { toast } from "sonner";+import {+ AlertDialog,+ AlertDialogAction,+ AlertDialogCancel,+ AlertDialogContent,+ AlertDialogDescription,+ AlertDialogFooter,+ AlertDialogHeader,+ AlertDialogTitle,+} from "@/components/ui/alert-dialog";+import { Button } from "@/components/ui/button";+import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";+import { diffDays, formatLong, formatShort, formatWeekday } from "@/lib/dates";+import type { WithdrawalMethod } from "@/lib/types";+import { useToday } from "@/hooks/use-today";+import { useAppStore } from "@/stores/app-store";+import { AddMethodDialog } from "./add-method-dialog";+import { KIND_META, KindTile, lastWorkingDay, masked, nextPayoutDate } from "./shared";++const money = (amount: number, currency: string) =>+ new Intl.NumberFormat("en-US", { style: "currency", currency }).format(amount);++export function WithdrawalMethodsPage() {+ const today = useToday();+ const methods = useAppStore((s) => s.withdrawalMethods);+ const invoices = useAppStore((s) => s.invoices);+ const holidays = useAppStore((s) => s.holidays);+ const setDefault = useAppStore((s) => s.setDefaultWithdrawalMethod);+ const removeMethod = useAppStore((s) => s.removeWithdrawalMethod);+ const [adding, setAdding] = useState({ open: false, session: 0 });+ const [removeId, setRemoveId] = useState<string | null>(null);++ const defaultMethod = methods.find((m) => m.isDefault);+ const toRemove = methods.find((m) => m.id === removeId);+ const nextPayout = nextPayoutDate(today, holidays);+ const daysToPayout = diffDays(today, nextPayout);++ const payouts = useMemo(+ () =>+ invoices+ .filter((i) => i.status === "paid")+ .map((i) => ({+ id: i.id,+ number: i.number,+ client: i.client,+ currency: i.currency,+ amount: i.items.reduce((n, it) => n + it.quantity * it.rate, 0),+ date: lastWorkingDay(i.dueDate, holidays),+ }))+ .sort((a, b) => b.date.localeCompare(a.date)),+ [invoices, holidays],+ );++ const makeDefault = (m: WithdrawalMethod) => {+ setDefault(m.id);+ toast.success("Default method updated", { description: `Payouts now go to ${m.label}` });+ };++ return (+ <div className="flex min-h-0 flex-1 flex-col overflow-y-auto scroll-thin bg-app">+ <header className="sticky top-0 z-10 flex h-[68px] shrink-0 items-center gap-3 border-b border-hairline bg-surface px-4">+ <div className="flex min-w-0 flex-1 flex-col gap-1.5">+ <h2 className="t-16 text-fg">Withdrawal methods</h2>+ <p className="t-14 truncate text-fg-2">Where your invoice payments are paid out</p>+ </div>+ <Button variant="brand" onClick={() => setAdding((a) => ({ open: true, session: a.session + 1 }))}>+ <PlusIcon /> Add method+ </Button>+ </header>++ <div className="grid grid-cols-[minmax(0,1fr)_340px] items-start gap-4 p-4">+ <section className="overflow-hidden rounded-xl border border-hairline bg-surface">+ <div className="flex h-12 items-center justify-between border-b border-hairline px-4">+ <h3 className="t-14 text-fg">Methods</h3>+ <span className="t-12 text-fg-2">{methods.length} saved</span>+ </div>+ {methods.length === 0 ? (+ <div className="flex flex-col items-center gap-3 px-4 py-14 text-center">+ <span className="flex size-10 items-center justify-center rounded-lg bg-app">+ <WalletCardsIcon className="size-4 text-icon" />+ </span>+ <div className="flex flex-col gap-1.5">+ <p className="t-14 text-fg">No withdrawal methods</p>+ <p className="t-14 text-fg-2">Add one so we know where to send your payouts.</p>+ </div>+ <Button onClick={() => setAdding((a) => ({ open: true, session: a.session + 1 }))}>+ <PlusIcon /> Add method+ </Button>+ </div>+ ) : (+ <ul>+ {methods.map((m) => (+ <li key={m.id} className="flex h-[68px] items-center gap-3 border-b border-subtle px-4 last:border-b-0">+ <KindTile kind={m.kind} />+ <div className="flex min-w-0 flex-1 flex-col gap-1.5">+ <span className="flex items-center gap-2">+ <span className="t-14 truncate text-fg">{m.label}</span>+ {m.isDefault && (+ <span className="t-12 shrink-0 rounded-md bg-brand-tint px-1.5 py-1 text-brand">Default</span>+ )}+ </span>+ <span className="t-12 truncate text-fg-2">+ {KIND_META[m.kind].label} · {m.holder}+ </span>+ </div>+ <span className="t-14 w-24 shrink-0 text-right text-table tabular-nums">+ {masked(m.last4) || <span className="text-placeholder">—</span>}+ </span>+ <span className="t-12 w-12 shrink-0 rounded-md border border-control py-1 text-center text-fg-2">+ {m.currency}+ </span>+ <div className="flex w-[132px] shrink-0 items-center justify-end gap-0.5">+ {!m.isDefault && (+ <Button size="sm" className="px-2" onClick={() => makeDefault(m)}>+ Set default+ </Button>+ )}+ <Tooltip>+ <TooltipTrigger asChild>+ <Button variant="ghost" size="icon-sm" aria-label={`Remove ${m.label}`} onClick={() => setRemoveId(m.id)}>+ <Trash2Icon />+ </Button>+ </TooltipTrigger>+ <TooltipContent>Remove</TooltipContent>+ </Tooltip>+ </div>+ </li>+ ))}+ </ul>+ )}+ </section>++ <div className="flex flex-col gap-4">+ <section className="overflow-hidden rounded-xl border border-hairline bg-surface">+ <div className="flex h-12 items-center gap-2 border-b border-hairline px-4">+ <CalendarClockIcon className="size-3.5 text-icon" />+ <h3 className="t-14 text-fg">Payout schedule</h3>+ </div>+ <div className="flex flex-col gap-4 p-4">+ <div className="flex items-center gap-3">+ <span className="flex w-11 shrink-0 flex-col items-center gap-1 rounded-md bg-[var(--event-purple-bg)] py-1.5 text-[var(--event-purple-fg)]">+ <span className="text-[10px] leading-none tracking-wide uppercase">{formatShort(nextPayout).slice(0, 3)}</span>+ <span className="t-16">{Number(nextPayout.slice(8))}</span>+ </span>+ <div className="flex min-w-0 flex-col gap-1.5">+ <span className="t-14 text-fg">+ Next payout {daysToPayout === 0 ? "today" : daysToPayout === 1 ? "tomorrow" : `in ${daysToPayout} days`}+ </span>+ <span className="t-12 text-fg-2">+ {formatWeekday(nextPayout)}, {formatLong(nextPayout)}+ </span>+ </div>+ </div>+ <dl className="grid gap-3 border-t border-hairline pt-4">+ <Row label="Frequency" value="Monthly" />+ <Row label="Pay day" value="Last working day" />+ <Row+ label="Destination"+ value={+ defaultMethod+ ? [defaultMethod.label, masked(defaultMethod.last4)].filter(Boolean).join(" ")+ : "No method yet"+ }+ muted={!defaultMethod}+ />+ </dl>+ <p className="t-12 leading-[1.4] text-fg-2">+ Weekends and public holidays move the payout to the working day before.+ </p>+ </div>+ </section>++ <section className="overflow-hidden rounded-xl border border-hairline bg-surface">+ <div className="flex h-12 items-center gap-2 border-b border-hairline px-4">+ <ArrowDownToLineIcon className="size-3.5 text-icon" />+ <h3 className="t-14 flex-1 text-fg">Recent payouts</h3>+ <span className="t-12 text-fg-2">From paid invoices</span>+ </div>+ {payouts.length === 0 ? (+ <p className="t-14 px-4 py-8 text-center text-fg-2">Paid invoices will show up here.</p>+ ) : (+ <ul>+ {payouts.map((p) => {+ const done = p.date <= today;+ return (+ <li key={p.id} className="flex items-center gap-3 border-b border-subtle px-4 py-3 last:border-b-0">+ <div className="flex min-w-0 flex-1 flex-col gap-1.5">+ <span className="t-14 truncate text-fg">{p.client}</span>+ <span className="t-12 truncate text-fg-2">+ {p.number} · {formatShort(p.date)}, {p.date.slice(0, 4)}+ </span>+ </div>+ <div className="flex shrink-0 flex-col items-end gap-1.5">+ <span className="t-14 text-table tabular-nums">{money(p.amount, p.currency)}</span>+ <span+ className="t-12 flex items-center gap-1"+ style={{ color: done ? "var(--status-success)" : "var(--status-warning)" }}+ >+ {done && <CheckIcon className="size-3" strokeWidth={2.5} />}+ {done ? "Paid out" : "Scheduled"}+ </span>+ </div>+ </li>+ );+ })}+ </ul>+ )}+ </section>+ </div>+ </div>++ <AddMethodDialog+ open={adding.open}+ session={adding.session}+ onClose={() => setAdding((a) => ({ ...a, open: false }))}+ />++ <AlertDialog open={!!toRemove} onOpenChange={(v) => !v && setRemoveId(null)}>+ <AlertDialogContent>+ <AlertDialogHeader>+ <AlertDialogTitle className="t-16">Remove {toRemove?.label}?</AlertDialogTitle>+ <AlertDialogDescription className="t-14 leading-[1.4]">+ {toRemove?.isDefault && methods.length > 1+ ? "This is your default method. Future payouts will go to your next saved method."+ : toRemove?.isDefault+ ? "This is your only method — payouts will be held until you add a new one."+ : "Payouts won't be sent here any more. You can add it again later."}+ </AlertDialogDescription>+ </AlertDialogHeader>+ <AlertDialogFooter>+ <AlertDialogCancel>Keep</AlertDialogCancel>+ <AlertDialogAction+ variant="destructive"+ onClick={() => {+ if (!toRemove) return;+ removeMethod(toRemove.id);+ toast(`${toRemove.label} removed`);+ }}+ >+ Remove+ </AlertDialogAction>+ </AlertDialogFooter>+ </AlertDialogContent>+ </AlertDialog>+ </div>+ );+}++function Row({ label, value, muted }: { label: string; value: string; muted?: boolean }) {+ return (+ <div className="flex items-center justify-between gap-4">+ <dt className="t-14 text-fg-2">{label}</dt>+ <dd className={muted ? "t-14 truncate text-placeholder" : "t-14 truncate text-right text-table"}>{value}</dd>+ </div>+ );+}