昨天我們解決了 CORS 問題,並讓後台可以成功串接 API 顯示訂單列表。
但一個訂單系統如果只能「看」卻不能「管」,店家仍然無法真正運作。
今天我們要在後台加入 訂單狀態修改功能,讓管理員可以直接在後台把訂單從「待處理」改成「製作中」或「已完成」,並更新資料庫中的狀態。這會是後台管理的重要核心。
店家需要追蹤訂單進度。
不同狀態可以影響通知邏輯(例如完成時推播給顧客)。
是從「紀錄系統」到「管理系統」的必經之路。
我們在 Day 13 設計的 orderSchema
:
status: { type: String, enum: ['Pending', 'In Progress', 'Completed'], default: 'Pending' }
今天會用 PUT/PATCH API 修改這個欄位。
小提醒!
記得要在 CORS 設定將 PATCH Method 加上去喔~
Route: PATCH /orders/:id/status
Body: { status: "In Progress" }
保護:必須通過 authAdmin
。
// routes/order.js
router.patch("/:id/status", authAdmin, async (req, res) => {
const { status } = req.body;
if (!["Pending", "In Progress", "Completed"].includes(status)) {
return res.status(400).json({ message: "不合法的狀態" });
}
try {
const order = await Order.findByIdAndUpdate(
req.params.id,
{ status },
{ new: true }
);
if (!order) return res.status(404).json({ message: "找不到訂單" });
res.json({ success: true, order });
} catch (err) {
res.status(500).json({ message: "伺服器錯誤" });
}
});
在 Dashboard 每個訂單旁邊加一個下拉選單或按鈕,管理員選取新狀態 → 呼叫 API 更新 → 成功後刷新 UI。
// pages/Dashboard.jsx
import { useEffect, useState } from "react";
import axios from "axios";
export default function Dashboard() {
const [orders, setOrders] = useState([]);
const token = localStorage.getItem("jwt");
useEffect(() => {
axios.get("http://localhost:3000/orders", {
headers: { Authorization: `Bearer ${token}` }
})
.then(res => setOrders(res.data.orders));
}, []);
async function updateStatus(id, newStatus) {
await axios.patch(`http://localhost:3000/orders/${id}/status`,
{ status: newStatus },
{ headers: { Authorization: `Bearer ${token}` } }
);
setOrders(orders.map(o => o._id === id ? { ...o, status: newStatus } : o));
}
return (
<div>
<h1>訂單管理</h1>
<ul>
{orders.map(o => (
<li key={o._id}>
{o.items.map(i => i.productName).join(", ")} - {o.status}
<select
value={o.status}
onChange={e => updateStatus(o._id, e.target.value)}
>
<option>Pending</option>
<option>In Progress</option>
<option>Completed</option>
</select>
</li>
))}
</ul>
</div>
);
}
今天的部分完成後,就可以從後台介面更改訂單狀態了!
訂單狀態修改是後台的核心功能,讓管理員真正「控制」訂單流程。
API 採用 PATCH /orders/:id/status
,簡單明確。
前端用下拉選單快速更新狀態,體驗直觀。
明天(Day 21)我們將導入 Redis,為狀態與訂單處理打下快取/佇列的基礎。