defineFlow
Khai báo vòng đời của một bản ghi một lần: trạng thái nào được chuyển sang đâu, và vai nào được chuyển. Server chặn bước sai, giao diện chỉ hiện nút hợp lệ.
Cách dùng
app/shared/order.ts
import { defineFlow } from "manh/flow";
import { OrderStatus } from "./order-status"; // defineEnum
export const OrderFlow = defineFlow({
new: { confirmed: ["sales", "admin"], cancelled: ["sales", "admin"] },
confirmed: { shipping: ["warehouse", "admin"], cancelled: ["admin"] },
shipping: { done: ["warehouse", "admin"] },
done: {},
cancelled: {},
}, OrderStatus);app/orders/repository.ts
import { fail } from "manh/errors";
import { OrderFlow } from "app/shared/order";
export async function moveOrder(user, id: number, to: string) {
const [row] = await db.select().from(orders).where(eq(orders.id, id));
if (!row) fail(404, "Không tìm thấy đơn", "NOT_FOUND");
OrderFlow.assert(user, row.status, to); // sai bước: 409, sai vai: 403
const [updated] = await db.update(orders).set({ status: to }).where(eq(orders.id, id)).returning();
return updated;
}Chữ ký
manh/flow
function defineFlow<const T extends Record<string, Record<string, readonly string[] | true>>>(
def: T,
labels?: { label(v: string): string },
): {
readonly states: S[];
next(from: string, role?: string | null): S[];
can(role: string | null | undefined, from: string, to: string): boolean;
isFinal(status: string): boolean;
assert(user: { role?: string } | null | undefined, from: string, to: string): void;
move(user: { id?: number | string; name?: string; role?: string } | null | undefined, from: string, to: string, note?: string | null):
{ from: string; to: S; actorId: number | string | null; actorName: string | null; note: string | null; at: number };
};
// S = các khoá của defTham số
def: object, mỗi khoá là một trạng thái. Giá trị là các bước đi tiếp: trạng thái đích → danh sách vai được làm bước đó, hoặctruecho mọi người đã đăng nhập. Trạng thái cuối có giá trị{}.labels: enum trạng thái tạo bằng defineEnum. Có nó thì lỗi chuyển sai ghi tên dễ đọc, ví dụ: Không thể chuyển từ “Mới” sang “Đã giao”, thay cho khoánew,done.
Trả về
states: mọi trạng thái.next(from, role?): các trạng thái đi tiếp từfrom. Córolethì chỉ còn các bước vai đó được làm;rolelànull(chưa đăng nhập) thì không còn bước nào.can(role, from, to): vai này có được chuyểnfrom→tokhông.isFinal(status):truekhi trạng thái không còn bước nào.assert(user, from, to): ném lỗi 409 mãFLOW_ILLEGALkhi không có bước đó, 403 mãFORBIDDENkhi sai vai. Body lỗi giốngfail:{ error, message, code }.move(user, from, to, note?): chạyassert, rồi trả dòng lịch sử{ from, to, actorId, actorName, note, at }để bạn ghi vào bảng lịch sử của mình.
Ví dụ
Chỉ hiện nút người dùng được bấm:
app/orders/[id]/page.tsx
const { user } = useSession();
const moves = OrderFlow.next(order.status, user?.role ?? null);
return moves.map((to) => <Button key={to} onClick={() => move(order.id, { to })}>{OrderStatus.label(to)}</Button>);Ghi lịch sử cùng lúc với đổi trạng thái:
app/orders/repository.ts
const event = OrderFlow.move(user, row.status, to, note);
await db.insert(orderEvents).values({ orderId: id, ...event });Không giữ bản sao thứ hai của bảng chuyển trạng thái trong trang hay handler.
Bước tiếp theo
- defineEnum: nhãn và màu cho từng trạng thái.
- Đăng nhập và phân quyền: vai của người dùng.
Cập nhật