From bf1495497228c9134c8c3ffa3fc95e723733f575 Mon Sep 17 00:00:00 2001 From: chanwoo7 Date: Thu, 19 Nov 2026 05:52:27 +0900 Subject: [PATCH 1/2] =?UTF-8?q?feat:=20=EC=B1=84=ED=8C=85=20=EC=9D=B4?= =?UTF-8?q?=EB=AF=B8=EC=A7=80=20=EC=B2=A8=EB=B6=80=EC=99=80=20=EC=A3=BC?= =?UTF-8?q?=EB=AC=B8=20=EC=B9=B4=EB=93=9C=20=EB=A9=94=EC=8B=9C=EC=A7=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 채팅에서 구매자·판매자가 사진 1장(10MB)을 보내고, 구매자가 '이 주문 문의'로 주문 카드를 보낼 수 있게 한다. 입금 확인 전 주문은 판매자에게 보이지 않으므로 카드로 보낼 수 없다. 판매자 정지 등으로 숨긴 매장도 그 매장에 진행 중인 주문이 있는 구매자는 문의할 수 있게 해 주문 문의 경로를 남긴다(그 밖의 숨김 매장은 지금처럼 STORE_NOT_FOUND). 변경점 - 스키마·마이그레이션(conversation_image_order_card): ConversationBodyFormat 끝에 IMAGE·ORDER_CARD, 메시지에 image_url과 주문 카드 스냅샷(order_card_order_id·주문번호·상품명·썸네일·픽업 일시, 주문 FK 없음). nullable 컬럼 추가와 enum 덧붙임뿐이라 기존 메시지 이행 없음 - 업로드: TS UploadPurpose·UPLOAD_POLICIES에 CONVERSATION_IMAGE(conversation-images, 10MB, JPEG·PNG·WebP), SDL UploadPurpose와 판매자 허용 목록에 추가. 관리자 업로드는 계속 거절. 판매자 업로드 설명의 크기 상한을 용도별로 고침 - 구매자: createConversationImageUploadUrl(contentType, contentLength), sendConversationImageMessage(input: { storeId, imageUrl }), sendConversationOrderCard(orderId). 카드는 본인 주문이 아니면 ORDER_NOT_FOUND, submitted_at이 없으면 ORDER_INQUIRY_NOT_AVAILABLE - 판매자: sellerSendConversationMessage IMAGE + imageUrl(없으면 IMAGE_URL_REQUIRED, 본인 발급 URL 아니면 INVALID_IMAGE_URL), ORDER_CARD는 INVALID_BODY_FORMAT. DTO는 SDL enum 전체를 받고 service가 거절한다 - 대체 문구('사진을 보냈습니다.'·'주문 문의: {상품명} ({주문번호})')를 body_text에 저장해 목록 미리보기·판매자 BUYER_MESSAGE 푸시가 그대로 쓴다 - 출력·구독: ConversationMessage·SellerConversationMessage에 imageUrl·orderCard { orderId orderNumber productName thumbnailUrl pickupAt } - order: OrderInquiryRepository(findOrderCardSource·existsInProgressOrderAtStore)를 배럴로 공개. 썸네일은 커스텀 대표 이미지 우선, 없으면 상품 대표 이미지 - store: findInquiryStore가 숨김 매장도 is_active와 함께 돌려주고, 허용 판정은 conversation이 한다(문의 컨텍스트·텍스트·FAQ·이미지·카드 공통) - 에러: IMAGE_URL_REQUIRED, ORDER_INQUIRY_NOT_AVAILABLE('입금이 확인된 뒤 문의할 수 있어요.') 테스트 - 구매자 이미지: 저장·푸시 미리보기, 소유 우회 5건(다른 계정·다른 용도·%2e·외부·2048자 초과), 공백 URL, presign 10MB·0·형식·USER_ONLY - 주문 카드: 스냅샷·썸네일 우선순위·푸시 미리보기, 본인·삭제·없는 주문, 입금 대기·입금 전 취소 거절, 입금 확인 뒤 취소 허용, 숨김 매장 진행 중/끝난 주문 - 숨김 매장 문의: 진행 중 주문이면 컨텍스트·텍스트·FAQ 허용, 끝난·취소 주문만이면 거절, 다른 구매자·다른 매장·삭제 매장 거절, 진행 중 상태 7종 표 - 판매자 IMAGE 저장·필수·소유 우회 3건, ORDER_CARD 거절, 목록 카드 출력 - S3 presign·소유 판정 표에 CONVERSATION_IMAGE, 관리자 DTO 거절 반증, enum-sdl-sync에 UploadPurpose 입력 쌍 추가(ConversationBodyFormat은 기존 쌍이 대조) - 반증: 숨김 허용·입금 전·URL 길이·ORDER_CARD 가드를 지우면 해당 6건이 실패함을 확인하고 되돌렸다 --- .../migration.sql | 9 + prisma/schema.prisma | 11 + src/common/errors/error-catalog.ts | 8 + .../constants/conversation.constants.ts | 5 + .../conversation/conversation-inquiry.graphql | 38 +- .../conversation/conversation-seller.graphql | 17 +- .../conversation/conversation.module.ts | 5 +- .../conversation/conversation.types.graphql | 24 ++ ...er-send-conversation-message.input.spec.ts | 20 ++ .../seller-send-conversation-message.input.ts | 14 +- ...d-conversation-image-message.input.spec.ts | 25 ++ .../send-conversation-image-message.input.ts | 11 + .../repositories/conversation.repository.ts | 26 ++ .../conversation-center.resolver.spec.ts | 4 + .../conversation-inquiry-mutation.resolver.ts | 36 ++ .../conversation-inquiry.resolver.spec.ts | 45 +++ .../conversation-seller.resolver.spec.ts | 2 + .../conversation-attachment.helper.ts | 28 ++ ...conversation-center-mappers.helper.spec.ts | 13 + .../conversation-center-mappers.helper.ts | 5 +- ...conversation-events-mappers.helper.spec.ts | 33 +- .../conversation-events-mappers.helper.ts | 7 + .../conversation-events.service.spec.ts | 26 +- ...onversation-inquiry-mappers.helper.spec.ts | 40 +++ .../conversation-inquiry-mappers.helper.ts | 53 ++- .../conversation-inquiry.service.spec.ts | 338 +++++++++++++++++- .../services/conversation-inquiry.service.ts | 119 +++++- .../conversation-seller.service.spec.ts | 131 +++++++ .../services/conversation-seller.service.ts | 116 +++--- .../conversation-subscription.service.spec.ts | 4 + .../types/conversation-output.type.ts | 16 + .../types/conversation-seller-output.type.ts | 11 +- src/features/order/index.ts | 5 + src/features/order/order.module.ts | 4 + .../order-inquiry.repository.spec.ts | 192 ++++++++++ .../repositories/order-inquiry.repository.ts | 75 ++++ .../admin-create-upload-url.input.spec.ts | 28 +- .../seller-create-upload-url.input.spec.ts | 2 +- .../inputs/seller-create-upload-url.input.ts | 6 +- .../product/product-seller-upload.graphql | 4 +- .../product/product-upload.types.graphql | 7 +- ...tore-catalog-query.repository.interface.ts | 4 +- .../store-catalog-query.repository.spec.ts | 16 +- .../store-catalog-query.repository.ts | 5 +- .../storage/constants/storage.constants.ts | 6 + src/global/storage/s3.service.spec.ts | 2 + src/global/storage/types/storage.types.ts | 3 +- src/test/enum-sdl-sync.spec.ts | 7 + 48 files changed, 1488 insertions(+), 118 deletions(-) create mode 100644 prisma/migrations/20261118203227_conversation_image_order_card/migration.sql create mode 100644 src/features/conversation/dto/inputs/send-conversation-image-message.input.spec.ts create mode 100644 src/features/conversation/dto/inputs/send-conversation-image-message.input.ts create mode 100644 src/features/conversation/services/conversation-attachment.helper.ts create mode 100644 src/features/order/repositories/order-inquiry.repository.spec.ts create mode 100644 src/features/order/repositories/order-inquiry.repository.ts diff --git a/prisma/migrations/20261118203227_conversation_image_order_card/migration.sql b/prisma/migrations/20261118203227_conversation_image_order_card/migration.sql new file mode 100644 index 00000000..9ba1e316 --- /dev/null +++ b/prisma/migrations/20261118203227_conversation_image_order_card/migration.sql @@ -0,0 +1,9 @@ +-- 채팅 이미지·주문 카드 메시지. 새 컬럼은 모두 nullable이고 enum은 끝에 덧붙여 기존 TEXT·HTML 메시지는 그대로다(백필 없음). +-- AlterTable +ALTER TABLE `store_conversation_message` ADD COLUMN `image_url` VARCHAR(2048) NULL, + ADD COLUMN `order_card_order_id` BIGINT UNSIGNED NULL, + ADD COLUMN `order_card_order_number` VARCHAR(30) NULL, + ADD COLUMN `order_card_pickup_at` DATETIME(3) NULL, + ADD COLUMN `order_card_product_name` VARCHAR(200) NULL, + ADD COLUMN `order_card_thumbnail_url` VARCHAR(2048) NULL, + MODIFY `body_format` ENUM('TEXT', 'HTML', 'IMAGE', 'ORDER_CARD') NOT NULL DEFAULT 'TEXT'; diff --git a/prisma/schema.prisma b/prisma/schema.prisma index 27ee7339..2ba0a173 100644 --- a/prisma/schema.prisma +++ b/prisma/schema.prisma @@ -177,6 +177,8 @@ enum ConversationSenderType { enum ConversationBodyFormat { TEXT HTML + IMAGE + ORDER_CARD } enum ReviewMediaType { @@ -1858,8 +1860,17 @@ model StoreConversationMessage { sender_account_id BigInt? @db.UnsignedBigInt body_format ConversationBodyFormat @default(TEXT) + // IMAGE·ORDER_CARD는 목록 미리보기·푸시에 쓰는 대체 문구를 담는다 body_text String? @db.Text body_html String? @db.Text + image_url String? @db.VarChar(2048) + + // 주문 카드는 보낸 시점 값으로 남긴다. 주문이 바뀌거나 지워져도 대화 이력이 그대로 보이게 FK를 두지 않는다 + order_card_order_id BigInt? @db.UnsignedBigInt + order_card_order_number String? @db.VarChar(30) + order_card_product_name String? @db.VarChar(200) + order_card_thumbnail_url String? @db.VarChar(2048) + order_card_pickup_at DateTime? @db.DateTime(3) created_at DateTime @default(now()) @db.DateTime(3) deleted_at DateTime? @db.DateTime(3) diff --git a/src/common/errors/error-catalog.ts b/src/common/errors/error-catalog.ts index f93c23ad..288f5c50 100644 --- a/src/common/errors/error-catalog.ts +++ b/src/common/errors/error-catalog.ts @@ -660,6 +660,14 @@ export const ERROR_CATALOG = { status: HttpStatus.BAD_REQUEST, message: '본문 형식이 올바르지 않습니다.', }, + IMAGE_URL_REQUIRED: { + status: HttpStatus.BAD_REQUEST, + message: 'IMAGE 형식에는 imageUrl이 필요합니다.', + }, + ORDER_INQUIRY_NOT_AVAILABLE: { + status: HttpStatus.BAD_REQUEST, + message: '입금이 확인된 뒤 문의할 수 있어요.', + }, // ── 관리자 ADMIN_ONLY: { status: HttpStatus.FORBIDDEN, diff --git a/src/features/conversation/constants/conversation.constants.ts b/src/features/conversation/constants/conversation.constants.ts index 22cfee1b..c3b75bde 100644 --- a/src/features/conversation/constants/conversation.constants.ts +++ b/src/features/conversation/constants/conversation.constants.ts @@ -10,3 +10,8 @@ export const DEFAULT_GREETING_TEMPLATE = export const MAX_INQUIRY_BODY_TEXT_LENGTH = 2000; // store.greeting_message VARCHAR(500)과 동일 상한 export const MAX_CONVERSATION_BODY_HTML_LENGTH = 100000; + +// 이미지 메시지 대체 문구. 목록 미리보기·판매자 푸시가 본문 대신 이 값을 쓴다. +export const CONVERSATION_IMAGE_ALT_TEXT = '사진을 보냈습니다.'; +// image_url VARCHAR(2048)과 동일 상한 +export const MAX_CONVERSATION_IMAGE_URL_LENGTH = 2048; diff --git a/src/features/conversation/conversation-inquiry.graphql b/src/features/conversation/conversation-inquiry.graphql index 04bb5e55..211c89de 100644 --- a/src/features/conversation/conversation-inquiry.graphql +++ b/src/features/conversation/conversation-inquiry.graphql @@ -3,6 +3,7 @@ extend type Query { 문의 채팅 진입 컨텍스트(구매자). 매장 프로필·상담시간·치환 완료 인사말·질문 칩을 한 번에 내려준다. 아직 대화가 없어도 조회 가능하며 그 경우 conversationId는 null. 로그인 필수. + 숨김 매장은 그 매장에 진행 중인 주문이 있는 구매자만 조회할 수 있다(아니면 STORE_NOT_FOUND). 문의 전송도 같다. """ storeInquiryContext(storeId: ID!): StoreInquiryContext! } @@ -20,6 +21,29 @@ extend type Mutation { 로그인 필수. """ sendConversationFaqMessage(input: SendConversationFaqMessageInput!): ConversationMessagesPayload! + """ + 채팅 이미지 업로드용 Presigned URL 발급(구매자). uploadUrl로 PUT한 뒤 publicUrl을 sendConversationImageMessage에 넣는다. + JPEG·PNG·WebP, 1바이트 이상 10MB 이하(아니면 INVALID_CONTENT_TYPE·INVALID_CONTENT_LENGTH·FILE_TOO_LARGE). + 로그인 필수. + """ + createConversationImageUploadUrl( + """파일 MIME 타입(image/jpeg·image/png·image/webp).""" + contentType: String! + """파일 크기(바이트, 1 이상 10MB 이하).""" + contentLength: Int! + ): UploadUrl! + """ + 구매자 이미지 메시지 전송(메시지당 1장). 대화가 없으면 sendConversationMessage처럼 생성하고 인사말을 먼저 저장한다. + imageUrl이 이 계정에 createConversationImageUploadUrl로 발급된 URL이 아니면 INVALID_IMAGE_URL, 공백이면 + IMAGE_URL_REQUIRED다. 로그인 필수. + """ + sendConversationImageMessage(input: SendConversationImageMessageInput!): ConversationMessagesPayload! + """ + 주문 카드 전송(구매자). 주문의 매장과의 대화에 보낸 시점의 주문 스냅샷을 카드로 남긴다(대화가 없으면 생성). + 본인 주문이 아니면 ORDER_NOT_FOUND, 입금 확인 전(판매자가 볼 수 없는) 주문이면 ORDER_INQUIRY_NOT_AVAILABLE, + 매장이 숨김이고 그 매장에 진행 중인 주문이 없으면 STORE_NOT_FOUND다. 로그인 필수. + """ + sendConversationOrderCard(orderId: ID!): ConversationMessagesPayload! } """문의 채팅 진입 컨텍스트""" @@ -66,10 +90,14 @@ type ConversationMessage { senderType: ConversationSenderType! """본문 형식. 읽어야 할 본문 필드를 가리킨다.""" bodyFormat: ConversationBodyFormat! - """평문 본문. bodyFormat이 TEXT면 이 값을 쓴다.""" + """평문 본문. bodyFormat이 TEXT면 이 값을 쓴다. IMAGE·ORDER_CARD는 대체 문구가 들어 있다.""" bodyText: String """서식 본문. bodyFormat이 HTML이면 이 값을 쓴다.""" bodyHtml: String + """이미지 URL. bodyFormat이 IMAGE면 채워진다.""" + imageUrl: String + """주문 카드. bodyFormat이 ORDER_CARD면 채워진다.""" + orderCard: ConversationOrderCard """발송 시각. 메시지 스트림 정렬은 id 기준이다.""" createdAt: DateTime! } @@ -90,6 +118,14 @@ input SendConversationMessageInput { bodyText: String! } +"""구매자 이미지 메시지 전송 입력""" +input SendConversationImageMessageInput { + """문의할 매장 ID. 대화방이 없으면 이 호출에서 생성된다.""" + storeId: ID! + """createConversationImageUploadUrl이 이 계정에 발급한 publicUrl.""" + imageUrl: String! +} + """질문 칩(FAQ) 전송 입력""" input SendConversationFaqMessageInput { """문의할 매장 ID. 대화방이 없으면 이 호출에서 생성된다.""" diff --git a/src/features/conversation/conversation-seller.graphql b/src/features/conversation/conversation-seller.graphql index f08ced36..6f96999b 100644 --- a/src/features/conversation/conversation-seller.graphql +++ b/src/features/conversation/conversation-seller.graphql @@ -15,6 +15,7 @@ extend type Query { extend type Mutation { """ 판매자 메시지를 발송한다. 판매자 로그인 필수. SELLER 계정이 아니면 FORBIDDEN, 매장을 보유하지 않으면 NOT_FOUND. + bodyFormat은 TEXT·HTML·IMAGE이고 ORDER_CARD는 INVALID_BODY_FORMAT이다(주문 카드는 구매자만 보낸다). """ sellerSendConversationMessage( input: SellerSendConversationMessageInput! @@ -118,6 +119,14 @@ type SellerConversationMessage { """ bodyHtml: String """ + 이미지 URL. bodyFormat이 IMAGE면 채워진다(bodyText에는 대체 문구 '사진을 보냈습니다.'). + """ + imageUrl: String + """ + 주문 카드. bodyFormat이 ORDER_CARD(구매자가 보낸 카드)면 채워진다. orderId로 주문 상세를 연다. + """ + orderCard: ConversationOrderCard + """ 발송 시각. """ createdAt: DateTime! @@ -152,7 +161,8 @@ type SellerConversationMessageConnection { input SellerSendConversationMessageInput { conversationId: ID! """ - 본문 형식. 이 값에 해당하는 본문 필드가 필수다(다른 쪽을 함께 넘기면 그대로 저장된다). + 본문 형식. 이 값에 해당하는 본문 필드가 필수다(TEXT·HTML은 다른 쪽을 함께 넘기면 그대로 저장된다). + IMAGE는 imageUrl만 저장하고 본문은 대체 문구로 채운다. ORDER_CARD는 INVALID_BODY_FORMAT이다. """ bodyFormat: ConversationBodyFormat! """ @@ -163,4 +173,9 @@ input SellerSendConversationMessageInput { 서식 본문(최대 100000자). bodyFormat이 HTML이면 필수. """ bodyHtml: String + """ + 이미지 URL. bodyFormat이 IMAGE면 필수(없으면 IMAGE_URL_REQUIRED)이고 sellerCreateUploadUrl(CONVERSATION_IMAGE)로 + 이 계정에 발급된 publicUrl이어야 한다(아니면 INVALID_IMAGE_URL). 다른 형식에서는 무시한다. + """ + imageUrl: String } diff --git a/src/features/conversation/conversation.module.ts b/src/features/conversation/conversation.module.ts index 53532264..44f9a90f 100644 --- a/src/features/conversation/conversation.module.ts +++ b/src/features/conversation/conversation.module.ts @@ -14,13 +14,14 @@ import { ConversationEventsService } from '@/features/conversation/services/conv import { ConversationInquiryService } from '@/features/conversation/services/conversation-inquiry.service'; import { SellerConversationService } from '@/features/conversation/services/conversation-seller.service'; import { ConversationSubscriptionService } from '@/features/conversation/services/conversation-subscription.service'; +import { OrderModule } from '@/features/order'; import { OutboxModule } from '@/features/outbox'; import { StoreModule } from '@/features/store'; @Module({ // 판매자 컨텍스트·catalog 읽기 포트(StoreModule), 감사 기록(AuditLogModule), 구매자 상태 판정(AuthModule), - // 구매자 메시지 이벤트 발행(OutboxModule) - imports: [StoreModule, AuditLogModule, AuthModule, OutboxModule], + // 구매자 메시지 이벤트 발행(OutboxModule), 주문 카드 원천·숨김 매장 문의 판정(OrderModule) + imports: [StoreModule, AuditLogModule, AuthModule, OutboxModule, OrderModule], providers: [ ConversationRepository, ConversationEventsService, diff --git a/src/features/conversation/conversation.types.graphql b/src/features/conversation/conversation.types.graphql index ff308fa1..fefcff23 100644 --- a/src/features/conversation/conversation.types.graphql +++ b/src/features/conversation/conversation.types.graphql @@ -17,4 +17,28 @@ enum ConversationBodyFormat { 서버 측 sanitize는 아직 적용돼 있지 않다. """ HTML + """ + 이미지 1장. imageUrl을 그리고, bodyText에는 대체 문구('사진을 보냈습니다.')가 있다. + """ + IMAGE + """ + 주문 카드(구매자만 보낸다). orderCard를 그리고, bodyText에는 대체 문구('주문 문의: {상품명} ({주문번호})')가 있다. + """ + ORDER_CARD +} + +""" +채팅 주문 카드. 구매자가 보낸 시점의 주문 스냅샷이라 이후 주문이 바뀌거나 지워져도 그대로 보인다. +판매자 앱은 orderId로 주문 상세를 연다. +""" +type ConversationOrderCard { + orderId: ID! + """주문번호.""" + orderNumber: String! + """상품명(주문 시점 스냅샷).""" + productName: String! + """썸네일. 커스텀 주문이면 커스텀 대표 이미지(3D 윗면·슬롯형 합성), 아니면 상품 대표 이미지. 둘 다 없으면 null.""" + thumbnailUrl: String + """보낸 시점의 픽업 일시.""" + pickupAt: DateTime! } diff --git a/src/features/conversation/dto/inputs/seller-send-conversation-message.input.spec.ts b/src/features/conversation/dto/inputs/seller-send-conversation-message.input.spec.ts index afc73928..7978dd49 100644 --- a/src/features/conversation/dto/inputs/seller-send-conversation-message.input.spec.ts +++ b/src/features/conversation/dto/inputs/seller-send-conversation-message.input.spec.ts @@ -28,6 +28,26 @@ describe('SellerSendConversationMessageInput', () => { expect(await validate(dto)).toHaveLength(0); }); + // ORDER_CARD는 DTO를 통과시켜 service가 INVALID_BODY_FORMAT으로 거절한다 + it.each(['IMAGE', 'ORDER_CARD'])('%s 형식 통과', async (bodyFormat) => { + const dto = build({ + conversationId: '1', + bodyFormat, + imageUrl: 'https://example.com/a.jpg', + }); + expect(await validate(dto)).toHaveLength(0); + }); + + it('문자열이 아닌 imageUrl 거절', async () => { + const dto = build({ + conversationId: '1', + bodyFormat: 'IMAGE', + imageUrl: 1, + }); + const errors = await validate(dto); + expect(errors[0].property).toBe('imageUrl'); + }); + it('알 수 없는 bodyFormat 거절', async () => { const dto = build({ conversationId: '1', diff --git a/src/features/conversation/dto/inputs/seller-send-conversation-message.input.ts b/src/features/conversation/dto/inputs/seller-send-conversation-message.input.ts index 517836b9..99ec19a0 100644 --- a/src/features/conversation/dto/inputs/seller-send-conversation-message.input.ts +++ b/src/features/conversation/dto/inputs/seller-send-conversation-message.input.ts @@ -1,14 +1,16 @@ import { IsIn, IsOptional, IsString } from 'class-validator'; -const BODY_FORMATS = ['TEXT', 'HTML'] as const; -type ConversationBodyFormat = (typeof BODY_FORMATS)[number]; +import { ConversationBodyFormat } from '@/generated/prisma/client'; -/** bodyFormat에 따라 bodyText/bodyHtml 중 하나가 필수라는 invariant는 service에서 검증한다(class-validator로 표현하기 어렵다). */ +/** + * 형식별 필수 필드·판매자가 보낼 수 없는 형식(ORDER_CARD)은 service가 판정한다. DTO는 SDL enum 전체를 받아야 + * ORDER_CARD가 VALIDATION_FAILED가 아니라 INVALID_BODY_FORMAT으로 거절된다. + */ export class SellerSendConversationMessageInput { @IsString() conversationId!: string; - @IsIn(BODY_FORMATS) + @IsIn(Object.values(ConversationBodyFormat)) bodyFormat!: ConversationBodyFormat; @IsOptional() @@ -18,4 +20,8 @@ export class SellerSendConversationMessageInput { @IsOptional() @IsString() bodyHtml?: string; + + @IsOptional() + @IsString() + imageUrl?: string; } diff --git a/src/features/conversation/dto/inputs/send-conversation-image-message.input.spec.ts b/src/features/conversation/dto/inputs/send-conversation-image-message.input.spec.ts new file mode 100644 index 00000000..9ce98505 --- /dev/null +++ b/src/features/conversation/dto/inputs/send-conversation-image-message.input.spec.ts @@ -0,0 +1,25 @@ +import 'reflect-metadata'; + +import { plainToInstance } from 'class-transformer'; +import { validate } from 'class-validator'; + +import { SendConversationImageMessageInput } from '@/features/conversation/dto/inputs/send-conversation-image-message.input'; + +function build(plain: object): SendConversationImageMessageInput { + return plainToInstance(SendConversationImageMessageInput, plain); +} + +describe('SendConversationImageMessageInput', () => { + it('storeId·imageUrl 정상 조합 허용', async () => { + const dto = build({ storeId: '1', imageUrl: 'https://example.com/a.jpg' }); + expect(await validate(dto)).toHaveLength(0); + }); + + it.each([ + ['storeId 누락', { imageUrl: 'https://example.com/a.jpg' }, 'storeId'], + ['imageUrl 빈 문자열', { storeId: '1', imageUrl: '' }, 'imageUrl'], + ])('%s 거절', async (_label, plain, property) => { + const errors = await validate(build(plain)); + expect(errors.map((e) => e.property)).toEqual([property]); + }); +}); diff --git a/src/features/conversation/dto/inputs/send-conversation-image-message.input.ts b/src/features/conversation/dto/inputs/send-conversation-image-message.input.ts new file mode 100644 index 00000000..3e3e35d7 --- /dev/null +++ b/src/features/conversation/dto/inputs/send-conversation-image-message.input.ts @@ -0,0 +1,11 @@ +import { IsNotEmpty, IsString } from 'class-validator'; + +export class SendConversationImageMessageInput { + @IsString() + @IsNotEmpty() + storeId!: string; + + @IsString() + @IsNotEmpty() + imageUrl!: string; +} diff --git a/src/features/conversation/repositories/conversation.repository.ts b/src/features/conversation/repositories/conversation.repository.ts index 0b7e0df6..e58290df 100644 --- a/src/features/conversation/repositories/conversation.repository.ts +++ b/src/features/conversation/repositories/conversation.repository.ts @@ -14,12 +14,34 @@ import { } from '@/generated/prisma/client'; import { activeWhere, PrismaService } from '@/prisma'; +export interface ConversationOrderCardSnapshot { + orderId: bigint; + orderNumber: string; + productName: string; + thumbnailUrl: string | null; + pickupAt: Date; +} + export interface ConversationMessageEntry { senderType: ConversationSenderType; senderAccountId: bigint | null; bodyFormat: ConversationBodyFormat; bodyText: string | null; bodyHtml: string | null; + imageUrl?: string; + orderCard?: ConversationOrderCardSnapshot; +} + +function orderCardColumns(card: ConversationOrderCardSnapshot | undefined) { + return card + ? { + order_card_order_id: card.orderId, + order_card_order_number: card.orderNumber, + order_card_product_name: card.productName, + order_card_thumbnail_url: card.thumbnailUrl, + order_card_pickup_at: card.pickupAt, + } + : {}; } @Injectable() @@ -539,6 +561,8 @@ export class ConversationRepository { body_format: entry.bodyFormat, body_text: entry.bodyText, body_html: entry.bodyHtml, + image_url: entry.imageUrl ?? null, + ...orderCardColumns(entry.orderCard), created_at: now, }, }), @@ -684,6 +708,7 @@ export class ConversationRepository { bodyFormat: ConversationBodyFormat; bodyText: string | null; bodyHtml: string | null; + imageUrl?: string | null; }, audit: (row: { id: bigint }) => AuditEntry, ) { @@ -701,6 +726,7 @@ export class ConversationRepository { body_format: args.bodyFormat, body_text: args.bodyText, body_html: args.bodyHtml, + image_url: args.imageUrl ?? null, created_at: now, }, }); diff --git a/src/features/conversation/resolvers/conversation-center.resolver.spec.ts b/src/features/conversation/resolvers/conversation-center.resolver.spec.ts index 4d10e039..ded1e656 100644 --- a/src/features/conversation/resolvers/conversation-center.resolver.spec.ts +++ b/src/features/conversation/resolvers/conversation-center.resolver.spec.ts @@ -10,6 +10,7 @@ import { ConversationInquiryMutationResolver } from '@/features/conversation/res import { ConversationCenterService } from '@/features/conversation/services/conversation-center.service'; import { ConversationEventsService } from '@/features/conversation/services/conversation-events.service'; import { ConversationInquiryService } from '@/features/conversation/services/conversation-inquiry.service'; +import { OrderInquiryRepository } from '@/features/order'; import { CATALOG_QUERY } from '@/features/store'; import { StoreCatalogQueryRepository } from '@/features/store/repositories/store-catalog-query.repository'; import type { PrismaClient } from '@/generated/prisma/client'; @@ -23,6 +24,7 @@ import { } from '@/test/factories'; import { createTestingModuleWithRealDb } from '@/test/modules/testing-module.builder'; import { outboxPublisherProviders } from '@/test/outbox'; +import { s3TestProviders } from '@/test/storage/s3-test.helper'; describe('Conversation Center Resolvers (real DB)', () => { let centerResolver: ConversationCenterQueryResolver; @@ -40,6 +42,8 @@ describe('Conversation Center Resolvers (real DB)', () => { // 발행 repository가 OutboxPublisher를 주입받는다 ...outboxPublisherProviders(), ConversationEventsService, + OrderInquiryRepository, + ...s3TestProviders(), AccountUserRepository, { provide: CATALOG_QUERY, useClass: StoreCatalogQueryRepository }, { provide: PUB_SUB, useValue: new PubSub() }, diff --git a/src/features/conversation/resolvers/conversation-inquiry-mutation.resolver.ts b/src/features/conversation/resolvers/conversation-inquiry-mutation.resolver.ts index 311c3552..3e44953a 100644 --- a/src/features/conversation/resolvers/conversation-inquiry-mutation.resolver.ts +++ b/src/features/conversation/resolvers/conversation-inquiry-mutation.resolver.ts @@ -2,6 +2,7 @@ import { UseGuards } from '@nestjs/common'; import { Args, Mutation, Resolver } from '@nestjs/graphql'; import { SendConversationFaqMessageInput } from '@/features/conversation/dto/inputs/send-conversation-faq-message.input'; +import { SendConversationImageMessageInput } from '@/features/conversation/dto/inputs/send-conversation-image-message.input'; import { SendConversationMessageInput } from '@/features/conversation/dto/inputs/send-conversation-message.input'; import { ConversationInquiryService } from '@/features/conversation/services/conversation-inquiry.service'; import type { ConversationMessagesPayload } from '@/features/conversation/types/conversation-output.type'; @@ -11,6 +12,7 @@ import { parseAccountId, type JwtUser, } from '@/global/auth'; +import type { CreateUploadUrlOutput } from '@/global/storage/types/storage.types'; @Resolver('Mutation') @UseGuards(JwtAuthGuard) @@ -34,4 +36,38 @@ export class ConversationInquiryMutationResolver { const accountId = parseAccountId(user); return this.inquiryService.sendConversationFaqMessage(accountId, input); } + + @Mutation('createConversationImageUploadUrl') + createConversationImageUploadUrl( + @CurrentUser() user: JwtUser, + @Args('contentType') contentType: string, + @Args('contentLength') contentLength: number, + ): Promise { + return this.inquiryService.createConversationImageUploadUrl( + parseAccountId(user), + { contentType, contentLength }, + ); + } + + @Mutation('sendConversationImageMessage') + sendConversationImageMessage( + @CurrentUser() user: JwtUser, + @Args('input') input: SendConversationImageMessageInput, + ): Promise { + return this.inquiryService.sendConversationImageMessage( + parseAccountId(user), + input, + ); + } + + @Mutation('sendConversationOrderCard') + sendConversationOrderCard( + @CurrentUser() user: JwtUser, + @Args('orderId') orderId: string, + ): Promise { + return this.inquiryService.sendConversationOrderCard( + parseAccountId(user), + orderId, + ); + } } diff --git a/src/features/conversation/resolvers/conversation-inquiry.resolver.spec.ts b/src/features/conversation/resolvers/conversation-inquiry.resolver.spec.ts index 99037037..59034862 100644 --- a/src/features/conversation/resolvers/conversation-inquiry.resolver.spec.ts +++ b/src/features/conversation/resolvers/conversation-inquiry.resolver.spec.ts @@ -9,6 +9,7 @@ import { ConversationInquiryMutationResolver } from '@/features/conversation/res import { ConversationInquiryQueryResolver } from '@/features/conversation/resolvers/conversation-inquiry-query.resolver'; import { ConversationEventsService } from '@/features/conversation/services/conversation-events.service'; import { ConversationInquiryService } from '@/features/conversation/services/conversation-inquiry.service'; +import { OrderInquiryRepository } from '@/features/order'; import { CATALOG_QUERY } from '@/features/store'; import { StoreCatalogQueryRepository } from '@/features/store/repositories/store-catalog-query.repository'; import type { PrismaClient } from '@/generated/prisma/client'; @@ -17,11 +18,18 @@ import { disconnectTestPrismaClient } from '@/test/db/prisma-test-client'; import { closeTruncateConnection, truncateAll } from '@/test/db/truncate'; import { createAccount, + createOrder, + createOrderItem, createStore, createUserProfile, } from '@/test/factories'; import { createTestingModuleWithRealDb } from '@/test/modules/testing-module.builder'; import { outboxPublisherProviders } from '@/test/outbox'; +import { s3TestProviders } from '@/test/storage/s3-test.helper'; + +jest.mock('@aws-sdk/s3-request-presigner', () => ({ + getSignedUrl: jest.fn().mockResolvedValue('https://mock-presigned-url.com'), +})); describe('Conversation Inquiry Resolvers (real DB)', () => { let queryResolver: ConversationInquiryQueryResolver; @@ -38,6 +46,8 @@ describe('Conversation Inquiry Resolvers (real DB)', () => { // 발행 repository가 OutboxPublisher를 주입받는다 ...outboxPublisherProviders(), ConversationEventsService, + OrderInquiryRepository, + ...s3TestProviders(), AccountUserRepository, { provide: CATALOG_QUERY, useClass: StoreCatalogQueryRepository }, { provide: PUB_SUB, useValue: new PubSub() }, @@ -104,4 +114,39 @@ describe('Conversation Inquiry Resolvers (real DB)', () => { expect(result.messages).toHaveLength(3); expect(result.messages[2].bodyHtml).toBe('

캘린더를 확인해 주세요.

'); }); + + it('이미지 업로드 URL 발급 → 이미지 메시지, 주문 카드 전송 전체 경로', async () => { + const buyer = await createAccount(prisma, { account_type: 'USER' }); + await createUserProfile(prisma, { account_id: buyer.id }); + const store = await createStore(prisma); + const order = await createOrder(prisma, { + account_id: buyer.id, + status: 'CONFIRMED', + }); + await createOrderItem(prisma, { order_id: order.id, store_id: store.id }); + const jwtUser = { accountId: buyer.id.toString() }; + + const upload = await mutationResolver.createConversationImageUploadUrl( + jwtUser, + 'image/jpeg', + 1024, + ); + const image = await mutationResolver.sendConversationImageMessage(jwtUser, { + storeId: store.id.toString(), + imageUrl: upload.publicUrl, + }); + const card = await mutationResolver.sendConversationOrderCard( + jwtUser, + order.id.toString(), + ); + + expect(image.messages.at(-1)?.imageUrl).toBe(upload.publicUrl); + expect(card.conversationId).toBe(image.conversationId); + expect(card.messages).toEqual([ + expect.objectContaining({ + bodyFormat: 'ORDER_CARD', + orderCard: expect.objectContaining({ orderId: order.id.toString() }), + }), + ]); + }); }); diff --git a/src/features/conversation/resolvers/conversation-seller.resolver.spec.ts b/src/features/conversation/resolvers/conversation-seller.resolver.spec.ts index 901b396b..85cb74b4 100644 --- a/src/features/conversation/resolvers/conversation-seller.resolver.spec.ts +++ b/src/features/conversation/resolvers/conversation-seller.resolver.spec.ts @@ -15,6 +15,7 @@ import { closeTruncateConnection, truncateAll } from '@/test/db/truncate'; import { createAccount, setupSellerWithStore } from '@/test/factories'; import { createTestingModuleWithRealDb } from '@/test/modules/testing-module.builder'; import { outboxPublisherProviders } from '@/test/outbox'; +import { s3TestProviders } from '@/test/storage/s3-test.helper'; describe('Seller Conversation Resolvers (real DB)', () => { let queryResolver: SellerConversationQueryResolver; @@ -32,6 +33,7 @@ describe('Seller Conversation Resolvers (real DB)', () => { // 발행 repository가 OutboxPublisher를 주입받는다 ...outboxPublisherProviders(), ConversationEventsService, + ...s3TestProviders(), { provide: PUB_SUB, useValue: new PubSub() }, { provide: AUDIT_LOG_REPOSITORY, diff --git a/src/features/conversation/services/conversation-attachment.helper.ts b/src/features/conversation/services/conversation-attachment.helper.ts new file mode 100644 index 00000000..ee9ae9b4 --- /dev/null +++ b/src/features/conversation/services/conversation-attachment.helper.ts @@ -0,0 +1,28 @@ +import { DomainException } from '@/common/errors/error-catalog'; +import { MAX_CONVERSATION_IMAGE_URL_LENGTH } from '@/features/conversation/constants/conversation.constants'; +import type { S3Service } from '@/global/storage/s3.service'; + +/** 보내는 계정이 CONVERSATION_IMAGE로 발급받은 URL만 싣는다(구매자·판매자 공용). */ +export function requireOwnedConversationImageUrl( + s3: S3Service, + raw: string | null | undefined, + accountId: bigint, +): string { + const url = raw?.trim(); + if (!url) throw new DomainException('IMAGE_URL_REQUIRED'); + if ( + url.length > MAX_CONVERSATION_IMAGE_URL_LENGTH || + !s3.isOwnedUploadUrl(url, 'CONVERSATION_IMAGE', accountId) + ) { + throw new DomainException('INVALID_IMAGE_URL'); + } + return url; +} + +/** 주문 카드 대체 문구. 목록 미리보기·판매자 푸시가 본문 대신 이 값을 쓴다. */ +export function orderCardAltText(card: { + productName: string; + orderNumber: string; +}): string { + return `주문 문의: ${card.productName} (${card.orderNumber})`; +} diff --git a/src/features/conversation/services/conversation-center-mappers.helper.spec.ts b/src/features/conversation/services/conversation-center-mappers.helper.spec.ts index ee48c4a7..d62da184 100644 --- a/src/features/conversation/services/conversation-center-mappers.helper.spec.ts +++ b/src/features/conversation/services/conversation-center-mappers.helper.spec.ts @@ -42,6 +42,19 @@ describe('conversation-center-mappers.helper', () => { ).toBe('답변'); }); + it.each([ + ['IMAGE', '사진을 보냈습니다.'], + ['ORDER_CARD', '주문 문의: 케이크 (ORD-1)'], + ] as const)('%s 메시지는 대체 문구를 반환한다', (format, alt) => { + expect( + toLastMessagePreview({ + body_format: format, + body_text: alt, + body_html: null, + }), + ).toBe(alt); + }); + it('메시지가 없거나 본문이 비면 null', () => { expect(toLastMessagePreview(null)).toBeNull(); expect( diff --git a/src/features/conversation/services/conversation-center-mappers.helper.ts b/src/features/conversation/services/conversation-center-mappers.helper.ts index 043aa27a..80159b0d 100644 --- a/src/features/conversation/services/conversation-center-mappers.helper.ts +++ b/src/features/conversation/services/conversation-center-mappers.helper.ts @@ -1,3 +1,5 @@ +import type { ConversationBodyFormat } from '@/generated/prisma/client'; + /** 표시용 한 줄 미리보기라 완전한 HTML 파싱 대신 태그 제거 + 공백 정리로 충분하다(저장 원문은 그대로). */ export function stripHtmlToPreview(html: string): string { return ( @@ -14,9 +16,10 @@ export function stripHtmlToPreview(html: string): string { ); } +/** IMAGE·ORDER_CARD는 body_text에 저장한 대체 문구가 미리보기다. */ export function toLastMessagePreview( message: { - body_format: 'TEXT' | 'HTML'; + body_format: ConversationBodyFormat; body_text: string | null; body_html: string | null; } | null, diff --git a/src/features/conversation/services/conversation-events-mappers.helper.spec.ts b/src/features/conversation/services/conversation-events-mappers.helper.spec.ts index ef9fec7d..6c8c09b7 100644 --- a/src/features/conversation/services/conversation-events-mappers.helper.spec.ts +++ b/src/features/conversation/services/conversation-events-mappers.helper.spec.ts @@ -14,6 +14,8 @@ function message( bodyFormat: 'TEXT', bodyText: '안녕하세요', bodyHtml: null, + imageUrl: null, + orderCard: null, createdAt: new Date('2026-08-01T12:00:00Z'), ...overrides, }; @@ -28,12 +30,41 @@ describe('conversation-events-mappers.helper', () => { bodyFormat: 'TEXT', bodyText: '안녕하세요', bodyHtml: null, + imageUrl: null, + orderCard: null, createdAt: '2026-08-01T12:00:00.000Z', }); }); - it('미리보기는 TEXT 원문 / HTML 태그 제거 텍스트를 쓴다', () => { + it('주문 카드 픽업 일시도 ISO 문자열로 바꾼다', () => { + const event = toConversationMessageEvent( + message({ + bodyFormat: 'ORDER_CARD', + orderCard: { + orderId: '5', + orderNumber: 'ORD-1', + productName: '케이크', + thumbnailUrl: 'https://cdn.example.com/t.jpg', + pickupAt: new Date('2026-08-03T03:00:00Z'), + }, + }), + ); + expect(event.orderCard).toEqual({ + orderId: '5', + orderNumber: 'ORD-1', + productName: '케이크', + thumbnailUrl: 'https://cdn.example.com/t.jpg', + pickupAt: '2026-08-03T03:00:00.000Z', + }); + }); + + it('미리보기는 TEXT·IMAGE 원문(대체 문구) / HTML 태그 제거 텍스트를 쓴다', () => { expect(toEventPreview(message())).toBe('안녕하세요'); + expect( + toEventPreview( + message({ bodyFormat: 'IMAGE', bodyText: '사진을 보냈습니다.' }), + ), + ).toBe('사진을 보냈습니다.'); expect( toEventPreview( message({ diff --git a/src/features/conversation/services/conversation-events-mappers.helper.ts b/src/features/conversation/services/conversation-events-mappers.helper.ts index 64dfcf47..36bf4a51 100644 --- a/src/features/conversation/services/conversation-events-mappers.helper.ts +++ b/src/features/conversation/services/conversation-events-mappers.helper.ts @@ -15,6 +15,13 @@ export function toConversationMessageEvent( bodyFormat: message.bodyFormat, bodyText: message.bodyText, bodyHtml: message.bodyHtml, + imageUrl: message.imageUrl, + orderCard: message.orderCard + ? { + ...message.orderCard, + pickupAt: message.orderCard.pickupAt.toISOString(), + } + : null, createdAt: message.createdAt.toISOString(), }; } diff --git a/src/features/conversation/services/conversation-events.service.spec.ts b/src/features/conversation/services/conversation-events.service.spec.ts index c095e84d..95b0412e 100644 --- a/src/features/conversation/services/conversation-events.service.spec.ts +++ b/src/features/conversation/services/conversation-events.service.spec.ts @@ -81,9 +81,17 @@ describe('ConversationEventsService (real Redis)', () => { id: '1', conversationId: '10', senderType: 'USER', - bodyFormat: 'TEXT', - bodyText: '픽업 문의', + bodyFormat: 'ORDER_CARD', + bodyText: '주문 문의: 케이크 (ORD-1)', bodyHtml: null, + imageUrl: null, + orderCard: { + orderId: '5', + orderNumber: 'ORD-1', + productName: '케이크', + thumbnailUrl: null, + pickupAt: new Date('2026-08-03T03:00:00Z'), + }, createdAt: new Date('2026-08-01T12:00:00Z'), }; await service.publishMessagesAdded([message]); @@ -93,9 +101,17 @@ describe('ConversationEventsService (real Redis)', () => { id: '1', conversationId: '10', senderType: 'USER', - bodyFormat: 'TEXT', - bodyText: '픽업 문의', + bodyFormat: 'ORDER_CARD', + bodyText: '주문 문의: 케이크 (ORD-1)', bodyHtml: null, + imageUrl: null, + orderCard: { + orderId: '5', + orderNumber: 'ORD-1', + productName: '케이크', + thumbnailUrl: null, + pickupAt: '2026-08-03T03:00:00.000Z', + }, createdAt: '2026-08-01T12:00:00.000Z', }); expect(otherReceived).not.toHaveBeenCalled(); @@ -169,6 +185,8 @@ describe('ConversationEventsService (real Redis)', () => { bodyFormat: 'TEXT', bodyText: '문의', bodyHtml: null, + imageUrl: null, + orderCard: null, createdAt: new Date(), }, ]), diff --git a/src/features/conversation/services/conversation-inquiry-mappers.helper.spec.ts b/src/features/conversation/services/conversation-inquiry-mappers.helper.spec.ts index bcf431f0..492de78f 100644 --- a/src/features/conversation/services/conversation-inquiry-mappers.helper.spec.ts +++ b/src/features/conversation/services/conversation-inquiry-mappers.helper.spec.ts @@ -1,7 +1,10 @@ import { formatTimeOfDay, renderGreeting, + toConversationMessageOutput, toInquiryBusinessHour, + toOrderCardOutput, + type ConversationMessageRow, } from '@/features/conversation/services/conversation-inquiry-mappers.helper'; describe('conversation-inquiry-mappers.helper', () => { @@ -72,4 +75,41 @@ describe('conversation-inquiry-mappers.helper', () => { }); }); }); + + describe('toOrderCardOutput', () => { + const cardRow: ConversationMessageRow = { + id: 1n, + conversation_id: 2n, + sender_type: 'USER', + body_format: 'ORDER_CARD', + body_text: '주문 문의: 케이크 (ORD-1)', + body_html: null, + image_url: null, + order_card_order_id: 5n, + order_card_order_number: 'ORD-1', + order_card_product_name: '케이크', + order_card_thumbnail_url: null, + order_card_pickup_at: new Date('2026-08-03T03:00:00Z'), + created_at: new Date('2026-08-01T12:00:00Z'), + }; + + it('카드 스냅샷 컬럼으로 주문 카드를 만든다(썸네일은 없으면 null)', () => { + expect(toConversationMessageOutput(cardRow).orderCard).toEqual({ + orderId: '5', + orderNumber: 'ORD-1', + productName: '케이크', + thumbnailUrl: null, + pickupAt: new Date('2026-08-03T03:00:00Z'), + }); + }); + + it.each([ + 'order_card_order_id', + 'order_card_order_number', + 'order_card_product_name', + 'order_card_pickup_at', + ] as const)('%s가 비면 카드가 아니다(null)', (column) => { + expect(toOrderCardOutput({ ...cardRow, [column]: null })).toBeNull(); + }); + }); }); diff --git a/src/features/conversation/services/conversation-inquiry-mappers.helper.ts b/src/features/conversation/services/conversation-inquiry-mappers.helper.ts index 92411bff..774c058d 100644 --- a/src/features/conversation/services/conversation-inquiry-mappers.helper.ts +++ b/src/features/conversation/services/conversation-inquiry-mappers.helper.ts @@ -5,8 +5,10 @@ import { } from '@/features/conversation/constants/conversation.constants'; import type { ConversationMessageOutput, + ConversationOrderCardOutput, InquiryBusinessHourOutput, } from '@/features/conversation/types/conversation-output.type'; +import type { StoreConversationMessage } from '@/generated/prisma/client'; /** placeholder는 등장 위치·횟수 제한 없이 전부 치환한다. */ export function renderGreeting( @@ -40,15 +42,46 @@ export function toInquiryBusinessHour(row: { }; } -export function toConversationMessageOutput(row: { - id: bigint; - conversation_id: bigint; - sender_type: 'USER' | 'STORE' | 'SYSTEM'; - body_format: 'TEXT' | 'HTML'; - body_text: string | null; - body_html: string | null; - created_at: Date; -}): ConversationMessageOutput { +export type ConversationMessageRow = Pick< + StoreConversationMessage, + | 'id' + | 'conversation_id' + | 'sender_type' + | 'body_format' + | 'body_text' + | 'body_html' + | 'image_url' + | 'order_card_order_id' + | 'order_card_order_number' + | 'order_card_product_name' + | 'order_card_thumbnail_url' + | 'order_card_pickup_at' + | 'created_at' +>; + +export function toOrderCardOutput( + row: ConversationMessageRow, +): ConversationOrderCardOutput | null { + if ( + row.order_card_order_id === null || + row.order_card_order_number === null || + row.order_card_product_name === null || + row.order_card_pickup_at === null + ) { + return null; + } + return { + orderId: row.order_card_order_id.toString(), + orderNumber: row.order_card_order_number, + productName: row.order_card_product_name, + thumbnailUrl: row.order_card_thumbnail_url, + pickupAt: row.order_card_pickup_at, + }; +} + +export function toConversationMessageOutput( + row: ConversationMessageRow, +): ConversationMessageOutput { return { id: row.id.toString(), conversationId: row.conversation_id.toString(), @@ -56,6 +89,8 @@ export function toConversationMessageOutput(row: { bodyFormat: row.body_format, bodyText: row.body_text, bodyHtml: row.body_html, + imageUrl: row.image_url, + orderCard: toOrderCardOutput(row), createdAt: row.created_at, }; } diff --git a/src/features/conversation/services/conversation-inquiry.service.spec.ts b/src/features/conversation/services/conversation-inquiry.service.spec.ts index 2a07d9f8..af0c7312 100644 --- a/src/features/conversation/services/conversation-inquiry.service.spec.ts +++ b/src/features/conversation/services/conversation-inquiry.service.spec.ts @@ -10,19 +10,32 @@ import { import { ConversationRepository } from '@/features/conversation/repositories/conversation.repository'; import { ConversationEventsService } from '@/features/conversation/services/conversation-events.service'; import { ConversationInquiryService } from '@/features/conversation/services/conversation-inquiry.service'; +import { OrderInquiryRepository } from '@/features/order'; import { CATALOG_QUERY } from '@/features/store'; import { StoreCatalogQueryRepository } from '@/features/store/repositories/store-catalog-query.repository'; -import type { PrismaClient } from '@/generated/prisma/client'; +import type { OrderStatus, PrismaClient } from '@/generated/prisma/client'; import { PUB_SUB } from '@/global/pubsub'; import { disconnectTestPrismaClient } from '@/test/db/prisma-test-client'; import { closeTruncateConnection, truncateAll } from '@/test/db/truncate'; import { createAccount, + createOrder, + createOrderItem, createStore, createUserProfile, } from '@/test/factories'; import { createTestingModuleWithRealDb } from '@/test/modules/testing-module.builder'; import { outboxPublisherProviders } from '@/test/outbox'; +import { + FOREIGN_UPLOAD_URL, + ownedUploadUrl, + s3TestProviders, + TEST_S3_CONFIG, +} from '@/test/storage/s3-test.helper'; + +jest.mock('@aws-sdk/s3-request-presigner', () => ({ + getSignedUrl: jest.fn().mockResolvedValue('https://mock-presigned-url.com'), +})); describe('ConversationInquiryService (real DB)', () => { let service: ConversationInquiryService; @@ -37,6 +50,8 @@ describe('ConversationInquiryService (real DB)', () => { // 발행 repository가 OutboxPublisher를 주입받는다 ...outboxPublisherProviders(), ConversationEventsService, + OrderInquiryRepository, + ...s3TestProviders(), AccountUserRepository, { provide: CATALOG_QUERY, useClass: StoreCatalogQueryRepository }, // 발행 경로 실검증은 events service spec(실 Redis) 담당 — 여기선 in-memory @@ -508,4 +523,325 @@ describe('ConversationInquiryService (real DB)', () => { }); }); }); + + /** 매장의 상품 1개짜리 주문. 주문 1건 = 상품 1개 = 매장 1곳. */ + async function orderAt( + accountId: bigint, + storeId: bigint, + overrides: { + status?: OrderStatus; + submitted_at?: Date | null; + product_name_snapshot?: string; + product_thumbnail_url_snapshot?: string | null; + custom_preview_image_url?: string | null; + } = {}, + ) { + const { status, submitted_at, ...item } = overrides; + const order = await createOrder(prisma, { + account_id: accountId, + ...(status ? { status } : {}), + ...(submitted_at !== undefined ? { submitted_at } : {}), + }); + await createOrderItem(prisma, { + order_id: order.id, + store_id: storeId, + ...item, + }); + return order; + } + + describe('숨김 매장 문의(그 매장에 진행 중인 주문이 있는 구매자만)', () => { + it('진행 중인 주문이 있으면 문의 컨텍스트 조회·텍스트·FAQ 전송을 허용한다', async () => { + const buyer = await setupBuyer(); + const store = await createStore(prisma, { is_active: false }); + const faq = await createFaq(store.id); + await orderAt(buyer.id, store.id, { status: 'CONFIRMED' }); + + await expect( + service.storeInquiryContext(buyer.id, store.id.toString()), + ).resolves.toMatchObject({ storeId: store.id.toString() }); + await service.sendConversationMessage(buyer.id, { + storeId: store.id.toString(), + bodyText: '정지됐다는데 케이크는 받을 수 있나요?', + }); + const faqResult = await service.sendConversationFaqMessage(buyer.id, { + storeId: store.id.toString(), + faqTopicId: faq.id.toString(), + }); + expect(faqResult.messages).toHaveLength(2); + }); + + it.each([ + ['끝난 주문만 있음', 'PICKED_UP'], + ['취소된 주문만 있음', 'CANCELED'], + ] as const)('%s이면 STORE_NOT_FOUND', async (_label, status) => { + const buyer = await setupBuyer(); + const store = await createStore(prisma, { is_active: false }); + await orderAt(buyer.id, store.id, { status }); + + await expect( + service.storeInquiryContext(buyer.id, store.id.toString()), + ).rejects.toThrowDomain('STORE_NOT_FOUND'); + await expect( + service.sendConversationMessage(buyer.id, { + storeId: store.id.toString(), + bodyText: '문의', + }), + ).rejects.toThrowDomain('STORE_NOT_FOUND'); + }); + + it('다른 구매자·다른 매장의 진행 주문은 허용 근거가 아니고, 삭제된 매장은 진행 주문이 있어도 거절한다', async () => { + const buyer = await setupBuyer(); + const other = await setupBuyer('다른 구매자'); + const hidden = await createStore(prisma, { is_active: false }); + const elsewhere = await createStore(prisma); + const deleted = await createStore(prisma, { deleted_at: new Date() }); + await orderAt(other.id, hidden.id, { status: 'SUBMITTED' }); + await orderAt(buyer.id, elsewhere.id, { status: 'SUBMITTED' }); + await orderAt(buyer.id, deleted.id, { status: 'SUBMITTED' }); + + for (const store of [hidden, deleted]) { + await expect( + service.storeInquiryContext(buyer.id, store.id.toString()), + ).rejects.toThrowDomain('STORE_NOT_FOUND'); + } + }); + }); + + describe('createConversationImageUploadUrl', () => { + it('conversation-images/{accountId}/ 아래로 10MB까지 발급한다', async () => { + const buyer = await setupBuyer(); + + const result = await service.createConversationImageUploadUrl(buyer.id, { + contentType: 'image/png', + contentLength: 10 * 1024 * 1024, + }); + + expect(result.key).toMatch( + new RegExp( + `^conversation-images/${buyer.id}/\\d{4}-\\d{2}-\\d{2}/[a-f0-9-]+\\.png$`, + ), + ); + expect(result.publicUrl).toBe( + `https://${TEST_S3_CONFIG.bucket}.s3.${TEST_S3_CONFIG.region}.amazonaws.com/${result.key}`, + ); + }); + + it.each([ + ['10MB 초과', 'image/png', 10 * 1024 * 1024 + 1, 'FILE_TOO_LARGE'], + ['0바이트', 'image/png', 0, 'INVALID_CONTENT_LENGTH'], + ['이미지가 아닌 형식', 'video/mp4', 1, 'INVALID_CONTENT_TYPE'], + ] as const)('%s는 %s', async (_label, contentType, contentLength, code) => { + const buyer = await setupBuyer(); + await expect( + service.createConversationImageUploadUrl(buyer.id, { + contentType, + contentLength, + }), + ).rejects.toThrowDomain(code); + }); + + it('구매자 계정이 아니면 USER_ONLY', async () => { + const seller = await createAccount(prisma, { account_type: 'SELLER' }); + await expect( + service.createConversationImageUploadUrl(seller.id, { + contentType: 'image/png', + contentLength: 1, + }), + ).rejects.toThrowDomain('USER_ONLY'); + }); + }); + + describe('sendConversationImageMessage', () => { + it('첫 전송이면 인사말 → 이미지 메시지를 저장하고 본문·푸시 미리보기는 대체 문구다', async () => { + const buyer = await setupBuyer(); + const store = await createStore(prisma); + const imageUrl = ownedUploadUrl('CONVERSATION_IMAGE', buyer.id); + + const result = await service.sendConversationImageMessage(buyer.id, { + storeId: store.id.toString(), + imageUrl, + }); + + expect(result.messages.map((m) => m.bodyFormat)).toEqual([ + 'TEXT', + 'IMAGE', + ]); + expect(result.messages[1]).toMatchObject({ + senderType: 'USER', + bodyText: '사진을 보냈습니다.', + bodyHtml: null, + imageUrl, + orderCard: null, + }); + const rows = await messagesOf(BigInt(result.conversationId)); + expect(rows[1]).toMatchObject({ + body_format: 'IMAGE', + image_url: imageUrl, + }); + const [event] = await prisma.outbox.findMany(); + expect( + parseConversationBuyerMessageSentPayload(event.payload_json).preview, + ).toBe('사진을 보냈습니다.'); + }); + + const HOST = `${TEST_S3_CONFIG.bucket}.s3.${TEST_S3_CONFIG.region}.amazonaws.com`; + it.each([ + [ + '다른 계정 경로', + (_me: bigint, other: bigint) => + ownedUploadUrl('CONVERSATION_IMAGE', other), + ], + ['다른 용도 경로', (me: bigint) => ownedUploadUrl('REVIEW_IMAGE', me)], + [ + '인코딩된 dot(%2e) 우회', + (me: bigint, other: bigint) => + `https://${HOST}/conversation-images/${me}/%2e%2e/${other}/a.jpg`, + ], + ['외부 URL', () => FOREIGN_UPLOAD_URL], + [ + '2048자 초과', + (me: bigint) => + ownedUploadUrl('CONVERSATION_IMAGE', me, `${'a'.repeat(2048)}.jpg`), + ], + ])('%s는 INVALID_IMAGE_URL', async (_label, urlOf) => { + const buyer = await setupBuyer(); + const other = await setupBuyer('다른 구매자'); + const store = await createStore(prisma); + + await expect( + service.sendConversationImageMessage(buyer.id, { + storeId: store.id.toString(), + imageUrl: urlOf(buyer.id, other.id), + }), + ).rejects.toThrowDomain('INVALID_IMAGE_URL'); + expect(await prisma.storeConversationMessage.count()).toBe(0); + }); + + it('공백 URL은 IMAGE_URL_REQUIRED', async () => { + const buyer = await setupBuyer(); + const store = await createStore(prisma); + await expect( + service.sendConversationImageMessage(buyer.id, { + storeId: store.id.toString(), + imageUrl: ' ', + }), + ).rejects.toThrowDomain('IMAGE_URL_REQUIRED'); + }); + }); + + describe('sendConversationOrderCard', () => { + it('주문 매장 대화에 보낸 시점 카드(커스텀 대표 이미지 우선)와 대체 문구를 저장한다', async () => { + const buyer = await setupBuyer(); + const store = await createStore(prisma); + const order = await orderAt(buyer.id, store.id, { + status: 'SUBMITTED', + product_name_snapshot: '딸기 케이크', + product_thumbnail_url_snapshot: 'https://cdn.example.com/product.jpg', + custom_preview_image_url: 'https://cdn.example.com/custom.jpg', + }); + const altText = `주문 문의: 딸기 케이크 (${order.order_number})`; + + const result = await service.sendConversationOrderCard( + buyer.id, + order.id.toString(), + ); + + const conversation = await prisma.storeConversation.findFirstOrThrow({ + where: { account_id: buyer.id }, + }); + expect(conversation.store_id).toBe(store.id); + expect(result.messages[1]).toMatchObject({ + senderType: 'USER', + bodyFormat: 'ORDER_CARD', + bodyText: altText, + imageUrl: null, + orderCard: { + orderId: order.id.toString(), + orderNumber: order.order_number, + productName: '딸기 케이크', + thumbnailUrl: 'https://cdn.example.com/custom.jpg', + pickupAt: order.pickup_at, + }, + }); + const [event] = await prisma.outbox.findMany(); + expect( + parseConversationBuyerMessageSentPayload(event.payload_json).preview, + ).toBe(altText); + }); + + it('입금 확인 뒤 취소된 주문도 판매자가 볼 수 있어 보낼 수 있다', async () => { + const buyer = await setupBuyer(); + const store = await createStore(prisma); + const order = await orderAt(buyer.id, store.id, { + status: 'CANCELED', + submitted_at: new Date(), + }); + + const result = await service.sendConversationOrderCard( + buyer.id, + order.id.toString(), + ); + expect(result.messages.at(-1)?.bodyFormat).toBe('ORDER_CARD'); + }); + + it('다른 구매자의 주문·삭제된 주문·없는 주문은 ORDER_NOT_FOUND', async () => { + const buyer = await setupBuyer(); + const other = await setupBuyer('다른 구매자'); + const store = await createStore(prisma); + const others = await orderAt(other.id, store.id); + const deleted = await orderAt(buyer.id, store.id); + await prisma.order.update({ + where: { id: deleted.id }, + data: { deleted_at: new Date() }, + }); + + for (const id of [others.id.toString(), deleted.id.toString(), '0']) { + await expect( + service.sendConversationOrderCard(buyer.id, id), + ).rejects.toThrowDomain('ORDER_NOT_FOUND'); + } + }); + + it.each([ + ['입금 대기', 'PENDING_PAYMENT'], + ['입금 전 취소', 'CANCELED'], + ] as const)( + '%s 주문(입금 확인 전)은 ORDER_INQUIRY_NOT_AVAILABLE', + async (_label, status) => { + const buyer = await setupBuyer(); + const store = await createStore(prisma); + const order = await orderAt(buyer.id, store.id, { + status, + submitted_at: null, + }); + + await expect( + service.sendConversationOrderCard(buyer.id, order.id.toString()), + ).rejects.toThrowDomain('ORDER_INQUIRY_NOT_AVAILABLE'); + expect(await prisma.storeConversationMessage.count()).toBe(0); + }, + ); + + it('숨김 매장은 카드 주문이 진행 중이면 보내고, 끝난 주문이면 STORE_NOT_FOUND', async () => { + const buyer = await setupBuyer(); + const store = await createStore(prisma, { is_active: false }); + const made = await orderAt(buyer.id, store.id, { status: 'MADE' }); + const pickedUp = await orderAt(buyer.id, store.id, { + status: 'PICKED_UP', + }); + + await expect( + service.sendConversationOrderCard(buyer.id, pickedUp.id.toString()), + ).resolves.toMatchObject({ messages: expect.any(Array) }); + + await prisma.order.update({ + where: { id: made.id }, + data: { status: 'PICKED_UP' }, + }); + await expect( + service.sendConversationOrderCard(buyer.id, pickedUp.id.toString()), + ).rejects.toThrowDomain('STORE_NOT_FOUND'); + }); + }); }); diff --git a/src/features/conversation/services/conversation-inquiry.service.ts b/src/features/conversation/services/conversation-inquiry.service.ts index 7e7e762a..863cd8aa 100644 --- a/src/features/conversation/services/conversation-inquiry.service.ts +++ b/src/features/conversation/services/conversation-inquiry.service.ts @@ -4,13 +4,21 @@ import { DomainException } from '@/common/errors/error-catalog'; import { parseId } from '@/common/utils/id-parser'; import { cleanRequiredText } from '@/common/utils/text-cleaner'; import { AccountUserRepository } from '@/features/auth'; -import { MAX_INQUIRY_BODY_TEXT_LENGTH } from '@/features/conversation/constants/conversation.constants'; +import { + CONVERSATION_IMAGE_ALT_TEXT, + MAX_INQUIRY_BODY_TEXT_LENGTH, +} from '@/features/conversation/constants/conversation.constants'; import type { SendConversationFaqMessageInput } from '@/features/conversation/dto/inputs/send-conversation-faq-message.input'; +import type { SendConversationImageMessageInput } from '@/features/conversation/dto/inputs/send-conversation-image-message.input'; import type { SendConversationMessageInput } from '@/features/conversation/dto/inputs/send-conversation-message.input'; import { ConversationRepository, type ConversationMessageEntry, } from '@/features/conversation/repositories/conversation.repository'; +import { + orderCardAltText, + requireOwnedConversationImageUrl, +} from '@/features/conversation/services/conversation-attachment.helper'; import { ConversationBaseService } from '@/features/conversation/services/conversation-base.service'; import { toLastMessagePreview } from '@/features/conversation/services/conversation-center-mappers.helper'; import { toEventPreview } from '@/features/conversation/services/conversation-events-mappers.helper'; @@ -24,11 +32,14 @@ import type { ConversationMessagesPayload, StoreInquiryContextOutput, } from '@/features/conversation/types/conversation-output.type'; +import { OrderInquiryRepository } from '@/features/order'; import { CATALOG_QUERY, type ICatalogQuery } from '@/features/store'; import { ConversationBodyFormat, ConversationSenderType, } from '@/generated/prisma/client'; +import { S3Service } from '@/global/storage/s3.service'; +import type { CreateUploadUrlOutput } from '@/global/storage/types/storage.types'; @Injectable() export class ConversationInquiryService extends ConversationBaseService { @@ -39,6 +50,8 @@ export class ConversationInquiryService extends ConversationBaseService { accounts: AccountUserRepository, private readonly events: ConversationEventsService, @Inject(CATALOG_QUERY) private readonly catalog: ICatalogQuery, + private readonly orders: OrderInquiryRepository, + private readonly s3: S3Service, ) { super(repo, accounts); } @@ -50,7 +63,7 @@ export class ConversationInquiryService extends ConversationBaseService { const { nickname } = await this.requireActiveUser(accountId); const storeId = parseId(storeIdRaw); - const store = await this.requireInquiryStore(storeId); + const store = await this.requireInquiryStore(accountId, storeId); const [faqTopics, conversation] = await Promise.all([ this.catalog.listActiveFaqTopics(storeId), this.repo.findConversationByAccountAndStore({ accountId, storeId }), @@ -79,7 +92,7 @@ export class ConversationInquiryService extends ConversationBaseService { ): Promise { const { nickname } = await this.requireActiveUser(accountId); const storeId = parseId(input.storeId); - const store = await this.requireInquiryStore(storeId); + const store = await this.requireInquiryStore(accountId, storeId); const bodyText = cleanRequiredText( input.bodyText, @@ -110,7 +123,7 @@ export class ConversationInquiryService extends ConversationBaseService { ): Promise { const { nickname } = await this.requireActiveUser(accountId); const storeId = parseId(input.storeId); - const store = await this.requireInquiryStore(storeId); + const store = await this.requireInquiryStore(accountId, storeId); const topic = await this.catalog.findActiveFaqTopic({ storeId, @@ -146,6 +159,92 @@ export class ConversationInquiryService extends ConversationBaseService { }); } + async createConversationImageUploadUrl( + accountId: bigint, + input: { contentType: string; contentLength: number }, + ): Promise { + await this.requireActiveUser(accountId); + return this.s3.createUploadUrl({ + accountId, + purpose: 'CONVERSATION_IMAGE', + contentType: input.contentType, + contentLength: input.contentLength, + }); + } + + async sendConversationImageMessage( + accountId: bigint, + input: SendConversationImageMessageInput, + ): Promise { + const { nickname } = await this.requireActiveUser(accountId); + const storeId = parseId(input.storeId); + const store = await this.requireInquiryStore(accountId, storeId); + const imageUrl = requireOwnedConversationImageUrl( + this.s3, + input.imageUrl, + accountId, + ); + + return this.saveBuyerMessages({ + accountId, + storeId, + nickname, + storeName: store.store_name, + greetingTemplate: store.greeting_message, + entries: [ + { + senderType: ConversationSenderType.USER, + senderAccountId: accountId, + bodyFormat: ConversationBodyFormat.IMAGE, + bodyText: CONVERSATION_IMAGE_ALT_TEXT, + bodyHtml: null, + imageUrl, + }, + ], + }); + } + + /** 판매자가 볼 수 없는 입금 전 주문은 카드로 보낼 수 없다. 카드는 보낸 시점 값으로 남는다. */ + async sendConversationOrderCard( + accountId: bigint, + orderIdRaw: string, + ): Promise { + const { nickname } = await this.requireActiveUser(accountId); + const source = await this.orders.findOrderCardSource({ + orderId: parseId(orderIdRaw), + accountId, + }); + if (!source) throw new DomainException('ORDER_NOT_FOUND'); + if (source.submittedAt === null) { + throw new DomainException('ORDER_INQUIRY_NOT_AVAILABLE'); + } + const store = await this.requireInquiryStore(accountId, source.storeId); + + return this.saveBuyerMessages({ + accountId, + storeId: source.storeId, + nickname, + storeName: store.store_name, + greetingTemplate: store.greeting_message, + entries: [ + { + senderType: ConversationSenderType.USER, + senderAccountId: accountId, + bodyFormat: ConversationBodyFormat.ORDER_CARD, + bodyText: orderCardAltText(source), + bodyHtml: null, + orderCard: { + orderId: source.orderId, + orderNumber: source.orderNumber, + productName: source.productName, + thumbnailUrl: source.thumbnailUrl, + pickupAt: source.pickupAt, + }, + }, + ], + }); + } + private async saveBuyerMessages(args: { accountId: bigint; storeId: bigint; @@ -252,9 +351,17 @@ export class ConversationInquiryService extends ConversationBaseService { }); } - private async requireInquiryStore(storeId: bigint) { + /** 숨김 매장은 진행 중인 주문이 있는 구매자만 문의할 수 있다(판매자 정지·매장 숨김 뒤에도 주문 문의 경로를 남긴다). */ + private async requireInquiryStore(accountId: bigint, storeId: bigint) { const store = await this.catalog.findInquiryStore(storeId); - if (!store) { + if ( + !store || + (!store.is_active && + !(await this.orders.existsInProgressOrderAtStore({ + accountId, + storeId, + }))) + ) { throw new DomainException('STORE_NOT_FOUND'); } return store; diff --git a/src/features/conversation/services/conversation-seller.service.spec.ts b/src/features/conversation/services/conversation-seller.service.spec.ts index b222fc81..3d885a69 100644 --- a/src/features/conversation/services/conversation-seller.service.spec.ts +++ b/src/features/conversation/services/conversation-seller.service.spec.ts @@ -13,6 +13,11 @@ import { closeTruncateConnection, truncateAll } from '@/test/db/truncate'; import { createAccount, setupSellerWithStore } from '@/test/factories'; import { createTestingModuleWithRealDb } from '@/test/modules/testing-module.builder'; import { outboxPublisherProviders } from '@/test/outbox'; +import { + ownedUploadUrl, + s3TestProviders, + TEST_S3_CONFIG, +} from '@/test/storage/s3-test.helper'; describe('SellerConversationService (real DB)', () => { let service: SellerConversationService; @@ -28,6 +33,7 @@ describe('SellerConversationService (real DB)', () => { // 발행 repository가 OutboxPublisher를 주입받는다 ...outboxPublisherProviders(), ConversationEventsService, + ...s3TestProviders(), { provide: PUB_SUB, useValue: new PubSub() }, { provide: AUDIT_LOG_REPOSITORY, @@ -423,4 +429,129 @@ describe('SellerConversationService (real DB)', () => { expect(systemMsg!.senderAccountId).toBeNull(); }); }); + + describe('sellerSendConversationMessage IMAGE·ORDER_CARD', () => { + it('IMAGE는 판매자에게 발급된 URL을 저장하고 본문은 대체 문구다(다른 본문 무시, 감사 기록)', async () => { + const { account, store } = await setupSellerWithStore(prisma); + const conv = await setupConversation(store.id); + const imageUrl = ownedUploadUrl('CONVERSATION_IMAGE', account.id); + + const result = await service.sellerSendConversationMessage(account.id, { + conversationId: conv.id.toString(), + bodyFormat: 'IMAGE', + bodyText: '무시되는 본문', + imageUrl: ` ${imageUrl} `, + }); + + expect(result).toMatchObject({ + bodyFormat: 'IMAGE', + bodyText: '사진을 보냈습니다.', + bodyHtml: null, + imageUrl, + orderCard: null, + }); + const [row] = await prisma.storeConversationMessage.findMany({ + where: { conversation_id: conv.id }, + }); + expect(row).toMatchObject({ body_format: 'IMAGE', image_url: imageUrl }); + expect( + await prisma.auditLog.count({ + where: { store_id: store.id, target_type: 'CONVERSATION' }, + }), + ).toBe(1); + }); + + it.each([undefined, ' '])( + 'IMAGE인데 imageUrl이 %p면 IMAGE_URL_REQUIRED', + async (imageUrl) => { + const { account, store } = await setupSellerWithStore(prisma); + const conv = await setupConversation(store.id); + await expect( + service.sellerSendConversationMessage(account.id, { + conversationId: conv.id.toString(), + bodyFormat: 'IMAGE', + imageUrl, + }), + ).rejects.toThrowDomain('IMAGE_URL_REQUIRED'); + }, + ); + + const HOST = `${TEST_S3_CONFIG.bucket}.s3.${TEST_S3_CONFIG.region}.amazonaws.com`; + it.each([ + [ + '구매자 계정 경로', + (_seller: bigint, buyer: bigint) => + ownedUploadUrl('CONVERSATION_IMAGE', buyer), + ], + [ + '다른 용도 경로', + (seller: bigint) => ownedUploadUrl('PRODUCT_IMAGE', seller), + ], + [ + '인코딩된 dot(%2e) 우회', + (seller: bigint, buyer: bigint) => + `https://${HOST}/conversation-images/${seller}/%2e%2e/${buyer}/a.jpg`, + ], + ])('%s는 INVALID_IMAGE_URL', async (_label, urlOf) => { + const { account, store } = await setupSellerWithStore(prisma); + const conv = await setupConversation(store.id); + await expect( + service.sellerSendConversationMessage(account.id, { + conversationId: conv.id.toString(), + bodyFormat: 'IMAGE', + imageUrl: urlOf(account.id, conv.account_id), + }), + ).rejects.toThrowDomain('INVALID_IMAGE_URL'); + expect(await prisma.storeConversationMessage.count()).toBe(0); + }); + + it('ORDER_CARD는 구매자만 보낼 수 있어 INVALID_BODY_FORMAT', async () => { + const { account, store } = await setupSellerWithStore(prisma); + const conv = await setupConversation(store.id); + await expect( + service.sellerSendConversationMessage(account.id, { + conversationId: conv.id.toString(), + bodyFormat: 'ORDER_CARD', + bodyText: '주문 문의', + }), + ).rejects.toThrowDomain('INVALID_BODY_FORMAT'); + }); + + it('메시지 목록에 이미지·주문 카드 스냅샷이 실린다', async () => { + const { account, store } = await setupSellerWithStore(prisma); + const conv = await setupConversation(store.id); + const pickupAt = new Date('2026-08-03T03:00:00Z'); + await prisma.storeConversationMessage.create({ + data: { + conversation_id: conv.id, + sender_type: 'USER', + sender_account_id: conv.account_id, + body_format: 'ORDER_CARD', + body_text: '주문 문의: 케이크 (ORD-1)', + order_card_order_id: 77n, + order_card_order_number: 'ORD-1', + order_card_product_name: '케이크', + order_card_thumbnail_url: 'https://cdn.example.com/t.jpg', + order_card_pickup_at: pickupAt, + }, + }); + + const result = await service.sellerConversationMessages( + account.id, + conv.id, + ); + + expect(result.items[0]).toMatchObject({ + bodyFormat: 'ORDER_CARD', + imageUrl: null, + orderCard: { + orderId: '77', + orderNumber: 'ORD-1', + productName: '케이크', + thumbnailUrl: 'https://cdn.example.com/t.jpg', + pickupAt, + }, + }); + }); + }); }); diff --git a/src/features/conversation/services/conversation-seller.service.ts b/src/features/conversation/services/conversation-seller.service.ts index d0e54e9a..50c0e697 100644 --- a/src/features/conversation/services/conversation-seller.service.ts +++ b/src/features/conversation/services/conversation-seller.service.ts @@ -21,14 +21,20 @@ import { type IAuditLogRepository, } from '@/features/audit-log'; import { + CONVERSATION_IMAGE_ALT_TEXT, MAX_CONVERSATION_BODY_HTML_LENGTH, MAX_INQUIRY_BODY_TEXT_LENGTH, } from '@/features/conversation/constants/conversation.constants'; import type { SellerSendConversationMessageInput } from '@/features/conversation/dto/inputs/seller-send-conversation-message.input'; import { ConversationRepository } from '@/features/conversation/repositories/conversation.repository'; +import { requireOwnedConversationImageUrl } from '@/features/conversation/services/conversation-attachment.helper'; import { toLastMessagePreview } from '@/features/conversation/services/conversation-center-mappers.helper'; import { toEventPreview } from '@/features/conversation/services/conversation-events-mappers.helper'; import { ConversationEventsService } from '@/features/conversation/services/conversation-events.service'; +import { + toConversationMessageOutput, + type ConversationMessageRow, +} from '@/features/conversation/services/conversation-inquiry-mappers.helper'; import type { SellerConversationMessageOutput, SellerConversationOutput, @@ -39,6 +45,7 @@ import { AuditTargetType, ConversationBodyFormat, } from '@/generated/prisma/client'; +import { S3Service } from '@/global/storage/s3.service'; @Injectable() export class SellerConversationService extends SellerBaseService { @@ -50,6 +57,7 @@ export class SellerConversationService extends SellerBaseService { auditLogs: IAuditLogRepository, private readonly conversationRepository: ConversationRepository, private readonly conversationEvents: ConversationEventsService, + private readonly s3: S3Service, ) { super(repo, auditLogs); } @@ -154,33 +162,12 @@ export class SellerConversationService extends SellerBaseService { }); if (!conversation) throw new DomainException('CONVERSATION_NOT_FOUND'); - const bodyFormat = this.toConversationBodyFormat(input.bodyFormat); - const bodyText = cleanNullableText( - input.bodyText, - MAX_INQUIRY_BODY_TEXT_LENGTH, - ); - const bodyHtml = cleanNullableText( - input.bodyHtml, - MAX_CONVERSATION_BODY_HTML_LENGTH, - ); - - if (bodyFormat === ConversationBodyFormat.TEXT && !bodyText) { - throw new DomainException('BODY_TEXT_REQUIRED'); - } - if (bodyFormat === ConversationBodyFormat.HTML && !bodyHtml) { - throw new DomainException('BODY_HTML_REQUIRED'); - } + const body = this.toSellerMessageBody(input, ctx.accountId); // 감사 기록은 repository가 메시지 저장과 같은 트랜잭션에서 남긴다 const row = await this.conversationRepository.createSellerConversationMessage( - { - conversationId, - sellerAccountId: ctx.accountId, - bodyFormat, - bodyText, - bodyHtml, - }, + { conversationId, sellerAccountId: ctx.accountId, ...body }, (created) => ({ actorAccountId: ctx.accountId, storeId: ctx.storeId, @@ -234,15 +221,7 @@ export class SellerConversationService extends SellerBaseService { storeId: bigint; message: SellerConversationMessageOutput; }): Promise { - const message = { - id: args.message.id, - conversationId: args.message.conversationId, - senderType: args.message.senderType, - bodyFormat: args.message.bodyFormat, - bodyText: args.message.bodyText, - bodyHtml: args.message.bodyHtml, - createdAt: args.message.createdAt, - }; + const { message } = args; // 목록 이벤트는 발행 시점의 최신 커밋 상태를 단일 트랜잭션 스냅샷으로 조립한다 — 독립 조회로 쪼개면 // 경쟁 커밋이 끼어들어 혼합 상태가 나갈 수 있다. 메시지 스트림은 id 정렬. const snapshot = @@ -287,10 +266,54 @@ export class SellerConversationService extends SellerBaseService { ); } - private toConversationBodyFormat(raw: string): ConversationBodyFormat { - if (raw === 'TEXT') return ConversationBodyFormat.TEXT; - if (raw === 'HTML') return ConversationBodyFormat.HTML; - throw new DomainException('INVALID_BODY_FORMAT'); + /** IMAGE는 대체 문구만 본문으로 남긴다. 주문 카드는 구매자만 보낼 수 있다. */ + private toSellerMessageBody( + input: SellerSendConversationMessageInput, + sellerAccountId: bigint, + ): { + bodyFormat: ConversationBodyFormat; + bodyText: string | null; + bodyHtml: string | null; + imageUrl: string | null; + } { + switch (input.bodyFormat) { + case ConversationBodyFormat.IMAGE: + return { + bodyFormat: input.bodyFormat, + bodyText: CONVERSATION_IMAGE_ALT_TEXT, + bodyHtml: null, + imageUrl: requireOwnedConversationImageUrl( + this.s3, + input.imageUrl, + sellerAccountId, + ), + }; + case ConversationBodyFormat.TEXT: + case ConversationBodyFormat.HTML: { + const bodyText = cleanNullableText( + input.bodyText, + MAX_INQUIRY_BODY_TEXT_LENGTH, + ); + const bodyHtml = cleanNullableText( + input.bodyHtml, + MAX_CONVERSATION_BODY_HTML_LENGTH, + ); + if (input.bodyFormat === ConversationBodyFormat.TEXT && !bodyText) { + throw new DomainException('BODY_TEXT_REQUIRED'); + } + if (input.bodyFormat === ConversationBodyFormat.HTML && !bodyHtml) { + throw new DomainException('BODY_HTML_REQUIRED'); + } + return { + bodyFormat: input.bodyFormat, + bodyText, + bodyHtml, + imageUrl: null, + }; + } + default: + throw new DomainException('INVALID_BODY_FORMAT'); + } } private toConversationOutput( @@ -323,25 +346,12 @@ export class SellerConversationService extends SellerBaseService { }; } - private toConversationMessageOutput(row: { - id: bigint; - conversation_id: bigint; - sender_type: 'USER' | 'STORE' | 'SYSTEM'; - sender_account_id: bigint | null; - body_format: 'TEXT' | 'HTML'; - body_text: string | null; - body_html: string | null; - created_at: Date; - }): SellerConversationMessageOutput { + private toConversationMessageOutput( + row: ConversationMessageRow & { sender_account_id: bigint | null }, + ): SellerConversationMessageOutput { return { - id: row.id.toString(), - conversationId: row.conversation_id.toString(), - senderType: row.sender_type, + ...toConversationMessageOutput(row), senderAccountId: row.sender_account_id?.toString() ?? null, - bodyFormat: row.body_format, - bodyText: row.body_text, - bodyHtml: row.body_html, - createdAt: row.created_at, }; } } diff --git a/src/features/conversation/services/conversation-subscription.service.spec.ts b/src/features/conversation/services/conversation-subscription.service.spec.ts index b79a0aa8..667cb1b3 100644 --- a/src/features/conversation/services/conversation-subscription.service.spec.ts +++ b/src/features/conversation/services/conversation-subscription.service.spec.ts @@ -7,6 +7,7 @@ import { ConversationRepository } from '@/features/conversation/repositories/con import { ConversationEventsService } from '@/features/conversation/services/conversation-events.service'; import { ConversationInquiryService } from '@/features/conversation/services/conversation-inquiry.service'; import { ConversationSubscriptionService } from '@/features/conversation/services/conversation-subscription.service'; +import { OrderInquiryRepository } from '@/features/order'; import { CATALOG_QUERY, StoreSellerRepository } from '@/features/store'; import { StoreCatalogQueryRepository } from '@/features/store/repositories/store-catalog-query.repository'; import type { PrismaClient } from '@/generated/prisma/client'; @@ -20,6 +21,7 @@ import { } from '@/test/factories'; import { createTestingModuleWithRealDb } from '@/test/modules/testing-module.builder'; import { outboxPublisherProviders } from '@/test/outbox'; +import { s3TestProviders } from '@/test/storage/s3-test.helper'; describe('ConversationSubscriptionService (real DB)', () => { let service: ConversationSubscriptionService; @@ -32,6 +34,8 @@ describe('ConversationSubscriptionService (real DB)', () => { ConversationSubscriptionService, ConversationInquiryService, ConversationEventsService, + OrderInquiryRepository, + ...s3TestProviders(), ConversationRepository, // 발행 repository가 OutboxPublisher를 주입받는다 ...outboxPublisherProviders(), diff --git a/src/features/conversation/types/conversation-output.type.ts b/src/features/conversation/types/conversation-output.type.ts index 67d20982..bd46e17b 100644 --- a/src/features/conversation/types/conversation-output.type.ts +++ b/src/features/conversation/types/conversation-output.type.ts @@ -26,6 +26,14 @@ export interface StoreInquiryContextOutput { conversationId: string | null; } +export interface ConversationOrderCardOutput { + orderId: string; + orderNumber: string; + productName: string; + thumbnailUrl: string | null; + pickupAt: Date; +} + export interface ConversationMessageOutput { id: string; conversationId: string; @@ -33,6 +41,8 @@ export interface ConversationMessageOutput { bodyFormat: ConversationBodyFormat; bodyText: string | null; bodyHtml: string | null; + imageUrl: string | null; + orderCard: ConversationOrderCardOutput | null; createdAt: Date; } @@ -65,6 +75,12 @@ export interface ConversationMessageEvent { bodyFormat: ConversationBodyFormat; bodyText: string | null; bodyHtml: string | null; + imageUrl: string | null; + orderCard: + | (Omit & { + pickupAt: string; + }) + | null; createdAt: string; } diff --git a/src/features/conversation/types/conversation-seller-output.type.ts b/src/features/conversation/types/conversation-seller-output.type.ts index 61a93e1b..d76c9978 100644 --- a/src/features/conversation/types/conversation-seller-output.type.ts +++ b/src/features/conversation/types/conversation-seller-output.type.ts @@ -1,3 +1,5 @@ +import type { ConversationMessageOutput } from '@/features/conversation/types/conversation-output.type'; + export interface SellerConversationOutput { id: string; accountId: string; @@ -11,13 +13,6 @@ export interface SellerConversationOutput { updatedAt: Date; } -export interface SellerConversationMessageOutput { - id: string; - conversationId: string; - senderType: 'USER' | 'STORE' | 'SYSTEM'; +export interface SellerConversationMessageOutput extends ConversationMessageOutput { senderAccountId: string | null; - bodyFormat: 'TEXT' | 'HTML'; - bodyText: string | null; - bodyHtml: string | null; - createdAt: Date; } diff --git a/src/features/order/index.ts b/src/features/order/index.ts index a7f80945..a2070447 100644 --- a/src/features/order/index.ts +++ b/src/features/order/index.ts @@ -5,6 +5,11 @@ export { OrderRepository, type AdminOrderStatusCounts, } from '@/features/order/repositories/order.repository'; +// 채팅 주문 카드 원천과 숨김 매장 문의 허용 판정(conversation). +export { + OrderInquiryRepository, + type OrderCardSource, +} from '@/features/order/repositories/order-inquiry.repository'; // 주문 상태 전이 이벤트 계약(outbox). 소비자(notification)는 payload 스냅샷만 읽는다. export { ORDER_STATUS_CHANGED, diff --git a/src/features/order/order.module.ts b/src/features/order/order.module.ts index e0c805f8..a2e61da7 100644 --- a/src/features/order/order.module.ts +++ b/src/features/order/order.module.ts @@ -7,6 +7,7 @@ import { OrderCancelPolicy } from '@/features/order/policies/order-cancel.policy import { OrderStatusTransitionPolicy } from '@/features/order/policies/order-status-transition.policy'; import { OrderBookedRepository } from '@/features/order/repositories/order-booked.repository'; import { OrderCustomUploadRepository } from '@/features/order/repositories/order-custom-upload.repository'; +import { OrderInquiryRepository } from '@/features/order/repositories/order-inquiry.repository'; import { OrderStoreDailyLimitRepository } from '@/features/order/repositories/order-store-daily-limit.repository'; import { OrderTransitionRepository } from '@/features/order/repositories/order-transition.repository'; import { OrderRepository } from '@/features/order/repositories/order.repository'; @@ -106,9 +107,12 @@ import { StoreModule } from '@/features/store'; SellerSettlementService, SellerSettlementQueryResolver, SellerSettlementMutationResolver, + // 채팅 주문 카드·숨김 매장 문의 판정(conversation) + OrderInquiryRepository, ], exports: [ OrderRepository, + OrderInquiryRepository, OrderStatusTransitionPolicy, BOOKED_QUANTITY_QUERY, ], diff --git a/src/features/order/repositories/order-inquiry.repository.spec.ts b/src/features/order/repositories/order-inquiry.repository.spec.ts new file mode 100644 index 00000000..6d509b92 --- /dev/null +++ b/src/features/order/repositories/order-inquiry.repository.spec.ts @@ -0,0 +1,192 @@ +import { OrderInquiryRepository } from '@/features/order/repositories/order-inquiry.repository'; +import type { OrderStatus, PrismaClient } from '@/generated/prisma/client'; +import { disconnectTestPrismaClient } from '@/test/db/prisma-test-client'; +import { closeTruncateConnection, truncateAll } from '@/test/db/truncate'; +import { + createAccount, + createOrder, + createOrderItem, + createStore, +} from '@/test/factories'; +import { createTestingModuleWithRealDb } from '@/test/modules/testing-module.builder'; + +describe('OrderInquiryRepository (real DB)', () => { + let repo: OrderInquiryRepository; + let prisma: PrismaClient; + + beforeAll(async () => { + const { module, prisma: p } = await createTestingModuleWithRealDb({ + providers: [OrderInquiryRepository], + }); + repo = module.get(OrderInquiryRepository); + prisma = p; + }); + afterAll(async () => { + await closeTruncateConnection(); + await disconnectTestPrismaClient(); + }); + beforeEach(async () => { + await truncateAll(); + }); + + async function buyer() { + return createAccount(prisma, { account_type: 'USER' }); + } + + describe('findOrderCardSource', () => { + it.each([ + [ + '커스텀 대표 이미지 우선', + 'https://cdn.example.com/custom.jpg', + 'https://cdn.example.com/product.jpg', + 'https://cdn.example.com/custom.jpg', + ], + [ + '없으면 상품 대표 이미지', + null, + 'https://cdn.example.com/product.jpg', + 'https://cdn.example.com/product.jpg', + ], + ['둘 다 없으면 null', null, null, null], + ])('썸네일: %s', async (_label, custom, product, expected) => { + const account = await buyer(); + const store = await createStore(prisma); + const order = await createOrder(prisma, { account_id: account.id }); + await createOrderItem(prisma, { + order_id: order.id, + store_id: store.id, + product_name_snapshot: '딸기 케이크', + custom_preview_image_url: custom, + product_thumbnail_url_snapshot: product, + }); + + expect( + await repo.findOrderCardSource({ + orderId: order.id, + accountId: account.id, + }), + ).toEqual({ + orderId: order.id, + orderNumber: order.order_number, + storeId: store.id, + productName: '딸기 케이크', + thumbnailUrl: expected, + pickupAt: order.pickup_at, + submittedAt: order.submitted_at, + }); + }); + + it('삭제된 품목은 건너뛰고 남은 첫 품목을 쓴다', async () => { + const account = await buyer(); + const order = await createOrder(prisma, { account_id: account.id }); + await createOrderItem(prisma, { + order_id: order.id, + product_name_snapshot: '지운 품목', + deleted_at: new Date(), + }); + await createOrderItem(prisma, { + order_id: order.id, + product_name_snapshot: '남은 품목', + }); + + const source = await repo.findOrderCardSource({ + orderId: order.id, + accountId: account.id, + }); + expect(source?.productName).toBe('남은 품목'); + }); + + it('남의 주문·삭제된 주문·품목이 모두 지워진 주문은 null', async () => { + const account = await buyer(); + const others = await createOrder(prisma); + await createOrderItem(prisma, { order_id: others.id }); + const deleted = await createOrder(prisma, { + account_id: account.id, + deleted_at: new Date(), + }); + await createOrderItem(prisma, { order_id: deleted.id }); + const emptied = await createOrder(prisma, { account_id: account.id }); + await createOrderItem(prisma, { + order_id: emptied.id, + deleted_at: new Date(), + }); + + for (const order of [others, deleted, emptied]) { + expect( + await repo.findOrderCardSource({ + orderId: order.id, + accountId: account.id, + }), + ).toBeNull(); + } + }); + }); + + describe('existsInProgressOrderAtStore', () => { + it.each([ + ['PENDING_PAYMENT', true], + ['SUBMITTED', true], + ['CONFIRMED', true], + ['MADE', true], + ['PICKED_UP', false], + ['NO_SHOW', false], + ['CANCELED', false], + ] as [OrderStatus, boolean][])('%s 주문 → %s', async (status, expected) => { + const account = await buyer(); + const store = await createStore(prisma); + const order = await createOrder(prisma, { + account_id: account.id, + status, + }); + await createOrderItem(prisma, { order_id: order.id, store_id: store.id }); + + expect( + await repo.existsInProgressOrderAtStore({ + accountId: account.id, + storeId: store.id, + }), + ).toBe(expected); + }); + + it('다른 구매자·다른 매장·삭제된 주문·삭제된 품목은 세지 않는다', async () => { + const account = await buyer(); + const store = await createStore(prisma); + const elsewhere = await createStore(prisma); + const othersOrder = await createOrder(prisma); + await createOrderItem(prisma, { + order_id: othersOrder.id, + store_id: store.id, + }); + const elsewhereOrder = await createOrder(prisma, { + account_id: account.id, + }); + await createOrderItem(prisma, { + order_id: elsewhereOrder.id, + store_id: elsewhere.id, + }); + const deletedOrder = await createOrder(prisma, { + account_id: account.id, + deleted_at: new Date(), + }); + await createOrderItem(prisma, { + order_id: deletedOrder.id, + store_id: store.id, + }); + const deletedItemOrder = await createOrder(prisma, { + account_id: account.id, + }); + await createOrderItem(prisma, { + order_id: deletedItemOrder.id, + store_id: store.id, + deleted_at: new Date(), + }); + + expect( + await repo.existsInProgressOrderAtStore({ + accountId: account.id, + storeId: store.id, + }), + ).toBe(false); + }); + }); +}); diff --git a/src/features/order/repositories/order-inquiry.repository.ts b/src/features/order/repositories/order-inquiry.repository.ts new file mode 100644 index 00000000..3cef7636 --- /dev/null +++ b/src/features/order/repositories/order-inquiry.repository.ts @@ -0,0 +1,75 @@ +import { Injectable } from '@nestjs/common'; + +import { IN_PROGRESS_ORDER_STATUSES } from '@/features/order/constants/order-status-traits'; +import { activeWhere, PrismaService } from '@/prisma'; + +export interface OrderCardSource { + orderId: bigint; + orderNumber: string; + storeId: bigint; + productName: string; + thumbnailUrl: string | null; + pickupAt: Date; + /** 입금 확인(판매자 노출) 시각. null이면 판매자가 볼 수 없는 주문이다 */ + submittedAt: Date | null; +} + +/** 채팅(conversation)이 묻는 구매자 주문 읽기. */ +@Injectable() +export class OrderInquiryRepository { + constructor(private readonly prisma: PrismaService) {} + + /** 본인 주문의 카드 원천. 주문 1건 = 상품 1개라 첫 품목이 상품·매장을 대표한다. */ + async findOrderCardSource(args: { + orderId: bigint; + accountId: bigint; + }): Promise { + const order = await this.prisma.order.findFirst({ + where: { id: args.orderId, account_id: args.accountId }, + select: { + id: true, + order_number: true, + pickup_at: true, + submitted_at: true, + items: { + where: activeWhere, + orderBy: { id: 'asc' }, + take: 1, + select: { + store_id: true, + product_name_snapshot: true, + product_thumbnail_url_snapshot: true, + custom_preview_image_url: true, + }, + }, + }, + }); + const item = order?.items[0]; + if (!order || !item) return null; + return { + orderId: order.id, + orderNumber: order.order_number, + storeId: item.store_id, + productName: item.product_name_snapshot, + thumbnailUrl: + item.custom_preview_image_url ?? item.product_thumbnail_url_snapshot, + pickupAt: order.pickup_at, + submittedAt: order.submitted_at, + }; + } + + async existsInProgressOrderAtStore(args: { + accountId: bigint; + storeId: bigint; + }): Promise { + const found = await this.prisma.order.findFirst({ + where: { + account_id: args.accountId, + status: { in: [...IN_PROGRESS_ORDER_STATUSES] }, + items: { some: { store_id: args.storeId, ...activeWhere } }, + }, + select: { id: true }, + }); + return found !== null; + } +} diff --git a/src/features/product/dto/inputs/admin-create-upload-url.input.spec.ts b/src/features/product/dto/inputs/admin-create-upload-url.input.spec.ts index e77041da..a6cd2e07 100644 --- a/src/features/product/dto/inputs/admin-create-upload-url.input.spec.ts +++ b/src/features/product/dto/inputs/admin-create-upload-url.input.spec.ts @@ -23,18 +23,22 @@ describe('AdminCreateUploadUrlInput', () => { ); // 판매자 전용·미정의 용도는 스키마 단계에서 막히지만 DTO도 같은 집합을 강제한다 - it.each(['PRODUCT_IMAGE', 'PROFILE_IMAGE', 'REVIEW_VIDEO', '', undefined])( - 'purpose %s 거절', - async (purpose) => { - const dto = build({ - purpose, - contentType: 'image/png', - contentLength: 1, - }); - const errors = await validate(dto); - expect(errors[0].property).toBe('purpose'); - }, - ); + it.each([ + 'PRODUCT_IMAGE', + 'CONVERSATION_IMAGE', + 'PROFILE_IMAGE', + 'REVIEW_VIDEO', + '', + undefined, + ])('purpose %s 거절', async (purpose) => { + const dto = build({ + purpose, + contentType: 'image/png', + contentLength: 1, + }); + const errors = await validate(dto); + expect(errors[0].property).toBe('purpose'); + }); it('contentLength 0 거절', async () => { const dto = build({ diff --git a/src/features/product/dto/inputs/seller-create-upload-url.input.spec.ts b/src/features/product/dto/inputs/seller-create-upload-url.input.spec.ts index 407d2c8e..1ec1bcc0 100644 --- a/src/features/product/dto/inputs/seller-create-upload-url.input.spec.ts +++ b/src/features/product/dto/inputs/seller-create-upload-url.input.spec.ts @@ -10,7 +10,7 @@ function build(plain: object): SellerCreateUploadUrlInput { } describe('SellerCreateUploadUrlInput', () => { - it.each(['PRODUCT_IMAGE', 'STORE_IMAGE'])( + it.each(['PRODUCT_IMAGE', 'STORE_IMAGE', 'CONVERSATION_IMAGE'])( 'purpose %s 통과', async (purpose) => { const dto = build({ diff --git a/src/features/product/dto/inputs/seller-create-upload-url.input.ts b/src/features/product/dto/inputs/seller-create-upload-url.input.ts index b428ca4e..29106826 100644 --- a/src/features/product/dto/inputs/seller-create-upload-url.input.ts +++ b/src/features/product/dto/inputs/seller-create-upload-url.input.ts @@ -1,6 +1,10 @@ import { IsIn, IsInt, IsString, Min } from 'class-validator'; -export const SELLER_UPLOAD_PURPOSES = ['PRODUCT_IMAGE', 'STORE_IMAGE'] as const; +export const SELLER_UPLOAD_PURPOSES = [ + 'PRODUCT_IMAGE', + 'STORE_IMAGE', + 'CONVERSATION_IMAGE', +] as const; export type SellerUploadPurposeInput = (typeof SELLER_UPLOAD_PURPOSES)[number]; // contentType·contentLength의 허용 목록·상한은 S3Service.createUploadUrl이 담당한다. diff --git a/src/features/product/product-seller-upload.graphql b/src/features/product/product-seller-upload.graphql index 8945656c..f861a9ac 100644 --- a/src/features/product/product-seller-upload.graphql +++ b/src/features/product/product-seller-upload.graphql @@ -1,6 +1,6 @@ extend type Mutation { """ - 이미지 업로드용 Presigned URL을 발급한다. 판매자 로그인 필수. SELLER 계정이 아니면 FORBIDDEN, 매장을 보유하지 않으면 NOT_FOUND. 상품·옵션·커스텀 템플릿·매장 로고의 URL 필드는 여기서 발급된 publicUrl만 받는다. + 이미지 업로드용 Presigned URL을 발급한다. 판매자 로그인 필수. SELLER 계정이 아니면 FORBIDDEN, 매장을 보유하지 않으면 NOT_FOUND. 상품·옵션·커스텀 템플릿·매장 로고·채팅 이미지의 URL 필드는 여기서 발급된 publicUrl만 받는다. """ sellerCreateUploadUrl(input: SellerCreateUploadUrlInput!): UploadUrl! } @@ -18,7 +18,7 @@ input SellerCreateUploadUrlInput { """ contentType: String! """ - 파일 크기(바이트). 1 이상 5MB 이하, 아니면 BAD_USER_INPUT. + 파일 크기(바이트). 1 이상, 용도별 최대 크기(CONVERSATION_IMAGE 10MB, 그 밖 5MB) 이하. 아니면 BAD_USER_INPUT. """ contentLength: Int! } diff --git a/src/features/product/product-upload.types.graphql b/src/features/product/product-upload.types.graphql index 39f35cd7..1b9e41f5 100644 --- a/src/features/product/product-upload.types.graphql +++ b/src/features/product/product-upload.types.graphql @@ -1,6 +1,7 @@ """ 업로드 용도. 용도마다 저장 경로가 다르고, 저장 입력은 같은 용도로 발급된 URL만 받는다. -역할별 허용 범위: 판매자 PRODUCT_IMAGE·STORE_IMAGE, 관리자 BANNER_IMAGE·STORE_IMAGE(밖이면 BAD_USER_INPUT). +역할별 허용 범위: 판매자 PRODUCT_IMAGE·STORE_IMAGE·CONVERSATION_IMAGE, 관리자 BANNER_IMAGE·STORE_IMAGE(밖이면 BAD_USER_INPUT). +최대 크기는 CONVERSATION_IMAGE 10MB, 그 밖의 용도 5MB다. """ enum UploadPurpose { """ @@ -15,4 +16,8 @@ enum UploadPurpose { 플랫폼 배너 이미지(관리자). """ BANNER_IMAGE + """ + 채팅 첨부 이미지(판매자). sellerSendConversationMessage의 IMAGE 메시지가 이 용도 URL만 받는다. + """ + CONVERSATION_IMAGE } diff --git a/src/features/store/repositories/store-catalog-query.repository.interface.ts b/src/features/store/repositories/store-catalog-query.repository.interface.ts index e566883e..88f19766 100644 --- a/src/features/store/repositories/store-catalog-query.repository.interface.ts +++ b/src/features/store/repositories/store-catalog-query.repository.interface.ts @@ -12,7 +12,7 @@ export const CATALOG_QUERY = Symbol('CATALOG_QUERY'); export type InquiryStoreRow = Pick< Store, - 'id' | 'store_name' | 'profile_image_url' | 'greeting_message' + 'id' | 'store_name' | 'profile_image_url' | 'greeting_message' | 'is_active' > & { business_hours: Pick< StoreBusinessHour, @@ -24,7 +24,7 @@ export type FaqTopicSummaryRow = Pick; export type FaqTopicRow = Pick; export interface ICatalogQuery { - /** 노출 가능한(활성·미삭제) 매장만 — 문의 진입 화면의 매장 컨텍스트. */ + /** 삭제되지 않은 매장(숨김 포함) — 문의 진입 화면의 매장 컨텍스트. 숨김 매장 문의 허용은 호출부가 is_active로 가린다. */ findInquiryStore(storeId: bigint): Promise; listActiveFaqTopics(storeId: bigint): Promise; findActiveFaqTopic(args: { diff --git a/src/features/store/repositories/store-catalog-query.repository.spec.ts b/src/features/store/repositories/store-catalog-query.repository.spec.ts index 6e683efb..f5e831ca 100644 --- a/src/features/store/repositories/store-catalog-query.repository.spec.ts +++ b/src/features/store/repositories/store-catalog-query.repository.spec.ts @@ -62,15 +62,21 @@ describe('StoreCatalogQueryRepository (real DB)', () => { id: store.id, store_name: '문의 매장', greeting_message: '{nickname}님 환영', + is_active: true, }); expect(row!.business_hours.map((h) => h.day_of_week)).toEqual([1, 3]); }); - it.each([ - ['비활성 매장', { is_active: false }], - ['삭제된 매장', { deleted_at: new Date() }], - ])('%s은 null', async (_label, overrides) => { - const store = await createStore(prisma, overrides); + it('숨김 매장도 is_active=false로 돌려준다', async () => { + const store = await createStore(prisma, { is_active: false }); + expect(await repo.findInquiryStore(store.id)).toMatchObject({ + id: store.id, + is_active: false, + }); + }); + + it('삭제된 매장은 null', async () => { + const store = await createStore(prisma, { deleted_at: new Date() }); expect(await repo.findInquiryStore(store.id)).toBeNull(); }); }); diff --git a/src/features/store/repositories/store-catalog-query.repository.ts b/src/features/store/repositories/store-catalog-query.repository.ts index 86a5351e..b45d2aba 100644 --- a/src/features/store/repositories/store-catalog-query.repository.ts +++ b/src/features/store/repositories/store-catalog-query.repository.ts @@ -6,7 +6,7 @@ import type { ICatalogQuery, InquiryStoreRow, } from '@/features/store/repositories/store-catalog-query.repository.interface'; -import { activeWhere, PrismaService, visibleWhere } from '@/prisma'; +import { activeWhere, PrismaService } from '@/prisma'; /** CatalogQuery 포트의 모놀리스 구현. 서비스로 분리되면 클라이언트 구현으로 바뀐다. */ @Injectable() @@ -15,12 +15,13 @@ export class StoreCatalogQueryRepository implements ICatalogQuery { async findInquiryStore(storeId: bigint): Promise { return this.prisma.store.findFirst({ - where: { id: storeId, ...visibleWhere }, + where: { id: storeId, ...activeWhere }, select: { id: true, store_name: true, profile_image_url: true, greeting_message: true, + is_active: true, business_hours: { where: activeWhere, orderBy: { day_of_week: 'asc' }, diff --git a/src/global/storage/constants/storage.constants.ts b/src/global/storage/constants/storage.constants.ts index 9d5e4957..948fdcdd 100644 --- a/src/global/storage/constants/storage.constants.ts +++ b/src/global/storage/constants/storage.constants.ts @@ -51,4 +51,10 @@ export const UPLOAD_POLICIES: Record = { maxSizeBytes: 10 * 1024 * 1024, allowedContentTypes: ['image/jpeg', 'image/png', 'image/webp'], }, + // 채팅 첨부(구매자·판매자 공용). 계정별 경로라 보낸 사람 것만 메시지에 실을 수 있다 + CONVERSATION_IMAGE: { + keyPrefix: 'conversation-images', + maxSizeBytes: 10 * 1024 * 1024, + allowedContentTypes: ['image/jpeg', 'image/png', 'image/webp'], + }, } as const; diff --git a/src/global/storage/s3.service.spec.ts b/src/global/storage/s3.service.spec.ts index 023e9921..8df5ef1a 100644 --- a/src/global/storage/s3.service.spec.ts +++ b/src/global/storage/s3.service.spec.ts @@ -202,6 +202,7 @@ describe('S3Service', () => { ['ORDER_CUSTOM_RENDER', 'order-custom/renders/'], ['ORDER_CUSTOM_COMPOSITE', 'order-custom/composites/'], ['ORDER_CUSTOM_REFERENCE', 'order-custom/references/'], + ['CONVERSATION_IMAGE', 'conversation-images/'], ] as const)('%s purpose', (purpose, prefix) => { const input = { ...baseInput, purpose }; @@ -339,6 +340,7 @@ describe('S3Service', () => { ['PROFILE_IMAGE', 'profile-images', 'review-media/images'], ['REVIEW_IMAGE', 'review-media/images', 'profile-images'], ['REVIEW_VIDEO', 'review-media/videos', 'review-media/images'], + ['CONVERSATION_IMAGE', 'conversation-images', 'product-images'], ] as const; describe.each(PURPOSES)('%s', (purpose, prefix, otherPrefix) => { diff --git a/src/global/storage/types/storage.types.ts b/src/global/storage/types/storage.types.ts index f7525e59..9b7a0e77 100644 --- a/src/global/storage/types/storage.types.ts +++ b/src/global/storage/types/storage.types.ts @@ -7,7 +7,8 @@ export type UploadPurpose = | 'BANNER_IMAGE' | 'ORDER_CUSTOM_RENDER' | 'ORDER_CUSTOM_COMPOSITE' - | 'ORDER_CUSTOM_REFERENCE'; + | 'ORDER_CUSTOM_REFERENCE' + | 'CONVERSATION_IMAGE'; export interface CreateUploadUrlInput { accountId: bigint; diff --git a/src/test/enum-sdl-sync.spec.ts b/src/test/enum-sdl-sync.spec.ts index cb7f242a..dbbf9cff 100644 --- a/src/test/enum-sdl-sync.spec.ts +++ b/src/test/enum-sdl-sync.spec.ts @@ -19,6 +19,7 @@ import { RefundKind, RefundStatus, } from '@/generated/prisma/client'; +import { UPLOAD_POLICIES } from '@/global/storage/constants/storage.constants'; /** * 응답에 그대로 실리는 Prisma enum·TS 상수 union은 SDL enum이 그 값을 모두 가져야 한다. 하나라도 빠지면 @@ -129,6 +130,12 @@ const INPUT_PAIRS: Array< 'src/features/order/order-checkout.graphql', 'OrderCustomUploadPurpose', ], + [ + 'UploadPurpose', + Object.keys(UPLOAD_POLICIES), + 'src/features/product/product-upload.types.graphql', + 'UploadPurpose', + ], ]; function missingFrom(values: string[], target: string[]): string[] { From ea0e11c60cd9aa61253888dc2fb47fb1cb0a9e99 Mon Sep 17 00:00:00 2001 From: chanwoo7 Date: Thu, 19 Nov 2026 06:08:36 +0900 Subject: [PATCH 2/2] =?UTF-8?q?fix:=20=EC=82=AC=EC=A7=84=20=EB=AF=B8?= =?UTF-8?q?=EC=B2=A8=EB=B6=80=20=EC=98=A4=EB=A5=98=20=EB=AC=B8=EA=B5=AC?= =?UTF-8?q?=EB=A5=BC=20=EC=82=AC=EC=9A=A9=EC=9E=90=20=EB=AC=B8=EC=9E=A5?= =?UTF-8?q?=EC=9C=BC=EB=A1=9C=20=EB=B0=94=EA=BE=B8=EA=B3=A0=20=EC=88=A8?= =?UTF-8?q?=EA=B9=80=20=EB=A7=A4=EC=9E=A5=20FAQ=C2=B7=EC=9D=B4=EB=AF=B8?= =?UTF-8?q?=EC=A7=80=20=EA=B1=B0=EC=A0=88=20=ED=9A=8C=EA=B7=80=20=ED=85=8C?= =?UTF-8?q?=EC=8A=A4=ED=8A=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - IMAGE_URL_REQUIRED 메시지가 enum 값·필드명을 그대로 드러내 판매자 앱에 그대로 보일 수 없었음. 신규 에러는 사용자에게 보여 줄 한국어 문장이어야 함. - 숨김 매장 판정이 repository에서 service로 옮겨지며 FAQ·이미지 전송의 거절은 검증되지 않았음. 변경 - error-catalog: IMAGE_URL_REQUIRED '보낼 사진을 첨부해 주세요.' - order 배럴: 밖에서 쓰지 않는 OrderCardSource 타입 노출 제거 테스트 - 숨김 매장에 끝난·취소된 주문만 있으면 FAQ·이미지 전송도 STORE_NOT_FOUND, 메시지 0건(2건 보강) - 진행 중 주문이 있으면 이미지 전송도 허용(1건 보강) - 반증: FAQ·이미지 경로의 판정을 각각 건너뛰게 바꾸면 거절 케이스 2건이 실패함을 확인하고 되돌림 --- src/common/errors/error-catalog.ts | 2 +- .../conversation-inquiry.service.spec.ts | 26 ++++++++++++++++--- src/features/order/index.ts | 5 +--- 3 files changed, 25 insertions(+), 8 deletions(-) diff --git a/src/common/errors/error-catalog.ts b/src/common/errors/error-catalog.ts index 288f5c50..1083f0d7 100644 --- a/src/common/errors/error-catalog.ts +++ b/src/common/errors/error-catalog.ts @@ -662,7 +662,7 @@ export const ERROR_CATALOG = { }, IMAGE_URL_REQUIRED: { status: HttpStatus.BAD_REQUEST, - message: 'IMAGE 형식에는 imageUrl이 필요합니다.', + message: '보낼 사진을 첨부해 주세요.', }, ORDER_INQUIRY_NOT_AVAILABLE: { status: HttpStatus.BAD_REQUEST, diff --git a/src/features/conversation/services/conversation-inquiry.service.spec.ts b/src/features/conversation/services/conversation-inquiry.service.spec.ts index af0c7312..f4bc31da 100644 --- a/src/features/conversation/services/conversation-inquiry.service.spec.ts +++ b/src/features/conversation/services/conversation-inquiry.service.spec.ts @@ -551,7 +551,7 @@ describe('ConversationInquiryService (real DB)', () => { } describe('숨김 매장 문의(그 매장에 진행 중인 주문이 있는 구매자만)', () => { - it('진행 중인 주문이 있으면 문의 컨텍스트 조회·텍스트·FAQ 전송을 허용한다', async () => { + it('진행 중인 주문이 있으면 문의 컨텍스트 조회·텍스트·FAQ·이미지 전송을 허용한다', async () => { const buyer = await setupBuyer(); const store = await createStore(prisma, { is_active: false }); const faq = await createFaq(store.id); @@ -569,6 +569,11 @@ describe('ConversationInquiryService (real DB)', () => { faqTopicId: faq.id.toString(), }); expect(faqResult.messages).toHaveLength(2); + const imageResult = await service.sendConversationImageMessage(buyer.id, { + storeId: store.id.toString(), + imageUrl: ownedUploadUrl('CONVERSATION_IMAGE', buyer.id), + }); + expect(imageResult.messages.map((m) => m.bodyFormat)).toEqual(['IMAGE']); }); it.each([ @@ -577,17 +582,32 @@ describe('ConversationInquiryService (real DB)', () => { ] as const)('%s이면 STORE_NOT_FOUND', async (_label, status) => { const buyer = await setupBuyer(); const store = await createStore(prisma, { is_active: false }); + const faq = await createFaq(store.id); await orderAt(buyer.id, store.id, { status }); + const storeId = store.id.toString(); await expect( - service.storeInquiryContext(buyer.id, store.id.toString()), + service.storeInquiryContext(buyer.id, storeId), ).rejects.toThrowDomain('STORE_NOT_FOUND'); await expect( service.sendConversationMessage(buyer.id, { - storeId: store.id.toString(), + storeId, bodyText: '문의', }), ).rejects.toThrowDomain('STORE_NOT_FOUND'); + await expect( + service.sendConversationFaqMessage(buyer.id, { + storeId, + faqTopicId: faq.id.toString(), + }), + ).rejects.toThrowDomain('STORE_NOT_FOUND'); + await expect( + service.sendConversationImageMessage(buyer.id, { + storeId, + imageUrl: ownedUploadUrl('CONVERSATION_IMAGE', buyer.id), + }), + ).rejects.toThrowDomain('STORE_NOT_FOUND'); + expect(await prisma.storeConversationMessage.count()).toBe(0); }); it('다른 구매자·다른 매장의 진행 주문은 허용 근거가 아니고, 삭제된 매장은 진행 주문이 있어도 거절한다', async () => { diff --git a/src/features/order/index.ts b/src/features/order/index.ts index a2070447..185781a3 100644 --- a/src/features/order/index.ts +++ b/src/features/order/index.ts @@ -6,10 +6,7 @@ export { type AdminOrderStatusCounts, } from '@/features/order/repositories/order.repository'; // 채팅 주문 카드 원천과 숨김 매장 문의 허용 판정(conversation). -export { - OrderInquiryRepository, - type OrderCardSource, -} from '@/features/order/repositories/order-inquiry.repository'; +export { OrderInquiryRepository } from '@/features/order/repositories/order-inquiry.repository'; // 주문 상태 전이 이벤트 계약(outbox). 소비자(notification)는 payload 스냅샷만 읽는다. export { ORDER_STATUS_CHANGED,