diff --git a/src/common/errors/error-catalog.spec.ts b/src/common/errors/error-catalog.spec.ts index 21749898..cac760d7 100644 --- a/src/common/errors/error-catalog.spec.ts +++ b/src/common/errors/error-catalog.spec.ts @@ -36,6 +36,9 @@ const RENDER_PARAMS: Partial< CUSTOM_TEXT_DEFAULT_TOO_LONG: { label: '이름', max: 20 }, CUSTOM_3D_ITEM_LIMIT_EXCEEDED: { max: 10 }, CUSTOM_3D_DESIGN_INVALID: { field: 'top[0].size' }, + CUSTOM_SLOT_TEXT_REQUIRED: { label: '이름' }, + CUSTOM_SLOT_TEXT_TOO_LONG: { label: '이름', max: 20 }, + CUSTOM_FREE_EDIT_INVALID: { field: 'freeEdits[0].descriptionText' }, IDS_LENGTH_MISMATCH: { field: 'imageIds' }, INVALID_IDS: { field: 'imageIds' }, PRODUCT_IMAGE_LIMIT_EXCEEDED: { max: 10 }, diff --git a/src/common/errors/error-catalog.ts b/src/common/errors/error-catalog.ts index fa18a216..f93c23ad 100644 --- a/src/common/errors/error-catalog.ts +++ b/src/common/errors/error-catalog.ts @@ -570,6 +570,52 @@ export const ERROR_CATALOG = { message: ({ field }) => `3D 디자인에 쓸 수 없는 값이 있어요(${field}). 다시 꾸며 주세요.`, }, + CUSTOM_INPUT_REQUIRED: { + status: HttpStatus.BAD_REQUEST, + message: '케이크를 꾸민 뒤 주문해 주세요.', + }, + CUSTOM_INPUT_MISMATCH: { + status: HttpStatus.BAD_REQUEST, + message: '이 상품의 꾸미기 방식과 맞지 않는 주문이에요. 다시 꾸며 주세요.', + }, + CUSTOM_QUANTITY_FIXED: { + status: HttpStatus.BAD_REQUEST, + message: '꾸민 케이크는 한 번에 1개만 주문할 수 있어요.', + }, + CUSTOM_TEMPLATE_CHANGED: { + status: HttpStatus.CONFLICT, + message: '판매자가 꾸미기 설정을 바꿨어요. 다시 꾸며 주세요.', + }, + CUSTOM_SLOT_TEXTS_MISMATCH: { + status: HttpStatus.BAD_REQUEST, + message: '문구 자리 입력이 상품 설정과 맞지 않아요. 다시 꾸며 주세요.', + }, + CUSTOM_SLOT_TEXT_REQUIRED: { + status: HttpStatus.BAD_REQUEST, + message: ({ label }) => `'${label}'에 문구를 넣어 주세요.`, + }, + CUSTOM_SLOT_TEXT_TOO_LONG: { + status: HttpStatus.BAD_REQUEST, + message: ({ label, max }) => `'${label}'에는 ${max}자까지 쓸 수 있어요.`, + }, + CUSTOM_FREE_EDIT_INVALID: { + status: HttpStatus.BAD_REQUEST, + message: ({ field }) => + `자유 편집 요청에 쓸 수 없는 값이 있어요(${field}). 다시 확인해 주세요.`, + }, + CUSTOM_RENDER_IMAGES_INVALID: { + status: HttpStatus.BAD_REQUEST, + message: + '3D 렌더 이미지는 윗면과 옆면 앞·뒤·왼쪽·오른쪽이 1장씩 있어야 해요.', + }, + CUSTOM_UPLOAD_INVALID: { + status: HttpStatus.BAD_REQUEST, + message: '꾸미기 이미지를 확인할 수 없어요. 이미지를 다시 올려 주세요.', + }, + CUSTOM_UPLOAD_EXPIRED: { + status: HttpStatus.BAD_REQUEST, + message: '꾸미기 이미지 보관 기간이 지났어요. 이미지를 다시 올려 주세요.', + }, INVALID_DAY_OF_WEEK: { status: HttpStatus.BAD_REQUEST, message: 'dayOfWeek는 0~6이어야 합니다.', diff --git a/src/features/order/constants/order-custom-upload-purposes.ts b/src/features/order/constants/order-custom-upload-purposes.ts new file mode 100644 index 00000000..5d7cfdf6 --- /dev/null +++ b/src/features/order/constants/order-custom-upload-purposes.ts @@ -0,0 +1,9 @@ +import type { OrderCustomUploadPurpose } from '@/generated/prisma/client'; +import type { UploadPurpose } from '@/global/storage/types/storage.types'; + +/** 구매자 커스텀 업로드 용도 → 저장소 정책(키 접두·형식·크기). 발급과 주문 생성의 소유 검증이 같은 표를 쓴다. */ +export const CUSTOM_UPLOAD_PURPOSES = { + RENDER: 'ORDER_CUSTOM_RENDER', + COMPOSITE: 'ORDER_CUSTOM_COMPOSITE', + REFERENCE: 'ORDER_CUSTOM_REFERENCE', +} as const satisfies Record; diff --git a/src/features/order/dto/inputs/create-order-custom.input.ts b/src/features/order/dto/inputs/create-order-custom.input.ts new file mode 100644 index 00000000..47581e0d --- /dev/null +++ b/src/features/order/dto/inputs/create-order-custom.input.ts @@ -0,0 +1,182 @@ +import { Type } from 'class-transformer'; +import { + IsArray, + IsDefined, + IsEnum, + IsIn, + IsInt, + IsNumber, + IsOptional, + IsString, + MaxLength, + ValidateNested, +} from 'class-validator'; + +import { CustomImageKind } from '@/generated/prisma/client'; + +// 저장 컬럼 길이. 개수·글자 수·좌표 범위는 상품 설정과 함께 봐야 해서 서비스가 도메인 코드로 판정한다. +const MAX_URL_LENGTH = 2048; + +export class CreateOrderSlotTextInput { + @IsString() + tokenId!: string; + + @IsOptional() + @IsString() + valueText?: string | null; +} + +export class CreateOrderFreeEditInput { + @IsInt() + posX!: number; + + @IsInt() + posY!: number; + + @IsInt() + width!: number; + + @IsInt() + height!: number; + + @IsString() + descriptionText!: string; + + @IsOptional() + @IsArray() + @IsString({ each: true }) + @MaxLength(MAX_URL_LENGTH, { each: true }) + referenceImageUrls?: string[] | null; +} + +export class CreateOrderSlotCustomInput { + @IsInt() + templateRevision!: number; + + @IsArray() + @ValidateNested({ each: true }) + @Type(() => CreateOrderSlotTextInput) + texts!: CreateOrderSlotTextInput[]; + + @IsString() + @MaxLength(MAX_URL_LENGTH) + compositeImageUrl!: string; + + @IsOptional() + @IsArray() + @ValidateNested({ each: true }) + @Type(() => CreateOrderFreeEditInput) + freeEdits?: CreateOrderFreeEditInput[] | null; +} + +export class ThreeDDesignBasicInput { + @IsString() + shape!: string; + + @IsString() + size!: string; + + @IsOptional() + @IsString() + design?: string | null; + + @IsOptional() + @IsString() + flavor?: string | null; + + @IsString() + sheetColor!: string; +} + +export class ThreeDDesignEffectInput { + @IsString() + type!: string; + + @IsInt() + intensity!: number; +} + +export class ThreeDDesignItemInput { + @IsIn(['TEXT', 'DECO']) + kind!: 'TEXT' | 'DECO'; + + @IsNumber() + x!: number; + + @IsNumber() + y!: number; + + @IsNumber() + size!: number; + + @IsDefined() + @ValidateNested() + @Type(() => ThreeDDesignEffectInput) + effect!: ThreeDDesignEffectInput; + + @IsOptional() + @IsString() + text?: string | null; + + @IsOptional() + @IsString() + color?: string | null; + + @IsOptional() + @IsString() + decoId?: string | null; +} + +export class ThreeDDesignInput { + @IsInt() + schemaVersion!: number; + + @IsDefined() + @ValidateNested() + @Type(() => ThreeDDesignBasicInput) + basic!: ThreeDDesignBasicInput; + + @IsArray() + @ValidateNested({ each: true }) + @Type(() => ThreeDDesignItemInput) + top!: ThreeDDesignItemInput[]; + + @IsArray() + @ValidateNested({ each: true }) + @Type(() => ThreeDDesignItemInput) + side!: ThreeDDesignItemInput[]; +} + +export class CreateOrderRenderImageInput { + @IsEnum(CustomImageKind) + kind!: CustomImageKind; + + @IsString() + @MaxLength(MAX_URL_LENGTH) + imageUrl!: string; +} + +export class CreateOrderThreeDCustomInput { + @IsDefined() + @ValidateNested() + @Type(() => ThreeDDesignInput) + design!: ThreeDDesignInput; + + @IsArray() + @ValidateNested({ each: true }) + @Type(() => CreateOrderRenderImageInput) + renderImages!: CreateOrderRenderImageInput[]; +} + +/** 커스텀 상품이면 그 방식의 입력 하나만 보낸다. */ +export class CreateOrderCustomInput { + @IsOptional() + @ValidateNested() + @Type(() => CreateOrderSlotCustomInput) + slot?: CreateOrderSlotCustomInput | null; + + @IsOptional() + @ValidateNested() + @Type(() => CreateOrderThreeDCustomInput) + threeD?: CreateOrderThreeDCustomInput | null; +} diff --git a/src/features/order/dto/inputs/create-order.input.spec.ts b/src/features/order/dto/inputs/create-order.input.spec.ts index f4a2bc5f..cc5190cd 100644 --- a/src/features/order/dto/inputs/create-order.input.spec.ts +++ b/src/features/order/dto/inputs/create-order.input.spec.ts @@ -111,4 +111,143 @@ describe('CreateOrderInput', () => { ); expect(errors.map((e) => e.property)).toEqual(['requestNote']); }); + + describe('custom', () => { + // 전역 ValidationPipe와 같은 옵션 — 데코레이터가 빠진 중첩 필드는 여기서 거절된다 + const STRICT = { whitelist: true, forbidNonWhitelisted: true }; + const SLOT = { + templateRevision: 1, + texts: [{ tokenId: '1', valueText: '축하해' }, { tokenId: '2' }], + compositeImageUrl: 'https://img/c.png', + freeEdits: [ + { + posX: 0, + posY: 0, + width: 10, + height: 10, + descriptionText: '꽃', + referenceImageUrls: ['https://img/r.png'], + }, + ], + }; + const THREE_D = { + design: { + schemaVersion: 1, + basic: { + shape: 'heart', + size: 'mini', + design: null, + flavor: 'cream', + sheetColor: 'white', + }, + top: [ + { + kind: 'TEXT', + x: 0.5, + y: 0.5, + size: 8, + effect: { type: 'none', intensity: 50 }, + text: '축하해', + color: '#000000', + }, + ], + side: [ + { + kind: 'DECO', + x: 0.1, + y: 0.2, + size: 20, + effect: { type: 'soft', intensity: 0 }, + decoId: 'number-1', + }, + ], + }, + renderImages: [{ kind: 'THREE_D_TOP', imageUrl: 'https://img/t.png' }], + }; + + it.each([ + ['슬롯형', { slot: SLOT }], + ['3D', { threeD: THREE_D }], + ['자유 편집·참고 사진 생략', { slot: { ...SLOT, freeEdits: undefined } }], + ])( + '%s 입력의 모든 필드가 화이트리스트를 통과한다', + async (_case, custom) => { + expect( + await validate(build({ ...VALID, custom }), STRICT), + ).toHaveLength(0); + }, + ); + + it.each<[string, object]>([ + [ + '문구 자리 tokenId가 숫자', + { slot: { ...SLOT, texts: [{ tokenId: 1 }] } }, + ], + [ + '모르는 필드', + { slot: { ...SLOT, texts: [{ tokenId: '1', extra: 'x' }] } }, + ], + [ + '자유 편집 좌표가 문자열', + { slot: { ...SLOT, freeEdits: [{ ...SLOT.freeEdits[0], posX: '1' }] } }, + ], + [ + '합성 이미지 URL 2049자', + { slot: { ...SLOT, compositeImageUrl: 'h'.repeat(2049) } }, + ], + [ + '렌더 이미지 종류가 enum 밖', + { + threeD: { + ...THREE_D, + renderImages: [{ kind: 'SIDE', imageUrl: 'https://img/t.png' }], + }, + }, + ], + [ + '3D 항목 종류가 enum 밖', + { + threeD: { + ...THREE_D, + design: { + ...THREE_D.design, + top: [{ ...THREE_D.design.top[0], kind: 'IMAGE' }], + }, + }, + }, + ], + [ + '효과 강도가 소수', + { + threeD: { + ...THREE_D, + design: { + ...THREE_D.design, + side: [ + { + ...THREE_D.design.side[0], + effect: { type: 'soft', intensity: 1.5 }, + }, + ], + }, + }, + }, + ], + [ + '디자인 basic 누락', + { + threeD: { + ...THREE_D, + design: { ...THREE_D.design, basic: undefined }, + }, + }, + ], + ])( + '중첩 입력의 형식 오류(%s)는 custom에서 거절한다', + async (_case, custom) => { + const errors = await validate(build({ ...VALID, custom }), STRICT); + expect(errors.map((e) => e.property)).toEqual(['custom']); + }, + ); + }); }); diff --git a/src/features/order/dto/inputs/create-order.input.ts b/src/features/order/dto/inputs/create-order.input.ts index baa3fc85..c0e75b43 100644 --- a/src/features/order/dto/inputs/create-order.input.ts +++ b/src/features/order/dto/inputs/create-order.input.ts @@ -1,3 +1,4 @@ +import { Type } from 'class-transformer'; import { IsArray, IsDate, @@ -10,9 +11,11 @@ import { Max, MaxLength, Min, + ValidateNested, } from 'class-validator'; import { PHONE_REGEX } from '@/features/auth'; +import { CreateOrderCustomInput } from '@/features/order/dto/inputs/create-order-custom.input'; export class CreateOrderInput { // 8~64자, 공백 문자 불가 — 형식은 길이만 제한한다. @@ -64,4 +67,9 @@ export class CreateOrderInput { @IsString() @MaxLength(500) requestNote?: string; + + @IsOptional() + @ValidateNested() + @Type(() => CreateOrderCustomInput) + custom?: CreateOrderCustomInput | null; } diff --git a/src/features/order/order-checkout.graphql b/src/features/order/order-checkout.graphql index 30a60af5..3ab6cc7e 100644 --- a/src/features/order/order-checkout.graphql +++ b/src/features/order/order-checkout.graphql @@ -4,7 +4,8 @@ extend type Mutation { 결과의 payment로 입금을 안내하고, 1시간 안에 입금이 확인되지 않으면 자동 취소된다. 판매자에게는 입금 확인 뒤에 보인다. 입금 계좌가 설정되지 않았으면 PAYMENT_ACCOUNT_NOT_CONFIGURED(SERVICE_UNAVAILABLE), 입금 대기 주문이 이미 2건이면 PENDING_PAYMENT_LIMIT_EXCEEDED(CONFLICT), 같은 계정의 다른 주문 요청이 처리 중이라 3초 안에 차례가 오지 않으면 - CONCURRENT_REQUEST(CONFLICT)다. 로그인 필수. + CONCURRENT_REQUEST(CONFLICT)다. 커스텀 상품이면 custom 입력을 검증해 주문 시점 스냅샷으로 저장하고 수량은 1이다 + (CreateOrderCustomInput 참고). 로그인 필수. """ createOrder(input: CreateOrderInput!): CreateOrderOutput! """ @@ -33,7 +34,7 @@ enum OrderCustomUploadPurpose { REFERENCE } -"""주문 생성 입력. 커스텀 필드는 커스텀 스펙 확정 후 optional로 확장 예정.""" +"""주문 생성 입력.""" input CreateOrderInput { """ 클라이언트 생성 멱등 키(8~64자). 체크아웃 진입 시 새로 만들고 재시도에는 @@ -63,6 +64,151 @@ input CreateOrderInput { expectedTotalPrice: Int! """판매자에게 전할 요청 사항(최대 500자). 공백만 보내면 없음으로 저장한다.""" requestNote: String + """ + 커스텀 입력. 상품의 커스텀 방식(ProductDetail.customMode)이 SLOT이면 slot, THREE_D면 threeD 하나만 보낸다. + 커스텀 상품인데 없으면 CUSTOM_INPUT_REQUIRED, 방식이 다르거나 커스텀 상품이 아닌데 보내면 CUSTOM_INPUT_MISMATCH, + 수량이 1이 아니면 CUSTOM_QUANTITY_FIXED, 판매자 설정이 끝나지 않은 상품이면 CUSTOM_PRODUCT_NOT_READY다. + 커스텀은 추가 금액이 없다(3D 모양·크기 등의 가격은 옵션 추가금으로만 들어온다). + """ + custom: CreateOrderCustomInput +} + +""" +주문 커스텀 입력. 이미지 URL은 모두 createOrderCustomUploadUrl로 올린 본인 파일의 publicUrl이어야 하고(용도가 맞아야 한다), +한 주문 안에서 같은 파일을 두 번 쓸 수 없다. 아니면 CUSTOM_UPLOAD_INVALID, 발급 뒤 오래돼 정리 중인 파일이면 +CUSTOM_UPLOAD_EXPIRED다. 다른 주문에 이미 쓴 파일도 CUSTOM_UPLOAD_INVALID다. +""" +input CreateOrderCustomInput { + """슬롯형(바탕 이미지 + 문구 자리) 입력. 슬롯형 상품에서만 보낸다.""" + slot: CreateOrderSlotCustomInput + """3D 입력. 3D 상품에서만 보낸다.""" + threeD: CreateOrderThreeDCustomInput +} + +""" +슬롯형 커스텀 입력. 좌표는 바탕 이미지 한 변을 10000으로 본 정수 비율이고 원점은 왼쪽 위다. +""" +input CreateOrderSlotCustomInput { + """ + 꾸미기를 시작할 때 본 ProductDetail.customTemplate.revision. 그 사이 판매자가 설정을 바꿨으면 + CUSTOM_TEMPLATE_CHANGED(CONFLICT)이고 다시 꾸며야 한다. + """ + templateRevision: Int! + """ + 문구 자리마다 1건(customTemplate.slots 전부, 중복 없이). 빠지거나 남는 자리가 있으면 CUSTOM_SLOT_TEXTS_MISMATCH다. + """ + texts: [CreateOrderSlotTextInput!]! + """구매자가 본 그대로의 합성 이미지 URL(바탕 + 문구, 용도 COMPOSITE). 대표 이미지로 저장된다.""" + compositeImageUrl: String! + """ + 자유 편집 요청(customTemplate.freeEditEnabled일 때만, 최대 5건). 규칙을 벗어나면 CUSTOM_FREE_EDIT_INVALID다. + """ + freeEdits: [CreateOrderFreeEditInput!] = [] +} + +"""문구 자리 1개의 입력.""" +input CreateOrderSlotTextInput { + tokenId: ID! + """ + 넣을 문구. 손대지 않았으면 기본 문구를 그대로 보낸다. 줄바꿈(CRLF는 LF로 바꾼다)·이모지를 쓸 수 있고 앞뒤 공백은 지운다. + 지운 뒤 비었거나 null이면 '문구 없음'이다(필수 자리면 CUSTOM_SLOT_TEXT_REQUIRED). 자리의 maxLength(코드 포인트)를 + 넘으면 CUSTOM_SLOT_TEXT_TOO_LONG이다. + """ + valueText: String +} + +"""자유 편집 요청 1건. 바탕 이미지 위 영역과 설명, 참고 사진이다.""" +input CreateOrderFreeEditInput { + """영역 왼쪽 위 x(0~10000).""" + posX: Int! + """영역 왼쪽 위 y(0~10000).""" + posY: Int! + """영역 너비(1 이상, posX + width ≤ 10000).""" + width: Int! + """영역 높이(1 이상, posY + height ≤ 10000).""" + height: Int! + """요청 설명(앞뒤 공백을 지운 뒤 1~2000자, 줄바꿈 허용).""" + descriptionText: String! + """참고 사진 URL(용도 REFERENCE, 최대 3장).""" + referenceImageUrls: [String!] = [] +} + +"""3D 커스텀 입력.""" +input CreateOrderThreeDCustomInput { + """ + 3D 디자인(JSON v1). 모양·크기·디자인·맛은 고른 옵션의 threeDKey와 같아야 한다(아니면 CUSTOM_3D_OPTIONS_CHANGED). + 카탈로그·한도 검증은 customThreeDCatalog를 따른다. + """ + design: ThreeDDesignInput! + """ + 렌더 이미지(용도 RENDER). THREE_D_TOP·FRONT·BACK·LEFT·RIGHT 정확히 1장씩이고, 아니면 CUSTOM_RENDER_IMAGES_INVALID다. + 윗면이 대표 이미지로 저장된다. + """ + renderImages: [CreateOrderRenderImageInput!]! +} + +"""3D 렌더 이미지 1장.""" +input CreateOrderRenderImageInput { + """렌더 자세.""" + kind: CustomImageKindType! + """이미지 URL.""" + imageUrl: String! +} + +""" +3D 디자인 입력(JSON v1). 저장 형태는 ThreeDDesign이고 같은 좌표계·규칙을 쓴다. 배열 순서가 그리는 순서다. +""" +input ThreeDDesignInput { + """디자인 JSON 버전. 지금은 1만 받는다(아니면 CUSTOM_3D_SCHEMA_UNSUPPORTED).""" + schemaVersion: Int! + """모양·크기·디자인·맛·시트 색.""" + basic: ThreeDDesignBasicInput! + """윗면 항목(글자·꾸미기 각 10개까지).""" + top: [ThreeDDesignItemInput!]! + """옆면 항목(글자·꾸미기 각 10개까지).""" + side: [ThreeDDesignItemInput!]! +} + +"""3D 디자인의 케이크 기본값.""" +input ThreeDDesignBasicInput { + """모양 선택지 value(고른 모양 옵션의 값).""" + shape: String! + """크기 선택지 value(고른 크기 옵션의 값).""" + size: String! + """디자인 선택지 value. 디자인 옵션을 고르지 않았으면 null(장식 없는 시트).""" + design: String + """맛 선택지 value. 맛 옵션을 고르지 않았으면 null.""" + flavor: String + """시트 색 key(카탈로그 sheetColors).""" + sheetColor: String! +} + +"""3D 디자인 항목(글자 또는 꾸미기) 1개.""" +input ThreeDDesignItemInput { + """항목 종류.""" + kind: ThreeDItemKindType! + """가로 위치(0~1, ThreeDDesign.top·side 좌표계).""" + x: Float! + """세로 위치(0~1, ThreeDDesign.top·side 좌표계).""" + y: Float! + """크기(cqw). 글자 4~30, 꾸미기 8~50.""" + size: Float! + """효과.""" + effect: ThreeDDesignEffectInput! + """글자 내용(TEXT만, 1~30 코드 포인트, 줄바꿈·이모지 허용). DECO는 null.""" + text: String + """글자색(TEXT만, #RRGGBB). DECO는 null.""" + color: String + """꾸미기 key(DECO만, 카탈로그 decos). TEXT는 null.""" + decoId: String +} + +"""3D 디자인 항목에 건 효과.""" +input ThreeDDesignEffectInput { + """효과 key(카탈로그 effects).""" + type: String! + """효과 강도(0~100 정수).""" + intensity: Int! } """주문 생성 결과 요약. 상세는 myOrder로 재조회.""" diff --git a/src/features/order/order.module.ts b/src/features/order/order.module.ts index b831613f..e0c805f8 100644 --- a/src/features/order/order.module.ts +++ b/src/features/order/order.module.ts @@ -32,6 +32,7 @@ import { OrderAdminAlertConsumer } from '@/features/order/services/order-admin-a import { AdminOrderService } from '@/features/order/services/order-admin.service'; import { OrderCheckoutService } from '@/features/order/services/order-checkout.service'; import { OrderCustomUploadCleanupScheduler } from '@/features/order/services/order-custom-upload-cleanup.scheduler'; +import { OrderCustomizationService } from '@/features/order/services/order-customization.service'; import { AdminDepositService } from '@/features/order/services/order-deposit-admin.service'; import { OrderEventsService } from '@/features/order/services/order-events.service'; import { UserOrderService } from '@/features/order/services/order-my.service'; @@ -70,6 +71,8 @@ import { StoreModule } from '@/features/store'; OrderSubscriptionResolver, OrderCheckoutService, OrderCheckoutMutationResolver, + // 주문 생성의 커스텀 입력 검증·스냅샷(상품 설정 대조, 업로드 소유) + OrderCustomizationService, // 커스텀 이미지 선업로드 기록과 미사용분 정리(worker 크론) OrderCustomUploadRepository, OrderCustomUploadCleanupScheduler, diff --git a/src/features/order/repositories/order-custom-upload-attach.helper.ts b/src/features/order/repositories/order-custom-upload-attach.helper.ts new file mode 100644 index 00000000..932fa8be --- /dev/null +++ b/src/features/order/repositories/order-custom-upload-attach.helper.ts @@ -0,0 +1,67 @@ +import { + OrderCustomUploadPurpose, + OrderCustomUploadStatus, + Prisma, +} from '@/generated/prisma/client'; + +export interface CustomUploadRef { + objectKey: string; + purpose: OrderCustomUploadPurpose; +} + +export type CustomUploadIssue = 'upload-invalid' | 'upload-expired'; + +/** + * 주문에 붙일 업로드 행을 주문 tx 안에서 잠그고 검사한다. 잠근 행은 정리 크론(SKIP LOCKED)이 건너뛰므로 + * 검사와 ATTACHED 표시 사이에 지워지지 않는다. 발급 기록이 없거나 계정·용도가 다르거나 이미 다른 주문에 쓰였으면 + * 'upload-invalid', 정리 중이면 'upload-expired'. + */ +export async function lockCustomUploadsForAttach( + tx: Prisma.TransactionClient, + accountId: bigint, + uploads: readonly CustomUploadRef[], +): Promise { + if (uploads.length === 0) return null; + const rows = await tx.$queryRaw< + { + object_key: string; + account_id: bigint; + purpose: OrderCustomUploadPurpose; + status: OrderCustomUploadStatus; + }[] + >` + SELECT object_key, account_id, purpose, status FROM order_custom_upload + WHERE object_key IN (${Prisma.join(uploads.map((u) => u.objectKey))}) + FOR UPDATE`; + // 컬럼 콜레이션이 대소문자를 가리지 않아 IN이 다른 키를 함께 잡을 수 있다 — 키 비교는 여기서 정확히 한다 + const byKey = new Map(rows.map((row) => [row.object_key, row])); + for (const upload of uploads) { + const row = byKey.get(upload.objectKey); + if ( + !row || + row.account_id !== accountId || + row.purpose !== upload.purpose || + row.status === OrderCustomUploadStatus.ATTACHED + ) { + return 'upload-invalid'; + } + if (row.status === OrderCustomUploadStatus.PURGING) return 'upload-expired'; + } + return null; +} + +/** 주문된 파일은 정리 대상에서 빠진다. lockCustomUploadsForAttach로 잠근 같은 tx에서 부른다. */ +export async function markCustomUploadsAttached( + tx: Prisma.TransactionClient, + uploads: readonly CustomUploadRef[], + now: Date, +): Promise { + if (uploads.length === 0) return; + await tx.orderCustomUpload.updateMany({ + where: { + object_key: { in: uploads.map((u) => u.objectKey) }, + status: OrderCustomUploadStatus.PENDING, + }, + data: { status: OrderCustomUploadStatus.ATTACHED, attached_at: now }, + }); +} diff --git a/src/features/order/repositories/order.repository.spec.ts b/src/features/order/repositories/order.repository.spec.ts index 7f216a73..5b047efc 100644 --- a/src/features/order/repositories/order.repository.spec.ts +++ b/src/features/order/repositories/order.repository.spec.ts @@ -975,6 +975,7 @@ describe('OrderRepository (real DB)', () => { quantity, itemSubtotalPrice: 25000 * quantity, options: [], + custom: null, }, }; } diff --git a/src/features/order/repositories/order.repository.ts b/src/features/order/repositories/order.repository.ts index 74e6df1f..5d8c98d0 100644 --- a/src/features/order/repositories/order.repository.ts +++ b/src/features/order/repositories/order.repository.ts @@ -7,6 +7,12 @@ import { import { IN_PROGRESS_ORDER_STATUSES } from '@/features/order/constants/order-status-traits'; import { orderPaymentPendingEvent } from '@/features/order/events/order-payment-pending.event'; import { orderStatusChangedEvent } from '@/features/order/events/order-status-changed.event'; +import { + lockCustomUploadsForAttach, + markCustomUploadsAttached, + type CustomUploadIssue, + type CustomUploadRef, +} from '@/features/order/repositories/order-custom-upload-attach.helper'; import { countPendingPaymentOrdersLocked, PENDING_PAYMENT_LIMIT, @@ -31,6 +37,9 @@ import { Prisma, RefundKind, type AccountType, + type CustomImageKind, + type CustomMode, + type CustomTextAlign, type PaymentStatus, } from '@/generated/prisma/client'; import { activeWhere, PrismaService } from '@/prisma'; @@ -180,6 +189,38 @@ export interface DailyCapacityGuard { dayEndUtc: Date; } +/** 주문 품목 커스텀 스냅샷. 검증·정규화를 마친 값이고, uploads는 같은 tx에서 잠가 ATTACHED로 바꿀 업로드다. */ +export interface OrderItemCustomSnapshot { + mode: Exclude; + baseImageUrl: string | null; + previewImageUrl: string; + texts: { + tokenId: bigint; + tokenKey: string; + label: string; + defaultText: string; + valueText: string | null; + sortOrder: number; + posX: number; + posY: number; + width: number; + height: number; + textColor: string; + textAlign: CustomTextAlign; + }[]; + freeEdits: { + posX: number; + posY: number; + width: number; + height: number; + descriptionText: string; + referenceImageUrls: string[]; + }[]; + design: { schemaVersion: number; json: Prisma.InputJsonObject } | null; + images: { kind: CustomImageKind; imageUrl: string }[]; + uploads: CustomUploadRef[]; +} + export interface CreatePendingPaymentOrderArgs { accountId: bigint; orderNumber: string; @@ -221,6 +262,7 @@ export interface CreatePendingPaymentOrderArgs { optionTitleSnapshot: string; optionPriceDeltaSnapshot: number; }[]; + custom: OrderItemCustomSnapshot | null; }; } @@ -246,7 +288,11 @@ const createdOrderSelect = { } satisfies Prisma.OrderSelect; export type CreatePendingPaymentOrderResult = - CreatedOrderRow | 'capacity-exceeded' | 'pending-limit' | 'lock-timeout'; + | CreatedOrderRow + | 'capacity-exceeded' + | 'pending-limit' + | 'lock-timeout' + | CustomUploadIssue; export interface ReviewableOrderItemRow { id: bigint; @@ -293,7 +339,7 @@ export class OrderRepository { } /** - * 입금 대기 주문을 결제(PENDING)와 함께 만든다. 계정 잠금(GET_LOCK) → 입금 대기 건수 → capacity 순으로 잠그고, + * 입금 대기 주문을 결제(PENDING)와 함께 만든다. 계정 잠금(GET_LOCK) → 입금 대기 건수 → capacity → 커스텀 업로드 순으로 잠그고, * capacity는 행을 FOR UPDATE로 잠근 뒤 점유를 재집계해 동시 주문이 마지막 잔여를 함께 차지하지 못하게 한다. * order_number P2002는 호출부가 재시도한다. * READ COMMITTED: REPEATABLE READ의 갭 잠금은 다른 계정끼리도 건수 잠금 읽기 → INSERT에서 교착한다. @@ -317,6 +363,12 @@ export class OrderRepository { ); if (exceeded) return 'capacity-exceeded'; } + const uploadIssue = await lockCustomUploadsForAttach( + tx, + args.accountId, + args.item.custom?.uploads ?? [], + ); + if (uploadIssue) return uploadIssue; return this.insertPendingPaymentOrder(tx, args); }), { @@ -421,6 +473,7 @@ export class OrderRepository { option_price_delta_snapshot: option.optionPriceDeltaSnapshot, })), }, + ...(args.item.custom && customItemData(args.item.custom)), }, }, payment: { @@ -446,6 +499,11 @@ export class OrderRepository { }, select: createdOrderSelect, }); + await markCustomUploadsAttached( + tx, + args.item.custom?.uploads ?? [], + args.now, + ); // 관리자 경보 원천. 판매자 '새 주문'(order.submitted)은 입금 확인 때 나간다 await this.outbox.publish( tx, @@ -1136,3 +1194,58 @@ export class OrderRepository { return { counts, amountSum }; } } + +/** 품목 생성에 펼쳐 넣는 커스텀 스냅샷. 자유 편집·참고 사진 순서는 입력 순서다. */ +function customItemData(custom: OrderItemCustomSnapshot) { + return { + custom_mode_snapshot: custom.mode, + custom_base_image_url_snapshot: custom.baseImageUrl, + custom_preview_image_url: custom.previewImageUrl, + custom_texts: { + create: custom.texts.map((text) => ({ + token_id: text.tokenId, + token_key_snapshot: text.tokenKey, + label_snapshot: text.label, + default_text_snapshot: text.defaultText, + value_text: text.valueText, + sort_order: text.sortOrder, + pos_x: text.posX, + pos_y: text.posY, + width: text.width, + height: text.height, + text_color: text.textColor, + text_align: text.textAlign, + })), + }, + free_edits: { + create: custom.freeEdits.map((edit, index) => ({ + pos_x: edit.posX, + pos_y: edit.posY, + width: edit.width, + height: edit.height, + description_text: edit.descriptionText, + sort_order: index, + attachments: { + create: edit.referenceImageUrls.map((url, order) => ({ + image_url: url, + sort_order: order, + })), + }, + })), + }, + custom_images: { + create: custom.images.map((image) => ({ + kind: image.kind, + image_url: image.imageUrl, + })), + }, + ...(custom.design && { + custom_design: { + create: { + schema_version: custom.design.schemaVersion, + design_json: custom.design.json, + }, + }, + }), + }; +} diff --git a/src/features/order/resolvers/order-checkout-mutation.resolver.spec.ts b/src/features/order/resolvers/order-checkout-mutation.resolver.spec.ts index 091deeec..bb68507d 100644 --- a/src/features/order/resolvers/order-checkout-mutation.resolver.spec.ts +++ b/src/features/order/resolvers/order-checkout-mutation.resolver.spec.ts @@ -7,6 +7,7 @@ import { OrderRepository } from '@/features/order/repositories/order.repository' import { PaymentSettingRepository } from '@/features/order/repositories/payment-setting.repository'; import { OrderCheckoutMutationResolver } from '@/features/order/resolvers/order-checkout-mutation.resolver'; import { OrderCheckoutService } from '@/features/order/services/order-checkout.service'; +import { OrderCustomizationService } from '@/features/order/services/order-customization.service'; import { ProductRepository } from '@/features/product'; import { StorePickupScheduleService } from '@/features/store'; import { StoreRepository } from '@/features/store/repositories/store.repository'; @@ -44,6 +45,7 @@ describe('OrderCheckout Mutation Resolver (real DB)', () => { providers: [ OrderCheckoutMutationResolver, OrderCheckoutService, + OrderCustomizationService, OrderRepository, OrderCustomUploadRepository, ...s3TestProviders(), diff --git a/src/features/order/services/order-checkout.service.custom.spec.ts b/src/features/order/services/order-checkout.service.custom.spec.ts new file mode 100644 index 00000000..3f4cdf58 --- /dev/null +++ b/src/features/order/services/order-checkout.service.custom.spec.ts @@ -0,0 +1,632 @@ +import { ClockService } from '@/common/providers/clock.service'; +import { RandomService } from '@/common/providers/random.service'; +import { AUDIT_LOG_REPOSITORY } from '@/features/audit-log'; +import { AuditLogRepository } from '@/features/audit-log/repositories/audit-log.repository'; +import type { + CreateOrderCustomInput, + CreateOrderSlotCustomInput, + CreateOrderThreeDCustomInput, +} from '@/features/order/dto/inputs/create-order-custom.input'; +import type { CreateOrderInput } from '@/features/order/dto/inputs/create-order.input'; +import { OrderCustomUploadRepository } from '@/features/order/repositories/order-custom-upload.repository'; +import { OrderRepository } from '@/features/order/repositories/order.repository'; +import { PaymentSettingRepository } from '@/features/order/repositories/payment-setting.repository'; +import { OrderCheckoutService } from '@/features/order/services/order-checkout.service'; +import { OrderCustomizationService } from '@/features/order/services/order-customization.service'; +import { OutboxPublisher } from '@/features/outbox/services/outbox-publisher.service'; +import { ProductRepository } from '@/features/product'; +import { StorePickupScheduleService } from '@/features/store'; +import { StoreRepository } from '@/features/store/repositories/store.repository'; +import type { + Account, + CustomImageKind, + OrderCustomUploadPurpose, + PrismaClient, + Product, +} from '@/generated/prisma/client'; +import { UPLOAD_POLICIES } from '@/global/storage/constants/storage.constants'; +import { bookedQuantityProviders } from '@/test/booked-quantity'; +import { disconnectTestPrismaClient } from '@/test/db/prisma-test-client'; +import { closeTruncateConnection, truncateAll } from '@/test/db/truncate'; +import { + createAccount, + createCustomTemplate, + createCustomTextToken, + createOrderCustomUpload, + createPaymentSetting, + createProduct, + createStore, + createUserProfile, +} from '@/test/factories'; +import { createTestingModuleWithRealDb } from '@/test/modules/testing-module.builder'; +import { outboxPublisherProviders } from '@/test/outbox'; +import { s3TestProviders, TEST_S3_CONFIG } from '@/test/storage/s3-test.helper'; + +// 2026-09-16(수) 16:00 KST 고정 +const NOW = new Date('2026-09-16T07:00:00.000Z'); +/** 2026-09-18(금) 14:00 KST */ +const PICKUP_AT = new Date('2026-09-18T05:00:00.000Z'); + +const PURPOSE_POLICY = { + RENDER: UPLOAD_POLICIES.ORDER_CUSTOM_RENDER, + COMPOSITE: UPLOAD_POLICIES.ORDER_CUSTOM_COMPOSITE, + REFERENCE: UPLOAD_POLICIES.ORDER_CUSTOM_REFERENCE, +} as const; +const RENDER_KINDS = [ + 'THREE_D_TOP', + 'THREE_D_FRONT', + 'THREE_D_BACK', + 'THREE_D_LEFT', + 'THREE_D_RIGHT', +] as const satisfies readonly CustomImageKind[]; + +describe('OrderCheckoutService 커스텀 주문 (real DB)', () => { + let service: OrderCheckoutService; + let orderRepo: OrderRepository; + let uploads: OrderCustomUploadRepository; + let outbox: OutboxPublisher; + let clock: ClockService; + let prisma: PrismaClient; + + beforeAll(async () => { + const { module, prisma: p } = await createTestingModuleWithRealDb({ + providers: [ + OrderCheckoutService, + OrderCustomizationService, + OrderRepository, + OrderCustomUploadRepository, + ...s3TestProviders(), + PaymentSettingRepository, + ProductRepository, + { provide: AUDIT_LOG_REPOSITORY, useClass: AuditLogRepository }, + StorePickupScheduleService, + StoreRepository, + ClockService, + RandomService, + ...outboxPublisherProviders({ clock: true }), + ...bookedQuantityProviders(), + ], + }); + service = module.get(OrderCheckoutService); + orderRepo = module.get(OrderRepository); + uploads = module.get(OrderCustomUploadRepository); + outbox = module.get(OutboxPublisher); + clock = module.get(ClockService); + prisma = p; + }); + + afterAll(async () => { + await closeTruncateConnection(); + await disconnectTestPrismaClient(); + }); + + beforeEach(async () => { + await truncateAll(); + await createPaymentSetting(prisma); + jest.spyOn(clock, 'now').mockReturnValue(NOW); + }); + + afterEach(() => { + jest.restoreAllMocks(); + }); + + async function makeOpenStoreId(): Promise { + const store = await createStore(prisma, { + pickup_slot_interval_minutes: 30, + min_lead_time_minutes: 60, + }); + for (let dayOfWeek = 0; dayOfWeek < 7; dayOfWeek += 1) { + await prisma.storeBusinessHour.create({ + data: { + store_id: store.id, + day_of_week: dayOfWeek, + is_closed: false, + open_time: new Date(Date.UTC(1970, 0, 1, 10)), + close_time: new Date(Date.UTC(1970, 0, 1, 20)), + }, + }); + } + return store.id; + } + + async function makeBuyer(): Promise { + const account = await createAccount(prisma, { account_type: 'USER' }); + await createUserProfile(prisma, { + account_id: account.id, + phone_number: '010-1234-5678', + }); + return account; + } + + /** 발급 기록이 있는 본인 업로드의 공개 URL. */ + async function upload( + buyer: Account, + purpose: OrderCustomUploadPurpose, + name: string, + row: Parameters[1] = {}, + ): Promise { + const key = `${PURPOSE_POLICY[purpose].keyPrefix}/${buyer.id}/2026-09-16/${name}`; + await createOrderCustomUpload(prisma, { + account_id: buyer.id, + purpose, + object_key: key, + ...row, + }); + return `https://${TEST_S3_CONFIG.bucket}.s3.${TEST_S3_CONFIG.region}.amazonaws.com/${key}`; + } + + async function uploadStatuses() { + const rows = await prisma.orderCustomUpload.findMany({ + orderBy: { object_key: 'asc' }, + }); + return rows.map((row) => [row.object_key.split('/').pop(), row.status]); + } + + let idemSeq = 0; + function input( + product: Product, + expectedTotalPrice: number, + custom: CreateOrderCustomInput, + overrides: Partial = {}, + ): CreateOrderInput { + idemSeq += 1; + return { + idempotencyKey: `custom-idem-${idemSeq}`, + productId: product.id.toString(), + optionItemIds: [], + pickupAt: PICKUP_AT, + expectedTotalPrice, + custom, + ...overrides, + }; + } + + describe('슬롯형', () => { + /** 정가 30000·판매가 25000, 필수 자리(이름)·선택 자리(문구), 자유 편집 켜짐. */ + async function setup() { + const buyer = await makeBuyer(); + const product = await createProduct(prisma, { + store_id: await makeOpenStoreId(), + regular_price: 30000, + sale_price: 25000, + }); + await prisma.product.update({ + where: { id: product.id }, + data: { custom_mode: 'SLOT' }, + }); + const template = await createCustomTemplate(prisma, { + product_id: product.id, + base_image_url: 'https://i.example/base-square.png', + free_edit_enabled: true, + revision: 4, + }); + const name = await createCustomTextToken(prisma, { + template_id: template.id, + token_key: 'name', + label: '이름', + default_text: '민지', + max_length: 10, + sort_order: 0, + pos_x: 1000, + pos_y: 1000, + width: 8000, + height: 1000, + text_color: '#FF8800', + text_align: 'LEFT', + }); + const phrase = await createCustomTextToken(prisma, { + template_id: template.id, + token_key: 'phrase', + label: '문구', + default_text: '축하해', + is_required: false, + sort_order: 1, + }); + const composite = await upload(buyer, 'COMPOSITE', 'composite.png'); + const reference = await upload(buyer, 'REFERENCE', 'ref.png'); + const slot: CreateOrderSlotCustomInput = { + templateRevision: 4, + texts: [ + { tokenId: phrase.id.toString(), valueText: null }, + { tokenId: name.id.toString(), valueText: '지수\r\n🎂' }, + ], + compositeImageUrl: composite, + freeEdits: [ + { + posX: 0, + posY: 5000, + width: 10000, + height: 5000, + descriptionText: ' 아래쪽에 꽃 ', + referenceImageUrls: [reference], + }, + ], + }; + return { buyer, product, name, phrase, composite, reference, slot }; + } + + it('문구 자리·자유 편집·합성 이미지를 스냅샷하고 업로드를 ATTACHED로 바꾼다(추가 금액 없음)', async () => { + const { buyer, product, name, phrase, composite, reference, slot } = + await setup(); + + const created = await service.createOrder( + buyer.id, + input(product, 25000, { slot }), + ); + + expect(created.totalPrice).toBe(25000); + const item = await prisma.orderItem.findFirstOrThrow({ + where: { order_id: BigInt(created.orderId) }, + include: { + custom_texts: { orderBy: { sort_order: 'asc' } }, + free_edits: { include: { attachments: true } }, + custom_images: true, + custom_design: true, + }, + }); + expect(item).toMatchObject({ + quantity: 1, + item_subtotal_price: 25000, + custom_mode_snapshot: 'SLOT', + custom_base_image_url_snapshot: 'https://i.example/base-square.png', + custom_preview_image_url: composite, + custom_design: null, + custom_images: [{ kind: 'SLOT_COMPOSITE', image_url: composite }], + }); + expect(item.custom_texts).toMatchObject([ + { + token_id: name.id, + token_key_snapshot: 'name', + label_snapshot: '이름', + default_text_snapshot: '민지', + value_text: '지수\n🎂', + sort_order: 0, + pos_x: 1000, + pos_y: 1000, + width: 8000, + height: 1000, + text_color: '#FF8800', + text_align: 'LEFT', + }, + { + token_id: phrase.id, + label_snapshot: '문구', + default_text_snapshot: '축하해', + value_text: null, + }, + ]); + expect(item.free_edits).toMatchObject([ + { + pos_x: 0, + pos_y: 5000, + width: 10000, + height: 5000, + description_text: '아래쪽에 꽃', + sort_order: 0, + attachments: [{ image_url: reference, sort_order: 0 }], + }, + ]); + expect(await uploadStatuses()).toEqual([ + ['composite.png', 'ATTACHED'], + ['ref.png', 'ATTACHED'], + ]); + const attached = await prisma.orderCustomUpload.findFirstOrThrow(); + expect(attached.attached_at).toEqual(NOW); + }); + + it('한 번 주문에 쓴 이미지는 다른 주문에 쓸 수 없다', async () => { + const { buyer, product, slot } = await setup(); + await service.createOrder(buyer.id, input(product, 25000, { slot })); + + await expect( + service.createOrder(buyer.id, input(product, 25000, { slot })), + ).rejects.toThrowDomain('CUSTOM_UPLOAD_INVALID'); + expect(await prisma.order.count()).toBe(1); + }); + + it.each<[string, Parameters[1], string]>([ + [ + '다른 주문에 붙은 업로드', + { status: 'ATTACHED' }, + 'CUSTOM_UPLOAD_INVALID', + ], + [ + '정리 중인 업로드', + { status: 'PURGING', purge_started_at: NOW }, + 'CUSTOM_UPLOAD_EXPIRED', + ], + [ + '기록의 용도가 다른 업로드', + { purpose: 'RENDER' }, + 'CUSTOM_UPLOAD_INVALID', + ], + ])('%s는 거절하고 주문·연결을 남기지 않는다', async (_case, row, code) => { + const { buyer, product, slot } = await setup(); + slot.freeEdits![0].referenceImageUrls = [ + await upload(buyer, 'REFERENCE', 'bad.png', row), + ]; + + await expect( + service.createOrder(buyer.id, input(product, 25000, { slot })), + ).rejects.toThrowDomain(code); + expect(await prisma.order.count()).toBe(0); + expect( + await prisma.orderCustomUpload.count({ + where: { status: 'ATTACHED', attached_at: NOW }, + }), + ).toBe(0); + }); + + it('발급 기록이 없는 본인 경로 URL·다른 계정 기록·대소문자만 같은 키면 CUSTOM_UPLOAD_INVALID다', async () => { + const { buyer, product, slot } = await setup(); + const other = await createAccount(prisma, { account_type: 'USER' }); + const unissued = `https://${TEST_S3_CONFIG.bucket}.s3.${TEST_S3_CONFIG.region}.amazonaws.com/order-custom/references/${buyer.id}/2026-09-16/none.png`; + const othersRow = await upload(buyer, 'REFERENCE', 'other.png', { + account_id: other.id, + }); + // 키 컬럼 콜레이션은 대소문자를 가리지 않는다 — 다른 키로 같은 행을 붙이지 못해야 한다 + const caseVariant = ( + await upload(buyer, 'REFERENCE', 'case.png') + ).replace('case.png', 'CASE.png'); + + for (const url of [unissued, othersRow, caseVariant]) { + slot.freeEdits![0].referenceImageUrls = [url]; + await expect( + service.createOrder(buyer.id, input(product, 25000, { slot })), + ).rejects.toThrowDomain('CUSTOM_UPLOAD_INVALID'); + } + expect(await prisma.order.count()).toBe(0); + }); + + it('주문 tx가 연결 뒤에 실패하면 업로드는 PENDING으로 남는다', async () => { + const { buyer, product, slot } = await setup(); + jest + .spyOn(outbox, 'publish') + .mockRejectedValueOnce(new Error('outbox down')); + + await expect( + service.createOrder(buyer.id, input(product, 25000, { slot })), + ).rejects.toThrow('outbox down'); + + expect(await prisma.order.count()).toBe(0); + expect(await prisma.orderItemCustomText.count()).toBe(0); + expect(await uploadStatuses()).toEqual([ + ['composite.png', 'PENDING'], + ['ref.png', 'PENDING'], + ]); + // 같은 업로드로 다시 주문할 수 있다 + await expect( + service.createOrder(buyer.id, input(product, 25000, { slot })), + ).resolves.toMatchObject({ status: 'PENDING_PAYMENT' }); + }); + + it('주문 tx가 업로드를 잠근 동안 돈 정리 크론은 그 업로드를 잡지 못하고, 주문이 ATTACHED로 붙인다', async () => { + const { buyer, product, slot } = await setup(); + // 잠금 검사와 ATTACHED 표시 사이에 크론이 끼어드는 경우를 재현한다(크론은 별도 커넥션) + const repo = orderRepo as unknown as { + insertPendingPaymentOrder: (...args: unknown[]) => Promise; + }; + const insert = repo.insertPendingPaymentOrder.bind(orderRepo); + let claimed: unknown[] | undefined; + jest + .spyOn(repo, 'insertPendingPaymentOrder') + .mockImplementation(async (...args) => { + claimed = await uploads.claimForPurge({ + now: NOW, + pendingCreatedBefore: new Date('2100-01-01T00:00:00.000Z'), + purgingStartedBefore: NOW, + limit: 10, + }); + return insert(...args); + }); + + await service.createOrder(buyer.id, input(product, 25000, { slot })); + + expect(claimed).toEqual([]); + expect(await uploadStatuses()).toEqual([ + ['composite.png', 'ATTACHED'], + ['ref.png', 'ATTACHED'], + ]); + }); + + it('같은 키·같은 커스텀 입력의 재요청은 기존 주문을 돌려주고, 커스텀만 달라도 IDEMPOTENCY_KEY_INPUT_MISMATCH다', async () => { + const { buyer, product, slot } = await setup(); + const first = input(product, 25000, { slot }); + const created = await service.createOrder(buyer.id, first); + + await expect( + service.createOrder(buyer.id, { + ...first, + custom: { slot: { ...slot, texts: [...slot.texts].reverse() } }, + }), + ).resolves.toEqual(created); + await expect( + service.createOrder(buyer.id, { + ...first, + custom: { + slot: { + ...slot, + texts: [slot.texts[0], { ...slot.texts[1], valueText: '지수' }], + }, + }, + }), + ).rejects.toThrowDomain('IDEMPOTENCY_KEY_INPUT_MISMATCH'); + expect(await prisma.order.count()).toBe(1); + }); + + it('같은 키 재시도가 사전 조회를 지나 업로드 잠금에서 걸리면 내 주문을 replay한다', async () => { + const { buyer, product, slot } = await setup(); + const first = input(product, 25000, { slot }); + const created = await service.createOrder(buyer.id, first); + + const raceOnce = () => + jest + .spyOn(orderRepo, 'findOrderByIdempotencyKey') + .mockResolvedValueOnce(null); + raceOnce(); + await expect(service.createOrder(buyer.id, first)).resolves.toEqual( + created, + ); + raceOnce(); + await expect( + service.createOrder(buyer.id, { ...first, requestNote: '다른 메모' }), + ).rejects.toThrowDomain('IDEMPOTENCY_KEY_INPUT_MISMATCH'); + expect(await prisma.order.count()).toBe(1); + }); + + it('판매자가 설정을 바꿨으면(revision) 주문을 만들지 않고 업로드도 그대로 둔다', async () => { + const { buyer, product, slot } = await setup(); + await prisma.productCustomTemplate.update({ + where: { product_id: product.id }, + data: { revision: 5 }, + }); + + await expect( + service.createOrder(buyer.id, input(product, 25000, { slot })), + ).rejects.toThrowDomain('CUSTOM_TEMPLATE_CHANGED'); + expect(await prisma.order.count()).toBe(0); + expect(await uploadStatuses()).toEqual([ + ['composite.png', 'PENDING'], + ['ref.png', 'PENDING'], + ]); + }); + }); + + describe('3D', () => { + /** 정가 20000, 모양(하트 +1000)·크기(1호 +5000) 필수 그룹. */ + async function setup() { + const buyer = await makeBuyer(); + const product = await createProduct(prisma, { + store_id: await makeOpenStoreId(), + regular_price: 20000, + }); + await prisma.product.update({ + where: { id: product.id }, + data: { custom_mode: 'THREE_D' }, + }); + const items: bigint[] = []; + for (const [name, key, delta] of [ + ['모양', 'shape.heart', 1000], + ['크기', 'size.no1', 5000], + ] as const) { + const group = await prisma.productOptionGroup.create({ + data: { product_id: product.id, name, min_select: 1, max_select: 1 }, + }); + const item = await prisma.productOptionItem.create({ + data: { + option_group_id: group.id, + title: name, + price_delta: delta, + three_d_key: key, + }, + }); + items.push(item.id); + } + const renders: { kind: CustomImageKind; imageUrl: string }[] = []; + for (const kind of RENDER_KINDS) { + renders.push({ + kind, + imageUrl: await upload(buyer, 'RENDER', `${kind}.png`), + }); + } + const threeD: CreateOrderThreeDCustomInput = { + design: { + schemaVersion: 1, + basic: { shape: 'heart', size: 'no1', sheetColor: 'white' }, + top: [ + { + kind: 'TEXT', + x: 0.5, + y: 0.5, + size: 10, + effect: { type: 'none', intensity: 50 }, + text: '축하해', + color: '#ff0000', + }, + ], + side: [], + }, + renderImages: renders, + }; + return { + buyer, + product, + optionItemIds: items.map(String), + renders, + threeD, + }; + } + + it('디자인 JSON v1과 렌더 5장을 저장하고 윗면을 대표 이미지로 둔다(가격은 옵션 추가금만)', async () => { + const { buyer, product, optionItemIds, renders, threeD } = await setup(); + + const created = await service.createOrder( + buyer.id, + input(product, 26000, { threeD }, { optionItemIds }), + ); + + expect(created.totalPrice).toBe(26000); + const item = await prisma.orderItem.findFirstOrThrow({ + where: { order_id: BigInt(created.orderId) }, + include: { + custom_design: true, + custom_images: { orderBy: { kind: 'asc' } }, + custom_texts: true, + free_edits: true, + }, + }); + expect(item).toMatchObject({ + custom_mode_snapshot: 'THREE_D', + custom_base_image_url_snapshot: null, + custom_preview_image_url: renders[0].imageUrl, + custom_texts: [], + free_edits: [], + custom_design: { + schema_version: 1, + design_json: { + schemaVersion: 1, + basic: { + shape: 'heart', + size: 'no1', + design: null, + flavor: null, + sheetColor: 'white', + }, + top: [{ kind: 'TEXT', text: '축하해', color: '#FF0000' }], + side: [], + }, + }, + }); + expect( + item.custom_images.map((image) => [image.kind, image.image_url]), + ).toEqual(renders.map((r) => [r.kind, r.imageUrl])); + expect( + await prisma.orderCustomUpload.count({ where: { status: 'ATTACHED' } }), + ).toBe(5); + }); + + it('고른 옵션과 디자인이 다르면 CUSTOM_3D_OPTIONS_CHANGED다', async () => { + const { buyer, product, optionItemIds, threeD } = await setup(); + threeD.design.basic.size = 'mini'; + + await expect( + service.createOrder( + buyer.id, + input(product, 26000, { threeD }, { optionItemIds }), + ), + ).rejects.toThrowDomain('CUSTOM_3D_OPTIONS_CHANGED'); + expect(await prisma.order.count()).toBe(0); + }); + + it('3D 상품을 커스텀 없이 주문하면 CUSTOM_INPUT_REQUIRED다', async () => { + const { buyer, product, optionItemIds } = await setup(); + + await expect( + service.createOrder(buyer.id, { + ...input(product, 26000, {}, { optionItemIds }), + custom: undefined, + }), + ).rejects.toThrowDomain('CUSTOM_INPUT_REQUIRED'); + }); + }); +}); diff --git a/src/features/order/services/order-checkout.service.spec.ts b/src/features/order/services/order-checkout.service.spec.ts index 94bd0a2e..85cd9a87 100644 --- a/src/features/order/services/order-checkout.service.spec.ts +++ b/src/features/order/services/order-checkout.service.spec.ts @@ -15,6 +15,7 @@ import { pendingPaymentLockName } from '@/features/order/repositories/order-pend import { OrderRepository } from '@/features/order/repositories/order.repository'; import { PaymentSettingRepository } from '@/features/order/repositories/payment-setting.repository'; import { OrderCheckoutService } from '@/features/order/services/order-checkout.service'; +import { OrderCustomizationService } from '@/features/order/services/order-customization.service'; import { OrderEventsService } from '@/features/order/services/order-events.service'; import { ProductRepository } from '@/features/product'; import { StorePickupScheduleService } from '@/features/store'; @@ -67,6 +68,7 @@ describe('OrderCheckoutService (real DB)', () => { const { module, prisma: p } = await createTestingModuleWithRealDb({ providers: [ OrderCheckoutService, + OrderCustomizationService, OrderRepository, OrderCustomUploadRepository, ...s3TestProviders(), diff --git a/src/features/order/services/order-checkout.service.ts b/src/features/order/services/order-checkout.service.ts index 45fb0d37..fed03626 100644 --- a/src/features/order/services/order-checkout.service.ts +++ b/src/features/order/services/order-checkout.service.ts @@ -1,6 +1,6 @@ import { Injectable } from '@nestjs/common'; -import { DomainException } from '@/common/errors/error-catalog'; +import { DomainException, type ErrorCode } from '@/common/errors/error-catalog'; import { ClockService } from '@/common/providers/clock.service'; import { RandomService } from '@/common/providers/random.service'; import { parseId } from '@/common/utils/id-parser'; @@ -9,14 +9,17 @@ import { uniqueConstraintName } from '@/common/utils/prisma-error'; import { buildRegionLabel } from '@/common/utils/region-label'; import { codePointLength } from '@/common/utils/text-cleaner'; import { evaluateActiveUserAccount } from '@/features/auth'; +import { CUSTOM_UPLOAD_PURPOSES } from '@/features/order/constants/order-custom-upload-purposes'; import type { CreateOrderInput } from '@/features/order/dto/inputs/create-order.input'; import { OrderCustomUploadRepository } from '@/features/order/repositories/order-custom-upload.repository'; import { OrderRepository, type CreatedOrderRow, type CreatePendingPaymentOrderArgs, + type CreatePendingPaymentOrderResult, } from '@/features/order/repositories/order.repository'; import { PaymentSettingRepository } from '@/features/order/repositories/payment-setting.repository'; +import { OrderCustomizationService } from '@/features/order/services/order-customization.service'; import { hashCreateOrderInput } from '@/features/order/services/order-input-hash.helper'; import { toOrderPaymentOutput } from '@/features/order/services/order-payment-mappers.helper'; import type { CreateOrderOutput } from '@/features/order/types/create-order-output.type'; @@ -27,10 +30,7 @@ import { type OrderCustomUploadPurpose, } from '@/generated/prisma/client'; import { S3Service } from '@/global/storage/s3.service'; -import type { - CreateUploadUrlOutput, - UploadPurpose, -} from '@/global/storage/types/storage.types'; +import type { CreateUploadUrlOutput } from '@/global/storage/types/storage.types'; // 0/O·1/I 등 혼동 문자를 뺀 대문자 영숫자. 주문번호 무작위부에 사용. const ORDER_NUMBER_ALPHABET = 'ABCDEFGHJKMNPQRSTUVWXYZ23456789'; @@ -47,11 +47,16 @@ const PAYMENT_WINDOW_MS = 60 * 60_000; /** 은행 입금자명과 대조하는 값이라 자르지 않고 입력을 요구한다. */ const MAX_DEPOSITOR_NAME_LENGTH = 20; -const CUSTOM_UPLOAD_PURPOSES = { - RENDER: 'ORDER_CUSTOM_RENDER', - COMPOSITE: 'ORDER_CUSTOM_COMPOSITE', - REFERENCE: 'ORDER_CUSTOM_REFERENCE', -} as const satisfies Record; +/** tx 안 잠금 재검사의 거절 결과 → 같은 키 replay가 아니면 내는 코드. */ +const LOCKED_REJECT_CODES = { + 'capacity-exceeded': 'PICKUP_NOT_AVAILABLE', + 'pending-limit': 'PENDING_PAYMENT_LIMIT_EXCEEDED', + 'upload-invalid': 'CUSTOM_UPLOAD_INVALID', + 'upload-expired': 'CUSTOM_UPLOAD_EXPIRED', +} as const satisfies Record< + Exclude, + ErrorCode +>; interface ResolvedOptionSelection { optionGroupId: bigint; @@ -59,6 +64,7 @@ interface ResolvedOptionSelection { groupNameSnapshot: string; optionTitleSnapshot: string; optionPriceDeltaSnapshot: number; + threeDKey: string | null; } @Injectable() @@ -72,6 +78,7 @@ export class OrderCheckoutService { private readonly paymentSettings: PaymentSettingRepository, private readonly customUploads: OrderCustomUploadRepository, private readonly s3: S3Service, + private readonly customization: OrderCustomizationService, ) {} /** @@ -142,6 +149,13 @@ export class OrderCheckoutService { } const selections = this.resolveOptionSelections(product, optionItemIds); + const custom = this.customization.resolve({ + product, + selectedThreeDKeys: selections.map((selection) => selection.threeDKey), + quantity, + custom: input.custom, + accountId, + }); const buyer = this.resolveBuyerInfo(buyerProfile, input); const depositorName = resolveDepositorName(input.depositorName, buyer.name); @@ -241,6 +255,7 @@ export class OrderCheckoutService { quantity, itemSubtotalPrice, options: selections, + custom, }, }); @@ -283,6 +298,7 @@ export class OrderCheckoutService { groupNameSnapshot: group.name, optionTitleSnapshot: item.title, optionPriceDeltaSnapshot: item.price_delta, + threeDKey: item.three_d_key, }); groupIdByItemId.set(item.id.toString(), group.id.toString()); } @@ -358,16 +374,14 @@ export class OrderCheckoutService { if (created === 'lock-timeout') { throw new DomainException('CONCURRENT_REQUEST'); } - if (created === 'capacity-exceeded' || created === 'pending-limit') { - // 트랜잭션 안 잠금 재검사에서 거절됐다. 자리를 채운 것이 같은 키의 내 주문(응답 유실 재시도)일 수 있어 - // 거절 전에 replay를 확인한다. + if (typeof created === 'string') { + // 트랜잭션 안 잠금 재검사에서 거절됐다. 자리·건수를 채우거나 업로드를 붙인 것이 같은 키의 내 주문 + // (응답 유실 재시도)일 수 있어 거절 전에 replay를 확인한다. return this.replayOrReject( args.accountId, args.idempotencyKey, args.idempotencyInputHash, - created === 'capacity-exceeded' - ? 'PICKUP_NOT_AVAILABLE' - : 'PENDING_PAYMENT_LIMIT_EXCEEDED', + LOCKED_REJECT_CODES[created], ); } return created; @@ -415,7 +429,7 @@ export class OrderCheckoutService { accountId: bigint, idempotencyKey: string, inputHash: string, - rejectCode: 'PICKUP_NOT_AVAILABLE' | 'PENDING_PAYMENT_LIMIT_EXCEEDED', + rejectCode: ErrorCode, ): Promise { const existing = await this.orderRepo.findOrderByIdempotencyKey( accountId, diff --git a/src/features/order/services/order-customization.service.spec.ts b/src/features/order/services/order-customization.service.spec.ts new file mode 100644 index 00000000..1bb0bae1 --- /dev/null +++ b/src/features/order/services/order-customization.service.spec.ts @@ -0,0 +1,813 @@ +import { Test } from '@nestjs/testing'; + +import type { + CreateOrderCustomInput, + CreateOrderFreeEditInput, + CreateOrderSlotCustomInput, + CreateOrderThreeDCustomInput, +} from '@/features/order/dto/inputs/create-order-custom.input'; +import { OrderCustomizationService } from '@/features/order/services/order-customization.service'; +import type { ProductDetailRow } from '@/features/product'; +import type { CustomImageKind, CustomMode } from '@/generated/prisma/client'; +import type { UploadPurpose } from '@/global/storage/types/storage.types'; +import { + FOREIGN_UPLOAD_URL, + ownedUploadUrl, + s3TestProviders, +} from '@/test/storage/s3-test.helper'; + +const ACCOUNT = 7n; +const BASE_IMAGE = 'https://i.example/base.png'; +const url = (purpose: UploadPurpose, name: string) => + ownedUploadUrl(purpose, ACCOUNT, name); +const keyOf = (u: string) => new URL(u).pathname.slice(1); +const COMPOSITE = url('ORDER_CUSTOM_COMPOSITE', 'composite.png'); +const RENDER_KINDS = [ + 'THREE_D_TOP', + 'THREE_D_FRONT', + 'THREE_D_BACK', + 'THREE_D_LEFT', + 'THREE_D_RIGHT', +] as const satisfies readonly CustomImageKind[]; +const renderUrl = (kind: CustomImageKind) => + url('ORDER_CUSTOM_RENDER', `${kind}.png`); + +type Template = NonNullable; +type Token = Template['text_tokens'][number]; +type OptionGroup = ProductDetailRow['option_groups'][number]; + +function token(id: bigint, overrides: Partial = {}): Token { + return { + id, + token_key: `slot${id}`, + label: `자리${id}`, + default_text: '축하해', + max_length: 20, + is_required: true, + pos_x: 1000, + pos_y: 2000, + width: 8000, + height: 1500, + text_color: '#FF0000', + text_align: 'LEFT', + sort_order: Number(id), + ...overrides, + }; +} + +function product( + mode: CustomMode, + overrides: Partial = {}, +): ProductDetailRow { + return { + id: 1n, + store_id: 1n, + name: '케이크', + description: null, + purchase_notice: null, + regular_price: 30000, + sale_price: null, + currency: 'KRW', + preparation_time_minutes: 180, + custom_mode: mode, + custom_template: { + base_image_url: BASE_IMAGE, + free_edit_enabled: true, + revision: 3, + deleted_at: null, + text_tokens: [token(11n), token(12n, { is_required: false })], + }, + store: { + store_name: '매장', + address_city: null, + address_neighborhood: null, + region: null, + }, + images: [], + option_groups: [ + group(1n, ['shape.heart', 'shape.circle']), + group(2n, ['size.mini', 'size.no1']), + group(3n, ['flavor.cream'], { is_required: false, min_select: 0 }), + ], + ...overrides, + }; +} + +function group( + id: bigint, + keys: string[], + overrides: Partial = {}, +): OptionGroup { + return { + id, + name: `그룹${id}`, + description: null, + is_active: true, + is_required: true, + min_select: 1, + max_select: 1, + sort_order: Number(id), + option_items: keys.map((key, index) => ({ + id: id * 100n + BigInt(index), + title: key, + description: null, + image_url: null, + price_delta: 0, + sort_order: index, + is_active: true, + three_d_key: key, + })), + ...overrides, + }; +} + +function template(overrides: Partial