TypeScript
feat: add Benefits page
Vipul Kumar2736d730baad
diff --git a/src/app/benefits/page.tsx b/src/app/benefits/page.tsxnew file mode 100644index 0000000..b4a544f--- /dev/null+++ b/src/app/benefits/page.tsx@@ -0,0 +1,8 @@+import type { Metadata } from "next";+import { BenefitsPage } from "@/components/pages/benefits/benefits-page";++export const metadata: Metadata = { title: "Benefits" };++export default function Page() {+ return <BenefitsPage />;+}diff --git a/src/components/pages/benefits/benefits-page.tsx b/src/components/pages/benefits/benefits-page.tsxnew file mode 100644index 0000000..9a754bf--- /dev/null+++ b/src/components/pages/benefits/benefits-page.tsx@@ -0,0 +1,288 @@+"use client";++import { useMemo, useState } from "react";+import { CalendarSyncIcon, CheckIcon, PlusIcon, ReceiptIcon } 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 { Progress } from "@/components/ui/progress";+import { formatLong, formatShort } from "@/lib/dates";+import type { Benefit } from "@/lib/types";+import { cn } from "@/lib/utils";+import { useAppStore } from "@/stores/app-store";+import { ClaimDialog } from "./claim-dialog";+import { CATEGORIES, CategoryTile, formatMoney, type BenefitCategory } from "./shared";++type Filter = "All" | BenefitCategory;++export function BenefitsPage() {+ const benefits = useAppStore((s) => s.benefits);+ const toggleBenefit = useAppStore((s) => s.toggleBenefit);+ const [filter, setFilter] = useState<Filter>("All");+ const [claim, setClaim] = useState<{ open: boolean; session: number; id?: string }>({ open: false, session: 0 });+ const [unenrollId, setUnenrollId] = useState<string | null>(null);++ const summary = useMemo(() => {+ const enrolled = benefits.filter((b) => b.enrolled);+ const budget = enrolled.reduce((n, b) => n + b.budget, 0);+ const used = enrolled.reduce((n, b) => n + b.used, 0);+ return { budget, used, remaining: budget - used, enrolled: enrolled.length };+ }, [benefits]);++ const counts = useMemo(() => {+ const map = new Map<Filter, number>([["All", benefits.length]]);+ for (const b of benefits) map.set(b.category, (map.get(b.category) ?? 0) + 1);+ return map;+ }, [benefits]);++ const visible = useMemo(+ () => (filter === "All" ? benefits : benefits.filter((b) => b.category === filter)),+ [benefits, filter],+ );++ const claimBenefit = benefits.find((b) => b.id === claim.id);+ const unenrollBenefit = benefits.find((b) => b.id === unenrollId);++ const enroll = (b: Benefit) => {+ toggleBenefit(b.id);+ toast.success(`Enrolled in ${b.name}`, { description: `Active until ${formatLong(b.renewsOn)}` });+ };++ 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">Your benefits</h2>+ <p className="t-14 text-fg-2">+ {summary.enrolled} of {benefits.length} enrolled · budgets reset on renewal+ </p>+ </div>+ </header>++ <div className="flex flex-col gap-4 p-4">+ <dl className="grid grid-cols-4 overflow-hidden rounded-xl border border-hairline bg-surface">+ <SummaryStat label="Total budget" value={formatMoney(summary.budget)} />+ <SummaryStat label="Used" value={formatMoney(summary.used)} />+ <SummaryStat+ label="Remaining"+ value={formatMoney(summary.remaining)}+ extra={+ summary.budget > 0 ? (+ <Progress+ value={(summary.used / summary.budget) * 100}+ className="mt-1 h-1 bg-app"+ aria-label="Budget used"+ />+ ) : null+ }+ />+ <SummaryStat label="Enrolled" value={`${summary.enrolled}`} suffix={`of ${benefits.length}`} />+ </dl>++ <div role="toolbar" aria-label="Filter by category" className="flex flex-wrap items-center gap-1">+ {(["All", ...CATEGORIES] as Filter[]).map((c) => {+ const active = filter === c;+ const n = counts.get(c) ?? 0;+ return (+ <button+ key={c}+ type="button"+ aria-pressed={active}+ onClick={() => setFilter(c)}+ className={cn(+ "press t-14 flex h-7 items-center gap-1.5 rounded-lg border px-2.5 outline-none focus-visible:ring-3 focus-visible:ring-brand/15",+ active+ ? "border-control bg-surface text-fg shadow-[0_1px_2px_rgba(0,0,0,0.04)]"+ : "border-transparent text-fg-2 hover-fine:bg-hover hover-fine:text-fg",+ )}+ >+ {c !== "All" && <CategoryTile category={c} size="sm" />}+ {c}+ <span className="t-12 text-placeholder tabular-nums">{n}</span>+ </button>+ );+ })}+ </div>++ {visible.length === 0 ? (+ <div className="rounded-xl border border-dashed border-hairline bg-surface px-4 py-14 text-center">+ <p className="t-14 text-fg-2">No {filter.toLowerCase()} benefits yet.</p>+ </div>+ ) : (+ <div className="grid grid-cols-[repeat(auto-fill,minmax(340px,1fr))] gap-4">+ {visible.map((b) => (+ <BenefitCard+ key={b.id}+ benefit={b}+ onEnroll={() => enroll(b)}+ onUnenroll={() => setUnenrollId(b.id)}+ onClaim={() => setClaim((c) => ({ open: true, session: c.session + 1, id: b.id }))}+ />+ ))}+ </div>+ )}+ </div>++ <ClaimDialog+ open={claim.open}+ session={claim.session}+ benefit={claimBenefit}+ onClose={() => setClaim((c) => ({ ...c, open: false }))}+ />++ <AlertDialog open={!!unenrollBenefit} onOpenChange={(v) => !v && setUnenrollId(null)}>+ <AlertDialogContent>+ <AlertDialogHeader>+ <AlertDialogTitle className="t-16">Unenroll from {unenrollBenefit?.name}?</AlertDialogTitle>+ <AlertDialogDescription className="t-14 leading-[1.4]">+ {unenrollBenefit && unenrollBenefit.budget - unenrollBenefit.used > 0+ ? `Your remaining ${formatMoney(unenrollBenefit.budget - unenrollBenefit.used)} won't be available until you enroll again.`+ : "You can enroll again at any time before the next renewal."}+ </AlertDialogDescription>+ </AlertDialogHeader>+ <AlertDialogFooter>+ <AlertDialogCancel>Stay enrolled</AlertDialogCancel>+ <AlertDialogAction+ variant="destructive"+ onClick={() => {+ if (!unenrollBenefit) return;+ toggleBenefit(unenrollBenefit.id);+ toast(`Unenrolled from ${unenrollBenefit.name}`, {+ action: { label: "Undo", onClick: () => useAppStore.getState().toggleBenefit(unenrollBenefit.id) },+ });+ }}+ >+ Unenroll+ </AlertDialogAction>+ </AlertDialogFooter>+ </AlertDialogContent>+ </AlertDialog>+ </div>+ );+}++function SummaryStat({+ label,+ value,+ suffix,+ extra,+}: {+ label: string;+ value: string;+ suffix?: string;+ extra?: React.ReactNode;+}) {+ return (+ <div className="flex flex-col gap-2.5 border-r border-hairline px-4 py-3.5 last:border-r-0">+ <dt className="t-12 text-fg-2">{label}</dt>+ <dd className="flex items-baseline gap-1.5">+ <span className="text-[20px] leading-none font-medium tracking-[-0.4px] text-fg tabular-nums">{value}</span>+ {suffix && <span className="t-14 text-fg-2">{suffix}</span>}+ </dd>+ {extra}+ </div>+ );+}++function BenefitCard({+ benefit: b,+ onEnroll,+ onUnenroll,+ onClaim,+}: {+ benefit: Benefit;+ onEnroll: () => void;+ onUnenroll: () => void;+ onClaim: () => void;+}) {+ const remaining = Math.max(0, b.budget - b.used);+ const pct = b.budget > 0 ? Math.min(100, (b.used / b.budget) * 100) : 0;+ const nearlyUsed = pct >= 90;++ return (+ <article className="flex flex-col rounded-xl border border-hairline bg-surface">+ <div className="flex flex-1 flex-col gap-4 p-4">+ <div className="flex items-start gap-3">+ <CategoryTile category={b.category} />+ <div className="flex min-w-0 flex-1 flex-col gap-1.5 pt-0.5">+ <h3 className="t-14 truncate text-fg">{b.name}</h3>+ <p className="t-12 text-fg-2">+ {b.provider} · {b.category}+ </p>+ </div>+ {b.enrolled && (+ <span+ className="salt inline-flex h-[22px] shrink-0 items-center gap-1 rounded-[6px] border pr-1.5 pl-1 text-[12px] leading-none tracking-[-0.24px]"+ style={{+ background: "var(--status-success-tint)",+ borderColor: "var(--status-success-border)",+ color: "var(--status-success)",+ }}+ >+ <CheckIcon className="size-3.5" strokeWidth={2.25} /> Enrolled+ </span>+ )}+ </div>+ <p className="t-14 leading-[1.4] text-fg-2">{b.description}</p>++ <div className="mt-auto flex flex-col gap-2">+ {b.budget > 0 ? (+ <>+ <div className="flex items-baseline justify-between gap-3">+ <span className="t-14 text-table tabular-nums">+ {formatMoney(b.used, true)} <span className="text-fg-2">of {formatMoney(b.budget)} used</span>+ </span>+ <span className={cn("t-12 tabular-nums", nearlyUsed ? "text-warning" : "text-fg-2")}>+ {formatMoney(remaining)} left+ </span>+ </div>+ <Progress+ value={pct}+ aria-label={`${b.name} budget used`}+ className={cn(+ "h-1.5 bg-app",+ !b.enrolled && "opacity-50",+ nearlyUsed && "[&_[data-slot=progress-indicator]]:bg-warning",+ )}+ />+ </>+ ) : (+ <p className="t-14 text-fg-2">No spending budget — covered in full by the company.</p>+ )}+ </div>+ </div>++ <div className="flex items-center gap-2 border-t border-hairline px-4 py-3">+ <span className="t-12 flex min-w-0 flex-1 items-center gap-1.5 text-fg-2">+ <CalendarSyncIcon className="size-3.5 shrink-0 text-icon" />+ <span className="truncate">Renews {formatShort(b.renewsOn)}, {b.renewsOn.slice(0, 4)}</span>+ </span>+ {b.enrolled ? (+ <>+ {b.budget > 0 && (+ <Button size="sm" className="px-2" disabled={remaining <= 0} onClick={onClaim} aria-label={`Submit a claim for ${b.name}`}>+ <ReceiptIcon className="text-icon" /> Claim+ </Button>+ )}+ <Button size="sm" variant="ghost" className="px-2" onClick={onUnenroll}>+ Unenroll+ </Button>+ </>+ ) : (+ <Button size="sm" variant="brand" className="px-2" onClick={onEnroll}>+ <PlusIcon /> Enroll+ </Button>+ )}+ </div>+ </article>+ );+}diff --git a/src/components/pages/benefits/claim-dialog.tsx b/src/components/pages/benefits/claim-dialog.tsxnew file mode 100644index 0000000..3354ab4--- /dev/null+++ b/src/components/pages/benefits/claim-dialog.tsx@@ -0,0 +1,158 @@+"use client";++import { useRef, useState } from "react";+import { PaperclipIcon, XIcon } 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 { Textarea } from "@/components/ui/textarea";+import type { Benefit } from "@/lib/types";+import { useAppStore } from "@/stores/app-store";+import { CategoryTile, formatMoney } from "./shared";++type Props = { benefit?: Benefit; session: number; open: boolean; onClose: () => void };++export function ClaimDialog({ benefit, session, open, onClose }: Props) {+ return (+ <Dialog open={open} onOpenChange={(v) => !v && onClose()}>+ <DialogContent className="gap-5 p-5 sm:max-w-[440px]">+ {benefit && <ClaimForm key={session} benefit={benefit} onDone={onClose} />}+ </DialogContent>+ </Dialog>+ );+}++function ClaimForm({ benefit, onDone }: { benefit: Benefit; onDone: () => void }) {+ const claimBenefit = useAppStore((s) => s.claimBenefit);+ const notify = useAppStore((s) => s.notify);+ const fileRef = useRef<HTMLInputElement>(null);+ const [amount, setAmount] = useState("");+ const [description, setDescription] = useState("");+ // Only the file name is kept — receipts aren't uploaded anywhere in this demo.+ const [receipt, setReceipt] = useState<string | null>(null);++ const remaining = Math.max(0, benefit.budget - benefit.used);+ const value = Number(amount);+ const error =+ amount === ""+ ? null+ : !Number.isFinite(value) || value <= 0+ ? "Enter an amount greater than zero."+ : value > remaining+ ? `You have ${formatMoney(remaining)} left on this benefit.`+ : null;+ const valid = amount !== "" && !error && description.trim().length > 0;++ return (+ <form+ className="contents"+ onSubmit={(e) => {+ e.preventDefault();+ if (!valid) return;+ claimBenefit(benefit.id, value);+ toast.success("Claim submitted", {+ description: `${formatMoney(value, true)} · ${benefit.name}`,+ });+ notify({+ title: "Benefit claim submitted",+ body: `${formatMoney(value, true)} from your ${benefit.name.toLowerCase()} for “${description.trim()}”.`,+ href: "/benefits",+ });+ onDone();+ }}+ >+ <DialogHeader className="gap-1.5">+ <DialogTitle className="t-16">Submit a claim</DialogTitle>+ <DialogDescription className="t-14">Reimbursed with your next payroll run.</DialogDescription>+ </DialogHeader>++ <div className="flex items-center gap-3 rounded-lg border border-hairline bg-app px-3 py-2.5">+ <CategoryTile category={benefit.category} />+ <div className="flex min-w-0 flex-1 flex-col gap-1.5">+ <span className="t-14 truncate text-fg">{benefit.name}</span>+ <span className="t-12 text-fg-2">+ {formatMoney(remaining)} of {formatMoney(benefit.budget)} remaining+ </span>+ </div>+ </div>++ <div className="grid gap-4">+ <Field label="Amount" htmlFor="claim-amount" error={error}>+ <div className="relative">+ <span className="t-14 pointer-events-none absolute top-1/2 left-2.5 -translate-y-1/2 text-fg-2">£</span>+ <Input+ id="claim-amount"+ type="number"+ inputMode="decimal"+ min={0.01}+ step={0.01}+ max={remaining}+ required+ autoFocus+ placeholder="0.00"+ className="pl-6 tabular-nums"+ aria-invalid={!!error}+ value={amount}+ onChange={(e) => setAmount(e.target.value)}+ />+ </div>+ </Field>+ <Field label="Description" htmlFor="claim-description">+ <Textarea+ id="claim-description"+ rows={2}+ required+ placeholder="e.g. Figma Config 2026 ticket"+ value={description}+ onChange={(e) => setDescription(e.target.value)}+ />+ </Field>+ <Field label="Receipt (optional)" hint="PDF or image. Only the file name is attached in this demo.">+ <input+ ref={fileRef}+ type="file"+ accept="image/*,application/pdf"+ className="sr-only"+ tabIndex={-1}+ aria-hidden+ onChange={(e) => {+ setReceipt(e.target.files?.[0]?.name ?? null);+ e.target.value = "";+ }}+ />+ {receipt ? (+ <div className="flex h-8 items-center gap-2 rounded-lg border border-control bg-surface pr-1 pl-2.5">+ <PaperclipIcon className="size-3.5 shrink-0 text-icon" />+ <span className="t-14 min-w-0 flex-1 truncate text-fg">{receipt}</span>+ <Button type="button" variant="ghost" size="icon-sm" aria-label="Remove receipt" onClick={() => setReceipt(null)}>+ <XIcon />+ </Button>+ </div>+ ) : (+ <Button type="button" className="justify-self-start" onClick={() => fileRef.current?.click()}>+ <PaperclipIcon className="text-icon" /> Attach receipt+ </Button>+ )}+ </Field>+ </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}>+ Submit claim+ </Button>+ </DialogFooter>+ </form>+ );+}diff --git a/src/components/pages/benefits/shared.tsx b/src/components/pages/benefits/shared.tsxnew file mode 100644index 0000000..20356a2--- /dev/null+++ b/src/components/pages/benefits/shared.tsx@@ -0,0 +1,39 @@+import { ArmchairIcon, DumbbellIcon, GraduationCapIcon, HeartPulseIcon, PiggyBankIcon, type LucideIcon } from "lucide-react";+import { cn } from "@/lib/utils";+import type { Benefit, EventColor } from "@/lib/types";++export type BenefitCategory = Benefit["category"];++export const CATEGORIES: BenefitCategory[] = ["Health", "Wellness", "Learning", "Financial", "Lifestyle"];++const CATEGORY_STYLE: Record<BenefitCategory, { color: EventColor; icon: LucideIcon }> = {+ Health: { color: "green", icon: HeartPulseIcon },+ Wellness: { color: "pink", icon: DumbbellIcon },+ Learning: { color: "blue", icon: GraduationCapIcon },+ Financial: { color: "orange", icon: PiggyBankIcon },+ Lifestyle: { color: "purple", icon: ArmchairIcon },+};++/** Benefits carry no currency in the store; the employee is UK-based. */+const money = new Intl.NumberFormat("en-GB", { style: "currency", currency: "GBP", maximumFractionDigits: 0 });+const moneyExact = new Intl.NumberFormat("en-GB", { style: "currency", currency: "GBP" });++export function formatMoney(amount: number, exact = false): string {+ return (exact && amount % 1 !== 0 ? moneyExact : money).format(amount);+}++export function CategoryTile({ category, size = "md" }: { category: BenefitCategory; size?: "sm" | "md" }) {+ const { color, icon: CategoryIcon } = CATEGORY_STYLE[category];+ return (+ <span+ aria-hidden+ className={cn(+ "flex shrink-0 items-center justify-center",+ size === "md" ? "size-9 rounded-lg" : "size-5 rounded-[6px]",+ )}+ style={{ background: `var(--category-${color}-tint)`, color: `var(--event-${color}-fg)` }}+ >+ <CategoryIcon className={size === "md" ? "size-4" : "size-3"} strokeWidth={2} />+ </span>+ );+}