From a8ff90bfe00221f6a0bb8e2468b9cc963d2271e8 Mon Sep 17 00:00:00 2001 From: chanwoo7 Date: Tue, 3 Nov 2026 00:23:04 +0900 Subject: [PATCH 01/54] =?UTF-8?q?chore:=20develop=20=EC=82=AD=EC=A0=9C=20?= =?UTF-8?q?=EA=B8=88=EC=A7=80=20ruleset=20=EB=B6=84=EB=A6=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 릴리즈 PR(head develop)을 Admin이 머지할 때마다 delete_branch_on_merge가 develop을 지워 매번 재생성하고 있었음. develop-protection에 deletion이 있지만 같은 ruleset의 Admin 우회(always)가 자동 삭제에도 적용됨. - 우회자 없는 develop-no-deletion ruleset을 새로 두고 deletion을 옮김(우회 권한은 ruleset 단위). - develop-protection은 PR·CI·force push 규칙과 Admin 우회(릴리즈 뒤 ff 동기화용)만 유지. - README 관리 범위·import 목록 갱신. terraform plan(-target 두 ruleset): 1 to add, 1 to change. 실제 차단은 apply 뒤 다음 릴리즈 머지에서 확인. --- terraform/README.md | 6 ++++-- terraform/main.tf | 25 ++++++++++++++++++++++++- 2 files changed, 28 insertions(+), 3 deletions(-) diff --git a/terraform/README.md b/terraform/README.md index 2aca0807..b5a347bb 100644 --- a/terraform/README.md +++ b/terraform/README.md @@ -15,7 +15,8 @@ - 레포 머지 옵션 (`delete_branch_on_merge`, `allow_auto_merge` 등) - `main` 브랜치 Ruleset (삭제/force push 차단, PR 필수, CI 통과 필수) -- `develop` 브랜치 Ruleset (동일 수준) +- `develop` 브랜치 Ruleset (동일 수준, 릴리즈 뒤 fast-forward 동기화용 Admin 우회) +- `develop` 삭제 금지 Ruleset (우회자 없음 — 릴리즈 PR 머지 때 `delete_branch_on_merge`가 develop을 지우지 못하게 분리) - `develop-msa` 브랜치 Ruleset (MSA 전환 통합 브랜치, develop과 동일 수준 — 전환 완료 시 제거) > **관리 밖**: 레포 이름/가시성/이슈 탭 등 이미 설정된 값은 `lifecycle.ignore_changes`로 제외 — UI에서 편하게 바꿔도 Terraform이 되돌리지 않는다. @@ -50,13 +51,14 @@ terraform import github_repository.caquick_be caquick-be # gh api repos/CaQuick/caquick-be/rulesets --jq '.[] | {id, name}' terraform import github_repository_ruleset.main_protection caquick-be: terraform import github_repository_ruleset.develop_protection caquick-be: +terraform import github_repository_ruleset.develop_no_deletion caquick-be: terraform import github_repository_ruleset.develop_msa_protection caquick-be: # import 후 plan 돌려서 drift 없는지 확인 terraform plan ``` -AWS 리소스(미디어 버킷 2개·백업 버킷·IAM 사용자·정책·연결)는 전부 `aws.tf`의 `import` 블록이 apply 때 자동으로 연결한다(이미 state에 있으면 no-op) — 별도 import 명령이 없다. state를 잃었을 때 빈 state로 plan하면 AWS 쪽은 전부 `to import`(add 0)로 잡힌다 — `to add`로 남는 4개(레포·Ruleset 3)는 위 GitHub import 명령으로 먼저 연결한다(실측 2026-09-25: `16 to import, 4 to add`). +AWS 리소스(미디어 버킷 2개·백업 버킷·IAM 사용자·정책·연결)는 전부 `aws.tf`의 `import` 블록이 apply 때 자동으로 연결한다(이미 state에 있으면 no-op) — 별도 import 명령이 없다. state를 잃었을 때 빈 state로 plan하면 AWS 쪽은 전부 `to import`(add 0)로 잡힌다 — `to add`로 남는 레포·Ruleset은 위 GitHub import 명령으로 먼저 연결한다(실측 2026-09-25: `16 to import, 4 to add`). > owner는 provider 인증(`GITHUB_TOKEN`)에서 자동 결정되므로 import 시 별도 지정 불필요. diff --git a/terraform/main.tf b/terraform/main.tf index b4aa68e4..36aad6c8 100644 --- a/terraform/main.tf +++ b/terraform/main.tf @@ -129,8 +129,8 @@ resource "github_repository_ruleset" "develop_protection" { bypass_mode = "always" } + # 삭제 금지는 아래 develop_no_deletion에 둔다 — 여기 두면 Admin 우회가 함께 풀린다. rules { - deletion = true non_fast_forward = true pull_request { @@ -160,6 +160,29 @@ resource "github_repository_ruleset" "develop_protection" { } } +############################################ +# Branch Ruleset: develop 삭제 금지 (우회자 없음) +############################################ +# 릴리즈 PR(head develop)을 Admin이 머지하면 delete_branch_on_merge가 develop을 지운다 — +# 우회 권한은 ruleset 단위라, 우회자 없는 ruleset으로 분리해야 Admin 머지에서도 삭제가 막힌다. +resource "github_repository_ruleset" "develop_no_deletion" { + name = "develop-no-deletion" + repository = data.github_repository.this.name + target = "branch" + enforcement = "active" + + conditions { + ref_name { + include = ["refs/heads/develop"] + exclude = [] + } + } + + rules { + deletion = true + } +} + ############################################ # Branch Ruleset: develop-msa (MSA 전환 통합 브랜치, develop과 동일 수준) ############################################ From 57e69eb01aea622b11849f363a41fbfa670dcca5 Mon Sep 17 00:00:00 2001 From: chanwoo7 Date: Thu, 19 Nov 2026 00:22:37 +0900 Subject: [PATCH 02/54] =?UTF-8?q?feat:=20=EC=A3=BC=EB=AC=B8=20=EA=B2=B0?= =?UTF-8?q?=EC=A0=9C=C2=B7=ED=99=98=EB=B6=88=C2=B7=EC=A0=95=EC=82=B0=20?= =?UTF-8?q?=EC=8A=A4=ED=82=A4=EB=A7=88=EC=99=80=20=EC=9E=85=EA=B8=88=20?= =?UTF-8?q?=EB=8C=80=EA=B8=B0=C2=B7=EB=85=B8=EC=87=BC=20=EC=83=81=ED=83=9C?= =?UTF-8?q?=20=EC=B6=94=EA=B0=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 계좌이체 결제·환불·입금 반환·주간 정산을 받을 기초 스키마. 결제·환불·정산 모델은 입금 확인과 주문 전이를 한 트랜잭션에 두려고 order가 소유한다. 이 커밋은 저장 구조와 기존 데이터 이행만 하고 주문 생성 동작은 그대로(SUBMITTED)다. - enum: OrderStatus에 PENDING_PAYMENT·NO_SHOW, NotificationEvent 6값, AuditTargetType 5값을 끝에 덧붙임(기존 순번 유지, INSTANT ALTER). OrderActor·OrderCancelReason·OrderCancelFault·결제·환불·입금 기록·정산 enum 신설 - Order: 기본 상태 PENDING_PAYMENT, 요청 사항·입력 해시·수수료율 스냅샷·정산 확정·확정 마감·노쇼 컬럼, 인덱스 4개((account_id, status)는 입금 대기 건수 잠금 읽기용) - OrderStatusHistory: actor_type(필수)·actor_account_id·취소 사유·사정·환불액 - 신규 모델 Payment·Refund(cancel_order_id unique로 주문당 취소 환불 1건)·DepositRecord·Settlement·StoreSettlementAccount·PaymentSetting(단일 행)·OrderPickupChange. 금전 모델은 deleted_at 없음, 돈이 걸린 선택 관계는 ON DELETE RESTRICT - 백필: 이력 주체(최초 BUYER, '[관리자] ' 메모 ADMIN, 나머지 SELLER), 기존 취소 이력은 사유 OTHER·환불 0, 입금 대기가 아닌 주문의 submitted_at = created_at, payment_setting id=1. 기존 주문에는 결제 기록을 만들지 않음 - 코드: 이력을 쓰는 세 경로(주문 생성·판매자 상태 변경·관리자 취소)가 주체와 계정을 남김 - SDL: OrderStatusType·NotificationEvent·AuditTargetType 새 값(감사 대상 필터 목록 포함) - 게이트: enum-sdl-sync spec 신설(NotificationEvent·ConversationBodyFormat·OrderStatus가 SDL에 모두 있는지), 모델 소유권 7개 등록 - 테스트 인프라: createOrder 팩토리는 입금 대기가 아니면 submitted_at을 채움, createPaymentSetting 팩토리 - 시드: 입금 흐름 예시 주문 5건(입금 대기·노쇼·부분 환불·미입금 취소 뒤 반환·입금 확인 접수)과 결제·환불·입금 기록, 테스트 입금 계좌(seedPayments). resetSeedScope는 결제·환불·입금 기록·픽업 변경을 주문보다 먼저, 정산·정산 계좌는 매장 범위로 지우고 결제 설정은 남김 테스트 21건 추가 - migration spec 9: 이력 주체·취소 백필·submitted_at 채움(입금 대기·기존 값 보존)·결제 설정 1행·enum 4개 컬럼 순서 보존·기본값 - enum-sdl-sync 8: 값 하나를 뺀 SDL로 잡히는 반증 3, 정합 3, 부분집합 판정 1, enum 없음 1 - seed-reset-scope 1: 결제 예시가 붙은 시드를 정리·재시드, 결제 설정 보존 - 이력 주체 단언 3(주문 생성·판매자 전이·관리자 취소) --- .../migration.sql | 226 +++++++++++++ prisma/schema.prisma | 303 +++++++++++++++++- prisma/seed.ts | 6 +- prisma/seed/admins.ts | 10 +- prisma/seed/idempotent.ts | 21 ++ prisma/seed/orders.ts | 280 +++++++++++++++- prisma/seed/payments.ts | 106 ++++++ .../audit-log/audit-log.types.graphql | 20 ++ .../constants/dashboard.constants.ts | 5 + .../notification/notification.types.graphql | 26 +- src/features/order/order.types.graphql | 15 +- .../order-payment-schema.migration.spec.ts | 202 ++++++++++++ .../repositories/order.repository.spec.ts | 11 + .../order/repositories/order.repository.ts | 7 + .../services/order-admin.service.spec.ts | 15 +- .../services/order-checkout.service.spec.ts | 4 + .../order/services/order-my.service.spec.ts | 1 + .../services/order-seller.service.spec.ts | 10 +- .../order/types/order-seller-output.type.ts | 7 +- src/test/enum-sdl-sync.spec.ts | 90 ++++++ src/test/factories/order.factory.ts | 41 ++- src/test/model-ownership.ts | 7 + src/test/seed-reset-scope.spec.ts | 76 +++++ 23 files changed, 1461 insertions(+), 28 deletions(-) create mode 100644 prisma/migrations/20261118150004_order_payment_schema/migration.sql create mode 100644 prisma/seed/payments.ts create mode 100644 src/features/order/repositories/order-payment-schema.migration.spec.ts create mode 100644 src/test/enum-sdl-sync.spec.ts diff --git a/prisma/migrations/20261118150004_order_payment_schema/migration.sql b/prisma/migrations/20261118150004_order_payment_schema/migration.sql new file mode 100644 index 00000000..28514e94 --- /dev/null +++ b/prisma/migrations/20261118150004_order_payment_schema/migration.sql @@ -0,0 +1,226 @@ +-- 주문 결제·환불·정산 스키마와 입금 대기(PENDING_PAYMENT)·노쇼(NO_SHOW) 상태. +-- enum 값은 끝에 덧붙여 기존 값의 순번을 지킨다(저장값 보존, INSTANT ALTER). +-- AlterTable +ALTER TABLE `audit_log` MODIFY `target_type` ENUM('STORE', 'PRODUCT', 'ORDER', 'CONVERSATION', 'CHANGE_PASSWORD', 'ACCOUNT', 'BANNER', 'CATEGORY', 'TAG', 'REGION', 'REVIEW', 'REVIEW_COMMENT', 'REVIEW_REPORT', 'NOTIFICATION', 'SEARCH_KEYWORD_CHIP', 'PAYMENT_SETTING', 'SETTLEMENT_ACCOUNT', 'SETTLEMENT', 'REFUND', 'DEPOSIT_RECORD') NOT NULL; + +-- AlterTable +ALTER TABLE `notification` MODIFY `event` ENUM('REVIEW_LIKED', 'ORDER_CONFIRMED', 'ORDER_MADE', 'ORDER_PICKED_UP', 'ORDER_CANCELED', 'ORDER_PAYMENT_CONFIRMED', 'ORDER_PAYMENT_EXPIRED', 'ORDER_NO_SHOW', 'ORDER_PICKUP_RESCHEDULED', 'REFUND_ACCOUNT_REQUESTED', 'REFUND_COMPLETED') NULL; + +-- AlterTable +ALTER TABLE `order` ADD COLUMN `commission_amount` INTEGER UNSIGNED NULL, + ADD COLUMN `commission_rate_bps` SMALLINT UNSIGNED NOT NULL DEFAULT 0, + ADD COLUMN `confirm_deadline_at` DATETIME(3) NULL, + ADD COLUMN `confirm_reminder_sent_at` DATETIME(3) NULL, + ADD COLUMN `idempotency_input_hash` CHAR(64) NULL, + ADD COLUMN `no_show_at` DATETIME(3) NULL, + ADD COLUMN `request_note` VARCHAR(500) NULL, + ADD COLUMN `settlement_base_amount` INTEGER UNSIGNED NULL, + ADD COLUMN `settlement_finalized_at` DATETIME(3) NULL, + ADD COLUMN `settlement_id` BIGINT UNSIGNED NULL, + MODIFY `status` ENUM('SUBMITTED', 'CONFIRMED', 'MADE', 'PICKED_UP', 'CANCELED', 'PENDING_PAYMENT', 'NO_SHOW') NOT NULL DEFAULT 'PENDING_PAYMENT'; + +-- AlterTable +ALTER TABLE `order_status_history` ADD COLUMN `actor_account_id` BIGINT UNSIGNED NULL, + ADD COLUMN `actor_type` ENUM('BUYER', 'SELLER', 'ADMIN', 'SYSTEM') NULL, + ADD COLUMN `cancel_fault` ENUM('SELLER', 'BUYER') NULL, + ADD COLUMN `cancel_reason` ENUM('DESIGN_NOT_FEASIBLE', 'OUT_OF_MATERIALS', 'SCHEDULE_UNAVAILABLE', 'INAPPROPRIATE_REQUEST', 'BUYER_REQUEST', 'OTHER', 'PAYMENT_NOT_RECEIVED', 'CONFIRM_TIMEOUT') NULL, + ADD COLUMN `refund_amount` INTEGER UNSIGNED NULL, + MODIFY `from_status` ENUM('SUBMITTED', 'CONFIRMED', 'MADE', 'PICKED_UP', 'CANCELED', 'PENDING_PAYMENT', 'NO_SHOW') NULL, + MODIFY `to_status` ENUM('SUBMITTED', 'CONFIRMED', 'MADE', 'PICKED_UP', 'CANCELED', 'PENDING_PAYMENT', 'NO_SHOW') NOT NULL; + +-- CreateTable +CREATE TABLE `payment` ( + `id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT, + `order_id` BIGINT UNSIGNED NOT NULL, + `method` ENUM('BANK_TRANSFER', 'TOSS') NOT NULL, + `status` ENUM('PENDING', 'CONFIRMED', 'CANCELED') NOT NULL DEFAULT 'PENDING', + `amount` INTEGER UNSIGNED NOT NULL, + `depositor_name` VARCHAR(20) NOT NULL, + `deposit_bank_code` CHAR(3) NOT NULL, + `deposit_account_number` VARCHAR(30) NOT NULL, + `deposit_account_holder` VARCHAR(50) NOT NULL, + `expires_at` DATETIME(3) NOT NULL, + `buyer_claimed_at` DATETIME(3) NULL, + `confirmed_at` DATETIME(3) NULL, + `confirm_source` ENUM('AUTO', 'ADMIN') NULL, + `confirmed_by_account_id` BIGINT UNSIGNED NULL, + `confirmed_by_label_snapshot` VARCHAR(200) NULL, + `confirm_note` VARCHAR(500) NULL, + `canceled_at` DATETIME(3) NULL, + `created_at` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3), + `updated_at` DATETIME(3) NOT NULL, + + UNIQUE INDEX `uk_payment_order`(`order_id`), + INDEX `idx_payment_status_claimed_expires`(`status`, `buyer_claimed_at`, `expires_at`), + INDEX `idx_payment_status_amount`(`status`, `amount`), + PRIMARY KEY (`id`) +) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; + +-- CreateTable +CREATE TABLE `refund` ( + `id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT, + `order_id` BIGINT UNSIGNED NOT NULL, + `kind` ENUM('CANCEL', 'DEPOSIT_RETURN') NOT NULL, + `cancel_order_id` BIGINT UNSIGNED NULL, + `deposit_record_id` BIGINT UNSIGNED NULL, + `amount` INTEGER UNSIGNED NOT NULL, + `status` ENUM('AWAITING_ACCOUNT', 'AWAITING_TRANSFER', 'COMPLETED') NOT NULL DEFAULT 'AWAITING_ACCOUNT', + `bank_code` CHAR(3) NULL, + `account_holder` VARCHAR(50) NULL, + `account_number_enc` VARCHAR(255) NULL, + `account_number_last4` CHAR(4) NULL, + `account_submitted_at` DATETIME(3) NULL, + `requested_at` DATETIME(3) NOT NULL, + `completed_at` DATETIME(3) NULL, + `completed_by_account_id` BIGINT UNSIGNED NULL, + `completed_by_label_snapshot` VARCHAR(200) NULL, + `complete_note` VARCHAR(500) NULL, + `created_at` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3), + `updated_at` DATETIME(3) NOT NULL, + + UNIQUE INDEX `uk_refund_cancel_order`(`cancel_order_id`), + UNIQUE INDEX `uk_refund_deposit_record`(`deposit_record_id`), + INDEX `idx_refund_order`(`order_id`), + PRIMARY KEY (`id`) +) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; + +-- CreateTable +CREATE TABLE `deposit_record` ( + `id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT, + `kind` ENUM('RETURN', 'UNIDENTIFIED') NOT NULL, + `order_id` BIGINT UNSIGNED NULL, + `amount` INTEGER UNSIGNED NOT NULL, + `depositor_name` VARCHAR(50) NOT NULL, + `deposited_at` DATETIME(3) NULL, + `note` VARCHAR(500) NULL, + `recorded_by_account_id` BIGINT UNSIGNED NOT NULL, + `recorded_by_label_snapshot` VARCHAR(200) NULL, + `created_at` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3), + `updated_at` DATETIME(3) NOT NULL, + + INDEX `idx_deposit_record_kind_created`(`kind`, `created_at`), + INDEX `idx_deposit_record_order`(`order_id`), + PRIMARY KEY (`id`) +) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; + +-- CreateTable +CREATE TABLE `settlement` ( + `id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT, + `store_id` BIGINT UNSIGNED NOT NULL, + `store_name_snapshot` VARCHAR(200) NOT NULL, + `period_start` DATE NOT NULL, + `period_end` DATE NOT NULL, + `order_count` INTEGER UNSIGNED NOT NULL, + `settlement_base_amount` INTEGER UNSIGNED NOT NULL, + `commission_amount` INTEGER UNSIGNED NOT NULL, + `payout_amount` INTEGER UNSIGNED NOT NULL, + `status` ENUM('PENDING', 'PAID') NOT NULL DEFAULT 'PENDING', + `paid_at` DATETIME(3) NULL, + `paid_by_account_id` BIGINT UNSIGNED NULL, + `paid_by_label_snapshot` VARCHAR(200) NULL, + `paid_note` VARCHAR(500) NULL, + `paid_bank_code` CHAR(3) NULL, + `paid_account_holder` VARCHAR(50) NULL, + `paid_account_number_enc` VARCHAR(255) NULL, + `paid_account_last4` CHAR(4) NULL, + `created_at` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3), + `updated_at` DATETIME(3) NOT NULL, + + UNIQUE INDEX `uk_settlement_store_period`(`store_id`, `period_start`), + PRIMARY KEY (`id`) +) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; + +-- CreateTable +CREATE TABLE `store_settlement_account` ( + `id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT, + `store_id` BIGINT UNSIGNED NOT NULL, + `bank_code` CHAR(3) NOT NULL, + `account_holder` VARCHAR(50) NOT NULL, + `account_number_enc` VARCHAR(255) NOT NULL, + `account_number_last4` CHAR(4) NOT NULL, + `updated_by_account_id` BIGINT UNSIGNED NOT NULL, + `updated_by_role` ENUM('BUYER', 'SELLER', 'ADMIN', 'SYSTEM') NOT NULL, + `created_at` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3), + `updated_at` DATETIME(3) NOT NULL, + + UNIQUE INDEX `uk_store_settlement_account_store`(`store_id`), + PRIMARY KEY (`id`) +) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; + +-- CreateTable +CREATE TABLE `payment_setting` ( + `id` INTEGER NOT NULL, + `commission_rate_bps` SMALLINT UNSIGNED NOT NULL DEFAULT 0, + `deposit_bank_code` CHAR(3) NULL, + `deposit_account_number` VARCHAR(30) NULL, + `deposit_account_holder` VARCHAR(50) NULL, + `updated_by_account_id` BIGINT UNSIGNED NULL, + `created_at` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3), + `updated_at` DATETIME(3) NOT NULL, + + PRIMARY KEY (`id`) +) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; + +-- CreateTable +CREATE TABLE `order_pickup_change` ( + `id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT, + `order_id` BIGINT UNSIGNED NOT NULL, + `from_pickup_at` DATETIME(3) NOT NULL, + `to_pickup_at` DATETIME(3) NOT NULL, + `changed_by_account_id` BIGINT UNSIGNED NOT NULL, + `note` VARCHAR(500) NULL, + `changed_at` DATETIME(3) NOT NULL, + `created_at` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3), + + INDEX `idx_order_pickup_change_order`(`order_id`, `changed_at`), + PRIMARY KEY (`id`) +) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; + +-- CreateIndex +CREATE INDEX `idx_order_status_confirm_deadline` ON `order`(`status`, `confirm_deadline_at`); + +-- CreateIndex +CREATE INDEX `idx_order_status_pickup` ON `order`(`status`, `pickup_at`); + +-- CreateIndex +CREATE INDEX `idx_order_settlement` ON `order`(`settlement_id`, `settlement_finalized_at`); + +-- CreateIndex +CREATE INDEX `idx_order_account_status` ON `order`(`account_id`, `status`); + +-- AddForeignKey +ALTER TABLE `order` ADD CONSTRAINT `order_settlement_id_fkey` FOREIGN KEY (`settlement_id`) REFERENCES `settlement`(`id`) ON DELETE RESTRICT ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE `payment` ADD CONSTRAINT `payment_order_id_fkey` FOREIGN KEY (`order_id`) REFERENCES `order`(`id`) ON DELETE RESTRICT ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE `refund` ADD CONSTRAINT `refund_order_id_fkey` FOREIGN KEY (`order_id`) REFERENCES `order`(`id`) ON DELETE RESTRICT ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE `refund` ADD CONSTRAINT `refund_deposit_record_id_fkey` FOREIGN KEY (`deposit_record_id`) REFERENCES `deposit_record`(`id`) ON DELETE RESTRICT ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE `deposit_record` ADD CONSTRAINT `deposit_record_order_id_fkey` FOREIGN KEY (`order_id`) REFERENCES `order`(`id`) ON DELETE RESTRICT ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE `settlement` ADD CONSTRAINT `settlement_store_id_fkey` FOREIGN KEY (`store_id`) REFERENCES `store`(`id`) ON DELETE RESTRICT ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE `store_settlement_account` ADD CONSTRAINT `store_settlement_account_store_id_fkey` FOREIGN KEY (`store_id`) REFERENCES `store`(`id`) ON DELETE RESTRICT ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE `order_pickup_change` ADD CONSTRAINT `order_pickup_change_order_id_fkey` FOREIGN KEY (`order_id`) REFERENCES `order`(`id`) ON DELETE RESTRICT ON UPDATE CASCADE; + +-- backfill: 기존 이력의 주체는 메모로 가린다(관리자 취소만 '[관리자] ' 접두). 기존 취소는 사유 기타·환불 0. +UPDATE `order_status_history` SET `actor_type` = CASE + WHEN `from_status` IS NULL THEN 'BUYER' + WHEN `note` LIKE '[관리자] %' THEN 'ADMIN' + ELSE 'SELLER' +END; +UPDATE `order_status_history` SET `cancel_reason` = 'OTHER', `refund_amount` = 0 WHERE `to_status` = 'CANCELED'; +-- 판매자 노출은 submitted_at으로 가린다. 결제 도입 전 주문은 전부 접수된 주문이다 +UPDATE `order` SET `submitted_at` = `created_at` WHERE `submitted_at` IS NULL AND `status` <> 'PENDING_PAYMENT'; +INSERT INTO `payment_setting` (`id`, `commission_rate_bps`, `created_at`, `updated_at`) VALUES (1, 0, CURRENT_TIMESTAMP(3), CURRENT_TIMESTAMP(3)); +-- end backfill +ALTER TABLE `order_status_history` MODIFY `actor_type` ENUM('BUYER', 'SELLER', 'ADMIN', 'SYSTEM') NOT NULL; diff --git a/prisma/schema.prisma b/prisma/schema.prisma index 6cb89998..f112e454 100644 --- a/prisma/schema.prisma +++ b/prisma/schema.prisma @@ -52,6 +52,72 @@ enum OrderStatus { MADE PICKED_UP CANCELED + // 새 값은 끝에 덧붙인다(기존 값의 순번이 바뀌지 않아야 INSTANT ALTER) + PENDING_PAYMENT + NO_SHOW +} + +// 주문 전이를 일으킨 주체 +enum OrderActor { + BUYER + SELLER + ADMIN + SYSTEM +} + +enum OrderCancelReason { + DESIGN_NOT_FEASIBLE + OUT_OF_MATERIALS + SCHEDULE_UNAVAILABLE + INAPPROPRIATE_REQUEST + BUYER_REQUEST + OTHER + PAYMENT_NOT_RECEIVED + CONFIRM_TIMEOUT +} + +// 확정 뒤 취소의 귀책. 환불액 규칙이 갈린다 +enum OrderCancelFault { + SELLER + BUYER +} + +enum PaymentMethod { + BANK_TRANSFER + TOSS +} + +// CANCELED는 PENDING에서만 간다. 확인된 결제는 주문이 취소돼도 CONFIRMED로 남고 환불은 Refund가 맡는다 +enum PaymentStatus { + PENDING + CONFIRMED + CANCELED +} + +enum PaymentConfirmSource { + AUTO + ADMIN +} + +enum RefundKind { + CANCEL + DEPOSIT_RETURN +} + +enum RefundStatus { + AWAITING_ACCOUNT + AWAITING_TRANSFER + COMPLETED +} + +enum DepositRecordKind { + RETURN + UNIDENTIFIED +} + +enum SettlementStatus { + PENDING + PAID } enum NotificationType { @@ -104,6 +170,12 @@ enum NotificationEvent { ORDER_MADE ORDER_PICKED_UP ORDER_CANCELED + ORDER_PAYMENT_CONFIRMED + ORDER_PAYMENT_EXPIRED + ORDER_NO_SHOW + ORDER_PICKUP_RESCHEDULED + REFUND_ACCOUNT_REQUESTED + REFUND_COMPLETED } enum PushPlatform { @@ -138,6 +210,11 @@ enum AuditTargetType { REVIEW_REPORT NOTIFICATION SEARCH_KEYWORD_CHIP + PAYMENT_SETTING + SETTLEMENT_ACCOUNT + SETTLEMENT + REFUND + DEPOSIT_RECORD } enum AuditActionType { @@ -458,6 +535,8 @@ model Store { conversations StoreConversation[] faq_topics StoreFaqTopic[] daily_capacities StoreDailyCapacity[] + settlements Settlement[] + settlement_account StoreSettlementAccount? @@index([seller_account_id], map: "idx_store_seller") @@index([store_name], map: "idx_store_name") @@ -814,7 +893,7 @@ model Order { account_id BigInt @db.UnsignedBigInt - status OrderStatus @default(SUBMITTED) + status OrderStatus @default(PENDING_PAYMENT) pickup_at DateTime @db.DateTime(3) buyer_name String @db.VarChar(100) @@ -832,23 +911,49 @@ model Order { // 클라이언트 재시도 중복 생성 방지 키(이슈 #212). 기존 row 호환을 위해 nullable // (MySQL unique는 NULL 중복 허용) — 신규 주문은 항상 저장한다. - idempotency_key String? @db.VarChar(64) + idempotency_key String? @db.VarChar(64) + // 같은 멱등 키 재요청이 같은 입력인지 가리는 sha256(hex). 해시 도입 전 주문은 null이고 비교를 건너뛴다 + idempotency_input_hash String? @db.Char(64) + + request_note String? @db.VarChar(500) + + // 생성 시점 수수료율 스냅샷(1bp = 0.01%). 설정이 바뀌어도 이 주문의 정산은 그대로다 + commission_rate_bps Int @default(0) @db.UnsignedSmallInt + // 정산 확정(픽업 완료·노쇼·구매자 사정 부분 환불 취소) 때 채운다. 확인된 결제가 없는 주문은 끝까지 null + settlement_base_amount Int? @db.UnsignedInt + commission_amount Int? @db.UnsignedInt + settlement_finalized_at DateTime? @db.DateTime(3) + settlement_id BigInt? @db.UnsignedBigInt + + confirm_deadline_at DateTime? @db.DateTime(3) + confirm_reminder_sent_at DateTime? @db.DateTime(3) + no_show_at DateTime? @db.DateTime(3) created_at DateTime @default(now()) @db.DateTime(3) updated_at DateTime @updatedAt @db.DateTime(3) deleted_at DateTime? @db.DateTime(3) - account Account @relation(fields: [account_id], references: [id]) + account Account @relation(fields: [account_id], references: [id]) + settlement Settlement? @relation(fields: [settlement_id], references: [id], onDelete: Restrict) status_histories OrderStatusHistory[] items OrderItem[] notifications Notification[] + payment Payment? + refunds Refund[] + deposit_records DepositRecord[] + pickup_changes OrderPickupChange[] @@unique([account_id, idempotency_key], map: "uk_order_account_idempotency") @@index([account_id], map: "idx_order_account") @@index([status, created_at], map: "idx_order_status") @@index([pickup_at], map: "idx_order_pickup_at") @@index([deleted_at], map: "idx_order_deleted_at") + @@index([status, confirm_deadline_at], map: "idx_order_status_confirm_deadline") + @@index([status, pickup_at], map: "idx_order_status_pickup") + @@index([settlement_id, settlement_finalized_at], map: "idx_order_settlement") + // 계정당 입금 대기 건수를 잠금 읽기로 센다 + @@index([account_id, status], map: "idx_order_account_status") @@map("order") } @@ -860,6 +965,14 @@ model OrderStatusHistory { to_status OrderStatus changed_at DateTime @default(now()) @db.DateTime(3) + actor_type OrderActor + // 시스템 전이는 null + actor_account_id BigInt? @db.UnsignedBigInt + cancel_reason OrderCancelReason? + cancel_fault OrderCancelFault? + // 취소 전이의 환불액(원). 취소가 아니면 null + refund_amount Int? @db.UnsignedInt + note String? @db.VarChar(500) created_at DateTime @default(now()) @db.DateTime(3) @@ -995,6 +1108,190 @@ model OrderItemCustomFreeEditAttachment { @@map("order_item_custom_free_edit_attachment") } +// 주문 1건의 결제. 계좌이체는 PENDING으로 만들고 입금 확인(관리자, 후속 연동은 AUTO) 때 CONFIRMED가 된다. +model Payment { + id BigInt @id @default(autoincrement()) @db.UnsignedBigInt + order_id BigInt @unique(map: "uk_payment_order") @db.UnsignedBigInt + + method PaymentMethod + status PaymentStatus @default(PENDING) + amount Int @db.UnsignedInt + // 은행 앱의 입금자명과 대조하는 값 + depositor_name String @db.VarChar(20) + + // 안내한 플랫폼 입금 계좌 스냅샷 — 설정이 바뀌어도 이 주문의 안내는 그대로다 + deposit_bank_code String @db.Char(3) + deposit_account_number String @db.VarChar(30) + deposit_account_holder String @db.VarChar(50) + + expires_at DateTime @db.DateTime(3) + // 구매자 '입금했어요' 시각. 있으면 미입금 자동 취소에서 빠진다 + buyer_claimed_at DateTime? @db.DateTime(3) + confirmed_at DateTime? @db.DateTime(3) + confirm_source PaymentConfirmSource? + confirmed_by_account_id BigInt? @db.UnsignedBigInt + confirmed_by_label_snapshot String? @db.VarChar(200) + confirm_note String? @db.VarChar(500) + canceled_at DateTime? @db.DateTime(3) + + created_at DateTime @default(now()) @db.DateTime(3) + updated_at DateTime @updatedAt @db.DateTime(3) + + order Order @relation(fields: [order_id], references: [id]) + + @@index([status, buyer_claimed_at, expires_at], map: "idx_payment_status_claimed_expires") + @@index([status, amount], map: "idx_payment_status_amount") + @@map("payment") +} + +// 구매자에게 돌려줄 돈. 취소 환불(CANCEL)과 반환 대상으로 연결한 입금(DEPOSIT_RETURN)이 같은 처리 흐름을 탄다. +model Refund { + id BigInt @id @default(autoincrement()) @db.UnsignedBigInt + order_id BigInt @db.UnsignedBigInt + kind RefundKind + // kind=CANCEL이면 order_id — 주문당 취소 환불 1건을 DB가 보장한다(NULL은 중복 허용) + cancel_order_id BigInt? @unique(map: "uk_refund_cancel_order") @db.UnsignedBigInt + deposit_record_id BigInt? @unique(map: "uk_refund_deposit_record") @db.UnsignedBigInt + + amount Int @db.UnsignedInt + status RefundStatus @default(AWAITING_ACCOUNT) + + // 구매자 환불 계좌. 계좌번호는 암호문과 표시용 끝 4자리만 둔다 + bank_code String? @db.Char(3) + account_holder String? @db.VarChar(50) + account_number_enc String? @db.VarChar(255) + account_number_last4 String? @db.Char(4) + account_submitted_at DateTime? @db.DateTime(3) + + requested_at DateTime @db.DateTime(3) + completed_at DateTime? @db.DateTime(3) + completed_by_account_id BigInt? @db.UnsignedBigInt + completed_by_label_snapshot String? @db.VarChar(200) + complete_note String? @db.VarChar(500) + + created_at DateTime @default(now()) @db.DateTime(3) + updated_at DateTime @updatedAt @db.DateTime(3) + + order Order @relation(fields: [order_id], references: [id]) + deposit_record DepositRecord? @relation(fields: [deposit_record_id], references: [id], onDelete: Restrict) + + @@index([order_id], map: "idx_refund_order") + @@map("refund") +} + +// 관리자가 은행 앱에서 본 입금 중 주문 결제로 확인하지 않은 것. RETURN은 주문에 연결해 돌려주고, UNIDENTIFIED는 메모로 종결한다. +model DepositRecord { + id BigInt @id @default(autoincrement()) @db.UnsignedBigInt + kind DepositRecordKind + // RETURN만 주문을 가리킨다 + order_id BigInt? @db.UnsignedBigInt + amount Int @db.UnsignedInt + depositor_name String @db.VarChar(50) + deposited_at DateTime? @db.DateTime(3) + note String? @db.VarChar(500) + + recorded_by_account_id BigInt @db.UnsignedBigInt + // 처리자 표시 라벨. 라벨을 만들 수 없는 계정이면 null + recorded_by_label_snapshot String? @db.VarChar(200) + + created_at DateTime @default(now()) @db.DateTime(3) + updated_at DateTime @updatedAt @db.DateTime(3) + + order Order? @relation(fields: [order_id], references: [id], onDelete: Restrict) + refund Refund? + + @@index([kind, created_at], map: "idx_deposit_record_kind_created") + @@index([order_id], map: "idx_deposit_record_order") + @@map("deposit_record") +} + +// 매장별 주간 정산(월~일, KST). 정산 확정된 주문을 묶고 관리자가 송금한 뒤 PAID로 바꾼다. +model Settlement { + id BigInt @id @default(autoincrement()) @db.UnsignedBigInt + store_id BigInt @db.UnsignedBigInt + store_name_snapshot String @db.VarChar(200) + + period_start DateTime @db.Date + period_end DateTime @db.Date + + order_count Int @db.UnsignedInt + settlement_base_amount Int @db.UnsignedInt + commission_amount Int @db.UnsignedInt + payout_amount Int @db.UnsignedInt + + status SettlementStatus @default(PENDING) + paid_at DateTime? @db.DateTime(3) + paid_by_account_id BigInt? @db.UnsignedBigInt + paid_by_label_snapshot String? @db.VarChar(200) + paid_note String? @db.VarChar(500) + // 송금 시점 정산 계좌 스냅샷 + paid_bank_code String? @db.Char(3) + paid_account_holder String? @db.VarChar(50) + paid_account_number_enc String? @db.VarChar(255) + paid_account_last4 String? @db.Char(4) + + created_at DateTime @default(now()) @db.DateTime(3) + updated_at DateTime @updatedAt @db.DateTime(3) + + store Store @relation(fields: [store_id], references: [id]) + orders Order[] + + @@unique([store_id, period_start], map: "uk_settlement_store_period") + @@map("settlement") +} + +model StoreSettlementAccount { + id BigInt @id @default(autoincrement()) @db.UnsignedBigInt + store_id BigInt @unique(map: "uk_store_settlement_account_store") @db.UnsignedBigInt + bank_code String @db.Char(3) + account_holder String @db.VarChar(50) + account_number_enc String @db.VarChar(255) + account_number_last4 String @db.Char(4) + updated_by_account_id BigInt @db.UnsignedBigInt + // 판매자 본인(SELLER)과 관리자 대리 수정(ADMIN)을 가른다 + updated_by_role OrderActor + + created_at DateTime @default(now()) @db.DateTime(3) + updated_at DateTime @updatedAt @db.DateTime(3) + + store Store @relation(fields: [store_id], references: [id]) + + @@map("store_settlement_account") +} + +// 플랫폼 결제 설정 단일 행(id=1). 행이 없으면 기본값(수수료 0, 입금 계좌 없음)으로 읽는다. +model PaymentSetting { + id Int @id + commission_rate_bps Int @default(0) @db.UnsignedSmallInt + deposit_bank_code String? @db.Char(3) + deposit_account_number String? @db.VarChar(30) + deposit_account_holder String? @db.VarChar(50) + updated_by_account_id BigInt? @db.UnsignedBigInt + + created_at DateTime @default(now()) @db.DateTime(3) + updated_at DateTime @updatedAt @db.DateTime(3) + + @@map("payment_setting") +} + +// 판매자 픽업 일시 변경 이력 +model OrderPickupChange { + id BigInt @id @default(autoincrement()) @db.UnsignedBigInt + order_id BigInt @db.UnsignedBigInt + from_pickup_at DateTime @db.DateTime(3) + to_pickup_at DateTime @db.DateTime(3) + changed_by_account_id BigInt @db.UnsignedBigInt + note String? @db.VarChar(500) + changed_at DateTime @db.DateTime(3) + + created_at DateTime @default(now()) @db.DateTime(3) + + order Order @relation(fields: [order_id], references: [id]) + + @@index([order_id, changed_at], map: "idx_order_pickup_change_order") + @@map("order_pickup_change") +} + /** * ========================= * 9) Review diff --git a/prisma/seed.ts b/prisma/seed.ts index 043ab7bc..f5bd4bba 100644 --- a/prisma/seed.ts +++ b/prisma/seed.ts @@ -17,6 +17,7 @@ import { seedConversations } from './seed/conversations'; import { resetSeedScope } from './seed/idempotent'; import { seedNotifications } from './seed/notifications'; import { seedOrders } from './seed/orders'; +import { seedPayments } from './seed/payments'; import { seedRecentViews } from './seed/recent-views'; import { seedRegions } from './seed/regions'; import { seedReviews } from './seed/reviews'; @@ -83,7 +84,10 @@ async function main(): Promise { await seedBanners(prisma); log('관리자 시드 중...'); - await seedAdmins(prisma); + const admin = await seedAdmins(prisma); + + log('결제 설정·결제·환불·입금 기록 시드 중...'); + await seedPayments(prisma, { orders, admin }); log('완료. 발급된 테스트 계정:'); for (const u of users) { diff --git a/prisma/seed/admins.ts b/prisma/seed/admins.ts index b4b0f3de..f084a374 100644 --- a/prisma/seed/admins.ts +++ b/prisma/seed/admins.ts @@ -11,9 +11,13 @@ import { } from './credential-policy'; import { SEED_ADMIN_EMAIL_PREFIX } from './idempotent'; +import { formatAccountLabel } from '@/common/utils/account-label'; import type { PrismaClient } from '@/generated/prisma/client'; -export async function seedAdmins(prisma: PrismaClient): Promise { +/** 처리자 라벨은 관리자 조작 기록(결제 확인·입금 기록)의 스냅샷 값이다. */ +export async function seedAdmins( + prisma: PrismaClient, +): Promise<{ id: bigint; label: string | null }> { assertSeedCredential({ username: SEED_ADMIN_USERNAME, password: SEED_PASSWORD, @@ -41,4 +45,8 @@ export async function seedAdmins(prisma: PrismaClient): Promise { console.log( `[seed] 관리자 accountId=${admin.id.toString()} (${SEED_ADMIN_USERNAME})`, ); + return { + id: admin.id, + label: formatAccountLabel(admin.name, SEED_ADMIN_USERNAME), + }; } diff --git a/prisma/seed/idempotent.ts b/prisma/seed/idempotent.ts index 464d8a9b..3bad3b31 100644 --- a/prisma/seed/idempotent.ts +++ b/prisma/seed/idempotent.ts @@ -9,6 +9,7 @@ * * 정리 시 위 prefix에 매칭되는 row와 그 종속 데이터(주문/리뷰/찜/...)를 * 삭제한 뒤 다시 삽입하므로, 수동으로 만든 다른 데이터는 보존된다. + * 결제 설정(payment_setting 단일 행)은 시드 영역이 아니라 지우지 않고 seedPayments가 upsert한다. */ import type { PrismaClient } from '@/generated/prisma/client'; @@ -135,6 +136,19 @@ export async function resetSeedScope(prisma: PrismaClient): Promise { where: { order_item_id: { in: orderItemIds } }, }); } + // 결제·환불·입금 기록(환불이 입금 기록을 가리켜 먼저)·픽업 변경 — 전부 주문 FK(RESTRICT) + await prisma.refund.deleteMany({ + where: { order_id: { in: orderIds } }, + }); + await prisma.depositRecord.deleteMany({ + where: { order_id: { in: orderIds } }, + }); + await prisma.payment.deleteMany({ + where: { order_id: { in: orderIds } }, + }); + await prisma.orderPickupChange.deleteMany({ + where: { order_id: { in: orderIds } }, + }); await prisma.orderItem.deleteMany({ where: { order_id: { in: orderIds } }, }); @@ -301,6 +315,13 @@ export async function resetSeedScope(prisma: PrismaClient): Promise { await prisma.storeFaqTopic.deleteMany({ where: { store_id: { in: storeIds } }, }); + // 정산은 주문이 가리키지만 시드 매장 주문은 1)에서 이미 지웠다 + await prisma.settlement.deleteMany({ + where: { store_id: { in: storeIds } }, + }); + await prisma.storeSettlementAccount.deleteMany({ + where: { store_id: { in: storeIds } }, + }); await prisma.storeBusinessHour.deleteMany({ where: { store_id: { in: storeIds } }, diff --git a/prisma/seed/orders.ts b/prisma/seed/orders.ts index d95cf347..21b40fc4 100644 --- a/prisma/seed/orders.ts +++ b/prisma/seed/orders.ts @@ -1,19 +1,32 @@ /** * 시드 주문 + 아이템 + 상태 히스토리. * - * user1 기준 6건: + * user1 기준 11건. o1~o6은 결제 도입 전 주문(결제 기록 없음), o7~o11은 입금 흐름을 거친 주문이다 + * (결제·환불·입금 기록은 seedPayments가 붙인다): * o1 SUBMITTED - p1×1 * o2 CONFIRMED - p2×1 + selectedOptions(레귤러) * o3 MADE - p3×2 * o4 PICKED_UP - p1×1 (리뷰 작성됨 → hasReviewableItem=false, hasMyReview=true) * o5 PICKED_UP - p4×1 (리뷰 미작성 → hasReviewableItem=true) * o6 CANCELED - p2×1 + * o7 PENDING_PAYMENT - p1×1 (입금 대기, 판매자 비노출) + * o8 NO_SHOW - p3×1 (정산 확정) + * o9 CANCELED - p2×1 (확정 뒤 구매자 사정 취소, 부분 환불 20,000원 + 잔액 정산 확정) + * o10 CANCELED - p1×1 (미입금 자동 취소 뒤 늦은 입금 → 반환 대상) + * o11 SUBMITTED - p1×1 (입금 확인으로 접수, 확정 마감 있음) */ import type { SeededStores } from './stores'; import type { SeededUser } from './users'; import { buildRegionLabel } from '@/common/utils/region-label'; -import type { OrderStatus, PrismaClient } from '@/generated/prisma/client'; +import type { + OrderActor, + OrderCancelFault, + OrderCancelReason, + OrderStatus, + PrismaClient, + Product, +} from '@/generated/prisma/client'; import { activeWhere } from '@/prisma'; /** 주문 시점 썸네일 스냅샷 — 주문 생성 경로와 같은 규칙(활성 첫 이미지). */ @@ -48,6 +61,22 @@ export interface SeededOrders { o4OrderItemId: bigint; o5PickedUpReviewable: bigint; o6Canceled: bigint; + o7PendingPayment: bigint; + o8NoShow: bigint; + o9PartialRefund: bigint; + o10UnpaidCanceled: bigint; + o11PaidSubmitted: bigint; +} + +interface FlowStep { + to: OrderStatus; + at: Date; + actor: OrderActor; + cancel?: { + reason: OrderCancelReason; + fault?: OrderCancelFault; + refundAmount: number; + }; } export async function seedOrders( @@ -98,7 +127,12 @@ export async function seedOrders( }, status_histories: { create: [ - { from_status: null, to_status: 'SUBMITTED', changed_at: now }, + { + from_status: null, + to_status: 'SUBMITTED', + changed_at: now, + actor_type: 'BUYER', + }, ], }, }, @@ -126,11 +160,13 @@ export async function seedOrders( from_status: null, to_status: 'SUBMITTED', changed_at: o2SubmittedAt, + actor_type: 'BUYER', }, { from_status: 'SUBMITTED', to_status: 'CONFIRMED', changed_at: o2ConfirmedAt, + actor_type: 'SELLER', }, ], }, @@ -223,16 +259,22 @@ export async function seedOrders( }, status_histories: { create: [ - { to_status: 'SUBMITTED', changed_at: o3Submitted }, + { + to_status: 'SUBMITTED', + changed_at: o3Submitted, + actor_type: 'BUYER', + }, { from_status: 'SUBMITTED', to_status: 'CONFIRMED', changed_at: o3Confirmed, + actor_type: 'SELLER', }, { from_status: 'CONFIRMED', to_status: 'MADE', changed_at: o3Made, + actor_type: 'SELLER', }, ], }, @@ -261,14 +303,29 @@ export async function seedOrders( picked_up_at: o4Picked, status_histories: { create: [ - { to_status: 'SUBMITTED', changed_at: o4Sub }, + { + to_status: 'SUBMITTED', + changed_at: o4Sub, + actor_type: 'BUYER', + }, { from_status: 'SUBMITTED', to_status: 'CONFIRMED', changed_at: o4Conf, + actor_type: 'SELLER', + }, + { + from_status: 'CONFIRMED', + to_status: 'MADE', + changed_at: o4Made, + actor_type: 'SELLER', + }, + { + from_status: 'MADE', + to_status: 'PICKED_UP', + changed_at: o4Picked, + actor_type: 'SELLER', }, - { from_status: 'CONFIRMED', to_status: 'MADE', changed_at: o4Made }, - { from_status: 'MADE', to_status: 'PICKED_UP', changed_at: o4Picked }, ], }, }, @@ -337,21 +394,25 @@ export async function seedOrders( { to_status: 'SUBMITTED', changed_at: new Date(now.getTime() - 8 * day), + actor_type: 'BUYER', }, { from_status: 'SUBMITTED', to_status: 'CONFIRMED', changed_at: new Date(now.getTime() - 7 * day), + actor_type: 'SELLER', }, { from_status: 'CONFIRMED', to_status: 'MADE', changed_at: new Date(now.getTime() - 6 * day), + actor_type: 'SELLER', }, { from_status: 'MADE', to_status: 'PICKED_UP', changed_at: o5Picked, + actor_type: 'SELLER', }, ], }, @@ -392,11 +453,18 @@ export async function seedOrders( }, status_histories: { create: [ - { to_status: 'SUBMITTED', changed_at: o6Sub }, + { + to_status: 'SUBMITTED', + changed_at: o6Sub, + actor_type: 'BUYER', + }, { from_status: 'SUBMITTED', to_status: 'CANCELED', changed_at: o6Cancel, + actor_type: 'SELLER', + cancel_reason: 'OTHER', + refund_amount: 0, note: '재료 수급 불가', }, ], @@ -404,6 +472,100 @@ export async function seedOrders( }, }); + // ── o7~o11: 입금 흐름(입금 대기 → 관리자 입금 확인 → 접수)을 거친 주문 ── + const storeAContext = { + accountId: user1.id, + buyerName, + buyerPhone, + storeId: storeA.id, + storeName: storeA.store_name, + regionLabel: regionA, + }; + const hour = 60 * 60 * 1000; + const o7 = await createFlowOrder(prisma, { + ...storeAContext, + orderNumber: 'SEED-O7-PENDING', + product: p1, + pickupAt: new Date(now.getTime() + 5 * day), + steps: [{ to: 'PENDING_PAYMENT', at: now, actor: 'BUYER' }], + }); + + const o8At = (h: number) => new Date(now.getTime() - 4 * day + h * hour); + const o8 = await createFlowOrder(prisma, { + ...storeAContext, + orderNumber: 'SEED-O8-NOSHOW', + product: p3, + pickupAt: o8At(72), + steps: [ + { to: 'PENDING_PAYMENT', at: o8At(0), actor: 'BUYER' }, + { to: 'SUBMITTED', at: o8At(0.5), actor: 'ADMIN' }, + { to: 'CONFIRMED', at: o8At(2), actor: 'SELLER' }, + { to: 'MADE', at: o8At(70), actor: 'SELLER' }, + { to: 'NO_SHOW', at: o8At(74), actor: 'SELLER' }, + ], + // 노쇼는 픽업 완료와 같이 결제액 전체로 정산 확정 + settlement: { baseAmount: p3.regular_price, at: o8At(74) }, + }); + + const o9At = (h: number) => new Date(now.getTime() - 3 * day + h * hour); + const o9Refund = 20000; + const o9 = await createFlowOrder(prisma, { + ...storeAContext, + orderNumber: 'SEED-O9-PARTIAL', + product: p2, + pickupAt: new Date(now.getTime() + 2 * day), + steps: [ + { to: 'PENDING_PAYMENT', at: o9At(0), actor: 'BUYER' }, + { to: 'SUBMITTED', at: o9At(0.5), actor: 'ADMIN' }, + { to: 'CONFIRMED', at: o9At(3), actor: 'SELLER' }, + { + to: 'CANCELED', + at: o9At(30), + actor: 'SELLER', + cancel: { + reason: 'BUYER_REQUEST', + fault: 'BUYER', + refundAmount: o9Refund, + }, + }, + ], + // 구매자 사정 부분 환불은 남은 금액을 취소 시각에 정산 확정 + settlement: { baseAmount: p2.regular_price - o9Refund, at: o9At(30) }, + }); + + const o10At = (h: number) => new Date(now.getTime() - 2 * day + h * hour); + const o10 = await createFlowOrder(prisma, { + ...storeAContext, + orderNumber: 'SEED-O10-UNPAID', + product: p1, + pickupAt: new Date(now.getTime() + 1 * day), + steps: [ + { to: 'PENDING_PAYMENT', at: o10At(0), actor: 'BUYER' }, + { + to: 'CANCELED', + at: o10At(1), + actor: 'SYSTEM', + cancel: { reason: 'PAYMENT_NOT_RECEIVED', refundAmount: 0 }, + }, + ], + }); + + const o11At = (h: number) => new Date(now.getTime() - 2 * hour + h * hour); + const o11PickupAt = new Date(now.getTime() + 3 * day); + const o11 = await createFlowOrder(prisma, { + ...storeAContext, + orderNumber: 'SEED-O11-PAID', + product: p1, + pickupAt: o11PickupAt, + steps: [ + { to: 'PENDING_PAYMENT', at: o11At(0), actor: 'BUYER' }, + { to: 'SUBMITTED', at: o11At(0.5), actor: 'ADMIN' }, + ], + confirmDeadlineAt: new Date( + Math.min(o11At(0.5).getTime() + day, o11PickupAt.getTime()), + ), + }); + return { o1Submitted: o1.id, o2Confirmed: o2.id, @@ -412,5 +574,107 @@ export async function seedOrders( o4OrderItemId: o4Item.id, o5PickedUpReviewable: o5.id, o6Canceled: o6.id, + o7PendingPayment: o7.id, + o8NoShow: o8.id, + o9PartialRefund: o9.id, + o10UnpaidCanceled: o10.id, + o11PaidSubmitted: o11.id, }; } + +const TIMESTAMP_BY_STATUS: Partial< + Record< + OrderStatus, + 'submitted_at' | 'confirmed_at' | 'made_at' | 'canceled_at' | 'no_show_at' + > +> = { + SUBMITTED: 'submitted_at', + CONFIRMED: 'confirmed_at', + MADE: 'made_at', + CANCELED: 'canceled_at', + NO_SHOW: 'no_show_at', +}; + +/** 단일 품목(정가, 수량 1) 주문을 전이 단계대로 만든다. 마지막 단계가 현재 상태다. */ +async function createFlowOrder( + prisma: PrismaClient, + args: { + accountId: bigint; + buyerName: string; + buyerPhone: string; + storeId: bigint; + storeName: string; + regionLabel: string | null; + orderNumber: string; + product: Product; + pickupAt: Date; + steps: FlowStep[]; + settlement?: { baseAmount: number; at: Date }; + confirmDeadlineAt?: Date; + }, +) { + const price = args.product.regular_price; + const timestamps = Object.fromEntries( + args.steps.flatMap((step) => { + const column = TIMESTAMP_BY_STATUS[step.to]; + return column ? [[column, step.at]] : []; + }), + ); + return prisma.order.create({ + data: { + order_number: args.orderNumber, + account_id: args.accountId, + status: args.steps[args.steps.length - 1].to, + pickup_at: args.pickupAt, + buyer_name: args.buyerName, + buyer_phone: args.buyerPhone, + subtotal_price: price, + discount_price: 0, + total_price: price, + created_at: args.steps[0].at, + ...timestamps, + confirm_deadline_at: args.confirmDeadlineAt ?? null, + ...(args.settlement + ? { + settlement_base_amount: args.settlement.baseAmount, + commission_amount: 0, + settlement_finalized_at: args.settlement.at, + } + : {}), + items: { + create: [ + { + store_id: args.storeId, + product_id: args.product.id, + product_name_snapshot: args.product.name, + store_name_snapshot: args.storeName, + store_region_label_snapshot: args.regionLabel, + product_thumbnail_url_snapshot: await firstImageUrl( + prisma, + args.product.id, + ), + regular_price_snapshot: price, + sale_price_snapshot: null, + quantity: 1, + item_subtotal_price: price, + }, + ], + }, + status_histories: { + create: args.steps.map((step, i) => ({ + from_status: i === 0 ? null : args.steps[i - 1].to, + to_status: step.to, + changed_at: step.at, + actor_type: step.actor, + ...(step.cancel + ? { + cancel_reason: step.cancel.reason, + cancel_fault: step.cancel.fault ?? null, + refund_amount: step.cancel.refundAmount, + } + : {}), + })), + }, + }, + }); +} diff --git a/prisma/seed/payments.ts b/prisma/seed/payments.ts new file mode 100644 index 00000000..5060b233 --- /dev/null +++ b/prisma/seed/payments.ts @@ -0,0 +1,106 @@ +/** + * 결제 설정·결제·환불·입금 기록 시드. seedOrders의 o7~o11에 붙이고, 처리자는 시드 관리자다. + * o7 입금 대기(PENDING, 1시간 기한) + * o8·o11 관리자 입금 확인(CONFIRMED) + * o9 확인된 결제 + 부분 환불 요청(계좌 입력 대기) + * o10 미입금 취소(CANCELED) + 늦은 입금을 반환 대상으로 연결 + * 결제 설정은 resetSeedScope가 지우지 않는 단일 행이라 upsert한다. + */ +import type { SeededOrders } from './orders'; + +import type { Payment, PrismaClient } from '@/generated/prisma/client'; + +const DEPOSIT_ACCOUNT = { + deposit_bank_code: '004', + deposit_account_number: '00000000000000', + deposit_account_holder: '케이퀵(테스트)', +} as const; + +const PAYMENT_WINDOW_MS = 60 * 60 * 1000; + +export async function seedPayments( + prisma: PrismaClient, + ctx: { orders: SeededOrders; admin: { id: bigint; label: string | null } }, +): Promise { + await prisma.paymentSetting.upsert({ + where: { id: 1 }, + create: { id: 1, ...DEPOSIT_ACCOUNT }, + update: DEPOSIT_ACCOUNT, + }); + + const orderOf = (id: bigint) => + prisma.order.findUniqueOrThrow({ where: { id } }); + const createPayment = async ( + orderId: bigint, + status: Payment['status'], + ): Promise => { + const order = await orderOf(orderId); + await prisma.payment.create({ + data: { + order_id: order.id, + method: 'BANK_TRANSFER', + status, + amount: order.total_price, + depositor_name: order.buyer_name, + ...DEPOSIT_ACCOUNT, + expires_at: new Date(order.created_at.getTime() + PAYMENT_WINDOW_MS), + ...(status === 'CONFIRMED' + ? { + confirmed_at: order.submitted_at, + confirm_source: 'ADMIN', + confirmed_by_account_id: ctx.admin.id, + confirmed_by_label_snapshot: ctx.admin.label, + } + : {}), + ...(status === 'CANCELED' ? { canceled_at: order.canceled_at } : {}), + }, + }); + }; + + const { orders } = ctx; + await createPayment(orders.o7PendingPayment, 'PENDING'); + await createPayment(orders.o8NoShow, 'CONFIRMED'); + await createPayment(orders.o9PartialRefund, 'CONFIRMED'); + await createPayment(orders.o10UnpaidCanceled, 'CANCELED'); + await createPayment(orders.o11PaidSubmitted, 'CONFIRMED'); + + const o9 = await orderOf(orders.o9PartialRefund); + const o9Cancel = await prisma.orderStatusHistory.findFirstOrThrow({ + where: { order_id: o9.id, to_status: 'CANCELED' }, + }); + await prisma.refund.create({ + data: { + order_id: o9.id, + kind: 'CANCEL', + cancel_order_id: o9.id, + amount: o9Cancel.refund_amount ?? 0, + requested_at: o9Cancel.changed_at, + }, + }); + + const o10 = await orderOf(orders.o10UnpaidCanceled); + const lateDepositAt = new Date( + (o10.canceled_at ?? o10.created_at).getTime() + 2 * PAYMENT_WINDOW_MS, + ); + const depositRecord = await prisma.depositRecord.create({ + data: { + kind: 'RETURN', + order_id: o10.id, + amount: o10.total_price, + depositor_name: o10.buyer_name, + deposited_at: lateDepositAt, + note: '미입금 자동 취소 뒤 들어온 입금', + recorded_by_account_id: ctx.admin.id, + recorded_by_label_snapshot: ctx.admin.label, + }, + }); + await prisma.refund.create({ + data: { + order_id: o10.id, + kind: 'DEPOSIT_RETURN', + deposit_record_id: depositRecord.id, + amount: depositRecord.amount, + requested_at: lateDepositAt, + }, + }); +} diff --git a/src/features/audit-log/audit-log.types.graphql b/src/features/audit-log/audit-log.types.graphql index 1625ab85..36e514d5 100644 --- a/src/features/audit-log/audit-log.types.graphql +++ b/src/features/audit-log/audit-log.types.graphql @@ -62,6 +62,26 @@ enum AuditTargetType { 검색 진입 화면 키워드 바로가기 칩. 순서 변경은 순서가 바뀐 칩마다 1건씩 남는다. """ SEARCH_KEYWORD_CHIP + """ + 플랫폼 결제 설정(수수료율·입금 계좌). + """ + PAYMENT_SETTING + """ + 매장 정산 계좌. 기록에는 계좌번호 마스킹 값만 남는다. + """ + SETTLEMENT_ACCOUNT + """ + 주간 정산(송금 완료 처리). + """ + SETTLEMENT + """ + 환불(완료 처리). + """ + REFUND + """ + 입금 기록(반환 연결·주인 모를 입금 종결). + """ + DEPOSIT_RECORD } """ diff --git a/src/features/dashboard/constants/dashboard.constants.ts b/src/features/dashboard/constants/dashboard.constants.ts index e598ffaf..ae39d517 100644 --- a/src/features/dashboard/constants/dashboard.constants.ts +++ b/src/features/dashboard/constants/dashboard.constants.ts @@ -16,6 +16,11 @@ export const AUDIT_TARGET_TYPES = [ 'REVIEW_REPORT', 'NOTIFICATION', 'SEARCH_KEYWORD_CHIP', + 'PAYMENT_SETTING', + 'SETTLEMENT_ACCOUNT', + 'SETTLEMENT', + 'REFUND', + 'DEPOSIT_RECORD', ] as const; export type AuditTargetTypeValue = (typeof AUDIT_TARGET_TYPES)[number]; export const AUDIT_ACTION_TYPES = [ diff --git a/src/features/notification/notification.types.graphql b/src/features/notification/notification.types.graphql index 8aa59e88..b4c8a6a9 100644 --- a/src/features/notification/notification.types.graphql +++ b/src/features/notification/notification.types.graphql @@ -3,7 +3,7 @@ """ enum NotificationType { """ - 주문 상태 변경 알림. ORDER_CONFIRMED·ORDER_MADE·ORDER_PICKED_UP 이벤트가 여기 속한다. + 주문 상태 변경 알림. 주문(ORDER_*)·환불(REFUND_*) 이벤트가 여기 속한다. """ ORDER_STATUS """ @@ -44,4 +44,28 @@ enum NotificationEvent { 주문이 취소됐다(판매자 또는 운영자). 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 } diff --git a/src/features/order/order.types.graphql b/src/features/order/order.types.graphql index fa6df15d..a08bb093 100644 --- a/src/features/order/order.types.graphql +++ b/src/features/order/order.types.graphql @@ -1,12 +1,15 @@ """ -주문 상태. 구매자·판매자 API가 공용으로 쓴다. +주문 상태. 구매자·판매자·관리자 API가 공용으로 쓴다. 값은 늘어날 수 있으니 모르는 값을 받아도 화면이 죽지 않게 처리한다. -전이는 `SUBMITTED → CONFIRMED → MADE → PICKED_UP` 한 방향이며 각 단계는 직전 -상태에서만 진입할 수 있다. `CANCELED`는 `PICKED_UP` 이전 세 상태에서만 가능하고, -어떤 상태에서도 `SUBMITTED`로 되돌아갈 수 없다. +흐름은 `PENDING_PAYMENT → SUBMITTED → CONFIRMED → MADE → PICKED_UP`이며 어떤 상태에서도 +앞 단계로 되돌아갈 수 없다. 판매자가 직접 바꿀 수 있는 전이는 `SUBMITTED → CONFIRMED`, +`CONFIRMED → MADE`, `MADE → PICKED_UP`, `SUBMITTED·CONFIRMED·MADE → CANCELED`뿐이다. +판매자에게는 입금이 확인된(접수된) 주문만 보인다. """ enum OrderStatusType { - """구매자가 주문을 넣은 직후의 초기 상태. 판매자 확인 대기.""" + """입금 대기. 주문 직후 계좌이체 입금을 기다리는 상태이고, 판매자에게 보이지 않는다.""" + PENDING_PAYMENT + """입금이 확인돼 접수된 상태. 판매자 확인 대기.""" SUBMITTED """판매자가 주문을 확인·수락한 상태. 제작 대기.""" CONFIRMED @@ -14,6 +17,8 @@ enum OrderStatusType { MADE """구매자가 수령을 마친 종료 상태. 이후 상태 변경 불가.""" PICKED_UP + """노쇼. 구매자가 픽업 시간에 오지 않아 판매자가 처리한 종료 상태. 환불 없음, 리뷰 불가.""" + NO_SHOW """취소된 종료 상태. 취소 처리에는 사유(note)가 필수다.""" CANCELED } diff --git a/src/features/order/repositories/order-payment-schema.migration.spec.ts b/src/features/order/repositories/order-payment-schema.migration.spec.ts new file mode 100644 index 00000000..aedd8d71 --- /dev/null +++ b/src/features/order/repositories/order-payment-schema.migration.spec.ts @@ -0,0 +1,202 @@ +import { readFileSync } from 'node:fs'; +import { join } from 'node:path'; + +import type { PrismaClient } from '@/generated/prisma/client'; +import { disconnectTestPrismaClient } from '@/test/db/prisma-test-client'; +import { closeTruncateConnection, truncateAll } from '@/test/db/truncate'; +import { createOrder } from '@/test/factories'; +import { createTestingModuleWithRealDb } from '@/test/modules/testing-module.builder'; + +// 결제 도입 마이그레이션의 백필 SQL을 그대로 실행해 기존 주문·이력이 새 규칙(이력 주체, 판매자 노출, 결제 설정 행)으로 +// 옮겨지는지 본다. 마이그레이션은 빈 DB에 적용되므로 백필은 여기서만 검증된다. +const MIGRATION = join( + __dirname, + '../../../../prisma/migrations/20261118150004_order_payment_schema/migration.sql', +); + +function backfillStatements(): string[] { + const sql = readFileSync(MIGRATION, 'utf8'); + const body = sql.slice( + sql.indexOf('-- backfill'), + sql.indexOf('-- end backfill'), + ); + return body + .split(';') + .map((stmt) => stmt.replace(/^\s*--[^\n]*$/gm, '').trim()) + .filter((stmt) => stmt.length > 0); +} + +describe('주문 결제 스키마 백필 (real DB)', () => { + let prisma: PrismaClient; + + beforeAll(async () => { + ({ prisma } = await createTestingModuleWithRealDb({ providers: [] })); + }); + afterAll(async () => { + await closeTruncateConnection(); + await disconnectTestPrismaClient(); + }); + beforeEach(async () => { + await truncateAll(); + }); + + async function runBackfill(): Promise { + const statements = backfillStatements(); + expect(statements).toHaveLength(4); + for (const stmt of statements) await prisma.$executeRawUnsafe(stmt); + } + + async function history( + orderId: bigint, + row: { + from: 'SUBMITTED' | 'CONFIRMED' | null; + to: 'SUBMITTED' | 'CONFIRMED' | 'CANCELED'; + note?: string; + }, + ) { + // 최신 스키마라 actor_type을 비울 수 없다 — 백필이 덮어쓰는지 보려고 SYSTEM으로 채워 둔다 + return prisma.orderStatusHistory.create({ + data: { + order_id: orderId, + from_status: row.from, + to_status: row.to, + note: row.note ?? null, + actor_type: 'SYSTEM', + }, + }); + } + + it('이력 주체: 최초는 구매자, [관리자] 접두 메모는 관리자, 나머지는 판매자다', async () => { + const order = await createOrder(prisma, { status: 'CANCELED' }); + const first = await history(order.id, { from: null, to: 'SUBMITTED' }); + const seller = await history(order.id, { + from: 'SUBMITTED', + to: 'CONFIRMED', + note: '[관리자]가 아닌 메모', + }); + const admin = await history(order.id, { + from: 'CONFIRMED', + to: 'CANCELED', + note: '[관리자] 가게 사정', + }); + + await runBackfill(); + + const actors = await prisma.orderStatusHistory.findMany({ + where: { id: { in: [first.id, seller.id, admin.id] } }, + orderBy: { id: 'asc' }, + select: { actor_type: true }, + }); + expect(actors.map((a) => a.actor_type)).toEqual([ + 'BUYER', + 'SELLER', + 'ADMIN', + ]); + }); + + it('기존 취소 이력만 사유 기타·환불 0이 된다', async () => { + const order = await createOrder(prisma, { status: 'CANCELED' }); + const confirmed = await history(order.id, { + from: 'SUBMITTED', + to: 'CONFIRMED', + }); + const canceled = await history(order.id, { + from: 'CONFIRMED', + to: 'CANCELED', + }); + + await runBackfill(); + + const rows = await prisma.orderStatusHistory.findMany({ + where: { id: { in: [confirmed.id, canceled.id] } }, + orderBy: { id: 'asc' }, + select: { cancel_reason: true, refund_amount: true }, + }); + expect(rows).toEqual([ + { cancel_reason: null, refund_amount: null }, + { cancel_reason: 'OTHER', refund_amount: 0 }, + ]); + }); + + it('입금 대기가 아닌 주문의 비어 있는 submitted_at을 생성 시각으로 채우고 이미 있는 값은 둔다', async () => { + const created = new Date('2026-05-01T01:02:03.456Z'); + const kept = new Date('2026-05-02T00:00:00.000Z'); + const legacy = await createOrder(prisma, { + status: 'CANCELED', + created_at: created, + submitted_at: null, + }); + const pending = await createOrder(prisma, { + status: 'PENDING_PAYMENT', + created_at: created, + }); + const already = await createOrder(prisma, { + status: 'SUBMITTED', + created_at: created, + submitted_at: kept, + }); + + await runBackfill(); + + const submittedAt = async (id: bigint) => + (await prisma.order.findUniqueOrThrow({ where: { id } })).submitted_at; + expect(await submittedAt(legacy.id)).toEqual(created); + expect(await submittedAt(pending.id)).toBeNull(); + expect(await submittedAt(already.id)).toEqual(kept); + }); + + it('결제 설정 행(id=1)을 하나 넣고 기본값은 수수료 0·계좌 없음이다', async () => { + await runBackfill(); + expect(await prisma.paymentSetting.findMany()).toEqual([ + expect.objectContaining({ + id: 1, + commission_rate_bps: 0, + deposit_bank_code: null, + deposit_account_number: null, + deposit_account_holder: null, + }), + ]); + }); + + // 기존 값의 순번이 바뀌면 저장값이 다른 값으로 읽히고 INSTANT ALTER도 깨진다 + const STATUS = [ + 'SUBMITTED CONFIRMED MADE PICKED_UP CANCELED', + 'PENDING_PAYMENT NO_SHOW', + ]; + it.each([ + ['order', 'status', ...STATUS], + ['order_status_history', 'to_status', ...STATUS], + [ + 'notification', + 'event', + 'REVIEW_LIKED ORDER_CONFIRMED ORDER_MADE ORDER_PICKED_UP ORDER_CANCELED', + 'ORDER_PAYMENT_CONFIRMED ORDER_PAYMENT_EXPIRED ORDER_NO_SHOW ' + + 'ORDER_PICKUP_RESCHEDULED REFUND_ACCOUNT_REQUESTED REFUND_COMPLETED', + ], + [ + 'audit_log', + 'target_type', + 'STORE PRODUCT ORDER CONVERSATION CHANGE_PASSWORD ACCOUNT BANNER CATEGORY TAG ' + + 'REGION REVIEW REVIEW_COMMENT REVIEW_REPORT NOTIFICATION SEARCH_KEYWORD_CHIP', + 'PAYMENT_SETTING SETTLEMENT_ACCOUNT SETTLEMENT REFUND DEPOSIT_RECORD', + ], + ])( + '%s.%s enum은 기존 값 순서를 지키고 새 값을 끝에 붙인다', + async (table, column, existing, appended) => { + const rows = await prisma.$queryRaw<{ column_type: string }[]>` + SELECT COLUMN_TYPE AS column_type FROM information_schema.COLUMNS + WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ${table} AND COLUMN_NAME = ${column}`; + const values = [...rows[0].column_type.matchAll(/'([^']+)'/g)].map( + (m) => m[1], + ); + expect(values).toEqual(`${existing} ${appended}`.split(' ')); + }, + ); + + it('주문 상태 기본값은 입금 대기다', async () => { + const rows = await prisma.$queryRaw<{ column_default: string }[]>` + SELECT COLUMN_DEFAULT AS column_default FROM information_schema.COLUMNS + WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'order' AND COLUMN_NAME = 'status'`; + expect(rows[0].column_default).toBe('PENDING_PAYMENT'); + }); +}); diff --git a/src/features/order/repositories/order.repository.spec.ts b/src/features/order/repositories/order.repository.spec.ts index cc41ae3c..9b2a0374 100644 --- a/src/features/order/repositories/order.repository.spec.ts +++ b/src/features/order/repositories/order.repository.spec.ts @@ -287,6 +287,7 @@ describe('OrderRepository (real DB)', () => { from_status: 'SUBMITTED', to_status: 'CONFIRMED', changed_at: new Date(), + actor_type: 'SELLER', note: '확정', }, }); @@ -914,6 +915,16 @@ describe('OrderRepository (real DB)', () => { submitArgs({ buyerId: buyer.id, store, product }), ); + const history = await prisma.orderStatusHistory.findFirstOrThrow({ + where: { order_id: created!.id }, + }); + expect(history).toMatchObject({ + from_status: null, + to_status: 'SUBMITTED', + actor_type: 'BUYER', + actor_account_id: buyer.id, + }); + const events = await prisma.outbox.findMany(); expect(events).toHaveLength(1); expect(events[0]).toMatchObject({ diff --git a/src/features/order/repositories/order.repository.ts b/src/features/order/repositories/order.repository.ts index 78199b2f..c56c6a71 100644 --- a/src/features/order/repositories/order.repository.ts +++ b/src/features/order/repositories/order.repository.ts @@ -10,6 +10,7 @@ import { OutboxPublisher } from '@/features/outbox'; import { AuditActionType, AuditTargetType, + OrderActor, OrderStatus, Prisma, type AccountType, @@ -330,6 +331,8 @@ export class OrderRepository { from_status: null, to_status: OrderStatus.SUBMITTED, changed_at: args.submittedAt, + actor_type: OrderActor.BUYER, + actor_account_id: args.accountId, }, }, }, @@ -824,6 +827,8 @@ export class OrderRepository { from_status: fromStatus, to_status: args.toStatus, changed_at: args.now, + actor_type: OrderActor.SELLER, + actor_account_id: args.actorAccountId, note: args.note, }, }); @@ -988,6 +993,8 @@ export class OrderRepository { from_status: current.status, to_status: OrderStatus.CANCELED, changed_at: args.now, + actor_type: OrderActor.ADMIN, + actor_account_id: args.actorAccountId, note: args.note, }, }); diff --git a/src/features/order/services/order-admin.service.spec.ts b/src/features/order/services/order-admin.service.spec.ts index 37d3ef03..888d448d 100644 --- a/src/features/order/services/order-admin.service.spec.ts +++ b/src/features/order/services/order-admin.service.spec.ts @@ -230,7 +230,12 @@ describe('AdminOrderService (real DB)', () => { it('구매자 요약·전체 품목·상태 이력을 준다', async () => { const { order, item, buyer } = await orderWithItem(); await prisma.orderStatusHistory.create({ - data: { order_id: order.id, from_status: null, to_status: 'SUBMITTED' }, + data: { + order_id: order.id, + from_status: null, + to_status: 'SUBMITTED', + actor_type: 'BUYER', + }, }); const result = await service.adminOrder(await admin(), order.id); @@ -281,8 +286,12 @@ describe('AdminOrderService (real DB)', () => { const history = await prisma.orderStatusHistory.findFirstOrThrow({ where: { order_id: order.id, to_status: 'CANCELED' }, }); - expect(history.from_status).toBe(status); - expect(history.note).toBe('[관리자] 가게 사정'); + expect(history).toMatchObject({ + from_status: status, + actor_type: 'ADMIN', + actor_account_id: actor, + note: '[관리자] 가게 사정', + }); await drainOutbox(dispatcher); const notification = await prisma.notification.findFirstOrThrow({ where: { order_id: order.id }, diff --git a/src/features/order/services/order-checkout.service.spec.ts b/src/features/order/services/order-checkout.service.spec.ts index 7fd3612c..d7ee7307 100644 --- a/src/features/order/services/order-checkout.service.spec.ts +++ b/src/features/order/services/order-checkout.service.spec.ts @@ -29,6 +29,7 @@ import { createAccount, createOrder as createOrderRow, createOrderItem, + createPaymentSetting, createProduct, createRegion, createStore, @@ -86,6 +87,8 @@ describe('OrderCheckoutService (real DB)', () => { beforeEach(async () => { await truncateAll(); + // truncateAll이 마이그레이션이 넣은 결제 설정 행까지 지운다 + await createPaymentSetting(prisma); jest.spyOn(clock, 'now').mockReturnValue(NOW); }); @@ -267,6 +270,7 @@ describe('OrderCheckoutService (real DB)', () => { expect(saved.status_histories[0]).toMatchObject({ from_status: null, to_status: 'SUBMITTED', + actor_type: 'BUYER', }); }); diff --git a/src/features/order/services/order-my.service.spec.ts b/src/features/order/services/order-my.service.spec.ts index b3fed3a3..3f95be44 100644 --- a/src/features/order/services/order-my.service.spec.ts +++ b/src/features/order/services/order-my.service.spec.ts @@ -499,6 +499,7 @@ describe('UserOrderService (real DB)', () => { from_status: 'SUBMITTED', to_status: 'CONFIRMED', changed_at: new Date('2026-04-15T10:00:00Z'), + actor_type: 'SELLER', note: '접수 확정', }, }); diff --git a/src/features/order/services/order-seller.service.spec.ts b/src/features/order/services/order-seller.service.spec.ts index bfc5d191..acd3a847 100644 --- a/src/features/order/services/order-seller.service.spec.ts +++ b/src/features/order/services/order-seller.service.spec.ts @@ -273,6 +273,7 @@ describe('SellerOrderService (real DB)', () => { from_status: 'SUBMITTED', to_status: 'CONFIRMED', changed_at: new Date('2026-04-15T10:00:00Z'), + actor_type: 'SELLER', note: '접수 확정', }, }); @@ -299,6 +300,7 @@ describe('SellerOrderService (real DB)', () => { from_status: 'SUBMITTED', to_status: 'CONFIRMED', changed_at: new Date('2026-04-15T10:00:00Z'), + actor_type: 'SELLER', deleted_at: new Date(), }, }); @@ -392,8 +394,12 @@ describe('SellerOrderService (real DB)', () => { where: { order_id: order.id }, }); expect(histories).toHaveLength(1); - expect(histories[0].from_status).toBe('SUBMITTED'); - expect(histories[0].to_status).toBe('CONFIRMED'); + expect(histories[0]).toMatchObject({ + from_status: 'SUBMITTED', + to_status: 'CONFIRMED', + actor_type: 'SELLER', + actor_account_id: account.id, + }); }); it('사전 검사 뒤 품목이 삭제돼도 상태는 바뀌고 첫 품목 필드는 null이다', async () => { diff --git a/src/features/order/types/order-seller-output.type.ts b/src/features/order/types/order-seller-output.type.ts index 09f06fe9..9cc8a201 100644 --- a/src/features/order/types/order-seller-output.type.ts +++ b/src/features/order/types/order-seller-output.type.ts @@ -2,11 +2,12 @@ import type { OrderItemDetailOutput, OrderStatusHistoryOutput, } from '@/features/order/types/order-output.type'; +import type { OrderStatus } from '@/generated/prisma/client'; export interface SellerOrderSummaryOutput { id: string; orderNumber: string; - status: 'SUBMITTED' | 'CONFIRMED' | 'MADE' | 'PICKED_UP' | 'CANCELED'; + status: OrderStatus; pickupAt: Date; buyerName: string; buyerPhone: string; @@ -20,7 +21,7 @@ export interface SellerOrderDetailOutput { id: string; orderNumber: string; accountId: string; - status: 'SUBMITTED' | 'CONFIRMED' | 'MADE' | 'PICKED_UP' | 'CANCELED'; + status: OrderStatus; pickupAt: Date; buyerName: string; buyerPhone: string; @@ -42,7 +43,7 @@ export interface SellerOrderDetailOutput { export interface SellerOrderUpdateEvent { orderId: string; orderNumber: string; - status: 'SUBMITTED' | 'CONFIRMED' | 'MADE' | 'PICKED_UP' | 'CANCELED'; + status: OrderStatus; pickupAt: string; buyerName: string; totalPrice: number; diff --git a/src/test/enum-sdl-sync.spec.ts b/src/test/enum-sdl-sync.spec.ts new file mode 100644 index 00000000..8ebe0751 --- /dev/null +++ b/src/test/enum-sdl-sync.spec.ts @@ -0,0 +1,90 @@ +import { readFileSync } from 'node:fs'; +import { join } from 'node:path'; + +import { Kind, parse, print, visit } from 'graphql'; + +import { + ConversationBodyFormat, + NotificationEvent, + OrderStatus, +} from '@/generated/prisma/client'; + +/** + * 응답에 그대로 실리는 Prisma enum은 SDL enum이 그 값을 모두 가져야 한다. 하나라도 빠지면 그 값이 든 + * 응답 전체가 직렬화 오류로 실패한다(예: 새 NotificationEvent가 든 myNotifications). tsc는 둘을 묶지 못한다. + */ +const PAIRS: Array< + [label: string, prisma: string[], file: string, sdl: string] +> = [ + [ + 'NotificationEvent', + Object.values(NotificationEvent), + 'src/features/notification/notification.types.graphql', + 'NotificationEvent', + ], + [ + 'ConversationBodyFormat', + Object.values(ConversationBodyFormat), + 'src/features/conversation/conversation.types.graphql', + 'ConversationBodyFormat', + ], + [ + 'OrderStatus', + Object.values(OrderStatus), + 'src/features/order/order.types.graphql', + 'OrderStatusType', + ], +]; + +function sdlEnumValues(source: string, enumName: string): string[] { + for (const def of parse(source).definitions) { + if (def.kind === Kind.ENUM_TYPE_DEFINITION && def.name.value === enumName) { + return (def.values ?? []).map((v) => v.name.value); + } + } + throw new Error(`enum ${enumName}이 SDL에 없습니다`); +} + +function missingInSdl(prisma: string[], sdl: string[]): string[] { + return prisma.filter((v) => !sdl.includes(v)); +} + +const read = (file: string) => readFileSync(join(process.cwd(), file), 'utf8'); + +describe('Prisma enum ⊆ SDL enum', () => { + describe('검사기 반증', () => { + it.each(PAIRS)( + '%s: SDL에서 값 하나를 지우면 그 값이 빠졌다고 잡는다', + (_label, prisma, file, sdl) => { + const removed = prisma[prisma.length - 1]; + const broken = print( + visit(parse(read(file)), { + EnumValueDefinition: (node) => + node.name.value === removed ? null : undefined, + }), + ); + expect(missingInSdl(prisma, sdlEnumValues(broken, sdl))).toEqual([ + removed, + ]); + }, + ); + + it('SDL에만 있는 값은 허용한다(부분집합 판정)', () => { + expect(missingInSdl(['A'], ['A', 'B'])).toEqual([]); + }); + + it('SDL에 enum이 없으면 실패한다', () => { + expect(() => sdlEnumValues('enum Other { A }', 'NoSuchEnum')).toThrow( + 'NoSuchEnum', + ); + }); + }); + + it.each(PAIRS)( + '%s: Prisma 값이 SDL에 모두 있다', + (_label, prisma, file, sdl) => { + expect(prisma.length).toBeGreaterThan(0); + expect(missingInSdl(prisma, sdlEnumValues(read(file), sdl))).toEqual([]); + }, + ); +}); diff --git a/src/test/factories/order.factory.ts b/src/test/factories/order.factory.ts index 0c81f5ca..b81ecf56 100644 --- a/src/test/factories/order.factory.ts +++ b/src/test/factories/order.factory.ts @@ -4,6 +4,7 @@ import type { Order, OrderItem, OrderStatus, + PaymentSetting, PrismaClient, } from '@/generated/prisma/client'; import { activeWhere } from '@/prisma'; @@ -24,6 +25,8 @@ export interface OrderOverrides { deleted_at?: Date; idempotency_key?: string; created_at?: Date; + /** 미지정 시 PENDING_PAYMENT면 null, 그 밖의 상태는 생성 시각(입금 확인 = 판매자 노출) */ + submitted_at?: Date | null; } export async function createOrder( @@ -34,12 +37,13 @@ export async function createOrder( const accountId = overrides.account_id ?? (await createAccount(prisma, { account_type: 'USER' })).id; + const status = overrides.status ?? 'SUBMITTED'; return prisma.order.create({ data: { account_id: accountId, order_number: overrides.order_number ?? `ORD-${Date.now()}-${seq}`, - status: overrides.status ?? 'SUBMITTED', + status, pickup_at: overrides.pickup_at ?? new Date(Date.now() + DAY_MS), buyer_name: overrides.buyer_name ?? `Buyer ${seq}`, buyer_phone: overrides.buyer_phone ?? '010-0000-0000', @@ -51,10 +55,45 @@ export async function createOrder( : {}), ...(overrides.deleted_at ? { deleted_at: overrides.deleted_at } : {}), ...(overrides.created_at ? { created_at: overrides.created_at } : {}), + submitted_at: + overrides.submitted_at !== undefined + ? overrides.submitted_at + : status === 'PENDING_PAYMENT' + ? null + : (overrides.created_at ?? new Date()), }, }); } +export type PaymentSettingOverrides = Partial< + Pick< + PaymentSetting, + | 'commission_rate_bps' + | 'deposit_bank_code' + | 'deposit_account_number' + | 'deposit_account_holder' + > +>; + +/** 결제 설정 단일 행(id=1). truncateAll이 마이그레이션이 넣은 행까지 지우므로 필요한 spec이 다시 만든다. */ +export async function createPaymentSetting( + prisma: PrismaClient, + overrides: PaymentSettingOverrides = {}, +): Promise { + const data = { + commission_rate_bps: 0, + deposit_bank_code: '004', + deposit_account_number: '12345678901234', + deposit_account_holder: '케이퀵', + ...overrides, + }; + return prisma.paymentSetting.upsert({ + where: { id: 1 }, + create: { id: 1, ...data }, + update: data, + }); +} + export interface OrderItemOverrides { order_id?: bigint; store_id?: bigint; diff --git a/src/test/model-ownership.ts b/src/test/model-ownership.ts index f214744e..2e50fae6 100644 --- a/src/test/model-ownership.ts +++ b/src/test/model-ownership.ts @@ -90,6 +90,13 @@ export const MODEL_OWNERSHIP: Readonly> = { OrderItemCustomText: order([]), OrderItemCustomFreeEdit: order([]), OrderItemCustomFreeEditAttachment: order([]), + Payment: order(), + Refund: order(), + DepositRecord: order(), + Settlement: order(), + StoreSettlementAccount: order(), + PaymentSetting: order(), + OrderPickupChange: order(), Review: review(), ReviewMedia: review(), diff --git a/src/test/seed-reset-scope.spec.ts b/src/test/seed-reset-scope.spec.ts index 3f854e03..6f50ce54 100644 --- a/src/test/seed-reset-scope.spec.ts +++ b/src/test/seed-reset-scope.spec.ts @@ -11,6 +11,7 @@ import { resetSeedScope, } from '../../prisma/seed/idempotent'; import { seedOrders } from '../../prisma/seed/orders'; +import { seedPayments } from '../../prisma/seed/payments'; import { seedRegions } from '../../prisma/seed/regions'; import { seedReviews } from '../../prisma/seed/reviews'; import { seedStores } from '../../prisma/seed/stores'; @@ -201,6 +202,81 @@ describe('resetSeedScope (real DB)', () => { ).toBeNull(); }); + it('결제·환불·입금 기록·픽업 변경·정산·정산 계좌가 붙어도 정리하고 다시 시드하며 결제 설정은 남긴다', async () => { + const seedAll = async () => { + const users = await seedUsers(prisma); + await seedRegions(prisma); + const categories = await seedCategories(prisma); + const stores = await seedStores(prisma, { categories }); + const orders = await seedOrders(prisma, { users, stores }); + const admin = await seedAdmins(prisma); + await seedPayments(prisma, { orders, admin }); + return { stores, orders }; + }; + const { stores, orders } = await seedAll(); + const [storeA] = stores.stores; + const settlement = await prisma.settlement.create({ + data: { + store_id: storeA.id, + store_name_snapshot: storeA.store_name, + period_start: new Date('2026-11-02'), + period_end: new Date('2026-11-08'), + order_count: 1, + settlement_base_amount: 25000, + commission_amount: 0, + payout_amount: 25000, + }, + }); + await prisma.order.update({ + where: { id: orders.o8NoShow }, + data: { settlement_id: settlement.id }, + }); + await prisma.storeSettlementAccount.create({ + data: { + store_id: storeA.id, + bank_code: '004', + account_holder: '케이크샵 A', + account_number_enc: 'v1.test', + account_number_last4: '1234', + updated_by_account_id: storeA.seller_account_id, + updated_by_role: 'SELLER', + }, + }); + await prisma.orderPickupChange.create({ + data: { + order_id: orders.o11PaidSubmitted, + from_pickup_at: new Date('2026-11-20T03:00:00Z'), + to_pickup_at: new Date('2026-11-21T03:00:00Z'), + changed_by_account_id: storeA.seller_account_id, + changed_at: new Date(), + }, + }); + const counts = () => + Promise.all([ + prisma.payment.count(), + prisma.refund.count(), + prisma.depositRecord.count(), + ]); + expect(await counts()).toEqual([5, 2, 1]); + + await resetSeedScope(prisma); + for (const count of await Promise.all([ + prisma.payment.count(), + prisma.refund.count(), + prisma.depositRecord.count(), + prisma.orderPickupChange.count(), + prisma.settlement.count(), + prisma.storeSettlementAccount.count(), + ])) { + expect(count).toBe(0); + } + expect(await prisma.paymentSetting.count()).toBe(1); + + await seedAll(); + expect(await counts()).toEqual([5, 2, 1]); + expect(await prisma.paymentSetting.count()).toBe(1); + }); + it('시드 사용자가 시드 밖 리뷰에 단 댓글은 지우고 그 리뷰는 남긴다', async () => { const [seedUser] = await seedThroughReviews(); const outsideReview = await createReview(prisma); From 6beaa2d645777e73e4528caacc60cf2a23e61635 Mon Sep 17 00:00:00 2001 From: chanwoo7 Date: Thu, 19 Nov 2026 00:26:32 +0900 Subject: [PATCH 03/54] =?UTF-8?q?feat:=20=EC=9E=85=EA=B8=88=20=EB=8C=80?= =?UTF-8?q?=EA=B8=B0=C2=B7=EB=85=B8=EC=87=BC=20=EC=83=81=ED=83=9C=20?= =?UTF-8?q?=EB=B6=84=EB=A5=98=EC=99=80=20=ED=8C=90=EB=A7=A4=EC=9E=90=20?= =?UTF-8?q?=EB=85=B8=EC=B6=9C=20=EB=B2=94=EC=9C=84,=20=EC=A7=84=ED=96=89?= =?UTF-8?q?=20=EC=A3=BC=EB=AC=B8=20=EC=9A=94=EC=95=BD=C2=B7=ED=95=84?= =?UTF-8?q?=ED=84=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 새 상태(PENDING_PAYMENT·NO_SHOW)를 기존 조회·전이 규칙에 분류해 넣는다. 판매자에게는 입금이 확인된 주문만 보이고, 판매자 전이는 허용 목록 밖을 거절해 새 상태로 넘어가지 못한다. 주문 생성은 여전히 SUBMITTED라 기존 동작은 바뀌지 않는다. - 분류: order/constants/order-status-traits.ts의 ORDER_STATUS_TRAITS(satisfies Record)에서 IN_PROGRESS_ORDER_STATUSES(입금 대기·접수·확정·제작 완료)를 파생. 새 상태는 분류 전까지 tsc가 막음 - 판매자 노출: submitted_at IS NOT NULL을 목록·건수(storeOrderScopeWhere)·상세·대시보드 집계·상태 변경 잠금 SQL에 건다. 상세 이력은 입금 대기 행을 빼고 접수 이력의 fromStatus를 null로 내림. 관리자 취소는 입금 확인 전 주문이면 판매자 구독으로 발행하지 않음 - 상태 리터럴 4곳을 Prisma enum 파생으로: 관리자·판매자 목록 입력과 판매자 상태 변경 입력은 IsEnum(OrderStatus), 정책 parse는 Object.values(OrderStatus) - assertSellerTransition을 허용 목록(기본 거절)으로: 기존 6개 전이 외 to는 INVALID_ORDER_STATUS_TRANSITION(취소는 ORDER_NOT_CANCELLABLE). NO_SHOW·PENDING_PAYMENT는 이후 표 기반 전이 정책이 연다 - 대시보드: 판매자 접수 지표 기준을 created_at → submitted_at, SellerDashboard.pendingPaymentQuantity(입금 대기 점유 수량, bookedQuantity에 포함). 관리자 AdminOrderStatusCounts.pendingPayment·noShow, 금액 합에서 취소·입금 대기 제외 - 랭킹 유효 상태에 NO_SHOW, 마이페이지 진행 주문은 IN_PROGRESS_ORDER_STATUSES. 리뷰는 PICKED_UP만이라 노쇼 리뷰 불가(회귀 테스트) - 조회: adminStoreInProgressOrderSummary(storeId) { storeId totalCount byStatus { status count } }(order.groupBy, 0건 상태 제외·흐름 순), AdminOrderListInput.inProgress(null·false = 전체, status와 AND), SellerOrderListInput.buyerAccountId - 게이트: roles-coverage admin 접두 59 → 60. admin-query-null-inputs는 input 객체 Query 수 변화 없음(17), inProgress null은 전수 검사에 포함 테스트 - 정책: 판매자 전이 7×7 전수 49, parse(enum 전부 + 잘못된 값 3), 취소 메모 7 - 분류 표 9, DTO 입력 28(관리자 목록·판매자 목록·판매자 상태 변경이 enum 전부를 받는지 21, inProgress 5, buyerAccountId 1, 알 수 없는 status 1) - 판매자 노출 8(목록·건수, 상세 404, 이력, 상태 변경 404, to=NO_SHOW·PENDING_PAYMENT 거절, buyerAccountId·빈 문자열·"0"), 잠금 SQL 1, 집계 3 - 관리자: inProgress 5(true·false·null·undefined·AND), 진행 주문 요약 3(새 상태·0건·403) + 리졸버 경로 1, 입금 대기·노쇼 취소 400 2, 입금 확인 전 취소 미발행 1 - 대시보드 3(판매자 2·관리자 1 갱신), 랭킹 상태 전수 7, 노쇼 리뷰 불가 2곳(작성 거절·작성 가능 목록 제외), 마이페이지·진행 주문 갱신 2 - 가드 반증: 노출 조건·잠금 SQL·구독 가드·SDL 값을 지우면 해당 테스트가 실패하고, 허용 목록을 되돌리면 정책 테스트 13건이 실패함을 확인 --- .../dashboard/dashboard-admin.graphql | 10 +- .../dashboard/dashboard-seller.graphql | 12 +- .../services/dashboard-admin.service.spec.ts | 17 ++- .../services/dashboard-seller.service.spec.ts | 58 +++++++- .../services/dashboard-seller.service.ts | 11 +- .../types/dashboard-admin-output.type.ts | 9 +- .../types/dashboard-seller-output.type.ts | 1 + .../services/mypage-overview.service.spec.ts | 28 +++- .../services/mypage-review.service.spec.ts | 47 +++--- .../order/constants/order-admin.constants.ts | 8 - .../constants/order-status-traits.spec.ts | 34 +++++ .../order/constants/order-status-traits.ts | 17 +++ .../dto/inputs/admin-order-list.input.spec.ts | 32 ++++ .../dto/inputs/admin-order-list.input.ts | 22 ++- .../inputs/seller-order-list.input.spec.ts | 12 ++ .../dto/inputs/seller-order-list.input.ts | 20 +-- .../seller-update-order-status.input.spec.ts | 6 + .../seller-update-order-status.input.ts | 16 +- src/features/order/index.ts | 5 +- src/features/order/order-admin.graphql | 40 +++++ src/features/order/order-seller.graphql | 10 +- .../order-status-transition.policy.spec.ts | 128 +++++----------- .../order-status-transition.policy.ts | 50 +++---- .../repositories/order.repository.spec.ts | 89 ++++++++++- .../order/repositories/order.repository.ts | 139 +++++++++++++----- .../resolvers/order-admin-query.resolver.ts | 12 ++ .../resolvers/order-admin.resolver.spec.ts | 15 ++ .../services/order-admin.service.spec.ts | 123 +++++++++++++++- .../order/services/order-admin.service.ts | 21 ++- .../services/order-seller.service.spec.ts | 128 +++++++++++++++- .../order/services/order-seller.service.ts | 12 +- .../order/types/order-admin-output.type.ts | 6 + .../constants/store-ranking.constants.ts | 2 + .../store-stats.repository.spec.ts | 21 ++- src/test/roles-coverage.spec.ts | 2 +- 35 files changed, 898 insertions(+), 265 deletions(-) create mode 100644 src/features/order/constants/order-status-traits.spec.ts create mode 100644 src/features/order/constants/order-status-traits.ts create mode 100644 src/features/order/dto/inputs/admin-order-list.input.spec.ts diff --git a/src/features/dashboard/dashboard-admin.graphql b/src/features/dashboard/dashboard-admin.graphql index 48d7cdb8..4188f1a6 100644 --- a/src/features/dashboard/dashboard-admin.graphql +++ b/src/features/dashboard/dashboard-admin.graphql @@ -54,7 +54,7 @@ type AdminDashboardSummary { """ orderCounts: AdminOrderStatusCounts! """ - 기간 내 생성된 주문의 최종 결제 금액 합(원). 취소 주문은 제외. + 기간 내 생성된 주문의 최종 결제 금액 합(원). 취소·입금 대기 주문은 제외. Int(32비트)를 넘을 수 있어 Float로 내리지만 값은 항상 정수다. """ orderAmountSum: Float! @@ -76,6 +76,10 @@ type AdminDashboardSummary { 주문 상태별 건수. """ type AdminOrderStatusCounts { + """ + 입금 대기(PENDING_PAYMENT). + """ + pendingPayment: Int! """ 접수(SUBMITTED). """ @@ -93,6 +97,10 @@ type AdminOrderStatusCounts { """ pickedUp: Int! """ + 노쇼(NO_SHOW). + """ + noShow: Int! + """ 취소(CANCELED). """ canceled: Int! diff --git a/src/features/dashboard/dashboard-seller.graphql b/src/features/dashboard/dashboard-seller.graphql index dc49363d..303633dd 100644 --- a/src/features/dashboard/dashboard-seller.graphql +++ b/src/features/dashboard/dashboard-seller.graphql @@ -30,15 +30,15 @@ type SellerDashboard { """ asOf: DateTime! """ - 접수(SUBMITTED) 상태로 남아 있는 주문 수. 날짜와 무관하게 전체를 센다. + 접수(SUBMITTED) 상태로 남아 있는 주문 수. 날짜와 무관하게 전체를 센다. 입금 대기 주문은 세지 않는다. """ newOrderCount: Int! """ - 기준일에 픽업 예정인 주문의 건수·금액. 취소 주문은 제외. 시안의 '오늘 매출 / 정산예정'에 해당한다. + 기준일에 픽업 예정인 주문의 건수·금액. 입금 대기·취소 주문은 제외. 시안의 '오늘 매출 / 정산예정'에 해당한다. """ pickupDay: SellerDashboardOrderMetrics! """ - 기준일에 생성된 주문의 건수·금액. 취소 주문은 제외. 접수 추세 표기('+N')용. + 기준일에 접수(입금 확인)된 주문의 건수·금액. 취소 주문은 제외. 접수 추세 표기('+N')용. """ createdDay: SellerDashboardOrderMetrics! """ @@ -51,10 +51,14 @@ type SellerDashboard { """ remainingCapacity: Int """ - 기준일 픽업 주문의 제작 수량 합(취소 제외). capacity 유무와 무관하게 센다. + 기준일 픽업 주문의 제작 수량 합(취소 제외, 입금 대기 포함). capacity 유무와 무관하게 센다. """ bookedQuantity: Int! """ + bookedQuantity 중 입금 대기 주문의 수량. 입금 대기 주문은 판매자에게 보이지 않지만 제작 수량을 차지한다('입금 대기 n개 포함' 표기용). + """ + pendingPaymentQuantity: Int! + """ 노출 중(is_active)인 내 상품 수. 매장 노출 여부와 무관하다. """ activeProductCount: Int! diff --git a/src/features/dashboard/services/dashboard-admin.service.spec.ts b/src/features/dashboard/services/dashboard-admin.service.spec.ts index 785ff6e0..744958fb 100644 --- a/src/features/dashboard/services/dashboard-admin.service.spec.ts +++ b/src/features/dashboard/services/dashboard-admin.service.spec.ts @@ -136,6 +136,19 @@ describe('AdminDashboardService (real DB)', () => { total_price: 9_000, created_at: outOfRange, }); + // 입금 대기는 돈이 오가지 않아 금액에서 빠지고, 노쇼는 픽업 완료처럼 금액에 든다 + await createOrder(prisma, { + account_id: user.id, + status: 'PENDING_PAYMENT', + total_price: 20_000, + created_at: inRange, + }); + await createOrder(prisma, { + account_id: user.id, + status: 'NO_SHOW', + total_price: 40_000, + created_at: inRange, + }); // 신고 대상 리뷰는 위 매장·주문에 붙인다 — 팩토리 기본값이 계정·매장·주문을 새로 만들면 집계가 흔들린다 const item = await createOrderItem(prisma, { order_id: submitted.id, @@ -160,13 +173,15 @@ describe('AdminDashboardService (real DB)', () => { newUserCount: 1, newSellerCount: 1, orderCounts: { + pendingPayment: 1, submitted: 1, confirmed: 0, made: 0, pickedUp: 1, + noShow: 1, canceled: 1, }, - orderAmountSum: 3_000, + orderAmountSum: 43_000, activeStoreCount: 1, activeProductCount: 1, pendingReportCount: 1, diff --git a/src/features/dashboard/services/dashboard-seller.service.spec.ts b/src/features/dashboard/services/dashboard-seller.service.spec.ts index 12ed003d..6394783d 100644 --- a/src/features/dashboard/services/dashboard-seller.service.spec.ts +++ b/src/features/dashboard/services/dashboard-seller.service.spec.ts @@ -119,6 +119,7 @@ describe('SellerDashboardService (real DB)', () => { capacity: null, remainingCapacity: null, bookedQuantity: 0, + pendingPaymentQuantity: 0, activeProductCount: 0, unansweredConversationCount: 0, }); @@ -197,9 +198,9 @@ describe('SellerDashboardService (real DB)', () => { }); describe('pickupDay · createdDay', () => { - it('픽업 기준과 생성 기준을 각자의 컬럼으로 센다', async () => { + it('픽업 기준과 접수 기준을 각자의 컬럼으로 센다', async () => { const { account, store } = await setupSellerWithStore(prisma); - // 픽업은 오늘, 생성은 어제 + // 픽업은 오늘, 접수(=생성)는 어제 await storeOrder(store.id, { pickupAt: IN_DAY, createdAt: YESTERDAY, @@ -237,6 +238,59 @@ describe('SellerDashboardService (real DB)', () => { }); }); + describe('입금 대기 주문', () => { + it('판매자 지표(새 주문·픽업·접수)에서 빠지고 예약 수량에는 들어가며 따로 센다', async () => { + const { account, store } = await setupSellerWithStore(prisma); + await createStoreDailyCapacity(prisma, { + store_id: store.id, + capacity_date: TODAY_DATE_ONLY, + capacity: 10, + }); + await storeOrder(store.id, { quantity: 1, totalPrice: 100 }); + await storeOrder(store.id, { + status: 'PENDING_PAYMENT', + quantity: 2, + totalPrice: 1_000, + }); + + expect(await dashboard(account.id)).toMatchObject({ + newOrderCount: 1, + pickupDay: { orderCount: 1, salesAmount: 100 }, + createdDay: { orderCount: 1, salesAmount: 100 }, + bookedQuantity: 3, + remainingCapacity: 7, + pendingPaymentQuantity: 2, + }); + }); + + it('pendingPaymentQuantity는 기준일 픽업·내 매장·삭제 안 된 입금 대기만 센다', async () => { + const { account, store } = await setupSellerWithStore(prisma); + const other = await setupSellerWithStore(prisma); + const pending = { status: 'PENDING_PAYMENT' as const }; + await storeOrder(store.id, { ...pending, quantity: 1 }); + await storeOrder(store.id, { + ...pending, + quantity: 1, + pickupAt: DAY_START, + }); + await storeOrder(store.id, { + ...pending, + quantity: 10, + pickupAt: BEFORE_DAY_START, + }); + await storeOrder(store.id, { ...pending, quantity: 10, deletedAt: NOW }); + await storeOrder(store.id, { + ...pending, + quantity: 10, + itemDeletedAt: NOW, + }); + await storeOrder(store.id, { status: 'SUBMITTED', quantity: 10 }); + await storeOrder(other.store.id, { ...pending, quantity: 10 }); + + expect((await dashboard(account.id)).pendingPaymentQuantity).toBe(2); + }); + }); + describe('capacity · remainingCapacity · bookedQuantity', () => { it('설정이 없으면 capacity·remainingCapacity는 null이고 예약 수량은 그대로 센다', async () => { const { account, store } = await setupSellerWithStore(prisma); diff --git a/src/features/dashboard/services/dashboard-seller.service.ts b/src/features/dashboard/services/dashboard-seller.service.ts index cad710e8..796a02e8 100644 --- a/src/features/dashboard/services/dashboard-seller.service.ts +++ b/src/features/dashboard/services/dashboard-seller.service.ts @@ -23,7 +23,7 @@ import { ProductRepository } from '@/features/product'; import { SellerBaseService, StoreSellerRepository } from '@/features/store'; /** - * 요청 시 계산하며 스냅샷 테이블은 두지 않는다(관리자 대시보드와 동일). 읽기 7개를 트랜잭션으로 묶지 않는다 — + * 요청 시 계산하며 스냅샷 테이블은 두지 않는다(관리자 대시보드와 동일). 읽기 8개를 트랜잭션으로 묶지 않는다 — * 카드 간 ms 단위 불일치는 허용. capacity는 catalog 정본을, 예약 수량은 픽업 판정과 같은 포트를 읽는다. */ @Injectable() @@ -59,6 +59,7 @@ export class SellerDashboardService extends SellerBaseService { createdDay, capacityRow, bookedByStore, + pendingPaymentQuantity, activeProductCount, unansweredConversationCount, ] = await Promise.all([ @@ -73,10 +74,15 @@ export class SellerDashboardService extends SellerBaseService { storeId, from: dayStartUtc, to: dayEndUtc, - basis: 'created', + basis: 'submitted', }), this.repo.findStoreDailyCapacityByDate(storeId, dateOnlyUtc), this.booked.sumByStore([storeId], dayStartUtc, dayEndUtc), + this.orders.sumPendingPaymentQuantityByStore({ + storeId, + from: dayStartUtc, + to: dayEndUtc, + }), this.products.countProductsByStore({ storeId, isActive: true }), this.conversations.countUnansweredConversationsByStore(storeId), ]); @@ -94,6 +100,7 @@ export class SellerDashboardService extends SellerBaseService { remainingCapacity: capacity === null ? null : Math.max(capacity - bookedQuantity, 0), bookedQuantity, + pendingPaymentQuantity, activeProductCount, unansweredConversationCount, }; diff --git a/src/features/dashboard/types/dashboard-admin-output.type.ts b/src/features/dashboard/types/dashboard-admin-output.type.ts index 4d8e4fbd..c1aa55f2 100644 --- a/src/features/dashboard/types/dashboard-admin-output.type.ts +++ b/src/features/dashboard/types/dashboard-admin-output.type.ts @@ -1,3 +1,4 @@ +import type { AdminOrderStatusCounts } from '@/features/order'; import type { AccountType, AuditActionType, @@ -25,13 +26,7 @@ export interface AdminDashboardSummaryOutput { to: Date; newUserCount: number; newSellerCount: number; - orderCounts: { - submitted: number; - confirmed: number; - made: number; - pickedUp: number; - canceled: number; - }; + orderCounts: AdminOrderStatusCounts; orderAmountSum: number; activeStoreCount: number; activeProductCount: number; diff --git a/src/features/dashboard/types/dashboard-seller-output.type.ts b/src/features/dashboard/types/dashboard-seller-output.type.ts index c3a3aa73..359f0864 100644 --- a/src/features/dashboard/types/dashboard-seller-output.type.ts +++ b/src/features/dashboard/types/dashboard-seller-output.type.ts @@ -12,6 +12,7 @@ export interface SellerDashboardOutput { capacity: number | null; remainingCapacity: number | null; bookedQuantity: number; + pendingPaymentQuantity: number; activeProductCount: number; unansweredConversationCount: number; } diff --git a/src/features/mypage/services/mypage-overview.service.spec.ts b/src/features/mypage/services/mypage-overview.service.spec.ts index deedad72..d0117008 100644 --- a/src/features/mypage/services/mypage-overview.service.spec.ts +++ b/src/features/mypage/services/mypage-overview.service.spec.ts @@ -126,7 +126,7 @@ describe('UserMypageService (real DB)', () => { expect(result.counts.myReviewCount).toBe(0); }); - it('진행중 주문은 SUBMITTED/CONFIRMED/MADE 상태만, 90일 내로 필터한다', async () => { + it('진행중 주문은 진행 중 상태(입금 대기~제작 완료)만, 90일 내로 필터한다', async () => { const account = await setupUser(); const store = await createStore(prisma); const product = await createProduct(prisma, { store_id: store.id }); @@ -141,13 +141,25 @@ describe('UserMypageService (real DB)', () => { product_name_snapshot: '대표상품A', }); - // 완료(PICKED_UP) 상태 → 진행중에서 제외 - const completed = await createOrder(prisma, { + // 완료(PICKED_UP)·노쇼 → 진행중에서 제외 + for (const status of ['PICKED_UP', 'NO_SHOW'] as const) { + const completed = await createOrder(prisma, { + account_id: account.id, + status, + }); + await createOrderItem(prisma, { + order_id: completed.id, + product_id: product.id, + }); + } + // 입금 대기는 진행중이다 + const pending = await createOrder(prisma, { account_id: account.id, - status: 'PICKED_UP', + status: 'PENDING_PAYMENT', + created_at: new Date(Date.now() - 60_000), }); await createOrderItem(prisma, { - order_id: completed.id, + order_id: pending.id, product_id: product.id, }); @@ -173,9 +185,11 @@ describe('UserMypageService (real DB)', () => { const result = await service.getOverview(account.id); - expect(result.ongoingOrders).toHaveLength(1); + expect(result.ongoingOrders.map((o) => o.status)).toEqual([ + 'SUBMITTED', + 'PENDING_PAYMENT', + ]); expect(result.ongoingOrders[0].orderId).toBe(active1.id.toString()); - expect(result.ongoingOrders[0].status).toBe('SUBMITTED'); expect(result.ongoingOrders[0].representativeProductName).toBe( '대표상품A', ); diff --git a/src/features/mypage/services/mypage-review.service.spec.ts b/src/features/mypage/services/mypage-review.service.spec.ts index 6c1964aa..ca22ec41 100644 --- a/src/features/mypage/services/mypage-review.service.spec.ts +++ b/src/features/mypage/services/mypage-review.service.spec.ts @@ -406,27 +406,31 @@ describe('UserReviewService (real DB)', () => { ).rejects.toThrowDomain(404); }); - it('주문이 PICKED_UP 이전 상태면 400', async () => { - const account = await createAccount(prisma, { account_type: 'USER' }); - await createUserProfile(prisma, { account_id: account.id }); - const product = await createProduct(prisma); - const order = await createOrder(prisma, { - account_id: account.id, - status: 'SUBMITTED', - }); - const item = await createOrderItem(prisma, { - order_id: order.id, - product_id: product.id, - }); + // 노쇼는 종료 상태지만 받지 않은 케이크라 리뷰를 쓸 수 없다 + it.each(['SUBMITTED', 'NO_SHOW'] as const)( + '주문이 %s면 400(PICKED_UP만 쓸 수 있다)', + async (status) => { + const account = await createAccount(prisma, { account_type: 'USER' }); + await createUserProfile(prisma, { account_id: account.id }); + const product = await createProduct(prisma); + const order = await createOrder(prisma, { + account_id: account.id, + status, + }); + const item = await createOrderItem(prisma, { + order_id: order.id, + product_id: product.id, + }); - await expect( - service.writeReview(account.id, { - orderItemId: item.id.toString(), - rating: 5, - content: VALID_CONTENT, - }), - ).rejects.toThrowDomain(400); - }); + await expect( + service.writeReview(account.id, { + orderItemId: item.id.toString(), + rating: 5, + content: VALID_CONTENT, + }), + ).rejects.toThrowDomain(400); + }, + ); it('활성 리뷰가 이미 있으면 409', async () => { const ctx = await setupReviewableOrderItem(); @@ -733,7 +737,7 @@ describe('UserReviewService (real DB)', () => { args?: { productName?: string; pickedUpAt?: Date; - orderStatus?: 'PICKED_UP' | 'CONFIRMED'; + orderStatus?: 'PICKED_UP' | 'CONFIRMED' | 'NO_SHOW'; orderDeletedAt?: Date | null; }, ): Promise { @@ -838,6 +842,7 @@ describe('UserReviewService (real DB)', () => { it('픽업 완료가 아닌 주문·삭제된 주문·타인 주문은 제외한다', async () => { const account = await createAccount(prisma, { account_type: 'USER' }); await pickUpItem(account.id, { orderStatus: 'CONFIRMED' }); + await pickUpItem(account.id, { orderStatus: 'NO_SHOW' }); await pickUpItem(account.id, { orderDeletedAt: new Date() }); const other = await createAccount(prisma, { account_type: 'USER' }); await pickUpItem(other.id); diff --git a/src/features/order/constants/order-admin.constants.ts b/src/features/order/constants/order-admin.constants.ts index cc76fbdf..38527953 100644 --- a/src/features/order/constants/order-admin.constants.ts +++ b/src/features/order/constants/order-admin.constants.ts @@ -2,14 +2,6 @@ import { MAX_REASON_LENGTH } from '@/common/constants/reason.constants'; // ── 주문 ── -export const ORDER_STATUSES = [ - 'SUBMITTED', - 'CONFIRMED', - 'MADE', - 'PICKED_UP', - 'CANCELED', -] as const; -export type OrderStatusValue = (typeof ORDER_STATUSES)[number]; /** 관리자 취소 이력 메모 접두 — 판매자 취소와 구분한다. */ export const ADMIN_CANCEL_NOTE_PREFIX = '[관리자] '; /** 접두를 붙인 뒤에도 order_status_history.note(500)에 들어가야 한다. */ diff --git a/src/features/order/constants/order-status-traits.spec.ts b/src/features/order/constants/order-status-traits.spec.ts new file mode 100644 index 00000000..5483d5f7 --- /dev/null +++ b/src/features/order/constants/order-status-traits.spec.ts @@ -0,0 +1,34 @@ +import { + IN_PROGRESS_ORDER_STATUSES, + ORDER_STATUS_TRAITS, +} from '@/features/order/constants/order-status-traits'; +import { OrderStatus } from '@/generated/prisma/client'; + +describe('ORDER_STATUS_TRAITS', () => { + it('Prisma enum 값과 분류 키가 같은 집합이다', () => { + expect(Object.keys(ORDER_STATUS_TRAITS).sort()).toEqual( + Object.values(OrderStatus).sort(), + ); + }); + + it.each([ + ['PENDING_PAYMENT', true], + ['SUBMITTED', true], + ['CONFIRMED', true], + ['MADE', true], + ['PICKED_UP', false], + ['NO_SHOW', false], + ['CANCELED', false], + ] as const)('%s 진행 중 여부는 %s다', (status, inProgress) => { + expect(ORDER_STATUS_TRAITS[status].inProgress).toBe(inProgress); + }); + + it('진행 중 상태는 흐름 순이다', () => { + expect(IN_PROGRESS_ORDER_STATUSES).toEqual([ + 'PENDING_PAYMENT', + 'SUBMITTED', + 'CONFIRMED', + 'MADE', + ]); + }); +}); diff --git a/src/features/order/constants/order-status-traits.ts b/src/features/order/constants/order-status-traits.ts new file mode 100644 index 00000000..e5ccfb6f --- /dev/null +++ b/src/features/order/constants/order-status-traits.ts @@ -0,0 +1,17 @@ +import type { OrderStatus } from '@/generated/prisma/client'; + +/** 상태 분류 정본. 새 상태는 여기서 분류하기 전까지 tsc가 막는다(순서는 흐름 순). */ +export const ORDER_STATUS_TRAITS = { + PENDING_PAYMENT: { inProgress: true }, + SUBMITTED: { inProgress: true }, + CONFIRMED: { inProgress: true }, + MADE: { inProgress: true }, + PICKED_UP: { inProgress: false }, + NO_SHOW: { inProgress: false }, + CANCELED: { inProgress: false }, +} as const satisfies Record; + +/** 진행 중 주문: 입금 대기부터 제작 완료까지. 마이페이지 진행 주문·관리자 진행 주문 필터·요약이 쓴다. */ +export const IN_PROGRESS_ORDER_STATUSES: readonly OrderStatus[] = ( + Object.keys(ORDER_STATUS_TRAITS) as OrderStatus[] +).filter((status) => ORDER_STATUS_TRAITS[status].inProgress); diff --git a/src/features/order/dto/inputs/admin-order-list.input.spec.ts b/src/features/order/dto/inputs/admin-order-list.input.spec.ts new file mode 100644 index 00000000..1dea6bc7 --- /dev/null +++ b/src/features/order/dto/inputs/admin-order-list.input.spec.ts @@ -0,0 +1,32 @@ +import 'reflect-metadata'; + +import { plainToInstance } from 'class-transformer'; +import { validate } from 'class-validator'; + +import { AdminOrderListInput } from '@/features/order/dto/inputs/admin-order-list.input'; +import { OrderStatus } from '@/generated/prisma/client'; + +function build(plain: object): AdminOrderListInput { + return plainToInstance(AdminOrderListInput, plain); +} + +describe('AdminOrderListInput', () => { + // 손으로 적은 목록이면 새 상태(입금 대기·노쇼)가 빠진다 — enum에서 파생해야 통과한다 + it.each(Object.values(OrderStatus))('status %s 허용', async (status) => { + expect(await validate(build({ status }))).toHaveLength(0); + }); + + it('알 수 없는 status 거절', async () => { + const errors = await validate(build({ status: 'UNKNOWN' })); + expect(errors[0].property).toBe('status'); + }); + + it.each([true, false, null, undefined])('inProgress %p 허용', async (v) => { + expect(await validate(build({ inProgress: v }))).toHaveLength(0); + }); + + it('inProgress가 불리언이 아니면 거절', async () => { + const errors = await validate(build({ inProgress: 'true' })); + expect(errors[0].property).toBe('inProgress'); + }); +}); diff --git a/src/features/order/dto/inputs/admin-order-list.input.ts b/src/features/order/dto/inputs/admin-order-list.input.ts index d0bef7cc..b6e89701 100644 --- a/src/features/order/dto/inputs/admin-order-list.input.ts +++ b/src/features/order/dto/inputs/admin-order-list.input.ts @@ -1,11 +1,15 @@ -import { IsDate, IsIn, IsOptional, IsString, MaxLength } from 'class-validator'; +import { + IsBoolean, + IsDate, + IsEnum, + IsOptional, + IsString, + MaxLength, +} from 'class-validator'; import { MAX_KEYWORD_LENGTH } from '@/common/constants/list-search.constants'; import { CursorInput } from '@/common/dto/inputs/cursor.input'; -import { - ORDER_STATUSES, - type OrderStatusValue, -} from '@/features/order/constants/order-admin.constants'; +import { OrderStatus } from '@/generated/prisma/client'; export class AdminOrderListInput extends CursorInput { @IsOptional() @@ -14,8 +18,12 @@ export class AdminOrderListInput extends CursorInput { keyword?: string; @IsOptional() - @IsIn(ORDER_STATUSES) - status?: OrderStatusValue; + @IsEnum(OrderStatus) + status?: OrderStatus; + + @IsOptional() + @IsBoolean() + inProgress?: boolean; @IsOptional() @IsString() diff --git a/src/features/order/dto/inputs/seller-order-list.input.spec.ts b/src/features/order/dto/inputs/seller-order-list.input.spec.ts index d5a2f404..b0f15102 100644 --- a/src/features/order/dto/inputs/seller-order-list.input.spec.ts +++ b/src/features/order/dto/inputs/seller-order-list.input.spec.ts @@ -4,6 +4,7 @@ import { plainToInstance } from 'class-transformer'; import { validate } from 'class-validator'; import { SellerOrderListInput } from '@/features/order/dto/inputs/seller-order-list.input'; +import { OrderStatus } from '@/generated/prisma/client'; function build(plain: object): SellerOrderListInput { return plainToInstance(SellerOrderListInput, plain); @@ -25,6 +26,17 @@ describe('SellerOrderListInput', () => { expect(await validate(dto)).toHaveLength(0); }); + // 손으로 적은 목록이면 새 상태(입금 대기·노쇼)가 빠진다 — enum에서 파생해야 통과한다 + it.each(Object.values(OrderStatus))('status %s 허용', async (status) => { + expect(await validate(build({ status }))).toHaveLength(0); + }); + + it('buyerAccountId는 문자열만 받는다', async () => { + expect(await validate(build({ buyerAccountId: '7' }))).toHaveLength(0); + const errors = await validate(build({ buyerAccountId: 7 })); + expect(errors[0].property).toBe('buyerAccountId'); + }); + it('알 수 없는 status 거절', async () => { const dto = build({ status: 'UNKNOWN' }); const errors = await validate(dto); diff --git a/src/features/order/dto/inputs/seller-order-list.input.ts b/src/features/order/dto/inputs/seller-order-list.input.ts index 84c0c959..b838a870 100644 --- a/src/features/order/dto/inputs/seller-order-list.input.ts +++ b/src/features/order/dto/inputs/seller-order-list.input.ts @@ -1,20 +1,16 @@ -import { IsDate, IsIn, IsOptional, IsString } from 'class-validator'; +import { IsDate, IsEnum, IsOptional, IsString } from 'class-validator'; import { CursorInput } from '@/common/dto/inputs/cursor.input'; - -const ORDER_STATUSES = [ - 'SUBMITTED', - 'CONFIRMED', - 'MADE', - 'PICKED_UP', - 'CANCELED', -] as const; -type SellerOrderStatusInput = (typeof ORDER_STATUSES)[number]; +import { OrderStatus } from '@/generated/prisma/client'; export class SellerOrderListInput extends CursorInput { @IsOptional() - @IsIn(ORDER_STATUSES) - status?: SellerOrderStatusInput; + @IsEnum(OrderStatus) + status?: OrderStatus; + + @IsOptional() + @IsString() + buyerAccountId?: string; @IsOptional() @IsDate() diff --git a/src/features/order/dto/inputs/seller-update-order-status.input.spec.ts b/src/features/order/dto/inputs/seller-update-order-status.input.spec.ts index b4ac5011..51c93aaf 100644 --- a/src/features/order/dto/inputs/seller-update-order-status.input.spec.ts +++ b/src/features/order/dto/inputs/seller-update-order-status.input.spec.ts @@ -4,6 +4,7 @@ import { plainToInstance } from 'class-transformer'; import { validate } from 'class-validator'; import { SellerUpdateOrderStatusInput } from '@/features/order/dto/inputs/seller-update-order-status.input'; +import { OrderStatus } from '@/generated/prisma/client'; function build(plain: object): SellerUpdateOrderStatusInput { return plainToInstance(SellerUpdateOrderStatusInput, plain); @@ -24,6 +25,11 @@ describe('SellerUpdateOrderStatusInput', () => { expect(await validate(dto)).toHaveLength(0); }); + // 형식은 enum 전부 통과시키고 전이 가능 여부는 정책이 거절한다(NO_SHOW 포함) + it.each(Object.values(OrderStatus))('toStatus %s 허용', async (toStatus) => { + expect(await validate(build({ orderId: '1', toStatus }))).toHaveLength(0); + }); + it('알 수 없는 toStatus 거절', async () => { const dto = build({ orderId: '1', toStatus: 'UNKNOWN' }); const errors = await validate(dto); diff --git a/src/features/order/dto/inputs/seller-update-order-status.input.ts b/src/features/order/dto/inputs/seller-update-order-status.input.ts index 08201936..a2d92270 100644 --- a/src/features/order/dto/inputs/seller-update-order-status.input.ts +++ b/src/features/order/dto/inputs/seller-update-order-status.input.ts @@ -1,20 +1,14 @@ -import { IsIn, IsOptional, IsString } from 'class-validator'; +import { IsEnum, IsOptional, IsString } from 'class-validator'; -const ORDER_STATUSES = [ - 'SUBMITTED', - 'CONFIRMED', - 'MADE', - 'PICKED_UP', - 'CANCELED', -] as const; -type SellerOrderStatusInput = (typeof ORDER_STATUSES)[number]; +import { OrderStatus } from '@/generated/prisma/client'; export class SellerUpdateOrderStatusInput { @IsString() orderId!: string; - @IsIn(ORDER_STATUSES) - toStatus!: SellerOrderStatusInput; + // 전이 가능 여부는 정책(assertSellerTransition)이 판정한다 + @IsEnum(OrderStatus) + toStatus!: OrderStatus; @IsOptional() @IsString() diff --git a/src/features/order/index.ts b/src/features/order/index.ts index 38228e43..b14b47fd 100644 --- a/src/features/order/index.ts +++ b/src/features/order/index.ts @@ -1,7 +1,10 @@ // cross-feature 공개 API. 단일 구현 repo라 토큰/인터페이스 없이 구체 클래스로 주입(의도적). export { OrderModule } from '@/features/order/order.module'; // 주문 집계(dashboard feature)와 주문 읽기(user·notification). -export { OrderRepository } from '@/features/order/repositories/order.repository'; +export { + OrderRepository, + type AdminOrderStatusCounts, +} from '@/features/order/repositories/order.repository'; // 주문 상태 전이 이벤트 계약(outbox). 소비자(notification)는 payload 스냅샷만 읽는다. export { ORDER_STATUS_CHANGED, diff --git a/src/features/order/order-admin.graphql b/src/features/order/order-admin.graphql index e2e0cbe5..0c22488d 100644 --- a/src/features/order/order-admin.graphql +++ b/src/features/order/order-admin.graphql @@ -7,6 +7,13 @@ extend type Query { 주문 상세를 전체 품목·구매자 요약·상태 이력과 함께 조회한다. 없으면 NOT_FOUND. 관리자 로그인 필수. ADMIN 계정이 아니면 FORBIDDEN. """ adminOrder(orderId: ID!): AdminOrderDetail! + """ + 매장의 진행 중 주문(입금 대기·접수·확정·제작 완료) 건수를 상태별로 센다. 판매자 정지·매장 숨김 전 경고용이며 + 없는 매장이면 0건이다. 관리자 로그인 필수. ADMIN 계정이 아니면 FORBIDDEN. + """ + adminStoreInProgressOrderSummary( + storeId: ID! + ): AdminStoreInProgressOrderSummary! } extend type Mutation { @@ -190,6 +197,35 @@ type AdminOrderDetail { statusHistories: [OrderStatusHistory!]! } +""" +매장의 진행 중 주문 요약. +""" +type AdminStoreInProgressOrderSummary { + storeId: ID! + """ + 진행 중 주문 전체 건수. + """ + totalCount: Int! + """ + 상태별 건수. 0건인 상태는 빠지고 흐름 순(입금 대기 → 제작 완료)으로 온다. + """ + byStatus: [AdminStoreInProgressStatusCount!]! +} + +""" +상태 1개의 주문 건수. +""" +type AdminStoreInProgressStatusCount { + """ + 주문 상태. + """ + status: OrderStatusType! + """ + 건수. + """ + count: Int! +} + """ 주문 목록 조회 조건. 모든 필터는 AND로 결합된다. """ @@ -211,6 +247,10 @@ input AdminOrderListInput { """ status: OrderStatusType """ + true면 진행 중 주문(입금 대기·접수·확정·제작 완료)만. 기본 false, null도 false(전체)로 본다. status와 함께 오면 AND다. + """ + inProgress: Boolean = false + """ 매장 ID 필터(품목 기준). 미지정 시 전체. """ storeId: ID diff --git a/src/features/order/order-seller.graphql b/src/features/order/order-seller.graphql index 9d257c32..56a55828 100644 --- a/src/features/order/order-seller.graphql +++ b/src/features/order/order-seller.graphql @@ -1,10 +1,10 @@ extend type Query { """ - 내 매장 주문 목록을 조회한다. 판매자 로그인 필수. SELLER 계정이 아니면 FORBIDDEN, 매장을 보유하지 않으면 NOT_FOUND. + 내 매장 주문 목록을 조회한다. 입금이 확인된(접수된) 주문만 보인다. 판매자 로그인 필수. SELLER 계정이 아니면 FORBIDDEN, 매장을 보유하지 않으면 NOT_FOUND. """ sellerOrderList(input: SellerOrderListInput): SellerOrderConnection! """ - 내 매장 주문 상세를 조회한다. 판매자 로그인 필수. SELLER 계정이 아니면 FORBIDDEN, 매장을 보유하지 않으면 NOT_FOUND. + 내 매장 주문 상세를 조회한다. 입금 확인 전 주문은 없는 주문과 같이 NOT_FOUND다. 판매자 로그인 필수. SELLER 계정이 아니면 FORBIDDEN, 매장을 보유하지 않으면 NOT_FOUND. """ sellerOrder(orderId: ID!): SellerOrderDetail! } @@ -100,6 +100,10 @@ input SellerOrderListInput { """ status: OrderStatusType """ + 구매자 계정 ID 필터. 채팅 상대의 주문만 볼 때 쓴다. 미지정 시 전체. + """ + buyerAccountId: ID + """ 주문 생성 시각 하한(이상). """ fromCreatedAt: DateTime @@ -189,7 +193,7 @@ type SellerOrderDetail { """ items: [OrderItemDetail!]! """ - 상태 변경 이력. 최신순. + 상태 변경 이력. 최신순. 입금 대기 이력은 빠지고, 접수 이력은 fromStatus가 null(최초)로 온다. """ statusHistories: [OrderStatusHistory!]! } diff --git a/src/features/order/policies/order-status-transition.policy.spec.ts b/src/features/order/policies/order-status-transition.policy.spec.ts index 5cd3652b..1f538b31 100644 --- a/src/features/order/policies/order-status-transition.policy.spec.ts +++ b/src/features/order/policies/order-status-transition.policy.spec.ts @@ -1,112 +1,62 @@ import { OrderStatusTransitionPolicy } from '@/features/order/policies/order-status-transition.policy'; import { OrderStatus } from '@/generated/prisma/client'; +const STATUSES = Object.values(OrderStatus); + +/** 판매자 전이 허용 목록. 이 밖은 전부 거절이다(기본 거절). */ +const ALLOWED = new Set([ + 'SUBMITTED>CONFIRMED', + 'CONFIRMED>MADE', + 'MADE>PICKED_UP', + 'SUBMITTED>CANCELED', + 'CONFIRMED>CANCELED', + 'MADE>CANCELED', +]); + +function expectedCode(from: OrderStatus, to: OrderStatus): string | null { + if (from === to) return 'ORDER_STATUS_UNCHANGED'; + if (ALLOWED.has(`${from}>${to}`)) return null; + return to === 'CANCELED' + ? 'ORDER_NOT_CANCELLABLE' + : 'INVALID_ORDER_STATUS_TRANSITION'; +} + describe('OrderStatusTransitionPolicy', () => { const policy = new OrderStatusTransitionPolicy(); describe('parse', () => { - it.each([ - ['SUBMITTED', OrderStatus.SUBMITTED], - ['CONFIRMED', OrderStatus.CONFIRMED], - ['MADE', OrderStatus.MADE], - ['PICKED_UP', OrderStatus.PICKED_UP], - ['CANCELED', OrderStatus.CANCELED], - ])('"%s" → enum %s', (raw, expected) => { - expect(policy.parse(raw)).toBe(expected); + it('Prisma enum 값 전부를 받는다(입금 대기·노쇼 포함)', () => { + expect(STATUSES).toEqual( + expect.arrayContaining(['PENDING_PAYMENT', 'NO_SHOW']), + ); + for (const status of STATUSES) expect(policy.parse(status)).toBe(status); }); - it('알 수 없는 문자열이면 400', () => { - expect(() => policy.parse('INVALID')).toThrowDomain(400); + it.each(['INVALID', '', 'submitted'])('%p면 400', (raw) => { + expect(() => policy.parse(raw)).toThrowDomain('INVALID_ORDER_STATUS'); }); }); describe('assertSellerTransition', () => { - it('from === to면 400', () => { - expect(() => - policy.assertSellerTransition( - OrderStatus.SUBMITTED, - OrderStatus.SUBMITTED, - ), - ).toThrowDomain(400); - }); - - it('CONFIRMED는 SUBMITTED에서만 가능', () => { - expect(() => - policy.assertSellerTransition( - OrderStatus.SUBMITTED, - OrderStatus.CONFIRMED, - ), - ).not.toThrow(); - expect(() => - policy.assertSellerTransition(OrderStatus.MADE, OrderStatus.CONFIRMED), - ).toThrowDomain(400); - }); + const cases = STATUSES.flatMap((from) => + STATUSES.map((to) => [from, to, expectedCode(from, to)] as const), + ); - it('MADE는 CONFIRMED에서만 가능', () => { - expect(() => - policy.assertSellerTransition(OrderStatus.CONFIRMED, OrderStatus.MADE), - ).not.toThrow(); - expect(() => - policy.assertSellerTransition(OrderStatus.SUBMITTED, OrderStatus.MADE), - ).toThrowDomain(400); + it('표는 상태 전 조합(7×7)을 덮고 허용 전이는 6개다', () => { + expect(cases).toHaveLength(49); + expect(cases.filter(([, , code]) => code === null)).toHaveLength(6); }); - it('PICKED_UP은 MADE에서만 가능', () => { - expect(() => - policy.assertSellerTransition(OrderStatus.MADE, OrderStatus.PICKED_UP), - ).not.toThrow(); - expect(() => - policy.assertSellerTransition( - OrderStatus.CONFIRMED, - OrderStatus.PICKED_UP, - ), - ).toThrowDomain(400); - }); - - it('CANCELED는 SUBMITTED/CONFIRMED/MADE에서 가능, PICKED_UP에서는 불가', () => { - expect(() => - policy.assertSellerTransition( - OrderStatus.SUBMITTED, - OrderStatus.CANCELED, - ), - ).not.toThrow(); - expect(() => - policy.assertSellerTransition( - OrderStatus.CONFIRMED, - OrderStatus.CANCELED, - ), - ).not.toThrow(); - expect(() => - policy.assertSellerTransition(OrderStatus.MADE, OrderStatus.CANCELED), - ).not.toThrow(); - expect(() => - policy.assertSellerTransition( - OrderStatus.PICKED_UP, - OrderStatus.CANCELED, - ), - ).toThrowDomain(400); - }); - - // SUBMITTED는 주문 생성 시점의 초기 상태라 어떤 상태에서도 되돌아갈 수 없다 — 가드가 빠지면 역전이가 조용히 통과되므로 모든 from을 전수 검증한다. - it.each([ - OrderStatus.CONFIRMED, - OrderStatus.MADE, - OrderStatus.PICKED_UP, - OrderStatus.CANCELED, - ])('SUBMITTED로 되돌리는 역전이는 거부 (from=%s)', (from) => { - expect(() => - policy.assertSellerTransition(from, OrderStatus.SUBMITTED), - ).toThrowDomain(400); + it.each(cases)('%s → %s: %s', (from, to, code) => { + const run = () => policy.assertSellerTransition(from, to); + if (code === null) expect(run).not.toThrow(); + else expect(run).toThrowDomain(code); }); }); describe('requiresCancellationNote', () => { - it('CANCELED일 때만 true', () => { - expect(policy.requiresCancellationNote(OrderStatus.CANCELED)).toBe(true); - expect(policy.requiresCancellationNote(OrderStatus.CONFIRMED)).toBe( - false, - ); - expect(policy.requiresCancellationNote(OrderStatus.MADE)).toBe(false); + it.each(STATUSES)('%s', (to) => { + expect(policy.requiresCancellationNote(to)).toBe(to === 'CANCELED'); }); }); }); diff --git a/src/features/order/policies/order-status-transition.policy.ts b/src/features/order/policies/order-status-transition.policy.ts index 0a0fcb8b..a81958d1 100644 --- a/src/features/order/policies/order-status-transition.policy.ts +++ b/src/features/order/policies/order-status-transition.policy.ts @@ -3,14 +3,21 @@ import { Injectable } from '@nestjs/common'; import { DomainException } from '@/common/errors/error-catalog'; import { OrderStatus } from '@/generated/prisma/client'; +const ORDER_STATUS_VALUES: readonly string[] = Object.values(OrderStatus); + +/** 판매자가 만들 수 있는 전이(to → 허용 from). 표에 없는 to는 거절한다 — 새 상태가 조용히 열리지 않게. */ +const SELLER_TRANSITIONS: Partial> = + { + CONFIRMED: [OrderStatus.SUBMITTED], + MADE: [OrderStatus.CONFIRMED], + PICKED_UP: [OrderStatus.MADE], + CANCELED: [OrderStatus.SUBMITTED, OrderStatus.CONFIRMED, OrderStatus.MADE], + }; + @Injectable() export class OrderStatusTransitionPolicy { parse(raw: string): OrderStatus { - if (raw === 'SUBMITTED') return OrderStatus.SUBMITTED; - if (raw === 'CONFIRMED') return OrderStatus.CONFIRMED; - if (raw === 'MADE') return OrderStatus.MADE; - if (raw === 'PICKED_UP') return OrderStatus.PICKED_UP; - if (raw === 'CANCELED') return OrderStatus.CANCELED; + if (ORDER_STATUS_VALUES.includes(raw)) return raw as OrderStatus; throw new DomainException('INVALID_ORDER_STATUS'); } @@ -18,33 +25,12 @@ export class OrderStatusTransitionPolicy { if (from === to) { throw new DomainException('ORDER_STATUS_UNCHANGED'); } - - // SUBMITTED는 주문 생성 시점의 초기 상태이므로 어떤 상태에서도 되돌아갈 수 없다. - if (to === OrderStatus.SUBMITTED) { - throw new DomainException('INVALID_ORDER_STATUS_TRANSITION'); - } - - if (to === OrderStatus.CONFIRMED && from !== OrderStatus.SUBMITTED) { - throw new DomainException('INVALID_ORDER_STATUS_TRANSITION'); - } - - if (to === OrderStatus.MADE && from !== OrderStatus.CONFIRMED) { - throw new DomainException('INVALID_ORDER_STATUS_TRANSITION'); - } - - if (to === OrderStatus.PICKED_UP && from !== OrderStatus.MADE) { - throw new DomainException('INVALID_ORDER_STATUS_TRANSITION'); - } - - if (to === OrderStatus.CANCELED) { - const cancellable = - from === OrderStatus.SUBMITTED || - from === OrderStatus.CONFIRMED || - from === OrderStatus.MADE; - if (!cancellable) { - throw new DomainException('ORDER_NOT_CANCELLABLE'); - } - } + if (SELLER_TRANSITIONS[to]?.includes(from)) return; + throw new DomainException( + to === OrderStatus.CANCELED + ? 'ORDER_NOT_CANCELLABLE' + : 'INVALID_ORDER_STATUS_TRANSITION', + ); } requiresCancellationNote(to: OrderStatus): boolean { diff --git a/src/features/order/repositories/order.repository.spec.ts b/src/features/order/repositories/order.repository.spec.ts index 9b2a0374..ae464686 100644 --- a/src/features/order/repositories/order.repository.spec.ts +++ b/src/features/order/repositories/order.repository.spec.ts @@ -108,9 +108,14 @@ describe('OrderRepository (real DB)', () => { }); describe('findOngoingOrdersByAccount', () => { - it('SUBMITTED/CONFIRMED/MADE 상태 주문만 since 이후로 반환하고 PICKED_UP/CANCELED 제외', async () => { + it('진행 중(입금 대기·접수·확정·제작 완료) 주문만 since 이후로 반환하고 PICKED_UP·NO_SHOW·CANCELED 제외', async () => { const buyer = await setupBuyer(); const since = new Date('2026-01-01'); + const pending = await createOrder(prisma, { + account_id: buyer.id, + status: 'PENDING_PAYMENT', + }); + await createOrder(prisma, { account_id: buyer.id, status: 'NO_SHOW' }); const o1 = await createOrder(prisma, { account_id: buyer.id, @@ -134,7 +139,9 @@ describe('OrderRepository (real DB)', () => { since, limit: 10, }); - expect(rows.map((r) => r.id).sort()).toEqual([o1.id, o4.id].sort()); + expect(rows.map((r) => r.id).sort()).toEqual( + [pending.id, o1.id, o4.id].sort(), + ); }); it('since 이전에 생성된 주문은 제외한다', async () => { @@ -393,6 +400,7 @@ describe('OrderRepository (real DB)', () => { discount_price: 0, total_price: 0, created_at: new Date('2025-01-01'), + submitted_at: new Date('2025-01-01'), }, }); await createOrderItem(prisma, { @@ -425,6 +433,7 @@ describe('OrderRepository (real DB)', () => { discount_price: 0, total_price: 0, created_at: new Date('2025-06-01'), + submitted_at: new Date('2025-06-01'), }, }); await createOrderItem(prisma, { @@ -444,6 +453,7 @@ describe('OrderRepository (real DB)', () => { discount_price: 0, total_price: 0, created_at: new Date('2026-05-01'), + submitted_at: new Date('2026-05-01'), }, }); await createOrderItem(prisma, { @@ -508,21 +518,21 @@ describe('OrderRepository (real DB)', () => { it('basis가 기준 컬럼을 고르고 범위는 [from, to)다', async () => { const store = await createStore(prisma); - // 픽업은 범위 안, 생성은 범위 밖 + // 픽업은 범위 안, 접수는 범위 밖 await storeOrder(store.id, { pickup_at: inside, - created_at: before, + submitted_at: before, total_price: 1_000, }); // 경계: from은 포함, to는 제외 await storeOrder(store.id, { pickup_at: from, - created_at: to, + submitted_at: to, total_price: 10, }); await storeOrder(store.id, { pickup_at: to, - created_at: from, + submitted_at: from, total_price: 100, }); @@ -531,10 +541,48 @@ describe('OrderRepository (real DB)', () => { await repo.aggregateStoreOrdersInRange({ ...base, basis: 'pickup' }), ).toEqual({ orderCount: 2, salesAmount: 1_010 }); expect( - await repo.aggregateStoreOrdersInRange({ ...base, basis: 'created' }), + await repo.aggregateStoreOrdersInRange({ ...base, basis: 'submitted' }), ).toEqual({ orderCount: 1, salesAmount: 100 }); }); + it('접수 기준은 생성 시각이 아니라 입금 확인(접수) 시각이다', async () => { + const store = await createStore(prisma); + await storeOrder(store.id, { + created_at: before, + submitted_at: inside, + total_price: 7, + }); + expect( + await repo.aggregateStoreOrdersInRange({ + storeId: store.id, + from, + to, + basis: 'submitted', + }), + ).toEqual({ orderCount: 1, salesAmount: 7 }); + }); + + it.each(['pickup', 'submitted'] as const)( + '입금 대기(판매자 비노출) 주문은 %s 기준에서 빠진다', + async (basis) => { + const store = await createStore(prisma); + await storeOrder(store.id, { + status: 'PENDING_PAYMENT', + pickup_at: inside, + created_at: inside, + total_price: 5, + }); + expect( + await repo.aggregateStoreOrdersInRange({ + storeId: store.id, + from, + to, + basis, + }), + ).toEqual({ orderCount: 0, salesAmount: 0 }); + }, + ); + it('CANCELED·soft-delete 주문·품목이 soft-delete된 주문·다른 매장은 제외한다', async () => { const store = await createStore(prisma); const other = await createStore(prisma); @@ -573,7 +621,7 @@ describe('OrderRepository (real DB)', () => { storeId: store.id, from, to, - basis: 'created', + basis: 'submitted', }), ).toEqual({ orderCount: 0, salesAmount: 0 }); }); @@ -660,6 +708,31 @@ describe('OrderRepository (real DB)', () => { ).toBe(0); }); + it('입금 확인 전(submitted_at 없음) 주문은 잠금 조회에서 빠져 null이다(전이 판정 전)', async () => { + const store = await createStore(prisma); + const order = await createOrder(prisma, { status: 'PENDING_PAYMENT' }); + await createOrderItem(prisma, { order_id: order.id, store_id: store.id }); + const seller = await createAccount(prisma, { account_type: 'SELLER' }); + const assertTransition = jest.fn(); + + const result = await repo.updateOrderStatusBySeller({ + orderId: order.id, + storeId: store.id, + actorAccountId: seller.id, + toStatus: OrderStatus.CANCELED, + assertTransition, + note: null, + now: new Date(), + }); + + expect(result).toBeNull(); + expect(assertTransition).not.toHaveBeenCalled(); + const row = await prisma.order.findUniqueOrThrow({ + where: { id: order.id }, + }); + expect(row.status).toBe('PENDING_PAYMENT'); + }); + it('다른 store의 주문이면 null 반환 (update 미수행)', async () => { const storeA = await createStore(prisma); const storeB = await createStore(prisma); diff --git a/src/features/order/repositories/order.repository.ts b/src/features/order/repositories/order.repository.ts index c56c6a71..f0076f9c 100644 --- a/src/features/order/repositories/order.repository.ts +++ b/src/features/order/repositories/order.repository.ts @@ -4,6 +4,7 @@ import { AUDIT_LOG_REPOSITORY, type IAuditLogRepository, } from '@/features/audit-log'; +import { IN_PROGRESS_ORDER_STATUSES } from '@/features/order/constants/order-status-traits'; import { orderStatusChangedEvent } from '@/features/order/events/order-status-changed.event'; import { orderSubmittedEvent } from '@/features/order/events/order-submitted.event'; import { OutboxPublisher } from '@/features/outbox'; @@ -27,6 +28,11 @@ export type SellerOrderRow = Prisma.OrderGetPayload<{ include: ReturnType; }>; +/** 판매자에게 보이는 주문 — 입금 확인(접수) 때 submitted_at을 채우므로 입금 대기와 입금 전 취소가 함께 빠진다. */ +const sellerVisibleWhere = { + submitted_at: { not: null }, +} satisfies Prisma.OrderWhereInput; + const adminOrderInclude = { items: { where: activeWhere, @@ -83,6 +89,26 @@ const adminOrderDetailInclude = { }, } satisfies Prisma.OrderInclude; +export interface AdminOrderStatusCounts { + pendingPayment: number; + submitted: number; + confirmed: number; + made: number; + pickedUp: number; + noShow: number; + canceled: number; +} + +const ADMIN_STATUS_COUNT_KEYS = { + PENDING_PAYMENT: 'pendingPayment', + SUBMITTED: 'submitted', + CONFIRMED: 'confirmed', + MADE: 'made', + PICKED_UP: 'pickedUp', + NO_SHOW: 'noShow', + CANCELED: 'canceled', +} as const satisfies Record; + export interface MyOrderRow { id: bigint; order_number: string; @@ -412,9 +438,7 @@ export class OrderRepository { return this.prisma.order.findMany({ where: { account_id: args.accountId, - status: { - in: [OrderStatus.SUBMITTED, OrderStatus.CONFIRMED, OrderStatus.MADE], - }, + status: { in: [...IN_PROGRESS_ORDER_STATUSES] }, created_at: { gte: args.since }, }, orderBy: { created_at: 'desc' }, @@ -617,6 +641,7 @@ export class OrderRepository { private storeOrderScopeWhere(args: { storeId: bigint; status?: OrderStatus; + buyerAccountId?: bigint; fromCreatedAt?: Date; toCreatedAt?: Date; fromPickupAt?: Date; @@ -624,7 +649,11 @@ export class OrderRepository { search?: string; }): Prisma.OrderWhereInput { return { + ...sellerVisibleWhere, ...(args.status ? { status: args.status } : {}), + ...(args.buyerAccountId !== undefined + ? { account_id: args.buyerAccountId } + : {}), ...(args.fromCreatedAt || args.toCreatedAt ? { created_at: { @@ -662,6 +691,7 @@ export class OrderRepository { async countOrdersByStore(args: { storeId: bigint; status?: OrderStatus; + buyerAccountId?: bigint; fromCreatedAt?: Date; toCreatedAt?: Date; fromPickupAt?: Date; @@ -673,17 +703,18 @@ export class OrderRepository { }); } - /** [from, to) 픽업 또는 생성 기준 건수·금액 합(CANCELED 제외). 주문 1건 = 매장 1곳이라 total_price 합이 매장 매출이다. */ + /** [from, to) 픽업 또는 접수 기준 건수·금액 합(판매자 노출·CANCELED 제외). 주문 1건 = 매장 1곳이라 total_price 합이 매장 매출이다. */ async aggregateStoreOrdersInRange(args: { storeId: bigint; from: Date; to: Date; - basis: 'pickup' | 'created'; + basis: 'pickup' | 'submitted'; }): Promise<{ orderCount: number; salesAmount: number }> { const result = await this.prisma.order.aggregate({ where: { + ...sellerVisibleWhere, status: { not: 'CANCELED' }, - [args.basis === 'pickup' ? 'pickup_at' : 'created_at']: { + [args.basis === 'pickup' ? 'pickup_at' : 'submitted_at']: { gte: args.from, lt: args.to, }, @@ -698,11 +729,32 @@ export class OrderRepository { }; } + /** [from, to) 픽업 입금 대기 주문의 제작 수량 합. 판매자에게 주문은 숨기고 점유한 수량만 알린다. */ + async sumPendingPaymentQuantityByStore(args: { + storeId: bigint; + from: Date; + to: Date; + }): Promise { + const result = await this.prisma.orderItem.aggregate({ + where: { + store_id: args.storeId, + order: { + status: OrderStatus.PENDING_PAYMENT, + pickup_at: { gte: args.from, lt: args.to }, + ...activeWhere, + }, + }, + _sum: { quantity: true }, + }); + return result._sum.quantity ?? 0; + } + async listOrdersByStore(args: { storeId: bigint; limit: number; cursor?: bigint; status?: OrderStatus; + buyerAccountId?: bigint; fromCreatedAt?: Date; toCreatedAt?: Date; fromPickupAt?: Date; @@ -724,6 +776,7 @@ export class OrderRepository { return this.prisma.order.findFirst({ where: { id: args.orderId, + ...sellerVisibleWhere, items: { some: { store_id: args.storeId, @@ -733,8 +786,12 @@ export class OrderRepository { }, // 유저측 상세(findOrderDetailByUser)와 동일하게 soft-delete 자식을 가드한다 include: { + // 입금 대기 이력은 판매자에게 보이지 않는다 status_histories: { - where: activeWhere, + where: { + to_status: { not: OrderStatus.PENDING_PAYMENT }, + ...activeWhere, + }, orderBy: { changed_at: 'desc', }, @@ -787,6 +844,7 @@ export class OrderRepository { const locked = await tx.$queryRaw<{ id: bigint; status: OrderStatus }[]>` SELECT o.id, o.status FROM \`order\` o WHERE o.id = ${args.orderId} AND o.deleted_at IS NULL + AND o.submitted_at IS NOT NULL AND EXISTS ( SELECT 1 FROM order_item i WHERE i.order_id = o.id AND i.store_id = ${args.storeId} @@ -889,13 +947,20 @@ export class OrderRepository { private adminOrderScopeWhere(args: { keyword?: string; status?: OrderStatus; + inProgress?: boolean; storeId?: bigint; accountId?: bigint; fromCreatedAt?: Date; toCreatedAt?: Date; }): Prisma.OrderWhereInput { return { - ...(args.status ? { status: args.status } : {}), + // status와 함께 오면 AND — 둘이 겹치지 않으면 빈 결과다 + AND: [ + args.status ? { status: args.status } : {}, + args.inProgress + ? { status: { in: [...IN_PROGRESS_ORDER_STATUSES] } } + : {}, + ], ...(args.accountId !== undefined ? { account_id: args.accountId } : {}), ...(args.storeId !== undefined ? { items: { some: { store_id: args.storeId, ...activeWhere } } } @@ -923,6 +988,7 @@ export class OrderRepository { async listOrdersForAdmin(args: { keyword?: string; status?: OrderStatus; + inProgress?: boolean; storeId?: bigint; accountId?: bigint; fromCreatedAt?: Date; @@ -944,6 +1010,7 @@ export class OrderRepository { async countOrdersForAdmin(args: { keyword?: string; status?: OrderStatus; + inProgress?: boolean; storeId?: bigint; accountId?: bigint; fromCreatedAt?: Date; @@ -1045,55 +1112,53 @@ export class OrderRepository { }); } + /** 매장의 진행 중 주문 상태별 건수(관리자 정지·숨김 경고용). 0건 상태는 빼고 흐름 순으로 돌려준다. */ + async countInProgressOrdersByStore( + storeId: bigint, + ): Promise<{ status: OrderStatus; count: number }[]> { + const grouped = await this.prisma.order.groupBy({ + by: ['status'], + where: { + status: { in: [...IN_PROGRESS_ORDER_STATUSES] }, + items: { some: { store_id: storeId, ...activeWhere } }, + }, + _count: { _all: true }, + }); + const counts = new Map(grouped.map((g) => [g.status, g._count._all])); + return IN_PROGRESS_ORDER_STATUSES.flatMap((status) => { + const count = counts.get(status); + return count ? [{ status, count }] : []; + }); + } + // ── 대시보드 집계(dashboard feature가 배럴로 소비) ── + /** 금액 합은 돈이 오가지 않은 취소·입금 대기를 뺀다. */ async aggregateOrdersBetween( from: Date, to: Date, - ): Promise<{ - counts: { - submitted: number; - confirmed: number; - made: number; - pickedUp: number; - canceled: number; - }; - amountSum: number; - }> { + ): Promise<{ counts: AdminOrderStatusCounts; amountSum: number }> { const grouped = await this.prisma.order.groupBy({ by: ['status'], where: { created_at: { gte: from, lte: to } }, _count: { _all: true }, _sum: { total_price: true }, }); - const counts = { + const counts: AdminOrderStatusCounts = { + pendingPayment: 0, submitted: 0, confirmed: 0, made: 0, pickedUp: 0, + noShow: 0, canceled: 0, }; let amountSum = 0; for (const g of grouped) { - const n = g._count._all; - switch (g.status) { - case 'SUBMITTED': - counts.submitted = n; - break; - case 'CONFIRMED': - counts.confirmed = n; - break; - case 'MADE': - counts.made = n; - break; - case 'PICKED_UP': - counts.pickedUp = n; - break; - case 'CANCELED': - counts.canceled = n; - break; + counts[ADMIN_STATUS_COUNT_KEYS[g.status]] = g._count._all; + if (g.status !== 'CANCELED' && g.status !== 'PENDING_PAYMENT') { + amountSum += g._sum.total_price ?? 0; } - if (g.status !== 'CANCELED') amountSum += g._sum.total_price ?? 0; } return { counts, amountSum }; } diff --git a/src/features/order/resolvers/order-admin-query.resolver.ts b/src/features/order/resolvers/order-admin-query.resolver.ts index 664e08e1..0fc99139 100644 --- a/src/features/order/resolvers/order-admin-query.resolver.ts +++ b/src/features/order/resolvers/order-admin-query.resolver.ts @@ -8,6 +8,7 @@ import { AdminOrderService } from '@/features/order/services/order-admin.service import type { AdminOrderDetailOutput, AdminOrderSummaryOutput, + AdminStoreInProgressOrderSummaryOutput, } from '@/features/order/types/order-admin-output.type'; import { CurrentUser, @@ -39,4 +40,15 @@ export class AdminOrderQueryResolver { ): Promise { return this.orderService.adminOrder(parseAccountId(user), parseId(orderId)); } + + @Query('adminStoreInProgressOrderSummary') + adminStoreInProgressOrderSummary( + @CurrentUser() user: JwtUser, + @Args('storeId') storeId: string, + ): Promise { + return this.orderService.adminStoreInProgressOrderSummary( + parseAccountId(user), + parseId(storeId), + ); + } } diff --git a/src/features/order/resolvers/order-admin.resolver.spec.ts b/src/features/order/resolvers/order-admin.resolver.spec.ts index 626e8ad8..312c2283 100644 --- a/src/features/order/resolvers/order-admin.resolver.spec.ts +++ b/src/features/order/resolvers/order-admin.resolver.spec.ts @@ -86,4 +86,19 @@ describe('Admin Order Resolvers (real DB)', () => { }); expect(canceled.status).toBe('CANCELED'); }); + + it('매장 진행 주문 요약 경로', async () => { + const actor = await createAccount(prisma, { account_type: 'ADMIN' }); + const item = await createOrderItem(prisma); + + const summary = await queryResolver.adminStoreInProgressOrderSummary( + { accountId: actor.id.toString(), accountType: 'ADMIN' }, + item.store_id.toString(), + ); + expect(summary).toEqual({ + storeId: item.store_id.toString(), + totalCount: 1, + byStatus: [{ status: 'SUBMITTED', count: 1 }], + }); + }); }); diff --git a/src/features/order/services/order-admin.service.spec.ts b/src/features/order/services/order-admin.service.spec.ts index 888d448d..85f5f240 100644 --- a/src/features/order/services/order-admin.service.spec.ts +++ b/src/features/order/services/order-admin.service.spec.ts @@ -12,7 +12,7 @@ import { OrderRepository } from '@/features/order/repositories/order.repository' import { AdminOrderService } from '@/features/order/services/order-admin.service'; import { OrderEventsService } from '@/features/order/services/order-events.service'; import { OutboxDispatcherService } from '@/features/outbox'; -import type { PrismaClient } from '@/generated/prisma/client'; +import type { OrderStatus, PrismaClient } from '@/generated/prisma/client'; import { PUB_SUB } from '@/global/pubsub'; import { disconnectTestPrismaClient } from '@/test/db/prisma-test-client'; import { closeTruncateConnection, truncateAll } from '@/test/db/truncate'; @@ -78,10 +78,11 @@ describe('AdminOrderService (real DB)', () => { async function orderWithItem( overrides: { - status?: 'SUBMITTED' | 'CONFIRMED' | 'MADE' | 'PICKED_UP' | 'CANCELED'; + status?: OrderStatus; storeId?: bigint; buyerName?: string; orderNumber?: string; + submittedAt?: Date | null; } = {}, ) { const buyer = await createAccount(prisma, { account_type: 'USER' }); @@ -97,6 +98,7 @@ describe('AdminOrderService (real DB)', () => { status: overrides.status, buyer_name: overrides.buyerName, order_number: overrides.orderNumber, + submitted_at: overrides.submittedAt, }); const item = await createOrderItem(prisma, { order_id: order.id, @@ -226,6 +228,106 @@ describe('AdminOrderService (real DB)', () => { }); }); + describe('adminOrders inProgress', () => { + async function seedStatuses(): Promise> { + const byId = new Map(); + for (const status of [ + 'PENDING_PAYMENT', + 'SUBMITTED', + 'CONFIRMED', + 'MADE', + 'PICKED_UP', + 'NO_SHOW', + 'CANCELED', + ] as const) { + const { order } = await orderWithItem({ status }); + byId.set(order.id.toString(), status); + } + return byId; + } + + it('true면 입금 대기·접수·확정·제작 완료만, totalCount도 같다', async () => { + const byId = await seedStatuses(); + const result = await service.adminOrders(await admin(), { + inProgress: true, + }); + expect(result.items.map((o) => byId.get(o.id)).sort()).toEqual( + ['CONFIRMED', 'MADE', 'PENDING_PAYMENT', 'SUBMITTED'].sort(), + ); + expect(result.totalCount).toBe(4); + }); + + it.each([false, null, undefined])('%p면 전체다', async (inProgress) => { + await seedStatuses(); + const result = await service.adminOrders(await admin(), { + inProgress: inProgress as boolean | undefined, + }); + expect(result.totalCount).toBe(7); + }); + + it('status와 함께 오면 AND다', async () => { + await seedStatuses(); + const actor = await admin(); + const both = (status: OrderStatus) => + service.adminOrders(actor, { inProgress: true, status }); + expect((await both('MADE')).totalCount).toBe(1); + expect((await both('PICKED_UP')).totalCount).toBe(0); + }); + }); + + describe('adminStoreInProgressOrderSummary', () => { + it('진행 중 주문만 상태별로 세고 0건 상태는 빼며 흐름 순으로 준다', async () => { + const store = await createStore(prisma); + for (const status of [ + 'MADE', + 'PENDING_PAYMENT', + 'PENDING_PAYMENT', + 'SUBMITTED', + 'PICKED_UP', + 'NO_SHOW', + 'CANCELED', + ] as const) { + await orderWithItem({ status, storeId: store.id }); + } + // 다른 매장 주문은 세지 않는다 + await orderWithItem({ status: 'CONFIRMED' }); + + const result = await service.adminStoreInProgressOrderSummary( + await admin(), + store.id, + ); + expect(result).toEqual({ + storeId: store.id.toString(), + totalCount: 4, + byStatus: [ + { status: 'PENDING_PAYMENT', count: 2 }, + { status: 'SUBMITTED', count: 1 }, + { status: 'MADE', count: 1 }, + ], + }); + }); + + it('진행 중 주문이 없으면(없는 매장 포함) 0건이다', async () => { + const store = await createStore(prisma); + await orderWithItem({ status: 'PICKED_UP', storeId: store.id }); + for (const storeId of [store.id, store.id + 1000n]) { + expect( + await service.adminStoreInProgressOrderSummary( + await admin(), + storeId, + ), + ).toEqual({ storeId: storeId.toString(), totalCount: 0, byStatus: [] }); + } + }); + + it('관리자가 아니면 403', async () => { + const user = await createAccount(prisma, { account_type: 'USER' }); + await expect( + service.adminStoreInProgressOrderSummary(user.id, 1n), + ).rejects.toThrowDomain(403); + }); + }); + describe('adminOrder', () => { it('구매자 요약·전체 품목·상태 이력을 준다', async () => { const { order, item, buyer } = await orderWithItem(); @@ -312,7 +414,7 @@ describe('AdminOrderService (real DB)', () => { }, ); - it.each(['PICKED_UP', 'CANCELED'] as const)( + it.each(['PICKED_UP', 'CANCELED', 'NO_SHOW', 'PENDING_PAYMENT'] as const)( '%s 주문은 400(판매자와 같은 전이 규칙)', async (status) => { const { order } = await orderWithItem({ status }); @@ -485,6 +587,21 @@ describe('AdminOrderService (real DB)', () => { topic.stop(); }); + it('입금 확인 전(submitted_at 없음) 주문의 취소는 판매자에게 보이지 않아 발행하지 않는다', async () => { + const { order } = await orderWithItem({ submittedAt: null }); + const publish = jest.spyOn(pubSub, 'publish'); + + const result = await service.adminCancelOrder(await admin(), { + orderId: order.id.toString(), + note: 'x', + }); + + const published = publish.mock.calls.length; + publish.mockRestore(); + expect(result.status).toBe('CANCELED'); + expect(published).toBe(0); + }); + it('활성 품목이 없으면 매장을 알 수 없어 발행을 생략한다', async () => { const { order, item } = await orderWithItem(); await prisma.orderItem.update({ diff --git a/src/features/order/services/order-admin.service.ts b/src/features/order/services/order-admin.service.ts index e2e9434d..0f5f92c6 100644 --- a/src/features/order/services/order-admin.service.ts +++ b/src/features/order/services/order-admin.service.ts @@ -31,6 +31,7 @@ import { OrderEventsService } from '@/features/order/services/order-events.servi import type { AdminOrderDetailOutput, AdminOrderSummaryOutput, + AdminStoreInProgressOrderSummaryOutput, } from '@/features/order/types/order-admin-output.type'; import { OrderStatus } from '@/generated/prisma/client'; @@ -60,6 +61,7 @@ export class AdminOrderService extends AdminBaseService { const filter = { keyword: input?.keyword?.trim() || undefined, status: input?.status ? this.statusPolicy.parse(input.status) : undefined, + inProgress: input?.inProgress ?? false, storeId: parseOptionalId(input?.storeId) ?? undefined, accountId: parseOptionalId(input?.accountId) ?? undefined, fromCreatedAt: toDate(input?.fromCreatedAt), @@ -89,6 +91,21 @@ export class AdminOrderService extends AdminBaseService { return toAdminOrderDetailOutput(row); } + /** 정지·숨김 전 경고용. 매장 존재는 보지 않는다(없는 매장은 0건). */ + async adminStoreInProgressOrderSummary( + accountId: bigint, + storeId: bigint, + ): Promise { + await this.requireAdminContext(accountId); + const byStatus = + await this.orderRepository.countInProgressOrdersByStore(storeId); + return { + storeId: storeId.toString(), + totalCount: byStatus.reduce((sum, row) => sum + row.count, 0), + byStatus, + }; + } + async adminCancelOrder( accountId: bigint, input: AdminCancelOrderInput, @@ -136,9 +153,9 @@ export class AdminOrderService extends AdminBaseService { throw new DomainException('ORDER_NOT_CANCELLABLE'); } - // 활성 품목이 없으면 매장을 알 수 없어 발행을 생략한다 + // 활성 품목이 없으면 매장을 알 수 없고, 입금 확인 전 주문은 판매자에게 보이지 않아 발행을 생략한다 const [firstItem] = updated.items; - if (firstItem) { + if (firstItem && updated.submitted_at) { await this.events.publishSellerOrderUpdate( firstItem.store_id, toSellerOrderUpdateEvent(updated, firstItem.product_name_snapshot), diff --git a/src/features/order/services/order-seller.service.spec.ts b/src/features/order/services/order-seller.service.spec.ts index acd3a847..98f42534 100644 --- a/src/features/order/services/order-seller.service.spec.ts +++ b/src/features/order/services/order-seller.service.spec.ts @@ -63,11 +63,13 @@ describe('SellerOrderService (real DB)', () => { async function createStoreOrder( storeId: bigint, - opts: { status?: OrderStatus } = {}, + opts: { status?: OrderStatus; buyerId?: bigint } = {}, ) { - const buyer = await createAccount(prisma, { account_type: 'USER' }); + const buyerId = + opts.buyerId ?? + (await createAccount(prisma, { account_type: 'USER' })).id; const order = await createOrder(prisma, { - account_id: buyer.id, + account_id: buyerId, status: opts.status ?? 'SUBMITTED', }); await createOrderItem(prisma, { @@ -244,6 +246,54 @@ describe('SellerOrderService (real DB)', () => { expect(result.items).toHaveLength(2); expect(result.nextCursor).not.toBeNull(); }); + + it('입금 확인 전(submitted_at 없음) 주문은 목록·건수에서 빠진다', async () => { + const { account, store } = await setupSellerWithStore(prisma); + const visible = await createStoreOrder(store.id); + await createStoreOrder(store.id, { status: 'PENDING_PAYMENT' }); + // 입금 전 취소도 submitted_at이 없어 함께 숨는다 + const unpaidCanceled = await createOrder(prisma, { + status: 'CANCELED', + submitted_at: null, + }); + await createOrderItem(prisma, { + order_id: unpaidCanceled.id, + store_id: store.id, + }); + + const all = await service.sellerOrderList(account.id); + expect(all.items.map((o) => o.id)).toEqual([visible.id.toString()]); + expect(all.totalCount).toBe(1); + const pending = await service.sellerOrderList(account.id, { + status: 'PENDING_PAYMENT', + }); + expect(pending.totalCount).toBe(0); + }); + + it('buyerAccountId면 그 구매자 주문만 준다', async () => { + const { account, store } = await setupSellerWithStore(prisma); + const buyer = await createAccount(prisma, { account_type: 'USER' }); + const mine = await createStoreOrder(store.id, { buyerId: buyer.id }); + await createStoreOrder(store.id); + + const result = await service.sellerOrderList(account.id, { + buyerAccountId: buyer.id.toString(), + }); + expect(result.items.map((o) => o.id)).toEqual([mine.id.toString()]); + expect(result.totalCount).toBe(1); + }); + + it('buyerAccountId 빈 문자열은 INVALID_ID, "0"은 버리지 않고 필터로 쓴다', async () => { + const { account, store } = await setupSellerWithStore(prisma); + await createStoreOrder(store.id); + await expect( + service.sellerOrderList(account.id, { buyerAccountId: '' }), + ).rejects.toThrowDomain('INVALID_ID'); + const zero = await service.sellerOrderList(account.id, { + buyerAccountId: '0', + }); + expect(zero.totalCount).toBe(0); + }); }); describe('sellerOrder', () => { @@ -310,6 +360,45 @@ describe('SellerOrderService (real DB)', () => { expect(result.statusHistories).toHaveLength(0); }); + it('입금 대기 주문 상세는 404다', async () => { + const { account, store } = await setupSellerWithStore(prisma); + const order = await createStoreOrder(store.id, { + status: 'PENDING_PAYMENT', + }); + await expect( + service.sellerOrder(account.id, order.id), + ).rejects.toThrowDomain('ORDER_NOT_FOUND'); + }); + + it('입금 대기 이력은 빠지고 접수 이력의 출발 상태는 null(최초)이다', async () => { + const { account, store } = await setupSellerWithStore(prisma); + const order = await createStoreOrder(store.id); + const at = (m: number) => new Date(Date.UTC(2026, 3, 15, 10, m)); + await prisma.orderStatusHistory.createMany({ + data: [ + { + order_id: order.id, + from_status: null, + to_status: 'PENDING_PAYMENT', + changed_at: at(0), + actor_type: 'BUYER', + }, + { + order_id: order.id, + from_status: 'PENDING_PAYMENT', + to_status: 'SUBMITTED', + changed_at: at(10), + actor_type: 'ADMIN', + }, + ], + }); + + const result = await service.sellerOrder(account.id, order.id); + expect(result.statusHistories).toEqual([ + expect.objectContaining({ fromStatus: null, toStatus: 'SUBMITTED' }), + ]); + }); + it('soft-delete된 아이템만 있는 주문은 상세·목록 모두에서 제외한다', async () => { const { account, store } = await setupSellerWithStore(prisma); const order = await createStoreOrder(store.id); @@ -402,6 +491,39 @@ describe('SellerOrderService (real DB)', () => { }); }); + it.each([OrderStatus.NO_SHOW, OrderStatus.PENDING_PAYMENT])( + '판매자는 %s로 바꿀 수 없다(400, 상태 불변)', + async (toStatus) => { + const { account, store } = await setupSellerWithStore(prisma); + const order = await createStoreOrder(store.id, { status: 'MADE' }); + + await expect( + service.sellerUpdateOrderStatus(account.id, { + orderId: order.id.toString(), + toStatus, + }), + ).rejects.toThrowDomain('INVALID_ORDER_STATUS_TRANSITION'); + const row = await prisma.order.findUniqueOrThrow({ + where: { id: order.id }, + }); + expect(row.status).toBe('MADE'); + }, + ); + + it('입금 대기 주문은 상태를 바꿀 수 없다(404)', async () => { + const { account, store } = await setupSellerWithStore(prisma); + const order = await createStoreOrder(store.id, { + status: 'PENDING_PAYMENT', + }); + await expect( + service.sellerUpdateOrderStatus(account.id, { + orderId: order.id.toString(), + toStatus: 'CANCELED', + note: '취소', + }), + ).rejects.toThrowDomain('ORDER_NOT_FOUND'); + }); + it('사전 검사 뒤 품목이 삭제돼도 상태는 바뀌고 첫 품목 필드는 null이다', async () => { const { account, store } = await setupSellerWithStore(prisma); const order = await createStoreOrder(store.id); diff --git a/src/features/order/services/order-seller.service.ts b/src/features/order/services/order-seller.service.ts index 988d04db..d4b0f597 100644 --- a/src/features/order/services/order-seller.service.ts +++ b/src/features/order/services/order-seller.service.ts @@ -3,7 +3,7 @@ import { Inject, Injectable } from '@nestjs/common'; import { DomainException } from '@/common/errors/error-catalog'; import type { CursorConnection } from '@/common/types/cursor-connection.type'; import { toDate } from '@/common/utils/date-parser'; -import { parseId } from '@/common/utils/id-parser'; +import { parseId, parseOptionalId } from '@/common/utils/id-parser'; import { parseIdCursor } from '@/common/utils/keyset-cursor'; import { normalizeCursorInput, @@ -62,6 +62,7 @@ export class SellerOrderService extends SellerBaseService { const filters = { storeId: ctx.storeId, status: input?.status ? this.statusPolicy.parse(input.status) : undefined, + buyerAccountId: parseOptionalId(input?.buyerAccountId) ?? undefined, fromCreatedAt: toDate(input?.fromCreatedAt), toCreatedAt: toDate(input?.toCreatedAt), fromPickupAt: toDate(input?.fromPickupAt), @@ -202,7 +203,14 @@ export class SellerOrderService extends SellerBaseService { createdAt: row.created_at, updatedAt: row.updated_at, items: row.items.map(toOrderItemDetail), - statusHistories: row.status_histories.map(toOrderStatusHistory), + // 입금 대기 이력은 repository가 뺐다 — 접수 이력의 출발 상태도 판매자에게는 '최초'로 보인다 + statusHistories: row.status_histories.map((history) => + toOrderStatusHistory( + history.from_status === OrderStatus.PENDING_PAYMENT + ? { ...history, from_status: null } + : history, + ), + ), }; } } diff --git a/src/features/order/types/order-admin-output.type.ts b/src/features/order/types/order-admin-output.type.ts index 55246c2d..6cb07d00 100644 --- a/src/features/order/types/order-admin-output.type.ts +++ b/src/features/order/types/order-admin-output.type.ts @@ -20,6 +20,12 @@ export interface AdminOrderSummaryOutput { firstItemImageUrl: string | null; } +export interface AdminStoreInProgressOrderSummaryOutput { + storeId: string; + totalCount: number; + byStatus: { status: OrderStatus; count: number }[]; +} + export interface AdminOrderDetailOutput { id: string; orderNumber: string; diff --git a/src/features/store/constants/store-ranking.constants.ts b/src/features/store/constants/store-ranking.constants.ts index a62d7d86..2daf9933 100644 --- a/src/features/store/constants/store-ranking.constants.ts +++ b/src/features/store/constants/store-ranking.constants.ts @@ -13,10 +13,12 @@ export const RANKING_BAYESIAN_M = 5; export const RANKING_RECENT_ORDER_DAYS = 30; +// 노쇼도 판매자가 만든 케이크라 픽업 완료와 같이 센다 export const RANKING_VALID_ORDER_STATUSES = [ 'CONFIRMED', 'MADE', 'PICKED_UP', + 'NO_SHOW', ] as const; export const DEFAULT_GLOBAL_RATING_PRIOR = 4.0; diff --git a/src/features/store/repositories/store-stats.repository.spec.ts b/src/features/store/repositories/store-stats.repository.spec.ts index 29043b22..339f9b32 100644 --- a/src/features/store/repositories/store-stats.repository.spec.ts +++ b/src/features/store/repositories/store-stats.repository.spec.ts @@ -1,5 +1,5 @@ import { StoreStatsRepository } from '@/features/store/repositories/store-stats.repository'; -import type { OrderStatus, PrismaClient } from '@/generated/prisma/client'; +import { OrderStatus, type PrismaClient } from '@/generated/prisma/client'; import { disconnectTestPrismaClient } from '@/test/db/prisma-test-client'; import { closeTruncateConnection, truncateAll } from '@/test/db/truncate'; import { @@ -113,6 +113,25 @@ describe('StoreStatsRepository (real DB)', () => { expect(sold.get(store.id)).toBe(4); }); + // 판매자가 만든 케이크(확정 이후, 노쇼 포함)만 유효하다 + it.each( + Object.values(OrderStatus).map((status) => [ + status, + ['CONFIRMED', 'MADE', 'PICKED_UP', 'NO_SHOW'].includes(status), + ]), + )('%s 주문의 유효 여부는 %s다', async (status, valid) => { + const store = await createStore(prisma); + const product = await createProduct(prisma, { store_id: store.id }); + await placeOrder({ storeId: store.id, productId: product.id, status }); + + const counts = await repo.aggregateRecentOrderCounts( + 'store_id', + [store.id], + SINCE, + ); + expect(counts.get(store.id) ?? 0).toBe(valid ? 1 : 0); + }); + it('since 경계(같은 시각)는 포함한다', async () => { const store = await createStore(prisma); const product = await createProduct(prisma, { store_id: store.id }); diff --git a/src/test/roles-coverage.spec.ts b/src/test/roles-coverage.spec.ts index 383e3d8f..6f65f801 100644 --- a/src/test/roles-coverage.spec.ts +++ b/src/test/roles-coverage.spec.ts @@ -14,7 +14,7 @@ describe('접두 루트 필드 인가 커버리지', () => { describe.each([ ['seller', 'SELLER', 56], - ['admin', 'ADMIN', 59], + ['admin', 'ADMIN', 60], ] as const)('%s 접두 → @Roles(%s)', (prefix, role, count) => { const fields = collectRootFieldsWithPrefix(prefix); From 9ecf314cbbc20b20addbdb6147bcd5cef5ab2d1e Mon Sep 17 00:00:00 2001 From: chanwoo7 Date: Thu, 19 Nov 2026 00:46:42 +0900 Subject: [PATCH 04/54] =?UTF-8?q?fix:=20=EC=A7=84=ED=96=89=20=EC=A3=BC?= =?UTF-8?q?=EB=AC=B8=20=EC=9A=94=EC=95=BD=20=EC=82=AD=EC=A0=9C=20=EC=A0=9C?= =?UTF-8?q?=EC=99=B8=20=ED=9A=8C=EA=B7=80=20=ED=85=8C=EC=8A=A4=ED=8A=B8?= =?UTF-8?q?=EC=99=80=20=ED=8C=90=EB=A7=A4=EC=9E=90=20=EC=A7=91=EA=B3=84=20?= =?UTF-8?q?=EB=85=B8=EC=B6=9C=20=EC=A1=B0=EA=B1=B4=20=EC=A0=95=EB=A6=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 리뷰 지적을 반영한다. - 주문 생성 리졸버 spec도 truncateAll 뒤 결제 설정 행을 다시 만든다. 이후 결제 계좌 미설정 검사가 들어와도 깨지지 않게 서비스 spec과 맞춘다. - 매장 진행 주문 요약이 삭제된 주문과 이 매장 품목이 삭제된 주문을 세지 않는지 확인하는 테스트가 없었다. - aggregateStoreOrdersInRange의 접수 기준 범위가 같은 submitted_at 키로 판매자 노출 조건을 덮어써 조건이 조용히 사라졌다(결과는 범위가 NULL을 빼서 같았다). - SDL 설명 두 곳이 새 동작과 어긋났다. 변경점 - order.repository: aggregateStoreOrdersInRange에서 노출 조건과 기간 범위를 AND로 묶는다. - order-subscription.graphql: 입금 확인 전 주문의 취소는 발행하지 않는다고 적는다. - mypage-overview.graphql: OngoingOrderSummary를 입금 대기부터 제작 완료까지로, 노쇼 제외를 적는다. - order-checkout-mutation.resolver.spec: beforeEach에서 createPaymentSetting을 부른다. 테스트 - order-admin.service.spec: 진행 주문 요약 삭제 제외 1건 추가. 품목 조건의 activeWhere를 지우면 실패한다. - AND 안의 노출 조건을 지우면 order.repository·dashboard-seller spec의 입금 대기 제외 2건이 실패한다. - order-admin.service·order-checkout-mutation.resolver·order.repository·dashboard-seller service·resolver 5 스위트 86건 통과. --- src/features/mypage/mypage-overview.graphql | 2 +- src/features/order/order-subscription.graphql | 2 +- .../order/repositories/order.repository.ts | 15 ++++++---- .../order-checkout-mutation.resolver.spec.ts | 3 ++ .../services/order-admin.service.spec.ts | 29 +++++++++++++++++++ 5 files changed, 44 insertions(+), 7 deletions(-) diff --git a/src/features/mypage/mypage-overview.graphql b/src/features/mypage/mypage-overview.graphql index eecd03f3..5c10008c 100644 --- a/src/features/mypage/mypage-overview.graphql +++ b/src/features/mypage/mypage-overview.graphql @@ -38,7 +38,7 @@ type MyPageCounts { } """ -진행중 주문 요약 카드. 픽업 완료·취소는 제외된다. +진행중 주문 요약 카드. 입금 대기부터 제작 완료까지만 담고, 픽업 완료·노쇼·취소는 제외된다. """ type OngoingOrderSummary { orderId: ID! diff --git a/src/features/order/order-subscription.graphql b/src/features/order/order-subscription.graphql index 781c9753..8759b9c5 100644 --- a/src/features/order/order-subscription.graphql +++ b/src/features/order/order-subscription.graphql @@ -3,7 +3,7 @@ extend type Subscription { 내 매장 주문 생성·상태 변경 이벤트. 판매자 로그인 필수(SELLER 아니면 FORBIDDEN). 삭제되지 않은 매장을 보유한 판매자만 구독할 수 있다 — 매장이 없거나 삭제됐으면 NOT_FOUND. 비활성(is_active=false) 매장도 구독은 유지된다. 인증은 graphql-ws connectionParams.authorization. - 구매자 주문 생성(SUBMITTED)·판매자 상태 변경·관리자 강제 취소가 모두 여기로 온다. + 구매자 주문 생성(SUBMITTED)·판매자 상태 변경·관리자 강제 취소가 모두 여기로 온다. 입금 확인 전 주문의 취소는 오지 않는다. """ sellerOrderUpdated: SellerOrderUpdate! } diff --git a/src/features/order/repositories/order.repository.ts b/src/features/order/repositories/order.repository.ts index f0076f9c..663c6d25 100644 --- a/src/features/order/repositories/order.repository.ts +++ b/src/features/order/repositories/order.repository.ts @@ -712,12 +712,17 @@ export class OrderRepository { }): Promise<{ orderCount: number; salesAmount: number }> { const result = await this.prisma.order.aggregate({ where: { - ...sellerVisibleWhere, + // 접수 기준 범위가 노출 조건의 submitted_at 키를 덮어쓰지 않도록 AND로 묶는다 + AND: [ + sellerVisibleWhere, + { + [args.basis === 'pickup' ? 'pickup_at' : 'submitted_at']: { + gte: args.from, + lt: args.to, + }, + }, + ], status: { not: 'CANCELED' }, - [args.basis === 'pickup' ? 'pickup_at' : 'submitted_at']: { - gte: args.from, - lt: args.to, - }, items: { some: { store_id: args.storeId, ...activeWhere } }, }, _count: { _all: true }, diff --git a/src/features/order/resolvers/order-checkout-mutation.resolver.spec.ts b/src/features/order/resolvers/order-checkout-mutation.resolver.spec.ts index 8dc0094d..1862e869 100644 --- a/src/features/order/resolvers/order-checkout-mutation.resolver.spec.ts +++ b/src/features/order/resolvers/order-checkout-mutation.resolver.spec.ts @@ -19,6 +19,7 @@ import { disconnectTestPrismaClient } from '@/test/db/prisma-test-client'; import { closeTruncateConnection, truncateAll } from '@/test/db/truncate'; import { createAccount, + createPaymentSetting, createProduct, createStore, createUserProfile, @@ -66,6 +67,8 @@ describe('OrderCheckout Mutation Resolver (real DB)', () => { beforeEach(async () => { await truncateAll(); + // truncateAll이 마이그레이션이 넣은 결제 설정 행까지 지운다 + await createPaymentSetting(prisma); jest.spyOn(clock, 'now').mockReturnValue(NOW); }); diff --git a/src/features/order/services/order-admin.service.spec.ts b/src/features/order/services/order-admin.service.spec.ts index 85f5f240..526fb519 100644 --- a/src/features/order/services/order-admin.service.spec.ts +++ b/src/features/order/services/order-admin.service.spec.ts @@ -320,6 +320,35 @@ describe('AdminOrderService (real DB)', () => { } }); + it('삭제된 주문과 이 매장 품목이 삭제된 주문은 세지 않는다', async () => { + const store = await createStore(prisma); + await orderWithItem({ status: 'SUBMITTED', storeId: store.id }); + const deletedOrder = await orderWithItem({ + status: 'CONFIRMED', + storeId: store.id, + }); + await prisma.order.update({ + where: { id: deletedOrder.order.id }, + data: { deleted_at: new Date() }, + }); + const deletedItem = await orderWithItem({ + status: 'MADE', + storeId: store.id, + }); + await prisma.orderItem.update({ + where: { id: deletedItem.item.id }, + data: { deleted_at: new Date() }, + }); + + expect( + await service.adminStoreInProgressOrderSummary(await admin(), store.id), + ).toEqual({ + storeId: store.id.toString(), + totalCount: 1, + byStatus: [{ status: 'SUBMITTED', count: 1 }], + }); + }); + it('관리자가 아니면 403', async () => { const user = await createAccount(prisma, { account_type: 'USER' }); await expect( From 4d50cbe73dc635452f0a776b94e51d2b0e14d1e2 Mon Sep 17 00:00:00 2001 From: chanwoo7 Date: Thu, 19 Nov 2026 01:08:56 +0900 Subject: [PATCH 05/54] =?UTF-8?q?feat:=20=EC=A3=BC=EB=AC=B8=20=EC=83=9D?= =?UTF-8?q?=EC=84=B1=20=EA=B8=B0=EB=8C=80=20=EA=B8=88=EC=95=A1=C2=B7?= =?UTF-8?q?=EC=9E=85=EB=A0=A5=20=ED=95=B4=EC=8B=9C=C2=B7=EC=9A=94=EC=B2=AD?= =?UTF-8?q?=20=EC=82=AC=ED=95=AD=EA=B3=BC=20=ED=94=BD=EC=97=85=20=EB=8B=AC?= =?UTF-8?q?=EB=A0=A5=20=EC=83=81=ED=92=88=20=EC=A0=9C=EC=9E=91=20=EC=8B=9C?= =?UTF-8?q?=EA=B0=84=20=EB=B0=98=EC=98=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 주문서가 본 금액·입력과 서버가 만드는 주문이 어긋나지 않게 한다. 픽업 달력은 상품 제작 시간을 보지 않아 달력에서 고른 슬롯이 주문 생성에서 거절될 수 있었고, 멱등 replay는 입력을 비교하지 않아 같은 키로 다른 주문서를 보내도 기존 주문을 돌려줬다. 주문 생성 결과 상태는 여전히 SUBMITTED다. - 픽업 하한 단일화: store-pickup-policy.helper의 effectiveLeadTimeMinutes(매장 리드타임과 상품 제작 시간 중 긴 쪽)를 달력·슬롯·isPickupSlotAvailable이 함께 쓴다(store 배럴로 공개). 하한 자체(지금 + 리드타임/제작 시간)는 그대로 - pickupCalendar·pickupTimeSlots에 productId(선택). store repository가 그 매장의 판매 중 상품 제작 시간을 읽고, 아니면 PRODUCT_NOT_FOUND. 매장 확인이 먼저다 - isPickupSlotAvailable({ storeId, pickupAt, preparationTimeMinutes }). createOrder의 자체 제작 시간 비교를 지우고 이 판정만 쓴다 - CreateOrderInput.expectedTotalPrice: Int!(0 이상). 서버 계산 총액과 다르면 ORDER_PRICE_CHANGED(409), 주문·키를 남기지 않는다 - CreateOrderInput.requestNote(500자). 앞뒤 공백을 지우고 비면 null로 저장. MyOrderDetail·SellerOrderDetail·AdminOrderDetail.requestNote로 내보냄 - 입력 해시: order-input-hash.helper가 productId·optionItemIds(정렬)·pickupAt(ISO)·quantity(생략 = 1)·buyerName·buyerPhone·requestNote·expectedTotalPrice를 키 정렬 JSON(null 키 생략)으로 만든 sha256을 idempotency_input_hash에 저장. replay 세 경로(사전 조회, capacity 거절 뒤 tx 밖·안, 멱등 키 P2002)에서 다르면 IDEMPOTENCY_KEY_INPUT_MISMATCH(400). 해시가 없는 기존 주문은 비교하지 않음 - 에러 카탈로그: ORDER_PRICE_CHANGED, IDEMPOTENCY_KEY_INPUT_MISMATCH 테스트 68건 추가(1건 대체) - 하루 슬롯 20개 전부에 대해 pickupTimeSlots(productId)의 available ⇔ createOrder 성공(it.each) - 해시 경우: 같은 입력 replay, 필드별 불일치 6, 기존 해시 null, capacity 거절 뒤 2(tx 밖·안), P2002, quantity 생략 = 1. '입력 비교 없음' 테스트는 불일치 거절로 대체 - 해시 helper 14: 정규화 형식 고정, 옵션 순서·시각 표기·quantity·null 불변, 필드 8개 각각 변화, 따옴표 주입 - productId: 빈 문자열 INVALID_ID·"0"은 버리지 않고 PRODUCT_NOT_FOUND, 다른 매장·비활성·삭제·없는 상품 PRODUCT_NOT_FOUND, 매장 우선, 달력·슬롯 제작 시간 반영, 하한 helper 5 - 기대 금액 ±1원 거절 뒤 같은 키 성공 2, 요청 사항 정규화 3, DTO 6, 3면 출력 단언 - 반증: replay 비교를 경로별로 지우면 각 경로 테스트(6·2·1건)가, 제작 시간 전달을 0으로 바꾸면 슬롯 16건과 제작 시간 테스트가, 금액 비교를 지우면 2건이, 달력의 제작 시간 반영을 지우면 19건이, 상품 매장·판매 조건을 지우면 PRODUCT_NOT_FOUND 테스트가 실패함을 확인 --- src/common/errors/error-catalog.ts | 9 + .../dto/inputs/create-order.input.spec.ts | 29 +- .../order/dto/inputs/create-order.input.ts | 9 + src/features/order/order-admin.graphql | 4 + src/features/order/order-checkout.graphql | 9 +- src/features/order/order-my.graphql | 4 + src/features/order/order-seller.graphql | 4 + .../repositories/order.repository.spec.ts | 2 + .../order/repositories/order.repository.ts | 7 + .../order-checkout-mutation.resolver.spec.ts | 3 + .../services/order-admin-mappers.helper.ts | 1 + .../services/order-admin.service.spec.ts | 5 + .../services/order-checkout.service.spec.ts | 281 ++++++++++++++++-- .../order/services/order-checkout.service.ts | 46 ++- .../services/order-input-hash.helper.spec.ts | 81 +++++ .../order/services/order-input-hash.helper.ts | 43 +++ .../order/services/order-my.service.spec.ts | 5 + .../order/services/order-my.service.ts | 1 + .../services/order-seller.service.spec.ts | 5 + .../order/services/order-seller.service.ts | 2 + .../order/types/order-admin-output.type.ts | 1 + .../order/types/order-my-output.type.ts | 1 + .../order/types/order-seller-output.type.ts | 1 + src/features/store/index.ts | 2 + .../store/repositories/store.repository.ts | 12 + ...ore-pickup-schedule-query.resolver.spec.ts | 44 ++- .../store-pickup-schedule-query.resolver.ts | 16 +- .../store-pickup-policy.helper.spec.ts | 16 + .../services/store-pickup-policy.helper.ts | 8 + .../store-pickup-schedule.service.spec.ts | 137 +++++++++ .../services/store-pickup-schedule.service.ts | 52 +++- .../store/store-pickup-schedule.graphql | 12 +- 32 files changed, 797 insertions(+), 55 deletions(-) create mode 100644 src/features/order/services/order-input-hash.helper.spec.ts create mode 100644 src/features/order/services/order-input-hash.helper.ts diff --git a/src/common/errors/error-catalog.ts b/src/common/errors/error-catalog.ts index acbc5450..f3191925 100644 --- a/src/common/errors/error-catalog.ts +++ b/src/common/errors/error-catalog.ts @@ -343,6 +343,10 @@ export const ERROR_CATALOG = { status: HttpStatus.BAD_REQUEST, message: '주문 금액이 처리 가능한 범위를 벗어났습니다.', }, + ORDER_PRICE_CHANGED: { + status: HttpStatus.CONFLICT, + message: '가격이 바뀌었어요. 금액을 다시 확인해 주세요.', + }, UNSUPPORTED_CURRENCY: { status: HttpStatus.BAD_REQUEST, message: 'KRW 상품만 주문할 수 있습니다.', @@ -357,6 +361,11 @@ export const ERROR_CATALOG = { message: '이 요청 키로는 주문을 만들 수 없습니다. 주문서를 새로 열어 다시 시도해 주세요.', }, + IDEMPOTENCY_KEY_INPUT_MISMATCH: { + status: HttpStatus.BAD_REQUEST, + message: + '같은 요청 키로 다른 주문 내용이 들어왔습니다. 주문서를 새로 열어 다시 시도해 주세요.', + }, IDEMPOTENT_REPLAY_FAILED: { status: HttpStatus.INTERNAL_SERVER_ERROR, message: diff --git a/src/features/order/dto/inputs/create-order.input.spec.ts b/src/features/order/dto/inputs/create-order.input.spec.ts index 8d42f493..f4a2bc5f 100644 --- a/src/features/order/dto/inputs/create-order.input.spec.ts +++ b/src/features/order/dto/inputs/create-order.input.spec.ts @@ -14,10 +14,11 @@ const VALID = { productId: '1', optionItemIds: ['10', '11'], pickupAt: new Date('2026-09-18T05:00:00.000Z'), + expectedTotalPrice: 25000, }; describe('CreateOrderInput', () => { - it('필수 필드만으로 통과한다 (quantity/buyer는 optional)', async () => { + it('필수 필드만으로 통과한다 (quantity/buyer/requestNote는 optional)', async () => { expect(await validate(build(VALID))).toHaveLength(0); }); @@ -84,4 +85,30 @@ describe('CreateOrderInput', () => { await validate(build({ ...VALID, buyerPhone: '010-0000-1111' })), ).toHaveLength(0); }); + + it.each<[string, unknown]>([ + ['누락', undefined], + ['음수', -1], + ['소수', 100.5], + ['문자열', '25000'], + ])('expectedTotalPrice %s는 거절한다', async (_case, expectedTotalPrice) => { + const errors = await validate(build({ ...VALID, expectedTotalPrice })); + expect(errors.map((e) => e.property)).toEqual(['expectedTotalPrice']); + }); + + it('expectedTotalPrice 0은 통과한다', async () => { + expect( + await validate(build({ ...VALID, expectedTotalPrice: 0 })), + ).toHaveLength(0); + }); + + it('requestNote는 500자까지 허용하고 501자는 거절한다', async () => { + expect( + await validate(build({ ...VALID, requestNote: '가'.repeat(500) })), + ).toHaveLength(0); + const errors = await validate( + build({ ...VALID, requestNote: '가'.repeat(501) }), + ); + expect(errors.map((e) => e.property)).toEqual(['requestNote']); + }); }); diff --git a/src/features/order/dto/inputs/create-order.input.ts b/src/features/order/dto/inputs/create-order.input.ts index b8620efd..cd7e9f67 100644 --- a/src/features/order/dto/inputs/create-order.input.ts +++ b/src/features/order/dto/inputs/create-order.input.ts @@ -50,4 +50,13 @@ export class CreateOrderInput { // 검증된 프로필 값을 덮어쓰지 못하게 형식을 강제한다 @Matches(PHONE_REGEX) buyerPhone?: string; + + @IsInt() + @Min(0) + expectedTotalPrice!: number; + + @IsOptional() + @IsString() + @MaxLength(500) + requestNote?: string; } diff --git a/src/features/order/order-admin.graphql b/src/features/order/order-admin.graphql index 0c22488d..7e4f11bd 100644 --- a/src/features/order/order-admin.graphql +++ b/src/features/order/order-admin.graphql @@ -154,6 +154,10 @@ type AdminOrderDetail { """ buyerPhone: String! """ + 구매자가 남긴 요청 사항. 없으면 null. + """ + requestNote: String + """ 할인 전 품목 합계(원). """ subtotalPrice: Int! diff --git a/src/features/order/order-checkout.graphql b/src/features/order/order-checkout.graphql index 0ae41297..2ab60063 100644 --- a/src/features/order/order-checkout.graphql +++ b/src/features/order/order-checkout.graphql @@ -8,12 +8,13 @@ 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 @@ -21,6 +22,12 @@ input CreateOrderInput { buyerName: String """미입력 시 프로필 전화번호 사용. 둘 다 없으면 거절.""" buyerPhone: String + """ + 화면에 보여 준 최종 결제 금액(원). 서버가 다시 계산한 금액과 다르면 ORDER_PRICE_CHANGED로 거절한다. + """ + expectedTotalPrice: Int! + """판매자에게 전할 요청 사항(최대 500자). 공백만 보내면 없음으로 저장한다.""" + requestNote: String } """주문 생성 결과 요약. 상세는 myOrder로 재조회.""" diff --git a/src/features/order/order-my.graphql b/src/features/order/order-my.graphql index a8ea08d8..9f495868 100644 --- a/src/features/order/order-my.graphql +++ b/src/features/order/order-my.graphql @@ -131,6 +131,10 @@ type MyOrderDetail { 주문자 연락처. """ buyerPhone: String! + """ + 구매자가 남긴 요청 사항. 없으면 null. + """ + requestNote: String """ 할인 전 품목 합계(원). diff --git a/src/features/order/order-seller.graphql b/src/features/order/order-seller.graphql index 56a55828..6e055b3d 100644 --- a/src/features/order/order-seller.graphql +++ b/src/features/order/order-seller.graphql @@ -155,6 +155,10 @@ type SellerOrderDetail { """ buyerPhone: String! """ + 구매자가 남긴 요청 사항. 없으면 null. + """ + requestNote: String + """ 할인 전 품목 합계(원). """ subtotalPrice: Int! diff --git a/src/features/order/repositories/order.repository.spec.ts b/src/features/order/repositories/order.repository.spec.ts index ae464686..1bc90036 100644 --- a/src/features/order/repositories/order.repository.spec.ts +++ b/src/features/order/repositories/order.repository.spec.ts @@ -952,9 +952,11 @@ describe('OrderRepository (real DB)', () => { accountId: args.buyerId, orderNumber: args.orderNumber ?? 'ORD-20260916-ABC234', idempotencyKey: `idem-${args.orderNumber ?? 'base'}`, + idempotencyInputHash: 'a'.repeat(64), pickupAt: PICKUP_AT, buyerName: '차차', buyerPhone: '010-0000-1111', + requestNote: null, subtotalPrice: 30000 * quantity, discountPrice: 5000 * quantity, totalPrice: 25000 * quantity, diff --git a/src/features/order/repositories/order.repository.ts b/src/features/order/repositories/order.repository.ts index 663c6d25..4a009248 100644 --- a/src/features/order/repositories/order.repository.ts +++ b/src/features/order/repositories/order.repository.ts @@ -152,9 +152,11 @@ export interface CreateSubmittedOrderArgs { accountId: bigint; orderNumber: string; idempotencyKey: string; + idempotencyInputHash: string; pickupAt: Date; buyerName: string; buyerPhone: string; + requestNote: string | null; subtotalPrice: number; discountPrice: number; totalPrice: number; @@ -190,6 +192,7 @@ export interface CreatedOrderRow { buyer_name: string; total_price: number; updated_at: Date; + idempotency_input_hash: string | null; } export interface ReviewableOrderItemRow { @@ -320,10 +323,12 @@ export class OrderRepository { account_id: args.accountId, order_number: args.orderNumber, idempotency_key: args.idempotencyKey, + idempotency_input_hash: args.idempotencyInputHash, status: OrderStatus.SUBMITTED, pickup_at: args.pickupAt, buyer_name: args.buyerName, buyer_phone: args.buyerPhone, + request_note: args.requestNote, subtotal_price: args.subtotalPrice, discount_price: args.discountPrice, total_price: args.totalPrice, @@ -370,6 +375,7 @@ export class OrderRepository { buyer_name: true, total_price: true, updated_at: true, + idempotency_input_hash: true, }, }); // 접수 이벤트(outbox, 같은 tx) — 판매자 푸시 원천. 구매자 알림은 없다(notification 소비자는 구독하지 않는다). @@ -407,6 +413,7 @@ export class OrderRepository { buyer_name: true, total_price: true, updated_at: true, + idempotency_input_hash: true, }, }); } diff --git a/src/features/order/resolvers/order-checkout-mutation.resolver.spec.ts b/src/features/order/resolvers/order-checkout-mutation.resolver.spec.ts index 1862e869..10e4ff4b 100644 --- a/src/features/order/resolvers/order-checkout-mutation.resolver.spec.ts +++ b/src/features/order/resolvers/order-checkout-mutation.resolver.spec.ts @@ -105,6 +105,8 @@ describe('OrderCheckout Mutation Resolver (real DB)', () => { productId: product.id.toString(), optionItemIds: [], pickupAt: new Date('2026-09-18T05:00:00.000Z'), // 9/18(금) 14:00 KST + expectedTotalPrice: 20000, + requestNote: '초는 빼 주세요', }); expect(result.status).toBe('SUBMITTED'); @@ -113,5 +115,6 @@ describe('OrderCheckout Mutation Resolver (real DB)', () => { where: { id: BigInt(result.orderId) }, }); expect(saved.account_id).toBe(account.id); + expect(saved.request_note).toBe('초는 빼 주세요'); }); }); diff --git a/src/features/order/services/order-admin-mappers.helper.ts b/src/features/order/services/order-admin-mappers.helper.ts index b1f937b7..cba192b8 100644 --- a/src/features/order/services/order-admin-mappers.helper.ts +++ b/src/features/order/services/order-admin-mappers.helper.ts @@ -51,6 +51,7 @@ export function toAdminOrderDetailOutput( pickupAt: row.pickup_at, buyerName: row.buyer_name, buyerPhone: row.buyer_phone, + requestNote: row.request_note, subtotalPrice: row.subtotal_price, discountPrice: row.discount_price, totalPrice: row.total_price, diff --git a/src/features/order/services/order-admin.service.spec.ts b/src/features/order/services/order-admin.service.spec.ts index 526fb519..b2c9e054 100644 --- a/src/features/order/services/order-admin.service.spec.ts +++ b/src/features/order/services/order-admin.service.spec.ts @@ -368,10 +368,15 @@ describe('AdminOrderService (real DB)', () => { actor_type: 'BUYER', }, }); + await prisma.order.update({ + where: { id: order.id }, + data: { request_note: '초는 빼 주세요' }, + }); const result = await service.adminOrder(await admin(), order.id); expect(result.id).toBe(order.id.toString()); + expect(result.requestNote).toBe('초는 빼 주세요'); expect(result.buyer).toEqual({ accountId: buyer.id.toString(), email: buyer.email, diff --git a/src/features/order/services/order-checkout.service.spec.ts b/src/features/order/services/order-checkout.service.spec.ts index d7ee7307..48ee471f 100644 --- a/src/features/order/services/order-checkout.service.spec.ts +++ b/src/features/order/services/order-checkout.service.spec.ts @@ -48,6 +48,7 @@ const VALID_PICKUP_AT = new Date('2026-09-18T05:00:00.000Z'); describe('OrderCheckoutService (real DB)', () => { let service: OrderCheckoutService; let orderRepo: OrderRepository; + let pickupSchedule: StorePickupScheduleService; let clock: ClockService; let random: RandomService; let pubSub: PubSub; @@ -74,6 +75,7 @@ describe('OrderCheckoutService (real DB)', () => { }); service = module.get(OrderCheckoutService); orderRepo = module.get(OrderRepository); + pickupSchedule = module.get(StorePickupScheduleService); clock = module.get(ClockService); random = module.get(RandomService); pubSub = module.get(PUB_SUB); @@ -185,7 +187,8 @@ describe('OrderCheckoutService (real DB)', () => { } // 호출마다 새 키 — 한 케이스에서 createOrder를 여러 번 부를 때 의도치 않은 - // 멱등 replay로 두 번째 생성이 생략되는 것을 막는다 + // 멱등 replay로 두 번째 생성이 생략되는 것을 막는다. + // 기대 금액 기본값은 factory 기본 상품(정가 10000·판매가 없음·옵션 없음) 기준이다. let idemSeq = 0; function baseInput(overrides: Partial): CreateOrderInput { idemSeq += 1; @@ -194,6 +197,7 @@ describe('OrderCheckoutService (real DB)', () => { productId: '0', optionItemIds: [], pickupAt: VALID_PICKUP_AT, + expectedTotalPrice: 10_000 * (overrides.quantity ?? 1), ...overrides, }; } @@ -227,6 +231,7 @@ describe('OrderCheckoutService (real DB)', () => { quantity: 2, buyerName: '차차', buyerPhone: '010-0000-1111', + expectedTotalPrice: 56000, }), ); @@ -285,7 +290,10 @@ describe('OrderCheckoutService (real DB)', () => { const result = await service.createOrder( buyer.id, - baseInput({ productId: product.id.toString() }), + baseInput({ + productId: product.id.toString(), + expectedTotalPrice: 20000, + }), ); expect(result.totalPrice).toBe(20000); @@ -836,34 +844,6 @@ describe('OrderCheckoutService (real DB)', () => { expect(await prisma.order.count()).toBe(1); }); - it('같은 키면 입력이 달라도 기존 주문을 반환한다(입력 비교 없음)', async () => { - const store = await makeOpenStore(); - const product = await createProduct(prisma, { store_id: store.id }); - const buyer = await makeBuyer(); - - const first = await service.createOrder( - buyer.id, - baseInput({ - idempotencyKey: 'fixed-idem-key-02', - productId: product.id.toString(), - quantity: 1, - }), - ); - const replayed = await service.createOrder( - buyer.id, - baseInput({ - idempotencyKey: 'fixed-idem-key-02', - productId: product.id.toString(), - quantity: 3, - }), - ); - - // 수량 3의 새 주문이 아니라 수량 1로 만든 기존 주문의 결과가 그대로 온다 - expect(replayed.orderId).toBe(first.orderId); - expect(replayed.totalPrice).toBe(first.totalPrice); - expect(await prisma.order.count()).toBe(1); - }); - it('다른 계정의 같은 키는 서로 간섭하지 않는다', async () => { const store = await makeOpenStore(); const product = await createProduct(prisma, { store_id: store.id }); @@ -1023,6 +1003,246 @@ describe('OrderCheckoutService (real DB)', () => { }); }); + describe('createOrder — 기대 금액·요청 사항', () => { + it.each([-1, 1])( + '기대 금액이 서버 계산과 %i원 다르면 ORDER_PRICE_CHANGED이고 키를 소모하지 않는다', + async (diff) => { + const store = await makeOpenStore(); + const product = await createProduct(prisma, { store_id: store.id }); + const buyer = await makeBuyer(); + const input = baseInput({ + productId: product.id.toString(), + expectedTotalPrice: 10_000 + diff, + }); + + await expect( + service.createOrder(buyer.id, input), + ).rejects.toThrowDomain('ORDER_PRICE_CHANGED'); + expect(await prisma.order.count()).toBe(0); + + const ok = await service.createOrder(buyer.id, { + ...input, + expectedTotalPrice: 10_000, + }); + expect(ok.totalPrice).toBe(10_000); + }, + ); + + it.each<[string, string | undefined, string | null]>([ + ['앞뒤 공백은 지운다', ' 초는 빼 주세요 ', '초는 빼 주세요'], + ['공백만 보내면 없음', ' ', null], + ['안 보내면 없음', undefined, null], + ])('요청 사항을 저장한다 — %s', async (_case, requestNote, expected) => { + const store = await makeOpenStore(); + const product = await createProduct(prisma, { store_id: store.id }); + const buyer = await makeBuyer(); + + const result = await service.createOrder( + buyer.id, + baseInput({ productId: product.id.toString(), requestNote }), + ); + + const saved = await prisma.order.findUniqueOrThrow({ + where: { id: BigInt(result.orderId) }, + }); + expect(saved.request_note).toBe(expected); + }); + }); + + describe('createOrder — 픽업 판정이 달력과 같다', () => { + // 9/17 10:00~19:30(30분 간격) 전 슬롯. 지금(9/16 16:00) + 제작 26시간 = 9/17 18:00이 + // 매장 리드타임(60분)보다 늦어 하한이 된다 + const DAY_SLOTS = Array.from({ length: 20 }, (_, index) => { + const minutes = 10 * 60 + index * 30; + const time = `${String(Math.floor(minutes / 60)).padStart(2, '0')}:${String(minutes % 60).padStart(2, '0')}`; + return [time, minutes >= 18 * 60] as const; + }); + + it.each(DAY_SLOTS)( + '%s 슬롯: available=%s ⇔ createOrder 성공', + async (time, expectedAvailable) => { + const store = await makeOpenStore(); + const product = await createProduct(prisma, { + store_id: store.id, + preparation_time_minutes: 26 * 60, + }); + const buyer = await makeBuyer(); + + const slots = await pickupSchedule.pickupTimeSlots( + store.id, + '2026-09-17', + product.id, + ); + const daySlots = [...slots.morning, ...slots.afternoon]; + expect(daySlots).toHaveLength(DAY_SLOTS.length); + const slot = daySlots.find((candidate) => candidate.time === time); + expect(slot?.available).toBe(expectedAvailable); + + const attempt = service.createOrder( + buyer.id, + baseInput({ + productId: product.id.toString(), + pickupAt: new Date(`2026-09-17T${time}:00+09:00`), + }), + ); + if (slot?.available) { + await expect(attempt).resolves.toMatchObject({ status: 'SUBMITTED' }); + } else { + await expect(attempt).rejects.toThrowDomain('PICKUP_NOT_AVAILABLE'); + } + }, + ); + }); + + describe('createOrder — 멱등 입력 해시', () => { + async function setup() { + const store = await makeOpenStore(); + const product = await createProduct(prisma, { store_id: store.id }); + const buyer = await makeBuyer(); + return { store, product, buyer }; + } + + it('같은 키·같은 입력이면 기존 주문을 돌려주고 해시를 저장해 둔다', async () => { + const { product, buyer } = await setup(); + const input = baseInput({ + idempotencyKey: 'hash-same-key', + productId: product.id.toString(), + requestNote: '메모', + }); + + const first = await service.createOrder(buyer.id, input); + const replayed = await service.createOrder(buyer.id, { ...input }); + + expect(replayed).toEqual(first); + expect(await prisma.order.count()).toBe(1); + const saved = await prisma.order.findUniqueOrThrow({ + where: { id: BigInt(first.orderId) }, + }); + expect(saved.idempotency_input_hash).toMatch(/^[0-9a-f]{64}$/); + }); + + it.each<[string, Partial]>([ + ['수량', { quantity: 2, expectedTotalPrice: 20_000 }], + ['픽업 일시', { pickupAt: new Date('2026-09-18T05:30:00.000Z') }], + ['주문자 이름', { buyerName: '다른 이름' }], + ['주문자 연락처', { buyerPhone: '010-9999-9999' }], + ['요청 사항', { requestNote: '다른 메모' }], + ['기대 금액', { expectedTotalPrice: 9_999 }], + ])( + '같은 키로 %s만 달라도 IDEMPOTENCY_KEY_INPUT_MISMATCH다', + async (_field, change) => { + const { product, buyer } = await setup(); + const input = baseInput({ + idempotencyKey: 'hash-mismatch-key', + productId: product.id.toString(), + }); + await service.createOrder(buyer.id, input); + + await expect( + service.createOrder(buyer.id, { ...input, ...change }), + ).rejects.toThrowDomain('IDEMPOTENCY_KEY_INPUT_MISMATCH'); + expect(await prisma.order.count()).toBe(1); + }, + ); + + it('해시가 없는 기존 주문(도입 전)은 입력이 달라도 비교 없이 돌려준다', async () => { + const { product, buyer } = await setup(); + const legacy = await createOrderRow(prisma, { + account_id: buyer.id, + idempotency_key: 'legacy-hashless-key', + }); + + const replayed = await service.createOrder( + buyer.id, + baseInput({ + idempotencyKey: 'legacy-hashless-key', + productId: product.id.toString(), + quantity: 5, + }), + ); + + expect(replayed.orderId).toBe(legacy.id.toString()); + expect(await prisma.order.count()).toBe(1); + }); + + it('quantity를 생략하면 1을 보낸 것과 같은 입력이다', async () => { + const { product, buyer } = await setup(); + const input = baseInput({ + idempotencyKey: 'hash-quantity-key', + productId: product.id.toString(), + }); + + const first = await service.createOrder(buyer.id, { + ...input, + quantity: 1, + }); + expect(input.quantity).toBeUndefined(); + await expect(service.createOrder(buyer.id, input)).resolves.toEqual( + first, + ); + }); + + it.each([ + ['tx 밖 사전 검사', false], + ['tx 안 잠금 재검사', true], + ])( + 'capacity 거절 뒤 replay도 입력을 비교한다 — %s', + async (_path, bypassPrecheck) => { + const { store, product, buyer } = await setup(); + await createStoreDailyCapacity(prisma, { + store_id: store.id, + capacity_date: new Date(Date.UTC(2026, 8, 18)), + capacity: 1, + }); + const input = baseInput({ + idempotencyKey: 'capacity-hash-key', + productId: product.id.toString(), + }); + const first = await service.createOrder(buyer.id, input); + + const raceOnce = () => { + jest + .spyOn(orderRepo, 'findOrderByIdempotencyKey') + .mockResolvedValueOnce(null); + if (bypassPrecheck) { + jest + .spyOn(orderRepo, 'isDailyCapacityExceeded') + .mockResolvedValueOnce(false); + } + }; + raceOnce(); + await expect( + service.createOrder(buyer.id, { ...input, requestNote: '다른 메모' }), + ).rejects.toThrowDomain('IDEMPOTENCY_KEY_INPUT_MISMATCH'); + raceOnce(); + await expect(service.createOrder(buyer.id, input)).resolves.toEqual( + first, + ); + expect(await prisma.order.count()).toBe(1); + }, + ); + + it('멱등 키 unique 경합(P2002) 뒤 replay도 입력을 비교한다', async () => { + const { product, buyer } = await setup(); + const input = baseInput({ + idempotencyKey: 'p2002-hash-key', + productId: product.id.toString(), + }); + await service.createOrder(buyer.id, input); + + // 사전 조회를 놓친 동시 제출 — INSERT가 키 unique에 걸린 뒤 기존 주문을 다시 읽는다 + jest + .spyOn(orderRepo, 'findOrderByIdempotencyKey') + .mockResolvedValueOnce(null); + const insert = jest.spyOn(orderRepo, 'createSubmittedOrder'); + await expect( + service.createOrder(buyer.id, { ...input, requestNote: '다른 메모' }), + ).rejects.toThrowDomain('IDEMPOTENCY_KEY_INPUT_MISMATCH'); + expect(insert).toHaveBeenCalledTimes(1); + expect(await prisma.order.count()).toBe(1); + }); + }); + describe('createOrder — 접수 이벤트(order.submitted)', () => { async function submittedEvents() { return prisma.outbox.findMany({ @@ -1042,6 +1262,7 @@ describe('OrderCheckoutService (real DB)', () => { productId: product.id.toString(), optionItemIds: [sizeSmallId.toString()], quantity: 2, + expectedTotalPrice: 54000, }), ); diff --git a/src/features/order/services/order-checkout.service.ts b/src/features/order/services/order-checkout.service.ts index 7e2fac25..d22b6512 100644 --- a/src/features/order/services/order-checkout.service.ts +++ b/src/features/order/services/order-checkout.service.ts @@ -12,6 +12,7 @@ import type { CreateOrderInput } from '@/features/order/dto/inputs/create-order. import { OrderRepository } from '@/features/order/repositories/order.repository'; import { toSellerOrderUpdateEvent } from '@/features/order/services/order-events-mappers.helper'; import { OrderEventsService } from '@/features/order/services/order-events.service'; +import { hashCreateOrderInput } from '@/features/order/services/order-input-hash.helper'; import type { CreateOrderOutput } from '@/features/order/types/create-order-output.type'; import { ProductRepository, type ProductDetailRow } from '@/features/product'; import { StorePickupScheduleService } from '@/features/store'; @@ -54,6 +55,11 @@ export class OrderCheckoutService { const productId = parseId(input.productId); const optionItemIds = input.optionItemIds.map((id) => parseId(id)); const quantity = input.quantity ?? 1; + const inputHash = hashCreateOrderInput({ + ...input, + productId, + optionItemIds, + }); // 멱등 replay: 같은 (계정, 키)의 주문이 있으면 검증·생성 없이 그 결과를 반환한다 — 원 요청 시점의 검증을 이미 통과한 주문이다. const replayed = await this.orderRepo.findOrderByIdempotencyKey( @@ -61,6 +67,7 @@ export class OrderCheckoutService { input.idempotencyKey, ); if (replayed) { + assertReplayInputMatches(replayed, inputHash); return this.toCreateOrderOutput(replayed); } @@ -79,19 +86,16 @@ export class OrderCheckoutService { const buyer = this.resolveBuyerInfo(buyerProfile, input); const now = this.clock.now(); - // 상품별 제작 소요시간은 매장 리드타임과 별개 조건 — 둘 다 충족해야 한다 - const preparationDeadlineMs = - now.getTime() + product.preparation_time_minutes * 60_000; - // 영업일·슬롯 정합은 catalog가, 주문 수량까지 더한 capacity 잔여는 order 복제본이 판정한다 + // 영업일·슬롯·하한(리드타임과 제작 시간 중 긴 쪽)은 달력과 같은 catalog 판정, 주문 수량까지 더한 capacity 잔여는 order 복제본이 판정한다 const capacityGuard = this.buildCapacityGuard( product.store_id, input.pickupAt, ); const pickupAvailable = - input.pickupAt.getTime() >= preparationDeadlineMs && (await this.pickupSchedule.isPickupSlotAvailable({ storeId: product.store_id, pickupAt: input.pickupAt, + preparationTimeMinutes: product.preparation_time_minutes, })) && !(await this.orderRepo.isDailyCapacityExceeded(capacityGuard, quantity)); if (!pickupAvailable) { @@ -100,6 +104,7 @@ export class OrderCheckoutService { const raced = await this.replayAfterCapacityReject( accountId, input.idempotencyKey, + inputHash, ); return this.toCreateOrderOutput(raced); } @@ -125,14 +130,20 @@ export class OrderCheckoutService { throw new DomainException('ORDER_AMOUNT_OUT_OF_RANGE'); } } + // 구매자가 본 금액과 다르면 바뀐 가격으로 주문을 만들지 않는다 + if (itemSubtotalPrice !== input.expectedTotalPrice) { + throw new DomainException('ORDER_PRICE_CHANGED'); + } const submittedAt = now; const created = await this.createWithOrderNumberRetry({ accountId, idempotencyKey: input.idempotencyKey, + idempotencyInputHash: inputHash, pickupAt: input.pickupAt, buyerName: buyer.name, buyerPhone: buyer.phone, + requestNote: input.requestNote?.trim() || null, subtotalPrice, discountPrice, totalPrice: itemSubtotalPrice, @@ -287,6 +298,7 @@ export class OrderCheckoutService { return this.replayAfterCapacityReject( args.accountId, args.idempotencyKey, + args.idempotencyInputHash, ); } // 커밋된 새 주문만 발행한다 — replay(멱등 키·capacity·P2002)는 이미 발행된 주문이다 @@ -305,7 +317,10 @@ export class OrderCheckoutService { args.accountId, args.idempotencyKey, ); - if (existing) return existing; + if (existing) { + assertReplayInputMatches(existing, args.idempotencyInputHash); + return existing; + } // 활성 주문이 없는데 키 unique가 충돌했다면 soft-delete된 주문이 키를 점유한 경우다 — MySQL unique는 // deleted_at을 보지 않는다. 같은 키로는 몇 번을 재시도해도 동일하게 실패하므로 새 주문서(새 키)로 유도한다. const heldByDeleted = @@ -335,13 +350,15 @@ export class OrderCheckoutService { private async replayAfterCapacityReject( accountId: bigint, idempotencyKey: string, + inputHash: string, ) { const existing = await this.orderRepo.findOrderByIdempotencyKey( accountId, idempotencyKey, ); - if (existing) return existing; - throw new DomainException('PICKUP_NOT_AVAILABLE'); + if (!existing) throw new DomainException('PICKUP_NOT_AVAILABLE'); + assertReplayInputMatches(existing, inputHash); + return existing; } /** 그 외 P2002(주문번호 등)는 재시도 대상이라 구분한다. */ @@ -362,3 +379,16 @@ export class OrderCheckoutService { return `ORD-${datePart}-${randomPart}`; } } + +/** 해시 도입 전 주문(null)은 비교하지 않는다. */ +function assertReplayInputMatches( + existing: { idempotency_input_hash: string | null }, + inputHash: string, +): void { + if ( + existing.idempotency_input_hash !== null && + existing.idempotency_input_hash !== inputHash + ) { + throw new DomainException('IDEMPOTENCY_KEY_INPUT_MISMATCH'); + } +} diff --git a/src/features/order/services/order-input-hash.helper.spec.ts b/src/features/order/services/order-input-hash.helper.spec.ts new file mode 100644 index 00000000..15277124 --- /dev/null +++ b/src/features/order/services/order-input-hash.helper.spec.ts @@ -0,0 +1,81 @@ +import { sha256Hex } from '@/common/utils/crypto'; +import { + hashCreateOrderInput, + type CreateOrderHashInput, +} from '@/features/order/services/order-input-hash.helper'; + +const BASE: CreateOrderHashInput = { + productId: 1n, + optionItemIds: [10n, 11n], + pickupAt: new Date('2026-09-18T05:00:00.000Z'), + quantity: 2, + buyerName: '차차', + buyerPhone: '010-0000-1111', + requestNote: '메모', + expectedTotalPrice: 56000, +}; + +function hashWith(change: Partial): string { + return hashCreateOrderInput({ ...BASE, ...change }); +} + +describe('hashCreateOrderInput', () => { + it('주문에 저장되는 값이라 정규화 형식을 고정한다(키 정렬·문자열 ID·ISO 시각)', () => { + expect(hashCreateOrderInput(BASE)).toBe( + sha256Hex( + '{"buyerName":"차차","buyerPhone":"010-0000-1111","expectedTotalPrice":56000,' + + '"optionItemIds":["10","11"],"pickupAt":"2026-09-18T05:00:00.000Z",' + + '"productId":"1","quantity":2,"requestNote":"메모"}', + ), + ); + }); + + it.each<[string, Partial]>([ + ['옵션 순서', { optionItemIds: [11n, 10n] }], + [ + '같은 시각의 다른 표기', + { pickupAt: new Date('2026-09-18T14:00:00+09:00') }, + ], + ])('%s만 다르면 같은 해시다', (_case, change) => { + expect(hashWith(change)).toBe(hashCreateOrderInput(BASE)); + }); + + it('quantity 생략·null은 1과 같다', () => { + const one = hashWith({ quantity: 1 }); + expect(hashWith({ quantity: undefined })).toBe(one); + expect(hashWith({ quantity: null })).toBe(one); + }); + + it('선택 입력의 생략과 null은 같다', () => { + const omitted = hashWith({ + buyerName: undefined, + buyerPhone: undefined, + requestNote: undefined, + }); + expect( + hashWith({ buyerName: null, buyerPhone: null, requestNote: null }), + ).toBe(omitted); + }); + + it.each<[keyof CreateOrderHashInput, Partial]>([ + ['productId', { productId: 2n }], + ['optionItemIds', { optionItemIds: [10n] }], + ['pickupAt', { pickupAt: new Date('2026-09-18T05:30:00.000Z') }], + ['quantity', { quantity: 3 }], + ['buyerName', { buyerName: '다른 이름' }], + ['buyerPhone', { buyerPhone: '010-9999-9999' }], + ['requestNote', { requestNote: '다른 메모' }], + ['expectedTotalPrice', { expectedTotalPrice: 56001 }], + ])('%s가 다르면 해시가 다르다', (_field, change) => { + expect(hashWith(change)).not.toBe(hashCreateOrderInput(BASE)); + }); + + it('값 안의 따옴표가 다음 필드를 흉내 내도 다른 입력으로 본다', () => { + expect( + hashWith({ + buyerName: '차차","buyerPhone":"010-0000-1111', + buyerPhone: null, + }), + ).not.toBe(hashWith({ buyerName: '차차', buyerPhone: '010-0000-1111' })); + }); +}); diff --git a/src/features/order/services/order-input-hash.helper.ts b/src/features/order/services/order-input-hash.helper.ts new file mode 100644 index 00000000..5d8cefcf --- /dev/null +++ b/src/features/order/services/order-input-hash.helper.ts @@ -0,0 +1,43 @@ +import { sha256Hex } from '@/common/utils/crypto'; + +export interface CreateOrderHashInput { + productId: bigint; + optionItemIds: bigint[]; + pickupAt: Date; + quantity?: number | null; + buyerName?: string | null; + buyerPhone?: string | null; + requestNote?: string | null; + expectedTotalPrice: number; +} + +/** 같은 멱등 키의 재요청이 같은 주문서인지 가린다. 옵션 순서·quantity 생략(= 1)·null 키에 흔들리지 않게 정규화한다. */ +export function hashCreateOrderInput(input: CreateOrderHashInput): string { + return sha256Hex( + canonicalJson({ + productId: input.productId.toString(), + optionItemIds: input.optionItemIds.map(String).sort(), + pickupAt: input.pickupAt.toISOString(), + quantity: input.quantity ?? 1, + buyerName: input.buyerName, + buyerPhone: input.buyerPhone, + requestNote: input.requestNote, + expectedTotalPrice: input.expectedTotalPrice, + }), + ); +} + +/** 객체 키를 정렬하고 null·undefined 키를 뺀 JSON. 배열은 순서가 의미라 그대로 둔다. */ +function canonicalJson(value: unknown): string { + if (Array.isArray(value)) { + return `[${value.map(canonicalJson).join(',')}]`; + } + if (value !== null && typeof value === 'object') { + const fields = Object.entries(value) + .filter(([, field]) => field !== null && field !== undefined) + .sort(([a], [b]) => (a < b ? -1 : 1)) + .map(([key, field]) => `${JSON.stringify(key)}:${canonicalJson(field)}`); + return `{${fields.join(',')}}`; + } + return JSON.stringify(value); +} diff --git a/src/features/order/services/order-my.service.spec.ts b/src/features/order/services/order-my.service.spec.ts index 3f95be44..8d73931b 100644 --- a/src/features/order/services/order-my.service.spec.ts +++ b/src/features/order/services/order-my.service.spec.ts @@ -386,10 +386,15 @@ describe('UserOrderService (real DB)', () => { regular_price_snapshot: 30000, sale_price_snapshot: 25000, }); + await prisma.order.update({ + where: { id: order.id }, + data: { request_note: '초는 빼 주세요' }, + }); const result = await service.getMyOrder(account.id, order.id); expect(result.orderId).toBe(order.id.toString()); + expect(result.requestNote).toBe('초는 빼 주세요'); expect(result.items).toHaveLength(1); expect(result.items[0]).toMatchObject({ item: { diff --git a/src/features/order/services/order-my.service.ts b/src/features/order/services/order-my.service.ts index bcb34591..2ee8d5df 100644 --- a/src/features/order/services/order-my.service.ts +++ b/src/features/order/services/order-my.service.ts @@ -104,6 +104,7 @@ export class UserOrderService { pickupAt: order.pickup_at, buyerName: order.buyer_name, buyerPhone: order.buyer_phone, + requestNote: order.request_note, subtotalPrice: order.subtotal_price, discountPrice: order.discount_price, totalPrice: order.total_price, diff --git a/src/features/order/services/order-seller.service.spec.ts b/src/features/order/services/order-seller.service.spec.ts index 98f42534..863be011 100644 --- a/src/features/order/services/order-seller.service.spec.ts +++ b/src/features/order/services/order-seller.service.spec.ts @@ -327,10 +327,15 @@ describe('SellerOrderService (real DB)', () => { note: '접수 확정', }, }); + await prisma.order.update({ + where: { id: order.id }, + data: { request_note: '초는 빼 주세요' }, + }); const result = await service.sellerOrder(account.id, order.id); expect(result.id).toBe(order.id.toString()); expect(result.status).toBe('CONFIRMED'); + expect(result.requestNote).toBe('초는 빼 주세요'); expect(result.items).toHaveLength(1); expect(result.statusHistories).toHaveLength(1); expect(result.statusHistories[0].toStatus).toBe('CONFIRMED'); diff --git a/src/features/order/services/order-seller.service.ts b/src/features/order/services/order-seller.service.ts index d4b0f597..a558e2d5 100644 --- a/src/features/order/services/order-seller.service.ts +++ b/src/features/order/services/order-seller.service.ts @@ -171,6 +171,7 @@ export class SellerOrderService extends SellerBaseService { pickup_at: Date; buyer_name: string; buyer_phone: string; + request_note: string | null; subtotal_price: number; discount_price: number; total_price: number; @@ -192,6 +193,7 @@ export class SellerOrderService extends SellerBaseService { pickupAt: row.pickup_at, buyerName: row.buyer_name, buyerPhone: row.buyer_phone, + requestNote: row.request_note, subtotalPrice: row.subtotal_price, discountPrice: row.discount_price, totalPrice: row.total_price, diff --git a/src/features/order/types/order-admin-output.type.ts b/src/features/order/types/order-admin-output.type.ts index 6cb07d00..7527ade4 100644 --- a/src/features/order/types/order-admin-output.type.ts +++ b/src/features/order/types/order-admin-output.type.ts @@ -39,6 +39,7 @@ export interface AdminOrderDetailOutput { pickupAt: Date; buyerName: string; buyerPhone: string; + requestNote: string | null; subtotalPrice: number; discountPrice: number; totalPrice: number; diff --git a/src/features/order/types/order-my-output.type.ts b/src/features/order/types/order-my-output.type.ts index 10df934b..819da811 100644 --- a/src/features/order/types/order-my-output.type.ts +++ b/src/features/order/types/order-my-output.type.ts @@ -52,6 +52,7 @@ export interface MyOrderDetail { pickupAt: Date; buyerName: string; buyerPhone: string; + requestNote: string | null; subtotalPrice: number; discountPrice: number; totalPrice: number; diff --git a/src/features/order/types/order-seller-output.type.ts b/src/features/order/types/order-seller-output.type.ts index 9cc8a201..b10dd95c 100644 --- a/src/features/order/types/order-seller-output.type.ts +++ b/src/features/order/types/order-seller-output.type.ts @@ -25,6 +25,7 @@ export interface SellerOrderDetailOutput { pickupAt: Date; buyerName: string; buyerPhone: string; + requestNote: string | null; subtotalPrice: number; discountPrice: number; totalPrice: number; diff --git a/src/features/store/index.ts b/src/features/store/index.ts index 72ab79f6..bc8e6213 100644 --- a/src/features/store/index.ts +++ b/src/features/store/index.ts @@ -8,6 +8,8 @@ export { // 매장 픽업 가능 판정. 주문 생성(order feature)이 픽업 일시 재검증에 사용한다 — // 판정 규칙은 store feature에 유지한다(달력·슬롯 조회와 단일 소스). export { StorePickupScheduleService } from '@/features/store/services/store-pickup-schedule.service'; +// 픽업 하한(매장 리드타임과 상품 제작 시간 중 긴 쪽). 달력·슬롯·주문 생성이 같은 규칙을 쓴다. +export { effectiveLeadTimeMinutes } from '@/features/store/services/store-pickup-policy.helper'; export { scoreAndSortByPopularity } from '@/features/store/services/store-ranking.helper'; // 검색 요약(search feature)의 매장 건수. 검색 조건은 store feature의 where 빌더가 단일 소스. export { StoreSearchService } from '@/features/store/services/store-search.service'; diff --git a/src/features/store/repositories/store.repository.ts b/src/features/store/repositories/store.repository.ts index 1dd14f0d..3887a336 100644 --- a/src/features/store/repositories/store.repository.ts +++ b/src/features/store/repositories/store.repository.ts @@ -191,6 +191,18 @@ export class StoreRepository { }); } + /** 그 매장의 판매 중 상품만 찾는다. 다른 매장 상품이거나 판매 중이 아니면 null. */ + async findProductPreparationTimeMinutes( + storeId: bigint, + productId: bigint, + ): Promise { + const product = await this.prisma.product.findFirst({ + where: { id: productId, store_id: storeId, ...visibleWhere }, + select: { preparation_time_minutes: true }, + }); + return product?.preparation_time_minutes ?? null; + } + async findBusinessHoursForStore( storeId: bigint, ): Promise { diff --git a/src/features/store/resolvers/store-pickup-schedule-query.resolver.spec.ts b/src/features/store/resolvers/store-pickup-schedule-query.resolver.spec.ts index 51615cca..01873d51 100644 --- a/src/features/store/resolvers/store-pickup-schedule-query.resolver.spec.ts +++ b/src/features/store/resolvers/store-pickup-schedule-query.resolver.spec.ts @@ -6,7 +6,7 @@ import type { PrismaClient } from '@/generated/prisma/client'; import { bookedQuantityProviders } from '@/test/booked-quantity'; import { disconnectTestPrismaClient } from '@/test/db/prisma-test-client'; import { closeTruncateConnection, truncateAll } from '@/test/db/truncate'; -import { createStore } from '@/test/factories'; +import { createProduct, createStore } from '@/test/factories'; import { createTestingModuleWithRealDb } from '@/test/modules/testing-module.builder'; // 2026-09-16(수) 16:00 KST 고정 @@ -93,4 +93,46 @@ describe('StorePickupSchedule Query Resolver (real DB)', () => { expect(result.afternoon[0]).toEqual({ time: '12:00', available: true }); expect(result.morning.length + result.afternoon.length).toBe(20); }); + + it('productId를 파싱해 제작 시간을 반영하고, 빈 문자열은 INVALID_ID·"0"은 버리지 않고 상품 조회에 쓴다', async () => { + const store = await createStore(prisma, { min_lead_time_minutes: 60 }); + await openAllWeek(store.id); + const product = await createProduct(prisma, { + store_id: store.id, + preparation_time_minutes: 26 * 60, + }); + + const slots = await resolver.pickupTimeSlots( + store.id.toString(), + '2026-09-17', + product.id.toString(), + ); + expect(slots.afternoon.find((s) => s.time === '17:30')?.available).toBe( + false, + ); + expect(slots.afternoon.find((s) => s.time === '18:00')?.available).toBe( + true, + ); + const calendar = await resolver.pickupCalendar( + store.id.toString(), + '2026-09', + null, + ); + expect(calendar.days.find((d) => d.date === '2026-09-17')?.selectable).toBe( + true, + ); + + expect(() => + resolver.pickupCalendar(store.id.toString(), '2026-09', ''), + ).toThrowDomain('INVALID_ID'); + expect(() => + resolver.pickupTimeSlots(store.id.toString(), '2026-09-17', ''), + ).toThrowDomain('INVALID_ID'); + await expect( + resolver.pickupCalendar(store.id.toString(), '2026-09', '0'), + ).rejects.toThrowDomain('PRODUCT_NOT_FOUND'); + await expect( + resolver.pickupTimeSlots(store.id.toString(), '2026-09-17', '0'), + ).rejects.toThrowDomain('PRODUCT_NOT_FOUND'); + }); }); diff --git a/src/features/store/resolvers/store-pickup-schedule-query.resolver.ts b/src/features/store/resolvers/store-pickup-schedule-query.resolver.ts index dae5c31b..8f9a08c4 100644 --- a/src/features/store/resolvers/store-pickup-schedule-query.resolver.ts +++ b/src/features/store/resolvers/store-pickup-schedule-query.resolver.ts @@ -1,6 +1,6 @@ import { Args, Query, Resolver } from '@nestjs/graphql'; -import { parseId } from '@/common/utils/id-parser'; +import { parseId, parseOptionalId } from '@/common/utils/id-parser'; import { StorePickupScheduleService } from '@/features/store/services/store-pickup-schedule.service'; import type { PickupCalendar, @@ -15,15 +15,25 @@ export class StorePickupScheduleQueryResolver { pickupCalendar( @Args('storeId') storeId: string, @Args('yearMonth') yearMonth: string, + @Args('productId') productId?: string | null, ): Promise { - return this.service.pickupCalendar(parseId(storeId), yearMonth); + return this.service.pickupCalendar( + parseId(storeId), + yearMonth, + parseOptionalId(productId), + ); } @Query('pickupTimeSlots') pickupTimeSlots( @Args('storeId') storeId: string, @Args('date') date: string, + @Args('productId') productId?: string | null, ): Promise { - return this.service.pickupTimeSlots(parseId(storeId), date); + return this.service.pickupTimeSlots( + parseId(storeId), + date, + parseOptionalId(productId), + ); } } diff --git a/src/features/store/services/store-pickup-policy.helper.spec.ts b/src/features/store/services/store-pickup-policy.helper.spec.ts index f4a6a95b..1512169f 100644 --- a/src/features/store/services/store-pickup-policy.helper.spec.ts +++ b/src/features/store/services/store-pickup-policy.helper.spec.ts @@ -2,6 +2,7 @@ import { kstMidnightUtc } from '@/common/utils/kst-time'; import { buildPickupDaySlots, buildTodaySlots, + effectiveLeadTimeMinutes, evaluatePickupDay, timeColumnToMinutes, type PickupDayInput, @@ -233,4 +234,19 @@ describe('store-pickup-policy.helper', () => { expect(timeColumnToMinutes(new Date('1970-01-01T00:00:00Z'))).toBe(0); }); }); + + describe('effectiveLeadTimeMinutes', () => { + it.each([ + [60, 0, 60], + [60, 59, 60], + [60, 60, 60], + [60, 61, 61], + [0, 26 * 60, 26 * 60], + ])( + '매장 리드타임 %i분·제작 시간 %i분이면 하한은 %i분이다', + (store, preparation, expected) => { + expect(effectiveLeadTimeMinutes(store, preparation)).toBe(expected); + }, + ); + }); }); diff --git a/src/features/store/services/store-pickup-policy.helper.ts b/src/features/store/services/store-pickup-policy.helper.ts index d8e46632..9b27a657 100644 --- a/src/features/store/services/store-pickup-policy.helper.ts +++ b/src/features/store/services/store-pickup-policy.helper.ts @@ -47,6 +47,14 @@ export interface PickupPolicyStore { max_days_ahead: number; } +/** 픽업 하한은 지금 + 이 값이다. 매장 리드타임과 상품 제작 시간 중 긴 쪽을 따른다. */ +export function effectiveLeadTimeMinutes( + storeLeadTimeMinutes: number, + preparationTimeMinutes: number, +): number { + return Math.max(storeLeadTimeMinutes, preparationTimeMinutes); +} + export interface PickupBusinessHour { is_closed: boolean; open_time: Date | null; diff --git a/src/features/store/services/store-pickup-schedule.service.spec.ts b/src/features/store/services/store-pickup-schedule.service.spec.ts index c53c7f86..b691f504 100644 --- a/src/features/store/services/store-pickup-schedule.service.spec.ts +++ b/src/features/store/services/store-pickup-schedule.service.spec.ts @@ -13,6 +13,7 @@ import { closeTruncateConnection, truncateAll } from '@/test/db/truncate'; import { createOrder, createOrderItem, + createProduct, createStore, createStoreDailyCapacity, } from '@/test/factories'; @@ -306,6 +307,41 @@ describe('StorePickupScheduleService (real DB)', () => { ).rejects.toThrowDomain(400); }); + it('productId를 주면 매장 리드타임과 상품 제작 시간 중 긴 쪽을 하한으로 쓴다', async () => { + // 리드 60분, 제작 3일 → 현재(9/16 16:00) 기준 9/19 16:00 이전은 마감 + const store = await createStore(prisma, { min_lead_time_minutes: 60 }); + await openAllWeek(store); + const slow = await createProduct(prisma, { + store_id: store.id, + preparation_time_minutes: 3 * 24 * 60, + }); + const quick = await createProduct(prisma, { + store_id: store.id, + preparation_time_minutes: 30, + }); + + const withSlow = await service.pickupCalendar( + store.id, + '2026-09', + slow.id, + ); + expect(dayOf(withSlow, '2026-09-18')).toMatchObject({ + selectable: false, + reason: 'CLOSED', + }); + expect(dayOf(withSlow, '2026-09-19').selectable).toBe(true); + + // 상품이 없거나 제작 시간이 리드타임보다 짧으면 매장 리드타임 그대로다 + for (const productId of [null, quick.id]) { + const calendar = await service.pickupCalendar( + store.id, + '2026-09', + productId, + ); + expect(dayOf(calendar, '2026-09-17').selectable).toBe(true); + } + }); + it('없거나 비활성 매장은 NOT_FOUND다', async () => { const inactive = await createStore(prisma, { is_active: false }); @@ -344,6 +380,40 @@ describe('StorePickupScheduleService (real DB)', () => { ]); }); + it('productId를 주면 상품 제작 시간 이전 슬롯을 마감한다', async () => { + // 리드 60분, 제작 26시간 → 현재(9/16 16:00) 기준 9/17 18:00부터 가능 + const store = await createStore(prisma, { min_lead_time_minutes: 60 }); + await openAllWeek(store, 16, 20); + const product = await createProduct(prisma, { + store_id: store.id, + preparation_time_minutes: 26 * 60, + }); + + const withProduct = await service.pickupTimeSlots( + store.id, + '2026-09-17', + product.id, + ); + const withoutProduct = await service.pickupTimeSlots( + store.id, + '2026-09-17', + ); + + expect(withProduct.afternoon).toEqual([ + { time: '16:00', available: false }, + { time: '16:30', available: false }, + { time: '17:00', available: false }, + { time: '17:30', available: false }, + { time: '18:00', available: true }, + { time: '18:30', available: true }, + { time: '19:00', available: true }, + { time: '19:30', available: true }, + ]); + expect(withoutProduct.afternoon.every((slot) => slot.available)).toBe( + true, + ); + }); + it('미래 날짜는 전 슬롯 가용이고 12:00 기준으로 오전/오후를 나눈다', async () => { const store = await createStore(prisma); await openAllWeek(store, 11, 13); @@ -457,6 +527,41 @@ describe('StorePickupScheduleService (real DB)', () => { }); }); + describe('productId 검증', () => { + it('그 매장의 판매 중 상품이 아니면 달력·슬롯 모두 PRODUCT_NOT_FOUND다', async () => { + const store = await createStore(prisma); + await openAllWeek(store); + const candidates = [ + await createProduct(prisma), // 다른 매장 상품 + await createProduct(prisma, { store_id: store.id, is_active: false }), + await createProduct(prisma, { + store_id: store.id, + deleted_at: new Date('2026-09-01T00:00:00.000Z'), + }), + ]; + + for (const product of candidates) { + await expect( + service.pickupCalendar(store.id, '2026-09', product.id), + ).rejects.toThrowDomain('PRODUCT_NOT_FOUND'); + await expect( + service.pickupTimeSlots(store.id, '2026-09-18', product.id), + ).rejects.toThrowDomain('PRODUCT_NOT_FOUND'); + } + await expect( + service.pickupCalendar(store.id, '2026-09', 999999n), + ).rejects.toThrowDomain('PRODUCT_NOT_FOUND'); + }); + + it('매장이 없으면 상품보다 매장을 먼저 거절한다', async () => { + const product = await createProduct(prisma); + + await expect( + service.pickupTimeSlots(999999n, '2026-09-18', product.id), + ).rejects.toThrowDomain('STORE_NOT_FOUND'); + }); + }); + describe('isPickupSlotAvailable', () => { /** 9/18(금) 14:00 KST — 전 요일 10~20시 영업 기준 유효 슬롯. */ const VALID_PICKUP_AT = new Date('2026-09-18T05:00:00.000Z'); @@ -469,6 +574,7 @@ describe('StorePickupScheduleService (real DB)', () => { service.isPickupSlotAvailable({ storeId: store.id, pickupAt: VALID_PICKUP_AT, + preparationTimeMinutes: 0, }), ).resolves.toBe(true); }); @@ -481,12 +587,14 @@ describe('StorePickupScheduleService (real DB)', () => { service.isPickupSlotAvailable({ storeId: store.id, pickupAt: new Date('2026-09-18T05:00:30.000Z'), + preparationTimeMinutes: 0, }), ).resolves.toBe(false); await expect( service.isPickupSlotAvailable({ storeId: store.id, pickupAt: new Date('2026-09-18T05:10:00.000Z'), + preparationTimeMinutes: 0, }), ).resolves.toBe(false); // 영업시간 밖(21:00 KST) @@ -494,6 +602,7 @@ describe('StorePickupScheduleService (real DB)', () => { service.isPickupSlotAvailable({ storeId: store.id, pickupAt: new Date('2026-09-18T12:00:00.000Z'), + preparationTimeMinutes: 0, }), ).resolves.toBe(false); }); @@ -513,6 +622,7 @@ describe('StorePickupScheduleService (real DB)', () => { service.isPickupSlotAvailable({ storeId: store.id, pickupAt: new Date('2026-09-16T07:30:00.000Z'), + preparationTimeMinutes: 0, }), ).resolves.toBe(false); // 오늘 17:00 KST — 리드타임 충족 @@ -520,6 +630,7 @@ describe('StorePickupScheduleService (real DB)', () => { service.isPickupSlotAvailable({ storeId: store.id, pickupAt: new Date('2026-09-16T08:00:00.000Z'), + preparationTimeMinutes: 0, }), ).resolves.toBe(true); // 휴무일(9/18) @@ -527,6 +638,7 @@ describe('StorePickupScheduleService (real DB)', () => { service.isPickupSlotAvailable({ storeId: store.id, pickupAt: VALID_PICKUP_AT, + preparationTimeMinutes: 0, }), ).resolves.toBe(false); }); @@ -543,6 +655,7 @@ describe('StorePickupScheduleService (real DB)', () => { service.isPickupSlotAvailable({ storeId: store.id, pickupAt: new Date('2026-09-18T05:00:00.000Z'), + preparationTimeMinutes: 0, }), ).resolves.toBe(false); // 9/19 14:00 — 여전히 미달, 9/19 16:00 — 충족 @@ -550,12 +663,14 @@ describe('StorePickupScheduleService (real DB)', () => { service.isPickupSlotAvailable({ storeId: store.id, pickupAt: new Date('2026-09-19T05:00:00.000Z'), + preparationTimeMinutes: 0, }), ).resolves.toBe(false); await expect( service.isPickupSlotAvailable({ storeId: store.id, pickupAt: new Date('2026-09-19T07:00:00.000Z'), + preparationTimeMinutes: 0, }), ).resolves.toBe(true); @@ -577,6 +692,26 @@ describe('StorePickupScheduleService (real DB)', () => { ).toBe(true); }); + it('제작 시간이 리드타임보다 길면 제작 시간을 하한으로 쓴다', async () => { + const store = await createStore(prisma, { min_lead_time_minutes: 60 }); + await openAllWeek(store); + const at = (iso: string, preparationTimeMinutes: number) => + service.isPickupSlotAvailable({ + storeId: store.id, + pickupAt: new Date(iso), + preparationTimeMinutes, + }); + + // 제작 26시간 → 9/17 18:00 KST부터 가능 + await expect(at('2026-09-17T08:30:00.000Z', 26 * 60)).resolves.toBe( + false, + ); + await expect(at('2026-09-17T09:00:00.000Z', 26 * 60)).resolves.toBe(true); + // 제작 30분은 리드 60분보다 짧아 오늘 16:30은 여전히 불가, 17:00은 가능 + await expect(at('2026-09-16T07:30:00.000Z', 30)).resolves.toBe(false); + await expect(at('2026-09-16T08:00:00.000Z', 30)).resolves.toBe(true); + }); + it('없거나 비활성 매장은 불가하다', async () => { const inactive = await createStore(prisma, { is_active: false }); await openAllWeek(inactive); @@ -585,12 +720,14 @@ describe('StorePickupScheduleService (real DB)', () => { service.isPickupSlotAvailable({ storeId: 999999n, pickupAt: VALID_PICKUP_AT, + preparationTimeMinutes: 0, }), ).resolves.toBe(false); await expect( service.isPickupSlotAvailable({ storeId: inactive.id, pickupAt: VALID_PICKUP_AT, + preparationTimeMinutes: 0, }), ).resolves.toBe(false); }); diff --git a/src/features/store/services/store-pickup-schedule.service.ts b/src/features/store/services/store-pickup-schedule.service.ts index 7496c1b2..3686d7cf 100644 --- a/src/features/store/services/store-pickup-schedule.service.ts +++ b/src/features/store/services/store-pickup-schedule.service.ts @@ -18,6 +18,7 @@ import { type StoreWeekdayBusinessHourRow, } from '@/features/store/repositories/store.repository'; import { + effectiveLeadTimeMinutes, evaluatePickupDay, type PickupDayInput, } from '@/features/store/services/store-pickup-policy.helper'; @@ -55,15 +56,13 @@ export class StorePickupScheduleService { async pickupCalendar( storeId: bigint, yearMonth: string, + productId: bigint | null = null, ): Promise { const ym = parseKstYearMonth(yearMonth); if (!ym || ym.year < MIN_SCHEDULE_YEAR || ym.year > MAX_SCHEDULE_YEAR) { throw new DomainException('INVALID_YEAR_MONTH'); } - const store = await this.repo.findStoreForPickupSchedule(storeId); - if (!store) { - throw new DomainException('STORE_NOT_FOUND'); - } + const store = await this.findScheduleStore(storeId, productId); const now = this.clock.now(); const dayCount = daysInMonth(ym.year, ym.month); @@ -97,6 +96,7 @@ export class StorePickupScheduleService { async pickupTimeSlots( storeId: bigint, date: string, + productId: bigint | null = null, ): Promise { const parsed = parseKstDate(date); if (!parsed) { @@ -106,10 +106,7 @@ export class StorePickupScheduleService { if (year < MIN_SCHEDULE_YEAR || year > MAX_SCHEDULE_YEAR) { throw new DomainException('INVALID_DATE'); } - const store = await this.repo.findStoreForPickupSchedule(storeId); - if (!store) { - throw new DomainException('STORE_NOT_FOUND'); - } + const store = await this.findScheduleStore(storeId, productId); const now = this.clock.now(); const ctx = await this.loadScheduleContext( @@ -154,9 +151,11 @@ export class StorePickupScheduleService { async isPickupSlotAvailable(args: { storeId: bigint; pickupAt: Date; + preparationTimeMinutes: number; }): Promise { - const store = await this.repo.findStoreForPickupSchedule(args.storeId); - if (!store) return false; + const found = await this.repo.findStoreForPickupSchedule(args.storeId); + if (!found) return false; + const store = withPreparationTime(found, args.preparationTimeMinutes); // 슬롯은 분 단위 시작 시각 포인트 — 초 이하가 남아 있으면 슬롯 정합 실패 if ( @@ -190,6 +189,26 @@ export class StorePickupScheduleService { ); } + /** 상품을 주면 그 상품 제작 시간까지 하한에 반영한다. */ + private async findScheduleStore( + storeId: bigint, + productId: bigint | null, + ): Promise { + const store = await this.repo.findStoreForPickupSchedule(storeId); + if (!store) { + throw new DomainException('STORE_NOT_FOUND'); + } + if (productId === null) return store; + const preparation = await this.repo.findProductPreparationTimeMinutes( + store.id, + productId, + ); + if (preparation === null) { + throw new DomainException('PRODUCT_NOT_FOUND'); + } + return withPreparationTime(store, preparation); + } + /** withCapacity=false면 capacity·예약 수량을 읽지 않는다(주문 생성 재검증 — 수량 판정은 order 몫). */ private async loadScheduleContext( storeId: bigint, @@ -248,6 +267,19 @@ export class StorePickupScheduleService { } } +function withPreparationTime( + store: StorePickupPolicyRow, + preparationTimeMinutes: number, +): StorePickupPolicyRow { + return { + ...store, + min_lead_time_minutes: effectiveLeadTimeMinutes( + store.min_lead_time_minutes, + preparationTimeMinutes, + ), + }; +} + function slotMinutes(slot: PickupSlot): number { const hours = Number(slot.time.slice(0, 2)); const minutes = Number(slot.time.slice(3, 5)); diff --git a/src/features/store/store-pickup-schedule.graphql b/src/features/store/store-pickup-schedule.graphql index 03e2c5c5..bd7d9d6c 100644 --- a/src/features/store/store-pickup-schedule.graphql +++ b/src/features/store/store-pickup-schedule.graphql @@ -4,12 +4,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! } @@ -45,6 +55,6 @@ type PickupTimeSlots { type PickupSlot { """슬롯 시각. "HH:mm" (KST).""" time: String! - """예약 가능 여부. 매장 리드타임·영업시간·잔여 수량을 반영한 값이다.""" + """예약 가능 여부. 매장 리드타임(productId를 주면 상품 제작 시간 포함)·영업시간·잔여 수량을 반영한 값이다.""" available: Boolean! } From c70c111b97049fcbaecbc97a3ca5808f1e0532c5 Mon Sep 17 00:00:00 2001 From: chanwoo7 Date: Thu, 19 Nov 2026 01:59:08 +0900 Subject: [PATCH 06/54] =?UTF-8?q?docs:=20=ED=94=BD=EC=97=85=20=EB=8B=AC?= =?UTF-8?q?=EB=A0=A5=20=ED=95=98=EB=A3=A8=20=EC=84=A4=EB=AA=85=EC=97=90=20?= =?UTF-8?q?=ED=94=BD=EC=97=85=20=ED=95=98=ED=95=9C=20=EB=B0=98=EC=98=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit productId를 주면 상품 제작 시간까지 하한에 들어가 미래 날짜도 CLOSED가 될 수 있어 PickupDay 설명을 맞춤. --- src/features/store/store-pickup-schedule.graphql | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/features/store/store-pickup-schedule.graphql b/src/features/store/store-pickup-schedule.graphql index bd7d9d6c..624655a2 100644 --- a/src/features/store/store-pickup-schedule.graphql +++ b/src/features/store/store-pickup-schedule.graphql @@ -31,13 +31,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 } From c44f8708c3cbd898f82c59762356bbe00e3b7698 Mon Sep 17 00:00:00 2001 From: chanwoo7 Date: Thu, 19 Nov 2026 01:17:49 +0900 Subject: [PATCH 07/54] =?UTF-8?q?feat:=20=EA=B3=84=EC=A2=8C=EB=B2=88?= =?UTF-8?q?=ED=98=B8=20=EC=95=94=ED=98=B8=ED=99=94(AccountCipher)=EC=99=80?= =?UTF-8?q?=20=ED=82=A4=20=EC=84=A4=EC=A0=95=C2=B7=EC=9E=AC=EC=95=94?= =?UTF-8?q?=ED=98=B8=ED=99=94=20=EC=8A=A4=ED=81=AC=EB=A6=BD=ED=8A=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 환불·정산 계좌번호를 암호화해 저장하기 위한 공용 암호기. 키를 회전해도 옛 토큰을 풀 수 있게 토큰에 keyId를 싣고, 용도(AAD)를 묶어 한 칼럼의 토큰을 다른 용도 칼럼에 옮겨 붙이면 풀리지 않게 한다. - global/crypto: AccountCipher(AES-256-GCM, 토큰 v1.... b64url, AAD refund-account·settlement-account). 첫 키로 암호화하고 keyId로 복호화, 실패 메시지에 평문·토큰을 싣지 않음. CryptoModule(global)이 설정으로 만들고 개발 키면 경고 - config/account-crypto.config: ACCOUNT_ENCRYPTION_KEYS="k2:,k1:". production은 없거나 형식이 틀리면 부팅 실패, 그 외 환경은 고정 개발 키 + 경고. 형식 오류 메시지에 키 값을 싣지 않음. AppModule load 목록에 등록 - 키 회전: yarn accounts:reencrypt(대상 수 먼저 출력, --dry-run은 대상 수만). 환불·매장 정산 계좌·정산 송금 스냅샷의 첫 키가 아닌 토큰을 첫 키로 다시 암호화하고, 읽은 뒤 바뀐 행은 덮어쓰지 않음. 개발 키로는 돌지 않음. 쓰기는 order repository(AccountNumberReencryptRepository) 경유 - 문서: README·README.en 필요 환경 변수·스크립트 표, infra/app.env.example, infra/runbook.md에 키 만들기·백업·회전 절차 테스트 - 설정 파싱: 순서·공백·base64url, 형식 오류 10종이 production에서 부팅 실패이고 비운영은 개발 키로 대신함(반증 표), 메시지에 키 값 없음, production 미설정 실패, 개발 키 고정 - 암호기: 왕복, IV 무작위, 키 회전(새 키 암호화·옛 토큰 복호화·isStale), 옛 키 제거 시 실패, AAD 불일치, 변조 8종(암호문·태그·IV·짧은 태그·다른 키 keyId·버전·조각 수·평문), CryptoModule 배선과 개발 키 경고 - 재암호화 repository(real DB): 세 칼럼 대상 수·재암호화 뒤 0·새 키만으로 원문 복호화·이미 새 키인 행 불변, 대상은 첫 키 기준 - 스크립트를 로컬 DB에 --dry-run으로 돌려 키 미설정 거절·대상 수 출력·알 수 없는 인자 거절을 확인 --- README.en.md | 54 +++---- README.md | 28 ++-- infra/app.env.example | 3 + infra/runbook.md | 13 +- package.json | 1 + scripts/accounts-reencrypt.ts | 56 +++++++ src/app.module.ts | 4 + src/config/account-crypto.config.spec.ts | 116 ++++++++++++++ src/config/account-crypto.config.ts | 87 +++++++++++ ...ccount-number-reencrypt.repository.spec.ts | 135 ++++++++++++++++ .../account-number-reencrypt.repository.ts | 115 ++++++++++++++ .../crypto/account-cipher.service.spec.ts | 144 ++++++++++++++++++ src/global/crypto/account-cipher.service.ts | 77 ++++++++++ src/global/crypto/crypto.module.ts | 28 ++++ src/test/account-cipher.ts | 13 ++ 15 files changed, 834 insertions(+), 40 deletions(-) create mode 100644 scripts/accounts-reencrypt.ts create mode 100644 src/config/account-crypto.config.spec.ts create mode 100644 src/config/account-crypto.config.ts create mode 100644 src/features/order/repositories/account-number-reencrypt.repository.spec.ts create mode 100644 src/features/order/repositories/account-number-reencrypt.repository.ts create mode 100644 src/global/crypto/account-cipher.service.spec.ts create mode 100644 src/global/crypto/account-cipher.service.ts create mode 100644 src/global/crypto/crypto.module.ts create mode 100644 src/test/account-cipher.ts diff --git a/README.en.md b/README.en.md index 6b1aaa6b..f24fe23c 100644 --- a/README.en.md +++ b/README.en.md @@ -299,35 +299,37 @@ Operational endpoints > There is no `.env.example` in the repository. The validation schemas live in [`src/config/`](./src/config/) and the production key list in [`infra/app.env.example`](./infra/app.env.example). -| Category | Keys | -| ----------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| **Server** | `NODE_ENV`, `PORT`, `BACKEND_BASE_URL`, `FRONTEND_BASE_URL` (comma-separated list; every entry becomes a non-production CORS origin and the first entry is the default post-login redirect), `APP_ROLE` (`api`, `ws`, `worker`; default `api`), `TRUST_PROXY_HOPS` | -| **Database** | `DATABASE_URL` | -| **Redis (required)** | `REDIS_URL`. Used for the auth blacklist and Subscription PubSub. If `maxmemory` is set, the policy must be `noeviction`; otherwise the worker detects it, raises an alert, and auth falls back to the database | -| **RabbitMQ (required)** | `RABBITMQ_URL`. The event backbone from the outbox relay to consumers | -| **JWT / Auth** | `JWT_PRIVATE_KEY_PEM_B64` (or `JWT_PRIVATE_KEY_PATH`) is the RS256 signing key and is required in production. `JWT_PUBLIC_KEY_PEM_B64` is derived from the private key when omitted. Also `JWT_ISSUER`, `JWT_AUDIENCE`, `JWT_ACCESS_EXPIRES_SECONDS`, `AUTH_REFRESH_EXPIRES_DAYS`, `AUTH_COOKIE_*` | -| **OIDC** | `OIDC_GOOGLE_CLIENT_ID`, `OIDC_GOOGLE_CLIENT_SECRET`, `OIDC_GOOGLE_ISSUER_URL`, `OIDC_KAKAO_CLIENT_ID`, `OIDC_KAKAO_CLIENT_SECRET`, `OIDC_KAKAO_ISSUER_URL`, `OIDC_TEMP_COOKIE_MAX_AGE_MS` | -| **AWS S3** | `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY` (IAM user `caquick-app`, media put/get only), `AWS_REGION`, `AWS_S3_BUCKET` (required in production), `S3_PRESIGN_EXPIRES_SECONDS` | -| **Docs · Metrics** | `DOCS_ACCESS_TOKEN` (access token for `/gql-docs` and `/rest-docs`, required in production), `METRICS_ACCESS_TOKEN` (Bearer token for `/metrics`, required in production) | -| **Alerts (optional)** | `DISCORD_ALERT_WEBHOOK_URL` (log-only when unset), `ALERT_DEDUPE_WINDOW_MS` (default 5 minutes), `BOOT_ALERT_STATE_DIR` (suppression files for boot-failure alerts, default `~/.caquick/boot-alert`) | -| **Outbox (optional)** | `OUTBOX_DISPATCH_ENABLED` (only `false` has an effect; enabling is decided by the worker role), `OUTBOX_POLL_INTERVAL_MS`, `OUTBOX_BATCH_SIZE`, `OUTBOX_MAX_ATTEMPTS`, `OUTBOX_PARTITION_CONCURRENCY` | +| Category | Keys | +| ----------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| **Server** | `NODE_ENV`, `PORT`, `BACKEND_BASE_URL`, `FRONTEND_BASE_URL` (comma-separated list; every entry becomes a non-production CORS origin and the first entry is the default post-login redirect), `APP_ROLE` (`api`, `ws`, `worker`; default `api`), `TRUST_PROXY_HOPS` | +| **Database** | `DATABASE_URL` | +| **Redis (required)** | `REDIS_URL`. Used for the auth blacklist and Subscription PubSub. If `maxmemory` is set, the policy must be `noeviction`; otherwise the worker detects it, raises an alert, and auth falls back to the database | +| **RabbitMQ (required)** | `RABBITMQ_URL`. The event backbone from the outbox relay to consumers | +| **JWT / Auth** | `JWT_PRIVATE_KEY_PEM_B64` (or `JWT_PRIVATE_KEY_PATH`) is the RS256 signing key and is required in production. `JWT_PUBLIC_KEY_PEM_B64` is derived from the private key when omitted. Also `JWT_ISSUER`, `JWT_AUDIENCE`, `JWT_ACCESS_EXPIRES_SECONDS`, `AUTH_REFRESH_EXPIRES_DAYS`, `AUTH_COOKIE_*` | +| **OIDC** | `OIDC_GOOGLE_CLIENT_ID`, `OIDC_GOOGLE_CLIENT_SECRET`, `OIDC_GOOGLE_ISSUER_URL`, `OIDC_KAKAO_CLIENT_ID`, `OIDC_KAKAO_CLIENT_SECRET`, `OIDC_KAKAO_ISSUER_URL`, `OIDC_TEMP_COOKIE_MAX_AGE_MS` | +| **AWS S3** | `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY` (IAM user `caquick-app`, media put/get only), `AWS_REGION`, `AWS_S3_BUCKET` (required in production), `S3_PRESIGN_EXPIRES_SECONDS` | +| **Account encryption** | `ACCOUNT_ENCRYPTION_KEYS` (keys for refund and settlement account numbers, comma-separated like `k2:,k1:`; the first key encrypts). Required in production — boot fails if missing or malformed; non-production falls back to a fixed development key with a warning. Backup and rotation in [`infra/runbook.md`](./infra/runbook.md) | +| **Docs · Metrics** | `DOCS_ACCESS_TOKEN` (access token for `/gql-docs` and `/rest-docs`, required in production), `METRICS_ACCESS_TOKEN` (Bearer token for `/metrics`, required in production) | +| **Alerts (optional)** | `DISCORD_ALERT_WEBHOOK_URL` (log-only when unset), `ALERT_DEDUPE_WINDOW_MS` (default 5 minutes), `BOOT_ALERT_STATE_DIR` (suppression files for boot-failure alerts, default `~/.caquick/boot-alert`) | +| **Outbox (optional)** | `OUTBOX_DISPATCH_ENABLED` (only `false` has an effect; enabling is decided by the worker role), `OUTBOX_POLL_INTERVAL_MS`, `OUTBOX_BATCH_SIZE`, `OUTBOX_MAX_ATTEMPTS`, `OUTBOX_PARTITION_CONCURRENCY` | ### Common Scripts -| Command | Purpose | -| ------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `yarn validate:push` | run by the pre-push hook: lint, tsc, dto:check, docs:check, arch:check, and test:scripts in full, plus only the Jest specs the change reaches (`test:push`) | -| `yarn validate` | the static checks above plus the full test:cov (manual full check); on the production Mac mini, run heavy test commands one at a time | -| `yarn test [path]` | Jest integration tests against a real database (Docker required) | -| `yarn test:scripts` | infrastructure and workflow specs (`scripts/*.spec.ts`) | -| `yarn test:push` | picks the Jest scope (full, related specs, or none) from changes against the base commit (`origin/develop` merge-base); `--dry-run` prints the plan only | -| `yarn graphql:codegen` | generates TypeScript types from the SDL | -| `yarn dto:check` | verifies SDL inputs and DTO classes are in sync | -| `yarn docs:check` | verifies SDL description coverage | -| `yarn arch:check` | checks layer direction and cycles with dependency-cruiser | -| `yarn prisma:migrate:dev` | creates and applies a migration, then regenerates the client | -| `yarn graphql:docs` | builds the SpectaQL HTML docs into `public/` | -| `yarn outbox:requeue` | resets FAILED outbox events to PENDING in production (`--id=`, `--event-type=`, `--all`); events stuck in a consumer DLQ are republished with `--event-id= --republish` | +| Command | Purpose | +| ------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `yarn validate:push` | run by the pre-push hook: lint, tsc, dto:check, docs:check, arch:check, and test:scripts in full, plus only the Jest specs the change reaches (`test:push`) | +| `yarn validate` | the static checks above plus the full test:cov (manual full check); on the production Mac mini, run heavy test commands one at a time | +| `yarn test [path]` | Jest integration tests against a real database (Docker required) | +| `yarn test:scripts` | infrastructure and workflow specs (`scripts/*.spec.ts`) | +| `yarn test:push` | picks the Jest scope (full, related specs, or none) from changes against the base commit (`origin/develop` merge-base); `--dry-run` prints the plan only | +| `yarn graphql:codegen` | generates TypeScript types from the SDL | +| `yarn dto:check` | verifies SDL inputs and DTO classes are in sync | +| `yarn docs:check` | verifies SDL description coverage | +| `yarn arch:check` | checks layer direction and cycles with dependency-cruiser | +| `yarn prisma:migrate:dev` | creates and applies a migration, then regenerates the client | +| `yarn graphql:docs` | builds the SpectaQL HTML docs into `public/` | +| `yarn outbox:requeue` | resets FAILED outbox events to PENDING in production (`--id=`, `--event-type=`, `--all`); events stuck in a consumer DLQ are republished with `--event-id= --republish` | +| `yarn accounts:reencrypt` | after rotating the account encryption key, re-encrypts refund and settlement account numbers that use a non-first key; prints the target counts first, `--dry-run` prints only the counts | ## 🧬 GraphQL diff --git a/README.md b/README.md index 1684bcfb..7349ab5c 100644 --- a/README.md +++ b/README.md @@ -299,19 +299,20 @@ APP_ROLE=worker PORT=4001 yarn start:dev # (선택) 이벤트 소비까지 보 > `.env.example`은 레포에 두지 않습니다. 검증 스키마는 [`src/config/`](./src/config/)에, 운영 키 목록은 [`infra/app.env.example`](./infra/app.env.example)에 있습니다. -| 카테고리 | 키 | -| ------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| **서버** | `NODE_ENV`, `PORT`, `BACKEND_BASE_URL`, `FRONTEND_BASE_URL`(쉼표로 여러 개를 적을 수 있으며 전부 비운영 CORS 오리진이 되고, 첫 값이 로그인 뒤 리다이렉트 기본값), `APP_ROLE`(`api`·`ws`·`worker`, 기본 `api`), `TRUST_PROXY_HOPS` | -| **DB** | `DATABASE_URL` | -| **Redis (필수)** | `REDIS_URL`. 인증 블랙리스트와 Subscription PubSub에 사용합니다. `maxmemory`를 설정했다면 정책이 `noeviction`이어야 하며, 아니면 worker가 점검해 경보를 보내고 인증은 DB 폴백으로 동작합니다 | -| **RabbitMQ (필수)** | `RABBITMQ_URL`. outbox 릴레이에서 소비자로 이어지는 이벤트 백본에 사용합니다 | -| **JWT / Auth** | `JWT_PRIVATE_KEY_PEM_B64`(또는 `JWT_PRIVATE_KEY_PATH`)는 RS256 서명키이며 운영에서 필수입니다. `JWT_PUBLIC_KEY_PEM_B64`는 생략하면 개인키에서 유도합니다. 그 밖에 `JWT_ISSUER`, `JWT_AUDIENCE`, `JWT_ACCESS_EXPIRES_SECONDS`, `AUTH_REFRESH_EXPIRES_DAYS`, `AUTH_COOKIE_*` | -| **OIDC** | `OIDC_GOOGLE_CLIENT_ID`, `OIDC_GOOGLE_CLIENT_SECRET`, `OIDC_GOOGLE_ISSUER_URL`, `OIDC_KAKAO_CLIENT_ID`, `OIDC_KAKAO_CLIENT_SECRET`, `OIDC_KAKAO_ISSUER_URL`, `OIDC_TEMP_COOKIE_MAX_AGE_MS` | -| **AWS S3** | `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`(IAM 사용자 `caquick-app`, 미디어 put/get 권한만), `AWS_REGION`, `AWS_S3_BUCKET`(운영 필수), `S3_PRESIGN_EXPIRES_SECONDS` | -| **문서 · 메트릭** | `DOCS_ACCESS_TOKEN`(`/gql-docs`와 `/rest-docs` 접근 토큰, 운영 필수), `METRICS_ACCESS_TOKEN`(`/metrics` Bearer 토큰, 운영 필수) | -| **경보 (선택)** | `DISCORD_ALERT_WEBHOOK_URL`(없으면 로그로만 남깁니다), `ALERT_DEDUPE_WINDOW_MS`(기본 5분), `BOOT_ALERT_STATE_DIR`(부팅 실패 경보의 억제 파일 위치, 기본 `~/.caquick/boot-alert`) | -| **Outbox (선택)** | `OUTBOX_DISPATCH_ENABLED`(`false`로 끄는 용도만 있으며 켜는 것은 worker 역할이 결정), `OUTBOX_POLL_INTERVAL_MS`, `OUTBOX_BATCH_SIZE`, `OUTBOX_MAX_ATTEMPTS`, `OUTBOX_PARTITION_CONCURRENCY` | -| **푸시 (선택)** | `EXPO_PUSH_ENABLED`(`true`일 때만 worker가 판매자 앱 푸시를 보내고, 기본 `false`면 소비자가 전송 없이 ack합니다), `EXPO_PUSH_ACCESS_TOKEN`(Expo 액세스 토큰, 없으면 인증 헤더 없이 보냅니다), `EXPO_PUSH_TIMEOUT_MS`(기본 5000) | +| 카테고리 | 키 | +| ------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| **서버** | `NODE_ENV`, `PORT`, `BACKEND_BASE_URL`, `FRONTEND_BASE_URL`(쉼표로 여러 개를 적을 수 있으며 전부 비운영 CORS 오리진이 되고, 첫 값이 로그인 뒤 리다이렉트 기본값), `APP_ROLE`(`api`·`ws`·`worker`, 기본 `api`), `TRUST_PROXY_HOPS` | +| **DB** | `DATABASE_URL` | +| **Redis (필수)** | `REDIS_URL`. 인증 블랙리스트와 Subscription PubSub에 사용합니다. `maxmemory`를 설정했다면 정책이 `noeviction`이어야 하며, 아니면 worker가 점검해 경보를 보내고 인증은 DB 폴백으로 동작합니다 | +| **RabbitMQ (필수)** | `RABBITMQ_URL`. outbox 릴레이에서 소비자로 이어지는 이벤트 백본에 사용합니다 | +| **JWT / Auth** | `JWT_PRIVATE_KEY_PEM_B64`(또는 `JWT_PRIVATE_KEY_PATH`)는 RS256 서명키이며 운영에서 필수입니다. `JWT_PUBLIC_KEY_PEM_B64`는 생략하면 개인키에서 유도합니다. 그 밖에 `JWT_ISSUER`, `JWT_AUDIENCE`, `JWT_ACCESS_EXPIRES_SECONDS`, `AUTH_REFRESH_EXPIRES_DAYS`, `AUTH_COOKIE_*` | +| **OIDC** | `OIDC_GOOGLE_CLIENT_ID`, `OIDC_GOOGLE_CLIENT_SECRET`, `OIDC_GOOGLE_ISSUER_URL`, `OIDC_KAKAO_CLIENT_ID`, `OIDC_KAKAO_CLIENT_SECRET`, `OIDC_KAKAO_ISSUER_URL`, `OIDC_TEMP_COOKIE_MAX_AGE_MS` | +| **AWS S3** | `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`(IAM 사용자 `caquick-app`, 미디어 put/get 권한만), `AWS_REGION`, `AWS_S3_BUCKET`(운영 필수), `S3_PRESIGN_EXPIRES_SECONDS` | +| **계좌 암호화** | `ACCOUNT_ENCRYPTION_KEYS`(환불·정산 계좌번호 암호화 키, `k2:,k1:`처럼 쉼표로 나열하고 첫 키로 암호화합니다). 운영 필수이며 없거나 형식이 틀리면 부팅이 실패합니다. 비운영은 고정 개발 키를 쓰고 경고를 남깁니다. 백업·회전은 [`infra/runbook.md`](./infra/runbook.md) | +| **문서 · 메트릭** | `DOCS_ACCESS_TOKEN`(`/gql-docs`와 `/rest-docs` 접근 토큰, 운영 필수), `METRICS_ACCESS_TOKEN`(`/metrics` Bearer 토큰, 운영 필수) | +| **경보 (선택)** | `DISCORD_ALERT_WEBHOOK_URL`(없으면 로그로만 남깁니다), `ALERT_DEDUPE_WINDOW_MS`(기본 5분), `BOOT_ALERT_STATE_DIR`(부팅 실패 경보의 억제 파일 위치, 기본 `~/.caquick/boot-alert`) | +| **Outbox (선택)** | `OUTBOX_DISPATCH_ENABLED`(`false`로 끄는 용도만 있으며 켜는 것은 worker 역할이 결정), `OUTBOX_POLL_INTERVAL_MS`, `OUTBOX_BATCH_SIZE`, `OUTBOX_MAX_ATTEMPTS`, `OUTBOX_PARTITION_CONCURRENCY` | +| **푸시 (선택)** | `EXPO_PUSH_ENABLED`(`true`일 때만 worker가 판매자 앱 푸시를 보내고, 기본 `false`면 소비자가 전송 없이 ack합니다), `EXPO_PUSH_ACCESS_TOKEN`(Expo 액세스 토큰, 없으면 인증 헤더 없이 보냅니다), `EXPO_PUSH_TIMEOUT_MS`(기본 5000) | ### 자주 쓰는 스크립트 @@ -329,6 +330,7 @@ APP_ROLE=worker PORT=4001 yarn start:dev # (선택) 이벤트 소비까지 보 | `yarn prisma:migrate:dev` | 마이그레이션을 생성·적용하고 클라이언트를 다시 생성합니다 | | `yarn graphql:docs` | SpectaQL HTML 문서를 `public/`에 빌드합니다 | | `yarn outbox:requeue` | 운영에서 FAILED 상태의 outbox 이벤트를 PENDING으로 되돌립니다(`--id=`, `--event-type=`, `--all`). 소비 DLQ에 빠진 이벤트는 `--event-id= --republish`로 다시 싣습니다 | +| `yarn accounts:reencrypt` | 계좌번호 암호화 키를 회전한 뒤 첫 키가 아닌 키로 암호화된 환불·정산 계좌번호를 첫 키로 다시 암호화합니다. 대상 수를 먼저 출력하고, `--dry-run`은 대상 수만 출력합니다 | ## 🧬 GraphQL diff --git a/infra/app.env.example b/infra/app.env.example index 1ae6082a..49aa03ac 100644 --- a/infra/app.env.example +++ b/infra/app.env.example @@ -32,6 +32,9 @@ OIDC_KAKAO_CLIENT_SECRET= OIDC_KAKAO_ISSUER_URL=https://kauth.kakao.com OIDC_TEMP_COOKIE_MAX_AGE_MS= +# ---- 앱: 계좌번호 암호화 ---- +ACCOUNT_ENCRYPTION_KEYS= # 운영 필수(NODE_ENV=production이면 미설정·형식 오류 시 부팅 실패). keyId:를 쉼표로 나열, 첫 키로 암호화. 백업·회전은 runbook + # ---- 앱: S3(미디어) ---- AWS_ACCESS_KEY_ID= AWS_SECRET_ACCESS_KEY= diff --git a/infra/runbook.md b/infra/runbook.md index bcc26450..cc8f4528 100644 --- a/infra/runbook.md +++ b/infra/runbook.md @@ -1,4 +1,4 @@ -# 운영 runbook — 백업·복구·롤백 +# 운영 runbook — 백업·복구·롤백·키 회전 ## 백업 @@ -76,3 +76,14 @@ Actions → `Deploy` → Run workflow → `image_tag`에 이전 sha. 마이그 - `FAILED`(릴레이 상한 초과): `docker compose exec worker yarn outbox:requeue --event-type=` 또는 `--id=` - 소비 DLQ(`q..dlq`): 원인 해소 뒤 `docker compose exec worker yarn outbox:requeue --event-id= --republish`(경보 메시지의 명령 앞에 `docker compose exec worker`를 붙인다) + +## 계좌번호 암호화 키 + +환불·정산 계좌번호는 `ACCOUNT_ENCRYPTION_KEYS`(APP_ENV secret)로 암호화한다. 형식은 `k2:,k1:`이고, 첫 키로 암호화하며 토큰에 적힌 keyId로 복호화한다. + +- 만들기: `printf 'k1:%s\n' "$(openssl rand -base64 32)"`. keyId는 영문·숫자·`_`·`-` 32자 이하. +- 백업: 키를 잃으면 계좌번호를 복구할 수 없다. GitHub secret은 다시 읽을 수 없으므로 등록 전에 비밀번호 관리자에 먼저 보관한다. DB 백업과 같은 곳에 두지 않는다. +- 회전(유출이 의심될 때도 같은 절차) + 1. 새 키를 만들어 백업하고, APP_ENV의 `ACCOUNT_ENCRYPTION_KEYS` 맨 앞에 넣어(`k2:<새 키>,k1:<옛 키>`) 배포한다. 이때부터 새로 쓰는 계좌번호는 새 키로 암호화된다. + 2. `docker compose exec worker yarn accounts:reencrypt --dry-run`으로 대상 수를 보고, `docker compose exec worker yarn accounts:reencrypt`로 다시 암호화한다. 읽은 뒤 바뀐 행은 건너뛰므로 `--dry-run`이 0이 될 때까지 반복한다. + 3. 대상이 0이면 옛 키를 env에서 빼고 배포한다. 옛 키 백업은 DB 백업 보관 기간(14일)이 지날 때까지 남긴다 — 그 전 덤프를 복구하면 옛 키로 암호화된 행이 돌아온다(복구 뒤 1단계부터 다시). diff --git a/package.json b/package.json index 4b329171..63ecfaaf 100644 --- a/package.json +++ b/package.json @@ -39,6 +39,7 @@ "postinstall": "prisma generate", "prepare": "husky", "outbox:requeue": "ts-node -r tsconfig-paths/register scripts/outbox-requeue.ts", + "accounts:reencrypt": "ts-node -r tsconfig-paths/register scripts/accounts-reencrypt.ts", "lint:fix": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix" }, "dependencies": { diff --git a/scripts/accounts-reencrypt.ts b/scripts/accounts-reencrypt.ts new file mode 100644 index 00000000..b95639c4 --- /dev/null +++ b/scripts/accounts-reencrypt.ts @@ -0,0 +1,56 @@ +/** + * 계좌번호 키 회전: ACCOUNT_ENCRYPTION_KEYS 맨 앞에 새 키를 넣고 배포한 뒤 돌린다. 대상 수를 먼저 찍는다. + * yarn accounts:reencrypt --dry-run # 대상 수만 + * yarn accounts:reencrypt # 첫 키가 아닌 키로 암호화된 계좌번호를 첫 키로 다시 암호화 + * 대상이 0이 된 뒤에야 옛 키를 env에서 뺀다(infra/runbook.md). + */ +import '@/config/preload-env'; + +import { readAccountCryptoConfig } from '@/config/account-crypto.config'; +import { AccountNumberReencryptRepository } from '@/features/order/repositories/account-number-reencrypt.repository'; +import { AccountCipher } from '@/global/crypto/account-cipher.service'; +import type { PrismaService } from '@/prisma'; +import { createExtendedPrismaClient } from '@/prisma/prisma.service'; + +async function main(): Promise { + const databaseUrl = process.env.DATABASE_URL; + if (!databaseUrl) throw new Error('DATABASE_URL이 필요합니다'); + const argv = process.argv.slice(2); + const unknown = argv.filter((arg) => arg !== '--dry-run'); + if (unknown.length > 0) + throw new Error(`알 수 없는 인자: ${unknown.join(' ')}`); + + const config = readAccountCryptoConfig(); + if (config.devKeyReason) { + throw new Error( + `고정 개발 키로는 재암호화하지 않습니다: ${config.devKeyReason}`, + ); + } + const cipher = new AccountCipher(config); + const prisma = createExtendedPrismaClient(databaseUrl); + try { + // 모델 write는 소유 feature의 repository만 — 스크립트도 예외가 아니다 + const repo = new AccountNumberReencryptRepository( + prisma as PrismaService, + cipher, + ); + const stale = await repo.countStale(); + process.stdout.write( + `primary key ${cipher.primaryKeyId}, 대상 ${JSON.stringify(stale)}\n`, + ); + if (argv.includes('--dry-run')) return; + const done = await repo.reencryptStale(); + process.stdout.write(`재암호화 ${JSON.stringify(done)}\n`); + } finally { + await prisma.$disconnect(); + } +} + +if (require.main === module) { + main().catch((error: unknown) => { + process.stderr.write( + `${error instanceof Error ? error.message : String(error)}\n`, + ); + process.exit(1); + }); +} diff --git a/src/app.module.ts b/src/app.module.ts index ad74fb8a..ecadf66e 100644 --- a/src/app.module.ts +++ b/src/app.module.ts @@ -17,6 +17,7 @@ import { ScheduleModule } from '@nestjs/schedule'; import { ServeStaticModule } from '@nestjs/serve-static'; import { CommonModule } from '@/common/common.module'; +import accountCryptoConfig from '@/config/account-crypto.config'; import alertingConfig from '@/config/alerting.config'; import appConfig, { APP_ROLE_TOKEN, @@ -48,6 +49,7 @@ import { SystemModule } from '@/features/system/system.module'; import { AlertingModule } from '@/global/alerting'; import { AuthGlobalModule } from '@/global/auth/auth-global.module'; import { BlacklistModule } from '@/global/auth/blacklist'; +import { CryptoModule } from '@/global/crypto/crypto.module'; import { formatGraphqlError } from '@/global/graphql/format-graphql-error'; import { buildGraphqlContext } from '@/global/graphql/graphql-context.helper'; import { GraphqlGlobalModule } from '@/global/graphql/graphql.module'; @@ -120,6 +122,7 @@ export class AppModule implements NestModule { isGlobal: true, cache: true, load: [ + accountCryptoConfig, alertingConfig, appConfig, authConfig, @@ -147,6 +150,7 @@ export class AppModule implements NestModule { BlacklistModule, PubSubModule, StorageModule, + CryptoModule, // 크론(SearchModule)은 worker만 — api가 같이 돌리면 같은 스냅샷을 두 번 만든다 ...(runsBackgroundJobs(role) ? [ScheduleModule.forRoot()] : []), ...(servesHttpApi(role) ? httpModules() : []), diff --git a/src/config/account-crypto.config.spec.ts b/src/config/account-crypto.config.spec.ts new file mode 100644 index 00000000..6dd822cc --- /dev/null +++ b/src/config/account-crypto.config.spec.ts @@ -0,0 +1,116 @@ +import { randomBytes } from 'node:crypto'; + +import accountCryptoConfig, { + parseAccountEncryptionKeys, + readAccountCryptoConfig, +} from '@/config/account-crypto.config'; + +const b64 = (bytes: number) => randomBytes(bytes).toString('base64'); + +describe('accountCryptoConfig', () => { + const k1 = b64(32); + const k2 = b64(32); + + it('키를 적힌 순서대로 읽는다(첫 키가 암호화 키), 공백·빈 항목은 무시한다', () => { + const keys = parseAccountEncryptionKeys(` k2:${k2} , k1:${k1} ,`); + expect(keys.map((k) => k.id)).toEqual(['k2', 'k1']); + expect(keys[0].key.equals(Buffer.from(k2, 'base64'))).toBe(true); + expect(keys[1].key).toHaveLength(32); + }); + + it('base64url 문자도 받는다', () => { + const key = randomBytes(32); + expect( + parseAccountEncryptionKeys(`k1:${key.toString('base64url')}`)[0].key, + ).toEqual(key); + }); + + // 반증 — 운영 부팅을 막아야 하는 형식 오류 전수 + const malformed: Array<[string, string]> = [ + ['빈 목록', ' , '], + ['콜론 없음', `k1${k1}`], + ['빈 keyId', `:${k1}`], + ['keyId에 점', `k.1:${k1}`], + ['keyId 33자', `${'k'.repeat(33)}:${k1}`], + ['31바이트 키', `k1:${b64(31)}`], + ['33바이트 키', `k1:${b64(33)}`], + ['base64 밖 문자', `k1:${k1.slice(0, -2)}!=`], + ['키 없음', 'k1:'], + ['keyId 중복', `k1:${k1},k1:${k2}`], + ]; + + it.each(malformed)('반증: %s면 production 부팅에서 던진다', (_label, raw) => { + expect(() => + readAccountCryptoConfig({ + NODE_ENV: 'production', + ACCOUNT_ENCRYPTION_KEYS: raw, + }), + ).toThrow('ACCOUNT_ENCRYPTION_KEYS is malformed'); + }); + + it.each(malformed)( + '%s면 비운영은 고정 개발 키로 대신하고 이유를 남긴다', + (_label, raw) => { + const config = readAccountCryptoConfig({ + NODE_ENV: 'development', + ACCOUNT_ENCRYPTION_KEYS: raw, + }); + expect(config.keys.map((k) => k.id)).toEqual(['dev']); + expect(config.devKeyReason).toContain('형식 오류'); + }, + ); + + it('형식 오류 메시지에 키 값을 싣지 않는다', () => { + const secret = b64(31); + let message = ''; + try { + readAccountCryptoConfig({ + NODE_ENV: 'production', + ACCOUNT_ENCRYPTION_KEYS: `k1:${secret}`, + }); + } catch (error) { + message = (error as Error).message; + } + expect(message).toContain('entry 1 (k1)'); + expect(message).not.toContain(secret); + }); + + it('반증: production에서 키가 없거나 공백뿐이면 부팅에서 던진다', () => { + for (const raw of [undefined, ' ']) { + expect(() => + readAccountCryptoConfig({ + NODE_ENV: 'production', + ACCOUNT_ENCRYPTION_KEYS: raw, + }), + ).toThrow('ACCOUNT_ENCRYPTION_KEYS must be set'); + } + }); + + it('production에서 올바른 키면 그대로 쓴다', () => { + const config = readAccountCryptoConfig({ + NODE_ENV: 'production', + ACCOUNT_ENCRYPTION_KEYS: `k1:${k1}`, + }); + expect(config.devKeyReason).toBeNull(); + expect(config.keys.map((k) => k.id)).toEqual(['k1']); + }); + + it('비운영에서 키가 없으면 매번 같은 32바이트 개발 키를 쓴다(로컬 재시작 뒤에도 풀린다)', () => { + const a = readAccountCryptoConfig({}); + const b = readAccountCryptoConfig({ NODE_ENV: 'test' }); + expect(a.devKeyReason).toBe('ACCOUNT_ENCRYPTION_KEYS 미설정'); + expect(a.keys[0].key).toHaveLength(32); + expect(a.keys[0].key.equals(b.keys[0].key)).toBe(true); + }); + + it('registerAs는 process.env를 같은 규칙으로 읽는다', () => { + const saved = process.env.ACCOUNT_ENCRYPTION_KEYS; + process.env.ACCOUNT_ENCRYPTION_KEYS = `k9:${k1}`; + try { + expect(accountCryptoConfig().keys.map((k) => k.id)).toEqual(['k9']); + } finally { + if (saved === undefined) delete process.env.ACCOUNT_ENCRYPTION_KEYS; + else process.env.ACCOUNT_ENCRYPTION_KEYS = saved; + } + }); +}); diff --git a/src/config/account-crypto.config.ts b/src/config/account-crypto.config.ts new file mode 100644 index 00000000..88639142 --- /dev/null +++ b/src/config/account-crypto.config.ts @@ -0,0 +1,87 @@ +import { createHash } from 'node:crypto'; + +import { registerAs } from '@nestjs/config'; + +import { parseEnvList, parseEnvString } from '@/common/utils/env-parse'; + +export interface AccountCryptoKey { + id: string; + key: Buffer; +} + +export interface AccountCryptoConfig { + /** 첫 키로 암호화하고 토큰에 적힌 keyId로 복호화한다. 회전 중에는 옛 키를 뒤에 남긴다. */ + keys: AccountCryptoKey[]; + /** 비운영에서 고정 개발 키로 대신한 이유. 설정한 키를 쓰면 null. */ + devKeyReason: string | null; +} + +// keyId는 토큰 구분자(.)와 env 구분자(: ,)를 쓰지 못한다 +const KEY_ID = /^[A-Za-z0-9_-]{1,32}$/; +const BASE64 = /^[A-Za-z0-9+/_-]+={0,2}$/; +const KEY_BYTES = 32; + +/** 로컬·테스트 전용. production은 키가 없으면 부팅하지 않아 운영 데이터가 이 키로 암호화되지 않는다. */ +const DEV_KEY: AccountCryptoKey = { + id: 'dev', + key: createHash('sha256').update('caquick-local-account-key').digest(), +}; + +/** `k2:,k1:`. 오류 메시지에 키 값을 싣지 않는다. */ +export function parseAccountEncryptionKeys(raw: string): AccountCryptoKey[] { + const entries = parseEnvList(raw); + if (entries.length === 0) throw new Error('no keys'); + const keys = entries.map((entry, index) => { + const sep = entry.indexOf(':'); + const id = sep < 0 ? '' : entry.slice(0, sep); + if (!KEY_ID.test(id)) { + throw new Error(`entry ${index + 1}: keyId must match ${KEY_ID.source}`); + } + const encoded = entry.slice(sep + 1); + if ( + !BASE64.test(encoded) || + Buffer.from(encoded, 'base64').length !== KEY_BYTES + ) { + throw new Error( + `entry ${index + 1} (${id}): key must be base64 32 bytes`, + ); + } + return { id, key: Buffer.from(encoded, 'base64') }; + }); + if (new Set(keys.map((k) => k.id)).size !== keys.length) { + throw new Error('duplicate keyId'); + } + return keys; +} + +/** registerAs와 DI 밖(재암호화 스크립트·시드)이 같은 규칙으로 읽도록 순수 함수로 둔다. */ +export function readAccountCryptoConfig( + env: NodeJS.ProcessEnv = process.env, +): AccountCryptoConfig { + const isProd = env.NODE_ENV === 'production'; + const raw = parseEnvString(env.ACCOUNT_ENCRYPTION_KEYS); + if (raw === undefined) { + if (isProd) { + throw new Error( + 'ACCOUNT_ENCRYPTION_KEYS must be set in production environment', + ); + } + return { keys: [DEV_KEY], devKeyReason: 'ACCOUNT_ENCRYPTION_KEYS 미설정' }; + } + try { + return { keys: parseAccountEncryptionKeys(raw), devKeyReason: null }; + } catch (error) { + const reason = error instanceof Error ? error.message : String(error); + if (isProd) { + throw new Error(`ACCOUNT_ENCRYPTION_KEYS is malformed: ${reason}`); + } + return { + keys: [DEV_KEY], + devKeyReason: `ACCOUNT_ENCRYPTION_KEYS 형식 오류(${reason})`, + }; + } +} + +export default registerAs('accountCrypto', (): AccountCryptoConfig => + readAccountCryptoConfig(), +); diff --git a/src/features/order/repositories/account-number-reencrypt.repository.spec.ts b/src/features/order/repositories/account-number-reencrypt.repository.spec.ts new file mode 100644 index 00000000..b84453c8 --- /dev/null +++ b/src/features/order/repositories/account-number-reencrypt.repository.spec.ts @@ -0,0 +1,135 @@ +import { AccountNumberReencryptRepository } from '@/features/order/repositories/account-number-reencrypt.repository'; +import type { PrismaClient } from '@/generated/prisma/client'; +import { AccountCipher } from '@/global/crypto/account-cipher.service'; +import { testAccountKey } from '@/test/account-cipher'; +import { disconnectTestPrismaClient } from '@/test/db/prisma-test-client'; +import { closeTruncateConnection, truncateAll } from '@/test/db/truncate'; +import { createOrder, createStore } from '@/test/factories'; +import { createTestingModuleWithRealDb } from '@/test/modules/testing-module.builder'; + +describe('AccountNumberReencryptRepository (real DB)', () => { + let prisma: PrismaClient; + const k1 = testAccountKey('k1'); + const k2 = testAccountKey('k2'); + const oldCipher = new AccountCipher({ keys: [k1] }); + const rotated = new AccountCipher({ keys: [k2, k1] }); + + beforeAll(async () => { + ({ prisma } = await createTestingModuleWithRealDb({ providers: [] })); + }); + + afterAll(async () => { + await closeTruncateConnection(); + await disconnectTestPrismaClient(); + }); + + beforeEach(async () => { + await truncateAll(); + }); + + const repoWith = (cipher: AccountCipher) => + new AccountNumberReencryptRepository(prisma, cipher); + + /** 세 칼럼에 k1 토큰을 하나씩, 환불은 계좌 미입력 행과 이미 k2인 행도 둔다. */ + async function seedTokens() { + const store = await createStore(prisma); + const order = await createOrder(prisma); + const refund = (token: string | null) => + prisma.refund.create({ + data: { + order_id: order.id, + kind: 'DEPOSIT_RETURN', + amount: 1000, + requested_at: new Date(), + account_number_enc: token, + }, + }); + const stale = await refund( + oldCipher.encrypt('1111222233', 'refund-account'), + ); + await refund(null); + const fresh = await refund(rotated.encrypt('9999888877', 'refund-account')); + const account = await prisma.storeSettlementAccount.create({ + data: { + store_id: store.id, + bank_code: '004', + account_holder: '케이크샵', + account_number_enc: oldCipher.encrypt('44445555', 'settlement-account'), + account_number_last4: '5555', + updated_by_account_id: store.seller_account_id, + updated_by_role: 'SELLER', + }, + }); + const settlement = await prisma.settlement.create({ + data: { + store_id: store.id, + store_name_snapshot: store.store_name, + period_start: new Date('2026-11-09'), + period_end: new Date('2026-11-15'), + order_count: 1, + settlement_base_amount: 1000, + commission_amount: 0, + payout_amount: 1000, + paid_account_number_enc: oldCipher.encrypt( + '44445555', + 'settlement-account', + ), + }, + }); + return { stale, fresh, account, settlement }; + } + + it('첫 키가 아닌 토큰만 대상으로 세고, 재암호화 뒤에는 0이며 원문이 그대로 풀린다', async () => { + const { stale, fresh, account, settlement } = await seedTokens(); + const repo = repoWith(rotated); + const freshBefore = ( + await prisma.refund.findUniqueOrThrow({ where: { id: fresh.id } }) + ).account_number_enc; + + const target = { refund: 1, storeSettlementAccount: 1, settlement: 1 }; + expect(await repo.countStale()).toEqual(target); + expect(await repo.reencryptStale()).toEqual(target); + expect(await repo.countStale()).toEqual({ + refund: 0, + storeSettlementAccount: 0, + settlement: 0, + }); + + const refundToken = ( + await prisma.refund.findUniqueOrThrow({ where: { id: stale.id } }) + ).account_number_enc!; + const accountToken = ( + await prisma.storeSettlementAccount.findUniqueOrThrow({ + where: { id: account.id }, + }) + ).account_number_enc; + const paidToken = ( + await prisma.settlement.findUniqueOrThrow({ + where: { id: settlement.id }, + }) + ).paid_account_number_enc!; + for (const token of [refundToken, accountToken, paidToken]) { + expect(token.startsWith('v1.k2.')).toBe(true); + } + // 옛 키를 뺀 뒤에도 풀린다 — 회전 마지막 단계(옛 키 제거)의 전제 + const newOnly = new AccountCipher({ keys: [k2] }); + expect(newOnly.decrypt(refundToken, 'refund-account')).toBe('1111222233'); + expect(newOnly.decrypt(accountToken, 'settlement-account')).toBe( + '44445555', + ); + expect(newOnly.decrypt(paidToken, 'settlement-account')).toBe('44445555'); + expect( + (await prisma.refund.findUniqueOrThrow({ where: { id: fresh.id } })) + .account_number_enc, + ).toBe(freshBefore); + }); + + it('대상은 첫 키 기준이다 — 첫 키가 k1이면 k2 토큰만 센다', async () => { + await seedTokens(); + expect(await repoWith(oldCipher).countStale()).toEqual({ + refund: 1, + storeSettlementAccount: 0, + settlement: 0, + }); + }); +}); diff --git a/src/features/order/repositories/account-number-reencrypt.repository.ts b/src/features/order/repositories/account-number-reencrypt.repository.ts new file mode 100644 index 00000000..ccd9f20d --- /dev/null +++ b/src/features/order/repositories/account-number-reencrypt.repository.ts @@ -0,0 +1,115 @@ +import type { + AccountCipher, + AccountCipherPurpose, +} from '@/global/crypto/account-cipher.service'; +import type { PrismaService } from '@/prisma'; + +export interface ReencryptCounts { + refund: number; + storeSettlementAccount: number; + settlement: number; +} + +interface EncryptedRow { + id: bigint; + token: string; +} + +/** + * 키 회전용(`yarn accounts:reencrypt`). 첫 키가 아닌 키로 암호화된 계좌번호를 첫 키로 다시 암호화한다. + * 행마다 읽은 토큰이 그대로일 때만 바꿔, 그사이 사용자가 새로 입력한 계좌를 옛 값으로 덮지 않는다. + */ +export class AccountNumberReencryptRepository { + constructor( + private readonly prisma: PrismaService, + private readonly cipher: AccountCipher, + ) {} + + async countStale(): Promise { + const rows = await this.staleRows(); + return { + refund: rows.refund.length, + storeSettlementAccount: rows.storeSettlementAccount.length, + settlement: rows.settlement.length, + }; + } + + async reencryptStale(): Promise { + const rows = await this.staleRows(); + const counts: ReencryptCounts = { + refund: 0, + storeSettlementAccount: 0, + settlement: 0, + }; + for (const row of rows.refund) { + const { count } = await this.prisma.refund.updateMany({ + where: { id: row.id, account_number_enc: row.token }, + data: { account_number_enc: this.rotate(row.token, 'refund-account') }, + }); + counts.refund += count; + } + for (const row of rows.storeSettlementAccount) { + const { count } = await this.prisma.storeSettlementAccount.updateMany({ + where: { id: row.id, account_number_enc: row.token }, + data: { + account_number_enc: this.rotate(row.token, 'settlement-account'), + }, + }); + counts.storeSettlementAccount += count; + } + for (const row of rows.settlement) { + const { count } = await this.prisma.settlement.updateMany({ + where: { id: row.id, paid_account_number_enc: row.token }, + data: { + paid_account_number_enc: this.rotate(row.token, 'settlement-account'), + }, + }); + counts.settlement += count; + } + return counts; + } + + private rotate(token: string, purpose: AccountCipherPurpose): string { + return this.cipher.encrypt(this.cipher.decrypt(token, purpose), purpose); + } + + private async staleRows(): Promise< + Record + > { + const [refunds, accounts, settlements] = await Promise.all([ + this.prisma.refund.findMany({ + where: { account_number_enc: { not: null } }, + select: { id: true, account_number_enc: true }, + orderBy: { id: 'asc' }, + }), + this.prisma.storeSettlementAccount.findMany({ + select: { id: true, account_number_enc: true }, + orderBy: { id: 'asc' }, + }), + this.prisma.settlement.findMany({ + where: { paid_account_number_enc: { not: null } }, + select: { id: true, paid_account_number_enc: true }, + orderBy: { id: 'asc' }, + }), + ]); + const stale = (rows: { id: bigint; token: string | null }[]) => + rows.filter( + (row): row is EncryptedRow => + row.token !== null && this.cipher.isStale(row.token), + ); + return { + refund: stale( + refunds.map((r) => ({ id: r.id, token: r.account_number_enc })), + ), + storeSettlementAccount: stale( + accounts.map((r) => ({ id: r.id, token: r.account_number_enc })), + ), + settlement: stale( + settlements.map((r) => ({ + id: r.id, + token: r.paid_account_number_enc, + })), + ), + }; + } +} diff --git a/src/global/crypto/account-cipher.service.spec.ts b/src/global/crypto/account-cipher.service.spec.ts new file mode 100644 index 00000000..853ded0b --- /dev/null +++ b/src/global/crypto/account-cipher.service.spec.ts @@ -0,0 +1,144 @@ +import { ConfigService } from '@nestjs/config'; +import { Test } from '@nestjs/testing'; + +import { readAccountCryptoConfig } from '@/config/account-crypto.config'; +import { AccountCipher } from '@/global/crypto/account-cipher.service'; +import { CryptoModule } from '@/global/crypto/crypto.module'; +import { CustomLoggerService } from '@/global/logger/custom-logger.service'; +import { testAccountKey } from '@/test/account-cipher'; + +const PLAIN = '110123456789'; + +describe('AccountCipher', () => { + const k1 = testAccountKey('k1'); + const k2 = testAccountKey('k2'); + + it('암호화한 값을 같은 용도로 풀면 원문이 나온다', () => { + const cipher = new AccountCipher({ keys: [k1] }); + const token = cipher.encrypt(PLAIN, 'settlement-account'); + + expect(token).toMatch(/^v1\.k1\.[\w-]+\.[\w-]+\.[\w-]+$/); + expect(token).not.toContain(PLAIN); + expect(cipher.decrypt(token, 'settlement-account')).toBe(PLAIN); + }); + + it('같은 원문도 매번 다른 토큰이 된다(IV 무작위)', () => { + const cipher = new AccountCipher({ keys: [k1] }); + expect(cipher.encrypt(PLAIN, 'refund-account')).not.toBe( + cipher.encrypt(PLAIN, 'refund-account'), + ); + }); + + it('키 회전: 새 키를 앞에 두면 새 키로 암호화하고 옛 토큰도 keyId로 푼다', () => { + const oldToken = new AccountCipher({ keys: [k1] }).encrypt( + PLAIN, + 'refund-account', + ); + const rotated = new AccountCipher({ keys: [k2, k1] }); + const newToken = rotated.encrypt(PLAIN, 'refund-account'); + + expect(rotated.primaryKeyId).toBe('k2'); + expect(newToken.startsWith('v1.k2.')).toBe(true); + expect(rotated.decrypt(oldToken, 'refund-account')).toBe(PLAIN); + expect(rotated.isStale(oldToken)).toBe(true); + expect(rotated.isStale(newToken)).toBe(false); + }); + + it('반증: 옛 키를 빼면 옛 토큰은 풀리지 않는다', () => { + const oldToken = new AccountCipher({ keys: [k1] }).encrypt( + PLAIN, + 'refund-account', + ); + expect(() => + new AccountCipher({ keys: [k2] }).decrypt(oldToken, 'refund-account'), + ).toThrow('계좌번호 키(k1)가 설정에 없습니다'); + }); + + it('반증: 용도(AAD)가 다르면 풀리지 않는다', () => { + const cipher = new AccountCipher({ keys: [k1] }); + const token = cipher.encrypt(PLAIN, 'refund-account'); + expect(() => cipher.decrypt(token, 'settlement-account')).toThrow( + '복호화 실패', + ); + }); + + describe('반증: 변조', () => { + const cipher = new AccountCipher({ keys: [k1, k2] }); + const token = cipher.encrypt(PLAIN, 'settlement-account'); + const parts = token.split('.'); + const flip = (text: string) => + (text[0] === 'A' ? 'B' : 'A') + text.slice(1); + const withPart = (index: number, value: string) => + parts.map((p, i) => (i === index ? value : p)).join('.'); + + it.each([ + ['암호문', withPart(4, flip(parts[4])), '복호화 실패'], + ['인증 태그', withPart(3, flip(parts[3])), '복호화 실패'], + ['IV', withPart(2, flip(parts[2])), '복호화 실패'], + ['짧은 태그', withPart(3, parts[3].slice(0, 8)), '복호화 실패'], + ['다른 키의 keyId', withPart(1, 'k2'), '복호화 실패'], + ['모르는 버전', withPart(0, 'v2'), '형식'], + ['조각 수', parts.slice(0, 4).join('.'), '형식'], + ['평문', PLAIN, '형식'], + ])('%s를 바꾸면 던지고 원문을 싣지 않는다', (_label, tampered, message) => { + let error: Error | undefined; + try { + cipher.decrypt(tampered, 'settlement-account'); + } catch (e) { + error = e as Error; + } + expect(error?.message).toContain(message); + expect(error?.message).not.toContain(PLAIN); + }); + }); + + it('키가 하나도 없으면 만들 수 없다', () => { + expect(() => new AccountCipher({ keys: [] })).toThrow('at least one key'); + }); +}); + +describe('CryptoModule', () => { + async function resolve(env: NodeJS.ProcessEnv) { + const warn = jest.fn(); + const module = await Test.createTestingModule({ + imports: [ + { + module: class CryptoDeps {}, + global: true, + providers: [ + { + provide: ConfigService, + useValue: new ConfigService({ + accountCrypto: readAccountCryptoConfig(env), + }), + }, + { provide: CustomLoggerService, useValue: { warn } }, + ], + exports: [ConfigService, CustomLoggerService], + }, + CryptoModule, + ], + }).compile(); + const cipher = module.get(AccountCipher); + await module.close(); + return { cipher, warn }; + } + + it('설정한 키로 AccountCipher를 만들고 경고하지 않는다', async () => { + const key = testAccountKey('k7'); + const { cipher, warn } = await resolve({ + ACCOUNT_ENCRYPTION_KEYS: `k7:${key.key.toString('base64')}`, + }); + expect(cipher.primaryKeyId).toBe('k7'); + expect(warn).not.toHaveBeenCalled(); + }); + + it('비운영에서 키가 없으면 개발 키로 만들고 경고한다', async () => { + const { cipher, warn } = await resolve({}); + expect(cipher.primaryKeyId).toBe('dev'); + expect(warn).toHaveBeenCalledWith( + expect.stringContaining('고정 개발 키'), + 'AccountCipher', + ); + }); +}); diff --git a/src/global/crypto/account-cipher.service.ts b/src/global/crypto/account-cipher.service.ts new file mode 100644 index 00000000..bf01c5b1 --- /dev/null +++ b/src/global/crypto/account-cipher.service.ts @@ -0,0 +1,77 @@ +import { createCipheriv, createDecipheriv, randomBytes } from 'node:crypto'; + +import type { AccountCryptoConfig } from '@/config/account-crypto.config'; + +/** AAD로 묶는 용도. 한 용도의 토큰을 다른 용도 칼럼에 옮겨 붙이면 풀리지 않는다. */ +export type AccountCipherPurpose = 'refund-account' | 'settlement-account'; + +const VERSION = 'v1'; +const ALGORITHM = 'aes-256-gcm'; +const IV_BYTES = 12; +const TAG_BYTES = 16; + +const b64url = (buf: Buffer): string => buf.toString('base64url'); +const fromB64url = (text: string): Buffer => Buffer.from(text, 'base64url'); + +/** + * 환불·정산 계좌번호 암호화(AES-256-GCM). 토큰 `v1....`(b64url)에 keyId가 있어 + * 키를 회전해도 옛 토큰을 풀 수 있다. 실패는 던지되 메시지에 평문·토큰을 싣지 않는다. + */ +export class AccountCipher { + readonly primaryKeyId: string; + private readonly keys: ReadonlyMap; + + constructor(config: Pick) { + const [primary] = config.keys; + if (!primary) throw new Error('AccountCipher needs at least one key'); + this.primaryKeyId = primary.id; + this.keys = new Map(config.keys.map((k) => [k.id, k.key])); + } + + encrypt(plain: string, purpose: AccountCipherPurpose): string { + const iv = randomBytes(IV_BYTES); + const cipher = createCipheriv( + ALGORITHM, + this.keys.get(this.primaryKeyId)!, + iv, + { authTagLength: TAG_BYTES }, + ); + cipher.setAAD(Buffer.from(purpose)); + const ct = Buffer.concat([cipher.update(plain, 'utf8'), cipher.final()]); + return [ + VERSION, + this.primaryKeyId, + b64url(iv), + b64url(cipher.getAuthTag()), + b64url(ct), + ].join('.'); + } + + decrypt(token: string, purpose: AccountCipherPurpose): string { + const parts = token.split('.'); + if (parts.length !== 5 || parts[0] !== VERSION) { + throw new Error('계좌번호 토큰 형식이 아닙니다'); + } + const [, keyId, iv, tag, ct] = parts; + const key = this.keys.get(keyId); + if (!key) throw new Error(`계좌번호 키(${keyId})가 설정에 없습니다`); + try { + const decipher = createDecipheriv(ALGORITHM, key, fromB64url(iv), { + authTagLength: TAG_BYTES, + }); + decipher.setAAD(Buffer.from(purpose)); + decipher.setAuthTag(fromB64url(tag)); + return Buffer.concat([ + decipher.update(fromB64url(ct)), + decipher.final(), + ]).toString('utf8'); + } catch { + throw new Error('계좌번호 복호화 실패(용도 불일치 또는 변조)'); + } + } + + /** 첫 키가 아닌 키로 암호화된 토큰. 키 회전 뒤 재암호화 대상이다. */ + isStale(token: string): boolean { + return token.split('.')[1] !== this.primaryKeyId; + } +} diff --git a/src/global/crypto/crypto.module.ts b/src/global/crypto/crypto.module.ts new file mode 100644 index 00000000..a78750c1 --- /dev/null +++ b/src/global/crypto/crypto.module.ts @@ -0,0 +1,28 @@ +import { Global, Module } from '@nestjs/common'; +import { ConfigService } from '@nestjs/config'; + +import type { AccountCryptoConfig } from '@/config/account-crypto.config'; +import { AccountCipher } from '@/global/crypto/account-cipher.service'; +import { CustomLoggerService } from '@/global/logger/custom-logger.service'; + +@Global() +@Module({ + providers: [ + { + provide: AccountCipher, + inject: [ConfigService, CustomLoggerService], + useFactory: (config: ConfigService, logger: CustomLoggerService) => { + const crypto = config.getOrThrow('accountCrypto'); + if (crypto.devKeyReason) { + logger.warn( + `계좌번호 암호화에 고정 개발 키를 씁니다: ${crypto.devKeyReason}`, + AccountCipher.name, + ); + } + return new AccountCipher(crypto); + }, + }, + ], + exports: [AccountCipher], +}) +export class CryptoModule {} diff --git a/src/test/account-cipher.ts b/src/test/account-cipher.ts new file mode 100644 index 00000000..95297a1d --- /dev/null +++ b/src/test/account-cipher.ts @@ -0,0 +1,13 @@ +import { randomBytes } from 'node:crypto'; + +import type { AccountCryptoKey } from '@/config/account-crypto.config'; +import { AccountCipher } from '@/global/crypto/account-cipher.service'; + +/** 테스트 키는 실행마다 만든다 — 운영·개발 키를 테스트에 두지 않는다. */ +export function testAccountKey(id = 'test'): AccountCryptoKey { + return { id, key: randomBytes(32) }; +} + +export function createTestAccountCipher(): AccountCipher { + return new AccountCipher({ keys: [testAccountKey()] }); +} From c31da2b4dd0f6ba278cd7df4ff9a0866a3c418f8 Mon Sep 17 00:00:00 2001 From: chanwoo7 Date: Thu, 19 Nov 2026 01:18:20 +0900 Subject: [PATCH 08/54] =?UTF-8?q?feat:=20=EA=B2=B0=EC=A0=9C=20=EC=84=A4?= =?UTF-8?q?=EC=A0=95=C2=B7=EB=A7=A4=EC=9E=A5=20=EC=A0=95=EC=82=B0=20?= =?UTF-8?q?=EA=B3=84=EC=A2=8C=20API=EC=99=80=20=EC=9D=80=ED=96=89=20?= =?UTF-8?q?=EB=AA=A9=EB=A1=9D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 케이퀵 입금 계좌·판매 수수료율(플랫폼 공통 1개)을 관리자가 설정하고, 매장 정산 계좌를 판매자 본인과 관리자가 등록·수정한다. 정산 계좌번호는 AccountCipher로 암호화해 두고 응답·감사에는 끝 4자리만 남기며, 원문 복호화는 관리자 매장 정산 계좌 조회에서만 한다. - 은행: order/constants/payment-banks.ts(금융결제원 3자리 25개), 공개 Query paymentBanks: [Bank!]!. 은행 코드는 목록 안(INVALID_BANK_CODE), 계좌번호는 하이픈 제거 뒤 숫자 8~20(INVALID_ACCOUNT_NUMBER), 예금주 1~50자(TEXT_REQUIRED·TEXT_TOO_LONG) - 결제 설정: adminPaymentSetting(행이 없으면 수수료 0·계좌 없음), adminUpdatePaymentSetting(보낸 필드만 변경, 수수료 0~10000bp INVALID_COMMISSION_RATE, 사유 필수, 첫 변경은 행 생성). 감사 PAYMENT_SETTING(변경 전·후 값 + 사유)이 같은 트랜잭션 - 정산 계좌: sellerSettlementAccount·sellerUpsertSettlementAccount, adminStoreSettlementAccount(storeId)(원문 포함, 등록 전 null)·adminUpsertStoreSettlementAccount(사유 필수). 매장 존재는 store 배럴의 StoreAdminRepository로 확인(STORE_NOT_FOUND). updated_by_role로 판매자 본인·관리자 대리 수정을 가르고, 감사 SETTLEMENT_ACCOUNT(생성·수정, 끝 4자리만)는 매장 ID를 달아 남김 - 판매자 감사 로그에 SETTLEMENT_ACCOUNT 노출(SELLER_AUDIT_TARGET_TYPES, 필터 매핑, SDL 설명) - 동시 첫 등록: 없는 행을 FOR UPDATE로 잡으면 갭 잠금끼리 교착하므로, 생성 경합은 unique 충돌로 받아 한 번 다시 돌린다(retryOnceOnUniqueConflict, 두 번째는 갱신 경로) - SDL: order-payment.graphql·order-payment-admin.graphql·order-settlement-seller.graphql, enum OrderActorType 신설(정산 계좌 updatedByRole) - 오류 코드: INVALID_BANK_CODE·INVALID_ACCOUNT_NUMBER·INVALID_COMMISSION_RATE(400) - 시드: seed-seller-a 매장 정산 계좌(앱과 같은 키 설정으로 암호화) - 게이트: roles-coverage seller 56 → 58, admin 60 → 64, enum-sdl-sync에 OrderActor ↔ OrderActorType. admin-query-null-inputs는 input 객체 admin Query가 늘지 않아 그대로(17) 테스트 - 은행·계좌 경계: 은행 코드 전수 통과·잘못된 코드 7, 계좌번호 통과 4·거절 8(7·21자리, 공백·영문·전각·하이픈만 등), 예금주 경계(50자·이모지 50·빈 값·51자) - 결제 설정(real DB): 행 부재 기본값 read, 첫 upsert 행 생성·감사 before 기본값, 보낸 필드만 변경, 수수료 경계 5(-1·0·10000·10001·1.5), 입력 오류 4종 무변경, 감사 실패 시 설정 미변경(같은 tx), 행 부재 동시 변경 2건 - 정산 계좌(real DB): 없는 매장·삭제된 매장 404, 등록 전 null·원문 복호화, 암호문·끝 4자리 저장과 감사에 원문·암호문 없음, 생성·수정 감사, 입력 오류 5종, 감사 실패 시 미변경, 동시 첫 등록 2건(행 1개, CREATE·UPDATE 각 1), 판매자 등록·관리자 대리 수정 뒤 SELLER 복귀·권한 거절 - 리졸버 경로 3, 판매자 감사 로그(관리자 정산 계좌 기록 노출·다른 관리자 조작 제외, 필터 매핑), 입력 DTO(SETTLEMENT_ACCOUNT 허용·ACCOUNT 거절), 재시도 helper 4, 시드 정산 계좌 복호화와 정리·재시드 - 반증: 동시 첫 등록 재시도·매장 존재 확인·판매자 감사 노출 항목을 각각 지우면 해당 테스트 4건이 실패함을 확인 --- prisma/schema.prisma | 2 +- prisma/seed.ts | 4 +- prisma/seed/payments.ts | 35 +- src/common/errors/error-catalog.ts | 13 + src/common/utils/prisma-error.spec.ts | 39 +- src/common/utils/prisma-error.ts | 20 + .../audit-log/audit-log.types.graphql | 4 +- .../constants/audit-log.constants.ts | 2 + src/features/order/constants/payment-banks.ts | 30 ++ .../admin-update-payment-setting.input.ts | 26 ++ ...n-upsert-store-settlement-account.input.ts | 22 + .../seller-upsert-settlement-account.input.ts | 13 + .../order/order-payment-admin.graphql | 138 ++++++ src/features/order/order-payment.graphql | 21 + .../order/order-settlement-seller.graphql | 63 +++ src/features/order/order.module.ts | 19 + src/features/order/order.types.graphql | 14 + .../payment-setting.repository.ts | 112 +++++ .../store-settlement-account.repository.ts | 97 +++++ .../order-payment-admin-mutation.resolver.ts | 47 ++ .../order-payment-admin-query.resolver.ts | 42 ++ .../resolvers/order-payment-query.resolver.ts | 13 + .../resolvers/order-payment.resolver.spec.ts | 131 ++++++ ...der-settlement-seller-mutation.resolver.ts | 32 ++ .../order-settlement-seller-query.resolver.ts | 27 ++ .../order-bank-account.helper.spec.ts | 98 +++++ .../services/order-bank-account.helper.ts | 56 +++ .../order-payment-admin.service.spec.ts | 412 ++++++++++++++++++ .../services/order-payment-admin.service.ts | 137 ++++++ .../services/order-payment-mappers.helper.ts | 46 ++ .../order-settlement-seller.service.spec.ts | 143 ++++++ .../order-settlement-seller.service.ts | 48 ++ .../order/types/order-payment-output.type.ts | 28 ++ .../seller-audit-log-list.input.spec.ts | 8 + .../store-seller-audit.service.spec.ts | 32 +- .../services/store-seller-audit.service.ts | 1 + src/test/enum-sdl-sync.spec.ts | 7 + src/test/roles-coverage.spec.ts | 4 +- src/test/seed-reset-scope.spec.ts | 55 ++- 39 files changed, 2014 insertions(+), 27 deletions(-) create mode 100644 src/features/order/constants/payment-banks.ts create mode 100644 src/features/order/dto/inputs/admin-update-payment-setting.input.ts create mode 100644 src/features/order/dto/inputs/admin-upsert-store-settlement-account.input.ts create mode 100644 src/features/order/dto/inputs/seller-upsert-settlement-account.input.ts create mode 100644 src/features/order/order-payment-admin.graphql create mode 100644 src/features/order/order-payment.graphql create mode 100644 src/features/order/order-settlement-seller.graphql create mode 100644 src/features/order/repositories/payment-setting.repository.ts create mode 100644 src/features/order/repositories/store-settlement-account.repository.ts create mode 100644 src/features/order/resolvers/order-payment-admin-mutation.resolver.ts create mode 100644 src/features/order/resolvers/order-payment-admin-query.resolver.ts create mode 100644 src/features/order/resolvers/order-payment-query.resolver.ts create mode 100644 src/features/order/resolvers/order-payment.resolver.spec.ts create mode 100644 src/features/order/resolvers/order-settlement-seller-mutation.resolver.ts create mode 100644 src/features/order/resolvers/order-settlement-seller-query.resolver.ts create mode 100644 src/features/order/services/order-bank-account.helper.spec.ts create mode 100644 src/features/order/services/order-bank-account.helper.ts create mode 100644 src/features/order/services/order-payment-admin.service.spec.ts create mode 100644 src/features/order/services/order-payment-admin.service.ts create mode 100644 src/features/order/services/order-payment-mappers.helper.ts create mode 100644 src/features/order/services/order-settlement-seller.service.spec.ts create mode 100644 src/features/order/services/order-settlement-seller.service.ts create mode 100644 src/features/order/types/order-payment-output.type.ts diff --git a/prisma/schema.prisma b/prisma/schema.prisma index f112e454..c295faed 100644 --- a/prisma/schema.prisma +++ b/prisma/schema.prisma @@ -199,7 +199,7 @@ enum AuditTargetType { ORDER CONVERSATION CHANGE_PASSWORD - // 이하 관리자 조작 대상. 판매자 감사 로그 조회는 위 5종만 보여준다. + // 이하 관리자 조작 대상. 판매자 감사 로그 조회는 위 5종과 SETTLEMENT_ACCOUNT만 보여준다. ACCOUNT BANNER CATEGORY diff --git a/prisma/seed.ts b/prisma/seed.ts index f5bd4bba..ce0f2735 100644 --- a/prisma/seed.ts +++ b/prisma/seed.ts @@ -86,8 +86,8 @@ async function main(): Promise { log('관리자 시드 중...'); const admin = await seedAdmins(prisma); - log('결제 설정·결제·환불·입금 기록 시드 중...'); - await seedPayments(prisma, { orders, admin }); + log('결제 설정·결제·환불·입금 기록·정산 계좌 시드 중...'); + await seedPayments(prisma, { orders, stores, admin }); log('완료. 발급된 테스트 계정:'); for (const u of users) { diff --git a/prisma/seed/payments.ts b/prisma/seed/payments.ts index 5060b233..93309a82 100644 --- a/prisma/seed/payments.ts +++ b/prisma/seed/payments.ts @@ -1,14 +1,18 @@ /** - * 결제 설정·결제·환불·입금 기록 시드. seedOrders의 o7~o11에 붙이고, 처리자는 시드 관리자다. + * 결제 설정·결제·환불·입금 기록·정산 계좌 시드. seedOrders의 o7~o11에 붙이고, 처리자는 시드 관리자다. * o7 입금 대기(PENDING, 1시간 기한) * o8·o11 관리자 입금 확인(CONFIRMED) * o9 확인된 결제 + 부분 환불 요청(계좌 입력 대기) * o10 미입금 취소(CANCELED) + 늦은 입금을 반환 대상으로 연결 * 결제 설정은 resetSeedScope가 지우지 않는 단일 행이라 upsert한다. + * seed-seller-a 매장 정산 계좌는 앱과 같은 키 설정(ACCOUNT_ENCRYPTION_KEYS, 없으면 개발 키)으로 암호화한다. */ import type { SeededOrders } from './orders'; +import type { SeededStores } from './stores'; +import { readAccountCryptoConfig } from '@/config/account-crypto.config'; import type { Payment, PrismaClient } from '@/generated/prisma/client'; +import { AccountCipher } from '@/global/crypto/account-cipher.service'; const DEPOSIT_ACCOUNT = { deposit_bank_code: '004', @@ -18,9 +22,19 @@ const DEPOSIT_ACCOUNT = { const PAYMENT_WINDOW_MS = 60 * 60 * 1000; +export const SEED_SETTLEMENT_ACCOUNT = { + bank_code: '088', + account_holder: '케이크샵 A', + account_number: '110123456789', +} as const; + export async function seedPayments( prisma: PrismaClient, - ctx: { orders: SeededOrders; admin: { id: bigint; label: string | null } }, + ctx: { + orders: SeededOrders; + stores: SeededStores; + admin: { id: bigint; label: string | null }; + }, ): Promise { await prisma.paymentSetting.upsert({ where: { id: 1 }, @@ -103,4 +117,21 @@ export async function seedPayments( requested_at: lateDepositAt, }, }); + + const [storeA] = ctx.stores.stores; + const cipher = new AccountCipher(readAccountCryptoConfig()); + await prisma.storeSettlementAccount.create({ + data: { + store_id: storeA.id, + bank_code: SEED_SETTLEMENT_ACCOUNT.bank_code, + account_holder: SEED_SETTLEMENT_ACCOUNT.account_holder, + account_number_enc: cipher.encrypt( + SEED_SETTLEMENT_ACCOUNT.account_number, + 'settlement-account', + ), + account_number_last4: SEED_SETTLEMENT_ACCOUNT.account_number.slice(-4), + updated_by_account_id: storeA.seller_account_id, + updated_by_role: 'SELLER', + }, + }); } diff --git a/src/common/errors/error-catalog.ts b/src/common/errors/error-catalog.ts index f3191925..5b55082a 100644 --- a/src/common/errors/error-catalog.ts +++ b/src/common/errors/error-catalog.ts @@ -375,6 +375,19 @@ export const ERROR_CATALOG = { status: HttpStatus.INTERNAL_SERVER_ERROR, message: '주문번호 생성에 실패했습니다. 잠시 후 다시 시도해 주세요.', }, + // ── 결제·정산 + INVALID_BANK_CODE: { + status: HttpStatus.BAD_REQUEST, + message: '지원하지 않는 은행입니다. 은행을 다시 선택해 주세요.', + }, + INVALID_ACCOUNT_NUMBER: { + status: HttpStatus.BAD_REQUEST, + message: '계좌번호는 하이픈(-)을 뺀 숫자 8~20자리로 입력해 주세요.', + }, + INVALID_COMMISSION_RATE: { + status: HttpStatus.BAD_REQUEST, + message: '수수료율은 0~10000bp(0~100%) 사이 정수여야 합니다.', + }, // ── 판매자 SELLER_ONLY: { status: HttpStatus.FORBIDDEN, diff --git a/src/common/utils/prisma-error.spec.ts b/src/common/utils/prisma-error.spec.ts index b7ade617..18db5d1a 100644 --- a/src/common/utils/prisma-error.spec.ts +++ b/src/common/utils/prisma-error.spec.ts @@ -1,4 +1,7 @@ -import { uniqueConstraintName } from '@/common/utils/prisma-error'; +import { + retryOnceOnUniqueConflict, + uniqueConstraintName, +} from '@/common/utils/prisma-error'; import { Prisma } from '@/generated/prisma/client'; function p2002( @@ -51,3 +54,37 @@ describe('uniqueConstraintName', () => { expect(uniqueConstraintName(err)).toBeNull(); }); }); + +describe('retryOnceOnUniqueConflict', () => { + it('P2002면 한 번 다시 돌리고 그 결과를 돌려준다', async () => { + const run = jest + .fn, []>() + .mockRejectedValueOnce(p2002({})) + .mockResolvedValueOnce('ok'); + await expect(retryOnceOnUniqueConflict(run)).resolves.toBe('ok'); + expect(run).toHaveBeenCalledTimes(2); + }); + + it('두 번째도 P2002면 그대로 던진다(무한 재시도 없음)', async () => { + const run = jest.fn, []>().mockRejectedValue(p2002({})); + await expect(retryOnceOnUniqueConflict(run)).rejects.toMatchObject({ + code: 'P2002', + }); + expect(run).toHaveBeenCalledTimes(2); + }); + + it.each([ + [ + '다른 Prisma 오류', + new Prisma.PrismaClientKnownRequestError('x', { + code: 'P2025', + clientVersion: 'test', + }), + ], + ['일반 오류', new Error('boom')], + ])('%s는 재시도하지 않는다', async (_label, error) => { + const run = jest.fn, []>().mockRejectedValue(error); + await expect(retryOnceOnUniqueConflict(run)).rejects.toBe(error); + expect(run).toHaveBeenCalledTimes(1); + }); +}); diff --git a/src/common/utils/prisma-error.ts b/src/common/utils/prisma-error.ts index 2d776f18..f2d298a7 100644 --- a/src/common/utils/prisma-error.ts +++ b/src/common/utils/prisma-error.ts @@ -24,3 +24,23 @@ export function uniqueConstraintName( if (constraint?.fields?.length) return constraint.fields.join(','); return null; } + +/** + * 없는 행을 동시에 만들면 한쪽이 unique 충돌(P2002)로 진다. 한 번만 다시 돌리면 그때는 이미 생긴 행의 + * 갱신 경로를 탄다. 없는 행을 FOR UPDATE로 잡으면 갭 잠금끼리 교착하므로 이 방식으로 경합을 받는다. + */ +export async function retryOnceOnUniqueConflict( + run: () => Promise, +): Promise { + try { + return await run(); + } catch (error) { + if ( + !(error instanceof Prisma.PrismaClientKnownRequestError) || + error.code !== 'P2002' + ) { + throw error; + } + return run(); + } +} diff --git a/src/features/audit-log/audit-log.types.graphql b/src/features/audit-log/audit-log.types.graphql index 36e514d5..0acde0c5 100644 --- a/src/features/audit-log/audit-log.types.graphql +++ b/src/features/audit-log/audit-log.types.graphql @@ -1,5 +1,5 @@ """ -감사 로그가 가리키는 대상 종류. 판매자 화면(sellerAuditLogs)은 STORE·PRODUCT·ORDER·CONVERSATION·CHANGE_PASSWORD만 노출하고 필터 입력도 그 범위만 받는다. +감사 로그가 가리키는 대상 종류. 판매자 화면(sellerAuditLogs)은 STORE·PRODUCT·ORDER·CONVERSATION·CHANGE_PASSWORD·SETTLEMENT_ACCOUNT만 노출하고 필터 입력도 그 범위만 받는다. """ enum AuditTargetType { """ @@ -67,7 +67,7 @@ enum AuditTargetType { """ PAYMENT_SETTING """ - 매장 정산 계좌. 기록에는 계좌번호 마스킹 값만 남는다. + 매장 정산 계좌(판매자 본인·관리자 대리 수정). 기록에는 계좌번호 끝 4자리만 남고, 판매자 감사 로그에도 보인다. """ SETTLEMENT_ACCOUNT """ diff --git a/src/features/audit-log/constants/audit-log.constants.ts b/src/features/audit-log/constants/audit-log.constants.ts index 2935705b..31479dcf 100644 --- a/src/features/audit-log/constants/audit-log.constants.ts +++ b/src/features/audit-log/constants/audit-log.constants.ts @@ -1,9 +1,11 @@ // 판매자 화면(내 매장 감사 로그)에 노출하는 대상 종류. 관리자 조작(REVIEW·ACCOUNT 등)은 매장 ID가 달려도 제외한다. +// 정산 계좌는 관리자 대리 수정도 판매자가 알아야 해 넣는다(기록은 끝 4자리만). export const SELLER_AUDIT_TARGET_TYPES = [ 'STORE', 'PRODUCT', 'ORDER', 'CONVERSATION', 'CHANGE_PASSWORD', + 'SETTLEMENT_ACCOUNT', ] as const; export type SellerAuditTargetType = (typeof SELLER_AUDIT_TARGET_TYPES)[number]; diff --git a/src/features/order/constants/payment-banks.ts b/src/features/order/constants/payment-banks.ts new file mode 100644 index 00000000..2a8ac418 --- /dev/null +++ b/src/features/order/constants/payment-banks.ts @@ -0,0 +1,30 @@ +/** 금융결제원 은행 코드(3자리). 환불·정산·케이퀵 입금 계좌가 같은 목록을 쓰고, 화면 표시는 이 순서다. */ +export const PAYMENT_BANKS = [ + { code: '004', name: 'KB국민은행' }, + { code: '088', name: '신한은행' }, + { code: '020', name: '우리은행' }, + { code: '081', name: '하나은행' }, + { code: '011', name: 'NH농협은행' }, + { code: '012', name: '지역농축협' }, + { code: '003', name: 'IBK기업은행' }, + { code: '090', name: '카카오뱅크' }, + { code: '092', name: '토스뱅크' }, + { code: '089', name: '케이뱅크' }, + { code: '002', name: 'KDB산업은행' }, + { code: '007', name: '수협은행' }, + { code: '023', name: 'SC제일은행' }, + { code: '027', name: '한국씨티은행' }, + { code: '031', name: 'iM뱅크' }, + { code: '032', name: '부산은행' }, + { code: '034', name: '광주은행' }, + { code: '035', name: '제주은행' }, + { code: '037', name: '전북은행' }, + { code: '039', name: '경남은행' }, + { code: '045', name: '새마을금고' }, + { code: '048', name: '신협' }, + { code: '050', name: '저축은행' }, + { code: '064', name: '산림조합' }, + { code: '071', name: '우체국' }, +] as const satisfies readonly { code: string; name: string }[]; + +export const MAX_ACCOUNT_HOLDER_LENGTH = 50; diff --git a/src/features/order/dto/inputs/admin-update-payment-setting.input.ts b/src/features/order/dto/inputs/admin-update-payment-setting.input.ts new file mode 100644 index 00000000..cb8bdadf --- /dev/null +++ b/src/features/order/dto/inputs/admin-update-payment-setting.input.ts @@ -0,0 +1,26 @@ +import { IsInt, IsOptional, IsString, MaxLength } from 'class-validator'; + +import { MAX_REASON_LENGTH } from '@/common/constants/reason.constants'; + +// 범위·은행·계좌 형식은 서비스가 도메인 오류 코드로 거절한다 +export class AdminUpdatePaymentSettingInput { + @IsOptional() + @IsInt() + commissionRateBps?: number | null; + + @IsOptional() + @IsString() + depositBankCode?: string | null; + + @IsOptional() + @IsString() + depositAccountNumber?: string | null; + + @IsOptional() + @IsString() + depositAccountHolder?: string | null; + + @IsString() + @MaxLength(MAX_REASON_LENGTH) + reason!: string; +} diff --git a/src/features/order/dto/inputs/admin-upsert-store-settlement-account.input.ts b/src/features/order/dto/inputs/admin-upsert-store-settlement-account.input.ts new file mode 100644 index 00000000..2d904c69 --- /dev/null +++ b/src/features/order/dto/inputs/admin-upsert-store-settlement-account.input.ts @@ -0,0 +1,22 @@ +import { IsString, MaxLength } from 'class-validator'; + +import { MAX_REASON_LENGTH } from '@/common/constants/reason.constants'; + +// 은행·계좌번호·예금주 형식은 서비스가 도메인 오류 코드로 거절한다 +export class AdminUpsertStoreSettlementAccountInput { + @IsString() + storeId!: string; + + @IsString() + bankCode!: string; + + @IsString() + accountHolder!: string; + + @IsString() + accountNumber!: string; + + @IsString() + @MaxLength(MAX_REASON_LENGTH) + reason!: string; +} diff --git a/src/features/order/dto/inputs/seller-upsert-settlement-account.input.ts b/src/features/order/dto/inputs/seller-upsert-settlement-account.input.ts new file mode 100644 index 00000000..5dfeb46a --- /dev/null +++ b/src/features/order/dto/inputs/seller-upsert-settlement-account.input.ts @@ -0,0 +1,13 @@ +import { IsString } from 'class-validator'; + +// 은행·계좌번호·예금주 형식은 서비스가 도메인 오류 코드로 거절한다 +export class SellerUpsertSettlementAccountInput { + @IsString() + bankCode!: string; + + @IsString() + accountHolder!: string; + + @IsString() + accountNumber!: string; +} diff --git a/src/features/order/order-payment-admin.graphql b/src/features/order/order-payment-admin.graphql new file mode 100644 index 00000000..65694d3c --- /dev/null +++ b/src/features/order/order-payment-admin.graphql @@ -0,0 +1,138 @@ +extend type Query { + """ + 플랫폼 결제 설정(판매 수수료율·케이퀵 입금 계좌)을 조회한다. 설정한 적이 없으면 수수료 0, 입금 계좌 없음이다. + 관리자 로그인 필수. ADMIN 계정이 아니면 FORBIDDEN. + """ + adminPaymentSetting: AdminPaymentSetting! + """ + 매장 정산 계좌를 계좌번호 원문과 함께 조회한다. 등록 전이면 null, 없는 매장이면 NOT_FOUND. + 관리자 로그인 필수. ADMIN 계정이 아니면 FORBIDDEN. + """ + adminStoreSettlementAccount(storeId: ID!): AdminStoreSettlementAccount +} + +extend type Mutation { + """ + 플랫폼 결제 설정을 바꾼다. 보낸 필드만 바꾸고 생략·null인 필드는 그대로 둔다. 수수료율은 바꾼 뒤 생성되는 주문부터 적용된다. + 수수료율이 0~10000bp 밖이면 INVALID_COMMISSION_RATE, 은행 코드가 paymentBanks에 없으면 INVALID_BANK_CODE, + 계좌번호가 하이픈을 뺀 숫자 8~20자리가 아니면 INVALID_ACCOUNT_NUMBER, 예금주·사유가 비었거나 길면 TEXT_REQUIRED·TEXT_TOO_LONG + (모두 BAD_USER_INPUT). 감사 로그(PAYMENT_SETTING)를 남긴다. 관리자 로그인 필수. ADMIN 계정이 아니면 FORBIDDEN. + """ + adminUpdatePaymentSetting( + input: AdminUpdatePaymentSettingInput! + ): AdminPaymentSetting! + """ + 매장 정산 계좌를 등록하거나 바꾼다(관리자 대리 수정). 계좌번호는 암호화해 저장하고, 감사 로그(SETTLEMENT_ACCOUNT)에는 + 끝 4자리만 남는다. 이 기록은 판매자 감사 로그에도 보인다. 없는 매장이면 NOT_FOUND, 은행·계좌번호·예금주·사유 오류는 + adminUpdatePaymentSetting과 같은 코드(BAD_USER_INPUT). 관리자 로그인 필수. ADMIN 계정이 아니면 FORBIDDEN. + """ + adminUpsertStoreSettlementAccount( + input: AdminUpsertStoreSettlementAccountInput! + ): AdminStoreSettlementAccount! +} + +""" +플랫폼 결제 설정. 플랫폼 전체에 하나뿐이다. +""" +type AdminPaymentSetting { + """ + 판매 수수료율(bp, 1bp = 0.01%). 0~10000. 주문 생성 시점의 값이 주문에 저장된다. + """ + commissionRateBps: Int! + """ + 구매자가 입금할 케이퀵 계좌의 은행. 설정 전이면 null. + """ + depositBank: Bank + """ + 케이퀵 입금 계좌번호(숫자만). 설정 전이면 null. + """ + depositAccountNumber: String + """ + 케이퀵 입금 계좌 예금주. 설정 전이면 null. + """ + depositAccountHolder: String + """ + 마지막 변경 시각. 설정한 적이 없으면 null. + """ + updatedAt: DateTime +} + +""" +매장 정산 계좌(관리자 시점). 계좌번호 원문이 들어 있으니 화면 밖(로그·분석 이벤트)에 남기지 않는다. +""" +type AdminStoreSettlementAccount { + storeId: ID! + """ + 은행. + """ + 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! +} diff --git a/src/features/order/order-payment.graphql b/src/features/order/order-payment.graphql new file mode 100644 index 00000000..fcc9073a --- /dev/null +++ b/src/features/order/order-payment.graphql @@ -0,0 +1,21 @@ +extend type Query { + """ + 계좌 입력 화면의 은행 목록(금융결제원 3자리 코드). 환불 계좌·정산 계좌·케이퀵 입금 계좌가 같은 목록을 쓰고, + 배열 순서가 표시 순서다. 로그인 없이 조회할 수 있다. + """ + paymentBanks: [Bank!]! +} + +""" +은행. +""" +type Bank { + """ + 금융결제원 3자리 은행 코드(예: 004). 계좌 입력 mutation의 bankCode로 그대로 보낸다. + """ + code: String! + """ + 은행 이름(예: KB국민은행). 목록에서 빠진 옛 코드면 코드를 그대로 준다. + """ + name: String! +} diff --git a/src/features/order/order-settlement-seller.graphql b/src/features/order/order-settlement-seller.graphql new file mode 100644 index 00000000..74627014 --- /dev/null +++ b/src/features/order/order-settlement-seller.graphql @@ -0,0 +1,63 @@ +extend type Query { + """ + 내 매장 정산 계좌를 조회한다. 계좌번호는 끝 4자리만 내려준다. 등록 전이면 null. + 판매자 로그인 필수. SELLER 계정이 아니면 FORBIDDEN, 매장을 보유하지 않으면 NOT_FOUND. + """ + sellerSettlementAccount: SellerSettlementAccount +} + +extend type Mutation { + """ + 내 매장 정산 계좌를 등록하거나 바꾼다. 계좌번호는 암호화해 저장하고, 응답과 감사 로그(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. + """ + sellerUpsertSettlementAccount( + input: SellerUpsertSettlementAccountInput! + ): SellerSettlementAccount! +} + +""" +내 매장 정산 계좌(판매자 시점). 계좌번호 원문은 내려주지 않는다. +""" +type SellerSettlementAccount { + """ + 은행. + """ + bank: Bank! + """ + 예금주. + """ + accountHolder: String! + """ + 끝 4자리만 남긴 계좌번호(예: ****1234). + """ + accountNumberMasked: String! + """ + 마지막으로 바꾼 주체. SELLER는 본인, ADMIN은 관리자가 대신 바꾼 경우다. + """ + updatedByRole: OrderActorType! + """ + 마지막 변경 시각. + """ + updatedAt: DateTime! +} + +""" +정산 계좌 등록·변경 입력. +""" +input SellerUpsertSettlementAccountInput { + """ + 은행 코드(paymentBanks의 code). + """ + bankCode: String! + """ + 예금주(1~50자). + """ + accountHolder: String! + """ + 계좌번호. 하이픈을 빼고 숫자 8~20자리여야 하며 숫자만 저장한다. + """ + accountNumber: String! +} diff --git a/src/features/order/order.module.ts b/src/features/order/order.module.ts index dfe5cfc4..93370974 100644 --- a/src/features/order/order.module.ts +++ b/src/features/order/order.module.ts @@ -7,18 +7,27 @@ import { OrderStatusTransitionPolicy } from '@/features/order/policies/order-sta import { OrderBookedRepository } from '@/features/order/repositories/order-booked.repository'; import { OrderStoreDailyLimitRepository } from '@/features/order/repositories/order-store-daily-limit.repository'; import { OrderRepository } from '@/features/order/repositories/order.repository'; +import { PaymentSettingRepository } from '@/features/order/repositories/payment-setting.repository'; +import { StoreSettlementAccountRepository } from '@/features/order/repositories/store-settlement-account.repository'; import { AdminOrderMutationResolver } from '@/features/order/resolvers/order-admin-mutation.resolver'; import { AdminOrderQueryResolver } from '@/features/order/resolvers/order-admin-query.resolver'; import { OrderCheckoutMutationResolver } from '@/features/order/resolvers/order-checkout-mutation.resolver'; import { UserOrderQueryResolver } from '@/features/order/resolvers/order-my-query.resolver'; +import { AdminPaymentMutationResolver } from '@/features/order/resolvers/order-payment-admin-mutation.resolver'; +import { AdminPaymentQueryResolver } from '@/features/order/resolvers/order-payment-admin-query.resolver'; +import { PaymentQueryResolver } from '@/features/order/resolvers/order-payment-query.resolver'; import { SellerOrderMutationResolver } from '@/features/order/resolvers/order-seller-mutation.resolver'; import { SellerOrderQueryResolver } from '@/features/order/resolvers/order-seller-query.resolver'; +import { SellerSettlementMutationResolver } from '@/features/order/resolvers/order-settlement-seller-mutation.resolver'; +import { SellerSettlementQueryResolver } from '@/features/order/resolvers/order-settlement-seller-query.resolver'; import { OrderSubscriptionResolver } from '@/features/order/resolvers/order-subscription.resolver'; import { AdminOrderService } from '@/features/order/services/order-admin.service'; import { OrderCheckoutService } from '@/features/order/services/order-checkout.service'; import { OrderEventsService } from '@/features/order/services/order-events.service'; import { UserOrderService } from '@/features/order/services/order-my.service'; +import { AdminPaymentService } from '@/features/order/services/order-payment-admin.service'; import { SellerOrderService } from '@/features/order/services/order-seller.service'; +import { SellerSettlementService } from '@/features/order/services/order-settlement-seller.service'; import { OrderStoreDailyLimitConsumer } from '@/features/order/services/order-store-daily-limit.consumer'; import { OrderSubscriptionService } from '@/features/order/services/order-subscription.service'; import { OutboxModule } from '@/features/outbox'; @@ -60,6 +69,16 @@ import { StoreModule } from '@/features/store'; // 구매자 주문 목록·상세 UserOrderService, UserOrderQueryResolver, + // 결제 설정·매장 정산 계좌(계좌번호는 global AccountCipher로 암호화) + PaymentSettingRepository, + StoreSettlementAccountRepository, + PaymentQueryResolver, + AdminPaymentService, + AdminPaymentQueryResolver, + AdminPaymentMutationResolver, + SellerSettlementService, + SellerSettlementQueryResolver, + SellerSettlementMutationResolver, ], exports: [ OrderRepository, diff --git a/src/features/order/order.types.graphql b/src/features/order/order.types.graphql index a08bb093..be239f71 100644 --- a/src/features/order/order.types.graphql +++ b/src/features/order/order.types.graphql @@ -23,6 +23,20 @@ enum OrderStatusType { CANCELED } +""" +주문·결제·정산 기록을 남긴 주체. 값은 늘어날 수 있으니 모르는 값을 받아도 화면이 죽지 않게 처리한다. +""" +enum OrderActorType { + """구매자.""" + BUYER + """판매자.""" + SELLER + """관리자.""" + ADMIN + """시스템 자동 처리.""" + SYSTEM +} + """주문 상태 변경 이력 1건. 구매자·판매자·관리자 주문 상세가 공용으로 쓴다.""" type OrderStatusHistory { id: ID! diff --git a/src/features/order/repositories/payment-setting.repository.ts b/src/features/order/repositories/payment-setting.repository.ts new file mode 100644 index 00000000..f8c7cbb9 --- /dev/null +++ b/src/features/order/repositories/payment-setting.repository.ts @@ -0,0 +1,112 @@ +import { Inject, Injectable } from '@nestjs/common'; + +import { retryOnceOnUniqueConflict } from '@/common/utils/prisma-error'; +import { + AUDIT_LOG_REPOSITORY, + type IAuditLogRepository, +} from '@/features/audit-log'; +import { + AuditActionType, + AuditTargetType, + type PaymentSetting, +} from '@/generated/prisma/client'; +import { PrismaService } from '@/prisma'; + +const PAYMENT_SETTING_ID = 1; + +export type PaymentSettingValues = Pick< + PaymentSetting, + | 'commission_rate_bps' + | 'deposit_bank_code' + | 'deposit_account_number' + | 'deposit_account_holder' +>; + +export type PaymentSettingRow = PaymentSettingValues & { + updated_at: Date | null; +}; + +const DEFAULT_PAYMENT_SETTING: PaymentSettingValues = { + commission_rate_bps: 0, + deposit_bank_code: null, + deposit_account_number: null, + deposit_account_holder: null, +}; + +function valuesOf(row: PaymentSettingValues): PaymentSettingValues { + return { + commission_rate_bps: row.commission_rate_bps, + deposit_bank_code: row.deposit_bank_code, + deposit_account_number: row.deposit_account_number, + deposit_account_holder: row.deposit_account_holder, + }; +} + +/** 플랫폼 결제 설정 단일 행(id=1). 행이 없으면(테스트 truncate 등) 기본값으로 읽고, 쓰기는 upsert다. */ +@Injectable() +export class PaymentSettingRepository { + constructor( + private readonly prisma: PrismaService, + @Inject(AUDIT_LOG_REPOSITORY) + private readonly auditLogs: IAuditLogRepository, + ) {} + + async findPaymentSetting(): Promise { + const row = await this.prisma.paymentSetting.findUnique({ + where: { id: PAYMENT_SETTING_ID }, + }); + return row + ? { ...valuesOf(row), updated_at: row.updated_at } + : { ...DEFAULT_PAYMENT_SETTING, updated_at: null }; + } + + /** 준 필드만 바꾼다. 변경 전 값은 잠금 뒤에 읽어 감사에 남긴다(계좌는 케이퀵 공개 입금 계좌라 원문). */ + async updatePaymentSetting(args: { + patch: Partial; + actorAccountId: bigint; + reason: string; + }): Promise { + return retryOnceOnUniqueConflict(async () => { + const exists = await this.prisma.paymentSetting.findUnique({ + where: { id: PAYMENT_SETTING_ID }, + select: { id: true }, + }); + return this.prisma.$transaction(async (tx) => { + let before = DEFAULT_PAYMENT_SETTING; + if (exists) { + await tx.$queryRaw`SELECT id FROM payment_setting WHERE id = ${PAYMENT_SETTING_ID} FOR UPDATE`; + before = valuesOf( + await tx.paymentSetting.findUniqueOrThrow({ + where: { id: PAYMENT_SETTING_ID }, + }), + ); + } + // undefined 필드는 Prisma가 건너뛴다(생략 = 그대로) + const data = { + commission_rate_bps: args.patch.commission_rate_bps, + deposit_bank_code: args.patch.deposit_bank_code, + deposit_account_number: args.patch.deposit_account_number, + deposit_account_holder: args.patch.deposit_account_holder, + updated_by_account_id: args.actorAccountId, + }; + const after = exists + ? await tx.paymentSetting.update({ + where: { id: PAYMENT_SETTING_ID }, + data, + }) + : await tx.paymentSetting.create({ + data: { id: PAYMENT_SETTING_ID, ...data }, + }); + await this.auditLogs.recordAudit(tx, { + actorAccountId: args.actorAccountId, + targetType: AuditTargetType.PAYMENT_SETTING, + targetId: BigInt(PAYMENT_SETTING_ID), + action: AuditActionType.UPDATE, + beforeJson: { ...before }, + afterJson: { ...valuesOf(after), reason: args.reason }, + }); + return { ...valuesOf(after), updated_at: after.updated_at }; + }); + }); + } +} diff --git a/src/features/order/repositories/store-settlement-account.repository.ts b/src/features/order/repositories/store-settlement-account.repository.ts new file mode 100644 index 00000000..e0641489 --- /dev/null +++ b/src/features/order/repositories/store-settlement-account.repository.ts @@ -0,0 +1,97 @@ +import { Inject, Injectable } from '@nestjs/common'; + +import { retryOnceOnUniqueConflict } from '@/common/utils/prisma-error'; +import { + AUDIT_LOG_REPOSITORY, + type IAuditLogRepository, +} from '@/features/audit-log'; +import { + AuditActionType, + AuditTargetType, + type OrderActor, + type StoreSettlementAccount, +} from '@/generated/prisma/client'; +import { AccountCipher } from '@/global/crypto/account-cipher.service'; +import { PrismaService } from '@/prisma'; + +/** 감사에는 계좌번호 끝 4자리만 남긴다. */ +function maskedSnapshot(row: StoreSettlementAccount) { + return { + bank_code: row.bank_code, + account_holder: row.account_holder, + account_number_last4: row.account_number_last4, + }; +} + +@Injectable() +export class StoreSettlementAccountRepository { + constructor( + private readonly prisma: PrismaService, + @Inject(AUDIT_LOG_REPOSITORY) + private readonly auditLogs: IAuditLogRepository, + private readonly cipher: AccountCipher, + ) {} + + async findByStoreId(storeId: bigint): Promise { + return this.prisma.storeSettlementAccount.findUnique({ + where: { store_id: storeId }, + }); + } + + /** + * 매장당 1행. 판매자 본인·관리자 대리 수정이 같은 경로다. 계좌번호는 암호문과 끝 4자리로만 저장하고, + * 감사는 매장 ID를 달아 판매자 감사 로그에도 보인다. + */ + async upsertByStore(args: { + storeId: bigint; + account: { bankCode: string; accountHolder: string; accountNumber: string }; + actorAccountId: bigint; + actorRole: OrderActor; + reason?: string; + }): Promise { + const data = { + bank_code: args.account.bankCode, + account_holder: args.account.accountHolder, + account_number_enc: this.cipher.encrypt( + args.account.accountNumber, + 'settlement-account', + ), + account_number_last4: args.account.accountNumber.slice(-4), + updated_by_account_id: args.actorAccountId, + updated_by_role: args.actorRole, + }; + return retryOnceOnUniqueConflict(async () => { + const exists = await this.findByStoreId(args.storeId); + return this.prisma.$transaction(async (tx) => { + let before: StoreSettlementAccount | null = null; + if (exists) { + await tx.$queryRaw`SELECT id FROM store_settlement_account WHERE id = ${exists.id} FOR UPDATE`; + before = await tx.storeSettlementAccount.findUniqueOrThrow({ + where: { id: exists.id }, + }); + } + const after = before + ? await tx.storeSettlementAccount.update({ + where: { id: before.id }, + data, + }) + : await tx.storeSettlementAccount.create({ + data: { store_id: args.storeId, ...data }, + }); + await this.auditLogs.recordAudit(tx, { + actorAccountId: args.actorAccountId, + storeId: args.storeId, + targetType: AuditTargetType.SETTLEMENT_ACCOUNT, + targetId: after.id, + action: before ? AuditActionType.UPDATE : AuditActionType.CREATE, + beforeJson: before ? maskedSnapshot(before) : null, + afterJson: { + ...maskedSnapshot(after), + ...(args.reason ? { reason: args.reason } : {}), + }, + }); + return after; + }); + }); + } +} diff --git a/src/features/order/resolvers/order-payment-admin-mutation.resolver.ts b/src/features/order/resolvers/order-payment-admin-mutation.resolver.ts new file mode 100644 index 00000000..84862533 --- /dev/null +++ b/src/features/order/resolvers/order-payment-admin-mutation.resolver.ts @@ -0,0 +1,47 @@ +import { UseGuards } from '@nestjs/common'; +import { Args, Mutation, Resolver } from '@nestjs/graphql'; + +import { AdminUpdatePaymentSettingInput } from '@/features/order/dto/inputs/admin-update-payment-setting.input'; +import { AdminUpsertStoreSettlementAccountInput } from '@/features/order/dto/inputs/admin-upsert-store-settlement-account.input'; +import { AdminPaymentService } from '@/features/order/services/order-payment-admin.service'; +import type { + AdminPaymentSettingOutput, + AdminStoreSettlementAccountOutput, +} from '@/features/order/types/order-payment-output.type'; +import { + CurrentUser, + JwtAuthGuard, + Roles, + RolesGuard, + parseAccountId, + type JwtUser, +} from '@/global/auth'; + +@Resolver('Mutation') +@UseGuards(JwtAuthGuard, RolesGuard) +@Roles('ADMIN') +export class AdminPaymentMutationResolver { + constructor(private readonly paymentService: AdminPaymentService) {} + + @Mutation('adminUpdatePaymentSetting') + adminUpdatePaymentSetting( + @CurrentUser() user: JwtUser, + @Args('input') input: AdminUpdatePaymentSettingInput, + ): Promise { + return this.paymentService.adminUpdatePaymentSetting( + parseAccountId(user), + input, + ); + } + + @Mutation('adminUpsertStoreSettlementAccount') + adminUpsertStoreSettlementAccount( + @CurrentUser() user: JwtUser, + @Args('input') input: AdminUpsertStoreSettlementAccountInput, + ): Promise { + return this.paymentService.adminUpsertStoreSettlementAccount( + parseAccountId(user), + input, + ); + } +} diff --git a/src/features/order/resolvers/order-payment-admin-query.resolver.ts b/src/features/order/resolvers/order-payment-admin-query.resolver.ts new file mode 100644 index 00000000..8d0a9cb6 --- /dev/null +++ b/src/features/order/resolvers/order-payment-admin-query.resolver.ts @@ -0,0 +1,42 @@ +import { UseGuards } from '@nestjs/common'; +import { Args, Query, Resolver } from '@nestjs/graphql'; + +import { parseId } from '@/common/utils/id-parser'; +import { AdminPaymentService } from '@/features/order/services/order-payment-admin.service'; +import type { + AdminPaymentSettingOutput, + AdminStoreSettlementAccountOutput, +} from '@/features/order/types/order-payment-output.type'; +import { + CurrentUser, + JwtAuthGuard, + Roles, + RolesGuard, + parseAccountId, + type JwtUser, +} from '@/global/auth'; + +@Resolver('Query') +@UseGuards(JwtAuthGuard, RolesGuard) +@Roles('ADMIN') +export class AdminPaymentQueryResolver { + constructor(private readonly paymentService: AdminPaymentService) {} + + @Query('adminPaymentSetting') + adminPaymentSetting( + @CurrentUser() user: JwtUser, + ): Promise { + return this.paymentService.adminPaymentSetting(parseAccountId(user)); + } + + @Query('adminStoreSettlementAccount') + adminStoreSettlementAccount( + @CurrentUser() user: JwtUser, + @Args('storeId') storeId: string, + ): Promise { + return this.paymentService.adminStoreSettlementAccount( + parseAccountId(user), + parseId(storeId), + ); + } +} diff --git a/src/features/order/resolvers/order-payment-query.resolver.ts b/src/features/order/resolvers/order-payment-query.resolver.ts new file mode 100644 index 00000000..4689225b --- /dev/null +++ b/src/features/order/resolvers/order-payment-query.resolver.ts @@ -0,0 +1,13 @@ +import { Query, Resolver } from '@nestjs/graphql'; + +import { PAYMENT_BANKS } from '@/features/order/constants/payment-banks'; +import type { BankOutput } from '@/features/order/types/order-payment-output.type'; + +/** 계좌 입력 화면의 은행 목록. 고정 목록이라 로그인 없이 연다. */ +@Resolver('Query') +export class PaymentQueryResolver { + @Query('paymentBanks') + paymentBanks(): readonly BankOutput[] { + return PAYMENT_BANKS; + } +} diff --git a/src/features/order/resolvers/order-payment.resolver.spec.ts b/src/features/order/resolvers/order-payment.resolver.spec.ts new file mode 100644 index 00000000..cd65f2bb --- /dev/null +++ b/src/features/order/resolvers/order-payment.resolver.spec.ts @@ -0,0 +1,131 @@ +// 분기/검증 세부는 order-payment-admin.service.spec.ts·order-settlement-seller.service.spec.ts에서 담당. 여기서는 리졸버→서비스→DB 경로만 본다. + +import { AUDIT_LOG_REPOSITORY } from '@/features/audit-log'; +import { AuditLogRepository } from '@/features/audit-log/repositories/audit-log.repository'; +import { AccountAdminRepository } from '@/features/auth/repositories/account-admin.repository'; +import { PAYMENT_BANKS } from '@/features/order/constants/payment-banks'; +import { PaymentSettingRepository } from '@/features/order/repositories/payment-setting.repository'; +import { StoreSettlementAccountRepository } from '@/features/order/repositories/store-settlement-account.repository'; +import { AdminPaymentMutationResolver } from '@/features/order/resolvers/order-payment-admin-mutation.resolver'; +import { AdminPaymentQueryResolver } from '@/features/order/resolvers/order-payment-admin-query.resolver'; +import { PaymentQueryResolver } from '@/features/order/resolvers/order-payment-query.resolver'; +import { SellerSettlementMutationResolver } from '@/features/order/resolvers/order-settlement-seller-mutation.resolver'; +import { SellerSettlementQueryResolver } from '@/features/order/resolvers/order-settlement-seller-query.resolver'; +import { AdminPaymentService } from '@/features/order/services/order-payment-admin.service'; +import { SellerSettlementService } from '@/features/order/services/order-settlement-seller.service'; +import { StoreAdminRepository } from '@/features/store/repositories/store-admin.repository'; +import { StoreSellerRepository } from '@/features/store/repositories/store-seller.repository'; +import type { PrismaClient } from '@/generated/prisma/client'; +import { AccountCipher } from '@/global/crypto/account-cipher.service'; +import { createTestAccountCipher } from '@/test/account-cipher'; +import { disconnectTestPrismaClient } from '@/test/db/prisma-test-client'; +import { closeTruncateConnection, truncateAll } from '@/test/db/truncate'; +import { createAccount, setupSellerWithStore } from '@/test/factories'; +import { createTestingModuleWithRealDb } from '@/test/modules/testing-module.builder'; + +describe('결제 설정·정산 계좌 Resolvers (real DB)', () => { + let banks: PaymentQueryResolver; + let adminQuery: AdminPaymentQueryResolver; + let adminMutation: AdminPaymentMutationResolver; + let sellerQuery: SellerSettlementQueryResolver; + let sellerMutation: SellerSettlementMutationResolver; + let prisma: PrismaClient; + + beforeAll(async () => { + const { module, prisma: p } = await createTestingModuleWithRealDb({ + providers: [ + PaymentQueryResolver, + AdminPaymentQueryResolver, + AdminPaymentMutationResolver, + SellerSettlementQueryResolver, + SellerSettlementMutationResolver, + AdminPaymentService, + SellerSettlementService, + AccountAdminRepository, + StoreAdminRepository, + StoreSellerRepository, + PaymentSettingRepository, + StoreSettlementAccountRepository, + { provide: AUDIT_LOG_REPOSITORY, useClass: AuditLogRepository }, + { provide: AccountCipher, useValue: createTestAccountCipher() }, + ], + }); + banks = module.get(PaymentQueryResolver); + adminQuery = module.get(AdminPaymentQueryResolver); + adminMutation = module.get(AdminPaymentMutationResolver); + sellerQuery = module.get(SellerSettlementQueryResolver); + sellerMutation = module.get(SellerSettlementMutationResolver); + prisma = p; + }); + + afterAll(async () => { + await closeTruncateConnection(); + await disconnectTestPrismaClient(); + }); + + beforeEach(async () => { + await truncateAll(); + }); + + it('은행 목록은 상수 그대로다', () => { + expect(banks.paymentBanks()).toEqual(PAYMENT_BANKS); + }); + + it('관리자: 결제 설정 변경 → 조회', async () => { + const actor = await createAccount(prisma, { account_type: 'ADMIN' }); + const user = { + accountId: actor.id.toString(), + accountType: 'ADMIN' as const, + }; + + await adminMutation.adminUpdatePaymentSetting(user, { + commissionRateBps: 500, + reason: '수수료 5%', + }); + + expect(await adminQuery.adminPaymentSetting(user)).toMatchObject({ + commissionRateBps: 500, + depositBank: null, + }); + }); + + it('판매자 등록 → 관리자 원문 조회 → 관리자 대리 수정 → 판매자 조회', async () => { + const actor = await createAccount(prisma, { account_type: 'ADMIN' }); + const adminUser = { + accountId: actor.id.toString(), + accountType: 'ADMIN' as const, + }; + const { account, store } = await setupSellerWithStore(prisma); + const sellerUser = { + accountId: account.id.toString(), + accountType: 'SELLER' as const, + }; + + await sellerMutation.sellerUpsertSettlementAccount(sellerUser, { + bankCode: '088', + accountHolder: '케이크샵', + accountNumber: '110-123-456789', + }); + expect( + await adminQuery.adminStoreSettlementAccount( + adminUser, + store.id.toString(), + ), + ).toMatchObject({ accountNumber: '110123456789', updatedByRole: 'SELLER' }); + + await adminMutation.adminUpsertStoreSettlementAccount(adminUser, { + storeId: store.id.toString(), + bankCode: '004', + accountHolder: '케이크샵', + accountNumber: '12345678', + reason: '판매자 요청', + }); + expect(await sellerQuery.sellerSettlementAccount(sellerUser)).toMatchObject( + { + bank: { code: '004' }, + accountNumberMasked: '****5678', + updatedByRole: 'ADMIN', + }, + ); + }); +}); diff --git a/src/features/order/resolvers/order-settlement-seller-mutation.resolver.ts b/src/features/order/resolvers/order-settlement-seller-mutation.resolver.ts new file mode 100644 index 00000000..84f5eccd --- /dev/null +++ b/src/features/order/resolvers/order-settlement-seller-mutation.resolver.ts @@ -0,0 +1,32 @@ +import { UseGuards } from '@nestjs/common'; +import { Args, Mutation, Resolver } from '@nestjs/graphql'; + +import { SellerUpsertSettlementAccountInput } from '@/features/order/dto/inputs/seller-upsert-settlement-account.input'; +import { SellerSettlementService } from '@/features/order/services/order-settlement-seller.service'; +import type { SellerSettlementAccountOutput } from '@/features/order/types/order-payment-output.type'; +import { + CurrentUser, + JwtAuthGuard, + Roles, + RolesGuard, + parseAccountId, + type JwtUser, +} from '@/global/auth'; + +@Resolver('Mutation') +@UseGuards(JwtAuthGuard, RolesGuard) +@Roles('SELLER') +export class SellerSettlementMutationResolver { + constructor(private readonly settlementService: SellerSettlementService) {} + + @Mutation('sellerUpsertSettlementAccount') + sellerUpsertSettlementAccount( + @CurrentUser() user: JwtUser, + @Args('input') input: SellerUpsertSettlementAccountInput, + ): Promise { + return this.settlementService.sellerUpsertSettlementAccount( + parseAccountId(user), + input, + ); + } +} diff --git a/src/features/order/resolvers/order-settlement-seller-query.resolver.ts b/src/features/order/resolvers/order-settlement-seller-query.resolver.ts new file mode 100644 index 00000000..89d17030 --- /dev/null +++ b/src/features/order/resolvers/order-settlement-seller-query.resolver.ts @@ -0,0 +1,27 @@ +import { UseGuards } from '@nestjs/common'; +import { Query, Resolver } from '@nestjs/graphql'; + +import { SellerSettlementService } from '@/features/order/services/order-settlement-seller.service'; +import type { SellerSettlementAccountOutput } from '@/features/order/types/order-payment-output.type'; +import { + CurrentUser, + JwtAuthGuard, + Roles, + RolesGuard, + parseAccountId, + type JwtUser, +} from '@/global/auth'; + +@Resolver('Query') +@UseGuards(JwtAuthGuard, RolesGuard) +@Roles('SELLER') +export class SellerSettlementQueryResolver { + constructor(private readonly settlementService: SellerSettlementService) {} + + @Query('sellerSettlementAccount') + sellerSettlementAccount( + @CurrentUser() user: JwtUser, + ): Promise { + return this.settlementService.sellerSettlementAccount(parseAccountId(user)); + } +} diff --git a/src/features/order/services/order-bank-account.helper.spec.ts b/src/features/order/services/order-bank-account.helper.spec.ts new file mode 100644 index 00000000..aedfd9a8 --- /dev/null +++ b/src/features/order/services/order-bank-account.helper.spec.ts @@ -0,0 +1,98 @@ +import { PAYMENT_BANKS } from '@/features/order/constants/payment-banks'; +import { + maskAccountNumber, + normalizeAccountHolder, + normalizeAccountNumber, + normalizeBankAccount, + normalizeBankCode, + toBank, +} from '@/features/order/services/order-bank-account.helper'; + +describe('order-bank-account.helper', () => { + describe('은행 코드', () => { + it('목록은 금융결제원 3자리 코드이고 겹치지 않는다', () => { + const codes = PAYMENT_BANKS.map((bank) => bank.code); + expect(codes.length).toBeGreaterThan(20); + expect(new Set(codes).size).toBe(codes.length); + expect(codes.every((code) => /^\d{3}$/.test(code))).toBe(true); + }); + + it.each(PAYMENT_BANKS.map((bank) => bank.code))('%s는 통과한다', (code) => { + expect(normalizeBankCode(` ${code} `)).toBe(code); + }); + + it.each(['', '4', '04', '0004', '999', 'abc', '004'])( + '반증: "%s"는 INVALID_BANK_CODE', + (code) => { + expect(() => normalizeBankCode(code)).toThrowDomain( + 'INVALID_BANK_CODE', + ); + }, + ); + }); + + describe('계좌번호', () => { + it.each([ + ['8자리', '12345678', '12345678'], + ['20자리', '1'.repeat(20), '1'.repeat(20)], + ['하이픈 제거', '110-123-456789', '110123456789'], + ['앞뒤 공백', ' 1234-5678 ', '12345678'], + ])('%s: 숫자만 남긴다', (_label, raw, expected) => { + expect(normalizeAccountNumber(raw)).toBe(expected); + }); + + it.each([ + ['7자리', '1234567'], + ['21자리', '1'.repeat(21)], + ['하이픈 제거 뒤 7자리', '123-4567'], + ['가운데 공백', '1234 5678'], + ['영문 섞임', '12345678a'], + ['전각 숫자', '12345678'], + ['하이픈만', '--------'], + ['빈 문자열', ''], + ])('반증: %s는 INVALID_ACCOUNT_NUMBER', (_label, raw) => { + expect(() => normalizeAccountNumber(raw)).toThrowDomain( + 'INVALID_ACCOUNT_NUMBER', + ); + }); + }); + + describe('예금주', () => { + it('1~50자(코드 포인트)를 trim해 받는다', () => { + expect(normalizeAccountHolder(' 케이크샵 ')).toBe('케이크샵'); + expect(normalizeAccountHolder('가'.repeat(50))).toHaveLength(50); + expect(normalizeAccountHolder('😀'.repeat(50))).toBe('😀'.repeat(50)); + }); + + it.each([ + ['빈 문자열', '', 'TEXT_REQUIRED'], + ['공백뿐', ' ', 'TEXT_REQUIRED'], + ['51자', '가'.repeat(51), 'TEXT_TOO_LONG'], + ])('반증: %s는 %s', (_label, raw, code) => { + expect(() => normalizeAccountHolder(raw)).toThrowDomain(code); + }); + }); + + it('normalizeBankAccount는 세 값을 함께 정리한다', () => { + expect( + normalizeBankAccount({ + bankCode: '088', + accountHolder: ' 홍길동 ', + accountNumber: '110-123-456789', + }), + ).toEqual({ + bankCode: '088', + accountHolder: '홍길동', + accountNumber: '110123456789', + }); + }); + + it('toBank는 이름을 붙이고, 목록에서 빠진 코드는 코드를 이름으로 쓴다', () => { + expect(toBank('004')).toEqual({ code: '004', name: 'KB국민은행' }); + expect(toBank('999')).toEqual({ code: '999', name: '999' }); + }); + + it('maskAccountNumber는 끝 4자리만 보인다', () => { + expect(maskAccountNumber('6789')).toBe('****6789'); + }); +}); diff --git a/src/features/order/services/order-bank-account.helper.ts b/src/features/order/services/order-bank-account.helper.ts new file mode 100644 index 00000000..9225a8ff --- /dev/null +++ b/src/features/order/services/order-bank-account.helper.ts @@ -0,0 +1,56 @@ +import { DomainException } from '@/common/errors/error-catalog'; +import { cleanRequiredText } from '@/common/utils/text-cleaner'; +import { + MAX_ACCOUNT_HOLDER_LENGTH, + PAYMENT_BANKS, +} from '@/features/order/constants/payment-banks'; +import type { BankOutput } from '@/features/order/types/order-payment-output.type'; + +const BANK_NAMES: ReadonlyMap = new Map( + PAYMENT_BANKS.map((bank) => [bank.code, bank.name]), +); +const ACCOUNT_DIGITS = /^\d{8,20}$/; + +export interface BankAccountInput { + bankCode: string; + accountHolder: string; + accountNumber: string; +} + +export function normalizeBankCode(raw: string): string { + const code = raw.trim(); + if (!BANK_NAMES.has(code)) throw new DomainException('INVALID_BANK_CODE'); + return code; +} + +/** 하이픈을 뺀 숫자 8~20자리. 저장·암호화는 숫자만 한다. */ +export function normalizeAccountNumber(raw: string): string { + const digits = raw.trim().replaceAll('-', ''); + if (!ACCOUNT_DIGITS.test(digits)) { + throw new DomainException('INVALID_ACCOUNT_NUMBER'); + } + return digits; +} + +export function normalizeAccountHolder(raw: string): string { + return cleanRequiredText(raw, MAX_ACCOUNT_HOLDER_LENGTH); +} + +export function normalizeBankAccount( + input: BankAccountInput, +): BankAccountInput { + return { + bankCode: normalizeBankCode(input.bankCode), + accountHolder: normalizeAccountHolder(input.accountHolder), + accountNumber: normalizeAccountNumber(input.accountNumber), + }; +} + +/** 목록에서 빠진 옛 코드도 화면이 죽지 않게 코드를 이름으로 쓴다. */ +export function toBank(code: string): BankOutput { + return { code, name: BANK_NAMES.get(code) ?? code }; +} + +export function maskAccountNumber(last4: string): string { + return `****${last4}`; +} diff --git a/src/features/order/services/order-payment-admin.service.spec.ts b/src/features/order/services/order-payment-admin.service.spec.ts new file mode 100644 index 00000000..b6edc710 --- /dev/null +++ b/src/features/order/services/order-payment-admin.service.spec.ts @@ -0,0 +1,412 @@ +import { + AUDIT_LOG_REPOSITORY, + type IAuditLogRepository, +} from '@/features/audit-log'; +import { AuditLogRepository } from '@/features/audit-log/repositories/audit-log.repository'; +import { AccountAdminRepository } from '@/features/auth/repositories/account-admin.repository'; +import { PaymentSettingRepository } from '@/features/order/repositories/payment-setting.repository'; +import { StoreSettlementAccountRepository } from '@/features/order/repositories/store-settlement-account.repository'; +import { AdminPaymentService } from '@/features/order/services/order-payment-admin.service'; +import { StoreAdminRepository } from '@/features/store/repositories/store-admin.repository'; +import type { PrismaClient } from '@/generated/prisma/client'; +import { AccountCipher } from '@/global/crypto/account-cipher.service'; +import { createTestAccountCipher } from '@/test/account-cipher'; +import { disconnectTestPrismaClient } from '@/test/db/prisma-test-client'; +import { closeTruncateConnection, truncateAll } from '@/test/db/truncate'; +import { + createAccount, + createPaymentSetting, + createStore, +} from '@/test/factories'; +import { createTestingModuleWithRealDb } from '@/test/modules/testing-module.builder'; + +describe('AdminPaymentService (real DB)', () => { + let service: AdminPaymentService; + let auditLogs: IAuditLogRepository; + let cipher: AccountCipher; + let prisma: PrismaClient; + + beforeAll(async () => { + const { module, prisma: p } = await createTestingModuleWithRealDb({ + providers: [ + AdminPaymentService, + AccountAdminRepository, + PaymentSettingRepository, + StoreSettlementAccountRepository, + StoreAdminRepository, + { provide: AUDIT_LOG_REPOSITORY, useClass: AuditLogRepository }, + { provide: AccountCipher, useValue: createTestAccountCipher() }, + ], + }); + service = module.get(AdminPaymentService); + auditLogs = module.get(AUDIT_LOG_REPOSITORY); + cipher = module.get(AccountCipher); + prisma = p; + }); + + afterAll(async () => { + await closeTruncateConnection(); + await disconnectTestPrismaClient(); + }); + + beforeEach(async () => { + await truncateAll(); + }); + + afterEach(() => { + jest.restoreAllMocks(); + }); + + async function admin(): Promise { + return (await createAccount(prisma, { account_type: 'ADMIN' })).id; + } + + /** 감사 기록 단계에서 실패시킨다(장애 주입) — 같은 트랜잭션이면 본 write도 남지 않아야 한다. */ + function failAuditOnce(): void { + jest + .spyOn(auditLogs, 'recordAudit') + .mockRejectedValueOnce(new Error('audit down')); + } + + const auditsOf = (targetType: 'PAYMENT_SETTING' | 'SETTLEMENT_ACCOUNT') => + prisma.auditLog.findMany({ + where: { target_type: targetType }, + orderBy: { id: 'asc' }, + }); + + describe('adminPaymentSetting', () => { + it('행이 없으면 수수료 0·입금 계좌 없음으로 읽는다', async () => { + expect(await prisma.paymentSetting.count()).toBe(0); + await expect(service.adminPaymentSetting(await admin())).resolves.toEqual( + { + commissionRateBps: 0, + depositBank: null, + depositAccountNumber: null, + depositAccountHolder: null, + updatedAt: null, + }, + ); + }); + + it('있는 행을 은행 이름과 함께 읽는다', async () => { + await createPaymentSetting(prisma, { commission_rate_bps: 550 }); + await expect( + service.adminPaymentSetting(await admin()), + ).resolves.toMatchObject({ + commissionRateBps: 550, + depositBank: { code: '004', name: 'KB국민은행' }, + depositAccountNumber: '12345678901234', + depositAccountHolder: '케이퀵', + updatedAt: expect.any(Date) as Date, + }); + }); + + it('관리자가 아니면 거절한다', async () => { + const seller = await createAccount(prisma, { account_type: 'SELLER' }); + await expect( + service.adminPaymentSetting(seller.id), + ).rejects.toThrowDomain('ADMIN_ONLY'); + }); + }); + + describe('adminUpdatePaymentSetting', () => { + it('행이 없으면 첫 변경이 행을 만들고 기본값을 변경 전으로 감사에 남긴다', async () => { + const actor = await admin(); + const out = await service.adminUpdatePaymentSetting(actor, { + commissionRateBps: 300, + depositBankCode: '088', + depositAccountNumber: '140-012-345678', + depositAccountHolder: ' 케이퀵 ', + reason: '입금 계좌 개설', + }); + + expect(out).toMatchObject({ + commissionRateBps: 300, + depositBank: { code: '088', name: '신한은행' }, + depositAccountNumber: '140012345678', + depositAccountHolder: '케이퀵', + }); + const row = await prisma.paymentSetting.findUniqueOrThrow({ + where: { id: 1 }, + }); + expect(row.updated_by_account_id).toBe(actor); + const [audit] = await auditsOf('PAYMENT_SETTING'); + expect(audit).toMatchObject({ + actor_account_id: actor, + store_id: null, + target_id: 1n, + action: 'UPDATE', + before_json: { + commission_rate_bps: 0, + deposit_bank_code: null, + deposit_account_number: null, + deposit_account_holder: null, + }, + after_json: { + commission_rate_bps: 300, + deposit_bank_code: '088', + deposit_account_number: '140012345678', + deposit_account_holder: '케이퀵', + reason: '입금 계좌 개설', + }, + }); + }); + + it('보낸 필드만 바꾸고 생략·null인 필드는 그대로 둔다', async () => { + await createPaymentSetting(prisma, { commission_rate_bps: 550 }); + const out = await service.adminUpdatePaymentSetting(await admin(), { + commissionRateBps: null, + depositAccountHolder: '케이퀵 주식회사', + reason: '예금주 정정', + }); + + expect(out).toMatchObject({ + commissionRateBps: 550, + depositBank: { code: '004' }, + depositAccountNumber: '12345678901234', + depositAccountHolder: '케이퀵 주식회사', + }); + const [audit] = await auditsOf('PAYMENT_SETTING'); + expect(audit.before_json).toMatchObject({ + deposit_account_holder: '케이퀵', + }); + }); + + it.each([ + [-1, false], + [0, true], + [10_000, true], + [10_001, false], + [1.5, false], + ])('수수료율 %p bp → 허용 %p', async (bps, ok) => { + const run = service.adminUpdatePaymentSetting(await admin(), { + commissionRateBps: bps, + reason: '수수료 조정', + }); + if (ok) { + await expect(run).resolves.toMatchObject({ commissionRateBps: bps }); + } else { + await expect(run).rejects.toThrowDomain('INVALID_COMMISSION_RATE'); + } + }); + + it.each([ + [{ depositBankCode: '999' }, 'INVALID_BANK_CODE'], + [{ depositAccountNumber: '1234567' }, 'INVALID_ACCOUNT_NUMBER'], + [{ depositAccountHolder: ' ' }, 'TEXT_REQUIRED'], + [{ reason: ' ' }, 'TEXT_REQUIRED'], + ])( + '잘못된 입력 %p은 %s로 거절하고 아무것도 바꾸지 않는다', + async (patch, code) => { + await createPaymentSetting(prisma); + const before = await prisma.paymentSetting.findUniqueOrThrow({ + where: { id: 1 }, + }); + await expect( + service.adminUpdatePaymentSetting(await admin(), { + reason: '변경', + ...patch, + }), + ).rejects.toThrowDomain(code); + expect( + await prisma.paymentSetting.findUniqueOrThrow({ where: { id: 1 } }), + ).toEqual(before); + expect(await auditsOf('PAYMENT_SETTING')).toHaveLength(0); + }, + ); + + it('감사 기록이 실패하면 설정 변경도 남지 않는다(같은 트랜잭션)', async () => { + await createPaymentSetting(prisma, { commission_rate_bps: 100 }); + failAuditOnce(); + await expect( + service.adminUpdatePaymentSetting(await admin(), { + commissionRateBps: 900, + reason: '변경', + }), + ).rejects.toThrow('audit down'); + expect( + (await prisma.paymentSetting.findUniqueOrThrow({ where: { id: 1 } })) + .commission_rate_bps, + ).toBe(100); + }); + + it('행이 없을 때 동시에 바꿔도 둘 다 성공하고 행은 1개다', async () => { + const actor = await admin(); + await Promise.all([ + service.adminUpdatePaymentSetting(actor, { + commissionRateBps: 100, + reason: 'a', + }), + service.adminUpdatePaymentSetting(actor, { + depositBankCode: '004', + reason: 'b', + }), + ]); + const row = await prisma.paymentSetting.findUniqueOrThrow({ + where: { id: 1 }, + }); + expect(row).toMatchObject({ + commission_rate_bps: 100, + deposit_bank_code: '004', + }); + expect(await auditsOf('PAYMENT_SETTING')).toHaveLength(2); + }); + }); + + describe('adminStoreSettlementAccount', () => { + it('없는 매장·삭제된 매장은 STORE_NOT_FOUND', async () => { + const actor = await admin(); + const deleted = await createStore(prisma, { deleted_at: new Date() }); + for (const storeId of [999_999n, deleted.id]) { + await expect( + service.adminStoreSettlementAccount(actor, storeId), + ).rejects.toThrowDomain('STORE_NOT_FOUND'); + } + }); + + it('등록 전이면 null, 등록 뒤에는 계좌번호 원문을 복호화해 준다', async () => { + const actor = await admin(); + const store = await createStore(prisma); + expect(await service.adminStoreSettlementAccount(actor, store.id)).toBe( + null, + ); + + await service.adminUpsertStoreSettlementAccount(actor, { + storeId: store.id.toString(), + bankCode: '004', + accountHolder: '케이크샵', + accountNumber: '123-456-7890', + reason: '판매자 요청', + }); + + expect( + await service.adminStoreSettlementAccount(actor, store.id), + ).toMatchObject({ + storeId: store.id.toString(), + bank: { code: '004', name: 'KB국민은행' }, + accountHolder: '케이크샵', + accountNumber: '1234567890', + accountNumberMasked: '****7890', + updatedByRole: 'ADMIN', + }); + }); + }); + + describe('adminUpsertStoreSettlementAccount', () => { + const input = (storeId: bigint, accountNumber = '1234567890') => ({ + storeId: storeId.toString(), + bankCode: '088', + accountHolder: '케이크샵', + accountNumber, + reason: '판매자 요청', + }); + + it('없는 매장이면 STORE_NOT_FOUND이고 계좌를 만들지 않는다', async () => { + await expect( + service.adminUpsertStoreSettlementAccount( + await admin(), + input(999_999n), + ), + ).rejects.toThrowDomain('STORE_NOT_FOUND'); + expect(await prisma.storeSettlementAccount.count()).toBe(0); + }); + + it('계좌번호는 암호문과 끝 4자리로만 저장하고 감사에는 끝 4자리만 남긴다', async () => { + const actor = await admin(); + const store = await createStore(prisma); + await service.adminUpsertStoreSettlementAccount( + actor, + input(store.id, '1234567890'), + ); + await service.adminUpsertStoreSettlementAccount( + actor, + input(store.id, '9876543210'), + ); + + const row = await prisma.storeSettlementAccount.findUniqueOrThrow({ + where: { store_id: store.id }, + }); + expect(row).toMatchObject({ + account_number_last4: '3210', + updated_by_account_id: actor, + updated_by_role: 'ADMIN', + }); + expect(row.account_number_enc).not.toContain('9876543210'); + expect(cipher.decrypt(row.account_number_enc, 'settlement-account')).toBe( + '9876543210', + ); + + const audits = await auditsOf('SETTLEMENT_ACCOUNT'); + expect(audits.map((a) => [a.action, a.store_id, a.target_id])).toEqual([ + ['CREATE', store.id, row.id], + ['UPDATE', store.id, row.id], + ]); + expect(audits[1]).toMatchObject({ + before_json: { account_number_last4: '7890' }, + after_json: { account_number_last4: '3210', reason: '판매자 요청' }, + }); + const serialized = JSON.stringify( + audits.map((a) => [a.before_json, a.after_json]), + ); + expect(serialized).not.toContain('1234567890'); + expect(serialized).not.toContain('9876543210'); + expect(serialized).not.toContain(row.account_number_enc); + }); + + it.each([ + [{ bankCode: '000' }, 'INVALID_BANK_CODE'], + [{ accountNumber: '1'.repeat(21) }, 'INVALID_ACCOUNT_NUMBER'], + [{ accountHolder: '가'.repeat(51) }, 'TEXT_TOO_LONG'], + [{ reason: '' }, 'TEXT_REQUIRED'], + [{ storeId: '' }, 'INVALID_ID'], + ])('잘못된 입력 %p은 %s로 거절한다', async (patch, code) => { + const store = await createStore(prisma); + await expect( + service.adminUpsertStoreSettlementAccount(await admin(), { + ...input(store.id), + ...patch, + }), + ).rejects.toThrowDomain(code); + expect(await prisma.storeSettlementAccount.count()).toBe(0); + }); + + it('감사 기록이 실패하면 계좌도 바뀌지 않는다(같은 트랜잭션)', async () => { + const actor = await admin(); + const store = await createStore(prisma); + await service.adminUpsertStoreSettlementAccount(actor, input(store.id)); + failAuditOnce(); + await expect( + service.adminUpsertStoreSettlementAccount( + actor, + input(store.id, '5555555555'), + ), + ).rejects.toThrow('audit down'); + expect( + ( + await prisma.storeSettlementAccount.findUniqueOrThrow({ + where: { store_id: store.id }, + }) + ).account_number_last4, + ).toBe('7890'); + }); + + it('첫 등록이 동시에 두 번 와도 둘 다 성공하고 행은 1개다(생성·갱신 감사 각 1건)', async () => { + const actor = await admin(); + const store = await createStore(prisma); + await Promise.all([ + service.adminUpsertStoreSettlementAccount( + actor, + input(store.id, '1111111111'), + ), + service.adminUpsertStoreSettlementAccount( + actor, + input(store.id, '2222222222'), + ), + ]); + expect(await prisma.storeSettlementAccount.count()).toBe(1); + expect( + (await auditsOf('SETTLEMENT_ACCOUNT')).map((a) => a.action).sort(), + ).toEqual(['CREATE', 'UPDATE']); + }); + }); +}); diff --git a/src/features/order/services/order-payment-admin.service.ts b/src/features/order/services/order-payment-admin.service.ts new file mode 100644 index 00000000..552bdf41 --- /dev/null +++ b/src/features/order/services/order-payment-admin.service.ts @@ -0,0 +1,137 @@ +import { Inject, Injectable } from '@nestjs/common'; + +import { MAX_REASON_LENGTH } from '@/common/constants/reason.constants'; +import { DomainException } from '@/common/errors/error-catalog'; +import { parseId } from '@/common/utils/id-parser'; +import { cleanRequiredText } from '@/common/utils/text-cleaner'; +import { + AUDIT_LOG_REPOSITORY, + type IAuditLogRepository, +} from '@/features/audit-log'; +import { AccountAdminRepository, AdminBaseService } from '@/features/auth'; +import type { AdminUpdatePaymentSettingInput } from '@/features/order/dto/inputs/admin-update-payment-setting.input'; +import type { AdminUpsertStoreSettlementAccountInput } from '@/features/order/dto/inputs/admin-upsert-store-settlement-account.input'; +import { + PaymentSettingRepository, + type PaymentSettingValues, +} from '@/features/order/repositories/payment-setting.repository'; +import { StoreSettlementAccountRepository } from '@/features/order/repositories/store-settlement-account.repository'; +import { + normalizeAccountHolder, + normalizeAccountNumber, + normalizeBankAccount, + normalizeBankCode, +} from '@/features/order/services/order-bank-account.helper'; +import { + toAdminPaymentSettingOutput, + toAdminStoreSettlementAccountOutput, +} from '@/features/order/services/order-payment-mappers.helper'; +import type { + AdminPaymentSettingOutput, + AdminStoreSettlementAccountOutput, +} from '@/features/order/types/order-payment-output.type'; +import { StoreAdminRepository } from '@/features/store'; +import { OrderActor } from '@/generated/prisma/client'; +import { AccountCipher } from '@/global/crypto/account-cipher.service'; + +const MAX_COMMISSION_RATE_BPS = 10_000; + +/** 플랫폼 결제 설정과 매장 정산 계좌 관리. 계좌번호 원문 복호화는 관리자 매장 정산 계좌 조회에서만 한다. */ +@Injectable() +export class AdminPaymentService extends AdminBaseService { + constructor( + accounts: AccountAdminRepository, + @Inject(AUDIT_LOG_REPOSITORY) + auditLogs: IAuditLogRepository, + private readonly paymentSettings: PaymentSettingRepository, + private readonly settlementAccounts: StoreSettlementAccountRepository, + private readonly stores: StoreAdminRepository, + private readonly cipher: AccountCipher, + ) { + super(accounts, auditLogs); + } + + async adminPaymentSetting( + accountId: bigint, + ): Promise { + await this.requireAdminContext(accountId); + return toAdminPaymentSettingOutput( + await this.paymentSettings.findPaymentSetting(), + ); + } + + async adminUpdatePaymentSetting( + accountId: bigint, + input: AdminUpdatePaymentSettingInput, + ): Promise { + const ctx = await this.requireAdminContext(accountId); + const reason = cleanRequiredText(input.reason, MAX_REASON_LENGTH); + const patch: Partial = {}; + if (input.commissionRateBps != null) { + const bps = input.commissionRateBps; + if (!Number.isInteger(bps) || bps < 0 || bps > MAX_COMMISSION_RATE_BPS) { + throw new DomainException('INVALID_COMMISSION_RATE'); + } + patch.commission_rate_bps = bps; + } + if (input.depositBankCode != null) { + patch.deposit_bank_code = normalizeBankCode(input.depositBankCode); + } + if (input.depositAccountNumber != null) { + patch.deposit_account_number = normalizeAccountNumber( + input.depositAccountNumber, + ); + } + if (input.depositAccountHolder != null) { + patch.deposit_account_holder = normalizeAccountHolder( + input.depositAccountHolder, + ); + } + const row = await this.paymentSettings.updatePaymentSetting({ + patch, + actorAccountId: ctx.accountId, + reason, + }); + return toAdminPaymentSettingOutput(row); + } + + async adminStoreSettlementAccount( + accountId: bigint, + storeId: bigint, + ): Promise { + await this.requireAdminContext(accountId); + await this.requireStore(storeId); + const row = await this.settlementAccounts.findByStoreId(storeId); + return row + ? toAdminStoreSettlementAccountOutput( + row, + this.cipher.decrypt(row.account_number_enc, 'settlement-account'), + ) + : null; + } + + async adminUpsertStoreSettlementAccount( + accountId: bigint, + input: AdminUpsertStoreSettlementAccountInput, + ): Promise { + const ctx = await this.requireAdminContext(accountId); + const storeId = parseId(input.storeId); + const account = normalizeBankAccount(input); + const reason = cleanRequiredText(input.reason, MAX_REASON_LENGTH); + await this.requireStore(storeId); + const row = await this.settlementAccounts.upsertByStore({ + storeId, + account, + actorAccountId: ctx.accountId, + actorRole: OrderActor.ADMIN, + reason, + }); + return toAdminStoreSettlementAccountOutput(row, account.accountNumber); + } + + private async requireStore(storeId: bigint): Promise { + if (!(await this.stores.findStoreById(storeId))) { + throw new DomainException('STORE_NOT_FOUND'); + } + } +} diff --git a/src/features/order/services/order-payment-mappers.helper.ts b/src/features/order/services/order-payment-mappers.helper.ts new file mode 100644 index 00000000..60cf27b1 --- /dev/null +++ b/src/features/order/services/order-payment-mappers.helper.ts @@ -0,0 +1,46 @@ +import type { PaymentSettingRow } from '@/features/order/repositories/payment-setting.repository'; +import { + maskAccountNumber, + toBank, +} from '@/features/order/services/order-bank-account.helper'; +import type { + AdminPaymentSettingOutput, + AdminStoreSettlementAccountOutput, + SellerSettlementAccountOutput, +} from '@/features/order/types/order-payment-output.type'; +import type { StoreSettlementAccount } from '@/generated/prisma/client'; + +export function toAdminPaymentSettingOutput( + row: PaymentSettingRow, +): AdminPaymentSettingOutput { + return { + commissionRateBps: row.commission_rate_bps, + depositBank: row.deposit_bank_code ? toBank(row.deposit_bank_code) : null, + depositAccountNumber: row.deposit_account_number, + depositAccountHolder: row.deposit_account_holder, + updatedAt: row.updated_at, + }; +} + +export function toSellerSettlementAccountOutput( + row: StoreSettlementAccount, +): SellerSettlementAccountOutput { + return { + bank: toBank(row.bank_code), + accountHolder: row.account_holder, + accountNumberMasked: maskAccountNumber(row.account_number_last4), + updatedByRole: row.updated_by_role, + updatedAt: row.updated_at, + }; +} + +export function toAdminStoreSettlementAccountOutput( + row: StoreSettlementAccount, + accountNumber: string, +): AdminStoreSettlementAccountOutput { + return { + ...toSellerSettlementAccountOutput(row), + storeId: row.store_id.toString(), + accountNumber, + }; +} diff --git a/src/features/order/services/order-settlement-seller.service.spec.ts b/src/features/order/services/order-settlement-seller.service.spec.ts new file mode 100644 index 00000000..7d68f46f --- /dev/null +++ b/src/features/order/services/order-settlement-seller.service.spec.ts @@ -0,0 +1,143 @@ +import { AUDIT_LOG_REPOSITORY } from '@/features/audit-log'; +import { AuditLogRepository } from '@/features/audit-log/repositories/audit-log.repository'; +import { StoreSettlementAccountRepository } from '@/features/order/repositories/store-settlement-account.repository'; +import { SellerSettlementService } from '@/features/order/services/order-settlement-seller.service'; +import { StoreSellerRepository } from '@/features/store/repositories/store-seller.repository'; +import type { PrismaClient } from '@/generated/prisma/client'; +import { AccountCipher } from '@/global/crypto/account-cipher.service'; +import { createTestAccountCipher } from '@/test/account-cipher'; +import { disconnectTestPrismaClient } from '@/test/db/prisma-test-client'; +import { closeTruncateConnection, truncateAll } from '@/test/db/truncate'; +import { createAccount, setupSellerWithStore } from '@/test/factories'; +import { createTestingModuleWithRealDb } from '@/test/modules/testing-module.builder'; + +describe('SellerSettlementService (real DB)', () => { + let service: SellerSettlementService; + let cipher: AccountCipher; + let prisma: PrismaClient; + + beforeAll(async () => { + const { module, prisma: p } = await createTestingModuleWithRealDb({ + providers: [ + SellerSettlementService, + StoreSellerRepository, + StoreSettlementAccountRepository, + { provide: AUDIT_LOG_REPOSITORY, useClass: AuditLogRepository }, + { provide: AccountCipher, useValue: createTestAccountCipher() }, + ], + }); + service = module.get(SellerSettlementService); + cipher = module.get(AccountCipher); + prisma = p; + }); + + afterAll(async () => { + await closeTruncateConnection(); + await disconnectTestPrismaClient(); + }); + + beforeEach(async () => { + await truncateAll(); + }); + + const input = { + bankCode: '090', + accountHolder: '홍길동', + accountNumber: '3333-01-2345678', + }; + + it('등록 전이면 null이다', async () => { + const { account } = await setupSellerWithStore(prisma); + expect(await service.sellerSettlementAccount(account.id)).toBeNull(); + }); + + it('등록하면 내 매장 계좌로 저장하고 끝 4자리만 내려준다', async () => { + const { account, store } = await setupSellerWithStore(prisma); + + const out = await service.sellerUpsertSettlementAccount(account.id, input); + + const expected = { + bank: { code: '090', name: '카카오뱅크' }, + accountHolder: '홍길동', + accountNumberMasked: '****5678', + updatedByRole: 'SELLER', + }; + expect(out).toMatchObject(expected); + expect(JSON.stringify(out)).not.toContain('3333012345678'); + expect(await service.sellerSettlementAccount(account.id)).toMatchObject( + expected, + ); + + const row = await prisma.storeSettlementAccount.findUniqueOrThrow({ + where: { store_id: store.id }, + }); + expect(row.updated_by_account_id).toBe(account.id); + expect(cipher.decrypt(row.account_number_enc, 'settlement-account')).toBe( + '3333012345678', + ); + const [audit] = await prisma.auditLog.findMany({ + where: { target_type: 'SETTLEMENT_ACCOUNT' }, + }); + expect(audit).toMatchObject({ + actor_account_id: account.id, + store_id: store.id, + action: 'CREATE', + before_json: null, + after_json: { + bank_code: '090', + account_holder: '홍길동', + account_number_last4: '5678', + }, + }); + }); + + it('관리자가 바꾼 계좌는 판매자가 다시 바꾸면 SELLER로 돌아온다', async () => { + const { account, store } = await setupSellerWithStore(prisma); + const admin = await createAccount(prisma, { account_type: 'ADMIN' }); + await prisma.storeSettlementAccount.create({ + data: { + store_id: store.id, + bank_code: '004', + account_holder: '대리 입력', + account_number_enc: cipher.encrypt('11112222', 'settlement-account'), + account_number_last4: '2222', + updated_by_account_id: admin.id, + updated_by_role: 'ADMIN', + }, + }); + expect(await service.sellerSettlementAccount(account.id)).toMatchObject({ + updatedByRole: 'ADMIN', + }); + + await service.sellerUpsertSettlementAccount(account.id, input); + + expect(await prisma.storeSettlementAccount.count()).toBe(1); + expect(await service.sellerSettlementAccount(account.id)).toMatchObject({ + accountNumberMasked: '****5678', + updatedByRole: 'SELLER', + }); + }); + + it.each([ + [{ bankCode: '04' }, 'INVALID_BANK_CODE'], + [{ accountNumber: '1234-567' }, 'INVALID_ACCOUNT_NUMBER'], + [{ accountHolder: '' }, 'TEXT_REQUIRED'], + ])('잘못된 입력 %p은 %s로 거절하고 저장하지 않는다', async (patch, code) => { + const { account } = await setupSellerWithStore(prisma); + await expect( + service.sellerUpsertSettlementAccount(account.id, { ...input, ...patch }), + ).rejects.toThrowDomain(code); + expect(await prisma.storeSettlementAccount.count()).toBe(0); + }); + + it('판매자가 아니거나 매장이 없으면 거절한다', async () => { + const buyer = await createAccount(prisma, { account_type: 'USER' }); + await expect( + service.sellerSettlementAccount(buyer.id), + ).rejects.toThrowDomain('SELLER_ONLY'); + const storeless = await createAccount(prisma, { account_type: 'SELLER' }); + await expect( + service.sellerUpsertSettlementAccount(storeless.id, input), + ).rejects.toThrowDomain('STORE_NOT_FOUND'); + }); +}); diff --git a/src/features/order/services/order-settlement-seller.service.ts b/src/features/order/services/order-settlement-seller.service.ts new file mode 100644 index 00000000..7b3a3bdf --- /dev/null +++ b/src/features/order/services/order-settlement-seller.service.ts @@ -0,0 +1,48 @@ +import { Inject, Injectable } from '@nestjs/common'; + +import { + AUDIT_LOG_REPOSITORY, + type IAuditLogRepository, +} from '@/features/audit-log'; +import type { SellerUpsertSettlementAccountInput } from '@/features/order/dto/inputs/seller-upsert-settlement-account.input'; +import { StoreSettlementAccountRepository } from '@/features/order/repositories/store-settlement-account.repository'; +import { normalizeBankAccount } from '@/features/order/services/order-bank-account.helper'; +import { toSellerSettlementAccountOutput } from '@/features/order/services/order-payment-mappers.helper'; +import type { SellerSettlementAccountOutput } from '@/features/order/types/order-payment-output.type'; +import { SellerBaseService, StoreSellerRepository } from '@/features/store'; +import { OrderActor } from '@/generated/prisma/client'; + +/** 판매자 본인 정산 계좌. 계좌번호는 끝 4자리만 내려주고 원문은 복호화하지 않는다. */ +@Injectable() +export class SellerSettlementService extends SellerBaseService { + constructor( + repo: StoreSellerRepository, + @Inject(AUDIT_LOG_REPOSITORY) + auditLogs: IAuditLogRepository, + private readonly settlementAccounts: StoreSettlementAccountRepository, + ) { + super(repo, auditLogs); + } + + async sellerSettlementAccount( + accountId: bigint, + ): Promise { + const ctx = await this.requireSellerContext(accountId); + const row = await this.settlementAccounts.findByStoreId(ctx.storeId); + return row ? toSellerSettlementAccountOutput(row) : null; + } + + async sellerUpsertSettlementAccount( + accountId: bigint, + input: SellerUpsertSettlementAccountInput, + ): Promise { + const ctx = await this.requireSellerContext(accountId); + const row = await this.settlementAccounts.upsertByStore({ + storeId: ctx.storeId, + account: normalizeBankAccount(input), + actorAccountId: ctx.accountId, + actorRole: OrderActor.SELLER, + }); + return toSellerSettlementAccountOutput(row); + } +} diff --git a/src/features/order/types/order-payment-output.type.ts b/src/features/order/types/order-payment-output.type.ts new file mode 100644 index 00000000..74ba079e --- /dev/null +++ b/src/features/order/types/order-payment-output.type.ts @@ -0,0 +1,28 @@ +import type { OrderActor } from '@/generated/prisma/client'; + +export interface BankOutput { + code: string; + name: string; +} + +export interface AdminPaymentSettingOutput { + commissionRateBps: number; + depositBank: BankOutput | null; + depositAccountNumber: string | null; + depositAccountHolder: string | null; + updatedAt: Date | null; +} + +export interface SellerSettlementAccountOutput { + bank: BankOutput; + accountHolder: string; + accountNumberMasked: string; + updatedByRole: OrderActor; + updatedAt: Date; +} + +export interface AdminStoreSettlementAccountOutput extends SellerSettlementAccountOutput { + storeId: string; + /** 원문. 관리자 상세에서만 복호화해 내려준다. */ + accountNumber: string; +} diff --git a/src/features/store/dto/inputs/seller-audit-log-list.input.spec.ts b/src/features/store/dto/inputs/seller-audit-log-list.input.spec.ts index 7629a980..154db6a3 100644 --- a/src/features/store/dto/inputs/seller-audit-log-list.input.spec.ts +++ b/src/features/store/dto/inputs/seller-audit-log-list.input.spec.ts @@ -20,6 +20,14 @@ describe('SellerAuditLogListInput', () => { expect(await validate(dto)).toHaveLength(0); }); + it('정산 계좌(SETTLEMENT_ACCOUNT)는 받고 관리자 전용 대상(ACCOUNT)은 거절한다', async () => { + expect( + await validate(build({ targetType: 'SETTLEMENT_ACCOUNT' })), + ).toHaveLength(0); + const errors = await validate(build({ targetType: 'ACCOUNT' })); + expect(errors[0].property).toBe('targetType'); + }); + it('알 수 없는 targetType 거절', async () => { const dto = build({ targetType: 'INVALID' }); const errors = await validate(dto); diff --git a/src/features/store/services/store-seller-audit.service.spec.ts b/src/features/store/services/store-seller-audit.service.spec.ts index 4b30b293..4edf0596 100644 --- a/src/features/store/services/store-seller-audit.service.spec.ts +++ b/src/features/store/services/store-seller-audit.service.spec.ts @@ -127,10 +127,15 @@ describe('SellerAuditService (real DB)', () => { expect(second.items.length).toBeGreaterThanOrEqual(1); }); - it('audit targetType ORDER/CONVERSATION/CHANGE_PASSWORD가 enum으로 정확히 매핑되어 필터된다', async () => { + it('audit targetType ORDER/CONVERSATION/CHANGE_PASSWORD/SETTLEMENT_ACCOUNT가 enum으로 정확히 매핑되어 필터된다', async () => { const { account, store } = await setupSellerWithStore(prisma); - const types = ['ORDER', 'CONVERSATION', 'CHANGE_PASSWORD'] as const; + const types = [ + 'ORDER', + 'CONVERSATION', + 'CHANGE_PASSWORD', + 'SETTLEMENT_ACCOUNT', + ] as const; const created = new Map(); for (const t of types) { const row = await prisma.auditLog.create({ @@ -155,6 +160,29 @@ describe('SellerAuditService (real DB)', () => { } }); + it('관리자가 내 매장 정산 계좌를 바꾼 기록은 보이고, 다른 관리자 조작은 보이지 않는다', async () => { + const { account, store } = await setupSellerWithStore(prisma); + const admin = await prisma.account.create({ + data: { account_type: 'ADMIN', status: 'ACTIVE' }, + }); + const byAdmin = (targetType: 'SETTLEMENT_ACCOUNT' | 'ACCOUNT') => + prisma.auditLog.create({ + data: { + actor_account_id: admin.id, + store_id: store.id, + target_type: targetType, + target_id: store.id, + action: 'UPDATE', + }, + }); + const visible = await byAdmin('SETTLEMENT_ACCOUNT'); + await byAdmin('ACCOUNT'); + + const result = await service.sellerAuditLogs(account.id); + expect(result.items.map((it) => it.id)).toEqual([visible.id.toString()]); + expect(result.items[0].actorAccountId).toBe(admin.id.toString()); + }); + it('before/after json이 null인 audit log도 정상 직렬화된다', async () => { const { account, store } = await setupSellerWithStore(prisma); const created = await prisma.auditLog.create({ diff --git a/src/features/store/services/store-seller-audit.service.ts b/src/features/store/services/store-seller-audit.service.ts index 8924988f..155e342d 100644 --- a/src/features/store/services/store-seller-audit.service.ts +++ b/src/features/store/services/store-seller-audit.service.ts @@ -64,6 +64,7 @@ export class SellerAuditService extends SellerBaseService { if (raw === 'ORDER') return AuditTargetType.ORDER; if (raw === 'CONVERSATION') return AuditTargetType.CONVERSATION; if (raw === 'CHANGE_PASSWORD') return AuditTargetType.CHANGE_PASSWORD; + if (raw === 'SETTLEMENT_ACCOUNT') return AuditTargetType.SETTLEMENT_ACCOUNT; throw new DomainException('INVALID_AUDIT_TARGET_TYPE'); } } diff --git a/src/test/enum-sdl-sync.spec.ts b/src/test/enum-sdl-sync.spec.ts index 8ebe0751..2044062b 100644 --- a/src/test/enum-sdl-sync.spec.ts +++ b/src/test/enum-sdl-sync.spec.ts @@ -6,6 +6,7 @@ import { Kind, parse, print, visit } from 'graphql'; import { ConversationBodyFormat, NotificationEvent, + OrderActor, OrderStatus, } from '@/generated/prisma/client'; @@ -34,6 +35,12 @@ const PAIRS: Array< 'src/features/order/order.types.graphql', 'OrderStatusType', ], + [ + 'OrderActor', + Object.values(OrderActor), + 'src/features/order/order.types.graphql', + 'OrderActorType', + ], ]; function sdlEnumValues(source: string, enumName: string): string[] { diff --git a/src/test/roles-coverage.spec.ts b/src/test/roles-coverage.spec.ts index 6f65f801..09d8b41b 100644 --- a/src/test/roles-coverage.spec.ts +++ b/src/test/roles-coverage.spec.ts @@ -13,8 +13,8 @@ describe('접두 루트 필드 인가 커버리지', () => { const handlerAuth = collectHandlerAuth(collectFeatureResolverClasses()); describe.each([ - ['seller', 'SELLER', 56], - ['admin', 'ADMIN', 60], + ['seller', 'SELLER', 58], + ['admin', 'ADMIN', 64], ] as const)('%s 접두 → @Roles(%s)', (prefix, role, count) => { const fields = collectRootFieldsWithPrefix(prefix); diff --git a/src/test/seed-reset-scope.spec.ts b/src/test/seed-reset-scope.spec.ts index 6f50ce54..3d566427 100644 --- a/src/test/seed-reset-scope.spec.ts +++ b/src/test/seed-reset-scope.spec.ts @@ -11,13 +11,18 @@ import { resetSeedScope, } from '../../prisma/seed/idempotent'; import { seedOrders } from '../../prisma/seed/orders'; -import { seedPayments } from '../../prisma/seed/payments'; +import { + SEED_SETTLEMENT_ACCOUNT, + seedPayments, +} from '../../prisma/seed/payments'; import { seedRegions } from '../../prisma/seed/regions'; import { seedReviews } from '../../prisma/seed/reviews'; import { seedStores } from '../../prisma/seed/stores'; import { seedUsers, type SeededUser } from '../../prisma/seed/users'; +import { readAccountCryptoConfig } from '@/config/account-crypto.config'; import type { PrismaClient } from '@/generated/prisma/client'; +import { AccountCipher } from '@/global/crypto/account-cipher.service'; import { disconnectTestPrismaClient } from '@/test/db/prisma-test-client'; import { closeTruncateConnection, truncateAll } from '@/test/db/truncate'; import { @@ -210,7 +215,7 @@ describe('resetSeedScope (real DB)', () => { const stores = await seedStores(prisma, { categories }); const orders = await seedOrders(prisma, { users, stores }); const admin = await seedAdmins(prisma); - await seedPayments(prisma, { orders, admin }); + await seedPayments(prisma, { orders, stores, admin }); return { stores, orders }; }; const { stores, orders } = await seedAll(); @@ -231,17 +236,6 @@ describe('resetSeedScope (real DB)', () => { where: { id: orders.o8NoShow }, data: { settlement_id: settlement.id }, }); - await prisma.storeSettlementAccount.create({ - data: { - store_id: storeA.id, - bank_code: '004', - account_holder: '케이크샵 A', - account_number_enc: 'v1.test', - account_number_last4: '1234', - updated_by_account_id: storeA.seller_account_id, - updated_by_role: 'SELLER', - }, - }); await prisma.orderPickupChange.create({ data: { order_id: orders.o11PaidSubmitted, @@ -256,8 +250,9 @@ describe('resetSeedScope (real DB)', () => { prisma.payment.count(), prisma.refund.count(), prisma.depositRecord.count(), + prisma.storeSettlementAccount.count(), ]); - expect(await counts()).toEqual([5, 2, 1]); + expect(await counts()).toEqual([5, 2, 1, 1]); await resetSeedScope(prisma); for (const count of await Promise.all([ @@ -273,10 +268,40 @@ describe('resetSeedScope (real DB)', () => { expect(await prisma.paymentSetting.count()).toBe(1); await seedAll(); - expect(await counts()).toEqual([5, 2, 1]); + expect(await counts()).toEqual([5, 2, 1, 1]); expect(await prisma.paymentSetting.count()).toBe(1); }); + it('seed-seller-a 매장 정산 계좌는 앱과 같은 키 설정으로 암호화돼 풀린다', async () => { + const users = await seedUsers(prisma); + await seedRegions(prisma); + const categories = await seedCategories(prisma); + const stores = await seedStores(prisma, { categories }); + const orders = await seedOrders(prisma, { users, stores }); + const admin = await seedAdmins(prisma); + await seedPayments(prisma, { orders, stores, admin }); + + const [storeA] = stores.stores; + const account = await prisma.storeSettlementAccount.findUniqueOrThrow({ + where: { store_id: storeA.id }, + }); + expect(account).toMatchObject({ + bank_code: SEED_SETTLEMENT_ACCOUNT.bank_code, + account_number_last4: SEED_SETTLEMENT_ACCOUNT.account_number.slice(-4), + updated_by_account_id: storeA.seller_account_id, + updated_by_role: 'SELLER', + }); + expect(account.account_number_enc).not.toContain( + SEED_SETTLEMENT_ACCOUNT.account_number, + ); + expect( + new AccountCipher(readAccountCryptoConfig()).decrypt( + account.account_number_enc, + 'settlement-account', + ), + ).toBe(SEED_SETTLEMENT_ACCOUNT.account_number); + }); + it('시드 사용자가 시드 밖 리뷰에 단 댓글은 지우고 그 리뷰는 남긴다', async () => { const [seedUser] = await seedThroughReviews(); const outsideReview = await createReview(prisma); From ace9ba4b6e421c4dc9fbf2ff8ece85022f5872a9 Mon Sep 17 00:00:00 2001 From: chanwoo7 Date: Thu, 19 Nov 2026 01:41:08 +0900 Subject: [PATCH 09/54] =?UTF-8?q?fix:=20=EA=B3=84=EC=A2=8C=EB=B2=88?= =?UTF-8?q?=ED=98=B8=20=EC=9E=AC=EC=95=94=ED=98=B8=ED=99=94=EA=B0=80=20?= =?UTF-8?q?=EB=A7=88=EC=A7=80=EB=A7=89=20=EB=B3=80=EA=B2=BD=20=EC=8B=9C?= =?UTF-8?q?=EA=B0=81=EC=9D=84=20=EB=B0=94=EA=BE=B8=EC=A7=80=20=EC=95=8A?= =?UTF-8?q?=EA=B2=8C=20=ED=95=98=EA=B3=A0=20=EC=8A=A4=ED=81=AC=EB=A6=BD?= =?UTF-8?q?=ED=8A=B8=20=EA=B0=80=EB=93=9C=20=ED=85=8C=EC=8A=A4=ED=8A=B8=20?= =?UTF-8?q?=EC=B6=94=EA=B0=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 리뷰 지적을 반영한다. - 키 회전 재암호화(updateMany)가 @updatedAt 때문에 store_settlement_account·refund·settlement의 updated_at을 회전 시각으로 바꿨다. 정산 계좌 updatedAt은 SDL에서 '마지막 변경 시각'으로 updatedByRole과 나란히 내려가, 아무도 바꾸지 않은 계좌를 판매자·관리자가 그 시각에 바꾼 것처럼 보였다. - 재암호화 스크립트의 안전 가드(알 수 없는 인자 거절, 고정 개발 키 거절)가 main() 안에만 있어 자동 테스트가 없었다. 변경 - AccountNumberReencryptRepository: updated_at도 읽어 updateMany data에 읽은 값을 다시 쓴다. where에도 updated_at을 더해, 읽은 뒤 다른 필드가 바뀐 행(토큰은 그대로)은 건너뛴다. 넣지 않으면 그 행의 최신 updated_at을 옛 값으로 되돌린다. 건너뛴 행은 다음 실행 대상으로 남는다(runbook의 0이 될 때까지 반복과 같음) - scripts/accounts-reencrypt-args.ts: parseReencryptArgs·assertRotatableConfig로 분리하고 스크립트가 이를 쓴다(동작 동일) 테스트 - 재암호화 repository(real DB): 세 칼럼 재암호화 뒤 updated_at 불변, 읽은 직후 상태가 바뀐 환불은 건너뛰고 updated_at을 되돌리지 않으며 다음 실행 대상으로 남음 - scripts/accounts-reencrypt.spec.ts 9건: 인자 2(없음·--dry-run), 반증 4(--dryrun·--dry-run=true·여분 인자·대시 없음), 키 가드 통과 1·개발 키 거절 2 - 반증: data의 updated_at 보존을 지우면 불변 단언이, where의 updated_at을 지우면 경합 케이스가, 가드 두 곳을 끄면 scripts spec 6건이 실패함을 확인 --- scripts/accounts-reencrypt-args.ts | 19 ++++++ scripts/accounts-reencrypt.spec.ts | 38 +++++++++++ scripts/accounts-reencrypt.ts | 19 +++--- ...ccount-number-reencrypt.repository.spec.ts | 65 +++++++++++++++---- .../account-number-reencrypt.repository.ts | 52 +++++++++++---- 5 files changed, 158 insertions(+), 35 deletions(-) create mode 100644 scripts/accounts-reencrypt-args.ts create mode 100644 scripts/accounts-reencrypt.spec.ts diff --git a/scripts/accounts-reencrypt-args.ts b/scripts/accounts-reencrypt-args.ts new file mode 100644 index 00000000..0d8ddcb9 --- /dev/null +++ b/scripts/accounts-reencrypt-args.ts @@ -0,0 +1,19 @@ +/** 인자·키 가드만 — spec이 DB·키 없이 검증할 수 있게 분리한다. */ +export function parseReencryptArgs(argv: string[]): { dryRun: boolean } { + const unknown = argv.filter((arg) => arg !== '--dry-run'); + if (unknown.length > 0) { + throw new Error(`알 수 없는 인자: ${unknown.join(' ')}`); + } + return { dryRun: argv.includes('--dry-run') }; +} + +/** 공개된 고정 개발 키로 다시 암호화하면 운영 계좌번호를 누구나 풀 수 있게 된다. */ +export function assertRotatableConfig(config: { + devKeyReason: string | null; +}): void { + if (config.devKeyReason) { + throw new Error( + `고정 개발 키로는 재암호화하지 않습니다: ${config.devKeyReason}`, + ); + } +} diff --git a/scripts/accounts-reencrypt.spec.ts b/scripts/accounts-reencrypt.spec.ts new file mode 100644 index 00000000..54369bdf --- /dev/null +++ b/scripts/accounts-reencrypt.spec.ts @@ -0,0 +1,38 @@ +import { + assertRotatableConfig, + parseReencryptArgs, +} from './accounts-reencrypt-args'; + +describe('accounts-reencrypt 인자', () => { + it.each([ + [[], false], + [['--dry-run'], true], + ])('%j → dryRun %s', (argv, dryRun) => { + expect(parseReencryptArgs(argv)).toEqual({ dryRun }); + }); + + // 반증 — 오타가 dry-run 없는 실제 재암호화로 흘러가지 않는다 + it.each([ + [['--dryrun']], + [['--dry-run=true']], + [['--dry-run', '--all']], + [['dry-run']], + ])('반증: %j 는 던진다', (argv) => { + expect(() => parseReencryptArgs(argv)).toThrow('알 수 없는 인자'); + }); +}); + +describe('accounts-reencrypt 키 가드', () => { + it('설정한 키(devKeyReason null)는 통과한다', () => { + expect(() => assertRotatableConfig({ devKeyReason: null })).not.toThrow(); + }); + + it.each([ + 'ACCOUNT_ENCRYPTION_KEYS 미설정', + 'ACCOUNT_ENCRYPTION_KEYS 형식 오류(콜론 없음)', + ])('반증: 개발 키로 대신한 설정(%s)은 던진다', (devKeyReason) => { + expect(() => assertRotatableConfig({ devKeyReason })).toThrow( + '고정 개발 키로는 재암호화하지 않습니다', + ); + }); +}); diff --git a/scripts/accounts-reencrypt.ts b/scripts/accounts-reencrypt.ts index b95639c4..f0b6e63f 100644 --- a/scripts/accounts-reencrypt.ts +++ b/scripts/accounts-reencrypt.ts @@ -6,6 +6,11 @@ */ import '@/config/preload-env'; +import { + assertRotatableConfig, + parseReencryptArgs, +} from './accounts-reencrypt-args'; + import { readAccountCryptoConfig } from '@/config/account-crypto.config'; import { AccountNumberReencryptRepository } from '@/features/order/repositories/account-number-reencrypt.repository'; import { AccountCipher } from '@/global/crypto/account-cipher.service'; @@ -15,17 +20,9 @@ import { createExtendedPrismaClient } from '@/prisma/prisma.service'; async function main(): Promise { const databaseUrl = process.env.DATABASE_URL; if (!databaseUrl) throw new Error('DATABASE_URL이 필요합니다'); - const argv = process.argv.slice(2); - const unknown = argv.filter((arg) => arg !== '--dry-run'); - if (unknown.length > 0) - throw new Error(`알 수 없는 인자: ${unknown.join(' ')}`); - + const { dryRun } = parseReencryptArgs(process.argv.slice(2)); const config = readAccountCryptoConfig(); - if (config.devKeyReason) { - throw new Error( - `고정 개발 키로는 재암호화하지 않습니다: ${config.devKeyReason}`, - ); - } + assertRotatableConfig(config); const cipher = new AccountCipher(config); const prisma = createExtendedPrismaClient(databaseUrl); try { @@ -38,7 +35,7 @@ async function main(): Promise { process.stdout.write( `primary key ${cipher.primaryKeyId}, 대상 ${JSON.stringify(stale)}\n`, ); - if (argv.includes('--dry-run')) return; + if (dryRun) return; const done = await repo.reencryptStale(); process.stdout.write(`재암호화 ${JSON.stringify(done)}\n`); } finally { diff --git a/src/features/order/repositories/account-number-reencrypt.repository.spec.ts b/src/features/order/repositories/account-number-reencrypt.repository.spec.ts index b84453c8..b4a7f805 100644 --- a/src/features/order/repositories/account-number-reencrypt.repository.spec.ts +++ b/src/features/order/repositories/account-number-reencrypt.repository.spec.ts @@ -30,6 +30,9 @@ describe('AccountNumberReencryptRepository (real DB)', () => { const repoWith = (cipher: AccountCipher) => new AccountNumberReencryptRepository(prisma, cipher); + // 재암호화가 updated_at을 건드리는지 가리려고 과거 시각으로 만든다 + const PAST = new Date('2026-01-01T00:00:00.000Z'); + /** 세 칼럼에 k1 토큰을 하나씩, 환불은 계좌 미입력 행과 이미 k2인 행도 둔다. */ async function seedTokens() { const store = await createStore(prisma); @@ -42,6 +45,7 @@ describe('AccountNumberReencryptRepository (real DB)', () => { amount: 1000, requested_at: new Date(), account_number_enc: token, + updated_at: PAST, }, }); const stale = await refund( @@ -58,6 +62,7 @@ describe('AccountNumberReencryptRepository (real DB)', () => { account_number_last4: '5555', updated_by_account_id: store.seller_account_id, updated_by_role: 'SELLER', + updated_at: PAST, }, }); const settlement = await prisma.settlement.create({ @@ -74,6 +79,7 @@ describe('AccountNumberReencryptRepository (real DB)', () => { '44445555', 'settlement-account', ), + updated_at: PAST, }, }); return { stale, fresh, account, settlement }; @@ -95,22 +101,25 @@ describe('AccountNumberReencryptRepository (real DB)', () => { settlement: 0, }); - const refundToken = ( - await prisma.refund.findUniqueOrThrow({ where: { id: stale.id } }) - ).account_number_enc!; - const accountToken = ( - await prisma.storeSettlementAccount.findUniqueOrThrow({ - where: { id: account.id }, - }) - ).account_number_enc; - const paidToken = ( - await prisma.settlement.findUniqueOrThrow({ - where: { id: settlement.id }, - }) - ).paid_account_number_enc!; + const refundRow = await prisma.refund.findUniqueOrThrow({ + where: { id: stale.id }, + }); + const accountRow = await prisma.storeSettlementAccount.findUniqueOrThrow({ + where: { id: account.id }, + }); + const settlementRow = await prisma.settlement.findUniqueOrThrow({ + where: { id: settlement.id }, + }); + const refundToken = refundRow.account_number_enc!; + const accountToken = accountRow.account_number_enc; + const paidToken = settlementRow.paid_account_number_enc!; for (const token of [refundToken, accountToken, paidToken]) { expect(token.startsWith('v1.k2.')).toBe(true); } + // '마지막 변경 시각'은 키 회전으로 움직이지 않는다 + for (const row of [refundRow, accountRow, settlementRow]) { + expect(row.updated_at).toEqual(PAST); + } // 옛 키를 뺀 뒤에도 풀린다 — 회전 마지막 단계(옛 키 제거)의 전제 const newOnly = new AccountCipher({ keys: [k2] }); expect(newOnly.decrypt(refundToken, 'refund-account')).toBe('1111222233'); @@ -124,6 +133,36 @@ describe('AccountNumberReencryptRepository (real DB)', () => { ).toBe(freshBefore); }); + it('읽은 뒤 다른 요청이 바꾼 행은 건너뛰어 updated_at을 되돌리지 않고, 다음 실행 대상으로 남긴다', async () => { + const { stale } = await seedTokens(); + const findMany = prisma.refund.findMany.bind(prisma.refund); + // 재암호화가 행을 읽은 직후 같은 환불의 상태가 바뀐다(토큰은 그대로) + const race = jest + .spyOn(prisma.refund, 'findMany') + .mockImplementationOnce((async (args: Parameters[0]) => { + const rows = await findMany(args); + await prisma.refund.update({ + where: { id: stale.id }, + data: { status: 'AWAITING_TRANSFER' }, + }); + return rows; + }) as unknown as typeof prisma.refund.findMany); + + try { + expect((await repoWith(rotated).reencryptStale()).refund).toBe(0); + } finally { + race.mockRestore(); + } + + const row = await prisma.refund.findUniqueOrThrow({ + where: { id: stale.id }, + }); + expect(row.status).toBe('AWAITING_TRANSFER'); + expect(row.updated_at.getTime()).toBeGreaterThan(PAST.getTime()); + expect(row.account_number_enc!.startsWith('v1.k1.')).toBe(true); + expect((await repoWith(rotated).countStale()).refund).toBe(1); + }); + it('대상은 첫 키 기준이다 — 첫 키가 k1이면 k2 토큰만 센다', async () => { await seedTokens(); expect(await repoWith(oldCipher).countStale()).toEqual({ diff --git a/src/features/order/repositories/account-number-reencrypt.repository.ts b/src/features/order/repositories/account-number-reencrypt.repository.ts index ccd9f20d..a2b11d4e 100644 --- a/src/features/order/repositories/account-number-reencrypt.repository.ts +++ b/src/features/order/repositories/account-number-reencrypt.repository.ts @@ -13,11 +13,13 @@ export interface ReencryptCounts { interface EncryptedRow { id: bigint; token: string; + updatedAt: Date; } /** * 키 회전용(`yarn accounts:reencrypt`). 첫 키가 아닌 키로 암호화된 계좌번호를 첫 키로 다시 암호화한다. - * 행마다 읽은 토큰이 그대로일 때만 바꿔, 그사이 사용자가 새로 입력한 계좌를 옛 값으로 덮지 않는다. + * 행마다 읽은 토큰·updated_at이 그대로일 때만 바꿔, 그사이 바뀐 행(새로 입력한 계좌 등)을 덮지 않는다. + * updated_at은 읽은 값으로 다시 써서 화면의 '마지막 변경 시각'이 키 회전으로 움직이지 않게 한다. */ export class AccountNumberReencryptRepository { constructor( @@ -43,25 +45,42 @@ export class AccountNumberReencryptRepository { }; for (const row of rows.refund) { const { count } = await this.prisma.refund.updateMany({ - where: { id: row.id, account_number_enc: row.token }, - data: { account_number_enc: this.rotate(row.token, 'refund-account') }, + where: { + id: row.id, + account_number_enc: row.token, + updated_at: row.updatedAt, + }, + data: { + account_number_enc: this.rotate(row.token, 'refund-account'), + updated_at: row.updatedAt, + }, }); counts.refund += count; } for (const row of rows.storeSettlementAccount) { const { count } = await this.prisma.storeSettlementAccount.updateMany({ - where: { id: row.id, account_number_enc: row.token }, + where: { + id: row.id, + account_number_enc: row.token, + updated_at: row.updatedAt, + }, data: { account_number_enc: this.rotate(row.token, 'settlement-account'), + updated_at: row.updatedAt, }, }); counts.storeSettlementAccount += count; } for (const row of rows.settlement) { const { count } = await this.prisma.settlement.updateMany({ - where: { id: row.id, paid_account_number_enc: row.token }, + where: { + id: row.id, + paid_account_number_enc: row.token, + updated_at: row.updatedAt, + }, data: { paid_account_number_enc: this.rotate(row.token, 'settlement-account'), + updated_at: row.updatedAt, }, }); counts.settlement += count; @@ -79,35 +98,46 @@ export class AccountNumberReencryptRepository { const [refunds, accounts, settlements] = await Promise.all([ this.prisma.refund.findMany({ where: { account_number_enc: { not: null } }, - select: { id: true, account_number_enc: true }, + select: { id: true, account_number_enc: true, updated_at: true }, orderBy: { id: 'asc' }, }), this.prisma.storeSettlementAccount.findMany({ - select: { id: true, account_number_enc: true }, + select: { id: true, account_number_enc: true, updated_at: true }, orderBy: { id: 'asc' }, }), this.prisma.settlement.findMany({ where: { paid_account_number_enc: { not: null } }, - select: { id: true, paid_account_number_enc: true }, + select: { id: true, paid_account_number_enc: true, updated_at: true }, orderBy: { id: 'asc' }, }), ]); - const stale = (rows: { id: bigint; token: string | null }[]) => + const stale = ( + rows: { id: bigint; token: string | null; updatedAt: Date }[], + ) => rows.filter( (row): row is EncryptedRow => row.token !== null && this.cipher.isStale(row.token), ); return { refund: stale( - refunds.map((r) => ({ id: r.id, token: r.account_number_enc })), + refunds.map((r) => ({ + id: r.id, + token: r.account_number_enc, + updatedAt: r.updated_at, + })), ), storeSettlementAccount: stale( - accounts.map((r) => ({ id: r.id, token: r.account_number_enc })), + accounts.map((r) => ({ + id: r.id, + token: r.account_number_enc, + updatedAt: r.updated_at, + })), ), settlement: stale( settlements.map((r) => ({ id: r.id, token: r.paid_account_number_enc, + updatedAt: r.updated_at, })), ), }; From c65709493cca36ec322a8f52126e3a249e0f3d33 Mon Sep 17 00:00:00 2001 From: chanwoo7 Date: Thu, 19 Nov 2026 01:41:29 +0900 Subject: [PATCH 10/54] =?UTF-8?q?fix:=20=EA=B4=80=EB=A6=AC=EC=9E=90=20?= =?UTF-8?q?=EA=B2=B0=EC=A0=9C=20=EC=84=A4=EC=A0=95=20=EC=82=AC=EC=9C=A0=20?= =?UTF-8?q?=EA=B8=B8=EC=9D=B4=20=EC=98=A4=EB=A5=98=20=EC=BD=94=EB=93=9C?= =?UTF-8?q?=EC=99=80=20=ED=8C=90=EB=A7=A4=EC=9E=90=20=EA=B0=90=EC=82=AC=20?= =?UTF-8?q?=EB=A1=9C=EA=B7=B8=20=EC=84=A4=EB=AA=85=20=EC=A0=95=EC=A0=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 리뷰 지적을 반영한다. - adminUpdatePaymentSetting SDL은 사유가 길면 TEXT_TOO_LONG이라고 적었지만, 두 관리자 입력 DTO의 @MaxLength(MAX_REASON_LENGTH)가 먼저 걸려 500자 초과 사유는 ValidationPipe의 VALIDATION_FAILED로 거절된다. adminUpsertStoreSettlementAccount도 같은 코드를 따른다고 적혀 있어 둘 다 어긋났다. 다른 관리자 사유 입력(정지·숨김 등)이 DTO MaxLength를 쓰므로 동작은 두고 SDL을 고친다. - SellerAuditLog 설명이 '판매자 조작'으로만 적혀 있었는데, 관리자가 그 매장에 한 조작(정산 계좌 대리 수정·주문 취소 등)도 함께 보인다. 변경 - order-payment-admin.graphql: 예금주는 비었거나 50자 초과면 TEXT_REQUIRED·TEXT_TOO_LONG, 사유는 비면 TEXT_REQUIRED, 500자 초과면 VALIDATION_FAILED - store-seller-audit.graphql: SellerAuditLog 설명에 관리자 조작 포함을 적음 테스트 - AdminUpdatePaymentSettingInput·AdminUpsertStoreSettlementAccountInput spec 각 2건: 사유 500자 통과·501자 거절, 예금주 51자는 DTO에서 거르지 않음(서비스가 TEXT_TOO_LONG) - 반증: 두 DTO에서 사유 MaxLength를 지우면 501자 거절 2건이 실패함을 확인 --- ...admin-update-payment-setting.input.spec.ts | 35 +++++++++++++++ ...ert-store-settlement-account.input.spec.ts | 43 +++++++++++++++++++ .../order/order-payment-admin.graphql | 5 ++- src/features/store/store-seller-audit.graphql | 2 +- 4 files changed, 82 insertions(+), 3 deletions(-) create mode 100644 src/features/order/dto/inputs/admin-update-payment-setting.input.spec.ts create mode 100644 src/features/order/dto/inputs/admin-upsert-store-settlement-account.input.spec.ts diff --git a/src/features/order/dto/inputs/admin-update-payment-setting.input.spec.ts b/src/features/order/dto/inputs/admin-update-payment-setting.input.spec.ts new file mode 100644 index 00000000..26298b72 --- /dev/null +++ b/src/features/order/dto/inputs/admin-update-payment-setting.input.spec.ts @@ -0,0 +1,35 @@ +import 'reflect-metadata'; + +import { plainToInstance } from 'class-transformer'; +import { validate } from 'class-validator'; + +import { MAX_REASON_LENGTH } from '@/common/constants/reason.constants'; +import { AdminUpdatePaymentSettingInput } from '@/features/order/dto/inputs/admin-update-payment-setting.input'; + +async function invalidProps(plain: object): Promise { + const errors = await validate( + plainToInstance(AdminUpdatePaymentSettingInput, plain), + ); + return errors.map((e) => e.property); +} + +// 사유 길이는 DTO(VALIDATION_FAILED)가, 예금주 길이는 서비스(TEXT_TOO_LONG)가 거절한다 +describe('AdminUpdatePaymentSettingInput', () => { + it('사유 500자는 통과하고 501자는 거절한다', async () => { + expect( + await invalidProps({ reason: 'r'.repeat(MAX_REASON_LENGTH) }), + ).toEqual([]); + expect( + await invalidProps({ reason: 'r'.repeat(MAX_REASON_LENGTH + 1) }), + ).toEqual(['reason']); + }); + + it('예금주 길이는 DTO에서 거르지 않는다', async () => { + expect( + await invalidProps({ + depositAccountHolder: '가'.repeat(51), + reason: '사유', + }), + ).toEqual([]); + }); +}); diff --git a/src/features/order/dto/inputs/admin-upsert-store-settlement-account.input.spec.ts b/src/features/order/dto/inputs/admin-upsert-store-settlement-account.input.spec.ts new file mode 100644 index 00000000..302b29a9 --- /dev/null +++ b/src/features/order/dto/inputs/admin-upsert-store-settlement-account.input.spec.ts @@ -0,0 +1,43 @@ +import 'reflect-metadata'; + +import { plainToInstance } from 'class-transformer'; +import { validate } from 'class-validator'; + +import { MAX_REASON_LENGTH } from '@/common/constants/reason.constants'; +import { AdminUpsertStoreSettlementAccountInput } from '@/features/order/dto/inputs/admin-upsert-store-settlement-account.input'; + +const VALID = { + storeId: '1', + bankCode: '004', + accountHolder: '케이크샵', + accountNumber: '12345678', + reason: '사유', +}; + +async function invalidProps(plain: object): Promise { + const errors = await validate( + plainToInstance(AdminUpsertStoreSettlementAccountInput, plain), + ); + return errors.map((e) => e.property); +} + +// 사유 길이는 DTO(VALIDATION_FAILED)가, 예금주 길이는 서비스(TEXT_TOO_LONG)가 거절한다 +describe('AdminUpsertStoreSettlementAccountInput', () => { + it('사유 500자는 통과하고 501자는 거절한다', async () => { + expect( + await invalidProps({ ...VALID, reason: 'r'.repeat(MAX_REASON_LENGTH) }), + ).toEqual([]); + expect( + await invalidProps({ + ...VALID, + reason: 'r'.repeat(MAX_REASON_LENGTH + 1), + }), + ).toEqual(['reason']); + }); + + it('예금주 길이는 DTO에서 거르지 않는다', async () => { + expect( + await invalidProps({ ...VALID, accountHolder: '가'.repeat(51) }), + ).toEqual([]); + }); +}); diff --git a/src/features/order/order-payment-admin.graphql b/src/features/order/order-payment-admin.graphql index 65694d3c..88076511 100644 --- a/src/features/order/order-payment-admin.graphql +++ b/src/features/order/order-payment-admin.graphql @@ -15,8 +15,9 @@ extend type Mutation { """ 플랫폼 결제 설정을 바꾼다. 보낸 필드만 바꾸고 생략·null인 필드는 그대로 둔다. 수수료율은 바꾼 뒤 생성되는 주문부터 적용된다. 수수료율이 0~10000bp 밖이면 INVALID_COMMISSION_RATE, 은행 코드가 paymentBanks에 없으면 INVALID_BANK_CODE, - 계좌번호가 하이픈을 뺀 숫자 8~20자리가 아니면 INVALID_ACCOUNT_NUMBER, 예금주·사유가 비었거나 길면 TEXT_REQUIRED·TEXT_TOO_LONG - (모두 BAD_USER_INPUT). 감사 로그(PAYMENT_SETTING)를 남긴다. 관리자 로그인 필수. ADMIN 계정이 아니면 FORBIDDEN. + 계좌번호가 하이픈을 뺀 숫자 8~20자리가 아니면 INVALID_ACCOUNT_NUMBER, 예금주가 비었거나 50자를 넘으면 TEXT_REQUIRED·TEXT_TOO_LONG, + 사유가 비면 TEXT_REQUIRED, 500자를 넘으면 VALIDATION_FAILED(모두 BAD_USER_INPUT). 감사 로그(PAYMENT_SETTING)를 남긴다. + 관리자 로그인 필수. ADMIN 계정이 아니면 FORBIDDEN. """ adminUpdatePaymentSetting( input: AdminUpdatePaymentSettingInput! diff --git a/src/features/store/store-seller-audit.graphql b/src/features/store/store-seller-audit.graphql index 07080782..148f6458 100644 --- a/src/features/store/store-seller-audit.graphql +++ b/src/features/store/store-seller-audit.graphql @@ -6,7 +6,7 @@ extend type Query { } """ -판매자 조작 감사 로그 1건. 매장 설정·상품·주문 변경 이력을 남긴다. +내 매장 감사 로그 1건. 매장 설정·상품·주문·정산 계좌 변경 이력을 남기며, 관리자가 이 매장에 한 조작(대리 수정·주문 취소 등)도 포함한다. 로그는 누적만 되고 수정·삭제되지 않는다. """ type SellerAuditLog { From e55543d04c4d4cce905a5037d12398d4d06b984f Mon Sep 17 00:00:00 2001 From: chanwoo7 Date: Thu, 19 Nov 2026 01:23:56 +0900 Subject: [PATCH 11/54] =?UTF-8?q?feat:=20=EC=83=81=ED=92=88=20=EC=BB=A4?= =?UTF-8?q?=EC=8A=A4=ED=85=80=20=EB=B0=A9=EC=8B=9D=EA=B3=BC=20=EB=AC=B8?= =?UTF-8?q?=EA=B5=AC=20=EC=9E=90=EB=A6=AC=20=ED=91=9C=EC=8B=9C=20=EC=9D=B4?= =?UTF-8?q?=EB=A6=84=C2=B7=EC=8A=A4=ED=83=80=EC=9D=BC=C2=B7=EC=A2=8C?= =?UTF-8?q?=ED=91=9C=20=EA=B2=80=EC=A6=9D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 상품마다 커스텀 방식(없음·슬롯형·3D)을 두고, 슬롯형 문구 자리에 표시 이름·글자색·정렬을 더하며 좌표를 서버가 검증한다. 템플릿 활성 토글은 커스텀 방식이, 상품 바탕 이미지(base_design_image_url)는 템플릿 바탕이, 옵션 커스텀 요구 플래그는 커스텀 방식이 대신해 지운다. 운영 판매자가 없어 레거시 필드는 바로 지우고 기존 데이터는 백필로 옮긴다. 변경점 - 스키마: Product.custom_mode(CustomMode NONE·SLOT·THREE_D), 템플릿 free_edit_enabled·revision, 문구 자리 label VarChar(30)·max_length 기본 20·pos_x..height NOT NULL·text_color Char(7) 기본 #000000·text_align(CustomTextAlign) 기본 CENTER. DROP product.base_design_image_url, product_option_group.option_requires_*, 템플릿 is_active - 백필: 활성·미삭제 템플릿 상품은 SLOT, label = 키 앞 30자, 기본 문구 50자 절단, max_length를 기본 문구 길이 이상·50 이하로, 좌표가 하나라도 없으면 판매자 앱 기본 배치(템플릿별 활성 순번, 위에서 2000 간격), 좌표를 0~10000으로 자른 뒤 NOT NULL. 순번은 임시 표로 뽑는다(임시 표는 한 문장에서 두 번 읽을 수 없어 백필 검증이 깨진다) - 준비 상태: product 순수 헬퍼 evaluateProductCustomIssues(배럴 공개). SLOT_TEMPLATE_MISSING, SLOT_NOTHING_TO_EDIT(문구 자리 0 ∧ 자유 편집 꺼짐), 3D는 옵션 3D 연결 칸이 생기기 전까지 THREE_D_GROUP_MISSING - API: sellerSetProductCustomMode(productId, customMode)(준비 이슈가 있으면 CUSTOM_PRODUCT_NOT_READY, 같은 방식이면 감사 없이 그대로), SellerProduct.customMode·customReadiness(방식별 ready·issues), sellerSetProductCustomTemplateActive 삭제 - 템플릿: freeEditEnabled(생략하면 새 템플릿 false·기존 유지), revision은 템플릿 갱신과 슬롯 등록·수정·삭제·순서 변경 tx 안에서 1씩 올린다 - 문구 자리 검증: 키 ^[a-z0-9]{1,60}$(CUSTOM_TOKEN_KEY_INVALID, 규칙 전 키는 바꾸지 않으면 허용), maxLength 1~50(FIELD_OUT_OF_RANGE), 기본 문구 ≤ maxLength 코드 포인트(CUSTOM_TEXT_DEFAULT_TOO_LONG), 좌표 0~10000·너비·높이 1 이상·x+w·y+h ≤ 10000(CUSTOM_AREA_OUT_OF_BOUNDS), 글자색 #RRGGBB 대문자 저장(INVALID_COLOR_FORMAT). label·textColor·textAlign은 SDL 기본값 없이 생략하면 수정은 유지, 등록은 키·#000000·CENTER - 조회: 구매자 ProductDetail.customMode·customTemplate(SLOT일 때만, revision·바탕·자유 편집·문구 자리), 관리자 AdminProduct.customMode·thumbnailUrl(삭제 제외 첫 이미지, 목록 include에 images take 1)·템플릿 freeEditEnabled·슬롯 표시 이름·스타일 - 주문 생성의 OPTION_CUSTOMIZATION_REQUIRED 가드와 에러 코드 삭제(플래그 컬럼이 없어짐) - 게이트: removed-schema-elements에 삭제 출력 필드 8·입력 필드 7·타입 1·루트 필드 1과 입력 필드 판정기(반증 포함), enum-sdl-sync에 CustomMode·CustomTextAlign - 테스트 인프라: createCustomTemplate·createCustomTextToken 팩토리 테스트 - migration spec 4: SLOT 백필(활성·비활성·삭제·없음), 표시 이름·기본 문구·최대 글자 수(이모지 코드 포인트 포함), 좌표 기본 배치·클램프(삭제 자리 순번·8500 상한·템플릿별 순번), 백필 없이는 NOT NULL 전환 실패(반증). 템플릿 is_active·좌표 NULL은 최신 스키마에서 만들 수 없어 연결 하나에서 같은 이름 임시 표로 가린다 - 준비 상태 표 9, 방식 변경 8(다른 매장 404, 준비 안 됨 3, 슬롯형 전환·감사 2, 없음 전환, 같은 방식 멱등) - 좌표 경계 표 11, maxLength 4, 기본 문구 코드 포인트 1, 키 형식 6 + 규칙 전 키 1, 글자색 3, 표시 이름 2, 기본값·유지·저장 3 - revision 지점 1(템플릿 갱신·등록 2·수정·순서·삭제가 1씩), 실패한 슬롯 변경은 revision 불변 1, 글자색·정렬 등록 기본값·수정 유지 1 - 구매자 상세 4(SLOT 템플릿·없음·3D·삭제 템플릿), 관리자 목록 썸네일 1(상세 썸네일 단언 추가)·커스텀 필드 1, 판매자 상세 1, DTO 14(문구 자리 11·템플릿 자유 편집 3) - 가드 반증: 백필 클램프·revision 증가·준비 판정·좌표 경계를 하나씩 깨면 해당 테스트가 실패함을 확인 --- .../migration.sql | 49 ++ prisma/schema.prisma | 40 +- src/common/errors/error-catalog.spec.ts | 1 + src/common/errors/error-catalog.ts | 25 +- .../services/order-checkout.service.spec.ts | 36 - .../order/services/order-checkout.service.ts | 8 - .../constants/product-seller.constants.ts | 9 +- .../seller-create-option-group.input.spec.ts | 2 - .../seller-create-option-group.input.ts | 8 - .../dto/inputs/seller-create-product.input.ts | 4 - ...oduct-custom-template-active.input.spec.ts | 29 - ...et-product-custom-template-active.input.ts | 9 - .../seller-update-option-group.input.ts | 8 - .../dto/inputs/seller-update-product.input.ts | 4 - ...sert-product-custom-template.input.spec.ts | 4 +- ...er-upsert-product-custom-template.input.ts | 2 +- ...rt-product-custom-text-token.input.spec.ts | 79 ++- ...-upsert-product-custom-text-token.input.ts | 32 +- src/features/product/index.ts | 5 + src/features/product/product-admin.graphql | 32 +- src/features/product/product-detail.graphql | 47 ++ src/features/product/product-seller.graphql | 209 +++--- src/features/product/product.types.graphql | 24 + .../custom-product-settings.migration.spec.ts | 284 ++++++++ .../repositories/product-admin.repository.ts | 9 +- .../repositories/product.repository.spec.ts | 251 ++++--- .../repositories/product.repository.ts | 187 ++++-- .../product-seller-mutation.resolver.ts | 16 +- .../resolvers/product-seller.resolver.spec.ts | 23 +- .../services/product-admin-mappers.helper.ts | 5 +- .../services/product-admin.service.spec.ts | 138 ++-- .../product-custom-readiness.helper.spec.ts | 58 ++ .../product-custom-readiness.helper.ts | 53 ++ .../services/product-detail-mappers.helper.ts | 37 +- .../services/product-detail.service.spec.ts | 90 +++ ...uct-seller-custom-template.service.spec.ts | 619 ++++++++++++------ .../product-seller-custom-template.service.ts | 260 ++++---- .../product-seller-lifecycle.service.spec.ts | 51 +- .../product-seller-lifecycle.service.ts | 29 - .../services/product-seller-mappers.helper.ts | 96 ++- .../product-seller-option.service.spec.ts | 6 +- .../services/product-seller-option.service.ts | 12 - .../product-seller-query.service.spec.ts | 56 +- .../types/product-admin-output.type.ts | 4 +- .../types/product-detail-output.type.ts | 26 + .../types/product-seller-output.type.ts | 28 +- src/graphql/removed-schema-elements.spec.ts | 54 ++ src/test/enum-sdl-sync.spec.ts | 14 + src/test/factories/custom-template.factory.ts | 63 ++ src/test/factories/index.ts | 1 + 50 files changed, 2164 insertions(+), 972 deletions(-) create mode 100644 prisma/migrations/20261118155816_custom_product_settings/migration.sql delete mode 100644 src/features/product/dto/inputs/seller-set-product-custom-template-active.input.spec.ts delete mode 100644 src/features/product/dto/inputs/seller-set-product-custom-template-active.input.ts create mode 100644 src/features/product/repositories/custom-product-settings.migration.spec.ts create mode 100644 src/features/product/services/product-custom-readiness.helper.spec.ts create mode 100644 src/features/product/services/product-custom-readiness.helper.ts create mode 100644 src/test/factories/custom-template.factory.ts diff --git a/prisma/migrations/20261118155816_custom_product_settings/migration.sql b/prisma/migrations/20261118155816_custom_product_settings/migration.sql new file mode 100644 index 00000000..f4fb3780 --- /dev/null +++ b/prisma/migrations/20261118155816_custom_product_settings/migration.sql @@ -0,0 +1,49 @@ +-- 상품 커스텀 방식(없음·슬롯형·3D)과 문구 자리 표시 이름·글자색·정렬, 템플릿 자유 편집·revision. +-- 템플릿 활성 토글은 커스텀 방식이, 상품 바탕 이미지는 템플릿 바탕이, 옵션 커스텀 요구 플래그는 커스텀 방식이 대신해 지운다. +-- AlterTable +ALTER TABLE `product` ADD COLUMN `custom_mode` ENUM('NONE', 'SLOT', 'THREE_D') NOT NULL DEFAULT 'NONE'; + +-- AlterTable +ALTER TABLE `product_custom_template` ADD COLUMN `free_edit_enabled` BOOLEAN NOT NULL DEFAULT false, + ADD COLUMN `revision` INTEGER UNSIGNED NOT NULL DEFAULT 1; + +-- AlterTable +ALTER TABLE `product_custom_text_token` ADD COLUMN `label` VARCHAR(30) NULL, + ADD COLUMN `text_align` ENUM('LEFT', 'CENTER', 'RIGHT') NOT NULL DEFAULT 'CENTER', + ADD COLUMN `text_color` CHAR(7) NOT NULL DEFAULT '#000000', + MODIFY `max_length` SMALLINT UNSIGNED NOT NULL DEFAULT 20; + +-- backfill: 활성 템플릿이 있는 상품은 슬롯형이다 +UPDATE `product` p JOIN `product_custom_template` t ON t.`product_id` = p.`id` SET p.`custom_mode` = 'SLOT' WHERE t.`is_active` = 1 AND t.`deleted_at` IS NULL; +-- 표시 이름은 키에서 따온다. 기본 문구는 50자에서 자르고, 최대 글자 수는 기본 문구 길이 이상·50 이하로 맞춘다 +UPDATE `product_custom_text_token` SET `label` = LEFT(`token_key`, 30); +UPDATE `product_custom_text_token` SET `default_text` = LEFT(`default_text`, 50) WHERE CHAR_LENGTH(`default_text`) > 50; +UPDATE `product_custom_text_token` SET `max_length` = LEAST(50, GREATEST(`max_length`, CHAR_LENGTH(`default_text`), 1)); +-- 좌표가 하나라도 없으면 판매자 앱 기본 배치(활성 자리 순서대로 위에서 2000 간격)로 채운다. +-- 순번은 별도 임시 표로 뽑는다 — 같은 표를 한 문장에서 두 번 읽으면 임시 표(백필 검증)에서 실패한다 +CREATE TEMPORARY TABLE `_custom_text_token_rank` AS + SELECT `id`, ROW_NUMBER() OVER (PARTITION BY `template_id` ORDER BY `deleted_at` IS NOT NULL, `sort_order`, `id`) - 1 AS `idx` + FROM `product_custom_text_token`; +UPDATE `product_custom_text_token` t JOIN `_custom_text_token_rank` r ON r.`id` = t.`id` +SET t.`pos_x` = 1000, t.`pos_y` = LEAST(1000 + r.`idx` * 2000, 8500), t.`width` = 8000, t.`height` = 1500 +WHERE t.`pos_x` IS NULL OR t.`pos_y` IS NULL OR t.`width` IS NULL OR t.`height` IS NULL; +DROP TEMPORARY TABLE `_custom_text_token_rank`; +UPDATE `product_custom_text_token` SET `pos_x` = LEAST(GREATEST(`pos_x`, 0), 10000), `pos_y` = LEAST(GREATEST(`pos_y`, 0), 10000), `width` = LEAST(GREATEST(`width`, 0), 10000), `height` = LEAST(GREATEST(`height`, 0), 10000); +-- end backfill + +-- AlterTable +ALTER TABLE `product_custom_text_token` MODIFY `label` VARCHAR(30) NOT NULL, + MODIFY `pos_x` INTEGER NOT NULL, + MODIFY `pos_y` INTEGER NOT NULL, + MODIFY `width` INTEGER NOT NULL, + MODIFY `height` INTEGER NOT NULL; + +-- AlterTable +ALTER TABLE `product_custom_template` DROP COLUMN `is_active`; + +-- AlterTable +ALTER TABLE `product` DROP COLUMN `base_design_image_url`; + +-- AlterTable +ALTER TABLE `product_option_group` DROP COLUMN `option_requires_description`, + DROP COLUMN `option_requires_image`; diff --git a/prisma/schema.prisma b/prisma/schema.prisma index c295faed..75b2a879 100644 --- a/prisma/schema.prisma +++ b/prisma/schema.prisma @@ -46,6 +46,18 @@ enum CategoryType { OTHER } +enum CustomMode { + NONE + SLOT + THREE_D +} + +enum CustomTextAlign { + LEFT + CENTER + RIGHT +} + enum OrderStatus { SUBMITTED CONFIRMED @@ -659,8 +671,8 @@ model Product { currency String @default("KRW") @db.Char(3) - base_design_image_url String? @db.VarChar(2048) - preparation_time_minutes Int @default(180) @db.UnsignedInt + preparation_time_minutes Int @default(180) @db.UnsignedInt + custom_mode CustomMode @default(NONE) is_active Boolean @default(true) @db.TinyInt @@ -761,9 +773,6 @@ model ProductOptionGroup { min_select Int @default(1) @db.UnsignedSmallInt max_select Int @default(1) @db.UnsignedSmallInt - option_requires_description Boolean @default(false) @db.TinyInt - option_requires_image Boolean @default(false) @db.TinyInt - sort_order Int @default(0) is_active Boolean @default(true) @db.TinyInt @@ -816,8 +825,10 @@ model ProductCustomTemplate { id BigInt @id @default(autoincrement()) @db.UnsignedBigInt product_id BigInt @unique @db.UnsignedBigInt - base_image_url String @db.VarChar(2048) - is_active Boolean @default(true) @db.TinyInt + base_image_url String @db.VarChar(2048) + free_edit_enabled Boolean @default(false) @db.TinyInt + // 템플릿·슬롯이 바뀔 때마다 1 올린다. 구매자가 꾸민 기준과 주문 시점 설정이 같은지 대조한다 + revision Int @default(1) @db.UnsignedInt created_at DateTime @default(now()) @db.DateTime(3) updated_at DateTime @updatedAt @db.DateTime(3) @@ -836,15 +847,20 @@ model ProductCustomTextToken { template_id BigInt @db.UnsignedBigInt token_key String @db.VarChar(60) + label String @db.VarChar(30) default_text String @db.VarChar(200) - max_length Int @default(30) @db.UnsignedSmallInt + max_length Int @default(20) @db.UnsignedSmallInt sort_order Int @default(0) is_required Boolean @default(true) @db.TinyInt - pos_x Int? - pos_y Int? - width Int? - height Int? + // 바탕 이미지 한 변을 10000으로 본 정수 비율, 원점은 왼쪽 위 + pos_x Int + pos_y Int + width Int + height Int + + text_color String @default("#000000") @db.Char(7) + text_align CustomTextAlign @default(CENTER) created_at DateTime @default(now()) @db.DateTime(3) updated_at DateTime @updatedAt @db.DateTime(3) diff --git a/src/common/errors/error-catalog.spec.ts b/src/common/errors/error-catalog.spec.ts index 9f1b73d9..471452f0 100644 --- a/src/common/errors/error-catalog.spec.ts +++ b/src/common/errors/error-catalog.spec.ts @@ -32,6 +32,7 @@ const RENDER_PARAMS: Partial< INVALID_PHONE_FORMAT: { example: '010-1234-5678' }, INVALID_LIMIT: { max: 50 }, FIELD_OUT_OF_RANGE: { field: 'capacity', min: 1, max: 100 }, + CUSTOM_TEXT_DEFAULT_TOO_LONG: { label: '이름', max: 20 }, IDS_LENGTH_MISMATCH: { field: 'imageIds' }, INVALID_IDS: { field: 'imageIds' }, PRODUCT_IMAGE_LIMIT_EXCEEDED: { max: 10 }, diff --git a/src/common/errors/error-catalog.ts b/src/common/errors/error-catalog.ts index 5b55082a..37eb2083 100644 --- a/src/common/errors/error-catalog.ts +++ b/src/common/errors/error-catalog.ts @@ -331,10 +331,6 @@ export const ERROR_CATALOG = { status: HttpStatus.BAD_REQUEST, message: '옵션 그룹의 선택 규칙을 충족하지 않습니다.', }, - OPTION_CUSTOMIZATION_REQUIRED: { - status: HttpStatus.BAD_REQUEST, - message: '커스텀 정보가 필요한 옵션은 아직 주문할 수 없습니다.', - }, PICKUP_NOT_AVAILABLE: { status: HttpStatus.BAD_REQUEST, message: '선택한 픽업 일시는 예약할 수 없습니다.', @@ -466,6 +462,27 @@ export const ERROR_CATALOG = { status: HttpStatus.CONFLICT, message: '이 템플릿에 이미 같은 키의 커스텀 텍스트 토큰이 있습니다.', }, + CUSTOM_PRODUCT_NOT_READY: { + status: HttpStatus.BAD_REQUEST, + message: '커스텀 설정이 아직 끝나지 않았어요.', + }, + CUSTOM_TOKEN_KEY_INVALID: { + status: HttpStatus.BAD_REQUEST, + message: '문구 자리 키는 영문 소문자와 숫자 1~60자여야 해요.', + }, + CUSTOM_TEXT_DEFAULT_TOO_LONG: { + status: HttpStatus.BAD_REQUEST, + message: ({ label, max }) => + `'${label}'의 기본 문구는 ${max}자 이하여야 해요.`, + }, + CUSTOM_AREA_OUT_OF_BOUNDS: { + status: HttpStatus.BAD_REQUEST, + message: '문구 자리가 바탕 이미지 밖으로 나갔어요.', + }, + INVALID_COLOR_FORMAT: { + status: HttpStatus.BAD_REQUEST, + message: '글자색은 #RRGGBB 형식으로 입력해 주세요.', + }, INVALID_DAY_OF_WEEK: { status: HttpStatus.BAD_REQUEST, message: 'dayOfWeek는 0~6이어야 합니다.', diff --git a/src/features/order/services/order-checkout.service.spec.ts b/src/features/order/services/order-checkout.service.spec.ts index 48ee471f..5483414f 100644 --- a/src/features/order/services/order-checkout.service.spec.ts +++ b/src/features/order/services/order-checkout.service.spec.ts @@ -416,42 +416,6 @@ describe('OrderCheckoutService (real DB)', () => { ).rejects.toThrowDomain(400); }); - it('설명/이미지 필수 옵션 선택은 커스텀 확장 전까지 거절한다', async () => { - const store = await makeOpenStore(); - const product = await createProduct(prisma, { store_id: store.id }); - const group = await prisma.productOptionGroup.create({ - data: { - product_id: product.id, - name: '레터링', - is_required: false, - min_select: 1, - max_select: 1, - option_requires_description: true, - }, - }); - const item = await prisma.productOptionItem.create({ - data: { option_group_id: group.id, title: '문구 입력', price_delta: 0 }, - }); - const buyer = await makeBuyer(); - - await expect( - service.createOrder( - buyer.id, - baseInput({ - productId: product.id.toString(), - optionItemIds: [item.id.toString()], - }), - ), - ).rejects.toThrowDomain(400); - - // 해당 그룹을 선택하지 않으면 주문 가능(선택 그룹이므로) - const ok = await service.createOrder( - buyer.id, - baseInput({ productId: product.id.toString() }), - ); - expect(ok.status).toBe('SUBMITTED'); - }); - it('없거나 비활성 상품·비활성 매장 상품은 NOT_FOUND다', async () => { const buyer = await makeBuyer(); const inactiveStore = await createStore(prisma, { is_active: false }); diff --git a/src/features/order/services/order-checkout.service.ts b/src/features/order/services/order-checkout.service.ts index d22b6512..0359ada0 100644 --- a/src/features/order/services/order-checkout.service.ts +++ b/src/features/order/services/order-checkout.service.ts @@ -237,14 +237,6 @@ export class OrderCheckoutService { if (!valid) { throw new DomainException('OPTION_GROUP_RULE_VIOLATION'); } - // 설명/이미지 필수 옵션은 커스텀 입력 없이는 판매자 요구 정보가 빠진 채 - // 주문된다 — 커스텀 체크아웃 확장 전까지 해당 옵션 선택은 거절한다 - if ( - count > 0 && - (group.option_requires_description || group.option_requires_image) - ) { - throw new DomainException('OPTION_CUSTOMIZATION_REQUIRED'); - } } return selections; } diff --git a/src/features/product/constants/product-seller.constants.ts b/src/features/product/constants/product-seller.constants.ts index 209e10a5..d67c99d9 100644 --- a/src/features/product/constants/product-seller.constants.ts +++ b/src/features/product/constants/product-seller.constants.ts @@ -23,9 +23,14 @@ export const MAX_OPTION_ITEM_DESCRIPTION_LENGTH = 500; // ── 커스텀 템플릿 ── -export const MAX_TOKEN_KEY_LENGTH = 60; +export const TOKEN_KEY_PATTERN = /^[a-z0-9]{1,60}$/; +export const MAX_TOKEN_LABEL_LENGTH = 30; export const MAX_TOKEN_DEFAULT_TEXT_LENGTH = 200; -export const DEFAULT_TOKEN_MAX_LENGTH = 30; +export const DEFAULT_TOKEN_MAX_LENGTH = 20; +export const TOKEN_MAX_LENGTH_RANGE = { min: 1, max: 50 } as const; +export const DEFAULT_TEXT_COLOR = '#000000'; +/** 바탕 이미지 한 변을 이 값으로 본 정수 비율이 문구 자리 좌표다(원점 왼쪽 위). */ +export const CUSTOM_AREA_SCALE = 10_000; // ── 태그 검색 ── diff --git a/src/features/product/dto/inputs/seller-create-option-group.input.spec.ts b/src/features/product/dto/inputs/seller-create-option-group.input.spec.ts index 289d85a5..37f71b73 100644 --- a/src/features/product/dto/inputs/seller-create-option-group.input.spec.ts +++ b/src/features/product/dto/inputs/seller-create-option-group.input.spec.ts @@ -22,8 +22,6 @@ describe('SellerCreateOptionGroupInput', () => { isRequired: true, minSelect: 1, maxSelect: 2, - optionRequiresDescription: false, - optionRequiresImage: false, sortOrder: 0, isActive: true, }); diff --git a/src/features/product/dto/inputs/seller-create-option-group.input.ts b/src/features/product/dto/inputs/seller-create-option-group.input.ts index 112046d1..89dbb5e9 100644 --- a/src/features/product/dto/inputs/seller-create-option-group.input.ts +++ b/src/features/product/dto/inputs/seller-create-option-group.input.ts @@ -26,14 +26,6 @@ export class SellerCreateOptionGroupInput { @Min(1) maxSelect?: number; - @IsOptional() - @IsBoolean() - optionRequiresDescription?: boolean; - - @IsOptional() - @IsBoolean() - optionRequiresImage?: boolean; - @IsOptional() @IsInt() sortOrder?: number; diff --git a/src/features/product/dto/inputs/seller-create-product.input.ts b/src/features/product/dto/inputs/seller-create-product.input.ts index 73012ab3..8899279b 100644 --- a/src/features/product/dto/inputs/seller-create-product.input.ts +++ b/src/features/product/dto/inputs/seller-create-product.input.ts @@ -29,10 +29,6 @@ export class SellerCreateProductInput { @IsString() currency?: string; - @IsOptional() - @IsString() - baseDesignImageUrl?: string; - @IsOptional() @IsInt() @Min(1) diff --git a/src/features/product/dto/inputs/seller-set-product-custom-template-active.input.spec.ts b/src/features/product/dto/inputs/seller-set-product-custom-template-active.input.spec.ts deleted file mode 100644 index 54b2b174..00000000 --- a/src/features/product/dto/inputs/seller-set-product-custom-template-active.input.spec.ts +++ /dev/null @@ -1,29 +0,0 @@ -import 'reflect-metadata'; - -import { plainToInstance } from 'class-transformer'; -import { validate } from 'class-validator'; - -import { SellerSetProductCustomTemplateActiveInput } from '@/features/product/dto/inputs/seller-set-product-custom-template-active.input'; - -function build(plain: object): SellerSetProductCustomTemplateActiveInput { - return plainToInstance(SellerSetProductCustomTemplateActiveInput, plain); -} - -describe('SellerSetProductCustomTemplateActiveInput', () => { - it('정상 통과', async () => { - const dto = build({ templateId: '1', isActive: true }); - expect(await validate(dto)).toHaveLength(0); - }); - - it('templateId 누락 거절', async () => { - const dto = build({ isActive: true }); - const errors = await validate(dto); - expect(errors[0].property).toBe('templateId'); - }); - - it('isActive 누락 거절', async () => { - const dto = build({ templateId: '1' }); - const errors = await validate(dto); - expect(errors[0].property).toBe('isActive'); - }); -}); diff --git a/src/features/product/dto/inputs/seller-set-product-custom-template-active.input.ts b/src/features/product/dto/inputs/seller-set-product-custom-template-active.input.ts deleted file mode 100644 index fb43b660..00000000 --- a/src/features/product/dto/inputs/seller-set-product-custom-template-active.input.ts +++ /dev/null @@ -1,9 +0,0 @@ -import { IsBoolean, IsString } from 'class-validator'; - -export class SellerSetProductCustomTemplateActiveInput { - @IsString() - templateId!: string; - - @IsBoolean() - isActive!: boolean; -} diff --git a/src/features/product/dto/inputs/seller-update-option-group.input.ts b/src/features/product/dto/inputs/seller-update-option-group.input.ts index cf79ddf1..07723bf3 100644 --- a/src/features/product/dto/inputs/seller-update-option-group.input.ts +++ b/src/features/product/dto/inputs/seller-update-option-group.input.ts @@ -26,14 +26,6 @@ export class SellerUpdateOptionGroupInput { @Min(1) maxSelect?: number; - @IsOptional() - @IsBoolean() - optionRequiresDescription?: boolean; - - @IsOptional() - @IsBoolean() - optionRequiresImage?: boolean; - @IsOptional() @IsInt() sortOrder?: number; diff --git a/src/features/product/dto/inputs/seller-update-product.input.ts b/src/features/product/dto/inputs/seller-update-product.input.ts index 2f21b81b..43165b5d 100644 --- a/src/features/product/dto/inputs/seller-update-product.input.ts +++ b/src/features/product/dto/inputs/seller-update-product.input.ts @@ -30,10 +30,6 @@ export class SellerUpdateProductInput { @IsString() currency?: string; - @IsOptional() - @IsString() - baseDesignImageUrl?: string; - @IsOptional() @IsInt() @Min(1) diff --git a/src/features/product/dto/inputs/seller-upsert-product-custom-template.input.spec.ts b/src/features/product/dto/inputs/seller-upsert-product-custom-template.input.spec.ts index d0df8966..ab7909d5 100644 --- a/src/features/product/dto/inputs/seller-upsert-product-custom-template.input.spec.ts +++ b/src/features/product/dto/inputs/seller-upsert-product-custom-template.input.spec.ts @@ -18,11 +18,11 @@ describe('SellerUpsertProductCustomTemplateInput', () => { expect(await validate(dto)).toHaveLength(0); }); - it('isActive 포함 통과', async () => { + it.each([true, false, null])('freeEditEnabled %s 통과', async (value) => { const dto = build({ productId: '1', baseImageUrl: 'https://x/y.jpg', - isActive: false, + freeEditEnabled: value, }); expect(await validate(dto)).toHaveLength(0); }); diff --git a/src/features/product/dto/inputs/seller-upsert-product-custom-template.input.ts b/src/features/product/dto/inputs/seller-upsert-product-custom-template.input.ts index 8f352423..77a16076 100644 --- a/src/features/product/dto/inputs/seller-upsert-product-custom-template.input.ts +++ b/src/features/product/dto/inputs/seller-upsert-product-custom-template.input.ts @@ -9,5 +9,5 @@ export class SellerUpsertProductCustomTemplateInput { @IsOptional() @IsBoolean() - isActive?: boolean; + freeEditEnabled?: boolean | null; } diff --git a/src/features/product/dto/inputs/seller-upsert-product-custom-text-token.input.spec.ts b/src/features/product/dto/inputs/seller-upsert-product-custom-text-token.input.spec.ts index 6b9fbe5d..9cbd0ffe 100644 --- a/src/features/product/dto/inputs/seller-upsert-product-custom-text-token.input.spec.ts +++ b/src/features/product/dto/inputs/seller-upsert-product-custom-text-token.input.spec.ts @@ -9,64 +9,63 @@ function build(plain: object): SellerUpsertProductCustomTextTokenInput { return plainToInstance(SellerUpsertProductCustomTextTokenInput, plain); } +const REQUIRED = { + templateId: '1', + tokenKey: 'name', + defaultText: '홍길동', + posX: 0, + posY: 0, + width: 100, + height: 50, +}; + describe('SellerUpsertProductCustomTextTokenInput', () => { it('필수만 통과 (신규)', async () => { - const dto = build({ - templateId: '1', - tokenKey: 'name', - defaultText: '홍길동', - }); - expect(await validate(dto)).toHaveLength(0); + expect(await validate(build(REQUIRED))).toHaveLength(0); }); it('전체 필드 통과 (수정)', async () => { const dto = build({ + ...REQUIRED, tokenId: '5', - templateId: '1', - tokenKey: 'name', - defaultText: '홍길동', + label: '받는 사람', maxLength: 30, sortOrder: 0, isRequired: true, - posX: 100, - posY: 200, - width: 300, - height: 50, + textColor: '#FF0000', + textAlign: 'LEFT', }); expect(await validate(dto)).toHaveLength(0); }); - it('tokenKey 누락 거절', async () => { - const dto = build({ templateId: '1', defaultText: '홍길동' }); - const errors = await validate(dto); - expect(errors[0].property).toBe('tokenKey'); + it('표시 이름·글자색·정렬의 명시적 null은 생략과 같다', async () => { + const dto = build({ + ...REQUIRED, + label: null, + textColor: null, + textAlign: null, + }); + expect(await validate(dto)).toHaveLength(0); }); - it('defaultText 누락 거절', async () => { - const dto = build({ templateId: '1', tokenKey: 'name' }); - const errors = await validate(dto); - expect(errors[0].property).toBe('defaultText'); - }); + it.each(['tokenKey', 'defaultText', 'posX', 'posY', 'width', 'height'])( + '%s 누락 거절', + async (field) => { + const plain: Record = { ...REQUIRED }; + delete plain[field]; + const errors = await validate(build(plain)); + expect(errors.map((e) => e.property)).toEqual([field]); + }, + ); - it('maxLength 0 거절', async () => { - const dto = build({ - templateId: '1', - tokenKey: 'name', - defaultText: '홍길동', - maxLength: 0, - }); - const errors = await validate(dto); - expect(errors[0].property).toBe('maxLength'); + it('정렬은 LEFT·CENTER·RIGHT만 받는다', async () => { + const errors = await validate(build({ ...REQUIRED, textAlign: 'JUSTIFY' })); + expect(errors.map((e) => e.property)).toEqual(['textAlign']); }); - it('width 0 거절', async () => { - const dto = build({ - templateId: '1', - tokenKey: 'name', - defaultText: '홍길동', - width: 0, - }); - const errors = await validate(dto); - expect(errors[0].property).toBe('width'); + // 범위·형식은 도메인 오류 코드를 내도록 service가 검사한다 + it('최대 글자 수·좌표 범위는 DTO에서 막지 않는다', async () => { + const dto = build({ ...REQUIRED, maxLength: 0, posX: -1, width: 0 }); + expect(await validate(dto)).toHaveLength(0); }); }); diff --git a/src/features/product/dto/inputs/seller-upsert-product-custom-text-token.input.ts b/src/features/product/dto/inputs/seller-upsert-product-custom-text-token.input.ts index 2f0d95ce..c8a9817d 100644 --- a/src/features/product/dto/inputs/seller-upsert-product-custom-text-token.input.ts +++ b/src/features/product/dto/inputs/seller-upsert-product-custom-text-token.input.ts @@ -1,5 +1,8 @@ -import { IsBoolean, IsInt, IsOptional, IsString, Min } from 'class-validator'; +import { IsBoolean, IsIn, IsInt, IsOptional, IsString } from 'class-validator'; +import { CustomTextAlign } from '@/generated/prisma/client'; + +/** 범위·형식(최대 글자 수·좌표·글자색·키)은 도메인 오류 코드를 내도록 service가 검사한다. */ export class SellerUpsertProductCustomTextTokenInput { @IsOptional() @IsString() @@ -11,12 +14,15 @@ export class SellerUpsertProductCustomTextTokenInput { @IsString() tokenKey!: string; + @IsOptional() + @IsString() + label?: string | null; + @IsString() defaultText!: string; @IsOptional() @IsInt() - @Min(1) maxLength?: number; @IsOptional() @@ -27,21 +33,23 @@ export class SellerUpsertProductCustomTextTokenInput { @IsBoolean() isRequired?: boolean; - @IsOptional() @IsInt() - posX?: number; + posX!: number; - @IsOptional() @IsInt() - posY?: number; + posY!: number; - @IsOptional() @IsInt() - @Min(1) - width?: number; + width!: number; - @IsOptional() @IsInt() - @Min(1) - height?: number; + height!: number; + + @IsOptional() + @IsString() + textColor?: string | null; + + @IsOptional() + @IsIn(Object.values(CustomTextAlign)) + textAlign?: CustomTextAlign | null; } diff --git a/src/features/product/index.ts b/src/features/product/index.ts index 76b8e9e1..e15f2687 100644 --- a/src/features/product/index.ts +++ b/src/features/product/index.ts @@ -5,6 +5,11 @@ export { // 주문 생성(order feature)의 옵션 검증·가격 스냅샷 입력 타입 type ProductDetailRow, } from '@/features/product/repositories/product.repository'; +// 커스텀 방식 준비 상태. 판매자 방식 변경과 주문 생성(order feature)이 같은 판정을 쓴다. +export { + evaluateProductCustomIssues, + type ProductCustomIssue, +} from '@/features/product/services/product-custom-readiness.helper'; // 상품 카드 1벌. 찜·최근 본 상품(user feature)이 같은 카드를 쓴다. export { ProductCardService } from '@/features/product/services/product-card.service'; export type { ProductCardOutput } from '@/features/product/types/product-card-output.type'; diff --git a/src/features/product/product-admin.graphql b/src/features/product/product-admin.graphql index f56e997f..45fcc238 100644 --- a/src/features/product/product-admin.graphql +++ b/src/features/product/product-admin.graphql @@ -51,9 +51,13 @@ type AdminProduct { """ currency: String! """ - 기본 디자인 이미지 URL. 미등록 시 null. + 대표 이미지 URL(삭제 제외 첫 장). 이미지가 없으면 null. """ - baseDesignImageUrl: String + thumbnailUrl: String + """ + 커스텀 방식. + """ + customMode: CustomModeType! """ 노출 여부. false면 구매자 화면에 나오지 않는다. """ @@ -173,14 +177,6 @@ type AdminProductOptionGroup { """ maxSelect: Int! """ - 선택지에 구매자 커스텀 입력(설명)이 필요한 그룹인지. 현재는 true인 그룹의 옵션을 고르면 주문이 거절된다(잠정 가드). - """ - optionRequiresDescription: Boolean! - """ - 선택지에 구매자 커스텀 입력(이미지)이 필요한 그룹인지. 현재는 true인 그룹의 옵션을 고르면 주문이 거절된다(잠정 가드). - """ - optionRequiresImage: Boolean! - """ 상품 안에서의 그룹 노출 순서. 오름차순. """ sortOrder: Int! @@ -235,9 +231,9 @@ type AdminProductCustomTemplate { """ baseImageUrl: String! """ - 활성 여부. false면 구매자 화면에 커스텀 입력이 열리지 않는다. + 자유 편집(바탕 위 영역 지정 + 요청 문구·참고 사진) 허용 여부. """ - isActive: Boolean! + freeEditEnabled: Boolean! """ 문구 슬롯. sortOrder 오름차순. 삭제된 슬롯은 뺀다. """ @@ -254,6 +250,10 @@ type AdminProductCustomTextToken { """ tokenKey: String! """ + 표시 이름(구매자 입력 화면 라벨). + """ + label: String! + """ 구매자가 입력하지 않았을 때 쓸 기본 문구. """ defaultText: String! @@ -269,6 +269,14 @@ type AdminProductCustomTextToken { 필수 입력 여부. """ isRequired: Boolean! + """ + 글자색(#RRGGBB 대문자). + """ + textColor: String! + """ + 자리 안 글자 정렬. + """ + textAlign: CustomTextAlignType! } """ diff --git a/src/features/product/product-detail.graphql b/src/features/product/product-detail.graphql index 81bcb54f..e81aded6 100644 --- a/src/features/product/product-detail.graphql +++ b/src/features/product/product-detail.graphql @@ -30,6 +30,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! } """상품 상세 옵션 섹션(그룹).""" diff --git a/src/features/product/product-seller.graphql b/src/features/product/product-seller.graphql index 37eeb965..f1796dfb 100644 --- a/src/features/product/product-seller.graphql +++ b/src/features/product/product-seller.graphql @@ -113,21 +113,31 @@ 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. + 상품 커스텀 템플릿(슬롯형 바탕)을 등록 또는 수정한다. 수정하면 revision이 1 오른다. + 판매자 로그인 필수. SELLER 계정이 아니면 FORBIDDEN, 매장을 보유하지 않으면 NOT_FOUND. """ - sellerSetProductCustomTemplateActive( - input: SellerSetProductCustomTemplateActiveInput! + 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! @@ -260,17 +270,6 @@ type SellerOptionGroup { """ maxSelect: Int! """ - 선택지에 구매자 커스텀 입력(설명)이 필요한 그룹인지. - 현재는 커스텀 체크아웃이 확장되기 전이라, 이 값이 true인 그룹의 옵션을 고르면 - 주문이 거절된다(잠정 가드). 켜기 전에 주문 가능 여부를 확인해야 한다. - """ - optionRequiresDescription: Boolean! - """ - 선택지에 구매자 커스텀 입력(이미지)이 필요한 그룹인지. - optionRequiresDescription과 마찬가지로 현재는 true인 그룹의 옵션 선택이 거절된다. - """ - optionRequiresImage: Boolean! - """ 상품 안에서의 그룹 노출 순서. 오름차순. """ sortOrder: Int! @@ -295,11 +294,15 @@ type SellerCustomTextToken { """ tokenKey: String! """ + 표시 이름(구매자 입력 화면 라벨). 주문에 스냅샷으로 남는다. + """ + label: String! + """ 구매자가 입력하지 않았을 때 쓸 기본 문구. """ defaultText: String! """ - 입력 가능한 최대 글자 수. + 입력 가능한 최대 글자 수(코드 포인트, 1~50). """ maxLength: Int! """ @@ -311,39 +314,50 @@ type SellerCustomTextToken { """ isRequired: Boolean! """ - 문구 영역 왼쪽 위 모서리의 가로 위치. 베이스 이미지 한 변을 10000으로 본 정수 비율(0~10000)이고 서버는 범위를 검사하지 않는다. - 미지정 시 null이고 배치는 클라이언트가 정한다. + 문구 영역 왼쪽 위 모서리의 가로 위치. 바탕 이미지 한 변을 10000으로 본 정수 비율(0~10000), 원점은 왼쪽 위. + """ + posX: Int! + """ + 문구 영역 왼쪽 위 모서리의 세로 위치(0~10000). """ - posX: Int + posY: Int! """ - 문구 영역 왼쪽 위 모서리의 세로 위치. 베이스 이미지 한 변을 10000으로 본 정수 비율(0~10000). 미지정 시 null. + 문구 영역 너비(1~10000, posX + width ≤ 10000). """ - posY: Int + width: Int! """ - 문구 영역 너비. 베이스 이미지 한 변을 10000으로 본 정수 비율(1~10000). 미지정 시 null. + 문구 영역 높이(1~10000, posY + height ≤ 10000). """ - width: Int + height: Int! """ - 문구 영역 높이. 베이스 이미지 한 변을 10000으로 본 정수 비율(1~10000). 미지정 시 null. + 글자색(#RRGGBB 대문자). """ - height: Int + 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 오름차순. """ @@ -381,14 +395,19 @@ type SellerProduct { """ currency: String! """ - 커스텀 도안의 바탕 이미지 URL. 커스텀을 쓰지 않으면 null. - """ - baseDesignImageUrl: String - """ 제작 소요 시간(분). 픽업 가능 시각 계산의 리드타임에 반영된다. """ preparationTimeMinutes: Int! """ + 커스텀 방식. 바꾸려면 sellerSetProductCustomMode. + """ + customMode: CustomModeType! + """ + 커스텀 방식별 준비 상태(NONE·SLOT·THREE_D 순). 준비 이슈가 있는 방식으로는 바꿀 수 없고, + 지금 방식에 이슈가 생기면 구매자 주문이 거절된다. + """ + customReadiness: [SellerCustomReadiness!]! + """ 노출 여부. false면 구매자 화면에 나오지 않는다. """ isActive: Boolean! @@ -416,6 +435,42 @@ type SellerProduct { updatedAt: DateTime! } +""" +커스텀 방식 하나의 준비 상태. +""" +type SellerCustomReadiness { + """ + 대상 커스텀 방식. + """ + mode: CustomModeType! + """ + issues가 비어 있으면 true. + """ + ready: Boolean! + """ + 준비 이슈. 판매자에게 그대로 보여 줄 메시지를 담는다. + """ + issues: [SellerCustomReadinessIssue!]! +} + +""" +커스텀 준비 이슈 1건. +""" +type SellerCustomReadinessIssue { + """ + 이슈 코드(SLOT_TEMPLATE_MISSING, SLOT_NOTHING_TO_EDIT, THREE_D_GROUP_MISSING 등). 값이 늘 수 있어 문자열이다. + """ + code: String! + """ + 판매자에게 보여 줄 안내 문장. + """ + message: String! + """ + 이슈가 걸린 옵션 그룹. 그룹과 무관하면 null. + """ + optionGroupId: ID +} + """ 상품 목록 페이지. 최신 등록이 먼저 온다. """ @@ -498,10 +553,6 @@ input SellerCreateProductInput { """ currency: String = "KRW" """ - 커스텀 도안의 바탕 이미지 URL. sellerCreateUploadUrl(PRODUCT_IMAGE)로 이 계정에 발급된 publicUrl만 허용, 아니면 BAD_USER_INPUT. - """ - baseDesignImageUrl: String - """ 제작 소요 시간(분). 기본 180. """ preparationTimeMinutes: Int = 180 @@ -541,10 +592,6 @@ input SellerUpdateProductInput { """ currency: String """ - 커스텀 도안의 바탕 이미지 URL. sellerCreateUploadUrl(PRODUCT_IMAGE)로 이 계정에 발급된 publicUrl만 허용, 아니면 BAD_USER_INPUT. - """ - baseDesignImageUrl: String - """ 제작 소요 시간(분). """ preparationTimeMinutes: Int @@ -663,14 +710,6 @@ input SellerCreateOptionGroupInput { """ maxSelect: Int = 1 """ - 구매자 커스텀 입력(설명)이 필요한 그룹으로 표시한다. 기본 false. 현재는 켜면 해당 옵션 주문이 거절된다. - """ - optionRequiresDescription: Boolean = false - """ - 구매자 커스텀 입력(이미지)이 필요한 그룹으로 표시한다. 기본 false. 현재는 켜면 해당 옵션 주문이 거절된다. - """ - optionRequiresImage: Boolean = false - """ 노출 순서. 오름차순이고 동률의 순서는 보장하지 않는다. 미지정 시 0. """ sortOrder: Int @@ -706,14 +745,6 @@ input SellerUpdateOptionGroupInput { """ maxSelect: Int """ - 구매자 커스텀 입력(설명)이 필요한 그룹으로 표시한다. 현재는 켜면 해당 옵션 주문이 거절된다. - """ - optionRequiresDescription: Boolean - """ - 구매자 커스텀 입력(이미지)이 필요한 그룹으로 표시한다. 현재는 켜면 해당 옵션 주문이 거절된다. - """ - optionRequiresImage: Boolean - """ 노출 순서. """ sortOrder: Int @@ -815,24 +846,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 } """ @@ -845,17 +865,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. """ @@ -865,22 +889,29 @@ input SellerUpsertProductCustomTextTokenInput { """ isRequired: Boolean = true """ - 문구 영역 왼쪽 위 모서리의 가로 위치. 베이스 이미지 한 변을 10000으로 본 정수 비율(0~10000)이고 서버는 범위를 검사하지 않는다. - 생략 시 배치를 클라이언트가 정한다. + 문구 영역 왼쪽 위 모서리의 가로 위치. 바탕 이미지 한 변을 10000으로 본 정수 비율(0~10000), 원점은 왼쪽 위. + """ + posX: Int! + """ + 문구 영역 왼쪽 위 모서리의 세로 위치(0~10000). + """ + posY: Int! + """ + 문구 영역 너비(1 이상, posX + width ≤ 10000). """ - posX: Int + width: Int! """ - 문구 영역 왼쪽 위 모서리의 세로 위치. 베이스 이미지 한 변을 10000으로 본 정수 비율(0~10000). + 문구 영역 높이(1 이상, posY + height ≤ 10000). """ - posY: Int + height: Int! """ - 문구 영역 너비. 베이스 이미지 한 변을 10000으로 본 정수 비율(1~10000). + 글자색 #RRGGBB(대소문자 무관, 대문자로 저장). 생략하면 수정은 지금 값을 두고, 등록은 #000000. """ - width: Int + textColor: String """ - 문구 영역 높이. 베이스 이미지 한 변을 10000으로 본 정수 비율(1~10000). + 자리 안 글자 정렬. 생략하면 수정은 지금 값을 두고, 등록은 CENTER. """ - height: Int + textAlign: CustomTextAlignType } """ diff --git a/src/features/product/product.types.graphql b/src/features/product/product.types.graphql index 37472ecf..b15b116f 100644 --- a/src/features/product/product.types.graphql +++ b/src/features/product/product.types.graphql @@ -70,3 +70,27 @@ enum BannerPlacement { """예약값. 이 자리를 읽는 구매자 쿼리가 없어 등록해도 노출되지 않는다.""" STORE } + +""" +상품의 커스텀 방식. 방식이 있는 상품은 구매자가 꾸민 내용 없이 주문할 수 없다. +""" +enum CustomModeType { + """커스텀 없음. 옵션만 고르고 주문한다.""" + NONE + """슬롯형. 판매자가 정한 바탕 이미지 위 문구 자리에 문구를 넣는다(자유 편집은 상품별 선택).""" + SLOT + """3D. 모양·크기 등 옵션을 3D 케이크로 꾸민다. 자유 편집은 없다.""" + THREE_D +} + +""" +문구 자리 안 글자 정렬. +""" +enum CustomTextAlignType { + """왼쪽 정렬.""" + LEFT + """가운데 정렬.""" + CENTER + """오른쪽 정렬.""" + RIGHT +} diff --git a/src/features/product/repositories/custom-product-settings.migration.spec.ts b/src/features/product/repositories/custom-product-settings.migration.spec.ts new file mode 100644 index 00000000..ec44560d --- /dev/null +++ b/src/features/product/repositories/custom-product-settings.migration.spec.ts @@ -0,0 +1,284 @@ +import { readFileSync } from 'node:fs'; +import { join } from 'node:path'; + +import mysql, { type RowDataPacket } from 'mysql2/promise'; + +import type { PrismaClient } from '@/generated/prisma/client'; +import { + disconnectTestPrismaClient, + getTestDatabaseUrl, +} from '@/test/db/prisma-test-client'; +import { closeTruncateConnection, truncateAll } from '@/test/db/truncate'; +import { createProduct, nextSeq } from '@/test/factories'; +import { createTestingModuleWithRealDb } from '@/test/modules/testing-module.builder'; + +// 커스텀 설정 마이그레이션의 백필 SQL을 그대로 실행해 기존 템플릿·문구 자리가 새 규칙으로 옮겨지는지 본다. +// 백필이 읽는 템플릿 is_active는 같은 마이그레이션에서 지워지고 좌표 NULL 행은 최신 스키마에서 만들 수 없어, +// 백필 직전 모양의 임시 표로 같은 이름을 가린 연결 하나에서 돌린다(임시 표는 세션 범위라 풀 연결로는 안 보인다). +const SQL = readFileSync( + join( + __dirname, + '../../../../prisma/migrations/20261118155816_custom_product_settings/migration.sql', + ), + 'utf8', +); + +function statements(body: string): string[] { + return body + .split(';') + .map((stmt) => stmt.replace(/^\s*--[^\n]*$/gm, '').trim()) + .filter((stmt) => stmt.length > 0); +} + +const BACKFILL = statements( + SQL.slice(SQL.indexOf('-- backfill'), SQL.indexOf('-- end backfill')), +); +/** 백필 바로 뒤 NOT NULL 전환. 백필이 남긴 NULL이 있으면 여기서 실패한다. */ +const NOT_NULL_AFTER_BACKFILL = statements( + SQL.slice(SQL.indexOf('-- end backfill')), +)[0]; + +const LEGACY_SHAPES: Array<[table: string, alter: string]> = [ + [ + 'product_custom_template', + 'ADD COLUMN `is_active` TINYINT(1) NOT NULL DEFAULT 1', + ], + [ + 'product_custom_text_token', + 'MODIFY `label` VARCHAR(30) NULL, MODIFY `pos_x` INT NULL, MODIFY `pos_y` INT NULL, MODIFY `width` INT NULL, MODIFY `height` INT NULL', + ], +]; + +describe('상품 커스텀 설정 백필 (real DB)', () => { + let prisma: PrismaClient; + + beforeAll(async () => { + ({ prisma } = await createTestingModuleWithRealDb({ providers: [] })); + }); + afterAll(async () => { + await closeTruncateConnection(); + await disconnectTestPrismaClient(); + }); + beforeEach(async () => { + await truncateAll(); + }); + + async function withLegacyTables( + run: (conn: mysql.Connection) => Promise, + ): Promise { + const conn = await mysql.createConnection({ uri: getTestDatabaseUrl() }); + try { + for (const [table, alter] of LEGACY_SHAPES) { + // 같은 이름을 LIKE로 바로 만들 수 없어 사본을 거친다 + await conn.query( + `CREATE TEMPORARY TABLE \`_legacy_${table}\` LIKE \`${table}\``, + ); + await conn.query( + `CREATE TEMPORARY TABLE \`${table}\` LIKE \`_legacy_${table}\``, + ); + // 가림이 안 된 채 ALTER가 진짜 표에 닿지 않게 먼저 확인한다 + const [[shown]] = await conn.query( + `SHOW CREATE TABLE \`${table}\``, + ); + expect(String(shown['Create Table'])).toMatch( + /^CREATE TEMPORARY TABLE/, + ); + await conn.query(`ALTER TABLE \`${table}\` ${alter}`); + } + await run(conn); + } finally { + await conn.end(); + } + } + + async function runBackfill(conn: mysql.Connection): Promise { + expect(BACKFILL).toHaveLength(8); + for (const stmt of BACKFILL) await conn.query(stmt); + } + + async function insertTemplate( + conn: mysql.Connection, + productId: bigint, + isActive: boolean, + deleted = false, + ): Promise { + const [result] = await conn.query( + 'INSERT INTO product_custom_template (product_id, base_image_url, is_active, deleted_at, updated_at) VALUES (?, ?, ?, ?, NOW(3))', + [ + productId, + 'https://i.example/base.png', + isActive, + deleted ? new Date() : null, + ], + ); + return result.insertId; + } + + async function insertToken( + conn: mysql.Connection, + row: { + templateId: number; + key?: string; + defaultText?: string; + maxLength?: number; + sortOrder?: number; + area?: [number | null, number | null, number | null, number | null]; + deleted?: boolean; + }, + ): Promise { + const [x, y, w, h] = row.area ?? [null, null, null, null]; + const [result] = await conn.query( + 'INSERT INTO product_custom_text_token (template_id, token_key, default_text, max_length, sort_order, pos_x, pos_y, width, height, deleted_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(3))', + [ + row.templateId, + row.key ?? `k${nextSeq()}`, + row.defaultText ?? '문구', + row.maxLength ?? 30, + row.sortOrder ?? 0, + x, + y, + w, + h, + row.deleted ? new Date() : null, + ], + ); + return result.insertId; + } + + async function tokens(conn: mysql.Connection): Promise { + const [rows] = await conn.query( + 'SELECT id, label, default_text, max_length, pos_x, pos_y, width, height FROM product_custom_text_token ORDER BY id', + ); + return rows; + } + + it('활성·미삭제 템플릿이 있는 상품만 슬롯형이 된다', async () => { + const [active, inactive, deleted, bare] = await Promise.all( + [0, 1, 2, 3].map(() => createProduct(prisma)), + ); + + await withLegacyTables(async (conn) => { + await insertTemplate(conn, active.id, true); + await insertTemplate(conn, inactive.id, false); + await insertTemplate(conn, deleted.id, true, true); + await runBackfill(conn); + }); + + const modes = await prisma.product.findMany({ + where: { id: { in: [active.id, inactive.id, deleted.id, bare.id] } }, + select: { id: true, custom_mode: true }, + }); + expect( + Object.fromEntries(modes.map((p) => [p.id.toString(), p.custom_mode])), + ).toEqual({ + [active.id.toString()]: 'SLOT', + [inactive.id.toString()]: 'NONE', + [deleted.id.toString()]: 'NONE', + [bare.id.toString()]: 'NONE', + }); + }); + + it('표시 이름은 키 앞 30자, 기본 문구는 50자에서 자르고, 최대 글자 수는 기본 문구 길이 이상·50 이하다', async () => { + const product = await createProduct(prisma); + + await withLegacyTables(async (conn) => { + const tpl = await insertTemplate(conn, product.id, true); + const area: [number, number, number, number] = [0, 0, 100, 100]; + const cases: Array<[string, string, number]> = [ + ['a'.repeat(40), '가'.repeat(60), 30], + ['short', 'abc', 2], + ['big', 'abc', 99], + ['emoji', '🎂🎂🎂', 1], + ['zero', 'abc', 0], + ]; + for (const [key, defaultText, maxLength] of cases) { + await insertToken(conn, { + templateId: tpl, + key, + defaultText, + maxLength, + area, + }); + } + + await runBackfill(conn); + + expect( + (await tokens(conn)).map((t) => [ + t.label, + t.default_text, + t.max_length, + ]), + ).toEqual([ + ['a'.repeat(30), '가'.repeat(50), 50], + ['short', 'abc', 3], + ['big', 'abc', 50], + ['emoji', '🎂🎂🎂', 3], + ['zero', 'abc', 3], + ]); + await conn.query(NOT_NULL_AFTER_BACKFILL); + }); + }); + + it('좌표가 하나라도 없는 자리는 판매자 앱 기본 배치(템플릿별 활성 순번)로, 있는 자리는 0~10000으로 자른다', async () => { + const [p1, p2] = await Promise.all([ + createProduct(prisma), + createProduct(prisma), + ]); + + await withLegacyTables(async (conn) => { + const tpl = await insertTemplate(conn, p1.id, true); + const other = await insertTemplate(conn, p2.id, true); + // 삭제 자리는 활성 자리 뒤 순번을 받는다(sort_order가 앞서도) + const deleted = await insertToken(conn, { + templateId: tpl, + sortOrder: 0, + deleted: true, + }); + const first = await insertToken(conn, { templateId: tpl, sortOrder: 0 }); + const clamped = await insertToken(conn, { + templateId: tpl, + sortOrder: 1, + area: [-5, 20000, 300, 12000], + }); + const partial = await insertToken(conn, { + templateId: tpl, + sortOrder: 2, + area: [10, 20, null, 40], + }); + const fourth = await insertToken(conn, { templateId: tpl, sortOrder: 5 }); + const otherFirst = await insertToken(conn, { + templateId: other, + sortOrder: 9, + }); + + await runBackfill(conn); + + const byId = new Map( + (await tokens(conn)).map((t) => [ + Number(t.id), + [t.pos_x, t.pos_y, t.width, t.height], + ]), + ); + expect(byId.get(first)).toEqual([1000, 1000, 8000, 1500]); + expect(byId.get(clamped)).toEqual([0, 10000, 300, 10000]); + expect(byId.get(partial)).toEqual([1000, 5000, 8000, 1500]); + expect(byId.get(fourth)).toEqual([1000, 7000, 8000, 1500]); + expect(byId.get(deleted)).toEqual([1000, 8500, 8000, 1500]); + expect(byId.get(otherFirst)).toEqual([1000, 1000, 8000, 1500]); + await conn.query(NOT_NULL_AFTER_BACKFILL); + }); + }); + + it('백필 없이는 NOT NULL 전환이 실패한다(검증 반증)', async () => { + const product = await createProduct(prisma); + await withLegacyTables(async (conn) => { + const tpl = await insertTemplate(conn, product.id, true); + await insertToken(conn, { templateId: tpl }); + expect(NOT_NULL_AFTER_BACKFILL).toMatch( + /^ALTER TABLE `product_custom_text_token` MODIFY `label`/, + ); + await expect(conn.query(NOT_NULL_AFTER_BACKFILL)).rejects.toThrow(); + }); + }); +}); diff --git a/src/features/product/repositories/product-admin.repository.ts b/src/features/product/repositories/product-admin.repository.ts index 21834e84..264ac483 100644 --- a/src/features/product/repositories/product-admin.repository.ts +++ b/src/features/product/repositories/product-admin.repository.ts @@ -61,9 +61,16 @@ export type AdminProductDetailRow = Prisma.ProductGetPayload<{ include: typeof productDetailInclude; }>; +// 목록 썸네일은 대표 이미지(삭제 제외 첫 장). 상세 include와 같은 모양이라 매퍼 하나를 같이 쓴다 const productInclude = { store: { select: { store_name: true, is_active: true } }, -} as const; + images: { + where: activeWhere, + select: { image_url: true, deleted_at: true }, + orderBy: [{ sort_order: 'asc' }, { id: 'asc' }], + take: 1, + }, +} satisfies Prisma.ProductInclude; // orderBy 배열은 as const로 readonly가 되면 Prisma 타입과 어긋나 satisfies로 고정한다 const productDetailInclude = { diff --git a/src/features/product/repositories/product.repository.spec.ts b/src/features/product/repositories/product.repository.spec.ts index f93ab44c..5d2645c6 100644 --- a/src/features/product/repositories/product.repository.spec.ts +++ b/src/features/product/repositories/product.repository.spec.ts @@ -5,7 +5,12 @@ import { AuditActionType, AuditTargetType } from '@/generated/prisma/client'; import type { PrismaClient } from '@/generated/prisma/client'; import { disconnectTestPrismaClient } from '@/test/db/prisma-test-client'; import { closeTruncateConnection, truncateAll } from '@/test/db/truncate'; -import { createProduct, createStore } from '@/test/factories'; +import { + createCustomTemplate, + createCustomTextToken, + createProduct, + createStore, +} from '@/test/factories'; import { createTestingModuleWithRealDb } from '@/test/modules/testing-module.builder'; /** repository가 조작과 같은 트랜잭션에 남기는 감사 항목 — 내용 자체는 서비스 spec이 본다. */ @@ -68,12 +73,7 @@ describe('ProductRepository (real DB)', () => { } async function createTemplate(productId: bigint) { - return prisma.productCustomTemplate.create({ - data: { - product_id: productId, - base_image_url: 'https://i.example/base.png', - }, - }); + return createCustomTemplate(prisma, { product_id: productId }); } describe('listProductsByStore', () => { @@ -218,9 +218,7 @@ describe('ProductRepository (real DB)', () => { const group = await createOptionGroup(product.id); await createOptionItem(group.id); const tpl = await createTemplate(product.id); - await prisma.productCustomTextToken.create({ - data: { template_id: tpl.id, token_key: 'K', default_text: 'V' }, - }); + await createCustomTextToken(prisma, { template_id: tpl.id }); const rows = await repo.listProductsByStore({ storeId: store.id, @@ -728,115 +726,192 @@ describe('ProductRepository (real DB)', () => { }); describe('Custom template / text token', () => { - it('upsertProductCustomTemplate: 동일 product_id 재호출 시 같은 row 갱신', async () => { - const store = await createStore(prisma); - const product = await createProduct(prisma, { store_id: store.id }); + it('upsertProductCustomTemplate: 같은 상품이면 같은 행을 갱신하고, 자유 편집을 생략하면 새 템플릿은 꺼짐·기존은 유지다', async () => { + const product = await createProduct(prisma); const first = await repo.upsertProductCustomTemplate( + { productId: product.id, baseImageUrl: 'https://i.example/a.png' }, + () => AUDIT_ENTRY, + ); + expect(first.free_edit_enabled).toBe(false); + const enabled = await repo.upsertProductCustomTemplate( { productId: product.id, baseImageUrl: 'https://i.example/a.png', - isActive: true, + freeEditEnabled: true, }, () => AUDIT_ENTRY, ); - const second = await repo.upsertProductCustomTemplate( + const kept = await repo.upsertProductCustomTemplate( + { productId: product.id, baseImageUrl: 'https://i.example/b.png' }, + () => AUDIT_ENTRY, + ); + + expect([enabled.id, kept.id]).toEqual([first.id, first.id]); + expect(kept.base_image_url).toBe('https://i.example/b.png'); + expect(kept.free_edit_enabled).toBe(true); + }); + + it('템플릿 갱신·슬롯 등록·수정·순서 변경·삭제마다 revision이 1씩 오른다', async () => { + const product = await createProduct(prisma); + const revision = async () => + ( + await prisma.productCustomTemplate.findUniqueOrThrow({ + where: { product_id: product.id }, + }) + ).revision; + const tpl = await repo.upsertProductCustomTemplate( + { productId: product.id, baseImageUrl: 'https://i.example/a.png' }, + () => AUDIT_ENTRY, + ); + const seen = [await revision()]; + const slot = { + templateId: tpl.id, + label: '이름', + defaultText: '가', + maxLength: 20, + sortOrder: 0, + isRequired: true, + posX: 0, + posY: 0, + width: 100, + height: 100, + }; + + await repo.upsertProductCustomTemplate( { productId: product.id, - baseImageUrl: 'https://i.example/b.png', - isActive: false, + baseImageUrl: 'https://i.example/a.png', + freeEditEnabled: true, }, () => AUDIT_ENTRY, ); - expect(second.id).toBe(first.id); - expect(second.base_image_url).toBe('https://i.example/b.png'); - expect(second.is_active).toBe(false); + seen.push(await revision()); + const a = await repo.upsertCustomTextToken( + { ...slot, tokenKey: 'a' }, + () => AUDIT_ENTRY, + ); + seen.push(await revision()); + const b = await repo.upsertCustomTextToken( + { ...slot, tokenKey: 'b' }, + () => AUDIT_ENTRY, + ); + seen.push(await revision()); + await repo.upsertCustomTextToken( + { ...slot, tokenId: a.id, tokenKey: 'a', defaultText: '나' }, + () => AUDIT_ENTRY, + ); + seen.push(await revision()); + await repo.reorderCustomTextTokens( + { templateId: tpl.id, tokenIds: [b.id, a.id] }, + () => AUDIT_ENTRY, + ); + seen.push(await revision()); + await repo.softDeleteCustomTextToken(a.id, () => AUDIT_ENTRY); + seen.push(await revision()); + + expect(seen).toEqual([1, 2, 3, 4, 5, 6, 7]); }); - it('findCustomTemplateById는 soft-delete된 텍스트 토큰을 제외한다', async () => { - const store = await createStore(prisma); - const product = await createProduct(prisma, { store_id: store.id }); + it('슬롯 변경이 실패하면 revision도 오르지 않는다(같은 tx)', async () => { + const product = await createProduct(prisma); const tpl = await createTemplate(product.id); - const live = await prisma.productCustomTextToken.create({ - data: { template_id: tpl.id, token_key: 'live', default_text: '문구' }, - }); - await prisma.productCustomTextToken.create({ - data: { - template_id: tpl.id, - token_key: 'deleted', - default_text: '삭제', - deleted_at: new Date(), - }, + await createCustomTextToken(prisma, { + template_id: tpl.id, + token_key: 'taken', }); - const found = await repo.findCustomTemplateById(tpl.id); - expect(found?.text_tokens.map((t) => t.id)).toEqual([live.id]); + await expect( + repo.upsertCustomTextToken( + { + templateId: tpl.id, + tokenKey: 'taken', + label: '이름', + defaultText: '가', + maxLength: 20, + sortOrder: 0, + isRequired: true, + posX: 0, + posY: 0, + width: 100, + height: 100, + }, + () => AUDIT_ENTRY, + ), + ).rejects.toThrowDomain('CUSTOM_TEXT_TOKEN_KEY_TAKEN'); + + const after = await prisma.productCustomTemplate.findUniqueOrThrow({ + where: { id: tpl.id }, + }); + expect(after.revision).toBe(1); }); - it('findCustomTemplateById + setCustomTemplateActive', async () => { + it('findCustomTemplateById는 soft-delete된 텍스트 토큰을 제외하고 소속 매장을 담는다', async () => { const store = await createStore(prisma); const product = await createProduct(prisma, { store_id: store.id }); const tpl = await createTemplate(product.id); + const live = await createCustomTextToken(prisma, { template_id: tpl.id }); + await createCustomTextToken(prisma, { + template_id: tpl.id, + deleted_at: new Date(), + }); const found = await repo.findCustomTemplateById(tpl.id); expect(found?.product.store_id).toBe(store.id); - - const toggled = await repo.setCustomTemplateActive( - tpl.id, - false, - () => AUDIT_ENTRY, - ); - expect(toggled.is_active).toBe(false); + expect(found?.text_tokens.map((t) => t.id)).toEqual([live.id]); }); - it('upsertCustomTextToken: tokenId 없으면 create, 있으면 update', async () => { - const store = await createStore(prisma); - const product = await createProduct(prisma, { store_id: store.id }); + it('upsertCustomTextToken: 등록은 글자색·정렬 기본값을 채우고, 수정은 생략한 글자색·정렬을 그대로 둔다', async () => { + const product = await createProduct(prisma); const tpl = await createTemplate(product.id); - - const created = await repo.upsertCustomTextToken( + const base = { + templateId: tpl.id, + tokenKey: 'name', + label: '이름', + defaultText: '가', + maxLength: 20, + sortOrder: 0, + isRequired: true, + posX: 10, + posY: 20, + width: 100, + height: 50, + }; + + const created = await repo.upsertCustomTextToken(base, () => AUDIT_ENTRY); + expect([created.text_color, created.text_align]).toEqual([ + '#000000', + 'CENTER', + ]); + const styled = await repo.upsertCustomTextToken( { - templateId: tpl.id, - tokenKey: 'NAME', - defaultText: '가', - maxLength: 30, - sortOrder: 0, - isRequired: true, - posX: 10, - posY: 20, - width: 100, - height: 50, + ...base, + tokenId: created.id, + textColor: '#FF0000', + textAlign: 'LEFT', }, () => AUDIT_ENTRY, ); - expect(created.token_key).toBe('NAME'); - - const updated = await repo.upsertCustomTextToken( - { - tokenId: created.id, - templateId: tpl.id, - tokenKey: 'NAME2', - defaultText: '나', - maxLength: 40, - sortOrder: 0, - isRequired: false, - posX: null, - posY: null, - width: null, - height: null, - }, + const kept = await repo.upsertCustomTextToken( + { ...base, tokenId: created.id, tokenKey: 'name2', maxLength: 40 }, () => AUDIT_ENTRY, ); - expect(updated.id).toBe(created.id); - expect(updated.token_key).toBe('NAME2'); + + expect([styled.id, kept.id]).toEqual([created.id, created.id]); + expect(kept).toMatchObject({ + token_key: 'name2', + max_length: 40, + text_color: '#FF0000', + text_align: 'LEFT', + }); }); it('findCustomTextTokenById (template 경유 store_id 확인용 include)', async () => { const store = await createStore(prisma); const product = await createProduct(prisma, { store_id: store.id }); const tpl = await createTemplate(product.id); - const token = await prisma.productCustomTextToken.create({ - data: { template_id: tpl.id, token_key: 'K', default_text: 'V' }, + const token = await createCustomTextToken(prisma, { + template_id: tpl.id, }); const found = await repo.findCustomTextTokenById(token.id); @@ -847,21 +922,13 @@ describe('ProductRepository (real DB)', () => { const store = await createStore(prisma); const product = await createProduct(prisma, { store_id: store.id }); const tpl = await createTemplate(product.id); - const t1 = await prisma.productCustomTextToken.create({ - data: { - template_id: tpl.id, - token_key: 'A', - default_text: 'a', - sort_order: 0, - }, + const t1 = await createCustomTextToken(prisma, { + template_id: tpl.id, + sort_order: 0, }); - const t2 = await prisma.productCustomTextToken.create({ - data: { - template_id: tpl.id, - token_key: 'B', - default_text: 'b', - sort_order: 1, - }, + const t2 = await createCustomTextToken(prisma, { + template_id: tpl.id, + sort_order: 1, }); const listed = await repo.listCustomTextTokens(tpl.id); diff --git a/src/features/product/repositories/product.repository.ts b/src/features/product/repositories/product.repository.ts index 08600b2f..a39654d6 100644 --- a/src/features/product/repositories/product.repository.ts +++ b/src/features/product/repositories/product.repository.ts @@ -7,10 +7,13 @@ import { type AuditEntry, type IAuditLogRepository, } from '@/features/audit-log'; +import { DEFAULT_TEXT_COLOR } from '@/features/product/constants/product-seller.constants'; import { bannerLinkTargetVisibleWhere } from '@/features/product/repositories/banner-link-target.helper'; import { type BannerLinkType, type CategoryType, + type CustomMode, + CustomTextAlign, Prisma, type Product, type ProductCustomTemplate, @@ -109,6 +112,22 @@ export interface HomeBannerRow { link_category_id: bigint | null; } +export interface ProductDetailSlotRow { + id: bigint; + token_key: string; + label: string; + default_text: string; + max_length: number; + is_required: boolean; + pos_x: number; + pos_y: number; + width: number; + height: number; + text_color: string; + text_align: CustomTextAlign; + sort_order: number; +} + export interface ProductDetailRow { id: bigint; store_id: bigint; @@ -119,6 +138,15 @@ export interface ProductDetailRow { sale_price: number | null; currency: string; preparation_time_minutes: number; + custom_mode: CustomMode; + /** 삭제된 템플릿도 올 수 있어 deleted_at으로 거른다. 문구 자리는 삭제 제외. */ + custom_template: { + base_image_url: string; + free_edit_enabled: boolean; + revision: number; + deleted_at: Date | null; + text_tokens: ProductDetailSlotRow[]; + } | null; /** 주문 생성 시 매장명·지역 표기 스냅샷용 */ store: { store_name: string; @@ -134,8 +162,6 @@ export interface ProductDetailRow { is_required: boolean; min_select: number; max_select: number; - option_requires_description: boolean; - option_requires_image: boolean; sort_order: number; option_items: { id: bigint; @@ -917,11 +943,12 @@ export class ProductRepository { }, audit); } + /** 갱신이면 revision을 1 올린다. freeEditEnabled를 생략하면 새 템플릿은 꺼짐, 기존 템플릿은 그대로다. */ async upsertProductCustomTemplate( args: { productId: bigint; baseImageUrl: string; - isActive: boolean; + freeEditEnabled?: boolean; }, audit: (row: ProductCustomTemplate) => AuditEntry, ) { @@ -934,11 +961,12 @@ export class ProductRepository { create: { product_id: args.productId, base_image_url: args.baseImageUrl, - is_active: args.isActive, + free_edit_enabled: args.freeEditEnabled ?? false, }, update: { base_image_url: args.baseImageUrl, - is_active: args.isActive, + free_edit_enabled: args.freeEditEnabled, + revision: { increment: 1 }, }, include: { text_tokens: { @@ -951,6 +979,17 @@ export class ProductRepository { ); } + /** 슬롯이 바뀐 tx 안에서 부른다 — 구매자가 꾸민 기준 revision과 주문 시점 설정을 대조하는 근거다. */ + private async bumpTemplateRevision( + tx: Prisma.TransactionClient, + templateId: bigint, + ): Promise { + await tx.productCustomTemplate.update({ + where: { id: templateId }, + data: { revision: { increment: 1 } }, + }); + } + async findCustomTemplateById(id: bigint) { return this.prisma.productCustomTemplate.findFirst({ where: { id }, @@ -969,47 +1008,29 @@ export class ProductRepository { }); } - async setCustomTemplateActive( - templateId: bigint, - isActive: boolean, - audit: (row: ProductCustomTemplate) => AuditEntry, - ) { - return this.writeWithAudit( - (tx) => - tx.productCustomTemplate.update({ - where: { id: templateId }, - data: { - is_active: isActive, - }, - include: { - text_tokens: { - where: activeWhere, - orderBy: { sort_order: 'asc' }, - }, - }, - }), - audit, - ); - } - + /** label·textColor·textAlign을 생략하면 수정은 기존 값을 두고, 등록(삭제 슬롯 복구 포함)은 기본값으로 채운다. */ async upsertCustomTextToken( args: { tokenId?: bigint; templateId: bigint; tokenKey: string; + label: string; defaultText: string; maxLength: number; sortOrder: number; isRequired: boolean; - posX: number | null; - posY: number | null; - width: number | null; - height: number | null; + posX: number; + posY: number; + width: number; + height: number; + textColor?: string; + textAlign?: CustomTextAlign; }, audit: (row: ProductCustomTextToken) => AuditEntry, ) { const data = { token_key: args.tokenKey, + label: args.label, default_text: args.defaultText, max_length: args.maxLength, sort_order: args.sortOrder, @@ -1018,33 +1039,44 @@ export class ProductRepository { pos_y: args.posY, width: args.width, height: args.height, + text_color: args.textColor, + text_align: args.textAlign, + }; + const createData = { + ...data, + text_color: args.textColor ?? DEFAULT_TEXT_COLOR, + text_align: args.textAlign ?? CustomTextAlign.CENTER, }; const tokenId = args.tokenId; return this.writeWithAudit(async (tx) => { + let row: ProductCustomTextToken; if (tokenId) { - return tx.productCustomTextToken + row = await tx.productCustomTextToken .update({ where: { id: tokenId }, data }) .catch(rethrowTokenKeyTaken); + } else { + // 같은 템플릿의 슬롯 생성을 직렬화한다 — 잠금 없이는 같은 삭제 슬롯을 동시에 복구한 둘이 모두 성공한다 + await tx.$queryRaw`SELECT id FROM product_custom_template WHERE id = ${args.templateId} FOR UPDATE`; + // unique가 삭제 행도 세므로 같은 키의 삭제 슬롯은 새로 만들지 않고 복구한다 + const deleted = await tx.productCustomTextToken.findFirst({ + where: { + template_id: args.templateId, + token_key: args.tokenKey, + deleted_at: { not: null }, + }, + select: { id: true }, + }); + row = deleted + ? await tx.productCustomTextToken.update({ + where: { id: deleted.id }, + data: { ...createData, deleted_at: null }, + }) + : await tx.productCustomTextToken + .create({ data: { template_id: args.templateId, ...createData } }) + .catch(rethrowTokenKeyTaken); } - // 같은 템플릿의 슬롯 생성을 직렬화한다 — 잠금 없이는 같은 삭제 슬롯을 동시에 복구한 둘이 모두 성공한다 - await tx.$queryRaw`SELECT id FROM product_custom_template WHERE id = ${args.templateId} FOR UPDATE`; - // unique가 삭제 행도 세므로 같은 키의 삭제 슬롯은 새로 만들지 않고 복구한다 - const deleted = await tx.productCustomTextToken.findFirst({ - where: { - template_id: args.templateId, - token_key: args.tokenKey, - deleted_at: { not: null }, - }, - select: { id: true }, - }); - return deleted - ? tx.productCustomTextToken.update({ - where: { id: deleted.id }, - data: { ...data, deleted_at: null }, - }) - : tx.productCustomTextToken - .create({ data: { template_id: args.templateId, ...data } }) - .catch(rethrowTokenKeyTaken); + await this.bumpTemplateRevision(tx, args.templateId); + return row; }, audit); } @@ -1070,16 +1102,16 @@ export class ProductRepository { id: bigint, audit: (row: { id: bigint }) => AuditEntry, ): Promise { - await this.writeWithAudit( - (tx) => - tx.productCustomTextToken.update({ - where: { id }, - data: { - deleted_at: new Date(), - }, - }), - audit, - ); + await this.writeWithAudit(async (tx) => { + const row = await tx.productCustomTextToken.update({ + where: { id }, + data: { + deleted_at: new Date(), + }, + }); + await this.bumpTemplateRevision(tx, row.template_id); + return row; + }, audit); } async listCustomTextTokens(templateId: bigint) { @@ -1107,6 +1139,7 @@ export class ProductRepository { }), ), ); + await this.bumpTemplateRevision(tx, args.templateId); return tx.productCustomTextToken.findMany({ where: { @@ -1261,6 +1294,34 @@ export class ProductRepository { sale_price: true, currency: true, preparation_time_minutes: true, + custom_mode: true, + custom_template: { + select: { + base_image_url: true, + free_edit_enabled: true, + revision: true, + deleted_at: true, + text_tokens: { + where: activeWhere, + orderBy: [{ sort_order: 'asc' }, { id: 'asc' }], + select: { + id: true, + token_key: true, + label: true, + default_text: true, + max_length: true, + is_required: true, + pos_x: true, + pos_y: true, + width: true, + height: true, + text_color: true, + text_align: true, + sort_order: true, + }, + }, + }, + }, store: { select: { store_name: true, @@ -1285,8 +1346,6 @@ export class ProductRepository { is_required: true, min_select: true, max_select: true, - option_requires_description: true, - option_requires_image: true, sort_order: true, option_items: { where: visibleWhere, diff --git a/src/features/product/resolvers/product-seller-mutation.resolver.ts b/src/features/product/resolvers/product-seller-mutation.resolver.ts index faba6f41..7e28dc5b 100644 --- a/src/features/product/resolvers/product-seller-mutation.resolver.ts +++ b/src/features/product/resolvers/product-seller-mutation.resolver.ts @@ -12,7 +12,6 @@ import { SellerReorderProductCustomTextTokensInput } from '@/features/product/dt import { SellerReorderProductImagesInput } from '@/features/product/dto/inputs/seller-reorder-product-images.input'; import { SellerSetProductActiveInput } from '@/features/product/dto/inputs/seller-set-product-active.input'; import { SellerSetProductCategoriesInput } from '@/features/product/dto/inputs/seller-set-product-categories.input'; -import { SellerSetProductCustomTemplateActiveInput } from '@/features/product/dto/inputs/seller-set-product-custom-template-active.input'; import { SellerSetProductTagsByNameInput } from '@/features/product/dto/inputs/seller-set-product-tags-by-name.input'; import { SellerSetProductTagsInput } from '@/features/product/dto/inputs/seller-set-product-tags.input'; import { SellerUpdateOptionGroupInput } from '@/features/product/dto/inputs/seller-update-option-group.input'; @@ -33,6 +32,7 @@ import type { SellerProductImageOutput, SellerProductOutput, } from '@/features/product/types/product-seller-output.type'; +import type { CustomMode } from '@/generated/prisma/client'; import { CurrentUser, JwtAuthGuard, @@ -240,15 +240,17 @@ export class SellerProductMutationResolver { ); } - @Mutation('sellerSetProductCustomTemplateActive') - sellerSetProductCustomTemplateActive( + @Mutation('sellerSetProductCustomMode') + sellerSetProductCustomMode( @CurrentUser() user: JwtUser, - @Args('input') input: SellerSetProductCustomTemplateActiveInput, - ): Promise { + @Args('productId') productId: string, + @Args('customMode') customMode: CustomMode, + ): Promise { const accountId = parseAccountId(user); - return this.templateService.sellerSetProductCustomTemplateActive( + return this.templateService.sellerSetProductCustomMode( accountId, - input, + parseId(productId), + customMode, ); } diff --git a/src/features/product/resolvers/product-seller.resolver.spec.ts b/src/features/product/resolvers/product-seller.resolver.spec.ts index 6e419b09..7c4e5b4e 100644 --- a/src/features/product/resolvers/product-seller.resolver.spec.ts +++ b/src/features/product/resolvers/product-seller.resolver.spec.ts @@ -10,7 +10,6 @@ import type { SellerReorderProductCustomTextTokensInput } from '@/features/produ import type { SellerReorderProductImagesInput } from '@/features/product/dto/inputs/seller-reorder-product-images.input'; import type { SellerSetProductActiveInput } from '@/features/product/dto/inputs/seller-set-product-active.input'; import type { SellerSetProductCategoriesInput } from '@/features/product/dto/inputs/seller-set-product-categories.input'; -import type { SellerSetProductCustomTemplateActiveInput } from '@/features/product/dto/inputs/seller-set-product-custom-template-active.input'; import type { SellerSetProductTagsInput } from '@/features/product/dto/inputs/seller-set-product-tags.input'; import type { SellerUpdateOptionGroupInput } from '@/features/product/dto/inputs/seller-update-option-group.input'; import type { SellerUpdateOptionItemInput } from '@/features/product/dto/inputs/seller-update-option-item.input'; @@ -379,28 +378,18 @@ describe('Seller Product Resolvers (real DB)', () => { BigInt(auth.accountId), 'tpl.png', ), - isActive: true, }; const template = await mutationResolver.sellerUpsertProductCustomTemplate( auth, upsertTemplateInput, ); - const setTemplateActiveInput: SellerSetProductCustomTemplateActiveInput = - { - templateId: template.id, - isActive: false, - }; - const templateActive = - await mutationResolver.sellerSetProductCustomTemplateActive( - auth, - setTemplateActiveInput, - ); - expect(templateActive.isActive).toBe(false); + const area = { posX: 0, posY: 0, width: 5000, height: 1000 }; const upsertToken1: SellerUpsertProductCustomTextTokenInput = { templateId: template.id, tokenKey: 'name', defaultText: '기본', + ...area, }; const token1 = await mutationResolver.sellerUpsertProductCustomTextToken( auth, @@ -410,12 +399,20 @@ describe('Seller Product Resolvers (real DB)', () => { templateId: template.id, tokenKey: 'age', defaultText: '10', + ...area, }; const token2 = await mutationResolver.sellerUpsertProductCustomTextToken( auth, upsertToken2, ); + const slotProduct = await mutationResolver.sellerSetProductCustomMode( + auth, + productId, + 'SLOT', + ); + expect(slotProduct.customMode).toBe('SLOT'); + const reorderTokensInput: SellerReorderProductCustomTextTokensInput = { templateId: template.id, tokenIds: [token2.id, token1.id], diff --git a/src/features/product/services/product-admin-mappers.helper.ts b/src/features/product/services/product-admin-mappers.helper.ts index 0dda5bd4..f300c47b 100644 --- a/src/features/product/services/product-admin-mappers.helper.ts +++ b/src/features/product/services/product-admin-mappers.helper.ts @@ -21,7 +21,10 @@ export function toAdminProductOutput(row: AdminProductRow): AdminProductOutput { regularPrice: row.regular_price, salePrice: row.sale_price, currency: row.currency, - baseDesignImageUrl: row.base_design_image_url, + customMode: row.custom_mode, + // 상세 include는 삭제 이미지도 담아 첫 미삭제 장을 고른다 + thumbnailUrl: + row.images.find((image) => image.deleted_at === null)?.image_url ?? null, isActive: row.is_active, createdAt: row.created_at, updatedAt: row.updated_at, diff --git a/src/features/product/services/product-admin.service.spec.ts b/src/features/product/services/product-admin.service.spec.ts index c85dc0b9..0c5e98ab 100644 --- a/src/features/product/services/product-admin.service.spec.ts +++ b/src/features/product/services/product-admin.service.spec.ts @@ -9,6 +9,8 @@ import { closeTruncateConnection, truncateAll } from '@/test/db/truncate'; import { createAccount, createCategory, + createCustomTemplate, + createCustomTextToken, createOrderItem, createProduct, createReview, @@ -109,6 +111,36 @@ describe('AdminProductService (real DB)', () => { ).toEqual({ [a.id.toString()]: true, [b.id.toString()]: false }); }); + it('썸네일은 삭제를 뺀 첫 이미지(sort_order → id 순)이고 이미지가 없으면 null이다', async () => { + const store = await createStore(prisma); + const bare = await createProduct(prisma, { store_id: store.id }); + const product = await createProduct(prisma, { store_id: store.id }); + for (const [url, sortOrder, deleted] of [ + ['https://i/deleted.png', 0, new Date()], + ['https://i/second.png', 1, null], + ['https://i/first.png', 1, null], + ['https://i/later.png', 2, null], + ] as const) { + await prisma.productImage.create({ + data: { + product_id: product.id, + image_url: url, + sort_order: sortOrder, + deleted_at: deleted, + }, + }); + } + + const { items } = await service.adminProducts(await admin()); + + expect( + Object.fromEntries(items.map((p) => [p.id, p.thumbnailUrl])), + ).toEqual({ + [bare.id.toString()]: null, + [product.id.toString()]: 'https://i/second.png', + }); + }); + it('limit+1 조회로 hasMore·nextCursor를 판정하고 삭제 상품은 제외한다', async () => { const store = await createStore(prisma); const ids = [ @@ -168,6 +200,7 @@ describe('AdminProductService (real DB)', () => { const result = await service.adminProduct(await admin(), product.id); expect(result.product.id).toBe(product.id.toString()); + expect(result.product.thumbnailUrl).toBe('https://i/1.png'); expect(result.storeIsActive).toBe(false); expect(result.imageUrls).toEqual(['https://i/1.png', 'https://i/2.png']); expect(result.reviewCount).toBe(1); @@ -257,7 +290,7 @@ describe('AdminProductService (real DB)', () => { expect(result.tags.map((t) => t.name)).toEqual(['달콤', '촉촉']); }); - it('옵션 그룹·선택지는 sortOrder 순으로 숨김을 담고 삭제는 빼며 음수 가격 증감과 커스텀 입력 플래그를 그대로 준다', async () => { + it('옵션 그룹·선택지는 sortOrder 순으로 숨김을 담고 삭제는 빼며 음수 가격 증감을 그대로 준다', async () => { const product = await createProduct(prisma); const later = await prisma.productOptionGroup.create({ data: { product_id: product.id, name: '토핑', sort_order: 2 }, @@ -271,8 +304,6 @@ describe('AdminProductService (real DB)', () => { min_select: 0, max_select: 3, is_active: false, - option_requires_description: true, - option_requires_image: true, }, }); await prisma.productOptionGroup.create({ @@ -311,8 +342,6 @@ describe('AdminProductService (real DB)', () => { minSelect: 0, maxSelect: 3, isActive: false, - optionRequiresDescription: true, - optionRequiresImage: true, optionItems: [], }); expect( @@ -325,75 +354,84 @@ describe('AdminProductService (real DB)', () => { ]); }); - it('커스텀 템플릿이 없으면 null이고, 있으면 삭제된 슬롯을 뺀 슬롯을 sortOrder 순으로 준다', async () => { + it('커스텀 템플릿이 없으면 null이고, 있으면 자유 편집과 삭제된 슬롯을 뺀 슬롯(스타일 포함)을 sortOrder 순으로 준다', async () => { const bare = await createProduct(prisma); const product = await createProduct(prisma); - const template = await prisma.productCustomTemplate.create({ - data: { - product_id: product.id, - base_image_url: 'https://i/tpl.png', - is_active: false, - }, + await prisma.product.update({ + where: { id: product.id }, + data: { custom_mode: 'SLOT' }, }); - await prisma.productCustomTextToken.createMany({ - data: [ - { - template_id: template.id, - token_key: 'NAME', - default_text: '이름', - max_length: 10, - sort_order: 2, - is_required: false, - }, - { - template_id: template.id, - token_key: 'MSG', - default_text: '축하해', - max_length: 20, - sort_order: 1, - }, - { - template_id: template.id, - token_key: 'GONE', - default_text: '삭제', - sort_order: 0, - deleted_at: new Date(), - }, - ], + const template = await createCustomTemplate(prisma, { + product_id: product.id, + base_image_url: 'https://i/tpl.png', + free_edit_enabled: true, + }); + await createCustomTextToken(prisma, { + template_id: template.id, + token_key: 'name', + label: '받는 사람', + default_text: '이름', + max_length: 10, + sort_order: 2, + is_required: false, + text_color: '#FF0000', + text_align: 'LEFT', + }); + await createCustomTextToken(prisma, { + template_id: template.id, + token_key: 'msg', + label: '문구', + default_text: '축하해', + max_length: 20, + sort_order: 1, + }); + await createCustomTextToken(prisma, { + template_id: template.id, + sort_order: 0, + deleted_at: new Date(), }); - expect( - (await service.adminProduct(await admin(), bare.id)).customTemplate, - ).toBeNull(); + const bareResult = await service.adminProduct(await admin(), bare.id); + expect(bareResult.customTemplate).toBeNull(); + expect(bareResult.product.customMode).toBe('NONE'); const result = await service.adminProduct(await admin(), product.id); + expect(result.product.customMode).toBe('SLOT'); expect(result.customTemplate).toMatchObject({ id: template.id.toString(), baseImageUrl: 'https://i/tpl.png', - isActive: false, + freeEditEnabled: true, }); expect( result.customTemplate?.textTokens.map( - ({ tokenKey, defaultText, maxLength, isRequired }) => [ + ({ + tokenKey, + label, + defaultText, + maxLength, + isRequired, + textColor, + textAlign, + }) => [ tokenKey, + label, defaultText, maxLength, isRequired, + textColor, + textAlign, ], ), ).toEqual([ - ['MSG', '축하해', 20, true], - ['NAME', '이름', 10, false], + ['msg', '문구', '축하해', 20, true, '#000000', 'CENTER'], + ['name', '받는 사람', '이름', 10, false, '#FF0000', 'LEFT'], ]); }); it('삭제된 커스텀 템플릿은 null로 준다', async () => { const product = await createProduct(prisma); - await prisma.productCustomTemplate.create({ - data: { - product_id: product.id, - base_image_url: 'https://i/tpl.png', - deleted_at: new Date(), - }, + await createCustomTemplate(prisma, { + product_id: product.id, + deleted_at: new Date(), }); const result = await service.adminProduct(await admin(), product.id); diff --git a/src/features/product/services/product-custom-readiness.helper.spec.ts b/src/features/product/services/product-custom-readiness.helper.spec.ts new file mode 100644 index 00000000..177266d0 --- /dev/null +++ b/src/features/product/services/product-custom-readiness.helper.spec.ts @@ -0,0 +1,58 @@ +import { + evaluateProductCustomIssues, + type ProductCustomReadinessSource, +} from '@/features/product/services/product-custom-readiness.helper'; +import { CustomMode } from '@/generated/prisma/client'; + +const template = ( + slots: number, + freeEdit: boolean, + deleted = false, +): ProductCustomReadinessSource['custom_template'] => ({ + deleted_at: deleted ? new Date() : null, + free_edit_enabled: freeEdit, + text_tokens: Array.from({ length: slots }, (_, i) => ({ id: i })), +}); + +describe('evaluateProductCustomIssues', () => { + it.each([ + ['NONE', '템플릿 없음', null, []], + ['NONE', '빈 템플릿', template(0, false), []], + ['SLOT', '템플릿 없음', null, ['SLOT_TEMPLATE_MISSING']], + [ + 'SLOT', + '삭제된 템플릿', + template(2, true, true), + ['SLOT_TEMPLATE_MISSING'], + ], + [ + 'SLOT', + '문구 자리 0·자유 편집 끔', + template(0, false), + ['SLOT_NOTHING_TO_EDIT'], + ], + ['SLOT', '문구 자리 0·자유 편집 켬', template(0, true), []], + ['SLOT', '문구 자리 1·자유 편집 끔', template(1, false), []], + ['THREE_D', '템플릿 없음', null, ['THREE_D_GROUP_MISSING']], + [ + 'THREE_D', + '문구 자리 있는 템플릿', + template(1, true), + ['THREE_D_GROUP_MISSING'], + ], + ] as const)('%s · %s → %j', (mode, _label, customTemplate, codes) => { + const issues = evaluateProductCustomIssues( + { custom_template: customTemplate }, + mode, + ); + expect(issues.map((i) => i.code)).toEqual(codes); + for (const issue of issues) { + expect(issue.message).toMatch(/[가-힣]/); + expect(issue.optionGroupId).toBeNull(); + } + }); + + it('표가 모든 커스텀 방식을 덮는다', () => { + expect(Object.values(CustomMode)).toEqual(['NONE', 'SLOT', 'THREE_D']); + }); +}); diff --git a/src/features/product/services/product-custom-readiness.helper.ts b/src/features/product/services/product-custom-readiness.helper.ts new file mode 100644 index 00000000..e0ce549a --- /dev/null +++ b/src/features/product/services/product-custom-readiness.helper.ts @@ -0,0 +1,53 @@ +import { CustomMode } from '@/generated/prisma/client'; + +export type ProductCustomIssueCode = + 'SLOT_TEMPLATE_MISSING' | 'SLOT_NOTHING_TO_EDIT' | 'THREE_D_GROUP_MISSING'; + +export interface ProductCustomIssue { + code: ProductCustomIssueCode; + message: string; + optionGroupId: string | null; +} + +/** 준비 상태 판정에 필요한 만큼만 받는다. text_tokens는 삭제 제외 목록이어야 한다. */ +export interface ProductCustomReadinessSource { + custom_template: { + deleted_at: Date | null; + free_edit_enabled: boolean; + text_tokens: readonly unknown[]; + } | null; +} + +const ISSUE_MESSAGES: Record = { + SLOT_TEMPLATE_MISSING: '바탕 이미지를 먼저 등록해 주세요.', + SLOT_NOTHING_TO_EDIT: '문구 자리를 추가하거나 자유 편집을 허용해 주세요.', + THREE_D_GROUP_MISSING: '모양·크기 옵션을 3D 항목과 연결해 주세요.', +}; + +const issue = (code: ProductCustomIssueCode): ProductCustomIssue => ({ + code, + message: ISSUE_MESSAGES[code], + optionGroupId: null, +}); + +/** 판매자 방식 변경·준비 상태 경고·주문 생성이 같은 판정을 쓴다. 빈 배열이면 그 방식으로 주문을 받을 수 있다. */ +export function evaluateProductCustomIssues( + row: ProductCustomReadinessSource, + mode: CustomMode, +): ProductCustomIssue[] { + switch (mode) { + case CustomMode.NONE: + return []; + case CustomMode.SLOT: { + const template = + row.custom_template?.deleted_at === null ? row.custom_template : null; + if (!template) return [issue('SLOT_TEMPLATE_MISSING')]; + return template.text_tokens.length === 0 && !template.free_edit_enabled + ? [issue('SLOT_NOTHING_TO_EDIT')] + : []; + } + case CustomMode.THREE_D: + // 옵션 항목을 3D 카탈로그에 연결하는 칸이 아직 없어 모양·크기 그룹을 만들 수 없다 + return [issue('THREE_D_GROUP_MISSING')]; + } +} diff --git a/src/features/product/services/product-detail-mappers.helper.ts b/src/features/product/services/product-detail-mappers.helper.ts index ca12a4ec..59df4ba6 100644 --- a/src/features/product/services/product-detail-mappers.helper.ts +++ b/src/features/product/services/product-detail-mappers.helper.ts @@ -1,6 +1,39 @@ import { calcDiscountRate } from '@/common/utils/discount-rate'; import type { ProductDetailRow } from '@/features/product/repositories/product.repository'; -import type { ProductDetail } from '@/features/product/types/product-detail-output.type'; +import type { + ProductDetail, + ProductDetailCustomTemplate, +} from '@/features/product/types/product-detail-output.type'; +import { CustomMode } from '@/generated/prisma/client'; + +/** 슬롯형 상품만 템플릿을 연다 — 3D·없음은 바탕 위 문구 편집이 없다. */ +function toCustomTemplate( + row: ProductDetailRow, +): ProductDetailCustomTemplate | null { + const template = row.custom_template; + if (row.custom_mode !== CustomMode.SLOT || template?.deleted_at !== null) { + return null; + } + return { + revision: template.revision, + baseImageUrl: template.base_image_url, + freeEditEnabled: template.free_edit_enabled, + slots: template.text_tokens.map((slot) => ({ + id: slot.id.toString(), + label: slot.label, + defaultText: slot.default_text, + maxLength: slot.max_length, + isRequired: slot.is_required, + posX: slot.pos_x, + posY: slot.pos_y, + width: slot.width, + height: slot.height, + textColor: slot.text_color, + textAlign: slot.text_align, + sortOrder: slot.sort_order, + })), + }; +} export function toProductDetail( row: ProductDetailRow, @@ -37,5 +70,7 @@ export function toProductDetail( sortOrder: item.sort_order, })), })), + customMode: row.custom_mode, + customTemplate: toCustomTemplate(row), }; } diff --git a/src/features/product/services/product-detail.service.spec.ts b/src/features/product/services/product-detail.service.spec.ts index 4b0bb09d..0082dcf8 100644 --- a/src/features/product/services/product-detail.service.spec.ts +++ b/src/features/product/services/product-detail.service.spec.ts @@ -9,6 +9,8 @@ import { disconnectTestPrismaClient } from '@/test/db/prisma-test-client'; import { closeTruncateConnection, truncateAll } from '@/test/db/truncate'; import { createAccount, + createCustomTemplate, + createCustomTextToken, createOrderItem, createProduct, createReview, @@ -169,6 +171,94 @@ describe('ProductDetailService (real DB)', () => { expect(flavor.items[1].priceDelta).toBe(2000); }); + it('슬롯형 상품은 꾸미기 설정(revision·바탕·자유 편집·삭제 제외 문구 자리 sortOrder 순)을 준다', async () => { + const product = await createProduct(prisma); + await prisma.product.update({ + where: { id: product.id }, + data: { custom_mode: 'SLOT' }, + }); + const template = await createCustomTemplate(prisma, { + product_id: product.id, + base_image_url: 'https://i.example/base.png', + free_edit_enabled: true, + revision: 3, + }); + const later = await createCustomTextToken(prisma, { + template_id: template.id, + label: '보내는 사람', + sort_order: 2, + }); + const first = await createCustomTextToken(prisma, { + template_id: template.id, + label: '받는 사람', + default_text: '엄마', + max_length: 10, + is_required: false, + pos_x: 0, + pos_y: 500, + width: 10000, + height: 2000, + text_color: '#FF0000', + text_align: 'LEFT', + sort_order: 1, + }); + await createCustomTextToken(prisma, { + template_id: template.id, + sort_order: 0, + deleted_at: new Date(), + }); + + const result = await service.productDetail(product.id.toString()); + + expect(result.customMode).toBe('SLOT'); + expect(result.customTemplate).toMatchObject({ + revision: 3, + baseImageUrl: 'https://i.example/base.png', + freeEditEnabled: true, + }); + expect(result.customTemplate?.slots).toEqual([ + { + id: first.id.toString(), + label: '받는 사람', + defaultText: '엄마', + maxLength: 10, + isRequired: false, + posX: 0, + posY: 500, + width: 10000, + height: 2000, + textColor: '#FF0000', + textAlign: 'LEFT', + sortOrder: 1, + }, + expect.objectContaining({ id: later.id.toString() }), + ]); + }); + + it.each([ + ['커스텀 없음', 'NONE', false], + ['3D', 'THREE_D', false], + ['템플릿이 삭제된 슬롯형', 'SLOT', true], + ] as const)( + '%s 상품은 템플릿이 있어도 customTemplate이 null이다', + async (_label, mode, deleted) => { + const product = await createProduct(prisma); + await prisma.product.update({ + where: { id: product.id }, + data: { custom_mode: mode }, + }); + await createCustomTemplate(prisma, { + product_id: product.id, + deleted_at: deleted ? new Date() : null, + }); + + const result = await service.productDetail(product.id.toString()); + + expect(result.customMode).toBe(mode); + expect(result.customTemplate).toBeNull(); + }, + ); + it('리뷰 수를 집계하고 soft-delete 리뷰는 제외한다', async () => { const product = await createProduct(prisma); const orderItem1 = await createOrderItem(prisma, { diff --git a/src/features/product/services/product-seller-custom-template.service.spec.ts b/src/features/product/services/product-seller-custom-template.service.spec.ts index 24d323eb..ab8e9551 100644 --- a/src/features/product/services/product-seller-custom-template.service.spec.ts +++ b/src/features/product/services/product-seller-custom-template.service.spec.ts @@ -7,7 +7,12 @@ import { StoreSellerRepository } from '@/features/store/repositories/store-selle import type { PrismaClient, Product } from '@/generated/prisma/client'; import { disconnectTestPrismaClient } from '@/test/db/prisma-test-client'; import { closeTruncateConnection, truncateAll } from '@/test/db/truncate'; -import { createProduct, setupSellerWithStore } from '@/test/factories'; +import { + createCustomTemplate, + createCustomTextToken, + createProduct, + setupSellerWithStore, +} from '@/test/factories'; import { createTestingModuleWithRealDb } from '@/test/modules/testing-module.builder'; import { FOREIGN_UPLOAD_URL, @@ -55,31 +60,158 @@ describe('SellerCustomTemplateService (real DB)', () => { return { accountId: account.id, storeId: store.id, product }; } - async function createTemplate(productId: bigint) { - return prisma.productCustomTemplate.create({ - data: { - product_id: productId, - base_image_url: 'https://i.example/base.png', - }, + async function createTemplate(productId: bigint, freeEditEnabled = false) { + return createCustomTemplate(prisma, { + product_id: productId, + free_edit_enabled: freeEditEnabled, }); } - /** 활성 슬롯 A + soft-delete된 슬롯 B. */ + /** 활성 슬롯 1개 + soft-delete된 슬롯 1개. */ async function createTokensWithDeleted(templateId: bigint) { - const live = await prisma.productCustomTextToken.create({ - data: { template_id: templateId, token_key: 'A', default_text: 'a' }, + const live = await createCustomTextToken(prisma, { + template_id: templateId, }); - await prisma.productCustomTextToken.create({ - data: { - template_id: templateId, - token_key: 'B', - default_text: 'b', - deleted_at: new Date(), - }, + await createCustomTextToken(prisma, { + template_id: templateId, + deleted_at: new Date(), }); return live; } + const AREA = { posX: 1000, posY: 1000, width: 8000, height: 1500 }; + const slot = (templateId: bigint, overrides: object = {}) => ({ + templateId: templateId.toString(), + tokenKey: 'name', + defaultText: '가', + ...AREA, + ...overrides, + }); + + describe('sellerSetProductCustomMode', () => { + it('다른 매장 상품이면 404', async () => { + const me = await setupSellerWithProduct(); + const other = await setupSellerWithProduct(); + await expect( + service.sellerSetProductCustomMode( + me.accountId, + other.product.id, + 'NONE', + ), + ).rejects.toThrowDomain('PRODUCT_NOT_FOUND'); + }); + + it.each([ + ['템플릿이 없는 슬롯형', 'SLOT', 'none'], + ['문구 자리도 자유 편집도 없는 슬롯형', 'SLOT', 'empty'], + ['3D 연결 그룹이 없는 3D', 'THREE_D', 'empty'], + ] as const)( + '%s으로는 바꿀 수 없고 방식·감사 기록이 그대로다', + async (_label, mode, template) => { + const { accountId, storeId, product } = await setupSellerWithProduct(); + if (template === 'empty') await createTemplate(product.id); + + await expect( + service.sellerSetProductCustomMode(accountId, product.id, mode), + ).rejects.toThrowDomain('CUSTOM_PRODUCT_NOT_READY'); + + const after = await prisma.product.findUniqueOrThrow({ + where: { id: product.id }, + }); + expect(after.custom_mode).toBe('NONE'); + expect( + await prisma.auditLog.count({ where: { store_id: storeId } }), + ).toBe(0); + }, + ); + + it.each([ + ['문구 자리가 있으면', false, 1], + ['자유 편집을 허용했으면', true, 0], + ])( + '%s 슬롯형으로 바꾸고 이전·이후 방식을 감사에 남긴다', + async (_label, freeEdit, slots) => { + const { accountId, storeId, product } = await setupSellerWithProduct(); + const tpl = await createTemplate(product.id, freeEdit); + for (let i = 0; i < slots; i++) { + await createCustomTextToken(prisma, { template_id: tpl.id }); + } + + const result = await service.sellerSetProductCustomMode( + accountId, + product.id, + 'SLOT', + ); + + expect(result.customMode).toBe('SLOT'); + expect(result.customReadiness.find((r) => r.mode === 'SLOT')).toEqual({ + mode: 'SLOT', + ready: true, + issues: [], + }); + const audits = await prisma.auditLog.findMany({ + where: { store_id: storeId }, + }); + expect(audits.map((a) => [a.before_json, a.after_json])).toEqual([ + [{ customMode: 'NONE' }, { customMode: 'SLOT' }], + ]); + }, + ); + + it('없음으로는 준비 상태와 무관하게 바꾼다', async () => { + const { accountId, product } = await setupSellerWithProduct(); + await prisma.product.update({ + where: { id: product.id }, + data: { custom_mode: 'SLOT' }, + }); + + const result = await service.sellerSetProductCustomMode( + accountId, + product.id, + 'NONE', + ); + expect(result.customMode).toBe('NONE'); + }); + + it('지금과 같은 방식이면 준비 상태를 보지 않고 감사 없이 그대로 돌려준다', async () => { + const { accountId, storeId, product } = await setupSellerWithProduct(); + await prisma.product.update({ + where: { id: product.id }, + data: { custom_mode: 'SLOT' }, + }); + + const result = await service.sellerSetProductCustomMode( + accountId, + product.id, + 'SLOT', + ); + + expect(result.customMode).toBe('SLOT'); + expect(result.customReadiness).toEqual([ + { mode: 'NONE', ready: true, issues: [] }, + { + mode: 'SLOT', + ready: false, + issues: [ + { + code: 'SLOT_TEMPLATE_MISSING', + message: '바탕 이미지를 먼저 등록해 주세요.', + optionGroupId: null, + }, + ], + }, + { + mode: 'THREE_D', + ready: false, + issues: [expect.objectContaining({ code: 'THREE_D_GROUP_MISSING' })], + }, + ]); + expect( + await prisma.auditLog.count({ where: { store_id: storeId } }), + ).toBe(0); + }); + }); + describe('sellerUpsertProductCustomTemplate', () => { it('없는 productId면 404', async () => { const { accountId } = await setupSellerWithProduct(); @@ -92,30 +224,48 @@ describe('SellerCustomTemplateService (real DB)', () => { }); it('처음 호출 시 template 생성, 두 번째 호출 시 같은 product_id의 template 갱신 (upsert)', async () => { - const { accountId, product } = await setupSellerWithProduct(); + const { accountId, storeId, product } = await setupSellerWithProduct(); const first = await service.sellerUpsertProductCustomTemplate(accountId, { productId: product.id.toString(), baseImageUrl: ownedUploadUrl('PRODUCT_IMAGE', accountId, 'a.png'), }); - const second = await service.sellerUpsertProductCustomTemplate( accountId, { productId: product.id.toString(), baseImageUrl: ownedUploadUrl('PRODUCT_IMAGE', accountId, 'b.png'), + freeEditEnabled: true, }, ); - expect(second.id).toBe(first.id); - expect(second.baseImageUrl).toBe( - ownedUploadUrl('PRODUCT_IMAGE', accountId, 'b.png'), - ); - - const templates = await prisma.productCustomTemplate.findMany({ - where: { product_id: product.id }, + expect(second).toMatchObject({ + id: first.id, + baseImageUrl: ownedUploadUrl('PRODUCT_IMAGE', accountId, 'b.png'), + freeEditEnabled: true, + revision: first.revision + 1, }); - expect(templates).toHaveLength(1); + expect( + await prisma.productCustomTemplate.count({ + where: { product_id: product.id }, + }), + ).toBe(1); + const audits = await prisma.auditLog.findMany({ + where: { store_id: storeId }, + orderBy: { id: 'asc' }, + }); + expect(audits.map((a) => a.after_json)).toEqual([ + { + templateId: first.id, + baseImageUrl: first.baseImageUrl, + freeEditEnabled: false, + }, + { + templateId: first.id, + baseImageUrl: second.baseImageUrl, + freeEditEnabled: true, + }, + ]); }); it('응답 textTokens에서 soft-delete된 슬롯은 제외한다', async () => { @@ -135,137 +285,246 @@ describe('SellerCustomTemplateService (real DB)', () => { }); }); - describe('sellerSetProductCustomTemplateActive', () => { - it('없는 templateId면 404', async () => { + describe('sellerUpsertProductCustomTextToken', () => { + it('templateId가 없으면 404', async () => { const { accountId } = await setupSellerWithProduct(); await expect( - service.sellerSetProductCustomTemplateActive(accountId, { - templateId: '999999', - isActive: false, - }), + service.sellerUpsertProductCustomTextToken(accountId, slot(999999n)), ).rejects.toThrowDomain(404); }); - it('다른 매장 template이면 404', async () => { + it('tokenId를 줬는데 다른 template 소속이면 404', async () => { const me = await setupSellerWithProduct(); const other = await setupSellerWithProduct(); - const othersTemplate = await createTemplate(other.product.id); + const myTpl = await createTemplate(me.product.id); + const othersTpl = await createTemplate(other.product.id); + const othersToken = await createCustomTextToken(prisma, { + template_id: othersTpl.id, + }); await expect( - service.sellerSetProductCustomTemplateActive(me.accountId, { - templateId: othersTemplate.id.toString(), - isActive: false, - }), + service.sellerUpsertProductCustomTextToken( + me.accountId, + slot(myTpl.id, { tokenId: othersToken.id.toString() }), + ), ).rejects.toThrowDomain(404); }); - it('is_active 토글 + audit log STATUS_CHANGE', async () => { - const { accountId, storeId, product } = await setupSellerWithProduct(); + it('tokenId 없이 호출하면 새로 만들고 표시 이름·글자색·정렬은 기본값이다', async () => { + const { accountId, product } = await setupSellerWithProduct(); const tpl = await createTemplate(product.id); - await service.sellerSetProductCustomTemplateActive(accountId, { - templateId: tpl.id.toString(), - isActive: false, - }); - - const after = await prisma.productCustomTemplate.findUniqueOrThrow({ - where: { id: tpl.id }, - }); - expect(after.is_active).toBe(false); + const result = await service.sellerUpsertProductCustomTextToken( + accountId, + slot(tpl.id, { tokenKey: 'name', defaultText: '홍길동' }), + ); - const auditLogs = await prisma.auditLog.findMany({ - where: { store_id: storeId, action: 'STATUS_CHANGE' }, + expect(result).toMatchObject({ + tokenKey: 'name', + label: 'name', + maxLength: 20, + textColor: '#000000', + textAlign: 'CENTER', + ...AREA, }); - expect(auditLogs).toHaveLength(1); }); - it('응답 textTokens에서 soft-delete된 슬롯은 제외한다', async () => { + it('tokenId 포함 호출 → 기존 토큰 갱신, 생략한 표시 이름·글자색·정렬은 그대로 둔다', async () => { const { accountId, product } = await setupSellerWithProduct(); const tpl = await createTemplate(product.id); - const live = await createTokensWithDeleted(tpl.id); + const token = await createCustomTextToken(prisma, { + template_id: tpl.id, + token_key: 'a', + label: '받는 사람', + text_color: '#FF0000', + text_align: 'RIGHT', + }); - const result = await service.sellerSetProductCustomTemplateActive( + const result = await service.sellerUpsertProductCustomTextToken( accountId, - { templateId: tpl.id.toString(), isActive: false }, - ); - - expect(result.textTokens.map((t) => t.id)).toEqual([live.id.toString()]); - }); - }); - - describe('sellerUpsertProductCustomTextToken', () => { - it('templateId가 없으면 404', async () => { - const { accountId } = await setupSellerWithProduct(); - await expect( - service.sellerUpsertProductCustomTextToken(accountId, { - templateId: '999999', - tokenKey: 'NAME', - defaultText: 'X', + slot(tpl.id, { + tokenId: token.id.toString(), + tokenKey: 'b', + defaultText: '나', }), - ).rejects.toThrowDomain(404); - }); + ); - it('tokenId를 줬는데 다른 template 소속이면 404', async () => { - const me = await setupSellerWithProduct(); - const other = await setupSellerWithProduct(); - const myTpl = await createTemplate(me.product.id); - const othersTpl = await createTemplate(other.product.id); - const othersToken = await prisma.productCustomTextToken.create({ - data: { - template_id: othersTpl.id, - token_key: 'X', - default_text: 'x', - }, + expect(result).toMatchObject({ + id: token.id.toString(), + tokenKey: 'b', + label: '받는 사람', + defaultText: '나', + textColor: '#FF0000', + textAlign: 'RIGHT', }); - - await expect( - service.sellerUpsertProductCustomTextToken(me.accountId, { - templateId: myTpl.id.toString(), - tokenId: othersToken.id.toString(), - tokenKey: 'Y', - defaultText: 'y', - }), - ).rejects.toThrowDomain(404); }); - it('tokenId 없이 호출 → 신규 생성', async () => { + it('표시 이름·글자색(소문자는 대문자로)·정렬을 입력대로 저장한다', async () => { const { accountId, product } = await setupSellerWithProduct(); const tpl = await createTemplate(product.id); const result = await service.sellerUpsertProductCustomTextToken( accountId, - { - templateId: tpl.id.toString(), - tokenKey: 'NAME', - defaultText: '홍길동', - }, + slot(tpl.id, { + label: ' 받는 사람 ', + textColor: '#ff00aa', + textAlign: 'LEFT', + }), ); - expect(result.tokenKey).toBe('NAME'); - const tokens = await prisma.productCustomTextToken.findMany({ - where: { template_id: tpl.id }, + expect(result).toMatchObject({ + label: '받는 사람', + textColor: '#FF00AA', + textAlign: 'LEFT', }); - expect(tokens).toHaveLength(1); }); - it('tokenId 포함 호출 → 기존 토큰 갱신', async () => { - const { accountId, product } = await setupSellerWithProduct(); - const tpl = await createTemplate(product.id); - const token = await prisma.productCustomTextToken.create({ - data: { template_id: tpl.id, token_key: 'A', default_text: '가' }, - }); + describe('입력 검증', () => { + it.each([ + ['가득 찬 영역', 0, 0, 10000, 10000, true], + ['최소 영역', 0, 0, 1, 1, true], + ['오른쪽 아래 끝 1칸', 9999, 9999, 1, 1, true], + ['x 음수', -1, 0, 10, 10, false], + ['y 음수', 0, -1, 10, 10, false], + ['너비 0', 0, 0, 0, 10, false], + ['높이 0', 0, 0, 10, 0, false], + ['x + 너비 10001', 5000, 0, 5001, 10, false], + ['y + 높이 10001', 0, 5000, 10, 5001, false], + ['x가 끝(10000)', 10000, 0, 1, 1, false], + ['너비 10001', 0, 0, 10001, 1, false], + ])( + '좌표 경계 — %s(x=%i, y=%i, w=%i, h=%i)', + async (_label, posX, posY, width, height, ok) => { + const { accountId, product } = await setupSellerWithProduct(); + const tpl = await createTemplate(product.id); + const upsert = service.sellerUpsertProductCustomTextToken( + accountId, + slot(tpl.id, { posX, posY, width, height }), + ); - const result = await service.sellerUpsertProductCustomTextToken( - accountId, - { - templateId: tpl.id.toString(), - tokenId: token.id.toString(), - tokenKey: 'B', - defaultText: '나', + if (ok) await expect(upsert).resolves.toMatchObject({ posX, width }); + else + await expect(upsert).rejects.toThrowDomain( + 'CUSTOM_AREA_OUT_OF_BOUNDS', + ); }, ); - expect(result.id).toBe(token.id.toString()); - expect(result.tokenKey).toBe('B'); + + it.each([ + [0, 'FIELD_OUT_OF_RANGE'], + [1, null], + [50, null], + [51, 'FIELD_OUT_OF_RANGE'], + ] as const)('최대 글자 수 %i', async (maxLength, error) => { + const { accountId, product } = await setupSellerWithProduct(); + const tpl = await createTemplate(product.id); + const upsert = service.sellerUpsertProductCustomTextToken( + accountId, + slot(tpl.id, { maxLength }), + ); + + if (error) await expect(upsert).rejects.toThrowDomain(error); + else await expect(upsert).resolves.toMatchObject({ maxLength }); + }); + + it('기본 문구는 코드 포인트로 최대 글자 수까지다(이모지 1개 = 1자)', async () => { + const { accountId, product } = await setupSellerWithProduct(); + const tpl = await createTemplate(product.id); + + await expect( + service.sellerUpsertProductCustomTextToken( + accountId, + slot(tpl.id, { tokenKey: 'ok', maxLength: 2, defaultText: '🎂🎂' }), + ), + ).resolves.toMatchObject({ defaultText: '🎂🎂' }); + const tooLong = service.sellerUpsertProductCustomTextToken( + accountId, + slot(tpl.id, { + tokenKey: 'long', + label: '이름', + maxLength: 2, + defaultText: '🎂🎂🎂', + }), + ); + await expect(tooLong).rejects.toThrowDomain( + 'CUSTOM_TEXT_DEFAULT_TOO_LONG', + ); + await expect(tooLong).rejects.toThrow( + "'이름'의 기본 문구는 2자 이하여야 해요.", + ); + }); + + it.each([ + ['slot1', true], + ['a'.repeat(60), true], + ['a'.repeat(61), false], + ['Name', false], + ['slot_1', false], + [' ', false], + ])('키 %s', async (tokenKey, ok) => { + const { accountId, product } = await setupSellerWithProduct(); + const tpl = await createTemplate(product.id); + const upsert = service.sellerUpsertProductCustomTextToken( + accountId, + slot(tpl.id, { tokenKey }), + ); + + if (ok) await expect(upsert).resolves.toMatchObject({ tokenKey }); + else + await expect(upsert).rejects.toThrowDomain( + 'CUSTOM_TOKEN_KEY_INVALID', + ); + }); + + it('형식 규칙 전 키는 그대로 두면 수정할 수 있고, 다른 형식 밖 키로는 못 바꾼다', async () => { + const { accountId, product } = await setupSellerWithProduct(); + const tpl = await createTemplate(product.id); + const legacy = await createCustomTextToken(prisma, { + template_id: tpl.id, + token_key: 'NAME', + }); + const update = (tokenKey: string) => + service.sellerUpsertProductCustomTextToken( + accountId, + slot(tpl.id, { tokenId: legacy.id.toString(), tokenKey }), + ); + + await expect(update('NAME')).resolves.toMatchObject({ + tokenKey: 'NAME', + }); + await expect(update('NAME2')).rejects.toThrowDomain( + 'CUSTOM_TOKEN_KEY_INVALID', + ); + }); + + it.each([ + ['#FFF', 'INVALID_COLOR_FORMAT'], + ['red', 'INVALID_COLOR_FORMAT'], + ['#GGGGGG', 'INVALID_COLOR_FORMAT'], + ])('글자색 %s', async (textColor, error) => { + const { accountId, product } = await setupSellerWithProduct(); + const tpl = await createTemplate(product.id); + await expect( + service.sellerUpsertProductCustomTextToken( + accountId, + slot(tpl.id, { textColor }), + ), + ).rejects.toThrowDomain(error); + }); + + it.each([ + ['공백뿐', ' ', 'TEXT_REQUIRED'], + ['31자', '가'.repeat(31), 'TEXT_TOO_LONG'], + ])('표시 이름 %s', async (_label, label, error) => { + const { accountId, product } = await setupSellerWithProduct(); + const tpl = await createTemplate(product.id); + await expect( + service.sellerUpsertProductCustomTextToken( + accountId, + slot(tpl.id, { label }), + ), + ).rejects.toThrowDomain(error); + }); }); describe('같은 tokenKey 재사용', () => { @@ -274,11 +533,7 @@ describe('SellerCustomTemplateService (real DB)', () => { const tpl = await createTemplate(product.id); const first = await service.sellerUpsertProductCustomTextToken( accountId, - { - templateId: tpl.id.toString(), - tokenKey: 'NAME', - defaultText: '가', - }, + slot(tpl.id, { textColor: '#FF0000' }), ); await service.sellerDeleteProductCustomTextToken( accountId, @@ -289,7 +544,8 @@ describe('SellerCustomTemplateService (real DB)', () => { accountId, { templateId: tpl.id.toString(), - tokenKey: 'NAME', + tokenKey: 'name', + label: '이름', defaultText: '나', maxLength: 12, sortOrder: 3, @@ -301,10 +557,12 @@ describe('SellerCustomTemplateService (real DB)', () => { }, ); + // 복구도 등록이라 생략한 글자색은 기본값으로 돌아간다 expect(result).toEqual({ id: first.id, templateId: tpl.id.toString(), - tokenKey: 'NAME', + tokenKey: 'name', + label: '이름', defaultText: '나', maxLength: 12, sortOrder: 3, @@ -313,6 +571,8 @@ describe('SellerCustomTemplateService (real DB)', () => { posY: 2000, width: 8000, height: 1500, + textColor: '#000000', + textAlign: 'CENTER', }); const rows = await prisma.productCustomTextToken.findMany({ where: { template_id: tpl.id, deleted_at: undefined }, @@ -324,24 +584,25 @@ describe('SellerCustomTemplateService (real DB)', () => { orderBy: { id: 'asc' }, }); expect(audits.map((a) => a.after_json)).toEqual([ - { tokenId: first.id, tokenKey: 'NAME' }, - { tokenId: first.id, tokenKey: 'NAME' }, + { tokenId: first.id, tokenKey: 'name' }, + { tokenId: first.id, tokenKey: 'name' }, ]); }); it('활성 슬롯과 키가 겹치면 CUSTOM_TEXT_TOKEN_KEY_TAKEN이고 아무것도 바뀌지 않는다', async () => { const { accountId, storeId, product } = await setupSellerWithProduct(); const tpl = await createTemplate(product.id); - const live = await prisma.productCustomTextToken.create({ - data: { template_id: tpl.id, token_key: 'NAME', default_text: '가' }, + const live = await createCustomTextToken(prisma, { + template_id: tpl.id, + token_key: 'name', + default_text: '가', }); await expect( - service.sellerUpsertProductCustomTextToken(accountId, { - templateId: tpl.id.toString(), - tokenKey: 'NAME', - defaultText: '나', - }), + service.sellerUpsertProductCustomTextToken( + accountId, + slot(tpl.id, { defaultText: '나' }), + ), ).rejects.toThrowDomain('CUSTOM_TEXT_TOKEN_KEY_TAKEN'); const after = await prisma.productCustomTextToken.findUniqueOrThrow({ @@ -361,25 +622,21 @@ describe('SellerCustomTemplateService (real DB)', () => { async (_label, deletedAt) => { const { accountId, product } = await setupSellerWithProduct(); const tpl = await createTemplate(product.id); - await prisma.productCustomTextToken.create({ - data: { - template_id: tpl.id, - token_key: 'TAKEN', - default_text: 'x', - deleted_at: deletedAt, - }, + await createCustomTextToken(prisma, { + template_id: tpl.id, + token_key: 'taken', + deleted_at: deletedAt, }); - const mine = await prisma.productCustomTextToken.create({ - data: { template_id: tpl.id, token_key: 'MINE', default_text: 'y' }, + const mine = await createCustomTextToken(prisma, { + template_id: tpl.id, + token_key: 'mine', }); await expect( - service.sellerUpsertProductCustomTextToken(accountId, { - templateId: tpl.id.toString(), - tokenId: mine.id.toString(), - tokenKey: 'TAKEN', - defaultText: 'y', - }), + service.sellerUpsertProductCustomTextToken( + accountId, + slot(tpl.id, { tokenId: mine.id.toString(), tokenKey: 'taken' }), + ), ).rejects.toThrowDomain('CUSTOM_TEXT_TOKEN_KEY_TAKEN'); }, ); @@ -389,29 +646,22 @@ describe('SellerCustomTemplateService (real DB)', () => { const other = await setupSellerWithProduct(); const myTpl = await createTemplate(me.product.id); const othersTpl = await createTemplate(other.product.id); - const othersLive = await prisma.productCustomTextToken.create({ - data: { - template_id: othersTpl.id, - token_key: 'NAME', - default_text: 'a', - }, + const othersLive = await createCustomTextToken(prisma, { + template_id: othersTpl.id, + token_key: 'name', }); - const othersDeleted = await prisma.productCustomTextToken.create({ - data: { - template_id: othersTpl.id, - token_key: 'GONE', - default_text: 'b', - deleted_at: new Date(), - }, + const othersDeleted = await createCustomTextToken(prisma, { + template_id: othersTpl.id, + token_key: 'gone', + deleted_at: new Date(), }); const created = await Promise.all( - ['NAME', 'GONE'].map((tokenKey) => - service.sellerUpsertProductCustomTextToken(me.accountId, { - templateId: myTpl.id.toString(), - tokenKey, - defaultText: '내것', - }), + ['name', 'gone'].map((tokenKey) => + service.sellerUpsertProductCustomTextToken( + me.accountId, + slot(myTpl.id, { tokenKey, defaultText: '내것' }), + ), ), ); @@ -439,23 +689,20 @@ describe('SellerCustomTemplateService (real DB)', () => { await setupSellerWithProduct(); const tpl = await createTemplate(product.id); if (withDeleted) { - await prisma.productCustomTextToken.create({ - data: { - template_id: tpl.id, - token_key: 'NAME', - default_text: 'old', - deleted_at: new Date(), - }, + await createCustomTextToken(prisma, { + template_id: tpl.id, + token_key: 'name', + default_text: 'old', + deleted_at: new Date(), }); } const results = await Promise.allSettled( ['A', 'B'].map((defaultText) => - service.sellerUpsertProductCustomTextToken(accountId, { - templateId: tpl.id.toString(), - tokenKey: 'NAME', - defaultText, - }), + service.sellerUpsertProductCustomTextToken( + accountId, + slot(tpl.id, { defaultText }), + ), ), ); @@ -498,8 +745,8 @@ describe('SellerCustomTemplateService (real DB)', () => { it('soft-delete + audit log', async () => { const { accountId, storeId, product } = await setupSellerWithProduct(); const tpl = await createTemplate(product.id); - const token = await prisma.productCustomTextToken.create({ - data: { template_id: tpl.id, token_key: 'A', default_text: '가' }, + const token = await createCustomTextToken(prisma, { + template_id: tpl.id, }); await service.sellerDeleteProductCustomTextToken(accountId, token.id); @@ -531,12 +778,8 @@ describe('SellerCustomTemplateService (real DB)', () => { it('정상 재정렬', async () => { const { accountId, product } = await setupSellerWithProduct(); const tpl = await createTemplate(product.id); - const t1 = await prisma.productCustomTextToken.create({ - data: { template_id: tpl.id, token_key: 'A', default_text: 'a' }, - }); - const t2 = await prisma.productCustomTextToken.create({ - data: { template_id: tpl.id, token_key: 'B', default_text: 'b' }, - }); + const t1 = await createCustomTextToken(prisma, { template_id: tpl.id }); + const t2 = await createCustomTextToken(prisma, { template_id: tpl.id }); const result = await service.sellerReorderProductCustomTextTokens( accountId, diff --git a/src/features/product/services/product-seller-custom-template.service.ts b/src/features/product/services/product-seller-custom-template.service.ts index 384a79a9..5eda8ccb 100644 --- a/src/features/product/services/product-seller-custom-template.service.ts +++ b/src/features/product/services/product-seller-custom-template.service.ts @@ -8,25 +8,40 @@ import { type IAuditLogRepository, } from '@/features/audit-log'; import { + CUSTOM_AREA_SCALE, DEFAULT_TOKEN_MAX_LENGTH, MAX_TOKEN_DEFAULT_TEXT_LENGTH, - MAX_TOKEN_KEY_LENGTH, + MAX_TOKEN_LABEL_LENGTH, MAX_URL_LENGTH, + TOKEN_KEY_PATTERN, + TOKEN_MAX_LENGTH_RANGE, } from '@/features/product/constants/product-seller.constants'; import type { SellerReorderProductCustomTextTokensInput } from '@/features/product/dto/inputs/seller-reorder-product-custom-text-tokens.input'; -import type { SellerSetProductCustomTemplateActiveInput } from '@/features/product/dto/inputs/seller-set-product-custom-template-active.input'; import type { SellerUpsertProductCustomTemplateInput } from '@/features/product/dto/inputs/seller-upsert-product-custom-template.input'; import type { SellerUpsertProductCustomTextTokenInput } from '@/features/product/dto/inputs/seller-upsert-product-custom-text-token.input'; import { ProductRepository } from '@/features/product/repositories/product.repository'; +import { evaluateProductCustomIssues } from '@/features/product/services/product-custom-readiness.helper'; +import { + toCustomTemplateOutput, + toCustomTextTokenOutput, + toProductOutput, +} from '@/features/product/services/product-seller-mappers.helper'; import type { SellerCustomTemplateOutput, SellerCustomTextTokenOutput, + SellerProductOutput, } from '@/features/product/types/product-seller-output.type'; import { SellerBaseService, StoreSellerRepository } from '@/features/store'; -import { AuditActionType, AuditTargetType } from '@/generated/prisma/client'; +import { + AuditActionType, + AuditTargetType, + type CustomMode, +} from '@/generated/prisma/client'; import { assertOwnedUploadUrl } from '@/global/storage/assert-owned-upload-url'; import { S3Service } from '@/global/storage/s3.service'; +const HEX_COLOR = /^#[0-9a-f]{6}$/i; + @Injectable() export class SellerCustomTemplateService extends SellerBaseService { constructor( @@ -39,19 +54,43 @@ export class SellerCustomTemplateService extends SellerBaseService { super(repo, auditLogs); } + /** 같은 방식이면 그대로 돌려준다(감사 없음). 바꿀 방식에 준비 이슈가 있으면 CUSTOM_PRODUCT_NOT_READY. */ + async sellerSetProductCustomMode( + accountId: bigint, + productId: bigint, + customMode: CustomMode, + ): Promise { + const ctx = await this.requireSellerContext(accountId); + const product = await this.requireOwnProduct(productId, ctx.storeId); + if (product.custom_mode === customMode) return toProductOutput(product); + + if (evaluateProductCustomIssues(product, customMode).length > 0) { + throw new DomainException('CUSTOM_PRODUCT_NOT_READY'); + } + await this.productRepository.updateProduct( + { productId, data: { custom_mode: customMode } }, + () => ({ + actorAccountId: ctx.accountId, + storeId: ctx.storeId, + targetType: AuditTargetType.PRODUCT, + targetId: productId, + action: AuditActionType.UPDATE, + beforeJson: { customMode: product.custom_mode }, + afterJson: { customMode }, + }), + ); + return toProductOutput( + await this.requireOwnProduct(productId, ctx.storeId), + ); + } + async sellerUpsertProductCustomTemplate( accountId: bigint, input: SellerUpsertProductCustomTemplateInput, ): Promise { const ctx = await this.requireSellerContext(accountId); const productId = parseId(input.productId); - - const product = - await this.productRepository.findProductByIdIncludingInactive({ - productId, - storeId: ctx.storeId, - }); - if (!product) throw new DomainException('PRODUCT_NOT_FOUND'); + await this.requireOwnProduct(productId, ctx.storeId); const baseImageUrl = cleanRequiredText(input.baseImageUrl, MAX_URL_LENGTH); assertOwnedUploadUrl( @@ -66,51 +105,22 @@ export class SellerCustomTemplateService extends SellerBaseService { { productId, baseImageUrl, - isActive: input.isActive ?? true, + freeEditEnabled: input.freeEditEnabled ?? undefined, }, - (created) => ({ + (saved) => ({ actorAccountId: ctx.accountId, storeId: ctx.storeId, targetType: AuditTargetType.PRODUCT, targetId: productId, action: AuditActionType.UPDATE, afterJson: { - templateId: created.id.toString(), - }, - }), - ); - return this.toCustomTemplateOutput(row); - } - - async sellerSetProductCustomTemplateActive( - accountId: bigint, - input: SellerSetProductCustomTemplateActiveInput, - ): Promise { - const ctx = await this.requireSellerContext(accountId); - const templateId = parseId(input.templateId); - - const template = - await this.productRepository.findCustomTemplateById(templateId); - if (!template || template.product.store_id !== ctx.storeId) { - throw new DomainException('CUSTOM_TEMPLATE_NOT_FOUND'); - } - - const row = await this.productRepository.setCustomTemplateActive( - templateId, - input.isActive, - (created) => ({ - actorAccountId: ctx.accountId, - storeId: ctx.storeId, - targetType: AuditTargetType.PRODUCT, - targetId: template.product_id, - action: AuditActionType.STATUS_CHANGE, - afterJson: { - templateId: created.id.toString(), - isActive: created.is_active, + templateId: saved.id.toString(), + baseImageUrl: saved.base_image_url, + freeEditEnabled: saved.free_edit_enabled, }, }), ); - return this.toCustomTemplateOutput(row); + return toCustomTemplateOutput(row); } async sellerUpsertProductCustomTextToken( @@ -127,48 +137,79 @@ export class SellerCustomTemplateService extends SellerBaseService { throw new DomainException('CUSTOM_TEMPLATE_NOT_FOUND'); } - if (tokenId) { - const token = - await this.productRepository.findCustomTextTokenById(tokenId); - if ( - !token || - token.template.product.store_id !== ctx.storeId || - token.template.id !== templateId - ) { - throw new DomainException('CUSTOM_TEXT_TOKEN_NOT_FOUND'); - } + const existing = tokenId + ? await this.productRepository.findCustomTextTokenById(tokenId) + : null; + if ( + tokenId && + (!existing || + existing.template.product.store_id !== ctx.storeId || + existing.template.id !== templateId) + ) { + throw new DomainException('CUSTOM_TEXT_TOKEN_NOT_FOUND'); + } + + const tokenKey = input.tokenKey.trim(); + // 형식 규칙 전에 만든 키는 바꾸지 않는 한 그대로 둔다 + if (tokenKey !== existing?.token_key && !TOKEN_KEY_PATTERN.test(tokenKey)) { + throw new DomainException('CUSTOM_TOKEN_KEY_INVALID'); + } + const label = + input.label != null + ? cleanRequiredText(input.label, MAX_TOKEN_LABEL_LENGTH) + : (existing?.label ?? tokenKey.slice(0, MAX_TOKEN_LABEL_LENGTH)); + const maxLength = input.maxLength ?? DEFAULT_TOKEN_MAX_LENGTH; + this.assertPositiveRange( + maxLength, + TOKEN_MAX_LENGTH_RANGE.min, + TOKEN_MAX_LENGTH_RANGE.max, + 'maxLength', + ); + const defaultText = cleanRequiredText( + input.defaultText, + MAX_TOKEN_DEFAULT_TEXT_LENGTH, + ); + if ([...defaultText].length > maxLength) { + throw new DomainException('CUSTOM_TEXT_DEFAULT_TOO_LONG', { + label, + max: maxLength, + }); } + assertAreaInBounds(input); const row = await this.productRepository.upsertCustomTextToken( { tokenId, templateId, - tokenKey: cleanRequiredText(input.tokenKey, MAX_TOKEN_KEY_LENGTH), - defaultText: cleanRequiredText( - input.defaultText, - MAX_TOKEN_DEFAULT_TEXT_LENGTH, - ), - maxLength: input.maxLength ?? DEFAULT_TOKEN_MAX_LENGTH, + tokenKey, + label, + defaultText, + maxLength, sortOrder: input.sortOrder ?? 0, isRequired: input.isRequired ?? true, - posX: input.posX ?? null, - posY: input.posY ?? null, - width: input.width ?? null, - height: input.height ?? null, + posX: input.posX, + posY: input.posY, + width: input.width, + height: input.height, + textColor: + input.textColor != null + ? toUpperHexColor(input.textColor) + : undefined, + textAlign: input.textAlign ?? undefined, }, - (created) => ({ + (saved) => ({ actorAccountId: ctx.accountId, storeId: ctx.storeId, targetType: AuditTargetType.PRODUCT, targetId: template.product_id, action: tokenId ? AuditActionType.UPDATE : AuditActionType.CREATE, afterJson: { - tokenId: created.id.toString(), - tokenKey: created.token_key, + tokenId: saved.id.toString(), + tokenKey: saved.token_key, }, }), ); - return this.toCustomTextTokenOutput(row); + return toCustomTextTokenOutput(row); } async sellerDeleteProductCustomTextToken( @@ -238,64 +279,35 @@ export class SellerCustomTemplateService extends SellerBaseService { }, }), ); - return rows.map((row) => this.toCustomTextTokenOutput(row)); + return rows.map(toCustomTextTokenOutput); } - private toCustomTemplateOutput(row: { - id: bigint; - product_id: bigint; - base_image_url: string; - is_active: boolean; - text_tokens: { - id: bigint; - template_id: bigint; - token_key: string; - default_text: string; - max_length: number; - sort_order: number; - is_required: boolean; - pos_x: number | null; - pos_y: number | null; - width: number | null; - height: number | null; - }[]; - }): SellerCustomTemplateOutput { - return { - id: row.id.toString(), - productId: row.product_id.toString(), - baseImageUrl: row.base_image_url, - isActive: row.is_active, - textTokens: row.text_tokens.map((token) => - this.toCustomTextTokenOutput(token), - ), - }; + private async requireOwnProduct(productId: bigint, storeId: bigint) { + const product = + await this.productRepository.findProductByIdIncludingInactive({ + productId, + storeId, + }); + if (!product) throw new DomainException('PRODUCT_NOT_FOUND'); + return product; } +} - private toCustomTextTokenOutput(row: { - id: bigint; - template_id: bigint; - token_key: string; - default_text: string; - max_length: number; - sort_order: number; - is_required: boolean; - pos_x: number | null; - pos_y: number | null; - width: number | null; - height: number | null; - }): SellerCustomTextTokenOutput { - return { - id: row.id.toString(), - templateId: row.template_id.toString(), - tokenKey: row.token_key, - defaultText: row.default_text, - maxLength: row.max_length, - sortOrder: row.sort_order, - isRequired: row.is_required, - posX: row.pos_x, - posY: row.pos_y, - width: row.width, - height: row.height, - }; +function assertAreaInBounds(area: { + posX: number; + posY: number; + width: number; + height: number; +}): void { + const fits = (start: number, length: number) => + start >= 0 && length >= 1 && start + length <= CUSTOM_AREA_SCALE; + if (!fits(area.posX, area.width) || !fits(area.posY, area.height)) { + throw new DomainException('CUSTOM_AREA_OUT_OF_BOUNDS'); } } + +function toUpperHexColor(raw: string): string { + const value = raw.trim(); + if (!HEX_COLOR.test(value)) throw new DomainException('INVALID_COLOR_FORMAT'); + return value.toUpperCase(); +} diff --git a/src/features/product/services/product-seller-lifecycle.service.spec.ts b/src/features/product/services/product-seller-lifecycle.service.spec.ts index bff575ab..9dbb2698 100644 --- a/src/features/product/services/product-seller-lifecycle.service.spec.ts +++ b/src/features/product/services/product-seller-lifecycle.service.spec.ts @@ -140,7 +140,7 @@ describe('SellerProductLifecycleService (real DB)', () => { expect(auditLogs).toHaveLength(1); }); - it('description/purchaseNotice/currency/baseDesignImageUrl/preparationTimeMinutes 포함 수정 (buildProductUpdateData 전 필드 분기)', async () => { + it('description/purchaseNotice/currency/preparationTimeMinutes 포함 수정 (buildProductUpdateData 전 필드 분기)', async () => { const { account, store } = await setupSellerWithStore(prisma); const product = await createSellerProduct(store.id, { name: '초기' }); @@ -149,11 +149,6 @@ describe('SellerProductLifecycleService (real DB)', () => { description: '설명', purchaseNotice: '주의사항', currency: 'KRW', - baseDesignImageUrl: ownedUploadUrl( - 'PRODUCT_IMAGE', - account.id, - 'base.png', - ), preparationTimeMinutes: 60, regularPrice: 12000, salePrice: 9000, @@ -162,9 +157,6 @@ describe('SellerProductLifecycleService (real DB)', () => { expect(result.description).toBe('설명'); expect(result.purchaseNotice).toBe('주의사항'); expect(result.currency).toBe('KRW'); - expect(result.baseDesignImageUrl).toBe( - ownedUploadUrl('PRODUCT_IMAGE', account.id, 'base.png'), - ); expect(result.preparationTimeMinutes).toBe(60); expect(result.regularPrice).toBe(12000); expect(result.salePrice).toBe(9000); @@ -262,46 +254,5 @@ describe('SellerProductLifecycleService (real DB)', () => { expect(await prisma.product.count()).toBe(0); }, ); - - it.each(rejected)( - 'sellerCreateProduct.baseDesignImageUrl이 %s면 BadRequest', - async (_label, url) => { - const { account } = await setupSellerWithStore(prisma); - await expect( - service.sellerCreateProduct(account.id, { - name: 'X', - regularPrice: 10000, - initialImageUrl: ownedUploadUrl('PRODUCT_IMAGE', account.id), - baseDesignImageUrl: url(account.id), - }), - ).rejects.toThrowDomain('INVALID_IMAGE_URL'); - }, - ); - - it.each(rejected)( - 'sellerUpdateProduct.baseDesignImageUrl이 %s면 BadRequest', - async (_label, url) => { - const { account, store } = await setupSellerWithStore(prisma); - const product = await createSellerProduct(store.id); - await expect( - service.sellerUpdateProduct(account.id, { - productId: product.id.toString(), - baseDesignImageUrl: url(account.id), - }), - ).rejects.toThrowDomain('INVALID_IMAGE_URL'); - }, - ); - - it('sellerUpdateProduct.baseDesignImageUrl 빈 문자열은 제거 의미라 검증 없이 통과한다', async () => { - const { account, store } = await setupSellerWithStore(prisma); - const product = await createSellerProduct(store.id, { - base_design_image_url: 'https://legacy.example/base.png', - }); - const result = await service.sellerUpdateProduct(account.id, { - productId: product.id.toString(), - baseDesignImageUrl: '', - }); - expect(result.baseDesignImageUrl).toBeNull(); - }); }); }); diff --git a/src/features/product/services/product-seller-lifecycle.service.ts b/src/features/product/services/product-seller-lifecycle.service.ts index 8f303563..75416dc8 100644 --- a/src/features/product/services/product-seller-lifecycle.service.ts +++ b/src/features/product/services/product-seller-lifecycle.service.ts @@ -55,21 +55,10 @@ export class SellerProductLifecycleService extends SellerBaseService { this.validateProductPrices(input.regularPrice, input.salePrice); - const baseDesignImageUrl = cleanNullableText( - input.baseDesignImageUrl, - MAX_URL_LENGTH, - ); const initialImageUrl = cleanRequiredText( input.initialImageUrl, MAX_URL_LENGTH, ); - assertOwnedUploadUrl( - this.s3, - baseDesignImageUrl, - 'PRODUCT_IMAGE', - ctx.accountId, - 'INVALID_IMAGE_URL', - ); assertOwnedUploadUrl( this.s3, initialImageUrl, @@ -96,7 +85,6 @@ export class SellerProductLifecycleService extends SellerBaseService { regular_price: input.regularPrice, sale_price: input.salePrice ?? null, currency: this.cleanCurrency(input.currency), - base_design_image_url: baseDesignImageUrl, preparation_time_minutes: input.preparationTimeMinutes ?? DEFAULT_PREPARATION_TIME_MINUTES, is_active: input.isActive ?? true, @@ -139,15 +127,6 @@ export class SellerProductLifecycleService extends SellerBaseService { if (!current) throw new DomainException('PRODUCT_NOT_FOUND'); const data = this.buildProductUpdateData(input); - if (typeof data.base_design_image_url === 'string') { - assertOwnedUploadUrl( - this.s3, - data.base_design_image_url, - 'PRODUCT_IMAGE', - ctx.accountId, - 'INVALID_IMAGE_URL', - ); - } const nextRegularPrice = input.regularPrice ?? current.regular_price; const nextSalePrice = input.salePrice !== undefined ? input.salePrice : current.sale_price; @@ -307,14 +286,6 @@ export class SellerProductLifecycleService extends SellerBaseService { ...(input.currency !== undefined ? { currency: this.cleanCurrency(input.currency) } : {}), - ...(input.baseDesignImageUrl !== undefined - ? { - base_design_image_url: cleanNullableText( - input.baseDesignImageUrl, - MAX_URL_LENGTH, - ), - } - : {}), ...(input.preparationTimeMinutes !== undefined && input.preparationTimeMinutes !== null ? { preparation_time_minutes: input.preparationTimeMinutes } diff --git a/src/features/product/services/product-seller-mappers.helper.ts b/src/features/product/services/product-seller-mappers.helper.ts index 12ac2e74..c66ce9eb 100644 --- a/src/features/product/services/product-seller-mappers.helper.ts +++ b/src/features/product/services/product-seller-mappers.helper.ts @@ -1,7 +1,11 @@ +import { evaluateProductCustomIssues } from '@/features/product/services/product-custom-readiness.helper'; import type { + SellerCustomReadinessOutput, + SellerCustomTextTokenOutput, SellerProductImageOutput, SellerProductOutput, } from '@/features/product/types/product-seller-output.type'; +import { CustomMode, type CustomTextAlign } from '@/generated/prisma/client'; export interface ProductOptionGroupRow { id: bigint; @@ -11,8 +15,6 @@ export interface ProductOptionGroupRow { is_required: boolean; min_select: number; max_select: number; - option_requires_description: boolean; - option_requires_image: boolean; sort_order: number; is_active: boolean; option_items: { @@ -27,24 +29,31 @@ export interface ProductOptionGroupRow { }[]; } +export interface ProductCustomTextTokenRow { + id: bigint; + template_id: bigint; + token_key: string; + label: string; + default_text: string; + max_length: number; + sort_order: number; + is_required: boolean; + pos_x: number; + pos_y: number; + width: number; + height: number; + text_color: string; + text_align: CustomTextAlign; +} + export interface ProductCustomTemplateRow { id: bigint; product_id: bigint; base_image_url: string; - is_active: boolean; - text_tokens: { - id: bigint; - template_id: bigint; - token_key: string; - default_text: string; - max_length: number; - sort_order: number; - is_required: boolean; - pos_x: number | null; - pos_y: number | null; - width: number | null; - height: number | null; - }[]; + free_edit_enabled: boolean; + revision: number; + deleted_at: Date | null; + text_tokens: ProductCustomTextTokenRow[]; } export interface ProductDetailRow { @@ -56,8 +65,8 @@ export interface ProductDetailRow { regular_price: number; sale_price: number | null; currency: string; - base_design_image_url: string | null; preparation_time_minutes: number; + custom_mode: CustomMode; is_active: boolean; created_at: Date; updated_at: Date; @@ -89,8 +98,6 @@ export function toOptionGroupOutput(g: ProductOptionGroupRow) { isRequired: g.is_required, minSelect: g.min_select, maxSelect: g.max_select, - optionRequiresDescription: g.option_requires_description, - optionRequiresImage: g.option_requires_image, sortOrder: g.sort_order, isActive: g.is_active, optionItems: g.option_items.map((item) => ({ @@ -106,28 +113,48 @@ export function toOptionGroupOutput(g: ProductOptionGroupRow) { }; } +export function toCustomTextTokenOutput( + token: ProductCustomTextTokenRow, +): SellerCustomTextTokenOutput { + return { + id: token.id.toString(), + templateId: token.template_id.toString(), + tokenKey: token.token_key, + label: token.label, + defaultText: token.default_text, + maxLength: token.max_length, + sortOrder: token.sort_order, + isRequired: token.is_required, + posX: token.pos_x, + posY: token.pos_y, + width: token.width, + height: token.height, + textColor: token.text_color, + textAlign: token.text_align, + }; +} + export function toCustomTemplateOutput(t: ProductCustomTemplateRow) { return { id: t.id.toString(), productId: t.product_id.toString(), baseImageUrl: t.base_image_url, - isActive: t.is_active, - textTokens: t.text_tokens.map((token) => ({ - id: token.id.toString(), - templateId: token.template_id.toString(), - tokenKey: token.token_key, - defaultText: token.default_text, - maxLength: token.max_length, - sortOrder: token.sort_order, - isRequired: token.is_required, - posX: token.pos_x, - posY: token.pos_y, - width: token.width, - height: token.height, - })), + freeEditEnabled: t.free_edit_enabled, + revision: t.revision, + textTokens: t.text_tokens.map(toCustomTextTokenOutput), }; } +/** 판매자 커스텀 설정 화면이 방식별 카드에 준비 이슈를 띄운다. */ +export function toCustomReadinessOutput( + row: Pick, +): SellerCustomReadinessOutput[] { + return Object.values(CustomMode).map((mode) => { + const issues = evaluateProductCustomIssues(row, mode); + return { mode, ready: issues.length === 0, issues }; + }); +} + export function toProductOutput(row: ProductDetailRow): SellerProductOutput { return { id: row.id.toString(), @@ -138,8 +165,9 @@ export function toProductOutput(row: ProductDetailRow): SellerProductOutput { regularPrice: row.regular_price, salePrice: row.sale_price, currency: row.currency, - baseDesignImageUrl: row.base_design_image_url, preparationTimeMinutes: row.preparation_time_minutes, + customMode: row.custom_mode, + customReadiness: toCustomReadinessOutput(row), isActive: row.is_active, images: row.images.map((image) => toProductImageOutput(image)), categories: row.product_categories.map((c) => ({ diff --git a/src/features/product/services/product-seller-option.service.spec.ts b/src/features/product/services/product-seller-option.service.spec.ts index e1bbe58a..30f37c58 100644 --- a/src/features/product/services/product-seller-option.service.spec.ts +++ b/src/features/product/services/product-seller-option.service.spec.ts @@ -368,7 +368,7 @@ describe('SellerOptionService (real DB)', () => { }); describe('sellerUpdateOptionGroup 모든 선택 필드 분기', () => { - it('name/isRequired/minSelect/maxSelect/sortOrder/isActive/optionRequires* 전체 포함 수정', async () => { + it('name/isRequired/minSelect/maxSelect/sortOrder/isActive 전체 포함 수정', async () => { const { accountId, product } = await setupProductForSeller(); const group = await prisma.productOptionGroup.create({ data: { @@ -388,8 +388,6 @@ describe('SellerOptionService (real DB)', () => { maxSelect: 3, sortOrder: 5, isActive: false, - optionRequiresDescription: true, - optionRequiresImage: true, }); expect(result.name).toBe('사이즈(수정)'); @@ -398,8 +396,6 @@ describe('SellerOptionService (real DB)', () => { expect(result.maxSelect).toBe(3); expect(result.sortOrder).toBe(5); expect(result.isActive).toBe(false); - expect(result.optionRequiresDescription).toBe(true); - expect(result.optionRequiresImage).toBe(true); }); }); diff --git a/src/features/product/services/product-seller-option.service.ts b/src/features/product/services/product-seller-option.service.ts index adc28aaa..87f5ad6d 100644 --- a/src/features/product/services/product-seller-option.service.ts +++ b/src/features/product/services/product-seller-option.service.ts @@ -77,8 +77,6 @@ export class SellerOptionService extends SellerBaseService { is_required: input.isRequired ?? true, min_select: minSelect, max_select: maxSelect, - option_requires_description: input.optionRequiresDescription ?? false, - option_requires_image: input.optionRequiresImage ?? false, sort_order: input.sortOrder ?? 0, is_active: input.isActive ?? true, }, @@ -145,12 +143,6 @@ export class SellerOptionService extends SellerBaseService { ...(input.maxSelect !== undefined ? { max_select: input.maxSelect } : {}), - ...(input.optionRequiresDescription !== undefined - ? { option_requires_description: input.optionRequiresDescription } - : {}), - ...(input.optionRequiresImage !== undefined - ? { option_requires_image: input.optionRequiresImage } - : {}), ...(input.sortOrder !== undefined ? { sort_order: input.sortOrder } : {}), @@ -450,8 +442,6 @@ export class SellerOptionService extends SellerBaseService { is_required: boolean; min_select: number; max_select: number; - option_requires_description: boolean; - option_requires_image: boolean; sort_order: number; is_active: boolean; option_items: { @@ -473,8 +463,6 @@ export class SellerOptionService extends SellerBaseService { isRequired: row.is_required, minSelect: row.min_select, maxSelect: row.max_select, - optionRequiresDescription: row.option_requires_description, - optionRequiresImage: row.option_requires_image, sortOrder: row.sort_order, isActive: row.is_active, optionItems: row.option_items.map((item) => diff --git a/src/features/product/services/product-seller-query.service.spec.ts b/src/features/product/services/product-seller-query.service.spec.ts index 45c0a4fb..1ffed9f6 100644 --- a/src/features/product/services/product-seller-query.service.spec.ts +++ b/src/features/product/services/product-seller-query.service.spec.ts @@ -8,6 +8,8 @@ import { disconnectTestPrismaClient } from '@/test/db/prisma-test-client'; import { closeTruncateConnection, truncateAll } from '@/test/db/truncate'; import { createAccount, + createCustomTemplate, + createCustomTextToken, createProduct, setupSellerWithStore, } from '@/test/factories'; @@ -243,19 +245,53 @@ describe('SellerProductQueryService (real DB)', () => { const product = await createSellerProduct(store.id, { name: '템플릿 상품', }); - await prisma.productCustomTemplate.create({ - data: { - product_id: product.id, - base_image_url: 'https://i.example/tpl.png', - is_active: true, - }, + const template = await createCustomTemplate(prisma, { + product_id: product.id, + base_image_url: 'https://i.example/tpl.png', + }); + const slot = await createCustomTextToken(prisma, { + template_id: template.id, + token_key: 'name', + label: '받는 사람', + text_color: '#FF0000', + text_align: 'LEFT', }); const result = await service.sellerProduct(account.id, product.id); - expect(result.customTemplate).not.toBeNull(); - expect(result.customTemplate?.baseImageUrl).toBe( - 'https://i.example/tpl.png', - ); + expect(result.customMode).toBe('NONE'); + expect(result.customTemplate).toEqual({ + id: template.id.toString(), + productId: product.id.toString(), + baseImageUrl: 'https://i.example/tpl.png', + freeEditEnabled: false, + revision: 1, + textTokens: [ + { + id: slot.id.toString(), + templateId: template.id.toString(), + tokenKey: 'name', + label: '받는 사람', + defaultText: slot.default_text, + maxLength: 20, + sortOrder: 0, + isRequired: true, + posX: 1000, + posY: 1000, + width: 8000, + height: 1500, + textColor: '#FF0000', + textAlign: 'LEFT', + }, + ], + }); + // 문구 자리가 있어 슬롯형은 준비됐고, 3D는 연결 그룹이 없다 + expect( + result.customReadiness.map(({ mode, ready }) => [mode, ready]), + ).toEqual([ + ['NONE', true], + ['SLOT', true], + ['THREE_D', false], + ]); }); }); }); diff --git a/src/features/product/types/product-admin-output.type.ts b/src/features/product/types/product-admin-output.type.ts index 1c2106cb..ca0f8190 100644 --- a/src/features/product/types/product-admin-output.type.ts +++ b/src/features/product/types/product-admin-output.type.ts @@ -6,6 +6,7 @@ import type { BannerLinkType, BannerPlacement, CategoryType, + CustomMode, } from '@/generated/prisma/client'; export interface AdminBannerOutput { @@ -36,7 +37,8 @@ export interface AdminProductOutput { regularPrice: number; salePrice: number | null; currency: string; - baseDesignImageUrl: string | null; + customMode: CustomMode; + thumbnailUrl: string | null; isActive: boolean; createdAt: Date; updatedAt: Date; diff --git a/src/features/product/types/product-detail-output.type.ts b/src/features/product/types/product-detail-output.type.ts index 58aa47e3..62160077 100644 --- a/src/features/product/types/product-detail-output.type.ts +++ b/src/features/product/types/product-detail-output.type.ts @@ -1,3 +1,5 @@ +import type { CustomMode, CustomTextAlign } from '@/generated/prisma/client'; + export interface ProductDetailOptionItem { id: string; title: string; @@ -18,6 +20,28 @@ export interface ProductDetailOptionGroup { items: ProductDetailOptionItem[]; } +export interface ProductDetailCustomSlot { + id: string; + label: string; + defaultText: string; + maxLength: number; + isRequired: boolean; + posX: number; + posY: number; + width: number; + height: number; + textColor: string; + textAlign: CustomTextAlign; + sortOrder: number; +} + +export interface ProductDetailCustomTemplate { + revision: number; + baseImageUrl: string; + freeEditEnabled: boolean; + slots: ProductDetailCustomSlot[]; +} + export interface ProductDetail { id: string; storeId: string; @@ -32,4 +56,6 @@ export interface ProductDetail { reviewCount: number; isWishlisted: boolean; optionGroups: ProductDetailOptionGroup[]; + customMode: CustomMode; + customTemplate: ProductDetailCustomTemplate | null; } diff --git a/src/features/product/types/product-seller-output.type.ts b/src/features/product/types/product-seller-output.type.ts index 7c0e4dad..f4eb30ce 100644 --- a/src/features/product/types/product-seller-output.type.ts +++ b/src/features/product/types/product-seller-output.type.ts @@ -1,3 +1,6 @@ +import type { ProductCustomIssue } from '@/features/product/services/product-custom-readiness.helper'; +import type { CustomMode, CustomTextAlign } from '@/generated/prisma/client'; + export interface SellerCategoryOutput { id: string; name: string; @@ -40,8 +43,6 @@ export interface SellerOptionGroupOutput { isRequired: boolean; minSelect: number; maxSelect: number; - optionRequiresDescription: boolean; - optionRequiresImage: boolean; sortOrder: number; isActive: boolean; optionItems: SellerOptionItemOutput[]; @@ -51,24 +52,34 @@ export interface SellerCustomTextTokenOutput { id: string; templateId: string; tokenKey: string; + label: string; defaultText: string; maxLength: number; sortOrder: number; isRequired: boolean; - posX: number | null; - posY: number | null; - width: number | null; - height: number | null; + posX: number; + posY: number; + width: number; + height: number; + textColor: string; + textAlign: CustomTextAlign; } export interface SellerCustomTemplateOutput { id: string; productId: string; baseImageUrl: string; - isActive: boolean; + freeEditEnabled: boolean; + revision: number; textTokens: SellerCustomTextTokenOutput[]; } +export interface SellerCustomReadinessOutput { + mode: CustomMode; + ready: boolean; + issues: ProductCustomIssue[]; +} + export interface SellerProductOutput { id: string; storeId: string; @@ -78,8 +89,9 @@ export interface SellerProductOutput { regularPrice: number; salePrice: number | null; currency: string; - baseDesignImageUrl: string | null; preparationTimeMinutes: number; + customMode: CustomMode; + customReadiness: SellerCustomReadinessOutput[]; isActive: boolean; images: SellerProductImageOutput[]; categories: SellerCategoryOutput[]; diff --git a/src/graphql/removed-schema-elements.spec.ts b/src/graphql/removed-schema-elements.spec.ts index b32bd117..0329f573 100644 --- a/src/graphql/removed-schema-elements.spec.ts +++ b/src/graphql/removed-schema-elements.spec.ts @@ -4,6 +4,7 @@ import { join } from 'node:path'; import { buildSchema, type GraphQLSchema, + isInputObjectType, isNonNullType, isObjectType, } from 'graphql'; @@ -19,6 +20,33 @@ const REMOVED_OUTPUT_FIELDS: Array<[type: string, field: string, pr: string]> = ['TodayPickupStore', 'storeName', '플랜 11'], ['PopularCake', 'name', '플랜 12'], ['StoreProduct', 'name', '플랜 12'], + // 커스텀 방식이 템플릿 활성 토글·옵션 커스텀 요구 플래그를, 템플릿 바탕이 상품 바탕 이미지를 대신한다 + ['SellerProduct', 'baseDesignImageUrl', '커스텀 방식'], + ['AdminProduct', 'baseDesignImageUrl', '커스텀 방식'], + ['SellerOptionGroup', 'optionRequiresDescription', '커스텀 방식'], + ['SellerOptionGroup', 'optionRequiresImage', '커스텀 방식'], + ['AdminProductOptionGroup', 'optionRequiresDescription', '커스텀 방식'], + ['AdminProductOptionGroup', 'optionRequiresImage', '커스텀 방식'], + ['SellerCustomTemplate', 'isActive', '커스텀 방식'], + ['AdminProductCustomTemplate', 'isActive', '커스텀 방식'], + ]; +const REMOVED_INPUT_FIELDS: Array<[input: string, field: string, pr: string]> = + [ + ['SellerCreateProductInput', 'baseDesignImageUrl', '커스텀 방식'], + ['SellerUpdateProductInput', 'baseDesignImageUrl', '커스텀 방식'], + [ + 'SellerCreateOptionGroupInput', + 'optionRequiresDescription', + '커스텀 방식', + ], + ['SellerCreateOptionGroupInput', 'optionRequiresImage', '커스텀 방식'], + [ + 'SellerUpdateOptionGroupInput', + 'optionRequiresDescription', + '커스텀 방식', + ], + ['SellerUpdateOptionGroupInput', 'optionRequiresImage', '커스텀 방식'], + ['SellerUpsertProductCustomTemplateInput', 'isActive', '커스텀 방식'], ]; const REMOVED_TYPES: Array<[type: string, pr: string]> = [ ['SellerCursorInput', '플랜 06'], @@ -55,12 +83,14 @@ const REMOVED_TYPES: Array<[type: string, pr: string]> = [ ['MyOrderItemSelectedOption', '플랜 13'], ['MyOrderItemCustomText', '플랜 13'], ['MyOrderItemCustomFreeEdit', '플랜 13'], + ['SellerSetProductCustomTemplateActiveInput', '커스텀 방식'], ]; const REMOVED_ROOT_FIELDS: Array< [root: 'Query' | 'Mutation', field: string, pr: string] > = [ ['Query', 'storePickupCalendar', '플랜 08'], ['Query', 'storePickupTimeSlots', '플랜 08'], + ['Mutation', 'sellerSetProductCustomTemplateActive', '커스텀 방식'], ]; // 개명된 매장판 루트 필드는 storeId를 필수로 받는다 — 전역판(인자 없음)이 같은 이름으로 되살아나지 않게. const REQUIRED_ROOT_ARGS: Array< @@ -75,6 +105,10 @@ const PRESENT_OUTPUT_FIELD: [string, string] = [ 'MyPageCounts', 'wishlistCount', ]; +const PRESENT_INPUT_FIELD: [string, string] = [ + 'SellerCreateProductInput', + 'name', +]; const PRESENT_TYPE = 'MyPageCounts'; const PRESENT_ROOT_FIELD: ['Query', string] = ['Query', 'myPageOverview']; @@ -95,6 +129,15 @@ function hasOutputField( return isObjectType(t) && field in t.getFields(); } +function hasInputField( + schema: GraphQLSchema, + input: string, + field: string, +): boolean { + const t = schema.getType(input); + return isInputObjectType(t) && field in t.getFields(); +} + describe('삭제된 스키마 요소 부재 (전체 SDL 빌드)', () => { const schema = buildSchema( collectSdl(join(process.cwd(), 'src/features')).join('\n'), @@ -102,6 +145,10 @@ describe('삭제된 스키마 요소 부재 (전체 SDL 빌드)', () => { it('검사기는 존재하는 요소를 있음으로 판정한다 (반증)', () => { expect(hasOutputField(schema, ...PRESENT_OUTPUT_FIELD)).toBe(true); + expect(hasInputField(schema, ...PRESENT_INPUT_FIELD)).toBe(true); + // 출력 판정기는 입력 타입을, 입력 판정기는 출력 타입을 보지 않는다 + expect(hasOutputField(schema, ...PRESENT_INPUT_FIELD)).toBe(false); + expect(hasInputField(schema, ...PRESENT_OUTPUT_FIELD)).toBe(false); expect(schema.getType(PRESENT_TYPE)).toBeDefined(); expect( hasOutputField(schema, PRESENT_ROOT_FIELD[0], PRESENT_ROOT_FIELD[1]), @@ -115,6 +162,13 @@ describe('삭제된 스키마 요소 부재 (전체 SDL 빌드)', () => { }); } + for (const [input, field, pr] of REMOVED_INPUT_FIELDS) { + it(`${input}.${field} 입력 필드는 없다 (${pr})`, () => { + expect(schema.getType(input)).toBeDefined(); + expect(hasInputField(schema, input, field)).toBe(false); + }); + } + for (const [type, pr] of REMOVED_TYPES) { it(`${type} 타입은 없다 (${pr})`, () => { expect(schema.getType(type)).toBeUndefined(); diff --git a/src/test/enum-sdl-sync.spec.ts b/src/test/enum-sdl-sync.spec.ts index 2044062b..be137a72 100644 --- a/src/test/enum-sdl-sync.spec.ts +++ b/src/test/enum-sdl-sync.spec.ts @@ -5,6 +5,8 @@ import { Kind, parse, print, visit } from 'graphql'; import { ConversationBodyFormat, + CustomMode, + CustomTextAlign, NotificationEvent, OrderActor, OrderStatus, @@ -41,6 +43,18 @@ const PAIRS: Array< 'src/features/order/order.types.graphql', 'OrderActorType', ], + [ + 'CustomMode', + Object.values(CustomMode), + 'src/features/product/product.types.graphql', + 'CustomModeType', + ], + [ + 'CustomTextAlign', + Object.values(CustomTextAlign), + 'src/features/product/product.types.graphql', + 'CustomTextAlignType', + ], ]; function sdlEnumValues(source: string, enumName: string): string[] { diff --git a/src/test/factories/custom-template.factory.ts b/src/test/factories/custom-template.factory.ts new file mode 100644 index 00000000..08c8ef44 --- /dev/null +++ b/src/test/factories/custom-template.factory.ts @@ -0,0 +1,63 @@ +import type { + CustomTextAlign, + PrismaClient, + ProductCustomTemplate, + ProductCustomTextToken, +} from '@/generated/prisma/client'; +import { nextSeq } from '@/test/factories/sequence'; + +export interface CustomTemplateOverrides { + product_id: bigint; + base_image_url?: string; + free_edit_enabled?: boolean; + revision?: number; + deleted_at?: Date | null; +} + +export async function createCustomTemplate( + prisma: PrismaClient, + overrides: CustomTemplateOverrides, +): Promise { + return prisma.productCustomTemplate.create({ + data: { + base_image_url: 'https://i.example/base.png', + ...overrides, + }, + }); +} + +export interface CustomTextTokenOverrides { + template_id: bigint; + token_key?: string; + label?: string; + default_text?: string; + max_length?: number; + sort_order?: number; + is_required?: boolean; + pos_x?: number; + pos_y?: number; + width?: number; + height?: number; + text_color?: string; + text_align?: CustomTextAlign; + deleted_at?: Date | null; +} + +export async function createCustomTextToken( + prisma: PrismaClient, + overrides: CustomTextTokenOverrides, +): Promise { + const tokenKey = overrides.token_key ?? `slot${nextSeq()}`; + return prisma.productCustomTextToken.create({ + data: { + token_key: tokenKey, + label: tokenKey, + default_text: '문구', + pos_x: 1000, + pos_y: 1000, + width: 8000, + height: 1500, + ...overrides, + }, + }); +} diff --git a/src/test/factories/index.ts b/src/test/factories/index.ts index 08141a0f..242b3c6a 100644 --- a/src/test/factories/index.ts +++ b/src/test/factories/index.ts @@ -1,6 +1,7 @@ export * from './account.factory'; export * from './auth.factory'; export * from './category.factory'; +export * from './custom-template.factory'; export * from './notification.factory'; export * from './order.factory'; export * from './product.factory'; From f942904e0017d17808acfe024fea52c0cda829ce Mon Sep 17 00:00:00 2001 From: chanwoo7 Date: Thu, 19 Nov 2026 01:49:34 +0900 Subject: [PATCH 12/54] =?UTF-8?q?fix:=20=EB=AC=B8=EA=B5=AC=20=EC=9E=90?= =?UTF-8?q?=EB=A6=AC=20=EC=A2=8C=ED=91=9C=20=EB=B0=B1=ED=95=84=EC=9D=84=20?= =?UTF-8?q?=EB=B0=94=ED=83=95=20=EC=95=88=EC=9C=BC=EB=A1=9C=20=EC=9E=90?= =?UTF-8?q?=EB=A6=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 좌표 네 값을 따로 0~10000으로만 자르면 x+w·y+h가 10000을 넘거나 너비·높이가 0인 자리가 남는다. 이런 자리는 구매자 출력 계약(너비 1~10000, x+w ≤ 10000)을 어기고, 판매자가 좌표를 그대로 둔 채 다른 값만 고쳐도 CUSTOM_AREA_OUT_OF_BOUNDS로 거절된다. 변경점 - 백필 클램프를 서버 좌표 검증과 같은 범위로: 좌표 0~9999로 먼저 자르고, 다음 문장에서 너비·높이를 1~(10000 − 좌표)로 맞춘다(두 문장으로 나눠 SET 평가 순서에 기대지 않음) 테스트 - migration spec 좌표 케이스: 기존 클램프 행 기대값 수정([-5, 20000, 300, 12000] → [0, 9999, 300, 1]), 경계 행 5개(x+w 초과·좌표 10000·음수 너비·꽉 찬 영역·범위 안 그대로) 표 추가, 백필 뒤 모든 자리가 서버 좌표 검증 범위 안인지 단언 - 반증: 이전 클램프 문장으로 되돌리면 이 케이스가 실패함을 확인 --- .../migration.sql | 4 +- .../custom-product-settings.migration.spec.ts | 48 +++++++++++++++++-- 2 files changed, 47 insertions(+), 5 deletions(-) diff --git a/prisma/migrations/20261118155816_custom_product_settings/migration.sql b/prisma/migrations/20261118155816_custom_product_settings/migration.sql index f4fb3780..a7b2e55c 100644 --- a/prisma/migrations/20261118155816_custom_product_settings/migration.sql +++ b/prisma/migrations/20261118155816_custom_product_settings/migration.sql @@ -28,7 +28,9 @@ UPDATE `product_custom_text_token` t JOIN `_custom_text_token_rank` r ON r.`id` SET t.`pos_x` = 1000, t.`pos_y` = LEAST(1000 + r.`idx` * 2000, 8500), t.`width` = 8000, t.`height` = 1500 WHERE t.`pos_x` IS NULL OR t.`pos_y` IS NULL OR t.`width` IS NULL OR t.`height` IS NULL; DROP TEMPORARY TABLE `_custom_text_token_rank`; -UPDATE `product_custom_text_token` SET `pos_x` = LEAST(GREATEST(`pos_x`, 0), 10000), `pos_y` = LEAST(GREATEST(`pos_y`, 0), 10000), `width` = LEAST(GREATEST(`width`, 0), 10000), `height` = LEAST(GREATEST(`height`, 0), 10000); +-- 자리는 바탕 안에 둔다(서버 좌표 검증과 같은 범위): 좌표 0~9999, 너비·높이 1 이상, x+w·y+h ≤ 10000 +UPDATE `product_custom_text_token` SET `pos_x` = LEAST(GREATEST(`pos_x`, 0), 9999), `pos_y` = LEAST(GREATEST(`pos_y`, 0), 9999); +UPDATE `product_custom_text_token` SET `width` = LEAST(GREATEST(`width`, 1), 10000 - `pos_x`), `height` = LEAST(GREATEST(`height`, 1), 10000 - `pos_y`); -- end backfill -- AlterTable diff --git a/src/features/product/repositories/custom-product-settings.migration.spec.ts b/src/features/product/repositories/custom-product-settings.migration.spec.ts index ec44560d..1d1349fb 100644 --- a/src/features/product/repositories/custom-product-settings.migration.spec.ts +++ b/src/features/product/repositories/custom-product-settings.migration.spec.ts @@ -92,7 +92,7 @@ describe('상품 커스텀 설정 백필 (real DB)', () => { } async function runBackfill(conn: mysql.Connection): Promise { - expect(BACKFILL).toHaveLength(8); + expect(BACKFILL).toHaveLength(9); for (const stmt of BACKFILL) await conn.query(stmt); } @@ -220,7 +220,7 @@ describe('상품 커스텀 설정 백필 (real DB)', () => { }); }); - it('좌표가 하나라도 없는 자리는 판매자 앱 기본 배치(템플릿별 활성 순번)로, 있는 자리는 0~10000으로 자른다', async () => { + it('좌표가 하나라도 없는 자리는 판매자 앱 기본 배치(템플릿별 활성 순번)로, 있는 자리는 바탕 안으로 자른다', async () => { const [p1, p2] = await Promise.all([ createProduct(prisma), createProduct(prisma), @@ -251,21 +251,61 @@ describe('상품 커스텀 설정 백필 (real DB)', () => { templateId: other, sortOrder: 9, }); + // 좌표가 다 있는 자리: [입력, 기대] + const bounded: Array< + [[number, number, number, number], [number, number, number, number]] + > = [ + [ + [9000, 500, 3000, 0], + [9000, 500, 1000, 1], + ], + [ + [10000, 10000, 5, 5], + [9999, 9999, 1, 1], + ], + [ + [100, 200, -3, 400], + [100, 200, 1, 400], + ], + [ + [0, 0, 10000, 10000], + [0, 0, 10000, 10000], + ], + [ + [100, 200, 300, 400], + [100, 200, 300, 400], + ], + ]; + const boundedIds: number[] = []; + for (const [area] of bounded) { + boundedIds.push( + await insertToken(conn, { templateId: other, sortOrder: 10, area }), + ); + } await runBackfill(conn); const byId = new Map( (await tokens(conn)).map((t) => [ Number(t.id), - [t.pos_x, t.pos_y, t.width, t.height], + [t.pos_x, t.pos_y, t.width, t.height] as number[], ]), ); expect(byId.get(first)).toEqual([1000, 1000, 8000, 1500]); - expect(byId.get(clamped)).toEqual([0, 10000, 300, 10000]); + expect(byId.get(clamped)).toEqual([0, 9999, 300, 1]); expect(byId.get(partial)).toEqual([1000, 5000, 8000, 1500]); expect(byId.get(fourth)).toEqual([1000, 7000, 8000, 1500]); expect(byId.get(deleted)).toEqual([1000, 8500, 8000, 1500]); expect(byId.get(otherFirst)).toEqual([1000, 1000, 8000, 1500]); + expect(boundedIds.map((id) => byId.get(id))).toEqual( + bounded.map(([, expected]) => expected), + ); + // 판매자가 좌표를 그대로 두고 저장해도 서버 좌표 검증을 통과한다 + for (const [x, y, w, h] of byId.values()) { + expect(Math.min(x, y)).toBeGreaterThanOrEqual(0); + expect(Math.min(w, h)).toBeGreaterThanOrEqual(1); + expect(Math.max(x + w, y + h)).toBeLessThanOrEqual(10000); + } await conn.query(NOT_NULL_AFTER_BACKFILL); }); }); From 28c192b5a5845bc450ee8dc5e5eb7d976c56cf91 Mon Sep 17 00:00:00 2001 From: chanwoo7 Date: Thu, 19 Nov 2026 01:49:41 +0900 Subject: [PATCH 13/54] =?UTF-8?q?test:=20=EC=82=AD=EC=A0=9C=EB=90=9C=20?= =?UTF-8?q?=EB=AC=B8=EA=B5=AC=20=EC=9E=90=EB=A6=AC=EB=A7=8C=20=EB=82=A8?= =?UTF-8?q?=EC=9D=80=20=ED=85=9C=ED=94=8C=EB=A6=BF=EC=9D=98=20=EC=8A=AC?= =?UTF-8?q?=EB=A1=AF=ED=98=95=20=EC=A4=80=EB=B9=84=20=ED=8C=90=EC=A0=95=20?= =?UTF-8?q?=ED=9A=8C=EA=B7=80=20=ED=85=8C=EC=8A=A4=ED=8A=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 방식 변경과 판매자 상품 준비 상태의 '문구 자리 0개' 판정은 상품 조회가 문구 자리에 거는 삭제 제외 조건에 기댄다. 이 조건을 지워도 실패하는 테스트가 없어, 삭제 자리만 남은 템플릿이 슬롯형 준비 완료로 판정되는 회귀를 막지 못했다. 변경점 - sellerSetProductCustomMode spec 1건: 자유 편집 꺼진 템플릿 + 삭제된 문구 자리만 있음 → 슬롯형 전환 CUSTOM_PRODUCT_NOT_READY, 슬롯형 상품 출력의 SLOT 준비 이슈 SLOT_NOTHING_TO_EDIT, 응답 문구 자리 목록에서 삭제 자리 제외 테스트 - 반증: findProductByIdIncludingInactive의 문구 자리 삭제 제외 조건을 지우면 이 케이스가 실패함을 확인(전환이 성공으로 바뀜) --- ...uct-seller-custom-template.service.spec.ts | 28 +++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/src/features/product/services/product-seller-custom-template.service.spec.ts b/src/features/product/services/product-seller-custom-template.service.spec.ts index ab8e9551..68f0f831 100644 --- a/src/features/product/services/product-seller-custom-template.service.spec.ts +++ b/src/features/product/services/product-seller-custom-template.service.spec.ts @@ -125,6 +125,34 @@ describe('SellerCustomTemplateService (real DB)', () => { }, ); + it('삭제된 문구 자리만 남았고 자유 편집이 꺼졌으면 슬롯형으로 바꿀 수 없고, 준비 상태·응답 문구 자리에서도 삭제 자리를 세지 않는다', async () => { + const { accountId, product } = await setupSellerWithProduct(); + const tpl = await createTemplate(product.id); + await createCustomTextToken(prisma, { + template_id: tpl.id, + deleted_at: new Date(), + }); + + await expect( + service.sellerSetProductCustomMode(accountId, product.id, 'SLOT'), + ).rejects.toThrowDomain('CUSTOM_PRODUCT_NOT_READY'); + + // 이미 슬롯형인 상품은 같은 방식 요청이 판매자 상품 출력을 그대로 돌려준다 + await prisma.product.update({ + where: { id: product.id }, + data: { custom_mode: 'SLOT' }, + }); + const result = await service.sellerSetProductCustomMode( + accountId, + product.id, + 'SLOT', + ); + expect( + result.customReadiness.find((r) => r.mode === 'SLOT')?.issues, + ).toEqual([expect.objectContaining({ code: 'SLOT_NOTHING_TO_EDIT' })]); + expect(result.customTemplate?.textTokens).toEqual([]); + }); + it.each([ ['문구 자리가 있으면', false, 1], ['자유 편집을 허용했으면', true, 0], From c46d4b22b6f97e721d00e92ca5803efe49b3742d Mon Sep 17 00:00:00 2001 From: chanwoo7 Date: Thu, 19 Nov 2026 01:25:24 +0900 Subject: [PATCH 14/54] =?UTF-8?q?feat:=20=EC=BB=A4=EC=8A=A4=ED=85=80=20?= =?UTF-8?q?=EB=B0=94=ED=83=95=20=EC=9D=B4=EB=AF=B8=EC=A7=80=201:1=20?= =?UTF-8?q?=EC=84=9C=EB=B2=84=20=EA=B2=80=EC=A6=9D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문구 자리 좌표는 바탕 한 변을 10000으로 본 비율이라 바탕이 정사각이어야 뜻이 맞는다. 판매자 앱 크롭에 더해 서버가 업로드된 바탕 이미지의 가로·세로를 읽어 1:1을 강제한다. 변경점 - S3Service.readImageSize(url): 이 버킷 공개 URL의 객체를 Range GET(앞 64KB)으로 읽어 image-size로 크기를 구한다. 크기를 못 구했고 객체가 더 크면(JPEG SOF가 EXIF·ICC 뒤) 전체를 다시 읽는다. 이미지가 아니거나 객체가 없으면(404·416) null, 그 밖의 S3 오류는 로그 + S3_READ_FAILED(503) - 의존성: image-size 2.0.4 고정(2.x 중 2주 이상 지난 최신) - sellerUpsertProductCustomTemplate: 바탕 URL이 새로 들어오거나 바뀔 때만 읽는다. 가로·세로 차이 1px 이하만 허용(CUSTOM_BASE_IMAGE_NOT_SQUARE), 읽을 수 없으면 CUSTOM_BASE_IMAGE_UNREADABLE(400) - 에러 코드 CUSTOM_BASE_IMAGE_NOT_SQUARE·CUSTOM_BASE_IMAGE_UNREADABLE·S3_READ_FAILED 신설, SDL 설명 갱신 테스트 - readImageSize 11: 앞 64KB만 읽음(요청 인자 단언), SOF가 64KB 밖인 JPEG는 전체 재읽기, 작은 비이미지는 재읽기 없이 null, 큰 비이미지는 재읽기 뒤 null, 404·416은 null, 5xx·403·네트워크 오류는 S3_READ_FAILED와 원인 로그, 다른 버킷·URL 아님은 읽지 않음. 이미지는 PNG IHDR·JPEG SOF 바이트를 직접 만든다 - 템플릿 1:1 8: 정사각·가로·세로 1px 허용, 2px·세로로 긴 이미지 거절(템플릿 미생성), 읽기 실패 400, S3 실패 503, URL이 그대로면 읽지 않고 바뀔 때만 읽음. S3 읽기는 결과만 주입 - 가드 반증: 재읽기 분기·허용치·URL 비교를 깨면 해당 테스트가 실패함을 확인 --- package.json | 1 + src/common/errors/error-catalog.ts | 12 ++ .../constants/product-seller.constants.ts | 2 + src/features/product/product-seller.graphql | 2 + .../resolvers/product-seller.resolver.spec.ts | 5 + ...uct-seller-custom-template.service.spec.ts | 85 +++++++++ .../product-seller-custom-template.service.ts | 16 +- .../s3.service.read-image-size.spec.ts | 178 ++++++++++++++++++ src/global/storage/s3.service.ts | 90 ++++++++- src/global/storage/types/storage.types.ts | 5 + yarn.lock | 10 + 11 files changed, 404 insertions(+), 2 deletions(-) create mode 100644 src/global/storage/s3.service.read-image-size.spec.ts diff --git a/package.json b/package.json index 63ecfaaf..a4ebf344 100644 --- a/package.json +++ b/package.json @@ -71,6 +71,7 @@ "graphql-redis-subscriptions": "^2.7.0", "graphql-subscriptions": "^3.0.0", "graphql-ws": "^6.2.1", + "image-size": "2.0.4", "ioredis": "^5.3.2", "logform": "^2.7.0", "openid-client": "5.7.1", diff --git a/src/common/errors/error-catalog.ts b/src/common/errors/error-catalog.ts index 37eb2083..264fe8d5 100644 --- a/src/common/errors/error-catalog.ts +++ b/src/common/errors/error-catalog.ts @@ -138,6 +138,10 @@ export const ERROR_CATALOG = { status: HttpStatus.INTERNAL_SERVER_ERROR, message: '업로드 URL 생성에 실패했습니다.', }, + S3_READ_FAILED: { + status: HttpStatus.SERVICE_UNAVAILABLE, + message: '이미지를 확인하지 못했어요. 잠시 뒤 다시 시도해 주세요.', + }, INVALID_PROFILE_IMAGE_URL: { status: HttpStatus.BAD_REQUEST, message: '업로드 URL로 발급된 프로필 이미지 URL만 저장할 수 있습니다.', @@ -483,6 +487,14 @@ export const ERROR_CATALOG = { status: HttpStatus.BAD_REQUEST, message: '글자색은 #RRGGBB 형식으로 입력해 주세요.', }, + CUSTOM_BASE_IMAGE_NOT_SQUARE: { + status: HttpStatus.BAD_REQUEST, + message: '바탕 이미지는 정사각형(1:1)이어야 해요.', + }, + CUSTOM_BASE_IMAGE_UNREADABLE: { + status: HttpStatus.BAD_REQUEST, + message: '바탕 이미지를 읽을 수 없어요. 이미지를 다시 올려 주세요.', + }, INVALID_DAY_OF_WEEK: { status: HttpStatus.BAD_REQUEST, message: 'dayOfWeek는 0~6이어야 합니다.', diff --git a/src/features/product/constants/product-seller.constants.ts b/src/features/product/constants/product-seller.constants.ts index d67c99d9..e153c209 100644 --- a/src/features/product/constants/product-seller.constants.ts +++ b/src/features/product/constants/product-seller.constants.ts @@ -31,6 +31,8 @@ export const TOKEN_MAX_LENGTH_RANGE = { min: 1, max: 50 } as const; export const DEFAULT_TEXT_COLOR = '#000000'; /** 바탕 이미지 한 변을 이 값으로 본 정수 비율이 문구 자리 좌표다(원점 왼쪽 위). */ export const CUSTOM_AREA_SCALE = 10_000; +/** 바탕 이미지 가로·세로 차이 허용치(px). 크롭·축소 반올림 오차만 받는다. */ +export const BASE_IMAGE_SQUARE_TOLERANCE_PX = 1; // ── 태그 검색 ── diff --git a/src/features/product/product-seller.graphql b/src/features/product/product-seller.graphql index f1796dfb..71c4cf25 100644 --- a/src/features/product/product-seller.graphql +++ b/src/features/product/product-seller.graphql @@ -126,6 +126,8 @@ extend type Mutation { ): SellerProduct! """ 상품 커스텀 템플릿(슬롯형 바탕)을 등록 또는 수정한다. 수정하면 revision이 1 오른다. + 바탕 이미지가 바뀔 때만 서버가 이미지를 읽어 정사각(가로·세로 차이 1px 이하)인지 확인한다: + 아니면 CUSTOM_BASE_IMAGE_NOT_SQUARE, 이미지로 읽을 수 없으면 CUSTOM_BASE_IMAGE_UNREADABLE, 저장소를 읽지 못하면 S3_READ_FAILED(503). 판매자 로그인 필수. SELLER 계정이 아니면 FORBIDDEN, 매장을 보유하지 않으면 NOT_FOUND. """ sellerUpsertProductCustomTemplate( diff --git a/src/features/product/resolvers/product-seller.resolver.spec.ts b/src/features/product/resolvers/product-seller.resolver.spec.ts index 7c4e5b4e..e6927c57 100644 --- a/src/features/product/resolvers/product-seller.resolver.spec.ts +++ b/src/features/product/resolvers/product-seller.resolver.spec.ts @@ -27,6 +27,7 @@ import { SellerProductQueryService } from '@/features/product/services/product-s import { SellerProductTaxonomyService } from '@/features/product/services/product-seller-taxonomy.service'; import { StoreSellerRepository } from '@/features/store/repositories/store-seller.repository'; import type { PrismaClient } from '@/generated/prisma/client'; +import { S3Service } from '@/global/storage/s3.service'; import { disconnectTestPrismaClient } from '@/test/db/prisma-test-client'; import { closeTruncateConnection, truncateAll } from '@/test/db/truncate'; import { @@ -65,6 +66,10 @@ describe('Seller Product Resolvers (real DB)', () => { queryResolver = module.get(SellerProductQueryResolver); mutationResolver = module.get(SellerProductMutationResolver); prisma = p; + // 바탕 이미지 1:1 확인은 S3를 읽는다 — 배선 검증이라 정사각 결과만 준다 + jest + .spyOn(module.get(S3Service), 'readImageSize') + .mockResolvedValue({ width: 1000, height: 1000 }); }); afterAll(async () => { diff --git a/src/features/product/services/product-seller-custom-template.service.spec.ts b/src/features/product/services/product-seller-custom-template.service.spec.ts index 68f0f831..9a9a6a4a 100644 --- a/src/features/product/services/product-seller-custom-template.service.spec.ts +++ b/src/features/product/services/product-seller-custom-template.service.spec.ts @@ -1,3 +1,4 @@ +import { DomainException } from '@/common/errors/error-catalog'; import { AUDIT_LOG_REPOSITORY } from '@/features/audit-log'; import { AuditLogRepository } from '@/features/audit-log/repositories/audit-log.repository'; import { ProductRepository } from '@/features/product/repositories/product.repository'; @@ -5,6 +6,7 @@ import { SellerCustomTemplateService } from '@/features/product/services/product import type { SellerCustomTextTokenOutput } from '@/features/product/types/product-seller-output.type'; import { StoreSellerRepository } from '@/features/store/repositories/store-seller.repository'; import type { PrismaClient, Product } from '@/generated/prisma/client'; +import { S3Service } from '@/global/storage/s3.service'; import { disconnectTestPrismaClient } from '@/test/db/prisma-test-client'; import { closeTruncateConnection, truncateAll } from '@/test/db/truncate'; import { @@ -23,6 +25,7 @@ import { describe('SellerCustomTemplateService (real DB)', () => { let service: SellerCustomTemplateService; let prisma: PrismaClient; + let readImageSize: jest.SpyInstance; beforeAll(async () => { const { module, prisma: p } = await createTestingModuleWithRealDb({ @@ -39,6 +42,8 @@ describe('SellerCustomTemplateService (real DB)', () => { }); service = module.get(SellerCustomTemplateService); prisma = p; + // 바탕 이미지 읽기는 S3 네트워크 호출이라 결과만 주입한다(읽기 자체는 S3Service spec이 본다) + readImageSize = jest.spyOn(module.get(S3Service), 'readImageSize'); }); afterAll(async () => { @@ -48,6 +53,8 @@ describe('SellerCustomTemplateService (real DB)', () => { beforeEach(async () => { await truncateAll(); + readImageSize.mockReset(); + readImageSize.mockResolvedValue({ width: 1000, height: 1000 }); }); async function setupSellerWithProduct(): Promise<{ @@ -311,6 +318,83 @@ describe('SellerCustomTemplateService (real DB)', () => { expect(result.textTokens.map((t) => t.id)).toEqual([live.id.toString()]); }); + + describe('바탕 이미지 1:1', () => { + it.each([ + ['정사각', 1000, 1000, null], + ['가로가 1px 길다', 1001, 1000, null], + ['세로가 1px 길다', 1000, 1001, null], + ['가로가 2px 길다', 1002, 1000, 'CUSTOM_BASE_IMAGE_NOT_SQUARE'], + ['세로로 길다', 800, 1000, 'CUSTOM_BASE_IMAGE_NOT_SQUARE'], + ] as const)('%s(%i×%i)', async (_label, width, height, error) => { + const { accountId, product } = await setupSellerWithProduct(); + readImageSize.mockResolvedValue({ width, height }); + const upsert = service.sellerUpsertProductCustomTemplate(accountId, { + productId: product.id.toString(), + baseImageUrl: ownedUploadUrl('PRODUCT_IMAGE', accountId, 'b.png'), + }); + + if (error) await expect(upsert).rejects.toThrowDomain(error); + else await expect(upsert).resolves.toBeDefined(); + expect( + await prisma.productCustomTemplate.count({ + where: { product_id: product.id }, + }), + ).toBe(error ? 0 : 1); + }); + + it('이미지로 읽을 수 없으면 CUSTOM_BASE_IMAGE_UNREADABLE', async () => { + const { accountId, product } = await setupSellerWithProduct(); + readImageSize.mockResolvedValue(null); + await expect( + service.sellerUpsertProductCustomTemplate(accountId, { + productId: product.id.toString(), + baseImageUrl: ownedUploadUrl('PRODUCT_IMAGE', accountId, 'b.png'), + }), + ).rejects.toThrowDomain('CUSTOM_BASE_IMAGE_UNREADABLE'); + }); + + it('저장소를 읽지 못하면 503(S3_READ_FAILED)을 그대로 낸다', async () => { + const { accountId, product } = await setupSellerWithProduct(); + readImageSize.mockRejectedValue(new DomainException('S3_READ_FAILED')); + await expect( + service.sellerUpsertProductCustomTemplate(accountId, { + productId: product.id.toString(), + baseImageUrl: ownedUploadUrl('PRODUCT_IMAGE', accountId, 'b.png'), + }), + ).rejects.toThrowDomain(503); + }); + + it('바탕 URL이 그대로면 다시 읽지 않고, 바뀔 때만 읽는다', async () => { + const { accountId, product } = await setupSellerWithProduct(); + const kept = ownedUploadUrl('PRODUCT_IMAGE', accountId, 'kept.png'); + await createCustomTemplate(prisma, { + product_id: product.id, + base_image_url: kept, + }); + readImageSize.mockResolvedValue({ width: 300, height: 1000 }); + + const result = await service.sellerUpsertProductCustomTemplate( + accountId, + { + productId: product.id.toString(), + baseImageUrl: kept, + freeEditEnabled: true, + }, + ); + expect(result.freeEditEnabled).toBe(true); + expect(readImageSize).not.toHaveBeenCalled(); + + const changed = ownedUploadUrl('PRODUCT_IMAGE', accountId, 'new.png'); + await expect( + service.sellerUpsertProductCustomTemplate(accountId, { + productId: product.id.toString(), + baseImageUrl: changed, + }), + ).rejects.toThrowDomain('CUSTOM_BASE_IMAGE_NOT_SQUARE'); + expect(readImageSize).toHaveBeenCalledWith(changed); + }); + }); }); describe('sellerUpsertProductCustomTextToken', () => { @@ -843,6 +927,7 @@ describe('SellerCustomTemplateService (real DB)', () => { baseImageUrl: url(accountId), }), ).rejects.toThrowDomain('INVALID_IMAGE_URL'); + expect(readImageSize).not.toHaveBeenCalled(); }, ); }); diff --git a/src/features/product/services/product-seller-custom-template.service.ts b/src/features/product/services/product-seller-custom-template.service.ts index 5eda8ccb..77c5cbcc 100644 --- a/src/features/product/services/product-seller-custom-template.service.ts +++ b/src/features/product/services/product-seller-custom-template.service.ts @@ -8,6 +8,7 @@ import { type IAuditLogRepository, } from '@/features/audit-log'; import { + BASE_IMAGE_SQUARE_TOLERANCE_PX, CUSTOM_AREA_SCALE, DEFAULT_TOKEN_MAX_LENGTH, MAX_TOKEN_DEFAULT_TEXT_LENGTH, @@ -90,7 +91,7 @@ export class SellerCustomTemplateService extends SellerBaseService { ): Promise { const ctx = await this.requireSellerContext(accountId); const productId = parseId(input.productId); - await this.requireOwnProduct(productId, ctx.storeId); + const product = await this.requireOwnProduct(productId, ctx.storeId); const baseImageUrl = cleanRequiredText(input.baseImageUrl, MAX_URL_LENGTH); assertOwnedUploadUrl( @@ -100,6 +101,10 @@ export class SellerCustomTemplateService extends SellerBaseService { ctx.accountId, 'INVALID_IMAGE_URL', ); + // 검증해 저장한 바탕은 다시 읽지 않는다 — 자유 편집만 바꿀 때 S3를 타지 않게 + if (product.custom_template?.base_image_url !== baseImageUrl) { + await this.assertSquareBaseImage(baseImageUrl); + } const row = await this.productRepository.upsertProductCustomTemplate( { @@ -291,6 +296,15 @@ export class SellerCustomTemplateService extends SellerBaseService { if (!product) throw new DomainException('PRODUCT_NOT_FOUND'); return product; } + + /** 문구 자리 좌표는 정사각 바탕을 전제로 한 비율이라 1:1을 서버가 강제한다. */ + private async assertSquareBaseImage(url: string): Promise { + const size = await this.s3.readImageSize(url); + if (!size) throw new DomainException('CUSTOM_BASE_IMAGE_UNREADABLE'); + if (Math.abs(size.width - size.height) > BASE_IMAGE_SQUARE_TOLERANCE_PX) { + throw new DomainException('CUSTOM_BASE_IMAGE_NOT_SQUARE'); + } + } } function assertAreaInBounds(area: { diff --git a/src/global/storage/s3.service.read-image-size.spec.ts b/src/global/storage/s3.service.read-image-size.spec.ts new file mode 100644 index 00000000..023a3081 --- /dev/null +++ b/src/global/storage/s3.service.read-image-size.spec.ts @@ -0,0 +1,178 @@ +import { S3ServiceException } from '@aws-sdk/client-s3'; +import { ConfigService } from '@nestjs/config'; +import { Test } from '@nestjs/testing'; + +import { CustomLoggerService } from '@/global/logger/custom-logger.service'; +import { S3Service } from '@/global/storage/s3.service'; + +const mockSend = jest.fn(); + +jest.mock('@aws-sdk/client-s3', () => ({ + ...jest.requireActual('@aws-sdk/client-s3'), + S3Client: jest.fn().mockImplementation(() => ({ + send: (command: unknown) => mockSend(command), + })), + GetObjectCommand: jest.fn().mockImplementation((input: unknown) => input), +})); + +const HEADER_BYTES = 64 * 1024; +const HOST = 'caquick-media-test.s3.ap-northeast-2.amazonaws.com'; +const KEY = 'product-images/1/2026-06-10/base.png'; +const URL_ = `https://${HOST}/${KEY}`; + +function png(width: number, height: number): Uint8Array { + const bytes = new Uint8Array(33); + bytes.set([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]); + const view = new DataView(bytes.buffer); + view.setUint32(8, 13); + bytes.set([0x49, 0x48, 0x44, 0x52], 12); // IHDR + view.setUint32(16, width); + view.setUint32(20, height); + bytes.set([8, 6, 0, 0, 0], 24); + return bytes; +} + +/** SOI → 꽉 찬 APP1 세그먼트(65535) → SOF0. SOF가 앞 64KB 밖에 놓인다. */ +function jpegWithSofAfterHeader(width: number, height: number): Uint8Array { + const app = 0xffff; + const bytes = new Uint8Array(2 + 2 + app + 19); + const view = new DataView(bytes.buffer); + bytes.set([0xff, 0xd8, 0xff, 0xe1]); + view.setUint16(4, app); + const sof = 4 + app; + bytes.set([0xff, 0xc0], sof); + view.setUint16(sof + 2, 17); + bytes[sof + 4] = 8; + view.setUint16(sof + 5, height); + view.setUint16(sof + 7, width); + return bytes; +} + +/** Range 요청이면 앞부분만, 아니면 전체를 돌려주는 S3 응답. */ +function serve(object: Uint8Array) { + mockSend.mockImplementation((input: { Range?: string }) => { + const bytes = input.Range ? object.slice(0, HEADER_BYTES) : object; + return Promise.resolve({ + Body: { transformToByteArray: () => Promise.resolve(bytes) }, + ContentRange: input.Range + ? `bytes 0-${bytes.length - 1}/${object.length}` + : undefined, + }); + }); +} + +function s3Error(status: number, name: string) { + return new S3ServiceException({ + name, + $fault: status < 500 ? 'client' : 'server', + $metadata: { httpStatusCode: status }, + message: name, + }); +} + +describe('S3Service.readImageSize', () => { + let service: S3Service; + const logger = { error: jest.fn() }; + + beforeEach(async () => { + mockSend.mockReset(); + logger.error.mockClear(); + const moduleRef = await Test.createTestingModule({ + providers: [ + S3Service, + { + provide: ConfigService, + useValue: { + get: () => ({ + region: 'ap-northeast-2', + bucket: 'caquick-media-test', + presignExpiresSeconds: 600, + }), + }, + }, + { provide: CustomLoggerService, useValue: logger }, + ], + }).compile(); + service = moduleRef.get(S3Service); + }); + + it('앞 64KB만 읽어 크기를 구한다', async () => { + serve(png(1200, 1199)); + + await expect(service.readImageSize(URL_)).resolves.toEqual({ + width: 1200, + height: 1199, + }); + expect(mockSend.mock.calls).toEqual([ + [ + { + Bucket: 'caquick-media-test', + Key: KEY, + Range: `bytes=0-${HEADER_BYTES - 1}`, + }, + ], + ]); + }); + + it('SOF가 앞 64KB 밖이면 전체를 다시 읽어 크기를 구한다', async () => { + const jpeg = jpegWithSofAfterHeader(800, 600); + expect(jpeg.length).toBeGreaterThan(HEADER_BYTES); + serve(jpeg); + + await expect(service.readImageSize(URL_)).resolves.toEqual({ + width: 800, + height: 600, + }); + expect( + mockSend.mock.calls.map(([c]) => (c as { Range?: string }).Range), + ).toEqual([`bytes=0-${HEADER_BYTES - 1}`, undefined]); + }); + + it('작은 객체를 다 읽었는데 이미지가 아니면 다시 읽지 않고 null이다', async () => { + serve(new TextEncoder().encode('not an image')); + + await expect(service.readImageSize(URL_)).resolves.toBeNull(); + expect(mockSend).toHaveBeenCalledTimes(1); + }); + + it('큰 객체가 끝까지 이미지가 아니면 전체를 읽고도 null이다', async () => { + serve(new Uint8Array(HEADER_BYTES * 2).fill(0x41)); + + await expect(service.readImageSize(URL_)).resolves.toBeNull(); + expect(mockSend).toHaveBeenCalledTimes(2); + }); + + it.each([ + [404, 'NoSuchKey'], + [416, 'InvalidRange'], + ])('객체를 읽을 수 없으면(%i %s) null이다', async (status, name) => { + mockSend.mockRejectedValue(s3Error(status, name)); + + await expect(service.readImageSize(URL_)).resolves.toBeNull(); + expect(logger.error).not.toHaveBeenCalled(); + }); + + it.each([ + ['S3 5xx', s3Error(503, 'SlowDown')], + ['권한 거부', s3Error(403, 'AccessDenied')], + ['네트워크 오류', new Error('socket hang up')], + ])('%s면 S3_READ_FAILED(503)이고 원인을 남긴다', async (_label, error) => { + mockSend.mockRejectedValue(error); + + await expect(service.readImageSize(URL_)).rejects.toThrowDomain( + 'S3_READ_FAILED', + ); + expect(logger.error).toHaveBeenCalledWith( + 'S3 객체 읽기 실패', + expect.objectContaining({ key: KEY }), + ); + }); + + it.each([ + ['다른 버킷', `https://other.s3.ap-northeast-2.amazonaws.com/${KEY}`], + ['URL 아님', 'not a url'], + ])('%s의 URL은 읽지 않고 null이다', async (_label, url) => { + await expect(service.readImageSize(url)).resolves.toBeNull(); + expect(mockSend).not.toHaveBeenCalled(); + }); +}); diff --git a/src/global/storage/s3.service.ts b/src/global/storage/s3.service.ts index a991c09e..c6850116 100644 --- a/src/global/storage/s3.service.ts +++ b/src/global/storage/s3.service.ts @@ -1,9 +1,15 @@ import { randomUUID } from 'node:crypto'; -import { PutObjectCommand, S3Client } from '@aws-sdk/client-s3'; +import { + GetObjectCommand, + PutObjectCommand, + S3Client, + S3ServiceException, +} from '@aws-sdk/client-s3'; import { getSignedUrl } from '@aws-sdk/s3-request-presigner'; import { Injectable } from '@nestjs/common'; import { ConfigService } from '@nestjs/config'; +import { imageSize } from 'image-size'; import { DomainException } from '@/common/errors/error-catalog'; import type { S3Config } from '@/config/s3.config'; @@ -12,6 +18,7 @@ import { UPLOAD_POLICIES } from '@/global/storage/constants/storage.constants'; import type { CreateUploadUrlInput, CreateUploadUrlOutput, + ImageDimensions, UploadPurpose, } from '@/global/storage/types/storage.types'; @@ -23,6 +30,11 @@ const CONTENT_TYPE_TO_EXT: Record = { 'video/quicktime': '.mov', }; +/** 크기 헤더는 대개 앞부분에 있다. JPEG은 EXIF·ICC 세그먼트가 길면 SOF가 이보다 뒤에 올 수 있어 전체를 다시 읽는다. */ +const IMAGE_HEADER_BYTES = 64 * 1024; +/** 객체가 없거나(404) 0바이트라 범위를 못 읽는(416) 경우는 장애가 아니라 읽을 수 없는 이미지다. */ +const UNREADABLE_OBJECT_STATUS = new Set([404, 416]); + @Injectable() export class S3Service { private readonly client: S3Client; @@ -138,6 +150,73 @@ export class S3Service { ); } + /** + * 이 버킷의 공개 URL이 가리키는 이미지의 가로·세로(px)를 헤더만 읽어 구한다. 이미지가 아니거나 객체가 없으면 null, + * S3 호출 자체가 실패하면 S3_READ_FAILED다. 호출부가 URL 소유를 먼저 검증한다. + */ + async readImageSize(url: string): Promise { + const key = this.keyOfPublicUrl(url); + if (key === null) return null; + + const head = await this.readObject( + key, + `bytes=0-${IMAGE_HEADER_BYTES - 1}`, + ); + if (head === null) return null; + const size = measureImage(head.bytes); + if (size !== null || head.bytes.length >= head.totalBytes) return size; + + const full = await this.readObject(key); + return full === null ? null : measureImage(full.bytes); + } + + private keyOfPublicUrl(url: string): string | null { + try { + const parsed = new URL(url); + const expectedHost = `${this.bucket}.s3.${this.region}.amazonaws.com`; + return parsed.host === expectedHost + ? decodeURIComponent(parsed.pathname.slice(1)) + : null; + } catch { + return null; + } + } + + private async readObject( + key: string, + range?: string, + ): Promise<{ bytes: Uint8Array; totalBytes: number } | null> { + try { + const res = await this.client.send( + new GetObjectCommand({ Bucket: this.bucket, Key: key, Range: range }), + ); + const bytes = + (await res.Body?.transformToByteArray()) ?? new Uint8Array(); + // ContentRange: "bytes 0-65535/1234567" — 범위 요청이 아니면 받은 바이트가 전체다 + const total = Number(res.ContentRange?.split('/')[1]); + return { + bytes, + totalBytes: Number.isFinite(total) ? total : bytes.length, + }; + } catch (error) { + if ( + error instanceof S3ServiceException && + UNREADABLE_OBJECT_STATUS.has(error.$metadata.httpStatusCode ?? 0) + ) { + return null; + } + this.logger.error('S3 객체 읽기 실패', { + bucket: this.bucket, + key, + cause: + error instanceof Error + ? `${error.name}: ${error.message}` + : String(error), + }); + throw new DomainException('S3_READ_FAILED'); + } + } + private validateContentType( contentType: string, allowedTypes: readonly string[], @@ -177,3 +256,12 @@ export class S3Service { return `https://${this.bucket}.s3.${this.region}.amazonaws.com/${key}`; } } + +function measureImage(bytes: Uint8Array): ImageDimensions | null { + try { + const { width, height } = imageSize(bytes); + return width > 0 && height > 0 ? { width, height } : null; + } catch { + return null; + } +} diff --git a/src/global/storage/types/storage.types.ts b/src/global/storage/types/storage.types.ts index 390e4756..abe438a2 100644 --- a/src/global/storage/types/storage.types.ts +++ b/src/global/storage/types/storage.types.ts @@ -25,3 +25,8 @@ export interface UploadPolicy { maxSizeBytes: number; allowedContentTypes: readonly string[]; } + +export interface ImageDimensions { + width: number; + height: number; +} diff --git a/yarn.lock b/yarn.lock index 39da4d0b..b7b6f8d1 100644 --- a/yarn.lock +++ b/yarn.lock @@ -8089,6 +8089,7 @@ __metadata: graphql-subscriptions: "npm:^3.0.0" graphql-ws: "npm:^6.2.1" husky: "npm:^9.1.7" + image-size: "npm:2.0.4" ioredis: "npm:^5.3.2" istanbul-lib-coverage: "npm:3.2.2" istanbul-lib-report: "npm:3.0.1" @@ -11938,6 +11939,15 @@ __metadata: languageName: node linkType: hard +"image-size@npm:2.0.4": + version: 2.0.4 + resolution: "image-size@npm:2.0.4" + bin: + image-size: bin/image-size.js + checksum: 10c0/af01b8c2b7c536df1b866fc6daaa7e58ee909cde42fcae27562612ea77181f473445bc8acf0dfb5b9e8590e966a7a1f3f0fbf4c87ec6d1d4d60d68d87d529d76 + languageName: node + linkType: hard + "immutable@npm:^5.0.2": version: 5.1.4 resolution: "immutable@npm:5.1.4" From 45c288a826e4cff60e8fb919ad9eabba54bcc08a Mon Sep 17 00:00:00 2001 From: chanwoo7 Date: Thu, 19 Nov 2026 01:51:52 +0900 Subject: [PATCH 15/54] =?UTF-8?q?fix:=20=EB=B0=94=ED=83=95=20=EC=9D=B4?= =?UTF-8?q?=EB=AF=B8=EC=A7=80=20=EA=B0=9D=EC=B2=B4=EA=B0=80=20=EC=97=86?= =?UTF-8?q?=EC=9D=84=20=EB=95=8C=20403=20AccessDenied=EB=A5=BC=20=EC=9D=BD?= =?UTF-8?q?=EC=9D=84=20=EC=88=98=20=EC=97=86=EC=9D=8C=EC=9C=BC=EB=A1=9C=20?= =?UTF-8?q?=EC=B2=98=EB=A6=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 앱 IAM 정책에는 media 버킷 s3:ListBucket이 없어, S3는 없는 키(업로드 실패·미완료)를 404가 아니라 403 AccessDenied로 돌려준다. 그래서 운영에서는 404 분기에 닿지 않고 S3_READ_FAILED(503)와 error 로그가 나서, 판매자가 다시 시도해도 계속 503을 받았다. 변경점 - readObject: 403 AccessDenied는 없는 객체로 보고 null(→ CUSTOM_BASE_IMAGE_UNREADABLE 400). 호출부가 URL이 이 계정 업로드 prefix인지 먼저 검증하므로 그 키의 거부는 객체 없음이다. 정책에서 GetObject가 빠진 경우와 구별되지 않아 warn 로그는 남긴다 - 다른 403(서명 오류 등)·5xx·네트워크 오류는 그대로 error 로그 + S3_READ_FAILED - ListBucket 권한 추가(terraform apply 필요)는 하지 않음 — 앱 코드만으로 닫는다 테스트 - readImageSize: 403 AccessDenied → null·warn 로그·error 로그 없음 1건 추가, 실패 표의 권한 거부 행을 403 SignatureDoesNotMatch → S3_READ_FAILED로 교체 - 반증: AccessDenied 분기를 끄면 새 케이스가, 403 전체를 null로 넓히면 서명 오류 행이 실패함을 확인 --- .../s3.service.read-image-size.spec.ts | 16 ++++++++++++++-- src/global/storage/s3.service.ts | 19 +++++++++++++------ 2 files changed, 27 insertions(+), 8 deletions(-) diff --git a/src/global/storage/s3.service.read-image-size.spec.ts b/src/global/storage/s3.service.read-image-size.spec.ts index 023a3081..dcfbc630 100644 --- a/src/global/storage/s3.service.read-image-size.spec.ts +++ b/src/global/storage/s3.service.read-image-size.spec.ts @@ -72,11 +72,12 @@ function s3Error(status: number, name: string) { describe('S3Service.readImageSize', () => { let service: S3Service; - const logger = { error: jest.fn() }; + const logger = { error: jest.fn(), warn: jest.fn() }; beforeEach(async () => { mockSend.mockReset(); logger.error.mockClear(); + logger.warn.mockClear(); const moduleRef = await Test.createTestingModule({ providers: [ S3Service, @@ -152,9 +153,20 @@ describe('S3Service.readImageSize', () => { expect(logger.error).not.toHaveBeenCalled(); }); + it('ListBucket 권한이 없어 없는 키가 403 AccessDenied로 오면 null이고 경고만 남긴다', async () => { + mockSend.mockRejectedValue(s3Error(403, 'AccessDenied')); + + await expect(service.readImageSize(URL_)).resolves.toBeNull(); + expect(logger.warn).toHaveBeenCalledWith( + 'S3 객체 접근 거부 — 없는 객체로 본다', + expect.objectContaining({ key: KEY }), + ); + expect(logger.error).not.toHaveBeenCalled(); + }); + it.each([ ['S3 5xx', s3Error(503, 'SlowDown')], - ['권한 거부', s3Error(403, 'AccessDenied')], + ['403 서명 오류', s3Error(403, 'SignatureDoesNotMatch')], ['네트워크 오류', new Error('socket hang up')], ])('%s면 S3_READ_FAILED(503)이고 원인을 남긴다', async (_label, error) => { mockSend.mockRejectedValue(error); diff --git a/src/global/storage/s3.service.ts b/src/global/storage/s3.service.ts index c6850116..1ede2486 100644 --- a/src/global/storage/s3.service.ts +++ b/src/global/storage/s3.service.ts @@ -152,7 +152,7 @@ export class S3Service { /** * 이 버킷의 공개 URL이 가리키는 이미지의 가로·세로(px)를 헤더만 읽어 구한다. 이미지가 아니거나 객체가 없으면 null, - * S3 호출 자체가 실패하면 S3_READ_FAILED다. 호출부가 URL 소유를 먼저 검증한다. + * S3 호출 자체가 실패하면 S3_READ_FAILED다. 호출부가 URL 소유를 먼저 검증한다(403을 없는 객체로 보는 전제). */ async readImageSize(url: string): Promise { const key = this.keyOfPublicUrl(url); @@ -199,11 +199,18 @@ export class S3Service { totalBytes: Number.isFinite(total) ? total : bytes.length, }; } catch (error) { - if ( - error instanceof S3ServiceException && - UNREADABLE_OBJECT_STATUS.has(error.$metadata.httpStatusCode ?? 0) - ) { - return null; + if (error instanceof S3ServiceException) { + const status = error.$metadata.httpStatusCode ?? 0; + if (UNREADABLE_OBJECT_STATUS.has(status)) return null; + // 앱에 ListBucket 권한이 없어 S3는 없는 키를 404 대신 403 AccessDenied로 준다. + // 권한이 빠진 경우와 구별할 수 없어 경고는 남긴다. + if (status === 403 && error.name === 'AccessDenied') { + this.logger.warn('S3 객체 접근 거부 — 없는 객체로 본다', { + bucket: this.bucket, + key, + }); + return null; + } } this.logger.error('S3 객체 읽기 실패', { bucket: this.bucket, From 1f09e9da477e322a492872d7206f6e90145be78d Mon Sep 17 00:00:00 2001 From: chanwoo7 Date: Thu, 19 Nov 2026 02:39:20 +0900 Subject: [PATCH 16/54] =?UTF-8?q?feat:=20=EC=9E=85=EA=B8=88=20=EB=8C=80?= =?UTF-8?q?=EA=B8=B0=20=EC=A3=BC=EB=AC=B8=EA=B3=BC=20=EA=B4=80=EB=A6=AC?= =?UTF-8?q?=EC=9E=90=20=EC=88=98=EB=8F=99=20=EC=9E=85=EA=B8=88=20=ED=99=95?= =?UTF-8?q?=EC=9D=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ① 무엇·왜 - 주문이 계좌이체 결제로 바뀐다. createOrder는 입금 대기(PENDING_PAYMENT) 주문과 결제(PENDING, 케이퀵 계좌 스냅샷, 1시간 기한)를 만들고, 관리자가 은행 앱에서 입금을 확인하면 접수(SUBMITTED)로 넘어가 그때부터 판매자에게 보인다. - 계정당 입금 대기는 2건까지다. 같은 계정 요청은 GET_LOCK으로 직렬화하고 건수는 잠금 읽기로 세서 커밋 직전에 잠금이 풀려도 3건째가 생기지 않는다. - 입금액이 결제 금액과 다르면 확인을 막고(반환 연결로 처리), 픽업이 지난 주문도 확인을 막는다(확인 직후 마감 초과로 접수·취소 알림이 연달아 가는 것을 피한다). ② 변경점 - 주문 생성: 입금자명(생략 시 주문자 이름, 20자 초과 DEPOSITOR_NAME_INVALID), 입금 계좌 세 값이 모두 있어야 받음(PAYMENT_ACCOUNT_NOT_CONFIGURED), 수수료율 스냅샷, 입력 해시에 입금자명 추가, 판매자 구독 발행 제거, CreateOrderOutput.payment - 생성 tx: READ COMMITTED + timeout 10초, GET_LOCK 3초(시간 초과 CONCURRENT_REQUEST) → 입금 대기 건수 FOR SHARE → capacity 잠금 → 주문·결제·이력. REPEATABLE READ의 갭 잠금은 다른 계정끼리 건수 잠금 읽기 → INSERT에서 교착해 격리 수준을 낮췄다 - 상한 거절도 capacity 거절처럼 같은 키 주문이 있으면 replay한다 - OrderTransitionRepository.confirmPaymentLocked: 주문 → 결제 잠금 뒤 재판정, 결제 CONFIRMED(처리자 라벨·메모), 주문 SUBMITTED(확정 마감 = min(확인 + 24시간, 픽업)), 이력·감사(입금액)·outbox(order.status_changed + order.submitted) - 관리자: adminConfirmPayment, adminPendingPayments(claimedOnly는 '입금했어요' 시각 복합 커서, 금액·입금자명 필터, null = 생략), adminTaskCounts(claimedPayments·pendingPayments) - 구매자: markMyOrderDepositSent(기한 전 첫 누름만 기록, 다시 누르면 멱등), MyOrderDetail.payment, MyOrderSummary.paymentExpiresAt - 판매자·관리자 출력: SellerOrderDetail.paymentMethod, AdminOrderDetail.payment(처리자 라벨·메모), SellerOrderUpdate.kind(SUBMITTED·STATUS_CHANGED·PICKUP_RESCHEDULED) - 알림: 입금 확인(→ SUBMITTED)에 구매자 ORDER_PAYMENT_CONFIRMED, 판매자 '새 주문' 푸시는 확정 마감까지 2시간 미만이면 마감 시각을 싣는다(order.submitted.confirmDeadlineAt) - 에러 9종, ADMIN_QUERY_COUNT 18, admin 접두 루트 필드 67, createPayment 팩토리 ③ 테스트 - 결제·이력·계좌 스냅샷, 입금자명 경계(생략·공백·20자 이모지·21자·주문자 이름 21자), 계좌 미설정 4경우, 해시 입금자명 불일치 - 입금 대기 2건 경계·다른 상태/삭제/다른 계정 제외·상한에서 replay·동시 2요청·미커밋 행 대기 뒤 거절·GET_LOCK 시간 초과·다른 계정 동시 주문 무교착(5라운드) - 반증: REPEATABLE READ면 다른 계정 동시 주문 2건이 교착으로 실패, FOR SHARE를 빼면 미커밋 대기 케이스가 3건째를 받음, GET_LOCK을 빼면 동시 2요청이 둘 다 받음, RELEASE_LOCK을 빼면 실패 tx 뒤 잠금이 남음 - 입금 확인: 일치 성공·마감 두 경우·outbox·판매자 노출·구독 kind·구매자 알림, 불일치·0/음수·취소/확인됨/결제 없음 409·픽업 정각/경과·기한 지난 클레임 확인·없음/삭제·메모 길이·동시 확인 1건, 정책 전수 표 - 입금 대기 목록 순서·커서·claimedOnly 복합 커서·필터·null 입력·잘못된 커서, 처리 대기 건수 - '입금했어요' 기록·멱등·기한 정각/뒤/1ms 전·상태별 409·다른 계정/삭제 404 --- src/common/errors/error-catalog.ts | 39 ++ src/common/utils/text-cleaner.ts | 2 +- .../constants/notification-messages.ts | 2 + .../notification-outbox.consumer.spec.ts | 33 +- .../services/notification-outbox.consumer.ts | 2 +- .../notification-payloads.helper.spec.ts | 13 +- .../services/notification-payloads.helper.ts | 4 +- .../seller-push-messages.helper.spec.ts | 46 +- .../services/seller-push-messages.helper.ts | 12 +- .../seller-push-outbox.consumer.spec.ts | 20 +- .../services/seller-push-outbox.consumer.ts | 2 +- .../dto/inputs/admin-confirm-payment.input.ts | 14 + .../admin-pending-payment-list.input.ts | 24 + .../order/dto/inputs/create-order.input.ts | 5 + .../events/order-submitted.event.spec.ts | 20 +- .../order/events/order-submitted.event.ts | 14 +- src/features/order/order-admin.graphql | 4 + src/features/order/order-checkout.graphql | 19 +- .../order/order-deposit-admin.graphql | 208 +++++++ src/features/order/order-my.graphql | 17 + src/features/order/order-payment.graphql | 82 +++ src/features/order/order-seller.graphql | 4 + src/features/order/order-subscription.graphql | 18 +- src/features/order/order.module.ts | 17 +- .../policies/payment-confirm.policy.spec.ts | 68 +++ .../order/policies/payment-confirm.policy.ts | 26 + .../order-pending-payment-lock.helper.ts | 48 ++ .../order-transition.repository.spec.ts | 132 ++++ .../order-transition.repository.ts | 200 ++++++ .../repositories/order.repository.spec.ts | 130 ++-- .../order/repositories/order.repository.ts | 162 ++--- .../order/repositories/payment.repository.ts | 161 +++++ .../order-checkout-mutation.resolver.spec.ts | 11 +- .../order-deposit-admin-mutation.resolver.ts | 29 + .../order-deposit-admin-query.resolver.ts | 43 ++ .../order-deposit-admin.resolver.spec.ts | 88 +++ .../resolvers/order-my-mutation.resolver.ts | 29 + .../order/resolvers/order-my.resolver.spec.ts | 28 + .../services/order-admin-mappers.helper.ts | 2 + .../services/order-admin.service.spec.ts | 39 ++ .../order/services/order-admin.service.ts | 6 +- .../services/order-checkout.service.spec.ts | 507 ++++++++++----- .../order/services/order-checkout.service.ts | 107 ++-- .../order-deposit-admin.service.spec.ts | 575 ++++++++++++++++++ .../services/order-deposit-admin.service.ts | 138 +++++ .../services/order-events-mappers.helper.ts | 7 +- .../services/order-events.service.spec.ts | 1 + .../order/services/order-events.service.ts | 2 +- .../services/order-input-hash.helper.spec.ts | 12 +- .../order/services/order-input-hash.helper.ts | 2 + .../order/services/order-my.service.spec.ts | 190 ++++++ .../order/services/order-my.service.ts | 36 +- .../services/order-payment-mappers.helper.ts | 58 +- .../services/order-seller.service.spec.ts | 13 + .../order/services/order-seller.service.ts | 5 +- .../order-subscription.service.spec.ts | 1 + .../services/order-subscription.service.ts | 2 +- .../order/types/create-order-output.type.ts | 2 + .../order/types/order-admin-output.type.ts | 2 + .../order/types/order-my-output.type.ts | 3 + .../order/types/order-payment-output.type.ts | 46 +- .../order/types/order-seller-output.type.ts | 8 +- src/test/admin-query-null-inputs.spec.ts | 2 +- src/test/factories/order.factory.ts | 43 ++ src/test/roles-coverage.spec.ts | 2 +- 65 files changed, 3213 insertions(+), 374 deletions(-) create mode 100644 src/features/order/dto/inputs/admin-confirm-payment.input.ts create mode 100644 src/features/order/dto/inputs/admin-pending-payment-list.input.ts create mode 100644 src/features/order/order-deposit-admin.graphql create mode 100644 src/features/order/policies/payment-confirm.policy.spec.ts create mode 100644 src/features/order/policies/payment-confirm.policy.ts create mode 100644 src/features/order/repositories/order-pending-payment-lock.helper.ts create mode 100644 src/features/order/repositories/order-transition.repository.spec.ts create mode 100644 src/features/order/repositories/order-transition.repository.ts create mode 100644 src/features/order/repositories/payment.repository.ts create mode 100644 src/features/order/resolvers/order-deposit-admin-mutation.resolver.ts create mode 100644 src/features/order/resolvers/order-deposit-admin-query.resolver.ts create mode 100644 src/features/order/resolvers/order-deposit-admin.resolver.spec.ts create mode 100644 src/features/order/resolvers/order-my-mutation.resolver.ts create mode 100644 src/features/order/services/order-deposit-admin.service.spec.ts create mode 100644 src/features/order/services/order-deposit-admin.service.ts diff --git a/src/common/errors/error-catalog.ts b/src/common/errors/error-catalog.ts index 264fe8d5..1c7831be 100644 --- a/src/common/errors/error-catalog.ts +++ b/src/common/errors/error-catalog.ts @@ -375,6 +375,19 @@ export const ERROR_CATALOG = { status: HttpStatus.INTERNAL_SERVER_ERROR, message: '주문번호 생성에 실패했습니다. 잠시 후 다시 시도해 주세요.', }, + DEPOSITOR_NAME_INVALID: { + status: HttpStatus.BAD_REQUEST, + message: '입금자명을 20자 이내로 입력해 주세요.', + }, + PENDING_PAYMENT_LIMIT_EXCEEDED: { + status: HttpStatus.CONFLICT, + message: + '입금 대기 중인 주문이 2건 있어요. 입금하거나 취소한 뒤 다시 주문해 주세요.', + }, + CONCURRENT_REQUEST: { + status: HttpStatus.CONFLICT, + message: '같은 요청을 처리하고 있어요. 잠시 뒤 다시 시도해 주세요.', + }, // ── 결제·정산 INVALID_BANK_CODE: { status: HttpStatus.BAD_REQUEST, @@ -388,6 +401,32 @@ export const ERROR_CATALOG = { status: HttpStatus.BAD_REQUEST, message: '수수료율은 0~10000bp(0~100%) 사이 정수여야 합니다.', }, + PAYMENT_ACCOUNT_NOT_CONFIGURED: { + status: HttpStatus.SERVICE_UNAVAILABLE, + message: '지금은 주문을 받을 수 없습니다.', + }, + PAYMENT_NOT_PENDING: { + status: HttpStatus.CONFLICT, + message: '입금 대기 중인 주문이 아닙니다. 이미 처리됐는지 확인해 주세요.', + }, + PAYMENT_DEADLINE_PASSED: { + status: HttpStatus.BAD_REQUEST, + message: '입금 기한이 지났어요.', + }, + PAYMENT_PICKUP_PASSED: { + status: HttpStatus.CONFLICT, + message: + '픽업 시각이 지난 주문은 입금 확인할 수 없어요. 미입금 취소 뒤 반환 대상으로 연결해 주세요.', + }, + DEPOSIT_AMOUNT_INVALID: { + status: HttpStatus.BAD_REQUEST, + message: '입금액은 1원 이상의 정수로 입력해 주세요.', + }, + DEPOSIT_AMOUNT_MISMATCH: { + status: HttpStatus.BAD_REQUEST, + message: + '입금액이 결제 금액과 달라 입금 확인할 수 없어요. 반환 대상으로 연결해 주세요.', + }, // ── 판매자 SELLER_ONLY: { status: HttpStatus.FORBIDDEN, diff --git a/src/common/utils/text-cleaner.ts b/src/common/utils/text-cleaner.ts index cbb5c23e..ea956ff1 100644 --- a/src/common/utils/text-cleaner.ts +++ b/src/common/utils/text-cleaner.ts @@ -4,7 +4,7 @@ import { DomainException } from '@/common/errors/error-catalog'; * 길이는 코드 포인트 수로 센다 — class-validator MaxLength·MySQL utf8mb4 VARCHAR(n)과 같은 기준. * UTF-16 단위(String.length)로 세면 이모지 같은 보조 평면 문자가 2로 잡혀 DTO를 통과한 입력을 거절한다. */ -function codePointLength(text: string): number { +export function codePointLength(text: string): number { let n = 0; for (const _ of text) n += 1; return n; diff --git a/src/features/notification/constants/notification-messages.ts b/src/features/notification/constants/notification-messages.ts index 7112846d..8f785bf3 100644 --- a/src/features/notification/constants/notification-messages.ts +++ b/src/features/notification/constants/notification-messages.ts @@ -4,6 +4,7 @@ import { OrderStatus } from '@/generated/prisma/client'; export const ORDER_STATUS_NOTIFICATION_TITLES: Partial< Record > = { + [OrderStatus.SUBMITTED]: '입금확인', [OrderStatus.CONFIRMED]: '주문확정', [OrderStatus.MADE]: '제작완료', [OrderStatus.PICKED_UP]: '픽업완료', @@ -15,6 +16,7 @@ export const ORDER_STATUS_NOTIFICATION_TITLES: Partial< export const ORDER_STATUS_NOTIFICATION_BODIES: Partial< Record > = { + [OrderStatus.SUBMITTED]: '입금이 확인되어 주문이 접수되었어요.', [OrderStatus.CONFIRMED]: '주문이 확정되었어요.', [OrderStatus.MADE]: '주문하신 케이크 제작이 완료되었어요.', [OrderStatus.PICKED_UP]: '케이크 픽업이 완료되었어요.', diff --git a/src/features/notification/services/notification-outbox.consumer.spec.ts b/src/features/notification/services/notification-outbox.consumer.spec.ts index 99664075..a388cd35 100644 --- a/src/features/notification/services/notification-outbox.consumer.spec.ts +++ b/src/features/notification/services/notification-outbox.consumer.spec.ts @@ -37,7 +37,7 @@ function event( }; } -// 알림 생성의 단일 진입점 — payload 스냅샷 → 알림 컬럼 매핑, SUBMITTED 무시, 재전달 멱등, 형식 오류는 던진다. +// 알림 생성의 단일 진입점 — payload 스냅샷 → 알림 컬럼 매핑, 대상 아닌 전이 무시, 재전달 멱등, 형식 오류는 던진다. describe('NotificationOutboxConsumer (real DB)', () => { let consumer: NotificationOutboxConsumer; let repo: NotificationRepository; @@ -104,7 +104,34 @@ describe('NotificationOutboxConsumer (real DB)', () => { expect(row.body).toContain('ORD-77'); }); - it('SUBMITTED 전이는 알림 없이 정상 소비되고, 같은 이벤트 재전달은 중복을 만들지 않는다', async () => { + it('입금 확인(PENDING_PAYMENT → SUBMITTED)은 구매자에게 ORDER_PAYMENT_CONFIRMED 알림을 만든다', async () => { + const buyer = await createAccount(prisma, { account_type: 'USER' }); + const order = await createOrder(prisma, { account_id: buyer.id }); + + await consumer.handle( + event('order.status_changed', { + orderId: order.id.toString(), + orderNumber: 'ORD-9', + buyerAccountId: buyer.id.toString(), + fromStatus: 'PENDING_PAYMENT', + toStatus: 'SUBMITTED', + storeId: null, + storeName: null, + productId: null, + productName: null, + }), + ); + + const row = await prisma.notification.findFirstOrThrow(); + expect(row).toMatchObject({ + account_id: buyer.id, + event: 'ORDER_PAYMENT_CONFIRMED', + title: '입금확인', + body: 'ORD-9 입금이 확인되어 주문이 접수되었어요.', + }); + }); + + it('알림 대상이 아닌 전이는 알림 없이 정상 소비되고, 같은 이벤트 재전달은 중복을 만들지 않는다', async () => { const buyer = await createAccount(prisma, { account_type: 'USER' }); const order = await createOrder(prisma, { account_id: buyer.id }); const submitted = event('order.status_changed', { @@ -112,7 +139,7 @@ describe('NotificationOutboxConsumer (real DB)', () => { orderNumber: 'ORD-1', buyerAccountId: buyer.id.toString(), fromStatus: 'SUBMITTED', - toStatus: 'SUBMITTED', + toStatus: 'PENDING_PAYMENT', storeId: null, storeName: null, productId: null, diff --git a/src/features/notification/services/notification-outbox.consumer.ts b/src/features/notification/services/notification-outbox.consumer.ts index e730176c..7a114aae 100644 --- a/src/features/notification/services/notification-outbox.consumer.ts +++ b/src/features/notification/services/notification-outbox.consumer.ts @@ -61,7 +61,7 @@ export class NotificationOutboxConsumer implements OutboxConsumer { private async onOrderStatusChanged(event: OutboxEvent): Promise { const p = parseOrderStatusChangedPayload(event.payload); - // SUBMITTED 등 알림 대상이 아닌 전이는 payload가 null — 이벤트는 정상 소비된다 + // 알림 대상이 아닌 전이는 payload가 null — 이벤트는 정상 소비된다 const payload = buildOrderStatusNotification(p.orderNumber, p.toStatus); if (!payload) return; await this.repo.createFromEvent(event.eventId, [ diff --git a/src/features/notification/services/notification-payloads.helper.spec.ts b/src/features/notification/services/notification-payloads.helper.spec.ts index 0ab55b5c..f92669f3 100644 --- a/src/features/notification/services/notification-payloads.helper.spec.ts +++ b/src/features/notification/services/notification-payloads.helper.spec.ts @@ -49,9 +49,20 @@ describe('notification-payloads.helper', () => { }); }); - it('알림 대상이 아닌 상태(SUBMITTED)는 null을 반환한다', () => { + it('SUBMITTED(입금 확인으로만 도달)는 입금 확인 이벤트·문구로 매핑된다', () => { expect( buildOrderStatusNotification('ORD-5', OrderStatus.SUBMITTED), + ).toEqual({ + type: NotificationType.ORDER_STATUS, + event: NotificationEvent.ORDER_PAYMENT_CONFIRMED, + title: '입금확인', + body: 'ORD-5 입금이 확인되어 주문이 접수되었어요.', + }); + }); + + it('알림 대상이 아닌 상태(PENDING_PAYMENT)는 null을 반환한다', () => { + expect( + buildOrderStatusNotification('ORD-6', OrderStatus.PENDING_PAYMENT), ).toBeNull(); }); }); diff --git a/src/features/notification/services/notification-payloads.helper.ts b/src/features/notification/services/notification-payloads.helper.ts index 0a662d43..99c4900a 100644 --- a/src/features/notification/services/notification-payloads.helper.ts +++ b/src/features/notification/services/notification-payloads.helper.ts @@ -24,13 +24,15 @@ export interface NotificationPayload { const ORDER_STATUS_NOTIFICATION_EVENTS: Partial< Record > = { + // 접수는 관리자 입금 확인으로만 일어난다(주문 생성은 입금 대기) + [OrderStatus.SUBMITTED]: NotificationEvent.ORDER_PAYMENT_CONFIRMED, [OrderStatus.CONFIRMED]: NotificationEvent.ORDER_CONFIRMED, [OrderStatus.MADE]: NotificationEvent.ORDER_MADE, [OrderStatus.PICKED_UP]: NotificationEvent.ORDER_PICKED_UP, [OrderStatus.CANCELED]: NotificationEvent.ORDER_CANCELED, }; -/** SUBMITTED는 구매자 본인의 행위라 알림 없음(null). */ +/** 매핑에 없는 상태는 알림 없음(null). */ export function buildOrderStatusNotification( orderNumber: string, toStatus: OrderStatus, diff --git a/src/features/notification/services/seller-push-messages.helper.spec.ts b/src/features/notification/services/seller-push-messages.helper.spec.ts index 33370ddf..c4b72d29 100644 --- a/src/features/notification/services/seller-push-messages.helper.spec.ts +++ b/src/features/notification/services/seller-push-messages.helper.spec.ts @@ -15,27 +15,45 @@ describe('seller-push-messages.helper', () => { expect(formatKstPickupAt(new Date(iso))).toBe(expected); }); + const SUBMITTED = { + orderId: '42', + orderNumber: 'ORD-1', + buyerAccountId: '7', + storeId: '3', + storeName: '케이크샵', + productId: '9', + productName: '레터링 케이크', + quantity: 2, + pickupAt: '2026-10-05T03:05:00.000Z', + totalPrice: 50000, + // 접수 10/4 12:00 KST + 24시간 + confirmDeadlineAt: '2026-10-05T03:00:00.000Z', + }; + const SUBMITTED_AT = new Date('2026-10-04T03:00:00.000Z'); + it('주문 접수: 상품명·수량·픽업 시각(KST) 본문, 딥링크 data는 kind·orderId', () => { - expect( - buildOrderSubmittedPush({ - orderId: '42', - orderNumber: 'ORD-1', - buyerAccountId: '7', - storeId: '3', - storeName: '케이크샵', - productId: '9', - productName: '레터링 케이크', - quantity: 2, - pickupAt: '2026-10-05T03:05:00.000Z', - totalPrice: 50000, - }), - ).toEqual({ + expect(buildOrderSubmittedPush(SUBMITTED, SUBMITTED_AT)).toEqual({ title: '새 주문', body: '레터링 케이크 2개 · 픽업 10/5 12:05', data: { kind: 'ORDER_SUBMITTED', orderId: '42' }, }); }); + // 마감 2시간 전 미리 알림을 받을 수 없는 접수(마감 − 2시간 ≤ 접수)만 마감 시각을 싣는다 + it.each<[string, string | null, string]>([ + ['마감까지 2시간 1ms', '2026-10-04T05:00:00.001Z', ''], + ['마감까지 정확히 2시간', '2026-10-04T05:00:00.000Z', ' · 14:00까지 확정'], + ['마감까지 30분', '2026-10-04T03:30:00.000Z', ' · 12:30까지 확정'], + ['마감 없음(옛 이벤트)', null, ''], + ])('%s → 본문 꼬리 %p', (_case, deadline, suffix) => { + expect( + buildOrderSubmittedPush( + { ...SUBMITTED, confirmDeadlineAt: deadline }, + SUBMITTED_AT, + ).body, + ).toBe(`레터링 케이크 2개 · 픽업 10/5 12:05${suffix}`); + }); + it('구매자 문의: 본문은 preview 그대로, data는 kind·conversationId', () => { expect( buildBuyerMessagePush({ diff --git a/src/features/notification/services/seller-push-messages.helper.ts b/src/features/notification/services/seller-push-messages.helper.ts index 89e8099c..0f2675fc 100644 --- a/src/features/notification/services/seller-push-messages.helper.ts +++ b/src/features/notification/services/seller-push-messages.helper.ts @@ -27,12 +27,22 @@ export function formatKstPickupAt(date: Date): string { return `${month}/${day} ${formatMinutesOfDay(kstMinutesOfDay(date))}`; } +/** 확정 마감 2시간 전 미리 알림을 받을 수 없는 주문(접수 시점에 이미 2시간 미만)은 새 주문 푸시에 마감 시각을 싣는다. */ +const CONFIRM_REMINDER_LEAD_MS = 2 * 60 * 60_000; + export function buildOrderSubmittedPush( p: OrderSubmittedPayload, + submittedAt: Date, ): SellerPushContent { + const deadline = p.confirmDeadlineAt ? new Date(p.confirmDeadlineAt) : null; + const deadlineNote = + deadline && + deadline.getTime() - CONFIRM_REMINDER_LEAD_MS <= submittedAt.getTime() + ? ` · ${formatMinutesOfDay(kstMinutesOfDay(deadline))}까지 확정` + : ''; return { title: '새 주문', - body: `${p.productName} ${p.quantity}개 · 픽업 ${formatKstPickupAt(new Date(p.pickupAt))}`, + body: `${p.productName} ${p.quantity}개 · 픽업 ${formatKstPickupAt(new Date(p.pickupAt))}${deadlineNote}`, data: { kind: SELLER_PUSH_KIND.ORDER_SUBMITTED, orderId: p.orderId }, }; } diff --git a/src/features/notification/services/seller-push-outbox.consumer.spec.ts b/src/features/notification/services/seller-push-outbox.consumer.spec.ts index 1a335a0c..6d1b30af 100644 --- a/src/features/notification/services/seller-push-outbox.consumer.spec.ts +++ b/src/features/notification/services/seller-push-outbox.consumer.spec.ts @@ -47,10 +47,15 @@ function event( }; } -function orderSubmitted(storeId: bigint, eventId = EVENT_ID): OutboxEvent { +function orderSubmitted( + storeId: bigint, + eventId = EVENT_ID, + confirmDeadlineAt?: string, +): OutboxEvent { return event( 'order.submitted', { + ...(confirmDeadlineAt ? { confirmDeadlineAt } : {}), orderId: '42', orderNumber: 'ORD-1', buyerAccountId: '7', @@ -179,6 +184,19 @@ describe('SellerPushOutboxConsumer (real DB)', () => { expect(await sendsCounter()).toEqual({ TICKET_OK: 2 }); }); + it('접수 시각(occurredAt) 기준 확정 마감까지 2시간 미만이면 본문에 마감 시각을 싣는다', async () => { + const { storeId } = await storeWithDevices(1); + + // NOW(10/5 21:00 KST) + 1시간 + await consumer.handle( + orderSubmitted(storeId, EVENT_ID, '2026-10-05T13:00:00.000Z'), + ); + + expect(send.mock.calls[0][0][0].body).toBe( + '레터링 케이크 2개 · 픽업 10/5 12:05 · 22:00까지 확정', + ); + }); + it('해제된 디바이스와 다른 매장의 디바이스는 대상이 아니다', async () => { const { storeId, devices } = await storeWithDevices(1); await createSellerPushDevice(prisma, { diff --git a/src/features/notification/services/seller-push-outbox.consumer.ts b/src/features/notification/services/seller-push-outbox.consumer.ts index 2c9b9e89..133c07ed 100644 --- a/src/features/notification/services/seller-push-outbox.consumer.ts +++ b/src/features/notification/services/seller-push-outbox.consumer.ts @@ -158,7 +158,7 @@ export class SellerPushOutboxConsumer implements OutboxConsumer { const p = parseOrderSubmittedPayload(event.payload); return { storeId: parseId(p.storeId), - content: buildOrderSubmittedPush(p), + content: buildOrderSubmittedPush(p, event.occurredAt), }; } case CONVERSATION_BUYER_MESSAGE_SENT: { diff --git a/src/features/order/dto/inputs/admin-confirm-payment.input.ts b/src/features/order/dto/inputs/admin-confirm-payment.input.ts new file mode 100644 index 00000000..ef927aaf --- /dev/null +++ b/src/features/order/dto/inputs/admin-confirm-payment.input.ts @@ -0,0 +1,14 @@ +import { IsInt, IsOptional, IsString } from 'class-validator'; + +export class AdminConfirmPaymentInput { + @IsString() + orderId!: string; + + // 1원 미만은 서비스가 DEPOSIT_AMOUNT_INVALID로 거절한다 + @IsInt() + depositedAmount!: number; + + @IsOptional() + @IsString() + note?: string; +} diff --git a/src/features/order/dto/inputs/admin-pending-payment-list.input.ts b/src/features/order/dto/inputs/admin-pending-payment-list.input.ts new file mode 100644 index 00000000..c8f1e004 --- /dev/null +++ b/src/features/order/dto/inputs/admin-pending-payment-list.input.ts @@ -0,0 +1,24 @@ +import { + IsBoolean, + IsInt, + IsOptional, + IsString, + MaxLength, +} from 'class-validator'; + +import { CursorInput } from '@/common/dto/inputs/cursor.input'; + +export class AdminPendingPaymentListInput extends CursorInput { + @IsOptional() + @IsBoolean() + claimedOnly?: boolean; + + @IsOptional() + @IsInt() + amount?: number; + + @IsOptional() + @IsString() + @MaxLength(50) + depositorName?: string; +} diff --git a/src/features/order/dto/inputs/create-order.input.ts b/src/features/order/dto/inputs/create-order.input.ts index cd7e9f67..baa3fc85 100644 --- a/src/features/order/dto/inputs/create-order.input.ts +++ b/src/features/order/dto/inputs/create-order.input.ts @@ -51,6 +51,11 @@ export class CreateOrderInput { @Matches(PHONE_REGEX) buyerPhone?: string; + // 길이(20자)는 생략 시 쓰는 주문자 이름과 같은 규칙으로 서비스가 DEPOSITOR_NAME_INVALID로 판정한다 + @IsOptional() + @IsString() + depositorName?: string; + @IsInt() @Min(0) expectedTotalPrice!: number; diff --git a/src/features/order/events/order-submitted.event.spec.ts b/src/features/order/events/order-submitted.event.spec.ts index 7ef28909..9f0afb8c 100644 --- a/src/features/order/events/order-submitted.event.spec.ts +++ b/src/features/order/events/order-submitted.event.spec.ts @@ -16,10 +16,11 @@ const VALID = { quantity: 2, pickupAt: '2026-09-18T05:00:00.000Z', totalPrice: 56000, + confirmDeadlineAt: '2026-09-17T07:00:00.000Z', }; describe('order.submitted 이벤트', () => { - it('bigint·Date를 문자열로 싣고 order aggregate(상태 전이와 같은 파티션)에 묶는다', () => { + it('bigint·Date를 문자열로 싣고 order aggregate(상태 전이와 같은 파티션)에 묶고 행위자는 입금 확인자다', () => { const occurredAt = new Date('2026-09-16T07:00:00.000Z'); const event = orderSubmittedEvent({ orderId: 7n, @@ -32,7 +33,9 @@ describe('order.submitted 이벤트', () => { quantity: 2, pickupAt: new Date(VALID.pickupAt), totalPrice: 56000, + confirmDeadlineAt: new Date(VALID.confirmDeadlineAt), occurredAt, + actorAccountId: 11n, }); expect(event).toEqual({ @@ -41,13 +44,26 @@ describe('order.submitted 이벤트', () => { eventType: ORDER_SUBMITTED, payload: VALID, occurredAt, - actorAccountId: 3n, + actorAccountId: 11n, }); expect( parseOrderSubmittedPayload(event.payload as Prisma.JsonValue), ).toEqual(VALID); }); + it.each([ + ['누락', undefined], + ['비ISO', 'not-a-date'], + ['숫자', 1_700_000_000], + ])('확정 마감이 %s이면 null로 읽는다(옛 이벤트 호환)', (_label, value) => { + expect( + parseOrderSubmittedPayload({ + ...VALID, + confirmDeadlineAt: value, + }).confirmDeadlineAt, + ).toBeNull(); + }); + it.each([ ['null', null], ['배열', [VALID]], diff --git a/src/features/order/events/order-submitted.event.ts b/src/features/order/events/order-submitted.event.ts index a0170a31..fc4b5958 100644 --- a/src/features/order/events/order-submitted.event.ts +++ b/src/features/order/events/order-submitted.event.ts @@ -2,7 +2,7 @@ import type { OutboxEventInput } from '@/features/outbox'; import type { Prisma } from '@/generated/prisma/client'; /** - * 주문 접수 이벤트(판매자 푸시 원천). order.status_changed와 같은 aggregate라 릴레이가 "접수 → 상태 전이" 순서를 지킨다. + * 주문 접수 이벤트(판매자 '새 주문' 푸시 원천). 입금 확인 때 발행한다. * payload는 생산 시점 스냅샷 — 소비자가 order·store·product를 다시 읽지 않는다. */ export const ORDER_SUBMITTED = 'order.submitted'; @@ -19,6 +19,8 @@ export interface OrderSubmittedPayload { /** ISO 8601 */ pickupAt: string; totalPrice: number; + /** ISO 8601. 확정 마감이 없던 옛 이벤트는 null */ + confirmDeadlineAt: string | null; } export function orderSubmittedEvent(args: { @@ -32,7 +34,9 @@ export function orderSubmittedEvent(args: { quantity: number; pickupAt: Date; totalPrice: number; + confirmDeadlineAt: Date; occurredAt: Date; + actorAccountId: bigint | null; }): OutboxEventInput { const payload: OrderSubmittedPayload = { orderId: args.orderId.toString(), @@ -45,6 +49,7 @@ export function orderSubmittedEvent(args: { quantity: args.quantity, pickupAt: args.pickupAt.toISOString(), totalPrice: args.totalPrice, + confirmDeadlineAt: args.confirmDeadlineAt.toISOString(), }; return { aggregateType: 'order', @@ -52,7 +57,7 @@ export function orderSubmittedEvent(args: { eventType: ORDER_SUBMITTED, payload: { ...payload }, occurredAt: args.occurredAt, - actorAccountId: args.buyerAccountId, + actorAccountId: args.actorAccountId, }; } @@ -90,5 +95,10 @@ export function parseOrderSubmittedPayload( quantity: p.quantity as number, pickupAt: p.pickupAt, totalPrice: p.totalPrice as number, + confirmDeadlineAt: + typeof p.confirmDeadlineAt === 'string' && + !Number.isNaN(Date.parse(p.confirmDeadlineAt)) + ? p.confirmDeadlineAt + : null, }; } diff --git a/src/features/order/order-admin.graphql b/src/features/order/order-admin.graphql index 7e4f11bd..65888191 100644 --- a/src/features/order/order-admin.graphql +++ b/src/features/order/order-admin.graphql @@ -158,6 +158,10 @@ type AdminOrderDetail { """ requestNote: String """ + 결제와 입금 확인 기록. 결제 도입 전 주문이면 null. + """ + payment: AdminOrderPayment + """ 할인 전 품목 합계(원). """ subtotalPrice: Int! diff --git a/src/features/order/order-checkout.graphql b/src/features/order/order-checkout.graphql index 2ab60063..6e799e08 100644 --- a/src/features/order/order-checkout.graphql +++ b/src/features/order/order-checkout.graphql @@ -1,5 +1,11 @@ extend type Mutation { - """주문 생성(구매자). 옵션·픽업 일시를 서버가 재검증하고 가격을 스냅샷한다. 로그인 필수.""" + """ + 주문 생성(구매자). 옵션·픽업 일시를 서버가 재검증하고 가격을 스냅샷한 뒤 입금 대기(PENDING_PAYMENT) 주문을 만든다. + 결과의 payment로 입금을 안내하고, 1시간 안에 입금이 확인되지 않으면 자동 취소된다. 판매자에게는 입금 확인 뒤에 보인다. + 입금 계좌가 설정되지 않았으면 PAYMENT_ACCOUNT_NOT_CONFIGURED(SERVICE_UNAVAILABLE), 입금 대기 주문이 이미 2건이면 + PENDING_PAYMENT_LIMIT_EXCEEDED(CONFLICT), 같은 계정의 다른 주문 요청이 처리 중이라 3초 안에 차례가 오지 않으면 + CONCURRENT_REQUEST(CONFLICT)다. 로그인 필수. + """ createOrder(input: CreateOrderInput!): CreateOrderOutput! } @@ -23,6 +29,11 @@ input CreateOrderInput { """미입력 시 프로필 전화번호 사용. 둘 다 없으면 거절.""" buyerPhone: String """ + 입금자명(1~20자). 생략하거나 공백만 보내면 주문자 이름을 쓴다. 입력값이든 주문자 이름이든 20자를 넘으면 + DEPOSITOR_NAME_INVALID로 거절한다(은행 입금자명과 대조하는 값이라 자르지 않는다). + """ + depositorName: String + """ 화면에 보여 준 최종 결제 금액(원). 서버가 다시 계산한 금액과 다르면 ORDER_PRICE_CHANGED로 거절한다. """ expectedTotalPrice: Int! @@ -36,12 +47,14 @@ 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 } diff --git a/src/features/order/order-deposit-admin.graphql b/src/features/order/order-deposit-admin.graphql new file mode 100644 index 00000000..23f41fea --- /dev/null +++ b/src/features/order/order-deposit-admin.graphql @@ -0,0 +1,208 @@ +extend type Query { + """ + 입금 확인을 기다리는 주문(입금 대기 + 결제 대기) 목록. claimedOnly면 '입금했어요'를 누른 시각, 아니면 주문 생성 순으로 + 오래된 것부터 온다. 기한이 지났지만 아직 자동 취소되지 않은 주문도 포함한다. 관리자 로그인 필수. ADMIN 계정이 아니면 FORBIDDEN. + """ + adminPendingPayments( + input: AdminPendingPaymentListInput + ): AdminPendingPaymentConnection! + """ + 처리 대기 건수(배지용). 관리자 로그인 필수. ADMIN 계정이 아니면 FORBIDDEN. + """ + adminTaskCounts: AdminTaskCounts! +} + +extend type Mutation { + """ + 은행 앱에서 확인한 입금으로 주문을 접수(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. + """ + adminConfirmPayment(input: AdminConfirmPaymentInput!): AdminOrderSummary! +} + +""" +입금 확인 대기 목록 조회 조건. 모든 필터는 AND로 결합된다. +""" +input AdminPendingPaymentListInput { + """ + 한 번에 가져올 개수. 기본 20, 1~100만 허용하며 벗어나면 BAD_USER_INPUT. + """ + limit: Int = 20 + """ + 이전 응답의 nextCursor. 첫 페이지는 생략한다. claimedOnly를 바꾸면 커서를 버리고 첫 페이지부터 다시 조회한다. + """ + cursor: String + """ + true면 구매자가 '입금했어요'를 누른 주문만. 기본 false, null도 false(전체)로 본다. + """ + claimedOnly: Boolean = false + """ + 결제 금액(원) 일치 필터. 은행 앱에서 본 입금액으로 주문을 찾는다. null이면 전체. + """ + amount: Int + """ + 입금자명 부분일치 필터(최대 50자). 공백만 보내거나 null이면 전체. + """ + depositorName: String +} + +""" +입금 확인 대기 주문 1건. +""" +type AdminPendingPayment { + orderId: ID! + """ + 주문번호. + """ + orderNumber: String! + """ + 매장명(주문 시점 스냅샷). 품목이 없으면 null. + """ + storeName: String + """ + 상품명(주문 시점 스냅샷). 품목이 없으면 null. + """ + productName: String + """ + 입금할 금액(원). + """ + amount: Int! + """ + 입금자명. + """ + depositorName: 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! +} + +""" +입금 확인 입력. +""" +input AdminConfirmPaymentInput { + orderId: ID! + """ + 은행 앱에서 본 입금액(원, 1 이상 정수). 결제 금액과 같아야 확인된다. + """ + 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 +} diff --git a/src/features/order/order-my.graphql b/src/features/order/order-my.graphql index 9f495868..85c418bb 100644 --- a/src/features/order/order-my.graphql +++ b/src/features/order/order-my.graphql @@ -9,6 +9,15 @@ extend type Query { myOrder(orderId: ID!): MyOrderDetail! } +extend type Mutation { + """ + '입금했어요'. 입금 기한 전에 누르면 미입금 자동 취소에서 빠지고 관리자에게 확인 요청이 간다(입금이 없으면 관리자가 취소한다). + 이미 눌렀으면 아무것도 바꾸지 않고 그대로 돌려준다. 입금 대기가 아니면(확인·취소됨) PAYMENT_NOT_PENDING(CONFLICT), + 기한이 지났으면 PAYMENT_DEADLINE_PASSED(BAD_USER_INPUT). 로그인 필수. 본인 주문이 아니면 NOT_FOUND. + """ + markMyOrderDepositSent(orderId: ID!): MyOrderDetail! +} + """ 내 주문 조회 입력 """ @@ -99,6 +108,10 @@ type MyOrderSummary { 주문 내 OrderItem 중 리뷰 작성 가능한 것이 1건이라도 있는지 (PICKED_UP + 활성 리뷰 미존재) """ hasReviewableItem: Boolean! + """ + 입금 기한. 입금을 기다리는 주문(결제 대기)만 값이 있고 그 밖은 null. + """ + paymentExpiresAt: DateTime } """ @@ -135,6 +148,10 @@ type MyOrderDetail { 구매자가 남긴 요청 사항. 없으면 null. """ requestNote: String + """ + 결제(입금 안내·진행 상태). 결제 도입 전 주문이면 null. + """ + payment: OrderPayment """ 할인 전 품목 합계(원). diff --git a/src/features/order/order-payment.graphql b/src/features/order/order-payment.graphql index fcc9073a..ba9aa8b7 100644 --- a/src/features/order/order-payment.graphql +++ b/src/features/order/order-payment.graphql @@ -19,3 +19,85 @@ type Bank { """ 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 +} diff --git a/src/features/order/order-seller.graphql b/src/features/order/order-seller.graphql index 6e055b3d..37818e26 100644 --- a/src/features/order/order-seller.graphql +++ b/src/features/order/order-seller.graphql @@ -159,6 +159,10 @@ type SellerOrderDetail { """ requestNote: String """ + 결제 수단. 결제 도입 전 주문이면 null. 값은 늘어날 수 있으니 모르는 값은 '기타'로 보여 준다. + """ + paymentMethod: PaymentMethodType + """ 할인 전 품목 합계(원). """ subtotalPrice: Int! diff --git a/src/features/order/order-subscription.graphql b/src/features/order/order-subscription.graphql index 8759b9c5..6059c540 100644 --- a/src/features/order/order-subscription.graphql +++ b/src/features/order/order-subscription.graphql @@ -3,7 +3,7 @@ extend type Subscription { 내 매장 주문 생성·상태 변경 이벤트. 판매자 로그인 필수(SELLER 아니면 FORBIDDEN). 삭제되지 않은 매장을 보유한 판매자만 구독할 수 있다 — 매장이 없거나 삭제됐으면 NOT_FOUND. 비활성(is_active=false) 매장도 구독은 유지된다. 인증은 graphql-ws connectionParams.authorization. - 구매자 주문 생성(SUBMITTED)·판매자 상태 변경·관리자 강제 취소가 모두 여기로 온다. 입금 확인 전 주문의 취소는 오지 않는다. + 입금 확인(새 주문)·판매자 상태 변경·관리자 강제 취소가 모두 여기로 온다. 입금 확인 전 주문(생성·취소)은 오지 않는다. """ sellerOrderUpdated: SellerOrderUpdate! } @@ -14,6 +14,10 @@ extend type Subscription { 전달 누락 가능(Redis 장애 시 발행 생략)하므로 폴백은 sellerOrderList 재조회다. """ type SellerOrderUpdate { + """ + 갱신 종류. 새 주문 알림은 SUBMITTED일 때만 띄운다. + """ + kind: SellerOrderUpdateKind! orderId: ID! """주문번호.""" orderNumber: String! @@ -30,3 +34,15 @@ type SellerOrderUpdate { """주문 행의 updated_at. 폐기 규칙의 비교 키다.""" updatedAt: DateTime! } + +""" +판매자 주문 갱신 종류. 값은 늘어날 수 있으니 모르는 값은 목록 재조회로 처리한다. +""" +enum SellerOrderUpdateKind { + """입금이 확인돼 새 주문이 접수됐다.""" + SUBMITTED + """주문 상태가 바뀌었다(확정·제작 완료·픽업 완료·취소 등).""" + STATUS_CHANGED + """픽업 일시가 바뀌었다.""" + PICKUP_RESCHEDULED +} diff --git a/src/features/order/order.module.ts b/src/features/order/order.module.ts index 93370974..9ec8a5ee 100644 --- a/src/features/order/order.module.ts +++ b/src/features/order/order.module.ts @@ -6,12 +6,17 @@ import { AuthModule } from '@/features/auth'; import { OrderStatusTransitionPolicy } from '@/features/order/policies/order-status-transition.policy'; import { OrderBookedRepository } from '@/features/order/repositories/order-booked.repository'; import { OrderStoreDailyLimitRepository } from '@/features/order/repositories/order-store-daily-limit.repository'; +import { OrderTransitionRepository } from '@/features/order/repositories/order-transition.repository'; import { OrderRepository } from '@/features/order/repositories/order.repository'; import { PaymentSettingRepository } from '@/features/order/repositories/payment-setting.repository'; +import { PaymentRepository } from '@/features/order/repositories/payment.repository'; import { StoreSettlementAccountRepository } from '@/features/order/repositories/store-settlement-account.repository'; import { AdminOrderMutationResolver } from '@/features/order/resolvers/order-admin-mutation.resolver'; import { AdminOrderQueryResolver } from '@/features/order/resolvers/order-admin-query.resolver'; import { OrderCheckoutMutationResolver } from '@/features/order/resolvers/order-checkout-mutation.resolver'; +import { AdminDepositMutationResolver } from '@/features/order/resolvers/order-deposit-admin-mutation.resolver'; +import { AdminDepositQueryResolver } from '@/features/order/resolvers/order-deposit-admin-query.resolver'; +import { UserOrderMutationResolver } from '@/features/order/resolvers/order-my-mutation.resolver'; import { UserOrderQueryResolver } from '@/features/order/resolvers/order-my-query.resolver'; import { AdminPaymentMutationResolver } from '@/features/order/resolvers/order-payment-admin-mutation.resolver'; import { AdminPaymentQueryResolver } from '@/features/order/resolvers/order-payment-admin-query.resolver'; @@ -23,6 +28,7 @@ import { SellerSettlementQueryResolver } from '@/features/order/resolvers/order- import { OrderSubscriptionResolver } from '@/features/order/resolvers/order-subscription.resolver'; import { AdminOrderService } from '@/features/order/services/order-admin.service'; import { OrderCheckoutService } from '@/features/order/services/order-checkout.service'; +import { AdminDepositService } from '@/features/order/services/order-deposit-admin.service'; import { OrderEventsService } from '@/features/order/services/order-events.service'; import { UserOrderService } from '@/features/order/services/order-my.service'; import { AdminPaymentService } from '@/features/order/services/order-payment-admin.service'; @@ -52,7 +58,7 @@ import { StoreModule } from '@/features/store'; OrderStoreDailyLimitRepository, OrderStoreDailyLimitConsumer, OrderStatusTransitionPolicy, - // 판매자 주문 구독(Redis PubSub) — 발행은 체크아웃·판매자 상태 변경·관리자 취소 서비스가 커밋 뒤 직접 + // 판매자 주문 구독(Redis PubSub) — 발행은 입금 확인·판매자 상태 변경·관리자 취소 서비스가 커밋 뒤 직접 OrderEventsService, OrderSubscriptionService, OrderSubscriptionResolver, @@ -66,9 +72,16 @@ import { StoreModule } from '@/features/store'; AdminOrderService, AdminOrderQueryResolver, AdminOrderMutationResolver, - // 구매자 주문 목록·상세 + // 구매자 주문 목록·상세·'입금했어요' UserOrderService, UserOrderQueryResolver, + UserOrderMutationResolver, + // 결제(입금 대기)와 상태 전이 잠금 단위, 관리자 입금 확인 + PaymentRepository, + OrderTransitionRepository, + AdminDepositService, + AdminDepositQueryResolver, + AdminDepositMutationResolver, // 결제 설정·매장 정산 계좌(계좌번호는 global AccountCipher로 암호화) PaymentSettingRepository, StoreSettlementAccountRepository, diff --git a/src/features/order/policies/payment-confirm.policy.spec.ts b/src/features/order/policies/payment-confirm.policy.spec.ts new file mode 100644 index 00000000..b3ba0823 --- /dev/null +++ b/src/features/order/policies/payment-confirm.policy.spec.ts @@ -0,0 +1,68 @@ +import { assertPaymentConfirmable } from '@/features/order/policies/payment-confirm.policy'; +import type { PaymentConfirmState } from '@/features/order/repositories/order-transition.repository'; +import { + OrderStatus, + PaymentStatus, + type OrderStatus as OrderStatusType, +} from '@/generated/prisma/client'; + +const NOW = new Date('2026-09-16T07:00:00.000Z'); +const OK: PaymentConfirmState = { + orderStatus: OrderStatus.PENDING_PAYMENT, + paymentStatus: PaymentStatus.PENDING, + paymentAmount: 30_000, + pickupAt: new Date(NOW.getTime() + 1), +}; + +describe('assertPaymentConfirmable', () => { + it('입금 대기·결제 대기·픽업 전·금액 일치면 통과한다', () => { + expect(() => assertPaymentConfirmable(OK, 30_000, NOW)).not.toThrow(); + }); + + // 주문 상태 전수 — 입금 대기 밖은 모두 409 + it.each( + (Object.values(OrderStatus) as OrderStatusType[]).filter( + (status) => status !== OrderStatus.PENDING_PAYMENT, + ), + )('주문 %s는 PAYMENT_NOT_PENDING이다', (orderStatus) => { + expect(() => + assertPaymentConfirmable({ ...OK, orderStatus }, 30_000, NOW), + ).toThrowDomain('PAYMENT_NOT_PENDING'); + }); + + it.each([PaymentStatus.CONFIRMED, PaymentStatus.CANCELED, null])( + '결제 %s는 PAYMENT_NOT_PENDING이다', + (paymentStatus) => { + expect(() => + assertPaymentConfirmable({ ...OK, paymentStatus }, 30_000, NOW), + ).toThrowDomain('PAYMENT_NOT_PENDING'); + }, + ); + + it('상태가 틀리면 픽업·금액보다 먼저 409다', () => { + expect(() => + assertPaymentConfirmable( + { ...OK, orderStatus: OrderStatus.CANCELED, pickupAt: NOW }, + 1, + NOW, + ), + ).toThrowDomain('PAYMENT_NOT_PENDING'); + }); + + it('픽업 시각이 지금이거나 지났으면 금액과 무관하게 PAYMENT_PICKUP_PASSED다', () => { + for (const pickupAt of [NOW, new Date(NOW.getTime() - 1)]) { + expect(() => + assertPaymentConfirmable({ ...OK, pickupAt }, 1, NOW), + ).toThrowDomain('PAYMENT_PICKUP_PASSED'); + } + }); + + it.each([29_999, 30_001])( + '입금액 %s(결제 30000)는 DEPOSIT_AMOUNT_MISMATCH다', + (deposited) => { + expect(() => assertPaymentConfirmable(OK, deposited, NOW)).toThrowDomain( + 'DEPOSIT_AMOUNT_MISMATCH', + ); + }, + ); +}); diff --git a/src/features/order/policies/payment-confirm.policy.ts b/src/features/order/policies/payment-confirm.policy.ts new file mode 100644 index 00000000..06b3dc8a --- /dev/null +++ b/src/features/order/policies/payment-confirm.policy.ts @@ -0,0 +1,26 @@ +import { DomainException } from '@/common/errors/error-catalog'; +import type { PaymentConfirmState } from '@/features/order/repositories/order-transition.repository'; +import { OrderStatus, PaymentStatus } from '@/generated/prisma/client'; + +/** + * 입금 확인 가능 판정. 픽업이 지난 주문은 확인하면 곧바로 확정 마감이 지나 접수·취소 알림이 연달아 가므로 막고, + * 금액이 틀린 입금은 반환 대상으로 돌린다. + */ +export function assertPaymentConfirmable( + state: PaymentConfirmState, + depositedAmount: number, + now: Date, +): void { + if ( + state.orderStatus !== OrderStatus.PENDING_PAYMENT || + state.paymentStatus !== PaymentStatus.PENDING + ) { + throw new DomainException('PAYMENT_NOT_PENDING'); + } + if (state.pickupAt <= now) { + throw new DomainException('PAYMENT_PICKUP_PASSED'); + } + if (depositedAmount !== state.paymentAmount) { + throw new DomainException('DEPOSIT_AMOUNT_MISMATCH'); + } +} diff --git a/src/features/order/repositories/order-pending-payment-lock.helper.ts b/src/features/order/repositories/order-pending-payment-lock.helper.ts new file mode 100644 index 00000000..c6addb1f --- /dev/null +++ b/src/features/order/repositories/order-pending-payment-lock.helper.ts @@ -0,0 +1,48 @@ +import { OrderStatus, type Prisma } from '@/generated/prisma/client'; + +/** 계정당 동시 입금 대기 주문 상한. */ +export const PENDING_PAYMENT_LIMIT = 2; +/** tx timeout(10초)보다 짧아야 대기 중 tx가 먼저 끊기지 않는다. */ +const LOCK_WAIT_SECONDS = 3; + +function lockName(accountId: bigint): string { + return `pending-payment:${accountId}`; +} + +/** + * 같은 계정의 주문 생성을 직렬화한다. GET_LOCK은 연결(세션) 단위라 tx 콜백 안에서 잡고 같은 콜백의 finally에서 푼다 — + * 커밋 뒤에는 같은 연결로 문장을 보낼 수 없어, 밖에서 풀거나 해제를 빼면 풀 연결에 잠금이 남는다. + * 0(시간 초과)·NULL(오류)이면 'lock-timeout'. + */ +export async function withPendingPaymentLock( + tx: Prisma.TransactionClient, + accountId: bigint, + fn: () => Promise, +): Promise { + const name = lockName(accountId); + const [row] = await tx.$queryRaw<{ acquired: unknown }[]>` + SELECT GET_LOCK(${name}, ${LOCK_WAIT_SECONDS}) AS acquired`; + if (Number(row.acquired) !== 1) return 'lock-timeout'; + try { + return await fn(); + } finally { + await tx.$queryRaw`SELECT RELEASE_LOCK(${name})`; + } +} + +/** + * 잠금 읽기로 센다 — 앞 요청의 미커밋 INSERT 행에서 기다렸다가 커밋된 값을 보므로, + * 커밋 직전에 GET_LOCK이 풀려도 3건째가 생기지 않는다. + */ +export async function countPendingPaymentOrdersLocked( + tx: Prisma.TransactionClient, + accountId: bigint, +): Promise { + const [row] = await tx.$queryRaw<{ n: bigint }[]>` + SELECT COUNT(*) AS n FROM \`order\` + WHERE account_id = ${accountId} + AND status = ${OrderStatus.PENDING_PAYMENT} + AND deleted_at IS NULL + FOR SHARE`; + return Number(row.n); +} diff --git a/src/features/order/repositories/order-transition.repository.spec.ts b/src/features/order/repositories/order-transition.repository.spec.ts new file mode 100644 index 00000000..5a5874ef --- /dev/null +++ b/src/features/order/repositories/order-transition.repository.spec.ts @@ -0,0 +1,132 @@ +import { AUDIT_LOG_REPOSITORY } from '@/features/audit-log'; +import { AuditLogRepository } from '@/features/audit-log/repositories/audit-log.repository'; +import { ORDER_STATUS_CHANGED } from '@/features/order/events/order-status-changed.event'; +import { + OrderTransitionRepository, + type ConfirmPaymentArgs, +} from '@/features/order/repositories/order-transition.repository'; +import type { PrismaClient } from '@/generated/prisma/client'; +import { disconnectTestPrismaClient } from '@/test/db/prisma-test-client'; +import { closeTruncateConnection, truncateAll } from '@/test/db/truncate'; +import { createAccount, createOrder, createPayment } from '@/test/factories'; +import { createTestingModuleWithRealDb } from '@/test/modules/testing-module.builder'; +import { outboxPublisherProviders } from '@/test/outbox'; + +const NOW = new Date('2026-09-16T07:00:00.000Z'); + +describe('OrderTransitionRepository (real DB)', () => { + let repo: OrderTransitionRepository; + let prisma: PrismaClient; + + beforeAll(async () => { + const { module, prisma: p } = await createTestingModuleWithRealDb({ + providers: [ + OrderTransitionRepository, + { provide: AUDIT_LOG_REPOSITORY, useClass: AuditLogRepository }, + ...outboxPublisherProviders(), + ], + }); + repo = module.get(OrderTransitionRepository); + prisma = p; + }); + + afterAll(async () => { + await closeTruncateConnection(); + await disconnectTestPrismaClient(); + }); + + beforeEach(async () => { + await truncateAll(); + }); + + async function confirmArgs( + orderId: bigint, + overrides: Partial = {}, + ): Promise { + const actor = await createAccount(prisma, { account_type: 'ADMIN' }); + return { + orderId, + source: 'ADMIN', + actorAccountId: actor.id, + actorLabel: null, + depositedAmount: 10_000, + note: null, + now: NOW, + assertConfirmable: () => undefined, + ...overrides, + }; + } + + describe('confirmPayment', () => { + it('품목이 없는 주문은 매장을 알 수 없어 판매자 새 주문 이벤트 없이 접수한다', async () => { + const order = await createOrder(prisma, { + status: 'PENDING_PAYMENT', + pickup_at: new Date(NOW.getTime() + 48 * 60 * 60_000), + }); + await createPayment(prisma, { order_id: order.id }); + + const updated = await repo.confirmPayment(await confirmArgs(order.id)); + + expect(updated).toMatchObject({ status: 'SUBMITTED', items: [] }); + const events = await prisma.outbox.findMany(); + expect(events.map((e) => e.event_type)).toEqual([ORDER_STATUS_CHANGED]); + await expect( + prisma.auditLog.findFirstOrThrow({ where: { target_id: order.id } }), + ).resolves.toMatchObject({ store_id: null }); + }); + + it('자동 매칭(AUTO) 확인은 이력 주체를 SYSTEM으로 남긴다', async () => { + const order = await createOrder(prisma, { + status: 'PENDING_PAYMENT', + pickup_at: new Date(NOW.getTime() + 48 * 60 * 60_000), + }); + await createPayment(prisma, { order_id: order.id }); + + await repo.confirmPayment( + await confirmArgs(order.id, { source: 'AUTO' }), + ); + + await expect( + prisma.orderStatusHistory.findFirstOrThrow({ + where: { order_id: order.id }, + }), + ).resolves.toMatchObject({ actor_type: 'SYSTEM' }); + await expect( + prisma.payment.findUniqueOrThrow({ where: { order_id: order.id } }), + ).resolves.toMatchObject({ confirm_source: 'AUTO' }); + }); + + it('잠금 뒤 판정이 던지면 롤백되어 아무것도 남지 않는다', async () => { + const order = await createOrder(prisma, { status: 'PENDING_PAYMENT' }); + await createPayment(prisma, { order_id: order.id }); + const seen: unknown[] = []; + + await expect( + repo.confirmPayment( + await confirmArgs(order.id, { + assertConfirmable: (state) => { + seen.push(state); + throw new Error('거절'); + }, + }), + ), + ).rejects.toThrow('거절'); + + expect(seen).toEqual([ + { + orderStatus: 'PENDING_PAYMENT', + paymentStatus: 'PENDING', + paymentAmount: order.total_price, + pickupAt: order.pickup_at, + }, + ]); + await expect( + prisma.order.findUniqueOrThrow({ where: { id: order.id } }), + ).resolves.toMatchObject({ + status: 'PENDING_PAYMENT', + submitted_at: null, + }); + expect(await prisma.outbox.count()).toBe(0); + }); + }); +}); diff --git a/src/features/order/repositories/order-transition.repository.ts b/src/features/order/repositories/order-transition.repository.ts new file mode 100644 index 00000000..5c42658d --- /dev/null +++ b/src/features/order/repositories/order-transition.repository.ts @@ -0,0 +1,200 @@ +import { Inject, Injectable } from '@nestjs/common'; + +import { DAY_MS } from '@/common/utils/kst-time'; +import { + AUDIT_LOG_REPOSITORY, + type IAuditLogRepository, +} from '@/features/audit-log'; +import { orderStatusChangedEvent } from '@/features/order/events/order-status-changed.event'; +import { orderSubmittedEvent } from '@/features/order/events/order-submitted.event'; +import { + adminOrderInclude, + type AdminOrderRow, +} from '@/features/order/repositories/order.repository'; +import { OutboxPublisher } from '@/features/outbox'; +import { + AuditActionType, + AuditTargetType, + OrderActor, + OrderStatus, + PaymentConfirmSource, + PaymentStatus, + type Prisma, +} from '@/generated/prisma/client'; +import { activeWhere, PrismaService } from '@/prisma'; + +/** 잠금 시점의 입금 확인 판정 재료. */ +export interface PaymentConfirmState { + orderStatus: OrderStatus; + paymentStatus: PaymentStatus | null; + paymentAmount: number | null; + pickupAt: Date; +} + +export interface ConfirmPaymentArgs { + orderId: bigint; + source: PaymentConfirmSource; + actorAccountId: bigint; + actorLabel: string | null; + depositedAmount: number; + note: string | null; + now: Date; + /** 잠금 뒤 상태로 다시 판정한다. 던지면 tx가 롤백되고 예외가 그대로 나간다. */ + assertConfirmable: (state: PaymentConfirmState) => void; +} + +/** 접수 뒤 판매자 확정 마감: 확인 + 24시간과 픽업 시각 중 이른 쪽. */ +const CONFIRM_WINDOW_MS = DAY_MS; + +/** 주문 상태 전이 잠금 단위. 잠금 순서는 order → payment. */ +@Injectable() +export class OrderTransitionRepository { + constructor( + private readonly prisma: PrismaService, + private readonly outbox: OutboxPublisher, + @Inject(AUDIT_LOG_REPOSITORY) + private readonly auditLogs: IAuditLogRepository, + ) {} + + /** 없는 주문이면 null. */ + async confirmPayment( + args: ConfirmPaymentArgs, + ): Promise { + return this.prisma.$transaction((tx) => + this.confirmPaymentLocked(tx, args), + ); + } + + /** + * 입금 확인 → 접수. 결제 CONFIRMED, 주문 SUBMITTED(submitted_at으로 판매자에게 보이기 시작), 이력·감사(입금액 포함)· + * outbox(order.status_changed + 판매자 '새 주문' order.submitted)를 같은 tx에 남긴다. + */ + async confirmPaymentLocked( + tx: Prisma.TransactionClient, + args: ConfirmPaymentArgs, + ): Promise { + const [locked] = await tx.$queryRaw<{ id: bigint }[]>` + SELECT id FROM \`order\` + WHERE id = ${args.orderId} AND deleted_at IS NULL + FOR UPDATE`; + if (!locked) return null; + await tx.$queryRaw`SELECT id FROM payment WHERE order_id = ${locked.id} FOR UPDATE`; + const order = await tx.order.findUniqueOrThrow({ + where: { id: locked.id }, + select: { status: true, pickup_at: true, payment: true }, + }); + args.assertConfirmable({ + orderStatus: order.status, + paymentStatus: order.payment?.status ?? null, + paymentAmount: order.payment?.amount ?? null, + pickupAt: order.pickup_at, + }); + const payment = order.payment!; + const confirmDeadlineAt = new Date( + Math.min( + args.now.getTime() + CONFIRM_WINDOW_MS, + order.pickup_at.getTime(), + ), + ); + const actorType = + args.source === PaymentConfirmSource.ADMIN + ? OrderActor.ADMIN + : OrderActor.SYSTEM; + + await tx.payment.update({ + where: { id: payment.id }, + data: { + status: PaymentStatus.CONFIRMED, + confirmed_at: args.now, + confirm_source: args.source, + confirmed_by_account_id: args.actorAccountId, + confirmed_by_label_snapshot: args.actorLabel, + confirm_note: args.note, + }, + }); + const updated = await tx.order.update({ + where: { id: locked.id }, + data: { + status: OrderStatus.SUBMITTED, + submitted_at: args.now, + confirm_deadline_at: confirmDeadlineAt, + }, + include: adminOrderInclude, + }); + await tx.orderStatusHistory.create({ + data: { + order_id: locked.id, + from_status: OrderStatus.PENDING_PAYMENT, + to_status: OrderStatus.SUBMITTED, + changed_at: args.now, + actor_type: actorType, + actor_account_id: args.actorAccountId, + }, + }); + + const firstItem = await tx.orderItem.findFirst({ + where: { order_id: locked.id, ...activeWhere }, + orderBy: { id: 'asc' }, + select: { + store_id: true, + product_id: true, + product_name_snapshot: true, + store_name_snapshot: true, + quantity: true, + }, + }); + await this.outbox.publish( + tx, + orderStatusChangedEvent({ + orderId: locked.id, + orderNumber: updated.order_number, + buyerAccountId: updated.account_id, + fromStatus: OrderStatus.PENDING_PAYMENT, + toStatus: OrderStatus.SUBMITTED, + storeId: firstItem?.store_id ?? null, + storeName: firstItem?.store_name_snapshot ?? null, + productId: firstItem?.product_id ?? null, + productName: firstItem?.product_name_snapshot ?? null, + occurredAt: args.now, + actorAccountId: args.actorAccountId, + }), + ); + if (firstItem) { + await this.outbox.publish( + tx, + orderSubmittedEvent({ + orderId: locked.id, + orderNumber: updated.order_number, + buyerAccountId: updated.account_id, + storeId: firstItem.store_id, + storeName: firstItem.store_name_snapshot, + productId: firstItem.product_id, + productName: firstItem.product_name_snapshot, + quantity: firstItem.quantity, + pickupAt: updated.pickup_at, + totalPrice: updated.total_price, + confirmDeadlineAt, + occurredAt: args.now, + actorAccountId: args.actorAccountId, + }), + ); + } + + await this.auditLogs.recordAudit(tx, { + actorAccountId: args.actorAccountId, + storeId: firstItem?.store_id ?? null, + targetType: AuditTargetType.ORDER, + targetId: locked.id, + action: AuditActionType.STATUS_CHANGE, + beforeJson: { status: OrderStatus.PENDING_PAYMENT }, + afterJson: { + status: OrderStatus.SUBMITTED, + paymentAmount: payment.amount, + depositedAmount: args.depositedAmount, + confirmSource: args.source, + note: args.note, + }, + }); + return updated; + } +} diff --git a/src/features/order/repositories/order.repository.spec.ts b/src/features/order/repositories/order.repository.spec.ts index 1bc90036..6a91f873 100644 --- a/src/features/order/repositories/order.repository.spec.ts +++ b/src/features/order/repositories/order.repository.spec.ts @@ -4,11 +4,7 @@ import { NotificationAdminRepository } from '@/features/notification/repositorie import { NotificationRepository } from '@/features/notification/repositories/notification.repository'; import { NotificationOutboxConsumer } from '@/features/notification/services/notification-outbox.consumer'; import { - ORDER_SUBMITTED, - parseOrderSubmittedPayload, -} from '@/features/order/events/order-submitted.event'; -import { - type CreateSubmittedOrderArgs, + type CreatePendingPaymentOrderArgs, type DailyCapacityGuard, OrderRepository, } from '@/features/order/repositories/order.repository'; @@ -935,18 +931,19 @@ describe('OrderRepository (real DB)', () => { }); }); - describe('createSubmittedOrder', () => { + describe('createPendingPaymentOrder', () => { const PICKUP_AT = new Date('2026-09-18T05:00:00.000Z'); - const SUBMITTED_AT = new Date('2026-09-16T07:00:00.000Z'); + const NOW = new Date('2026-09-16T07:00:00.000Z'); + const EXPIRES_AT = new Date('2026-09-16T08:00:00.000Z'); - function submitArgs(args: { + function createArgs(args: { buyerId: bigint; store: { id: bigint; store_name: string }; product: { id: bigint; name: string }; orderNumber?: string; quantity?: number; capacityGuard?: DailyCapacityGuard; - }): CreateSubmittedOrderArgs { + }): CreatePendingPaymentOrderArgs { const quantity = args.quantity ?? 2; return { accountId: args.buyerId, @@ -960,8 +957,16 @@ describe('OrderRepository (real DB)', () => { subtotalPrice: 30000 * quantity, discountPrice: 5000 * quantity, totalPrice: 25000 * quantity, - submittedAt: SUBMITTED_AT, + commissionRateBps: 550, + now: NOW, capacityGuard: args.capacityGuard ?? null, + payment: { + depositorName: '차차맘', + depositBankCode: '004', + depositAccountNumber: '12345678901234', + depositAccountHolder: '케이퀵', + expiresAt: EXPIRES_AT, + }, item: { storeId: args.store.id, productId: args.product.id, @@ -978,7 +983,7 @@ describe('OrderRepository (real DB)', () => { }; } - it('접수 이벤트(order.submitted)를 같은 tx에 1건 남기고 payload는 생성 시점 스냅샷이다', async () => { + it('입금 대기 주문·결제(계좌 스냅샷)·이력을 같은 tx에 남기고 판매자 새 주문 이벤트는 없다', async () => { const buyer = await setupBuyer(); const store = await createStore(prisma, { store_name: '해즈 케이크' }); const product = await createProduct(prisma, { @@ -986,45 +991,47 @@ describe('OrderRepository (real DB)', () => { name: '딸기 케이크', }); - const created = await repo.createSubmittedOrder( - submitArgs({ buyerId: buyer.id, store, product }), + const created = await repo.createPendingPaymentOrder( + createArgs({ buyerId: buyer.id, store, product }), ); + if (typeof created === 'string') throw new Error(created); - const history = await prisma.orderStatusHistory.findFirstOrThrow({ - where: { order_id: created!.id }, + const order = await prisma.order.findUniqueOrThrow({ + where: { id: created.id }, + include: { payment: true, status_histories: true }, }); - expect(history).toMatchObject({ - from_status: null, - to_status: 'SUBMITTED', - actor_type: 'BUYER', - actor_account_id: buyer.id, + expect(order).toMatchObject({ + status: 'PENDING_PAYMENT', + submitted_at: null, + commission_rate_bps: 550, + total_price: 50000, }); - - const events = await prisma.outbox.findMany(); - expect(events).toHaveLength(1); - expect(events[0]).toMatchObject({ - aggregate_type: 'order', - aggregate_id: created!.id.toString(), - event_type: ORDER_SUBMITTED, - occurred_at: SUBMITTED_AT, - actor_account_id: buyer.id, + expect(order.payment).toMatchObject({ + method: 'BANK_TRANSFER', status: 'PENDING', - }); - expect(parseOrderSubmittedPayload(events[0].payload_json)).toEqual({ - orderId: created!.id.toString(), - orderNumber: 'ORD-20260916-ABC234', - buyerAccountId: buyer.id.toString(), - storeId: store.id.toString(), - storeName: '해즈 케이크', - productId: product.id.toString(), - productName: '딸기 케이크', - quantity: 2, - pickupAt: PICKUP_AT.toISOString(), - totalPrice: 50000, - }); + amount: 50000, + depositor_name: '차차맘', + deposit_bank_code: '004', + deposit_account_number: '12345678901234', + deposit_account_holder: '케이퀵', + expires_at: EXPIRES_AT, + buyer_claimed_at: null, + confirmed_at: null, + }); + expect(order.status_histories).toEqual([ + expect.objectContaining({ + from_status: null, + to_status: 'PENDING_PAYMENT', + actor_type: 'BUYER', + actor_account_id: buyer.id, + changed_at: NOW, + }), + ]); + expect(created.payment).toMatchObject({ amount: 50000 }); + expect(await prisma.outbox.count()).toBe(0); }); - it('반증: capacity 재검사에서 거절되면 주문도 이벤트도 남지 않는다', async () => { + it('반증: capacity 재검사에서 거절되면 주문도 결제도 남지 않는다', async () => { const buyer = await setupBuyer(); const store = await createStore(prisma); const product = await createProduct(prisma, { store_id: store.id }); @@ -1034,8 +1041,8 @@ describe('OrderRepository (real DB)', () => { capacity: 1, }); - const created = await repo.createSubmittedOrder( - submitArgs({ + const created = await repo.createPendingPaymentOrder( + createArgs({ buyerId: buyer.id, store, product, @@ -1049,20 +1056,20 @@ describe('OrderRepository (real DB)', () => { }), ); - expect(created).toBeNull(); + expect(created).toBe('capacity-exceeded'); expect(await prisma.order.count()).toBe(0); - expect(await prisma.outbox.count()).toBe(0); + expect(await prisma.payment.count()).toBe(0); }); - it('반증: order_number 충돌로 tx가 롤백되면 이벤트도 남지 않는다', async () => { + it('반증: order_number 충돌로 tx가 롤백되면 결제도 남지 않는다', async () => { const buyer = await setupBuyer(); const store = await createStore(prisma); const product = await createProduct(prisma, { store_id: store.id }); await createOrder(prisma, { order_number: 'ORD-20260916-DUP000' }); await expect( - repo.createSubmittedOrder( - submitArgs({ + repo.createPendingPaymentOrder( + createArgs({ buyerId: buyer.id, store, product, @@ -1071,7 +1078,28 @@ describe('OrderRepository (real DB)', () => { ), ).rejects.toMatchObject({ code: 'P2002' }); - expect(await prisma.outbox.count()).toBe(0); + expect(await prisma.payment.count()).toBe(0); + }); + + it('실패한 tx도 계정 잠금을 풀어 같은 계정의 다음 요청이 기다리지 않는다', async () => { + const buyer = await setupBuyer(); + const store = await createStore(prisma); + const product = await createProduct(prisma, { store_id: store.id }); + await createOrder(prisma, { order_number: 'ORD-20260916-DUP000' }); + await expect( + repo.createPendingPaymentOrder( + createArgs({ + buyerId: buyer.id, + store, + product, + orderNumber: 'ORD-20260916-DUP000', + }), + ), + ).rejects.toMatchObject({ code: 'P2002' }); + + const [row] = await prisma.$queryRaw<{ used: unknown }[]>` + SELECT IS_USED_LOCK(${`pending-payment:${buyer.id}`}) AS used`; + expect(row.used).toBeNull(); }); }); }); diff --git a/src/features/order/repositories/order.repository.ts b/src/features/order/repositories/order.repository.ts index 4a009248..65e7de63 100644 --- a/src/features/order/repositories/order.repository.ts +++ b/src/features/order/repositories/order.repository.ts @@ -6,15 +6,25 @@ import { } from '@/features/audit-log'; import { IN_PROGRESS_ORDER_STATUSES } from '@/features/order/constants/order-status-traits'; import { orderStatusChangedEvent } from '@/features/order/events/order-status-changed.event'; -import { orderSubmittedEvent } from '@/features/order/events/order-submitted.event'; +import { + countPendingPaymentOrdersLocked, + PENDING_PAYMENT_LIMIT, + withPendingPaymentLock, +} from '@/features/order/repositories/order-pending-payment-lock.helper'; +import { + orderPaymentSelect, + type OrderPaymentRow, +} from '@/features/order/repositories/payment.repository'; import { OutboxPublisher } from '@/features/outbox'; import { AuditActionType, AuditTargetType, OrderActor, OrderStatus, + PaymentMethod, Prisma, type AccountType, + type PaymentStatus, } from '@/generated/prisma/client'; import { activeWhere, PrismaService } from '@/prisma'; @@ -33,7 +43,7 @@ const sellerVisibleWhere = { submitted_at: { not: null }, } satisfies Prisma.OrderWhereInput; -const adminOrderInclude = { +export const adminOrderInclude = { items: { where: activeWhere, select: { @@ -71,6 +81,7 @@ const adminOrderDetailInclude = { user_profile: { select: { nickname: true, deleted_at: true } }, }, }, + payment: true, status_histories: { where: activeWhere, orderBy: { changed_at: 'desc' } }, items: { where: activeWhere, @@ -125,6 +136,7 @@ export interface MyOrderRow { product_thumbnail_url_snapshot: string | null; }[]; _count: { items: number }; + payment: { status: PaymentStatus; expires_at: Date } | null; } export interface OngoingOrderRow { @@ -148,7 +160,7 @@ export interface DailyCapacityGuard { dayEndUtc: Date; } -export interface CreateSubmittedOrderArgs { +export interface CreatePendingPaymentOrderArgs { accountId: bigint; orderNumber: string; idempotencyKey: string; @@ -160,9 +172,17 @@ export interface CreateSubmittedOrderArgs { subtotalPrice: number; discountPrice: number; totalPrice: number; - submittedAt: Date; + commissionRateBps: number; + now: Date; /** null이면 capacity 원자 검사 생략 — 항상 전달 권장. */ capacityGuard: DailyCapacityGuard | null; + payment: { + depositorName: string; + depositBankCode: string; + depositAccountNumber: string; + depositAccountHolder: string; + expiresAt: Date; + }; item: { storeId: bigint; productId: bigint; @@ -189,12 +209,25 @@ export interface CreatedOrderRow { order_number: string; status: OrderStatus; pickup_at: Date; - buyer_name: string; total_price: number; - updated_at: Date; idempotency_input_hash: string | null; + /** 결제 도입 전 주문은 null */ + payment: OrderPaymentRow | null; } +const createdOrderSelect = { + id: true, + order_number: true, + status: true, + pickup_at: true, + total_price: true, + idempotency_input_hash: true, + payment: { select: orderPaymentSelect }, +} satisfies Prisma.OrderSelect; + +export type CreatePendingPaymentOrderResult = + CreatedOrderRow | 'capacity-exceeded' | 'pending-limit' | 'lock-timeout'; + export interface ReviewableOrderItemRow { id: bigint; product_id: bigint; @@ -240,27 +273,40 @@ export class OrderRepository { } /** - * SUBMITTED는 알림 미발송(알림은 판매자 상태 변경부터 — buildOrderStatusNotification 규칙). - * capacityGuard가 있으면 capacity 행을 FOR UPDATE로 잠근 뒤 점유를 재집계해, 동시 주문이 마지막 잔여를 - * 함께 차지하는 race를 차단한다. capacity 초과면 null(호출부가 도메인 에러로), order_number P2002는 호출부가 재시도한다. + * 입금 대기 주문을 결제(PENDING)와 함께 만든다. 계정 잠금(GET_LOCK) → 입금 대기 건수 → capacity 순으로 잠그고, + * capacity는 행을 FOR UPDATE로 잠근 뒤 점유를 재집계해 동시 주문이 마지막 잔여를 함께 차지하지 못하게 한다. + * order_number P2002는 호출부가 재시도한다. + * READ COMMITTED: REPEATABLE READ의 갭 잠금은 다른 계정끼리도 건수 잠금 읽기 → INSERT에서 교착한다. */ - async createSubmittedOrder( - args: CreateSubmittedOrderArgs, - ): Promise { - return this.prisma.$transaction(async (tx) => { - if (args.capacityGuard) { - const exceeded = await this.isCapacityExceededLocked( - tx, - args.capacityGuard, - args.item.quantity, - ); - if (exceeded) return null; - } - return this.insertSubmittedOrder(tx, args); - }); + async createPendingPaymentOrder( + args: CreatePendingPaymentOrderArgs, + ): Promise { + return this.prisma.$transaction( + (tx) => + withPendingPaymentLock(tx, args.accountId, async () => { + const pending = await countPendingPaymentOrdersLocked( + tx, + args.accountId, + ); + if (pending >= PENDING_PAYMENT_LIMIT) return 'pending-limit'; + if (args.capacityGuard) { + const exceeded = await this.isCapacityExceededLocked( + tx, + args.capacityGuard, + args.item.quantity, + ); + if (exceeded) return 'capacity-exceeded'; + } + return this.insertPendingPaymentOrder(tx, args); + }), + { + timeout: 10_000, + isolationLevel: Prisma.TransactionIsolationLevel.ReadCommitted, + }, + ); } - /** tx 밖 사전 검증(잠금 없음) — 거절을 tx 전에 내리고, 최종 판정은 createSubmittedOrder의 잠금 재검사가 한다. */ + /** tx 밖 사전 검증(잠금 없음) — 거절을 tx 전에 내리고, 최종 판정은 createPendingPaymentOrder의 잠금 재검사가 한다. */ async isDailyCapacityExceeded( guard: DailyCapacityGuard, quantity: number, @@ -314,17 +360,17 @@ export class OrderRepository { return booked + quantity > capacity; } - private async insertSubmittedOrder( + private insertPendingPaymentOrder( tx: Prisma.TransactionClient, - args: CreateSubmittedOrderArgs, + args: CreatePendingPaymentOrderArgs, ): Promise { - const created = await tx.order.create({ + return tx.order.create({ data: { account_id: args.accountId, order_number: args.orderNumber, idempotency_key: args.idempotencyKey, idempotency_input_hash: args.idempotencyInputHash, - status: OrderStatus.SUBMITTED, + status: OrderStatus.PENDING_PAYMENT, pickup_at: args.pickupAt, buyer_name: args.buyerName, buyer_phone: args.buyerPhone, @@ -332,7 +378,7 @@ export class OrderRepository { subtotal_price: args.subtotalPrice, discount_price: args.discountPrice, total_price: args.totalPrice, - submitted_at: args.submittedAt, + commission_rate_bps: args.commissionRateBps, items: { create: { store_id: args.item.storeId, @@ -357,45 +403,29 @@ export class OrderRepository { }, }, }, + payment: { + create: { + method: PaymentMethod.BANK_TRANSFER, + amount: args.totalPrice, + depositor_name: args.payment.depositorName, + deposit_bank_code: args.payment.depositBankCode, + deposit_account_number: args.payment.depositAccountNumber, + deposit_account_holder: args.payment.depositAccountHolder, + expires_at: args.payment.expiresAt, + }, + }, status_histories: { create: { from_status: null, - to_status: OrderStatus.SUBMITTED, - changed_at: args.submittedAt, + to_status: OrderStatus.PENDING_PAYMENT, + changed_at: args.now, actor_type: OrderActor.BUYER, actor_account_id: args.accountId, }, }, }, - select: { - id: true, - order_number: true, - status: true, - pickup_at: true, - buyer_name: true, - total_price: true, - updated_at: true, - idempotency_input_hash: true, - }, + select: createdOrderSelect, }); - // 접수 이벤트(outbox, 같은 tx) — 판매자 푸시 원천. 구매자 알림은 없다(notification 소비자는 구독하지 않는다). - await this.outbox.publish( - tx, - orderSubmittedEvent({ - orderId: created.id, - orderNumber: created.order_number, - buyerAccountId: args.accountId, - storeId: args.item.storeId, - storeName: args.item.storeNameSnapshot, - productId: args.item.productId, - productName: args.item.productNameSnapshot, - quantity: args.item.quantity, - pickupAt: args.pickupAt, - totalPrice: args.totalPrice, - occurredAt: args.submittedAt, - }), - ); - return created; } /** 상태가 이후 변경됐어도 현재 row를 그대로 반환한다(replay 응답 재구성용). */ @@ -405,16 +435,7 @@ export class OrderRepository { ): Promise { return this.prisma.order.findFirst({ where: { account_id: accountId, idempotency_key: idempotencyKey }, - select: { - id: true, - order_number: true, - status: true, - pickup_at: true, - buyer_name: true, - total_price: true, - updated_at: true, - idempotency_input_hash: true, - }, + select: createdOrderSelect, }); } @@ -487,6 +508,7 @@ export class OrderRepository { _count: { select: { items: { where: activeWhere } }, }, + payment: { select: { status: true, expires_at: true } }, }, }); } @@ -590,6 +612,7 @@ export class OrderRepository { account_id: args.accountId, }, include: { + payment: { select: orderPaymentSelect }, status_histories: { where: activeWhere, orderBy: { changed_at: 'asc' }, @@ -798,6 +821,7 @@ export class OrderRepository { }, // 유저측 상세(findOrderDetailByUser)와 동일하게 soft-delete 자식을 가드한다 include: { + payment: { select: { method: true } }, // 입금 대기 이력은 판매자에게 보이지 않는다 status_histories: { where: { diff --git a/src/features/order/repositories/payment.repository.ts b/src/features/order/repositories/payment.repository.ts new file mode 100644 index 00000000..bab96c83 --- /dev/null +++ b/src/features/order/repositories/payment.repository.ts @@ -0,0 +1,161 @@ +import { Injectable } from '@nestjs/common'; + +import type { TimestampIdCursor } from '@/common/utils/keyset-cursor'; +import { + OrderStatus, + PaymentStatus, + type Prisma, +} from '@/generated/prisma/client'; +import { activeWhere, PrismaService } from '@/prisma'; + +/** 구매자·관리자 결제 출력이 공통으로 읽는 열. */ +export const orderPaymentSelect = { + method: true, + status: true, + amount: true, + depositor_name: true, + deposit_bank_code: true, + deposit_account_number: true, + deposit_account_holder: true, + expires_at: true, + buyer_claimed_at: true, + confirmed_at: true, + confirm_source: true, +} satisfies Prisma.PaymentSelect; + +export type OrderPaymentRow = Prisma.PaymentGetPayload<{ + select: typeof orderPaymentSelect; +}>; + +/** 확인을 기다리는 결제: 결제 PENDING이고 주문이 아직 입금 대기다. */ +const awaitingConfirmationWhere = { + status: PaymentStatus.PENDING, + order: { status: OrderStatus.PENDING_PAYMENT, ...activeWhere }, +} satisfies Prisma.PaymentWhereInput; + +const pendingPaymentInclude = { + order: { + select: { + id: true, + order_number: true, + buyer_name: true, + buyer_phone: true, + pickup_at: true, + created_at: true, + items: { + where: activeWhere, + select: { store_name_snapshot: true, product_name_snapshot: true }, + orderBy: { id: 'asc' }, + take: 1, + }, + }, + }, +} satisfies Prisma.PaymentInclude; + +export type PendingPaymentRow = Prisma.PaymentGetPayload<{ + include: typeof pendingPaymentInclude; +}>; + +export interface PendingPaymentFilter { + claimedOnly: boolean; + amount?: number; + depositorName?: string; +} + +export type DepositClaimResult = + | 'claimed' + | 'already-claimed' + | 'not-found' + | 'not-pending' + | 'deadline-passed'; + +@Injectable() +export class PaymentRepository { + constructor(private readonly prisma: PrismaService) {} + + private pendingScopeWhere( + filter: PendingPaymentFilter, + ): Prisma.PaymentWhereInput { + return { + ...awaitingConfirmationWhere, + ...(filter.claimedOnly ? { buyer_claimed_at: { not: null } } : {}), + ...(filter.amount !== undefined ? { amount: filter.amount } : {}), + ...(filter.depositorName + ? { depositor_name: { contains: filter.depositorName } } + : {}), + }; + } + + /** '입금했어요' 목록은 누른 시각, 전체 목록은 생성 순(결제 id)으로 오래된 것부터. */ + async listPendingPayments( + filter: PendingPaymentFilter & { + limit: number; + claimedCursor?: TimestampIdCursor; + idCursor?: bigint; + }, + ): Promise { + const after: Prisma.PaymentWhereInput = filter.claimedOnly + ? filter.claimedCursor + ? { + OR: [ + { buyer_claimed_at: { gt: filter.claimedCursor.timestamp } }, + { + buyer_claimed_at: filter.claimedCursor.timestamp, + id: { gt: filter.claimedCursor.id }, + }, + ], + } + : {} + : filter.idCursor !== undefined + ? { id: { gt: filter.idCursor } } + : {}; + return this.prisma.payment.findMany({ + where: { AND: [this.pendingScopeWhere(filter), after] }, + include: pendingPaymentInclude, + orderBy: filter.claimedOnly + ? [{ buyer_claimed_at: 'asc' }, { id: 'asc' }] + : { id: 'asc' }, + take: filter.limit + 1, + }); + } + + async countPendingPayments(filter: PendingPaymentFilter): Promise { + return this.prisma.payment.count({ where: this.pendingScopeWhere(filter) }); + } + + /** + * 마감 전 첫 누름만 기록한다. 다시 누르면 아무것도 바꾸지 않는다(멱등). + * 잠금 순서는 주문 → 결제(입금 확인과 같다). + */ + async markDepositClaimed(args: { + orderId: bigint; + accountId: bigint; + now: Date; + }): Promise { + return this.prisma.$transaction(async (tx) => { + const [order] = await tx.$queryRaw<{ id: bigint; status: OrderStatus }[]>` + SELECT id, status FROM \`order\` + WHERE id = ${args.orderId} AND account_id = ${args.accountId} AND deleted_at IS NULL + FOR UPDATE`; + if (!order) return 'not-found'; + await tx.$queryRaw`SELECT id FROM payment WHERE order_id = ${order.id} FOR UPDATE`; + const payment = await tx.payment.findUnique({ + where: { order_id: order.id }, + }); + if ( + order.status !== OrderStatus.PENDING_PAYMENT || + payment?.status !== PaymentStatus.PENDING + ) { + return 'not-pending'; + } + if (payment.buyer_claimed_at) return 'already-claimed'; + if (args.now >= payment.expires_at) return 'deadline-passed'; + + await tx.payment.update({ + where: { id: payment.id }, + data: { buyer_claimed_at: args.now }, + }); + return 'claimed'; + }); + } +} diff --git a/src/features/order/resolvers/order-checkout-mutation.resolver.spec.ts b/src/features/order/resolvers/order-checkout-mutation.resolver.spec.ts index 10e4ff4b..4645d706 100644 --- a/src/features/order/resolvers/order-checkout-mutation.resolver.spec.ts +++ b/src/features/order/resolvers/order-checkout-mutation.resolver.spec.ts @@ -1,19 +1,16 @@ -import { PubSub } from 'graphql-subscriptions'; - import { ClockService } from '@/common/providers/clock.service'; import { RandomService } from '@/common/providers/random.service'; import { AUDIT_LOG_REPOSITORY } from '@/features/audit-log'; import { AuditLogRepository } from '@/features/audit-log/repositories/audit-log.repository'; import { OrderRepository } from '@/features/order/repositories/order.repository'; +import { PaymentSettingRepository } from '@/features/order/repositories/payment-setting.repository'; import { OrderCheckoutMutationResolver } from '@/features/order/resolvers/order-checkout-mutation.resolver'; import { OrderCheckoutService } from '@/features/order/services/order-checkout.service'; -import { OrderEventsService } from '@/features/order/services/order-events.service'; import { ProductRepository } from '@/features/product'; import { StorePickupScheduleService } from '@/features/store'; import { StoreRepository } from '@/features/store/repositories/store.repository'; import type { PrismaClient } from '@/generated/prisma/client'; import type { JwtUser } from '@/global/auth'; -import { PUB_SUB } from '@/global/pubsub'; import { bookedQuantityProviders } from '@/test/booked-quantity'; import { disconnectTestPrismaClient } from '@/test/db/prisma-test-client'; import { closeTruncateConnection, truncateAll } from '@/test/db/truncate'; @@ -42,14 +39,13 @@ describe('OrderCheckout Mutation Resolver (real DB)', () => { OrderCheckoutMutationResolver, OrderCheckoutService, OrderRepository, + PaymentSettingRepository, ProductRepository, { provide: AUDIT_LOG_REPOSITORY, useClass: AuditLogRepository }, StorePickupScheduleService, StoreRepository, ClockService, RandomService, - OrderEventsService, - { provide: PUB_SUB, useValue: new PubSub() }, // 발행 repository가 OutboxPublisher를 주입받는다(08b) ...outboxPublisherProviders({ clock: true }), ...bookedQuantityProviders(), @@ -109,8 +105,9 @@ describe('OrderCheckout Mutation Resolver (real DB)', () => { requestNote: '초는 빼 주세요', }); - expect(result.status).toBe('SUBMITTED'); + expect(result.status).toBe('PENDING_PAYMENT'); expect(result.totalPrice).toBe(20000); + expect(result.payment).toMatchObject({ amount: 20000, status: 'PENDING' }); const saved = await prisma.order.findUniqueOrThrow({ where: { id: BigInt(result.orderId) }, }); diff --git a/src/features/order/resolvers/order-deposit-admin-mutation.resolver.ts b/src/features/order/resolvers/order-deposit-admin-mutation.resolver.ts new file mode 100644 index 00000000..6d7c3f69 --- /dev/null +++ b/src/features/order/resolvers/order-deposit-admin-mutation.resolver.ts @@ -0,0 +1,29 @@ +import { UseGuards } from '@nestjs/common'; +import { Args, Mutation, Resolver } from '@nestjs/graphql'; + +import { AdminConfirmPaymentInput } from '@/features/order/dto/inputs/admin-confirm-payment.input'; +import { AdminDepositService } from '@/features/order/services/order-deposit-admin.service'; +import type { AdminOrderSummaryOutput } from '@/features/order/types/order-admin-output.type'; +import { + CurrentUser, + JwtAuthGuard, + Roles, + RolesGuard, + parseAccountId, + type JwtUser, +} from '@/global/auth'; + +@Resolver('Mutation') +@UseGuards(JwtAuthGuard, RolesGuard) +@Roles('ADMIN') +export class AdminDepositMutationResolver { + constructor(private readonly depositService: AdminDepositService) {} + + @Mutation('adminConfirmPayment') + adminConfirmPayment( + @CurrentUser() user: JwtUser, + @Args('input') input: AdminConfirmPaymentInput, + ): Promise { + return this.depositService.adminConfirmPayment(parseAccountId(user), input); + } +} diff --git a/src/features/order/resolvers/order-deposit-admin-query.resolver.ts b/src/features/order/resolvers/order-deposit-admin-query.resolver.ts new file mode 100644 index 00000000..3bf1a759 --- /dev/null +++ b/src/features/order/resolvers/order-deposit-admin-query.resolver.ts @@ -0,0 +1,43 @@ +import { UseGuards } from '@nestjs/common'; +import { Args, Query, Resolver } from '@nestjs/graphql'; + +import type { CursorConnection } from '@/common/types/cursor-connection.type'; +import { AdminPendingPaymentListInput } from '@/features/order/dto/inputs/admin-pending-payment-list.input'; +import { AdminDepositService } from '@/features/order/services/order-deposit-admin.service'; +import type { + AdminPendingPaymentOutput, + AdminTaskCountsOutput, +} from '@/features/order/types/order-payment-output.type'; +import { + CurrentUser, + JwtAuthGuard, + Roles, + RolesGuard, + parseAccountId, + type JwtUser, +} from '@/global/auth'; + +@Resolver('Query') +@UseGuards(JwtAuthGuard, RolesGuard) +@Roles('ADMIN') +export class AdminDepositQueryResolver { + constructor(private readonly depositService: AdminDepositService) {} + + @Query('adminPendingPayments') + adminPendingPayments( + @CurrentUser() user: JwtUser, + @Args('input', { nullable: true }) input?: AdminPendingPaymentListInput, + ): Promise> { + return this.depositService.adminPendingPayments( + parseAccountId(user), + input, + ); + } + + @Query('adminTaskCounts') + adminTaskCounts( + @CurrentUser() user: JwtUser, + ): Promise { + return this.depositService.adminTaskCounts(parseAccountId(user)); + } +} diff --git a/src/features/order/resolvers/order-deposit-admin.resolver.spec.ts b/src/features/order/resolvers/order-deposit-admin.resolver.spec.ts new file mode 100644 index 00000000..ec3866b0 --- /dev/null +++ b/src/features/order/resolvers/order-deposit-admin.resolver.spec.ts @@ -0,0 +1,88 @@ +// 분기/검증 세부는 order-deposit-admin.service.spec.ts에서 담당. 여기서는 리졸버→서비스→DB 경로만 본다. + +import { PubSub } from 'graphql-subscriptions'; + +import { AUDIT_LOG_REPOSITORY } from '@/features/audit-log'; +import { AuditLogRepository } from '@/features/audit-log/repositories/audit-log.repository'; +import { AccountAdminRepository } from '@/features/auth/repositories/account-admin.repository'; +import { OrderTransitionRepository } from '@/features/order/repositories/order-transition.repository'; +import { PaymentRepository } from '@/features/order/repositories/payment.repository'; +import { AdminDepositMutationResolver } from '@/features/order/resolvers/order-deposit-admin-mutation.resolver'; +import { AdminDepositQueryResolver } from '@/features/order/resolvers/order-deposit-admin-query.resolver'; +import { AdminDepositService } from '@/features/order/services/order-deposit-admin.service'; +import { OrderEventsService } from '@/features/order/services/order-events.service'; +import type { PrismaClient } from '@/generated/prisma/client'; +import type { JwtUser } from '@/global/auth'; +import { PUB_SUB } from '@/global/pubsub'; +import { disconnectTestPrismaClient } from '@/test/db/prisma-test-client'; +import { closeTruncateConnection, truncateAll } from '@/test/db/truncate'; +import { + createAccount, + createOrder, + createOrderItem, + createPayment, +} from '@/test/factories'; +import { createTestingModuleWithRealDb } from '@/test/modules/testing-module.builder'; +import { outboxPublisherProviders } from '@/test/outbox'; + +describe('Admin Deposit Resolvers (real DB)', () => { + let queryResolver: AdminDepositQueryResolver; + let mutationResolver: AdminDepositMutationResolver; + let prisma: PrismaClient; + + beforeAll(async () => { + const { module, prisma: p } = await createTestingModuleWithRealDb({ + providers: [ + AdminDepositQueryResolver, + AdminDepositMutationResolver, + AdminDepositService, + AccountAdminRepository, + PaymentRepository, + OrderTransitionRepository, + OrderEventsService, + { provide: PUB_SUB, useValue: new PubSub() }, + { provide: AUDIT_LOG_REPOSITORY, useClass: AuditLogRepository }, + ...outboxPublisherProviders(), + ], + }); + queryResolver = module.get(AdminDepositQueryResolver); + mutationResolver = module.get(AdminDepositMutationResolver); + prisma = p; + }); + + afterAll(async () => { + await closeTruncateConnection(); + await disconnectTestPrismaClient(); + }); + + beforeEach(async () => { + await truncateAll(); + }); + + it('입금 대기 목록·건수를 조회하고 ID 문자열로 입금 확인한다', async () => { + const admin = await createAccount(prisma, { account_type: 'ADMIN' }); + const user = { accountId: admin.id.toString() } as JwtUser; + const order = await createOrder(prisma, { + status: 'PENDING_PAYMENT', + pickup_at: new Date(Date.now() + 2 * 24 * 60 * 60_000), + }); + await createOrderItem(prisma, { order_id: order.id }); + await createPayment(prisma, { order_id: order.id }); + + const list = await queryResolver.adminPendingPayments(user, {}); + expect(list.items.map((i) => i.orderId)).toEqual([order.id.toString()]); + await expect(queryResolver.adminTaskCounts(user)).resolves.toEqual({ + claimedPayments: 0, + pendingPayments: 1, + }); + + const confirmed = await mutationResolver.adminConfirmPayment(user, { + orderId: order.id.toString(), + depositedAmount: order.total_price, + }); + expect(confirmed).toMatchObject({ + id: order.id.toString(), + status: 'SUBMITTED', + }); + }); +}); diff --git a/src/features/order/resolvers/order-my-mutation.resolver.ts b/src/features/order/resolvers/order-my-mutation.resolver.ts new file mode 100644 index 00000000..e58f020d --- /dev/null +++ b/src/features/order/resolvers/order-my-mutation.resolver.ts @@ -0,0 +1,29 @@ +import { UseGuards } from '@nestjs/common'; +import { Args, Mutation, Resolver } from '@nestjs/graphql'; + +import { parseId } from '@/common/utils/id-parser'; +import { UserOrderService } from '@/features/order/services/order-my.service'; +import type { MyOrderDetail } from '@/features/order/types/order-my-output.type'; +import { + CurrentUser, + JwtAuthGuard, + parseAccountId, + type JwtUser, +} from '@/global/auth'; + +@Resolver('Mutation') +@UseGuards(JwtAuthGuard) +export class UserOrderMutationResolver { + constructor(private readonly orderService: UserOrderService) {} + + @Mutation('markMyOrderDepositSent') + markMyOrderDepositSent( + @CurrentUser() user: JwtUser, + @Args('orderId') orderId: string, + ): Promise { + return this.orderService.markMyOrderDepositSent( + parseAccountId(user), + parseId(orderId), + ); + } +} diff --git a/src/features/order/resolvers/order-my.resolver.spec.ts b/src/features/order/resolvers/order-my.resolver.spec.ts index 7bfba62c..7485114b 100644 --- a/src/features/order/resolvers/order-my.resolver.spec.ts +++ b/src/features/order/resolvers/order-my.resolver.spec.ts @@ -1,6 +1,8 @@ import { AUDIT_LOG_REPOSITORY } from '@/features/audit-log'; import { AuditLogRepository } from '@/features/audit-log/repositories/audit-log.repository'; import { OrderRepository } from '@/features/order/repositories/order.repository'; +import { PaymentRepository } from '@/features/order/repositories/payment.repository'; +import { UserOrderMutationResolver } from '@/features/order/resolvers/order-my-mutation.resolver'; import { UserOrderQueryResolver } from '@/features/order/resolvers/order-my-query.resolver'; import { UserOrderService } from '@/features/order/services/order-my.service'; import type { PrismaClient } from '@/generated/prisma/client'; @@ -10,6 +12,7 @@ import { createAccount, createOrder, createOrderItem, + createPayment, createProduct, createStore, createUserProfile, @@ -19,20 +22,24 @@ import { outboxPublisherProviders } from '@/test/outbox'; describe('User Order Resolver (real DB)', () => { let resolver: UserOrderQueryResolver; + let mutationResolver: UserOrderMutationResolver; let prisma: PrismaClient; beforeAll(async () => { const { module, prisma: p } = await createTestingModuleWithRealDb({ providers: [ UserOrderQueryResolver, + UserOrderMutationResolver, UserOrderService, OrderRepository, + PaymentRepository, { provide: AUDIT_LOG_REPOSITORY, useClass: AuditLogRepository }, // 발행 repository가 OutboxPublisher를 주입받는다(08b) ...outboxPublisherProviders(), ], }); resolver = module.get(UserOrderQueryResolver); + mutationResolver = module.get(UserOrderMutationResolver); prisma = p; }); @@ -95,4 +102,25 @@ describe('User Order Resolver (real DB)', () => { ), ).rejects.toThrowDomain(404); }); + + it("Mutation.markMyOrderDepositSent: ID를 파싱해 '입금했어요'를 기록하고 상세를 반환한다", async () => { + const account = await createAccount(prisma, { account_type: 'USER' }); + await createUserProfile(prisma, { account_id: account.id }); + const order = await createOrder(prisma, { + account_id: account.id, + status: 'PENDING_PAYMENT', + }); + await createPayment(prisma, { + order_id: order.id, + expires_at: new Date(Date.now() + 60 * 60_000), + }); + + const result = await mutationResolver.markMyOrderDepositSent( + { accountId: account.id.toString() }, + order.id.toString(), + ); + + expect(result.orderId).toBe(order.id.toString()); + expect(result.payment?.buyerClaimedAt).toBeInstanceOf(Date); + }); }); diff --git a/src/features/order/services/order-admin-mappers.helper.ts b/src/features/order/services/order-admin-mappers.helper.ts index cba192b8..cc17875a 100644 --- a/src/features/order/services/order-admin-mappers.helper.ts +++ b/src/features/order/services/order-admin-mappers.helper.ts @@ -7,6 +7,7 @@ import { toOrderItemDetail, toOrderStatusHistory, } from '@/features/order/services/order-output-mappers.helper'; +import { toAdminOrderPaymentOutput } from '@/features/order/services/order-payment-mappers.helper'; import type { AdminOrderDetailOutput, AdminOrderSummaryOutput, @@ -52,6 +53,7 @@ export function toAdminOrderDetailOutput( buyerName: row.buyer_name, buyerPhone: row.buyer_phone, requestNote: row.request_note, + payment: row.payment ? toAdminOrderPaymentOutput(row.payment) : null, subtotalPrice: row.subtotal_price, discountPrice: row.discount_price, totalPrice: row.total_price, diff --git a/src/features/order/services/order-admin.service.spec.ts b/src/features/order/services/order-admin.service.spec.ts index b2c9e054..f4e34998 100644 --- a/src/features/order/services/order-admin.service.spec.ts +++ b/src/features/order/services/order-admin.service.spec.ts @@ -20,6 +20,7 @@ import { createAccount, createOrder, createOrderItem, + createPayment, createStore, createUserProfile, } from '@/test/factories'; @@ -385,6 +386,43 @@ describe('AdminOrderService (real DB)', () => { }); expect(result.items.map((i) => i.id)).toEqual([item.id.toString()]); expect(result.statusHistories).toHaveLength(1); + expect(result.payment).toBeNull(); + }); + + it('결제와 입금 확인 처리자·메모를 준다', async () => { + const { order } = await orderWithItem(); + const confirmedAt = new Date('2026-09-16T07:00:00.000Z'); + const payment = await createPayment(prisma, { + order_id: order.id, + status: 'CONFIRMED', + confirmed_at: confirmedAt, + }); + await prisma.payment.update({ + where: { id: payment.id }, + data: { + confirm_source: 'ADMIN', + confirmed_by_label_snapshot: '김운영(admin1)', + confirm_note: '국민 입금', + }, + }); + + const result = await service.adminOrder(await admin(), order.id); + + expect(result.payment).toEqual({ + method: 'BANK_TRANSFER', + status: 'CONFIRMED', + amount: order.total_price, + depositorName: payment.depositor_name, + depositBank: { code: '004', name: 'KB국민은행' }, + depositAccountNumber: '12345678901234', + depositAccountHolder: '케이퀵', + expiresAt: payment.expires_at, + buyerClaimedAt: null, + confirmedAt, + confirmSource: 'ADMIN', + confirmedByLabel: '김운영(admin1)', + confirmNote: '국민 입금', + }); }); it('없거나 삭제된 주문이면 404', async () => { @@ -593,6 +631,7 @@ describe('AdminOrderService (real DB)', () => { }); expect(topic.received).toEqual([ { + kind: 'STATUS_CHANGED', orderId: order.id.toString(), orderNumber: order.order_number, status: 'CANCELED', diff --git a/src/features/order/services/order-admin.service.ts b/src/features/order/services/order-admin.service.ts index 0f5f92c6..89fb9c55 100644 --- a/src/features/order/services/order-admin.service.ts +++ b/src/features/order/services/order-admin.service.ts @@ -158,7 +158,11 @@ export class AdminOrderService extends AdminBaseService { if (firstItem && updated.submitted_at) { await this.events.publishSellerOrderUpdate( firstItem.store_id, - toSellerOrderUpdateEvent(updated, firstItem.product_name_snapshot), + toSellerOrderUpdateEvent( + 'STATUS_CHANGED', + updated, + firstItem.product_name_snapshot, + ), ); } return toAdminOrderSummaryOutput(updated); diff --git a/src/features/order/services/order-checkout.service.spec.ts b/src/features/order/services/order-checkout.service.spec.ts index 5483414f..b669ba0b 100644 --- a/src/features/order/services/order-checkout.service.spec.ts +++ b/src/features/order/services/order-checkout.service.spec.ts @@ -5,11 +5,9 @@ import { RandomService } from '@/common/providers/random.service'; import { AUDIT_LOG_REPOSITORY } from '@/features/audit-log'; import { AuditLogRepository } from '@/features/audit-log/repositories/audit-log.repository'; import type { CreateOrderInput } from '@/features/order/dto/inputs/create-order.input'; -import { - ORDER_SUBMITTED, - parseOrderSubmittedPayload, -} from '@/features/order/events/order-submitted.event'; +import { ORDER_SUBMITTED } from '@/features/order/events/order-submitted.event'; import { OrderRepository } from '@/features/order/repositories/order.repository'; +import { PaymentSettingRepository } from '@/features/order/repositories/payment-setting.repository'; import { OrderCheckoutService } from '@/features/order/services/order-checkout.service'; import { OrderEventsService } from '@/features/order/services/order-events.service'; import { ProductRepository } from '@/features/product'; @@ -59,14 +57,15 @@ describe('OrderCheckoutService (real DB)', () => { providers: [ OrderCheckoutService, OrderRepository, + PaymentSettingRepository, ProductRepository, { provide: AUDIT_LOG_REPOSITORY, useClass: AuditLogRepository }, StorePickupScheduleService, StoreRepository, ClockService, RandomService, + // 생성은 판매자 토픽에 발행하지 않는다 — 발행 수단을 열어 두고 미발행을 확인한다(in-memory) OrderEventsService, - // 발행-구독 왕복은 실 Redis spec(events service) 담당 — 여기선 in-memory { provide: PUB_SUB, useValue: new PubSub() }, // 발행 repository가 OutboxPublisher를 주입받는다(08b) ...outboxPublisherProviders({ clock: true }), @@ -237,7 +236,7 @@ describe('OrderCheckoutService (real DB)', () => { // (25000 + 2000 + 1000) × 2 expect(result.totalPrice).toBe(56000); - expect(result.status).toBe('SUBMITTED'); + expect(result.status).toBe('PENDING_PAYMENT'); expect(result.pickupAt).toEqual(VALID_PICKUP_AT); expect(result.orderNumber).toMatch(/^ORD-20260916-[A-HJ-NP-Z2-9]{6}$/); @@ -248,8 +247,8 @@ describe('OrderCheckoutService (real DB)', () => { status_histories: true, }, }); - expect(saved.status).toBe('SUBMITTED'); - expect(saved.submitted_at).toEqual(NOW); + expect(saved.status).toBe('PENDING_PAYMENT'); + expect(saved.submitted_at).toBeNull(); expect(saved.buyer_name).toBe('차차'); expect(saved.buyer_phone).toBe('010-0000-1111'); expect(saved.subtotal_price).toBe(66000); // (30000+3000)×2 @@ -274,7 +273,7 @@ describe('OrderCheckoutService (real DB)', () => { expect(saved.status_histories).toHaveLength(1); expect(saved.status_histories[0]).toMatchObject({ from_status: null, - to_status: 'SUBMITTED', + to_status: 'PENDING_PAYMENT', actor_type: 'BUYER', }); }); @@ -549,7 +548,7 @@ describe('OrderCheckoutService (real DB)', () => { buyer.id, baseInput({ productId: product.id.toString(), quantity: 1 }), ); - expect(ok.status).toBe('SUBMITTED'); + expect(ok.status).toBe('PENDING_PAYMENT'); }); it('SELLER 계정·프로필 없는 계정은 주문할 수 없다', async () => { @@ -595,7 +594,7 @@ describe('OrderCheckoutService (real DB)', () => { buyer.id, baseInput({ productId: product.id.toString() }), ); - expect(ok.status).toBe('SUBMITTED'); + expect(ok.status).toBe('PENDING_PAYMENT'); }); it('KRW가 아닌 통화 상품은 거절한다', async () => { @@ -678,7 +677,7 @@ describe('OrderCheckoutService (real DB)', () => { buyer.id, baseInput({ productId: product.id.toString(), quantity: 5 }), ), - ).resolves.toMatchObject({ status: 'SUBMITTED' }); + ).resolves.toMatchObject({ status: 'PENDING_PAYMENT' }); }); it('반증: 복제 지연 — catalog 기준으로는 이미 소진이어도 복제본이 없으면 받는다', async () => { @@ -707,7 +706,7 @@ describe('OrderCheckoutService (real DB)', () => { buyer.id, baseInput({ productId: product.id.toString() }), ), - ).resolves.toMatchObject({ status: 'SUBMITTED' }); + ).resolves.toMatchObject({ status: 'PENDING_PAYMENT' }); }); it('반증: 설정 삭제가 아직 복제되지 않았으면 기존 제한이 유지된다', async () => { @@ -761,10 +760,14 @@ describe('OrderCheckoutService (real DB)', () => { const rejected = results.filter((r) => r.status === 'rejected'); expect(fulfilled).toHaveLength(1); expect(rejected).toHaveLength(1); - const submittedCount = await prisma.order.count({ - where: { status: 'SUBMITTED', deleted_at: null }, + // 교착 등 다른 실패로 한 건이 떨어진 것이 아니다 + expect(rejected[0].reason).toMatchObject({ + code: 'PICKUP_NOT_AVAILABLE', + }); + const createdCount = await prisma.order.count({ + where: { status: 'PENDING_PAYMENT', deleted_at: null }, }); - expect(submittedCount).toBe(1); + expect(createdCount).toBe(1); }); it('주문번호 충돌 시 새 번호로 재시도하고, 계속 충돌하면 실패한다', async () => { @@ -962,7 +965,7 @@ describe('OrderCheckoutService (real DB)', () => { productId: product.id.toString(), }), ); - expect(retried.status).toBe('SUBMITTED'); + expect(retried.status).toBe('PENDING_PAYMENT'); expect(await prisma.order.count()).toBe(1); }); }); @@ -1050,7 +1053,9 @@ describe('OrderCheckoutService (real DB)', () => { }), ); if (slot?.available) { - await expect(attempt).resolves.toMatchObject({ status: 'SUBMITTED' }); + await expect(attempt).resolves.toMatchObject({ + status: 'PENDING_PAYMENT', + }); } else { await expect(attempt).rejects.toThrowDomain('PICKUP_NOT_AVAILABLE'); } @@ -1090,6 +1095,7 @@ describe('OrderCheckoutService (real DB)', () => { ['픽업 일시', { pickupAt: new Date('2026-09-18T05:30:00.000Z') }], ['주문자 이름', { buyerName: '다른 이름' }], ['주문자 연락처', { buyerPhone: '010-9999-9999' }], + ['입금자명', { depositorName: '다른 입금자' }], ['요청 사항', { requestNote: '다른 메모' }], ['기대 금액', { expectedTotalPrice: 9_999 }], ])( @@ -1198,7 +1204,7 @@ describe('OrderCheckoutService (real DB)', () => { jest .spyOn(orderRepo, 'findOrderByIdempotencyKey') .mockResolvedValueOnce(null); - const insert = jest.spyOn(orderRepo, 'createSubmittedOrder'); + const insert = jest.spyOn(orderRepo, 'createPendingPaymentOrder'); await expect( service.createOrder(buyer.id, { ...input, requestNote: '다른 메모' }), ).rejects.toThrowDomain('IDEMPOTENCY_KEY_INPUT_MISMATCH'); @@ -1207,207 +1213,378 @@ describe('OrderCheckoutService (real DB)', () => { }); }); - describe('createOrder — 접수 이벤트(order.submitted)', () => { - async function submittedEvents() { - return prisma.outbox.findMany({ - where: { event_type: ORDER_SUBMITTED }, - orderBy: { id: 'asc' }, - }); - } - - it('생성과 같은 tx에 1건 남기고 payload는 생성 시점 스냅샷이다', async () => { + describe('createOrder — 판매자 비노출', () => { + it('판매자 새 주문 이벤트(order.submitted)도 구독 발행도 없다(입금 확인 뒤에 보인다)', async () => { const store = await makeOpenStore(); - const { product, sizeSmallId } = await makeProductWithOptions(store.id); + const product = await createProduct(prisma, { store_id: store.id }); const buyer = await makeBuyer(); + const topic = await collectTopic(pubSub, `order.seller.${store.id}`); + + await service.createOrder( + buyer.id, + baseInput({ productId: product.id.toString() }), + ); + + expect(await prisma.order.count()).toBe(1); + expect( + await prisma.outbox.count({ where: { event_type: ORDER_SUBMITTED } }), + ).toBe(0); + expect(topic.received).toEqual([]); + topic.stop(); + }); + }); + + describe('createOrder — 결제(입금 안내)', () => { + it('결제를 입금 대기로 만들고 계좌·기한(1시간)·수수료율을 주문 시점 값으로 스냅샷한다', async () => { + await createPaymentSetting(prisma, { + commission_rate_bps: 550, + deposit_bank_code: '088', + deposit_account_number: '110123456789', + deposit_account_holder: '케이퀵 주식회사', + }); + const store = await makeOpenStore(); + const product = await createProduct(prisma, { store_id: store.id }); + const buyer = await makeBuyer('010-1234-5678', '차차'); const result = await service.createOrder( buyer.id, - baseInput({ - productId: product.id.toString(), - optionItemIds: [sizeSmallId.toString()], - quantity: 2, - expectedTotalPrice: 54000, - }), + baseInput({ productId: product.id.toString() }), ); - const events = await submittedEvents(); - expect(events).toHaveLength(1); - expect(events[0]).toMatchObject({ - aggregate_type: 'order', - aggregate_id: result.orderId, - occurred_at: NOW, - actor_account_id: buyer.id, + const expiresAt = new Date(NOW.getTime() + 60 * 60_000); + expect(result.payment).toEqual({ + method: 'BANK_TRANSFER', + status: 'PENDING', + amount: 10_000, + depositorName: '차차', + depositBank: { code: '088', name: '신한은행' }, + depositAccountNumber: '110123456789', + depositAccountHolder: '케이퀵 주식회사', + expiresAt, + buyerClaimedAt: null, + confirmedAt: null, + confirmSource: null, }); - expect(parseOrderSubmittedPayload(events[0].payload_json)).toEqual({ - orderId: result.orderId, - orderNumber: result.orderNumber, - buyerAccountId: buyer.id.toString(), - storeId: store.id.toString(), - storeName: store.store_name, + const saved = await prisma.order.findUniqueOrThrow({ + where: { id: BigInt(result.orderId) }, + include: { payment: true }, + }); + expect(saved.commission_rate_bps).toBe(550); + expect(saved.payment).toMatchObject({ + amount: 10_000, + expires_at: expiresAt, + }); + + // 설정이 바뀌어도 만들어진 주문의 안내·수수료율은 그대로다(replay) + await createPaymentSetting(prisma, { commission_rate_bps: 0 }); + const input = baseInput({ + idempotencyKey: 'snapshot-key', productId: product.id.toString(), - productName: product.name, - quantity: 2, - pickupAt: VALID_PICKUP_AT.toISOString(), - // (25000 + 2000) × 2 - totalPrice: 54000, }); + const first = await service.createOrder(buyer.id, input); + await createPaymentSetting(prisma, { deposit_bank_code: '004' }); + await expect(service.createOrder(buyer.id, input)).resolves.toEqual( + first, + ); }); - it('반증: capacity 거절은 이벤트를 남기지 않는다', async () => { + it.each<[string, string | undefined, string]>([ + ['생략하면 주문자 이름', undefined, '주문자'], + ['공백만 보내면 주문자 이름', ' ', '주문자'], + ['입력값은 앞뒤 공백을 뗀다', ' 입금자 ', '입금자'], + [ + '20자(코드 포인트, 이모지 포함)', + `${'가'.repeat(18)}🎂🎂`, + `${'가'.repeat(18)}🎂🎂`, + ], + ])('입금자명: %s', async (_case, depositorName, expected) => { const store = await makeOpenStore(); const product = await createProduct(prisma, { store_id: store.id }); const buyer = await makeBuyer(); - await createStoreDailyCapacity(prisma, { - store_id: store.id, - capacity_date: new Date(Date.UTC(2026, 8, 18)), - capacity: 1, - }); - await expect( - service.createOrder( - buyer.id, - baseInput({ productId: product.id.toString(), quantity: 2 }), - ), - ).rejects.toThrowDomain(400); + const result = await service.createOrder( + buyer.id, + baseInput({ + productId: product.id.toString(), + buyerName: '주문자', + depositorName, + }), + ); - expect(await submittedEvents()).toHaveLength(0); + expect(result.payment?.depositorName).toBe(expected); }); - it('반증: 같은 키 replay(재요청·capacity race)는 이벤트를 추가하지 않는다', async () => { - const store = await makeOpenStore(); - const product = await createProduct(prisma, { store_id: store.id }); - const buyer = await makeBuyer(); - await createStoreDailyCapacity(prisma, { - store_id: store.id, - capacity_date: new Date(Date.UTC(2026, 8, 18)), - capacity: 1, - }); - const input = baseInput({ - idempotencyKey: 'replay-idem-key', - productId: product.id.toString(), - }); + it.each<[string, Partial]>([ + ['입력 21자', { depositorName: '가'.repeat(21) }], + // 잘라 쓰면 은행 입금자명과 어긋나 오확인을 부른다 + ['생략했는데 주문자 이름이 21자', { buyerName: '가'.repeat(21) }], + ])( + '입금자명이 20자를 넘으면 DEPOSITOR_NAME_INVALID다 — %s', + async (_case, change) => { + const store = await makeOpenStore(); + const product = await createProduct(prisma, { store_id: store.id }); + const buyer = await makeBuyer(); - const first = await service.createOrder(buyer.id, input); - expect(await service.createOrder(buyer.id, input)).toEqual(first); - // 사전 조회 miss → tx 안 capacity 거절 → replay 경로 - jest - .spyOn(orderRepo, 'findOrderByIdempotencyKey') - .mockResolvedValueOnce(null); - expect(await service.createOrder(buyer.id, input)).toEqual(first); + await expect( + service.createOrder( + buyer.id, + baseInput({ productId: product.id.toString(), ...change }), + ), + ).rejects.toThrowDomain('DEPOSITOR_NAME_INVALID'); + expect(await prisma.order.count()).toBe(0); + }, + ); - const events = await submittedEvents(); - expect(events).toHaveLength(1); - expect(events[0].aggregate_id).toBe(first.orderId); - }); + it.each<[string, Parameters[1] | null]>([ + ['설정 행 없음', null], + ['은행 없음', { deposit_bank_code: null }], + ['계좌번호 없음', { deposit_account_number: null }], + ['예금주 없음', { deposit_account_holder: null }], + ])( + '입금 계좌가 다 채워지지 않았으면 PAYMENT_ACCOUNT_NOT_CONFIGURED다 — %s', + async (_case, overrides) => { + if (overrides === null) { + await prisma.paymentSetting.deleteMany(); + } else { + await createPaymentSetting(prisma, overrides); + } + const store = await makeOpenStore(); + const product = await createProduct(prisma, { store_id: store.id }); + const buyer = await makeBuyer(); + + await expect( + service.createOrder( + buyer.id, + baseInput({ productId: product.id.toString() }), + ), + ).rejects.toThrowDomain('PAYMENT_ACCOUNT_NOT_CONFIGURED'); + expect(await prisma.order.count()).toBe(0); + }, + ); }); - describe('sellerOrderUpdated 발행', () => { - it('주문 생성 시 매장 토픽에 1건 — 커밋된 주문 행(updated_at)의 스냅샷을 싣는다', async () => { + describe('createOrder — 계정당 입금 대기 2건', () => { + async function setup() { const store = await makeOpenStore(); const product = await createProduct(prisma, { store_id: store.id }); const buyer = await makeBuyer(); - const topic = await collectTopic(pubSub, `order.seller.${store.id}`); + return { store, product, buyer }; + } - const result = await service.createOrder( + function pendingOrder(accountId: bigint, overrides = {}) { + return createOrderRow(prisma, { + account_id: accountId, + status: 'PENDING_PAYMENT', + ...overrides, + }); + } + + function sleep(ms: number) { + return new Promise((resolve) => setTimeout(resolve, ms)); + } + + it('입금 대기가 1건이면 받고, 2건이면 PENDING_PAYMENT_LIMIT_EXCEEDED다', async () => { + const { product, buyer } = await setup(); + await pendingOrder(buyer.id); + + const second = await service.createOrder( buyer.id, - baseInput({ productId: product.id.toString(), buyerName: '차차' }), + baseInput({ productId: product.id.toString() }), ); + expect(second.status).toBe('PENDING_PAYMENT'); - const saved = await prisma.order.findUniqueOrThrow({ - where: { id: BigInt(result.orderId) }, + await expect( + service.createOrder( + buyer.id, + baseInput({ productId: product.id.toString() }), + ), + ).rejects.toThrowDomain('PENDING_PAYMENT_LIMIT_EXCEEDED'); + expect( + await prisma.order.count({ where: { account_id: buyer.id } }), + ).toBe(2); + }); + + it('다른 상태·삭제된 입금 대기·다른 계정의 입금 대기는 세지 않는다', async () => { + const { product, buyer } = await setup(); + const other = await makeBuyer(); + await pendingOrder(buyer.id, { deleted_at: NOW }); + await createOrderRow(prisma, { + account_id: buyer.id, + status: 'SUBMITTED', }); - expect(topic.received).toEqual([ - { - orderId: result.orderId, - orderNumber: result.orderNumber, - status: 'SUBMITTED', - pickupAt: VALID_PICKUP_AT.toISOString(), - buyerName: '차차', - totalPrice: result.totalPrice, - productName: product.name, - updatedAt: saved.updated_at.toISOString(), - }, - ]); - topic.stop(); + await createOrderRow(prisma, { + account_id: buyer.id, + status: 'CANCELED', + }); + await pendingOrder(other.id); + await pendingOrder(other.id); + + for (let i = 0; i < 2; i += 1) { + await service.createOrder( + buyer.id, + baseInput({ productId: product.id.toString() }), + ); + } + expect( + await prisma.order.count({ + where: { account_id: buyer.id, status: 'PENDING_PAYMENT' }, + }), + ).toBe(2); }); - it('반증: 멱등 replay(사전 조회·P2002 경합)는 발행하지 않는다', async () => { - const store = await makeOpenStore(); - const product = await createProduct(prisma, { store_id: store.id }); - const buyer = await makeBuyer(); - const topic = await collectTopic(pubSub, `order.seller.${store.id}`); + it('상한에 걸려도 같은 키 재요청은 기존 주문을 돌려준다', async () => { + const { product, buyer } = await setup(); + await pendingOrder(buyer.id); const input = baseInput({ - idempotencyKey: 'replay-no-event', + idempotencyKey: 'limit-replay-key', productId: product.id.toString(), }); + const first = await service.createOrder(buyer.id, input); - await service.createOrder(buyer.id, input); - await service.createOrder(buyer.id, input); - // 사전 조회를 놓친 동시 제출 — 멱등 키 unique 충돌 뒤 기존 주문을 replay한다 + // 사전 조회를 놓친 재시도 — tx 안 건수 거절 뒤 내 주문을 찾아 replay한다 jest .spyOn(orderRepo, 'findOrderByIdempotencyKey') .mockResolvedValueOnce(null); - await service.createOrder(buyer.id, input); - - expect(await prisma.order.count()).toBe(1); - expect(topic.received).toHaveLength(1); - topic.stop(); + await expect(service.createOrder(buyer.id, input)).resolves.toEqual( + first, + ); + expect(await prisma.order.count()).toBe(2); }); - it('반증: capacity 거절·tx 안 capacity replay는 발행하지 않는다', async () => { - const store = await makeOpenStore(); - const product = await createProduct(prisma, { store_id: store.id }); - const buyer = await makeBuyer(); - await createStoreDailyCapacity(prisma, { - store_id: store.id, - capacity_date: new Date(Date.UTC(2026, 8, 18)), - capacity: 1, - }); - const topic = await collectTopic(pubSub, `order.seller.${store.id}`); - const input = baseInput({ - idempotencyKey: 'capacity-replay-no-event', - productId: product.id.toString(), - }); + it('동시 2요청은 하나만 받는다(입금 대기 1건에서 시작)', async () => { + const { product, buyer } = await setup(); + await pendingOrder(buyer.id); - await service.createOrder(buyer.id, input); - await expect( + const results = await Promise.allSettled([ service.createOrder( buyer.id, baseInput({ productId: product.id.toString() }), ), - ).rejects.toThrowDomain('PICKUP_NOT_AVAILABLE'); - // 사전 조회·사전 capacity 검사를 모두 놓친 동시 재시도 — 잠금 재검사가 거절하고 내 주문을 replay한다 - jest - .spyOn(orderRepo, 'findOrderByIdempotencyKey') - .mockResolvedValueOnce(null); - jest - .spyOn(orderRepo, 'isDailyCapacityExceeded') - .mockResolvedValueOnce(false); - await service.createOrder(buyer.id, input); + service.createOrder( + buyer.id, + baseInput({ productId: product.id.toString() }), + ), + ]); - expect(await prisma.order.count()).toBe(1); - expect(topic.received).toHaveLength(1); - topic.stop(); + expect(results.filter((r) => r.status === 'fulfilled')).toHaveLength(1); + const rejected = results.filter((r) => r.status === 'rejected'); + expect(rejected).toHaveLength(1); + expect(rejected[0].reason).toMatchObject({ + code: 'PENDING_PAYMENT_LIMIT_EXCEEDED', + }); + expect( + await prisma.order.count({ where: { status: 'PENDING_PAYMENT' } }), + ).toBe(2); }); - it('PubSub 발행이 실패해도 주문은 성공하고 이벤트만 빠진다', async () => { - const store = await makeOpenStore(); - const product = await createProduct(prisma, { store_id: store.id }); - const buyer = await makeBuyer(); - const topic = await collectTopic(pubSub, `order.seller.${store.id}`); - jest - .spyOn(pubSub, 'publish') - .mockRejectedValueOnce(new Error('redis down')); + it('앞 요청의 입금 대기 행이 커밋되기 전이면 기다렸다가 커밋된 건수로 거절한다', async () => { + const { product, buyer } = await setup(); + await pendingOrder(buyer.id); + let commit!: () => void; + const gate = new Promise((resolve) => (commit = resolve)); + let inserted!: () => void; + const insertedSignal = new Promise( + (resolve) => (inserted = resolve), + ); + // 계정 잠금 없이 같은 계정 입금 대기 행을 미커밋으로 잡아 둔다 + const holder = prisma.$transaction( + async (tx) => { + await tx.order.create({ + data: { + account_id: buyer.id, + order_number: 'ORD-UNCOMMITTED-1', + status: 'PENDING_PAYMENT', + pickup_at: VALID_PICKUP_AT, + buyer_name: '차차', + buyer_phone: '010-0000-0000', + }, + }); + inserted(); + await gate; + }, + { timeout: 20_000 }, + ); + await insertedSignal; - const result = await service.createOrder( + const attempt = service.createOrder( buyer.id, baseInput({ productId: product.id.toString() }), ); + const settled = attempt.then( + () => 'settled', + () => 'settled', + ); + await expect( + Promise.race([settled, sleep(500).then(() => 'waiting')]), + ).resolves.toBe('waiting'); - expect(result.status).toBe('SUBMITTED'); - expect(await prisma.order.count()).toBe(1); - expect(topic.received).toHaveLength(0); - topic.stop(); + commit(); + await holder; + await expect(attempt).rejects.toThrowDomain( + 'PENDING_PAYMENT_LIMIT_EXCEEDED', + ); + expect( + await prisma.order.count({ where: { account_id: buyer.id } }), + ).toBe(2); + }); + + it('같은 계정 요청이 3초 안에 계정 잠금을 얻지 못하면 CONCURRENT_REQUEST다', async () => { + const { product, buyer } = await setup(); + let release!: () => void; + const gate = new Promise((resolve) => (release = resolve)); + let locked!: () => void; + const lockedSignal = new Promise((resolve) => (locked = resolve)); + const name = `pending-payment:${buyer.id}`; + const holder = prisma.$transaction( + async (tx) => { + await tx.$queryRaw`SELECT GET_LOCK(${name}, 0)`; + locked(); + await gate; + await tx.$queryRaw`SELECT RELEASE_LOCK(${name})`; + }, + { timeout: 20_000 }, + ); + await lockedSignal; + + try { + await expect( + service.createOrder( + buyer.id, + baseInput({ productId: product.id.toString() }), + ), + ).rejects.toThrowDomain('CONCURRENT_REQUEST'); + expect(await prisma.order.count()).toBe(0); + } finally { + release(); + await holder; + } + }); + + it('다른 계정끼리는 같은 매장·날짜(capacity 잠금)로 동시에 주문해도 교착 없이 둘 다 받는다', async () => { + const { store, product } = await setup(); + await createStoreDailyCapacity(prisma, { + store_id: store.id, + capacity_date: new Date(Date.UTC(2026, 8, 18)), + capacity: 10, + }); + const buyers = [await makeBuyer(), await makeBuyer()]; + + for (let round = 0; round < 5; round += 1) { + const results = await Promise.allSettled( + buyers.map((buyer) => + service.createOrder( + buyer.id, + baseInput({ productId: product.id.toString() }), + ), + ), + ); + expect(results.map((r) => r.status)).toEqual([ + 'fulfilled', + 'fulfilled', + ]); + // 다음 라운드도 상한에 걸리지 않게 입금 대기를 비운다 + await prisma.order.updateMany({ data: { status: 'CANCELED' } }); + } }); }); }); diff --git a/src/features/order/services/order-checkout.service.ts b/src/features/order/services/order-checkout.service.ts index 0359ada0..368ba7a8 100644 --- a/src/features/order/services/order-checkout.service.ts +++ b/src/features/order/services/order-checkout.service.ts @@ -7,12 +7,17 @@ import { parseId } from '@/common/utils/id-parser'; import { formatKstDate, kstDayBoundaries } from '@/common/utils/kst-time'; import { uniqueConstraintName } from '@/common/utils/prisma-error'; import { buildRegionLabel } from '@/common/utils/region-label'; +import { codePointLength } from '@/common/utils/text-cleaner'; import { evaluateActiveUserAccount } from '@/features/auth'; import type { CreateOrderInput } from '@/features/order/dto/inputs/create-order.input'; -import { OrderRepository } from '@/features/order/repositories/order.repository'; -import { toSellerOrderUpdateEvent } from '@/features/order/services/order-events-mappers.helper'; -import { OrderEventsService } from '@/features/order/services/order-events.service'; +import { + OrderRepository, + type CreatedOrderRow, + type CreatePendingPaymentOrderArgs, +} from '@/features/order/repositories/order.repository'; +import { PaymentSettingRepository } from '@/features/order/repositories/payment-setting.repository'; import { hashCreateOrderInput } from '@/features/order/services/order-input-hash.helper'; +import { toOrderPaymentOutput } from '@/features/order/services/order-payment-mappers.helper'; import type { CreateOrderOutput } from '@/features/order/types/create-order-output.type'; import { ProductRepository, type ProductDetailRow } from '@/features/product'; import { StorePickupScheduleService } from '@/features/store'; @@ -28,6 +33,11 @@ const ORDER_NUMBER_MAX_ATTEMPTS = 3; // "저장은 됐는데 응답 직렬화에서 실패 → 재시도 중복 주문" 경로를 차단한다. const MAX_ORDER_AMOUNT = 2_147_483_647; +/** 미입금 자동 취소까지의 입금 기한. */ +const PAYMENT_WINDOW_MS = 60 * 60_000; +/** 은행 입금자명과 대조하는 값이라 자르지 않고 입력을 요구한다. */ +const MAX_DEPOSITOR_NAME_LENGTH = 20; + interface ResolvedOptionSelection { optionGroupId: bigint; optionItemId: bigint; @@ -44,10 +54,13 @@ export class OrderCheckoutService { private readonly pickupSchedule: StorePickupScheduleService, private readonly clock: ClockService, private readonly random: RandomService, - private readonly events: OrderEventsService, + private readonly paymentSettings: PaymentSettingRepository, ) {} - /** 옵션 그룹 규칙·픽업 일시를 서버가 재검증하고 가격을 스냅샷한다. 커스텀 입력은 스펙 확정 후 확장. */ + /** + * 옵션 그룹 규칙·픽업 일시를 서버가 재검증하고 가격을 스냅샷한 뒤 입금 대기 주문을 만든다. + * 판매자에게는 입금 확인 뒤에 보이므로 여기서는 판매자 구독을 발행하지 않는다. + */ async createOrder( accountId: bigint, input: CreateOrderInput, @@ -84,6 +97,7 @@ export class OrderCheckoutService { const selections = this.resolveOptionSelections(product, optionItemIds); const buyer = this.resolveBuyerInfo(buyerProfile, input); + const depositorName = resolveDepositorName(input.depositorName, buyer.name); const now = this.clock.now(); // 영업일·슬롯·하한(리드타임과 제작 시간 중 긴 쪽)은 달력과 같은 catalog 판정, 주문 수량까지 더한 capacity 잔여는 order 복제본이 판정한다 @@ -101,10 +115,11 @@ export class OrderCheckoutService { if (!pickupAvailable) { // 같은 키의 동시 재시도가 방금 capacity를 채운 것일 수 있다 — 거절 전에 키를 재조회해, // 내 주문이 이미 생성돼 있으면 실패 대신 replay로 응답한다(응답 유실 재시도가 '가득 참' 실패를 받는 race 차단). - const raced = await this.replayAfterCapacityReject( + const raced = await this.replayOrReject( accountId, input.idempotencyKey, inputHash, + 'PICKUP_NOT_AVAILABLE', ); return this.toCreateOrderOutput(raced); } @@ -135,7 +150,17 @@ export class OrderCheckoutService { throw new DomainException('ORDER_PRICE_CHANGED'); } - const submittedAt = now; + const setting = await this.paymentSettings.findPaymentSetting(); + const { + deposit_bank_code: depositBankCode, + deposit_account_number: depositAccountNumber, + deposit_account_holder: depositAccountHolder, + } = setting; + // 결제 설정은 보낸 필드만 바꾸므로 일부만 채워진 행이 있을 수 있다 — 세 값이 다 있어야 안내할 수 있다 + if (!depositBankCode || !depositAccountNumber || !depositAccountHolder) { + throw new DomainException('PAYMENT_ACCOUNT_NOT_CONFIGURED'); + } + const created = await this.createWithOrderNumberRetry({ accountId, idempotencyKey: input.idempotencyKey, @@ -147,8 +172,16 @@ export class OrderCheckoutService { subtotalPrice, discountPrice, totalPrice: itemSubtotalPrice, - submittedAt, + commissionRateBps: setting.commission_rate_bps, + now, capacityGuard, + payment: { + depositorName, + depositBankCode, + depositAccountNumber, + depositAccountHolder, + expiresAt: new Date(now.getTime() + PAYMENT_WINDOW_MS), + }, item: { storeId: product.store_id, productId: product.id, @@ -168,19 +201,14 @@ export class OrderCheckoutService { return this.toCreateOrderOutput(created); } - private toCreateOrderOutput(row: { - id: bigint; - order_number: string; - status: CreateOrderOutput['status']; - pickup_at: Date; - total_price: number; - }): CreateOrderOutput { + private toCreateOrderOutput(row: CreatedOrderRow): CreateOrderOutput { return { orderId: row.id.toString(), orderNumber: row.order_number, status: row.status, pickupAt: row.pickup_at, totalPrice: row.total_price, + payment: row.payment ? toOrderPaymentOutput(row.payment) : null, }; } @@ -273,31 +301,29 @@ export class OrderCheckoutService { } private async createWithOrderNumberRetry( - args: Omit< - Parameters[0], - 'orderNumber' - >, - ) { + args: Omit, + ): Promise { for (let attempt = 0; attempt < ORDER_NUMBER_MAX_ATTEMPTS; attempt += 1) { try { - const created = await this.orderRepo.createSubmittedOrder({ + const created = await this.orderRepo.createPendingPaymentOrder({ ...args, - orderNumber: this.generateOrderNumber(args.submittedAt), + orderNumber: this.generateOrderNumber(args.now), }); - if (created === null) { - // 트랜잭션 내 capacity 재검사에서 잔여 부족 판정(동시 주문 race 차단). - // 잔여를 채운 것이 같은 키의 내 주문일 수 있어 거절 전에 replay를 확인한다. - return this.replayAfterCapacityReject( + if (created === 'lock-timeout') { + throw new DomainException('CONCURRENT_REQUEST'); + } + if (created === 'capacity-exceeded' || created === 'pending-limit') { + // 트랜잭션 안 잠금 재검사에서 거절됐다. 자리를 채운 것이 같은 키의 내 주문(응답 유실 재시도)일 수 있어 + // 거절 전에 replay를 확인한다. + return this.replayOrReject( args.accountId, args.idempotencyKey, args.idempotencyInputHash, + created === 'capacity-exceeded' + ? 'PICKUP_NOT_AVAILABLE' + : 'PENDING_PAYMENT_LIMIT_EXCEEDED', ); } - // 커밋된 새 주문만 발행한다 — replay(멱등 키·capacity·P2002)는 이미 발행된 주문이다 - await this.events.publishSellerOrderUpdate( - args.item.storeId, - toSellerOrderUpdateEvent(created, args.item.productNameSnapshot), - ); return created; } catch (error) { const isUniqueViolation = @@ -339,16 +365,17 @@ export class OrderCheckoutService { throw new DomainException('ORDER_NUMBER_GENERATION_FAILED'); } - private async replayAfterCapacityReject( + private async replayOrReject( accountId: bigint, idempotencyKey: string, inputHash: string, - ) { + rejectCode: 'PICKUP_NOT_AVAILABLE' | 'PENDING_PAYMENT_LIMIT_EXCEEDED', + ): Promise { const existing = await this.orderRepo.findOrderByIdempotencyKey( accountId, idempotencyKey, ); - if (!existing) throw new DomainException('PICKUP_NOT_AVAILABLE'); + if (!existing) throw new DomainException(rejectCode); assertReplayInputMatches(existing, inputHash); return existing; } @@ -372,6 +399,18 @@ export class OrderCheckoutService { } } +/** 생략·공백이면 주문자 이름. 어느 쪽이든 20자를 넘으면 자르지 않고 입력을 요구한다. */ +function resolveDepositorName( + raw: string | null | undefined, + buyerName: string, +): string { + const name = raw?.trim() || buyerName; + if (codePointLength(name) > MAX_DEPOSITOR_NAME_LENGTH) { + throw new DomainException('DEPOSITOR_NAME_INVALID'); + } + return name; +} + /** 해시 도입 전 주문(null)은 비교하지 않는다. */ function assertReplayInputMatches( existing: { idempotency_input_hash: string | null }, diff --git a/src/features/order/services/order-deposit-admin.service.spec.ts b/src/features/order/services/order-deposit-admin.service.spec.ts new file mode 100644 index 00000000..133f43b8 --- /dev/null +++ b/src/features/order/services/order-deposit-admin.service.spec.ts @@ -0,0 +1,575 @@ +import { PubSub } from 'graphql-subscriptions'; + +import { ClockService } from '@/common/providers/clock.service'; +import { AUDIT_LOG_REPOSITORY } from '@/features/audit-log'; +import { AuditLogRepository } from '@/features/audit-log/repositories/audit-log.repository'; +import { AccountAdminRepository } from '@/features/auth/repositories/account-admin.repository'; +import { NotificationAdminRepository } from '@/features/notification/repositories/notification-admin.repository'; +import { NotificationRepository } from '@/features/notification/repositories/notification.repository'; +import { NotificationOutboxConsumer } from '@/features/notification/services/notification-outbox.consumer'; +import { ORDER_STATUS_CHANGED } from '@/features/order/events/order-status-changed.event'; +import { + ORDER_SUBMITTED, + parseOrderSubmittedPayload, +} from '@/features/order/events/order-submitted.event'; +import { OrderTransitionRepository } from '@/features/order/repositories/order-transition.repository'; +import { OrderRepository } from '@/features/order/repositories/order.repository'; +import { PaymentRepository } from '@/features/order/repositories/payment.repository'; +import { AdminDepositService } from '@/features/order/services/order-deposit-admin.service'; +import { OrderEventsService } from '@/features/order/services/order-events.service'; +import { OutboxDispatcherService } from '@/features/outbox'; +import type { OrderStatus, PrismaClient } from '@/generated/prisma/client'; +import { PUB_SUB } from '@/global/pubsub'; +import { disconnectTestPrismaClient } from '@/test/db/prisma-test-client'; +import { closeTruncateConnection, truncateAll } from '@/test/db/truncate'; +import { + createAccount, + createOrder, + createOrderItem, + createPayment, + createStore, +} from '@/test/factories'; +import { createTestingModuleWithRealDb } from '@/test/modules/testing-module.builder'; +import { + drainOutbox, + OUTBOX_TEST_IMPORTS, + outboxTestProviders, +} from '@/test/outbox'; +import { collectTopic } from '@/test/pubsub'; + +// 2026-09-16(수) 16:00 KST +const NOW = new Date('2026-09-16T07:00:00.000Z'); +const DAY_MS = 24 * 60 * 60_000; + +describe('AdminDepositService (real DB)', () => { + let service: AdminDepositService; + let orderRepo: OrderRepository; + let clock: ClockService; + let dispatcher: OutboxDispatcherService; + let pubSub: PubSub; + let prisma: PrismaClient; + + beforeAll(async () => { + const { module, prisma: p } = await createTestingModuleWithRealDb({ + imports: OUTBOX_TEST_IMPORTS, + providers: [ + AdminDepositService, + AccountAdminRepository, + PaymentRepository, + OrderTransitionRepository, + OrderRepository, + { provide: AUDIT_LOG_REPOSITORY, useClass: AuditLogRepository }, + OrderEventsService, + { provide: PUB_SUB, useValue: new PubSub() }, + ...outboxTestProviders(), + NotificationOutboxConsumer, + NotificationRepository, + NotificationAdminRepository, + ], + }); + service = module.get(AdminDepositService); + orderRepo = module.get(OrderRepository); + clock = module.get(ClockService); + dispatcher = module.get(OutboxDispatcherService); + pubSub = module.get(PUB_SUB); + prisma = p; + }); + + afterAll(async () => { + await closeTruncateConnection(); + await disconnectTestPrismaClient(); + }); + + beforeEach(async () => { + await truncateAll(); + jest.spyOn(clock, 'now').mockReturnValue(NOW); + }); + + afterEach(() => { + jest.restoreAllMocks(); + }); + + async function admin(name = '운영자'): Promise { + return (await createAccount(prisma, { account_type: 'ADMIN', name })).id; + } + + /** 입금 대기 주문 + 결제(PENDING) + 품목. */ + async function pendingOrder( + overrides: { + pickupAt?: Date; + createdAt?: Date; + totalPrice?: number; + depositorName?: string; + claimedAt?: Date | null; + status?: OrderStatus; + paymentStatus?: 'PENDING' | 'CONFIRMED' | 'CANCELED'; + } = {}, + ) { + const store = await createStore(prisma, { store_name: '해즈 케이크' }); + const order = await createOrder(prisma, { + status: overrides.status ?? 'PENDING_PAYMENT', + pickup_at: overrides.pickupAt ?? new Date(NOW.getTime() + 2 * DAY_MS), + total_price: overrides.totalPrice ?? 30_000, + ...(overrides.createdAt ? { created_at: overrides.createdAt } : {}), + }); + const item = await createOrderItem(prisma, { + order_id: order.id, + store_id: store.id, + product_name_snapshot: '딸기 케이크', + quantity: 2, + }); + const payment = await createPayment(prisma, { + order_id: order.id, + status: overrides.paymentStatus ?? 'PENDING', + depositor_name: overrides.depositorName ?? '차차', + buyer_claimed_at: overrides.claimedAt ?? null, + }); + return { order, item, payment, storeId: store.id }; + } + + describe('adminConfirmPayment', () => { + it('입금액이 결제 금액과 같으면 접수로 넘기고 결제·이력·감사(입금액)·마감을 남긴다', async () => { + const adminId = await admin('김운영'); + const { order, payment } = await pendingOrder(); + + const result = await service.adminConfirmPayment(adminId, { + orderId: order.id.toString(), + depositedAmount: 30_000, + note: ' 국민 08:01 입금 ', + }); + + expect(result).toMatchObject({ + id: order.id.toString(), + status: 'SUBMITTED', + storeName: '해즈 케이크', + }); + const saved = await prisma.order.findUniqueOrThrow({ + where: { id: order.id }, + include: { payment: true, status_histories: true }, + }); + expect(saved).toMatchObject({ + status: 'SUBMITTED', + submitted_at: NOW, + confirm_deadline_at: new Date(NOW.getTime() + DAY_MS), + }); + expect(saved.payment).toMatchObject({ + id: payment.id, + status: 'CONFIRMED', + confirmed_at: NOW, + confirm_source: 'ADMIN', + confirmed_by_account_id: adminId, + confirmed_by_label_snapshot: '김운영', + confirm_note: '국민 08:01 입금', + }); + expect(saved.status_histories).toEqual([ + expect.objectContaining({ + from_status: 'PENDING_PAYMENT', + to_status: 'SUBMITTED', + actor_type: 'ADMIN', + actor_account_id: adminId, + changed_at: NOW, + }), + ]); + const audit = await prisma.auditLog.findFirstOrThrow({ + where: { target_type: 'ORDER', target_id: order.id }, + }); + expect(audit).toMatchObject({ + actor_account_id: adminId, + action: 'STATUS_CHANGE', + before_json: { status: 'PENDING_PAYMENT' }, + after_json: { + status: 'SUBMITTED', + paymentAmount: 30_000, + depositedAmount: 30_000, + confirmSource: 'ADMIN', + note: '국민 08:01 입금', + }, + }); + }); + + it('픽업이 24시간 안이면 확정 마감은 픽업 시각이다', async () => { + const adminId = await admin(); + const pickupAt = new Date(NOW.getTime() + 3 * 60 * 60_000); + const { order } = await pendingOrder({ pickupAt }); + + await service.adminConfirmPayment(adminId, { + orderId: order.id.toString(), + depositedAmount: 30_000, + }); + + const saved = await prisma.order.findUniqueOrThrow({ + where: { id: order.id }, + }); + expect(saved.confirm_deadline_at).toEqual(pickupAt); + }); + + it('확인 뒤 outbox(상태 전이 + 판매자 새 주문)·판매자 노출·구독(SUBMITTED)·구매자 알림이 따른다', async () => { + const adminId = await admin(); + const { order, item, storeId } = await pendingOrder(); + // 확인 전에는 판매자에게 보이지 않는다 + expect( + await orderRepo.findOrderDetailByStore({ orderId: order.id, storeId }), + ).toBeNull(); + const topic = await collectTopic(pubSub, `order.seller.${storeId}`); + + await service.adminConfirmPayment(adminId, { + orderId: order.id.toString(), + depositedAmount: 30_000, + }); + + const events = await prisma.outbox.findMany({ orderBy: { id: 'asc' } }); + expect(events.map((e) => e.event_type)).toEqual([ + ORDER_STATUS_CHANGED, + ORDER_SUBMITTED, + ]); + expect(events[1].actor_account_id).toBe(adminId); + expect(parseOrderSubmittedPayload(events[1].payload_json)).toEqual({ + orderId: order.id.toString(), + orderNumber: order.order_number, + buyerAccountId: order.account_id.toString(), + storeId: storeId.toString(), + storeName: '해즈 케이크', + productId: item.product_id.toString(), + productName: '딸기 케이크', + quantity: 2, + pickupAt: order.pickup_at.toISOString(), + totalPrice: 30_000, + confirmDeadlineAt: new Date(NOW.getTime() + DAY_MS).toISOString(), + }); + + await expect( + orderRepo.findOrderDetailByStore({ orderId: order.id, storeId }), + ).resolves.toMatchObject({ + status: 'SUBMITTED', + payment: { method: 'BANK_TRANSFER' }, + }); + expect(topic.received).toEqual([ + expect.objectContaining({ + kind: 'SUBMITTED', + orderId: order.id.toString(), + status: 'SUBMITTED', + productName: '딸기 케이크', + }), + ]); + topic.stop(); + + await drainOutbox(dispatcher); + const notification = await prisma.notification.findFirstOrThrow({ + where: { account_id: order.account_id }, + }); + expect(notification.event).toBe('ORDER_PAYMENT_CONFIRMED'); + }); + + it('품목이 없는 주문은 매장을 알 수 없어 판매자 구독을 발행하지 않는다', async () => { + const adminId = await admin(); + const order = await createOrder(prisma, { + status: 'PENDING_PAYMENT', + pickup_at: new Date(NOW.getTime() + 2 * DAY_MS), + }); + await createPayment(prisma, { order_id: order.id }); + const publish = jest.spyOn(pubSub, 'publish'); + + await expect( + service.adminConfirmPayment(adminId, { + orderId: order.id.toString(), + depositedAmount: order.total_price, + }), + ).resolves.toMatchObject({ status: 'SUBMITTED', storeId: null }); + expect(publish).not.toHaveBeenCalled(); + }); + + it('입금액이 다르면 DEPOSIT_AMOUNT_MISMATCH로 거절하고 아무것도 바꾸지 않는다', async () => { + const adminId = await admin(); + const { order } = await pendingOrder(); + + for (const depositedAmount of [29_999, 30_001]) { + await expect( + service.adminConfirmPayment(adminId, { + orderId: order.id.toString(), + depositedAmount, + }), + ).rejects.toThrowDomain('DEPOSIT_AMOUNT_MISMATCH'); + } + await expect( + prisma.payment.findUniqueOrThrow({ where: { order_id: order.id } }), + ).resolves.toMatchObject({ status: 'PENDING', confirmed_at: null }); + expect(await prisma.outbox.count()).toBe(0); + expect(await prisma.auditLog.count()).toBe(0); + }); + + it.each([0, -1])( + '입금액 %s는 DEPOSIT_AMOUNT_INVALID다', + async (depositedAmount) => { + const adminId = await admin(); + const { order } = await pendingOrder(); + + await expect( + service.adminConfirmPayment(adminId, { + orderId: order.id.toString(), + depositedAmount, + }), + ).rejects.toThrowDomain('DEPOSIT_AMOUNT_INVALID'); + }, + ); + + it.each<[string, Parameters[0]]>([ + [ + '입금 전 취소된 주문', + { status: 'CANCELED', paymentStatus: 'CANCELED' }, + ], + ['이미 확인된 주문', { status: 'SUBMITTED', paymentStatus: 'CONFIRMED' }], + ])('%s은 PAYMENT_NOT_PENDING(409)이다', async (_case, overrides) => { + const adminId = await admin(); + const { order } = await pendingOrder(overrides); + + await expect( + service.adminConfirmPayment(adminId, { + orderId: order.id.toString(), + depositedAmount: 30_000, + }), + ).rejects.toThrowDomain(409); + await expect( + service.adminConfirmPayment(adminId, { + orderId: order.id.toString(), + depositedAmount: 30_000, + }), + ).rejects.toThrowDomain('PAYMENT_NOT_PENDING'); + }); + + it('결제 기록이 없는 입금 대기 주문도 PAYMENT_NOT_PENDING이다', async () => { + const adminId = await admin(); + const order = await createOrder(prisma, { status: 'PENDING_PAYMENT' }); + + await expect( + service.adminConfirmPayment(adminId, { + orderId: order.id.toString(), + depositedAmount: 10_000, + }), + ).rejects.toThrowDomain('PAYMENT_NOT_PENDING'); + }); + + it.each([ + ['픽업 정각', 0], + ['픽업 1분 뒤', 60_000], + ])('%s이면 PAYMENT_PICKUP_PASSED(409)다', async (_case, sincePickupMs) => { + const adminId = await admin(); + const { order } = await pendingOrder({ + pickupAt: new Date(NOW.getTime() - sincePickupMs), + }); + + await expect( + service.adminConfirmPayment(adminId, { + orderId: order.id.toString(), + depositedAmount: 30_000, + }), + ).rejects.toThrowDomain('PAYMENT_PICKUP_PASSED'); + expect(await prisma.outbox.count()).toBe(0); + }); + + it("입금 기한이 지났어도 '입금했어요'로 자동 취소를 피한 주문은 확인한다", async () => { + const adminId = await admin(); + const { order } = await pendingOrder({ + claimedAt: new Date(NOW.getTime() - 2 * 60 * 60_000), + }); + await prisma.payment.update({ + where: { order_id: order.id }, + data: { expires_at: new Date(NOW.getTime() - 60 * 60_000) }, + }); + + await expect( + service.adminConfirmPayment(adminId, { + orderId: order.id.toString(), + depositedAmount: 30_000, + }), + ).resolves.toMatchObject({ status: 'SUBMITTED' }); + }); + + it('없거나 삭제된 주문은 ORDER_NOT_FOUND, 메모가 500자를 넘으면 TEXT_TOO_LONG이다', async () => { + const adminId = await admin(); + const { order } = await pendingOrder(); + + await expect( + service.adminConfirmPayment(adminId, { + orderId: order.id.toString(), + depositedAmount: 30_000, + note: '가'.repeat(501), + }), + ).rejects.toThrowDomain('TEXT_TOO_LONG'); + await prisma.order.update({ + where: { id: order.id }, + data: { deleted_at: NOW }, + }); + for (const orderId of [order.id.toString(), '999999']) { + await expect( + service.adminConfirmPayment(adminId, { + orderId, + depositedAmount: 30_000, + }), + ).rejects.toThrowDomain('ORDER_NOT_FOUND'); + } + }); + + it('두 관리자가 동시에 확인하면 한 명만 성공하고 나머지는 PAYMENT_NOT_PENDING이다', async () => { + const [first, second] = [await admin('A'), await admin('B')]; + const { order } = await pendingOrder(); + + const results = await Promise.allSettled( + [first, second].map((adminId) => + service.adminConfirmPayment(adminId, { + orderId: order.id.toString(), + depositedAmount: 30_000, + }), + ), + ); + + expect(results.filter((r) => r.status === 'fulfilled')).toHaveLength(1); + const rejected = results.filter((r) => r.status === 'rejected'); + expect(rejected[0].reason).toMatchObject({ + code: 'PAYMENT_NOT_PENDING', + }); + expect( + await prisma.orderStatusHistory.count({ + where: { order_id: order.id }, + }), + ).toBe(1); + expect( + await prisma.outbox.count({ where: { event_type: ORDER_SUBMITTED } }), + ).toBe(1); + }); + }); + + describe('adminPendingPayments·adminTaskCounts', () => { + it('입금 확인을 기다리는 주문만 생성 순으로, 키셋 커서로 넘긴다', async () => { + const adminId = await admin(); + const a = await pendingOrder({ depositorName: '가나다' }); + const b = await pendingOrder({ depositorName: '라마바' }); + const c = await pendingOrder({ depositorName: '사아자' }); + await pendingOrder({ status: 'SUBMITTED', paymentStatus: 'CONFIRMED' }); + await pendingOrder({ status: 'CANCELED', paymentStatus: 'CANCELED' }); + const deleted = await pendingOrder(); + await prisma.order.update({ + where: { id: deleted.order.id }, + data: { deleted_at: NOW }, + }); + + const itemless = await createOrder(prisma, { status: 'PENDING_PAYMENT' }); + await createPayment(prisma, { order_id: itemless.id }); + + const first = await service.adminPendingPayments(adminId, { limit: 2 }); + expect(first.items.map((i) => i.orderId)).toEqual([ + a.order.id.toString(), + b.order.id.toString(), + ]); + expect(first).toMatchObject({ totalCount: 4, hasMore: true }); + expect(first.items[0]).toEqual({ + orderId: a.order.id.toString(), + orderNumber: a.order.order_number, + storeName: '해즈 케이크', + productName: '딸기 케이크', + amount: 30_000, + depositorName: '가나다', + buyerName: a.order.buyer_name, + buyerPhone: a.order.buyer_phone, + createdAt: a.order.created_at, + expiresAt: a.payment.expires_at, + buyerClaimedAt: null, + pickupAt: a.order.pickup_at, + }); + + const second = await service.adminPendingPayments(adminId, { + limit: 2, + cursor: first.nextCursor!, + }); + expect(second.items.map((i) => i.orderId)).toEqual([ + c.order.id.toString(), + itemless.id.toString(), + ]); + expect(second).toMatchObject({ hasMore: false, nextCursor: null }); + // 품목이 없으면 매장·상품명이 없다 + expect(second.items[1]).toMatchObject({ + storeName: null, + productName: null, + }); + }); + + it("claimedOnly면 '입금했어요' 시각 오름차순(같은 시각은 id 순)으로 복합 커서를 쓴다", async () => { + const adminId = await admin(); + const t1 = new Date(NOW.getTime() - 30 * 60_000); + const t2 = new Date(NOW.getTime() - 10 * 60_000); + const late = await pendingOrder({ claimedAt: t2 }); + const earlyA = await pendingOrder({ claimedAt: t1 }); + const earlyB = await pendingOrder({ claimedAt: t1 }); + await pendingOrder(); + + const ids: string[] = []; + let cursor: string | undefined; + do { + const page = await service.adminPendingPayments(adminId, { + claimedOnly: true, + limit: 1, + cursor, + }); + expect(page.totalCount).toBe(3); + ids.push(...page.items.map((i) => i.orderId)); + cursor = page.nextCursor ?? undefined; + } while (cursor); + + expect(ids).toEqual( + [earlyA, earlyB, late].map((o) => o.order.id.toString()), + ); + }); + + it('금액 일치·입금자명 부분일치로 찾고, 필터 null은 생략과 같다', async () => { + const adminId = await admin(); + const target = await pendingOrder({ + totalPrice: 45_000, + depositorName: '홍길동', + }); + await pendingOrder({ totalPrice: 45_000, depositorName: '김철수' }); + await pendingOrder({ totalPrice: 30_000, depositorName: '홍길순' }); + + const found = await service.adminPendingPayments(adminId, { + amount: 45_000, + depositorName: ' 길동 ', + }); + expect(found.items.map((i) => i.orderId)).toEqual([ + target.order.id.toString(), + ]); + + const all = await service.adminPendingPayments(adminId, { + claimedOnly: null, + amount: null, + depositorName: null, + cursor: null, + limit: null, + } as never); + expect(all.totalCount).toBe(3); + expect((await service.adminPendingPayments(adminId)).totalCount).toBe(3); + }); + + it.each([ + [false, 'abc'], + [true, '123'], + ])( + 'claimedOnly=%s에 맞지 않는 커서는 INVALID_CURSOR다', + async (claimedOnly, cursor) => { + const adminId = await admin(); + await expect( + service.adminPendingPayments(adminId, { claimedOnly, cursor }), + ).rejects.toThrowDomain('INVALID_CURSOR'); + }, + ); + + it("처리 대기 건수는 '입금했어요'와 전체 입금 대기를 센다", async () => { + const adminId = await admin(); + await pendingOrder({ claimedAt: NOW }); + await pendingOrder(); + await pendingOrder({ status: 'SUBMITTED', paymentStatus: 'CONFIRMED' }); + + await expect(service.adminTaskCounts(adminId)).resolves.toEqual({ + claimedPayments: 1, + pendingPayments: 2, + }); + }); + }); +}); diff --git a/src/features/order/services/order-deposit-admin.service.ts b/src/features/order/services/order-deposit-admin.service.ts new file mode 100644 index 00000000..fc2763eb --- /dev/null +++ b/src/features/order/services/order-deposit-admin.service.ts @@ -0,0 +1,138 @@ +import { Inject, Injectable } from '@nestjs/common'; + +import { DomainException } from '@/common/errors/error-catalog'; +import { ClockService } from '@/common/providers/clock.service'; +import type { CursorConnection } from '@/common/types/cursor-connection.type'; +import { parseId } from '@/common/utils/id-parser'; +import { + buildTimestampIdCursor, + parseIdCursor, + parseTimestampIdCursor, +} from '@/common/utils/keyset-cursor'; +import { + normalizeCursorInput, + sliceCursorPage, + toCursorConnection, +} from '@/common/utils/pagination'; +import { cleanNullableText } from '@/common/utils/text-cleaner'; +import { + AUDIT_LOG_REPOSITORY, + type IAuditLogRepository, +} from '@/features/audit-log'; +import { AccountAdminRepository, AdminBaseService } from '@/features/auth'; +import type { AdminConfirmPaymentInput } from '@/features/order/dto/inputs/admin-confirm-payment.input'; +import type { AdminPendingPaymentListInput } from '@/features/order/dto/inputs/admin-pending-payment-list.input'; +import { assertPaymentConfirmable } from '@/features/order/policies/payment-confirm.policy'; +import { OrderTransitionRepository } from '@/features/order/repositories/order-transition.repository'; +import { PaymentRepository } from '@/features/order/repositories/payment.repository'; +import { toAdminOrderSummaryOutput } from '@/features/order/services/order-admin-mappers.helper'; +import { toSellerOrderUpdateEvent } from '@/features/order/services/order-events-mappers.helper'; +import { OrderEventsService } from '@/features/order/services/order-events.service'; +import { toAdminPendingPaymentOutput } from '@/features/order/services/order-payment-mappers.helper'; +import type { AdminOrderSummaryOutput } from '@/features/order/types/order-admin-output.type'; +import type { + AdminPendingPaymentOutput, + AdminTaskCountsOutput, +} from '@/features/order/types/order-payment-output.type'; +import { PaymentConfirmSource } from '@/generated/prisma/client'; + +const MAX_CONFIRM_NOTE_LENGTH = 500; + +/** 관리자 입금 처리 대기(입금 확인). 은행 앱에서 본 입금을 주문과 대조해 접수로 넘긴다. */ +@Injectable() +export class AdminDepositService extends AdminBaseService { + constructor( + accounts: AccountAdminRepository, + @Inject(AUDIT_LOG_REPOSITORY) + auditLogs: IAuditLogRepository, + private readonly payments: PaymentRepository, + private readonly transitions: OrderTransitionRepository, + private readonly clock: ClockService, + private readonly events: OrderEventsService, + ) { + super(accounts, auditLogs); + } + + async adminPendingPayments( + accountId: bigint, + input?: AdminPendingPaymentListInput, + ): Promise> { + await this.requireAdminContext(accountId); + // 관리자 FE는 '전체'를 null로 보낸다 — 생략과 같다 + const claimedOnly = input?.claimedOnly ?? false; + const filter = { + claimedOnly, + amount: input?.amount ?? undefined, + depositorName: input?.depositorName?.trim() || undefined, + }; + const { limit } = normalizeCursorInput({ limit: input?.limit }); + const cursor = input?.cursor; + const [rows, totalCount] = await Promise.all([ + this.payments.listPendingPayments({ + ...filter, + limit, + ...(cursor === undefined || cursor === null + ? {} + : claimedOnly + ? { claimedCursor: parseTimestampIdCursor(cursor) } + : { idCursor: parseIdCursor(cursor) }), + }), + this.payments.countPendingPayments(filter), + ]); + const page = sliceCursorPage(rows, limit, (last) => + claimedOnly + ? buildTimestampIdCursor(last.buyer_claimed_at!, last.id) + : last.id.toString(), + ); + return toCursorConnection(page, totalCount, toAdminPendingPaymentOutput); + } + + async adminTaskCounts(accountId: bigint): Promise { + await this.requireAdminContext(accountId); + const [claimedPayments, pendingPayments] = await Promise.all([ + this.payments.countPendingPayments({ claimedOnly: true }), + this.payments.countPendingPayments({ claimedOnly: false }), + ]); + return { claimedPayments, pendingPayments }; + } + + async adminConfirmPayment( + accountId: bigint, + input: AdminConfirmPaymentInput, + ): Promise { + const ctx = await this.requireAdminContext(accountId); + const orderId = parseId(input.orderId); + const { depositedAmount } = input; + if (!Number.isSafeInteger(depositedAmount) || depositedAmount < 1) { + throw new DomainException('DEPOSIT_AMOUNT_INVALID'); + } + const note = cleanNullableText(input.note, MAX_CONFIRM_NOTE_LENGTH); + const now = this.clock.now(); + + const updated = await this.transitions.confirmPayment({ + orderId, + source: PaymentConfirmSource.ADMIN, + actorAccountId: ctx.accountId, + actorLabel: ctx.displayLabel, + depositedAmount, + note, + now, + assertConfirmable: (state) => + assertPaymentConfirmable(state, depositedAmount, now), + }); + if (!updated) throw new DomainException('ORDER_NOT_FOUND'); + + const [firstItem] = updated.items; + if (firstItem) { + await this.events.publishSellerOrderUpdate( + firstItem.store_id, + toSellerOrderUpdateEvent( + 'SUBMITTED', + updated, + firstItem.product_name_snapshot, + ), + ); + } + return toAdminOrderSummaryOutput(updated); + } +} diff --git a/src/features/order/services/order-events-mappers.helper.ts b/src/features/order/services/order-events-mappers.helper.ts index 67154191..9658d712 100644 --- a/src/features/order/services/order-events-mappers.helper.ts +++ b/src/features/order/services/order-events-mappers.helper.ts @@ -1,4 +1,7 @@ -import type { SellerOrderUpdateEvent } from '@/features/order/types/order-seller-output.type'; +import type { + SellerOrderUpdateEvent, + SellerOrderUpdateKind, +} from '@/features/order/types/order-seller-output.type'; import type { Order } from '@/generated/prisma/client'; export type SellerOrderUpdateRow = Pick< @@ -13,10 +16,12 @@ export type SellerOrderUpdateRow = Pick< >; export function toSellerOrderUpdateEvent( + kind: SellerOrderUpdateKind, row: SellerOrderUpdateRow, productName: string, ): SellerOrderUpdateEvent { return { + kind, orderId: row.id.toString(), orderNumber: row.order_number, status: row.status, diff --git a/src/features/order/services/order-events.service.spec.ts b/src/features/order/services/order-events.service.spec.ts index 7353a168..789e3cbe 100644 --- a/src/features/order/services/order-events.service.spec.ts +++ b/src/features/order/services/order-events.service.spec.ts @@ -11,6 +11,7 @@ import { redisTestContainer } from '@/test/containers'; jest.setTimeout(180_000); const EVENT: SellerOrderUpdateEvent = { + kind: 'SUBMITTED', orderId: '1', orderNumber: 'ORD-20260916-ABC234', status: 'SUBMITTED', diff --git a/src/features/order/services/order-events.service.ts b/src/features/order/services/order-events.service.ts index 2da20a07..70104b3f 100644 --- a/src/features/order/services/order-events.service.ts +++ b/src/features/order/services/order-events.service.ts @@ -4,7 +4,7 @@ import type { PubSubEngine } from 'graphql-subscriptions'; import type { SellerOrderUpdateEvent } from '@/features/order/types/order-seller-output.type'; import { PUB_SUB } from '@/global/pubsub'; -/** 토픽 문자열은 여기서만 조립한다 — 발행자(체크아웃·판매자 상태 변경·관리자 취소)와 구독 리졸버가 같은 토픽을 보는 단일 소스. */ +/** 토픽 문자열은 여기서만 조립한다 — 발행자(입금 확인·판매자 상태 변경·관리자 취소)와 구독 리졸버가 같은 토픽을 보는 단일 소스. */ @Injectable() export class OrderEventsService { private readonly logger = new Logger(OrderEventsService.name); diff --git a/src/features/order/services/order-input-hash.helper.spec.ts b/src/features/order/services/order-input-hash.helper.spec.ts index 15277124..670ad0c5 100644 --- a/src/features/order/services/order-input-hash.helper.spec.ts +++ b/src/features/order/services/order-input-hash.helper.spec.ts @@ -11,6 +11,7 @@ const BASE: CreateOrderHashInput = { quantity: 2, buyerName: '차차', buyerPhone: '010-0000-1111', + depositorName: '차차맘', requestNote: '메모', expectedTotalPrice: 56000, }; @@ -23,7 +24,7 @@ describe('hashCreateOrderInput', () => { it('주문에 저장되는 값이라 정규화 형식을 고정한다(키 정렬·문자열 ID·ISO 시각)', () => { expect(hashCreateOrderInput(BASE)).toBe( sha256Hex( - '{"buyerName":"차차","buyerPhone":"010-0000-1111","expectedTotalPrice":56000,' + + '{"buyerName":"차차","buyerPhone":"010-0000-1111","depositorName":"차차맘","expectedTotalPrice":56000,' + '"optionItemIds":["10","11"],"pickupAt":"2026-09-18T05:00:00.000Z",' + '"productId":"1","quantity":2,"requestNote":"메모"}', ), @@ -50,10 +51,16 @@ describe('hashCreateOrderInput', () => { const omitted = hashWith({ buyerName: undefined, buyerPhone: undefined, + depositorName: undefined, requestNote: undefined, }); expect( - hashWith({ buyerName: null, buyerPhone: null, requestNote: null }), + hashWith({ + buyerName: null, + buyerPhone: null, + depositorName: null, + requestNote: null, + }), ).toBe(omitted); }); @@ -64,6 +71,7 @@ describe('hashCreateOrderInput', () => { ['quantity', { quantity: 3 }], ['buyerName', { buyerName: '다른 이름' }], ['buyerPhone', { buyerPhone: '010-9999-9999' }], + ['depositorName', { depositorName: '다른 입금자' }], ['requestNote', { requestNote: '다른 메모' }], ['expectedTotalPrice', { expectedTotalPrice: 56001 }], ])('%s가 다르면 해시가 다르다', (_field, change) => { diff --git a/src/features/order/services/order-input-hash.helper.ts b/src/features/order/services/order-input-hash.helper.ts index 5d8cefcf..6a4cb1a8 100644 --- a/src/features/order/services/order-input-hash.helper.ts +++ b/src/features/order/services/order-input-hash.helper.ts @@ -7,6 +7,7 @@ export interface CreateOrderHashInput { quantity?: number | null; buyerName?: string | null; buyerPhone?: string | null; + depositorName?: string | null; requestNote?: string | null; expectedTotalPrice: number; } @@ -21,6 +22,7 @@ export function hashCreateOrderInput(input: CreateOrderHashInput): string { quantity: input.quantity ?? 1, buyerName: input.buyerName, buyerPhone: input.buyerPhone, + depositorName: input.depositorName, requestNote: input.requestNote, expectedTotalPrice: input.expectedTotalPrice, }), diff --git a/src/features/order/services/order-my.service.spec.ts b/src/features/order/services/order-my.service.spec.ts index 8d73931b..ffdcf52d 100644 --- a/src/features/order/services/order-my.service.spec.ts +++ b/src/features/order/services/order-my.service.spec.ts @@ -1,6 +1,8 @@ +import { ClockService } from '@/common/providers/clock.service'; import { AUDIT_LOG_REPOSITORY } from '@/features/audit-log'; import { AuditLogRepository } from '@/features/audit-log/repositories/audit-log.repository'; import { OrderRepository } from '@/features/order/repositories/order.repository'; +import { PaymentRepository } from '@/features/order/repositories/payment.repository'; import { UserOrderService } from '@/features/order/services/order-my.service'; import type { PrismaClient } from '@/generated/prisma/client'; import { disconnectTestPrismaClient } from '@/test/db/prisma-test-client'; @@ -9,6 +11,7 @@ import { createAccount, createOrder, createOrderItem, + createPayment, createProduct, createReview, createStore, @@ -19,6 +22,7 @@ import { outboxPublisherProviders } from '@/test/outbox'; describe('UserOrderService (real DB)', () => { let service: UserOrderService; + let clock: ClockService; let prisma: PrismaClient; beforeAll(async () => { @@ -26,12 +30,14 @@ describe('UserOrderService (real DB)', () => { providers: [ UserOrderService, OrderRepository, + PaymentRepository, { provide: AUDIT_LOG_REPOSITORY, useClass: AuditLogRepository }, // 발행 repository가 OutboxPublisher를 주입받는다(08b) ...outboxPublisherProviders(), ], }); service = module.get(UserOrderService); + clock = module.get(ClockService); prisma = p; }); @@ -44,6 +50,10 @@ describe('UserOrderService (real DB)', () => { await truncateAll(); }); + afterEach(() => { + jest.restoreAllMocks(); + }); + async function setupUser() { const account = await createAccount(prisma, { account_type: 'USER' }); await createUserProfile(prisma, { account_id: account.id }); @@ -519,4 +529,184 @@ describe('UserOrderService (real DB)', () => { }); }); }); + + describe('결제 출력', () => { + it('상세는 입금 안내를, 목록은 결제 대기일 때만 입금 기한을 싣는다', async () => { + const account = await setupUser(); + const expiresAt = new Date('2026-09-16T08:00:00.000Z'); + const pending = await createOrder(prisma, { + account_id: account.id, + status: 'PENDING_PAYMENT', + }); + await createPayment(prisma, { + order_id: pending.id, + depositor_name: '차차맘', + expires_at: expiresAt, + }); + const confirmed = await createOrder(prisma, { + account_id: account.id, + status: 'SUBMITTED', + }); + await createPayment(prisma, { + order_id: confirmed.id, + status: 'CONFIRMED', + confirmed_at: expiresAt, + }); + const legacy = await createOrder(prisma, { + account_id: account.id, + status: 'SUBMITTED', + }); + + const detail = await service.getMyOrder(account.id, pending.id); + expect(detail.payment).toEqual({ + method: 'BANK_TRANSFER', + status: 'PENDING', + amount: pending.total_price, + depositorName: '차차맘', + depositBank: { code: '004', name: 'KB국민은행' }, + depositAccountNumber: '12345678901234', + depositAccountHolder: '케이퀵', + expiresAt, + buyerClaimedAt: null, + confirmedAt: null, + confirmSource: null, + }); + expect((await service.getMyOrder(account.id, legacy.id)).payment).toBe( + null, + ); + + const list = await service.listMyOrders(account.id); + const expiresById = new Map( + list.items.map((item) => [item.orderId, item.paymentExpiresAt]), + ); + expect(expiresById).toEqual( + new Map([ + [pending.id.toString(), expiresAt], + [confirmed.id.toString(), null], + [legacy.id.toString(), null], + ]), + ); + }); + }); + + describe('markMyOrderDepositSent', () => { + const NOW = new Date('2026-09-16T07:30:00.000Z'); + const EXPIRES_AT = new Date('2026-09-16T08:00:00.000Z'); + + async function pendingOrder(accountId: bigint) { + const order = await createOrder(prisma, { + account_id: accountId, + status: 'PENDING_PAYMENT', + }); + await createPayment(prisma, { + order_id: order.id, + depositor_name: '차차맘', + expires_at: EXPIRES_AT, + }); + return order; + } + + const claimedCount = () => + prisma.payment.count({ where: { buyer_claimed_at: { not: null } } }); + + it('기한 전 첫 누름은 시각을 기록한다', async () => { + const account = await setupUser(); + const order = await pendingOrder(account.id); + jest.spyOn(clock, 'now').mockReturnValue(NOW); + + const result = await service.markMyOrderDepositSent(account.id, order.id); + + expect(result.payment).toMatchObject({ buyerClaimedAt: NOW }); + await expect( + prisma.payment.findUniqueOrThrow({ where: { order_id: order.id } }), + ).resolves.toMatchObject({ buyer_claimed_at: NOW, status: 'PENDING' }); + }); + + it('다시 누르면 기한이 지났어도 바꾸지 않고 그대로 돌려준다(멱등)', async () => { + const account = await setupUser(); + const order = await pendingOrder(account.id); + jest.spyOn(clock, 'now').mockReturnValue(NOW); + await service.markMyOrderDepositSent(account.id, order.id); + + jest + .spyOn(clock, 'now') + .mockReturnValue(new Date('2026-09-16T09:00:00Z')); + const again = await service.markMyOrderDepositSent(account.id, order.id); + + expect(again.payment).toMatchObject({ buyerClaimedAt: NOW }); + }); + + it.each([ + ['기한 정각', EXPIRES_AT], + ['기한 뒤', new Date(EXPIRES_AT.getTime() + 1)], + ])( + '누르지 않은 채 %s이면 PAYMENT_DEADLINE_PASSED다', + async (_case, now) => { + const account = await setupUser(); + const order = await pendingOrder(account.id); + jest.spyOn(clock, 'now').mockReturnValue(now); + + await expect( + service.markMyOrderDepositSent(account.id, order.id), + ).rejects.toThrowDomain('PAYMENT_DEADLINE_PASSED'); + expect(await claimedCount()).toBe(0); + }, + ); + + it('기한 1ms 전이면 받는다', async () => { + const account = await setupUser(); + const order = await pendingOrder(account.id); + jest + .spyOn(clock, 'now') + .mockReturnValue(new Date(EXPIRES_AT.getTime() - 1)); + + await expect( + service.markMyOrderDepositSent(account.id, order.id), + ).resolves.toMatchObject({ status: 'PENDING_PAYMENT' }); + }); + + it.each< + [string, 'SUBMITTED' | 'CANCELED', 'CONFIRMED' | 'CANCELED' | null] + >([ + ['입금 확인된 주문', 'SUBMITTED', 'CONFIRMED'], + ['입금 전 취소된 주문', 'CANCELED', 'CANCELED'], + ['결제 기록이 없는 주문', 'SUBMITTED', null], + ])('%s은 PAYMENT_NOT_PENDING이다', async (_case, status, paymentStatus) => { + const account = await setupUser(); + const order = await createOrder(prisma, { + account_id: account.id, + status, + }); + if (paymentStatus) { + await createPayment(prisma, { + order_id: order.id, + status: paymentStatus, + }); + } + jest.spyOn(clock, 'now').mockReturnValue(NOW); + + await expect( + service.markMyOrderDepositSent(account.id, order.id), + ).rejects.toThrowDomain('PAYMENT_NOT_PENDING'); + }); + + it('다른 계정·삭제된 주문은 ORDER_NOT_FOUND다', async () => { + const account = await setupUser(); + const other = await setupUser(); + const order = await pendingOrder(other.id); + const deleted = await pendingOrder(account.id); + await prisma.order.update({ + where: { id: deleted.id }, + data: { deleted_at: NOW }, + }); + jest.spyOn(clock, 'now').mockReturnValue(NOW); + + for (const id of [order.id, deleted.id]) { + await expect( + service.markMyOrderDepositSent(account.id, id), + ).rejects.toThrowDomain('ORDER_NOT_FOUND'); + } + expect(await claimedCount()).toBe(0); + }); + }); }); diff --git a/src/features/order/services/order-my.service.ts b/src/features/order/services/order-my.service.ts index 2ee8d5df..121b1c21 100644 --- a/src/features/order/services/order-my.service.ts +++ b/src/features/order/services/order-my.service.ts @@ -1,24 +1,51 @@ import { Injectable } from '@nestjs/common'; import { DomainException } from '@/common/errors/error-catalog'; +import { ClockService } from '@/common/providers/clock.service'; import { calcDiscountRate } from '@/common/utils/discount-rate'; import { sliceOverfetched } from '@/common/utils/pagination'; import type { MyOrdersInput } from '@/features/order/dto/inputs/my-orders.input'; import { OrderRepository } from '@/features/order/repositories/order.repository'; +import { PaymentRepository } from '@/features/order/repositories/payment.repository'; import { toOrderItemDetail, toOrderStatusHistory, } from '@/features/order/services/order-output-mappers.helper'; +import { toOrderPaymentOutput } from '@/features/order/services/order-payment-mappers.helper'; import type { MyOrderConnection, MyOrderDetail, } from '@/features/order/types/order-my-output.type'; import { formatBusinessHours } from '@/features/store'; -import { OrderStatus } from '@/generated/prisma/client'; +import { OrderStatus, PaymentStatus } from '@/generated/prisma/client'; @Injectable() export class UserOrderService { - constructor(private readonly orderRepository: OrderRepository) {} + constructor( + private readonly orderRepository: OrderRepository, + private readonly payments: PaymentRepository, + private readonly clock: ClockService, + ) {} + + /** '입금했어요'. 마감 전 첫 누름만 기록해 미입금 자동 취소에서 빼고, 다시 누르면 그대로 돌려준다. */ + async markMyOrderDepositSent( + accountId: bigint, + orderId: bigint, + ): Promise { + const result = await this.payments.markDepositClaimed({ + orderId, + accountId, + now: this.clock.now(), + }); + if (result === 'not-found') throw new DomainException('ORDER_NOT_FOUND'); + if (result === 'not-pending') { + throw new DomainException('PAYMENT_NOT_PENDING'); + } + if (result === 'deadline-passed') { + throw new DomainException('PAYMENT_DEADLINE_PASSED'); + } + return this.getMyOrder(accountId, orderId); + } async listMyOrders( accountId: bigint, @@ -75,6 +102,10 @@ export class UserOrderService { storeName: firstItem?.store_name_snapshot ?? '매장 정보 없음', regionLabel: firstItem?.store_region_label_snapshot ?? null, hasReviewableItem: reviewableOrderIds.has(order.id.toString()), + paymentExpiresAt: + order.payment?.status === PaymentStatus.PENDING + ? order.payment.expires_at + : null, }; }), totalCount, @@ -105,6 +136,7 @@ export class UserOrderService { buyerName: order.buyer_name, buyerPhone: order.buyer_phone, requestNote: order.request_note, + payment: order.payment ? toOrderPaymentOutput(order.payment) : null, subtotalPrice: order.subtotal_price, discountPrice: order.discount_price, totalPrice: order.total_price, diff --git a/src/features/order/services/order-payment-mappers.helper.ts b/src/features/order/services/order-payment-mappers.helper.ts index 60cf27b1..4babc69b 100644 --- a/src/features/order/services/order-payment-mappers.helper.ts +++ b/src/features/order/services/order-payment-mappers.helper.ts @@ -1,14 +1,24 @@ import type { PaymentSettingRow } from '@/features/order/repositories/payment-setting.repository'; +import type { + OrderPaymentRow, + PendingPaymentRow, +} from '@/features/order/repositories/payment.repository'; import { maskAccountNumber, toBank, } from '@/features/order/services/order-bank-account.helper'; import type { + AdminOrderPaymentOutput, AdminPaymentSettingOutput, + AdminPendingPaymentOutput, AdminStoreSettlementAccountOutput, + OrderPaymentOutput, SellerSettlementAccountOutput, } from '@/features/order/types/order-payment-output.type'; -import type { StoreSettlementAccount } from '@/generated/prisma/client'; +import type { + Payment, + StoreSettlementAccount, +} from '@/generated/prisma/client'; export function toAdminPaymentSettingOutput( row: PaymentSettingRow, @@ -44,3 +54,49 @@ export function toAdminStoreSettlementAccountOutput( accountNumber, }; } + +export function toOrderPaymentOutput(row: OrderPaymentRow): OrderPaymentOutput { + return { + method: row.method, + status: row.status, + amount: row.amount, + depositorName: row.depositor_name, + depositBank: toBank(row.deposit_bank_code), + depositAccountNumber: row.deposit_account_number, + depositAccountHolder: row.deposit_account_holder, + expiresAt: row.expires_at, + buyerClaimedAt: row.buyer_claimed_at, + confirmedAt: row.confirmed_at, + confirmSource: row.confirm_source, + }; +} + +export function toAdminOrderPaymentOutput( + row: Payment, +): AdminOrderPaymentOutput { + return { + ...toOrderPaymentOutput(row), + confirmedByLabel: row.confirmed_by_label_snapshot, + confirmNote: row.confirm_note, + }; +} + +export function toAdminPendingPaymentOutput( + row: PendingPaymentRow, +): AdminPendingPaymentOutput { + const [firstItem] = row.order.items; + return { + orderId: row.order.id.toString(), + orderNumber: row.order.order_number, + storeName: firstItem?.store_name_snapshot ?? null, + productName: firstItem?.product_name_snapshot ?? null, + amount: row.amount, + depositorName: row.depositor_name, + buyerName: row.order.buyer_name, + buyerPhone: row.order.buyer_phone, + createdAt: row.order.created_at, + expiresAt: row.expires_at, + buyerClaimedAt: row.buyer_claimed_at, + pickupAt: row.order.pickup_at, + }; +} diff --git a/src/features/order/services/order-seller.service.spec.ts b/src/features/order/services/order-seller.service.spec.ts index 863be011..6a468a75 100644 --- a/src/features/order/services/order-seller.service.spec.ts +++ b/src/features/order/services/order-seller.service.spec.ts @@ -15,6 +15,7 @@ import { createAccount, createOrder, createOrderItem, + createPayment, createProduct, setupSellerWithStore, } from '@/test/factories'; @@ -339,6 +340,17 @@ describe('SellerOrderService (real DB)', () => { expect(result.items).toHaveLength(1); expect(result.statusHistories).toHaveLength(1); expect(result.statusHistories[0].toStatus).toBe('CONFIRMED'); + // 결제 도입 전 주문은 결제 수단이 없다 + expect(result.paymentMethod).toBeNull(); + }); + + it('결제가 있으면 결제 수단을 준다', async () => { + const { account, store } = await setupSellerWithStore(prisma); + const order = await createStoreOrder(store.id, { status: 'SUBMITTED' }); + await createPayment(prisma, { order_id: order.id, status: 'CONFIRMED' }); + + const result = await service.sellerOrder(account.id, order.id); + expect(result.paymentMethod).toBe('BANK_TRANSFER'); }); it('soft-delete된 아이템·상태 이력은 상세에서 제외한다', async () => { @@ -598,6 +610,7 @@ describe('SellerOrderService (real DB)', () => { }); expect(topic.received).toEqual([ { + kind: 'STATUS_CHANGED', orderId: order.id.toString(), orderNumber: order.order_number, status: 'CONFIRMED', diff --git a/src/features/order/services/order-seller.service.ts b/src/features/order/services/order-seller.service.ts index a558e2d5..e3a5b540 100644 --- a/src/features/order/services/order-seller.service.ts +++ b/src/features/order/services/order-seller.service.ts @@ -34,7 +34,7 @@ import type { SellerOrderSummaryOutput, } from '@/features/order/types/order-seller-output.type'; import { SellerBaseService, StoreSellerRepository } from '@/features/store'; -import { OrderStatus } from '@/generated/prisma/client'; +import { OrderStatus, type PaymentMethod } from '@/generated/prisma/client'; @Injectable() export class SellerOrderService extends SellerBaseService { @@ -140,6 +140,7 @@ export class SellerOrderService extends SellerBaseService { await this.events.publishSellerOrderUpdate( ctx.storeId, toSellerOrderUpdateEvent( + 'STATUS_CHANGED', updated, updated.items[0]?.product_name_snapshot ?? '', ), @@ -172,6 +173,7 @@ export class SellerOrderService extends SellerBaseService { buyer_name: string; buyer_phone: string; request_note: string | null; + payment: { method: PaymentMethod } | null; subtotal_price: number; discount_price: number; total_price: number; @@ -194,6 +196,7 @@ export class SellerOrderService extends SellerBaseService { buyerName: row.buyer_name, buyerPhone: row.buyer_phone, requestNote: row.request_note, + paymentMethod: row.payment?.method ?? null, subtotalPrice: row.subtotal_price, discountPrice: row.discount_price, totalPrice: row.total_price, diff --git a/src/features/order/services/order-subscription.service.spec.ts b/src/features/order/services/order-subscription.service.spec.ts index 0b0a1852..e5682d86 100644 --- a/src/features/order/services/order-subscription.service.spec.ts +++ b/src/features/order/services/order-subscription.service.spec.ts @@ -53,6 +53,7 @@ describe('OrderSubscriptionService (real DB)', () => { } const event: SellerOrderUpdateEvent = { + kind: 'SUBMITTED', orderId: '1', orderNumber: 'ORD-1', status: 'SUBMITTED', diff --git a/src/features/order/services/order-subscription.service.ts b/src/features/order/services/order-subscription.service.ts index 73cba040..9f05ed44 100644 --- a/src/features/order/services/order-subscription.service.ts +++ b/src/features/order/services/order-subscription.service.ts @@ -4,7 +4,7 @@ import { DomainException } from '@/common/errors/error-catalog'; import { OrderEventsService } from '@/features/order/services/order-events.service'; import { StoreSellerRepository } from '@/features/store'; -/** 이벤트 발행은 각 쓰기 서비스(체크아웃·판매자 상태 변경·관리자 취소)가 담당한다. */ +/** 이벤트 발행은 각 쓰기 서비스(입금 확인·판매자 상태 변경·관리자 취소)가 담당한다. */ @Injectable() export class OrderSubscriptionService { constructor( diff --git a/src/features/order/types/create-order-output.type.ts b/src/features/order/types/create-order-output.type.ts index a7da52ee..e9eff985 100644 --- a/src/features/order/types/create-order-output.type.ts +++ b/src/features/order/types/create-order-output.type.ts @@ -1,3 +1,4 @@ +import type { OrderPaymentOutput } from '@/features/order/types/order-payment-output.type'; import type { OrderStatus } from '@/generated/prisma/client'; export interface CreateOrderOutput { @@ -6,4 +7,5 @@ export interface CreateOrderOutput { status: OrderStatus; pickupAt: Date; totalPrice: number; + payment: OrderPaymentOutput | null; } diff --git a/src/features/order/types/order-admin-output.type.ts b/src/features/order/types/order-admin-output.type.ts index 7527ade4..e4f727fc 100644 --- a/src/features/order/types/order-admin-output.type.ts +++ b/src/features/order/types/order-admin-output.type.ts @@ -2,6 +2,7 @@ import type { OrderItemDetailOutput, OrderStatusHistoryOutput, } from '@/features/order/types/order-output.type'; +import type { AdminOrderPaymentOutput } from '@/features/order/types/order-payment-output.type'; import type { AccountStatus, OrderStatus } from '@/generated/prisma/client'; export interface AdminOrderSummaryOutput { @@ -40,6 +41,7 @@ export interface AdminOrderDetailOutput { buyerName: string; buyerPhone: string; requestNote: string | null; + payment: AdminOrderPaymentOutput | null; subtotalPrice: number; discountPrice: number; totalPrice: number; diff --git a/src/features/order/types/order-my-output.type.ts b/src/features/order/types/order-my-output.type.ts index 819da811..808e41d6 100644 --- a/src/features/order/types/order-my-output.type.ts +++ b/src/features/order/types/order-my-output.type.ts @@ -3,6 +3,7 @@ import type { OrderItemDetailOutput, OrderStatusHistoryOutput, } from '@/features/order/types/order-output.type'; +import type { OrderPaymentOutput } from '@/features/order/types/order-payment-output.type'; import type { OrderStatus } from '@/generated/prisma/client'; export interface MyOrderSummary { @@ -19,6 +20,7 @@ export interface MyOrderSummary { storeName: string; regionLabel: string | null; hasReviewableItem: boolean; + paymentExpiresAt: Date | null; } export type MyOrderConnection = OffsetConnection; @@ -53,6 +55,7 @@ export interface MyOrderDetail { buyerName: string; buyerPhone: string; requestNote: string | null; + payment: OrderPaymentOutput | null; subtotalPrice: number; discountPrice: number; totalPrice: number; diff --git a/src/features/order/types/order-payment-output.type.ts b/src/features/order/types/order-payment-output.type.ts index 74ba079e..cb8cfb26 100644 --- a/src/features/order/types/order-payment-output.type.ts +++ b/src/features/order/types/order-payment-output.type.ts @@ -1,4 +1,9 @@ -import type { OrderActor } from '@/generated/prisma/client'; +import type { + OrderActor, + PaymentConfirmSource, + PaymentMethod, + PaymentStatus, +} from '@/generated/prisma/client'; export interface BankOutput { code: string; @@ -26,3 +31,42 @@ export interface AdminStoreSettlementAccountOutput extends SellerSettlementAccou /** 원문. 관리자 상세에서만 복호화해 내려준다. */ accountNumber: string; } + +export interface OrderPaymentOutput { + method: PaymentMethod; + status: PaymentStatus; + amount: number; + depositorName: string; + depositBank: BankOutput; + depositAccountNumber: string; + depositAccountHolder: string; + expiresAt: Date; + buyerClaimedAt: Date | null; + confirmedAt: Date | null; + confirmSource: PaymentConfirmSource | null; +} + +export interface AdminOrderPaymentOutput extends OrderPaymentOutput { + confirmedByLabel: string | null; + confirmNote: string | null; +} + +export interface AdminPendingPaymentOutput { + orderId: string; + orderNumber: string; + storeName: string | null; + productName: string | null; + amount: number; + depositorName: string; + buyerName: string; + buyerPhone: string; + createdAt: Date; + expiresAt: Date; + buyerClaimedAt: Date | null; + pickupAt: Date; +} + +export interface AdminTaskCountsOutput { + claimedPayments: number; + pendingPayments: number; +} diff --git a/src/features/order/types/order-seller-output.type.ts b/src/features/order/types/order-seller-output.type.ts index b10dd95c..66cb8df5 100644 --- a/src/features/order/types/order-seller-output.type.ts +++ b/src/features/order/types/order-seller-output.type.ts @@ -2,7 +2,7 @@ import type { OrderItemDetailOutput, OrderStatusHistoryOutput, } from '@/features/order/types/order-output.type'; -import type { OrderStatus } from '@/generated/prisma/client'; +import type { OrderStatus, PaymentMethod } from '@/generated/prisma/client'; export interface SellerOrderSummaryOutput { id: string; @@ -26,6 +26,7 @@ export interface SellerOrderDetailOutput { buyerName: string; buyerPhone: string; requestNote: string | null; + paymentMethod: PaymentMethod | null; subtotalPrice: number; discountPrice: number; totalPrice: number; @@ -40,8 +41,13 @@ export interface SellerOrderDetailOutput { statusHistories: OrderStatusHistoryOutput[]; } +/** SDL SellerOrderUpdateKind. PICKUP_RESCHEDULED는 판매자 픽업 일시 변경이 발행한다. */ +export type SellerOrderUpdateKind = + 'SUBMITTED' | 'STATUS_CHANGED' | 'PICKUP_RESCHEDULED'; + /** 구독 이벤트 payload — Redis JSON 직렬화를 거치므로 날짜는 ISO 문자열. */ export interface SellerOrderUpdateEvent { + kind: SellerOrderUpdateKind; orderId: string; orderNumber: string; status: OrderStatus; diff --git a/src/test/admin-query-null-inputs.spec.ts b/src/test/admin-query-null-inputs.spec.ts index 4a48a8e9..82f7c234 100644 --- a/src/test/admin-query-null-inputs.spec.ts +++ b/src/test/admin-query-null-inputs.spec.ts @@ -44,7 +44,7 @@ import { createTestingModuleWithRealDb } from '@/test/modules/testing-module.bui // admin 접두 Query 전수에 nullable 필드를 전부 null로 채워 실제 앱(파이프·필터·가드·실DB)으로 보낸다. const FEATURES_DIR = join(__dirname, '..', 'features'); -const ADMIN_QUERY_COUNT = 17; +const ADMIN_QUERY_COUNT = 18; /** 필수 스칼라의 최소 유효값. 새 스칼라가 필수 필드로 오면 표에 없다고 던져 결정을 강제한다 */ const MINIMAL_SCALARS: Record = { diff --git a/src/test/factories/order.factory.ts b/src/test/factories/order.factory.ts index b81ecf56..86b11800 100644 --- a/src/test/factories/order.factory.ts +++ b/src/test/factories/order.factory.ts @@ -4,7 +4,9 @@ import type { Order, OrderItem, OrderStatus, + Payment, PaymentSetting, + PaymentStatus, PrismaClient, } from '@/generated/prisma/client'; import { activeWhere } from '@/prisma'; @@ -94,6 +96,47 @@ export async function createPaymentSetting( }); } +export interface PaymentOverrides { + /** 미지정 시 입금 대기 주문을 새로 만든다 */ + order_id?: bigint; + status?: PaymentStatus; + /** 미지정 시 주문 total_price */ + amount?: number; + depositor_name?: string; + expires_at?: Date; + buyer_claimed_at?: Date | null; + confirmed_at?: Date | null; +} + +/** 계좌이체 결제. 계좌 스냅샷은 createPaymentSetting 기본값과 같다. */ +export async function createPayment( + prisma: PrismaClient, + overrides: PaymentOverrides = {}, +): Promise { + const order = overrides.order_id + ? await prisma.order.findUniqueOrThrow({ + where: { id: overrides.order_id }, + }) + : await createOrder(prisma, { status: 'PENDING_PAYMENT' }); + return prisma.payment.create({ + data: { + order_id: order.id, + method: 'BANK_TRANSFER', + status: overrides.status ?? 'PENDING', + amount: overrides.amount ?? order.total_price, + depositor_name: overrides.depositor_name ?? order.buyer_name.slice(0, 20), + deposit_bank_code: '004', + deposit_account_number: '12345678901234', + deposit_account_holder: '케이퀵', + expires_at: + overrides.expires_at ?? + new Date(order.created_at.getTime() + 3_600_000), + buyer_claimed_at: overrides.buyer_claimed_at ?? null, + confirmed_at: overrides.confirmed_at ?? null, + }, + }); +} + export interface OrderItemOverrides { order_id?: bigint; store_id?: bigint; diff --git a/src/test/roles-coverage.spec.ts b/src/test/roles-coverage.spec.ts index 09d8b41b..acb3d2fc 100644 --- a/src/test/roles-coverage.spec.ts +++ b/src/test/roles-coverage.spec.ts @@ -14,7 +14,7 @@ describe('접두 루트 필드 인가 커버리지', () => { describe.each([ ['seller', 'SELLER', 58], - ['admin', 'ADMIN', 64], + ['admin', 'ADMIN', 67], ] as const)('%s 접두 → @Roles(%s)', (prefix, role, count) => { const fields = collectRootFieldsWithPrefix(prefix); From a4491312d8c08159d7cf4664afd1c0310c6c9d27 Mon Sep 17 00:00:00 2001 From: chanwoo7 Date: Thu, 19 Nov 2026 03:15:04 +0900 Subject: [PATCH 17/54] =?UTF-8?q?fix:=20=EC=A3=BC=EB=AC=B8=20=EC=83=9D?= =?UTF-8?q?=EC=84=B1=20tx=EA=B0=80=20timeout=EC=9C=BC=EB=A1=9C=20=EB=A7=8C?= =?UTF-8?q?=EB=A3=8C=EB=8F=BC=EB=8F=84=20=EA=B3=84=EC=A0=95=20=EC=9E=A0?= =?UTF-8?q?=EA=B8=88=EC=9D=B4=20=EB=82=A8=EC=A7=80=20=EC=95=8A=EA=B2=8C=20?= =?UTF-8?q?=ED=95=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 주문 생성 tx가 timeout(10초)을 넘기면 Prisma가 ROLLBACK 뒤 연결을 풀로 돌려줘 finally의 RELEASE_LOCK이 만료된 tx 오류로 서버에 가지 않는다. MySQL 풀 반납은 ROLLBACK만 보내 세션 잠금(GET_LOCK)이 그 연결에 남고, 같은 계정의 주문은 다른 연결에서 3초씩 기다린 뒤 CONCURRENT_REQUEST를 받는다(연결이 닫힐 때까지). GET_LOCK 이름은 서버 전역이라 같은 서버를 쓰는 다른 스키마(테스트 워커 DB 등)의 같은 계정 id와도 겹쳤다. - withPendingPaymentLock: GET_LOCK과 함께 CONNECTION_ID()를 읽어 두고, RELEASE_LOCK이 실패하면 tx 밖 클라이언트로 KILL을 보내 그 세션을 끊는다. KILL 실패(세션이 이미 없음)는 무시하고 원래 오류를 그대로 던진다. - 잠금 이름을 CONCAT(DATABASE(), ':pending-payment:', id)로 바꾸고 pendingPaymentLockName으로 내보내 테스트의 수동 GET_LOCK·IS_USED_LOCK도 같은 이름을 쓴다. 테스트: timeout 1초 tx 안에서 SLEEP(2)로 만료시킨 뒤 IS_USED_LOCK이 NULL이고 같은 계정의 다음 주문이 받아지는지 1건 추가. KILL을 빼면 잠금이 남아(IS_USED_LOCK = 연결 id) 실패하는 것을 확인했다. --- .../order-pending-payment-lock.helper.ts | 24 +++++++---- .../repositories/order.repository.spec.ts | 41 +++++++++++++++++-- .../order/repositories/order.repository.ts | 2 +- .../services/order-checkout.service.spec.ts | 3 +- 4 files changed, 58 insertions(+), 12 deletions(-) diff --git a/src/features/order/repositories/order-pending-payment-lock.helper.ts b/src/features/order/repositories/order-pending-payment-lock.helper.ts index c6addb1f..778b1b29 100644 --- a/src/features/order/repositories/order-pending-payment-lock.helper.ts +++ b/src/features/order/repositories/order-pending-payment-lock.helper.ts @@ -1,32 +1,42 @@ -import { OrderStatus, type Prisma } from '@/generated/prisma/client'; +import { OrderStatus, Prisma } from '@/generated/prisma/client'; /** 계정당 동시 입금 대기 주문 상한. */ export const PENDING_PAYMENT_LIMIT = 2; /** tx timeout(10초)보다 짧아야 대기 중 tx가 먼저 끊기지 않는다. */ const LOCK_WAIT_SECONDS = 3; -function lockName(accountId: bigint): string { - return `pending-payment:${accountId}`; +/** GET_LOCK 이름은 서버 전역이라 스키마를 붙인다 — 같은 서버의 다른 스키마에서 같은 계정 id와 겹치지 않게. */ +export function pendingPaymentLockName(accountId: bigint): Prisma.Sql { + return Prisma.sql`CONCAT(DATABASE(), ':pending-payment:', ${accountId})`; } /** * 같은 계정의 주문 생성을 직렬화한다. GET_LOCK은 연결(세션) 단위라 tx 콜백 안에서 잡고 같은 콜백의 finally에서 푼다 — * 커밋 뒤에는 같은 연결로 문장을 보낼 수 없어, 밖에서 풀거나 해제를 빼면 풀 연결에 잠금이 남는다. + * tx가 timeout으로 만료되면 연결이 이미 풀로 돌아가 해제를 보낼 수 없으므로 tx 밖 클라이언트(`outer`)로 그 세션을 끊는다. * 0(시간 초과)·NULL(오류)이면 'lock-timeout'. */ export async function withPendingPaymentLock( tx: Prisma.TransactionClient, + outer: Prisma.TransactionClient, accountId: bigint, fn: () => Promise, ): Promise { - const name = lockName(accountId); - const [row] = await tx.$queryRaw<{ acquired: unknown }[]>` - SELECT GET_LOCK(${name}, ${LOCK_WAIT_SECONDS}) AS acquired`; + const name = pendingPaymentLockName(accountId); + const [row] = await tx.$queryRaw< + { acquired: unknown; connectionId: bigint }[] + >` + SELECT GET_LOCK(${name}, ${LOCK_WAIT_SECONDS}) AS acquired, CONNECTION_ID() AS connectionId`; if (Number(row.acquired) !== 1) return 'lock-timeout'; try { return await fn(); } finally { - await tx.$queryRaw`SELECT RELEASE_LOCK(${name})`; + try { + await tx.$queryRaw`SELECT RELEASE_LOCK(${name})`; + } catch { + // KILL 실패는 무시한다 — 끊을 세션이 이미 없으면 잠금도 이미 풀렸다. + await Promise.allSettled([outer.$executeRaw`KILL ${row.connectionId}`]); + } } } diff --git a/src/features/order/repositories/order.repository.spec.ts b/src/features/order/repositories/order.repository.spec.ts index 6a91f873..c3a48d2b 100644 --- a/src/features/order/repositories/order.repository.spec.ts +++ b/src/features/order/repositories/order.repository.spec.ts @@ -3,6 +3,10 @@ import { AuditLogRepository } from '@/features/audit-log/repositories/audit-log. import { NotificationAdminRepository } from '@/features/notification/repositories/notification-admin.repository'; import { NotificationRepository } from '@/features/notification/repositories/notification.repository'; import { NotificationOutboxConsumer } from '@/features/notification/services/notification-outbox.consumer'; +import { + pendingPaymentLockName, + withPendingPaymentLock, +} from '@/features/order/repositories/order-pending-payment-lock.helper'; import { type CreatePendingPaymentOrderArgs, type DailyCapacityGuard, @@ -1097,9 +1101,40 @@ describe('OrderRepository (real DB)', () => { ), ).rejects.toMatchObject({ code: 'P2002' }); - const [row] = await prisma.$queryRaw<{ used: unknown }[]>` - SELECT IS_USED_LOCK(${`pending-payment:${buyer.id}`}) AS used`; - expect(row.used).toBeNull(); + expect(await lockHolder(buyer.id)).toBeNull(); + }); + + it('tx가 timeout으로 만료돼 해제를 보내지 못해도 그 세션을 끊어 계정 잠금이 남지 않는다', async () => { + const buyer = await setupBuyer(); + const store = await createStore(prisma); + const product = await createProduct(prisma, { store_id: store.id }); + + await expect( + prisma.$transaction( + (tx) => + withPendingPaymentLock(tx, prisma, buyer.id, async () => { + await tx.$queryRaw`SELECT SLEEP(2)`; + }), + { timeout: 1_000 }, + ), + ).rejects.toThrow(); + + // 끊긴 세션의 잠금 해제는 KILL 응답 직후 비동기로 끝난다. + for (let i = 0; i < 20 && (await lockHolder(buyer.id)) !== null; i++) { + await new Promise((resolve) => setTimeout(resolve, 100)); + } + expect(await lockHolder(buyer.id)).toBeNull(); + await expect( + repo.createPendingPaymentOrder( + createArgs({ buyerId: buyer.id, store, product }), + ), + ).resolves.toMatchObject({ status: 'PENDING_PAYMENT' }); }); + + async function lockHolder(accountId: bigint): Promise { + const [row] = await prisma.$queryRaw<{ holder: unknown }[]>` + SELECT IS_USED_LOCK(${pendingPaymentLockName(accountId)}) AS holder`; + return row.holder; + } }); }); diff --git a/src/features/order/repositories/order.repository.ts b/src/features/order/repositories/order.repository.ts index 65e7de63..797baa8d 100644 --- a/src/features/order/repositories/order.repository.ts +++ b/src/features/order/repositories/order.repository.ts @@ -283,7 +283,7 @@ export class OrderRepository { ): Promise { return this.prisma.$transaction( (tx) => - withPendingPaymentLock(tx, args.accountId, async () => { + withPendingPaymentLock(tx, this.prisma, args.accountId, async () => { const pending = await countPendingPaymentOrdersLocked( tx, args.accountId, diff --git a/src/features/order/services/order-checkout.service.spec.ts b/src/features/order/services/order-checkout.service.spec.ts index b669ba0b..ce47f52a 100644 --- a/src/features/order/services/order-checkout.service.spec.ts +++ b/src/features/order/services/order-checkout.service.spec.ts @@ -6,6 +6,7 @@ import { AUDIT_LOG_REPOSITORY } from '@/features/audit-log'; import { AuditLogRepository } from '@/features/audit-log/repositories/audit-log.repository'; import type { CreateOrderInput } from '@/features/order/dto/inputs/create-order.input'; import { ORDER_SUBMITTED } from '@/features/order/events/order-submitted.event'; +import { pendingPaymentLockName } from '@/features/order/repositories/order-pending-payment-lock.helper'; import { OrderRepository } from '@/features/order/repositories/order.repository'; import { PaymentSettingRepository } from '@/features/order/repositories/payment-setting.repository'; import { OrderCheckoutService } from '@/features/order/services/order-checkout.service'; @@ -1534,7 +1535,7 @@ describe('OrderCheckoutService (real DB)', () => { const gate = new Promise((resolve) => (release = resolve)); let locked!: () => void; const lockedSignal = new Promise((resolve) => (locked = resolve)); - const name = `pending-payment:${buyer.id}`; + const name = pendingPaymentLockName(buyer.id); const holder = prisma.$transaction( async (tx) => { await tx.$queryRaw`SELECT GET_LOCK(${name}, 0)`; From d883eb998ab5d70ad3c48d2041121593b89e9e42 Mon Sep 17 00:00:00 2001 From: chanwoo7 Date: Thu, 19 Nov 2026 03:15:20 +0900 Subject: [PATCH 18/54] =?UTF-8?q?fix:=20=EC=9E=85=EA=B8=88=20=ED=99=95?= =?UTF-8?q?=EC=9D=B8=20=ED=8C=90=EC=A0=95=20=EC=9E=AC=EB=A3=8C=EB=A5=BC=20?= =?UTF-8?q?=EC=9E=A0=EA=B8=88=20=EC=9D=BD=EA=B8=B0=EC=97=90=EC=84=9C=20?= =?UTF-8?q?=EA=B0=80=EC=A0=B8=EC=98=B4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit confirmPaymentLocked는 주문·결제를 FOR UPDATE로 잠근 뒤 판정 재료(주문 상태·결제 상태·금액·픽업 일시)를 일관성 읽기(findUniqueOrThrow)로 다시 읽었다. 후속 중계 연동처럼 호출 tx가 앞서 일반 SELECT로 스냅샷을 만든 상태 (REPEATABLE READ)라면 잠금을 기다리는 사이 다른 관리자가 커밋한 확인을 보지 못하고 PENDING으로 판정해 이중 확인(이력 2건, order.submitted·감사 중복, 처리자 덮어쓰기)한다. - 주문은 SELECT id, status, pickup_at … FOR UPDATE, 결제는 SELECT id, status, amount … FOR UPDATE의 결과로 판정하고 findUniqueOrThrow를 지웠다. raw는 INT UNSIGNED를 bigint로 돌려줘 금액은 number로 바꿔 넘긴다. 테스트: 바깥 tx가 payment.count()로 스냅샷을 만든 사이 confirmPayment(ADMIN)가 커밋하고, 이어서 같은 tx에서 confirmPaymentLocked(AUTO)를 부르면 PAYMENT_NOT_PENDING이고 이력 1건·처리 경로 ADMIN이 유지되는지 1건 추가. 일관성 읽기로 되돌리면 두 번째 확인이 성공해 실패하는 것을 확인했다. --- .../order-transition.repository.spec.ts | 47 +++++++++++++++++++ .../order-transition.repository.ts | 30 ++++++------ 2 files changed, 63 insertions(+), 14 deletions(-) diff --git a/src/features/order/repositories/order-transition.repository.spec.ts b/src/features/order/repositories/order-transition.repository.spec.ts index 5a5874ef..71efaf29 100644 --- a/src/features/order/repositories/order-transition.repository.spec.ts +++ b/src/features/order/repositories/order-transition.repository.spec.ts @@ -1,6 +1,7 @@ import { AUDIT_LOG_REPOSITORY } from '@/features/audit-log'; import { AuditLogRepository } from '@/features/audit-log/repositories/audit-log.repository'; import { ORDER_STATUS_CHANGED } from '@/features/order/events/order-status-changed.event'; +import { assertPaymentConfirmable } from '@/features/order/policies/payment-confirm.policy'; import { OrderTransitionRepository, type ConfirmPaymentArgs, @@ -128,5 +129,51 @@ describe('OrderTransitionRepository (real DB)', () => { }); expect(await prisma.outbox.count()).toBe(0); }); + + it('호출 tx가 먼저 스냅샷을 만들었어도 그사이 커밋된 확인을 보고 다시 확인하지 않는다', async () => { + const order = await createOrder(prisma, { + status: 'PENDING_PAYMENT', + pickup_at: new Date(NOW.getTime() + 48 * 60 * 60_000), + }); + await createPayment(prisma, { order_id: order.id, amount: 10_000 }); + const args = await confirmArgs(order.id); + let snapshotTaken!: () => void; + const snapshot = new Promise( + (resolve) => (snapshotTaken = resolve), + ); + let proceed!: () => void; + const gate = new Promise((resolve) => (proceed = resolve)); + + const auto = prisma.$transaction( + async (tx) => { + await tx.payment.count(); + snapshotTaken(); + await gate; + return repo.confirmPaymentLocked(tx, { + ...args, + source: 'AUTO', + assertConfirmable: (state) => + assertPaymentConfirmable(state, args.depositedAmount, NOW), + }); + }, + { timeout: 20_000 }, + ); + await snapshot; + try { + await repo.confirmPayment(args); + } finally { + proceed(); + } + + await expect(auto).rejects.toThrowDomain('PAYMENT_NOT_PENDING'); + expect( + await prisma.orderStatusHistory.count({ + where: { order_id: order.id }, + }), + ).toBe(1); + await expect( + prisma.payment.findUniqueOrThrow({ where: { order_id: order.id } }), + ).resolves.toMatchObject({ confirm_source: 'ADMIN' }); + }); }); }); diff --git a/src/features/order/repositories/order-transition.repository.ts b/src/features/order/repositories/order-transition.repository.ts index 5c42658d..d9a201fc 100644 --- a/src/features/order/repositories/order-transition.repository.ts +++ b/src/features/order/repositories/order-transition.repository.ts @@ -73,27 +73,29 @@ export class OrderTransitionRepository { tx: Prisma.TransactionClient, args: ConfirmPaymentArgs, ): Promise { - const [locked] = await tx.$queryRaw<{ id: bigint }[]>` - SELECT id FROM \`order\` + // 판정 재료는 잠금 읽기에서 가져온다 — 호출 tx가 앞서 만든 스냅샷은 그사이 커밋된 확인을 보지 못한다. + const [locked] = await tx.$queryRaw< + { id: bigint; status: OrderStatus; pickup_at: Date }[] + >` + SELECT id, status, pickup_at FROM \`order\` WHERE id = ${args.orderId} AND deleted_at IS NULL FOR UPDATE`; if (!locked) return null; - await tx.$queryRaw`SELECT id FROM payment WHERE order_id = ${locked.id} FOR UPDATE`; - const order = await tx.order.findUniqueOrThrow({ - where: { id: locked.id }, - select: { status: true, pickup_at: true, payment: true }, - }); + const [payment] = await tx.$queryRaw< + { id: bigint; status: PaymentStatus; amount: bigint }[] + >`SELECT id, status, amount FROM payment WHERE order_id = ${locked.id} FOR UPDATE`; + // raw는 INT UNSIGNED를 bigint로 돌려준다. + const paymentAmount = payment ? Number(payment.amount) : null; args.assertConfirmable({ - orderStatus: order.status, - paymentStatus: order.payment?.status ?? null, - paymentAmount: order.payment?.amount ?? null, - pickupAt: order.pickup_at, + orderStatus: locked.status, + paymentStatus: payment?.status ?? null, + paymentAmount, + pickupAt: locked.pickup_at, }); - const payment = order.payment!; const confirmDeadlineAt = new Date( Math.min( args.now.getTime() + CONFIRM_WINDOW_MS, - order.pickup_at.getTime(), + locked.pickup_at.getTime(), ), ); const actorType = @@ -189,7 +191,7 @@ export class OrderTransitionRepository { beforeJson: { status: OrderStatus.PENDING_PAYMENT }, afterJson: { status: OrderStatus.SUBMITTED, - paymentAmount: payment.amount, + paymentAmount, depositedAmount: args.depositedAmount, confirmSource: args.source, note: args.note, From ee56e87cd783b431c9d4fa6234fe61905a1fea0f Mon Sep 17 00:00:00 2001 From: chanwoo7 Date: Thu, 19 Nov 2026 03:29:18 +0900 Subject: [PATCH 19/54] =?UTF-8?q?fix:=200=EC=9B=90=20=EC=A3=BC=EB=AC=B8?= =?UTF-8?q?=EC=9D=84=20=EC=9E=85=EA=B8=88=EC=95=A1=200=EC=9C=BC=EB=A1=9C?= =?UTF-8?q?=20=ED=99=95=EC=9D=B8=ED=95=A0=20=EC=88=98=20=EC=9E=88=EA=B2=8C?= =?UTF-8?q?=20=ED=95=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 판매가 0원(MIN_SALE_PRICE 0) 상품의 주문은 결제 금액이 0원인데, 입금액 1 이상 검사와 금액 일치 검사가 겹쳐 어떤 입금액으로도 확인할 수 없어 입금 대기에 묶였다. - adminConfirmPayment: 음수·비정수만 DEPOSIT_AMOUNT_INVALID, 0은 금액 일치 검사로 넘김 - 오류 메시지·SDL 설명·DTO 주석을 0 이상으로 정정 - 테스트: 0원 주문 입금액 0 접수, 30,000원 주문에 0은 DEPOSIT_AMOUNT_MISMATCH, 1.5는 DEPOSIT_AMOUNT_INVALID --- src/common/errors/error-catalog.ts | 2 +- .../dto/inputs/admin-confirm-payment.input.ts | 2 +- src/features/order/order-deposit-admin.graphql | 2 +- .../services/order-deposit-admin.service.spec.ts | 16 ++++++++++++++-- .../services/order-deposit-admin.service.ts | 2 +- 5 files changed, 18 insertions(+), 6 deletions(-) diff --git a/src/common/errors/error-catalog.ts b/src/common/errors/error-catalog.ts index 1c7831be..62e311e0 100644 --- a/src/common/errors/error-catalog.ts +++ b/src/common/errors/error-catalog.ts @@ -420,7 +420,7 @@ export const ERROR_CATALOG = { }, DEPOSIT_AMOUNT_INVALID: { status: HttpStatus.BAD_REQUEST, - message: '입금액은 1원 이상의 정수로 입력해 주세요.', + message: '입금액은 0원 이상의 정수로 입력해 주세요.', }, DEPOSIT_AMOUNT_MISMATCH: { status: HttpStatus.BAD_REQUEST, diff --git a/src/features/order/dto/inputs/admin-confirm-payment.input.ts b/src/features/order/dto/inputs/admin-confirm-payment.input.ts index ef927aaf..89f2bf3f 100644 --- a/src/features/order/dto/inputs/admin-confirm-payment.input.ts +++ b/src/features/order/dto/inputs/admin-confirm-payment.input.ts @@ -4,7 +4,7 @@ export class AdminConfirmPaymentInput { @IsString() orderId!: string; - // 1원 미만은 서비스가 DEPOSIT_AMOUNT_INVALID로 거절한다 + // 음수는 서비스가 DEPOSIT_AMOUNT_INVALID로 거절한다(0원 주문은 0으로 확인) @IsInt() depositedAmount!: number; diff --git a/src/features/order/order-deposit-admin.graphql b/src/features/order/order-deposit-admin.graphql index 23f41fea..2470a68f 100644 --- a/src/features/order/order-deposit-admin.graphql +++ b/src/features/order/order-deposit-admin.graphql @@ -140,7 +140,7 @@ type AdminTaskCounts { input AdminConfirmPaymentInput { orderId: ID! """ - 은행 앱에서 본 입금액(원, 1 이상 정수). 결제 금액과 같아야 확인된다. + 은행 앱에서 본 입금액(원, 0 이상 정수). 결제 금액과 같아야 확인된다(0원 주문은 0). """ depositedAmount: Int! """ diff --git a/src/features/order/services/order-deposit-admin.service.spec.ts b/src/features/order/services/order-deposit-admin.service.spec.ts index 133f43b8..b1917095 100644 --- a/src/features/order/services/order-deposit-admin.service.spec.ts +++ b/src/features/order/services/order-deposit-admin.service.spec.ts @@ -282,7 +282,7 @@ describe('AdminDepositService (real DB)', () => { const adminId = await admin(); const { order } = await pendingOrder(); - for (const depositedAmount of [29_999, 30_001]) { + for (const depositedAmount of [0, 29_999, 30_001]) { await expect( service.adminConfirmPayment(adminId, { orderId: order.id.toString(), @@ -297,7 +297,19 @@ describe('AdminDepositService (real DB)', () => { expect(await prisma.auditLog.count()).toBe(0); }); - it.each([0, -1])( + it('결제 금액이 0원인 주문은 입금액 0으로 접수한다', async () => { + const adminId = await admin(); + const { order } = await pendingOrder({ totalPrice: 0 }); + + await expect( + service.adminConfirmPayment(adminId, { + orderId: order.id.toString(), + depositedAmount: 0, + }), + ).resolves.toMatchObject({ status: 'SUBMITTED' }); + }); + + it.each([-1, 1.5])( '입금액 %s는 DEPOSIT_AMOUNT_INVALID다', async (depositedAmount) => { const adminId = await admin(); diff --git a/src/features/order/services/order-deposit-admin.service.ts b/src/features/order/services/order-deposit-admin.service.ts index fc2763eb..29a68b1c 100644 --- a/src/features/order/services/order-deposit-admin.service.ts +++ b/src/features/order/services/order-deposit-admin.service.ts @@ -103,7 +103,7 @@ export class AdminDepositService extends AdminBaseService { const ctx = await this.requireAdminContext(accountId); const orderId = parseId(input.orderId); const { depositedAmount } = input; - if (!Number.isSafeInteger(depositedAmount) || depositedAmount < 1) { + if (!Number.isSafeInteger(depositedAmount) || depositedAmount < 0) { throw new DomainException('DEPOSIT_AMOUNT_INVALID'); } const note = cleanNullableText(input.note, MAX_CONFIRM_NOTE_LENGTH); From 6c3ebe9b730912ecedf78d3dc2b3d4ee83bdf03f Mon Sep 17 00:00:00 2001 From: chanwoo7 Date: Thu, 19 Nov 2026 02:46:17 +0900 Subject: [PATCH 20/54] =?UTF-8?q?feat:=20=EC=9E=85=EA=B8=88=20=EB=8C=80?= =?UTF-8?q?=EA=B8=B0=C2=B7=EC=9E=85=EA=B8=88=ED=96=88=EC=96=B4=EC=9A=94=20?= =?UTF-8?q?=EA=B4=80=EB=A6=AC=EC=9E=90=20=EB=94=94=EC=8A=A4=EC=BD=94?= =?UTF-8?q?=EB=93=9C=20=EC=95=8C=EB=A6=BC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ① 무엇·왜 - 입금 확인은 관리자 수동 처리라 1시간 안에 확인해야 한다. 새 입금 대기 주문과 구매자 '입금했어요'를 관리자 디스코드로 알려 목록을 계속 들여다보지 않아도 되게 한다. - 업무 알림은 장애 경보와 같은 채널로 가므로 info 레벨 색으로 가르고, 주문별 key라 쌓이는 억제 기록은 창이 지나면 지운다. ② 변경점 - 이벤트: createOrder tx에 order.payment_pending(금액·입금자명·입금 기한), '입금했어요' tx에 payment.deposit_claimed. 둘 다 주문 aggregate라 상태 전이와 같은 파티션이다 - OrderAdminAlertConsumer(worker): deposit-pending:{orderId}·deposit-claim:{orderId} key, 금액(천 단위)·입금자명·입금 기한(KST)·처리 화면 링크(/tasks/deposits?orderId=). 상태를 바꾸지 않고 재전달 중복은 억제 창 안에서만 막는다 - AlertService: AlertLevel info(파랑), 웹훅이 없을 때 info는 일반 로그, notify 때 억제 창이 지난 key 삭제, 재전송은 더 새 시도가 있을 때만 건너뜀(창이 지나 key가 지워진 경우는 보냄) - ADMIN_WEB_BASE_URL(선택, admin-web.config): 쿼리·해시 없는 http(s) 주소만, 끝 슬래시 제거, 틀리면 부팅 실패. app.module load 등록, README·infra/app.env.example·guide §8 갱신 ③ 테스트 - 이벤트 payload·같은 tx·capacity 거절/replay 미발행, '입금했어요' 첫 누름만 1건(다시 누름·기한 지남·404는 0건) - 소비자: 문구·key·딥링크, 주소 없으면 링크 없음, 같은 이벤트 재전달 1회·같은 주문의 다른 알림은 따로, 형식 오류·모르는 이벤트는 던짐 - AlertService: info 로그, 만료 key 정리, key가 지워진 뒤 재전송, 색 3종 - 반증: key 정리를 빼면 정리·재전송 테스트 2건, 재전송 조건을 되돌리면 재전송 테스트가 실패 - 설정 파싱 표(정규화 4·미설정 3)와 부팅 차단 반증 5 --- README.md | 28 +-- docs/guide/architecture-conventions.md | 2 +- infra/app.env.example | 1 + src/app.module.ts | 2 + src/config/admin-web.config.spec.ts | 30 +++ src/config/admin-web.config.ts | 32 ++++ .../order-payment-pending.event.spec.ts | 57 ++++++ .../events/order-payment-pending.event.ts | 66 +++++++ .../payment-deposit-claimed.event.spec.ts | 53 ++++++ .../events/payment-deposit-claimed.event.ts | 61 ++++++ src/features/order/order.module.ts | 3 + .../repositories/order.repository.spec.ts | 30 ++- .../order/repositories/order.repository.ts | 19 +- .../order/repositories/payment.repository.ts | 26 ++- .../order-admin-alert-messages.helper.ts | 67 +++++++ .../order-admin-alert.consumer.spec.ts | 175 ++++++++++++++++++ .../services/order-admin-alert.consumer.ts | 57 ++++++ .../services/order-checkout.service.spec.ts | 81 +++++++- .../order/services/order-my.service.spec.ts | 28 ++- src/global/alerting/alert.service.spec.ts | 65 ++++++- src/global/alerting/alert.service.ts | 19 +- src/global/alerting/discord-webhook.spec.ts | 15 ++ src/global/alerting/discord-webhook.ts | 9 +- src/global/alerting/index.ts | 5 +- 24 files changed, 892 insertions(+), 39 deletions(-) create mode 100644 src/config/admin-web.config.spec.ts create mode 100644 src/config/admin-web.config.ts create mode 100644 src/features/order/events/order-payment-pending.event.spec.ts create mode 100644 src/features/order/events/order-payment-pending.event.ts create mode 100644 src/features/order/events/payment-deposit-claimed.event.spec.ts create mode 100644 src/features/order/events/payment-deposit-claimed.event.ts create mode 100644 src/features/order/services/order-admin-alert-messages.helper.ts create mode 100644 src/features/order/services/order-admin-alert.consumer.spec.ts create mode 100644 src/features/order/services/order-admin-alert.consumer.ts diff --git a/README.md b/README.md index 7349ab5c..f87edac7 100644 --- a/README.md +++ b/README.md @@ -299,20 +299,20 @@ APP_ROLE=worker PORT=4001 yarn start:dev # (선택) 이벤트 소비까지 보 > `.env.example`은 레포에 두지 않습니다. 검증 스키마는 [`src/config/`](./src/config/)에, 운영 키 목록은 [`infra/app.env.example`](./infra/app.env.example)에 있습니다. -| 카테고리 | 키 | -| ------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| **서버** | `NODE_ENV`, `PORT`, `BACKEND_BASE_URL`, `FRONTEND_BASE_URL`(쉼표로 여러 개를 적을 수 있으며 전부 비운영 CORS 오리진이 되고, 첫 값이 로그인 뒤 리다이렉트 기본값), `APP_ROLE`(`api`·`ws`·`worker`, 기본 `api`), `TRUST_PROXY_HOPS` | -| **DB** | `DATABASE_URL` | -| **Redis (필수)** | `REDIS_URL`. 인증 블랙리스트와 Subscription PubSub에 사용합니다. `maxmemory`를 설정했다면 정책이 `noeviction`이어야 하며, 아니면 worker가 점검해 경보를 보내고 인증은 DB 폴백으로 동작합니다 | -| **RabbitMQ (필수)** | `RABBITMQ_URL`. outbox 릴레이에서 소비자로 이어지는 이벤트 백본에 사용합니다 | -| **JWT / Auth** | `JWT_PRIVATE_KEY_PEM_B64`(또는 `JWT_PRIVATE_KEY_PATH`)는 RS256 서명키이며 운영에서 필수입니다. `JWT_PUBLIC_KEY_PEM_B64`는 생략하면 개인키에서 유도합니다. 그 밖에 `JWT_ISSUER`, `JWT_AUDIENCE`, `JWT_ACCESS_EXPIRES_SECONDS`, `AUTH_REFRESH_EXPIRES_DAYS`, `AUTH_COOKIE_*` | -| **OIDC** | `OIDC_GOOGLE_CLIENT_ID`, `OIDC_GOOGLE_CLIENT_SECRET`, `OIDC_GOOGLE_ISSUER_URL`, `OIDC_KAKAO_CLIENT_ID`, `OIDC_KAKAO_CLIENT_SECRET`, `OIDC_KAKAO_ISSUER_URL`, `OIDC_TEMP_COOKIE_MAX_AGE_MS` | -| **AWS S3** | `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`(IAM 사용자 `caquick-app`, 미디어 put/get 권한만), `AWS_REGION`, `AWS_S3_BUCKET`(운영 필수), `S3_PRESIGN_EXPIRES_SECONDS` | -| **계좌 암호화** | `ACCOUNT_ENCRYPTION_KEYS`(환불·정산 계좌번호 암호화 키, `k2:,k1:`처럼 쉼표로 나열하고 첫 키로 암호화합니다). 운영 필수이며 없거나 형식이 틀리면 부팅이 실패합니다. 비운영은 고정 개발 키를 쓰고 경고를 남깁니다. 백업·회전은 [`infra/runbook.md`](./infra/runbook.md) | -| **문서 · 메트릭** | `DOCS_ACCESS_TOKEN`(`/gql-docs`와 `/rest-docs` 접근 토큰, 운영 필수), `METRICS_ACCESS_TOKEN`(`/metrics` Bearer 토큰, 운영 필수) | -| **경보 (선택)** | `DISCORD_ALERT_WEBHOOK_URL`(없으면 로그로만 남깁니다), `ALERT_DEDUPE_WINDOW_MS`(기본 5분), `BOOT_ALERT_STATE_DIR`(부팅 실패 경보의 억제 파일 위치, 기본 `~/.caquick/boot-alert`) | -| **Outbox (선택)** | `OUTBOX_DISPATCH_ENABLED`(`false`로 끄는 용도만 있으며 켜는 것은 worker 역할이 결정), `OUTBOX_POLL_INTERVAL_MS`, `OUTBOX_BATCH_SIZE`, `OUTBOX_MAX_ATTEMPTS`, `OUTBOX_PARTITION_CONCURRENCY` | -| **푸시 (선택)** | `EXPO_PUSH_ENABLED`(`true`일 때만 worker가 판매자 앱 푸시를 보내고, 기본 `false`면 소비자가 전송 없이 ack합니다), `EXPO_PUSH_ACCESS_TOKEN`(Expo 액세스 토큰, 없으면 인증 헤더 없이 보냅니다), `EXPO_PUSH_TIMEOUT_MS`(기본 5000) | +| 카테고리 | 키 | +| ------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| **서버** | `NODE_ENV`, `PORT`, `BACKEND_BASE_URL`, `FRONTEND_BASE_URL`(쉼표로 여러 개를 적을 수 있으며 전부 비운영 CORS 오리진이 되고, 첫 값이 로그인 뒤 리다이렉트 기본값), `APP_ROLE`(`api`·`ws`·`worker`, 기본 `api`), `TRUST_PROXY_HOPS` | +| **DB** | `DATABASE_URL` | +| **Redis (필수)** | `REDIS_URL`. 인증 블랙리스트와 Subscription PubSub에 사용합니다. `maxmemory`를 설정했다면 정책이 `noeviction`이어야 하며, 아니면 worker가 점검해 경보를 보내고 인증은 DB 폴백으로 동작합니다 | +| **RabbitMQ (필수)** | `RABBITMQ_URL`. outbox 릴레이에서 소비자로 이어지는 이벤트 백본에 사용합니다 | +| **JWT / Auth** | `JWT_PRIVATE_KEY_PEM_B64`(또는 `JWT_PRIVATE_KEY_PATH`)는 RS256 서명키이며 운영에서 필수입니다. `JWT_PUBLIC_KEY_PEM_B64`는 생략하면 개인키에서 유도합니다. 그 밖에 `JWT_ISSUER`, `JWT_AUDIENCE`, `JWT_ACCESS_EXPIRES_SECONDS`, `AUTH_REFRESH_EXPIRES_DAYS`, `AUTH_COOKIE_*` | +| **OIDC** | `OIDC_GOOGLE_CLIENT_ID`, `OIDC_GOOGLE_CLIENT_SECRET`, `OIDC_GOOGLE_ISSUER_URL`, `OIDC_KAKAO_CLIENT_ID`, `OIDC_KAKAO_CLIENT_SECRET`, `OIDC_KAKAO_ISSUER_URL`, `OIDC_TEMP_COOKIE_MAX_AGE_MS` | +| **AWS S3** | `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`(IAM 사용자 `caquick-app`, 미디어 put/get 권한만), `AWS_REGION`, `AWS_S3_BUCKET`(운영 필수), `S3_PRESIGN_EXPIRES_SECONDS` | +| **계좌 암호화** | `ACCOUNT_ENCRYPTION_KEYS`(환불·정산 계좌번호 암호화 키, `k2:,k1:`처럼 쉼표로 나열하고 첫 키로 암호화합니다). 운영 필수이며 없거나 형식이 틀리면 부팅이 실패합니다. 비운영은 고정 개발 키를 쓰고 경고를 남깁니다. 백업·회전은 [`infra/runbook.md`](./infra/runbook.md) | +| **문서 · 메트릭** | `DOCS_ACCESS_TOKEN`(`/gql-docs`와 `/rest-docs` 접근 토큰, 운영 필수), `METRICS_ACCESS_TOKEN`(`/metrics` Bearer 토큰, 운영 필수) | +| **경보 (선택)** | `DISCORD_ALERT_WEBHOOK_URL`(장애 경보와 입금 확인 요청 같은 업무 알림이 함께 가며, 없으면 로그로만 남깁니다), `ALERT_DEDUPE_WINDOW_MS`(기본 5분), `BOOT_ALERT_STATE_DIR`(부팅 실패 경보의 억제 파일 위치, 기본 `~/.caquick/boot-alert`), `ADMIN_WEB_BASE_URL`(관리자 웹 주소, 있으면 업무 알림에 처리 화면 링크를 붙이며 쿼리·해시 없는 http(s) 주소가 아니면 부팅이 실패합니다) | +| **Outbox (선택)** | `OUTBOX_DISPATCH_ENABLED`(`false`로 끄는 용도만 있으며 켜는 것은 worker 역할이 결정), `OUTBOX_POLL_INTERVAL_MS`, `OUTBOX_BATCH_SIZE`, `OUTBOX_MAX_ATTEMPTS`, `OUTBOX_PARTITION_CONCURRENCY` | +| **푸시 (선택)** | `EXPO_PUSH_ENABLED`(`true`일 때만 worker가 판매자 앱 푸시를 보내고, 기본 `false`면 소비자가 전송 없이 ack합니다), `EXPO_PUSH_ACCESS_TOKEN`(Expo 액세스 토큰, 없으면 인증 헤더 없이 보냅니다), `EXPO_PUSH_TIMEOUT_MS`(기본 5000) | ### 자주 쓰는 스크립트 diff --git a/docs/guide/architecture-conventions.md b/docs/guide/architecture-conventions.md index dc580e88..6e29036e 100644 --- a/docs/guide/architecture-conventions.md +++ b/docs/guide/architecture-conventions.md @@ -110,7 +110,7 @@ ### 경보 -`AlertService.notify({ level, title, detail, key })`가 운영 경보의 단일 출구다. **절대 던지지 않고** 결과(`sent | suppressed | skipped | failed`)만 돌려준다 — 경보 때문에 본 작업이 실패하면 안 된다. 같은 `key`는 억제 창(`ALERT_DEDUPE_WINDOW_MS`, 기본 5분) 안에서 1회. 웹훅 미설정이면 로그만. 부팅 실패는 DI가 없을 수 있어 전송 함수를 직접 부르고, 감독자의 동시 재시작에 대비해 호스트 잠금 파일(`BOOT_ALERT_STATE_DIR`, 700)로 억제한다. **사람이 개입해야 하는 상태만** 보낸다(outbox FAILED·DLQ·블랙리스트 폴백·브로커 blocked·부팅 실패). 재시도 중인 상태는 보내지 않는다. +`AlertService.notify({ level, title, detail, key })`가 운영 경보의 단일 출구다. **절대 던지지 않고** 결과(`sent | suppressed | skipped | failed`)만 돌려준다 — 경보 때문에 본 작업이 실패하면 안 된다. 같은 `key`는 억제 창(`ALERT_DEDUPE_WINDOW_MS`, 기본 5분) 안에서 1회. 웹훅 미설정이면 로그만. 부팅 실패는 DI가 없을 수 있어 전송 함수를 직접 부르고, 감독자의 동시 재시작에 대비해 호스트 잠금 파일(`BOOT_ALERT_STATE_DIR`, 700)로 억제한다. **사람이 개입해야 하는 상태만** 보낸다(outbox FAILED·DLQ·블랙리스트 폴백·브로커 blocked·부팅 실패). 재시도 중인 상태는 보내지 않는다. 사람이 처리할 업무(입금 확인 요청 등)는 `level: 'info'`로 같은 채널에 보내 색으로 가르고, 건별 `key`(`deposit-claim:{orderId}` 등)를 쓴다 — 억제 창이 지난 key는 notify 때 지우며, 창이 지난 재전달은 다시 갈 수 있어 진실은 처리 대기 목록(`adminTaskCounts`)이다. `ADMIN_WEB_BASE_URL`이 있으면 처리 화면 링크를 붙인다. ### 메트릭 diff --git a/infra/app.env.example b/infra/app.env.example index 49aa03ac..af9ab73f 100644 --- a/infra/app.env.example +++ b/infra/app.env.example @@ -47,6 +47,7 @@ METRICS_ACCESS_TOKEN= # 운영 필수(NODE_ENV=production이면 미설정 시 DOCS_ACCESS_TOKEN= # 운영 필수(NODE_ENV=production이면 미설정 시 부팅 실패) DISCORD_ALERT_WEBHOOK_URL= ALERT_DEDUPE_WINDOW_MS= +ADMIN_WEB_BASE_URL= # 선택. 관리자 웹 주소(예: https://admin.caquick.com) — 업무 알림에 처리 화면 링크를 붙인다 OUTBOX_MAX_ATTEMPTS= OUTBOX_PARTITION_CONCURRENCY= diff --git a/src/app.module.ts b/src/app.module.ts index ecadf66e..854fac50 100644 --- a/src/app.module.ts +++ b/src/app.module.ts @@ -18,6 +18,7 @@ import { ServeStaticModule } from '@nestjs/serve-static'; import { CommonModule } from '@/common/common.module'; import accountCryptoConfig from '@/config/account-crypto.config'; +import adminWebConfig from '@/config/admin-web.config'; import alertingConfig from '@/config/alerting.config'; import appConfig, { APP_ROLE_TOKEN, @@ -123,6 +124,7 @@ export class AppModule implements NestModule { cache: true, load: [ accountCryptoConfig, + adminWebConfig, alertingConfig, appConfig, authConfig, diff --git a/src/config/admin-web.config.spec.ts b/src/config/admin-web.config.spec.ts new file mode 100644 index 00000000..13a844d9 --- /dev/null +++ b/src/config/admin-web.config.spec.ts @@ -0,0 +1,30 @@ +import { readAdminWebConfig } from '@/config/admin-web.config'; + +describe('adminWebConfig', () => { + it.each([ + [undefined, null], + ['', null], + [' ', null], + ['https://admin.caquick.com', 'https://admin.caquick.com'], + [' https://admin.caquick.com/ ', 'https://admin.caquick.com'], + ['https://caquick.com/admin//', 'https://caquick.com/admin'], + ['http://192.168.75.17:5173', 'http://192.168.75.17:5173'], + ])('ADMIN_WEB_BASE_URL=%p → %p', (value, expected) => { + expect(readAdminWebConfig({ ADMIN_WEB_BASE_URL: value }).baseUrl).toBe( + expected, + ); + }); + + // 틀린 값으로 부팅하면 업무 알림마다 깨진 링크가 나간다 + it.each([ + ['URL이 아님', 'admin.caquick.com'], + ['http(s)가 아님', 'ftp://admin.caquick.com'], + ['javascript 스킴', 'javascript:alert(1)'], + ['쿼리 포함', 'https://admin.caquick.com?x=1'], + ['해시 포함', 'https://admin.caquick.com/#/tasks'], + ])('반증: %s이면 부팅을 막는다', (_case, value) => { + expect(() => readAdminWebConfig({ ADMIN_WEB_BASE_URL: value })).toThrow( + 'ADMIN_WEB_BASE_URL', + ); + }); +}); diff --git a/src/config/admin-web.config.ts b/src/config/admin-web.config.ts new file mode 100644 index 00000000..ca181c06 --- /dev/null +++ b/src/config/admin-web.config.ts @@ -0,0 +1,32 @@ +import { registerAs } from '@nestjs/config'; + +import { parseEnvString } from '@/common/utils/env-parse'; + +export interface AdminWebConfig { + /** 관리자 웹 주소(끝 슬래시 없음). 있으면 업무 알림에 처리 화면 링크를 붙인다. */ + baseUrl: string | null; +} + +/** 선택 설정. 값이 있는데 쿼리·해시 없는 http(s) 주소가 아니면 부팅을 막는다 — 깨진 링크가 알림마다 나가지 않게. */ +export function readAdminWebConfig( + env: NodeJS.ProcessEnv = process.env, +): AdminWebConfig { + const raw = parseEnvString(env.ADMIN_WEB_BASE_URL); + if (!raw) return { baseUrl: null }; + const url = URL.parse(raw); + if ( + !url || + (url.protocol !== 'https:' && url.protocol !== 'http:') || + url.search || + url.hash + ) { + throw new Error( + `ADMIN_WEB_BASE_URL은 쿼리·해시 없는 http(s) 주소여야 합니다: ${raw}`, + ); + } + return { baseUrl: `${url.origin}${url.pathname}`.replace(/\/+$/, '') }; +} + +export default registerAs('adminWeb', (): AdminWebConfig => + readAdminWebConfig(), +); diff --git a/src/features/order/events/order-payment-pending.event.spec.ts b/src/features/order/events/order-payment-pending.event.spec.ts new file mode 100644 index 00000000..2b77f4e3 --- /dev/null +++ b/src/features/order/events/order-payment-pending.event.spec.ts @@ -0,0 +1,57 @@ +import { + ORDER_PAYMENT_PENDING, + orderPaymentPendingEvent, + parseOrderPaymentPendingPayload, +} from '@/features/order/events/order-payment-pending.event'; +import type { Prisma } from '@/generated/prisma/client'; + +const VALID = { + orderId: '7', + orderNumber: 'ORD-20260916-ABC234', + amount: 56000, + depositorName: '차차맘', + expiresAt: '2026-09-16T08:00:00.000Z', +}; + +describe('order.payment_pending 이벤트', () => { + it('bigint·Date를 문자열로 싣고 order aggregate에 묶는다(행위자는 구매자)', () => { + const occurredAt = new Date('2026-09-16T07:00:00.000Z'); + const event = orderPaymentPendingEvent({ + orderId: 7n, + orderNumber: VALID.orderNumber, + buyerAccountId: 3n, + amount: 56000, + depositorName: '차차맘', + expiresAt: new Date(VALID.expiresAt), + occurredAt, + }); + + expect(event).toEqual({ + aggregateType: 'order', + aggregateId: '7', + eventType: ORDER_PAYMENT_PENDING, + payload: VALID, + occurredAt, + actorAccountId: 3n, + }); + expect( + parseOrderPaymentPendingPayload(event.payload as Prisma.JsonValue), + ).toEqual(VALID); + }); + + it.each([ + ['null', null], + ['배열', [VALID]], + ['orderId 숫자', { ...VALID, orderId: 7 }], + ['orderNumber 누락', { ...VALID, orderNumber: undefined }], + ['amount 문자열', { ...VALID, amount: '56000' }], + ['amount 소수', { ...VALID, amount: 1.5 }], + ['depositorName null', { ...VALID, depositorName: null }], + ['expiresAt 숫자', { ...VALID, expiresAt: 1_700_000_000 }], + ['expiresAt 비ISO', { ...VALID, expiresAt: 'not-a-date' }], + ])('반증: %s payload는 던진다', (_label, payload) => { + expect(() => + parseOrderPaymentPendingPayload(payload as Prisma.JsonValue), + ).toThrow('payload 형식 오류'); + }); +}); diff --git a/src/features/order/events/order-payment-pending.event.ts b/src/features/order/events/order-payment-pending.event.ts new file mode 100644 index 00000000..d563ed93 --- /dev/null +++ b/src/features/order/events/order-payment-pending.event.ts @@ -0,0 +1,66 @@ +import type { OutboxEventInput } from '@/features/outbox'; +import type { Prisma } from '@/generated/prisma/client'; + +/** 새 입금 대기 주문(관리자 경보 원천). 1시간 안에 확인해야 해서 '입금했어요'를 누르지 않은 주문도 알린다. */ +export const ORDER_PAYMENT_PENDING = 'order.payment_pending'; + +export interface OrderPaymentPendingPayload { + orderId: string; + orderNumber: string; + amount: number; + depositorName: string; + /** ISO 8601 */ + expiresAt: string; +} + +export function orderPaymentPendingEvent(args: { + orderId: bigint; + orderNumber: string; + buyerAccountId: bigint; + amount: number; + depositorName: string; + expiresAt: Date; + occurredAt: Date; +}): OutboxEventInput { + const payload: OrderPaymentPendingPayload = { + orderId: args.orderId.toString(), + orderNumber: args.orderNumber, + amount: args.amount, + depositorName: args.depositorName, + expiresAt: args.expiresAt.toISOString(), + }; + return { + aggregateType: 'order', + aggregateId: payload.orderId, + eventType: ORDER_PAYMENT_PENDING, + payload: { ...payload }, + occurredAt: args.occurredAt, + actorAccountId: args.buyerAccountId, + }; +} + +export function parseOrderPaymentPendingPayload( + value: Prisma.JsonValue, +): OrderPaymentPendingPayload { + const p = value as Partial>; + if ( + typeof value !== 'object' || + value === null || + Array.isArray(value) || + typeof p.orderId !== 'string' || + typeof p.orderNumber !== 'string' || + !Number.isSafeInteger(p.amount) || + typeof p.depositorName !== 'string' || + typeof p.expiresAt !== 'string' || + Number.isNaN(Date.parse(p.expiresAt)) + ) { + throw new Error(`${ORDER_PAYMENT_PENDING} payload 형식 오류`); + } + return { + orderId: p.orderId, + orderNumber: p.orderNumber, + amount: p.amount as number, + depositorName: p.depositorName, + expiresAt: p.expiresAt, + }; +} diff --git a/src/features/order/events/payment-deposit-claimed.event.spec.ts b/src/features/order/events/payment-deposit-claimed.event.spec.ts new file mode 100644 index 00000000..0010c540 --- /dev/null +++ b/src/features/order/events/payment-deposit-claimed.event.spec.ts @@ -0,0 +1,53 @@ +import { + parsePaymentDepositClaimedPayload, + PAYMENT_DEPOSIT_CLAIMED, + paymentDepositClaimedEvent, +} from '@/features/order/events/payment-deposit-claimed.event'; +import type { Prisma } from '@/generated/prisma/client'; + +const VALID = { + orderId: '7', + orderNumber: 'ORD-20260916-ABC234', + amount: 56000, + depositorName: '차차맘', +}; + +describe('payment.deposit_claimed 이벤트', () => { + it('주문과 같은 aggregate(파티션)에 묶고 행위자는 구매자다', () => { + const occurredAt = new Date('2026-09-16T07:30:00.000Z'); + const event = paymentDepositClaimedEvent({ + orderId: 7n, + orderNumber: VALID.orderNumber, + buyerAccountId: 3n, + amount: 56000, + depositorName: '차차맘', + occurredAt, + }); + + expect(event).toEqual({ + aggregateType: 'order', + aggregateId: '7', + eventType: PAYMENT_DEPOSIT_CLAIMED, + payload: VALID, + occurredAt, + actorAccountId: 3n, + }); + expect( + parsePaymentDepositClaimedPayload(event.payload as Prisma.JsonValue), + ).toEqual(VALID); + }); + + it.each([ + ['null', null], + ['배열', [VALID]], + ['문자열', 'x'], + ['orderId 숫자', { ...VALID, orderId: 7 }], + ['orderNumber 누락', { ...VALID, orderNumber: undefined }], + ['amount 문자열', { ...VALID, amount: '56000' }], + ['depositorName 누락', { ...VALID, depositorName: undefined }], + ])('반증: %s payload는 던진다', (_label, payload) => { + expect(() => + parsePaymentDepositClaimedPayload(payload as Prisma.JsonValue), + ).toThrow('payload 형식 오류'); + }); +}); diff --git a/src/features/order/events/payment-deposit-claimed.event.ts b/src/features/order/events/payment-deposit-claimed.event.ts new file mode 100644 index 00000000..93c3e86a --- /dev/null +++ b/src/features/order/events/payment-deposit-claimed.event.ts @@ -0,0 +1,61 @@ +import type { OutboxEventInput } from '@/features/outbox'; +import type { Prisma } from '@/generated/prisma/client'; + +/** 구매자 '입금했어요'(관리자 경보 원천). 누른 주문은 미입금 자동 취소에서 빠져 관리자가 확인해야 끝난다. */ +export const PAYMENT_DEPOSIT_CLAIMED = 'payment.deposit_claimed'; + +export interface PaymentDepositClaimedPayload { + orderId: string; + orderNumber: string; + amount: number; + depositorName: string; +} + +export function paymentDepositClaimedEvent(args: { + orderId: bigint; + orderNumber: string; + buyerAccountId: bigint; + amount: number; + depositorName: string; + occurredAt: Date; +}): OutboxEventInput { + const payload: PaymentDepositClaimedPayload = { + orderId: args.orderId.toString(), + orderNumber: args.orderNumber, + amount: args.amount, + depositorName: args.depositorName, + }; + return { + aggregateType: 'order', + aggregateId: payload.orderId, + eventType: PAYMENT_DEPOSIT_CLAIMED, + payload: { ...payload }, + occurredAt: args.occurredAt, + actorAccountId: args.buyerAccountId, + }; +} + +export function parsePaymentDepositClaimedPayload( + value: Prisma.JsonValue, +): PaymentDepositClaimedPayload { + const p = value as Partial< + Record + >; + if ( + typeof value !== 'object' || + value === null || + Array.isArray(value) || + typeof p.orderId !== 'string' || + typeof p.orderNumber !== 'string' || + !Number.isSafeInteger(p.amount) || + typeof p.depositorName !== 'string' + ) { + throw new Error(`${PAYMENT_DEPOSIT_CLAIMED} payload 형식 오류`); + } + return { + orderId: p.orderId, + orderNumber: p.orderNumber, + amount: p.amount as number, + depositorName: p.depositorName, + }; +} diff --git a/src/features/order/order.module.ts b/src/features/order/order.module.ts index 9ec8a5ee..411de205 100644 --- a/src/features/order/order.module.ts +++ b/src/features/order/order.module.ts @@ -26,6 +26,7 @@ import { SellerOrderQueryResolver } from '@/features/order/resolvers/order-selle import { SellerSettlementMutationResolver } from '@/features/order/resolvers/order-settlement-seller-mutation.resolver'; import { SellerSettlementQueryResolver } from '@/features/order/resolvers/order-settlement-seller-query.resolver'; import { OrderSubscriptionResolver } from '@/features/order/resolvers/order-subscription.resolver'; +import { OrderAdminAlertConsumer } from '@/features/order/services/order-admin-alert.consumer'; import { AdminOrderService } from '@/features/order/services/order-admin.service'; import { OrderCheckoutService } from '@/features/order/services/order-checkout.service'; import { AdminDepositService } from '@/features/order/services/order-deposit-admin.service'; @@ -82,6 +83,8 @@ import { StoreModule } from '@/features/store'; AdminDepositService, AdminDepositQueryResolver, AdminDepositMutationResolver, + // 입금 대기·'입금했어요' 관리자 디스코드 알림(worker 소비자) + OrderAdminAlertConsumer, // 결제 설정·매장 정산 계좌(계좌번호는 global AccountCipher로 암호화) PaymentSettingRepository, StoreSettlementAccountRepository, diff --git a/src/features/order/repositories/order.repository.spec.ts b/src/features/order/repositories/order.repository.spec.ts index c3a48d2b..e371d5e9 100644 --- a/src/features/order/repositories/order.repository.spec.ts +++ b/src/features/order/repositories/order.repository.spec.ts @@ -3,6 +3,10 @@ import { AuditLogRepository } from '@/features/audit-log/repositories/audit-log. import { NotificationAdminRepository } from '@/features/notification/repositories/notification-admin.repository'; import { NotificationRepository } from '@/features/notification/repositories/notification.repository'; import { NotificationOutboxConsumer } from '@/features/notification/services/notification-outbox.consumer'; +import { + ORDER_PAYMENT_PENDING, + parseOrderPaymentPendingPayload, +} from '@/features/order/events/order-payment-pending.event'; import { pendingPaymentLockName, withPendingPaymentLock, @@ -987,7 +991,7 @@ describe('OrderRepository (real DB)', () => { }; } - it('입금 대기 주문·결제(계좌 스냅샷)·이력을 같은 tx에 남기고 판매자 새 주문 이벤트는 없다', async () => { + it('입금 대기 주문·결제(계좌 스냅샷)·이력과 입금 대기 이벤트를 같은 tx에 남긴다', async () => { const buyer = await setupBuyer(); const store = await createStore(prisma, { store_name: '해즈 케이크' }); const product = await createProduct(prisma, { @@ -1032,10 +1036,26 @@ describe('OrderRepository (real DB)', () => { }), ]); expect(created.payment).toMatchObject({ amount: 50000 }); - expect(await prisma.outbox.count()).toBe(0); + + const events = await prisma.outbox.findMany(); + expect(events).toHaveLength(1); + expect(events[0]).toMatchObject({ + aggregate_type: 'order', + aggregate_id: created.id.toString(), + event_type: ORDER_PAYMENT_PENDING, + occurred_at: NOW, + actor_account_id: buyer.id, + }); + expect(parseOrderPaymentPendingPayload(events[0].payload_json)).toEqual({ + orderId: created.id.toString(), + orderNumber: 'ORD-20260916-ABC234', + amount: 50000, + depositorName: '차차맘', + expiresAt: EXPIRES_AT.toISOString(), + }); }); - it('반증: capacity 재검사에서 거절되면 주문도 결제도 남지 않는다', async () => { + it('반증: capacity 재검사에서 거절되면 주문도 결제도 이벤트도 남지 않는다', async () => { const buyer = await setupBuyer(); const store = await createStore(prisma); const product = await createProduct(prisma, { store_id: store.id }); @@ -1063,9 +1083,10 @@ describe('OrderRepository (real DB)', () => { expect(created).toBe('capacity-exceeded'); expect(await prisma.order.count()).toBe(0); expect(await prisma.payment.count()).toBe(0); + expect(await prisma.outbox.count()).toBe(0); }); - it('반증: order_number 충돌로 tx가 롤백되면 결제도 남지 않는다', async () => { + it('반증: order_number 충돌로 tx가 롤백되면 결제도 이벤트도 남지 않는다', async () => { const buyer = await setupBuyer(); const store = await createStore(prisma); const product = await createProduct(prisma, { store_id: store.id }); @@ -1083,6 +1104,7 @@ describe('OrderRepository (real DB)', () => { ).rejects.toMatchObject({ code: 'P2002' }); expect(await prisma.payment.count()).toBe(0); + expect(await prisma.outbox.count()).toBe(0); }); it('실패한 tx도 계정 잠금을 풀어 같은 계정의 다음 요청이 기다리지 않는다', async () => { diff --git a/src/features/order/repositories/order.repository.ts b/src/features/order/repositories/order.repository.ts index 797baa8d..cbe65ef8 100644 --- a/src/features/order/repositories/order.repository.ts +++ b/src/features/order/repositories/order.repository.ts @@ -5,6 +5,7 @@ import { type IAuditLogRepository, } from '@/features/audit-log'; import { IN_PROGRESS_ORDER_STATUSES } from '@/features/order/constants/order-status-traits'; +import { orderPaymentPendingEvent } from '@/features/order/events/order-payment-pending.event'; import { orderStatusChangedEvent } from '@/features/order/events/order-status-changed.event'; import { countPendingPaymentOrdersLocked, @@ -360,11 +361,11 @@ export class OrderRepository { return booked + quantity > capacity; } - private insertPendingPaymentOrder( + private async insertPendingPaymentOrder( tx: Prisma.TransactionClient, args: CreatePendingPaymentOrderArgs, ): Promise { - return tx.order.create({ + const created = await tx.order.create({ data: { account_id: args.accountId, order_number: args.orderNumber, @@ -426,6 +427,20 @@ export class OrderRepository { }, select: createdOrderSelect, }); + // 관리자 경보 원천. 판매자 '새 주문'(order.submitted)은 입금 확인 때 나간다 + await this.outbox.publish( + tx, + orderPaymentPendingEvent({ + orderId: created.id, + orderNumber: created.order_number, + buyerAccountId: args.accountId, + amount: args.totalPrice, + depositorName: args.payment.depositorName, + expiresAt: args.payment.expiresAt, + occurredAt: args.now, + }), + ); + return created; } /** 상태가 이후 변경됐어도 현재 row를 그대로 반환한다(replay 응답 재구성용). */ diff --git a/src/features/order/repositories/payment.repository.ts b/src/features/order/repositories/payment.repository.ts index bab96c83..290d3ddc 100644 --- a/src/features/order/repositories/payment.repository.ts +++ b/src/features/order/repositories/payment.repository.ts @@ -1,6 +1,8 @@ import { Injectable } from '@nestjs/common'; import type { TimestampIdCursor } from '@/common/utils/keyset-cursor'; +import { paymentDepositClaimedEvent } from '@/features/order/events/payment-deposit-claimed.event'; +import { OutboxPublisher } from '@/features/outbox'; import { OrderStatus, PaymentStatus, @@ -71,7 +73,10 @@ export type DepositClaimResult = @Injectable() export class PaymentRepository { - constructor(private readonly prisma: PrismaService) {} + constructor( + private readonly prisma: PrismaService, + private readonly outbox: OutboxPublisher, + ) {} private pendingScopeWhere( filter: PendingPaymentFilter, @@ -124,7 +129,7 @@ export class PaymentRepository { } /** - * 마감 전 첫 누름만 기록한다. 다시 누르면 아무것도 바꾸지 않는다(멱등). + * 마감 전 첫 누름만 기록하고 경보 이벤트를 남긴다. 다시 누르면 아무것도 바꾸지 않는다(멱등). * 잠금 순서는 주문 → 결제(입금 확인과 같다). */ async markDepositClaimed(args: { @@ -133,8 +138,10 @@ export class PaymentRepository { now: Date; }): Promise { return this.prisma.$transaction(async (tx) => { - const [order] = await tx.$queryRaw<{ id: bigint; status: OrderStatus }[]>` - SELECT id, status FROM \`order\` + const [order] = await tx.$queryRaw< + { id: bigint; status: OrderStatus; order_number: string }[] + >` + SELECT id, status, order_number FROM \`order\` WHERE id = ${args.orderId} AND account_id = ${args.accountId} AND deleted_at IS NULL FOR UPDATE`; if (!order) return 'not-found'; @@ -155,6 +162,17 @@ export class PaymentRepository { where: { id: payment.id }, data: { buyer_claimed_at: args.now }, }); + await this.outbox.publish( + tx, + paymentDepositClaimedEvent({ + orderId: order.id, + orderNumber: order.order_number, + buyerAccountId: args.accountId, + amount: payment.amount, + depositorName: payment.depositor_name, + occurredAt: args.now, + }), + ); return 'claimed'; }); } diff --git a/src/features/order/services/order-admin-alert-messages.helper.ts b/src/features/order/services/order-admin-alert-messages.helper.ts new file mode 100644 index 00000000..431275e8 --- /dev/null +++ b/src/features/order/services/order-admin-alert-messages.helper.ts @@ -0,0 +1,67 @@ +import { + formatMinutesOfDay, + kstMinutesOfDay, + toKstYmd, +} from '@/common/utils/kst-time'; +import type { OrderPaymentPendingPayload } from '@/features/order/events/order-payment-pending.event'; +import type { PaymentDepositClaimedPayload } from '@/features/order/events/payment-deposit-claimed.event'; +import type { AlertMessage } from '@/global/alerting'; + +/** 관리자 웹 처리 화면 링크. 주소가 설정되지 않았으면 null(링크 없이 보낸다). */ +export function adminTaskLink( + baseUrl: string | null, + path: string, + params: Record, +): string | null { + if (!baseUrl) return null; + return `${baseUrl}${path}?${new URLSearchParams(params).toString()}`; +} + +function depositLines( + p: { orderNumber: string; amount: number; depositorName: string }, + link: string | null, + extra: string[] = [], +): string { + return [ + `주문 ${p.orderNumber}`, + `${p.amount.toLocaleString('ko-KR')}원 · 입금자명 ${p.depositorName}`, + ...extra, + ...(link ? [link] : []), + ].join('\n'); +} + +/** `M/d HH:mm`(KST). */ +function formatKst(date: Date): string { + const { month, day } = toKstYmd(date); + return `${month}/${day} ${formatMinutesOfDay(kstMinutesOfDay(date))}`; +} + +function depositLink(baseUrl: string | null, orderId: string): string | null { + return adminTaskLink(baseUrl, '/tasks/deposits', { orderId }); +} + +export function buildDepositPendingAlert( + p: OrderPaymentPendingPayload, + baseUrl: string | null, +): AlertMessage { + return { + level: 'info', + title: '새 입금 대기', + key: `deposit-pending:${p.orderId}`, + detail: depositLines(p, depositLink(baseUrl, p.orderId), [ + `입금 기한 ${formatKst(new Date(p.expiresAt))}`, + ]), + }; +} + +export function buildDepositClaimedAlert( + p: PaymentDepositClaimedPayload, + baseUrl: string | null, +): AlertMessage { + return { + level: 'info', + title: "입금 확인 요청('입금했어요')", + key: `deposit-claim:${p.orderId}`, + detail: depositLines(p, depositLink(baseUrl, p.orderId)), + }; +} diff --git a/src/features/order/services/order-admin-alert.consumer.spec.ts b/src/features/order/services/order-admin-alert.consumer.spec.ts new file mode 100644 index 00000000..55d4d2e8 --- /dev/null +++ b/src/features/order/services/order-admin-alert.consumer.spec.ts @@ -0,0 +1,175 @@ +import type { ConfigService } from '@nestjs/config'; + +import { ClockService } from '@/common/providers/clock.service'; +import type { AdminWebConfig } from '@/config/admin-web.config'; +import type { AlertingConfig } from '@/config/alerting.config'; +import { ORDER_PAYMENT_PENDING } from '@/features/order/events/order-payment-pending.event'; +import { PAYMENT_DEPOSIT_CLAIMED } from '@/features/order/events/payment-deposit-claimed.event'; +import { OrderAdminAlertConsumer } from '@/features/order/services/order-admin-alert.consumer'; +import type { OutboxEvent } from '@/features/outbox'; +import { AlertService } from '@/global/alerting'; +import type { CustomLoggerService } from '@/global/logger/custom-logger.service'; + +const PENDING = { + orderId: '42', + orderNumber: 'ORD-20260916-ABC234', + amount: 56000, + depositorName: '차차맘', + // 9/16 17:00 KST + expiresAt: '2026-09-16T08:00:00.000Z', +}; +const CLAIMED = { + orderId: '43', + orderNumber: 'ORD-20260916-XYZ789', + amount: 1234567, + depositorName: '홍길동', +}; + +function event( + eventType: string, + payload: OutboxEvent['payload'], + eventId = 'e-1', +): OutboxEvent { + return { + id: 1n, + eventId, + aggregateType: 'order', + aggregateId: '42', + eventType, + payload, + occurredAt: new Date('2026-09-16T07:00:00.000Z'), + actorAccountId: null, + clientIp: null, + userAgent: null, + attempts: 0, + }; +} + +// 관리자 처리 대기 알림 — 이벤트별 key·문구·딥링크, 재전달은 억제 창 안에서만 1회, 형식 오류는 던진다. +describe('OrderAdminAlertConsumer', () => { + let nowMs = 0; + const transport = jest.fn().mockResolvedValue(true); + + function build(adminWeb: AdminWebConfig) { + const clock = new ClockService(); + jest.spyOn(clock, 'nowMs').mockImplementation(() => nowMs); + const alerting: AlertingConfig = { + discordWebhookUrl: 'https://discord.test/hook', + dedupeWindowMs: 5 * 60_000, + }; + const config = { + getOrThrow: (key: string) => (key === 'adminWeb' ? adminWeb : alerting), + } as unknown as ConfigService; + const alerts = new AlertService( + config, + clock, + { warn: jest.fn(), log: jest.fn() } as unknown as CustomLoggerService, + transport, + ); + return new OrderAdminAlertConsumer(alerts, config); + } + + beforeEach(() => { + nowMs = 1_000_000; + transport.mockClear(); + }); + + afterEach(() => { + jest.restoreAllMocks(); + }); + + it('새 입금 대기: info, 주문별 key, 금액·입금자명·입금 기한(KST)·처리 화면 링크', async () => { + const consumer = build({ baseUrl: 'https://admin.caquick.com' }); + + await consumer.handle(event(ORDER_PAYMENT_PENDING, PENDING)); + + expect(transport).toHaveBeenCalledWith( + 'https://discord.test/hook', + { + level: 'info', + title: '새 입금 대기', + key: 'deposit-pending:42', + detail: [ + '주문 ORD-20260916-ABC234', + '56,000원 · 입금자명 차차맘', + '입금 기한 9/16 17:00', + 'https://admin.caquick.com/tasks/deposits?orderId=42', + ].join('\n'), + }, + expect.any(Object), + ); + }); + + it("'입금했어요': info, 주문별 key, 금액·입금자명·처리 화면 링크", async () => { + const consumer = build({ baseUrl: 'https://caquick.com/admin' }); + + await consumer.handle(event(PAYMENT_DEPOSIT_CLAIMED, CLAIMED)); + + expect(transport).toHaveBeenCalledWith( + expect.any(String), + { + level: 'info', + title: "입금 확인 요청('입금했어요')", + key: 'deposit-claim:43', + detail: [ + '주문 ORD-20260916-XYZ789', + '1,234,567원 · 입금자명 홍길동', + 'https://caquick.com/admin/tasks/deposits?orderId=43', + ].join('\n'), + }, + expect.any(Object), + ); + }); + + it('관리자 웹 주소가 없으면 링크 없이 보낸다', async () => { + const consumer = build({ baseUrl: null }); + + await consumer.handle(event(PAYMENT_DEPOSIT_CLAIMED, CLAIMED)); + + const [, message] = transport.mock.calls[0] as [string, { detail: string }]; + expect(message.detail).toBe( + ['주문 ORD-20260916-XYZ789', '1,234,567원 · 입금자명 홍길동'].join('\n'), + ); + }); + + it('같은 이벤트 재전달은 억제 창 안에서 한 번만 보내고, 다른 주문은 따로 보낸다', async () => { + const consumer = build({ baseUrl: null }); + + await consumer.handle(event(ORDER_PAYMENT_PENDING, PENDING)); + await consumer.handle(event(ORDER_PAYMENT_PENDING, PENDING)); + // 같은 주문의 '입금했어요'는 다른 일이라 따로 간다 + await consumer.handle( + event(PAYMENT_DEPOSIT_CLAIMED, { ...CLAIMED, orderId: '42' }), + ); + await consumer.handle( + event(ORDER_PAYMENT_PENDING, { ...PENDING, orderId: '44' }), + ); + + expect( + transport.mock.calls.map(([, m]) => (m as { key: string }).key), + ).toEqual(['deposit-pending:42', 'deposit-claim:42', 'deposit-pending:44']); + }); + + it.each([ + [ORDER_PAYMENT_PENDING, { ...PENDING, amount: '56000' }], + [ORDER_PAYMENT_PENDING, { ...PENDING, expiresAt: 'not-a-date' }], + [PAYMENT_DEPOSIT_CLAIMED, { ...CLAIMED, orderId: 43 }], + [PAYMENT_DEPOSIT_CLAIMED, null], + ])( + '반증: %s의 형식이 어긋난 payload는 던진다(재시도·DLQ로 드러난다)', + async (type, payload) => { + const consumer = build({ baseUrl: null }); + await expect( + consumer.handle(event(type, payload as OutboxEvent['payload'])), + ).rejects.toThrow('payload 형식 오류'); + expect(transport).not.toHaveBeenCalled(); + }, + ); + + it('반증: 구독하지 않은 이벤트는 던진다', async () => { + const consumer = build({ baseUrl: null }); + await expect(consumer.handle(event('order.unknown', {}))).rejects.toThrow( + '구독하지 않은 outbox 이벤트', + ); + }); +}); diff --git a/src/features/order/services/order-admin-alert.consumer.ts b/src/features/order/services/order-admin-alert.consumer.ts new file mode 100644 index 00000000..ff80ca72 --- /dev/null +++ b/src/features/order/services/order-admin-alert.consumer.ts @@ -0,0 +1,57 @@ +import { Injectable } from '@nestjs/common'; +import { ConfigService } from '@nestjs/config'; + +import type { AdminWebConfig } from '@/config/admin-web.config'; +import { + ORDER_PAYMENT_PENDING, + parseOrderPaymentPendingPayload, +} from '@/features/order/events/order-payment-pending.event'; +import { + parsePaymentDepositClaimedPayload, + PAYMENT_DEPOSIT_CLAIMED, +} from '@/features/order/events/payment-deposit-claimed.event'; +import { + buildDepositClaimedAlert, + buildDepositPendingAlert, +} from '@/features/order/services/order-admin-alert-messages.helper'; +import { + type OutboxConsumer, + type OutboxEvent, + SubscribeOutbox, +} from '@/features/outbox'; +import { AlertService, type AlertMessage } from '@/global/alerting'; + +/** + * 관리자 처리 대기 알림(디스코드, info). 상태를 바꾸지 않는다 — 재전달 중복은 AlertService 억제 창(건별 key) 안에서만 + * 막고, 창이 지난 재전달은 같은 알림이 다시 갈 수 있다(진실은 adminTaskCounts·처리 대기 목록). + */ +@Injectable() +@SubscribeOutbox(ORDER_PAYMENT_PENDING, PAYMENT_DEPOSIT_CLAIMED) +export class OrderAdminAlertConsumer implements OutboxConsumer { + constructor( + private readonly alerts: AlertService, + private readonly config: ConfigService, + ) {} + + async handle(event: OutboxEvent): Promise { + await this.alerts.notify(this.messageOf(event)); + } + + private messageOf(event: OutboxEvent): AlertMessage { + const { baseUrl } = this.config.getOrThrow('adminWeb'); + switch (event.eventType) { + case ORDER_PAYMENT_PENDING: + return buildDepositPendingAlert( + parseOrderPaymentPendingPayload(event.payload), + baseUrl, + ); + case PAYMENT_DEPOSIT_CLAIMED: + return buildDepositClaimedAlert( + parsePaymentDepositClaimedPayload(event.payload), + baseUrl, + ); + default: + throw new Error(`구독하지 않은 outbox 이벤트: ${event.eventType}`); + } + } +} diff --git a/src/features/order/services/order-checkout.service.spec.ts b/src/features/order/services/order-checkout.service.spec.ts index ce47f52a..36b42a9a 100644 --- a/src/features/order/services/order-checkout.service.spec.ts +++ b/src/features/order/services/order-checkout.service.spec.ts @@ -5,6 +5,10 @@ import { RandomService } from '@/common/providers/random.service'; import { AUDIT_LOG_REPOSITORY } from '@/features/audit-log'; import { AuditLogRepository } from '@/features/audit-log/repositories/audit-log.repository'; import type { CreateOrderInput } from '@/features/order/dto/inputs/create-order.input'; +import { + ORDER_PAYMENT_PENDING, + parseOrderPaymentPendingPayload, +} from '@/features/order/events/order-payment-pending.event'; import { ORDER_SUBMITTED } from '@/features/order/events/order-submitted.event'; import { pendingPaymentLockName } from '@/features/order/repositories/order-pending-payment-lock.helper'; import { OrderRepository } from '@/features/order/repositories/order.repository'; @@ -1214,8 +1218,78 @@ describe('OrderCheckoutService (real DB)', () => { }); }); - describe('createOrder — 판매자 비노출', () => { - it('판매자 새 주문 이벤트(order.submitted)도 구독 발행도 없다(입금 확인 뒤에 보인다)', async () => { + describe('createOrder — 입금 대기 이벤트(order.payment_pending)', () => { + async function pendingEvents() { + return prisma.outbox.findMany({ + where: { event_type: ORDER_PAYMENT_PENDING }, + orderBy: { id: 'asc' }, + }); + } + + it('생성과 같은 tx에 1건 남기고, 판매자 새 주문(order.submitted)은 남기지 않는다', async () => { + const store = await makeOpenStore(); + const product = await createProduct(prisma, { store_id: store.id }); + const buyer = await makeBuyer('010-1234-5678', '차차'); + + const result = await service.createOrder( + buyer.id, + baseInput({ productId: product.id.toString() }), + ); + + const events = await pendingEvents(); + expect(events).toHaveLength(1); + expect(events[0]).toMatchObject({ + aggregate_id: result.orderId, + occurred_at: NOW, + actor_account_id: buyer.id, + }); + expect(parseOrderPaymentPendingPayload(events[0].payload_json)).toEqual({ + orderId: result.orderId, + orderNumber: result.orderNumber, + amount: 10_000, + depositorName: '차차', + expiresAt: new Date(NOW.getTime() + 60 * 60_000).toISOString(), + }); + expect( + await prisma.outbox.count({ where: { event_type: ORDER_SUBMITTED } }), + ).toBe(0); + }); + + it('반증: capacity 거절과 같은 키 replay는 이벤트를 남기지 않는다', async () => { + const store = await makeOpenStore(); + const product = await createProduct(prisma, { store_id: store.id }); + const buyer = await makeBuyer(); + await createStoreDailyCapacity(prisma, { + store_id: store.id, + capacity_date: new Date(Date.UTC(2026, 8, 18)), + capacity: 1, + }); + await expect( + service.createOrder( + buyer.id, + baseInput({ productId: product.id.toString(), quantity: 2 }), + ), + ).rejects.toThrowDomain('PICKUP_NOT_AVAILABLE'); + expect(await pendingEvents()).toHaveLength(0); + + const input = baseInput({ + idempotencyKey: 'replay-idem-key', + productId: product.id.toString(), + }); + const first = await service.createOrder(buyer.id, input); + expect(await service.createOrder(buyer.id, input)).toEqual(first); + // 사전 조회 miss → tx 안 capacity 거절 → replay 경로 + jest + .spyOn(orderRepo, 'findOrderByIdempotencyKey') + .mockResolvedValueOnce(null); + expect(await service.createOrder(buyer.id, input)).toEqual(first); + + const events = await pendingEvents(); + expect(events).toHaveLength(1); + expect(events[0].aggregate_id).toBe(first.orderId); + }); + + it('판매자 주문 구독에는 아무것도 발행하지 않는다(입금 확인 뒤에 보인다)', async () => { const store = await makeOpenStore(); const product = await createProduct(prisma, { store_id: store.id }); const buyer = await makeBuyer(); @@ -1227,9 +1301,6 @@ describe('OrderCheckoutService (real DB)', () => { ); expect(await prisma.order.count()).toBe(1); - expect( - await prisma.outbox.count({ where: { event_type: ORDER_SUBMITTED } }), - ).toBe(0); expect(topic.received).toEqual([]); topic.stop(); }); diff --git a/src/features/order/services/order-my.service.spec.ts b/src/features/order/services/order-my.service.spec.ts index ffdcf52d..ffa0e1ba 100644 --- a/src/features/order/services/order-my.service.spec.ts +++ b/src/features/order/services/order-my.service.spec.ts @@ -1,6 +1,10 @@ import { ClockService } from '@/common/providers/clock.service'; import { AUDIT_LOG_REPOSITORY } from '@/features/audit-log'; import { AuditLogRepository } from '@/features/audit-log/repositories/audit-log.repository'; +import { + parsePaymentDepositClaimedPayload, + PAYMENT_DEPOSIT_CLAIMED, +} from '@/features/order/events/payment-deposit-claimed.event'; import { OrderRepository } from '@/features/order/repositories/order.repository'; import { PaymentRepository } from '@/features/order/repositories/payment.repository'; import { UserOrderService } from '@/features/order/services/order-my.service'; @@ -608,8 +612,12 @@ describe('UserOrderService (real DB)', () => { const claimedCount = () => prisma.payment.count({ where: { buyer_claimed_at: { not: null } } }); + const claimEvents = () => + prisma.outbox.findMany({ + where: { event_type: PAYMENT_DEPOSIT_CLAIMED }, + }); - it('기한 전 첫 누름은 시각을 기록한다', async () => { + it('기한 전 첫 누름은 시각을 기록하고 확인 요청 이벤트를 남긴다', async () => { const account = await setupUser(); const order = await pendingOrder(account.id); jest.spyOn(clock, 'now').mockReturnValue(NOW); @@ -620,6 +628,21 @@ describe('UserOrderService (real DB)', () => { await expect( prisma.payment.findUniqueOrThrow({ where: { order_id: order.id } }), ).resolves.toMatchObject({ buyer_claimed_at: NOW, status: 'PENDING' }); + const events = await claimEvents(); + expect(events).toHaveLength(1); + expect(events[0]).toMatchObject({ + aggregate_id: order.id.toString(), + actor_account_id: account.id, + occurred_at: NOW, + }); + expect(parsePaymentDepositClaimedPayload(events[0].payload_json)).toEqual( + { + orderId: order.id.toString(), + orderNumber: order.order_number, + amount: order.total_price, + depositorName: '차차맘', + }, + ); }); it('다시 누르면 기한이 지났어도 바꾸지 않고 그대로 돌려준다(멱등)', async () => { @@ -634,6 +657,7 @@ describe('UserOrderService (real DB)', () => { const again = await service.markMyOrderDepositSent(account.id, order.id); expect(again.payment).toMatchObject({ buyerClaimedAt: NOW }); + expect(await claimEvents()).toHaveLength(1); }); it.each([ @@ -650,6 +674,7 @@ describe('UserOrderService (real DB)', () => { service.markMyOrderDepositSent(account.id, order.id), ).rejects.toThrowDomain('PAYMENT_DEADLINE_PASSED'); expect(await claimedCount()).toBe(0); + expect(await claimEvents()).toHaveLength(0); }, ); @@ -707,6 +732,7 @@ describe('UserOrderService (real DB)', () => { ).rejects.toThrowDomain('ORDER_NOT_FOUND'); } expect(await claimedCount()).toBe(0); + expect(await claimEvents()).toHaveLength(0); }); }); }); diff --git a/src/global/alerting/alert.service.spec.ts b/src/global/alerting/alert.service.spec.ts index 3e8fdfec..3d87d0df 100644 --- a/src/global/alerting/alert.service.spec.ts +++ b/src/global/alerting/alert.service.spec.ts @@ -11,7 +11,15 @@ import type { CustomLoggerService } from '@/global/logger/custom-logger.service' describe('AlertService', () => { const START = 1_000_000; let nowMs = START; - const logger = { warn: jest.fn() } as unknown as CustomLoggerService; + const logger = { + warn: jest.fn(), + log: jest.fn(), + } as unknown as CustomLoggerService; + const trackedKeys = (service: AlertService) => [ + ...( + service as unknown as { lastSentAt: Map } + ).lastSentAt.keys(), + ]; function build( config: Partial = {}, @@ -91,6 +99,37 @@ describe('AlertService', () => { }); }); + it('웹훅 미설정이면 info(업무 알림)는 경고가 아닌 일반 로그로 남긴다', async () => { + const { service } = build({ discordWebhookUrl: null }); + + await service.notify({ level: 'info', title: '입금 확인 요청', key: 'k' }); + + expect(logger.log).toHaveBeenCalledWith('[alert:info] 입금 확인 요청', { + detail: undefined, + delivered: false, + }); + expect(logger.warn).not.toHaveBeenCalled(); + }); + + it('건별 key가 쌓이지 않게 억제 창이 지난 key는 다음 notify 때 지운다', async () => { + const { service } = build({ dedupeWindowMs: 5_000 }); + + await service.notify({ level: 'info', title: 't', key: 'deposit-claim:1' }); + nowMs += 1_000; + await service.notify({ level: 'info', title: 't', key: 'deposit-claim:2' }); + expect(trackedKeys(service)).toEqual([ + 'deposit-claim:1', + 'deposit-claim:2', + ]); + + nowMs += 4_000; // 1번은 창(5초)이 정확히 지났고 2번은 남았다 + await service.notify({ level: 'info', title: 't', key: 'deposit-claim:3' }); + expect(trackedKeys(service)).toEqual([ + 'deposit-claim:2', + 'deposit-claim:3', + ]); + }); + it('반증: 전송 실패는 failed로 돌려줄 뿐 던지지 않고, 실패도 억제 창을 열되 1회는 뒤늦게 재전송한다', async () => { jest.useFakeTimers(); try { @@ -144,6 +183,30 @@ describe('AlertService', () => { } }); + it('억제 창이 지나 key가 지워졌어도(새 시도 없음) 실패한 경보는 재전송한다', async () => { + jest.useFakeTimers(); + try { + const { service, transport } = build( + { dedupeWindowMs: 1_000 }, + jest.fn().mockResolvedValueOnce(false).mockResolvedValue(true), + ); + await service.notify({ level: 'error', title: 't', key: 'a' }); + nowMs += 2_000; // 다른 key 알림이 a를 지운다 + await service.notify({ level: 'error', title: 'u', key: 'b' }); + expect(trackedKeys(service)).toEqual(['b']); + + await jest.advanceTimersByTimeAsync(ALERT_RETRY_DELAY_MS); + expect(transport).toHaveBeenCalledTimes(3); + expect(transport).toHaveBeenLastCalledWith( + expect.any(String), + expect.objectContaining({ key: 'a' }), + expect.any(Object), + ); + } finally { + jest.useRealTimers(); + } + }); + it('반증: 재전송도 실패하면 경고 로그만 남기고 끝난다(억제 창이 지난 다음 발생 때 다시)', async () => { jest.useFakeTimers(); try { diff --git a/src/global/alerting/alert.service.ts b/src/global/alerting/alert.service.ts index 03bce17b..56a21dee 100644 --- a/src/global/alerting/alert.service.ts +++ b/src/global/alerting/alert.service.ts @@ -17,7 +17,7 @@ export type AlertOutcome = 'sent' | 'suppressed' | 'skipped' | 'failed'; export const ALERT_RETRY_DELAY_MS = 5_000; /** - * 운영 경보의 단일 출구. 절대 던지지 않고 결과만 돌려준다 — 경보 때문에 본 작업이 실패하면 안 된다. + * 운영 경보·업무 알림의 단일 출구. 절대 던지지 않고 결과만 돌려준다 — 경보 때문에 본 작업이 실패하면 안 된다. * 웹훅이 없으면 로그로만 남기고, 같은 key는 억제 창 안에서 한 번만 보낸다. */ @Injectable() @@ -36,6 +36,7 @@ export class AlertService { this.config.getOrThrow('alerting'); const key = message.key ?? message.title; const now = this.clock.nowMs(); + this.forgetExpired(now, dedupeWindowMs); const last = this.lastSentAt.get(key); if (last !== undefined && now - last < dedupeWindowMs) return 'suppressed'; @@ -43,7 +44,8 @@ export class AlertService { this.lastSentAt.set(key, now); const line = `[alert:${message.level}] ${message.title}`; if (!discordWebhookUrl) { - this.logger.warn(line, { detail: message.detail, delivered: false }); + const log = message.level === 'info' ? 'log' : 'warn'; + this.logger[log](line, { detail: message.detail, delivered: false }); return 'skipped'; } const origin = { @@ -64,6 +66,13 @@ export class AlertService { return 'sent'; } + /** 주문·환불 건별 key가 쌓이지 않게 억제 창이 지난 key를 지운다. */ + private forgetExpired(now: number, windowMs: number): void { + for (const [key, at] of this.lastSentAt) { + if (now - at >= windowMs) this.lastSentAt.delete(key); + } + } + /** * 일회성 사건(outbox FAILED 1건 등)의 유일한 경보가 잠깐의 웹훅 장애로 사라지지 않게 1회만 뒤늦게 다시 보낸다. * 억제 창은 첫 시도가 열었으므로 재전송은 창과 무관하다. 그래도 실패하면 창이 지난 다음 발생 때 다시. @@ -77,8 +86,10 @@ export class AlertService { attemptedAt: number, ): void { const timer = setTimeout(() => { - // 그 사이 같은 키로 더 새 시도가 있었으면(억제 창이 재전송 간격보다 짧을 때) 묵은 경보는 보내지 않는다 - if (this.lastSentAt.get(key) !== attemptedAt) return; + // 그 사이 같은 키로 더 새 시도가 있었으면(억제 창이 재전송 간격보다 짧을 때) 묵은 경보는 보내지 않는다. + // 창이 지나 key가 지워졌을 뿐이면 새 시도가 없었던 것이다 + const latest = this.lastSentAt.get(key); + if (latest !== undefined && latest !== attemptedAt) return; void this.transport(url, message, origin).then((ok) => { if (!ok) { this.logger.warn(`${line} — 재전송도 실패`, { diff --git a/src/global/alerting/discord-webhook.spec.ts b/src/global/alerting/discord-webhook.spec.ts index be6abe82..98866ea1 100644 --- a/src/global/alerting/discord-webhook.spec.ts +++ b/src/global/alerting/discord-webhook.spec.ts @@ -42,6 +42,21 @@ describe('buildDiscordPayload', () => { expect(payload.embeds[0].description).toHaveLength(1_800); expect(payload.embeds[0].color).toBe(0xf59e0b); }); + + // 업무 알림과 장애 경보가 같은 채널이라 색으로 가른다 + it.each([ + ['info', 0x3b82f6], + ['warn', 0xf59e0b], + ['error', 0xef4444], + ] as const)('%s 색은 %s다', (level, color) => { + const payload = buildDiscordPayload( + { level, title: 't' }, + { role: 'worker', env: 'test' }, + at, + ) as { embeds: Array<{ title: string; color: number }> }; + + expect(payload.embeds[0]).toMatchObject({ title: `[${level}] t`, color }); + }); }); describe('postDiscordAlert (real http)', () => { diff --git a/src/global/alerting/discord-webhook.ts b/src/global/alerting/discord-webhook.ts index c82770b5..3053c5bf 100644 --- a/src/global/alerting/discord-webhook.ts +++ b/src/global/alerting/discord-webhook.ts @@ -1,6 +1,7 @@ import { hostname } from 'node:os'; -export type AlertLevel = 'warn' | 'error'; +/** info는 사람이 처리할 업무 알림(입금 확인 요청 등), warn·error는 장애 경보. 같은 채널이라 색으로 가른다. */ +export type AlertLevel = 'info' | 'warn' | 'error'; export interface AlertMessage { level: AlertLevel; @@ -27,7 +28,11 @@ export const ALERT_TRANSPORT = Symbol('ALERT_TRANSPORT'); /** Discord 웹훅 전송 상한 — 경보 때문에 요청·소비가 매달리면 안 된다. */ export const ALERT_POST_TIMEOUT_MS = 3_000; const DESCRIPTION_LIMIT = 1_800; -const COLOR: Record = { warn: 0xf59e0b, error: 0xef4444 }; +const COLOR: Record = { + info: 0x3b82f6, + warn: 0xf59e0b, + error: 0xef4444, +}; export function buildDiscordPayload( message: AlertMessage, diff --git a/src/global/alerting/index.ts b/src/global/alerting/index.ts index 26671f25..4b8bb59a 100644 --- a/src/global/alerting/index.ts +++ b/src/global/alerting/index.ts @@ -1,4 +1,7 @@ export { AlertService } from '@/global/alerting/alert.service'; export { AlertingModule } from '@/global/alerting/alerting.module'; -export { postDiscordAlert } from '@/global/alerting/discord-webhook'; +export { + postDiscordAlert, + type AlertMessage, +} from '@/global/alerting/discord-webhook'; export { shouldSendBootAlert } from '@/global/alerting/boot-alert-throttle'; From cf0d9f7e96b96f796190378a5b1d0050aa31ef26 Mon Sep 17 00:00:00 2001 From: chanwoo7 Date: Thu, 19 Nov 2026 04:02:02 +0900 Subject: [PATCH 21/54] =?UTF-8?q?fix:=20=EA=B0=99=EC=9D=80=20key=EC=9D=98?= =?UTF-8?q?=20=EC=83=88=20=EA=B2=BD=EB=B3=B4=20=EC=8B=9C=EB=8F=84=EA=B0=80?= =?UTF-8?q?=20=EB=8C=80=EA=B8=B0=20=EC=A4=91=EC=9D=B8=20=EC=9E=AC=EC=A0=84?= =?UTF-8?q?=EC=86=A1=EC=9D=84=20=EC=B7=A8=EC=86=8C=ED=95=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 억제 창이 지난 key를 지우는 정리를 넣으면서, 재전송 직전 '더 새 시도가 있었는지'를 억제 창 맵으로 판정할 수 없게 됐다. 창이 재전송 간격보다 짧으면 새 시도가 성공한 뒤 다른 key 알림이 key를 지운 경우 묵은 경보가 다시 나갔다. - key별 대기 재전송 타이머(pendingRetries)를 억제 창 맵과 따로 두고, 같은 key의 새 시도가 시작되면 취소 - 테스트: 창 1초, t=0 실패 → t=2 성공 → t=4 다른 key가 정리 → 재전송 없음 --- src/global/alerting/alert.service.spec.ts | 23 +++++++++++++++++++++++ src/global/alerting/alert.service.ts | 14 ++++++++------ 2 files changed, 31 insertions(+), 6 deletions(-) diff --git a/src/global/alerting/alert.service.spec.ts b/src/global/alerting/alert.service.spec.ts index 3d87d0df..cee3bf78 100644 --- a/src/global/alerting/alert.service.spec.ts +++ b/src/global/alerting/alert.service.spec.ts @@ -207,6 +207,29 @@ describe('AlertService', () => { } }); + it('반증: 새 시도가 성공한 뒤 다른 key 알림이 억제 창 정리로 key를 지워도 묵은 경보를 재전송하지 않는다', async () => { + jest.useFakeTimers(); + try { + const { service, transport } = build( + { dedupeWindowMs: 1_000 }, + jest.fn().mockResolvedValueOnce(false).mockResolvedValue(true), + ); + await service.notify({ level: 'error', title: 't', key: 'a' }); // t=0 실패 + nowMs += 2_000; + await jest.advanceTimersByTimeAsync(2_000); + await service.notify({ level: 'error', title: 't', key: 'a' }); // t=2s 성공 + nowMs += 2_000; + await jest.advanceTimersByTimeAsync(2_000); + await service.notify({ level: 'error', title: 'u', key: 'b' }); // t=4s a 정리 + expect(trackedKeys(service)).toEqual(['b']); + + await jest.advanceTimersByTimeAsync(ALERT_RETRY_DELAY_MS); + expect(transport).toHaveBeenCalledTimes(3); + } finally { + jest.useRealTimers(); + } + }); + it('반증: 재전송도 실패하면 경고 로그만 남기고 끝난다(억제 창이 지난 다음 발생 때 다시)', async () => { jest.useFakeTimers(); try { diff --git a/src/global/alerting/alert.service.ts b/src/global/alerting/alert.service.ts index 56a21dee..98b97c47 100644 --- a/src/global/alerting/alert.service.ts +++ b/src/global/alerting/alert.service.ts @@ -23,6 +23,8 @@ export const ALERT_RETRY_DELAY_MS = 5_000; @Injectable() export class AlertService { private readonly lastSentAt = new Map(); + /** key별 대기 중인 재전송. 억제 창 정리와 따로 두어야 key가 지워져도 묵은 재전송이 되살아나지 않는다 */ + private readonly pendingRetries = new Map(); constructor( private readonly config: ConfigService, @@ -40,6 +42,9 @@ export class AlertService { const last = this.lastSentAt.get(key); if (last !== undefined && now - last < dedupeWindowMs) return 'suppressed'; + // 같은 key의 새 시도가 묵은 재전송을 대신한다(억제 창이 재전송 간격보다 짧을 때) + clearTimeout(this.pendingRetries.get(key)); + this.pendingRetries.delete(key); // 억제 기준은 "보내려 한 시각" — 전송 실패가 폭주로 이어지지 않게 한다 this.lastSentAt.set(key, now); const line = `[alert:${message.level}] ${message.title}`; @@ -60,7 +65,7 @@ export class AlertService { detail: message.detail, }, ); - this.scheduleRetry(discordWebhookUrl, message, origin, line, key, now); + this.scheduleRetry(discordWebhookUrl, message, origin, line, key); return 'failed'; } return 'sent'; @@ -83,13 +88,9 @@ export class AlertService { origin: Parameters[2], line: string, key: string, - attemptedAt: number, ): void { const timer = setTimeout(() => { - // 그 사이 같은 키로 더 새 시도가 있었으면(억제 창이 재전송 간격보다 짧을 때) 묵은 경보는 보내지 않는다. - // 창이 지나 key가 지워졌을 뿐이면 새 시도가 없었던 것이다 - const latest = this.lastSentAt.get(key); - if (latest !== undefined && latest !== attemptedAt) return; + this.pendingRetries.delete(key); void this.transport(url, message, origin).then((ok) => { if (!ok) { this.logger.warn(`${line} — 재전송도 실패`, { @@ -99,5 +100,6 @@ export class AlertService { }); }, ALERT_RETRY_DELAY_MS); timer.unref(); + this.pendingRetries.set(key, timer); } } From e6ca015a655563e212b0d0fdf66d9493e83a9c0c Mon Sep 17 00:00:00 2001 From: chanwoo7 Date: Thu, 19 Nov 2026 04:10:06 +0900 Subject: [PATCH 22/54] =?UTF-8?q?fix:=20=EA=B2=BD=EB=B3=B4=20=EC=9E=AC?= =?UTF-8?q?=EC=A0=84=EC=86=A1=EC=9D=84=20key=EB=B3=84=20=EC=8B=9C=EB=8F=84?= =?UTF-8?q?=20=EB=B2=88=ED=98=B8=EB=A1=9C=20=ED=8C=90=EC=A0=95=ED=95=B4=20?= =?UTF-8?q?=EA=B2=B9=EC=B9=9C=20=EC=A0=84=EC=86=A1=EC=97=90=EC=84=9C?= =?UTF-8?q?=EB=8F=84=20=EB=AC=B5=EC=9D=80=20=EC=9E=AC=EC=A0=84=EC=86=A1?= =?UTF-8?q?=EC=9D=84=20=EB=A7=89=EC=9D=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 새 시도가 묵은 시도의 전송이 끝나기 전에 성공하면 취소할 대기 타이머가 아직 없어, 늦게 실패한 묵은 시도가 재전송을 예약했다(old, new, old). - 전송 전에 key별 시도 번호(전역 증가)를 등록하고, 재전송 예약 직전·실행 직전에 최신인지 확인 - 억제 창 정리와 독립, 전송·재전송이 끝나면 번호를 지워 쌓이지 않음 - 대기 타이머 맵(pendingRetries)은 제거 - 테스트: 겹친 전송에서 재전송 없음·번호 정리(이전 구현에서 3회 호출로 실패 확인) --- src/global/alerting/alert.service.spec.ts | 32 +++++++++++++++++ src/global/alerting/alert.service.ts | 42 ++++++++++++++--------- 2 files changed, 57 insertions(+), 17 deletions(-) diff --git a/src/global/alerting/alert.service.spec.ts b/src/global/alerting/alert.service.spec.ts index cee3bf78..382a351e 100644 --- a/src/global/alerting/alert.service.spec.ts +++ b/src/global/alerting/alert.service.spec.ts @@ -20,6 +20,11 @@ describe('AlertService', () => { service as unknown as { lastSentAt: Map } ).lastSentAt.keys(), ]; + const trackedAttempts = (service: AlertService) => [ + ...( + service as unknown as { latestAttempt: Map } + ).latestAttempt.keys(), + ]; function build( config: Partial = {}, @@ -230,6 +235,33 @@ describe('AlertService', () => { } }); + it('반증: 겹친 전송에서 더 새 시도가 먼저 성공하면 늦게 실패한 묵은 시도는 재전송하지 않는다', async () => { + jest.useFakeTimers(); + try { + let failOld!: (ok: boolean) => void; + const { service, transport } = build( + { dedupeWindowMs: 1_000 }, + jest + .fn() + .mockReturnValueOnce(new Promise((r) => (failOld = r))) + .mockResolvedValue(true), + ); + const old = service.notify({ level: 'error', title: 't', key: 'a' }); // t=0 전송 중 + nowMs += 1_500; + await expect( + service.notify({ level: 'error', title: 't', key: 'a' }), + ).resolves.toBe('sent'); // t=1.5s 새 시도 성공 + failOld(false); // t=2.5s 묵은 시도 실패 + await expect(old).resolves.toBe('failed'); + + await jest.advanceTimersByTimeAsync(ALERT_RETRY_DELAY_MS); + expect(transport).toHaveBeenCalledTimes(2); + expect(trackedAttempts(service)).toEqual([]); + } finally { + jest.useRealTimers(); + } + }); + it('반증: 재전송도 실패하면 경고 로그만 남기고 끝난다(억제 창이 지난 다음 발생 때 다시)', async () => { jest.useFakeTimers(); try { diff --git a/src/global/alerting/alert.service.ts b/src/global/alerting/alert.service.ts index 98b97c47..967ee3a6 100644 --- a/src/global/alerting/alert.service.ts +++ b/src/global/alerting/alert.service.ts @@ -23,8 +23,12 @@ export const ALERT_RETRY_DELAY_MS = 5_000; @Injectable() export class AlertService { private readonly lastSentAt = new Map(); - /** key별 대기 중인 재전송. 억제 창 정리와 따로 두어야 key가 지워져도 묵은 재전송이 되살아나지 않는다 */ - private readonly pendingRetries = new Map(); + /** + * key별 진행 중인 마지막 전송 시도 번호(전송·재전송이 끝나면 지운다). 억제 창 정리와 따로 두어, + * 정리나 겹친 전송이 이미 더 새 시도로 대체된 경보의 재전송을 되살리지 않게 한다 + */ + private readonly latestAttempt = new Map(); + private attemptSeq = 0; constructor( private readonly config: ConfigService, @@ -42,9 +46,6 @@ export class AlertService { const last = this.lastSentAt.get(key); if (last !== undefined && now - last < dedupeWindowMs) return 'suppressed'; - // 같은 key의 새 시도가 묵은 재전송을 대신한다(억제 창이 재전송 간격보다 짧을 때) - clearTimeout(this.pendingRetries.get(key)); - this.pendingRetries.delete(key); // 억제 기준은 "보내려 한 시각" — 전송 실패가 폭주로 이어지지 않게 한다 this.lastSentAt.set(key, now); const line = `[alert:${message.level}] ${message.title}`; @@ -57,18 +58,24 @@ export class AlertService { role: resolveAppRole(), env: process.env.NODE_ENV ?? 'development', }; + // 같은 key의 새 시도가 묵은 시도의 재전송을 대신한다(억제 창이 재전송 간격·전송 시간보다 짧을 때) + const attempt = ++this.attemptSeq; + this.latestAttempt.set(key, attempt); const ok = await this.transport(discordWebhookUrl, message, origin); - if (!ok) { - this.logger.warn( - `${line} — Discord 전송 실패, ${ALERT_RETRY_DELAY_MS}ms 뒤 1회 재전송`, - { - detail: message.detail, - }, - ); - this.scheduleRetry(discordWebhookUrl, message, origin, line, key); - return 'failed'; + if (ok || this.latestAttempt.get(key) !== attempt) { + this.settle(key, attempt); + return ok ? 'sent' : 'failed'; } - return 'sent'; + this.logger.warn( + `${line} — Discord 전송 실패, ${ALERT_RETRY_DELAY_MS}ms 뒤 1회 재전송`, + { detail: message.detail }, + ); + this.scheduleRetry(discordWebhookUrl, message, origin, line, key, attempt); + return 'failed'; + } + + private settle(key: string, attempt: number): void { + if (this.latestAttempt.get(key) === attempt) this.latestAttempt.delete(key); } /** 주문·환불 건별 key가 쌓이지 않게 억제 창이 지난 key를 지운다. */ @@ -88,10 +95,12 @@ export class AlertService { origin: Parameters[2], line: string, key: string, + attempt: number, ): void { const timer = setTimeout(() => { - this.pendingRetries.delete(key); + if (this.latestAttempt.get(key) !== attempt) return; void this.transport(url, message, origin).then((ok) => { + this.settle(key, attempt); if (!ok) { this.logger.warn(`${line} — 재전송도 실패`, { detail: message.detail, @@ -100,6 +109,5 @@ export class AlertService { }); }, ALERT_RETRY_DELAY_MS); timer.unref(); - this.pendingRetries.set(key, timer); } } From 55826283f5783ce42dbd796d1a15777792e08f8b Mon Sep 17 00:00:00 2001 From: chanwoo7 Date: Thu, 19 Nov 2026 02:28:25 +0900 Subject: [PATCH 23/54] =?UTF-8?q?feat:=203D=20=EC=BC=80=EC=9D=B4=ED=81=AC?= =?UTF-8?q?=20=EC=B9=B4=ED=83=88=EB=A1=9C=EA=B7=B8=20=EA=B3=B5=EA=B0=9C=20?= =?UTF-8?q?=EC=A1=B0=ED=9A=8C=EC=99=80=20=EC=97=90=EC=85=8B=20=EC=97=85?= =?UTF-8?q?=EB=A1=9C=EB=93=9C=20=EC=8A=A4=ED=81=AC=EB=A6=BD=ED=8A=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 판매자 앱 3D 렌더러와 서버 디자인 검증이 같은 허용 목록을 쓰도록 3D 카탈로그(모양·크기·디자인·맛 선택지, 시트 색, 글자색, 효과, 꾸미기, 한도)를 서버 상수로 두고 공개 쿼리로 내보낸다. 값은 구매자 편집기 상수를 그대로 옮기되 지금 쓸 수 있는 것만 담는다(디자인 5종, 이미지 있는 꾸미기 숫자 0~7). 항목은 지우지 않고 selectable=false로 퇴역시켜 과거 주문이 같은 모습으로 그려진다. 변경점 - product 상수 custom-3d-catalog.constants: 선택지 key는 카테고리.값(shape.heart, design.heart처럼 값이 겹쳐도 구분), 크기 renderScale 0.7·0.82·1, 디자인 기본 가격 물결 0·흘림·하트·반짝 1000·문구 2000, 모양 +1000, 1호 +5000, 시트 색 6, 글자색 프리셋 17(기본 #1D1D1D, 대문자), 효과 4(기본 강도 50), 한도(면당 글자·꾸미기 10, 글자 30자, 글자 크기 4~30·꾸미기 8~50cqw, 효과 강도 0~100) - 에셋 13개(디자인 5 + 꾸미기 8)를 assets/custom-3d-catalog/v1에 커밋. S3 key는 같은 경로 - 공개 쿼리 customThreeDCatalog(비로그인): 에셋 경로를 이 환경 버킷의 공개 URL로 바꿔 내보내고 한 번 만든 결과를 재사용. enum ThreeDOptionCategoryType(SIZE·FLAVOR·SHAPE·DESIGN) 신설 - S3Service.publicUrlFor(key): private buildPublicUrl을 공개로 바꿔 업로드 URL과 고정 에셋 URL이 같은 규칙을 쓴다 - yarn catalog:upload --bucket <버킷> [--dry-run]: 같은 내용(ETag = MD5)은 건너뛰고, 같은 경로에 다른 내용이 있으면 아무것도 올리지 않고 실패한다(immutable 캐시). 버킷은 기본값 없이 인자로만. worker 컨테이너에서 돌리도록 이미지에 assets를 싣고 runbook·README에 절차를 적었다 테스트 - 에셋 대조: 상수가 가리키는 파일 13개 = 폴더의 파일 13개, 양방향 반증(빠진 파일·남는 파일), PNG 서명 - 카탈로그 값 고정 표(선택지 key·값·가격·배율·이미지, 시트 색 hex, 효과, 꾸미기), key 형식·40자 이하·중복 없음, 카테고리별 선택 가능 수, 색 형식 - 공개 쿼리: 에셋 URL 변환, 결과 재사용 / publicUrlFor 1 - 업로드 스크립트: 인자 2 + 반증 7, 형식 3 + 반증 3, 계획(건너뛰기·업로드·다른 내용이면 전체 중단) - 가드 반증: 에셋 파일을 더하거나 빼면, 업로드 충돌·버킷 검사를 끄면 해당 테스트가 실패함을 확인 --- Dockerfile | 2 + README.md | 1 + assets/custom-3d-catalog/v1/deco/number-0.png | Bin 0 -> 9529 bytes assets/custom-3d-catalog/v1/deco/number-1.png | Bin 0 -> 7246 bytes assets/custom-3d-catalog/v1/deco/number-2.png | Bin 0 -> 8192 bytes assets/custom-3d-catalog/v1/deco/number-3.png | Bin 0 -> 7767 bytes assets/custom-3d-catalog/v1/deco/number-4.png | Bin 0 -> 9232 bytes assets/custom-3d-catalog/v1/deco/number-5.png | Bin 0 -> 8735 bytes assets/custom-3d-catalog/v1/deco/number-6.png | Bin 0 -> 9445 bytes assets/custom-3d-catalog/v1/deco/number-7.png | Bin 0 -> 6269 bytes assets/custom-3d-catalog/v1/design/drip.png | Bin 0 -> 7851 bytes assets/custom-3d-catalog/v1/design/heart.png | Bin 0 -> 6848 bytes assets/custom-3d-catalog/v1/design/phrase.png | Bin 0 -> 7166 bytes .../custom-3d-catalog/v1/design/sparkle.png | Bin 0 -> 8277 bytes assets/custom-3d-catalog/v1/design/wave.png | Bin 0 -> 7379 bytes infra/runbook.md | 7 + package.json | 1 + scripts/catalog-upload-plan.ts | 58 +++++ scripts/catalog-upload.spec.ts | 80 +++++++ scripts/catalog-upload.ts | 98 ++++++++ .../custom-3d-catalog.constants.spec.ts | 192 ++++++++++++++++ .../constants/custom-3d-catalog.constants.ts | 192 ++++++++++++++++ .../product/product-custom-catalog.graphql | 217 ++++++++++++++++++ src/features/product/product.module.ts | 4 + src/features/product/product.types.graphql | 14 ++ ...duct-custom-catalog-query.resolver.spec.ts | 54 +++++ .../product-custom-catalog-query.resolver.ts | 14 ++ .../product-custom-catalog.service.ts | 53 +++++ .../product-custom-catalog-output.type.ts | 39 ++++ src/global/storage/s3.service.spec.ts | 10 + src/global/storage/s3.service.ts | 5 +- 31 files changed, 1039 insertions(+), 2 deletions(-) create mode 100644 assets/custom-3d-catalog/v1/deco/number-0.png create mode 100644 assets/custom-3d-catalog/v1/deco/number-1.png create mode 100644 assets/custom-3d-catalog/v1/deco/number-2.png create mode 100644 assets/custom-3d-catalog/v1/deco/number-3.png create mode 100644 assets/custom-3d-catalog/v1/deco/number-4.png create mode 100644 assets/custom-3d-catalog/v1/deco/number-5.png create mode 100644 assets/custom-3d-catalog/v1/deco/number-6.png create mode 100644 assets/custom-3d-catalog/v1/deco/number-7.png create mode 100644 assets/custom-3d-catalog/v1/design/drip.png create mode 100644 assets/custom-3d-catalog/v1/design/heart.png create mode 100644 assets/custom-3d-catalog/v1/design/phrase.png create mode 100644 assets/custom-3d-catalog/v1/design/sparkle.png create mode 100644 assets/custom-3d-catalog/v1/design/wave.png create mode 100644 scripts/catalog-upload-plan.ts create mode 100644 scripts/catalog-upload.spec.ts create mode 100644 scripts/catalog-upload.ts create mode 100644 src/features/product/constants/custom-3d-catalog.constants.spec.ts create mode 100644 src/features/product/constants/custom-3d-catalog.constants.ts create mode 100644 src/features/product/product-custom-catalog.graphql create mode 100644 src/features/product/resolvers/product-custom-catalog-query.resolver.spec.ts create mode 100644 src/features/product/resolvers/product-custom-catalog-query.resolver.ts create mode 100644 src/features/product/services/product-custom-catalog.service.ts create mode 100644 src/features/product/types/product-custom-catalog-output.type.ts diff --git a/Dockerfile b/Dockerfile index c18fd5f7..d34664fb 100644 --- a/Dockerfile +++ b/Dockerfile @@ -35,6 +35,8 @@ COPY --from=build --chown=node:node /app/node_modules ./node_modules COPY --from=build --chown=node:node /app/prisma ./prisma COPY --from=build --chown=node:node /app/src ./src COPY --from=build --chown=node:node /app/scripts ./scripts +# 3D 카탈로그 에셋 — worker 컨테이너에서 yarn catalog:upload로 올린다(infra/runbook.md) +COPY --from=build --chown=node:node /app/assets ./assets COPY --from=build --chown=node:node /app/public ./public COPY --from=build --chown=node:node /app/dist ./dist # corepack은 첫 실행 때 패키지 매니저를 내려받으려 한다(런타임 네트워크 의존) — 릴리즈 파일을 바로 yarn으로 건다 diff --git a/README.md b/README.md index f87edac7..09e270f8 100644 --- a/README.md +++ b/README.md @@ -331,6 +331,7 @@ APP_ROLE=worker PORT=4001 yarn start:dev # (선택) 이벤트 소비까지 보 | `yarn graphql:docs` | SpectaQL HTML 문서를 `public/`에 빌드합니다 | | `yarn outbox:requeue` | 운영에서 FAILED 상태의 outbox 이벤트를 PENDING으로 되돌립니다(`--id=`, `--event-type=`, `--all`). 소비 DLQ에 빠진 이벤트는 `--event-id= --republish`로 다시 싣습니다 | | `yarn accounts:reencrypt` | 계좌번호 암호화 키를 회전한 뒤 첫 키가 아닌 키로 암호화된 환불·정산 계좌번호를 첫 키로 다시 암호화합니다. 대상 수를 먼저 출력하고, `--dry-run`은 대상 수만 출력합니다 | +| `yarn catalog:upload` | 3D 카탈로그 에셋(`assets/custom-3d-catalog`)을 미디어 버킷에 올립니다(`--bucket <버킷>`, `--dry-run`). 같은 내용은 건너뛰고 같은 경로의 다른 내용은 덮어쓰지 않습니다 | ## 🧬 GraphQL diff --git a/assets/custom-3d-catalog/v1/deco/number-0.png b/assets/custom-3d-catalog/v1/deco/number-0.png new file mode 100644 index 0000000000000000000000000000000000000000..44ef5ff330552d0704fd38f95ca4508b70d16b09 GIT binary patch literal 9529 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 literal 0 HcmV?d00001 diff --git a/assets/custom-3d-catalog/v1/deco/number-2.png b/assets/custom-3d-catalog/v1/deco/number-2.png new file mode 100644 index 0000000000000000000000000000000000000000..d797d8129bd128fa69921c13cff343edf83d87df GIT binary patch literal 8192 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 z z0c9|SIiy$kq10t@8KX_&tR*H%6U^u?y=-i4nIWpF9fy(X*Uoni|7uZVE_Nhcffq5| z&p7WM*|U!9O*v*8XCi!VlFo?FOeX0o5YEG6;Fh<%<>ugn4_^0W2^`n7e-!|-YxSF? z|6}J{4kz2k?qz<^EA6Dp7NBU$p@$y&KY?rS#{M?Pq~~T;>0E4M{gn5cYCZGa3F`EI zwV(Ul<~U7C@6K(o*|{l&q@~aybxP#|W;&O4ae60P-0xz=neI_*@u7mLP|0&eQ>o?B zCw2;wbHhx`AlQ$0dY*4W&GV| zd&*ko2E%D?`ivmZ+E~~w_BQP_kpYcAo*wVoGY5{Pn^LB^#WTVjyorr3)LEXY3d_JN zCdy$09Qb{eGIwuIJ30TJsyEZSS;F7VRu;kko}6q=W7lVZ^eqGW*+qZLGtq8;%(R1r zEP4L!156ZPow;gC;I4o3Xp^akQ&DBSAx<^CD7`Y6^n-0_+0e7LN6a0Wlc_0Lb9Ymq zOcl;v2Jrksru}kL#d2Dyq<5uXq5$g5%xEY27t;7m1!rb6O$4wj{kO=|mW~D7)vtc_ ztv8u38k~+RjT@kNC-AgUi??A#X$b>)tm$a}xwC6&0+IU<(4;b{X`!gu&bVjeO0DL% zWOG7DjNBOGDl@zi|=~T>{VdxPlZ!kd*w`o zxJln6D;w$rr1(u}z;Rh1Z>cb8^PW8;3Y$q=p!bDiOMrIOCqRV72Fik7fIj9ik6GI) zERt7NT0JS$m4eJbSSQ6h?pa1u7O%9#KD2p78?yxDq%O6cUbHa^hVyu-HrrxnWP6bH zmn6*u-zpaHFpg1D!-Mt#9e}AKnj5?2!9tg^hQ2IvzVChS+oy(DN#6b!f)qB(#6OG!`=$?Tn=gLxii)~~Nd)UJkV?r3&hn&+p zX8zvyzV`}wfN$bv*paPuzYp2~>F++l1RMYX*=9)e0?mZ?H+sBBTlx&4SkSs}j;Kij z=*&1e7I0!U62ZerrAPq#fDnHd0%V6eGQ_Fib*^)rt%M?w^a@n~qGTlO;od!K!FNuC zm3L;tT0nNnHi+u|g+f4Kuv>galhyl{8!>8^e0H&;0)~Et7Bh`&ms0t71<_fXY@5Xv zIMoWoI_Fn3ZT<41(1hsE5QC&vB643`)b`e!-~8sQPG&bb$?~oxM5?HC?(Ex85{m&q z0;2B;N~eSzfz~9E)B<9ET!jYo6bBZ_3wE1W?X>y({9ct! zAaxjQkp#gEE5HCitf`mHd+J|^>#G&dNR!U*bD#SxNwA?ASZZ-4$jxwSW>2Z0dyF?;ib1JuSw#VKYDc@gTX`K1ee;SpX_;yZ$xRBU<6OXb zSw!7-CycQHEyGbkL@}H^p4nulT5EJ#0Jcg5K!aN|rDA0uNe2njp8b^j${lU;L#Qe+ zRW?@nV_`!cwU0ft&rxN}IUSQ~LMmU)(tX?Zfyo5)?SiB9s`U?a(7;*j(C0pzZpg}SCjwv_16N<@M;ix;x4HO( zzI{@z#C}He1}IE1h_X^;Ae{r+zz=`;!`Fss562b){iH5YdZmu5K&h$ue$#``fSJ)uv~RV=grS zOdsY>?}t9NPao`3Db=i-W&HI)QYPc|)s808s2>vCXOuF7zS-J-1wBexZT%8%ZGkgm z_Ldp6M4D=(G8nfcXw868byXda99uoN%xAW!6rzP8JSb*?UnPYka1_86!gEhYTTBh8Euvb2BayaqVJ=(9W-=F5O0u

r2MD5T0#oFIBYkv9q@`e%(h^`!6$iQj*52-Q_NK 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 T4IIJ$00000NkvXXu0mjfTORw! literal 0 HcmV?d00001 diff --git a/assets/custom-3d-catalog/v1/design/wave.png b/assets/custom-3d-catalog/v1/design/wave.png new file mode 100644 index 0000000000000000000000000000000000000000..db4d844f85284db82e06be30cb35d2943e8602ef GIT binary patch literal 7379 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 FV1husWB&jE literal 0 HcmV?d00001 diff --git a/infra/runbook.md b/infra/runbook.md index cc8f4528..9494524b 100644 --- a/infra/runbook.md +++ b/infra/runbook.md @@ -87,3 +87,10 @@ Actions → `Deploy` → Run workflow → `image_tag`에 이전 sha. 마이그 1. 새 키를 만들어 백업하고, APP_ENV의 `ACCOUNT_ENCRYPTION_KEYS` 맨 앞에 넣어(`k2:<새 키>,k1:<옛 키>`) 배포한다. 이때부터 새로 쓰는 계좌번호는 새 키로 암호화된다. 2. `docker compose exec worker yarn accounts:reencrypt --dry-run`으로 대상 수를 보고, `docker compose exec worker yarn accounts:reencrypt`로 다시 암호화한다. 읽은 뒤 바뀐 행은 건너뛰므로 `--dry-run`이 0이 될 때까지 반복한다. 3. 대상이 0이면 옛 키를 env에서 빼고 배포한다. 옛 키 백업은 DB 백업 보관 기간(14일)이 지날 때까지 남긴다 — 그 전 덤프를 복구하면 옛 키로 암호화된 행이 돌아온다(복구 뒤 1단계부터 다시). + +## 3D 카탈로그 에셋 + +판매자 앱 3D 렌더러와 옵션 칩이 쓰는 이미지(`assets/custom-3d-catalog/v1`)는 미디어 버킷의 같은 경로에서 공개 URL로 열린다(`customThreeDCatalog`). 에셋이 더해진 릴리즈를 배포한 뒤 올린다. 빠지면 렌더러·옵션 칩 이미지가 404다. + +- `docker compose exec worker yarn catalog:upload --bucket <미디어 버킷> --dry-run`으로 올릴 개수를 보고, `--dry-run`을 빼고 올린다. 같은 내용은 건너뛴다. +- 에셋은 `immutable`로 캐시되고 과거 주문이 같은 모습으로 그려져야 해서 덮어쓰지 않는다. 같은 경로에 다른 내용이 있으면 아무것도 올리지 않고 실패한다. 그림을 바꾸려면 새 파일과 새 key를 더하고 옛 key를 `selectable: false`로 퇴역시킨다. diff --git a/package.json b/package.json index a4ebf344..2d5a777d 100644 --- a/package.json +++ b/package.json @@ -40,6 +40,7 @@ "prepare": "husky", "outbox:requeue": "ts-node -r tsconfig-paths/register scripts/outbox-requeue.ts", "accounts:reencrypt": "ts-node -r tsconfig-paths/register scripts/accounts-reencrypt.ts", + "catalog:upload": "ts-node -r tsconfig-paths/register scripts/catalog-upload.ts", "lint:fix": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix" }, "dependencies": { diff --git a/scripts/catalog-upload-plan.ts b/scripts/catalog-upload-plan.ts new file mode 100644 index 00000000..22c094a7 --- /dev/null +++ b/scripts/catalog-upload-plan.ts @@ -0,0 +1,58 @@ +/** 인자·업로드 계획만 — spec이 S3 없이 검증할 수 있게 분리한다. */ +export interface CatalogUploadArgs { + bucket: string; + dryRun: boolean; +} + +const BUCKET_NAME = /^[a-z0-9][a-z0-9.-]{1,61}[a-z0-9]$/; + +/** 버킷은 `--bucket `으로만 받는다 — 기본값이 있으면 엉뚱한 환경에 올라간다. */ +export function parseCatalogUploadArgs(argv: string[]): CatalogUploadArgs { + let bucket: string | undefined; + let dryRun = false; + for (let i = 0; i < argv.length; i += 1) { + if (argv[i] === '--dry-run') dryRun = true; + else if (argv[i] === '--bucket' && BUCKET_NAME.test(argv[i + 1] ?? '')) { + bucket = argv[(i += 1)]; + } else throw new Error(`알 수 없는 인자: ${argv[i]}`); + } + if (!bucket) throw new Error('--bucket <버킷 이름>이 필요합니다'); + return { bucket, dryRun }; +} + +const CONTENT_TYPES: Record = { + '.png': 'image/png', + '.webp': 'image/webp', + '.jpg': 'image/jpeg', +}; + +export function contentTypeOf(path: string): string { + const type = CONTENT_TYPES[path.slice(path.lastIndexOf('.'))]; + if (!type) throw new Error(`올릴 수 없는 에셋 형식: ${path}`); + return type; +} + +export interface CatalogAsset { + key: string; + md5: string; +} + +/** + * 같은 key에 같은 내용(ETag = MD5)이면 건너뛴다. 다른 내용이 이미 있으면 아무것도 올리지 않고 던진다 — + * 에셋은 immutable로 캐시되고 과거 주문이 같은 모습으로 그려져야 하므로, 바꿀 때는 새 경로로 더한다. + */ +export function planCatalogUpload( + assets: CatalogAsset[], + remoteEtags: ReadonlyMap, +): CatalogAsset[] { + const changed = assets.filter((asset) => { + const etag = remoteEtags.get(asset.key); + return etag != null && etag.replaceAll('"', '') !== asset.md5; + }); + if (changed.length > 0) { + throw new Error( + `이미 다른 내용이 올라가 있습니다(덮어쓰지 않음): ${changed.map((a) => a.key).join(', ')}`, + ); + } + return assets.filter((asset) => remoteEtags.get(asset.key) == null); +} diff --git a/scripts/catalog-upload.spec.ts b/scripts/catalog-upload.spec.ts new file mode 100644 index 00000000..82d86f7d --- /dev/null +++ b/scripts/catalog-upload.spec.ts @@ -0,0 +1,80 @@ +import { + contentTypeOf, + parseCatalogUploadArgs, + planCatalogUpload, +} from './catalog-upload-plan'; + +describe('catalog-upload 인자', () => { + it.each([ + [ + ['--bucket', 'caquick-media-prod'], + { bucket: 'caquick-media-prod', dryRun: false }, + ], + [ + ['--dry-run', '--bucket', 'caquick-media-dev'], + { bucket: 'caquick-media-dev', dryRun: true }, + ], + ])('%j → %j', (argv, expected) => { + expect(parseCatalogUploadArgs(argv)).toEqual(expected); + }); + + // 반증 — 버킷 없이·잘못된 형태로는 어느 버킷에도 올리지 않는다 + it.each([ + [[], '--bucket'], + [['--dry-run'], '--bucket'], + [['--bucket'], '알 수 없는 인자'], + [['--bucket=caquick-media-prod'], '알 수 없는 인자'], + [['--bucket', '--dry-run'], '알 수 없는 인자'], + [['--bucket', 'Caquick_Media'], '알 수 없는 인자'], + [['--bucket', 'caquick-media-dev', '--force'], '알 수 없는 인자'], + ])('반증: %j 는 던진다', (argv, message) => { + expect(() => parseCatalogUploadArgs(argv)).toThrow(message); + }); +}); + +describe('catalog-upload 형식', () => { + it.each([ + ['deco/number-0.png', 'image/png'], + ['design/wave.webp', 'image/webp'], + ['x/a.jpg', 'image/jpeg'], + ])('%s → %s', (path, type) => { + expect(contentTypeOf(path)).toBe(type); + }); + + it.each(['notes.txt', '.DS_Store', 'png'])('반증: %s 는 던진다', (path) => { + expect(() => contentTypeOf(path)).toThrow('올릴 수 없는 에셋 형식'); + }); +}); + +describe('catalog-upload 계획', () => { + const a = { key: 'p/a.png', md5: 'aaa' }; + const b = { key: 'p/b.png', md5: 'bbb' }; + + it('없는 것만 올리고 같은 ETag는 건너뛴다', () => { + expect( + planCatalogUpload( + [a, b], + new Map([ + [a.key, '"aaa"'], + [b.key, null], + ]), + ), + ).toEqual([b]); + }); + + it('조회 결과가 없는 key도 올린다', () => { + expect(planCatalogUpload([a], new Map())).toEqual([a]); + }); + + it('반증: 같은 경로에 다른 내용이 있으면 하나도 올리지 않고 던진다', () => { + expect(() => + planCatalogUpload( + [a, b], + new Map([ + [a.key, '"zzz"'], + [b.key, null], + ]), + ), + ).toThrow('p/a.png'); + }); +}); diff --git a/scripts/catalog-upload.ts b/scripts/catalog-upload.ts new file mode 100644 index 00000000..09dad9e6 --- /dev/null +++ b/scripts/catalog-upload.ts @@ -0,0 +1,98 @@ +/** + * 3D 카탈로그 에셋(assets/custom-3d-catalog)을 미디어 버킷에 올린다. 배포 뒤 사람이 돌린다(infra/runbook.md). + * yarn catalog:upload --bucket <버킷> --dry-run # 올릴 대상만 + * yarn catalog:upload --bucket <버킷> + * 같은 내용은 건너뛰고, 같은 경로에 다른 내용이 있으면 아무것도 올리지 않고 실패한다. + */ +import '@/config/preload-env'; + +import { createHash } from 'node:crypto'; +import { readFileSync } from 'node:fs'; +import { join, resolve } from 'node:path'; + +import { + HeadObjectCommand, + PutObjectCommand, + S3Client, + S3ServiceException, +} from '@aws-sdk/client-s3'; + +import { + contentTypeOf, + parseCatalogUploadArgs, + planCatalogUpload, +} from './catalog-upload-plan'; + +import { + catalogAssetPaths, + CUSTOM_3D_ASSET_PREFIX, +} from '@/features/product/constants/custom-3d-catalog.constants'; + +const ASSET_ROOT = resolve(__dirname, '..', 'assets', CUSTOM_3D_ASSET_PREFIX); + +async function remoteEtag( + s3: S3Client, + bucket: string, + key: string, +): Promise { + try { + const head = await s3.send( + new HeadObjectCommand({ Bucket: bucket, Key: key }), + ); + return head.ETag ?? null; + } catch (error) { + // ListBucket 권한이 없으면 없는 객체가 403으로 온다 + const status = + error instanceof S3ServiceException ? error.$metadata.httpStatusCode : 0; + if (status === 404 || status === 403) return null; + throw error; + } +} + +async function main(): Promise { + const { bucket, dryRun } = parseCatalogUploadArgs(process.argv.slice(2)); + const s3 = new S3Client({ + region: process.env.AWS_REGION?.trim() || 'ap-northeast-2', + }); + // 카탈로그가 가리키는 파일 = 폴더의 파일(custom-3d-catalog.constants.spec이 양방향 대조) + const files = catalogAssetPaths().map((relativePath) => { + const path = join(ASSET_ROOT, relativePath); + return { + path, + key: `${CUSTOM_3D_ASSET_PREFIX}/${relativePath}`, + contentType: contentTypeOf(path), + md5: createHash('md5').update(readFileSync(path)).digest('hex'), + }; + }); + const etags = new Map(); + for (const file of files) { + etags.set(file.key, await remoteEtag(s3, bucket, file.key)); + } + const keys = new Set(planCatalogUpload(files, etags).map((a) => a.key)); + const uploads = files.filter((file) => keys.has(file.key)); + process.stdout.write( + `${bucket}: 에셋 ${files.length}개 중 업로드 ${uploads.length}개\n`, + ); + if (dryRun) return; + for (const file of uploads) { + await s3.send( + new PutObjectCommand({ + Bucket: bucket, + Key: file.key, + Body: readFileSync(file.path), + ContentType: file.contentType, + CacheControl: 'public, max-age=31536000, immutable', + }), + ); + process.stdout.write(` ${file.key}\n`); + } +} + +if (require.main === module) { + main().catch((error: unknown) => { + process.stderr.write( + `${error instanceof Error ? error.message : String(error)}\n`, + ); + process.exit(1); + }); +} diff --git a/src/features/product/constants/custom-3d-catalog.constants.spec.ts b/src/features/product/constants/custom-3d-catalog.constants.spec.ts new file mode 100644 index 00000000..e871d37b --- /dev/null +++ b/src/features/product/constants/custom-3d-catalog.constants.spec.ts @@ -0,0 +1,192 @@ +import { readdirSync, readFileSync } from 'node:fs'; +import { join, relative, sep } from 'node:path'; + +import { + catalogAssetPaths, + CUSTOM_3D_ASSET_PREFIX, + findThreeDChoice, + THREE_D_DECO_CATEGORIES, + THREE_D_DECOS, + THREE_D_DEFAULT_TEXT_COLOR, + THREE_D_EFFECTS, + THREE_D_OPTION_CATEGORIES, + THREE_D_OPTION_CHOICES, + THREE_D_SHEET_COLORS, + THREE_D_TEXT_COLOR_PRESETS, +} from '@/features/product/constants/custom-3d-catalog.constants'; + +const ASSET_ROOT = join( + __dirname, + '..', + '..', + '..', + '..', + 'assets', + CUSTOM_3D_ASSET_PREFIX, +); +const PNG_SIGNATURE = Buffer.from([0x89, 0x50, 0x4e, 0x47]); + +function listAssetFiles(dir: string): string[] { + return readdirSync(dir, { withFileTypes: true }).flatMap((entry) => + entry.isDirectory() + ? listAssetFiles(join(dir, entry.name)) + : [relative(ASSET_ROOT, join(dir, entry.name)).split(sep).join('/')], + ); +} + +/** 상수가 가리키는데 없는 파일, 있는데 아무도 가리키지 않는 파일. */ +function diffAssets(referenced: string[], files: string[]) { + return { + missing: referenced.filter((path) => !files.includes(path)), + unreferenced: files.filter((path) => !referenced.includes(path)), + }; +} + +describe('3D 카탈로그 에셋 대조', () => { + const referenced = catalogAssetPaths(); + const files = listAssetFiles(ASSET_ROOT); + + it('대상이 비어 있지 않다(디자인 5 + 꾸미기 8)', () => { + expect(referenced).toHaveLength(13); + expect([...files].sort()).toEqual([...referenced].sort()); + }); + + it('상수가 가리키는 파일이 모두 있고, 아무도 가리키지 않는 파일이 없다', () => { + expect(diffAssets(referenced, files)).toEqual({ + missing: [], + unreferenced: [], + }); + }); + + it('반증: 파일이 빠지거나 남으면 양쪽 모두 잡는다', () => { + expect(diffAssets(referenced, referenced.slice(1))).toEqual({ + missing: [referenced[0]], + unreferenced: [], + }); + expect( + diffAssets(referenced, [...referenced, 'deco/number-8.png']), + ).toEqual({ + missing: [], + unreferenced: ['deco/number-8.png'], + }); + }); + + it.each(referenced)('%s 는 PNG다', (path) => { + const head = readFileSync(join(ASSET_ROOT, path)).subarray(0, 4); + expect(head.equals(PNG_SIGNATURE)).toBe(true); + }); +}); + +describe('3D 카탈로그 상수', () => { + // 값이 바뀌면 과거 주문이 다른 모습으로 그려진다. 바꿀 때는 새 key를 더하고 옛 key를 퇴역시킨다. + it('선택지 값이 고정돼 있다', () => { + expect( + THREE_D_OPTION_CHOICES.map((c) => [ + c.key, + c.value, + c.defaultPriceDelta, + c.renderScale, + c.imagePath, + ]), + ).toEqual([ + ['shape.heart', 'heart', 1000, null, null], + ['shape.circle', 'circle', 1000, null, null], + ['shape.square', 'square', 1000, null, null], + ['shape.star', 'star', 1000, null, null], + ['shape.triangle', 'triangle', 1000, null, null], + ['shape.bear', 'bear', 1000, null, null], + ['shape.clover', 'clover', 1000, null, null], + ['shape.flower', 'flower', 1000, null, null], + ['size.lunchbox', 'lunchbox', 0, 0.7, null], + ['size.mini', 'mini', 0, 0.82, null], + ['size.no1', 'no1', 5000, 1, null], + ['design.wave', 'wave', 0, null, 'design/wave.png'], + ['design.drip', 'drip', 1000, null, 'design/drip.png'], + ['design.phrase', 'phrase', 2000, null, 'design/phrase.png'], + ['design.heart', 'heart', 1000, null, 'design/heart.png'], + ['design.sparkle', 'sparkle', 1000, null, 'design/sparkle.png'], + ['flavor.cream', 'cream', 0, null, null], + ['flavor.vanilla', 'vanilla', 0, null, null], + ['flavor.choco', 'choco', 0, null, null], + ]); + expect(THREE_D_SHEET_COLORS.map((c) => [c.key, c.hex])).toEqual([ + ['white', '#FFFFFF'], + ['pink', '#FFC2CF'], + ['yellow', '#FFE08A'], + ['green', '#B9ECB7'], + ['blue', '#B5D2FF'], + ['purple', '#DCC4FF'], + ]); + expect(THREE_D_EFFECTS.map((e) => e.key)).toEqual([ + 'none', + 'soft', + 'drawing', + 'pencil', + ]); + expect(THREE_D_DECOS.map((d) => [d.key, d.imagePath])).toEqual( + Array.from({ length: 8 }, (_, n) => [ + `number-${n}`, + `deco/number-${n}.png`, + ]), + ); + expect(THREE_D_TEXT_COLOR_PRESETS).toHaveLength(17); + expect(THREE_D_DEFAULT_TEXT_COLOR).toBe('#1D1D1D'); + }); + + it('선택지 key는 카테고리.값 형식이고 옵션 항목 칸(40자)에 들어간다', () => { + for (const c of THREE_D_OPTION_CHOICES) { + expect(c.key).toBe(`${c.category.toLowerCase()}.${c.value}`); + expect(c.key.length).toBeLessThanOrEqual(40); + expect(c.label.trim()).not.toBe(''); + } + }); + + it.each([ + ['선택지', THREE_D_OPTION_CHOICES], + ['시트 색', THREE_D_SHEET_COLORS], + ['효과', THREE_D_EFFECTS], + ['꾸미기', THREE_D_DECOS], + ['꾸미기 분류', THREE_D_DECO_CATEGORIES], + ] as const)('%s key는 겹치지 않는다', (_label, entries) => { + const keys = entries.map((e: { key: string }) => e.key); + expect(new Set(keys).size).toBe(keys.length); + }); + + it('카테고리마다 고를 수 있는 선택지가 있다', () => { + const counts = Object.fromEntries( + THREE_D_OPTION_CATEGORIES.map((category) => [ + category, + THREE_D_OPTION_CHOICES.filter( + (c) => c.category === category && c.selectable, + ).length, + ]), + ); + expect(counts).toEqual({ SIZE: 3, FLAVOR: 3, SHAPE: 8, DESIGN: 5 }); + }); + + it('색은 #RRGGBB 대문자다', () => { + for (const hex of [ + ...THREE_D_SHEET_COLORS.map((c) => c.hex), + ...THREE_D_TEXT_COLOR_PRESETS, + THREE_D_DEFAULT_TEXT_COLOR, + ]) { + expect(hex).toMatch(/^#[0-9A-F]{6}$/); + } + }); + + it('꾸미기 분류는 목록에 있는 분류다', () => { + const categories = new Set(THREE_D_DECO_CATEGORIES.map((c) => c.key)); + for (const deco of THREE_D_DECOS) { + expect(categories.has(deco.category)).toBe(true); + } + }); + + it.each([ + ['shape.heart', 'SHAPE'], + ['design.heart', 'DESIGN'], + ['heart', undefined], + [null, undefined], + ] as const)('findThreeDChoice(%s) → %s', (key, category) => { + expect(findThreeDChoice(key)?.category).toBe(category); + }); +}); diff --git a/src/features/product/constants/custom-3d-catalog.constants.ts b/src/features/product/constants/custom-3d-catalog.constants.ts new file mode 100644 index 00000000..12cf00d5 --- /dev/null +++ b/src/features/product/constants/custom-3d-catalog.constants.ts @@ -0,0 +1,192 @@ +// 3D 케이크 카탈로그 정본. 판매자 앱 렌더러와 서버 디자인 검증이 같은 값을 쓴다. +// id(key)는 지우지 않고 selectable: false로 퇴역시키며, 값(hex·이미지·배율)은 바꾸지 않는다 — 과거 주문이 같은 모습으로 그려진다. +// 값을 바꿔야 하면 새 key를 더하고 옛 key를 퇴역시킨다. 에셋 경로는 assets/custom-3d-catalog/v1 기준이다. + +/** 바꾸면 클라이언트 캐시를 버리게 한다. 항목을 더하거나 퇴역시킬 때 올린다. */ +export const CUSTOM_3D_CATALOG_REVISION = 1; +/** 주문에 저장하는 디자인 JSON 버전. 해석이 바뀔 때만 올린다. */ +export const THREE_D_DESIGN_SCHEMA_VERSION = 1; +/** 에셋 S3 key 접두. 로컬 원본은 assets/ 아래 같은 경로에 있다. */ +export const CUSTOM_3D_ASSET_PREFIX = 'custom-3d-catalog/v1'; + +export const THREE_D_OPTION_CATEGORIES = [ + 'SIZE', + 'FLAVOR', + 'SHAPE', + 'DESIGN', +] as const; +export type ThreeDOptionCategory = (typeof THREE_D_OPTION_CATEGORIES)[number]; + +export const THREE_D_CATEGORY_LABELS: Record = { + SIZE: '크기', + FLAVOR: '맛', + SHAPE: '모양', + DESIGN: '디자인', +}; + +export interface ThreeDOptionChoice { + /** 옵션 항목 three_d_key. 카테고리가 달라도 value가 겹칠 수 있어(heart) 카테고리를 앞에 붙인다. */ + key: string; + category: ThreeDOptionCategory; + /** 디자인 JSON basic에 들어가는 값 */ + value: string; + label: string; + defaultPriceDelta: number; + imagePath: string | null; + /** 위에서 본 케이크 판·옆모습 배율. SIZE만 */ + renderScale: number | null; + selectable: boolean; +} + +const choice = ( + category: ThreeDOptionCategory, + value: string, + label: string, + defaultPriceDelta: number, + extra: { imagePath?: string; renderScale?: number } = {}, +): ThreeDOptionChoice => ({ + key: `${category.toLowerCase()}.${value}`, + category, + value, + label, + defaultPriceDelta, + imagePath: extra.imagePath ?? null, + renderScale: extra.renderScale ?? null, + selectable: true, +}); + +const design = (value: string, label: string, price: number) => + choice('DESIGN', value, label, price, { imagePath: `design/${value}.png` }); + +export const THREE_D_OPTION_CHOICES: readonly ThreeDOptionChoice[] = [ + choice('SHAPE', 'heart', '하트', 1000), + choice('SHAPE', 'circle', '원', 1000), + choice('SHAPE', 'square', '네모', 1000), + choice('SHAPE', 'star', '별', 1000), + choice('SHAPE', 'triangle', '삼각', 1000), + choice('SHAPE', 'bear', '곰', 1000), + choice('SHAPE', 'clover', '클로버', 1000), + choice('SHAPE', 'flower', '꽃', 1000), + choice('SIZE', 'lunchbox', '도시락 (1~2인)', 0, { renderScale: 0.7 }), + choice('SIZE', 'mini', '미니 (1~2인)', 0, { renderScale: 0.82 }), + choice('SIZE', 'no1', '1호 (2~3인)', 5000, { renderScale: 1 }), + design('wave', '물결', 0), + design('drip', '흘림', 1000), + design('phrase', '문구', 2000), + design('heart', '하트', 1000), + design('sparkle', '반짝', 1000), + choice('FLAVOR', 'cream', '생크림', 0), + choice('FLAVOR', 'vanilla', '바닐라', 0), + choice('FLAVOR', 'choco', '초코', 0), +]; + +export interface ThreeDSheetColor { + key: string; + label: string; + hex: string; + selectable: boolean; +} + +export const THREE_D_SHEET_COLORS: readonly ThreeDSheetColor[] = [ + { key: 'white', label: '화이트', hex: '#FFFFFF', selectable: true }, + { key: 'pink', label: '핑크', hex: '#FFC2CF', selectable: true }, + { key: 'yellow', label: '옐로우', hex: '#FFE08A', selectable: true }, + { key: 'green', label: '그린', hex: '#B9ECB7', selectable: true }, + { key: 'blue', label: '블루', hex: '#B5D2FF', selectable: true }, + { key: 'purple', label: '퍼플', hex: '#DCC4FF', selectable: true }, +]; + +/** 편집기 팔레트 순서. 그 밖의 #RRGGBB도 허용한다. */ +export const THREE_D_TEXT_COLOR_PRESETS: readonly string[] = [ + '#D9D9D9', + '#EE3049', + '#FF6A00', + '#00A02A', + '#0050D0', + '#3D2A12', + '#000000', + '#FF6B9D', + '#FFEE00', + '#55DD3A', + '#00AEDB', + '#A38468', + '#FFFFFF', + '#FBC9CC', + '#FFFD8A', + '#C6FF3D', + '#3EE8C0', +]; +export const THREE_D_DEFAULT_TEXT_COLOR = '#1D1D1D'; + +export interface ThreeDEffect { + key: string; + label: string; + selectable: boolean; +} + +export const THREE_D_EFFECTS: readonly ThreeDEffect[] = [ + { key: 'none', label: '기본', selectable: true }, + { key: 'soft', label: '소프트', selectable: true }, + { key: 'drawing', label: '드로잉', selectable: true }, + { key: 'pencil', label: '연필', selectable: true }, +]; + +export interface ThreeDDecoCategory { + key: string; + label: string; +} + +export const THREE_D_DECO_CATEGORIES: readonly ThreeDDecoCategory[] = [ + { key: 'number', label: '숫자' }, +]; + +export interface ThreeDDeco { + key: string; + category: string; + label: string; + imagePath: string; + selectable: boolean; +} + +export const THREE_D_DECOS: readonly ThreeDDeco[] = Array.from( + { length: 8 }, + (_, n) => ({ + key: `number-${n}`, + category: 'number', + label: `${n}`, + imagePath: `deco/number-${n}.png`, + selectable: true, + }), +); + +/** 서버가 강제하는 한도. 크기 단위는 케이크 판 너비 대비 cqw. */ +export const THREE_D_LIMITS = { + maxTextsPerFace: 10, + maxDecosPerFace: 10, + maxTextLength: 30, + textSizeMin: 4, + textSizeMax: 30, + decoSizeMin: 8, + decoSizeMax: 50, + effectIntensityMin: 0, + effectIntensityMax: 100, + effectIntensityDefault: 50, +} as const; + +/** 카탈로그가 가리키는 에셋 상대 경로 전부. 에셋 대조 spec과 업로드 스크립트가 쓴다. */ +export function catalogAssetPaths(): string[] { + return [ + ...THREE_D_OPTION_CHOICES.flatMap((c) => + c.imagePath ? [c.imagePath] : [], + ), + ...THREE_D_DECOS.map((d) => d.imagePath), + ]; +} + +const CHOICE_BY_KEY = new Map(THREE_D_OPTION_CHOICES.map((c) => [c.key, c])); + +export function findThreeDChoice( + key: string | null, +): ThreeDOptionChoice | undefined { + return key === null ? undefined : CHOICE_BY_KEY.get(key); +} diff --git a/src/features/product/product-custom-catalog.graphql b/src/features/product/product-custom-catalog.graphql new file mode 100644 index 00000000..3e5b8fae --- /dev/null +++ b/src/features/product/product-custom-catalog.graphql @@ -0,0 +1,217 @@ +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! +} + +""" +옵션 항목에 이을 수 있는 3D 선택지. +""" +type CustomThreeDOptionChoice { + """ + 옵션 항목 threeDKey로 저장하는 키(예: shape.heart). + """ + key: String! + """ + 선택지 카테고리. + """ + category: ThreeDOptionCategoryType! + """ + 디자인 JSON basic에 들어가는 값(예: heart). + """ + value: String! + """ + 표시 이름. 기본 세트로 만든 옵션 항목의 이름이 된다. + """ + label: String! + """ + 기본 추가 금액(원). 기본 세트로 만든 옵션 항목의 priceDelta가 되고, 매장이 바꿀 수 있다. + """ + defaultPriceDelta: Int! + """ + 선택지 이미지 URL(디자인만). 없으면 null. + """ + imageUrl: String + """ + 위에서 본 케이크 판·옆모습 배율(크기만). 없으면 null. + """ + renderScale: Float + """ + 새로 고를 수 있는지. false면 퇴역한 값으로, 과거 주문을 그릴 때만 쓴다. + """ + selectable: Boolean! +} + +""" +3D 시트 색. +""" +type CustomThreeDSheetColor { + """ + 디자인 JSON basic.sheetColor 값. + """ + key: String! + """ + 표시 이름. + """ + label: String! + """ + 렌더 색(#RRGGBB 대문자). + """ + hex: String! + """ + 새로 고를 수 있는지. false면 과거 주문을 그릴 때만 쓴다. + """ + selectable: Boolean! +} + +""" +글자·꾸미기 효과. +""" +type CustomThreeDEffect { + """ + 디자인 JSON effect.type 값. + """ + key: String! + """ + 표시 이름. + """ + label: String! + """ + 새로 고를 수 있는지. false면 과거 주문을 그릴 때만 쓴다. + """ + selectable: Boolean! +} + +""" +꾸미기 분류. +""" +type CustomThreeDDecoCategory { + """ + 분류 키. CustomThreeDDeco.category가 가리킨다. + """ + key: String! + """ + 표시 이름(편집기 탭). + """ + label: String! +} + +""" +꾸미기 이미지 1개. +""" +type CustomThreeDDeco { + """ + 디자인 JSON 꾸미기 항목의 decoId 값. + """ + key: String! + """ + 분류 키(CustomThreeDDecoCategory.key). + """ + category: String! + """ + 표시 이름. + """ + label: String! + """ + 이미지 URL(PNG, 투명 배경). + """ + imageUrl: String! + """ + 새로 고를 수 있는지. false면 과거 주문을 그릴 때만 쓴다. + """ + selectable: Boolean! +} diff --git a/src/features/product/product.module.ts b/src/features/product/product.module.ts index c037b526..a32f45d2 100644 --- a/src/features/product/product.module.ts +++ b/src/features/product/product.module.ts @@ -12,6 +12,7 @@ import { AdminTaxonomyMutationResolver } from '@/features/product/resolvers/prod import { AdminTaxonomyQueryResolver } from '@/features/product/resolvers/product-admin-taxonomy-query.resolver'; import { AdminUploadMutationResolver } from '@/features/product/resolvers/product-admin-upload-mutation.resolver'; import { ProductCategoryQueryResolver } from '@/features/product/resolvers/product-category-query.resolver'; +import { ProductCustomCatalogQueryResolver } from '@/features/product/resolvers/product-custom-catalog-query.resolver'; import { ProductDetailQueryResolver } from '@/features/product/resolvers/product-detail-query.resolver'; import { ProductHomeQueryResolver } from '@/features/product/resolvers/product-home-query.resolver'; import { ProductReviewQueryResolver } from '@/features/product/resolvers/product-review-query.resolver'; @@ -27,6 +28,7 @@ import { AdminProductService } from '@/features/product/services/product-admin.s import { ProductBestSellerService } from '@/features/product/services/product-best-seller.service'; import { ProductCardService } from '@/features/product/services/product-card.service'; import { ProductCategoryService } from '@/features/product/services/product-category.service'; +import { ProductCustomCatalogService } from '@/features/product/services/product-custom-catalog.service'; import { ProductDetailService } from '@/features/product/services/product-detail.service'; import { ProductHomeService } from '@/features/product/services/product-home.service'; import { ProductReviewService } from '@/features/product/services/product-review.service'; @@ -60,6 +62,8 @@ import { StoreModule } from '@/features/store'; ProductBestSellerService, ProductSearchService, ProductSearchQueryResolver, + ProductCustomCatalogService, + ProductCustomCatalogQueryResolver, // 판매자 상품 관리(상품·이미지·분류·옵션·커스텀 템플릿·업로드 URL) — 상품 도메인이 소유한다 SellerProductQueryService, SellerProductLifecycleService, diff --git a/src/features/product/product.types.graphql b/src/features/product/product.types.graphql index b15b116f..46042cce 100644 --- a/src/features/product/product.types.graphql +++ b/src/features/product/product.types.graphql @@ -94,3 +94,17 @@ enum CustomTextAlignType { """오른쪽 정렬.""" RIGHT } + +""" +3D 옵션 카테고리. 옵션 항목의 threeDKey가 가리키는 카탈로그 선택지의 종류다. +""" +enum ThreeDOptionCategoryType { + """케이크 크기. 3D 상품은 필수 단일 선택 그룹이 있어야 한다.""" + SIZE + """시트·크림 맛. 고르지 않아도 되는 그룹으로 둘 수 있다.""" + FLAVOR + """시트 모양. 3D 상품은 필수 단일 선택 그룹이 있어야 한다.""" + SHAPE + """시트 디자인. 고르지 않으면 장식 없는 시트로 그린다.""" + DESIGN +} diff --git a/src/features/product/resolvers/product-custom-catalog-query.resolver.spec.ts b/src/features/product/resolvers/product-custom-catalog-query.resolver.spec.ts new file mode 100644 index 00000000..0eaa0836 --- /dev/null +++ b/src/features/product/resolvers/product-custom-catalog-query.resolver.spec.ts @@ -0,0 +1,54 @@ +import { Test } from '@nestjs/testing'; + +import { ProductCustomCatalogQueryResolver } from '@/features/product/resolvers/product-custom-catalog-query.resolver'; +import { ProductCustomCatalogService } from '@/features/product/services/product-custom-catalog.service'; +import { s3TestProviders } from '@/test/storage/s3-test.helper'; + +const ASSET_BASE = + 'https://caquick-media-test.s3.ap-northeast-2.amazonaws.com/custom-3d-catalog/v1'; + +describe('ProductCustomCatalogQueryResolver', () => { + let resolver: ProductCustomCatalogQueryResolver; + + beforeAll(async () => { + const module = await Test.createTestingModule({ + providers: [ + ...s3TestProviders(), + ProductCustomCatalogService, + ProductCustomCatalogQueryResolver, + ], + }).compile(); + resolver = module.get(ProductCustomCatalogQueryResolver); + }); + + it('카탈로그 상수를 내보내고 에셋 경로를 이 버킷의 공개 URL로 바꾼다', () => { + const catalog = resolver.customThreeDCatalog(); + + expect(catalog).toMatchObject({ + revision: 1, + designSchemaVersion: 1, + defaultTextColor: '#1D1D1D', + limits: { maxTextsPerFace: 10, maxTextLength: 30 }, + }); + expect( + catalog.optionChoices + .filter((c) => c.key === 'design.wave' || c.key === 'shape.heart') + .map((c) => [c.key, c.imageUrl]), + ).toEqual([ + ['shape.heart', null], + ['design.wave', `${ASSET_BASE}/design/wave.png`], + ]); + expect(catalog.optionChoices[0]).not.toHaveProperty('imagePath'); + expect(catalog.decos[0]).toEqual({ + key: 'number-0', + category: 'number', + label: '0', + imageUrl: `${ASSET_BASE}/deco/number-0.png`, + selectable: true, + }); + }); + + it('요청마다 같은 결과를 다시 만들지 않는다', () => { + expect(resolver.customThreeDCatalog()).toBe(resolver.customThreeDCatalog()); + }); +}); diff --git a/src/features/product/resolvers/product-custom-catalog-query.resolver.ts b/src/features/product/resolvers/product-custom-catalog-query.resolver.ts new file mode 100644 index 00000000..a2b076e9 --- /dev/null +++ b/src/features/product/resolvers/product-custom-catalog-query.resolver.ts @@ -0,0 +1,14 @@ +import { Query, Resolver } from '@nestjs/graphql'; + +import { ProductCustomCatalogService } from '@/features/product/services/product-custom-catalog.service'; +import type { CustomThreeDCatalogOutput } from '@/features/product/types/product-custom-catalog-output.type'; + +@Resolver('Query') +export class ProductCustomCatalogQueryResolver { + constructor(private readonly service: ProductCustomCatalogService) {} + + @Query('customThreeDCatalog') + customThreeDCatalog(): CustomThreeDCatalogOutput { + return this.service.customThreeDCatalog(); + } +} diff --git a/src/features/product/services/product-custom-catalog.service.ts b/src/features/product/services/product-custom-catalog.service.ts new file mode 100644 index 00000000..fac4eb01 --- /dev/null +++ b/src/features/product/services/product-custom-catalog.service.ts @@ -0,0 +1,53 @@ +import { Injectable } from '@nestjs/common'; + +import { + CUSTOM_3D_ASSET_PREFIX, + CUSTOM_3D_CATALOG_REVISION, + THREE_D_DECO_CATEGORIES, + THREE_D_DECOS, + THREE_D_DEFAULT_TEXT_COLOR, + THREE_D_DESIGN_SCHEMA_VERSION, + THREE_D_EFFECTS, + THREE_D_LIMITS, + THREE_D_OPTION_CHOICES, + THREE_D_SHEET_COLORS, + THREE_D_TEXT_COLOR_PRESETS, +} from '@/features/product/constants/custom-3d-catalog.constants'; +import type { CustomThreeDCatalogOutput } from '@/features/product/types/product-custom-catalog-output.type'; +import { S3Service } from '@/global/storage/s3.service'; + +/** 카탈로그는 코드 상수라 요청마다 같은 값이다. 에셋 URL은 이 환경 버킷 기준으로 한 번만 만든다. */ +@Injectable() +export class ProductCustomCatalogService { + private catalog: CustomThreeDCatalogOutput | null = null; + + constructor(private readonly s3: S3Service) {} + + customThreeDCatalog(): CustomThreeDCatalogOutput { + this.catalog ??= this.build(); + return this.catalog; + } + + private build(): CustomThreeDCatalogOutput { + const assetUrl = (path: string) => + this.s3.publicUrlFor(`${CUSTOM_3D_ASSET_PREFIX}/${path}`); + return { + revision: CUSTOM_3D_CATALOG_REVISION, + designSchemaVersion: THREE_D_DESIGN_SCHEMA_VERSION, + limits: THREE_D_LIMITS, + optionChoices: THREE_D_OPTION_CHOICES.map(({ imagePath, ...choice }) => ({ + ...choice, + imageUrl: imagePath === null ? null : assetUrl(imagePath), + })), + sheetColors: THREE_D_SHEET_COLORS, + textColorPresets: THREE_D_TEXT_COLOR_PRESETS, + defaultTextColor: THREE_D_DEFAULT_TEXT_COLOR, + effects: THREE_D_EFFECTS, + decoCategories: THREE_D_DECO_CATEGORIES, + decos: THREE_D_DECOS.map(({ imagePath, ...deco }) => ({ + ...deco, + imageUrl: assetUrl(imagePath), + })), + }; + } +} diff --git a/src/features/product/types/product-custom-catalog-output.type.ts b/src/features/product/types/product-custom-catalog-output.type.ts new file mode 100644 index 00000000..02ca5606 --- /dev/null +++ b/src/features/product/types/product-custom-catalog-output.type.ts @@ -0,0 +1,39 @@ +import type { + THREE_D_LIMITS, + ThreeDDecoCategory, + ThreeDEffect, + ThreeDOptionCategory, + ThreeDSheetColor, +} from '@/features/product/constants/custom-3d-catalog.constants'; + +export interface CustomThreeDOptionChoiceOutput { + key: string; + category: ThreeDOptionCategory; + value: string; + label: string; + defaultPriceDelta: number; + imageUrl: string | null; + renderScale: number | null; + selectable: boolean; +} + +export interface CustomThreeDDecoOutput { + key: string; + category: string; + label: string; + imageUrl: string; + selectable: boolean; +} + +export interface CustomThreeDCatalogOutput { + revision: number; + designSchemaVersion: number; + limits: typeof THREE_D_LIMITS; + optionChoices: CustomThreeDOptionChoiceOutput[]; + sheetColors: readonly ThreeDSheetColor[]; + textColorPresets: readonly string[]; + defaultTextColor: string; + effects: readonly ThreeDEffect[]; + decoCategories: readonly ThreeDDecoCategory[]; + decos: CustomThreeDDecoOutput[]; +} diff --git a/src/global/storage/s3.service.spec.ts b/src/global/storage/s3.service.spec.ts index fac9f371..7d714038 100644 --- a/src/global/storage/s3.service.spec.ts +++ b/src/global/storage/s3.service.spec.ts @@ -256,6 +256,16 @@ describe('S3Service', () => { }); }); + describe('publicUrlFor', () => { + it('이 버킷·리전의 공개 URL을 만든다', () => { + expect( + service.publicUrlFor('custom-3d-catalog/v1/deco/number-0.png'), + ).toBe( + 'https://caquick-media-test.s3.ap-northeast-2.amazonaws.com/custom-3d-catalog/v1/deco/number-0.png', + ); + }); + }); + describe('생성자의 credentials 분기', () => { it('accessKeyId/secretAccessKey가 없으면 S3Client에 credentials 없이 초기화한다', async () => { const { S3Client: MockS3Client } = diff --git a/src/global/storage/s3.service.ts b/src/global/storage/s3.service.ts index 1ede2486..6ebc9aa3 100644 --- a/src/global/storage/s3.service.ts +++ b/src/global/storage/s3.service.ts @@ -98,7 +98,7 @@ export class S3Service { return { uploadUrl, - publicUrl: this.buildPublicUrl(key), + publicUrl: this.publicUrlFor(key), key, expiresInSeconds: this.presignExpiresSeconds, }; @@ -259,7 +259,8 @@ export class S3Service { return `${prefix}/${accountId.toString()}/${date}/${uuid}${ext}`; } - private buildPublicUrl(key: string): string { + /** 이 버킷 객체의 공개 URL. 버킷 정책이 전체 공개 읽기라 업로드 외 고정 에셋(3D 카탈로그)도 이 주소로 연다. */ + publicUrlFor(key: string): string { return `https://${this.bucket}.s3.${this.region}.amazonaws.com/${key}`; } } From b40a07254fe386446bf8a5459136517da3eaf072 Mon Sep 17 00:00:00 2001 From: chanwoo7 Date: Thu, 19 Nov 2026 02:34:19 +0900 Subject: [PATCH 24/54] =?UTF-8?q?feat:=20=EC=98=B5=EC=85=98=203D=20?= =?UTF-8?q?=EC=97=B0=EA=B2=B0=EA=B3=BC=203D=20=EC=83=81=ED=92=88=20?= =?UTF-8?q?=EC=A4=80=EB=B9=84=20=EC=83=81=ED=83=9C=C2=B7=EA=B8=B0=EB=B3=B8?= =?UTF-8?q?=20=EC=84=B8=ED=8A=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 3D 상품은 크기·맛·모양·디자인을 상품 옵션으로 고르고, 옵션 항목마다 3D 카탈로그 선택지 키를 이어 렌더 값을 정한다(가격·사용 여부는 매장이 정한다). 3D 방식은 모양·크기 옵션이 이어져 있어야 열리고, 맛·디자인은 고르지 않아도 되는 그룹으로 둘 수 있다(디자인이 없으면 장식 없는 시트). 판매자 앱의 '3D 기본 세트 불러오기'가 빈 카테고리를 한 번에 채운다. 변경점 - 스키마: product_option_item.three_d_key VARCHAR(40) NULL(기존 항목은 연결 없음이라 백필 없음) - 입력: SellerCreateOptionItemInput·SellerUpdateOptionItemInput.threeDKey(공백 제거, 빈 문자열은 연결 없음, 수정에서 null은 연결 끊기·생략은 유지, 40자 초과 TEXT_TOO_LONG). 카탈로그에 없거나 퇴역한 키도 저장하고 준비 이슈로 막는다 - 출력: 판매자 SellerOptionItem.threeDKey·SellerOptionGroup.threeDCategory, 구매자 ProductDetailOptionItem.threeDKey·ProductDetailOptionGroup.threeDCategory, 관리자 AdminProductOptionItem.threeDKey. 그룹 카테고리는 활성 선택지의 카탈로그 키가 한 카테고리로 모일 때만 값, 아니면 null. 옵션 서비스의 중복 매퍼를 공용 매퍼로 합쳤다 - 준비 상태 THREE_D(활성 그룹·활성 선택지 기준, 키가 없는 그룹은 3D와 무관): THREE_D_GROUP_MISSING(모양·크기 카테고리별), THREE_D_GROUP_DUPLICATED(같은 카테고리 두 번째 그룹부터), THREE_D_GROUP_MIXED(카테고리 섞임·미지정 선택지), THREE_D_GROUP_NOT_SINGLE_SELECT(모양·크기는 필수·1개, 맛·디자인은 최대 1개), THREE_D_KEY_DUPLICATED, THREE_D_KEY_UNAVAILABLE(카탈로그 밖·퇴역). 구매자 상세 행도 같은 입력 모양을 갖춰 주문 생성이 같은 판정을 쓸 수 있다 - sellerApplyThreeDOptionPreset(productId): 활성 3D 그룹이 없는 카테고리마다 크기·맛·모양·디자인 순으로 기존 그룹 뒤에 단일 선택 그룹을 만들고 선택 가능한 선택지 전부를 기본 가격으로 넣는다. 크기·맛·모양은 필수(min=max=1), 디자인은 선택(min 0·max 1). 상품 행을 잠근 뒤 같은 tx에서 읽고 만들어 동시 호출도 한 벌만 생기고, 만든 그룹이 없으면 감사도 없다(멱등). 응답은 SellerProduct - 게이트: 판매자 접두 루트 필드 58 → 59 테스트 - THREE_D 이슈 표 20 + 메시지 1 + 퇴역 키 1, threeDCategoryOf 6 - 기본 세트 5: 다른 매장 404, 빈 카테고리 생성(순서·필수·가격·키·감사·준비 완료 뒤 3D 전환), 다시 불러도 그대로·감사 1건, 있는 카테고리 유지·숨긴 그룹 카테고리는 다시 만듦, 동시 두 번에도 카테고리당 1개 - 옵션 키 저장·정규화·40자·수정 유지/변경/끊기, 그룹 카테고리 출력, 구매자 상세·관리자 상세 3D 키, 리졸버 배선 1 - 가드 반증: 퇴역·미지정·필수 단일 선택 판정을 끄거나 상품 행 잠금을 빼면 해당 테스트가 실패함을 확인 --- .../migration.sql | 3 + prisma/schema.prisma | 2 + .../constants/product-seller.constants.ts | 1 + .../inputs/seller-create-option-item.input.ts | 4 + .../inputs/seller-update-option-item.input.ts | 4 + src/features/product/product-admin.graphql | 4 + src/features/product/product-detail.graphql | 8 + src/features/product/product-seller.graphql | 31 ++- .../repositories/product.repository.ts | 78 ++++++ .../product-seller-mutation.resolver.ts | 12 + .../resolvers/product-seller.resolver.spec.ts | 22 ++ .../services/custom-3d-preset.helper.ts | 44 ++++ .../services/product-admin.service.spec.ts | 20 +- .../product-custom-readiness.helper.spec.ts | 237 +++++++++++++++++- .../product-custom-readiness.helper.ts | 174 +++++++++++-- .../services/product-detail-mappers.helper.ts | 3 + .../services/product-detail.service.spec.ts | 37 +++ ...uct-seller-custom-template.service.spec.ts | 167 +++++++++++- .../product-seller-custom-template.service.ts | 27 ++ .../services/product-seller-mappers.helper.ts | 64 +++-- .../product-seller-option.service.spec.ts | 89 +++++++ .../services/product-seller-option.service.ts | 88 ++----- .../types/product-detail-output.type.ts | 3 + .../types/product-seller-output.type.ts | 3 + 24 files changed, 1012 insertions(+), 113 deletions(-) create mode 100644 prisma/migrations/20261118170655_option_item_three_d_key/migration.sql create mode 100644 src/features/product/services/custom-3d-preset.helper.ts diff --git a/prisma/migrations/20261118170655_option_item_three_d_key/migration.sql b/prisma/migrations/20261118170655_option_item_three_d_key/migration.sql new file mode 100644 index 00000000..4b6dfdcc --- /dev/null +++ b/prisma/migrations/20261118170655_option_item_three_d_key/migration.sql @@ -0,0 +1,3 @@ +-- 옵션 항목을 3D 카탈로그 선택지에 잇는 키. 기존 항목은 연결 없음(NULL)이라 백필이 없다. +-- AlterTable +ALTER TABLE `product_option_item` ADD COLUMN `three_d_key` VARCHAR(40) NULL; diff --git a/prisma/schema.prisma b/prisma/schema.prisma index 75b2a879..a7afb2d5 100644 --- a/prisma/schema.prisma +++ b/prisma/schema.prisma @@ -801,6 +801,8 @@ model ProductOptionItem { price_delta Int @default(0) sort_order Int @default(0) is_active Boolean @default(true) @db.TinyInt + // 3D 카탈로그 선택지 키. 3D 상품의 모양·크기·맛·디자인 옵션을 렌더 값에 잇는다 + three_d_key String? @db.VarChar(40) created_at DateTime @default(now()) @db.DateTime(3) updated_at DateTime @updatedAt @db.DateTime(3) diff --git a/src/features/product/constants/product-seller.constants.ts b/src/features/product/constants/product-seller.constants.ts index e153c209..40fa8e5c 100644 --- a/src/features/product/constants/product-seller.constants.ts +++ b/src/features/product/constants/product-seller.constants.ts @@ -20,6 +20,7 @@ export const MAX_OPTION_GROUP_NAME_LENGTH = 120; export const MAX_OPTION_GROUP_DESCRIPTION_LENGTH = 1000; export const MAX_OPTION_ITEM_TITLE_LENGTH = 120; export const MAX_OPTION_ITEM_DESCRIPTION_LENGTH = 500; +export const MAX_THREE_D_KEY_LENGTH = 40; // ── 커스텀 템플릿 ── diff --git a/src/features/product/dto/inputs/seller-create-option-item.input.ts b/src/features/product/dto/inputs/seller-create-option-item.input.ts index 49198a01..e823f7c8 100644 --- a/src/features/product/dto/inputs/seller-create-option-item.input.ts +++ b/src/features/product/dto/inputs/seller-create-option-item.input.ts @@ -26,4 +26,8 @@ export class SellerCreateOptionItemInput { @IsOptional() @IsBoolean() isActive?: boolean; + + @IsOptional() + @IsString() + threeDKey?: string | null; } diff --git a/src/features/product/dto/inputs/seller-update-option-item.input.ts b/src/features/product/dto/inputs/seller-update-option-item.input.ts index 9aa0da2a..be2e699e 100644 --- a/src/features/product/dto/inputs/seller-update-option-item.input.ts +++ b/src/features/product/dto/inputs/seller-update-option-item.input.ts @@ -27,4 +27,8 @@ export class SellerUpdateOptionItemInput { @IsOptional() @IsBoolean() isActive?: boolean; + + @IsOptional() + @IsString() + threeDKey?: string | null; } diff --git a/src/features/product/product-admin.graphql b/src/features/product/product-admin.graphql index 45fcc238..9b523e8d 100644 --- a/src/features/product/product-admin.graphql +++ b/src/features/product/product-admin.graphql @@ -219,6 +219,10 @@ type AdminProductOptionItem { 노출 여부. false면 구매자가 고를 수 없다. """ isActive: Boolean! + """ + 이어진 3D 카탈로그 선택지 키(customThreeDCatalog.optionChoices.key). 없으면 null. + """ + threeDKey: String } """ diff --git a/src/features/product/product-detail.graphql b/src/features/product/product-detail.graphql index e81aded6..0c1cf701 100644 --- a/src/features/product/product-detail.graphql +++ b/src/features/product/product-detail.graphql @@ -94,6 +94,10 @@ type ProductDetailOptionGroup { maxSelect: Int! """섹션 노출 순서. 오름차순.""" sortOrder: Int! + """ + 3D 상품에서 이 그룹이 정하는 3D 값의 종류. 선택지가 3D 항목과 이어지지 않았거나 종류가 섞였으면 null. + """ + threeDCategory: ThreeDOptionCategoryType """이 그룹의 선택지. 활성 항목만 온다.""" items: [ProductDetailOptionItem!]! } @@ -111,4 +115,8 @@ type ProductDetailOptionItem { priceDelta: Int! """그룹 안에서의 노출 순서. 오름차순.""" sortOrder: Int! + """ + 이어진 3D 카탈로그 선택지 키(customThreeDCatalog.optionChoices.key). 3D 편집기는 이 키의 value로 모양·크기 등을 그린다. 없으면 null. + """ + threeDKey: String } diff --git a/src/features/product/product-seller.graphql b/src/features/product/product-seller.graphql index 71c4cf25..0ef3d236 100644 --- a/src/features/product/product-seller.graphql +++ b/src/features/product/product-seller.graphql @@ -125,6 +125,13 @@ extend type Mutation { customMode: CustomModeType! ): SellerProduct! """ + 3D 기본 세트를 불러온다. 3D 항목 그룹이 없는 카테고리(크기·맛·모양·디자인)마다 단일 선택 그룹을 만들고 + 선택 가능한 카탈로그 선택지 전부를 기본 가격으로 넣는다. 크기·맛·모양은 필수, 디자인은 고르지 않아도 되는 그룹이다. + 이미 그룹이 있는 카테고리는 건드리지 않아 여러 번 불러도 결과가 같다(새로 만든 그룹이 없으면 감사 기록도 없다). + 판매자 로그인 필수. SELLER 계정이 아니면 FORBIDDEN, 매장을 보유하지 않거나 내 상품이 아니면 NOT_FOUND. + """ + sellerApplyThreeDOptionPreset(productId: ID!): SellerProduct! + """ 상품 커스텀 템플릿(슬롯형 바탕)을 등록 또는 수정한다. 수정하면 revision이 1 오른다. 바탕 이미지가 바뀔 때만 서버가 이미지를 읽어 정사각(가로·세로 차이 1px 이하)인지 확인한다: 아니면 CUSTOM_BASE_IMAGE_NOT_SQUARE, 이미지로 읽을 수 없으면 CUSTOM_BASE_IMAGE_UNREADABLE, 저장소를 읽지 못하면 S3_READ_FAILED(503). @@ -242,6 +249,10 @@ type SellerOptionItem { 노출 여부. false면 구매자가 고를 수 없다. """ isActive: Boolean! + """ + 이어진 3D 카탈로그 선택지 키(customThreeDCatalog.optionChoices.key). 없으면 null. + """ + threeDKey: String } """ @@ -280,6 +291,10 @@ type SellerOptionGroup { """ isActive: Boolean! """ + 활성 선택지의 threeDKey로 정해지는 3D 카테고리. 이어진 키가 없거나 종류가 섞였으면 null. + """ + threeDCategory: ThreeDOptionCategoryType + """ 이 그룹의 선택지. sortOrder 오름차순. """ optionItems: [SellerOptionItem!]! @@ -460,7 +475,12 @@ type SellerCustomReadiness { """ type SellerCustomReadinessIssue { """ - 이슈 코드(SLOT_TEMPLATE_MISSING, SLOT_NOTHING_TO_EDIT, THREE_D_GROUP_MISSING 등). 값이 늘 수 있어 문자열이다. + 이슈 코드. 값이 늘 수 있어 문자열이다. + 슬롯형: 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! """ @@ -797,6 +817,11 @@ input SellerCreateOptionItemInput { 노출 여부. 기본 true. """ isActive: Boolean = true + """ + 3D 카탈로그 선택지 키(customThreeDCatalog.optionChoices.key, 40자 이하). 생략하거나 빈 문자열이면 연결하지 않는다. + 카탈로그에 없거나 퇴역한 키도 저장되지만 3D 준비 이슈(THREE_D_KEY_UNAVAILABLE)가 되어 3D 주문을 받을 수 없다. + """ + threeDKey: String } """ @@ -828,6 +853,10 @@ input SellerUpdateOptionItemInput { 노출 여부. """ isActive: Boolean + """ + 3D 카탈로그 선택지 키(40자 이하). null이나 빈 문자열이면 연결을 끊고, 생략하면 그대로 둔다. + """ + threeDKey: String } """ diff --git a/src/features/product/repositories/product.repository.ts b/src/features/product/repositories/product.repository.ts index a39654d6..26e77d9f 100644 --- a/src/features/product/repositories/product.repository.ts +++ b/src/features/product/repositories/product.repository.ts @@ -155,10 +155,12 @@ export interface ProductDetailRow { region: { name: string } | null; }; images: { image_url: string }[]; + /** 활성 그룹·항목만 온다. is_active는 준비 상태 판정 입력과 모양을 맞추려고 함께 읽는다. */ option_groups: { id: bigint; name: string; description: string | null; + is_active: boolean; is_required: boolean; min_select: number; max_select: number; @@ -170,10 +172,20 @@ export interface ProductDetailRow { image_url: string | null; price_delta: number; sort_order: number; + is_active: boolean; + three_d_key: string | null; }[]; }[]; } +export interface NewOptionGroup { + name: string; + is_required: boolean; + min_select: number; + max_select: number; + items: { title: string; price_delta: number; three_d_key: string }[]; +} + @Injectable() export class ProductRepository { constructor( @@ -943,6 +955,69 @@ export class ProductRepository { }, audit); } + /** + * 상품 행을 잠근 뒤 현재 그룹으로 계획해 만든다 — 동시 호출이 같은 계획을 두 번 실행하지 않는다. + * 새 그룹은 기존 그룹 뒤에 붙고, 만든 그룹이 없으면 감사도 남기지 않는다. + */ + async createOptionGroupsLocked( + args: { + productId: bigint; + plan: ( + groups: { + is_active: boolean; + option_items: { is_active: boolean; three_d_key: string | null }[]; + }[], + ) => NewOptionGroup[]; + }, + audit: (optionGroupIds: bigint[]) => AuditEntry, + ): Promise { + return this.prisma.$transaction(async (tx) => { + await this.lockProductRow(tx, args.productId); + const groups = await tx.productOptionGroup.findMany({ + where: { product_id: args.productId, ...activeWhere }, + orderBy: [{ sort_order: 'asc' }, { id: 'asc' }], + select: { + is_active: true, + sort_order: true, + option_items: { + where: activeWhere, + select: { is_active: true, three_d_key: true }, + }, + }, + }); + const planned = args.plan(groups); + if (planned.length === 0) return []; + + const nextSortOrder = + Math.max(-1, ...groups.map((g) => g.sort_order)) + 1; + const ids: bigint[] = []; + for (const [index, group] of planned.entries()) { + const created = await tx.productOptionGroup.create({ + data: { + product_id: args.productId, + name: group.name, + is_required: group.is_required, + min_select: group.min_select, + max_select: group.max_select, + sort_order: nextSortOrder + index, + option_items: { + create: group.items.map((item, sortOrder) => ({ + title: item.title, + price_delta: item.price_delta, + three_d_key: item.three_d_key, + sort_order: sortOrder, + })), + }, + }, + select: { id: true }, + }); + ids.push(created.id); + } + await this.auditLogs.recordAudit(tx, audit(ids)); + return ids; + }); + } + /** 갱신이면 revision을 1 올린다. freeEditEnabled를 생략하면 새 템플릿은 꺼짐, 기존 템플릿은 그대로다. */ async upsertProductCustomTemplate( args: { @@ -1343,6 +1418,7 @@ export class ProductRepository { id: true, name: true, description: true, + is_active: true, is_required: true, min_select: true, max_select: true, @@ -1357,6 +1433,8 @@ export class ProductRepository { image_url: true, price_delta: true, sort_order: true, + is_active: true, + three_d_key: true, }, }, }, diff --git a/src/features/product/resolvers/product-seller-mutation.resolver.ts b/src/features/product/resolvers/product-seller-mutation.resolver.ts index 7e28dc5b..9e576de5 100644 --- a/src/features/product/resolvers/product-seller-mutation.resolver.ts +++ b/src/features/product/resolvers/product-seller-mutation.resolver.ts @@ -254,6 +254,18 @@ export class SellerProductMutationResolver { ); } + @Mutation('sellerApplyThreeDOptionPreset') + sellerApplyThreeDOptionPreset( + @CurrentUser() user: JwtUser, + @Args('productId') productId: string, + ): Promise { + const accountId = parseAccountId(user); + return this.templateService.sellerApplyThreeDOptionPreset( + accountId, + parseId(productId), + ); + } + @Mutation('sellerUpsertProductCustomTextToken') sellerUpsertProductCustomTextToken( @CurrentUser() user: JwtUser, diff --git a/src/features/product/resolvers/product-seller.resolver.spec.ts b/src/features/product/resolvers/product-seller.resolver.spec.ts index e6927c57..e567a443 100644 --- a/src/features/product/resolvers/product-seller.resolver.spec.ts +++ b/src/features/product/resolvers/product-seller.resolver.spec.ts @@ -436,5 +436,27 @@ describe('Seller Product Resolvers (real DB)', () => { ), ).toBe(true); }); + + it('3D 기본 세트 → 3D 방식 전환 배선', async () => { + const { auth, productId } = await setupProductForMutationWiring(); + + const preset = await mutationResolver.sellerApplyThreeDOptionPreset( + auth, + productId, + ); + expect(preset.optionGroups.map((g) => g.threeDCategory)).toEqual([ + 'SIZE', + 'FLAVOR', + 'SHAPE', + 'DESIGN', + ]); + + const threeD = await mutationResolver.sellerSetProductCustomMode( + auth, + productId, + 'THREE_D', + ); + expect(threeD.customMode).toBe('THREE_D'); + }); }); }); diff --git a/src/features/product/services/custom-3d-preset.helper.ts b/src/features/product/services/custom-3d-preset.helper.ts new file mode 100644 index 00000000..64f8ed66 --- /dev/null +++ b/src/features/product/services/custom-3d-preset.helper.ts @@ -0,0 +1,44 @@ +import { + THREE_D_CATEGORY_LABELS, + THREE_D_OPTION_CATEGORIES, + THREE_D_OPTION_CHOICES, + type ThreeDOptionCategory, +} from '@/features/product/constants/custom-3d-catalog.constants'; +import type { NewOptionGroup } from '@/features/product/repositories/product.repository'; +import { threeDCategoryOf } from '@/features/product/services/product-custom-readiness.helper'; + +/** 디자인은 고르지 않아도 되는 그룹으로 만든다. 매장이 필수로 바꿀 수 있다. */ +const OPTIONAL_PRESET_CATEGORIES: readonly ThreeDOptionCategory[] = ['DESIGN']; + +/** + * 활성 그룹이 차지하지 않은 카테고리마다 단일 선택 그룹을 계획한다. 준비 상태 판정과 같은 그룹 기준이라 + * 기본 세트를 불러온 뒤에는 모양·크기 누락이 사라지고, 다시 불러도 아무것도 만들지 않는다. + */ +export function planThreeDOptionPreset( + groups: readonly { + is_active: boolean; + option_items: readonly { is_active: boolean; three_d_key: string | null }[]; + }[], +): NewOptionGroup[] { + const taken = new Set( + groups.filter((g) => g.is_active).map((g) => threeDCategoryOf(g)), + ); + return THREE_D_OPTION_CATEGORIES.filter((c) => !taken.has(c)).map( + (category) => { + const required = !OPTIONAL_PRESET_CATEGORIES.includes(category); + return { + name: THREE_D_CATEGORY_LABELS[category], + is_required: required, + min_select: required ? 1 : 0, + max_select: 1, + items: THREE_D_OPTION_CHOICES.filter( + (c) => c.category === category && c.selectable, + ).map((c) => ({ + title: c.label, + price_delta: c.defaultPriceDelta, + three_d_key: c.key, + })), + }; + }, + ); +} diff --git a/src/features/product/services/product-admin.service.spec.ts b/src/features/product/services/product-admin.service.spec.ts index 0c5e98ab..943d2993 100644 --- a/src/features/product/services/product-admin.service.spec.ts +++ b/src/features/product/services/product-admin.service.spec.ts @@ -290,7 +290,7 @@ describe('AdminProductService (real DB)', () => { expect(result.tags.map((t) => t.name)).toEqual(['달콤', '촉촉']); }); - it('옵션 그룹·선택지는 sortOrder 순으로 숨김을 담고 삭제는 빼며 음수 가격 증감을 그대로 준다', async () => { + it('옵션 그룹·선택지는 sortOrder 순으로 숨김을 담고 삭제는 빼며 음수 가격 증감·3D 키를 그대로 준다', async () => { const product = await createProduct(prisma); const later = await prisma.productOptionGroup.create({ data: { product_id: product.id, name: '토핑', sort_order: 2 }, @@ -316,7 +316,12 @@ describe('AdminProductService (real DB)', () => { }); await prisma.productOptionItem.createMany({ data: [ - { option_group_id: later.id, title: '딸기', sort_order: 2 }, + { + option_group_id: later.id, + title: '딸기', + sort_order: 2, + three_d_key: 'design.heart', + }, { option_group_id: later.id, title: '빼기', @@ -346,11 +351,16 @@ describe('AdminProductService (real DB)', () => { }); expect( result.optionGroups[1].optionItems.map( - ({ title, priceDelta, isActive }) => [title, priceDelta, isActive], + ({ title, priceDelta, isActive, threeDKey }) => [ + title, + priceDelta, + isActive, + threeDKey, + ], ), ).toEqual([ - ['빼기', -1000, false], - ['딸기', 0, true], + ['빼기', -1000, false, null], + ['딸기', 0, true, 'design.heart'], ]); }); diff --git a/src/features/product/services/product-custom-readiness.helper.spec.ts b/src/features/product/services/product-custom-readiness.helper.spec.ts index 177266d0..0cd61d3b 100644 --- a/src/features/product/services/product-custom-readiness.helper.spec.ts +++ b/src/features/product/services/product-custom-readiness.helper.spec.ts @@ -1,5 +1,8 @@ +import type * as Catalog from '@/features/product/constants/custom-3d-catalog.constants'; import { evaluateProductCustomIssues, + threeDCategoryOf, + type ProductCustomReadinessOptionGroup, type ProductCustomReadinessSource, } from '@/features/product/services/product-custom-readiness.helper'; import { CustomMode } from '@/generated/prisma/client'; @@ -14,6 +17,37 @@ const template = ( text_tokens: Array.from({ length: slots }, (_, i) => ({ id: i })), }); +const item = (key: string | null, isActive = true) => ({ + is_active: isActive, + three_d_key: key, +}); + +const group = ( + id: number, + keys: (string | null | ReturnType)[], + overrides: Partial> = {}, +): ProductCustomReadinessOptionGroup => ({ + id: BigInt(id), + is_active: true, + is_required: true, + min_select: 1, + max_select: 1, + option_items: keys.map((k) => + typeof k === 'object' && k !== null ? k : item(k), + ), + ...overrides, +}); + +const optional = { is_required: false, min_select: 0, max_select: 1 }; +const SHAPE = group(1, ['shape.heart', 'shape.circle']); +const SIZE = group(2, ['size.mini', 'size.no1']); + +const codesOf = (groups: ProductCustomReadinessOptionGroup[]) => + evaluateProductCustomIssues( + { custom_template: null, option_groups: groups }, + 'THREE_D', + ).map((i) => [i.code, i.optionGroupId]); + describe('evaluateProductCustomIssues', () => { it.each([ ['NONE', '템플릿 없음', null, []], @@ -33,16 +67,15 @@ describe('evaluateProductCustomIssues', () => { ], ['SLOT', '문구 자리 0·자유 편집 켬', template(0, true), []], ['SLOT', '문구 자리 1·자유 편집 끔', template(1, false), []], - ['THREE_D', '템플릿 없음', null, ['THREE_D_GROUP_MISSING']], [ 'THREE_D', - '문구 자리 있는 템플릿', + '문구 자리 있는 템플릿만', template(1, true), - ['THREE_D_GROUP_MISSING'], + ['THREE_D_GROUP_MISSING', 'THREE_D_GROUP_MISSING'], ], ] as const)('%s · %s → %j', (mode, _label, customTemplate, codes) => { const issues = evaluateProductCustomIssues( - { custom_template: customTemplate }, + { custom_template: customTemplate, option_groups: [] }, mode, ); expect(issues.map((i) => i.code)).toEqual(codes); @@ -55,4 +88,200 @@ describe('evaluateProductCustomIssues', () => { it('표가 모든 커스텀 방식을 덮는다', () => { expect(Object.values(CustomMode)).toEqual(['NONE', 'SLOT', 'THREE_D']); }); + + describe('THREE_D', () => { + it.each< + [string, ProductCustomReadinessOptionGroup[], [string, string | null][]] + >([ + [ + '그룹 없음', + [], + [ + ['THREE_D_GROUP_MISSING', null], + ['THREE_D_GROUP_MISSING', null], + ], + ], + ['모양·크기', [SHAPE, SIZE], []], + [ + '모양·크기 + 고르지 않아도 되는 맛·디자인', + [ + SHAPE, + SIZE, + group(3, ['flavor.cream'], optional), + group(4, ['design.wave', 'design.drip'], optional), + ], + [], + ], + [ + '필수 맛·디자인', + [SHAPE, SIZE, group(3, ['flavor.cream']), group(4, ['design.wave'])], + [], + ], + [ + '3D와 무관한 그룹은 보지 않는다', + [SHAPE, SIZE, group(3, [null, null], { max_select: 2 })], + [], + ], + ['크기 없음', [SHAPE], [['THREE_D_GROUP_MISSING', null]]], + [ + '숨긴 모양 그룹은 없는 것과 같다', + [group(1, ['shape.heart'], { is_active: false }), SIZE], + [['THREE_D_GROUP_MISSING', null]], + ], + [ + '숨긴 선택지의 키는 보지 않는다', + [group(1, [item('shape.heart', false), null]), SIZE], + [['THREE_D_GROUP_MISSING', null]], + ], + [ + '모양 그룹 둘', + [SHAPE, SIZE, group(3, ['shape.star'])], + [['THREE_D_GROUP_DUPLICATED', '3']], + ], + [ + '한 그룹에 모양·크기가 섞임', + [group(1, ['shape.heart', 'size.mini'])], + [ + ['THREE_D_GROUP_MISSING', null], + ['THREE_D_GROUP_MISSING', null], + ['THREE_D_GROUP_MIXED', '1'], + ], + ], + [ + '3D 항목 미지정 선택지가 섞임', + [group(1, ['shape.heart', null]), SIZE], + [['THREE_D_GROUP_MIXED', '1']], + ], + [ + '모양 그룹이 필수가 아님', + [group(1, ['shape.heart'], { is_required: false }), SIZE], + [['THREE_D_GROUP_NOT_SINGLE_SELECT', '1']], + ], + [ + '모양 그룹 최대 2개', + [group(1, ['shape.heart'], { max_select: 2 }), SIZE], + [['THREE_D_GROUP_NOT_SINGLE_SELECT', '1']], + ], + [ + '크기 그룹 최소 0개', + [SHAPE, group(2, ['size.mini'], { min_select: 0 })], + [['THREE_D_GROUP_NOT_SINGLE_SELECT', '2']], + ], + [ + '맛 그룹 최대 2개', + [ + SHAPE, + SIZE, + group(3, ['flavor.cream'], { ...optional, max_select: 2 }), + ], + [['THREE_D_GROUP_NOT_SINGLE_SELECT', '3']], + ], + [ + '디자인 그룹 2개 선택', + [ + SHAPE, + SIZE, + group(4, ['design.wave'], { min_select: 2, max_select: 2 }), + ], + [['THREE_D_GROUP_NOT_SINGLE_SELECT', '4']], + ], + [ + '한 그룹에 같은 키 둘', + [group(1, ['shape.heart', 'shape.heart']), SIZE], + [['THREE_D_KEY_DUPLICATED', '1']], + ], + [ + '두 그룹에 같은 키', + [SHAPE, SIZE, group(3, ['shape.heart'])], + [ + ['THREE_D_KEY_DUPLICATED', '3'], + ['THREE_D_GROUP_DUPLICATED', '3'], + ], + ], + [ + '카탈로그에 없는 키가 섞임', + [group(1, ['shape.heart', 'shape.moon']), SIZE], + [['THREE_D_KEY_UNAVAILABLE', '1']], + ], + [ + '키가 전부 카탈로그 밖', + [group(1, ['moon']), SIZE], + [ + ['THREE_D_GROUP_MISSING', null], + ['THREE_D_KEY_UNAVAILABLE', '1'], + ], + ], + ])('%s', (_label, groups, expected) => { + expect(codesOf(groups)).toEqual(expected); + }); + + it('이슈 메시지는 카테고리 이름을 담은 한국어 문장이다', () => { + const issues = evaluateProductCustomIssues( + { + custom_template: null, + option_groups: [ + group(3, ['flavor.cream'], { max_select: 2 }), + group(4, ['shape.heart'], { max_select: 2 }), + ], + }, + 'THREE_D', + ); + expect(issues.map((i) => i.message)).toEqual([ + '크기 옵션을 만들고 3D 항목과 연결해 주세요.', + '맛 옵션은 최대 1개 선택으로 설정해 주세요.', + '모양 옵션은 필수, 1개 선택으로 설정해 주세요.', + ]); + }); + + it('퇴역한 키(selectable=false)는 쓸 수 없는 키다', () => { + jest.isolateModules(() => { + jest.doMock( + '@/features/product/constants/custom-3d-catalog.constants', + () => { + const actual = jest.requireActual( + '@/features/product/constants/custom-3d-catalog.constants', + ); + return { + ...actual, + findThreeDChoice: (key: string | null) => { + const found = actual.findThreeDChoice(key); + return key === 'shape.heart' && found + ? { ...found, selectable: false } + : found; + }, + }; + }, + ); + const isolated = jest.requireActual<{ + evaluateProductCustomIssues: typeof evaluateProductCustomIssues; + }>('@/features/product/services/product-custom-readiness.helper'); + expect( + isolated + .evaluateProductCustomIssues( + { custom_template: null, option_groups: [SHAPE, SIZE] }, + 'THREE_D', + ) + .map((i) => [i.code, i.optionGroupId]), + ).toEqual([['THREE_D_KEY_UNAVAILABLE', '1']]); + }); + }); + }); +}); + +describe('threeDCategoryOf', () => { + it.each([ + ['한 카테고리', ['shape.heart', 'shape.star'], 'SHAPE'], + ['미지정 선택지가 섞여도 카테고리는 하나', ['size.mini', null], 'SIZE'], + ['카테고리가 섞이면 null', ['shape.heart', 'size.mini'], null], + ['키가 없으면 null', [null], null], + ['카탈로그 밖 키는 세지 않는다', ['moon', 'flavor.choco'], 'FLAVOR'], + ] as const)('%s → %s', (_label, keys, expected) => { + expect(threeDCategoryOf(group(1, [...keys]))).toBe(expected); + }); + + it('숨긴 선택지의 키는 세지 않는다', () => { + expect( + threeDCategoryOf(group(1, [item('design.wave', false), 'flavor.cream'])), + ).toBe('FLAVOR'); + }); }); diff --git a/src/features/product/services/product-custom-readiness.helper.ts b/src/features/product/services/product-custom-readiness.helper.ts index e0ce549a..278c8209 100644 --- a/src/features/product/services/product-custom-readiness.helper.ts +++ b/src/features/product/services/product-custom-readiness.helper.ts @@ -1,7 +1,19 @@ +import { + findThreeDChoice, + THREE_D_CATEGORY_LABELS, + type ThreeDOptionCategory, +} from '@/features/product/constants/custom-3d-catalog.constants'; import { CustomMode } from '@/generated/prisma/client'; export type ProductCustomIssueCode = - 'SLOT_TEMPLATE_MISSING' | 'SLOT_NOTHING_TO_EDIT' | 'THREE_D_GROUP_MISSING'; + | 'SLOT_TEMPLATE_MISSING' + | 'SLOT_NOTHING_TO_EDIT' + | 'THREE_D_GROUP_MISSING' + | 'THREE_D_GROUP_DUPLICATED' + | 'THREE_D_GROUP_MIXED' + | 'THREE_D_GROUP_NOT_SINGLE_SELECT' + | 'THREE_D_KEY_DUPLICATED' + | 'THREE_D_KEY_UNAVAILABLE'; export interface ProductCustomIssue { code: ProductCustomIssueCode; @@ -9,27 +21,153 @@ export interface ProductCustomIssue { optionGroupId: string | null; } -/** 준비 상태 판정에 필요한 만큼만 받는다. text_tokens는 삭제 제외 목록이어야 한다. */ +interface ThreeDKeyedItem { + is_active: boolean; + three_d_key: string | null; +} + +export interface ProductCustomReadinessOptionGroup { + id: bigint; + is_active: boolean; + is_required: boolean; + min_select: number; + max_select: number; + option_items: readonly ThreeDKeyedItem[]; +} + +/** 준비 상태 판정에 필요한 만큼만 받는다. 문구 자리·옵션 그룹·항목은 삭제 제외 목록이어야 한다. */ export interface ProductCustomReadinessSource { custom_template: { deleted_at: Date | null; free_edit_enabled: boolean; text_tokens: readonly unknown[]; } | null; + option_groups: readonly ProductCustomReadinessOptionGroup[]; } -const ISSUE_MESSAGES: Record = { - SLOT_TEMPLATE_MISSING: '바탕 이미지를 먼저 등록해 주세요.', - SLOT_NOTHING_TO_EDIT: '문구 자리를 추가하거나 자유 편집을 허용해 주세요.', - THREE_D_GROUP_MISSING: '모양·크기 옵션을 3D 항목과 연결해 주세요.', -}; +/** 모양·크기는 구매자가 꼭 하나 고른다. 맛·디자인은 고르지 않아도 된다(디자인이 없으면 장식 없는 시트). */ +const REQUIRED_CATEGORIES: readonly ThreeDOptionCategory[] = ['SHAPE', 'SIZE']; -const issue = (code: ProductCustomIssueCode): ProductCustomIssue => ({ +const issue = ( + code: ProductCustomIssueCode, + message: string, + optionGroupId: bigint | null = null, +): ProductCustomIssue => ({ code, - message: ISSUE_MESSAGES[code], - optionGroupId: null, + message, + optionGroupId: optionGroupId?.toString() ?? null, }); +function categoriesOf( + items: readonly ThreeDKeyedItem[], +): Set { + const categories = new Set(); + for (const item of items) { + const choice = item.is_active ? findThreeDChoice(item.three_d_key) : null; + if (choice) categories.add(choice.category); + } + return categories; +} + +/** 활성 선택지의 카탈로그 키가 한 카테고리로 모이면 그 값, 없거나 섞이면 null. */ +export function threeDCategoryOf(group: { + option_items: readonly ThreeDKeyedItem[]; +}): ThreeDOptionCategory | null { + const categories = categoriesOf(group.option_items); + return categories.size === 1 ? [...categories][0] : null; +} + +function evaluateThreeDIssues( + groups: readonly ProductCustomReadinessOptionGroup[], +): ProductCustomIssue[] { + const issues: ProductCustomIssue[] = []; + const seenCategories = new Set(); + const seenKeys = new Set(); + + for (const group of groups) { + if (!group.is_active) continue; + const items = group.option_items.filter((item) => item.is_active); + const keys = items.flatMap((item) => item.three_d_key ?? []); + if (keys.length === 0) continue; // 3D와 무관한 그룹(초 추가 등) + + if (keys.some((key) => !findThreeDChoice(key)?.selectable)) { + issues.push( + issue( + 'THREE_D_KEY_UNAVAILABLE', + '더 이상 쓸 수 없는 3D 항목이 연결돼 있어요. 다른 항목으로 바꿔 주세요.', + group.id, + ), + ); + } + if ( + new Set(keys).size < keys.length || + keys.some((key) => seenKeys.has(key)) + ) { + issues.push( + issue( + 'THREE_D_KEY_DUPLICATED', + '같은 3D 항목에 연결된 선택지가 둘 이상이에요.', + group.id, + ), + ); + } + keys.forEach((key) => seenKeys.add(key)); + + const categories = categoriesOf(items); + if (categories.size === 0) continue; + if (categories.size > 1 || keys.length < items.length) { + issues.push( + issue( + 'THREE_D_GROUP_MIXED', + '한 옵션 그룹의 선택지는 모두 같은 종류의 3D 항목에 연결해 주세요.', + group.id, + ), + ); + } + if (categories.size > 1) continue; + + const [category] = categories; + const label = THREE_D_CATEGORY_LABELS[category]; + if (seenCategories.has(category)) { + issues.push( + issue( + 'THREE_D_GROUP_DUPLICATED', + `${label} 3D 항목을 쓰는 옵션 그룹이 둘 이상이에요. 하나만 남겨 주세요.`, + group.id, + ), + ); + } + seenCategories.add(category); + + const required = REQUIRED_CATEGORIES.includes(category); + const singleSelect = required + ? group.is_required && group.min_select === 1 && group.max_select === 1 + : group.max_select === 1; + if (!singleSelect) { + issues.push( + issue( + 'THREE_D_GROUP_NOT_SINGLE_SELECT', + required + ? `${label} 옵션은 필수, 1개 선택으로 설정해 주세요.` + : `${label} 옵션은 최대 1개 선택으로 설정해 주세요.`, + group.id, + ), + ); + } + } + + const missing = REQUIRED_CATEGORIES.filter((c) => !seenCategories.has(c)); + return [ + ...missing.map((category) => + issue( + 'THREE_D_GROUP_MISSING', + `${THREE_D_CATEGORY_LABELS[category]} 옵션을 만들고 3D 항목과 연결해 주세요.`, + ), + ), + ...issues, + ]; +} + /** 판매자 방식 변경·준비 상태 경고·주문 생성이 같은 판정을 쓴다. 빈 배열이면 그 방식으로 주문을 받을 수 있다. */ export function evaluateProductCustomIssues( row: ProductCustomReadinessSource, @@ -41,13 +179,21 @@ export function evaluateProductCustomIssues( case CustomMode.SLOT: { const template = row.custom_template?.deleted_at === null ? row.custom_template : null; - if (!template) return [issue('SLOT_TEMPLATE_MISSING')]; + if (!template) { + return [ + issue('SLOT_TEMPLATE_MISSING', '바탕 이미지를 먼저 등록해 주세요.'), + ]; + } return template.text_tokens.length === 0 && !template.free_edit_enabled - ? [issue('SLOT_NOTHING_TO_EDIT')] + ? [ + issue( + 'SLOT_NOTHING_TO_EDIT', + '문구 자리를 추가하거나 자유 편집을 허용해 주세요.', + ), + ] : []; } case CustomMode.THREE_D: - // 옵션 항목을 3D 카탈로그에 연결하는 칸이 아직 없어 모양·크기 그룹을 만들 수 없다 - return [issue('THREE_D_GROUP_MISSING')]; + return evaluateThreeDIssues(row.option_groups); } } diff --git a/src/features/product/services/product-detail-mappers.helper.ts b/src/features/product/services/product-detail-mappers.helper.ts index 59df4ba6..9f852ab9 100644 --- a/src/features/product/services/product-detail-mappers.helper.ts +++ b/src/features/product/services/product-detail-mappers.helper.ts @@ -1,5 +1,6 @@ import { calcDiscountRate } from '@/common/utils/discount-rate'; import type { ProductDetailRow } from '@/features/product/repositories/product.repository'; +import { threeDCategoryOf } from '@/features/product/services/product-custom-readiness.helper'; import type { ProductDetail, ProductDetailCustomTemplate, @@ -61,6 +62,7 @@ export function toProductDetail( minSelect: group.min_select, maxSelect: group.max_select, sortOrder: group.sort_order, + threeDCategory: threeDCategoryOf(group), items: group.option_items.map((item) => ({ id: item.id.toString(), title: item.title, @@ -68,6 +70,7 @@ export function toProductDetail( imageUrl: item.image_url, priceDelta: item.price_delta, sortOrder: item.sort_order, + threeDKey: item.three_d_key, })), })), customMode: row.custom_mode, diff --git a/src/features/product/services/product-detail.service.spec.ts b/src/features/product/services/product-detail.service.spec.ts index 0082dcf8..98521841 100644 --- a/src/features/product/services/product-detail.service.spec.ts +++ b/src/features/product/services/product-detail.service.spec.ts @@ -171,6 +171,43 @@ describe('ProductDetailService (real DB)', () => { expect(flavor.items[1].priceDelta).toBe(2000); }); + it('옵션 항목의 3D 키와 그룹의 3D 카테고리를 준다(키가 없거나 섞이면 null)', async () => { + const product = await createProduct(prisma); + const groupOf = async (sortOrder: number, keys: (string | null)[]) => { + const group = await prisma.productOptionGroup.create({ + data: { + product_id: product.id, + name: `g${sortOrder}`, + sort_order: sortOrder, + }, + }); + await prisma.productOptionItem.createMany({ + data: keys.map((key, i) => ({ + option_group_id: group.id, + title: `i${i}`, + sort_order: i, + three_d_key: key, + })), + }); + }; + await groupOf(0, ['shape.heart', 'shape.star']); + await groupOf(1, ['size.mini', 'flavor.cream']); + await groupOf(2, [null]); + + const result = await service.productDetail(product.id.toString()); + + expect( + result.optionGroups.map((g) => [ + g.threeDCategory, + g.items.map((i) => i.threeDKey), + ]), + ).toEqual([ + ['SHAPE', ['shape.heart', 'shape.star']], + [null, ['size.mini', 'flavor.cream']], + [null, [null]], + ]); + }); + it('슬롯형 상품은 꾸미기 설정(revision·바탕·자유 편집·삭제 제외 문구 자리 sortOrder 순)을 준다', async () => { const product = await createProduct(prisma); await prisma.product.update({ diff --git a/src/features/product/services/product-seller-custom-template.service.spec.ts b/src/features/product/services/product-seller-custom-template.service.spec.ts index 9a9a6a4a..3fb8cf26 100644 --- a/src/features/product/services/product-seller-custom-template.service.spec.ts +++ b/src/features/product/services/product-seller-custom-template.service.spec.ts @@ -238,7 +238,10 @@ describe('SellerCustomTemplateService (real DB)', () => { { mode: 'THREE_D', ready: false, - issues: [expect.objectContaining({ code: 'THREE_D_GROUP_MISSING' })], + issues: [ + expect.objectContaining({ code: 'THREE_D_GROUP_MISSING' }), + expect.objectContaining({ code: 'THREE_D_GROUP_MISSING' }), + ], }, ]); expect( @@ -247,6 +250,168 @@ describe('SellerCustomTemplateService (real DB)', () => { }); }); + describe('sellerApplyThreeDOptionPreset', () => { + const groupsOf = (productId: bigint) => + prisma.productOptionGroup.findMany({ + where: { product_id: productId }, + orderBy: { sort_order: 'asc' }, + include: { option_items: { orderBy: { sort_order: 'asc' } } }, + }); + + it('다른 매장 상품이면 404이고 아무것도 만들지 않는다', async () => { + const me = await setupSellerWithProduct(); + const other = await setupSellerWithProduct(); + + await expect( + service.sellerApplyThreeDOptionPreset(me.accountId, other.product.id), + ).rejects.toThrowDomain('PRODUCT_NOT_FOUND'); + expect(await groupsOf(other.product.id)).toEqual([]); + }); + + it('빈 카테고리마다 단일 선택 그룹을 기존 그룹 뒤에 만들고, 3D 방식으로 바꿀 수 있게 된다', async () => { + const { accountId, storeId, product } = await setupSellerWithProduct(); + await prisma.productOptionGroup.create({ + data: { product_id: product.id, name: '초', sort_order: 4 }, + }); + + const result = await service.sellerApplyThreeDOptionPreset( + accountId, + product.id, + ); + + const groups = await groupsOf(product.id); + expect( + groups.map((g) => [ + g.name, + g.sort_order, + g.is_required, + g.min_select, + g.max_select, + ]), + ).toEqual([ + ['초', 4, true, 1, 1], + ['크기', 5, true, 1, 1], + ['맛', 6, true, 1, 1], + ['모양', 7, true, 1, 1], + ['디자인', 8, false, 0, 1], + ]); + expect( + groups[1].option_items.map((i) => [ + i.title, + i.price_delta, + i.three_d_key, + i.sort_order, + ]), + ).toEqual([ + ['도시락 (1~2인)', 0, 'size.lunchbox', 0], + ['미니 (1~2인)', 0, 'size.mini', 1], + ['1호 (2~3인)', 5000, 'size.no1', 2], + ]); + expect(groups.slice(1).map((g) => g.option_items.length)).toEqual([ + 3, 3, 8, 5, + ]); + expect(result.optionGroups.map((g) => g.threeDCategory)).toEqual([ + null, + 'SIZE', + 'FLAVOR', + 'SHAPE', + 'DESIGN', + ]); + expect(result.customReadiness.find((r) => r.mode === 'THREE_D')).toEqual({ + mode: 'THREE_D', + ready: true, + issues: [], + }); + + const audits = await prisma.auditLog.findMany({ + where: { store_id: storeId }, + }); + expect(audits.map((a) => [a.action, a.after_json])).toEqual([ + [ + 'CREATE', + { + threeDOptionPreset: true, + optionGroupIds: groups.slice(1).map((g) => g.id.toString()), + }, + ], + ]); + await expect( + service.sellerSetProductCustomMode(accountId, product.id, 'THREE_D'), + ).resolves.toMatchObject({ customMode: 'THREE_D' }); + }); + + it('다시 불러도 아무것도 만들지 않고 감사도 남기지 않는다', async () => { + const { accountId, storeId, product } = await setupSellerWithProduct(); + await service.sellerApplyThreeDOptionPreset(accountId, product.id); + const before = await groupsOf(product.id); + + await service.sellerApplyThreeDOptionPreset(accountId, product.id); + + expect(await groupsOf(product.id)).toEqual(before); + expect( + await prisma.auditLog.count({ where: { store_id: storeId } }), + ).toBe(1); + }); + + it('3D 항목 그룹이 이미 있는 카테고리는 건드리지 않고, 숨긴 그룹의 카테고리는 다시 만든다', async () => { + const { accountId, product } = await setupSellerWithProduct(); + const shape = await prisma.productOptionGroup.create({ + data: { product_id: product.id, name: '하트만', sort_order: 0 }, + }); + await prisma.productOptionItem.create({ + data: { + option_group_id: shape.id, + title: '하트', + price_delta: 3000, + three_d_key: 'shape.heart', + }, + }); + const hiddenSize = await prisma.productOptionGroup.create({ + data: { + product_id: product.id, + name: '숨긴 크기', + sort_order: 1, + is_active: false, + }, + }); + await prisma.productOptionItem.create({ + data: { + option_group_id: hiddenSize.id, + title: '미니', + three_d_key: 'size.mini', + }, + }); + + await service.sellerApplyThreeDOptionPreset(accountId, product.id); + + const groups = await groupsOf(product.id); + expect(groups.map((g) => g.name)).toEqual([ + '하트만', + '숨긴 크기', + '크기', + '맛', + '디자인', + ]); + expect(groups[0].option_items.map((i) => i.price_delta)).toEqual([3000]); + }); + + it('동시에 두 번 불러도 카테고리마다 그룹은 하나다', async () => { + const { accountId, product } = await setupSellerWithProduct(); + + await Promise.all([ + service.sellerApplyThreeDOptionPreset(accountId, product.id), + service.sellerApplyThreeDOptionPreset(accountId, product.id), + ]); + + expect((await groupsOf(product.id)).map((g) => g.name)).toEqual([ + '크기', + '맛', + '모양', + '디자인', + ]); + }); + }); + describe('sellerUpsertProductCustomTemplate', () => { it('없는 productId면 404', async () => { const { accountId } = await setupSellerWithProduct(); diff --git a/src/features/product/services/product-seller-custom-template.service.ts b/src/features/product/services/product-seller-custom-template.service.ts index 77c5cbcc..cefa4576 100644 --- a/src/features/product/services/product-seller-custom-template.service.ts +++ b/src/features/product/services/product-seller-custom-template.service.ts @@ -21,6 +21,7 @@ import type { SellerReorderProductCustomTextTokensInput } from '@/features/produ import type { SellerUpsertProductCustomTemplateInput } from '@/features/product/dto/inputs/seller-upsert-product-custom-template.input'; import type { SellerUpsertProductCustomTextTokenInput } from '@/features/product/dto/inputs/seller-upsert-product-custom-text-token.input'; import { ProductRepository } from '@/features/product/repositories/product.repository'; +import { planThreeDOptionPreset } from '@/features/product/services/custom-3d-preset.helper'; import { evaluateProductCustomIssues } from '@/features/product/services/product-custom-readiness.helper'; import { toCustomTemplateOutput, @@ -85,6 +86,32 @@ export class SellerCustomTemplateService extends SellerBaseService { ); } + /** 3D 항목 그룹이 없는 카테고리만 기본 세트로 채운다. 이미 있는 카테고리는 건드리지 않는다. */ + async sellerApplyThreeDOptionPreset( + accountId: bigint, + productId: bigint, + ): Promise { + const ctx = await this.requireSellerContext(accountId); + await this.requireOwnProduct(productId, ctx.storeId); + await this.productRepository.createOptionGroupsLocked( + { productId, plan: planThreeDOptionPreset }, + (optionGroupIds) => ({ + actorAccountId: ctx.accountId, + storeId: ctx.storeId, + targetType: AuditTargetType.PRODUCT, + targetId: productId, + action: AuditActionType.CREATE, + afterJson: { + threeDOptionPreset: true, + optionGroupIds: optionGroupIds.map((id) => id.toString()), + }, + }), + ); + return toProductOutput( + await this.requireOwnProduct(productId, ctx.storeId), + ); + } + async sellerUpsertProductCustomTemplate( accountId: bigint, input: SellerUpsertProductCustomTemplateInput, diff --git a/src/features/product/services/product-seller-mappers.helper.ts b/src/features/product/services/product-seller-mappers.helper.ts index c66ce9eb..61d17e7b 100644 --- a/src/features/product/services/product-seller-mappers.helper.ts +++ b/src/features/product/services/product-seller-mappers.helper.ts @@ -1,12 +1,29 @@ -import { evaluateProductCustomIssues } from '@/features/product/services/product-custom-readiness.helper'; +import { + evaluateProductCustomIssues, + threeDCategoryOf, +} from '@/features/product/services/product-custom-readiness.helper'; import type { SellerCustomReadinessOutput, SellerCustomTextTokenOutput, + SellerOptionGroupOutput, + SellerOptionItemOutput, SellerProductImageOutput, SellerProductOutput, } from '@/features/product/types/product-seller-output.type'; import { CustomMode, type CustomTextAlign } from '@/generated/prisma/client'; +export interface ProductOptionItemRow { + id: bigint; + option_group_id: bigint; + title: string; + description: string | null; + image_url: string | null; + price_delta: number; + sort_order: number; + is_active: boolean; + three_d_key: string | null; +} + export interface ProductOptionGroupRow { id: bigint; product_id: bigint; @@ -17,16 +34,7 @@ export interface ProductOptionGroupRow { max_select: number; sort_order: number; is_active: boolean; - option_items: { - id: bigint; - option_group_id: bigint; - title: string; - description: string | null; - image_url: string | null; - price_delta: number; - sort_order: number; - is_active: boolean; - }[]; + option_items: ProductOptionItemRow[]; } export interface ProductCustomTextTokenRow { @@ -89,7 +97,25 @@ export function toProductImageOutput(row: { }; } -export function toOptionGroupOutput(g: ProductOptionGroupRow) { +export function toOptionItemOutput( + item: ProductOptionItemRow, +): SellerOptionItemOutput { + return { + id: item.id.toString(), + optionGroupId: item.option_group_id.toString(), + title: item.title, + description: item.description, + imageUrl: item.image_url, + priceDelta: item.price_delta, + sortOrder: item.sort_order, + isActive: item.is_active, + threeDKey: item.three_d_key, + }; +} + +export function toOptionGroupOutput( + g: ProductOptionGroupRow, +): SellerOptionGroupOutput { return { id: g.id.toString(), productId: g.product_id.toString(), @@ -100,16 +126,8 @@ export function toOptionGroupOutput(g: ProductOptionGroupRow) { maxSelect: g.max_select, sortOrder: g.sort_order, isActive: g.is_active, - optionItems: g.option_items.map((item) => ({ - id: item.id.toString(), - optionGroupId: item.option_group_id.toString(), - title: item.title, - description: item.description, - imageUrl: item.image_url, - priceDelta: item.price_delta, - sortOrder: item.sort_order, - isActive: item.is_active, - })), + threeDCategory: threeDCategoryOf(g), + optionItems: g.option_items.map(toOptionItemOutput), }; } @@ -147,7 +165,7 @@ export function toCustomTemplateOutput(t: ProductCustomTemplateRow) { /** 판매자 커스텀 설정 화면이 방식별 카드에 준비 이슈를 띄운다. */ export function toCustomReadinessOutput( - row: Pick, + row: Pick, ): SellerCustomReadinessOutput[] { return Object.values(CustomMode).map((mode) => { const issues = evaluateProductCustomIssues(row, mode); diff --git a/src/features/product/services/product-seller-option.service.spec.ts b/src/features/product/services/product-seller-option.service.spec.ts index 30f37c58..589ac960 100644 --- a/src/features/product/services/product-seller-option.service.spec.ts +++ b/src/features/product/services/product-seller-option.service.spec.ts @@ -268,6 +268,41 @@ describe('SellerOptionService (real DB)', () => { }); expect(result.title).toBe('L'); expect(result.priceDelta).toBe(3000); + expect(result.threeDKey).toBeNull(); + }); + + it('3D 키는 공백을 지워 저장하고, 빈 문자열이면 연결하지 않는다', async () => { + const { accountId, product } = await setupProductForSeller(); + const group = await createOptionGroup(product.id); + + const linked = await service.sellerCreateOptionItem(accountId, { + optionGroupId: group.id.toString(), + title: '하트', + threeDKey: ' shape.heart ', + }); + const blank = await service.sellerCreateOptionItem(accountId, { + optionGroupId: group.id.toString(), + title: '초', + threeDKey: ' ', + }); + + expect([linked.threeDKey, blank.threeDKey]).toEqual([ + 'shape.heart', + null, + ]); + }); + + it('3D 키가 40자를 넘으면 거절한다', async () => { + const { accountId, product } = await setupProductForSeller(); + const group = await createOptionGroup(product.id); + + await expect( + service.sellerCreateOptionItem(accountId, { + optionGroupId: group.id.toString(), + title: 'X', + threeDKey: `shape.${'a'.repeat(35)}`, + }), + ).rejects.toThrowDomain('TEXT_TOO_LONG'); }); }); @@ -311,6 +346,60 @@ describe('SellerOptionService (real DB)', () => { }); expect(result.title).toBe('XL'); }); + + it('3D 키는 생략하면 그대로, 바꾸면 새 값, null이면 연결을 끊는다', async () => { + const { accountId, product } = await setupProductForSeller(); + const group = await createOptionGroup(product.id); + const item = await prisma.productOptionItem.create({ + data: { + option_group_id: group.id, + title: 'S', + three_d_key: 'size.mini', + }, + }); + const update = (threeDKey?: string | null) => + service.sellerUpdateOptionItem(accountId, { + optionItemId: item.id.toString(), + threeDKey, + }); + + expect((await update()).threeDKey).toBe('size.mini'); + expect((await update('size.no1')).threeDKey).toBe('size.no1'); + expect((await update(null)).threeDKey).toBeNull(); + }); + + it('그룹 출력의 3D 카테고리는 활성 선택지의 키로 정한다', async () => { + const { accountId, product } = await setupProductForSeller(); + const group = await createOptionGroup(product.id); + await prisma.productOptionItem.createMany({ + data: [ + { + option_group_id: group.id, + title: '원', + three_d_key: 'shape.circle', + sort_order: 0, + }, + { + option_group_id: group.id, + title: '숨긴 크기', + three_d_key: 'size.mini', + sort_order: 1, + is_active: false, + }, + ], + }); + + const result = await service.sellerUpdateOptionGroup(accountId, { + optionGroupId: group.id.toString(), + name: '모양', + }); + + expect(result.threeDCategory).toBe('SHAPE'); + expect(result.optionItems.map((i) => i.threeDKey)).toEqual([ + 'shape.circle', + 'size.mini', + ]); + }); }); describe('sellerDeleteOptionItem', () => { diff --git a/src/features/product/services/product-seller-option.service.ts b/src/features/product/services/product-seller-option.service.ts index 87f5ad6d..8c2242e7 100644 --- a/src/features/product/services/product-seller-option.service.ts +++ b/src/features/product/services/product-seller-option.service.ts @@ -15,6 +15,7 @@ import { MAX_OPTION_GROUP_NAME_LENGTH, MAX_OPTION_ITEM_DESCRIPTION_LENGTH, MAX_OPTION_ITEM_TITLE_LENGTH, + MAX_THREE_D_KEY_LENGTH, MAX_URL_LENGTH, } from '@/features/product/constants/product-seller.constants'; import type { SellerCreateOptionGroupInput } from '@/features/product/dto/inputs/seller-create-option-group.input'; @@ -24,6 +25,10 @@ import type { SellerReorderOptionItemsInput } from '@/features/product/dto/input import type { SellerUpdateOptionGroupInput } from '@/features/product/dto/inputs/seller-update-option-group.input'; import type { SellerUpdateOptionItemInput } from '@/features/product/dto/inputs/seller-update-option-item.input'; import { ProductRepository } from '@/features/product/repositories/product.repository'; +import { + toOptionGroupOutput, + toOptionItemOutput, +} from '@/features/product/services/product-seller-mappers.helper'; import type { SellerOptionGroupOutput, SellerOptionItemOutput, @@ -92,7 +97,7 @@ export class SellerOptionService extends SellerBaseService { }, }), ); - return this.toOptionGroupOutput(row); + return toOptionGroupOutput(row); } async sellerUpdateOptionGroup( @@ -162,7 +167,7 @@ export class SellerOptionService extends SellerBaseService { }, }), ); - return this.toOptionGroupOutput(row); + return toOptionGroupOutput(row); } async sellerDeleteOptionGroup( @@ -235,7 +240,7 @@ export class SellerOptionService extends SellerBaseService { }, }), ); - return rows.map((row) => this.toOptionGroupOutput(row)); + return rows.map(toOptionGroupOutput); } async sellerCreateOptionItem( @@ -273,6 +278,10 @@ export class SellerOptionService extends SellerBaseService { price_delta: input.priceDelta ?? 0, sort_order: input.sortOrder ?? 0, is_active: input.isActive ?? true, + three_d_key: cleanNullableText( + input.threeDKey, + MAX_THREE_D_KEY_LENGTH, + ), }, }, (created) => ({ @@ -286,7 +295,7 @@ export class SellerOptionService extends SellerBaseService { }, }), ); - return this.toOptionItemOutput(row); + return toOptionItemOutput(row); } async sellerUpdateOptionItem( @@ -346,6 +355,14 @@ export class SellerOptionService extends SellerBaseService { ...(input.isActive !== undefined ? { is_active: input.isActive } : {}), + ...(input.threeDKey !== undefined + ? { + three_d_key: cleanNullableText( + input.threeDKey, + MAX_THREE_D_KEY_LENGTH, + ), + } + : {}), }, }, (created) => ({ @@ -359,7 +376,7 @@ export class SellerOptionService extends SellerBaseService { }, }), ); - return this.toOptionItemOutput(row); + return toOptionItemOutput(row); } async sellerDeleteOptionItem( @@ -431,65 +448,6 @@ export class SellerOptionService extends SellerBaseService { }, }), ); - return rows.map((row) => this.toOptionItemOutput(row)); - } - - private toOptionGroupOutput(row: { - id: bigint; - product_id: bigint; - name: string; - description: string | null; - is_required: boolean; - min_select: number; - max_select: number; - sort_order: number; - is_active: boolean; - option_items: { - id: bigint; - option_group_id: bigint; - title: string; - description: string | null; - image_url: string | null; - price_delta: number; - sort_order: number; - is_active: boolean; - }[]; - }): SellerOptionGroupOutput { - return { - id: row.id.toString(), - productId: row.product_id.toString(), - name: row.name, - description: row.description, - isRequired: row.is_required, - minSelect: row.min_select, - maxSelect: row.max_select, - sortOrder: row.sort_order, - isActive: row.is_active, - optionItems: row.option_items.map((item) => - this.toOptionItemOutput(item), - ), - }; - } - - private toOptionItemOutput(row: { - id: bigint; - option_group_id: bigint; - title: string; - description: string | null; - image_url: string | null; - price_delta: number; - sort_order: number; - is_active: boolean; - }): SellerOptionItemOutput { - return { - id: row.id.toString(), - optionGroupId: row.option_group_id.toString(), - title: row.title, - description: row.description, - imageUrl: row.image_url, - priceDelta: row.price_delta, - sortOrder: row.sort_order, - isActive: row.is_active, - }; + return rows.map(toOptionItemOutput); } } diff --git a/src/features/product/types/product-detail-output.type.ts b/src/features/product/types/product-detail-output.type.ts index 62160077..7cba7240 100644 --- a/src/features/product/types/product-detail-output.type.ts +++ b/src/features/product/types/product-detail-output.type.ts @@ -1,3 +1,4 @@ +import type { ThreeDOptionCategory } from '@/features/product/constants/custom-3d-catalog.constants'; import type { CustomMode, CustomTextAlign } from '@/generated/prisma/client'; export interface ProductDetailOptionItem { @@ -7,6 +8,7 @@ export interface ProductDetailOptionItem { imageUrl: string | null; priceDelta: number; sortOrder: number; + threeDKey: string | null; } export interface ProductDetailOptionGroup { @@ -17,6 +19,7 @@ export interface ProductDetailOptionGroup { minSelect: number; maxSelect: number; sortOrder: number; + threeDCategory: ThreeDOptionCategory | null; items: ProductDetailOptionItem[]; } diff --git a/src/features/product/types/product-seller-output.type.ts b/src/features/product/types/product-seller-output.type.ts index f4eb30ce..29f570f3 100644 --- a/src/features/product/types/product-seller-output.type.ts +++ b/src/features/product/types/product-seller-output.type.ts @@ -1,3 +1,4 @@ +import type { ThreeDOptionCategory } from '@/features/product/constants/custom-3d-catalog.constants'; import type { ProductCustomIssue } from '@/features/product/services/product-custom-readiness.helper'; import type { CustomMode, CustomTextAlign } from '@/generated/prisma/client'; @@ -33,6 +34,7 @@ export interface SellerOptionItemOutput { priceDelta: number; sortOrder: number; isActive: boolean; + threeDKey: string | null; } export interface SellerOptionGroupOutput { @@ -45,6 +47,7 @@ export interface SellerOptionGroupOutput { maxSelect: number; sortOrder: number; isActive: boolean; + threeDCategory: ThreeDOptionCategory | null; optionItems: SellerOptionItemOutput[]; } From 6f2cd4034a4aed240287f50e9c2f18f62cac889f Mon Sep 17 00:00:00 2001 From: chanwoo7 Date: Thu, 19 Nov 2026 02:34:48 +0900 Subject: [PATCH 25/54] =?UTF-8?q?feat:=203D=20=EB=94=94=EC=9E=90=EC=9D=B8?= =?UTF-8?q?=20JSON=20v1=20=EC=84=9C=EB=B2=84=20=EA=B2=80=EC=A6=9D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 주문에 저장할 3D 디자인(JSON + 스키마 버전)을 서버가 카탈로그·한도로 검증하고 정규형으로 만든다. 주문 생성이 이 헬퍼를 쓰는데 order가 product를 import하므로, 입력은 product 안의 구조 타입으로 받고 order DTO가 그 구조를 만족하게 한다. 변경점 - product 순수 헬퍼 validateThreeDDesign(design, selectedThreeDKeys)(배럴 공개, 입력 구조 타입 ThreeDDesignSource·출력 ThreeDDesignV1) - schemaVersion == 1(CUSTOM_3D_SCHEMA_UNSUPPORTED) - basic: 모양·크기는 고른 옵션 키의 값과 같고, 디자인·맛은 고른 항목이 있으면 같고 없으면 null(그룹이 있어도 고르지 않았으면 null). 같은 카테고리를 둘 고른 경우 포함 CUSTOM_3D_OPTIONS_CHANGED(409). 3D와 무관한 옵션은 보지 않는다 - 면당 글자·꾸미기 각 10개(CUSTOM_3D_ITEM_LIMIT_EXCEEDED) - 시트 색·효과·꾸미기는 카탈로그 선택 가능 값, x·y 0~1 유한수, 크기 글자 4~30·꾸미기 8~50, 효과 강도 정수 0~100, 글자는 CRLF·CR→LF·trim 뒤 1~30 코드 포인트(줄바꿈·이모지 허용)·#RRGGBB(대문자로 저장)·decoId 없음, 꾸미기는 글자·색 없음(CUSTOM_3D_DESIGN_INVALID, 메시지에 어긋난 위치 top[0].size 형식) - 에러 코드 4종 신설(CUSTOM_3D_OPTIONS_CHANGED만 409) 테스트 - 3D 검증 표: 정규형 1, 글자 정규화 1, 빈 면 1, 버전 3, 옵션 통과 3·불일치 10, 면당 개수 통과 2·초과 4, 값 범위 통과(경계·시트 색·효과·꾸미기 전수) 30·거절 31, 검사 순서 1 - 가드 반증: 디자인 옵션 대조·시트 색·효과 강도 정수 검사를 끄면 해당 테스트가 실패함을 확인 --- src/common/errors/error-catalog.spec.ts | 2 + src/common/errors/error-catalog.ts | 19 + src/features/product/index.ts | 6 + .../services/three-d-design.helper.spec.ts | 327 ++++++++++++++++++ .../product/services/three-d-design.helper.ts | 212 ++++++++++++ 5 files changed, 566 insertions(+) create mode 100644 src/features/product/services/three-d-design.helper.spec.ts create mode 100644 src/features/product/services/three-d-design.helper.ts diff --git a/src/common/errors/error-catalog.spec.ts b/src/common/errors/error-catalog.spec.ts index 471452f0..5341e7d9 100644 --- a/src/common/errors/error-catalog.spec.ts +++ b/src/common/errors/error-catalog.spec.ts @@ -33,6 +33,8 @@ const RENDER_PARAMS: Partial< INVALID_LIMIT: { max: 50 }, FIELD_OUT_OF_RANGE: { field: 'capacity', min: 1, max: 100 }, CUSTOM_TEXT_DEFAULT_TOO_LONG: { label: '이름', max: 20 }, + CUSTOM_3D_ITEM_LIMIT_EXCEEDED: { max: 10 }, + CUSTOM_3D_DESIGN_INVALID: { field: 'top[0].size' }, IDS_LENGTH_MISMATCH: { field: 'imageIds' }, INVALID_IDS: { field: 'imageIds' }, PRODUCT_IMAGE_LIMIT_EXCEEDED: { max: 10 }, diff --git a/src/common/errors/error-catalog.ts b/src/common/errors/error-catalog.ts index 62e311e0..a23172ce 100644 --- a/src/common/errors/error-catalog.ts +++ b/src/common/errors/error-catalog.ts @@ -534,6 +534,25 @@ export const ERROR_CATALOG = { status: HttpStatus.BAD_REQUEST, message: '바탕 이미지를 읽을 수 없어요. 이미지를 다시 올려 주세요.', }, + CUSTOM_3D_SCHEMA_UNSUPPORTED: { + status: HttpStatus.BAD_REQUEST, + message: + '지원하지 않는 3D 디자인 형식이에요. 앱을 업데이트한 뒤 다시 꾸며 주세요.', + }, + CUSTOM_3D_OPTIONS_CHANGED: { + status: HttpStatus.CONFLICT, + message: '고른 옵션과 3D 디자인이 맞지 않아요. 다시 꾸며 주세요.', + }, + CUSTOM_3D_ITEM_LIMIT_EXCEEDED: { + status: HttpStatus.BAD_REQUEST, + message: ({ max }) => + `한 면에 글자와 꾸미기는 각각 ${max}개까지 올릴 수 있어요.`, + }, + CUSTOM_3D_DESIGN_INVALID: { + status: HttpStatus.BAD_REQUEST, + message: ({ field }) => + `3D 디자인에 쓸 수 없는 값이 있어요(${field}). 다시 꾸며 주세요.`, + }, INVALID_DAY_OF_WEEK: { status: HttpStatus.BAD_REQUEST, message: 'dayOfWeek는 0~6이어야 합니다.', diff --git a/src/features/product/index.ts b/src/features/product/index.ts index e15f2687..0b1245bd 100644 --- a/src/features/product/index.ts +++ b/src/features/product/index.ts @@ -10,6 +10,12 @@ export { evaluateProductCustomIssues, type ProductCustomIssue, } from '@/features/product/services/product-custom-readiness.helper'; +// 주문 생성(order feature)의 3D 디자인 검증. 입력은 product 구조 타입이라 order DTO가 이 구조를 만족한다. +export { + validateThreeDDesign, + type ThreeDDesignSource, + type ThreeDDesignV1, +} from '@/features/product/services/three-d-design.helper'; // 상품 카드 1벌. 찜·최근 본 상품(user feature)이 같은 카드를 쓴다. export { ProductCardService } from '@/features/product/services/product-card.service'; export type { ProductCardOutput } from '@/features/product/types/product-card-output.type'; diff --git a/src/features/product/services/three-d-design.helper.spec.ts b/src/features/product/services/three-d-design.helper.spec.ts new file mode 100644 index 00000000..401adb59 --- /dev/null +++ b/src/features/product/services/three-d-design.helper.spec.ts @@ -0,0 +1,327 @@ +import { + THREE_D_DECOS, + THREE_D_EFFECTS, + THREE_D_SHEET_COLORS, +} from '@/features/product/constants/custom-3d-catalog.constants'; +import { + validateThreeDDesign, + type ThreeDDesignItemSource, + type ThreeDDesignSource, +} from '@/features/product/services/three-d-design.helper'; + +const SELECTED = ['shape.heart', 'size.no1', 'design.wave', 'flavor.cream']; + +const text = ( + overrides: Partial = {}, +): ThreeDDesignItemSource => ({ + kind: 'TEXT', + x: 0.5, + y: 0.5, + size: 8, + effect: { type: 'none', intensity: 50 }, + text: '생일 축하해', + color: '#1d1d1d', + ...overrides, +}); + +const deco = ( + overrides: Partial = {}, +): ThreeDDesignItemSource => ({ + kind: 'DECO', + x: 0.2, + y: 0.3, + size: 20, + effect: { type: 'soft', intensity: 0 }, + decoId: 'number-1', + ...overrides, +}); + +const design = ( + overrides: Partial = {}, + basic: Partial = {}, +): ThreeDDesignSource => ({ + schemaVersion: 1, + basic: { + shape: 'heart', + size: 'no1', + design: 'wave', + flavor: 'cream', + sheetColor: 'white', + ...basic, + }, + top: [text(), deco()], + side: [deco()], + ...overrides, +}); + +const times = (n: number, make: () => T): T[] => + Array.from({ length: n }, make); + +describe('validateThreeDDesign', () => { + it('통과한 디자인을 저장할 정규형으로 돌려준다(글자색 대문자)', () => { + expect(validateThreeDDesign(design(), SELECTED)).toEqual({ + schemaVersion: 1, + basic: { + shape: 'heart', + size: 'no1', + design: 'wave', + flavor: 'cream', + sheetColor: 'white', + }, + top: [ + { + kind: 'TEXT', + x: 0.5, + y: 0.5, + size: 8, + effect: { type: 'none', intensity: 50 }, + text: '생일 축하해', + color: '#1D1D1D', + }, + { + kind: 'DECO', + x: 0.2, + y: 0.3, + size: 20, + effect: { type: 'soft', intensity: 0 }, + decoId: 'number-1', + }, + ], + side: [ + { + kind: 'DECO', + x: 0.2, + y: 0.3, + size: 20, + effect: { type: 'soft', intensity: 0 }, + decoId: 'number-1', + }, + ], + }); + }); + + it('글자는 줄바꿈을 LF로 바꾸고 앞뒤 공백을 지운다(줄바꿈·이모지 허용)', () => { + const result = validateThreeDDesign( + design({ top: [text({ text: ' 축하해\r\n🎂\r고마워 \n' })], side: [] }), + SELECTED, + ); + expect(result.top[0]).toMatchObject({ text: '축하해\n🎂\n고마워' }); + }); + + it('면이 비어 있어도 된다', () => { + const result = validateThreeDDesign( + design({ top: [], side: [] }), + SELECTED, + ); + expect(result.top).toEqual([]); + expect(result.side).toEqual([]); + }); + + it.each([0, 2, 1.5])('schemaVersion %s 는 지원하지 않는다', (version) => { + expect(() => + validateThreeDDesign(design({ schemaVersion: version }), SELECTED), + ).toThrowDomain('CUSTOM_3D_SCHEMA_UNSUPPORTED'); + }); + + describe('basic ↔ 고른 옵션', () => { + it.each<[string, Partial, (string | null)[]]>([ + [ + '디자인·맛을 고르지 않았고 둘 다 null', + { design: null, flavor: null }, + ['shape.heart', 'size.no1'], + ], + [ + '디자인·맛을 고르지 않았고 둘 다 생략', + { design: undefined, flavor: undefined }, + ['shape.heart', 'size.no1'], + ], + [ + '3D와 무관한 항목·모르는 키는 보지 않는다', + {}, + [...SELECTED, null, 'candle.big'], + ], + ])('통과: %s', (_label, basic, selected) => { + expect(() => + validateThreeDDesign(design({}, basic), selected), + ).not.toThrow(); + }); + + it.each<[string, Partial, (string | null)[]]>([ + ['모양이 다름', { shape: 'star' }, SELECTED], + ['크기가 다름', { size: 'mini' }, SELECTED], + ['모양을 고르지 않음', {}, ['size.no1', 'design.wave', 'flavor.cream']], + [ + '크기를 고르지 않음', + {}, + ['shape.heart', 'design.wave', 'flavor.cream'], + ], + ['디자인을 골랐는데 null', { design: null }, SELECTED], + ['디자인을 골랐는데 다름', { design: 'drip' }, SELECTED], + [ + '디자인을 고르지 않았는데 값이 있음', + {}, + ['shape.heart', 'size.no1', 'flavor.cream'], + ], + ['맛을 골랐는데 null', { flavor: null }, SELECTED], + [ + '맛을 고르지 않았는데 값이 있음', + {}, + ['shape.heart', 'size.no1', 'design.wave'], + ], + ['같은 카테고리를 둘 고름', {}, [...SELECTED, 'shape.star']], + ])('CUSTOM_3D_OPTIONS_CHANGED: %s', (_label, basic, selected) => { + expect(() => + validateThreeDDesign(design({}, basic), selected), + ).toThrowDomain('CUSTOM_3D_OPTIONS_CHANGED'); + }); + }); + + describe('면당 개수', () => { + it.each(['top', 'side'] as const)( + '%s 에 글자 10개·꾸미기 10개까지 올릴 수 있다', + (face) => { + const items = [...times(10, () => text()), ...times(10, () => deco())]; + expect(() => + validateThreeDDesign(design({ [face]: items }), SELECTED), + ).not.toThrow(); + }, + ); + + it.each([ + ['top', '글자', () => text()], + ['top', '꾸미기', () => deco()], + ['side', '글자', () => text()], + ['side', '꾸미기', () => deco()], + ] as const)('%s 에 %s 11개는 넘친다', (face, _label, make) => { + const run = () => + validateThreeDDesign(design({ [face]: times(11, make) }), SELECTED); + expect(run).toThrowDomain('CUSTOM_3D_ITEM_LIMIT_EXCEEDED'); + expect(run).toThrow('10개'); + }); + }); + + describe('값 범위', () => { + const top = (item: ThreeDDesignItemSource) => design({ top: [item] }); + + it.each<[string, ThreeDDesignSource]>([ + ['x·y 0', top(text({ x: 0, y: 0 }))], + ['x·y 1', top(deco({ x: 1, y: 1 }))], + ['글자 크기 4', top(text({ size: 4 }))], + ['글자 크기 30', top(text({ size: 30 }))], + ['꾸미기 크기 8', top(deco({ size: 8 }))], + ['꾸미기 크기 50', top(deco({ size: 50 }))], + ['효과 강도 0', top(text({ effect: { type: 'none', intensity: 0 } }))], + [ + '효과 강도 100', + top(text({ effect: { type: 'none', intensity: 100 } })), + ], + ['글자 30자(이모지 코드 포인트)', top(text({ text: '🎂'.repeat(30) }))], + ['카탈로그에 없는 임의 글자색', top(text({ color: '#a1B2c3' }))], + ['decoId·text·color를 null로 보냄', top(text({ decoId: null }))], + ['꾸미기의 text·color null', top(deco({ text: null, color: null }))], + ...THREE_D_SHEET_COLORS.map((c): [string, ThreeDDesignSource] => [ + `시트 색 ${c.key}`, + design({}, { sheetColor: c.key }), + ]), + ...THREE_D_EFFECTS.map((e): [string, ThreeDDesignSource] => [ + `효과 ${e.key}`, + top(deco({ effect: { type: e.key, intensity: 50 } })), + ]), + ...THREE_D_DECOS.map((d): [string, ThreeDDesignSource] => [ + `꾸미기 ${d.key}`, + top(deco({ decoId: d.key })), + ]), + ])('통과: %s', (_label, input) => { + expect(() => validateThreeDDesign(input, SELECTED)).not.toThrow(); + }); + + it.each<[string, ThreeDDesignSource, string]>([ + [ + '시트 색이 카탈로그 밖', + design({}, { sheetColor: 'black' }), + 'basic.sheetColor', + ], + ['x < 0', top(text({ x: -0.01 })), 'top[0].x'], + ['x > 1', top(text({ x: 1.01 })), 'top[0].x'], + ['x NaN', top(deco({ x: Number.NaN })), 'top[0].x'], + ['y < 0', top(text({ y: -0.01 })), 'top[0].y'], + ['y 무한대', top(deco({ y: Number.POSITIVE_INFINITY })), 'top[0].y'], + ['옆면 y > 1', design({ side: [deco({ y: 1.5 })] }), 'side[0].y'], + ['글자 크기 3.99', top(text({ size: 3.99 })), 'top[0].size'], + ['글자 크기 30.01', top(text({ size: 30.01 })), 'top[0].size'], + ['꾸미기 크기 7.99', top(deco({ size: 7.99 })), 'top[0].size'], + ['꾸미기 크기 50.01', top(deco({ size: 50.01 })), 'top[0].size'], + ['꾸미기 크기 NaN', top(deco({ size: Number.NaN })), 'top[0].size'], + [ + '효과 종류가 카탈로그 밖', + top(text({ effect: { type: 'blur', intensity: 50 } })), + 'top[0].effect.type', + ], + [ + '효과 강도 -1', + top(text({ effect: { type: 'none', intensity: -1 } })), + 'top[0].effect.intensity', + ], + [ + '효과 강도 101', + top(text({ effect: { type: 'none', intensity: 101 } })), + 'top[0].effect.intensity', + ], + [ + '효과 강도 소수', + top(deco({ effect: { type: 'soft', intensity: 50.5 } })), + 'top[0].effect.intensity', + ], + ['빈 글자', top(text({ text: '' })), 'top[0].text'], + ['공백·줄바꿈뿐인 글자', top(text({ text: ' \r\n ' })), 'top[0].text'], + ['글자 없음', top(text({ text: null })), 'top[0].text'], + ['글자 31자', top(text({ text: '가'.repeat(31) })), 'top[0].text'], + ['글자색 없음', top(text({ color: null })), 'top[0].color'], + ['글자색 이름', top(text({ color: 'red' })), 'top[0].color'], + ['글자색 5자리', top(text({ color: '#12345' })), 'top[0].color'], + ['글자색 16진수 아님', top(text({ color: '#GGGGGG' })), 'top[0].color'], + ['글자에 decoId', top(text({ decoId: 'number-1' })), 'top[0].decoId'], + [ + '꾸미기 decoId 카탈로그 밖', + top(deco({ decoId: 'number-8' })), + 'top[0].decoId', + ], + ['꾸미기 decoId 없음', top(deco({ decoId: null })), 'top[0].decoId'], + ['꾸미기에 글자', top(deco({ text: '1' })), 'top[0].text'], + ['꾸미기에 글자색', top(deco({ color: '#000000' })), 'top[0].color'], + [ + '모르는 종류', + top({ ...deco(), kind: 'IMAGE' as 'DECO' }), + 'top[0].kind', + ], + [ + '두 번째 항목', + design({ side: [deco(), deco({ size: 51 })] }), + 'side[1].size', + ], + ])('CUSTOM_3D_DESIGN_INVALID: %s', (_label, input, field) => { + const run = () => validateThreeDDesign(input, SELECTED); + expect(run).toThrowDomain('CUSTOM_3D_DESIGN_INVALID'); + expect(run).toThrow(`(${field})`); + }); + }); + + it('검사 순서: 버전 → 옵션 → 개수 → 값', () => { + const broken = design( + { schemaVersion: 2, top: times(11, () => text({ x: 2 })) }, + { shape: 'star' }, + ); + expect(() => validateThreeDDesign(broken, SELECTED)).toThrowDomain( + 'CUSTOM_3D_SCHEMA_UNSUPPORTED', + ); + expect(() => + validateThreeDDesign({ ...broken, schemaVersion: 1 }, SELECTED), + ).toThrowDomain('CUSTOM_3D_OPTIONS_CHANGED'); + expect(() => + validateThreeDDesign( + { ...broken, schemaVersion: 1, basic: design().basic }, + SELECTED, + ), + ).toThrowDomain('CUSTOM_3D_ITEM_LIMIT_EXCEEDED'); + }); +}); diff --git a/src/features/product/services/three-d-design.helper.ts b/src/features/product/services/three-d-design.helper.ts new file mode 100644 index 00000000..c856d7bd --- /dev/null +++ b/src/features/product/services/three-d-design.helper.ts @@ -0,0 +1,212 @@ +import { DomainException } from '@/common/errors/error-catalog'; +import { + findThreeDChoice, + THREE_D_DECOS, + THREE_D_DESIGN_SCHEMA_VERSION, + THREE_D_EFFECTS, + THREE_D_LIMITS, + THREE_D_SHEET_COLORS, + type ThreeDOptionCategory, +} from '@/features/product/constants/custom-3d-catalog.constants'; + +export type ThreeDItemKind = 'TEXT' | 'DECO'; + +/** + * 주문 입력의 3D 디자인. order가 product를 import하므로 order DTO 타입을 여기서 import하면 순환이다 — + * 구조 타입으로 받고 order DTO가 이 구조를 만족한다. + */ +export interface ThreeDDesignItemSource { + kind: ThreeDItemKind; + x: number; + y: number; + size: number; + effect: { type: string; intensity: number }; + text?: string | null; + color?: string | null; + decoId?: string | null; +} + +export interface ThreeDDesignSource { + schemaVersion: number; + basic: { + shape: string; + size: string; + design?: string | null; + flavor?: string | null; + sheetColor: string; + }; + top: readonly ThreeDDesignItemSource[]; + side: readonly ThreeDDesignItemSource[]; +} + +interface ThreeDDesignItemBase { + x: number; + y: number; + size: number; + effect: { type: string; intensity: number }; +} + +export type ThreeDDesignItemV1 = + | (ThreeDDesignItemBase & { kind: 'TEXT'; text: string; color: string }) + | (ThreeDDesignItemBase & { kind: 'DECO'; decoId: string }); + +/** 주문에 저장하는 디자인 JSON v1. 배열 순서가 그리는 순서다. */ +export interface ThreeDDesignV1 { + schemaVersion: 1; + basic: { + shape: string; + size: string; + design: string | null; + flavor: string | null; + sheetColor: string; + }; + top: ThreeDDesignItemV1[]; + side: ThreeDDesignItemV1[]; +} + +const HEX_COLOR = /^#[0-9A-Fa-f]{6}$/; +const selectableKeys = ( + entries: readonly { key: string; selectable: boolean }[], +) => new Set(entries.filter((e) => e.selectable).map((e) => e.key)); +const SHEET_COLOR_KEYS = selectableKeys(THREE_D_SHEET_COLORS); +const EFFECT_KEYS = selectableKeys(THREE_D_EFFECTS); +const DECO_KEYS = selectableKeys(THREE_D_DECOS); + +const invalid = (field: string): never => { + throw new DomainException('CUSTOM_3D_DESIGN_INVALID', { field }); +}; + +/** 모양·크기는 고른 옵션의 값과 같아야 하고, 디자인·맛은 고른 항목이 없으면 null이어야 한다. */ +function matchBasic( + basic: ThreeDDesignSource['basic'], + selectedThreeDKeys: readonly (string | null)[], +): ThreeDDesignV1['basic'] { + const selected = new Map(); + for (const key of selectedThreeDKeys) { + const choice = findThreeDChoice(key); + if (!choice) continue; + if (selected.has(choice.category)) { + throw new DomainException('CUSTOM_3D_OPTIONS_CHANGED'); + } + selected.set(choice.category, choice.value); + } + const result = { + shape: basic.shape, + size: basic.size, + design: basic.design ?? null, + flavor: basic.flavor ?? null, + sheetColor: basic.sheetColor, + }; + if ( + result.shape !== selected.get('SHAPE') || + result.size !== selected.get('SIZE') || + result.design !== (selected.get('DESIGN') ?? null) || + result.flavor !== (selected.get('FLAVOR') ?? null) + ) { + throw new DomainException('CUSTOM_3D_OPTIONS_CHANGED'); + } + return result; +} + +function assertFaceLimits(items: readonly ThreeDDesignItemSource[]): void { + const count = (kind: ThreeDItemKind) => + items.filter((item) => item.kind === kind).length; + if (count('TEXT') > THREE_D_LIMITS.maxTextsPerFace) { + throw new DomainException('CUSTOM_3D_ITEM_LIMIT_EXCEEDED', { + max: THREE_D_LIMITS.maxTextsPerFace, + }); + } + if (count('DECO') > THREE_D_LIMITS.maxDecosPerFace) { + throw new DomainException('CUSTOM_3D_ITEM_LIMIT_EXCEEDED', { + max: THREE_D_LIMITS.maxDecosPerFace, + }); + } +} + +const inRange = (value: number, min: number, max: number) => + Number.isFinite(value) && value >= min && value <= max; + +function toItem( + item: ThreeDDesignItemSource, + field: string, +): ThreeDDesignItemV1 { + if (!inRange(item.x, 0, 1)) invalid(`${field}.x`); + if (!inRange(item.y, 0, 1)) invalid(`${field}.y`); + if (!EFFECT_KEYS.has(item.effect.type)) invalid(`${field}.effect.type`); + const { intensity } = item.effect; + if ( + !Number.isInteger(intensity) || + !inRange( + intensity, + THREE_D_LIMITS.effectIntensityMin, + THREE_D_LIMITS.effectIntensityMax, + ) + ) { + invalid(`${field}.effect.intensity`); + } + const base = { + x: item.x, + y: item.y, + size: item.size, + effect: { type: item.effect.type, intensity }, + }; + + if (item.kind === 'TEXT') { + if ( + !inRange( + item.size, + THREE_D_LIMITS.textSizeMin, + THREE_D_LIMITS.textSizeMax, + ) + ) { + invalid(`${field}.size`); + } + if (item.decoId != null) invalid(`${field}.decoId`); + const text = (item.text ?? '').replace(/\r\n?/g, '\n').trim(); + const length = [...text].length; + if (length < 1 || length > THREE_D_LIMITS.maxTextLength) { + invalid(`${field}.text`); + } + if (!HEX_COLOR.test(item.color ?? '')) invalid(`${field}.color`); + return { kind: 'TEXT', ...base, text, color: item.color!.toUpperCase() }; + } + if (item.kind === 'DECO') { + if ( + !inRange( + item.size, + THREE_D_LIMITS.decoSizeMin, + THREE_D_LIMITS.decoSizeMax, + ) + ) { + invalid(`${field}.size`); + } + if (item.text != null) invalid(`${field}.text`); + if (item.color != null) invalid(`${field}.color`); + if (!DECO_KEYS.has(item.decoId ?? '')) invalid(`${field}.decoId`); + return { kind: 'DECO', ...base, decoId: item.decoId! }; + } + return invalid(`${field}.kind`); +} + +/** + * 주문할 3D 디자인을 카탈로그·한도로 검증하고 저장할 정규형(v1)으로 돌려준다. + * selectedThreeDKeys는 구매자가 고른 옵션 항목의 three_d_key다(3D와 무관한 항목은 null). + */ +export function validateThreeDDesign( + design: ThreeDDesignSource, + selectedThreeDKeys: readonly (string | null)[], +): ThreeDDesignV1 { + if (design.schemaVersion !== THREE_D_DESIGN_SCHEMA_VERSION) { + throw new DomainException('CUSTOM_3D_SCHEMA_UNSUPPORTED'); + } + const basic = matchBasic(design.basic, selectedThreeDKeys); + assertFaceLimits(design.top); + assertFaceLimits(design.side); + if (!SHEET_COLOR_KEYS.has(basic.sheetColor)) invalid('basic.sheetColor'); + return { + schemaVersion: THREE_D_DESIGN_SCHEMA_VERSION, + basic, + top: design.top.map((item, i) => toItem(item, `top[${i}]`)), + side: design.side.map((item, i) => toItem(item, `side[${i}]`)), + }; +} From d93e55803eb3f7a64bd4a8dba467d482ef608284 Mon Sep 17 00:00:00 2001 From: chanwoo7 Date: Thu, 19 Nov 2026 02:52:49 +0900 Subject: [PATCH 26/54] =?UTF-8?q?test:=203D=20=EC=98=B5=EC=85=98=20?= =?UTF-8?q?=EC=B9=B4=ED=85=8C=EA=B3=A0=EB=A6=AC=20SDL=20=EB=8F=99=EA=B8=B0?= =?UTF-8?q?=ED=99=94=EC=99=80=20=ED=87=B4=EC=97=AD=20=EC=B9=B4=ED=83=88?= =?UTF-8?q?=EB=A1=9C=EA=B7=B8=20=ED=95=AD=EB=AA=A9=20=EA=B1=B0=EC=A0=88=20?= =?UTF-8?q?=ED=9A=8C=EA=B7=80=20=ED=85=8C=EC=8A=A4=ED=8A=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 판매자 상품·구매자 상품 상세·3D 카탈로그 응답은 TS 상수 THREE_D_OPTION_CATEGORIES 값을 SDL enum ThreeDOptionCategoryType으로 그대로 직렬화한다. TS에만 카테고리를 더하면 그 값이 든 응답 전체가 실패하는데 tsc·codegen은 둘을 묶지 못해, Prisma enum만 보던 enum-sdl-sync 검사에 이 쌍을 더한다. 또 3D 디자인 검증은 시트 색·효과·꾸미기를 선택 가능한 항목만 받는데, 지금 카탈로그가 전부 선택 가능이라 퇴역 판정을 지워도 표가 통과했다. 변경점 - enum-sdl-sync: ThreeDOptionCategory ↔ ThreeDOptionCategoryType 쌍 추가(기존 반증 it.each가 이 쌍에도 적용) - three-d-design.helper.spec: 카탈로그 상수를 격리 모듈로 바꿔 시트 색·효과·꾸미기를 하나씩 퇴역시키고 CUSTOM_3D_DESIGN_INVALID(어긋난 위치 포함)를 단언 테스트 - 추가 5건(enum 쌍 검사·반증 2, 퇴역 거절 3) - 반증: TS 상수에 카테고리를 더하면 enum 쌍 검사 1건이, 선택 가능 필터를 지우면 퇴역 거절 3건이 실패함을 확인 --- .../services/three-d-design.helper.spec.ts | 48 +++++++++++++++++++ src/test/enum-sdl-sync.spec.ts | 15 ++++-- 2 files changed, 59 insertions(+), 4 deletions(-) diff --git a/src/features/product/services/three-d-design.helper.spec.ts b/src/features/product/services/three-d-design.helper.spec.ts index 401adb59..05ba6298 100644 --- a/src/features/product/services/three-d-design.helper.spec.ts +++ b/src/features/product/services/three-d-design.helper.spec.ts @@ -1,3 +1,4 @@ +import type * as Catalog from '@/features/product/constants/custom-3d-catalog.constants'; import { THREE_D_DECOS, THREE_D_EFFECTS, @@ -306,6 +307,53 @@ describe('validateThreeDDesign', () => { }); }); + describe('퇴역 항목(selectable=false)', () => { + const CATALOG = '@/features/product/constants/custom-3d-catalog.constants'; + const retire = ( + list: readonly T[], + key: string, + ) => list.map((e) => (e.key === key ? { ...e, selectable: false } : e)); + + it.each<[string, Partial, string]>([ + [ + '시트 색', + { THREE_D_SHEET_COLORS: retire(THREE_D_SHEET_COLORS, 'white') }, + 'basic.sheetColor', + ], + [ + '효과', + { THREE_D_EFFECTS: retire(THREE_D_EFFECTS, 'soft') }, + 'top[1].effect.type', + ], + [ + '꾸미기', + { THREE_D_DECOS: retire(THREE_D_DECOS, 'number-1') }, + 'top[1].decoId', + ], + ])('%s: 퇴역한 값은 새 주문에서 거절한다', (_label, override, field) => { + let error: unknown; + jest.isolateModules(() => { + jest.doMock(CATALOG, () => ({ + ...jest.requireActual(CATALOG), + ...override, + })); + const isolated = jest.requireActual<{ + validateThreeDDesign: typeof validateThreeDDesign; + }>('@/features/product/services/three-d-design.helper'); + try { + isolated.validateThreeDDesign(design(), SELECTED); + } catch (e) { + error = e; + } + }); + // 격리 레지스트리의 DomainException은 클래스가 달라 toThrowDomain 대신 code를 본다 + expect(error).toMatchObject({ + code: 'CUSTOM_3D_DESIGN_INVALID', + message: expect.stringContaining(`(${field})`), + }); + }); + }); + it('검사 순서: 버전 → 옵션 → 개수 → 값', () => { const broken = design( { schemaVersion: 2, top: times(11, () => text({ x: 2 })) }, diff --git a/src/test/enum-sdl-sync.spec.ts b/src/test/enum-sdl-sync.spec.ts index be137a72..8625ec3d 100644 --- a/src/test/enum-sdl-sync.spec.ts +++ b/src/test/enum-sdl-sync.spec.ts @@ -3,6 +3,7 @@ import { join } from 'node:path'; import { Kind, parse, print, visit } from 'graphql'; +import { THREE_D_OPTION_CATEGORIES } from '@/features/product/constants/custom-3d-catalog.constants'; import { ConversationBodyFormat, CustomMode, @@ -13,8 +14,8 @@ import { } from '@/generated/prisma/client'; /** - * 응답에 그대로 실리는 Prisma enum은 SDL enum이 그 값을 모두 가져야 한다. 하나라도 빠지면 그 값이 든 - * 응답 전체가 직렬화 오류로 실패한다(예: 새 NotificationEvent가 든 myNotifications). tsc는 둘을 묶지 못한다. + * 응답에 그대로 실리는 Prisma enum·TS 상수 union은 SDL enum이 그 값을 모두 가져야 한다. 하나라도 빠지면 + * 그 값이 든 응답 전체가 직렬화 오류로 실패한다(예: 새 NotificationEvent가 든 myNotifications). tsc는 둘을 묶지 못한다. */ const PAIRS: Array< [label: string, prisma: string[], file: string, sdl: string] @@ -55,6 +56,12 @@ const PAIRS: Array< 'src/features/product/product.types.graphql', 'CustomTextAlignType', ], + [ + 'ThreeDOptionCategory', + [...THREE_D_OPTION_CATEGORIES], + 'src/features/product/product.types.graphql', + 'ThreeDOptionCategoryType', + ], ]; function sdlEnumValues(source: string, enumName: string): string[] { @@ -72,7 +79,7 @@ function missingInSdl(prisma: string[], sdl: string[]): string[] { const read = (file: string) => readFileSync(join(process.cwd(), file), 'utf8'); -describe('Prisma enum ⊆ SDL enum', () => { +describe('Prisma enum·TS 상수 ⊆ SDL enum', () => { describe('검사기 반증', () => { it.each(PAIRS)( '%s: SDL에서 값 하나를 지우면 그 값이 빠졌다고 잡는다', @@ -102,7 +109,7 @@ describe('Prisma enum ⊆ SDL enum', () => { }); it.each(PAIRS)( - '%s: Prisma 값이 SDL에 모두 있다', + '%s: 서버 값이 SDL에 모두 있다', (_label, prisma, file, sdl) => { expect(prisma.length).toBeGreaterThan(0); expect(missingInSdl(prisma, sdlEnumValues(read(file), sdl))).toEqual([]); From c2a87c0cc0666a19d27eeb375beab45ced8483b4 Mon Sep 17 00:00:00 2001 From: chanwoo7 Date: Thu, 19 Nov 2026 02:52:56 +0900 Subject: [PATCH 27/54] =?UTF-8?q?fix:=20=EC=B9=B4=ED=83=88=EB=A1=9C?= =?UTF-8?q?=EA=B7=B8=20=EC=97=85=EB=A1=9C=EB=93=9C=EA=B0=80=20=EC=9D=B4?= =?UTF-8?q?=EB=AF=B8=20=EC=9E=88=EB=8A=94=20=EA=B0=9D=EC=B2=B4=EB=A5=BC=20?= =?UTF-8?q?=EB=8D=AE=EC=96=B4=EC=93=B0=EC=A7=80=20=EC=95=8A=EA=B2=8C=20?= =?UTF-8?q?=EC=A1=B0=EA=B1=B4=EB=B6=80=20=EC=97=85=EB=A1=9C=EB=93=9C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 업로드 스크립트는 같은 경로에 다른 내용이 있으면 실패해야 하는데, 그 판정이 HeadObject 결과에만 기대고 있었다. HeadObject 403은 '없음'으로 읽으므로 GetObject 없이 PutObject만 가진 자격 증명이면 있는 객체도 덮어써지고, Head와 Put 사이 경합도 남는다. immutable 캐시와 과거 주문 모습이 어긋나는 사고라 서버 쪽에서 막는다. 변경점 - PutObject에 IfNoneMatch: '*'(이미 있으면 412로 실패). HeadObject는 같은 내용 건너뛰기 판정에만 쓴다 테스트 - scripts/catalog-upload.spec 18건 통과(S3 호출부는 사람이 운영 버킷에 돌리는 경로라 spec 대상 밖) --- scripts/catalog-upload.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/scripts/catalog-upload.ts b/scripts/catalog-upload.ts index 09dad9e6..a7d9697f 100644 --- a/scripts/catalog-upload.ts +++ b/scripts/catalog-upload.ts @@ -82,6 +82,7 @@ async function main(): Promise { Body: readFileSync(file.path), ContentType: file.contentType, CacheControl: 'public, max-age=31536000, immutable', + IfNoneMatch: '*', // 이미 있으면 412 — Head가 403으로 못 본 객체·동시 업로드도 덮어쓰지 않는다 }), ); process.stdout.write(` ${file.key}\n`); From 139e4ded189faadef3c2d81ad368a0ade122d039 Mon Sep 17 00:00:00 2001 From: chanwoo7 Date: Thu, 19 Nov 2026 04:27:52 +0900 Subject: [PATCH 28/54] =?UTF-8?q?test:=20roles-coverage=20=EA=B0=9C?= =?UTF-8?q?=EC=88=98=20=EC=9E=AC=EA=B3=84=EC=82=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit rebase 뒤 develop SDL 기준으로 seller·admin 루트 필드 수 갱신. --- src/test/roles-coverage.spec.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/test/roles-coverage.spec.ts b/src/test/roles-coverage.spec.ts index acb3d2fc..f8839b3f 100644 --- a/src/test/roles-coverage.spec.ts +++ b/src/test/roles-coverage.spec.ts @@ -13,7 +13,7 @@ describe('접두 루트 필드 인가 커버리지', () => { const handlerAuth = collectHandlerAuth(collectFeatureResolverClasses()); describe.each([ - ['seller', 'SELLER', 58], + ['seller', 'SELLER', 59], ['admin', 'ADMIN', 67], ] as const)('%s 접두 → @Roles(%s)', (prefix, role, count) => { const fields = collectRootFieldsWithPrefix(prefix); From 12217b847d8f7430971cdec02226d9679310133a Mon Sep 17 00:00:00 2001 From: chanwoo7 Date: Thu, 19 Nov 2026 04:08:14 +0900 Subject: [PATCH 29/54] =?UTF-8?q?feat:=20=EC=B7=A8=EC=86=8C=20=EC=82=AC?= =?UTF-8?q?=EC=9C=A0=C2=B7=EC=A3=BC=EC=B2=B4=C2=B7=EC=82=AC=EC=A0=95?= =?UTF-8?q?=EA=B3=BC=20=ED=99=98=EB=B6=88=20=EC=83=9D=EC=84=B1=C2=B7?= =?UTF-8?q?=EC=A0=95=EC=82=B0=20=ED=99=95=EC=A0=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ① 무엇·왜 - 주문 취소를 주체(구매자·판매자·관리자·시스템)별 사유와 상태 × 사정 × 환불액 규칙으로 바꾼다. 입금 대기는 환불 없이 결제를 닫고, 접수는 결제액 전액, 확정·제작 완료는 사정을 골라 판매자 사정이면 전액, 구매자 사정이면 취소자가 입력한 금액(0~결제액)을 돌려준다. - 돌려줄 돈이 생기면 환불 기록(계좌 입력 대기)과 구매자 계좌 요청 알림을, 구매자 사정 부분 환불의 남는 금액과 판매자 픽업 완료에는 정산 확정(수수료 원 미만 버림)을 같은 tx에 남긴다. 돈이 있는 주문은 결제가 확인된 주문뿐이라 결제 도입 전 주문은 결제액 0으로 본다. - 운영 판매자가 없어 레거시 취소 경로를 바로 정리한다: 판매자 상태 변경의 CANCELED를 막고 sellerCancelOrder로만, 관리자 취소는 사유 필수. ② 변경점 - OrderCancelPolicy(순수): 주체 → 상태 → 사유 표(기본 거절), 환불 규칙(NO_REFUND·FULL_REFUND·BY_FAULT), decide가 ORDER_NOT_CANCELLABLE → CANCEL_REASON_NOT_ALLOWED → CANCEL_FAULT_REQUIRED → REFUND_AMOUNT_REQUIRED·REFUND_AMOUNT_OUT_OF_RANGE 순으로 거절 - OrderTransitionRepository.cancel·cancelLocked: 주문 → 결제 FOR UPDATE 뒤 잠금 읽기 재료(상태·확인된 결제액)로 판정, 범위(구매자 본인·판매자 접수된 자기 매장·전체), 주문 CANCELED, 결제는 PENDING만 CANCELED, 이력(주체·사유·사정·환불액·메모), Refund(CANCEL, cancel_order_id), 구매자 사정 정산 확정, outbox order.status_changed + refund.requested, 감사(처리자 있을 때만, 입금 전 주문은 매장 id 없음) - order-settlement-finalizer.helper: lockPayment·confirmedPaidAmount·settlementAmounts·finalizeSettlementLocked, 판매자 PICKED_UP이 정산 확정 - API: cancelMyOrder, sellerCancelOrder, adminCancelOrder(reason 필수·note 선택·fault·refundAmount), 커밋 뒤 판매자 구독(OrderEventsService.publishSellerStatusChanged) - 출력: OrderStatusHistory.actorType·cancelReason·cancelFault·refundAmount, OrderCancellation(구매자·판매자·관리자 상세), MyOrderDetail.canCancel, AdminOrderDetail.refunds·cancelOptions, enum 5종 - 이벤트: order.status_changed에 actorType·cancelReason·refundAmount·pickupAt(옛 이벤트는 null), refund.requested 신설 - 알림: 구매자 취소 알림에 사유 라벨, 미입금 취소는 ORDER_PAYMENT_EXPIRED, 환불 생성은 REFUND_ACCOUNT_REQUESTED, 구매자 본인 취소는 상태 알림 없음. 판매자 ORDER_CANCELED 푸시는 입금 전 주문이 아니고 주체가 구매자·관리자·시스템일 때만 - 레거시: 판매자 전이 표의 CANCELED, cancelOrderByAdmin, '[관리자] ' 접두·order-admin.constants, requiresCancellationNote, CANCELLATION_NOTE_REQUIRED 삭제 - 에러 4종, enum-sdl-sync 5쌍, roles-coverage seller 60, createOrder 팩토리 commission_rate_bps ③ 테스트 - 정책 전수: 주체 4 × 상태 7 × 사유 8(224, 허용 47), 상태 4 × 사정 3 × 금액 6(72), 결제액 0, 환불 규칙 - 수수료 버림 경계(0.9999·1.0002·INT UNSIGNED 상한), 확인된 결제액 3경우 - cancelLocked: 입금 대기 결제 닫힘·접수 전액 환불·확정 뒤 사정 4경우(정산 확정 포함)·판정 재료와 롤백·범위 밖 4경우·감사 규칙·동시 취소 1건, 반증: cancel_order_id 두 번째 행 P2002·입금 반환 NULL 공존 - 서비스: 관리자·판매자·구매자 취소 경로·거절 표·알림·구독·cancelOptions 7상태·canCancel 7상태·판매자 픽업 완료 정산 확정 - 이벤트 파서 반증 표, 구매자 알림 문구, 판매자 푸시 필터 245조합 전수, 소비자 전송·비대상·재전달 멱등 --- src/common/errors/error-catalog.spec.ts | 1 + src/common/errors/error-catalog.ts | 21 +- .../constants/notification-messages.ts | 19 +- .../notification/notification.types.graphql | 2 +- .../notification-outbox.consumer.spec.ts | 83 ++++ .../services/notification-outbox.consumer.ts | 25 +- .../notification-payloads.helper.spec.ts | 133 ++++-- .../services/notification-payloads.helper.ts | 64 ++- .../seller-push-messages.helper.spec.ts | 79 ++++ .../services/seller-push-messages.helper.ts | 40 +- .../seller-push-outbox.consumer.spec.ts | 58 ++- .../services/seller-push-outbox.consumer.ts | 34 +- .../order/constants/order-admin.constants.ts | 9 - .../order/constants/order-cancel-reasons.ts | 13 + .../dto/inputs/admin-cancel-order.input.ts | 21 +- .../order/dto/inputs/cancel-my-order.input.ts | 10 + .../dto/inputs/seller-cancel-order.input.ts | 25 ++ .../events/order-status-changed.event.spec.ts | 106 +++++ .../events/order-status-changed.event.ts | 52 ++- .../events/refund-requested.event.spec.ts | 81 ++++ .../order/events/refund-requested.event.ts | 91 +++++ src/features/order/index.ts | 9 + src/features/order/order-admin.graphql | 62 ++- src/features/order/order-my.graphql | 26 ++ src/features/order/order-seller.graphql | 41 +- src/features/order/order.module.ts | 9 +- src/features/order/order.types.graphql | 132 +++++- .../policies/order-cancel.policy.spec.ts | 213 ++++++++++ .../order/policies/order-cancel.policy.ts | 138 +++++++ .../order-status-transition.policy.spec.ts | 19 +- .../order-status-transition.policy.ts | 16 +- .../order-settlement-finalizer.helper.spec.ts | 39 ++ .../order-settlement-finalizer.helper.ts | 72 ++++ .../order-transition.repository.spec.ts | 362 ++++++++++++++++- .../order-transition.repository.ts | 191 ++++++++- .../repositories/order.repository.spec.ts | 38 +- .../order/repositories/order.repository.ts | 118 ++---- .../resolvers/order-admin.resolver.spec.ts | 10 + .../resolvers/order-my-mutation.resolver.ts | 9 + .../order/resolvers/order-my.resolver.spec.ts | 37 ++ .../order-seller-mutation.resolver.ts | 9 + .../resolvers/order-seller.resolver.spec.ts | 19 + .../services/order-admin-mappers.helper.ts | 7 + .../services/order-admin.service.spec.ts | 381 ++++++++++++++---- .../order/services/order-admin.service.ts | 111 +++-- .../order/services/order-events.service.ts | 16 + .../order/services/order-my.service.spec.ts | 189 ++++++++- .../order/services/order-my.service.ts | 47 ++- .../order-output-mappers.helper.spec.ts | 192 ++++++++- .../services/order-output-mappers.helper.ts | 69 +++- .../services/order-seller.service.spec.ts | 331 +++++++++++++-- .../order/services/order-seller.service.ts | 53 ++- .../order/types/order-admin-output.type.ts | 19 +- .../order/types/order-my-output.type.ts | 3 + src/features/order/types/order-output.type.ts | 39 +- .../order/types/order-seller-output.type.ts | 2 + src/test/enum-sdl-sync.spec.ts | 35 ++ src/test/factories/order.factory.ts | 4 + src/test/roles-coverage.spec.ts | 2 +- 59 files changed, 3595 insertions(+), 441 deletions(-) delete mode 100644 src/features/order/constants/order-admin.constants.ts create mode 100644 src/features/order/constants/order-cancel-reasons.ts create mode 100644 src/features/order/dto/inputs/cancel-my-order.input.ts create mode 100644 src/features/order/dto/inputs/seller-cancel-order.input.ts create mode 100644 src/features/order/events/order-status-changed.event.spec.ts create mode 100644 src/features/order/events/refund-requested.event.spec.ts create mode 100644 src/features/order/events/refund-requested.event.ts create mode 100644 src/features/order/policies/order-cancel.policy.spec.ts create mode 100644 src/features/order/policies/order-cancel.policy.ts create mode 100644 src/features/order/repositories/order-settlement-finalizer.helper.spec.ts create mode 100644 src/features/order/repositories/order-settlement-finalizer.helper.ts diff --git a/src/common/errors/error-catalog.spec.ts b/src/common/errors/error-catalog.spec.ts index 5341e7d9..21749898 100644 --- a/src/common/errors/error-catalog.spec.ts +++ b/src/common/errors/error-catalog.spec.ts @@ -32,6 +32,7 @@ const RENDER_PARAMS: Partial< INVALID_PHONE_FORMAT: { example: '010-1234-5678' }, INVALID_LIMIT: { max: 50 }, FIELD_OUT_OF_RANGE: { field: 'capacity', min: 1, max: 100 }, + REFUND_AMOUNT_OUT_OF_RANGE: { max: '30,000' }, CUSTOM_TEXT_DEFAULT_TOO_LONG: { label: '이름', max: 20 }, CUSTOM_3D_ITEM_LIMIT_EXCEEDED: { max: 10 }, CUSTOM_3D_DESIGN_INVALID: { field: 'top[0].size' }, diff --git a/src/common/errors/error-catalog.ts b/src/common/errors/error-catalog.ts index a23172ce..fa18a216 100644 --- a/src/common/errors/error-catalog.ts +++ b/src/common/errors/error-catalog.ts @@ -323,6 +323,23 @@ export const ERROR_CATALOG = { status: HttpStatus.BAD_REQUEST, message: '현재 상태에서는 주문을 취소할 수 없습니다.', }, + CANCEL_REASON_NOT_ALLOWED: { + status: HttpStatus.BAD_REQUEST, + message: '이 주문에는 선택할 수 없는 취소 사유입니다.', + }, + CANCEL_FAULT_REQUIRED: { + status: HttpStatus.BAD_REQUEST, + message: + '확정된 주문은 판매자 사정인지 구매자 사정인지 선택해야 취소할 수 있습니다.', + }, + REFUND_AMOUNT_REQUIRED: { + status: HttpStatus.BAD_REQUEST, + message: '구매자 사정으로 취소하려면 환불 금액을 입력해 주세요.', + }, + REFUND_AMOUNT_OUT_OF_RANGE: { + status: HttpStatus.BAD_REQUEST, + message: ({ max }) => `환불 금액은 0원 이상 ${max}원 이하로 입력해 주세요.`, + }, DUPLICATE_OPTION_ITEM: { status: HttpStatus.BAD_REQUEST, message: '중복된 옵션 선택입니다.', @@ -597,10 +614,6 @@ export const ERROR_CATALOG = { status: HttpStatus.BAD_REQUEST, message: '본문 형식이 올바르지 않습니다.', }, - CANCELLATION_NOTE_REQUIRED: { - status: HttpStatus.BAD_REQUEST, - message: '취소 사유가 필요합니다.', - }, // ── 관리자 ADMIN_ONLY: { status: HttpStatus.FORBIDDEN, diff --git a/src/features/notification/constants/notification-messages.ts b/src/features/notification/constants/notification-messages.ts index 8f785bf3..92ff1513 100644 --- a/src/features/notification/constants/notification-messages.ts +++ b/src/features/notification/constants/notification-messages.ts @@ -1,6 +1,6 @@ import { OrderStatus } from '@/generated/prisma/client'; -/** 매핑이 없는 상태는 알림을 만들지 않는다. */ +/** 매핑이 없는 상태는 알림을 만들지 않는다. 취소는 아래 문구로 따로 만든다. */ export const ORDER_STATUS_NOTIFICATION_TITLES: Partial< Record > = { @@ -8,8 +8,6 @@ export const ORDER_STATUS_NOTIFICATION_TITLES: Partial< [OrderStatus.CONFIRMED]: '주문확정', [OrderStatus.MADE]: '제작완료', [OrderStatus.PICKED_UP]: '픽업완료', - // 관리자 강제 취소 도입 시 판매자 취소와 함께 알리기로 확정 - [OrderStatus.CANCELED]: '주문취소', }; /** 주문번호 prefix는 식별 필요 가능성에 대비해 유지한다 — 표시 여부는 FE 판단. */ @@ -20,9 +18,22 @@ export const ORDER_STATUS_NOTIFICATION_BODIES: Partial< [OrderStatus.CONFIRMED]: '주문이 확정되었어요.', [OrderStatus.MADE]: '주문하신 케이크 제작이 완료되었어요.', [OrderStatus.PICKED_UP]: '케이크 픽업이 완료되었어요.', - [OrderStatus.CANCELED]: '주문이 취소되었어요.', }; +/** 취소는 사유 라벨을 덧붙인다(판매자·운영자·자동 미확정 공통). */ +export const ORDER_CANCELED_NOTIFICATION = { + title: '주문취소', + body: '주문이 취소되었어요.', +} as const; + +/** 미입금(PAYMENT_NOT_RECEIVED) 취소는 일반 취소 문구 대신 이 문구로 알린다. */ +export const ORDER_PAYMENT_EXPIRED_NOTIFICATION = { + title: '주문취소', + body: '입금이 확인되지 않아 주문이 취소되었어요.', +} as const; + +export const REFUND_ACCOUNT_REQUESTED_TITLE = '환불계좌입력'; + export const REVIEW_LIKED_NOTIFICATION = { title: '리뷰 좋아요', body: '다른 사람이 내가 남긴 리뷰를 좋아했어요.', diff --git a/src/features/notification/notification.types.graphql b/src/features/notification/notification.types.graphql index b4c8a6a9..8a0d6922 100644 --- a/src/features/notification/notification.types.graphql +++ b/src/features/notification/notification.types.graphql @@ -41,7 +41,7 @@ enum NotificationEvent { """ ORDER_PICKED_UP """ - 주문이 취소됐다(판매자 또는 운영자). type은 ORDER_STATUS. + 주문이 취소됐다(판매자·운영자·자동 미확정). 본문 끝에 사유 라벨이 붙고, 구매자 본인 취소는 알림이 없다. type은 ORDER_STATUS. """ ORDER_CANCELED """ diff --git a/src/features/notification/services/notification-outbox.consumer.spec.ts b/src/features/notification/services/notification-outbox.consumer.spec.ts index a388cd35..55c1a316 100644 --- a/src/features/notification/services/notification-outbox.consumer.spec.ts +++ b/src/features/notification/services/notification-outbox.consumer.spec.ts @@ -158,6 +158,89 @@ describe('NotificationOutboxConsumer (real DB)', () => { }); }); + describe('취소·환불', () => { + it('구매자 본인 취소는 알림 없이 소비되고, 운영자 취소는 사유 라벨을 붙여 알린다', async () => { + const buyer = await createAccount(prisma, { account_type: 'USER' }); + const order = await createOrder(prisma, { account_id: buyer.id }); + const base = { + orderId: order.id.toString(), + orderNumber: 'ORD-3', + buyerAccountId: buyer.id.toString(), + fromStatus: 'SUBMITTED', + toStatus: 'CANCELED', + storeId: null, + storeName: null, + productId: null, + productName: null, + cancelReason: 'BUYER_REQUEST', + refundAmount: 10_000, + pickupAt: '2026-09-20T03:00:00.000Z', + }; + + await consumer.handle( + event('order.status_changed', { ...base, actorType: 'BUYER' }), + ); + expect(await prisma.notification.count()).toBe(0); + + await consumer.handle( + event( + 'order.status_changed', + { ...base, actorType: 'ADMIN', cancelReason: 'OUT_OF_MATERIALS' }, + '22222222-2222-4222-8222-222222222222', + ), + ); + await expect( + prisma.notification.findFirstOrThrow(), + ).resolves.toMatchObject({ + event: 'ORDER_CANCELED', + body: 'ORD-3 주문이 취소되었어요. 사유: 재료 소진', + }); + }); + + it('refund.requested는 구매자에게 환불 계좌 입력 요청을 만들고, 재전달은 중복을 만들지 않는다', async () => { + const buyer = await createAccount(prisma, { account_type: 'USER' }); + const order = await createOrder(prisma, { account_id: buyer.id }); + const item = await createOrderItem(prisma, { order_id: order.id }); + const requested = event('refund.requested', { + refundId: '5', + orderId: order.id.toString(), + orderNumber: 'ORD-4', + buyerAccountId: buyer.id.toString(), + kind: 'CANCEL', + amount: 12_500, + storeId: item.store_id.toString(), + storeName: '케이크샵', + productId: item.product_id.toString(), + productName: '레터링 케이크', + }); + + await consumer.handle(requested); + await consumer.handle(requested); + + const rows = await prisma.notification.findMany(); + expect(rows).toHaveLength(1); + expect(rows[0]).toMatchObject({ + account_id: buyer.id, + type: 'ORDER_STATUS', + event: 'REFUND_ACCOUNT_REQUESTED', + title: '환불계좌입력', + body: 'ORD-4 12,500원을 돌려받을 계좌를 입력해 주세요.', + order_id: order.id, + store_id: item.store_id, + product_id: item.product_id, + order_number: 'ORD-4', + store_name: '케이크샵', + created_at: OCCURRED_AT, + }); + }); + + it('반증: 형식이 어긋난 refund.requested는 던진다', async () => { + await expect( + consumer.handle(event('refund.requested', { refundId: 5 })), + ).rejects.toThrow('payload 형식 오류'); + }); + }); + it('review.liked는 작성자에게 좋아요 알림을 만든다', async () => { const review = await createReview(prisma); await consumer.handle( diff --git a/src/features/notification/services/notification-outbox.consumer.ts b/src/features/notification/services/notification-outbox.consumer.ts index 7a114aae..fdf8cfc2 100644 --- a/src/features/notification/services/notification-outbox.consumer.ts +++ b/src/features/notification/services/notification-outbox.consumer.ts @@ -14,11 +14,14 @@ import { } from '@/features/notification/repositories/notification.repository'; import { buildOrderStatusNotification, + buildRefundAccountRequestedNotification, buildReviewLikedNotification, } from '@/features/notification/services/notification-payloads.helper'; import { ORDER_STATUS_CHANGED, parseOrderStatusChangedPayload, + parseRefundRequestedPayload, + REFUND_REQUESTED, } from '@/features/order'; import { type OutboxConsumer, @@ -34,6 +37,7 @@ import { parseReviewLikedPayload, REVIEW_LIKED } from '@/features/review'; @Injectable() @SubscribeOutbox( ORDER_STATUS_CHANGED, + REFUND_REQUESTED, REVIEW_LIKED, NOTIFICATION_BROADCAST_REQUESTED, ) @@ -50,6 +54,8 @@ export class NotificationOutboxConsumer implements OutboxConsumer { switch (event.eventType) { case ORDER_STATUS_CHANGED: return this.onOrderStatusChanged(event); + case REFUND_REQUESTED: + return this.onRefundRequested(event); case REVIEW_LIKED: return this.onReviewLiked(event); case NOTIFICATION_BROADCAST_REQUESTED: @@ -62,7 +68,7 @@ export class NotificationOutboxConsumer implements OutboxConsumer { private async onOrderStatusChanged(event: OutboxEvent): Promise { const p = parseOrderStatusChangedPayload(event.payload); // 알림 대상이 아닌 전이는 payload가 null — 이벤트는 정상 소비된다 - const payload = buildOrderStatusNotification(p.orderNumber, p.toStatus); + const payload = buildOrderStatusNotification(p); if (!payload) return; await this.repo.createFromEvent(event.eventId, [ { @@ -79,6 +85,23 @@ export class NotificationOutboxConsumer implements OutboxConsumer { ]); } + private async onRefundRequested(event: OutboxEvent): Promise { + const p = parseRefundRequestedPayload(event.payload); + await this.repo.createFromEvent(event.eventId, [ + { + account_id: parseId(p.buyerAccountId), + ...buildRefundAccountRequestedNotification(p.orderNumber, p.amount), + order_id: parseId(p.orderId), + store_id: p.storeId === null ? null : parseId(p.storeId), + product_id: p.productId === null ? null : parseId(p.productId), + order_number: p.orderNumber, + store_name: p.storeName, + product_name: p.productName, + created_at: event.occurredAt, + }, + ]); + } + private async onReviewLiked(event: OutboxEvent): Promise { const p = parseReviewLikedPayload(event.payload); await this.repo.createFromEvent(event.eventId, [ diff --git a/src/features/notification/services/notification-payloads.helper.spec.ts b/src/features/notification/services/notification-payloads.helper.spec.ts index f92669f3..c419316c 100644 --- a/src/features/notification/services/notification-payloads.helper.spec.ts +++ b/src/features/notification/services/notification-payloads.helper.spec.ts @@ -1,69 +1,126 @@ import { buildOrderStatusNotification, + buildRefundAccountRequestedNotification, buildReviewLikedNotification, } from '@/features/notification/services/notification-payloads.helper'; +import { ORDER_CANCEL_REASON_LABELS } from '@/features/order'; import { NotificationEvent, NotificationType, - OrderStatus, + OrderCancelReason, + type OrderActor, + type OrderStatus, } from '@/generated/prisma/client'; describe('notification-payloads.helper', () => { describe('buildOrderStatusNotification', () => { - it('CONFIRMED는 주문번호가 붙은 확정 알림 payload를 만든다', () => { - expect( - buildOrderStatusNotification('ORD-1', OrderStatus.CONFIRMED), - ).toEqual({ - type: NotificationType.ORDER_STATUS, - event: NotificationEvent.ORDER_CONFIRMED, - title: '주문확정', - body: 'ORD-1 주문이 확정되었어요.', + const status = ( + toStatus: OrderStatus, + overrides: Partial<{ + actorType: OrderActor | null; + cancelReason: OrderCancelReason | null; + }> = {}, + ) => + buildOrderStatusNotification({ + orderNumber: 'ORD-1', + toStatus, + actorType: 'SELLER', + cancelReason: null, + ...overrides, }); - }); - it('MADE·PICKED_UP도 상태별 이벤트·문구로 매핑된다', () => { - expect(buildOrderStatusNotification('ORD-2', OrderStatus.MADE)).toEqual({ + it.each([ + [ + 'SUBMITTED', + 'ORDER_PAYMENT_CONFIRMED', + '입금확인', + '입금이 확인되어 주문이 접수되었어요.', + ], + ['CONFIRMED', 'ORDER_CONFIRMED', '주문확정', '주문이 확정되었어요.'], + [ + 'MADE', + 'ORDER_MADE', + '제작완료', + '주문하신 케이크 제작이 완료되었어요.', + ], + [ + 'PICKED_UP', + 'ORDER_PICKED_UP', + '픽업완료', + '케이크 픽업이 완료되었어요.', + ], + ] as const)('%s는 %s(주문번호 접두)', (toStatus, event, title, body) => { + expect(status(toStatus)).toEqual({ type: NotificationType.ORDER_STATUS, - event: NotificationEvent.ORDER_MADE, - title: '제작완료', - body: 'ORD-2 주문하신 케이크 제작이 완료되었어요.', - }); - expect( - buildOrderStatusNotification('ORD-3', OrderStatus.PICKED_UP), - ).toEqual({ - type: NotificationType.ORDER_STATUS, - event: NotificationEvent.ORDER_PICKED_UP, - title: '픽업완료', - body: 'ORD-3 케이크 픽업이 완료되었어요.', + event, + title, + body: `ORD-1 ${body}`, }); }); - it('CANCELED는 취소 이벤트·문구로 매핑된다(판매자·운영자 취소 공통)', () => { - expect( - buildOrderStatusNotification('ORD-4', OrderStatus.CANCELED), - ).toEqual({ + it.each(['PENDING_PAYMENT', 'NO_SHOW'] as const)( + '매핑이 없는 상태(%s)는 null', + (toStatus) => { + expect(status(toStatus)).toBeNull(); + }, + ); + + it.each( + Object.values(OrderCancelReason).filter( + (r) => r !== 'PAYMENT_NOT_RECEIVED', + ), + )('취소(%s)는 사유 라벨을 붙인 ORDER_CANCELED', (cancelReason) => { + expect(status('CANCELED', { actorType: 'ADMIN', cancelReason })).toEqual({ type: NotificationType.ORDER_STATUS, event: NotificationEvent.ORDER_CANCELED, title: '주문취소', - body: 'ORD-4 주문이 취소되었어요.', + body: `ORD-1 주문이 취소되었어요. 사유: ${ORDER_CANCEL_REASON_LABELS[cancelReason]}`, }); }); - it('SUBMITTED(입금 확인으로만 도달)는 입금 확인 이벤트·문구로 매핑된다', () => { - expect( - buildOrderStatusNotification('ORD-5', OrderStatus.SUBMITTED), - ).toEqual({ - type: NotificationType.ORDER_STATUS, - event: NotificationEvent.ORDER_PAYMENT_CONFIRMED, - title: '입금확인', - body: 'ORD-5 입금이 확인되어 주문이 접수되었어요.', + it.each(['ADMIN', 'SYSTEM'] as const)( + '미입금 취소(%s)는 ORDER_PAYMENT_EXPIRED', + (actorType) => { + expect( + status('CANCELED', { + actorType, + cancelReason: 'PAYMENT_NOT_RECEIVED', + }), + ).toEqual({ + type: NotificationType.ORDER_STATUS, + event: NotificationEvent.ORDER_PAYMENT_EXPIRED, + title: '주문취소', + body: 'ORD-1 입금이 확인되지 않아 주문이 취소되었어요.', + }); + }, + ); + + it('사유가 없는 옛 취소 이벤트는 사유 없이 ORDER_CANCELED', () => { + expect(status('CANCELED', { actorType: null })).toMatchObject({ + event: NotificationEvent.ORDER_CANCELED, + body: 'ORD-1 주문이 취소되었어요.', }); }); - it('알림 대상이 아닌 상태(PENDING_PAYMENT)는 null을 반환한다', () => { + it('구매자 본인 행위는 알림이 없다(입금 대기·접수 취소)', () => { expect( - buildOrderStatusNotification('ORD-6', OrderStatus.PENDING_PAYMENT), + status('CANCELED', { + actorType: 'BUYER', + cancelReason: 'BUYER_REQUEST', + }), ).toBeNull(); + expect(status('PENDING_PAYMENT', { actorType: 'BUYER' })).toBeNull(); + }); + }); + + describe('buildRefundAccountRequestedNotification', () => { + it('금액을 천 단위로 적어 계좌 입력을 요청한다', () => { + expect(buildRefundAccountRequestedNotification('ORD-2', 30_000)).toEqual({ + type: NotificationType.ORDER_STATUS, + event: NotificationEvent.REFUND_ACCOUNT_REQUESTED, + title: '환불계좌입력', + body: 'ORD-2 30,000원을 돌려받을 계좌를 입력해 주세요.', + }); }); }); diff --git a/src/features/notification/services/notification-payloads.helper.ts b/src/features/notification/services/notification-payloads.helper.ts index 99c4900a..6d398953 100644 --- a/src/features/notification/services/notification-payloads.helper.ts +++ b/src/features/notification/services/notification-payloads.helper.ts @@ -1,11 +1,20 @@ import { + ORDER_CANCELED_NOTIFICATION, + ORDER_PAYMENT_EXPIRED_NOTIFICATION, ORDER_STATUS_NOTIFICATION_BODIES, ORDER_STATUS_NOTIFICATION_TITLES, + REFUND_ACCOUNT_REQUESTED_TITLE, REVIEW_LIKED_NOTIFICATION, } from '@/features/notification/constants/notification-messages'; +import { + ORDER_CANCEL_REASON_LABELS, + type OrderStatusChangedPayload, +} from '@/features/order'; import { NotificationEvent, NotificationType, + OrderActor, + OrderCancelReason, OrderStatus, } from '@/generated/prisma/client'; @@ -29,23 +38,62 @@ const ORDER_STATUS_NOTIFICATION_EVENTS: Partial< [OrderStatus.CONFIRMED]: NotificationEvent.ORDER_CONFIRMED, [OrderStatus.MADE]: NotificationEvent.ORDER_MADE, [OrderStatus.PICKED_UP]: NotificationEvent.ORDER_PICKED_UP, - [OrderStatus.CANCELED]: NotificationEvent.ORDER_CANCELED, }; -/** 매핑에 없는 상태는 알림 없음(null). */ +/** 매핑에 없는 상태와 구매자 본인 행위(취소)는 알림 없음(null). */ export function buildOrderStatusNotification( - orderNumber: string, - toStatus: OrderStatus, + p: Pick< + OrderStatusChangedPayload, + 'orderNumber' | 'toStatus' | 'actorType' | 'cancelReason' + >, ): NotificationPayload | null { - const event = ORDER_STATUS_NOTIFICATION_EVENTS[toStatus]; - const title = ORDER_STATUS_NOTIFICATION_TITLES[toStatus]; - const body = ORDER_STATUS_NOTIFICATION_BODIES[toStatus]; + if (p.actorType === OrderActor.BUYER) return null; + if (p.toStatus === OrderStatus.CANCELED) return buildOrderCanceled(p); + const event = ORDER_STATUS_NOTIFICATION_EVENTS[p.toStatus]; + const title = ORDER_STATUS_NOTIFICATION_TITLES[p.toStatus]; + const body = ORDER_STATUS_NOTIFICATION_BODIES[p.toStatus]; if (!event || !title || !body) return null; return { type: NotificationType.ORDER_STATUS, event, title, - body: `${orderNumber} ${body}`, + body: `${p.orderNumber} ${body}`, + }; +} + +function buildOrderCanceled( + p: Pick, +): NotificationPayload { + if (p.cancelReason === OrderCancelReason.PAYMENT_NOT_RECEIVED) { + return { + type: NotificationType.ORDER_STATUS, + event: NotificationEvent.ORDER_PAYMENT_EXPIRED, + title: ORDER_PAYMENT_EXPIRED_NOTIFICATION.title, + body: `${p.orderNumber} ${ORDER_PAYMENT_EXPIRED_NOTIFICATION.body}`, + }; + } + // 사유가 없는 건 취소 정책 도입 전 이벤트다 + const reason = p.cancelReason + ? ` 사유: ${ORDER_CANCEL_REASON_LABELS[p.cancelReason]}` + : ''; + return { + type: NotificationType.ORDER_STATUS, + event: NotificationEvent.ORDER_CANCELED, + title: ORDER_CANCELED_NOTIFICATION.title, + body: `${p.orderNumber} ${ORDER_CANCELED_NOTIFICATION.body}${reason}`, + }; +} + +/** 돌려줄 돈이 생겼을 때 계좌 입력을 요청한다. */ +export function buildRefundAccountRequestedNotification( + orderNumber: string, + amount: number, +): NotificationPayload { + return { + type: NotificationType.ORDER_STATUS, + event: NotificationEvent.REFUND_ACCOUNT_REQUESTED, + title: REFUND_ACCOUNT_REQUESTED_TITLE, + body: `${orderNumber} ${amount.toLocaleString('ko-KR')}원을 돌려받을 계좌를 입력해 주세요.`, }; } diff --git a/src/features/notification/services/seller-push-messages.helper.spec.ts b/src/features/notification/services/seller-push-messages.helper.spec.ts index c4b72d29..3b481b34 100644 --- a/src/features/notification/services/seller-push-messages.helper.spec.ts +++ b/src/features/notification/services/seller-push-messages.helper.spec.ts @@ -1,8 +1,11 @@ import { buildBuyerMessagePush, + buildOrderCanceledPush, buildOrderSubmittedPush, formatKstPickupAt, } from '@/features/notification/services/seller-push-messages.helper'; +import type { OrderStatusChangedPayload } from '@/features/order'; +import { OrderActor, OrderStatus } from '@/generated/prisma/client'; describe('seller-push-messages.helper', () => { // UTC → KST(+9), 월·일은 0 채움 없이, 시·분은 두 자리 @@ -70,4 +73,80 @@ describe('seller-push-messages.helper', () => { data: { kind: 'BUYER_MESSAGE', conversationId: '11' }, }); }); + + describe('buildOrderCanceledPush', () => { + const CANCELED: OrderStatusChangedPayload = { + orderId: '42', + orderNumber: 'ORD-1', + buyerAccountId: '7', + fromStatus: 'SUBMITTED', + toStatus: 'CANCELED', + storeId: '3', + storeName: '케이크샵', + productId: '9', + productName: '레터링 케이크', + actorType: 'BUYER', + cancelReason: 'BUYER_REQUEST', + refundAmount: 30_000, + pickupAt: '2026-10-05T03:05:00.000Z', + }; + + it.each([ + ['BUYER', '구매자'], + ['ADMIN', '운영자'], + ['SYSTEM', '자동'], + ] as const)( + '%s 취소: 본문 끝에 주체(%s), 딥링크는 주문', + (actorType, label) => { + expect(buildOrderCanceledPush({ ...CANCELED, actorType })).toEqual({ + storeId: '3', + content: { + title: '주문 취소', + body: `레터링 케이크 · 픽업 10/5 12:05 주문이 취소됐어요(${label})`, + data: { kind: 'ORDER_CANCELED', orderId: '42' }, + }, + }); + }, + ); + + // 푸시 필터 전수: 취소 전이 ∧ 입금 전 주문 아님 ∧ 판매자 본인이 아닌 주체만 + const cases = Object.values(OrderStatus).flatMap((fromStatus) => + Object.values(OrderStatus).flatMap((toStatus) => + [...Object.values(OrderActor), null].map( + (actorType) => + [ + fromStatus, + toStatus, + actorType, + toStatus === 'CANCELED' && + fromStatus !== 'PENDING_PAYMENT' && + actorType !== null && + actorType !== 'SELLER', + ] as const, + ), + ), + ); + + it('필터 표는 7 × 7 × 주체 5(모름 포함)를 덮고 보내는 경우는 18개다', () => { + expect(cases).toHaveLength(245); + expect(cases.filter(([, , , sent]) => sent)).toHaveLength(18); + }); + + it.each(cases)( + '%s → %s by %s: 보냄 %s', + (fromStatus, toStatus, actorType, sent) => { + const push = buildOrderCanceledPush({ + ...CANCELED, + fromStatus, + toStatus, + actorType, + }); + expect(push !== null).toBe(sent); + }, + ); + + it('매장을 모르면(품목 없음) 보내지 않는다', () => { + expect(buildOrderCanceledPush({ ...CANCELED, storeId: null })).toBeNull(); + }); + }); }); diff --git a/src/features/notification/services/seller-push-messages.helper.ts b/src/features/notification/services/seller-push-messages.helper.ts index 0f2675fc..53b5f0d5 100644 --- a/src/features/notification/services/seller-push-messages.helper.ts +++ b/src/features/notification/services/seller-push-messages.helper.ts @@ -4,14 +4,26 @@ import { toKstYmd, } from '@/common/utils/kst-time'; import type { ConversationBuyerMessageSentPayload } from '@/features/conversation'; -import type { OrderSubmittedPayload } from '@/features/order'; +import type { + OrderStatusChangedPayload, + OrderSubmittedPayload, +} from '@/features/order'; +import { OrderActor, OrderStatus } from '@/generated/prisma/client'; /** 앱 딥링크 키. */ const SELLER_PUSH_KIND = { ORDER_SUBMITTED: 'ORDER_SUBMITTED', + ORDER_CANCELED: 'ORDER_CANCELED', BUYER_MESSAGE: 'BUYER_MESSAGE', } as const; +/** 판매자 본인이 아닌 취소 주체. 이 밖(판매자 본인·주체를 모르는 옛 이벤트)은 푸시하지 않는다. */ +const CANCEL_ACTOR_LABELS: Partial> = { + [OrderActor.BUYER]: '구매자', + [OrderActor.ADMIN]: '운영자', + [OrderActor.SYSTEM]: '자동', +}; + /** Android 알림 채널 — 앱이 같은 id로 만든다. */ export const SELLER_PUSH_CHANNEL_ID = 'default'; @@ -47,6 +59,32 @@ export function buildOrderSubmittedPush( }; } +/** 판매자가 모르는 사이 일어난 취소만 알린다. 입금 전 주문은 판매자에게 보인 적이 없어 뺀다. 대상이 아니거나 매장을 모르면 null. */ +export function buildOrderCanceledPush( + p: OrderStatusChangedPayload, +): { storeId: string; content: SellerPushContent } | null { + const actorLabel = p.actorType ? CANCEL_ACTOR_LABELS[p.actorType] : null; + if ( + p.toStatus !== OrderStatus.CANCELED || + p.fromStatus === OrderStatus.PENDING_PAYMENT || + !actorLabel || + p.storeId === null + ) { + return null; + } + const pickup = p.pickupAt + ? ` · 픽업 ${formatKstPickupAt(new Date(p.pickupAt))}` + : ''; + return { + storeId: p.storeId, + content: { + title: '주문 취소', + body: `${p.productName ?? p.orderNumber}${pickup} 주문이 취소됐어요(${actorLabel})`, + data: { kind: SELLER_PUSH_KIND.ORDER_CANCELED, orderId: p.orderId }, + }, + }; +} + export function buildBuyerMessagePush( p: ConversationBuyerMessageSentPayload, ): SellerPushContent { diff --git a/src/features/notification/services/seller-push-outbox.consumer.spec.ts b/src/features/notification/services/seller-push-outbox.consumer.spec.ts index 6d1b30af..0bc97994 100644 --- a/src/features/notification/services/seller-push-outbox.consumer.spec.ts +++ b/src/features/notification/services/seller-push-outbox.consumer.spec.ts @@ -438,6 +438,58 @@ describe('SellerPushOutboxConsumer (real DB)', () => { }); }); + describe('order.status_changed', () => { + function statusChanged( + storeId: bigint, + overrides: Record = {}, + ): OutboxEvent { + return event('order.status_changed', { + orderId: '42', + orderNumber: 'ORD-1', + buyerAccountId: '7', + fromStatus: 'CONFIRMED', + toStatus: 'CANCELED', + storeId: storeId.toString(), + storeName: '케이크샵', + productId: '9', + productName: '레터링 케이크', + actorType: 'ADMIN', + cancelReason: 'OTHER', + refundAmount: 0, + pickupAt: '2026-10-05T03:05:00.000Z', + ...overrides, + }); + } + + it('운영자 취소는 매장 디바이스에 취소 푸시를 보낸다', async () => { + const { storeId } = await storeWithDevices(1); + + await consumer.handle(statusChanged(storeId)); + + expect(send).toHaveBeenCalledTimes(1); + expect(send.mock.calls[0][0][0]).toMatchObject({ + title: '주문 취소', + body: '레터링 케이크 · 픽업 10/5 12:05 주문이 취소됐어요(운영자)', + data: { kind: 'ORDER_CANCELED', orderId: '42' }, + }); + expect(await deliveries()).toHaveLength(1); + }); + + it.each([ + ['판매자 본인 취소', { actorType: 'SELLER' }], + ['입금 전 주문 취소', { fromStatus: 'PENDING_PAYMENT' }], + ['취소가 아닌 전이', { toStatus: 'MADE', cancelReason: null }], + ['주체를 모르는 옛 이벤트', { actorType: undefined }], + ])('%s는 보내지 않고 정상 소비된다(행 없음)', async (_label, overrides) => { + const { storeId } = await storeWithDevices(1); + + await consumer.handle(statusChanged(storeId, overrides)); + + expect(send).not.toHaveBeenCalled(); + expect(await deliveries()).toHaveLength(0); + }); + }); + it('conversation.buyer_message_sent는 preview를 본문으로, 딥링크는 대화 id', async () => { const { storeId, devices } = await storeWithDevices(1); @@ -465,9 +517,9 @@ describe('SellerPushOutboxConsumer (real DB)', () => { }); it('반증: 구독하지 않은 event_type은 던진다', async () => { - await expect( - consumer.handle(event('order.status_changed', {})), - ).rejects.toThrow('구독하지 않은 outbox 이벤트: order.status_changed'); + await expect(consumer.handle(event('review.liked', {}))).rejects.toThrow( + '구독하지 않은 outbox 이벤트: review.liked', + ); expect(send).not.toHaveBeenCalled(); }); }); diff --git a/src/features/notification/services/seller-push-outbox.consumer.ts b/src/features/notification/services/seller-push-outbox.consumer.ts index 133c07ed..3b014bac 100644 --- a/src/features/notification/services/seller-push-outbox.consumer.ts +++ b/src/features/notification/services/seller-push-outbox.consumer.ts @@ -20,11 +20,17 @@ import { import { SellerPushDeviceRepository } from '@/features/notification/repositories/seller-push-device.repository'; import { buildBuyerMessagePush, + buildOrderCanceledPush, buildOrderSubmittedPush, SELLER_PUSH_CHANNEL_ID, type SellerPushContent, } from '@/features/notification/services/seller-push-messages.helper'; -import { ORDER_SUBMITTED, parseOrderSubmittedPayload } from '@/features/order'; +import { + ORDER_STATUS_CHANGED, + ORDER_SUBMITTED, + parseOrderStatusChangedPayload, + parseOrderSubmittedPayload, +} from '@/features/order'; import { type OutboxConsumer, type OutboxEvent, @@ -46,7 +52,11 @@ import { MetricsService } from '@/global/metrics'; * 전송 실패(네트워크·5xx·429)는 던져 호스트의 retry/DLQ에 맡기고, 인증 실패는 경보를 낸 뒤 던진다. */ @Injectable() -@SubscribeOutbox(ORDER_SUBMITTED, CONVERSATION_BUYER_MESSAGE_SENT) +@SubscribeOutbox( + ORDER_SUBMITTED, + ORDER_STATUS_CHANGED, + CONVERSATION_BUYER_MESSAGE_SENT, +) export class SellerPushOutboxConsumer implements OutboxConsumer { private readonly logger = new Logger(SellerPushOutboxConsumer.name); @@ -69,7 +79,10 @@ export class SellerPushOutboxConsumer implements OutboxConsumer { ); return; } - const { storeId, content } = this.contentOf(event); + const target = this.contentOf(event); + // 푸시 대상이 아닌 상태 전이 — 이벤트는 정상 소비된다 + if (!target) return; + const { storeId, content } = target; const devices = await this.devices.listActiveByStore(storeId); if (devices.length === 0) return; @@ -149,10 +162,9 @@ export class SellerPushOutboxConsumer implements OutboxConsumer { } } - private contentOf(event: OutboxEvent): { - storeId: bigint; - content: SellerPushContent; - } { + private contentOf( + event: OutboxEvent, + ): { storeId: bigint; content: SellerPushContent } | null { switch (event.eventType) { case ORDER_SUBMITTED: { const p = parseOrderSubmittedPayload(event.payload); @@ -161,6 +173,14 @@ export class SellerPushOutboxConsumer implements OutboxConsumer { content: buildOrderSubmittedPush(p, event.occurredAt), }; } + case ORDER_STATUS_CHANGED: { + const push = buildOrderCanceledPush( + parseOrderStatusChangedPayload(event.payload), + ); + return push + ? { storeId: parseId(push.storeId), content: push.content } + : null; + } case CONVERSATION_BUYER_MESSAGE_SENT: { const p = parseConversationBuyerMessageSentPayload(event.payload); return { diff --git a/src/features/order/constants/order-admin.constants.ts b/src/features/order/constants/order-admin.constants.ts deleted file mode 100644 index 38527953..00000000 --- a/src/features/order/constants/order-admin.constants.ts +++ /dev/null @@ -1,9 +0,0 @@ -import { MAX_REASON_LENGTH } from '@/common/constants/reason.constants'; - -// ── 주문 ── - -/** 관리자 취소 이력 메모 접두 — 판매자 취소와 구분한다. */ -export const ADMIN_CANCEL_NOTE_PREFIX = '[관리자] '; -/** 접두를 붙인 뒤에도 order_status_history.note(500)에 들어가야 한다. */ -export const MAX_ADMIN_CANCEL_NOTE_LENGTH = - MAX_REASON_LENGTH - ADMIN_CANCEL_NOTE_PREFIX.length; diff --git a/src/features/order/constants/order-cancel-reasons.ts b/src/features/order/constants/order-cancel-reasons.ts new file mode 100644 index 00000000..1f7b3366 --- /dev/null +++ b/src/features/order/constants/order-cancel-reasons.ts @@ -0,0 +1,13 @@ +import type { OrderCancelReason } from '@/generated/prisma/client'; + +/** 취소 사유 표시 라벨. 주문 상세 reasonLabel과 구매자 취소 알림 본문이 같은 값을 쓴다. */ +export const ORDER_CANCEL_REASON_LABELS = { + DESIGN_NOT_FEASIBLE: '제작할 수 없는 디자인', + OUT_OF_MATERIALS: '재료 소진', + SCHEDULE_UNAVAILABLE: '일정 불가', + INAPPROPRIATE_REQUEST: '부적절한 요청', + BUYER_REQUEST: '구매자 요청', + OTHER: '기타', + PAYMENT_NOT_RECEIVED: '미입금', + CONFIRM_TIMEOUT: '판매자 미확정', +} as const satisfies Record; diff --git a/src/features/order/dto/inputs/admin-cancel-order.input.ts b/src/features/order/dto/inputs/admin-cancel-order.input.ts index 723162f3..5f67ca7d 100644 --- a/src/features/order/dto/inputs/admin-cancel-order.input.ts +++ b/src/features/order/dto/inputs/admin-cancel-order.input.ts @@ -1,12 +1,25 @@ -import { IsString, MaxLength } from 'class-validator'; +import { IsEnum, IsInt, IsOptional, IsString } from 'class-validator'; -import { MAX_ADMIN_CANCEL_NOTE_LENGTH } from '@/features/order/constants/order-admin.constants'; +import { OrderCancelFault, OrderCancelReason } from '@/generated/prisma/client'; export class AdminCancelOrderInput { @IsString() orderId!: string; + // 주문 상태별 허용 여부는 OrderCancelPolicy가 판정한다 + @IsEnum(OrderCancelReason) + reason!: OrderCancelReason; + + @IsOptional() @IsString() - @MaxLength(MAX_ADMIN_CANCEL_NOTE_LENGTH) - note!: string; + note?: string | null; + + @IsOptional() + @IsEnum(OrderCancelFault) + fault?: OrderCancelFault | null; + + // 범위(0~결제액)는 잠금 뒤 결제액으로 판정한다 + @IsOptional() + @IsInt() + refundAmount?: number | null; } diff --git a/src/features/order/dto/inputs/cancel-my-order.input.ts b/src/features/order/dto/inputs/cancel-my-order.input.ts new file mode 100644 index 00000000..636866db --- /dev/null +++ b/src/features/order/dto/inputs/cancel-my-order.input.ts @@ -0,0 +1,10 @@ +import { IsOptional, IsString } from 'class-validator'; + +export class CancelMyOrderInput { + @IsString() + orderId!: string; + + @IsOptional() + @IsString() + note?: string | null; +} diff --git a/src/features/order/dto/inputs/seller-cancel-order.input.ts b/src/features/order/dto/inputs/seller-cancel-order.input.ts new file mode 100644 index 00000000..53186d9a --- /dev/null +++ b/src/features/order/dto/inputs/seller-cancel-order.input.ts @@ -0,0 +1,25 @@ +import { IsEnum, IsInt, IsOptional, IsString } from 'class-validator'; + +import { OrderCancelFault, OrderCancelReason } from '@/generated/prisma/client'; + +export class SellerCancelOrderInput { + @IsString() + orderId!: string; + + // 주문 상태별 허용 여부는 OrderCancelPolicy가 판정한다 + @IsEnum(OrderCancelReason) + reason!: OrderCancelReason; + + @IsOptional() + @IsString() + note?: string | null; + + @IsOptional() + @IsEnum(OrderCancelFault) + fault?: OrderCancelFault | null; + + // 범위(0~결제액)는 잠금 뒤 결제액으로 판정한다 + @IsOptional() + @IsInt() + refundAmount?: number | null; +} diff --git a/src/features/order/events/order-status-changed.event.spec.ts b/src/features/order/events/order-status-changed.event.spec.ts new file mode 100644 index 00000000..31ac4c84 --- /dev/null +++ b/src/features/order/events/order-status-changed.event.spec.ts @@ -0,0 +1,106 @@ +import { + ORDER_STATUS_CHANGED, + orderStatusChangedEvent, + parseOrderStatusChangedPayload, +} from '@/features/order/events/order-status-changed.event'; +import type { Prisma } from '@/generated/prisma/client'; + +const LEGACY = { + orderId: '7', + orderNumber: 'ORD-1', + buyerAccountId: '3', + fromStatus: 'CONFIRMED', + toStatus: 'CANCELED', + storeId: '2', + storeName: '케이크샵', + productId: '5', + productName: '레터링 케이크', +}; +const VALID = { + ...LEGACY, + actorType: 'ADMIN', + cancelReason: 'OUT_OF_MATERIALS', + refundAmount: 10_000, + pickupAt: '2026-09-20T03:00:00.000Z', +}; + +describe('order.status_changed 이벤트', () => { + it('취소 주체·사유·환불액·픽업 일시를 싣고 파서가 그대로 읽는다', () => { + const occurredAt = new Date('2026-09-16T07:30:00.000Z'); + const event = orderStatusChangedEvent({ + orderId: 7n, + orderNumber: 'ORD-1', + buyerAccountId: 3n, + fromStatus: 'CONFIRMED', + toStatus: 'CANCELED', + storeId: 2n, + storeName: '케이크샵', + productId: 5n, + productName: '레터링 케이크', + actorType: 'ADMIN', + pickupAt: new Date(VALID.pickupAt), + cancelReason: 'OUT_OF_MATERIALS', + refundAmount: 10_000, + occurredAt, + actorAccountId: 9n, + }); + + expect(event).toMatchObject({ + aggregateId: '7', + eventType: ORDER_STATUS_CHANGED, + payload: VALID, + }); + expect( + parseOrderStatusChangedPayload(event.payload as Prisma.JsonValue), + ).toEqual(VALID); + }); + + it('취소가 아닌 전이는 사유·환불액이 null이다', () => { + const event = orderStatusChangedEvent({ + orderId: 7n, + orderNumber: 'ORD-1', + buyerAccountId: 3n, + fromStatus: 'SUBMITTED', + toStatus: 'CONFIRMED', + storeId: null, + storeName: null, + productId: null, + productName: null, + actorType: 'SELLER', + pickupAt: new Date(VALID.pickupAt), + occurredAt: new Date(), + actorAccountId: null, + }); + expect(event.payload).toMatchObject({ + actorType: 'SELLER', + cancelReason: null, + refundAmount: null, + }); + }); + + it('새 필드가 없는 옛 이벤트는 null로 읽는다', () => { + expect(parseOrderStatusChangedPayload(LEGACY as Prisma.JsonValue)).toEqual({ + ...LEGACY, + actorType: null, + cancelReason: null, + refundAmount: null, + pickupAt: null, + }); + }); + + it.each([ + ['null', null], + ['배열', [VALID]], + ['fromStatus 모름', { ...VALID, fromStatus: 'SHIPPED' }], + ['toStatus 누락', { ...VALID, toStatus: undefined }], + ['actorType 모름', { ...VALID, actorType: 'ROBOT' }], + ['cancelReason 모름', { ...VALID, cancelReason: 'WHATEVER' }], + ['refundAmount 문자열', { ...VALID, refundAmount: '10000' }], + ['refundAmount 소수', { ...VALID, refundAmount: 1.5 }], + ['pickupAt 날짜 아님', { ...VALID, pickupAt: 'tomorrow' }], + ])('반증: %s payload는 던진다', (_label, payload) => { + expect(() => + parseOrderStatusChangedPayload(payload as Prisma.JsonValue), + ).toThrow('payload 형식 오류'); + }); +}); diff --git a/src/features/order/events/order-status-changed.event.ts b/src/features/order/events/order-status-changed.event.ts index 1ee557c8..6c151e04 100644 --- a/src/features/order/events/order-status-changed.event.ts +++ b/src/features/order/events/order-status-changed.event.ts @@ -1,5 +1,10 @@ import type { OutboxEventInput } from '@/features/outbox'; -import { OrderStatus, type Prisma } from '@/generated/prisma/client'; +import { + OrderActor, + OrderCancelReason, + OrderStatus, + type Prisma, +} from '@/generated/prisma/client'; /** 주문 상태 전이 이벤트. payload는 생산 시점 스냅샷(P1-9) — 소비자(notification)가 order·store·product를 다시 읽지 않는다. */ export const ORDER_STATUS_CHANGED = 'order.status_changed'; @@ -14,6 +19,11 @@ export interface OrderStatusChangedPayload { storeName: string | null; productId: string | null; productName: string | null; + /** 아래 넷은 취소 정책 도입 전 이벤트에 없다 — 파서가 null로 채운다 */ + actorType: OrderActor | null; + cancelReason: OrderCancelReason | null; + refundAmount: number | null; + pickupAt: string | null; } export function orderStatusChangedEvent(args: { @@ -26,8 +36,12 @@ export function orderStatusChangedEvent(args: { storeName: string | null; productId: bigint | null; productName: string | null; + actorType: OrderActor; + pickupAt: Date; + cancelReason?: OrderCancelReason; + refundAmount?: number; occurredAt: Date; - actorAccountId: bigint; + actorAccountId: bigint | null; }): OutboxEventInput { const payload: OrderStatusChangedPayload = { orderId: args.orderId.toString(), @@ -39,6 +53,10 @@ export function orderStatusChangedEvent(args: { storeName: args.storeName, productId: args.productId?.toString() ?? null, productName: args.productName, + actorType: args.actorType, + cancelReason: args.cancelReason ?? null, + refundAmount: args.refundAmount ?? null, + pickupAt: args.pickupAt.toISOString(), }; return { aggregateType: 'order', @@ -51,6 +69,21 @@ export function orderStatusChangedEvent(args: { } const ORDER_STATUSES = new Set(Object.values(OrderStatus)); +const ORDER_ACTORS = new Set(Object.values(OrderActor)); +const CANCEL_REASONS = new Set(Object.values(OrderCancelReason)); + +const malformed = (): Error => + new Error(`${ORDER_STATUS_CHANGED} payload 형식 오류`); + +const isMember = (set: Set) => (v: unknown) => + typeof v === 'string' && set.has(v); + +/** 없으면(옛 이벤트) null, 있는데 형태가 어긋나면 던진다. */ +function optional(value: unknown, valid: (v: unknown) => boolean): T | null { + if (value === undefined || value === null) return null; + if (!valid(value)) throw malformed(); + return value as T; +} /** 소비자용 방어적 파싱 — 형태가 어긋난 payload는 던져서 재시도·FAILED로 드러낸다. */ export function parseOrderStatusChangedPayload( @@ -64,12 +97,10 @@ export function parseOrderStatusChangedPayload( typeof p.orderId !== 'string' || typeof p.orderNumber !== 'string' || typeof p.buyerAccountId !== 'string' || - typeof p.fromStatus !== 'string' || - !ORDER_STATUSES.has(p.fromStatus) || - typeof p.toStatus !== 'string' || - !ORDER_STATUSES.has(p.toStatus) + !isMember(ORDER_STATUSES)(p.fromStatus) || + !isMember(ORDER_STATUSES)(p.toStatus) ) { - throw new Error(`${ORDER_STATUS_CHANGED} payload 형식 오류`); + throw malformed(); } return { orderId: p.orderId, @@ -81,5 +112,12 @@ export function parseOrderStatusChangedPayload( storeName: typeof p.storeName === 'string' ? p.storeName : null, productId: typeof p.productId === 'string' ? p.productId : null, productName: typeof p.productName === 'string' ? p.productName : null, + actorType: optional(p.actorType, isMember(ORDER_ACTORS)), + cancelReason: optional(p.cancelReason, isMember(CANCEL_REASONS)), + refundAmount: optional(p.refundAmount, Number.isSafeInteger), + pickupAt: optional( + p.pickupAt, + (v) => typeof v === 'string' && !Number.isNaN(Date.parse(v)), + ), }; } diff --git a/src/features/order/events/refund-requested.event.spec.ts b/src/features/order/events/refund-requested.event.spec.ts new file mode 100644 index 00000000..7e7e99d3 --- /dev/null +++ b/src/features/order/events/refund-requested.event.spec.ts @@ -0,0 +1,81 @@ +import { + parseRefundRequestedPayload, + REFUND_REQUESTED, + refundRequestedEvent, +} from '@/features/order/events/refund-requested.event'; +import type { Prisma } from '@/generated/prisma/client'; + +const VALID = { + refundId: '11', + orderId: '7', + orderNumber: 'ORD-1', + buyerAccountId: '3', + kind: 'CANCEL', + amount: 30_000, + storeId: '2', + storeName: '케이크샵', + productId: '5', + productName: '레터링 케이크', +}; + +describe('refund.requested 이벤트', () => { + it('주문과 같은 aggregate(파티션)에 묶고 파서가 그대로 읽는다', () => { + const occurredAt = new Date('2026-09-16T07:30:00.000Z'); + const event = refundRequestedEvent({ + refundId: 11n, + orderId: 7n, + orderNumber: 'ORD-1', + buyerAccountId: 3n, + kind: 'CANCEL', + amount: 30_000, + storeId: 2n, + storeName: '케이크샵', + productId: 5n, + productName: '레터링 케이크', + occurredAt, + actorAccountId: 9n, + }); + + expect(event).toEqual({ + aggregateType: 'order', + aggregateId: '7', + eventType: REFUND_REQUESTED, + payload: VALID, + occurredAt, + actorAccountId: 9n, + }); + expect( + parseRefundRequestedPayload(event.payload as Prisma.JsonValue), + ).toEqual(VALID); + }); + + it('매장·상품 스냅샷이 없으면 null로 읽는다', () => { + expect( + parseRefundRequestedPayload({ + ...VALID, + storeId: null, + storeName: undefined, + productId: null, + productName: null, + }), + ).toMatchObject({ + storeId: null, + storeName: null, + productId: null, + productName: null, + }); + }); + + it.each([ + ['null', null], + ['배열', [VALID]], + ['refundId 숫자', { ...VALID, refundId: 11 }], + ['buyerAccountId 누락', { ...VALID, buyerAccountId: undefined }], + ['kind 모름', { ...VALID, kind: 'CHARGEBACK' }], + ['amount 문자열', { ...VALID, amount: '30000' }], + ])('반증: %s payload는 던진다', (_label, payload) => { + expect(() => + parseRefundRequestedPayload(payload as Prisma.JsonValue), + ).toThrow('payload 형식 오류'); + }); +}); diff --git a/src/features/order/events/refund-requested.event.ts b/src/features/order/events/refund-requested.event.ts new file mode 100644 index 00000000..b7485e2d --- /dev/null +++ b/src/features/order/events/refund-requested.event.ts @@ -0,0 +1,91 @@ +import type { OutboxEventInput } from '@/features/outbox'; +import { RefundKind, type Prisma } from '@/generated/prisma/client'; + +/** 환불 생성(취소 환불·입금 반환). 구매자에게 돌려받을 계좌 입력을 요청하는 알림의 원천이다. */ +export const REFUND_REQUESTED = 'refund.requested'; + +export interface RefundRequestedPayload { + refundId: string; + orderId: string; + orderNumber: string; + buyerAccountId: string; + kind: RefundKind; + amount: number; + storeId: string | null; + storeName: string | null; + productId: string | null; + productName: string | null; +} + +export function refundRequestedEvent(args: { + refundId: bigint; + orderId: bigint; + orderNumber: string; + buyerAccountId: bigint; + kind: RefundKind; + amount: number; + storeId: bigint | null; + storeName: string | null; + productId: bigint | null; + productName: string | null; + occurredAt: Date; + actorAccountId: bigint | null; +}): OutboxEventInput { + const payload: RefundRequestedPayload = { + refundId: args.refundId.toString(), + orderId: args.orderId.toString(), + orderNumber: args.orderNumber, + buyerAccountId: args.buyerAccountId.toString(), + kind: args.kind, + amount: args.amount, + storeId: args.storeId?.toString() ?? null, + storeName: args.storeName, + productId: args.productId?.toString() ?? null, + productName: args.productName, + }; + return { + // 같은 주문의 상태 전이와 같은 파티션 순서를 탄다 + aggregateType: 'order', + aggregateId: payload.orderId, + eventType: REFUND_REQUESTED, + payload: { ...payload }, + occurredAt: args.occurredAt, + actorAccountId: args.actorAccountId, + }; +} + +const REFUND_KINDS = new Set(Object.values(RefundKind)); +const nullableString = (v: unknown): string | null => + typeof v === 'string' ? v : null; + +export function parseRefundRequestedPayload( + value: Prisma.JsonValue, +): RefundRequestedPayload { + const p = value as Partial>; + if ( + typeof value !== 'object' || + value === null || + Array.isArray(value) || + typeof p.refundId !== 'string' || + typeof p.orderId !== 'string' || + typeof p.orderNumber !== 'string' || + typeof p.buyerAccountId !== 'string' || + typeof p.kind !== 'string' || + !REFUND_KINDS.has(p.kind) || + !Number.isSafeInteger(p.amount) + ) { + throw new Error(`${REFUND_REQUESTED} payload 형식 오류`); + } + return { + refundId: p.refundId, + orderId: p.orderId, + orderNumber: p.orderNumber, + buyerAccountId: p.buyerAccountId, + kind: p.kind as RefundKind, + amount: p.amount as number, + storeId: nullableString(p.storeId), + storeName: nullableString(p.storeName), + productId: nullableString(p.productId), + productName: nullableString(p.productName), + }; +} diff --git a/src/features/order/index.ts b/src/features/order/index.ts index b14b47fd..a7f80945 100644 --- a/src/features/order/index.ts +++ b/src/features/order/index.ts @@ -8,8 +8,17 @@ export { // 주문 상태 전이 이벤트 계약(outbox). 소비자(notification)는 payload 스냅샷만 읽는다. export { ORDER_STATUS_CHANGED, + type OrderStatusChangedPayload, parseOrderStatusChangedPayload, } from '@/features/order/events/order-status-changed.event'; +// 취소 사유 라벨 — 구매자 취소 알림 본문(notification)이 주문 상세와 같은 값을 쓴다. +export { ORDER_CANCEL_REASON_LABELS } from '@/features/order/constants/order-cancel-reasons'; +// 환불 생성 이벤트 계약(outbox). 구매자 환불 계좌 요청 알림(notification)이 읽는다. +export { + REFUND_REQUESTED, + type RefundRequestedPayload, + parseRefundRequestedPayload, +} from '@/features/order/events/refund-requested.event'; // 주문 접수 이벤트 계약(outbox). 판매자 푸시 소비자(notification)가 읽는다. export { ORDER_SUBMITTED, diff --git a/src/features/order/order-admin.graphql b/src/features/order/order-admin.graphql index 65888191..a96a1447 100644 --- a/src/features/order/order-admin.graphql +++ b/src/features/order/order-admin.graphql @@ -18,9 +18,13 @@ extend type Query { 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! } @@ -203,6 +207,40 @@ type AdminOrderDetail { 상태 변경 이력. 최신순. """ statusHistories: [OrderStatusHistory!]! + """ + 이 주문의 환불(취소 환불·입금 반환). 오래된 순, 없으면 빈 배열. + """ + refunds: [OrderRefund!]! + """ + 취소 정보(주체·사유·사정·환불액·환불 진행). 취소되지 않은 주문이면 null. + """ + cancellation: OrderCancellation + """ + 강제 취소 다이얼로그의 선택지. 지금 상태 기준이다. + """ + cancelOptions: AdminOrderCancelOptions! +} + +""" +관리자 강제 취소 선택지. 화면은 이 값으로 다이얼로그를 그리고 규칙을 복제하지 않는다. +""" +type AdminOrderCancelOptions { + """ + 지금 취소할 수 있는지. + """ + cancelable: Boolean! + """ + 고를 수 있는 취소 사유. 취소할 수 없으면 빈 배열. + """ + reasons: [OrderCancelReasonType!]! + """ + 환불 규칙. BY_FAULT면 사정을 고르게 하고, 구매자 사정이면 환불 금액(0~paidAmount)을 입력받는다. 취소할 수 없으면 null. + """ + refundRule: CancelRefundRuleType + """ + 확인된 결제액(원). 입금 전이거나 결제 도입 전 주문이면 0. + """ + paidAmount: Int! } """ @@ -277,12 +315,24 @@ input AdminOrderListInput { } """ -주문 강제 취소 입력. +주문 강제 취소 입력. 허용 범위는 adminOrder.cancelOptions를 따른다. """ input AdminCancelOrderInput { orderId: ID! """ - 취소 사유. 필수. 최대 494자('[관리자] ' 접두를 붙여 500자 이내로 이력에 남는다). 감사 로그에도 기록된다. + 취소 사유. 필수. cancelOptions.reasons 중 하나여야 한다. + """ + reason: OrderCancelReasonType! + """ + 취소 메모. 선택, 최대 500자. 상태 이력과 감사 로그에 남는다. + """ + note: String + """ + 취소 사정. cancelOptions.refundRule이 BY_FAULT면 필수이고, 그 밖에는 무시한다. + """ + fault: OrderCancelFaultType + """ + 돌려줄 금액(원, 0~cancelOptions.paidAmount). fault가 BUYER일 때 필수이고, 그 밖에는 무시한다. """ - note: String! + refundAmount: Int } diff --git a/src/features/order/order-my.graphql b/src/features/order/order-my.graphql index 85c418bb..4d744a28 100644 --- a/src/features/order/order-my.graphql +++ b/src/features/order/order-my.graphql @@ -16,6 +16,24 @@ extend type Mutation { 기한이 지났으면 PAYMENT_DEADLINE_PASSED(BAD_USER_INPUT). 로그인 필수. 본인 주문이 아니면 NOT_FOUND. """ markMyOrderDepositSent(orderId: ID!): MyOrderDetail! + """ + 내 주문을 취소한다. 판매자 확정 전(입금 대기·접수)까지만 되고 사유는 구매자 요청으로 기록된다. + 입금 대기는 환불 없이, 접수는 결제액 전액 환불로 취소되고 환불이 생기면 환불 계좌 입력 요청 알림이 간다. + '입금했어요'를 누른 주문도 취소할 수 있다. 그 밖의 상태면 ORDER_NOT_CANCELLABLE(BAD_USER_INPUT). + 로그인 필수. 본인 주문이 아니면 NOT_FOUND. + """ + cancelMyOrder(input: CancelMyOrderInput!): MyOrderDetail! +} + +""" +내 주문 취소 입력. +""" +input CancelMyOrderInput { + orderId: ID! + """ + 취소 메모. 선택, 최대 500자. 상태 이력에 남고 판매자도 본다. + """ + note: String } """ @@ -186,6 +204,14 @@ type MyOrderDetail { CANCELED 도달 시각. 취소되지 않았으면 null. """ canceledAt: DateTime + """ + 취소 정보(주체·사유·환불액·환불 진행). 취소되지 않은 주문이면 null. + """ + cancellation: OrderCancellation + """ + 지금 cancelMyOrder로 취소할 수 있는지. 입금 대기·접수 상태일 때 true. + """ + canCancel: Boolean! """ 상태 변경 이력. 오래된 순이다(판매자 주문 상세는 최신순 — 방향이 반대다). diff --git a/src/features/order/order-seller.graphql b/src/features/order/order-seller.graphql index 37818e26..895f6744 100644 --- a/src/features/order/order-seller.graphql +++ b/src/features/order/order-seller.graphql @@ -11,11 +11,21 @@ extend type Query { extend type Mutation { """ - 주문 상태를 변경한다. 판매자 로그인 필수. SELLER 계정이 아니면 FORBIDDEN, 매장을 보유하지 않으면 NOT_FOUND. + 주문 상태를 변경한다. 취소(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! } """ @@ -204,6 +214,10 @@ type SellerOrderDetail { 상태 변경 이력. 최신순. 입금 대기 이력은 빠지고, 접수 이력은 fromStatus가 null(최초)로 온다. """ statusHistories: [OrderStatusHistory!]! + """ + 취소 정보(주체·사유·사정·환불액·환불 진행). 취소되지 않은 주문이면 null. + """ + cancellation: OrderCancellation } """ @@ -217,7 +231,30 @@ input SellerUpdateOrderStatusInput { """ toStatus: OrderStatusType! """ - 변경 사유 메모. toStatus가 CANCELED면 필수이고, 없으면 BAD_USER_INPUT. + 변경 메모. 선택, 최대 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 } diff --git a/src/features/order/order.module.ts b/src/features/order/order.module.ts index 411de205..db97fa0e 100644 --- a/src/features/order/order.module.ts +++ b/src/features/order/order.module.ts @@ -3,6 +3,7 @@ import { Module } from '@nestjs/common'; import { BOOKED_QUANTITY_QUERY } from '@/common/ports/booked-quantity.port'; import { AuditLogModule } from '@/features/audit-log'; import { AuthModule } from '@/features/auth'; +import { OrderCancelPolicy } from '@/features/order/policies/order-cancel.policy'; import { OrderStatusTransitionPolicy } from '@/features/order/policies/order-status-transition.policy'; import { OrderBookedRepository } from '@/features/order/repositories/order-booked.repository'; import { OrderStoreDailyLimitRepository } from '@/features/order/repositories/order-store-daily-limit.repository'; @@ -59,13 +60,15 @@ import { StoreModule } from '@/features/store'; OrderStoreDailyLimitRepository, OrderStoreDailyLimitConsumer, OrderStatusTransitionPolicy, - // 판매자 주문 구독(Redis PubSub) — 발행은 입금 확인·판매자 상태 변경·관리자 취소 서비스가 커밋 뒤 직접 + // 주체별 취소 사유·사정·환불액 판정(구매자·판매자·관리자 취소가 공유) + OrderCancelPolicy, + // 판매자 주문 구독(Redis PubSub) — 발행은 입금 확인·판매자 상태 변경·취소 서비스가 커밋 뒤 직접 OrderEventsService, OrderSubscriptionService, OrderSubscriptionResolver, OrderCheckoutService, OrderCheckoutMutationResolver, - // 판매자 주문 관리(목록·상세·상태 변경) — 주문 도메인이 소유한다 + // 판매자 주문 관리(목록·상세·상태 변경·거절·취소) — 주문 도메인이 소유한다 SellerOrderService, SellerOrderQueryResolver, SellerOrderMutationResolver, @@ -73,7 +76,7 @@ import { StoreModule } from '@/features/store'; AdminOrderService, AdminOrderQueryResolver, AdminOrderMutationResolver, - // 구매자 주문 목록·상세·'입금했어요' + // 구매자 주문 목록·상세·'입금했어요'·취소 UserOrderService, UserOrderQueryResolver, UserOrderMutationResolver, diff --git a/src/features/order/order.types.graphql b/src/features/order/order.types.graphql index be239f71..2cc80a6d 100644 --- a/src/features/order/order.types.graphql +++ b/src/features/order/order.types.graphql @@ -2,8 +2,8 @@ 주문 상태. 구매자·판매자·관리자 API가 공용으로 쓴다. 값은 늘어날 수 있으니 모르는 값을 받아도 화면이 죽지 않게 처리한다. 흐름은 `PENDING_PAYMENT → SUBMITTED → CONFIRMED → MADE → PICKED_UP`이며 어떤 상태에서도 -앞 단계로 되돌아갈 수 없다. 판매자가 직접 바꿀 수 있는 전이는 `SUBMITTED → CONFIRMED`, -`CONFIRMED → MADE`, `MADE → PICKED_UP`, `SUBMITTED·CONFIRMED·MADE → CANCELED`뿐이다. +앞 단계로 되돌아갈 수 없다. 판매자가 sellerUpdateOrderStatus로 바꿀 수 있는 전이는 `SUBMITTED → CONFIRMED`, +`CONFIRMED → MADE`, `MADE → PICKED_UP`뿐이고, 취소는 주체별 취소 mutation(cancelMyOrder·sellerCancelOrder·adminCancelOrder)으로만 한다. 판매자에게는 입금이 확인된(접수된) 주문만 보인다. """ enum OrderStatusType { @@ -19,7 +19,7 @@ enum OrderStatusType { PICKED_UP """노쇼. 구매자가 픽업 시간에 오지 않아 판매자가 처리한 종료 상태. 환불 없음, 리뷰 불가.""" NO_SHOW - """취소된 종료 상태. 취소 처리에는 사유(note)가 필수다.""" + """취소된 종료 상태. 주체·사유·사정·환불은 주문 상세의 cancellation에 있다.""" CANCELED } @@ -46,8 +46,132 @@ type OrderStatusHistory { toStatus: OrderStatusType! """변경 시각.""" changedAt: DateTime! - """변경 사유 메모. 취소(CANCELED) 전이에는 필수로 기록된다(관리자 취소는 '[관리자]' 접두).""" + """변경할 때 남긴 메모. 없으면 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 +} + +""" +주문 취소 정보. 취소된 주문에만 있다. +""" +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 OrderRefund { + 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 } """ diff --git a/src/features/order/policies/order-cancel.policy.spec.ts b/src/features/order/policies/order-cancel.policy.spec.ts new file mode 100644 index 00000000..d1997be5 --- /dev/null +++ b/src/features/order/policies/order-cancel.policy.spec.ts @@ -0,0 +1,213 @@ +import { + OrderCancelPolicy, + type OrderCancelRequest, +} from '@/features/order/policies/order-cancel.policy'; +import { + OrderActor, + OrderCancelFault, + OrderCancelReason, + OrderStatus, +} from '@/generated/prisma/client'; + +const policy = new OrderCancelPolicy(); +const ACTORS = Object.values(OrderActor); +const STATUSES = Object.values(OrderStatus); +const REASONS = Object.values(OrderCancelReason); + +const SELLER_REASONS = [ + 'DESIGN_NOT_FEASIBLE', + 'OUT_OF_MATERIALS', + 'SCHEDULE_UNAVAILABLE', + 'INAPPROPRIATE_REQUEST', + 'BUYER_REQUEST', + 'OTHER', +]; + +/** 기대 허용 표(주체:상태 → 사유). 구현과 따로 적어 두고 전 조합을 대조한다. */ +const ALLOWED: Record = { + 'BUYER:PENDING_PAYMENT': ['BUYER_REQUEST'], + 'BUYER:SUBMITTED': ['BUYER_REQUEST'], + 'SELLER:SUBMITTED': SELLER_REASONS, + 'SELLER:CONFIRMED': SELLER_REASONS, + 'SELLER:MADE': SELLER_REASONS, + 'ADMIN:PENDING_PAYMENT': [...SELLER_REASONS, 'PAYMENT_NOT_RECEIVED'], + 'ADMIN:SUBMITTED': SELLER_REASONS, + 'ADMIN:CONFIRMED': SELLER_REASONS, + 'ADMIN:MADE': SELLER_REASONS, + 'SYSTEM:PENDING_PAYMENT': ['PAYMENT_NOT_RECEIVED'], + 'SYSTEM:SUBMITTED': ['CONFIRM_TIMEOUT'], +}; + +function expectedReasonCode( + actor: OrderActor, + status: OrderStatus, + reason: OrderCancelReason, +): string | null { + const allowed = ALLOWED[`${actor}:${status}`]; + if (!allowed) return 'ORDER_NOT_CANCELLABLE'; + return allowed.includes(reason) ? null : 'CANCEL_REASON_NOT_ALLOWED'; +} + +describe('OrderCancelPolicy', () => { + describe('주체 × 상태 × 사유 전수', () => { + const cases = ACTORS.flatMap((actor) => + STATUSES.flatMap((status) => + REASONS.map( + (reason) => + [ + actor, + status, + reason, + expectedReasonCode(actor, status, reason), + ] as const, + ), + ), + ); + + it('표는 4 × 7 × 8 조합을 덮고 허용은 47개다', () => { + expect(cases).toHaveLength(224); + expect(cases.filter(([, , , code]) => code === null)).toHaveLength(47); + }); + + it.each(cases)('%s %s %s: %s', (actor, status, reason, code) => { + const run = () => + policy.decide( + { + actor, + reason, + fault: OrderCancelFault.SELLER, + }, + { status, paidAmount: 0 }, + ); + if (code === null) expect(run).not.toThrow(); + else expect(run).toThrowDomain(code); + }); + + it.each(ACTORS.flatMap((a) => STATUSES.map((s) => [a, s] as const)))( + 'reasonsFor·canCancel(%s, %s)는 같은 표를 따른다', + (actor, status) => { + const expected = ALLOWED[`${actor}:${status}`] ?? []; + expect([...policy.reasonsFor(actor, status)].sort()).toEqual( + [...expected].sort(), + ); + expect(policy.canCancel(actor, status)).toBe(expected.length > 0); + }, + ); + }); + + describe('상태 × 사정 × 환불액', () => { + const PAID = 30_000; + const admin = ( + overrides: Partial, + ): OrderCancelRequest => ({ + actor: OrderActor.ADMIN, + reason: OrderCancelReason.OTHER, + ...overrides, + }); + type Expect = { refundAmount: number; fault: string | null } | string; + const FAULTS = [null, OrderCancelFault.SELLER, OrderCancelFault.BUYER]; + const AMOUNTS = [null, -1, 0, 1.5, PAID, PAID + 1]; + + function expected( + status: OrderStatus, + fault: OrderCancelFault | null, + amount: number | null, + ): Expect { + if (status === 'PENDING_PAYMENT') return { refundAmount: 0, fault: null }; + if (status === 'SUBMITTED') return { refundAmount: PAID, fault: null }; + if (fault === null) return 'CANCEL_FAULT_REQUIRED'; + if (fault === 'SELLER') return { refundAmount: PAID, fault }; + if (amount === null) return 'REFUND_AMOUNT_REQUIRED'; + if (amount === 0 || amount === PAID) + return { refundAmount: amount, fault }; + return 'REFUND_AMOUNT_OUT_OF_RANGE'; + } + + const cases = ( + ['PENDING_PAYMENT', 'SUBMITTED', 'CONFIRMED', 'MADE'] as const + ).flatMap((status) => + FAULTS.flatMap((fault) => + AMOUNTS.map( + (amount) => + [status, fault, amount, expected(status, fault, amount)] as const, + ), + ), + ); + + it('표는 취소 가능 상태 4 × 사정 3 × 금액 6을 덮는다', () => { + expect(cases).toHaveLength(72); + }); + + it.each(cases)( + '%s fault=%s R=%s → %j', + (status, fault, refundAmount, result) => { + const run = () => + policy.decide(admin({ fault, refundAmount }), { + status, + paidAmount: PAID, + }); + if (typeof result === 'string') { + expect(run).toThrowDomain(result); + } else { + expect(run()).toEqual({ reason: 'OTHER', ...result }); + } + }, + ); + + it('범위 오류 메시지는 결제액 상한을 천 단위로 알려 준다', () => { + expect(() => + policy.decide( + admin({ fault: OrderCancelFault.BUYER, refundAmount: PAID + 1 }), + { status: OrderStatus.MADE, paidAmount: PAID }, + ), + ).toThrow('환불 금액은 0원 이상 30,000원 이하로 입력해 주세요.'); + }); + + it('확인된 결제가 없는 주문(결제액 0)은 구매자 사정 환불이 0원만 된다', () => { + const state = { status: OrderStatus.CONFIRMED, paidAmount: 0 }; + expect( + policy.decide( + admin({ fault: OrderCancelFault.BUYER, refundAmount: 0 }), + state, + ), + ).toEqual({ reason: 'OTHER', fault: 'BUYER', refundAmount: 0 }); + expect(() => + policy.decide( + admin({ fault: OrderCancelFault.BUYER, refundAmount: 1 }), + state, + ), + ).toThrowDomain('REFUND_AMOUNT_OUT_OF_RANGE'); + expect( + policy.decide(admin({ fault: OrderCancelFault.SELLER }), state), + ).toEqual({ reason: 'OTHER', fault: 'SELLER', refundAmount: 0 }); + }); + + it('취소할 수 없는 상태는 사유·금액보다 먼저 ORDER_NOT_CANCELLABLE이다', () => { + expect(() => + policy.decide( + admin({ + reason: OrderCancelReason.CONFIRM_TIMEOUT, + refundAmount: -1, + }), + { status: OrderStatus.PICKED_UP, paidAmount: PAID }, + ), + ).toThrowDomain('ORDER_NOT_CANCELLABLE'); + }); + }); + + describe('refundRule', () => { + const RULES = { + PENDING_PAYMENT: 'NO_REFUND', + SUBMITTED: 'FULL_REFUND', + CONFIRMED: 'BY_FAULT', + MADE: 'BY_FAULT', + PICKED_UP: null, + NO_SHOW: null, + CANCELED: null, + } satisfies Record; + + it.each(Object.entries(RULES))('%s → %s', (status, rule) => { + expect(policy.refundRule(status as OrderStatus)).toBe(rule); + }); + }); +}); diff --git a/src/features/order/policies/order-cancel.policy.ts b/src/features/order/policies/order-cancel.policy.ts new file mode 100644 index 00000000..adbe76de --- /dev/null +++ b/src/features/order/policies/order-cancel.policy.ts @@ -0,0 +1,138 @@ +import { Injectable } from '@nestjs/common'; + +import { DomainException } from '@/common/errors/error-catalog'; +import { + OrderCancelFault, + OrderCancelReason, + type OrderActor, + type OrderStatus, +} from '@/generated/prisma/client'; + +/** SDL CancelRefundRuleType. */ +export const CANCEL_REFUND_RULES = [ + 'NO_REFUND', + 'FULL_REFUND', + 'BY_FAULT', +] as const; +export type CancelRefundRule = (typeof CANCEL_REFUND_RULES)[number]; + +/** 잠금 시점의 취소 판정 재료. 돈이 있는 주문은 결제가 확인된 주문뿐이라 paidAmount는 미확인이면 0이다. */ +export interface OrderCancelState { + status: OrderStatus; + paidAmount: number; +} + +export interface OrderCancelRequest { + actor: OrderActor; + reason: OrderCancelReason; + fault?: OrderCancelFault | null; + refundAmount?: number | null; +} + +export interface OrderCancelDecision { + reason: OrderCancelReason; + fault: OrderCancelFault | null; + refundAmount: number; +} + +const SELLER_REASONS: readonly OrderCancelReason[] = [ + OrderCancelReason.DESIGN_NOT_FEASIBLE, + OrderCancelReason.OUT_OF_MATERIALS, + OrderCancelReason.SCHEDULE_UNAVAILABLE, + OrderCancelReason.INAPPROPRIATE_REQUEST, + OrderCancelReason.BUYER_REQUEST, + OrderCancelReason.OTHER, +]; + +/** 주체 → 취소할 수 있는 상태 → 고를 수 있는 사유. 표에 없는 조합은 거절한다(기본 거절). */ +const CANCEL_REASONS: Record< + OrderActor, + Partial> +> = { + BUYER: { + PENDING_PAYMENT: [OrderCancelReason.BUYER_REQUEST], + SUBMITTED: [OrderCancelReason.BUYER_REQUEST], + }, + SELLER: { + SUBMITTED: SELLER_REASONS, + CONFIRMED: SELLER_REASONS, + MADE: SELLER_REASONS, + }, + ADMIN: { + PENDING_PAYMENT: [ + ...SELLER_REASONS, + OrderCancelReason.PAYMENT_NOT_RECEIVED, + ], + SUBMITTED: SELLER_REASONS, + CONFIRMED: SELLER_REASONS, + MADE: SELLER_REASONS, + }, + SYSTEM: { + PENDING_PAYMENT: [OrderCancelReason.PAYMENT_NOT_RECEIVED], + SUBMITTED: [OrderCancelReason.CONFIRM_TIMEOUT], + }, +}; + +const REFUND_RULES: Partial> = { + PENDING_PAYMENT: 'NO_REFUND', + SUBMITTED: 'FULL_REFUND', + CONFIRMED: 'BY_FAULT', + MADE: 'BY_FAULT', +}; + +/** 주체별 사유와 상태 × 사정 × 환불액 판정. 저장은 OrderTransitionRepository.cancelLocked가 잠금 뒤 이 판정으로 한다. */ +@Injectable() +export class OrderCancelPolicy { + reasonsFor( + actor: OrderActor, + status: OrderStatus, + ): readonly OrderCancelReason[] { + return CANCEL_REASONS[actor][status] ?? []; + } + + canCancel(actor: OrderActor, status: OrderStatus): boolean { + return this.reasonsFor(actor, status).length > 0; + } + + refundRule(status: OrderStatus): CancelRefundRule | null { + return REFUND_RULES[status] ?? null; + } + + /** fault·refundAmount는 사정 선택 상태에서만 쓰고 그 밖에는 무시한다. */ + decide( + request: OrderCancelRequest, + state: OrderCancelState, + ): OrderCancelDecision { + const reasons = this.reasonsFor(request.actor, state.status); + if (reasons.length === 0) { + throw new DomainException('ORDER_NOT_CANCELLABLE'); + } + if (!reasons.includes(request.reason)) { + throw new DomainException('CANCEL_REASON_NOT_ALLOWED'); + } + const { reason } = request; + const rule = this.refundRule(state.status); + if (rule === 'NO_REFUND') return { reason, fault: null, refundAmount: 0 }; + if (rule === 'FULL_REFUND') { + return { reason, fault: null, refundAmount: state.paidAmount }; + } + const { fault, refundAmount } = request; + if (!fault) throw new DomainException('CANCEL_FAULT_REQUIRED'); + if (fault === OrderCancelFault.SELLER) { + return { reason, fault, refundAmount: state.paidAmount }; + } + if (refundAmount === undefined || refundAmount === null) { + throw new DomainException('REFUND_AMOUNT_REQUIRED'); + } + if ( + !Number.isSafeInteger(refundAmount) || + refundAmount < 0 || + refundAmount > state.paidAmount + ) { + throw new DomainException('REFUND_AMOUNT_OUT_OF_RANGE', { + max: state.paidAmount.toLocaleString('ko-KR'), + }); + } + return { reason, fault, refundAmount }; + } +} diff --git a/src/features/order/policies/order-status-transition.policy.spec.ts b/src/features/order/policies/order-status-transition.policy.spec.ts index 1f538b31..99d70b06 100644 --- a/src/features/order/policies/order-status-transition.policy.spec.ts +++ b/src/features/order/policies/order-status-transition.policy.spec.ts @@ -3,22 +3,17 @@ import { OrderStatus } from '@/generated/prisma/client'; const STATUSES = Object.values(OrderStatus); -/** 판매자 전이 허용 목록. 이 밖은 전부 거절이다(기본 거절). */ +/** 판매자 전이 허용 목록. 이 밖은 전부 거절이다(기본 거절). 취소는 sellerCancelOrder로만 한다. */ const ALLOWED = new Set([ 'SUBMITTED>CONFIRMED', 'CONFIRMED>MADE', 'MADE>PICKED_UP', - 'SUBMITTED>CANCELED', - 'CONFIRMED>CANCELED', - 'MADE>CANCELED', ]); function expectedCode(from: OrderStatus, to: OrderStatus): string | null { if (from === to) return 'ORDER_STATUS_UNCHANGED'; if (ALLOWED.has(`${from}>${to}`)) return null; - return to === 'CANCELED' - ? 'ORDER_NOT_CANCELLABLE' - : 'INVALID_ORDER_STATUS_TRANSITION'; + return 'INVALID_ORDER_STATUS_TRANSITION'; } describe('OrderStatusTransitionPolicy', () => { @@ -42,9 +37,9 @@ describe('OrderStatusTransitionPolicy', () => { STATUSES.map((to) => [from, to, expectedCode(from, to)] as const), ); - it('표는 상태 전 조합(7×7)을 덮고 허용 전이는 6개다', () => { + it('표는 상태 전 조합(7×7)을 덮고 허용 전이는 3개다(CANCELED로 가는 전이는 없다)', () => { expect(cases).toHaveLength(49); - expect(cases.filter(([, , code]) => code === null)).toHaveLength(6); + expect(cases.filter(([, , code]) => code === null)).toHaveLength(3); }); it.each(cases)('%s → %s: %s', (from, to, code) => { @@ -53,10 +48,4 @@ describe('OrderStatusTransitionPolicy', () => { else expect(run).toThrowDomain(code); }); }); - - describe('requiresCancellationNote', () => { - it.each(STATUSES)('%s', (to) => { - expect(policy.requiresCancellationNote(to)).toBe(to === 'CANCELED'); - }); - }); }); diff --git a/src/features/order/policies/order-status-transition.policy.ts b/src/features/order/policies/order-status-transition.policy.ts index a81958d1..a18e7e7e 100644 --- a/src/features/order/policies/order-status-transition.policy.ts +++ b/src/features/order/policies/order-status-transition.policy.ts @@ -5,13 +5,15 @@ import { OrderStatus } from '@/generated/prisma/client'; const ORDER_STATUS_VALUES: readonly string[] = Object.values(OrderStatus); -/** 판매자가 만들 수 있는 전이(to → 허용 from). 표에 없는 to는 거절한다 — 새 상태가 조용히 열리지 않게. */ +/** + * 판매자가 만들 수 있는 전이(to → 허용 from). 표에 없는 to는 거절한다 — 새 상태가 조용히 열리지 않게. + * 취소는 사유·사정·환불액이 필요해 sellerCancelOrder(OrderCancelPolicy)로만 한다. + */ const SELLER_TRANSITIONS: Partial> = { CONFIRMED: [OrderStatus.SUBMITTED], MADE: [OrderStatus.CONFIRMED], PICKED_UP: [OrderStatus.MADE], - CANCELED: [OrderStatus.SUBMITTED, OrderStatus.CONFIRMED, OrderStatus.MADE], }; @Injectable() @@ -26,14 +28,6 @@ export class OrderStatusTransitionPolicy { throw new DomainException('ORDER_STATUS_UNCHANGED'); } if (SELLER_TRANSITIONS[to]?.includes(from)) return; - throw new DomainException( - to === OrderStatus.CANCELED - ? 'ORDER_NOT_CANCELLABLE' - : 'INVALID_ORDER_STATUS_TRANSITION', - ); - } - - requiresCancellationNote(to: OrderStatus): boolean { - return to === OrderStatus.CANCELED; + throw new DomainException('INVALID_ORDER_STATUS_TRANSITION'); } } diff --git a/src/features/order/repositories/order-settlement-finalizer.helper.spec.ts b/src/features/order/repositories/order-settlement-finalizer.helper.spec.ts new file mode 100644 index 00000000..d71bae2b --- /dev/null +++ b/src/features/order/repositories/order-settlement-finalizer.helper.spec.ts @@ -0,0 +1,39 @@ +import { + confirmedPaidAmount, + settlementAmounts, +} from '@/features/order/repositories/order-settlement-finalizer.helper'; + +describe('order-settlement-finalizer.helper', () => { + describe('settlementAmounts: 수수료 원 미만 버림', () => { + it.each([ + // [기준액, bps, 수수료, 지급액] + [10_000, 0, 0, 10_000], + [10_000, 10_000, 10_000, 0], + [10_000, 1_000, 1_000, 9_000], + [10_001, 333, 333, 9_668], // 333.0333 + [3, 3_333, 0, 3], // 0.9999 + [3, 3_334, 1, 2], // 1.0002 + [1, 9_999, 0, 1], // 0.9999 + [29_999, 550, 1_649, 28_350], // 1649.945 + [4_294_967_295, 10_000, 4_294_967_295, 0], // INT UNSIGNED 상한에서도 정수 연산이 정확하다 + ])( + '기준액 %d × %dbp → 수수료 %d, 지급액 %d', + (base, bps, commission, payout) => { + expect(settlementAmounts(base, bps)).toEqual({ + commissionAmount: commission, + payoutAmount: payout, + }); + }, + ); + }); + + describe('confirmedPaidAmount', () => { + it.each([ + ['결제 없음(결제 도입 전 주문)', null, 0], + ['입금 대기', { amount: 30_000, confirmed_at: null }, 0], + ['입금 확인', { amount: 30_000, confirmed_at: new Date() }, 30_000], + ])('%s → %d', (_label, payment, expected) => { + expect(confirmedPaidAmount(payment)).toBe(expected); + }); + }); +}); diff --git a/src/features/order/repositories/order-settlement-finalizer.helper.ts b/src/features/order/repositories/order-settlement-finalizer.helper.ts new file mode 100644 index 00000000..a1f49e55 --- /dev/null +++ b/src/features/order/repositories/order-settlement-finalizer.helper.ts @@ -0,0 +1,72 @@ +import type { PaymentStatus, Prisma } from '@/generated/prisma/client'; + +const BPS_DENOMINATOR = 10_000; + +export interface LockedPayment { + id: bigint; + status: PaymentStatus; + amount: number; + confirmed_at: Date | null; +} + +/** 결제 행을 잠그고 읽는다(잠금 순서 order → payment). 결제 도입 전 주문이면 null. */ +export async function lockPayment( + tx: Prisma.TransactionClient, + orderId: bigint, +): Promise { + const [row] = await tx.$queryRaw< + { + id: bigint; + status: PaymentStatus; + amount: bigint; + confirmed_at: Date | null; + }[] + >`SELECT id, status, amount, confirmed_at FROM payment WHERE order_id = ${orderId} FOR UPDATE`; + // raw는 INT UNSIGNED를 bigint로 돌려준다 + return row ? { ...row, amount: Number(row.amount) } : null; +} + +/** 돈이 있는 주문은 결제가 확인된 주문뿐이다. */ +export function confirmedPaidAmount( + payment: Pick | null, +): number { + return payment?.confirmed_at ? payment.amount : 0; +} + +/** 수수료는 원 미만 버림, 지급액 = 기준액 − 수수료. */ +export function settlementAmounts( + baseAmount: number, + commissionRateBps: number, +): { commissionAmount: number; payoutAmount: number } { + const commissionAmount = Math.floor( + (baseAmount * commissionRateBps) / BPS_DENOMINATOR, + ); + return { commissionAmount, payoutAmount: baseAmount - commissionAmount }; +} + +/** + * 정산 확정: 기준액·수수료·확정 시각을 주문에 고정한다. 기준액은 호출자가 확인된 결제액(confirmedPaidAmount)에서 + * 만든다 — 픽업 완료·노쇼는 결제액, 구매자 사정 취소는 결제액 − 환불액. 0 이하면(미확인·전액 환불) 확정하지 않는다. + * 주문·결제 행을 잠근 tx 안에서 부른다. + */ +export async function finalizeSettlementLocked( + tx: Prisma.TransactionClient, + order: { id: bigint; commission_rate_bps: number }, + baseAmount: number, + now: Date, +): Promise { + if (baseAmount <= 0) return false; + const { commissionAmount } = settlementAmounts( + baseAmount, + order.commission_rate_bps, + ); + await tx.order.update({ + where: { id: order.id }, + data: { + settlement_base_amount: baseAmount, + commission_amount: commissionAmount, + settlement_finalized_at: now, + }, + }); + return true; +} diff --git a/src/features/order/repositories/order-transition.repository.spec.ts b/src/features/order/repositories/order-transition.repository.spec.ts index 71efaf29..23bf0160 100644 --- a/src/features/order/repositories/order-transition.repository.spec.ts +++ b/src/features/order/repositories/order-transition.repository.spec.ts @@ -1,15 +1,27 @@ import { AUDIT_LOG_REPOSITORY } from '@/features/audit-log'; import { AuditLogRepository } from '@/features/audit-log/repositories/audit-log.repository'; import { ORDER_STATUS_CHANGED } from '@/features/order/events/order-status-changed.event'; +import { REFUND_REQUESTED } from '@/features/order/events/refund-requested.event'; +import { + OrderCancelPolicy, + type OrderCancelDecision, + type OrderCancelRequest, +} from '@/features/order/policies/order-cancel.policy'; import { assertPaymentConfirmable } from '@/features/order/policies/payment-confirm.policy'; import { OrderTransitionRepository, + type CancelOrderArgs, type ConfirmPaymentArgs, } from '@/features/order/repositories/order-transition.repository'; -import type { PrismaClient } from '@/generated/prisma/client'; +import type { OrderStatus, PrismaClient } from '@/generated/prisma/client'; import { disconnectTestPrismaClient } from '@/test/db/prisma-test-client'; import { closeTruncateConnection, truncateAll } from '@/test/db/truncate'; -import { createAccount, createOrder, createPayment } from '@/test/factories'; +import { + createAccount, + createOrder, + createOrderItem, + createPayment, +} from '@/test/factories'; import { createTestingModuleWithRealDb } from '@/test/modules/testing-module.builder'; import { outboxPublisherProviders } from '@/test/outbox'; @@ -176,4 +188,350 @@ describe('OrderTransitionRepository (real DB)', () => { ).resolves.toMatchObject({ confirm_source: 'ADMIN' }); }); }); + describe('cancel', () => { + const policy = new OrderCancelPolicy(); + const PAID = 30_000; + + async function paidOrder( + status: OrderStatus, + opts: { confirmed?: boolean; commissionRateBps?: number } = {}, + ) { + const order = await createOrder(prisma, { + status, + total_price: PAID, + commission_rate_bps: opts.commissionRateBps ?? 0, + }); + const item = await createOrderItem(prisma, { order_id: order.id }); + const confirmed = opts.confirmed ?? status !== 'PENDING_PAYMENT'; + const payment = await createPayment(prisma, { + order_id: order.id, + status: confirmed ? 'CONFIRMED' : 'PENDING', + confirmed_at: confirmed ? NOW : null, + }); + return { order, item, payment }; + } + + function cancelArgs( + orderId: bigint, + request: Partial = {}, + overrides: Partial = {}, + ): CancelOrderArgs { + return { + orderId, + actor: 'ADMIN', + actorAccountId: 1n, + scope: { kind: 'any' }, + note: null, + now: NOW, + decide: (state) => + policy.decide({ actor: 'ADMIN', reason: 'OTHER', ...request }, state), + ...overrides, + }; + } + + it('입금 대기 취소는 결제를 CANCELED로 닫고 환불·정산 없이 이력·이벤트를 남긴다', async () => { + const { order, payment } = await paidOrder('PENDING_PAYMENT'); + + await repo.cancel( + cancelArgs(order.id, { reason: 'PAYMENT_NOT_RECEIVED' }), + ); + + await expect( + prisma.payment.findUniqueOrThrow({ where: { id: payment.id } }), + ).resolves.toMatchObject({ status: 'CANCELED', canceled_at: NOW }); + await expect( + prisma.order.findUniqueOrThrow({ where: { id: order.id } }), + ).resolves.toMatchObject({ + status: 'CANCELED', + canceled_at: NOW, + settlement_finalized_at: null, + }); + await expect( + prisma.orderStatusHistory.findFirstOrThrow({ + where: { order_id: order.id }, + }), + ).resolves.toMatchObject({ + from_status: 'PENDING_PAYMENT', + to_status: 'CANCELED', + actor_type: 'ADMIN', + cancel_reason: 'PAYMENT_NOT_RECEIVED', + cancel_fault: null, + refund_amount: 0, + }); + expect(await prisma.refund.count()).toBe(0); + const events = await prisma.outbox.findMany(); + expect(events.map((e) => e.event_type)).toEqual([ORDER_STATUS_CHANGED]); + expect(events[0].payload_json).toMatchObject({ + fromStatus: 'PENDING_PAYMENT', + toStatus: 'CANCELED', + actorType: 'ADMIN', + cancelReason: 'PAYMENT_NOT_RECEIVED', + refundAmount: 0, + pickupAt: order.pickup_at.toISOString(), + }); + }); + + it('접수 취소는 확인된 결제를 그대로 두고 결제액 전액 환불(계좌 입력 대기)과 환불 이벤트를 남긴다', async () => { + const { order, item, payment } = await paidOrder('SUBMITTED'); + + await repo.cancel(cancelArgs(order.id)); + + await expect( + prisma.payment.findUniqueOrThrow({ where: { id: payment.id } }), + ).resolves.toMatchObject({ status: 'CONFIRMED', canceled_at: null }); + const refund = await prisma.refund.findFirstOrThrow(); + expect(refund).toMatchObject({ + order_id: order.id, + kind: 'CANCEL', + cancel_order_id: order.id, + amount: PAID, + status: 'AWAITING_ACCOUNT', + requested_at: NOW, + account_number_enc: null, + }); + const events = await prisma.outbox.findMany({ orderBy: { id: 'asc' } }); + expect(events.map((e) => e.event_type)).toEqual([ + ORDER_STATUS_CHANGED, + REFUND_REQUESTED, + ]); + expect(events[1]).toMatchObject({ + aggregate_type: 'order', + aggregate_id: order.id.toString(), + payload_json: { + refundId: refund.id.toString(), + orderId: order.id.toString(), + orderNumber: order.order_number, + buyerAccountId: order.account_id.toString(), + kind: 'CANCEL', + amount: PAID, + storeId: item.store_id.toString(), + productId: item.product_id.toString(), + productName: 'Product snapshot', + }, + }); + await expect( + prisma.order.findUniqueOrThrow({ where: { id: order.id } }), + ).resolves.toMatchObject({ settlement_finalized_at: null }); + }); + + it.each([ + // [사정, 환불액, 기대 환불, 정산 기준액] + ['SELLER', null, PAID, null], + ['BUYER', 0, null, PAID], + ['BUYER', 10_001, 10_001, PAID - 10_001], + ['BUYER', PAID, PAID, null], + ] as const)( + '확정 뒤 %s 사정 R=%s: 환불 %s, 남는 금액 %s를 취소 시각에 정산 확정한다', + async (fault, refundAmount, refund, base) => { + const { order } = await paidOrder('CONFIRMED', { + commissionRateBps: 333, + }); + + await repo.cancel(cancelArgs(order.id, { fault, refundAmount })); + + const refunds = await prisma.refund.findMany(); + expect(refunds.map((r) => r.amount)).toEqual( + refund === null ? [] : [refund], + ); + const row = await prisma.order.findUniqueOrThrow({ + where: { id: order.id }, + }); + expect(row).toMatchObject( + base === null + ? { + settlement_base_amount: null, + commission_amount: null, + settlement_finalized_at: null, + } + : { + settlement_base_amount: base, + commission_amount: Math.floor((base * 333) / 10_000), + settlement_finalized_at: NOW, + settlement_id: null, + }, + ); + await expect( + prisma.orderStatusHistory.findFirstOrThrow({ + where: { order_id: order.id }, + }), + ).resolves.toMatchObject({ + cancel_fault: fault, + refund_amount: refund ?? 0, + }); + }, + ); + + it('판정에는 잠금 시점 상태와 확인된 결제액만 넘기고(미확인 결제는 0), 던지면 아무것도 남지 않는다', async () => { + const confirmed = await paidOrder('MADE'); + const unconfirmed = await paidOrder('SUBMITTED', { confirmed: false }); + const legacy = await createOrder(prisma, { status: 'CONFIRMED' }); + const seen: unknown[] = []; + const reject = (): OrderCancelDecision => { + throw new Error('거절'); + }; + + for (const id of [confirmed.order.id, unconfirmed.order.id, legacy.id]) { + await expect( + repo.cancel( + cancelArgs( + id, + {}, + { + decide: (state) => { + seen.push(state); + return reject(); + }, + }, + ), + ), + ).rejects.toThrow('거절'); + } + + expect(seen).toEqual([ + { status: 'MADE', paidAmount: PAID }, + { status: 'SUBMITTED', paidAmount: 0 }, + { status: 'CONFIRMED', paidAmount: 0 }, + ]); + expect(await prisma.order.count({ where: { status: 'CANCELED' } })).toBe( + 0, + ); + expect(await prisma.orderStatusHistory.count()).toBe(0); + expect( + await prisma.payment.count({ where: { status: 'CANCELED' } }), + ).toBe(0); + expect(await prisma.outbox.count()).toBe(0); + expect(await prisma.auditLog.count()).toBe(0); + }); + + it('범위 밖 주문은 null이다: 다른 구매자, 입금 전·다른 매장(판매자), 삭제된 주문', async () => { + const { order, item } = await paidOrder('SUBMITTED'); + const pending = await paidOrder('PENDING_PAYMENT'); + const deleted = await createOrder(prisma, { deleted_at: new Date() }); + + for (const [id, scope] of [ + [order.id, { kind: 'buyer', accountId: order.account_id + 1n }], + [order.id, { kind: 'store', storeId: item.store_id + 1n }], + [pending.order.id, { kind: 'store', storeId: pending.item.store_id }], + [deleted.id, { kind: 'any' }], + ] as const) { + await expect( + repo.cancel(cancelArgs(id, {}, { scope })), + ).resolves.toBeNull(); + } + expect(await prisma.orderStatusHistory.count()).toBe(0); + + await expect( + repo.cancel( + cancelArgs( + order.id, + {}, + { scope: { kind: 'buyer', accountId: order.account_id } }, + ), + ), + ).resolves.toMatchObject({ status: 'CANCELED' }); + }); + + it('감사는 처리자가 있을 때만, 매장은 판매자에게 보이는(접수된) 주문만 남긴다', async () => { + const submitted = await paidOrder('SUBMITTED'); + const pending = await paidOrder('PENDING_PAYMENT'); + const system = await paidOrder('PENDING_PAYMENT'); + + await repo.cancel(cancelArgs(submitted.order.id, {}, { note: '메모' })); + await repo.cancel(cancelArgs(pending.order.id)); + await repo.cancel( + cancelArgs( + system.order.id, + {}, + { + actor: 'SYSTEM', + actorAccountId: null, + decide: (state) => + policy.decide( + { actor: 'SYSTEM', reason: 'PAYMENT_NOT_RECEIVED' }, + state, + ), + }, + ), + ); + + const audits = await prisma.auditLog.findMany({ orderBy: { id: 'asc' } }); + expect(audits).toHaveLength(2); + expect(audits[0]).toMatchObject({ + target_id: submitted.order.id, + store_id: submitted.item.store_id, + action: 'STATUS_CHANGE', + before_json: { status: 'SUBMITTED' }, + after_json: { + status: 'CANCELED', + actorType: 'ADMIN', + reason: 'OTHER', + fault: null, + refundAmount: PAID, + note: '메모', + }, + }); + expect(audits[1]).toMatchObject({ + target_id: pending.order.id, + store_id: null, + }); + await expect( + prisma.orderStatusHistory.findFirstOrThrow({ + where: { order_id: system.order.id }, + }), + ).resolves.toMatchObject({ + actor_type: 'SYSTEM', + actor_account_id: null, + }); + const systemEvent = await prisma.outbox.findFirstOrThrow({ + where: { aggregate_id: system.order.id.toString() }, + }); + expect(systemEvent.actor_account_id).toBeNull(); + }); + + it('동시에 두 번 취소해도 하나만 성공하고 환불은 1건이다', async () => { + const { order } = await paidOrder('SUBMITTED'); + + const results = await Promise.allSettled([ + repo.cancel(cancelArgs(order.id)), + repo.cancel(cancelArgs(order.id)), + ]); + + expect(results.map((r) => r.status).sort()).toEqual([ + 'fulfilled', + 'rejected', + ]); + const rejected = results.find((r) => r.status === 'rejected'); + expect((rejected as PromiseRejectedResult).reason).toMatchObject({ + code: 'ORDER_NOT_CANCELLABLE', + }); + expect(await prisma.refund.count()).toBe(1); + expect(await prisma.orderStatusHistory.count()).toBe(1); + }); + + // 정책을 거치지 않는 경로가 생겨도 주문당 취소 환불은 DB가 1건으로 막는다 + it('반증: 같은 주문의 취소 환불(cancel_order_id)은 두 번째 행이 unique로 거절되고, 입금 반환은 NULL이라 여러 건이 공존한다', async () => { + const { order } = await paidOrder('SUBMITTED'); + await repo.cancel(cancelArgs(order.id)); + const base = { + order_id: order.id, + amount: 1_000, + requested_at: NOW, + }; + + await expect( + prisma.refund.create({ + data: { ...base, kind: 'CANCEL', cancel_order_id: order.id }, + }), + ).rejects.toMatchObject({ code: 'P2002' }); + await prisma.refund.createMany({ + data: [ + { ...base, kind: 'DEPOSIT_RETURN' }, + { ...base, kind: 'DEPOSIT_RETURN' }, + ], + }); + expect(await prisma.refund.count({ where: { order_id: order.id } })).toBe( + 3, + ); + }); + }); }); diff --git a/src/features/order/repositories/order-transition.repository.ts b/src/features/order/repositories/order-transition.repository.ts index d9a201fc..b1fae4d8 100644 --- a/src/features/order/repositories/order-transition.repository.ts +++ b/src/features/order/repositories/order-transition.repository.ts @@ -7,6 +7,16 @@ import { } from '@/features/audit-log'; import { orderStatusChangedEvent } from '@/features/order/events/order-status-changed.event'; import { orderSubmittedEvent } from '@/features/order/events/order-submitted.event'; +import { refundRequestedEvent } from '@/features/order/events/refund-requested.event'; +import type { + OrderCancelDecision, + OrderCancelState, +} from '@/features/order/policies/order-cancel.policy'; +import { + confirmedPaidAmount, + finalizeSettlementLocked, + lockPayment, +} from '@/features/order/repositories/order-settlement-finalizer.helper'; import { adminOrderInclude, type AdminOrderRow, @@ -16,10 +26,12 @@ import { AuditActionType, AuditTargetType, OrderActor, + OrderCancelFault, OrderStatus, PaymentConfirmSource, PaymentStatus, - type Prisma, + Prisma, + RefundKind, } from '@/generated/prisma/client'; import { activeWhere, PrismaService } from '@/prisma'; @@ -43,10 +55,41 @@ export interface ConfirmPaymentArgs { assertConfirmable: (state: PaymentConfirmState) => void; } +/** 취소 대상 범위. 범위 밖 주문은 없는 주문과 같다. */ +export type OrderCancelScope = + | { kind: 'any' } + | { kind: 'buyer'; accountId: bigint } + /** 판매자에게 보이는(접수된) 자기 매장 주문 */ + | { kind: 'store'; storeId: bigint }; + +export interface CancelOrderArgs { + orderId: bigint; + actor: OrderActor; + /** 시스템 취소는 null(감사 기록 없음) */ + actorAccountId: bigint | null; + scope: OrderCancelScope; + note: string | null; + now: Date; + /** 잠금 시점 재료로 사유·사정·환불액을 정한다. 던지면 tx가 롤백되고 예외가 그대로 나간다. */ + decide: (state: OrderCancelState) => OrderCancelDecision; +} + /** 접수 뒤 판매자 확정 마감: 확인 + 24시간과 픽업 시각 중 이른 쪽. */ const CONFIRM_WINDOW_MS = DAY_MS; -/** 주문 상태 전이 잠금 단위. 잠금 순서는 order → payment. */ +function cancelScopeSql(scope: OrderCancelScope): Prisma.Sql { + switch (scope.kind) { + case 'buyer': + return Prisma.sql`AND o.account_id = ${scope.accountId}`; + case 'store': + return Prisma.sql`AND o.submitted_at IS NOT NULL AND EXISTS ( + SELECT 1 FROM order_item i WHERE i.order_id = o.id AND i.store_id = ${scope.storeId})`; + default: + return Prisma.empty; + } +} + +/** 주문 상태 전이 잠금 단위. 잠금 순서는 order → payment → refund. */ @Injectable() export class OrderTransitionRepository { constructor( @@ -157,6 +200,8 @@ export class OrderTransitionRepository { storeName: firstItem?.store_name_snapshot ?? null, productId: firstItem?.product_id ?? null, productName: firstItem?.product_name_snapshot ?? null, + actorType, + pickupAt: updated.pickup_at, occurredAt: args.now, actorAccountId: args.actorAccountId, }), @@ -199,4 +244,146 @@ export class OrderTransitionRepository { }); return updated; } + + /** 없거나 범위 밖 주문이면 null. */ + async cancel(args: CancelOrderArgs): Promise { + return this.prisma.$transaction((tx) => this.cancelLocked(tx, args)); + } + + /** + * 취소. 판정(decide)은 잠금 읽기 결과로 한다. 입금 전 결제는 CANCELED로 닫고 확인된 결제는 그대로 둔다(돌려줄 돈은 + * 환불이 맡는다). 환불액이 있으면 환불(AWAITING_ACCOUNT)을, 구매자 사정 취소의 남는 금액은 정산 확정을 같은 tx에 남긴다. + */ + async cancelLocked( + tx: Prisma.TransactionClient, + args: CancelOrderArgs, + ): Promise { + const [locked] = await tx.$queryRaw< + { + id: bigint; + status: OrderStatus; + commission_rate_bps: number; + submitted_at: Date | null; + }[] + >` + SELECT o.id, o.status, o.commission_rate_bps, o.submitted_at FROM \`order\` o + WHERE o.id = ${args.orderId} AND o.deleted_at IS NULL ${cancelScopeSql(args.scope)} + FOR UPDATE OF o`; + if (!locked) return null; + const payment = await lockPayment(tx, locked.id); + const paidAmount = confirmedPaidAmount(payment); + const decision = args.decide({ status: locked.status, paidAmount }); + + if (payment?.status === PaymentStatus.PENDING) { + await tx.payment.update({ + where: { id: payment.id }, + data: { status: PaymentStatus.CANCELED, canceled_at: args.now }, + }); + } + const updated = await tx.order.update({ + where: { id: locked.id }, + data: { status: OrderStatus.CANCELED, canceled_at: args.now }, + include: adminOrderInclude, + }); + if (decision.fault === OrderCancelFault.BUYER) { + await finalizeSettlementLocked( + tx, + locked, + paidAmount - decision.refundAmount, + args.now, + ); + } + await tx.orderStatusHistory.create({ + data: { + order_id: locked.id, + from_status: locked.status, + to_status: OrderStatus.CANCELED, + changed_at: args.now, + actor_type: args.actor, + actor_account_id: args.actorAccountId, + cancel_reason: decision.reason, + cancel_fault: decision.fault, + refund_amount: decision.refundAmount, + note: args.note, + }, + }); + const refund = + decision.refundAmount > 0 + ? await tx.refund.create({ + data: { + order_id: locked.id, + kind: RefundKind.CANCEL, + cancel_order_id: locked.id, + amount: decision.refundAmount, + requested_at: args.now, + }, + }) + : null; + + const firstItem = await tx.orderItem.findFirst({ + where: { order_id: locked.id, ...activeWhere }, + orderBy: { id: 'asc' }, + select: { + store_id: true, + product_id: true, + product_name_snapshot: true, + store_name_snapshot: true, + }, + }); + const snapshot = { + orderId: locked.id, + orderNumber: updated.order_number, + buyerAccountId: updated.account_id, + storeId: firstItem?.store_id ?? null, + storeName: firstItem?.store_name_snapshot ?? null, + productId: firstItem?.product_id ?? null, + productName: firstItem?.product_name_snapshot ?? null, + occurredAt: args.now, + actorAccountId: args.actorAccountId, + }; + await this.outbox.publish( + tx, + orderStatusChangedEvent({ + ...snapshot, + fromStatus: locked.status, + toStatus: OrderStatus.CANCELED, + actorType: args.actor, + pickupAt: updated.pickup_at, + cancelReason: decision.reason, + refundAmount: decision.refundAmount, + }), + ); + if (refund) { + await this.outbox.publish( + tx, + refundRequestedEvent({ + ...snapshot, + refundId: refund.id, + kind: refund.kind, + amount: refund.amount, + }), + ); + } + + if (args.actorAccountId !== null) { + await this.auditLogs.recordAudit(tx, { + actorAccountId: args.actorAccountId, + // 입금 전 주문은 판매자에게 보이지 않으므로 매장 감사 로그에도 남기지 않는다 + storeId: locked.submitted_at ? (firstItem?.store_id ?? null) : null, + targetType: AuditTargetType.ORDER, + targetId: locked.id, + action: AuditActionType.STATUS_CHANGE, + beforeJson: { status: locked.status }, + afterJson: { + status: OrderStatus.CANCELED, + actorType: args.actor, + reason: decision.reason, + fault: decision.fault, + refundAmount: decision.refundAmount, + note: args.note, + }, + }); + } + return updated; + } } diff --git a/src/features/order/repositories/order.repository.spec.ts b/src/features/order/repositories/order.repository.spec.ts index e371d5e9..7f216a73 100644 --- a/src/features/order/repositories/order.repository.spec.ts +++ b/src/features/order/repositories/order.repository.spec.ts @@ -723,7 +723,7 @@ describe('OrderRepository (real DB)', () => { orderId: order.id, storeId: store.id, actorAccountId: seller.id, - toStatus: OrderStatus.CANCELED, + toStatus: OrderStatus.CONFIRMED, assertTransition, note: null, now: new Date(), @@ -832,43 +832,31 @@ describe('OrderRepository (real DB)', () => { expect(auditLogs[0].user_agent).toBe('seller-app'); }); - it('CANCELED 전환: canceled_at 갱신되고 ORDER_CANCELED notification이 생성된다', async () => { + it('전이 이벤트에 판매자 주체와 픽업 일시를 싣는다', async () => { const store = await createStore(prisma); const buyer = await setupBuyer(); const order = await setupOrderForStore(store.id, buyer.id); const seller = await createAccount(prisma, { account_type: 'SELLER' }); - const now = new Date('2026-04-22T10:00:00Z'); - const updated = await repo.updateOrderStatusBySeller({ + await repo.updateOrderStatusBySeller({ orderId: order.id, storeId: store.id, actorAccountId: seller.id, - toStatus: OrderStatus.CANCELED, + toStatus: OrderStatus.CONFIRMED, assertTransition: () => undefined, - note: '재고 부족', - now, + note: null, + now: new Date('2026-04-22T10:00:00Z'), }); - expect(updated?.status).toBe('CANCELED'); - expect(updated?.canceled_at?.toISOString()).toBe(now.toISOString()); - - // 취소도 구매자에게 알린다(판매자·운영자 취소 공통) - await drainOutbox(dispatcher); - const notifications = await prisma.notification.findMany({ - where: { order_id: order.id }, + const event = await prisma.outbox.findFirstOrThrow({ + where: { event_type: 'order.status_changed' }, }); - expect(notifications).toHaveLength(1); - expect(notifications[0]).toMatchObject({ - account_id: buyer.id, - type: 'ORDER_STATUS', - event: 'ORDER_CANCELED', - store_id: store.id, - }); - - const histories = await prisma.orderStatusHistory.findMany({ - where: { order_id: order.id }, + expect(event.payload_json).toMatchObject({ + actorType: 'SELLER', + cancelReason: null, + refundAmount: null, + pickupAt: order.pickup_at.toISOString(), }); - expect(histories[0].note).toBe('재고 부족'); }); it('CONFIRMED→MADE→PICKED_UP 연속 전이 시 각 타임스탬프 컬럼이 누적 기록된다', async () => { diff --git a/src/features/order/repositories/order.repository.ts b/src/features/order/repositories/order.repository.ts index cbe65ef8..f456a930 100644 --- a/src/features/order/repositories/order.repository.ts +++ b/src/features/order/repositories/order.repository.ts @@ -12,6 +12,11 @@ import { PENDING_PAYMENT_LIMIT, withPendingPaymentLock, } from '@/features/order/repositories/order-pending-payment-lock.helper'; +import { + confirmedPaidAmount, + finalizeSettlementLocked, + lockPayment, +} from '@/features/order/repositories/order-settlement-finalizer.helper'; import { orderPaymentSelect, type OrderPaymentRow, @@ -24,6 +29,7 @@ import { OrderStatus, PaymentMethod, Prisma, + RefundKind, type AccountType, type PaymentStatus, } from '@/generated/prisma/client'; @@ -83,6 +89,7 @@ const adminOrderDetailInclude = { }, }, payment: true, + refunds: { orderBy: { id: 'asc' } }, status_histories: { where: activeWhere, orderBy: { changed_at: 'desc' } }, items: { where: activeWhere, @@ -628,6 +635,7 @@ export class OrderRepository { }, include: { payment: { select: orderPaymentSelect }, + refunds: { orderBy: { id: 'asc' } }, status_histories: { where: activeWhere, orderBy: { changed_at: 'asc' }, @@ -837,6 +845,8 @@ export class OrderRepository { // 유저측 상세(findOrderDetailByUser)와 동일하게 soft-delete 자식을 가드한다 include: { payment: { select: { method: true } }, + // 입금 반환은 구매자와 플랫폼 사이 일이라 취소 환불만 본다 + refunds: { where: { kind: RefundKind.CANCEL } }, // 입금 대기 이력은 판매자에게 보이지 않는다 status_histories: { where: { @@ -876,8 +886,8 @@ export class OrderRepository { /** * 판매자 상태 변경. 주문 행을 잠근(FOR UPDATE) 뒤 잠금 시점 상태로 전이를 다시 판정한다 — - * 관리자 강제 취소(cancelOrderByAdmin)와 같은 잠금을 쓰므로 둘이 교차해도 나중 쪽은 바뀐 - * 상태를 보고 거절된다(잠금 없이 읽으면 CANCELED 위에 CONFIRMED를 덮어쓴다). + * 취소(OrderTransitionRepository.cancelLocked)와 같은 잠금을 쓰므로 둘이 교차해도 나중 쪽은 바뀐 + * 상태를 보고 거절된다(잠금 없이 읽으면 CANCELED 위에 CONFIRMED를 덮어쓴다). 픽업 완료는 정산을 함께 확정한다. * assertTransition이 던지면 트랜잭션은 롤백되고 예외가 그대로 전파된다. */ async updateOrderStatusBySeller(args: { @@ -892,8 +902,10 @@ export class OrderRepository { userAgent?: string; }) { return this.prisma.$transaction(async (tx) => { - const locked = await tx.$queryRaw<{ id: bigint; status: OrderStatus }[]>` - SELECT o.id, o.status FROM \`order\` o + const locked = await tx.$queryRaw< + { id: bigint; status: OrderStatus; commission_rate_bps: number }[] + >` + SELECT o.id, o.status, o.commission_rate_bps FROM \`order\` o WHERE o.id = ${args.orderId} AND o.deleted_at IS NULL AND o.submitted_at IS NOT NULL AND EXISTS ( @@ -923,12 +935,18 @@ export class OrderRepository { ...(args.toStatus === OrderStatus.PICKED_UP ? { picked_up_at: args.now } : {}), - ...(args.toStatus === OrderStatus.CANCELED - ? { canceled_at: args.now } - : {}), }, include: sellerOrderSummaryInclude(args.storeId), }); + if (args.toStatus === OrderStatus.PICKED_UP) { + const payment = await lockPayment(tx, order.id); + await finalizeSettlementLocked( + tx, + order, + confirmedPaidAmount(payment), + args.now, + ); + } await tx.orderStatusHistory.create({ data: { @@ -965,6 +983,8 @@ export class OrderRepository { storeName: firstItem?.store_name_snapshot ?? null, productId: firstItem?.product_id ?? null, productName: firstItem?.product_name_snapshot ?? null, + actorType: OrderActor.SELLER, + pickupAt: updatedOrder.pickup_at, occurredAt: args.now, actorAccountId: args.actorAccountId, }), @@ -1079,90 +1099,6 @@ export class OrderRepository { }); } - /** - * 관리자 강제 취소. 주문 행을 잠근(FOR UPDATE) 뒤 트랜잭션 안에서 현재 상태로 취소 가능 여부를 - * 다시 판정한다 — 판매자 상태 변경과 교차해도 둘 다 커밋되지 않게. 이력·알림(ORDER_CANCELED)· - * 감사(store_id는 첫 품목 매장)는 판매자 취소와 같은 규칙으로 같은 트랜잭션에 남긴다. - */ - async cancelOrderByAdmin(args: { - orderId: bigint; - actorAccountId: bigint; - note: string; - now: Date; - canCancelFrom: (status: OrderStatus) => boolean; - }): Promise { - return this.prisma.$transaction(async (tx) => { - const locked = await tx.$queryRaw<{ id: bigint; status: OrderStatus }[]>` - SELECT id, status FROM \`order\` - WHERE id = ${args.orderId} AND deleted_at IS NULL - FOR UPDATE`; - const current = locked[0]; - if (!current) return 'not-found'; - if (!args.canCancelFrom(current.status)) return 'not-cancellable'; - - const updated = await tx.order.update({ - where: { id: current.id }, - data: { status: OrderStatus.CANCELED, canceled_at: args.now }, - include: adminOrderInclude, - }); - await tx.orderStatusHistory.create({ - data: { - order_id: current.id, - from_status: current.status, - to_status: OrderStatus.CANCELED, - changed_at: args.now, - actor_type: OrderActor.ADMIN, - actor_account_id: args.actorAccountId, - note: args.note, - }, - }); - - const firstItem = await tx.orderItem.findFirst({ - where: { order_id: current.id, ...activeWhere }, - orderBy: { id: 'asc' }, - select: { - product_id: true, - store_id: true, - product_name_snapshot: true, - store_name_snapshot: true, - }, - }); - // 상태 전이 이벤트(outbox, 같은 tx) — 판매자 취소와 같은 계약 - await this.outbox.publish( - tx, - orderStatusChangedEvent({ - orderId: current.id, - orderNumber: updated.order_number, - buyerAccountId: updated.account_id, - fromStatus: current.status, - toStatus: OrderStatus.CANCELED, - storeId: firstItem?.store_id ?? null, - storeName: firstItem?.store_name_snapshot ?? null, - productId: firstItem?.product_id ?? null, - productName: firstItem?.product_name_snapshot ?? null, - occurredAt: args.now, - actorAccountId: args.actorAccountId, - }), - ); - - await this.auditLogs.recordAudit(tx, { - actorAccountId: args.actorAccountId, - storeId: firstItem?.store_id ?? null, - targetType: AuditTargetType.ORDER, - targetId: current.id, - action: AuditActionType.STATUS_CHANGE, - beforeJson: { status: current.status }, - afterJson: { - status: OrderStatus.CANCELED, - note: args.note, - byAdmin: true, - }, - }); - - return updated; - }); - } - /** 매장의 진행 중 주문 상태별 건수(관리자 정지·숨김 경고용). 0건 상태는 빼고 흐름 순으로 돌려준다. */ async countInProgressOrdersByStore( storeId: bigint, diff --git a/src/features/order/resolvers/order-admin.resolver.spec.ts b/src/features/order/resolvers/order-admin.resolver.spec.ts index 312c2283..20a4777d 100644 --- a/src/features/order/resolvers/order-admin.resolver.spec.ts +++ b/src/features/order/resolvers/order-admin.resolver.spec.ts @@ -5,7 +5,9 @@ import { PubSub } from 'graphql-subscriptions'; import { AUDIT_LOG_REPOSITORY } from '@/features/audit-log'; import { AuditLogRepository } from '@/features/audit-log/repositories/audit-log.repository'; import { AccountAdminRepository } from '@/features/auth/repositories/account-admin.repository'; +import { OrderCancelPolicy } from '@/features/order/policies/order-cancel.policy'; import { OrderStatusTransitionPolicy } from '@/features/order/policies/order-status-transition.policy'; +import { OrderTransitionRepository } from '@/features/order/repositories/order-transition.repository'; import { OrderRepository } from '@/features/order/repositories/order.repository'; import { AdminOrderMutationResolver } from '@/features/order/resolvers/order-admin-mutation.resolver'; import { AdminOrderQueryResolver } from '@/features/order/resolvers/order-admin-query.resolver'; @@ -37,6 +39,8 @@ describe('Admin Order Resolvers (real DB)', () => { AccountAdminRepository, OrderRepository, OrderStatusTransitionPolicy, + OrderCancelPolicy, + OrderTransitionRepository, OrderEventsService, { provide: PUB_SUB, useValue: new PubSub() }, { provide: AUDIT_LOG_REPOSITORY, useClass: AuditLogRepository }, @@ -80,8 +84,14 @@ describe('Admin Order Resolvers (real DB)', () => { const detail = await queryResolver.adminOrder(user, order.id.toString()); expect(detail.items).toHaveLength(1); + expect(detail.cancelOptions).toMatchObject({ + cancelable: true, + refundRule: 'FULL_REFUND', + }); + const canceled = await mutationResolver.adminCancelOrder(user, { orderId: order.id.toString(), + reason: 'OTHER', note: '운영 판단', }); expect(canceled.status).toBe('CANCELED'); diff --git a/src/features/order/resolvers/order-my-mutation.resolver.ts b/src/features/order/resolvers/order-my-mutation.resolver.ts index e58f020d..a52cbd1e 100644 --- a/src/features/order/resolvers/order-my-mutation.resolver.ts +++ b/src/features/order/resolvers/order-my-mutation.resolver.ts @@ -2,6 +2,7 @@ import { UseGuards } from '@nestjs/common'; import { Args, Mutation, Resolver } from '@nestjs/graphql'; import { parseId } from '@/common/utils/id-parser'; +import { CancelMyOrderInput } from '@/features/order/dto/inputs/cancel-my-order.input'; import { UserOrderService } from '@/features/order/services/order-my.service'; import type { MyOrderDetail } from '@/features/order/types/order-my-output.type'; import { @@ -26,4 +27,12 @@ export class UserOrderMutationResolver { parseId(orderId), ); } + + @Mutation('cancelMyOrder') + cancelMyOrder( + @CurrentUser() user: JwtUser, + @Args('input') input: CancelMyOrderInput, + ): Promise { + return this.orderService.cancelMyOrder(parseAccountId(user), input); + } } diff --git a/src/features/order/resolvers/order-my.resolver.spec.ts b/src/features/order/resolvers/order-my.resolver.spec.ts index 7485114b..3f054a48 100644 --- a/src/features/order/resolvers/order-my.resolver.spec.ts +++ b/src/features/order/resolvers/order-my.resolver.spec.ts @@ -1,11 +1,17 @@ +import { PubSub } from 'graphql-subscriptions'; + import { AUDIT_LOG_REPOSITORY } from '@/features/audit-log'; import { AuditLogRepository } from '@/features/audit-log/repositories/audit-log.repository'; +import { OrderCancelPolicy } from '@/features/order/policies/order-cancel.policy'; +import { OrderTransitionRepository } from '@/features/order/repositories/order-transition.repository'; import { OrderRepository } from '@/features/order/repositories/order.repository'; import { PaymentRepository } from '@/features/order/repositories/payment.repository'; import { UserOrderMutationResolver } from '@/features/order/resolvers/order-my-mutation.resolver'; import { UserOrderQueryResolver } from '@/features/order/resolvers/order-my-query.resolver'; +import { OrderEventsService } from '@/features/order/services/order-events.service'; import { UserOrderService } from '@/features/order/services/order-my.service'; import type { PrismaClient } from '@/generated/prisma/client'; +import { PUB_SUB } from '@/global/pubsub'; import { disconnectTestPrismaClient } from '@/test/db/prisma-test-client'; import { closeTruncateConnection, truncateAll } from '@/test/db/truncate'; import { @@ -33,6 +39,10 @@ describe('User Order Resolver (real DB)', () => { UserOrderService, OrderRepository, PaymentRepository, + OrderTransitionRepository, + OrderCancelPolicy, + OrderEventsService, + { provide: PUB_SUB, useValue: new PubSub() }, { provide: AUDIT_LOG_REPOSITORY, useClass: AuditLogRepository }, // 발행 repository가 OutboxPublisher를 주입받는다(08b) ...outboxPublisherProviders(), @@ -123,4 +133,31 @@ describe('User Order Resolver (real DB)', () => { expect(result.orderId).toBe(order.id.toString()); expect(result.payment?.buyerClaimedAt).toBeInstanceOf(Date); }); + + it('Mutation.cancelMyOrder: 입금 대기 주문을 취소하고 상세(취소 정보·취소 불가)를 반환한다', async () => { + const account = await createAccount(prisma, { account_type: 'USER' }); + await createUserProfile(prisma, { account_id: account.id }); + const order = await createOrder(prisma, { + account_id: account.id, + status: 'PENDING_PAYMENT', + }); + await createOrderItem(prisma, { order_id: order.id }); + await createPayment(prisma, { order_id: order.id }); + + const result = await mutationResolver.cancelMyOrder( + { accountId: account.id.toString() }, + { orderId: order.id.toString(), note: '다시 주문할게요' }, + ); + + expect(result).toMatchObject({ + status: 'CANCELED', + canCancel: false, + cancellation: { + actorType: 'BUYER', + reason: 'BUYER_REQUEST', + note: '다시 주문할게요', + refundAmount: 0, + }, + }); + }); }); diff --git a/src/features/order/resolvers/order-seller-mutation.resolver.ts b/src/features/order/resolvers/order-seller-mutation.resolver.ts index 968c6015..1832d470 100644 --- a/src/features/order/resolvers/order-seller-mutation.resolver.ts +++ b/src/features/order/resolvers/order-seller-mutation.resolver.ts @@ -1,6 +1,7 @@ import { UseGuards } from '@nestjs/common'; import { Args, Mutation, Resolver } from '@nestjs/graphql'; +import { SellerCancelOrderInput } from '@/features/order/dto/inputs/seller-cancel-order.input'; import { SellerUpdateOrderStatusInput } from '@/features/order/dto/inputs/seller-update-order-status.input'; import { SellerOrderService } from '@/features/order/services/order-seller.service'; import type { SellerOrderSummaryOutput } from '@/features/order/types/order-seller-output.type'; @@ -27,4 +28,12 @@ export class SellerOrderMutationResolver { const accountId = parseAccountId(user); return this.orderService.sellerUpdateOrderStatus(accountId, input); } + + @Mutation('sellerCancelOrder') + sellerCancelOrder( + @CurrentUser() user: JwtUser, + @Args('input') input: SellerCancelOrderInput, + ): Promise { + return this.orderService.sellerCancelOrder(parseAccountId(user), input); + } } diff --git a/src/features/order/resolvers/order-seller.resolver.spec.ts b/src/features/order/resolvers/order-seller.resolver.spec.ts index e7f9d97a..a3391baf 100644 --- a/src/features/order/resolvers/order-seller.resolver.spec.ts +++ b/src/features/order/resolvers/order-seller.resolver.spec.ts @@ -2,7 +2,9 @@ import { PubSub } from 'graphql-subscriptions'; import { AUDIT_LOG_REPOSITORY } from '@/features/audit-log'; import { AuditLogRepository } from '@/features/audit-log/repositories/audit-log.repository'; +import { OrderCancelPolicy } from '@/features/order/policies/order-cancel.policy'; import { OrderStatusTransitionPolicy } from '@/features/order/policies/order-status-transition.policy'; +import { OrderTransitionRepository } from '@/features/order/repositories/order-transition.repository'; import { OrderRepository } from '@/features/order/repositories/order.repository'; import { SellerOrderMutationResolver } from '@/features/order/resolvers/order-seller-mutation.resolver'; import { SellerOrderQueryResolver } from '@/features/order/resolvers/order-seller-query.resolver'; @@ -36,6 +38,8 @@ describe('Seller Order Resolvers (real DB)', () => { StoreSellerRepository, OrderRepository, OrderStatusTransitionPolicy, + OrderCancelPolicy, + OrderTransitionRepository, OrderEventsService, { provide: PUB_SUB, useValue: new PubSub() }, { @@ -102,4 +106,19 @@ describe('Seller Order Resolvers (real DB)', () => { ), ).rejects.toThrowDomain(404); }); + + it('Mutation.sellerCancelOrder: ID를 파싱해 접수 주문을 거절하고 요약을 반환한다', async () => { + const me = await setupSellerWithStore(prisma); + const order = await setupOrderForStore(me.store.id); + + const result = await mutationResolver.sellerCancelOrder( + { accountId: me.account.id.toString() }, + { orderId: order.id.toString(), reason: 'SCHEDULE_UNAVAILABLE' }, + ); + + expect(result).toMatchObject({ + id: order.id.toString(), + status: 'CANCELED', + }); + }); }); diff --git a/src/features/order/services/order-admin-mappers.helper.ts b/src/features/order/services/order-admin-mappers.helper.ts index cc17875a..0ac20253 100644 --- a/src/features/order/services/order-admin-mappers.helper.ts +++ b/src/features/order/services/order-admin-mappers.helper.ts @@ -4,11 +4,14 @@ import type { AdminOrderRow, } from '@/features/order/repositories/order.repository'; import { + toOrderCancellation, toOrderItemDetail, + toOrderRefund, toOrderStatusHistory, } from '@/features/order/services/order-output-mappers.helper'; import { toAdminOrderPaymentOutput } from '@/features/order/services/order-payment-mappers.helper'; import type { + AdminOrderCancelOptionsOutput, AdminOrderDetailOutput, AdminOrderSummaryOutput, } from '@/features/order/types/order-admin-output.type'; @@ -36,6 +39,7 @@ export function toAdminOrderSummaryOutput( export function toAdminOrderDetailOutput( row: AdminOrderDetailRow, + cancelOptions: AdminOrderCancelOptionsOutput, ): AdminOrderDetailOutput { const profile = row.account.user_profile; return { @@ -66,5 +70,8 @@ export function toAdminOrderDetailOutput( updatedAt: row.updated_at, items: row.items.map(toOrderItemDetail), statusHistories: row.status_histories.map(toOrderStatusHistory), + refunds: row.refunds.map(toOrderRefund), + cancellation: toOrderCancellation(row), + cancelOptions, }; } diff --git a/src/features/order/services/order-admin.service.spec.ts b/src/features/order/services/order-admin.service.spec.ts index f4e34998..491215a8 100644 --- a/src/features/order/services/order-admin.service.spec.ts +++ b/src/features/order/services/order-admin.service.spec.ts @@ -7,7 +7,10 @@ import { AccountAdminRepository } from '@/features/auth/repositories/account-adm import { NotificationAdminRepository } from '@/features/notification/repositories/notification-admin.repository'; import { NotificationRepository } from '@/features/notification/repositories/notification.repository'; import { NotificationOutboxConsumer } from '@/features/notification/services/notification-outbox.consumer'; +import type { AdminCancelOrderInput } from '@/features/order/dto/inputs/admin-cancel-order.input'; +import { OrderCancelPolicy } from '@/features/order/policies/order-cancel.policy'; import { OrderStatusTransitionPolicy } from '@/features/order/policies/order-status-transition.policy'; +import { OrderTransitionRepository } from '@/features/order/repositories/order-transition.repository'; import { OrderRepository } from '@/features/order/repositories/order.repository'; import { AdminOrderService } from '@/features/order/services/order-admin.service'; import { OrderEventsService } from '@/features/order/services/order-events.service'; @@ -47,6 +50,8 @@ describe('AdminOrderService (real DB)', () => { AccountAdminRepository, OrderRepository, OrderStatusTransitionPolicy, + OrderCancelPolicy, + OrderTransitionRepository, { provide: AUDIT_LOG_REPOSITORY, useClass: AuditLogRepository }, OrderEventsService, // 발행-구독 왕복은 실 Redis spec(events service) 담당 — 여기선 in-memory @@ -84,6 +89,8 @@ describe('AdminOrderService (real DB)', () => { buyerName?: string; orderNumber?: string; submittedAt?: Date | null; + /** 확인된 결제(입금 대기면 PENDING 결제)를 함께 만든다 */ + paid?: boolean; } = {}, ) { const buyer = await createAccount(prisma, { account_type: 'USER' }); @@ -105,9 +112,24 @@ describe('AdminOrderService (real DB)', () => { order_id: order.id, store_id: store.id, }); + if (overrides.paid) { + const confirmed = order.status !== 'PENDING_PAYMENT'; + await createPayment(prisma, { + order_id: order.id, + status: confirmed ? 'CONFIRMED' : 'PENDING', + confirmed_at: confirmed ? new Date() : null, + }); + } return { order, item, buyer, storeId: store.id }; } + function cancelInput( + orderId: bigint, + overrides: Partial = {}, + ): AdminCancelOrderInput { + return { orderId: orderId.toString(), reason: 'OTHER', ...overrides }; + } + describe('adminOrders', () => { it('전 매장 주문을 최신순으로, keyword·status·storeId·accountId·기간 필터가 totalCount에도 적용된다', async () => { const a = await orderWithItem({ @@ -387,6 +409,8 @@ describe('AdminOrderService (real DB)', () => { expect(result.items.map((i) => i.id)).toEqual([item.id.toString()]); expect(result.statusHistories).toHaveLength(1); expect(result.payment).toBeNull(); + expect(result.refunds).toEqual([]); + expect(result.cancellation).toBeNull(); }); it('결제와 입금 확인 처리자·메모를 준다', async () => { @@ -425,6 +449,95 @@ describe('AdminOrderService (real DB)', () => { }); }); + it.each([ + ['PENDING_PAYMENT', true, 'NO_REFUND', 7, 0], + ['SUBMITTED', true, 'FULL_REFUND', 6, 10_000], + ['CONFIRMED', true, 'BY_FAULT', 6, 10_000], + ['MADE', true, 'BY_FAULT', 6, 10_000], + ['PICKED_UP', false, null, 0, 10_000], + ['NO_SHOW', false, null, 0, 10_000], + ['CANCELED', false, null, 0, 10_000], + ] as const)( + '%s 주문의 취소 선택지: 취소 가능 %s, 규칙 %s, 사유 %d개, 결제액 %d', + async (status, cancelable, refundRule, reasonCount, paidAmount) => { + const { order } = await orderWithItem({ status, paid: true }); + + const { cancelOptions } = await service.adminOrder( + await admin(), + order.id, + ); + + expect(cancelOptions).toMatchObject({ + cancelable, + refundRule, + paidAmount, + }); + expect(cancelOptions.reasons).toHaveLength(reasonCount); + expect(cancelOptions.reasons.includes('PAYMENT_NOT_RECEIVED')).toBe( + status === 'PENDING_PAYMENT', + ); + }, + ); + + it('결제 도입 전 주문은 결제액 0으로 내려 준다', async () => { + const { order } = await orderWithItem({ status: 'CONFIRMED' }); + const { cancelOptions } = await service.adminOrder( + await admin(), + order.id, + ); + expect(cancelOptions.paidAmount).toBe(0); + }); + + it('취소 뒤에는 취소 정보와 환불 목록(입금 반환 포함, 오래된 순)을 준다', async () => { + const { order } = await orderWithItem({ status: 'MADE', paid: true }); + await service.adminCancelOrder( + await admin(), + cancelInput(order.id, { + reason: 'OUT_OF_MATERIALS', + note: '재료 소진', + fault: 'BUYER', + refundAmount: 4_000, + }), + ); + await prisma.refund.create({ + data: { + order_id: order.id, + kind: 'DEPOSIT_RETURN', + amount: 500, + requested_at: new Date(), + }, + }); + + const result = await service.adminOrder(await admin(), order.id); + + expect(result.cancellation).toMatchObject({ + actorType: 'ADMIN', + reason: 'OUT_OF_MATERIALS', + reasonLabel: '재료 소진', + note: '재료 소진', + fault: 'BUYER', + refundAmount: 4_000, + refundStatus: 'AWAITING_ACCOUNT', + refundCompletedAt: null, + }); + expect(result.refunds.map((r) => [r.kind, r.amount])).toEqual([ + ['CANCEL', 4_000], + ['DEPOSIT_RETURN', 500], + ]); + expect(result.statusHistories[0]).toMatchObject({ + toStatus: 'CANCELED', + actorType: 'ADMIN', + cancelReason: 'OUT_OF_MATERIALS', + cancelFault: 'BUYER', + refundAmount: 4_000, + }); + expect(result.cancelOptions).toMatchObject({ + cancelable: false, + reasons: [], + refundRule: null, + }); + }); + it('없거나 삭제된 주문이면 404', async () => { const deleted = await createOrder(prisma, { deleted_at: new Date() }); await expect( @@ -437,26 +550,33 @@ describe('AdminOrderService (real DB)', () => { }); describe('adminCancelOrder', () => { - it.each(['SUBMITTED', 'CONFIRMED', 'MADE'] as const)( - '%s 주문을 취소하고 이력([관리자] 접두)·ORDER_CANCELED 알림·감사(store_id)를 한 번에 남긴다', - async (status) => { + it.each([ + ['SUBMITTED', null], + ['CONFIRMED', 'SELLER'], + ['MADE', 'SELLER'], + ] as const)( + '%s 주문을 취소하고 이력(주체·사유·환불액, 접두 없음)·전액 환불·취소 알림·환불 계좌 요청·감사를 남긴다', + async (status, fault) => { const actor = await admin(); - const { order, buyer, storeId } = await orderWithItem({ status }); - - const result = await service.adminCancelOrder(actor, { - orderId: order.id.toString(), - note: ' 가게 사정 ', + const { order, buyer, storeId } = await orderWithItem({ + status, + paid: true, }); + const result = await service.adminCancelOrder( + actor, + cancelInput(order.id, { + reason: 'SCHEDULE_UNAVAILABLE', + note: ' 가게 사정 ', + fault, + }), + ); + expect(result).toMatchObject({ status: 'CANCELED', firstItemName: 'Product snapshot', firstItemImageUrl: null, }); - const row = await prisma.order.findUniqueOrThrow({ - where: { id: order.id }, - }); - expect(row.canceled_at).not.toBeNull(); const history = await prisma.orderStatusHistory.findFirstOrThrow({ where: { order_id: order.id, to_status: 'CANCELED' }, }); @@ -464,17 +584,36 @@ describe('AdminOrderService (real DB)', () => { from_status: status, actor_type: 'ADMIN', actor_account_id: actor, - note: '[관리자] 가게 사정', + cancel_reason: 'SCHEDULE_UNAVAILABLE', + cancel_fault: fault, + refund_amount: order.total_price, + note: '가게 사정', + }); + await expect( + prisma.refund.findFirstOrThrow({ where: { order_id: order.id } }), + ).resolves.toMatchObject({ + kind: 'CANCEL', + amount: order.total_price, + status: 'AWAITING_ACCOUNT', }); await drainOutbox(dispatcher); - const notification = await prisma.notification.findFirstOrThrow({ + const notifications = await prisma.notification.findMany({ where: { order_id: order.id }, + orderBy: { id: 'asc' }, }); - expect(notification).toMatchObject({ - account_id: buyer.id, - event: 'ORDER_CANCELED', - store_id: storeId, - }); + expect(notifications).toEqual([ + expect.objectContaining({ + account_id: buyer.id, + event: 'ORDER_CANCELED', + body: `${order.order_number} 주문이 취소되었어요. 사유: 일정 불가`, + store_id: storeId, + }), + expect.objectContaining({ + account_id: buyer.id, + event: 'REFUND_ACCOUNT_REQUESTED', + body: `${order.order_number} 10,000원을 돌려받을 계좌를 입력해 주세요.`, + }), + ]); const audit = await prisma.auditLog.findFirstOrThrow({ where: { target_type: 'ORDER', target_id: order.id }, }); @@ -486,16 +625,43 @@ describe('AdminOrderService (real DB)', () => { }, ); - it.each(['PICKED_UP', 'CANCELED', 'NO_SHOW', 'PENDING_PAYMENT'] as const)( - '%s 주문은 400(판매자와 같은 전이 규칙)', + it("입금 대기 주문을 미입금으로 취소하면('입금했어요'를 눌렀어도) 결제를 닫고 입금 기한 만료 알림을 보낸다", async () => { + const { order, buyer } = await orderWithItem({ + status: 'PENDING_PAYMENT', + }); + await createPayment(prisma, { + order_id: order.id, + buyer_claimed_at: new Date(), + }); + + await service.adminCancelOrder( + await admin(), + cancelInput(order.id, { reason: 'PAYMENT_NOT_RECEIVED' }), + ); + + await expect( + prisma.payment.findUniqueOrThrow({ where: { order_id: order.id } }), + ).resolves.toMatchObject({ status: 'CANCELED' }); + expect(await prisma.refund.count()).toBe(0); + await drainOutbox(dispatcher); + await expect( + prisma.notification.findMany({ where: { order_id: order.id } }), + ).resolves.toEqual([ + expect.objectContaining({ + account_id: buyer.id, + event: 'ORDER_PAYMENT_EXPIRED', + body: `${order.order_number} 입금이 확인되지 않아 주문이 취소되었어요.`, + }), + ]); + }); + + it.each(['PICKED_UP', 'CANCELED', 'NO_SHOW'] as const)( + '%s 주문은 ORDER_NOT_CANCELLABLE', async (status) => { const { order } = await orderWithItem({ status }); await expect( - service.adminCancelOrder(await admin(), { - orderId: order.id.toString(), - note: 'x', - }), - ).rejects.toThrowDomain(400); + service.adminCancelOrder(await admin(), cancelInput(order.id)), + ).rejects.toThrowDomain('ORDER_NOT_CANCELLABLE'); expect( await prisma.orderStatusHistory.count({ where: { order_id: order.id }, @@ -504,40 +670,101 @@ describe('AdminOrderService (real DB)', () => { }, ); - it('사유가 공백이면 400, 없는 주문은 404', async () => { - const { order } = await orderWithItem(); - await expect( - service.adminCancelOrder(await admin(), { - orderId: order.id.toString(), - note: ' ', + it.each([ + [ + '접수 주문에 미입금 사유', + 'SUBMITTED', + { reason: 'PAYMENT_NOT_RECEIVED' }, + 'CANCEL_REASON_NOT_ALLOWED', + ], + [ + '자동 미확정 사유', + 'SUBMITTED', + { reason: 'CONFIRM_TIMEOUT' }, + 'CANCEL_REASON_NOT_ALLOWED', + ], + ['확정 주문에 사정 없음', 'CONFIRMED', {}, 'CANCEL_FAULT_REQUIRED'], + [ + '구매자 사정에 금액 없음', + 'MADE', + { fault: 'BUYER' }, + 'REFUND_AMOUNT_REQUIRED', + ], + [ + '결제액 + 1원', + 'MADE', + { fault: 'BUYER', refundAmount: 10_001 }, + 'REFUND_AMOUNT_OUT_OF_RANGE', + ], + [ + '음수', + 'CONFIRMED', + { fault: 'BUYER', refundAmount: -1 }, + 'REFUND_AMOUNT_OUT_OF_RANGE', + ], + ] as const)( + '%s는 %s로 거절하고 아무것도 바꾸지 않는다', + async (_label, status, overrides, code) => { + const { order } = await orderWithItem({ status, paid: true }); + await expect( + service.adminCancelOrder( + await admin(), + cancelInput(order.id, overrides), + ), + ).rejects.toThrowDomain(code); + await expect( + prisma.order.findUniqueOrThrow({ where: { id: order.id } }), + ).resolves.toMatchObject({ status }); + expect(await prisma.refund.count()).toBe(0); + expect(await prisma.outbox.count()).toBe(0); + }, + ); + + it('구매자 사정 부분 환불은 환불 R과 남는 금액의 정산 확정을 함께 남긴다', async () => { + const { order } = await orderWithItem({ status: 'MADE', paid: true }); + + await service.adminCancelOrder( + await admin(), + cancelInput(order.id, { + reason: 'BUYER_REQUEST', + fault: 'BUYER', + refundAmount: 3_000, }), - ).rejects.toThrowDomain(400); + ); + await expect( - service.adminCancelOrder(await admin(), { - orderId: '999999', - note: 'x', - }), - ).rejects.toThrowDomain(404); + prisma.refund.findFirstOrThrow({ where: { order_id: order.id } }), + ).resolves.toMatchObject({ amount: 3_000 }); + await expect( + prisma.order.findUniqueOrThrow({ where: { id: order.id } }), + ).resolves.toMatchObject({ settlement_base_amount: 7_000 }); }); - it('사유는 접두를 붙여 500자 이내여야 한다(494자 허용, 495자 거절)', async () => { + it('메모는 선택(공백은 null)이고 500자까지 받으며, 없는 주문은 404', async () => { const { order } = await orderWithItem(); + const other = await orderWithItem(); await expect( - service.adminCancelOrder(await admin(), { - orderId: order.id.toString(), - note: 'x'.repeat(495), - }), - ).rejects.toThrowDomain(400); + service.adminCancelOrder( + await admin(), + cancelInput(order.id, { note: 'x'.repeat(501) }), + ), + ).rejects.toThrowDomain('TEXT_TOO_LONG'); - await service.adminCancelOrder(await admin(), { - orderId: order.id.toString(), - note: 'x'.repeat(494), - }); - const history = await prisma.orderStatusHistory.findFirstOrThrow({ - where: { order_id: order.id }, + await service.adminCancelOrder( + await admin(), + cancelInput(order.id, { note: 'x'.repeat(500) }), + ); + await service.adminCancelOrder( + await admin(), + cancelInput(other.order.id, { note: ' ' }), + ); + const notes = await prisma.orderStatusHistory.findMany({ + orderBy: { id: 'asc' }, }); - expect(history.note).toHaveLength(500); - expect(history.note?.startsWith('[관리자] ')).toBe(true); + expect(notes.map((h) => h.note)).toEqual(['x'.repeat(500), null]); + await expect( + service.adminCancelOrder(await admin(), cancelInput(999_999n)), + ).rejects.toThrowDomain(404); }); // 판매자 확인과 교차: 어느 쪽이 먼저든 최종은 CANCELED이고 이력은 실제 전이 순서만 남는다. @@ -546,11 +773,11 @@ describe('AdminOrderService (real DB)', () => { const { order, storeId } = await orderWithItem(); const seller = await createAccount(prisma, { account_type: 'SELLER' }); - const [, sellerResult] = await Promise.allSettled([ - service.adminCancelOrder(await admin(), { - orderId: order.id.toString(), - note: 'a', - }), + const [cancelResult, sellerResult] = await Promise.allSettled([ + service.adminCancelOrder( + await admin(), + cancelInput(order.id, { fault: 'SELLER' }), + ), orderRepo.updateOrderStatusBySeller({ orderId: order.id, storeId, @@ -564,6 +791,7 @@ describe('AdminOrderService (real DB)', () => { }), ]); + expect(cancelResult.status).toBe('fulfilled'); const row = await prisma.order.findUniqueOrThrow({ where: { id: order.id }, }); @@ -584,14 +812,8 @@ describe('AdminOrderService (real DB)', () => { const topic = await collectTopic(pubSub, `order.seller.${storeId}`); const [a, b] = [await admin(), await admin()]; const results = await Promise.allSettled([ - service.adminCancelOrder(a, { - orderId: order.id.toString(), - note: 'a', - }), - service.adminCancelOrder(b, { - orderId: order.id.toString(), - note: 'b', - }), + service.adminCancelOrder(a, cancelInput(order.id, { note: 'a' })), + service.adminCancelOrder(b, cancelInput(order.id, { note: 'b' })), ]); expect(results.map((r) => r.status).sort()).toEqual([ 'fulfilled', @@ -621,10 +843,10 @@ describe('AdminOrderService (real DB)', () => { const { order, storeId } = await orderWithItem({ status: 'CONFIRMED' }); const topic = await collectTopic(pubSub, `order.seller.${storeId}`); - await service.adminCancelOrder(await admin(), { - orderId: order.id.toString(), - note: '가게 사정', - }); + await service.adminCancelOrder( + await admin(), + cancelInput(order.id, { fault: 'SELLER' }), + ); const row = await prisma.order.findUniqueOrThrow({ where: { id: order.id }, @@ -650,10 +872,7 @@ describe('AdminOrderService (real DB)', () => { const topic = await collectTopic(pubSub, `order.seller.${storeId}`); await expect( - service.adminCancelOrder(await admin(), { - orderId: order.id.toString(), - note: 'x', - }), + service.adminCancelOrder(await admin(), cancelInput(order.id)), ).rejects.toThrowDomain('ORDER_NOT_CANCELLABLE'); expect(topic.received).toHaveLength(0); @@ -664,10 +883,10 @@ describe('AdminOrderService (real DB)', () => { const { order } = await orderWithItem({ submittedAt: null }); const publish = jest.spyOn(pubSub, 'publish'); - const result = await service.adminCancelOrder(await admin(), { - orderId: order.id.toString(), - note: 'x', - }); + const result = await service.adminCancelOrder( + await admin(), + cancelInput(order.id), + ); const published = publish.mock.calls.length; publish.mockRestore(); @@ -683,10 +902,10 @@ describe('AdminOrderService (real DB)', () => { }); const publish = jest.spyOn(pubSub, 'publish'); - const result = await service.adminCancelOrder(await admin(), { - orderId: order.id.toString(), - note: 'x', - }); + const result = await service.adminCancelOrder( + await admin(), + cancelInput(order.id), + ); expect(result).toMatchObject({ status: 'CANCELED', storeId: null }); expect(publish).not.toHaveBeenCalled(); diff --git a/src/features/order/services/order-admin.service.ts b/src/features/order/services/order-admin.service.ts index 89fb9c55..b73bbb37 100644 --- a/src/features/order/services/order-admin.service.ts +++ b/src/features/order/services/order-admin.service.ts @@ -1,6 +1,8 @@ import { Inject, Injectable } from '@nestjs/common'; +import { MAX_REASON_LENGTH } from '@/common/constants/reason.constants'; import { DomainException } from '@/common/errors/error-catalog'; +import { ClockService } from '@/common/providers/clock.service'; import type { CursorConnection } from '@/common/types/cursor-connection.type'; import { toDate } from '@/common/utils/date-parser'; import { parseId, parseOptionalId } from '@/common/utils/id-parser'; @@ -8,34 +10,36 @@ import { normalizeCursorInput, sliceIdCursorPage, } from '@/common/utils/pagination'; -import { cleanRequiredText } from '@/common/utils/text-cleaner'; +import { cleanNullableText } from '@/common/utils/text-cleaner'; import { AUDIT_LOG_REPOSITORY, type IAuditLogRepository, } from '@/features/audit-log'; import { AccountAdminRepository, AdminBaseService } from '@/features/auth'; -import { - ADMIN_CANCEL_NOTE_PREFIX, - MAX_ADMIN_CANCEL_NOTE_LENGTH, -} from '@/features/order/constants/order-admin.constants'; import type { AdminCancelOrderInput } from '@/features/order/dto/inputs/admin-cancel-order.input'; import type { AdminOrderListInput } from '@/features/order/dto/inputs/admin-order-list.input'; +import { OrderCancelPolicy } from '@/features/order/policies/order-cancel.policy'; import { OrderStatusTransitionPolicy } from '@/features/order/policies/order-status-transition.policy'; -import { OrderRepository } from '@/features/order/repositories/order.repository'; +import { confirmedPaidAmount } from '@/features/order/repositories/order-settlement-finalizer.helper'; +import { OrderTransitionRepository } from '@/features/order/repositories/order-transition.repository'; +import { + OrderRepository, + type AdminOrderDetailRow, +} from '@/features/order/repositories/order.repository'; import { toAdminOrderDetailOutput, toAdminOrderSummaryOutput, } from '@/features/order/services/order-admin-mappers.helper'; -import { toSellerOrderUpdateEvent } from '@/features/order/services/order-events-mappers.helper'; import { OrderEventsService } from '@/features/order/services/order-events.service'; import type { + AdminOrderCancelOptionsOutput, AdminOrderDetailOutput, AdminOrderSummaryOutput, AdminStoreInProgressOrderSummaryOutput, } from '@/features/order/types/order-admin-output.type'; -import { OrderStatus } from '@/generated/prisma/client'; +import { OrderActor } from '@/generated/prisma/client'; -/** 전이 규칙은 판매자와 같은 OrderStatusTransitionPolicy가 단일 소스이고, 저장·이력·알림·감사는 order feature의 repository가 한 트랜잭션에서 처리한다. */ +/** 취소 규칙은 OrderCancelPolicy가 단일 소스이고, 저장·이력·환불·알림·감사는 OrderTransitionRepository가 한 트랜잭션에서 처리한다. */ @Injectable() export class AdminOrderService extends AdminBaseService { constructor( @@ -44,7 +48,10 @@ export class AdminOrderService extends AdminBaseService { auditLogs: IAuditLogRepository, private readonly orderRepository: OrderRepository, private readonly statusPolicy: OrderStatusTransitionPolicy, + private readonly cancelPolicy: OrderCancelPolicy, + private readonly transitions: OrderTransitionRepository, private readonly events: OrderEventsService, + private readonly clock: ClockService, ) { super(accounts, auditLogs); } @@ -88,7 +95,21 @@ export class AdminOrderService extends AdminBaseService { await this.requireAdminContext(accountId); const row = await this.orderRepository.findOrderDetailForAdmin(orderId); if (!row) throw new DomainException('ORDER_NOT_FOUND'); - return toAdminOrderDetailOutput(row); + return toAdminOrderDetailOutput(row, this.cancelOptionsOf(row)); + } + + /** 관리자 FE 취소 다이얼로그가 규칙을 복제하지 않도록 지금 상태의 선택지를 내려 준다. */ + private cancelOptionsOf( + row: AdminOrderDetailRow, + ): AdminOrderCancelOptionsOutput { + const reasons = this.cancelPolicy.reasonsFor(OrderActor.ADMIN, row.status); + return { + cancelable: reasons.length > 0, + reasons: [...reasons], + refundRule: + reasons.length > 0 ? this.cancelPolicy.refundRule(row.status) : null, + paidAmount: confirmedPaidAmount(row.payment), + }; } /** 정지·숨김 전 경고용. 매장 존재는 보지 않는다(없는 매장은 0건). */ @@ -111,60 +132,26 @@ export class AdminOrderService extends AdminBaseService { input: AdminCancelOrderInput, ): Promise { const ctx = await this.requireAdminContext(accountId); - const note = cleanRequiredText(input.note, MAX_ADMIN_CANCEL_NOTE_LENGTH); - // 사전 검사는 빠른 거절용 — 최종 판정은 repository가 잠금 뒤 트랜잭션 안에서 다시 한다 - const current = await this.orderRepository.findOrderDetailForAdmin( - parseId(input.orderId), - ); - if (!current) throw new DomainException('ORDER_NOT_FOUND'); - this.statusPolicy.assertSellerTransition( - current.status, - OrderStatus.CANCELED, - ); - - const updated = await this.orderRepository.cancelOrderByAdmin({ - orderId: current.id, + const updated = await this.transitions.cancel({ + orderId: parseId(input.orderId), + actor: OrderActor.ADMIN, actorAccountId: ctx.accountId, - note: `${ADMIN_CANCEL_NOTE_PREFIX}${note}`, - now: new Date(), - // 잠금 뒤 현재 상태가 취소 가능한지 repository가 이 함수로 다시 판정한다 - canCancelFrom: (status) => { - try { - this.statusPolicy.assertSellerTransition( - status, - OrderStatus.CANCELED, - ); - return true; - } catch { - return false; - } - }, - }); - if (updated === 'not-found') throw new DomainException('ORDER_NOT_FOUND'); - if (updated === 'not-cancellable') { - // 사전 검사 뒤 상태가 바뀐 경쟁 — 같은 규칙으로 다시 던진다 - const latest = await this.orderRepository.findOrderDetailForAdmin( - current.id, - ); - this.statusPolicy.assertSellerTransition( - latest?.status ?? OrderStatus.CANCELED, - OrderStatus.CANCELED, - ); - throw new DomainException('ORDER_NOT_CANCELLABLE'); - } - - // 활성 품목이 없으면 매장을 알 수 없고, 입금 확인 전 주문은 판매자에게 보이지 않아 발행을 생략한다 - const [firstItem] = updated.items; - if (firstItem && updated.submitted_at) { - await this.events.publishSellerOrderUpdate( - firstItem.store_id, - toSellerOrderUpdateEvent( - 'STATUS_CHANGED', - updated, - firstItem.product_name_snapshot, + scope: { kind: 'any' }, + note: cleanNullableText(input.note, MAX_REASON_LENGTH), + now: this.clock.now(), + decide: (state) => + this.cancelPolicy.decide( + { + actor: OrderActor.ADMIN, + reason: input.reason, + fault: input.fault, + refundAmount: input.refundAmount, + }, + state, ), - ); - } + }); + if (!updated) throw new DomainException('ORDER_NOT_FOUND'); + await this.events.publishSellerStatusChanged(updated); return toAdminOrderSummaryOutput(updated); } } diff --git a/src/features/order/services/order-events.service.ts b/src/features/order/services/order-events.service.ts index 70104b3f..3f8ce31a 100644 --- a/src/features/order/services/order-events.service.ts +++ b/src/features/order/services/order-events.service.ts @@ -1,6 +1,8 @@ import { Inject, Injectable, Logger } from '@nestjs/common'; import type { PubSubEngine } from 'graphql-subscriptions'; +import type { AdminOrderRow } from '@/features/order/repositories/order.repository'; +import { toSellerOrderUpdateEvent } from '@/features/order/services/order-events-mappers.helper'; import type { SellerOrderUpdateEvent } from '@/features/order/types/order-seller-output.type'; import { PUB_SUB } from '@/global/pubsub'; @@ -38,6 +40,20 @@ export class OrderEventsService { await this.safePublish(this.sellerTopic(storeId), event); } + /** 입금 확인 전 주문은 판매자에게 보이지 않고, 활성 품목이 없으면 매장을 알 수 없어 발행하지 않는다. */ + async publishSellerStatusChanged(row: AdminOrderRow): Promise { + const [firstItem] = row.items; + if (!firstItem || !row.submitted_at) return; + await this.publishSellerOrderUpdate( + firstItem.store_id, + toSellerOrderUpdateEvent( + 'STATUS_CHANGED', + row, + firstItem.product_name_snapshot, + ), + ); + } + sellerOrderIterator(storeId: bigint): AsyncIterator { return this.pubSub.asyncIterableIterator(this.sellerTopic(storeId)); } diff --git a/src/features/order/services/order-my.service.spec.ts b/src/features/order/services/order-my.service.spec.ts index ffa0e1ba..1470ef2a 100644 --- a/src/features/order/services/order-my.service.spec.ts +++ b/src/features/order/services/order-my.service.spec.ts @@ -1,14 +1,22 @@ +import { PubSub } from 'graphql-subscriptions'; + import { ClockService } from '@/common/providers/clock.service'; import { AUDIT_LOG_REPOSITORY } from '@/features/audit-log'; import { AuditLogRepository } from '@/features/audit-log/repositories/audit-log.repository'; +import { ORDER_STATUS_CHANGED } from '@/features/order/events/order-status-changed.event'; import { parsePaymentDepositClaimedPayload, PAYMENT_DEPOSIT_CLAIMED, } from '@/features/order/events/payment-deposit-claimed.event'; +import { REFUND_REQUESTED } from '@/features/order/events/refund-requested.event'; +import { OrderCancelPolicy } from '@/features/order/policies/order-cancel.policy'; +import { OrderTransitionRepository } from '@/features/order/repositories/order-transition.repository'; import { OrderRepository } from '@/features/order/repositories/order.repository'; import { PaymentRepository } from '@/features/order/repositories/payment.repository'; +import { OrderEventsService } from '@/features/order/services/order-events.service'; import { UserOrderService } from '@/features/order/services/order-my.service'; -import type { PrismaClient } from '@/generated/prisma/client'; +import type { OrderStatus, PrismaClient } from '@/generated/prisma/client'; +import { PUB_SUB } from '@/global/pubsub'; import { disconnectTestPrismaClient } from '@/test/db/prisma-test-client'; import { closeTruncateConnection, truncateAll } from '@/test/db/truncate'; import { @@ -23,11 +31,13 @@ import { } from '@/test/factories'; import { createTestingModuleWithRealDb } from '@/test/modules/testing-module.builder'; import { outboxPublisherProviders } from '@/test/outbox'; +import { collectTopic } from '@/test/pubsub'; describe('UserOrderService (real DB)', () => { let service: UserOrderService; let clock: ClockService; let prisma: PrismaClient; + let pubSub: PubSub; beforeAll(async () => { const { module, prisma: p } = await createTestingModuleWithRealDb({ @@ -35,6 +45,10 @@ describe('UserOrderService (real DB)', () => { UserOrderService, OrderRepository, PaymentRepository, + OrderTransitionRepository, + OrderCancelPolicy, + OrderEventsService, + { provide: PUB_SUB, useValue: new PubSub() }, { provide: AUDIT_LOG_REPOSITORY, useClass: AuditLogRepository }, // 발행 repository가 OutboxPublisher를 주입받는다(08b) ...outboxPublisherProviders(), @@ -42,6 +56,7 @@ describe('UserOrderService (real DB)', () => { }); service = module.get(UserOrderService); clock = module.get(ClockService); + pubSub = module.get(PUB_SUB); prisma = p; }); @@ -735,4 +750,176 @@ describe('UserOrderService (real DB)', () => { expect(await claimEvents()).toHaveLength(0); }); }); + + describe('cancelMyOrder', () => { + const NOW = new Date('2026-09-16T07:30:00.000Z'); + + async function myOrder( + accountId: bigint, + status: OrderStatus, + payment: 'PENDING' | 'CONFIRMED' | null, + ) { + const order = await createOrder(prisma, { + account_id: accountId, + status, + }); + const item = await createOrderItem(prisma, { order_id: order.id }); + if (payment) { + await createPayment(prisma, { + order_id: order.id, + status: payment, + confirmed_at: payment === 'CONFIRMED' ? NOW : null, + }); + } + return { order, item }; + } + + it('입금 대기 주문은 환불 없이 취소되고 결제를 닫으며 판매자에게는 아무것도 가지 않는다', async () => { + const account = await setupUser(); + const { order, item } = await myOrder( + account.id, + 'PENDING_PAYMENT', + 'PENDING', + ); + jest.spyOn(clock, 'now').mockReturnValue(NOW); + const topic = await collectTopic(pubSub, `order.seller.${item.store_id}`); + + const result = await service.cancelMyOrder(account.id, { + orderId: order.id.toString(), + note: ' 다시 주문할게요 ', + }); + + expect(result).toMatchObject({ + status: 'CANCELED', + canceledAt: NOW, + canCancel: false, + cancellation: { + actorType: 'BUYER', + reason: 'BUYER_REQUEST', + reasonLabel: '구매자 요청', + note: '다시 주문할게요', + fault: null, + refundAmount: 0, + refundStatus: null, + canceledAt: NOW, + }, + }); + expect(result.payment).toMatchObject({ status: 'CANCELED' }); + expect(await prisma.refund.count()).toBe(0); + const events = await prisma.outbox.findMany(); + expect(events.map((e) => e.event_type)).toEqual([ORDER_STATUS_CHANGED]); + expect(events[0].payload_json).toMatchObject({ + actorType: 'BUYER', + cancelReason: 'BUYER_REQUEST', + }); + expect(topic.received).toHaveLength(0); + topic.stop(); + }); + + it("'입금했어요'를 누른 입금 대기 주문도 취소할 수 있다", async () => { + const account = await setupUser(); + const order = await createOrder(prisma, { + account_id: account.id, + status: 'PENDING_PAYMENT', + }); + await createPayment(prisma, { + order_id: order.id, + buyer_claimed_at: NOW, + }); + + await expect( + service.cancelMyOrder(account.id, { orderId: order.id.toString() }), + ).resolves.toMatchObject({ status: 'CANCELED' }); + }); + + it('접수 주문은 결제액 전액 환불(계좌 입력 대기)로 취소되고 판매자 구독에 알린다', async () => { + const account = await setupUser(); + const { order, item } = await myOrder( + account.id, + 'SUBMITTED', + 'CONFIRMED', + ); + const topic = await collectTopic(pubSub, `order.seller.${item.store_id}`); + + const result = await service.cancelMyOrder(account.id, { + orderId: order.id.toString(), + }); + + expect(result.cancellation).toMatchObject({ + refundAmount: order.total_price, + refundStatus: 'AWAITING_ACCOUNT', + }); + expect(result.payment).toMatchObject({ status: 'CONFIRMED' }); + await expect( + prisma.refund.findFirstOrThrow({ where: { order_id: order.id } }), + ).resolves.toMatchObject({ + kind: 'CANCEL', + amount: order.total_price, + }); + expect( + (await prisma.outbox.findMany({ orderBy: { id: 'asc' } })).map( + (e) => e.event_type, + ), + ).toEqual([ORDER_STATUS_CHANGED, REFUND_REQUESTED]); + expect(topic.received).toEqual([ + expect.objectContaining({ kind: 'STATUS_CHANGED', status: 'CANCELED' }), + ]); + topic.stop(); + }); + + it.each(['CONFIRMED', 'MADE', 'PICKED_UP', 'NO_SHOW', 'CANCELED'] as const)( + '판매자 확정 뒤(%s)에는 ORDER_NOT_CANCELLABLE이다', + async (status) => { + const account = await setupUser(); + const { order } = await myOrder(account.id, status, 'CONFIRMED'); + + await expect( + service.cancelMyOrder(account.id, { orderId: order.id.toString() }), + ).rejects.toThrowDomain('ORDER_NOT_CANCELLABLE'); + expect(await prisma.orderStatusHistory.count()).toBe(0); + }, + ); + + it('다른 계정·삭제된 주문은 ORDER_NOT_FOUND, 메모 501자는 TEXT_TOO_LONG이다', async () => { + const account = await setupUser(); + const other = await setupUser(); + const { order: othersOrder } = await myOrder(other.id, 'SUBMITTED', null); + const deleted = await createOrder(prisma, { + account_id: account.id, + deleted_at: NOW, + }); + const { order } = await myOrder(account.id, 'SUBMITTED', null); + + for (const id of [othersOrder.id, deleted.id]) { + await expect( + service.cancelMyOrder(account.id, { orderId: id.toString() }), + ).rejects.toThrowDomain('ORDER_NOT_FOUND'); + } + await expect( + service.cancelMyOrder(account.id, { + orderId: order.id.toString(), + note: 'x'.repeat(501), + }), + ).rejects.toThrowDomain('TEXT_TOO_LONG'); + expect(await prisma.orderStatusHistory.count()).toBe(0); + }); + + it.each([ + ['PENDING_PAYMENT', true], + ['SUBMITTED', true], + ['CONFIRMED', false], + ['MADE', false], + ['PICKED_UP', false], + ['NO_SHOW', false], + ['CANCELED', false], + ] as const)('상세 canCancel: %s → %s', async (status, canCancel) => { + const account = await setupUser(); + const { order } = await myOrder(account.id, status, null); + + const detail = await service.getMyOrder(account.id, order.id); + + expect(detail.canCancel).toBe(canCancel); + expect(detail.cancellation).toBeNull(); + }); + }); }); diff --git a/src/features/order/services/order-my.service.ts b/src/features/order/services/order-my.service.ts index 121b1c21..2b0e1568 100644 --- a/src/features/order/services/order-my.service.ts +++ b/src/features/order/services/order-my.service.ts @@ -1,13 +1,21 @@ import { Injectable } from '@nestjs/common'; +import { MAX_REASON_LENGTH } from '@/common/constants/reason.constants'; import { DomainException } from '@/common/errors/error-catalog'; import { ClockService } from '@/common/providers/clock.service'; import { calcDiscountRate } from '@/common/utils/discount-rate'; +import { parseId } from '@/common/utils/id-parser'; import { sliceOverfetched } from '@/common/utils/pagination'; +import { cleanNullableText } from '@/common/utils/text-cleaner'; +import type { CancelMyOrderInput } from '@/features/order/dto/inputs/cancel-my-order.input'; import type { MyOrdersInput } from '@/features/order/dto/inputs/my-orders.input'; +import { OrderCancelPolicy } from '@/features/order/policies/order-cancel.policy'; +import { OrderTransitionRepository } from '@/features/order/repositories/order-transition.repository'; import { OrderRepository } from '@/features/order/repositories/order.repository'; import { PaymentRepository } from '@/features/order/repositories/payment.repository'; +import { OrderEventsService } from '@/features/order/services/order-events.service'; import { + toOrderCancellation, toOrderItemDetail, toOrderStatusHistory, } from '@/features/order/services/order-output-mappers.helper'; @@ -17,16 +25,51 @@ import type { MyOrderDetail, } from '@/features/order/types/order-my-output.type'; import { formatBusinessHours } from '@/features/store'; -import { OrderStatus, PaymentStatus } from '@/generated/prisma/client'; +import { + OrderActor, + OrderCancelReason, + OrderStatus, + PaymentStatus, +} from '@/generated/prisma/client'; @Injectable() export class UserOrderService { constructor( private readonly orderRepository: OrderRepository, private readonly payments: PaymentRepository, + private readonly transitions: OrderTransitionRepository, + private readonly cancelPolicy: OrderCancelPolicy, + private readonly events: OrderEventsService, private readonly clock: ClockService, ) {} + /** 판매자 확정 전까지만. 입금 대기면 환불 없이, 접수면 전액 환불로 취소한다('입금했어요'를 눌렀어도 허용). */ + async cancelMyOrder( + accountId: bigint, + input: CancelMyOrderInput, + ): Promise { + const orderId = parseId(input.orderId); + const updated = await this.transitions.cancel({ + orderId, + actor: OrderActor.BUYER, + actorAccountId: accountId, + scope: { kind: 'buyer', accountId }, + note: cleanNullableText(input.note, MAX_REASON_LENGTH), + now: this.clock.now(), + decide: (state) => + this.cancelPolicy.decide( + { + actor: OrderActor.BUYER, + reason: OrderCancelReason.BUYER_REQUEST, + }, + state, + ), + }); + if (!updated) throw new DomainException('ORDER_NOT_FOUND'); + await this.events.publishSellerStatusChanged(updated); + return this.getMyOrder(accountId, orderId); + } + /** '입금했어요'. 마감 전 첫 누름만 기록해 미입금 자동 취소에서 빼고, 다시 누르면 그대로 돌려준다. */ async markMyOrderDepositSent( accountId: bigint, @@ -145,6 +188,8 @@ export class UserOrderService { madeAt: order.made_at, pickedUpAt: order.picked_up_at, canceledAt: order.canceled_at, + cancellation: toOrderCancellation(order), + canCancel: this.cancelPolicy.canCancel(OrderActor.BUYER, order.status), statusHistories: order.status_histories.map(toOrderStatusHistory), items: order.items.map((item) => ({ item: toOrderItemDetail(item), diff --git a/src/features/order/services/order-output-mappers.helper.spec.ts b/src/features/order/services/order-output-mappers.helper.spec.ts index 37179c52..3b725544 100644 --- a/src/features/order/services/order-output-mappers.helper.spec.ts +++ b/src/features/order/services/order-output-mappers.helper.spec.ts @@ -1,9 +1,13 @@ import { + toOrderCancellation, toOrderItemDetail, toOrderItemFreeEdit, + toOrderRefund, toOrderStatusHistory, type OrderItemDetailRow, + type OrderStatusHistoryRow, } from '@/features/order/services/order-output-mappers.helper'; +import type { Refund } from '@/generated/prisma/client'; function itemRow(o: Partial = {}): OrderItemDetailRow { return { @@ -113,22 +117,182 @@ describe('order-output-mappers', () => { }); }); - it('toOrderStatusHistory: 최초 이력은 fromStatus null, note null 허용', () => { + it('toOrderStatusHistory: 최초 이력은 fromStatus null, note null 허용, 주체·취소 필드를 그대로 싣는다', () => { const changedAt = new Date('2026-09-01T00:00:00.000Z'); - expect( - toOrderStatusHistory({ - id: 5n, - from_status: null, - to_status: 'SUBMITTED', - changed_at: changedAt, + expect(toOrderStatusHistory(historyRow({ changed_at: changedAt }))).toEqual( + { + id: '5', + fromStatus: null, + toStatus: 'SUBMITTED', + changedAt, note: null, - }), - ).toEqual({ - id: '5', - fromStatus: null, - toStatus: 'SUBMITTED', - changedAt, - note: null, + actorType: 'ADMIN', + cancelReason: null, + cancelFault: null, + refundAmount: null, + }, + ); + }); + + describe('toOrderCancellation', () => { + const canceledAt = new Date('2026-09-02T00:00:00.000Z'); + const cancelHistory = historyRow({ + from_status: 'CONFIRMED', + to_status: 'CANCELED', + actor_type: 'SELLER', + cancel_reason: 'OUT_OF_MATERIALS', + cancel_fault: 'BUYER', + refund_amount: 10_000, + note: '재료가 떨어졌어요', + }); + + it('취소 이력과 취소 환불을 합친다(입금 반환은 보지 않는다)', () => { + const completedAt = new Date('2026-09-03T00:00:00.000Z'); + expect( + toOrderCancellation({ + status: 'CANCELED', + canceled_at: canceledAt, + status_histories: [historyRow(), cancelHistory], + refunds: [ + { + kind: 'DEPOSIT_RETURN', + status: 'AWAITING_ACCOUNT', + completed_at: null, + }, + { kind: 'CANCEL', status: 'COMPLETED', completed_at: completedAt }, + ], + }), + ).toEqual({ + actorType: 'SELLER', + reason: 'OUT_OF_MATERIALS', + reasonLabel: '재료 소진', + note: '재료가 떨어졌어요', + fault: 'BUYER', + refundAmount: 10_000, + refundStatus: 'COMPLETED', + refundCompletedAt: completedAt, + canceledAt, + }); + }); + + it('환불이 없으면 환불 상태는 null이고, 사유가 없는 옛 이력은 기타·0원으로 보인다', () => { + expect( + toOrderCancellation({ + status: 'CANCELED', + canceled_at: null, + status_histories: [ + { + ...cancelHistory, + cancel_reason: null, + cancel_fault: null, + refund_amount: null, + }, + ], + refunds: [], + }), + ).toMatchObject({ + reason: 'OTHER', + reasonLabel: '기타', + refundAmount: 0, + refundStatus: null, + refundCompletedAt: null, + canceledAt: cancelHistory.changed_at, + }); + }); + + it('취소되지 않았거나 취소 이력이 없으면 null', () => { + expect( + toOrderCancellation({ + status: 'CONFIRMED', + canceled_at: null, + status_histories: [cancelHistory], + refunds: [], + }), + ).toBeNull(); + expect( + toOrderCancellation({ + status: 'CANCELED', + canceled_at: canceledAt, + status_histories: [historyRow()], + refunds: [], + }), + ).toBeNull(); + }); + }); + + describe('toOrderRefund', () => { + const requestedAt = new Date('2026-09-02T00:00:00.000Z'); + const refund: Refund = { + id: 7n, + order_id: 1n, + kind: 'CANCEL', + cancel_order_id: 1n, + deposit_record_id: null, + amount: 30_000, + status: 'AWAITING_ACCOUNT', + bank_code: null, + account_holder: null, + account_number_enc: null, + account_number_last4: null, + account_submitted_at: null, + requested_at: requestedAt, + completed_at: null, + completed_by_account_id: null, + completed_by_label_snapshot: null, + complete_note: null, + created_at: requestedAt, + updated_at: requestedAt, + }; + + it('계좌 입력 전이면 은행·예금주·계좌는 null', () => { + expect(toOrderRefund(refund)).toEqual({ + id: '7', + kind: 'CANCEL', + amount: 30_000, + status: 'AWAITING_ACCOUNT', + bank: null, + accountHolder: null, + accountNumberMasked: null, + requestedAt, + accountSubmittedAt: null, + completedAt: null, + }); + }); + + it('계좌가 있으면 은행 이름과 끝 4자리 마스킹만 준다(암호문은 내보내지 않는다)', () => { + expect( + toOrderRefund({ + ...refund, + status: 'AWAITING_TRANSFER', + bank_code: '004', + account_holder: '홍길동', + account_number_enc: 'v1.k1.x.y.z', + account_number_last4: '1234', + account_submitted_at: requestedAt, + }), + ).toMatchObject({ + bank: { code: '004', name: 'KB국민은행' }, + accountHolder: '홍길동', + accountNumberMasked: '****1234', + accountSubmittedAt: requestedAt, + }); }); }); }); + +function historyRow( + o: Partial = {}, +): OrderStatusHistoryRow { + return { + id: 5n, + from_status: null, + to_status: 'SUBMITTED', + changed_at: new Date('2026-09-01T00:00:00.000Z'), + note: null, + actor_type: 'ADMIN', + cancel_reason: null, + cancel_fault: null, + refund_amount: null, + ...o, + }; +} diff --git a/src/features/order/services/order-output-mappers.helper.ts b/src/features/order/services/order-output-mappers.helper.ts index 5024b25f..8160ae54 100644 --- a/src/features/order/services/order-output-mappers.helper.ts +++ b/src/features/order/services/order-output-mappers.helper.ts @@ -1,9 +1,23 @@ +import { ORDER_CANCEL_REASON_LABELS } from '@/features/order/constants/order-cancel-reasons'; +import { + maskAccountNumber, + toBank, +} from '@/features/order/services/order-bank-account.helper'; import type { + OrderCancellationOutput, OrderItemDetailOutput, OrderItemFreeEditOutput, + OrderRefundOutput, OrderStatusHistoryOutput, } from '@/features/order/types/order-output.type'; -import type { OrderStatus } from '@/generated/prisma/client'; +import { + OrderCancelReason, + OrderStatus, + RefundKind, + type OrderActor, + type OrderCancelFault, + type Refund, +} from '@/generated/prisma/client'; /** 판매자·관리자·구매자 조회 row가 모두 만족하는 구조적 부분집합. */ export interface OrderItemFreeEditRow { @@ -45,6 +59,10 @@ export interface OrderStatusHistoryRow { to_status: OrderStatus; changed_at: Date; note: string | null; + actor_type: OrderActor; + cancel_reason: OrderCancelReason | null; + cancel_fault: OrderCancelFault | null; + refund_amount: number | null; } export function toOrderItemDetail( @@ -101,5 +119,54 @@ export function toOrderStatusHistory( toStatus: history.to_status, changedAt: history.changed_at, note: history.note, + actorType: history.actor_type, + cancelReason: history.cancel_reason, + cancelFault: history.cancel_fault, + refundAmount: history.refund_amount, + }; +} + +/** 취소된 주문의 취소 이력과 취소 환불. 취소되지 않았거나 취소 이력이 없으면 null. */ +export function toOrderCancellation(row: { + status: OrderStatus; + canceled_at: Date | null; + status_histories: OrderStatusHistoryRow[]; + refunds: Pick[]; +}): OrderCancellationOutput | null { + if (row.status !== OrderStatus.CANCELED) return null; + const history = row.status_histories.find( + (h) => h.to_status === OrderStatus.CANCELED, + ); + if (!history) return null; + // 도입 전 취소는 마이그레이션이 OTHER로 채웠다 + const reason = history.cancel_reason ?? OrderCancelReason.OTHER; + const refund = row.refunds.find((r) => r.kind === RefundKind.CANCEL); + return { + actorType: history.actor_type, + reason, + reasonLabel: ORDER_CANCEL_REASON_LABELS[reason], + note: history.note, + fault: history.cancel_fault, + refundAmount: history.refund_amount ?? 0, + refundStatus: refund?.status ?? null, + refundCompletedAt: refund?.completed_at ?? null, + canceledAt: row.canceled_at ?? history.changed_at, + }; +} + +export function toOrderRefund(row: Refund): OrderRefundOutput { + return { + id: row.id.toString(), + kind: row.kind, + amount: row.amount, + status: row.status, + bank: row.bank_code ? toBank(row.bank_code) : null, + accountHolder: row.account_holder, + accountNumberMasked: row.account_number_last4 + ? maskAccountNumber(row.account_number_last4) + : null, + requestedAt: row.requested_at, + accountSubmittedAt: row.account_submitted_at, + completedAt: row.completed_at, }; } diff --git a/src/features/order/services/order-seller.service.spec.ts b/src/features/order/services/order-seller.service.spec.ts index 6a468a75..57e4d482 100644 --- a/src/features/order/services/order-seller.service.spec.ts +++ b/src/features/order/services/order-seller.service.spec.ts @@ -2,7 +2,10 @@ import { PubSub } from 'graphql-subscriptions'; import { AUDIT_LOG_REPOSITORY } from '@/features/audit-log'; import { AuditLogRepository } from '@/features/audit-log/repositories/audit-log.repository'; +import type { SellerCancelOrderInput } from '@/features/order/dto/inputs/seller-cancel-order.input'; +import { OrderCancelPolicy } from '@/features/order/policies/order-cancel.policy'; import { OrderStatusTransitionPolicy } from '@/features/order/policies/order-status-transition.policy'; +import { OrderTransitionRepository } from '@/features/order/repositories/order-transition.repository'; import { OrderRepository } from '@/features/order/repositories/order.repository'; import { OrderEventsService } from '@/features/order/services/order-events.service'; import { SellerOrderService } from '@/features/order/services/order-seller.service'; @@ -36,6 +39,8 @@ describe('SellerOrderService (real DB)', () => { StoreSellerRepository, OrderRepository, OrderStatusTransitionPolicy, + OrderCancelPolicy, + OrderTransitionRepository, { provide: AUDIT_LOG_REPOSITORY, useClass: AuditLogRepository, @@ -64,7 +69,13 @@ describe('SellerOrderService (real DB)', () => { async function createStoreOrder( storeId: bigint, - opts: { status?: OrderStatus; buyerId?: bigint } = {}, + opts: { + status?: OrderStatus; + buyerId?: bigint; + /** 확인된 결제를 함께 만든다 */ + paid?: boolean; + commissionRateBps?: number; + } = {}, ) { const buyerId = opts.buyerId ?? @@ -72,11 +83,19 @@ describe('SellerOrderService (real DB)', () => { const order = await createOrder(prisma, { account_id: buyerId, status: opts.status ?? 'SUBMITTED', + commission_rate_bps: opts.commissionRateBps, }); await createOrderItem(prisma, { order_id: order.id, store_id: storeId, }); + if (opts.paid) { + await createPayment(prisma, { + order_id: order.id, + status: 'CONFIRMED', + confirmed_at: new Date(), + }); + } return order; } @@ -342,6 +361,38 @@ describe('SellerOrderService (real DB)', () => { expect(result.statusHistories[0].toStatus).toBe('CONFIRMED'); // 결제 도입 전 주문은 결제 수단이 없다 expect(result.paymentMethod).toBeNull(); + expect(result.statusHistories[0].actorType).toBe('SELLER'); + expect(result.cancellation).toBeNull(); + }); + + it('입금 반환 환불은 판매자 취소 정보에 섞이지 않는다', async () => { + const { account, store } = await setupSellerWithStore(prisma); + const order = await createStoreOrder(store.id, { status: 'CANCELED' }); + await prisma.orderStatusHistory.create({ + data: { + order_id: order.id, + from_status: 'SUBMITTED', + to_status: 'CANCELED', + actor_type: 'ADMIN', + cancel_reason: 'OTHER', + refund_amount: 0, + }, + }); + await prisma.refund.create({ + data: { + order_id: order.id, + kind: 'DEPOSIT_RETURN', + amount: 500, + requested_at: new Date(), + }, + }); + + const result = await service.sellerOrder(account.id, order.id); + expect(result.cancellation).toMatchObject({ + actorType: 'ADMIN', + refundAmount: 0, + refundStatus: null, + }); }); it('결제가 있으면 결제 수단을 준다', async () => { @@ -456,17 +507,25 @@ describe('SellerOrderService (real DB)', () => { ).rejects.toThrowDomain(400); }); - it('CANCELED 전환 시 note 누락되면 400', async () => { - const { account, store } = await setupSellerWithStore(prisma); - const order = await createStoreOrder(store.id); - await expect( - service.sellerUpdateOrderStatus(account.id, { - orderId: order.id.toString(), - toStatus: 'CANCELED', - note: null, - }), - ).rejects.toThrowDomain(400); - }); + it.each(['SUBMITTED', 'CONFIRMED', 'MADE'] as const)( + '%s 주문도 상태 변경으로는 취소할 수 없다(INVALID_ORDER_STATUS_TRANSITION, sellerCancelOrder로만)', + async (status) => { + const { account, store } = await setupSellerWithStore(prisma); + const order = await createStoreOrder(store.id, { status }); + await expect( + service.sellerUpdateOrderStatus(account.id, { + orderId: order.id.toString(), + toStatus: 'CANCELED', + note: '재고 부족', + }), + ).rejects.toThrowDomain('INVALID_ORDER_STATUS_TRANSITION'); + expect( + await prisma.orderStatusHistory.count({ + where: { order_id: order.id }, + }), + ).toBe(0); + }, + ); it('정상 상태 전이: SUBMITTED → CONFIRMED, status_history row 생성 확인', async () => { const { account, store } = await setupSellerWithStore(prisma); @@ -535,8 +594,7 @@ describe('SellerOrderService (real DB)', () => { await expect( service.sellerUpdateOrderStatus(account.id, { orderId: order.id.toString(), - toStatus: 'CANCELED', - note: '취소', + toStatus: 'CONFIRMED', }), ).rejects.toThrowDomain('ORDER_NOT_FOUND'); }); @@ -570,21 +628,248 @@ describe('SellerOrderService (real DB)', () => { }); }); - it('CANCELED 전환 + note 제공 시 정상 처리', async () => { + it('픽업 완료는 확인된 결제액으로 정산을 확정한다(수수료 원 미만 버림)', async () => { const { account, store } = await setupSellerWithStore(prisma); - const order = await createStoreOrder(store.id); + const order = await createStoreOrder(store.id, { + status: 'MADE', + paid: true, + commissionRateBps: 333, + }); - const result = await service.sellerUpdateOrderStatus(account.id, { + await service.sellerUpdateOrderStatus(account.id, { orderId: order.id.toString(), - toStatus: 'CANCELED', - note: '재고 부족', + toStatus: 'PICKED_UP', }); - expect(result.status).toBe('CANCELED'); - const histories = await prisma.orderStatusHistory.findMany({ - where: { order_id: order.id }, + const row = await prisma.order.findUniqueOrThrow({ + where: { id: order.id }, + }); + expect(row).toMatchObject({ + status: 'PICKED_UP', + settlement_base_amount: 10_000, + commission_amount: 333, + settlement_id: null, + }); + expect(row.settlement_finalized_at).toEqual(row.picked_up_at); + }); + + it('확인된 결제가 없는 주문(결제 도입 전)의 픽업 완료는 정산을 확정하지 않는다', async () => { + const { account, store } = await setupSellerWithStore(prisma); + const order = await createStoreOrder(store.id, { status: 'MADE' }); + + await service.sellerUpdateOrderStatus(account.id, { + orderId: order.id.toString(), + toStatus: 'PICKED_UP', + }); + + await expect( + prisma.order.findUniqueOrThrow({ where: { id: order.id } }), + ).resolves.toMatchObject({ + status: 'PICKED_UP', + settlement_base_amount: null, + settlement_finalized_at: null, + }); + }); + + it('픽업 완료가 아닌 전이는 정산을 확정하지 않는다', async () => { + const { account, store } = await setupSellerWithStore(prisma); + const order = await createStoreOrder(store.id, { + status: 'CONFIRMED', + paid: true, + }); + + await service.sellerUpdateOrderStatus(account.id, { + orderId: order.id.toString(), + toStatus: 'MADE', + }); + + await expect( + prisma.order.findUniqueOrThrow({ where: { id: order.id } }), + ).resolves.toMatchObject({ settlement_finalized_at: null }); + }); + }); + + describe('sellerCancelOrder', () => { + function cancelInput( + orderId: bigint, + overrides: Partial = {}, + ): SellerCancelOrderInput { + return { + orderId: orderId.toString(), + reason: 'OUT_OF_MATERIALS', + ...overrides, + }; + } + + it('접수 주문 거절은 결제액 전액 환불이고 사정은 기록하지 않는다', async () => { + const { account, store } = await setupSellerWithStore(prisma); + const order = await createStoreOrder(store.id, { paid: true }); + const topic = await collectTopic(pubSub, `order.seller.${store.id}`); + + const result = await service.sellerCancelOrder( + account.id, + cancelInput(order.id, { + reason: 'DESIGN_NOT_FEASIBLE', + note: '도안이 어려워요', + fault: 'BUYER', + refundAmount: 0, + }), + ); + + expect(result).toMatchObject({ + status: 'CANCELED', + firstItemName: 'Product snapshot', + }); + await expect( + prisma.orderStatusHistory.findFirstOrThrow({ + where: { order_id: order.id }, + }), + ).resolves.toMatchObject({ + from_status: 'SUBMITTED', + actor_type: 'SELLER', + actor_account_id: account.id, + cancel_reason: 'DESIGN_NOT_FEASIBLE', + cancel_fault: null, + refund_amount: 10_000, + note: '도안이 어려워요', + }); + await expect( + prisma.refund.findFirstOrThrow({ where: { order_id: order.id } }), + ).resolves.toMatchObject({ amount: 10_000, status: 'AWAITING_ACCOUNT' }); + expect(topic.received).toEqual([ + expect.objectContaining({ + kind: 'STATUS_CHANGED', + orderId: order.id.toString(), + status: 'CANCELED', + }), + ]); + topic.stop(); + }); + + it('제작 완료 주문도 취소할 수 있고 구매자 사정이면 R만 환불하고 남는 금액을 정산 확정한다', async () => { + const { account, store } = await setupSellerWithStore(prisma); + const order = await createStoreOrder(store.id, { + status: 'MADE', + paid: true, + commissionRateBps: 1_000, + }); + + await service.sellerCancelOrder( + account.id, + cancelInput(order.id, { + reason: 'BUYER_REQUEST', + fault: 'BUYER', + refundAmount: 2_500, + }), + ); + + await expect( + prisma.refund.findFirstOrThrow({ where: { order_id: order.id } }), + ).resolves.toMatchObject({ amount: 2_500 }); + await expect( + prisma.order.findUniqueOrThrow({ where: { id: order.id } }), + ).resolves.toMatchObject({ + status: 'CANCELED', + settlement_base_amount: 7_500, + commission_amount: 750, + }); + }); + + it.each([ + [ + '미입금 사유', + 'SUBMITTED', + { reason: 'PAYMENT_NOT_RECEIVED' }, + 'CANCEL_REASON_NOT_ALLOWED', + ], + [ + '자동 미확정 사유', + 'SUBMITTED', + { reason: 'CONFIRM_TIMEOUT' }, + 'CANCEL_REASON_NOT_ALLOWED', + ], + ['확정 주문에 사정 없음', 'CONFIRMED', {}, 'CANCEL_FAULT_REQUIRED'], + [ + '구매자 사정에 금액 없음', + 'CONFIRMED', + { fault: 'BUYER' }, + 'REFUND_AMOUNT_REQUIRED', + ], + [ + '결제액 + 1원', + 'MADE', + { fault: 'BUYER', refundAmount: 10_001 }, + 'REFUND_AMOUNT_OUT_OF_RANGE', + ], + [ + '픽업 완료 주문', + 'PICKED_UP', + { fault: 'SELLER' }, + 'ORDER_NOT_CANCELLABLE', + ], + ['이미 취소된 주문', 'CANCELED', {}, 'ORDER_NOT_CANCELLABLE'], + ] as const)( + '%s는 %s로 거절한다', + async (_label, status, overrides, code) => { + const { account, store } = await setupSellerWithStore(prisma); + const order = await createStoreOrder(store.id, { status, paid: true }); + + await expect( + service.sellerCancelOrder( + account.id, + cancelInput(order.id, overrides), + ), + ).rejects.toThrowDomain(code); + expect( + await prisma.orderStatusHistory.count({ + where: { order_id: order.id }, + }), + ).toBe(0); + }, + ); + + it('다른 매장 주문과 입금 확인 전 주문은 404다', async () => { + const me = await setupSellerWithStore(prisma); + const other = await setupSellerWithStore(prisma); + const othersOrder = await createStoreOrder(other.store.id); + const pending = await createStoreOrder(me.store.id, { + status: 'PENDING_PAYMENT', + }); + + for (const order of [othersOrder, pending]) { + await expect( + service.sellerCancelOrder(me.account.id, cancelInput(order.id)), + ).rejects.toThrowDomain('ORDER_NOT_FOUND'); + } + expect(await prisma.orderStatusHistory.count()).toBe(0); + }); + + it('취소된 주문 상세는 취소 정보(주체·사유·환불)를 준다', async () => { + const { account, store } = await setupSellerWithStore(prisma); + const order = await createStoreOrder(store.id, { + status: 'CONFIRMED', + paid: true, + }); + await service.sellerCancelOrder( + account.id, + cancelInput(order.id, { fault: 'SELLER' }), + ); + + const detail = await service.sellerOrder(account.id, order.id); + + expect(detail.cancellation).toMatchObject({ + actorType: 'SELLER', + reason: 'OUT_OF_MATERIALS', + reasonLabel: '재료 소진', + fault: 'SELLER', + refundAmount: 10_000, + refundStatus: 'AWAITING_ACCOUNT', + }); + expect(detail.statusHistories[0]).toMatchObject({ + toStatus: 'CANCELED', + actorType: 'SELLER', + cancelReason: 'OUT_OF_MATERIALS', }); - expect(histories[0].note).toBe('재고 부족'); }); }); diff --git a/src/features/order/services/order-seller.service.ts b/src/features/order/services/order-seller.service.ts index e3a5b540..16d63192 100644 --- a/src/features/order/services/order-seller.service.ts +++ b/src/features/order/services/order-seller.service.ts @@ -1,6 +1,8 @@ import { Inject, Injectable } from '@nestjs/common'; +import { MAX_REASON_LENGTH } from '@/common/constants/reason.constants'; import { DomainException } from '@/common/errors/error-catalog'; +import { ClockService } from '@/common/providers/clock.service'; import type { CursorConnection } from '@/common/types/cursor-connection.type'; import { toDate } from '@/common/utils/date-parser'; import { parseId, parseOptionalId } from '@/common/utils/id-parser'; @@ -14,9 +16,12 @@ import { AUDIT_LOG_REPOSITORY, type IAuditLogRepository, } from '@/features/audit-log'; +import type { SellerCancelOrderInput } from '@/features/order/dto/inputs/seller-cancel-order.input'; import type { SellerOrderListInput } from '@/features/order/dto/inputs/seller-order-list.input'; import type { SellerUpdateOrderStatusInput } from '@/features/order/dto/inputs/seller-update-order-status.input'; +import { OrderCancelPolicy } from '@/features/order/policies/order-cancel.policy'; import { OrderStatusTransitionPolicy } from '@/features/order/policies/order-status-transition.policy'; +import { OrderTransitionRepository } from '@/features/order/repositories/order-transition.repository'; import { OrderRepository, type SellerOrderRow, @@ -24,6 +29,7 @@ import { import { toSellerOrderUpdateEvent } from '@/features/order/services/order-events-mappers.helper'; import { OrderEventsService } from '@/features/order/services/order-events.service'; import { + toOrderCancellation, toOrderItemDetail, toOrderStatusHistory, type OrderItemDetailRow, @@ -34,7 +40,12 @@ import type { SellerOrderSummaryOutput, } from '@/features/order/types/order-seller-output.type'; import { SellerBaseService, StoreSellerRepository } from '@/features/store'; -import { OrderStatus, type PaymentMethod } from '@/generated/prisma/client'; +import { + OrderActor, + OrderStatus, + type PaymentMethod, + type Refund, +} from '@/generated/prisma/client'; @Injectable() export class SellerOrderService extends SellerBaseService { @@ -44,7 +55,10 @@ export class SellerOrderService extends SellerBaseService { auditLogs: IAuditLogRepository, private readonly orderRepository: OrderRepository, private readonly statusPolicy: OrderStatusTransitionPolicy, + private readonly cancelPolicy: OrderCancelPolicy, + private readonly transitions: OrderTransitionRepository, private readonly events: OrderEventsService, + private readonly clock: ClockService, ) { super(repo, auditLogs); } @@ -117,12 +131,6 @@ export class SellerOrderService extends SellerBaseService { this.statusPolicy.assertSellerTransition(current.status, toStatus); - if (this.statusPolicy.requiresCancellationNote(toStatus)) { - if (!input.note || input.note.trim().length === 0) { - throw new DomainException('CANCELLATION_NOTE_REQUIRED'); - } - } - const updated = await this.orderRepository.updateOrderStatusBySeller({ orderId, storeId: ctx.storeId, @@ -148,6 +156,35 @@ export class SellerOrderService extends SellerBaseService { return this.toOrderSummaryOutput(updated); } + /** 접수 단계 거절(전액 환불)과 확정 뒤 취소(사정 선택). 입금 확인 전 주문은 없는 주문과 같다. */ + async sellerCancelOrder( + accountId: bigint, + input: SellerCancelOrderInput, + ): Promise { + const ctx = await this.requireSellerContext(accountId); + const updated = await this.transitions.cancel({ + orderId: parseId(input.orderId), + actor: OrderActor.SELLER, + actorAccountId: ctx.accountId, + scope: { kind: 'store', storeId: ctx.storeId }, + note: cleanNullableText(input.note, MAX_REASON_LENGTH), + now: this.clock.now(), + decide: (state) => + this.cancelPolicy.decide( + { + actor: OrderActor.SELLER, + reason: input.reason, + fault: input.fault, + refundAmount: input.refundAmount, + }, + state, + ), + }); + if (!updated) throw new DomainException('ORDER_NOT_FOUND'); + await this.events.publishSellerStatusChanged(updated); + return this.toOrderSummaryOutput(updated); + } + private toOrderSummaryOutput(row: SellerOrderRow): SellerOrderSummaryOutput { return { id: row.id.toString(), @@ -185,6 +222,7 @@ export class SellerOrderService extends SellerBaseService { created_at: Date; updated_at: Date; status_histories: OrderStatusHistoryRow[]; + refunds: Refund[]; items: OrderItemDetailRow[]; }): SellerOrderDetailOutput { return { @@ -216,6 +254,7 @@ export class SellerOrderService extends SellerBaseService { : history, ), ), + cancellation: toOrderCancellation(row), }; } } diff --git a/src/features/order/types/order-admin-output.type.ts b/src/features/order/types/order-admin-output.type.ts index e4f727fc..8a761303 100644 --- a/src/features/order/types/order-admin-output.type.ts +++ b/src/features/order/types/order-admin-output.type.ts @@ -1,9 +1,16 @@ +import type { CancelRefundRule } from '@/features/order/policies/order-cancel.policy'; import type { + OrderCancellationOutput, OrderItemDetailOutput, + OrderRefundOutput, OrderStatusHistoryOutput, } from '@/features/order/types/order-output.type'; import type { AdminOrderPaymentOutput } from '@/features/order/types/order-payment-output.type'; -import type { AccountStatus, OrderStatus } from '@/generated/prisma/client'; +import type { + AccountStatus, + OrderCancelReason, + OrderStatus, +} from '@/generated/prisma/client'; export interface AdminOrderSummaryOutput { id: string; @@ -54,4 +61,14 @@ export interface AdminOrderDetailOutput { updatedAt: Date; items: OrderItemDetailOutput[]; statusHistories: OrderStatusHistoryOutput[]; + refunds: OrderRefundOutput[]; + cancellation: OrderCancellationOutput | null; + cancelOptions: AdminOrderCancelOptionsOutput; +} + +export interface AdminOrderCancelOptionsOutput { + cancelable: boolean; + reasons: OrderCancelReason[]; + refundRule: CancelRefundRule | null; + paidAmount: number; } diff --git a/src/features/order/types/order-my-output.type.ts b/src/features/order/types/order-my-output.type.ts index 808e41d6..15947eac 100644 --- a/src/features/order/types/order-my-output.type.ts +++ b/src/features/order/types/order-my-output.type.ts @@ -1,5 +1,6 @@ import type { OffsetConnection } from '@/common/types/cursor-connection.type'; import type { + OrderCancellationOutput, OrderItemDetailOutput, OrderStatusHistoryOutput, } from '@/features/order/types/order-output.type'; @@ -64,6 +65,8 @@ export interface MyOrderDetail { madeAt: Date | null; pickedUpAt: Date | null; canceledAt: Date | null; + cancellation: OrderCancellationOutput | null; + canCancel: boolean; statusHistories: OrderStatusHistoryOutput[]; items: MyOrderItem[]; store: MyOrderStoreInfo; diff --git a/src/features/order/types/order-output.type.ts b/src/features/order/types/order-output.type.ts index 8004ef7b..922fb59e 100644 --- a/src/features/order/types/order-output.type.ts +++ b/src/features/order/types/order-output.type.ts @@ -1,4 +1,12 @@ -import type { OrderStatus } from '@/generated/prisma/client'; +import type { BankOutput } from '@/features/order/types/order-payment-output.type'; +import type { + OrderActor, + OrderCancelFault, + OrderCancelReason, + OrderStatus, + RefundKind, + RefundStatus, +} from '@/generated/prisma/client'; export interface OrderItemOptionOutput { id: string; @@ -49,4 +57,33 @@ export interface OrderStatusHistoryOutput { toStatus: OrderStatus; changedAt: Date; note: string | null; + actorType: OrderActor; + cancelReason: OrderCancelReason | null; + cancelFault: OrderCancelFault | null; + refundAmount: number | null; +} + +export interface OrderCancellationOutput { + actorType: OrderActor; + reason: OrderCancelReason; + reasonLabel: string; + note: string | null; + fault: OrderCancelFault | null; + refundAmount: number; + refundStatus: RefundStatus | null; + refundCompletedAt: Date | null; + canceledAt: Date; +} + +export interface OrderRefundOutput { + id: string; + kind: RefundKind; + amount: number; + status: RefundStatus; + bank: BankOutput | null; + accountHolder: string | null; + accountNumberMasked: string | null; + requestedAt: Date; + accountSubmittedAt: Date | null; + completedAt: Date | null; } diff --git a/src/features/order/types/order-seller-output.type.ts b/src/features/order/types/order-seller-output.type.ts index 66cb8df5..1e76d016 100644 --- a/src/features/order/types/order-seller-output.type.ts +++ b/src/features/order/types/order-seller-output.type.ts @@ -1,4 +1,5 @@ import type { + OrderCancellationOutput, OrderItemDetailOutput, OrderStatusHistoryOutput, } from '@/features/order/types/order-output.type'; @@ -39,6 +40,7 @@ export interface SellerOrderDetailOutput { updatedAt: Date; items: OrderItemDetailOutput[]; statusHistories: OrderStatusHistoryOutput[]; + cancellation: OrderCancellationOutput | null; } /** SDL SellerOrderUpdateKind. PICKUP_RESCHEDULED는 판매자 픽업 일시 변경이 발행한다. */ diff --git a/src/test/enum-sdl-sync.spec.ts b/src/test/enum-sdl-sync.spec.ts index 8625ec3d..35a3d670 100644 --- a/src/test/enum-sdl-sync.spec.ts +++ b/src/test/enum-sdl-sync.spec.ts @@ -3,6 +3,7 @@ import { join } from 'node:path'; import { Kind, parse, print, visit } from 'graphql'; +import { CANCEL_REFUND_RULES } from '@/features/order/policies/order-cancel.policy'; import { THREE_D_OPTION_CATEGORIES } from '@/features/product/constants/custom-3d-catalog.constants'; import { ConversationBodyFormat, @@ -10,7 +11,11 @@ import { CustomTextAlign, NotificationEvent, OrderActor, + OrderCancelFault, + OrderCancelReason, OrderStatus, + RefundKind, + RefundStatus, } from '@/generated/prisma/client'; /** @@ -44,6 +49,36 @@ const PAIRS: Array< 'src/features/order/order.types.graphql', 'OrderActorType', ], + [ + 'OrderCancelReason', + Object.values(OrderCancelReason), + 'src/features/order/order.types.graphql', + 'OrderCancelReasonType', + ], + [ + 'OrderCancelFault', + Object.values(OrderCancelFault), + 'src/features/order/order.types.graphql', + 'OrderCancelFaultType', + ], + [ + 'CancelRefundRule', + [...CANCEL_REFUND_RULES], + 'src/features/order/order.types.graphql', + 'CancelRefundRuleType', + ], + [ + 'RefundKind', + Object.values(RefundKind), + 'src/features/order/order.types.graphql', + 'RefundKindType', + ], + [ + 'RefundStatus', + Object.values(RefundStatus), + 'src/features/order/order.types.graphql', + 'RefundStatusType', + ], [ 'CustomMode', Object.values(CustomMode), diff --git a/src/test/factories/order.factory.ts b/src/test/factories/order.factory.ts index 86b11800..392d7702 100644 --- a/src/test/factories/order.factory.ts +++ b/src/test/factories/order.factory.ts @@ -27,6 +27,7 @@ export interface OrderOverrides { deleted_at?: Date; idempotency_key?: string; created_at?: Date; + commission_rate_bps?: number; /** 미지정 시 PENDING_PAYMENT면 null, 그 밖의 상태는 생성 시각(입금 확인 = 판매자 노출) */ submitted_at?: Date | null; } @@ -57,6 +58,9 @@ export async function createOrder( : {}), ...(overrides.deleted_at ? { deleted_at: overrides.deleted_at } : {}), ...(overrides.created_at ? { created_at: overrides.created_at } : {}), + ...(overrides.commission_rate_bps !== undefined + ? { commission_rate_bps: overrides.commission_rate_bps } + : {}), submitted_at: overrides.submitted_at !== undefined ? overrides.submitted_at diff --git a/src/test/roles-coverage.spec.ts b/src/test/roles-coverage.spec.ts index f8839b3f..17c91e7b 100644 --- a/src/test/roles-coverage.spec.ts +++ b/src/test/roles-coverage.spec.ts @@ -13,7 +13,7 @@ describe('접두 루트 필드 인가 커버리지', () => { const handlerAuth = collectHandlerAuth(collectFeatureResolverClasses()); describe.each([ - ['seller', 'SELLER', 59], + ['seller', 'SELLER', 60], ['admin', 'ADMIN', 67], ] as const)('%s 접두 → @Roles(%s)', (prefix, role, count) => { const fields = collectRootFieldsWithPrefix(prefix); From 8220761d79cc14195960201acad4c20aedf452f0 Mon Sep 17 00:00:00 2001 From: chanwoo7 Date: Thu, 19 Nov 2026 04:47:56 +0900 Subject: [PATCH 30/54] =?UTF-8?q?fix:=20=EA=B5=AC=EB=A7=A4=EC=9E=90=20?= =?UTF-8?q?=EC=B7=A8=EC=86=8C=20=EA=B0=90=EC=82=AC=EB=A5=BC=20=ED=8C=90?= =?UTF-8?q?=EB=A7=A4=EC=9E=90=EC=97=90=EA=B2=8C=20=EC=88=A8=EA=B8=B0?= =?UTF-8?q?=EA=B3=A0=20=ED=8C=90=EB=A7=A4=EC=9E=90=20=EC=B7=A8=EC=86=8C=20?= =?UTF-8?q?=EB=B2=94=EC=9C=84=EC=97=90=EC=84=9C=20=ED=92=88=EB=AA=A9=20?= =?UTF-8?q?=EC=82=AD=EC=A0=9C=20=EC=A3=BC=EB=AC=B8=EC=9D=84=20=EB=BA=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ① 무엇·왜 - 구매자 본인 취소(접수 주문)의 감사가 매장 id를 달고 남아, 같은 매장 판매자의 감사 로그(store_id ∧ ORDER)에 구매자 계정 id·IP·User-Agent가 그대로 보였다. ORDER 감사에 구매자 행위자가 처음 생긴 경로다. 이력에 주체·계정이 이미 있고 관리자 감사 조회에는 남아야 하므로 기록은 두고 매장 id만 비운다. - 판매자 범위 잠금 SQL의 EXISTS가 품목 deleted_at을 보지 않아, 그 매장 품목이 삭제된 주문(판매자 상세는 404)을 판매자가 취소할 수 있었다. raw SQL은 soft-delete Extension 밖이라 직접 건다. - 판매자 상태 변경의 시각이 new Date()라, 이제 그 값이 픽업 완료 정산 확정 시각(settlement_finalized_at, 주간 정산의 주 경계 기준)이 되는데도 테스트가 고정할 수 없었다. ② 변경점 - OrderTransitionRepository.cancelLocked: 감사 storeId는 접수된 주문이고 주체가 구매자가 아닐 때만 - cancelScopeSql('store'): EXISTS에 i.deleted_at IS NULL - SellerOrderService.sellerUpdateOrderStatus: now를 ClockService로 - SDL NotificationEvent.ORDER_PAYMENT_EXPIRED 설명: 운영자 미입금 취소도 같은 값을 낸다는 점을 반영 - 판매자 상태 변경 잠금 SQL(updateOrderStatusBySeller)의 같은 누락은 기존 동작을 기존 테스트가 고정하고 있어 이 커밋에서 바꾸지 않는다 ③ 테스트 - 주체 4 × (입금 대기·접수) 감사 표 7행(판매자 입금 대기는 범위 밖): actor·store_id와 같은 매장 다른 판매자 감사 목록 노출 여부 - 범위 밖 테스트에 품목 삭제 주문(판매자 범위) 추가 - 판매자 픽업 완료 정산 테스트가 고정 시각으로 picked_up_at·settlement_finalized_at을 단언 - 반증: 세 수정을 되돌리면 위 3건이 실패하는 것을 확인 --- .../notification/notification.types.graphql | 2 +- .../order-transition.repository.spec.ts | 91 ++++++++++++++++++- .../order-transition.repository.ts | 10 +- .../services/order-seller.service.spec.ts | 20 +++- .../order/services/order-seller.service.ts | 2 +- 5 files changed, 114 insertions(+), 11 deletions(-) diff --git a/src/features/notification/notification.types.graphql b/src/features/notification/notification.types.graphql index 8a0d6922..cfab71ea 100644 --- a/src/features/notification/notification.types.graphql +++ b/src/features/notification/notification.types.graphql @@ -49,7 +49,7 @@ enum NotificationEvent { """ ORDER_PAYMENT_CONFIRMED """ - 입금 기한 안에 입금이 확인되지 않아 주문이 취소됐다. type은 ORDER_STATUS. + 입금이 확인되지 않아 주문이 취소됐다(입금 기한 만료 자동 취소 또는 운영자 미입금 취소). type은 ORDER_STATUS. """ ORDER_PAYMENT_EXPIRED """ diff --git a/src/features/order/repositories/order-transition.repository.spec.ts b/src/features/order/repositories/order-transition.repository.spec.ts index 23bf0160..97ea5d25 100644 --- a/src/features/order/repositories/order-transition.repository.spec.ts +++ b/src/features/order/repositories/order-transition.repository.spec.ts @@ -12,8 +12,10 @@ import { OrderTransitionRepository, type CancelOrderArgs, type ConfirmPaymentArgs, + type OrderCancelScope, } from '@/features/order/repositories/order-transition.repository'; import type { OrderStatus, PrismaClient } from '@/generated/prisma/client'; +import { requestContextStorage } from '@/global/request-context'; import { disconnectTestPrismaClient } from '@/test/db/prisma-test-client'; import { closeTruncateConnection, truncateAll } from '@/test/db/truncate'; import { @@ -29,6 +31,7 @@ const NOW = new Date('2026-09-16T07:00:00.000Z'); describe('OrderTransitionRepository (real DB)', () => { let repo: OrderTransitionRepository; + let auditLogs: AuditLogRepository; let prisma: PrismaClient; beforeAll(async () => { @@ -40,6 +43,7 @@ describe('OrderTransitionRepository (real DB)', () => { ], }); repo = module.get(OrderTransitionRepository); + auditLogs = module.get(AUDIT_LOG_REPOSITORY); prisma = p; }); @@ -403,15 +407,24 @@ describe('OrderTransitionRepository (real DB)', () => { expect(await prisma.auditLog.count()).toBe(0); }); - it('범위 밖 주문은 null이다: 다른 구매자, 입금 전·다른 매장(판매자), 삭제된 주문', async () => { + it('범위 밖 주문은 null이다: 다른 구매자, 입금 전·다른 매장·품목 삭제(판매자), 삭제된 주문', async () => { const { order, item } = await paidOrder('SUBMITTED'); const pending = await paidOrder('PENDING_PAYMENT'); + const itemDeleted = await paidOrder('SUBMITTED'); + await prisma.orderItem.update({ + where: { id: itemDeleted.item.id }, + data: { deleted_at: NOW }, + }); const deleted = await createOrder(prisma, { deleted_at: new Date() }); for (const [id, scope] of [ [order.id, { kind: 'buyer', accountId: order.account_id + 1n }], [order.id, { kind: 'store', storeId: item.store_id + 1n }], [pending.order.id, { kind: 'store', storeId: pending.item.store_id }], + [ + itemDeleted.order.id, + { kind: 'store', storeId: itemDeleted.item.store_id }, + ], [deleted.id, { kind: 'any' }], ] as const) { await expect( @@ -488,6 +501,82 @@ describe('OrderTransitionRepository (real DB)', () => { expect(systemEvent.actor_account_id).toBeNull(); }); + // 판매자는 입금 대기 주문이 범위 밖이라 표에서 뺀다(범위 밖 테스트) + it.each([ + ['BUYER', 'PENDING_PAYMENT', '매장 없이 남긴다'], + ['BUYER', 'SUBMITTED', '매장 없이 남긴다'], + ['SELLER', 'SUBMITTED', '매장과 함께 남긴다'], + ['ADMIN', 'PENDING_PAYMENT', '매장 없이 남긴다'], + ['ADMIN', 'SUBMITTED', '매장과 함께 남긴다'], + ['SYSTEM', 'PENDING_PAYMENT', '남기지 않는다'], + ['SYSTEM', 'SUBMITTED', '남기지 않는다'], + ] as const)( + '%s의 %s 취소 감사는 %s — 같은 매장 다른 판매자의 감사 목록에는 매장이 있을 때만 보인다', + async (actor, status, audit) => { + const { order, item } = await paidOrder(status); + const actorAccountId = + actor === 'SYSTEM' + ? null + : actor === 'BUYER' + ? order.account_id + : (await createAccount(prisma, { account_type: actor })).id; + const scope: OrderCancelScope = + actor === 'BUYER' + ? { kind: 'buyer', accountId: order.account_id } + : actor === 'SELLER' + ? { kind: 'store', storeId: item.store_id } + : { kind: 'any' }; + + await requestContextStorage.run( + { clientIp: '203.0.113.77', userAgent: 'buyer-phone' }, + () => + repo.cancel( + cancelArgs( + order.id, + {}, + { + actor, + actorAccountId, + scope, + decide: () => ({ + reason: 'OTHER', + fault: null, + refundAmount: 0, + }), + }, + ), + ), + ); + + const audits = await prisma.auditLog.findMany(); + expect( + audits.map((a) => ({ + actor: a.actor_account_id, + store: a.store_id, + })), + ).toEqual( + audit === '남기지 않는다' + ? [] + : [ + { + actor: actorAccountId, + store: audit === '매장과 함께 남긴다' ? item.store_id : null, + }, + ], + ); + const otherSeller = await createAccount(prisma, { + account_type: 'SELLER', + }); + await expect( + auditLogs.listAuditLogsBySeller({ + sellerAccountId: otherSeller.id, + storeId: item.store_id, + limit: 10, + }), + ).resolves.toHaveLength(audit === '매장과 함께 남긴다' ? 1 : 0); + }, + ); + it('동시에 두 번 취소해도 하나만 성공하고 환불은 1건이다', async () => { const { order } = await paidOrder('SUBMITTED'); diff --git a/src/features/order/repositories/order-transition.repository.ts b/src/features/order/repositories/order-transition.repository.ts index b1fae4d8..38305604 100644 --- a/src/features/order/repositories/order-transition.repository.ts +++ b/src/features/order/repositories/order-transition.repository.ts @@ -83,7 +83,8 @@ function cancelScopeSql(scope: OrderCancelScope): Prisma.Sql { return Prisma.sql`AND o.account_id = ${scope.accountId}`; case 'store': return Prisma.sql`AND o.submitted_at IS NOT NULL AND EXISTS ( - SELECT 1 FROM order_item i WHERE i.order_id = o.id AND i.store_id = ${scope.storeId})`; + SELECT 1 FROM order_item i + WHERE i.order_id = o.id AND i.store_id = ${scope.storeId} AND i.deleted_at IS NULL)`; default: return Prisma.empty; } @@ -368,8 +369,11 @@ export class OrderTransitionRepository { if (args.actorAccountId !== null) { await this.auditLogs.recordAudit(tx, { actorAccountId: args.actorAccountId, - // 입금 전 주문은 판매자에게 보이지 않으므로 매장 감사 로그에도 남기지 않는다 - storeId: locked.submitted_at ? (firstItem?.store_id ?? null) : null, + // 매장 id가 붙으면 판매자 감사 로그에 ip·ua까지 보인다 — 입금 전 주문과 구매자 행위는 비운다 + storeId: + locked.submitted_at && args.actor !== OrderActor.BUYER + ? (firstItem?.store_id ?? null) + : null, targetType: AuditTargetType.ORDER, targetId: locked.id, action: AuditActionType.STATUS_CHANGE, diff --git a/src/features/order/services/order-seller.service.spec.ts b/src/features/order/services/order-seller.service.spec.ts index 57e4d482..4f8faa9d 100644 --- a/src/features/order/services/order-seller.service.spec.ts +++ b/src/features/order/services/order-seller.service.spec.ts @@ -1,5 +1,6 @@ import { PubSub } from 'graphql-subscriptions'; +import { ClockService } from '@/common/providers/clock.service'; import { AUDIT_LOG_REPOSITORY } from '@/features/audit-log'; import { AuditLogRepository } from '@/features/audit-log/repositories/audit-log.repository'; import type { SellerCancelOrderInput } from '@/features/order/dto/inputs/seller-cancel-order.input'; @@ -31,6 +32,7 @@ describe('SellerOrderService (real DB)', () => { let prisma: PrismaClient; let repo: OrderRepository; let pubSub: PubSub; + let clock: ClockService; beforeAll(async () => { const { module, prisma: p } = await createTestingModuleWithRealDb({ @@ -55,6 +57,7 @@ describe('SellerOrderService (real DB)', () => { service = module.get(SellerOrderService); repo = module.get(OrderRepository); pubSub = module.get(PUB_SUB); + clock = module.get(ClockService); prisma = p; }); @@ -67,6 +70,10 @@ describe('SellerOrderService (real DB)', () => { await truncateAll(); }); + afterEach(() => { + jest.restoreAllMocks(); + }); + async function createStoreOrder( storeId: bigint, opts: { @@ -636,21 +643,24 @@ describe('SellerOrderService (real DB)', () => { commissionRateBps: 333, }); + const now = new Date('2026-09-16T07:00:00.000Z'); + jest.spyOn(clock, 'now').mockReturnValue(now); + await service.sellerUpdateOrderStatus(account.id, { orderId: order.id.toString(), toStatus: 'PICKED_UP', }); - const row = await prisma.order.findUniqueOrThrow({ - where: { id: order.id }, - }); - expect(row).toMatchObject({ + await expect( + prisma.order.findUniqueOrThrow({ where: { id: order.id } }), + ).resolves.toMatchObject({ status: 'PICKED_UP', + picked_up_at: now, settlement_base_amount: 10_000, commission_amount: 333, + settlement_finalized_at: now, settlement_id: null, }); - expect(row.settlement_finalized_at).toEqual(row.picked_up_at); }); it('확인된 결제가 없는 주문(결제 도입 전)의 픽업 완료는 정산을 확정하지 않는다', async () => { diff --git a/src/features/order/services/order-seller.service.ts b/src/features/order/services/order-seller.service.ts index 16d63192..1f0cc40d 100644 --- a/src/features/order/services/order-seller.service.ts +++ b/src/features/order/services/order-seller.service.ts @@ -137,7 +137,7 @@ export class SellerOrderService extends SellerBaseService { actorAccountId: ctx.accountId, toStatus, note: cleanNullableText(input.note, 500), - now: new Date(), + now: this.clock.now(), // 잠금 뒤 현재 상태로 같은 규칙을 다시 적용한다(위 사전 검사는 빠른 거절용) assertTransition: (from) => this.statusPolicy.assertSellerTransition(from, toStatus), From 81cb14f098e927e2eee8b94b5368cdced88948b2 Mon Sep 17 00:00:00 2001 From: chanwoo7 Date: Thu, 19 Nov 2026 04:02:49 +0900 Subject: [PATCH 31/54] =?UTF-8?q?feat:=20=EC=A3=BC=EB=AC=B8=20=EC=BB=A4?= =?UTF-8?q?=EC=8A=A4=ED=85=80=20=EC=8A=A4=EB=83=85=EC=83=B7=20=EC=8A=A4?= =?UTF-8?q?=ED=82=A4=EB=A7=88=EC=99=80=20=EC=A3=BC=EB=AC=B8=20=EC=83=81?= =?UTF-8?q?=EC=84=B8=20=EC=BB=A4=EC=8A=A4=ED=85=80=20=EC=B6=9C=EB=A0=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 주문에 커스텀 방식·바탕·대표 이미지, 문구 자리 표시 이름·좌표·스타일, 자유 편집 영역, 3D 디자인 JSON(스키마 버전 동반)과 커스텀 이미지(3D 렌더 5장·슬롯형 합성 1장)를 스냅샷으로 남기고 구매자·판매자·관리자 상세에 내보낸다. 자유 편집은 크롭 이미지 대신 바탕 위 영역 좌표만 저장한다. 리뷰 Before와 판매자·관리자 목록 '커스텀' 배지는 품목의 커스텀 대표 이미지·방식을 쓴다. 주문 생성의 커스텀 입력·저장은 다음 PR이 붙인다. 변경점 - 스키마·마이그레이션(order_custom_snapshot) - order_item: custom_mode_snapshot(기본 NONE)·custom_base_image_url_snapshot·custom_preview_image_url - order_item_custom_text: token_id(FK 없음, 자리 지정 전 주문 null)·label_snapshot·pos_x..height·text_color·text_align, value_text nullable('문구 없음') - order_item_custom_free_edit: pos_x..height 추가, crop_image_url 삭제 - 신규 order_item_custom_design(order_item_id unique, schema_version, design_json)·order_item_custom_image(kind, image_url, (order_item_id, kind) unique). 주문과 함께 한 번만 쓰여 deleted_at이 없고 가시성은 부모 품목을 따른다(SOFT_DELETE_MODELS 미등록) - 백필: 기존 문구·자유 편집은 바탕 전체 영역(0/0/10000/10000)·#000000·CENTER, 표시 이름은 키 앞 30자, 살아 있는 문구·자유 편집이 있는 품목은 SLOT. 백필 뒤 좌표·스타일 기본값 제거 - 출력: OrderItemDetail.customMode·customPreviewImageUrl·customBaseImageUrl·customImages(kind 선언 순)·threeDDesign(타입 출력 ThreeDDesign), OrderItemCustomText.tokenId·label·valueText(nullable)·좌표·textColor·textAlign, OrderItemFreeEdit.posX..height(cropImageUrl 삭제). 상세 include 3곳은 공용 조각 하나로 합쳤다 - 저장된 디자인 JSON은 형태·버전을 방어적으로 읽고 어긋나면 디자인만 null + 경고 로그(상세는 내려간다) - 리뷰 Before 원천을 custom_preview_image_url로 바꿨다(기존 리뷰 불변, 옵션 요약 현행, 문구 미복사) - 배지: SellerOrderSummary·AdminOrderSummary.hasCustom·firstItemCustomImageUrl, SellerOrderUpdate.hasCustom(발행 매퍼가 행의 첫 품목에서 상품명·커스텀 여부를 함께 읽는다) - 시드: 문구·자유 편집 새 열, 슬롯형 합성 이미지 예시. resetSeedScope는 디자인·이미지를 주문 품목보다 먼저 지운다 - 게이트: model-ownership(디자인·이미지 order, 앱 writer는 주문 생성 PR에서), removed-schema-elements(OrderItemFreeEdit.cropImageUrl), enum-sdl-sync(CustomImageKind ↔ CustomImageKindType) 테스트 - 마이그레이션 spec 3건(마이그레이션 직전 모양 임시 표에서 열 추가·백필·기본값 제거 실행): 이행 값, 기본값 제거·nullable, SLOT 판정(삭제만 있는 품목 NONE) - 리뷰 07b 백필 spec은 지워진 crop_image_url을 임시 표로 되살려 그대로 검증 - 디자인 방어 파싱 26건(정상·키 생략·행 없음 + 깨진 형태 23종 → null + 기록) - 매퍼: 커스텀 출력·없음·tokenId/valueText null·3D 디자인·배지 표 - real DB: 구매자 상세 커스텀 스냅샷·읽을 수 없는 디자인, 판매자 목록 배지 3종·상세 렌더 순서, 관리자 목록 배지·상세, 리뷰 Before 3D·슬롯형·없음, 구독 hasCustom, resetSeedScope 디자인·이미지 --- .../migration.sql | 77 +++++++ prisma/schema.prisma | 72 +++++- prisma/seed/idempotent.ts | 6 + prisma/seed/orders.ts | 41 +++- .../services/mypage-review.service.spec.ts | 75 ++++--- src/features/order/order-admin.graphql | 8 + src/features/order/order-seller.graphql | 8 + src/features/order/order-subscription.graphql | 2 + src/features/order/order.types.graphql | 151 ++++++++++++- .../order-custom-snapshot.migration.spec.ts | 208 ++++++++++++++++++ .../order/repositories/order.repository.ts | 58 ++--- .../services/order-admin-mappers.helper.ts | 2 + .../services/order-admin.service.spec.ts | 37 ++++ .../order-custom-design.helper.spec.ts | 126 +++++++++++ .../services/order-custom-design.helper.ts | 109 +++++++++ .../order-deposit-admin.service.spec.ts | 1 + .../services/order-deposit-admin.service.ts | 6 +- .../services/order-events-mappers.helper.ts | 13 +- .../services/order-events.service.spec.ts | 1 + .../order/services/order-events.service.ts | 6 +- .../order/services/order-my.service.spec.ts | 110 +++++++++ .../order-output-mappers.helper.spec.ts | 141 +++++++++++- .../services/order-output-mappers.helper.ts | 75 ++++++- .../services/order-seller.service.spec.ts | 51 ++++- .../order/services/order-seller.service.ts | 8 +- .../order-subscription.service.spec.ts | 1 + .../order/types/order-admin-output.type.ts | 2 + src/features/order/types/order-output.type.ts | 56 ++++- .../order/types/order-seller-output.type.ts | 3 + src/features/product/index.ts | 2 + .../product-home-query.resolver.spec.ts | 10 +- .../services/product-home.service.spec.ts | 48 ++-- .../review-order-item-snapshot.helper.ts | 11 +- ...view-order-item-snapshot.migration.spec.ts | 65 ++++-- src/graphql/removed-schema-elements.spec.ts | 2 + src/test/enum-sdl-sync.spec.ts | 7 + src/test/factories/order.factory.ts | 55 +++++ src/test/model-ownership.ts | 2 + src/test/seed-reset-scope.spec.ts | 31 +++ 39 files changed, 1499 insertions(+), 188 deletions(-) create mode 100644 prisma/migrations/20261118182831_order_custom_snapshot/migration.sql create mode 100644 src/features/order/repositories/order-custom-snapshot.migration.spec.ts create mode 100644 src/features/order/services/order-custom-design.helper.spec.ts create mode 100644 src/features/order/services/order-custom-design.helper.ts diff --git a/prisma/migrations/20261118182831_order_custom_snapshot/migration.sql b/prisma/migrations/20261118182831_order_custom_snapshot/migration.sql new file mode 100644 index 00000000..5b6a1e5c --- /dev/null +++ b/prisma/migrations/20261118182831_order_custom_snapshot/migration.sql @@ -0,0 +1,77 @@ +-- 주문 품목 커스텀 스냅샷: 방식·바탕·대표 이미지, 문구 자리 표시 이름·좌표·스타일, 자유 편집 영역, 3D 디자인 JSON과 커스텀 이미지. +-- 자유 편집 크롭 이미지는 영역 좌표가 대신해 지운다. 기존 문구·자유 편집은 바탕 전체 영역·검정·가운데로 옮긴다. +-- AlterTable +ALTER TABLE `order_item` ADD COLUMN `custom_mode_snapshot` ENUM('NONE', 'SLOT', 'THREE_D') NOT NULL DEFAULT 'NONE', + ADD COLUMN `custom_base_image_url_snapshot` VARCHAR(2048) NULL, + ADD COLUMN `custom_preview_image_url` VARCHAR(2048) NULL; + +-- AlterTable +ALTER TABLE `order_item_custom_text` ADD COLUMN `token_id` BIGINT UNSIGNED NULL, + ADD COLUMN `label_snapshot` VARCHAR(30) NULL, + ADD COLUMN `pos_x` INTEGER NOT NULL DEFAULT 0, + ADD COLUMN `pos_y` INTEGER NOT NULL DEFAULT 0, + ADD COLUMN `width` INTEGER NOT NULL DEFAULT 10000, + ADD COLUMN `height` INTEGER NOT NULL DEFAULT 10000, + ADD COLUMN `text_color` CHAR(7) NOT NULL DEFAULT '#000000', + ADD COLUMN `text_align` ENUM('LEFT', 'CENTER', 'RIGHT') NOT NULL DEFAULT 'CENTER', + MODIFY `value_text` VARCHAR(200) NULL; + +-- AlterTable +ALTER TABLE `order_item_custom_free_edit` ADD COLUMN `pos_x` INTEGER NOT NULL DEFAULT 0, + ADD COLUMN `pos_y` INTEGER NOT NULL DEFAULT 0, + ADD COLUMN `width` INTEGER NOT NULL DEFAULT 10000, + ADD COLUMN `height` INTEGER NOT NULL DEFAULT 10000; + +-- backfill: 표시 이름은 키에서 따오고, 살아 있는 문구·자유 편집이 있는 품목은 슬롯형이다 +UPDATE `order_item_custom_text` SET `label_snapshot` = LEFT(`token_key_snapshot`, 30); +UPDATE `order_item` oi SET oi.`custom_mode_snapshot` = 'SLOT' +WHERE EXISTS (SELECT 1 FROM `order_item_custom_text` t WHERE t.`order_item_id` = oi.`id` AND t.`deleted_at` IS NULL) + OR EXISTS (SELECT 1 FROM `order_item_custom_free_edit` f WHERE f.`order_item_id` = oi.`id` AND f.`deleted_at` IS NULL); +-- end backfill + +-- 새 행은 주문 생성이 값을 모두 채운다 +-- AlterTable +ALTER TABLE `order_item_custom_text` MODIFY `label_snapshot` VARCHAR(30) NOT NULL, + ALTER COLUMN `pos_x` DROP DEFAULT, + ALTER COLUMN `pos_y` DROP DEFAULT, + ALTER COLUMN `width` DROP DEFAULT, + ALTER COLUMN `height` DROP DEFAULT, + ALTER COLUMN `text_color` DROP DEFAULT, + ALTER COLUMN `text_align` DROP DEFAULT; + +-- AlterTable +ALTER TABLE `order_item_custom_free_edit` ALTER COLUMN `pos_x` DROP DEFAULT, + ALTER COLUMN `pos_y` DROP DEFAULT, + ALTER COLUMN `width` DROP DEFAULT, + ALTER COLUMN `height` DROP DEFAULT, + DROP COLUMN `crop_image_url`; + +-- CreateTable +CREATE TABLE `order_item_custom_design` ( + `id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT, + `order_item_id` BIGINT UNSIGNED NOT NULL, + `schema_version` SMALLINT UNSIGNED NOT NULL, + `design_json` JSON NOT NULL, + `created_at` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3), + + UNIQUE INDEX `uk_order_item_custom_design_item`(`order_item_id`), + PRIMARY KEY (`id`) +) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; + +-- CreateTable +CREATE TABLE `order_item_custom_image` ( + `id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT, + `order_item_id` BIGINT UNSIGNED NOT NULL, + `kind` ENUM('THREE_D_TOP', 'THREE_D_FRONT', 'THREE_D_BACK', 'THREE_D_LEFT', 'THREE_D_RIGHT', 'SLOT_COMPOSITE') NOT NULL, + `image_url` VARCHAR(2048) NOT NULL, + `created_at` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3), + + UNIQUE INDEX `uk_order_item_custom_image_kind`(`order_item_id`, `kind`), + PRIMARY KEY (`id`) +) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; + +-- AddForeignKey +ALTER TABLE `order_item_custom_design` ADD CONSTRAINT `order_item_custom_design_order_item_id_fkey` FOREIGN KEY (`order_item_id`) REFERENCES `order_item`(`id`) ON DELETE RESTRICT ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE `order_item_custom_image` ADD CONSTRAINT `order_item_custom_image_order_item_id_fkey` FOREIGN KEY (`order_item_id`) REFERENCES `order_item`(`id`) ON DELETE RESTRICT ON UPDATE CASCADE; diff --git a/prisma/schema.prisma b/prisma/schema.prisma index a7afb2d5..85b33b30 100644 --- a/prisma/schema.prisma +++ b/prisma/schema.prisma @@ -58,6 +58,16 @@ enum CustomTextAlign { RIGHT } +// 주문 커스텀 이미지 종류. 3D는 윗면 + 옆면 앞·뒤·좌·우 렌더, 슬롯형은 '본 그대로' 합성 1장 +enum CustomImageKind { + THREE_D_TOP + THREE_D_FRONT + THREE_D_BACK + THREE_D_LEFT + THREE_D_RIGHT + SLOT_COMPOSITE +} + enum OrderStatus { SUBMITTED CONFIRMED @@ -1022,6 +1032,11 @@ model OrderItem { quantity Int @default(1) @db.UnsignedSmallInt item_subtotal_price Int @default(0) @db.UnsignedInt + custom_mode_snapshot CustomMode @default(NONE) + // 슬롯형 바탕 이미지. 문구 자리·자유 편집 영역 좌표의 기준이다 + custom_base_image_url_snapshot String? @db.VarChar(2048) + // 커스텀 대표 이미지(3D 윗면 렌더·슬롯형 합성). 목록 썸네일과 리뷰 Before의 원천이다 + custom_preview_image_url String? @db.VarChar(2048) created_at DateTime @default(now()) @db.DateTime(3) updated_at DateTime @updatedAt @db.DateTime(3) @@ -1034,6 +1049,8 @@ model OrderItem { option_items OrderItemOptionItem[] custom_texts OrderItemCustomText[] free_edits OrderItemCustomFreeEdit[] + custom_design OrderItemCustomDesign? + custom_images OrderItemCustomImage[] notifications Notification[] review Review? @@ -1072,10 +1089,22 @@ model OrderItemCustomText { id BigInt @id @default(autoincrement()) @db.UnsignedBigInt order_item_id BigInt @db.UnsignedBigInt - token_key_snapshot String @db.VarChar(60) - default_text_snapshot String @db.VarChar(200) - value_text String @db.VarChar(200) - sort_order Int @default(0) + // 원본 문구 자리. 자리가 바뀌거나 지워져도 스냅샷은 그대로라 FK를 두지 않는다. 자리 지정 전 주문은 null + token_id BigInt? @db.UnsignedBigInt + token_key_snapshot String @db.VarChar(60) + label_snapshot String @db.VarChar(30) + default_text_snapshot String @db.VarChar(200) + // 선택 자리를 지운 '문구 없음'은 null + value_text String? @db.VarChar(200) + sort_order Int @default(0) + + // 바탕 이미지 한 변을 10000으로 본 정수 비율, 원점은 왼쪽 위 + pos_x Int + pos_y Int + width Int + height Int + text_color String @db.Char(7) + text_align CustomTextAlign created_at DateTime @default(now()) @db.DateTime(3) updated_at DateTime @updatedAt @db.DateTime(3) @@ -1092,7 +1121,11 @@ model OrderItemCustomFreeEdit { id BigInt @id @default(autoincrement()) @db.UnsignedBigInt order_item_id BigInt @db.UnsignedBigInt - crop_image_url String @db.VarChar(2048) + // 바탕 이미지 위 요청 영역(문구 자리와 같은 좌표계) + pos_x Int + pos_y Int + width Int + height Int description_text String @db.VarChar(2000) sort_order Int @default(0) @@ -1126,6 +1159,35 @@ model OrderItemCustomFreeEditAttachment { @@map("order_item_custom_free_edit_attachment") } +// 3D 디자인 JSON(스키마 버전 동반). 주문과 함께 한 번만 쓰고 단독 삭제 경로가 없어 deleted_at을 두지 않는다 — 가시성은 order_item을 따른다 +model OrderItemCustomDesign { + id BigInt @id @default(autoincrement()) @db.UnsignedBigInt + order_item_id BigInt @unique(map: "uk_order_item_custom_design_item") @db.UnsignedBigInt + schema_version Int @db.UnsignedSmallInt + design_json Json + + created_at DateTime @default(now()) @db.DateTime(3) + + order_item OrderItem @relation(fields: [order_item_id], references: [id]) + + @@map("order_item_custom_design") +} + +// 커스텀 이미지(3D 렌더 5장·슬롯형 합성). 종류당 1장이고 디자인과 같은 이유로 deleted_at이 없다 +model OrderItemCustomImage { + id BigInt @id @default(autoincrement()) @db.UnsignedBigInt + order_item_id BigInt @db.UnsignedBigInt + kind CustomImageKind + image_url String @db.VarChar(2048) + + created_at DateTime @default(now()) @db.DateTime(3) + + order_item OrderItem @relation(fields: [order_item_id], references: [id]) + + @@unique([order_item_id, kind], map: "uk_order_item_custom_image_kind") + @@map("order_item_custom_image") +} + // 주문 1건의 결제. 계좌이체는 PENDING으로 만들고 입금 확인(관리자, 후속 연동은 AUTO) 때 CONFIRMED가 된다. model Payment { id BigInt @id @default(autoincrement()) @db.UnsignedBigInt diff --git a/prisma/seed/idempotent.ts b/prisma/seed/idempotent.ts index 3bad3b31..ac9f8973 100644 --- a/prisma/seed/idempotent.ts +++ b/prisma/seed/idempotent.ts @@ -118,6 +118,12 @@ export async function resetSeedScope(prisma: PrismaClient): Promise { await prisma.orderItemCustomText.deleteMany({ where: { order_item_id: { in: orderItemIds } }, }); + await prisma.orderItemCustomDesign.deleteMany({ + where: { order_item_id: { in: orderItemIds } }, + }); + await prisma.orderItemCustomImage.deleteMany({ + where: { order_item_id: { in: orderItemIds } }, + }); await prisma.orderItemOptionItem.deleteMany({ where: { order_item_id: { in: orderItemIds } }, }); diff --git a/prisma/seed/orders.ts b/prisma/seed/orders.ts index 21b40fc4..98d16bf3 100644 --- a/prisma/seed/orders.ts +++ b/prisma/seed/orders.ts @@ -185,6 +185,17 @@ export async function seedOrders( sale_price_snapshot: p2.sale_price, quantity: 1, item_subtotal_price: 60000, + custom_mode_snapshot: 'SLOT', + custom_base_image_url_snapshot: + 'https://placehold.co/600x600/png?text=Custom+Base', + custom_preview_image_url: + 'https://placehold.co/600x600/png?text=Custom+Composite', + custom_images: { + create: { + kind: 'SLOT_COMPOSITE', + image_url: 'https://placehold.co/600x600/png?text=Custom+Composite', + }, + }, }, }); await prisma.orderItemOptionItem.create({ @@ -202,15 +213,25 @@ export async function seedOrders( data: { order_item_id: o2Item.id, token_key_snapshot: 'message', + label_snapshot: '메시지', default_text_snapshot: '메시지를 입력하세요', value_text: '생일 축하해 :)', sort_order: 0, + pos_x: 1000, + pos_y: 1000, + width: 8000, + height: 1500, + text_color: '#1D1D1D', + text_align: 'CENTER', }, }); const o2FreeEdit = await prisma.orderItemCustomFreeEdit.create({ data: { order_item_id: o2Item.id, - crop_image_url: 'https://placehold.co/300x300/png?text=Custom+Crop', + pos_x: 2000, + pos_y: 4000, + width: 6000, + height: 4000, description_text: '이 사진을 케이크 위에 그려주세요', sort_order: 0, }, @@ -330,6 +351,9 @@ export async function seedOrders( }, }, }); + // o4에는 리뷰가 달리므로(seedReviews) 커스텀 대표 이미지를 함께 둬 + // 홈 제작 후기 쇼케이스(Before/After 페어)가 로컬에서 동작하게 한다 + const o4Preview = 'https://placehold.co/600x600/png?text=Requested+Design'; const o4Item = await prisma.orderItem.create({ data: { order_id: o4.id, @@ -343,16 +367,11 @@ export async function seedOrders( sale_price_snapshot: p1.sale_price, quantity: 1, item_subtotal_price: 35000, - }, - }); - // o4에는 리뷰가 달리므로(seedReviews) 커스텀 크롭을 함께 둬 - // 홈 제작 후기 쇼케이스(Before/After 페어)가 로컬에서 동작하게 한다 - await prisma.orderItemCustomFreeEdit.create({ - data: { - order_item_id: o4Item.id, - crop_image_url: 'https://placehold.co/300x300/png?text=Requested+Design', - description_text: '이 그림처럼 레터링해 주세요', - sort_order: 0, + custom_mode_snapshot: 'SLOT', + custom_preview_image_url: o4Preview, + custom_images: { + create: { kind: 'SLOT_COMPOSITE', image_url: o4Preview }, + }, }, }); diff --git a/src/features/mypage/services/mypage-review.service.spec.ts b/src/features/mypage/services/mypage-review.service.spec.ts index ca22ec41..61c7f50a 100644 --- a/src/features/mypage/services/mypage-review.service.spec.ts +++ b/src/features/mypage/services/mypage-review.service.spec.ts @@ -60,7 +60,9 @@ describe('UserReviewService (real DB)', () => { }); /** 리뷰 작성 가능한 상태(PICKED_UP 주문 + 본인 아이템)를 세팅 */ - async function setupReviewableOrderItem(): Promise<{ + async function setupReviewableOrderItem( + itemOverrides: Parameters[1] = {}, + ): Promise<{ accountId: bigint; storeId: bigint; productId: bigint; @@ -81,6 +83,7 @@ describe('UserReviewService (real DB)', () => { order_id: order.id, product_id: product.id, product_name_snapshot: '상품R 스냅샷', + ...itemOverrides, }); return { accountId: account.id, @@ -127,8 +130,11 @@ describe('UserReviewService (real DB)', () => { expect(saved.media.some((m) => m.media_type === 'VIDEO')).toBe(true); }); - it('작성 시점에 주문 품목의 상품명·활성 옵션(id 순)·커스텀 크롭 첫 장을 리뷰에 복사한다', async () => { - const ctx = await setupReviewableOrderItem(); + it('작성 시점에 주문 품목의 상품명·활성 옵션(id 순)·커스텀 대표 이미지를 리뷰에 복사한다', async () => { + const ctx = await setupReviewableOrderItem({ + custom_mode_snapshot: 'SLOT', + custom_preview_image_url: 'https://img/composite.png', + }); const group = await prisma.productOptionGroup.create({ data: { product_id: ctx.productId, name: '모양' }, }); @@ -151,20 +157,6 @@ describe('UserReviewService (real DB)', () => { }, }); } - for (const [url, sortOrder] of [ - ['https://img/second.png', 1], - ['https://img/first.png', 0], - ] as const) { - await prisma.orderItemCustomFreeEdit.create({ - data: { - order_item_id: ctx.orderItemId, - crop_image_url: url, - description_text: '요청', - sort_order: sortOrder, - }, - }); - } - const result = await service.writeReview(ctx.accountId, { orderItemId: ctx.orderItemId.toString(), rating: 5, @@ -180,10 +172,42 @@ describe('UserReviewService (real DB)', () => { { groupName: '모양', optionTitle: '동그라미' }, { groupName: '모양', optionTitle: '하트' }, ]); - expect(saved.before_image_url).toBe('https://img/first.png'); + expect(saved.before_image_url).toBe('https://img/composite.png'); }); - it('옵션·크롭이 없는 품목이면 option_summary·before_image_url은 null', async () => { + it.each([ + ['3D 윗면 렌더', 'THREE_D', 'https://img/top.png'], + ['슬롯형 합성', 'SLOT', 'https://img/composite.png'], + ['커스텀 없음', 'NONE', null], + ] as const)( + 'Before 이미지는 품목 커스텀 대표 이미지다(%s)', + async (_case, mode, url) => { + const ctx = await setupReviewableOrderItem({ + custom_mode_snapshot: mode, + custom_preview_image_url: url, + }); + // 대표 이미지가 아닌 커스텀 이미지·자유 편집 참고 사진은 Before 원천이 아니다 + await prisma.orderItemCustomImage.create({ + data: { + order_item_id: ctx.orderItemId, + kind: 'THREE_D_FRONT', + image_url: 'https://img/front.png', + }, + }); + const result = await service.writeReview(ctx.accountId, { + orderItemId: ctx.orderItemId.toString(), + rating: 5, + content: VALID_CONTENT, + media: [], + }); + const saved = await prisma.review.findUniqueOrThrow({ + where: { id: BigInt(result.reviewId) }, + }); + expect(saved.before_image_url).toBe(url); + }, + ); + + it('옵션·커스텀 대표 이미지가 없는 품목이면 option_summary·before_image_url은 null', async () => { const ctx = await setupReviewableOrderItem(); const result = await service.writeReview(ctx.accountId, { orderItemId: ctx.orderItemId.toString(), @@ -467,13 +491,10 @@ describe('UserReviewService (real DB)', () => { ], }); await service.deleteMyReview(ctx.accountId, first.reviewId); - // 복원도 작성 시점 규칙으로 스냅샷을 다시 찍는지 — 삭제 후 생긴 크롭이 반영돼야 한다 - await prisma.orderItemCustomFreeEdit.create({ - data: { - order_item_id: ctx.orderItemId, - crop_image_url: 'https://img/late-crop.png', - description_text: '요청', - }, + // 복원도 작성 시점 규칙으로 스냅샷을 다시 찍는지 — 삭제 후 바뀐 대표 이미지가 반영돼야 한다 + await prisma.orderItem.update({ + where: { id: ctx.orderItemId }, + data: { custom_preview_image_url: 'https://img/late-preview.png' }, }); // 다시 작성 → 같은 row 복원, rating/content/media 모두 새 값으로 교체되어야 함 @@ -502,7 +523,7 @@ describe('UserReviewService (real DB)', () => { expect(saved.deleted_at).toBeNull(); expect(Number(saved.rating)).toBe(5); expect(saved.content).toBe(NEW_CONTENT); - expect(saved.before_image_url).toBe('https://img/late-crop.png'); + expect(saved.before_image_url).toBe('https://img/late-preview.png'); // media: 새 값 2건만 남고 stale 1건은 정리됐는지 확인 const mediaRows = await prisma.reviewMedia.findMany({ diff --git a/src/features/order/order-admin.graphql b/src/features/order/order-admin.graphql index a96a1447..b3d7f789 100644 --- a/src/features/order/order-admin.graphql +++ b/src/features/order/order-admin.graphql @@ -82,6 +82,14 @@ type AdminOrderSummary { 첫 품목의 상품 대표 이미지 URL(주문 시점 스냅샷). 주문 당시 이미지가 없었거나 품목이 없으면 null. """ firstItemImageUrl: String + """ + 커스텀 주문 여부(첫 품목의 커스텀 방식이 NONE이 아니면 true). 목록 '커스텀' 배지용이다. + """ + hasCustom: Boolean! + """ + 첫 품목의 커스텀 대표 이미지 URL(3D 윗면 렌더 또는 슬롯형 합성). 없으면 null. + """ + firstItemCustomImageUrl: String } """ diff --git a/src/features/order/order-seller.graphql b/src/features/order/order-seller.graphql index 895f6744..9a1cc892 100644 --- a/src/features/order/order-seller.graphql +++ b/src/features/order/order-seller.graphql @@ -69,6 +69,14 @@ type SellerOrderSummary { 내 매장 첫 품목의 상품 대표 이미지 URL(주문 시점 스냅샷). 주문 당시 이미지가 없었으면 null. """ firstItemImageUrl: String + """ + 커스텀 주문 여부(내 매장 첫 품목의 커스텀 방식이 NONE이 아니면 true). 목록 '커스텀' 배지용이다. + """ + hasCustom: Boolean! + """ + 내 매장 첫 품목의 커스텀 대표 이미지 URL(3D 윗면 렌더 또는 슬롯형 합성). 없으면 null. + """ + firstItemCustomImageUrl: String } """ diff --git a/src/features/order/order-subscription.graphql b/src/features/order/order-subscription.graphql index 6059c540..cdcf029f 100644 --- a/src/features/order/order-subscription.graphql +++ b/src/features/order/order-subscription.graphql @@ -31,6 +31,8 @@ type SellerOrderUpdate { totalPrice: Int! """첫 품목의 상품명(주문 시점 스냅샷). 주문은 단일 상품 구조다.""" productName: String! + """커스텀 주문 여부(첫 품목의 커스텀 방식이 NONE이 아니면 true).""" + hasCustom: Boolean! """주문 행의 updated_at. 폐기 규칙의 비교 키다.""" updatedAt: DateTime! } diff --git a/src/features/order/order.types.graphql b/src/features/order/order.types.graphql index 2cc80a6d..6f9773dd 100644 --- a/src/features/order/order.types.graphql +++ b/src/features/order/order.types.graphql @@ -194,12 +194,119 @@ type OrderItemDetail { itemSubtotalPrice: Int! """선택한 옵션(주문 시점 스냅샷).""" optionItems: [OrderItemOption!]! + """커스텀 방식(주문 시점 스냅샷). 커스텀이 없는 품목은 NONE.""" + customMode: CustomModeType! + """ + 커스텀 대표 이미지 URL. 3D는 윗면 렌더, 슬롯형은 합성 이미지이고 목록 썸네일·리뷰 Before에 쓰인다. 없으면 null. + """ + customPreviewImageUrl: String + """ + 슬롯형 바탕 이미지 URL(주문 시점 스냅샷, 정사각). 문구 자리·자유 편집 영역 좌표의 기준이다. 슬롯형이 아니거나 바탕을 저장하기 전 주문이면 null. + """ + customBaseImageUrl: String + """커스텀 이미지(3D 렌더 5장 또는 슬롯형 합성 1장). kind 선언 순서다. 없으면 빈 배열.""" + customImages: [OrderItemCustomImage!]! + """3D 디자인(JSON v1). 3D가 아니거나 저장된 값을 읽을 수 없으면 null.""" + threeDDesign: ThreeDDesign """입력한 커스텀 문구(주문 시점 스냅샷).""" customTexts: [OrderItemCustomText!]! """자유 편집 요청(주문 시점 스냅샷).""" freeEdits: [OrderItemFreeEdit!]! } +""" +주문 커스텀 이미지 종류. 값은 늘어날 수 있으니 모르는 값을 받아도 화면이 죽지 않게 처리한다. +3D 옆면은 옆면 고도 asin(0.4) 정사영이고 좌·우는 정면을 보는 사람 기준이다. +""" +enum CustomImageKindType { + """3D 윗면(위에서 내려다본 정사각). 대표 이미지다.""" + THREE_D_TOP + """3D 옆면 정면(yaw 0).""" + THREE_D_FRONT + """3D 옆면 뒤(정면 반대).""" + THREE_D_BACK + """3D 옆면 왼쪽.""" + THREE_D_LEFT + """3D 옆면 오른쪽.""" + THREE_D_RIGHT + """슬롯형 합성 이미지(바탕 + 문구, 구매자가 본 그대로). 대표 이미지다.""" + SLOT_COMPOSITE +} + +"""주문 커스텀 이미지 1장.""" +type OrderItemCustomImage { + id: ID! + """이미지 종류. 품목마다 종류당 1장이다.""" + kind: CustomImageKindType! + """이미지 URL.""" + imageUrl: String! +} + +""" +주문에 저장된 3D 디자인(JSON v1). 배열 순서가 그리는 순서다. 그리는 규칙은 판매자 앱 렌더러와 구매자 편집기가 공유한다. +선택지·시트 색·효과·꾸미기 키는 customThreeDCatalog의 key이고, 퇴역한 항목도 과거 주문을 그릴 수 있게 카탈로그에 남는다. +""" +type ThreeDDesign { + """디자인 JSON 버전. 지금은 1.""" + schemaVersion: Int! + """모양·크기·디자인·맛·시트 색.""" + basic: ThreeDDesignBasic! + """윗면 항목. x·y는 케이크 판 정사각 기준 중심 0~1(왼쪽 위 원점).""" + top: [ThreeDDesignItem!]! + """옆면 항목. x는 정면(yaw 0)에서 잰 둘레 비율 0~1, y는 윗면 0~바닥 1.""" + side: [ThreeDDesignItem!]! +} + +"""3D 디자인의 케이크 기본값.""" +type ThreeDDesignBasic { + """모양 선택지 key.""" + shape: String! + """크기 선택지 key.""" + size: String! + """디자인 선택지 key. 고르지 않았으면 null(장식 없는 시트).""" + design: String + """맛 선택지 key. 고르지 않았으면 null.""" + flavor: String + """시트 색 key.""" + sheetColor: String! +} + +"""3D 디자인 항목 종류. 값은 늘어날 수 있으니 모르는 값을 받아도 화면이 죽지 않게 처리한다.""" +enum ThreeDItemKindType { + """글자.""" + TEXT + """꾸미기 이미지.""" + DECO +} + +"""3D 디자인 항목(글자 또는 꾸미기) 1개.""" +type ThreeDDesignItem { + """항목 종류.""" + kind: ThreeDItemKindType! + """가로 위치(면별 좌표계, ThreeDDesign.top·side 참고).""" + x: Float! + """세로 위치(면별 좌표계, ThreeDDesign.top·side 참고).""" + y: Float! + """크기(케이크 판 너비 대비 cqw).""" + size: Float! + """효과.""" + effect: ThreeDDesignEffect! + """글자 내용(줄바꿈·이모지 포함). TEXT만 값이 있다.""" + text: String + """글자색(#RRGGBB 대문자). TEXT만 값이 있다.""" + color: String + """꾸미기 key. DECO만 값이 있다.""" + decoId: String +} + +"""3D 디자인 항목에 건 효과.""" +type ThreeDDesignEffect { + """효과 key(카탈로그 effects).""" + type: String! + """효과 강도(0~100 정수).""" + intensity: Int! +} + """주문 시점의 옵션 스냅샷. 판매자가 이후 옵션을 수정·삭제해도 주문 내용은 변하지 않는다.""" type OrderItemOption { id: ID! @@ -211,24 +318,52 @@ type OrderItemOption { priceDelta: Int! } -"""주문 시점의 커스텀 문구 스냅샷.""" +""" +주문 시점의 커스텀 문구 스냅샷. 좌표는 바탕 이미지 한 변을 10000으로 본 정수 비율이고 원점은 왼쪽 위다. +글꼴은 플랫폼 공통 1종(Pretendard Bold)이고 크기는 영역에 맞춰 자동이다. +""" type OrderItemCustomText { id: ID! - """문구 슬롯 식별 키(주문 시점).""" + """원본 문구 자리 ID. 자리가 이후 바뀌거나 지워져도 스냅샷은 그대로다. 문구 자리를 지정하기 전 주문이면 null.""" + tokenId: ID + """문구 자리 식별 키(주문 시점).""" tokenKey: String! - """슬롯의 기본 문구(주문 시점).""" + """문구 자리 표시 이름(주문 시점).""" + label: String! + """문구 자리의 기본 문구(주문 시점).""" defaultText: String! - """구매자가 실제로 입력한 문구.""" - valueText: String! + """구매자가 넣은 문구(줄바꿈·이모지 포함). 선택 자리를 지웠으면 null('문구 없음').""" + valueText: String + """영역 왼쪽 위 x(0~10000).""" + posX: Int! + """영역 왼쪽 위 y(0~10000).""" + posY: Int! + """영역 너비(posX + width ≤ 10000).""" + width: Int! + """영역 높이(posY + height ≤ 10000).""" + height: Int! + """글자색(#RRGGBB 대문자).""" + textColor: String! + """영역 안 글자 정렬.""" + textAlign: CustomTextAlignType! """입력 화면 노출 순서. 오름차순.""" sortOrder: Int! } -"""주문 시점의 자유 편집 요청 스냅샷. 구매자가 이미지 위에 영역을 지정해 남긴 요청이다.""" +""" +주문 시점의 자유 편집 요청 스냅샷. 구매자가 슬롯형 바탕 이미지 위에 영역을 지정해 남긴 요청이다. +좌표계는 OrderItemCustomText와 같다(바탕 한 변 10000, 왼쪽 위 원점). +""" type OrderItemFreeEdit { id: ID! - """지정한 편집 영역을 잘라낸 이미지 URL.""" - cropImageUrl: String! + """영역 왼쪽 위 x(0~10000).""" + posX: Int! + """영역 왼쪽 위 y(0~10000).""" + posY: Int! + """영역 너비(posX + width ≤ 10000).""" + width: Int! + """영역 높이(posY + height ≤ 10000).""" + height: Int! """해당 영역에 대한 요청 문구.""" descriptionText: String! """요청 순서. 오름차순.""" diff --git a/src/features/order/repositories/order-custom-snapshot.migration.spec.ts b/src/features/order/repositories/order-custom-snapshot.migration.spec.ts new file mode 100644 index 00000000..a342eeea --- /dev/null +++ b/src/features/order/repositories/order-custom-snapshot.migration.spec.ts @@ -0,0 +1,208 @@ +import { readFileSync, readdirSync } from 'node:fs'; +import { join } from 'node:path'; + +import mysql, { type RowDataPacket } from 'mysql2/promise'; + +import { + disconnectTestPrismaClient, + getTestDatabaseUrl, +} from '@/test/db/prisma-test-client'; +import { closeTruncateConnection } from '@/test/db/truncate'; +import { createTestingModuleWithRealDb } from '@/test/modules/testing-module.builder'; + +// 주문 커스텀 스냅샷 마이그레이션의 열 추가·백필·기본값 제거를 그대로 실행해 기존 문구·자유 편집이 새 모양으로 옮겨지는지 본다. +// 지워지는 crop_image_url과 기본값 없는 NOT NULL 열 때문에 최신 스키마에서는 옛 행을 만들 수 없어, +// 마이그레이션 직전 모양의 임시 표로 같은 이름을 가린 연결 하나에서 돌린다(임시 표는 세션 범위라 풀 연결로는 안 보인다). +const MIGRATIONS = join(__dirname, '../../../../prisma/migrations'); +const SQL = readFileSync( + join( + MIGRATIONS, + readdirSync(MIGRATIONS).find((d) => d.endsWith('_order_custom_snapshot'))!, + 'migration.sql', + ), + 'utf8', +); + +const STATEMENTS = SQL.split(';') + .map((stmt) => stmt.replace(/^\s*--[^\n]*$/gm, '').trim()) + .filter((stmt) => stmt.length > 0); +/** 기존 행에 닿는 문장(열 추가 → 백필 → 기본값 제거). 새 표 생성·FK는 빈 표라 제외한다. */ +const DATA_STEPS = STATEMENTS.slice( + 0, + STATEMENTS.findIndex((stmt) => stmt.startsWith('CREATE TABLE')), +); + +const LEGACY_SHAPES: Array<[table: string, alter: string]> = [ + [ + 'order_item', + 'DROP COLUMN `custom_mode_snapshot`, DROP COLUMN `custom_base_image_url_snapshot`, DROP COLUMN `custom_preview_image_url`', + ], + [ + 'order_item_custom_text', + 'DROP COLUMN `token_id`, DROP COLUMN `label_snapshot`, DROP COLUMN `pos_x`, DROP COLUMN `pos_y`, DROP COLUMN `width`, DROP COLUMN `height`, DROP COLUMN `text_color`, DROP COLUMN `text_align`, MODIFY `value_text` VARCHAR(200) NOT NULL', + ], + [ + 'order_item_custom_free_edit', + 'DROP COLUMN `pos_x`, DROP COLUMN `pos_y`, DROP COLUMN `width`, DROP COLUMN `height`, ADD COLUMN `crop_image_url` VARCHAR(2048) NOT NULL', + ], +]; + +describe('주문 커스텀 스냅샷 마이그레이션 (real DB)', () => { + let conn: mysql.Connection; + + beforeAll(async () => { + await createTestingModuleWithRealDb({ providers: [] }); + }); + afterAll(async () => { + await closeTruncateConnection(); + await disconnectTestPrismaClient(); + }); + // 행은 전부 연결이 닫히면 사라지는 임시 표에만 쓴다 + beforeEach(async () => { + conn = await mysql.createConnection({ uri: getTestDatabaseUrl() }); + for (const [table, alter] of LEGACY_SHAPES) { + // 같은 이름을 LIKE로 바로 만들 수 없어 사본을 거친다 + await conn.query( + `CREATE TEMPORARY TABLE \`_legacy_${table}\` LIKE \`${table}\``, + ); + await conn.query( + `CREATE TEMPORARY TABLE \`${table}\` LIKE \`_legacy_${table}\``, + ); + // 가림이 안 된 채 ALTER가 진짜 표에 닿지 않게 먼저 확인한다 + expect(await showCreate(table)).toMatch(/^CREATE TEMPORARY TABLE/); + await conn.query(`ALTER TABLE \`${table}\` ${alter}`); + } + }); + afterEach(async () => { + await conn.end(); + }); + + async function showCreate(table: string): Promise { + const [[row]] = await conn.query( + `SHOW CREATE TABLE \`${table}\``, + ); + return String(row['Create Table']); + } + + async function insert( + table: string, + row: Record, + ): Promise { + const columns = Object.keys(row); + const [result] = await conn.query( + `INSERT INTO \`${table}\` (${columns.join(', ')}, updated_at) VALUES (${columns.map(() => '?').join(', ')}, NOW(3))`, + Object.values(row), + ); + return result.insertId; + } + + const insertItem = () => + insert('order_item', { + order_id: 1, + store_id: 1, + product_id: 1, + product_name_snapshot: '케이크', + regular_price_snapshot: 10000, + store_name_snapshot: '매장', + }); + const insertText = (orderItemId: number, key: string, deleted = false) => + insert('order_item_custom_text', { + order_item_id: orderItemId, + token_key_snapshot: key, + default_text_snapshot: '기본', + value_text: '입력', + deleted_at: deleted ? new Date() : null, + }); + const insertFreeEdit = (orderItemId: number, deleted = false) => + insert('order_item_custom_free_edit', { + order_item_id: orderItemId, + crop_image_url: 'https://img/crop.png', + description_text: '요청', + deleted_at: deleted ? new Date() : null, + }); + + async function runMigration(): Promise { + expect(DATA_STEPS).toHaveLength(7); + for (const stmt of DATA_STEPS) await conn.query(stmt); + } + + it('문구는 키 앞 30자 표시 이름·바탕 전체 영역·검정·가운데로, 자유 편집은 바탕 전체 영역으로 옮기고 크롭을 지운다', async () => { + const item = await insertItem(); + const keys = ['message', 'k'.repeat(40), '한'.repeat(40)]; + for (const key of keys) await insertText(item, key); + await insertFreeEdit(item); + + await runMigration(); + + const [texts] = await conn.query( + 'SELECT label_snapshot, value_text, token_id, pos_x, pos_y, width, height, text_color, text_align FROM order_item_custom_text ORDER BY id', + ); + expect(texts).toEqual( + ['message', 'k'.repeat(30), '한'.repeat(30)].map((label) => ({ + label_snapshot: label, + value_text: '입력', + token_id: null, + pos_x: 0, + pos_y: 0, + width: 10000, + height: 10000, + text_color: '#000000', + text_align: 'CENTER', + })), + ); + const [edits] = await conn.query( + 'SELECT pos_x, pos_y, width, height FROM order_item_custom_free_edit', + ); + expect(edits).toEqual([ + { pos_x: 0, pos_y: 0, width: 10000, height: 10000 }, + ]); + }); + + it('기본값을 지워 새 행은 좌표·스타일을 모두 받아야 하고, 선택 자리를 지운 문구는 null로 둘 수 있다', async () => { + await runMigration(); + + const text = await showCreate('order_item_custom_text'); + for (const column of ['pos_x', 'pos_y', 'width', 'height']) { + expect(text).toContain(`\`${column}\` int NOT NULL,`); + } + expect(text).toMatch(/`label_snapshot` varchar\(30\)[^,]* NOT NULL,/); + expect(text).toMatch(/`text_color` char\(7\)[^,]* NOT NULL,/); + expect(text).toMatch(/`text_align` enum\([^)]*\)[^,]* NOT NULL,/); + expect(text).toMatch(/`value_text` varchar\(200\)[^,]* DEFAULT NULL,/); + const edit = await showCreate('order_item_custom_free_edit'); + expect(edit).not.toContain('crop_image_url'); + for (const column of ['pos_x', 'pos_y', 'width', 'height']) { + expect(edit).toContain(`\`${column}\` int NOT NULL,`); + } + }); + + it('살아 있는 문구나 자유 편집이 있는 품목만 슬롯형이 된다', async () => { + const withText = await insertItem(); + await insertText(withText, 'a'); + const withFreeEdit = await insertItem(); + await insertFreeEdit(withFreeEdit); + const deletedOnly = await insertItem(); + await insertText(deletedOnly, 'b', true); + await insertFreeEdit(deletedOnly, true); + const bare = await insertItem(); + + await runMigration(); + + const [rows] = await conn.query( + 'SELECT id, custom_mode_snapshot, custom_base_image_url_snapshot, custom_preview_image_url FROM order_item ORDER BY id', + ); + expect(rows).toEqual( + [ + [withText, 'SLOT'], + [withFreeEdit, 'SLOT'], + [deletedOnly, 'NONE'], + [bare, 'NONE'], + ].map(([id, mode]) => ({ + id, + custom_mode_snapshot: mode, + custom_base_image_url_snapshot: null, + custom_preview_image_url: null, + })), + ); + }); +}); diff --git a/src/features/order/repositories/order.repository.ts b/src/features/order/repositories/order.repository.ts index f456a930..74e6df1f 100644 --- a/src/features/order/repositories/order.repository.ts +++ b/src/features/order/repositories/order.repository.ts @@ -50,6 +50,21 @@ const sellerVisibleWhere = { submitted_at: { not: null }, } satisfies Prisma.OrderWhereInput; +/** 주문 상세 3곳(구매자·판매자·관리자)의 커스텀 스냅샷. 디자인·이미지는 deleted_at이 없어 부모 품목 가시성을 따른다 */ +const orderItemCustomInclude = { + custom_design: { select: { schema_version: true, design_json: true } }, + // enum 선언 순서(3D 윗면·앞·뒤·좌·우, 슬롯형 합성) + custom_images: { orderBy: { kind: 'asc' } }, + custom_texts: { where: activeWhere, orderBy: { sort_order: 'asc' } }, + free_edits: { + where: activeWhere, + orderBy: { sort_order: 'asc' }, + include: { + attachments: { where: activeWhere, orderBy: { sort_order: 'asc' } }, + }, + }, +} satisfies Prisma.OrderItemInclude; + export const adminOrderInclude = { items: { where: activeWhere, @@ -58,6 +73,8 @@ export const adminOrderInclude = { store_name_snapshot: true, product_name_snapshot: true, product_thumbnail_url_snapshot: true, + custom_mode_snapshot: true, + custom_preview_image_url: true, }, orderBy: { id: 'asc' }, take: 1, @@ -72,6 +89,8 @@ function sellerOrderSummaryInclude(storeId: bigint) { select: { product_name_snapshot: true, product_thumbnail_url_snapshot: true, + custom_mode_snapshot: true, + custom_preview_image_url: true, }, orderBy: { id: 'asc' }, take: 1, @@ -96,14 +115,7 @@ const adminOrderDetailInclude = { orderBy: { id: 'asc' }, include: { option_items: { where: activeWhere }, - custom_texts: { where: activeWhere, orderBy: { sort_order: 'asc' } }, - free_edits: { - where: activeWhere, - orderBy: { sort_order: 'asc' }, - include: { - attachments: { where: activeWhere, orderBy: { sort_order: 'asc' } }, - }, - }, + ...orderItemCustomInclude, }, }, } satisfies Prisma.OrderInclude; @@ -667,20 +679,7 @@ export class OrderRepository { where: activeWhere, orderBy: { id: 'asc' }, }, - custom_texts: { - where: activeWhere, - orderBy: { sort_order: 'asc' }, - }, - free_edits: { - where: activeWhere, - orderBy: { sort_order: 'asc' }, - include: { - attachments: { - where: activeWhere, - orderBy: { sort_order: 'asc' }, - }, - }, - }, + ...orderItemCustomInclude, review: { select: { id: true, deleted_at: true }, }, @@ -864,20 +863,7 @@ export class OrderRepository { }, include: { option_items: { where: activeWhere }, - custom_texts: { - where: activeWhere, - orderBy: { sort_order: 'asc' }, - }, - free_edits: { - where: activeWhere, - orderBy: { sort_order: 'asc' }, - include: { - attachments: { - where: activeWhere, - orderBy: { sort_order: 'asc' }, - }, - }, - }, + ...orderItemCustomInclude, }, }, }, diff --git a/src/features/order/services/order-admin-mappers.helper.ts b/src/features/order/services/order-admin-mappers.helper.ts index 0ac20253..c709b692 100644 --- a/src/features/order/services/order-admin-mappers.helper.ts +++ b/src/features/order/services/order-admin-mappers.helper.ts @@ -7,6 +7,7 @@ import { toOrderCancellation, toOrderItemDetail, toOrderRefund, + toOrderListCustomBadge, toOrderStatusHistory, } from '@/features/order/services/order-output-mappers.helper'; import { toAdminOrderPaymentOutput } from '@/features/order/services/order-payment-mappers.helper'; @@ -34,6 +35,7 @@ export function toAdminOrderSummaryOutput( createdAt: row.created_at, firstItemName: row.items[0]?.product_name_snapshot ?? null, firstItemImageUrl: row.items[0]?.product_thumbnail_url_snapshot ?? null, + ...toOrderListCustomBadge(row.items[0]), }; } diff --git a/src/features/order/services/order-admin.service.spec.ts b/src/features/order/services/order-admin.service.spec.ts index 491215a8..fdb40610 100644 --- a/src/features/order/services/order-admin.service.spec.ts +++ b/src/features/order/services/order-admin.service.spec.ts @@ -25,6 +25,7 @@ import { createOrderItem, createPayment, createStore, + createThreeDOrderItemCustom, createUserProfile, } from '@/test/factories'; import { createTestingModuleWithRealDb } from '@/test/modules/testing-module.builder'; @@ -247,8 +248,43 @@ describe('AdminOrderService (real DB)', () => { storeName: null, firstItemName: null, firstItemImageUrl: null, + hasCustom: false, + firstItemCustomImageUrl: null, }); }); + + it('커스텀 첫 품목이면 목록에 배지·대표 이미지를, 상세에 렌더·디자인을 싣는다', async () => { + const order = await createOrder(prisma); + const item = await createOrderItem(prisma, { + order_id: order.id, + custom_mode_snapshot: 'THREE_D', + custom_preview_image_url: 'https://img/THREE_D_TOP.png', + }); + await createThreeDOrderItemCustom(prisma, item.id); + const plain = await createOrder(prisma); + await createOrderItem(prisma, { order_id: plain.id }); + const adminId = await admin(); + + const list = await service.adminOrders(adminId); + const byId = new Map(list.items.map((o) => [o.id, o])); + expect(byId.get(order.id.toString())).toMatchObject({ + hasCustom: true, + firstItemCustomImageUrl: 'https://img/THREE_D_TOP.png', + }); + expect(byId.get(plain.id.toString())).toMatchObject({ + hasCustom: false, + firstItemCustomImageUrl: null, + }); + const [detail] = (await service.adminOrder(adminId, order.id)).items; + expect(detail.customImages.map((i) => i.kind)).toEqual([ + 'THREE_D_TOP', + 'THREE_D_FRONT', + 'THREE_D_BACK', + 'THREE_D_LEFT', + 'THREE_D_RIGHT', + ]); + expect(detail.threeDDesign?.schemaVersion).toBe(1); + }); }); describe('adminOrders inProgress', () => { @@ -861,6 +897,7 @@ describe('AdminOrderService (real DB)', () => { buyerName: order.buyer_name, totalPrice: order.total_price, productName: 'Product snapshot', + hasCustom: false, updatedAt: row.updated_at.toISOString(), }, ]); diff --git a/src/features/order/services/order-custom-design.helper.spec.ts b/src/features/order/services/order-custom-design.helper.spec.ts new file mode 100644 index 00000000..ba489f0f --- /dev/null +++ b/src/features/order/services/order-custom-design.helper.spec.ts @@ -0,0 +1,126 @@ +import { Logger } from '@nestjs/common'; + +import { readStoredThreeDDesign } from '@/features/order/services/order-custom-design.helper'; +import type { Prisma } from '@/generated/prisma/client'; + +const TEXT = { + kind: 'TEXT', + x: 0.5, + y: 0.25, + size: 12, + effect: { type: 'soft', intensity: 50 }, + text: '생일\n축하해 🎂', + color: '#1D1D1D', +}; +const DECO = { + kind: 'DECO', + x: 0.1, + y: 0.9, + size: 20, + effect: { type: 'none', intensity: 0 }, + decoId: 'number-3', +}; +const DESIGN = { + schemaVersion: 1, + basic: { + shape: 'circle', + size: 'no1', + design: 'wave', + flavor: null, + sheetColor: 'pink', + }, + top: [TEXT, DECO], + side: [DECO], +}; + +const read = (design_json: unknown, schema_version = 1) => + readStoredThreeDDesign(42n, { + schema_version, + design_json: design_json as Prisma.JsonValue, + }); + +type Node = Record; + +/** DESIGN을 깊은 복사한 뒤 path 위치 값을 바꾼다. undefined면 그 키를 지운다. */ +function patched(path: (string | number)[], value: unknown): unknown { + const copy = structuredClone(DESIGN) as unknown as Node; + const parent = path + .slice(0, -1) + .reduce((node, key) => node[key] as Node, copy); + const last = path[path.length - 1]; + if (value === undefined) delete parent[last]; + else parent[last] = value; + return copy; +} + +describe('readStoredThreeDDesign', () => { + let warn: jest.SpyInstance; + beforeEach(() => { + warn = jest.spyOn(Logger.prototype, 'warn').mockImplementation(() => {}); + }); + afterEach(() => jest.restoreAllMocks()); + + it('저장된 v1 디자인을 그대로 읽고 항목 종류에 없는 칸은 null로 채운다', () => { + expect(read(DESIGN)).toEqual({ + ...DESIGN, + top: [ + { ...TEXT, decoId: null }, + { ...DECO, text: null, color: null }, + ], + side: [{ ...DECO, text: null, color: null }], + }); + expect(warn).not.toHaveBeenCalled(); + }); + + it('디자인·맛 키가 빠져 있으면 null로 읽는다', () => { + const noFlavor = patched(['basic', 'flavor'], undefined) as Node; + delete (noFlavor.basic as Node).design; + expect(read(noFlavor)?.basic).toMatchObject({ design: null, flavor: null }); + }); + + it('디자인 행이 없으면 기록 없이 null이다', () => { + expect(readStoredThreeDDesign(1n, null)).toBeNull(); + expect(warn).not.toHaveBeenCalled(); + }); + + it('지원하지 않는 컬럼 버전이면 null + 기록', () => { + expect(read(DESIGN, 2)).toBeNull(); + expect(warn).toHaveBeenCalledWith( + expect.stringContaining('orderItemId=42'), + ); + }); + + // 콜백 인자 수가 행 길이보다 많으면 jest가 마지막 인자를 done으로 본다 — 행과 인자 수를 맞춘다 + it.each<[string, unknown]>([ + ['JSON 버전이 컬럼과 다름', patched(['schemaVersion'], 2)], + ['JSON이 객체가 아님', [DESIGN]], + ['JSON이 null', null], + ['basic 없음', patched(['basic'], undefined)], + ['shape가 문자열이 아님', patched(['basic', 'shape'], 3)], + ['size 없음', patched(['basic', 'size'], undefined)], + ['sheetColor 없음', patched(['basic', 'sheetColor'], undefined)], + ['design이 문자열·null이 아님', patched(['basic', 'design'], 1)], + ['flavor가 문자열·null이 아님', patched(['basic', 'flavor'], {})], + ['top이 배열이 아님', patched(['top'], {})], + ['side 없음', patched(['side'], undefined)], + ['항목이 객체가 아님', patched(['top', 0], 'TEXT')], + ['모르는 항목 종류', patched(['top', 0, 'kind'], 'IMAGE')], + ['x가 수가 아님', patched(['top', 0, 'x'], '0.5')], + ['y 없음', patched(['side', 0, 'y'], undefined)], + ['size가 유한수가 아님', patched(['top', 1, 'size'], null)], + ['effect 없음', patched(['top', 0, 'effect'], undefined)], + ['effect.type이 문자열이 아님', patched(['top', 0, 'effect', 'type'], 1)], + [ + 'effect.intensity가 정수가 아님', + patched(['top', 0, 'effect', 'intensity'], 0.5), + ], + ['글자에 text 없음', patched(['top', 0, 'text'], undefined)], + ['글자에 color 없음', patched(['top', 0, 'color'], undefined)], + ['꾸미기에 decoId 없음', patched(['side', 0, 'decoId'], undefined)], + ])('%s → null + 기록', (_case, json) => { + expect(read(json)).toBeNull(); + expect(warn).toHaveBeenCalledWith( + expect.stringContaining('orderItemId=42'), + ); + }); +}); diff --git a/src/features/order/services/order-custom-design.helper.ts b/src/features/order/services/order-custom-design.helper.ts new file mode 100644 index 00000000..5ad04c8a --- /dev/null +++ b/src/features/order/services/order-custom-design.helper.ts @@ -0,0 +1,109 @@ +import { Logger } from '@nestjs/common'; + +import type { + ThreeDDesignItemOutput, + ThreeDDesignOutput, +} from '@/features/order/types/order-output.type'; +import { THREE_D_DESIGN_SCHEMA_VERSION } from '@/features/product'; +import type { Prisma } from '@/generated/prisma/client'; + +const logger = new Logger('OrderCustomDesign'); + +type JsonObject = { [key: string]: Prisma.JsonValue | undefined }; + +const isObject = (v: unknown): v is JsonObject => + v !== null && typeof v === 'object' && !Array.isArray(v); +const isString = (v: unknown): v is string => typeof v === 'string'; +const isNumber = (v: unknown): v is number => + typeof v === 'number' && Number.isFinite(v); +const isInteger = (v: unknown): v is number => Number.isInteger(v); +const nullableString = (v: unknown): string | null | undefined => + v === null || v === undefined ? null : isString(v) ? v : undefined; + +function parseItem(v: unknown): ThreeDDesignItemOutput | null { + if ( + !isObject(v) || + !isNumber(v.x) || + !isNumber(v.y) || + !isNumber(v.size) || + !isObject(v.effect) || + !isString(v.effect.type) || + !isInteger(v.effect.intensity) + ) + return null; + const base = { + x: v.x, + y: v.y, + size: v.size, + effect: { type: v.effect.type, intensity: v.effect.intensity }, + }; + if (v.kind === 'TEXT' && isString(v.text) && isString(v.color)) + return { + kind: 'TEXT', + ...base, + text: v.text, + color: v.color, + decoId: null, + }; + if (v.kind === 'DECO' && isString(v.decoId)) + return { kind: 'DECO', ...base, text: null, color: null, decoId: v.decoId }; + return null; +} + +function parseItems(v: unknown): ThreeDDesignItemOutput[] | null { + if (!Array.isArray(v)) return null; + const items = v.map(parseItem); + return items.every((item) => item !== null) ? items : null; +} + +function parseDesign( + schemaVersion: number, + json: Prisma.JsonValue, +): ThreeDDesignOutput | null { + if ( + schemaVersion !== THREE_D_DESIGN_SCHEMA_VERSION || + !isObject(json) || + json.schemaVersion !== schemaVersion || + !isObject(json.basic) + ) + return null; + const { shape, size, sheetColor } = json.basic; + const design = nullableString(json.basic.design); + const flavor = nullableString(json.basic.flavor); + const top = parseItems(json.top); + const side = parseItems(json.side); + if ( + !isString(shape) || + !isString(size) || + !isString(sheetColor) || + design === undefined || + flavor === undefined || + !top || + !side + ) + return null; + return { + schemaVersion, + basic: { shape, size, design, flavor, sheetColor }, + top, + side, + }; +} + +/** + * 저장된 3D 디자인을 출력 형태로 읽는다. 저장 전 검증을 거친 값이지만 버전·형태가 어긋나면 + * 상세 전체를 실패시키지 않고 디자인만 null로 내리고 기록을 남긴다. + */ +export function readStoredThreeDDesign( + orderItemId: bigint, + row: { schema_version: number; design_json: Prisma.JsonValue } | null, +): ThreeDDesignOutput | null { + if (!row) return null; + const design = parseDesign(row.schema_version, row.design_json); + if (!design) { + logger.warn( + `주문 3D 디자인을 읽을 수 없음 (orderItemId=${orderItemId}, schemaVersion=${row.schema_version})`, + ); + } + return design; +} diff --git a/src/features/order/services/order-deposit-admin.service.spec.ts b/src/features/order/services/order-deposit-admin.service.spec.ts index b1917095..8b460c15 100644 --- a/src/features/order/services/order-deposit-admin.service.spec.ts +++ b/src/features/order/services/order-deposit-admin.service.spec.ts @@ -249,6 +249,7 @@ describe('AdminDepositService (real DB)', () => { orderId: order.id.toString(), status: 'SUBMITTED', productName: '딸기 케이크', + hasCustom: false, }), ]); topic.stop(); diff --git a/src/features/order/services/order-deposit-admin.service.ts b/src/features/order/services/order-deposit-admin.service.ts index 29a68b1c..33f1eeb2 100644 --- a/src/features/order/services/order-deposit-admin.service.ts +++ b/src/features/order/services/order-deposit-admin.service.ts @@ -126,11 +126,7 @@ export class AdminDepositService extends AdminBaseService { if (firstItem) { await this.events.publishSellerOrderUpdate( firstItem.store_id, - toSellerOrderUpdateEvent( - 'SUBMITTED', - updated, - firstItem.product_name_snapshot, - ), + toSellerOrderUpdateEvent('SUBMITTED', updated), ); } return toAdminOrderSummaryOutput(updated); diff --git a/src/features/order/services/order-events-mappers.helper.ts b/src/features/order/services/order-events-mappers.helper.ts index 9658d712..1719d935 100644 --- a/src/features/order/services/order-events-mappers.helper.ts +++ b/src/features/order/services/order-events-mappers.helper.ts @@ -1,8 +1,9 @@ +import { isCustomOrderItem } from '@/features/order/services/order-output-mappers.helper'; import type { SellerOrderUpdateEvent, SellerOrderUpdateKind, } from '@/features/order/types/order-seller-output.type'; -import type { Order } from '@/generated/prisma/client'; +import type { Order, OrderItem } from '@/generated/prisma/client'; export type SellerOrderUpdateRow = Pick< Order, @@ -13,13 +14,16 @@ export type SellerOrderUpdateRow = Pick< | 'buyer_name' | 'total_price' | 'updated_at' ->; +> & { + /** 첫 품목이 상품명·커스텀 여부를 정한다 */ + items: Pick[]; +}; export function toSellerOrderUpdateEvent( kind: SellerOrderUpdateKind, row: SellerOrderUpdateRow, - productName: string, ): SellerOrderUpdateEvent { + const [firstItem] = row.items; return { kind, orderId: row.id.toString(), @@ -28,7 +32,8 @@ export function toSellerOrderUpdateEvent( pickupAt: row.pickup_at.toISOString(), buyerName: row.buyer_name, totalPrice: row.total_price, - productName, + productName: firstItem?.product_name_snapshot ?? '', + hasCustom: isCustomOrderItem(firstItem), updatedAt: row.updated_at.toISOString(), }; } diff --git a/src/features/order/services/order-events.service.spec.ts b/src/features/order/services/order-events.service.spec.ts index 789e3cbe..827a6163 100644 --- a/src/features/order/services/order-events.service.spec.ts +++ b/src/features/order/services/order-events.service.spec.ts @@ -19,6 +19,7 @@ const EVENT: SellerOrderUpdateEvent = { buyerName: '차차', totalPrice: 56000, productName: '딸기 케이크', + hasCustom: false, updatedAt: '2026-09-16T07:00:00.000Z', }; diff --git a/src/features/order/services/order-events.service.ts b/src/features/order/services/order-events.service.ts index 3f8ce31a..73d0f407 100644 --- a/src/features/order/services/order-events.service.ts +++ b/src/features/order/services/order-events.service.ts @@ -46,11 +46,7 @@ export class OrderEventsService { if (!firstItem || !row.submitted_at) return; await this.publishSellerOrderUpdate( firstItem.store_id, - toSellerOrderUpdateEvent( - 'STATUS_CHANGED', - row, - firstItem.product_name_snapshot, - ), + toSellerOrderUpdateEvent('STATUS_CHANGED', row), ); } diff --git a/src/features/order/services/order-my.service.spec.ts b/src/features/order/services/order-my.service.spec.ts index 1470ef2a..3287767e 100644 --- a/src/features/order/services/order-my.service.spec.ts +++ b/src/features/order/services/order-my.service.spec.ts @@ -1,3 +1,4 @@ +import { Logger } from '@nestjs/common'; import { PubSub } from 'graphql-subscriptions'; import { ClockService } from '@/common/providers/clock.service'; @@ -27,7 +28,9 @@ import { createProduct, createReview, createStore, + createThreeDOrderItemCustom, createUserProfile, + MINIMAL_THREE_D_DESIGN, } from '@/test/factories'; import { createTestingModuleWithRealDb } from '@/test/modules/testing-module.builder'; import { outboxPublisherProviders } from '@/test/outbox'; @@ -441,6 +444,113 @@ describe('UserOrderService (real DB)', () => { }); }); + it('커스텀 스냅샷(방식·대표·바탕 이미지·렌더 종류 순·3D 디자인·문구·자유 편집 영역)을 상세에 싣는다', async () => { + const account = await setupUser(); + const order = await createOrder(prisma, { account_id: account.id }); + const item = await createOrderItem(prisma, { + order_id: order.id, + custom_mode_snapshot: 'THREE_D', + custom_preview_image_url: 'https://img/THREE_D_TOP.png', + }); + await createThreeDOrderItemCustom(prisma, item.id); + const slot = await createOrderItem(prisma, { + order_id: order.id, + custom_mode_snapshot: 'SLOT', + custom_base_image_url_snapshot: 'https://img/base.png', + custom_preview_image_url: 'https://img/composite.png', + }); + await prisma.orderItemCustomText.create({ + data: { + order_item_id: slot.id, + token_id: 77n, + token_key_snapshot: 'top', + label_snapshot: '윗줄', + default_text_snapshot: '축하해', + value_text: null, + pos_x: 1000, + pos_y: 1000, + width: 8000, + height: 1500, + text_color: '#1D1D1D', + text_align: 'RIGHT', + }, + }); + await prisma.orderItemCustomFreeEdit.create({ + data: { + order_item_id: slot.id, + pos_x: 2000, + pos_y: 4000, + width: 6000, + height: 4000, + description_text: '여기에 그림', + }, + }); + + const result = await service.getMyOrder(account.id, order.id); + + const [threeD, slotItem] = result.items.map((i) => i.item); + expect(threeD).toMatchObject({ + customMode: 'THREE_D', + customPreviewImageUrl: 'https://img/THREE_D_TOP.png', + customBaseImageUrl: null, + threeDDesign: MINIMAL_THREE_D_DESIGN, + customTexts: [], + freeEdits: [], + }); + expect(threeD.customImages.map((i) => i.kind)).toEqual([ + 'THREE_D_TOP', + 'THREE_D_FRONT', + 'THREE_D_BACK', + 'THREE_D_LEFT', + 'THREE_D_RIGHT', + ]); + expect(slotItem).toMatchObject({ + customMode: 'SLOT', + customPreviewImageUrl: 'https://img/composite.png', + customBaseImageUrl: 'https://img/base.png', + customImages: [], + threeDDesign: null, + customTexts: [ + { + tokenId: '77', + label: '윗줄', + valueText: null, + posX: 1000, + posY: 1000, + width: 8000, + height: 1500, + textColor: '#1D1D1D', + textAlign: 'RIGHT', + }, + ], + freeEdits: [ + { + posX: 2000, + posY: 4000, + width: 6000, + height: 4000, + descriptionText: '여기에 그림', + }, + ], + }); + }); + + it('저장된 3D 디자인을 읽을 수 없으면 디자인만 null이고 상세는 내려간다', async () => { + const account = await setupUser(); + const order = await createOrder(prisma, { account_id: account.id }); + const item = await createOrderItem(prisma, { + order_id: order.id, + custom_mode_snapshot: 'THREE_D', + }); + await createThreeDOrderItemCustom(prisma, item.id, { schemaVersion: 1 }); + jest.spyOn(Logger.prototype, 'warn').mockImplementation(() => undefined); + + const result = await service.getMyOrder(account.id, order.id); + + expect(result.items[0].item.threeDDesign).toBeNull(); + expect(result.items[0].item.customImages).toHaveLength(5); + }); + it('존재하지 않는 orderId면 404', async () => { const account = await setupUser(); await expect( diff --git a/src/features/order/services/order-output-mappers.helper.spec.ts b/src/features/order/services/order-output-mappers.helper.spec.ts index 3b725544..c8d37f72 100644 --- a/src/features/order/services/order-output-mappers.helper.spec.ts +++ b/src/features/order/services/order-output-mappers.helper.spec.ts @@ -2,6 +2,7 @@ import { toOrderCancellation, toOrderItemDetail, toOrderItemFreeEdit, + toOrderListCustomBadge, toOrderRefund, toOrderStatusHistory, type OrderItemDetailRow, @@ -9,6 +10,8 @@ import { } from '@/features/order/services/order-output-mappers.helper'; import type { Refund } from '@/generated/prisma/client'; +const AREA = { pos_x: 1000, pos_y: 2000, width: 8000, height: 1500 }; + function itemRow(o: Partial = {}): OrderItemDetailRow { return { id: 10n, @@ -27,19 +30,31 @@ function itemRow(o: Partial = {}): OrderItemDetailRow { option_price_delta_snapshot: 1000, }, ], + custom_mode_snapshot: 'SLOT', + custom_base_image_url_snapshot: 'base.png', + custom_preview_image_url: 'composite.png', + custom_design: null, + custom_images: [ + { id: 500n, kind: 'SLOT_COMPOSITE', image_url: 'composite.png' }, + ], custom_texts: [ { id: 200n, - token_key_snapshot: 'TOP', + token_id: 7n, + token_key_snapshot: 'top', + label_snapshot: '윗줄', default_text_snapshot: '축하해', value_text: '생일 축하해', + ...AREA, + text_color: '#1D1D1D', + text_align: 'LEFT', sort_order: 0, }, ], free_edits: [ { id: 300n, - crop_image_url: 'crop.png', + ...AREA, description_text: '여기 하트', sort_order: 0, attachments: [{ id: 400n, image_url: 'ref.png', sort_order: 0 }], @@ -63,19 +78,37 @@ describe('order-output-mappers', () => { optionItems: [ { id: '100', groupName: '크기', optionTitle: '2호', priceDelta: 1000 }, ], + customMode: 'SLOT', + customPreviewImageUrl: 'composite.png', + customBaseImageUrl: 'base.png', + customImages: [ + { id: '500', kind: 'SLOT_COMPOSITE', imageUrl: 'composite.png' }, + ], + threeDDesign: null, customTexts: [ { id: '200', - tokenKey: 'TOP', + tokenId: '7', + tokenKey: 'top', + label: '윗줄', defaultText: '축하해', valueText: '생일 축하해', + posX: 1000, + posY: 2000, + width: 8000, + height: 1500, + textColor: '#1D1D1D', + textAlign: 'LEFT', sortOrder: 0, }, ], freeEdits: [ { id: '300', - cropImageUrl: 'crop.png', + posX: 1000, + posY: 2000, + width: 8000, + height: 1500, descriptionText: '여기 하트', sortOrder: 0, attachments: [{ id: '400', imageUrl: 'ref.png', sortOrder: 0 }], @@ -99,18 +132,114 @@ describe('order-output-mappers', () => { expect(result.freeEdits).toEqual([]); }); + it('커스텀이 없는 품목은 NONE·이미지 없음·디자인 null이다', () => { + const result = toOrderItemDetail( + itemRow({ + custom_mode_snapshot: 'NONE', + custom_base_image_url_snapshot: null, + custom_preview_image_url: null, + custom_images: [], + custom_texts: [], + free_edits: [], + }), + ); + expect(result).toMatchObject({ + customMode: 'NONE', + customPreviewImageUrl: null, + customBaseImageUrl: null, + customImages: [], + threeDDesign: null, + }); + }); + + it('문구 자리 지정 전 문구는 tokenId null, 지운 선택 자리는 valueText null로 내린다', () => { + const [text] = toOrderItemDetail( + itemRow({ + custom_texts: [ + { + ...itemRow().custom_texts[0], + token_id: null, + value_text: null, + }, + ], + }), + ).customTexts; + expect(text).toMatchObject({ tokenId: null, valueText: null }); + }); + + it('3D 디자인은 저장된 JSON을 출력 형태로 읽는다', () => { + const design = { + schemaVersion: 1, + basic: { + shape: 'heart', + size: 'mini', + design: null, + flavor: 'choco', + sheetColor: 'white', + }, + top: [ + { + kind: 'TEXT', + x: 0.5, + y: 0.5, + size: 10, + effect: { type: 'none', intensity: 50 }, + text: '축하', + color: '#FFFFFF', + }, + ], + side: [], + }; + const result = toOrderItemDetail( + itemRow({ + custom_mode_snapshot: 'THREE_D', + custom_design: { schema_version: 1, design_json: design }, + }), + ); + expect(result.threeDDesign).toEqual({ + ...design, + top: [{ ...design.top[0], decoId: null }], + }); + }); + + it.each([ + ['NONE', null, { hasCustom: false, firstItemCustomImageUrl: null }], + ['SLOT', 'c.png', { hasCustom: true, firstItemCustomImageUrl: 'c.png' }], + ['THREE_D', 't.png', { hasCustom: true, firstItemCustomImageUrl: 't.png' }], + ] as const)('toOrderListCustomBadge: %s 품목 → %o', (mode, url, expected) => { + expect( + toOrderListCustomBadge({ + custom_mode_snapshot: mode, + custom_preview_image_url: url, + }), + ).toEqual(expected); + }); + + it('toOrderListCustomBadge: 품목이 없으면 배지 없음', () => { + expect(toOrderListCustomBadge(undefined)).toEqual({ + hasCustom: false, + firstItemCustomImageUrl: null, + }); + }); + it('toOrderItemFreeEdit: 첨부가 없으면 빈 배열', () => { expect( toOrderItemFreeEdit({ id: 1n, - crop_image_url: 'c.png', + pos_x: 0, + pos_y: 0, + width: 10000, + height: 10000, description_text: 'd', sort_order: 1, attachments: [], }), ).toEqual({ id: '1', - cropImageUrl: 'c.png', + posX: 0, + posY: 0, + width: 10000, + height: 10000, descriptionText: 'd', sortOrder: 1, attachments: [], diff --git a/src/features/order/services/order-output-mappers.helper.ts b/src/features/order/services/order-output-mappers.helper.ts index 8160ae54..b6720cd9 100644 --- a/src/features/order/services/order-output-mappers.helper.ts +++ b/src/features/order/services/order-output-mappers.helper.ts @@ -3,6 +3,7 @@ import { maskAccountNumber, toBank, } from '@/features/order/services/order-bank-account.helper'; +import { readStoredThreeDDesign } from '@/features/order/services/order-custom-design.helper'; import type { OrderCancellationOutput, OrderItemDetailOutput, @@ -14,15 +15,25 @@ import { OrderCancelReason, OrderStatus, RefundKind, + type CustomImageKind, + type CustomMode, + type CustomTextAlign, type OrderActor, type OrderCancelFault, + type Prisma, type Refund, } from '@/generated/prisma/client'; +interface CustomAreaRow { + pos_x: number; + pos_y: number; + width: number; + height: number; +} + /** 판매자·관리자·구매자 조회 row가 모두 만족하는 구조적 부분집합. */ -export interface OrderItemFreeEditRow { +export interface OrderItemFreeEditRow extends CustomAreaRow { id: bigint; - crop_image_url: string; description_text: string; sort_order: number; attachments: { id: bigint; image_url: string; sort_order: number }[]; @@ -43,16 +54,35 @@ export interface OrderItemDetailRow { option_title_snapshot: string; option_price_delta_snapshot: number; }[]; - custom_texts: { + custom_mode_snapshot: CustomMode; + custom_base_image_url_snapshot: string | null; + custom_preview_image_url: string | null; + custom_design: { + schema_version: number; + design_json: Prisma.JsonValue; + } | null; + custom_images: { id: bigint; kind: CustomImageKind; image_url: string }[]; + custom_texts: (CustomAreaRow & { id: bigint; + token_id: bigint | null; token_key_snapshot: string; + label_snapshot: string; default_text_snapshot: string; - value_text: string; + value_text: string | null; + text_color: string; + text_align: CustomTextAlign; sort_order: number; - }[]; + })[]; free_edits: OrderItemFreeEditRow[]; } +const toArea = (row: CustomAreaRow) => ({ + posX: row.pos_x, + posY: row.pos_y, + width: row.width, + height: row.height, +}); + export interface OrderStatusHistoryRow { id: bigint; from_status: OrderStatus | null; @@ -83,11 +113,25 @@ export function toOrderItemDetail( optionTitle: opt.option_title_snapshot, priceDelta: opt.option_price_delta_snapshot, })), + customMode: item.custom_mode_snapshot, + customPreviewImageUrl: item.custom_preview_image_url, + customBaseImageUrl: item.custom_base_image_url_snapshot, + customImages: item.custom_images.map((image) => ({ + id: image.id.toString(), + kind: image.kind, + imageUrl: image.image_url, + })), + threeDDesign: readStoredThreeDDesign(item.id, item.custom_design), customTexts: item.custom_texts.map((text) => ({ id: text.id.toString(), + tokenId: text.token_id?.toString() ?? null, tokenKey: text.token_key_snapshot, + label: text.label_snapshot, defaultText: text.default_text_snapshot, valueText: text.value_text, + ...toArea(text), + textColor: text.text_color, + textAlign: text.text_align, sortOrder: text.sort_order, })), freeEdits: item.free_edits.map(toOrderItemFreeEdit), @@ -99,7 +143,7 @@ export function toOrderItemFreeEdit( ): OrderItemFreeEditOutput { return { id: edit.id.toString(), - cropImageUrl: edit.crop_image_url, + ...toArea(edit), descriptionText: edit.description_text, sortOrder: edit.sort_order, attachments: edit.attachments.map((a) => ({ @@ -110,6 +154,25 @@ export function toOrderItemFreeEdit( }; } +/** 판매자·관리자 목록과 판매자 구독의 '커스텀' 배지. 주문은 단일 상품이라 첫 품목이 정한다 */ +export const isCustomOrderItem = ( + item: { custom_mode_snapshot: CustomMode } | undefined, +): boolean => item !== undefined && item.custom_mode_snapshot !== 'NONE'; + +export function toOrderListCustomBadge( + item: + | { + custom_mode_snapshot: CustomMode; + custom_preview_image_url: string | null; + } + | undefined, +): { hasCustom: boolean; firstItemCustomImageUrl: string | null } { + return { + hasCustom: isCustomOrderItem(item), + firstItemCustomImageUrl: item?.custom_preview_image_url ?? null, + }; +} + export function toOrderStatusHistory( history: OrderStatusHistoryRow, ): OrderStatusHistoryOutput { diff --git a/src/features/order/services/order-seller.service.spec.ts b/src/features/order/services/order-seller.service.spec.ts index 4f8faa9d..3b845e41 100644 --- a/src/features/order/services/order-seller.service.spec.ts +++ b/src/features/order/services/order-seller.service.spec.ts @@ -21,6 +21,7 @@ import { createOrderItem, createPayment, createProduct, + createThreeDOrderItemCustom, setupSellerWithStore, } from '@/test/factories'; import { createTestingModuleWithRealDb } from '@/test/modules/testing-module.builder'; @@ -192,6 +193,30 @@ describe('SellerOrderService (real DB)', () => { expect(result.items[0].firstItemName).toBe('활성 품목'); }); + it.each([ + ['3D', 'THREE_D', 'https://img/top.png', true], + ['슬롯형', 'SLOT', 'https://img/composite.png', true], + ['커스텀 없음', 'NONE', null, false], + ] as const)( + '%s 첫 품목이면 커스텀 배지·대표 이미지를 싣는다', + async (_case, mode, url, hasCustom) => { + const { account, store } = await setupSellerWithStore(prisma); + const order = await createOrder(prisma); + await createOrderItem(prisma, { + order_id: order.id, + store_id: store.id, + custom_mode_snapshot: mode, + custom_preview_image_url: url, + }); + + const result = await service.sellerOrderList(account.id); + expect(result.items[0]).toMatchObject({ + hasCustom, + firstItemCustomImageUrl: url, + }); + }, + ); + it('썸네일 스냅샷이 없으면 firstItemImageUrl은 null', async () => { const { account, store } = await setupSellerWithStore(prisma); const order = await createOrder(prisma); @@ -402,6 +427,28 @@ describe('SellerOrderService (real DB)', () => { }); }); + it('상세 품목에 렌더 이미지(종류 순)·3D 디자인을 싣는다', async () => { + const { account, store } = await setupSellerWithStore(prisma); + const order = await createOrder(prisma); + const item = await createOrderItem(prisma, { + order_id: order.id, + store_id: store.id, + custom_mode_snapshot: 'THREE_D', + }); + await createThreeDOrderItemCustom(prisma, item.id); + + const [detail] = (await service.sellerOrder(account.id, order.id)).items; + expect(detail.customMode).toBe('THREE_D'); + expect(detail.threeDDesign?.basic.shape).toBe('heart'); + expect(detail.customImages.map((i) => i.imageUrl)).toEqual([ + 'https://img/THREE_D_TOP.png', + 'https://img/THREE_D_FRONT.png', + 'https://img/THREE_D_BACK.png', + 'https://img/THREE_D_LEFT.png', + 'https://img/THREE_D_RIGHT.png', + ]); + }); + it('결제가 있으면 결제 수단을 준다', async () => { const { account, store } = await setupSellerWithStore(prisma); const order = await createStoreOrder(store.id, { status: 'SUBMITTED' }); @@ -884,13 +931,14 @@ describe('SellerOrderService (real DB)', () => { }); describe('sellerOrderUpdated 발행', () => { - it('상태 변경 시 매장 토픽에 1건 — 첫 품목 상품명과 갱신된 updated_at을 싣는다', async () => { + it('상태 변경 시 매장 토픽에 1건 — 첫 품목 상품명·커스텀 여부와 갱신된 updated_at을 싣는다', async () => { const { account, store } = await setupSellerWithStore(prisma); const order = await createOrder(prisma); await createOrderItem(prisma, { order_id: order.id, store_id: store.id, product_name_snapshot: '확정 품목', + custom_mode_snapshot: 'THREE_D', }); const topic = await collectTopic(pubSub, `order.seller.${store.id}`); @@ -913,6 +961,7 @@ describe('SellerOrderService (real DB)', () => { buyerName: order.buyer_name, totalPrice: order.total_price, productName: '확정 품목', + hasCustom: true, updatedAt: row.updated_at.toISOString(), }, ]); diff --git a/src/features/order/services/order-seller.service.ts b/src/features/order/services/order-seller.service.ts index 1f0cc40d..c35276d1 100644 --- a/src/features/order/services/order-seller.service.ts +++ b/src/features/order/services/order-seller.service.ts @@ -31,6 +31,7 @@ import { OrderEventsService } from '@/features/order/services/order-events.servi import { toOrderCancellation, toOrderItemDetail, + toOrderListCustomBadge, toOrderStatusHistory, type OrderItemDetailRow, type OrderStatusHistoryRow, @@ -147,11 +148,7 @@ export class SellerOrderService extends SellerBaseService { await this.events.publishSellerOrderUpdate( ctx.storeId, - toSellerOrderUpdateEvent( - 'STATUS_CHANGED', - updated, - updated.items[0]?.product_name_snapshot ?? '', - ), + toSellerOrderUpdateEvent('STATUS_CHANGED', updated), ); return this.toOrderSummaryOutput(updated); } @@ -198,6 +195,7 @@ export class SellerOrderService extends SellerBaseService { // 내 매장 첫 품목의 주문 시점 스냅샷 — 상품이 바뀌어도 카드 값은 유지된다 firstItemName: row.items[0]?.product_name_snapshot ?? null, firstItemImageUrl: row.items[0]?.product_thumbnail_url_snapshot ?? null, + ...toOrderListCustomBadge(row.items[0]), }; } diff --git a/src/features/order/services/order-subscription.service.spec.ts b/src/features/order/services/order-subscription.service.spec.ts index e5682d86..7b9e623a 100644 --- a/src/features/order/services/order-subscription.service.spec.ts +++ b/src/features/order/services/order-subscription.service.spec.ts @@ -61,6 +61,7 @@ describe('OrderSubscriptionService (real DB)', () => { buyerName: '차차', totalPrice: 10000, productName: '케이크', + hasCustom: false, updatedAt: '2026-09-16T07:00:00.000Z', }; diff --git a/src/features/order/types/order-admin-output.type.ts b/src/features/order/types/order-admin-output.type.ts index 8a761303..96f5be36 100644 --- a/src/features/order/types/order-admin-output.type.ts +++ b/src/features/order/types/order-admin-output.type.ts @@ -26,6 +26,8 @@ export interface AdminOrderSummaryOutput { createdAt: Date; firstItemName: string | null; firstItemImageUrl: string | null; + hasCustom: boolean; + firstItemCustomImageUrl: string | null; } export interface AdminStoreInProgressOrderSummaryOutput { diff --git a/src/features/order/types/order-output.type.ts b/src/features/order/types/order-output.type.ts index 922fb59e..cfba822c 100644 --- a/src/features/order/types/order-output.type.ts +++ b/src/features/order/types/order-output.type.ts @@ -1,5 +1,8 @@ import type { BankOutput } from '@/features/order/types/order-payment-output.type'; import type { + CustomImageKind, + CustomMode, + CustomTextAlign, OrderActor, OrderCancelFault, OrderCancelReason, @@ -15,11 +18,22 @@ export interface OrderItemOptionOutput { priceDelta: number; } -export interface OrderItemCustomTextOutput { +export interface OrderCustomAreaOutput { + posX: number; + posY: number; + width: number; + height: number; +} + +export interface OrderItemCustomTextOutput extends OrderCustomAreaOutput { id: string; + tokenId: string | null; tokenKey: string; + label: string; defaultText: string; - valueText: string; + valueText: string | null; + textColor: string; + textAlign: CustomTextAlign; sortOrder: number; } @@ -29,14 +43,43 @@ export interface OrderItemFreeEditAttachmentOutput { sortOrder: number; } -export interface OrderItemFreeEditOutput { +export interface OrderItemFreeEditOutput extends OrderCustomAreaOutput { id: string; - cropImageUrl: string; descriptionText: string; sortOrder: number; attachments: OrderItemFreeEditAttachmentOutput[]; } +export interface OrderItemCustomImageOutput { + id: string; + kind: CustomImageKind; + imageUrl: string; +} + +export interface ThreeDDesignItemOutput { + kind: 'TEXT' | 'DECO'; + x: number; + y: number; + size: number; + effect: { type: string; intensity: number }; + text: string | null; + color: string | null; + decoId: string | null; +} + +export interface ThreeDDesignOutput { + schemaVersion: number; + basic: { + shape: string; + size: string; + design: string | null; + flavor: string | null; + sheetColor: string; + }; + top: ThreeDDesignItemOutput[]; + side: ThreeDDesignItemOutput[]; +} + export interface OrderItemDetailOutput { id: string; storeId: string; @@ -47,6 +90,11 @@ export interface OrderItemDetailOutput { quantity: number; itemSubtotalPrice: number; optionItems: OrderItemOptionOutput[]; + customMode: CustomMode; + customPreviewImageUrl: string | null; + customBaseImageUrl: string | null; + customImages: OrderItemCustomImageOutput[]; + threeDDesign: ThreeDDesignOutput | null; customTexts: OrderItemCustomTextOutput[]; freeEdits: OrderItemFreeEditOutput[]; } diff --git a/src/features/order/types/order-seller-output.type.ts b/src/features/order/types/order-seller-output.type.ts index 1e76d016..6a013837 100644 --- a/src/features/order/types/order-seller-output.type.ts +++ b/src/features/order/types/order-seller-output.type.ts @@ -16,6 +16,8 @@ export interface SellerOrderSummaryOutput { createdAt: Date; firstItemName: string | null; firstItemImageUrl: string | null; + hasCustom: boolean; + firstItemCustomImageUrl: string | null; } export interface SellerOrderDetailOutput { @@ -57,5 +59,6 @@ export interface SellerOrderUpdateEvent { buyerName: string; totalPrice: number; productName: string; + hasCustom: boolean; updatedAt: string; } diff --git a/src/features/product/index.ts b/src/features/product/index.ts index 0b1245bd..cfacdf61 100644 --- a/src/features/product/index.ts +++ b/src/features/product/index.ts @@ -16,6 +16,8 @@ export { type ThreeDDesignSource, type ThreeDDesignV1, } from '@/features/product/services/three-d-design.helper'; +// 주문 상세가 저장된 3D 디자인을 읽을 때 지원하는 JSON 버전. +export { THREE_D_DESIGN_SCHEMA_VERSION } from '@/features/product/constants/custom-3d-catalog.constants'; // 상품 카드 1벌. 찜·최근 본 상품(user feature)이 같은 카드를 쓴다. export { ProductCardService } from '@/features/product/services/product-card.service'; export type { ProductCardOutput } from '@/features/product/types/product-card-output.type'; diff --git a/src/features/product/resolvers/product-home-query.resolver.spec.ts b/src/features/product/resolvers/product-home-query.resolver.spec.ts index 0189aeac..0925ac9c 100644 --- a/src/features/product/resolvers/product-home-query.resolver.spec.ts +++ b/src/features/product/resolvers/product-home-query.resolver.spec.ts @@ -63,13 +63,9 @@ describe('ProductHome Query Resolver (real DB)', () => { }); it('customCakeShowcase: 서비스에 위임해 제작 후기 목록을 반환한다', async () => { - const orderItem = await createOrderItem(prisma); - await prisma.orderItemCustomFreeEdit.create({ - data: { - order_item_id: orderItem.id, - crop_image_url: 'https://img/before.png', - description_text: '요청 디자인', - }, + const orderItem = await createOrderItem(prisma, { + custom_mode_snapshot: 'SLOT', + custom_preview_image_url: 'https://img/before.png', }); const review = await createReview(prisma, { order_item_id: orderItem.id, diff --git a/src/features/product/services/product-home.service.spec.ts b/src/features/product/services/product-home.service.spec.ts index 8c5568cd..cceb4e3e 100644 --- a/src/features/product/services/product-home.service.spec.ts +++ b/src/features/product/services/product-home.service.spec.ts @@ -23,6 +23,7 @@ import { createStore, createUserProfile, linkProductCategory, + nextSeq, } from '@/test/factories'; import { createTestingModuleWithRealDb } from '@/test/modules/testing-module.builder'; @@ -424,7 +425,7 @@ describe('ProductHomeService (real DB)', () => { }); describe('customCakeShowcase', () => { - /** Before(주문 커스텀 크롭)/After(리뷰 이미지)가 모두 있는 쇼케이스 후보 리뷰. */ + /** Before(주문 커스텀 대표 이미지)/After(리뷰 이미지)가 모두 있는 쇼케이스 후보 리뷰. */ async function makeShowcaseReview(args?: { storeId?: bigint; nickname?: string; @@ -432,19 +433,15 @@ describe('ProductHomeService (real DB)', () => { before?: boolean; after?: boolean; }): Promise { - const orderItem = await createOrderItem( - prisma, - args?.storeId !== undefined ? { store_id: args.storeId } : {}, - ); - if (args?.before !== false) { - await prisma.orderItemCustomFreeEdit.create({ - data: { - order_item_id: orderItem.id, - crop_image_url: `https://img/before-${orderItem.id}.png`, - description_text: '요청 디자인', - }, - }); - } + const orderItem = await createOrderItem(prisma, { + ...(args?.storeId !== undefined ? { store_id: args.storeId } : {}), + ...(args?.before !== false + ? { + custom_mode_snapshot: 'SLOT', + custom_preview_image_url: `https://img/before-${nextSeq()}.png`, + } + : {}), + }); const review = await createReview(prisma, { order_item_id: orderItem.id, content: args?.content ?? '후기 본문', @@ -583,28 +580,19 @@ describe('ProductHomeService (real DB)', () => { expect(limited).toHaveLength(2); }); - it('beforeImageUrl은 sort_order가 앞선 커스텀 크롭을 사용한다', async () => { + it('beforeImageUrl은 주문 품목의 커스텀 대표 이미지를 사용한다', async () => { const review = await makeShowcaseReview({ before: false }); const row = await prisma.review.findUniqueOrThrow({ where: { id: review }, }); - await prisma.orderItemCustomFreeEdit.create({ + await prisma.orderItem.update({ + where: { id: row.order_item_id }, data: { - order_item_id: row.order_item_id, - crop_image_url: 'https://img/second-crop.png', - description_text: '두 번째', - sort_order: 1, - }, - }); - await prisma.orderItemCustomFreeEdit.create({ - data: { - order_item_id: row.order_item_id, - crop_image_url: 'https://img/first-crop.png', - description_text: '첫 번째', - sort_order: 0, + custom_mode_snapshot: 'THREE_D', + custom_preview_image_url: 'https://img/top-render.png', }, }); - // before 이미지는 작성 시점 스냅샷(07b) — 크롭을 만든 뒤 작성 경로와 같은 규칙으로 다시 찍는다 + // before 이미지는 작성 시점 스냅샷 — 대표 이미지를 채운 뒤 작성 경로와 같은 규칙으로 다시 찍는다 await prisma.review.update({ where: { id: review }, data: await snapshotReviewOrderItem(prisma, row.order_item_id), @@ -612,7 +600,7 @@ describe('ProductHomeService (real DB)', () => { const result = await service.customCakeShowcase(); - expect(result[0].beforeImageUrl).toBe('https://img/first-crop.png'); + expect(result[0].beforeImageUrl).toBe('https://img/top-render.png'); }); }); diff --git a/src/features/review/repositories/review-order-item-snapshot.helper.ts b/src/features/review/repositories/review-order-item-snapshot.helper.ts index 9374c28f..342ef60f 100644 --- a/src/features/review/repositories/review-order-item-snapshot.helper.ts +++ b/src/features/review/repositories/review-order-item-snapshot.helper.ts @@ -17,7 +17,7 @@ export interface ReviewOrderItemSnapshot { /** * 리뷰 작성 시점에 주문 품목에서 표시값(상품명·매장명·옵션·before 이미지)을 복사한다 — 이후 조회는 review 컬럼만 읽는다. - * 옵션은 활성 option_item을 id 순으로, before 이미지는 활성 free_edit 첫 장(sort_order·id 순). 옵션이 없으면 null. + * 옵션은 활성 option_item을 id 순으로(없으면 null), before 이미지는 커스텀 대표 이미지(3D 윗면 렌더·슬롯형 합성). 커스텀 문구는 옮기지 않는다. */ export async function snapshotReviewOrderItem( tx: Prisma.TransactionClient, @@ -33,12 +33,7 @@ export async function snapshotReviewOrderItem( orderBy: { id: 'asc' }, select: { group_name_snapshot: true, option_title_snapshot: true }, }, - free_edits: { - where: activeWhere, - orderBy: [{ sort_order: 'asc' }, { id: 'asc' }], - take: 1, - select: { crop_image_url: true }, - }, + custom_preview_image_url: true, }, }); return { @@ -51,7 +46,7 @@ export async function snapshotReviewOrderItem( optionTitle: o.option_title_snapshot, })) : Prisma.DbNull, - before_image_url: item.free_edits[0]?.crop_image_url ?? null, + before_image_url: item.custom_preview_image_url, }; } diff --git a/src/features/review/repositories/review-order-item-snapshot.migration.spec.ts b/src/features/review/repositories/review-order-item-snapshot.migration.spec.ts index 164224fa..78b67d49 100644 --- a/src/features/review/repositories/review-order-item-snapshot.migration.spec.ts +++ b/src/features/review/repositories/review-order-item-snapshot.migration.spec.ts @@ -1,14 +1,20 @@ import { readFileSync } from 'node:fs'; import { join } from 'node:path'; +import mysql, { type RowDataPacket } from 'mysql2/promise'; + import type { PrismaClient } from '@/generated/prisma/client'; -import { disconnectTestPrismaClient } from '@/test/db/prisma-test-client'; +import { + disconnectTestPrismaClient, + getTestDatabaseUrl, +} from '@/test/db/prisma-test-client'; import { closeTruncateConnection, truncateAll } from '@/test/db/truncate'; import { createOrderItem, createReview } from '@/test/factories'; import { createTestingModuleWithRealDb } from '@/test/modules/testing-module.builder'; // 07b 마이그레이션의 백필 SQL을 그대로 실행해, 작성 시점 스냅샷 규칙(품목 상품명·활성 옵션 id 순·활성 크롭 첫 장)이 // 기존 리뷰에 같은 값으로 채워지는지 본다. 마이그레이션은 빈 DB에 적용되므로 여기서만 검증된다. +// 백필이 읽는 자유 편집 crop_image_url은 뒤 마이그레이션에서 지워져, 그 열을 더한 임시 표로 같은 이름을 가린 연결 하나에서 돌린다. const MIGRATION = join( __dirname, '../../../../prisma/migrations/20260919123000_review_order_item_snapshot/migration.sql', @@ -40,10 +46,38 @@ describe('review 주문 품목 스냅샷 백필 (real DB)', () => { await truncateAll(); }); - async function runBackfill(): Promise { + /** crop_image_url이 있던 자유 편집 표로 가린 연결에서 크롭을 넣고 백필을 돌린다(임시 표는 세션 범위). */ + async function runBackfill( + crops: Array<{ orderItemId: bigint; url: string; sortOrder: number }> = [], + ): Promise { const statements = backfillStatements(); expect(statements).toHaveLength(3); - for (const stmt of statements) await prisma.$executeRawUnsafe(stmt); + const conn = await mysql.createConnection({ uri: getTestDatabaseUrl() }); + try { + const table = 'order_item_custom_free_edit'; + await conn.query( + `CREATE TEMPORARY TABLE \`_legacy_${table}\` LIKE \`${table}\``, + ); + await conn.query( + `CREATE TEMPORARY TABLE \`${table}\` LIKE \`_legacy_${table}\``, + ); + const [[shown]] = await conn.query( + `SHOW CREATE TABLE \`${table}\``, + ); + expect(String(shown['Create Table'])).toMatch(/^CREATE TEMPORARY TABLE/); + await conn.query( + `ALTER TABLE \`${table}\` ADD COLUMN crop_image_url VARCHAR(2048) NOT NULL`, + ); + for (const crop of crops) { + await conn.query( + `INSERT INTO \`${table}\` (order_item_id, crop_image_url, description_text, sort_order, pos_x, pos_y, width, height, updated_at) VALUES (?, ?, '요청', ?, 0, 0, 10000, 10000, NOW(3))`, + [crop.orderItemId, crop.url, crop.sortOrder], + ); + } + for (const stmt of statements) await conn.query(stmt); + } finally { + await conn.end(); + } } it('상품명·활성 옵션(id 순)·활성 크롭 첫 장(sort_order 순)을 리뷰에 채운다', async () => { @@ -76,22 +110,6 @@ describe('review 주문 품목 스냅샷 백필 (real DB)', () => { }, }); } - await prisma.orderItemCustomFreeEdit.create({ - data: { - order_item_id: orderItem.id, - crop_image_url: 'https://img/second.png', - description_text: '둘째', - sort_order: 1, - }, - }); - await prisma.orderItemCustomFreeEdit.create({ - data: { - order_item_id: orderItem.id, - crop_image_url: 'https://img/first.png', - description_text: '첫째', - sort_order: 0, - }, - }); // 백필 대상 재현: 스냅샷이 비어 있는(=마이그레이션 전) 리뷰 const review = await createReview(prisma, { order_item_id: orderItem.id, @@ -100,7 +118,14 @@ describe('review 주문 품목 스냅샷 백필 (real DB)', () => { before_image_url: null, }); - await runBackfill(); + await runBackfill([ + { + orderItemId: orderItem.id, + url: 'https://img/second.png', + sortOrder: 1, + }, + { orderItemId: orderItem.id, url: 'https://img/first.png', sortOrder: 0 }, + ]); const row = await prisma.review.findUniqueOrThrow({ where: { id: review.id }, diff --git a/src/graphql/removed-schema-elements.spec.ts b/src/graphql/removed-schema-elements.spec.ts index 0329f573..e01a5398 100644 --- a/src/graphql/removed-schema-elements.spec.ts +++ b/src/graphql/removed-schema-elements.spec.ts @@ -29,6 +29,8 @@ const REMOVED_OUTPUT_FIELDS: Array<[type: string, field: string, pr: string]> = ['AdminProductOptionGroup', 'optionRequiresImage', '커스텀 방식'], ['SellerCustomTemplate', 'isActive', '커스텀 방식'], ['AdminProductCustomTemplate', 'isActive', '커스텀 방식'], + // 자유 편집은 크롭 이미지 대신 바탕 위 영역 좌표를 저장한다 + ['OrderItemFreeEdit', 'cropImageUrl', '커스텀 주문 스냅샷'], ]; const REMOVED_INPUT_FIELDS: Array<[input: string, field: string, pr: string]> = [ diff --git a/src/test/enum-sdl-sync.spec.ts b/src/test/enum-sdl-sync.spec.ts index 35a3d670..4e59d5e8 100644 --- a/src/test/enum-sdl-sync.spec.ts +++ b/src/test/enum-sdl-sync.spec.ts @@ -7,6 +7,7 @@ import { CANCEL_REFUND_RULES } from '@/features/order/policies/order-cancel.poli import { THREE_D_OPTION_CATEGORIES } from '@/features/product/constants/custom-3d-catalog.constants'; import { ConversationBodyFormat, + CustomImageKind, CustomMode, CustomTextAlign, NotificationEvent, @@ -91,6 +92,12 @@ const PAIRS: Array< 'src/features/product/product.types.graphql', 'CustomTextAlignType', ], + [ + 'CustomImageKind', + Object.values(CustomImageKind), + 'src/features/order/order.types.graphql', + 'CustomImageKindType', + ], [ 'ThreeDOptionCategory', [...THREE_D_OPTION_CATEGORIES], diff --git a/src/test/factories/order.factory.ts b/src/test/factories/order.factory.ts index 392d7702..75deb59d 100644 --- a/src/test/factories/order.factory.ts +++ b/src/test/factories/order.factory.ts @@ -1,12 +1,15 @@ import { DAY_MS } from '@/common/utils/kst-time'; import { buildRegionLabel } from '@/common/utils/region-label'; import type { + CustomImageKind, + CustomMode, Order, OrderItem, OrderStatus, Payment, PaymentSetting, PaymentStatus, + Prisma, PrismaClient, } from '@/generated/prisma/client'; import { activeWhere } from '@/prisma'; @@ -154,6 +157,9 @@ export interface OrderItemOverrides { sale_price_snapshot?: number | null; quantity?: number; item_subtotal_price?: number; + custom_mode_snapshot?: CustomMode; + custom_base_image_url_snapshot?: string | null; + custom_preview_image_url?: string | null; deleted_at?: Date; } @@ -210,7 +216,56 @@ export async function createOrderItem( sale_price_snapshot: overrides.sale_price_snapshot ?? null, quantity: overrides.quantity ?? 1, item_subtotal_price: overrides.item_subtotal_price ?? 10000, + custom_mode_snapshot: overrides.custom_mode_snapshot ?? 'NONE', + custom_base_image_url_snapshot: + overrides.custom_base_image_url_snapshot ?? null, + custom_preview_image_url: overrides.custom_preview_image_url ?? null, ...(overrides.deleted_at ? { deleted_at: overrides.deleted_at } : {}), }, }); } + +const THREE_D_RENDER_KINDS = [ + 'THREE_D_TOP', + 'THREE_D_FRONT', + 'THREE_D_BACK', + 'THREE_D_LEFT', + 'THREE_D_RIGHT', +] as const satisfies readonly CustomImageKind[]; + +export const MINIMAL_THREE_D_DESIGN = { + schemaVersion: 1, + basic: { + shape: 'heart', + size: 'mini', + design: null, + flavor: null, + sheetColor: 'white', + }, + top: [], + side: [], +}; + +/** 3D 품목 스냅샷: 디자인 JSON과 렌더 5장(`https://img/.png`). 정렬이 드러나게 종류 역순으로 넣는다. */ +export async function createThreeDOrderItemCustom( + prisma: PrismaClient, + orderItemId: bigint, + designJson: Prisma.InputJsonValue = MINIMAL_THREE_D_DESIGN, +): Promise { + await prisma.orderItemCustomDesign.create({ + data: { + order_item_id: orderItemId, + schema_version: 1, + design_json: designJson, + }, + }); + for (const kind of [...THREE_D_RENDER_KINDS].reverse()) { + await prisma.orderItemCustomImage.create({ + data: { + order_item_id: orderItemId, + kind, + image_url: `https://img/${kind}.png`, + }, + }); + } +} diff --git a/src/test/model-ownership.ts b/src/test/model-ownership.ts index 2e50fae6..8e8580d2 100644 --- a/src/test/model-ownership.ts +++ b/src/test/model-ownership.ts @@ -90,6 +90,8 @@ export const MODEL_OWNERSHIP: Readonly> = { OrderItemCustomText: order([]), OrderItemCustomFreeEdit: order([]), OrderItemCustomFreeEditAttachment: order([]), + OrderItemCustomDesign: order([]), + OrderItemCustomImage: order([]), Payment: order(), Refund: order(), DepositRecord: order(), diff --git a/src/test/seed-reset-scope.spec.ts b/src/test/seed-reset-scope.spec.ts index 3d566427..6c035f5b 100644 --- a/src/test/seed-reset-scope.spec.ts +++ b/src/test/seed-reset-scope.spec.ts @@ -151,6 +151,37 @@ describe('resetSeedScope (real DB)', () => { ).not.toBeNull(); }); + it('시드 주문과 시드 상품을 산 외부 주문에 커스텀 디자인·이미지가 붙어도 정리하고 다시 시드한다', async () => { + await seedThroughReviews(); + const seedProduct = await prisma.product.findFirstOrThrow({ + where: { store: { store_name: { startsWith: SEED_STORE_NAME_PREFIX } } }, + }); + const { item } = await outsiderOrder(seedProduct.id); + await prisma.orderItemCustomDesign.create({ + data: { order_item_id: item.id, schema_version: 1, design_json: {} }, + }); + await prisma.orderItemCustomImage.create({ + data: { + order_item_id: item.id, + kind: 'THREE_D_TOP', + image_url: 'https://img/top.png', + }, + }); + const counts = () => + Promise.all([ + prisma.orderItemCustomDesign.count(), + prisma.orderItemCustomImage.count(), + ]); + // 시드도 슬롯형 합성 이미지를 2장 넣는다 + expect(await counts()).toEqual([1, 3]); + + await resetSeedScope(prisma); + expect(await counts()).toEqual([0, 0]); + + await seedThroughReviews(); + expect(await counts()).toEqual([0, 2]); + }); + it('시드 밖 계정이 시드 밖 매장에 넣은 주문은 남긴다', async () => { await seedThroughReviews(); const { order, item } = await outsiderOrder(); From fb80fbf1ee54d944b2de9918679ae4785d19bcb0 Mon Sep 17 00:00:00 2001 From: chanwoo7 Date: Thu, 19 Nov 2026 05:16:40 +0900 Subject: [PATCH 32/54] =?UTF-8?q?fix:=20=EC=8B=9C=EB=93=9C=20=EB=A6=AC?= =?UTF-8?q?=EB=B7=B0=EA=B0=80=20=ED=99=88=20=EC=A0=9C=EC=9E=91=20=ED=9B=84?= =?UTF-8?q?=EA=B8=B0=20=EC=87=BC=EC=BC=80=EC=9D=B4=EC=8A=A4=20=ED=9B=84?= =?UTF-8?q?=EB=B3=B4=EA=B0=80=20=EB=90=98=EA=B2=8C=20Before=20=EC=8A=A4?= =?UTF-8?q?=EB=83=85=EC=83=B7=20=EC=B1=84=EC=9B=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 쇼케이스는 리뷰의 작성 시점 스냅샷 before_image_url만 읽는데 시드 리뷰가 이 열을 채우지 않아, o4 품목에 커스텀 대표 이미지를 둬도 로컬에서 쇼케이스 후보에서 빠졌다. 변경점 - SeededOrders에 o4 대표 이미지 URL을 싣고 seedReviews가 before_image_url로 복사한다 테스트 - seed-reset-scope spec 통과 - 시드 → listShowcaseReviewIdsByLikes 임시 spec으로 시드 리뷰가 후보 1건으로 잡히고, 시드 변경을 되돌리면 0건인 것을 확인했다(임시 spec은 커밋하지 않음) --- prisma/seed/orders.ts | 2 ++ prisma/seed/reviews.ts | 3 ++- 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/prisma/seed/orders.ts b/prisma/seed/orders.ts index 98d16bf3..7fae4c0f 100644 --- a/prisma/seed/orders.ts +++ b/prisma/seed/orders.ts @@ -59,6 +59,7 @@ export interface SeededOrders { o3Made: bigint; o4PickedUpReviewed: bigint; o4OrderItemId: bigint; + o4PreviewImageUrl: string; o5PickedUpReviewable: bigint; o6Canceled: bigint; o7PendingPayment: bigint; @@ -591,6 +592,7 @@ export async function seedOrders( o3Made: o3.id, o4PickedUpReviewed: o4.id, o4OrderItemId: o4Item.id, + o4PreviewImageUrl: o4Preview, o5PickedUpReviewable: o5.id, o6Canceled: o6.id, o7PendingPayment: o7.id, diff --git a/prisma/seed/reviews.ts b/prisma/seed/reviews.ts index 97fdbc1d..436fe6c6 100644 --- a/prisma/seed/reviews.ts +++ b/prisma/seed/reviews.ts @@ -26,9 +26,10 @@ export async function seedReviews( account_id: user1.id, store_id: storeA.id, product_id: p1.id, - // 작성 시점 주문 품목 스냅샷(07b) — 시드 주문 품목의 상품명·옵션과 같게 + // 작성 시점 주문 품목 스냅샷 — 시드 주문 품목의 상품명·옵션·대표 이미지와 같게 product_name_snapshot: p1.name, store_name_snapshot: storeA.store_name, + before_image_url: ctx.orders.o4PreviewImageUrl, rating: new Prisma.Decimal('4.5'), content: '레터링이 정말 예쁘게 나왔어요. 케이크 맛도 좋고 다음에 또 주문할게요!', From 706d7fb8cc16a6ce405310ef8cf0ca81b4b22033 Mon Sep 17 00:00:00 2001 From: chanwoo7 Date: Thu, 19 Nov 2026 04:52:44 +0900 Subject: [PATCH 33/54] =?UTF-8?q?feat:=20=EC=BB=A4=EC=8A=A4=ED=85=80=20?= =?UTF-8?q?=EC=A3=BC=EB=AC=B8=20=EC=9D=B4=EB=AF=B8=EC=A7=80=20=EC=84=A0?= =?UTF-8?q?=EC=97=85=EB=A1=9C=EB=93=9C=EC=99=80=20=EB=AF=B8=EC=82=AC?= =?UTF-8?q?=EC=9A=A9=20=EC=97=85=EB=A1=9C=EB=93=9C=20=EC=A0=95=EB=A6=AC=20?= =?UTF-8?q?=ED=81=AC=EB=A1=A0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 구매자가 커스텀 이미지(3D 렌더·슬롯형 합성·자유 편집 참고 사진)를 주문 전에 presign으로 올리고 주문 생성 때 URL을 내도록 발급 API와 발급 기록을 둔다. 주문에 쓰이지 않은 업로드는 worker가 하루 뒤 S3에서 지우고, 주문된 파일은 보관한다. 주문 생성의 업로드 연결(소유·용도·상태 검사 후 ATTACHED)은 다음 PR이 붙인다. 변경점 - 스키마·마이그레이션(order_custom_upload): OrderCustomUpload(account_id, purpose RENDER·COMPOSITE·REFERENCE, object_key unique, content_type, content_length, status PENDING·ATTACHED·PURGING, attached_at, purge_started_at), (status, created_at)·(status, purge_started_at)·account_id 인덱스. 새 표라 백필 없음 - 업로드 용도: TS UploadPurpose·UPLOAD_POLICIES에 ORDER_CUSTOM_RENDER·COMPOSITE·REFERENCE(order-custom/{renders,composites,references}, 10MB, JPEG·PNG·WebP). 판매자·관리자 SDL UploadPurpose에는 섞지 않았다 - createOrderCustomUploadUrl(purpose: OrderCustomUploadPurpose!, contentType, contentLength): UploadUrl!. 구매자 계정만(USER_ONLY), 발급 뒤 PENDING으로 기록한다 - S3Service.deleteObjects(keys): 요청당 1000개, 키별 오류와 요청 실패를 실패 목록으로 돌려주고 던지지 않는다 - 정리 크론(매시 20분, 역할 게이트, 겹친 틱 건너뜀): PURGING ∧ 1시간 경과, PENDING ∧ 24시간 경과를 상태별 인덱스 범위로 LIMIT 500 FOR UPDATE SKIP LOCKED로 잡아 PURGING 표시·커밋 → S3 삭제 → 지워진 행만 하드 삭제. 실패한 키는 PURGING으로 남기고 error 경보(key order-custom-upload:purge), 그 틱에서는 더 잡지 않는다. 한 틱 최대 20묶음 - IAM: terraform/aws.tf 앱 정책에 s3:DeleteObject(order-custom/*) statement. apply는 사람 키로 한다 - resetSeedScope: 시드 사용자의 업로드 기록을 지운다. model-ownership: OrderCustomUpload는 order 테스트 - 정리 크론 7건(real DB, S3·경보 stub): 대상 경계(PENDING 24h·24h−1ms, PURGING 1h·1h−1ms, ATTACHED 72h 미선택), 부분 실패 PURGING 유지·경보·1시간 뒤 재시도, 묶음 이어 잡기·실패 뒤 중단, 주문 tx가 잡은 행 건너뜀, api 역할 미실행, 겹친 틱, DB 실패 경보 - S3 deleteObjects 5건(조용한 모드·키별 오류·요청 실패·1000개 분할·빈 목록), 용도 정책 3종 × 형식·크기 - 발급: 용도 3종 키·기록, 형식·크기·0 거절과 미기록, 판매자 USER_ONLY, 리졸버 1건 - resetSeedScope 업로드 기록 1건 --- .../migration.sql | 22 ++ prisma/schema.prisma | 35 +++ prisma/seed/idempotent.ts | 5 + src/features/order/order-checkout.graphql | 25 ++ src/features/order/order.module.ts | 5 + .../order-custom-upload.repository.ts | 86 ++++++ .../order-checkout-mutation.resolver.spec.ts | 30 +++ .../order-checkout-mutation.resolver.ts | 15 ++ .../services/order-checkout.service.spec.ts | 85 ++++++ .../order/services/order-checkout.service.ts | 48 +++- ...er-custom-upload-cleanup.scheduler.spec.ts | 253 ++++++++++++++++++ .../order-custom-upload-cleanup.scheduler.ts | 90 +++++++ .../storage/constants/storage.constants.ts | 16 ++ .../storage/s3.service.delete-objects.spec.ts | 113 ++++++++ src/global/storage/s3.service.spec.ts | 32 +++ src/global/storage/s3.service.ts | 47 ++++ src/global/storage/types/storage.types.ts | 5 +- src/test/factories/order.factory.ts | 34 +++ src/test/model-ownership.ts | 1 + src/test/seed-reset-scope.spec.ts | 21 ++ terraform/aws.tf | 7 + 21 files changed, 973 insertions(+), 2 deletions(-) create mode 100644 prisma/migrations/20261118190324_order_custom_upload/migration.sql create mode 100644 src/features/order/repositories/order-custom-upload.repository.ts create mode 100644 src/features/order/services/order-custom-upload-cleanup.scheduler.spec.ts create mode 100644 src/features/order/services/order-custom-upload-cleanup.scheduler.ts create mode 100644 src/global/storage/s3.service.delete-objects.spec.ts diff --git a/prisma/migrations/20261118190324_order_custom_upload/migration.sql b/prisma/migrations/20261118190324_order_custom_upload/migration.sql new file mode 100644 index 00000000..d85a4e12 --- /dev/null +++ b/prisma/migrations/20261118190324_order_custom_upload/migration.sql @@ -0,0 +1,22 @@ +-- 구매자 커스텀 이미지 presign 발급 기록. 정리 크론이 주문에 쓰이지 않은 객체를 지운다(기존 데이터 없음). +-- CreateTable +CREATE TABLE `order_custom_upload` ( + `id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT, + `account_id` BIGINT UNSIGNED NOT NULL, + `purpose` ENUM('RENDER', 'COMPOSITE', 'REFERENCE') NOT NULL, + `object_key` VARCHAR(512) NOT NULL, + `content_type` VARCHAR(50) NOT NULL, + `content_length` INTEGER UNSIGNED NOT NULL, + `status` ENUM('PENDING', 'ATTACHED', 'PURGING') NOT NULL DEFAULT 'PENDING', + `attached_at` DATETIME(3) NULL, + `purge_started_at` DATETIME(3) NULL, + `created_at` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3), + `updated_at` DATETIME(3) NOT NULL, + + UNIQUE INDEX `uk_order_custom_upload_key`(`object_key`), + INDEX `idx_order_custom_upload_status_created`(`status`, `created_at`), + INDEX `idx_order_custom_upload_status_purge`(`status`, `purge_started_at`), + INDEX `idx_order_custom_upload_account`(`account_id`), + PRIMARY KEY (`id`) +) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; + diff --git a/prisma/schema.prisma b/prisma/schema.prisma index 85b33b30..27ee7339 100644 --- a/prisma/schema.prisma +++ b/prisma/schema.prisma @@ -68,6 +68,20 @@ enum CustomImageKind { SLOT_COMPOSITE } +// 구매자 커스텀 이미지 선업로드 용도(3D 렌더·슬롯형 합성·자유 편집 참고 사진) +enum OrderCustomUploadPurpose { + RENDER + COMPOSITE + REFERENCE +} + +// 발급(PENDING) → 주문에 쓰임(ATTACHED, 보관) 또는 정리 중(PURGING, 주문에 붙일 수 없다) +enum OrderCustomUploadStatus { + PENDING + ATTACHED + PURGING +} + enum OrderStatus { SUBMITTED CONFIRMED @@ -1188,6 +1202,27 @@ model OrderItemCustomImage { @@map("order_item_custom_image") } +// 커스텀 이미지 presign 발급 기록. 주문에 쓰이지 않은 객체는 정리 크론이 S3에서 지우고 행도 지운다(주문된 파일은 보관) +model OrderCustomUpload { + id BigInt @id @default(autoincrement()) @db.UnsignedBigInt + account_id BigInt @db.UnsignedBigInt + purpose OrderCustomUploadPurpose + object_key String @unique(map: "uk_order_custom_upload_key") @db.VarChar(512) + content_type String @db.VarChar(50) + content_length Int @db.UnsignedInt + status OrderCustomUploadStatus @default(PENDING) + attached_at DateTime? @db.DateTime(3) + purge_started_at DateTime? @db.DateTime(3) + + created_at DateTime @default(now()) @db.DateTime(3) + updated_at DateTime @updatedAt @db.DateTime(3) + + @@index([status, created_at], map: "idx_order_custom_upload_status_created") + @@index([status, purge_started_at], map: "idx_order_custom_upload_status_purge") + @@index([account_id], map: "idx_order_custom_upload_account") + @@map("order_custom_upload") +} + // 주문 1건의 결제. 계좌이체는 PENDING으로 만들고 입금 확인(관리자, 후속 연동은 AUTO) 때 CONFIRMED가 된다. model Payment { id BigInt @id @default(autoincrement()) @db.UnsignedBigInt diff --git a/prisma/seed/idempotent.ts b/prisma/seed/idempotent.ts index ac9f8973..1761bba3 100644 --- a/prisma/seed/idempotent.ts +++ b/prisma/seed/idempotent.ts @@ -185,6 +185,11 @@ export async function resetSeedScope(prisma: PrismaClient): Promise { }); await prisma.review.deleteMany({ where: { account_id: { in: userIds } } }); + // 커스텀 이미지 선업로드 기록(계정 FK는 없지만 시드 사용자 것은 함께 지운다) + await prisma.orderCustomUpload.deleteMany({ + where: { account_id: { in: userIds } }, + }); + // 찜 await prisma.wishlistItem.deleteMany({ where: { account_id: { in: userIds } }, diff --git a/src/features/order/order-checkout.graphql b/src/features/order/order-checkout.graphql index 6e799e08..7ddba327 100644 --- a/src/features/order/order-checkout.graphql +++ b/src/features/order/order-checkout.graphql @@ -7,6 +7,31 @@ extend type Mutation { CONCURRENT_REQUEST(CONFLICT)다. 로그인 필수. """ createOrder(input: CreateOrderInput!): CreateOrderOutput! + """ + 커스텀 이미지 업로드용 Presigned URL 발급(구매자). uploadUrl로 PUT한 뒤 publicUrl을 주문 생성의 커스텀 입력에 넣는다. + JPEG·PNG·WebP, 장당 10MB 이하(아니면 INVALID_CONTENT_TYPE·FILE_TOO_LARGE). 주문에 쓰이지 않은 파일은 발급 하루 뒤 지워진다. + 구매자 계정만 쓸 수 있다(아니면 USER_ONLY). 로그인 필수. + """ + createOrderCustomUploadUrl( + """이미지 용도. 주문 생성 때 이 용도의 자리에만 쓸 수 있다.""" + purpose: OrderCustomUploadPurpose! + """파일 MIME 타입(image/jpeg·image/png·image/webp).""" + contentType: String! + """파일 크기(바이트, 1 이상 10MB 이하).""" + contentLength: Int! + ): UploadUrl! +} + +""" +구매자 커스텀 이미지 업로드 용도. 값은 늘어날 수 있으니 모르는 값을 받아도 화면이 죽지 않게 처리한다. +""" +enum OrderCustomUploadPurpose { + """3D 렌더 이미지(윗면·옆면 앞·뒤·좌·우).""" + RENDER + """슬롯형 합성 이미지(바탕 + 문구, 구매자가 본 그대로).""" + COMPOSITE + """자유 편집 참고 사진.""" + REFERENCE } """주문 생성 입력. 커스텀 필드는 커스텀 스펙 확정 후 optional로 확장 예정.""" diff --git a/src/features/order/order.module.ts b/src/features/order/order.module.ts index db97fa0e..b831613f 100644 --- a/src/features/order/order.module.ts +++ b/src/features/order/order.module.ts @@ -6,6 +6,7 @@ import { AuthModule } from '@/features/auth'; import { OrderCancelPolicy } from '@/features/order/policies/order-cancel.policy'; import { OrderStatusTransitionPolicy } from '@/features/order/policies/order-status-transition.policy'; import { OrderBookedRepository } from '@/features/order/repositories/order-booked.repository'; +import { OrderCustomUploadRepository } from '@/features/order/repositories/order-custom-upload.repository'; import { OrderStoreDailyLimitRepository } from '@/features/order/repositories/order-store-daily-limit.repository'; import { OrderTransitionRepository } from '@/features/order/repositories/order-transition.repository'; import { OrderRepository } from '@/features/order/repositories/order.repository'; @@ -30,6 +31,7 @@ import { OrderSubscriptionResolver } from '@/features/order/resolvers/order-subs import { OrderAdminAlertConsumer } from '@/features/order/services/order-admin-alert.consumer'; import { AdminOrderService } from '@/features/order/services/order-admin.service'; import { OrderCheckoutService } from '@/features/order/services/order-checkout.service'; +import { OrderCustomUploadCleanupScheduler } from '@/features/order/services/order-custom-upload-cleanup.scheduler'; import { AdminDepositService } from '@/features/order/services/order-deposit-admin.service'; import { OrderEventsService } from '@/features/order/services/order-events.service'; import { UserOrderService } from '@/features/order/services/order-my.service'; @@ -68,6 +70,9 @@ import { StoreModule } from '@/features/store'; OrderSubscriptionResolver, OrderCheckoutService, OrderCheckoutMutationResolver, + // 커스텀 이미지 선업로드 기록과 미사용분 정리(worker 크론) + OrderCustomUploadRepository, + OrderCustomUploadCleanupScheduler, // 판매자 주문 관리(목록·상세·상태 변경·거절·취소) — 주문 도메인이 소유한다 SellerOrderService, SellerOrderQueryResolver, diff --git a/src/features/order/repositories/order-custom-upload.repository.ts b/src/features/order/repositories/order-custom-upload.repository.ts new file mode 100644 index 00000000..a6570926 --- /dev/null +++ b/src/features/order/repositories/order-custom-upload.repository.ts @@ -0,0 +1,86 @@ +import { Injectable } from '@nestjs/common'; + +import { + OrderCustomUploadStatus, + type OrderCustomUploadPurpose, +} from '@/generated/prisma/client'; +import { PrismaService } from '@/prisma'; + +export interface PurgeClaim { + id: bigint; + object_key: string; +} + +@Injectable() +export class OrderCustomUploadRepository { + constructor(private readonly prisma: PrismaService) {} + + async create(args: { + accountId: bigint; + purpose: OrderCustomUploadPurpose; + objectKey: string; + contentType: string; + contentLength: number; + }): Promise { + await this.prisma.orderCustomUpload.create({ + data: { + account_id: args.accountId, + purpose: args.purpose, + object_key: args.objectKey, + content_type: args.contentType, + content_length: args.contentLength, + }, + }); + } + + /** + * 정리 대상(오래된 PENDING, 지우다 만 PURGING)을 PURGING으로 표시하고 커밋한다. 표시 뒤에는 주문이 이 업로드를 + * 붙이지 못하므로 S3에서 지워도 된다. 주문 tx가 잡고 있는 행은 SKIP LOCKED로 건너뛴다(다음 정리에서 다시 본다). + */ + async claimForPurge(args: { + now: Date; + pendingCreatedBefore: Date; + purgingStartedBefore: Date; + limit: number; + }): Promise { + return this.prisma.$transaction(async (tx) => { + // 상태별 인덱스 범위만 잠그도록 두 번 나눠 읽는다 + const retries = await tx.$queryRaw` + SELECT id, object_key FROM order_custom_upload + WHERE status = ${OrderCustomUploadStatus.PURGING} + AND purge_started_at <= ${args.purgingStartedBefore} + ORDER BY purge_started_at, id + LIMIT ${args.limit} + FOR UPDATE SKIP LOCKED`; + const fresh = + retries.length < args.limit + ? await tx.$queryRaw` + SELECT id, object_key FROM order_custom_upload + WHERE status = ${OrderCustomUploadStatus.PENDING} + AND created_at <= ${args.pendingCreatedBefore} + ORDER BY created_at, id + LIMIT ${args.limit - retries.length} + FOR UPDATE SKIP LOCKED` + : []; + const claimed = [...retries, ...fresh]; + if (claimed.length > 0) { + await tx.orderCustomUpload.updateMany({ + where: { id: { in: claimed.map((row) => row.id) } }, + data: { + status: OrderCustomUploadStatus.PURGING, + purge_started_at: args.now, + }, + }); + } + return claimed; + }); + } + + /** S3에서 지운 업로드 기록을 지운다. 정리 중인 행만 대상이다. */ + async deletePurged(ids: bigint[]): Promise { + if (ids.length === 0) return; + await this.prisma.orderCustomUpload.deleteMany({ + where: { id: { in: ids }, status: OrderCustomUploadStatus.PURGING }, + }); + } +} diff --git a/src/features/order/resolvers/order-checkout-mutation.resolver.spec.ts b/src/features/order/resolvers/order-checkout-mutation.resolver.spec.ts index 4645d706..091deeec 100644 --- a/src/features/order/resolvers/order-checkout-mutation.resolver.spec.ts +++ b/src/features/order/resolvers/order-checkout-mutation.resolver.spec.ts @@ -2,6 +2,7 @@ import { ClockService } from '@/common/providers/clock.service'; import { RandomService } from '@/common/providers/random.service'; import { AUDIT_LOG_REPOSITORY } from '@/features/audit-log'; import { AuditLogRepository } from '@/features/audit-log/repositories/audit-log.repository'; +import { OrderCustomUploadRepository } from '@/features/order/repositories/order-custom-upload.repository'; import { OrderRepository } from '@/features/order/repositories/order.repository'; import { PaymentSettingRepository } from '@/features/order/repositories/payment-setting.repository'; import { OrderCheckoutMutationResolver } from '@/features/order/resolvers/order-checkout-mutation.resolver'; @@ -23,6 +24,11 @@ import { } from '@/test/factories'; import { createTestingModuleWithRealDb } from '@/test/modules/testing-module.builder'; import { outboxPublisherProviders } from '@/test/outbox'; +import { s3TestProviders } from '@/test/storage/s3-test.helper'; + +jest.mock('@aws-sdk/s3-request-presigner', () => ({ + getSignedUrl: jest.fn().mockResolvedValue('https://mock-presigned-url.com'), +})); // 2026-09-16(수) 16:00 KST 고정 const NOW = new Date('2026-09-16T07:00:00.000Z'); @@ -39,6 +45,8 @@ describe('OrderCheckout Mutation Resolver (real DB)', () => { OrderCheckoutMutationResolver, OrderCheckoutService, OrderRepository, + OrderCustomUploadRepository, + ...s3TestProviders(), PaymentSettingRepository, ProductRepository, { provide: AUDIT_LOG_REPOSITORY, useClass: AuditLogRepository }, @@ -114,4 +122,26 @@ describe('OrderCheckout Mutation Resolver (real DB)', () => { expect(saved.account_id).toBe(account.id); expect(saved.request_note).toBe('초는 빼 주세요'); }); + + it('createOrderCustomUploadUrl: 구매자에게 용도별 업로드 URL을 발급하고 기록한다', async () => { + const account = await createAccount(prisma, { account_type: 'USER' }); + await createUserProfile(prisma, { account_id: account.id }); + const user = { accountId: account.id.toString() } as JwtUser; + + const result = await resolver.createOrderCustomUploadUrl( + user, + 'COMPOSITE', + 'image/png', + 1024, + ); + + expect(result.key).toMatch( + new RegExp(`^order-custom/composites/${account.id}/`), + ); + await expect( + prisma.orderCustomUpload.findUniqueOrThrow({ + where: { object_key: result.key }, + }), + ).resolves.toMatchObject({ account_id: account.id, purpose: 'COMPOSITE' }); + }); }); diff --git a/src/features/order/resolvers/order-checkout-mutation.resolver.ts b/src/features/order/resolvers/order-checkout-mutation.resolver.ts index 55328011..3541a9d5 100644 --- a/src/features/order/resolvers/order-checkout-mutation.resolver.ts +++ b/src/features/order/resolvers/order-checkout-mutation.resolver.ts @@ -4,12 +4,14 @@ import { Args, Mutation, Resolver } from '@nestjs/graphql'; import { CreateOrderInput } from '@/features/order/dto/inputs/create-order.input'; import { OrderCheckoutService } from '@/features/order/services/order-checkout.service'; import type { CreateOrderOutput } from '@/features/order/types/create-order-output.type'; +import type { OrderCustomUploadPurpose } from '@/generated/prisma/client'; import { CurrentUser, JwtAuthGuard, parseAccountId, type JwtUser, } from '@/global/auth'; +import type { CreateUploadUrlOutput } from '@/global/storage/types/storage.types'; @Resolver('Mutation') @UseGuards(JwtAuthGuard) @@ -23,4 +25,17 @@ export class OrderCheckoutMutationResolver { ): Promise { return this.checkoutService.createOrder(parseAccountId(user), input); } + + @Mutation('createOrderCustomUploadUrl') + createOrderCustomUploadUrl( + @CurrentUser() user: JwtUser, + @Args('purpose') purpose: OrderCustomUploadPurpose, + @Args('contentType') contentType: string, + @Args('contentLength') contentLength: number, + ): Promise { + return this.checkoutService.createOrderCustomUploadUrl( + parseAccountId(user), + { purpose, contentType, contentLength }, + ); + } } diff --git a/src/features/order/services/order-checkout.service.spec.ts b/src/features/order/services/order-checkout.service.spec.ts index 36b42a9a..94bd0a2e 100644 --- a/src/features/order/services/order-checkout.service.spec.ts +++ b/src/features/order/services/order-checkout.service.spec.ts @@ -10,6 +10,7 @@ import { parseOrderPaymentPendingPayload, } from '@/features/order/events/order-payment-pending.event'; import { ORDER_SUBMITTED } from '@/features/order/events/order-submitted.event'; +import { OrderCustomUploadRepository } from '@/features/order/repositories/order-custom-upload.repository'; import { pendingPaymentLockName } from '@/features/order/repositories/order-pending-payment-lock.helper'; import { OrderRepository } from '@/features/order/repositories/order.repository'; import { PaymentSettingRepository } from '@/features/order/repositories/payment-setting.repository'; @@ -42,6 +43,11 @@ import { import { createTestingModuleWithRealDb } from '@/test/modules/testing-module.builder'; import { outboxPublisherProviders } from '@/test/outbox'; import { collectTopic } from '@/test/pubsub'; +import { s3TestProviders, TEST_S3_CONFIG } from '@/test/storage/s3-test.helper'; + +jest.mock('@aws-sdk/s3-request-presigner', () => ({ + getSignedUrl: jest.fn().mockResolvedValue('https://mock-presigned-url.com'), +})); // 2026-09-16(수) 16:00 KST 고정 const NOW = new Date('2026-09-16T07:00:00.000Z'); @@ -62,6 +68,8 @@ describe('OrderCheckoutService (real DB)', () => { providers: [ OrderCheckoutService, OrderRepository, + OrderCustomUploadRepository, + ...s3TestProviders(), PaymentSettingRepository, ProductRepository, { provide: AUDIT_LOG_REPOSITORY, useClass: AuditLogRepository }, @@ -206,6 +214,83 @@ describe('OrderCheckoutService (real DB)', () => { }; } + describe('createOrderCustomUploadUrl', () => { + async function buyer(): Promise { + const account = await createAccount(prisma, { account_type: 'USER' }); + await createUserProfile(prisma, { account_id: account.id }); + return account; + } + + it.each([ + ['RENDER', 'order-custom/renders'], + ['COMPOSITE', 'order-custom/composites'], + ['REFERENCE', 'order-custom/references'], + ] as const)( + '%s 용도는 %s/{accountId}/ 아래로 발급하고 PENDING으로 기록한다', + async (purpose, prefix) => { + const account = await buyer(); + + const result = await service.createOrderCustomUploadUrl(account.id, { + purpose, + contentType: 'image/webp', + contentLength: 10 * 1024 * 1024, + }); + + expect(result.key).toMatch( + new RegExp( + `^${prefix}/${account.id}/\\d{4}-\\d{2}-\\d{2}/[a-f0-9-]+\\.webp$`, + ), + ); + expect(result.publicUrl).toBe( + `https://${TEST_S3_CONFIG.bucket}.s3.${TEST_S3_CONFIG.region}.amazonaws.com/${result.key}`, + ); + expect(await prisma.orderCustomUpload.findMany()).toEqual([ + expect.objectContaining({ + account_id: account.id, + purpose, + object_key: result.key, + content_type: 'image/webp', + content_length: 10 * 1024 * 1024, + status: 'PENDING', + attached_at: null, + purge_started_at: null, + }), + ]); + }, + ); + + it.each([ + ['형식이 이미지가 아님', 'video/mp4', 1024, 'INVALID_CONTENT_TYPE'], + ['10MB 초과', 'image/png', 10 * 1024 * 1024 + 1, 'FILE_TOO_LARGE'], + ['크기 0', 'image/png', 0, 'INVALID_CONTENT_LENGTH'], + ] as const)( + '%s이면 %s이고 기록하지 않는다', + async (_case, contentType, contentLength, code) => { + const account = await buyer(); + await expect( + service.createOrderCustomUploadUrl(account.id, { + purpose: 'RENDER', + contentType, + contentLength, + }), + ).rejects.toThrowDomain(code); + expect(await prisma.orderCustomUpload.count()).toBe(0); + }, + ); + + it('구매자 계정이 아니면 USER_ONLY이고 기록하지 않는다', async () => { + const seller = await createAccount(prisma, { account_type: 'SELLER' }); + await expect( + service.createOrderCustomUploadUrl(seller.id, { + purpose: 'RENDER', + contentType: 'image/png', + contentLength: 1024, + }), + ).rejects.toThrowDomain('USER_ONLY'); + expect(await prisma.orderCustomUpload.count()).toBe(0); + }); + }); + describe('createOrder', () => { it('주문을 생성하고 가격·옵션·상태 히스토리를 스냅샷한다', async () => { const store = await makeOpenStore(); diff --git a/src/features/order/services/order-checkout.service.ts b/src/features/order/services/order-checkout.service.ts index 368ba7a8..45fb0d37 100644 --- a/src/features/order/services/order-checkout.service.ts +++ b/src/features/order/services/order-checkout.service.ts @@ -10,6 +10,7 @@ import { buildRegionLabel } from '@/common/utils/region-label'; import { codePointLength } from '@/common/utils/text-cleaner'; import { evaluateActiveUserAccount } from '@/features/auth'; import type { CreateOrderInput } from '@/features/order/dto/inputs/create-order.input'; +import { OrderCustomUploadRepository } from '@/features/order/repositories/order-custom-upload.repository'; import { OrderRepository, type CreatedOrderRow, @@ -21,7 +22,15 @@ import { toOrderPaymentOutput } from '@/features/order/services/order-payment-ma import type { CreateOrderOutput } from '@/features/order/types/create-order-output.type'; import { ProductRepository, type ProductDetailRow } from '@/features/product'; import { StorePickupScheduleService } from '@/features/store'; -import { Prisma } from '@/generated/prisma/client'; +import { + Prisma, + type OrderCustomUploadPurpose, +} from '@/generated/prisma/client'; +import { S3Service } from '@/global/storage/s3.service'; +import type { + CreateUploadUrlOutput, + UploadPurpose, +} from '@/global/storage/types/storage.types'; // 0/O·1/I 등 혼동 문자를 뺀 대문자 영숫자. 주문번호 무작위부에 사용. const ORDER_NUMBER_ALPHABET = 'ABCDEFGHJKMNPQRSTUVWXYZ23456789'; @@ -38,6 +47,12 @@ const PAYMENT_WINDOW_MS = 60 * 60_000; /** 은행 입금자명과 대조하는 값이라 자르지 않고 입력을 요구한다. */ const MAX_DEPOSITOR_NAME_LENGTH = 20; +const CUSTOM_UPLOAD_PURPOSES = { + RENDER: 'ORDER_CUSTOM_RENDER', + COMPOSITE: 'ORDER_CUSTOM_COMPOSITE', + REFERENCE: 'ORDER_CUSTOM_REFERENCE', +} as const satisfies Record; + interface ResolvedOptionSelection { optionGroupId: bigint; optionItemId: bigint; @@ -55,8 +70,39 @@ export class OrderCheckoutService { private readonly clock: ClockService, private readonly random: RandomService, private readonly paymentSettings: PaymentSettingRepository, + private readonly customUploads: OrderCustomUploadRepository, + private readonly s3: S3Service, ) {} + /** + * 커스텀 이미지(3D 렌더·슬롯형 합성·참고 사진) 선업로드 URL. 발급을 기록해 두고, 주문에 쓰이지 않으면 + * 정리 크론이 하루 뒤 지운다. 형식·크기는 S3 정책이 검증한다. + */ + async createOrderCustomUploadUrl( + accountId: bigint, + input: { + purpose: OrderCustomUploadPurpose; + contentType: string; + contentLength: number; + }, + ): Promise { + await this.requireActiveBuyer(accountId); + const issued = await this.s3.createUploadUrl({ + accountId, + purpose: CUSTOM_UPLOAD_PURPOSES[input.purpose], + contentType: input.contentType, + contentLength: input.contentLength, + }); + await this.customUploads.create({ + accountId, + purpose: input.purpose, + objectKey: issued.key, + contentType: input.contentType, + contentLength: input.contentLength, + }); + return issued; + } + /** * 옵션 그룹 규칙·픽업 일시를 서버가 재검증하고 가격을 스냅샷한 뒤 입금 대기 주문을 만든다. * 판매자에게는 입금 확인 뒤에 보이므로 여기서는 판매자 구독을 발행하지 않는다. diff --git a/src/features/order/services/order-custom-upload-cleanup.scheduler.spec.ts b/src/features/order/services/order-custom-upload-cleanup.scheduler.spec.ts new file mode 100644 index 00000000..bf6efcee --- /dev/null +++ b/src/features/order/services/order-custom-upload-cleanup.scheduler.spec.ts @@ -0,0 +1,253 @@ +import { Logger } from '@nestjs/common'; + +import { ClockService } from '@/common/providers/clock.service'; +import { HOUR_MS } from '@/common/utils/kst-time'; +import { OrderCustomUploadRepository } from '@/features/order/repositories/order-custom-upload.repository'; +import { + OrderCustomUploadCleanupScheduler, + PURGE_BATCH_LIMIT, +} from '@/features/order/services/order-custom-upload-cleanup.scheduler'; +import type { + OrderCustomUploadStatus, + PrismaClient, +} from '@/generated/prisma/client'; +import { AlertService } from '@/global/alerting'; +import { + S3Service, + type DeleteObjectsFailure, +} from '@/global/storage/s3.service'; +import { disconnectTestPrismaClient } from '@/test/db/prisma-test-client'; +import { closeTruncateConnection, truncateAll } from '@/test/db/truncate'; +import { createAccount, createOrderCustomUpload } from '@/test/factories'; +import { createTestingModuleWithRealDb } from '@/test/modules/testing-module.builder'; + +const NOW = new Date('2026-11-19T11:20:00.000Z'); +const ago = (ms: number) => new Date(NOW.getTime() - ms); + +// 정리 대상 판정(오래된 PENDING·멈춘 PURGING, ATTACHED는 제외)·S3 삭제·기록 삭제·실패 시 PURGING 유지와 경보. S3는 외부라 stub이다. +describe('OrderCustomUploadCleanupScheduler (real DB)', () => { + let scheduler: OrderCustomUploadCleanupScheduler; + let repository: OrderCustomUploadRepository; + let prisma: PrismaClient; + let accountId: bigint; + let now = NOW; + const deleteObjects = jest.fn< + Promise, + [readonly string[]] + >(); + const alerts = { notify: jest.fn().mockResolvedValue('sent') }; + const savedRole = process.env.APP_ROLE; + + beforeAll(async () => { + const { module, prisma: p } = await createTestingModuleWithRealDb({ + providers: [ + OrderCustomUploadCleanupScheduler, + OrderCustomUploadRepository, + { provide: ClockService, useValue: { now: () => now } }, + { provide: S3Service, useValue: { deleteObjects } }, + { provide: AlertService, useValue: alerts }, + ], + }); + scheduler = module.get(OrderCustomUploadCleanupScheduler); + repository = module.get(OrderCustomUploadRepository); + prisma = p; + }); + afterAll(async () => { + if (savedRole === undefined) delete process.env.APP_ROLE; + else process.env.APP_ROLE = savedRole; + await closeTruncateConnection(); + await disconnectTestPrismaClient(); + }); + beforeEach(async () => { + await truncateAll(); + process.env.APP_ROLE = 'worker'; + now = NOW; + deleteObjects.mockReset(); + deleteObjects.mockResolvedValue([]); + alerts.notify.mockClear(); + jest.spyOn(Logger.prototype, 'error').mockImplementation(() => undefined); + accountId = (await createAccount(prisma, { account_type: 'USER' })).id; + }); + afterEach(() => jest.restoreAllMocks()); + + async function upload( + key: string, + status: OrderCustomUploadStatus, + at: { createdAgo?: number; purgeStartedAgo?: number } = {}, + ) { + return createOrderCustomUpload(prisma, { + account_id: accountId, + object_key: key, + status, + created_at: ago(at.createdAgo ?? 0), + purge_started_at: + at.purgeStartedAgo === undefined ? null : ago(at.purgeStartedAgo), + }); + } + + const statusOf = async () => + Object.fromEntries( + (await prisma.orderCustomUpload.findMany()).map((u) => [ + u.object_key, + u.status, + ]), + ); + + it('하루 지난 PENDING과 한 시간 지난 PURGING만 S3에서 지우고 기록도 지운다', async () => { + await upload('pending-24h', 'PENDING', { createdAgo: 24 * HOUR_MS }); + await upload('pending-23h59', 'PENDING', { createdAgo: 24 * HOUR_MS - 1 }); + await upload('purging-1h', 'PURGING', { + createdAgo: 30 * HOUR_MS, + purgeStartedAgo: HOUR_MS, + }); + await upload('purging-59m', 'PURGING', { + createdAgo: 30 * HOUR_MS, + purgeStartedAgo: HOUR_MS - 1, + }); + // 주문에 쓰인 파일은 오래돼도 보관한다 + await upload('attached-old', 'ATTACHED', { createdAgo: 72 * HOUR_MS }); + + await scheduler.purgeUnusedUploads(); + + expect(deleteObjects).toHaveBeenCalledTimes(1); + expect([...deleteObjects.mock.calls[0][0]].sort()).toEqual([ + 'pending-24h', + 'purging-1h', + ]); + expect(await statusOf()).toEqual({ + 'pending-23h59': 'PENDING', + 'purging-59m': 'PURGING', + 'attached-old': 'ATTACHED', + }); + expect(alerts.notify).not.toHaveBeenCalled(); + }); + + it('S3 삭제에 실패한 키는 PURGING으로 남기고 경보하며, 한 시간 뒤 정리에서 다시 지운다', async () => { + await upload('ok', 'PENDING', { createdAgo: 25 * HOUR_MS }); + await upload('denied', 'PENDING', { createdAgo: 25 * HOUR_MS }); + deleteObjects.mockResolvedValueOnce([ + { key: 'denied', code: 'AccessDenied' }, + ]); + + await scheduler.purgeUnusedUploads(); + + const left = await prisma.orderCustomUpload.findMany(); + expect(left).toEqual([ + expect.objectContaining({ + object_key: 'denied', + status: 'PURGING', + purge_started_at: NOW, + }), + ]); + expect(alerts.notify).toHaveBeenCalledWith( + expect.objectContaining({ + level: 'error', + key: 'order-custom-upload:purge', + detail: expect.stringContaining('1/2건 실패(AccessDenied)'), + }), + ); + + now = new Date(NOW.getTime() + HOUR_MS - 1); + await scheduler.purgeUnusedUploads(); + expect(deleteObjects).toHaveBeenCalledTimes(1); + + now = new Date(NOW.getTime() + HOUR_MS); + await scheduler.purgeUnusedUploads(); + expect(deleteObjects).toHaveBeenLastCalledWith(['denied']); + expect(await prisma.orderCustomUpload.count()).toBe(0); + }); + + it('묶음 상한을 넘으면 다음 묶음을 이어 잡고, 실패한 묶음 뒤에는 더 잡지 않는다', async () => { + const createdAt = ago(25 * HOUR_MS); + await prisma.orderCustomUpload.createMany({ + data: Array.from({ length: PURGE_BATCH_LIMIT + 1 }, (_, i) => ({ + account_id: accountId, + purpose: 'RENDER' as const, + object_key: `k${i}`, + content_type: 'image/png', + content_length: 1, + created_at: createdAt, + })), + }); + deleteObjects.mockImplementationOnce((keys) => + Promise.resolve(keys.map((key) => ({ key, code: 'InternalError' }))), + ); + + await scheduler.purgeUnusedUploads(); + expect(deleteObjects).toHaveBeenCalledTimes(1); + expect(deleteObjects.mock.calls[0][0]).toHaveLength(PURGE_BATCH_LIMIT); + expect( + await prisma.orderCustomUpload.count({ where: { status: 'PENDING' } }), + ).toBe(1); + + now = new Date(NOW.getTime() + HOUR_MS); + await scheduler.purgeUnusedUploads(); + expect(deleteObjects.mock.calls.slice(1).map((c) => c[0].length)).toEqual([ + PURGE_BATCH_LIMIT, + 1, + ]); + expect(await prisma.orderCustomUpload.count()).toBe(0); + }); + + it('주문 tx가 잡고 있는 업로드는 건너뛴다', async () => { + const held = await upload('held', 'PENDING', { createdAgo: 25 * HOUR_MS }); + await upload('free', 'PENDING', { createdAgo: 25 * HOUR_MS }); + + await prisma.$transaction(async (tx) => { + await tx.$queryRaw`SELECT id FROM order_custom_upload WHERE id = ${held.id} FOR UPDATE`; + await scheduler.purgeUnusedUploads(); + }); + + expect(deleteObjects).toHaveBeenCalledWith(['free']); + expect(await statusOf()).toEqual({ held: 'PENDING' }); + }); + + it('api 역할에서는 아무것도 하지 않는다', async () => { + process.env.APP_ROLE = 'api'; + await upload('old', 'PENDING', { createdAgo: 25 * HOUR_MS }); + + await scheduler.purgeUnusedUploads(); + + expect(deleteObjects).not.toHaveBeenCalled(); + expect(await statusOf()).toEqual({ old: 'PENDING' }); + }); + + it('앞 틱이 도는 중이면 겹친 틱은 건너뛴다', async () => { + await upload('old', 'PENDING', { createdAgo: 25 * HOUR_MS }); + let release!: () => void; + deleteObjects.mockImplementationOnce( + () => new Promise((resolve) => (release = () => resolve([]))), + ); + + const first = scheduler.purgeUnusedUploads(); + while (deleteObjects.mock.calls.length === 0) { + await new Promise((resolve) => setTimeout(resolve, 10)); + } + await scheduler.purgeUnusedUploads(); + release(); + await first; + + expect(deleteObjects).toHaveBeenCalledTimes(1); + expect(await prisma.orderCustomUpload.count()).toBe(0); + }); + + it('기록을 읽다 실패하면 경보하고 던지지 않는다', async () => { + jest + .spyOn(repository, 'claimForPurge') + .mockRejectedValueOnce(new Error('db down')); + + await expect(scheduler.purgeUnusedUploads()).resolves.toBeUndefined(); + + expect(alerts.notify).toHaveBeenCalledWith( + expect.objectContaining({ + level: 'error', + key: 'order-custom-upload:purge', + detail: 'db down', + }), + ); + // 실패 뒤에도 다음 틱은 돈다 + await upload('old', 'PENDING', { createdAgo: 25 * HOUR_MS }); + await scheduler.purgeUnusedUploads(); + expect(deleteObjects).toHaveBeenCalledWith(['old']); + }); +}); diff --git a/src/features/order/services/order-custom-upload-cleanup.scheduler.ts b/src/features/order/services/order-custom-upload-cleanup.scheduler.ts new file mode 100644 index 00000000..9853bf95 --- /dev/null +++ b/src/features/order/services/order-custom-upload-cleanup.scheduler.ts @@ -0,0 +1,90 @@ +import { Injectable, Logger } from '@nestjs/common'; +import { Cron } from '@nestjs/schedule'; + +import { ClockService } from '@/common/providers/clock.service'; +import { HOUR_MS } from '@/common/utils/kst-time'; +import { resolveAppRole, runsBackgroundJobs } from '@/config/app.config'; +import { OrderCustomUploadRepository } from '@/features/order/repositories/order-custom-upload.repository'; +import { AlertService } from '@/global/alerting'; +import { S3Service } from '@/global/storage/s3.service'; + +/** 발급 뒤 이만큼 주문에 쓰이지 않은 업로드를 지운다. */ +export const UNUSED_UPLOAD_TTL_MS = 24 * HOUR_MS; +/** 정리 중(PURGING)으로 남은 업로드는 이만큼 지나 다시 지운다. */ +export const PURGE_RETRY_AFTER_MS = HOUR_MS; +export const PURGE_BATCH_LIMIT = 500; +/** 한 틱에서 도는 묶음 상한(밀린 양이 많아도 다음 틱으로 넘긴다). */ +export const PURGE_MAX_BATCHES = 20; + +/** + * 주문에 쓰이지 않은 커스텀 업로드 정리(매시 20분, worker). PURGING 표시를 먼저 커밋해 주문이 붙이지 못하게 한 뒤 + * S3에서 지우고, 지워진 것만 기록을 지운다. 삭제 실패는 PURGING으로 남겨 다음 정리에서 다시 시도하고 경보한다. + */ +@Injectable() +export class OrderCustomUploadCleanupScheduler { + private readonly logger = new Logger(OrderCustomUploadCleanupScheduler.name); + private running = false; + + constructor( + private readonly uploads: OrderCustomUploadRepository, + private readonly s3: S3Service, + private readonly clock: ClockService, + private readonly alerts: AlertService, + ) {} + + /** 크론(ScheduleModule)은 worker에만 실리지만 역할도 함께 본다 — api·ws에서 호출돼도 S3를 지우지 않게. */ + @Cron('0 20 * * * *') + async purgeUnusedUploads(): Promise { + if (!runsBackgroundJobs(resolveAppRole()) || this.running) return; + this.running = true; + try { + await this.run(); + } catch (error) { + const detail = error instanceof Error ? error.message : String(error); + this.logger.error(`커스텀 업로드 정리 실패: ${detail}`); + await this.alerts.notify({ + level: 'error', + title: '커스텀 업로드 정리 실패', + key: 'order-custom-upload:purge', + detail, + }); + } finally { + this.running = false; + } + } + + private async run(): Promise { + const now = this.clock.now(); + for (let batch = 0; batch < PURGE_MAX_BATCHES; batch++) { + const claimed = await this.uploads.claimForPurge({ + now, + pendingCreatedBefore: new Date(now.getTime() - UNUSED_UPLOAD_TTL_MS), + purgingStartedBefore: new Date(now.getTime() - PURGE_RETRY_AFTER_MS), + limit: PURGE_BATCH_LIMIT, + }); + if (claimed.length === 0) return; + + const failures = await this.s3.deleteObjects( + claimed.map((row) => row.object_key), + ); + const failedKeys = new Set(failures.map((f) => f.key)); + await this.uploads.deletePurged( + claimed + .filter((row) => !failedKeys.has(row.object_key)) + .map((row) => row.id), + ); + if (failures.length > 0) { + // 남은 행은 PURGING이라 1시간 뒤 정리에서 다시 시도한다. S3 장애면 더 묶음을 잡지 않는다 + const codes = [...new Set(failures.map((f) => f.code))].join(', '); + await this.alerts.notify({ + level: 'error', + title: '커스텀 업로드 S3 삭제 실패', + key: 'order-custom-upload:purge', + detail: `${failures.length}/${claimed.length}건 실패(${codes}) — 다음 정리에서 다시 시도`, + }); + return; + } + if (claimed.length < PURGE_BATCH_LIMIT) return; + } + } +} diff --git a/src/global/storage/constants/storage.constants.ts b/src/global/storage/constants/storage.constants.ts index bb6b85fb..9d5e4957 100644 --- a/src/global/storage/constants/storage.constants.ts +++ b/src/global/storage/constants/storage.constants.ts @@ -35,4 +35,20 @@ export const UPLOAD_POLICIES: Record = { maxSizeBytes: 5 * 1024 * 1024, allowedContentTypes: ['image/jpeg', 'image/png', 'image/webp'], }, + // 구매자 커스텀 주문 이미지는 리뷰 이미지와 같은 정책. 주문에 쓰이지 않으면 정리 크론이 order-custom/ 아래를 지운다 + ORDER_CUSTOM_RENDER: { + keyPrefix: 'order-custom/renders', + maxSizeBytes: 10 * 1024 * 1024, + allowedContentTypes: ['image/jpeg', 'image/png', 'image/webp'], + }, + ORDER_CUSTOM_COMPOSITE: { + keyPrefix: 'order-custom/composites', + maxSizeBytes: 10 * 1024 * 1024, + allowedContentTypes: ['image/jpeg', 'image/png', 'image/webp'], + }, + ORDER_CUSTOM_REFERENCE: { + keyPrefix: 'order-custom/references', + maxSizeBytes: 10 * 1024 * 1024, + allowedContentTypes: ['image/jpeg', 'image/png', 'image/webp'], + }, } as const; diff --git a/src/global/storage/s3.service.delete-objects.spec.ts b/src/global/storage/s3.service.delete-objects.spec.ts new file mode 100644 index 00000000..1ce2d8a8 --- /dev/null +++ b/src/global/storage/s3.service.delete-objects.spec.ts @@ -0,0 +1,113 @@ +import { S3ServiceException } from '@aws-sdk/client-s3'; +import { ConfigService } from '@nestjs/config'; +import { Test } from '@nestjs/testing'; + +import { CustomLoggerService } from '@/global/logger/custom-logger.service'; +import { S3Service } from '@/global/storage/s3.service'; + +const mockSend = jest.fn(); + +jest.mock('@aws-sdk/client-s3', () => ({ + ...jest.requireActual('@aws-sdk/client-s3'), + S3Client: jest.fn().mockImplementation(() => ({ + send: (command: unknown) => mockSend(command), + })), + DeleteObjectsCommand: jest.fn().mockImplementation((input: unknown) => input), +})); + +interface DeleteInput { + Bucket: string; + Delete: { Objects: { Key: string }[]; Quiet: boolean }; +} + +const sentKeyCounts = () => + (mockSend.mock.calls as [DeleteInput][]).map( + ([input]) => input.Delete.Objects.length, + ); + +describe('S3Service.deleteObjects', () => { + let service: S3Service; + const logger = { error: jest.fn(), warn: jest.fn() }; + + beforeEach(async () => { + mockSend.mockReset(); + logger.error.mockClear(); + const module = await Test.createTestingModule({ + providers: [ + S3Service, + { + provide: ConfigService, + useValue: { + get: () => ({ + region: 'ap-northeast-2', + bucket: 'caquick-media-test', + presignExpiresSeconds: 600, + }), + }, + }, + { provide: CustomLoggerService, useValue: logger }, + ], + }).compile(); + service = module.get(S3Service); + }); + + it('이 버킷에 조용한 모드로 한 번에 지우고, 오류가 없으면 실패 없음이다', async () => { + mockSend.mockResolvedValue({}); + + await expect(service.deleteObjects(['a.png', 'b.png'])).resolves.toEqual( + [], + ); + expect(mockSend).toHaveBeenCalledTimes(1); + expect(mockSend.mock.calls[0][0]).toEqual({ + Bucket: 'caquick-media-test', + Delete: { Objects: [{ Key: 'a.png' }, { Key: 'b.png' }], Quiet: true }, + }); + }); + + it('키별 오류는 키·코드로 돌려준다', async () => { + mockSend.mockResolvedValue({ + Errors: [{ Key: 'b.png', Code: 'AccessDenied', Message: 'denied' }], + }); + + await expect(service.deleteObjects(['a.png', 'b.png'])).resolves.toEqual([ + { key: 'b.png', code: 'AccessDenied' }, + ]); + }); + + it('요청 자체가 실패하면 그 묶음 전부를 실패로 돌려주고 던지지 않는다', async () => { + mockSend.mockRejectedValue( + new S3ServiceException({ + name: 'AccessDenied', + $fault: 'client', + $metadata: { httpStatusCode: 403 }, + message: 'denied', + }), + ); + + await expect(service.deleteObjects(['a.png', 'b.png'])).resolves.toEqual([ + { key: 'a.png', code: 'AccessDenied' }, + { key: 'b.png', code: 'AccessDenied' }, + ]); + expect(logger.error).toHaveBeenCalledWith( + 'S3 객체 삭제 실패', + expect.objectContaining({ keys: 2 }), + ); + }); + + it('1000개를 넘으면 1000개씩 나눠 보내고, 실패한 묶음만 실패로 돌려준다', async () => { + const keys = Array.from({ length: 1001 }, (_, i) => `k${i}`); + mockSend + .mockResolvedValueOnce({}) + .mockRejectedValueOnce(new Error('socket hang up')); + + const failures = await service.deleteObjects(keys); + + expect(sentKeyCounts()).toEqual([1000, 1]); + expect(failures).toEqual([{ key: 'k1000', code: 'Error' }]); + }); + + it('빈 목록이면 요청하지 않는다', async () => { + await expect(service.deleteObjects([])).resolves.toEqual([]); + expect(mockSend).not.toHaveBeenCalled(); + }); +}); diff --git a/src/global/storage/s3.service.spec.ts b/src/global/storage/s3.service.spec.ts index 7d714038..023e9921 100644 --- a/src/global/storage/s3.service.spec.ts +++ b/src/global/storage/s3.service.spec.ts @@ -198,6 +198,38 @@ describe('S3Service', () => { }); }); + describe.each([ + ['ORDER_CUSTOM_RENDER', 'order-custom/renders/'], + ['ORDER_CUSTOM_COMPOSITE', 'order-custom/composites/'], + ['ORDER_CUSTOM_REFERENCE', 'order-custom/references/'], + ] as const)('%s purpose', (purpose, prefix) => { + const input = { ...baseInput, purpose }; + + it.each(['image/jpeg', 'image/png', 'image/webp'])( + `%s 10MB를 ${prefix} 아래로 발급한다`, + async (contentType) => { + const result = await service.createUploadUrl({ + ...input, + contentType, + contentLength: 10 * 1024 * 1024, + }); + expect(result.key.startsWith(`${prefix}1/`)).toBe(true); + }, + ); + + it('10MB 초과·이미지가 아닌 형식은 거부한다', async () => { + await expect( + service.createUploadUrl({ + ...input, + contentLength: 10 * 1024 * 1024 + 1, + }), + ).rejects.toThrowDomain('FILE_TOO_LARGE'); + await expect( + service.createUploadUrl({ ...input, contentType: 'video/mp4' }), + ).rejects.toThrowDomain('INVALID_CONTENT_TYPE'); + }); + }); + describe('contentLength 검증', () => { it('0이면 거부해야 한다', async () => { await expect( diff --git a/src/global/storage/s3.service.ts b/src/global/storage/s3.service.ts index 6ebc9aa3..cb766c46 100644 --- a/src/global/storage/s3.service.ts +++ b/src/global/storage/s3.service.ts @@ -1,6 +1,7 @@ import { randomUUID } from 'node:crypto'; import { + DeleteObjectsCommand, GetObjectCommand, PutObjectCommand, S3Client, @@ -34,6 +35,13 @@ const CONTENT_TYPE_TO_EXT: Record = { const IMAGE_HEADER_BYTES = 64 * 1024; /** 객체가 없거나(404) 0바이트라 범위를 못 읽는(416) 경우는 장애가 아니라 읽을 수 없는 이미지다. */ const UNREADABLE_OBJECT_STATUS = new Set([404, 416]); +/** DeleteObjects 요청 1건의 키 상한. */ +const DELETE_OBJECTS_MAX_KEYS = 1000; + +export interface DeleteObjectsFailure { + key: string; + code: string; +} @Injectable() export class S3Service { @@ -170,6 +178,45 @@ export class S3Service { return full === null ? null : measureImage(full.bytes); } + /** + * 이 버킷의 객체를 지운다(요청당 1000개). 없는 객체는 S3가 지운 것으로 답한다. 키별 실패와 요청 자체의 실패를 + * 모두 실패 목록으로 돌려주고 던지지 않는다 — 호출부가 지워진 키만 골라 기록을 정리한다. + */ + async deleteObjects( + keys: readonly string[], + ): Promise { + const failures: DeleteObjectsFailure[] = []; + for (let i = 0; i < keys.length; i += DELETE_OBJECTS_MAX_KEYS) { + const chunk = keys.slice(i, i + DELETE_OBJECTS_MAX_KEYS); + try { + const res = await this.client.send( + new DeleteObjectsCommand({ + Bucket: this.bucket, + Delete: { Objects: chunk.map((Key) => ({ Key })), Quiet: true }, + }), + ); + for (const error of res.Errors ?? []) { + failures.push({ + key: error.Key ?? '', + code: error.Code ?? 'Unknown', + }); + } + } catch (error) { + const code = error instanceof Error ? error.name : 'Unknown'; + this.logger.error('S3 객체 삭제 실패', { + bucket: this.bucket, + keys: chunk.length, + cause: + error instanceof Error + ? `${error.name}: ${error.message}` + : String(error), + }); + failures.push(...chunk.map((key) => ({ key, code }))); + } + } + return failures; + } + private keyOfPublicUrl(url: string): string | null { try { const parsed = new URL(url); diff --git a/src/global/storage/types/storage.types.ts b/src/global/storage/types/storage.types.ts index abe438a2..f7525e59 100644 --- a/src/global/storage/types/storage.types.ts +++ b/src/global/storage/types/storage.types.ts @@ -4,7 +4,10 @@ export type UploadPurpose = | 'REVIEW_VIDEO' | 'PRODUCT_IMAGE' | 'STORE_IMAGE' - | 'BANNER_IMAGE'; + | 'BANNER_IMAGE' + | 'ORDER_CUSTOM_RENDER' + | 'ORDER_CUSTOM_COMPOSITE' + | 'ORDER_CUSTOM_REFERENCE'; export interface CreateUploadUrlInput { accountId: bigint; diff --git a/src/test/factories/order.factory.ts b/src/test/factories/order.factory.ts index 75deb59d..89c91530 100644 --- a/src/test/factories/order.factory.ts +++ b/src/test/factories/order.factory.ts @@ -4,6 +4,7 @@ import type { CustomImageKind, CustomMode, Order, + OrderCustomUpload, OrderItem, OrderStatus, Payment, @@ -269,3 +270,36 @@ export async function createThreeDOrderItemCustom( }); } } + +export type OrderCustomUploadOverrides = Partial< + Pick< + OrderCustomUpload, + | 'account_id' + | 'purpose' + | 'object_key' + | 'status' + | 'created_at' + | 'purge_started_at' + | 'attached_at' + > +>; + +/** 커스텀 이미지 선업로드 기록. 계정을 안 주면 구매자를 새로 만든다. */ +export async function createOrderCustomUpload( + prisma: PrismaClient, + overrides: OrderCustomUploadOverrides = {}, +): Promise { + const accountId = + overrides.account_id ?? + (await createAccount(prisma, { account_type: 'USER' })).id; + return prisma.orderCustomUpload.create({ + data: { + purpose: 'RENDER', + object_key: `order-custom/renders/${accountId}/2026-11-19/${nextSeq()}.png`, + content_type: 'image/png', + content_length: 1024, + ...overrides, + account_id: accountId, + }, + }); +} diff --git a/src/test/model-ownership.ts b/src/test/model-ownership.ts index 8e8580d2..da7341c2 100644 --- a/src/test/model-ownership.ts +++ b/src/test/model-ownership.ts @@ -92,6 +92,7 @@ export const MODEL_OWNERSHIP: Readonly> = { OrderItemCustomFreeEditAttachment: order([]), OrderItemCustomDesign: order([]), OrderItemCustomImage: order([]), + OrderCustomUpload: order(), Payment: order(), Refund: order(), DepositRecord: order(), diff --git a/src/test/seed-reset-scope.spec.ts b/src/test/seed-reset-scope.spec.ts index 6c035f5b..91304c9e 100644 --- a/src/test/seed-reset-scope.spec.ts +++ b/src/test/seed-reset-scope.spec.ts @@ -29,6 +29,7 @@ import { createAccount, createNotification, createOrder, + createOrderCustomUpload, createOrderItem, createReview, createReviewReport, @@ -182,6 +183,26 @@ describe('resetSeedScope (real DB)', () => { expect(await counts()).toEqual([0, 2]); }); + it('시드 사용자의 커스텀 업로드 기록은 지우고 시드 밖 계정 것은 남긴다', async () => { + const [seedUser] = await seedThroughReviews(); + const outsider = await createAccount(prisma, { account_type: 'USER' }); + for (const [accountId, key] of [ + [seedUser.id, 'order-custom/renders/seed.png'], + [outsider.id, 'order-custom/renders/outsider.png'], + ] as const) { + await createOrderCustomUpload(prisma, { + account_id: accountId, + object_key: key, + }); + } + + await resetSeedScope(prisma); + await seedThroughReviews(); + + const left = await prisma.orderCustomUpload.findMany(); + expect(left.map((u) => u.account_id)).toEqual([outsider.id]); + }); + it('시드 밖 계정이 시드 밖 매장에 넣은 주문은 남긴다', async () => { await seedThroughReviews(); const { order, item } = await outsiderOrder(); diff --git a/terraform/aws.tf b/terraform/aws.tf index afe5c82c..e61d3325 100644 --- a/terraform/aws.tf +++ b/terraform/aws.tf @@ -185,6 +185,13 @@ data "aws_iam_policy_document" "app" { actions = ["s3:PutObject", "s3:GetObject"] resources = [for b in aws_s3_bucket.media : "${b.arn}/*"] } + # 주문에 쓰이지 않은 커스텀 이미지 정리(worker 크론). 다른 접두는 지우지 못한다 + statement { + sid = "OrderCustomUploadCleanup" + effect = "Allow" + actions = ["s3:DeleteObject"] + resources = [for b in aws_s3_bucket.media : "${b.arn}/order-custom/*"] + } } resource "aws_iam_policy" "app" { From bfa336a4cd3550df1e14535291c526ee14b7e45b Mon Sep 17 00:00:00 2001 From: chanwoo7 Date: Thu, 19 Nov 2026 05:15:05 +0900 Subject: [PATCH 34/54] =?UTF-8?q?test:=20=EC=BB=A4=EC=8A=A4=ED=85=80=20?= =?UTF-8?q?=EC=97=85=EB=A1=9C=EB=93=9C=20=EC=9A=A9=EB=8F=84=20=EC=9E=85?= =?UTF-8?q?=EB=A0=A5=20enum=EC=9D=B4=20=EC=84=9C=EB=B2=84=20enum=EC=9D=84?= =?UTF-8?q?=20=EB=B2=97=EC=96=B4=EB=82=98=EC=A7=80=20=EC=95=8A=EA=B2=8C=20?= =?UTF-8?q?SDL=20=EB=8F=99=EA=B8=B0=ED=99=94=20=EA=B2=8C=EC=9D=B4=ED=8A=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 입력 SDL enum OrderCustomUploadPurpose에만 값이 늘면 발급 서비스의 용도 → 업로드 정책 매핑이 비어 S3Service에서 TypeError가 나고 500으로 떨어진다. 매핑은 Prisma enum으로만 satisfies 검사되고, enum-sdl-sync는 출력 방향(Prisma ⊆ SDL)만 대조해 이 어긋남을 잡지 못했다. 변경점 - enum-sdl-sync에 입력 쌍 목록(INPUT_PAIRS)을 두고 반대 방향(SDL ⊆ Prisma)을 대조한다. 첫 쌍은 OrderCustomUploadPurpose - 대조 함수 이름을 방향 중립(missingFrom)으로 바꿨다 테스트 - enum-sdl-sync 20건 통과(입력 방향 2건 추가: 반증 — SDL에 값을 더하면 잡는다, 실제 SDL 대조) - 반증: 실제 SDL에 SKETCH를 더하면 실제 대조가 실패하는 것을 확인하고 되돌렸다 --- src/test/enum-sdl-sync.spec.ts | 63 +++++++++++++++++++++++++++++++--- 1 file changed, 58 insertions(+), 5 deletions(-) diff --git a/src/test/enum-sdl-sync.spec.ts b/src/test/enum-sdl-sync.spec.ts index 4e59d5e8..cb7f242a 100644 --- a/src/test/enum-sdl-sync.spec.ts +++ b/src/test/enum-sdl-sync.spec.ts @@ -14,6 +14,7 @@ import { OrderActor, OrderCancelFault, OrderCancelReason, + OrderCustomUploadPurpose, OrderStatus, RefundKind, RefundStatus, @@ -115,8 +116,23 @@ function sdlEnumValues(source: string, enumName: string): string[] { throw new Error(`enum ${enumName}이 SDL에 없습니다`); } -function missingInSdl(prisma: string[], sdl: string[]): string[] { - return prisma.filter((v) => !sdl.includes(v)); +/** + * 입력 SDL enum은 방향이 반대다 — SDL 값이 서버 enum에 모두 있어야 한다. SDL에만 값이 늘면 그 값을 받은 + * 요청이 서버 매핑(예: 업로드 용도 → 정책)을 찾지 못해 500으로 떨어진다. + */ +const INPUT_PAIRS: Array< + [label: string, prisma: string[], file: string, sdl: string] +> = [ + [ + 'OrderCustomUploadPurpose', + Object.values(OrderCustomUploadPurpose), + 'src/features/order/order-checkout.graphql', + 'OrderCustomUploadPurpose', + ], +]; + +function missingFrom(values: string[], target: string[]): string[] { + return values.filter((v) => !target.includes(v)); } const read = (file: string) => readFileSync(join(process.cwd(), file), 'utf8'); @@ -133,14 +149,14 @@ describe('Prisma enum·TS 상수 ⊆ SDL enum', () => { node.name.value === removed ? null : undefined, }), ); - expect(missingInSdl(prisma, sdlEnumValues(broken, sdl))).toEqual([ + expect(missingFrom(prisma, sdlEnumValues(broken, sdl))).toEqual([ removed, ]); }, ); it('SDL에만 있는 값은 허용한다(부분집합 판정)', () => { - expect(missingInSdl(['A'], ['A', 'B'])).toEqual([]); + expect(missingFrom(['A'], ['A', 'B'])).toEqual([]); }); it('SDL에 enum이 없으면 실패한다', () => { @@ -154,7 +170,44 @@ describe('Prisma enum·TS 상수 ⊆ SDL enum', () => { '%s: 서버 값이 SDL에 모두 있다', (_label, prisma, file, sdl) => { expect(prisma.length).toBeGreaterThan(0); - expect(missingInSdl(prisma, sdlEnumValues(read(file), sdl))).toEqual([]); + expect(missingFrom(prisma, sdlEnumValues(read(file), sdl))).toEqual([]); + }, + ); +}); + +describe('입력 SDL enum ⊆ Prisma enum', () => { + it.each(INPUT_PAIRS)( + '%s: 검사기 반증 — SDL에 값을 하나 더하면 서버에 없다고 잡는다', + (_label, prisma, file, sdl) => { + const added = print( + visit(parse(read(file)), { + EnumTypeDefinition: (node) => + node.name.value === sdl + ? { + ...node, + values: [ + ...(node.values ?? []), + { + kind: Kind.ENUM_VALUE_DEFINITION, + name: { kind: Kind.NAME, value: 'ADDED_IN_SDL' }, + }, + ], + } + : undefined, + }), + ); + expect(missingFrom(sdlEnumValues(added, sdl), prisma)).toEqual([ + 'ADDED_IN_SDL', + ]); + }, + ); + + it.each(INPUT_PAIRS)( + '%s: SDL 값이 서버에 모두 있다', + (_label, prisma, file, sdl) => { + const values = sdlEnumValues(read(file), sdl); + expect(values.length).toBeGreaterThan(0); + expect(missingFrom(values, prisma)).toEqual([]); }, ); }); From 0dcb9f19974520773f850e989f936d0738f5c2b1 Mon Sep 17 00:00:00 2001 From: chanwoo7 Date: Thu, 19 Nov 2026 05:19:20 +0900 Subject: [PATCH 35/54] =?UTF-8?q?fix:=20=EC=97=85=EB=A1=9C=EB=93=9C=20?= =?UTF-8?q?=EB=B0=9C=EA=B8=89=20=EC=98=A4=EB=A5=98=20=EC=BD=94=EB=93=9C=20?= =?UTF-8?q?=EC=84=A4=EB=AA=85=EA=B3=BC=20=EC=A0=95=EB=A6=AC=20=EC=9E=AC?= =?UTF-8?q?=EC=8B=9C=EB=8F=84=20=EC=A3=BC=EC=84=9D=20=EC=A0=95=EC=A0=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit createOrderCustomUploadUrl 설명이 실제로 나는 오류 코드 일부를 빠뜨렸고, 입력 전용 enum에 출력 enum용 문구가 붙어 있었다. 정리 크론의 재시도 주석은 매시 크론이라 실제로는 1~2시간 뒤 다시 지우는 것을 1시간 뒤로 적고 있었다. 변경점 - SDL 설명: INVALID_CONTENT_LENGTH(크기 0 이하)·BUYER_ACCOUNT_NOT_ACTIVE(정지·탈퇴·프로필 없음) 추가, OrderCustomUploadPurpose 설명에서 출력용 문구 삭제 - 정리 크론: 재시도 시점 주석을 '1시간이 지난 뒤의 정리(1~2시간 뒤)'로 정정(판정 기준 1시간은 그대로) 테스트 - 정리 크론·발급 리졸버 spec 통과, docs:check 통과 --- src/features/order/order-checkout.graphql | 9 ++++----- .../services/order-custom-upload-cleanup.scheduler.ts | 3 ++- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/src/features/order/order-checkout.graphql b/src/features/order/order-checkout.graphql index 7ddba327..30a60af5 100644 --- a/src/features/order/order-checkout.graphql +++ b/src/features/order/order-checkout.graphql @@ -9,8 +9,9 @@ extend type Mutation { createOrder(input: CreateOrderInput!): CreateOrderOutput! """ 커스텀 이미지 업로드용 Presigned URL 발급(구매자). uploadUrl로 PUT한 뒤 publicUrl을 주문 생성의 커스텀 입력에 넣는다. - JPEG·PNG·WebP, 장당 10MB 이하(아니면 INVALID_CONTENT_TYPE·FILE_TOO_LARGE). 주문에 쓰이지 않은 파일은 발급 하루 뒤 지워진다. - 구매자 계정만 쓸 수 있다(아니면 USER_ONLY). 로그인 필수. + JPEG·PNG·WebP, 장당 1바이트 이상 10MB 이하(아니면 INVALID_CONTENT_TYPE·INVALID_CONTENT_LENGTH·FILE_TOO_LARGE). + 주문에 쓰이지 않은 파일은 발급 하루 뒤 지워진다. 구매자 계정만 쓸 수 있고(아니면 USER_ONLY), 정지·탈퇴 등으로 + 이용할 수 없는 계정이면 BUYER_ACCOUNT_NOT_ACTIVE다. 로그인 필수. """ createOrderCustomUploadUrl( """이미지 용도. 주문 생성 때 이 용도의 자리에만 쓸 수 있다.""" @@ -22,9 +23,7 @@ extend type Mutation { ): UploadUrl! } -""" -구매자 커스텀 이미지 업로드 용도. 값은 늘어날 수 있으니 모르는 값을 받아도 화면이 죽지 않게 처리한다. -""" +"""구매자 커스텀 이미지 업로드 용도.""" enum OrderCustomUploadPurpose { """3D 렌더 이미지(윗면·옆면 앞·뒤·좌·우).""" RENDER diff --git a/src/features/order/services/order-custom-upload-cleanup.scheduler.ts b/src/features/order/services/order-custom-upload-cleanup.scheduler.ts index 9853bf95..149f40b1 100644 --- a/src/features/order/services/order-custom-upload-cleanup.scheduler.ts +++ b/src/features/order/services/order-custom-upload-cleanup.scheduler.ts @@ -74,7 +74,8 @@ export class OrderCustomUploadCleanupScheduler { .map((row) => row.id), ); if (failures.length > 0) { - // 남은 행은 PURGING이라 1시간 뒤 정리에서 다시 시도한다. S3 장애면 더 묶음을 잡지 않는다 + // 남은 행은 PURGING이라 1시간이 지난 뒤의 정리(매시 크론이라 1~2시간 뒤)에서 다시 지운다. + // S3 장애일 수 있어 이 틱에서는 더 잡지 않는다 const codes = [...new Set(failures.map((f) => f.code))].join(', '); await this.alerts.notify({ level: 'error', From e3829d049fbbad21e672434530d369b10f4b130e Mon Sep 17 00:00:00 2001 From: chanwoo7 Date: Thu, 19 Nov 2026 06:04:05 +0900 Subject: [PATCH 36/54] =?UTF-8?q?feat:=20=EC=A3=BC=EB=AC=B8=20=EC=83=9D?= =?UTF-8?q?=EC=84=B1=20=EC=BB=A4=EC=8A=A4=ED=85=80=20=EC=9E=85=EB=A0=A5=20?= =?UTF-8?q?=EA=B2=80=EC=A6=9D=EA=B3=BC=20=EC=8A=A4=EB=83=85=EC=83=B7=20?= =?UTF-8?q?=EC=A0=80=EC=9E=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 커스텀 상품(슬롯형·3D)은 createOrder가 커스텀 입력을 함께 받아 주문 시점 상품 설정과 대조하고, 통과한 값을 품목 스냅샷으로 저장한다. 커스텀 방식이 있는 상품은 커스텀이 필수이고 수량은 1이며, 커스텀은 가격을 바꾸지 않는다(3D 모양·크기 등은 옵션 추가금으로만 들어온다). 선업로드한 이미지는 주문 tx 안에서 잠가 소유·용도·상태를 확인한 뒤 ATTACHED로 바꿔 정리 크론 대상에서 뺀다. 같은 멱등 키 재요청 판정(입력 해시)에 커스텀 입력도 포함한다. 변경점 - SDL·DTO: CreateOrderInput.custom: CreateOrderCustomInput { slot | threeD } - 슬롯형: templateRevision, texts[{ tokenId, valueText }], compositeImageUrl, freeEdits[{ posX..height, descriptionText, referenceImageUrls }] = [] - 3D: design(ThreeDDesignInput, JSON v1), renderImages[{ kind: CustomImageKindType, imageUrl }] - 전역 ValidationPipe(whitelist·forbidNonWhitelisted)를 통과하도록 중첩 필드 전부에 검증 데코레이터, 필수 중첩 객체는 IsDefined - OrderCustomizationService.resolve(order): 방식 대조(CUSTOM_INPUT_REQUIRED·CUSTOM_INPUT_MISMATCH) → 수량 1(CUSTOM_QUANTITY_FIXED) → 준비 상태(evaluateProductCustomIssues, CUSTOM_PRODUCT_NOT_READY) - 슬롯형: revision(CUSTOM_TEMPLATE_CHANGED 409) → 문구 자리 집합(CUSTOM_SLOT_TEXTS_MISMATCH) → 값(CRLF·CR→LF, trim, 코드 포인트 ≤ max_length; 필수 자리 지움 CUSTOM_SLOT_TEXT_REQUIRED, 선택 자리 지움 null) → 자유 편집(켜짐·5건·영역 0~10000·설명 1~2000자·참고 사진 3장) - 3D: validateThreeDDesign(고른 옵션의 three_d_key와 대조) → 렌더 5종 정확히 1장씩(CUSTOM_RENDER_IMAGES_INVALID) - 모든 이미지 URL: assertOwnedUploadUrl(용도별 접두) + 같은 파일 중복 금지(CUSTOM_UPLOAD_INVALID) - 저장(order.repository): 품목 custom_mode_snapshot·바탕(슬롯형)·대표 이미지(슬롯형 합성, 3D 윗면), 문구 자리 스냅샷(tokenId·key·label·기본 문구·값·좌표·색·정렬), 자유 편집 영역·설명·참고 사진, 3D 디자인 JSON(검증된 정규형)·버전, 커스텀 이미지(렌더는 종류 순) - 업로드 연결: 계정 잠금 → 입금 대기 건수 → capacity 뒤에 order_custom_upload를 object_key IN (…) FOR UPDATE로 잠그고 검사, 품목 생성 뒤 같은 tx에서 ATTACHED. tx 안 거절('upload-invalid'·'upload-expired')도 capacity 거절처럼 같은 키 replay를 먼저 확인한다 - 입력 해시: canonicalizeCustomOrderInput(product 순수 헬퍼, 입력은 product 구조 타입)을 hashCreateOrderInput에 더했다. 커스텀이 없으면 기존 해시와 같다 - 업로드 용도 표(CUSTOM_UPLOAD_PURPOSES)를 order 상수로 옮겨 발급과 주문 생성이 같이 쓴다. product 배럴에 CUSTOM_AREA_SCALE을 공개했다 - 게이트: model-ownership의 OrderItemCustomText·FreeEdit·FreeEditAttachment·Design·Image writers를 order로 - 에러 코드 11종 신설(CUSTOM_TEMPLATE_CHANGED만 409) 명세에 없던 결정 - 문구 길이 초과는 CUSTOM_SLOT_TEXT_TOO_LONG('{label}'·{max}), 자유 편집 규칙 위반은 CUSTOM_FREE_EDIT_INVALID 하나로 두고 메시지에 위치(freeEdits[0].descriptionText 형식)를 담는다 - 이미지 중복은 URL이 아니라 객체 키로 가린다(쿼리만 다른 같은 파일 차단). 키 컬럼 콜레이션이 대소문자를 가리지 않아 잠근 행과 키를 코드에서 정확히 비교한다 - 발급 기록이 없거나 이미 다른 주문에 붙은 업로드는 CUSTOM_UPLOAD_INVALID, 정리 중(PURGING)이면 CUSTOM_UPLOAD_EXPIRED - 해시 정규형은 문구 자리(tokenId)·렌더 이미지(종류)를 정렬하고, 그리는 순서·입력 순서가 의미인 3D 항목·자유 편집·참고 사진은 그대로 둔다. 생략한 자유 편집·참고 사진은 빈 배열과 같다 - custom이 {}(슬롯·3D 모두 없음)이면 커스텀 없음과 같다 테스트 - OrderCustomizationService 82건(DB 없음): 방식 표 12, 수량 3, 준비 상태 4, 슬롯형 스냅샷, revision, 자리 집합 5 + 빈 ID, 문구 값 표(기본·CRLF·CR·trim·이모지·합자 이모지·경계·지움) 18, 자유 편집(5건·6건·꺼짐·영역 경계 8·설명 6·사진 3/4), 3D 정상·옵션 불일치 3·디자인 무효·렌더 5종 5, 업로드 소유·중복 9 - createOrder 커스텀(real DB) 13건: 슬롯형 스냅샷·ATTACHED·가격 불변, 3D 디자인·렌더·가격(옵션 추가금만), 재사용 업로드, ATTACHED·PURGING·용도 다른 기록, 미발급·다른 계정 기록·대소문자 변형 키, 연결 뒤 tx 실패 시 PENDING 유지와 재주문, 같은 키 replay·커스텀 불일치, 업로드 잠금에서 걸린 같은 키 replay, revision 변경, 3D 옵션 불일치, 3D 커스텀 누락 - 입력 해시: 커스텀 정규형 고정 1, 커스텀 없음 3, 같은 해시 5, 다른 해시 8, 슬롯·3D 구분 1. canonicalizeCustomOrderInput 6. DTO 중첩 검증 통과 3·거절 8. 에러 카탈로그 렌더 파라미터 - 반증: writers 비움, 업로드 검사 무시, 키 대소문자 무시, 해시에서 커스텀 제외, URL 기준 중복, 준비 상태·렌더 개수·자유 편집 꺼짐·수량·revision 검사 제거가 각각 실패함을 확인했다 --- src/common/errors/error-catalog.spec.ts | 3 + src/common/errors/error-catalog.ts | 46 + .../constants/order-custom-upload-purposes.ts | 9 + .../dto/inputs/create-order-custom.input.ts | 182 ++++ .../dto/inputs/create-order.input.spec.ts | 139 +++ .../order/dto/inputs/create-order.input.ts | 8 + src/features/order/order-checkout.graphql | 150 +++- src/features/order/order.module.ts | 3 + .../order-custom-upload-attach.helper.ts | 67 ++ .../repositories/order.repository.spec.ts | 1 + .../order/repositories/order.repository.ts | 117 ++- .../order-checkout-mutation.resolver.spec.ts | 2 + .../order-checkout.service.custom.spec.ts | 601 +++++++++++++ .../services/order-checkout.service.spec.ts | 2 + .../order/services/order-checkout.service.ts | 48 +- .../order-customization.service.spec.ts | 792 ++++++++++++++++++ .../services/order-customization.service.ts | 274 ++++++ .../services/order-input-hash.helper.spec.ts | 184 ++++ .../order/services/order-input-hash.helper.ts | 8 +- src/features/product/index.ts | 6 + .../custom-order-input.helper.spec.ts | 136 +++ .../services/custom-order-input.helper.ts | 92 ++ src/test/model-ownership.ts | 10 +- 23 files changed, 2853 insertions(+), 27 deletions(-) create mode 100644 src/features/order/constants/order-custom-upload-purposes.ts create mode 100644 src/features/order/dto/inputs/create-order-custom.input.ts create mode 100644 src/features/order/repositories/order-custom-upload-attach.helper.ts create mode 100644 src/features/order/services/order-checkout.service.custom.spec.ts create mode 100644 src/features/order/services/order-customization.service.spec.ts create mode 100644 src/features/order/services/order-customization.service.ts create mode 100644 src/features/product/services/custom-order-input.helper.spec.ts create mode 100644 src/features/product/services/custom-order-input.helper.ts diff --git a/src/common/errors/error-catalog.spec.ts b/src/common/errors/error-catalog.spec.ts index 21749898..cac760d7 100644 --- a/src/common/errors/error-catalog.spec.ts +++ b/src/common/errors/error-catalog.spec.ts @@ -36,6 +36,9 @@ const RENDER_PARAMS: Partial< CUSTOM_TEXT_DEFAULT_TOO_LONG: { label: '이름', max: 20 }, CUSTOM_3D_ITEM_LIMIT_EXCEEDED: { max: 10 }, CUSTOM_3D_DESIGN_INVALID: { field: 'top[0].size' }, + CUSTOM_SLOT_TEXT_REQUIRED: { label: '이름' }, + CUSTOM_SLOT_TEXT_TOO_LONG: { label: '이름', max: 20 }, + CUSTOM_FREE_EDIT_INVALID: { field: 'freeEdits[0].descriptionText' }, IDS_LENGTH_MISMATCH: { field: 'imageIds' }, INVALID_IDS: { field: 'imageIds' }, PRODUCT_IMAGE_LIMIT_EXCEEDED: { max: 10 }, diff --git a/src/common/errors/error-catalog.ts b/src/common/errors/error-catalog.ts index fa18a216..f93c23ad 100644 --- a/src/common/errors/error-catalog.ts +++ b/src/common/errors/error-catalog.ts @@ -570,6 +570,52 @@ export const ERROR_CATALOG = { message: ({ field }) => `3D 디자인에 쓸 수 없는 값이 있어요(${field}). 다시 꾸며 주세요.`, }, + CUSTOM_INPUT_REQUIRED: { + status: HttpStatus.BAD_REQUEST, + message: '케이크를 꾸민 뒤 주문해 주세요.', + }, + CUSTOM_INPUT_MISMATCH: { + status: HttpStatus.BAD_REQUEST, + message: '이 상품의 꾸미기 방식과 맞지 않는 주문이에요. 다시 꾸며 주세요.', + }, + CUSTOM_QUANTITY_FIXED: { + status: HttpStatus.BAD_REQUEST, + message: '꾸민 케이크는 한 번에 1개만 주문할 수 있어요.', + }, + CUSTOM_TEMPLATE_CHANGED: { + status: HttpStatus.CONFLICT, + message: '판매자가 꾸미기 설정을 바꿨어요. 다시 꾸며 주세요.', + }, + CUSTOM_SLOT_TEXTS_MISMATCH: { + status: HttpStatus.BAD_REQUEST, + message: '문구 자리 입력이 상품 설정과 맞지 않아요. 다시 꾸며 주세요.', + }, + CUSTOM_SLOT_TEXT_REQUIRED: { + status: HttpStatus.BAD_REQUEST, + message: ({ label }) => `'${label}'에 문구를 넣어 주세요.`, + }, + CUSTOM_SLOT_TEXT_TOO_LONG: { + status: HttpStatus.BAD_REQUEST, + message: ({ label, max }) => `'${label}'에는 ${max}자까지 쓸 수 있어요.`, + }, + CUSTOM_FREE_EDIT_INVALID: { + status: HttpStatus.BAD_REQUEST, + message: ({ field }) => + `자유 편집 요청에 쓸 수 없는 값이 있어요(${field}). 다시 확인해 주세요.`, + }, + CUSTOM_RENDER_IMAGES_INVALID: { + status: HttpStatus.BAD_REQUEST, + message: + '3D 렌더 이미지는 윗면과 옆면 앞·뒤·왼쪽·오른쪽이 1장씩 있어야 해요.', + }, + CUSTOM_UPLOAD_INVALID: { + status: HttpStatus.BAD_REQUEST, + message: '꾸미기 이미지를 확인할 수 없어요. 이미지를 다시 올려 주세요.', + }, + CUSTOM_UPLOAD_EXPIRED: { + status: HttpStatus.BAD_REQUEST, + message: '꾸미기 이미지 보관 기간이 지났어요. 이미지를 다시 올려 주세요.', + }, INVALID_DAY_OF_WEEK: { status: HttpStatus.BAD_REQUEST, message: 'dayOfWeek는 0~6이어야 합니다.', diff --git a/src/features/order/constants/order-custom-upload-purposes.ts b/src/features/order/constants/order-custom-upload-purposes.ts new file mode 100644 index 00000000..5d7cfdf6 --- /dev/null +++ b/src/features/order/constants/order-custom-upload-purposes.ts @@ -0,0 +1,9 @@ +import type { OrderCustomUploadPurpose } from '@/generated/prisma/client'; +import type { UploadPurpose } from '@/global/storage/types/storage.types'; + +/** 구매자 커스텀 업로드 용도 → 저장소 정책(키 접두·형식·크기). 발급과 주문 생성의 소유 검증이 같은 표를 쓴다. */ +export const CUSTOM_UPLOAD_PURPOSES = { + RENDER: 'ORDER_CUSTOM_RENDER', + COMPOSITE: 'ORDER_CUSTOM_COMPOSITE', + REFERENCE: 'ORDER_CUSTOM_REFERENCE', +} as const satisfies Record; diff --git a/src/features/order/dto/inputs/create-order-custom.input.ts b/src/features/order/dto/inputs/create-order-custom.input.ts new file mode 100644 index 00000000..47581e0d --- /dev/null +++ b/src/features/order/dto/inputs/create-order-custom.input.ts @@ -0,0 +1,182 @@ +import { Type } from 'class-transformer'; +import { + IsArray, + IsDefined, + IsEnum, + IsIn, + IsInt, + IsNumber, + IsOptional, + IsString, + MaxLength, + ValidateNested, +} from 'class-validator'; + +import { CustomImageKind } from '@/generated/prisma/client'; + +// 저장 컬럼 길이. 개수·글자 수·좌표 범위는 상품 설정과 함께 봐야 해서 서비스가 도메인 코드로 판정한다. +const MAX_URL_LENGTH = 2048; + +export class CreateOrderSlotTextInput { + @IsString() + tokenId!: string; + + @IsOptional() + @IsString() + valueText?: string | null; +} + +export class CreateOrderFreeEditInput { + @IsInt() + posX!: number; + + @IsInt() + posY!: number; + + @IsInt() + width!: number; + + @IsInt() + height!: number; + + @IsString() + descriptionText!: string; + + @IsOptional() + @IsArray() + @IsString({ each: true }) + @MaxLength(MAX_URL_LENGTH, { each: true }) + referenceImageUrls?: string[] | null; +} + +export class CreateOrderSlotCustomInput { + @IsInt() + templateRevision!: number; + + @IsArray() + @ValidateNested({ each: true }) + @Type(() => CreateOrderSlotTextInput) + texts!: CreateOrderSlotTextInput[]; + + @IsString() + @MaxLength(MAX_URL_LENGTH) + compositeImageUrl!: string; + + @IsOptional() + @IsArray() + @ValidateNested({ each: true }) + @Type(() => CreateOrderFreeEditInput) + freeEdits?: CreateOrderFreeEditInput[] | null; +} + +export class ThreeDDesignBasicInput { + @IsString() + shape!: string; + + @IsString() + size!: string; + + @IsOptional() + @IsString() + design?: string | null; + + @IsOptional() + @IsString() + flavor?: string | null; + + @IsString() + sheetColor!: string; +} + +export class ThreeDDesignEffectInput { + @IsString() + type!: string; + + @IsInt() + intensity!: number; +} + +export class ThreeDDesignItemInput { + @IsIn(['TEXT', 'DECO']) + kind!: 'TEXT' | 'DECO'; + + @IsNumber() + x!: number; + + @IsNumber() + y!: number; + + @IsNumber() + size!: number; + + @IsDefined() + @ValidateNested() + @Type(() => ThreeDDesignEffectInput) + effect!: ThreeDDesignEffectInput; + + @IsOptional() + @IsString() + text?: string | null; + + @IsOptional() + @IsString() + color?: string | null; + + @IsOptional() + @IsString() + decoId?: string | null; +} + +export class ThreeDDesignInput { + @IsInt() + schemaVersion!: number; + + @IsDefined() + @ValidateNested() + @Type(() => ThreeDDesignBasicInput) + basic!: ThreeDDesignBasicInput; + + @IsArray() + @ValidateNested({ each: true }) + @Type(() => ThreeDDesignItemInput) + top!: ThreeDDesignItemInput[]; + + @IsArray() + @ValidateNested({ each: true }) + @Type(() => ThreeDDesignItemInput) + side!: ThreeDDesignItemInput[]; +} + +export class CreateOrderRenderImageInput { + @IsEnum(CustomImageKind) + kind!: CustomImageKind; + + @IsString() + @MaxLength(MAX_URL_LENGTH) + imageUrl!: string; +} + +export class CreateOrderThreeDCustomInput { + @IsDefined() + @ValidateNested() + @Type(() => ThreeDDesignInput) + design!: ThreeDDesignInput; + + @IsArray() + @ValidateNested({ each: true }) + @Type(() => CreateOrderRenderImageInput) + renderImages!: CreateOrderRenderImageInput[]; +} + +/** 커스텀 상품이면 그 방식의 입력 하나만 보낸다. */ +export class CreateOrderCustomInput { + @IsOptional() + @ValidateNested() + @Type(() => CreateOrderSlotCustomInput) + slot?: CreateOrderSlotCustomInput | null; + + @IsOptional() + @ValidateNested() + @Type(() => CreateOrderThreeDCustomInput) + threeD?: CreateOrderThreeDCustomInput | null; +} diff --git a/src/features/order/dto/inputs/create-order.input.spec.ts b/src/features/order/dto/inputs/create-order.input.spec.ts index f4a2bc5f..cc5190cd 100644 --- a/src/features/order/dto/inputs/create-order.input.spec.ts +++ b/src/features/order/dto/inputs/create-order.input.spec.ts @@ -111,4 +111,143 @@ describe('CreateOrderInput', () => { ); expect(errors.map((e) => e.property)).toEqual(['requestNote']); }); + + describe('custom', () => { + // 전역 ValidationPipe와 같은 옵션 — 데코레이터가 빠진 중첩 필드는 여기서 거절된다 + const STRICT = { whitelist: true, forbidNonWhitelisted: true }; + const SLOT = { + templateRevision: 1, + texts: [{ tokenId: '1', valueText: '축하해' }, { tokenId: '2' }], + compositeImageUrl: 'https://img/c.png', + freeEdits: [ + { + posX: 0, + posY: 0, + width: 10, + height: 10, + descriptionText: '꽃', + referenceImageUrls: ['https://img/r.png'], + }, + ], + }; + const THREE_D = { + design: { + schemaVersion: 1, + basic: { + shape: 'heart', + size: 'mini', + design: null, + flavor: 'cream', + sheetColor: 'white', + }, + top: [ + { + kind: 'TEXT', + x: 0.5, + y: 0.5, + size: 8, + effect: { type: 'none', intensity: 50 }, + text: '축하해', + color: '#000000', + }, + ], + side: [ + { + kind: 'DECO', + x: 0.1, + y: 0.2, + size: 20, + effect: { type: 'soft', intensity: 0 }, + decoId: 'number-1', + }, + ], + }, + renderImages: [{ kind: 'THREE_D_TOP', imageUrl: 'https://img/t.png' }], + }; + + it.each([ + ['슬롯형', { slot: SLOT }], + ['3D', { threeD: THREE_D }], + ['자유 편집·참고 사진 생략', { slot: { ...SLOT, freeEdits: undefined } }], + ])( + '%s 입력의 모든 필드가 화이트리스트를 통과한다', + async (_case, custom) => { + expect( + await validate(build({ ...VALID, custom }), STRICT), + ).toHaveLength(0); + }, + ); + + it.each<[string, object]>([ + [ + '문구 자리 tokenId가 숫자', + { slot: { ...SLOT, texts: [{ tokenId: 1 }] } }, + ], + [ + '모르는 필드', + { slot: { ...SLOT, texts: [{ tokenId: '1', extra: 'x' }] } }, + ], + [ + '자유 편집 좌표가 문자열', + { slot: { ...SLOT, freeEdits: [{ ...SLOT.freeEdits[0], posX: '1' }] } }, + ], + [ + '합성 이미지 URL 2049자', + { slot: { ...SLOT, compositeImageUrl: 'h'.repeat(2049) } }, + ], + [ + '렌더 이미지 종류가 enum 밖', + { + threeD: { + ...THREE_D, + renderImages: [{ kind: 'SIDE', imageUrl: 'https://img/t.png' }], + }, + }, + ], + [ + '3D 항목 종류가 enum 밖', + { + threeD: { + ...THREE_D, + design: { + ...THREE_D.design, + top: [{ ...THREE_D.design.top[0], kind: 'IMAGE' }], + }, + }, + }, + ], + [ + '효과 강도가 소수', + { + threeD: { + ...THREE_D, + design: { + ...THREE_D.design, + side: [ + { + ...THREE_D.design.side[0], + effect: { type: 'soft', intensity: 1.5 }, + }, + ], + }, + }, + }, + ], + [ + '디자인 basic 누락', + { + threeD: { + ...THREE_D, + design: { ...THREE_D.design, basic: undefined }, + }, + }, + ], + ])( + '중첩 입력의 형식 오류(%s)는 custom에서 거절한다', + async (_case, custom) => { + const errors = await validate(build({ ...VALID, custom }), STRICT); + expect(errors.map((e) => e.property)).toEqual(['custom']); + }, + ); + }); }); diff --git a/src/features/order/dto/inputs/create-order.input.ts b/src/features/order/dto/inputs/create-order.input.ts index baa3fc85..c0e75b43 100644 --- a/src/features/order/dto/inputs/create-order.input.ts +++ b/src/features/order/dto/inputs/create-order.input.ts @@ -1,3 +1,4 @@ +import { Type } from 'class-transformer'; import { IsArray, IsDate, @@ -10,9 +11,11 @@ import { Max, MaxLength, Min, + ValidateNested, } from 'class-validator'; import { PHONE_REGEX } from '@/features/auth'; +import { CreateOrderCustomInput } from '@/features/order/dto/inputs/create-order-custom.input'; export class CreateOrderInput { // 8~64자, 공백 문자 불가 — 형식은 길이만 제한한다. @@ -64,4 +67,9 @@ export class CreateOrderInput { @IsString() @MaxLength(500) requestNote?: string; + + @IsOptional() + @ValidateNested() + @Type(() => CreateOrderCustomInput) + custom?: CreateOrderCustomInput | null; } diff --git a/src/features/order/order-checkout.graphql b/src/features/order/order-checkout.graphql index 30a60af5..3ab6cc7e 100644 --- a/src/features/order/order-checkout.graphql +++ b/src/features/order/order-checkout.graphql @@ -4,7 +4,8 @@ extend type Mutation { 결과의 payment로 입금을 안내하고, 1시간 안에 입금이 확인되지 않으면 자동 취소된다. 판매자에게는 입금 확인 뒤에 보인다. 입금 계좌가 설정되지 않았으면 PAYMENT_ACCOUNT_NOT_CONFIGURED(SERVICE_UNAVAILABLE), 입금 대기 주문이 이미 2건이면 PENDING_PAYMENT_LIMIT_EXCEEDED(CONFLICT), 같은 계정의 다른 주문 요청이 처리 중이라 3초 안에 차례가 오지 않으면 - CONCURRENT_REQUEST(CONFLICT)다. 로그인 필수. + CONCURRENT_REQUEST(CONFLICT)다. 커스텀 상품이면 custom 입력을 검증해 주문 시점 스냅샷으로 저장하고 수량은 1이다 + (CreateOrderCustomInput 참고). 로그인 필수. """ createOrder(input: CreateOrderInput!): CreateOrderOutput! """ @@ -33,7 +34,7 @@ enum OrderCustomUploadPurpose { REFERENCE } -"""주문 생성 입력. 커스텀 필드는 커스텀 스펙 확정 후 optional로 확장 예정.""" +"""주문 생성 입력.""" input CreateOrderInput { """ 클라이언트 생성 멱등 키(8~64자). 체크아웃 진입 시 새로 만들고 재시도에는 @@ -63,6 +64,151 @@ input CreateOrderInput { expectedTotalPrice: Int! """판매자에게 전할 요청 사항(최대 500자). 공백만 보내면 없음으로 저장한다.""" requestNote: String + """ + 커스텀 입력. 상품의 커스텀 방식(ProductDetail.customMode)이 SLOT이면 slot, THREE_D면 threeD 하나만 보낸다. + 커스텀 상품인데 없으면 CUSTOM_INPUT_REQUIRED, 방식이 다르거나 커스텀 상품이 아닌데 보내면 CUSTOM_INPUT_MISMATCH, + 수량이 1이 아니면 CUSTOM_QUANTITY_FIXED, 판매자 설정이 끝나지 않은 상품이면 CUSTOM_PRODUCT_NOT_READY다. + 커스텀은 추가 금액이 없다(3D 모양·크기 등의 가격은 옵션 추가금으로만 들어온다). + """ + custom: CreateOrderCustomInput +} + +""" +주문 커스텀 입력. 이미지 URL은 모두 createOrderCustomUploadUrl로 올린 본인 파일의 publicUrl이어야 하고(용도가 맞아야 한다), +한 주문 안에서 같은 파일을 두 번 쓸 수 없다. 아니면 CUSTOM_UPLOAD_INVALID, 발급 뒤 오래돼 정리 중인 파일이면 +CUSTOM_UPLOAD_EXPIRED다. 다른 주문에 이미 쓴 파일도 CUSTOM_UPLOAD_INVALID다. +""" +input CreateOrderCustomInput { + """슬롯형(바탕 이미지 + 문구 자리) 입력. 슬롯형 상품에서만 보낸다.""" + slot: CreateOrderSlotCustomInput + """3D 입력. 3D 상품에서만 보낸다.""" + threeD: CreateOrderThreeDCustomInput +} + +""" +슬롯형 커스텀 입력. 좌표는 바탕 이미지 한 변을 10000으로 본 정수 비율이고 원점은 왼쪽 위다. +""" +input CreateOrderSlotCustomInput { + """ + 꾸미기를 시작할 때 본 ProductDetail.customTemplate.revision. 그 사이 판매자가 설정을 바꿨으면 + CUSTOM_TEMPLATE_CHANGED(CONFLICT)이고 다시 꾸며야 한다. + """ + templateRevision: Int! + """ + 문구 자리마다 1건(customTemplate.slots 전부, 중복 없이). 빠지거나 남는 자리가 있으면 CUSTOM_SLOT_TEXTS_MISMATCH다. + """ + texts: [CreateOrderSlotTextInput!]! + """구매자가 본 그대로의 합성 이미지 URL(바탕 + 문구, 용도 COMPOSITE). 대표 이미지로 저장된다.""" + compositeImageUrl: String! + """ + 자유 편집 요청(customTemplate.freeEditEnabled일 때만, 최대 5건). 규칙을 벗어나면 CUSTOM_FREE_EDIT_INVALID다. + """ + freeEdits: [CreateOrderFreeEditInput!] = [] +} + +"""문구 자리 1개의 입력.""" +input CreateOrderSlotTextInput { + tokenId: ID! + """ + 넣을 문구. 손대지 않았으면 기본 문구를 그대로 보낸다. 줄바꿈(CRLF는 LF로 바꾼다)·이모지를 쓸 수 있고 앞뒤 공백은 지운다. + 지운 뒤 비었거나 null이면 '문구 없음'이다(필수 자리면 CUSTOM_SLOT_TEXT_REQUIRED). 자리의 maxLength(코드 포인트)를 + 넘으면 CUSTOM_SLOT_TEXT_TOO_LONG이다. + """ + valueText: String +} + +"""자유 편집 요청 1건. 바탕 이미지 위 영역과 설명, 참고 사진이다.""" +input CreateOrderFreeEditInput { + """영역 왼쪽 위 x(0~10000).""" + posX: Int! + """영역 왼쪽 위 y(0~10000).""" + posY: Int! + """영역 너비(1 이상, posX + width ≤ 10000).""" + width: Int! + """영역 높이(1 이상, posY + height ≤ 10000).""" + height: Int! + """요청 설명(앞뒤 공백을 지운 뒤 1~2000자, 줄바꿈 허용).""" + descriptionText: String! + """참고 사진 URL(용도 REFERENCE, 최대 3장).""" + referenceImageUrls: [String!] = [] +} + +"""3D 커스텀 입력.""" +input CreateOrderThreeDCustomInput { + """ + 3D 디자인(JSON v1). 모양·크기·디자인·맛은 고른 옵션의 threeDKey와 같아야 한다(아니면 CUSTOM_3D_OPTIONS_CHANGED). + 카탈로그·한도 검증은 customThreeDCatalog를 따른다. + """ + design: ThreeDDesignInput! + """ + 렌더 이미지(용도 RENDER). THREE_D_TOP·FRONT·BACK·LEFT·RIGHT 정확히 1장씩이고, 아니면 CUSTOM_RENDER_IMAGES_INVALID다. + 윗면이 대표 이미지로 저장된다. + """ + renderImages: [CreateOrderRenderImageInput!]! +} + +"""3D 렌더 이미지 1장.""" +input CreateOrderRenderImageInput { + """렌더 자세.""" + kind: CustomImageKindType! + """이미지 URL.""" + imageUrl: String! +} + +""" +3D 디자인 입력(JSON v1). 저장 형태는 ThreeDDesign이고 같은 좌표계·규칙을 쓴다. 배열 순서가 그리는 순서다. +""" +input ThreeDDesignInput { + """디자인 JSON 버전. 지금은 1만 받는다(아니면 CUSTOM_3D_SCHEMA_UNSUPPORTED).""" + schemaVersion: Int! + """모양·크기·디자인·맛·시트 색.""" + basic: ThreeDDesignBasicInput! + """윗면 항목(글자·꾸미기 각 10개까지).""" + top: [ThreeDDesignItemInput!]! + """옆면 항목(글자·꾸미기 각 10개까지).""" + side: [ThreeDDesignItemInput!]! +} + +"""3D 디자인의 케이크 기본값.""" +input ThreeDDesignBasicInput { + """모양 선택지 value(고른 모양 옵션의 값).""" + shape: String! + """크기 선택지 value(고른 크기 옵션의 값).""" + size: String! + """디자인 선택지 value. 디자인 옵션을 고르지 않았으면 null(장식 없는 시트).""" + design: String + """맛 선택지 value. 맛 옵션을 고르지 않았으면 null.""" + flavor: String + """시트 색 key(카탈로그 sheetColors).""" + sheetColor: String! +} + +"""3D 디자인 항목(글자 또는 꾸미기) 1개.""" +input ThreeDDesignItemInput { + """항목 종류.""" + kind: ThreeDItemKindType! + """가로 위치(0~1, ThreeDDesign.top·side 좌표계).""" + x: Float! + """세로 위치(0~1, ThreeDDesign.top·side 좌표계).""" + y: Float! + """크기(cqw). 글자 4~30, 꾸미기 8~50.""" + size: Float! + """효과.""" + effect: ThreeDDesignEffectInput! + """글자 내용(TEXT만, 1~30 코드 포인트, 줄바꿈·이모지 허용). DECO는 null.""" + text: String + """글자색(TEXT만, #RRGGBB). DECO는 null.""" + color: String + """꾸미기 key(DECO만, 카탈로그 decos). TEXT는 null.""" + decoId: String +} + +"""3D 디자인 항목에 건 효과.""" +input ThreeDDesignEffectInput { + """효과 key(카탈로그 effects).""" + type: String! + """효과 강도(0~100 정수).""" + intensity: Int! } """주문 생성 결과 요약. 상세는 myOrder로 재조회.""" diff --git a/src/features/order/order.module.ts b/src/features/order/order.module.ts index b831613f..e0c805f8 100644 --- a/src/features/order/order.module.ts +++ b/src/features/order/order.module.ts @@ -32,6 +32,7 @@ import { OrderAdminAlertConsumer } from '@/features/order/services/order-admin-a import { AdminOrderService } from '@/features/order/services/order-admin.service'; import { OrderCheckoutService } from '@/features/order/services/order-checkout.service'; import { OrderCustomUploadCleanupScheduler } from '@/features/order/services/order-custom-upload-cleanup.scheduler'; +import { OrderCustomizationService } from '@/features/order/services/order-customization.service'; import { AdminDepositService } from '@/features/order/services/order-deposit-admin.service'; import { OrderEventsService } from '@/features/order/services/order-events.service'; import { UserOrderService } from '@/features/order/services/order-my.service'; @@ -70,6 +71,8 @@ import { StoreModule } from '@/features/store'; OrderSubscriptionResolver, OrderCheckoutService, OrderCheckoutMutationResolver, + // 주문 생성의 커스텀 입력 검증·스냅샷(상품 설정 대조, 업로드 소유) + OrderCustomizationService, // 커스텀 이미지 선업로드 기록과 미사용분 정리(worker 크론) OrderCustomUploadRepository, OrderCustomUploadCleanupScheduler, diff --git a/src/features/order/repositories/order-custom-upload-attach.helper.ts b/src/features/order/repositories/order-custom-upload-attach.helper.ts new file mode 100644 index 00000000..932fa8be --- /dev/null +++ b/src/features/order/repositories/order-custom-upload-attach.helper.ts @@ -0,0 +1,67 @@ +import { + OrderCustomUploadPurpose, + OrderCustomUploadStatus, + Prisma, +} from '@/generated/prisma/client'; + +export interface CustomUploadRef { + objectKey: string; + purpose: OrderCustomUploadPurpose; +} + +export type CustomUploadIssue = 'upload-invalid' | 'upload-expired'; + +/** + * 주문에 붙일 업로드 행을 주문 tx 안에서 잠그고 검사한다. 잠근 행은 정리 크론(SKIP LOCKED)이 건너뛰므로 + * 검사와 ATTACHED 표시 사이에 지워지지 않는다. 발급 기록이 없거나 계정·용도가 다르거나 이미 다른 주문에 쓰였으면 + * 'upload-invalid', 정리 중이면 'upload-expired'. + */ +export async function lockCustomUploadsForAttach( + tx: Prisma.TransactionClient, + accountId: bigint, + uploads: readonly CustomUploadRef[], +): Promise { + if (uploads.length === 0) return null; + const rows = await tx.$queryRaw< + { + object_key: string; + account_id: bigint; + purpose: OrderCustomUploadPurpose; + status: OrderCustomUploadStatus; + }[] + >` + SELECT object_key, account_id, purpose, status FROM order_custom_upload + WHERE object_key IN (${Prisma.join(uploads.map((u) => u.objectKey))}) + FOR UPDATE`; + // 컬럼 콜레이션이 대소문자를 가리지 않아 IN이 다른 키를 함께 잡을 수 있다 — 키 비교는 여기서 정확히 한다 + const byKey = new Map(rows.map((row) => [row.object_key, row])); + for (const upload of uploads) { + const row = byKey.get(upload.objectKey); + if ( + !row || + row.account_id !== accountId || + row.purpose !== upload.purpose || + row.status === OrderCustomUploadStatus.ATTACHED + ) { + return 'upload-invalid'; + } + if (row.status === OrderCustomUploadStatus.PURGING) return 'upload-expired'; + } + return null; +} + +/** 주문된 파일은 정리 대상에서 빠진다. lockCustomUploadsForAttach로 잠근 같은 tx에서 부른다. */ +export async function markCustomUploadsAttached( + tx: Prisma.TransactionClient, + uploads: readonly CustomUploadRef[], + now: Date, +): Promise { + if (uploads.length === 0) return; + await tx.orderCustomUpload.updateMany({ + where: { + object_key: { in: uploads.map((u) => u.objectKey) }, + status: OrderCustomUploadStatus.PENDING, + }, + data: { status: OrderCustomUploadStatus.ATTACHED, attached_at: now }, + }); +} diff --git a/src/features/order/repositories/order.repository.spec.ts b/src/features/order/repositories/order.repository.spec.ts index 7f216a73..5b047efc 100644 --- a/src/features/order/repositories/order.repository.spec.ts +++ b/src/features/order/repositories/order.repository.spec.ts @@ -975,6 +975,7 @@ describe('OrderRepository (real DB)', () => { quantity, itemSubtotalPrice: 25000 * quantity, options: [], + custom: null, }, }; } diff --git a/src/features/order/repositories/order.repository.ts b/src/features/order/repositories/order.repository.ts index 74e6df1f..5d8c98d0 100644 --- a/src/features/order/repositories/order.repository.ts +++ b/src/features/order/repositories/order.repository.ts @@ -7,6 +7,12 @@ import { import { IN_PROGRESS_ORDER_STATUSES } from '@/features/order/constants/order-status-traits'; import { orderPaymentPendingEvent } from '@/features/order/events/order-payment-pending.event'; import { orderStatusChangedEvent } from '@/features/order/events/order-status-changed.event'; +import { + lockCustomUploadsForAttach, + markCustomUploadsAttached, + type CustomUploadIssue, + type CustomUploadRef, +} from '@/features/order/repositories/order-custom-upload-attach.helper'; import { countPendingPaymentOrdersLocked, PENDING_PAYMENT_LIMIT, @@ -31,6 +37,9 @@ import { Prisma, RefundKind, type AccountType, + type CustomImageKind, + type CustomMode, + type CustomTextAlign, type PaymentStatus, } from '@/generated/prisma/client'; import { activeWhere, PrismaService } from '@/prisma'; @@ -180,6 +189,38 @@ export interface DailyCapacityGuard { dayEndUtc: Date; } +/** 주문 품목 커스텀 스냅샷. 검증·정규화를 마친 값이고, uploads는 같은 tx에서 잠가 ATTACHED로 바꿀 업로드다. */ +export interface OrderItemCustomSnapshot { + mode: Exclude; + baseImageUrl: string | null; + previewImageUrl: string; + texts: { + tokenId: bigint; + tokenKey: string; + label: string; + defaultText: string; + valueText: string | null; + sortOrder: number; + posX: number; + posY: number; + width: number; + height: number; + textColor: string; + textAlign: CustomTextAlign; + }[]; + freeEdits: { + posX: number; + posY: number; + width: number; + height: number; + descriptionText: string; + referenceImageUrls: string[]; + }[]; + design: { schemaVersion: number; json: Prisma.InputJsonObject } | null; + images: { kind: CustomImageKind; imageUrl: string }[]; + uploads: CustomUploadRef[]; +} + export interface CreatePendingPaymentOrderArgs { accountId: bigint; orderNumber: string; @@ -221,6 +262,7 @@ export interface CreatePendingPaymentOrderArgs { optionTitleSnapshot: string; optionPriceDeltaSnapshot: number; }[]; + custom: OrderItemCustomSnapshot | null; }; } @@ -246,7 +288,11 @@ const createdOrderSelect = { } satisfies Prisma.OrderSelect; export type CreatePendingPaymentOrderResult = - CreatedOrderRow | 'capacity-exceeded' | 'pending-limit' | 'lock-timeout'; + | CreatedOrderRow + | 'capacity-exceeded' + | 'pending-limit' + | 'lock-timeout' + | CustomUploadIssue; export interface ReviewableOrderItemRow { id: bigint; @@ -293,7 +339,7 @@ export class OrderRepository { } /** - * 입금 대기 주문을 결제(PENDING)와 함께 만든다. 계정 잠금(GET_LOCK) → 입금 대기 건수 → capacity 순으로 잠그고, + * 입금 대기 주문을 결제(PENDING)와 함께 만든다. 계정 잠금(GET_LOCK) → 입금 대기 건수 → capacity → 커스텀 업로드 순으로 잠그고, * capacity는 행을 FOR UPDATE로 잠근 뒤 점유를 재집계해 동시 주문이 마지막 잔여를 함께 차지하지 못하게 한다. * order_number P2002는 호출부가 재시도한다. * READ COMMITTED: REPEATABLE READ의 갭 잠금은 다른 계정끼리도 건수 잠금 읽기 → INSERT에서 교착한다. @@ -317,6 +363,12 @@ export class OrderRepository { ); if (exceeded) return 'capacity-exceeded'; } + const uploadIssue = await lockCustomUploadsForAttach( + tx, + args.accountId, + args.item.custom?.uploads ?? [], + ); + if (uploadIssue) return uploadIssue; return this.insertPendingPaymentOrder(tx, args); }), { @@ -421,6 +473,7 @@ export class OrderRepository { option_price_delta_snapshot: option.optionPriceDeltaSnapshot, })), }, + ...(args.item.custom && customItemData(args.item.custom)), }, }, payment: { @@ -446,6 +499,11 @@ export class OrderRepository { }, select: createdOrderSelect, }); + await markCustomUploadsAttached( + tx, + args.item.custom?.uploads ?? [], + args.now, + ); // 관리자 경보 원천. 판매자 '새 주문'(order.submitted)은 입금 확인 때 나간다 await this.outbox.publish( tx, @@ -1136,3 +1194,58 @@ export class OrderRepository { return { counts, amountSum }; } } + +/** 품목 생성에 펼쳐 넣는 커스텀 스냅샷. 자유 편집·참고 사진 순서는 입력 순서다. */ +function customItemData(custom: OrderItemCustomSnapshot) { + return { + custom_mode_snapshot: custom.mode, + custom_base_image_url_snapshot: custom.baseImageUrl, + custom_preview_image_url: custom.previewImageUrl, + custom_texts: { + create: custom.texts.map((text) => ({ + token_id: text.tokenId, + token_key_snapshot: text.tokenKey, + label_snapshot: text.label, + default_text_snapshot: text.defaultText, + value_text: text.valueText, + sort_order: text.sortOrder, + pos_x: text.posX, + pos_y: text.posY, + width: text.width, + height: text.height, + text_color: text.textColor, + text_align: text.textAlign, + })), + }, + free_edits: { + create: custom.freeEdits.map((edit, index) => ({ + pos_x: edit.posX, + pos_y: edit.posY, + width: edit.width, + height: edit.height, + description_text: edit.descriptionText, + sort_order: index, + attachments: { + create: edit.referenceImageUrls.map((url, order) => ({ + image_url: url, + sort_order: order, + })), + }, + })), + }, + custom_images: { + create: custom.images.map((image) => ({ + kind: image.kind, + image_url: image.imageUrl, + })), + }, + ...(custom.design && { + custom_design: { + create: { + schema_version: custom.design.schemaVersion, + design_json: custom.design.json, + }, + }, + }), + }; +} diff --git a/src/features/order/resolvers/order-checkout-mutation.resolver.spec.ts b/src/features/order/resolvers/order-checkout-mutation.resolver.spec.ts index 091deeec..bb68507d 100644 --- a/src/features/order/resolvers/order-checkout-mutation.resolver.spec.ts +++ b/src/features/order/resolvers/order-checkout-mutation.resolver.spec.ts @@ -7,6 +7,7 @@ import { OrderRepository } from '@/features/order/repositories/order.repository' import { PaymentSettingRepository } from '@/features/order/repositories/payment-setting.repository'; import { OrderCheckoutMutationResolver } from '@/features/order/resolvers/order-checkout-mutation.resolver'; import { OrderCheckoutService } from '@/features/order/services/order-checkout.service'; +import { OrderCustomizationService } from '@/features/order/services/order-customization.service'; import { ProductRepository } from '@/features/product'; import { StorePickupScheduleService } from '@/features/store'; import { StoreRepository } from '@/features/store/repositories/store.repository'; @@ -44,6 +45,7 @@ describe('OrderCheckout Mutation Resolver (real DB)', () => { providers: [ OrderCheckoutMutationResolver, OrderCheckoutService, + OrderCustomizationService, OrderRepository, OrderCustomUploadRepository, ...s3TestProviders(), diff --git a/src/features/order/services/order-checkout.service.custom.spec.ts b/src/features/order/services/order-checkout.service.custom.spec.ts new file mode 100644 index 00000000..d1690fc1 --- /dev/null +++ b/src/features/order/services/order-checkout.service.custom.spec.ts @@ -0,0 +1,601 @@ +import { ClockService } from '@/common/providers/clock.service'; +import { RandomService } from '@/common/providers/random.service'; +import { AUDIT_LOG_REPOSITORY } from '@/features/audit-log'; +import { AuditLogRepository } from '@/features/audit-log/repositories/audit-log.repository'; +import type { + CreateOrderCustomInput, + CreateOrderSlotCustomInput, + CreateOrderThreeDCustomInput, +} from '@/features/order/dto/inputs/create-order-custom.input'; +import type { CreateOrderInput } from '@/features/order/dto/inputs/create-order.input'; +import { OrderCustomUploadRepository } from '@/features/order/repositories/order-custom-upload.repository'; +import { OrderRepository } from '@/features/order/repositories/order.repository'; +import { PaymentSettingRepository } from '@/features/order/repositories/payment-setting.repository'; +import { OrderCheckoutService } from '@/features/order/services/order-checkout.service'; +import { OrderCustomizationService } from '@/features/order/services/order-customization.service'; +import { OutboxPublisher } from '@/features/outbox/services/outbox-publisher.service'; +import { ProductRepository } from '@/features/product'; +import { StorePickupScheduleService } from '@/features/store'; +import { StoreRepository } from '@/features/store/repositories/store.repository'; +import type { + Account, + CustomImageKind, + OrderCustomUploadPurpose, + PrismaClient, + Product, +} from '@/generated/prisma/client'; +import { UPLOAD_POLICIES } from '@/global/storage/constants/storage.constants'; +import { bookedQuantityProviders } from '@/test/booked-quantity'; +import { disconnectTestPrismaClient } from '@/test/db/prisma-test-client'; +import { closeTruncateConnection, truncateAll } from '@/test/db/truncate'; +import { + createAccount, + createCustomTemplate, + createCustomTextToken, + createOrderCustomUpload, + createPaymentSetting, + createProduct, + createStore, + createUserProfile, +} from '@/test/factories'; +import { createTestingModuleWithRealDb } from '@/test/modules/testing-module.builder'; +import { outboxPublisherProviders } from '@/test/outbox'; +import { s3TestProviders, TEST_S3_CONFIG } from '@/test/storage/s3-test.helper'; + +// 2026-09-16(수) 16:00 KST 고정 +const NOW = new Date('2026-09-16T07:00:00.000Z'); +/** 2026-09-18(금) 14:00 KST */ +const PICKUP_AT = new Date('2026-09-18T05:00:00.000Z'); + +const PURPOSE_POLICY = { + RENDER: UPLOAD_POLICIES.ORDER_CUSTOM_RENDER, + COMPOSITE: UPLOAD_POLICIES.ORDER_CUSTOM_COMPOSITE, + REFERENCE: UPLOAD_POLICIES.ORDER_CUSTOM_REFERENCE, +} as const; +const RENDER_KINDS = [ + 'THREE_D_TOP', + 'THREE_D_FRONT', + 'THREE_D_BACK', + 'THREE_D_LEFT', + 'THREE_D_RIGHT', +] as const satisfies readonly CustomImageKind[]; + +describe('OrderCheckoutService 커스텀 주문 (real DB)', () => { + let service: OrderCheckoutService; + let orderRepo: OrderRepository; + let outbox: OutboxPublisher; + let clock: ClockService; + let prisma: PrismaClient; + + beforeAll(async () => { + const { module, prisma: p } = await createTestingModuleWithRealDb({ + providers: [ + OrderCheckoutService, + OrderCustomizationService, + OrderRepository, + OrderCustomUploadRepository, + ...s3TestProviders(), + PaymentSettingRepository, + ProductRepository, + { provide: AUDIT_LOG_REPOSITORY, useClass: AuditLogRepository }, + StorePickupScheduleService, + StoreRepository, + ClockService, + RandomService, + ...outboxPublisherProviders({ clock: true }), + ...bookedQuantityProviders(), + ], + }); + service = module.get(OrderCheckoutService); + orderRepo = module.get(OrderRepository); + outbox = module.get(OutboxPublisher); + clock = module.get(ClockService); + prisma = p; + }); + + afterAll(async () => { + await closeTruncateConnection(); + await disconnectTestPrismaClient(); + }); + + beforeEach(async () => { + await truncateAll(); + await createPaymentSetting(prisma); + jest.spyOn(clock, 'now').mockReturnValue(NOW); + }); + + afterEach(() => { + jest.restoreAllMocks(); + }); + + async function makeOpenStoreId(): Promise { + const store = await createStore(prisma, { + pickup_slot_interval_minutes: 30, + min_lead_time_minutes: 60, + }); + for (let dayOfWeek = 0; dayOfWeek < 7; dayOfWeek += 1) { + await prisma.storeBusinessHour.create({ + data: { + store_id: store.id, + day_of_week: dayOfWeek, + is_closed: false, + open_time: new Date(Date.UTC(1970, 0, 1, 10)), + close_time: new Date(Date.UTC(1970, 0, 1, 20)), + }, + }); + } + return store.id; + } + + async function makeBuyer(): Promise { + const account = await createAccount(prisma, { account_type: 'USER' }); + await createUserProfile(prisma, { + account_id: account.id, + phone_number: '010-1234-5678', + }); + return account; + } + + /** 발급 기록이 있는 본인 업로드의 공개 URL. */ + async function upload( + buyer: Account, + purpose: OrderCustomUploadPurpose, + name: string, + row: Parameters[1] = {}, + ): Promise { + const key = `${PURPOSE_POLICY[purpose].keyPrefix}/${buyer.id}/2026-09-16/${name}`; + await createOrderCustomUpload(prisma, { + account_id: buyer.id, + purpose, + object_key: key, + ...row, + }); + return `https://${TEST_S3_CONFIG.bucket}.s3.${TEST_S3_CONFIG.region}.amazonaws.com/${key}`; + } + + async function uploadStatuses() { + const rows = await prisma.orderCustomUpload.findMany({ + orderBy: { object_key: 'asc' }, + }); + return rows.map((row) => [row.object_key.split('/').pop(), row.status]); + } + + let idemSeq = 0; + function input( + product: Product, + expectedTotalPrice: number, + custom: CreateOrderCustomInput, + overrides: Partial = {}, + ): CreateOrderInput { + idemSeq += 1; + return { + idempotencyKey: `custom-idem-${idemSeq}`, + productId: product.id.toString(), + optionItemIds: [], + pickupAt: PICKUP_AT, + expectedTotalPrice, + custom, + ...overrides, + }; + } + + describe('슬롯형', () => { + /** 정가 30000·판매가 25000, 필수 자리(이름)·선택 자리(문구), 자유 편집 켜짐. */ + async function setup() { + const buyer = await makeBuyer(); + const product = await createProduct(prisma, { + store_id: await makeOpenStoreId(), + regular_price: 30000, + sale_price: 25000, + }); + await prisma.product.update({ + where: { id: product.id }, + data: { custom_mode: 'SLOT' }, + }); + const template = await createCustomTemplate(prisma, { + product_id: product.id, + base_image_url: 'https://i.example/base-square.png', + free_edit_enabled: true, + revision: 4, + }); + const name = await createCustomTextToken(prisma, { + template_id: template.id, + token_key: 'name', + label: '이름', + default_text: '민지', + max_length: 10, + sort_order: 0, + pos_x: 1000, + pos_y: 1000, + width: 8000, + height: 1000, + text_color: '#FF8800', + text_align: 'LEFT', + }); + const phrase = await createCustomTextToken(prisma, { + template_id: template.id, + token_key: 'phrase', + label: '문구', + default_text: '축하해', + is_required: false, + sort_order: 1, + }); + const composite = await upload(buyer, 'COMPOSITE', 'composite.png'); + const reference = await upload(buyer, 'REFERENCE', 'ref.png'); + const slot: CreateOrderSlotCustomInput = { + templateRevision: 4, + texts: [ + { tokenId: phrase.id.toString(), valueText: null }, + { tokenId: name.id.toString(), valueText: '지수\r\n🎂' }, + ], + compositeImageUrl: composite, + freeEdits: [ + { + posX: 0, + posY: 5000, + width: 10000, + height: 5000, + descriptionText: ' 아래쪽에 꽃 ', + referenceImageUrls: [reference], + }, + ], + }; + return { buyer, product, name, phrase, composite, reference, slot }; + } + + it('문구 자리·자유 편집·합성 이미지를 스냅샷하고 업로드를 ATTACHED로 바꾼다(추가 금액 없음)', async () => { + const { buyer, product, name, phrase, composite, reference, slot } = + await setup(); + + const created = await service.createOrder( + buyer.id, + input(product, 25000, { slot }), + ); + + expect(created.totalPrice).toBe(25000); + const item = await prisma.orderItem.findFirstOrThrow({ + where: { order_id: BigInt(created.orderId) }, + include: { + custom_texts: { orderBy: { sort_order: 'asc' } }, + free_edits: { include: { attachments: true } }, + custom_images: true, + custom_design: true, + }, + }); + expect(item).toMatchObject({ + quantity: 1, + item_subtotal_price: 25000, + custom_mode_snapshot: 'SLOT', + custom_base_image_url_snapshot: 'https://i.example/base-square.png', + custom_preview_image_url: composite, + custom_design: null, + custom_images: [{ kind: 'SLOT_COMPOSITE', image_url: composite }], + }); + expect(item.custom_texts).toMatchObject([ + { + token_id: name.id, + token_key_snapshot: 'name', + label_snapshot: '이름', + default_text_snapshot: '민지', + value_text: '지수\n🎂', + sort_order: 0, + pos_x: 1000, + pos_y: 1000, + width: 8000, + height: 1000, + text_color: '#FF8800', + text_align: 'LEFT', + }, + { + token_id: phrase.id, + label_snapshot: '문구', + default_text_snapshot: '축하해', + value_text: null, + }, + ]); + expect(item.free_edits).toMatchObject([ + { + pos_x: 0, + pos_y: 5000, + width: 10000, + height: 5000, + description_text: '아래쪽에 꽃', + sort_order: 0, + attachments: [{ image_url: reference, sort_order: 0 }], + }, + ]); + expect(await uploadStatuses()).toEqual([ + ['composite.png', 'ATTACHED'], + ['ref.png', 'ATTACHED'], + ]); + const attached = await prisma.orderCustomUpload.findFirstOrThrow(); + expect(attached.attached_at).toEqual(NOW); + }); + + it('한 번 주문에 쓴 이미지는 다른 주문에 쓸 수 없다', async () => { + const { buyer, product, slot } = await setup(); + await service.createOrder(buyer.id, input(product, 25000, { slot })); + + await expect( + service.createOrder(buyer.id, input(product, 25000, { slot })), + ).rejects.toThrowDomain('CUSTOM_UPLOAD_INVALID'); + expect(await prisma.order.count()).toBe(1); + }); + + it.each<[string, Parameters[1], string]>([ + [ + '다른 주문에 붙은 업로드', + { status: 'ATTACHED' }, + 'CUSTOM_UPLOAD_INVALID', + ], + [ + '정리 중인 업로드', + { status: 'PURGING', purge_started_at: NOW }, + 'CUSTOM_UPLOAD_EXPIRED', + ], + [ + '기록의 용도가 다른 업로드', + { purpose: 'RENDER' }, + 'CUSTOM_UPLOAD_INVALID', + ], + ])('%s는 거절하고 주문·연결을 남기지 않는다', async (_case, row, code) => { + const { buyer, product, slot } = await setup(); + slot.freeEdits![0].referenceImageUrls = [ + await upload(buyer, 'REFERENCE', 'bad.png', row), + ]; + + await expect( + service.createOrder(buyer.id, input(product, 25000, { slot })), + ).rejects.toThrowDomain(code); + expect(await prisma.order.count()).toBe(0); + expect( + await prisma.orderCustomUpload.count({ + where: { status: 'ATTACHED', attached_at: NOW }, + }), + ).toBe(0); + }); + + it('발급 기록이 없는 본인 경로 URL·다른 계정 기록·대소문자만 같은 키면 CUSTOM_UPLOAD_INVALID다', async () => { + const { buyer, product, slot } = await setup(); + const other = await createAccount(prisma, { account_type: 'USER' }); + const unissued = `https://${TEST_S3_CONFIG.bucket}.s3.${TEST_S3_CONFIG.region}.amazonaws.com/order-custom/references/${buyer.id}/2026-09-16/none.png`; + const othersRow = await upload(buyer, 'REFERENCE', 'other.png', { + account_id: other.id, + }); + // 키 컬럼 콜레이션은 대소문자를 가리지 않는다 — 다른 키로 같은 행을 붙이지 못해야 한다 + const caseVariant = ( + await upload(buyer, 'REFERENCE', 'case.png') + ).replace('case.png', 'CASE.png'); + + for (const url of [unissued, othersRow, caseVariant]) { + slot.freeEdits![0].referenceImageUrls = [url]; + await expect( + service.createOrder(buyer.id, input(product, 25000, { slot })), + ).rejects.toThrowDomain('CUSTOM_UPLOAD_INVALID'); + } + expect(await prisma.order.count()).toBe(0); + }); + + it('주문 tx가 연결 뒤에 실패하면 업로드는 PENDING으로 남는다', async () => { + const { buyer, product, slot } = await setup(); + jest + .spyOn(outbox, 'publish') + .mockRejectedValueOnce(new Error('outbox down')); + + await expect( + service.createOrder(buyer.id, input(product, 25000, { slot })), + ).rejects.toThrow('outbox down'); + + expect(await prisma.order.count()).toBe(0); + expect(await prisma.orderItemCustomText.count()).toBe(0); + expect(await uploadStatuses()).toEqual([ + ['composite.png', 'PENDING'], + ['ref.png', 'PENDING'], + ]); + // 같은 업로드로 다시 주문할 수 있다 + await expect( + service.createOrder(buyer.id, input(product, 25000, { slot })), + ).resolves.toMatchObject({ status: 'PENDING_PAYMENT' }); + }); + + it('같은 키·같은 커스텀 입력의 재요청은 기존 주문을 돌려주고, 커스텀만 달라도 IDEMPOTENCY_KEY_INPUT_MISMATCH다', async () => { + const { buyer, product, slot } = await setup(); + const first = input(product, 25000, { slot }); + const created = await service.createOrder(buyer.id, first); + + await expect( + service.createOrder(buyer.id, { + ...first, + custom: { slot: { ...slot, texts: [...slot.texts].reverse() } }, + }), + ).resolves.toEqual(created); + await expect( + service.createOrder(buyer.id, { + ...first, + custom: { + slot: { + ...slot, + texts: [slot.texts[0], { ...slot.texts[1], valueText: '지수' }], + }, + }, + }), + ).rejects.toThrowDomain('IDEMPOTENCY_KEY_INPUT_MISMATCH'); + expect(await prisma.order.count()).toBe(1); + }); + + it('같은 키 재시도가 사전 조회를 지나 업로드 잠금에서 걸리면 내 주문을 replay한다', async () => { + const { buyer, product, slot } = await setup(); + const first = input(product, 25000, { slot }); + const created = await service.createOrder(buyer.id, first); + + const raceOnce = () => + jest + .spyOn(orderRepo, 'findOrderByIdempotencyKey') + .mockResolvedValueOnce(null); + raceOnce(); + await expect(service.createOrder(buyer.id, first)).resolves.toEqual( + created, + ); + raceOnce(); + await expect( + service.createOrder(buyer.id, { ...first, requestNote: '다른 메모' }), + ).rejects.toThrowDomain('IDEMPOTENCY_KEY_INPUT_MISMATCH'); + expect(await prisma.order.count()).toBe(1); + }); + + it('판매자가 설정을 바꿨으면(revision) 주문을 만들지 않고 업로드도 그대로 둔다', async () => { + const { buyer, product, slot } = await setup(); + await prisma.productCustomTemplate.update({ + where: { product_id: product.id }, + data: { revision: 5 }, + }); + + await expect( + service.createOrder(buyer.id, input(product, 25000, { slot })), + ).rejects.toThrowDomain('CUSTOM_TEMPLATE_CHANGED'); + expect(await prisma.order.count()).toBe(0); + expect(await uploadStatuses()).toEqual([ + ['composite.png', 'PENDING'], + ['ref.png', 'PENDING'], + ]); + }); + }); + + describe('3D', () => { + /** 정가 20000, 모양(하트 +1000)·크기(1호 +5000) 필수 그룹. */ + async function setup() { + const buyer = await makeBuyer(); + const product = await createProduct(prisma, { + store_id: await makeOpenStoreId(), + regular_price: 20000, + }); + await prisma.product.update({ + where: { id: product.id }, + data: { custom_mode: 'THREE_D' }, + }); + const items: bigint[] = []; + for (const [name, key, delta] of [ + ['모양', 'shape.heart', 1000], + ['크기', 'size.no1', 5000], + ] as const) { + const group = await prisma.productOptionGroup.create({ + data: { product_id: product.id, name, min_select: 1, max_select: 1 }, + }); + const item = await prisma.productOptionItem.create({ + data: { + option_group_id: group.id, + title: name, + price_delta: delta, + three_d_key: key, + }, + }); + items.push(item.id); + } + const renders: { kind: CustomImageKind; imageUrl: string }[] = []; + for (const kind of RENDER_KINDS) { + renders.push({ + kind, + imageUrl: await upload(buyer, 'RENDER', `${kind}.png`), + }); + } + const threeD: CreateOrderThreeDCustomInput = { + design: { + schemaVersion: 1, + basic: { shape: 'heart', size: 'no1', sheetColor: 'white' }, + top: [ + { + kind: 'TEXT', + x: 0.5, + y: 0.5, + size: 10, + effect: { type: 'none', intensity: 50 }, + text: '축하해', + color: '#ff0000', + }, + ], + side: [], + }, + renderImages: renders, + }; + return { + buyer, + product, + optionItemIds: items.map(String), + renders, + threeD, + }; + } + + it('디자인 JSON v1과 렌더 5장을 저장하고 윗면을 대표 이미지로 둔다(가격은 옵션 추가금만)', async () => { + const { buyer, product, optionItemIds, renders, threeD } = await setup(); + + const created = await service.createOrder( + buyer.id, + input(product, 26000, { threeD }, { optionItemIds }), + ); + + expect(created.totalPrice).toBe(26000); + const item = await prisma.orderItem.findFirstOrThrow({ + where: { order_id: BigInt(created.orderId) }, + include: { + custom_design: true, + custom_images: { orderBy: { kind: 'asc' } }, + custom_texts: true, + free_edits: true, + }, + }); + expect(item).toMatchObject({ + custom_mode_snapshot: 'THREE_D', + custom_base_image_url_snapshot: null, + custom_preview_image_url: renders[0].imageUrl, + custom_texts: [], + free_edits: [], + custom_design: { + schema_version: 1, + design_json: { + schemaVersion: 1, + basic: { + shape: 'heart', + size: 'no1', + design: null, + flavor: null, + sheetColor: 'white', + }, + top: [{ kind: 'TEXT', text: '축하해', color: '#FF0000' }], + side: [], + }, + }, + }); + expect( + item.custom_images.map((image) => [image.kind, image.image_url]), + ).toEqual(renders.map((r) => [r.kind, r.imageUrl])); + expect( + await prisma.orderCustomUpload.count({ where: { status: 'ATTACHED' } }), + ).toBe(5); + }); + + it('고른 옵션과 디자인이 다르면 CUSTOM_3D_OPTIONS_CHANGED다', async () => { + const { buyer, product, optionItemIds, threeD } = await setup(); + threeD.design.basic.size = 'mini'; + + await expect( + service.createOrder( + buyer.id, + input(product, 26000, { threeD }, { optionItemIds }), + ), + ).rejects.toThrowDomain('CUSTOM_3D_OPTIONS_CHANGED'); + expect(await prisma.order.count()).toBe(0); + }); + + it('3D 상품을 커스텀 없이 주문하면 CUSTOM_INPUT_REQUIRED다', async () => { + const { buyer, product, optionItemIds } = await setup(); + + await expect( + service.createOrder(buyer.id, { + ...input(product, 26000, {}, { optionItemIds }), + custom: undefined, + }), + ).rejects.toThrowDomain('CUSTOM_INPUT_REQUIRED'); + }); + }); +}); diff --git a/src/features/order/services/order-checkout.service.spec.ts b/src/features/order/services/order-checkout.service.spec.ts index 94bd0a2e..85cd9a87 100644 --- a/src/features/order/services/order-checkout.service.spec.ts +++ b/src/features/order/services/order-checkout.service.spec.ts @@ -15,6 +15,7 @@ import { pendingPaymentLockName } from '@/features/order/repositories/order-pend import { OrderRepository } from '@/features/order/repositories/order.repository'; import { PaymentSettingRepository } from '@/features/order/repositories/payment-setting.repository'; import { OrderCheckoutService } from '@/features/order/services/order-checkout.service'; +import { OrderCustomizationService } from '@/features/order/services/order-customization.service'; import { OrderEventsService } from '@/features/order/services/order-events.service'; import { ProductRepository } from '@/features/product'; import { StorePickupScheduleService } from '@/features/store'; @@ -67,6 +68,7 @@ describe('OrderCheckoutService (real DB)', () => { const { module, prisma: p } = await createTestingModuleWithRealDb({ providers: [ OrderCheckoutService, + OrderCustomizationService, OrderRepository, OrderCustomUploadRepository, ...s3TestProviders(), diff --git a/src/features/order/services/order-checkout.service.ts b/src/features/order/services/order-checkout.service.ts index 45fb0d37..fed03626 100644 --- a/src/features/order/services/order-checkout.service.ts +++ b/src/features/order/services/order-checkout.service.ts @@ -1,6 +1,6 @@ import { Injectable } from '@nestjs/common'; -import { DomainException } from '@/common/errors/error-catalog'; +import { DomainException, type ErrorCode } from '@/common/errors/error-catalog'; import { ClockService } from '@/common/providers/clock.service'; import { RandomService } from '@/common/providers/random.service'; import { parseId } from '@/common/utils/id-parser'; @@ -9,14 +9,17 @@ import { uniqueConstraintName } from '@/common/utils/prisma-error'; import { buildRegionLabel } from '@/common/utils/region-label'; import { codePointLength } from '@/common/utils/text-cleaner'; import { evaluateActiveUserAccount } from '@/features/auth'; +import { CUSTOM_UPLOAD_PURPOSES } from '@/features/order/constants/order-custom-upload-purposes'; import type { CreateOrderInput } from '@/features/order/dto/inputs/create-order.input'; import { OrderCustomUploadRepository } from '@/features/order/repositories/order-custom-upload.repository'; import { OrderRepository, type CreatedOrderRow, type CreatePendingPaymentOrderArgs, + type CreatePendingPaymentOrderResult, } from '@/features/order/repositories/order.repository'; import { PaymentSettingRepository } from '@/features/order/repositories/payment-setting.repository'; +import { OrderCustomizationService } from '@/features/order/services/order-customization.service'; import { hashCreateOrderInput } from '@/features/order/services/order-input-hash.helper'; import { toOrderPaymentOutput } from '@/features/order/services/order-payment-mappers.helper'; import type { CreateOrderOutput } from '@/features/order/types/create-order-output.type'; @@ -27,10 +30,7 @@ import { type OrderCustomUploadPurpose, } from '@/generated/prisma/client'; import { S3Service } from '@/global/storage/s3.service'; -import type { - CreateUploadUrlOutput, - UploadPurpose, -} from '@/global/storage/types/storage.types'; +import type { CreateUploadUrlOutput } from '@/global/storage/types/storage.types'; // 0/O·1/I 등 혼동 문자를 뺀 대문자 영숫자. 주문번호 무작위부에 사용. const ORDER_NUMBER_ALPHABET = 'ABCDEFGHJKMNPQRSTUVWXYZ23456789'; @@ -47,11 +47,16 @@ const PAYMENT_WINDOW_MS = 60 * 60_000; /** 은행 입금자명과 대조하는 값이라 자르지 않고 입력을 요구한다. */ const MAX_DEPOSITOR_NAME_LENGTH = 20; -const CUSTOM_UPLOAD_PURPOSES = { - RENDER: 'ORDER_CUSTOM_RENDER', - COMPOSITE: 'ORDER_CUSTOM_COMPOSITE', - REFERENCE: 'ORDER_CUSTOM_REFERENCE', -} as const satisfies Record; +/** tx 안 잠금 재검사의 거절 결과 → 같은 키 replay가 아니면 내는 코드. */ +const LOCKED_REJECT_CODES = { + 'capacity-exceeded': 'PICKUP_NOT_AVAILABLE', + 'pending-limit': 'PENDING_PAYMENT_LIMIT_EXCEEDED', + 'upload-invalid': 'CUSTOM_UPLOAD_INVALID', + 'upload-expired': 'CUSTOM_UPLOAD_EXPIRED', +} as const satisfies Record< + Exclude, + ErrorCode +>; interface ResolvedOptionSelection { optionGroupId: bigint; @@ -59,6 +64,7 @@ interface ResolvedOptionSelection { groupNameSnapshot: string; optionTitleSnapshot: string; optionPriceDeltaSnapshot: number; + threeDKey: string | null; } @Injectable() @@ -72,6 +78,7 @@ export class OrderCheckoutService { private readonly paymentSettings: PaymentSettingRepository, private readonly customUploads: OrderCustomUploadRepository, private readonly s3: S3Service, + private readonly customization: OrderCustomizationService, ) {} /** @@ -142,6 +149,13 @@ export class OrderCheckoutService { } const selections = this.resolveOptionSelections(product, optionItemIds); + const custom = this.customization.resolve({ + product, + selectedThreeDKeys: selections.map((selection) => selection.threeDKey), + quantity, + custom: input.custom, + accountId, + }); const buyer = this.resolveBuyerInfo(buyerProfile, input); const depositorName = resolveDepositorName(input.depositorName, buyer.name); @@ -241,6 +255,7 @@ export class OrderCheckoutService { quantity, itemSubtotalPrice, options: selections, + custom, }, }); @@ -283,6 +298,7 @@ export class OrderCheckoutService { groupNameSnapshot: group.name, optionTitleSnapshot: item.title, optionPriceDeltaSnapshot: item.price_delta, + threeDKey: item.three_d_key, }); groupIdByItemId.set(item.id.toString(), group.id.toString()); } @@ -358,16 +374,14 @@ export class OrderCheckoutService { if (created === 'lock-timeout') { throw new DomainException('CONCURRENT_REQUEST'); } - if (created === 'capacity-exceeded' || created === 'pending-limit') { - // 트랜잭션 안 잠금 재검사에서 거절됐다. 자리를 채운 것이 같은 키의 내 주문(응답 유실 재시도)일 수 있어 - // 거절 전에 replay를 확인한다. + if (typeof created === 'string') { + // 트랜잭션 안 잠금 재검사에서 거절됐다. 자리·건수를 채우거나 업로드를 붙인 것이 같은 키의 내 주문 + // (응답 유실 재시도)일 수 있어 거절 전에 replay를 확인한다. return this.replayOrReject( args.accountId, args.idempotencyKey, args.idempotencyInputHash, - created === 'capacity-exceeded' - ? 'PICKUP_NOT_AVAILABLE' - : 'PENDING_PAYMENT_LIMIT_EXCEEDED', + LOCKED_REJECT_CODES[created], ); } return created; @@ -415,7 +429,7 @@ export class OrderCheckoutService { accountId: bigint, idempotencyKey: string, inputHash: string, - rejectCode: 'PICKUP_NOT_AVAILABLE' | 'PENDING_PAYMENT_LIMIT_EXCEEDED', + rejectCode: ErrorCode, ): Promise { const existing = await this.orderRepo.findOrderByIdempotencyKey( accountId, diff --git a/src/features/order/services/order-customization.service.spec.ts b/src/features/order/services/order-customization.service.spec.ts new file mode 100644 index 00000000..d340dc9e --- /dev/null +++ b/src/features/order/services/order-customization.service.spec.ts @@ -0,0 +1,792 @@ +import { Test } from '@nestjs/testing'; + +import type { + CreateOrderCustomInput, + CreateOrderFreeEditInput, + CreateOrderSlotCustomInput, + CreateOrderThreeDCustomInput, +} from '@/features/order/dto/inputs/create-order-custom.input'; +import { OrderCustomizationService } from '@/features/order/services/order-customization.service'; +import type { ProductDetailRow } from '@/features/product'; +import type { CustomImageKind, CustomMode } from '@/generated/prisma/client'; +import type { UploadPurpose } from '@/global/storage/types/storage.types'; +import { + FOREIGN_UPLOAD_URL, + ownedUploadUrl, + s3TestProviders, +} from '@/test/storage/s3-test.helper'; + +const ACCOUNT = 7n; +const BASE_IMAGE = 'https://i.example/base.png'; +const url = (purpose: UploadPurpose, name: string) => + ownedUploadUrl(purpose, ACCOUNT, name); +const keyOf = (u: string) => new URL(u).pathname.slice(1); +const COMPOSITE = url('ORDER_CUSTOM_COMPOSITE', 'composite.png'); +const RENDER_KINDS = [ + 'THREE_D_TOP', + 'THREE_D_FRONT', + 'THREE_D_BACK', + 'THREE_D_LEFT', + 'THREE_D_RIGHT', +] as const satisfies readonly CustomImageKind[]; +const renderUrl = (kind: CustomImageKind) => + url('ORDER_CUSTOM_RENDER', `${kind}.png`); + +type Template = NonNullable; +type Token = Template['text_tokens'][number]; +type OptionGroup = ProductDetailRow['option_groups'][number]; + +function token(id: bigint, overrides: Partial = {}): Token { + return { + id, + token_key: `slot${id}`, + label: `자리${id}`, + default_text: '축하해', + max_length: 20, + is_required: true, + pos_x: 1000, + pos_y: 2000, + width: 8000, + height: 1500, + text_color: '#FF0000', + text_align: 'LEFT', + sort_order: Number(id), + ...overrides, + }; +} + +function product( + mode: CustomMode, + overrides: Partial = {}, +): ProductDetailRow { + return { + id: 1n, + store_id: 1n, + name: '케이크', + description: null, + purchase_notice: null, + regular_price: 30000, + sale_price: null, + currency: 'KRW', + preparation_time_minutes: 180, + custom_mode: mode, + custom_template: { + base_image_url: BASE_IMAGE, + free_edit_enabled: true, + revision: 3, + deleted_at: null, + text_tokens: [token(11n), token(12n, { is_required: false })], + }, + store: { + store_name: '매장', + address_city: null, + address_neighborhood: null, + region: null, + }, + images: [], + option_groups: [ + group(1n, ['shape.heart', 'shape.circle']), + group(2n, ['size.mini', 'size.no1']), + group(3n, ['flavor.cream'], { is_required: false, min_select: 0 }), + ], + ...overrides, + }; +} + +function group( + id: bigint, + keys: string[], + overrides: Partial = {}, +): OptionGroup { + return { + id, + name: `그룹${id}`, + description: null, + is_active: true, + is_required: true, + min_select: 1, + max_select: 1, + sort_order: Number(id), + option_items: keys.map((key, index) => ({ + id: id * 100n + BigInt(index), + title: key, + description: null, + image_url: null, + price_delta: 0, + sort_order: index, + is_active: true, + three_d_key: key, + })), + ...overrides, + }; +} + +function template(overrides: Partial