-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathdatabase.route.tsx
More file actions
730 lines (676 loc) · 20.5 KB
/
Copy pathdatabase.route.tsx
File metadata and controls
730 lines (676 loc) · 20.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
import { DatabaseHTTPError, db } from "@databricks/appkit-ui/js";
import {
Badge,
Button,
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
CreateEntity,
EditEntity,
Input,
Label,
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
ViewEntity,
} from "@databricks/appkit-ui/react";
import { createFileRoute } from "@tanstack/react-router";
import {
type FormEvent,
useCallback,
useEffect,
useId,
useMemo,
useState,
} from "react";
import { codeToHtml } from "shiki";
/**
* Database plugin demo: `db.cases` is typed from `config/database/schema.ts`;
* the Vite-generated `database.d.ts` keeps this route honest at compile time.
*/
const STATUS_VALUES = [
"New",
"In Review",
"Pending",
"Closed",
"Escalated",
] as const;
const STATUS_FILTER_ALL = "__all__";
const RISK_BADGE: Record<string, "default" | "secondary" | "destructive"> = {
High: "destructive",
Medium: "secondary",
Low: "default",
};
const CASE_VIEW_FIELDS = [
"case_id",
"entity_name",
"risk_level",
"status",
"assigned_to",
] as const;
const CASE_MUTATION_FIELDS = [
"case_id",
"entity_id",
"entity_name",
"risk_level",
"status",
] as const;
const MANUAL_DB_SNIPPET = `const base =
status === "All" ? db.cases : db.cases.where({ status });
const [rows, count] = await Promise.all([
base
.include({
ai_summaries: true,
activity_log: { select: ["log_id", "action", "created_at"] },
})
.order({ created_at: "desc" })
.limit(50)
.toArray(),
base.count(),
]);
await db.cases.create({
case_id: "CASE-1001",
entity_id: "ENT-5001",
entity_name: "Acme Trading",
risk_level: "Medium",
status: "New",
});
await db.cases.update("CASE-1001", {
status: "Closed",
updated_at: new Date().toISOString(),
});
await db.cases.delete("CASE-1001");`;
const ENTITY_COMPONENTS_SNIPPET = `const [createOpen, setCreateOpen] = useState(false);
const [editingId, setEditingId] = useState<string | null>(null);
<ViewEntity
entity="cases"
fields={["case_id", "entity_name", "risk_level", "status", "assigned_to"]}
order={{ created_at: "desc" }}
limit={8}
onRowClick={(row) => setEditingId(row.case_id)}
/>
<CreateEntity
entity="cases"
fields={["case_id", "entity_id", "entity_name", "risk_level", "status"]}
open={createOpen}
onOpenChange={setCreateOpen}
/>
{editingId && (
<EditEntity
entity="cases"
id={editingId}
fields={["entity_id", "entity_name", "risk_level", "status"]}
open
onOpenChange={(open) => !open && setEditingId(null)}
/>
)}`;
export const Route = createFileRoute("/database")({
component: DatabaseRoute,
});
function DatabaseRoute() {
return (
<div className="min-h-screen bg-background">
<div className="max-w-7xl mx-auto px-6 py-10">
<div className="mb-8 max-w-3xl">
<div className="text-xs font-semibold uppercase tracking-[0.18em] text-muted-foreground mb-3">
Database plugin beta
</div>
<h1 className="text-3xl font-bold tracking-tight mb-3">
Two ways to build on the same typed entity API
</h1>
<p className="text-base text-muted-foreground">
Both sections hit the auto-mounted <code>/api/database/cases</code>{" "}
routes. The left side shows hand-built product UI using{" "}
<code>db.cases</code>; the right side shows the schema-driven entity
components that generate the table and forms from metadata.
</p>
</div>
<div className="grid xl:grid-cols-2 gap-6 items-start">
<ManualDbSection />
<EntityComponentsSection />
</div>
</div>
</div>
);
}
function CodeBlock({
code,
lang = "typescript",
}: {
code: string;
lang?: string;
}) {
const [html, setHtml] = useState("");
useEffect(() => {
let active = true;
codeToHtml(code, {
lang,
theme: "dark-plus",
}).then((highlighted) => {
if (active) setHtml(highlighted);
});
return () => {
active = false;
};
}, [code, lang]);
return (
<div
className="rounded-md overflow-hidden border bg-zinc-950 [&>pre]:m-0 [&>pre]:max-h-[420px] [&>pre]:overflow-auto [&>pre]:p-4 [&>pre]:text-xs [&>pre]:leading-relaxed"
dangerouslySetInnerHTML={{ __html: html }}
/>
);
}
function CodeDisclosure({
code,
label = "Show snippet",
}: {
code: string;
label?: string;
}) {
const [open, setOpen] = useState(false);
return (
<div className="space-y-3">
<Button
type="button"
variant="outline"
size="sm"
onClick={() => setOpen((value) => !value)}
>
{open ? "Hide snippet" : label}
</Button>
{open && <CodeBlock code={code} />}
</div>
);
}
function ManualDbSection() {
const [refreshToken, setRefreshToken] = useState(0);
const refresh = useCallback(() => setRefreshToken((value) => value + 1), []);
return (
<Card className="overflow-hidden">
<CardHeader className="border-b">
<div className="text-xs font-semibold uppercase tracking-[0.16em] text-muted-foreground">
Side A
</div>
<CardTitle>Hand-built UI, typed database client</CardTitle>
<CardDescription>
Custom AML case workflow using direct, typed calls like{" "}
<code>db.cases.where(...)</code>, <code>create</code>,{" "}
<code>update</code>, and <code>delete</code>.
</CardDescription>
</CardHeader>
<CardContent className="space-y-5">
<CodeDisclosure code={MANUAL_DB_SNIPPET} />
<CaseList refreshToken={refreshToken} />
<CreateCase onCreated={refresh} />
</CardContent>
</Card>
);
}
function EntityComponentsSection() {
const [createOpen, setCreateOpen] = useState(false);
const [editingId, setEditingId] = useState<string | null>(null);
const [refreshToken, setRefreshToken] = useState(0);
const refresh = useCallback(() => setRefreshToken((value) => value + 1), []);
return (
<Card className="overflow-hidden">
<CardHeader className="border-b">
<div className="text-xs font-semibold uppercase tracking-[0.16em] text-muted-foreground">
Side B
</div>
<CardTitle>Entity components from the same schema</CardTitle>
<CardDescription>
Generic table and mutation dialogs driven by column metadata from{" "}
<code>config/database/schema.ts</code>.
</CardDescription>
</CardHeader>
<CardContent className="space-y-5">
<CodeDisclosure code={ENTITY_COMPONENTS_SNIPPET} />
<div className="flex flex-wrap items-center justify-between gap-3 rounded-lg border bg-muted/20 p-3">
<div>
<div className="font-medium">Cases entity</div>
<div className="text-sm text-muted-foreground">
Click a row to open the generated edit dialog.
</div>
</div>
<Button onClick={() => setCreateOpen(true)}>
New with component
</Button>
</div>
<ViewEntity
key={refreshToken}
entity="cases"
fields={CASE_VIEW_FIELDS}
order={{ created_at: "desc" }}
limit={8}
onRowClick={(row) => setEditingId(row.case_id)}
/>
<CreateEntity
entity="cases"
fields={CASE_MUTATION_FIELDS}
open={createOpen}
onOpenChange={setCreateOpen}
onSuccess={refresh}
title="Create case with Entity component"
description="The form is generated from database.columns.ts metadata."
/>
{editingId && (
<EditEntity
entity="cases"
id={editingId}
fields={["entity_id", "entity_name", "risk_level", "status"]}
open
onOpenChange={(open) => {
if (!open) setEditingId(null);
}}
onSuccess={refresh}
title={`Edit ${editingId}`}
description="Only editable, non-generated columns are shown."
/>
)}
</CardContent>
</Card>
);
}
async function fetchCasesWithIncludes(status: string, signal?: AbortSignal) {
const base =
status === STATUS_FILTER_ALL ? db.cases : db.cases.where({ status });
return base
.include({
ai_summaries: true,
activity_log: { select: ["log_id", "action", "created_at"] },
})
.order({ created_at: "desc" })
.limit(50)
.toArray(signal);
}
type CaseRow = Awaited<ReturnType<typeof fetchCasesWithIncludes>>[number];
function useCases(status: string, refreshToken: number) {
const [data, setData] = useState<CaseRow[] | null>(null);
const [total, setTotal] = useState<number | null>(null);
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const [tick, setTick] = useState(0);
const refetch = useCallback(() => setTick((n) => n + 1), []);
useEffect(() => {
void refreshToken;
void tick;
const ctrl = new AbortController();
let active = true;
const run = async () => {
setLoading(true);
setError(null);
try {
const base =
status === STATUS_FILTER_ALL ? db.cases : db.cases.where({ status });
const [rows, count] = await Promise.all([
fetchCasesWithIncludes(status, ctrl.signal),
base.count(ctrl.signal),
]);
if (!active) return;
setData(rows);
setTotal(count);
} catch (err) {
if (ctrl.signal.aborted) return;
if (!active) return;
setError(describeError(err));
} finally {
if (active) setLoading(false);
}
};
run();
return () => {
active = false;
ctrl.abort();
};
}, [status, refreshToken, tick]);
return { data, total, loading, error, refetch };
}
function CaseList({ refreshToken }: { refreshToken: number }) {
const [statusFilter, setStatusFilter] = useState<string>(STATUS_FILTER_ALL);
const { data, total, loading, error, refetch } = useCases(
statusFilter,
refreshToken,
);
const statusFilterId = useId();
const filterLabel = useMemo(
() =>
statusFilter === STATUS_FILTER_ALL
? "all statuses"
: `status = "${statusFilter}"`,
[statusFilter],
);
return (
<div>
<div className="flex items-center justify-between gap-4 mb-4">
<div>
<h2 className="text-xl font-semibold">Cases</h2>
<p className="text-sm text-muted-foreground">
{total === null ? "—" : total} row{total === 1 ? "" : "s"} (
{filterLabel})
</p>
</div>
<div className="flex items-center gap-2">
<Label htmlFor={statusFilterId} className="text-sm">
Status
</Label>
<Select value={statusFilter} onValueChange={setStatusFilter}>
<SelectTrigger id={statusFilterId} className="w-[140px]">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value={STATUS_FILTER_ALL}>All</SelectItem>
{STATUS_VALUES.map((s) => (
<SelectItem key={s} value={s}>
{s}
</SelectItem>
))}
</SelectContent>
</Select>
<Button variant="outline" size="sm" onClick={refetch}>
Refresh
</Button>
</div>
</div>
{error && (
<div className="mb-4 rounded-md border border-destructive/40 bg-destructive/5 px-3 py-2 text-sm text-destructive">
{error}
</div>
)}
<div className="rounded-md border overflow-hidden">
<Table>
<TableHeader>
<TableRow>
<TableHead>Case</TableHead>
<TableHead>Entity</TableHead>
<TableHead>Risk</TableHead>
<TableHead>Status</TableHead>
<TableHead>Activity</TableHead>
<TableHead>AI summary</TableHead>
<TableHead>Assigned to</TableHead>
<TableHead className="text-right">Actions</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{data === null && loading && (
<TableRow>
<TableCell
colSpan={8}
className="text-center text-muted-foreground py-8"
>
Loading cases…
</TableCell>
</TableRow>
)}
{data !== null && data.length === 0 && !loading && (
<TableRow>
<TableCell
colSpan={8}
className="text-center text-muted-foreground py-8"
>
No cases match the current filter.
</TableCell>
</TableRow>
)}
{data?.map((row) => (
<CaseRowItem key={row.case_id} row={row} onChanged={refetch} />
))}
</TableBody>
</Table>
</div>
</div>
);
}
function CaseRowItem({
row,
onChanged,
}: {
row: CaseRow;
onChanged: () => void;
}) {
const activityLog = row.activity_log ?? [];
const aiSummary = row.ai_summaries?.[0];
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
const updateStatus = async (next: string) => {
if (next === row.status) return;
setBusy(true);
setError(null);
try {
await db.cases.update(row.case_id, {
status: next,
updated_at: new Date().toISOString(),
});
onChanged();
} catch (err) {
setError(describeError(err));
} finally {
setBusy(false);
}
};
const remove = async () => {
if (!window.confirm(`Delete case ${row.case_id}?`)) return;
setBusy(true);
setError(null);
try {
await db.cases.delete(row.case_id);
onChanged();
} catch (err) {
setError(describeError(err));
setBusy(false);
}
};
return (
<TableRow data-busy={busy} className="align-top">
<TableCell className="font-mono text-xs">
<div className="font-semibold">{row.case_id}</div>
<div className="text-muted-foreground">{row.case_type ?? "—"}</div>
</TableCell>
<TableCell>
<div className="font-medium">{row.entity_name ?? row.entity_id}</div>
<div className="text-xs text-muted-foreground">{row.entity_id}</div>
</TableCell>
<TableCell>
{row.risk_level ? (
<Badge variant={RISK_BADGE[row.risk_level] ?? "default"}>
{row.risk_level} {row.risk_score != null && `(${row.risk_score})`}
</Badge>
) : (
<span className="text-muted-foreground">—</span>
)}
</TableCell>
<TableCell>
<Select value={row.status} onValueChange={updateStatus} disabled={busy}>
<SelectTrigger className="w-[130px] h-8">
<SelectValue />
</SelectTrigger>
<SelectContent>
{STATUS_VALUES.map((s) => (
<SelectItem key={s} value={s}>
{s}
</SelectItem>
))}
</SelectContent>
</Select>
{error && <div className="text-xs text-destructive mt-1">{error}</div>}
</TableCell>
<TableCell className="text-sm">
{activityLog.length > 0 ? (
<span title={activityLog.map((e) => e.action).join(", ")}>
{activityLog.length} event{activityLog.length === 1 ? "" : "s"}
</span>
) : (
<span className="text-muted-foreground">—</span>
)}
</TableCell>
<TableCell className="max-w-[200px]">
{aiSummary ? (
<span
className="text-xs text-muted-foreground line-clamp-2"
title={aiSummary.summary}
>
{aiSummary.summary}
</span>
) : (
<span className="text-muted-foreground text-sm">—</span>
)}
</TableCell>
<TableCell className="text-sm">{row.assigned_to ?? "—"}</TableCell>
<TableCell className="text-right">
<Button
variant="ghost"
size="sm"
onClick={remove}
disabled={busy}
className="text-destructive hover:text-destructive"
>
Delete
</Button>
</TableCell>
</TableRow>
);
}
function CreateCase({ onCreated }: { onCreated: () => void }) {
const [caseId, setCaseId] = useState("");
const [entityId, setEntityId] = useState("");
const [entityName, setEntityName] = useState("");
const [riskLevel, setRiskLevel] = useState("Medium");
const [status, setStatus] = useState("New");
const [busy, setBusy] = useState(false);
const [message, setMessage] = useState<{
kind: "ok" | "err";
text: string;
} | null>(null);
const caseIdField = useId();
const entityIdField = useId();
const entityNameField = useId();
const riskField = useId();
const statusField = useId();
const disabled = busy || caseId.trim() === "" || entityId.trim() === "";
const submit = async (e: FormEvent) => {
e.preventDefault();
if (disabled) return;
setBusy(true);
setMessage(null);
try {
await db.cases.create({
case_id: caseId.trim(),
entity_id: entityId.trim(),
entity_name: entityName.trim() || null,
risk_level: riskLevel,
status,
});
setMessage({ kind: "ok", text: `Created ${caseId.trim()}` });
setCaseId("");
setEntityId("");
setEntityName("");
onCreated();
} catch (err) {
setMessage({ kind: "err", text: describeError(err) });
} finally {
setBusy(false);
}
};
return (
<Card className="p-6 h-fit">
<h2 className="text-xl font-semibold mb-1">New Case</h2>
<p className="text-sm text-muted-foreground mb-4">
Exercises <code>db.cases.create(...)</code>. The server validates the
body against the Zod schema generated from <code>schema.ts</code>.
</p>
<form className="space-y-3" onSubmit={submit}>
<div>
<Label htmlFor={caseIdField}>Case ID</Label>
<Input
id={caseIdField}
placeholder="CASE-1001"
value={caseId}
onChange={(e) => setCaseId(e.target.value)}
disabled={busy}
required
/>
</div>
<div>
<Label htmlFor={entityIdField}>Entity ID</Label>
<Input
id={entityIdField}
placeholder="ENT-5001"
value={entityId}
onChange={(e) => setEntityId(e.target.value)}
disabled={busy}
required
/>
</div>
<div>
<Label htmlFor={entityNameField}>Entity Name</Label>
<Input
id={entityNameField}
placeholder="Acme Trading"
value={entityName}
onChange={(e) => setEntityName(e.target.value)}
disabled={busy}
/>
</div>
<div>
<Label htmlFor={riskField}>Risk Level</Label>
<Select value={riskLevel} onValueChange={setRiskLevel}>
<SelectTrigger id={riskField}>
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="High">High</SelectItem>
<SelectItem value="Medium">Medium</SelectItem>
<SelectItem value="Low">Low</SelectItem>
</SelectContent>
</Select>
</div>
<div>
<Label htmlFor={statusField}>Status</Label>
<Select value={status} onValueChange={setStatus}>
<SelectTrigger id={statusField}>
<SelectValue />
</SelectTrigger>
<SelectContent>
{STATUS_VALUES.map((s) => (
<SelectItem key={s} value={s}>
{s}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
<Button type="submit" disabled={disabled} className="w-full">
{busy ? "Creating…" : "Create case"}
</Button>
{message && (
<div
className={
message.kind === "ok"
? "text-sm text-green-600 dark:text-green-400"
: "text-sm text-destructive"
}
>
{message.text}
</div>
)}
</form>
</Card>
);
}
function describeError(err: unknown): string {
if (err instanceof DatabaseHTTPError) {
const body = err.body as { error?: string; message?: string } | undefined;
return `HTTP ${err.statusCode} — ${body?.error ?? body?.message ?? err.message}`;
}
if (err instanceof Error) return err.message;
return String(err);
}