2026-07-08 15:02:03 +08:00
|
|
|
|
"use server";
|
|
|
|
|
|
|
|
|
|
|
|
import { revalidatePath } from "next/cache";
|
|
|
|
|
|
import { redirect } from "next/navigation";
|
|
|
|
|
|
import { z } from "zod";
|
|
|
|
|
|
import * as XLSX from "xlsx";
|
|
|
|
|
|
import { Prisma } from "@prisma/client";
|
|
|
|
|
|
import { prisma } from "@/lib/prisma";
|
|
|
|
|
|
import { auth } from "@/lib/auth";
|
2026-07-12 00:06:00 +08:00
|
|
|
|
import { isSuperAdmin } from "@/lib/acl";
|
2026-07-12 00:30:17 +08:00
|
|
|
|
import { fmtDate, parseDate } from "@/lib/utils";
|
2026-07-08 15:02:03 +08:00
|
|
|
|
|
|
|
|
|
|
// 校验规则对齐老系统必填项(customer_name/contacts/balance_user/detail/salesman/report_date)
|
|
|
|
|
|
const schema = z.object({
|
2026-07-12 00:30:17 +08:00
|
|
|
|
customerName: z.string().trim().min(1, "商户名称必填").max(500),
|
2026-07-08 15:02:03 +08:00
|
|
|
|
contacts: z.string().trim().min(1, "联系人必填").max(500),
|
|
|
|
|
|
balanceUser: z.string().trim().min(1, "结算人必填").max(500),
|
2026-07-12 00:30:17 +08:00
|
|
|
|
detail: z.string().trim().min(1, "产品明细必填"),
|
2026-07-08 15:02:03 +08:00
|
|
|
|
salesman: z.string().trim().min(1, "业务员必填"),
|
|
|
|
|
|
reportDate: z
|
|
|
|
|
|
.string()
|
|
|
|
|
|
.trim()
|
2026-07-12 00:30:17 +08:00
|
|
|
|
.min(1, "报单日期必填")
|
|
|
|
|
|
.refine((s) => parseDate(s) !== null, "报单日期格式应为 YYYY-MM-DD"),
|
2026-07-08 15:02:03 +08:00
|
|
|
|
phone: z.string().trim().optional().default(""),
|
|
|
|
|
|
deposit: z.string().trim().optional().default(""),
|
|
|
|
|
|
buy: z.string().trim().optional().default(""),
|
|
|
|
|
|
birthdayType: z.coerce.number().int().min(1).max(2).default(1),
|
|
|
|
|
|
birthday: z.string().trim().optional().default(""),
|
|
|
|
|
|
remark: z.string().trim().optional().default(""),
|
|
|
|
|
|
});
|
|
|
|
|
|
|
2026-07-12 00:30:17 +08:00
|
|
|
|
// 新增商户更严格:名称无空格、手机号必填 11 位、押金/买断/生日必填(仅用于创建,编辑仍用 schema)
|
2026-07-11 21:17:59 +08:00
|
|
|
|
const createSchema = schema.extend({
|
|
|
|
|
|
customerName: z
|
|
|
|
|
|
.string()
|
|
|
|
|
|
.trim()
|
2026-07-12 00:30:17 +08:00
|
|
|
|
.min(1, "商户名称必填")
|
2026-07-11 21:17:59 +08:00
|
|
|
|
.max(500)
|
2026-07-12 00:30:17 +08:00
|
|
|
|
.refine((s) => !/\s/.test(s), "商户名称不能包含空格"),
|
2026-07-11 21:17:59 +08:00
|
|
|
|
phone: z.string().trim().regex(/^1\d{10}$/, "手机号必须为 11 位数字"),
|
|
|
|
|
|
deposit: z.string().trim().min(1, "押金必填"),
|
|
|
|
|
|
buy: z.string().trim().min(1, "买断必填"),
|
|
|
|
|
|
birthday: z
|
|
|
|
|
|
.string()
|
|
|
|
|
|
.trim()
|
|
|
|
|
|
.min(1, "生日必填")
|
|
|
|
|
|
.refine((s) => parseDate(s) !== null, "生日格式应为 YYYY-MM-DD"),
|
|
|
|
|
|
});
|
|
|
|
|
|
|
2026-07-08 15:02:03 +08:00
|
|
|
|
export type ActionState = { error?: string };
|
|
|
|
|
|
|
2026-07-11 21:17:59 +08:00
|
|
|
|
/** 从 FormData 取出待校验的原始字段值 */
|
|
|
|
|
|
function pickForm(formData: FormData) {
|
|
|
|
|
|
return {
|
2026-07-08 15:02:03 +08:00
|
|
|
|
customerName: formData.get("customerName"),
|
|
|
|
|
|
contacts: formData.get("contacts"),
|
|
|
|
|
|
balanceUser: formData.get("balanceUser"),
|
|
|
|
|
|
detail: formData.get("detail"),
|
|
|
|
|
|
salesman: formData.get("salesman"),
|
|
|
|
|
|
reportDate: formData.get("reportDate"),
|
|
|
|
|
|
phone: formData.get("phone") ?? "",
|
|
|
|
|
|
deposit: formData.get("deposit") ?? "",
|
|
|
|
|
|
buy: formData.get("buy") ?? "",
|
|
|
|
|
|
birthdayType: formData.get("birthdayType") ?? 1,
|
|
|
|
|
|
birthday: formData.get("birthday") ?? "",
|
|
|
|
|
|
remark: formData.get("remark") ?? "",
|
2026-07-11 21:17:59 +08:00
|
|
|
|
};
|
2026-07-08 15:02:03 +08:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
/** 把校验后的表单值转成 Prisma 写入数据(日期字段转 Date) */
|
|
|
|
|
|
function toData(v: z.infer<typeof schema>) {
|
|
|
|
|
|
const { reportDate, birthday, ...rest } = v;
|
|
|
|
|
|
return {
|
|
|
|
|
|
...rest,
|
|
|
|
|
|
reportDate: parseDate(reportDate),
|
|
|
|
|
|
birthday: parseDate(birthday),
|
|
|
|
|
|
};
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
export async function createCustomer(
|
|
|
|
|
|
_prev: ActionState,
|
|
|
|
|
|
formData: FormData
|
|
|
|
|
|
): Promise<ActionState> {
|
|
|
|
|
|
if (!(await auth())) return { error: "未登录" };
|
2026-07-11 21:17:59 +08:00
|
|
|
|
const r = createSchema.safeParse(pickForm(formData));
|
2026-07-08 15:02:03 +08:00
|
|
|
|
if (!r.success) return { error: r.error.issues[0].message };
|
|
|
|
|
|
|
|
|
|
|
|
await prisma.customer.create({ data: toData(r.data) });
|
|
|
|
|
|
revalidatePath("/customers");
|
|
|
|
|
|
redirect("/customers");
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
export async function updateCustomer(
|
|
|
|
|
|
id: number,
|
|
|
|
|
|
_prev: ActionState,
|
|
|
|
|
|
formData: FormData
|
|
|
|
|
|
): Promise<ActionState> {
|
|
|
|
|
|
if (!(await auth())) return { error: "未登录" };
|
2026-07-11 21:17:59 +08:00
|
|
|
|
const r = schema.safeParse(pickForm(formData));
|
2026-07-08 15:02:03 +08:00
|
|
|
|
if (!r.success) return { error: r.error.issues[0].message };
|
|
|
|
|
|
|
|
|
|
|
|
await prisma.customer.update({ where: { id }, data: toData(r.data) });
|
|
|
|
|
|
revalidatePath("/customers");
|
|
|
|
|
|
redirect("/customers");
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
export async function deleteCustomer(id: number): Promise<void> {
|
2026-07-12 00:06:00 +08:00
|
|
|
|
const session = await auth();
|
|
|
|
|
|
if (!isSuperAdmin(session?.user?.roles)) return;
|
2026-07-08 15:02:03 +08:00
|
|
|
|
// 软删除,对齐老系统 deleted_at
|
|
|
|
|
|
await prisma.customer.update({
|
|
|
|
|
|
where: { id },
|
|
|
|
|
|
data: { deletedAt: new Date() },
|
|
|
|
|
|
});
|
|
|
|
|
|
revalidatePath("/customers");
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
// ============ Excel 导入 ============
|
|
|
|
|
|
|
|
|
|
|
|
const HEADER_MAP: Record<string, string> = {
|
2026-07-12 00:30:17 +08:00
|
|
|
|
商户名称: "customerName",
|
2026-07-08 15:02:03 +08:00
|
|
|
|
联系人: "contacts",
|
|
|
|
|
|
结算人: "balanceUser",
|
2026-07-12 00:30:17 +08:00
|
|
|
|
联系电话: "phone",
|
|
|
|
|
|
产品明细: "detail",
|
2026-07-08 15:02:03 +08:00
|
|
|
|
押金: "deposit",
|
|
|
|
|
|
买断: "buy",
|
|
|
|
|
|
生日类型: "birthdayType",
|
|
|
|
|
|
生日: "birthday",
|
|
|
|
|
|
业务员: "salesman",
|
2026-07-12 00:30:17 +08:00
|
|
|
|
报单日期: "reportDate",
|
2026-07-08 15:02:03 +08:00
|
|
|
|
备注: "remark",
|
|
|
|
|
|
};
|
|
|
|
|
|
|
2026-07-12 00:30:17 +08:00
|
|
|
|
export type ImportResult =
|
|
|
|
|
|
| { ok: true; inserted: number }
|
|
|
|
|
|
| { ok: false; error?: string; errorFileBase64?: string; fileName?: string; totalRows?: number };
|
2026-07-08 15:02:03 +08:00
|
|
|
|
|
|
|
|
|
|
export async function importCustomers(formData: FormData): Promise<ImportResult> {
|
|
|
|
|
|
if (!(await auth())) return { ok: false, error: "未登录" };
|
|
|
|
|
|
const file = formData.get("file");
|
|
|
|
|
|
if (!(file instanceof File) || file.size === 0) return { ok: false, error: "请选择文件" };
|
|
|
|
|
|
|
|
|
|
|
|
try {
|
|
|
|
|
|
const buf = Buffer.from(await file.arrayBuffer());
|
|
|
|
|
|
const wb = XLSX.read(buf, { type: "buffer", cellDates: true });
|
|
|
|
|
|
const sheet = wb.Sheets[wb.SheetNames[0]];
|
|
|
|
|
|
const raw = XLSX.utils.sheet_to_json<Record<string, unknown>>(sheet, { raw: false, defval: "" });
|
|
|
|
|
|
|
2026-07-12 00:30:17 +08:00
|
|
|
|
const headers = Object.keys(raw[0] ?? {});
|
|
|
|
|
|
const validData: Prisma.CustomerCreateManyInput[] = [];
|
|
|
|
|
|
const errorRows: (Record<string, unknown> & { _error: string })[] = [];
|
|
|
|
|
|
|
2026-07-08 15:02:03 +08:00
|
|
|
|
for (const row of raw) {
|
|
|
|
|
|
const rec: Record<string, string> = {};
|
|
|
|
|
|
for (const [header, val] of Object.entries(row)) {
|
|
|
|
|
|
const key = HEADER_MAP[String(header).trim()];
|
|
|
|
|
|
if (key) rec[key] = String(val ?? "").trim();
|
|
|
|
|
|
}
|
2026-07-12 00:30:17 +08:00
|
|
|
|
|
|
|
|
|
|
const errors: string[] = [];
|
|
|
|
|
|
if (!rec.customerName) errors.push("商户名称必填");
|
2026-07-08 15:02:03 +08:00
|
|
|
|
const reportDate = parseDate(rec.reportDate);
|
2026-07-12 00:30:17 +08:00
|
|
|
|
if (!rec.reportDate || !reportDate) errors.push("报单日期必填且格式为 YYYY-MM-DD");
|
|
|
|
|
|
if (rec.birthday && !parseDate(rec.birthday)) errors.push("生日格式应为 YYYY-MM-DD");
|
|
|
|
|
|
|
|
|
|
|
|
if (errors.length > 0) {
|
|
|
|
|
|
errorRows.push({ ...row, _error: errors.join(";") });
|
|
|
|
|
|
} else {
|
|
|
|
|
|
validData.push({
|
|
|
|
|
|
customerName: rec.customerName,
|
|
|
|
|
|
contacts: rec.contacts || null,
|
|
|
|
|
|
balanceUser: rec.balanceUser || null,
|
|
|
|
|
|
phone: rec.phone || null,
|
|
|
|
|
|
detail: rec.detail || null,
|
|
|
|
|
|
deposit: rec.deposit || null,
|
|
|
|
|
|
buy: rec.buy || null,
|
|
|
|
|
|
salesman: rec.salesman || null,
|
|
|
|
|
|
remark: rec.remark || null,
|
|
|
|
|
|
birthdayType: rec.birthdayType === "阴历" || rec.birthdayType === "2" ? 2 : 1,
|
|
|
|
|
|
birthday: parseDate(rec.birthday),
|
|
|
|
|
|
reportDate,
|
|
|
|
|
|
});
|
2026-07-08 15:02:03 +08:00
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-07-12 00:30:17 +08:00
|
|
|
|
// 有任何无效行:返回带错误列的 Excel
|
|
|
|
|
|
if (errorRows.length > 0) {
|
|
|
|
|
|
const errorHeaders = [...headers, "导入失败原因"];
|
|
|
|
|
|
const aoa: (string | number)[][] = [errorHeaders];
|
|
|
|
|
|
for (const row of errorRows) {
|
|
|
|
|
|
const values = headers.map((h) => String(row[h] ?? ""));
|
|
|
|
|
|
values.push(row._error);
|
|
|
|
|
|
aoa.push(values);
|
|
|
|
|
|
}
|
|
|
|
|
|
const ws = XLSX.utils.aoa_to_sheet(aoa);
|
|
|
|
|
|
ws["!cols"] = errorHeaders.map(() => ({ wch: 18 }));
|
|
|
|
|
|
const errorWb = XLSX.utils.book_new();
|
|
|
|
|
|
XLSX.utils.book_append_sheet(errorWb, ws, "导入失败明细");
|
|
|
|
|
|
const errorBuf = XLSX.write(errorWb, { type: "buffer", bookType: "xlsx" }) as Buffer;
|
|
|
|
|
|
return {
|
|
|
|
|
|
ok: false,
|
|
|
|
|
|
errorFileBase64: errorBuf.toString("base64"),
|
|
|
|
|
|
fileName: `导入失败明细_${fmtDate(new Date())}.xlsx`,
|
|
|
|
|
|
totalRows: raw.length,
|
|
|
|
|
|
};
|
|
|
|
|
|
}
|
2026-07-08 15:02:03 +08:00
|
|
|
|
|
2026-07-12 00:30:17 +08:00
|
|
|
|
if (validData.length === 0) return { ok: false, error: "无有效数据" };
|
|
|
|
|
|
|
|
|
|
|
|
await prisma.customer.createMany({ data: validData });
|
2026-07-08 15:02:03 +08:00
|
|
|
|
revalidatePath("/customers");
|
2026-07-12 00:30:17 +08:00
|
|
|
|
return { ok: true, inserted: validData.length };
|
2026-07-08 15:02:03 +08:00
|
|
|
|
} catch (e) {
|
|
|
|
|
|
return { ok: false, error: (e as Error).message };
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|