feat: update
CI / Verify (push) Successful in 1m57s
CI / Build immutable images and deploy (push) Successful in 2m20s

This commit is contained in:
2026-10-02 18:28:23 +07:00 Unverified
parent 6bbeb79551
commit 1ed9ea29eb
14 changed files with 1356 additions and 368 deletions
+132 -27
View File
@@ -10,8 +10,14 @@ import { Field, FieldGroup, FieldLabel } from "@/components/ui/field";
import { Input } from "@/components/ui/input";
import { authClient } from "@/lib/auth/client";
export function AccountForm({ mode, siteKey, nextPath }: {
mode: "login" | "register"; siteKey: string; nextPath: string;
export function AccountForm({
mode,
siteKey,
nextPath,
}: {
mode: "login" | "register";
siteKey: string;
nextPath: string;
}) {
const router = useRouter();
const register = mode === "register";
@@ -24,50 +30,149 @@ export function AccountForm({ mode, siteKey, nextPath }: {
useEffect(() => {
if (!captcha) return;
const script = document.createElement("script");
script.src = "https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit";
script.src =
"https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit";
script.async = true;
script.onload = () => {
if (container.current && window.turnstile && !widget.current) widget.current = window.turnstile.render(container.current, {
sitekey: siteKey, callback: (value: string) => setToken(value),
"expired-callback": () => setToken(""), "error-callback": () => setToken(""),
});
if (container.current && window.turnstile && !widget.current)
widget.current = window.turnstile.render(container.current, {
sitekey: siteKey,
callback: (value: string) => setToken(value),
"expired-callback": () => setToken(""),
"error-callback": () => setToken(""),
});
};
document.head.append(script);
return () => { script.remove(); };
return () => {
script.remove();
};
}, [captcha, siteKey]);
async function submit(event: FormEvent<HTMLFormElement>) {
event.preventDefault();
if (captcha && !token) return;
setBusy(true); setError("");
setBusy(true);
setError("");
const form = new FormData(event.currentTarget);
const email = String(form.get("email") ?? "").trim();
const password = String(form.get("password") ?? "");
const fetchOptions = { headers: captcha ? { "x-captcha-response": token } : undefined };
const image = register ? form.get("image") : null;
const fetchOptions = {
headers: captcha ? { "x-captcha-response": token } : undefined,
};
try {
if (image instanceof File && image.size > 0 &&
(image.size > 6 * 1024 * 1024 || !["image/png", "image/jpeg", "image/webp"].includes(image.type))) {
throw new Error("ใช้รูป PNG, JPEG หรือ WebP ขนาดไม่เกิน 6 MB");
}
const result = register
? await authClient.signUp.email({ name: String(form.get("name") ?? "").trim(), email, password, fetchOptions })
? await authClient.signUp.email({
name: String(form.get("name") ?? "").trim(),
email,
password,
fetchOptions,
})
: await authClient.signIn.email({ email, password, fetchOptions });
if (result.error) throw new Error(result.error.message ?? "เข้าสู่ระบบไม่สำเร็จ");
router.push(nextPath); router.refresh();
if (result.error)
throw new Error(result.error.message ?? "เข้าสู่ระบบไม่สำเร็จ");
if (register && image instanceof File && image.size > 0) {
const profile = new FormData();
profile.set("name", String(form.get("name") ?? "").trim());
profile.set("image", image);
const uploaded = await fetch("/api/profile", { method: "POST", body: profile })
.then((response) => response.ok).catch(() => false);
if (!uploaded) {
router.push(`/profile?setup=1&upload=failed&next=${encodeURIComponent(nextPath)}`);
router.refresh();
return;
}
}
router.push(nextPath);
router.refresh();
} catch (cause) {
setError(cause instanceof Error ? cause.message : "ลองอีกครั้ง");
setToken("");
if (widget.current) window.turnstile?.reset(widget.current);
} finally { setBusy(false); }
} finally {
setBusy(false);
}
}
return <Card className="w-full max-w-sm"><CardHeader><CardTitle>{register ? "สมัครสมาชิก" : "เข้าสู่ระบบ"}</CardTitle></CardHeader>
<CardContent className="flex flex-col gap-4"><form onSubmit={submit}><FieldGroup>
{register && <Field><FieldLabel htmlFor="name">ชื่อ</FieldLabel><Input id="name" name="name" required maxLength={100} /></Field>}
<Field><FieldLabel htmlFor="email">อีเมล</FieldLabel><Input id="email" name="email" type="email" required autoComplete="email" /></Field>
<Field><FieldLabel htmlFor="password">รหัสผ่าน</FieldLabel><Input id="password" name="password" type="password" required minLength={6} autoComplete={register ? "new-password" : "current-password"} /></Field>
{captcha && <div ref={container} />}
<Button type="submit" disabled={busy || (captcha && !token)}>{busy ? "กำลังดำเนินการ..." : register ? "สมัครสมาชิก" : "เข้าสู่ระบบ"}</Button>
</FieldGroup></form>
<Button variant="link" nativeButton={false} render={<Link href={`${register ? "/login" : "/register"}${nextPath === "/" ? "" : `?next=${encodeURIComponent(nextPath)}`}`} />}>
{register ? "มีบัญชีแล้ว? เข้าสู่ระบบ" : "ยังไม่มีบัญชี? สมัครสมาชิก"}
</Button>
{error && <Alert variant="destructive"><AlertDescription>{error}</AlertDescription></Alert>}
</CardContent></Card>;
return (
<Card className="w-full max-w-sm">
<CardHeader>
<CardTitle>{register ? "สมัครสมาชิก" : "เข้าสู่ระบบ"}</CardTitle>
</CardHeader>
<CardContent className="flex flex-col gap-4">
<form onSubmit={submit}>
<FieldGroup>
{register && (
<Field>
<FieldLabel htmlFor="name">ชื่อที่แสดง</FieldLabel>
<Input
id="name"
name="name"
required
minLength={2}
maxLength={80}
autoComplete="name"
/>
</Field>
)}
{register && (
<Field>
<FieldLabel htmlFor="register-image">รูปโปรไฟล์ (ไม่บังคับ)</FieldLabel>
<Input id="register-image" name="image" type="file" accept="image/png,image/jpeg,image/webp" />
</Field>
)}
<Field>
<FieldLabel htmlFor="email">อีเมล</FieldLabel>
<Input
id="email"
name="email"
type="email"
required
autoComplete="email"
/>
</Field>
<Field>
<FieldLabel htmlFor="password">รหัสผ่าน</FieldLabel>
<Input
id="password"
name="password"
type="password"
required
minLength={6}
autoComplete={register ? "new-password" : "current-password"}
/>
</Field>
{captcha && <div ref={container} />}
<Button type="submit" disabled={busy || (captcha && !token)}>
{busy
? "กำลังดำเนินการ..."
: register
? "สมัครสมาชิก"
: "เข้าสู่ระบบ"}
</Button>
</FieldGroup>
</form>
<Button
variant="link"
nativeButton={false}
render={
<Link
href={`${register ? "/login" : "/register"}${nextPath === "/" ? "" : `?next=${encodeURIComponent(nextPath)}`}`}
/>
}
>
{register ? "มีบัญชีแล้ว? เข้าสู่ระบบ" : "ยังไม่มีบัญชี? สมัครสมาชิก"}
</Button>
{error && (
<Alert variant="destructive">
<AlertDescription>{error}</AlertDescription>
</Alert>
)}
</CardContent>
</Card>
);
}
+126 -38
View File
@@ -1,15 +1,31 @@
"use client";
import { useEffect, useState, type FormEvent } from "react";
import Link from "next/link";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { Alert, AlertDescription } from "@/components/ui/alert";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from "@/components/ui/card";
import {
Card,
CardContent,
CardDescription,
CardFooter,
CardHeader,
CardTitle,
} from "@/components/ui/card";
import { Field, FieldGroup, FieldLabel } from "@/components/ui/field";
import { Input } from "@/components/ui/input";
export function ProfileForm({ name: initialName, email, image: initialImage }: {
name: string; email: string; image: string | null;
export function ProfileForm({
name: initialName,
email,
image: initialImage,
nextPath,
}: {
name: string;
email: string;
image: string | null;
nextPath?: string;
}) {
const [name, setName] = useState(initialName);
const [file, setFile] = useState<File | null>(null);
@@ -17,11 +33,20 @@ export function ProfileForm({ name: initialName, email, image: initialImage }: {
const [busy, setBusy] = useState(false);
const [error, setError] = useState("");
useEffect(() => () => { if (preview) URL.revokeObjectURL(preview); }, [preview]);
useEffect(
() => () => {
if (preview) URL.revokeObjectURL(preview);
},
[preview],
);
function chooseFile(next: File | null) {
setError("");
if (next && (next.size > 6 * 1024 * 1024 || !["image/png", "image/jpeg", "image/webp"].includes(next.type))) {
if (
next &&
(next.size > 6 * 1024 * 1024 ||
!["image/png", "image/jpeg", "image/webp"].includes(next.type))
) {
setError("ใช้รูป PNG, JPEG หรือ WebP ขนาดไม่เกิน 6 MB");
return;
}
@@ -32,46 +57,109 @@ export function ProfileForm({ name: initialName, email, image: initialImage }: {
async function save(event: FormEvent<HTMLFormElement>) {
event.preventDefault();
if (busy) return;
setBusy(true); setError("");
setBusy(true);
setError("");
try {
const form = new FormData();
form.set("name", name.trim());
if (file) form.set("image", file);
const response = await fetch("/api/profile", { method: "POST", body: form });
if (!response.ok) throw new Error("บันทึกโปรไฟล์ไม่สำเร็จ กรุณาลองอีกครั้ง");
window.location.reload();
const response = await fetch("/api/profile", {
method: "POST",
body: form,
});
if (!response.ok)
throw new Error("บันทึกโปรไฟล์ไม่สำเร็จ กรุณาลองอีกครั้ง");
if (nextPath) window.location.assign(nextPath);
else window.location.reload();
} catch (cause) {
setError(cause instanceof Error ? cause.message : "บันทึกโปรไฟล์ไม่สำเร็จ");
setError(
cause instanceof Error ? cause.message : "บันทึกโปรไฟล์ไม่สำเร็จ",
);
setBusy(false);
}
}
return <Card>
<CardHeader><CardTitle>ข้อมูลบัญชี</CardTitle><CardDescription>{email}</CardDescription></CardHeader>
<CardContent><form id="profile-form" onSubmit={save}><FieldGroup>
<Field><FieldLabel htmlFor="profile-image">รูปโปรไฟล์</FieldLabel>
<div className="flex items-center gap-4">
<Avatar size="lg" className="size-16">
{(preview || initialImage) && <AvatarImage src={preview || initialImage || ""} alt="รูปโปรไฟล์" />}
<AvatarFallback>{name.trim().charAt(0).toUpperCase() || "?"}</AvatarFallback>
</Avatar>
<Input id="profile-image" type="file" accept="image/png,image/jpeg,image/webp"
onChange={(event) => {
const selected = event.target.files?.[0] ?? null;
chooseFile(selected);
if (selected && (selected.size > 6 * 1024 * 1024 ||
!["image/png", "image/jpeg", "image/webp"].includes(selected.type))) event.target.value = "";
}} disabled={busy} />
</div>
</Field>
<Field><FieldLabel htmlFor="profile-name">ชื่อที่แสดง</FieldLabel>
<Input id="profile-name" value={name} onChange={(event) => setName(event.target.value)}
minLength={2} maxLength={80} required disabled={busy} />
</Field>
{error && <Alert variant="destructive"><AlertDescription>{error}</AlertDescription></Alert>}
</FieldGroup></form></CardContent>
<CardFooter><Button type="submit" form="profile-form" disabled={busy || name.trim().length < 2 || name.trim().length > 80}>
{busy ? "กำลังบันทึก..." : "บันทึกโปรไฟล์"}
</Button></CardFooter>
</Card>;
return (
<Card>
<CardHeader>
<CardTitle>ข้อมูลบัญชี</CardTitle>
<CardDescription>{email}</CardDescription>
</CardHeader>
<CardContent>
<form id="profile-form" onSubmit={save}>
<FieldGroup>
<Field>
<FieldLabel htmlFor="profile-image">รูปโปรไฟล์</FieldLabel>
<div className="flex items-center gap-4">
<Avatar size="lg" className="size-16">
{(preview || initialImage) && (
<AvatarImage
src={preview || initialImage || ""}
alt="รูปโปรไฟล์"
/>
)}
<AvatarFallback>
{name.trim().charAt(0).toUpperCase() || "?"}
</AvatarFallback>
</Avatar>
<Input
id="profile-image"
type="file"
accept="image/png,image/jpeg,image/webp"
onChange={(event) => {
const selected = event.target.files?.[0] ?? null;
chooseFile(selected);
if (
selected &&
(selected.size > 6 * 1024 * 1024 ||
!["image/png", "image/jpeg", "image/webp"].includes(
selected.type,
))
)
event.target.value = "";
}}
disabled={busy}
/>
</div>
</Field>
<Field>
<FieldLabel htmlFor="profile-name">ชื่อที่แสดง</FieldLabel>
<Input
id="profile-name"
value={name}
onChange={(event) => setName(event.target.value)}
minLength={2}
maxLength={80}
required
disabled={busy}
/>
</Field>
{error && (
<Alert variant="destructive">
<AlertDescription>{error}</AlertDescription>
</Alert>
)}
</FieldGroup>
</form>
</CardContent>
<CardFooter className="flex-wrap gap-2">
<Button
type="submit"
form="profile-form"
disabled={busy || name.trim().length < 2 || name.trim().length > 80}
>
{busy ? "กำลังบันทึก..." : "บันทึกโปรไฟล์"}
</Button>
{nextPath && (
<Button
variant="ghost"
nativeButton={false}
render={<Link href={nextPath} />}
>
ไว้ก่อน
</Button>
)}
</CardFooter>
</Card>
);
}
File diff suppressed because it is too large Load Diff
+146
View File
@@ -0,0 +1,146 @@
"use client";
import { useEffect, useState } from "react";
import { usePathname } from "next/navigation";
import { syncCommissionPush } from "@/components/commission/push-client";
import { Button } from "@/components/ui/button";
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
type InstallEvent = Event & { prompt: () => Promise<void>; userChoice: Promise<{ outcome: string }> };
const dismissedKey = "site-entry-prompt-dismissed";
function isInstalled() {
return window.matchMedia("(display-mode: standalone)").matches ||
(navigator as Navigator & { standalone?: boolean }).standalone === true;
}
export function SiteEntryPrompt() {
const pathname = usePathname();
const [open, setOpen] = useState(false);
const [installed, setInstalled] = useState(false);
const [installEvent, setInstallEvent] = useState<InstallEvent | null>(null);
const [instructions, setInstructions] = useState(false);
const [permission, setPermission] = useState<NotificationPermission | null>(null);
const [busy, setBusy] = useState(false);
const [error, setError] = useState("");
useEffect(() => {
// Commission pages have their own prompt, tied to the signed-in user's messages.
if (pathname !== "/") {
const frame = requestAnimationFrame(() => setOpen(false));
return () => cancelAnimationFrame(frame);
}
const installedNow = isInstalled();
const ios = /iPad|iPhone|iPod/.test(navigator.userAgent) ||
(navigator.platform === "MacIntel" && navigator.maxTouchPoints > 1);
const mobile = ios || /Android|Mobile/.test(navigator.userAgent);
const canNotify = window.isSecureContext && "Notification" in window &&
"PushManager" in window && "serviceWorker" in navigator;
const frame = requestAnimationFrame(() => {
setInstalled(installedNow);
setPermission(canNotify ? Notification.permission : null);
if (!sessionStorage.getItem(dismissedKey) &&
((mobile && !installedNow) || (canNotify && Notification.permission === "default"))) {
setOpen(true);
}
});
const beforeInstall = (event: Event) => {
event.preventDefault();
setInstallEvent(event as InstallEvent);
if (!sessionStorage.getItem(dismissedKey)) setOpen(true);
};
const onInstalled = () => {
setInstalled(true);
setInstallEvent(null);
setInstructions(false);
if (!canNotify || Notification.permission !== "default") setOpen(false);
};
window.addEventListener("beforeinstallprompt", beforeInstall);
window.addEventListener("appinstalled", onInstalled);
return () => {
cancelAnimationFrame(frame);
window.removeEventListener("beforeinstallprompt", beforeInstall);
window.removeEventListener("appinstalled", onInstalled);
};
}, [pathname]);
function dismiss() {
sessionStorage.setItem(dismissedKey, "1");
setOpen(false);
}
async function install() {
if (!installEvent) {
setInstructions(true);
return;
}
await installEvent.prompt();
await installEvent.userChoice;
setInstallEvent(null);
}
async function enableNotifications() {
setBusy(true);
setError("");
try {
const result = await Notification.requestPermission();
setPermission(result);
if (result !== "granted") {
if (!showInstall) setOpen(false);
return;
}
// A signed-in commission user can receive messages immediately. Guests can
// subscribe when they later sign in and visit their commission page.
const response = await fetch("/api/commission/push-subscription", { cache: "no-store" });
if (response.ok) {
const config = await response.json() as { publicKey: string; canAdmin: boolean };
await syncCommissionPush(config.canAdmin ? "admin" : "customer", config.publicKey);
}
if (!showInstall) setOpen(false);
} catch {
setError("เปิดการแจ้งเตือนไม่สำเร็จ กรุณาลองอีกครั้ง");
} finally {
setBusy(false);
}
}
const ios = typeof navigator !== "undefined" &&
(/iPad|iPhone|iPod/.test(navigator.userAgent) ||
(navigator.platform === "MacIntel" && navigator.maxTouchPoints > 1));
const mobile = typeof navigator !== "undefined" &&
(ios || /Android|Mobile/.test(navigator.userAgent));
const showInstall = !installed && (mobile || installEvent !== null);
const canAskNotification = permission === "default" && (!ios || installed);
return <Dialog open={open} onOpenChange={(next) => { if (!next) dismiss(); }}>
<DialogContent>
<DialogHeader>
<DialogTitle>{showInstall ? "ติดตั้ง Buzz Guide และรับการแจ้งเตือน" : "รับการแจ้งเตือนจาก Buzz Guide"}</DialogTitle>
<DialogDescription>
{showInstall ?
"เพิ่มเว็บไซต์ลงหน้าจอหลักเพื่อเปิดใช้งานได้สะดวก และรับการแจ้งเตือนเมื่อมีข้อความใหม่ใน Commission หลังเข้าสู่ระบบ" :
"รับการแจ้งเตือนเมื่อมีข้อความใหม่ใน Commission หลังเข้าสู่ระบบ"}
</DialogDescription>
</DialogHeader>
{!installed && (ios || instructions) && <p className="text-sm text-muted-foreground">
{ios ? "บน iPhone/iPad แตะปุ่มแชร์ใน Safari แล้วเลือก ‘เพิ่มไปยังหน้าจอโฮม’ จากนั้นเปิดแอปที่ติดตั้ง" :
"เปิดเมนูของเบราว์เซอร์ แล้วเลือก ‘ติดตั้งแอป’ หรือ ‘เพิ่มไปยังหน้าจอหลัก’"}
</p>}
{ios && !installed && <p className="text-sm text-muted-foreground">
ติดตั้งและเปิดจากหน้าจอโฮมก่อน จึงจะเปิดการแจ้งเตือนได้บน iPhone/iPad
</p>}
{error && <p role="alert" className="text-sm text-destructive">{error}</p>}
<DialogFooter>
<Button type="button" variant="outline" disabled={busy} onClick={dismiss}>ไว้ก่อน</Button>
{showInstall && !ios && <Button type="button" variant="secondary" disabled={busy} onClick={() => void install()}>ติดตั้งแอป</Button>}
{canAskNotification && <Button type="button" disabled={busy} onClick={() => void enableNotifications()}>เปิดการแจ้งเตือน</Button>}
</DialogFooter>
</DialogContent>
</Dialog>;
}