From c8f930f8a24f3fc2b2422b7d447b9f2f3142bc4f Mon Sep 17 00:00:00 2001 From: chanwoo7 Date: Thu, 19 Nov 2026 08:11:23 +0900 Subject: [PATCH 01/14] =?UTF-8?q?feat:=20=EC=8A=A4=ED=82=A4=EB=A7=88=20?= =?UTF-8?q?=EA=B0=B1=EC=8B=A0=EA=B3=BC=20=EC=83=81=ED=92=88=C2=B7=EC=A3=BC?= =?UTF-8?q?=EB=AC=B8=20=EC=BB=A4=EC=8A=A4=ED=85=80=20=ED=91=9C=EC=8B=9C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit BE 커스텀·주문 흐름 릴리즈(#588, develop b2ee9d3)의 SDL을 받고 깨지는 화면을 맞춘 뒤, 관리자가 렌더러 없이 커스텀 주문과 상품 커스텀 설정을 확인할 수 있게 한다. 3D는 판매자 앱만 렌더러를 갖고 관리자는 구매자가 올린 캡처로 본다. - 스키마: schema:pull(BE_DIR, b2ee9d3) → codegen - 삭제 필드 제거: AdminProduct.baseDesignImageUrl → thumbnailUrl(목록 썸네일), 옵션 그룹 optionRequires*, 템플릿 isActive, 자유 편집 cropImageUrl - adminCancelOrder reason 필수: 지금 다이얼로그는 사유 코드 선택이 없어 OTHER + 메모로 보낸다(메모 상한 494 → 500, '[관리자]' 접두 안내 삭제). cancelOptions 기반 다이얼로그는 다음 PR - 감사 대상 라벨 5종(결제 설정·정산 계좌·정산·환불·입금 기록) - 커스텀 공용(features/custom): 방식·정렬·이미지 종류 라벨(Record + 모르는 값 원문 폴백), 문구 상태(기본 그대로/바꿈/문구 없음), 0~10000 좌표 → % 변환(범위 밖 자름), 렌더 이미지 순서(윗면 → 앞·뒤·왼·오), 글자색 견본 - 주문 상세: 3D 렌더 5장(윗면 크게), 슬롯형 합성 이미지 + 문구 자리 표(입력 문구·기본 대비·글자색·정렬), 자유 편집은 바탕 위 번호 영역 + 요청 문구 + 참고 사진. 주문 목록에 hasCustom '커스텀' 배지 - 상품 상세: '커스텀 설정' 카드(방식·자유 편집·문구 자리 표시 이름·키·기본 문구·최대 글자 수·필수·글자색·정렬, 3D 안내, 슬롯형이 아닌데 남은 템플릿 안내), 선택지 3D 연결 키 칩, '입력 필요' 경고 제거 테스트: custom-geometry(좌표 7경우·이미지 순서 5경우), 커스텀 meta(SDL enum 전수 라벨·모르는 값·프로토타입 키 폴백·문구 상태 7경우), 감사 meta(새 라벨 5종·모르는 유형), 주문 페이지(슬롯형 표·자유 편집 영역 %·3D 순서·옛 주문 2경우·비커스텀·목록 배지·취소 입력), 상품 페이지(썸네일·3D 키 칩·커스텀 카드 4경우). 반증: 크기 자르기·정렬·제자리 정렬·hasOwn 폴백·기본 문구 정규화·감사 라벨 누락을 각각 되돌리면 해당 케이스가 실패한다. --- schema/schema.graphql | 3651 +++++++++++++++-- src/features/audit-logs/meta.spec.ts | 18 + src/features/audit-logs/meta.ts | 5 + .../custom/components/color-swatch.tsx | 16 + src/features/custom/custom-geometry.spec.ts | 62 + src/features/custom/custom-geometry.ts | 52 + src/features/custom/index.ts | 9 + src/features/custom/meta.spec.ts | 77 + src/features/custom/meta.ts | 42 + src/features/orders/api/queries.ts | 27 +- .../orders/components/cancel-order-dialog.tsx | 6 +- .../components/order-detail-sections.tsx | 67 +- .../orders/components/order-item-custom.tsx | 215 + .../orders/components/orders-table.tsx | 18 +- src/features/orders/pages/orders.spec.tsx | 250 +- src/features/products/api/queries.ts | 12 +- .../components/product-custom-card.tsx | 103 + .../components/product-options-card.tsx | 6 + .../components/product-template-card.tsx | 72 - .../products/components/products-table.tsx | 4 +- src/features/products/option-rules.spec.ts | 33 +- src/features/products/option-rules.ts | 32 +- .../products/pages/product-detail-page.tsx | 4 +- src/features/products/pages/products.spec.tsx | 116 +- src/graphql/generated/gql.ts | 24 +- src/graphql/generated/graphql.ts | 156 +- 26 files changed, 4416 insertions(+), 661 deletions(-) create mode 100644 src/features/custom/components/color-swatch.tsx create mode 100644 src/features/custom/custom-geometry.spec.ts create mode 100644 src/features/custom/custom-geometry.ts create mode 100644 src/features/custom/index.ts create mode 100644 src/features/custom/meta.spec.ts create mode 100644 src/features/custom/meta.ts create mode 100644 src/features/orders/components/order-item-custom.tsx create mode 100644 src/features/products/components/product-custom-card.tsx delete mode 100644 src/features/products/components/product-template-card.tsx diff --git a/schema/schema.graphql b/schema/schema.graphql index 85f87d0..df0b1bf 100644 --- a/schema/schema.graphql +++ b/schema/schema.graphql @@ -1,9 +1,9 @@ -# 생성 파일 — 수정하지 않는다. caquick-be main@b3fe44f45b6940700e03723f7c6abe17f1656a29 의 src/features/**/*.graphql 68개를 경로순으로 합쳤다. +# 생성 파일 — 수정하지 않는다. caquick-be local@b2ee9d3b7353182fdfa5ad5d70d22f4364cbeb2d 의 src/features/**/*.graphql 77개를 경로순으로 합쳤다. # 갱신: pnpm schema:pull [ref] # ---- src/features/audit-log/audit-log.types.graphql ---- """ -감사 로그가 가리키는 대상 종류. 판매자 화면(sellerAuditLogs)은 STORE·PRODUCT·ORDER·CONVERSATION·CHANGE_PASSWORD만 노출하고 필터 입력도 그 범위만 받는다. +감사 로그가 가리키는 대상 종류. 판매자 화면(sellerAuditLogs)은 STORE·PRODUCT·ORDER·CONVERSATION·CHANGE_PASSWORD·SETTLEMENT_ACCOUNT만 노출하고 필터 입력도 그 범위만 받는다. """ enum AuditTargetType { """ @@ -66,6 +66,26 @@ enum AuditTargetType { 검색 진입 화면 키워드 바로가기 칩. 순서 변경은 순서가 바뀐 칩마다 1건씩 남는다. """ SEARCH_KEYWORD_CHIP + """ + 플랫폼 결제 설정(수수료율·입금 계좌). + """ + PAYMENT_SETTING + """ + 매장 정산 계좌(판매자 본인·관리자 대리 수정). 기록에는 계좌번호 끝 4자리만 남고, 판매자 감사 로그에도 보인다. + """ + SETTLEMENT_ACCOUNT + """ + 주간 정산(송금 완료 처리). + """ + SETTLEMENT + """ + 환불(완료 처리). + """ + REFUND + """ + 입금 기록(반환 연결·주인 모를 입금 종결). + """ + DEPOSIT_RECORD } """ @@ -434,7 +454,8 @@ extend type Mutation { """ updateMyProfileImage(input: UpdateMyProfileImageInput!): MePayload! """ - 회원 탈퇴(soft delete). 로그인 필수. 본인 데이터만 대상이 된다. + 회원 탈퇴(soft delete). 진행 중인 주문(입금 대기~제작 완료)이나 송금이 끝나지 않은 환불(계좌 입력 대기·송금 대기)이 있으면 + ACCOUNT_HAS_ACTIVE_ORDERS(CONFLICT, 메시지에 건수). 로그인 필수. 본인 데이터만 대상이 된다. """ deleteMyAccount: Boolean! """ @@ -710,6 +731,7 @@ extend type Query { 문의 채팅 진입 컨텍스트(구매자). 매장 프로필·상담시간·치환 완료 인사말·질문 칩을 한 번에 내려준다. 아직 대화가 없어도 조회 가능하며 그 경우 conversationId는 null. 로그인 필수. + 숨김 매장은 그 매장에 진행 중인 주문이 있는 구매자만 조회할 수 있다(아니면 STORE_NOT_FOUND). 문의 전송도 같다. """ storeInquiryContext(storeId: ID!): StoreInquiryContext! } @@ -727,6 +749,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! } """문의 채팅 진입 컨텍스트""" @@ -773,10 +818,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! } @@ -797,6 +846,14 @@ input SendConversationMessageInput { bodyText: String! } +"""구매자 이미지 메시지 전송 입력""" +input SendConversationImageMessageInput { + """문의할 매장 ID. 대화방이 없으면 이 호출에서 생성된다.""" + storeId: ID! + """createConversationImageUploadUrl이 이 계정에 발급한 publicUrl.""" + imageUrl: String! +} + """질문 칩(FAQ) 전송 입력""" input SendConversationFaqMessageInput { """문의할 매장 ID. 대화방이 없으면 이 호출에서 생성된다.""" @@ -823,6 +880,7 @@ extend type Query { extend type Mutation { """ 판매자 메시지를 발송한다. 판매자 로그인 필수. SELLER 계정이 아니면 FORBIDDEN, 매장을 보유하지 않으면 NOT_FOUND. + bodyFormat은 TEXT·HTML·IMAGE이고 ORDER_CARD는 INVALID_BODY_FORMAT이다(주문 카드는 구매자만 보낸다). """ sellerSendConversationMessage( input: SellerSendConversationMessageInput! @@ -926,6 +984,14 @@ type SellerConversationMessage { """ bodyHtml: String """ + 이미지 URL. bodyFormat이 IMAGE면 채워진다(bodyText에는 대체 문구 '사진을 보냈습니다.'). + """ + imageUrl: String + """ + 주문 카드. bodyFormat이 ORDER_CARD(구매자가 보낸 카드)면 채워진다. orderId로 주문 상세를 연다. + """ + orderCard: ConversationOrderCard + """ 발송 시각. """ createdAt: DateTime! @@ -960,7 +1026,8 @@ type SellerConversationMessageConnection { input SellerSendConversationMessageInput { conversationId: ID! """ - 본문 형식. 이 값에 해당하는 본문 필드가 필수다(다른 쪽을 함께 넘기면 그대로 저장된다). + 본문 형식. 이 값에 해당하는 본문 필드가 필수다(TEXT·HTML은 다른 쪽을 함께 넘기면 그대로 저장된다). + IMAGE는 imageUrl만 저장하고 본문은 대체 문구로 채운다. ORDER_CARD는 INVALID_BODY_FORMAT이다. """ bodyFormat: ConversationBodyFormat! """ @@ -971,6 +1038,11 @@ input SellerSendConversationMessageInput { 서식 본문(최대 100000자). bodyFormat이 HTML이면 필수. """ bodyHtml: String + """ + 이미지 URL. bodyFormat이 IMAGE면 필수(없으면 IMAGE_URL_REQUIRED)이고 sellerCreateUploadUrl(CONVERSATION_IMAGE)로 + 이 계정에 발급된 publicUrl이어야 한다(아니면 INVALID_IMAGE_URL). 다른 형식에서는 무시한다. + """ + imageUrl: String } # ---- src/features/conversation/conversation-subscription.graphql ---- @@ -1053,6 +1125,30 @@ 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! } # ---- src/features/core/pagination.graphql ---- @@ -1287,7 +1383,7 @@ type AdminDashboardSummary { """ orderCounts: AdminOrderStatusCounts! """ - 기간 내 생성된 주문의 최종 결제 금액 합(원). 취소 주문은 제외. + 기간 내 생성된 주문의 최종 결제 금액 합(원). 취소·입금 대기 주문은 제외. Int(32비트)를 넘을 수 있어 Float로 내리지만 값은 항상 정수다. """ orderAmountSum: Float! @@ -1309,6 +1405,10 @@ type AdminDashboardSummary { 주문 상태별 건수. """ type AdminOrderStatusCounts { + """ + 입금 대기(PENDING_PAYMENT). + """ + pendingPayment: Int! """ 접수(SUBMITTED). """ @@ -1326,6 +1426,10 @@ type AdminOrderStatusCounts { """ pickedUp: Int! """ + 노쇼(NO_SHOW). + """ + noShow: Int! + """ 취소(CANCELED). """ canceled: Int! @@ -1410,15 +1514,15 @@ type SellerDashboard { """ asOf: DateTime! """ - 접수(SUBMITTED) 상태로 남아 있는 주문 수. 날짜와 무관하게 전체를 센다. + 접수(SUBMITTED) 상태로 남아 있는 주문 수. 날짜와 무관하게 전체를 센다. 입금 대기 주문은 세지 않는다. """ newOrderCount: Int! """ - 기준일에 픽업 예정인 주문의 건수·금액. 취소 주문은 제외. 시안의 '오늘 매출 / 정산예정'에 해당한다. + 기준일에 픽업 예정인 주문의 건수·금액. 입금 대기·취소 주문은 제외. 시안의 '오늘 매출 / 정산예정'에 해당한다. """ pickupDay: SellerDashboardOrderMetrics! """ - 기준일에 생성된 주문의 건수·금액. 취소 주문은 제외. 접수 추세 표기('+N')용. + 기준일에 접수(입금 확인)된 주문의 건수·금액. 취소 주문은 제외. 접수 추세 표기('+N')용. """ createdDay: SellerDashboardOrderMetrics! """ @@ -1431,10 +1535,14 @@ type SellerDashboard { """ remainingCapacity: Int """ - 기준일 픽업 주문의 제작 수량 합(취소 제외). capacity 유무와 무관하게 센다. + 기준일 픽업 주문의 제작 수량 합(취소 제외, 입금 대기 포함). capacity 유무와 무관하게 센다. """ bookedQuantity: Int! """ + bookedQuantity 중 입금 대기 주문의 수량. 입금 대기 주문은 판매자에게 보이지 않지만 제작 수량을 차지한다('입금 대기 n개 포함' 표기용). + """ + pendingPaymentQuantity: Int! + """ 노출 중(is_active)인 내 상품 수. 매장 노출 여부와 무관하다. """ activeProductCount: Int! @@ -1499,7 +1607,7 @@ type MyPageCounts { } """ -진행중 주문 요약 카드. 픽업 완료·취소는 제외된다. +진행중 주문 요약 카드. 입금 대기부터 제작 완료까지만 담고, 픽업 완료·노쇼·취소는 제외된다. """ type OngoingOrderSummary { orderId: ID! @@ -2412,7 +2520,7 @@ enum PushPlatform { """ enum NotificationType { """ - 주문 상태 변경 알림. ORDER_CONFIRMED·ORDER_MADE·ORDER_PICKED_UP 이벤트가 여기 속한다. + 주문 상태 변경 알림. 주문(ORDER_*)·환불(REFUND_*) 이벤트가 여기 속한다. """ ORDER_STATUS """ @@ -2450,9 +2558,33 @@ enum NotificationEvent { """ ORDER_PICKED_UP """ - 주문이 취소됐다(판매자 또는 운영자). type은 ORDER_STATUS. + 주문이 취소됐다(판매자·운영자·자동 미확정). 본문 끝에 사유 라벨이 붙고, 구매자 본인 취소는 알림이 없다. type은 ORDER_STATUS. """ ORDER_CANCELED + """ + 입금이 확인돼 주문이 접수됐다. type은 ORDER_STATUS. + """ + ORDER_PAYMENT_CONFIRMED + """ + 입금이 확인되지 않아 주문이 취소됐다(입금 기한 만료 자동 취소 또는 운영자 미입금 취소). type은 ORDER_STATUS. + """ + ORDER_PAYMENT_EXPIRED + """ + 픽업 시간에 방문하지 않아 노쇼로 처리됐다. type은 ORDER_STATUS. + """ + ORDER_NO_SHOW + """ + 판매자가 픽업 일시를 바꿨다. type은 ORDER_STATUS. + """ + ORDER_PICKUP_RESCHEDULED + """ + 돌려받을 돈이 생겨 환불 계좌 입력이 필요하다. type은 ORDER_STATUS. + """ + REFUND_ACCOUNT_REQUESTED + """ + 환불 송금이 끝났다. type은 ORDER_STATUS. + """ + REFUND_COMPLETED } # ---- src/features/order/order-admin.graphql ---- @@ -2465,15 +2597,35 @@ extend type Query { 주문 상세를 전체 품목·구매자 요약·상태 이력과 함께 조회한다. 없으면 NOT_FOUND. 관리자 로그인 필수. ADMIN 계정이 아니면 FORBIDDEN. """ adminOrder(orderId: ID!): AdminOrderDetail! + """ + 매장의 진행 중 주문(입금 대기·접수·확정·제작 완료) 건수를 상태별로 센다. 판매자 정지·매장 숨김 전 경고용이며 + 없는 매장이면 0건이다. 관리자 로그인 필수. ADMIN 계정이 아니면 FORBIDDEN. + """ + adminStoreInProgressOrderSummary( + storeId: ID! + ): AdminStoreInProgressOrderSummary! } extend type Mutation { """ - 주문을 강제 취소한다. 전이 규칙은 판매자 취소와 같다 — SUBMITTED·CONFIRMED·MADE에서만 가능하고 - PICKED_UP·CANCELED면 BAD_USER_INPUT. 사유(note)는 필수이며 상태 이력에 '[관리자]' 접두로 기록된다. - 구매자에게 ORDER_CANCELED 알림이 간다. 없으면 NOT_FOUND. 관리자 로그인 필수. ADMIN 계정이 아니면 FORBIDDEN. + 주문을 강제 취소한다. 입금 대기·접수·확정·제작 완료 주문만 되고(그 밖은 ORDER_NOT_CANCELLABLE), 규칙은 adminOrder의 + cancelOptions가 그대로 알려 준다. 입금 대기는 환불 없이(미입금이면 reason PAYMENT_NOT_RECEIVED), 접수는 결제액 전액, + 확정·제작 완료는 fault(사정)에 따라 환불한다(판매자 사정 = 전액, 구매자 사정 = refundAmount, 남는 금액은 수수료를 뺀 뒤 정산에 포함). + 고를 수 없는 사유면 CANCEL_REASON_NOT_ALLOWED, 사정이 없으면 CANCEL_FAULT_REQUIRED, 구매자 사정인데 금액이 없으면 + REFUND_AMOUNT_REQUIRED, 금액이 0~결제액 밖이면 REFUND_AMOUNT_OUT_OF_RANGE(모두 BAD_USER_INPUT). + 구매자에게 취소 알림(미입금이면 입금 기한 만료 알림)이, 입금 확인 뒤 주문이면 판매자에게 취소 푸시가 간다. + 없으면 NOT_FOUND. 관리자 로그인 필수. ADMIN 계정이 아니면 FORBIDDEN. """ adminCancelOrder(input: AdminCancelOrderInput!): AdminOrderSummary! + """ + 주문을 픽업 완료로 처리한다. 확정·제작 완료 주문만 되고(이미 픽업 완료면 ORDER_STATUS_UNCHANGED, 그 밖은 + INVALID_ORDER_STATUS_TRANSITION, 모두 BAD_USER_INPUT), 매장이 숨김이어도 픽업 시각 전이어도 처리한다. + 확인된 결제액으로 정산을 확정하고(결제 도입 전 주문은 건너뜀) 구매자에게 픽업 완료 알림이 간다. + 없으면 NOT_FOUND. 관리자 로그인 필수. ADMIN 계정이 아니면 FORBIDDEN. + """ + adminCompleteOrderPickup( + input: AdminCompleteOrderPickupInput! + ): AdminOrderSummary! } """ @@ -2529,6 +2681,14 @@ type AdminOrderSummary { 첫 품목의 상품 대표 이미지 URL(주문 시점 스냅샷). 주문 당시 이미지가 없었거나 품목이 없으면 null. """ firstItemImageUrl: String + """ + 커스텀 주문 여부(첫 품목의 커스텀 방식이 NONE이 아니면 true). 목록 '커스텀' 배지용이다. + """ + hasCustom: Boolean! + """ + 첫 품목의 커스텀 대표 이미지 URL(3D 윗면 렌더 또는 슬롯형 합성). 없으면 null. + """ + firstItemCustomImageUrl: String } """ @@ -2605,6 +2765,14 @@ type AdminOrderDetail { """ buyerPhone: String! """ + 구매자가 남긴 요청 사항. 없으면 null. + """ + requestNote: String + """ + 결제와 입금 확인 기록. 결제 도입 전 주문이면 null. + """ + payment: AdminOrderPayment + """ 할인 전 품목 합계(원). """ subtotalPrice: Int! @@ -2646,6 +2814,111 @@ type AdminOrderDetail { 상태 변경 이력. 최신순. """ statusHistories: [OrderStatusHistory!]! + """ + 이 주문의 환불(취소 환불·입금 반환). 오래된 순, 없으면 빈 배열. + """ + refunds: [OrderRefund!]! + """ + 취소 정보(주체·사유·사정·환불액·환불 진행). 취소되지 않은 주문이면 null. + """ + cancellation: OrderCancellation + """ + 강제 취소 다이얼로그의 선택지. 지금 상태 기준이다. + """ + cancelOptions: AdminOrderCancelOptions! + """ + 판매자 확정 마감 시각. 지나면 자동 취소·전액 환불된다. 접수(SUBMITTED) 상태가 아니거나 결제 도입 전 주문이면 null. + """ + confirmDeadlineAt: DateTime + """ + 자동 픽업 완료 예정 시각(픽업 시각 + 24시간). 확정·제작 완료 상태에서만 있고 그 밖은 null. + 매장이 숨김이면 자동으로 픽업 완료되지 않으므로 관리자가 건별로 픽업 완료(adminCompleteOrderPickup)하거나 취소(adminCancelOrder)한다. + """ + autoPickupAt: DateTime + """ + 노쇼 처리 시각. 노쇼가 아니면 null. + """ + noShowAt: DateTime + """ + 판매자 픽업 일시 변경 이력. 오래된 순, 없으면 빈 배열. + """ + pickupChanges: [OrderPickupChange!]! + """ + 주문 생성 시점의 수수료율(bp, 1bp = 0.01%). 바뀐 설정은 그 뒤 주문부터 적용된다. + """ + commissionRateBps: Int! + """ + 정산 예정 금액(원). 정산 확정 뒤에는 실제 지급액(기준액 − 수수료), 확정 전에는 결제 금액에서 수수료(원 미만 버림)를 뺀 + 예상값이다. 입금이 확인되지 않았거나 결제 도입 전 주문이면 null, 확정 없이 취소된 주문(전액 환불)은 0. + """ + expectedPayoutAmount: Int + """ + 확정된 수수료 기준액(원). 픽업 완료·노쇼는 결제 금액, 구매자 사정 취소는 결제 금액 − 환불 금액. 확정 전이면 null. + """ + settlementBaseAmount: Int + """ + 확정된 수수료(원). 기준액 × 수수료율, 원 미만 버림. 확정 전이면 null. + """ + commissionAmount: Int + """ + 정산 확정 시각. 확정 전이면 null. + """ + settlementFinalizedAt: DateTime + """ + 이 주문이 묶인 주간 정산(adminSettlement). 아직 묶이지 않았으면 null. + """ + settlementId: ID +} + +""" +관리자 강제 취소 선택지. 화면은 이 값으로 다이얼로그를 그리고 규칙을 복제하지 않는다. +""" +type AdminOrderCancelOptions { + """ + 지금 취소할 수 있는지. + """ + cancelable: Boolean! + """ + 고를 수 있는 취소 사유. 취소할 수 없으면 빈 배열. + """ + reasons: [OrderCancelReasonType!]! + """ + 환불 규칙. BY_FAULT면 사정을 고르게 하고, 구매자 사정이면 환불 금액(0~paidAmount)을 입력받는다. 취소할 수 없으면 null. + """ + refundRule: CancelRefundRuleType + """ + 확인된 결제액(원). 입금 전이거나 결제 도입 전 주문이면 0. + """ + paidAmount: Int! +} + +""" +매장의 진행 중 주문 요약. +""" +type AdminStoreInProgressOrderSummary { + storeId: ID! + """ + 진행 중 주문 전체 건수. + """ + totalCount: Int! + """ + 상태별 건수. 0건인 상태는 빠지고 흐름 순(입금 대기 → 제작 완료)으로 온다. + """ + byStatus: [AdminStoreInProgressStatusCount!]! +} + +""" +상태 1개의 주문 건수. +""" +type AdminStoreInProgressStatusCount { + """ + 주문 상태. + """ + status: OrderStatusType! + """ + 건수. + """ + count: Int! } """ @@ -2669,6 +2942,10 @@ input AdminOrderListInput { """ status: OrderStatusType """ + true면 진행 중 주문(입금 대기·접수·확정·제작 완료)만. 기본 false, null도 false(전체)로 본다. status와 함께 오면 AND다. + """ + inProgress: Boolean = false + """ 매장 ID 필터(품목 기준). 미지정 시 전체. """ storeId: ID @@ -2687,33 +2964,88 @@ input AdminOrderListInput { } """ -주문 강제 취소 입력. +주문 강제 취소 입력. 허용 범위는 adminOrder.cancelOptions를 따른다. """ input AdminCancelOrderInput { orderId: ID! """ - 취소 사유. 필수. 최대 494자('[관리자] ' 접두를 붙여 500자 이내로 이력에 남는다). 감사 로그에도 기록된다. + 취소 사유. 필수. cancelOptions.reasons 중 하나여야 한다. """ - note: String! + reason: OrderCancelReasonType! + """ + 취소 메모. 선택, 최대 500자. 상태 이력과 감사 로그에 남는다. + """ + note: String + """ + 취소 사정. cancelOptions.refundRule이 BY_FAULT면 필수이고, 그 밖에는 무시한다. + """ + fault: OrderCancelFaultType + """ + 돌려줄 금액(원, 0~cancelOptions.paidAmount). fault가 BUYER일 때 필수이고, 그 밖에는 무시한다. + """ + refundAmount: Int +} + +""" +주문 픽업 완료 입력. 확정·제작 완료 주문만 처리할 수 있다. +""" +input AdminCompleteOrderPickupInput { + orderId: ID! + """ + 처리 메모. 선택, 최대 500자. 상태 이력과 감사 로그에 남는다. + """ + note: String } # ---- src/features/order/order-checkout.graphql ---- extend type Mutation { - """주문 생성(구매자). 옵션·픽업 일시를 서버가 재검증하고 가격을 스냅샷한다. 로그인 필수.""" + """ + 주문 생성(구매자). 옵션·픽업 일시를 서버가 재검증하고 가격을 스냅샷한 뒤 입금 대기(PENDING_PAYMENT) 주문을 만든다. + 결과의 payment로 입금을 안내하고, 1시간 안에 입금이 확인되지 않으면 자동 취소된다. 판매자에게는 입금 확인 뒤에 보인다. + 입금 계좌가 설정되지 않았으면 PAYMENT_ACCOUNT_NOT_CONFIGURED(SERVICE_UNAVAILABLE), 입금 대기 주문이 이미 2건이면 + PENDING_PAYMENT_LIMIT_EXCEEDED(CONFLICT), 같은 계정의 다른 주문 요청이 처리 중이라 3초 안에 차례가 오지 않으면 + CONCURRENT_REQUEST(CONFLICT)다. 커스텀 상품이면 custom 입력을 검증해 주문 시점 스냅샷으로 저장하고 수량은 1이다 + (CreateOrderCustomInput 참고). 로그인 필수. + """ createOrder(input: CreateOrderInput!): CreateOrderOutput! + """ + 커스텀 이미지 업로드용 Presigned URL 발급(구매자). uploadUrl로 PUT한 뒤 publicUrl을 주문 생성의 커스텀 입력에 넣는다. + JPEG·PNG·WebP, 장당 1바이트 이상 10MB 이하(아니면 INVALID_CONTENT_TYPE·INVALID_CONTENT_LENGTH·FILE_TOO_LARGE). + 주문에 쓰이지 않은 파일은 발급 하루 뒤 지워진다. 구매자 계정만 쓸 수 있고(아니면 USER_ONLY), 정지·탈퇴 등으로 + 이용할 수 없는 계정이면 BUYER_ACCOUNT_NOT_ACTIVE다. 로그인 필수. + """ + createOrderCustomUploadUrl( + """이미지 용도. 주문 생성 때 이 용도의 자리에만 쓸 수 있다.""" + purpose: OrderCustomUploadPurpose! + """파일 MIME 타입(image/jpeg·image/png·image/webp).""" + contentType: String! + """파일 크기(바이트, 1 이상 10MB 이하).""" + contentLength: Int! + ): UploadUrl! +} + +"""구매자 커스텀 이미지 업로드 용도.""" +enum OrderCustomUploadPurpose { + """3D 렌더 이미지(윗면·옆면 앞·뒤·좌·우).""" + RENDER + """슬롯형 합성 이미지(바탕 + 문구, 구매자가 본 그대로).""" + COMPOSITE + """자유 편집 참고 사진.""" + REFERENCE } -"""주문 생성 입력. 커스텀 필드는 커스텀 스펙 확정 후 optional로 확장 예정.""" +"""주문 생성 입력.""" input CreateOrderInput { """ 클라이언트 생성 멱등 키(8~64자). 체크아웃 진입 시 새로 만들고 재시도에는 같은 키를 재사용한다. 같은 키의 재요청은 새 주문을 만들지 않고 기존 주문을 반환한다. + 같은 키로 다른 입력을 보내면 IDEMPOTENCY_KEY_INPUT_MISMATCH로 거절한다. """ idempotencyKey: String! productId: ID! """선택한 옵션 아이템 ID 목록. 그룹 규칙(필수/min/max)을 서버가 검증한다.""" optionItemIds: [ID!]! - """픽업 일시. 매장 정책(영업시간·휴무·capacity·리드타임·슬롯 정렬) 재검증.""" + """픽업 일시. 매장 정책(영업시간·휴무·capacity·리드타임과 상품 제작 시간 중 긴 쪽·슬롯 정렬) 재검증.""" pickupAt: DateTime! """주문 수량. 기본 1.""" quantity: Int = 1 @@ -2721,6 +3053,162 @@ input CreateOrderInput { buyerName: String """미입력 시 프로필 전화번호 사용. 둘 다 없으면 거절.""" buyerPhone: String + """ + 입금자명(1~20자). 생략하거나 공백만 보내면 주문자 이름을 쓴다. 입력값이든 주문자 이름이든 20자를 넘으면 + DEPOSITOR_NAME_INVALID로 거절한다(은행 입금자명과 대조하는 값이라 자르지 않는다). + """ + depositorName: String + """ + 화면에 보여 준 최종 결제 금액(원). 서버가 다시 계산한 금액과 다르면 ORDER_PRICE_CHANGED로 거절한다. + """ + expectedTotalPrice: Int! + """판매자에게 전할 요청 사항(최대 500자). 공백만 보내면 없음으로 저장한다.""" + requestNote: String + """ + 커스텀 입력. 상품의 커스텀 방식(ProductDetail.customMode)이 SLOT이면 slot, THREE_D면 threeD 하나만 보낸다. + 커스텀 상품인데 없으면 CUSTOM_INPUT_REQUIRED, 방식이 다르거나 커스텀 상품이 아닌데 보내면 CUSTOM_INPUT_MISMATCH, + 수량이 1이 아니면 CUSTOM_QUANTITY_FIXED, 판매자 설정이 끝나지 않은 상품이면 CUSTOM_PRODUCT_NOT_READY다. + 커스텀은 추가 금액이 없다(3D 모양·크기 등의 가격은 옵션 추가금으로만 들어온다). + """ + custom: CreateOrderCustomInput +} + +""" +주문 커스텀 입력. 이미지 URL은 모두 createOrderCustomUploadUrl로 올린 본인 파일의 publicUrl이어야 하고(용도가 맞아야 한다), +한 주문 안에서 같은 파일을 두 번 쓸 수 없다. 아니면 CUSTOM_UPLOAD_INVALID, 발급 뒤 오래돼 정리 중인 파일이면 +CUSTOM_UPLOAD_EXPIRED다. 다른 주문에 이미 쓴 파일도 CUSTOM_UPLOAD_INVALID다. +""" +input CreateOrderCustomInput { + """슬롯형(바탕 이미지 + 문구 자리) 입력. 슬롯형 상품에서만 보낸다.""" + slot: CreateOrderSlotCustomInput + """3D 입력. 3D 상품에서만 보낸다.""" + threeD: CreateOrderThreeDCustomInput +} + +""" +슬롯형 커스텀 입력. 좌표는 바탕 이미지 한 변을 10000으로 본 정수 비율이고 원점은 왼쪽 위다. +""" +input CreateOrderSlotCustomInput { + """ + 꾸미기를 시작할 때 본 ProductDetail.customTemplate.revision. 그 사이 판매자가 설정을 바꿨으면 + CUSTOM_TEMPLATE_CHANGED(CONFLICT)이고 다시 꾸며야 한다. + """ + templateRevision: Int! + """ + 문구 자리마다 1건(customTemplate.slots 전부, 중복 없이). 빠지거나 남는 자리가 있으면 CUSTOM_SLOT_TEXTS_MISMATCH다. + """ + texts: [CreateOrderSlotTextInput!]! + """구매자가 본 그대로의 합성 이미지 URL(바탕 + 문구, 용도 COMPOSITE). 대표 이미지로 저장된다.""" + compositeImageUrl: String! + """ + 자유 편집 요청(customTemplate.freeEditEnabled일 때만, 최대 5건). 규칙을 벗어나면 CUSTOM_FREE_EDIT_INVALID다. + """ + freeEdits: [CreateOrderFreeEditInput!] = [] +} + +"""문구 자리 1개의 입력.""" +input CreateOrderSlotTextInput { + tokenId: ID! + """ + 넣을 문구. 손대지 않았으면 기본 문구를 그대로 보낸다. 줄바꿈(CRLF는 LF로 바꾼다)·이모지를 쓸 수 있고 앞뒤 공백은 지운다. + 지운 뒤 비었거나 null이면 '문구 없음'이다(필수 자리면 CUSTOM_SLOT_TEXT_REQUIRED). 자리의 maxLength(코드 포인트)를 + 넘으면 CUSTOM_SLOT_TEXT_TOO_LONG이다. + """ + valueText: String +} + +"""자유 편집 요청 1건. 바탕 이미지 위 영역과 설명, 참고 사진이다.""" +input CreateOrderFreeEditInput { + """영역 왼쪽 위 x(0~10000).""" + posX: Int! + """영역 왼쪽 위 y(0~10000).""" + posY: Int! + """영역 너비(1 이상, posX + width ≤ 10000).""" + width: Int! + """영역 높이(1 이상, posY + height ≤ 10000).""" + height: Int! + """요청 설명(앞뒤 공백을 지운 뒤 1~2000자, 줄바꿈 허용).""" + descriptionText: String! + """참고 사진 URL(용도 REFERENCE, 최대 3장).""" + referenceImageUrls: [String!] = [] +} + +"""3D 커스텀 입력.""" +input CreateOrderThreeDCustomInput { + """ + 3D 디자인(JSON v1). 모양·크기·디자인·맛은 고른 옵션의 threeDKey와 같아야 한다(아니면 CUSTOM_3D_OPTIONS_CHANGED). + 카탈로그·한도 검증은 customThreeDCatalog를 따른다. + """ + design: ThreeDDesignInput! + """ + 렌더 이미지(용도 RENDER). THREE_D_TOP·FRONT·BACK·LEFT·RIGHT 정확히 1장씩이고, 아니면 CUSTOM_RENDER_IMAGES_INVALID다. + 윗면이 대표 이미지로 저장된다. + """ + renderImages: [CreateOrderRenderImageInput!]! +} + +"""3D 렌더 이미지 1장.""" +input CreateOrderRenderImageInput { + """렌더 자세.""" + kind: CustomImageKindType! + """이미지 URL.""" + imageUrl: String! +} + +""" +3D 디자인 입력(JSON v1). 저장 형태는 ThreeDDesign이고 같은 좌표계·규칙을 쓴다. 배열 순서가 그리는 순서다. +""" +input ThreeDDesignInput { + """디자인 JSON 버전. 지금은 1만 받는다(아니면 CUSTOM_3D_SCHEMA_UNSUPPORTED).""" + schemaVersion: Int! + """모양·크기·디자인·맛·시트 색.""" + basic: ThreeDDesignBasicInput! + """윗면 항목(글자·꾸미기 각 10개까지).""" + top: [ThreeDDesignItemInput!]! + """옆면 항목(글자·꾸미기 각 10개까지).""" + side: [ThreeDDesignItemInput!]! +} + +"""3D 디자인의 케이크 기본값.""" +input ThreeDDesignBasicInput { + """모양 선택지 value(고른 모양 옵션의 값).""" + shape: String! + """크기 선택지 value(고른 크기 옵션의 값).""" + size: String! + """디자인 선택지 value. 디자인 옵션을 고르지 않았으면 null(장식 없는 시트).""" + design: String + """맛 선택지 value. 맛 옵션을 고르지 않았으면 null.""" + flavor: String + """시트 색 key(카탈로그 sheetColors).""" + sheetColor: String! +} + +"""3D 디자인 항목(글자 또는 꾸미기) 1개.""" +input ThreeDDesignItemInput { + """항목 종류.""" + kind: ThreeDItemKindType! + """가로 위치(0~1, ThreeDDesign.top·side 좌표계).""" + x: Float! + """세로 위치(0~1, ThreeDDesign.top·side 좌표계).""" + y: Float! + """크기(cqw). 글자 4~30, 꾸미기 8~50.""" + size: Float! + """효과.""" + effect: ThreeDDesignEffectInput! + """글자 내용(TEXT만, 1~30 코드 포인트, 줄바꿈·이모지 허용). DECO는 null.""" + text: String + """글자색(TEXT만, #RRGGBB). DECO는 null.""" + color: String + """꾸미기 key(DECO만, 카탈로그 decos). TEXT는 null.""" + decoId: String +} + +"""3D 디자인 항목에 건 효과.""" +input ThreeDDesignEffectInput { + """효과 key(카탈로그 effects).""" + type: String! + """효과 강도(0~100 정수).""" + intensity: Int! } """주문 생성 결과 요약. 상세는 myOrder로 재조회.""" @@ -2729,98 +3217,404 @@ type CreateOrderOutput { """주문번호. 화면·문의에 쓰는 식별자.""" orderNumber: String! """ - 주문 상태. 새로 생성된 경우 SUBMITTED다. 같은 idempotencyKey로 재시도하면 기존 - 주문을 그대로 돌려주므로 그 사이 진행된 상태(CONFIRMED·MADE·PICKED_UP 등)일 수 있다. + 주문 상태. 새로 생성된 경우 PENDING_PAYMENT다. 같은 idempotencyKey로 재시도하면 기존 + 주문을 그대로 돌려주므로 그 사이 진행된 상태(SUBMITTED·CONFIRMED·CANCELED 등)일 수 있다. """ status: OrderStatusType! """확정된 픽업 일시. 서버가 매장 정책으로 재검증한 값이다.""" pickupAt: DateTime! """서버가 스냅샷한 최종 결제 금액(원). 클라이언트 계산값이 아니다.""" totalPrice: Int! + """입금 안내(계좌·금액·입금자명·기한). 결제 도입 전 주문을 replay한 경우만 null.""" + payment: OrderPayment } -# ---- src/features/order/order-my.graphql ---- +# ---- src/features/order/order-deposit-admin.graphql ---- extend type Query { """ - 내 주문 목록 조회. 로그인 필수. 본인 데이터만 대상이 된다. + 입금 확인을 기다리는 주문(입금 대기 + 결제 대기) 목록. claimedOnly면 '입금했어요'를 누른 시각, 아니면 주문 생성 순으로 + 오래된 것부터 온다. 기한이 지났지만 아직 자동 취소되지 않은 주문도 포함한다. 관리자 로그인 필수. ADMIN 계정이 아니면 FORBIDDEN. """ - myOrders(input: MyOrdersInput): MyOrderConnection! + adminPendingPayments( + input: AdminPendingPaymentListInput + ): AdminPendingPaymentConnection! """ - 내 주문 상세 조회. 로그인 필수. 본인 데이터만 대상이 된다. + 처리 대기 건수(배지용). 관리자 로그인 필수. ADMIN 계정이 아니면 FORBIDDEN. """ - myOrder(orderId: ID!): MyOrderDetail! + adminTaskCounts: AdminTaskCounts! } -""" -내 주문 조회 입력 -""" -input MyOrdersInput { - """ - 상태 필터 (복수 선택 가능). 미지정 시 전체 - """ - statuses: [OrderStatusType!] - """ - 건너뛸 개수. 기본 0. - """ - offset: Int = 0 +extend type Mutation { """ - 한 번에 가져올 개수. 기본 20, 1~50만 허용하며 벗어나면 BAD_USER_INPUT. + 은행 앱에서 확인한 입금으로 주문을 접수(SUBMITTED)로 넘긴다. 이때부터 판매자에게 주문이 보이고 '새 주문' 푸시가 가며, + 판매자 확정 마감은 min(지금 + 24시간, 픽업 일시)이다. 구매자에게 ORDER_PAYMENT_CONFIRMED 알림이 간다. + 입금 대기가 아니면(이미 확인·취소) PAYMENT_NOT_PENDING(CONFLICT), 픽업 일시가 지났으면 PAYMENT_PICKUP_PASSED(CONFLICT), + 입금액이 1 미만이면 DEPOSIT_AMOUNT_INVALID, 결제 금액과 다르면 DEPOSIT_AMOUNT_MISMATCH(BAD_USER_INPUT)다. + 거절된 입금은 미입금 취소·반환 대상 연결로 처리한다. 메모가 500자를 넘으면 TEXT_TOO_LONG. 없는 주문이면 NOT_FOUND. + 감사 로그에 입금액이 남는다. 관리자 로그인 필수. ADMIN 계정이 아니면 FORBIDDEN. """ - limit: Int = 20 + adminConfirmPayment(input: AdminConfirmPaymentInput!): AdminOrderSummary! } """ -주문 목록 응답 +입금 확인 대기 목록 조회 조건. 모든 필터는 AND로 결합된다. """ -type MyOrderConnection { +input AdminPendingPaymentListInput { """ - 주문 카드. 최신 주문이 먼저 온다. + 한 번에 가져올 개수. 기본 20, 1~100만 허용하며 벗어나면 BAD_USER_INPUT. """ - items: [MyOrderSummary!]! + limit: Int = 20 """ - 전체 주문 수. 상태 필터를 적용한 뒤의 총계이며 offset·limit과 무관하다. + 이전 응답의 nextCursor. 첫 페이지는 생략한다. claimedOnly를 바꾸면 커서를 버리고 첫 페이지부터 다시 조회한다. """ - totalCount: Int! + cursor: String """ - 다음 페이지 존재 여부. + true면 구매자가 '입금했어요'를 누른 주문만. 기본 false, null도 false(전체)로 본다. """ - hasMore: Boolean! + claimedOnly: Boolean = false + """ + 결제 금액(원) 일치 필터. 은행 앱에서 본 입금액으로 주문을 찾는다. null이면 전체. + """ + amount: Int + """ + 입금자명 부분일치 필터(최대 50자). 공백만 보내거나 null이면 전체. + """ + depositorName: String } """ -유저 주문 목록 카드 +입금 확인 대기 주문 1건. """ -type MyOrderSummary { +type AdminPendingPayment { orderId: ID! """ - 주문번호. 화면·문의에 쓰는 식별자. + 주문번호. """ orderNumber: String! """ - 현재 주문 상태. + 매장명(주문 시점 스냅샷). 품목이 없으면 null. """ - status: OrderStatusType! + storeName: String """ - 주문 생성 시각. + 상품명(주문 시점 스냅샷). 품목이 없으면 null. """ - createdAt: DateTime! + productName: String """ - 픽업 예정 일시. + 입금할 금액(원). """ - pickupAt: DateTime! + amount: Int! """ - 대표 상품명 (첫 OrderItem 기준) + 입금자명. """ - representativeProductName: String! + depositorName: String! """ - 대표 상품 이미지 URL + 주문자 이름. """ - representativeProductImageUrl: String + buyerName: String! """ - 주문에 포함된 추가 상품 종류 수 (첫 아이템 제외) + 주문자 연락처. + """ + buyerPhone: String! + createdAt: DateTime! + """ + 입금 기한. + """ + expiresAt: DateTime! + """ + 구매자가 '입금했어요'를 누른 시각. 누르지 않았으면 null. + """ + buyerClaimedAt: DateTime + """ + 픽업 예정 일시. 지난 주문은 입금 확인할 수 없다. + """ + pickupAt: DateTime! +} + +""" +입금 확인 대기 목록 페이지. +""" +type AdminPendingPaymentConnection { + """ + 입금 확인 대기 주문. 오래된 것부터 온다. + """ + items: [AdminPendingPayment!]! + """ + 조건에 맞는 전체 건수(현재 페이지와 무관). 커서 필터는 제외하고 센다. + """ + totalCount: Int! + """ + 다음 페이지 존재 여부. + """ + hasMore: Boolean! + """ + 다음 페이지 커서. null이면 마지막 페이지다. + """ + nextCursor: String +} + +""" +처리 대기 건수. 진실은 각 목록이고 이 값은 배지용이다. +""" +type AdminTaskCounts { + """ + '입금했어요'를 눌렀고 아직 확인하지 않은 주문 수(adminPendingPayments claimedOnly=true의 totalCount). + """ + claimedPayments: Int! + """ + 입금 확인을 기다리는 전체 주문 수(adminPendingPayments의 totalCount, '입금했어요' 포함). + """ + pendingPayments: Int! + """ + 구매자의 환불 계좌 입력을 기다리는 환불 수(adminRefunds status=AWAITING_ACCOUNT의 totalCount). + """ + refundsAwaitingAccount: Int! + """ + 계좌가 들어와 송금을 기다리는 환불 수(adminRefunds status=AWAITING_TRANSFER의 totalCount). + """ + refundsAwaitingTransfer: Int! + """ + 송금을 기다리는 주간 정산 수(adminSettlements status=PENDING의 totalCount). + """ + pendingSettlements: Int! +} + +""" +입금 확인 입력. +""" +input AdminConfirmPaymentInput { + orderId: ID! + """ + 은행 앱에서 본 입금액(원, 0 이상 정수). 결제 금액과 같아야 확인된다(0원 주문은 0). + """ + depositedAmount: Int! + """ + 처리 메모(선택, 500자 이하). 결제 기록에 남는다. + """ + note: String +} + +""" +주문 결제(관리자 시점). 처리자 표시가 더해진다. +""" +type AdminOrderPayment { + """ + 결제 수단. + """ + method: PaymentMethodType! + """ + 결제 상태. + """ + status: PaymentStatusType! + """ + 결제 금액(원). + """ + amount: Int! + """ + 입금자명. + """ + depositorName: String! + """ + 안내한 케이퀵 계좌의 은행(주문 시점 스냅샷). + """ + depositBank: Bank! + """ + 안내한 케이퀵 계좌번호(주문 시점 스냅샷). + """ + depositAccountNumber: String! + """ + 안내한 케이퀵 계좌 예금주(주문 시점 스냅샷). + """ + depositAccountHolder: String! + """ + 입금 기한. + """ + expiresAt: DateTime! + """ + 구매자가 '입금했어요'를 누른 시각. 누르지 않았으면 null. + """ + buyerClaimedAt: DateTime + """ + 입금이 확인된 시각. 확인 전이면 null. + """ + confirmedAt: DateTime + """ + 입금 확인 경로. 확인 전이면 null. + """ + confirmSource: PaymentConfirmSourceType + """ + 입금을 확인한 관리자 표시 이름(확인 시점 스냅샷). 확인 전이거나 이름이 없으면 null. + """ + confirmedByLabel: String + """ + 입금 확인 메모. 없으면 null. + """ + confirmNote: String +} + +# ---- src/features/order/order-my.graphql ---- +extend type Query { + """ + 내 주문 목록 조회. 로그인 필수. 본인 데이터만 대상이 된다. + """ + myOrders(input: MyOrdersInput): MyOrderConnection! + """ + 내 주문 상세 조회. 로그인 필수. 본인 데이터만 대상이 된다. + """ + myOrder(orderId: ID!): MyOrderDetail! +} + +extend type Mutation { + """ + '입금했어요'. 입금 기한 전에 누르면 미입금 자동 취소에서 빠지고 관리자에게 확인 요청이 간다(입금이 없으면 관리자가 취소한다). + 이미 눌렀으면 아무것도 바꾸지 않고 그대로 돌려준다. 입금 대기가 아니면(확인·취소됨) PAYMENT_NOT_PENDING(CONFLICT), + 기한이 지났으면 PAYMENT_DEADLINE_PASSED(BAD_USER_INPUT). 로그인 필수. 본인 주문이 아니면 NOT_FOUND. + """ + markMyOrderDepositSent(orderId: ID!): MyOrderDetail! + """ + 내 주문을 취소한다. 판매자 확정 전(입금 대기·접수)까지만 되고 사유는 구매자 요청으로 기록된다. + 입금 대기는 환불 없이, 접수는 결제액 전액 환불로 취소되고 환불이 생기면 환불 계좌 입력 요청 알림이 간다. + refundAccount를 함께 보내면 환불이 바로 송금 대기가 되고 계좌 요청 알림은 가지 않는다(환불이 없으면 계좌는 버린다). + '입금했어요'를 누른 주문도 취소할 수 있다. 그 밖의 상태면 ORDER_NOT_CANCELLABLE(BAD_USER_INPUT). + 계좌 형식 오류는 submitMyRefundAccount와 같은 코드다. 로그인 필수. 본인 주문이 아니면 NOT_FOUND. + """ + cancelMyOrder(input: CancelMyOrderInput!): MyOrderDetail! + """ + 돌려받을 환불 계좌를 입력한다(MyOrderDetail.refunds의 id). 송금 완료 전이면 다시 보내 덮어쓸 수 있고, 입력하면 송금 대기가 된다. + 계좌번호는 암호화해 저장하고 응답에는 끝 4자리만 나간다. 은행 코드가 paymentBanks에 없으면 INVALID_BANK_CODE, + 계좌번호가 하이픈을 뺀 숫자 8~20자리가 아니면 INVALID_ACCOUNT_NUMBER, 예금주가 비었거나 50자를 넘으면 + TEXT_REQUIRED·TEXT_TOO_LONG(모두 BAD_USER_INPUT), 송금이 끝났으면 REFUND_ALREADY_COMPLETED(CONFLICT). + 로그인 필수. 본인 환불이 아니면 REFUND_NOT_FOUND(NOT_FOUND). + """ + submitMyRefundAccount(input: SubmitMyRefundAccountInput!): MyOrderDetail! +} + +""" +내 주문 취소 입력. +""" +input CancelMyOrderInput { + orderId: ID! + """ + 취소 메모. 선택, 최대 500자. 상태 이력에 남고 판매자도 본다. + """ + note: String + """ + 환불받을 계좌. 선택. 접수 주문처럼 환불이 생기는 취소에서 계좌 입력을 한 번에 끝낸다. + """ + refundAccount: RefundAccountInput +} + +""" +환불받을 계좌. +""" +input RefundAccountInput { + """ + 은행 코드(paymentBanks의 code). + """ + bankCode: String! + """ + 예금주(1~50자). + """ + accountHolder: String! + """ + 계좌번호. 하이픈을 빼고 숫자 8~20자리여야 하며 숫자만 저장한다. + """ + accountNumber: String! +} + +""" +환불 계좌 입력. +""" +input SubmitMyRefundAccountInput { + refundId: ID! + """ + 은행 코드(paymentBanks의 code). + """ + bankCode: String! + """ + 예금주(1~50자). + """ + accountHolder: String! + """ + 계좌번호. 하이픈을 빼고 숫자 8~20자리여야 하며 숫자만 저장한다. + """ + accountNumber: String! +} + +""" +내 주문 조회 입력 +""" +input MyOrdersInput { + """ + 상태 필터 (복수 선택 가능). 미지정 시 전체 + """ + statuses: [OrderStatusType!] + """ + 건너뛸 개수. 기본 0. + """ + offset: Int = 0 + """ + 한 번에 가져올 개수. 기본 20, 1~50만 허용하며 벗어나면 BAD_USER_INPUT. + """ + limit: Int = 20 +} + +""" +주문 목록 응답 +""" +type MyOrderConnection { + """ + 주문 카드. 최신 주문이 먼저 온다. + """ + items: [MyOrderSummary!]! + """ + 전체 주문 수. 상태 필터를 적용한 뒤의 총계이며 offset·limit과 무관하다. + """ + totalCount: Int! + """ + 다음 페이지 존재 여부. + """ + hasMore: Boolean! +} + +""" +유저 주문 목록 카드 +""" +type MyOrderSummary { + orderId: ID! + """ + 주문번호. 화면·문의에 쓰는 식별자. + """ + orderNumber: String! + """ + 현재 주문 상태. + """ + status: OrderStatusType! + """ + 주문 생성 시각. + """ + createdAt: DateTime! + """ + 픽업 예정 일시. + """ + pickupAt: DateTime! + """ + 대표 상품명 (첫 OrderItem 기준) + """ + representativeProductName: String! + """ + 대표 상품 이미지 URL + """ + representativeProductImageUrl: String + """ + 주문에 포함된 추가 상품 종류 수 (첫 아이템 제외) """ additionalItemCount: Int! """ + 주문 할인율(0~100, 반올림) = 할인 금액 ÷ 할인 전 합계. 할인이 없으면 0. + 옵션 추가금은 할인 대상이 아니라서, 옵션이 붙은 주문은 상품 카드의 할인율보다 낮을 수 있다. + """ + discountRate: Int! + """ 총 가격 """ totalPrice: Int! @@ -2829,9 +3623,17 @@ type MyOrderSummary { """ storeName: String! """ + 매장 위치 표기(예: 인천 청라동). 주문 시점 스냅샷이며, 그때 매장 주소·지역이 없었으면 null. + """ + regionLabel: String + """ 주문 내 OrderItem 중 리뷰 작성 가능한 것이 1건이라도 있는지 (PICKED_UP + 활성 리뷰 미존재) """ hasReviewableItem: Boolean! + """ + 입금 기한. 입금을 기다리는 주문(결제 대기)만 값이 있고 그 밖은 null. + """ + paymentExpiresAt: DateTime } """ @@ -2864,6 +3666,14 @@ type MyOrderDetail { 주문자 연락처. """ buyerPhone: String! + """ + 구매자가 남긴 요청 사항. 없으면 null. + """ + requestNote: String + """ + 결제(입금 안내·진행 상태). 결제 도입 전 주문이면 null. + """ + payment: OrderPayment """ 할인 전 품목 합계(원). @@ -2898,6 +3708,23 @@ type MyOrderDetail { CANCELED 도달 시각. 취소되지 않았으면 null. """ canceledAt: DateTime + """ + 취소 정보(주체·사유·환불액·환불 진행). 취소되지 않은 주문이면 null. + """ + cancellation: OrderCancellation + """ + 지금 cancelMyOrder로 취소할 수 있는지. 입금 대기·접수 상태일 때 true. + """ + canCancel: Boolean! + """ + 이 주문에서 돌려받을 돈(취소 환불·입금 반환). 오래된 순, 없으면 빈 배열. + status가 AWAITING_ACCOUNT면 submitMyRefundAccount로 계좌를 입력받는다. + """ + refunds: [OrderRefund!]! + """ + 판매자가 바꾼 픽업 일시 이력. 오래된 순, 없으면 빈 배열. pickupAt은 마지막 변경 뒤 값이다. + """ + pickupChanges: [OrderPickupChange!]! """ 상태 변경 이력. 오래된 순이다(판매자 주문 상세는 최신순 — 방향이 반대다). @@ -2983,96 +3810,1267 @@ type MyOrderStoreInfo { websiteUrl: String } -# ---- src/features/order/order-seller.graphql ---- +# ---- src/features/order/order-payment-admin.graphql ---- extend type Query { """ - 내 매장 주문 목록을 조회한다. 판매자 로그인 필수. SELLER 계정이 아니면 FORBIDDEN, 매장을 보유하지 않으면 NOT_FOUND. + 플랫폼 결제 설정(판매 수수료율·케이퀵 입금 계좌)을 조회한다. 설정한 적이 없으면 수수료 0, 입금 계좌 없음이다. + 관리자 로그인 필수. ADMIN 계정이 아니면 FORBIDDEN. """ - sellerOrderList(input: SellerOrderListInput): SellerOrderConnection! + adminPaymentSetting: AdminPaymentSetting! """ - 내 매장 주문 상세를 조회한다. 판매자 로그인 필수. SELLER 계정이 아니면 FORBIDDEN, 매장을 보유하지 않으면 NOT_FOUND. + 매장 정산 계좌를 계좌번호 원문과 함께 조회한다. 등록 전이면 null, 없는 매장이면 NOT_FOUND. + 관리자 로그인 필수. ADMIN 계정이 아니면 FORBIDDEN. """ - sellerOrder(orderId: ID!): SellerOrderDetail! + adminStoreSettlementAccount(storeId: ID!): AdminStoreSettlementAccount } extend type Mutation { """ - 주문 상태를 변경한다. 판매자 로그인 필수. SELLER 계정이 아니면 FORBIDDEN, 매장을 보유하지 않으면 NOT_FOUND. + 플랫폼 결제 설정을 바꾼다. 보낸 필드만 바꾸고 생략·null인 필드는 그대로 둔다. 수수료율은 바꾼 뒤 생성되는 주문부터 적용된다. + 수수료율이 0~10000bp 밖이면 INVALID_COMMISSION_RATE, 은행 코드가 paymentBanks에 없으면 INVALID_BANK_CODE, + 계좌번호가 하이픈을 뺀 숫자 8~20자리가 아니면 INVALID_ACCOUNT_NUMBER, 예금주가 비었거나 50자를 넘으면 TEXT_REQUIRED·TEXT_TOO_LONG, + 사유가 비면 TEXT_REQUIRED, 500자를 넘으면 VALIDATION_FAILED(모두 BAD_USER_INPUT). 감사 로그(PAYMENT_SETTING)를 남긴다. + 관리자 로그인 필수. ADMIN 계정이 아니면 FORBIDDEN. """ - sellerUpdateOrderStatus( - input: SellerUpdateOrderStatusInput! - ): SellerOrderSummary! + adminUpdatePaymentSetting( + input: AdminUpdatePaymentSettingInput! + ): AdminPaymentSetting! + """ + 매장 정산 계좌를 등록하거나 바꾼다(관리자 대리 수정). 계좌번호는 암호화해 저장하고, 감사 로그(SETTLEMENT_ACCOUNT)에는 + 끝 4자리만 남는다. 이 기록은 판매자 감사 로그에도 보인다. 없는 매장이면 NOT_FOUND, 은행·계좌번호·예금주·사유 오류는 + adminUpdatePaymentSetting과 같은 코드(BAD_USER_INPUT). 관리자 로그인 필수. ADMIN 계정이 아니면 FORBIDDEN. + """ + adminUpsertStoreSettlementAccount( + input: AdminUpsertStoreSettlementAccountInput! + ): AdminStoreSettlementAccount! } """ -주문 목록 카드. 상세는 sellerOrder로 재조회한다. +플랫폼 결제 설정. 플랫폼 전체에 하나뿐이다. """ -type SellerOrderSummary { - id: ID! +type AdminPaymentSetting { """ - 주문번호. 구매자에게 노출되는 식별자이며 검색(search) 대상이다. + 판매 수수료율(bp, 1bp = 0.01%). 0~10000. 주문 생성 시점의 값이 주문에 저장된다. """ - orderNumber: String! + commissionRateBps: Int! """ - 현재 주문 상태. + 구매자가 입금할 케이퀵 계좌의 은행. 설정 전이면 null. """ - status: OrderStatusType! + depositBank: Bank """ - 픽업 예정 일시. + 케이퀵 입금 계좌번호(숫자만). 설정 전이면 null. """ - pickupAt: DateTime! + depositAccountNumber: String """ - 주문자 이름. 구매자가 주문 시 입력했거나 프로필 닉네임에서 온 값. + 케이퀵 입금 계좌 예금주. 설정 전이면 null. """ - buyerName: String! + depositAccountHolder: String """ - 주문자 연락처. + 마지막 변경 시각. 설정한 적이 없으면 null. """ - buyerPhone: String! + updatedAt: DateTime +} + +""" +매장 정산 계좌(관리자 시점). 계좌번호 원문이 들어 있으니 화면 밖(로그·분석 이벤트)에 남기지 않는다. +""" +type AdminStoreSettlementAccount { + storeId: ID! """ - 할인 반영 후 최종 결제 금액(원). + 은행. """ - totalPrice: Int! + bank: Bank! """ - 주문 생성 시각. 목록 정렬 기준이다. + 예금주. """ + accountHolder: String! + """ + 계좌번호 원문(숫자만). 정산 송금에 쓴다. + """ + accountNumber: String! + """ + 끝 4자리만 남긴 계좌번호(예: ****1234). 목록 표시용. + """ + accountNumberMasked: String! + """ + 마지막으로 바꾼 주체. SELLER는 판매자 본인, ADMIN은 관리자 대리 수정이다. + """ + updatedByRole: OrderActorType! + """ + 마지막 변경 시각. + """ + updatedAt: DateTime! +} + +""" +결제 설정 변경 입력. 보낸 필드만 바꾼다. +""" +input AdminUpdatePaymentSettingInput { + """ + 판매 수수료율(bp). 0~10000 정수. 생략·null이면 그대로 둔다. + """ + commissionRateBps: Int + """ + 케이퀵 입금 계좌 은행 코드(paymentBanks의 code). 생략·null이면 그대로 둔다. + """ + depositBankCode: String + """ + 케이퀵 입금 계좌번호. 하이픈을 빼고 숫자 8~20자리여야 하며 숫자만 저장한다. 생략·null이면 그대로 둔다. + """ + depositAccountNumber: String + """ + 케이퀵 입금 계좌 예금주(1~50자). 생략·null이면 그대로 둔다. + """ + depositAccountHolder: String + """ + 변경 사유(필수, 500자 이하). 감사 로그에 남는다. + """ + reason: String! +} + +""" +매장 정산 계좌 등록·변경 입력(관리자 대리 수정). +""" +input AdminUpsertStoreSettlementAccountInput { + storeId: ID! + """ + 은행 코드(paymentBanks의 code). + """ + bankCode: String! + """ + 예금주(1~50자). + """ + accountHolder: String! + """ + 계좌번호. 하이픈을 빼고 숫자 8~20자리여야 하며 숫자만 저장한다. + """ + accountNumber: String! + """ + 변경 사유(필수, 500자 이하). 감사 로그에 남는다. + """ + reason: String! +} + +# ---- src/features/order/order-payment.graphql ---- +extend type Query { + """ + 계좌 입력 화면의 은행 목록(금융결제원 3자리 코드). 환불 계좌·정산 계좌·케이퀵 입금 계좌가 같은 목록을 쓰고, + 배열 순서가 표시 순서다. 로그인 없이 조회할 수 있다. + """ + paymentBanks: [Bank!]! +} + +""" +은행. +""" +type Bank { + """ + 금융결제원 3자리 은행 코드(예: 004). 계좌 입력 mutation의 bankCode로 그대로 보낸다. + """ + code: String! + """ + 은행 이름(예: KB국민은행). 목록에서 빠진 옛 코드면 코드를 그대로 준다. + """ + name: String! +} + +""" +결제 수단. 값은 늘어날 수 있으니 모르는 값을 받아도 화면이 죽지 않게 처리한다. +""" +enum PaymentMethodType { + """계좌이체(케이퀵 계좌로 입금).""" + BANK_TRANSFER + """토스 결제. 아직 쓰지 않는다.""" + TOSS +} + +""" +결제 상태. 값은 늘어날 수 있으니 모르는 값을 받아도 화면이 죽지 않게 처리한다. +""" +enum PaymentStatusType { + """입금 대기.""" + PENDING + """입금 확인됨. 주문이 나중에 취소돼도 이 값으로 남고 돌려줄 돈은 환불이 맡는다.""" + CONFIRMED + """입금 전에 주문이 취소됨.""" + CANCELED +} + +""" +입금을 확인한 경로. +""" +enum PaymentConfirmSourceType { + """입금 알림 자동 매칭. 아직 쓰지 않는다.""" + AUTO + """관리자가 은행 앱에서 확인.""" + ADMIN +} + +""" +주문 결제(계좌이체 입금 안내와 진행 상태). 구매자 주문 화면이 그대로 입금 안내에 쓴다. +""" +type OrderPayment { + """ + 결제 수단. + """ + method: PaymentMethodType! + """ + 결제 상태. + """ + status: PaymentStatusType! + """ + 입금할 금액(원). 주문 최종 결제 금액과 같다. + """ + amount: Int! + """ + 입금자명. 은행 입금자명이 이 값과 같아야 확인이 빠르다. + """ + depositorName: String! + """ + 입금할 케이퀵 계좌의 은행(주문 시점 스냅샷). + """ + depositBank: Bank! + """ + 입금할 케이퀵 계좌번호(숫자만, 주문 시점 스냅샷). + """ + depositAccountNumber: String! + """ + 입금할 케이퀵 계좌 예금주(주문 시점 스냅샷). + """ + depositAccountHolder: String! + """ + 입금 기한(주문 후 1시간). 이때까지 입금이 확인되지 않고 '입금했어요'도 누르지 않았으면 주문이 자동 취소된다. + """ + expiresAt: DateTime! + """ + 구매자가 '입금했어요'를 누른 시각. 누르지 않았으면 null. + """ + buyerClaimedAt: DateTime + """ + 입금이 확인된 시각. 확인 전이면 null. + """ + confirmedAt: DateTime + """ + 입금 확인 경로. 확인 전이면 null. + """ + confirmSource: PaymentConfirmSourceType +} + +# ---- src/features/order/order-refund-admin.graphql ---- +extend type Query { + """ + 환불(취소 환불·입금 반환) 목록. 처리 순서대로 오래된 환불부터 온다. 계좌번호는 끝 4자리만 나간다. + 관리자 로그인 필수. ADMIN 계정이 아니면 FORBIDDEN. + """ + adminRefunds(input: AdminRefundListInput): AdminRefundConnection! + """ + 환불 상세. 송금에 쓸 계좌번호 원문과 입금 반환이면 그 입금 기록이 함께 온다. 없으면 REFUND_NOT_FOUND(NOT_FOUND). + 관리자 로그인 필수. ADMIN 계정이 아니면 FORBIDDEN. + """ + adminRefund(refundId: ID!): AdminRefundDetail! + """ + 결제로 확인하지 않은 입금 기록(반환·종결) 목록. 최근 기록부터 온다. + 관리자 로그인 필수. ADMIN 계정이 아니면 FORBIDDEN. + """ + adminDepositRecords( + input: AdminDepositRecordListInput + ): AdminDepositRecordConnection! +} + +extend type Mutation { + """ + 환불 송금을 마쳤다고 기록한다. 계좌가 들어온(송금 대기) 환불만 되고, 계좌 입력 전이면 REFUND_NOT_READY(BAD_USER_INPUT), + 이미 끝났으면 REFUND_ALREADY_COMPLETED(CONFLICT), 없으면 REFUND_NOT_FOUND(NOT_FOUND). 메모가 500자를 넘으면 TEXT_TOO_LONG. + 구매자에게 REFUND_COMPLETED 알림이 가고 감사 로그(REFUND)를 남긴다. 관리자 로그인 필수. ADMIN 계정이 아니면 FORBIDDEN. + """ + adminCompleteRefund(input: AdminCompleteRefundInput!): AdminRefund! + """ + 은행 앱에서 본 입금을 주문의 반환 대상으로 연결한다. 입금 기록(RETURN)과 입금액 전액의 환불(계좌 입력 대기)이 생기고 + 구매자에게 환불 계좌 입력 요청 알림이 간다. 주문 상태·결제·정산은 바꾸지 않으며 주문 상태와 관계없이 연결할 수 있다 + (미입금 취소 뒤 늦은 입금, 취소 뒤 입금, 금액이 틀린 입금, 이중 입금). 입금액이 1 미만이면 DEPOSIT_AMOUNT_INVALID, + 입금자명이 비었거나 50자를 넘으면 TEXT_REQUIRED·TEXT_TOO_LONG, 메모가 500자를 넘으면 TEXT_TOO_LONG(모두 BAD_USER_INPUT), + 없는 주문이면 ORDER_NOT_FOUND(NOT_FOUND). 감사 로그(DEPOSIT_RECORD)를 남긴다. + 관리자 로그인 필수. ADMIN 계정이 아니면 FORBIDDEN. + """ + adminCreateDepositReturn( + input: AdminCreateDepositReturnInput! + ): AdminDepositRecord! + """ + 주인을 알 수 없는 입금을 메모와 함께 종결 기록(UNIDENTIFIED)으로 남긴다. 메모가 비면 DEPOSIT_NOTE_REQUIRED, + 입금액·입금자명·메모 길이 오류는 adminCreateDepositReturn과 같다(모두 BAD_USER_INPUT). 감사 로그(DEPOSIT_RECORD)를 남긴다. + 관리자 로그인 필수. ADMIN 계정이 아니면 FORBIDDEN. + """ + adminRecordUnidentifiedDeposit( + input: AdminRecordUnidentifiedDepositInput! + ): AdminDepositRecord! + """ + 종결 기록한 입금의 주인을 찾았을 때 그 기록을 주문의 반환 대상으로 바꾼다. 같은 입금을 새로 기록하지 않고 기록 종류가 + RETURN으로 바뀌며, 입금액 전액의 환불이 생겨 구매자에게 계좌 입력 요청 알림이 간다(주문 상태·결제·정산은 그대로). + 이미 반환으로 연결된 기록이면 DEPOSIT_RECORD_ALREADY_LINKED(CONFLICT), 없는 기록이면 DEPOSIT_RECORD_NOT_FOUND, + 없는 주문이면 ORDER_NOT_FOUND(모두 NOT_FOUND). 감사 로그(DEPOSIT_RECORD)를 남긴다. + 관리자 로그인 필수. ADMIN 계정이 아니면 FORBIDDEN. + """ + adminLinkUnidentifiedDeposit( + input: AdminLinkUnidentifiedDepositInput! + ): AdminDepositRecord! +} + +""" +입금 기록 종류. 값은 늘어날 수 있으니 모르는 값을 받아도 화면이 죽지 않게 처리한다. +""" +enum DepositRecordKindType { + """주문에 연결해 돌려주는 입금. 같은 금액의 입금 반환 환불이 함께 있다.""" + RETURN + """주인을 알 수 없어 메모로 종결한 입금.""" + UNIDENTIFIED +} + +""" +환불 목록 조회 조건. 모든 필터는 AND로 결합된다. +""" +input AdminRefundListInput { + """ + 한 번에 가져올 개수. 기본 20, 1~100만 허용하며 벗어나면 BAD_USER_INPUT. + """ + limit: Int = 20 + """ + 이전 응답의 nextCursor. 첫 페이지는 생략한다. + """ + cursor: String + """ + 진행 상태 필터. null이면 전체. + """ + status: RefundStatusType + """ + 종류 필터. null이면 전체. + """ + kind: RefundKindType +} + +""" +환불(관리자 시점). 계좌번호는 끝 4자리만 담는다. +""" +type AdminRefund { + id: ID! + """ + 환불 종류. + """ + kind: RefundKindType! + """ + 돌려줄 금액(원). + """ + amount: Int! + """ + 진행 상태. + """ + status: RefundStatusType! + """ + 환불받을 은행. 계좌 입력 전이면 null. + """ + bank: Bank + """ + 환불 계좌 예금주. 계좌 입력 전이면 null. + """ + accountHolder: String + """ + 환불 계좌번호 끝 4자리만 보이는 값(예: ****1234). 계좌 입력 전이면 null. + """ + accountNumberMasked: String + """ + 환불이 생긴 시각. + """ + requestedAt: DateTime! + """ + 구매자가 계좌를 입력한 시각(덮어쓰면 마지막 입력). 입력 전이면 null. + """ + accountSubmittedAt: DateTime + """ + 송금 완료 시각. 완료 전이면 null. + """ + completedAt: DateTime + orderId: ID! + """ + 주문번호. + """ + orderNumber: String! + """ + 주문자 이름. 계좌 입력을 기다릴 때 연락에 쓴다. + """ + buyerName: String! + """ + 주문자 연락처. + """ + buyerPhone: String! + """ + 매장명(주문 시점 스냅샷). 품목이 없으면 null. + """ + storeName: String + """ + 상품명(주문 시점 스냅샷). 품목이 없으면 null. + """ + productName: String + """ + 송금 완료를 기록한 관리자 표시 이름(처리 시점 스냅샷). 완료 전이거나 이름이 없으면 null. + """ + completedByLabel: String + """ + 송금 완료 메모. 없으면 null. + """ + completeNote: String +} + +""" +환불 상세. 계좌번호 원문이 들어 있으니 화면 밖(로그·분석 이벤트)에 남기지 않는다. +""" +type AdminRefundDetail { + """ + 환불. + """ + refund: AdminRefund! + """ + 환불 계좌번호 원문(숫자만). 송금에 쓴다. 계좌 입력 전이면 null. + """ + accountNumber: String + """ + 입금 반환이면 그 입금 기록, 취소 환불이면 null. + """ + depositRecord: AdminDepositRecord +} + +""" +환불 목록 페이지. +""" +type AdminRefundConnection { + """ + 환불. 오래된 것부터 온다. + """ + items: [AdminRefund!]! + """ + 조건에 맞는 전체 건수(현재 페이지와 무관). 커서 필터는 제외하고 센다. + """ + totalCount: Int! + """ + 다음 페이지 존재 여부. + """ + hasMore: Boolean! + """ + 다음 페이지 커서. null이면 마지막 페이지다. + """ + nextCursor: String +} + +""" +입금 기록 목록 조회 조건. +""" +input AdminDepositRecordListInput { + """ + 한 번에 가져올 개수. 기본 20, 1~100만 허용하며 벗어나면 BAD_USER_INPUT. + """ + limit: Int = 20 + """ + 이전 응답의 nextCursor. 첫 페이지는 생략한다. + """ + cursor: String + """ + 종류 필터. null이면 전체. + """ + kind: DepositRecordKindType +} + +""" +결제로 확인하지 않은 입금 기록 1건. +""" +type AdminDepositRecord { + id: ID! + """ + 기록 종류. + """ + kind: DepositRecordKindType! + """ + 연결한 주문 ID. 반환(RETURN)만 있고 종결이면 null. + """ + orderId: ID + """ + 연결한 주문번호. 반환(RETURN)만 있고 종결이면 null. + """ + orderNumber: String + """ + 입금액(원). + """ + amount: Int! + """ + 은행 앱에 보인 입금자명. + """ + depositorName: String! + """ + 은행 앱에 보인 입금 일시. 입력하지 않았으면 null. + """ + depositedAt: DateTime + """ + 처리 메모. 없으면 null(종결 기록은 항상 있다). + """ + note: String + """ + 기록한 관리자 표시 이름(기록 시점 스냅샷). 이름이 없으면 null. + """ + recordedByLabel: String + """ + 반환으로 생긴 환불 ID(adminRefund로 연다). 종결이면 null. + """ + refundId: ID + """ + 반환으로 생긴 환불의 진행 상태. 종결이면 null. + """ + refundStatus: RefundStatusType + createdAt: DateTime! +} + +""" +입금 기록 목록 페이지. +""" +type AdminDepositRecordConnection { + """ + 입금 기록. 최근 것부터 온다. + """ + items: [AdminDepositRecord!]! + """ + 조건에 맞는 전체 건수(현재 페이지와 무관). 커서 필터는 제외하고 센다. + """ + totalCount: Int! + """ + 다음 페이지 존재 여부. + """ + hasMore: Boolean! + """ + 다음 페이지 커서. null이면 마지막 페이지다. + """ + nextCursor: String +} + +""" +환불 송금 완료 입력. +""" +input AdminCompleteRefundInput { + refundId: ID! + """ + 처리 메모(선택, 500자 이하). 환불 기록에 남는다. + """ + note: String +} + +""" +입금 반환 연결 입력. +""" +input AdminCreateDepositReturnInput { + orderId: ID! + """ + 은행 앱에서 본 입금액(원, 1 이상). 이 금액 전액을 돌려준다. + """ + amount: Int! + """ + 은행 앱에 보인 입금자명(1~50자). + """ + depositorName: String! + """ + 은행 앱에 보인 입금 일시(선택). + """ + depositedAt: DateTime + """ + 처리 메모(선택, 500자 이하). + """ + note: String +} + +""" +주인 모를 입금 종결 기록 입력. +""" +input AdminRecordUnidentifiedDepositInput { + """ + 은행 앱에서 본 입금액(원, 1 이상). + """ + amount: Int! + """ + 은행 앱에 보인 입금자명(1~50자). + """ + depositorName: String! + """ + 은행 앱에 보인 입금 일시(선택). + """ + depositedAt: DateTime + """ + 종결 사유 메모(필수, 500자 이하). + """ + note: String! +} + +""" +종결 기록을 반환 대상으로 바꾸는 입력. +""" +input AdminLinkUnidentifiedDepositInput { + depositRecordId: ID! + orderId: ID! +} + +# ---- src/features/order/order-seller-pickup.graphql ---- +extend type Query { + """ + 픽업 일시 변경 시트의 월 달력. 영업일·특별휴무·예약 가능 기간·일일 제작 수량을 보고, 리드타임·상품 제작 시간은 보지 않는다 + (지난 시각만 막는다). 이 주문이 지금 점유한 수량은 빼고 세며, 숨긴 매장도 계산한다. 접수·확정·제작 완료가 아니면 + PICKUP_RESCHEDULE_NOT_ALLOWED, yearMonth 형식이 어긋나면 BAD_USER_INPUT(INVALID_YEAR_MONTH). 입금 확인 전·다른 매장 주문은 NOT_FOUND. + 판매자 로그인 필수. SELLER 계정이 아니면 FORBIDDEN, 매장을 보유하지 않으면 NOT_FOUND. + """ + sellerOrderPickupCalendar( + orderId: ID! + """대상 연월. "YYYY-MM" 형식(KST 기준).""" + yearMonth: String! + ): PickupCalendar! + """ + 픽업 일시 변경 시트의 그날 슬롯. 규칙은 sellerOrderPickupCalendar와 같다. date 형식이 어긋나면 BAD_USER_INPUT(INVALID_DATE). + 판매자 로그인 필수. SELLER 계정이 아니면 FORBIDDEN, 매장을 보유하지 않으면 NOT_FOUND. + """ + sellerOrderPickupTimeSlots( + orderId: ID! + """대상 날짜. "YYYY-MM-DD" 형식(KST 기준).""" + date: String! + ): PickupTimeSlots! +} + +extend type Mutation { + """ + 주문 픽업 일시를 바꾼다(접수·확정·제작 완료만, 그 밖은 PICKUP_RESCHEDULE_NOT_ALLOWED). 지금과 같은 일시면 PICKUP_UNCHANGED, + 영업일·특별휴무·슬롯 시각·지난 시각·예약 가능 기간·일일 제작 수량(이 주문 수량은 빼고 센다)에 맞지 않으면 PICKUP_NOT_AVAILABLE + (모두 BAD_USER_INPUT). 리드타임·상품 제작 시간은 보지 않고, 숨긴 매장의 주문도 바꿀 수 있다. 접수 상태면 확정 마감을 + min(접수 + 24시간, 새 픽업 시각)으로 다시 잰다. 변경 이력(pickupChanges)이 남고 구매자에게 알림이 간다. 커스텀 내용은 바뀌지 않는다. + 입금 확인 전·다른 매장 주문은 NOT_FOUND. 판매자 로그인 필수. SELLER 계정이 아니면 FORBIDDEN, 매장을 보유하지 않으면 NOT_FOUND. + """ + sellerRescheduleOrderPickup( + input: SellerRescheduleOrderPickupInput! + ): SellerOrderSummary! +} + +""" +판매자 픽업 일시 변경 입력. +""" +input SellerRescheduleOrderPickupInput { + orderId: ID! + """ + 새 픽업 일시. sellerOrderPickupTimeSlots의 슬롯 시각이어야 한다(초 이하는 0). + """ + pickupAt: DateTime! + """ + 변경 메모. 선택, 최대 500자. 변경 이력에 남고 구매자도 본다. + """ + note: String +} + +# ---- src/features/order/order-seller.graphql ---- +extend type Query { + """ + 내 매장 주문 목록을 조회한다. 입금이 확인된(접수된) 주문만 보인다. 판매자 로그인 필수. SELLER 계정이 아니면 FORBIDDEN, 매장을 보유하지 않으면 NOT_FOUND. + """ + sellerOrderList(input: SellerOrderListInput): SellerOrderConnection! + """ + 내 매장 주문 상세를 조회한다. 입금 확인 전 주문은 없는 주문과 같이 NOT_FOUND다. 판매자 로그인 필수. SELLER 계정이 아니면 FORBIDDEN, 매장을 보유하지 않으면 NOT_FOUND. + """ + sellerOrder(orderId: ID!): SellerOrderDetail! +} + +extend type Mutation { + """ + 주문 상태를 변경한다. 접수 → 확정, 확정 → 제작 완료, 확정·제작 완료 → 픽업 완료·노쇼만 된다(그 밖은 + INVALID_ORDER_STATUS_TRANSITION, 같은 상태면 ORDER_STATUS_UNCHANGED). 노쇼는 픽업 시각부터 24시간(자동 픽업 완료 전) + 안에서만 되고 벗어나면 NO_SHOW_NOT_ALLOWED(BAD_USER_INPUT)다. 픽업 완료·노쇼는 정산 금액을 확정하고, 노쇼는 환불이 없다. + 취소(CANCELED)는 받지 않으므로 sellerCancelOrder를 쓴다(INVALID_ORDER_STATUS_TRANSITION). + 판매자 로그인 필수. SELLER 계정이 아니면 FORBIDDEN, 매장을 보유하지 않으면 NOT_FOUND. + """ + sellerUpdateOrderStatus( + input: SellerUpdateOrderStatusInput! + ): SellerOrderSummary! + """ + 주문을 거절·취소한다. 접수(SUBMITTED) 단계 거절은 결제액 전액 환불이고, 확정·제작 완료(CONFIRMED·MADE) 뒤 취소는 + fault(사정)가 필수다(판매자 사정 = 전액 환불, 구매자 사정 = refundAmount 환불, 남는 금액은 수수료를 뺀 뒤 정산에 포함). + 환불 송금은 케이퀵이 한다. 그 밖의 상태면 ORDER_NOT_CANCELLABLE, 판매자가 고를 수 없는 사유면 CANCEL_REASON_NOT_ALLOWED, + 사정이 없으면 CANCEL_FAULT_REQUIRED, 구매자 사정인데 금액이 없으면 REFUND_AMOUNT_REQUIRED, + 금액이 0~결제액 밖이면 REFUND_AMOUNT_OUT_OF_RANGE(모두 BAD_USER_INPUT). 입금 확인 전·다른 매장 주문은 NOT_FOUND. + 판매자 로그인 필수. SELLER 계정이 아니면 FORBIDDEN, 매장을 보유하지 않으면 NOT_FOUND. + """ + sellerCancelOrder(input: SellerCancelOrderInput!): SellerOrderSummary! +} + +""" +주문 목록 카드. 상세는 sellerOrder로 재조회한다. +""" +type SellerOrderSummary { + id: ID! + """ + 주문번호. 구매자에게 노출되는 식별자이며 검색(search) 대상이다. + """ + orderNumber: String! + """ + 현재 주문 상태. + """ + status: OrderStatusType! + """ + 픽업 예정 일시. + """ + pickupAt: DateTime! + """ + 주문자 이름. 구매자가 주문 시 입력했거나 프로필 닉네임에서 온 값. + """ + buyerName: String! + """ + 주문자 연락처. + """ + buyerPhone: String! + """ + 할인 반영 후 최종 결제 금액(원). + """ + totalPrice: Int! + """ + 주문 생성 시각. 목록 정렬 기준이다. + """ + createdAt: DateTime! + """ + 내 매장 첫 품목의 상품명(주문 시점 스냅샷). 이후 상품명이 바뀌어도 유지된다. 활성 품목이 없으면 null. + """ + firstItemName: String + """ + 내 매장 첫 품목의 상품 대표 이미지 URL(주문 시점 스냅샷). 주문 당시 이미지가 없었으면 null. + """ + firstItemImageUrl: String + """ + 커스텀 주문 여부(내 매장 첫 품목의 커스텀 방식이 NONE이 아니면 true). 목록 '커스텀' 배지용이다. + """ + hasCustom: Boolean! + """ + 내 매장 첫 품목의 커스텀 대표 이미지 URL(3D 윗면 렌더 또는 슬롯형 합성). 없으면 null. + """ + firstItemCustomImageUrl: String + """ + 확정 마감 시각. 이때까지 확정하지 않으면 자동 취소되고 결제액 전액이 환불된다. 접수(SUBMITTED) 상태가 아니거나 + 결제 도입 전 주문이면 null. + """ + confirmDeadlineAt: DateTime +} + +""" +주문 목록 페이지. 최신 주문이 먼저 온다. +""" +type SellerOrderConnection { + """ + 주문 카드. 최신 주문이 먼저 온다. + """ + items: [SellerOrderSummary!]! + """ + 조건에 맞는 전체 건수(현재 페이지와 무관). 커서 필터는 제외하고 센다. + """ + totalCount: Int! + """ + 다음 페이지 존재 여부. limit+1 조회로 판정하므로 추가 쿼리가 없다. + """ + hasMore: Boolean! + """ + 다음 페이지 커서. null이면 마지막 페이지다. 불투명 토큰이라 값의 형식에 의존하지 않는다. + """ + nextCursor: String +} + +""" +주문 목록 조회 조건. 모든 필터는 AND로 결합되고, 미지정 필터는 적용되지 않는다. +""" +input SellerOrderListInput { + """ + 한 번에 가져올 개수. 기본 20, 1~100만 허용하며 벗어나면 BAD_USER_INPUT. + """ + limit: Int = 20 + """ + 이전 응답의 nextCursor. 첫 페이지는 생략한다. + """ + cursor: String + """ + 주문 상태 필터. 미지정 시 전체 상태. + """ + status: OrderStatusType + """ + 구매자 계정 ID 필터. 채팅 상대의 주문만 볼 때 쓴다. 미지정 시 전체. + """ + buyerAccountId: ID + """ + 주문 생성 시각 하한(이상). + """ + fromCreatedAt: DateTime + """ + 주문 생성 시각 상한(이하). + """ + toCreatedAt: DateTime + """ + 픽업 일시 하한(이상). + """ + fromPickupAt: DateTime + """ + 픽업 일시 상한(이하). + """ + toPickupAt: DateTime + """ + 주문번호·주문자 이름·연락처 부분일치 검색. 셋 중 하나라도 맞으면 포함된다. + """ + search: String +} + +""" +주문 상세. items에는 내 매장 품목만 담긴다. +""" +type SellerOrderDetail { + id: ID! + """ + 주문번호. + """ + orderNumber: String! + """ + 주문한 구매자 계정 ID. + """ + accountId: ID! + """ + 현재 주문 상태. + """ + status: OrderStatusType! + """ + 픽업 예정 일시. + """ + pickupAt: DateTime! + """ + 주문자 이름. + """ + buyerName: String! + """ + 주문자 연락처. + """ + buyerPhone: String! + """ + 구매자가 남긴 요청 사항. 없으면 null. + """ + requestNote: String + """ + 결제 수단. 결제 도입 전 주문이면 null. 값은 늘어날 수 있으니 모르는 값은 '기타'로 보여 준다. + """ + paymentMethod: PaymentMethodType + """ + 할인 전 품목 합계(원). + """ + subtotalPrice: Int! + """ + 할인 금액(원). 할인이 없으면 0. + """ + discountPrice: Int! + """ + 최종 결제 금액(원) = subtotalPrice - discountPrice. + """ + totalPrice: Int! + """ + 각 상태에 도달한 시각. 아직 그 상태를 거치지 않았으면 null이다. + """ + submittedAt: DateTime + """ + CONFIRMED 도달 시각. 미도달 시 null. + """ + confirmedAt: DateTime + """ + MADE(제작 완료) 도달 시각. 미도달 시 null. + """ + madeAt: DateTime + """ + PICKED_UP 도달 시각. 미도달 시 null. + """ + pickedUpAt: DateTime + """ + CANCELED 도달 시각. 취소되지 않았으면 null. + """ + canceledAt: DateTime + createdAt: DateTime! + updatedAt: DateTime! + """ + 내 매장에 속한 주문 품목만 포함된다. 다른 매장 품목은 내려오지 않는다. + """ + items: [OrderItemDetail!]! + """ + 상태 변경 이력. 최신순. 입금 대기 이력은 빠지고, 접수 이력은 fromStatus가 null(최초)로 온다. + """ + statusHistories: [OrderStatusHistory!]! + """ + 취소 정보(주체·사유·사정·환불액·환불 진행). 취소되지 않은 주문이면 null. + """ + cancellation: OrderCancellation + """ + 확정 마감 시각. 이때까지 확정하지 않으면 자동 취소되고 결제액 전액이 환불된다. 접수(SUBMITTED) 상태가 아니거나 + 결제 도입 전 주문이면 null. + """ + confirmDeadlineAt: DateTime + """ + 자동 픽업 완료 예정 시각(픽업 시각 + 24시간). 확정·제작 완료 상태에서만 있고 그 밖은 null. + 매장이 숨김이면 자동으로 픽업 완료되지 않는다. + """ + autoPickupAt: DateTime + """ + 지금 노쇼로 처리할 수 있는지. 확정·제작 완료 상태이고 픽업 시각 ≤ 지금 < autoPickupAt일 때 true. + """ + canMarkNoShow: Boolean! + """ + 노쇼 처리 시각. 노쇼가 아니면 null. + """ + noShowAt: DateTime + """ + 픽업 일시 변경 이력. 오래된 순, 없으면 빈 배열. + """ + pickupChanges: [OrderPickupChange!]! + """ + 주문 생성 시점의 수수료율(bp, 1bp = 0.01%). 바뀐 설정은 그 뒤 주문부터 적용된다. + """ + commissionRateBps: Int! + """ + 정산 예정 금액(원). 정산 확정 뒤에는 실제 지급액(기준액 − 수수료), 확정 전에는 결제 금액에서 수수료(원 미만 버림)를 뺀 + 예상값이다. 입금이 확인되지 않았거나 결제 도입 전 주문이면 null, 확정 없이 취소된 주문(전액 환불)은 0. + """ + expectedPayoutAmount: Int + """ + 확정된 수수료 기준액(원). 픽업 완료·노쇼는 결제 금액, 구매자 사정 취소는 결제 금액 − 환불 금액. 확정 전이면 null. + """ + settlementBaseAmount: Int + """ + 확정된 수수료(원). 기준액 × 수수료율, 원 미만 버림. 확정 전이면 null. + """ + commissionAmount: Int +} + +""" +주문 상태 변경 입력. 전이 규칙은 OrderStatusType 설명을 따르며, 규칙에 어긋나면 +BAD_USER_INPUT으로 거절된다. +""" +input SellerUpdateOrderStatusInput { + orderId: ID! + """ + 변경할 상태. CONFIRMED·MADE·PICKED_UP·NO_SHOW 중 현재 상태에서 진입 가능한 값이어야 한다. + """ + toStatus: OrderStatusType! + """ + 변경 메모. 선택, 최대 500자. 상태 이력에 남는다. + """ + note: String +} + +""" +판매자 주문 거절·취소 입력. 허용 범위는 sellerCancelOrder 설명을 따른다. +""" +input SellerCancelOrderInput { + orderId: ID! + """ + 취소 사유. DESIGN_NOT_FEASIBLE·OUT_OF_MATERIALS·SCHEDULE_UNAVAILABLE·INAPPROPRIATE_REQUEST·BUYER_REQUEST·OTHER 중 하나. + """ + reason: OrderCancelReasonType! + """ + 취소 메모. 선택, 최대 500자. 상태 이력에 남고 구매자도 본다. + """ + note: String + """ + 취소 사정. 확정·제작 완료 주문이면 필수이고, 접수 단계 거절에서는 무시한다. + """ + fault: OrderCancelFaultType + """ + 돌려줄 금액(원, 0~결제액). fault가 BUYER일 때 필수이고, 그 밖에는 무시한다. + """ + refundAmount: Int +} + +# ---- src/features/order/order-settlement-admin.graphql ---- +extend type Query { + """ + 주간 정산 목록. 최근 생성 순. 매주 월요일 05:00(KST)에 지난주(월~일)까지 정산이 확정된 주문을 매장별로 묶어 만든다. + 날짜 형식이 어긋나면 INVALID_DATE(BAD_USER_INPUT). 관리자 로그인 필수. ADMIN 계정이 아니면 FORBIDDEN. + """ + adminSettlements(input: AdminSettlementListInput): AdminSettlementConnection! + """ + 주간 정산 1건과 포함 주문·현재 매장 정산 계좌(원문). 없으면 NOT_FOUND(SETTLEMENT_NOT_FOUND). + 관리자 로그인 필수. ADMIN 계정이 아니면 FORBIDDEN. + """ + adminSettlement(settlementId: ID!): AdminSettlementDetail! + """ + 월 수수료 집계. 정산 확정 시각의 KST 월로 매장별 주문 수·기준액·수수료를 묶는다(주간 정산 여부와 무관). + 월 형식이 어긋나면 INVALID_YEAR_MONTH(BAD_USER_INPUT). 관리자 로그인 필수. ADMIN 계정이 아니면 FORBIDDEN. + """ + adminMonthlyCommissions( + input: AdminMonthlyCommissionInput! + ): AdminMonthlyCommissionReport! +} + +extend type Mutation { + """ + 은행 앱에서 매장 정산 계좌로 송금한 뒤 송금 완료로 처리한다. 그 시점 매장 정산 계좌를 송금 계좌로 남기고 감사 로그(SETTLEMENT)를 쓴다. + 이미 송금 완료면 SETTLEMENT_ALREADY_PAID(CONFLICT), 매장 정산 계좌가 없으면 SETTLEMENT_ACCOUNT_REQUIRED(BAD_USER_INPUT), + 메모가 500자를 넘으면 TEXT_TOO_LONG, 없는 정산이면 NOT_FOUND. 관리자 로그인 필수. ADMIN 계정이 아니면 FORBIDDEN. + """ + adminMarkSettlementPaid( + input: AdminMarkSettlementPaidInput! + ): AdminSettlementDetail! +} + +""" +주간 정산 목록 조회 조건. 모든 필터는 AND로 결합된다. +""" +input AdminSettlementListInput { + """ + 한 번에 가져올 개수. 기본 20, 1~100만 허용하며 벗어나면 BAD_USER_INPUT. + """ + limit: Int = 20 + """ + 이전 응답의 nextCursor. 첫 페이지는 생략한다. 필터를 바꾸면 커서를 버리고 첫 페이지부터 다시 조회한다. + """ + cursor: String + """ + 송금 상태 필터. null이면 전체. + """ + status: SettlementStatusType + """ + 매장 필터. null이면 전체. + """ + storeId: ID + """ + 정산 기간 시작일(월요일, KST, YYYY-MM-DD) 필터. 관리자 알림 링크의 periodStart와 같다. null이면 전체. + """ + periodStart: String +} + +""" +주간 정산 1건(관리자 시점). +""" +type AdminSettlementSummary { + id: ID! + storeId: ID! + """ + 매장명(정산에 묶인 가장 최근 주문의 스냅샷). + """ + storeName: String! + """ + 정산 기간 시작일(월요일, KST). YYYY-MM-DD. + """ + periodStart: String! + """ + 정산 기간 마지막 날(일요일, KST). YYYY-MM-DD. + """ + periodEnd: String! + """ + 포함 주문 수. 앞 정산에서 빠진 주문(늦게 확정된 주문)도 함께 묶인다. + """ + orderCount: Int! + """ + 수수료 기준액 합계(원). + """ + settlementBaseAmount: Int! + """ + 수수료 합계(원). + """ + commissionAmount: Int! + """ + 송금할 금액(원) = 기준액 합계 − 수수료 합계. + """ + payoutAmount: Int! + """ + 송금 상태. + """ + status: SettlementStatusType! + """ + 송금 완료 시각. 송금 전이면 null. + """ + paidAt: DateTime + """ + 지금 매장 정산 계좌가 등록돼 있는지. false면 송금 완료로 처리할 수 없다. + """ + accountRegistered: Boolean! + createdAt: DateTime! +} + +""" +주간 정산 목록 페이지. +""" +type AdminSettlementConnection { + """ + 주간 정산. 최근 생성 순. + """ + items: [AdminSettlementSummary!]! + """ + 조건에 맞는 전체 건수(현재 페이지와 무관). 커서 필터는 제외하고 센다. + """ + totalCount: Int! + """ + 다음 페이지 존재 여부. + """ + hasMore: Boolean! + """ + 다음 페이지 커서. null이면 마지막 페이지다. + """ + nextCursor: String +} + +""" +주간 정산 상세(관리자 시점). 현재 계좌 원문이 들어 있으니 화면 밖(로그·분석 이벤트)에 남기지 않는다. +""" +type AdminSettlementDetail { + id: ID! + storeId: ID! + """ + 매장명(정산에 묶인 가장 최근 주문의 스냅샷). + """ + storeName: String! + """ + 정산 기간 시작일(월요일, KST). YYYY-MM-DD. + """ + periodStart: String! + """ + 정산 기간 마지막 날(일요일, KST). YYYY-MM-DD. + """ + periodEnd: String! + """ + 포함 주문 수. + """ + orderCount: Int! + """ + 수수료 기준액 합계(원). + """ + settlementBaseAmount: Int! + """ + 수수료 합계(원). + """ + commissionAmount: Int! + """ + 송금할 금액(원) = 기준액 합계 − 수수료 합계. + """ + payoutAmount: Int! + """ + 송금 상태. + """ + status: SettlementStatusType! + """ + 송금 완료 시각. 송금 전이면 null. + """ + paidAt: DateTime + """ + 지금 매장 정산 계좌가 등록돼 있는지(currentAccount가 있는지). + """ + accountRegistered: Boolean! createdAt: DateTime! """ - 내 매장 첫 품목의 상품명(주문 시점 스냅샷). 이후 상품명이 바뀌어도 유지된다. 활성 품목이 없으면 null. + 송금 완료로 처리한 관리자 표시 이름(처리 시점 스냅샷). 송금 전이거나 이름이 없으면 null. """ - firstItemName: String + paidByLabel: String """ - 내 매장 첫 품목의 상품 대표 이미지 URL(주문 시점 스냅샷). 주문 당시 이미지가 없었으면 null. + 송금 메모. 없으면 null. """ - firstItemImageUrl: String + paidNote: String + """ + 송금한 계좌(송금 시점 스냅샷, 끝 4자리만). 송금 전이면 null. + """ + paidAccount: SettlementPaidAccount + """ + 지금 매장 정산 계좌(계좌번호 원문 포함). 송금할 때 쓴다. 등록 전이면 null. + """ + currentAccount: AdminStoreSettlementAccount + """ + 포함 주문. 주문 id 순. + """ + orders: [SettlementOrder!]! } """ -주문 목록 페이지. 최신 주문이 먼저 온다. +송금 완료 입력. """ -type SellerOrderConnection { +input AdminMarkSettlementPaidInput { + settlementId: ID! """ - 주문 카드. 최신 주문이 먼저 온다. + 송금 메모(선택, 500자 이하). 정산과 감사 로그에 남는다. """ - items: [SellerOrderSummary!]! + note: String +} + +""" +월 수수료 집계 조건. +""" +input AdminMonthlyCommissionInput { """ - 조건에 맞는 전체 건수(현재 페이지와 무관). 커서 필터는 제외하고 센다. + 집계 월(KST). "YYYY-MM" 형식. 예: "2026-11". """ - totalCount: Int! + month: String! +} + +""" +월 수수료 집계. +""" +type AdminMonthlyCommissionReport { """ - 다음 페이지 존재 여부. limit+1 조회로 판정하므로 추가 쿼리가 없다. + 집계 월. "YYYY-MM". """ - hasMore: Boolean! + month: String! """ - 다음 페이지 커서. null이면 마지막 페이지다. 불투명 토큰이라 값의 형식에 의존하지 않는다. + 정산이 확정된 주문 수 합계. """ - nextCursor: String + orderCount: Int! + """ + 수수료 기준액 합계(원). + """ + settlementBaseAmount: Int! + """ + 수수료 합계(원). + """ + commissionAmount: Int! + """ + 매장별 집계. 매장 id 순, 확정 주문이 없는 매장은 빠진다. + """ + stores: [AdminMonthlyCommissionStore!]! } """ -주문 목록 조회 조건. 모든 필터는 AND로 결합되고, 미지정 필터는 적용되지 않는다. +매장 1곳의 월 수수료. """ -input SellerOrderListInput { +type AdminMonthlyCommissionStore { + storeId: ID! + """ + 매장명(그 달 가장 최근 확정 주문의 스냅샷). + """ + storeName: String! + """ + 정산이 확정된 주문 수. + """ + orderCount: Int! + """ + 수수료 기준액 합계(원). + """ + settlementBaseAmount: Int! + """ + 수수료 합계(원). + """ + commissionAmount: Int! +} + +# ---- src/features/order/order-settlement-seller.graphql ---- +extend type Query { + """ + 내 매장 정산 계좌를 조회한다. 계좌번호는 끝 4자리만 내려준다. 등록 전이면 null. + 판매자 로그인 필수. SELLER 계정이 아니면 FORBIDDEN, 매장을 보유하지 않으면 NOT_FOUND. + """ + sellerSettlementAccount: SellerSettlementAccount + """ + 내 매장 주간 정산 내역. 최근 생성 순(매주 월요일에 지난주분이 생긴다). + 판매자 로그인 필수. SELLER 계정이 아니면 FORBIDDEN, 매장을 보유하지 않으면 NOT_FOUND. + """ + sellerSettlements(input: SellerSettlementListInput): SellerSettlementConnection! + """ + 내 매장 주간 정산 1건과 포함 주문. 다른 매장 정산이거나 없으면 NOT_FOUND(SETTLEMENT_NOT_FOUND). + 판매자 로그인 필수. SELLER 계정이 아니면 FORBIDDEN, 매장을 보유하지 않으면 NOT_FOUND. + """ + sellerSettlement(settlementId: ID!): SellerSettlementDetail! +} + +""" +주간 정산 목록 조회 조건. +""" +input SellerSettlementListInput { """ 한 번에 가져올 개수. 기본 20, 1~100만 허용하며 벗어나면 BAD_USER_INPUT. """ @@ -3081,119 +5079,172 @@ input SellerOrderListInput { 이전 응답의 nextCursor. 첫 페이지는 생략한다. """ cursor: String +} + +""" +주간 정산 1건(판매자 시점). 월~일(KST) 동안 정산이 확정된 주문(그 전에 빠진 주문 포함)을 묶는다. +""" +type SellerSettlementSummary { + id: ID! """ - 주문 상태 필터. 미지정 시 전체 상태. + 정산 기간 시작일(월요일, KST). YYYY-MM-DD. """ - status: OrderStatusType + periodStart: String! """ - 주문 생성 시각 하한(이상). + 정산 기간 마지막 날(일요일, KST). YYYY-MM-DD. """ - fromCreatedAt: DateTime + periodEnd: String! """ - 주문 생성 시각 상한(이하). + 포함 주문 수. """ - toCreatedAt: DateTime + orderCount: Int! """ - 픽업 일시 하한(이상). + 수수료 기준액 합계(원). """ - fromPickupAt: DateTime + settlementBaseAmount: Int! """ - 픽업 일시 상한(이하). + 수수료 합계(원). """ - toPickupAt: DateTime + commissionAmount: Int! """ - 주문번호·주문자 이름·연락처 부분일치 검색. 셋 중 하나라도 맞으면 포함된다. + 정산 금액(원) = 기준액 합계 − 수수료 합계. 케이퀵이 매장 정산 계좌로 보내는 금액이다. """ - search: String + payoutAmount: Int! + """ + 송금 여부. PENDING이면 송금 대기, PAID면 송금 완료. + """ + status: SettlementStatusType! + """ + 송금 완료 시각. 송금 전이면 null. + """ + paidAt: DateTime + createdAt: DateTime! } """ -주문 상세. items에는 내 매장 품목만 담긴다. +주간 정산 목록 페이지. """ -type SellerOrderDetail { +type SellerSettlementConnection { + """ + 주간 정산. 최근 생성 순. + """ + items: [SellerSettlementSummary!]! + """ + 전체 건수(현재 페이지와 무관). + """ + totalCount: Int! + """ + 다음 페이지 존재 여부. + """ + hasMore: Boolean! + """ + 다음 페이지 커서. null이면 마지막 페이지다. + """ + nextCursor: String +} + +""" +주간 정산 상세(판매자 시점). +""" +type SellerSettlementDetail { id: ID! """ - 주문번호. + 정산 기간 시작일(월요일, KST). YYYY-MM-DD. """ - orderNumber: String! + periodStart: String! """ - 주문한 구매자 계정 ID. + 정산 기간 마지막 날(일요일, KST). YYYY-MM-DD. """ - accountId: ID! + periodEnd: String! """ - 현재 주문 상태. + 포함 주문 수. """ - status: OrderStatusType! + orderCount: Int! """ - 픽업 예정 일시. + 수수료 기준액 합계(원). """ - pickupAt: DateTime! + settlementBaseAmount: Int! """ - 주문자 이름. + 수수료 합계(원). """ - buyerName: String! + commissionAmount: Int! """ - 주문자 연락처. + 정산 금액(원) = 기준액 합계 − 수수료 합계. """ - buyerPhone: String! + payoutAmount: Int! """ - 할인 전 품목 합계(원). + 송금 여부. """ - subtotalPrice: Int! + status: SettlementStatusType! """ - 할인 금액(원). 할인이 없으면 0. + 송금 완료 시각. 송금 전이면 null. """ - discountPrice: Int! + paidAt: DateTime + createdAt: DateTime! """ - 최종 결제 금액(원) = subtotalPrice - discountPrice. + 송금한 계좌(송금 시점 스냅샷, 끝 4자리만). 송금 전이면 null. """ - totalPrice: Int! + paidAccount: SettlementPaidAccount """ - 각 상태에 도달한 시각. 아직 그 상태를 거치지 않았으면 null이다. + 포함 주문. 주문 id 순. """ - submittedAt: DateTime + orders: [SettlementOrder!]! +} + +extend type Mutation { """ - CONFIRMED 도달 시각. 미도달 시 null. + 내 매장 정산 계좌를 등록하거나 바꾼다. 계좌번호는 암호화해 저장하고, 응답과 감사 로그(SETTLEMENT_ACCOUNT)에는 끝 4자리만 남는다. + 은행 코드가 paymentBanks에 없으면 INVALID_BANK_CODE, 계좌번호가 하이픈을 뺀 숫자 8~20자리가 아니면 INVALID_ACCOUNT_NUMBER, + 예금주가 비었거나 50자를 넘으면 TEXT_REQUIRED·TEXT_TOO_LONG(모두 BAD_USER_INPUT). + 판매자 로그인 필수. SELLER 계정이 아니면 FORBIDDEN, 매장을 보유하지 않으면 NOT_FOUND. """ - confirmedAt: DateTime + sellerUpsertSettlementAccount( + input: SellerUpsertSettlementAccountInput! + ): SellerSettlementAccount! +} + +""" +내 매장 정산 계좌(판매자 시점). 계좌번호 원문은 내려주지 않는다. +""" +type SellerSettlementAccount { """ - MADE(제작 완료) 도달 시각. 미도달 시 null. + 은행. """ - madeAt: DateTime + bank: Bank! """ - PICKED_UP 도달 시각. 미도달 시 null. + 예금주. """ - pickedUpAt: DateTime + accountHolder: String! """ - CANCELED 도달 시각. 취소되지 않았으면 null. + 끝 4자리만 남긴 계좌번호(예: ****1234). """ - canceledAt: DateTime - createdAt: DateTime! - updatedAt: DateTime! + accountNumberMasked: String! """ - 내 매장에 속한 주문 품목만 포함된다. 다른 매장 품목은 내려오지 않는다. + 마지막으로 바꾼 주체. SELLER는 본인, ADMIN은 관리자가 대신 바꾼 경우다. """ - items: [OrderItemDetail!]! + updatedByRole: OrderActorType! """ - 상태 변경 이력. 최신순. + 마지막 변경 시각. """ - statusHistories: [OrderStatusHistory!]! + updatedAt: DateTime! } """ -주문 상태 변경 입력. 전이 규칙은 OrderStatusType 설명을 따르며, 규칙에 어긋나면 -BAD_USER_INPUT으로 거절된다. +정산 계좌 등록·변경 입력. """ -input SellerUpdateOrderStatusInput { - orderId: ID! +input SellerUpsertSettlementAccountInput { """ - 변경할 상태. 현재 상태에서 진입 가능한 값이어야 한다. + 은행 코드(paymentBanks의 code). """ - toStatus: OrderStatusType! + bankCode: String! """ - 변경 사유 메모. toStatus가 CANCELED면 필수이고, 없으면 BAD_USER_INPUT. + 예금주(1~50자). """ - note: String + accountHolder: String! + """ + 계좌번호. 하이픈을 빼고 숫자 8~20자리여야 하며 숫자만 저장한다. + """ + accountNumber: String! } # ---- src/features/order/order-subscription.graphql ---- @@ -3202,7 +5253,7 @@ extend type Subscription { 내 매장 주문 생성·상태 변경 이벤트. 판매자 로그인 필수(SELLER 아니면 FORBIDDEN). 삭제되지 않은 매장을 보유한 판매자만 구독할 수 있다 — 매장이 없거나 삭제됐으면 NOT_FOUND. 비활성(is_active=false) 매장도 구독은 유지된다. 인증은 graphql-ws connectionParams.authorization. - 구매자 주문 생성(SUBMITTED)·판매자 상태 변경·관리자 강제 취소가 모두 여기로 온다. + 입금 확인(새 주문)·판매자 상태 변경·관리자 강제 취소가 모두 여기로 온다. 입금 확인 전 주문(생성·취소)은 오지 않는다. """ sellerOrderUpdated: SellerOrderUpdate! } @@ -3213,6 +5264,10 @@ extend type Subscription { 전달 누락 가능(Redis 장애 시 발행 생략)하므로 폴백은 sellerOrderList 재조회다. """ type SellerOrderUpdate { + """ + 갱신 종류. 새 주문 알림은 SUBMITTED일 때만 띄운다. + """ + kind: SellerOrderUpdateKind! orderId: ID! """주문번호.""" orderNumber: String! @@ -3226,42 +5281,268 @@ type SellerOrderUpdate { totalPrice: Int! """첫 품목의 상품명(주문 시점 스냅샷). 주문은 단일 상품 구조다.""" productName: String! + """커스텀 주문 여부(첫 품목의 커스텀 방식이 NONE이 아니면 true).""" + hasCustom: Boolean! """주문 행의 updated_at. 폐기 규칙의 비교 키다.""" updatedAt: DateTime! } -# ---- src/features/order/order.types.graphql ---- """ -주문 상태. 구매자·판매자 API가 공용으로 쓴다. - -전이는 `SUBMITTED → CONFIRMED → MADE → PICKED_UP` 한 방향이며 각 단계는 직전 -상태에서만 진입할 수 있다. `CANCELED`는 `PICKED_UP` 이전 세 상태에서만 가능하고, -어떤 상태에서도 `SUBMITTED`로 되돌아갈 수 없다. +판매자 주문 갱신 종류. 값은 늘어날 수 있으니 모르는 값은 목록 재조회로 처리한다. +""" +enum SellerOrderUpdateKind { + """입금이 확인돼 새 주문이 접수됐다.""" + SUBMITTED + """주문 상태가 바뀌었다(확정·제작 완료·픽업 완료·취소 등).""" + STATUS_CHANGED + """픽업 일시가 바뀌었다.""" + PICKUP_RESCHEDULED +} + +# ---- src/features/order/order.types.graphql ---- +""" +주문 상태. 구매자·판매자·관리자 API가 공용으로 쓴다. 값은 늘어날 수 있으니 모르는 값을 받아도 화면이 죽지 않게 처리한다. + +흐름은 `PENDING_PAYMENT → SUBMITTED → CONFIRMED → MADE → PICKED_UP`이며 어떤 상태에서도 +앞 단계로 되돌아갈 수 없다. 판매자가 sellerUpdateOrderStatus로 바꿀 수 있는 전이는 `SUBMITTED → CONFIRMED`, +`CONFIRMED → MADE`, `CONFIRMED·MADE → PICKED_UP·NO_SHOW`뿐이고, 취소는 주체별 취소 mutation(cancelMyOrder·sellerCancelOrder·adminCancelOrder)으로만 한다. +관리자도 adminCompleteOrderPickup으로 확정·제작 완료 주문을 픽업 완료할 수 있다. +시스템은 입금 기한(1시간)이 지난 입금 대기를 취소하고, 확정 마감이 지난 접수를 취소(전액 환불)하며, +픽업 시각 + 24시간이 지난 확정·제작 완료를 픽업 완료로 바꾼다. 판매자에게는 입금이 확인된(접수된) 주문만 보인다. +""" +enum OrderStatusType { + """입금 대기. 주문 직후 계좌이체 입금을 기다리는 상태이고, 판매자에게 보이지 않는다.""" + PENDING_PAYMENT + """입금이 확인돼 접수된 상태. 판매자 확인 대기.""" + SUBMITTED + """판매자가 주문을 확인·수락한 상태. 제작 대기.""" + CONFIRMED + """판매자가 제작을 완료해 픽업을 기다리는 상태. "주문 생성됨"이 아니다.""" + MADE + """구매자가 수령을 마친 종료 상태. 이후 상태 변경 불가.""" + PICKED_UP + """노쇼. 구매자가 픽업 시간에 오지 않아 판매자가 처리한 종료 상태. 환불 없음, 리뷰 불가.""" + NO_SHOW + """취소된 종료 상태. 주체·사유·사정·환불은 주문 상세의 cancellation에 있다.""" + CANCELED +} + +""" +주문·결제·정산 기록을 남긴 주체. 값은 늘어날 수 있으니 모르는 값을 받아도 화면이 죽지 않게 처리한다. +""" +enum OrderActorType { + """구매자.""" + BUYER + """판매자.""" + SELLER + """관리자.""" + ADMIN + """시스템 자동 처리.""" + SYSTEM +} + +"""주문 상태 변경 이력 1건. 구매자·판매자·관리자 주문 상세가 공용으로 쓴다.""" +type OrderStatusHistory { + id: ID! + """변경 전 상태. 최초 생성 이력이면 null.""" + fromStatus: OrderStatusType + """변경 후 상태.""" + toStatus: OrderStatusType! + """변경 시각.""" + changedAt: DateTime! + """변경할 때 남긴 메모. 없으면 null. 예전 관리자 취소 이력은 '[관리자] ' 접두가 붙어 있다.""" + note: String + """변경한 주체.""" + actorType: OrderActorType! + """취소 사유. 취소(CANCELED) 이력에만 있고 그 밖은 null.""" + cancelReason: OrderCancelReasonType + """취소 사정. 확정·제작 완료 뒤 취소 이력에만 있고 그 밖은 null.""" + cancelFault: OrderCancelFaultType + """취소로 돌려줄 금액(원). 취소 이력에만 있고(환불이 없으면 0) 그 밖은 null.""" + refundAmount: Int +} + +""" +취소 사유. 값은 늘어날 수 있으니 모르는 값은 reasonLabel(또는 '기타')로 보여 준다. +판매자는 앞의 여섯 값, 관리자는 여기에 입금 대기 주문의 PAYMENT_NOT_RECEIVED, 구매자는 BUYER_REQUEST(서버가 정한다)를 쓴다. +""" +enum OrderCancelReasonType { + """제작할 수 없는 디자인.""" + DESIGN_NOT_FEASIBLE + """재료 소진.""" + OUT_OF_MATERIALS + """일정 불가.""" + SCHEDULE_UNAVAILABLE + """부적절한 요청.""" + INAPPROPRIATE_REQUEST + """구매자 요청.""" + BUYER_REQUEST + """기타. 결제 도입 전 취소 기록도 이 값이다.""" + OTHER + """미입금. 입금 기한이 지났거나 관리자가 입금이 없다고 판단한 입금 대기 주문.""" + PAYMENT_NOT_RECEIVED + """판매자가 확정 마감까지 확정하지 않아 자동 취소.""" + CONFIRM_TIMEOUT +} + +""" +확정·제작 완료 뒤 취소의 사정. 환불액이 갈린다(판매자 사정 = 전액, 구매자 사정 = 취소자가 정한 금액). +""" +enum OrderCancelFaultType { + """판매자 사정.""" + SELLER + """구매자 사정.""" + BUYER +} + +""" +지금 상태에서 취소할 때의 환불 규칙. +""" +enum CancelRefundRuleType { + """환불 없음(입금 대기).""" + NO_REFUND + """결제액 전액 환불(접수).""" + FULL_REFUND + """사정에 따라: 판매자 사정은 전액, 구매자 사정은 0~결제액 중 입력한 금액(확정·제작 완료).""" + BY_FAULT +} + +""" +환불 종류. +""" +enum RefundKindType { + """주문 취소 환불.""" + CANCEL + """주문과 별개로 들어온 입금을 돌려주는 반환.""" + DEPOSIT_RETURN +} + +""" +환불 진행 상태. 값은 늘어날 수 있으니 모르는 값을 받아도 화면이 죽지 않게 처리한다. +""" +enum RefundStatusType { + """구매자의 환불 계좌 입력 대기.""" + AWAITING_ACCOUNT + """계좌가 입력돼 케이퀵 송금 대기.""" + AWAITING_TRANSFER + """송금 완료.""" + COMPLETED +} + +""" +주간 정산 상태. 값은 늘어날 수 있으니 모르는 값을 받아도 화면이 죽지 않게 처리한다. +""" +enum SettlementStatusType { + """케이퀵의 매장 송금 대기.""" + PENDING + """송금 완료.""" + PAID +} + +""" +정산을 송금한 계좌(송금 시점 스냅샷). 계좌번호는 끝 4자리만 내려준다. +""" +type SettlementPaidAccount { + """ + 은행. + """ + bank: Bank! + """ + 예금주. + """ + accountHolder: String! + """ + 끝 4자리만 남긴 계좌번호(예: ****1234). + """ + accountNumberMasked: String! +} + +""" +주간 정산에 묶인 주문 1건. +""" +type SettlementOrder { + orderId: ID! + """ + 주문번호. + """ + orderNumber: String! + """ + 상품명(주문 시점 스냅샷). 품목이 없으면 null. + """ + productName: String + """ + 주문 상태(픽업 완료·노쇼, 구매자 사정 취소의 남은 금액이면 취소). + """ + status: OrderStatusType! + """ + 주문 생성 시점의 수수료율(bp, 1bp = 0.01%). + """ + commissionRateBps: Int! + """ + 수수료 기준액(원). 결제 금액, 구매자 사정 취소면 결제 금액 − 환불 금액. + """ + settlementBaseAmount: Int! + """ + 수수료(원). 기준액 × 수수료율, 원 미만 버림. + """ + commissionAmount: Int! + """ + 매장 지급액(원) = 기준액 − 수수료. + """ + payoutAmount: Int! + """ + 정산 확정 시각(픽업 완료·노쇼·구매자 사정 취소 시각). 이 시각이 속한 주(월~일, KST)가 끝난 뒤 첫 주간 정산에 묶인다. + """ + settlementFinalizedAt: DateTime! +} + +""" +주문 취소 정보. 취소된 주문에만 있다. """ -enum OrderStatusType { - """구매자가 주문을 넣은 직후의 초기 상태. 판매자 확인 대기.""" - SUBMITTED - """판매자가 주문을 확인·수락한 상태. 제작 대기.""" - CONFIRMED - """판매자가 제작을 완료해 픽업을 기다리는 상태. "주문 생성됨"이 아니다.""" - MADE - """구매자가 수령을 마친 종료 상태. 이후 상태 변경 불가.""" - PICKED_UP - """취소된 종료 상태. 취소 처리에는 사유(note)가 필수다.""" - CANCELED +type OrderCancellation { + """취소한 주체.""" + actorType: OrderActorType! + """취소 사유.""" + reason: OrderCancelReasonType! + """취소 사유 표시 라벨(예: 재료 소진). 모르는 reason 값의 표시에 쓴다.""" + reasonLabel: String! + """취소하며 남긴 메모. 없으면 null.""" + note: String + """취소 사정. 확정·제작 완료 뒤 취소에만 있고 그 밖은 null.""" + fault: OrderCancelFaultType + """돌려줄 금액(원). 환불이 없으면 0.""" + refundAmount: Int! + """환불 진행 상태. 환불이 없으면 null.""" + refundStatus: RefundStatusType + """환불 송금 완료 시각. 완료 전이거나 환불이 없으면 null.""" + refundCompletedAt: DateTime + """취소 시각.""" + canceledAt: DateTime! } -"""주문 상태 변경 이력 1건. 구매자·판매자·관리자 주문 상세가 공용으로 쓴다.""" -type OrderStatusHistory { +""" +구매자에게 돌려줄 돈 1건(취소 환불 또는 입금 반환). +""" +type OrderRefund { id: ID! - """변경 전 상태. 최초 생성 이력이면 null.""" - fromStatus: OrderStatusType - """변경 후 상태.""" - toStatus: OrderStatusType! - """변경 시각.""" - changedAt: DateTime! - """변경 사유 메모. 취소(CANCELED) 전이에는 필수로 기록된다(관리자 취소는 '[관리자]' 접두).""" - note: String + """환불 종류.""" + kind: RefundKindType! + """돌려줄 금액(원).""" + amount: Int! + """진행 상태.""" + status: RefundStatusType! + """환불받을 은행. 계좌 입력 전이면 null.""" + bank: Bank + """환불 계좌 예금주. 계좌 입력 전이면 null.""" + accountHolder: String + """환불 계좌번호 끝 4자리만 보이는 값(예: ****1234). 계좌 입력 전이면 null.""" + accountNumberMasked: String + """환불이 생긴 시각.""" + requestedAt: DateTime! + """구매자가 계좌를 입력한 시각. 입력 전이면 null.""" + accountSubmittedAt: DateTime + """송금 완료 시각. 완료 전이면 null.""" + completedAt: DateTime } """ @@ -3284,12 +5565,119 @@ type OrderItemDetail { itemSubtotalPrice: Int! """선택한 옵션(주문 시점 스냅샷).""" optionItems: [OrderItemOption!]! + """커스텀 방식(주문 시점 스냅샷). 커스텀이 없는 품목은 NONE.""" + customMode: CustomModeType! + """ + 커스텀 대표 이미지 URL. 3D는 윗면 렌더, 슬롯형은 합성 이미지이고 목록 썸네일·리뷰 Before에 쓰인다. 없으면 null. + """ + customPreviewImageUrl: String + """ + 슬롯형 바탕 이미지 URL(주문 시점 스냅샷, 정사각). 문구 자리·자유 편집 영역 좌표의 기준이다. 슬롯형이 아니거나 바탕을 저장하기 전 주문이면 null. + """ + customBaseImageUrl: String + """커스텀 이미지(3D 렌더 5장 또는 슬롯형 합성 1장). kind 선언 순서다. 없으면 빈 배열.""" + customImages: [OrderItemCustomImage!]! + """3D 디자인(JSON v1). 3D가 아니거나 저장된 값을 읽을 수 없으면 null.""" + threeDDesign: ThreeDDesign """입력한 커스텀 문구(주문 시점 스냅샷).""" customTexts: [OrderItemCustomText!]! """자유 편집 요청(주문 시점 스냅샷).""" freeEdits: [OrderItemFreeEdit!]! } +""" +주문 커스텀 이미지 종류. 값은 늘어날 수 있으니 모르는 값을 받아도 화면이 죽지 않게 처리한다. +3D 옆면은 옆면 고도 asin(0.4) 정사영이고 좌·우는 정면을 보는 사람 기준이다. +""" +enum CustomImageKindType { + """3D 윗면(위에서 내려다본 정사각). 대표 이미지다.""" + THREE_D_TOP + """3D 옆면 정면(yaw 0).""" + THREE_D_FRONT + """3D 옆면 뒤(정면 반대).""" + THREE_D_BACK + """3D 옆면 왼쪽.""" + THREE_D_LEFT + """3D 옆면 오른쪽.""" + THREE_D_RIGHT + """슬롯형 합성 이미지(바탕 + 문구, 구매자가 본 그대로). 대표 이미지다.""" + SLOT_COMPOSITE +} + +"""주문 커스텀 이미지 1장.""" +type OrderItemCustomImage { + id: ID! + """이미지 종류. 품목마다 종류당 1장이다.""" + kind: CustomImageKindType! + """이미지 URL.""" + imageUrl: String! +} + +""" +주문에 저장된 3D 디자인(JSON v1). 배열 순서가 그리는 순서다. 그리는 규칙은 판매자 앱 렌더러와 구매자 편집기가 공유한다. +선택지·시트 색·효과·꾸미기 키는 customThreeDCatalog의 key이고, 퇴역한 항목도 과거 주문을 그릴 수 있게 카탈로그에 남는다. +""" +type ThreeDDesign { + """디자인 JSON 버전. 지금은 1.""" + schemaVersion: Int! + """모양·크기·디자인·맛·시트 색.""" + basic: ThreeDDesignBasic! + """윗면 항목. x·y는 케이크 판 정사각 기준 중심 0~1(왼쪽 위 원점).""" + top: [ThreeDDesignItem!]! + """옆면 항목. x는 정면(yaw 0)에서 잰 둘레 비율 0~1, y는 윗면 0~바닥 1.""" + side: [ThreeDDesignItem!]! +} + +"""3D 디자인의 케이크 기본값.""" +type ThreeDDesignBasic { + """모양 선택지 key.""" + shape: String! + """크기 선택지 key.""" + size: String! + """디자인 선택지 key. 고르지 않았으면 null(장식 없는 시트).""" + design: String + """맛 선택지 key. 고르지 않았으면 null.""" + flavor: String + """시트 색 key.""" + sheetColor: String! +} + +"""3D 디자인 항목 종류. 값은 늘어날 수 있으니 모르는 값을 받아도 화면이 죽지 않게 처리한다.""" +enum ThreeDItemKindType { + """글자.""" + TEXT + """꾸미기 이미지.""" + DECO +} + +"""3D 디자인 항목(글자 또는 꾸미기) 1개.""" +type ThreeDDesignItem { + """항목 종류.""" + kind: ThreeDItemKindType! + """가로 위치(면별 좌표계, ThreeDDesign.top·side 참고).""" + x: Float! + """세로 위치(면별 좌표계, ThreeDDesign.top·side 참고).""" + y: Float! + """크기(케이크 판 너비 대비 cqw).""" + size: Float! + """효과.""" + effect: ThreeDDesignEffect! + """글자 내용(줄바꿈·이모지 포함). TEXT만 값이 있다.""" + text: String + """글자색(#RRGGBB 대문자). TEXT만 값이 있다.""" + color: String + """꾸미기 key. DECO만 값이 있다.""" + decoId: String +} + +"""3D 디자인 항목에 건 효과.""" +type ThreeDDesignEffect { + """효과 key(카탈로그 effects).""" + type: String! + """효과 강도(0~100 정수).""" + intensity: Int! +} + """주문 시점의 옵션 스냅샷. 판매자가 이후 옵션을 수정·삭제해도 주문 내용은 변하지 않는다.""" type OrderItemOption { id: ID! @@ -3301,24 +5689,52 @@ type OrderItemOption { priceDelta: Int! } -"""주문 시점의 커스텀 문구 스냅샷.""" +""" +주문 시점의 커스텀 문구 스냅샷. 좌표는 바탕 이미지 한 변을 10000으로 본 정수 비율이고 원점은 왼쪽 위다. +글꼴은 플랫폼 공통 1종(Pretendard Bold)이고 크기는 영역에 맞춰 자동이다. +""" type OrderItemCustomText { id: ID! - """문구 슬롯 식별 키(주문 시점).""" + """원본 문구 자리 ID. 자리가 이후 바뀌거나 지워져도 스냅샷은 그대로다. 문구 자리를 지정하기 전 주문이면 null.""" + tokenId: ID + """문구 자리 식별 키(주문 시점).""" tokenKey: String! - """슬롯의 기본 문구(주문 시점).""" + """문구 자리 표시 이름(주문 시점).""" + label: String! + """문구 자리의 기본 문구(주문 시점).""" defaultText: String! - """구매자가 실제로 입력한 문구.""" - valueText: String! + """구매자가 넣은 문구(줄바꿈·이모지 포함). 선택 자리를 지웠으면 null('문구 없음').""" + valueText: String + """영역 왼쪽 위 x(0~10000).""" + posX: Int! + """영역 왼쪽 위 y(0~10000).""" + posY: Int! + """영역 너비(posX + width ≤ 10000).""" + width: Int! + """영역 높이(posY + height ≤ 10000).""" + height: Int! + """글자색(#RRGGBB 대문자).""" + textColor: String! + """영역 안 글자 정렬.""" + textAlign: CustomTextAlignType! """입력 화면 노출 순서. 오름차순.""" sortOrder: Int! } -"""주문 시점의 자유 편집 요청 스냅샷. 구매자가 이미지 위에 영역을 지정해 남긴 요청이다.""" +""" +주문 시점의 자유 편집 요청 스냅샷. 구매자가 슬롯형 바탕 이미지 위에 영역을 지정해 남긴 요청이다. +좌표계는 OrderItemCustomText와 같다(바탕 한 변 10000, 왼쪽 위 원점). +""" type OrderItemFreeEdit { id: ID! - """지정한 편집 영역을 잘라낸 이미지 URL.""" - cropImageUrl: String! + """영역 왼쪽 위 x(0~10000).""" + posX: Int! + """영역 왼쪽 위 y(0~10000).""" + posY: Int! + """영역 너비(posX + width ≤ 10000).""" + width: Int! + """영역 높이(posY + height ≤ 10000).""" + height: Int! """해당 영역에 대한 요청 문구.""" descriptionText: String! """요청 순서. 오름차순.""" @@ -3336,6 +5752,21 @@ type OrderItemFreeEditAttachment { sortOrder: Int! } +""" +판매자 픽업 일시 변경 이력 1건. 구매자·판매자·관리자 주문 상세가 공용으로 쓴다. +""" +type OrderPickupChange { + id: ID! + """변경 전 픽업 일시.""" + fromPickupAt: DateTime! + """변경 후 픽업 일시.""" + toPickupAt: DateTime! + """변경 시각.""" + changedAt: DateTime! + """판매자가 남긴 변경 메모. 없으면 null.""" + note: String +} + # ---- src/features/product/product-admin-banner.graphql ---- extend type Query { """ @@ -3882,9 +6313,13 @@ type AdminProduct { """ currency: String! """ - 기본 디자인 이미지 URL. 미등록 시 null. + 대표 이미지 URL(삭제 제외 첫 장). 이미지가 없으면 null. + """ + thumbnailUrl: String + """ + 커스텀 방식. """ - baseDesignImageUrl: String + customMode: CustomModeType! """ 노출 여부. false면 구매자 화면에 나오지 않는다. """ @@ -4004,14 +6439,6 @@ type AdminProductOptionGroup { """ maxSelect: Int! """ - 선택지에 구매자 커스텀 입력(설명)이 필요한 그룹인지. 현재는 true인 그룹의 옵션을 고르면 주문이 거절된다(잠정 가드). - """ - optionRequiresDescription: Boolean! - """ - 선택지에 구매자 커스텀 입력(이미지)이 필요한 그룹인지. 현재는 true인 그룹의 옵션을 고르면 주문이 거절된다(잠정 가드). - """ - optionRequiresImage: Boolean! - """ 상품 안에서의 그룹 노출 순서. 오름차순. """ sortOrder: Int! @@ -4054,6 +6481,10 @@ type AdminProductOptionItem { 노출 여부. false면 구매자가 고를 수 없다. """ isActive: Boolean! + """ + 이어진 3D 카탈로그 선택지 키(customThreeDCatalog.optionChoices.key). 없으면 null. + """ + threeDKey: String } """ @@ -4066,126 +6497,357 @@ type AdminProductCustomTemplate { """ baseImageUrl: String! """ - 활성 여부. false면 구매자 화면에 커스텀 입력이 열리지 않는다. + 자유 편집(바탕 위 영역 지정 + 요청 문구·참고 사진) 허용 여부. """ - isActive: Boolean! + freeEditEnabled: Boolean! """ 문구 슬롯. sortOrder 오름차순. 삭제된 슬롯은 뺀다. """ - textTokens: [AdminProductCustomTextToken!]! + textTokens: [AdminProductCustomTextToken!]! +} + +""" +커스텀 템플릿의 문구 슬롯 1개. +""" +type AdminProductCustomTextToken { + id: ID! + """ + 슬롯 식별 키. + """ + tokenKey: String! + """ + 표시 이름(구매자 입력 화면 라벨). + """ + label: String! + """ + 구매자가 입력하지 않았을 때 쓸 기본 문구. + """ + defaultText: String! + """ + 입력 가능한 최대 글자 수. + """ + maxLength: Int! + """ + 입력 화면에서의 노출 순서. 오름차순. + """ + sortOrder: Int! + """ + 필수 입력 여부. + """ + isRequired: Boolean! + """ + 글자색(#RRGGBB 대문자). + """ + textColor: String! + """ + 자리 안 글자 정렬. + """ + textAlign: CustomTextAlignType! +} + +""" +상품 목록 페이지. 최신 등록이 먼저 온다. +""" +type AdminProductConnection { + """ + 상품. 최신 등록이 먼저 온다. + """ + items: [AdminProduct!]! + """ + 조건에 맞는 전체 건수(현재 페이지와 무관). 커서 필터는 제외하고 센다. + """ + totalCount: Int! + """ + 다음 페이지 존재 여부. limit+1 조회로 판정하므로 추가 쿼리가 없다. + """ + hasMore: Boolean! + """ + 다음 페이지 커서. null이면 마지막 페이지다. + """ + nextCursor: String +} + +""" +상품 목록 조회 조건. +""" +input AdminProductListInput { + """ + 한 번에 가져올 개수. 기본 20, 1~100만 허용하며 벗어나면 BAD_USER_INPUT. + """ + limit: Int = 20 + """ + 이전 응답의 nextCursor. 첫 페이지는 생략한다. + """ + cursor: String + """ + 상품명 부분일치 검색어. 최대 100자. 미지정 시 전체. + """ + keyword: String + """ + 소속 매장 ID 필터. 미지정 시 전체. + """ + storeId: ID + """ + 노출 여부 필터. 미지정 시 전체. + """ + isActive: Boolean +} + +""" +상품 노출 여부 변경 입력. +""" +input AdminSetProductActiveInput { + productId: ID! + """ + 노출 여부. + """ + isActive: Boolean! + """ + 변경 사유. 감사 로그에 기록된다. 최대 500자. 선택. + """ + reason: String +} + +# ---- src/features/product/product-category.graphql ---- +extend type Query { + """전역 카테고리 목록(홈 칩·카테고리 진입 화면). type 미지정 시 전체. 비로그인 접근 가능.""" + categories(input: CategoriesInput): [CategoryItem!]! +} + +"""전역 카테고리 조회 조건.""" +input CategoriesInput { + """EVENT | STYLE | OTHER. 비우면 전체.""" + type: CategoryType +} + +"""전역 카테고리 항목. '전체' 칩은 카테고리가 아니라 FE 가상 칩(필터 미적용)이라 포함하지 않는다.""" +type CategoryItem { + id: ID! + """카테고리명. 칩에 그대로 노출된다.""" + name: String! + """분류 축. 홈 칩에는 EVENT만 노출된다.""" + categoryType: CategoryType! + """노출 순서. 오름차순.""" + sortOrder: Int! +} + +# ---- src/features/product/product-custom-catalog.graphql ---- +extend type Query { + """ + 3D 케이크 카탈로그. 모양·크기·디자인·맛 선택지, 시트 색, 글자색, 효과, 꾸미기, 서버가 강제하는 한도를 담는다. 비로그인 접근 가능. + 항목은 지우지 않고 selectable=false로 퇴역시켜 과거 주문의 디자인도 이 목록으로 그릴 수 있다. revision이 같으면 내용도 같다. + """ + customThreeDCatalog: CustomThreeDCatalog! +} + +""" +3D 케이크 카탈로그. +""" +type CustomThreeDCatalog { + """ + 카탈로그 버전. 항목을 더하거나 퇴역시키면 오른다. 클라이언트 캐시 무효화 기준이다. + """ + revision: Int! + """ + 주문에 저장하는 3D 디자인 JSON 버전. 주문 생성의 design.schemaVersion은 이 값이어야 한다. + """ + designSchemaVersion: Int! + """ + 서버가 강제하는 개수·길이·크기 한도. + """ + limits: CustomThreeDLimits! + """ + 상품 옵션 항목이 threeDKey로 이어지는 선택지(크기·맛·모양·디자인). + """ + optionChoices: [CustomThreeDOptionChoice!]! + """ + 시트 색(디자인 basic.sheetColor 값). + """ + sheetColors: [CustomThreeDSheetColor!]! + """ + 글자색 팔레트(#RRGGBB 대문자, 편집기 표시 순서). 이 밖의 #RRGGBB도 쓸 수 있다. + """ + textColorPresets: [String!]! + """ + 새 글자의 기본 색(#RRGGBB). + """ + defaultTextColor: String! + """ + 글자·꾸미기에 거는 효과. + """ + effects: [CustomThreeDEffect!]! + """ + 꾸미기 분류(편집기 탭). + """ + decoCategories: [CustomThreeDDecoCategory!]! + """ + 꾸미기 이미지. + """ + decos: [CustomThreeDDeco!]! +} + +""" +3D 디자인 한도. 크기 단위는 케이크 판 너비 대비 cqw다. +""" +type CustomThreeDLimits { + """ + 면(윗면·옆면)당 글자 최대 개수. + """ + maxTextsPerFace: Int! + """ + 면(윗면·옆면)당 꾸미기 최대 개수. + """ + maxDecosPerFace: Int! + """ + 글자 하나의 최대 길이(코드 포인트, 줄바꿈·이모지 포함). + """ + maxTextLength: Int! + """ + 글자 크기 최솟값(cqw). + """ + textSizeMin: Float! + """ + 글자 크기 최댓값(cqw). + """ + textSizeMax: Float! + """ + 꾸미기 크기 최솟값(cqw). + """ + decoSizeMin: Float! + """ + 꾸미기 크기 최댓값(cqw). + """ + decoSizeMax: Float! + """ + 효과 강도 최솟값(정수). + """ + effectIntensityMin: Int! + """ + 효과 강도 최댓값(정수). + """ + effectIntensityMax: Int! + """ + 새 글자·꾸미기의 기본 효과 강도. + """ + effectIntensityDefault: Int! } """ -커스텀 템플릿의 문구 슬롯 1개. +옵션 항목에 이을 수 있는 3D 선택지. """ -type AdminProductCustomTextToken { - id: ID! +type CustomThreeDOptionChoice { """ - 슬롯 식별 키. + 옵션 항목 threeDKey로 저장하는 키(예: shape.heart). """ - tokenKey: String! + key: String! """ - 구매자가 입력하지 않았을 때 쓸 기본 문구. + 선택지 카테고리. """ - defaultText: String! + category: ThreeDOptionCategoryType! """ - 입력 가능한 최대 글자 수. + 디자인 JSON basic에 들어가는 값(예: heart). """ - maxLength: Int! + value: String! """ - 입력 화면에서의 노출 순서. 오름차순. + 표시 이름. 기본 세트로 만든 옵션 항목의 이름이 된다. """ - sortOrder: Int! + label: String! """ - 필수 입력 여부. + 기본 추가 금액(원). 기본 세트로 만든 옵션 항목의 priceDelta가 되고, 매장이 바꿀 수 있다. """ - isRequired: Boolean! + defaultPriceDelta: Int! + """ + 선택지 이미지 URL(디자인만). 없으면 null. + """ + imageUrl: String + """ + 위에서 본 케이크 판·옆모습 배율(크기만). 없으면 null. + """ + renderScale: Float + """ + 새로 고를 수 있는지. false면 퇴역한 값으로, 과거 주문을 그릴 때만 쓴다. + """ + selectable: Boolean! } """ -상품 목록 페이지. 최신 등록이 먼저 온다. +3D 시트 색. """ -type AdminProductConnection { +type CustomThreeDSheetColor { """ - 상품. 최신 등록이 먼저 온다. + 디자인 JSON basic.sheetColor 값. """ - items: [AdminProduct!]! + key: String! """ - 조건에 맞는 전체 건수(현재 페이지와 무관). 커서 필터는 제외하고 센다. + 표시 이름. """ - totalCount: Int! + label: String! """ - 다음 페이지 존재 여부. limit+1 조회로 판정하므로 추가 쿼리가 없다. + 렌더 색(#RRGGBB 대문자). """ - hasMore: Boolean! + hex: String! """ - 다음 페이지 커서. null이면 마지막 페이지다. + 새로 고를 수 있는지. false면 과거 주문을 그릴 때만 쓴다. """ - nextCursor: String + selectable: Boolean! } """ -상품 목록 조회 조건. +글자·꾸미기 효과. """ -input AdminProductListInput { +type CustomThreeDEffect { """ - 한 번에 가져올 개수. 기본 20, 1~100만 허용하며 벗어나면 BAD_USER_INPUT. + 디자인 JSON effect.type 값. """ - limit: Int = 20 + key: String! """ - 이전 응답의 nextCursor. 첫 페이지는 생략한다. + 표시 이름. """ - cursor: String + label: String! """ - 상품명 부분일치 검색어. 최대 100자. 미지정 시 전체. + 새로 고를 수 있는지. false면 과거 주문을 그릴 때만 쓴다. """ - keyword: String + selectable: Boolean! +} + +""" +꾸미기 분류. +""" +type CustomThreeDDecoCategory { """ - 소속 매장 ID 필터. 미지정 시 전체. + 분류 키. CustomThreeDDeco.category가 가리킨다. """ - storeId: ID + key: String! """ - 노출 여부 필터. 미지정 시 전체. + 표시 이름(편집기 탭). """ - isActive: Boolean + label: String! } """ -상품 노출 여부 변경 입력. +꾸미기 이미지 1개. """ -input AdminSetProductActiveInput { - productId: ID! +type CustomThreeDDeco { """ - 노출 여부. + 디자인 JSON 꾸미기 항목의 decoId 값. """ - isActive: Boolean! + key: String! """ - 변경 사유. 감사 로그에 기록된다. 최대 500자. 선택. + 분류 키(CustomThreeDDecoCategory.key). """ - reason: String -} - -# ---- src/features/product/product-category.graphql ---- -extend type Query { - """전역 카테고리 목록(홈 칩·카테고리 진입 화면). type 미지정 시 전체. 비로그인 접근 가능.""" - categories(input: CategoriesInput): [CategoryItem!]! -} - -"""전역 카테고리 조회 조건.""" -input CategoriesInput { - """EVENT | STYLE | OTHER. 비우면 전체.""" - type: CategoryType -} - -"""전역 카테고리 항목. '전체' 칩은 카테고리가 아니라 FE 가상 칩(필터 미적용)이라 포함하지 않는다.""" -type CategoryItem { - id: ID! - """카테고리명. 칩에 그대로 노출된다.""" - name: String! - """분류 축. 홈 칩에는 EVENT만 노출된다.""" - categoryType: CategoryType! - """노출 순서. 오름차순.""" - sortOrder: Int! + category: String! + """ + 표시 이름. + """ + label: String! + """ + 이미지 URL(PNG, 투명 배경). + """ + imageUrl: String! + """ + 새로 고를 수 있는지. false면 과거 주문을 그릴 때만 쓴다. + """ + selectable: Boolean! } # ---- src/features/product/product-detail.graphql ---- @@ -4221,6 +6883,53 @@ type ProductDetail { isWishlisted: Boolean! """옵션 섹션(케이크 사이즈/맛 등, sort_order asc). 활성 그룹만.""" optionGroups: [ProductDetailOptionGroup!]! + """커스텀 방식. NONE이 아니면 꾸민 내용과 함께 주문해야 한다.""" + customMode: CustomModeType! + """슬롯형 꾸미기 설정. customMode가 SLOT일 때만 오고 그 밖에는 null.""" + customTemplate: ProductDetailCustomTemplate +} + +""" +슬롯형 꾸미기 설정. 바탕 이미지는 정사각(1:1)이고 문구 자리 좌표는 한 변을 10000으로 본 정수 비율이다(원점 왼쪽 위). +""" +type ProductDetailCustomTemplate { + """설정 버전. 주문할 때 그대로 보내고, 그사이 판매자가 설정을 바꿨으면 주문이 거절되어 다시 꾸며야 한다.""" + revision: Int! + """바탕 이미지 URL(정사각).""" + baseImageUrl: String! + """자유 편집(바탕 위 영역 지정 + 요청 문구·참고 사진) 허용 여부.""" + freeEditEnabled: Boolean! + """문구 자리. sortOrder 오름차순.""" + slots: [ProductDetailCustomSlot!]! +} + +""" +슬롯형 문구 자리 1개. 구매자는 기본 문구로 시작해 바꾸거나 지운다(필수 자리는 지울 수 없다). +""" +type ProductDetailCustomSlot { + id: ID! + """자리 이름(예: 받는 사람). 입력 화면 라벨로 쓴다.""" + label: String! + """기본 문구. 바꾸지 않으면 이 문구로 주문된다.""" + defaultText: String! + """입력 가능한 최대 글자 수(코드 포인트, 1~50).""" + maxLength: Int! + """필수 자리 여부. true면 문구를 비울 수 없다.""" + isRequired: Boolean! + """자리 왼쪽 위 가로 위치(0~10000).""" + posX: Int! + """자리 왼쪽 위 세로 위치(0~10000).""" + posY: Int! + """자리 너비(1~10000, posX + width ≤ 10000).""" + width: Int! + """자리 높이(1~10000, posY + height ≤ 10000).""" + height: Int! + """글자색(#RRGGBB 대문자).""" + textColor: String! + """자리 안 글자 정렬.""" + textAlign: CustomTextAlignType! + """입력 화면 노출 순서. 오름차순.""" + sortOrder: Int! } """상품 상세 옵션 섹션(그룹).""" @@ -4238,6 +6947,10 @@ type ProductDetailOptionGroup { maxSelect: Int! """섹션 노출 순서. 오름차순.""" sortOrder: Int! + """ + 3D 상품에서 이 그룹이 정하는 3D 값의 종류. 선택지가 3D 항목과 이어지지 않았거나 종류가 섞였으면 null. + """ + threeDCategory: ThreeDOptionCategoryType """이 그룹의 선택지. 활성 항목만 온다.""" items: [ProductDetailOptionItem!]! } @@ -4255,6 +6968,10 @@ type ProductDetailOptionItem { priceDelta: Int! """그룹 안에서의 노출 순서. 오름차순.""" sortOrder: Int! + """ + 이어진 3D 카탈로그 선택지 키(customThreeDCatalog.optionChoices.key). 3D 편집기는 이 키의 value로 모양·크기 등을 그린다. 없으면 null. + """ + threeDKey: String } # ---- src/features/product/product-home.graphql ---- @@ -4535,7 +7252,7 @@ type SearchPriceBucket { # ---- src/features/product/product-seller-upload.graphql ---- extend type Mutation { """ - 이미지 업로드용 Presigned URL을 발급한다. 판매자 로그인 필수. SELLER 계정이 아니면 FORBIDDEN, 매장을 보유하지 않으면 NOT_FOUND. 상품·옵션·커스텀 템플릿·매장 로고의 URL 필드는 여기서 발급된 publicUrl만 받는다. + 이미지 업로드용 Presigned URL을 발급한다. 판매자 로그인 필수. SELLER 계정이 아니면 FORBIDDEN, 매장을 보유하지 않으면 NOT_FOUND. 상품·옵션·커스텀 템플릿·매장 로고·채팅 이미지의 URL 필드는 여기서 발급된 publicUrl만 받는다. """ sellerCreateUploadUrl(input: SellerCreateUploadUrlInput!): UploadUrl! } @@ -4553,7 +7270,7 @@ input SellerCreateUploadUrlInput { """ contentType: String! """ - 파일 크기(바이트). 1 이상 5MB 이하, 아니면 BAD_USER_INPUT. + 파일 크기(바이트). 1 이상, 용도별 최대 크기(CONVERSATION_IMAGE 10MB, 그 밖 5MB) 이하. 아니면 BAD_USER_INPUT. """ contentLength: Int! } @@ -4674,21 +7391,40 @@ extend type Mutation { ): [SellerOptionItem!]! """ - 상품 커스텀 템플릿을 등록 또는 수정한다. 판매자 로그인 필수. SELLER 계정이 아니면 FORBIDDEN, 매장을 보유하지 않으면 NOT_FOUND. + 상품 커스텀 방식을 바꾼다. 바꿀 방식의 준비가 끝나지 않았으면(SellerProduct.customReadiness의 issues가 있으면) + CUSTOM_PRODUCT_NOT_READY. 지금과 같은 방식이면 아무것도 바꾸지 않고 그대로 돌려준다. + 판매자 로그인 필수. SELLER 계정이 아니면 FORBIDDEN, 매장을 보유하지 않거나 내 상품이 아니면 NOT_FOUND. """ - sellerUpsertProductCustomTemplate( - input: SellerUpsertProductCustomTemplateInput! - ): SellerCustomTemplate! + sellerSetProductCustomMode( + productId: ID! + """ + 바꿀 커스텀 방식. + """ + customMode: CustomModeType! + ): SellerProduct! """ - 상품 커스텀 템플릿 활성 상태를 변경한다. 판매자 로그인 필수. SELLER 계정이 아니면 FORBIDDEN, 매장을 보유하지 않으면 NOT_FOUND. + 3D 기본 세트를 불러온다. 3D 항목 그룹이 없는 카테고리(크기·맛·모양·디자인)마다 단일 선택 그룹을 만들고 + 선택 가능한 카탈로그 선택지 전부를 기본 가격으로 넣는다. 크기·맛·모양은 필수, 디자인은 고르지 않아도 되는 그룹이다. + 이미 그룹이 있는 카테고리는 건드리지 않아 여러 번 불러도 결과가 같다(새로 만든 그룹이 없으면 감사 기록도 없다). + 판매자 로그인 필수. SELLER 계정이 아니면 FORBIDDEN, 매장을 보유하지 않거나 내 상품이 아니면 NOT_FOUND. + """ + sellerApplyThreeDOptionPreset(productId: ID!): SellerProduct! """ - sellerSetProductCustomTemplateActive( - input: SellerSetProductCustomTemplateActiveInput! + 상품 커스텀 템플릿(슬롯형 바탕)을 등록 또는 수정한다. 수정하면 revision이 1 오른다. + 바탕 이미지가 바뀔 때만 서버가 이미지를 읽어 정사각(가로·세로 차이 1px 이하)인지 확인한다: + 아니면 CUSTOM_BASE_IMAGE_NOT_SQUARE, 이미지로 읽을 수 없으면 CUSTOM_BASE_IMAGE_UNREADABLE, 저장소를 읽지 못하면 S3_READ_FAILED(503). + 판매자 로그인 필수. SELLER 계정이 아니면 FORBIDDEN, 매장을 보유하지 않으면 NOT_FOUND. + """ + sellerUpsertProductCustomTemplate( + input: SellerUpsertProductCustomTemplateInput! ): SellerCustomTemplate! """ - 커스텀 텍스트 토큰을 등록 또는 수정한다. 판매자 로그인 필수. SELLER 계정이 아니면 FORBIDDEN, 매장을 보유하지 않으면 NOT_FOUND. + 커스텀 텍스트 토큰(문구 자리)을 등록 또는 수정한다. 등록·수정·삭제·순서 변경마다 템플릿 revision이 1 오른다. 등록 시 같은 템플릿에 같은 tokenKey의 삭제된 슬롯이 있으면 그 슬롯(같은 id)을 복구해 입력값으로 갱신한다. 활성 슬롯과 tokenKey가 겹치면(수정으로 삭제된 슬롯의 키로 바꾸는 경우 포함) CUSTOM_TEXT_TOKEN_KEY_TAKEN. + 검증: tokenKey 형식 CUSTOM_TOKEN_KEY_INVALID, maxLength 1~50 FIELD_OUT_OF_RANGE, 기본 문구가 maxLength 초과면 CUSTOM_TEXT_DEFAULT_TOO_LONG, + 좌표가 바탕 밖이면 CUSTOM_AREA_OUT_OF_BOUNDS, 글자색 형식 INVALID_COLOR_FORMAT. + 판매자 로그인 필수. SELLER 계정이 아니면 FORBIDDEN, 매장을 보유하지 않으면 NOT_FOUND. """ sellerUpsertProductCustomTextToken( input: SellerUpsertProductCustomTextTokenInput! @@ -4791,6 +7527,10 @@ type SellerOptionItem { 노출 여부. false면 구매자가 고를 수 없다. """ isActive: Boolean! + """ + 이어진 3D 카탈로그 선택지 키(customThreeDCatalog.optionChoices.key). 없으면 null. + """ + threeDKey: String } """ @@ -4821,17 +7561,6 @@ type SellerOptionGroup { """ maxSelect: Int! """ - 선택지에 구매자 커스텀 입력(설명)이 필요한 그룹인지. - 현재는 커스텀 체크아웃이 확장되기 전이라, 이 값이 true인 그룹의 옵션을 고르면 - 주문이 거절된다(잠정 가드). 켜기 전에 주문 가능 여부를 확인해야 한다. - """ - optionRequiresDescription: Boolean! - """ - 선택지에 구매자 커스텀 입력(이미지)이 필요한 그룹인지. - optionRequiresDescription과 마찬가지로 현재는 true인 그룹의 옵션 선택이 거절된다. - """ - optionRequiresImage: Boolean! - """ 상품 안에서의 그룹 노출 순서. 오름차순. """ sortOrder: Int! @@ -4840,6 +7569,10 @@ type SellerOptionGroup { """ isActive: Boolean! """ + 활성 선택지의 threeDKey로 정해지는 3D 카테고리. 이어진 키가 없거나 종류가 섞였으면 null. + """ + threeDCategory: ThreeDOptionCategoryType + """ 이 그룹의 선택지. sortOrder 오름차순. """ optionItems: [SellerOptionItem!]! @@ -4856,11 +7589,15 @@ type SellerCustomTextToken { """ tokenKey: String! """ + 표시 이름(구매자 입력 화면 라벨). 주문에 스냅샷으로 남는다. + """ + label: String! + """ 구매자가 입력하지 않았을 때 쓸 기본 문구. """ defaultText: String! """ - 입력 가능한 최대 글자 수. + 입력 가능한 최대 글자 수(코드 포인트, 1~50). """ maxLength: Int! """ @@ -4872,39 +7609,50 @@ type SellerCustomTextToken { """ isRequired: Boolean! """ - 문구 영역 왼쪽 위 모서리의 가로 위치. 베이스 이미지 한 변을 10000으로 본 정수 비율(0~10000)이고 서버는 범위를 검사하지 않는다. - 미지정 시 null이고 배치는 클라이언트가 정한다. + 문구 영역 왼쪽 위 모서리의 가로 위치. 바탕 이미지 한 변을 10000으로 본 정수 비율(0~10000), 원점은 왼쪽 위. """ - posX: Int + posX: Int! """ - 문구 영역 왼쪽 위 모서리의 세로 위치. 베이스 이미지 한 변을 10000으로 본 정수 비율(0~10000). 미지정 시 null. + 문구 영역 왼쪽 위 모서리의 세로 위치(0~10000). """ - posY: Int + posY: Int! """ - 문구 영역 너비. 베이스 이미지 한 변을 10000으로 본 정수 비율(1~10000). 미지정 시 null. + 문구 영역 너비(1~10000, posX + width ≤ 10000). """ - width: Int + width: Int! """ - 문구 영역 높이. 베이스 이미지 한 변을 10000으로 본 정수 비율(1~10000). 미지정 시 null. + 문구 영역 높이(1~10000, posY + height ≤ 10000). """ - height: Int + height: Int! + """ + 글자색(#RRGGBB 대문자). + """ + textColor: String! + """ + 자리 안 글자 정렬. + """ + textAlign: CustomTextAlignType! } """ -상품 커스텀 템플릿. 베이스 이미지 위에 문구 슬롯을 올려 구매자가 문구를 넣게 한다. -상품당 1개다. +상품 커스텀 템플릿(슬롯형). 정사각 바탕 이미지 위에 문구 슬롯을 올려 구매자가 문구를 넣게 한다. +상품당 1개다. 구매자에게 열리는지는 템플릿이 아니라 SellerProduct.customMode(SLOT)로 정한다. """ type SellerCustomTemplate { id: ID! productId: ID! """ - 문구를 올릴 바탕 이미지 URL. + 문구를 올릴 바탕 이미지 URL(정사각). """ baseImageUrl: String! """ - 활성 여부. false면 구매자 화면에 커스텀 입력이 열리지 않는다. + 자유 편집(바탕 위 영역 지정 + 요청 문구·참고 사진) 허용 여부. """ - isActive: Boolean! + freeEditEnabled: Boolean! + """ + 설정 버전. 템플릿·문구 슬롯이 바뀔 때마다 1 오른다. + """ + revision: Int! """ 문구 슬롯. sortOrder 오름차순. """ @@ -4942,14 +7690,19 @@ type SellerProduct { """ currency: String! """ - 커스텀 도안의 바탕 이미지 URL. 커스텀을 쓰지 않으면 null. - """ - baseDesignImageUrl: String - """ 제작 소요 시간(분). 픽업 가능 시각 계산의 리드타임에 반영된다. """ preparationTimeMinutes: Int! """ + 커스텀 방식. 바꾸려면 sellerSetProductCustomMode. + """ + customMode: CustomModeType! + """ + 커스텀 방식별 준비 상태(NONE·SLOT·THREE_D 순). 준비 이슈가 있는 방식으로는 바꿀 수 없고, + 지금 방식에 이슈가 생기면 구매자 주문이 거절된다. + """ + customReadiness: [SellerCustomReadiness!]! + """ 노출 여부. false면 구매자 화면에 나오지 않는다. """ isActive: Boolean! @@ -4977,6 +7730,47 @@ type SellerProduct { updatedAt: DateTime! } +""" +커스텀 방식 하나의 준비 상태. +""" +type SellerCustomReadiness { + """ + 대상 커스텀 방식. + """ + mode: CustomModeType! + """ + issues가 비어 있으면 true. + """ + ready: Boolean! + """ + 준비 이슈. 판매자에게 그대로 보여 줄 메시지를 담는다. + """ + issues: [SellerCustomReadinessIssue!]! +} + +""" +커스텀 준비 이슈 1건. +""" +type SellerCustomReadinessIssue { + """ + 이슈 코드. 값이 늘 수 있어 문자열이다. + 슬롯형: SLOT_TEMPLATE_MISSING(바탕 없음), SLOT_NOTHING_TO_EDIT(문구 자리 0개이고 자유 편집 꺼짐). + 3D: THREE_D_GROUP_MISSING(모양·크기 그룹 없음), THREE_D_GROUP_DUPLICATED(같은 카테고리 그룹이 둘 이상), + THREE_D_GROUP_MIXED(한 그룹에 카테고리가 섞였거나 3D 항목 미지정 선택지가 있음), + THREE_D_GROUP_NOT_SINGLE_SELECT(모양·크기는 필수·1개 선택, 맛·디자인은 최대 1개 선택이 아님), + THREE_D_KEY_DUPLICATED(같은 키가 둘 이상), THREE_D_KEY_UNAVAILABLE(카탈로그에 없거나 퇴역한 키). + """ + code: String! + """ + 판매자에게 보여 줄 안내 문장. + """ + message: String! + """ + 이슈가 걸린 옵션 그룹. 그룹과 무관하면 null. + """ + optionGroupId: ID +} + """ 상품 목록 페이지. 최신 등록이 먼저 온다. """ @@ -5059,10 +7853,6 @@ input SellerCreateProductInput { """ currency: String = "KRW" """ - 커스텀 도안의 바탕 이미지 URL. sellerCreateUploadUrl(PRODUCT_IMAGE)로 이 계정에 발급된 publicUrl만 허용, 아니면 BAD_USER_INPUT. - """ - baseDesignImageUrl: String - """ 제작 소요 시간(분). 기본 180. """ preparationTimeMinutes: Int = 180 @@ -5102,10 +7892,6 @@ input SellerUpdateProductInput { """ currency: String """ - 커스텀 도안의 바탕 이미지 URL. sellerCreateUploadUrl(PRODUCT_IMAGE)로 이 계정에 발급된 publicUrl만 허용, 아니면 BAD_USER_INPUT. - """ - baseDesignImageUrl: String - """ 제작 소요 시간(분). """ preparationTimeMinutes: Int @@ -5224,14 +8010,6 @@ input SellerCreateOptionGroupInput { """ maxSelect: Int = 1 """ - 구매자 커스텀 입력(설명)이 필요한 그룹으로 표시한다. 기본 false. 현재는 켜면 해당 옵션 주문이 거절된다. - """ - optionRequiresDescription: Boolean = false - """ - 구매자 커스텀 입력(이미지)이 필요한 그룹으로 표시한다. 기본 false. 현재는 켜면 해당 옵션 주문이 거절된다. - """ - optionRequiresImage: Boolean = false - """ 노출 순서. 오름차순이고 동률의 순서는 보장하지 않는다. 미지정 시 0. """ sortOrder: Int @@ -5267,14 +8045,6 @@ input SellerUpdateOptionGroupInput { """ maxSelect: Int """ - 구매자 커스텀 입력(설명)이 필요한 그룹으로 표시한다. 현재는 켜면 해당 옵션 주문이 거절된다. - """ - optionRequiresDescription: Boolean - """ - 구매자 커스텀 입력(이미지)이 필요한 그룹으로 표시한다. 현재는 켜면 해당 옵션 주문이 거절된다. - """ - optionRequiresImage: Boolean - """ 노출 순서. """ sortOrder: Int @@ -5325,6 +8095,11 @@ input SellerCreateOptionItemInput { 노출 여부. 기본 true. """ isActive: Boolean = true + """ + 3D 카탈로그 선택지 키(customThreeDCatalog.optionChoices.key, 40자 이하). 생략하거나 빈 문자열이면 연결하지 않는다. + 카탈로그에 없거나 퇴역한 키도 저장되지만 3D 준비 이슈(THREE_D_KEY_UNAVAILABLE)가 되어 3D 주문을 받을 수 없다. + """ + threeDKey: String } """ @@ -5356,6 +8131,10 @@ input SellerUpdateOptionItemInput { 노출 여부. """ isActive: Boolean + """ + 3D 카탈로그 선택지 키(40자 이하). null이나 빈 문자열이면 연결을 끊고, 생략하면 그대로 둔다. + """ + threeDKey: String } """ @@ -5376,24 +8155,13 @@ input SellerReorderOptionItemsInput { input SellerUpsertProductCustomTemplateInput { productId: ID! """ - 문구를 올릴 바탕 이미지 URL. sellerCreateUploadUrl(PRODUCT_IMAGE)로 이 계정에 발급된 publicUrl만 허용, 아니면 BAD_USER_INPUT. + 문구를 올릴 바탕 이미지 URL(정사각). sellerCreateUploadUrl(PRODUCT_IMAGE)로 이 계정에 발급된 publicUrl만 허용, 아니면 INVALID_IMAGE_URL. """ baseImageUrl: String! """ - 활성 여부. 기본 true. - """ - isActive: Boolean = true -} - -""" -커스텀 템플릿 활성 상태 변경 입력. -""" -input SellerSetProductCustomTemplateActiveInput { - templateId: ID! - """ - true면 구매자 화면에 커스텀 입력이 열린다. + 자유 편집 허용 여부. 생략하면 새 템플릿은 false, 기존 템플릿은 지금 값을 둔다. """ - isActive: Boolean! + freeEditEnabled: Boolean } """ @@ -5406,17 +8174,21 @@ input SellerUpsertProductCustomTextTokenInput { tokenId: ID templateId: ID! """ - 슬롯 식별 키. 주문 스냅샷에 그대로 남는다. + 슬롯 식별 키. 영문 소문자·숫자 1~60자(이 규칙 전에 만든 키는 바꾸지 않는 한 그대로 쓸 수 있다). 주문 스냅샷에 그대로 남는다. """ tokenKey: String! """ - 구매자가 입력하지 않았을 때 쓸 기본 문구. + 표시 이름(1~30자). 생략하면 수정은 지금 값을 두고, 등록은 tokenKey 앞 30자로 채운다. + """ + label: String + """ + 구매자가 입력하지 않았을 때 쓸 기본 문구. maxLength 이하(코드 포인트). """ defaultText: String! """ - 입력 가능한 최대 글자 수. 기본 30. + 입력 가능한 최대 글자 수(코드 포인트, 1~50). 기본 20. """ - maxLength: Int = 30 + maxLength: Int = 20 """ 입력 화면 노출 순서. 오름차순이고 동률의 순서는 보장하지 않는다. 미지정 시 0. """ @@ -5426,22 +8198,29 @@ input SellerUpsertProductCustomTextTokenInput { """ isRequired: Boolean = true """ - 문구 영역 왼쪽 위 모서리의 가로 위치. 베이스 이미지 한 변을 10000으로 본 정수 비율(0~10000)이고 서버는 범위를 검사하지 않는다. - 생략 시 배치를 클라이언트가 정한다. + 문구 영역 왼쪽 위 모서리의 가로 위치. 바탕 이미지 한 변을 10000으로 본 정수 비율(0~10000), 원점은 왼쪽 위. + """ + posX: Int! + """ + 문구 영역 왼쪽 위 모서리의 세로 위치(0~10000). """ - posX: Int + posY: Int! """ - 문구 영역 왼쪽 위 모서리의 세로 위치. 베이스 이미지 한 변을 10000으로 본 정수 비율(0~10000). + 문구 영역 너비(1 이상, posX + width ≤ 10000). """ - posY: Int + width: Int! """ - 문구 영역 너비. 베이스 이미지 한 변을 10000으로 본 정수 비율(1~10000). + 문구 영역 높이(1 이상, posY + height ≤ 10000). """ - width: Int + height: Int! """ - 문구 영역 높이. 베이스 이미지 한 변을 10000으로 본 정수 비율(1~10000). + 글자색 #RRGGBB(대소문자 무관, 대문자로 저장). 생략하면 수정은 지금 값을 두고, 등록은 #000000. """ - height: Int + textColor: String + """ + 자리 안 글자 정렬. 생략하면 수정은 지금 값을 두고, 등록은 CENTER. + """ + textAlign: CustomTextAlignType } """ @@ -5528,7 +8307,8 @@ type StoreProduct { # ---- src/features/product/product-upload.types.graphql ---- """ 업로드 용도. 용도마다 저장 경로가 다르고, 저장 입력은 같은 용도로 발급된 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 { """ @@ -5543,6 +8323,10 @@ enum UploadPurpose { 플랫폼 배너 이미지(관리자). """ BANNER_IMAGE + """ + 채팅 첨부 이미지(판매자). sellerSendConversationMessage의 IMAGE 메시지가 이 용도 URL만 받는다. + """ + CONVERSATION_IMAGE } # ---- src/features/product/product.types.graphql ---- @@ -5619,6 +8403,44 @@ enum BannerPlacement { STORE } +""" +상품의 커스텀 방식. 방식이 있는 상품은 구매자가 꾸민 내용 없이 주문할 수 없다. +""" +enum CustomModeType { + """커스텀 없음. 옵션만 고르고 주문한다.""" + NONE + """슬롯형. 판매자가 정한 바탕 이미지 위 문구 자리에 문구를 넣는다(자유 편집은 상품별 선택).""" + SLOT + """3D. 모양·크기 등 옵션을 3D 케이크로 꾸민다. 자유 편집은 없다.""" + THREE_D +} + +""" +문구 자리 안 글자 정렬. +""" +enum CustomTextAlignType { + """왼쪽 정렬.""" + LEFT + """가운데 정렬.""" + CENTER + """오른쪽 정렬.""" + RIGHT +} + +""" +3D 옵션 카테고리. 옵션 항목의 threeDKey가 가리키는 카탈로그 선택지의 종류다. +""" +enum ThreeDOptionCategoryType { + """케이크 크기. 3D 상품은 필수 단일 선택 그룹이 있어야 한다.""" + SIZE + """시트·크림 맛. 고르지 않아도 되는 그룹으로 둘 수 있다.""" + FLAVOR + """시트 모양. 3D 상품은 필수 단일 선택 그룹이 있어야 한다.""" + SHAPE + """시트 디자인. 고르지 않으면 장식 없는 시트로 그린다.""" + DESIGN +} + # ---- src/features/region/region-admin.graphql ---- extend type Query { """ @@ -7741,12 +10563,22 @@ extend type Query { storeId: ID! """대상 연월. "YYYY-MM" 형식(KST 기준). 예: "2026-09". 형식이 어긋나면 BAD_USER_INPUT.""" yearMonth: String! + """ + 주문할 상품 ID. 주면 매장 리드타임과 상품 제작 시간 중 긴 쪽을 픽업 하한으로 쓴다(createOrder와 같은 판정). + 그 매장의 판매 중 상품이 아니면 PRODUCT_NOT_FOUND. + """ + productId: ID ): PickupCalendar! """매장별 선택 날짜의 픽업 시간 슬롯. date: "YYYY-MM-DD" """ pickupTimeSlots( storeId: ID! """대상 날짜. "YYYY-MM-DD" 형식(KST 기준). 예: "2026-09-10". 형식이 어긋나면 BAD_USER_INPUT.""" date: String! + """ + 주문할 상품 ID. 주면 매장 리드타임과 상품 제작 시간 중 긴 쪽을 픽업 하한으로 쓴다(createOrder와 같은 판정). + 그 매장의 판매 중 상품이 아니면 PRODUCT_NOT_FOUND. + """ + productId: ID ): PickupTimeSlots! } @@ -7758,13 +10590,13 @@ type PickupCalendar { days: [PickupDay!]! } -"""매장 달력의 하루. 매장 영업요일·특별휴무·일별 생산 수량이 모두 반영된 결과다.""" +"""매장 달력의 하루. 매장 영업요일·특별휴무·일별 생산 수량·픽업 하한(리드타임, productId를 주면 상품 제작 시간 중 긴 쪽)이 모두 반영된 결과다.""" type PickupDay { """날짜. "YYYY-MM-DD" (KST).""" date: String! """픽업 예약 가능 여부.""" selectable: Boolean! - """선택 불가 사유. PAST | OUT_OF_RANGE | CLOSED(휴무·영업요일 아님·당일 잔여 슬롯 없음) | CAPACITY_FULL. 선택 가능 시 null.""" + """선택 불가 사유. PAST | OUT_OF_RANGE | CLOSED(휴무·영업요일 아님·픽업 하한 이후 그날 잔여 슬롯 없음) | CAPACITY_FULL. 선택 가능 시 null.""" reason: String } @@ -7782,14 +10614,73 @@ type PickupTimeSlots { type PickupSlot { """슬롯 시각. "HH:mm" (KST).""" time: String! - """예약 가능 여부. 매장 리드타임·영업시간·잔여 수량을 반영한 값이다.""" + """예약 가능 여부. 매장 리드타임(productId를 주면 상품 제작 시간 포함)·영업시간·잔여 수량을 반영한 값이다.""" available: Boolean! } +# ---- src/features/store/store-pickup-stores.graphql ---- +extend type Query { + """매장 선택(메인 검색 결과). 픽업 날짜·시간에 예약 가능한 매장을 요청한 정렬로 돌려준다. 비로그인 접근 가능.""" + pickupStores(input: PickupStoresInput!): PickupStoreConnection! +} + +"""매장 선택 조회 조건. 커서가 아니라 오프셋 방식이다.""" +input PickupStoresInput { + """픽업 날짜. "YYYY-MM-DD"(KST). 형식이 어긋나면 INVALID_DATE, 오늘보다 앞서면 PICKUP_DATE_PAST.""" + date: String! + """픽업 시각. "HH:mm"(KST). 그 슬롯이 예약 가능한 매장만 남긴다. 생략·null이면 그날 예약 가능한 슬롯이 하나라도 있는 매장. 형식이 어긋나면 INVALID_TIME_VALUE.""" + time: String + """2차 시군구 ID 다중 선택. 비우면 전국 대상.""" + regionIds: [ID!] + """정렬 기준. 기본 인기순.""" + sort: StoreSort = POPULAR + """건너뛸 개수. 기본 0.""" + offset: Int = 0 + """조회 개수(최대 50).""" + limit: Int = 20 +} + +"""매장 선택 결과 목록.""" +type PickupStoreConnection { + """매장 항목. 요청한 sort 순서로 온다.""" + items: [PickupStoreItem!]! + """조건에 맞는 전체 매장 수.""" + totalCount: Int! + """다음 페이지 존재 여부.""" + hasMore: Boolean! + """ + 선택한 지역들의 중심 좌표를 모두 담는 범위(지도 카메라용). 매장이 0건이어도 온다. 지역이 하나면 한 점(south=north, west=east)이다. + regionIds를 비웠거나(전국) 좌표가 등록된 2차 지역이 없으면 null. + """ + regionBounds: MapBounds +} + +"""지도 범위(WGS84).""" +type MapBounds { + """남쪽 끝 위도.""" + south: Float! + """서쪽 끝 경도.""" + west: Float! + """북쪽 끝 위도.""" + north: Float! + """동쪽 끝 경도.""" + east: Float! +} + +"""매장 선택 항목. 매장 카드와 지도 마커 좌표.""" +type PickupStoreItem { + """매장 카드.""" + store: StoreCard! + """위도(지도 마커). 미설정 시 null.""" + latitude: Float + """경도(지도 마커). 미설정 시 null.""" + longitude: Float +} + # ---- src/features/store/store-search.graphql ---- extend type Query { """ - 매장 검색(검색 결과 매장 탭). 매장명에 단어별 AND 부분일치, 인기순 고정. keyword를 생략하면 지역 조건만 적용한다. 비로그인 접근 가능. + 매장 검색(검색 결과 매장 탭). 매장명에 단어별 AND 부분일치. keyword를 생략하면 지역 조건만 적용한다. 비로그인 접근 가능. """ searchStores(input: SearchStoresInput!): SearchStoreConnection! } @@ -7800,6 +10691,8 @@ input SearchStoresInput { keyword: String """2차 시군구 ID 다중 선택. 비우면 전국 대상.""" regionIds: [ID!] + """정렬 기준. 기본 인기순.""" + sort: StoreSort = POPULAR """건너뛸 개수. 기본 0.""" offset: Int = 0 """조회 개수(최대 50).""" @@ -7808,7 +10701,7 @@ input SearchStoresInput { """매장 검색 결과 목록.""" type SearchStoreConnection { - """매장 카드. 인기순으로 온다 — 찜 수·리뷰 통계·최근 주문 수로 산출하며 검색어 관련도는 반영하지 않는다.""" + """매장 카드. 요청한 sort 순서로 온다. 검색어 관련도는 반영하지 않는다.""" items: [StoreCard!]! """조건에 맞는 전체 매장 수. 탭 카운트에 쓴다.""" totalCount: Int! @@ -7825,7 +10718,7 @@ extend type Query { } """ -판매자 조작 감사 로그 1건. 매장 설정·상품·주문 변경 이력을 남긴다. +내 매장 감사 로그 1건. 매장 설정·상품·주문·정산 계좌 변경 이력을 남기며, 관리자가 이 매장에 한 조작(대리 수정·주문 취소 등)도 포함한다. 로그는 누적만 되고 수정·삭제되지 않는다. """ type SellerAuditLog { @@ -8325,6 +11218,16 @@ type StoreCard { isWishlisted: Boolean! } +"""매장 목록 정렬. 시안 '추천순' 라벨은 POPULAR(기본)로 해석한다.""" +enum StoreSort { + """인기순(최근 30일 주문 수·찜 수·베이지안 평점 — 인기 매장과 동일 산식).""" + POPULAR + """등록순(최신 등록 매장 우선).""" + LATEST + """판매순(최근 30일 유효 주문 수량 합).""" + BEST_SELLING +} + """매장 지도 연동 provider. 구매자·판매자 API가 공용으로 쓴다.""" enum StoreMapProvider { """네이버 지도 딥링크를 쓴다.""" diff --git a/src/features/audit-logs/meta.spec.ts b/src/features/audit-logs/meta.spec.ts index 1b76487..e16a8e8 100644 --- a/src/features/audit-logs/meta.spec.ts +++ b/src/features/audit-logs/meta.spec.ts @@ -142,6 +142,24 @@ describe('감사 대상 유형 라벨', () => { expect(targetLabel(value)).not.toBe(value); }); + it.each([ + ['PAYMENT_SETTING', '결제 설정'], + ['SETTLEMENT_ACCOUNT', '정산 계좌'], + ['SETTLEMENT', '정산'], + ['REFUND', '환불'], + ['DEPOSIT_RECORD', '입금 기록'], + ])('결제·정산 대상 %s의 라벨: %s', (value, label) => { + expect(targetLabel(value)).toBe(label); + }); + + it.each([['PAYOUT'], ['constructor'], ['']])( + '모르는 유형 %j는 원문으로 보이고 필터에는 나오지 않는다', + (value) => { + expect(targetLabel(value)).toBe(value); + expect(auditSearchSchema.parse({ targetType: value }).targetType).toBeUndefined(); + }, + ); + it('스키마에 없는 유형은 라벨 표에도 없다', () => { const known = new Set(schemaTargetTypes()); expect(TARGET_TYPES.map((t) => t.value).filter((v) => !known.has(v))).toEqual([]); diff --git a/src/features/audit-logs/meta.ts b/src/features/audit-logs/meta.ts index 0cb840d..ceeaf01 100644 --- a/src/features/audit-logs/meta.ts +++ b/src/features/audit-logs/meta.ts @@ -31,6 +31,11 @@ const TARGET_LABELS: Record = { REVIEW_REPORT: '신고', NOTIFICATION: '알림', CONVERSATION: '대화', + PAYMENT_SETTING: '결제 설정', + SETTLEMENT_ACCOUNT: '정산 계좌', + SETTLEMENT: '정산', + REFUND: '환불', + DEPOSIT_RECORD: '입금 기록', }; export const TARGET_TYPES = (Object.keys(TARGET_LABELS) as AuditTargetType[]).map((value) => ({ value, diff --git a/src/features/custom/components/color-swatch.tsx b/src/features/custom/components/color-swatch.tsx new file mode 100644 index 0000000..795b072 --- /dev/null +++ b/src/features/custom/components/color-swatch.tsx @@ -0,0 +1,16 @@ +const HEX = /^#[0-9A-Fa-f]{6}$/; + +/** 판매자가 고른 글자색 견본과 값. 형식이 어긋난 값은 견본 없이 글자만 보인다 */ +export function ColorSwatch({ color }: { color: string }) { + return ( + + + {color} + + ); +} diff --git a/src/features/custom/custom-geometry.spec.ts b/src/features/custom/custom-geometry.spec.ts new file mode 100644 index 0000000..5a83e5e --- /dev/null +++ b/src/features/custom/custom-geometry.spec.ts @@ -0,0 +1,62 @@ +import { areaToPercent, splitCustomImages } from './custom-geometry'; + +describe('areaToPercent', () => { + it.each([ + ['바탕 전체', [0, 0, 10000, 10000], ['0%', '0%', '100%', '100%']], + ['소수 둘째 자리', [1234, 5678, 100, 1], ['12.34%', '56.78%', '1%', '0.01%']], + ['오른쪽 아래 끝 1칸', [9999, 9999, 1, 1], ['99.99%', '99.99%', '0.01%', '0.01%']], + ['넘치는 크기는 바탕 끝까지', [5000, 2500, 6000, 9000], ['50%', '25%', '50%', '75%']], + ['범위 밖 시작점은 가장자리로', [-10, 12000, 100, 100], ['0%', '100%', '1%', '0%']], + ['음수 크기는 0', [100, 100, -5, -1], ['1%', '1%', '0%', '0%']], + ['숫자가 아니면 0', [Number.NaN, 0, Number.POSITIVE_INFINITY, 10], ['0%', '0%', '0%', '0.1%']], + ])('%s', (_, [posX, posY, width, height], [left, top, w, h]) => { + expect(areaToPercent({ posX: posX!, posY: posY!, width: width!, height: height! })).toEqual({ + left, + top, + width: w, + height: h, + }); + }); +}); + +const img = (kind: string) => ({ kind, imageUrl: `https://img.test/${kind}.png` }); +const kinds = (list: readonly { kind: string }[]) => list.map((i) => i.kind); + +describe('splitCustomImages', () => { + it('3D 5장은 받은 순서와 관계없이 윗면 → 앞·뒤·왼·오다', () => { + const r = splitCustomImages( + ['THREE_D_RIGHT', 'THREE_D_BACK', 'THREE_D_TOP', 'THREE_D_LEFT', 'THREE_D_FRONT'].map(img), + ); + expect(r.top?.kind).toBe('THREE_D_TOP'); + expect(kinds(r.sides)).toEqual([ + 'THREE_D_FRONT', + 'THREE_D_BACK', + 'THREE_D_LEFT', + 'THREE_D_RIGHT', + ]); + expect(r.composite).toBeNull(); + }); + + it('슬롯형 합성은 렌더와 따로 나온다', () => { + const r = splitCustomImages([img('SLOT_COMPOSITE')]); + expect(r).toEqual({ top: null, sides: [], composite: img('SLOT_COMPOSITE') }); + }); + + it('모르는 종류는 버리지 않고 옆면 뒤에 받은 순서대로 둔다', () => { + const r = splitCustomImages(['HOLOGRAM', 'THREE_D_LEFT', 'THREE_D_TOP', 'BOTTOM'].map(img)); + expect(r.top?.kind).toBe('THREE_D_TOP'); + expect(kinds(r.sides)).toEqual(['THREE_D_LEFT', 'HOLOGRAM', 'BOTTOM']); + }); + + it('윗면이 없으면 렌더는 전부 옆면 자리에 둔다', () => { + const r = splitCustomImages(['THREE_D_BACK', 'THREE_D_FRONT'].map(img)); + expect(r.top).toBeNull(); + expect(kinds(r.sides)).toEqual(['THREE_D_FRONT', 'THREE_D_BACK']); + }); + + it('이미지가 없으면 모두 비어 있고 입력 배열은 바꾸지 않는다', () => { + expect(splitCustomImages([])).toEqual({ top: null, sides: [], composite: null }); + const input = Object.freeze(['THREE_D_FRONT', 'THREE_D_TOP'].map(img)); + expect(() => splitCustomImages(input)).not.toThrow(); + }); +}); diff --git a/src/features/custom/custom-geometry.ts b/src/features/custom/custom-geometry.ts new file mode 100644 index 0000000..88f5fa5 --- /dev/null +++ b/src/features/custom/custom-geometry.ts @@ -0,0 +1,52 @@ +/** 커스텀 좌표는 바탕 이미지 한 변을 10000으로 본 정수 비율이고 원점은 왼쪽 위다 */ +const SCALE = 10000; + +interface Area { + posX: number; + posY: number; + width: number; + height: number; +} + +const clamp = (v: number, max: number) => Math.min(Math.max(Number.isFinite(v) ? v : 0, 0), max); +const percent = (v: number) => `${v / 100}%`; + +/** 바탕 위 영역을 CSS 백분율 위치로 바꾼다. 범위 밖 값은 바탕 안으로 자른다 */ +export function areaToPercent(a: Area) { + const left = clamp(a.posX, SCALE); + const top = clamp(a.posY, SCALE); + return { + left: percent(left), + top: percent(top), + width: percent(clamp(a.width, SCALE - left)), + height: percent(clamp(a.height, SCALE - top)), + }; +} + +const RENDER_ORDER: readonly string[] = [ + 'THREE_D_TOP', + 'THREE_D_FRONT', + 'THREE_D_BACK', + 'THREE_D_LEFT', + 'THREE_D_RIGHT', +]; + +/** + * 커스텀 이미지를 윗면 · 옆면(앞·뒤·왼·오) · 슬롯형 합성으로 나눈다. + * 모르는 종류는 버리지 않고 옆면 뒤에 받은 순서대로 둔다. + */ +export function splitCustomImages(images: readonly T[]) { + const rank = (kind: string) => { + const i = RENDER_ORDER.indexOf(kind); + return i === -1 ? RENDER_ORDER.length : i; + }; + const renders = images + .filter((i) => i.kind !== 'SLOT_COMPOSITE') + .sort((a, b) => rank(a.kind) - rank(b.kind)); + const top = renders[0]?.kind === 'THREE_D_TOP' ? renders[0] : null; + return { + top, + sides: top ? renders.slice(1) : renders, + composite: images.find((i) => i.kind === 'SLOT_COMPOSITE') ?? null, + }; +} diff --git a/src/features/custom/index.ts b/src/features/custom/index.ts new file mode 100644 index 0000000..a635b73 --- /dev/null +++ b/src/features/custom/index.ts @@ -0,0 +1,9 @@ +export { ColorSwatch } from './components/color-swatch'; +export { areaToPercent, splitCustomImages } from './custom-geometry'; +export { + customModeLabel, + imageKindLabel, + SLOT_TEXT_STATE_LABEL, + slotTextState, + textAlignLabel, +} from './meta'; diff --git a/src/features/custom/meta.spec.ts b/src/features/custom/meta.spec.ts new file mode 100644 index 0000000..e754154 --- /dev/null +++ b/src/features/custom/meta.spec.ts @@ -0,0 +1,77 @@ +import { buildSchema, isEnumType } from 'graphql'; + +// codegen이 읽는 SDL 스냅샷 원문. 손으로 적은 라벨 표와 대조하는 정답지다 +import sdl from '../../../schema/schema.graphql?raw'; + +import { + customModeLabel, + imageKindLabel, + SLOT_TEXT_STATE_LABEL, + slotTextState, + textAlignLabel, +} from './meta'; + +function enumValues(name: string): string[] { + const t = buildSchema(sdl).getType(name); + if (!isEnumType(t)) throw new Error(`${name} enum이 스키마에 없다`); + return t.getValues().map((v) => v.name); +} + +const TABLES = [ + ['CustomModeType', customModeLabel], + ['CustomTextAlignType', textAlignLabel], + ['CustomImageKindType', imageKindLabel], +] as const; + +describe('커스텀 enum 라벨', () => { + it.each(TABLES)('%s 값이 스키마에 있다(정답지가 비어 통과하지 않게)', (name) => { + expect(enumValues(name).length).toBeGreaterThanOrEqual(3); + }); + + it.each(TABLES.flatMap(([name, fn]) => enumValues(name).map((v) => [name, v, fn] as const)))( + '%s.%s는 원문이 아닌 한국어 라벨로 보인다', + (_, value, fn) => { + expect(fn(value)).not.toBe(value); + }, + ); + + it.each([['HOLOGRAM'], ['constructor'], ['toString'], ['']])( + '모르는 값 %j는 원문으로 보인다', + (value) => { + for (const [, fn] of TABLES) expect(fn(value)).toBe(value); + }, + ); + + it('대표 라벨', () => { + expect([customModeLabel('SLOT'), customModeLabel('THREE_D')]).toEqual(['슬롯형', '3D']); + expect(textAlignLabel('CENTER')).toBe('가운데'); + expect(imageKindLabel('THREE_D_TOP')).toBe('윗면'); + }); +}); + +describe('slotTextState', () => { + it.each([ + ['기본 문구 그대로', 'DEFAULT', '축하해', '축하해'], + [ + '기본 문구의 CRLF·앞뒤 공백은 저장 규칙대로 맞춰 본다', + 'DEFAULT', + ' 생일\r\n축하해 ', + '생일\n축하해', + ], + ['바꾼 문구', 'CHANGED', '축하해', '서연아 생일 축하해 🎂'], + ['줄바꿈만 다름', 'CHANGED', '생일 축하해', '생일\n축하해'], + ['선택 자리를 지움(null)', 'EMPTY', '축하해', null], + ['빈 문자열', 'EMPTY', '축하해', ''], + ['기본 문구가 비어 있고 입력도 없음', 'EMPTY', '', null], + ] as const)('%s → %s', (_, state, defaultText, valueText) => { + expect(slotTextState({ defaultText, valueText })).toBe(state); + }); + + it('상태마다 라벨이 있다', () => { + expect(SLOT_TEXT_STATE_LABEL).toEqual({ + DEFAULT: '기본 그대로', + CHANGED: '바꿈', + EMPTY: '문구 없음', + }); + }); +}); diff --git a/src/features/custom/meta.ts b/src/features/custom/meta.ts new file mode 100644 index 0000000..c3f4145 --- /dev/null +++ b/src/features/custom/meta.ts @@ -0,0 +1,42 @@ +import { + type CustomImageKindType, + type CustomModeType, + type CustomTextAlignType, +} from '@/graphql/generated/graphql'; + +// Record라 codegen enum에 값이 늘면 tsc가 잡는다. 화면은 BE가 먼저 배포돼 모르는 값이 와도 원문으로 보인다 +const MODE: Record = { NONE: '없음', SLOT: '슬롯형', THREE_D: '3D' }; +const ALIGN: Record = { + LEFT: '왼쪽', + CENTER: '가운데', + RIGHT: '오른쪽', +}; +const IMAGE_KIND: Record = { + THREE_D_TOP: '윗면', + THREE_D_FRONT: '앞', + THREE_D_BACK: '뒤', + THREE_D_LEFT: '왼쪽', + THREE_D_RIGHT: '오른쪽', + SLOT_COMPOSITE: '합성 이미지', +}; + +/** 표에 있는 값만 라벨로 바꾼다. `constructor` 같은 프로토타입 키도 모르는 값이다 */ +const label = (table: Record, value: string) => + Object.hasOwn(table, value) ? table[value]! : value; + +export const customModeLabel = (v: string) => label(MODE, v); +export const textAlignLabel = (v: string) => label(ALIGN, v); +export const imageKindLabel = (v: string) => label(IMAGE_KIND, v); + +export type SlotTextState = 'DEFAULT' | 'CHANGED' | 'EMPTY'; +export const SLOT_TEXT_STATE_LABEL: Record = { + DEFAULT: '기본 그대로', + CHANGED: '바꿈', + EMPTY: '문구 없음', +}; + +/** BE는 문구를 CRLF→LF·trim해 저장하므로 기본 문구도 같은 규칙으로 맞춰 비교한다 */ +export function slotTextState(t: { defaultText: string; valueText: string | null }): SlotTextState { + if (t.valueText === null || t.valueText === '') return 'EMPTY'; + return t.valueText === t.defaultText.replaceAll('\r\n', '\n').trim() ? 'DEFAULT' : 'CHANGED'; +} diff --git a/src/features/orders/api/queries.ts b/src/features/orders/api/queries.ts index 95f7900..cb08804 100644 --- a/src/features/orders/api/queries.ts +++ b/src/features/orders/api/queries.ts @@ -33,6 +33,7 @@ const AdminOrdersDocument = graphql(/* GraphQL */ ` buyerPhone totalPrice createdAt + hasCustom } totalCount hasMore @@ -81,16 +82,34 @@ const AdminOrderDocument = graphql(/* GraphQL */ ` optionTitle priceDelta } + customMode + customPreviewImageUrl + customBaseImageUrl + customImages { + id + kind + imageUrl + } customTexts { id tokenKey + label defaultText valueText + posX + posY + width + height + textColor + textAlign sortOrder } freeEdits { id - cropImageUrl + posX + posY + width + height descriptionText sortOrder attachments { @@ -248,9 +267,11 @@ export function buyerNameQueryOptions(accountId: string) { }); } +/** 사유 코드 선택은 아직 없어 '기타' + 입력한 메모로 보낸다 */ export async function cancelOrder(queryClient: QueryClient, orderId: string, note: string) { - const result = (await gqlRequest(AdminCancelOrderDocument, { input: { orderId, note } })) - .adminCancelOrder; + const result = ( + await gqlRequest(AdminCancelOrderDocument, { input: { orderId, reason: 'OTHER', note } }) + ).adminCancelOrder; await Promise.all([ queryClient.invalidateQueries({ queryKey: ordersKeys.detail(orderId) }), queryClient.invalidateQueries({ queryKey: ordersKeys.lists() }), diff --git a/src/features/orders/components/cancel-order-dialog.tsx b/src/features/orders/components/cancel-order-dialog.tsx index 626706e..779b879 100644 --- a/src/features/orders/components/cancel-order-dialog.tsx +++ b/src/features/orders/components/cancel-order-dialog.tsx @@ -18,7 +18,7 @@ import { Textarea } from '@/shared/ui/textarea'; import { cancelOrder } from '../api/queries'; -const NOTE_MAX = 494; +const NOTE_MAX = 500; export function CancelOrderDialog({ orderId, @@ -59,8 +59,8 @@ export function CancelOrderDialog({ 주문을 취소할까요? - {orderNumber} 주문을 취소하면 구매자에게 취소 알림을 보냅니다. 사유는 상태 이력에 - "[관리자]"로 시작하는 메모로 남고, 취소한 주문은 되돌릴 수 없습니다. + {orderNumber} 주문을 취소하면 구매자에게 취소 알림을 보냅니다. 사유는 상태 이력과 감사 + 로그에 남고, 취소한 주문은 되돌릴 수 없습니다.
diff --git a/src/features/orders/components/order-detail-sections.tsx b/src/features/orders/components/order-detail-sections.tsx index 6c96c4e..1ca91c7 100644 --- a/src/features/orders/components/order-detail-sections.tsx +++ b/src/features/orders/components/order-detail-sections.tsx @@ -10,6 +10,7 @@ import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/sha import { storeNameQueryOptions } from '../api/queries'; import { ORDER_STATUS, orderStatusMeta } from '../status'; +import { OrderItemCustom } from './order-item-custom'; export type OrderDetail = AdminOrderQuery['adminOrder']; @@ -74,8 +75,6 @@ export function OrderProgress({ order }: { order: OrderDetail }) { ); } -type FreeEdit = OrderDetail['items'][number]['freeEdits'][number]; - /** 품목에는 매장명 스냅샷이 없어 현재 매장 이름을 불러 보인다. 못 불러오면 #ID */ function StoreLink({ storeId }: { storeId: string }) { const name = useQuery(storeNameQueryOptions(storeId)); @@ -90,52 +89,6 @@ function StoreLink({ storeId }: { storeId: string }) { ); } -const bySortOrder = (a: { sortOrder: number }, b: { sortOrder: number }) => - a.sortOrder - b.sortOrder; - -/** 자유 편집 1건: 편집 이미지, 요청 문구 전문, 첨부 이미지. 이미지는 새 탭에서 원본으로 연다 */ -function FreeEditRow({ edit }: { edit: FreeEdit }) { - const n = edit.sortOrder + 1; - const attachments = [...edit.attachments].sort(bySortOrder); - return ( -
  • - - {`자유 - -
    -
    -
    요청 문구
    -

    - {edit.descriptionText.trim() ? edit.descriptionText : '요청 문구가 없습니다.'} -

    -
    - {attachments.length > 0 && ( -
    -
    첨부 이미지 {attachments.length}장
    -
      - {attachments.map((a, i) => ( -
    • - - {`자유 - -
    • - ))} -
    -
    - )} -
    -
  • - ); -} - export function OrderItems({ order }: { order: OrderDetail }) { return ( @@ -180,23 +133,7 @@ export function OrderItems({ order }: { order: OrderDetail }) { ))}
    )} - {it.customTexts.length > 0 && ( -
    - {it.customTexts.map((c) => ( - - 문구 “{c.valueText}” - (기본 {c.defaultText}) - - ))} -
    - )} - {it.freeEdits.length > 0 && ( -
      - {it.freeEdits.map((f) => ( - - ))} -
    - )} +
    {formatKrw(it.itemSubtotalPrice)} diff --git a/src/features/orders/components/order-item-custom.tsx b/src/features/orders/components/order-item-custom.tsx new file mode 100644 index 0000000..d97632f --- /dev/null +++ b/src/features/orders/components/order-item-custom.tsx @@ -0,0 +1,215 @@ +import { + areaToPercent, + ColorSwatch, + customModeLabel, + imageKindLabel, + SLOT_TEXT_STATE_LABEL, + slotTextState, + splitCustomImages, + textAlignLabel, +} from '@/features/custom'; +import { type AdminOrderQuery } from '@/graphql/generated/graphql'; +import { cn } from '@/shared/lib/utils'; +import { Badge } from '@/shared/ui/badge'; +import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/shared/ui/table'; + +type Item = AdminOrderQuery['adminOrder']['items'][number]; +type CustomText = Item['customTexts'][number]; +type FreeEdit = Item['freeEdits'][number]; +type CustomImage = Item['customImages'][number]; + +const bySortOrder = (a: { sortOrder: number }, b: { sortOrder: number }) => + a.sortOrder - b.sortOrder; + +/** 품목의 커스텀 내용. 관리자 화면에는 렌더러가 없어 구매자가 올린 이미지와 주문 시점 스냅샷으로 확인한다 */ +export function OrderItemCustom({ item }: { item: Item }) { + const { top, sides, composite } = splitCustomImages(item.customImages); + // 슬롯형의 대표 이미지가 곧 합성 이미지다 + const compositeUrl = + composite?.imageUrl ?? (item.customMode === 'SLOT' ? item.customPreviewImageUrl : null); + const texts = [...item.customTexts].sort(bySortOrder); + const edits = [...item.freeEdits].sort(bySortOrder); + const hasRenders = top !== null || sides.length > 0; + const hasSlot = compositeUrl !== null || texts.length > 0; + if (item.customMode === 'NONE' && !hasRenders && !hasSlot && edits.length === 0) return null; + return ( +
    + + 커스텀{item.customMode === 'NONE' ? '' : ` · ${customModeLabel(item.customMode)}`} + + {hasRenders && } + {hasSlot && } + {edits.length > 0 && } +
    + ); +} + +/** 이미지를 새 탭에서 원본으로 연다. 아래 글자로 어느 면인지 보인다 */ +function ImageLink({ url, label, className }: { url: string; label: string; className: string }) { + return ( + + + {label} + + ); +} + +const renderLabel = (image: CustomImage) => `3D ${imageKindLabel(image.kind)}`; + +function RenderImages({ top, sides }: { top: CustomImage | null; sides: CustomImage[] }) { + return ( +
    +
    3D 렌더 이미지
    +
      + {top && ( +
    • + +
    • + )} + {sides.map((image) => ( +
    • + +
    • + ))} +
    +
    + ); +} + +function SlotTexts({ compositeUrl, texts }: { compositeUrl: string | null; texts: CustomText[] }) { + return ( +
    + {compositeUrl && } + {texts.length > 0 && ( +
    + + + + 문구 자리 + 입력 문구 + 기본 문구 대비 + 글자색 + 정렬 + + + + {texts.map((t) => { + const state = slotTextState(t); + return ( + + {t.label} + + {state === 'EMPTY' ? '—' : t.valueText} + + + {SLOT_TEXT_STATE_LABEL[state]} + {state === 'CHANGED' && ( + + 기본: {t.defaultText} + + )} + + + + + {textAlignLabel(t.textAlign)} + + ); + })} + +
    +
    + )} +
    + ); +} + +/** 바탕 위 번호 영역과 영역별 요청 문구·참고 사진. 영역 번호는 요청 순서다 */ +function FreeEdits({ baseImageUrl, edits }: { baseImageUrl: string | null; edits: FreeEdit[] }) { + return ( +
    +
    자유 편집 {edits.length}건
    +
    + {baseImageUrl && ( +
    + 바탕 이미지 + {edits.map((e, i) => ( + + + {i + 1} + + + ))} +
    + )} +
      + {edits.map((e, i) => ( + + ))} +
    +
    +
    + ); +} + +function FreeEditRow({ n, edit }: { n: number; edit: FreeEdit }) { + const photos = [...edit.attachments].sort(bySortOrder); + return ( +
  • + + {n} + +
    +
    +
    요청 문구
    +

    + {edit.descriptionText.trim() ? edit.descriptionText : '요청 문구가 없습니다.'} +

    +
    + {photos.length > 0 && ( +
    +
    참고 사진 {photos.length}장
    +
      + {photos.map((a, i) => ( +
    • + + {`자유 + +
    • + ))} +
    +
    + )} +
    +
  • + ); +} diff --git a/src/features/orders/components/orders-table.tsx b/src/features/orders/components/orders-table.tsx index 468a6fe..8a0de4d 100644 --- a/src/features/orders/components/orders-table.tsx +++ b/src/features/orders/components/orders-table.tsx @@ -4,6 +4,7 @@ import { type ColumnDef } from '@tanstack/react-table'; import { type AdminOrdersQuery } from '@/graphql/generated/graphql'; import { formatKrw } from '@/shared/lib/format'; import { formatKst } from '@/shared/lib/kst'; +import { Badge } from '@/shared/ui/badge'; import { DataTable } from '@/shared/ui/data-table'; import { OrderStatusPill } from './order-status-pill'; @@ -15,13 +16,16 @@ const columns: ColumnDef[] = [ accessorKey: 'orderNumber', header: '주문번호', cell: ({ row }) => ( - - {row.original.orderNumber} - + + + {row.original.orderNumber} + + {row.original.hasCustom && 커스텀} + ), }, { diff --git a/src/features/orders/pages/orders.spec.tsx b/src/features/orders/pages/orders.spec.tsx index 99ff6f6..89ef4c1 100644 --- a/src/features/orders/pages/orders.spec.tsx +++ b/src/features/orders/pages/orders.spec.tsx @@ -30,6 +30,7 @@ const row = (id: string, status = 'CONFIRMED') => ({ buyerPhone: '010-4321-1182', totalPrice: 48000, createdAt: '2026-09-27T02:20:00.000Z', + hasCustom: false, }); const LONG_REQUEST = '왼쪽 위에 강아지 얼굴을 크게 넣어 주세요.\n아래쪽에는 꽃 장식을 둘러 주시고, 글씨는 금색으로 부탁드립니다.'; @@ -62,19 +63,73 @@ const detail = { quantity: 1, itemSubtotalPrice: 48000, optionItems: [{ id: 'o1', groupName: '맛', optionTitle: '얼그레이', priceDelta: 3000 }], + customMode: 'SLOT', + customPreviewImageUrl: 'https://img.test/composite.png', + customBaseImageUrl: 'https://img.test/base.png', + customImages: [ + { id: 'm1', kind: 'SLOT_COMPOSITE', imageUrl: 'https://img.test/composite.png' }, + ], customTexts: [ + { + id: 'c3', + tokenKey: 'slot3', + label: '보내는 사람', + defaultText: '엄마가', + valueText: null, + posX: 0, + posY: 9000, + width: 10000, + height: 1000, + textColor: '#000000', + textAlign: 'RIGHT', + sortOrder: 2, + }, { id: 'c1', tokenKey: 'msg', + label: '메인 문구', defaultText: '축하해', valueText: '서연아 생일 축하해', + posX: 1000, + posY: 1000, + width: 8000, + height: 2000, + textColor: '#1D1D1D', + textAlign: 'CENTER', sortOrder: 0, }, + { + id: 'c2', + tokenKey: 'slot2', + label: '날짜', + defaultText: '9.28', + valueText: '9.28', + posX: 1000, + posY: 4000, + width: 3000, + height: 1000, + textColor: '#FF5A5F', + textAlign: 'LEFT', + sortOrder: 1, + }, ], freeEdits: [ + { + id: 'f2', + posX: 6000, + posY: 5000, + width: 2500, + height: 2500, + descriptionText: '리본 그려 주세요', + sortOrder: 1, + attachments: [], + }, { id: 'f1', - cropImageUrl: 'https://img.test/crop.png', + posX: 1234, + posY: 5678, + width: 3000, + height: 1000, descriptionText: LONG_REQUEST, sortOrder: 0, attachments: [ @@ -279,6 +334,24 @@ describe('주문 목록', () => { else expect(link).toHaveAttribute('href', href); }); + it('커스텀 주문만 주문번호 옆에 커스텀 배지를 단다', async () => { + server.use( + gqlOk('AdminOrders', { + adminOrders: { + items: [{ ...row('1'), hasCustom: true }, row('2')], + totalCount: 2, + hasMore: false, + nextCursor: null, + }, + }), + ); + boot('/orders'); + const custom = (await screen.findByRole('link', { name: 'CQ-2609-1' })).closest('td')!; + expect(within(custom).getByText('커스텀')).toBeInTheDocument(); + const plain = screen.getByRole('link', { name: 'CQ-2609-2' }).closest('td')!; + expect(within(plain).queryByText('커스텀')).not.toBeInTheDocument(); + }); + it('날짜 칸 제목은 주문일이고 CONFIRMED는 주문 확정으로 보인다', async () => { server.use( gqlOk('AdminOrders', { @@ -477,7 +550,9 @@ describe('주문 상세', () => { expect(confirm).toBeDisabled(); await userEvent.type(within(dialog).getByLabelText('취소 사유 (필수)'), ' 재고 없음 '); await userEvent.click(confirm); - await vi.waitFor(() => expect(cancelInput).toEqual({ orderId: '1', note: '재고 없음' })); + await vi.waitFor(() => + expect(cancelInput).toEqual({ orderId: '1', reason: 'OTHER', note: '재고 없음' }), + ); await vi.waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument()); expect(await screen.findByText(/취소됨/)).toBeInTheDocument(); expect(screen.queryByRole('button', { name: '주문 취소' })).not.toBeInTheDocument(); @@ -535,16 +610,57 @@ describe('주문 상세', () => { ); }); - it('자유 편집의 요청 문구는 전문을, 첨부 이미지는 순서대로 새 탭 링크 썸네일로 보인다', async () => { + it('슬롯형은 합성 이미지와 문구 자리 표(입력 문구·기본 대비·글자색·정렬)를 자리 순서로 보인다', async () => { server.use(gqlOk('AdminOrder', { adminOrder: detail })); boot('/orders/1'); - const request = await screen.findByText( + const custom = await screen.findByRole('region', { name: '커스텀 내용' }); + expect(within(custom).getByText('커스텀 · 슬롯형')).toBeInTheDocument(); + expect( + within(custom).getByRole('link', { name: '합성 이미지 원본 보기(새 탭)' }), + ).toHaveAttribute('href', 'https://img.test/composite.png'); + const rows = within(within(custom).getByRole('table', { name: '문구 자리' })) + .getAllByRole('row') + .map((r) => r.textContent); + expect(rows).toEqual([ + '문구 자리입력 문구기본 문구 대비글자색정렬', + '메인 문구서연아 생일 축하해바꿈기본: 축하해#1D1D1D가운데', + '날짜9.28기본 그대로#FF5A5F왼쪽', + '보내는 사람—문구 없음#000000오른쪽', + ]); + expect(within(custom).queryByRole('list', { name: '3D 렌더 이미지' })).not.toBeInTheDocument(); + }); + + it('자유 편집은 바탕 위 번호 영역과 요청 문구 전문·참고 사진을 요청 순서로 보인다', async () => { + server.use(gqlOk('AdminOrder', { adminOrder: detail })); + boot('/orders/1'); + const figure = await screen.findByRole('figure', { name: '바탕 위 자유 편집 영역' }); + expect(within(figure).getByRole('img', { name: '바탕 이미지' })).toHaveAttribute( + 'src', + 'https://img.test/base.png', + ); + const areas = [...figure.querySelectorAll('[data-area]')].map((a) => [ + a.textContent, + a.style.left, + a.style.top, + a.style.width, + a.style.height, + ]); + expect(areas).toEqual([ + ['1', '12.34%', '56.78%', '30%', '10%'], + ['2', '60%', '50%', '25%', '25%'], + ]); + + const first = screen.getByRole('listitem', { name: '자유 편집 1' }); + const request = within(first).getByText( (_, el) => el?.tagName === 'P' && el.textContent === LONG_REQUEST, ); expect(request.className).not.toContain('truncate'); expect(request).toHaveClass('whitespace-pre-wrap'); + expect(screen.getByRole('listitem', { name: '자유 편집 2' })).toHaveTextContent( + '리본 그려 주세요', + ); - const list = screen.getByRole('list', { name: '자유 편집 1 첨부 이미지' }); + const list = within(first).getByRole('list', { name: '자유 편집 1 참고 사진' }); const images = within(list).getAllByRole('img'); expect(images.map((i) => i.getAttribute('src'))).toEqual([ 'https://img.test/a.png', @@ -556,14 +672,11 @@ describe('주문 상세', () => { expect(link).toHaveAttribute('target', '_blank'); expect(link).toHaveAttribute('rel', 'noreferrer'); } - expect(screen.getByText('첨부 이미지 2장')).toBeInTheDocument(); - expect(screen.getByRole('img', { name: '자유 편집 1 이미지' }).closest('a')).toHaveAttribute( - 'href', - 'https://img.test/crop.png', - ); + expect(within(first).getByText('참고 사진 2장')).toBeInTheDocument(); + expect(screen.getByText('자유 편집 2건')).toBeInTheDocument(); }); - it('요청 문구가 비어 있으면 없다고 알리고 첨부가 없으면 첨부 목록을 두지 않는다', async () => { + it('요청 문구가 비어 있으면 없다고 알리고 참고 사진이 없으면 사진 목록을 두지 않는다', async () => { const item = detail.items[0]!; server.use( gqlOk('AdminOrder', { @@ -572,7 +685,7 @@ describe('주문 상세', () => { items: [ { ...item, - freeEdits: [{ ...item.freeEdits[0]!, descriptionText: ' ', attachments: [] }], + freeEdits: [{ ...item.freeEdits[1]!, descriptionText: ' ', attachments: [] }], }, ], }, @@ -580,7 +693,118 @@ describe('주문 상세', () => { ); boot('/orders/1'); expect(await screen.findByText('요청 문구가 없습니다.')).toBeInTheDocument(); - expect(screen.queryByRole('list', { name: /첨부 이미지/ })).not.toBeInTheDocument(); + expect(screen.queryByRole('list', { name: /참고 사진/ })).not.toBeInTheDocument(); + }); + + it('바탕 이미지가 없는 옛 주문은 영역 그림 없이 요청만 보인다', async () => { + const item = detail.items[0]!; + server.use( + gqlOk('AdminOrder', { + adminOrder: { ...detail, items: [{ ...item, customBaseImageUrl: null }] }, + }), + ); + boot('/orders/1'); + expect(await screen.findByRole('listitem', { name: '자유 편집 1' })).toBeInTheDocument(); + expect(screen.queryByRole('figure')).not.toBeInTheDocument(); + }); + + it('3D는 렌더 5장을 윗면 크게 → 앞·뒤·왼·오 순서로 보이고 문구 표는 없다', async () => { + const item = detail.items[0]!; + const render = (kind: string) => ({ + id: kind, + kind, + imageUrl: `https://img.test/${kind}.png`, + }); + server.use( + gqlOk('AdminOrder', { + adminOrder: { + ...detail, + items: [ + { + ...item, + customMode: 'THREE_D', + customPreviewImageUrl: 'https://img.test/THREE_D_TOP.png', + customBaseImageUrl: null, + customImages: [ + 'THREE_D_RIGHT', + 'THREE_D_LEFT', + 'THREE_D_TOP', + 'THREE_D_BACK', + 'THREE_D_FRONT', + ].map(render), + customTexts: [], + freeEdits: [], + }, + ], + }, + }), + ); + boot('/orders/1'); + const list = await screen.findByRole('list', { name: '3D 렌더 이미지' }); + const links = within(list).getAllByRole('link'); + expect(links.map((l) => l.getAttribute('aria-label'))).toEqual([ + '3D 윗면 원본 보기(새 탭)', + '3D 앞 원본 보기(새 탭)', + '3D 뒤 원본 보기(새 탭)', + '3D 왼쪽 원본 보기(새 탭)', + '3D 오른쪽 원본 보기(새 탭)', + ]); + expect(links.map((l) => l.getAttribute('href'))[0]).toBe('https://img.test/THREE_D_TOP.png'); + expect(links.map((l) => l.querySelector('img')!.classList.contains('size-40'))).toEqual([ + true, + false, + false, + false, + false, + ]); + const custom = screen.getByRole('region', { name: '커스텀 내용' }); + expect(within(custom).getByText('커스텀 · 3D')).toBeInTheDocument(); + expect(within(custom).queryByRole('table')).not.toBeInTheDocument(); + expect(within(custom).queryByText(/합성 이미지/)).not.toBeInTheDocument(); + }); + + it.each([ + ['슬롯형에 합성 이미지 기록이 없으면 대표 이미지를 합성으로', 'SLOT', '커스텀 · 슬롯형', true], + ['방식이 없는데 문구가 남은 품목은 방식 없이', 'NONE', '커스텀', false], + ] as const)('옛 주문: %s 보인다', async (_, customMode, badge, composite) => { + const item = detail.items[0]!; + server.use( + gqlOk('AdminOrder', { + adminOrder: { ...detail, items: [{ ...item, customMode, customImages: [] }] }, + }), + ); + boot('/orders/1'); + const custom = await screen.findByRole('region', { name: '커스텀 내용' }); + expect(within(custom).getByText(badge)).toBeInTheDocument(); + const link = within(custom).queryByRole('link', { name: '합성 이미지 원본 보기(새 탭)' }); + if (composite) expect(link).toHaveAttribute('href', 'https://img.test/composite.png'); + else expect(link).toBeNull(); + expect(within(custom).getByRole('table', { name: '문구 자리' })).toBeInTheDocument(); + }); + + it('커스텀이 없는 품목은 커스텀 내용을 두지 않는다', async () => { + const item = detail.items[0]!; + server.use( + gqlOk('AdminOrder', { + adminOrder: { + ...detail, + items: [ + { + ...item, + customMode: 'NONE', + customPreviewImageUrl: null, + customBaseImageUrl: null, + customImages: [], + customTexts: [], + freeEdits: [], + }, + ], + }, + }), + ); + boot('/orders/1'); + await screen.findByText('레터링 생크림 케이크'); + expect(screen.queryByRole('region', { name: '커스텀 내용' })).not.toBeInTheDocument(); }); it.each([ diff --git a/src/features/products/api/queries.ts b/src/features/products/api/queries.ts index aa7e32e..c2ab679 100644 --- a/src/features/products/api/queries.ts +++ b/src/features/products/api/queries.ts @@ -27,7 +27,7 @@ const AdminProductsDocument = graphql(/* GraphQL */ ` regularPrice salePrice currency - baseDesignImageUrl + thumbnailUrl isActive createdAt updatedAt @@ -50,7 +50,7 @@ const AdminProductDocument = graphql(/* GraphQL */ ` regularPrice salePrice currency - baseDesignImageUrl + customMode isActive createdAt updatedAt @@ -79,8 +79,6 @@ const AdminProductDocument = graphql(/* GraphQL */ ` isRequired minSelect maxSelect - optionRequiresDescription - optionRequiresImage sortOrder isActive optionItems { @@ -91,19 +89,23 @@ const AdminProductDocument = graphql(/* GraphQL */ ` priceDelta sortOrder isActive + threeDKey } } customTemplate { id baseImageUrl - isActive + freeEditEnabled textTokens { id tokenKey + label defaultText maxLength sortOrder isRequired + textColor + textAlign } } } diff --git a/src/features/products/components/product-custom-card.tsx b/src/features/products/components/product-custom-card.tsx new file mode 100644 index 0000000..08008f9 --- /dev/null +++ b/src/features/products/components/product-custom-card.tsx @@ -0,0 +1,103 @@ +import { ColorSwatch, customModeLabel, textAlignLabel } from '@/features/custom'; +import { type AdminProductQuery, type CustomModeType } from '@/graphql/generated/graphql'; +import { Card, CardContent, CardHeader, CardTitle } from '@/shared/ui/card'; +import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/shared/ui/table'; + +type Template = NonNullable; + +/** 커스텀 방식과 슬롯형 템플릿(바탕·자유 편집·문구 자리 스타일). 문구 자리 위치는 보이지 않는다 */ +export function ProductCustomCard({ + mode, + template, +}: { + mode: CustomModeType; + template: Template | null; +}) { + return ( + + + 커스텀 설정 + + +
    +
    커스텀 방식
    +
    {customModeLabel(mode)}
    + {template && ( + <> +
    자유 편집
    +
    {template.freeEditEnabled ? '허용' : '허용 안 함'}
    + + )} +
    + {mode === 'THREE_D' && ( +

    + 모양·크기·맛·디자인은 옵션 선택지의 3D 연결로 고릅니다. 3D 상품에는 자유 편집이 + 없습니다. +

    + )} + {template ? ( + + ) : ( + mode === 'SLOT' &&

    등록된 템플릿이 없습니다.

    + )} +
    +
    + ); +} + +function TemplateSection({ template, unused }: { template: Template; unused: boolean }) { + const tokens = [...template.textTokens].sort((a, b) => a.sortOrder - b.sortOrder); + return ( + <> + {unused && ( +

    + 커스텀 방식이 슬롯형이 아니라 이 템플릿은 구매자에게 보이지 않습니다. +

    + )} + + 템플릿 바탕 이미지 + + {tokens.length === 0 ? ( +

    문구 자리가 없습니다.

    + ) : ( +
    + + + + 문구 자리 + 기본 문구 + 최대 글자 수 + 필수 입력 + 글자색 + 정렬 + + + + {tokens.map((t) => ( + + + {t.label} + + {t.tokenKey} + + + {t.defaultText || '—'} + {t.maxLength}자 + {t.isRequired ? '필수' : '선택'} + + + + {textAlignLabel(t.textAlign)} + + ))} + +
    +
    + )} + + ); +} diff --git a/src/features/products/components/product-options-card.tsx b/src/features/products/components/product-options-card.tsx index 3d85d4a..80f30c5 100644 --- a/src/features/products/components/product-options-card.tsx +++ b/src/features/products/components/product-options-card.tsx @@ -1,4 +1,5 @@ import { type AdminProductQuery } from '@/graphql/generated/graphql'; +import { Badge } from '@/shared/ui/badge'; import { Card, CardContent, CardHeader, CardTitle } from '@/shared/ui/card'; import { StatusPill } from '@/shared/ui/status-pill'; @@ -81,6 +82,11 @@ function OptionGroupItem({ group: g }: { group: OptionGroup }) { {item.title} + {item.threeDKey && ( + + 3D {item.threeDKey} + + )} {!item.isActive && 숨김} {item.description && ( diff --git a/src/features/products/components/product-template-card.tsx b/src/features/products/components/product-template-card.tsx deleted file mode 100644 index 4d93a43..0000000 --- a/src/features/products/components/product-template-card.tsx +++ /dev/null @@ -1,72 +0,0 @@ -import { type AdminProductQuery } from '@/graphql/generated/graphql'; -import { Card, CardContent, CardHeader, CardTitle } from '@/shared/ui/card'; -import { StatusPill } from '@/shared/ui/status-pill'; -import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/shared/ui/table'; - -type Template = NonNullable; - -/** 케이크 문구 커스텀 템플릿 요약. 바탕 이미지와 문구 칸 구성만 보이고 위치는 보이지 않는다 */ -export function ProductTemplateCard({ template }: { template: Template | null | undefined }) { - return ( - - - 문구 커스텀 템플릿 - - - {!template ? ( -

    등록된 템플릿이 없습니다.

    - ) : ( - <> -
    - - 템플릿 바탕 이미지 - -
    - - {template.isActive ? '사용 중' : '사용 안 함'} - - - {template.isActive - ? '구매자가 이 템플릿에 문구를 입력할 수 있습니다.' - : '구매자 화면에 문구 입력이 열리지 않습니다.'} - -
    -
    - {template.textTokens.length === 0 ? ( -

    문구 칸이 없습니다.

    - ) : ( -
    - - - - 문구 칸 이름 - 기본 문구 - 최대 글자 수 - 필수 입력 - - - - {template.textTokens.map((t) => ( - - {t.tokenKey} - - {t.defaultText || '—'} - - {t.maxLength}자 - {t.isRequired ? '필수' : '선택'} - - ))} - -
    -
    - )} - - )} -
    -
    - ); -} diff --git a/src/features/products/components/products-table.tsx b/src/features/products/components/products-table.tsx index e63ea9c..2d1bb42 100644 --- a/src/features/products/components/products-table.tsx +++ b/src/features/products/components/products-table.tsx @@ -16,8 +16,8 @@ const columns: ColumnDef[] = [ cell: ({ row }) => ( - {row.original.baseDesignImageUrl && ( - + {row.original.thumbnailUrl && ( + )} [0]> = {}) => isRequired: true, minSelect: 1, maxSelect: 1, - optionRequiresDescription: false, - optionRequiresImage: false, optionItems: items(true), ...over, }); @@ -32,34 +30,11 @@ describe('optionGroupWarnings', () => { ['필수지만 최소 0개·선택지 없음', group({ minSelect: 0, optionItems: [] }), []], ['선택 그룹·선택지 없음', group({ isRequired: false, optionItems: [] }), []], ['숨긴 필수 그룹·선택지 없음', group({ isActive: false, optionItems: [] }), []], - ['숨긴 그룹·설명 입력 필요', group({ isActive: false, optionRequiresDescription: true }), []], - ['필수·설명 입력 필요', group({ optionRequiresDescription: true }), ['설명 입력 필요!']], - ['필수·이미지 입력 필요', group({ optionRequiresImage: true }), ['이미지 입력 필요!']], - [ - '필수·설명과 이미지 입력 필요', - group({ optionRequiresDescription: true, optionRequiresImage: true }), - ['설명·이미지 입력 필요!'], - ], - [ - '필수 최소 0개·설명 입력 필요', - group({ minSelect: 0, optionRequiresDescription: true }), - ['설명 입력 필요'], - ], - [ - '선택 그룹·이미지 입력 필요', - group({ isRequired: false, optionRequiresImage: true }), - ['이미지 입력 필요'], - ], - [ - '필수·선택지 없음·설명 입력 필요', - group({ optionItems: [], optionRequiresDescription: true }), - ['주문 불가!', '설명 입력 필요!'], - ], ])('%s → %j', (_, g, expected) => { expect(summary(g)).toEqual(expected); }); - it('사유는 노출 선택지 수와 최소 개수를 알리고 조사를 맞춘다', () => { + it('사유는 노출 선택지 수와 최소 개수를 알린다', () => { expect(optionGroupWarnings(group({ optionItems: [] }))[0]?.reason).toBe( '필수 그룹에 노출 중인 선택지가 없어 구매자가 이 상품을 주문할 수 없습니다.', ); @@ -69,12 +44,6 @@ describe('optionGroupWarnings', () => { ).toBe( '필수 그룹에 노출 중인 선택지가 2개뿐이라 최소 3개를 고를 수 없습니다. 구매자가 이 상품을 주문할 수 없습니다.', ); - expect(optionGroupWarnings(group({ optionRequiresDescription: true }))[0]?.reason).toBe( - '구매자가 설명을 입력할 수 없어 이 그룹의 선택지를 고르면 주문이 거절됩니다. 필수 그룹이라 구매자가 이 상품을 주문할 수 없습니다.', - ); - expect( - optionGroupWarnings(group({ isRequired: false, optionRequiresImage: true }))[0]?.reason, - ).toBe('구매자가 이미지를 입력할 수 없어 이 그룹의 선택지를 고르면 주문이 거절됩니다.'); }); }); diff --git a/src/features/products/option-rules.ts b/src/features/products/option-rules.ts index a26f87a..3934edf 100644 --- a/src/features/products/option-rules.ts +++ b/src/features/products/option-rules.ts @@ -1,13 +1,10 @@ import { formatKrw } from '@/shared/lib/format'; -import { withJosa } from '@/shared/lib/josa'; interface OptionGroupLike { isActive: boolean; isRequired: boolean; minSelect: number; maxSelect: number; - optionRequiresDescription: boolean; - optionRequiresImage: boolean; optionItems: readonly { isActive: boolean }[]; } @@ -24,38 +21,21 @@ export interface OptionGroupWarning { * 주문 체크아웃이 거절하는 옵션 구성을 미리 알린다. 기준은 BE 체크아웃과 같다. * - 숨긴 그룹·선택지는 구매자에게 보이지 않고 체크아웃도 보지 않는다. * - 필수 그룹은 노출 선택지 중 최소 개수 이상을 골라야 한다. - * - 설명·이미지 입력이 필요한 그룹의 선택지를 고르면 거절된다(구매자 입력 기능이 아직 없다). */ export function optionGroupWarnings(group: OptionGroupLike): OptionGroupWarning[] { - if (!group.isActive) return []; - const warnings: OptionGroupWarning[] = []; + if (!group.isActive || !group.isRequired) return []; const visible = group.optionItems.filter((i) => i.isActive).length; - if (group.isRequired && visible < group.minSelect) { - warnings.push({ + if (visible >= group.minSelect) return []; + return [ + { label: '주문 불가', reason: visible === 0 ? '필수 그룹에 노출 중인 선택지가 없어 구매자가 이 상품을 주문할 수 없습니다.' : `필수 그룹에 노출 중인 선택지가 ${visible}개뿐이라 최소 ${group.minSelect}개를 고를 수 없습니다. 구매자가 이 상품을 주문할 수 없습니다.`, blocksOrder: true, - }); - } - const inputs = [ - group.optionRequiresDescription && '설명', - group.optionRequiresImage && '이미지', - ].filter((v) => v !== false); - if (inputs.length > 0) { - const mustPick = group.isRequired && group.minSelect > 0; - const what = inputs.join('·'); - warnings.push({ - label: `${what} 입력 필요`, - reason: mustPick - ? `구매자가 ${withJosa(what, '을/를')} 입력할 수 없어 이 그룹의 선택지를 고르면 주문이 거절됩니다. 필수 그룹이라 구매자가 이 상품을 주문할 수 없습니다.` - : `구매자가 ${withJosa(what, '을/를')} 입력할 수 없어 이 그룹의 선택지를 고르면 주문이 거절됩니다.`, - blocksOrder: mustPick, - }); - } - return warnings; + }, + ]; } /** 고를 수 있는 개수. 'n개 선택'·'최대 n개 선택'·'min~max개 선택' */ diff --git a/src/features/products/pages/product-detail-page.tsx b/src/features/products/pages/product-detail-page.tsx index 771d516..4046b8d 100644 --- a/src/features/products/pages/product-detail-page.tsx +++ b/src/features/products/pages/product-detail-page.tsx @@ -13,9 +13,9 @@ import { StatusPill } from '@/shared/ui/status-pill'; import { productDetailQueryOptions } from '../api/queries'; import { ProductActiveToggle } from '../components/product-active-toggle'; +import { ProductCustomCard } from '../components/product-custom-card'; import { ProductOptionsCard } from '../components/product-options-card'; import { ProductTaxonomyCard } from '../components/product-taxonomy-card'; -import { ProductTemplateCard } from '../components/product-template-card'; export function ProductDetailPage({ productId }: { productId: string }) { const q = useQuery(productDetailQueryOptions(productId)); @@ -113,7 +113,7 @@ export function ProductDetailPage({ productId }: { productId: string }) { - +
    diff --git a/src/features/products/pages/products.spec.tsx b/src/features/products/pages/products.spec.tsx index 4e909b5..70cbc42 100644 --- a/src/features/products/pages/products.spec.tsx +++ b/src/features/products/pages/products.spec.tsx @@ -4,7 +4,7 @@ import { HttpResponse, graphql } from 'msw'; import { App } from '@/app/app'; import { useAuthStore } from '@/features/auth'; -import { type AdminProductQuery } from '@/graphql/generated/graphql'; +import { type AdminProductQuery, type CustomModeType } from '@/graphql/generated/graphql'; import { forgetSearches } from '@/shared/lib/list-return'; import { gqlError, gqlOk, restOk } from '@/test/msw/graphql'; import { server } from '@/test/msw/server'; @@ -27,7 +27,8 @@ const product = (isActive = true) => ({ regularPrice: 45000, salePrice: 39000, currency: 'KRW', - baseDesignImageUrl: 'https://img.test/base.png', + thumbnailUrl: 'https://img.test/thumb.png' as string | null, + customMode: 'SLOT' as CustomModeType, isActive, createdAt: '2026-09-01T00:00:00.000Z', updatedAt: '2026-09-02T00:00:00.000Z', @@ -57,8 +58,6 @@ const group = (over: Partial): Group => ({ isRequired: true, minSelect: 1, maxSelect: 1, - optionRequiresDescription: false, - optionRequiresImage: false, sortOrder: 0, isActive: true, optionItems: [], @@ -73,6 +72,7 @@ const item = (over: Partial): Item => ({ priceDelta: 0, sortOrder: 0, isActive: true, + threeDKey: null, ...over, }); const RICH: Partial = { @@ -109,23 +109,36 @@ const RICH: Partial = { description: '사진은 주문 뒤 채팅으로 보내 주세요.', isRequired: false, minSelect: 0, - optionRequiresImage: true, - optionItems: [item({ id: '31', title: '사진 1장', priceDelta: 5000 })], + optionItems: [item({ id: '31', title: '사진 1장', priceDelta: 5000, threeDKey: 'heart' })], }), group({ id: '4', name: '초', isRequired: false, isActive: false }), ], customTemplate: { id: '5', baseImageUrl: 'https://img.test/tpl.png', - isActive: false, + freeEditEnabled: true, textTokens: [ + { + id: '2', + tokenKey: 'slot2', + label: '보내는 사람', + defaultText: '', + maxLength: 10, + sortOrder: 1, + isRequired: false, + textColor: 'not-a-color', + textAlign: 'RIGHT', + }, { id: '1', - tokenKey: '메인 문구', + tokenKey: 'slot1', + label: '메인 문구', defaultText: 'HAPPY BIRTHDAY', maxLength: 20, sortOrder: 0, isRequired: true, + textColor: '#FF5A5F', + textAlign: 'CENTER', }, ], }, @@ -151,11 +164,14 @@ describe('상품', () => { forgetSearches(); }); - it('목록: 판매가 첫 줄·정가 둘째 줄, 수정일 헤더', async () => { + it('목록: 대표 이미지 썸네일, 판매가 첫 줄·정가 둘째 줄, 수정일 헤더', async () => { server.use( gqlOk('AdminProducts', { adminProducts: { - items: [product(), { ...product(), id: '100', name: '생크림 케이크', salePrice: null }], + items: [ + product(), + { ...product(), id: '100', name: '생크림 케이크', salePrice: null, thumbnailUrl: null }, + ], totalCount: 2, hasMore: false, nextCursor: null, @@ -171,6 +187,8 @@ describe('상품', () => { expect(within(plain).getByText('45,000원').tagName).not.toBe('S'); expect(within(plain).queryByText(/정가/)).not.toBeInTheDocument(); expect(screen.getByRole('columnheader', { name: '수정일' })).toBeInTheDocument(); + expect(row.querySelector('img')).toHaveAttribute('src', 'https://img.test/thumb.png'); + expect(plain.querySelector('img')).toBeNull(); }); it('목록: 매장 필터는 이름으로 검색해 고르고, 주소로 들어온 매장은 이름으로 보인다', async () => { @@ -329,7 +347,7 @@ describe('상품', () => { expect(new URL(tag.getAttribute('href')!, 'http://x').searchParams.get('q')).toBe('비건'); }); - it('상세: 옵션 그룹은 규칙·선택지·가격 증감과 주문 불가 경고를 보인다', async () => { + it('상세: 옵션 그룹은 규칙·선택지·가격 증감·3D 연결 키와 주문 불가 경고를 보인다', async () => { server.use(gqlOk('AdminProduct', { adminProduct: detail(RICH) })); boot('/products/99'); expect(await screen.findByText('옵션 그룹 4개')).toBeInTheDocument(); @@ -365,11 +383,10 @@ describe('상품', () => { expect(within(photo).getByText('선택 사항')).toBeInTheDocument(); expect(within(photo).getByText('최대 1개 선택')).toBeInTheDocument(); expect(within(photo).getByText('사진은 주문 뒤 채팅으로 보내 주세요.')).toBeInTheDocument(); - expect( - within(photo).getByText('이미지 입력 필요').closest('[tabindex]'), - ).toHaveAccessibleDescription( - '구매자가 이미지를 입력할 수 없어 이 그룹의 선택지를 고르면 주문이 거절됩니다.', - ); + expect(within(photo).getAllByRole('listitem')[0]).toHaveTextContent('사진 1장3D heart+5,000원'); + expect(within(size).queryByText(/^3D /)).not.toBeInTheDocument(); + // 옵션 입력 플래그가 없어져 입력 필요 경고는 더 이상 없다 + expect(screen.queryByText(/입력 필요/)).not.toBeInTheDocument(); const candle = screen.getByRole('listitem', { name: '옵션 그룹 초' }); expect(within(candle).getByText('숨김')).toBeInTheDocument(); @@ -377,20 +394,71 @@ describe('상품', () => { expect(within(candle).queryByText('주문 불가')).not.toBeInTheDocument(); }); - it('상세: 문구 커스텀 템플릿은 바탕 이미지·사용 여부·문구 칸을 보인다', async () => { + it('상세: 커스텀 설정은 방식·자유 편집과 문구 자리 스타일을 순서대로 보인다', async () => { server.use(gqlOk('AdminProduct', { adminProduct: detail(RICH) })); boot('/products/99'); - const card = (await screen.findByText('문구 커스텀 템플릿')).closest( - '[data-slot=card]', - )!; + const card = (await screen.findByText('커스텀 설정')).closest('[data-slot=card]')!; + expect( + within(card) + .getAllByRole('term') + .map((t) => t.textContent), + ).toEqual(['커스텀 방식', '자유 편집']); + expect( + within(card) + .getAllByRole('definition') + .map((d) => d.textContent), + ).toEqual(['슬롯형', '허용']); expect(within(card).getByRole('img', { name: '템플릿 바탕 이미지' })).toHaveAttribute( 'src', 'https://img.test/tpl.png', ); - expect(within(card).getByText('사용 안 함')).toBeInTheDocument(); - const [header, row] = within(card).getAllByRole('row'); - expect(header).toHaveTextContent('문구 칸 이름기본 문구최대 글자 수필수 입력'); - expect(row).toHaveTextContent('메인 문구HAPPY BIRTHDAY20자필수'); + const [header, main, sender] = within(card).getAllByRole('row'); + expect(header).toHaveTextContent('문구 자리기본 문구최대 글자 수필수 입력글자색정렬'); + expect(main).toHaveTextContent('메인 문구slot1HAPPY BIRTHDAY20자필수#FF5A5F가운데'); + expect(sender).toHaveTextContent('보내는 사람slot2—10자선택not-a-color오른쪽'); + expect(main!.querySelector('[data-slot=color-swatch]')).toHaveStyle( + 'background-color: rgb(255, 90, 95)', + ); + expect(sender!.querySelector('[data-slot=color-swatch]')).not.toHaveAttribute('style'); + expect(within(card).queryByText(/구매자에게 보이지 않습니다/)).not.toBeInTheDocument(); + }); + + it.each([ + [ + '3D는 옵션 3D 연결 안내만 보인다', + 'THREE_D', + null, + ['3D'], + '모양·크기·맛·디자인은 옵션 선택지의 3D 연결로 고릅니다. 3D 상품에는 자유 편집이 없습니다.', + ], + [ + '슬롯형인데 템플릿이 없으면 없다고 알린다', + 'SLOT', + null, + ['슬롯형'], + '등록된 템플릿이 없습니다.', + ], + [ + '슬롯형이 아닌데 남은 템플릿은 구매자에게 보이지 않는다고 알린다', + 'NONE', + { ...RICH.customTemplate!, freeEditEnabled: false }, + ['없음', '허용 안 함'], + '커스텀 방식이 슬롯형이 아니라 이 템플릿은 구매자에게 보이지 않습니다.', + ], + ] as const)('상세: 커스텀 설정 — %s', async (_, customMode, customTemplate, defs, text) => { + server.use( + gqlOk('AdminProduct', { + adminProduct: detail({ product: { ...product(), customMode }, customTemplate }), + }), + ); + boot('/products/99'); + const card = (await screen.findByText('커스텀 설정')).closest('[data-slot=card]')!; + expect( + within(card) + .getAllByRole('definition') + .map((d) => d.textContent), + ).toEqual(defs); + expect(within(card).getByText(text)).toBeInTheDocument(); }); it('상세: 분류·옵션·템플릿이 없으면 없다고 알린다', async () => { diff --git a/src/graphql/generated/gql.ts b/src/graphql/generated/gql.ts index c8019d1..41b83d2 100644 --- a/src/graphql/generated/gql.ts +++ b/src/graphql/generated/gql.ts @@ -44,15 +44,15 @@ type Documents = { "\n mutation AdminSendNotification($input: AdminSendNotificationInput!) {\n adminSendNotification(input: $input) {\n sentCount\n skippedAccountIds\n broadcastId\n }\n }\n": typeof types.AdminSendNotificationDocument, "\n query AdminNotificationActiveUserCount {\n adminUsers(input: { status: ACTIVE, limit: 1 }) {\n totalCount\n }\n }\n": typeof types.AdminNotificationActiveUserCountDocument, "\n query AdminNotificationUserOptions($input: AdminUserListInput) {\n adminUsers(input: $input) {\n items {\n accountId\n nickname\n name\n email\n }\n }\n }\n": typeof types.AdminNotificationUserOptionsDocument, - "\n query AdminOrders($input: AdminOrderListInput) {\n adminOrders(input: $input) {\n items {\n id\n orderNumber\n accountId\n storeId\n storeName\n status\n pickupAt\n buyerName\n buyerPhone\n totalPrice\n createdAt\n }\n totalCount\n hasMore\n nextCursor\n }\n }\n": typeof types.AdminOrdersDocument, - "\n query AdminOrder($orderId: ID!) {\n adminOrder(orderId: $orderId) {\n id\n orderNumber\n buyer {\n accountId\n email\n nickname\n status\n }\n status\n pickupAt\n buyerName\n buyerPhone\n subtotalPrice\n discountPrice\n totalPrice\n submittedAt\n confirmedAt\n madeAt\n pickedUpAt\n canceledAt\n createdAt\n updatedAt\n items {\n id\n storeId\n productId\n productName\n regularPrice\n salePrice\n quantity\n itemSubtotalPrice\n optionItems {\n id\n groupName\n optionTitle\n priceDelta\n }\n customTexts {\n id\n tokenKey\n defaultText\n valueText\n sortOrder\n }\n freeEdits {\n id\n cropImageUrl\n descriptionText\n sortOrder\n attachments {\n id\n imageUrl\n sortOrder\n }\n }\n }\n statusHistories {\n id\n fromStatus\n toStatus\n changedAt\n note\n }\n }\n }\n": typeof types.AdminOrderDocument, + "\n query AdminOrders($input: AdminOrderListInput) {\n adminOrders(input: $input) {\n items {\n id\n orderNumber\n accountId\n storeId\n storeName\n status\n pickupAt\n buyerName\n buyerPhone\n totalPrice\n createdAt\n hasCustom\n }\n totalCount\n hasMore\n nextCursor\n }\n }\n": typeof types.AdminOrdersDocument, + "\n query AdminOrder($orderId: ID!) {\n adminOrder(orderId: $orderId) {\n id\n orderNumber\n buyer {\n accountId\n email\n nickname\n status\n }\n status\n pickupAt\n buyerName\n buyerPhone\n subtotalPrice\n discountPrice\n totalPrice\n submittedAt\n confirmedAt\n madeAt\n pickedUpAt\n canceledAt\n createdAt\n updatedAt\n items {\n id\n storeId\n productId\n productName\n regularPrice\n salePrice\n quantity\n itemSubtotalPrice\n optionItems {\n id\n groupName\n optionTitle\n priceDelta\n }\n customMode\n customPreviewImageUrl\n customBaseImageUrl\n customImages {\n id\n kind\n imageUrl\n }\n customTexts {\n id\n tokenKey\n label\n defaultText\n valueText\n posX\n posY\n width\n height\n textColor\n textAlign\n sortOrder\n }\n freeEdits {\n id\n posX\n posY\n width\n height\n descriptionText\n sortOrder\n attachments {\n id\n imageUrl\n sortOrder\n }\n }\n }\n statusHistories {\n id\n fromStatus\n toStatus\n changedAt\n note\n }\n }\n }\n": typeof types.AdminOrderDocument, "\n query AdminOrdersStoreOptions($input: AdminStoreListInput) {\n adminStores(input: $input) {\n items {\n id\n storeName\n isActive\n }\n }\n }\n": typeof types.AdminOrdersStoreOptionsDocument, "\n query AdminOrdersBuyerOptions($input: AdminUserListInput) {\n adminUsers(input: $input) {\n items {\n accountId\n nickname\n name\n email\n }\n }\n }\n": typeof types.AdminOrdersBuyerOptionsDocument, "\n query AdminOrdersStoreName($storeId: ID!) {\n adminStore(storeId: $storeId) {\n store {\n id\n storeName\n }\n }\n }\n": typeof types.AdminOrdersStoreNameDocument, "\n query AdminOrdersBuyerName($accountId: ID!) {\n adminUser(accountId: $accountId) {\n accountId\n nickname\n name\n email\n }\n }\n": typeof types.AdminOrdersBuyerNameDocument, "\n mutation AdminCancelOrder($input: AdminCancelOrderInput!) {\n adminCancelOrder(input: $input) {\n id\n status\n }\n }\n": typeof types.AdminCancelOrderDocument, - "\n query AdminProducts($input: AdminProductListInput) {\n adminProducts(input: $input) {\n items {\n id\n storeId\n storeName\n name\n regularPrice\n salePrice\n currency\n baseDesignImageUrl\n isActive\n createdAt\n updatedAt\n }\n totalCount\n hasMore\n nextCursor\n }\n }\n": typeof types.AdminProductsDocument, - "\n query AdminProduct($productId: ID!) {\n adminProduct(productId: $productId) {\n product {\n id\n storeId\n storeName\n name\n regularPrice\n salePrice\n currency\n baseDesignImageUrl\n isActive\n createdAt\n updatedAt\n }\n storeIsActive\n description\n purchaseNotice\n preparationTimeMinutes\n imageUrls\n reviewCount\n orderItemCount\n categories {\n id\n categoryType\n name\n isActive\n }\n tags {\n id\n name\n }\n optionGroups {\n id\n name\n description\n isRequired\n minSelect\n maxSelect\n optionRequiresDescription\n optionRequiresImage\n sortOrder\n isActive\n optionItems {\n id\n title\n description\n imageUrl\n priceDelta\n sortOrder\n isActive\n }\n }\n customTemplate {\n id\n baseImageUrl\n isActive\n textTokens {\n id\n tokenKey\n defaultText\n maxLength\n sortOrder\n isRequired\n }\n }\n }\n }\n": typeof types.AdminProductDocument, + "\n query AdminProducts($input: AdminProductListInput) {\n adminProducts(input: $input) {\n items {\n id\n storeId\n storeName\n name\n regularPrice\n salePrice\n currency\n thumbnailUrl\n isActive\n createdAt\n updatedAt\n }\n totalCount\n hasMore\n nextCursor\n }\n }\n": typeof types.AdminProductsDocument, + "\n query AdminProduct($productId: ID!) {\n adminProduct(productId: $productId) {\n product {\n id\n storeId\n storeName\n name\n regularPrice\n salePrice\n currency\n customMode\n isActive\n createdAt\n updatedAt\n }\n storeIsActive\n description\n purchaseNotice\n preparationTimeMinutes\n imageUrls\n reviewCount\n orderItemCount\n categories {\n id\n categoryType\n name\n isActive\n }\n tags {\n id\n name\n }\n optionGroups {\n id\n name\n description\n isRequired\n minSelect\n maxSelect\n sortOrder\n isActive\n optionItems {\n id\n title\n description\n imageUrl\n priceDelta\n sortOrder\n isActive\n threeDKey\n }\n }\n customTemplate {\n id\n baseImageUrl\n freeEditEnabled\n textTokens {\n id\n tokenKey\n label\n defaultText\n maxLength\n sortOrder\n isRequired\n textColor\n textAlign\n }\n }\n }\n }\n": typeof types.AdminProductDocument, "\n query AdminProductStoreOptions($input: AdminStoreListInput) {\n adminStores(input: $input) {\n items {\n id\n storeName\n isActive\n }\n }\n }\n": typeof types.AdminProductStoreOptionsDocument, "\n mutation AdminSetProductActive($input: AdminSetProductActiveInput!) {\n adminSetProductActive(input: $input) {\n id\n isActive\n }\n }\n": typeof types.AdminSetProductActiveDocument, "\n query AdminRegions($input: AdminRegionListInput) {\n adminRegions(input: $input) {\n id\n parentId\n level\n name\n slug\n sortOrder\n isActive\n centerLat\n centerLng\n storeCount\n childCount\n createdAt\n updatedAt\n }\n }\n": typeof types.AdminRegionsDocument, @@ -122,15 +122,15 @@ const documents: Documents = { "\n mutation AdminSendNotification($input: AdminSendNotificationInput!) {\n adminSendNotification(input: $input) {\n sentCount\n skippedAccountIds\n broadcastId\n }\n }\n": types.AdminSendNotificationDocument, "\n query AdminNotificationActiveUserCount {\n adminUsers(input: { status: ACTIVE, limit: 1 }) {\n totalCount\n }\n }\n": types.AdminNotificationActiveUserCountDocument, "\n query AdminNotificationUserOptions($input: AdminUserListInput) {\n adminUsers(input: $input) {\n items {\n accountId\n nickname\n name\n email\n }\n }\n }\n": types.AdminNotificationUserOptionsDocument, - "\n query AdminOrders($input: AdminOrderListInput) {\n adminOrders(input: $input) {\n items {\n id\n orderNumber\n accountId\n storeId\n storeName\n status\n pickupAt\n buyerName\n buyerPhone\n totalPrice\n createdAt\n }\n totalCount\n hasMore\n nextCursor\n }\n }\n": types.AdminOrdersDocument, - "\n query AdminOrder($orderId: ID!) {\n adminOrder(orderId: $orderId) {\n id\n orderNumber\n buyer {\n accountId\n email\n nickname\n status\n }\n status\n pickupAt\n buyerName\n buyerPhone\n subtotalPrice\n discountPrice\n totalPrice\n submittedAt\n confirmedAt\n madeAt\n pickedUpAt\n canceledAt\n createdAt\n updatedAt\n items {\n id\n storeId\n productId\n productName\n regularPrice\n salePrice\n quantity\n itemSubtotalPrice\n optionItems {\n id\n groupName\n optionTitle\n priceDelta\n }\n customTexts {\n id\n tokenKey\n defaultText\n valueText\n sortOrder\n }\n freeEdits {\n id\n cropImageUrl\n descriptionText\n sortOrder\n attachments {\n id\n imageUrl\n sortOrder\n }\n }\n }\n statusHistories {\n id\n fromStatus\n toStatus\n changedAt\n note\n }\n }\n }\n": types.AdminOrderDocument, + "\n query AdminOrders($input: AdminOrderListInput) {\n adminOrders(input: $input) {\n items {\n id\n orderNumber\n accountId\n storeId\n storeName\n status\n pickupAt\n buyerName\n buyerPhone\n totalPrice\n createdAt\n hasCustom\n }\n totalCount\n hasMore\n nextCursor\n }\n }\n": types.AdminOrdersDocument, + "\n query AdminOrder($orderId: ID!) {\n adminOrder(orderId: $orderId) {\n id\n orderNumber\n buyer {\n accountId\n email\n nickname\n status\n }\n status\n pickupAt\n buyerName\n buyerPhone\n subtotalPrice\n discountPrice\n totalPrice\n submittedAt\n confirmedAt\n madeAt\n pickedUpAt\n canceledAt\n createdAt\n updatedAt\n items {\n id\n storeId\n productId\n productName\n regularPrice\n salePrice\n quantity\n itemSubtotalPrice\n optionItems {\n id\n groupName\n optionTitle\n priceDelta\n }\n customMode\n customPreviewImageUrl\n customBaseImageUrl\n customImages {\n id\n kind\n imageUrl\n }\n customTexts {\n id\n tokenKey\n label\n defaultText\n valueText\n posX\n posY\n width\n height\n textColor\n textAlign\n sortOrder\n }\n freeEdits {\n id\n posX\n posY\n width\n height\n descriptionText\n sortOrder\n attachments {\n id\n imageUrl\n sortOrder\n }\n }\n }\n statusHistories {\n id\n fromStatus\n toStatus\n changedAt\n note\n }\n }\n }\n": types.AdminOrderDocument, "\n query AdminOrdersStoreOptions($input: AdminStoreListInput) {\n adminStores(input: $input) {\n items {\n id\n storeName\n isActive\n }\n }\n }\n": types.AdminOrdersStoreOptionsDocument, "\n query AdminOrdersBuyerOptions($input: AdminUserListInput) {\n adminUsers(input: $input) {\n items {\n accountId\n nickname\n name\n email\n }\n }\n }\n": types.AdminOrdersBuyerOptionsDocument, "\n query AdminOrdersStoreName($storeId: ID!) {\n adminStore(storeId: $storeId) {\n store {\n id\n storeName\n }\n }\n }\n": types.AdminOrdersStoreNameDocument, "\n query AdminOrdersBuyerName($accountId: ID!) {\n adminUser(accountId: $accountId) {\n accountId\n nickname\n name\n email\n }\n }\n": types.AdminOrdersBuyerNameDocument, "\n mutation AdminCancelOrder($input: AdminCancelOrderInput!) {\n adminCancelOrder(input: $input) {\n id\n status\n }\n }\n": types.AdminCancelOrderDocument, - "\n query AdminProducts($input: AdminProductListInput) {\n adminProducts(input: $input) {\n items {\n id\n storeId\n storeName\n name\n regularPrice\n salePrice\n currency\n baseDesignImageUrl\n isActive\n createdAt\n updatedAt\n }\n totalCount\n hasMore\n nextCursor\n }\n }\n": types.AdminProductsDocument, - "\n query AdminProduct($productId: ID!) {\n adminProduct(productId: $productId) {\n product {\n id\n storeId\n storeName\n name\n regularPrice\n salePrice\n currency\n baseDesignImageUrl\n isActive\n createdAt\n updatedAt\n }\n storeIsActive\n description\n purchaseNotice\n preparationTimeMinutes\n imageUrls\n reviewCount\n orderItemCount\n categories {\n id\n categoryType\n name\n isActive\n }\n tags {\n id\n name\n }\n optionGroups {\n id\n name\n description\n isRequired\n minSelect\n maxSelect\n optionRequiresDescription\n optionRequiresImage\n sortOrder\n isActive\n optionItems {\n id\n title\n description\n imageUrl\n priceDelta\n sortOrder\n isActive\n }\n }\n customTemplate {\n id\n baseImageUrl\n isActive\n textTokens {\n id\n tokenKey\n defaultText\n maxLength\n sortOrder\n isRequired\n }\n }\n }\n }\n": types.AdminProductDocument, + "\n query AdminProducts($input: AdminProductListInput) {\n adminProducts(input: $input) {\n items {\n id\n storeId\n storeName\n name\n regularPrice\n salePrice\n currency\n thumbnailUrl\n isActive\n createdAt\n updatedAt\n }\n totalCount\n hasMore\n nextCursor\n }\n }\n": types.AdminProductsDocument, + "\n query AdminProduct($productId: ID!) {\n adminProduct(productId: $productId) {\n product {\n id\n storeId\n storeName\n name\n regularPrice\n salePrice\n currency\n customMode\n isActive\n createdAt\n updatedAt\n }\n storeIsActive\n description\n purchaseNotice\n preparationTimeMinutes\n imageUrls\n reviewCount\n orderItemCount\n categories {\n id\n categoryType\n name\n isActive\n }\n tags {\n id\n name\n }\n optionGroups {\n id\n name\n description\n isRequired\n minSelect\n maxSelect\n sortOrder\n isActive\n optionItems {\n id\n title\n description\n imageUrl\n priceDelta\n sortOrder\n isActive\n threeDKey\n }\n }\n customTemplate {\n id\n baseImageUrl\n freeEditEnabled\n textTokens {\n id\n tokenKey\n label\n defaultText\n maxLength\n sortOrder\n isRequired\n textColor\n textAlign\n }\n }\n }\n }\n": types.AdminProductDocument, "\n query AdminProductStoreOptions($input: AdminStoreListInput) {\n adminStores(input: $input) {\n items {\n id\n storeName\n isActive\n }\n }\n }\n": types.AdminProductStoreOptionsDocument, "\n mutation AdminSetProductActive($input: AdminSetProductActiveInput!) {\n adminSetProductActive(input: $input) {\n id\n isActive\n }\n }\n": types.AdminSetProductActiveDocument, "\n query AdminRegions($input: AdminRegionListInput) {\n adminRegions(input: $input) {\n id\n parentId\n level\n name\n slug\n sortOrder\n isActive\n centerLat\n centerLng\n storeCount\n childCount\n createdAt\n updatedAt\n }\n }\n": types.AdminRegionsDocument, @@ -290,11 +290,11 @@ export function graphql(source: "\n query AdminNotificationUserOptions($input: /** * The graphql function is used to parse GraphQL queries into a document that can be used by GraphQL clients. */ -export function graphql(source: "\n query AdminOrders($input: AdminOrderListInput) {\n adminOrders(input: $input) {\n items {\n id\n orderNumber\n accountId\n storeId\n storeName\n status\n pickupAt\n buyerName\n buyerPhone\n totalPrice\n createdAt\n }\n totalCount\n hasMore\n nextCursor\n }\n }\n"): typeof import('./graphql').AdminOrdersDocument; +export function graphql(source: "\n query AdminOrders($input: AdminOrderListInput) {\n adminOrders(input: $input) {\n items {\n id\n orderNumber\n accountId\n storeId\n storeName\n status\n pickupAt\n buyerName\n buyerPhone\n totalPrice\n createdAt\n hasCustom\n }\n totalCount\n hasMore\n nextCursor\n }\n }\n"): typeof import('./graphql').AdminOrdersDocument; /** * The graphql function is used to parse GraphQL queries into a document that can be used by GraphQL clients. */ -export function graphql(source: "\n query AdminOrder($orderId: ID!) {\n adminOrder(orderId: $orderId) {\n id\n orderNumber\n buyer {\n accountId\n email\n nickname\n status\n }\n status\n pickupAt\n buyerName\n buyerPhone\n subtotalPrice\n discountPrice\n totalPrice\n submittedAt\n confirmedAt\n madeAt\n pickedUpAt\n canceledAt\n createdAt\n updatedAt\n items {\n id\n storeId\n productId\n productName\n regularPrice\n salePrice\n quantity\n itemSubtotalPrice\n optionItems {\n id\n groupName\n optionTitle\n priceDelta\n }\n customTexts {\n id\n tokenKey\n defaultText\n valueText\n sortOrder\n }\n freeEdits {\n id\n cropImageUrl\n descriptionText\n sortOrder\n attachments {\n id\n imageUrl\n sortOrder\n }\n }\n }\n statusHistories {\n id\n fromStatus\n toStatus\n changedAt\n note\n }\n }\n }\n"): typeof import('./graphql').AdminOrderDocument; +export function graphql(source: "\n query AdminOrder($orderId: ID!) {\n adminOrder(orderId: $orderId) {\n id\n orderNumber\n buyer {\n accountId\n email\n nickname\n status\n }\n status\n pickupAt\n buyerName\n buyerPhone\n subtotalPrice\n discountPrice\n totalPrice\n submittedAt\n confirmedAt\n madeAt\n pickedUpAt\n canceledAt\n createdAt\n updatedAt\n items {\n id\n storeId\n productId\n productName\n regularPrice\n salePrice\n quantity\n itemSubtotalPrice\n optionItems {\n id\n groupName\n optionTitle\n priceDelta\n }\n customMode\n customPreviewImageUrl\n customBaseImageUrl\n customImages {\n id\n kind\n imageUrl\n }\n customTexts {\n id\n tokenKey\n label\n defaultText\n valueText\n posX\n posY\n width\n height\n textColor\n textAlign\n sortOrder\n }\n freeEdits {\n id\n posX\n posY\n width\n height\n descriptionText\n sortOrder\n attachments {\n id\n imageUrl\n sortOrder\n }\n }\n }\n statusHistories {\n id\n fromStatus\n toStatus\n changedAt\n note\n }\n }\n }\n"): typeof import('./graphql').AdminOrderDocument; /** * The graphql function is used to parse GraphQL queries into a document that can be used by GraphQL clients. */ @@ -318,11 +318,11 @@ export function graphql(source: "\n mutation AdminCancelOrder($input: AdminCanc /** * The graphql function is used to parse GraphQL queries into a document that can be used by GraphQL clients. */ -export function graphql(source: "\n query AdminProducts($input: AdminProductListInput) {\n adminProducts(input: $input) {\n items {\n id\n storeId\n storeName\n name\n regularPrice\n salePrice\n currency\n baseDesignImageUrl\n isActive\n createdAt\n updatedAt\n }\n totalCount\n hasMore\n nextCursor\n }\n }\n"): typeof import('./graphql').AdminProductsDocument; +export function graphql(source: "\n query AdminProducts($input: AdminProductListInput) {\n adminProducts(input: $input) {\n items {\n id\n storeId\n storeName\n name\n regularPrice\n salePrice\n currency\n thumbnailUrl\n isActive\n createdAt\n updatedAt\n }\n totalCount\n hasMore\n nextCursor\n }\n }\n"): typeof import('./graphql').AdminProductsDocument; /** * The graphql function is used to parse GraphQL queries into a document that can be used by GraphQL clients. */ -export function graphql(source: "\n query AdminProduct($productId: ID!) {\n adminProduct(productId: $productId) {\n product {\n id\n storeId\n storeName\n name\n regularPrice\n salePrice\n currency\n baseDesignImageUrl\n isActive\n createdAt\n updatedAt\n }\n storeIsActive\n description\n purchaseNotice\n preparationTimeMinutes\n imageUrls\n reviewCount\n orderItemCount\n categories {\n id\n categoryType\n name\n isActive\n }\n tags {\n id\n name\n }\n optionGroups {\n id\n name\n description\n isRequired\n minSelect\n maxSelect\n optionRequiresDescription\n optionRequiresImage\n sortOrder\n isActive\n optionItems {\n id\n title\n description\n imageUrl\n priceDelta\n sortOrder\n isActive\n }\n }\n customTemplate {\n id\n baseImageUrl\n isActive\n textTokens {\n id\n tokenKey\n defaultText\n maxLength\n sortOrder\n isRequired\n }\n }\n }\n }\n"): typeof import('./graphql').AdminProductDocument; +export function graphql(source: "\n query AdminProduct($productId: ID!) {\n adminProduct(productId: $productId) {\n product {\n id\n storeId\n storeName\n name\n regularPrice\n salePrice\n currency\n customMode\n isActive\n createdAt\n updatedAt\n }\n storeIsActive\n description\n purchaseNotice\n preparationTimeMinutes\n imageUrls\n reviewCount\n orderItemCount\n categories {\n id\n categoryType\n name\n isActive\n }\n tags {\n id\n name\n }\n optionGroups {\n id\n name\n description\n isRequired\n minSelect\n maxSelect\n sortOrder\n isActive\n optionItems {\n id\n title\n description\n imageUrl\n priceDelta\n sortOrder\n isActive\n threeDKey\n }\n }\n customTemplate {\n id\n baseImageUrl\n freeEditEnabled\n textTokens {\n id\n tokenKey\n label\n defaultText\n maxLength\n sortOrder\n isRequired\n textColor\n textAlign\n }\n }\n }\n }\n"): typeof import('./graphql').AdminProductDocument; /** * The graphql function is used to parse GraphQL queries into a document that can be used by GraphQL clients. */ diff --git a/src/graphql/generated/graphql.ts b/src/graphql/generated/graphql.ts index 4bf07d3..4b4d0d7 100644 --- a/src/graphql/generated/graphql.ts +++ b/src/graphql/generated/graphql.ts @@ -56,11 +56,17 @@ export type AdminBannerListInput = { placement?: BannerPlacement | null | undefined; }; -/** 주문 강제 취소 입력. */ +/** 주문 강제 취소 입력. 허용 범위는 adminOrder.cancelOptions를 따른다. */ export type AdminCancelOrderInput = { - /** 취소 사유. 필수. 최대 494자('[관리자] ' 접두를 붙여 500자 이내로 이력에 남는다). 감사 로그에도 기록된다. */ - note: string; + /** 취소 사정. cancelOptions.refundRule이 BY_FAULT면 필수이고, 그 밖에는 무시한다. */ + fault?: OrderCancelFaultType | null | undefined; + /** 취소 메모. 선택, 최대 500자. 상태 이력과 감사 로그에 남는다. */ + note?: string | null | undefined; orderId: string | number; + /** 취소 사유. 필수. cancelOptions.reasons 중 하나여야 한다. */ + reason: OrderCancelReasonType; + /** 돌려줄 금액(원, 0~cancelOptions.paidAmount). fault가 BUYER일 때 필수이고, 그 밖에는 무시한다. */ + refundAmount?: number | null | undefined; }; /** 카테고리 목록 조회 조건. */ @@ -280,6 +286,8 @@ export type AdminOrderListInput = { cursor?: string | null | undefined; /** 주문 생성 시각 하한(이상). */ fromCreatedAt?: string | null | undefined; + /** true면 진행 중 주문(입금 대기·접수·확정·제작 완료)만. 기본 false, null도 false(전체)로 본다. status와 함께 오면 AND다. */ + inProgress?: boolean | null | undefined; /** 주문번호·주문자 이름·연락처 부분일치 검색. 최대 100자. */ keyword?: string | null | undefined; /** 한 번에 가져올 개수. 기본 20, 1~100만 허용하며 벗어나면 BAD_USER_INPUT. */ @@ -624,7 +632,7 @@ export type AuditActionType = /** 수정. */ | 'UPDATE'; -/** 감사 로그가 가리키는 대상 종류. 판매자 화면(sellerAuditLogs)은 STORE·PRODUCT·ORDER·CONVERSATION·CHANGE_PASSWORD만 노출하고 필터 입력도 그 범위만 받는다. */ +/** 감사 로그가 가리키는 대상 종류. 판매자 화면(sellerAuditLogs)은 STORE·PRODUCT·ORDER·CONVERSATION·CHANGE_PASSWORD·SETTLEMENT_ACCOUNT만 노출하고 필터 입력도 그 범위만 받는다. */ export type AuditTargetType = /** 계정(관리자·판매자 생성, 정지/복구, 비밀번호 초기화). */ | 'ACCOUNT' @@ -636,12 +644,18 @@ export type AuditTargetType = | 'CHANGE_PASSWORD' /** 구매자 문의 대화. */ | 'CONVERSATION' + /** 입금 기록(반환 연결·주인 모를 입금 종결). */ + | 'DEPOSIT_RECORD' /** 관리자 알림 발송. */ | 'NOTIFICATION' /** 주문 상태 변경. */ | 'ORDER' + /** 플랫폼 결제 설정(수수료율·입금 계좌). */ + | 'PAYMENT_SETTING' /** 상품과 그 하위. */ | 'PRODUCT' + /** 환불(완료 처리). */ + | 'REFUND' /** 지역 마스터. */ | 'REGION' /** 리뷰 강제 삭제. */ @@ -652,6 +666,10 @@ export type AuditTargetType = | 'REVIEW_REPORT' /** 검색 진입 화면 키워드 바로가기 칩. 순서 변경은 순서가 바뀐 칩마다 1건씩 남는다. */ | 'SEARCH_KEYWORD_CHIP' + /** 주간 정산(송금 완료 처리). */ + | 'SETTLEMENT' + /** 매장 정산 계좌(판매자 본인·관리자 대리 수정). 기록에는 계좌번호 끝 4자리만 남고, 판매자 감사 로그에도 보인다. */ + | 'SETTLEMENT_ACCOUNT' /** 매장 설정·콘텐츠. */ | 'STORE' /** 태그 마스터. */ @@ -718,6 +736,42 @@ export type CursorInput = { limit?: number | null | undefined; }; +/** + * 주문 커스텀 이미지 종류. 값은 늘어날 수 있으니 모르는 값을 받아도 화면이 죽지 않게 처리한다. + * 3D 옆면은 옆면 고도 asin(0.4) 정사영이고 좌·우는 정면을 보는 사람 기준이다. + */ +export type CustomImageKindType = + /** 슬롯형 합성 이미지(바탕 + 문구, 구매자가 본 그대로). 대표 이미지다. */ + | 'SLOT_COMPOSITE' + /** 3D 옆면 뒤(정면 반대). */ + | 'THREE_D_BACK' + /** 3D 옆면 정면(yaw 0). */ + | 'THREE_D_FRONT' + /** 3D 옆면 왼쪽. */ + | 'THREE_D_LEFT' + /** 3D 옆면 오른쪽. */ + | 'THREE_D_RIGHT' + /** 3D 윗면(위에서 내려다본 정사각). 대표 이미지다. */ + | 'THREE_D_TOP'; + +/** 상품의 커스텀 방식. 방식이 있는 상품은 구매자가 꾸민 내용 없이 주문할 수 없다. */ +export type CustomModeType = + /** 커스텀 없음. 옵션만 고르고 주문한다. */ + | 'NONE' + /** 슬롯형. 판매자가 정한 바탕 이미지 위 문구 자리에 문구를 넣는다(자유 편집은 상품별 선택). */ + | 'SLOT' + /** 3D. 모양·크기 등 옵션을 3D 케이크로 꾸민다. 자유 편집은 없다. */ + | 'THREE_D'; + +/** 문구 자리 안 글자 정렬. */ +export type CustomTextAlignType = + /** 가운데 정렬. */ + | 'CENTER' + /** 왼쪽 정렬. */ + | 'LEFT' + /** 오른쪽 정렬. */ + | 'RIGHT'; + /** 소셜 로그인 Provider 종류 */ export type IdentityProvider = /** 구글 OIDC. */ @@ -725,23 +779,59 @@ export type IdentityProvider = /** 카카오 OIDC. */ | 'KAKAO'; +/** 확정·제작 완료 뒤 취소의 사정. 환불액이 갈린다(판매자 사정 = 전액, 구매자 사정 = 취소자가 정한 금액). */ +export type OrderCancelFaultType = + /** 구매자 사정. */ + | 'BUYER' + /** 판매자 사정. */ + | 'SELLER'; + +/** + * 취소 사유. 값은 늘어날 수 있으니 모르는 값은 reasonLabel(또는 '기타')로 보여 준다. + * 판매자는 앞의 여섯 값, 관리자는 여기에 입금 대기 주문의 PAYMENT_NOT_RECEIVED, 구매자는 BUYER_REQUEST(서버가 정한다)를 쓴다. + */ +export type OrderCancelReasonType = + /** 구매자 요청. */ + | 'BUYER_REQUEST' + /** 판매자가 확정 마감까지 확정하지 않아 자동 취소. */ + | 'CONFIRM_TIMEOUT' + /** 제작할 수 없는 디자인. */ + | 'DESIGN_NOT_FEASIBLE' + /** 부적절한 요청. */ + | 'INAPPROPRIATE_REQUEST' + /** 기타. 결제 도입 전 취소 기록도 이 값이다. */ + | 'OTHER' + /** 재료 소진. */ + | 'OUT_OF_MATERIALS' + /** 미입금. 입금 기한이 지났거나 관리자가 입금이 없다고 판단한 입금 대기 주문. */ + | 'PAYMENT_NOT_RECEIVED' + /** 일정 불가. */ + | 'SCHEDULE_UNAVAILABLE'; + /** - * 주문 상태. 구매자·판매자 API가 공용으로 쓴다. + * 주문 상태. 구매자·판매자·관리자 API가 공용으로 쓴다. 값은 늘어날 수 있으니 모르는 값을 받아도 화면이 죽지 않게 처리한다. * - * 전이는 `SUBMITTED → CONFIRMED → MADE → PICKED_UP` 한 방향이며 각 단계는 직전 - * 상태에서만 진입할 수 있다. `CANCELED`는 `PICKED_UP` 이전 세 상태에서만 가능하고, - * 어떤 상태에서도 `SUBMITTED`로 되돌아갈 수 없다. + * 흐름은 `PENDING_PAYMENT → SUBMITTED → CONFIRMED → MADE → PICKED_UP`이며 어떤 상태에서도 + * 앞 단계로 되돌아갈 수 없다. 판매자가 sellerUpdateOrderStatus로 바꿀 수 있는 전이는 `SUBMITTED → CONFIRMED`, + * `CONFIRMED → MADE`, `CONFIRMED·MADE → PICKED_UP·NO_SHOW`뿐이고, 취소는 주체별 취소 mutation(cancelMyOrder·sellerCancelOrder·adminCancelOrder)으로만 한다. + * 관리자도 adminCompleteOrderPickup으로 확정·제작 완료 주문을 픽업 완료할 수 있다. + * 시스템은 입금 기한(1시간)이 지난 입금 대기를 취소하고, 확정 마감이 지난 접수를 취소(전액 환불)하며, + * 픽업 시각 + 24시간이 지난 확정·제작 완료를 픽업 완료로 바꾼다. 판매자에게는 입금이 확인된(접수된) 주문만 보인다. */ export type OrderStatusType = - /** 취소된 종료 상태. 취소 처리에는 사유(note)가 필수다. */ + /** 취소된 종료 상태. 주체·사유·사정·환불은 주문 상세의 cancellation에 있다. */ | 'CANCELED' /** 판매자가 주문을 확인·수락한 상태. 제작 대기. */ | 'CONFIRMED' /** 판매자가 제작을 완료해 픽업을 기다리는 상태. "주문 생성됨"이 아니다. */ | 'MADE' + /** 노쇼. 구매자가 픽업 시간에 오지 않아 판매자가 처리한 종료 상태. 환불 없음, 리뷰 불가. */ + | 'NO_SHOW' + /** 입금 대기. 주문 직후 계좌이체 입금을 기다리는 상태이고, 판매자에게 보이지 않는다. */ + | 'PENDING_PAYMENT' /** 구매자가 수령을 마친 종료 상태. 이후 상태 변경 불가. */ | 'PICKED_UP' - /** 구매자가 주문을 넣은 직후의 초기 상태. 판매자 확인 대기. */ + /** 입금이 확인돼 접수된 상태. 판매자 확인 대기. */ | 'SUBMITTED'; /** 리뷰 첨부 미디어 종류. */ @@ -782,11 +872,14 @@ export type StoreMapProvider = /** * 업로드 용도. 용도마다 저장 경로가 다르고, 저장 입력은 같은 용도로 발급된 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다. */ export type UploadPurpose = /** 플랫폼 배너 이미지(관리자). */ | 'BANNER_IMAGE' + /** 채팅 첨부 이미지(판매자). sellerSendConversationMessage의 IMAGE 메시지가 이 용도 URL만 받는다. */ + | 'CONVERSATION_IMAGE' /** 상품 이미지·커스텀 도안 바탕·옵션 선택지 이미지·커스텀 템플릿 바탕(판매자). */ | 'PRODUCT_IMAGE' /** 매장 프로필(로고) 이미지(판매자·관리자). */ @@ -997,14 +1090,14 @@ export type AdminOrdersQueryVariables = Exact<{ }>; -export type AdminOrdersQuery = { adminOrders: { totalCount: number, hasMore: boolean, nextCursor: string | null, items: Array<{ id: string, orderNumber: string, accountId: string, storeId: string | null, storeName: string | null, status: OrderStatusType, pickupAt: string, buyerName: string, buyerPhone: string, totalPrice: number, createdAt: string }> } }; +export type AdminOrdersQuery = { adminOrders: { totalCount: number, hasMore: boolean, nextCursor: string | null, items: Array<{ id: string, orderNumber: string, accountId: string, storeId: string | null, storeName: string | null, status: OrderStatusType, pickupAt: string, buyerName: string, buyerPhone: string, totalPrice: number, createdAt: string, hasCustom: boolean }> } }; export type AdminOrderQueryVariables = Exact<{ orderId: string | number; }>; -export type AdminOrderQuery = { adminOrder: { id: string, orderNumber: string, status: OrderStatusType, pickupAt: string, buyerName: string, buyerPhone: string, subtotalPrice: number, discountPrice: number, totalPrice: number, submittedAt: string | null, confirmedAt: string | null, madeAt: string | null, pickedUpAt: string | null, canceledAt: string | null, createdAt: string, updatedAt: string, buyer: { accountId: string, email: string | null, nickname: string | null, status: AccountStatus }, items: Array<{ id: string, storeId: string, productId: string, productName: string, regularPrice: number, salePrice: number | null, quantity: number, itemSubtotalPrice: number, optionItems: Array<{ id: string, groupName: string, optionTitle: string, priceDelta: number }>, customTexts: Array<{ id: string, tokenKey: string, defaultText: string, valueText: string, sortOrder: number }>, freeEdits: Array<{ id: string, cropImageUrl: string, descriptionText: string, sortOrder: number, attachments: Array<{ id: string, imageUrl: string, sortOrder: number }> }> }>, statusHistories: Array<{ id: string, fromStatus: OrderStatusType | null, toStatus: OrderStatusType, changedAt: string, note: string | null }> } }; +export type AdminOrderQuery = { adminOrder: { id: string, orderNumber: string, status: OrderStatusType, pickupAt: string, buyerName: string, buyerPhone: string, subtotalPrice: number, discountPrice: number, totalPrice: number, submittedAt: string | null, confirmedAt: string | null, madeAt: string | null, pickedUpAt: string | null, canceledAt: string | null, createdAt: string, updatedAt: string, buyer: { accountId: string, email: string | null, nickname: string | null, status: AccountStatus }, items: Array<{ id: string, storeId: string, productId: string, productName: string, regularPrice: number, salePrice: number | null, quantity: number, itemSubtotalPrice: number, customMode: CustomModeType, customPreviewImageUrl: string | null, customBaseImageUrl: string | null, optionItems: Array<{ id: string, groupName: string, optionTitle: string, priceDelta: number }>, customImages: Array<{ id: string, kind: CustomImageKindType, imageUrl: string }>, customTexts: Array<{ id: string, tokenKey: string, label: string, defaultText: string, valueText: string | null, posX: number, posY: number, width: number, height: number, textColor: string, textAlign: CustomTextAlignType, sortOrder: number }>, freeEdits: Array<{ id: string, posX: number, posY: number, width: number, height: number, descriptionText: string, sortOrder: number, attachments: Array<{ id: string, imageUrl: string, sortOrder: number }> }> }>, statusHistories: Array<{ id: string, fromStatus: OrderStatusType | null, toStatus: OrderStatusType, changedAt: string, note: string | null }> } }; export type AdminOrdersStoreOptionsQueryVariables = Exact<{ input?: AdminStoreListInput | null | undefined; @@ -1046,14 +1139,14 @@ export type AdminProductsQueryVariables = Exact<{ }>; -export type AdminProductsQuery = { adminProducts: { totalCount: number, hasMore: boolean, nextCursor: string | null, items: Array<{ id: string, storeId: string, storeName: string, name: string, regularPrice: number, salePrice: number | null, currency: string, baseDesignImageUrl: string | null, isActive: boolean, createdAt: string, updatedAt: string }> } }; +export type AdminProductsQuery = { adminProducts: { totalCount: number, hasMore: boolean, nextCursor: string | null, items: Array<{ id: string, storeId: string, storeName: string, name: string, regularPrice: number, salePrice: number | null, currency: string, thumbnailUrl: string | null, isActive: boolean, createdAt: string, updatedAt: string }> } }; export type AdminProductQueryVariables = Exact<{ productId: string | number; }>; -export type AdminProductQuery = { adminProduct: { storeIsActive: boolean, description: string | null, purchaseNotice: string | null, preparationTimeMinutes: number, imageUrls: Array, reviewCount: number, orderItemCount: number, product: { id: string, storeId: string, storeName: string, name: string, regularPrice: number, salePrice: number | null, currency: string, baseDesignImageUrl: string | null, isActive: boolean, createdAt: string, updatedAt: string }, categories: Array<{ id: string, categoryType: CategoryType, name: string, isActive: boolean }>, tags: Array<{ id: string, name: string }>, optionGroups: Array<{ id: string, name: string, description: string | null, isRequired: boolean, minSelect: number, maxSelect: number, optionRequiresDescription: boolean, optionRequiresImage: boolean, sortOrder: number, isActive: boolean, optionItems: Array<{ id: string, title: string, description: string | null, imageUrl: string | null, priceDelta: number, sortOrder: number, isActive: boolean }> }>, customTemplate: { id: string, baseImageUrl: string, isActive: boolean, textTokens: Array<{ id: string, tokenKey: string, defaultText: string, maxLength: number, sortOrder: number, isRequired: boolean }> } | null } }; +export type AdminProductQuery = { adminProduct: { storeIsActive: boolean, description: string | null, purchaseNotice: string | null, preparationTimeMinutes: number, imageUrls: Array, reviewCount: number, orderItemCount: number, product: { id: string, storeId: string, storeName: string, name: string, regularPrice: number, salePrice: number | null, currency: string, customMode: CustomModeType, isActive: boolean, createdAt: string, updatedAt: string }, categories: Array<{ id: string, categoryType: CategoryType, name: string, isActive: boolean }>, tags: Array<{ id: string, name: string }>, optionGroups: Array<{ id: string, name: string, description: string | null, isRequired: boolean, minSelect: number, maxSelect: number, sortOrder: number, isActive: boolean, optionItems: Array<{ id: string, title: string, description: string | null, imageUrl: string | null, priceDelta: number, sortOrder: number, isActive: boolean, threeDKey: string | null }> }>, customTemplate: { id: string, baseImageUrl: string, freeEditEnabled: boolean, textTokens: Array<{ id: string, tokenKey: string, label: string, defaultText: string, maxLength: number, sortOrder: number, isRequired: boolean, textColor: string, textAlign: CustomTextAlignType }> } | null } }; export type AdminProductStoreOptionsQueryVariables = Exact<{ input?: AdminStoreListInput | null | undefined; @@ -1754,6 +1847,7 @@ export const AdminOrdersDocument = new TypedDocumentString(` buyerPhone totalPrice createdAt + hasCustom } totalCount hasMore @@ -1801,16 +1895,34 @@ export const AdminOrderDocument = new TypedDocumentString(` optionTitle priceDelta } + customMode + customPreviewImageUrl + customBaseImageUrl + customImages { + id + kind + imageUrl + } customTexts { id tokenKey + label defaultText valueText + posX + posY + width + height + textColor + textAlign sortOrder } freeEdits { id - cropImageUrl + posX + posY + width + height descriptionText sortOrder attachments { @@ -1892,7 +2004,7 @@ export const AdminProductsDocument = new TypedDocumentString(` regularPrice salePrice currency - baseDesignImageUrl + thumbnailUrl isActive createdAt updatedAt @@ -1914,7 +2026,7 @@ export const AdminProductDocument = new TypedDocumentString(` regularPrice salePrice currency - baseDesignImageUrl + customMode isActive createdAt updatedAt @@ -1943,8 +2055,6 @@ export const AdminProductDocument = new TypedDocumentString(` isRequired minSelect maxSelect - optionRequiresDescription - optionRequiresImage sortOrder isActive optionItems { @@ -1955,19 +2065,23 @@ export const AdminProductDocument = new TypedDocumentString(` priceDelta sortOrder isActive + threeDKey } } customTemplate { id baseImageUrl - isActive + freeEditEnabled textTokens { id tokenKey + label defaultText maxLength sortOrder isRequired + textColor + textAlign } } } From ebde314e15bf2bebc64fd1cd5640290b4c0d3095 Mon Sep 17 00:00:00 2001 From: chanwoo7 Date: Thu, 19 Nov 2026 08:11:39 +0900 Subject: [PATCH 02/14] =?UTF-8?q?docs:=20=EC=B2=98=EB=A6=AC=20=EB=8C=80?= =?UTF-8?q?=EA=B8=B0=20=EB=94=A5=EB=A7=81=ED=81=AC=20=EA=B3=84=EC=95=BD?= =?UTF-8?q?=C2=B7=EA=B3=84=EC=A2=8C=EB=B2=88=ED=98=B8=20=ED=91=9C=EC=8B=9C?= =?UTF-8?q?=20=EA=B7=9C=EC=B9=99=EA=B3=BC=20=EC=BB=A4=EC=8A=A4=ED=85=80=20?= =?UTF-8?q?=ED=91=9C=EC=8B=9C=20=EA=B2=B0=EC=A0=95=20=EA=B8=B0=EB=A1=9D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 다음 PR(주문 결제 카드·정산·처리 대기 허브)이 따를 규칙을 먼저 남긴다. - D19 처리 대기 허브 /tasks와 BE 경보 딥링크 계약(deposits?orderId·refunds?refundId·settlements?periodStart), 딥링크 시트 바로 열기·로그인 뒤 복귀, 건수 진실은 adminTaskCounts - D20 계좌번호: 목록 마스킹, 단건 시트·상세만 전체 + 복사, 콘솔·오류·URL에 남기지 않음 - D21 커스텀 주문은 렌더러 없이 이미지·스냅샷으로 확인 - 아키텍처 §3: enum 라벨은 Record + 모르는 값 원문 폴백 --- docs/guide/architecture-conventions.md | 1 + docs/guide/decisions.md | 43 ++++++++++++++------------ 2 files changed, 24 insertions(+), 20 deletions(-) diff --git a/docs/guide/architecture-conventions.md b/docs/guide/architecture-conventions.md index 1c27b36..b30e42e 100644 --- a/docs/guide/architecture-conventions.md +++ b/docs/guide/architecture-conventions.md @@ -40,6 +40,7 @@ src/ - **mutation 뒤**에는 그 feature의 list·detail 키를 invalidate한다. 낙관적 업데이트는 쓰지 않는다 — 감사 대상 작업이라 서버 결과가 진실이다. - **목록**은 커서 방식(`items · totalCount · hasMore · nextCursor`). 필터·커서는 URL 검색 파라미터(zod)로 유지해 새로고침·공유가 된다. - **ID**는 문자열 그대로. `"0"`·빈 문자열을 truthy 검사로 버리지 않는다. +- **enum 라벨**은 `Record<생성 enum, …>`로 둬 값이 늘면 tsc가 잡게 하고, 조회는 모르는 값에 원문으로 폴백한다. BE가 먼저 배포돼 새 값이 와도 화면이 죽지 않아야 한다. - **날짜**는 표시·입력 KST, 전송 ISO(UTC). 기간 필터의 경계는 KST 하루 시작·끝을 UTC로 바꿔 보낸다. ## 4. 인증 diff --git a/docs/guide/decisions.md b/docs/guide/decisions.md index a43f654..046977a 100644 --- a/docs/guide/decisions.md +++ b/docs/guide/decisions.md @@ -2,23 +2,26 @@ 확정된 결정만 적는다. 번호는 바꾸지 않고, 뒤집힌 결정은 줄을 긋지 않고 "대체됨 → D-n"으로 표시한다. 결정의 배경이 되는 구조 설명은 [architecture-conventions.md](./architecture-conventions.md). -| # | 일자 | 결정 | 이유 | -| --- | ---------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------- | -| D1 | 2026-09-27 | 레포 `CaQuick/caquick-admin-fe`(public), pnpm, Node 24 | 판매자 앱(`caquick-seller-fe`)과 이름 짝, FE-v2와 같은 pnpm | -| D2 | 2026-09-27 | Vite + React 19 + TypeScript strict SPA | 관리자 도구는 SSR이 필요 없고 정적 서빙이 배포에 가장 단순 | -| D3 | 2026-09-27 | TanStack Router(파일 기반) | 목록 필터·커서를 타입 있는 검색 파라미터로 URL에 유지 | -| D4 | 2026-09-27 | TanStack Query + graphql-request + graphql-codegen(client-preset) | 정규화 캐시 없이 invalidate로 충분한 CRUD 화면. 서버 진실 우선, 낙관적 업데이트 없음 | -| D5 | 2026-09-27 | Tailwind v4 + shadcn/ui(new-york, neutral) + TanStack Table + react-hook-form + zod, 차트 Recharts | FE-v2와 같은 스타일 체계. 컴포넌트는 레포가 소유(`src/shared/ui`) | -| D6 | 2026-09-27 | 디자인 토큰은 FE-v2 계승(primary #7c5cff 계열, gray 스케일, status 3색, radius 10px, Pretendard), 라이트/다크 | 서비스와 같은 브랜드 인상, 장시간 사용 도구라 다크 필요 | -| D7 | 2026-09-27 | Vitest + Testing Library + MSW. E2E 없음. 커버리지 lines/statements 80 · branches 70 · functions 80(대체됨 → D16), Codecov patch 80 | 관리자 도구 범위에 맞는 비용. shadcn 복사본은 커버리지 제외 | -| D8 | 2026-09-27 | 배포: 이 레포가 Dockerfile(nginx) · `infra/compose.yml` · `deploy.yml` 소유. GHCR `ghcr.io/caquick/caquick-admin-fe:`(arm64), 맥미니 셀프호스트 러너, BE compose 네트워크 `caquick_default`에 external 참여, 기존 cloudflared가 라우팅 | BE와 독립 배포·롤백. BE 레포 변경은 Tunnel 호스트 1줄 | -| D9 | 2026-09-27 | 도메인 `admin.caquick.site` → 컨테이너 `caquick-admin:80`. API `https://api.caquick.site` | 같은 부모 도메인이라 refresh 쿠키가 same-site로 전송된다 — 쿠키 도메인 변경 불필요, BE는 CORS 오리진만 추가 | -| D10 | 2026-09-27 | 인증: REST `/auth/admin/*`. accessToken은 메모리, refresh는 httpOnly 쿠키. 401이면 refresh 1회 후 재시도, 부팅 시 refresh로 복원, `mustChangePassword`면 변경 화면 강제 | 토큰을 localStorage에 두지 않는다(XSS 반경). 로컬은 Vite 프록시로 same-origin | -| D11 | 2026-09-27 | 머지 게이트는 BE와 동일: terraform ruleset(main·develop), 필수 체크 `check`·`pr-title`·`coverage-report`·`Analyze (javascript-typescript)`, Codex 상태기계(CodeRabbit은 대체됨 → D17) | 무인 진행의 전제 | -| D12 | 2026-09-27 | 릴리즈 순서: R1(기반·CI/CD·인증·셸·대시보드) → main → 영역별 PR → R2 | 배포 파이프라인·Tunnel·쿠키 문제를 가장 이른 시점에 실사이트에서 확인 | -| D13 | 2026-09-27 | BE SDL 스냅샷(`schema/schema.graphql`) 커밋 + `pnpm schema:pull`. CI는 codegen 신선도만 게이트, BE main과의 drift는 advisory | CI가 BE 체크아웃에 의존하지 않게 | -| D14 | 2026-09-27 | 문서: `CLAUDE.md`·`.claude/`·`AGENTS.md`·`docs/*`(guide 제외)·`.figma/` gitignore. `docs/guide/`·README 커밋 | BE와 같은 방식 | -| D15 | 2026-09-27 | 의존 방향은 ESLint boundaries로 강제(shared→features 금지, feature 간은 index.ts만). 검사기는 반증 케이스로 확인하고 넣는다 | BE `arch:check`와 같은 역할 | -| D16 | 2026-10-05 | 커버리지 임계를 실측 정수 내림으로 상향: statements 95 · branches 88 · functions 94 · lines 96. CI는 테스트를 3샤드로 나누고 coverage-report가 합친 결과로 검사 | 실측(95.54·88.07·94.29·96.07)보다 한참 낮은 임계는 회귀를 못 잡는다. 샤드 합산이 단일 실행과 같음을 확인 | -| D17 | 2026-10-06 | 리뷰 봇은 Codex만 쓴다. CodeRabbit은 BE 전용 — `.coderabbit.yaml`은 자동 리뷰를 끈 최소 설정만 둔다 | 사용자 결정(판매자 앱도 같음) | -| D18 | 2026-11-01 | 도메인을 `admin.caquick.com`·API `https://api.caquick.com`으로 옮긴다(D9 대체). 이미지 하나에 API 주소와 CSP가 같이 들어가므로 둘을 한 번에 바꾼다 | caquick.site 만료(2026-11-29). 관리자 웹과 API가 같은 사이트여야 refresh 쿠키가 실린다 | +| # | 일자 | 결정 | 이유 | +| --- | ---------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| D1 | 2026-09-27 | 레포 `CaQuick/caquick-admin-fe`(public), pnpm, Node 24 | 판매자 앱(`caquick-seller-fe`)과 이름 짝, FE-v2와 같은 pnpm | +| D2 | 2026-09-27 | Vite + React 19 + TypeScript strict SPA | 관리자 도구는 SSR이 필요 없고 정적 서빙이 배포에 가장 단순 | +| D3 | 2026-09-27 | TanStack Router(파일 기반) | 목록 필터·커서를 타입 있는 검색 파라미터로 URL에 유지 | +| D4 | 2026-09-27 | TanStack Query + graphql-request + graphql-codegen(client-preset) | 정규화 캐시 없이 invalidate로 충분한 CRUD 화면. 서버 진실 우선, 낙관적 업데이트 없음 | +| D5 | 2026-09-27 | Tailwind v4 + shadcn/ui(new-york, neutral) + TanStack Table + react-hook-form + zod, 차트 Recharts | FE-v2와 같은 스타일 체계. 컴포넌트는 레포가 소유(`src/shared/ui`) | +| D6 | 2026-09-27 | 디자인 토큰은 FE-v2 계승(primary #7c5cff 계열, gray 스케일, status 3색, radius 10px, Pretendard), 라이트/다크 | 서비스와 같은 브랜드 인상, 장시간 사용 도구라 다크 필요 | +| D7 | 2026-09-27 | Vitest + Testing Library + MSW. E2E 없음. 커버리지 lines/statements 80 · branches 70 · functions 80(대체됨 → D16), Codecov patch 80 | 관리자 도구 범위에 맞는 비용. shadcn 복사본은 커버리지 제외 | +| D8 | 2026-09-27 | 배포: 이 레포가 Dockerfile(nginx) · `infra/compose.yml` · `deploy.yml` 소유. GHCR `ghcr.io/caquick/caquick-admin-fe:`(arm64), 맥미니 셀프호스트 러너, BE compose 네트워크 `caquick_default`에 external 참여, 기존 cloudflared가 라우팅 | BE와 독립 배포·롤백. BE 레포 변경은 Tunnel 호스트 1줄 | +| D9 | 2026-09-27 | 도메인 `admin.caquick.site` → 컨테이너 `caquick-admin:80`. API `https://api.caquick.site` | 같은 부모 도메인이라 refresh 쿠키가 same-site로 전송된다 — 쿠키 도메인 변경 불필요, BE는 CORS 오리진만 추가 | +| D10 | 2026-09-27 | 인증: REST `/auth/admin/*`. accessToken은 메모리, refresh는 httpOnly 쿠키. 401이면 refresh 1회 후 재시도, 부팅 시 refresh로 복원, `mustChangePassword`면 변경 화면 강제 | 토큰을 localStorage에 두지 않는다(XSS 반경). 로컬은 Vite 프록시로 same-origin | +| D11 | 2026-09-27 | 머지 게이트는 BE와 동일: terraform ruleset(main·develop), 필수 체크 `check`·`pr-title`·`coverage-report`·`Analyze (javascript-typescript)`, Codex 상태기계(CodeRabbit은 대체됨 → D17) | 무인 진행의 전제 | +| D12 | 2026-09-27 | 릴리즈 순서: R1(기반·CI/CD·인증·셸·대시보드) → main → 영역별 PR → R2 | 배포 파이프라인·Tunnel·쿠키 문제를 가장 이른 시점에 실사이트에서 확인 | +| D13 | 2026-09-27 | BE SDL 스냅샷(`schema/schema.graphql`) 커밋 + `pnpm schema:pull`. CI는 codegen 신선도만 게이트, BE main과의 drift는 advisory | CI가 BE 체크아웃에 의존하지 않게 | +| D14 | 2026-09-27 | 문서: `CLAUDE.md`·`.claude/`·`AGENTS.md`·`docs/*`(guide 제외)·`.figma/` gitignore. `docs/guide/`·README 커밋 | BE와 같은 방식 | +| D15 | 2026-09-27 | 의존 방향은 ESLint boundaries로 강제(shared→features 금지, feature 간은 index.ts만). 검사기는 반증 케이스로 확인하고 넣는다 | BE `arch:check`와 같은 역할 | +| D16 | 2026-10-05 | 커버리지 임계를 실측 정수 내림으로 상향: statements 95 · branches 88 · functions 94 · lines 96. CI는 테스트를 3샤드로 나누고 coverage-report가 합친 결과로 검사 | 실측(95.54·88.07·94.29·96.07)보다 한참 낮은 임계는 회귀를 못 잡는다. 샤드 합산이 단일 실행과 같음을 확인 | +| D17 | 2026-10-06 | 리뷰 봇은 Codex만 쓴다. CodeRabbit은 BE 전용 — `.coderabbit.yaml`은 자동 리뷰를 끈 최소 설정만 둔다 | 사용자 결정(판매자 앱도 같음) | +| D18 | 2026-11-01 | 도메인을 `admin.caquick.com`·API `https://api.caquick.com`으로 옮긴다(D9 대체). 이미지 하나에 API 주소와 CSP가 같이 들어가므로 둘을 한 번에 바꾼다 | caquick.site 만료(2026-11-29). 관리자 웹과 API가 같은 사이트여야 refresh 쿠키가 실린다 | +| D19 | 2026-11-19 | 처리 대기 허브는 `/tasks`(탭 입금·환불·정산 송금)다. BE 경보 딥링크 계약은 `/tasks/deposits?orderId=`·`/tasks/refunds?refundId=`·`/tasks/settlements?periodStart=YYYY-MM-DD`(KST 월요일)이고, 딥링크 ID가 있으면 그 건의 시트를 바로 연다. 세션이 없으면 로그인 뒤 같은 주소로 돌아온다. 건수는 `adminTaskCounts`가 진실이다(60초 폴링 + 창 포커스 재조회) | BE `ADMIN_WEB_BASE_URL` 경보가 이 주소를 만든다. 주소를 바꾸면 BE 경보 문구 helper와 같이 바꾼다. 디스코드 알림은 다시 올 수 있어 목록과 건수를 진실로 둔다 | +| D20 | 2026-11-19 | 계좌번호(환불·정산·입금 계좌)는 목록에서 마스킹(`****1234`)만 보이고, 전체 번호는 단건 시트·상세에서만 복사 버튼과 함께 보인다. 전체 번호를 콘솔·오류 메시지·URL에 남기지 않는다 | BE는 원문을 관리자 상세 조회 3곳(`adminRefund`·`adminSettlement`·`adminStoreSettlementAccount`)에서만 복호화한다. 화면이 노출 범위를 넓히면 암호화 저장이 의미를 잃는다 | +| D21 | 2026-11-19 | 커스텀 주문은 렌더러 없이 이미지로 확인한다. 3D는 렌더 5장(윗면 크게 → 앞·뒤·왼·오), 슬롯형은 합성 이미지 + 문구 자리 표, 자유 편집은 바탕 위 번호 영역(0~10000 → %)이다. 커스텀 enum 라벨은 `Record` + 모르는 값 원문 폴백 | 3D 렌더러는 판매자 앱만 갖는다. 관리자는 문의·분쟁 확인용이라 구매자가 본 그대로의 캡처면 충분하다 | From c6904cfe18b947407ba4f3945a4545d4764f12b8 Mon Sep 17 00:00:00 2001 From: chanwoo7 Date: Thu, 19 Nov 2026 08:27:11 +0900 Subject: [PATCH 03/14] =?UTF-8?q?fix:=20=EC=82=AC=EC=A0=95=20=EC=84=A0?= =?UTF-8?q?=ED=83=9D=EC=9D=B4=20=ED=95=84=EC=9A=94=ED=95=9C=20=EC=A3=BC?= =?UTF-8?q?=EB=AC=B8=EC=9D=98=20=EC=B7=A8=EC=86=8C=20=EB=B2=84=ED=8A=BC?= =?UTF-8?q?=EC=9D=84=20=EC=88=A8=EA=B8=B0=EA=B3=A0=20=EC=9E=90=EC=9C=A0=20?= =?UTF-8?q?=ED=8E=B8=EC=A7=91=20=ED=91=9C=EC=8B=9C=EB=A5=BC=20=EC=8A=AC?= =?UTF-8?q?=EB=A1=AF=ED=98=95=20=EC=83=81=ED=92=88=EC=97=90=EB=A7=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 지금 취소 다이얼로그는 사유 OTHER만 보내는데, 확정·제작 완료 주문은 BE가 사정(fault)을 요구해 늘 CANCEL_FAULT_REQUIRED로 거절됐다. 사정을 고르는 cancelOptions 다이얼로그가 들어올 때까지 이 상태에서는 취소 버튼을 두지 않는다. 상품 커스텀 설정 카드는 3D·없음 상품에 템플릿이 남아 있으면 '자유 편집: 허용'을 보여 3D 안내와 어긋났다. 구매자는 슬롯형에서만 템플릿을 받는다. - 주문: isCancelable을 입금 대기·접수로 좁힘(BE가 사정 없이 받는 상태). 취소 spec fixture를 접수 주문으로 바꾸고 확정·제작 완료에는 버튼이 없음을 단언 - 상품: 자유 편집 행은 슬롯형이고 템플릿이 있을 때만. 남은 템플릿의 자유 편집 값은 '구매자에게 보이지 않습니다' 안내 아래로 - 커스텀 문구 상태: 기본 문구의 홀로 있는 CR도 LF로 맞춤(BE 저장 규칙과 같게) - 렌더 이미지 라벨: THREE_D_ 종류에만 '3D' 접두, 모르는 종류는 원문 테스트: status 7상태 표, 주문 상세 확정·제작 완료 취소 버튼 없음 2건, 3D 렌더에 모르는 종류 1장, 커스텀 설정 카드 2경우 추가(없음+템플릿 없음, 3D+남은 템플릿), slotTextState 홀로 있는 CR 1건. 반증: 네 수정을 하나씩 되돌리면 각각 5·2·1·1건이 실패한다. --- src/features/custom/meta.spec.ts | 1 + src/features/custom/meta.ts | 4 +-- .../orders/components/order-item-custom.tsx | 4 ++- src/features/orders/pages/orders.spec.tsx | 30 +++++++++++++++---- src/features/orders/status.spec.ts | 10 +++++-- src/features/orders/status.ts | 4 +-- .../components/product-custom-card.tsx | 19 +++++++----- src/features/products/pages/products.spec.tsx | 29 ++++++++++-------- 8 files changed, 69 insertions(+), 32 deletions(-) diff --git a/src/features/custom/meta.spec.ts b/src/features/custom/meta.spec.ts index e754154..d0714b7 100644 --- a/src/features/custom/meta.spec.ts +++ b/src/features/custom/meta.spec.ts @@ -58,6 +58,7 @@ describe('slotTextState', () => { ' 생일\r\n축하해 ', '생일\n축하해', ], + ['기본 문구의 홀로 있는 CR도 LF로 맞춰 본다', 'DEFAULT', '생일\r축하해', '생일\n축하해'], ['바꾼 문구', 'CHANGED', '축하해', '서연아 생일 축하해 🎂'], ['줄바꿈만 다름', 'CHANGED', '생일 축하해', '생일\n축하해'], ['선택 자리를 지움(null)', 'EMPTY', '축하해', null], diff --git a/src/features/custom/meta.ts b/src/features/custom/meta.ts index c3f4145..e0606d6 100644 --- a/src/features/custom/meta.ts +++ b/src/features/custom/meta.ts @@ -35,8 +35,8 @@ export const SLOT_TEXT_STATE_LABEL: Record = { EMPTY: '문구 없음', }; -/** BE는 문구를 CRLF→LF·trim해 저장하므로 기본 문구도 같은 규칙으로 맞춰 비교한다 */ +/** BE는 문구의 CRLF·CR을 LF로 바꾸고 trim해 저장하므로 기본 문구도 같은 규칙으로 맞춰 비교한다 */ export function slotTextState(t: { defaultText: string; valueText: string | null }): SlotTextState { if (t.valueText === null || t.valueText === '') return 'EMPTY'; - return t.valueText === t.defaultText.replaceAll('\r\n', '\n').trim() ? 'DEFAULT' : 'CHANGED'; + return t.valueText === t.defaultText.replace(/\r\n?/g, '\n').trim() ? 'DEFAULT' : 'CHANGED'; } diff --git a/src/features/orders/components/order-item-custom.tsx b/src/features/orders/components/order-item-custom.tsx index d97632f..fd5782e 100644 --- a/src/features/orders/components/order-item-custom.tsx +++ b/src/features/orders/components/order-item-custom.tsx @@ -68,7 +68,9 @@ function ImageLink({ url, label, className }: { url: string; label: string; clas ); } -const renderLabel = (image: CustomImage) => `3D ${imageKindLabel(image.kind)}`; +// 모르는 종류는 3D 렌더라고 단정하지 않고 원문으로 보인다 +const renderLabel = ({ kind }: CustomImage) => + kind.startsWith('THREE_D_') ? `3D ${imageKindLabel(kind)}` : imageKindLabel(kind); function RenderImages({ top, sides }: { top: CustomImage | null; sides: CustomImage[] }) { return ( diff --git a/src/features/orders/pages/orders.spec.tsx b/src/features/orders/pages/orders.spec.tsx index 89ef4c1..9873ae8 100644 --- a/src/features/orders/pages/orders.spec.tsx +++ b/src/features/orders/pages/orders.spec.tsx @@ -157,6 +157,13 @@ const detail = { }, ], }; +// 확정·제작 완료는 사정(fault) 선택이 필요해 지금 다이얼로그로는 취소할 수 없다 +const submitted = { + ...detail, + status: 'SUBMITTED', + confirmedAt: null, + statusHistories: detail.statusHistories.slice(1), +}; /** 매장·구매자 이름 조회 기본 응답. 테스트가 뒤에 등록한 핸들러가 이긴다 */ function useNameLookups() { @@ -525,8 +532,8 @@ describe('주문 상세', () => { data: { adminOrder: detailCalls === 1 - ? detail - : { ...detail, status: 'CANCELED', canceledAt: '2026-09-27T03:00:00.000Z' }, + ? submitted + : { ...submitted, status: 'CANCELED', canceledAt: '2026-09-27T03:00:00.000Z' }, }, }); }), @@ -542,7 +549,7 @@ describe('주문 상세', () => { expect(screen.getByText(/서연아 생일 축하해/)).toBeInTheDocument(); expect(screen.getByText('seoyeon')).toBeInTheDocument(); const history = screen.getByText('상태 이력').closest('[data-slot="card"]')!; - expect(within(history).getAllByRole('listitem')).toHaveLength(2); + expect(within(history).getAllByRole('listitem')).toHaveLength(1); await userEvent.click(screen.getByRole('button', { name: '주문 취소' })); const dialog = await screen.findByRole('dialog'); @@ -559,6 +566,16 @@ describe('주문 상세', () => { expect(detailCalls).toBe(2); }); + it.each(['CONFIRMED', 'MADE'])( + '%s 주문은 사정 선택이 필요해 취소 버튼이 없다', + async (status) => { + server.use(gqlOk('AdminOrder', { adminOrder: { ...detail, status } })); + boot('/orders/1'); + await screen.findByText('레터링 생크림 케이크'); + expect(screen.queryByRole('button', { name: '주문 취소' })).not.toBeInTheDocument(); + }, + ); + it('상품·매장·구매자를 해당 상세로 잇고 계정 상태는 한국어로 보인다', async () => { server.use(gqlOk('AdminOrder', { adminOrder: detail })); boot('/orders/1'); @@ -708,7 +725,7 @@ describe('주문 상세', () => { expect(screen.queryByRole('figure')).not.toBeInTheDocument(); }); - it('3D는 렌더 5장을 윗면 크게 → 앞·뒤·왼·오 순서로 보이고 문구 표는 없다', async () => { + it('3D는 렌더 5장을 윗면 크게 → 앞·뒤·왼·오 순서로, 모르는 종류는 원문 라벨로 뒤에 보이고 문구 표는 없다', async () => { const item = detail.items[0]!; const render = (kind: string) => ({ id: kind, @@ -726,6 +743,7 @@ describe('주문 상세', () => { customPreviewImageUrl: 'https://img.test/THREE_D_TOP.png', customBaseImageUrl: null, customImages: [ + 'HOLOGRAM', 'THREE_D_RIGHT', 'THREE_D_LEFT', 'THREE_D_TOP', @@ -748,6 +766,7 @@ describe('주문 상세', () => { '3D 뒤 원본 보기(새 탭)', '3D 왼쪽 원본 보기(새 탭)', '3D 오른쪽 원본 보기(새 탭)', + 'HOLOGRAM 원본 보기(새 탭)', ]); expect(links.map((l) => l.getAttribute('href'))[0]).toBe('https://img.test/THREE_D_TOP.png'); expect(links.map((l) => l.querySelector('img')!.classList.contains('size-40'))).toEqual([ @@ -756,6 +775,7 @@ describe('주문 상세', () => { false, false, false, + false, ]); const custom = screen.getByRole('region', { name: '커스텀 내용' }); expect(within(custom).getByText('커스텀 · 3D')).toBeInTheDocument(); @@ -832,7 +852,7 @@ describe('주문 상세', () => { it('취소 실패는 토스트로 알리고 다이얼로그는 남는다', async () => { server.use( - gqlOk('AdminOrder', { adminOrder: detail }), + gqlOk('AdminOrder', { adminOrder: submitted }), gqlError('AdminCancelOrder', { message: '이미 픽업된 주문', code: 'ORDER_NOT_CANCELABLE', diff --git a/src/features/orders/status.spec.ts b/src/features/orders/status.spec.ts index 1015799..c13dd92 100644 --- a/src/features/orders/status.spec.ts +++ b/src/features/orders/status.spec.ts @@ -1,13 +1,17 @@ +import { type OrderStatusType } from '@/graphql/generated/graphql'; + import { ORDER_STATUS, isCancelable, orderStatusMeta } from './status'; describe('order status', () => { it.each([ + ['PENDING_PAYMENT', true], ['SUBMITTED', true], - ['CONFIRMED', true], - ['MADE', true], + ['CONFIRMED', false], + ['MADE', false], ['PICKED_UP', false], + ['NO_SHOW', false], ['CANCELED', false], - ] as const)('%s 취소 가능=%s', (status, ok) => { + ] satisfies [OrderStatusType, boolean][])('%s 취소 가능=%s', (status, ok) => { expect(isCancelable(status)).toBe(ok); }); diff --git a/src/features/orders/status.ts b/src/features/orders/status.ts index c012ba4..623d1d8 100644 --- a/src/features/orders/status.ts +++ b/src/features/orders/status.ts @@ -20,7 +20,7 @@ export function orderStatusMeta(value: OrderStatusType) { ); } -/** 취소 가능 상태(BE: SUBMITTED·CONFIRMED·MADE) */ +/** 사정(fault) 선택 없이 취소할 수 있는 상태. 확정·제작 완료는 BE가 사정을 요구한다 */ export function isCancelable(status: OrderStatusType): boolean { - return status === 'SUBMITTED' || status === 'CONFIRMED' || status === 'MADE'; + return status === 'PENDING_PAYMENT' || status === 'SUBMITTED'; } diff --git a/src/features/products/components/product-custom-card.tsx b/src/features/products/components/product-custom-card.tsx index 08008f9..ef131b3 100644 --- a/src/features/products/components/product-custom-card.tsx +++ b/src/features/products/components/product-custom-card.tsx @@ -5,6 +5,8 @@ import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@ type Template = NonNullable; +const freeEditLabel = (t: Template) => (t.freeEditEnabled ? '허용' : '허용 안 함'); + /** 커스텀 방식과 슬롯형 템플릿(바탕·자유 편집·문구 자리 스타일). 문구 자리 위치는 보이지 않는다 */ export function ProductCustomCard({ mode, @@ -13,6 +15,8 @@ export function ProductCustomCard({ mode: CustomModeType; template: Template | null; }) { + // 구매자는 슬롯형에서만 템플릿을 받아 그 밖의 방식에는 자유 편집이 없다 + const slot = mode === 'SLOT'; return ( @@ -22,10 +26,10 @@ export function ProductCustomCard({
    커스텀 방식
    {customModeLabel(mode)}
    - {template && ( + {slot && template && ( <>
    자유 편집
    -
    {template.freeEditEnabled ? '허용' : '허용 안 함'}
    +
    {freeEditLabel(template)}
    )}
    @@ -36,9 +40,9 @@ export function ProductCustomCard({

    )} {template ? ( - + ) : ( - mode === 'SLOT' &&

    등록된 템플릿이 없습니다.

    + slot &&

    등록된 템플릿이 없습니다.

    )}
    @@ -50,9 +54,10 @@ function TemplateSection({ template, unused }: { template: Template; unused: boo return ( <> {unused && ( -

    - 커스텀 방식이 슬롯형이 아니라 이 템플릿은 구매자에게 보이지 않습니다. -

    +
    +

    커스텀 방식이 슬롯형이 아니라 이 템플릿은 구매자에게 보이지 않습니다.

    +

    템플릿 자유 편집: {freeEditLabel(template)}

    +
    )} { expect(within(card).queryByText(/구매자에게 보이지 않습니다/)).not.toBeInTheDocument(); }); + const THREE_D_NOTE = + '모양·크기·맛·디자인은 옵션 선택지의 3D 연결로 고릅니다. 3D 상품에는 자유 편집이 없습니다.'; + const UNUSED_NOTE = '커스텀 방식이 슬롯형이 아니라 이 템플릿은 구매자에게 보이지 않습니다.'; it.each([ - [ - '3D는 옵션 3D 연결 안내만 보인다', - 'THREE_D', - null, - ['3D'], - '모양·크기·맛·디자인은 옵션 선택지의 3D 연결로 고릅니다. 3D 상품에는 자유 편집이 없습니다.', - ], + ['3D는 옵션 3D 연결 안내만 보인다', 'THREE_D', null, ['3D'], [THREE_D_NOTE]], [ '슬롯형인데 템플릿이 없으면 없다고 알린다', 'SLOT', null, ['슬롯형'], - '등록된 템플릿이 없습니다.', + ['등록된 템플릿이 없습니다.'], ], + ['방식이 없고 템플릿도 없으면 방식만 보인다', 'NONE', null, ['없음'], []], [ '슬롯형이 아닌데 남은 템플릿은 구매자에게 보이지 않는다고 알린다', 'NONE', { ...RICH.customTemplate!, freeEditEnabled: false }, - ['없음', '허용 안 함'], - '커스텀 방식이 슬롯형이 아니라 이 템플릿은 구매자에게 보이지 않습니다.', + ['없음'], + [UNUSED_NOTE, '템플릿 자유 편집: 허용 안 함'], + ], + [ + '3D에 남은 템플릿의 자유 편집 허용은 방식 아래가 아니라 남은 템플릿 안내에 보인다', + 'THREE_D', + RICH.customTemplate!, + ['3D'], + [THREE_D_NOTE, UNUSED_NOTE, '템플릿 자유 편집: 허용'], ], - ] as const)('상세: 커스텀 설정 — %s', async (_, customMode, customTemplate, defs, text) => { + ] as const)('상세: 커스텀 설정 — %s', async (_, customMode, customTemplate, defs, notes) => { server.use( gqlOk('AdminProduct', { adminProduct: detail({ product: { ...product(), customMode }, customTemplate }), @@ -458,7 +463,7 @@ describe('상품', () => { .getAllByRole('definition') .map((d) => d.textContent), ).toEqual(defs); - expect(within(card).getByText(text)).toBeInTheDocument(); + expect([...card.querySelectorAll('p')].map((p) => p.textContent)).toEqual(notes); }); it('상세: 분류·옵션·템플릿이 없으면 없다고 알린다', async () => { From 3cb6f7a8bd880fb663a5cc0a237d058357d92835 Mon Sep 17 00:00:00 2001 From: chanwoo7 Date: Thu, 19 Nov 2026 08:27:25 +0900 Subject: [PATCH 04/14] =?UTF-8?q?docs:=20=EA=B3=84=EC=A2=8C=EB=B2=88?= =?UTF-8?q?=ED=98=B8=20=EC=9B=90=EB=AC=B8=EC=9D=B4=20=EC=98=A4=EB=8A=94=20?= =?UTF-8?q?=EC=B2=98=EB=A6=AC=20mutation=20=EC=9D=91=EB=8B=B5=EB=8F=84=20?= =?UTF-8?q?=ED=91=9C=EC=8B=9C=20=EA=B7=9C=EC=B9=99=EC=97=90=20=ED=8F=AC?= =?UTF-8?q?=ED=95=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit D20 이유 칸이 원문이 오는 곳을 관리자 상세 조회 3곳으로만 적어, 화면 규칙(콘솔·오류·URL 금지)이 mutation 결과에도 적용된다는 점이 빠졌다. - 원문이 오는 곳에 adminMarkSettlementPaid(정산 상세 반환)·adminUpsertStoreSettlementAccount(정산 계좌 반환)를 더함 - 표 열 너비는 prettier가 다시 맞춤 테스트: 문서 변경만(format:check 통과). --- docs/guide/decisions.md | 46 ++++++++++++++++++++--------------------- 1 file changed, 23 insertions(+), 23 deletions(-) diff --git a/docs/guide/decisions.md b/docs/guide/decisions.md index 046977a..2236865 100644 --- a/docs/guide/decisions.md +++ b/docs/guide/decisions.md @@ -2,26 +2,26 @@ 확정된 결정만 적는다. 번호는 바꾸지 않고, 뒤집힌 결정은 줄을 긋지 않고 "대체됨 → D-n"으로 표시한다. 결정의 배경이 되는 구조 설명은 [architecture-conventions.md](./architecture-conventions.md). -| # | 일자 | 결정 | 이유 | -| --- | ---------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| D1 | 2026-09-27 | 레포 `CaQuick/caquick-admin-fe`(public), pnpm, Node 24 | 판매자 앱(`caquick-seller-fe`)과 이름 짝, FE-v2와 같은 pnpm | -| D2 | 2026-09-27 | Vite + React 19 + TypeScript strict SPA | 관리자 도구는 SSR이 필요 없고 정적 서빙이 배포에 가장 단순 | -| D3 | 2026-09-27 | TanStack Router(파일 기반) | 목록 필터·커서를 타입 있는 검색 파라미터로 URL에 유지 | -| D4 | 2026-09-27 | TanStack Query + graphql-request + graphql-codegen(client-preset) | 정규화 캐시 없이 invalidate로 충분한 CRUD 화면. 서버 진실 우선, 낙관적 업데이트 없음 | -| D5 | 2026-09-27 | Tailwind v4 + shadcn/ui(new-york, neutral) + TanStack Table + react-hook-form + zod, 차트 Recharts | FE-v2와 같은 스타일 체계. 컴포넌트는 레포가 소유(`src/shared/ui`) | -| D6 | 2026-09-27 | 디자인 토큰은 FE-v2 계승(primary #7c5cff 계열, gray 스케일, status 3색, radius 10px, Pretendard), 라이트/다크 | 서비스와 같은 브랜드 인상, 장시간 사용 도구라 다크 필요 | -| D7 | 2026-09-27 | Vitest + Testing Library + MSW. E2E 없음. 커버리지 lines/statements 80 · branches 70 · functions 80(대체됨 → D16), Codecov patch 80 | 관리자 도구 범위에 맞는 비용. shadcn 복사본은 커버리지 제외 | -| D8 | 2026-09-27 | 배포: 이 레포가 Dockerfile(nginx) · `infra/compose.yml` · `deploy.yml` 소유. GHCR `ghcr.io/caquick/caquick-admin-fe:`(arm64), 맥미니 셀프호스트 러너, BE compose 네트워크 `caquick_default`에 external 참여, 기존 cloudflared가 라우팅 | BE와 독립 배포·롤백. BE 레포 변경은 Tunnel 호스트 1줄 | -| D9 | 2026-09-27 | 도메인 `admin.caquick.site` → 컨테이너 `caquick-admin:80`. API `https://api.caquick.site` | 같은 부모 도메인이라 refresh 쿠키가 same-site로 전송된다 — 쿠키 도메인 변경 불필요, BE는 CORS 오리진만 추가 | -| D10 | 2026-09-27 | 인증: REST `/auth/admin/*`. accessToken은 메모리, refresh는 httpOnly 쿠키. 401이면 refresh 1회 후 재시도, 부팅 시 refresh로 복원, `mustChangePassword`면 변경 화면 강제 | 토큰을 localStorage에 두지 않는다(XSS 반경). 로컬은 Vite 프록시로 same-origin | -| D11 | 2026-09-27 | 머지 게이트는 BE와 동일: terraform ruleset(main·develop), 필수 체크 `check`·`pr-title`·`coverage-report`·`Analyze (javascript-typescript)`, Codex 상태기계(CodeRabbit은 대체됨 → D17) | 무인 진행의 전제 | -| D12 | 2026-09-27 | 릴리즈 순서: R1(기반·CI/CD·인증·셸·대시보드) → main → 영역별 PR → R2 | 배포 파이프라인·Tunnel·쿠키 문제를 가장 이른 시점에 실사이트에서 확인 | -| D13 | 2026-09-27 | BE SDL 스냅샷(`schema/schema.graphql`) 커밋 + `pnpm schema:pull`. CI는 codegen 신선도만 게이트, BE main과의 drift는 advisory | CI가 BE 체크아웃에 의존하지 않게 | -| D14 | 2026-09-27 | 문서: `CLAUDE.md`·`.claude/`·`AGENTS.md`·`docs/*`(guide 제외)·`.figma/` gitignore. `docs/guide/`·README 커밋 | BE와 같은 방식 | -| D15 | 2026-09-27 | 의존 방향은 ESLint boundaries로 강제(shared→features 금지, feature 간은 index.ts만). 검사기는 반증 케이스로 확인하고 넣는다 | BE `arch:check`와 같은 역할 | -| D16 | 2026-10-05 | 커버리지 임계를 실측 정수 내림으로 상향: statements 95 · branches 88 · functions 94 · lines 96. CI는 테스트를 3샤드로 나누고 coverage-report가 합친 결과로 검사 | 실측(95.54·88.07·94.29·96.07)보다 한참 낮은 임계는 회귀를 못 잡는다. 샤드 합산이 단일 실행과 같음을 확인 | -| D17 | 2026-10-06 | 리뷰 봇은 Codex만 쓴다. CodeRabbit은 BE 전용 — `.coderabbit.yaml`은 자동 리뷰를 끈 최소 설정만 둔다 | 사용자 결정(판매자 앱도 같음) | -| D18 | 2026-11-01 | 도메인을 `admin.caquick.com`·API `https://api.caquick.com`으로 옮긴다(D9 대체). 이미지 하나에 API 주소와 CSP가 같이 들어가므로 둘을 한 번에 바꾼다 | caquick.site 만료(2026-11-29). 관리자 웹과 API가 같은 사이트여야 refresh 쿠키가 실린다 | -| D19 | 2026-11-19 | 처리 대기 허브는 `/tasks`(탭 입금·환불·정산 송금)다. BE 경보 딥링크 계약은 `/tasks/deposits?orderId=`·`/tasks/refunds?refundId=`·`/tasks/settlements?periodStart=YYYY-MM-DD`(KST 월요일)이고, 딥링크 ID가 있으면 그 건의 시트를 바로 연다. 세션이 없으면 로그인 뒤 같은 주소로 돌아온다. 건수는 `adminTaskCounts`가 진실이다(60초 폴링 + 창 포커스 재조회) | BE `ADMIN_WEB_BASE_URL` 경보가 이 주소를 만든다. 주소를 바꾸면 BE 경보 문구 helper와 같이 바꾼다. 디스코드 알림은 다시 올 수 있어 목록과 건수를 진실로 둔다 | -| D20 | 2026-11-19 | 계좌번호(환불·정산·입금 계좌)는 목록에서 마스킹(`****1234`)만 보이고, 전체 번호는 단건 시트·상세에서만 복사 버튼과 함께 보인다. 전체 번호를 콘솔·오류 메시지·URL에 남기지 않는다 | BE는 원문을 관리자 상세 조회 3곳(`adminRefund`·`adminSettlement`·`adminStoreSettlementAccount`)에서만 복호화한다. 화면이 노출 범위를 넓히면 암호화 저장이 의미를 잃는다 | -| D21 | 2026-11-19 | 커스텀 주문은 렌더러 없이 이미지로 확인한다. 3D는 렌더 5장(윗면 크게 → 앞·뒤·왼·오), 슬롯형은 합성 이미지 + 문구 자리 표, 자유 편집은 바탕 위 번호 영역(0~10000 → %)이다. 커스텀 enum 라벨은 `Record` + 모르는 값 원문 폴백 | 3D 렌더러는 판매자 앱만 갖는다. 관리자는 문의·분쟁 확인용이라 구매자가 본 그대로의 캡처면 충분하다 | +| # | 일자 | 결정 | 이유 | +| --- | ---------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| D1 | 2026-09-27 | 레포 `CaQuick/caquick-admin-fe`(public), pnpm, Node 24 | 판매자 앱(`caquick-seller-fe`)과 이름 짝, FE-v2와 같은 pnpm | +| D2 | 2026-09-27 | Vite + React 19 + TypeScript strict SPA | 관리자 도구는 SSR이 필요 없고 정적 서빙이 배포에 가장 단순 | +| D3 | 2026-09-27 | TanStack Router(파일 기반) | 목록 필터·커서를 타입 있는 검색 파라미터로 URL에 유지 | +| D4 | 2026-09-27 | TanStack Query + graphql-request + graphql-codegen(client-preset) | 정규화 캐시 없이 invalidate로 충분한 CRUD 화면. 서버 진실 우선, 낙관적 업데이트 없음 | +| D5 | 2026-09-27 | Tailwind v4 + shadcn/ui(new-york, neutral) + TanStack Table + react-hook-form + zod, 차트 Recharts | FE-v2와 같은 스타일 체계. 컴포넌트는 레포가 소유(`src/shared/ui`) | +| D6 | 2026-09-27 | 디자인 토큰은 FE-v2 계승(primary #7c5cff 계열, gray 스케일, status 3색, radius 10px, Pretendard), 라이트/다크 | 서비스와 같은 브랜드 인상, 장시간 사용 도구라 다크 필요 | +| D7 | 2026-09-27 | Vitest + Testing Library + MSW. E2E 없음. 커버리지 lines/statements 80 · branches 70 · functions 80(대체됨 → D16), Codecov patch 80 | 관리자 도구 범위에 맞는 비용. shadcn 복사본은 커버리지 제외 | +| D8 | 2026-09-27 | 배포: 이 레포가 Dockerfile(nginx) · `infra/compose.yml` · `deploy.yml` 소유. GHCR `ghcr.io/caquick/caquick-admin-fe:`(arm64), 맥미니 셀프호스트 러너, BE compose 네트워크 `caquick_default`에 external 참여, 기존 cloudflared가 라우팅 | BE와 독립 배포·롤백. BE 레포 변경은 Tunnel 호스트 1줄 | +| D9 | 2026-09-27 | 도메인 `admin.caquick.site` → 컨테이너 `caquick-admin:80`. API `https://api.caquick.site` | 같은 부모 도메인이라 refresh 쿠키가 same-site로 전송된다 — 쿠키 도메인 변경 불필요, BE는 CORS 오리진만 추가 | +| D10 | 2026-09-27 | 인증: REST `/auth/admin/*`. accessToken은 메모리, refresh는 httpOnly 쿠키. 401이면 refresh 1회 후 재시도, 부팅 시 refresh로 복원, `mustChangePassword`면 변경 화면 강제 | 토큰을 localStorage에 두지 않는다(XSS 반경). 로컬은 Vite 프록시로 same-origin | +| D11 | 2026-09-27 | 머지 게이트는 BE와 동일: terraform ruleset(main·develop), 필수 체크 `check`·`pr-title`·`coverage-report`·`Analyze (javascript-typescript)`, Codex 상태기계(CodeRabbit은 대체됨 → D17) | 무인 진행의 전제 | +| D12 | 2026-09-27 | 릴리즈 순서: R1(기반·CI/CD·인증·셸·대시보드) → main → 영역별 PR → R2 | 배포 파이프라인·Tunnel·쿠키 문제를 가장 이른 시점에 실사이트에서 확인 | +| D13 | 2026-09-27 | BE SDL 스냅샷(`schema/schema.graphql`) 커밋 + `pnpm schema:pull`. CI는 codegen 신선도만 게이트, BE main과의 drift는 advisory | CI가 BE 체크아웃에 의존하지 않게 | +| D14 | 2026-09-27 | 문서: `CLAUDE.md`·`.claude/`·`AGENTS.md`·`docs/*`(guide 제외)·`.figma/` gitignore. `docs/guide/`·README 커밋 | BE와 같은 방식 | +| D15 | 2026-09-27 | 의존 방향은 ESLint boundaries로 강제(shared→features 금지, feature 간은 index.ts만). 검사기는 반증 케이스로 확인하고 넣는다 | BE `arch:check`와 같은 역할 | +| D16 | 2026-10-05 | 커버리지 임계를 실측 정수 내림으로 상향: statements 95 · branches 88 · functions 94 · lines 96. CI는 테스트를 3샤드로 나누고 coverage-report가 합친 결과로 검사 | 실측(95.54·88.07·94.29·96.07)보다 한참 낮은 임계는 회귀를 못 잡는다. 샤드 합산이 단일 실행과 같음을 확인 | +| D17 | 2026-10-06 | 리뷰 봇은 Codex만 쓴다. CodeRabbit은 BE 전용 — `.coderabbit.yaml`은 자동 리뷰를 끈 최소 설정만 둔다 | 사용자 결정(판매자 앱도 같음) | +| D18 | 2026-11-01 | 도메인을 `admin.caquick.com`·API `https://api.caquick.com`으로 옮긴다(D9 대체). 이미지 하나에 API 주소와 CSP가 같이 들어가므로 둘을 한 번에 바꾼다 | caquick.site 만료(2026-11-29). 관리자 웹과 API가 같은 사이트여야 refresh 쿠키가 실린다 | +| D19 | 2026-11-19 | 처리 대기 허브는 `/tasks`(탭 입금·환불·정산 송금)다. BE 경보 딥링크 계약은 `/tasks/deposits?orderId=`·`/tasks/refunds?refundId=`·`/tasks/settlements?periodStart=YYYY-MM-DD`(KST 월요일)이고, 딥링크 ID가 있으면 그 건의 시트를 바로 연다. 세션이 없으면 로그인 뒤 같은 주소로 돌아온다. 건수는 `adminTaskCounts`가 진실이다(60초 폴링 + 창 포커스 재조회) | BE `ADMIN_WEB_BASE_URL` 경보가 이 주소를 만든다. 주소를 바꾸면 BE 경보 문구 helper와 같이 바꾼다. 디스코드 알림은 다시 올 수 있어 목록과 건수를 진실로 둔다 | +| D20 | 2026-11-19 | 계좌번호(환불·정산·입금 계좌)는 목록에서 마스킹(`****1234`)만 보이고, 전체 번호는 단건 시트·상세에서만 복사 버튼과 함께 보인다. 전체 번호를 콘솔·오류 메시지·URL에 남기지 않는다 | BE는 원문을 관리자 상세 조회 3곳(`adminRefund`·`adminSettlement`·`adminStoreSettlementAccount`)과 그 처리 mutation 응답(`adminMarkSettlementPaid`·`adminUpsertStoreSettlementAccount`)에만 담는다. 화면이 노출 범위를 넓히면 암호화 저장이 의미를 잃는다 | +| D21 | 2026-11-19 | 커스텀 주문은 렌더러 없이 이미지로 확인한다. 3D는 렌더 5장(윗면 크게 → 앞·뒤·왼·오), 슬롯형은 합성 이미지 + 문구 자리 표, 자유 편집은 바탕 위 번호 영역(0~10000 → %)이다. 커스텀 enum 라벨은 `Record` + 모르는 값 원문 폴백 | 3D 렌더러는 판매자 앱만 갖는다. 관리자는 문의·분쟁 확인용이라 구매자가 본 그대로의 캡처면 충분하다 | From 960abdc738812412621d016a9ca0cce83534d2c0 Mon Sep 17 00:00:00 2001 From: chanwoo7 Date: Thu, 19 Nov 2026 08:52:32 +0900 Subject: [PATCH 05/14] =?UTF-8?q?feat:=20=EC=A3=BC=EB=AC=B8=20=EC=9E=85?= =?UTF-8?q?=EA=B8=88=20=EB=8C=80=EA=B8=B0=C2=B7=EB=85=B8=EC=87=BC=20?= =?UTF-8?q?=EC=83=81=ED=83=9C=EC=99=80=20=EA=B2=B0=EC=A0=9C=C2=B7=ED=99=98?= =?UTF-8?q?=EB=B6=88=C2=B7=EC=A0=95=EC=82=B0=20=EC=B9=B4=EB=93=9C,=20?= =?UTF-8?q?=EA=B0=95=EC=A0=9C=20=EC=B7=A8=EC=86=8C=20=EC=82=AC=EC=9C=A0?= =?UTF-8?q?=C2=B7=ED=99=98=EB=B6=88=20=EA=B8=88=EC=95=A1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 계좌이체 결제·취소 사유·노쇼·자동 전이·정산이 들어온 BE 주문을 관리자가 한 화면에서 보고 처리할 수 있게 한다. 지금 취소 다이얼로그는 사유 OTHER만 보내 확정·제작 완료 주문을 취소할 수 없었고(버튼을 숨겨 둠), 숨김 매장의 확정·제작 완료 주문은 자동 픽업 완료가 돌지 않아 관리자가 처리할 수단이 필요했다. - 상태: 7종 라벨·톤(입금 대기 neutral, 접수 primary, 주문 확정 caution, 제작 완료 neutral, 픽업 완료 positive, 노쇼·취소 negative)을 Record로 두고 모르는 값은 원문 폴백. 목록 필터에 '진행 중' 칩(inProgress, URL 유지) - 강제 취소: 버튼 노출과 선택지는 cancelOptions가 정한다. 사유 필수(선택지만), 사정은 BY_FAULT일 때만, 환불 금액은 구매자 사정일 때만 0~paidAmount 정수와 [전액]·[0원], 요약 문구. 입력 조립은 buildCancelInput 순수 함수, 메모는 BE처럼 코드 포인트로 500자 - 픽업 완료: 확정·제작 완료 주문에 [픽업 완료](adminCompleteOrderPickup, 메모 선택) 확인 다이얼로그를 [강제 취소]와 나란히. ORDER_STATUS_UNCHANGED·INVALID_ORDER_STATUS_TRANSITION은 버튼 맥락 문구로 알림 - 처리 뒤: 성공이든 거절이든 상세·목록을 다시 불러 바뀐 상태·선택지를 보인다 - 상세 카드: 결제(수단·상태·입금자명·입금 계좌 끝 4자리·기한·'입금했어요'·확인 처리자·메모), 취소(주체·사유·사정·환불액·환불 상태·메모), 환불 목록(종류 칩·상태·마스킹 계좌·요청/계좌 입력/송금 시각), 정산(주문 시점 수수료율·정산 예정/지급액·기준액·수수료·확정 시각·주간 정산), 요청 사항, 판매자 픽업 일시 변경 이력 - 진행 상태: 입금 대기 단계(결제 도입 전 주문은 접수부터), 노쇼 종료 표시, 자동 처리 예정(입금 기한·'입금했어요' 뒤 자동 취소 제외·확정 마감·자동 픽업 완료, 숨김 매장은 직접 처리 안내) - 상태 이력: 주체 배지, 취소 이력의 사유·사정·환불액 - 대시보드: 주문 건수 키와 상태를 dashboard/order-count-keys.ts 한 곳에서 잇고(입금 대기·노쇼 추가) KPI 합계·상태 분포가 같이 쓴다. 주문 금액 라벨은 BE 기준대로 '취소·입금 대기 제외' - 스키마는 BE develop(b2ee9d3) 스냅샷 그대로이고 조회 문서만 늘림(codegen) 테스트: cancel-form 표(환불 규칙 3 × 사정 3 × 금액 9 = 81건, '0' 유효, 결제액 0, 선택지 밖 사유·프로토타입 키, 메모 이모지 500자·501자), 요약 문구 9건과 요약 없음 2경우, 상태 7종 표·모르는 값, 라벨 표 전수·폴백, 수수료율 0~10000bp 전수, 자동 처리 예정 8건, 검색 inProgress 5건. 페이지: 접수 취소(사유 선택·메모 코드 포인트·이력 갱신), 확정 취소(사정 필수·판매자 사정·금액 범위·[전액]·[0원]으로 0 전송), 입금 대기 미입금 취소, 취소·픽업 불가 상태 2건, 픽업 완료 2건·거절 3건(재조회), 결제·정산 카드와 계좌 마스킹, 숨김 매장 안내, 취소·환불·정산 확정·요청 사항·픽업 변경, 결제 도입 전 주문, 목록 진행 중 칩·상태 7종, 대시보드 7개 상태 순서. 반증: 사정 규칙·금액 상한·'0' falsy·코드 포인트·선택지 밖 사유·hasOwn 폴백 2곳·픽업 완료 상태·숨김 매장·inProgress 'false'·실패 시 재조회·cancelable 게이트·계좌 마스킹을 하나씩 되돌리면 각각 30·4·2·2·2·1·6·1·1·2·4·3·1건이 실패하고, 건수 키 하나를 빼면 tsc가 깨진다. --- .../audit-logs/pages/audit-logs.spec.tsx | 15 + src/features/dashboard/api/queries.ts | 2 + .../dashboard/components/kpi-tiles.tsx | 6 +- .../components/order-status-chart.tsx | 22 +- src/features/dashboard/order-count-keys.ts | 25 + .../dashboard/pages/dashboard-page.spec.tsx | 31 +- src/features/orders/api/queries.ts | 134 ++++- src/features/orders/auto-transition.spec.ts | 67 +++ src/features/orders/auto-transition.ts | 25 + src/features/orders/cancel-form.spec.ts | 158 +++++ src/features/orders/cancel-form.ts | 82 +++ .../orders/components/cancel-order-dialog.tsx | 167 +++++- .../components/complete-pickup-dialog.tsx | 44 ++ .../components/order-detail-sections.tsx | 110 +++- .../components/order-money-sections.tsx | 188 ++++++ .../orders/components/orders-filter-bar.tsx | 20 +- src/features/orders/meta.spec.ts | 84 +++ src/features/orders/meta.ts | 74 +++ .../orders/pages/order-detail-page.tsx | 28 +- src/features/orders/pages/orders.spec.tsx | 567 +++++++++++++++++- src/features/orders/search.spec.ts | 17 + src/features/orders/search.ts | 9 +- src/features/orders/status.spec.ts | 54 +- src/features/orders/status.ts | 35 +- src/graphql/generated/gql.ts | 24 +- src/graphql/generated/graphql.ts | 161 ++++- 26 files changed, 1996 insertions(+), 153 deletions(-) create mode 100644 src/features/dashboard/order-count-keys.ts create mode 100644 src/features/orders/auto-transition.spec.ts create mode 100644 src/features/orders/auto-transition.ts create mode 100644 src/features/orders/cancel-form.spec.ts create mode 100644 src/features/orders/cancel-form.ts create mode 100644 src/features/orders/components/complete-pickup-dialog.tsx create mode 100644 src/features/orders/components/order-money-sections.tsx create mode 100644 src/features/orders/meta.spec.ts create mode 100644 src/features/orders/meta.ts diff --git a/src/features/audit-logs/pages/audit-logs.spec.tsx b/src/features/audit-logs/pages/audit-logs.spec.tsx index 6bd30bf..ae8b46a 100644 --- a/src/features/audit-logs/pages/audit-logs.spec.tsx +++ b/src/features/audit-logs/pages/audit-logs.spec.tsx @@ -316,6 +316,21 @@ describe('감사 로그', () => { updatedAt: '2026-09-27T02:34:00.000Z', items: [], statusHistories: [], + requestNote: null, + payment: null, + refunds: [], + cancellation: null, + cancelOptions: { cancelable: false, reasons: [], refundRule: null, paidAmount: 0 }, + confirmDeadlineAt: null, + autoPickupAt: null, + noShowAt: null, + pickupChanges: [], + commissionRateBps: 0, + expectedPayoutAmount: null, + settlementBaseAmount: null, + commissionAmount: null, + settlementFinalizedAt: null, + settlementId: null, }, }), ); diff --git a/src/features/dashboard/api/queries.ts b/src/features/dashboard/api/queries.ts index d4cdb5f..a14a6e2 100644 --- a/src/features/dashboard/api/queries.ts +++ b/src/features/dashboard/api/queries.ts @@ -18,10 +18,12 @@ const AdminDashboardSummaryDocument = graphql(/* GraphQL */ ` newUserCount newSellerCount orderCounts { + pendingPayment submitted confirmed made pickedUp + noShow canceled } orderAmountSum diff --git a/src/features/dashboard/components/kpi-tiles.tsx b/src/features/dashboard/components/kpi-tiles.tsx index b083e40..673a1fc 100644 --- a/src/features/dashboard/components/kpi-tiles.tsx +++ b/src/features/dashboard/components/kpi-tiles.tsx @@ -3,6 +3,7 @@ import { Link } from '@tanstack/react-router'; import { formatCount, formatKrw } from '@/shared/lib/format'; import { Card } from '@/shared/ui/card'; +import { orderCountTotal } from '../order-count-keys'; import { type DashboardSummary } from './types'; function Tile({ @@ -36,12 +37,11 @@ function Tile({ } export function KpiTiles({ summary }: { summary: DashboardSummary }) { - const c = summary.orderCounts; - const orderTotal = c.submitted + c.confirmed + c.made + c.pickedUp + c.canceled; + const orderTotal = orderCountTotal(summary.orderCounts); return (
    diff --git a/src/features/dashboard/components/order-status-chart.tsx b/src/features/dashboard/components/order-status-chart.tsx index 16edf32..902b35c 100644 --- a/src/features/dashboard/components/order-status-chart.tsx +++ b/src/features/dashboard/components/order-status-chart.tsx @@ -11,24 +11,19 @@ import { } from 'recharts'; import { orderStatusMeta } from '@/features/orders'; -import { type OrderStatusType } from '@/graphql/generated/graphql'; import { formatCount } from '@/shared/lib/format'; import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/shared/ui/card'; +import { ORDER_COUNT_KEYS } from '../order-count-keys'; import { type DashboardSummary } from './types'; -// 라벨은 주문 화면과 한 벌(주문 확정 등) -const STATUS: { key: keyof DashboardSummary['orderCounts']; status: OrderStatusType }[] = [ - { key: 'submitted', status: 'SUBMITTED' }, - { key: 'confirmed', status: 'CONFIRMED' }, - { key: 'made', status: 'MADE' }, - { key: 'pickedUp', status: 'PICKED_UP' }, - { key: 'canceled', status: 'CANCELED' }, -]; +// 흐름 밖에서 끝난 상태는 회색으로 가른다 +const MUTED = new Set(['noShow', 'canceled']); -/** 기간 내 주문 상태 분포. 단일 계열(진행 단계)이라 색 1개, 취소만 회색. 표는 스크린리더·색각 보조용. */ +/** 기간 내 주문 상태 분포. 단일 계열(진행 단계)이라 색 1개, 노쇼·취소만 회색. 표는 스크린리더·색각 보조용. */ export function OrderStatusChart({ summary }: { summary: DashboardSummary }) { - const data = STATUS.map((s) => ({ + // 라벨은 주문 화면과 한 벌(주문 확정 등) + const data = ORDER_COUNT_KEYS.map((s) => ({ key: s.key, label: orderStatusMeta(s.status).label, count: summary.orderCounts[s.key], @@ -73,10 +68,7 @@ export function OrderStatusChart({ summary }: { summary: DashboardSummary }) { /> {data.map((d) => ( - + ))} = { + pendingPayment: 'PENDING_PAYMENT', + submitted: 'SUBMITTED', + confirmed: 'CONFIRMED', + made: 'MADE', + pickedUp: 'PICKED_UP', + noShow: 'NO_SHOW', + canceled: 'CANCELED', +}; + +/** 흐름 순서(차트 막대 순서) */ +export const ORDER_COUNT_KEYS = (Object.keys(STATUS_BY_KEY) as CountKey[]).map((key) => ({ + key, + status: STATUS_BY_KEY[key], +})); + +export const orderCountTotal = (counts: DashboardSummary['orderCounts']) => + ORDER_COUNT_KEYS.reduce((sum, { key }) => sum + counts[key], 0); diff --git a/src/features/dashboard/pages/dashboard-page.spec.tsx b/src/features/dashboard/pages/dashboard-page.spec.tsx index bff5430..5df2093 100644 --- a/src/features/dashboard/pages/dashboard-page.spec.tsx +++ b/src/features/dashboard/pages/dashboard-page.spec.tsx @@ -22,7 +22,15 @@ const summary = { to: 'y', newUserCount: 128, newSellerCount: 3, - orderCounts: { submitted: 21, confirmed: 34, made: 18, pickedUp: 78, canceled: 12 }, + orderCounts: { + pendingPayment: 5, + submitted: 21, + confirmed: 34, + made: 18, + pickedUp: 78, + noShow: 2, + canceled: 12, + }, orderAmountSum: 4812000, activeStoreCount: 42, activeProductCount: 517, @@ -66,7 +74,7 @@ describe('DashboardPage', () => { ); boot(); expect(await screen.findByText('4,812,000원')).toBeInTheDocument(); - expect(screen.getByText('주문 163건')).toBeInTheDocument(); + expect(screen.getByText('주문 170건')).toBeInTheDocument(); expect(screen.getByText('7건')).toBeInTheDocument(); expect(screen.getByRole('link', { name: '처리 필요' })).toHaveAttribute('href', '/reports'); const table = screen.getByRole('table', { name: '주문 상태별 건수' }); @@ -91,10 +99,12 @@ describe('DashboardPage', () => { ); it.each([ + ['입금 대기', '5건'], ['접수', '21건'], ['주문 확정', '34건'], ['제작 완료', '18건'], ['픽업 완료', '78건'], + ['노쇼', '2건'], ['취소', '12건'], ])('상태 분포 표에서 %s는 %s', async (label, count) => { server.use( @@ -107,9 +117,24 @@ describe('DashboardPage', () => { expect(header.closest('tr')).toHaveTextContent(`${label}${count}`); }); + it('상태 분포는 흐름 순서 뒤에 종료 상태로 7개 상태를 모두 싣고 주문 금액은 입금 대기를 뺀다', async () => { + server.use( + gqlOk('AdminDashboardSummary', { adminDashboardSummary: summary }), + gqlOk('AdminSearchKeywordSnapshot', { adminSearchKeywordSnapshot: snapshot }), + ); + boot(); + const table = await screen.findByRole('table', { name: '주문 상태별 건수' }); + expect( + within(table) + .getAllByRole('rowheader') + .map((h) => h.textContent), + ).toEqual(['입금 대기', '접수', '주문 확정', '제작 완료', '픽업 완료', '노쇼', '취소']); + expect(screen.getByText('주문 금액 (취소·입금 대기 제외)')).toBeInTheDocument(); + }); + // CardHeader는 grid라 flex-row를 덧붙여도 한 줄이 되지 않았다. 보조 문구는 CardDescription 자리에 둔다 it.each([ - ['주문 상태 분포', '기간 내 주문 163건'], + ['주문 상태 분포', '기간 내 주문 170건'], ['검색어 순위', '09-27 17:00 기준 집계'], ])('%s 카드의 보조 문구는 카드 설명 자리에 있다', async (title, caption) => { server.use( diff --git a/src/features/orders/api/queries.ts b/src/features/orders/api/queries.ts index cb08804..dacb707 100644 --- a/src/features/orders/api/queries.ts +++ b/src/features/orders/api/queries.ts @@ -1,7 +1,7 @@ import { type QueryClient, queryOptions } from '@tanstack/react-query'; import { graphql } from '@/graphql/generated'; -import { type AdminOrderListInput } from '@/graphql/generated/graphql'; +import { type AdminCancelOrderInput, type AdminOrderListInput } from '@/graphql/generated/graphql'; import { gqlRequest } from '@/shared/api'; import { type EntityOption } from '@/shared/ui/entity-picker'; @@ -14,7 +14,7 @@ const ordersKeys = { // 필터 선택기·링크 이름. 매장·구매자 화면의 캐시와 섞이지 않게 주문 아래에 둔다 storeOptions: (keyword: string) => [...ordersKeys.all, 'store-options', keyword] as const, buyerOptions: (keyword: string) => [...ordersKeys.all, 'buyer-options', keyword] as const, - storeName: (storeId: string) => [...ordersKeys.all, 'store-name', storeId] as const, + store: (storeId: string) => [...ordersKeys.all, 'store', storeId] as const, buyerName: (accountId: string) => [...ordersKeys.all, 'buyer-name', accountId] as const, }; @@ -57,6 +57,25 @@ const AdminOrderDocument = graphql(/* GraphQL */ ` pickupAt buyerName buyerPhone + requestNote + payment { + method + status + amount + depositorName + depositBank { + code + name + } + depositAccountNumber + depositAccountHolder + expiresAt + buyerClaimedAt + confirmedAt + confirmSource + confirmedByLabel + confirmNote + } subtotalPrice discountPrice totalPrice @@ -125,7 +144,59 @@ const AdminOrderDocument = graphql(/* GraphQL */ ` toStatus changedAt note + actorType + cancelReason + cancelFault + refundAmount + } + refunds { + id + kind + amount + status + bank { + code + name + } + accountHolder + accountNumberMasked + requestedAt + accountSubmittedAt + completedAt + } + cancellation { + actorType + reason + reasonLabel + note + fault + refundAmount + refundStatus + refundCompletedAt + canceledAt + } + cancelOptions { + cancelable + reasons + refundRule + paidAmount + } + confirmDeadlineAt + autoPickupAt + noShowAt + pickupChanges { + id + fromPickupAt + toPickupAt + changedAt + note } + commissionRateBps + expectedPayoutAmount + settlementBaseAmount + commissionAmount + settlementFinalizedAt + settlementId } } `); @@ -163,6 +234,7 @@ const AdminOrdersStoreNameDocument = graphql(/* GraphQL */ ` store { id storeName + isActive } } } @@ -188,6 +260,15 @@ const AdminCancelOrderDocument = graphql(/* GraphQL */ ` } `); +const AdminCompleteOrderPickupDocument = graphql(/* GraphQL */ ` + mutation AdminCompleteOrderPickup($input: AdminCompleteOrderPickupInput!) { + adminCompleteOrderPickup(input: $input) { + id + status + } + } +`); + export function ordersListQueryOptions(input: AdminOrderListInput) { return queryOptions({ queryKey: ordersKeys.list(input), @@ -248,12 +329,12 @@ export function buyerOptionsQueryOptions(keyword: string) { }); } -/** 주소로 들어온 매장 ID의 이름. 찾지 못하면 오류로 두고 부르는 쪽은 #ID를 보인다 */ -export function storeNameQueryOptions(storeId: string) { +/** 매장 이름·숨김 여부. 찾지 못하면 오류로 두고 부르는 쪽은 #ID를 보인다 */ +export function storeRefQueryOptions(storeId: string) { return queryOptions({ - queryKey: ordersKeys.storeName(storeId), + queryKey: ordersKeys.store(storeId), queryFn: async () => - (await gqlRequest(AdminOrdersStoreNameDocument, { storeId })).adminStore.store.storeName, + (await gqlRequest(AdminOrdersStoreNameDocument, { storeId })).adminStore.store, retry: false, }); } @@ -267,14 +348,35 @@ export function buyerNameQueryOptions(accountId: string) { }); } -/** 사유 코드 선택은 아직 없어 '기타' + 입력한 메모로 보낸다 */ -export async function cancelOrder(queryClient: QueryClient, orderId: string, note: string) { - const result = ( - await gqlRequest(AdminCancelOrderDocument, { input: { orderId, reason: 'OTHER', note } }) - ).adminCancelOrder; - await Promise.all([ - queryClient.invalidateQueries({ queryKey: ordersKeys.detail(orderId) }), - queryClient.invalidateQueries({ queryKey: ordersKeys.lists() }), - ]); - return result; +/** 처리했든 거절됐든(다른 곳에서 상태가 바뀐 경우 등) 상세·목록을 다시 불러 지금 상태와 선택지를 보인다 */ +async function withRefresh(queryClient: QueryClient, orderId: string, run: () => Promise) { + try { + return await run(); + } finally { + await Promise.all([ + queryClient.invalidateQueries({ queryKey: ordersKeys.detail(orderId) }), + queryClient.invalidateQueries({ queryKey: ordersKeys.lists() }), + ]); + } +} + +export function cancelOrder(queryClient: QueryClient, input: AdminCancelOrderInput) { + return withRefresh( + queryClient, + String(input.orderId), + async () => (await gqlRequest(AdminCancelOrderDocument, { input })).adminCancelOrder, + ); +} + +export function completeOrderPickup(queryClient: QueryClient, orderId: string, note: string) { + return withRefresh( + queryClient, + orderId, + async () => + ( + await gqlRequest(AdminCompleteOrderPickupDocument, { + input: { orderId, note: note || null }, + }) + ).adminCompleteOrderPickup, + ); } diff --git a/src/features/orders/auto-transition.spec.ts b/src/features/orders/auto-transition.spec.ts new file mode 100644 index 0000000..6290fcb --- /dev/null +++ b/src/features/orders/auto-transition.spec.ts @@ -0,0 +1,67 @@ +import { type OrderStatusType } from '@/graphql/generated/graphql'; + +import { autoTransitionNote } from './auto-transition'; + +const payment = (buyerClaimedAt: string | null) => ({ + method: 'BANK_TRANSFER' as const, + status: 'PENDING' as const, + amount: 30000, + depositorName: '김서연', + depositAccountNumber: '1002123456789', + depositAccountHolder: '케이퀵', + expiresAt: '2026-11-19T01:00:00.000Z', + buyerClaimedAt, + confirmedAt: null, + confirmSource: null, + confirmedByLabel: null, + confirmNote: null, + depositBank: { code: '020', name: '우리은행' }, +}); +const order = (status: OrderStatusType, patch: object = {}) => ({ + status, + payment: payment(null), + confirmDeadlineAt: null, + autoPickupAt: null, + ...patch, +}); +const AT = '2026-11-20T05:00:00.000Z'; + +describe('autoTransitionNote', () => { + it.each([ + [ + '입금 대기는 입금 기한', + order('PENDING_PAYMENT'), + false, + '11-19 10:00까지 입금이 확인되지 않으면 자동 취소됩니다.', + ], + [ + "'입금했어요'를 누른 입금 대기는 자동 취소에서 빠진다", + order('PENDING_PAYMENT', { payment: payment('2026-11-19T00:30:00.000Z') }), + false, + '구매자가 11-19 09:30에 입금했다고 알려 자동 취소되지 않습니다. 입금을 확인하거나 미입금으로 취소하세요.', + ], + [ + '접수는 확정 마감', + order('SUBMITTED', { confirmDeadlineAt: AT }), + true, + '11-20 14:00까지 판매자가 확정하지 않으면 자동 취소·전액 환불됩니다.', + ], + [ + '확정은 자동 픽업 완료', + order('CONFIRMED', { autoPickupAt: AT }), + false, + '11-20 14:00에 자동으로 픽업 완료됩니다.', + ], + [ + '숨김 매장의 제작 완료는 직접 처리 안내', + order('MADE', { autoPickupAt: AT }), + true, + '매장이 숨김이라 11-20 14:00에 자동 픽업 완료되지 않습니다. 픽업 완료나 강제 취소로 직접 처리하세요.', + ], + ['결제 도입 전 입금 대기는 없음', order('PENDING_PAYMENT', { payment: null }), false, null], + ['결제 도입 전 접수(마감 null)는 없음', order('SUBMITTED'), false, null], + ['종료 상태는 없음', order('PICKED_UP'), false, null], + ])('%s', (_, o, hidden, note) => { + expect(autoTransitionNote(o, hidden)).toBe(note); + }); +}); diff --git a/src/features/orders/auto-transition.ts b/src/features/orders/auto-transition.ts new file mode 100644 index 0000000..bc4166c --- /dev/null +++ b/src/features/orders/auto-transition.ts @@ -0,0 +1,25 @@ +import { type AdminOrderQuery } from '@/graphql/generated/graphql'; +import { formatKst } from '@/shared/lib/kst'; + +type Order = Pick< + AdminOrderQuery['adminOrder'], + 'status' | 'payment' | 'confirmDeadlineAt' | 'autoPickupAt' +>; + +/** 지금 상태에서 시스템이 언제 무엇을 할지. 숨김 매장은 자동 픽업 완료가 돌지 않는다 */ +export function autoTransitionNote(o: Order, storeHidden: boolean): string | null { + if (o.status === 'PENDING_PAYMENT' && o.payment) { + return o.payment.buyerClaimedAt + ? `구매자가 ${formatKst(o.payment.buyerClaimedAt)}에 입금했다고 알려 자동 취소되지 않습니다. 입금을 확인하거나 미입금으로 취소하세요.` + : `${formatKst(o.payment.expiresAt)}까지 입금이 확인되지 않으면 자동 취소됩니다.`; + } + if (o.status === 'SUBMITTED' && o.confirmDeadlineAt) { + return `${formatKst(o.confirmDeadlineAt)}까지 판매자가 확정하지 않으면 자동 취소·전액 환불됩니다.`; + } + if (o.autoPickupAt) { + return storeHidden + ? `매장이 숨김이라 ${formatKst(o.autoPickupAt)}에 자동 픽업 완료되지 않습니다. 픽업 완료나 강제 취소로 직접 처리하세요.` + : `${formatKst(o.autoPickupAt)}에 자동으로 픽업 완료됩니다.`; + } + return null; +} diff --git a/src/features/orders/cancel-form.spec.ts b/src/features/orders/cancel-form.spec.ts new file mode 100644 index 0000000..9468ee8 --- /dev/null +++ b/src/features/orders/cancel-form.spec.ts @@ -0,0 +1,158 @@ +import { type CancelRefundRuleType } from '@/graphql/generated/graphql'; + +import { + CANCEL_NOTE_MAX, + type CancelForm, + type CancelOptions, + EMPTY_CANCEL_FORM, + buildCancelInput, + cancelSummary, + noteLength, + parseRefundAmount, +} from './cancel-form'; + +const PAID = 30000; +const options = (refundRule: CancelRefundRuleType | null, paidAmount = PAID): CancelOptions => ({ + cancelable: refundRule !== null, + reasons: ['OUT_OF_MATERIALS', 'OTHER'], + refundRule, + paidAmount, +}); +const form = (patch: Partial = {}): CancelForm => ({ + ...EMPTY_CANCEL_FORM, + reason: 'OTHER', + ...patch, +}); +const base = { orderId: '0', reason: 'OTHER', note: null }; + +describe('buildCancelInput', () => { + const FAULTS = ['', 'SELLER', 'BUYER'] as const; + const AMOUNTS = ['', '0', ' 7 ', '30000', '30001', '-1', '1.5', '1e3', '3']; + + /** 기대값은 구현과 따로: BY_FAULT만 사정을 묻고, 구매자 사정만 0~결제액 정수 금액을 받는다 */ + function expected(rule: CancelRefundRuleType, fault: string, amount: string) { + if (rule !== 'BY_FAULT') return { input: base }; + if (fault === '') return { issue: 'FAULT_REQUIRED' }; + if (fault === 'SELLER') return { input: { ...base, fault: 'SELLER' } }; + if (amount === '') return { issue: 'AMOUNT_REQUIRED' }; + const ok: Record = { '0': 0, ' 7 ': 7, '30000': 30000 }; + return amount in ok + ? { input: { ...base, fault: 'BUYER', refundAmount: ok[amount] } } + : { issue: 'AMOUNT_OUT_OF_RANGE' }; + } + + const cases = (['NO_REFUND', 'FULL_REFUND', 'BY_FAULT'] as const).flatMap((rule) => + FAULTS.flatMap((fault) => + AMOUNTS.map((amount) => [rule, fault, amount, expected(rule, fault, amount)] as const), + ), + ); + + it('표는 규칙 3 × 사정 3 × 금액 9를 덮고 금액을 보내는 경우는 3개다', () => { + expect(cases).toHaveLength(81); + const withAmount = cases.filter(([, , , r]) => 'refundAmount' in (r.input ?? {})); + expect(withAmount).toHaveLength(3); + }); + + it.each(cases)('%s fault=%j 금액=%j → %j', (rule, fault, refundAmount, result) => { + // ID "0"도 그대로 보낸다 + expect(buildCancelInput('0', options(rule), form({ fault, refundAmount }))).toEqual(result); + }); + + it('결제액이 0이면 구매자 사정 금액은 0만 받는다', () => { + const o = options('BY_FAULT', 0); + expect(buildCancelInput('1', o, form({ fault: 'BUYER', refundAmount: '0' }))).toMatchObject({ + input: { refundAmount: 0 }, + }); + expect(buildCancelInput('1', o, form({ fault: 'BUYER', refundAmount: '1' }))).toEqual({ + issue: 'AMOUNT_OUT_OF_RANGE', + }); + }); + + it.each([ + ['고르지 않은 사유', { reason: '' }], + ['선택지에 없는 사유', { reason: 'PAYMENT_NOT_RECEIVED' }], + ['프로토타입 키', { reason: 'constructor' }], + ])('%s는 REASON_REQUIRED', (_, patch) => { + expect(buildCancelInput('1', options('FULL_REFUND'), form(patch))).toEqual({ + issue: 'REASON_REQUIRED', + }); + }); + + it('취소할 수 없는 주문은 입력과 관계없이 NOT_CANCELABLE', () => { + expect(buildCancelInput('1', { ...options('FULL_REFUND'), cancelable: false }, form())).toEqual( + { issue: 'NOT_CANCELABLE' }, + ); + }); + + it.each([ + ['앞뒤 공백은 빼고 보낸다', ' 재고 없음 ', '재고 없음'], + ['공백만이면 null', ' ', null], + ['이모지 500자는 받는다', '🎂'.repeat(CANCEL_NOTE_MAX), '🎂'.repeat(CANCEL_NOTE_MAX)], + ])('메모: %s', (_, note, sent) => { + expect(buildCancelInput('1', options('FULL_REFUND'), form({ note }))).toEqual({ + input: { orderId: '1', reason: 'OTHER', note: sent }, + }); + }); + + it('메모는 코드 포인트 501자부터 NOTE_TOO_LONG', () => { + expect(noteLength(` ${'🎂'.repeat(CANCEL_NOTE_MAX)} `)).toBe(CANCEL_NOTE_MAX); + expect( + buildCancelInput('1', options('NO_REFUND'), form({ note: 'a'.repeat(CANCEL_NOTE_MAX + 1) })), + ).toEqual({ issue: 'NOTE_TOO_LONG' }); + }); +}); + +describe('parseRefundAmount', () => { + it.each([ + ['0', 0], + ['007', 7], + ['30000', 30000], + ['30001', null], + ['', null], + ['1,000', null], + ['99999999999999999999', null], + ])('%j → %s', (raw, n) => { + expect(parseRefundAmount(raw, PAID)).toBe(n); + }); +}); + +describe('cancelSummary', () => { + it.each([ + ['NO_REFUND', {}, PAID, '입금 전 주문이라 환불 없이 취소합니다.'], + ['FULL_REFUND', {}, PAID, '결제액 30,000원을 전액 환불합니다.'], + ['FULL_REFUND', {}, 0, '확인된 결제액이 없어 환불 없이 취소합니다.'], + ['BY_FAULT', {}, PAID, '사정을 고르면 환불 금액이 정해집니다.'], + ['BY_FAULT', { fault: 'SELLER' }, PAID, '판매자 사정이라 결제액 30,000원을 전액 환불합니다.'], + [ + 'BY_FAULT', + { fault: 'BUYER', refundAmount: '0' }, + PAID, + '0원을 환불하고, 남은 30,000원은 수수료를 뺀 뒤 매장 정산에 포함합니다.', + ], + [ + 'BY_FAULT', + { fault: 'BUYER', refundAmount: '10000' }, + PAID, + '10,000원을 환불하고, 남은 20,000원은 수수료를 뺀 뒤 매장 정산에 포함합니다.', + ], + [ + 'BY_FAULT', + { fault: 'BUYER', refundAmount: '30000' }, + PAID, + '결제액 30,000원을 전액 환불합니다.', + ], + [ + 'BY_FAULT', + { fault: 'BUYER', refundAmount: '' }, + PAID, + '환불 금액을 0원~30,000원 사이 정수로 입력하세요.', + ], + ] as const)('%s %j 결제액 %i → %s', (rule, patch, paid, text) => { + expect(cancelSummary(options(rule, paid), form(patch))).toBe(text); + }); + + it('취소할 수 없거나 모르는 규칙이면 요약이 없다', () => { + expect(cancelSummary(options(null), form())).toBeNull(); + expect(cancelSummary(options('PARTIAL' as CancelRefundRuleType), form())).toBeNull(); + }); +}); diff --git a/src/features/orders/cancel-form.ts b/src/features/orders/cancel-form.ts new file mode 100644 index 0000000..4826dfc --- /dev/null +++ b/src/features/orders/cancel-form.ts @@ -0,0 +1,82 @@ +import { + type AdminCancelOrderInput, + type AdminOrderQuery, + type OrderCancelFaultType, +} from '@/graphql/generated/graphql'; +import { formatKrw } from '@/shared/lib/format'; + +export type CancelOptions = AdminOrderQuery['adminOrder']['cancelOptions']; + +export const CANCEL_NOTE_MAX = 500; + +export interface CancelForm { + /** '' = 고르지 않음 */ + reason: string; + fault: '' | OrderCancelFaultType; + /** 입력 원문 */ + refundAmount: string; + note: string; +} + +export const EMPTY_CANCEL_FORM: CancelForm = { reason: '', fault: '', refundAmount: '', note: '' }; + +export type CancelFormIssue = + | 'NOT_CANCELABLE' + | 'REASON_REQUIRED' + | 'NOTE_TOO_LONG' + | 'FAULT_REQUIRED' + | 'AMOUNT_REQUIRED' + | 'AMOUNT_OUT_OF_RANGE'; + +/** BE처럼 앞뒤 공백을 뺀 코드 포인트 수(이모지도 1자) */ +export const noteLength = (note: string) => [...note.trim()].length; + +/** 사정을 고르는 규칙인지. 금액 입력은 그중 구매자 사정일 때만 */ +export const asksFault = (o: CancelOptions) => o.refundRule === 'BY_FAULT'; +export const asksAmount = (o: CancelOptions, f: CancelForm) => asksFault(o) && f.fault === 'BUYER'; + +/** 구매자 사정 환불액. 0~결제액 정수만 받고 아니면 null('0'은 유효) */ +export function parseRefundAmount(raw: string, paidAmount: number): number | null { + const t = raw.trim(); + if (!/^\d+$/.test(t)) return null; + const n = Number(t); + return n <= paidAmount ? n : null; +} + +/** 다이얼로그 입력 → adminCancelOrder 입력. 규칙은 cancelOptions가 정하고 화면은 복제하지 않는다 */ +export function buildCancelInput( + orderId: string, + o: CancelOptions, + f: CancelForm, +): { input: AdminCancelOrderInput } | { issue: CancelFormIssue } { + if (!o.cancelable) return { issue: 'NOT_CANCELABLE' }; + const reason = o.reasons.find((r) => r === f.reason); + if (!reason) return { issue: 'REASON_REQUIRED' }; + if (noteLength(f.note) > CANCEL_NOTE_MAX) return { issue: 'NOTE_TOO_LONG' }; + const base = { orderId, reason, note: f.note.trim() || null }; + if (!asksFault(o)) return { input: base }; + if (f.fault === '') return { issue: 'FAULT_REQUIRED' }; + if (f.fault === 'SELLER') return { input: { ...base, fault: 'SELLER' } }; + if (f.refundAmount.trim() === '') return { issue: 'AMOUNT_REQUIRED' }; + const refundAmount = parseRefundAmount(f.refundAmount, o.paidAmount); + if (refundAmount === null) return { issue: 'AMOUNT_OUT_OF_RANGE' }; + return { input: { ...base, fault: 'BUYER', refundAmount } }; +} + +/** 확인 버튼 위 요약. 고른 사정·금액으로 무엇이 일어나는지 */ +export function cancelSummary(o: CancelOptions, f: CancelForm): string | null { + const paid = formatKrw(o.paidAmount); + const full = + o.paidAmount > 0 + ? `결제액 ${paid}을 전액 환불합니다.` + : '확인된 결제액이 없어 환불 없이 취소합니다.'; + if (o.refundRule === 'NO_REFUND') return '입금 전 주문이라 환불 없이 취소합니다.'; + if (o.refundRule === 'FULL_REFUND') return full; + if (!asksFault(o)) return null; + if (f.fault === 'SELLER') return `판매자 사정이라 ${full}`; + if (f.fault !== 'BUYER') return '사정을 고르면 환불 금액이 정해집니다.'; + const r = parseRefundAmount(f.refundAmount, o.paidAmount); + if (r === null) return `환불 금액을 0원~${paid} 사이 정수로 입력하세요.`; + if (r === o.paidAmount) return full; + return `${formatKrw(r)}을 환불하고, 남은 ${formatKrw(o.paidAmount - r)}은 수수료를 뺀 뒤 매장 정산에 포함합니다.`; +} diff --git a/src/features/orders/components/cancel-order-dialog.tsx b/src/features/orders/components/cancel-order-dialog.tsx index 779b879..e5a1f02 100644 --- a/src/features/orders/components/cancel-order-dialog.tsx +++ b/src/features/orders/components/cancel-order-dialog.tsx @@ -3,6 +3,8 @@ import { useState } from 'react'; import { toast } from 'sonner'; import { messageFor } from '@/shared/api'; +import { formatKrw } from '@/shared/lib/format'; +import { cn } from '@/shared/lib/utils'; import { Button } from '@/shared/ui/button'; import { Dialog, @@ -13,34 +15,57 @@ import { DialogTitle, DialogTrigger, } from '@/shared/ui/dialog'; +import { Input } from '@/shared/ui/input'; import { Label } from '@/shared/ui/label'; +import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/shared/ui/select'; import { Textarea } from '@/shared/ui/textarea'; import { cancelOrder } from '../api/queries'; +import { + CANCEL_NOTE_MAX, + type CancelForm, + type CancelOptions, + EMPTY_CANCEL_FORM, + asksAmount, + asksFault, + buildCancelInput, + cancelSummary, + noteLength, + parseRefundAmount, +} from '../cancel-form'; +import { cancelFaultLabel, cancelReasonLabel } from '../meta'; -const NOTE_MAX = 500; +const FAULTS = ['SELLER', 'BUYER'] as const; export function CancelOrderDialog({ orderId, orderNumber, + options, }: { orderId: string; orderNumber: string; + options: CancelOptions; }) { const queryClient = useQueryClient(); const [open, setOpen] = useState(false); - const [note, setNote] = useState(''); + const [form, setForm] = useState(EMPTY_CANCEL_FORM); const [busy, setBusy] = useState(false); - const trimmed = note.trim(); - const invalid = trimmed.length === 0 || trimmed.length > NOTE_MAX; + const set = (patch: Partial) => setForm((f) => ({ ...f, ...patch })); + const built = buildCancelInput(orderId, options, form); + const summary = cancelSummary(options, form); + const noteLen = noteLength(form.note); + const amountInvalid = + form.refundAmount.trim() !== '' && + parseRefundAmount(form.refundAmount, options.paidAmount) === null; const submit = async () => { + if (!('input' in built)) return; setBusy(true); try { - await cancelOrder(queryClient, orderId, trimmed); + await cancelOrder(queryClient, built.input); toast.success(`${orderNumber} 주문을 취소했습니다.`); setOpen(false); - setNote(''); + setForm(EMPTY_CANCEL_FORM); } catch (e) { toast.error(messageFor(e)); } finally { @@ -52,38 +77,128 @@ export function CancelOrderDialog({ - 주문을 취소할까요? + 주문을 강제 취소할까요? - {orderNumber} 주문을 취소하면 구매자에게 취소 알림을 보냅니다. 사유는 상태 이력과 감사 - 로그에 남고, 취소한 주문은 되돌릴 수 없습니다. + {orderNumber} 주문을 취소하면 구매자에게 알림이 가고, 입금이 확인된 주문이면 + 판매자에게도 알립니다. 사유는 상태 이력과 감사 로그에 남고, 취소한 주문은 되돌릴 수 + 없습니다. -
    - -