188 lines
6.6 KiB
TypeScript
188 lines
6.6 KiB
TypeScript
"use client"
|
|
|
|
import Link from './LocalizedLink'
|
|
import { useRouter } from 'next/navigation'
|
|
import { useEffect, useState } from 'react'
|
|
import { ChevronRight, Loader2, Package, Search } from 'lucide-react'
|
|
|
|
import { API_BASE } from '../lib/api'
|
|
import { useLang } from '../hooks/useLang'
|
|
import { getPathWithLocale } from '../lib/locales'
|
|
import { toneClass } from '../lib/theme'
|
|
|
|
type TrackResponse =
|
|
| { success: true; orderId: number }
|
|
| { error?: string }
|
|
|
|
function parseStoredOrders(value: string | null) {
|
|
if (!value) return []
|
|
|
|
try {
|
|
const parsed = JSON.parse(value)
|
|
return Array.isArray(parsed)
|
|
? parsed.map(Number).filter((id) => Number.isFinite(id) && id > 0)
|
|
: []
|
|
} catch {
|
|
return []
|
|
}
|
|
}
|
|
|
|
function orderLabel(id: number) {
|
|
return `#${id.toString().padStart(4, '0')}`
|
|
}
|
|
|
|
export default function TrackOrderClient() {
|
|
const router = useRouter()
|
|
const lang = useLang()
|
|
const [orderId, setOrderId] = useState('')
|
|
const [phone, setPhone] = useState('')
|
|
const [localOrders, setLocalOrders] = useState<number[]>([])
|
|
const [loading, setLoading] = useState(false)
|
|
const [error, setError] = useState<string | null>(null)
|
|
|
|
useEffect(() => {
|
|
const storedOrders = parseStoredOrders(localStorage.getItem('app_local_orders'))
|
|
queueMicrotask(() => setLocalOrders(storedOrders))
|
|
}, [])
|
|
|
|
const saveLocalOrder = (id: number) => {
|
|
setLocalOrders((current) => {
|
|
const next = [id, ...current.filter((item) => item !== id)].slice(0, 12)
|
|
localStorage.setItem('app_local_orders', JSON.stringify(next))
|
|
return next
|
|
})
|
|
}
|
|
|
|
const handleSubmit = async (event: React.FormEvent<HTMLFormElement>) => {
|
|
event.preventDefault()
|
|
setLoading(true)
|
|
setError(null)
|
|
|
|
const normalizedOrderId = Number.parseInt(orderId.replace(/[^0-9]/g, ''), 10)
|
|
|
|
if (!Number.isFinite(normalizedOrderId) || normalizedOrderId <= 0) {
|
|
setError('กรุณากรอกหมายเลขคำสั่งซื้อให้ถูกต้อง')
|
|
setLoading(false)
|
|
return
|
|
}
|
|
|
|
try {
|
|
const response = await fetch(`${API_BASE}/orders/track`, {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify({
|
|
orderId: normalizedOrderId,
|
|
phone,
|
|
}),
|
|
})
|
|
const data = await response.json() as TrackResponse
|
|
|
|
if (response.ok && 'success' in data && data.success) {
|
|
saveLocalOrder(data.orderId)
|
|
router.push(getPathWithLocale(`/order/${data.orderId}`, lang))
|
|
return
|
|
}
|
|
|
|
setError('error' in data && data.error ? data.error : 'ไม่สามารถยืนยันข้อมูลคำสั่งซื้อได้')
|
|
} catch (err) {
|
|
setError(err instanceof Error ? err.message : 'เกิดข้อผิดพลาดในการเชื่อมต่อ กรุณาลองใหม่อีกครั้ง')
|
|
} finally {
|
|
setLoading(false)
|
|
}
|
|
}
|
|
|
|
return (
|
|
<div className="grid gap-10 md:grid-cols-2">
|
|
<section className="ui-panel self-start p-8">
|
|
<div className="mb-6 flex items-center gap-3 border-b border-line-primary/20 pb-4">
|
|
<div className="flex h-10 w-10 items-center justify-center rounded-full bg-surface-page text-brand-primary">
|
|
<Search className="h-5 w-5" />
|
|
</div>
|
|
<div>
|
|
<p className="ui-eyebrow">Manual Search</p>
|
|
<h2 className="text-xl font-semibold text-text-main">ค้นหาคำสั่งซื้อ</h2>
|
|
</div>
|
|
</div>
|
|
|
|
<form className="space-y-5" onSubmit={handleSubmit}>
|
|
{error && (
|
|
<div className={`p-4 text-sm font-medium ${toneClass('error')}`}>
|
|
{error}
|
|
</div>
|
|
)}
|
|
|
|
<div className="space-y-2">
|
|
<label htmlFor="orderId" className="ui-form-label">
|
|
Order Number
|
|
</label>
|
|
<input
|
|
id="orderId"
|
|
required
|
|
value={orderId}
|
|
onChange={(event) => setOrderId(event.target.value)}
|
|
className="ui-form-shell"
|
|
placeholder="เช่น 1024"
|
|
type="text"
|
|
/>
|
|
</div>
|
|
|
|
<div className="space-y-2">
|
|
<label htmlFor="phone" className="ui-form-label">
|
|
Phone Number
|
|
</label>
|
|
<input
|
|
id="phone"
|
|
required
|
|
value={phone}
|
|
onChange={(event) => setPhone(event.target.value)}
|
|
className="ui-form-shell"
|
|
placeholder="เบอร์โทรที่ใช้ตอนสั่งซื้อ"
|
|
type="tel"
|
|
/>
|
|
</div>
|
|
|
|
<button
|
|
type="submit"
|
|
disabled={loading}
|
|
className="ui-form-inline-button w-full"
|
|
>
|
|
{loading ? <Loader2 className="h-5 w-5 animate-spin" /> : 'Find Order'}
|
|
</button>
|
|
</form>
|
|
</section>
|
|
|
|
<section className="space-y-6">
|
|
<div className="flex items-center gap-3 border-b border-line-primary/20 pb-4">
|
|
<Package className="h-5 w-5 text-brand-primary" />
|
|
<h2 className="text-xl font-semibold text-text-main">Recent Device Orders</h2>
|
|
</div>
|
|
|
|
{localOrders.length === 0 ? (
|
|
<div className="ui-empty-panel p-10 text-center">
|
|
<p className="text-sm font-semibold text-muted-text">ยังไม่มีประวัติคำสั่งซื้อบนอุปกรณ์นี้</p>
|
|
<p className="mt-2 text-xs uppercase tracking-[0.18em] text-muted-text/70">ใช้ฟอร์มค้นหาด้านซ้ายเพื่อบันทึกออเดอร์</p>
|
|
</div>
|
|
) : (
|
|
<div className="space-y-3">
|
|
{localOrders.map((id) => (
|
|
<Link
|
|
key={id}
|
|
href={`/order/${id}`}
|
|
className="ui-card ui-card-hover group flex items-center justify-between p-5"
|
|
>
|
|
<div>
|
|
<p className="text-xs font-bold uppercase tracking-[0.22em] text-muted-text/70">Order</p>
|
|
<p className="mt-1 font-mono text-2xl font-bold text-text-main">{orderLabel(id)}</p>
|
|
</div>
|
|
<div className="flex h-10 w-10 items-center justify-center rounded-full bg-surface-page text-text-main transition group-hover:bg-brand-primary group-hover:text-surface-card">
|
|
<ChevronRight className="h-5 w-5" />
|
|
</div>
|
|
</Link>
|
|
))}
|
|
</div>
|
|
)}
|
|
</section>
|
|
</div>
|
|
)
|
|
}
|