210 lines
8.0 KiB
TypeScript
210 lines
8.0 KiB
TypeScript
import { BadRequestException, Injectable, NotFoundException } from "@nestjs/common";
|
|
import { BookingStatus, Prisma } from "@prisma/client";
|
|
import { PrismaService } from "./prisma.service.js";
|
|
|
|
export interface CreateBookingInput {
|
|
requestType: "package" | "private_chef" | "inquiry";
|
|
customerName: string;
|
|
phone?: string;
|
|
wechatId?: string;
|
|
contactPreference: "wechat" | "phone" | "none";
|
|
fulfillmentType?: "pickup" | "delivery";
|
|
serviceId?: string;
|
|
requestedDate?: string;
|
|
requestedTime?: string;
|
|
deliveryAddress?: string;
|
|
note?: string;
|
|
extraData?: Prisma.InputJsonObject;
|
|
items?: Array<{ serviceId: string; quantity: number }>;
|
|
}
|
|
|
|
@Injectable()
|
|
export class BookingService {
|
|
constructor(private readonly prisma: PrismaService) {}
|
|
|
|
async create(brandId: string, customerUserId: string, input: CreateBookingInput) {
|
|
if (!input.customerName.trim() || (!input.phone?.trim() && !input.wechatId?.trim())) {
|
|
throw new BadRequestException("称呼和至少一种联系方式为必填项");
|
|
}
|
|
if (
|
|
input.requestType === "package" &&
|
|
(!input.items?.length || input.items.some((item) => item.quantity < 1))
|
|
) {
|
|
throw new BadRequestException("普通套餐至少选择一份有效套餐");
|
|
}
|
|
const extraData = input.extraData as { people?: unknown; location?: unknown } | undefined;
|
|
const allowedExtraKeys = new Set([
|
|
"people",
|
|
"location",
|
|
"budgetRange",
|
|
"tastePreferences",
|
|
"allergyNotes",
|
|
"dishPreferences",
|
|
]);
|
|
if (input.extraData && Object.keys(input.extraData).some((key) => !allowedExtraKeys.has(key)))
|
|
throw new BadRequestException("存在不支持的行业字段");
|
|
if (
|
|
input.requestType === "private_chef" &&
|
|
(!input.requestedDate || !extraData?.people || !extraData.location)
|
|
) {
|
|
throw new BadRequestException("私厨需求必须填写日期、人数和地点");
|
|
}
|
|
const services = input.items?.length
|
|
? await this.prisma.service.findMany({
|
|
where: {
|
|
id: { in: input.items.map((item) => item.serviceId) },
|
|
brandId,
|
|
isEnabled: true,
|
|
},
|
|
})
|
|
: [];
|
|
const serviceMap = new Map(services.map((service) => [service.id, service]));
|
|
const items = (input.items ?? []).map((item) => {
|
|
const service = serviceMap.get(item.serviceId);
|
|
if (!service || !service.bookingEnabled || service.priceAmount === null)
|
|
throw new BadRequestException("套餐不存在或暂不可预订");
|
|
return {
|
|
serviceId: service.id,
|
|
serviceNameSnapshot: service.name,
|
|
unitPriceSnapshot: service.priceAmount,
|
|
quantity: item.quantity,
|
|
subtotalSnapshot: service.priceAmount * item.quantity,
|
|
};
|
|
});
|
|
const estimatedAmount = items.reduce((sum, item) => sum + item.subtotalSnapshot, 0) || null;
|
|
const booking = await this.prisma.booking.create({
|
|
data: {
|
|
bookingNo: `AC${Date.now()}${Math.floor(Math.random() * 1000)
|
|
.toString()
|
|
.padStart(3, "0")}`,
|
|
brandId,
|
|
customerUserId,
|
|
requestType: input.requestType,
|
|
customerName: input.customerName.trim(),
|
|
phone: input.phone?.trim() ?? null,
|
|
wechatId: input.wechatId?.trim() ?? null,
|
|
contactPreference: input.contactPreference,
|
|
fulfillmentType: input.fulfillmentType ?? null,
|
|
serviceId: items[0]?.serviceId ?? input.serviceId ?? null,
|
|
requestedDate: input.requestedDate
|
|
? new Date(`${input.requestedDate}T00:00:00.000Z`)
|
|
: null,
|
|
requestedTime: input.requestedTime ?? null,
|
|
deliveryAddress: input.deliveryAddress ?? null,
|
|
estimatedAmount,
|
|
...(input.extraData ? { extraData: input.extraData } : {}),
|
|
note: input.note ?? null,
|
|
items: { create: items },
|
|
},
|
|
select: { bookingNo: true, status: true, estimatedAmount: true, createdAt: true },
|
|
});
|
|
return booking;
|
|
}
|
|
|
|
async listForCustomer(brandId: string, customerUserId: string) {
|
|
return this.prisma.booking.findMany({
|
|
where: { brandId, customerUserId },
|
|
orderBy: { createdAt: "desc" },
|
|
include: { items: true, service: { select: { name: true } } },
|
|
});
|
|
}
|
|
|
|
async cancelForCustomer(brandId: string, customerUserId: string, id: string) {
|
|
const booking = await this.prisma.booking.findFirst({ where: { id, brandId, customerUserId } });
|
|
if (!booking) throw new NotFoundException("订单不存在");
|
|
if (booking.status !== "received") throw new BadRequestException("当前状态不可取消");
|
|
return this.prisma.booking.update({ where: { id }, data: { status: "cancelled" } });
|
|
}
|
|
|
|
async listForAdmin(
|
|
brandId: string,
|
|
options: { status?: BookingStatus; unreadOnly?: boolean; tagId?: string } = {},
|
|
) {
|
|
return this.prisma.booking.findMany({
|
|
where: {
|
|
brandId,
|
|
...(options.status ? { status: options.status } : {}),
|
|
...(options.unreadOnly ? { isRead: false } : {}),
|
|
...(options.tagId ? { tags: { some: { tagId: options.tagId } } } : {}),
|
|
},
|
|
orderBy: { createdAt: "desc" },
|
|
include: { items: true, tags: { include: { tag: true } } },
|
|
});
|
|
}
|
|
|
|
async getForAdmin(brandId: string, id: string) {
|
|
const booking = await this.prisma.booking.findFirst({
|
|
where: { id, brandId },
|
|
include: { items: true, tags: { include: { tag: true } }, service: true },
|
|
});
|
|
if (!booking) throw new NotFoundException("订单不存在");
|
|
return booking;
|
|
}
|
|
|
|
async unreadCountForAdmin(brandId: string) {
|
|
return { count: await this.prisma.booking.count({ where: { brandId, isRead: false } }) };
|
|
}
|
|
|
|
async updateStatus(
|
|
brandId: string,
|
|
id: string,
|
|
status: "received" | "contacting" | "confirmed" | "completed" | "cancelled",
|
|
adminNote?: string,
|
|
) {
|
|
const booking = await this.prisma.booking.findFirst({ where: { id, brandId } });
|
|
if (!booking) throw new NotFoundException("订单不存在");
|
|
const allowed: Record<string, string[]> = {
|
|
received: ["contacting", "cancelled"],
|
|
contacting: ["confirmed", "cancelled"],
|
|
confirmed: ["completed", "cancelled"],
|
|
completed: [],
|
|
cancelled: [],
|
|
};
|
|
if (status !== booking.status && !allowed[booking.status]?.includes(status))
|
|
throw new BadRequestException("不允许的订单状态流转");
|
|
return this.prisma.booking.update({
|
|
where: { id },
|
|
data: { status, ...(adminNote !== undefined ? { adminNote } : {}), isRead: true },
|
|
});
|
|
}
|
|
|
|
async markRead(brandId: string, id: string) {
|
|
const booking = await this.prisma.booking.findFirst({ where: { id, brandId } });
|
|
if (!booking) throw new NotFoundException("订单不存在");
|
|
return this.prisma.booking.update({ where: { id }, data: { isRead: true } });
|
|
}
|
|
|
|
async listTags(brandId: string) {
|
|
return this.prisma.tag.findMany({
|
|
where: { brandId, isEnabled: true },
|
|
orderBy: [{ isPreset: "desc" }, { name: "asc" }],
|
|
});
|
|
}
|
|
|
|
async createTag(brandId: string, name: string) {
|
|
const normalized = name.trim();
|
|
if (!normalized || normalized.length > 24) throw new BadRequestException("标签名称长度无效");
|
|
return this.prisma.tag.create({ data: { brandId, name: normalized } });
|
|
}
|
|
|
|
async updateTags(brandId: string, bookingId: string, tagIds: string[]) {
|
|
const booking = await this.prisma.booking.findFirst({ where: { id: bookingId, brandId } });
|
|
if (!booking) throw new NotFoundException("订单不存在");
|
|
const tags = await this.prisma.tag.findMany({
|
|
where: { id: { in: tagIds }, brandId, isEnabled: true },
|
|
select: { id: true },
|
|
});
|
|
if (tags.length !== new Set(tagIds).size) throw new BadRequestException("存在无效标签");
|
|
await this.prisma.$transaction([
|
|
this.prisma.bookingTag.deleteMany({ where: { bookingId } }),
|
|
this.prisma.bookingTag.createMany({
|
|
data: tags.map((tag) => ({ bookingId, tagId: tag.id })),
|
|
}),
|
|
]);
|
|
return this.prisma.booking.findUnique({
|
|
where: { id: bookingId },
|
|
include: { tags: { include: { tag: true } } },
|
|
});
|
|
}
|
|
}
|