diff --git a/apps/api/prisma/migrations/20260921170000_remove_service_model/migration.sql b/apps/api/prisma/migrations/20260921170000_remove_service_model/migration.sql new file mode 100644 index 0000000..d0af403 --- /dev/null +++ b/apps/api/prisma/migrations/20260921170000_remove_service_model/migration.sql @@ -0,0 +1,9 @@ +-- Service data was backfilled into Offering before this migration. +ALTER TABLE "BookingItem" DROP CONSTRAINT IF EXISTS "BookingItem_serviceId_fkey"; +ALTER TABLE "Booking" DROP CONSTRAINT IF EXISTS "Booking_serviceId_fkey"; +ALTER TABLE "Offering" DROP CONSTRAINT IF EXISTS "Service_offeringId_fkey"; +ALTER TABLE "BookingItem" DROP COLUMN IF EXISTS "serviceId"; +ALTER TABLE "Booking" DROP COLUMN IF EXISTS "serviceId"; +DROP INDEX IF EXISTS "Service_brandId_isEnabled_sortOrder_idx"; +DROP INDEX IF EXISTS "Service_brandId_name_key"; +DROP TABLE IF EXISTS "Service"; diff --git a/apps/api/prisma/schema.prisma b/apps/api/prisma/schema.prisma index 5027541..dee3d18 100644 --- a/apps/api/prisma/schema.prisma +++ b/apps/api/prisma/schema.prisma @@ -48,7 +48,6 @@ model BrandProfile { config Json? createdAt DateTime @default(now()) updatedAt DateTime @updatedAt - services Service[] bookings Booking[] customerUsers CustomerUser[] tags Tag[] @@ -61,30 +60,6 @@ model BrandProfile { inquirySubmissions InquirySubmission[] } -model Service { - id String @id @default(uuid()) - brandId String - brand BrandProfile @relation(fields: [brandId], references: [id]) - name String - description String - categoryKey String @default("standard") - config Json? - coverUrl String? - priceText String? - priceAmount Int? - bookingEnabled Boolean @default(true) - isEnabled Boolean @default(true) - sortOrder Int @default(0) - createdAt DateTime @default(now()) - updatedAt DateTime @updatedAt - bookings Booking[] - bookingItems BookingItem[] - offeringId String? - offering Offering? @relation(fields: [offeringId], references: [id], onDelete: SetNull) - @@unique([brandId, name]) - @@index([brandId, isEnabled, sortOrder]) -} - model BrandTemplateInstallation { id String @id @default(uuid()) brandId String @@ -151,7 +126,6 @@ model Offering { config Json? createdAt DateTime @default(now()) updatedAt DateTime @updatedAt - services Service[] inquiryForms InquiryForm[] bookings Booking[] bookingItems BookingItem[] @@ -235,8 +209,6 @@ model Booking { wechatId String? contactPreference ContactPreference fulfillmentType FulfillmentType? - serviceId String? - service Service? @relation(fields: [serviceId], references: [id], onDelete: SetNull) offeringId String? offering Offering? @relation(fields: [offeringId], references: [id], onDelete: SetNull) requestedDate DateTime? @@ -277,8 +249,6 @@ model BookingItem { id String @id @default(uuid()) bookingId String booking Booking @relation(fields: [bookingId], references: [id], onDelete: Cascade) - serviceId String? - service Service? @relation(fields: [serviceId], references: [id], onDelete: SetNull) offeringId String? offering Offering? @relation(fields: [offeringId], references: [id], onDelete: SetNull) serviceNameSnapshot String diff --git a/apps/api/prisma/seed.ts b/apps/api/prisma/seed.ts index bf4b3bb..cc712f8 100644 --- a/apps/api/prisma/seed.ts +++ b/apps/api/prisma/seed.ts @@ -19,7 +19,7 @@ async function main(): Promise { }, }); - const services = [ + const offerings = [ { brandId: brand.id, name: "红烧肉双拼套餐", @@ -41,16 +41,15 @@ async function main(): Promise { name: "家庭聚餐私厨", description: "根据人数、地点和口味人工沟通报价", priceText: "面议", - bookingEnabled: true, sortOrder: 3, }, ]; - for (const service of services) { - const existing = await prisma.service.findFirst({ - where: { brandId: brand.id, name: service.name }, + for (const offering of offerings) { + const existing = await prisma.offering.findFirst({ + where: { brandId: brand.id, name: offering.name }, }); - if (existing) await prisma.service.update({ where: { id: existing.id }, data: service }); - else await prisma.service.create({ data: service }); + if (existing) await prisma.offering.update({ where: { id: existing.id }, data: offering }); + else await prisma.offering.create({ data: { ...offering, kind: "service" } }); } for (const name of ["普通套餐", "私厨", "配送", "自取", "熟客", "重点跟进"]) { diff --git a/apps/api/src/booking.dto.ts b/apps/api/src/booking.dto.ts index 87a800c..a58fb82 100644 --- a/apps/api/src/booking.dto.ts +++ b/apps/api/src/booking.dto.ts @@ -13,7 +13,7 @@ import { } from "class-validator"; export class BookingItemDto { - @IsString() serviceId!: string; + @IsString() offeringId!: string; @IsInt() @Min(1) @Max(50) quantity!: number; } @@ -25,7 +25,7 @@ export class CreateBookingDto { @IsOptional() @IsString() wechatId?: string; @IsIn(["wechat", "phone", "none"]) contactPreference!: "wechat" | "phone" | "none"; @IsOptional() @IsIn(["pickup", "delivery"]) fulfillmentType?: "pickup" | "delivery"; - @IsOptional() @IsString() serviceId?: string; + @IsOptional() @IsString() offeringId?: string; @IsOptional() @IsISO8601() requestedDate?: string; @IsOptional() @IsString() requestedTime?: string; @IsOptional() @IsString() deliveryAddress?: string; diff --git a/apps/api/src/booking.service.ts b/apps/api/src/booking.service.ts index d8d5e11..a923b1b 100644 --- a/apps/api/src/booking.service.ts +++ b/apps/api/src/booking.service.ts @@ -12,13 +12,13 @@ export interface CreateBookingInput { wechatId?: string; contactPreference: "wechat" | "phone" | "none"; fulfillmentType?: "pickup" | "delivery"; - serviceId?: string; + offeringId?: string; requestedDate?: string; requestedTime?: string; deliveryAddress?: string; note?: string; extraData?: Prisma.InputJsonObject; - items?: Array<{ serviceId: string; quantity: number }>; + items?: Array<{ offeringId: string; quantity: number }>; } @Injectable() @@ -52,27 +52,26 @@ export class BookingService { ) { throw new BadRequestException("私厨需求必须填写日期、人数和地点"); } - const services = input.items?.length - ? await this.prisma.service.findMany({ + const offerings = input.items?.length + ? await this.prisma.offering.findMany({ where: { - id: { in: input.items.map((item) => item.serviceId) }, + id: { in: input.items.map((item) => item.offeringId) }, brandId, isEnabled: true, }, }) : []; - const serviceMap = new Map(services.map((service) => [service.id, service])); + const offeringMap = new Map(offerings.map((offering) => [offering.id, offering])); const items = (input.items ?? []).map((item) => { - const service = serviceMap.get(item.serviceId); - if (!service || !service.bookingEnabled || service.priceAmount === null) + const offering = offeringMap.get(item.offeringId); + if (!offering || offering.priceAmount === null) throw new BadRequestException("套餐不存在或暂不可预订"); return { - serviceId: service.id, - offeringId: service.offeringId, - serviceNameSnapshot: service.name, - unitPriceSnapshot: service.priceAmount, + offeringId: offering.id, + serviceNameSnapshot: offering.name, + unitPriceSnapshot: offering.priceAmount, quantity: item.quantity, - subtotalSnapshot: service.priceAmount * item.quantity, + subtotalSnapshot: offering.priceAmount * item.quantity, }; }); const estimatedAmount = items.reduce((sum, item) => sum + item.subtotalSnapshot, 0) || null; @@ -89,8 +88,7 @@ export class BookingService { wechatId: input.wechatId?.trim() ?? null, contactPreference: input.contactPreference, fulfillmentType: input.fulfillmentType ?? null, - serviceId: items[0]?.serviceId ?? input.serviceId ?? null, - offeringId: items[0]?.offeringId ?? null, + offeringId: items[0]?.offeringId ?? input.offeringId ?? null, requestedDate: input.requestedDate ? new Date(`${input.requestedDate}T00:00:00.000Z`) : null, @@ -118,7 +116,7 @@ export class BookingService { return this.prisma.booking.findMany({ where: { brandId, customerUserId }, orderBy: { createdAt: "desc" }, - include: { items: true, service: { select: { name: true } } }, + include: { items: true, offering: { select: { name: true } } }, }); } @@ -165,7 +163,7 @@ export class BookingService { 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 }, + include: { items: true, tags: { include: { tag: true } }, offering: true }, }); if (!booking) throw new NotFoundException("订单不存在"); return booking; diff --git a/apps/api/src/main.ts b/apps/api/src/main.ts index f417f9a..eae2f88 100644 --- a/apps/api/src/main.ts +++ b/apps/api/src/main.ts @@ -82,12 +82,11 @@ export class PublicController { const offerings = await this.prisma.offering.findMany({ where: { isEnabled: true }, orderBy: { sortOrder: "asc" }, - include: { services: { where: { isEnabled: true }, take: 1 } }, }); - return offerings.map(({ services, ...offering }) => ({ + return offerings.map((offering) => ({ ...offering, - bookingEnabled: services[0]?.bookingEnabled ?? false, - categoryKey: services[0]?.categoryKey ?? offering.kind, + bookingEnabled: true, + categoryKey: offering.kind, })); } } @@ -559,7 +558,7 @@ export class AdminConfigController { @Get("services") listServices(@Req() request: FastifyRequest): Promise { this.requireAdmin(request); - return this.prisma.service.findMany({ + return this.prisma.offering.findMany({ where: { brandId: this.brandId() }, orderBy: { sortOrder: "asc" }, }); @@ -570,32 +569,15 @@ export class AdminConfigController { @Body() body: CreateServiceDto, ): Promise { this.requireAdmin(request); - const { config, ...fields } = body; + const { config, categoryKey, ...fields } = body; const brandId = this.brandId(); - return this.prisma.$transaction(async (tx) => { - const offering = await tx.offering.create({ - data: { - brandId, - kind: "service", - name: body.name, - description: body.description, - coverUrl: body.coverUrl ?? null, - priceText: body.priceText ?? null, - priceAmount: body.priceAmount ?? null, - isEnabled: body.isEnabled ?? true, - sortOrder: body.sortOrder ?? 0, - ...(config === undefined ? {} : { config: config as Prisma.InputJsonValue }), - }, - }); - return tx.service.create({ - data: { - ...fields, - brandId, - offeringId: offering.id, - categoryKey: body.categoryKey ?? "standard", - ...(config === undefined ? {} : { config: config as Prisma.InputJsonValue }), - }, - }); + return this.prisma.offering.create({ + data: { + ...fields, + brandId, + kind: categoryKey ?? "service", + ...(config === undefined ? {} : { config: config as Prisma.InputJsonValue }), + }, }); } @Patch("services/:id") @@ -605,33 +587,16 @@ export class AdminConfigController { @Body() body: UpdateServiceDto, ): Promise { this.requireAdmin(request); - const service = await this.prisma.service.findFirst({ where: { id, brandId: this.brandId() } }); - if (!service) throw new BadRequestException("服务不存在"); - const { config, ...fields } = body; - return this.prisma.$transaction(async (tx) => { - const updated = await tx.service.update({ - where: { id }, - data: { - ...fields, - ...(config === undefined ? {} : { config: config as Prisma.InputJsonValue }), - }, - }); - if (service.offeringId) { - await tx.offering.update({ - where: { id: service.offeringId }, - data: { - name: updated.name, - description: updated.description, - coverUrl: updated.coverUrl, - priceText: updated.priceText, - priceAmount: updated.priceAmount, - isEnabled: updated.isEnabled, - sortOrder: updated.sortOrder, - config: updated.config ?? Prisma.JsonNull, - }, - }); - } - return updated; + const item = await this.prisma.offering.findFirst({ where: { id, brandId: this.brandId() } }); + if (!item) throw new BadRequestException("业务提供项不存在"); + const { config, categoryKey, ...fields } = body; + return this.prisma.offering.update({ + where: { id }, + data: { + ...fields, + ...(categoryKey === undefined ? {} : { kind: categoryKey }), + ...(config === undefined ? {} : { config: config as Prisma.InputJsonValue }), + }, }); } } diff --git a/apps/api/test/booking.service.test.ts b/apps/api/test/booking.service.test.ts index e60267a..90c9985 100644 --- a/apps/api/test/booking.service.test.ts +++ b/apps/api/test/booking.service.test.ts @@ -5,17 +5,16 @@ import { BookingService } from "../src/booking.service.js"; const brandId = "brand-1"; const customerId = "customer-1"; -const service = { +const offering = { id: "service-1", name: "套餐", - bookingEnabled: true, priceAmount: 2800, }; function createPrisma(overrides: Record = {}): any { return { - service: { - findMany: async () => [service], + offering: { + findMany: async () => [offering], }, booking: { create: async ({ data }: any) => ({ @@ -31,7 +30,7 @@ function createPrisma(overrides: Record = {}): any { }, tag: { findMany: async () => [] }, bookingTag: { deleteMany: {}, createMany: {} }, - $transaction: async () => undefined, + $transaction: async (callback: (tx: unknown) => unknown) => callback(undefined), ...overrides, }; } @@ -43,7 +42,7 @@ test("创建普通套餐订单时保存价格快照和预计金额", async () => customerName: "陈同学", wechatId: "wx-test", contactPreference: "wechat", - items: [{ serviceId: service.id, quantity: 2 }], + items: [{ offeringId: offering.id, quantity: 2 }], }); assert.equal(result.estimatedAmount, 5600); assert.equal(result.status, "received"); @@ -85,9 +84,20 @@ test("取消不存在或不属于当前客户的订单返回不存在", async () test("订单状态只能按定义的状态机流转", async () => { const prisma = createPrisma({ booking: { - findFirst: async () => ({ id: "booking-1", status: "received" }), + findFirst: async () => ({ + id: "booking-1", + status: "received", + currentState: "received", + workflowKey: "booking.basic", + workflowVersion: "1.0.0", + }), update: async ({ data }: any) => data, }, + $transaction: async (callback: (tx: any) => unknown) => + callback({ + booking: { update: async ({ data }: any) => data }, + bookingStateTransition: { create: async () => undefined }, + }), }); const bookings = new BookingService(prisma); assert.equal( diff --git a/apps/api/test/http.integration.test.js b/apps/api/test/http.integration.test.js index cadf2a3..0067809 100644 --- a/apps/api/test/http.integration.test.js +++ b/apps/api/test/http.integration.test.js @@ -346,7 +346,7 @@ test("admin can read and update brand and service configuration", async () => { const brandBefore = await prisma.brandProfile.findUnique({ where: { id: brandId } }); assert.ok(brandBefore); - const serviceBefore = await prisma.service.findFirst({ where: { brandId, isEnabled: true } }); + const serviceBefore = await prisma.offering.findFirst({ where: { brandId, isEnabled: true } }); assert.ok(serviceBefore); let createdServiceId; @@ -381,7 +381,7 @@ test("admin can read and update brand and service configuration", async () => { const publicServices = await request("/public/services"); assert.equal(publicServices.statusCode, 200); const projectedService = JSON.parse(publicServices.body).find( - (item) => item.id === serviceBefore.offeringId, + (item) => item.id === serviceBefore.id, ); assert.equal(projectedService.priceText, "集成测试价格"); @@ -404,10 +404,9 @@ test("admin can read and update brand and service configuration", async () => { assert.equal(createdService.statusCode, 201); const createdServiceBody = JSON.parse(createdService.body); createdServiceId = createdServiceBody.id; - assert.equal(createdServiceBody.categoryKey, "consulting"); - assert.ok(createdServiceBody.offeringId); + assert.equal(createdServiceBody.kind, "consulting"); const createdOffering = await prisma.offering.findUnique({ - where: { id: createdServiceBody.offeringId }, + where: { id: createdServiceBody.id }, }); assert.equal(createdOffering?.name, "集成测试通用服务"); } finally { @@ -419,15 +418,12 @@ test("admin can read and update brand and service configuration", async () => { templateKey: brandBefore.templateKey, }, }); - await prisma.service.update({ + await prisma.offering.update({ where: { id: serviceBefore.id }, data: { priceText: serviceBefore.priceText, sortOrder: serviceBefore.sortOrder }, }); if (createdServiceId) { - const deletedService = await prisma.service.delete({ where: { id: createdServiceId } }); - if (deletedService.offeringId) { - await prisma.offering.delete({ where: { id: deletedService.offeringId } }); - } + await prisma.offering.delete({ where: { id: createdServiceId } }); } } }); @@ -534,11 +530,10 @@ test("customer can create a generic inquiry without food-specific fields", async }); test("customer can create and cancel a package booking", async () => { - const service = await prisma.service.findFirst({ + const service = await prisma.offering.findFirst({ where: { brandId, isEnabled: true, priceAmount: { not: null } }, }); assert.ok(service); - assert.ok(service.offeringId); const created = await request("/customer/bookings", { method: "POST", headers: { authorization: `Bearer ${customerToken}` }, @@ -547,7 +542,7 @@ test("customer can create and cancel a package booking", async () => { customerName: "集成测试客户", wechatId: "integration-wechat", contactPreference: "wechat", - items: [{ serviceId: service.id, quantity: 2 }], + items: [{ offeringId: service.id, quantity: 2 }], }, }); assert.equal(created.statusCode, 201); @@ -557,7 +552,7 @@ test("customer can create and cancel a package booking", async () => { assert.ok(booking); assert.equal(booking.workflowKey, "booking.basic"); assert.equal(booking.currentState, "received"); - assert.equal(booking.offeringId, service.offeringId); + assert.equal(booking.offeringId, service.id); const initialTransitions = await prisma.bookingStateTransition.findMany({ where: { bookingId: booking.id }, }); @@ -582,7 +577,7 @@ test("customer can create and cancel a package booking", async () => { }); test("admin can advance booking status but cannot skip the state machine", async () => { - const service = await prisma.service.findFirst({ + const service = await prisma.offering.findFirst({ where: { brandId, isEnabled: true, priceAmount: { not: null } }, }); assert.ok(service); @@ -594,7 +589,7 @@ test("admin can advance booking status but cannot skip the state machine", async customerName: "状态测试客户", phone: "13800000000", contactPreference: "phone", - items: [{ serviceId: service.id, quantity: 1 }], + items: [{ offeringId: service.id, quantity: 1 }], }, }); const booking = await prisma.booking.findUnique({ diff --git a/apps/miniapp/pages/booking/index.js b/apps/miniapp/pages/booking/index.js index 54719e3..68cd9e6 100644 --- a/apps/miniapp/pages/booking/index.js +++ b/apps/miniapp/pages/booking/index.js @@ -4,7 +4,7 @@ Page({ data: { service: {}, form: {}, - serviceId: "", + offeringId: "", quantity: 1, fulfillment: "pickup", submitting: false, @@ -15,12 +15,12 @@ Page({ .then(([services, brand]) => { const list = Array.isArray(services) ? services : []; const service = - list.find((item) => item.id === query.serviceId) || + list.find((item) => item.id === query.offeringId || item.id === query.serviceId) || list.find((item) => item.priceAmount !== null) || {}; this.setData({ service, - serviceId: service.id || "", + offeringId: service.id || "", template: getTemplate(brand.templateKey), }); }) @@ -40,7 +40,7 @@ Page({ }, submit() { const form = this.data.form; - if (!this.data.serviceId) return wx.showToast({ title: "请先选择服务", icon: "none" }); + if (!this.data.offeringId) return wx.showToast({ title: "请先选择服务", icon: "none" }); if (!form.customerName || !form.wechatId) return wx.showToast({ title: "请填写称呼和联系方式", icon: "none" }); if (this.data.fulfillment === "delivery" && !form.deliveryAddress) @@ -58,7 +58,7 @@ Page({ deliveryAddress: form.deliveryAddress, requestedTime: form.requestedTime, note: form.note, - items: [{ serviceId: this.data.serviceId, quantity: this.data.quantity }], + items: [{ offeringId: this.data.offeringId, quantity: this.data.quantity }], }, }) .then(() => { diff --git a/apps/miniapp/pages/index/index.js b/apps/miniapp/pages/index/index.js index 109c6e0..496632d 100644 --- a/apps/miniapp/pages/index/index.js +++ b/apps/miniapp/pages/index/index.js @@ -25,7 +25,7 @@ Page({ }, selectService(event) { wx.navigateTo({ - url: "/pages/booking/index?serviceId=" + encodeURIComponent(event.currentTarget.dataset.id), + url: "/pages/booking/index?offeringId=" + encodeURIComponent(event.currentTarget.dataset.id), }); }, goServices() { diff --git a/apps/miniapp/pages/offering/detail.js b/apps/miniapp/pages/offering/detail.js index d8e0648..6a1f1a4 100644 --- a/apps/miniapp/pages/offering/detail.js +++ b/apps/miniapp/pages/offering/detail.js @@ -21,7 +21,7 @@ Page({ return wx.showToast({ title: "请从品牌主页查看联系方式", icon: "none" }); } wx.navigateTo({ - url: "/pages/booking/index?serviceId=" + encodeURIComponent(this.data.item?.id || ""), + url: "/pages/booking/index?offeringId=" + encodeURIComponent(this.data.item?.id || ""), }); }, }); diff --git a/apps/miniapp/pages/services/index.js b/apps/miniapp/pages/services/index.js index 066be85..fab200d 100644 --- a/apps/miniapp/pages/services/index.js +++ b/apps/miniapp/pages/services/index.js @@ -52,7 +52,7 @@ Page({ return; } wx.navigateTo({ - url: "/pages/booking/index?serviceId=" + encodeURIComponent(e.currentTarget.dataset.id), + url: "/pages/booking/index?offeringId=" + encodeURIComponent(e.currentTarget.dataset.id), }); }, }); diff --git a/packages/api-client/src/index.ts b/packages/api-client/src/index.ts index b61f8dd..9196954 100644 --- a/packages/api-client/src/index.ts +++ b/packages/api-client/src/index.ts @@ -60,7 +60,7 @@ export interface TrustContentInput { } export interface BookingItemInput { - serviceId: string; + offeringId: string; quantity: number; } export interface CreateBookingInput { @@ -70,7 +70,7 @@ export interface CreateBookingInput { wechatId?: string; contactPreference: ContactPreference; fulfillmentType?: FulfillmentType; - serviceId?: string; + offeringId?: string; requestedDate?: string; requestedTime?: string; deliveryAddress?: string;