Files
web-alterflixhub/app/routes/admin.tsx
T
Bkk1234 1932098a1d feat(home): ชั้นกรองที่ 1 — ประเภทโรงหนัง (ท้องถิ่น / อินดี้ / กลุ่มคนฉายหนัง)
- แถบกรองสองชั้นในแถวเดียว: ทั้งหมด → 3 ประเภท │ ยอดนิยม → หมวดภาพยนตร์เดิม
- เก็บประเภทที่ฟิลด์เดี่ยว cinema.venue_type (ค่าเดียว) + hasVenue()/filterCinemas({ venue })
- ย้าย "กลุ่มคนฉายหนัง" จาก categories ขึ้นชั้น 1 (ไม่ให้ปุ่มซ้ำ) · tag ยังอยู่และยังค้นหาเจอ
- เลือกได้ทีละชั้น: กดประเภทล้างหมวด / กดหมวดล้างประเภท / ทั้งหมดล้างทั้งคู่
- ปิด popularity path เมื่อกรองด้วยประเภท (กันจัดอันดับข้ามประเภท)
- หลังบ้าน: ช่อง "ประเภทโรงหนัง" ในหมวดข้อมูลหลัก + sanitize เฉพาะค่าใน VENUE_TYPES
- i18n: messages.venues (TH/EN) · override ได้ผ่าน site.terms
- scripts/set-venue-types.mjs จัดประเภท 29 โรง (15 ท้องถิ่น / 11 อินดี้ / 3 กลุ่มคนฉายหนัง) พร้อมสำรอง content.json
- tests: hasVenue + filterCinemas (165 ผ่าน) · sw v2.0.5 · DESIGN/AGENTS/README/admin-guide/api อัปเดต
2026-11-16 01:46:59 +07:00

1358 lines
56 KiB
TypeScript

