import { BadRequestException, Injectable, NotFoundException } from "@nestjs/common"; import { BookingStatus, Prisma } from "@prisma/client"; import { PrismaService } from "./prisma.service.js"; import { canTransitionWorkflow, workflowRegistry } from "@personal-brand/config"; import { BrandReleaseService } from "./brand-release.service.js"; const BASIC_BOOKING_WORKFLOW = workflowRegistry["booking.basic"]; export interface CreateBookingInput { requestType: "package" | "private_chef" | "inquiry"; customerName: string; phone?: string; wechatId?: string; contactPreference: "wechat" | "phone" | "none"; fulfillmentType?: "pickup" | "delivery"; offeringId?: string; requestedDate?: string; requestedTime?: string; deliveryAddress?: string; note?: string; extraData?: Prisma.InputJsonObject; items?: Array<{ offeringId: string; quantity: number }>; } @Injectable() export class BookingService { constructor( private readonly prisma: PrismaService, private readonly releases: BrandReleaseService, ) {} async create(brandId: string, customerUserId: string, input: CreateBookingInput) { const snapshot = await this.releases.getPublishedSnapshot(brandId); if (!snapshot) throw new BadRequestException("品牌尚未发布"); const publishedOfferingIds = this.releases.publishedOfferingIds(snapshot); if ( (input.offeringId && !publishedOfferingIds.has(input.offeringId)) || input.items?.some((item) => !publishedOfferingIds.has(item.offeringId)) ) { throw new BadRequestException("业务提供项不存在或暂不可预订"); } const requestedOfferingIds = [ ...(input.offeringId ? [input.offeringId] : []), ...(input.items ?? []).map((item) => item.offeringId), ]; if (requestedOfferingIds.length) { const enabledCount = await this.prisma.offering.count({ where: { id: { in: requestedOfferingIds }, brandId, isEnabled: true }, }); if (enabledCount !== new Set(requestedOfferingIds).size) throw new BadRequestException("业务提供项不存在或暂不可预订"); } 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 offeringMap = new Map( snapshot.offerings.flatMap((raw) => { if (!raw || typeof raw !== "object") return []; const item = raw as Record; return typeof item.id === "string" && item.isEnabled === true ? [[item.id, item] as const] : []; }), ); const items = (input.items ?? []).map((item) => { const offering = offeringMap.get(item.offeringId); if (!offering || typeof offering.priceAmount !== "number") throw new BadRequestException("套餐不存在或暂不可预订"); return { offeringId: item.offeringId, serviceNameSnapshot: String(offering.name), unitPriceSnapshot: offering.priceAmount, quantity: item.quantity, subtotalSnapshot: offering.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, offeringId: items[0]?.offeringId ?? input.offeringId ?? 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 }, stateTransitions: { create: { workflowKey: BASIC_BOOKING_WORKFLOW.key, workflowVersion: BASIC_BOOKING_WORKFLOW.version, toState: "received", actorRole: "customer", }, }, }, 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, offering: { 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 (!canTransitionWorkflow(booking.workflowKey, booking.currentState, "cancelled")) throw new BadRequestException("当前状态不可取消"); return this.prisma.$transaction(async (tx) => { const updated = await tx.booking.update({ where: { id }, data: { status: "cancelled", currentState: "cancelled" }, }); await tx.bookingStateTransition.create({ data: { bookingId: id, workflowKey: booking.workflowKey, workflowVersion: booking.workflowVersion, fromState: booking.currentState, toState: "cancelled", actorRole: "customer", }, }); return updated; }); } 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 } }, offering: 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("订单不存在"); if (!canTransitionWorkflow(booking.workflowKey, booking.currentState, status)) throw new BadRequestException("不允许的订单状态流转"); return this.prisma.$transaction(async (tx) => { const updated = await tx.booking.update({ where: { id }, data: { status, currentState: status, ...(adminNote !== undefined ? { adminNote } : {}), isRead: true, }, }); if (status !== booking.currentState) { await tx.bookingStateTransition.create({ data: { bookingId: id, workflowKey: booking.workflowKey, workflowVersion: booking.workflowVersion, fromState: booking.currentState, toState: status, actorRole: "admin", }, }); } return updated; }); } 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 } } }, }); } }