From 81cb14f098e927e2eee8b94b5368cdced88948b2 Mon Sep 17 00:00:00 2001 From: chanwoo7 Date: Thu, 19 Nov 2026 04:02:49 +0900 Subject: [PATCH 1/2] =?UTF-8?q?feat:=20=EC=A3=BC=EB=AC=B8=20=EC=BB=A4?= =?UTF-8?q?=EC=8A=A4=ED=85=80=20=EC=8A=A4=EB=83=85=EC=83=B7=20=EC=8A=A4?= =?UTF-8?q?=ED=82=A4=EB=A7=88=EC=99=80=20=EC=A3=BC=EB=AC=B8=20=EC=83=81?= =?UTF-8?q?=EC=84=B8=20=EC=BB=A4=EC=8A=A4=ED=85=80=20=EC=B6=9C=EB=A0=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 주문에 커스텀 방식·바탕·대표 이미지, 문구 자리 표시 이름·좌표·스타일, 자유 편집 영역, 3D 디자인 JSON(스키마 버전 동반)과 커스텀 이미지(3D 렌더 5장·슬롯형 합성 1장)를 스냅샷으로 남기고 구매자·판매자·관리자 상세에 내보낸다. 자유 편집은 크롭 이미지 대신 바탕 위 영역 좌표만 저장한다. 리뷰 Before와 판매자·관리자 목록 '커스텀' 배지는 품목의 커스텀 대표 이미지·방식을 쓴다. 주문 생성의 커스텀 입력·저장은 다음 PR이 붙인다. 변경점 - 스키마·마이그레이션(order_custom_snapshot) - order_item: custom_mode_snapshot(기본 NONE)·custom_base_image_url_snapshot·custom_preview_image_url - order_item_custom_text: token_id(FK 없음, 자리 지정 전 주문 null)·label_snapshot·pos_x..height·text_color·text_align, value_text nullable('문구 없음') - order_item_custom_free_edit: pos_x..height 추가, crop_image_url 삭제 - 신규 order_item_custom_design(order_item_id unique, schema_version, design_json)·order_item_custom_image(kind, image_url, (order_item_id, kind) unique). 주문과 함께 한 번만 쓰여 deleted_at이 없고 가시성은 부모 품목을 따른다(SOFT_DELETE_MODELS 미등록) - 백필: 기존 문구·자유 편집은 바탕 전체 영역(0/0/10000/10000)·#000000·CENTER, 표시 이름은 키 앞 30자, 살아 있는 문구·자유 편집이 있는 품목은 SLOT. 백필 뒤 좌표·스타일 기본값 제거 - 출력: OrderItemDetail.customMode·customPreviewImageUrl·customBaseImageUrl·customImages(kind 선언 순)·threeDDesign(타입 출력 ThreeDDesign), OrderItemCustomText.tokenId·label·valueText(nullable)·좌표·textColor·textAlign, OrderItemFreeEdit.posX..height(cropImageUrl 삭제). 상세 include 3곳은 공용 조각 하나로 합쳤다 - 저장된 디자인 JSON은 형태·버전을 방어적으로 읽고 어긋나면 디자인만 null + 경고 로그(상세는 내려간다) - 리뷰 Before 원천을 custom_preview_image_url로 바꿨다(기존 리뷰 불변, 옵션 요약 현행, 문구 미복사) - 배지: SellerOrderSummary·AdminOrderSummary.hasCustom·firstItemCustomImageUrl, SellerOrderUpdate.hasCustom(발행 매퍼가 행의 첫 품목에서 상품명·커스텀 여부를 함께 읽는다) - 시드: 문구·자유 편집 새 열, 슬롯형 합성 이미지 예시. resetSeedScope는 디자인·이미지를 주문 품목보다 먼저 지운다 - 게이트: model-ownership(디자인·이미지 order, 앱 writer는 주문 생성 PR에서), removed-schema-elements(OrderItemFreeEdit.cropImageUrl), enum-sdl-sync(CustomImageKind ↔ CustomImageKindType) 테스트 - 마이그레이션 spec 3건(마이그레이션 직전 모양 임시 표에서 열 추가·백필·기본값 제거 실행): 이행 값, 기본값 제거·nullable, SLOT 판정(삭제만 있는 품목 NONE) - 리뷰 07b 백필 spec은 지워진 crop_image_url을 임시 표로 되살려 그대로 검증 - 디자인 방어 파싱 26건(정상·키 생략·행 없음 + 깨진 형태 23종 → null + 기록) - 매퍼: 커스텀 출력·없음·tokenId/valueText null·3D 디자인·배지 표 - real DB: 구매자 상세 커스텀 스냅샷·읽을 수 없는 디자인, 판매자 목록 배지 3종·상세 렌더 순서, 관리자 목록 배지·상세, 리뷰 Before 3D·슬롯형·없음, 구독 hasCustom, resetSeedScope 디자인·이미지 --- .../migration.sql | 77 +++++++ prisma/schema.prisma | 72 +++++- prisma/seed/idempotent.ts | 6 + prisma/seed/orders.ts | 41 +++- .../services/mypage-review.service.spec.ts | 75 ++++--- src/features/order/order-admin.graphql | 8 + src/features/order/order-seller.graphql | 8 + src/features/order/order-subscription.graphql | 2 + src/features/order/order.types.graphql | 151 ++++++++++++- .../order-custom-snapshot.migration.spec.ts | 208 ++++++++++++++++++ .../order/repositories/order.repository.ts | 58 ++--- .../services/order-admin-mappers.helper.ts | 2 + .../services/order-admin.service.spec.ts | 37 ++++ .../order-custom-design.helper.spec.ts | 126 +++++++++++ .../services/order-custom-design.helper.ts | 109 +++++++++ .../order-deposit-admin.service.spec.ts | 1 + .../services/order-deposit-admin.service.ts | 6 +- .../services/order-events-mappers.helper.ts | 13 +- .../services/order-events.service.spec.ts | 1 + .../order/services/order-events.service.ts | 6 +- .../order/services/order-my.service.spec.ts | 110 +++++++++ .../order-output-mappers.helper.spec.ts | 141 +++++++++++- .../services/order-output-mappers.helper.ts | 75 ++++++- .../services/order-seller.service.spec.ts | 51 ++++- .../order/services/order-seller.service.ts | 8 +- .../order-subscription.service.spec.ts | 1 + .../order/types/order-admin-output.type.ts | 2 + src/features/order/types/order-output.type.ts | 56 ++++- .../order/types/order-seller-output.type.ts | 3 + src/features/product/index.ts | 2 + .../product-home-query.resolver.spec.ts | 10 +- .../services/product-home.service.spec.ts | 48 ++-- .../review-order-item-snapshot.helper.ts | 11 +- ...view-order-item-snapshot.migration.spec.ts | 65 ++++-- src/graphql/removed-schema-elements.spec.ts | 2 + src/test/enum-sdl-sync.spec.ts | 7 + src/test/factories/order.factory.ts | 55 +++++ src/test/model-ownership.ts | 2 + src/test/seed-reset-scope.spec.ts | 31 +++ 39 files changed, 1499 insertions(+), 188 deletions(-) create mode 100644 prisma/migrations/20261118182831_order_custom_snapshot/migration.sql create mode 100644 src/features/order/repositories/order-custom-snapshot.migration.spec.ts create mode 100644 src/features/order/services/order-custom-design.helper.spec.ts create mode 100644 src/features/order/services/order-custom-design.helper.ts diff --git a/prisma/migrations/20261118182831_order_custom_snapshot/migration.sql b/prisma/migrations/20261118182831_order_custom_snapshot/migration.sql new file mode 100644 index 00000000..5b6a1e5c --- /dev/null +++ b/prisma/migrations/20261118182831_order_custom_snapshot/migration.sql @@ -0,0 +1,77 @@ +-- 주문 품목 커스텀 스냅샷: 방식·바탕·대표 이미지, 문구 자리 표시 이름·좌표·스타일, 자유 편집 영역, 3D 디자인 JSON과 커스텀 이미지. +-- 자유 편집 크롭 이미지는 영역 좌표가 대신해 지운다. 기존 문구·자유 편집은 바탕 전체 영역·검정·가운데로 옮긴다. +-- AlterTable +ALTER TABLE `order_item` ADD COLUMN `custom_mode_snapshot` ENUM('NONE', 'SLOT', 'THREE_D') NOT NULL DEFAULT 'NONE', + ADD COLUMN `custom_base_image_url_snapshot` VARCHAR(2048) NULL, + ADD COLUMN `custom_preview_image_url` VARCHAR(2048) NULL; + +-- AlterTable +ALTER TABLE `order_item_custom_text` ADD COLUMN `token_id` BIGINT UNSIGNED NULL, + ADD COLUMN `label_snapshot` VARCHAR(30) NULL, + ADD COLUMN `pos_x` INTEGER NOT NULL DEFAULT 0, + ADD COLUMN `pos_y` INTEGER NOT NULL DEFAULT 0, + ADD COLUMN `width` INTEGER NOT NULL DEFAULT 10000, + ADD COLUMN `height` INTEGER NOT NULL DEFAULT 10000, + ADD COLUMN `text_color` CHAR(7) NOT NULL DEFAULT '#000000', + ADD COLUMN `text_align` ENUM('LEFT', 'CENTER', 'RIGHT') NOT NULL DEFAULT 'CENTER', + MODIFY `value_text` VARCHAR(200) NULL; + +-- AlterTable +ALTER TABLE `order_item_custom_free_edit` ADD COLUMN `pos_x` INTEGER NOT NULL DEFAULT 0, + ADD COLUMN `pos_y` INTEGER NOT NULL DEFAULT 0, + ADD COLUMN `width` INTEGER NOT NULL DEFAULT 10000, + ADD COLUMN `height` INTEGER NOT NULL DEFAULT 10000; + +-- backfill: 표시 이름은 키에서 따오고, 살아 있는 문구·자유 편집이 있는 품목은 슬롯형이다 +UPDATE `order_item_custom_text` SET `label_snapshot` = LEFT(`token_key_snapshot`, 30); +UPDATE `order_item` oi SET oi.`custom_mode_snapshot` = 'SLOT' +WHERE EXISTS (SELECT 1 FROM `order_item_custom_text` t WHERE t.`order_item_id` = oi.`id` AND t.`deleted_at` IS NULL) + OR EXISTS (SELECT 1 FROM `order_item_custom_free_edit` f WHERE f.`order_item_id` = oi.`id` AND f.`deleted_at` IS NULL); +-- end backfill + +-- 새 행은 주문 생성이 값을 모두 채운다 +-- AlterTable +ALTER TABLE `order_item_custom_text` MODIFY `label_snapshot` VARCHAR(30) NOT NULL, + ALTER COLUMN `pos_x` DROP DEFAULT, + ALTER COLUMN `pos_y` DROP DEFAULT, + ALTER COLUMN `width` DROP DEFAULT, + ALTER COLUMN `height` DROP DEFAULT, + ALTER COLUMN `text_color` DROP DEFAULT, + ALTER COLUMN `text_align` DROP DEFAULT; + +-- AlterTable +ALTER TABLE `order_item_custom_free_edit` ALTER COLUMN `pos_x` DROP DEFAULT, + ALTER COLUMN `pos_y` DROP DEFAULT, + ALTER COLUMN `width` DROP DEFAULT, + ALTER COLUMN `height` DROP DEFAULT, + DROP COLUMN `crop_image_url`; + +-- CreateTable +CREATE TABLE `order_item_custom_design` ( + `id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT, + `order_item_id` BIGINT UNSIGNED NOT NULL, + `schema_version` SMALLINT UNSIGNED NOT NULL, + `design_json` JSON NOT NULL, + `created_at` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3), + + UNIQUE INDEX `uk_order_item_custom_design_item`(`order_item_id`), + PRIMARY KEY (`id`) +) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; + +-- CreateTable +CREATE TABLE `order_item_custom_image` ( + `id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT, + `order_item_id` BIGINT UNSIGNED NOT NULL, + `kind` ENUM('THREE_D_TOP', 'THREE_D_FRONT', 'THREE_D_BACK', 'THREE_D_LEFT', 'THREE_D_RIGHT', 'SLOT_COMPOSITE') NOT NULL, + `image_url` VARCHAR(2048) NOT NULL, + `created_at` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3), + + UNIQUE INDEX `uk_order_item_custom_image_kind`(`order_item_id`, `kind`), + PRIMARY KEY (`id`) +) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; + +-- AddForeignKey +ALTER TABLE `order_item_custom_design` ADD CONSTRAINT `order_item_custom_design_order_item_id_fkey` FOREIGN KEY (`order_item_id`) REFERENCES `order_item`(`id`) ON DELETE RESTRICT ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE `order_item_custom_image` ADD CONSTRAINT `order_item_custom_image_order_item_id_fkey` FOREIGN KEY (`order_item_id`) REFERENCES `order_item`(`id`) ON DELETE RESTRICT ON UPDATE CASCADE; diff --git a/prisma/schema.prisma b/prisma/schema.prisma index a7afb2d5..85b33b30 100644 --- a/prisma/schema.prisma +++ b/prisma/schema.prisma @@ -58,6 +58,16 @@ enum CustomTextAlign { RIGHT } +// 주문 커스텀 이미지 종류. 3D는 윗면 + 옆면 앞·뒤·좌·우 렌더, 슬롯형은 '본 그대로' 합성 1장 +enum CustomImageKind { + THREE_D_TOP + THREE_D_FRONT + THREE_D_BACK + THREE_D_LEFT + THREE_D_RIGHT + SLOT_COMPOSITE +} + enum OrderStatus { SUBMITTED CONFIRMED @@ -1022,6 +1032,11 @@ model OrderItem { quantity Int @default(1) @db.UnsignedSmallInt item_subtotal_price Int @default(0) @db.UnsignedInt + custom_mode_snapshot CustomMode @default(NONE) + // 슬롯형 바탕 이미지. 문구 자리·자유 편집 영역 좌표의 기준이다 + custom_base_image_url_snapshot String? @db.VarChar(2048) + // 커스텀 대표 이미지(3D 윗면 렌더·슬롯형 합성). 목록 썸네일과 리뷰 Before의 원천이다 + custom_preview_image_url String? @db.VarChar(2048) created_at DateTime @default(now()) @db.DateTime(3) updated_at DateTime @updatedAt @db.DateTime(3) @@ -1034,6 +1049,8 @@ model OrderItem { option_items OrderItemOptionItem[] custom_texts OrderItemCustomText[] free_edits OrderItemCustomFreeEdit[] + custom_design OrderItemCustomDesign? + custom_images OrderItemCustomImage[] notifications Notification[] review Review? @@ -1072,10 +1089,22 @@ model OrderItemCustomText { id BigInt @id @default(autoincrement()) @db.UnsignedBigInt order_item_id BigInt @db.UnsignedBigInt - token_key_snapshot String @db.VarChar(60) - default_text_snapshot String @db.VarChar(200) - value_text String @db.VarChar(200) - sort_order Int @default(0) + // 원본 문구 자리. 자리가 바뀌거나 지워져도 스냅샷은 그대로라 FK를 두지 않는다. 자리 지정 전 주문은 null + token_id BigInt? @db.UnsignedBigInt + token_key_snapshot String @db.VarChar(60) + label_snapshot String @db.VarChar(30) + default_text_snapshot String @db.VarChar(200) + // 선택 자리를 지운 '문구 없음'은 null + value_text String? @db.VarChar(200) + sort_order Int @default(0) + + // 바탕 이미지 한 변을 10000으로 본 정수 비율, 원점은 왼쪽 위 + pos_x Int + pos_y Int + width Int + height Int + text_color String @db.Char(7) + text_align CustomTextAlign created_at DateTime @default(now()) @db.DateTime(3) updated_at DateTime @updatedAt @db.DateTime(3) @@ -1092,7 +1121,11 @@ model OrderItemCustomFreeEdit { id BigInt @id @default(autoincrement()) @db.UnsignedBigInt order_item_id BigInt @db.UnsignedBigInt - crop_image_url String @db.VarChar(2048) + // 바탕 이미지 위 요청 영역(문구 자리와 같은 좌표계) + pos_x Int + pos_y Int + width Int + height Int description_text String @db.VarChar(2000) sort_order Int @default(0) @@ -1126,6 +1159,35 @@ model OrderItemCustomFreeEditAttachment { @@map("order_item_custom_free_edit_attachment") } +// 3D 디자인 JSON(스키마 버전 동반). 주문과 함께 한 번만 쓰고 단독 삭제 경로가 없어 deleted_at을 두지 않는다 — 가시성은 order_item을 따른다 +model OrderItemCustomDesign { + id BigInt @id @default(autoincrement()) @db.UnsignedBigInt + order_item_id BigInt @unique(map: "uk_order_item_custom_design_item") @db.UnsignedBigInt + schema_version Int @db.UnsignedSmallInt + design_json Json + + created_at DateTime @default(now()) @db.DateTime(3) + + order_item OrderItem @relation(fields: [order_item_id], references: [id]) + + @@map("order_item_custom_design") +} + +// 커스텀 이미지(3D 렌더 5장·슬롯형 합성). 종류당 1장이고 디자인과 같은 이유로 deleted_at이 없다 +model OrderItemCustomImage { + id BigInt @id @default(autoincrement()) @db.UnsignedBigInt + order_item_id BigInt @db.UnsignedBigInt + kind CustomImageKind + image_url String @db.VarChar(2048) + + created_at DateTime @default(now()) @db.DateTime(3) + + order_item OrderItem @relation(fields: [order_item_id], references: [id]) + + @@unique([order_item_id, kind], map: "uk_order_item_custom_image_kind") + @@map("order_item_custom_image") +} + // 주문 1건의 결제. 계좌이체는 PENDING으로 만들고 입금 확인(관리자, 후속 연동은 AUTO) 때 CONFIRMED가 된다. model Payment { id BigInt @id @default(autoincrement()) @db.UnsignedBigInt diff --git a/prisma/seed/idempotent.ts b/prisma/seed/idempotent.ts index 3bad3b31..ac9f8973 100644 --- a/prisma/seed/idempotent.ts +++ b/prisma/seed/idempotent.ts @@ -118,6 +118,12 @@ export async function resetSeedScope(prisma: PrismaClient): Promise { await prisma.orderItemCustomText.deleteMany({ where: { order_item_id: { in: orderItemIds } }, }); + await prisma.orderItemCustomDesign.deleteMany({ + where: { order_item_id: { in: orderItemIds } }, + }); + await prisma.orderItemCustomImage.deleteMany({ + where: { order_item_id: { in: orderItemIds } }, + }); await prisma.orderItemOptionItem.deleteMany({ where: { order_item_id: { in: orderItemIds } }, }); diff --git a/prisma/seed/orders.ts b/prisma/seed/orders.ts index 21b40fc4..98d16bf3 100644 --- a/prisma/seed/orders.ts +++ b/prisma/seed/orders.ts @@ -185,6 +185,17 @@ export async function seedOrders( sale_price_snapshot: p2.sale_price, quantity: 1, item_subtotal_price: 60000, + custom_mode_snapshot: 'SLOT', + custom_base_image_url_snapshot: + 'https://placehold.co/600x600/png?text=Custom+Base', + custom_preview_image_url: + 'https://placehold.co/600x600/png?text=Custom+Composite', + custom_images: { + create: { + kind: 'SLOT_COMPOSITE', + image_url: 'https://placehold.co/600x600/png?text=Custom+Composite', + }, + }, }, }); await prisma.orderItemOptionItem.create({ @@ -202,15 +213,25 @@ export async function seedOrders( data: { order_item_id: o2Item.id, token_key_snapshot: 'message', + label_snapshot: '메시지', default_text_snapshot: '메시지를 입력하세요', value_text: '생일 축하해 :)', sort_order: 0, + pos_x: 1000, + pos_y: 1000, + width: 8000, + height: 1500, + text_color: '#1D1D1D', + text_align: 'CENTER', }, }); const o2FreeEdit = await prisma.orderItemCustomFreeEdit.create({ data: { order_item_id: o2Item.id, - crop_image_url: 'https://placehold.co/300x300/png?text=Custom+Crop', + pos_x: 2000, + pos_y: 4000, + width: 6000, + height: 4000, description_text: '이 사진을 케이크 위에 그려주세요', sort_order: 0, }, @@ -330,6 +351,9 @@ export async function seedOrders( }, }, }); + // o4에는 리뷰가 달리므로(seedReviews) 커스텀 대표 이미지를 함께 둬 + // 홈 제작 후기 쇼케이스(Before/After 페어)가 로컬에서 동작하게 한다 + const o4Preview = 'https://placehold.co/600x600/png?text=Requested+Design'; const o4Item = await prisma.orderItem.create({ data: { order_id: o4.id, @@ -343,16 +367,11 @@ export async function seedOrders( sale_price_snapshot: p1.sale_price, quantity: 1, item_subtotal_price: 35000, - }, - }); - // o4에는 리뷰가 달리므로(seedReviews) 커스텀 크롭을 함께 둬 - // 홈 제작 후기 쇼케이스(Before/After 페어)가 로컬에서 동작하게 한다 - await prisma.orderItemCustomFreeEdit.create({ - data: { - order_item_id: o4Item.id, - crop_image_url: 'https://placehold.co/300x300/png?text=Requested+Design', - description_text: '이 그림처럼 레터링해 주세요', - sort_order: 0, + custom_mode_snapshot: 'SLOT', + custom_preview_image_url: o4Preview, + custom_images: { + create: { kind: 'SLOT_COMPOSITE', image_url: o4Preview }, + }, }, }); diff --git a/src/features/mypage/services/mypage-review.service.spec.ts b/src/features/mypage/services/mypage-review.service.spec.ts index ca22ec41..61c7f50a 100644 --- a/src/features/mypage/services/mypage-review.service.spec.ts +++ b/src/features/mypage/services/mypage-review.service.spec.ts @@ -60,7 +60,9 @@ describe('UserReviewService (real DB)', () => { }); /** 리뷰 작성 가능한 상태(PICKED_UP 주문 + 본인 아이템)를 세팅 */ - async function setupReviewableOrderItem(): Promise<{ + async function setupReviewableOrderItem( + itemOverrides: Parameters[1] = {}, + ): Promise<{ accountId: bigint; storeId: bigint; productId: bigint; @@ -81,6 +83,7 @@ describe('UserReviewService (real DB)', () => { order_id: order.id, product_id: product.id, product_name_snapshot: '상품R 스냅샷', + ...itemOverrides, }); return { accountId: account.id, @@ -127,8 +130,11 @@ describe('UserReviewService (real DB)', () => { expect(saved.media.some((m) => m.media_type === 'VIDEO')).toBe(true); }); - it('작성 시점에 주문 품목의 상품명·활성 옵션(id 순)·커스텀 크롭 첫 장을 리뷰에 복사한다', async () => { - const ctx = await setupReviewableOrderItem(); + it('작성 시점에 주문 품목의 상품명·활성 옵션(id 순)·커스텀 대표 이미지를 리뷰에 복사한다', async () => { + const ctx = await setupReviewableOrderItem({ + custom_mode_snapshot: 'SLOT', + custom_preview_image_url: 'https://img/composite.png', + }); const group = await prisma.productOptionGroup.create({ data: { product_id: ctx.productId, name: '모양' }, }); @@ -151,20 +157,6 @@ describe('UserReviewService (real DB)', () => { }, }); } - for (const [url, sortOrder] of [ - ['https://img/second.png', 1], - ['https://img/first.png', 0], - ] as const) { - await prisma.orderItemCustomFreeEdit.create({ - data: { - order_item_id: ctx.orderItemId, - crop_image_url: url, - description_text: '요청', - sort_order: sortOrder, - }, - }); - } - const result = await service.writeReview(ctx.accountId, { orderItemId: ctx.orderItemId.toString(), rating: 5, @@ -180,10 +172,42 @@ describe('UserReviewService (real DB)', () => { { groupName: '모양', optionTitle: '동그라미' }, { groupName: '모양', optionTitle: '하트' }, ]); - expect(saved.before_image_url).toBe('https://img/first.png'); + expect(saved.before_image_url).toBe('https://img/composite.png'); }); - it('옵션·크롭이 없는 품목이면 option_summary·before_image_url은 null', async () => { + it.each([ + ['3D 윗면 렌더', 'THREE_D', 'https://img/top.png'], + ['슬롯형 합성', 'SLOT', 'https://img/composite.png'], + ['커스텀 없음', 'NONE', null], + ] as const)( + 'Before 이미지는 품목 커스텀 대표 이미지다(%s)', + async (_case, mode, url) => { + const ctx = await setupReviewableOrderItem({ + custom_mode_snapshot: mode, + custom_preview_image_url: url, + }); + // 대표 이미지가 아닌 커스텀 이미지·자유 편집 참고 사진은 Before 원천이 아니다 + await prisma.orderItemCustomImage.create({ + data: { + order_item_id: ctx.orderItemId, + kind: 'THREE_D_FRONT', + image_url: 'https://img/front.png', + }, + }); + const result = await service.writeReview(ctx.accountId, { + orderItemId: ctx.orderItemId.toString(), + rating: 5, + content: VALID_CONTENT, + media: [], + }); + const saved = await prisma.review.findUniqueOrThrow({ + where: { id: BigInt(result.reviewId) }, + }); + expect(saved.before_image_url).toBe(url); + }, + ); + + it('옵션·커스텀 대표 이미지가 없는 품목이면 option_summary·before_image_url은 null', async () => { const ctx = await setupReviewableOrderItem(); const result = await service.writeReview(ctx.accountId, { orderItemId: ctx.orderItemId.toString(), @@ -467,13 +491,10 @@ describe('UserReviewService (real DB)', () => { ], }); await service.deleteMyReview(ctx.accountId, first.reviewId); - // 복원도 작성 시점 규칙으로 스냅샷을 다시 찍는지 — 삭제 후 생긴 크롭이 반영돼야 한다 - await prisma.orderItemCustomFreeEdit.create({ - data: { - order_item_id: ctx.orderItemId, - crop_image_url: 'https://img/late-crop.png', - description_text: '요청', - }, + // 복원도 작성 시점 규칙으로 스냅샷을 다시 찍는지 — 삭제 후 바뀐 대표 이미지가 반영돼야 한다 + await prisma.orderItem.update({ + where: { id: ctx.orderItemId }, + data: { custom_preview_image_url: 'https://img/late-preview.png' }, }); // 다시 작성 → 같은 row 복원, rating/content/media 모두 새 값으로 교체되어야 함 @@ -502,7 +523,7 @@ describe('UserReviewService (real DB)', () => { expect(saved.deleted_at).toBeNull(); expect(Number(saved.rating)).toBe(5); expect(saved.content).toBe(NEW_CONTENT); - expect(saved.before_image_url).toBe('https://img/late-crop.png'); + expect(saved.before_image_url).toBe('https://img/late-preview.png'); // media: 새 값 2건만 남고 stale 1건은 정리됐는지 확인 const mediaRows = await prisma.reviewMedia.findMany({ diff --git a/src/features/order/order-admin.graphql b/src/features/order/order-admin.graphql index a96a1447..b3d7f789 100644 --- a/src/features/order/order-admin.graphql +++ b/src/features/order/order-admin.graphql @@ -82,6 +82,14 @@ type AdminOrderSummary { 첫 품목의 상품 대표 이미지 URL(주문 시점 스냅샷). 주문 당시 이미지가 없었거나 품목이 없으면 null. """ firstItemImageUrl: String + """ + 커스텀 주문 여부(첫 품목의 커스텀 방식이 NONE이 아니면 true). 목록 '커스텀' 배지용이다. + """ + hasCustom: Boolean! + """ + 첫 품목의 커스텀 대표 이미지 URL(3D 윗면 렌더 또는 슬롯형 합성). 없으면 null. + """ + firstItemCustomImageUrl: String } """ diff --git a/src/features/order/order-seller.graphql b/src/features/order/order-seller.graphql index 895f6744..9a1cc892 100644 --- a/src/features/order/order-seller.graphql +++ b/src/features/order/order-seller.graphql @@ -69,6 +69,14 @@ type SellerOrderSummary { 내 매장 첫 품목의 상품 대표 이미지 URL(주문 시점 스냅샷). 주문 당시 이미지가 없었으면 null. """ firstItemImageUrl: String + """ + 커스텀 주문 여부(내 매장 첫 품목의 커스텀 방식이 NONE이 아니면 true). 목록 '커스텀' 배지용이다. + """ + hasCustom: Boolean! + """ + 내 매장 첫 품목의 커스텀 대표 이미지 URL(3D 윗면 렌더 또는 슬롯형 합성). 없으면 null. + """ + firstItemCustomImageUrl: String } """ diff --git a/src/features/order/order-subscription.graphql b/src/features/order/order-subscription.graphql index 6059c540..cdcf029f 100644 --- a/src/features/order/order-subscription.graphql +++ b/src/features/order/order-subscription.graphql @@ -31,6 +31,8 @@ type SellerOrderUpdate { totalPrice: Int! """첫 품목의 상품명(주문 시점 스냅샷). 주문은 단일 상품 구조다.""" productName: String! + """커스텀 주문 여부(첫 품목의 커스텀 방식이 NONE이 아니면 true).""" + hasCustom: Boolean! """주문 행의 updated_at. 폐기 규칙의 비교 키다.""" updatedAt: DateTime! } diff --git a/src/features/order/order.types.graphql b/src/features/order/order.types.graphql index 2cc80a6d..6f9773dd 100644 --- a/src/features/order/order.types.graphql +++ b/src/features/order/order.types.graphql @@ -194,12 +194,119 @@ type OrderItemDetail { itemSubtotalPrice: Int! """선택한 옵션(주문 시점 스냅샷).""" optionItems: [OrderItemOption!]! + """커스텀 방식(주문 시점 스냅샷). 커스텀이 없는 품목은 NONE.""" + customMode: CustomModeType! + """ + 커스텀 대표 이미지 URL. 3D는 윗면 렌더, 슬롯형은 합성 이미지이고 목록 썸네일·리뷰 Before에 쓰인다. 없으면 null. + """ + customPreviewImageUrl: String + """ + 슬롯형 바탕 이미지 URL(주문 시점 스냅샷, 정사각). 문구 자리·자유 편집 영역 좌표의 기준이다. 슬롯형이 아니거나 바탕을 저장하기 전 주문이면 null. + """ + customBaseImageUrl: String + """커스텀 이미지(3D 렌더 5장 또는 슬롯형 합성 1장). kind 선언 순서다. 없으면 빈 배열.""" + customImages: [OrderItemCustomImage!]! + """3D 디자인(JSON v1). 3D가 아니거나 저장된 값을 읽을 수 없으면 null.""" + threeDDesign: ThreeDDesign """입력한 커스텀 문구(주문 시점 스냅샷).""" customTexts: [OrderItemCustomText!]! """자유 편집 요청(주문 시점 스냅샷).""" freeEdits: [OrderItemFreeEdit!]! } +""" +주문 커스텀 이미지 종류. 값은 늘어날 수 있으니 모르는 값을 받아도 화면이 죽지 않게 처리한다. +3D 옆면은 옆면 고도 asin(0.4) 정사영이고 좌·우는 정면을 보는 사람 기준이다. +""" +enum CustomImageKindType { + """3D 윗면(위에서 내려다본 정사각). 대표 이미지다.""" + THREE_D_TOP + """3D 옆면 정면(yaw 0).""" + THREE_D_FRONT + """3D 옆면 뒤(정면 반대).""" + THREE_D_BACK + """3D 옆면 왼쪽.""" + THREE_D_LEFT + """3D 옆면 오른쪽.""" + THREE_D_RIGHT + """슬롯형 합성 이미지(바탕 + 문구, 구매자가 본 그대로). 대표 이미지다.""" + SLOT_COMPOSITE +} + +"""주문 커스텀 이미지 1장.""" +type OrderItemCustomImage { + id: ID! + """이미지 종류. 품목마다 종류당 1장이다.""" + kind: CustomImageKindType! + """이미지 URL.""" + imageUrl: String! +} + +""" +주문에 저장된 3D 디자인(JSON v1). 배열 순서가 그리는 순서다. 그리는 규칙은 판매자 앱 렌더러와 구매자 편집기가 공유한다. +선택지·시트 색·효과·꾸미기 키는 customThreeDCatalog의 key이고, 퇴역한 항목도 과거 주문을 그릴 수 있게 카탈로그에 남는다. +""" +type ThreeDDesign { + """디자인 JSON 버전. 지금은 1.""" + schemaVersion: Int! + """모양·크기·디자인·맛·시트 색.""" + basic: ThreeDDesignBasic! + """윗면 항목. x·y는 케이크 판 정사각 기준 중심 0~1(왼쪽 위 원점).""" + top: [ThreeDDesignItem!]! + """옆면 항목. x는 정면(yaw 0)에서 잰 둘레 비율 0~1, y는 윗면 0~바닥 1.""" + side: [ThreeDDesignItem!]! +} + +"""3D 디자인의 케이크 기본값.""" +type ThreeDDesignBasic { + """모양 선택지 key.""" + shape: String! + """크기 선택지 key.""" + size: String! + """디자인 선택지 key. 고르지 않았으면 null(장식 없는 시트).""" + design: String + """맛 선택지 key. 고르지 않았으면 null.""" + flavor: String + """시트 색 key.""" + sheetColor: String! +} + +"""3D 디자인 항목 종류. 값은 늘어날 수 있으니 모르는 값을 받아도 화면이 죽지 않게 처리한다.""" +enum ThreeDItemKindType { + """글자.""" + TEXT + """꾸미기 이미지.""" + DECO +} + +"""3D 디자인 항목(글자 또는 꾸미기) 1개.""" +type ThreeDDesignItem { + """항목 종류.""" + kind: ThreeDItemKindType! + """가로 위치(면별 좌표계, ThreeDDesign.top·side 참고).""" + x: Float! + """세로 위치(면별 좌표계, ThreeDDesign.top·side 참고).""" + y: Float! + """크기(케이크 판 너비 대비 cqw).""" + size: Float! + """효과.""" + effect: ThreeDDesignEffect! + """글자 내용(줄바꿈·이모지 포함). TEXT만 값이 있다.""" + text: String + """글자색(#RRGGBB 대문자). TEXT만 값이 있다.""" + color: String + """꾸미기 key. DECO만 값이 있다.""" + decoId: String +} + +"""3D 디자인 항목에 건 효과.""" +type ThreeDDesignEffect { + """효과 key(카탈로그 effects).""" + type: String! + """효과 강도(0~100 정수).""" + intensity: Int! +} + """주문 시점의 옵션 스냅샷. 판매자가 이후 옵션을 수정·삭제해도 주문 내용은 변하지 않는다.""" type OrderItemOption { id: ID! @@ -211,24 +318,52 @@ type OrderItemOption { priceDelta: Int! } -"""주문 시점의 커스텀 문구 스냅샷.""" +""" +주문 시점의 커스텀 문구 스냅샷. 좌표는 바탕 이미지 한 변을 10000으로 본 정수 비율이고 원점은 왼쪽 위다. +글꼴은 플랫폼 공통 1종(Pretendard Bold)이고 크기는 영역에 맞춰 자동이다. +""" type OrderItemCustomText { id: ID! - """문구 슬롯 식별 키(주문 시점).""" + """원본 문구 자리 ID. 자리가 이후 바뀌거나 지워져도 스냅샷은 그대로다. 문구 자리를 지정하기 전 주문이면 null.""" + tokenId: ID + """문구 자리 식별 키(주문 시점).""" tokenKey: String! - """슬롯의 기본 문구(주문 시점).""" + """문구 자리 표시 이름(주문 시점).""" + label: String! + """문구 자리의 기본 문구(주문 시점).""" defaultText: String! - """구매자가 실제로 입력한 문구.""" - valueText: String! + """구매자가 넣은 문구(줄바꿈·이모지 포함). 선택 자리를 지웠으면 null('문구 없음').""" + valueText: String + """영역 왼쪽 위 x(0~10000).""" + posX: Int! + """영역 왼쪽 위 y(0~10000).""" + posY: Int! + """영역 너비(posX + width ≤ 10000).""" + width: Int! + """영역 높이(posY + height ≤ 10000).""" + height: Int! + """글자색(#RRGGBB 대문자).""" + textColor: String! + """영역 안 글자 정렬.""" + textAlign: CustomTextAlignType! """입력 화면 노출 순서. 오름차순.""" sortOrder: Int! } -"""주문 시점의 자유 편집 요청 스냅샷. 구매자가 이미지 위에 영역을 지정해 남긴 요청이다.""" +""" +주문 시점의 자유 편집 요청 스냅샷. 구매자가 슬롯형 바탕 이미지 위에 영역을 지정해 남긴 요청이다. +좌표계는 OrderItemCustomText와 같다(바탕 한 변 10000, 왼쪽 위 원점). +""" type OrderItemFreeEdit { id: ID! - """지정한 편집 영역을 잘라낸 이미지 URL.""" - cropImageUrl: String! + """영역 왼쪽 위 x(0~10000).""" + posX: Int! + """영역 왼쪽 위 y(0~10000).""" + posY: Int! + """영역 너비(posX + width ≤ 10000).""" + width: Int! + """영역 높이(posY + height ≤ 10000).""" + height: Int! """해당 영역에 대한 요청 문구.""" descriptionText: String! """요청 순서. 오름차순.""" diff --git a/src/features/order/repositories/order-custom-snapshot.migration.spec.ts b/src/features/order/repositories/order-custom-snapshot.migration.spec.ts new file mode 100644 index 00000000..a342eeea --- /dev/null +++ b/src/features/order/repositories/order-custom-snapshot.migration.spec.ts @@ -0,0 +1,208 @@ +import { readFileSync, readdirSync } from 'node:fs'; +import { join } from 'node:path'; + +import mysql, { type RowDataPacket } from 'mysql2/promise'; + +import { + disconnectTestPrismaClient, + getTestDatabaseUrl, +} from '@/test/db/prisma-test-client'; +import { closeTruncateConnection } from '@/test/db/truncate'; +import { createTestingModuleWithRealDb } from '@/test/modules/testing-module.builder'; + +// 주문 커스텀 스냅샷 마이그레이션의 열 추가·백필·기본값 제거를 그대로 실행해 기존 문구·자유 편집이 새 모양으로 옮겨지는지 본다. +// 지워지는 crop_image_url과 기본값 없는 NOT NULL 열 때문에 최신 스키마에서는 옛 행을 만들 수 없어, +// 마이그레이션 직전 모양의 임시 표로 같은 이름을 가린 연결 하나에서 돌린다(임시 표는 세션 범위라 풀 연결로는 안 보인다). +const MIGRATIONS = join(__dirname, '../../../../prisma/migrations'); +const SQL = readFileSync( + join( + MIGRATIONS, + readdirSync(MIGRATIONS).find((d) => d.endsWith('_order_custom_snapshot'))!, + 'migration.sql', + ), + 'utf8', +); + +const STATEMENTS = SQL.split(';') + .map((stmt) => stmt.replace(/^\s*--[^\n]*$/gm, '').trim()) + .filter((stmt) => stmt.length > 0); +/** 기존 행에 닿는 문장(열 추가 → 백필 → 기본값 제거). 새 표 생성·FK는 빈 표라 제외한다. */ +const DATA_STEPS = STATEMENTS.slice( + 0, + STATEMENTS.findIndex((stmt) => stmt.startsWith('CREATE TABLE')), +); + +const LEGACY_SHAPES: Array<[table: string, alter: string]> = [ + [ + 'order_item', + 'DROP COLUMN `custom_mode_snapshot`, DROP COLUMN `custom_base_image_url_snapshot`, DROP COLUMN `custom_preview_image_url`', + ], + [ + 'order_item_custom_text', + 'DROP COLUMN `token_id`, DROP COLUMN `label_snapshot`, DROP COLUMN `pos_x`, DROP COLUMN `pos_y`, DROP COLUMN `width`, DROP COLUMN `height`, DROP COLUMN `text_color`, DROP COLUMN `text_align`, MODIFY `value_text` VARCHAR(200) NOT NULL', + ], + [ + 'order_item_custom_free_edit', + 'DROP COLUMN `pos_x`, DROP COLUMN `pos_y`, DROP COLUMN `width`, DROP COLUMN `height`, ADD COLUMN `crop_image_url` VARCHAR(2048) NOT NULL', + ], +]; + +describe('주문 커스텀 스냅샷 마이그레이션 (real DB)', () => { + let conn: mysql.Connection; + + beforeAll(async () => { + await createTestingModuleWithRealDb({ providers: [] }); + }); + afterAll(async () => { + await closeTruncateConnection(); + await disconnectTestPrismaClient(); + }); + // 행은 전부 연결이 닫히면 사라지는 임시 표에만 쓴다 + beforeEach(async () => { + conn = await mysql.createConnection({ uri: getTestDatabaseUrl() }); + for (const [table, alter] of LEGACY_SHAPES) { + // 같은 이름을 LIKE로 바로 만들 수 없어 사본을 거친다 + await conn.query( + `CREATE TEMPORARY TABLE \`_legacy_${table}\` LIKE \`${table}\``, + ); + await conn.query( + `CREATE TEMPORARY TABLE \`${table}\` LIKE \`_legacy_${table}\``, + ); + // 가림이 안 된 채 ALTER가 진짜 표에 닿지 않게 먼저 확인한다 + expect(await showCreate(table)).toMatch(/^CREATE TEMPORARY TABLE/); + await conn.query(`ALTER TABLE \`${table}\` ${alter}`); + } + }); + afterEach(async () => { + await conn.end(); + }); + + async function showCreate(table: string): Promise { + const [[row]] = await conn.query( + `SHOW CREATE TABLE \`${table}\``, + ); + return String(row['Create Table']); + } + + async function insert( + table: string, + row: Record, + ): Promise { + const columns = Object.keys(row); + const [result] = await conn.query( + `INSERT INTO \`${table}\` (${columns.join(', ')}, updated_at) VALUES (${columns.map(() => '?').join(', ')}, NOW(3))`, + Object.values(row), + ); + return result.insertId; + } + + const insertItem = () => + insert('order_item', { + order_id: 1, + store_id: 1, + product_id: 1, + product_name_snapshot: '케이크', + regular_price_snapshot: 10000, + store_name_snapshot: '매장', + }); + const insertText = (orderItemId: number, key: string, deleted = false) => + insert('order_item_custom_text', { + order_item_id: orderItemId, + token_key_snapshot: key, + default_text_snapshot: '기본', + value_text: '입력', + deleted_at: deleted ? new Date() : null, + }); + const insertFreeEdit = (orderItemId: number, deleted = false) => + insert('order_item_custom_free_edit', { + order_item_id: orderItemId, + crop_image_url: 'https://img/crop.png', + description_text: '요청', + deleted_at: deleted ? new Date() : null, + }); + + async function runMigration(): Promise { + expect(DATA_STEPS).toHaveLength(7); + for (const stmt of DATA_STEPS) await conn.query(stmt); + } + + it('문구는 키 앞 30자 표시 이름·바탕 전체 영역·검정·가운데로, 자유 편집은 바탕 전체 영역으로 옮기고 크롭을 지운다', async () => { + const item = await insertItem(); + const keys = ['message', 'k'.repeat(40), '한'.repeat(40)]; + for (const key of keys) await insertText(item, key); + await insertFreeEdit(item); + + await runMigration(); + + const [texts] = await conn.query( + 'SELECT label_snapshot, value_text, token_id, pos_x, pos_y, width, height, text_color, text_align FROM order_item_custom_text ORDER BY id', + ); + expect(texts).toEqual( + ['message', 'k'.repeat(30), '한'.repeat(30)].map((label) => ({ + label_snapshot: label, + value_text: '입력', + token_id: null, + pos_x: 0, + pos_y: 0, + width: 10000, + height: 10000, + text_color: '#000000', + text_align: 'CENTER', + })), + ); + const [edits] = await conn.query( + 'SELECT pos_x, pos_y, width, height FROM order_item_custom_free_edit', + ); + expect(edits).toEqual([ + { pos_x: 0, pos_y: 0, width: 10000, height: 10000 }, + ]); + }); + + it('기본값을 지워 새 행은 좌표·스타일을 모두 받아야 하고, 선택 자리를 지운 문구는 null로 둘 수 있다', async () => { + await runMigration(); + + const text = await showCreate('order_item_custom_text'); + for (const column of ['pos_x', 'pos_y', 'width', 'height']) { + expect(text).toContain(`\`${column}\` int NOT NULL,`); + } + expect(text).toMatch(/`label_snapshot` varchar\(30\)[^,]* NOT NULL,/); + expect(text).toMatch(/`text_color` char\(7\)[^,]* NOT NULL,/); + expect(text).toMatch(/`text_align` enum\([^)]*\)[^,]* NOT NULL,/); + expect(text).toMatch(/`value_text` varchar\(200\)[^,]* DEFAULT NULL,/); + const edit = await showCreate('order_item_custom_free_edit'); + expect(edit).not.toContain('crop_image_url'); + for (const column of ['pos_x', 'pos_y', 'width', 'height']) { + expect(edit).toContain(`\`${column}\` int NOT NULL,`); + } + }); + + it('살아 있는 문구나 자유 편집이 있는 품목만 슬롯형이 된다', async () => { + const withText = await insertItem(); + await insertText(withText, 'a'); + const withFreeEdit = await insertItem(); + await insertFreeEdit(withFreeEdit); + const deletedOnly = await insertItem(); + await insertText(deletedOnly, 'b', true); + await insertFreeEdit(deletedOnly, true); + const bare = await insertItem(); + + await runMigration(); + + const [rows] = await conn.query( + 'SELECT id, custom_mode_snapshot, custom_base_image_url_snapshot, custom_preview_image_url FROM order_item ORDER BY id', + ); + expect(rows).toEqual( + [ + [withText, 'SLOT'], + [withFreeEdit, 'SLOT'], + [deletedOnly, 'NONE'], + [bare, 'NONE'], + ].map(([id, mode]) => ({ + id, + custom_mode_snapshot: mode, + custom_base_image_url_snapshot: null, + custom_preview_image_url: null, + })), + ); + }); +}); diff --git a/src/features/order/repositories/order.repository.ts b/src/features/order/repositories/order.repository.ts index f456a930..74e6df1f 100644 --- a/src/features/order/repositories/order.repository.ts +++ b/src/features/order/repositories/order.repository.ts @@ -50,6 +50,21 @@ const sellerVisibleWhere = { submitted_at: { not: null }, } satisfies Prisma.OrderWhereInput; +/** 주문 상세 3곳(구매자·판매자·관리자)의 커스텀 스냅샷. 디자인·이미지는 deleted_at이 없어 부모 품목 가시성을 따른다 */ +const orderItemCustomInclude = { + custom_design: { select: { schema_version: true, design_json: true } }, + // enum 선언 순서(3D 윗면·앞·뒤·좌·우, 슬롯형 합성) + custom_images: { orderBy: { kind: 'asc' } }, + custom_texts: { where: activeWhere, orderBy: { sort_order: 'asc' } }, + free_edits: { + where: activeWhere, + orderBy: { sort_order: 'asc' }, + include: { + attachments: { where: activeWhere, orderBy: { sort_order: 'asc' } }, + }, + }, +} satisfies Prisma.OrderItemInclude; + export const adminOrderInclude = { items: { where: activeWhere, @@ -58,6 +73,8 @@ export const adminOrderInclude = { store_name_snapshot: true, product_name_snapshot: true, product_thumbnail_url_snapshot: true, + custom_mode_snapshot: true, + custom_preview_image_url: true, }, orderBy: { id: 'asc' }, take: 1, @@ -72,6 +89,8 @@ function sellerOrderSummaryInclude(storeId: bigint) { select: { product_name_snapshot: true, product_thumbnail_url_snapshot: true, + custom_mode_snapshot: true, + custom_preview_image_url: true, }, orderBy: { id: 'asc' }, take: 1, @@ -96,14 +115,7 @@ const adminOrderDetailInclude = { orderBy: { id: 'asc' }, include: { option_items: { where: activeWhere }, - custom_texts: { where: activeWhere, orderBy: { sort_order: 'asc' } }, - free_edits: { - where: activeWhere, - orderBy: { sort_order: 'asc' }, - include: { - attachments: { where: activeWhere, orderBy: { sort_order: 'asc' } }, - }, - }, + ...orderItemCustomInclude, }, }, } satisfies Prisma.OrderInclude; @@ -667,20 +679,7 @@ export class OrderRepository { where: activeWhere, orderBy: { id: 'asc' }, }, - custom_texts: { - where: activeWhere, - orderBy: { sort_order: 'asc' }, - }, - free_edits: { - where: activeWhere, - orderBy: { sort_order: 'asc' }, - include: { - attachments: { - where: activeWhere, - orderBy: { sort_order: 'asc' }, - }, - }, - }, + ...orderItemCustomInclude, review: { select: { id: true, deleted_at: true }, }, @@ -864,20 +863,7 @@ export class OrderRepository { }, include: { option_items: { where: activeWhere }, - custom_texts: { - where: activeWhere, - orderBy: { sort_order: 'asc' }, - }, - free_edits: { - where: activeWhere, - orderBy: { sort_order: 'asc' }, - include: { - attachments: { - where: activeWhere, - orderBy: { sort_order: 'asc' }, - }, - }, - }, + ...orderItemCustomInclude, }, }, }, diff --git a/src/features/order/services/order-admin-mappers.helper.ts b/src/features/order/services/order-admin-mappers.helper.ts index 0ac20253..c709b692 100644 --- a/src/features/order/services/order-admin-mappers.helper.ts +++ b/src/features/order/services/order-admin-mappers.helper.ts @@ -7,6 +7,7 @@ import { toOrderCancellation, toOrderItemDetail, toOrderRefund, + toOrderListCustomBadge, toOrderStatusHistory, } from '@/features/order/services/order-output-mappers.helper'; import { toAdminOrderPaymentOutput } from '@/features/order/services/order-payment-mappers.helper'; @@ -34,6 +35,7 @@ export function toAdminOrderSummaryOutput( createdAt: row.created_at, firstItemName: row.items[0]?.product_name_snapshot ?? null, firstItemImageUrl: row.items[0]?.product_thumbnail_url_snapshot ?? null, + ...toOrderListCustomBadge(row.items[0]), }; } diff --git a/src/features/order/services/order-admin.service.spec.ts b/src/features/order/services/order-admin.service.spec.ts index 491215a8..fdb40610 100644 --- a/src/features/order/services/order-admin.service.spec.ts +++ b/src/features/order/services/order-admin.service.spec.ts @@ -25,6 +25,7 @@ import { createOrderItem, createPayment, createStore, + createThreeDOrderItemCustom, createUserProfile, } from '@/test/factories'; import { createTestingModuleWithRealDb } from '@/test/modules/testing-module.builder'; @@ -247,8 +248,43 @@ describe('AdminOrderService (real DB)', () => { storeName: null, firstItemName: null, firstItemImageUrl: null, + hasCustom: false, + firstItemCustomImageUrl: null, }); }); + + it('커스텀 첫 품목이면 목록에 배지·대표 이미지를, 상세에 렌더·디자인을 싣는다', async () => { + const order = await createOrder(prisma); + const item = await createOrderItem(prisma, { + order_id: order.id, + custom_mode_snapshot: 'THREE_D', + custom_preview_image_url: 'https://img/THREE_D_TOP.png', + }); + await createThreeDOrderItemCustom(prisma, item.id); + const plain = await createOrder(prisma); + await createOrderItem(prisma, { order_id: plain.id }); + const adminId = await admin(); + + const list = await service.adminOrders(adminId); + const byId = new Map(list.items.map((o) => [o.id, o])); + expect(byId.get(order.id.toString())).toMatchObject({ + hasCustom: true, + firstItemCustomImageUrl: 'https://img/THREE_D_TOP.png', + }); + expect(byId.get(plain.id.toString())).toMatchObject({ + hasCustom: false, + firstItemCustomImageUrl: null, + }); + const [detail] = (await service.adminOrder(adminId, order.id)).items; + expect(detail.customImages.map((i) => i.kind)).toEqual([ + 'THREE_D_TOP', + 'THREE_D_FRONT', + 'THREE_D_BACK', + 'THREE_D_LEFT', + 'THREE_D_RIGHT', + ]); + expect(detail.threeDDesign?.schemaVersion).toBe(1); + }); }); describe('adminOrders inProgress', () => { @@ -861,6 +897,7 @@ describe('AdminOrderService (real DB)', () => { buyerName: order.buyer_name, totalPrice: order.total_price, productName: 'Product snapshot', + hasCustom: false, updatedAt: row.updated_at.toISOString(), }, ]); diff --git a/src/features/order/services/order-custom-design.helper.spec.ts b/src/features/order/services/order-custom-design.helper.spec.ts new file mode 100644 index 00000000..ba489f0f --- /dev/null +++ b/src/features/order/services/order-custom-design.helper.spec.ts @@ -0,0 +1,126 @@ +import { Logger } from '@nestjs/common'; + +import { readStoredThreeDDesign } from '@/features/order/services/order-custom-design.helper'; +import type { Prisma } from '@/generated/prisma/client'; + +const TEXT = { + kind: 'TEXT', + x: 0.5, + y: 0.25, + size: 12, + effect: { type: 'soft', intensity: 50 }, + text: '생일\n축하해 🎂', + color: '#1D1D1D', +}; +const DECO = { + kind: 'DECO', + x: 0.1, + y: 0.9, + size: 20, + effect: { type: 'none', intensity: 0 }, + decoId: 'number-3', +}; +const DESIGN = { + schemaVersion: 1, + basic: { + shape: 'circle', + size: 'no1', + design: 'wave', + flavor: null, + sheetColor: 'pink', + }, + top: [TEXT, DECO], + side: [DECO], +}; + +const read = (design_json: unknown, schema_version = 1) => + readStoredThreeDDesign(42n, { + schema_version, + design_json: design_json as Prisma.JsonValue, + }); + +type Node = Record; + +/** DESIGN을 깊은 복사한 뒤 path 위치 값을 바꾼다. undefined면 그 키를 지운다. */ +function patched(path: (string | number)[], value: unknown): unknown { + const copy = structuredClone(DESIGN) as unknown as Node; + const parent = path + .slice(0, -1) + .reduce((node, key) => node[key] as Node, copy); + const last = path[path.length - 1]; + if (value === undefined) delete parent[last]; + else parent[last] = value; + return copy; +} + +describe('readStoredThreeDDesign', () => { + let warn: jest.SpyInstance; + beforeEach(() => { + warn = jest.spyOn(Logger.prototype, 'warn').mockImplementation(() => {}); + }); + afterEach(() => jest.restoreAllMocks()); + + it('저장된 v1 디자인을 그대로 읽고 항목 종류에 없는 칸은 null로 채운다', () => { + expect(read(DESIGN)).toEqual({ + ...DESIGN, + top: [ + { ...TEXT, decoId: null }, + { ...DECO, text: null, color: null }, + ], + side: [{ ...DECO, text: null, color: null }], + }); + expect(warn).not.toHaveBeenCalled(); + }); + + it('디자인·맛 키가 빠져 있으면 null로 읽는다', () => { + const noFlavor = patched(['basic', 'flavor'], undefined) as Node; + delete (noFlavor.basic as Node).design; + expect(read(noFlavor)?.basic).toMatchObject({ design: null, flavor: null }); + }); + + it('디자인 행이 없으면 기록 없이 null이다', () => { + expect(readStoredThreeDDesign(1n, null)).toBeNull(); + expect(warn).not.toHaveBeenCalled(); + }); + + it('지원하지 않는 컬럼 버전이면 null + 기록', () => { + expect(read(DESIGN, 2)).toBeNull(); + expect(warn).toHaveBeenCalledWith( + expect.stringContaining('orderItemId=42'), + ); + }); + + // 콜백 인자 수가 행 길이보다 많으면 jest가 마지막 인자를 done으로 본다 — 행과 인자 수를 맞춘다 + it.each<[string, unknown]>([ + ['JSON 버전이 컬럼과 다름', patched(['schemaVersion'], 2)], + ['JSON이 객체가 아님', [DESIGN]], + ['JSON이 null', null], + ['basic 없음', patched(['basic'], undefined)], + ['shape가 문자열이 아님', patched(['basic', 'shape'], 3)], + ['size 없음', patched(['basic', 'size'], undefined)], + ['sheetColor 없음', patched(['basic', 'sheetColor'], undefined)], + ['design이 문자열·null이 아님', patched(['basic', 'design'], 1)], + ['flavor가 문자열·null이 아님', patched(['basic', 'flavor'], {})], + ['top이 배열이 아님', patched(['top'], {})], + ['side 없음', patched(['side'], undefined)], + ['항목이 객체가 아님', patched(['top', 0], 'TEXT')], + ['모르는 항목 종류', patched(['top', 0, 'kind'], 'IMAGE')], + ['x가 수가 아님', patched(['top', 0, 'x'], '0.5')], + ['y 없음', patched(['side', 0, 'y'], undefined)], + ['size가 유한수가 아님', patched(['top', 1, 'size'], null)], + ['effect 없음', patched(['top', 0, 'effect'], undefined)], + ['effect.type이 문자열이 아님', patched(['top', 0, 'effect', 'type'], 1)], + [ + 'effect.intensity가 정수가 아님', + patched(['top', 0, 'effect', 'intensity'], 0.5), + ], + ['글자에 text 없음', patched(['top', 0, 'text'], undefined)], + ['글자에 color 없음', patched(['top', 0, 'color'], undefined)], + ['꾸미기에 decoId 없음', patched(['side', 0, 'decoId'], undefined)], + ])('%s → null + 기록', (_case, json) => { + expect(read(json)).toBeNull(); + expect(warn).toHaveBeenCalledWith( + expect.stringContaining('orderItemId=42'), + ); + }); +}); diff --git a/src/features/order/services/order-custom-design.helper.ts b/src/features/order/services/order-custom-design.helper.ts new file mode 100644 index 00000000..5ad04c8a --- /dev/null +++ b/src/features/order/services/order-custom-design.helper.ts @@ -0,0 +1,109 @@ +import { Logger } from '@nestjs/common'; + +import type { + ThreeDDesignItemOutput, + ThreeDDesignOutput, +} from '@/features/order/types/order-output.type'; +import { THREE_D_DESIGN_SCHEMA_VERSION } from '@/features/product'; +import type { Prisma } from '@/generated/prisma/client'; + +const logger = new Logger('OrderCustomDesign'); + +type JsonObject = { [key: string]: Prisma.JsonValue | undefined }; + +const isObject = (v: unknown): v is JsonObject => + v !== null && typeof v === 'object' && !Array.isArray(v); +const isString = (v: unknown): v is string => typeof v === 'string'; +const isNumber = (v: unknown): v is number => + typeof v === 'number' && Number.isFinite(v); +const isInteger = (v: unknown): v is number => Number.isInteger(v); +const nullableString = (v: unknown): string | null | undefined => + v === null || v === undefined ? null : isString(v) ? v : undefined; + +function parseItem(v: unknown): ThreeDDesignItemOutput | null { + if ( + !isObject(v) || + !isNumber(v.x) || + !isNumber(v.y) || + !isNumber(v.size) || + !isObject(v.effect) || + !isString(v.effect.type) || + !isInteger(v.effect.intensity) + ) + return null; + const base = { + x: v.x, + y: v.y, + size: v.size, + effect: { type: v.effect.type, intensity: v.effect.intensity }, + }; + if (v.kind === 'TEXT' && isString(v.text) && isString(v.color)) + return { + kind: 'TEXT', + ...base, + text: v.text, + color: v.color, + decoId: null, + }; + if (v.kind === 'DECO' && isString(v.decoId)) + return { kind: 'DECO', ...base, text: null, color: null, decoId: v.decoId }; + return null; +} + +function parseItems(v: unknown): ThreeDDesignItemOutput[] | null { + if (!Array.isArray(v)) return null; + const items = v.map(parseItem); + return items.every((item) => item !== null) ? items : null; +} + +function parseDesign( + schemaVersion: number, + json: Prisma.JsonValue, +): ThreeDDesignOutput | null { + if ( + schemaVersion !== THREE_D_DESIGN_SCHEMA_VERSION || + !isObject(json) || + json.schemaVersion !== schemaVersion || + !isObject(json.basic) + ) + return null; + const { shape, size, sheetColor } = json.basic; + const design = nullableString(json.basic.design); + const flavor = nullableString(json.basic.flavor); + const top = parseItems(json.top); + const side = parseItems(json.side); + if ( + !isString(shape) || + !isString(size) || + !isString(sheetColor) || + design === undefined || + flavor === undefined || + !top || + !side + ) + return null; + return { + schemaVersion, + basic: { shape, size, design, flavor, sheetColor }, + top, + side, + }; +} + +/** + * 저장된 3D 디자인을 출력 형태로 읽는다. 저장 전 검증을 거친 값이지만 버전·형태가 어긋나면 + * 상세 전체를 실패시키지 않고 디자인만 null로 내리고 기록을 남긴다. + */ +export function readStoredThreeDDesign( + orderItemId: bigint, + row: { schema_version: number; design_json: Prisma.JsonValue } | null, +): ThreeDDesignOutput | null { + if (!row) return null; + const design = parseDesign(row.schema_version, row.design_json); + if (!design) { + logger.warn( + `주문 3D 디자인을 읽을 수 없음 (orderItemId=${orderItemId}, schemaVersion=${row.schema_version})`, + ); + } + return design; +} diff --git a/src/features/order/services/order-deposit-admin.service.spec.ts b/src/features/order/services/order-deposit-admin.service.spec.ts index b1917095..8b460c15 100644 --- a/src/features/order/services/order-deposit-admin.service.spec.ts +++ b/src/features/order/services/order-deposit-admin.service.spec.ts @@ -249,6 +249,7 @@ describe('AdminDepositService (real DB)', () => { orderId: order.id.toString(), status: 'SUBMITTED', productName: '딸기 케이크', + hasCustom: false, }), ]); topic.stop(); diff --git a/src/features/order/services/order-deposit-admin.service.ts b/src/features/order/services/order-deposit-admin.service.ts index 29a68b1c..33f1eeb2 100644 --- a/src/features/order/services/order-deposit-admin.service.ts +++ b/src/features/order/services/order-deposit-admin.service.ts @@ -126,11 +126,7 @@ export class AdminDepositService extends AdminBaseService { if (firstItem) { await this.events.publishSellerOrderUpdate( firstItem.store_id, - toSellerOrderUpdateEvent( - 'SUBMITTED', - updated, - firstItem.product_name_snapshot, - ), + toSellerOrderUpdateEvent('SUBMITTED', updated), ); } return toAdminOrderSummaryOutput(updated); diff --git a/src/features/order/services/order-events-mappers.helper.ts b/src/features/order/services/order-events-mappers.helper.ts index 9658d712..1719d935 100644 --- a/src/features/order/services/order-events-mappers.helper.ts +++ b/src/features/order/services/order-events-mappers.helper.ts @@ -1,8 +1,9 @@ +import { isCustomOrderItem } from '@/features/order/services/order-output-mappers.helper'; import type { SellerOrderUpdateEvent, SellerOrderUpdateKind, } from '@/features/order/types/order-seller-output.type'; -import type { Order } from '@/generated/prisma/client'; +import type { Order, OrderItem } from '@/generated/prisma/client'; export type SellerOrderUpdateRow = Pick< Order, @@ -13,13 +14,16 @@ export type SellerOrderUpdateRow = Pick< | 'buyer_name' | 'total_price' | 'updated_at' ->; +> & { + /** 첫 품목이 상품명·커스텀 여부를 정한다 */ + items: Pick[]; +}; export function toSellerOrderUpdateEvent( kind: SellerOrderUpdateKind, row: SellerOrderUpdateRow, - productName: string, ): SellerOrderUpdateEvent { + const [firstItem] = row.items; return { kind, orderId: row.id.toString(), @@ -28,7 +32,8 @@ export function toSellerOrderUpdateEvent( pickupAt: row.pickup_at.toISOString(), buyerName: row.buyer_name, totalPrice: row.total_price, - productName, + productName: firstItem?.product_name_snapshot ?? '', + hasCustom: isCustomOrderItem(firstItem), updatedAt: row.updated_at.toISOString(), }; } diff --git a/src/features/order/services/order-events.service.spec.ts b/src/features/order/services/order-events.service.spec.ts index 789e3cbe..827a6163 100644 --- a/src/features/order/services/order-events.service.spec.ts +++ b/src/features/order/services/order-events.service.spec.ts @@ -19,6 +19,7 @@ const EVENT: SellerOrderUpdateEvent = { buyerName: '차차', totalPrice: 56000, productName: '딸기 케이크', + hasCustom: false, updatedAt: '2026-09-16T07:00:00.000Z', }; diff --git a/src/features/order/services/order-events.service.ts b/src/features/order/services/order-events.service.ts index 3f8ce31a..73d0f407 100644 --- a/src/features/order/services/order-events.service.ts +++ b/src/features/order/services/order-events.service.ts @@ -46,11 +46,7 @@ export class OrderEventsService { if (!firstItem || !row.submitted_at) return; await this.publishSellerOrderUpdate( firstItem.store_id, - toSellerOrderUpdateEvent( - 'STATUS_CHANGED', - row, - firstItem.product_name_snapshot, - ), + toSellerOrderUpdateEvent('STATUS_CHANGED', row), ); } diff --git a/src/features/order/services/order-my.service.spec.ts b/src/features/order/services/order-my.service.spec.ts index 1470ef2a..3287767e 100644 --- a/src/features/order/services/order-my.service.spec.ts +++ b/src/features/order/services/order-my.service.spec.ts @@ -1,3 +1,4 @@ +import { Logger } from '@nestjs/common'; import { PubSub } from 'graphql-subscriptions'; import { ClockService } from '@/common/providers/clock.service'; @@ -27,7 +28,9 @@ import { createProduct, createReview, createStore, + createThreeDOrderItemCustom, createUserProfile, + MINIMAL_THREE_D_DESIGN, } from '@/test/factories'; import { createTestingModuleWithRealDb } from '@/test/modules/testing-module.builder'; import { outboxPublisherProviders } from '@/test/outbox'; @@ -441,6 +444,113 @@ describe('UserOrderService (real DB)', () => { }); }); + it('커스텀 스냅샷(방식·대표·바탕 이미지·렌더 종류 순·3D 디자인·문구·자유 편집 영역)을 상세에 싣는다', async () => { + const account = await setupUser(); + const order = await createOrder(prisma, { account_id: account.id }); + const item = await createOrderItem(prisma, { + order_id: order.id, + custom_mode_snapshot: 'THREE_D', + custom_preview_image_url: 'https://img/THREE_D_TOP.png', + }); + await createThreeDOrderItemCustom(prisma, item.id); + const slot = await createOrderItem(prisma, { + order_id: order.id, + custom_mode_snapshot: 'SLOT', + custom_base_image_url_snapshot: 'https://img/base.png', + custom_preview_image_url: 'https://img/composite.png', + }); + await prisma.orderItemCustomText.create({ + data: { + order_item_id: slot.id, + token_id: 77n, + token_key_snapshot: 'top', + label_snapshot: '윗줄', + default_text_snapshot: '축하해', + value_text: null, + pos_x: 1000, + pos_y: 1000, + width: 8000, + height: 1500, + text_color: '#1D1D1D', + text_align: 'RIGHT', + }, + }); + await prisma.orderItemCustomFreeEdit.create({ + data: { + order_item_id: slot.id, + pos_x: 2000, + pos_y: 4000, + width: 6000, + height: 4000, + description_text: '여기에 그림', + }, + }); + + const result = await service.getMyOrder(account.id, order.id); + + const [threeD, slotItem] = result.items.map((i) => i.item); + expect(threeD).toMatchObject({ + customMode: 'THREE_D', + customPreviewImageUrl: 'https://img/THREE_D_TOP.png', + customBaseImageUrl: null, + threeDDesign: MINIMAL_THREE_D_DESIGN, + customTexts: [], + freeEdits: [], + }); + expect(threeD.customImages.map((i) => i.kind)).toEqual([ + 'THREE_D_TOP', + 'THREE_D_FRONT', + 'THREE_D_BACK', + 'THREE_D_LEFT', + 'THREE_D_RIGHT', + ]); + expect(slotItem).toMatchObject({ + customMode: 'SLOT', + customPreviewImageUrl: 'https://img/composite.png', + customBaseImageUrl: 'https://img/base.png', + customImages: [], + threeDDesign: null, + customTexts: [ + { + tokenId: '77', + label: '윗줄', + valueText: null, + posX: 1000, + posY: 1000, + width: 8000, + height: 1500, + textColor: '#1D1D1D', + textAlign: 'RIGHT', + }, + ], + freeEdits: [ + { + posX: 2000, + posY: 4000, + width: 6000, + height: 4000, + descriptionText: '여기에 그림', + }, + ], + }); + }); + + it('저장된 3D 디자인을 읽을 수 없으면 디자인만 null이고 상세는 내려간다', async () => { + const account = await setupUser(); + const order = await createOrder(prisma, { account_id: account.id }); + const item = await createOrderItem(prisma, { + order_id: order.id, + custom_mode_snapshot: 'THREE_D', + }); + await createThreeDOrderItemCustom(prisma, item.id, { schemaVersion: 1 }); + jest.spyOn(Logger.prototype, 'warn').mockImplementation(() => undefined); + + const result = await service.getMyOrder(account.id, order.id); + + expect(result.items[0].item.threeDDesign).toBeNull(); + expect(result.items[0].item.customImages).toHaveLength(5); + }); + it('존재하지 않는 orderId면 404', async () => { const account = await setupUser(); await expect( diff --git a/src/features/order/services/order-output-mappers.helper.spec.ts b/src/features/order/services/order-output-mappers.helper.spec.ts index 3b725544..c8d37f72 100644 --- a/src/features/order/services/order-output-mappers.helper.spec.ts +++ b/src/features/order/services/order-output-mappers.helper.spec.ts @@ -2,6 +2,7 @@ import { toOrderCancellation, toOrderItemDetail, toOrderItemFreeEdit, + toOrderListCustomBadge, toOrderRefund, toOrderStatusHistory, type OrderItemDetailRow, @@ -9,6 +10,8 @@ import { } from '@/features/order/services/order-output-mappers.helper'; import type { Refund } from '@/generated/prisma/client'; +const AREA = { pos_x: 1000, pos_y: 2000, width: 8000, height: 1500 }; + function itemRow(o: Partial = {}): OrderItemDetailRow { return { id: 10n, @@ -27,19 +30,31 @@ function itemRow(o: Partial = {}): OrderItemDetailRow { option_price_delta_snapshot: 1000, }, ], + custom_mode_snapshot: 'SLOT', + custom_base_image_url_snapshot: 'base.png', + custom_preview_image_url: 'composite.png', + custom_design: null, + custom_images: [ + { id: 500n, kind: 'SLOT_COMPOSITE', image_url: 'composite.png' }, + ], custom_texts: [ { id: 200n, - token_key_snapshot: 'TOP', + token_id: 7n, + token_key_snapshot: 'top', + label_snapshot: '윗줄', default_text_snapshot: '축하해', value_text: '생일 축하해', + ...AREA, + text_color: '#1D1D1D', + text_align: 'LEFT', sort_order: 0, }, ], free_edits: [ { id: 300n, - crop_image_url: 'crop.png', + ...AREA, description_text: '여기 하트', sort_order: 0, attachments: [{ id: 400n, image_url: 'ref.png', sort_order: 0 }], @@ -63,19 +78,37 @@ describe('order-output-mappers', () => { optionItems: [ { id: '100', groupName: '크기', optionTitle: '2호', priceDelta: 1000 }, ], + customMode: 'SLOT', + customPreviewImageUrl: 'composite.png', + customBaseImageUrl: 'base.png', + customImages: [ + { id: '500', kind: 'SLOT_COMPOSITE', imageUrl: 'composite.png' }, + ], + threeDDesign: null, customTexts: [ { id: '200', - tokenKey: 'TOP', + tokenId: '7', + tokenKey: 'top', + label: '윗줄', defaultText: '축하해', valueText: '생일 축하해', + posX: 1000, + posY: 2000, + width: 8000, + height: 1500, + textColor: '#1D1D1D', + textAlign: 'LEFT', sortOrder: 0, }, ], freeEdits: [ { id: '300', - cropImageUrl: 'crop.png', + posX: 1000, + posY: 2000, + width: 8000, + height: 1500, descriptionText: '여기 하트', sortOrder: 0, attachments: [{ id: '400', imageUrl: 'ref.png', sortOrder: 0 }], @@ -99,18 +132,114 @@ describe('order-output-mappers', () => { expect(result.freeEdits).toEqual([]); }); + it('커스텀이 없는 품목은 NONE·이미지 없음·디자인 null이다', () => { + const result = toOrderItemDetail( + itemRow({ + custom_mode_snapshot: 'NONE', + custom_base_image_url_snapshot: null, + custom_preview_image_url: null, + custom_images: [], + custom_texts: [], + free_edits: [], + }), + ); + expect(result).toMatchObject({ + customMode: 'NONE', + customPreviewImageUrl: null, + customBaseImageUrl: null, + customImages: [], + threeDDesign: null, + }); + }); + + it('문구 자리 지정 전 문구는 tokenId null, 지운 선택 자리는 valueText null로 내린다', () => { + const [text] = toOrderItemDetail( + itemRow({ + custom_texts: [ + { + ...itemRow().custom_texts[0], + token_id: null, + value_text: null, + }, + ], + }), + ).customTexts; + expect(text).toMatchObject({ tokenId: null, valueText: null }); + }); + + it('3D 디자인은 저장된 JSON을 출력 형태로 읽는다', () => { + const design = { + schemaVersion: 1, + basic: { + shape: 'heart', + size: 'mini', + design: null, + flavor: 'choco', + sheetColor: 'white', + }, + top: [ + { + kind: 'TEXT', + x: 0.5, + y: 0.5, + size: 10, + effect: { type: 'none', intensity: 50 }, + text: '축하', + color: '#FFFFFF', + }, + ], + side: [], + }; + const result = toOrderItemDetail( + itemRow({ + custom_mode_snapshot: 'THREE_D', + custom_design: { schema_version: 1, design_json: design }, + }), + ); + expect(result.threeDDesign).toEqual({ + ...design, + top: [{ ...design.top[0], decoId: null }], + }); + }); + + it.each([ + ['NONE', null, { hasCustom: false, firstItemCustomImageUrl: null }], + ['SLOT', 'c.png', { hasCustom: true, firstItemCustomImageUrl: 'c.png' }], + ['THREE_D', 't.png', { hasCustom: true, firstItemCustomImageUrl: 't.png' }], + ] as const)('toOrderListCustomBadge: %s 품목 → %o', (mode, url, expected) => { + expect( + toOrderListCustomBadge({ + custom_mode_snapshot: mode, + custom_preview_image_url: url, + }), + ).toEqual(expected); + }); + + it('toOrderListCustomBadge: 품목이 없으면 배지 없음', () => { + expect(toOrderListCustomBadge(undefined)).toEqual({ + hasCustom: false, + firstItemCustomImageUrl: null, + }); + }); + it('toOrderItemFreeEdit: 첨부가 없으면 빈 배열', () => { expect( toOrderItemFreeEdit({ id: 1n, - crop_image_url: 'c.png', + pos_x: 0, + pos_y: 0, + width: 10000, + height: 10000, description_text: 'd', sort_order: 1, attachments: [], }), ).toEqual({ id: '1', - cropImageUrl: 'c.png', + posX: 0, + posY: 0, + width: 10000, + height: 10000, descriptionText: 'd', sortOrder: 1, attachments: [], diff --git a/src/features/order/services/order-output-mappers.helper.ts b/src/features/order/services/order-output-mappers.helper.ts index 8160ae54..b6720cd9 100644 --- a/src/features/order/services/order-output-mappers.helper.ts +++ b/src/features/order/services/order-output-mappers.helper.ts @@ -3,6 +3,7 @@ import { maskAccountNumber, toBank, } from '@/features/order/services/order-bank-account.helper'; +import { readStoredThreeDDesign } from '@/features/order/services/order-custom-design.helper'; import type { OrderCancellationOutput, OrderItemDetailOutput, @@ -14,15 +15,25 @@ import { OrderCancelReason, OrderStatus, RefundKind, + type CustomImageKind, + type CustomMode, + type CustomTextAlign, type OrderActor, type OrderCancelFault, + type Prisma, type Refund, } from '@/generated/prisma/client'; +interface CustomAreaRow { + pos_x: number; + pos_y: number; + width: number; + height: number; +} + /** 판매자·관리자·구매자 조회 row가 모두 만족하는 구조적 부분집합. */ -export interface OrderItemFreeEditRow { +export interface OrderItemFreeEditRow extends CustomAreaRow { id: bigint; - crop_image_url: string; description_text: string; sort_order: number; attachments: { id: bigint; image_url: string; sort_order: number }[]; @@ -43,16 +54,35 @@ export interface OrderItemDetailRow { option_title_snapshot: string; option_price_delta_snapshot: number; }[]; - custom_texts: { + custom_mode_snapshot: CustomMode; + custom_base_image_url_snapshot: string | null; + custom_preview_image_url: string | null; + custom_design: { + schema_version: number; + design_json: Prisma.JsonValue; + } | null; + custom_images: { id: bigint; kind: CustomImageKind; image_url: string }[]; + custom_texts: (CustomAreaRow & { id: bigint; + token_id: bigint | null; token_key_snapshot: string; + label_snapshot: string; default_text_snapshot: string; - value_text: string; + value_text: string | null; + text_color: string; + text_align: CustomTextAlign; sort_order: number; - }[]; + })[]; free_edits: OrderItemFreeEditRow[]; } +const toArea = (row: CustomAreaRow) => ({ + posX: row.pos_x, + posY: row.pos_y, + width: row.width, + height: row.height, +}); + export interface OrderStatusHistoryRow { id: bigint; from_status: OrderStatus | null; @@ -83,11 +113,25 @@ export function toOrderItemDetail( optionTitle: opt.option_title_snapshot, priceDelta: opt.option_price_delta_snapshot, })), + customMode: item.custom_mode_snapshot, + customPreviewImageUrl: item.custom_preview_image_url, + customBaseImageUrl: item.custom_base_image_url_snapshot, + customImages: item.custom_images.map((image) => ({ + id: image.id.toString(), + kind: image.kind, + imageUrl: image.image_url, + })), + threeDDesign: readStoredThreeDDesign(item.id, item.custom_design), customTexts: item.custom_texts.map((text) => ({ id: text.id.toString(), + tokenId: text.token_id?.toString() ?? null, tokenKey: text.token_key_snapshot, + label: text.label_snapshot, defaultText: text.default_text_snapshot, valueText: text.value_text, + ...toArea(text), + textColor: text.text_color, + textAlign: text.text_align, sortOrder: text.sort_order, })), freeEdits: item.free_edits.map(toOrderItemFreeEdit), @@ -99,7 +143,7 @@ export function toOrderItemFreeEdit( ): OrderItemFreeEditOutput { return { id: edit.id.toString(), - cropImageUrl: edit.crop_image_url, + ...toArea(edit), descriptionText: edit.description_text, sortOrder: edit.sort_order, attachments: edit.attachments.map((a) => ({ @@ -110,6 +154,25 @@ export function toOrderItemFreeEdit( }; } +/** 판매자·관리자 목록과 판매자 구독의 '커스텀' 배지. 주문은 단일 상품이라 첫 품목이 정한다 */ +export const isCustomOrderItem = ( + item: { custom_mode_snapshot: CustomMode } | undefined, +): boolean => item !== undefined && item.custom_mode_snapshot !== 'NONE'; + +export function toOrderListCustomBadge( + item: + | { + custom_mode_snapshot: CustomMode; + custom_preview_image_url: string | null; + } + | undefined, +): { hasCustom: boolean; firstItemCustomImageUrl: string | null } { + return { + hasCustom: isCustomOrderItem(item), + firstItemCustomImageUrl: item?.custom_preview_image_url ?? null, + }; +} + export function toOrderStatusHistory( history: OrderStatusHistoryRow, ): OrderStatusHistoryOutput { diff --git a/src/features/order/services/order-seller.service.spec.ts b/src/features/order/services/order-seller.service.spec.ts index 4f8faa9d..3b845e41 100644 --- a/src/features/order/services/order-seller.service.spec.ts +++ b/src/features/order/services/order-seller.service.spec.ts @@ -21,6 +21,7 @@ import { createOrderItem, createPayment, createProduct, + createThreeDOrderItemCustom, setupSellerWithStore, } from '@/test/factories'; import { createTestingModuleWithRealDb } from '@/test/modules/testing-module.builder'; @@ -192,6 +193,30 @@ describe('SellerOrderService (real DB)', () => { expect(result.items[0].firstItemName).toBe('활성 품목'); }); + it.each([ + ['3D', 'THREE_D', 'https://img/top.png', true], + ['슬롯형', 'SLOT', 'https://img/composite.png', true], + ['커스텀 없음', 'NONE', null, false], + ] as const)( + '%s 첫 품목이면 커스텀 배지·대표 이미지를 싣는다', + async (_case, mode, url, hasCustom) => { + const { account, store } = await setupSellerWithStore(prisma); + const order = await createOrder(prisma); + await createOrderItem(prisma, { + order_id: order.id, + store_id: store.id, + custom_mode_snapshot: mode, + custom_preview_image_url: url, + }); + + const result = await service.sellerOrderList(account.id); + expect(result.items[0]).toMatchObject({ + hasCustom, + firstItemCustomImageUrl: url, + }); + }, + ); + it('썸네일 스냅샷이 없으면 firstItemImageUrl은 null', async () => { const { account, store } = await setupSellerWithStore(prisma); const order = await createOrder(prisma); @@ -402,6 +427,28 @@ describe('SellerOrderService (real DB)', () => { }); }); + it('상세 품목에 렌더 이미지(종류 순)·3D 디자인을 싣는다', async () => { + const { account, store } = await setupSellerWithStore(prisma); + const order = await createOrder(prisma); + const item = await createOrderItem(prisma, { + order_id: order.id, + store_id: store.id, + custom_mode_snapshot: 'THREE_D', + }); + await createThreeDOrderItemCustom(prisma, item.id); + + const [detail] = (await service.sellerOrder(account.id, order.id)).items; + expect(detail.customMode).toBe('THREE_D'); + expect(detail.threeDDesign?.basic.shape).toBe('heart'); + expect(detail.customImages.map((i) => i.imageUrl)).toEqual([ + 'https://img/THREE_D_TOP.png', + 'https://img/THREE_D_FRONT.png', + 'https://img/THREE_D_BACK.png', + 'https://img/THREE_D_LEFT.png', + 'https://img/THREE_D_RIGHT.png', + ]); + }); + it('결제가 있으면 결제 수단을 준다', async () => { const { account, store } = await setupSellerWithStore(prisma); const order = await createStoreOrder(store.id, { status: 'SUBMITTED' }); @@ -884,13 +931,14 @@ describe('SellerOrderService (real DB)', () => { }); describe('sellerOrderUpdated 발행', () => { - it('상태 변경 시 매장 토픽에 1건 — 첫 품목 상품명과 갱신된 updated_at을 싣는다', async () => { + it('상태 변경 시 매장 토픽에 1건 — 첫 품목 상품명·커스텀 여부와 갱신된 updated_at을 싣는다', async () => { const { account, store } = await setupSellerWithStore(prisma); const order = await createOrder(prisma); await createOrderItem(prisma, { order_id: order.id, store_id: store.id, product_name_snapshot: '확정 품목', + custom_mode_snapshot: 'THREE_D', }); const topic = await collectTopic(pubSub, `order.seller.${store.id}`); @@ -913,6 +961,7 @@ describe('SellerOrderService (real DB)', () => { buyerName: order.buyer_name, totalPrice: order.total_price, productName: '확정 품목', + hasCustom: true, updatedAt: row.updated_at.toISOString(), }, ]); diff --git a/src/features/order/services/order-seller.service.ts b/src/features/order/services/order-seller.service.ts index 1f0cc40d..c35276d1 100644 --- a/src/features/order/services/order-seller.service.ts +++ b/src/features/order/services/order-seller.service.ts @@ -31,6 +31,7 @@ import { OrderEventsService } from '@/features/order/services/order-events.servi import { toOrderCancellation, toOrderItemDetail, + toOrderListCustomBadge, toOrderStatusHistory, type OrderItemDetailRow, type OrderStatusHistoryRow, @@ -147,11 +148,7 @@ export class SellerOrderService extends SellerBaseService { await this.events.publishSellerOrderUpdate( ctx.storeId, - toSellerOrderUpdateEvent( - 'STATUS_CHANGED', - updated, - updated.items[0]?.product_name_snapshot ?? '', - ), + toSellerOrderUpdateEvent('STATUS_CHANGED', updated), ); return this.toOrderSummaryOutput(updated); } @@ -198,6 +195,7 @@ export class SellerOrderService extends SellerBaseService { // 내 매장 첫 품목의 주문 시점 스냅샷 — 상품이 바뀌어도 카드 값은 유지된다 firstItemName: row.items[0]?.product_name_snapshot ?? null, firstItemImageUrl: row.items[0]?.product_thumbnail_url_snapshot ?? null, + ...toOrderListCustomBadge(row.items[0]), }; } diff --git a/src/features/order/services/order-subscription.service.spec.ts b/src/features/order/services/order-subscription.service.spec.ts index e5682d86..7b9e623a 100644 --- a/src/features/order/services/order-subscription.service.spec.ts +++ b/src/features/order/services/order-subscription.service.spec.ts @@ -61,6 +61,7 @@ describe('OrderSubscriptionService (real DB)', () => { buyerName: '차차', totalPrice: 10000, productName: '케이크', + hasCustom: false, updatedAt: '2026-09-16T07:00:00.000Z', }; diff --git a/src/features/order/types/order-admin-output.type.ts b/src/features/order/types/order-admin-output.type.ts index 8a761303..96f5be36 100644 --- a/src/features/order/types/order-admin-output.type.ts +++ b/src/features/order/types/order-admin-output.type.ts @@ -26,6 +26,8 @@ export interface AdminOrderSummaryOutput { createdAt: Date; firstItemName: string | null; firstItemImageUrl: string | null; + hasCustom: boolean; + firstItemCustomImageUrl: string | null; } export interface AdminStoreInProgressOrderSummaryOutput { diff --git a/src/features/order/types/order-output.type.ts b/src/features/order/types/order-output.type.ts index 922fb59e..cfba822c 100644 --- a/src/features/order/types/order-output.type.ts +++ b/src/features/order/types/order-output.type.ts @@ -1,5 +1,8 @@ import type { BankOutput } from '@/features/order/types/order-payment-output.type'; import type { + CustomImageKind, + CustomMode, + CustomTextAlign, OrderActor, OrderCancelFault, OrderCancelReason, @@ -15,11 +18,22 @@ export interface OrderItemOptionOutput { priceDelta: number; } -export interface OrderItemCustomTextOutput { +export interface OrderCustomAreaOutput { + posX: number; + posY: number; + width: number; + height: number; +} + +export interface OrderItemCustomTextOutput extends OrderCustomAreaOutput { id: string; + tokenId: string | null; tokenKey: string; + label: string; defaultText: string; - valueText: string; + valueText: string | null; + textColor: string; + textAlign: CustomTextAlign; sortOrder: number; } @@ -29,14 +43,43 @@ export interface OrderItemFreeEditAttachmentOutput { sortOrder: number; } -export interface OrderItemFreeEditOutput { +export interface OrderItemFreeEditOutput extends OrderCustomAreaOutput { id: string; - cropImageUrl: string; descriptionText: string; sortOrder: number; attachments: OrderItemFreeEditAttachmentOutput[]; } +export interface OrderItemCustomImageOutput { + id: string; + kind: CustomImageKind; + imageUrl: string; +} + +export interface ThreeDDesignItemOutput { + kind: 'TEXT' | 'DECO'; + x: number; + y: number; + size: number; + effect: { type: string; intensity: number }; + text: string | null; + color: string | null; + decoId: string | null; +} + +export interface ThreeDDesignOutput { + schemaVersion: number; + basic: { + shape: string; + size: string; + design: string | null; + flavor: string | null; + sheetColor: string; + }; + top: ThreeDDesignItemOutput[]; + side: ThreeDDesignItemOutput[]; +} + export interface OrderItemDetailOutput { id: string; storeId: string; @@ -47,6 +90,11 @@ export interface OrderItemDetailOutput { quantity: number; itemSubtotalPrice: number; optionItems: OrderItemOptionOutput[]; + customMode: CustomMode; + customPreviewImageUrl: string | null; + customBaseImageUrl: string | null; + customImages: OrderItemCustomImageOutput[]; + threeDDesign: ThreeDDesignOutput | null; customTexts: OrderItemCustomTextOutput[]; freeEdits: OrderItemFreeEditOutput[]; } diff --git a/src/features/order/types/order-seller-output.type.ts b/src/features/order/types/order-seller-output.type.ts index 1e76d016..6a013837 100644 --- a/src/features/order/types/order-seller-output.type.ts +++ b/src/features/order/types/order-seller-output.type.ts @@ -16,6 +16,8 @@ export interface SellerOrderSummaryOutput { createdAt: Date; firstItemName: string | null; firstItemImageUrl: string | null; + hasCustom: boolean; + firstItemCustomImageUrl: string | null; } export interface SellerOrderDetailOutput { @@ -57,5 +59,6 @@ export interface SellerOrderUpdateEvent { buyerName: string; totalPrice: number; productName: string; + hasCustom: boolean; updatedAt: string; } diff --git a/src/features/product/index.ts b/src/features/product/index.ts index 0b1245bd..cfacdf61 100644 --- a/src/features/product/index.ts +++ b/src/features/product/index.ts @@ -16,6 +16,8 @@ export { type ThreeDDesignSource, type ThreeDDesignV1, } from '@/features/product/services/three-d-design.helper'; +// 주문 상세가 저장된 3D 디자인을 읽을 때 지원하는 JSON 버전. +export { THREE_D_DESIGN_SCHEMA_VERSION } from '@/features/product/constants/custom-3d-catalog.constants'; // 상품 카드 1벌. 찜·최근 본 상품(user feature)이 같은 카드를 쓴다. export { ProductCardService } from '@/features/product/services/product-card.service'; export type { ProductCardOutput } from '@/features/product/types/product-card-output.type'; diff --git a/src/features/product/resolvers/product-home-query.resolver.spec.ts b/src/features/product/resolvers/product-home-query.resolver.spec.ts index 0189aeac..0925ac9c 100644 --- a/src/features/product/resolvers/product-home-query.resolver.spec.ts +++ b/src/features/product/resolvers/product-home-query.resolver.spec.ts @@ -63,13 +63,9 @@ describe('ProductHome Query Resolver (real DB)', () => { }); it('customCakeShowcase: 서비스에 위임해 제작 후기 목록을 반환한다', async () => { - const orderItem = await createOrderItem(prisma); - await prisma.orderItemCustomFreeEdit.create({ - data: { - order_item_id: orderItem.id, - crop_image_url: 'https://img/before.png', - description_text: '요청 디자인', - }, + const orderItem = await createOrderItem(prisma, { + custom_mode_snapshot: 'SLOT', + custom_preview_image_url: 'https://img/before.png', }); const review = await createReview(prisma, { order_item_id: orderItem.id, diff --git a/src/features/product/services/product-home.service.spec.ts b/src/features/product/services/product-home.service.spec.ts index 8c5568cd..cceb4e3e 100644 --- a/src/features/product/services/product-home.service.spec.ts +++ b/src/features/product/services/product-home.service.spec.ts @@ -23,6 +23,7 @@ import { createStore, createUserProfile, linkProductCategory, + nextSeq, } from '@/test/factories'; import { createTestingModuleWithRealDb } from '@/test/modules/testing-module.builder'; @@ -424,7 +425,7 @@ describe('ProductHomeService (real DB)', () => { }); describe('customCakeShowcase', () => { - /** Before(주문 커스텀 크롭)/After(리뷰 이미지)가 모두 있는 쇼케이스 후보 리뷰. */ + /** Before(주문 커스텀 대표 이미지)/After(리뷰 이미지)가 모두 있는 쇼케이스 후보 리뷰. */ async function makeShowcaseReview(args?: { storeId?: bigint; nickname?: string; @@ -432,19 +433,15 @@ describe('ProductHomeService (real DB)', () => { before?: boolean; after?: boolean; }): Promise { - const orderItem = await createOrderItem( - prisma, - args?.storeId !== undefined ? { store_id: args.storeId } : {}, - ); - if (args?.before !== false) { - await prisma.orderItemCustomFreeEdit.create({ - data: { - order_item_id: orderItem.id, - crop_image_url: `https://img/before-${orderItem.id}.png`, - description_text: '요청 디자인', - }, - }); - } + const orderItem = await createOrderItem(prisma, { + ...(args?.storeId !== undefined ? { store_id: args.storeId } : {}), + ...(args?.before !== false + ? { + custom_mode_snapshot: 'SLOT', + custom_preview_image_url: `https://img/before-${nextSeq()}.png`, + } + : {}), + }); const review = await createReview(prisma, { order_item_id: orderItem.id, content: args?.content ?? '후기 본문', @@ -583,28 +580,19 @@ describe('ProductHomeService (real DB)', () => { expect(limited).toHaveLength(2); }); - it('beforeImageUrl은 sort_order가 앞선 커스텀 크롭을 사용한다', async () => { + it('beforeImageUrl은 주문 품목의 커스텀 대표 이미지를 사용한다', async () => { const review = await makeShowcaseReview({ before: false }); const row = await prisma.review.findUniqueOrThrow({ where: { id: review }, }); - await prisma.orderItemCustomFreeEdit.create({ + await prisma.orderItem.update({ + where: { id: row.order_item_id }, data: { - order_item_id: row.order_item_id, - crop_image_url: 'https://img/second-crop.png', - description_text: '두 번째', - sort_order: 1, - }, - }); - await prisma.orderItemCustomFreeEdit.create({ - data: { - order_item_id: row.order_item_id, - crop_image_url: 'https://img/first-crop.png', - description_text: '첫 번째', - sort_order: 0, + custom_mode_snapshot: 'THREE_D', + custom_preview_image_url: 'https://img/top-render.png', }, }); - // before 이미지는 작성 시점 스냅샷(07b) — 크롭을 만든 뒤 작성 경로와 같은 규칙으로 다시 찍는다 + // before 이미지는 작성 시점 스냅샷 — 대표 이미지를 채운 뒤 작성 경로와 같은 규칙으로 다시 찍는다 await prisma.review.update({ where: { id: review }, data: await snapshotReviewOrderItem(prisma, row.order_item_id), @@ -612,7 +600,7 @@ describe('ProductHomeService (real DB)', () => { const result = await service.customCakeShowcase(); - expect(result[0].beforeImageUrl).toBe('https://img/first-crop.png'); + expect(result[0].beforeImageUrl).toBe('https://img/top-render.png'); }); }); diff --git a/src/features/review/repositories/review-order-item-snapshot.helper.ts b/src/features/review/repositories/review-order-item-snapshot.helper.ts index 9374c28f..342ef60f 100644 --- a/src/features/review/repositories/review-order-item-snapshot.helper.ts +++ b/src/features/review/repositories/review-order-item-snapshot.helper.ts @@ -17,7 +17,7 @@ export interface ReviewOrderItemSnapshot { /** * 리뷰 작성 시점에 주문 품목에서 표시값(상품명·매장명·옵션·before 이미지)을 복사한다 — 이후 조회는 review 컬럼만 읽는다. - * 옵션은 활성 option_item을 id 순으로, before 이미지는 활성 free_edit 첫 장(sort_order·id 순). 옵션이 없으면 null. + * 옵션은 활성 option_item을 id 순으로(없으면 null), before 이미지는 커스텀 대표 이미지(3D 윗면 렌더·슬롯형 합성). 커스텀 문구는 옮기지 않는다. */ export async function snapshotReviewOrderItem( tx: Prisma.TransactionClient, @@ -33,12 +33,7 @@ export async function snapshotReviewOrderItem( orderBy: { id: 'asc' }, select: { group_name_snapshot: true, option_title_snapshot: true }, }, - free_edits: { - where: activeWhere, - orderBy: [{ sort_order: 'asc' }, { id: 'asc' }], - take: 1, - select: { crop_image_url: true }, - }, + custom_preview_image_url: true, }, }); return { @@ -51,7 +46,7 @@ export async function snapshotReviewOrderItem( optionTitle: o.option_title_snapshot, })) : Prisma.DbNull, - before_image_url: item.free_edits[0]?.crop_image_url ?? null, + before_image_url: item.custom_preview_image_url, }; } diff --git a/src/features/review/repositories/review-order-item-snapshot.migration.spec.ts b/src/features/review/repositories/review-order-item-snapshot.migration.spec.ts index 164224fa..78b67d49 100644 --- a/src/features/review/repositories/review-order-item-snapshot.migration.spec.ts +++ b/src/features/review/repositories/review-order-item-snapshot.migration.spec.ts @@ -1,14 +1,20 @@ import { readFileSync } from 'node:fs'; import { join } from 'node:path'; +import mysql, { type RowDataPacket } from 'mysql2/promise'; + import type { PrismaClient } from '@/generated/prisma/client'; -import { disconnectTestPrismaClient } from '@/test/db/prisma-test-client'; +import { + disconnectTestPrismaClient, + getTestDatabaseUrl, +} from '@/test/db/prisma-test-client'; import { closeTruncateConnection, truncateAll } from '@/test/db/truncate'; import { createOrderItem, createReview } from '@/test/factories'; import { createTestingModuleWithRealDb } from '@/test/modules/testing-module.builder'; // 07b 마이그레이션의 백필 SQL을 그대로 실행해, 작성 시점 스냅샷 규칙(품목 상품명·활성 옵션 id 순·활성 크롭 첫 장)이 // 기존 리뷰에 같은 값으로 채워지는지 본다. 마이그레이션은 빈 DB에 적용되므로 여기서만 검증된다. +// 백필이 읽는 자유 편집 crop_image_url은 뒤 마이그레이션에서 지워져, 그 열을 더한 임시 표로 같은 이름을 가린 연결 하나에서 돌린다. const MIGRATION = join( __dirname, '../../../../prisma/migrations/20260919123000_review_order_item_snapshot/migration.sql', @@ -40,10 +46,38 @@ describe('review 주문 품목 스냅샷 백필 (real DB)', () => { await truncateAll(); }); - async function runBackfill(): Promise { + /** crop_image_url이 있던 자유 편집 표로 가린 연결에서 크롭을 넣고 백필을 돌린다(임시 표는 세션 범위). */ + async function runBackfill( + crops: Array<{ orderItemId: bigint; url: string; sortOrder: number }> = [], + ): Promise { const statements = backfillStatements(); expect(statements).toHaveLength(3); - for (const stmt of statements) await prisma.$executeRawUnsafe(stmt); + const conn = await mysql.createConnection({ uri: getTestDatabaseUrl() }); + try { + const table = 'order_item_custom_free_edit'; + await conn.query( + `CREATE TEMPORARY TABLE \`_legacy_${table}\` LIKE \`${table}\``, + ); + await conn.query( + `CREATE TEMPORARY TABLE \`${table}\` LIKE \`_legacy_${table}\``, + ); + const [[shown]] = await conn.query( + `SHOW CREATE TABLE \`${table}\``, + ); + expect(String(shown['Create Table'])).toMatch(/^CREATE TEMPORARY TABLE/); + await conn.query( + `ALTER TABLE \`${table}\` ADD COLUMN crop_image_url VARCHAR(2048) NOT NULL`, + ); + for (const crop of crops) { + await conn.query( + `INSERT INTO \`${table}\` (order_item_id, crop_image_url, description_text, sort_order, pos_x, pos_y, width, height, updated_at) VALUES (?, ?, '요청', ?, 0, 0, 10000, 10000, NOW(3))`, + [crop.orderItemId, crop.url, crop.sortOrder], + ); + } + for (const stmt of statements) await conn.query(stmt); + } finally { + await conn.end(); + } } it('상품명·활성 옵션(id 순)·활성 크롭 첫 장(sort_order 순)을 리뷰에 채운다', async () => { @@ -76,22 +110,6 @@ describe('review 주문 품목 스냅샷 백필 (real DB)', () => { }, }); } - await prisma.orderItemCustomFreeEdit.create({ - data: { - order_item_id: orderItem.id, - crop_image_url: 'https://img/second.png', - description_text: '둘째', - sort_order: 1, - }, - }); - await prisma.orderItemCustomFreeEdit.create({ - data: { - order_item_id: orderItem.id, - crop_image_url: 'https://img/first.png', - description_text: '첫째', - sort_order: 0, - }, - }); // 백필 대상 재현: 스냅샷이 비어 있는(=마이그레이션 전) 리뷰 const review = await createReview(prisma, { order_item_id: orderItem.id, @@ -100,7 +118,14 @@ describe('review 주문 품목 스냅샷 백필 (real DB)', () => { before_image_url: null, }); - await runBackfill(); + await runBackfill([ + { + orderItemId: orderItem.id, + url: 'https://img/second.png', + sortOrder: 1, + }, + { orderItemId: orderItem.id, url: 'https://img/first.png', sortOrder: 0 }, + ]); const row = await prisma.review.findUniqueOrThrow({ where: { id: review.id }, diff --git a/src/graphql/removed-schema-elements.spec.ts b/src/graphql/removed-schema-elements.spec.ts index 0329f573..e01a5398 100644 --- a/src/graphql/removed-schema-elements.spec.ts +++ b/src/graphql/removed-schema-elements.spec.ts @@ -29,6 +29,8 @@ const REMOVED_OUTPUT_FIELDS: Array<[type: string, field: string, pr: string]> = ['AdminProductOptionGroup', 'optionRequiresImage', '커스텀 방식'], ['SellerCustomTemplate', 'isActive', '커스텀 방식'], ['AdminProductCustomTemplate', 'isActive', '커스텀 방식'], + // 자유 편집은 크롭 이미지 대신 바탕 위 영역 좌표를 저장한다 + ['OrderItemFreeEdit', 'cropImageUrl', '커스텀 주문 스냅샷'], ]; const REMOVED_INPUT_FIELDS: Array<[input: string, field: string, pr: string]> = [ diff --git a/src/test/enum-sdl-sync.spec.ts b/src/test/enum-sdl-sync.spec.ts index 35a3d670..4e59d5e8 100644 --- a/src/test/enum-sdl-sync.spec.ts +++ b/src/test/enum-sdl-sync.spec.ts @@ -7,6 +7,7 @@ import { CANCEL_REFUND_RULES } from '@/features/order/policies/order-cancel.poli import { THREE_D_OPTION_CATEGORIES } from '@/features/product/constants/custom-3d-catalog.constants'; import { ConversationBodyFormat, + CustomImageKind, CustomMode, CustomTextAlign, NotificationEvent, @@ -91,6 +92,12 @@ const PAIRS: Array< 'src/features/product/product.types.graphql', 'CustomTextAlignType', ], + [ + 'CustomImageKind', + Object.values(CustomImageKind), + 'src/features/order/order.types.graphql', + 'CustomImageKindType', + ], [ 'ThreeDOptionCategory', [...THREE_D_OPTION_CATEGORIES], diff --git a/src/test/factories/order.factory.ts b/src/test/factories/order.factory.ts index 392d7702..75deb59d 100644 --- a/src/test/factories/order.factory.ts +++ b/src/test/factories/order.factory.ts @@ -1,12 +1,15 @@ import { DAY_MS } from '@/common/utils/kst-time'; import { buildRegionLabel } from '@/common/utils/region-label'; import type { + CustomImageKind, + CustomMode, Order, OrderItem, OrderStatus, Payment, PaymentSetting, PaymentStatus, + Prisma, PrismaClient, } from '@/generated/prisma/client'; import { activeWhere } from '@/prisma'; @@ -154,6 +157,9 @@ export interface OrderItemOverrides { sale_price_snapshot?: number | null; quantity?: number; item_subtotal_price?: number; + custom_mode_snapshot?: CustomMode; + custom_base_image_url_snapshot?: string | null; + custom_preview_image_url?: string | null; deleted_at?: Date; } @@ -210,7 +216,56 @@ export async function createOrderItem( sale_price_snapshot: overrides.sale_price_snapshot ?? null, quantity: overrides.quantity ?? 1, item_subtotal_price: overrides.item_subtotal_price ?? 10000, + custom_mode_snapshot: overrides.custom_mode_snapshot ?? 'NONE', + custom_base_image_url_snapshot: + overrides.custom_base_image_url_snapshot ?? null, + custom_preview_image_url: overrides.custom_preview_image_url ?? null, ...(overrides.deleted_at ? { deleted_at: overrides.deleted_at } : {}), }, }); } + +const THREE_D_RENDER_KINDS = [ + 'THREE_D_TOP', + 'THREE_D_FRONT', + 'THREE_D_BACK', + 'THREE_D_LEFT', + 'THREE_D_RIGHT', +] as const satisfies readonly CustomImageKind[]; + +export const MINIMAL_THREE_D_DESIGN = { + schemaVersion: 1, + basic: { + shape: 'heart', + size: 'mini', + design: null, + flavor: null, + sheetColor: 'white', + }, + top: [], + side: [], +}; + +/** 3D 품목 스냅샷: 디자인 JSON과 렌더 5장(`https://img/.png`). 정렬이 드러나게 종류 역순으로 넣는다. */ +export async function createThreeDOrderItemCustom( + prisma: PrismaClient, + orderItemId: bigint, + designJson: Prisma.InputJsonValue = MINIMAL_THREE_D_DESIGN, +): Promise { + await prisma.orderItemCustomDesign.create({ + data: { + order_item_id: orderItemId, + schema_version: 1, + design_json: designJson, + }, + }); + for (const kind of [...THREE_D_RENDER_KINDS].reverse()) { + await prisma.orderItemCustomImage.create({ + data: { + order_item_id: orderItemId, + kind, + image_url: `https://img/${kind}.png`, + }, + }); + } +} diff --git a/src/test/model-ownership.ts b/src/test/model-ownership.ts index 2e50fae6..8e8580d2 100644 --- a/src/test/model-ownership.ts +++ b/src/test/model-ownership.ts @@ -90,6 +90,8 @@ export const MODEL_OWNERSHIP: Readonly> = { OrderItemCustomText: order([]), OrderItemCustomFreeEdit: order([]), OrderItemCustomFreeEditAttachment: order([]), + OrderItemCustomDesign: order([]), + OrderItemCustomImage: order([]), Payment: order(), Refund: order(), DepositRecord: order(), diff --git a/src/test/seed-reset-scope.spec.ts b/src/test/seed-reset-scope.spec.ts index 3d566427..6c035f5b 100644 --- a/src/test/seed-reset-scope.spec.ts +++ b/src/test/seed-reset-scope.spec.ts @@ -151,6 +151,37 @@ describe('resetSeedScope (real DB)', () => { ).not.toBeNull(); }); + it('시드 주문과 시드 상품을 산 외부 주문에 커스텀 디자인·이미지가 붙어도 정리하고 다시 시드한다', async () => { + await seedThroughReviews(); + const seedProduct = await prisma.product.findFirstOrThrow({ + where: { store: { store_name: { startsWith: SEED_STORE_NAME_PREFIX } } }, + }); + const { item } = await outsiderOrder(seedProduct.id); + await prisma.orderItemCustomDesign.create({ + data: { order_item_id: item.id, schema_version: 1, design_json: {} }, + }); + await prisma.orderItemCustomImage.create({ + data: { + order_item_id: item.id, + kind: 'THREE_D_TOP', + image_url: 'https://img/top.png', + }, + }); + const counts = () => + Promise.all([ + prisma.orderItemCustomDesign.count(), + prisma.orderItemCustomImage.count(), + ]); + // 시드도 슬롯형 합성 이미지를 2장 넣는다 + expect(await counts()).toEqual([1, 3]); + + await resetSeedScope(prisma); + expect(await counts()).toEqual([0, 0]); + + await seedThroughReviews(); + expect(await counts()).toEqual([0, 2]); + }); + it('시드 밖 계정이 시드 밖 매장에 넣은 주문은 남긴다', async () => { await seedThroughReviews(); const { order, item } = await outsiderOrder(); From fb80fbf1ee54d944b2de9918679ae4785d19bcb0 Mon Sep 17 00:00:00 2001 From: chanwoo7 Date: Thu, 19 Nov 2026 05:16:40 +0900 Subject: [PATCH 2/2] =?UTF-8?q?fix:=20=EC=8B=9C=EB=93=9C=20=EB=A6=AC?= =?UTF-8?q?=EB=B7=B0=EA=B0=80=20=ED=99=88=20=EC=A0=9C=EC=9E=91=20=ED=9B=84?= =?UTF-8?q?=EA=B8=B0=20=EC=87=BC=EC=BC=80=EC=9D=B4=EC=8A=A4=20=ED=9B=84?= =?UTF-8?q?=EB=B3=B4=EA=B0=80=20=EB=90=98=EA=B2=8C=20Before=20=EC=8A=A4?= =?UTF-8?q?=EB=83=85=EC=83=B7=20=EC=B1=84=EC=9B=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 쇼케이스는 리뷰의 작성 시점 스냅샷 before_image_url만 읽는데 시드 리뷰가 이 열을 채우지 않아, o4 품목에 커스텀 대표 이미지를 둬도 로컬에서 쇼케이스 후보에서 빠졌다. 변경점 - SeededOrders에 o4 대표 이미지 URL을 싣고 seedReviews가 before_image_url로 복사한다 테스트 - seed-reset-scope spec 통과 - 시드 → listShowcaseReviewIdsByLikes 임시 spec으로 시드 리뷰가 후보 1건으로 잡히고, 시드 변경을 되돌리면 0건인 것을 확인했다(임시 spec은 커밋하지 않음) --- prisma/seed/orders.ts | 2 ++ prisma/seed/reviews.ts | 3 ++- 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/prisma/seed/orders.ts b/prisma/seed/orders.ts index 98d16bf3..7fae4c0f 100644 --- a/prisma/seed/orders.ts +++ b/prisma/seed/orders.ts @@ -59,6 +59,7 @@ export interface SeededOrders { o3Made: bigint; o4PickedUpReviewed: bigint; o4OrderItemId: bigint; + o4PreviewImageUrl: string; o5PickedUpReviewable: bigint; o6Canceled: bigint; o7PendingPayment: bigint; @@ -591,6 +592,7 @@ export async function seedOrders( o3Made: o3.id, o4PickedUpReviewed: o4.id, o4OrderItemId: o4Item.id, + o4PreviewImageUrl: o4Preview, o5PickedUpReviewable: o5.id, o6Canceled: o6.id, o7PendingPayment: o7.id, diff --git a/prisma/seed/reviews.ts b/prisma/seed/reviews.ts index 97fdbc1d..436fe6c6 100644 --- a/prisma/seed/reviews.ts +++ b/prisma/seed/reviews.ts @@ -26,9 +26,10 @@ export async function seedReviews( account_id: user1.id, store_id: storeA.id, product_id: p1.id, - // 작성 시점 주문 품목 스냅샷(07b) — 시드 주문 품목의 상품명·옵션과 같게 + // 작성 시점 주문 품목 스냅샷 — 시드 주문 품목의 상품명·옵션·대표 이미지와 같게 product_name_snapshot: p1.name, store_name_snapshot: storeA.store_name, + before_image_url: ctx.orders.o4PreviewImageUrl, rating: new Prisma.Decimal('4.5'), content: '레터링이 정말 예쁘게 나왔어요. 케이크 맛도 좋고 다음에 또 주문할게요!',