Full website

This commit is contained in:
Your Name committed 2026-06-17 07:42:59 -04:00
1 parent 807c43ece5
commit ea9f33f60e
40 files changed
+4503 -1202

No files matched your search

@@ -0,0 +1,613 @@
"use client";
import Link from 'next/link'
import { useEffect, useState } from 'react'
import {
Award,
Check,
Edit3,
ExternalLink,
Loader2,
LogOut,
Mail,
MapPin,
Package,
Phone,
Plus,
Settings,
Trash2,
User,
type LucideIcon,
} from 'lucide-react'
import { formatPrice, type CustomerAddress, type Order } from '@homaroma/types'
import { API_BASE } from '../lib/api'
import { useAuthStore, type Customer } from '../store/authStore'
type ProfileTab = 'orders' | 'addresses' | 'settings'
type ProfileTabItem = {
tab: ProfileTab
label: string
icon: LucideIcon
count: number | null
}
type ProfileCustomer = Customer & {
points?: number
addresses?: CustomerAddress[]
}
type AddressFormState = {
recipientName: string
phone: string
addressLine: string
subdistrict: string
district: string
province: string
zipcode: string
isDefault: boolean
}
const emptyAddressForm: AddressFormState = {
recipientName: '',
phone: '',
addressLine: '',
subdistrict: '',
district: '',
province: '',
zipcode: '',
isDefault: false,
}
function statusLabel(status: string) {
const labels: Record<string, string> = {
PENDING_PAYMENT: 'รอการชำระเงิน',
PAID: 'ชำระเงินสำเร็จ',
PROCESSING: 'กำลังจัดเตรียมสินค้า',
SHIPPED: 'จัดส่งแล้ว',
DELIVERED: 'จัดส่งสำเร็จ',
CANCELLED: 'ยกเลิกแล้ว',
}
return labels[status] ?? status.replaceAll('_', ' ')
}
function statusClass(status: string) {
if (status === 'PENDING_PAYMENT') return 'border-amber-100 bg-amber-50 text-amber-700'
if (status === 'PAID' || status === 'PROCESSING') return 'border-emerald-100 bg-emerald-50 text-emerald-700'
if (status === 'SHIPPED' || status === 'DELIVERED') return 'border-sky-100 bg-sky-50 text-sky-700'
if (status === 'CANCELLED') return 'border-rose-100 bg-rose-50 text-rose-700'
return 'border-gray-100 bg-gray-50 text-gray-700'
}
function formatAddress(address: CustomerAddress) {
return `${address.addressLine} ต.${address.subdistrict} อ.${address.district} จ.${address.province} ${address.zipcode}`
}
function toAddressForm(address: CustomerAddress): AddressFormState {
return {
recipientName: address.recipientName,
phone: address.phone,
addressLine: address.addressLine,
subdistrict: address.subdistrict,
district: address.district,
province: address.province,
zipcode: address.zipcode,
isDefault: address.isDefault,
}
}
async function readJson<T>(path: string, init?: RequestInit): Promise<T> {
const response = await fetch(`${API_BASE}${path}`, init)
const data = await response.json()
if (!response.ok) {
const message = data && typeof data === 'object' && 'error' in data && typeof data.error === 'string'
? data.error
: `${path} returned ${response.status}`
throw new Error(message)
}
return data as T
}
export default function ProfileClient() {
const { token, customer, setAuth, logout } = useAuthStore()
const [activeTab, setActiveTab] = useState<ProfileTab>('orders')
const [dbCustomer, setDbCustomer] = useState<ProfileCustomer | null>(null)
const [orders, setOrders] = useState<Order[]>([])
const [addresses, setAddresses] = useState<CustomerAddress[]>([])
const [loading, setLoading] = useState(false)
const [error, setError] = useState<string | null>(null)
const [showAddressForm, setShowAddressForm] = useState(false)
const [editingAddress, setEditingAddress] = useState<CustomerAddress | null>(null)
const [addressForm, setAddressForm] = useState<AddressFormState>(emptyAddressForm)
const [submittingAddress, setSubmittingAddress] = useState(false)
const [settingsForm, setSettingsForm] = useState({ email: '', phone: '' })
const [submittingSettings, setSubmittingSettings] = useState(false)
const [settingsSuccess, setSettingsSuccess] = useState(false)
const loadProfileData = async (currentCustomer: Customer) => {
setLoading(true)
setError(null)
try {
const [profileData, orderData, addressData] = await Promise.all([
readJson<ProfileCustomer>(`/profile/${currentCustomer.id}`),
readJson<Order[]>(`/orders/customer/${currentCustomer.id}`),
readJson<CustomerAddress[]>(`/profile/${currentCustomer.id}/addresses`),
])
setDbCustomer(profileData)
setOrders(Array.isArray(orderData) ? orderData : [])
setAddresses(Array.isArray(addressData) ? addressData : [])
setSettingsForm({
email: profileData.email ?? '',
phone: profileData.phone ?? '',
})
} catch (err) {
setError(err instanceof Error ? err.message : 'ไม่สามารถโหลดข้อมูลสมาชิกได้')
} finally {
setLoading(false)
}
}
useEffect(() => {
if (!customer) return
queueMicrotask(() => {
void loadProfileData(customer)
})
}, [customer])
const resetAddressForm = () => {
setAddressForm(emptyAddressForm)
setEditingAddress(null)
setShowAddressForm(false)
}
const updateAddressForm = (key: keyof AddressFormState, value: string | boolean) => {
setAddressForm((current) => ({ ...current, [key]: value }))
}
const handleStartAddress = (address?: CustomerAddress) => {
if (address) {
setEditingAddress(address)
setAddressForm(toAddressForm(address))
} else {
setEditingAddress(null)
setAddressForm(emptyAddressForm)
}
setShowAddressForm(true)
}
const reloadAddresses = async (customerId: number) => {
const data = await readJson<CustomerAddress[]>(`/profile/${customerId}/addresses`)
setAddresses(Array.isArray(data) ? data : [])
}
const handleAddressSubmit = async (event: React.FormEvent<HTMLFormElement>) => {
event.preventDefault()
if (!customer) return
setSubmittingAddress(true)
setError(null)
try {
await readJson<CustomerAddress>(
editingAddress
? `/profile/${customer.id}/addresses/${editingAddress.id}`
: `/profile/${customer.id}/addresses`,
{
method: editingAddress ? 'PUT' : 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(addressForm),
},
)
resetAddressForm()
await reloadAddresses(customer.id)
} catch (err) {
setError(err instanceof Error ? err.message : 'ไม่สามารถบันทึกที่อยู่ได้')
} finally {
setSubmittingAddress(false)
}
}
const handleDeleteAddress = async (addressId: number) => {
if (!customer) return
if (!window.confirm('ยืนยันที่จะลบที่อยู่จัดส่งนี้?')) return
setError(null)
try {
await readJson<{ success: boolean }>(`/profile/${customer.id}/addresses/${addressId}`, { method: 'DELETE' })
await reloadAddresses(customer.id)
} catch (err) {
setError(err instanceof Error ? err.message : 'ไม่สามารถลบที่อยู่ได้')
}
}
const handleSetDefaultAddress = async (addressId: number) => {
if (!customer) return
setError(null)
try {
await readJson<CustomerAddress>(`/profile/${customer.id}/addresses/${addressId}/default`, { method: 'PATCH' })
await reloadAddresses(customer.id)
} catch (err) {
setError(err instanceof Error ? err.message : 'ไม่สามารถตั้งค่าที่อยู่เริ่มต้นได้')
}
}
const handleSettingsSubmit = async (event: React.FormEvent<HTMLFormElement>) => {
event.preventDefault()
if (!customer) return
setSubmittingSettings(true)
setSettingsSuccess(false)
setError(null)
try {
const updatedCustomer = await readJson<ProfileCustomer>(`/profile/${customer.id}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
email: settingsForm.email || null,
phone: settingsForm.phone || null,
}),
})
setDbCustomer(updatedCustomer)
if (token) setAuth(token, updatedCustomer)
setSettingsSuccess(true)
setTimeout(() => setSettingsSuccess(false), 3000)
} catch (err) {
setError(err instanceof Error ? err.message : 'ไม่สามารถบันทึกข้อมูลติดต่อได้')
} finally {
setSubmittingSettings(false)
}
}
const handleLineLogin = () => {
const maybeWindow = window as Window & {
liff?: {
login: (options?: { redirectUri?: string }) => void
}
}
if (maybeWindow.liff) {
maybeWindow.liff.login({ redirectUri: window.location.href })
return
}
setError('ยังไม่พบ LINE LIFF ในหน้า website นี้ กรุณาเปิดผ่าน LINE OA หรือรอให้ทีมตั้งค่า LIFF สำหรับ website')
}
if (!customer) {
return (
<section className="mx-auto max-w-md rounded-3xl bg-white p-10 text-center shadow-brutal">
<div className="mx-auto mb-6 flex h-20 w-20 items-center justify-center rounded-full bg-pop-bg text-pop-pink">
<User className="h-10 w-10" />
</div>
<h1 className="text-3xl font-semibold text-pop-black">เข้าสู่ระบบสมาชิก</h1>
<p className="mt-3 text-sm leading-relaxed text-gray-600">
ล็อกอินเพื่อตรวจสอบประวัติคำสั่งซื้อ สะสมคะแนนสมาชิก และบันทึกสมุดที่อยู่จัดส่งสินค้า
</p>
{error && (
<p className="mt-5 rounded-2xl border border-amber-100 bg-amber-50 p-4 text-sm text-amber-700">
{error}
</p>
)}
<button
type="button"
onClick={handleLineLogin}
className="mt-8 flex w-full items-center justify-center gap-3 rounded-full bg-[#00B900] px-6 py-4 text-sm font-bold uppercase tracking-[0.16em] text-white transition hover:bg-[#009900]"
>
<Award className="h-5 w-5" />
เข้าสู่ระบบผ่าน LINE
</button>
<Link href="/shop" className="mt-5 inline-flex text-sm font-semibold text-pop-pink">
กลับไปเลือกซื้อสินค้า
</Link>
</section>
)
}
const displayCustomer = dbCustomer ?? customer
const tabs: ProfileTabItem[] = [
{ tab: 'orders', label: 'ออเดอร์', icon: Package, count: orders.length },
{ tab: 'addresses', label: 'ที่อยู่', icon: MapPin, count: addresses.length },
{ tab: 'settings', label: 'ตั้งค่า', icon: Settings, count: null },
]
return (
<section className="space-y-8">
{error && (
<div className="rounded-3xl border border-rose-100 bg-rose-50 p-5 text-sm font-medium text-rose-600">
{error}
</div>
)}
<div className="relative overflow-hidden rounded-3xl bg-white p-6 shadow-brutal">
<div className="absolute inset-x-0 top-0 h-1 bg-gradient-to-r from-pop-pink via-pop-yellow to-pop-red" />
<div className="flex flex-col gap-5 sm:flex-row sm:items-center sm:justify-between">
<div className="flex min-w-0 items-center gap-4">
<div className="h-16 w-16 shrink-0 overflow-hidden rounded-full border border-pop-pink/20 bg-pop-bg">
<img
src={displayCustomer.pictureUrl || `https://ui-avatars.com/api/?name=${encodeURIComponent(displayCustomer.displayName || 'HomAroma')}`}
alt={displayCustomer.displayName || 'LINE Profile'}
className="h-full w-full object-cover"
/>
</div>
<div className="min-w-0">
<h1 className="truncate text-2xl font-semibold text-pop-black">{displayCustomer.displayName || 'HomAroma Member'}</h1>
<div className="mt-2 flex flex-wrap gap-x-4 gap-y-1 text-xs font-semibold text-gray-500">
{displayCustomer.phone && <span className="inline-flex items-center gap-1"><Phone className="h-3 w-3" />{displayCustomer.phone}</span>}
{displayCustomer.email && <span className="inline-flex items-center gap-1"><Mail className="h-3 w-3" />{displayCustomer.email}</span>}
</div>
</div>
</div>
<div className="flex items-center justify-between gap-4 rounded-2xl bg-pop-bg px-4 py-3">
<Award className="h-6 w-6 text-pop-pink" />
<div>
<p className="text-[10px] font-bold uppercase tracking-[0.2em] text-gray-500">คะแนนสะสม</p>
<p className="text-xl font-black text-pop-black">{displayCustomer.points ?? 0} คะแนน</p>
</div>
</div>
</div>
</div>
<div className="flex gap-2 overflow-x-auto border-b border-gray-200">
{tabs.map(({ tab, label, icon: Icon, count }) => (
<button
key={tab}
type="button"
onClick={() => setActiveTab(tab)}
className={`relative flex shrink-0 items-center gap-2 px-3 pb-4 text-sm font-bold transition ${
activeTab === tab ? 'text-pop-pink' : 'text-gray-500 hover:text-pop-black'
}`}
>
<Icon className="h-4 w-4" />
{label}
{typeof count === 'number' && (
<span className="rounded-full bg-pop-bg px-2 py-0.5 text-[10px]">{count}</span>
)}
{activeTab === tab && <span className="absolute inset-x-0 bottom-0 h-0.5 rounded-full bg-pop-pink" />}
</button>
))}
</div>
{loading ? (
<div className="flex items-center justify-center rounded-3xl bg-white py-24 shadow-brutal">
<Loader2 className="h-8 w-8 animate-spin text-pop-pink" />
</div>
) : (
<>
{activeTab === 'orders' && (
<div className="space-y-5">
{orders.length === 0 ? (
<EmptyPanel icon={Package} title="ไม่มีประวัติการสั่งซื้อ" description="คุณยังไม่ได้ทำการสั่งซื้อสินค้าใด ๆ กับ HomAroma" actionHref="/shop" actionText="ไปหน้าช้อปปิ้ง" />
) : (
orders.map((order) => (
<article key={order.id} className="rounded-3xl bg-white p-6 shadow-brutal">
<div className="flex flex-col gap-3 border-b border-gray-100 pb-4 md:flex-row md:items-center md:justify-between">
<div>
<p className="text-xs font-semibold text-gray-500">เลขออเดอร์ #{order.id.toString().padStart(4, '0')}</p>
<p className="mt-1 text-[11px] text-gray-400">
สั่งเมื่อ {new Date(order.createdAt).toLocaleDateString('th-TH', { year: 'numeric', month: 'long', day: 'numeric' })}
</p>
</div>
<div className="flex items-center gap-3">
<span className={`rounded-full border px-3 py-1 text-xs font-bold ${statusClass(order.status)}`}>
{statusLabel(order.status)}
</span>
<Link href={`/order/${order.id}`} className="rounded-full border border-gray-200 p-2 text-gray-500 transition hover:text-pop-pink">
<ExternalLink className="h-4 w-4" />
</Link>
</div>
</div>
<div className="mt-4 space-y-3">
{order.items.map((item) => (
<div key={item.id} className="flex items-center gap-3 text-sm">
<div className="h-11 w-11 shrink-0 overflow-hidden rounded-xl bg-pop-bg">
<img src={item.productImage || '/images/oil_ozone.png'} alt={item.productName} className="h-full w-full object-cover" />
</div>
<div className="min-w-0 flex-1">
<p className="truncate font-semibold text-pop-black">{item.productName}</p>
<p className="text-xs text-gray-500">{item.variantSize ? `${item.variantSize} · ` : ''}x {item.quantity}</p>
</div>
<p className="font-bold text-pop-pink">{formatPrice(item.priceAtPurchase * item.quantity)}</p>
</div>
))}
</div>
<div className="mt-5 flex flex-col gap-3 border-t border-gray-100 pt-4 text-sm md:flex-row md:items-center md:justify-between">
<p className="text-gray-500">
{order.trackingNo ? <>เลขพัสดุ: <span className="font-mono font-bold text-pop-black">{order.trackingNo}</span></> : 'ยังไม่มีเลขพัสดุ'}
</p>
<p className="font-bold text-pop-black">ยอดรวมสุทธิ: <span className="text-pop-pink">{formatPrice(order.totalAmount)}</span></p>
</div>
</article>
))
)}
</div>
)}
{activeTab === 'addresses' && (
<div className="space-y-6">
<div className="flex flex-col gap-3 border-b border-gray-200 pb-4 sm:flex-row sm:items-center sm:justify-between">
<h2 className="flex items-center gap-2 text-xl font-semibold text-pop-black">
<MapPin className="h-5 w-5 text-pop-pink" />
สมุดที่อยู่จัดส่ง
</h2>
{!showAddressForm && (
<button type="button" onClick={() => handleStartAddress()} className="inline-flex items-center justify-center gap-2 rounded-full bg-pop-black px-5 py-3 text-xs font-bold uppercase tracking-[0.16em] text-white transition hover:bg-pop-pink">
<Plus className="h-4 w-4" />
เพิ่มที่อยู่ใหม่
</button>
)}
</div>
{showAddressForm && (
<form onSubmit={handleAddressSubmit} className="space-y-5 rounded-3xl bg-white p-6 shadow-brutal">
<h3 className="text-sm font-bold uppercase tracking-[0.2em] text-pop-pink">
{editingAddress ? 'แก้ไขที่อยู่จัดส่ง' : 'เพิ่มที่อยู่จัดส่งใหม่'}
</h3>
<div className="grid gap-4 md:grid-cols-2">
<TextInput label="ชื่อผู้รับ" value={addressForm.recipientName} onChange={(value) => updateAddressForm('recipientName', value)} required />
<TextInput label="เบอร์โทรศัพท์ผู้รับ" value={addressForm.phone} onChange={(value) => updateAddressForm('phone', value)} required />
</div>
<TextInput label="ที่อยู่" value={addressForm.addressLine} onChange={(value) => updateAddressForm('addressLine', value)} required />
<div className="grid gap-4 md:grid-cols-4">
<TextInput label="ตำบล/แขวง" value={addressForm.subdistrict} onChange={(value) => updateAddressForm('subdistrict', value)} required />
<TextInput label="อำเภอ/เขต" value={addressForm.district} onChange={(value) => updateAddressForm('district', value)} required />
<TextInput label="จังหวัด" value={addressForm.province} onChange={(value) => updateAddressForm('province', value)} required />
<TextInput label="รหัสไปรษณีย์" value={addressForm.zipcode} onChange={(value) => updateAddressForm('zipcode', value)} required />
</div>
<label className="flex items-center gap-3 text-sm font-semibold text-gray-600">
<input
type="checkbox"
checked={addressForm.isDefault}
onChange={(event) => updateAddressForm('isDefault', event.target.checked)}
className="h-4 w-4 rounded border-gray-300 text-pop-pink"
/>
ตั้งเป็นที่อยู่จัดส่งเริ่มต้น
</label>
<div className="flex justify-end gap-3 border-t border-gray-100 pt-4">
<button type="button" onClick={resetAddressForm} className="rounded-full border border-gray-200 px-5 py-2 text-sm font-semibold text-gray-600">
ยกเลิก
</button>
<button type="submit" disabled={submittingAddress} className="inline-flex items-center gap-2 rounded-full bg-pop-pink px-5 py-2 text-sm font-semibold text-white disabled:opacity-60">
{submittingAddress && <Loader2 className="h-4 w-4 animate-spin" />}
บันทึกที่อยู่
</button>
</div>
</form>
)}
{addresses.length === 0 ? (
<EmptyPanel icon={MapPin} title="ไม่มีข้อมูลที่อยู่จัดส่ง" description="เพิ่มที่อยู่เพื่อใช้ในขั้นตอน checkout รอบถัดไป" />
) : (
<div className="grid gap-4 md:grid-cols-2">
{addresses.map((address) => (
<article key={address.id} className={`rounded-3xl bg-white p-5 shadow-brutal ${address.isDefault ? 'ring-2 ring-pop-pink/30' : ''}`}>
<div className="flex items-start justify-between gap-4">
<div>
<div className="flex flex-wrap items-center gap-2">
<p className="font-semibold text-pop-black">{address.recipientName}</p>
{address.isDefault && <span className="rounded-full bg-pop-bg px-2 py-0.5 text-[10px] font-bold text-pop-pink">เริ่มต้น</span>}
</div>
<p className="mt-1 text-xs font-semibold text-gray-500">{address.phone}</p>
</div>
<div className="flex gap-1">
<button type="button" onClick={() => handleStartAddress(address)} className="rounded-full border border-gray-200 p-2 text-gray-500 hover:text-pop-pink">
<Edit3 className="h-4 w-4" />
</button>
<button type="button" onClick={() => void handleDeleteAddress(address.id)} className="rounded-full border border-rose-100 p-2 text-rose-500">
<Trash2 className="h-4 w-4" />
</button>
</div>
</div>
<p className="mt-4 text-sm leading-relaxed text-gray-600">{formatAddress(address)}</p>
{!address.isDefault && (
<button type="button" onClick={() => void handleSetDefaultAddress(address.id)} className="mt-4 w-full rounded-full border border-gray-200 px-4 py-2 text-xs font-bold uppercase tracking-[0.16em] text-gray-600 hover:text-pop-pink">
ตั้งเป็นที่อยู่เริ่มต้น
</button>
)}
</article>
))}
</div>
)}
</div>
)}
{activeTab === 'settings' && (
<div className="space-y-6">
<h2 className="flex items-center gap-2 border-b border-gray-200 pb-4 text-xl font-semibold text-pop-black">
<Settings className="h-5 w-5 text-pop-pink" />
ข้อมูลติดต่อสมาชิก
</h2>
<form onSubmit={handleSettingsSubmit} className="max-w-xl space-y-5 rounded-3xl bg-white p-6 shadow-brutal">
{settingsSuccess && (
<div className="flex items-center justify-center gap-2 rounded-2xl border border-emerald-100 bg-emerald-50 p-4 text-sm font-bold text-emerald-700">
<Check className="h-4 w-4" />
บันทึกข้อมูลติดต่อสำเร็จแล้ว
</div>
)}
<TextInput label="อีเมล" value={settingsForm.email} onChange={(email) => setSettingsForm((current) => ({ ...current, email }))} type="email" />
<TextInput label="เบอร์โทรศัพท์" value={settingsForm.phone} onChange={(phone) => setSettingsForm((current) => ({ ...current, phone }))} type="tel" />
<button type="submit" disabled={submittingSettings} className="inline-flex w-full items-center justify-center gap-2 rounded-full bg-pop-pink px-6 py-3 text-sm font-bold uppercase tracking-[0.16em] text-white disabled:opacity-60">
{submittingSettings ? <Loader2 className="h-4 w-4 animate-spin" /> : <Check className="h-4 w-4" />}
บันทึกข้อมูลติดต่อ
</button>
</form>
</div>
)}
</>
)}
<button type="button" onClick={logout} className="inline-flex items-center gap-2 text-sm font-semibold text-gray-500 transition hover:text-rose-500">
<LogOut className="h-4 w-4" />
ออกจากระบบบนอุปกรณ์นี้
</button>
</section>
)
}
function TextInput({
label,
value,
onChange,
required = false,
type = 'text',
}: {
label: string
value: string
onChange: (value: string) => void
required?: boolean
type?: string
}) {
return (
<label className="space-y-1.5">
<span className="block text-[10px] font-bold uppercase tracking-[0.2em] text-gray-500">{label}</span>
<input
type={type}
required={required}
value={value}
onChange={(event) => onChange(event.target.value)}
className="w-full rounded-2xl border border-gray-200 bg-pop-bg px-4 py-3 text-sm text-pop-black outline-none transition focus:border-pop-pink focus:ring-2 focus:ring-pop-pink/20"
/>
</label>
)
}
function EmptyPanel({
icon: Icon,
title,
description,
actionHref,
actionText,
}: {
icon: typeof Package
title: string
description: string
actionHref?: string
actionText?: string
}) {
return (
<div className="rounded-3xl bg-white px-6 py-16 text-center shadow-brutal">
<Icon className="mx-auto mb-5 h-12 w-12 text-gray-300" />
<h3 className="text-xl font-semibold text-pop-black">{title}</h3>
<p className="mx-auto mt-2 max-w-md text-sm text-gray-500">{description}</p>
{actionHref && actionText && (
<Link href={actionHref} className="mt-6 inline-flex rounded-full bg-pop-pink px-6 py-3 text-sm font-bold text-white">
{actionText}
</Link>
)}
</div>
)
}