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.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..09e270f8 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`), `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) | ### 자주 쓰는 스크립트 @@ -329,6 +330,8 @@ 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`은 대상 수만 출력합니다 | +| `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 00000000..44ef5ff3 Binary files /dev/null and b/assets/custom-3d-catalog/v1/deco/number-0.png differ diff --git a/assets/custom-3d-catalog/v1/deco/number-1.png b/assets/custom-3d-catalog/v1/deco/number-1.png new file mode 100644 index 00000000..061f4d88 Binary files /dev/null and b/assets/custom-3d-catalog/v1/deco/number-1.png differ 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 00000000..d797d812 Binary files /dev/null and b/assets/custom-3d-catalog/v1/deco/number-2.png differ diff --git a/assets/custom-3d-catalog/v1/deco/number-3.png b/assets/custom-3d-catalog/v1/deco/number-3.png new file mode 100644 index 00000000..fa40ca09 Binary files /dev/null and b/assets/custom-3d-catalog/v1/deco/number-3.png differ diff --git a/assets/custom-3d-catalog/v1/deco/number-4.png b/assets/custom-3d-catalog/v1/deco/number-4.png new file mode 100644 index 00000000..acdab7b3 Binary files /dev/null and b/assets/custom-3d-catalog/v1/deco/number-4.png differ diff --git a/assets/custom-3d-catalog/v1/deco/number-5.png b/assets/custom-3d-catalog/v1/deco/number-5.png new file mode 100644 index 00000000..e1e5ec18 Binary files /dev/null and b/assets/custom-3d-catalog/v1/deco/number-5.png differ diff --git a/assets/custom-3d-catalog/v1/deco/number-6.png b/assets/custom-3d-catalog/v1/deco/number-6.png new file mode 100644 index 00000000..88f33084 Binary files /dev/null and b/assets/custom-3d-catalog/v1/deco/number-6.png differ diff --git a/assets/custom-3d-catalog/v1/deco/number-7.png b/assets/custom-3d-catalog/v1/deco/number-7.png new file mode 100644 index 00000000..fd615844 Binary files /dev/null and b/assets/custom-3d-catalog/v1/deco/number-7.png differ diff --git a/assets/custom-3d-catalog/v1/design/drip.png b/assets/custom-3d-catalog/v1/design/drip.png new file mode 100644 index 00000000..60d631bf Binary files /dev/null and b/assets/custom-3d-catalog/v1/design/drip.png differ diff --git a/assets/custom-3d-catalog/v1/design/heart.png b/assets/custom-3d-catalog/v1/design/heart.png new file mode 100644 index 00000000..b76333ad Binary files /dev/null and b/assets/custom-3d-catalog/v1/design/heart.png differ diff --git a/assets/custom-3d-catalog/v1/design/phrase.png b/assets/custom-3d-catalog/v1/design/phrase.png new file mode 100644 index 00000000..b42614ee Binary files /dev/null and b/assets/custom-3d-catalog/v1/design/phrase.png differ diff --git a/assets/custom-3d-catalog/v1/design/sparkle.png b/assets/custom-3d-catalog/v1/design/sparkle.png new file mode 100644 index 00000000..5dfb68af Binary files /dev/null and b/assets/custom-3d-catalog/v1/design/sparkle.png differ 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 00000000..db4d844f Binary files /dev/null and b/assets/custom-3d-catalog/v1/design/wave.png differ diff --git a/docs/guide/architecture-conventions.md b/docs/guide/architecture-conventions.md index dc580e88..051cd3cc 100644 --- a/docs/guide/architecture-conventions.md +++ b/docs/guide/architecture-conventions.md @@ -12,7 +12,7 @@ - (a) 2번째 구현이 현실적으로 예상됨 - (b) 외부 부수효과 어댑터(OIDC 클라이언트, 경보 전송 함수, 시계, ID 생성기)라 테스트에서 stub이 필요 -- (c) 여러 feature가 광범위하게 주입하는 cross-cutting 포트 — `audit-log`(`AUDIT_LOG_REPOSITORY`), `store`의 `CatalogQuery`(conversation이 묻는 읽기 포트), `order`의 예약 수량 포트 +- (c) 여러 feature가 광범위하게 주입하는 cross-cutting 포트 — `audit-log`(`AUDIT_LOG_REPOSITORY`), `store`의 `CatalogQuery`(conversation이 묻는 읽기 포트), `order`의 예약 수량 포트, `order`의 탈퇴 차단 포트(`WithdrawalBlockingOrderQuery`, auth가 첫 호출 때 `ModuleRef`로 찾는 읽기 포트, `module-wiring.spec`이 역할별 resolve를 본다) **왜.** NestJS DI는 클래스 토큰도 `Test.overrideProvider(Class)`로 바꿀 수 있어 **테스트 용이성은 토큰 도입 근거가 아니다**. 전 repository에 1:1 인터페이스를 강제하면 lockstep 유지 비용만 늘고 얻는 게 없다(YAGNI, speculative generality). @@ -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 1ae6082a..af9ab73f 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= @@ -44,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/infra/runbook.md b/infra/runbook.md index bcc26450..9494524b 100644 --- a/infra/runbook.md +++ b/infra/runbook.md @@ -1,4 +1,4 @@ -# 운영 runbook — 백업·복구·롤백 +# 운영 runbook — 백업·복구·롤백·키 회전 ## 백업 @@ -76,3 +76,21 @@ 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단계부터 다시). + +## 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 4b329171..2d5a777d 100644 --- a/package.json +++ b/package.json @@ -39,6 +39,8 @@ "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", + "catalog:upload": "ts-node -r tsconfig-paths/register scripts/catalog-upload.ts", "lint:fix": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix" }, "dependencies": { @@ -70,6 +72,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/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/migrations/20261118155816_custom_product_settings/migration.sql b/prisma/migrations/20261118155816_custom_product_settings/migration.sql new file mode 100644 index 00000000..a7b2e55c --- /dev/null +++ b/prisma/migrations/20261118155816_custom_product_settings/migration.sql @@ -0,0 +1,51 @@ +-- 상품 커스텀 방식(없음·슬롯형·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`; +-- 자리는 바탕 안에 둔다(서버 좌표 검증과 같은 범위): 좌표 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 +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/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/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/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/migrations/20261118203227_conversation_image_order_card/migration.sql b/prisma/migrations/20261118203227_conversation_image_order_card/migration.sql new file mode 100644 index 00000000..9ba1e316 --- /dev/null +++ b/prisma/migrations/20261118203227_conversation_image_order_card/migration.sql @@ -0,0 +1,9 @@ +-- 채팅 이미지·주문 카드 메시지. 새 컬럼은 모두 nullable이고 enum은 끝에 덧붙여 기존 TEXT·HTML 메시지는 그대로다(백필 없음). +-- AlterTable +ALTER TABLE `store_conversation_message` ADD COLUMN `image_url` VARCHAR(2048) NULL, + ADD COLUMN `order_card_order_id` BIGINT UNSIGNED NULL, + ADD COLUMN `order_card_order_number` VARCHAR(30) NULL, + ADD COLUMN `order_card_pickup_at` DATETIME(3) NULL, + ADD COLUMN `order_card_product_name` VARCHAR(200) NULL, + ADD COLUMN `order_card_thumbnail_url` VARCHAR(2048) NULL, + MODIFY `body_format` ENUM('TEXT', 'HTML', 'IMAGE', 'ORDER_CARD') NOT NULL DEFAULT 'TEXT'; diff --git a/prisma/schema.prisma b/prisma/schema.prisma index 6cb89998..2ba0a173 100644 --- a/prisma/schema.prisma +++ b/prisma/schema.prisma @@ -46,12 +46,114 @@ enum CategoryType { OTHER } +enum CustomMode { + NONE + SLOT + THREE_D +} + +enum CustomTextAlign { + LEFT + CENTER + RIGHT +} + +// 주문 커스텀 이미지 종류. 3D는 윗면 + 옆면 앞·뒤·좌·우 렌더, 슬롯형은 '본 그대로' 합성 1장 +enum CustomImageKind { + THREE_D_TOP + THREE_D_FRONT + THREE_D_BACK + THREE_D_LEFT + THREE_D_RIGHT + SLOT_COMPOSITE +} + +// 구매자 커스텀 이미지 선업로드 용도(3D 렌더·슬롯형 합성·자유 편집 참고 사진) +enum OrderCustomUploadPurpose { + RENDER + COMPOSITE + REFERENCE +} + +// 발급(PENDING) → 주문에 쓰임(ATTACHED, 보관) 또는 정리 중(PURGING, 주문에 붙일 수 없다) +enum OrderCustomUploadStatus { + PENDING + ATTACHED + PURGING +} + enum OrderStatus { SUBMITTED CONFIRMED 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 { @@ -75,6 +177,8 @@ enum ConversationSenderType { enum ConversationBodyFormat { TEXT HTML + IMAGE + ORDER_CARD } enum ReviewMediaType { @@ -104,6 +208,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 { @@ -127,7 +237,7 @@ enum AuditTargetType { ORDER CONVERSATION CHANGE_PASSWORD - // 이하 관리자 조작 대상. 판매자 감사 로그 조회는 위 5종만 보여준다. + // 이하 관리자 조작 대상. 판매자 감사 로그 조회는 위 5종과 SETTLEMENT_ACCOUNT만 보여준다. ACCOUNT BANNER CATEGORY @@ -138,6 +248,11 @@ enum AuditTargetType { REVIEW_REPORT NOTIFICATION SEARCH_KEYWORD_CHIP + PAYMENT_SETTING + SETTLEMENT_ACCOUNT + SETTLEMENT + REFUND + DEPOSIT_RECORD } enum AuditActionType { @@ -458,6 +573,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") @@ -580,8 +697,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 @@ -682,9 +799,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 @@ -713,6 +827,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) @@ -737,8 +853,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) @@ -757,15 +875,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) @@ -814,7 +937,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 +955,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 +1009,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) @@ -891,6 +1048,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) @@ -903,6 +1065,8 @@ model OrderItem { option_items OrderItemOptionItem[] custom_texts OrderItemCustomText[] free_edits OrderItemCustomFreeEdit[] + custom_design OrderItemCustomDesign? + custom_images OrderItemCustomImage[] notifications Notification[] review Review? @@ -941,10 +1105,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) @@ -961,7 +1137,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) @@ -995,6 +1175,240 @@ 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") +} + +// 커스텀 이미지 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 + 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 @@ -1446,8 +1860,17 @@ model StoreConversationMessage { sender_account_id BigInt? @db.UnsignedBigInt body_format ConversationBodyFormat @default(TEXT) + // IMAGE·ORDER_CARD는 목록 미리보기·푸시에 쓰는 대체 문구를 담는다 body_text String? @db.Text body_html String? @db.Text + image_url String? @db.VarChar(2048) + + // 주문 카드는 보낸 시점 값으로 남긴다. 주문이 바뀌거나 지워져도 대화 이력이 그대로 보이게 FK를 두지 않는다 + order_card_order_id BigInt? @db.UnsignedBigInt + order_card_order_number String? @db.VarChar(30) + order_card_product_name String? @db.VarChar(200) + order_card_thumbnail_url String? @db.VarChar(2048) + order_card_pickup_at DateTime? @db.DateTime(3) created_at DateTime @default(now()) @db.DateTime(3) deleted_at DateTime? @db.DateTime(3) diff --git a/prisma/seed.ts b/prisma/seed.ts index 043ab7bc..ce0f2735 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, stores, 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..1761bba3 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'; @@ -117,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 } }, }); @@ -135,6 +142,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 } }, }); @@ -165,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 } }, @@ -301,6 +326,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..7fae4c0f 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'; /** 주문 시점 썸네일 스냅샷 — 주문 생성 경로와 같은 규칙(활성 첫 이미지). */ @@ -46,8 +59,25 @@ export interface SeededOrders { o3Made: bigint; o4PickedUpReviewed: bigint; o4OrderItemId: bigint; + o4PreviewImageUrl: string; 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 +128,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 +161,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', }, ], }, @@ -149,6 +186,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({ @@ -166,15 +214,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, }, @@ -223,16 +281,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,18 +325,36 @@ 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 }, ], }, }, }); + // 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, @@ -286,16 +368,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 }, + }, }, }); @@ -337,21 +414,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 +473,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,13 +492,210 @@ 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, o3Made: o3.id, o4PickedUpReviewed: o4.id, o4OrderItemId: o4Item.id, + o4PreviewImageUrl: o4Preview, 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..93309a82 --- /dev/null +++ b/prisma/seed/payments.ts @@ -0,0 +1,137 @@ +/** + * 결제 설정·결제·환불·입금 기록·정산 계좌 시드. 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', + deposit_account_number: '00000000000000', + deposit_account_holder: '케이퀵(테스트)', +} as const; + +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; + stores: SeededStores; + 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, + }, + }); + + 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/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: '레터링이 정말 예쁘게 나왔어요. 케이크 맛도 좋고 다음에 또 주문할게요!', 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 new file mode 100644 index 00000000..f0b6e63f --- /dev/null +++ b/scripts/accounts-reencrypt.ts @@ -0,0 +1,53 @@ +/** + * 계좌번호 키 회전: ACCOUNT_ENCRYPTION_KEYS 맨 앞에 새 키를 넣고 배포한 뒤 돌린다. 대상 수를 먼저 찍는다. + * yarn accounts:reencrypt --dry-run # 대상 수만 + * yarn accounts:reencrypt # 첫 키가 아닌 키로 암호화된 계좌번호를 첫 키로 다시 암호화 + * 대상이 0이 된 뒤에야 옛 키를 env에서 뺀다(infra/runbook.md). + */ +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'; +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 { dryRun } = parseReencryptArgs(process.argv.slice(2)); + const config = readAccountCryptoConfig(); + assertRotatableConfig(config); + 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 (dryRun) 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/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..a7d9697f --- /dev/null +++ b/scripts/catalog-upload.ts @@ -0,0 +1,99 @@ +/** + * 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', + IfNoneMatch: '*', // 이미 있으면 412 — Head가 403으로 못 본 객체·동시 업로드도 덮어쓰지 않는다 + }), + ); + 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/app.module.ts b/src/app.module.ts index ad74fb8a..854fac50 100644 --- a/src/app.module.ts +++ b/src/app.module.ts @@ -17,6 +17,8 @@ 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 adminWebConfig from '@/config/admin-web.config'; import alertingConfig from '@/config/alerting.config'; import appConfig, { APP_ROLE_TOKEN, @@ -48,6 +50,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 +123,8 @@ export class AppModule implements NestModule { isGlobal: true, cache: true, load: [ + accountCryptoConfig, + adminWebConfig, alertingConfig, appConfig, authConfig, @@ -147,6 +152,7 @@ export class AppModule implements NestModule { BlacklistModule, PubSubModule, StorageModule, + CryptoModule, // 크론(SearchModule)은 worker만 — api가 같이 돌리면 같은 스냅샷을 두 번 만든다 ...(runsBackgroundJobs(role) ? [ScheduleModule.forRoot()] : []), ...(servesHttpApi(role) ? httpModules() : []), diff --git a/src/common/errors/error-catalog.spec.ts b/src/common/errors/error-catalog.spec.ts index 9f1b73d9..a359aaf1 100644 --- a/src/common/errors/error-catalog.spec.ts +++ b/src/common/errors/error-catalog.spec.ts @@ -32,6 +32,14 @@ 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' }, + ACCOUNT_HAS_ACTIVE_ORDERS: { count: 2 }, + 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 acbc5450..d4cde05c 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만 저장할 수 있습니다.', @@ -221,6 +225,11 @@ export const ERROR_CATALOG = { status: HttpStatus.BAD_REQUEST, message: '푸시 토큰 형식이 올바르지 않습니다.', }, + ACCOUNT_HAS_ACTIVE_ORDERS: { + status: HttpStatus.CONFLICT, + message: ({ count }) => + `진행 중인 주문 또는 환불 ${count}건이 있어 탈퇴할 수 없습니다.`, + }, // ── 카탈로그(매장·상품·지역) STORE_NOT_FOUND: { @@ -319,6 +328,35 @@ 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}원 이하로 입력해 주세요.`, + }, + REFUND_NOT_FOUND: { + status: HttpStatus.NOT_FOUND, + message: '환불을 찾을 수 없습니다.', + }, + REFUND_NOT_READY: { + status: HttpStatus.BAD_REQUEST, + message: '환불 계좌가 입력되지 않아 송금 완료로 처리할 수 없어요.', + }, + REFUND_ALREADY_COMPLETED: { + status: HttpStatus.CONFLICT, + message: '이미 송금이 끝난 환불입니다.', + }, DUPLICATE_OPTION_ITEM: { status: HttpStatus.BAD_REQUEST, message: '중복된 옵션 선택입니다.', @@ -331,18 +369,30 @@ 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: '선택한 픽업 일시는 예약할 수 없습니다.', }, + NO_SHOW_NOT_ALLOWED: { + status: HttpStatus.BAD_REQUEST, + message: '노쇼는 픽업 시각부터 24시간 안에만 처리할 수 있습니다.', + }, + PICKUP_RESCHEDULE_NOT_ALLOWED: { + status: HttpStatus.BAD_REQUEST, + message: '접수·확정·제작 완료 주문만 픽업 일시를 바꿀 수 있습니다.', + }, + PICKUP_UNCHANGED: { + status: HttpStatus.BAD_REQUEST, + message: '지금과 같은 픽업 일시입니다.', + }, ORDER_AMOUNT_OUT_OF_RANGE: { status: HttpStatus.BAD_REQUEST, message: '주문 금액이 처리 가능한 범위를 벗어났습니다.', }, + ORDER_PRICE_CHANGED: { + status: HttpStatus.CONFLICT, + message: '가격이 바뀌었어요. 금액을 다시 확인해 주세요.', + }, UNSUPPORTED_CURRENCY: { status: HttpStatus.BAD_REQUEST, message: 'KRW 상품만 주문할 수 있습니다.', @@ -357,6 +407,11 @@ export const ERROR_CATALOG = { message: '이 요청 키로는 주문을 만들 수 없습니다. 주문서를 새로 열어 다시 시도해 주세요.', }, + IDEMPOTENCY_KEY_INPUT_MISMATCH: { + status: HttpStatus.BAD_REQUEST, + message: + '같은 요청 키로 다른 주문 내용이 들어왔습니다. 주문서를 새로 열어 다시 시도해 주세요.', + }, IDEMPOTENT_REPLAY_FAILED: { status: HttpStatus.INTERNAL_SERVER_ERROR, message: @@ -366,6 +421,83 @@ 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, + message: '지원하지 않는 은행입니다. 은행을 다시 선택해 주세요.', + }, + INVALID_ACCOUNT_NUMBER: { + status: HttpStatus.BAD_REQUEST, + message: '계좌번호는 하이픈(-)을 뺀 숫자 8~20자리로 입력해 주세요.', + }, + INVALID_COMMISSION_RATE: { + 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: '입금액이 올바르지 않아요. 원 단위 정수로 입력해 주세요.', + }, + DEPOSIT_AMOUNT_MISMATCH: { + status: HttpStatus.BAD_REQUEST, + message: + '입금액이 결제 금액과 달라 입금 확인할 수 없어요. 반환 대상으로 연결해 주세요.', + }, + DEPOSIT_NOTE_REQUIRED: { + status: HttpStatus.BAD_REQUEST, + message: '주인 모를 입금은 메모를 남겨야 기록할 수 있어요.', + }, + DEPOSIT_RECORD_NOT_FOUND: { + status: HttpStatus.NOT_FOUND, + message: '입금 기록을 찾을 수 없습니다.', + }, + DEPOSIT_RECORD_ALREADY_LINKED: { + status: HttpStatus.CONFLICT, + message: '이미 반환 대상으로 연결된 입금 기록입니다.', + }, + SETTLEMENT_NOT_FOUND: { + status: HttpStatus.NOT_FOUND, + message: '정산 내역을 찾을 수 없어요.', + }, + SETTLEMENT_ALREADY_PAID: { + status: HttpStatus.CONFLICT, + message: '이미 송금 완료로 처리된 정산이에요.', + }, + SETTLEMENT_ACCOUNT_REQUIRED: { + status: HttpStatus.BAD_REQUEST, + message: + '매장 정산 계좌가 등록되지 않아 송금 완료로 처리할 수 없어요. 정산 계좌를 먼저 등록해 주세요.', + }, // ── 판매자 SELLER_ONLY: { status: HttpStatus.FORBIDDEN, @@ -444,6 +576,100 @@ 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 형식으로 입력해 주세요.', + }, + CUSTOM_BASE_IMAGE_NOT_SQUARE: { + status: HttpStatus.BAD_REQUEST, + message: '바탕 이미지는 정사각형(1:1)이어야 해요.', + }, + CUSTOM_BASE_IMAGE_UNREADABLE: { + 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}). 다시 꾸며 주세요.`, + }, + 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이어야 합니다.', @@ -488,9 +714,13 @@ export const ERROR_CATALOG = { status: HttpStatus.BAD_REQUEST, message: '본문 형식이 올바르지 않습니다.', }, - CANCELLATION_NOTE_REQUIRED: { + IMAGE_URL_REQUIRED: { + status: HttpStatus.BAD_REQUEST, + message: '보낼 사진을 첨부해 주세요.', + }, + ORDER_INQUIRY_NOT_AVAILABLE: { status: HttpStatus.BAD_REQUEST, - message: '취소 사유가 필요합니다.', + message: '입금이 확인된 뒤 문의할 수 있어요.', }, // ── 관리자 ADMIN_ONLY: { diff --git a/src/common/ports/withdrawal-blocking-order.port.ts b/src/common/ports/withdrawal-blocking-order.port.ts new file mode 100644 index 00000000..bc6fe496 --- /dev/null +++ b/src/common/ports/withdrawal-blocking-order.port.ts @@ -0,0 +1,9 @@ +/** + * auth(구매자 탈퇴)가 order에 묻는 "탈퇴를 막는 주문·환불 수" 읽기 포트. + * order → auth 의존(관리자 컨텍스트)이 이미 있어 auth가 OrderModule을 import하면 순환이라, 계약은 무의존 common에 두고 + * order가 구현을 제공한다. auth는 첫 호출 때 ModuleRef(strict: false)로 찾는다. + */ +export abstract class WithdrawalBlockingOrderQuery { + /** 진행 중 주문(입금 대기~제작 완료)과 송금이 끝나지 않은 환불(종류 무관) 수의 합. */ + abstract countByBuyer(accountId: bigint): Promise; +} diff --git a/src/common/utils/kst-time.spec.ts b/src/common/utils/kst-time.spec.ts index 8068b2a6..fe5ec6ed 100644 --- a/src/common/utils/kst-time.spec.ts +++ b/src/common/utils/kst-time.spec.ts @@ -1,11 +1,13 @@ import { daysInMonth, + formatDateOnly, formatKstDate, formatMinutesOfDay, kstDayBoundaries, kstDayDiff, kstMidnightUtc, kstMinutesOfDay, + kstWeekStart, parseKstDate, parseKstYearMonth, toKstYmd, @@ -105,6 +107,41 @@ describe('kst-time', () => { }); }); + describe('kstWeekStart', () => { + it.each([ + [ + '월 00:00 KST는 그 주의 시작이다', + '2026-11-15T15:00:00.000Z', + '2026-11-15T15:00:00.000Z', + ], + [ + '일 23:59:59.999 KST는 앞 주에 속한다', + '2026-11-15T14:59:59.999Z', + '2026-11-08T15:00:00.000Z', + ], + [ + 'UTC로는 수요일인 목 00:30 KST', + '2026-11-18T15:30:00.000Z', + '2026-11-15T15:00:00.000Z', + ], + [ + '연말 금요일은 전년 12월 월요일로 간다', + '2027-01-01T01:00:00.000Z', + '2026-12-27T15:00:00.000Z', + ], + ])('%s', (_label, at, expected) => { + expect(kstWeekStart(new Date(at)).toISOString()).toBe(expected); + }); + }); + + describe('formatDateOnly', () => { + it('@db.Date 값을 YYYY-MM-DD로 쓴다', () => { + expect(formatDateOnly(new Date('2026-11-09T00:00:00.000Z'))).toBe( + '2026-11-09', + ); + }); + }); + describe('daysInMonth', () => { it('말일을 계산한다(윤년 포함)', () => { expect(daysInMonth(2026, 9)).toBe(30); diff --git a/src/common/utils/kst-time.ts b/src/common/utils/kst-time.ts index 2b53906b..b1530b1a 100644 --- a/src/common/utils/kst-time.ts +++ b/src/common/utils/kst-time.ts @@ -47,6 +47,17 @@ export function kstDayBoundaries(at: Date): KstDayBoundaries { }; } +/** 그 시각이 속한 KST 주(월~일)의 월요일 00:00 KST(UTC 시각). */ +export function kstWeekStart(at: Date): Date { + const { dayStartUtc, weekday } = kstDayBoundaries(at); + return new Date(dayStartUtc.getTime() - ((weekday + 6) % 7) * DAY_MS); +} + +/** `@db.Date` 값(KST 달력일의 UTC 자정 표현)을 YYYY-MM-DD로. */ +export function formatDateOnly(dateOnlyUtc: Date): string { + return dateOnlyUtc.toISOString().slice(0, 10); +} + export function daysInMonth(year: number, month: number): number { return new Date(Date.UTC(year, month, 0)).getUTCDate(); } 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/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/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/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/audit-log/audit-log.types.graphql b/src/features/audit-log/audit-log.types.graphql index 1625ab85..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 { """ @@ -62,6 +62,26 @@ enum AuditTargetType { 검색 진입 화면 키워드 바로가기 칩. 순서 변경은 순서가 바뀐 칩마다 1건씩 남는다. """ SEARCH_KEYWORD_CHIP + """ + 플랫폼 결제 설정(수수료율·입금 계좌). + """ + PAYMENT_SETTING + """ + 매장 정산 계좌(판매자 본인·관리자 대리 수정). 기록에는 계좌번호 끝 4자리만 남고, 판매자 감사 로그에도 보인다. + """ + SETTLEMENT_ACCOUNT + """ + 주간 정산(송금 완료 처리). + """ + SETTLEMENT + """ + 환불(완료 처리). + """ + REFUND + """ + 입금 기록(반환 연결·주인 모를 입금 종결). + """ + DEPOSIT_RECORD } """ 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/auth/auth-user-profile.graphql b/src/features/auth/auth-user-profile.graphql index c1191fc7..6348206b 100644 --- a/src/features/auth/auth-user-profile.graphql +++ b/src/features/auth/auth-user-profile.graphql @@ -29,7 +29,8 @@ extend type Mutation { """ updateMyProfileImage(input: UpdateMyProfileImageInput!): MePayload! """ - 회원 탈퇴(soft delete). 로그인 필수. 본인 데이터만 대상이 된다. + 회원 탈퇴(soft delete). 진행 중인 주문(입금 대기~제작 완료)이나 송금이 끝나지 않은 환불(계좌 입력 대기·송금 대기)이 있으면 + ACCOUNT_HAS_ACTIVE_ORDERS(CONFLICT, 메시지에 건수). 로그인 필수. 본인 데이터만 대상이 된다. """ deleteMyAccount: Boolean! """ diff --git a/src/features/auth/resolvers/auth-user-profile.resolver.spec.ts b/src/features/auth/resolvers/auth-user-profile.resolver.spec.ts index 57cefdc5..621760a8 100644 --- a/src/features/auth/resolvers/auth-user-profile.resolver.spec.ts +++ b/src/features/auth/resolvers/auth-user-profile.resolver.spec.ts @@ -1,7 +1,9 @@ +import { WithdrawalBlockingOrderQuery } from '@/common/ports/withdrawal-blocking-order.port'; import { AccountUserRepository } from '@/features/auth/repositories/account-user.repository'; import { UserProfileMutationResolver } from '@/features/auth/resolvers/auth-user-profile-mutation.resolver'; import { UserProfileQueryResolver } from '@/features/auth/resolvers/auth-user-profile-query.resolver'; import { UserProfileService } from '@/features/auth/services/auth-user-profile.service'; +import { OrderWithdrawalBlockingRepository } from '@/features/order/repositories/order-withdrawal-blocking.repository'; import type { PrismaClient } from '@/generated/prisma/client'; import { S3Service } from '@/global/storage/s3.service'; import { disconnectTestPrismaClient } from '@/test/db/prisma-test-client'; @@ -34,6 +36,10 @@ describe('User Profile Resolvers (real DB)', () => { NOOP_BLACKLIST_PROVIDER, AccountUserRepository, { provide: S3Service, useValue: s3Service }, + { + provide: WithdrawalBlockingOrderQuery, + useClass: OrderWithdrawalBlockingRepository, + }, ], }); diff --git a/src/features/auth/services/auth-user-profile.service.spec.ts b/src/features/auth/services/auth-user-profile.service.spec.ts index 6716be8b..9c4eed94 100644 --- a/src/features/auth/services/auth-user-profile.service.spec.ts +++ b/src/features/auth/services/auth-user-profile.service.spec.ts @@ -1,6 +1,8 @@ +import { WithdrawalBlockingOrderQuery } from '@/common/ports/withdrawal-blocking-order.port'; import { AccountUserRepository } from '@/features/auth/repositories/account-user.repository'; import { UserProfileService } from '@/features/auth/services/auth-user-profile.service'; -import type { PrismaClient } from '@/generated/prisma/client'; +import { OrderWithdrawalBlockingRepository } from '@/features/order/repositories/order-withdrawal-blocking.repository'; +import type { OrderStatus, PrismaClient } from '@/generated/prisma/client'; import { TokenBlacklistService } from '@/global/auth'; import { S3Service } from '@/global/storage/s3.service'; import { disconnectTestPrismaClient } from '@/test/db/prisma-test-client'; @@ -8,6 +10,8 @@ import { closeTruncateConnection, truncateAll } from '@/test/db/truncate'; import { createAccount, createAccountIdentity, + createOrder, + createRefund, createUserProfile, } from '@/test/factories'; import { createTestingModuleWithRealDb } from '@/test/modules/testing-module.builder'; @@ -35,6 +39,11 @@ describe('UserProfileService (real DB)', () => { { provide: TokenBlacklistService, useValue: blacklist }, AccountUserRepository, { provide: S3Service, useValue: s3Service }, + // 앱에서는 OrderModule이 제공하고 서비스가 ModuleRef로 찾는다 + { + provide: WithdrawalBlockingOrderQuery, + useClass: OrderWithdrawalBlockingRepository, + }, ], }); @@ -580,5 +589,90 @@ describe('UserProfileService (real DB)', () => { await expect(service.me(account.id)).rejects.toThrowDomain(401); }); + + async function buyer() { + const account = await createAccount(prisma, { account_type: 'USER' }); + await createUserProfile(prisma, { account_id: account.id }); + return account; + } + + async function expectBlocked(accountId: bigint, count: number) { + await expect(service.deleteMyAccount(accountId)).rejects.toThrowDomain( + 'ACCOUNT_HAS_ACTIVE_ORDERS', + ); + await expect(service.deleteMyAccount(accountId)).rejects.toThrow( + `진행 중인 주문 또는 환불 ${count}건이 있어 탈퇴할 수 없습니다.`, + ); + await expect( + prisma.account.findUniqueOrThrow({ where: { id: accountId } }), + ).resolves.toMatchObject({ deleted_at: null }); + expect(blacklist.blockStatus).not.toHaveBeenCalled(); + } + + it.each<[OrderStatus, boolean]>([ + ['PENDING_PAYMENT', true], + ['SUBMITTED', true], + ['CONFIRMED', true], + ['MADE', true], + ['PICKED_UP', false], + ['NO_SHOW', false], + ['CANCELED', false], + ])('%s 주문이 있으면 탈퇴 차단 = %s', async (status, blocked) => { + const account = await buyer(); + await createOrder(prisma, { account_id: account.id, status }); + + if (blocked) { + await expectBlocked(account.id, 1); + } else { + await expect(service.deleteMyAccount(account.id)).resolves.toBe(true); + } + }); + + it.each(['AWAITING_ACCOUNT', 'AWAITING_TRANSFER'] as const)( + '끝난 주문이라도 송금이 끝나지 않은 입금 반환(%s)이 있으면 막고, 진행 주문과 합쳐 센다', + async (status) => { + const account = await buyer(); + const canceled = await createOrder(prisma, { + account_id: account.id, + status: 'CANCELED', + }); + await createRefund(prisma, { + order_id: canceled.id, + kind: 'DEPOSIT_RETURN', + status, + }); + await expectBlocked(account.id, 1); + + await createOrder(prisma, { account_id: account.id, status: 'MADE' }); + await expectBlocked(account.id, 2); + }, + ); + + it('환불 송금이 끝나면 탈퇴할 수 있고, 다른 구매자·삭제된 주문의 건은 세지 않는다', async () => { + const account = await buyer(); + const canceled = await createOrder(prisma, { + account_id: account.id, + status: 'CANCELED', + }); + const refund = await createRefund(prisma, { + order_id: canceled.id, + status: 'AWAITING_TRANSFER', + }); + await createRefund(prisma); + await createOrder(prisma, { status: 'SUBMITTED' }); + await createOrder(prisma, { + account_id: account.id, + status: 'SUBMITTED', + deleted_at: new Date(), + }); + await expectBlocked(account.id, 1); + + await prisma.refund.update({ + where: { id: refund.id }, + data: { status: 'COMPLETED', completed_at: new Date() }, + }); + + await expect(service.deleteMyAccount(account.id)).resolves.toBe(true); + }); }); }); diff --git a/src/features/auth/services/auth-user-profile.service.ts b/src/features/auth/services/auth-user-profile.service.ts index a585f02f..b62e1b62 100644 --- a/src/features/auth/services/auth-user-profile.service.ts +++ b/src/features/auth/services/auth-user-profile.service.ts @@ -1,6 +1,8 @@ import { Injectable } from '@nestjs/common'; +import { ModuleRef } from '@nestjs/core'; import { DomainException } from '@/common/errors/error-catalog'; +import { WithdrawalBlockingOrderQuery } from '@/common/ports/withdrawal-blocking-order.port'; import { MAX_NICKNAME_LENGTH, MIN_NICKNAME_LENGTH, @@ -20,10 +22,13 @@ import type { CreateUploadUrlOutput } from '@/global/storage/types/storage.types @Injectable() export class UserProfileService extends UserBaseService { + private blockingOrders: WithdrawalBlockingOrderQuery | undefined; + constructor( accounts: AccountUserRepository, private readonly s3Service: S3Service, private readonly blacklist: TokenBlacklistService, + private readonly moduleRef: ModuleRef, ) { super(accounts); } @@ -190,8 +195,15 @@ export class UserProfileService extends UserBaseService { }); } + /** 진행 중 주문이나 송금이 끝나지 않은 환불이 있으면 거절한다 — 탈퇴하면 환불 계좌를 받을 수 없다. */ async deleteMyAccount(accountId: bigint): Promise { await this.requireActiveUser(accountId); + const blocking = await this.withdrawalBlocking().countByBuyer(accountId); + if (blocking > 0) { + throw new DomainException('ACCOUNT_HAS_ACTIVE_ORDERS', { + count: blocking, + }); + } const now = new Date(); const deletedNickname = `deleted_${accountId.toString()}`; @@ -206,4 +218,13 @@ export class UserProfileService extends UserBaseService { return true; } + + /** OrderModule이 auth를 import해 반대 방향 import는 순환이다 — 첫 호출 때 컨테이너 전체에서 찾는다. */ + private withdrawalBlocking(): WithdrawalBlockingOrderQuery { + this.blockingOrders ??= this.moduleRef.get( + WithdrawalBlockingOrderQuery, + { strict: false }, + ); + return this.blockingOrders; + } } diff --git a/src/features/conversation/constants/conversation.constants.ts b/src/features/conversation/constants/conversation.constants.ts index 22cfee1b..c3b75bde 100644 --- a/src/features/conversation/constants/conversation.constants.ts +++ b/src/features/conversation/constants/conversation.constants.ts @@ -10,3 +10,8 @@ export const DEFAULT_GREETING_TEMPLATE = export const MAX_INQUIRY_BODY_TEXT_LENGTH = 2000; // store.greeting_message VARCHAR(500)과 동일 상한 export const MAX_CONVERSATION_BODY_HTML_LENGTH = 100000; + +// 이미지 메시지 대체 문구. 목록 미리보기·판매자 푸시가 본문 대신 이 값을 쓴다. +export const CONVERSATION_IMAGE_ALT_TEXT = '사진을 보냈습니다.'; +// image_url VARCHAR(2048)과 동일 상한 +export const MAX_CONVERSATION_IMAGE_URL_LENGTH = 2048; diff --git a/src/features/conversation/conversation-inquiry.graphql b/src/features/conversation/conversation-inquiry.graphql index 04bb5e55..211c89de 100644 --- a/src/features/conversation/conversation-inquiry.graphql +++ b/src/features/conversation/conversation-inquiry.graphql @@ -3,6 +3,7 @@ extend type Query { 문의 채팅 진입 컨텍스트(구매자). 매장 프로필·상담시간·치환 완료 인사말·질문 칩을 한 번에 내려준다. 아직 대화가 없어도 조회 가능하며 그 경우 conversationId는 null. 로그인 필수. + 숨김 매장은 그 매장에 진행 중인 주문이 있는 구매자만 조회할 수 있다(아니면 STORE_NOT_FOUND). 문의 전송도 같다. """ storeInquiryContext(storeId: ID!): StoreInquiryContext! } @@ -20,6 +21,29 @@ extend type Mutation { 로그인 필수. """ sendConversationFaqMessage(input: SendConversationFaqMessageInput!): ConversationMessagesPayload! + """ + 채팅 이미지 업로드용 Presigned URL 발급(구매자). uploadUrl로 PUT한 뒤 publicUrl을 sendConversationImageMessage에 넣는다. + JPEG·PNG·WebP, 1바이트 이상 10MB 이하(아니면 INVALID_CONTENT_TYPE·INVALID_CONTENT_LENGTH·FILE_TOO_LARGE). + 로그인 필수. + """ + createConversationImageUploadUrl( + """파일 MIME 타입(image/jpeg·image/png·image/webp).""" + contentType: String! + """파일 크기(바이트, 1 이상 10MB 이하).""" + contentLength: Int! + ): UploadUrl! + """ + 구매자 이미지 메시지 전송(메시지당 1장). 대화가 없으면 sendConversationMessage처럼 생성하고 인사말을 먼저 저장한다. + imageUrl이 이 계정에 createConversationImageUploadUrl로 발급된 URL이 아니면 INVALID_IMAGE_URL, 공백이면 + IMAGE_URL_REQUIRED다. 로그인 필수. + """ + sendConversationImageMessage(input: SendConversationImageMessageInput!): ConversationMessagesPayload! + """ + 주문 카드 전송(구매자). 주문의 매장과의 대화에 보낸 시점의 주문 스냅샷을 카드로 남긴다(대화가 없으면 생성). + 본인 주문이 아니면 ORDER_NOT_FOUND, 입금 확인 전(판매자가 볼 수 없는) 주문이면 ORDER_INQUIRY_NOT_AVAILABLE, + 매장이 숨김이고 그 매장에 진행 중인 주문이 없으면 STORE_NOT_FOUND다. 로그인 필수. + """ + sendConversationOrderCard(orderId: ID!): ConversationMessagesPayload! } """문의 채팅 진입 컨텍스트""" @@ -66,10 +90,14 @@ type ConversationMessage { senderType: ConversationSenderType! """본문 형식. 읽어야 할 본문 필드를 가리킨다.""" bodyFormat: ConversationBodyFormat! - """평문 본문. bodyFormat이 TEXT면 이 값을 쓴다.""" + """평문 본문. bodyFormat이 TEXT면 이 값을 쓴다. IMAGE·ORDER_CARD는 대체 문구가 들어 있다.""" bodyText: String """서식 본문. bodyFormat이 HTML이면 이 값을 쓴다.""" bodyHtml: String + """이미지 URL. bodyFormat이 IMAGE면 채워진다.""" + imageUrl: String + """주문 카드. bodyFormat이 ORDER_CARD면 채워진다.""" + orderCard: ConversationOrderCard """발송 시각. 메시지 스트림 정렬은 id 기준이다.""" createdAt: DateTime! } @@ -90,6 +118,14 @@ input SendConversationMessageInput { bodyText: String! } +"""구매자 이미지 메시지 전송 입력""" +input SendConversationImageMessageInput { + """문의할 매장 ID. 대화방이 없으면 이 호출에서 생성된다.""" + storeId: ID! + """createConversationImageUploadUrl이 이 계정에 발급한 publicUrl.""" + imageUrl: String! +} + """질문 칩(FAQ) 전송 입력""" input SendConversationFaqMessageInput { """문의할 매장 ID. 대화방이 없으면 이 호출에서 생성된다.""" diff --git a/src/features/conversation/conversation-seller.graphql b/src/features/conversation/conversation-seller.graphql index f08ced36..6f96999b 100644 --- a/src/features/conversation/conversation-seller.graphql +++ b/src/features/conversation/conversation-seller.graphql @@ -15,6 +15,7 @@ extend type Query { extend type Mutation { """ 판매자 메시지를 발송한다. 판매자 로그인 필수. SELLER 계정이 아니면 FORBIDDEN, 매장을 보유하지 않으면 NOT_FOUND. + bodyFormat은 TEXT·HTML·IMAGE이고 ORDER_CARD는 INVALID_BODY_FORMAT이다(주문 카드는 구매자만 보낸다). """ sellerSendConversationMessage( input: SellerSendConversationMessageInput! @@ -118,6 +119,14 @@ type SellerConversationMessage { """ bodyHtml: String """ + 이미지 URL. bodyFormat이 IMAGE면 채워진다(bodyText에는 대체 문구 '사진을 보냈습니다.'). + """ + imageUrl: String + """ + 주문 카드. bodyFormat이 ORDER_CARD(구매자가 보낸 카드)면 채워진다. orderId로 주문 상세를 연다. + """ + orderCard: ConversationOrderCard + """ 발송 시각. """ createdAt: DateTime! @@ -152,7 +161,8 @@ type SellerConversationMessageConnection { input SellerSendConversationMessageInput { conversationId: ID! """ - 본문 형식. 이 값에 해당하는 본문 필드가 필수다(다른 쪽을 함께 넘기면 그대로 저장된다). + 본문 형식. 이 값에 해당하는 본문 필드가 필수다(TEXT·HTML은 다른 쪽을 함께 넘기면 그대로 저장된다). + IMAGE는 imageUrl만 저장하고 본문은 대체 문구로 채운다. ORDER_CARD는 INVALID_BODY_FORMAT이다. """ bodyFormat: ConversationBodyFormat! """ @@ -163,4 +173,9 @@ input SellerSendConversationMessageInput { 서식 본문(최대 100000자). bodyFormat이 HTML이면 필수. """ bodyHtml: String + """ + 이미지 URL. bodyFormat이 IMAGE면 필수(없으면 IMAGE_URL_REQUIRED)이고 sellerCreateUploadUrl(CONVERSATION_IMAGE)로 + 이 계정에 발급된 publicUrl이어야 한다(아니면 INVALID_IMAGE_URL). 다른 형식에서는 무시한다. + """ + imageUrl: String } diff --git a/src/features/conversation/conversation.module.ts b/src/features/conversation/conversation.module.ts index 53532264..44f9a90f 100644 --- a/src/features/conversation/conversation.module.ts +++ b/src/features/conversation/conversation.module.ts @@ -14,13 +14,14 @@ import { ConversationEventsService } from '@/features/conversation/services/conv import { ConversationInquiryService } from '@/features/conversation/services/conversation-inquiry.service'; import { SellerConversationService } from '@/features/conversation/services/conversation-seller.service'; import { ConversationSubscriptionService } from '@/features/conversation/services/conversation-subscription.service'; +import { OrderModule } from '@/features/order'; import { OutboxModule } from '@/features/outbox'; import { StoreModule } from '@/features/store'; @Module({ // 판매자 컨텍스트·catalog 읽기 포트(StoreModule), 감사 기록(AuditLogModule), 구매자 상태 판정(AuthModule), - // 구매자 메시지 이벤트 발행(OutboxModule) - imports: [StoreModule, AuditLogModule, AuthModule, OutboxModule], + // 구매자 메시지 이벤트 발행(OutboxModule), 주문 카드 원천·숨김 매장 문의 판정(OrderModule) + imports: [StoreModule, AuditLogModule, AuthModule, OutboxModule, OrderModule], providers: [ ConversationRepository, ConversationEventsService, diff --git a/src/features/conversation/conversation.types.graphql b/src/features/conversation/conversation.types.graphql index ff308fa1..fefcff23 100644 --- a/src/features/conversation/conversation.types.graphql +++ b/src/features/conversation/conversation.types.graphql @@ -17,4 +17,28 @@ enum ConversationBodyFormat { 서버 측 sanitize는 아직 적용돼 있지 않다. """ HTML + """ + 이미지 1장. imageUrl을 그리고, bodyText에는 대체 문구('사진을 보냈습니다.')가 있다. + """ + IMAGE + """ + 주문 카드(구매자만 보낸다). orderCard를 그리고, bodyText에는 대체 문구('주문 문의: {상품명} ({주문번호})')가 있다. + """ + ORDER_CARD +} + +""" +채팅 주문 카드. 구매자가 보낸 시점의 주문 스냅샷이라 이후 주문이 바뀌거나 지워져도 그대로 보인다. +판매자 앱은 orderId로 주문 상세를 연다. +""" +type ConversationOrderCard { + orderId: ID! + """주문번호.""" + orderNumber: String! + """상품명(주문 시점 스냅샷).""" + productName: String! + """썸네일. 커스텀 주문이면 커스텀 대표 이미지(3D 윗면·슬롯형 합성), 아니면 상품 대표 이미지. 둘 다 없으면 null.""" + thumbnailUrl: String + """보낸 시점의 픽업 일시.""" + pickupAt: DateTime! } diff --git a/src/features/conversation/dto/inputs/seller-send-conversation-message.input.spec.ts b/src/features/conversation/dto/inputs/seller-send-conversation-message.input.spec.ts index afc73928..7978dd49 100644 --- a/src/features/conversation/dto/inputs/seller-send-conversation-message.input.spec.ts +++ b/src/features/conversation/dto/inputs/seller-send-conversation-message.input.spec.ts @@ -28,6 +28,26 @@ describe('SellerSendConversationMessageInput', () => { expect(await validate(dto)).toHaveLength(0); }); + // ORDER_CARD는 DTO를 통과시켜 service가 INVALID_BODY_FORMAT으로 거절한다 + it.each(['IMAGE', 'ORDER_CARD'])('%s 형식 통과', async (bodyFormat) => { + const dto = build({ + conversationId: '1', + bodyFormat, + imageUrl: 'https://example.com/a.jpg', + }); + expect(await validate(dto)).toHaveLength(0); + }); + + it('문자열이 아닌 imageUrl 거절', async () => { + const dto = build({ + conversationId: '1', + bodyFormat: 'IMAGE', + imageUrl: 1, + }); + const errors = await validate(dto); + expect(errors[0].property).toBe('imageUrl'); + }); + it('알 수 없는 bodyFormat 거절', async () => { const dto = build({ conversationId: '1', diff --git a/src/features/conversation/dto/inputs/seller-send-conversation-message.input.ts b/src/features/conversation/dto/inputs/seller-send-conversation-message.input.ts index 517836b9..99ec19a0 100644 --- a/src/features/conversation/dto/inputs/seller-send-conversation-message.input.ts +++ b/src/features/conversation/dto/inputs/seller-send-conversation-message.input.ts @@ -1,14 +1,16 @@ import { IsIn, IsOptional, IsString } from 'class-validator'; -const BODY_FORMATS = ['TEXT', 'HTML'] as const; -type ConversationBodyFormat = (typeof BODY_FORMATS)[number]; +import { ConversationBodyFormat } from '@/generated/prisma/client'; -/** bodyFormat에 따라 bodyText/bodyHtml 중 하나가 필수라는 invariant는 service에서 검증한다(class-validator로 표현하기 어렵다). */ +/** + * 형식별 필수 필드·판매자가 보낼 수 없는 형식(ORDER_CARD)은 service가 판정한다. DTO는 SDL enum 전체를 받아야 + * ORDER_CARD가 VALIDATION_FAILED가 아니라 INVALID_BODY_FORMAT으로 거절된다. + */ export class SellerSendConversationMessageInput { @IsString() conversationId!: string; - @IsIn(BODY_FORMATS) + @IsIn(Object.values(ConversationBodyFormat)) bodyFormat!: ConversationBodyFormat; @IsOptional() @@ -18,4 +20,8 @@ export class SellerSendConversationMessageInput { @IsOptional() @IsString() bodyHtml?: string; + + @IsOptional() + @IsString() + imageUrl?: string; } diff --git a/src/features/conversation/dto/inputs/send-conversation-image-message.input.spec.ts b/src/features/conversation/dto/inputs/send-conversation-image-message.input.spec.ts new file mode 100644 index 00000000..9ce98505 --- /dev/null +++ b/src/features/conversation/dto/inputs/send-conversation-image-message.input.spec.ts @@ -0,0 +1,25 @@ +import 'reflect-metadata'; + +import { plainToInstance } from 'class-transformer'; +import { validate } from 'class-validator'; + +import { SendConversationImageMessageInput } from '@/features/conversation/dto/inputs/send-conversation-image-message.input'; + +function build(plain: object): SendConversationImageMessageInput { + return plainToInstance(SendConversationImageMessageInput, plain); +} + +describe('SendConversationImageMessageInput', () => { + it('storeId·imageUrl 정상 조합 허용', async () => { + const dto = build({ storeId: '1', imageUrl: 'https://example.com/a.jpg' }); + expect(await validate(dto)).toHaveLength(0); + }); + + it.each([ + ['storeId 누락', { imageUrl: 'https://example.com/a.jpg' }, 'storeId'], + ['imageUrl 빈 문자열', { storeId: '1', imageUrl: '' }, 'imageUrl'], + ])('%s 거절', async (_label, plain, property) => { + const errors = await validate(build(plain)); + expect(errors.map((e) => e.property)).toEqual([property]); + }); +}); diff --git a/src/features/conversation/dto/inputs/send-conversation-image-message.input.ts b/src/features/conversation/dto/inputs/send-conversation-image-message.input.ts new file mode 100644 index 00000000..3e3e35d7 --- /dev/null +++ b/src/features/conversation/dto/inputs/send-conversation-image-message.input.ts @@ -0,0 +1,11 @@ +import { IsNotEmpty, IsString } from 'class-validator'; + +export class SendConversationImageMessageInput { + @IsString() + @IsNotEmpty() + storeId!: string; + + @IsString() + @IsNotEmpty() + imageUrl!: string; +} diff --git a/src/features/conversation/repositories/conversation.repository.ts b/src/features/conversation/repositories/conversation.repository.ts index 0b7e0df6..e58290df 100644 --- a/src/features/conversation/repositories/conversation.repository.ts +++ b/src/features/conversation/repositories/conversation.repository.ts @@ -14,12 +14,34 @@ import { } from '@/generated/prisma/client'; import { activeWhere, PrismaService } from '@/prisma'; +export interface ConversationOrderCardSnapshot { + orderId: bigint; + orderNumber: string; + productName: string; + thumbnailUrl: string | null; + pickupAt: Date; +} + export interface ConversationMessageEntry { senderType: ConversationSenderType; senderAccountId: bigint | null; bodyFormat: ConversationBodyFormat; bodyText: string | null; bodyHtml: string | null; + imageUrl?: string; + orderCard?: ConversationOrderCardSnapshot; +} + +function orderCardColumns(card: ConversationOrderCardSnapshot | undefined) { + return card + ? { + order_card_order_id: card.orderId, + order_card_order_number: card.orderNumber, + order_card_product_name: card.productName, + order_card_thumbnail_url: card.thumbnailUrl, + order_card_pickup_at: card.pickupAt, + } + : {}; } @Injectable() @@ -539,6 +561,8 @@ export class ConversationRepository { body_format: entry.bodyFormat, body_text: entry.bodyText, body_html: entry.bodyHtml, + image_url: entry.imageUrl ?? null, + ...orderCardColumns(entry.orderCard), created_at: now, }, }), @@ -684,6 +708,7 @@ export class ConversationRepository { bodyFormat: ConversationBodyFormat; bodyText: string | null; bodyHtml: string | null; + imageUrl?: string | null; }, audit: (row: { id: bigint }) => AuditEntry, ) { @@ -701,6 +726,7 @@ export class ConversationRepository { body_format: args.bodyFormat, body_text: args.bodyText, body_html: args.bodyHtml, + image_url: args.imageUrl ?? null, created_at: now, }, }); diff --git a/src/features/conversation/resolvers/conversation-center.resolver.spec.ts b/src/features/conversation/resolvers/conversation-center.resolver.spec.ts index 4d10e039..ded1e656 100644 --- a/src/features/conversation/resolvers/conversation-center.resolver.spec.ts +++ b/src/features/conversation/resolvers/conversation-center.resolver.spec.ts @@ -10,6 +10,7 @@ import { ConversationInquiryMutationResolver } from '@/features/conversation/res import { ConversationCenterService } from '@/features/conversation/services/conversation-center.service'; import { ConversationEventsService } from '@/features/conversation/services/conversation-events.service'; import { ConversationInquiryService } from '@/features/conversation/services/conversation-inquiry.service'; +import { OrderInquiryRepository } from '@/features/order'; import { CATALOG_QUERY } from '@/features/store'; import { StoreCatalogQueryRepository } from '@/features/store/repositories/store-catalog-query.repository'; import type { PrismaClient } from '@/generated/prisma/client'; @@ -23,6 +24,7 @@ import { } from '@/test/factories'; import { createTestingModuleWithRealDb } from '@/test/modules/testing-module.builder'; import { outboxPublisherProviders } from '@/test/outbox'; +import { s3TestProviders } from '@/test/storage/s3-test.helper'; describe('Conversation Center Resolvers (real DB)', () => { let centerResolver: ConversationCenterQueryResolver; @@ -40,6 +42,8 @@ describe('Conversation Center Resolvers (real DB)', () => { // 발행 repository가 OutboxPublisher를 주입받는다 ...outboxPublisherProviders(), ConversationEventsService, + OrderInquiryRepository, + ...s3TestProviders(), AccountUserRepository, { provide: CATALOG_QUERY, useClass: StoreCatalogQueryRepository }, { provide: PUB_SUB, useValue: new PubSub() }, diff --git a/src/features/conversation/resolvers/conversation-inquiry-mutation.resolver.ts b/src/features/conversation/resolvers/conversation-inquiry-mutation.resolver.ts index 311c3552..3e44953a 100644 --- a/src/features/conversation/resolvers/conversation-inquiry-mutation.resolver.ts +++ b/src/features/conversation/resolvers/conversation-inquiry-mutation.resolver.ts @@ -2,6 +2,7 @@ import { UseGuards } from '@nestjs/common'; import { Args, Mutation, Resolver } from '@nestjs/graphql'; import { SendConversationFaqMessageInput } from '@/features/conversation/dto/inputs/send-conversation-faq-message.input'; +import { SendConversationImageMessageInput } from '@/features/conversation/dto/inputs/send-conversation-image-message.input'; import { SendConversationMessageInput } from '@/features/conversation/dto/inputs/send-conversation-message.input'; import { ConversationInquiryService } from '@/features/conversation/services/conversation-inquiry.service'; import type { ConversationMessagesPayload } from '@/features/conversation/types/conversation-output.type'; @@ -11,6 +12,7 @@ import { parseAccountId, type JwtUser, } from '@/global/auth'; +import type { CreateUploadUrlOutput } from '@/global/storage/types/storage.types'; @Resolver('Mutation') @UseGuards(JwtAuthGuard) @@ -34,4 +36,38 @@ export class ConversationInquiryMutationResolver { const accountId = parseAccountId(user); return this.inquiryService.sendConversationFaqMessage(accountId, input); } + + @Mutation('createConversationImageUploadUrl') + createConversationImageUploadUrl( + @CurrentUser() user: JwtUser, + @Args('contentType') contentType: string, + @Args('contentLength') contentLength: number, + ): Promise { + return this.inquiryService.createConversationImageUploadUrl( + parseAccountId(user), + { contentType, contentLength }, + ); + } + + @Mutation('sendConversationImageMessage') + sendConversationImageMessage( + @CurrentUser() user: JwtUser, + @Args('input') input: SendConversationImageMessageInput, + ): Promise { + return this.inquiryService.sendConversationImageMessage( + parseAccountId(user), + input, + ); + } + + @Mutation('sendConversationOrderCard') + sendConversationOrderCard( + @CurrentUser() user: JwtUser, + @Args('orderId') orderId: string, + ): Promise { + return this.inquiryService.sendConversationOrderCard( + parseAccountId(user), + orderId, + ); + } } diff --git a/src/features/conversation/resolvers/conversation-inquiry.resolver.spec.ts b/src/features/conversation/resolvers/conversation-inquiry.resolver.spec.ts index 99037037..59034862 100644 --- a/src/features/conversation/resolvers/conversation-inquiry.resolver.spec.ts +++ b/src/features/conversation/resolvers/conversation-inquiry.resolver.spec.ts @@ -9,6 +9,7 @@ import { ConversationInquiryMutationResolver } from '@/features/conversation/res import { ConversationInquiryQueryResolver } from '@/features/conversation/resolvers/conversation-inquiry-query.resolver'; import { ConversationEventsService } from '@/features/conversation/services/conversation-events.service'; import { ConversationInquiryService } from '@/features/conversation/services/conversation-inquiry.service'; +import { OrderInquiryRepository } from '@/features/order'; import { CATALOG_QUERY } from '@/features/store'; import { StoreCatalogQueryRepository } from '@/features/store/repositories/store-catalog-query.repository'; import type { PrismaClient } from '@/generated/prisma/client'; @@ -17,11 +18,18 @@ import { disconnectTestPrismaClient } from '@/test/db/prisma-test-client'; import { closeTruncateConnection, truncateAll } from '@/test/db/truncate'; import { createAccount, + createOrder, + createOrderItem, createStore, createUserProfile, } from '@/test/factories'; import { createTestingModuleWithRealDb } from '@/test/modules/testing-module.builder'; import { outboxPublisherProviders } from '@/test/outbox'; +import { s3TestProviders } from '@/test/storage/s3-test.helper'; + +jest.mock('@aws-sdk/s3-request-presigner', () => ({ + getSignedUrl: jest.fn().mockResolvedValue('https://mock-presigned-url.com'), +})); describe('Conversation Inquiry Resolvers (real DB)', () => { let queryResolver: ConversationInquiryQueryResolver; @@ -38,6 +46,8 @@ describe('Conversation Inquiry Resolvers (real DB)', () => { // 발행 repository가 OutboxPublisher를 주입받는다 ...outboxPublisherProviders(), ConversationEventsService, + OrderInquiryRepository, + ...s3TestProviders(), AccountUserRepository, { provide: CATALOG_QUERY, useClass: StoreCatalogQueryRepository }, { provide: PUB_SUB, useValue: new PubSub() }, @@ -104,4 +114,39 @@ describe('Conversation Inquiry Resolvers (real DB)', () => { expect(result.messages).toHaveLength(3); expect(result.messages[2].bodyHtml).toBe('

캘린더를 확인해 주세요.

'); }); + + it('이미지 업로드 URL 발급 → 이미지 메시지, 주문 카드 전송 전체 경로', async () => { + const buyer = await createAccount(prisma, { account_type: 'USER' }); + await createUserProfile(prisma, { account_id: buyer.id }); + const store = await createStore(prisma); + const order = await createOrder(prisma, { + account_id: buyer.id, + status: 'CONFIRMED', + }); + await createOrderItem(prisma, { order_id: order.id, store_id: store.id }); + const jwtUser = { accountId: buyer.id.toString() }; + + const upload = await mutationResolver.createConversationImageUploadUrl( + jwtUser, + 'image/jpeg', + 1024, + ); + const image = await mutationResolver.sendConversationImageMessage(jwtUser, { + storeId: store.id.toString(), + imageUrl: upload.publicUrl, + }); + const card = await mutationResolver.sendConversationOrderCard( + jwtUser, + order.id.toString(), + ); + + expect(image.messages.at(-1)?.imageUrl).toBe(upload.publicUrl); + expect(card.conversationId).toBe(image.conversationId); + expect(card.messages).toEqual([ + expect.objectContaining({ + bodyFormat: 'ORDER_CARD', + orderCard: expect.objectContaining({ orderId: order.id.toString() }), + }), + ]); + }); }); diff --git a/src/features/conversation/resolvers/conversation-seller.resolver.spec.ts b/src/features/conversation/resolvers/conversation-seller.resolver.spec.ts index 901b396b..85cb74b4 100644 --- a/src/features/conversation/resolvers/conversation-seller.resolver.spec.ts +++ b/src/features/conversation/resolvers/conversation-seller.resolver.spec.ts @@ -15,6 +15,7 @@ import { closeTruncateConnection, truncateAll } from '@/test/db/truncate'; import { createAccount, setupSellerWithStore } from '@/test/factories'; import { createTestingModuleWithRealDb } from '@/test/modules/testing-module.builder'; import { outboxPublisherProviders } from '@/test/outbox'; +import { s3TestProviders } from '@/test/storage/s3-test.helper'; describe('Seller Conversation Resolvers (real DB)', () => { let queryResolver: SellerConversationQueryResolver; @@ -32,6 +33,7 @@ describe('Seller Conversation Resolvers (real DB)', () => { // 발행 repository가 OutboxPublisher를 주입받는다 ...outboxPublisherProviders(), ConversationEventsService, + ...s3TestProviders(), { provide: PUB_SUB, useValue: new PubSub() }, { provide: AUDIT_LOG_REPOSITORY, diff --git a/src/features/conversation/services/conversation-attachment.helper.ts b/src/features/conversation/services/conversation-attachment.helper.ts new file mode 100644 index 00000000..ee9ae9b4 --- /dev/null +++ b/src/features/conversation/services/conversation-attachment.helper.ts @@ -0,0 +1,28 @@ +import { DomainException } from '@/common/errors/error-catalog'; +import { MAX_CONVERSATION_IMAGE_URL_LENGTH } from '@/features/conversation/constants/conversation.constants'; +import type { S3Service } from '@/global/storage/s3.service'; + +/** 보내는 계정이 CONVERSATION_IMAGE로 발급받은 URL만 싣는다(구매자·판매자 공용). */ +export function requireOwnedConversationImageUrl( + s3: S3Service, + raw: string | null | undefined, + accountId: bigint, +): string { + const url = raw?.trim(); + if (!url) throw new DomainException('IMAGE_URL_REQUIRED'); + if ( + url.length > MAX_CONVERSATION_IMAGE_URL_LENGTH || + !s3.isOwnedUploadUrl(url, 'CONVERSATION_IMAGE', accountId) + ) { + throw new DomainException('INVALID_IMAGE_URL'); + } + return url; +} + +/** 주문 카드 대체 문구. 목록 미리보기·판매자 푸시가 본문 대신 이 값을 쓴다. */ +export function orderCardAltText(card: { + productName: string; + orderNumber: string; +}): string { + return `주문 문의: ${card.productName} (${card.orderNumber})`; +} diff --git a/src/features/conversation/services/conversation-center-mappers.helper.spec.ts b/src/features/conversation/services/conversation-center-mappers.helper.spec.ts index ee48c4a7..d62da184 100644 --- a/src/features/conversation/services/conversation-center-mappers.helper.spec.ts +++ b/src/features/conversation/services/conversation-center-mappers.helper.spec.ts @@ -42,6 +42,19 @@ describe('conversation-center-mappers.helper', () => { ).toBe('답변'); }); + it.each([ + ['IMAGE', '사진을 보냈습니다.'], + ['ORDER_CARD', '주문 문의: 케이크 (ORD-1)'], + ] as const)('%s 메시지는 대체 문구를 반환한다', (format, alt) => { + expect( + toLastMessagePreview({ + body_format: format, + body_text: alt, + body_html: null, + }), + ).toBe(alt); + }); + it('메시지가 없거나 본문이 비면 null', () => { expect(toLastMessagePreview(null)).toBeNull(); expect( diff --git a/src/features/conversation/services/conversation-center-mappers.helper.ts b/src/features/conversation/services/conversation-center-mappers.helper.ts index 043aa27a..80159b0d 100644 --- a/src/features/conversation/services/conversation-center-mappers.helper.ts +++ b/src/features/conversation/services/conversation-center-mappers.helper.ts @@ -1,3 +1,5 @@ +import type { ConversationBodyFormat } from '@/generated/prisma/client'; + /** 표시용 한 줄 미리보기라 완전한 HTML 파싱 대신 태그 제거 + 공백 정리로 충분하다(저장 원문은 그대로). */ export function stripHtmlToPreview(html: string): string { return ( @@ -14,9 +16,10 @@ export function stripHtmlToPreview(html: string): string { ); } +/** IMAGE·ORDER_CARD는 body_text에 저장한 대체 문구가 미리보기다. */ export function toLastMessagePreview( message: { - body_format: 'TEXT' | 'HTML'; + body_format: ConversationBodyFormat; body_text: string | null; body_html: string | null; } | null, diff --git a/src/features/conversation/services/conversation-events-mappers.helper.spec.ts b/src/features/conversation/services/conversation-events-mappers.helper.spec.ts index ef9fec7d..6c8c09b7 100644 --- a/src/features/conversation/services/conversation-events-mappers.helper.spec.ts +++ b/src/features/conversation/services/conversation-events-mappers.helper.spec.ts @@ -14,6 +14,8 @@ function message( bodyFormat: 'TEXT', bodyText: '안녕하세요', bodyHtml: null, + imageUrl: null, + orderCard: null, createdAt: new Date('2026-08-01T12:00:00Z'), ...overrides, }; @@ -28,12 +30,41 @@ describe('conversation-events-mappers.helper', () => { bodyFormat: 'TEXT', bodyText: '안녕하세요', bodyHtml: null, + imageUrl: null, + orderCard: null, createdAt: '2026-08-01T12:00:00.000Z', }); }); - it('미리보기는 TEXT 원문 / HTML 태그 제거 텍스트를 쓴다', () => { + it('주문 카드 픽업 일시도 ISO 문자열로 바꾼다', () => { + const event = toConversationMessageEvent( + message({ + bodyFormat: 'ORDER_CARD', + orderCard: { + orderId: '5', + orderNumber: 'ORD-1', + productName: '케이크', + thumbnailUrl: 'https://cdn.example.com/t.jpg', + pickupAt: new Date('2026-08-03T03:00:00Z'), + }, + }), + ); + expect(event.orderCard).toEqual({ + orderId: '5', + orderNumber: 'ORD-1', + productName: '케이크', + thumbnailUrl: 'https://cdn.example.com/t.jpg', + pickupAt: '2026-08-03T03:00:00.000Z', + }); + }); + + it('미리보기는 TEXT·IMAGE 원문(대체 문구) / HTML 태그 제거 텍스트를 쓴다', () => { expect(toEventPreview(message())).toBe('안녕하세요'); + expect( + toEventPreview( + message({ bodyFormat: 'IMAGE', bodyText: '사진을 보냈습니다.' }), + ), + ).toBe('사진을 보냈습니다.'); expect( toEventPreview( message({ diff --git a/src/features/conversation/services/conversation-events-mappers.helper.ts b/src/features/conversation/services/conversation-events-mappers.helper.ts index 64dfcf47..36bf4a51 100644 --- a/src/features/conversation/services/conversation-events-mappers.helper.ts +++ b/src/features/conversation/services/conversation-events-mappers.helper.ts @@ -15,6 +15,13 @@ export function toConversationMessageEvent( bodyFormat: message.bodyFormat, bodyText: message.bodyText, bodyHtml: message.bodyHtml, + imageUrl: message.imageUrl, + orderCard: message.orderCard + ? { + ...message.orderCard, + pickupAt: message.orderCard.pickupAt.toISOString(), + } + : null, createdAt: message.createdAt.toISOString(), }; } diff --git a/src/features/conversation/services/conversation-events.service.spec.ts b/src/features/conversation/services/conversation-events.service.spec.ts index c095e84d..95b0412e 100644 --- a/src/features/conversation/services/conversation-events.service.spec.ts +++ b/src/features/conversation/services/conversation-events.service.spec.ts @@ -81,9 +81,17 @@ describe('ConversationEventsService (real Redis)', () => { id: '1', conversationId: '10', senderType: 'USER', - bodyFormat: 'TEXT', - bodyText: '픽업 문의', + bodyFormat: 'ORDER_CARD', + bodyText: '주문 문의: 케이크 (ORD-1)', bodyHtml: null, + imageUrl: null, + orderCard: { + orderId: '5', + orderNumber: 'ORD-1', + productName: '케이크', + thumbnailUrl: null, + pickupAt: new Date('2026-08-03T03:00:00Z'), + }, createdAt: new Date('2026-08-01T12:00:00Z'), }; await service.publishMessagesAdded([message]); @@ -93,9 +101,17 @@ describe('ConversationEventsService (real Redis)', () => { id: '1', conversationId: '10', senderType: 'USER', - bodyFormat: 'TEXT', - bodyText: '픽업 문의', + bodyFormat: 'ORDER_CARD', + bodyText: '주문 문의: 케이크 (ORD-1)', bodyHtml: null, + imageUrl: null, + orderCard: { + orderId: '5', + orderNumber: 'ORD-1', + productName: '케이크', + thumbnailUrl: null, + pickupAt: '2026-08-03T03:00:00.000Z', + }, createdAt: '2026-08-01T12:00:00.000Z', }); expect(otherReceived).not.toHaveBeenCalled(); @@ -169,6 +185,8 @@ describe('ConversationEventsService (real Redis)', () => { bodyFormat: 'TEXT', bodyText: '문의', bodyHtml: null, + imageUrl: null, + orderCard: null, createdAt: new Date(), }, ]), diff --git a/src/features/conversation/services/conversation-inquiry-mappers.helper.spec.ts b/src/features/conversation/services/conversation-inquiry-mappers.helper.spec.ts index bcf431f0..492de78f 100644 --- a/src/features/conversation/services/conversation-inquiry-mappers.helper.spec.ts +++ b/src/features/conversation/services/conversation-inquiry-mappers.helper.spec.ts @@ -1,7 +1,10 @@ import { formatTimeOfDay, renderGreeting, + toConversationMessageOutput, toInquiryBusinessHour, + toOrderCardOutput, + type ConversationMessageRow, } from '@/features/conversation/services/conversation-inquiry-mappers.helper'; describe('conversation-inquiry-mappers.helper', () => { @@ -72,4 +75,41 @@ describe('conversation-inquiry-mappers.helper', () => { }); }); }); + + describe('toOrderCardOutput', () => { + const cardRow: ConversationMessageRow = { + id: 1n, + conversation_id: 2n, + sender_type: 'USER', + body_format: 'ORDER_CARD', + body_text: '주문 문의: 케이크 (ORD-1)', + body_html: null, + image_url: null, + order_card_order_id: 5n, + order_card_order_number: 'ORD-1', + order_card_product_name: '케이크', + order_card_thumbnail_url: null, + order_card_pickup_at: new Date('2026-08-03T03:00:00Z'), + created_at: new Date('2026-08-01T12:00:00Z'), + }; + + it('카드 스냅샷 컬럼으로 주문 카드를 만든다(썸네일은 없으면 null)', () => { + expect(toConversationMessageOutput(cardRow).orderCard).toEqual({ + orderId: '5', + orderNumber: 'ORD-1', + productName: '케이크', + thumbnailUrl: null, + pickupAt: new Date('2026-08-03T03:00:00Z'), + }); + }); + + it.each([ + 'order_card_order_id', + 'order_card_order_number', + 'order_card_product_name', + 'order_card_pickup_at', + ] as const)('%s가 비면 카드가 아니다(null)', (column) => { + expect(toOrderCardOutput({ ...cardRow, [column]: null })).toBeNull(); + }); + }); }); diff --git a/src/features/conversation/services/conversation-inquiry-mappers.helper.ts b/src/features/conversation/services/conversation-inquiry-mappers.helper.ts index 92411bff..774c058d 100644 --- a/src/features/conversation/services/conversation-inquiry-mappers.helper.ts +++ b/src/features/conversation/services/conversation-inquiry-mappers.helper.ts @@ -5,8 +5,10 @@ import { } from '@/features/conversation/constants/conversation.constants'; import type { ConversationMessageOutput, + ConversationOrderCardOutput, InquiryBusinessHourOutput, } from '@/features/conversation/types/conversation-output.type'; +import type { StoreConversationMessage } from '@/generated/prisma/client'; /** placeholder는 등장 위치·횟수 제한 없이 전부 치환한다. */ export function renderGreeting( @@ -40,15 +42,46 @@ export function toInquiryBusinessHour(row: { }; } -export function toConversationMessageOutput(row: { - id: bigint; - conversation_id: bigint; - sender_type: 'USER' | 'STORE' | 'SYSTEM'; - body_format: 'TEXT' | 'HTML'; - body_text: string | null; - body_html: string | null; - created_at: Date; -}): ConversationMessageOutput { +export type ConversationMessageRow = Pick< + StoreConversationMessage, + | 'id' + | 'conversation_id' + | 'sender_type' + | 'body_format' + | 'body_text' + | 'body_html' + | 'image_url' + | 'order_card_order_id' + | 'order_card_order_number' + | 'order_card_product_name' + | 'order_card_thumbnail_url' + | 'order_card_pickup_at' + | 'created_at' +>; + +export function toOrderCardOutput( + row: ConversationMessageRow, +): ConversationOrderCardOutput | null { + if ( + row.order_card_order_id === null || + row.order_card_order_number === null || + row.order_card_product_name === null || + row.order_card_pickup_at === null + ) { + return null; + } + return { + orderId: row.order_card_order_id.toString(), + orderNumber: row.order_card_order_number, + productName: row.order_card_product_name, + thumbnailUrl: row.order_card_thumbnail_url, + pickupAt: row.order_card_pickup_at, + }; +} + +export function toConversationMessageOutput( + row: ConversationMessageRow, +): ConversationMessageOutput { return { id: row.id.toString(), conversationId: row.conversation_id.toString(), @@ -56,6 +89,8 @@ export function toConversationMessageOutput(row: { bodyFormat: row.body_format, bodyText: row.body_text, bodyHtml: row.body_html, + imageUrl: row.image_url, + orderCard: toOrderCardOutput(row), createdAt: row.created_at, }; } diff --git a/src/features/conversation/services/conversation-inquiry.service.spec.ts b/src/features/conversation/services/conversation-inquiry.service.spec.ts index 2a07d9f8..f4bc31da 100644 --- a/src/features/conversation/services/conversation-inquiry.service.spec.ts +++ b/src/features/conversation/services/conversation-inquiry.service.spec.ts @@ -10,19 +10,32 @@ import { import { ConversationRepository } from '@/features/conversation/repositories/conversation.repository'; import { ConversationEventsService } from '@/features/conversation/services/conversation-events.service'; import { ConversationInquiryService } from '@/features/conversation/services/conversation-inquiry.service'; +import { OrderInquiryRepository } from '@/features/order'; import { CATALOG_QUERY } from '@/features/store'; import { StoreCatalogQueryRepository } from '@/features/store/repositories/store-catalog-query.repository'; -import type { PrismaClient } from '@/generated/prisma/client'; +import type { OrderStatus, PrismaClient } from '@/generated/prisma/client'; import { PUB_SUB } from '@/global/pubsub'; import { disconnectTestPrismaClient } from '@/test/db/prisma-test-client'; import { closeTruncateConnection, truncateAll } from '@/test/db/truncate'; import { createAccount, + createOrder, + createOrderItem, createStore, createUserProfile, } from '@/test/factories'; import { createTestingModuleWithRealDb } from '@/test/modules/testing-module.builder'; import { outboxPublisherProviders } from '@/test/outbox'; +import { + FOREIGN_UPLOAD_URL, + ownedUploadUrl, + s3TestProviders, + TEST_S3_CONFIG, +} from '@/test/storage/s3-test.helper'; + +jest.mock('@aws-sdk/s3-request-presigner', () => ({ + getSignedUrl: jest.fn().mockResolvedValue('https://mock-presigned-url.com'), +})); describe('ConversationInquiryService (real DB)', () => { let service: ConversationInquiryService; @@ -37,6 +50,8 @@ describe('ConversationInquiryService (real DB)', () => { // 발행 repository가 OutboxPublisher를 주입받는다 ...outboxPublisherProviders(), ConversationEventsService, + OrderInquiryRepository, + ...s3TestProviders(), AccountUserRepository, { provide: CATALOG_QUERY, useClass: StoreCatalogQueryRepository }, // 발행 경로 실검증은 events service spec(실 Redis) 담당 — 여기선 in-memory @@ -508,4 +523,345 @@ describe('ConversationInquiryService (real DB)', () => { }); }); }); + + /** 매장의 상품 1개짜리 주문. 주문 1건 = 상품 1개 = 매장 1곳. */ + async function orderAt( + accountId: bigint, + storeId: bigint, + overrides: { + status?: OrderStatus; + submitted_at?: Date | null; + product_name_snapshot?: string; + product_thumbnail_url_snapshot?: string | null; + custom_preview_image_url?: string | null; + } = {}, + ) { + const { status, submitted_at, ...item } = overrides; + const order = await createOrder(prisma, { + account_id: accountId, + ...(status ? { status } : {}), + ...(submitted_at !== undefined ? { submitted_at } : {}), + }); + await createOrderItem(prisma, { + order_id: order.id, + store_id: storeId, + ...item, + }); + return order; + } + + describe('숨김 매장 문의(그 매장에 진행 중인 주문이 있는 구매자만)', () => { + it('진행 중인 주문이 있으면 문의 컨텍스트 조회·텍스트·FAQ·이미지 전송을 허용한다', async () => { + const buyer = await setupBuyer(); + const store = await createStore(prisma, { is_active: false }); + const faq = await createFaq(store.id); + await orderAt(buyer.id, store.id, { status: 'CONFIRMED' }); + + await expect( + service.storeInquiryContext(buyer.id, store.id.toString()), + ).resolves.toMatchObject({ storeId: store.id.toString() }); + await service.sendConversationMessage(buyer.id, { + storeId: store.id.toString(), + bodyText: '정지됐다는데 케이크는 받을 수 있나요?', + }); + const faqResult = await service.sendConversationFaqMessage(buyer.id, { + storeId: store.id.toString(), + faqTopicId: faq.id.toString(), + }); + expect(faqResult.messages).toHaveLength(2); + const imageResult = await service.sendConversationImageMessage(buyer.id, { + storeId: store.id.toString(), + imageUrl: ownedUploadUrl('CONVERSATION_IMAGE', buyer.id), + }); + expect(imageResult.messages.map((m) => m.bodyFormat)).toEqual(['IMAGE']); + }); + + it.each([ + ['끝난 주문만 있음', 'PICKED_UP'], + ['취소된 주문만 있음', 'CANCELED'], + ] as const)('%s이면 STORE_NOT_FOUND', async (_label, status) => { + const buyer = await setupBuyer(); + const store = await createStore(prisma, { is_active: false }); + const faq = await createFaq(store.id); + await orderAt(buyer.id, store.id, { status }); + const storeId = store.id.toString(); + + await expect( + service.storeInquiryContext(buyer.id, storeId), + ).rejects.toThrowDomain('STORE_NOT_FOUND'); + await expect( + service.sendConversationMessage(buyer.id, { + storeId, + bodyText: '문의', + }), + ).rejects.toThrowDomain('STORE_NOT_FOUND'); + await expect( + service.sendConversationFaqMessage(buyer.id, { + storeId, + faqTopicId: faq.id.toString(), + }), + ).rejects.toThrowDomain('STORE_NOT_FOUND'); + await expect( + service.sendConversationImageMessage(buyer.id, { + storeId, + imageUrl: ownedUploadUrl('CONVERSATION_IMAGE', buyer.id), + }), + ).rejects.toThrowDomain('STORE_NOT_FOUND'); + expect(await prisma.storeConversationMessage.count()).toBe(0); + }); + + it('다른 구매자·다른 매장의 진행 주문은 허용 근거가 아니고, 삭제된 매장은 진행 주문이 있어도 거절한다', async () => { + const buyer = await setupBuyer(); + const other = await setupBuyer('다른 구매자'); + const hidden = await createStore(prisma, { is_active: false }); + const elsewhere = await createStore(prisma); + const deleted = await createStore(prisma, { deleted_at: new Date() }); + await orderAt(other.id, hidden.id, { status: 'SUBMITTED' }); + await orderAt(buyer.id, elsewhere.id, { status: 'SUBMITTED' }); + await orderAt(buyer.id, deleted.id, { status: 'SUBMITTED' }); + + for (const store of [hidden, deleted]) { + await expect( + service.storeInquiryContext(buyer.id, store.id.toString()), + ).rejects.toThrowDomain('STORE_NOT_FOUND'); + } + }); + }); + + describe('createConversationImageUploadUrl', () => { + it('conversation-images/{accountId}/ 아래로 10MB까지 발급한다', async () => { + const buyer = await setupBuyer(); + + const result = await service.createConversationImageUploadUrl(buyer.id, { + contentType: 'image/png', + contentLength: 10 * 1024 * 1024, + }); + + expect(result.key).toMatch( + new RegExp( + `^conversation-images/${buyer.id}/\\d{4}-\\d{2}-\\d{2}/[a-f0-9-]+\\.png$`, + ), + ); + expect(result.publicUrl).toBe( + `https://${TEST_S3_CONFIG.bucket}.s3.${TEST_S3_CONFIG.region}.amazonaws.com/${result.key}`, + ); + }); + + it.each([ + ['10MB 초과', 'image/png', 10 * 1024 * 1024 + 1, 'FILE_TOO_LARGE'], + ['0바이트', 'image/png', 0, 'INVALID_CONTENT_LENGTH'], + ['이미지가 아닌 형식', 'video/mp4', 1, 'INVALID_CONTENT_TYPE'], + ] as const)('%s는 %s', async (_label, contentType, contentLength, code) => { + const buyer = await setupBuyer(); + await expect( + service.createConversationImageUploadUrl(buyer.id, { + contentType, + contentLength, + }), + ).rejects.toThrowDomain(code); + }); + + it('구매자 계정이 아니면 USER_ONLY', async () => { + const seller = await createAccount(prisma, { account_type: 'SELLER' }); + await expect( + service.createConversationImageUploadUrl(seller.id, { + contentType: 'image/png', + contentLength: 1, + }), + ).rejects.toThrowDomain('USER_ONLY'); + }); + }); + + describe('sendConversationImageMessage', () => { + it('첫 전송이면 인사말 → 이미지 메시지를 저장하고 본문·푸시 미리보기는 대체 문구다', async () => { + const buyer = await setupBuyer(); + const store = await createStore(prisma); + const imageUrl = ownedUploadUrl('CONVERSATION_IMAGE', buyer.id); + + const result = await service.sendConversationImageMessage(buyer.id, { + storeId: store.id.toString(), + imageUrl, + }); + + expect(result.messages.map((m) => m.bodyFormat)).toEqual([ + 'TEXT', + 'IMAGE', + ]); + expect(result.messages[1]).toMatchObject({ + senderType: 'USER', + bodyText: '사진을 보냈습니다.', + bodyHtml: null, + imageUrl, + orderCard: null, + }); + const rows = await messagesOf(BigInt(result.conversationId)); + expect(rows[1]).toMatchObject({ + body_format: 'IMAGE', + image_url: imageUrl, + }); + const [event] = await prisma.outbox.findMany(); + expect( + parseConversationBuyerMessageSentPayload(event.payload_json).preview, + ).toBe('사진을 보냈습니다.'); + }); + + const HOST = `${TEST_S3_CONFIG.bucket}.s3.${TEST_S3_CONFIG.region}.amazonaws.com`; + it.each([ + [ + '다른 계정 경로', + (_me: bigint, other: bigint) => + ownedUploadUrl('CONVERSATION_IMAGE', other), + ], + ['다른 용도 경로', (me: bigint) => ownedUploadUrl('REVIEW_IMAGE', me)], + [ + '인코딩된 dot(%2e) 우회', + (me: bigint, other: bigint) => + `https://${HOST}/conversation-images/${me}/%2e%2e/${other}/a.jpg`, + ], + ['외부 URL', () => FOREIGN_UPLOAD_URL], + [ + '2048자 초과', + (me: bigint) => + ownedUploadUrl('CONVERSATION_IMAGE', me, `${'a'.repeat(2048)}.jpg`), + ], + ])('%s는 INVALID_IMAGE_URL', async (_label, urlOf) => { + const buyer = await setupBuyer(); + const other = await setupBuyer('다른 구매자'); + const store = await createStore(prisma); + + await expect( + service.sendConversationImageMessage(buyer.id, { + storeId: store.id.toString(), + imageUrl: urlOf(buyer.id, other.id), + }), + ).rejects.toThrowDomain('INVALID_IMAGE_URL'); + expect(await prisma.storeConversationMessage.count()).toBe(0); + }); + + it('공백 URL은 IMAGE_URL_REQUIRED', async () => { + const buyer = await setupBuyer(); + const store = await createStore(prisma); + await expect( + service.sendConversationImageMessage(buyer.id, { + storeId: store.id.toString(), + imageUrl: ' ', + }), + ).rejects.toThrowDomain('IMAGE_URL_REQUIRED'); + }); + }); + + describe('sendConversationOrderCard', () => { + it('주문 매장 대화에 보낸 시점 카드(커스텀 대표 이미지 우선)와 대체 문구를 저장한다', async () => { + const buyer = await setupBuyer(); + const store = await createStore(prisma); + const order = await orderAt(buyer.id, store.id, { + status: 'SUBMITTED', + product_name_snapshot: '딸기 케이크', + product_thumbnail_url_snapshot: 'https://cdn.example.com/product.jpg', + custom_preview_image_url: 'https://cdn.example.com/custom.jpg', + }); + const altText = `주문 문의: 딸기 케이크 (${order.order_number})`; + + const result = await service.sendConversationOrderCard( + buyer.id, + order.id.toString(), + ); + + const conversation = await prisma.storeConversation.findFirstOrThrow({ + where: { account_id: buyer.id }, + }); + expect(conversation.store_id).toBe(store.id); + expect(result.messages[1]).toMatchObject({ + senderType: 'USER', + bodyFormat: 'ORDER_CARD', + bodyText: altText, + imageUrl: null, + orderCard: { + orderId: order.id.toString(), + orderNumber: order.order_number, + productName: '딸기 케이크', + thumbnailUrl: 'https://cdn.example.com/custom.jpg', + pickupAt: order.pickup_at, + }, + }); + const [event] = await prisma.outbox.findMany(); + expect( + parseConversationBuyerMessageSentPayload(event.payload_json).preview, + ).toBe(altText); + }); + + it('입금 확인 뒤 취소된 주문도 판매자가 볼 수 있어 보낼 수 있다', async () => { + const buyer = await setupBuyer(); + const store = await createStore(prisma); + const order = await orderAt(buyer.id, store.id, { + status: 'CANCELED', + submitted_at: new Date(), + }); + + const result = await service.sendConversationOrderCard( + buyer.id, + order.id.toString(), + ); + expect(result.messages.at(-1)?.bodyFormat).toBe('ORDER_CARD'); + }); + + it('다른 구매자의 주문·삭제된 주문·없는 주문은 ORDER_NOT_FOUND', async () => { + const buyer = await setupBuyer(); + const other = await setupBuyer('다른 구매자'); + const store = await createStore(prisma); + const others = await orderAt(other.id, store.id); + const deleted = await orderAt(buyer.id, store.id); + await prisma.order.update({ + where: { id: deleted.id }, + data: { deleted_at: new Date() }, + }); + + for (const id of [others.id.toString(), deleted.id.toString(), '0']) { + await expect( + service.sendConversationOrderCard(buyer.id, id), + ).rejects.toThrowDomain('ORDER_NOT_FOUND'); + } + }); + + it.each([ + ['입금 대기', 'PENDING_PAYMENT'], + ['입금 전 취소', 'CANCELED'], + ] as const)( + '%s 주문(입금 확인 전)은 ORDER_INQUIRY_NOT_AVAILABLE', + async (_label, status) => { + const buyer = await setupBuyer(); + const store = await createStore(prisma); + const order = await orderAt(buyer.id, store.id, { + status, + submitted_at: null, + }); + + await expect( + service.sendConversationOrderCard(buyer.id, order.id.toString()), + ).rejects.toThrowDomain('ORDER_INQUIRY_NOT_AVAILABLE'); + expect(await prisma.storeConversationMessage.count()).toBe(0); + }, + ); + + it('숨김 매장은 카드 주문이 진행 중이면 보내고, 끝난 주문이면 STORE_NOT_FOUND', async () => { + const buyer = await setupBuyer(); + const store = await createStore(prisma, { is_active: false }); + const made = await orderAt(buyer.id, store.id, { status: 'MADE' }); + const pickedUp = await orderAt(buyer.id, store.id, { + status: 'PICKED_UP', + }); + + await expect( + service.sendConversationOrderCard(buyer.id, pickedUp.id.toString()), + ).resolves.toMatchObject({ messages: expect.any(Array) }); + + await prisma.order.update({ + where: { id: made.id }, + data: { status: 'PICKED_UP' }, + }); + await expect( + service.sendConversationOrderCard(buyer.id, pickedUp.id.toString()), + ).rejects.toThrowDomain('STORE_NOT_FOUND'); + }); + }); }); diff --git a/src/features/conversation/services/conversation-inquiry.service.ts b/src/features/conversation/services/conversation-inquiry.service.ts index 7e7e762a..863cd8aa 100644 --- a/src/features/conversation/services/conversation-inquiry.service.ts +++ b/src/features/conversation/services/conversation-inquiry.service.ts @@ -4,13 +4,21 @@ import { DomainException } from '@/common/errors/error-catalog'; import { parseId } from '@/common/utils/id-parser'; import { cleanRequiredText } from '@/common/utils/text-cleaner'; import { AccountUserRepository } from '@/features/auth'; -import { MAX_INQUIRY_BODY_TEXT_LENGTH } from '@/features/conversation/constants/conversation.constants'; +import { + CONVERSATION_IMAGE_ALT_TEXT, + MAX_INQUIRY_BODY_TEXT_LENGTH, +} from '@/features/conversation/constants/conversation.constants'; import type { SendConversationFaqMessageInput } from '@/features/conversation/dto/inputs/send-conversation-faq-message.input'; +import type { SendConversationImageMessageInput } from '@/features/conversation/dto/inputs/send-conversation-image-message.input'; import type { SendConversationMessageInput } from '@/features/conversation/dto/inputs/send-conversation-message.input'; import { ConversationRepository, type ConversationMessageEntry, } from '@/features/conversation/repositories/conversation.repository'; +import { + orderCardAltText, + requireOwnedConversationImageUrl, +} from '@/features/conversation/services/conversation-attachment.helper'; import { ConversationBaseService } from '@/features/conversation/services/conversation-base.service'; import { toLastMessagePreview } from '@/features/conversation/services/conversation-center-mappers.helper'; import { toEventPreview } from '@/features/conversation/services/conversation-events-mappers.helper'; @@ -24,11 +32,14 @@ import type { ConversationMessagesPayload, StoreInquiryContextOutput, } from '@/features/conversation/types/conversation-output.type'; +import { OrderInquiryRepository } from '@/features/order'; import { CATALOG_QUERY, type ICatalogQuery } from '@/features/store'; import { ConversationBodyFormat, ConversationSenderType, } from '@/generated/prisma/client'; +import { S3Service } from '@/global/storage/s3.service'; +import type { CreateUploadUrlOutput } from '@/global/storage/types/storage.types'; @Injectable() export class ConversationInquiryService extends ConversationBaseService { @@ -39,6 +50,8 @@ export class ConversationInquiryService extends ConversationBaseService { accounts: AccountUserRepository, private readonly events: ConversationEventsService, @Inject(CATALOG_QUERY) private readonly catalog: ICatalogQuery, + private readonly orders: OrderInquiryRepository, + private readonly s3: S3Service, ) { super(repo, accounts); } @@ -50,7 +63,7 @@ export class ConversationInquiryService extends ConversationBaseService { const { nickname } = await this.requireActiveUser(accountId); const storeId = parseId(storeIdRaw); - const store = await this.requireInquiryStore(storeId); + const store = await this.requireInquiryStore(accountId, storeId); const [faqTopics, conversation] = await Promise.all([ this.catalog.listActiveFaqTopics(storeId), this.repo.findConversationByAccountAndStore({ accountId, storeId }), @@ -79,7 +92,7 @@ export class ConversationInquiryService extends ConversationBaseService { ): Promise { const { nickname } = await this.requireActiveUser(accountId); const storeId = parseId(input.storeId); - const store = await this.requireInquiryStore(storeId); + const store = await this.requireInquiryStore(accountId, storeId); const bodyText = cleanRequiredText( input.bodyText, @@ -110,7 +123,7 @@ export class ConversationInquiryService extends ConversationBaseService { ): Promise { const { nickname } = await this.requireActiveUser(accountId); const storeId = parseId(input.storeId); - const store = await this.requireInquiryStore(storeId); + const store = await this.requireInquiryStore(accountId, storeId); const topic = await this.catalog.findActiveFaqTopic({ storeId, @@ -146,6 +159,92 @@ export class ConversationInquiryService extends ConversationBaseService { }); } + async createConversationImageUploadUrl( + accountId: bigint, + input: { contentType: string; contentLength: number }, + ): Promise { + await this.requireActiveUser(accountId); + return this.s3.createUploadUrl({ + accountId, + purpose: 'CONVERSATION_IMAGE', + contentType: input.contentType, + contentLength: input.contentLength, + }); + } + + async sendConversationImageMessage( + accountId: bigint, + input: SendConversationImageMessageInput, + ): Promise { + const { nickname } = await this.requireActiveUser(accountId); + const storeId = parseId(input.storeId); + const store = await this.requireInquiryStore(accountId, storeId); + const imageUrl = requireOwnedConversationImageUrl( + this.s3, + input.imageUrl, + accountId, + ); + + return this.saveBuyerMessages({ + accountId, + storeId, + nickname, + storeName: store.store_name, + greetingTemplate: store.greeting_message, + entries: [ + { + senderType: ConversationSenderType.USER, + senderAccountId: accountId, + bodyFormat: ConversationBodyFormat.IMAGE, + bodyText: CONVERSATION_IMAGE_ALT_TEXT, + bodyHtml: null, + imageUrl, + }, + ], + }); + } + + /** 판매자가 볼 수 없는 입금 전 주문은 카드로 보낼 수 없다. 카드는 보낸 시점 값으로 남는다. */ + async sendConversationOrderCard( + accountId: bigint, + orderIdRaw: string, + ): Promise { + const { nickname } = await this.requireActiveUser(accountId); + const source = await this.orders.findOrderCardSource({ + orderId: parseId(orderIdRaw), + accountId, + }); + if (!source) throw new DomainException('ORDER_NOT_FOUND'); + if (source.submittedAt === null) { + throw new DomainException('ORDER_INQUIRY_NOT_AVAILABLE'); + } + const store = await this.requireInquiryStore(accountId, source.storeId); + + return this.saveBuyerMessages({ + accountId, + storeId: source.storeId, + nickname, + storeName: store.store_name, + greetingTemplate: store.greeting_message, + entries: [ + { + senderType: ConversationSenderType.USER, + senderAccountId: accountId, + bodyFormat: ConversationBodyFormat.ORDER_CARD, + bodyText: orderCardAltText(source), + bodyHtml: null, + orderCard: { + orderId: source.orderId, + orderNumber: source.orderNumber, + productName: source.productName, + thumbnailUrl: source.thumbnailUrl, + pickupAt: source.pickupAt, + }, + }, + ], + }); + } + private async saveBuyerMessages(args: { accountId: bigint; storeId: bigint; @@ -252,9 +351,17 @@ export class ConversationInquiryService extends ConversationBaseService { }); } - private async requireInquiryStore(storeId: bigint) { + /** 숨김 매장은 진행 중인 주문이 있는 구매자만 문의할 수 있다(판매자 정지·매장 숨김 뒤에도 주문 문의 경로를 남긴다). */ + private async requireInquiryStore(accountId: bigint, storeId: bigint) { const store = await this.catalog.findInquiryStore(storeId); - if (!store) { + if ( + !store || + (!store.is_active && + !(await this.orders.existsInProgressOrderAtStore({ + accountId, + storeId, + }))) + ) { throw new DomainException('STORE_NOT_FOUND'); } return store; diff --git a/src/features/conversation/services/conversation-seller.service.spec.ts b/src/features/conversation/services/conversation-seller.service.spec.ts index b222fc81..3d885a69 100644 --- a/src/features/conversation/services/conversation-seller.service.spec.ts +++ b/src/features/conversation/services/conversation-seller.service.spec.ts @@ -13,6 +13,11 @@ import { closeTruncateConnection, truncateAll } from '@/test/db/truncate'; import { createAccount, setupSellerWithStore } from '@/test/factories'; import { createTestingModuleWithRealDb } from '@/test/modules/testing-module.builder'; import { outboxPublisherProviders } from '@/test/outbox'; +import { + ownedUploadUrl, + s3TestProviders, + TEST_S3_CONFIG, +} from '@/test/storage/s3-test.helper'; describe('SellerConversationService (real DB)', () => { let service: SellerConversationService; @@ -28,6 +33,7 @@ describe('SellerConversationService (real DB)', () => { // 발행 repository가 OutboxPublisher를 주입받는다 ...outboxPublisherProviders(), ConversationEventsService, + ...s3TestProviders(), { provide: PUB_SUB, useValue: new PubSub() }, { provide: AUDIT_LOG_REPOSITORY, @@ -423,4 +429,129 @@ describe('SellerConversationService (real DB)', () => { expect(systemMsg!.senderAccountId).toBeNull(); }); }); + + describe('sellerSendConversationMessage IMAGE·ORDER_CARD', () => { + it('IMAGE는 판매자에게 발급된 URL을 저장하고 본문은 대체 문구다(다른 본문 무시, 감사 기록)', async () => { + const { account, store } = await setupSellerWithStore(prisma); + const conv = await setupConversation(store.id); + const imageUrl = ownedUploadUrl('CONVERSATION_IMAGE', account.id); + + const result = await service.sellerSendConversationMessage(account.id, { + conversationId: conv.id.toString(), + bodyFormat: 'IMAGE', + bodyText: '무시되는 본문', + imageUrl: ` ${imageUrl} `, + }); + + expect(result).toMatchObject({ + bodyFormat: 'IMAGE', + bodyText: '사진을 보냈습니다.', + bodyHtml: null, + imageUrl, + orderCard: null, + }); + const [row] = await prisma.storeConversationMessage.findMany({ + where: { conversation_id: conv.id }, + }); + expect(row).toMatchObject({ body_format: 'IMAGE', image_url: imageUrl }); + expect( + await prisma.auditLog.count({ + where: { store_id: store.id, target_type: 'CONVERSATION' }, + }), + ).toBe(1); + }); + + it.each([undefined, ' '])( + 'IMAGE인데 imageUrl이 %p면 IMAGE_URL_REQUIRED', + async (imageUrl) => { + const { account, store } = await setupSellerWithStore(prisma); + const conv = await setupConversation(store.id); + await expect( + service.sellerSendConversationMessage(account.id, { + conversationId: conv.id.toString(), + bodyFormat: 'IMAGE', + imageUrl, + }), + ).rejects.toThrowDomain('IMAGE_URL_REQUIRED'); + }, + ); + + const HOST = `${TEST_S3_CONFIG.bucket}.s3.${TEST_S3_CONFIG.region}.amazonaws.com`; + it.each([ + [ + '구매자 계정 경로', + (_seller: bigint, buyer: bigint) => + ownedUploadUrl('CONVERSATION_IMAGE', buyer), + ], + [ + '다른 용도 경로', + (seller: bigint) => ownedUploadUrl('PRODUCT_IMAGE', seller), + ], + [ + '인코딩된 dot(%2e) 우회', + (seller: bigint, buyer: bigint) => + `https://${HOST}/conversation-images/${seller}/%2e%2e/${buyer}/a.jpg`, + ], + ])('%s는 INVALID_IMAGE_URL', async (_label, urlOf) => { + const { account, store } = await setupSellerWithStore(prisma); + const conv = await setupConversation(store.id); + await expect( + service.sellerSendConversationMessage(account.id, { + conversationId: conv.id.toString(), + bodyFormat: 'IMAGE', + imageUrl: urlOf(account.id, conv.account_id), + }), + ).rejects.toThrowDomain('INVALID_IMAGE_URL'); + expect(await prisma.storeConversationMessage.count()).toBe(0); + }); + + it('ORDER_CARD는 구매자만 보낼 수 있어 INVALID_BODY_FORMAT', async () => { + const { account, store } = await setupSellerWithStore(prisma); + const conv = await setupConversation(store.id); + await expect( + service.sellerSendConversationMessage(account.id, { + conversationId: conv.id.toString(), + bodyFormat: 'ORDER_CARD', + bodyText: '주문 문의', + }), + ).rejects.toThrowDomain('INVALID_BODY_FORMAT'); + }); + + it('메시지 목록에 이미지·주문 카드 스냅샷이 실린다', async () => { + const { account, store } = await setupSellerWithStore(prisma); + const conv = await setupConversation(store.id); + const pickupAt = new Date('2026-08-03T03:00:00Z'); + await prisma.storeConversationMessage.create({ + data: { + conversation_id: conv.id, + sender_type: 'USER', + sender_account_id: conv.account_id, + body_format: 'ORDER_CARD', + body_text: '주문 문의: 케이크 (ORD-1)', + order_card_order_id: 77n, + order_card_order_number: 'ORD-1', + order_card_product_name: '케이크', + order_card_thumbnail_url: 'https://cdn.example.com/t.jpg', + order_card_pickup_at: pickupAt, + }, + }); + + const result = await service.sellerConversationMessages( + account.id, + conv.id, + ); + + expect(result.items[0]).toMatchObject({ + bodyFormat: 'ORDER_CARD', + imageUrl: null, + orderCard: { + orderId: '77', + orderNumber: 'ORD-1', + productName: '케이크', + thumbnailUrl: 'https://cdn.example.com/t.jpg', + pickupAt, + }, + }); + }); + }); }); diff --git a/src/features/conversation/services/conversation-seller.service.ts b/src/features/conversation/services/conversation-seller.service.ts index d0e54e9a..50c0e697 100644 --- a/src/features/conversation/services/conversation-seller.service.ts +++ b/src/features/conversation/services/conversation-seller.service.ts @@ -21,14 +21,20 @@ import { type IAuditLogRepository, } from '@/features/audit-log'; import { + CONVERSATION_IMAGE_ALT_TEXT, MAX_CONVERSATION_BODY_HTML_LENGTH, MAX_INQUIRY_BODY_TEXT_LENGTH, } from '@/features/conversation/constants/conversation.constants'; import type { SellerSendConversationMessageInput } from '@/features/conversation/dto/inputs/seller-send-conversation-message.input'; import { ConversationRepository } from '@/features/conversation/repositories/conversation.repository'; +import { requireOwnedConversationImageUrl } from '@/features/conversation/services/conversation-attachment.helper'; import { toLastMessagePreview } from '@/features/conversation/services/conversation-center-mappers.helper'; import { toEventPreview } from '@/features/conversation/services/conversation-events-mappers.helper'; import { ConversationEventsService } from '@/features/conversation/services/conversation-events.service'; +import { + toConversationMessageOutput, + type ConversationMessageRow, +} from '@/features/conversation/services/conversation-inquiry-mappers.helper'; import type { SellerConversationMessageOutput, SellerConversationOutput, @@ -39,6 +45,7 @@ import { AuditTargetType, ConversationBodyFormat, } from '@/generated/prisma/client'; +import { S3Service } from '@/global/storage/s3.service'; @Injectable() export class SellerConversationService extends SellerBaseService { @@ -50,6 +57,7 @@ export class SellerConversationService extends SellerBaseService { auditLogs: IAuditLogRepository, private readonly conversationRepository: ConversationRepository, private readonly conversationEvents: ConversationEventsService, + private readonly s3: S3Service, ) { super(repo, auditLogs); } @@ -154,33 +162,12 @@ export class SellerConversationService extends SellerBaseService { }); if (!conversation) throw new DomainException('CONVERSATION_NOT_FOUND'); - const bodyFormat = this.toConversationBodyFormat(input.bodyFormat); - const bodyText = cleanNullableText( - input.bodyText, - MAX_INQUIRY_BODY_TEXT_LENGTH, - ); - const bodyHtml = cleanNullableText( - input.bodyHtml, - MAX_CONVERSATION_BODY_HTML_LENGTH, - ); - - if (bodyFormat === ConversationBodyFormat.TEXT && !bodyText) { - throw new DomainException('BODY_TEXT_REQUIRED'); - } - if (bodyFormat === ConversationBodyFormat.HTML && !bodyHtml) { - throw new DomainException('BODY_HTML_REQUIRED'); - } + const body = this.toSellerMessageBody(input, ctx.accountId); // 감사 기록은 repository가 메시지 저장과 같은 트랜잭션에서 남긴다 const row = await this.conversationRepository.createSellerConversationMessage( - { - conversationId, - sellerAccountId: ctx.accountId, - bodyFormat, - bodyText, - bodyHtml, - }, + { conversationId, sellerAccountId: ctx.accountId, ...body }, (created) => ({ actorAccountId: ctx.accountId, storeId: ctx.storeId, @@ -234,15 +221,7 @@ export class SellerConversationService extends SellerBaseService { storeId: bigint; message: SellerConversationMessageOutput; }): Promise { - const message = { - id: args.message.id, - conversationId: args.message.conversationId, - senderType: args.message.senderType, - bodyFormat: args.message.bodyFormat, - bodyText: args.message.bodyText, - bodyHtml: args.message.bodyHtml, - createdAt: args.message.createdAt, - }; + const { message } = args; // 목록 이벤트는 발행 시점의 최신 커밋 상태를 단일 트랜잭션 스냅샷으로 조립한다 — 독립 조회로 쪼개면 // 경쟁 커밋이 끼어들어 혼합 상태가 나갈 수 있다. 메시지 스트림은 id 정렬. const snapshot = @@ -287,10 +266,54 @@ export class SellerConversationService extends SellerBaseService { ); } - private toConversationBodyFormat(raw: string): ConversationBodyFormat { - if (raw === 'TEXT') return ConversationBodyFormat.TEXT; - if (raw === 'HTML') return ConversationBodyFormat.HTML; - throw new DomainException('INVALID_BODY_FORMAT'); + /** IMAGE는 대체 문구만 본문으로 남긴다. 주문 카드는 구매자만 보낼 수 있다. */ + private toSellerMessageBody( + input: SellerSendConversationMessageInput, + sellerAccountId: bigint, + ): { + bodyFormat: ConversationBodyFormat; + bodyText: string | null; + bodyHtml: string | null; + imageUrl: string | null; + } { + switch (input.bodyFormat) { + case ConversationBodyFormat.IMAGE: + return { + bodyFormat: input.bodyFormat, + bodyText: CONVERSATION_IMAGE_ALT_TEXT, + bodyHtml: null, + imageUrl: requireOwnedConversationImageUrl( + this.s3, + input.imageUrl, + sellerAccountId, + ), + }; + case ConversationBodyFormat.TEXT: + case ConversationBodyFormat.HTML: { + const bodyText = cleanNullableText( + input.bodyText, + MAX_INQUIRY_BODY_TEXT_LENGTH, + ); + const bodyHtml = cleanNullableText( + input.bodyHtml, + MAX_CONVERSATION_BODY_HTML_LENGTH, + ); + if (input.bodyFormat === ConversationBodyFormat.TEXT && !bodyText) { + throw new DomainException('BODY_TEXT_REQUIRED'); + } + if (input.bodyFormat === ConversationBodyFormat.HTML && !bodyHtml) { + throw new DomainException('BODY_HTML_REQUIRED'); + } + return { + bodyFormat: input.bodyFormat, + bodyText, + bodyHtml, + imageUrl: null, + }; + } + default: + throw new DomainException('INVALID_BODY_FORMAT'); + } } private toConversationOutput( @@ -323,25 +346,12 @@ export class SellerConversationService extends SellerBaseService { }; } - private toConversationMessageOutput(row: { - id: bigint; - conversation_id: bigint; - sender_type: 'USER' | 'STORE' | 'SYSTEM'; - sender_account_id: bigint | null; - body_format: 'TEXT' | 'HTML'; - body_text: string | null; - body_html: string | null; - created_at: Date; - }): SellerConversationMessageOutput { + private toConversationMessageOutput( + row: ConversationMessageRow & { sender_account_id: bigint | null }, + ): SellerConversationMessageOutput { return { - id: row.id.toString(), - conversationId: row.conversation_id.toString(), - senderType: row.sender_type, + ...toConversationMessageOutput(row), senderAccountId: row.sender_account_id?.toString() ?? null, - bodyFormat: row.body_format, - bodyText: row.body_text, - bodyHtml: row.body_html, - createdAt: row.created_at, }; } } diff --git a/src/features/conversation/services/conversation-subscription.service.spec.ts b/src/features/conversation/services/conversation-subscription.service.spec.ts index b79a0aa8..667cb1b3 100644 --- a/src/features/conversation/services/conversation-subscription.service.spec.ts +++ b/src/features/conversation/services/conversation-subscription.service.spec.ts @@ -7,6 +7,7 @@ import { ConversationRepository } from '@/features/conversation/repositories/con import { ConversationEventsService } from '@/features/conversation/services/conversation-events.service'; import { ConversationInquiryService } from '@/features/conversation/services/conversation-inquiry.service'; import { ConversationSubscriptionService } from '@/features/conversation/services/conversation-subscription.service'; +import { OrderInquiryRepository } from '@/features/order'; import { CATALOG_QUERY, StoreSellerRepository } from '@/features/store'; import { StoreCatalogQueryRepository } from '@/features/store/repositories/store-catalog-query.repository'; import type { PrismaClient } from '@/generated/prisma/client'; @@ -20,6 +21,7 @@ import { } from '@/test/factories'; import { createTestingModuleWithRealDb } from '@/test/modules/testing-module.builder'; import { outboxPublisherProviders } from '@/test/outbox'; +import { s3TestProviders } from '@/test/storage/s3-test.helper'; describe('ConversationSubscriptionService (real DB)', () => { let service: ConversationSubscriptionService; @@ -32,6 +34,8 @@ describe('ConversationSubscriptionService (real DB)', () => { ConversationSubscriptionService, ConversationInquiryService, ConversationEventsService, + OrderInquiryRepository, + ...s3TestProviders(), ConversationRepository, // 발행 repository가 OutboxPublisher를 주입받는다 ...outboxPublisherProviders(), diff --git a/src/features/conversation/types/conversation-output.type.ts b/src/features/conversation/types/conversation-output.type.ts index 67d20982..bd46e17b 100644 --- a/src/features/conversation/types/conversation-output.type.ts +++ b/src/features/conversation/types/conversation-output.type.ts @@ -26,6 +26,14 @@ export interface StoreInquiryContextOutput { conversationId: string | null; } +export interface ConversationOrderCardOutput { + orderId: string; + orderNumber: string; + productName: string; + thumbnailUrl: string | null; + pickupAt: Date; +} + export interface ConversationMessageOutput { id: string; conversationId: string; @@ -33,6 +41,8 @@ export interface ConversationMessageOutput { bodyFormat: ConversationBodyFormat; bodyText: string | null; bodyHtml: string | null; + imageUrl: string | null; + orderCard: ConversationOrderCardOutput | null; createdAt: Date; } @@ -65,6 +75,12 @@ export interface ConversationMessageEvent { bodyFormat: ConversationBodyFormat; bodyText: string | null; bodyHtml: string | null; + imageUrl: string | null; + orderCard: + | (Omit & { + pickupAt: string; + }) + | null; createdAt: string; } diff --git a/src/features/conversation/types/conversation-seller-output.type.ts b/src/features/conversation/types/conversation-seller-output.type.ts index 61a93e1b..d76c9978 100644 --- a/src/features/conversation/types/conversation-seller-output.type.ts +++ b/src/features/conversation/types/conversation-seller-output.type.ts @@ -1,3 +1,5 @@ +import type { ConversationMessageOutput } from '@/features/conversation/types/conversation-output.type'; + export interface SellerConversationOutput { id: string; accountId: string; @@ -11,13 +13,6 @@ export interface SellerConversationOutput { updatedAt: Date; } -export interface SellerConversationMessageOutput { - id: string; - conversationId: string; - senderType: 'USER' | 'STORE' | 'SYSTEM'; +export interface SellerConversationMessageOutput extends ConversationMessageOutput { senderAccountId: string | null; - bodyFormat: 'TEXT' | 'HTML'; - bodyText: string | null; - bodyHtml: string | null; - createdAt: Date; } diff --git a/src/features/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/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/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/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..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.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 () => { + it('옵션·커스텀 대표 이미지가 없는 품목이면 option_summary·before_image_url은 null', async () => { const ctx = await setupReviewableOrderItem(); const result = await service.writeReview(ctx.accountId, { orderItemId: ctx.orderItemId.toString(), @@ -406,27 +430,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(); @@ -463,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 모두 새 값으로 교체되어야 함 @@ -498,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({ @@ -733,7 +758,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 +863,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/notification/constants/notification-messages.ts b/src/features/notification/constants/notification-messages.ts index 7112846d..a8774d8d 100644 --- a/src/features/notification/constants/notification-messages.ts +++ b/src/features/notification/constants/notification-messages.ts @@ -1,26 +1,45 @@ import { OrderStatus } from '@/generated/prisma/client'; -/** 매핑이 없는 상태는 알림을 만들지 않는다. */ +/** 매핑이 없는 상태는 알림을 만들지 않는다. 취소는 아래 문구로 따로 만든다. */ export const ORDER_STATUS_NOTIFICATION_TITLES: Partial< Record > = { + [OrderStatus.SUBMITTED]: '입금확인', [OrderStatus.CONFIRMED]: '주문확정', [OrderStatus.MADE]: '제작완료', [OrderStatus.PICKED_UP]: '픽업완료', - // 관리자 강제 취소 도입 시 판매자 취소와 함께 알리기로 확정 - [OrderStatus.CANCELED]: '주문취소', + [OrderStatus.NO_SHOW]: '노쇼', }; /** 주문번호 prefix는 식별 필요 가능성에 대비해 유지한다 — 표시 여부는 FE 판단. */ export const ORDER_STATUS_NOTIFICATION_BODIES: Partial< Record > = { + [OrderStatus.SUBMITTED]: '입금이 확인되어 주문이 접수되었어요.', [OrderStatus.CONFIRMED]: '주문이 확정되었어요.', [OrderStatus.MADE]: '주문하신 케이크 제작이 완료되었어요.', [OrderStatus.PICKED_UP]: '케이크 픽업이 완료되었어요.', - [OrderStatus.CANCELED]: '주문이 취소되었어요.', + [OrderStatus.NO_SHOW]: '픽업 시간에 방문하지 않아 노쇼로 처리되었어요.', }; +/** 취소는 사유 라벨을 덧붙인다(판매자·운영자·자동 미확정 공통). */ +export const ORDER_CANCELED_NOTIFICATION = { + title: '주문취소', + body: '주문이 취소되었어요.', +} as const; + +/** 미입금(PAYMENT_NOT_RECEIVED) 취소는 일반 취소 문구 대신 이 문구로 알린다. */ +export const ORDER_PAYMENT_EXPIRED_NOTIFICATION = { + title: '주문취소', + body: '입금이 확인되지 않아 주문이 취소되었어요.', +} as const; + +export const ORDER_PICKUP_RESCHEDULED_TITLE = '픽업변경'; + +export const REFUND_ACCOUNT_REQUESTED_TITLE = '환불계좌입력'; + +export const REFUND_COMPLETED_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 8aa59e88..cfab71ea 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 """ @@ -41,7 +41,31 @@ enum NotificationEvent { """ ORDER_PICKED_UP """ - 주문이 취소됐다(판매자 또는 운영자). type은 ORDER_STATUS. + 주문이 취소됐다(판매자·운영자·자동 미확정). 본문 끝에 사유 라벨이 붙고, 구매자 본인 취소는 알림이 없다. type은 ORDER_STATUS. """ ORDER_CANCELED + """ + 입금이 확인돼 주문이 접수됐다. type은 ORDER_STATUS. + """ + ORDER_PAYMENT_CONFIRMED + """ + 입금이 확인되지 않아 주문이 취소됐다(입금 기한 만료 자동 취소 또는 운영자 미입금 취소). type은 ORDER_STATUS. + """ + ORDER_PAYMENT_EXPIRED + """ + 픽업 시간에 방문하지 않아 노쇼로 처리됐다. type은 ORDER_STATUS. + """ + ORDER_NO_SHOW + """ + 판매자가 픽업 일시를 바꿨다. type은 ORDER_STATUS. + """ + ORDER_PICKUP_RESCHEDULED + """ + 돌려받을 돈이 생겨 환불 계좌 입력이 필요하다. type은 ORDER_STATUS. + """ + REFUND_ACCOUNT_REQUESTED + """ + 환불 송금이 끝났다. type은 ORDER_STATUS. + """ + REFUND_COMPLETED } diff --git a/src/features/notification/services/notification-outbox.consumer.spec.ts b/src/features/notification/services/notification-outbox.consumer.spec.ts index 99664075..403e67e3 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, @@ -131,6 +158,185 @@ 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 형식 오류'); + }); + + async function refundPayload(orderNumber: string) { + 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 }); + return { + buyer, + order, + item, + payload: { + refundId: '6', + orderId: order.id.toString(), + orderNumber, + buyerAccountId: buyer.id.toString(), + kind: 'DEPOSIT_RETURN', + amount: 30_000, + storeId: item.store_id.toString(), + storeName: '케이크샵', + productId: item.product_id.toString(), + productName: '레터링 케이크', + }, + }; + } + + it('취소와 함께 계좌가 들어온 refund.requested는 계좌 요청 알림을 만들지 않는다', async () => { + const { payload } = await refundPayload('ORD-5'); + + await consumer.handle( + event('refund.requested', { ...payload, accountSubmitted: true }), + ); + + expect(await prisma.notification.count()).toBe(0); + }); + + it('refund.completed는 구매자에게 환불 완료 알림을 만들고, 재전달은 중복을 만들지 않는다', async () => { + const { buyer, order, item, payload } = await refundPayload('ORD-6'); + const completed = event('refund.completed', payload); + + await consumer.handle(completed); + await consumer.handle(completed); + + const rows = await prisma.notification.findMany(); + expect(rows).toHaveLength(1); + expect(rows[0]).toMatchObject({ + account_id: buyer.id, + type: 'ORDER_STATUS', + event: 'REFUND_COMPLETED', + title: '환불완료', + body: 'ORD-6 30,000원 환불이 완료되었어요.', + order_id: order.id, + store_id: item.store_id, + product_id: item.product_id, + order_number: 'ORD-6', + created_at: OCCURRED_AT, + }); + }); + + it('반증: 형식이 어긋난 refund.completed는 던진다', async () => { + await expect( + consumer.handle(event('refund.completed', { refundId: 6 })), + ).rejects.toThrow('refund.completed payload 형식 오류'); + }); + }); + + it('order.pickup_rescheduled는 구매자에게 바뀐 픽업 일시(KST) 알림을 만들고, 재전달은 중복을 만들지 않는다', 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 rescheduled = event('order.pickup_rescheduled', { + orderId: order.id.toString(), + orderNumber: 'ORD-5', + buyerAccountId: buyer.id.toString(), + storeId: item.store_id.toString(), + storeName: '케이크샵', + productId: item.product_id.toString(), + productName: '레터링 케이크', + fromPickupAt: '2026-09-20T05:00:00.000Z', + toPickupAt: '2026-09-21T06:30:00.000Z', + }); + + await consumer.handle(rescheduled); + await consumer.handle(rescheduled); + + const rows = await prisma.notification.findMany(); + expect(rows).toHaveLength(1); + expect(rows[0]).toMatchObject({ + account_id: buyer.id, + type: 'ORDER_STATUS', + event: 'ORDER_PICKUP_RESCHEDULED', + title: '픽업변경', + body: 'ORD-5 픽업 일시가 9/21 15:30로 변경되었어요.', + order_id: order.id, + store_id: item.store_id, + product_id: item.product_id, + created_at: OCCURRED_AT, + }); + }); + 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 e730176c..5885e46a 100644 --- a/src/features/notification/services/notification-outbox.consumer.ts +++ b/src/features/notification/services/notification-outbox.consumer.ts @@ -13,12 +13,23 @@ import { NotificationRepository, } from '@/features/notification/repositories/notification.repository'; import { + buildOrderPickupRescheduledNotification, buildOrderStatusNotification, + buildRefundAccountRequestedNotification, + buildRefundCompletedNotification, buildReviewLikedNotification, + type NotificationPayload, } from '@/features/notification/services/notification-payloads.helper'; import { + ORDER_PICKUP_RESCHEDULED, ORDER_STATUS_CHANGED, + parseOrderPickupRescheduledPayload, parseOrderStatusChangedPayload, + parseRefundCompletedPayload, + parseRefundRequestedPayload, + REFUND_COMPLETED, + REFUND_REQUESTED, + type RefundEventPayload, } from '@/features/order'; import { type OutboxConsumer, @@ -34,6 +45,9 @@ import { parseReviewLikedPayload, REVIEW_LIKED } from '@/features/review'; @Injectable() @SubscribeOutbox( ORDER_STATUS_CHANGED, + ORDER_PICKUP_RESCHEDULED, + REFUND_REQUESTED, + REFUND_COMPLETED, REVIEW_LIKED, NOTIFICATION_BROADCAST_REQUESTED, ) @@ -50,6 +64,12 @@ export class NotificationOutboxConsumer implements OutboxConsumer { switch (event.eventType) { case ORDER_STATUS_CHANGED: return this.onOrderStatusChanged(event); + case ORDER_PICKUP_RESCHEDULED: + return this.onPickupRescheduled(event); + case REFUND_REQUESTED: + return this.onRefundRequested(event); + case REFUND_COMPLETED: + return this.onRefundCompleted(event); case REVIEW_LIKED: return this.onReviewLiked(event); case NOTIFICATION_BROADCAST_REQUESTED: @@ -61,8 +81,8 @@ export class NotificationOutboxConsumer implements OutboxConsumer { private async onOrderStatusChanged(event: OutboxEvent): Promise { const p = parseOrderStatusChangedPayload(event.payload); - // SUBMITTED 등 알림 대상이 아닌 전이는 payload가 null — 이벤트는 정상 소비된다 - const payload = buildOrderStatusNotification(p.orderNumber, p.toStatus); + // 알림 대상이 아닌 전이는 payload가 null — 이벤트는 정상 소비된다 + const payload = buildOrderStatusNotification(p); if (!payload) return; await this.repo.createFromEvent(event.eventId, [ { @@ -79,6 +99,66 @@ export class NotificationOutboxConsumer implements OutboxConsumer { ]); } + private async onPickupRescheduled(event: OutboxEvent): Promise { + const p = parseOrderPickupRescheduledPayload(event.payload); + await this.repo.createFromEvent(event.eventId, [ + { + account_id: parseId(p.buyerAccountId), + ...buildOrderPickupRescheduledNotification( + p.orderNumber, + new Date(p.toPickupAt), + ), + 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 onRefundRequested(event: OutboxEvent): Promise { + const p = parseRefundRequestedPayload(event.payload); + // 취소와 함께 계좌를 넣었으면 요청할 게 없다(관리자 송금 알림만 간다) + if (p.accountSubmitted) return; + await this.saveRefundNotification( + event, + p, + buildRefundAccountRequestedNotification(p.orderNumber, p.amount), + ); + } + + private async onRefundCompleted(event: OutboxEvent): Promise { + const p = parseRefundCompletedPayload(event.payload); + await this.saveRefundNotification( + event, + p, + buildRefundCompletedNotification(p.orderNumber, p.amount), + ); + } + + private async saveRefundNotification( + event: OutboxEvent, + p: RefundEventPayload, + payload: NotificationPayload, + ): Promise { + await this.repo.createFromEvent(event.eventId, [ + { + account_id: parseId(p.buyerAccountId), + ...payload, + 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 0ab55b5c..3b58c8f2 100644 --- a/src/features/notification/services/notification-payloads.helper.spec.ts +++ b/src/features/notification/services/notification-payloads.helper.spec.ts @@ -1,58 +1,164 @@ import { + buildOrderPickupRescheduledNotification, buildOrderStatusNotification, + buildRefundAccountRequestedNotification, + buildRefundCompletedNotification, 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', + '픽업완료', + '케이크 픽업이 완료되었어요.', + ], + [ + 'NO_SHOW', + 'ORDER_NO_SHOW', + '노쇼', + '픽업 시간에 방문하지 않아 노쇼로 처리되었어요.', + ], + ] as const)('%s는 %s(주문번호 접두)', (toStatus, event, title, body) => { + expect(status(toStatus)).toEqual({ type: NotificationType.ORDER_STATUS, - event: NotificationEvent.ORDER_MADE, - title: '제작완료', - body: 'ORD-2 주문하신 케이크 제작이 완료되었어요.', + event, + title, + body: `ORD-1 ${body}`, }); - expect( - buildOrderStatusNotification('ORD-3', OrderStatus.PICKED_UP), - ).toEqual({ - type: NotificationType.ORDER_STATUS, + }); + + it('매핑이 없는 상태(PENDING_PAYMENT)는 null', () => { + expect(status('PENDING_PAYMENT')).toBeNull(); + }); + + it('자동 픽업 완료(SYSTEM)도 픽업 완료 알림이다', () => { + expect(status('PICKED_UP', { actorType: 'SYSTEM' })).toMatchObject({ event: NotificationEvent.ORDER_PICKED_UP, - title: '픽업완료', - body: 'ORD-3 케이크 픽업이 완료되었어요.', }); }); - it('CANCELED는 취소 이벤트·문구로 매핑된다(판매자·운영자 취소 공통)', () => { - expect( - buildOrderStatusNotification('ORD-4', OrderStatus.CANCELED), - ).toEqual({ + 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.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('알림 대상이 아닌 상태(SUBMITTED)는 null을 반환한다', () => { + it('구매자 본인 행위는 알림이 없다(입금 대기·접수 취소)', () => { expect( - buildOrderStatusNotification('ORD-5', OrderStatus.SUBMITTED), + status('CANCELED', { + actorType: 'BUYER', + cancelReason: 'BUYER_REQUEST', + }), ).toBeNull(); + expect(status('PENDING_PAYMENT', { actorType: 'BUYER' })).toBeNull(); + }); + }); + + describe('buildOrderPickupRescheduledNotification', () => { + it('바뀐 픽업 일시를 KST M/d HH:mm로 적는다', () => { + expect( + buildOrderPickupRescheduledNotification( + 'ORD-3', + new Date('2026-10-05T15:30:00.000Z'), + ), + ).toEqual({ + type: NotificationType.ORDER_STATUS, + event: NotificationEvent.ORDER_PICKUP_RESCHEDULED, + title: '픽업변경', + body: 'ORD-3 픽업 일시가 10/6 00:30로 변경되었어요.', + }); + }); + }); + + 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원을 돌려받을 계좌를 입력해 주세요.', + }); + }); + }); + + describe('buildRefundCompletedNotification', () => { + it('주문번호와 천 단위 금액으로 환불 완료를 알린다', () => { + expect(buildRefundCompletedNotification('ORD-3', 1_234_567)).toEqual({ + type: NotificationType.ORDER_STATUS, + event: NotificationEvent.REFUND_COMPLETED, + title: '환불완료', + body: 'ORD-3 1,234,567원 환불이 완료되었어요.', + }); }); }); diff --git a/src/features/notification/services/notification-payloads.helper.ts b/src/features/notification/services/notification-payloads.helper.ts index 0a662d43..9e7ee2c7 100644 --- a/src/features/notification/services/notification-payloads.helper.ts +++ b/src/features/notification/services/notification-payloads.helper.ts @@ -1,11 +1,23 @@ import { + ORDER_CANCELED_NOTIFICATION, + ORDER_PAYMENT_EXPIRED_NOTIFICATION, + ORDER_PICKUP_RESCHEDULED_TITLE, ORDER_STATUS_NOTIFICATION_BODIES, ORDER_STATUS_NOTIFICATION_TITLES, + REFUND_ACCOUNT_REQUESTED_TITLE, + REFUND_COMPLETED_TITLE, REVIEW_LIKED_NOTIFICATION, } from '@/features/notification/constants/notification-messages'; +import { formatKstPickupAt } from '@/features/notification/services/seller-push-messages.helper'; +import { + ORDER_CANCEL_REASON_LABELS, + type OrderStatusChangedPayload, +} from '@/features/order'; import { NotificationEvent, NotificationType, + OrderActor, + OrderCancelReason, OrderStatus, } from '@/generated/prisma/client'; @@ -24,26 +36,94 @@ 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, + [OrderStatus.NO_SHOW]: NotificationEvent.ORDER_NO_SHOW, }; -/** SUBMITTED는 구매자 본인의 행위라 알림 없음(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 buildOrderPickupRescheduledNotification( + orderNumber: string, + toPickupAt: Date, +): NotificationPayload { + return { + type: NotificationType.ORDER_STATUS, + event: NotificationEvent.ORDER_PICKUP_RESCHEDULED, + title: ORDER_PICKUP_RESCHEDULED_TITLE, + body: `${orderNumber} 픽업 일시가 ${formatKstPickupAt(toPickupAt)}로 변경되었어요.`, + }; +} + +/** 돌려줄 돈이 생겼을 때 계좌 입력을 요청한다. */ +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')}원을 돌려받을 계좌를 입력해 주세요.`, + }; +} + +/** 환불 송금이 끝났다. */ +export function buildRefundCompletedNotification( + orderNumber: string, + amount: number, +): NotificationPayload { + return { + type: NotificationType.ORDER_STATUS, + event: NotificationEvent.REFUND_COMPLETED, + title: REFUND_COMPLETED_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 33370ddf..fdf5941d 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,12 @@ import { buildBuyerMessagePush, + buildOrderCanceledPush, + buildOrderConfirmReminderPush, 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 채움 없이, 시·분은 두 자리 @@ -15,24 +19,58 @@ 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(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('확정 마감 미리 알림: 상품명과 마감 시각(KST HH:mm), 딥링크 data는 kind·orderId', () => { expect( - buildOrderSubmittedPush({ + buildOrderConfirmReminderPush({ orderId: '42', orderNumber: 'ORD-1', - buyerAccountId: '7', storeId: '3', - storeName: '케이크샵', - productId: '9', productName: '레터링 케이크', - quantity: 2, - pickupAt: '2026-10-05T03:05:00.000Z', - totalPrice: 50000, + confirmDeadlineAt: '2026-10-05T03:00:00.000Z', }), ).toEqual({ - title: '새 주문', - body: '레터링 케이크 2개 · 픽업 10/5 12:05', - data: { kind: 'ORDER_SUBMITTED', orderId: '42' }, + title: '확정 마감 임박', + body: '레터링 케이크 주문을 12:00까지 확정하지 않으면 자동 취소돼요', + data: { kind: 'ORDER_CONFIRM_REMINDER', orderId: '42' }, }); }); @@ -52,4 +90,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 89e8099c..1740bc44 100644 --- a/src/features/notification/services/seller-push-messages.helper.ts +++ b/src/features/notification/services/seller-push-messages.helper.ts @@ -4,14 +4,28 @@ import { toKstYmd, } from '@/common/utils/kst-time'; import type { ConversationBuyerMessageSentPayload } from '@/features/conversation'; -import type { OrderSubmittedPayload } from '@/features/order'; +import type { + OrderConfirmReminderDuePayload, + OrderStatusChangedPayload, + OrderSubmittedPayload, +} from '@/features/order'; +import { OrderActor, OrderStatus } from '@/generated/prisma/client'; /** 앱 딥링크 키. */ const SELLER_PUSH_KIND = { ORDER_SUBMITTED: 'ORDER_SUBMITTED', + ORDER_CANCELED: 'ORDER_CANCELED', + ORDER_CONFIRM_REMINDER: 'ORDER_CONFIRM_REMINDER', 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'; @@ -27,16 +41,66 @@ 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 }, }; } +/** 판매자가 모르는 사이 일어난 취소만 알린다. 입금 전 주문은 판매자에게 보인 적이 없어 뺀다. 대상이 아니거나 매장을 모르면 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 }, + }, + }; +} + +/** 확정 마감 2시간 전. 마감은 2시간 안이라 시각만 적는다. */ +export function buildOrderConfirmReminderPush( + p: OrderConfirmReminderDuePayload, +): SellerPushContent { + const deadline = formatMinutesOfDay( + kstMinutesOfDay(new Date(p.confirmDeadlineAt)), + ); + return { + title: '확정 마감 임박', + body: `${p.productName} 주문을 ${deadline}까지 확정하지 않으면 자동 취소돼요`, + data: { kind: SELLER_PUSH_KIND.ORDER_CONFIRM_REMINDER, 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 1a335a0c..b558ffb9 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, { @@ -420,6 +438,79 @@ 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('order.confirm_reminder_due는 매장 디바이스에 확정 마감 미리 알림을 보낸다', async () => { + const { storeId } = await storeWithDevices(1); + + await consumer.handle( + event('order.confirm_reminder_due', { + orderId: '42', + orderNumber: 'ORD-1', + storeId: storeId.toString(), + productName: '레터링 케이크', + confirmDeadlineAt: '2026-10-05T03:00:00.000Z', + }), + ); + + expect(send.mock.calls[0][0][0]).toMatchObject({ + title: '확정 마감 임박', + body: '레터링 케이크 주문을 12:00까지 확정하지 않으면 자동 취소돼요', + data: { kind: 'ORDER_CONFIRM_REMINDER', orderId: '42' }, + }); + expect(await deliveries()).toHaveLength(1); + }); + it('conversation.buyer_message_sent는 preview를 본문으로, 딥링크는 대화 id', async () => { const { storeId, devices } = await storeWithDevices(1); @@ -447,9 +538,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 2c9b9e89..21b18984 100644 --- a/src/features/notification/services/seller-push-outbox.consumer.ts +++ b/src/features/notification/services/seller-push-outbox.consumer.ts @@ -20,11 +20,20 @@ import { import { SellerPushDeviceRepository } from '@/features/notification/repositories/seller-push-device.repository'; import { buildBuyerMessagePush, + buildOrderCanceledPush, + buildOrderConfirmReminderPush, buildOrderSubmittedPush, SELLER_PUSH_CHANNEL_ID, type SellerPushContent, } from '@/features/notification/services/seller-push-messages.helper'; -import { ORDER_SUBMITTED, parseOrderSubmittedPayload } from '@/features/order'; +import { + ORDER_CONFIRM_REMINDER_DUE, + ORDER_STATUS_CHANGED, + ORDER_SUBMITTED, + parseOrderConfirmReminderDuePayload, + parseOrderStatusChangedPayload, + parseOrderSubmittedPayload, +} from '@/features/order'; import { type OutboxConsumer, type OutboxEvent, @@ -46,7 +55,12 @@ import { MetricsService } from '@/global/metrics'; * 전송 실패(네트워크·5xx·429)는 던져 호스트의 retry/DLQ에 맡기고, 인증 실패는 경보를 낸 뒤 던진다. */ @Injectable() -@SubscribeOutbox(ORDER_SUBMITTED, CONVERSATION_BUYER_MESSAGE_SENT) +@SubscribeOutbox( + ORDER_SUBMITTED, + ORDER_STATUS_CHANGED, + ORDER_CONFIRM_REMINDER_DUE, + CONVERSATION_BUYER_MESSAGE_SENT, +) export class SellerPushOutboxConsumer implements OutboxConsumer { private readonly logger = new Logger(SellerPushOutboxConsumer.name); @@ -69,7 +83,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,16 +166,30 @@ 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); return { storeId: parseId(p.storeId), - content: buildOrderSubmittedPush(p), + 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 ORDER_CONFIRM_REMINDER_DUE: { + const p = parseOrderConfirmReminderDuePayload(event.payload); + return { + storeId: parseId(p.storeId), + content: buildOrderConfirmReminderPush(p), }; } case CONVERSATION_BUYER_MESSAGE_SENT: { 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 cc76fbdf..00000000 --- a/src/features/order/constants/order-admin.constants.ts +++ /dev/null @@ -1,17 +0,0 @@ -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)에 들어가야 한다. */ -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/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/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/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-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/admin-complete-order-pickup.input.ts b/src/features/order/dto/inputs/admin-complete-order-pickup.input.ts new file mode 100644 index 00000000..4ab9c922 --- /dev/null +++ b/src/features/order/dto/inputs/admin-complete-order-pickup.input.ts @@ -0,0 +1,10 @@ +import { IsOptional, IsString } from 'class-validator'; + +export class AdminCompleteOrderPickupInput { + @IsString() + orderId!: string; + + @IsOptional() + @IsString() + note?: string | null; +} diff --git a/src/features/order/dto/inputs/admin-complete-refund.input.ts b/src/features/order/dto/inputs/admin-complete-refund.input.ts new file mode 100644 index 00000000..fc5a42d4 --- /dev/null +++ b/src/features/order/dto/inputs/admin-complete-refund.input.ts @@ -0,0 +1,10 @@ +import { IsOptional, IsString } from 'class-validator'; + +export class AdminCompleteRefundInput { + @IsString() + refundId!: string; + + @IsOptional() + @IsString() + note?: string | null; +} 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..89f2bf3f --- /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; + + // 음수는 서비스가 DEPOSIT_AMOUNT_INVALID로 거절한다(0원 주문은 0으로 확인) + @IsInt() + depositedAmount!: number; + + @IsOptional() + @IsString() + note?: string; +} diff --git a/src/features/order/dto/inputs/admin-create-deposit-return.input.ts b/src/features/order/dto/inputs/admin-create-deposit-return.input.ts new file mode 100644 index 00000000..a43ed2c6 --- /dev/null +++ b/src/features/order/dto/inputs/admin-create-deposit-return.input.ts @@ -0,0 +1,21 @@ +import { IsDate, IsInt, IsOptional, IsString } from 'class-validator'; + +// 금액 하한·입금자명 길이는 서비스가 도메인 오류 코드로 거절한다 +export class AdminCreateDepositReturnInput { + @IsString() + orderId!: string; + + @IsInt() + amount!: number; + + @IsString() + depositorName!: string; + + @IsOptional() + @IsDate() + depositedAt?: Date | null; + + @IsOptional() + @IsString() + note?: string | null; +} diff --git a/src/features/order/dto/inputs/admin-deposit-record-list.input.ts b/src/features/order/dto/inputs/admin-deposit-record-list.input.ts new file mode 100644 index 00000000..5fdccf45 --- /dev/null +++ b/src/features/order/dto/inputs/admin-deposit-record-list.input.ts @@ -0,0 +1,10 @@ +import { IsEnum, IsOptional } from 'class-validator'; + +import { CursorInput } from '@/common/dto/inputs/cursor.input'; +import { DepositRecordKind } from '@/generated/prisma/client'; + +export class AdminDepositRecordListInput extends CursorInput { + @IsOptional() + @IsEnum(DepositRecordKind) + kind?: DepositRecordKind | null; +} diff --git a/src/features/order/dto/inputs/admin-link-unidentified-deposit.input.ts b/src/features/order/dto/inputs/admin-link-unidentified-deposit.input.ts new file mode 100644 index 00000000..bc6afcdd --- /dev/null +++ b/src/features/order/dto/inputs/admin-link-unidentified-deposit.input.ts @@ -0,0 +1,9 @@ +import { IsString } from 'class-validator'; + +export class AdminLinkUnidentifiedDepositInput { + @IsString() + depositRecordId!: string; + + @IsString() + orderId!: string; +} diff --git a/src/features/order/dto/inputs/admin-mark-settlement-paid.input.ts b/src/features/order/dto/inputs/admin-mark-settlement-paid.input.ts new file mode 100644 index 00000000..ed774e71 --- /dev/null +++ b/src/features/order/dto/inputs/admin-mark-settlement-paid.input.ts @@ -0,0 +1,10 @@ +import { IsOptional, IsString } from 'class-validator'; + +export class AdminMarkSettlementPaidInput { + @IsString() + settlementId!: string; + + @IsOptional() + @IsString() + note?: string; +} diff --git a/src/features/order/dto/inputs/admin-monthly-commission.input.ts b/src/features/order/dto/inputs/admin-monthly-commission.input.ts new file mode 100644 index 00000000..f3bd8025 --- /dev/null +++ b/src/features/order/dto/inputs/admin-monthly-commission.input.ts @@ -0,0 +1,7 @@ +import { IsString } from 'class-validator'; + +export class AdminMonthlyCommissionInput { + // 형식(YYYY-MM)은 서비스가 INVALID_YEAR_MONTH로 거절한다 + @IsString() + month!: string; +} 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/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/admin-record-unidentified-deposit.input.ts b/src/features/order/dto/inputs/admin-record-unidentified-deposit.input.ts new file mode 100644 index 00000000..2799bfa6 --- /dev/null +++ b/src/features/order/dto/inputs/admin-record-unidentified-deposit.input.ts @@ -0,0 +1,17 @@ +import { IsDate, IsInt, IsOptional, IsString } from 'class-validator'; + +// 메모가 비면 서비스가 DEPOSIT_NOTE_REQUIRED로 거절한다 +export class AdminRecordUnidentifiedDepositInput { + @IsInt() + amount!: number; + + @IsString() + depositorName!: string; + + @IsOptional() + @IsDate() + depositedAt?: Date | null; + + @IsString() + note!: string; +} diff --git a/src/features/order/dto/inputs/admin-refund-list.input.ts b/src/features/order/dto/inputs/admin-refund-list.input.ts new file mode 100644 index 00000000..ad998d29 --- /dev/null +++ b/src/features/order/dto/inputs/admin-refund-list.input.ts @@ -0,0 +1,14 @@ +import { IsEnum, IsOptional } from 'class-validator'; + +import { CursorInput } from '@/common/dto/inputs/cursor.input'; +import { RefundKind, RefundStatus } from '@/generated/prisma/client'; + +export class AdminRefundListInput extends CursorInput { + @IsOptional() + @IsEnum(RefundStatus) + status?: RefundStatus | null; + + @IsOptional() + @IsEnum(RefundKind) + kind?: RefundKind | null; +} diff --git a/src/features/order/dto/inputs/admin-settlement-list.input.ts b/src/features/order/dto/inputs/admin-settlement-list.input.ts new file mode 100644 index 00000000..f9ecb781 --- /dev/null +++ b/src/features/order/dto/inputs/admin-settlement-list.input.ts @@ -0,0 +1,19 @@ +import { IsEnum, IsOptional, IsString } from 'class-validator'; + +import { CursorInput } from '@/common/dto/inputs/cursor.input'; +import { SettlementStatus } from '@/generated/prisma/client'; + +export class AdminSettlementListInput extends CursorInput { + @IsOptional() + @IsEnum(SettlementStatus) + status?: SettlementStatus; + + @IsOptional() + @IsString() + storeId?: string; + + // 형식(YYYY-MM-DD)은 서비스가 INVALID_DATE로 거절한다 + @IsOptional() + @IsString() + periodStart?: string; +} 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-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.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/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/cancel-my-order.input.ts b/src/features/order/dto/inputs/cancel-my-order.input.ts new file mode 100644 index 00000000..e17150dc --- /dev/null +++ b/src/features/order/dto/inputs/cancel-my-order.input.ts @@ -0,0 +1,18 @@ +import { Type } from 'class-transformer'; +import { IsOptional, IsString, ValidateNested } from 'class-validator'; + +import { RefundAccountInput } from '@/features/order/dto/inputs/refund-account.input'; + +export class CancelMyOrderInput { + @IsString() + orderId!: string; + + @IsOptional() + @IsString() + note?: string | null; + + @IsOptional() + @ValidateNested() + @Type(() => RefundAccountInput) + refundAccount?: RefundAccountInput | null; +} 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 8d42f493..cc5190cd 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,169 @@ 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']); + }); + + 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 b8620efd..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자, 공백 문자 불가 — 형식은 길이만 제한한다. @@ -50,4 +53,23 @@ export class CreateOrderInput { // 검증된 프로필 값을 덮어쓰지 못하게 형식을 강제한다 @Matches(PHONE_REGEX) buyerPhone?: string; + + // 길이(20자)는 생략 시 쓰는 주문자 이름과 같은 규칙으로 서비스가 DEPOSITOR_NAME_INVALID로 판정한다 + @IsOptional() + @IsString() + depositorName?: string; + + @IsInt() + @Min(0) + expectedTotalPrice!: number; + + @IsOptional() + @IsString() + @MaxLength(500) + requestNote?: string; + + @IsOptional() + @ValidateNested() + @Type(() => CreateOrderCustomInput) + custom?: CreateOrderCustomInput | null; } diff --git a/src/features/order/dto/inputs/refund-account.input.ts b/src/features/order/dto/inputs/refund-account.input.ts new file mode 100644 index 00000000..cbd25e57 --- /dev/null +++ b/src/features/order/dto/inputs/refund-account.input.ts @@ -0,0 +1,13 @@ +import { IsString } from 'class-validator'; + +// 은행·계좌번호·예금주 형식은 서비스가 도메인 오류 코드로 거절한다 +export class RefundAccountInput { + @IsString() + bankCode!: string; + + @IsString() + accountHolder!: string; + + @IsString() + accountNumber!: string; +} 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/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-reschedule-order-pickup.input.ts b/src/features/order/dto/inputs/seller-reschedule-order-pickup.input.ts new file mode 100644 index 00000000..07144c03 --- /dev/null +++ b/src/features/order/dto/inputs/seller-reschedule-order-pickup.input.ts @@ -0,0 +1,14 @@ +import { IsDate, IsOptional, IsString } from 'class-validator'; + +export class SellerRescheduleOrderPickupInput { + @IsString() + orderId!: string; + + // 영업일·슬롯·수량은 매장 픽업 판정과 capacity 재검사가 본다 + @IsDate() + pickupAt!: Date; + + @IsOptional() + @IsString() + note?: string | null; +} diff --git a/src/features/order/dto/inputs/seller-settlement-list.input.ts b/src/features/order/dto/inputs/seller-settlement-list.input.ts new file mode 100644 index 00000000..c71b10b9 --- /dev/null +++ b/src/features/order/dto/inputs/seller-settlement-list.input.ts @@ -0,0 +1,3 @@ +import { CursorInput } from '@/common/dto/inputs/cursor.input'; + +export class SellerSettlementListInput extends CursorInput {} 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..b8e810df 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; + // 전이 가능 여부는 정책(assertTransition)이 판정한다 + @IsEnum(OrderStatus) + toStatus!: OrderStatus; @IsOptional() @IsString() 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/dto/inputs/submit-my-refund-account.input.ts b/src/features/order/dto/inputs/submit-my-refund-account.input.ts new file mode 100644 index 00000000..13ae9b39 --- /dev/null +++ b/src/features/order/dto/inputs/submit-my-refund-account.input.ts @@ -0,0 +1,8 @@ +import { IsString } from 'class-validator'; + +import { RefundAccountInput } from '@/features/order/dto/inputs/refund-account.input'; + +export class SubmitMyRefundAccountInput extends RefundAccountInput { + @IsString() + refundId!: string; +} diff --git a/src/features/order/events/order-confirm-reminder-due.event.spec.ts b/src/features/order/events/order-confirm-reminder-due.event.spec.ts new file mode 100644 index 00000000..de2b477b --- /dev/null +++ b/src/features/order/events/order-confirm-reminder-due.event.spec.ts @@ -0,0 +1,52 @@ +import { + ORDER_CONFIRM_REMINDER_DUE, + orderConfirmReminderDueEvent, + parseOrderConfirmReminderDuePayload, +} from '@/features/order/events/order-confirm-reminder-due.event'; +import type { Prisma } from '@/generated/prisma/client'; + +const VALID = { + orderId: '7', + orderNumber: 'ORD-20261119-ABC234', + storeId: '5', + productName: '딸기 케이크', + confirmDeadlineAt: '2026-11-19T09:00:00.000Z', +}; + +describe('order.confirm_reminder_due 이벤트', () => { + it('bigint·Date를 문자열로 싣고 order aggregate에 묶는다(시스템 발행이라 행위자 없음)', () => { + const occurredAt = new Date('2026-11-19T07:00:00.000Z'); + const event = orderConfirmReminderDueEvent({ + orderId: 7n, + orderNumber: VALID.orderNumber, + storeId: 5n, + productName: VALID.productName, + confirmDeadlineAt: new Date(VALID.confirmDeadlineAt), + occurredAt, + }); + + expect(event).toEqual({ + aggregateType: 'order', + aggregateId: '7', + eventType: ORDER_CONFIRM_REMINDER_DUE, + payload: VALID, + occurredAt, + actorAccountId: null, + }); + expect( + parseOrderConfirmReminderDuePayload(event.payload as Prisma.JsonValue), + ).toEqual(VALID); + }); + + it.each([ + ['배열', []], + ['null', null], + ['매장 누락', { ...VALID, storeId: undefined }], + ['마감 비ISO', { ...VALID, confirmDeadlineAt: 'not-a-date' }], + ['상품명 숫자', { ...VALID, productName: 3 }], + ])('%s payload는 던진다', (_label, value) => { + expect(() => + parseOrderConfirmReminderDuePayload(value as Prisma.JsonValue), + ).toThrow('order.confirm_reminder_due payload 형식 오류'); + }); +}); diff --git a/src/features/order/events/order-confirm-reminder-due.event.ts b/src/features/order/events/order-confirm-reminder-due.event.ts new file mode 100644 index 00000000..f823e22d --- /dev/null +++ b/src/features/order/events/order-confirm-reminder-due.event.ts @@ -0,0 +1,68 @@ +import type { OutboxEventInput } from '@/features/outbox'; +import type { Prisma } from '@/generated/prisma/client'; + +/** 확정 마감 2시간 전 판매자 미리 알림. payload는 생산 시점 스냅샷이다. */ +export const ORDER_CONFIRM_REMINDER_DUE = 'order.confirm_reminder_due'; + +export interface OrderConfirmReminderDuePayload { + orderId: string; + orderNumber: string; + storeId: string; + productName: string; + /** ISO 8601 */ + confirmDeadlineAt: string; +} + +export function orderConfirmReminderDueEvent(args: { + orderId: bigint; + orderNumber: string; + storeId: bigint; + productName: string; + confirmDeadlineAt: Date; + occurredAt: Date; +}): OutboxEventInput { + const payload: OrderConfirmReminderDuePayload = { + orderId: args.orderId.toString(), + orderNumber: args.orderNumber, + storeId: args.storeId.toString(), + productName: args.productName, + confirmDeadlineAt: args.confirmDeadlineAt.toISOString(), + }; + return { + aggregateType: 'order', + aggregateId: payload.orderId, + eventType: ORDER_CONFIRM_REMINDER_DUE, + payload: { ...payload }, + occurredAt: args.occurredAt, + actorAccountId: null, + }; +} + +/** 소비자용 방어적 파싱 — 형태가 어긋난 payload는 던져서 재시도·FAILED로 드러낸다. */ +export function parseOrderConfirmReminderDuePayload( + value: Prisma.JsonValue, +): OrderConfirmReminderDuePayload { + const p = value as Partial< + Record + >; + if ( + typeof value !== 'object' || + value === null || + Array.isArray(value) || + typeof p.orderId !== 'string' || + typeof p.orderNumber !== 'string' || + typeof p.storeId !== 'string' || + typeof p.productName !== 'string' || + typeof p.confirmDeadlineAt !== 'string' || + Number.isNaN(Date.parse(p.confirmDeadlineAt)) + ) { + throw new Error(`${ORDER_CONFIRM_REMINDER_DUE} payload 형식 오류`); + } + return { + orderId: p.orderId, + orderNumber: p.orderNumber, + storeId: p.storeId, + productName: p.productName, + confirmDeadlineAt: p.confirmDeadlineAt, + }; +} 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/order-pickup-rescheduled.event.spec.ts b/src/features/order/events/order-pickup-rescheduled.event.spec.ts new file mode 100644 index 00000000..b69be623 --- /dev/null +++ b/src/features/order/events/order-pickup-rescheduled.event.spec.ts @@ -0,0 +1,72 @@ +import { + ORDER_PICKUP_RESCHEDULED, + orderPickupRescheduledEvent, + parseOrderPickupRescheduledPayload, +} from '@/features/order/events/order-pickup-rescheduled.event'; +import type { Prisma } from '@/generated/prisma/client'; + +const VALID = { + orderId: '7', + orderNumber: 'ORD-20261119-ABC234', + buyerAccountId: '3', + storeId: '5', + storeName: '해즈 케이크', + productId: '9', + productName: '딸기 케이크', + fromPickupAt: '2026-11-20T05:00:00.000Z', + toPickupAt: '2026-11-21T06:30:00.000Z', +}; + +describe('order.pickup_rescheduled 이벤트', () => { + it('bigint·Date를 문자열로 싣고 order aggregate에 묶고 행위자는 판매자다', () => { + const occurredAt = new Date('2026-11-19T07:00:00.000Z'); + const event = orderPickupRescheduledEvent({ + orderId: 7n, + orderNumber: VALID.orderNumber, + buyerAccountId: 3n, + storeId: 5n, + storeName: VALID.storeName, + productId: 9n, + productName: VALID.productName, + fromPickupAt: new Date(VALID.fromPickupAt), + toPickupAt: new Date(VALID.toPickupAt), + occurredAt, + actorAccountId: 11n, + }); + + expect(event).toEqual({ + aggregateType: 'order', + aggregateId: '7', + eventType: ORDER_PICKUP_RESCHEDULED, + payload: VALID, + occurredAt, + actorAccountId: 11n, + }); + expect( + parseOrderPickupRescheduledPayload(event.payload as Prisma.JsonValue), + ).toEqual(VALID); + }); + + it('품목이 없던 주문의 매장·상품은 null로 읽는다', () => { + expect( + parseOrderPickupRescheduledPayload({ + ...VALID, + storeId: null, + storeName: null, + productId: null, + productName: null, + }), + ).toMatchObject({ storeId: null, productName: null }); + }); + + it.each([ + ['배열', []], + ['구매자 누락', { ...VALID, buyerAccountId: undefined }], + ['변경 후 시각 비ISO', { ...VALID, toPickupAt: 'not-a-date' }], + ['변경 전 시각 숫자', { ...VALID, fromPickupAt: 1_700_000_000 }], + ])('%s payload는 던진다', (_label, value) => { + expect(() => + parseOrderPickupRescheduledPayload(value as Prisma.JsonValue), + ).toThrow('order.pickup_rescheduled payload 형식 오류'); + }); +}); diff --git a/src/features/order/events/order-pickup-rescheduled.event.ts b/src/features/order/events/order-pickup-rescheduled.event.ts new file mode 100644 index 00000000..c836d902 --- /dev/null +++ b/src/features/order/events/order-pickup-rescheduled.event.ts @@ -0,0 +1,90 @@ +import type { OutboxEventInput } from '@/features/outbox'; +import type { Prisma } from '@/generated/prisma/client'; + +/** 판매자 픽업 일시 변경(구매자 알림 원천). payload는 생산 시점 스냅샷이다. */ +export const ORDER_PICKUP_RESCHEDULED = 'order.pickup_rescheduled'; + +export interface OrderPickupRescheduledPayload { + orderId: string; + orderNumber: string; + buyerAccountId: string; + storeId: string | null; + storeName: string | null; + productId: string | null; + productName: string | null; + /** ISO 8601 */ + fromPickupAt: string; + /** ISO 8601 */ + toPickupAt: string; +} + +export function orderPickupRescheduledEvent(args: { + orderId: bigint; + orderNumber: string; + buyerAccountId: bigint; + storeId: bigint | null; + storeName: string | null; + productId: bigint | null; + productName: string | null; + fromPickupAt: Date; + toPickupAt: Date; + occurredAt: Date; + actorAccountId: bigint; +}): OutboxEventInput { + const payload: OrderPickupRescheduledPayload = { + orderId: args.orderId.toString(), + orderNumber: args.orderNumber, + buyerAccountId: args.buyerAccountId.toString(), + storeId: args.storeId?.toString() ?? null, + storeName: args.storeName, + productId: args.productId?.toString() ?? null, + productName: args.productName, + fromPickupAt: args.fromPickupAt.toISOString(), + toPickupAt: args.toPickupAt.toISOString(), + }; + return { + aggregateType: 'order', + aggregateId: payload.orderId, + eventType: ORDER_PICKUP_RESCHEDULED, + payload: { ...payload }, + occurredAt: args.occurredAt, + actorAccountId: args.actorAccountId, + }; +} + +const isIsoString = (v: unknown): v is string => + typeof v === 'string' && !Number.isNaN(Date.parse(v)); +const stringOrNull = (v: unknown): string | null => + typeof v === 'string' ? v : null; + +/** 소비자용 방어적 파싱 — 형태가 어긋난 payload는 던져서 재시도·FAILED로 드러낸다. */ +export function parseOrderPickupRescheduledPayload( + value: Prisma.JsonValue, +): OrderPickupRescheduledPayload { + const p = value as Partial< + Record + >; + if ( + typeof value !== 'object' || + value === null || + Array.isArray(value) || + typeof p.orderId !== 'string' || + typeof p.orderNumber !== 'string' || + typeof p.buyerAccountId !== 'string' || + !isIsoString(p.fromPickupAt) || + !isIsoString(p.toPickupAt) + ) { + throw new Error(`${ORDER_PICKUP_RESCHEDULED} payload 형식 오류`); + } + return { + orderId: p.orderId, + orderNumber: p.orderNumber, + buyerAccountId: p.buyerAccountId, + storeId: stringOrNull(p.storeId), + storeName: stringOrNull(p.storeName), + productId: stringOrNull(p.productId), + productName: stringOrNull(p.productName), + fromPickupAt: p.fromPickupAt, + toPickupAt: p.toPickupAt, + }; +} 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/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/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/events/refund-account-submitted.event.ts b/src/features/order/events/refund-account-submitted.event.ts new file mode 100644 index 00000000..9de57e20 --- /dev/null +++ b/src/features/order/events/refund-account-submitted.event.ts @@ -0,0 +1,23 @@ +import { + parseRefundEventPayload, + type RefundEventArgs, + refundEventInput, + type RefundEventPayload, +} from '@/features/order/events/refund-requested.event'; +import type { OutboxEventInput } from '@/features/outbox'; +import type { Prisma } from '@/generated/prisma/client'; + +/** 구매자 환불 계좌 입력(덮어쓰기 포함). 관리자 송금 대기 알림의 원천이다. */ +export const REFUND_ACCOUNT_SUBMITTED = 'refund.account_submitted'; + +export function refundAccountSubmittedEvent( + args: RefundEventArgs, +): OutboxEventInput { + return refundEventInput(REFUND_ACCOUNT_SUBMITTED, args); +} + +export function parseRefundAccountSubmittedPayload( + value: Prisma.JsonValue, +): RefundEventPayload { + return parseRefundEventPayload(REFUND_ACCOUNT_SUBMITTED, value); +} diff --git a/src/features/order/events/refund-completed.event.ts b/src/features/order/events/refund-completed.event.ts new file mode 100644 index 00000000..41d405c4 --- /dev/null +++ b/src/features/order/events/refund-completed.event.ts @@ -0,0 +1,21 @@ +import { + parseRefundEventPayload, + type RefundEventArgs, + refundEventInput, + type RefundEventPayload, +} from '@/features/order/events/refund-requested.event'; +import type { OutboxEventInput } from '@/features/outbox'; +import type { Prisma } from '@/generated/prisma/client'; + +/** 관리자 환불 송금 완료. 구매자 환불 완료 알림의 원천이다. */ +export const REFUND_COMPLETED = 'refund.completed'; + +export function refundCompletedEvent(args: RefundEventArgs): OutboxEventInput { + return refundEventInput(REFUND_COMPLETED, args); +} + +export function parseRefundCompletedPayload( + value: Prisma.JsonValue, +): RefundEventPayload { + return parseRefundEventPayload(REFUND_COMPLETED, value); +} 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..33ab0ae3 --- /dev/null +++ b/src/features/order/events/refund-requested.event.spec.ts @@ -0,0 +1,126 @@ +import { + parseRefundAccountSubmittedPayload, + REFUND_ACCOUNT_SUBMITTED, + refundAccountSubmittedEvent, +} from '@/features/order/events/refund-account-submitted.event'; +import { + parseRefundCompletedPayload, + REFUND_COMPLETED, + refundCompletedEvent, +} from '@/features/order/events/refund-completed.event'; +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: '레터링 케이크', +}; +const occurredAt = new Date('2026-09-16T07:30:00.000Z'); +const ARGS = { + refundId: 11n, + orderId: 7n, + orderNumber: 'ORD-1', + buyerAccountId: 3n, + kind: 'CANCEL' as const, + amount: 30_000, + storeId: 2n, + storeName: '케이크샵', + productId: 5n, + productName: '레터링 케이크', + occurredAt, + actorAccountId: 9n, +}; + +describe('refund.requested 이벤트', () => { + it.each([true, false])( + '주문과 같은 aggregate(파티션)에 묶고 파서가 그대로 읽는다(계좌 입력 %s)', + (accountSubmitted) => { + const event = refundRequestedEvent({ ...ARGS, accountSubmitted }); + + expect(event).toEqual({ + aggregateType: 'order', + aggregateId: '7', + eventType: REFUND_REQUESTED, + payload: { ...VALID, accountSubmitted }, + occurredAt, + actorAccountId: 9n, + }); + expect( + parseRefundRequestedPayload(event.payload as Prisma.JsonValue), + ).toEqual({ ...VALID, accountSubmitted }); + }, + ); + + it('계좌 입력 여부가 없던 이벤트는 false로 읽는다', () => { + expect(parseRefundRequestedPayload(VALID).accountSubmitted).toBe(false); + }); + + 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('refund.requested payload 형식 오류'); + }); +}); + +describe.each([ + [ + REFUND_ACCOUNT_SUBMITTED, + refundAccountSubmittedEvent, + parseRefundAccountSubmittedPayload, + ], + [REFUND_COMPLETED, refundCompletedEvent, parseRefundCompletedPayload], +] as const)('%s 이벤트', (eventType, build, parse) => { + it('같은 공통 payload로 주문 파티션에 싣고 파서가 그대로 읽는다', () => { + const event = build(ARGS); + + expect(event).toMatchObject({ + aggregateType: 'order', + aggregateId: '7', + eventType, + payload: VALID, + }); + expect(parse(event.payload as Prisma.JsonValue)).toEqual(VALID); + }); + + it('반증: 형식이 틀리면 이벤트 이름과 함께 던진다', () => { + expect(() => parse({ ...VALID, amount: '1' })).toThrow( + `${eventType} 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..8ecf30fe --- /dev/null +++ b/src/features/order/events/refund-requested.event.ts @@ -0,0 +1,122 @@ +import type { OutboxEventInput } from '@/features/outbox'; +import { RefundKind, type Prisma } from '@/generated/prisma/client'; + +/** + * 환불 생성(취소 환불·입금 반환). 계좌가 없으면 구매자 계좌 요청 알림, 취소와 함께 계좌가 들어왔으면 + * 관리자 송금 대기 알림의 원천이다. + */ +export const REFUND_REQUESTED = 'refund.requested'; + +/** 환불 이벤트(생성·계좌 입력·송금 완료) 공통 payload. 알림 행이 매장·상품 스냅샷을 그대로 싣는다. */ +export interface RefundEventPayload { + 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 interface RefundEventArgs { + 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; +} + +export interface RefundRequestedPayload extends RefundEventPayload { + /** 생성과 함께 계좌가 들어왔는지. 이 필드가 없던 이벤트는 false다. */ + accountSubmitted: boolean; +} + +export function refundEventInput( + eventType: string, + args: RefundEventArgs, + extra: Record = {}, +): OutboxEventInput { + const payload: RefundEventPayload = { + 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, + payload: { ...payload, ...extra }, + 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 parseRefundEventPayload( + eventType: string, + value: Prisma.JsonValue, +): RefundEventPayload { + 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(`${eventType} 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), + }; +} + +export function refundRequestedEvent( + args: RefundEventArgs & { accountSubmitted: boolean }, +): OutboxEventInput { + const { accountSubmitted, ...rest } = args; + return refundEventInput(REFUND_REQUESTED, rest, { accountSubmitted }); +} + +export function parseRefundRequestedPayload( + value: Prisma.JsonValue, +): RefundRequestedPayload { + const base = parseRefundEventPayload(REFUND_REQUESTED, value); + const { accountSubmitted } = value as { accountSubmitted?: unknown }; + return { ...base, accountSubmitted: accountSubmitted === true }; +} diff --git a/src/features/order/events/settlement-created.event.spec.ts b/src/features/order/events/settlement-created.event.spec.ts new file mode 100644 index 00000000..b66896c9 --- /dev/null +++ b/src/features/order/events/settlement-created.event.spec.ts @@ -0,0 +1,55 @@ +import { + parseSettlementCreatedPayload, + SETTLEMENT_CREATED, + settlementCreatedEvent, +} from '@/features/order/events/settlement-created.event'; +import type { Prisma } from '@/generated/prisma/client'; + +const VALID = { + settlementId: '5', + storeId: '9', + storeName: '해즈 케이크', + periodStart: '2026-11-09', + periodEnd: '2026-11-15', + orderCount: 3, + settlementBaseAmount: 90_000, + commissionAmount: 4_995, + payoutAmount: 85_005, +}; + +describe('settlement.created 이벤트', () => { + it('정산 단위 aggregate에 묶고 시스템 행위(행위자 없음)다', () => { + const occurredAt = new Date('2026-11-15T20:00:00.000Z'); + const event = settlementCreatedEvent(VALID, occurredAt); + + expect(event).toEqual({ + aggregateType: 'settlement', + aggregateId: '5', + eventType: SETTLEMENT_CREATED, + payload: VALID, + occurredAt, + actorAccountId: null, + }); + expect( + parseSettlementCreatedPayload(event.payload as Prisma.JsonValue), + ).toEqual(VALID); + }); + + it.each([ + ['null', null], + ['배열', [VALID]], + ['settlementId 숫자', { ...VALID, settlementId: 5 }], + ['storeName 누락', { ...VALID, storeName: undefined }], + [ + 'periodStart 시각 형식', + { ...VALID, periodStart: '2026-11-09T00:00:00Z' }, + ], + ['periodEnd 누락', { ...VALID, periodEnd: undefined }], + ['orderCount 문자열', { ...VALID, orderCount: '3' }], + ['payoutAmount 소수', { ...VALID, payoutAmount: 1.5 }], + ])('반증: %s payload는 던진다', (_label, payload) => { + expect(() => + parseSettlementCreatedPayload(payload as Prisma.JsonValue), + ).toThrow('payload 형식 오류'); + }); +}); diff --git a/src/features/order/events/settlement-created.event.ts b/src/features/order/events/settlement-created.event.ts new file mode 100644 index 00000000..46f4bac4 --- /dev/null +++ b/src/features/order/events/settlement-created.event.ts @@ -0,0 +1,72 @@ +import type { OutboxEventInput } from '@/features/outbox'; +import type { Prisma } from '@/generated/prisma/client'; + +/** 주간 정산 생성(매장별). 관리자 '정산 송금' 알림의 원천이다. */ +export const SETTLEMENT_CREATED = 'settlement.created'; + +export interface SettlementCreatedPayload { + settlementId: string; + storeId: string; + storeName: string; + /** 정산 기간(KST 월~일), YYYY-MM-DD */ + periodStart: string; + periodEnd: string; + orderCount: number; + settlementBaseAmount: number; + commissionAmount: number; + payoutAmount: number; +} + +export function settlementCreatedEvent( + payload: SettlementCreatedPayload, + occurredAt: Date, +): OutboxEventInput { + return { + aggregateType: 'settlement', + aggregateId: payload.settlementId, + eventType: SETTLEMENT_CREATED, + payload: { ...payload }, + occurredAt, + actorAccountId: null, + }; +} + +const DATE_ONLY = /^\d{4}-\d{2}-\d{2}$/; +const AMOUNT_KEYS = [ + 'orderCount', + 'settlementBaseAmount', + 'commissionAmount', + 'payoutAmount', +] as const; + +export function parseSettlementCreatedPayload( + value: Prisma.JsonValue, +): SettlementCreatedPayload { + const p = value as Partial>; + if ( + typeof value !== 'object' || + value === null || + Array.isArray(value) || + typeof p.settlementId !== 'string' || + typeof p.storeId !== 'string' || + typeof p.storeName !== 'string' || + typeof p.periodStart !== 'string' || + !DATE_ONLY.test(p.periodStart) || + typeof p.periodEnd !== 'string' || + !DATE_ONLY.test(p.periodEnd) || + AMOUNT_KEYS.some((key) => !Number.isSafeInteger(p[key])) + ) { + throw new Error(`${SETTLEMENT_CREATED} payload 형식 오류`); + } + return { + settlementId: p.settlementId, + storeId: p.storeId, + storeName: p.storeName, + periodStart: p.periodStart, + periodEnd: p.periodEnd, + orderCount: p.orderCount as number, + settlementBaseAmount: p.settlementBaseAmount as number, + commissionAmount: p.commissionAmount as number, + payoutAmount: p.payoutAmount as number, + }; +} diff --git a/src/features/order/index.ts b/src/features/order/index.ts index 38228e43..73a4d464 100644 --- a/src/features/order/index.ts +++ b/src/features/order/index.ts @@ -1,15 +1,46 @@ // 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'; +// 채팅 주문 카드 원천과 숨김 매장 문의 허용 판정(conversation). +export { OrderInquiryRepository } from '@/features/order/repositories/order-inquiry.repository'; // 주문 상태 전이 이벤트 계약(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 RefundEventPayload, + parseRefundRequestedPayload, +} from '@/features/order/events/refund-requested.event'; +// 환불 송금 완료 이벤트 계약(outbox). 구매자 환불 완료 알림(notification)이 읽는다. +export { + REFUND_COMPLETED, + parseRefundCompletedPayload, +} from '@/features/order/events/refund-completed.event'; // 주문 접수 이벤트 계약(outbox). 판매자 푸시 소비자(notification)가 읽는다. export { ORDER_SUBMITTED, type OrderSubmittedPayload, parseOrderSubmittedPayload, } from '@/features/order/events/order-submitted.event'; +// 확정 마감 미리 알림 이벤트 계약(outbox). 판매자 푸시 소비자(notification)가 읽는다. +export { + ORDER_CONFIRM_REMINDER_DUE, + type OrderConfirmReminderDuePayload, + parseOrderConfirmReminderDuePayload, +} from '@/features/order/events/order-confirm-reminder-due.event'; +// 판매자 픽업 변경 이벤트 계약(outbox). 구매자 알림 소비자(notification)가 읽는다. +export { + ORDER_PICKUP_RESCHEDULED, + type OrderPickupRescheduledPayload, + parseOrderPickupRescheduledPayload, +} from '@/features/order/events/order-pickup-rescheduled.event'; diff --git a/src/features/order/order-admin.graphql b/src/features/order/order-admin.graphql index e2e0cbe5..376ece4b 100644 --- a/src/features/order/order-admin.graphql +++ b/src/features/order/order-admin.graphql @@ -7,15 +7,35 @@ extend type Query { 주문 상세를 전체 품목·구매자 요약·상태 이력과 함께 조회한다. 없으면 NOT_FOUND. 관리자 로그인 필수. ADMIN 계정이 아니면 FORBIDDEN. """ adminOrder(orderId: ID!): AdminOrderDetail! + """ + 매장의 진행 중 주문(입금 대기·접수·확정·제작 완료) 건수를 상태별로 센다. 판매자 정지·매장 숨김 전 경고용이며 + 없는 매장이면 0건이다. 관리자 로그인 필수. ADMIN 계정이 아니면 FORBIDDEN. + """ + adminStoreInProgressOrderSummary( + storeId: ID! + ): AdminStoreInProgressOrderSummary! } extend type Mutation { """ - 주문을 강제 취소한다. 전이 규칙은 판매자 취소와 같다 — SUBMITTED·CONFIRMED·MADE에서만 가능하고 - PICKED_UP·CANCELED면 BAD_USER_INPUT. 사유(note)는 필수이며 상태 이력에 '[관리자]' 접두로 기록된다. - 구매자에게 ORDER_CANCELED 알림이 간다. 없으면 NOT_FOUND. 관리자 로그인 필수. ADMIN 계정이 아니면 FORBIDDEN. + 주문을 강제 취소한다. 입금 대기·접수·확정·제작 완료 주문만 되고(그 밖은 ORDER_NOT_CANCELLABLE), 규칙은 adminOrder의 + cancelOptions가 그대로 알려 준다. 입금 대기는 환불 없이(미입금이면 reason PAYMENT_NOT_RECEIVED), 접수는 결제액 전액, + 확정·제작 완료는 fault(사정)에 따라 환불한다(판매자 사정 = 전액, 구매자 사정 = refundAmount, 남는 금액은 수수료를 뺀 뒤 정산에 포함). + 고를 수 없는 사유면 CANCEL_REASON_NOT_ALLOWED, 사정이 없으면 CANCEL_FAULT_REQUIRED, 구매자 사정인데 금액이 없으면 + REFUND_AMOUNT_REQUIRED, 금액이 0~결제액 밖이면 REFUND_AMOUNT_OUT_OF_RANGE(모두 BAD_USER_INPUT). + 구매자에게 취소 알림(미입금이면 입금 기한 만료 알림)이, 입금 확인 뒤 주문이면 판매자에게 취소 푸시가 간다. + 없으면 NOT_FOUND. 관리자 로그인 필수. ADMIN 계정이 아니면 FORBIDDEN. """ adminCancelOrder(input: AdminCancelOrderInput!): AdminOrderSummary! + """ + 주문을 픽업 완료로 처리한다. 확정·제작 완료 주문만 되고(이미 픽업 완료면 ORDER_STATUS_UNCHANGED, 그 밖은 + INVALID_ORDER_STATUS_TRANSITION, 모두 BAD_USER_INPUT), 매장이 숨김이어도 픽업 시각 전이어도 처리한다. + 확인된 결제액으로 정산을 확정하고(결제 도입 전 주문은 건너뜀) 구매자에게 픽업 완료 알림이 간다. + 없으면 NOT_FOUND. 관리자 로그인 필수. ADMIN 계정이 아니면 FORBIDDEN. + """ + adminCompleteOrderPickup( + input: AdminCompleteOrderPickupInput! + ): AdminOrderSummary! } """ @@ -71,6 +91,14 @@ type AdminOrderSummary { 첫 품목의 상품 대표 이미지 URL(주문 시점 스냅샷). 주문 당시 이미지가 없었거나 품목이 없으면 null. """ firstItemImageUrl: String + """ + 커스텀 주문 여부(첫 품목의 커스텀 방식이 NONE이 아니면 true). 목록 '커스텀' 배지용이다. + """ + hasCustom: Boolean! + """ + 첫 품목의 커스텀 대표 이미지 URL(3D 윗면 렌더 또는 슬롯형 합성). 없으면 null. + """ + firstItemCustomImageUrl: String } """ @@ -147,6 +175,14 @@ type AdminOrderDetail { """ buyerPhone: String! """ + 구매자가 남긴 요청 사항. 없으면 null. + """ + requestNote: String + """ + 결제와 입금 확인 기록. 결제 도입 전 주문이면 null. + """ + payment: AdminOrderPayment + """ 할인 전 품목 합계(원). """ subtotalPrice: Int! @@ -188,6 +224,111 @@ type AdminOrderDetail { 상태 변경 이력. 최신순. """ statusHistories: [OrderStatusHistory!]! + """ + 이 주문의 환불(취소 환불·입금 반환). 오래된 순, 없으면 빈 배열. + """ + refunds: [OrderRefund!]! + """ + 취소 정보(주체·사유·사정·환불액·환불 진행). 취소되지 않은 주문이면 null. + """ + cancellation: OrderCancellation + """ + 강제 취소 다이얼로그의 선택지. 지금 상태 기준이다. + """ + cancelOptions: AdminOrderCancelOptions! + """ + 판매자 확정 마감 시각. 지나면 자동 취소·전액 환불된다. 접수(SUBMITTED) 상태가 아니거나 결제 도입 전 주문이면 null. + """ + confirmDeadlineAt: DateTime + """ + 자동 픽업 완료 예정 시각(픽업 시각 + 24시간). 확정·제작 완료 상태에서만 있고 그 밖은 null. + 매장이 숨김이면 자동으로 픽업 완료되지 않으므로 관리자가 건별로 픽업 완료(adminCompleteOrderPickup)하거나 취소(adminCancelOrder)한다. + """ + autoPickupAt: DateTime + """ + 노쇼 처리 시각. 노쇼가 아니면 null. + """ + noShowAt: DateTime + """ + 판매자 픽업 일시 변경 이력. 오래된 순, 없으면 빈 배열. + """ + pickupChanges: [OrderPickupChange!]! + """ + 주문 생성 시점의 수수료율(bp, 1bp = 0.01%). 바뀐 설정은 그 뒤 주문부터 적용된다. + """ + commissionRateBps: Int! + """ + 정산 예정 금액(원). 정산 확정 뒤에는 실제 지급액(기준액 − 수수료), 확정 전에는 결제 금액에서 수수료(원 미만 버림)를 뺀 + 예상값이다. 입금이 확인되지 않았거나 결제 도입 전 주문이면 null, 확정 없이 취소된 주문(전액 환불)은 0. + """ + expectedPayoutAmount: Int + """ + 확정된 수수료 기준액(원). 픽업 완료·노쇼는 결제 금액, 구매자 사정 취소는 결제 금액 − 환불 금액. 확정 전이면 null. + """ + settlementBaseAmount: Int + """ + 확정된 수수료(원). 기준액 × 수수료율, 원 미만 버림. 확정 전이면 null. + """ + commissionAmount: Int + """ + 정산 확정 시각. 확정 전이면 null. + """ + settlementFinalizedAt: DateTime + """ + 이 주문이 묶인 주간 정산(adminSettlement). 아직 묶이지 않았으면 null. + """ + settlementId: ID +} + +""" +관리자 강제 취소 선택지. 화면은 이 값으로 다이얼로그를 그리고 규칙을 복제하지 않는다. +""" +type AdminOrderCancelOptions { + """ + 지금 취소할 수 있는지. + """ + cancelable: Boolean! + """ + 고를 수 있는 취소 사유. 취소할 수 없으면 빈 배열. + """ + reasons: [OrderCancelReasonType!]! + """ + 환불 규칙. BY_FAULT면 사정을 고르게 하고, 구매자 사정이면 환불 금액(0~paidAmount)을 입력받는다. 취소할 수 없으면 null. + """ + refundRule: CancelRefundRuleType + """ + 확인된 결제액(원). 입금 전이거나 결제 도입 전 주문이면 0. + """ + paidAmount: Int! +} + +""" +매장의 진행 중 주문 요약. +""" +type AdminStoreInProgressOrderSummary { + storeId: ID! + """ + 진행 중 주문 전체 건수. + """ + totalCount: Int! + """ + 상태별 건수. 0건인 상태는 빠지고 흐름 순(입금 대기 → 제작 완료)으로 온다. + """ + byStatus: [AdminStoreInProgressStatusCount!]! +} + +""" +상태 1개의 주문 건수. +""" +type AdminStoreInProgressStatusCount { + """ + 주문 상태. + """ + status: OrderStatusType! + """ + 건수. + """ + count: Int! } """ @@ -211,6 +352,10 @@ input AdminOrderListInput { """ status: OrderStatusType """ + true면 진행 중 주문(입금 대기·접수·확정·제작 완료)만. 기본 false, null도 false(전체)로 본다. status와 함께 오면 AND다. + """ + inProgress: Boolean = false + """ 매장 ID 필터(품목 기준). 미지정 시 전체. """ storeId: ID @@ -229,12 +374,35 @@ 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일 때 필수이고, 그 밖에는 무시한다. + """ + refundAmount: Int +} + +""" +주문 픽업 완료 입력. 확정·제작 완료 주문만 처리할 수 있다. +""" +input AdminCompleteOrderPickupInput { + orderId: ID! + """ + 처리 메모. 선택, 최대 500자. 상태 이력과 감사 로그에 남는다. """ - note: String! + note: String } diff --git a/src/features/order/order-checkout.graphql b/src/features/order/order-checkout.graphql index 0ae41297..3ab6cc7e 100644 --- a/src/features/order/order-checkout.graphql +++ b/src/features/order/order-checkout.graphql @@ -1,19 +1,51 @@ extend type Mutation { - """주문 생성(구매자). 옵션·픽업 일시를 서버가 재검증하고 가격을 스냅샷한다. 로그인 필수.""" + """ + 주문 생성(구매자). 옵션·픽업 일시를 서버가 재검증하고 가격을 스냅샷한 뒤 입금 대기(PENDING_PAYMENT) 주문을 만든다. + 결과의 payment로 입금을 안내하고, 1시간 안에 입금이 확인되지 않으면 자동 취소된다. 판매자에게는 입금 확인 뒤에 보인다. + 입금 계좌가 설정되지 않았으면 PAYMENT_ACCOUNT_NOT_CONFIGURED(SERVICE_UNAVAILABLE), 입금 대기 주문이 이미 2건이면 + PENDING_PAYMENT_LIMIT_EXCEEDED(CONFLICT), 같은 계정의 다른 주문 요청이 처리 중이라 3초 안에 차례가 오지 않으면 + CONCURRENT_REQUEST(CONFLICT)다. 커스텀 상품이면 custom 입력을 검증해 주문 시점 스냅샷으로 저장하고 수량은 1이다 + (CreateOrderCustomInput 참고). 로그인 필수. + """ createOrder(input: CreateOrderInput!): CreateOrderOutput! + """ + 커스텀 이미지 업로드용 Presigned URL 발급(구매자). uploadUrl로 PUT한 뒤 publicUrl을 주문 생성의 커스텀 입력에 넣는다. + JPEG·PNG·WebP, 장당 1바이트 이상 10MB 이하(아니면 INVALID_CONTENT_TYPE·INVALID_CONTENT_LENGTH·FILE_TOO_LARGE). + 주문에 쓰이지 않은 파일은 발급 하루 뒤 지워진다. 구매자 계정만 쓸 수 있고(아니면 USER_ONLY), 정지·탈퇴 등으로 + 이용할 수 없는 계정이면 BUYER_ACCOUNT_NOT_ACTIVE다. 로그인 필수. + """ + createOrderCustomUploadUrl( + """이미지 용도. 주문 생성 때 이 용도의 자리에만 쓸 수 있다.""" + purpose: OrderCustomUploadPurpose! + """파일 MIME 타입(image/jpeg·image/png·image/webp).""" + contentType: String! + """파일 크기(바이트, 1 이상 10MB 이하).""" + contentLength: Int! + ): UploadUrl! +} + +"""구매자 커스텀 이미지 업로드 용도.""" +enum OrderCustomUploadPurpose { + """3D 렌더 이미지(윗면·옆면 앞·뒤·좌·우).""" + RENDER + """슬롯형 합성 이미지(바탕 + 문구, 구매자가 본 그대로).""" + COMPOSITE + """자유 편집 참고 사진.""" + REFERENCE } -"""주문 생성 입력. 커스텀 필드는 커스텀 스펙 확정 후 optional로 확장 예정.""" +"""주문 생성 입력.""" input CreateOrderInput { """ 클라이언트 생성 멱등 키(8~64자). 체크아웃 진입 시 새로 만들고 재시도에는 같은 키를 재사용한다. 같은 키의 재요청은 새 주문을 만들지 않고 기존 주문을 반환한다. + 같은 키로 다른 입력을 보내면 IDEMPOTENCY_KEY_INPUT_MISMATCH로 거절한다. """ idempotencyKey: String! productId: ID! """선택한 옵션 아이템 ID 목록. 그룹 규칙(필수/min/max)을 서버가 검증한다.""" optionItemIds: [ID!]! - """픽업 일시. 매장 정책(영업시간·휴무·capacity·리드타임·슬롯 정렬) 재검증.""" + """픽업 일시. 매장 정책(영업시간·휴무·capacity·리드타임과 상품 제작 시간 중 긴 쪽·슬롯 정렬) 재검증.""" pickupAt: DateTime! """주문 수량. 기본 1.""" quantity: Int = 1 @@ -21,6 +53,162 @@ input CreateOrderInput { buyerName: String """미입력 시 프로필 전화번호 사용. 둘 다 없으면 거절.""" buyerPhone: String + """ + 입금자명(1~20자). 생략하거나 공백만 보내면 주문자 이름을 쓴다. 입력값이든 주문자 이름이든 20자를 넘으면 + DEPOSITOR_NAME_INVALID로 거절한다(은행 입금자명과 대조하는 값이라 자르지 않는다). + """ + depositorName: String + """ + 화면에 보여 준 최종 결제 금액(원). 서버가 다시 계산한 금액과 다르면 ORDER_PRICE_CHANGED로 거절한다. + """ + expectedTotalPrice: Int! + """판매자에게 전할 요청 사항(최대 500자). 공백만 보내면 없음으로 저장한다.""" + requestNote: String + """ + 커스텀 입력. 상품의 커스텀 방식(ProductDetail.customMode)이 SLOT이면 slot, THREE_D면 threeD 하나만 보낸다. + 커스텀 상품인데 없으면 CUSTOM_INPUT_REQUIRED, 방식이 다르거나 커스텀 상품이 아닌데 보내면 CUSTOM_INPUT_MISMATCH, + 수량이 1이 아니면 CUSTOM_QUANTITY_FIXED, 판매자 설정이 끝나지 않은 상품이면 CUSTOM_PRODUCT_NOT_READY다. + 커스텀은 추가 금액이 없다(3D 모양·크기 등의 가격은 옵션 추가금으로만 들어온다). + """ + custom: CreateOrderCustomInput +} + +""" +주문 커스텀 입력. 이미지 URL은 모두 createOrderCustomUploadUrl로 올린 본인 파일의 publicUrl이어야 하고(용도가 맞아야 한다), +한 주문 안에서 같은 파일을 두 번 쓸 수 없다. 아니면 CUSTOM_UPLOAD_INVALID, 발급 뒤 오래돼 정리 중인 파일이면 +CUSTOM_UPLOAD_EXPIRED다. 다른 주문에 이미 쓴 파일도 CUSTOM_UPLOAD_INVALID다. +""" +input CreateOrderCustomInput { + """슬롯형(바탕 이미지 + 문구 자리) 입력. 슬롯형 상품에서만 보낸다.""" + slot: CreateOrderSlotCustomInput + """3D 입력. 3D 상품에서만 보낸다.""" + threeD: CreateOrderThreeDCustomInput +} + +""" +슬롯형 커스텀 입력. 좌표는 바탕 이미지 한 변을 10000으로 본 정수 비율이고 원점은 왼쪽 위다. +""" +input CreateOrderSlotCustomInput { + """ + 꾸미기를 시작할 때 본 ProductDetail.customTemplate.revision. 그 사이 판매자가 설정을 바꿨으면 + CUSTOM_TEMPLATE_CHANGED(CONFLICT)이고 다시 꾸며야 한다. + """ + templateRevision: Int! + """ + 문구 자리마다 1건(customTemplate.slots 전부, 중복 없이). 빠지거나 남는 자리가 있으면 CUSTOM_SLOT_TEXTS_MISMATCH다. + """ + texts: [CreateOrderSlotTextInput!]! + """구매자가 본 그대로의 합성 이미지 URL(바탕 + 문구, 용도 COMPOSITE). 대표 이미지로 저장된다.""" + compositeImageUrl: String! + """ + 자유 편집 요청(customTemplate.freeEditEnabled일 때만, 최대 5건). 규칙을 벗어나면 CUSTOM_FREE_EDIT_INVALID다. + """ + freeEdits: [CreateOrderFreeEditInput!] = [] +} + +"""문구 자리 1개의 입력.""" +input CreateOrderSlotTextInput { + tokenId: ID! + """ + 넣을 문구. 손대지 않았으면 기본 문구를 그대로 보낸다. 줄바꿈(CRLF는 LF로 바꾼다)·이모지를 쓸 수 있고 앞뒤 공백은 지운다. + 지운 뒤 비었거나 null이면 '문구 없음'이다(필수 자리면 CUSTOM_SLOT_TEXT_REQUIRED). 자리의 maxLength(코드 포인트)를 + 넘으면 CUSTOM_SLOT_TEXT_TOO_LONG이다. + """ + valueText: String +} + +"""자유 편집 요청 1건. 바탕 이미지 위 영역과 설명, 참고 사진이다.""" +input CreateOrderFreeEditInput { + """영역 왼쪽 위 x(0~10000).""" + posX: Int! + """영역 왼쪽 위 y(0~10000).""" + posY: Int! + """영역 너비(1 이상, posX + width ≤ 10000).""" + width: Int! + """영역 높이(1 이상, posY + height ≤ 10000).""" + height: Int! + """요청 설명(앞뒤 공백을 지운 뒤 1~2000자, 줄바꿈 허용).""" + descriptionText: String! + """참고 사진 URL(용도 REFERENCE, 최대 3장).""" + referenceImageUrls: [String!] = [] +} + +"""3D 커스텀 입력.""" +input CreateOrderThreeDCustomInput { + """ + 3D 디자인(JSON v1). 모양·크기·디자인·맛은 고른 옵션의 threeDKey와 같아야 한다(아니면 CUSTOM_3D_OPTIONS_CHANGED). + 카탈로그·한도 검증은 customThreeDCatalog를 따른다. + """ + design: ThreeDDesignInput! + """ + 렌더 이미지(용도 RENDER). THREE_D_TOP·FRONT·BACK·LEFT·RIGHT 정확히 1장씩이고, 아니면 CUSTOM_RENDER_IMAGES_INVALID다. + 윗면이 대표 이미지로 저장된다. + """ + renderImages: [CreateOrderRenderImageInput!]! +} + +"""3D 렌더 이미지 1장.""" +input CreateOrderRenderImageInput { + """렌더 자세.""" + kind: CustomImageKindType! + """이미지 URL.""" + imageUrl: String! +} + +""" +3D 디자인 입력(JSON v1). 저장 형태는 ThreeDDesign이고 같은 좌표계·규칙을 쓴다. 배열 순서가 그리는 순서다. +""" +input ThreeDDesignInput { + """디자인 JSON 버전. 지금은 1만 받는다(아니면 CUSTOM_3D_SCHEMA_UNSUPPORTED).""" + schemaVersion: Int! + """모양·크기·디자인·맛·시트 색.""" + basic: ThreeDDesignBasicInput! + """윗면 항목(글자·꾸미기 각 10개까지).""" + top: [ThreeDDesignItemInput!]! + """옆면 항목(글자·꾸미기 각 10개까지).""" + side: [ThreeDDesignItemInput!]! +} + +"""3D 디자인의 케이크 기본값.""" +input ThreeDDesignBasicInput { + """모양 선택지 value(고른 모양 옵션의 값).""" + shape: String! + """크기 선택지 value(고른 크기 옵션의 값).""" + size: String! + """디자인 선택지 value. 디자인 옵션을 고르지 않았으면 null(장식 없는 시트).""" + design: String + """맛 선택지 value. 맛 옵션을 고르지 않았으면 null.""" + flavor: String + """시트 색 key(카탈로그 sheetColors).""" + sheetColor: String! +} + +"""3D 디자인 항목(글자 또는 꾸미기) 1개.""" +input ThreeDDesignItemInput { + """항목 종류.""" + kind: ThreeDItemKindType! + """가로 위치(0~1, ThreeDDesign.top·side 좌표계).""" + x: Float! + """세로 위치(0~1, ThreeDDesign.top·side 좌표계).""" + y: Float! + """크기(cqw). 글자 4~30, 꾸미기 8~50.""" + size: Float! + """효과.""" + effect: ThreeDDesignEffectInput! + """글자 내용(TEXT만, 1~30 코드 포인트, 줄바꿈·이모지 허용). DECO는 null.""" + text: String + """글자색(TEXT만, #RRGGBB). DECO는 null.""" + color: String + """꾸미기 key(DECO만, 카탈로그 decos). TEXT는 null.""" + decoId: String +} + +"""3D 디자인 항목에 건 효과.""" +input ThreeDDesignEffectInput { + """효과 key(카탈로그 effects).""" + type: String! + """효과 강도(0~100 정수).""" + intensity: Int! } """주문 생성 결과 요약. 상세는 myOrder로 재조회.""" @@ -29,12 +217,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..1ab5556b --- /dev/null +++ b/src/features/order/order-deposit-admin.graphql @@ -0,0 +1,220 @@ +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! + """ + 구매자의 환불 계좌 입력을 기다리는 환불 수(adminRefunds status=AWAITING_ACCOUNT의 totalCount). + """ + refundsAwaitingAccount: Int! + """ + 계좌가 들어와 송금을 기다리는 환불 수(adminRefunds status=AWAITING_TRANSFER의 totalCount). + """ + refundsAwaitingTransfer: Int! + """ + 송금을 기다리는 주간 정산 수(adminSettlements status=PENDING의 totalCount). + """ + pendingSettlements: Int! +} + +""" +입금 확인 입력. +""" +input AdminConfirmPaymentInput { + orderId: ID! + """ + 은행 앱에서 본 입금액(원, 0 이상 정수). 결제 금액과 같아야 확인된다(0원 주문은 0). + """ + depositedAmount: Int! + """ + 처리 메모(선택, 500자 이하). 결제 기록에 남는다. + """ + note: String +} + +""" +주문 결제(관리자 시점). 처리자 표시가 더해진다. +""" +type AdminOrderPayment { + """ + 결제 수단. + """ + method: PaymentMethodType! + """ + 결제 상태. + """ + status: PaymentStatusType! + """ + 결제 금액(원). + """ + amount: Int! + """ + 입금자명. + """ + depositorName: String! + """ + 안내한 케이퀵 계좌의 은행(주문 시점 스냅샷). + """ + depositBank: Bank! + """ + 안내한 케이퀵 계좌번호(주문 시점 스냅샷). + """ + depositAccountNumber: String! + """ + 안내한 케이퀵 계좌 예금주(주문 시점 스냅샷). + """ + depositAccountHolder: String! + """ + 입금 기한. + """ + expiresAt: DateTime! + """ + 구매자가 '입금했어요'를 누른 시각. 누르지 않았으면 null. + """ + buyerClaimedAt: DateTime + """ + 입금이 확인된 시각. 확인 전이면 null. + """ + confirmedAt: DateTime + """ + 입금 확인 경로. 확인 전이면 null. + """ + confirmSource: PaymentConfirmSourceType + """ + 입금을 확인한 관리자 표시 이름(확인 시점 스냅샷). 확인 전이거나 이름이 없으면 null. + """ + confirmedByLabel: String + """ + 입금 확인 메모. 없으면 null. + """ + confirmNote: String +} diff --git a/src/features/order/order-my.graphql b/src/features/order/order-my.graphql index a8ea08d8..1084611f 100644 --- a/src/features/order/order-my.graphql +++ b/src/features/order/order-my.graphql @@ -9,6 +9,83 @@ 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! + """ + 내 주문을 취소한다. 판매자 확정 전(입금 대기·접수)까지만 되고 사유는 구매자 요청으로 기록된다. + 입금 대기는 환불 없이, 접수는 결제액 전액 환불로 취소되고 환불이 생기면 환불 계좌 입력 요청 알림이 간다. + refundAccount를 함께 보내면 환불이 바로 송금 대기가 되고 계좌 요청 알림은 가지 않는다(환불이 없으면 계좌는 버린다). + '입금했어요'를 누른 주문도 취소할 수 있다. 그 밖의 상태면 ORDER_NOT_CANCELLABLE(BAD_USER_INPUT). + 계좌 형식 오류는 submitMyRefundAccount와 같은 코드다. 로그인 필수. 본인 주문이 아니면 NOT_FOUND. + """ + cancelMyOrder(input: CancelMyOrderInput!): MyOrderDetail! + """ + 돌려받을 환불 계좌를 입력한다(MyOrderDetail.refunds의 id). 송금 완료 전이면 다시 보내 덮어쓸 수 있고, 입력하면 송금 대기가 된다. + 계좌번호는 암호화해 저장하고 응답에는 끝 4자리만 나간다. 은행 코드가 paymentBanks에 없으면 INVALID_BANK_CODE, + 계좌번호가 하이픈을 뺀 숫자 8~20자리가 아니면 INVALID_ACCOUNT_NUMBER, 예금주가 비었거나 50자를 넘으면 + TEXT_REQUIRED·TEXT_TOO_LONG(모두 BAD_USER_INPUT), 송금이 끝났으면 REFUND_ALREADY_COMPLETED(CONFLICT). + 로그인 필수. 본인 환불이 아니면 REFUND_NOT_FOUND(NOT_FOUND). + """ + submitMyRefundAccount(input: SubmitMyRefundAccountInput!): MyOrderDetail! +} + +""" +내 주문 취소 입력. +""" +input CancelMyOrderInput { + orderId: ID! + """ + 취소 메모. 선택, 최대 500자. 상태 이력에 남고 판매자도 본다. + """ + note: String + """ + 환불받을 계좌. 선택. 접수 주문처럼 환불이 생기는 취소에서 계좌 입력을 한 번에 끝낸다. + """ + refundAccount: RefundAccountInput +} + +""" +환불받을 계좌. +""" +input RefundAccountInput { + """ + 은행 코드(paymentBanks의 code). + """ + bankCode: String! + """ + 예금주(1~50자). + """ + accountHolder: String! + """ + 계좌번호. 하이픈을 빼고 숫자 8~20자리여야 하며 숫자만 저장한다. + """ + accountNumber: String! +} + +""" +환불 계좌 입력. +""" +input SubmitMyRefundAccountInput { + refundId: ID! + """ + 은행 코드(paymentBanks의 code). + """ + bankCode: String! + """ + 예금주(1~50자). + """ + accountHolder: String! + """ + 계좌번호. 하이픈을 빼고 숫자 8~20자리여야 하며 숫자만 저장한다. + """ + accountNumber: String! +} + """ 내 주문 조회 입력 """ @@ -99,6 +176,10 @@ type MyOrderSummary { 주문 내 OrderItem 중 리뷰 작성 가능한 것이 1건이라도 있는지 (PICKED_UP + 활성 리뷰 미존재) """ hasReviewableItem: Boolean! + """ + 입금 기한. 입금을 기다리는 주문(결제 대기)만 값이 있고 그 밖은 null. + """ + paymentExpiresAt: DateTime } """ @@ -131,6 +212,14 @@ type MyOrderDetail { 주문자 연락처. """ buyerPhone: String! + """ + 구매자가 남긴 요청 사항. 없으면 null. + """ + requestNote: String + """ + 결제(입금 안내·진행 상태). 결제 도입 전 주문이면 null. + """ + payment: OrderPayment """ 할인 전 품목 합계(원). @@ -165,6 +254,23 @@ type MyOrderDetail { CANCELED 도달 시각. 취소되지 않았으면 null. """ canceledAt: DateTime + """ + 취소 정보(주체·사유·환불액·환불 진행). 취소되지 않은 주문이면 null. + """ + cancellation: OrderCancellation + """ + 지금 cancelMyOrder로 취소할 수 있는지. 입금 대기·접수 상태일 때 true. + """ + canCancel: Boolean! + """ + 이 주문에서 돌려받을 돈(취소 환불·입금 반환). 오래된 순, 없으면 빈 배열. + status가 AWAITING_ACCOUNT면 submitMyRefundAccount로 계좌를 입력받는다. + """ + refunds: [OrderRefund!]! + """ + 판매자가 바꾼 픽업 일시 이력. 오래된 순, 없으면 빈 배열. pickupAt은 마지막 변경 뒤 값이다. + """ + pickupChanges: [OrderPickupChange!]! """ 상태 변경 이력. 오래된 순이다(판매자 주문 상세는 최신순 — 방향이 반대다). diff --git a/src/features/order/order-payment-admin.graphql b/src/features/order/order-payment-admin.graphql new file mode 100644 index 00000000..88076511 --- /dev/null +++ b/src/features/order/order-payment-admin.graphql @@ -0,0 +1,139 @@ +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, 예금주가 비었거나 50자를 넘으면 TEXT_REQUIRED·TEXT_TOO_LONG, + 사유가 비면 TEXT_REQUIRED, 500자를 넘으면 VALIDATION_FAILED(모두 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..ba9aa8b7 --- /dev/null +++ b/src/features/order/order-payment.graphql @@ -0,0 +1,103 @@ +extend type Query { + """ + 계좌 입력 화면의 은행 목록(금융결제원 3자리 코드). 환불 계좌·정산 계좌·케이퀵 입금 계좌가 같은 목록을 쓰고, + 배열 순서가 표시 순서다. 로그인 없이 조회할 수 있다. + """ + paymentBanks: [Bank!]! +} + +""" +은행. +""" +type Bank { + """ + 금융결제원 3자리 은행 코드(예: 004). 계좌 입력 mutation의 bankCode로 그대로 보낸다. + """ + code: String! + """ + 은행 이름(예: KB국민은행). 목록에서 빠진 옛 코드면 코드를 그대로 준다. + """ + name: String! +} + +""" +결제 수단. 값은 늘어날 수 있으니 모르는 값을 받아도 화면이 죽지 않게 처리한다. +""" +enum PaymentMethodType { + """계좌이체(케이퀵 계좌로 입금).""" + BANK_TRANSFER + """토스 결제. 아직 쓰지 않는다.""" + TOSS +} + +""" +결제 상태. 값은 늘어날 수 있으니 모르는 값을 받아도 화면이 죽지 않게 처리한다. +""" +enum PaymentStatusType { + """입금 대기.""" + PENDING + """입금 확인됨. 주문이 나중에 취소돼도 이 값으로 남고 돌려줄 돈은 환불이 맡는다.""" + CONFIRMED + """입금 전에 주문이 취소됨.""" + CANCELED +} + +""" +입금을 확인한 경로. +""" +enum PaymentConfirmSourceType { + """입금 알림 자동 매칭. 아직 쓰지 않는다.""" + AUTO + """관리자가 은행 앱에서 확인.""" + ADMIN +} + +""" +주문 결제(계좌이체 입금 안내와 진행 상태). 구매자 주문 화면이 그대로 입금 안내에 쓴다. +""" +type OrderPayment { + """ + 결제 수단. + """ + method: PaymentMethodType! + """ + 결제 상태. + """ + status: PaymentStatusType! + """ + 입금할 금액(원). 주문 최종 결제 금액과 같다. + """ + amount: Int! + """ + 입금자명. 은행 입금자명이 이 값과 같아야 확인이 빠르다. + """ + depositorName: String! + """ + 입금할 케이퀵 계좌의 은행(주문 시점 스냅샷). + """ + depositBank: Bank! + """ + 입금할 케이퀵 계좌번호(숫자만, 주문 시점 스냅샷). + """ + depositAccountNumber: String! + """ + 입금할 케이퀵 계좌 예금주(주문 시점 스냅샷). + """ + depositAccountHolder: String! + """ + 입금 기한(주문 후 1시간). 이때까지 입금이 확인되지 않고 '입금했어요'도 누르지 않았으면 주문이 자동 취소된다. + """ + expiresAt: DateTime! + """ + 구매자가 '입금했어요'를 누른 시각. 누르지 않았으면 null. + """ + buyerClaimedAt: DateTime + """ + 입금이 확인된 시각. 확인 전이면 null. + """ + confirmedAt: DateTime + """ + 입금 확인 경로. 확인 전이면 null. + """ + confirmSource: PaymentConfirmSourceType +} diff --git a/src/features/order/order-refund-admin.graphql b/src/features/order/order-refund-admin.graphql new file mode 100644 index 00000000..622f3823 --- /dev/null +++ b/src/features/order/order-refund-admin.graphql @@ -0,0 +1,353 @@ +extend type Query { + """ + 환불(취소 환불·입금 반환) 목록. 처리 순서대로 오래된 환불부터 온다. 계좌번호는 끝 4자리만 나간다. + 관리자 로그인 필수. ADMIN 계정이 아니면 FORBIDDEN. + """ + adminRefunds(input: AdminRefundListInput): AdminRefundConnection! + """ + 환불 상세. 송금에 쓸 계좌번호 원문과 입금 반환이면 그 입금 기록이 함께 온다. 없으면 REFUND_NOT_FOUND(NOT_FOUND). + 관리자 로그인 필수. ADMIN 계정이 아니면 FORBIDDEN. + """ + adminRefund(refundId: ID!): AdminRefundDetail! + """ + 결제로 확인하지 않은 입금 기록(반환·종결) 목록. 최근 기록부터 온다. + 관리자 로그인 필수. ADMIN 계정이 아니면 FORBIDDEN. + """ + adminDepositRecords( + input: AdminDepositRecordListInput + ): AdminDepositRecordConnection! +} + +extend type Mutation { + """ + 환불 송금을 마쳤다고 기록한다. 계좌가 들어온(송금 대기) 환불만 되고, 계좌 입력 전이면 REFUND_NOT_READY(BAD_USER_INPUT), + 이미 끝났으면 REFUND_ALREADY_COMPLETED(CONFLICT), 없으면 REFUND_NOT_FOUND(NOT_FOUND). 메모가 500자를 넘으면 TEXT_TOO_LONG. + 구매자에게 REFUND_COMPLETED 알림이 가고 감사 로그(REFUND)를 남긴다. 관리자 로그인 필수. ADMIN 계정이 아니면 FORBIDDEN. + """ + adminCompleteRefund(input: AdminCompleteRefundInput!): AdminRefund! + """ + 은행 앱에서 본 입금을 주문의 반환 대상으로 연결한다. 입금 기록(RETURN)과 입금액 전액의 환불(계좌 입력 대기)이 생기고 + 구매자에게 환불 계좌 입력 요청 알림이 간다. 주문 상태·결제·정산은 바꾸지 않으며 주문 상태와 관계없이 연결할 수 있다 + (미입금 취소 뒤 늦은 입금, 취소 뒤 입금, 금액이 틀린 입금, 이중 입금). 입금액이 1 미만이면 DEPOSIT_AMOUNT_INVALID, + 입금자명이 비었거나 50자를 넘으면 TEXT_REQUIRED·TEXT_TOO_LONG, 메모가 500자를 넘으면 TEXT_TOO_LONG(모두 BAD_USER_INPUT), + 없는 주문이면 ORDER_NOT_FOUND(NOT_FOUND). 감사 로그(DEPOSIT_RECORD)를 남긴다. + 관리자 로그인 필수. ADMIN 계정이 아니면 FORBIDDEN. + """ + adminCreateDepositReturn( + input: AdminCreateDepositReturnInput! + ): AdminDepositRecord! + """ + 주인을 알 수 없는 입금을 메모와 함께 종결 기록(UNIDENTIFIED)으로 남긴다. 메모가 비면 DEPOSIT_NOTE_REQUIRED, + 입금액·입금자명·메모 길이 오류는 adminCreateDepositReturn과 같다(모두 BAD_USER_INPUT). 감사 로그(DEPOSIT_RECORD)를 남긴다. + 관리자 로그인 필수. ADMIN 계정이 아니면 FORBIDDEN. + """ + adminRecordUnidentifiedDeposit( + input: AdminRecordUnidentifiedDepositInput! + ): AdminDepositRecord! + """ + 종결 기록한 입금의 주인을 찾았을 때 그 기록을 주문의 반환 대상으로 바꾼다. 같은 입금을 새로 기록하지 않고 기록 종류가 + RETURN으로 바뀌며, 입금액 전액의 환불이 생겨 구매자에게 계좌 입력 요청 알림이 간다(주문 상태·결제·정산은 그대로). + 이미 반환으로 연결된 기록이면 DEPOSIT_RECORD_ALREADY_LINKED(CONFLICT), 없는 기록이면 DEPOSIT_RECORD_NOT_FOUND, + 없는 주문이면 ORDER_NOT_FOUND(모두 NOT_FOUND). 감사 로그(DEPOSIT_RECORD)를 남긴다. + 관리자 로그인 필수. ADMIN 계정이 아니면 FORBIDDEN. + """ + adminLinkUnidentifiedDeposit( + input: AdminLinkUnidentifiedDepositInput! + ): AdminDepositRecord! +} + +""" +입금 기록 종류. 값은 늘어날 수 있으니 모르는 값을 받아도 화면이 죽지 않게 처리한다. +""" +enum DepositRecordKindType { + """주문에 연결해 돌려주는 입금. 같은 금액의 입금 반환 환불이 함께 있다.""" + RETURN + """주인을 알 수 없어 메모로 종결한 입금.""" + UNIDENTIFIED +} + +""" +환불 목록 조회 조건. 모든 필터는 AND로 결합된다. +""" +input AdminRefundListInput { + """ + 한 번에 가져올 개수. 기본 20, 1~100만 허용하며 벗어나면 BAD_USER_INPUT. + """ + limit: Int = 20 + """ + 이전 응답의 nextCursor. 첫 페이지는 생략한다. + """ + cursor: String + """ + 진행 상태 필터. null이면 전체. + """ + status: RefundStatusType + """ + 종류 필터. null이면 전체. + """ + kind: RefundKindType +} + +""" +환불(관리자 시점). 계좌번호는 끝 4자리만 담는다. +""" +type AdminRefund { + id: ID! + """ + 환불 종류. + """ + kind: RefundKindType! + """ + 돌려줄 금액(원). + """ + amount: Int! + """ + 진행 상태. + """ + status: RefundStatusType! + """ + 환불받을 은행. 계좌 입력 전이면 null. + """ + bank: Bank + """ + 환불 계좌 예금주. 계좌 입력 전이면 null. + """ + accountHolder: String + """ + 환불 계좌번호 끝 4자리만 보이는 값(예: ****1234). 계좌 입력 전이면 null. + """ + accountNumberMasked: String + """ + 환불이 생긴 시각. + """ + requestedAt: DateTime! + """ + 구매자가 계좌를 입력한 시각(덮어쓰면 마지막 입력). 입력 전이면 null. + """ + accountSubmittedAt: DateTime + """ + 송금 완료 시각. 완료 전이면 null. + """ + completedAt: DateTime + orderId: ID! + """ + 주문번호. + """ + orderNumber: String! + """ + 주문자 이름. 계좌 입력을 기다릴 때 연락에 쓴다. + """ + buyerName: String! + """ + 주문자 연락처. + """ + buyerPhone: String! + """ + 매장명(주문 시점 스냅샷). 품목이 없으면 null. + """ + storeName: String + """ + 상품명(주문 시점 스냅샷). 품목이 없으면 null. + """ + productName: String + """ + 송금 완료를 기록한 관리자 표시 이름(처리 시점 스냅샷). 완료 전이거나 이름이 없으면 null. + """ + completedByLabel: String + """ + 송금 완료 메모. 없으면 null. + """ + completeNote: String +} + +""" +환불 상세. 계좌번호 원문이 들어 있으니 화면 밖(로그·분석 이벤트)에 남기지 않는다. +""" +type AdminRefundDetail { + """ + 환불. + """ + refund: AdminRefund! + """ + 환불 계좌번호 원문(숫자만). 송금에 쓴다. 계좌 입력 전이면 null. + """ + accountNumber: String + """ + 입금 반환이면 그 입금 기록, 취소 환불이면 null. + """ + depositRecord: AdminDepositRecord +} + +""" +환불 목록 페이지. +""" +type AdminRefundConnection { + """ + 환불. 오래된 것부터 온다. + """ + items: [AdminRefund!]! + """ + 조건에 맞는 전체 건수(현재 페이지와 무관). 커서 필터는 제외하고 센다. + """ + totalCount: Int! + """ + 다음 페이지 존재 여부. + """ + hasMore: Boolean! + """ + 다음 페이지 커서. null이면 마지막 페이지다. + """ + nextCursor: String +} + +""" +입금 기록 목록 조회 조건. +""" +input AdminDepositRecordListInput { + """ + 한 번에 가져올 개수. 기본 20, 1~100만 허용하며 벗어나면 BAD_USER_INPUT. + """ + limit: Int = 20 + """ + 이전 응답의 nextCursor. 첫 페이지는 생략한다. + """ + cursor: String + """ + 종류 필터. null이면 전체. + """ + kind: DepositRecordKindType +} + +""" +결제로 확인하지 않은 입금 기록 1건. +""" +type AdminDepositRecord { + id: ID! + """ + 기록 종류. + """ + kind: DepositRecordKindType! + """ + 연결한 주문 ID. 반환(RETURN)만 있고 종결이면 null. + """ + orderId: ID + """ + 연결한 주문번호. 반환(RETURN)만 있고 종결이면 null. + """ + orderNumber: String + """ + 입금액(원). + """ + amount: Int! + """ + 은행 앱에 보인 입금자명. + """ + depositorName: String! + """ + 은행 앱에 보인 입금 일시. 입력하지 않았으면 null. + """ + depositedAt: DateTime + """ + 처리 메모. 없으면 null(종결 기록은 항상 있다). + """ + note: String + """ + 기록한 관리자 표시 이름(기록 시점 스냅샷). 이름이 없으면 null. + """ + recordedByLabel: String + """ + 반환으로 생긴 환불 ID(adminRefund로 연다). 종결이면 null. + """ + refundId: ID + """ + 반환으로 생긴 환불의 진행 상태. 종결이면 null. + """ + refundStatus: RefundStatusType + createdAt: DateTime! +} + +""" +입금 기록 목록 페이지. +""" +type AdminDepositRecordConnection { + """ + 입금 기록. 최근 것부터 온다. + """ + items: [AdminDepositRecord!]! + """ + 조건에 맞는 전체 건수(현재 페이지와 무관). 커서 필터는 제외하고 센다. + """ + totalCount: Int! + """ + 다음 페이지 존재 여부. + """ + hasMore: Boolean! + """ + 다음 페이지 커서. null이면 마지막 페이지다. + """ + nextCursor: String +} + +""" +환불 송금 완료 입력. +""" +input AdminCompleteRefundInput { + refundId: ID! + """ + 처리 메모(선택, 500자 이하). 환불 기록에 남는다. + """ + note: String +} + +""" +입금 반환 연결 입력. +""" +input AdminCreateDepositReturnInput { + orderId: ID! + """ + 은행 앱에서 본 입금액(원, 1 이상). 이 금액 전액을 돌려준다. + """ + amount: Int! + """ + 은행 앱에 보인 입금자명(1~50자). + """ + depositorName: String! + """ + 은행 앱에 보인 입금 일시(선택). + """ + depositedAt: DateTime + """ + 처리 메모(선택, 500자 이하). + """ + note: String +} + +""" +주인 모를 입금 종결 기록 입력. +""" +input AdminRecordUnidentifiedDepositInput { + """ + 은행 앱에서 본 입금액(원, 1 이상). + """ + amount: Int! + """ + 은행 앱에 보인 입금자명(1~50자). + """ + depositorName: String! + """ + 은행 앱에 보인 입금 일시(선택). + """ + depositedAt: DateTime + """ + 종결 사유 메모(필수, 500자 이하). + """ + note: String! +} + +""" +종결 기록을 반환 대상으로 바꾸는 입력. +""" +input AdminLinkUnidentifiedDepositInput { + depositRecordId: ID! + orderId: ID! +} diff --git a/src/features/order/order-seller-pickup.graphql b/src/features/order/order-seller-pickup.graphql new file mode 100644 index 00000000..b01870d6 --- /dev/null +++ b/src/features/order/order-seller-pickup.graphql @@ -0,0 +1,50 @@ +extend type Query { + """ + 픽업 일시 변경 시트의 월 달력. 영업일·특별휴무·예약 가능 기간·일일 제작 수량을 보고, 리드타임·상품 제작 시간은 보지 않는다 + (지난 시각만 막는다). 이 주문이 지금 점유한 수량은 빼고 세며, 숨긴 매장도 계산한다. 접수·확정·제작 완료가 아니면 + PICKUP_RESCHEDULE_NOT_ALLOWED, yearMonth 형식이 어긋나면 BAD_USER_INPUT(INVALID_YEAR_MONTH). 입금 확인 전·다른 매장 주문은 NOT_FOUND. + 판매자 로그인 필수. SELLER 계정이 아니면 FORBIDDEN, 매장을 보유하지 않으면 NOT_FOUND. + """ + sellerOrderPickupCalendar( + orderId: ID! + """대상 연월. "YYYY-MM" 형식(KST 기준).""" + yearMonth: String! + ): PickupCalendar! + """ + 픽업 일시 변경 시트의 그날 슬롯. 규칙은 sellerOrderPickupCalendar와 같다. date 형식이 어긋나면 BAD_USER_INPUT(INVALID_DATE). + 판매자 로그인 필수. SELLER 계정이 아니면 FORBIDDEN, 매장을 보유하지 않으면 NOT_FOUND. + """ + sellerOrderPickupTimeSlots( + orderId: ID! + """대상 날짜. "YYYY-MM-DD" 형식(KST 기준).""" + date: String! + ): PickupTimeSlots! +} + +extend type Mutation { + """ + 주문 픽업 일시를 바꾼다(접수·확정·제작 완료만, 그 밖은 PICKUP_RESCHEDULE_NOT_ALLOWED). 지금과 같은 일시면 PICKUP_UNCHANGED, + 영업일·특별휴무·슬롯 시각·지난 시각·예약 가능 기간·일일 제작 수량(이 주문 수량은 빼고 센다)에 맞지 않으면 PICKUP_NOT_AVAILABLE + (모두 BAD_USER_INPUT). 리드타임·상품 제작 시간은 보지 않고, 숨긴 매장의 주문도 바꿀 수 있다. 접수 상태면 확정 마감을 + min(접수 + 24시간, 새 픽업 시각)으로 다시 잰다. 변경 이력(pickupChanges)이 남고 구매자에게 알림이 간다. 커스텀 내용은 바뀌지 않는다. + 입금 확인 전·다른 매장 주문은 NOT_FOUND. 판매자 로그인 필수. SELLER 계정이 아니면 FORBIDDEN, 매장을 보유하지 않으면 NOT_FOUND. + """ + sellerRescheduleOrderPickup( + input: SellerRescheduleOrderPickupInput! + ): SellerOrderSummary! +} + +""" +판매자 픽업 일시 변경 입력. +""" +input SellerRescheduleOrderPickupInput { + orderId: ID! + """ + 새 픽업 일시. sellerOrderPickupTimeSlots의 슬롯 시각이어야 한다(초 이하는 0). + """ + pickupAt: DateTime! + """ + 변경 메모. 선택, 최대 500자. 변경 이력에 남고 구매자도 본다. + """ + note: String +} diff --git a/src/features/order/order-seller.graphql b/src/features/order/order-seller.graphql index 9d257c32..64102e87 100644 --- a/src/features/order/order-seller.graphql +++ b/src/features/order/order-seller.graphql @@ -1,21 +1,34 @@ 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! } extend type Mutation { """ - 주문 상태를 변경한다. 판매자 로그인 필수. SELLER 계정이 아니면 FORBIDDEN, 매장을 보유하지 않으면 NOT_FOUND. + 주문 상태를 변경한다. 접수 → 확정, 확정 → 제작 완료, 확정·제작 완료 → 픽업 완료·노쇼만 된다(그 밖은 + INVALID_ORDER_STATUS_TRANSITION, 같은 상태면 ORDER_STATUS_UNCHANGED). 노쇼는 픽업 시각부터 24시간(자동 픽업 완료 전) + 안에서만 되고 벗어나면 NO_SHOW_NOT_ALLOWED(BAD_USER_INPUT)다. 픽업 완료·노쇼는 정산 금액을 확정하고, 노쇼는 환불이 없다. + 취소(CANCELED)는 받지 않으므로 sellerCancelOrder를 쓴다(INVALID_ORDER_STATUS_TRANSITION). + 판매자 로그인 필수. SELLER 계정이 아니면 FORBIDDEN, 매장을 보유하지 않으면 NOT_FOUND. """ sellerUpdateOrderStatus( input: SellerUpdateOrderStatusInput! ): SellerOrderSummary! + """ + 주문을 거절·취소한다. 접수(SUBMITTED) 단계 거절은 결제액 전액 환불이고, 확정·제작 완료(CONFIRMED·MADE) 뒤 취소는 + fault(사정)가 필수다(판매자 사정 = 전액 환불, 구매자 사정 = refundAmount 환불, 남는 금액은 수수료를 뺀 뒤 정산에 포함). + 환불 송금은 케이퀵이 한다. 그 밖의 상태면 ORDER_NOT_CANCELLABLE, 판매자가 고를 수 없는 사유면 CANCEL_REASON_NOT_ALLOWED, + 사정이 없으면 CANCEL_FAULT_REQUIRED, 구매자 사정인데 금액이 없으면 REFUND_AMOUNT_REQUIRED, + 금액이 0~결제액 밖이면 REFUND_AMOUNT_OUT_OF_RANGE(모두 BAD_USER_INPUT). 입금 확인 전·다른 매장 주문은 NOT_FOUND. + 판매자 로그인 필수. SELLER 계정이 아니면 FORBIDDEN, 매장을 보유하지 않으면 NOT_FOUND. + """ + sellerCancelOrder(input: SellerCancelOrderInput!): SellerOrderSummary! } """ @@ -59,6 +72,19 @@ type SellerOrderSummary { 내 매장 첫 품목의 상품 대표 이미지 URL(주문 시점 스냅샷). 주문 당시 이미지가 없었으면 null. """ firstItemImageUrl: String + """ + 커스텀 주문 여부(내 매장 첫 품목의 커스텀 방식이 NONE이 아니면 true). 목록 '커스텀' 배지용이다. + """ + hasCustom: Boolean! + """ + 내 매장 첫 품목의 커스텀 대표 이미지 URL(3D 윗면 렌더 또는 슬롯형 합성). 없으면 null. + """ + firstItemCustomImageUrl: String + """ + 확정 마감 시각. 이때까지 확정하지 않으면 자동 취소되고 결제액 전액이 환불된다. 접수(SUBMITTED) 상태가 아니거나 + 결제 도입 전 주문이면 null. + """ + confirmDeadlineAt: DateTime } """ @@ -100,6 +126,10 @@ input SellerOrderListInput { """ status: OrderStatusType """ + 구매자 계정 ID 필터. 채팅 상대의 주문만 볼 때 쓴다. 미지정 시 전체. + """ + buyerAccountId: ID + """ 주문 생성 시각 하한(이상). """ fromCreatedAt: DateTime @@ -151,6 +181,14 @@ type SellerOrderDetail { """ buyerPhone: String! """ + 구매자가 남긴 요청 사항. 없으면 null. + """ + requestNote: String + """ + 결제 수단. 결제 도입 전 주문이면 null. 값은 늘어날 수 있으니 모르는 값은 '기타'로 보여 준다. + """ + paymentMethod: PaymentMethodType + """ 할인 전 품목 합계(원). """ subtotalPrice: Int! @@ -189,9 +227,52 @@ type SellerOrderDetail { """ items: [OrderItemDetail!]! """ - 상태 변경 이력. 최신순. + 상태 변경 이력. 최신순. 입금 대기 이력은 빠지고, 접수 이력은 fromStatus가 null(최초)로 온다. """ statusHistories: [OrderStatusHistory!]! + """ + 취소 정보(주체·사유·사정·환불액·환불 진행). 취소되지 않은 주문이면 null. + """ + cancellation: OrderCancellation + """ + 확정 마감 시각. 이때까지 확정하지 않으면 자동 취소되고 결제액 전액이 환불된다. 접수(SUBMITTED) 상태가 아니거나 + 결제 도입 전 주문이면 null. + """ + confirmDeadlineAt: DateTime + """ + 자동 픽업 완료 예정 시각(픽업 시각 + 24시간). 확정·제작 완료 상태에서만 있고 그 밖은 null. + 매장이 숨김이면 자동으로 픽업 완료되지 않는다. + """ + autoPickupAt: DateTime + """ + 지금 노쇼로 처리할 수 있는지. 확정·제작 완료 상태이고 픽업 시각 ≤ 지금 < autoPickupAt일 때 true. + """ + canMarkNoShow: Boolean! + """ + 노쇼 처리 시각. 노쇼가 아니면 null. + """ + noShowAt: DateTime + """ + 픽업 일시 변경 이력. 오래된 순, 없으면 빈 배열. + """ + pickupChanges: [OrderPickupChange!]! + """ + 주문 생성 시점의 수수료율(bp, 1bp = 0.01%). 바뀐 설정은 그 뒤 주문부터 적용된다. + """ + commissionRateBps: Int! + """ + 정산 예정 금액(원). 정산 확정 뒤에는 실제 지급액(기준액 − 수수료), 확정 전에는 결제 금액에서 수수료(원 미만 버림)를 뺀 + 예상값이다. 입금이 확인되지 않았거나 결제 도입 전 주문이면 null, 확정 없이 취소된 주문(전액 환불)은 0. + """ + expectedPayoutAmount: Int + """ + 확정된 수수료 기준액(원). 픽업 완료·노쇼는 결제 금액, 구매자 사정 취소는 결제 금액 − 환불 금액. 확정 전이면 null. + """ + settlementBaseAmount: Int + """ + 확정된 수수료(원). 기준액 × 수수료율, 원 미만 버림. 확정 전이면 null. + """ + commissionAmount: Int } """ @@ -201,11 +282,34 @@ BAD_USER_INPUT으로 거절된다. input SellerUpdateOrderStatusInput { orderId: ID! """ - 변경할 상태. 현재 상태에서 진입 가능한 값이어야 한다. + 변경할 상태. CONFIRMED·MADE·PICKED_UP·NO_SHOW 중 현재 상태에서 진입 가능한 값이어야 한다. """ 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-settlement-admin.graphql b/src/features/order/order-settlement-admin.graphql new file mode 100644 index 00000000..4a98c577 --- /dev/null +++ b/src/features/order/order-settlement-admin.graphql @@ -0,0 +1,266 @@ +extend type Query { + """ + 주간 정산 목록. 최근 생성 순. 매주 월요일 05:00(KST)에 지난주(월~일)까지 정산이 확정된 주문을 매장별로 묶어 만든다. + 날짜 형식이 어긋나면 INVALID_DATE(BAD_USER_INPUT). 관리자 로그인 필수. ADMIN 계정이 아니면 FORBIDDEN. + """ + adminSettlements(input: AdminSettlementListInput): AdminSettlementConnection! + """ + 주간 정산 1건과 포함 주문·현재 매장 정산 계좌(원문). 없으면 NOT_FOUND(SETTLEMENT_NOT_FOUND). + 관리자 로그인 필수. ADMIN 계정이 아니면 FORBIDDEN. + """ + adminSettlement(settlementId: ID!): AdminSettlementDetail! + """ + 월 수수료 집계. 정산 확정 시각의 KST 월로 매장별 주문 수·기준액·수수료를 묶는다(주간 정산 여부와 무관). + 월 형식이 어긋나면 INVALID_YEAR_MONTH(BAD_USER_INPUT). 관리자 로그인 필수. ADMIN 계정이 아니면 FORBIDDEN. + """ + adminMonthlyCommissions( + input: AdminMonthlyCommissionInput! + ): AdminMonthlyCommissionReport! +} + +extend type Mutation { + """ + 은행 앱에서 매장 정산 계좌로 송금한 뒤 송금 완료로 처리한다. 그 시점 매장 정산 계좌를 송금 계좌로 남기고 감사 로그(SETTLEMENT)를 쓴다. + 이미 송금 완료면 SETTLEMENT_ALREADY_PAID(CONFLICT), 매장 정산 계좌가 없으면 SETTLEMENT_ACCOUNT_REQUIRED(BAD_USER_INPUT), + 메모가 500자를 넘으면 TEXT_TOO_LONG, 없는 정산이면 NOT_FOUND. 관리자 로그인 필수. ADMIN 계정이 아니면 FORBIDDEN. + """ + adminMarkSettlementPaid( + input: AdminMarkSettlementPaidInput! + ): AdminSettlementDetail! +} + +""" +주간 정산 목록 조회 조건. 모든 필터는 AND로 결합된다. +""" +input AdminSettlementListInput { + """ + 한 번에 가져올 개수. 기본 20, 1~100만 허용하며 벗어나면 BAD_USER_INPUT. + """ + limit: Int = 20 + """ + 이전 응답의 nextCursor. 첫 페이지는 생략한다. 필터를 바꾸면 커서를 버리고 첫 페이지부터 다시 조회한다. + """ + cursor: String + """ + 송금 상태 필터. null이면 전체. + """ + status: SettlementStatusType + """ + 매장 필터. null이면 전체. + """ + storeId: ID + """ + 정산 기간 시작일(월요일, KST, YYYY-MM-DD) 필터. 관리자 알림 링크의 periodStart와 같다. null이면 전체. + """ + periodStart: String +} + +""" +주간 정산 1건(관리자 시점). +""" +type AdminSettlementSummary { + id: ID! + storeId: ID! + """ + 매장명(정산에 묶인 가장 최근 주문의 스냅샷). + """ + storeName: String! + """ + 정산 기간 시작일(월요일, KST). YYYY-MM-DD. + """ + periodStart: String! + """ + 정산 기간 마지막 날(일요일, KST). YYYY-MM-DD. + """ + periodEnd: String! + """ + 포함 주문 수. 앞 정산에서 빠진 주문(늦게 확정된 주문)도 함께 묶인다. + """ + orderCount: Int! + """ + 수수료 기준액 합계(원). + """ + settlementBaseAmount: Int! + """ + 수수료 합계(원). + """ + commissionAmount: Int! + """ + 송금할 금액(원) = 기준액 합계 − 수수료 합계. + """ + payoutAmount: Int! + """ + 송금 상태. + """ + status: SettlementStatusType! + """ + 송금 완료 시각. 송금 전이면 null. + """ + paidAt: DateTime + """ + 지금 매장 정산 계좌가 등록돼 있는지. false면 송금 완료로 처리할 수 없다. + """ + accountRegistered: Boolean! + createdAt: DateTime! +} + +""" +주간 정산 목록 페이지. +""" +type AdminSettlementConnection { + """ + 주간 정산. 최근 생성 순. + """ + items: [AdminSettlementSummary!]! + """ + 조건에 맞는 전체 건수(현재 페이지와 무관). 커서 필터는 제외하고 센다. + """ + totalCount: Int! + """ + 다음 페이지 존재 여부. + """ + hasMore: Boolean! + """ + 다음 페이지 커서. null이면 마지막 페이지다. + """ + nextCursor: String +} + +""" +주간 정산 상세(관리자 시점). 현재 계좌 원문이 들어 있으니 화면 밖(로그·분석 이벤트)에 남기지 않는다. +""" +type AdminSettlementDetail { + id: ID! + storeId: ID! + """ + 매장명(정산에 묶인 가장 최근 주문의 스냅샷). + """ + storeName: String! + """ + 정산 기간 시작일(월요일, KST). YYYY-MM-DD. + """ + periodStart: String! + """ + 정산 기간 마지막 날(일요일, KST). YYYY-MM-DD. + """ + periodEnd: String! + """ + 포함 주문 수. + """ + orderCount: Int! + """ + 수수료 기준액 합계(원). + """ + settlementBaseAmount: Int! + """ + 수수료 합계(원). + """ + commissionAmount: Int! + """ + 송금할 금액(원) = 기준액 합계 − 수수료 합계. + """ + payoutAmount: Int! + """ + 송금 상태. + """ + status: SettlementStatusType! + """ + 송금 완료 시각. 송금 전이면 null. + """ + paidAt: DateTime + """ + 지금 매장 정산 계좌가 등록돼 있는지(currentAccount가 있는지). + """ + accountRegistered: Boolean! + createdAt: DateTime! + """ + 송금 완료로 처리한 관리자 표시 이름(처리 시점 스냅샷). 송금 전이거나 이름이 없으면 null. + """ + paidByLabel: String + """ + 송금 메모. 없으면 null. + """ + paidNote: String + """ + 송금한 계좌(송금 시점 스냅샷, 끝 4자리만). 송금 전이면 null. + """ + paidAccount: SettlementPaidAccount + """ + 지금 매장 정산 계좌(계좌번호 원문 포함). 송금할 때 쓴다. 등록 전이면 null. + """ + currentAccount: AdminStoreSettlementAccount + """ + 포함 주문. 주문 id 순. + """ + orders: [SettlementOrder!]! +} + +""" +송금 완료 입력. +""" +input AdminMarkSettlementPaidInput { + settlementId: ID! + """ + 송금 메모(선택, 500자 이하). 정산과 감사 로그에 남는다. + """ + note: String +} + +""" +월 수수료 집계 조건. +""" +input AdminMonthlyCommissionInput { + """ + 집계 월(KST). "YYYY-MM" 형식. 예: "2026-11". + """ + month: String! +} + +""" +월 수수료 집계. +""" +type AdminMonthlyCommissionReport { + """ + 집계 월. "YYYY-MM". + """ + month: String! + """ + 정산이 확정된 주문 수 합계. + """ + orderCount: Int! + """ + 수수료 기준액 합계(원). + """ + settlementBaseAmount: Int! + """ + 수수료 합계(원). + """ + commissionAmount: Int! + """ + 매장별 집계. 매장 id 순, 확정 주문이 없는 매장은 빠진다. + """ + stores: [AdminMonthlyCommissionStore!]! +} + +""" +매장 1곳의 월 수수료. +""" +type AdminMonthlyCommissionStore { + storeId: ID! + """ + 매장명(그 달 가장 최근 확정 주문의 스냅샷). + """ + storeName: String! + """ + 정산이 확정된 주문 수. + """ + orderCount: Int! + """ + 수수료 기준액 합계(원). + """ + settlementBaseAmount: Int! + """ + 수수료 합계(원). + """ + commissionAmount: Int! +} diff --git a/src/features/order/order-settlement-seller.graphql b/src/features/order/order-settlement-seller.graphql new file mode 100644 index 00000000..ad07a734 --- /dev/null +++ b/src/features/order/order-settlement-seller.graphql @@ -0,0 +1,197 @@ +extend type Query { + """ + 내 매장 정산 계좌를 조회한다. 계좌번호는 끝 4자리만 내려준다. 등록 전이면 null. + 판매자 로그인 필수. SELLER 계정이 아니면 FORBIDDEN, 매장을 보유하지 않으면 NOT_FOUND. + """ + sellerSettlementAccount: SellerSettlementAccount + """ + 내 매장 주간 정산 내역. 최근 생성 순(매주 월요일에 지난주분이 생긴다). + 판매자 로그인 필수. SELLER 계정이 아니면 FORBIDDEN, 매장을 보유하지 않으면 NOT_FOUND. + """ + sellerSettlements(input: SellerSettlementListInput): SellerSettlementConnection! + """ + 내 매장 주간 정산 1건과 포함 주문. 다른 매장 정산이거나 없으면 NOT_FOUND(SETTLEMENT_NOT_FOUND). + 판매자 로그인 필수. SELLER 계정이 아니면 FORBIDDEN, 매장을 보유하지 않으면 NOT_FOUND. + """ + sellerSettlement(settlementId: ID!): SellerSettlementDetail! +} + +""" +주간 정산 목록 조회 조건. +""" +input SellerSettlementListInput { + """ + 한 번에 가져올 개수. 기본 20, 1~100만 허용하며 벗어나면 BAD_USER_INPUT. + """ + limit: Int = 20 + """ + 이전 응답의 nextCursor. 첫 페이지는 생략한다. + """ + cursor: String +} + +""" +주간 정산 1건(판매자 시점). 월~일(KST) 동안 정산이 확정된 주문(그 전에 빠진 주문 포함)을 묶는다. +""" +type SellerSettlementSummary { + id: ID! + """ + 정산 기간 시작일(월요일, KST). YYYY-MM-DD. + """ + periodStart: String! + """ + 정산 기간 마지막 날(일요일, KST). YYYY-MM-DD. + """ + periodEnd: String! + """ + 포함 주문 수. + """ + orderCount: Int! + """ + 수수료 기준액 합계(원). + """ + settlementBaseAmount: Int! + """ + 수수료 합계(원). + """ + commissionAmount: Int! + """ + 정산 금액(원) = 기준액 합계 − 수수료 합계. 케이퀵이 매장 정산 계좌로 보내는 금액이다. + """ + payoutAmount: Int! + """ + 송금 여부. PENDING이면 송금 대기, PAID면 송금 완료. + """ + status: SettlementStatusType! + """ + 송금 완료 시각. 송금 전이면 null. + """ + paidAt: DateTime + createdAt: DateTime! +} + +""" +주간 정산 목록 페이지. +""" +type SellerSettlementConnection { + """ + 주간 정산. 최근 생성 순. + """ + items: [SellerSettlementSummary!]! + """ + 전체 건수(현재 페이지와 무관). + """ + totalCount: Int! + """ + 다음 페이지 존재 여부. + """ + hasMore: Boolean! + """ + 다음 페이지 커서. null이면 마지막 페이지다. + """ + nextCursor: String +} + +""" +주간 정산 상세(판매자 시점). +""" +type SellerSettlementDetail { + id: ID! + """ + 정산 기간 시작일(월요일, KST). YYYY-MM-DD. + """ + periodStart: String! + """ + 정산 기간 마지막 날(일요일, KST). YYYY-MM-DD. + """ + periodEnd: String! + """ + 포함 주문 수. + """ + orderCount: Int! + """ + 수수료 기준액 합계(원). + """ + settlementBaseAmount: Int! + """ + 수수료 합계(원). + """ + commissionAmount: Int! + """ + 정산 금액(원) = 기준액 합계 − 수수료 합계. + """ + payoutAmount: Int! + """ + 송금 여부. + """ + status: SettlementStatusType! + """ + 송금 완료 시각. 송금 전이면 null. + """ + paidAt: DateTime + createdAt: DateTime! + """ + 송금한 계좌(송금 시점 스냅샷, 끝 4자리만). 송금 전이면 null. + """ + paidAccount: SettlementPaidAccount + """ + 포함 주문. 주문 id 순. + """ + orders: [SettlementOrder!]! +} + +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-subscription.graphql b/src/features/order/order-subscription.graphql index 781c9753..cdcf029f 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! @@ -27,6 +31,20 @@ type SellerOrderUpdate { totalPrice: Int! """첫 품목의 상품명(주문 시점 스냅샷). 주문은 단일 상품 구조다.""" productName: String! + """커스텀 주문 여부(첫 품목의 커스텀 방식이 NONE이 아니면 true).""" + hasCustom: Boolean! """주문 행의 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 dfe5cfc4..199a9584 100644 --- a/src/features/order/order.module.ts +++ b/src/features/order/order.module.ts @@ -1,24 +1,63 @@ import { Module } from '@nestjs/common'; import { BOOKED_QUANTITY_QUERY } from '@/common/ports/booked-quantity.port'; +import { WithdrawalBlockingOrderQuery } from '@/common/ports/withdrawal-blocking-order.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 { DepositRecordRepository } from '@/features/order/repositories/deposit-record.repository'; import { OrderBookedRepository } from '@/features/order/repositories/order-booked.repository'; +import { OrderCustomUploadRepository } from '@/features/order/repositories/order-custom-upload.repository'; +import { OrderInquiryRepository } from '@/features/order/repositories/order-inquiry.repository'; +import { OrderLifecycleRepository } from '@/features/order/repositories/order-lifecycle.repository'; +import { OrderPickupChangeRepository } from '@/features/order/repositories/order-pickup-change.repository'; import { OrderStoreDailyLimitRepository } from '@/features/order/repositories/order-store-daily-limit.repository'; +import { OrderTransitionRepository } from '@/features/order/repositories/order-transition.repository'; +import { OrderWithdrawalBlockingRepository } from '@/features/order/repositories/order-withdrawal-blocking.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 { RefundRepository } from '@/features/order/repositories/refund.repository'; +import { SettlementRepository } from '@/features/order/repositories/settlement.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'; +import { PaymentQueryResolver } from '@/features/order/resolvers/order-payment-query.resolver'; +import { AdminRefundMutationResolver } from '@/features/order/resolvers/order-refund-admin-mutation.resolver'; +import { AdminRefundQueryResolver } from '@/features/order/resolvers/order-refund-admin-query.resolver'; import { SellerOrderMutationResolver } from '@/features/order/resolvers/order-seller-mutation.resolver'; +import { SellerOrderPickupMutationResolver } from '@/features/order/resolvers/order-seller-pickup-mutation.resolver'; +import { SellerOrderPickupQueryResolver } from '@/features/order/resolvers/order-seller-pickup-query.resolver'; import { SellerOrderQueryResolver } from '@/features/order/resolvers/order-seller-query.resolver'; +import { AdminSettlementMutationResolver } from '@/features/order/resolvers/order-settlement-admin-mutation.resolver'; +import { AdminSettlementQueryResolver } from '@/features/order/resolvers/order-settlement-admin-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 { 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 { 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 { OrderLifecycleScheduler } from '@/features/order/services/order-lifecycle.scheduler'; import { UserOrderService } from '@/features/order/services/order-my.service'; +import { AdminPaymentService } from '@/features/order/services/order-payment-admin.service'; +import { AdminRefundService } from '@/features/order/services/order-refund-admin.service'; +import { SellerOrderPickupService } from '@/features/order/services/order-seller-pickup.service'; import { SellerOrderService } from '@/features/order/services/order-seller.service'; +import { AdminSettlementService } from '@/features/order/services/order-settlement-admin.service'; +import { SellerSettlementService } from '@/features/order/services/order-settlement-seller.service'; +import { SettlementScheduler } from '@/features/order/services/order-settlement.scheduler'; 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'; @@ -43,26 +82,80 @@ import { StoreModule } from '@/features/store'; OrderStoreDailyLimitRepository, OrderStoreDailyLimitConsumer, OrderStatusTransitionPolicy, - // 판매자 주문 구독(Redis PubSub) — 발행은 체크아웃·판매자 상태 변경·관리자 취소 서비스가 커밋 뒤 직접 + // 주체별 취소 사유·사정·환불액 판정(구매자·판매자·관리자 취소가 공유) + OrderCancelPolicy, + // 판매자 주문 구독(Redis PubSub) — 발행은 입금 확인·판매자 상태 변경·취소 서비스가 커밋 뒤 직접 OrderEventsService, OrderSubscriptionService, OrderSubscriptionResolver, OrderCheckoutService, OrderCheckoutMutationResolver, - // 판매자 주문 관리(목록·상세·상태 변경) — 주문 도메인이 소유한다 + // 주문 생성의 커스텀 입력 검증·스냅샷(상품 설정 대조, 업로드 소유) + OrderCustomizationService, + // 커스텀 이미지 선업로드 기록과 미사용분 정리(worker 크론) + OrderCustomUploadRepository, + OrderCustomUploadCleanupScheduler, + // 판매자 주문 관리(목록·상세·상태 변경·거절·취소) — 주문 도메인이 소유한다 SellerOrderService, SellerOrderQueryResolver, SellerOrderMutationResolver, + // 판매자 픽업 일시 변경(변경 시트 달력·슬롯 포함) + OrderPickupChangeRepository, + SellerOrderPickupService, + SellerOrderPickupQueryResolver, + SellerOrderPickupMutationResolver, // 관리자 주문 관리(목록·상세·강제 취소) AdminOrderService, AdminOrderQueryResolver, AdminOrderMutationResolver, - // 구매자 주문 목록·상세 + // 구매자 주문 목록·상세·'입금했어요'·취소 UserOrderService, UserOrderQueryResolver, + UserOrderMutationResolver, + // 결제(입금 대기)와 상태 전이 잠금 단위, 관리자 입금 확인 + PaymentRepository, + OrderTransitionRepository, + // 자동 전이 크론(미입금 취소·확정 마감 알림·미확정 취소·자동 픽업 완료, worker) + OrderLifecycleRepository, + OrderLifecycleScheduler, + AdminDepositService, + AdminDepositQueryResolver, + AdminDepositMutationResolver, + // 환불 계좌 입력·송금 완료, 입금 반환·종결 기록 + RefundRepository, + DepositRecordRepository, + AdminRefundService, + AdminRefundQueryResolver, + AdminRefundMutationResolver, + // auth(구매자 탈퇴)가 ModuleRef로 찾는 탈퇴 차단 포트 구현 + { + provide: WithdrawalBlockingOrderQuery, + useClass: OrderWithdrawalBlockingRepository, + }, + // 입금 대기·'입금했어요'·환불 송금 대기·주간 정산 관리자 디스코드 알림(worker 소비자) + OrderAdminAlertConsumer, + // 결제 설정·매장 정산 계좌(계좌번호는 global AccountCipher로 암호화) + PaymentSettingRepository, + StoreSettlementAccountRepository, + PaymentQueryResolver, + AdminPaymentService, + AdminPaymentQueryResolver, + AdminPaymentMutationResolver, + SellerSettlementService, + SellerSettlementQueryResolver, + SellerSettlementMutationResolver, + // 채팅 주문 카드·숨김 매장 문의 판정(conversation) + OrderInquiryRepository, + // 주간 정산(worker 크론·부팅 1회)과 관리자 송금 완료·월 수수료, 판매자 정산 내역 + SettlementRepository, + SettlementScheduler, + AdminSettlementService, + AdminSettlementQueryResolver, + AdminSettlementMutationResolver, ], exports: [ OrderRepository, + OrderInquiryRepository, OrderStatusTransitionPolicy, BOOKED_QUANTITY_QUERY, ], diff --git a/src/features/order/order.types.graphql b/src/features/order/order.types.graphql index fa6df15d..a322dbb8 100644 --- a/src/features/order/order.types.graphql +++ b/src/features/order/order.types.graphql @@ -1,12 +1,17 @@ """ -주문 상태. 구매자·판매자 API가 공용으로 쓴다. +주문 상태. 구매자·판매자·관리자 API가 공용으로 쓴다. 값은 늘어날 수 있으니 모르는 값을 받아도 화면이 죽지 않게 처리한다. -전이는 `SUBMITTED → CONFIRMED → MADE → PICKED_UP` 한 방향이며 각 단계는 직전 -상태에서만 진입할 수 있다. `CANCELED`는 `PICKED_UP` 이전 세 상태에서만 가능하고, -어떤 상태에서도 `SUBMITTED`로 되돌아갈 수 없다. +흐름은 `PENDING_PAYMENT → SUBMITTED → CONFIRMED → MADE → PICKED_UP`이며 어떤 상태에서도 +앞 단계로 되돌아갈 수 없다. 판매자가 sellerUpdateOrderStatus로 바꿀 수 있는 전이는 `SUBMITTED → CONFIRMED`, +`CONFIRMED → MADE`, `CONFIRMED·MADE → PICKED_UP·NO_SHOW`뿐이고, 취소는 주체별 취소 mutation(cancelMyOrder·sellerCancelOrder·adminCancelOrder)으로만 한다. +관리자도 adminCompleteOrderPickup으로 확정·제작 완료 주문을 픽업 완료할 수 있다. +시스템은 입금 기한(1시간)이 지난 입금 대기를 취소하고, 확정 마감이 지난 접수를 취소(전액 환불)하며, +픽업 시각 + 24시간이 지난 확정·제작 완료를 픽업 완료로 바꾼다. 판매자에게는 입금이 확인된(접수된) 주문만 보인다. """ enum OrderStatusType { - """구매자가 주문을 넣은 직후의 초기 상태. 판매자 확인 대기.""" + """입금 대기. 주문 직후 계좌이체 입금을 기다리는 상태이고, 판매자에게 보이지 않는다.""" + PENDING_PAYMENT + """입금이 확인돼 접수된 상태. 판매자 확인 대기.""" SUBMITTED """판매자가 주문을 확인·수락한 상태. 제작 대기.""" CONFIRMED @@ -14,10 +19,26 @@ enum OrderStatusType { MADE """구매자가 수령을 마친 종료 상태. 이후 상태 변경 불가.""" PICKED_UP - """취소된 종료 상태. 취소 처리에는 사유(note)가 필수다.""" + """노쇼. 구매자가 픽업 시간에 오지 않아 판매자가 처리한 종료 상태. 환불 없음, 리뷰 불가.""" + NO_SHOW + """취소된 종료 상태. 주체·사유·사정·환불은 주문 상세의 cancellation에 있다.""" CANCELED } +""" +주문·결제·정산 기록을 남긴 주체. 값은 늘어날 수 있으니 모르는 값을 받아도 화면이 죽지 않게 처리한다. +""" +enum OrderActorType { + """구매자.""" + BUYER + """판매자.""" + SELLER + """관리자.""" + ADMIN + """시스템 자동 처리.""" + SYSTEM +} + """주문 상태 변경 이력 1건. 구매자·판매자·관리자 주문 상세가 공용으로 쓴다.""" type OrderStatusHistory { id: ID! @@ -27,8 +48,199 @@ 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 +} + +""" +주간 정산 상태. 값은 늘어날 수 있으니 모르는 값을 받아도 화면이 죽지 않게 처리한다. +""" +enum SettlementStatusType { + """케이퀵의 매장 송금 대기.""" + PENDING + """송금 완료.""" + PAID +} + +""" +정산을 송금한 계좌(송금 시점 스냅샷). 계좌번호는 끝 4자리만 내려준다. +""" +type SettlementPaidAccount { + """ + 은행. + """ + bank: Bank! + """ + 예금주. + """ + accountHolder: String! + """ + 끝 4자리만 남긴 계좌번호(예: ****1234). + """ + accountNumberMasked: String! +} + +""" +주간 정산에 묶인 주문 1건. +""" +type SettlementOrder { + orderId: ID! + """ + 주문번호. + """ + orderNumber: String! + """ + 상품명(주문 시점 스냅샷). 품목이 없으면 null. + """ + productName: String + """ + 주문 상태(픽업 완료·노쇼, 구매자 사정 취소의 남은 금액이면 취소). + """ + status: OrderStatusType! + """ + 주문 생성 시점의 수수료율(bp, 1bp = 0.01%). + """ + commissionRateBps: Int! + """ + 수수료 기준액(원). 결제 금액, 구매자 사정 취소면 결제 금액 − 환불 금액. + """ + settlementBaseAmount: Int! + """ + 수수료(원). 기준액 × 수수료율, 원 미만 버림. + """ + commissionAmount: Int! + """ + 매장 지급액(원) = 기준액 − 수수료. + """ + payoutAmount: Int! + """ + 정산 확정 시각(픽업 완료·노쇼·구매자 사정 취소 시각). 이 시각이 속한 주(월~일, KST)가 끝난 뒤 첫 주간 정산에 묶인다. + """ + settlementFinalizedAt: DateTime! +} + +""" +주문 취소 정보. 취소된 주문에만 있다. +""" +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 } """ @@ -51,12 +263,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! @@ -68,24 +387,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! """요청 순서. 오름차순.""" @@ -102,3 +449,18 @@ type OrderItemFreeEditAttachment { """첨부 순서. 오름차순.""" sortOrder: Int! } + +""" +판매자 픽업 일시 변경 이력 1건. 구매자·판매자·관리자 주문 상세가 공용으로 쓴다. +""" +type OrderPickupChange { + id: ID! + """변경 전 픽업 일시.""" + fromPickupAt: DateTime! + """변경 후 픽업 일시.""" + toPickupAt: DateTime! + """변경 시각.""" + changedAt: DateTime! + """판매자가 남긴 변경 메모. 없으면 null.""" + note: String +} 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-lifecycle.policy.spec.ts b/src/features/order/policies/order-lifecycle.policy.spec.ts new file mode 100644 index 00000000..acc18272 --- /dev/null +++ b/src/features/order/policies/order-lifecycle.policy.spec.ts @@ -0,0 +1,115 @@ +import { HOUR_MS } from '@/common/utils/kst-time'; +import { + isConfirmReminderDue, + isConfirmTimedOut, + isPaymentExpired, + type OrderLockedState, +} from '@/features/order/policies/order-lifecycle.policy'; +import type { OrderStatus } from '@/generated/prisma/client'; + +const NOW = new Date('2026-11-19T05:00:00.000Z'); +const DAY = 24 * HOUR_MS; +const at = (offsetMs: number) => new Date(NOW.getTime() + offsetMs); + +function state(overrides: Partial = {}): OrderLockedState { + return { + status: 'PENDING_PAYMENT', + pickupAt: at(DAY), + confirmDeadlineAt: null, + payment: { status: 'PENDING', expires_at: NOW, buyer_claimed_at: null }, + ...overrides, + }; +} + +describe('order-lifecycle.policy', () => { + describe('isPaymentExpired', () => { + it.each([ + ['기한 정각', state(), true], + [ + '기한 1ms 전', + state({ + payment: { + status: 'PENDING', + expires_at: at(1), + buyer_claimed_at: null, + }, + }), + false, + ], + [ + "'입금했어요'를 누름", + state({ + payment: { + status: 'PENDING', + expires_at: at(-1), + buyer_claimed_at: at(-HOUR_MS), + }, + }), + false, + ], + [ + '결제 확인됨', + state({ + payment: { + status: 'CONFIRMED', + expires_at: at(-1), + buyer_claimed_at: null, + }, + }), + false, + ], + ['주문이 이미 접수', state({ status: 'SUBMITTED' }), false], + ['결제 없음(도입 전)', state({ payment: null }), false], + ])('%s → %s', (_label, s, expected) => { + expect(isPaymentExpired(s, NOW)).toBe(expected); + }); + }); + + describe('isConfirmTimedOut', () => { + it.each<[string, OrderStatus, Date | null, boolean]>([ + ['마감 정각', 'SUBMITTED', NOW, true], + ['마감 1ms 전', 'SUBMITTED', at(1), false], + ['마감 없음(결제 도입 전)', 'SUBMITTED', null, false], + ['이미 확정', 'CONFIRMED', at(-1), false], + ])('%s → %s', (_label, status, deadline, expected) => { + expect( + isConfirmTimedOut(state({ status, confirmDeadlineAt: deadline }), NOW), + ).toBe(expected); + }); + }); + + describe('isConfirmReminderDue(마감 − 2h ≤ now < 마감, 마감 − 2h > 접수)', () => { + const due = ( + deadline: Date | null, + submittedAt: Date | null, + overrides: { status?: OrderStatus; sentAt?: Date | null } = {}, + ) => + isConfirmReminderDue( + { + status: overrides.status ?? 'SUBMITTED', + submittedAt, + confirmDeadlineAt: deadline, + confirmReminderSentAt: overrides.sentAt ?? null, + }, + NOW, + ); + + it.each<[string, Date | null, Date | null, boolean]>([ + ['마감 2시간 전 정각', at(2 * HOUR_MS), at(-DAY), true], + ['마감 2시간 + 1ms 전', at(2 * HOUR_MS + 1), at(-DAY), false], + ['마감 1ms 전', at(1), at(-DAY), true], + ['마감 정각', NOW, at(-DAY), false], + ['마감 − 2h = 접수', at(HOUR_MS), at(-HOUR_MS), false], + ['마감 − 2h = 접수 + 1ms', at(HOUR_MS + 1), at(-HOUR_MS), true], + ['마감 없음', null, at(-DAY), false], + ['접수 시각 없음', at(HOUR_MS), null, false], + ])('%s → %s', (_label, deadline, submittedAt, expected) => { + expect(due(deadline, submittedAt)).toBe(expected); + }); + + it('이미 보냈거나 접수 상태가 아니면 보내지 않는다', () => { + expect(due(at(HOUR_MS), at(-DAY), { sentAt: at(-1) })).toBe(false); + expect(due(at(HOUR_MS), at(-DAY), { status: 'CONFIRMED' })).toBe(false); + }); + }); +}); diff --git a/src/features/order/policies/order-lifecycle.policy.ts b/src/features/order/policies/order-lifecycle.policy.ts new file mode 100644 index 00000000..924f430e --- /dev/null +++ b/src/features/order/policies/order-lifecycle.policy.ts @@ -0,0 +1,71 @@ +import { DAY_MS, HOUR_MS } from '@/common/utils/kst-time'; +import { + OrderStatus, + PaymentStatus, + type Payment, +} from '@/generated/prisma/client'; + +/** 판매자 확정 마감: 접수(입금 확인) + 24시간과 픽업 시각 중 이른 쪽. 픽업 변경 때도 다시 잰다. */ +export function confirmDeadlineFor(submittedAt: Date, pickupAt: Date): Date { + return new Date(Math.min(submittedAt.getTime() + DAY_MS, pickupAt.getTime())); +} + +/** 확정 마감 이만큼 전에 판매자에게 미리 알린다. */ +export const CONFIRM_REMINDER_LEAD_MS = 2 * HOUR_MS; + +/** 잠금 읽기로 다시 본 주문·결제(크론 대상 재검사 재료). */ +export interface OrderLockedState { + status: OrderStatus; + pickupAt: Date; + confirmDeadlineAt: Date | null; + payment: Pick | null; +} + +export interface ConfirmReminderState { + status: OrderStatus; + submittedAt: Date | null; + confirmDeadlineAt: Date | null; + confirmReminderSentAt: Date | null; +} + +/** 미입금 취소 대상: 유예 없이 입금 기한 정각부터, '입금했어요'를 누른 주문은 관리자 확인을 기다린다. */ +export function isPaymentExpired(state: OrderLockedState, now: Date): boolean { + const { payment } = state; + return ( + state.status === OrderStatus.PENDING_PAYMENT && + payment?.status === PaymentStatus.PENDING && + payment.buyer_claimed_at === null && + payment.expires_at <= now + ); +} + +/** 미확정 취소 대상: 확정 마감이 지난 접수. 결제 도입 전 접수는 마감이 없어 빠진다. */ +export function isConfirmTimedOut(state: OrderLockedState, now: Date): boolean { + return ( + state.status === OrderStatus.SUBMITTED && + state.confirmDeadlineAt !== null && + state.confirmDeadlineAt <= now + ); +} + +/** 마감 2시간 전 구간의 미발송 접수. 접수 시점에 이미 그 구간이었으면(새 주문 푸시가 마감을 실었다) 보내지 않는다. */ +export function isConfirmReminderDue( + state: ConfirmReminderState, + now: Date, +): boolean { + const { confirmDeadlineAt: deadline, submittedAt } = state; + if ( + state.status !== OrderStatus.SUBMITTED || + state.confirmReminderSentAt !== null || + !deadline || + !submittedAt + ) { + return false; + } + const remindAt = deadline.getTime() - CONFIRM_REMINDER_LEAD_MS; + return ( + remindAt <= now.getTime() && + now < deadline && + remindAt > submittedAt.getTime() + ); +} 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..1a4fc333 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,215 @@ -import { OrderStatusTransitionPolicy } from '@/features/order/policies/order-status-transition.policy'; -import { OrderStatus } from '@/generated/prisma/client'; +import { HOUR_MS } from '@/common/utils/kst-time'; +import { OrderCancelPolicy } from '@/features/order/policies/order-cancel.policy'; +import { + autoPickupAt, + isInNoShowWindow, + OrderStatusTransitionPolicy, +} from '@/features/order/policies/order-status-transition.policy'; +import { OrderActor, OrderStatus } from '@/generated/prisma/client'; + +const STATUSES = Object.values(OrderStatus); +const ACTORS = Object.values(OrderActor); + +const PICKUP_AT = new Date('2026-11-20T05:00:00.000Z'); +const IN_NO_SHOW_WINDOW = new Date(PICKUP_AT.getTime() + HOUR_MS); +const AFTER_AUTO_PICKUP = autoPickupAt(PICKUP_AT); + +/** 허용 전이 정본(actor:from>to). 이 밖은 전부 거절이다(기본 거절). */ +const ALLOWED = new Set([ + 'ADMIN:PENDING_PAYMENT>SUBMITTED', + 'BUYER:PENDING_PAYMENT>CANCELED', + 'ADMIN:PENDING_PAYMENT>CANCELED', + 'SYSTEM:PENDING_PAYMENT>CANCELED', + 'SELLER:SUBMITTED>CONFIRMED', + 'BUYER:SUBMITTED>CANCELED', + 'SELLER:SUBMITTED>CANCELED', + 'ADMIN:SUBMITTED>CANCELED', + 'SYSTEM:SUBMITTED>CANCELED', + 'SELLER:CONFIRMED>MADE', + 'SELLER:CONFIRMED>PICKED_UP', + 'ADMIN:CONFIRMED>PICKED_UP', + 'SYSTEM:CONFIRMED>PICKED_UP', + 'SELLER:CONFIRMED>NO_SHOW', + 'SELLER:CONFIRMED>CANCELED', + 'ADMIN:CONFIRMED>CANCELED', + 'SELLER:MADE>PICKED_UP', + 'ADMIN:MADE>PICKED_UP', + 'SYSTEM:MADE>PICKED_UP', + 'SELLER:MADE>NO_SHOW', + 'SELLER:MADE>CANCELED', + 'ADMIN:MADE>CANCELED', +]); + +function expectedCode( + actor: OrderActor, + from: OrderStatus, + to: OrderStatus, +): string | null { + if (from === to) return 'ORDER_STATUS_UNCHANGED'; + if (ALLOWED.has(`${actor}:${from}>${to}`)) return null; + return 'INVALID_ORDER_STATUS_TRANSITION'; +} + +/** 시각 조건이 있는 전이는 그 조건을 채우는 시각으로 표를 본다(경계는 아래 describe). */ +function nowFor(actor: OrderActor, to: OrderStatus): Date { + return to === OrderStatus.PICKED_UP && actor === OrderActor.SYSTEM + ? AFTER_AUTO_PICKUP + : IN_NO_SHOW_WINDOW; +} 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, + describe('assertTransition 전수(주체 4 × from 7 × to 7)', () => { + const cases = ACTORS.flatMap((actor) => + STATUSES.flatMap((from) => + STATUSES.map( + (to) => [actor, from, to, expectedCode(actor, from, to)] as const, ), - ).toThrowDomain(400); - }); + ), + ); - it('CONFIRMED는 SUBMITTED에서만 가능', () => { - expect(() => - policy.assertSellerTransition( - OrderStatus.SUBMITTED, - OrderStatus.CONFIRMED, - ), - ).not.toThrow(); - expect(() => - policy.assertSellerTransition(OrderStatus.MADE, OrderStatus.CONFIRMED), - ).toThrowDomain(400); + it('표는 196 조합을 덮고 허용 전이는 22개다(종료 상태에서 나가는 전이는 없다)', () => { + expect(cases).toHaveLength(4 * 7 * 7); + expect(cases.filter(([, , , code]) => code === null)).toHaveLength(22); + for (const terminal of ['PICKED_UP', 'NO_SHOW', 'CANCELED']) { + expect( + cases.filter(([, from, , code]) => from === terminal && !code), + ).toHaveLength(0); + } }); - it('MADE는 CONFIRMED에서만 가능', () => { - expect(() => - policy.assertSellerTransition(OrderStatus.CONFIRMED, OrderStatus.MADE), - ).not.toThrow(); - expect(() => - policy.assertSellerTransition(OrderStatus.SUBMITTED, OrderStatus.MADE), - ).toThrowDomain(400); + it.each(cases)('%s: %s → %s = %s', (actor, from, to, code) => { + const request = { + actor, + from, + to, + now: nowFor(actor, to), + pickupAt: PICKUP_AT, + }; + expect(policy.canTransition(request)).toBe(code === null); + const run = () => policy.assertTransition(request); + if (code === null) expect(run).not.toThrow(); + else expect(run).toThrowDomain(code); }); - 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.each( + ACTORS.flatMap((actor) => STATUSES.map((s) => [actor, s] as const)), + )('%s의 %s 취소 허용은 OrderCancelPolicy와 같다', (actor, status) => { + const allowed = policy.canTransition({ + actor, + from: status, + to: OrderStatus.CANCELED, + now: IN_NO_SHOW_WINDOW, + pickupAt: PICKUP_AT, + }); + expect(allowed).toBe(new OrderCancelPolicy().canCancel(actor, status)); }); + }); - 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); + describe('노쇼 구간(pickupAt ≤ now < pickupAt + 24h)', () => { + const at = (offsetMs: number) => new Date(PICKUP_AT.getTime() + offsetMs); + + it.each([ + ['pickupAt − 1ms', at(-1), false], + ['pickupAt', at(0), true], + ['pickupAt + 24h − 1ms', at(24 * HOUR_MS - 1), true], + ['pickupAt + 24h', at(24 * HOUR_MS), false], + ])('%s: 허용 %s', (_label, now, allowed) => { + expect(isInNoShowWindow(PICKUP_AT, now)).toBe(allowed); + for (const from of [OrderStatus.CONFIRMED, OrderStatus.MADE]) { + const run = () => + policy.assertTransition({ + actor: OrderActor.SELLER, + from, + to: OrderStatus.NO_SHOW, + now, + pickupAt: PICKUP_AT, + }); + if (allowed) expect(run).not.toThrow(); + else expect(run).toThrowDomain('NO_SHOW_NOT_ALLOWED'); + } }); + }); - // SUBMITTED는 주문 생성 시점의 초기 상태라 어떤 상태에서도 되돌아갈 수 없다 — 가드가 빠지면 역전이가 조용히 통과되므로 모든 from을 전수 검증한다. + describe('픽업 완료 시각 조건은 시스템만 pickupAt + 24h부터', () => { it.each([ - OrderStatus.CONFIRMED, - OrderStatus.MADE, - OrderStatus.PICKED_UP, - OrderStatus.CANCELED, - ])('SUBMITTED로 되돌리는 역전이는 거부 (from=%s)', (from) => { - expect(() => - policy.assertSellerTransition(from, OrderStatus.SUBMITTED), - ).toThrowDomain(400); + [-1, false], + [0, true], + ])('pickupAt + 24h %+dms: 허용 %s', (offset, allowed) => { + const request = { + actor: OrderActor.SYSTEM, + from: OrderStatus.MADE, + to: OrderStatus.PICKED_UP, + now: new Date(AFTER_AUTO_PICKUP.getTime() + offset), + pickupAt: PICKUP_AT, + }; + expect(policy.canTransition(request)).toBe(allowed); }); + + it.each([OrderActor.SELLER, OrderActor.ADMIN])( + '%s 픽업 완료에는 시각 조건이 없다(픽업 시각 전에도 된다)', + (actor) => { + for (const from of [OrderStatus.CONFIRMED, OrderStatus.MADE]) { + expect( + policy.canTransition({ + actor, + from, + to: OrderStatus.PICKED_UP, + now: new Date(PICKUP_AT.getTime() - HOUR_MS), + pickupAt: PICKUP_AT, + }), + ).toBe(true); + } + }, + ); }); - 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); + describe('픽업 일시 변경', () => { + const changed = new Date(PICKUP_AT.getTime() + HOUR_MS); + + it.each( + STATUSES.map( + (status) => + [ + status, + ['SUBMITTED', 'CONFIRMED', 'MADE'].includes(status) + ? null + : 'PICKUP_RESCHEDULE_NOT_ALLOWED', + ] as const, + ), + )('%s: %s', (status, code) => { + const run = () => + policy.assertPickupChange({ + status, + fromPickupAt: PICKUP_AT, + toPickupAt: changed, + }); + if (code === null) expect(run).not.toThrow(); + else expect(run).toThrowDomain(code); + }); + + it('같은 일시면 PICKUP_UNCHANGED', () => { + expect(() => + policy.assertPickupChange({ + status: OrderStatus.CONFIRMED, + fromPickupAt: PICKUP_AT, + toPickupAt: new Date(PICKUP_AT.getTime()), + }), + ).toThrowDomain('PICKUP_UNCHANGED'); }); }); }); diff --git a/src/features/order/policies/order-status-transition.policy.ts b/src/features/order/policies/order-status-transition.policy.ts index 0a0fcb8b..b4aff268 100644 --- a/src/features/order/policies/order-status-transition.policy.ts +++ b/src/features/order/policies/order-status-transition.policy.ts @@ -1,53 +1,117 @@ import { Injectable } from '@nestjs/common'; -import { DomainException } from '@/common/errors/error-catalog'; -import { OrderStatus } from '@/generated/prisma/client'; +import { DomainException, type ErrorCode } from '@/common/errors/error-catalog'; +import { DAY_MS } from '@/common/utils/kst-time'; +import { OrderActor, OrderStatus } from '@/generated/prisma/client'; + +const ORDER_STATUS_VALUES: readonly string[] = Object.values(OrderStatus); + +const { BUYER, SELLER, ADMIN, SYSTEM } = OrderActor; + +/** + * from → to → 그 전이를 할 수 있는 주체. 표에 없는 조합은 거절한다(기본 거절) — 새 상태가 조용히 열리지 않게. + * 취소의 사유·사정·환불액은 OrderCancelPolicy가 따로 판정한다. + */ +const TRANSITIONS: Partial< + Record>> +> = { + PENDING_PAYMENT: { SUBMITTED: [ADMIN], CANCELED: [BUYER, ADMIN, SYSTEM] }, + SUBMITTED: { CONFIRMED: [SELLER], CANCELED: [BUYER, SELLER, ADMIN, SYSTEM] }, + CONFIRMED: { + MADE: [SELLER], + PICKED_UP: [SELLER, ADMIN, SYSTEM], + NO_SHOW: [SELLER], + CANCELED: [SELLER, ADMIN], + }, + MADE: { + PICKED_UP: [SELLER, ADMIN, SYSTEM], + NO_SHOW: [SELLER], + CANCELED: [SELLER, ADMIN], + }, +}; + +/** 판매자가 픽업 일시를 바꿀 수 있는 상태. */ +const PICKUP_RESCHEDULABLE: readonly OrderStatus[] = [ + OrderStatus.SUBMITTED, + OrderStatus.CONFIRMED, + OrderStatus.MADE, +]; + +/** 픽업 시각에서 이만큼 지나면 자동 픽업 완료되고, 노쇼는 그 전까지만 처리할 수 있다. */ +export const AUTO_PICKUP_DELAY_MS = DAY_MS; + +export interface OrderTransitionRequest { + actor: OrderActor; + from: OrderStatus; + to: OrderStatus; + now: Date; + pickupAt: Date; +} + +export function autoPickupAt(pickupAt: Date): Date { + return new Date(pickupAt.getTime() + AUTO_PICKUP_DELAY_MS); +} + +/** 노쇼 처리 구간: 픽업 시각 ≤ now < 자동 픽업 완료 시각. */ +export function isInNoShowWindow(pickupAt: Date, now: Date): boolean { + return pickupAt <= now && now < autoPickupAt(pickupAt); +} + +function violationOf({ + actor, + from, + to, + now, + pickupAt, +}: OrderTransitionRequest): ErrorCode | null { + if (from === to) return 'ORDER_STATUS_UNCHANGED'; + if (!TRANSITIONS[from]?.[to]?.includes(actor)) { + return 'INVALID_ORDER_STATUS_TRANSITION'; + } + if (to === OrderStatus.NO_SHOW && !isInNoShowWindow(pickupAt, now)) { + return 'NO_SHOW_NOT_ALLOWED'; + } + if ( + to === OrderStatus.PICKED_UP && + actor === SYSTEM && + now < autoPickupAt(pickupAt) + ) { + return 'INVALID_ORDER_STATUS_TRANSITION'; + } + return null; +} @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'); } - assertSellerTransition(from: OrderStatus, to: OrderStatus): void { - 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'); - } + /** 주체·상태·시각만 본다. 잠금 뒤 상태로 다시 부른다. */ + assertTransition(request: OrderTransitionRequest): void { + const code = violationOf(request); + if (code) throw new DomainException(code); + } - if (to === OrderStatus.PICKED_UP && from !== OrderStatus.MADE) { - throw new DomainException('INVALID_ORDER_STATUS_TRANSITION'); - } + canTransition(request: OrderTransitionRequest): boolean { + return violationOf(request) === null; + } - if (to === OrderStatus.CANCELED) { - const cancellable = - from === OrderStatus.SUBMITTED || - from === OrderStatus.CONFIRMED || - from === OrderStatus.MADE; - if (!cancellable) { - throw new DomainException('ORDER_NOT_CANCELLABLE'); - } + assertPickupReschedulable(status: OrderStatus): void { + if (!PICKUP_RESCHEDULABLE.includes(status)) { + throw new DomainException('PICKUP_RESCHEDULE_NOT_ALLOWED'); } } - requiresCancellationNote(to: OrderStatus): boolean { - return to === OrderStatus.CANCELED; + assertPickupChange(args: { + status: OrderStatus; + fromPickupAt: Date; + toPickupAt: Date; + }): void { + this.assertPickupReschedulable(args.status); + if (args.fromPickupAt.getTime() === args.toPickupAt.getTime()) { + throw new DomainException('PICKUP_UNCHANGED'); + } } } 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/account-number-reencrypt.repository.spec.ts b/src/features/order/repositories/account-number-reencrypt.repository.spec.ts new file mode 100644 index 00000000..b4a7f805 --- /dev/null +++ b/src/features/order/repositories/account-number-reencrypt.repository.spec.ts @@ -0,0 +1,174 @@ +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); + + // 재암호화가 updated_at을 건드리는지 가리려고 과거 시각으로 만든다 + const PAST = new Date('2026-01-01T00:00:00.000Z'); + + /** 세 칼럼에 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, + updated_at: PAST, + }, + }); + 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', + updated_at: PAST, + }, + }); + 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', + ), + updated_at: PAST, + }, + }); + 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 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'); + 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('읽은 뒤 다른 요청이 바꾼 행은 건너뛰어 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({ + 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..a2b11d4e --- /dev/null +++ b/src/features/order/repositories/account-number-reencrypt.repository.ts @@ -0,0 +1,145 @@ +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; + updatedAt: Date; +} + +/** + * 키 회전용(`yarn accounts:reencrypt`). 첫 키가 아닌 키로 암호화된 계좌번호를 첫 키로 다시 암호화한다. + * 행마다 읽은 토큰·updated_at이 그대로일 때만 바꿔, 그사이 바뀐 행(새로 입력한 계좌 등)을 덮지 않는다. + * updated_at은 읽은 값으로 다시 써서 화면의 '마지막 변경 시각'이 키 회전으로 움직이지 않게 한다. + */ +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, + 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, + 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, + updated_at: row.updatedAt, + }, + data: { + paid_account_number_enc: this.rotate(row.token, 'settlement-account'), + updated_at: row.updatedAt, + }, + }); + 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, updated_at: true }, + orderBy: { id: 'asc' }, + }), + this.prisma.storeSettlementAccount.findMany({ + 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, updated_at: true }, + orderBy: { id: 'asc' }, + }), + ]); + 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, + updatedAt: r.updated_at, + })), + ), + storeSettlementAccount: stale( + 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, + })), + ), + }; + } +} diff --git a/src/features/order/repositories/deposit-record.repository.ts b/src/features/order/repositories/deposit-record.repository.ts new file mode 100644 index 00000000..ae144c48 --- /dev/null +++ b/src/features/order/repositories/deposit-record.repository.ts @@ -0,0 +1,230 @@ +import { Inject, Injectable } from '@nestjs/common'; + +import type { TimestampIdCursor } from '@/common/utils/keyset-cursor'; +import { + AUDIT_LOG_REPOSITORY, + type IAuditLogRepository, +} from '@/features/audit-log'; +import { refundRequestedEvent } from '@/features/order/events/refund-requested.event'; +import { + adminDepositRecordInclude, + type AdminDepositRecordRow, + loadRefundEventArgs, +} from '@/features/order/repositories/refund.repository'; +import { OutboxPublisher } from '@/features/outbox'; +import { + AuditActionType, + AuditTargetType, + type DepositRecord, + DepositRecordKind, + type Prisma, + RefundKind, +} from '@/generated/prisma/client'; +import { PrismaService } from '@/prisma'; + +export interface DepositRecordInput { + amount: number; + depositorName: string; + depositedAt: Date | null; + note: string | null; + actorAccountId: bigint; + actorLabel: string | null; + now: Date; +} + +export type LinkDepositRecordResult = + | AdminDepositRecordRow + | 'order-not-found' + | 'record-not-found' + | 'already-linked'; + +function recordSnapshot(row: DepositRecord) { + return { + kind: row.kind, + orderId: row.order_id?.toString() ?? null, + amount: row.amount, + depositorName: row.depositor_name, + depositedAt: row.deposited_at?.toISOString() ?? null, + note: row.note, + }; +} + +/** + * 결제로 확인하지 않은 입금 기록. 돌려줄 입금(RETURN)은 주문에 연결하고 입금액 전액 환불을 만든다 — 주문 상태·결제·정산은 + * 건드리지 않는다. 주인 모를 입금(UNIDENTIFIED)은 메모로 종결하고, 나중에 주인을 찾으면 같은 기록을 반환으로 바꾼다. + */ +@Injectable() +export class DepositRecordRepository { + constructor( + private readonly prisma: PrismaService, + private readonly outbox: OutboxPublisher, + @Inject(AUDIT_LOG_REPOSITORY) + private readonly auditLogs: IAuditLogRepository, + ) {} + + /** 최근 기록부터. */ + async listDepositRecords(args: { + kind?: DepositRecordKind; + limit: number; + cursor?: TimestampIdCursor; + }): Promise { + const after: Prisma.DepositRecordWhereInput = args.cursor + ? { + OR: [ + { created_at: { lt: args.cursor.timestamp } }, + { created_at: args.cursor.timestamp, id: { lt: args.cursor.id } }, + ], + } + : {}; + return this.prisma.depositRecord.findMany({ + where: { ...(args.kind ? { kind: args.kind } : {}), ...after }, + include: adminDepositRecordInclude, + orderBy: [{ created_at: 'desc' }, { id: 'desc' }], + take: args.limit + 1, + }); + } + + async countDepositRecords(kind?: DepositRecordKind): Promise { + return this.prisma.depositRecord.count({ + where: kind ? { kind } : {}, + }); + } + + /** 없는 주문이면 null. */ + async createReturn( + args: DepositRecordInput & { orderId: bigint }, + ): Promise { + return this.prisma.$transaction(async (tx) => { + if (!(await this.lockOrder(tx, args.orderId))) return null; + const record = await tx.depositRecord.create({ + data: { + ...this.recordData(args), + kind: DepositRecordKind.RETURN, + order_id: args.orderId, + }, + }); + await this.requestReturnRefund(tx, record, args); + await this.audit(tx, args.actorAccountId, record, null); + return this.findAdminRow(tx, record.id); + }); + } + + async recordUnidentified( + args: DepositRecordInput, + ): Promise { + return this.prisma.$transaction(async (tx) => { + const record = await tx.depositRecord.create({ + data: { + ...this.recordData(args), + kind: DepositRecordKind.UNIDENTIFIED, + }, + }); + await this.audit(tx, args.actorAccountId, record, null); + return this.findAdminRow(tx, record.id); + }); + } + + /** 종결한 입금의 주인을 찾았을 때: 같은 기록을 반환으로 바꿔 주문에 잇는다(같은 돈을 두 번 기록하지 않는다). */ + async linkToOrder(args: { + depositRecordId: bigint; + orderId: bigint; + actorAccountId: bigint; + now: Date; + }): Promise { + return this.prisma.$transaction(async (tx) => { + // 잠금 순서 order → deposit_record + if (!(await this.lockOrder(tx, args.orderId))) return 'order-not-found'; + const [locked] = await tx.$queryRaw<{ id: bigint }[]>` + SELECT id FROM deposit_record WHERE id = ${args.depositRecordId} FOR UPDATE`; + if (!locked) return 'record-not-found'; + const before = await tx.depositRecord.findUniqueOrThrow({ + where: { id: locked.id }, + }); + if (before.kind !== DepositRecordKind.UNIDENTIFIED) { + return 'already-linked'; + } + const record = await tx.depositRecord.update({ + where: { id: before.id }, + data: { kind: DepositRecordKind.RETURN, order_id: args.orderId }, + }); + await this.requestReturnRefund(tx, record, args); + await this.audit(tx, args.actorAccountId, record, before); + return this.findAdminRow(tx, record.id); + }); + } + + private async lockOrder( + tx: Prisma.TransactionClient, + orderId: bigint, + ): Promise { + const [row] = await tx.$queryRaw<{ id: bigint }[]>` + SELECT id FROM \`order\` WHERE id = ${orderId} AND deleted_at IS NULL FOR UPDATE`; + return Boolean(row); + } + + private recordData(args: DepositRecordInput) { + return { + amount: args.amount, + depositor_name: args.depositorName, + deposited_at: args.depositedAt, + note: args.note, + recorded_by_account_id: args.actorAccountId, + recorded_by_label_snapshot: args.actorLabel, + }; + } + + /** 입금액 전액을 계좌 입력 대기 환불로 만들고 구매자 계좌 요청 이벤트를 남긴다. */ + private async requestReturnRefund( + tx: Prisma.TransactionClient, + record: DepositRecord, + args: { actorAccountId: bigint; now: Date }, + ): Promise { + const refund = await tx.refund.create({ + data: { + order_id: record.order_id!, + kind: RefundKind.DEPOSIT_RETURN, + deposit_record_id: record.id, + amount: record.amount, + requested_at: args.now, + }, + }); + await this.outbox.publish( + tx, + refundRequestedEvent({ + ...(await loadRefundEventArgs( + tx, + refund, + args.now, + args.actorAccountId, + )), + accountSubmitted: false, + }), + ); + } + + private async audit( + tx: Prisma.TransactionClient, + actorAccountId: bigint, + after: DepositRecord, + before: DepositRecord | null, + ): Promise { + await this.auditLogs.recordAudit(tx, { + actorAccountId, + targetType: AuditTargetType.DEPOSIT_RECORD, + targetId: after.id, + action: before ? AuditActionType.UPDATE : AuditActionType.CREATE, + beforeJson: before ? recordSnapshot(before) : null, + afterJson: recordSnapshot(after), + }); + } + + private findAdminRow( + tx: Prisma.TransactionClient, + id: bigint, + ): Promise { + return tx.depositRecord.findUniqueOrThrow({ + where: { id }, + include: adminDepositRecordInclude, + }); + } +} diff --git a/src/features/order/repositories/order-capacity.helper.ts b/src/features/order/repositories/order-capacity.helper.ts new file mode 100644 index 00000000..274ccf6d --- /dev/null +++ b/src/features/order/repositories/order-capacity.helper.ts @@ -0,0 +1,49 @@ +import { Prisma } from '@/generated/prisma/client'; + +/** 트랜잭션 안에서 capacity 행을 잠그고 점유를 재집계해 검사-삽입 race로 capacity가 초과되는 것을 막는다. */ +export interface DailyCapacityGuard { + storeId: bigint; + dateOnlyUtc: Date; + dayStartUtc: Date; + dayEndUtc: Date; +} + +/** + * capacity는 order 소유 복제본(order_store_daily_limit)에서 읽는다 — catalog 행을 잠그지 않는다. + * 복제본이 없거나 capacity가 비어 있으면(tombstone) 무제한: 설정 직후 복제 지연 구간에는 제한 없이 받는다. + * forUpdate는 READ COMMITTED tx에서만 같은 매장·날짜의 동시 주문 생성·픽업 변경을 직렬화한다(REPEATABLE READ면 재집계가 잠금 전 스냅샷을 읽는다). + * excludeOrderId는 픽업을 옮기는 주문 자신의 점유를 뺀다. + */ +export async function isDailyCapacityExceeded( + db: Prisma.TransactionClient, + guard: DailyCapacityGuard, + quantity: number, + options: { forUpdate: boolean; excludeOrderId?: bigint }, +): Promise { + const capacityRows = await db.$queryRaw<{ capacity: number }[]>(Prisma.sql` + SELECT capacity + FROM order_store_daily_limit + WHERE store_id = ${guard.storeId} + AND booking_date = ${guard.dateOnlyUtc} + AND capacity IS NOT NULL + ${options.forUpdate ? Prisma.sql`FOR UPDATE` : Prisma.empty} + `); + const capacity = capacityRows[0]?.capacity; + if (capacity === undefined) return false; + + const bookedRows = await db.$queryRaw<{ booked: bigint }[]>(Prisma.sql` + SELECT CAST(COALESCE(SUM(oi.quantity), 0) AS UNSIGNED) AS booked + FROM order_item oi + JOIN \`order\` o + ON o.id = oi.order_id + AND o.deleted_at IS NULL + AND o.status <> 'CANCELED' + AND o.pickup_at >= ${guard.dayStartUtc} + AND o.pickup_at < ${guard.dayEndUtc} + ${options.excludeOrderId !== undefined ? Prisma.sql`AND o.id <> ${options.excludeOrderId}` : Prisma.empty} + WHERE oi.store_id = ${guard.storeId} + AND oi.deleted_at IS NULL + `); + const booked = Number(bookedRows[0]?.booked ?? 0); + return booked + quantity > capacity; +} 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-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-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/repositories/order-inquiry.repository.spec.ts b/src/features/order/repositories/order-inquiry.repository.spec.ts new file mode 100644 index 00000000..6d509b92 --- /dev/null +++ b/src/features/order/repositories/order-inquiry.repository.spec.ts @@ -0,0 +1,192 @@ +import { OrderInquiryRepository } from '@/features/order/repositories/order-inquiry.repository'; +import type { OrderStatus, PrismaClient } from '@/generated/prisma/client'; +import { disconnectTestPrismaClient } from '@/test/db/prisma-test-client'; +import { closeTruncateConnection, truncateAll } from '@/test/db/truncate'; +import { + createAccount, + createOrder, + createOrderItem, + createStore, +} from '@/test/factories'; +import { createTestingModuleWithRealDb } from '@/test/modules/testing-module.builder'; + +describe('OrderInquiryRepository (real DB)', () => { + let repo: OrderInquiryRepository; + let prisma: PrismaClient; + + beforeAll(async () => { + const { module, prisma: p } = await createTestingModuleWithRealDb({ + providers: [OrderInquiryRepository], + }); + repo = module.get(OrderInquiryRepository); + prisma = p; + }); + afterAll(async () => { + await closeTruncateConnection(); + await disconnectTestPrismaClient(); + }); + beforeEach(async () => { + await truncateAll(); + }); + + async function buyer() { + return createAccount(prisma, { account_type: 'USER' }); + } + + describe('findOrderCardSource', () => { + it.each([ + [ + '커스텀 대표 이미지 우선', + 'https://cdn.example.com/custom.jpg', + 'https://cdn.example.com/product.jpg', + 'https://cdn.example.com/custom.jpg', + ], + [ + '없으면 상품 대표 이미지', + null, + 'https://cdn.example.com/product.jpg', + 'https://cdn.example.com/product.jpg', + ], + ['둘 다 없으면 null', null, null, null], + ])('썸네일: %s', async (_label, custom, product, expected) => { + const account = await buyer(); + const store = await createStore(prisma); + const order = await createOrder(prisma, { account_id: account.id }); + await createOrderItem(prisma, { + order_id: order.id, + store_id: store.id, + product_name_snapshot: '딸기 케이크', + custom_preview_image_url: custom, + product_thumbnail_url_snapshot: product, + }); + + expect( + await repo.findOrderCardSource({ + orderId: order.id, + accountId: account.id, + }), + ).toEqual({ + orderId: order.id, + orderNumber: order.order_number, + storeId: store.id, + productName: '딸기 케이크', + thumbnailUrl: expected, + pickupAt: order.pickup_at, + submittedAt: order.submitted_at, + }); + }); + + it('삭제된 품목은 건너뛰고 남은 첫 품목을 쓴다', async () => { + const account = await buyer(); + const order = await createOrder(prisma, { account_id: account.id }); + await createOrderItem(prisma, { + order_id: order.id, + product_name_snapshot: '지운 품목', + deleted_at: new Date(), + }); + await createOrderItem(prisma, { + order_id: order.id, + product_name_snapshot: '남은 품목', + }); + + const source = await repo.findOrderCardSource({ + orderId: order.id, + accountId: account.id, + }); + expect(source?.productName).toBe('남은 품목'); + }); + + it('남의 주문·삭제된 주문·품목이 모두 지워진 주문은 null', async () => { + const account = await buyer(); + const others = await createOrder(prisma); + await createOrderItem(prisma, { order_id: others.id }); + const deleted = await createOrder(prisma, { + account_id: account.id, + deleted_at: new Date(), + }); + await createOrderItem(prisma, { order_id: deleted.id }); + const emptied = await createOrder(prisma, { account_id: account.id }); + await createOrderItem(prisma, { + order_id: emptied.id, + deleted_at: new Date(), + }); + + for (const order of [others, deleted, emptied]) { + expect( + await repo.findOrderCardSource({ + orderId: order.id, + accountId: account.id, + }), + ).toBeNull(); + } + }); + }); + + describe('existsInProgressOrderAtStore', () => { + it.each([ + ['PENDING_PAYMENT', true], + ['SUBMITTED', true], + ['CONFIRMED', true], + ['MADE', true], + ['PICKED_UP', false], + ['NO_SHOW', false], + ['CANCELED', false], + ] as [OrderStatus, boolean][])('%s 주문 → %s', async (status, expected) => { + const account = await buyer(); + const store = await createStore(prisma); + const order = await createOrder(prisma, { + account_id: account.id, + status, + }); + await createOrderItem(prisma, { order_id: order.id, store_id: store.id }); + + expect( + await repo.existsInProgressOrderAtStore({ + accountId: account.id, + storeId: store.id, + }), + ).toBe(expected); + }); + + it('다른 구매자·다른 매장·삭제된 주문·삭제된 품목은 세지 않는다', async () => { + const account = await buyer(); + const store = await createStore(prisma); + const elsewhere = await createStore(prisma); + const othersOrder = await createOrder(prisma); + await createOrderItem(prisma, { + order_id: othersOrder.id, + store_id: store.id, + }); + const elsewhereOrder = await createOrder(prisma, { + account_id: account.id, + }); + await createOrderItem(prisma, { + order_id: elsewhereOrder.id, + store_id: elsewhere.id, + }); + const deletedOrder = await createOrder(prisma, { + account_id: account.id, + deleted_at: new Date(), + }); + await createOrderItem(prisma, { + order_id: deletedOrder.id, + store_id: store.id, + }); + const deletedItemOrder = await createOrder(prisma, { + account_id: account.id, + }); + await createOrderItem(prisma, { + order_id: deletedItemOrder.id, + store_id: store.id, + deleted_at: new Date(), + }); + + expect( + await repo.existsInProgressOrderAtStore({ + accountId: account.id, + storeId: store.id, + }), + ).toBe(false); + }); + }); +}); diff --git a/src/features/order/repositories/order-inquiry.repository.ts b/src/features/order/repositories/order-inquiry.repository.ts new file mode 100644 index 00000000..3cef7636 --- /dev/null +++ b/src/features/order/repositories/order-inquiry.repository.ts @@ -0,0 +1,75 @@ +import { Injectable } from '@nestjs/common'; + +import { IN_PROGRESS_ORDER_STATUSES } from '@/features/order/constants/order-status-traits'; +import { activeWhere, PrismaService } from '@/prisma'; + +export interface OrderCardSource { + orderId: bigint; + orderNumber: string; + storeId: bigint; + productName: string; + thumbnailUrl: string | null; + pickupAt: Date; + /** 입금 확인(판매자 노출) 시각. null이면 판매자가 볼 수 없는 주문이다 */ + submittedAt: Date | null; +} + +/** 채팅(conversation)이 묻는 구매자 주문 읽기. */ +@Injectable() +export class OrderInquiryRepository { + constructor(private readonly prisma: PrismaService) {} + + /** 본인 주문의 카드 원천. 주문 1건 = 상품 1개라 첫 품목이 상품·매장을 대표한다. */ + async findOrderCardSource(args: { + orderId: bigint; + accountId: bigint; + }): Promise { + const order = await this.prisma.order.findFirst({ + where: { id: args.orderId, account_id: args.accountId }, + select: { + id: true, + order_number: true, + pickup_at: true, + submitted_at: true, + items: { + where: activeWhere, + orderBy: { id: 'asc' }, + take: 1, + select: { + store_id: true, + product_name_snapshot: true, + product_thumbnail_url_snapshot: true, + custom_preview_image_url: true, + }, + }, + }, + }); + const item = order?.items[0]; + if (!order || !item) return null; + return { + orderId: order.id, + orderNumber: order.order_number, + storeId: item.store_id, + productName: item.product_name_snapshot, + thumbnailUrl: + item.custom_preview_image_url ?? item.product_thumbnail_url_snapshot, + pickupAt: order.pickup_at, + submittedAt: order.submitted_at, + }; + } + + async existsInProgressOrderAtStore(args: { + accountId: bigint; + storeId: bigint; + }): Promise { + const found = await this.prisma.order.findFirst({ + where: { + account_id: args.accountId, + status: { in: [...IN_PROGRESS_ORDER_STATUSES] }, + items: { some: { store_id: args.storeId, ...activeWhere } }, + }, + select: { id: true }, + }); + return found !== null; + } +} diff --git a/src/features/order/repositories/order-lifecycle.repository.ts b/src/features/order/repositories/order-lifecycle.repository.ts new file mode 100644 index 00000000..f824b5f9 --- /dev/null +++ b/src/features/order/repositories/order-lifecycle.repository.ts @@ -0,0 +1,180 @@ +import { Injectable } from '@nestjs/common'; + +import { orderConfirmReminderDueEvent } from '@/features/order/events/order-confirm-reminder-due.event'; +import { + CONFIRM_REMINDER_LEAD_MS, + type ConfirmReminderState, +} from '@/features/order/policies/order-lifecycle.policy'; +import { AUTO_PICKUP_DELAY_MS } from '@/features/order/policies/order-status-transition.policy'; +import { OutboxPublisher } from '@/features/outbox'; +import { OrderStatus, PaymentStatus, Prisma } from '@/generated/prisma/client'; +import { activeWhere, PrismaService } from '@/prisma'; + +/** 키셋 한 페이지(id 오름차순). afterId 다음부터 limit건. */ +export interface CandidatePage { + now: Date; + afterId?: bigint; + limit: number; +} + +function afterIdWhere(page: CandidatePage) { + return page.afterId !== undefined ? { id: { gt: page.afterId } } : {}; +} + +function keysetPage(page: CandidatePage) { + return { + select: { id: true }, + orderBy: { id: 'asc' as const }, + take: page.limit, + }; +} + +/** + * 자동 전이 크론의 대상 고르기와 미리 알림 기록. 전이 자체는 OrderTransitionRepository가 건마다 잠근 뒤 다시 판정한다 — + * 여기 조건은 후보를 좁히는 용도라 잠금 없이 읽는다. + */ +@Injectable() +export class OrderLifecycleRepository { + constructor( + private readonly prisma: PrismaService, + private readonly outbox: OutboxPublisher, + ) {} + + /** 입금 기한이 지났고 '입금했어요'를 누르지 않은 입금 대기. */ + async findPaymentExpiredIds(page: CandidatePage): Promise { + const rows = await this.prisma.order.findMany({ + where: { + status: OrderStatus.PENDING_PAYMENT, + payment: { + status: PaymentStatus.PENDING, + buyer_claimed_at: null, + expires_at: { lte: page.now }, + }, + ...afterIdWhere(page), + }, + ...keysetPage(page), + }); + return rows.map((row) => row.id); + } + + /** 확정 마감이 지난 접수. 결제 도입 전 접수는 마감이 없어 빠진다. */ + async findConfirmTimedOutIds(page: CandidatePage): Promise { + const rows = await this.prisma.order.findMany({ + where: { + status: OrderStatus.SUBMITTED, + confirm_deadline_at: { lte: page.now }, + ...afterIdWhere(page), + }, + ...keysetPage(page), + }); + return rows.map((row) => row.id); + } + + /** 픽업 + 24시간이 지난 확정·제작 완료. 숨긴 매장의 주문은 관리자가 건별로 처리하므로 뺀다. */ + async findAutoPickupIds( + page: CandidatePage & { excludeStoreIds: bigint[] }, + ): Promise { + const rows = await this.prisma.order.findMany({ + where: { + status: { in: [OrderStatus.CONFIRMED, OrderStatus.MADE] }, + pickup_at: { + lte: new Date(page.now.getTime() - AUTO_PICKUP_DELAY_MS), + }, + ...(page.excludeStoreIds.length > 0 + ? { + items: { + none: { + store_id: { in: page.excludeStoreIds }, + ...activeWhere, + }, + }, + } + : {}), + ...afterIdWhere(page), + }, + ...keysetPage(page), + }); + return rows.map((row) => row.id); + } + + /** 마감 2시간 전 구간의 미발송 접수. 접수 시점 조건은 열 비교라 raw다. */ + async findConfirmReminderDueIds(page: CandidatePage): Promise { + const remindBefore = new Date( + page.now.getTime() + CONFIRM_REMINDER_LEAD_MS, + ); + const rows = await this.prisma.$queryRaw<{ id: bigint }[]>` + SELECT o.id FROM \`order\` o + WHERE o.status = 'SUBMITTED' + AND o.deleted_at IS NULL + AND o.confirm_reminder_sent_at IS NULL + AND o.confirm_deadline_at > ${page.now} + AND o.confirm_deadline_at <= ${remindBefore} + AND o.confirm_deadline_at - INTERVAL ${CONFIRM_REMINDER_LEAD_MS / 1000} SECOND > o.submitted_at + ${page.afterId !== undefined ? Prisma.sql`AND o.id > ${page.afterId}` : Prisma.empty} + ORDER BY o.id + LIMIT ${page.limit}`; + return rows.map((row) => row.id); + } + + /** + * 미리 알림 1회: 잠금 뒤 isDue로 다시 판정하고 발송 표시와 판매자 푸시 이벤트를 같은 tx에 남긴다. + * 대상이 아니게 됐으면(확정·취소·이미 발송) false. + */ + async markConfirmReminderSent(args: { + orderId: bigint; + now: Date; + isDue: (state: ConfirmReminderState) => boolean; + }): Promise { + const { orderId, now } = args; + return this.prisma.$transaction(async (tx) => { + const [locked] = await tx.$queryRaw< + { + id: bigint; + order_number: string; + status: OrderStatus; + submitted_at: Date | null; + confirm_deadline_at: Date | null; + confirm_reminder_sent_at: Date | null; + }[] + >` + SELECT id, order_number, status, submitted_at, confirm_deadline_at, confirm_reminder_sent_at + FROM \`order\` WHERE id = ${orderId} AND deleted_at IS NULL + FOR UPDATE`; + if ( + !locked?.confirm_deadline_at || + !args.isDue({ + status: locked.status, + submittedAt: locked.submitted_at, + confirmDeadlineAt: locked.confirm_deadline_at, + confirmReminderSentAt: locked.confirm_reminder_sent_at, + }) + ) { + return false; + } + const firstItem = await tx.orderItem.findFirst({ + where: { order_id: locked.id, ...activeWhere }, + orderBy: { id: 'asc' }, + select: { store_id: true, product_name_snapshot: true }, + }); + await tx.order.update({ + where: { id: locked.id }, + data: { confirm_reminder_sent_at: now }, + }); + // 품목이 없으면 매장을 몰라 보낼 곳이 없다 — 표시만 남겨 다시 고르지 않게 한다 + if (firstItem) { + await this.outbox.publish( + tx, + orderConfirmReminderDueEvent({ + orderId: locked.id, + orderNumber: locked.order_number, + storeId: firstItem.store_id, + productName: firstItem.product_name_snapshot, + confirmDeadlineAt: locked.confirm_deadline_at, + occurredAt: now, + }), + ); + } + return true; + }); + } +} 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-pending-payment-lock.helper.ts b/src/features/order/repositories/order-pending-payment-lock.helper.ts new file mode 100644 index 00000000..778b1b29 --- /dev/null +++ b/src/features/order/repositories/order-pending-payment-lock.helper.ts @@ -0,0 +1,58 @@ +import { OrderStatus, Prisma } from '@/generated/prisma/client'; + +/** 계정당 동시 입금 대기 주문 상한. */ +export const PENDING_PAYMENT_LIMIT = 2; +/** tx timeout(10초)보다 짧아야 대기 중 tx가 먼저 끊기지 않는다. */ +const LOCK_WAIT_SECONDS = 3; + +/** 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 = 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 { + try { + await tx.$queryRaw`SELECT RELEASE_LOCK(${name})`; + } catch { + // KILL 실패는 무시한다 — 끊을 세션이 이미 없으면 잠금도 이미 풀렸다. + await Promise.allSettled([outer.$executeRaw`KILL ${row.connectionId}`]); + } + } +} + +/** + * 잠금 읽기로 센다 — 앞 요청의 미커밋 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-pickup-change.repository.ts b/src/features/order/repositories/order-pickup-change.repository.ts new file mode 100644 index 00000000..50e8dd48 --- /dev/null +++ b/src/features/order/repositories/order-pickup-change.repository.ts @@ -0,0 +1,169 @@ +import { Inject, Injectable } from '@nestjs/common'; + +import { + AUDIT_LOG_REPOSITORY, + type IAuditLogRepository, +} from '@/features/audit-log'; +import { orderPickupRescheduledEvent } from '@/features/order/events/order-pickup-rescheduled.event'; +import { confirmDeadlineFor } from '@/features/order/policies/order-lifecycle.policy'; +import { + isDailyCapacityExceeded, + type DailyCapacityGuard, +} from '@/features/order/repositories/order-capacity.helper'; +import { + sellerOrderSummaryInclude, + type SellerOrderRow, +} from '@/features/order/repositories/order.repository'; +import { OutboxPublisher } from '@/features/outbox'; +import { + AuditActionType, + AuditTargetType, + OrderStatus, + Prisma, +} from '@/generated/prisma/client'; +import { activeWhere, PrismaService } from '@/prisma'; + +export interface ReschedulePickupArgs { + orderId: bigint; + storeId: bigint; + actorAccountId: bigint; + pickupAt: Date; + note: string | null; + now: Date; + /** 새 픽업일의 capacity 재검사 대상(이 주문 자신의 점유는 빼고 센다) */ + capacityGuard: DailyCapacityGuard; + /** 잠금 뒤 상태·현재 픽업 시각으로 다시 판정한다. 던지면 롤백되고 예외가 그대로 나간다. */ + assertReschedulable: (state: { status: OrderStatus; pickupAt: Date }) => void; +} + +export type ReschedulePickupResult = SellerOrderRow | 'capacity-exceeded'; + +/** 판매자 픽업 일시 변경. 잠금 순서는 order → order_store_daily_limit. */ +@Injectable() +export class OrderPickupChangeRepository { + constructor( + private readonly prisma: PrismaService, + private readonly outbox: OutboxPublisher, + @Inject(AUDIT_LOG_REPOSITORY) + private readonly auditLogs: IAuditLogRepository, + ) {} + + /** + * 판매자에게 보이는 자기 매장 주문만 옮긴다(없으면 null). 새 날짜 capacity는 행을 잠근 뒤 이 주문을 뺀 점유로 다시 센다. + * 접수 상태면 확정 마감을 새 픽업 기준으로 다시 재고 미리 알림 표시를 지운다. 변경 이력·감사·구매자 알림 이벤트를 같은 tx에 남긴다. + * READ COMMITTED: 잠금을 기다린 뒤의 점유 재집계가 그사이 커밋된 주문 생성·픽업 변경을 봐야 한다. + */ + async reschedule( + args: ReschedulePickupArgs, + ): Promise { + return this.prisma.$transaction( + async (tx) => { + const [locked] = await tx.$queryRaw< + { + id: bigint; + status: OrderStatus; + pickup_at: Date; + submitted_at: Date; + confirm_deadline_at: Date | null; + }[] + >` + SELECT o.id, o.status, o.pickup_at, o.submitted_at, o.confirm_deadline_at 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} AND i.deleted_at IS NULL + ) + FOR UPDATE OF o`; + if (!locked) return null; + args.assertReschedulable({ + status: locked.status, + pickupAt: locked.pickup_at, + }); + + const items = await tx.orderItem.findMany({ + where: { + order_id: locked.id, + store_id: args.storeId, + ...activeWhere, + }, + orderBy: { id: 'asc' }, + select: { + product_id: true, + product_name_snapshot: true, + store_name_snapshot: true, + quantity: true, + }, + }); + const quantity = items.reduce((sum, item) => sum + item.quantity, 0); + const exceeded = await isDailyCapacityExceeded( + tx, + args.capacityGuard, + quantity, + { forUpdate: true, excludeOrderId: locked.id }, + ); + if (exceeded) return 'capacity-exceeded'; + + // 결제 도입 전 접수는 마감이 없다 — 새로 만들지 않는다 + const resetDeadline = + locked.status === OrderStatus.SUBMITTED && + locked.confirm_deadline_at !== null; + const updated = await tx.order.update({ + where: { id: locked.id }, + data: { + pickup_at: args.pickupAt, + ...(resetDeadline + ? { + confirm_deadline_at: confirmDeadlineFor( + locked.submitted_at, + args.pickupAt, + ), + confirm_reminder_sent_at: null, + } + : {}), + }, + include: sellerOrderSummaryInclude(args.storeId), + }); + await tx.orderPickupChange.create({ + data: { + order_id: locked.id, + from_pickup_at: locked.pickup_at, + to_pickup_at: args.pickupAt, + changed_by_account_id: args.actorAccountId, + note: args.note, + changed_at: args.now, + }, + }); + + const [firstItem] = items; + await this.outbox.publish( + tx, + orderPickupRescheduledEvent({ + orderId: locked.id, + orderNumber: updated.order_number, + buyerAccountId: updated.account_id, + storeId: args.storeId, + storeName: firstItem?.store_name_snapshot ?? null, + productId: firstItem?.product_id ?? null, + productName: firstItem?.product_name_snapshot ?? null, + fromPickupAt: locked.pickup_at, + toPickupAt: args.pickupAt, + occurredAt: args.now, + actorAccountId: args.actorAccountId, + }), + ); + await this.auditLogs.recordAudit(tx, { + actorAccountId: args.actorAccountId, + storeId: args.storeId, + targetType: AuditTargetType.ORDER, + targetId: locked.id, + action: AuditActionType.UPDATE, + beforeJson: { pickupAt: locked.pickup_at.toISOString() }, + afterJson: { pickupAt: args.pickupAt.toISOString(), note: args.note }, + }); + return updated; + }, + { isolationLevel: Prisma.TransactionIsolationLevel.ReadCommitted }, + ); + } +} 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..5fb671f5 --- /dev/null +++ b/src/features/order/repositories/order-settlement-finalizer.helper.ts @@ -0,0 +1,71 @@ +import type { PaymentStatus, Prisma } from '@/generated/prisma/client'; + +const BPS_DENOMINATOR = 10_000; + +export interface LockedPayment { + id: bigint; + status: PaymentStatus; + amount: number; + expires_at: Date; + buyer_claimed_at: Date | null; + confirmed_at: Date | null; +} + +/** 결제 행을 잠그고 읽는다(잠금 순서 order → payment). 결제 도입 전 주문이면 null. */ +export async function lockPayment( + tx: Prisma.TransactionClient, + orderId: bigint, +): Promise { + const [row] = await tx.$queryRaw< + (Omit & { amount: bigint })[] + >` + SELECT id, status, amount, expires_at, buyer_claimed_at, 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 new file mode 100644 index 00000000..97ea5d25 --- /dev/null +++ b/src/features/order/repositories/order-transition.repository.spec.ts @@ -0,0 +1,626 @@ +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, + 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 { + createAccount, + createOrder, + createOrderItem, + 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 auditLogs: AuditLogRepository; + let prisma: PrismaClient; + + beforeAll(async () => { + const { module, prisma: p } = await createTestingModuleWithRealDb({ + providers: [ + OrderTransitionRepository, + { provide: AUDIT_LOG_REPOSITORY, useClass: AuditLogRepository }, + ...outboxPublisherProviders(), + ], + }); + repo = module.get(OrderTransitionRepository); + auditLogs = module.get(AUDIT_LOG_REPOSITORY); + 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); + }); + + 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' }); + }); + }); + 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 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( + 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.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'); + + 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 new file mode 100644 index 00000000..e8abe7e5 --- /dev/null +++ b/src/features/order/repositories/order-transition.repository.ts @@ -0,0 +1,558 @@ +import { Inject, Injectable } from '@nestjs/common'; + +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 { refundRequestedEvent } from '@/features/order/events/refund-requested.event'; +import type { + OrderCancelDecision, + OrderCancelState, +} from '@/features/order/policies/order-cancel.policy'; +import { + confirmDeadlineFor, + type OrderLockedState, +} from '@/features/order/policies/order-lifecycle.policy'; +import { + confirmedPaidAmount, + finalizeSettlementLocked, + lockPayment, + type LockedPayment, +} from '@/features/order/repositories/order-settlement-finalizer.helper'; +import { + adminOrderInclude, + type AdminOrderRow, +} from '@/features/order/repositories/order.repository'; +import { + refundAccountColumns, + type RefundAccountData, +} from '@/features/order/repositories/refund.repository'; +import { OutboxPublisher } from '@/features/outbox'; +import { + AuditActionType, + AuditTargetType, + OrderActor, + OrderCancelFault, + OrderStatus, + PaymentConfirmSource, + PaymentStatus, + Prisma, + RefundKind, +} 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; +} + +/** 취소 대상 범위. 범위 밖 주문은 없는 주문과 같다. */ +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; + /** 취소와 함께 받은 환불 계좌. 환불이 생기면 바로 송금 대기로 만들고, 환불이 없으면 버린다. */ + refundAccount?: RefundAccountData | null; + now: Date; + /** 크론 대상 조건을 잠금 뒤 다시 본다. false면 아무것도 바꾸지 않고 null이다(그사이 다른 전이·입금했어요). */ + eligible?: (state: OrderLockedState) => boolean; + /** 잠금 시점 재료로 사유·사정·환불액을 정한다. 던지면 tx가 롤백되고 예외가 그대로 나간다. */ + decide: (state: OrderCancelState) => OrderCancelDecision; +} + +export interface CompletePickupBySystemArgs { + orderId: bigint; + now: Date; + /** 잠금 뒤 상태·픽업 시각으로 다시 판정한다. false면 아무것도 바꾸지 않고 null이다. */ + eligible: (state: OrderLockedState) => boolean; +} + +export interface CompletePickupByAdminArgs { + orderId: bigint; + actorAccountId: bigint; + note: string | null; + now: Date; + /** 잠금 뒤 상태·픽업 시각으로 판정한다. 던지면 tx가 롤백되고 예외가 그대로 나간다. */ + assertTransition: (state: OrderLockedState) => void; +} + +/** 픽업 완료를 남기는 주체. 시스템 전이는 계정·메모가 없다. */ +interface PickupActor { + actor: OrderActor; + actorAccountId: bigint | null; + note: string | null; + now: Date; +} + +interface LockedOrderRow { + id: bigint; + status: OrderStatus; + pickup_at: Date; + commission_rate_bps: number; + submitted_at: Date | null; + confirm_deadline_at: Date | null; +} + +async function lockOrder( + tx: Prisma.TransactionClient, + orderId: bigint, + scopeSql: Prisma.Sql = Prisma.empty, +): Promise { + const [row] = await tx.$queryRaw` + SELECT o.id, o.status, o.pickup_at, o.commission_rate_bps, o.submitted_at, o.confirm_deadline_at + FROM \`order\` o + WHERE o.id = ${orderId} AND o.deleted_at IS NULL ${scopeSql} + FOR UPDATE OF o`; + return row; +} + +function lockedState( + order: LockedOrderRow, + payment: LockedPayment | null, +): OrderLockedState { + return { + status: order.status, + pickupAt: order.pickup_at, + confirmDeadlineAt: order.confirm_deadline_at, + payment, + }; +} + +/** 이벤트 스냅샷용 첫 활성 품목(주문 1건 = 상품 1개). */ +function firstItemOf(tx: Prisma.TransactionClient, orderId: bigint) { + return tx.orderItem.findFirst({ + where: { order_id: orderId, ...activeWhere }, + orderBy: { id: 'asc' }, + select: { + store_id: true, + product_id: true, + product_name_snapshot: true, + store_name_snapshot: true, + quantity: true, + }, + }); +} + +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} AND i.deleted_at IS NULL)`; + default: + return Prisma.empty; + } +} + +/** 주문 상태 전이 잠금 단위. 잠금 순서는 order → payment → refund. */ +@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 { + // 판정 재료는 잠금 읽기에서 가져온다 — 호출 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; + 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: locked.status, + paymentStatus: payment?.status ?? null, + paymentAmount, + pickupAt: locked.pickup_at, + }); + const confirmDeadlineAt = confirmDeadlineFor(args.now, locked.pickup_at); + 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 firstItemOf(tx, locked.id); + 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, + actorType, + pickupAt: updated.pickup_at, + 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, + depositedAmount: args.depositedAmount, + confirmSource: args.source, + note: args.note, + }, + }); + 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 lockOrder( + tx, + args.orderId, + cancelScopeSql(args.scope), + ); + if (!locked) return null; + const payment = await lockPayment(tx, locked.id); + if (args.eligible && !args.eligible(lockedState(locked, payment))) { + return null; + } + 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, + ...(args.refundAccount + ? refundAccountColumns(args.refundAccount, args.now) + : {}), + }, + }) + : null; + + const firstItem = await firstItemOf(tx, locked.id); + 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, + accountSubmitted: refund.account_submitted_at !== null, + }), + ); + } + + if (args.actorAccountId !== null) { + await this.auditLogs.recordAudit(tx, { + actorAccountId: args.actorAccountId, + // 매장 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, + 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; + } + + /** + * 자동 픽업 완료(SYSTEM). 잠금 뒤 다시 판정해 그사이 판매자가 처리했거나 픽업이 바뀐 주문은 건너뛴다. + * 시스템 전이라 감사 기록은 없다. + */ + async completePickupBySystem( + args: CompletePickupBySystemArgs, + ): Promise { + return this.prisma.$transaction(async (tx) => { + const locked = await lockOrder(tx, args.orderId); + if (!locked) return null; + const payment = await lockPayment(tx, locked.id); + if (!args.eligible(lockedState(locked, payment))) return null; + return this.completePickupLocked(tx, locked, payment, { + actor: OrderActor.SYSTEM, + actorAccountId: null, + note: null, + now: args.now, + }); + }); + } + + /** 관리자 픽업 완료(매장 숨김과 무관). 없는 주문이면 null. */ + async completePickupByAdmin( + args: CompletePickupByAdminArgs, + ): Promise { + return this.prisma.$transaction(async (tx) => { + const locked = await lockOrder(tx, args.orderId); + if (!locked) return null; + const payment = await lockPayment(tx, locked.id); + args.assertTransition(lockedState(locked, payment)); + return this.completePickupLocked(tx, locked, payment, { + actor: OrderActor.ADMIN, + actorAccountId: args.actorAccountId, + note: args.note, + now: args.now, + }); + }); + } + + /** 픽업 완료와 정산 확정. 확인된 결제가 없는 주문(결제 도입 전)은 정산을 확정하지 않는다. */ + private async completePickupLocked( + tx: Prisma.TransactionClient, + locked: LockedOrderRow, + payment: LockedPayment | null, + by: PickupActor, + ): Promise { + const updated = await tx.order.update({ + where: { id: locked.id }, + data: { status: OrderStatus.PICKED_UP, picked_up_at: by.now }, + include: adminOrderInclude, + }); + await finalizeSettlementLocked( + tx, + locked, + confirmedPaidAmount(payment), + by.now, + ); + await tx.orderStatusHistory.create({ + data: { + order_id: locked.id, + from_status: locked.status, + to_status: OrderStatus.PICKED_UP, + changed_at: by.now, + actor_type: by.actor, + actor_account_id: by.actorAccountId, + note: by.note, + }, + }); + const firstItem = await firstItemOf(tx, locked.id); + await this.outbox.publish( + tx, + orderStatusChangedEvent({ + orderId: locked.id, + orderNumber: updated.order_number, + buyerAccountId: updated.account_id, + fromStatus: locked.status, + toStatus: OrderStatus.PICKED_UP, + storeId: firstItem?.store_id ?? null, + storeName: firstItem?.store_name_snapshot ?? null, + productId: firstItem?.product_id ?? null, + productName: firstItem?.product_name_snapshot ?? null, + actorType: by.actor, + pickupAt: updated.pickup_at, + occurredAt: by.now, + actorAccountId: by.actorAccountId, + }), + ); + if (by.actorAccountId !== null) { + await this.auditLogs.recordAudit(tx, { + actorAccountId: by.actorAccountId, + // 판매자에게 보인 주문만 매장 id를 붙인다(판매자 감사 로그 노출) + 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.PICKED_UP, + actorType: by.actor, + note: by.note, + }, + }); + } + return updated; + } +} diff --git a/src/features/order/repositories/order-withdrawal-blocking.repository.ts b/src/features/order/repositories/order-withdrawal-blocking.repository.ts new file mode 100644 index 00000000..967f3cf9 --- /dev/null +++ b/src/features/order/repositories/order-withdrawal-blocking.repository.ts @@ -0,0 +1,32 @@ +import { Injectable } from '@nestjs/common'; + +import { WithdrawalBlockingOrderQuery } from '@/common/ports/withdrawal-blocking-order.port'; +import { IN_PROGRESS_ORDER_STATUSES } from '@/features/order/constants/order-status-traits'; +import { RefundStatus } from '@/generated/prisma/client'; +import { activeWhere, PrismaService } from '@/prisma'; + +/** 탈퇴 차단 포트 구현. 돌려줄 돈이 남은 구매자가 탈퇴하면 환불 계좌를 받을 수 없어 막는다. */ +@Injectable() +export class OrderWithdrawalBlockingRepository extends WithdrawalBlockingOrderQuery { + constructor(private readonly prisma: PrismaService) { + super(); + } + + async countByBuyer(accountId: bigint): Promise { + const [orders, refunds] = await Promise.all([ + this.prisma.order.count({ + where: { + account_id: accountId, + status: { in: [...IN_PROGRESS_ORDER_STATUSES] }, + }, + }), + this.prisma.refund.count({ + where: { + status: { not: RefundStatus.COMPLETED }, + order: { account_id: accountId, ...activeWhere }, + }, + }), + ]); + return orders + refunds; + } +} diff --git a/src/features/order/repositories/order.repository.spec.ts b/src/features/order/repositories/order.repository.spec.ts index cc41ae3c..5b047efc 100644 --- a/src/features/order/repositories/order.repository.spec.ts +++ b/src/features/order/repositories/order.repository.spec.ts @@ -4,11 +4,15 @@ 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'; + ORDER_PAYMENT_PENDING, + parseOrderPaymentPendingPayload, +} from '@/features/order/events/order-payment-pending.event'; import { - type CreateSubmittedOrderArgs, + pendingPaymentLockName, + withPendingPaymentLock, +} from '@/features/order/repositories/order-pending-payment-lock.helper'; +import { + type CreatePendingPaymentOrderArgs, type DailyCapacityGuard, OrderRepository, } from '@/features/order/repositories/order.repository'; @@ -108,9 +112,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 +143,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 () => { @@ -287,6 +298,7 @@ describe('OrderRepository (real DB)', () => { from_status: 'SUBMITTED', to_status: 'CONFIRMED', changed_at: new Date(), + actor_type: 'SELLER', note: '확정', }, }); @@ -392,6 +404,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, { @@ -424,6 +437,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, { @@ -443,6 +457,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, { @@ -507,21 +522,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, }); @@ -530,10 +545,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); @@ -572,7 +625,7 @@ describe('OrderRepository (real DB)', () => { storeId: store.id, from, to, - basis: 'created', + basis: 'submitted', }), ).toEqual({ orderCount: 0, salesAmount: 0 }); }); @@ -659,6 +712,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.CONFIRMED, + 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); @@ -754,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 }, - }); - expect(notifications).toHaveLength(1); - expect(notifications[0]).toMatchObject({ - account_id: buyer.id, - type: 'ORDER_STATUS', - event: 'ORDER_CANCELED', - store_id: store.id, + const event = await prisma.outbox.findFirstOrThrow({ + where: { event_type: 'order.status_changed' }, }); - - 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 () => { @@ -861,31 +927,42 @@ 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, 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, - 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, @@ -898,11 +975,12 @@ describe('OrderRepository (real DB)', () => { quantity, itemSubtotalPrice: 25000 * quantity, options: [], + custom: null, }, }; } - 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, { @@ -910,35 +988,63 @@ 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 order = await prisma.order.findUniqueOrThrow({ + where: { id: created.id }, + include: { payment: true, status_histories: true }, + }); + expect(order).toMatchObject({ + status: 'PENDING_PAYMENT', + submitted_at: null, + commission_rate_bps: 550, + total_price: 50000, + }); + expect(order.payment).toMatchObject({ + method: 'BANK_TRANSFER', + status: 'PENDING', + 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 }); 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, + aggregate_id: created.id.toString(), + event_type: ORDER_PAYMENT_PENDING, + occurred_at: NOW, actor_account_id: buyer.id, - status: 'PENDING', }); - expect(parseOrderSubmittedPayload(events[0].payload_json)).toEqual({ - orderId: created!.id.toString(), + expect(parseOrderPaymentPendingPayload(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, + 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 }); @@ -948,8 +1054,8 @@ describe('OrderRepository (real DB)', () => { capacity: 1, }); - const created = await repo.createSubmittedOrder( - submitArgs({ + const created = await repo.createPendingPaymentOrder( + createArgs({ buyerId: buyer.id, store, product, @@ -963,20 +1069,21 @@ describe('OrderRepository (real DB)', () => { }), ); - expect(created).toBeNull(); + 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 }); await createOrder(prisma, { order_number: 'ORD-20260916-DUP000' }); await expect( - repo.createSubmittedOrder( - submitArgs({ + repo.createPendingPaymentOrder( + createArgs({ buyerId: buyer.id, store, product, @@ -985,7 +1092,60 @@ 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 () => { + 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' }); + + 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 78199b2f..575aa347 100644 --- a/src/features/order/repositories/order.repository.ts +++ b/src/features/order/repositories/order.repository.ts @@ -4,15 +4,47 @@ import { AUDIT_LOG_REPOSITORY, 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 { orderSubmittedEvent } from '@/features/order/events/order-submitted.event'; +import { + isDailyCapacityExceeded, + type DailyCapacityGuard, +} from '@/features/order/repositories/order-capacity.helper'; +import { + lockCustomUploadsForAttach, + markCustomUploadsAttached, + type CustomUploadIssue, + type CustomUploadRef, +} from '@/features/order/repositories/order-custom-upload-attach.helper'; +import { + countPendingPaymentOrdersLocked, + 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, +} from '@/features/order/repositories/payment.repository'; import { OutboxPublisher } from '@/features/outbox'; import { AuditActionType, AuditTargetType, + OrderActor, OrderStatus, + PaymentMethod, Prisma, + RefundKind, type AccountType, + type CustomImageKind, + type CustomMode, + type CustomTextAlign, + type PaymentStatus, } from '@/generated/prisma/client'; import { activeWhere, PrismaService } from '@/prisma'; @@ -26,7 +58,32 @@ export type SellerOrderRow = Prisma.OrderGetPayload<{ include: ReturnType; }>; -const adminOrderInclude = { +/** 판매자에게 보이는 주문 — 입금 확인(접수) 때 submitted_at을 채우므로 입금 대기와 입금 전 취소가 함께 빠진다. */ +const sellerVisibleWhere = { + submitted_at: { not: null }, +} satisfies Prisma.OrderWhereInput; + +/** 주문 상세 3곳(구매자·판매자·관리자)의 픽업 변경 이력(오래된 순). */ +const pickupChangesInclude = { + orderBy: [{ changed_at: 'asc' }, { id: 'asc' }], +} satisfies Prisma.Order$pickup_changesArgs; + +/** 주문 상세 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, select: { @@ -34,6 +91,8 @@ 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, @@ -41,13 +100,15 @@ const adminOrderInclude = { } satisfies Prisma.OrderInclude; /** 목록 카드용 첫 품목 스냅샷 — 매장 필터가 들어가 상수로 둘 수 없다. */ -function sellerOrderSummaryInclude(storeId: bigint) { +export function sellerOrderSummaryInclude(storeId: bigint) { return { items: { where: { store_id: storeId, ...activeWhere }, select: { product_name_snapshot: true, product_thumbnail_url_snapshot: true, + custom_mode_snapshot: true, + custom_preview_image_url: true, }, orderBy: { id: 'asc' }, take: 1, @@ -64,24 +125,40 @@ const adminOrderDetailInclude = { user_profile: { select: { nickname: true, deleted_at: true } }, }, }, + payment: true, + refunds: { orderBy: { id: 'asc' } }, + pickup_changes: pickupChangesInclude, status_histories: { where: activeWhere, orderBy: { changed_at: 'desc' } }, items: { where: activeWhere, 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; +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; @@ -98,6 +175,7 @@ export interface MyOrderRow { product_thumbnail_url_snapshot: string | null; }[]; _count: { items: number }; + payment: { status: PaymentStatus; expires_at: Date } | null; } export interface OngoingOrderRow { @@ -113,27 +191,63 @@ export interface OngoingOrderRow { }[]; } -/** 트랜잭션 안에서 capacity 행을 잠그고 점유를 재집계해 검사-삽입 race로 capacity가 초과되는 것을 막는다. */ -export interface DailyCapacityGuard { - storeId: bigint; - dateOnlyUtc: Date; - dayStartUtc: Date; - dayEndUtc: Date; +export type { DailyCapacityGuard } from '@/features/order/repositories/order-capacity.helper'; + +/** 주문 품목 커스텀 스냅샷. 검증·정규화를 마친 값이고, 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 CreateSubmittedOrderArgs { +export interface CreatePendingPaymentOrderArgs { accountId: bigint; orderNumber: string; idempotencyKey: string; + idempotencyInputHash: string; pickupAt: Date; buyerName: string; buyerPhone: string; + requestNote: string | null; 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; @@ -152,6 +266,7 @@ export interface CreateSubmittedOrderArgs { optionTitleSnapshot: string; optionPriceDeltaSnapshot: number; }[]; + custom: OrderItemCustomSnapshot | null; }; } @@ -160,11 +275,29 @@ 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' + | CustomUploadIssue; + export interface ReviewableOrderItemRow { id: bigint; product_id: bigint; @@ -210,97 +343,75 @@ 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, this.prisma, args.accountId, async () => { + const pending = await countPendingPaymentOrdersLocked( + tx, + args.accountId, + ); + if (pending >= PENDING_PAYMENT_LIMIT) return 'pending-limit'; + if (args.capacityGuard) { + const exceeded = await isDailyCapacityExceeded( + tx, + args.capacityGuard, + args.item.quantity, + { forUpdate: true }, + ); + 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); + }), + { + timeout: 10_000, + isolationLevel: Prisma.TransactionIsolationLevel.ReadCommitted, + }, + ); } - /** tx 밖 사전 검증(잠금 없음) — 거절을 tx 전에 내리고, 최종 판정은 createSubmittedOrder의 잠금 재검사가 한다. */ + /** tx 밖 사전 검증(잠금 없음) — 거절을 tx 전에 내리고, 최종 판정은 createPendingPaymentOrder의 잠금 재검사가 한다. */ async isDailyCapacityExceeded( guard: DailyCapacityGuard, quantity: number, ): Promise { - return this.capacityExceeded(this.prisma, guard, quantity, false); - } - - /** FOR UPDATE는 같은 매장·날짜의 동시 주문 생성을 직렬화한다. */ - private isCapacityExceededLocked( - tx: Prisma.TransactionClient, - guard: DailyCapacityGuard, - quantity: number, - ): Promise { - return this.capacityExceeded(tx, guard, quantity, true); - } - - /** - * capacity는 order 소유 복제본(order_store_daily_limit)에서 읽는다 — catalog 행을 잠그지 않는다. - * 복제본이 없거나 capacity가 비어 있으면(tombstone) 무제한: 설정 직후 복제 지연 구간에는 제한 없이 받는다. - */ - private async capacityExceeded( - db: Prisma.TransactionClient, - guard: DailyCapacityGuard, - quantity: number, - forUpdate: boolean, - ): Promise { - const capacityRows = await db.$queryRaw<{ capacity: number }[]>(Prisma.sql` - SELECT capacity - FROM order_store_daily_limit - WHERE store_id = ${guard.storeId} - AND booking_date = ${guard.dateOnlyUtc} - AND capacity IS NOT NULL - ${forUpdate ? Prisma.sql`FOR UPDATE` : Prisma.empty} - `); - const capacity = capacityRows[0]?.capacity; - if (capacity === undefined) return false; - - const bookedRows = await db.$queryRaw<{ booked: bigint }[]>(Prisma.sql` - SELECT CAST(COALESCE(SUM(oi.quantity), 0) AS UNSIGNED) AS booked - FROM order_item oi - JOIN \`order\` o - ON o.id = oi.order_id - AND o.deleted_at IS NULL - AND o.status <> 'CANCELED' - AND o.pickup_at >= ${guard.dayStartUtc} - AND o.pickup_at < ${guard.dayEndUtc} - WHERE oi.store_id = ${guard.storeId} - AND oi.deleted_at IS NULL - `); - const booked = Number(bookedRows[0]?.booked ?? 0); - return booked + quantity > capacity; + return isDailyCapacityExceeded(this.prisma, guard, quantity, { + forUpdate: false, + }); } - private async insertSubmittedOrder( + private async insertPendingPaymentOrder( tx: Prisma.TransactionClient, - args: CreateSubmittedOrderArgs, + args: CreatePendingPaymentOrderArgs, ): Promise { const created = await tx.order.create({ data: { account_id: args.accountId, order_number: args.orderNumber, idempotency_key: args.idempotencyKey, - status: OrderStatus.SUBMITTED, + idempotency_input_hash: args.idempotencyInputHash, + status: OrderStatus.PENDING_PAYMENT, 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, - submitted_at: args.submittedAt, + commission_rate_bps: args.commissionRateBps, items: { create: { store_id: args.item.storeId, @@ -323,41 +434,48 @@ export class OrderRepository { option_price_delta_snapshot: option.optionPriceDeltaSnapshot, })), }, + ...(args.item.custom && customItemData(args.item.custom)), + }, + }, + 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, - }, + select: createdOrderSelect, }); - // 접수 이벤트(outbox, 같은 tx) — 판매자 푸시 원천. 구매자 알림은 없다(notification 소비자는 구독하지 않는다). + await markCustomUploadsAttached( + tx, + args.item.custom?.uploads ?? [], + args.now, + ); + // 관리자 경보 원천. 판매자 '새 주문'(order.submitted)은 입금 확인 때 나간다 await this.outbox.publish( tx, - orderSubmittedEvent({ + orderPaymentPendingEvent({ 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, + amount: args.totalPrice, + depositorName: args.payment.depositorName, + expiresAt: args.payment.expiresAt, + occurredAt: args.now, }), ); return created; @@ -370,15 +488,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, - }, + select: createdOrderSelect, }); } @@ -409,9 +519,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' }, @@ -453,6 +561,7 @@ export class OrderRepository { _count: { select: { items: { where: activeWhere } }, }, + payment: { select: { status: true, expires_at: true } }, }, }); } @@ -556,6 +665,9 @@ export class OrderRepository { account_id: args.accountId, }, include: { + payment: { select: orderPaymentSelect }, + refunds: { orderBy: { id: 'asc' } }, + pickup_changes: pickupChangesInclude, status_histories: { where: activeWhere, orderBy: { changed_at: 'asc' }, @@ -587,20 +699,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 }, }, @@ -614,6 +713,7 @@ export class OrderRepository { private storeOrderScopeWhere(args: { storeId: bigint; status?: OrderStatus; + buyerAccountId?: bigint; fromCreatedAt?: Date; toCreatedAt?: Date; fromPickupAt?: Date; @@ -621,7 +721,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: { @@ -659,6 +763,7 @@ export class OrderRepository { async countOrdersByStore(args: { storeId: bigint; status?: OrderStatus; + buyerAccountId?: bigint; fromCreatedAt?: Date; toCreatedAt?: Date; fromPickupAt?: Date; @@ -670,20 +775,26 @@ 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: { + // 접수 기준 범위가 노출 조건의 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' : 'created_at']: { - gte: args.from, - lt: args.to, - }, items: { some: { store_id: args.storeId, ...activeWhere } }, }, _count: { _all: true }, @@ -695,11 +806,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; @@ -721,6 +853,7 @@ export class OrderRepository { return this.prisma.order.findFirst({ where: { id: args.orderId, + ...sellerVisibleWhere, items: { some: { store_id: args.storeId, @@ -730,8 +863,16 @@ export class OrderRepository { }, // 유저측 상세(findOrderDetailByUser)와 동일하게 soft-delete 자식을 가드한다 include: { + payment: { select: { method: true, amount: true, confirmed_at: true } }, + // 입금 반환은 구매자와 플랫폼 사이 일이라 취소 환불만 본다 + refunds: { where: { kind: RefundKind.CANCEL } }, + pickup_changes: pickupChangesInclude, + // 입금 대기 이력은 판매자에게 보이지 않는다 status_histories: { - where: activeWhere, + where: { + to_status: { not: OrderStatus.PENDING_PAYMENT }, + ...activeWhere, + }, orderBy: { changed_at: 'desc', }, @@ -743,20 +884,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, }, }, }, @@ -765,9 +893,9 @@ export class OrderRepository { /** * 판매자 상태 변경. 주문 행을 잠근(FOR UPDATE) 뒤 잠금 시점 상태로 전이를 다시 판정한다 — - * 관리자 강제 취소(cancelOrderByAdmin)와 같은 잠금을 쓰므로 둘이 교차해도 나중 쪽은 바뀐 - * 상태를 보고 거절된다(잠금 없이 읽으면 CANCELED 위에 CONFIRMED를 덮어쓴다). - * assertTransition이 던지면 트랜잭션은 롤백되고 예외가 그대로 전파된다. + * 취소(OrderTransitionRepository.cancelLocked)와 같은 잠금을 쓰므로 둘이 교차해도 나중 쪽은 바뀐 + * 상태를 보고 거절된다(잠금 없이 읽으면 CANCELED 위에 CONFIRMED를 덮어쓴다). 픽업 완료·노쇼는 정산을 함께 확정한다. + * assertTransition은 잠금 시점 상태·픽업 시각으로 부르고, 던지면 트랜잭션은 롤백되고 예외가 그대로 전파된다. */ async updateOrderStatusBySeller(args: { orderId: bigint; @@ -776,14 +904,22 @@ export class OrderRepository { toStatus: OrderStatus; note: string | null; now: Date; - assertTransition: (fromStatus: OrderStatus) => void; + assertTransition: (fromStatus: OrderStatus, pickupAt: Date) => void; ipAddress?: string; 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; + pickup_at: Date; + commission_rate_bps: number; + }[] + >` + SELECT o.id, o.status, o.pickup_at, 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 ( SELECT 1 FROM order_item i WHERE i.order_id = o.id AND i.store_id = ${args.storeId} @@ -796,7 +932,7 @@ export class OrderRepository { } const fromStatus = order.status; - args.assertTransition(fromStatus); + args.assertTransition(fromStatus, order.pickup_at); const updatedOrder = await tx.order.update({ where: { @@ -811,12 +947,24 @@ export class OrderRepository { ...(args.toStatus === OrderStatus.PICKED_UP ? { picked_up_at: args.now } : {}), - ...(args.toStatus === OrderStatus.CANCELED - ? { canceled_at: args.now } + ...(args.toStatus === OrderStatus.NO_SHOW + ? { no_show_at: args.now } : {}), }, include: sellerOrderSummaryInclude(args.storeId), }); + if ( + args.toStatus === OrderStatus.PICKED_UP || + args.toStatus === OrderStatus.NO_SHOW + ) { + const payment = await lockPayment(tx, order.id); + await finalizeSettlementLocked( + tx, + order, + confirmedPaidAmount(payment), + args.now, + ); + } await tx.orderStatusHistory.create({ data: { @@ -824,6 +972,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, }, }); @@ -851,6 +1001,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, }), @@ -884,13 +1036,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 } } } @@ -918,6 +1077,7 @@ export class OrderRepository { async listOrdersForAdmin(args: { keyword?: string; status?: OrderStatus; + inProgress?: boolean; storeId?: bigint; accountId?: bigint; fromCreatedAt?: Date; @@ -939,6 +1099,7 @@ export class OrderRepository { async countOrdersForAdmin(args: { keyword?: string; status?: OrderStatus; + inProgress?: boolean; storeId?: bigint; accountId?: bigint; fromCreatedAt?: Date; @@ -956,138 +1117,109 @@ 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, - 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, + ): 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 }; } } + +/** 품목 생성에 펼쳐 넣는 커스텀 스냅샷. 자유 편집·참고 사진 순서는 입력 순서다. */ +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/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/payment.repository.ts b/src/features/order/repositories/payment.repository.ts new file mode 100644 index 00000000..290d3ddc --- /dev/null +++ b/src/features/order/repositories/payment.repository.ts @@ -0,0 +1,179 @@ +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, + 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 readonly outbox: OutboxPublisher, + ) {} + + 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; 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'; + 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 }, + }); + 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/repositories/refund.repository.ts b/src/features/order/repositories/refund.repository.ts new file mode 100644 index 00000000..866b3c87 --- /dev/null +++ b/src/features/order/repositories/refund.repository.ts @@ -0,0 +1,248 @@ +import { Inject, Injectable } from '@nestjs/common'; + +import { + AUDIT_LOG_REPOSITORY, + type IAuditLogRepository, +} from '@/features/audit-log'; +import { refundAccountSubmittedEvent } from '@/features/order/events/refund-account-submitted.event'; +import { refundCompletedEvent } from '@/features/order/events/refund-completed.event'; +import type { RefundEventArgs } from '@/features/order/events/refund-requested.event'; +import { OutboxPublisher } from '@/features/outbox'; +import { + AuditActionType, + AuditTargetType, + type Prisma, + type Refund, + type RefundKind, + RefundStatus, +} from '@/generated/prisma/client'; +import { activeWhere, PrismaService } from '@/prisma'; + +export const adminDepositRecordInclude = { + order: { select: { order_number: true } }, + refund: { select: { id: true, status: true } }, +} satisfies Prisma.DepositRecordInclude; + +export type AdminDepositRecordRow = Prisma.DepositRecordGetPayload<{ + include: typeof adminDepositRecordInclude; +}>; + +/** 관리자 목록·상세: 주문 식별·연락처, 첫 품목 스냅샷, 입금 반환이면 입금 기록. */ +const adminRefundInclude = { + order: { + select: { + order_number: true, + buyer_name: true, + buyer_phone: true, + items: { + where: activeWhere, + select: { store_name_snapshot: true, product_name_snapshot: true }, + orderBy: { id: 'asc' }, + take: 1, + }, + }, + }, + deposit_record: { include: adminDepositRecordInclude }, +} satisfies Prisma.RefundInclude; + +export type AdminRefundRow = Prisma.RefundGetPayload<{ + include: typeof adminRefundInclude; +}>; + +export interface RefundFilter { + status?: RefundStatus; + kind?: RefundKind; +} + +/** 서비스가 정규화·암호화한 환불 계좌. 원문 계좌번호는 repository로 내려오지 않는다. */ +export interface RefundAccountData { + bankCode: string; + accountHolder: string; + accountNumberEnc: string; + accountNumberLast4: string; +} + +/** 계좌가 들어오면 송금 대기다. 덮어쓰기도 같은 값으로 바꾼다. */ +export function refundAccountColumns(account: RefundAccountData, now: Date) { + return { + status: RefundStatus.AWAITING_TRANSFER, + bank_code: account.bankCode, + account_holder: account.accountHolder, + account_number_enc: account.accountNumberEnc, + account_number_last4: account.accountNumberLast4, + account_submitted_at: now, + } satisfies Prisma.RefundUncheckedUpdateInput; +} + +/** 환불 이벤트 스냅샷: 주문번호·구매자와 첫 품목의 매장·상품. */ +export async function loadRefundEventArgs( + tx: Prisma.TransactionClient, + refund: Pick, + now: Date, + actorAccountId: bigint | null, +): Promise { + const order = await tx.order.findUniqueOrThrow({ + where: { id: refund.order_id }, + select: { + order_number: true, + account_id: true, + items: { + where: activeWhere, + orderBy: { id: 'asc' }, + take: 1, + select: { + store_id: true, + store_name_snapshot: true, + product_id: true, + product_name_snapshot: true, + }, + }, + }, + }); + const [item] = order.items; + return { + refundId: refund.id, + orderId: refund.order_id, + orderNumber: order.order_number, + buyerAccountId: order.account_id, + kind: refund.kind, + amount: refund.amount, + storeId: item?.store_id ?? null, + storeName: item?.store_name_snapshot ?? null, + productId: item?.product_id ?? null, + productName: item?.product_name_snapshot ?? null, + occurredAt: now, + actorAccountId, + }; +} + +export type SubmitRefundAccountResult = + { orderId: bigint } | 'not-found' | 'completed'; + +export type CompleteRefundResult = + AdminRefundRow | 'not-found' | 'completed' | 'not-ready'; + +/** 환불(취소 환불·입금 반환)의 계좌 입력·송금 완료와 관리자 조회. 잠금은 환불 행 하나만 잡는다. */ +@Injectable() +export class RefundRepository { + constructor( + private readonly prisma: PrismaService, + private readonly outbox: OutboxPublisher, + @Inject(AUDIT_LOG_REPOSITORY) + private readonly auditLogs: IAuditLogRepository, + ) {} + + private filterWhere(filter: RefundFilter): Prisma.RefundWhereInput { + return { + ...(filter.status ? { status: filter.status } : {}), + ...(filter.kind ? { kind: filter.kind } : {}), + }; + } + + /** 처리 순서대로(오래된 환불부터). */ + async listRefunds( + filter: RefundFilter & { limit: number; cursor?: bigint }, + ): Promise { + return this.prisma.refund.findMany({ + where: { + ...this.filterWhere(filter), + ...(filter.cursor !== undefined ? { id: { gt: filter.cursor } } : {}), + }, + include: adminRefundInclude, + orderBy: { id: 'asc' }, + take: filter.limit + 1, + }); + } + + async countRefunds(filter: RefundFilter): Promise { + return this.prisma.refund.count({ where: this.filterWhere(filter) }); + } + + async findAdminRefund(refundId: bigint): Promise { + return this.prisma.refund.findUnique({ + where: { id: refundId }, + include: adminRefundInclude, + }); + } + + /** 구매자 본인 환불의 계좌를 넣거나 바꾼다(송금 완료 전까지). */ + async submitAccount(args: { + refundId: bigint; + accountId: bigint; + account: RefundAccountData; + now: Date; + }): Promise { + return this.prisma.$transaction(async (tx) => { + const [locked] = await tx.$queryRaw[]>` + SELECT r.id, r.status FROM refund r + JOIN \`order\` o ON o.id = r.order_id + WHERE r.id = ${args.refundId} AND o.account_id = ${args.accountId} AND o.deleted_at IS NULL + FOR UPDATE OF r`; + if (!locked) return 'not-found'; + if (locked.status === RefundStatus.COMPLETED) return 'completed'; + + const updated = await tx.refund.update({ + where: { id: locked.id }, + data: refundAccountColumns(args.account, args.now), + }); + await this.outbox.publish( + tx, + refundAccountSubmittedEvent( + await loadRefundEventArgs(tx, updated, args.now, args.accountId), + ), + ); + return { orderId: updated.order_id }; + }); + } + + /** 송금 완료. 계좌가 들어온(송금 대기) 환불만 된다. */ + async complete(args: { + refundId: bigint; + actorAccountId: bigint; + actorLabel: string | null; + note: string | null; + now: Date; + }): Promise { + return this.prisma.$transaction(async (tx) => { + const [locked] = await tx.$queryRaw[]>` + SELECT id, status FROM refund WHERE id = ${args.refundId} FOR UPDATE`; + if (!locked) return 'not-found'; + if (locked.status === RefundStatus.COMPLETED) return 'completed'; + if (locked.status === RefundStatus.AWAITING_ACCOUNT) return 'not-ready'; + + const updated = await tx.refund.update({ + where: { id: locked.id }, + data: { + status: RefundStatus.COMPLETED, + completed_at: args.now, + completed_by_account_id: args.actorAccountId, + completed_by_label_snapshot: args.actorLabel, + complete_note: args.note, + }, + include: adminRefundInclude, + }); + await this.outbox.publish( + tx, + refundCompletedEvent( + await loadRefundEventArgs(tx, updated, args.now, args.actorAccountId), + ), + ); + await this.auditLogs.recordAudit(tx, { + actorAccountId: args.actorAccountId, + targetType: AuditTargetType.REFUND, + targetId: updated.id, + action: AuditActionType.STATUS_CHANGE, + beforeJson: { status: locked.status }, + afterJson: { + status: RefundStatus.COMPLETED, + orderId: updated.order_id.toString(), + kind: updated.kind, + amount: updated.amount, + accountNumberLast4: updated.account_number_last4, + note: args.note, + }, + }); + return updated; + }); + } +} diff --git a/src/features/order/repositories/settlement.repository.ts b/src/features/order/repositories/settlement.repository.ts new file mode 100644 index 00000000..263c4513 --- /dev/null +++ b/src/features/order/repositories/settlement.repository.ts @@ -0,0 +1,317 @@ +import { Inject, Injectable } from '@nestjs/common'; + +import { formatDateOnly } from '@/common/utils/kst-time'; +import { + AUDIT_LOG_REPOSITORY, + type IAuditLogRepository, +} from '@/features/audit-log'; +import { settlementCreatedEvent } from '@/features/order/events/settlement-created.event'; +import { OutboxPublisher } from '@/features/outbox'; +import { + AuditActionType, + AuditTargetType, + Prisma, + SettlementStatus, + type Settlement, +} from '@/generated/prisma/client'; +import { activeWhere, PrismaService } from '@/prisma'; + +/** 정산 매장은 주문의 첫 품목(남은 품목 중 id가 가장 작은 것)이 정한다 — 주문 1건 = 매장 1곳. */ +const FIRST_ITEM_JOIN = Prisma.sql`JOIN order_item oi ON oi.id = ( + SELECT MIN(i.id) FROM order_item i WHERE i.order_id = o.id AND i.deleted_at IS NULL)`; + +/** 정산이 확정됐지만 아직 주간 정산에 묶이지 않은 주문. raw라 deleted_at을 직접 건다. */ +function unsettledBefore(before: Date): Prisma.Sql { + return Prisma.sql`o.settlement_finalized_at < ${before} + AND o.settlement_id IS NULL AND o.settlement_base_amount > 0 + AND o.deleted_at IS NULL`; +} + +export const settlementDetailInclude = { + orders: { + where: activeWhere, + orderBy: { id: 'asc' }, + select: { + id: true, + order_number: true, + status: true, + commission_rate_bps: true, + settlement_base_amount: true, + commission_amount: true, + settlement_finalized_at: true, + items: { + where: activeWhere, + orderBy: { id: 'asc' }, + take: 1, + select: { product_name_snapshot: true }, + }, + }, + }, +} satisfies Prisma.SettlementInclude; + +export type SettlementDetailRow = Prisma.SettlementGetPayload<{ + include: typeof settlementDetailInclude; +}>; + +export interface SettlementListFilter { + storeId?: bigint; + status?: SettlementStatus; + /** `@db.Date` 값 */ + periodStart?: Date; +} + +export type MarkSettlementPaidResult = + | { kind: 'paid' } + | { kind: 'not-found' } + | { kind: 'already-paid' } + | { kind: 'account-required' }; + +export interface MonthlyCommissionRow { + storeId: bigint; + storeName: string; + orderCount: number; + settlementBaseAmount: number; + commissionAmount: number; +} + +@Injectable() +export class SettlementRepository { + constructor( + private readonly prisma: PrismaService, + private readonly outbox: OutboxPublisher, + @Inject(AUDIT_LOG_REPOSITORY) + private readonly auditLogs: IAuditLogRepository, + ) {} + + /** 정산할 주문이 남은 매장 id의 키셋 한 페이지(id 오름차순). afterStoreId 다음부터 limit곳. */ + async findUnsettledStoreIds(args: { + before: Date; + afterStoreId?: bigint; + limit: number; + }): Promise { + const rows = await this.prisma.$queryRaw<{ store_id: bigint }[]>` + SELECT DISTINCT oi.store_id FROM \`order\` o ${FIRST_ITEM_JOIN} + WHERE ${unsettledBefore(args.before)} + ${args.afterStoreId !== undefined ? Prisma.sql`AND oi.store_id > ${args.afterStoreId}` : Prisma.empty} + ORDER BY oi.store_id + LIMIT ${args.limit}`; + return rows.map((row) => row.store_id); + } + + /** + * 한 매장의 주간 정산. 주문 행을 id 순으로 잠근 뒤 다시 골라 합계를 내고, 정산 행·주문 연결·outbox를 한 tx에 남긴다. + * 그 기간 정산이 이미 있거나(재실행) 묶을 주문이 없으면 만들지 않는다 — 남은 주문은 다음 주 정산에 들어간다. + */ + async createWeeklySettlement(args: { + storeId: bigint; + /** 이 시각 전에 확정된 주문을 묶는다(이번 주 월요일 00:00 KST) */ + settledBefore: Date; + periodStart: Date; + periodEnd: Date; + now: Date; + }): Promise { + return this.prisma.$transaction(async (tx) => { + const orders = await tx.$queryRaw< + { id: bigint; base: bigint; commission: bigint; store_name: string }[] + >` + SELECT o.id, o.settlement_base_amount AS base, COALESCE(o.commission_amount, 0) AS commission, + oi.store_name_snapshot AS store_name + FROM \`order\` o ${FIRST_ITEM_JOIN} + WHERE ${unsettledBefore(args.settledBefore)} AND oi.store_id = ${args.storeId} + ORDER BY o.id + FOR UPDATE OF o`; + if (orders.length === 0) return null; + const existing = await tx.settlement.findUnique({ + where: { + store_id_period_start: { + store_id: args.storeId, + period_start: args.periodStart, + }, + }, + select: { id: true }, + }); + if (existing) return null; + + // raw는 INT UNSIGNED를 bigint로 돌려준다 + const base = orders.reduce((sum, o) => sum + Number(o.base), 0); + const commission = orders.reduce( + (sum, o) => sum + Number(o.commission), + 0, + ); + const settlement = await tx.settlement.create({ + data: { + store_id: args.storeId, + // 가장 최근 주문의 매장명 + store_name_snapshot: orders[orders.length - 1].store_name, + period_start: args.periodStart, + period_end: args.periodEnd, + order_count: orders.length, + settlement_base_amount: base, + commission_amount: commission, + payout_amount: base - commission, + }, + }); + await tx.order.updateMany({ + where: { id: { in: orders.map((o) => o.id) } }, + data: { settlement_id: settlement.id }, + }); + await this.outbox.publish( + tx, + settlementCreatedEvent( + { + settlementId: settlement.id.toString(), + storeId: args.storeId.toString(), + storeName: settlement.store_name_snapshot, + periodStart: formatDateOnly(args.periodStart), + periodEnd: formatDateOnly(args.periodEnd), + orderCount: settlement.order_count, + settlementBaseAmount: base, + commissionAmount: commission, + payoutAmount: settlement.payout_amount, + }, + args.now, + ), + ); + return settlement; + }); + } + + private listWhere(filter: SettlementListFilter): Prisma.SettlementWhereInput { + return { + ...(filter.storeId !== undefined ? { store_id: filter.storeId } : {}), + ...(filter.status ? { status: filter.status } : {}), + ...(filter.periodStart ? { period_start: filter.periodStart } : {}), + }; + } + + /** 최근 생성 순(id 내림차순). */ + async list( + filter: SettlementListFilter & { limit: number; cursor?: bigint }, + ): Promise { + return this.prisma.settlement.findMany({ + where: { + ...this.listWhere(filter), + ...(filter.cursor !== undefined ? { id: { lt: filter.cursor } } : {}), + }, + orderBy: { id: 'desc' }, + take: filter.limit + 1, + }); + } + + async count(filter: SettlementListFilter): Promise { + return this.prisma.settlement.count({ where: this.listWhere(filter) }); + } + + /** storeId를 주면 그 매장 정산만 찾는다. */ + async findDetail( + settlementId: bigint, + storeId?: bigint, + ): Promise { + return this.prisma.settlement.findFirst({ + where: { + id: settlementId, + ...(storeId !== undefined ? { store_id: storeId } : {}), + }, + include: settlementDetailInclude, + }); + } + + /** + * 송금 완료. 그 시점 매장 정산 계좌를 paid_*에 옮겨 적는다(암호문은 같은 용도 키라 그대로 복사). + * 감사에는 끝 4자리만 남긴다. + */ + async markPaid(args: { + settlementId: bigint; + actorAccountId: bigint; + actorLabel: string | null; + note: string | null; + now: Date; + }): Promise { + return this.prisma.$transaction(async (tx) => { + const [locked] = await tx.$queryRaw< + { id: bigint; store_id: bigint; status: SettlementStatus }[] + >`SELECT id, store_id, status FROM settlement WHERE id = ${args.settlementId} FOR UPDATE`; + if (!locked) return { kind: 'not-found' }; + if (locked.status !== SettlementStatus.PENDING) { + return { kind: 'already-paid' }; + } + const account = await tx.storeSettlementAccount.findUnique({ + where: { store_id: locked.store_id }, + }); + if (!account) return { kind: 'account-required' }; + + const paid = await tx.settlement.update({ + where: { id: locked.id }, + data: { + status: SettlementStatus.PAID, + paid_at: args.now, + paid_by_account_id: args.actorAccountId, + paid_by_label_snapshot: args.actorLabel, + paid_note: args.note, + paid_bank_code: account.bank_code, + paid_account_holder: account.account_holder, + paid_account_number_enc: account.account_number_enc, + paid_account_last4: account.account_number_last4, + }, + }); + await this.auditLogs.recordAudit(tx, { + actorAccountId: args.actorAccountId, + storeId: locked.store_id, + targetType: AuditTargetType.SETTLEMENT, + targetId: locked.id, + action: AuditActionType.STATUS_CHANGE, + beforeJson: { status: SettlementStatus.PENDING }, + afterJson: { + status: SettlementStatus.PAID, + payoutAmount: paid.payout_amount, + bank_code: account.bank_code, + account_holder: account.account_holder, + account_number_last4: account.account_number_last4, + note: args.note, + }, + }); + return { kind: 'paid' }; + }); + } + + async countPending(): Promise { + return this.prisma.settlement.count({ + where: { status: SettlementStatus.PENDING }, + }); + } + + /** [from, to)에 정산이 확정된 주문을 매장별로 묶는다. 매장명은 그 달 가장 늦게 확정된 주문의 것. */ + async monthlyCommissions( + from: Date, + to: Date, + ): Promise { + const rows = await this.prisma.$queryRaw< + { + store_id: bigint; + store_name: string; + order_count: bigint; + base: bigint; + commission: bigint; + }[] + >` + SELECT t.store_id, t.store_name, COUNT(*) AS order_count, + CAST(SUM(t.base) AS UNSIGNED) AS base, CAST(SUM(t.commission) AS UNSIGNED) AS commission + FROM ( + SELECT oi.store_id, o.settlement_base_amount AS base, COALESCE(o.commission_amount, 0) AS commission, + FIRST_VALUE(oi.store_name_snapshot) OVER ( + PARTITION BY oi.store_id ORDER BY o.settlement_finalized_at DESC, o.id DESC) AS store_name + FROM \`order\` o ${FIRST_ITEM_JOIN} + WHERE o.settlement_finalized_at >= ${from} AND o.settlement_finalized_at < ${to} + AND o.settlement_base_amount > 0 AND o.deleted_at IS NULL + ) t + GROUP BY t.store_id, t.store_name + ORDER BY t.store_id`; + return rows.map((row) => ({ + storeId: row.store_id, + storeName: row.store_name, + orderCount: Number(row.order_count), + settlementBaseAmount: Number(row.base), + commissionAmount: Number(row.commission), + })); + } +} 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..e8519d91 --- /dev/null +++ b/src/features/order/repositories/store-settlement-account.repository.ts @@ -0,0 +1,106 @@ +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 }, + }); + } + + async findStoreIdsWithAccount(storeIds: bigint[]): Promise> { + if (storeIds.length === 0) return new Set(); + const rows = await this.prisma.storeSettlementAccount.findMany({ + where: { store_id: { in: storeIds } }, + select: { store_id: true }, + }); + return new Set(rows.map((row) => row.store_id)); + } + + /** + * 매장당 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-admin-mutation.resolver.ts b/src/features/order/resolvers/order-admin-mutation.resolver.ts index 48528424..b78d220e 100644 --- a/src/features/order/resolvers/order-admin-mutation.resolver.ts +++ b/src/features/order/resolvers/order-admin-mutation.resolver.ts @@ -2,6 +2,7 @@ import { UseGuards } from '@nestjs/common'; import { Args, Mutation, Resolver } from '@nestjs/graphql'; import { AdminCancelOrderInput } from '@/features/order/dto/inputs/admin-cancel-order.input'; +import { AdminCompleteOrderPickupInput } from '@/features/order/dto/inputs/admin-complete-order-pickup.input'; import { AdminOrderService } from '@/features/order/services/order-admin.service'; import type { AdminOrderSummaryOutput } from '@/features/order/types/order-admin-output.type'; import { @@ -26,4 +27,15 @@ export class AdminOrderMutationResolver { ): Promise { return this.orderService.adminCancelOrder(parseAccountId(user), input); } + + @Mutation('adminCompleteOrderPickup') + adminCompleteOrderPickup( + @CurrentUser() user: JwtUser, + @Args('input') input: AdminCompleteOrderPickupInput, + ): Promise { + return this.orderService.adminCompleteOrderPickup( + parseAccountId(user), + input, + ); + } } 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..7746adef 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'; @@ -17,6 +19,7 @@ import { disconnectTestPrismaClient } from '@/test/db/prisma-test-client'; import { closeTruncateConnection, truncateAll } from '@/test/db/truncate'; import { createAccount, + createOrder, createOrderItem, createUserProfile, } from '@/test/factories'; @@ -37,6 +40,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,10 +85,55 @@ 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'); }); + + it('확정 주문 픽업 완료 경로', async () => { + const actor = await createAccount(prisma, { account_type: 'ADMIN' }); + const user = { + accountId: actor.id.toString(), + accountType: 'ADMIN' as const, + }; + const order = await createOrder(prisma, { status: 'CONFIRMED' }); + await createOrderItem(prisma, { order_id: order.id }); + await createUserProfile(prisma, { account_id: order.account_id }); + + const result = await mutationResolver.adminCompleteOrderPickup(user, { + orderId: order.id.toString(), + note: '매장 인도 확인', + }); + + expect(result.status).toBe('PICKED_UP'); + const detail = await queryResolver.adminOrder(user, order.id.toString()); + expect(detail.statusHistories[0]).toMatchObject({ + toStatus: 'PICKED_UP', + actorType: 'ADMIN', + }); + expect(detail.autoPickupAt).toBeNull(); + }); + + 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/resolvers/order-checkout-mutation.resolver.spec.ts b/src/features/order/resolvers/order-checkout-mutation.resolver.spec.ts index 8dc0094d..bb68507d 100644 --- a/src/features/order/resolvers/order-checkout-mutation.resolver.spec.ts +++ b/src/features/order/resolvers/order-checkout-mutation.resolver.spec.ts @@ -1,30 +1,35 @@ -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 { 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'; import { OrderCheckoutService } from '@/features/order/services/order-checkout.service'; -import { OrderEventsService } from '@/features/order/services/order-events.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'; 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'; import { createAccount, + createPaymentSetting, createProduct, createStore, createUserProfile, } from '@/test/factories'; import { createTestingModuleWithRealDb } from '@/test/modules/testing-module.builder'; import { outboxPublisherProviders } from '@/test/outbox'; +import { s3TestProviders } from '@/test/storage/s3-test.helper'; + +jest.mock('@aws-sdk/s3-request-presigner', () => ({ + getSignedUrl: jest.fn().mockResolvedValue('https://mock-presigned-url.com'), +})); // 2026-09-16(수) 16:00 KST 고정 const NOW = new Date('2026-09-16T07:00:00.000Z'); @@ -40,15 +45,17 @@ describe('OrderCheckout Mutation Resolver (real DB)', () => { providers: [ OrderCheckoutMutationResolver, OrderCheckoutService, + OrderCustomizationService, OrderRepository, + OrderCustomUploadRepository, + ...s3TestProviders(), + 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(), @@ -66,6 +73,8 @@ describe('OrderCheckout Mutation Resolver (real DB)', () => { beforeEach(async () => { await truncateAll(); + // truncateAll이 마이그레이션이 넣은 결제 설정 행까지 지운다 + await createPaymentSetting(prisma); jest.spyOn(clock, 'now').mockReturnValue(NOW); }); @@ -102,13 +111,39 @@ 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'); + 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) }, }); 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/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..b8441136 --- /dev/null +++ b/src/features/order/resolvers/order-deposit-admin.resolver.spec.ts @@ -0,0 +1,95 @@ +// 분기/검증 세부는 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 { RefundRepository } from '@/features/order/repositories/refund.repository'; +import { SettlementRepository } from '@/features/order/repositories/settlement.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, + SettlementRepository, + OrderTransitionRepository, + RefundRepository, + 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, + refundsAwaitingAccount: 0, + refundsAwaitingTransfer: 0, + pendingSettlements: 0, + }); + + 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..e89bb102 --- /dev/null +++ b/src/features/order/resolvers/order-my-mutation.resolver.ts @@ -0,0 +1,47 @@ +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 { SubmitMyRefundAccountInput } from '@/features/order/dto/inputs/submit-my-refund-account.input'; +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), + ); + } + + @Mutation('cancelMyOrder') + cancelMyOrder( + @CurrentUser() user: JwtUser, + @Args('input') input: CancelMyOrderInput, + ): Promise { + return this.orderService.cancelMyOrder(parseAccountId(user), input); + } + + @Mutation('submitMyRefundAccount') + submitMyRefundAccount( + @CurrentUser() user: JwtUser, + @Args('input') input: SubmitMyRefundAccountInput, + ): Promise { + return this.orderService.submitMyRefundAccount(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 7bfba62c..4e743fd8 100644 --- a/src/features/order/resolvers/order-my.resolver.spec.ts +++ b/src/features/order/resolvers/order-my.resolver.spec.ts @@ -1,16 +1,29 @@ +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 { RefundRepository } from '@/features/order/repositories/refund.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 { AccountCipher } from '@/global/crypto/account-cipher.service'; +import { PUB_SUB } from '@/global/pubsub'; +import { createTestAccountCipher } from '@/test/account-cipher'; import { disconnectTestPrismaClient } from '@/test/db/prisma-test-client'; import { closeTruncateConnection, truncateAll } from '@/test/db/truncate'; import { createAccount, createOrder, createOrderItem, + createPayment, createProduct, + createRefund, createStore, createUserProfile, } from '@/test/factories'; @@ -19,20 +32,30 @@ 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, + OrderTransitionRepository, + OrderCancelPolicy, + OrderEventsService, + RefundRepository, + { provide: AccountCipher, useValue: createTestAccountCipher() }, + { provide: PUB_SUB, useValue: new PubSub() }, { provide: AUDIT_LOG_REPOSITORY, useClass: AuditLogRepository }, // 발행 repository가 OutboxPublisher를 주입받는다(08b) ...outboxPublisherProviders(), ], }); resolver = module.get(UserOrderQueryResolver); + mutationResolver = module.get(UserOrderMutationResolver); prisma = p; }); @@ -95,4 +118,80 @@ 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); + }); + + 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, + }, + }); + }); + + it('Mutation.submitMyRefundAccount: 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: 'CANCELED', + }); + const refund = await createRefund(prisma, { order_id: order.id }); + + const result = await mutationResolver.submitMyRefundAccount( + { accountId: account.id.toString() }, + { + refundId: refund.id.toString(), + bankCode: '004', + accountHolder: '홍길동', + accountNumber: '12345678901', + }, + ); + + expect(result.refunds).toEqual([ + expect.objectContaining({ + id: refund.id.toString(), + status: 'AWAITING_TRANSFER', + accountNumberMasked: '****8901', + }), + ]); + }); }); 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..d009711b --- /dev/null +++ b/src/features/order/resolvers/order-payment.resolver.spec.ts @@ -0,0 +1,135 @@ +// 분기/검증 세부는 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 { SettlementRepository } from '@/features/order/repositories/settlement.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'; +import { outboxPublisherProviders } from '@/test/outbox'; + +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, + SettlementRepository, + ...outboxPublisherProviders(), + { 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-refund-admin-mutation.resolver.ts b/src/features/order/resolvers/order-refund-admin-mutation.resolver.ts new file mode 100644 index 00000000..94a752fe --- /dev/null +++ b/src/features/order/resolvers/order-refund-admin-mutation.resolver.ts @@ -0,0 +1,68 @@ +import { UseGuards } from '@nestjs/common'; +import { Args, Mutation, Resolver } from '@nestjs/graphql'; + +import { AdminCompleteRefundInput } from '@/features/order/dto/inputs/admin-complete-refund.input'; +import { AdminCreateDepositReturnInput } from '@/features/order/dto/inputs/admin-create-deposit-return.input'; +import { AdminLinkUnidentifiedDepositInput } from '@/features/order/dto/inputs/admin-link-unidentified-deposit.input'; +import { AdminRecordUnidentifiedDepositInput } from '@/features/order/dto/inputs/admin-record-unidentified-deposit.input'; +import { AdminRefundService } from '@/features/order/services/order-refund-admin.service'; +import type { + AdminDepositRecordOutput, + AdminRefundOutput, +} from '@/features/order/types/order-refund-output.type'; +import { + CurrentUser, + JwtAuthGuard, + Roles, + RolesGuard, + parseAccountId, + type JwtUser, +} from '@/global/auth'; + +@Resolver('Mutation') +@UseGuards(JwtAuthGuard, RolesGuard) +@Roles('ADMIN') +export class AdminRefundMutationResolver { + constructor(private readonly refundService: AdminRefundService) {} + + @Mutation('adminCompleteRefund') + adminCompleteRefund( + @CurrentUser() user: JwtUser, + @Args('input') input: AdminCompleteRefundInput, + ): Promise { + return this.refundService.adminCompleteRefund(parseAccountId(user), input); + } + + @Mutation('adminCreateDepositReturn') + adminCreateDepositReturn( + @CurrentUser() user: JwtUser, + @Args('input') input: AdminCreateDepositReturnInput, + ): Promise { + return this.refundService.adminCreateDepositReturn( + parseAccountId(user), + input, + ); + } + + @Mutation('adminRecordUnidentifiedDeposit') + adminRecordUnidentifiedDeposit( + @CurrentUser() user: JwtUser, + @Args('input') input: AdminRecordUnidentifiedDepositInput, + ): Promise { + return this.refundService.adminRecordUnidentifiedDeposit( + parseAccountId(user), + input, + ); + } + + @Mutation('adminLinkUnidentifiedDeposit') + adminLinkUnidentifiedDeposit( + @CurrentUser() user: JwtUser, + @Args('input') input: AdminLinkUnidentifiedDepositInput, + ): Promise { + return this.refundService.adminLinkUnidentifiedDeposit( + parseAccountId(user), + input, + ); + } +} diff --git a/src/features/order/resolvers/order-refund-admin-query.resolver.ts b/src/features/order/resolvers/order-refund-admin-query.resolver.ts new file mode 100644 index 00000000..c7fbf236 --- /dev/null +++ b/src/features/order/resolvers/order-refund-admin-query.resolver.ts @@ -0,0 +1,55 @@ +import { UseGuards } from '@nestjs/common'; +import { Args, Query, Resolver } from '@nestjs/graphql'; + +import type { CursorConnection } from '@/common/types/cursor-connection.type'; +import { parseId } from '@/common/utils/id-parser'; +import { AdminDepositRecordListInput } from '@/features/order/dto/inputs/admin-deposit-record-list.input'; +import { AdminRefundListInput } from '@/features/order/dto/inputs/admin-refund-list.input'; +import { AdminRefundService } from '@/features/order/services/order-refund-admin.service'; +import type { + AdminDepositRecordOutput, + AdminRefundDetailOutput, + AdminRefundOutput, +} from '@/features/order/types/order-refund-output.type'; +import { + CurrentUser, + JwtAuthGuard, + Roles, + RolesGuard, + parseAccountId, + type JwtUser, +} from '@/global/auth'; + +@Resolver('Query') +@UseGuards(JwtAuthGuard, RolesGuard) +@Roles('ADMIN') +export class AdminRefundQueryResolver { + constructor(private readonly refundService: AdminRefundService) {} + + @Query('adminRefunds') + adminRefunds( + @CurrentUser() user: JwtUser, + @Args('input', { nullable: true }) input?: AdminRefundListInput, + ): Promise> { + return this.refundService.adminRefunds(parseAccountId(user), input); + } + + @Query('adminRefund') + adminRefund( + @CurrentUser() user: JwtUser, + @Args('refundId') refundId: string, + ): Promise { + return this.refundService.adminRefund( + parseAccountId(user), + parseId(refundId), + ); + } + + @Query('adminDepositRecords') + adminDepositRecords( + @CurrentUser() user: JwtUser, + @Args('input', { nullable: true }) input?: AdminDepositRecordListInput, + ): Promise> { + return this.refundService.adminDepositRecords(parseAccountId(user), input); + } +} diff --git a/src/features/order/resolvers/order-refund-admin.resolver.spec.ts b/src/features/order/resolvers/order-refund-admin.resolver.spec.ts new file mode 100644 index 00000000..762e2e0e --- /dev/null +++ b/src/features/order/resolvers/order-refund-admin.resolver.spec.ts @@ -0,0 +1,106 @@ +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 { DepositRecordRepository } from '@/features/order/repositories/deposit-record.repository'; +import { RefundRepository } from '@/features/order/repositories/refund.repository'; +import { AdminRefundMutationResolver } from '@/features/order/resolvers/order-refund-admin-mutation.resolver'; +import { AdminRefundQueryResolver } from '@/features/order/resolvers/order-refund-admin-query.resolver'; +import { AdminRefundService } from '@/features/order/services/order-refund-admin.service'; +import type { PrismaClient } from '@/generated/prisma/client'; +import type { JwtUser } from '@/global/auth'; +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, createOrder, createRefund } from '@/test/factories'; +import { createTestingModuleWithRealDb } from '@/test/modules/testing-module.builder'; +import { outboxPublisherProviders } from '@/test/outbox'; + +// 상세 분기는 order-refund-admin.service.spec. 여기서는 리졸버 → 서비스 → DB 배선과 ID 파싱만 본다. +describe('Admin Refund Resolvers (real DB)', () => { + let queryResolver: AdminRefundQueryResolver; + let mutationResolver: AdminRefundMutationResolver; + let cipher: AccountCipher; + let prisma: PrismaClient; + + beforeAll(async () => { + const { module, prisma: p } = await createTestingModuleWithRealDb({ + providers: [ + AdminRefundQueryResolver, + AdminRefundMutationResolver, + AdminRefundService, + AccountAdminRepository, + RefundRepository, + DepositRecordRepository, + { provide: AUDIT_LOG_REPOSITORY, useClass: AuditLogRepository }, + { provide: AccountCipher, useValue: createTestAccountCipher() }, + ...outboxPublisherProviders(), + ], + }); + queryResolver = module.get(AdminRefundQueryResolver); + mutationResolver = module.get(AdminRefundMutationResolver); + cipher = module.get(AccountCipher); + 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 refund = await createRefund(prisma, { + status: 'AWAITING_TRANSFER', + account_number_enc: cipher.encrypt('12345678', 'refund-account'), + }); + + const list = await queryResolver.adminRefunds(user, {}); + expect(list.items.map((i) => i.id)).toEqual([refund.id.toString()]); + await expect( + queryResolver.adminRefund(user, refund.id.toString()), + ).resolves.toMatchObject({ + refund: { id: refund.id.toString() }, + accountNumber: '12345678', + }); + + await expect( + mutationResolver.adminCompleteRefund(user, { + refundId: refund.id.toString(), + }), + ).resolves.toMatchObject({ status: 'COMPLETED' }); + }); + + it('입금 반환·종결·연결 mutation과 입금 기록 목록이 이어진다', async () => { + const admin = await createAccount(prisma, { account_type: 'ADMIN' }); + const user = { accountId: admin.id.toString() } as JwtUser; + const order = await createOrder(prisma, { status: 'CANCELED' }); + + const returned = await mutationResolver.adminCreateDepositReturn(user, { + orderId: order.id.toString(), + amount: 10_000, + depositorName: '차차', + }); + const closed = await mutationResolver.adminRecordUnidentifiedDeposit(user, { + amount: 20_000, + depositorName: '모르는분', + note: '주문 없음', + }); + const linked = await mutationResolver.adminLinkUnidentifiedDeposit(user, { + depositRecordId: closed.id, + orderId: order.id.toString(), + }); + + expect(returned.kind).toBe('RETURN'); + expect(linked).toMatchObject({ id: closed.id, kind: 'RETURN' }); + const records = await queryResolver.adminDepositRecords(user, { + kind: 'RETURN', + }); + expect(records.totalCount).toBe(2); + }); +}); 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-pickup-mutation.resolver.ts b/src/features/order/resolvers/order-seller-pickup-mutation.resolver.ts new file mode 100644 index 00000000..dd6b44c0 --- /dev/null +++ b/src/features/order/resolvers/order-seller-pickup-mutation.resolver.ts @@ -0,0 +1,32 @@ +import { UseGuards } from '@nestjs/common'; +import { Args, Mutation, Resolver } from '@nestjs/graphql'; + +import { SellerRescheduleOrderPickupInput } from '@/features/order/dto/inputs/seller-reschedule-order-pickup.input'; +import { SellerOrderPickupService } from '@/features/order/services/order-seller-pickup.service'; +import type { SellerOrderSummaryOutput } from '@/features/order/types/order-seller-output.type'; +import { + CurrentUser, + JwtAuthGuard, + Roles, + RolesGuard, + parseAccountId, + type JwtUser, +} from '@/global/auth'; + +@Resolver('Mutation') +@UseGuards(JwtAuthGuard, RolesGuard) +@Roles('SELLER') +export class SellerOrderPickupMutationResolver { + constructor(private readonly pickupService: SellerOrderPickupService) {} + + @Mutation('sellerRescheduleOrderPickup') + sellerRescheduleOrderPickup( + @CurrentUser() user: JwtUser, + @Args('input') input: SellerRescheduleOrderPickupInput, + ): Promise { + return this.pickupService.sellerRescheduleOrderPickup( + parseAccountId(user), + input, + ); + } +} diff --git a/src/features/order/resolvers/order-seller-pickup-query.resolver.ts b/src/features/order/resolvers/order-seller-pickup-query.resolver.ts new file mode 100644 index 00000000..ce7a6ab5 --- /dev/null +++ b/src/features/order/resolvers/order-seller-pickup-query.resolver.ts @@ -0,0 +1,47 @@ +import { UseGuards } from '@nestjs/common'; +import { Args, Query, Resolver } from '@nestjs/graphql'; + +import { parseId } from '@/common/utils/id-parser'; +import { SellerOrderPickupService } from '@/features/order/services/order-seller-pickup.service'; +import type { PickupCalendar, PickupTimeSlots } from '@/features/store'; +import { + CurrentUser, + JwtAuthGuard, + Roles, + RolesGuard, + parseAccountId, + type JwtUser, +} from '@/global/auth'; + +@Resolver('Query') +@UseGuards(JwtAuthGuard, RolesGuard) +@Roles('SELLER') +export class SellerOrderPickupQueryResolver { + constructor(private readonly pickupService: SellerOrderPickupService) {} + + @Query('sellerOrderPickupCalendar') + sellerOrderPickupCalendar( + @CurrentUser() user: JwtUser, + @Args('orderId') orderId: string, + @Args('yearMonth') yearMonth: string, + ): Promise { + return this.pickupService.sellerOrderPickupCalendar( + parseAccountId(user), + parseId(orderId), + yearMonth, + ); + } + + @Query('sellerOrderPickupTimeSlots') + sellerOrderPickupTimeSlots( + @CurrentUser() user: JwtUser, + @Args('orderId') orderId: string, + @Args('date') date: string, + ): Promise { + return this.pickupService.sellerOrderPickupTimeSlots( + parseAccountId(user), + parseId(orderId), + date, + ); + } +} diff --git a/src/features/order/resolvers/order-seller-pickup.resolver.spec.ts b/src/features/order/resolvers/order-seller-pickup.resolver.spec.ts new file mode 100644 index 00000000..905ea2c9 --- /dev/null +++ b/src/features/order/resolvers/order-seller-pickup.resolver.spec.ts @@ -0,0 +1,126 @@ +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 { OrderStatusTransitionPolicy } from '@/features/order/policies/order-status-transition.policy'; +import { OrderPickupChangeRepository } from '@/features/order/repositories/order-pickup-change.repository'; +import { OrderRepository } from '@/features/order/repositories/order.repository'; +import { SellerOrderPickupMutationResolver } from '@/features/order/resolvers/order-seller-pickup-mutation.resolver'; +import { SellerOrderPickupQueryResolver } from '@/features/order/resolvers/order-seller-pickup-query.resolver'; +import { OrderEventsService } from '@/features/order/services/order-events.service'; +import { SellerOrderPickupService } from '@/features/order/services/order-seller-pickup.service'; +import { StoreSellerRepository } from '@/features/store/repositories/store-seller.repository'; +import { StoreRepository } from '@/features/store/repositories/store.repository'; +import { StorePickupScheduleService } from '@/features/store/services/store-pickup-schedule.service'; +import type { PrismaClient } from '@/generated/prisma/client'; +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'; +import { + createOrder, + createOrderItem, + setupSellerWithStore, +} from '@/test/factories'; +import { createTestingModuleWithRealDb } from '@/test/modules/testing-module.builder'; +import { outboxPublisherProviders } from '@/test/outbox'; + +// 2026-09-16(수) 16:00 KST +const NOW = new Date('2026-09-16T07:00:00.000Z'); + +describe('Seller Order Pickup Resolvers (real DB)', () => { + let queryResolver: SellerOrderPickupQueryResolver; + let mutationResolver: SellerOrderPickupMutationResolver; + let prisma: PrismaClient; + + beforeAll(async () => { + const { module, prisma: p } = await createTestingModuleWithRealDb({ + providers: [ + SellerOrderPickupQueryResolver, + SellerOrderPickupMutationResolver, + SellerOrderPickupService, + StoreSellerRepository, + StoreRepository, + StorePickupScheduleService, + OrderRepository, + OrderPickupChangeRepository, + OrderStatusTransitionPolicy, + OrderEventsService, + { provide: PUB_SUB, useValue: new PubSub() }, + { provide: AUDIT_LOG_REPOSITORY, useClass: AuditLogRepository }, + { provide: ClockService, useValue: { now: () => NOW } }, + ...bookedQuantityProviders(), + ...outboxPublisherProviders({ clock: true }), + ], + }); + queryResolver = module.get(SellerOrderPickupQueryResolver); + mutationResolver = module.get(SellerOrderPickupMutationResolver); + prisma = p; + }); + + afterAll(async () => { + await closeTruncateConnection(); + await disconnectTestPrismaClient(); + }); + + beforeEach(async () => { + await truncateAll(); + }); + + async function confirmedOrder() { + const me = await setupSellerWithStore(prisma); + await prisma.storeBusinessHour.createMany({ + data: Array.from({ length: 7 }, (_, dayOfWeek) => ({ + store_id: me.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)), + })), + }); + const order = await createOrder(prisma, { + status: 'CONFIRMED', + pickup_at: new Date('2026-09-18T05:00:00.000Z'), + }); + await createOrderItem(prisma, { + order_id: order.id, + store_id: me.store.id, + }); + return { user: { accountId: me.account.id.toString() }, order }; + } + + it('Query.sellerOrderPickupCalendar·TimeSlots: ID를 파싱해 변경 시트 달력과 슬롯을 준다', async () => { + const { user, order } = await confirmedOrder(); + + const calendar = await queryResolver.sellerOrderPickupCalendar( + user, + order.id.toString(), + '2026-09', + ); + const slots = await queryResolver.sellerOrderPickupTimeSlots( + user, + order.id.toString(), + '2026-09-17', + ); + + expect(calendar.yearMonth).toBe('2026-09'); + expect(calendar.days.find((d) => d.date === '2026-09-17')?.selectable).toBe( + true, + ); + expect(slots.date).toBe('2026-09-17'); + expect(slots.morning.length).toBeGreaterThan(0); + }); + + it('Mutation.sellerRescheduleOrderPickup: 픽업 일시를 바꾸고 요약을 반환한다', async () => { + const { user, order } = await confirmedOrder(); + const pickupAt = new Date('2026-09-17T06:30:00.000Z'); + + const result = await mutationResolver.sellerRescheduleOrderPickup(user, { + orderId: order.id.toString(), + pickupAt, + }); + + expect(result).toMatchObject({ id: order.id.toString(), pickupAt }); + }); +}); 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/resolvers/order-settlement-admin-mutation.resolver.ts b/src/features/order/resolvers/order-settlement-admin-mutation.resolver.ts new file mode 100644 index 00000000..73232325 --- /dev/null +++ b/src/features/order/resolvers/order-settlement-admin-mutation.resolver.ts @@ -0,0 +1,32 @@ +import { UseGuards } from '@nestjs/common'; +import { Args, Mutation, Resolver } from '@nestjs/graphql'; + +import { AdminMarkSettlementPaidInput } from '@/features/order/dto/inputs/admin-mark-settlement-paid.input'; +import { AdminSettlementService } from '@/features/order/services/order-settlement-admin.service'; +import type { AdminSettlementDetailOutput } from '@/features/order/types/order-settlement-output.type'; +import { + CurrentUser, + JwtAuthGuard, + Roles, + RolesGuard, + parseAccountId, + type JwtUser, +} from '@/global/auth'; + +@Resolver('Mutation') +@UseGuards(JwtAuthGuard, RolesGuard) +@Roles('ADMIN') +export class AdminSettlementMutationResolver { + constructor(private readonly settlementService: AdminSettlementService) {} + + @Mutation('adminMarkSettlementPaid') + adminMarkSettlementPaid( + @CurrentUser() user: JwtUser, + @Args('input') input: AdminMarkSettlementPaidInput, + ): Promise { + return this.settlementService.adminMarkSettlementPaid( + parseAccountId(user), + input, + ); + } +} diff --git a/src/features/order/resolvers/order-settlement-admin-query.resolver.ts b/src/features/order/resolvers/order-settlement-admin-query.resolver.ts new file mode 100644 index 00000000..4d1e7681 --- /dev/null +++ b/src/features/order/resolvers/order-settlement-admin-query.resolver.ts @@ -0,0 +1,58 @@ +import { UseGuards } from '@nestjs/common'; +import { Args, Query, Resolver } from '@nestjs/graphql'; + +import type { CursorConnection } from '@/common/types/cursor-connection.type'; +import { parseId } from '@/common/utils/id-parser'; +import { AdminMonthlyCommissionInput } from '@/features/order/dto/inputs/admin-monthly-commission.input'; +import { AdminSettlementListInput } from '@/features/order/dto/inputs/admin-settlement-list.input'; +import { AdminSettlementService } from '@/features/order/services/order-settlement-admin.service'; +import type { + AdminMonthlyCommissionReportOutput, + AdminSettlementDetailOutput, + AdminSettlementSummaryOutput, +} from '@/features/order/types/order-settlement-output.type'; +import { + CurrentUser, + JwtAuthGuard, + Roles, + RolesGuard, + parseAccountId, + type JwtUser, +} from '@/global/auth'; + +@Resolver('Query') +@UseGuards(JwtAuthGuard, RolesGuard) +@Roles('ADMIN') +export class AdminSettlementQueryResolver { + constructor(private readonly settlementService: AdminSettlementService) {} + + @Query('adminSettlements') + adminSettlements( + @CurrentUser() user: JwtUser, + @Args('input', { nullable: true }) input?: AdminSettlementListInput, + ): Promise> { + return this.settlementService.adminSettlements(parseAccountId(user), input); + } + + @Query('adminSettlement') + adminSettlement( + @CurrentUser() user: JwtUser, + @Args('settlementId') settlementId: string, + ): Promise { + return this.settlementService.adminSettlement( + parseAccountId(user), + parseId(settlementId), + ); + } + + @Query('adminMonthlyCommissions') + adminMonthlyCommissions( + @CurrentUser() user: JwtUser, + @Args('input') input: AdminMonthlyCommissionInput, + ): Promise { + return this.settlementService.adminMonthlyCommissions( + parseAccountId(user), + input, + ); + } +} 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..58935bf0 --- /dev/null +++ b/src/features/order/resolvers/order-settlement-seller-query.resolver.ts @@ -0,0 +1,56 @@ +import { UseGuards } from '@nestjs/common'; +import { Args, Query, Resolver } from '@nestjs/graphql'; + +import type { CursorConnection } from '@/common/types/cursor-connection.type'; +import { parseId } from '@/common/utils/id-parser'; +import { SellerSettlementListInput } from '@/features/order/dto/inputs/seller-settlement-list.input'; +import { SellerSettlementService } from '@/features/order/services/order-settlement-seller.service'; +import type { SellerSettlementAccountOutput } from '@/features/order/types/order-payment-output.type'; +import type { + SellerSettlementDetailOutput, + SellerSettlementSummaryOutput, +} from '@/features/order/types/order-settlement-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)); + } + + @Query('sellerSettlements') + sellerSettlements( + @CurrentUser() user: JwtUser, + @Args('input', { nullable: true }) input?: SellerSettlementListInput, + ): Promise> { + return this.settlementService.sellerSettlements( + parseAccountId(user), + input, + ); + } + + @Query('sellerSettlement') + sellerSettlement( + @CurrentUser() user: JwtUser, + @Args('settlementId') settlementId: string, + ): Promise { + return this.settlementService.sellerSettlement( + parseAccountId(user), + parseId(settlementId), + ); + } +} diff --git a/src/features/order/resolvers/order-settlement.resolver.spec.ts b/src/features/order/resolvers/order-settlement.resolver.spec.ts new file mode 100644 index 00000000..7d47dca2 --- /dev/null +++ b/src/features/order/resolvers/order-settlement.resolver.spec.ts @@ -0,0 +1,131 @@ +// 분기/검증 세부는 order-settlement-admin.service.spec.ts·order-settlement-seller.service.spec.ts에서 담당. 여기서는 리졸버→서비스→DB 경로만 본다. + +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 { SettlementRepository } from '@/features/order/repositories/settlement.repository'; +import { StoreSettlementAccountRepository } from '@/features/order/repositories/store-settlement-account.repository'; +import { AdminSettlementMutationResolver } from '@/features/order/resolvers/order-settlement-admin-mutation.resolver'; +import { AdminSettlementQueryResolver } from '@/features/order/resolvers/order-settlement-admin-query.resolver'; +import { SellerSettlementQueryResolver } from '@/features/order/resolvers/order-settlement-seller-query.resolver'; +import { AdminSettlementService } from '@/features/order/services/order-settlement-admin.service'; +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 type { JwtUser } from '@/global/auth'; +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, + createFinalizedOrder, + createSettlement, + setupSellerWithStore, +} from '@/test/factories'; +import { createTestingModuleWithRealDb } from '@/test/modules/testing-module.builder'; +import { outboxPublisherProviders } from '@/test/outbox'; + +describe('주간 정산 Resolvers (real DB)', () => { + let adminQuery: AdminSettlementQueryResolver; + let adminMutation: AdminSettlementMutationResolver; + let sellerQuery: SellerSettlementQueryResolver; + let cipher: AccountCipher; + let prisma: PrismaClient; + + beforeAll(async () => { + const { module, prisma: p } = await createTestingModuleWithRealDb({ + providers: [ + AdminSettlementQueryResolver, + AdminSettlementMutationResolver, + SellerSettlementQueryResolver, + AdminSettlementService, + SellerSettlementService, + AccountAdminRepository, + StoreSellerRepository, + SettlementRepository, + StoreSettlementAccountRepository, + ClockService, + { provide: AUDIT_LOG_REPOSITORY, useClass: AuditLogRepository }, + { provide: AccountCipher, useValue: createTestAccountCipher() }, + ...outboxPublisherProviders({ clock: true }), + ], + }); + adminQuery = module.get(AdminSettlementQueryResolver); + adminMutation = module.get(AdminSettlementMutationResolver); + sellerQuery = module.get(SellerSettlementQueryResolver); + cipher = module.get(AccountCipher); + prisma = p; + }); + + afterAll(async () => { + await closeTruncateConnection(); + await disconnectTestPrismaClient(); + }); + + beforeEach(async () => { + await truncateAll(); + }); + + it('판매자 정산 내역 → 관리자 목록·상세 → 송금 완료 → 판매자 상세·월 집계를 ID 문자열로 잇는다', async () => { + const { account: seller, store } = await setupSellerWithStore(prisma); + const sellerUser = { accountId: seller.id.toString() } as JwtUser; + const admin = await createAccount(prisma, { account_type: 'ADMIN' }); + const adminUser = { accountId: admin.id.toString() } as JwtUser; + await prisma.storeSettlementAccount.create({ + data: { + store_id: store.id, + bank_code: '090', + account_holder: '홍길동', + account_number_enc: cipher.encrypt( + '33330123455678', + 'settlement-account', + ), + account_number_last4: '5678', + updated_by_account_id: seller.id, + updated_by_role: 'SELLER', + }, + }); + const order = await createFinalizedOrder(prisma, { + store_id: store.id, + finalized_at: new Date('2026-11-12T05:00:00.000Z'), + }); + const settlement = await createSettlement(prisma, { store_id: store.id }); + await prisma.order.update({ + where: { id: order.id }, + data: { settlement_id: settlement.id }, + }); + const id = settlement.id.toString(); + + const mine = await sellerQuery.sellerSettlements(sellerUser, {}); + expect(mine.items.map((i) => i.id)).toEqual([id]); + const list = await adminQuery.adminSettlements(adminUser, { + storeId: store.id.toString(), + }); + expect(list.items).toEqual([ + expect.objectContaining({ id, accountRegistered: true }), + ]); + await expect( + adminQuery.adminSettlement(adminUser, id), + ).resolves.toMatchObject({ + id, + currentAccount: { accountNumber: '33330123455678' }, + }); + + await expect( + adminMutation.adminMarkSettlementPaid(adminUser, { settlementId: id }), + ).resolves.toMatchObject({ id, status: 'PAID' }); + + await expect( + sellerQuery.sellerSettlement(sellerUser, id), + ).resolves.toMatchObject({ + status: 'PAID', + paidAccount: { accountNumberMasked: '****5678' }, + orders: [expect.objectContaining({ orderId: order.id.toString() })], + }); + await expect( + adminQuery.adminMonthlyCommissions(adminUser, { month: '2026-11' }), + ).resolves.toMatchObject({ orderCount: 1, settlementBaseAmount: 10_000 }); + }); +}); 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..8ebd61ae --- /dev/null +++ b/src/features/order/services/order-admin-alert-messages.helper.ts @@ -0,0 +1,114 @@ +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 { RefundEventPayload } from '@/features/order/events/refund-requested.event'; +import type { SettlementCreatedPayload } from '@/features/order/events/settlement-created.event'; +import { RefundKind } from '@/generated/prisma/client'; +import type { AlertMessage } from '@/global/alerting'; + +const REFUND_KIND_LABELS: Record = { + [RefundKind.CANCEL]: '취소 환불', + [RefundKind.DEPOSIT_RETURN]: '입금 반환', +}; + +/** 관리자 웹 처리 화면 링크. 주소가 설정되지 않았으면 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)), + }; +} + +/** 환불 계좌가 들어와 송금할 차례(취소와 함께 입력·나중에 입력·덮어쓰기). 계좌번호는 싣지 않는다. */ +export function buildRefundReadyAlert( + p: RefundEventPayload, + baseUrl: string | null, +): AlertMessage { + const link = adminTaskLink(baseUrl, '/tasks/refunds', { + refundId: p.refundId, + }); + return { + level: 'info', + title: '환불 송금 대기', + key: `refund-ready:${p.refundId}`, + detail: [ + `주문 ${p.orderNumber}`, + `${p.amount.toLocaleString('ko-KR')}원 · ${REFUND_KIND_LABELS[p.kind]}`, + ...(link ? [link] : []), + ].join('\n'), + }; +} + +/** 매장별 이벤트를 주 단위 key로 묶어 억제 창 안에서 한 번만 보낸다 — 매장별 금액은 처리 화면에서 본다. */ +export function buildSettlementCreatedAlert( + p: SettlementCreatedPayload, + baseUrl: string | null, +): AlertMessage { + const link = adminTaskLink(baseUrl, '/tasks/settlements', { + periodStart: p.periodStart, + }); + return { + level: 'info', + title: '주간 정산 생성', + key: `settlement-week:${p.periodStart}`, + detail: [ + `${p.periodStart} ~ ${p.periodEnd} 정산이 생성됐어요. 매장별 정산을 확인하고 송금해 주세요.`, + ...(link ? [link] : []), + ].join('\n'), + }; +} 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..fa637668 --- /dev/null +++ b/src/features/order/services/order-admin-alert.consumer.spec.ts @@ -0,0 +1,317 @@ +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 { REFUND_ACCOUNT_SUBMITTED } from '@/features/order/events/refund-account-submitted.event'; +import { REFUND_REQUESTED } from '@/features/order/events/refund-requested.event'; +import { SETTLEMENT_CREATED } from '@/features/order/events/settlement-created.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: '홍길동', +}; +const REFUND = { + refundId: '9', + orderId: '42', + orderNumber: 'ORD-20260916-ABC234', + buyerAccountId: '3', + kind: 'CANCEL', + amount: 30000, + storeId: '2', + storeName: '케이크샵', + productId: '5', + productName: '레터링 케이크', +}; + +const SETTLED = { + settlementId: '5', + storeId: '9', + storeName: '해즈 케이크', + periodStart: '2026-11-09', + periodEnd: '2026-11-15', + orderCount: 3, + settlementBaseAmount: 90_000, + commissionAmount: 4_995, + payoutAmount: 85_005, +}; + +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('주간 정산 생성: info, 주 단위 key, 기간·처리 화면 링크(periodStart)', async () => { + const consumer = build({ baseUrl: 'https://admin.caquick.com' }); + + await consumer.handle(event(SETTLEMENT_CREATED, SETTLED)); + + expect(transport).toHaveBeenCalledWith( + expect.any(String), + { + level: 'info', + title: '주간 정산 생성', + key: 'settlement-week:2026-11-09', + detail: [ + '2026-11-09 ~ 2026-11-15 정산이 생성됐어요. 매장별 정산을 확인하고 송금해 주세요.', + 'https://admin.caquick.com/tasks/settlements?periodStart=2026-11-09', + ].join('\n'), + }, + expect.any(Object), + ); + }); + + it('같은 주의 매장별 정산 이벤트는 억제 창 안에서 한 번만 보내고, 다른 주는 따로 보낸다', async () => { + const consumer = build({ baseUrl: null }); + + await consumer.handle(event(SETTLEMENT_CREATED, SETTLED)); + await consumer.handle( + event(SETTLEMENT_CREATED, { + ...SETTLED, + settlementId: '6', + storeId: '10', + }), + ); + await consumer.handle( + event(SETTLEMENT_CREATED, { + ...SETTLED, + settlementId: '7', + periodStart: '2026-11-16', + periodEnd: '2026-11-22', + }), + ); + + expect( + transport.mock.calls.map(([, m]) => (m as { key: string }).key), + ).toEqual(['settlement-week:2026-11-09', 'settlement-week:2026-11-16']); + }); + + it.each([ + [ + '취소와 함께 계좌 입력', + REFUND_REQUESTED, + { ...REFUND, accountSubmitted: true }, + ], + ['나중에 계좌 입력', REFUND_ACCOUNT_SUBMITTED, REFUND], + ])( + '환불 송금 대기(%s): info, 환불별 key, 금액·종류·처리 화면 링크(계좌번호 없음)', + async (_label, type, payload) => { + const consumer = build({ baseUrl: 'https://admin.caquick.com' }); + + await consumer.handle(event(type, payload)); + + expect(transport).toHaveBeenCalledWith( + expect.any(String), + { + level: 'info', + title: '환불 송금 대기', + key: 'refund-ready:9', + detail: [ + '주문 ORD-20260916-ABC234', + '30,000원 · 취소 환불', + 'https://admin.caquick.com/tasks/refunds?refundId=9', + ].join('\n'), + }, + expect.any(Object), + ); + }, + ); + + it('계좌가 없는 환불 생성은 관리자에게 보내지 않는다(구매자 계좌 요청 알림만 간다)', async () => { + const consumer = build({ baseUrl: null }); + + await consumer.handle(event(REFUND_REQUESTED, REFUND)); + await consumer.handle( + event(REFUND_REQUESTED, { ...REFUND, accountSubmitted: false }), + ); + + expect(transport).not.toHaveBeenCalled(); + }); + + it('같은 환불의 계좌 덮어쓰기는 억제 창 안에서 한 번만, 입금 반환은 종류를 다르게 적는다', async () => { + const consumer = build({ baseUrl: null }); + + await consumer.handle(event(REFUND_ACCOUNT_SUBMITTED, REFUND)); + await consumer.handle(event(REFUND_ACCOUNT_SUBMITTED, REFUND)); + await consumer.handle( + event(REFUND_ACCOUNT_SUBMITTED, { + ...REFUND, + refundId: '10', + kind: 'DEPOSIT_RETURN', + }), + ); + + const messages = transport.mock.calls.map( + ([, m]) => m as { key: string; detail: string }, + ); + expect(messages.map((m) => m.key)).toEqual([ + 'refund-ready:9', + 'refund-ready:10', + ]); + expect(messages[1].detail).toBe( + ['주문 ORD-20260916-ABC234', '30,000원 · 입금 반환'].join('\n'), + ); + }); + + it.each([ + [REFUND_REQUESTED, { ...REFUND, kind: 'CHARGEBACK' }], + [REFUND_ACCOUNT_SUBMITTED, { ...REFUND, amount: '30000' }], + [SETTLEMENT_CREATED, { ...SETTLED, periodStart: 20261109 }], + [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..3e0983f1 --- /dev/null +++ b/src/features/order/services/order-admin-alert.consumer.ts @@ -0,0 +1,93 @@ +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 { + parseRefundAccountSubmittedPayload, + REFUND_ACCOUNT_SUBMITTED, +} from '@/features/order/events/refund-account-submitted.event'; +import { + parseRefundRequestedPayload, + REFUND_REQUESTED, +} from '@/features/order/events/refund-requested.event'; +import { + parseSettlementCreatedPayload, + SETTLEMENT_CREATED, +} from '@/features/order/events/settlement-created.event'; +import { + buildDepositClaimedAlert, + buildDepositPendingAlert, + buildRefundReadyAlert, + buildSettlementCreatedAlert, +} 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, + REFUND_REQUESTED, + REFUND_ACCOUNT_SUBMITTED, + SETTLEMENT_CREATED, +) +export class OrderAdminAlertConsumer implements OutboxConsumer { + constructor( + private readonly alerts: AlertService, + private readonly config: ConfigService, + ) {} + + async handle(event: OutboxEvent): Promise { + const message = this.messageOf(event); + if (message) await this.alerts.notify(message); + } + + private messageOf(event: OutboxEvent): AlertMessage | null { + 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, + ); + case REFUND_REQUESTED: { + const p = parseRefundRequestedPayload(event.payload); + // 계좌가 아직 없으면 구매자 계좌 요청 알림만 간다(알림 소비자) + return p.accountSubmitted ? buildRefundReadyAlert(p, baseUrl) : null; + } + case REFUND_ACCOUNT_SUBMITTED: + return buildRefundReadyAlert( + parseRefundAccountSubmittedPayload(event.payload), + baseUrl, + ); + case SETTLEMENT_CREATED: + return buildSettlementCreatedAlert( + parseSettlementCreatedPayload(event.payload), + baseUrl, + ); + default: + throw new Error(`구독하지 않은 outbox 이벤트: ${event.eventType}`); + } + } +} diff --git a/src/features/order/services/order-admin-mappers.helper.ts b/src/features/order/services/order-admin-mappers.helper.ts index b1f937b7..722c08ba 100644 --- a/src/features/order/services/order-admin-mappers.helper.ts +++ b/src/features/order/services/order-admin-mappers.helper.ts @@ -4,10 +4,18 @@ import type { AdminOrderRow, } from '@/features/order/repositories/order.repository'; import { + toOrderAutoTransitionTimes, + toOrderCancellation, toOrderItemDetail, + toOrderPickupChange, + toOrderRefund, + toOrderListCustomBadge, toOrderStatusHistory, } from '@/features/order/services/order-output-mappers.helper'; +import { toAdminOrderPaymentOutput } from '@/features/order/services/order-payment-mappers.helper'; +import { toOrderSettlementFields } from '@/features/order/services/order-settlement-mappers.helper'; import type { + AdminOrderCancelOptionsOutput, AdminOrderDetailOutput, AdminOrderSummaryOutput, } from '@/features/order/types/order-admin-output.type'; @@ -30,11 +38,13 @@ 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]), }; } export function toAdminOrderDetailOutput( row: AdminOrderDetailRow, + cancelOptions: AdminOrderCancelOptionsOutput, ): AdminOrderDetailOutput { const profile = row.account.user_profile; return { @@ -51,6 +61,8 @@ export function toAdminOrderDetailOutput( pickupAt: row.pickup_at, 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, @@ -63,5 +75,13 @@ 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, + ...toOrderAutoTransitionTimes(row), + pickupChanges: row.pickup_changes.map(toOrderPickupChange), + ...toOrderSettlementFields(row), + settlementFinalizedAt: row.settlement_finalized_at, + settlementId: row.settlement_id?.toString() ?? null, }; } diff --git a/src/features/order/services/order-admin.service.spec.ts b/src/features/order/services/order-admin.service.spec.ts index 37d3ef03..cbeb48fb 100644 --- a/src/features/order/services/order-admin.service.spec.ts +++ b/src/features/order/services/order-admin.service.spec.ts @@ -1,18 +1,23 @@ import { BadRequestException } from '@nestjs/common'; 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 type { AdminCancelOrderInput } from '@/features/order/dto/inputs/admin-cancel-order.input'; +import type { AdminCompleteOrderPickupInput } from '@/features/order/dto/inputs/admin-complete-order-pickup.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'; 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'; @@ -20,7 +25,10 @@ import { createAccount, createOrder, createOrderItem, + createPayment, + createSettlement, createStore, + createThreeDOrderItemCustom, createUserProfile, } from '@/test/factories'; import { createTestingModuleWithRealDb } from '@/test/modules/testing-module.builder'; @@ -37,6 +45,7 @@ describe('AdminOrderService (real DB)', () => { let prisma: PrismaClient; let dispatcher: OutboxDispatcherService; let pubSub: PubSub; + let clock: ClockService; beforeAll(async () => { const { module, prisma: p } = await createTestingModuleWithRealDb({ @@ -46,6 +55,8 @@ describe('AdminOrderService (real DB)', () => { AccountAdminRepository, OrderRepository, OrderStatusTransitionPolicy, + OrderCancelPolicy, + OrderTransitionRepository, { provide: AUDIT_LOG_REPOSITORY, useClass: AuditLogRepository }, OrderEventsService, // 발행-구독 왕복은 실 Redis spec(events service) 담당 — 여기선 in-memory @@ -60,6 +71,7 @@ describe('AdminOrderService (real DB)', () => { orderRepo = module.get(OrderRepository); dispatcher = module.get(OutboxDispatcherService); pubSub = module.get(PUB_SUB); + clock = module.get(ClockService); prisma = p; }); @@ -72,16 +84,23 @@ describe('AdminOrderService (real DB)', () => { await truncateAll(); }); + afterEach(() => { + jest.restoreAllMocks(); + }); + async function admin(): Promise { return (await createAccount(prisma, { account_type: 'ADMIN' })).id; } async function orderWithItem( overrides: { - status?: 'SUBMITTED' | 'CONFIRMED' | 'MADE' | 'PICKED_UP' | 'CANCELED'; + status?: OrderStatus; storeId?: bigint; buyerName?: string; orderNumber?: string; + submittedAt?: Date | null; + /** 확인된 결제(입금 대기면 PENDING 결제)를 함께 만든다 */ + paid?: boolean; } = {}, ) { const buyer = await createAccount(prisma, { account_type: 'USER' }); @@ -97,14 +116,30 @@ 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, 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({ @@ -222,20 +257,194 @@ 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', () => { + 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('삭제된 주문과 이 매장 품목이 삭제된 주문은 세지 않는다', 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( + service.adminStoreInProgressOrderSummary(user.id, 1n), + ).rejects.toThrowDomain(403); + }); }); describe('adminOrder', () => { 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', + }, + }); + 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, @@ -244,6 +453,228 @@ 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.each([ + ['SUBMITTED', true, false], + ['MADE', false, true], + ['NO_SHOW', false, false], + ] as const)( + '%s: 확정 마감은 접수만, 자동 픽업 완료는 확정·제작 완료만, 노쇼 시각은 그대로 준다', + async (status, hasDeadline, hasAutoPickup) => { + const { order } = await orderWithItem({ status }); + const deadline = new Date('2026-11-19T06:00:00.000Z'); + const noShowAt = new Date('2026-11-19T07:00:00.000Z'); + await prisma.order.update({ + where: { id: order.id }, + data: { + pickup_at: new Date('2026-11-19T04:00:00.000Z'), + confirm_deadline_at: deadline, + no_show_at: status === 'NO_SHOW' ? noShowAt : null, + }, + }); + + const result = await service.adminOrder(await admin(), order.id); + + expect(result).toMatchObject({ + confirmDeadlineAt: hasDeadline ? deadline : null, + autoPickupAt: hasAutoPickup + ? new Date('2026-11-20T04:00:00.000Z') + : null, + noShowAt: status === 'NO_SHOW' ? noShowAt : null, + }); + }, + ); + + it('판매자 픽업 일시 변경 이력을 준다(없으면 빈 배열)', async () => { + const { order } = await orderWithItem({ status: 'CONFIRMED' }); + const seller = await createAccount(prisma, { account_type: 'SELLER' }); + expect( + (await service.adminOrder(await admin(), order.id)).pickupChanges, + ).toEqual([]); + const change = await prisma.orderPickupChange.create({ + data: { + order_id: order.id, + from_pickup_at: order.pickup_at, + to_pickup_at: new Date('2026-09-21T05:00:00.000Z'), + changed_by_account_id: seller.id, + changed_at: new Date('2026-09-17T00:00:00.000Z'), + }, + }); + + const result = await service.adminOrder(await admin(), order.id); + + expect(result.pickupChanges).toEqual([ + { + id: change.id.toString(), + fromPickupAt: order.pickup_at, + toPickupAt: change.to_pickup_at, + changedAt: change.changed_at, + note: null, + }, + ]); + }); + + it('수수료·정산 확정과 묶인 주간 정산을 준다', async () => { + const { order, storeId } = await orderWithItem({ + status: 'PICKED_UP', + paid: true, + }); + expect(await service.adminOrder(await admin(), order.id)).toMatchObject({ + commissionRateBps: 0, + expectedPayoutAmount: 10_000, + settlementFinalizedAt: null, + settlementId: null, + }); + const finalizedAt = new Date('2026-11-12T05:00:00.000Z'); + const settlement = await createSettlement(prisma, { store_id: storeId }); + await prisma.order.update({ + where: { id: order.id }, + data: { + commission_rate_bps: 500, + settlement_base_amount: 10_000, + commission_amount: 500, + settlement_finalized_at: finalizedAt, + settlement_id: settlement.id, + }, + }); + + expect(await service.adminOrder(await admin(), order.id)).toMatchObject({ + commissionRateBps: 500, + expectedPayoutAmount: 9_500, + settlementBaseAmount: 10_000, + commissionAmount: 500, + settlementFinalizedAt: finalizedAt, + settlementId: settlement.id.toString(), + }); + }); + + 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.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 () => { @@ -258,40 +689,70 @@ 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' }, }); - expect(history.from_status).toBe(status); - expect(history.note).toBe('[관리자] 가게 사정'); + expect(history).toMatchObject({ + from_status: status, + actor_type: 'ADMIN', + actor_account_id: actor, + 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 }, }); @@ -303,16 +764,43 @@ describe('AdminOrderService (real DB)', () => { }, ); - it.each(['PICKED_UP', 'CANCELED'] 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 }, @@ -321,40 +809,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이고 이력은 실제 전이 순서만 남는다. @@ -363,11 +912,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, @@ -381,6 +930,7 @@ describe('AdminOrderService (real DB)', () => { }), ]); + expect(cancelResult.status).toBe('fulfilled'); const row = await prisma.order.findUniqueOrThrow({ where: { id: order.id }, }); @@ -401,14 +951,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', @@ -433,21 +977,279 @@ describe('AdminOrderService (real DB)', () => { }); }); + describe('adminCompleteOrderPickup', () => { + const NOW = new Date('2026-11-19T03:00:00.000Z'); + + beforeEach(() => { + jest.spyOn(clock, 'now').mockReturnValue(NOW); + }); + + function pickupInput( + orderId: bigint, + note?: string | null, + ): AdminCompleteOrderPickupInput { + return { orderId: orderId.toString(), note }; + } + + it.each(['CONFIRMED', 'MADE'] as const)( + '%s 주문을 픽업 완료하고 픽업 시각·정산 확정·이력(주체 ADMIN·메모)·픽업 완료 알림·감사·판매자 구독을 남긴다', + async (status) => { + const actor = await admin(); + const { order, buyer, storeId } = await orderWithItem({ + status, + paid: true, + }); + await prisma.order.update({ + where: { id: order.id }, + data: { commission_rate_bps: 333 }, + }); + const topic = await collectTopic(pubSub, `order.seller.${storeId}`); + + const result = await service.adminCompleteOrderPickup( + actor, + pickupInput(order.id, ' 매장 인도 확인 '), + ); + + expect(result).toMatchObject({ + id: order.id.toString(), + status: 'PICKED_UP', + storeId: storeId.toString(), + }); + 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, + }); + await expect( + prisma.orderStatusHistory.findMany({ where: { order_id: order.id } }), + ).resolves.toEqual([ + expect.objectContaining({ + from_status: status, + to_status: 'PICKED_UP', + changed_at: NOW, + actor_type: 'ADMIN', + actor_account_id: actor, + note: '매장 인도 확인', + }), + ]); + await expect( + prisma.auditLog.findMany({ + where: { target_type: 'ORDER', target_id: order.id }, + }), + ).resolves.toEqual([ + expect.objectContaining({ + actor_account_id: actor, + store_id: storeId, + action: 'STATUS_CHANGE', + before_json: { status }, + after_json: { + status: 'PICKED_UP', + actorType: 'ADMIN', + note: '매장 인도 확인', + }, + }), + ]); + await drainOutbox(dispatcher); + await expect( + prisma.notification.findMany({ where: { order_id: order.id } }), + ).resolves.toEqual([ + expect.objectContaining({ + account_id: buyer.id, + event: 'ORDER_PICKED_UP', + body: `${order.order_number} 케이크 픽업이 완료되었어요.`, + }), + ]); + expect(topic.received).toEqual([ + expect.objectContaining({ + kind: 'STATUS_CHANGED', + orderId: order.id.toString(), + status: 'PICKED_UP', + }), + ]); + topic.stop(); + }, + ); + + it('숨긴 매장의 주문도 픽업 시각 전에 처리한다(자동 픽업 완료가 건너뛰는 주문)', async () => { + const hidden = await createStore(prisma, { is_active: false }); + const { order } = await orderWithItem({ + status: 'MADE', + storeId: hidden.id, + paid: true, + }); + await prisma.order.update({ + where: { id: order.id }, + data: { pickup_at: new Date(NOW.getTime() + 3 * 60 * 60_000) }, + }); + + const result = await service.adminCompleteOrderPickup( + await admin(), + pickupInput(order.id), + ); + + expect(result.status).toBe('PICKED_UP'); + await expect( + prisma.order.findUniqueOrThrow({ where: { id: order.id } }), + ).resolves.toMatchObject({ + picked_up_at: NOW, + settlement_finalized_at: NOW, + }); + }); + + it('확인된 결제가 없는 주문(결제 도입 전)은 픽업 완료만 하고 정산은 건너뛴다', async () => { + const { order } = await orderWithItem({ status: 'CONFIRMED' }); + + await service.adminCompleteOrderPickup( + await admin(), + pickupInput(order.id), + ); + + await expect( + prisma.order.findUniqueOrThrow({ where: { id: order.id } }), + ).resolves.toMatchObject({ + status: 'PICKED_UP', + picked_up_at: NOW, + settlement_base_amount: null, + settlement_finalized_at: null, + }); + }); + + it.each([ + ['PENDING_PAYMENT', 'INVALID_ORDER_STATUS_TRANSITION'], + ['SUBMITTED', 'INVALID_ORDER_STATUS_TRANSITION'], + ['NO_SHOW', 'INVALID_ORDER_STATUS_TRANSITION'], + ['CANCELED', 'INVALID_ORDER_STATUS_TRANSITION'], + ['PICKED_UP', 'ORDER_STATUS_UNCHANGED'], + ] as const)( + '%s 주문은 %s로 거절하고 아무것도 바꾸지 않는다', + async (status, code) => { + const { order, storeId } = await orderWithItem({ status, paid: true }); + const topic = await collectTopic(pubSub, `order.seller.${storeId}`); + + await expect( + service.adminCompleteOrderPickup( + await admin(), + pickupInput(order.id), + ), + ).rejects.toThrowDomain(code); + + await expect( + prisma.order.findUniqueOrThrow({ where: { id: order.id } }), + ).resolves.toMatchObject({ + status, + picked_up_at: null, + settlement_finalized_at: null, + }); + expect(await prisma.orderStatusHistory.count()).toBe(0); + expect(await prisma.outbox.count()).toBe(0); + expect(await prisma.auditLog.count()).toBe(0); + expect(topic.received).toHaveLength(0); + topic.stop(); + }, + ); + + it('메모는 선택(공백은 null)이고 500자를 넘으면 TEXT_TOO_LONG, 없거나 삭제된 주문은 404', async () => { + const { order } = await orderWithItem({ status: 'CONFIRMED' }); + const other = await orderWithItem({ status: 'MADE' }); + await expect( + service.adminCompleteOrderPickup( + await admin(), + pickupInput(order.id, 'x'.repeat(501)), + ), + ).rejects.toThrowDomain('TEXT_TOO_LONG'); + + await service.adminCompleteOrderPickup( + await admin(), + pickupInput(order.id, 'x'.repeat(500)), + ); + await service.adminCompleteOrderPickup( + await admin(), + pickupInput(other.order.id, ' '), + ); + const histories = await prisma.orderStatusHistory.findMany({ + orderBy: { id: 'asc' }, + }); + expect(histories.map((h) => h.note)).toEqual(['x'.repeat(500), null]); + + const deleted = await createOrder(prisma, { + status: 'CONFIRMED', + deleted_at: new Date(), + }); + for (const orderId of [deleted.id, 999_999n]) { + await expect( + service.adminCompleteOrderPickup(await admin(), pickupInput(orderId)), + ).rejects.toThrowDomain(404); + } + }); + + it('관리자가 아니면 403', async () => { + const { order } = await orderWithItem({ status: 'CONFIRMED' }); + const user = await createAccount(prisma, { account_type: 'USER' }); + await expect( + service.adminCompleteOrderPickup(user.id, pickupInput(order.id)), + ).rejects.toThrowDomain(403); + }); + + it('두 관리자가 동시에 처리해도 전이·감사·알림·구독은 1건씩이고 늦은 쪽은 잠금 뒤 상태로 ORDER_STATUS_UNCHANGED', async () => { + const { order, storeId } = await orderWithItem({ + status: 'MADE', + paid: true, + }); + const topic = await collectTopic(pubSub, `order.seller.${storeId}`); + const [a, b] = [await admin(), await admin()]; + + const results = await Promise.allSettled([ + service.adminCompleteOrderPickup(a, pickupInput(order.id, 'a')), + service.adminCompleteOrderPickup(b, pickupInput(order.id, 'b')), + ]); + + expect(results.map((r) => r.status).sort()).toEqual([ + 'fulfilled', + 'rejected', + ]); + const rejected = results.find((r) => r.status === 'rejected'); + expect((rejected as PromiseRejectedResult).reason).toThrowDomain( + 'ORDER_STATUS_UNCHANGED', + ); + expect( + await prisma.orderStatusHistory.count({ + where: { order_id: order.id }, + }), + ).toBe(1); + expect( + await prisma.auditLog.count({ + where: { target_type: 'ORDER', target_id: order.id }, + }), + ).toBe(1); + await drainOutbox(dispatcher); + expect( + await prisma.notification.count({ where: { order_id: order.id } }), + ).toBe(1); + expect(topic.received).toHaveLength(1); + topic.stop(); + }); + }); + describe('sellerOrderUpdated 발행', () => { it('관리자 취소는 첫 품목 매장 토픽에 1건 — 취소된 주문 행의 스냅샷을 싣는다', async () => { 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 }, }); expect(topic.received).toEqual([ { + kind: 'STATUS_CHANGED', orderId: order.id.toString(), orderNumber: order.order_number, status: 'CANCELED', @@ -455,6 +1257,7 @@ describe('AdminOrderService (real DB)', () => { buyerName: order.buyer_name, totalPrice: order.total_price, productName: 'Product snapshot', + hasCustom: false, updatedAt: row.updated_at.toISOString(), }, ]); @@ -466,16 +1269,28 @@ 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); 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(), + cancelInput(order.id), + ); + + 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({ @@ -484,10 +1299,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 e2e9434d..87604717 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,33 +10,37 @@ 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 { AdminCompleteOrderPickupInput } from '@/features/order/dto/inputs/admin-complete-order-pickup.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, OrderStatus } from '@/generated/prisma/client'; -/** 전이 규칙은 판매자와 같은 OrderStatusTransitionPolicy가 단일 소스이고, 저장·이력·알림·감사는 order feature의 repository가 한 트랜잭션에서 처리한다. */ +/** 취소 규칙은 OrderCancelPolicy가 단일 소스이고, 저장·이력·환불·알림·감사는 OrderTransitionRepository가 한 트랜잭션에서 처리한다. */ @Injectable() export class AdminOrderService extends AdminBaseService { constructor( @@ -43,7 +49,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); } @@ -60,6 +69,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), @@ -86,7 +96,36 @@ 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건). */ + 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( @@ -94,56 +133,55 @@ 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; - } - }, + 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 === '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'); - } + if (!updated) throw new DomainException('ORDER_NOT_FOUND'); + await this.events.publishSellerStatusChanged(updated); + return toAdminOrderSummaryOutput(updated); + } - // 활성 품목이 없으면 매장을 알 수 없어 발행을 생략한다 - const [firstItem] = updated.items; - if (firstItem) { - await this.events.publishSellerOrderUpdate( - firstItem.store_id, - toSellerOrderUpdateEvent(updated, firstItem.product_name_snapshot), - ); - } + /** + * 확정·제작 완료 주문을 픽업 완료로 바꾸고 정산을 확정한다. 숨긴 매장 주문처럼 자동 픽업 완료가 건너뛰는 주문을 + * 관리자가 건별로 닫는 경로라 매장 숨김은 보지 않는다. 판정은 잠금 읽기 결과로 한다. + */ + async adminCompleteOrderPickup( + accountId: bigint, + input: AdminCompleteOrderPickupInput, + ): Promise { + const ctx = await this.requireAdminContext(accountId); + const now = this.clock.now(); + const updated = await this.transitions.completePickupByAdmin({ + orderId: parseId(input.orderId), + actorAccountId: ctx.accountId, + note: cleanNullableText(input.note, MAX_REASON_LENGTH), + now, + assertTransition: (state) => + this.statusPolicy.assertTransition({ + actor: OrderActor.ADMIN, + from: state.status, + to: OrderStatus.PICKED_UP, + now, + pickupAt: state.pickupAt, + }), + }); + if (!updated) throw new DomainException('ORDER_NOT_FOUND'); + await this.events.publishSellerStatusChanged(updated); return toAdminOrderSummaryOutput(updated); } } 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-checkout.service.custom.spec.ts b/src/features/order/services/order-checkout.service.custom.spec.ts new file mode 100644 index 00000000..3f4cdf58 --- /dev/null +++ b/src/features/order/services/order-checkout.service.custom.spec.ts @@ -0,0 +1,632 @@ +import { ClockService } from '@/common/providers/clock.service'; +import { RandomService } from '@/common/providers/random.service'; +import { AUDIT_LOG_REPOSITORY } from '@/features/audit-log'; +import { AuditLogRepository } from '@/features/audit-log/repositories/audit-log.repository'; +import type { + CreateOrderCustomInput, + CreateOrderSlotCustomInput, + CreateOrderThreeDCustomInput, +} from '@/features/order/dto/inputs/create-order-custom.input'; +import type { CreateOrderInput } from '@/features/order/dto/inputs/create-order.input'; +import { OrderCustomUploadRepository } from '@/features/order/repositories/order-custom-upload.repository'; +import { OrderRepository } from '@/features/order/repositories/order.repository'; +import { PaymentSettingRepository } from '@/features/order/repositories/payment-setting.repository'; +import { OrderCheckoutService } from '@/features/order/services/order-checkout.service'; +import { OrderCustomizationService } from '@/features/order/services/order-customization.service'; +import { OutboxPublisher } from '@/features/outbox/services/outbox-publisher.service'; +import { ProductRepository } from '@/features/product'; +import { StorePickupScheduleService } from '@/features/store'; +import { StoreRepository } from '@/features/store/repositories/store.repository'; +import type { + Account, + CustomImageKind, + OrderCustomUploadPurpose, + PrismaClient, + Product, +} from '@/generated/prisma/client'; +import { UPLOAD_POLICIES } from '@/global/storage/constants/storage.constants'; +import { bookedQuantityProviders } from '@/test/booked-quantity'; +import { disconnectTestPrismaClient } from '@/test/db/prisma-test-client'; +import { closeTruncateConnection, truncateAll } from '@/test/db/truncate'; +import { + createAccount, + createCustomTemplate, + createCustomTextToken, + createOrderCustomUpload, + createPaymentSetting, + createProduct, + createStore, + createUserProfile, +} from '@/test/factories'; +import { createTestingModuleWithRealDb } from '@/test/modules/testing-module.builder'; +import { outboxPublisherProviders } from '@/test/outbox'; +import { s3TestProviders, TEST_S3_CONFIG } from '@/test/storage/s3-test.helper'; + +// 2026-09-16(수) 16:00 KST 고정 +const NOW = new Date('2026-09-16T07:00:00.000Z'); +/** 2026-09-18(금) 14:00 KST */ +const PICKUP_AT = new Date('2026-09-18T05:00:00.000Z'); + +const PURPOSE_POLICY = { + RENDER: UPLOAD_POLICIES.ORDER_CUSTOM_RENDER, + COMPOSITE: UPLOAD_POLICIES.ORDER_CUSTOM_COMPOSITE, + REFERENCE: UPLOAD_POLICIES.ORDER_CUSTOM_REFERENCE, +} as const; +const RENDER_KINDS = [ + 'THREE_D_TOP', + 'THREE_D_FRONT', + 'THREE_D_BACK', + 'THREE_D_LEFT', + 'THREE_D_RIGHT', +] as const satisfies readonly CustomImageKind[]; + +describe('OrderCheckoutService 커스텀 주문 (real DB)', () => { + let service: OrderCheckoutService; + let orderRepo: OrderRepository; + let uploads: OrderCustomUploadRepository; + let outbox: OutboxPublisher; + let clock: ClockService; + let prisma: PrismaClient; + + beforeAll(async () => { + const { module, prisma: p } = await createTestingModuleWithRealDb({ + providers: [ + OrderCheckoutService, + OrderCustomizationService, + OrderRepository, + OrderCustomUploadRepository, + ...s3TestProviders(), + PaymentSettingRepository, + ProductRepository, + { provide: AUDIT_LOG_REPOSITORY, useClass: AuditLogRepository }, + StorePickupScheduleService, + StoreRepository, + ClockService, + RandomService, + ...outboxPublisherProviders({ clock: true }), + ...bookedQuantityProviders(), + ], + }); + service = module.get(OrderCheckoutService); + orderRepo = module.get(OrderRepository); + uploads = module.get(OrderCustomUploadRepository); + outbox = module.get(OutboxPublisher); + clock = module.get(ClockService); + prisma = p; + }); + + afterAll(async () => { + await closeTruncateConnection(); + await disconnectTestPrismaClient(); + }); + + beforeEach(async () => { + await truncateAll(); + await createPaymentSetting(prisma); + jest.spyOn(clock, 'now').mockReturnValue(NOW); + }); + + afterEach(() => { + jest.restoreAllMocks(); + }); + + async function makeOpenStoreId(): Promise { + const store = await createStore(prisma, { + pickup_slot_interval_minutes: 30, + min_lead_time_minutes: 60, + }); + for (let dayOfWeek = 0; dayOfWeek < 7; dayOfWeek += 1) { + await prisma.storeBusinessHour.create({ + data: { + store_id: store.id, + day_of_week: dayOfWeek, + is_closed: false, + open_time: new Date(Date.UTC(1970, 0, 1, 10)), + close_time: new Date(Date.UTC(1970, 0, 1, 20)), + }, + }); + } + return store.id; + } + + async function makeBuyer(): Promise { + const account = await createAccount(prisma, { account_type: 'USER' }); + await createUserProfile(prisma, { + account_id: account.id, + phone_number: '010-1234-5678', + }); + return account; + } + + /** 발급 기록이 있는 본인 업로드의 공개 URL. */ + async function upload( + buyer: Account, + purpose: OrderCustomUploadPurpose, + name: string, + row: Parameters[1] = {}, + ): Promise { + const key = `${PURPOSE_POLICY[purpose].keyPrefix}/${buyer.id}/2026-09-16/${name}`; + await createOrderCustomUpload(prisma, { + account_id: buyer.id, + purpose, + object_key: key, + ...row, + }); + return `https://${TEST_S3_CONFIG.bucket}.s3.${TEST_S3_CONFIG.region}.amazonaws.com/${key}`; + } + + async function uploadStatuses() { + const rows = await prisma.orderCustomUpload.findMany({ + orderBy: { object_key: 'asc' }, + }); + return rows.map((row) => [row.object_key.split('/').pop(), row.status]); + } + + let idemSeq = 0; + function input( + product: Product, + expectedTotalPrice: number, + custom: CreateOrderCustomInput, + overrides: Partial = {}, + ): CreateOrderInput { + idemSeq += 1; + return { + idempotencyKey: `custom-idem-${idemSeq}`, + productId: product.id.toString(), + optionItemIds: [], + pickupAt: PICKUP_AT, + expectedTotalPrice, + custom, + ...overrides, + }; + } + + describe('슬롯형', () => { + /** 정가 30000·판매가 25000, 필수 자리(이름)·선택 자리(문구), 자유 편집 켜짐. */ + async function setup() { + const buyer = await makeBuyer(); + const product = await createProduct(prisma, { + store_id: await makeOpenStoreId(), + regular_price: 30000, + sale_price: 25000, + }); + await prisma.product.update({ + where: { id: product.id }, + data: { custom_mode: 'SLOT' }, + }); + const template = await createCustomTemplate(prisma, { + product_id: product.id, + base_image_url: 'https://i.example/base-square.png', + free_edit_enabled: true, + revision: 4, + }); + const name = await createCustomTextToken(prisma, { + template_id: template.id, + token_key: 'name', + label: '이름', + default_text: '민지', + max_length: 10, + sort_order: 0, + pos_x: 1000, + pos_y: 1000, + width: 8000, + height: 1000, + text_color: '#FF8800', + text_align: 'LEFT', + }); + const phrase = await createCustomTextToken(prisma, { + template_id: template.id, + token_key: 'phrase', + label: '문구', + default_text: '축하해', + is_required: false, + sort_order: 1, + }); + const composite = await upload(buyer, 'COMPOSITE', 'composite.png'); + const reference = await upload(buyer, 'REFERENCE', 'ref.png'); + const slot: CreateOrderSlotCustomInput = { + templateRevision: 4, + texts: [ + { tokenId: phrase.id.toString(), valueText: null }, + { tokenId: name.id.toString(), valueText: '지수\r\n🎂' }, + ], + compositeImageUrl: composite, + freeEdits: [ + { + posX: 0, + posY: 5000, + width: 10000, + height: 5000, + descriptionText: ' 아래쪽에 꽃 ', + referenceImageUrls: [reference], + }, + ], + }; + return { buyer, product, name, phrase, composite, reference, slot }; + } + + it('문구 자리·자유 편집·합성 이미지를 스냅샷하고 업로드를 ATTACHED로 바꾼다(추가 금액 없음)', async () => { + const { buyer, product, name, phrase, composite, reference, slot } = + await setup(); + + const created = await service.createOrder( + buyer.id, + input(product, 25000, { slot }), + ); + + expect(created.totalPrice).toBe(25000); + const item = await prisma.orderItem.findFirstOrThrow({ + where: { order_id: BigInt(created.orderId) }, + include: { + custom_texts: { orderBy: { sort_order: 'asc' } }, + free_edits: { include: { attachments: true } }, + custom_images: true, + custom_design: true, + }, + }); + expect(item).toMatchObject({ + quantity: 1, + item_subtotal_price: 25000, + custom_mode_snapshot: 'SLOT', + custom_base_image_url_snapshot: 'https://i.example/base-square.png', + custom_preview_image_url: composite, + custom_design: null, + custom_images: [{ kind: 'SLOT_COMPOSITE', image_url: composite }], + }); + expect(item.custom_texts).toMatchObject([ + { + token_id: name.id, + token_key_snapshot: 'name', + label_snapshot: '이름', + default_text_snapshot: '민지', + value_text: '지수\n🎂', + sort_order: 0, + pos_x: 1000, + pos_y: 1000, + width: 8000, + height: 1000, + text_color: '#FF8800', + text_align: 'LEFT', + }, + { + token_id: phrase.id, + label_snapshot: '문구', + default_text_snapshot: '축하해', + value_text: null, + }, + ]); + expect(item.free_edits).toMatchObject([ + { + pos_x: 0, + pos_y: 5000, + width: 10000, + height: 5000, + description_text: '아래쪽에 꽃', + sort_order: 0, + attachments: [{ image_url: reference, sort_order: 0 }], + }, + ]); + expect(await uploadStatuses()).toEqual([ + ['composite.png', 'ATTACHED'], + ['ref.png', 'ATTACHED'], + ]); + const attached = await prisma.orderCustomUpload.findFirstOrThrow(); + expect(attached.attached_at).toEqual(NOW); + }); + + it('한 번 주문에 쓴 이미지는 다른 주문에 쓸 수 없다', async () => { + const { buyer, product, slot } = await setup(); + await service.createOrder(buyer.id, input(product, 25000, { slot })); + + await expect( + service.createOrder(buyer.id, input(product, 25000, { slot })), + ).rejects.toThrowDomain('CUSTOM_UPLOAD_INVALID'); + expect(await prisma.order.count()).toBe(1); + }); + + it.each<[string, Parameters[1], string]>([ + [ + '다른 주문에 붙은 업로드', + { status: 'ATTACHED' }, + 'CUSTOM_UPLOAD_INVALID', + ], + [ + '정리 중인 업로드', + { status: 'PURGING', purge_started_at: NOW }, + 'CUSTOM_UPLOAD_EXPIRED', + ], + [ + '기록의 용도가 다른 업로드', + { purpose: 'RENDER' }, + 'CUSTOM_UPLOAD_INVALID', + ], + ])('%s는 거절하고 주문·연결을 남기지 않는다', async (_case, row, code) => { + const { buyer, product, slot } = await setup(); + slot.freeEdits![0].referenceImageUrls = [ + await upload(buyer, 'REFERENCE', 'bad.png', row), + ]; + + await expect( + service.createOrder(buyer.id, input(product, 25000, { slot })), + ).rejects.toThrowDomain(code); + expect(await prisma.order.count()).toBe(0); + expect( + await prisma.orderCustomUpload.count({ + where: { status: 'ATTACHED', attached_at: NOW }, + }), + ).toBe(0); + }); + + it('발급 기록이 없는 본인 경로 URL·다른 계정 기록·대소문자만 같은 키면 CUSTOM_UPLOAD_INVALID다', async () => { + const { buyer, product, slot } = await setup(); + const other = await createAccount(prisma, { account_type: 'USER' }); + const unissued = `https://${TEST_S3_CONFIG.bucket}.s3.${TEST_S3_CONFIG.region}.amazonaws.com/order-custom/references/${buyer.id}/2026-09-16/none.png`; + const othersRow = await upload(buyer, 'REFERENCE', 'other.png', { + account_id: other.id, + }); + // 키 컬럼 콜레이션은 대소문자를 가리지 않는다 — 다른 키로 같은 행을 붙이지 못해야 한다 + const caseVariant = ( + await upload(buyer, 'REFERENCE', 'case.png') + ).replace('case.png', 'CASE.png'); + + for (const url of [unissued, othersRow, caseVariant]) { + slot.freeEdits![0].referenceImageUrls = [url]; + await expect( + service.createOrder(buyer.id, input(product, 25000, { slot })), + ).rejects.toThrowDomain('CUSTOM_UPLOAD_INVALID'); + } + expect(await prisma.order.count()).toBe(0); + }); + + it('주문 tx가 연결 뒤에 실패하면 업로드는 PENDING으로 남는다', async () => { + const { buyer, product, slot } = await setup(); + jest + .spyOn(outbox, 'publish') + .mockRejectedValueOnce(new Error('outbox down')); + + await expect( + service.createOrder(buyer.id, input(product, 25000, { slot })), + ).rejects.toThrow('outbox down'); + + expect(await prisma.order.count()).toBe(0); + expect(await prisma.orderItemCustomText.count()).toBe(0); + expect(await uploadStatuses()).toEqual([ + ['composite.png', 'PENDING'], + ['ref.png', 'PENDING'], + ]); + // 같은 업로드로 다시 주문할 수 있다 + await expect( + service.createOrder(buyer.id, input(product, 25000, { slot })), + ).resolves.toMatchObject({ status: 'PENDING_PAYMENT' }); + }); + + it('주문 tx가 업로드를 잠근 동안 돈 정리 크론은 그 업로드를 잡지 못하고, 주문이 ATTACHED로 붙인다', async () => { + const { buyer, product, slot } = await setup(); + // 잠금 검사와 ATTACHED 표시 사이에 크론이 끼어드는 경우를 재현한다(크론은 별도 커넥션) + const repo = orderRepo as unknown as { + insertPendingPaymentOrder: (...args: unknown[]) => Promise; + }; + const insert = repo.insertPendingPaymentOrder.bind(orderRepo); + let claimed: unknown[] | undefined; + jest + .spyOn(repo, 'insertPendingPaymentOrder') + .mockImplementation(async (...args) => { + claimed = await uploads.claimForPurge({ + now: NOW, + pendingCreatedBefore: new Date('2100-01-01T00:00:00.000Z'), + purgingStartedBefore: NOW, + limit: 10, + }); + return insert(...args); + }); + + await service.createOrder(buyer.id, input(product, 25000, { slot })); + + expect(claimed).toEqual([]); + expect(await uploadStatuses()).toEqual([ + ['composite.png', 'ATTACHED'], + ['ref.png', 'ATTACHED'], + ]); + }); + + it('같은 키·같은 커스텀 입력의 재요청은 기존 주문을 돌려주고, 커스텀만 달라도 IDEMPOTENCY_KEY_INPUT_MISMATCH다', async () => { + const { buyer, product, slot } = await setup(); + const first = input(product, 25000, { slot }); + const created = await service.createOrder(buyer.id, first); + + await expect( + service.createOrder(buyer.id, { + ...first, + custom: { slot: { ...slot, texts: [...slot.texts].reverse() } }, + }), + ).resolves.toEqual(created); + await expect( + service.createOrder(buyer.id, { + ...first, + custom: { + slot: { + ...slot, + texts: [slot.texts[0], { ...slot.texts[1], valueText: '지수' }], + }, + }, + }), + ).rejects.toThrowDomain('IDEMPOTENCY_KEY_INPUT_MISMATCH'); + expect(await prisma.order.count()).toBe(1); + }); + + it('같은 키 재시도가 사전 조회를 지나 업로드 잠금에서 걸리면 내 주문을 replay한다', async () => { + const { buyer, product, slot } = await setup(); + const first = input(product, 25000, { slot }); + const created = await service.createOrder(buyer.id, first); + + const raceOnce = () => + jest + .spyOn(orderRepo, 'findOrderByIdempotencyKey') + .mockResolvedValueOnce(null); + raceOnce(); + await expect(service.createOrder(buyer.id, first)).resolves.toEqual( + created, + ); + raceOnce(); + await expect( + service.createOrder(buyer.id, { ...first, requestNote: '다른 메모' }), + ).rejects.toThrowDomain('IDEMPOTENCY_KEY_INPUT_MISMATCH'); + expect(await prisma.order.count()).toBe(1); + }); + + it('판매자가 설정을 바꿨으면(revision) 주문을 만들지 않고 업로드도 그대로 둔다', async () => { + const { buyer, product, slot } = await setup(); + await prisma.productCustomTemplate.update({ + where: { product_id: product.id }, + data: { revision: 5 }, + }); + + await expect( + service.createOrder(buyer.id, input(product, 25000, { slot })), + ).rejects.toThrowDomain('CUSTOM_TEMPLATE_CHANGED'); + expect(await prisma.order.count()).toBe(0); + expect(await uploadStatuses()).toEqual([ + ['composite.png', 'PENDING'], + ['ref.png', 'PENDING'], + ]); + }); + }); + + describe('3D', () => { + /** 정가 20000, 모양(하트 +1000)·크기(1호 +5000) 필수 그룹. */ + async function setup() { + const buyer = await makeBuyer(); + const product = await createProduct(prisma, { + store_id: await makeOpenStoreId(), + regular_price: 20000, + }); + await prisma.product.update({ + where: { id: product.id }, + data: { custom_mode: 'THREE_D' }, + }); + const items: bigint[] = []; + for (const [name, key, delta] of [ + ['모양', 'shape.heart', 1000], + ['크기', 'size.no1', 5000], + ] as const) { + const group = await prisma.productOptionGroup.create({ + data: { product_id: product.id, name, min_select: 1, max_select: 1 }, + }); + const item = await prisma.productOptionItem.create({ + data: { + option_group_id: group.id, + title: name, + price_delta: delta, + three_d_key: key, + }, + }); + items.push(item.id); + } + const renders: { kind: CustomImageKind; imageUrl: string }[] = []; + for (const kind of RENDER_KINDS) { + renders.push({ + kind, + imageUrl: await upload(buyer, 'RENDER', `${kind}.png`), + }); + } + const threeD: CreateOrderThreeDCustomInput = { + design: { + schemaVersion: 1, + basic: { shape: 'heart', size: 'no1', sheetColor: 'white' }, + top: [ + { + kind: 'TEXT', + x: 0.5, + y: 0.5, + size: 10, + effect: { type: 'none', intensity: 50 }, + text: '축하해', + color: '#ff0000', + }, + ], + side: [], + }, + renderImages: renders, + }; + return { + buyer, + product, + optionItemIds: items.map(String), + renders, + threeD, + }; + } + + it('디자인 JSON v1과 렌더 5장을 저장하고 윗면을 대표 이미지로 둔다(가격은 옵션 추가금만)', async () => { + const { buyer, product, optionItemIds, renders, threeD } = await setup(); + + const created = await service.createOrder( + buyer.id, + input(product, 26000, { threeD }, { optionItemIds }), + ); + + expect(created.totalPrice).toBe(26000); + const item = await prisma.orderItem.findFirstOrThrow({ + where: { order_id: BigInt(created.orderId) }, + include: { + custom_design: true, + custom_images: { orderBy: { kind: 'asc' } }, + custom_texts: true, + free_edits: true, + }, + }); + expect(item).toMatchObject({ + custom_mode_snapshot: 'THREE_D', + custom_base_image_url_snapshot: null, + custom_preview_image_url: renders[0].imageUrl, + custom_texts: [], + free_edits: [], + custom_design: { + schema_version: 1, + design_json: { + schemaVersion: 1, + basic: { + shape: 'heart', + size: 'no1', + design: null, + flavor: null, + sheetColor: 'white', + }, + top: [{ kind: 'TEXT', text: '축하해', color: '#FF0000' }], + side: [], + }, + }, + }); + expect( + item.custom_images.map((image) => [image.kind, image.image_url]), + ).toEqual(renders.map((r) => [r.kind, r.imageUrl])); + expect( + await prisma.orderCustomUpload.count({ where: { status: 'ATTACHED' } }), + ).toBe(5); + }); + + it('고른 옵션과 디자인이 다르면 CUSTOM_3D_OPTIONS_CHANGED다', async () => { + const { buyer, product, optionItemIds, threeD } = await setup(); + threeD.design.basic.size = 'mini'; + + await expect( + service.createOrder( + buyer.id, + input(product, 26000, { threeD }, { optionItemIds }), + ), + ).rejects.toThrowDomain('CUSTOM_3D_OPTIONS_CHANGED'); + expect(await prisma.order.count()).toBe(0); + }); + + it('3D 상품을 커스텀 없이 주문하면 CUSTOM_INPUT_REQUIRED다', async () => { + const { buyer, product, optionItemIds } = await setup(); + + await expect( + service.createOrder(buyer.id, { + ...input(product, 26000, {}, { optionItemIds }), + custom: undefined, + }), + ).rejects.toThrowDomain('CUSTOM_INPUT_REQUIRED'); + }); + }); +}); diff --git a/src/features/order/services/order-checkout.service.spec.ts b/src/features/order/services/order-checkout.service.spec.ts index 7fd3612c..85cd9a87 100644 --- a/src/features/order/services/order-checkout.service.spec.ts +++ b/src/features/order/services/order-checkout.service.spec.ts @@ -6,11 +6,16 @@ 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'; + ORDER_PAYMENT_PENDING, + 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'; 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'; @@ -29,6 +34,7 @@ import { createAccount, createOrder as createOrderRow, createOrderItem, + createPaymentSetting, createProduct, createRegion, createStore, @@ -38,6 +44,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'); @@ -47,6 +58,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; @@ -56,15 +68,19 @@ describe('OrderCheckoutService (real DB)', () => { const { module, prisma: p } = await createTestingModuleWithRealDb({ providers: [ OrderCheckoutService, + OrderCustomizationService, OrderRepository, + OrderCustomUploadRepository, + ...s3TestProviders(), + 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 }), @@ -73,6 +89,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); @@ -86,6 +103,8 @@ describe('OrderCheckoutService (real DB)', () => { beforeEach(async () => { await truncateAll(); + // truncateAll이 마이그레이션이 넣은 결제 설정 행까지 지운다 + await createPaymentSetting(prisma); jest.spyOn(clock, 'now').mockReturnValue(NOW); }); @@ -182,7 +201,8 @@ describe('OrderCheckoutService (real DB)', () => { } // 호출마다 새 키 — 한 케이스에서 createOrder를 여러 번 부를 때 의도치 않은 - // 멱등 replay로 두 번째 생성이 생략되는 것을 막는다 + // 멱등 replay로 두 번째 생성이 생략되는 것을 막는다. + // 기대 금액 기본값은 factory 기본 상품(정가 10000·판매가 없음·옵션 없음) 기준이다. let idemSeq = 0; function baseInput(overrides: Partial): CreateOrderInput { idemSeq += 1; @@ -191,10 +211,88 @@ describe('OrderCheckoutService (real DB)', () => { productId: '0', optionItemIds: [], pickupAt: VALID_PICKUP_AT, + expectedTotalPrice: 10_000 * (overrides.quantity ?? 1), ...overrides, }; } + 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(); @@ -224,12 +322,13 @@ describe('OrderCheckoutService (real DB)', () => { quantity: 2, buyerName: '차차', buyerPhone: '010-0000-1111', + expectedTotalPrice: 56000, }), ); // (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}$/); @@ -240,8 +339,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 @@ -266,7 +365,8 @@ 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', }); }); @@ -281,7 +381,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); @@ -404,42 +507,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 }); @@ -573,7 +640,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 () => { @@ -619,7 +686,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 () => { @@ -702,7 +769,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 () => { @@ -731,7 +798,7 @@ describe('OrderCheckoutService (real DB)', () => { buyer.id, baseInput({ productId: product.id.toString() }), ), - ).resolves.toMatchObject({ status: 'SUBMITTED' }); + ).resolves.toMatchObject({ status: 'PENDING_PAYMENT' }); }); it('반증: 설정 삭제가 아직 복제되지 않았으면 기존 제한이 유지된다', async () => { @@ -785,10 +852,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', }); - expect(submittedCount).toBe(1); + const createdCount = await prisma.order.count({ + where: { status: 'PENDING_PAYMENT', deleted_at: null }, + }); + expect(createdCount).toBe(1); }); it('주문번호 충돌 시 새 번호로 재시도하고, 계속 충돌하면 실패한다', async () => { @@ -832,34 +903,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 }); @@ -1014,57 +1057,292 @@ 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); }); }); - describe('createOrder — 접수 이벤트(order.submitted)', () => { - async function submittedEvents() { - return prisma.outbox.findMany({ - where: { event_type: ORDER_SUBMITTED }, - orderBy: { id: 'asc' }, - }); - } + 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); - it('생성과 같은 tx에 1건 남기고 payload는 생성 시점 스냅샷이다', async () => { + 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, sizeSmallId } = await makeProductWithOptions(store.id); + 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: 'PENDING_PAYMENT', + }); + } 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' }], + ['입금자명', { depositorName: '다른 입금자' }], + ['요청 사항', { 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(), - optionItemIds: [sizeSmallId.toString()], - quantity: 2, + quantity: 5, }), ); - const events = await submittedEvents(); + 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, 'createPendingPaymentOrder'); + 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.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_type: 'order', aggregate_id: result.orderId, occurred_at: NOW, actor_account_id: buyer.id, }); - expect(parseOrderSubmittedPayload(events[0].payload_json)).toEqual({ + expect(parseOrderPaymentPendingPayload(events[0].payload_json)).toEqual({ orderId: result.orderId, orderNumber: result.orderNumber, - buyerAccountId: buyer.id.toString(), - storeId: store.id.toString(), - storeName: store.store_name, - productId: product.id.toString(), - productName: product.name, - quantity: 2, - pickupAt: VALID_PICKUP_AT.toISOString(), - // (25000 + 2000) × 2 - totalPrice: 54000, + 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 거절은 이벤트를 남기지 않는다', async () => { + it('반증: capacity 거절과 같은 키 replay는 이벤트를 남기지 않는다', async () => { const store = await makeOpenStore(); const product = await createProduct(prisma, { store_id: store.id }); const buyer = await makeBuyer(); @@ -1073,31 +1351,18 @@ describe('OrderCheckoutService (real DB)', () => { 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); - - expect(await submittedEvents()).toHaveLength(0); - }); + ).rejects.toThrowDomain('PICKUP_NOT_AVAILABLE'); + expect(await pendingEvents()).toHaveLength(0); - 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(), }); - const first = await service.createOrder(buyer.id, input); expect(await service.createOrder(buyer.id, input)).toEqual(first); // 사전 조회 miss → tx 안 capacity 거절 → replay 경로 @@ -1106,119 +1371,379 @@ describe('OrderCheckoutService (real DB)', () => { .mockResolvedValueOnce(null); expect(await service.createOrder(buyer.id, input)).toEqual(first); - const events = await submittedEvents(); + const events = await pendingEvents(); expect(events).toHaveLength(1); expect(events[0].aggregate_id).toBe(first.orderId); }); - }); - describe('sellerOrderUpdated 발행', () => { - it('주문 생성 시 매장 토픽에 1건 — 커밋된 주문 행(updated_at)의 스냅샷을 싣는다', async () => { + it('판매자 주문 구독에는 아무것도 발행하지 않는다(입금 확인 뒤에 보인다)', 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}`); + await service.createOrder( + buyer.id, + baseInput({ productId: product.id.toString() }), + ); + + expect(await prisma.order.count()).toBe(1); + 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(), buyerName: '차차' }), + baseInput({ productId: product.id.toString() }), ); + 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, + }); const saved = await prisma.order.findUniqueOrThrow({ where: { id: BigInt(result.orderId) }, + include: { payment: true }, }); - 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(); + 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(), + }); + 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('반증: 멱등 replay(사전 조회·P2002 경합)는 발행하지 않는다', 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(); - const topic = await collectTopic(pubSub, `order.seller.${store.id}`); - const input = baseInput({ - idempotencyKey: 'replay-no-event', - productId: product.id.toString(), - }); - await service.createOrder(buyer.id, input); - await service.createOrder(buyer.id, input); - // 사전 조회를 놓친 동시 제출 — 멱등 키 unique 충돌 뒤 기존 주문을 replay한다 - jest - .spyOn(orderRepo, 'findOrderByIdempotencyKey') - .mockResolvedValueOnce(null); - await service.createOrder(buyer.id, input); + const result = await service.createOrder( + buyer.id, + baseInput({ + productId: product.id.toString(), + buyerName: '주문자', + depositorName, + }), + ); - expect(await prisma.order.count()).toBe(1); - expect(topic.received).toHaveLength(1); - topic.stop(); + expect(result.payment?.depositorName).toBe(expected); }); - it('반증: capacity 거절·tx 안 capacity replay는 발행하지 않는다', async () => { + 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(); + + await expect( + service.createOrder( + buyer.id, + baseInput({ productId: product.id.toString(), ...change }), + ), + ).rejects.toThrowDomain('DEPOSITOR_NAME_INVALID'); + expect(await prisma.order.count()).toBe(0); + }, + ); + + 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('createOrder — 계정당 입금 대기 2건', () => { + async function setup() { 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(), + return { store, product, buyer }; + } + + 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() }), + ); + expect(second.status).toBe('PENDING_PAYMENT'); - await service.createOrder(buyer.id, input); await expect( service.createOrder( buyer.id, baseInput({ productId: product.id.toString() }), ), - ).rejects.toThrowDomain('PICKUP_NOT_AVAILABLE'); - // 사전 조회·사전 capacity 검사를 모두 놓친 동시 재시도 — 잠금 재검사가 거절하고 내 주문을 replay한다 + ).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', + }); + 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('상한에 걸려도 같은 키 재요청은 기존 주문을 돌려준다', async () => { + const { product, buyer } = await setup(); + await pendingOrder(buyer.id); + const input = baseInput({ + idempotencyKey: 'limit-replay-key', + productId: product.id.toString(), + }); + const first = await service.createOrder(buyer.id, input); + + // 사전 조회를 놓친 재시도 — tx 안 건수 거절 뒤 내 주문을 찾아 replay한다 jest .spyOn(orderRepo, 'findOrderByIdempotencyKey') .mockResolvedValueOnce(null); - jest - .spyOn(orderRepo, 'isDailyCapacityExceeded') - .mockResolvedValueOnce(false); - await service.createOrder(buyer.id, input); + await expect(service.createOrder(buyer.id, input)).resolves.toEqual( + first, + ); + expect(await prisma.order.count()).toBe(2); + }); - expect(await prisma.order.count()).toBe(1); - expect(topic.received).toHaveLength(1); - topic.stop(); + it('동시 2요청은 하나만 받는다(입금 대기 1건에서 시작)', async () => { + const { product, buyer } = await setup(); + await pendingOrder(buyer.id); + + const results = await Promise.allSettled([ + service.createOrder( + buyer.id, + baseInput({ productId: product.id.toString() }), + ), + service.createOrder( + buyer.id, + baseInput({ productId: product.id.toString() }), + ), + ]); + + 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 = pendingPaymentLockName(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 7e2fac25..fed03626 100644 --- a/src/features/order/services/order-checkout.service.ts +++ b/src/features/order/services/order-checkout.service.ts @@ -1,21 +1,36 @@ 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'; 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 { CUSTOM_UPLOAD_PURPOSES } from '@/features/order/constants/order-custom-upload-purposes'; 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 { 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'; 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 } from '@/global/storage/types/storage.types'; // 0/O·1/I 등 혼동 문자를 뺀 대문자 영숫자. 주문번호 무작위부에 사용. const ORDER_NUMBER_ALPHABET = 'ABCDEFGHJKMNPQRSTUVWXYZ23456789'; @@ -27,12 +42,29 @@ 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; + +/** 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; optionItemId: bigint; groupNameSnapshot: string; optionTitleSnapshot: string; optionPriceDeltaSnapshot: number; + threeDKey: string | null; } @Injectable() @@ -43,10 +75,45 @@ export class OrderCheckoutService { private readonly pickupSchedule: StorePickupScheduleService, private readonly clock: ClockService, private readonly random: RandomService, - private readonly events: OrderEventsService, + private readonly paymentSettings: PaymentSettingRepository, + private readonly customUploads: OrderCustomUploadRepository, + private readonly s3: S3Service, + private readonly customization: OrderCustomizationService, ) {} - /** 옵션 그룹 규칙·픽업 일시를 서버가 재검증하고 가격을 스냅샷한다. 커스텀 입력은 스펙 확정 후 확장. */ + /** + * 커스텀 이미지(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; + } + + /** + * 옵션 그룹 규칙·픽업 일시를 서버가 재검증하고 가격을 스냅샷한 뒤 입금 대기 주문을 만든다. + * 판매자에게는 입금 확인 뒤에 보이므로 여기서는 판매자 구독을 발행하지 않는다. + */ async createOrder( accountId: bigint, input: CreateOrderInput, @@ -54,6 +121,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 +133,7 @@ export class OrderCheckoutService { input.idempotencyKey, ); if (replayed) { + assertReplayInputMatches(replayed, inputHash); return this.toCreateOrderOutput(replayed); } @@ -76,30 +149,37 @@ 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); 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) { // 같은 키의 동시 재시도가 방금 capacity를 채운 것일 수 있다 — 거절 전에 키를 재조회해, // 내 주문이 이미 생성돼 있으면 실패 대신 replay로 응답한다(응답 유실 재시도가 '가득 참' 실패를 받는 race 차단). - const raced = await this.replayAfterCapacityReject( + const raced = await this.replayOrReject( accountId, input.idempotencyKey, + inputHash, + 'PICKUP_NOT_AVAILABLE', ); return this.toCreateOrderOutput(raced); } @@ -125,19 +205,43 @@ export class OrderCheckoutService { throw new DomainException('ORDER_AMOUNT_OUT_OF_RANGE'); } } + // 구매자가 본 금액과 다르면 바뀐 가격으로 주문을 만들지 않는다 + if (itemSubtotalPrice !== input.expectedTotalPrice) { + throw new DomainException('ORDER_PRICE_CHANGED'); + } + + 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 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, - 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, @@ -151,25 +255,21 @@ export class OrderCheckoutService { quantity, itemSubtotalPrice, options: selections, + custom, }, }); 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, }; } @@ -198,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()); } @@ -226,14 +327,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; } @@ -270,30 +363,27 @@ 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 (typeof created === 'string') { + // 트랜잭션 안 잠금 재검사에서 거절됐다. 자리·건수를 채우거나 업로드를 붙인 것이 같은 키의 내 주문 + // (응답 유실 재시도)일 수 있어 거절 전에 replay를 확인한다. + return this.replayOrReject( args.accountId, args.idempotencyKey, + args.idempotencyInputHash, + LOCKED_REJECT_CODES[created], ); } - // 커밋된 새 주문만 발행한다 — replay(멱등 키·capacity·P2002)는 이미 발행된 주문이다 - await this.events.publishSellerOrderUpdate( - args.item.storeId, - toSellerOrderUpdateEvent(created, args.item.productNameSnapshot), - ); return created; } catch (error) { const isUniqueViolation = @@ -305,7 +395,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 = @@ -332,16 +425,19 @@ export class OrderCheckoutService { throw new DomainException('ORDER_NUMBER_GENERATION_FAILED'); } - private async replayAfterCapacityReject( + private async replayOrReject( accountId: bigint, idempotencyKey: string, - ) { + inputHash: string, + rejectCode: ErrorCode, + ): Promise { const existing = await this.orderRepo.findOrderByIdempotencyKey( accountId, idempotencyKey, ); - if (existing) return existing; - throw new DomainException('PICKUP_NOT_AVAILABLE'); + if (!existing) throw new DomainException(rejectCode); + assertReplayInputMatches(existing, inputHash); + return existing; } /** 그 외 P2002(주문번호 등)는 재시도 대상이라 구분한다. */ @@ -362,3 +458,28 @@ export class OrderCheckoutService { return `ORD-${datePart}-${randomPart}`; } } + +/** 생략·공백이면 주문자 이름. 어느 쪽이든 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 }, + 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-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-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..149f40b1 --- /dev/null +++ b/src/features/order/services/order-custom-upload-cleanup.scheduler.ts @@ -0,0 +1,91 @@ +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시간이 지난 뒤의 정리(매시 크론이라 1~2시간 뒤)에서 다시 지운다. + // 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/features/order/services/order-customization.service.spec.ts b/src/features/order/services/order-customization.service.spec.ts new file mode 100644 index 00000000..1bb0bae1 --- /dev/null +++ b/src/features/order/services/order-customization.service.spec.ts @@ -0,0 +1,813 @@ +import { Test } from '@nestjs/testing'; + +import type { + CreateOrderCustomInput, + CreateOrderFreeEditInput, + CreateOrderSlotCustomInput, + CreateOrderThreeDCustomInput, +} from '@/features/order/dto/inputs/create-order-custom.input'; +import { OrderCustomizationService } from '@/features/order/services/order-customization.service'; +import type { ProductDetailRow } from '@/features/product'; +import type { CustomImageKind, CustomMode } from '@/generated/prisma/client'; +import type { UploadPurpose } from '@/global/storage/types/storage.types'; +import { + FOREIGN_UPLOAD_URL, + ownedUploadUrl, + s3TestProviders, +} from '@/test/storage/s3-test.helper'; + +const ACCOUNT = 7n; +const BASE_IMAGE = 'https://i.example/base.png'; +const url = (purpose: UploadPurpose, name: string) => + ownedUploadUrl(purpose, ACCOUNT, name); +const keyOf = (u: string) => new URL(u).pathname.slice(1); +const COMPOSITE = url('ORDER_CUSTOM_COMPOSITE', 'composite.png'); +const RENDER_KINDS = [ + 'THREE_D_TOP', + 'THREE_D_FRONT', + 'THREE_D_BACK', + 'THREE_D_LEFT', + 'THREE_D_RIGHT', +] as const satisfies readonly CustomImageKind[]; +const renderUrl = (kind: CustomImageKind) => + url('ORDER_CUSTOM_RENDER', `${kind}.png`); + +type Template = NonNullable; +type Token = Template['text_tokens'][number]; +type OptionGroup = ProductDetailRow['option_groups'][number]; + +function token(id: bigint, overrides: Partial = {}): Token { + return { + id, + token_key: `slot${id}`, + label: `자리${id}`, + default_text: '축하해', + max_length: 20, + is_required: true, + pos_x: 1000, + pos_y: 2000, + width: 8000, + height: 1500, + text_color: '#FF0000', + text_align: 'LEFT', + sort_order: Number(id), + ...overrides, + }; +} + +function product( + mode: CustomMode, + overrides: Partial = {}, +): ProductDetailRow { + return { + id: 1n, + store_id: 1n, + name: '케이크', + description: null, + purchase_notice: null, + regular_price: 30000, + sale_price: null, + currency: 'KRW', + preparation_time_minutes: 180, + custom_mode: mode, + custom_template: { + base_image_url: BASE_IMAGE, + free_edit_enabled: true, + revision: 3, + deleted_at: null, + text_tokens: [token(11n), token(12n, { is_required: false })], + }, + store: { + store_name: '매장', + address_city: null, + address_neighborhood: null, + region: null, + }, + images: [], + option_groups: [ + group(1n, ['shape.heart', 'shape.circle']), + group(2n, ['size.mini', 'size.no1']), + group(3n, ['flavor.cream'], { is_required: false, min_select: 0 }), + ], + ...overrides, + }; +} + +function group( + id: bigint, + keys: string[], + overrides: Partial = {}, +): OptionGroup { + return { + id, + name: `그룹${id}`, + description: null, + is_active: true, + is_required: true, + min_select: 1, + max_select: 1, + sort_order: Number(id), + option_items: keys.map((key, index) => ({ + id: id * 100n + BigInt(index), + title: key, + description: null, + image_url: null, + price_delta: 0, + sort_order: index, + is_active: true, + three_d_key: key, + })), + ...overrides, + }; +} + +function template(overrides: Partial