ecourt+groups: N8 เปิดเอกสารจากลิงก์ ?fileUrl=&fileId=&typeId= (metadata-only + allowlist + ดึงไฟล์สด + login วนกลับ + การ์ดจำลองลิงก์ + path dev /samples) + N9 กลุ่มเอกสารตาม typeId — หน้ารายการจัด section ต่อกลุ่ม + "ไม่มีกลุ่ม" ท้ายสุด + หน้า /groups/[typeId] พร้อมหมายเหตุ "อาจไม่ครบทุกฉบับ" + docs sync ครบ (2026-09-23)

Co-Authored-By: Claude Code <noreply@anthropic.com>
This commit is contained in:
Your Name 2026-09-23 10:44:14 +07:00
parent 0aef3ff028
commit 329ae8e956
31 changed files with 2766 additions and 155 deletions

63
app/annotate/page.tsx Normal file
View file

@ -0,0 +1,63 @@
import Link from "next/link";
import { redirect } from "next/navigation";
import { registerExternalFile } from "@/lib/external-import";
import { firstSearchParam } from "@/utils/external-file";
export const dynamic = "force-dynamic";
/**
* N8 entry point ที่สอง (ตามคำขอผู้ใช้ 2026-09-22): เข้า `/annotate?fileUrl=&fileId=&typeId=`
* โดยตรง — ลงทะเบียนเอกสารแล้ว redirect ต่อไป `/annotate/<id>` ของตัว viewer จริง
* (entry เดิมที่หน้า "/" ยังใช้ได้คู่กัน — สัญญาลิงก์รับทั้ง /?fileUrl= และ /annotate?fileUrl=)
*/
export default async function AnnotateEntryPage({
searchParams,
}: {
searchParams: Record<string, string | string[] | undefined>;
}) {
const fileUrl = firstSearchParam(searchParams.fileUrl);
if (fileUrl) {
const result = await registerExternalFile(
fileUrl,
firstSearchParam(searchParams.fileId),
firstSearchParam(searchParams.typeId),
);
// redirect โยน NEXT_REDIRECT — เรียกนอก try/catch เสมอ
if (result.ok) redirect(`/annotate/${result.fileId}`);
return (
<main className="mx-auto max-w-2xl px-4 py-10 sm:px-8">
<div
role="alert"
className="rounded-xl border border-red-200 bg-red-50 p-4 text-sm text-red-700"
>
เปิดเอกสารจากลิงก์ไม่สำเร็จ: {result.error}
</div>
<Link
href="/"
className="mt-4 inline-block rounded-md bg-primary px-4 py-2 text-sm font-medium text-white transition hover:opacity-90"
>
กลับหน้ารายการ
</Link>
</main>
);
}
// ไม่มี fileUrl เลย — ไม่มีอะไรให้เปิด (route จริงของ viewer อยู่ที่ /annotate/[id])
return (
<main className="mx-auto max-w-2xl px-4 py-10 sm:px-8">
<div className="rounded-xl border border-slate-200 bg-white p-6 text-sm text-slate-600">
ไม่ได้ระบุลิงก์เอกสาร — ใช้ <code className="rounded bg-slate-100 px-1">
/annotate?fileUrl=…&fileId=…&typeId=…
</code>{" "}
หรือเลือกไฟล์จากหน้ารายการ
</div>
<Link
href="/"
className="mt-4 inline-block rounded-md bg-primary px-4 py-2 text-sm font-medium text-white transition hover:opacity-90"
>
กลับหน้ารายการ
</Link>
</main>
);
}

View file

