forge
Explore
Log in

Don't you dare go Hollow

hezarfen_frontend

Clone
★ 0

0 watching0 forksTypeScript5.5 MiBdcf123aBurak Boduroğlu2 months ago674 commits

payment-statement-page.tsx194 lines, 8.4 KiBHistoryRawDownload
1import { Show, Suspense, createEffect, createMemo, createSignal } from "solid-js";
2import { createResource } from "@/lib/create-resource";
3import type { ColumnDef } from "@tanstack/solid-table";
4import {
5 getMyPaymentBalance,
6 getMyPaymentStatement,
7 getPaymentBalanceByUserId,
8 getPaymentStatementByUserId,
9 type StatementEntry,
10} from "@/api/payments";
11import { getMyStudents } from "@/api/parents";
12import { formatApiError } from "@/api/client";
13import { RouteGuard } from "@/components/layout/route-guard";
14import { Badge } from "@/components/ui/badge";
15import { DataTable, DataTableSkeleton } from "@/components/ui/data-table";
16import { DetailField } from "@/components/ui/detail-field";
17import { ErrorAlert } from "@/components/ui/error-alert";
18import { IconEye } from "@/components/ui/icons";
19import { Label } from "@/components/ui/label";
20import { SearchableSelect } from "@/components/ui/searchable-select";
21import { SidePanel } from "@/components/ui/side-panel";
22import { TableRowActions } from "@/components/ui/table-row-actions";
23import { formatDate } from "@/lib/format";
24import { formatTry } from "@/lib/meals";
25import { sortStatementEntries, statementStatus } from "@/lib/payments";
26import { personLabel } from "@/lib/person";
27import { useAuth } from "@/stores/auth-context";
28import { usePreferences, useT } from "@/stores/preferences-context";
29
30const STATEMENT_PAGE_SIZE = 10;
31
32export default function PaymentStatementPage() {
33 return (
34 <RouteGuard>
35 <StatementContent />
36 </RouteGuard>
37 );
38}
39
40function StatementContent() {
41 const auth = useAuth();
42 const t = useT();
43 const { locale } = usePreferences();
44 const moneyLocale = () => (locale() === "tr" ? "tr-TR" : "en-US");
45 const isParent = () => auth.user()!.role === "parent";
46
47 const [children] = createResource(() => (isParent() ? getMyStudents({ limit: 100 }) : null));
48 const [selectedChild, setSelectedChild] = createSignal("");
49 createEffect(() => {
50 if (isParent() && !selectedChild() && children()?.items[0]) setSelectedChild(children()!.items[0].id);
51 });
52 // Parent reads a child by id; everyone else reads their own record.
53 const targetId = () => (isParent() ? selectedChild() : "");
54
55 const [statement, { refetch }] = createResource(
56 () => (isParent() ? targetId() || null : "me"),
57 (key) => (key === "me" ? getMyPaymentStatement({ limit: 100 }) : getPaymentStatementByUserId(key, { limit: 100 })),
58 );
59 const [balance] = createResource(
60 () => (isParent() ? targetId() || null : "me"),
61 (key) => (key === "me" ? getMyPaymentBalance() : getPaymentBalanceByUserId(key)),
62 );
63 const entries = () => statement()?.entries.items ?? [];
64 const [viewEntry, setViewEntry] = createSignal<StatementEntry | null>(null);
65 const summary = createMemo(() => {
66 const rows = entries();
67 return {
68 billed: rows.filter((row) => !row.reversed).reduce((sum, row) => sum + row.amount_minor, 0),
69 collected: rows.reduce((sum, row) => sum + row.credited_minor, 0),
70 balance: statement()?.balance_minor ?? balance()?.balance_minor ?? 0,
71 };
72 });
73
74 const columns = createMemo<ColumnDef<StatementEntry>[]>(() => [
75 {
76 id: "plan",
77 header: t("payments.planName"),
78 cell: (cell) => <span class="block truncate font-medium">{cell.row.original.plan_name ?? "—"}</span>,
79 },
80 {
81 accessorKey: "due_at",
82 header: t("payments.due"),
83 cell: (cell) => <span class="block whitespace-nowrap text-sm" classList={{ "font-semibold text-destructive-text": cell.row.original.overdue }}>{cell.row.original.due_at == null ? "—" : formatDate(cell.row.original.due_at, locale())}</span>,
84 },
85 {
86 accessorKey: "outstanding_minor",
87 header: t("payments.outstanding"),
88 cell: (cell) => <span class="tabular-nums">{formatTry(cell.row.original.outstanding_minor, moneyLocale())}</span>,
89 },
90 {
91 id: "status",
92 header: t("payments.status"),
93 cell: (cell) => {
94 const status = statementStatus(cell.row.original);
95 return <Badge variant="outline" class={status.class}><span class={`mr-1.5 inline-block h-1.5 w-1.5 rounded-full ${status.dot}`} />{t(status.key)}</Badge>;
96 },
97 },
98 {
99 id: "actions",
100 header: t("common.actions"),
101 meta: {
102 headerClass: "w-[110px] min-w-[110px] max-w-[110px] h-[45px] text-center whitespace-nowrap",
103 cellClass: "w-[110px] min-w-[110px] max-w-[110px] h-[45px] text-center whitespace-nowrap",
104 },
105 cell: (cell) => (
106 <TableRowActions
107 label={t("common.actions")}
108 actions={[{
109 label: t("common.view"),
110 icon: <IconEye class="h-4 w-4" />,
111 onSelect: () => setViewEntry(cell.row.original),
112 }]}
113 />
114 ),
115 },
116 ]);
117
118 return (
119 <div class="space-y-6">
120 <Show when={isParent()}>
121 <div class="data-shell max-w-md p-4">
122 <Label for="statement-child">{t("meals.child")}</Label>
123 <SearchableSelect id="statement-child" value={selectedChild()} onChange={setSelectedChild} options={(children()?.items ?? []).map((child) => ({ value: child.id, label: personLabel(child) }))} />
124 </div>
125 </Show>
126
127 <section class="data-shell p-4">
128 <div class="flex flex-wrap items-baseline justify-between gap-2">
129 <p class="text-sm font-medium text-text-subtle">{t("payments.collected")}</p>
130 <p class="text-lg font-semibold tabular-nums text-text-strong">
131 {formatTry(summary().collected, moneyLocale())}
132 <span class="font-normal text-text-subtle"> / {formatTry(summary().billed, moneyLocale())}</span>
133 </p>
134 </div>
135 <div class="mt-3 h-2 overflow-hidden rounded-full bg-surface-tint">
136 <div
137 class="h-full rounded-full bg-primary"
138 style={{ width: `${summary().billed > 0 ? Math.max(0, Math.min(100, Math.round((summary().collected / summary().billed) * 100))) : 0}%` }}
139 />
140 </div>
141 <div class="mt-3 grid grid-cols-1 gap-3 sm:grid-cols-2">
142 <div>
143 <p class="text-xs font-medium text-text-subtle">{t("payments.totalDebt")}</p>
144 <p class="mt-1 font-semibold tabular-nums text-text-strong">{formatTry(summary().billed, moneyLocale())}</p>
145 </div>
146 <div>
147 <p class="text-xs font-medium text-text-subtle">{t("payments.balance")}</p>
148 <p class="mt-1 text-2xl font-semibold tabular-nums" classList={{ "text-destructive-text": summary().balance < 0 }}>{formatTry(summary().balance, moneyLocale())}</p>
149 </div>
150 </div>
151 </section>
152
153 <section class="space-y-4 p-0">
154 <Suspense fallback={<DataTableSkeleton columns={5} rows={6} />}>
155 <Show when={statement.error}>
156 <ErrorAlert message={formatApiError(statement.error)} onRetry={() => void refetch()} />
157 </Show>
158 <DataTable
159 title={t("payments.statementTitle")}
160 description={t("payments.statementSubtitle")}
161 empty={t("payments.noStatement")}
162 columns={columns()}
163 data={sortStatementEntries(entries())}
164 tableClass="min-w-160"
165 storageKey="my-payment-statement"
166 enablePagination
167 pageSize={STATEMENT_PAGE_SIZE}
168 onRowClick={setViewEntry}
169 />
170 </Suspense>
171 </section>
172
173 <SidePanel
174 open={viewEntry() != null}
175 onOpenChange={(open) => { if (!open) setViewEntry(null); }}
176 title={viewEntry()?.plan_name ?? t("payments.plan")}
177 description={viewEntry()?.due_at == null ? "—" : formatDate(viewEntry()!.due_at, locale())}
178 >
179 <Show when={viewEntry()} keyed>
180 {(entry) => (
181 <div class="grid grid-cols-1 gap-4 sm:grid-cols-2">
182 <DetailField label={t("payments.amountTry")} value={formatTry(entry.amount_minor, moneyLocale())} />
183 <DetailField label={t("payments.credited")} value={formatTry(entry.credited_minor, moneyLocale())} />
184 <DetailField label={t("payments.outstanding")} value={formatTry(entry.outstanding_minor, moneyLocale())} />
185 <DetailField label={t("payments.reversed")} value={entry.reversed ? t("payments.reversed") : "—"} />
186 <DetailField label={t("payments.plan")} value={entry.plan ?? "—"} />
187 <DetailField label={t("admin.id")} value={entry.charge_id} mono />
188 </div>
189 )}
190 </Show>
191 </SidePanel>
192 </div>
193 );
194}