import { useEffect, useMemo, useState } from "react";
import { useNavigate } from "react-router";
import { AboutEditor } from "@/components/admin/AboutEditor";
import { AdminSection } from "@/components/admin/AdminSection";
import { ArticleEditor } from "@/components/admin/ArticleEditor";
import { ChipPicker, toggleValue } from "@/components/admin/ChipPicker";
import { CinemaFacilitiesEditor } from "@/components/admin/CinemaFacilitiesEditor";
import { CinemaList, hasSameOrder } from "@/components/admin/CinemaList";
import { CommaListInput } from "@/components/admin/CommaListInput";
import { ContactsEditor } from "@/components/admin/ContactsEditor";
import { PhotosEditor } from "@/components/admin/PhotosEditor";
import { SlugInput, suggestSlug } from "@/components/admin/SlugInput";
import { TransportEditor } from "@/components/admin/TransportEditor";
import { FOOTER_ICON_NAMES } from "@/components/site/footer-icons";
import type { AnalyticsSummary } from "@/lib/analytics-types";
import {
ASSIGNABLE_CATEGORIES,
VENUE_TYPES,
type Cinema,
type VenueType,
} from "@/lib/cinemas";
import {
seedAbout,
seedForCinemas,
seedForFilmLovers,
} from "@/lib/content-seed";
import type {
AboutContent,
ArticleContent,
ContentStore,
FooterItem,
TermEntry,
} from "@/lib/content-types";
import {
DEFAULT_LOCALE,
FACILITY_KEYS,
MESSAGES,
type FacilityKey,
} from "@/lib/i18n/messages";
import { resolvePageOrigin } from "@/lib/page-origin";
import { originFromMatches, pageMeta } from "@/lib/seo";
/** meta() ของ route ลูกอ่าน origin ที่ root loader หาไว้ (ไม่ฝังโดเมน) */
type MetaArgs = { matches?: Array<{ id?: string; data?: unknown }> };
/** หน้าหลังบ้าน — ไม่ให้ search engine เก็บ (ทั้งหน้าและ API ที่เรียกจากหน้านี้) */
export async function loader({ request }: { request: Request }) {
return { origin: resolvePageOrigin(request) };
}
export function meta({ loaderData }: { loaderData?: { origin?: string } }) {
return pageMeta({
origin: loaderData?.origin ?? "",
title: "หลังบ้าน — AlterFlixHub",
description: "หน้าจัดการเนื้อหาและข้อมูลโรงหนังสำหรับผู้ดูแลเว็บไซต์",
path: "/admin",
noIndex: true,
});
}
const ADMIN_MESSAGES = MESSAGES[DEFAULT_LOCALE];
const CATEGORY_ORDER: string[] = [...ASSIGNABLE_CATEGORIES];
const CATEGORY_OPTIONS = ASSIGNABLE_CATEGORIES.map((category) => ({
value: category,
label: ADMIN_MESSAGES.categories[category],
}));
const FACILITY_OPTIONS = FACILITY_KEYS.map((key) => ({
value: key,
label: ADMIN_MESSAGES.facilities[key].title,
}));
const inputClass =
"w-full rounded-lg border border-[#303030] bg-[#141414] px-3 py-2 text-sm text-white outline-none focus:border-[#A92626]";
const labelClass = "flex flex-col gap-1 text-xs text-[#999]";
const buttonClass =
"rounded-lg border border-[#303030] px-3 py-2 text-sm transition hover:border-[#A92626] hover:text-[#D47272]";
const primaryButtonClass =
"rounded-lg bg-[#8F0808] px-4 py-2 text-sm font-medium transition hover:bg-[#a30a0a]";
type Tab =
| "cinemas"
| "about"
| "forCinemas"
| "forFilmLovers"
| "terms"
| "footer"
| "stats";
function newCinema(): Cinema {
return {
slug: `cinema-${Date.now()}`,
name: "โรงหนังใหม่",
tags: [],
location_label: "",
location_label_en: "",
coordinates: null,
description: "",
description_en: "",
map_url: null,
address_lines: [],
address_lines_en: [],
transport: [],
contacts: [],
payments: ["เงินสด"],
facilities: [],
photos: [],
};
}
export default function AdminRoute() {
const navigate = useNavigate();
const [tab, setTab] = useState<Tab>("cinemas");
const [store, setStore] = useState<ContentStore | null>(null);
/** ลำดับ cinemas ที่บันทึกล่าสุด — ใช้เทียบว่ามีการสลับตำแหน่งค้างอยู่หรือไม่ */
const [savedCinemas, setSavedCinemas] = useState<Cinema[]>([]);
const [status, setStatus] = useState<string | null>(null);
const [selected, setSelected] = useState<string | null>(null);
const [jsonDraft, setJsonDraft] = useState("");
const [importDraft, setImportDraft] = useState("");
const [analytics, setAnalytics] = useState<AnalyticsSummary | null>(null);
const [analyticsDays, setAnalyticsDays] = useState(7);
const [saving, setSaving] = useState(false);
useEffect(() => {
void (async () => {
const response = await fetch("/api/admin/content");
if (response.status === 401) {
navigate("/admin/login");
return;
}
const data = (await response.json()) as ContentStore;
setStore(data);
setSavedCinemas(data.cinemas);
setSelected(data.cinemas[0]?.slug ?? null);
})();
}, [navigate]);
const cinema = useMemo(
() => store?.cinemas.find((item) => item.slug === selected) ?? null,
[store, selected],
);
useEffect(() => {
setJsonDraft(cinema ? JSON.stringify(cinema, null, 2) : "");
}, [cinema]);
useEffect(() => {
if (tab !== "stats") return;
void (async () => {
const response = await fetch(
`/api/admin/analytics?days=${analyticsDays}`,
);
if (!response.ok) return;
setAnalytics((await response.json()) as AnalyticsSummary);
})();
}, [tab, analyticsDays]);
function flash(message: string) {
setStatus(message);
setTimeout(() => setStatus(null), 2500);
}
async function save(payload: Partial<ContentStore>): Promise<boolean> {
setSaving(true);
try {
const response = await fetch("/api/admin/content", {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(payload),
});
if (!response.ok) {
const data = (await response.json().catch(() => ({}))) as {
statusMessage?: string;
message?: string;
};
flash(data.statusMessage ?? data.message ?? "บันทึกไม่สำเร็จ");
return false;
}
const saved = (await response.json()) as ContentStore;
setStore(saved);
setSavedCinemas(saved.cinemas);
flash("บันทึกแล้ว");
return true;
} finally {
setSaving(false);
}
}
function updateCinema(next: Cinema) {
if (!store) return;
setStore({
...store,
cinemas: store.cinemas.map((item) =>
item.slug === next.slug ? next : item,
),
});
}
function updateCinemas(cinemas: Cinema[]) {
if (!store) return;
setStore({ ...store, cinemas });
}
/**
* แก้โรงหนังหนึ่งรายการแบบ functional update
* ใช้กับการกดชิปหลายครั้งติดกัน (ถ้าอ่าน store จาก closure ค่าจะตกหล่น)
*/
function patchCinema(slug: string, patch: (current: Cinema) => Cinema) {
setStore((prev) =>
prev
? {
...prev,
cinemas: prev.cinemas.map((item) =>
item.slug === slug ? patch(item) : item,
),
}
: prev,
);
}
function updateSite(site: ContentStore["site"]) {
if (!store) return;
setStore({ ...store, site });
}
function updateAbout(about: Record<"th" | "en", AboutContent>) {
if (!store) return;
setStore({ ...store, about });
}
function updateForCinemas(forCinemas: Record<"th" | "en", ArticleContent>) {
if (!store) return;
setStore({ ...store, forCinemas });
}
function updateForFilmLovers(
forFilmLovers: Record<"th" | "en", ArticleContent>,
) {
if (!store) return;
setStore({ ...store, forFilmLovers });
}
const aboutDefaults = useMemo(() => seedAbout(), []);
const forCinemasDefaults = useMemo(() => seedForCinemas(), []);
const forFilmLoversDefaults = useMemo(() => seedForFilmLovers(), []);
if (!store) {
return (
<div className="flex min-h-dvh items-center justify-center bg-[#0D0D0D] text-sm text-[#999]">
กำลังโหลดข้อมูลหลังบ้าน…
</div>
);
}
const terms = store.site.terms;
const locales = store.site.locales;
return (
<div className="min-h-dvh bg-[#0D0D0D] text-white">
<header className="sticky top-0 z-10 flex flex-wrap items-center justify-between gap-3 border-b border-[#242424] bg-[#0D0D0D]/95 px-6 py-4">
<div>
<h1 className="text-xl font-semibold">หลังบ้าน AlterFlixHub</h1>
<p className="text-xs text-[#999]">
{store.cinemas.length} โรงหนัง · {terms.length} คำศัพท์ ·{" "}
{store.site.footer.length} ไอคอน footer
</p>
</div>
<div className="flex items-center gap-2">
{status ? (
<span className="text-xs text-[#D47272]">{status}</span>
) : null}
<a href="/" className={buttonClass} target="_blank" rel="noreferrer">
ดูหน้าเว็บ
</a>
<button
type="button"
className={buttonClass}
onClick={async () => {
await fetch("/api/admin/logout", { method: "POST" });
navigate("/admin/login");
}}
>
ออกจากระบบ
</button>
</div>
</header>
<nav className="flex gap-2 px-6 pt-4">
{(
[
["cinemas", "โรงหนัง"],
["about", "หน้าเกี่ยวกับเรา"],
["forCinemas", "สำหรับคนทำโรงหนัง"],
["forFilmLovers", "สำหรับคนรักหนัง"],
["terms", "คำศัพท์หลายภาษา"],
["footer", "Footer / ไอคอน"],
["stats", "สถิติการค้นหา"],
] as Array<[Tab, string]>
).map(([key, label]) => (
<button
key={key}
type="button"
onClick={() => setTab(key)}
className={`rounded-lg px-4 py-2 text-sm transition ${
tab === key
? "bg-[#242424] text-white"
: "text-[#999] hover:text-white"
}`}
>
{label}
</button>
))}
</nav>
{tab === "cinemas" ? (
<div className="grid gap-6 px-6 py-5 lg:grid-cols-[280px_minmax(0,1fr)]">
<aside className="flex flex-col gap-2">
<button
type="button"
className={primaryButtonClass}
onClick={() => {
const created = newCinema();
updateCinemas([...store.cinemas, created]);
setSelected(created.slug);
}}
>
+ เพิ่มโรงหนัง
</button>
<CinemaList
cinemas={store.cinemas}
selected={selected}
dirty={!hasSameOrder(store.cinemas, savedCinemas)}
saving={saving}
onSelect={setSelected}
onReorder={updateCinemas}
onSaveOrder={() => void save({ cinemas: store.cinemas })}
/>
</aside>
<section className="flex flex-col gap-4">
{cinema ? (
<>
<AdminSection
title="ข้อมูลหลัก"
description="ชื่อ · slug · การแสดงบนหน้าเว็บ"
defaultOpen
>
<div className="grid gap-3 sm:grid-cols-2">
<label className={labelClass}>
ชื่อโรงหนัง (EN)
<input
className={inputClass}
value={cinema.name}
onChange={(event) => {
const nextName = event.target.value;
// slug ตามชื่ออังกฤษอัตโนมัติ จนกว่าจะแก้เอง
const previousAuto = suggestSlug(cinema.name);
const follows =
cinema.slug === "" ||
cinema.slug === previousAuto ||
/^cinema-\d+$/.test(cinema.slug);
const nextSlug = follows
? suggestSlug(nextName) || cinema.slug
: cinema.slug;
patchCinema(cinema.slug, (current) => ({
...current,
name: nextName,
slug: nextSlug,
}));
if (nextSlug !== cinema.slug) setSelected(nextSlug);
}}
/>
</label>
<label className={labelClass}>
ชื่อโรงหนัง (TH)
<input
className={inputClass}
value={cinema.name_th ?? ""}
onChange={(event) =>
updateCinema({
...cinema,
name_th: event.target.value,
})
}
/>
</label>
<label className={labelClass}>
ประเภทโรงหนัง (ตัวกรองชั้นแรกบนหน้าแรก)
<select
className={inputClass}
value={cinema.venue_type ?? ""}
onChange={(event) =>
updateCinema({
...cinema,
venue_type:
event.target.value === ""
? null
: (event.target.value as VenueType),
})
}
>
<option value="">— ยังไม่จัดประเภท —</option>
{VENUE_TYPES.map((venue) => (
<option key={venue} value={venue}>
{venue}
</option>
))}
</select>
</label>
<label className={labelClass}>
slug (ใช้ใน URL)
<SlugInput
className={inputClass}
value={cinema.slug}
others={store.cinemas.map((item) => item.slug)}
onChange={(next) => {
patchCinema(cinema.slug, (current) => ({
...current,
slug: next,
}));
setSelected(next);
}}
/>
<span className="text-[11px] text-[#777]">
ดึงจากชื่ออังกฤษอัตโนมัติ · แก้เองได้ตลอด (แก้แล้วจะไม่ถูกทับ)
</span>
<label className="mt-1 flex items-center gap-2 text-xs text-[#B3B3B3]">
<input
type="checkbox"
className="size-4 accent-[#8F0808]"
checked={cinema.hidden === true}
onChange={(event) =>
patchCinema(cinema.slug, (current) => ({
...current,
hidden: event.target.checked,
}))
}
/>
ซ่อนโรงนี้จากหน้าเว็บ (ไม่ขึ้นในรายการ/ค้นหา — เข้า URL ตรงยังได้)
</label>
</label>
</div>
</AdminSection>
<AdminSection
title="หมวดหมู่ & สิ่งอำนวยความสะดวก"
description="ชิปที่เลือก = แสดงบนหน้าโรงหนัง"
badge={`${cinema.tags.length} หมวด · ${(cinema.facilities ?? []).length} หัวข้อ`}
>
<div className="grid gap-3 sm:grid-cols-2">
<div className="flex flex-col gap-2 sm:col-span-2">
<span className="text-xs text-[#999]">หมวดหมู่</span>
<ChipPicker
options={CATEGORY_OPTIONS}
selected={cinema.tags}
onToggle={(value) =>
patchCinema(cinema.slug, (current) => ({
...current,
tags: toggleValue(
current.tags,
value,
CATEGORY_ORDER,
),
}))
}
/>
<CommaListInput
className={inputClass}
value={cinema.tags}
onChangeValue={(tags) =>
patchCinema(cinema.slug, (current) => ({
...current,
tags,
}))
}
placeholder="หรือพิมพ์เอง (คั่นด้วย ,)"
/>
</div>
<div className="flex flex-col gap-2 sm:col-span-2">
<span className="text-xs text-[#999]">
สิ่งอำนวยความสะดวก
</span>
<ChipPicker
options={FACILITY_OPTIONS}
selected={cinema.facilities ?? []}
onToggle={(value) =>
patchCinema(cinema.slug, (current) => ({
...current,
facilities: toggleValue(
current.facilities ?? [],
value,
FACILITY_KEYS,
) as FacilityKey[],
}))
}
/>
<span className="text-[11px] text-[#777]">
ไม่เลือกเลย = หน้าเว็บแสดง “ไม่มีข้อมูล”
</span>
<CinemaFacilitiesEditor
facilities={cinema.facilities ?? []}
details={cinema.facility_details ?? {}}
hasDescriptions={cinema.slug === "house-cinema-samyan"}
onChange={(facility_details) =>
patchCinema(cinema.slug, (current) => ({
...current,
facility_details,
}))
}
inputClass={inputClass}
labelClass={labelClass}
/>
</div>
</div>
</AdminSection>
<AdminSection
title="การเดินทาง & การติดต่อ"
description="รวมรูปภาพและช่องทางชำระเงิน"
badge={`${cinema.transport.length} เส้นทาง · ${cinema.photos.length} รูป`}
>
<div className="grid gap-3 sm:grid-cols-2">
<div className="sm:col-span-2">
<TransportEditor
value={cinema.transport}
onChange={(transport) =>
patchCinema(cinema.slug, (current) => ({
...current,
transport,
}))
}
inputClass={inputClass}
labelClass={labelClass}
/>
</div>
<label className="sm:col-span-2 flex flex-col gap-1 text-xs text-[#999]">
หัวข้อ “สอบถามข้อมูลและจองตั๋ว” (เฉพาะโรงนี้)
<input
className={inputClass}
value={cinema.contact_heading ?? ""}
placeholder="สอบถามข้อมูลและจองตั๋ว"
onChange={(event) =>
patchCinema(cinema.slug, (current) => ({
...current,
contact_heading: event.target.value,
}))
}
/>
<span className="text-[11px] text-[#777]">
เว้นว่าง = ใช้ค่ากลาง (แก้ได้ที่แท็บ “คำศัพท์หลายภาษา” →
detail.contactTitle)
</span>
</label>
<div className="sm:col-span-2">
<ContactsEditor
contacts={cinema.contacts}
onChange={(contacts) =>
patchCinema(cinema.slug, (current) => ({
...current,
contacts,
}))
}
inputClass={inputClass}
labelClass={labelClass}
/>
</div>
<div className="sm:col-span-2">
<PhotosEditor
photos={cinema.photos}
cinemaSlug={cinema.slug}
onChange={(photos) =>
patchCinema(cinema.slug, (current) => ({
...current,
photos,
}))
}
inputClass={inputClass}
labelClass={labelClass}
/>
</div>
<label className={labelClass}>
ชำระเงิน (คั่นด้วย ,)
<CommaListInput
className={inputClass}
value={cinema.payments}
onChangeValue={(payments) =>
patchCinema(cinema.slug, (current) => ({
...current,
payments,
}))
}
placeholder="เงินสด, โอน, บัตรเครดิต"
/>
</label>
</div>
</AdminSection>
<AdminSection
title="ที่ตั้ง & แผนที่"
description="ที่อยู่ พิกัด และลิงก์ Google Maps"
badge={cinema.coordinates ? "มีพิกัด" : "ยังไม่มีพิกัด"}
>
<div className="grid gap-3 sm:grid-cols-2">
<label className={labelClass}>
ที่ตั้ง (TH)
<input
className={inputClass}
value={cinema.location_label}
onChange={(event) =>
updateCinema({
...cinema,
location_label: event.target.value,
})
}
/>
</label>
<label className={labelClass}>
ที่ตั้ง (EN)
<input
className={inputClass}
value={cinema.location_label_en ?? ""}
onChange={(event) =>
updateCinema({
...cinema,
location_label_en: event.target.value,
})
}
/>
</label>
<label className={labelClass}>
ละติจูด (คำนวณระยะทาง)
<input
className={inputClass}
value={cinema.coordinates?.latitude ?? ""}
onChange={(event) => {
const text = event.target.value.trim();
if (text === "") {
updateCinema({ ...cinema, coordinates: null });
return;
}
const latitude = Number(text);
updateCinema({
...cinema,
coordinates: Number.isFinite(latitude)
? {
latitude,
longitude: cinema.coordinates?.longitude ?? 0,
}
: null,
});
}}
/>
</label>
<label className={labelClass}>
ลองจิจูด
<input
className={inputClass}
value={cinema.coordinates?.longitude ?? ""}
onChange={(event) => {
const text = event.target.value.trim();
if (text === "") {
updateCinema({ ...cinema, coordinates: null });
return;
}
const longitude = Number(text);
updateCinema({
...cinema,
coordinates: Number.isFinite(longitude)
? {
latitude: cinema.coordinates?.latitude ?? 0,
longitude,
}
: null,
});
}}
/>
</label>
<label className={labelClass}>
Google map URL
<input
className={inputClass}
value={cinema.map_url ?? ""}
onChange={(event) =>
updateCinema({
...cinema,
map_url: event.target.value || null,
})
}
/>
</label>
<label className={labelClass}>
ที่อยู่ (บรรทัดละรายการ)
<textarea
className={`${inputClass} h-20`}
value={cinema.address_lines.join("\n")}
onChange={(event) =>
updateCinema({
...cinema,
address_lines: event.target.value.split("\n"),
})
}
/>
</label>
</div>
</AdminSection>
<AdminSection
title="คำอธิบายโรงหนัง"
description="ข้อความที่แสดงใต้ชื่อโรง"
badge={cinema.description ? "มีคำอธิบาย" : "ยังไม่มี"}
>
<div className="grid gap-3 sm:grid-cols-2">
<label className={labelClass}>
คำอธิบาย (TH)
<textarea
className={`${inputClass} h-20`}
value={cinema.description}
onChange={(event) =>
updateCinema({
...cinema,
description: event.target.value,
})
}
/>
</label>
<label className={labelClass}>
คำอธิบาย (EN)
<textarea
className={`${inputClass} h-20`}
value={cinema.description_en ?? ""}
onChange={(event) =>
updateCinema({
...cinema,
description_en: event.target.value,
})
}
/>
</label>
</div>
</AdminSection>
<div className="sticky bottom-0 z-10 -mx-1 flex flex-wrap gap-2 rounded-xl border-t border-[#242424] bg-[#0D0D0D]/95 px-1 py-3 backdrop-blur">
<button
type="button"
className={primaryButtonClass}
onClick={() => void save({ cinemas: store.cinemas })}
>
บันทึกทั้งหมด
</button>
<button
type="button"
className={buttonClass}
onClick={() => {
const copy = {
...cinema,
slug: `${cinema.slug}-copy-${Date.now().toString().slice(-4)}`,
name: `${cinema.name} (สำเนา)`,
};
updateCinemas([...store.cinemas, copy]);
setSelected(copy.slug);
flash("สร้างสำเนาแล้ว — กดบันทึกเพื่อยืนยัน");
}}
>
ทำสำเนา
</button>
<button
type="button"
className={buttonClass}
onClick={() => {
void navigator.clipboard.writeText(jsonDraft);
flash("คัดลอก JSON แล้ว");
}}
>
คัดลอก JSON
</button>
<button
type="button"
className={`${buttonClass} text-[#D47272]`}
onClick={() => {
const rest = store.cinemas.filter(
(item) => item.slug !== cinema.slug,
);
updateCinemas(rest);
setSelected(rest[0]?.slug ?? null);
}}
>
ลบโรงหนังนี้
</button>
</div>
<details className="rounded-xl border border-[#242424] p-3">
<summary className="cursor-pointer text-sm text-[#B3B3B3]">
แก้ไขดิบเป็น JSON (คัดลอก/วางได้)
</summary>
<textarea
className={`${inputClass} mt-3 h-72 font-mono text-xs`}
value={jsonDraft}
onChange={(event) => setJsonDraft(event.target.value)}
spellCheck={false}
/>
<button
type="button"
className={`${buttonClass} mt-2`}
onClick={() => {
try {
updateCinema(JSON.parse(jsonDraft) as Cinema);
flash("ใช้ JSON แล้ว — กดบันทึกเพื่อยืนยัน");
} catch {
flash("JSON ไม่ถูกต้อง");
}
}}
>
ใช้ JSON นี้
</button>
</details>
<details className="rounded-xl border border-[#242424] p-3">
<summary className="cursor-pointer text-sm text-[#B3B3B3]">
วาง JSON เพื่อเพิ่มโรงหนัง (ทับ slug ที่ซ้ำ)
</summary>
<textarea
className={`${inputClass} mt-3 h-40 font-mono text-xs`}
value={importDraft}
onChange={(event) => setImportDraft(event.target.value)}
placeholder='{"slug":"new-cinema","name":"NEW CINEMA","tags":[]}'
spellCheck={false}
/>
<button
type="button"
className={`${buttonClass} mt-2`}
onClick={async () => {
const response = await fetch(
"/api/admin/cinemas/import",
{
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ raw: importDraft }),
},
);
if (!response.ok) {
const data = (await response
.json()
.catch(() => ({}))) as {
statusMessage?: string;
};
flash(data.statusMessage ?? "นำเข้าไม่สำเร็จ");
return;
}
const data = (await response.json()) as {
imported: number;
store: ContentStore;
};
setStore(data.store);
setImportDraft("");
flash(`นำเข้า ${data.imported} รายการแล้ว`);
}}
>
นำเข้า / วางทับ
</button>
</details>
</>
) : (
<p className="text-sm text-[#999]">เลือกโรงหนังหรือเพิ่มใหม่ก่อน</p>
)}
</section>
</div>
) : null}
{tab === "about" ? (
<AboutEditor
value={store.about}
defaults={aboutDefaults}
onChange={updateAbout}
onSave={() => void save({ about: store.about })}
saving={saving}
/>
) : null}
{tab === "forCinemas" ? (
<ArticleEditor
value={store.forCinemas}
defaults={forCinemasDefaults}
onChange={updateForCinemas}
onSave={() => void save({ forCinemas: store.forCinemas })}
saving={saving}
saveLabel="บันทึกหน้าสำหรับคนทำโรงหนัง"
/>
) : null}
{tab === "forFilmLovers" ? (
<ArticleEditor
value={store.forFilmLovers}
defaults={forFilmLoversDefaults}
onChange={updateForFilmLovers}
onSave={() => void save({ forFilmLovers: store.forFilmLovers })}
saving={saving}
saveLabel="บันทึกหน้าสำหรับคนรักหนัง"
/>
) : null}
{tab === "terms" ? (
<div className="px-6 py-5">
<p className="mb-3 text-sm text-[#999]">
แก้คำศัพท์ตามภาษา — key เป็นตำแหน่งข้อความในหน้าเว็บ (เช่น{" "}
<code>hero.subtitle</code>) เว้นว่างไว้แปลว่าใช้ค่าเดิม
</p>
<div className="mb-3 flex flex-wrap gap-2">
<button
type="button"
className={primaryButtonClass}
onClick={() => void save({ site: store.site })}
>
บันทึกคำศัพท์
</button>
<button
type="button"
className={buttonClass}
onClick={() =>
updateSite({
...store.site,
terms: [
...store.site.terms,
{
key: `custom.term${store.site.terms.length + 1}`,
values: Object.fromEntries(
locales.map((locale) => [locale.code, ""]),
),
},
],
})
}
>
+ เพิ่มคำศัพท์
</button>
</div>
<div className="overflow-x-auto rounded-xl border border-[#242424]">
<table className="w-full text-left text-sm">
<thead className="bg-[#141414] text-xs text-[#999]">
<tr>
<th className="px-3 py-2">key</th>
{locales.map((locale) => (
<th key={locale.code} className="px-3 py-2">
{locale.label} ({locale.code})
</th>
))}
<th className="px-3 py-2" />
</tr>
</thead>
<tbody>
{terms.map((term, index) => (
<tr
key={`${term.key}-${index}`}
className="border-t border-[#242424]"
>
<td className="px-3 py-2 font-mono text-xs text-[#D47272]">
{term.key}
</td>
{locales.map((locale) => (
<td key={locale.code} className="px-3 py-2">
<input
className={inputClass}
value={term.values[locale.code] ?? ""}
onChange={(event) => {
const next: TermEntry[] = terms.map((entry, i) =>
i === index
? {
...entry,
values: {
...entry.values,
[locale.code]: event.target.value,
},
}
: entry,
);
updateSite({ ...store.site, terms: next });
}}
/>
</td>
))}
<td className="px-3 py-2">
<button
type="button"
className="text-xs text-[#D47272]"
onClick={() =>
updateSite({
...store.site,
terms: terms.filter((_, i) => i !== index),
})
}
>
ลบ
</button>
</td>
</tr>
))}
</tbody>
</table>
</div>
</div>
) : null}
{tab === "stats" ? (
<div className="px-6 py-5">
<div className="mb-4 flex flex-wrap items-center gap-2">
<span className="text-sm text-[#999]">ช่วงเวลา</span>
{[1, 7, 30, 90].map((days) => (
<button
key={days}
type="button"
onClick={() => setAnalyticsDays(days)}
className={`rounded-lg px-3 py-1.5 text-sm transition ${
analyticsDays === days
? "bg-[#242424] text-[#D47272]"
: "text-[#999] hover:text-white"
}`}
>
{days} วัน
</button>
))}
</div>
{!analytics ? (
<p className="text-sm text-[#999]">กำลังโหลดสถิติ…</p>
) : (
<>
<div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-4">
{[
["ค้นหาทั้งหมด", analytics.total_searches],
["ผู้เข้าชม (ไม่ระบุตัวตน)", analytics.unique_visitors],
["ค้นแล้วไม่พบผล", analytics.zero_result_searches],
["กดใช้ ใกล้ฉัน", analytics.near_me_uses],
["ผลลัพธ์เฉลี่ย/ครั้ง", analytics.average_results],
["คลิกการ์ด / การค้นหา", `${analytics.click_through_rate}%`],
].map(([label, value]) => (
<div
key={String(label)}
className="rounded-xl border border-[#242424] p-4"
>
<div className="text-xs text-[#999]">{label}</div>
<div className="mt-1 text-2xl font-semibold">{value}</div>
</div>
))}
</div>
<div className="mt-6 grid gap-6 lg:grid-cols-2">
<section>
<h2 className="mb-2 text-sm font-semibold">คำค้นยอดนิยม</h2>
<table className="w-full text-left text-sm">
<thead className="text-xs text-[#999]">
<tr>
<th className="py-1">คำค้น</th>
<th className="py-1">ครั้ง</th>
<th className="py-1">ไม่พบผล</th>
<th className="py-1">คลิก</th>
</tr>
</thead>
<tbody>
{analytics.top_queries.length === 0 ? (
<tr>
<td className="py-2 text-[#999]" colSpan={4}>
ยังไม่มีข้อมูลการค้นหา
</td>
</tr>
) : (
analytics.top_queries.map((row) => (
<tr
key={row.query}
className="border-t border-[#242424]"
>
<td className="py-1.5 pr-2">{row.query}</td>
<td className="py-1.5">{row.count}</td>
<td className="py-1.5 text-[#D47272]">
{row.zero_result_count}
</td>
<td className="py-1.5">{row.click_count}</td>
</tr>
))
)}
</tbody>
</table>
</section>
<section>
<h2 className="mb-2 text-sm font-semibold">
คำค้นที่ค้นแล้วไม่พบผล
</h2>
<ul className="flex flex-col gap-1 text-sm">
{analytics.zero_result_queries.length === 0 ? (
<li className="text-[#999]">ไม่มี — ทุกคำค้นมีผลลัพธ์</li>
) : (
analytics.zero_result_queries.map((row) => (
<li
key={row.query}
className="flex justify-between border-t border-[#242424] py-1.5"
>
<span>{row.query}</span>
<span className="text-[#D47272]">
{row.zero_result_count} ครั้ง
</span>
</li>
))
)}
</ul>
<h2 className="mb-2 mt-6 text-sm font-semibold">หมวดที่ถูกใช้</h2>
<ul className="flex flex-col gap-1 text-sm">
{analytics.top_categories.length === 0 ? (
<li className="text-[#999]">ยังไม่มีข้อมูล</li>
) : (
analytics.top_categories.map((row) => (
<li
key={row.category}
className="flex justify-between border-t border-[#242424] py-1.5"
>
<span>{row.category}</span>
<span>{row.count}</span>
</li>
))
)}
</ul>
</section>
<section>
<h2 className="mb-2 text-sm font-semibold">
โรงหนังที่ถูกเปิด/คลิก
</h2>
<table className="w-full text-left text-sm">
<thead className="text-xs text-[#999]">
<tr>
<th className="py-1">slug</th>
<th className="py-1">เปิดดู</th>
<th className="py-1">คลิกการ์ด</th>
</tr>
</thead>
<tbody>
{analytics.top_cinemas.length === 0 ? (
<tr>
<td className="py-2 text-[#999]" colSpan={3}>
ยังไม่มีข้อมูล
</td>
</tr>
) : (
analytics.top_cinemas.map((row) => (
<tr
key={row.slug}
className="border-t border-[#242424]"
>
<td className="py-1.5 pr-2">{row.slug}</td>
<td className="py-1.5">{row.views}</td>
<td className="py-1.5">{row.selects}</td>
</tr>
))
)}
</tbody>
</table>
</section>
<section>
<h2 className="mb-2 text-sm font-semibold">การค้นหารายวัน</h2>
{analytics.daily_searches.length === 0 ? (
<p className="text-sm text-[#999]">ยังไม่มีข้อมูล</p>
) : (
(() => {
const max = Math.max(
...analytics.daily_searches.map((row) => row.count),
1,
);
return (
<ul className="flex flex-col gap-2">
{analytics.daily_searches.map((row) => (
<li
key={row.date}
className="flex items-center gap-3 text-xs"
>
<span className="w-20 shrink-0 text-[#999]">
{row.date}
</span>
<span
className="h-4 rounded-sm bg-[#8F0808]"
style={{
width: `${Math.max((row.count / max) * 100, 4)}%`,
}}
/>
<span>{row.count}</span>
</li>
))}
</ul>
);
})()
)}
</section>
<section>
<h2 className="mb-2 text-sm font-semibold">คำค้นล่าสุด</h2>
{analytics.recent_searches.length === 0 ? (
<p className="text-sm text-[#999]">ยังไม่มีข้อมูล</p>
) : (
<ul className="flex flex-col gap-1 text-sm">
{analytics.recent_searches.map((row, index) => (
<li
key={`${row.at}-${index}`}
className="flex items-center justify-between gap-2 border-t border-[#242424] py-1.5"
>
<span className="truncate">{row.query}</span>
<span className="shrink-0 text-xs text-[#999]">
{row.at.slice(11, 16)} · {row.result_count} ผล
</span>
</li>
))}
</ul>
)}
<button
type="button"
className={`${buttonClass} mt-4`}
onClick={() => {
const header =
"query,count,zero_result_count,click_count\n";
const rows = analytics.top_queries
.map(
(row) =>
`"${row.query.replace(/"/g, '""')}",${row.count},${row.zero_result_count},${row.click_count}`,
)
.join("\n");
const blob = new Blob([header + rows], {
type: "text/csv;charset=utf-8",
});
const url = URL.createObjectURL(blob);
const link = document.createElement("a");
link.href = url;
link.download = `search-stats-${analytics.range_days}d.csv`;
link.click();
URL.revokeObjectURL(url);
}}
>
ดาวน์โหลด CSV (คำค้นยอดนิยม)
</button>
</section>
</div>
<p className="mt-6 text-xs text-[#777]">
เก็บแบบไม่ใช้คุกกี้: ไม่เก็บ IP/User-Agent ดิบ ระบุผู้เข้าชมด้วย hash
ที่หมุนเกลือทุกวัน (แนวเดียวกับ Umami)
</p>
</>
)}
</div>
) : null}
{tab === "footer" ? (
<div className="px-6 py-5">
<p className="mb-3 text-sm text-[#999]">
เลือกไอคอนและใส่ลิงก์ของแต่ละอัน — ลำดับตามรายการนี้
</p>
<div className="mb-3 flex flex-wrap gap-2">
<button
type="button"
className={primaryButtonClass}
onClick={() => void save({ site: store.site })}
>
บันทึก Footer
</button>
<button
type="button"
className={buttonClass}
onClick={() =>
updateSite({
...store.site,
footer: [
...store.site.footer,
{
id: `footer-${Date.now()}`,
icon_name: "IconLink",
label: "ลิงก์ใหม่",
href: "https://",
},
],
})
}
>
+ เพิ่มไอคอน
</button>
</div>
<div className="flex flex-col gap-2">
{store.site.footer.map((item, index) => (
<div
key={item.id}
className="grid gap-2 rounded-xl border border-[#242424] p-3 sm:grid-cols-[180px_1fr_1fr_auto]"
>
<select
className={inputClass}
value={item.icon_name}
onChange={(event) => {
const next: FooterItem[] = store.site.footer.map(
(entry, i) =>
i === index
? { ...entry, icon_name: event.target.value }
: entry,
);
updateSite({ ...store.site, footer: next });
}}
>
{FOOTER_ICON_NAMES.map((name) => (
<option key={name} value={name}>
{name}
</option>
))}
</select>
<input
className={inputClass}
placeholder="ชื่อที่แสดง"
value={item.label}
onChange={(event) => {
const next = store.site.footer.map((entry, i) =>
i === index
? { ...entry, label: event.target.value }
: entry,
);
updateSite({ ...store.site, footer: next });
}}
/>
<input
className={inputClass}
placeholder="https://…"
value={item.href}
onChange={(event) => {
const next = store.site.footer.map((entry, i) =>
i === index
? { ...entry, href: event.target.value }
: entry,
);
updateSite({ ...store.site, footer: next });
}}
/>
<button
type="button"
className="text-xs text-[#D47272]"
onClick={() =>
updateSite({
...store.site,
footer: store.site.footer.filter((_, i) => i !== index),
})
}
>
ลบ
</button>
</div>
))}
</div>
</div>
) : null}
</div>
);
}