@ -18,6 +18,7 @@ import { and, asc, eq, inArray } from "drizzle-orm";
import { db } from "@/db";
import { PdfPathError, readPublicPdf } from "@/lib/server-pdf";
import { fetchSourceBytes, isRemoteSource, RemoteFileError } from "@/lib/remote-file";
import {
annotationReplies,
annotations,
@ -219,14 +220,24 @@ export async function GET(req: Request) {
if (!file) return new Response("ไม่พบไฟล์นี้", { status: 404 });
// Guard path traversal: pdfUrl จาก DB ต้อง resolve แล้วอยู่ใน public/ เท่านั้น (§5)
// N8: pdf_url เป็นรีโมต (ลิงก์ e-Court) → ดึงสดจาก allowlist แทนการอ่านดิสก์
let srcBytes: Buffer;
try {
srcBytes = readPublicPdf(file.pdfUrl);
} catch (err) {
if (err instanceof PdfPathError) {
return new Response("เส้นทางไฟล์ไม่ถูกต้อง", { status: 403 });
if (isRemoteSource(file.pdfUrl)) {
try {
srcBytes = await fetchSourceBytes(file.pdfUrl);
} catch (err) {
if (err instanceof RemoteFileError) return new Response(err.message, { status: 502 });
throw err;
}
} else {
try {
srcBytes = readPublicPdf(file.pdfUrl);
} catch (err) {
if (err instanceof PdfPathError) {
return new Response("เส้นทางไฟล์ไม่ถูกต้อง", { status: 403 });
}
return new Response("อ่านไฟล์ PDF ต้นฉบับไม่ได้", { status: 404 });
}
return new Response("อ่านไฟล์ PDF ต้นฉบับไม่ได้", { status: 404 });
}
// N3: ไฟล์รูปภาพ — สร้าง PDF ใหม่ที่ฝังรูปเต็มหน้า (embedJpg/embedPng + EXIF rotate)

View file

@ -3,6 +3,7 @@ import { eq } from "drizzle-orm";
import { db } from "@/db";
import { files } from "@/db/schema";
import { fixPdfActualText } from "@/lib/pdf-actual-text";
import { fetchSourceBytes, isRemoteSource, RemoteFileError } from "@/lib/remote-file";
import { PdfPathError, readPublicPdf } from "@/lib/server-pdf";
import { fileKindFromUrl, imageContentTypeFromUrl } from "@/utils/file-kind";
@ -25,12 +26,22 @@ export async function GET(req: Request) {
if (!file) return new Response("ไม่พบไฟล์นี้", { status: 404 });
// Guard path traversal: pdfUrl จาก DB ต้อง resolve แล้วอยู่ใน public/ เท่านั้น (§5)
// N8: pdf_url เป็นรีโมต (ลิงก์ e-Court) → ดึงสดจาก allowlist แทนการอ่านดิสก์
let srcBytes: Buffer;
try {
srcBytes = readPublicPdf(file.pdfUrl);
} catch (err) {
if (err instanceof PdfPathError) return new Response(err.message, { status: 400 });
throw err;
if (isRemoteSource(file.pdfUrl)) {
try {
srcBytes = await fetchSourceBytes(file.pdfUrl);
} catch (err) {
if (err instanceof RemoteFileError) return new Response(err.message, { status: 502 });
throw err;
}
} else {
try {
srcBytes = readPublicPdf(file.pdfUrl);
} catch (err) {
if (err instanceof PdfPathError) return new Response(err.message, { status: 400 });
throw err;
}
}
// N3: ไฟล์รูปภาพไม่มี ToUnicode ให้ซ่อม — คืน bytes ดิบ + content-type ถูกต้อง

View file

@ -0,0 +1,120 @@
import type { Metadata } from "next";
import Link from "next/link";
import { notFound } from "next/navigation";
import { asc, count, eq, inArray } from "drizzle-orm";
import { ArrowLeft, FileImage, FileText, Folder } from "lucide-react";
import { db } from "@/db";
import { annotations, bookmarks, files } from "@/db/schema";
import { formatThaiDate } from "@/utils/date-format";
import { imageFormatFromUrl } from "@/utils/file-kind";
// N9 (PLAN-DOCSET.md D3) — หน้ารวมเอกสารของกลุ่ม (type_id จากลิงก์ e-Court)
// server component force-dynamic — login ถูกบังคับโดย middleware.ts อยู่แล้ว
// snapshot ณ ตอนโหลดเหมือนหน้าสรุป F15 (ไม่มี SSE) — กลุ่มไม่มีไฟล์เลย = 404
// เพราะไม่มีตารางกลุ่ม: กลุ่มมีชีวิตตามข้อมูลจริงใน files ณ ตอน query
export const dynamic = "force-dynamic";
export async function generateMetadata({
params,
}: {
params: { typeId: string };
}): Promise<Metadata> {
return { title: `กลุ่มเอกสาร ${params.typeId} | Judge's Note` };
}
export default async function GroupPage({
params,
}: {
params: { typeId: string };
}) {
const { typeId } = params;
const rows = await db
.select()
.from(files)
.where(eq(files.typeId, typeId))
.orderBy(asc(files.createdAt));
if (rows.length === 0) notFound();
// จำนวน annotation/bookmark ต่อไฟล์ — 2 query แยกด้วย groupBy fileId (ไม่ join หนัก)
const ids = rows.map((f) => f.id);
const [annCounts, bmCounts] = await Promise.all([
db
.select({ fileId: annotations.fileId, n: count() })
.from(annotations)
.where(inArray(annotations.fileId, ids))
.groupBy(annotations.fileId),
db
.select({ fileId: bookmarks.fileId, n: count() })
.from(bookmarks)
.where(inArray(bookmarks.fileId, ids))
.groupBy(bookmarks.fileId),
]);
// drizzle count() ใช้ .mapWith(Number) ให้แล้ว — r.n เป็น number ทั้ง type และ runtime
const annByFile = new Map(annCounts.map((r) => [r.fileId, r.n]));
const bmByFile = new Map(bmCounts.map((r) => [r.fileId, r.n]));
return (
<main className="mx-auto max-w-2xl px-4 py-10 sm:px-8">
<Link
href="/"
className="inline-flex items-center gap-1.5 text-sm text-slate-500 transition hover:text-primary"
>
<ArrowLeft className="h-4 w-4" />
หน้ารายการ
</Link>
<header className="mt-4 flex items-center gap-3">
<div className="flex h-11 w-11 shrink-0 items-center justify-center rounded-xl bg-primary/10">
<Folder className="h-5 w-5 text-primary" />
</div>
<div className="min-w-0">
<h1 className="break-all text-xl font-bold leading-tight text-primary">
{typeId}
</h1>
<p className="text-sm text-slate-500">{rows.length} เอกสาร</p>
</div>
</header>
{/* หมายเหตุแสดงทุกครั้ง (แผน N9 D3): ระบบรู้จักเฉพาะเอกสารที่เคยเปิดผ่านลิงก์ e-Court
รายการครบทั้งคดีอยู่ใน e-Court ไม่ใช่ระบบนี้ */}
<div className="mt-4 rounded-xl border border-blue-200 bg-blue-50 p-4 text-sm text-blue-800">
แสดงเฉพาะเอกสารที่เคยเปิดในระบบนี้ — อาจไม่ครบทุกฉบับของกลุ่ม
</div>
<ul className="mt-6 space-y-3">
{rows.map((f) => (
<li
key={f.id}
className="group flex items-center gap-3 rounded-xl border border-slate-200 bg-white p-4 shadow-sm transition hover:border-primary/30 hover:shadow-md"
>
<div className="flex h-10 w-10 shrink-0 items-center justify-center rounded-lg bg-primary/10">
{imageFormatFromUrl(f.pdfUrl) ? (
<FileImage className="h-5 w-5 text-primary" />
) : (
<FileText className="h-5 w-5 text-primary" />
)}
</div>
<span className="min-w-0 flex-1">
<span className="block break-all line-clamp-2 text-sm font-medium text-slate-900">
{f.title}
</span>
<span className="mt-0.5 block text-xs text-slate-500">
นำเข้า {formatThaiDate(f.createdAt, true)} · หมายเหตุ{" "}
{annByFile.get(f.id) ?? 0} · ที่คั่นหน้า {bmByFile.get(f.id) ?? 0}
</span>
</span>
<Link
href={`/annotate/${f.id}`}
className="shrink-0 rounded-md bg-primary px-4 py-2 text-sm font-medium text-white transition hover:opacity-90 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary focus-visible:ring-offset-1"
>
Annotate
</Link>
</li>
))}
</ul>
</main>
);
}

View file

@ -3,19 +3,29 @@ import { redirect } from "next/navigation";
import LoginForm from "@/components/LoginForm";
import { getSessionUser } from "@/lib/session";
import { firstSearchParam, sanitizeNextPath } from "@/utils/external-file";
export const dynamic = "force-dynamic";
export const metadata: Metadata = { title: "เข้าสู่ระบบ | Judge's Note" };
export default function LoginPage() {
export default function LoginPage({
searchParams,
}: {
searchParams: Record<string, string | string[] | undefined>;
}) {
// N8 D5: path วนกลับหลัง login (middleware แนบมาตอน redirect เข้าหน้านี้) —
// ค่ามาจาก query ที่ใครก็แก้ได้ ต้อง sanitize กัน open-redirect ก่อนใช้เสมอ
const rawNext = firstSearchParam(searchParams.next);
const next = rawNext !== undefined ? sanitizeNextPath(rawNext) : null;
// เข้าสู่ระบบอยู่แล้ว (cookie ครบ) → ไม่ต้องเห็นฟอร์มอีก
const user = getSessionUser();
if (user) redirect("/");
if (user) redirect(next ?? "/");
return (
<main className="flex min-h-dvh items-center justify-center px-4 py-10">
<LoginForm />
<LoginForm next={next} />
</main>
);
}

View file

@ -1,18 +1,23 @@
import Link from "next/link";
import { redirect } from "next/navigation";
import { asc } from "drizzle-orm";
import { FileImage, FileText } from "lucide-react";
import { FileImage, FileText, Folder } from "lucide-react";
import { db } from "@/db";
import { files } from "@/db/schema";
import EcourtLinkForm from "@/components/EcourtLinkForm";
import SessionBar from "@/components/SessionBar";
import UploadFileForm from "@/components/UploadFileForm";
import { imageFormatFromUrl } from "@/utils/file-kind";
import { formatThaiDate } from "@/utils/date-format";
import { getSessionUser } from "@/lib/session";
import { registerExternalFile } from "@/lib/external-import";
import { firstSearchParam } from "@/utils/external-file";
export const dynamic = "force-dynamic";
type FileRow = typeof files.$inferSelect;
/** badge ชนิดไฟล์ต่อรายการ (N3) */
function kindBadge(pdfUrl: string): string {
switch (imageFormatFromUrl(pdfUrl)) {
@ -27,13 +32,86 @@ function kindBadge(pdfUrl: string): string {
}
}
export default async function HomePage() {
/** การ์ดไฟล์ของหน้ารายการ — ใช้ร่วมทุก section (N9 จัดกลุ่มแล้วยังหน้าตาเดิม) */
function FileCard({ file }: { file: FileRow }) {
return (
<li className="group flex items-center gap-3 rounded-xl border border-slate-200 bg-white p-4 shadow-sm transition hover:border-primary/30 hover:shadow-md">
<div className="flex h-10 w-10 shrink-0 items-center justify-center rounded-lg bg-primary/10">
{imageFormatFromUrl(file.pdfUrl) ? (
<FileImage className="h-5 w-5 text-primary" />
) : (
<FileText className="h-5 w-5 text-primary" />
)}
</div>
<span className="min-w-0 flex-1">
<span className="block break-all line-clamp-2 text-sm font-medium text-slate-900">
{file.title}
</span>
<span className="mt-0.5 block text-xs text-slate-500">
<span className="mr-1.5 rounded bg-slate-100 px-1 py-0.5 font-medium text-slate-500">
{kindBadge(file.pdfUrl)}
</span>
{formatThaiDate(file.createdAt, true)}
</span>
</span>
{/* ปุ่มเข้า annotate แทนลิงก์กางเต็มการ์ด (M4) ตาม feedback — เป้าจิ้ม 36px (H4) */}
<Link
href={`/annotate/${file.id}`}
className="shrink-0 rounded-md bg-primary px-4 py-2 text-sm font-medium text-white transition hover:opacity-90 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary focus-visible:ring-offset-1"
>
Annotate
</Link>
</li>
);
}
export default async function HomePage({
searchParams,
}: {
searchParams: Record<string, string | string[] | undefined>;
}) {
// defense ซ้อน middleware — หน้านี้อ่าน cookie อยู่ดีจึงกันซ้ำไม่ให้ render รายการให้คนไม่มี session
const user = getSessionUser();
if (!user) redirect("/login");
// N8: เข้าจากลิงก์ e-Court ?fileUrl=&fileId=&typeId= — ลงทะเบียนเอกสาร (metadata-only
// dedupe ด้วย external_id) แล้วพาเข้า viewer เลย — redirect() โยน NEXT_REDIRECT
// ต้องเรียกนอก try/catch เสมอ; หน้านี้ force-dynamic จึงไม่ต้อง revalidatePath
// (entry ที่สองอยู่ที่ /annotate?fileUrl=… — app/annotate/page.tsx)
let registerError: string | null = null;
const fileUrl = firstSearchParam(searchParams.fileUrl);
if (fileUrl) {
const result = await registerExternalFile(
fileUrl,
firstSearchParam(searchParams.fileId),
firstSearchParam(searchParams.typeId),
);
if (result.ok) redirect(`/annotate/${result.fileId}`);
registerError = result.error;
}
const rows = await db.select().from(files).orderBy(asc(files.createdAt));
// N9: จัดกลุ่มตาม type_id — การ์ดในกลุ่มเรียง createdAt เหมือนเดิม (ตาม query ที่ asc)
// ส่วนลำดับกลุ่มเรียงตาม createdAt ของไฟล์ล่าสุดในกลุ่ม (กลุ่มที่มี activity ใหม่อยู่บน)
// ไฟล์ type_id NULL (seed/อัปโหลด N4/ลิงก์ไม่มี typeId) = section "ไม่มีกลุ่ม" ท้ายสุด
const grouped = new Map<string, FileRow[]>();
const ungrouped: FileRow[] = [];
for (const f of rows) {
if (f.typeId) {
const list = grouped.get(f.typeId);
if (list) list.push(f);
else grouped.set(f.typeId, [f]);
} else {
ungrouped.push(f);
}
}
const sections = Array.from(grouped.entries()).sort(
(a, b) =>
b[1][b[1].length - 1].createdAt.getTime() -
a[1][a[1].length - 1].createdAt.getTime(),
);
return (
<main className="mx-auto max-w-2xl px-4 py-10 sm:px-8">
<header className="flex items-center gap-3">
@ -52,6 +130,18 @@ export default async function HomePage() {
<SessionBar userName={user.userName} />
{registerError && (
<div
role="alert"
className="mt-6 rounded-xl border border-red-200 bg-red-50 p-4 text-sm text-red-700"
>
เปิดเอกสารจากลิงก์ไม่สำเร็จ: {registerError}
</div>
)}
{/* การ์ดเปิดเอกสารจากลิงก์ e-Court — บล็อกแยกของตัวเอง มีหัวเรื่องในตัวแล้ว (N8) */}
<EcourtLinkForm />
<section className="mt-8">
<h2 className="text-sm font-semibold text-slate-700">เพิ่มเอกสาร</h2>
<UploadFileForm />
@ -75,40 +165,50 @@ export default async function HomePage() {
</p>
</div>
) : (
<ul className="mt-3 space-y-3">
{rows.map((f) => (
<li
key={f.id}
className="group flex items-center gap-3 rounded-xl border border-slate-200 bg-white p-4 shadow-sm transition hover:border-primary/30 hover:shadow-md"
>
<div className="flex h-10 w-10 shrink-0 items-center justify-center rounded-lg bg-primary/10">
{imageFormatFromUrl(f.pdfUrl) ? (
<FileImage className="h-5 w-5 text-primary" />
) : (
<FileText className="h-5 w-5 text-primary" />
)}
<>
{sections.map(([typeId, list]) => (
<section key={typeId} className="mt-6">
<div className="flex items-center gap-2 border-b border-slate-200 pb-2">
<Folder className="h-4 w-4 shrink-0 text-primary" />
<span className="min-w-0 break-all text-sm font-semibold text-slate-700">
{typeId}
</span>
<span className="shrink-0 text-xs tabular-nums text-slate-500">
{list.length} ไฟล์
</span>
{/* Next Link เติม basePath ให้เอง (invariant #12) */}
<Link
href={`/groups/${encodeURIComponent(typeId)}`}
className="ml-auto shrink-0 rounded text-xs font-medium text-primary hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary focus-visible:ring-offset-1"
>
เอกสารในกลุ่ม
</Link>
</div>
<span className="min-w-0 flex-1">
<span className="block break-all line-clamp-2 text-sm font-medium text-slate-900">
{f.title}
</span>
<span className="mt-0.5 block text-xs text-slate-500">
<span className="mr-1.5 rounded bg-slate-100 px-1 py-0.5 font-medium text-slate-500">
{kindBadge(f.pdfUrl)}
</span>
{formatThaiDate(f.createdAt, true)}
</span>
</span>
{/* ปุ่มเข้า annotate แทนลิงก์กางเต็มการ์ด (M4) ตาม feedback — เป้าจิ้ม 36px (H4) */}
<Link
href={`/annotate/${f.id}`}
className="shrink-0 rounded-md bg-primary px-4 py-2 text-sm font-medium text-white transition hover:opacity-90 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary focus-visible:ring-offset-1"
>
Annotate
</Link>
</li>
<ul className="mt-3 space-y-3">
{list.map((f) => (
<FileCard key={f.id} file={f} />
))}
</ul>
</section>
))}
</ul>
{ungrouped.length > 0 && (
<section className="mt-6">
<div className="flex items-center gap-2 border-b border-slate-200 pb-2">
<span className="text-sm font-semibold text-slate-700">
ไม่มีกลุ่ม
</span>
<span className="text-xs tabular-nums text-slate-500">
{ungrouped.length} ไฟล์
</span>
</div>
<ul className="mt-3 space-y-3">
{ungrouped.map((f) => (
<FileCard key={f.id} file={f} />
))}
</ul>
</section>
)}
</>
)}
</main>
);